content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class HashMismatchError(Exception):
"""Occurs when a file does not have the expected hash."""
class DataUnavailableError(Exception):
"""Data is missing from disk and isn't readily available to easily download."""
class ShouldNeverHappenError(Exception):
"""Portions of code have been reached that the dev... | class Hashmismatcherror(Exception):
"""Occurs when a file does not have the expected hash."""
class Dataunavailableerror(Exception):
"""Data is missing from disk and isn't readily available to easily download."""
class Shouldneverhappenerror(Exception):
"""Portions of code have been reached that the devel... |
l = input()
T = len(l)
if(T <= 80):
print("YES")
else:
print("NO") | l = input()
t = len(l)
if T <= 80:
print('YES')
else:
print('NO') |
#Entrada de dados.
frase = str(input('Digite uma frase: '))
#Processamento e saida de dados.
print(frase.replace(" ", ""))
| frase = str(input('Digite uma frase: '))
print(frase.replace(' ', '')) |
"""
Entradas
(X,M)-->int-->valores
Salida
Nueva experiencia Monster-->int-->E
"""
#Caja negra 1
while True:
#Entrada
X , M= input().split()
#Caja negra 2
if(X=='0' and M=='0'):
break
#Salida
print(int(X)*int(M)) | """
Entradas
(X,M)-->int-->valores
Salida
Nueva experiencia Monster-->int-->E
"""
while True:
(x, m) = input().split()
if X == '0' and M == '0':
break
print(int(X) * int(M)) |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0
for i in range(1,len(prices)):
if prices[i]>prices[i-1]:
res+=prices[i]-prices[i-1]
return res | class Solution:
def max_profit(self, prices: List[int]) -> int:
res = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
res += prices[i] - prices[i - 1]
return res |
s = 'My Name is Pankaj'
# create substring using slice
name = s[11:]
print(name)
# list of substrings using split
l1 = s.split()
print(l1)
# if present or not
if 'Name' in s:
print('Substring found')
if s.find('Name') != -1:
print('Substring found')
# substring count
print('Substring count =', s.count('a')... | s = 'My Name is Pankaj'
name = s[11:]
print(name)
l1 = s.split()
print(l1)
if 'Name' in s:
print('Substring found')
if s.find('Name') != -1:
print('Substring found')
print('Substring count =', s.count('a'))
s = 'This Is The Best Theorem'
print('Substring count =', s.count('Th'))
def find_all_indexes(input_str,... |
# This problem was recently asked by Amazon:
# The h-index is a metric that attempts to measure the productivity and citation impact of the publication of a scholar.
# The definition of the h-index is if a scholar has at least h of their papers cited h times.
def hIndex(publications):
# Fill this in.
n = len... | def h_index(publications):
n = len(publications)
eq = [0] * (n + 1)
for h in range(n):
if publications[h] >= n:
eq[n] += 1
else:
eq[publications[h]] += 1
s = 0
for h in range(n, 0, -1):
s += eq[h]
if s >= h:
return h
return 0
pr... |
#
# PySNMP MIB module CISCO-ETHERNET-ACCESS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ETHERNET-ACCESS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:40:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
class PythonListener(object):
def __init__(self, gateway):
self.gateway = gateway
def mapCollective(self, msg, harp_context):
harp_context.p(msg+1)
print(msg)
class Java:
implements = ["edu.iu.harp.boot.python.MapCollectiveReceiver"] | class Pythonlistener(object):
def __init__(self, gateway):
self.gateway = gateway
def map_collective(self, msg, harp_context):
harp_context.p(msg + 1)
print(msg)
class Java:
implements = ['edu.iu.harp.boot.python.MapCollectiveReceiver'] |
#code
def subary(l,n,k):
cur_sum=l[0]
j=0
i=1
while i<n:
cur_sum+=l[i]
i+=1
while cur_sum>k:
cur_sum-=l[j]
j+=1
if cur_sum==k:
return [j+1,i]
return -1
for _ in range(int(input())):
n,k = map(int,input().split(... | def subary(l, n, k):
cur_sum = l[0]
j = 0
i = 1
while i < n:
cur_sum += l[i]
i += 1
while cur_sum > k:
cur_sum -= l[j]
j += 1
if cur_sum == k:
return [j + 1, i]
return -1
for _ in range(int(input())):
(n, k) = map(int, input().s... |
i=0
while i<10:
child=raw_input()
child=child.split()
child=[int(u) for u in child]
sum=child[0]+child[1]
if sum>0:
print(sum)
i=i+1
if (child[0] == 0 and child[1] == 0):
break
| i = 0
while i < 10:
child = raw_input()
child = child.split()
child = [int(u) for u in child]
sum = child[0] + child[1]
if sum > 0:
print(sum)
i = i + 1
if child[0] == 0 and child[1] == 0:
break |
var = input ()
print("Hello, World." )
print (var)
| var = input()
print('Hello, World.')
print(var) |
def tileset_info(filename):
"""
Return the bounds of this tileset. The bounds should encompass the entire
width of this dataset.
So how do we know what those are if we don't know chromsizes? We can assume
that the file is enormous (e.g. has a width of 4 trillion) and rely on the
browser to pas... | def tileset_info(filename):
"""
Return the bounds of this tileset. The bounds should encompass the entire
width of this dataset.
So how do we know what those are if we don't know chromsizes? We can assume
that the file is enormous (e.g. has a width of 4 trillion) and rely on the
browser to pas... |
# The MIT License (MIT)
#
# Copyright (c) 2015 Christofer Hedbrandh
#
# 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 without restriction, including without limitation the rights
# to use, co... | __author__ = 'Christofer Hedbrandh (chedbrandh@gmail.com)'
__copyright__ = 'Copyright (c) 2015 Christofer Hedbrandh'
def get_ngrams(sequence_analyzer, bounds):
"""Returns all n-grams within some bounds.
Given a SequenceAnalyzer and some bounds, the n-grams that fulfill all
the bounds' constraints are returned... |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/900/A
xs = [list(map(int,input().split()))[0] for _ in range(int(input()))]
np = sum([x>0 for x in xs])
nn = sum([x<0 for x in xs])
print('NO' if np>1 and nn>1 else 'YES')
| xs = [list(map(int, input().split()))[0] for _ in range(int(input()))]
np = sum([x > 0 for x in xs])
nn = sum([x < 0 for x in xs])
print('NO' if np > 1 and nn > 1 else 'YES') |
def question(a, bc, s):
exa = int(a)
exb, exc = map(int, bc.split())
exs = s
return f"{exa + exb + exc} {exs}"
| def question(a, bc, s):
exa = int(a)
(exb, exc) = map(int, bc.split())
exs = s
return f'{exa + exb + exc} {exs}' |
def word_to_text_id(word):
return (word.text, int(word.id))
def filter_sent(sent, condition, postprocessor=word_to_text_id):
t = [w for w in sent.words if condition(w)]
if len(t) > 0:
return postprocessor(t[0])
else:
return None
def is_wh(word):
return word.xpos.startswith('W')
de... | def word_to_text_id(word):
return (word.text, int(word.id))
def filter_sent(sent, condition, postprocessor=word_to_text_id):
t = [w for w in sent.words if condition(w)]
if len(t) > 0:
return postprocessor(t[0])
else:
return None
def is_wh(word):
return word.xpos.startswith('W')
de... |
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not postorder or not inorder :
return None
root = TreeNode(postorder[-1])
m = inorder.index(root.val)
root.right = self.buildTree( inorder[m+1:] , postorder[m:-1] )
... | class Solution:
def build_tree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not postorder or not inorder:
return None
root = tree_node(postorder[-1])
m = inorder.index(root.val)
root.right = self.buildTree(inorder[m + 1:], postorder[m:-1])
... |
class Pedido():
def __init__(self,cliente,valor,quantidade):
self._cliente = cliente
self._valor = valor
self._quantidade = quantidade
self._valor_total = 0
def get_valor(self):
return self._valor
def get_quantidade(self):
return self._qua... | class Pedido:
def __init__(self, cliente, valor, quantidade):
self._cliente = cliente
self._valor = valor
self._quantidade = quantidade
self._valor_total = 0
def get_valor(self):
return self._valor
def get_quantidade(self):
return self._quantidade
def ... |
def generate_confluence_graph(
project, data, type='bar', x_axis='name',
exclude_metrics=['started_at'],
):
exclude_metrics.append(x_axis)
metric_names = []
for k in data[0]:
if k not in exclude_metrics:
metric_names.append(k)
html = ""
html += '''
<ac:structured-... | def generate_confluence_graph(project, data, type='bar', x_axis='name', exclude_metrics=['started_at']):
exclude_metrics.append(x_axis)
metric_names = []
for k in data[0]:
if k not in exclude_metrics:
metric_names.append(k)
html = ''
html += '\n <ac:structured-macro ac:mac... |
# -*- coding: utf-8 -*-
"""
Constants and unclassified functions.
"""
MAPPING_ID_FIELD = 'mapped_id'
"""
The name of the mapping id column.
:type str
"""
| """
Constants and unclassified functions.
"""
mapping_id_field = 'mapped_id'
'\nThe name of the mapping id column.\n\n:type str\n' |
s = 1201
n = s > 1200
print(n)
a = 5
b = 1
c = True
d = True
condicao = a > b and c or d
print(condicao)
| s = 1201
n = s > 1200
print(n)
a = 5
b = 1
c = True
d = True
condicao = a > b and c or d
print(condicao) |
"""Methods to help characterize or compare models & training"""
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
| """Methods to help characterize or compare models & training"""
def count_parameters(model):
return sum((p.numel() for p in model.parameters() if p.requires_grad)) |
""" Base interpolator: a dummy class is derived by the different interpolator schemes """
class BaseInterpolator(object):
""" Base class for interpolation
It sets what can be expected as methods during the interpolation calls
"""
def __init__(self, osl, *args, **kwargs):
pass
def interp(... | """ Base interpolator: a dummy class is derived by the different interpolator schemes """
class Baseinterpolator(object):
""" Base class for interpolation
It sets what can be expected as methods during the interpolation calls
"""
def __init__(self, osl, *args, **kwargs):
pass
def interp(... |
# https://leetcode.com/problems/ambiguous-coordinates/
#
# algorithms
# Medium (43.27%)
# Total Accepted: 5,726
# Total Submissions: 13,232
# beats 91.11% of python submissions
class Solution(object):
def ambiguousCoordinates(self, S):
"""
:type S: str
:rtype: List[str]
"""
... | class Solution(object):
def ambiguous_coordinates(self, S):
"""
:type S: str
:rtype: List[str]
"""
s = S[1:-1]
length = len(S)
res = set()
for i in xrange(1, length):
left = self.add_decimal_point(S[:i])
right = self.add_decima... |
class PerfilpageTests(SimpleTestCase):
def test_perfilpage_status_code(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_perfilpage_url_name(self):
response = self.client.get(reverse('profile'))
self.assertEqual(response.status_code, 20... | class Perfilpagetests(SimpleTestCase):
def test_perfilpage_status_code(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_perfilpage_url_name(self):
response = self.client.get(reverse('profile'))
self.assertEqual(response.status_code, 20... |
"""
Naechstes Haus
Um die Weihnachtsliefertouren noch besser zu machen, muss der
Weihnachtsmann wissen welche zwei Haeuser in einer Nachbarschaft
am naehesten aneinander liegen. Er hat also ein Liste von
Haeusern (die Nachbarschaft) und muss die beiden finden, die
am Naehesten beieinander sind, zB:
In der Nachbarscha... | """
Naechstes Haus
Um die Weihnachtsliefertouren noch besser zu machen, muss der
Weihnachtsmann wissen welche zwei Haeuser in einer Nachbarschaft
am naehesten aneinander liegen. Er hat also ein Liste von
Haeusern (die Nachbarschaft) und muss die beiden finden, die
am Naehesten beieinander sind, zB:
In der Nachbarscha... |
def tribonacci(signature, n):
accu = signature[0:n]
for i in range(3,n):
accu.append( sum(accu[i-3:i]) )
return accu | def tribonacci(signature, n):
accu = signature[0:n]
for i in range(3, n):
accu.append(sum(accu[i - 3:i]))
return accu |
#!/usr/bin/env python
ip_addr = input("Please enter IP address: ")
my_ip_list = ip_addr.split(".")
my_ip_list[-1] = 0
ip_binary = []
ip_binary.append(bin(int(my_ip_list[0])))
ip_binary.append(bin(int(my_ip_list[1])))
ip_binary.append(bin(int(my_ip_list[2])))
ip_binary.append(bin(int(my_ip_list[3])))
print()
print("{... | ip_addr = input('Please enter IP address: ')
my_ip_list = ip_addr.split('.')
my_ip_list[-1] = 0
ip_binary = []
ip_binary.append(bin(int(my_ip_list[0])))
ip_binary.append(bin(int(my_ip_list[1])))
ip_binary.append(bin(int(my_ip_list[2])))
ip_binary.append(bin(int(my_ip_list[3])))
print()
print('{:<12} {:<12} {:<12} {:<12... |
#
# PySNMP MIB module Novell-LANalyzer-TR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Novell-LANalyzer-TR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:31:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint) ... |
#!/usr/bin/env python
# encoding: utf-8
"""
pascals_triangle.py
Created by Shengwei on 2014-07-03.
"""
# https://oj.leetcode.com/problems/pascals-triangle/
# tags: easy / medium, triangle, dp
"""
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
... | """
pascals_triangle.py
Created by Shengwei on 2014-07-03.
"""
"\nGiven numRows, generate the first numRows of Pascal's triangle.\n\nFor example, given numRows = 5,\nReturn\n\n[\n [1],\n [1,1],\n [1,2,1],\n [1,3,3,1],\n [1,4,6,4,1]\n]\n"
def triangle(n):
if n == 1:
return [[1]]
sub_tria = tr... |
LANGUAGE_CONFIG = {"language": "en", "locale": "en_CA"}
CUSTOM_ACTION_CONFIG = {"url": "http://0.0.0.0:8080/"}
NLP_CONFIG = {
"resolve_entities_using_nbest_transcripts": ["store_info.get_store_hours"]
}
DOMAIN_CLASSIFIER_CONFIG = {
"model_type": "text",
"model_settings": {"classifier_type": "logreg",},
... | language_config = {'language': 'en', 'locale': 'en_CA'}
custom_action_config = {'url': 'http://0.0.0.0:8080/'}
nlp_config = {'resolve_entities_using_nbest_transcripts': ['store_info.get_store_hours']}
domain_classifier_config = {'model_type': 'text', 'model_settings': {'classifier_type': 'logreg'}, 'param_selection': {... |
#funcao soma
def sum(a, b):
return a + b
c = sum(1, 3)
print("Somado: ", c)
| def sum(a, b):
return a + b
c = sum(1, 3)
print('Somado: ', c) |
class Snake():
def __init__(self, snake):
self.id = snake['id']
self.name = snake['name']
self.health = snake['health']
self.body = snake['body']
self.head = snake['head']
self.length = snake['length']
# self.head = self.coordinates[0]
# self.len... | class Snake:
def __init__(self, snake):
self.id = snake['id']
self.name = snake['name']
self.health = snake['health']
self.body = snake['body']
self.head = snake['head']
self.length = snake['length'] |
# CHECKING ARRAY IF IN SORTED ORDER
def checkSorted(n,A,i):
if i==n:
return 1
if A[i]>=A[i-1]:
return checkSorted(n,A,i+1)
else:
return 0
n = int(input("Enter number of elements :"))
Arr = [int(a) for a in input().split()]
if checkSorted(n,Arr,1):
print("Sorted")
el... | def check_sorted(n, A, i):
if i == n:
return 1
if A[i] >= A[i - 1]:
return check_sorted(n, A, i + 1)
else:
return 0
n = int(input('Enter number of elements :'))
arr = [int(a) for a in input().split()]
if check_sorted(n, Arr, 1):
print('Sorted')
else:
print('Not Sorted') |
temp = 120
if temp > 85:
print("Hot")
elif temp > 100:
print("REALLY HOT!")
elif temp > 60:
print("Comfortable")
else:
print("Cold") | temp = 120
if temp > 85:
print('Hot')
elif temp > 100:
print('REALLY HOT!')
elif temp > 60:
print('Comfortable')
else:
print('Cold') |
# -*- coding: utf-8 -*-
"""Top-level package for pfm."""
__author__ = """Takahiko Ito"""
__email__ = 'takahiko03@gmail.com'
__version__ = '0.6.0'
| """Top-level package for pfm."""
__author__ = 'Takahiko Ito'
__email__ = 'takahiko03@gmail.com'
__version__ = '0.6.0' |
dict={}
a=[[1,['ocean','pondy','2']],[2,['xxx','yyy','zzz']]]
for i in a:
dict.update({i[0]:i[1]})
print(dict)
b=int(input('enter value '))
x=dict.get(b)
y=['name','place','age']
for i in range(len(y)):
print(y[i],':',x[i])
| dict = {}
a = [[1, ['ocean', 'pondy', '2']], [2, ['xxx', 'yyy', 'zzz']]]
for i in a:
dict.update({i[0]: i[1]})
print(dict)
b = int(input('enter value '))
x = dict.get(b)
y = ['name', 'place', 'age']
for i in range(len(y)):
print(y[i], ':', x[i]) |
# Python program to print odd Numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93]
i = 0
# using while loop
while(i < len(list1)):
# checking condition
if list1[i] % 2 != 0:
print(list1[i], end = " ")
# increment i
i += 1
| list1 = [10, 21, 4, 45, 66, 93]
i = 0
while i < len(list1):
if list1[i] % 2 != 0:
print(list1[i], end=' ')
i += 1 |
# -*- coding: UTF-8 -*-
# @Time : 04/08/2020 15:38
# @Author : QYD
# @FileName: tree.py
# @Software: PyCharm
class TreeNode(object):
def __init__(self, value, start_point_index):
self.value = value
self.start_point_index = start_point_index
self.child_list = []
def add_child(self, ... | class Treenode(object):
def __init__(self, value, start_point_index):
self.value = value
self.start_point_index = start_point_index
self.child_list = []
def add_child(self, node):
self.child_list.append(node) |
"""
N
1^3 + 2^3 + 3^3 + ... + N^3
"""
n = int(input())
result = 0
for i in range(1, n + 1):
result = result + i ** 3
print(result)
| """
N
1^3 + 2^3 + 3^3 + ... + N^3
"""
n = int(input())
result = 0
for i in range(1, n + 1):
result = result + i ** 3
print(result) |
def day_to_seconds(day):
return day * 24 * 60 * 60
def hour_to_seconds(hour):
return hour * 60 * 60
def seconds_to_hour(seconds):
return seconds / (60 * 60) | def day_to_seconds(day):
return day * 24 * 60 * 60
def hour_to_seconds(hour):
return hour * 60 * 60
def seconds_to_hour(seconds):
return seconds / (60 * 60) |
#!/usr/bin/python
n = int(input())
res, count = 0, 2
for _ in range(n):
name = input()
if name.endswith('+one'):
count += 2
else:
count += 1
if count == 13:
count += 1
print(count * 100)
| n = int(input())
(res, count) = (0, 2)
for _ in range(n):
name = input()
if name.endswith('+one'):
count += 2
else:
count += 1
if count == 13:
count += 1
print(count * 100) |
ENDPOINT_ARGUMENTS = {
'search_instruments': {
'projection': ['symbol-search', 'symbol-regex', 'desc-search', 'desc-regex', 'fundamental']
},
'get_market_hours': {
'markets': ['EQUITY', 'OPTION', 'FUTURE', 'BOND', 'FOREX']
},
'get_movers': {
'market': ['$DJI', '$COMPX', '$SPX... | endpoint_arguments = {'search_instruments': {'projection': ['symbol-search', 'symbol-regex', 'desc-search', 'desc-regex', 'fundamental']}, 'get_market_hours': {'markets': ['EQUITY', 'OPTION', 'FUTURE', 'BOND', 'FOREX']}, 'get_movers': {'market': ['$DJI', '$COMPX', '$SPX.X'], 'direction': ['up', 'down'], 'change': ['val... |
#
# PySNMP MIB module TC-GROUPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TC-GROUPS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:08:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, constraints_intersection, value_size_constraint) ... |
#-------------------------------------------------------------------------------
# readstrings.py - A demonstration of while loops to validate user input
#-------------------------------------------------------------------------------
# (note the need for "len(string) == 0" to appear twice).
def getString1():
stri... | def get_string1():
string = ''
while len(string) == 0:
string = input('Enter a non-empty string: ')
if len(string) == 0:
print("You didn't enter anything!")
return string
def get_string2():
while True:
string = input('Enter a non-empty string: ')
if len(strin... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2002-2019 "Neo4j,"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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
... | class Datetype(type):
def __getattr__(cls, name):
try:
return {'fromisoformat': cls.from_iso_format, 'fromordinal': cls.from_ordinal, 'fromtimestamp': cls.from_timestamp, 'utcfromtimestamp': cls.utc_from_timestamp}[name]
except KeyError:
raise attribute_error('%s has no attr... |
"""This application overrides django-machina's forum_moderation app."""
# pylint: disable=invalid-name
default_app_config = (
"ashley.machina_extensions.forum_moderation.apps.ForumModerationAppConfig"
)
| """This application overrides django-machina's forum_moderation app."""
default_app_config = 'ashley.machina_extensions.forum_moderation.apps.ForumModerationAppConfig' |
def insertion_sort(unsorted_list):
for index in range(1, len(unsorted_list)):
search_index = index
insert_value = unsorted_list[index]
while search_index > 0 and unsorted_list[search_index - 1] > insert_value:
unsorted_list[search_index] = unsorted_list[search_index - 1]
... | def insertion_sort(unsorted_list):
for index in range(1, len(unsorted_list)):
search_index = index
insert_value = unsorted_list[index]
while search_index > 0 and unsorted_list[search_index - 1] > insert_value:
unsorted_list[search_index] = unsorted_list[search_index - 1]
... |
test = {
'name': 'Problem 0',
'points': 0,
'suites': [
{
'cases': [
{
'answer': 'It represents the amount of health the insect has left, so the insect is eliminated when it reaches 0',
'choices': [
r"""
It represents armor protecting the insect, so the... | test = {'name': 'Problem 0', 'points': 0, 'suites': [{'cases': [{'answer': 'It represents the amount of health the insect has left, so the insect is eliminated when it reaches 0', 'choices': ['\n It represents armor protecting the insect, so the insect can only\n be damaged when its armor reaches ... |
"""
Good morning! Here's your coding interview problem for today.
This question was asked by Zillow.
You are given a 2-d matrix where each cell represents number of coins in that cell. Assuming we start at matrix[0][0], and can only move right or down, find the maximum number of coins you can collect by the bottom ri... | """
Good morning! Here's your coding interview problem for today.
This question was asked by Zillow.
You are given a 2-d matrix where each cell represents number of coins in that cell. Assuming we start at matrix[0][0], and can only move right or down, find the maximum number of coins you can collect by the bottom ri... |
Basic_HEADER = {'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers':
'access_token, accessToken,origin,'
' x-csrftoken, content-type, accept',
'Access-Control-Max-... | basic_header = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS', 'Access-Control-Allow-Headers': 'access_token, accessToken,origin, x-csrftoken, content-type, accept', 'Access-Control-Max-Age': '1728000'}
file_upload_header = {'Access-Control-Allow-Origin': '*', 'Access-Control-... |
# HEAD
# Membership Operators
# DESCRIPTION
# Describe the usage of membership operators
# RESOURCES
#
# 'in' operator checks if an item is a part of
# a sequence or iterator
# 'not in' operator checks if an item is not
# a part of a sequence or iterator
lists = [1, 2, 3, 4, 5]
dictions = {"key": "valu... | lists = [1, 2, 3, 4, 5]
dictions = {'key': 'value', 'a': 'b', 'c': 'd'}
if 1 in lists:
print('in operator - 1 in lists:', 1 in lists)
if 1 not in lists:
print('not in operator - 1 not in lists:', 1 not in lists)
if 'b' not in lists:
print("not in operator - 'b' not in lists:", 'b' not in lists)
if 'key' in ... |
class Character:
def __init__(self):
self._firstName = ''
self._lastName = ''
self._pic = ''
self._position = ''
self._bio = ''
@property
def firstName(self):
return self._firstName
@property
def lastName(self):
return self._lastN... | class Character:
def __init__(self):
self._firstName = ''
self._lastName = ''
self._pic = ''
self._position = ''
self._bio = ''
@property
def first_name(self):
return self._firstName
@property
def last_name(self):
return self._lastName
... |
def test_signal_wikidata_url(ranker):
rank = lambda url: ranker.client.get_signal_value_from_url("wikidata_url", url)
assert rank("http://www.douglasadams.com") > 0.5
assert rank("http://www.douglasadams.com/?a=b") > 0.5
assert rank("http://www.douglasadams.com/page2") == 0. # TODO, check domain?
... | def test_signal_wikidata_url(ranker):
rank = lambda url: ranker.client.get_signal_value_from_url('wikidata_url', url)
assert rank('http://www.douglasadams.com') > 0.5
assert rank('http://www.douglasadams.com/?a=b') > 0.5
assert rank('http://www.douglasadams.com/page2') == 0.0
assert rank('http://www... |
#!/usr/bin/env python3
fileNum = input('File Number: ')
file = bytearray(open(fileNum + '.txt', 'rb').read())
seed = input('Seed (format is XXX, XXX, XXX): ')
init = int(seed[0:3])
mult = int(seed[5:8])
inc = int(seed[10:13])
key = ""
current = init
for i in range(120):
key += chr(current)
current *= mult
... | file_num = input('File Number: ')
file = bytearray(open(fileNum + '.txt', 'rb').read())
seed = input('Seed (format is XXX, XXX, XXX): ')
init = int(seed[0:3])
mult = int(seed[5:8])
inc = int(seed[10:13])
key = ''
current = init
for i in range(120):
key += chr(current)
current *= mult
current += inc
curr... |
num=int(input())
r=[]
for i in range(num):
array=input().split(' ')
array=[int(m) for m in array if m !='']
array.remove(array[0])
js=[]
os=[]
for k in range(len(array)):
if array[k]%2==0:
os.append(array[k])
else:
js.append(array[k])
js=sorted(js)
... | num = int(input())
r = []
for i in range(num):
array = input().split(' ')
array = [int(m) for m in array if m != '']
array.remove(array[0])
js = []
os = []
for k in range(len(array)):
if array[k] % 2 == 0:
os.append(array[k])
else:
js.append(array[k])
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 19:56:21 2020
@author: darrenhsu
"""
def word_reduce(s, vowel=0, repeat=0, listAll=False):
vowel_set = {'a','e','i','o','u','A','E','I','O','U'}
# Assertions
if type(s) == list:
pass
elif listAll == False:
new_s =... | """
Created on Fri Nov 27 19:56:21 2020
@author: darrenhsu
"""
def word_reduce(s, vowel=0, repeat=0, listAll=False):
vowel_set = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
if type(s) == list:
pass
elif listAll == False:
new_s = ''
last_c = ''
vowel_index = 0
... |
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for st in s:
if st in ('(', '{', '['):
stack.append(st)
else:
if len(stack) < 1:
return False
tmp = stack.pop()
if st == ')' and t... | class Solution:
def is_valid(self, s: str) -> bool:
stack = []
for st in s:
if st in ('(', '{', '['):
stack.append(st)
else:
if len(stack) < 1:
return False
tmp = stack.pop()
if st == ')' and... |
class Camera():
def __init__(self, camera_matrix, projection_matrix, parameters={}):
self.camera_matrix = camera_matrix
self.projection_matrix = projection_matrix
self.parameters = parameters
class Material():
def __init__(self, shader, parameters={}):
self.shader = shader
... | class Camera:
def __init__(self, camera_matrix, projection_matrix, parameters={}):
self.camera_matrix = camera_matrix
self.projection_matrix = projection_matrix
self.parameters = parameters
class Material:
def __init__(self, shader, parameters={}):
self.shader = shader
... |
def factorial(n):
result = 1
for i in range(n):
result *= i + 1
return result
| def factorial(n):
result = 1
for i in range(n):
result *= i + 1
return result |
#!/bin/python3
def swap_case(s):
tmp = []
for c in s:
if c.islower():
tmp.append(c.upper())
else:
tmp.append(c.lower())
return ''.join(tmp)
def main():
s = input()
result = swap_case(s)
print(result)
if __name__ == '__main__':
main()
| def swap_case(s):
tmp = []
for c in s:
if c.islower():
tmp.append(c.upper())
else:
tmp.append(c.lower())
return ''.join(tmp)
def main():
s = input()
result = swap_case(s)
print(result)
if __name__ == '__main__':
main() |
__author__ = 'roeiherz'
"""
You have an integer matrix representation a plot of land, where the value at that location represents the height above
see level. A value of zero indicates water. A pond is a region of water connected vertically, horizontally,
or diagonally. The size of the pond is the total number of conn... | __author__ = 'roeiherz'
'\nYou have an integer matrix representation a plot of land, where the value at that location represents the height above\nsee level. A value of zero indicates water. A pond is a region of water connected vertically, horizontally, \nor diagonally. The size of the pond is the total number of conn... |
# Date: 2020/11/05
# Author: Luis Marquez
# Description:
# This is a demostration of brute-force Search algorithm, in this program we'll calculate
# an exact square root of a number 'n' -> Objective
#run
def run():
answer = 0
objective = int(input(f"Type an integer: "))
while a... | def run():
answer = 0
objective = int(input(f'Type an integer: '))
while answer ** 2 < objective:
answer += 1
if answer ** 2 == objective:
print(f'\nThe square root of {objective} is {answer}\n')
else:
print(f"\n{objective} doesn't have an exact square root\n")
if __name__ ==... |
def foo() -> int:
return 1
foo()
| def foo() -> int:
return 1
foo() |
#import Adafruit_DHT
# GPIO Channel for RGB LED Strip
r_channel = 25
g_channel = 27
b_channel = 22
# GPIO Channel for white LED Strip
w_channel = 18
# Location Latitude and Longitude (Auckland, New Zealand)
latitude = "-36.84"
longitude = "174.74"
# RGBW Value to use during Day
day_colour = [75, 255, 0, 100]
# RG... | r_channel = 25
g_channel = 27
b_channel = 22
w_channel = 18
latitude = '-36.84'
longitude = '174.74'
day_colour = [75, 255, 0, 100]
night_colour = [0, 100, 100, 0]
sunrise_colour_map = {3600: night_colour, 3000: [0, 50, 100, 15], 2400: [100, 30, 30, 30], 1800: [255, 0, 0, 60], 1500: [255, 100, 0, 80], 1200: [255, 200, ... |
def game_of_life(alive = []):
return list(set(newborns(alive) + staying_alive(alive)))
def newborns(alive):
return next_living_from(
cells = neighbors_of_all_alive(alive),
alive = alive,
valid_neighbor_counts = [3]
)
def staying_alive(alive):
return next_living_from(
ce... | def game_of_life(alive=[]):
return list(set(newborns(alive) + staying_alive(alive)))
def newborns(alive):
return next_living_from(cells=neighbors_of_all_alive(alive), alive=alive, valid_neighbor_counts=[3])
def staying_alive(alive):
return next_living_from(cells=alive, alive=alive, valid_neighbor_counts=[... |
"""
emailAge exception handling module.
"""
class EmailAgeServiceException(Exception):
"""
Exception: Serves as the exception handler for emailAge requests.
"""
def __init__(self, error_code, value):
self.error_code = error_code
self.value = value
def __unicode__(self):
r... | """
emailAge exception handling module.
"""
class Emailageserviceexception(Exception):
"""
Exception: Serves as the exception handler for emailAge requests.
"""
def __init__(self, error_code, value):
self.error_code = error_code
self.value = value
def __unicode__(self):
re... |
"""child_b docstr"""
class B:
"""This class is defined in .child_b."""
def b(self):
return 1
| """child_b docstr"""
class B:
"""This class is defined in .child_b."""
def b(self):
return 1 |
num1 = 1
num2 = 2
num3 = 45
num4 = 23
| num1 = 1
num2 = 2
num3 = 45
num4 = 23 |
# -*- coding: utf-8 -*-
'''
Let's teach the Robots to distinguish words and numbers.
You are given a string with words and numbers separated by whitespaces (one space).
The words contains only letters.
You should check if the string contains three words in succession.
For example, the string "start 5 one two three 7... | """
Let's teach the Robots to distinguish words and numbers.
You are given a string with words and numbers separated by whitespaces (one space).
The words contains only letters.
You should check if the string contains three words in succession.
For example, the string "start 5 one two three 7 end" contains three word... |
class Solution:
# @return a string
def convert(self, s, n):
if n <= 0:
return ''
if n == 1 or n >= len(s):
return s
step = n * 2 - 2
a = step
b = step
res = ''
for i in range(n):
res += s[i]
j = i
... | class Solution:
def convert(self, s, n):
if n <= 0:
return ''
if n == 1 or n >= len(s):
return s
step = n * 2 - 2
a = step
b = step
res = ''
for i in range(n):
res += s[i]
j = i
while j + a < len(s):... |
DB1 = 'default'
DB2 = 'streamdata'
DB3 = 'streamtimeseries'
# List of apps that should use Redshift
# Currently, we don't seem to be able to add another table
# so until we figure out, we can only keep one
REDSHIFT_APPs = ['streamdata', ]
STREAM_TIME_SERIES_APPs = ['streamtimeseries', ]
| db1 = 'default'
db2 = 'streamdata'
db3 = 'streamtimeseries'
redshift_ap_ps = ['streamdata']
stream_time_series_ap_ps = ['streamtimeseries'] |
class Solution:
"""
@param: A: An integer matrix
@return: The index of the peak
"""
def findPeakII(self, A):
m, n = len(A), len(A[0])
for i in range(1, m - 1):
left, right = 0, n - 1
while left + 1 < right:
mid = (left + right) // 2
... | class Solution:
"""
@param: A: An integer matrix
@return: The index of the peak
"""
def find_peak_ii(self, A):
(m, n) = (len(A), len(A[0]))
for i in range(1, m - 1):
(left, right) = (0, n - 1)
while left + 1 < right:
mid = (left + right) // 2
... |
def color_to_rgb(rgb_or_name):
color_name_to_rgb = {"black": [0, 0, 0],
"red": [1, 0, 0], "green": [0, 1, 0],
"blue": [0, 0, 1], "yellow": [1, 1, 0],
"orange": [1, 0.5, 0],
"white":[1,1,1]}
if isinstance(rgb_or_name, str):
... | def color_to_rgb(rgb_or_name):
color_name_to_rgb = {'black': [0, 0, 0], 'red': [1, 0, 0], 'green': [0, 1, 0], 'blue': [0, 0, 1], 'yellow': [1, 1, 0], 'orange': [1, 0.5, 0], 'white': [1, 1, 1]}
if isinstance(rgb_or_name, str):
return color_name_to_rgb[rgb_or_name]
else:
return rgb_or_name |
def parse_dset_config(path):
"""Parses the dset configuration file"""
options = dict()
with open(path, 'r') as fp:
lines = fp.readlines()
for line in lines:
line = line.strip()
if line == '' or line.startswith('#'):
continue
key, value = line.split('=')
... | def parse_dset_config(path):
"""Parses the dset configuration file"""
options = dict()
with open(path, 'r') as fp:
lines = fp.readlines()
for line in lines:
line = line.strip()
if line == '' or line.startswith('#'):
continue
(key, value) = line.split('=')
... |
"""
File: largest_digit.py
Name: Gibbs
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
"""
This function recursively finds the biggest dig... | """
File: largest_digit.py
Name: Gibbs
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
"""
This function recursively finds the biggest d... |
# Single-quoted string is preceded and succeeded by newlines.
# Translators: This is a helpful comment.
_(
'3'
)
| _('3') |
"""
Znajdz brakujacy element w liscie.
Ciag arytmetyczny.
"""
# Wersja 1
def znajdz_brakujacy_element(lista):
suma_przedzialu = (len(lista) + 1) * (min(lista) + max(lista)) // 2
return suma_przedzialu - sum(lista)
# Testy poprawnosci
lista = [6, 8, 4, 10, 14, 2]
wynik = 12
assert znajdz_brakujacy_element(li... | """
Znajdz brakujacy element w liscie.
Ciag arytmetyczny.
"""
def znajdz_brakujacy_element(lista):
suma_przedzialu = (len(lista) + 1) * (min(lista) + max(lista)) // 2
return suma_przedzialu - sum(lista)
lista = [6, 8, 4, 10, 14, 2]
wynik = 12
assert znajdz_brakujacy_element(lista) == wynik |
S = input()
level = len(S)
x = 0
y = 0
for i in range(level):
if S[i] == '1' or S[i] == '3':
x += 2**(level - i - 1)
if S[i] == '2' or S[i] == '3':
y += 2**(level - i - 1)
print(level, x, y) | s = input()
level = len(S)
x = 0
y = 0
for i in range(level):
if S[i] == '1' or S[i] == '3':
x += 2 ** (level - i - 1)
if S[i] == '2' or S[i] == '3':
y += 2 ** (level - i - 1)
print(level, x, y) |
#! /usr/bin/env python3
class Pattern:
def __init__ (self, order):
#rev = {}
#I = range (0, len (order))
#for i, v in zip (I, order):
# if v in rev: temp = rev[v]
# else: temp = []
# rev[v] = tuple (temp + [i])
self.order = order
#self.rev = rev
def __repr__ (self): return "Pattern [order=... | class Pattern:
def __init__(self, order):
self.order = order
def __repr__(self):
return 'Pattern [order=%s]' % (self.order,)
def __len__(self):
return len(self.order)
def __getitem__(self, key):
return self.order[key]
def __iter__(self):
return iter(self.... |
questions = {
'What year was the MicroBit educational foundation created?':
[
'2016',
'2014',
'2017',
0
],
'What year was the first computer invented?':
[
'1954',
'1943',
'1961',
1
],
... | questions = {'What year was the MicroBit educational foundation created?': ['2016', '2014', '2017', 0], 'What year was the first computer invented?': ['1954', '1943', '1961', 1], 'What year did Damien George create MicroPython?': ['2015', '2012', '2014', 2], 'What year did the Commodore 64 get released?': ['1983', '198... |
# Name: Reetesh Zope
# Student ID: 801138214
# Email ID: rzope1@uncc.edu
"""
edge.py
_________
A class used to represent the link between two routers in the network.
----------
Attributes
----------
source : str
A string which contains source router name of the link
destination : list
... | """
edge.py
_________
A class used to represent the link between two routers in the network.
----------
Attributes
----------
source : str
A string which contains source router name of the link
destination : list
A string which contains destination router name of the link
isUp : object
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 30 21:17:33 2018
@author: gaoxi
"""
def printdata(data):
print(data)
| """
Created on Mon Jul 30 21:17:33 2018
@author: gaoxi
"""
def printdata(data):
print(data) |
'''
Created on 22.11.2016
@author: rustr
'''
MSG_IDENTIFIER = 1
MSG_COMMAND = 2 # [command_id, counter, position, orientation, optional values]
MSG_COMMAND_RECEIVED = 3
MSG_COMMAND_EXECUTED = 4
MSG_CURRENT_POSE_CARTESIAN = 5 # [position, orientation]
MSG_CURRENT_POSE_JOINT = 6 # [j1j2j3j4j5j6]
MSG_CURRENT_DIGITAL_IN ... | """
Created on 22.11.2016
@author: rustr
"""
msg_identifier = 1
msg_command = 2
msg_command_received = 3
msg_command_executed = 4
msg_current_pose_cartesian = 5
msg_current_pose_joint = 6
msg_current_digital_in = 7
msg_current_analog_in = 20
msg_analog_in = 8
msg_analog_out = 9
msg_digital_in = 10
msg_digital_out = 11... |
#Jacob Hardman
#CS301 Algorithms and Data Structures
#Dr. Nathaniel Miller
#Stack
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]... | class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def is_empty(self):
return self.items == []
def size(self):
... |
def brute(n):
cnt = 0
for a in range(1, n + 1):
for b in range(a + 1, n + 1):
for c in range(b + 1, n + 1):
for d in range(c + 1, n + 1):
if a * d == b * c:
print('%s * %s = %s * %s = %s' % (a, d, b, c, a * d))
... | def brute(n):
cnt = 0
for a in range(1, n + 1):
for b in range(a + 1, n + 1):
for c in range(b + 1, n + 1):
for d in range(c + 1, n + 1):
if a * d == b * c:
print('%s * %s = %s * %s = %s' % (a, d, b, c, a * d))
... |
#Prints all the numbers from 1 - 1000
count = 0
while count <= 1000:
print(count)
count += 1
| count = 0
while count <= 1000:
print(count)
count += 1 |
# Given two arrays, a and b, calculate how many times the following is true:
# i <= j
# a[i] - b[j] = a[j] - b[i]
# This works on O(n^2) time
def checkArraysSlow(a, b):
counter = 0
for i in range(len(a)):
for j in range(i, len(a)):
if a[i] - b[j] == a[j] - b[i]:
counter += 1
re... | def check_arrays_slow(a, b):
counter = 0
for i in range(len(a)):
for j in range(i, len(a)):
if a[i] - b[j] == a[j] - b[i]:
counter += 1
return counter
def check_arrays_nr(a, b):
counter = 0
dict = {}
for i in range(len(a)):
dict[a[i] + b[i]] = i
f... |
class Solution:
# data structure type: stack
def decodeString(self, s: str):
#Traverse the string
stack, currCount, currString = [], 0, ""
for c in s:
if c == '[':
stack.append(currString)
stack.append(currCount)
currString = ""... | class Solution:
def decode_string(self, s: str):
(stack, curr_count, curr_string) = ([], 0, '')
for c in s:
if c == '[':
stack.append(currString)
stack.append(currCount)
curr_string = ''
curr_count = 0
elif c ==... |
"""1.9 String Rotation: Assume you have a method isSubst ring which checks if one word is a substring
of another. Given two strings, 51 and 52, write code to check if 52 is a rotation of 51 using only one
call to isSubstring (e.g., "waterbottle" is a rotation of "erbottlewat").
"""
def string_rotation(string_1: str, st... | """1.9 String Rotation: Assume you have a method isSubst ring which checks if one word is a substring
of another. Given two strings, 51 and 52, write code to check if 52 is a rotation of 51 using only one
call to isSubstring (e.g., "waterbottle" is a rotation of "erbottlewat").
"""
def string_rotation(string_1: str, s... |
# -*- coding: utf-8 -*-
# Copyright 2021 ICONation
#
# 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 agre... | scorelib_bag = ['scorelib/__init__.py', 'scorelib/consts.py', 'scorelib/bag.py']
scorelib_set = ['scorelib/__init__.py', *scorelib_bag, 'scorelib/set.py']
scorelib_consts = ['scorelib/__init__.py', 'scorelib/consts.py']
scorelib_utils = ['scorelib/__init__.py', *scorelib_consts, 'scorelib/utils.py']
scorelib_state = ['... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 18 08:16:50 2016
@author: ericgrimson
"""
class Student(MITPerson):
pass
class UG(Student):
def __init__(self, name, classYear):
MITPerson.__init__(self, name)
self.year = classYear
def getClass(self):
return self.year
class Grad(St... | """
Created on Wed May 18 08:16:50 2016
@author: ericgrimson
"""
class Student(MITPerson):
pass
class Ug(Student):
def __init__(self, name, classYear):
MITPerson.__init__(self, name)
self.year = classYear
def get_class(self):
return self.year
class Grad(Student):
pass
clas... |
__author__ = 'postrowski'
# -*-coding: utf-8-*-
class MakeDict(object):
@staticmethod
def make_dict(list1, list2, list3):
"""
Function makes a dictionary.
:param list1: input list (keys())
:param list2: input list (nested keys())
:param list3: input list (nested v... | __author__ = 'postrowski'
class Makedict(object):
@staticmethod
def make_dict(list1, list2, list3):
"""
Function makes a dictionary.
:param list1: input list (keys())
:param list2: input list (nested keys())
:param list3: input list (nested values())
:return... |
f = open("log/hbase_total.log")
lines = f.readlines()
indices = [index for index, l in enumerate(lines) if '======== tag_old: ' in l]
i = indices[0]
optional_required = []
rest = []
add_req = []
for j in indices[1:]:
cs = lines[i+1:j]
for c in cs:
t = lines[i]
t = t[:t.index('#change')]
tags = t.replac... | f = open('log/hbase_total.log')
lines = f.readlines()
indices = [index for (index, l) in enumerate(lines) if '======== tag_old: ' in l]
i = indices[0]
optional_required = []
rest = []
add_req = []
for j in indices[1:]:
cs = lines[i + 1:j]
for c in cs:
t = lines[i]
t = t[:t.index('#change')]
... |
def option_price_call_american_binomial(S, K, r, sigma, t, steps):
"""American Option (Call) using binomial approximations
Converted to Python from "Financial Numerical Recipes in C" by:
Bernt Arne Odegaard
http://finance.bi.no/~bernt/gcc_prog/index.html
@param S: spot (underlying) price
@param... | def option_price_call_american_binomial(S, K, r, sigma, t, steps):
"""American Option (Call) using binomial approximations
Converted to Python from "Financial Numerical Recipes in C" by:
Bernt Arne Odegaard
http://finance.bi.no/~bernt/gcc_prog/index.html
@param S: spot (underlying) price
@param ... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
value_array = []
... | class Solution(object):
def sort_list(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
value_array = []
current_node = head
while current_node != None:
value_array.append(current_node.val)
current_node = current_node.next
... |
{
"comment": "Create a twitter app here https://apps.twitter.com/ then and copy the key info below",
"consumer_key": "(your key goes here)",
"consumer_secret": "(your secret key goes here)",
"access_token": "(your key goes here)",
"access_token_secret": "(your secret key goes here)"
}
| {'comment': 'Create a twitter app here https://apps.twitter.com/ then and copy the key info below', 'consumer_key': '(your key goes here)', 'consumer_secret': '(your secret key goes here)', 'access_token': '(your key goes here)', 'access_token_secret': '(your secret key goes here)'} |
while True:
n = int(input('\033[1;97mQuer ver a tabuada de qual valor? '))
if n < 0:
break
print('=' * 19)
for c in range(1, 11):
if c == 10:
print('|\033[91m{:>4} \033[97mx \033[91m{} \033[97m= \033[91m{:<5}\033[97m|'.format(n, c, n * c))
break
print('|\0... | while True:
n = int(input('\x1b[1;97mQuer ver a tabuada de qual valor? '))
if n < 0:
break
print('=' * 19)
for c in range(1, 11):
if c == 10:
print('|\x1b[91m{:>4} \x1b[97mx \x1b[91m{} \x1b[97m= \x1b[91m{:<5}\x1b[97m|'.format(n, c, n * c))
break
print('|\x... |
# The mapping here uses hhblits convention, so that B is mapped to D, J and O
# are mapped to X, U is mapped to C, and Z is mapped to E. Other than that the
# remaining 20 amino acids are kept in alphabetical order.
# There are 2 non-amino acid codes, X (representing any amino acid) and
# "-" representing a missing ami... | hhblits_aa_to_id = {'A': 0, 'B': 2, 'C': 1, 'D': 2, 'E': 3, 'F': 4, 'G': 5, 'H': 6, 'I': 7, 'J': 20, 'K': 8, 'L': 9, 'M': 10, 'N': 11, 'O': 20, 'P': 12, 'Q': 13, 'R': 14, 'S': 15, 'T': 16, 'U': 1, 'V': 17, 'W': 18, 'X': 20, 'Y': 19, 'Z': 3, '-': 21}
id_to_hhblits_aa = {0: 'A', 1: 'C', 2: 'D', 3: 'E', 4: 'F', 5: 'G', 6:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.