content stringlengths 7 1.05M |
|---|
"""
Part 1 Solution: 580
Part 2 Solution: 81972
"""
# Basically a Sum function
def solve_day1_part1():
fname = "data_day1.txt"
frequency = 0
with open(fname) as fp:
line = fp.readline().rstrip("\n")
while line:
i = int(line)
frequency += i
# print("{} => {} = {}".format(line, i, total))
# print("{... |
a=int(input("enter first number:"))
b=int(input("enter second number:"))
sum=0
for i in range (a,b+1):
sum=sum+i
print(sum)
|
# contains bunch of buggy examples
# taken from https://hackernoon.com/10-common-security-gotchas-in-python
# -and-how-to-avoid-them-e19fbe265e03
def transcode_file(filename):
"""Input injection"""
command = 'ffmpeg -i "{source}" output_file.mpg'.format(source=filename)
return command
# a bad i... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {integer[]} preorder
# @param {integer[]} inorder
# @return {TreeNode}
def buildTree(self, preorder, inorder):
... |
while 1:
a = 1
break
print(a) # pass
|
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
start = self.binarySearch(nums, target)
if start == -1:
return [-1, -1]
end = self.binarySearch(nums, targe... |
# Migration removed because it depends on models which have been removed
def run():
return False |
"""
Program to determine whether a given number is a Harshad number
Harshad number
A number is said to be the Harshad number if it is divisible by the sum of its digit.
For example, if number is 156, then sum of its digit will be 1 + 5 + 6 = 12. Since 156 is divisible by 12.
So, 156 is a Harshad number.
Some of ... |
#-----------------------------------------------------------------#
#! Python3
# Author : NK
# Month, Year : March, 2019
# Info : Program to get Squares of numbers upto 25, using return
# Desc : An example program to show usage of return
#--------------------------------------... |
# Reference: http://www.unicode.org/versions/Unicode8.0.0/ch03.pdf#G24646
BASE_OF_SYLLABLES = 0xAC00
BASE_OF_LEADING_CONSONANTS = 0x1100
BASE_OF_VOWELS = 0x1161
BASE_OF_TRAILING_CONSONANTS = 0x11A7 # one less than the beginning of the range of trailing consonants (0x11A8)
NUMBER_OF_LEADING_CONSONANTS = 19
NUMBER_OF... |
def get_planet_name(id):
tmp = {
1: "Mercury",
2: "Venus",
3: "Earth",
4: "Mars",
5: "Jupiter",
6: "Saturn",
7: "Uranus",
8: "Neptune"
}
return tmp[id]
|
class Solution:
def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:
potions = [(val, idx) for idx, val in enumerate(potions)]
potions.sort()
spells = [(val, idx) for idx, val in enumerate(spells)]
spells.sort()
left = 0
right =... |
#
# PySNMP MIB module SONOMASYSTEMS-SONOMA-IPAPPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-IPAPPS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:09:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... |
#!/usr/bin/env python3
'''Iterate over multiple sequences in parallel using zip() function
NOET:
zip() stops when the shortest sequence is done
'''
# Init
days = ['Monday', 'Tuesday', 'Wednesday']
fruits = ['banana', 'orange', 'peach']
drinks = ['coffee', 'tea', 'beer']
desserts = ['tiramisu', 'ice cream', 'pie', '... |
"""One To Many.
...is used to mark that an instance of a class can be associated with
many instances of another class. For example, on a blog engine, an
instance of the Article class could be associated with many instances
of the Comment class. In this case, we would map the mentioned classes
and its relation as follo... |
name=input("Please input my daughter's name:")
while name!="Nina" and name!="Anime":
print("I'm sorry, but the name is not valid.")
name=input("Please input my daughter's name:")
print("Yes."+name+"is my daughter.")
|
cases = [
('pmt -s 1 -n 20 populations, use seed so same run each time',
'pmt -s 1 -n 20 populations'),
('pmt -s 2 -n 6 populations, use seed so same run each time',
'pmt -s 2 -n 6 -r 3 populations')
]
|
{
"hawq": {
"master": "localhost",
"standby": "",
"port": 5432,
"user": "johnsaxon",
"password": "test",
"database": "postgres"
},
"data_config": {
"schema": "public",
"table": "elec_tiny",
"features": [
{
"n... |
class Solution:
def decodeString(self, s: str) -> str:
stack_mul = []
stack_char = []
mul = 0
strr = ''
for char in s:
if char.isdigit():
mul = 10*mul + int(char)
elif char.isalpha():
strr += char
elif char =... |
# 这就是一个简单的节点了,相当的简单哈!!!
def main():
print('Hi from python my_package.')
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-03-24
算法思想:双指针
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head... |
"""New retry v2 handlers.
This package obsoletes the ibm_botocore/retryhandler.py module and contains
new retry logic.
"""
|
"""
38. User-registered management commands
The ``manage.py`` utility provides a number of useful commands for managing a
Django project. If you want to add a utility command of your own, you can.
The user-defined command ``dance`` is defined in the management/commands
subdirectory of this test application. It is a s... |
# -*- coding: utf-8 -*-
'''
Python内建的filter()函数用于过滤序列。
和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,
filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
'''
#在一个list中,删掉偶数,只保留奇数,可以这么写
def is_odd(n):
return n%2==1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9])))
#回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数:
d... |
{
"targets": [{
"target_name": "findGitRepos",
"dependencies": [
"vendor/openpa/openpa.gyp:openpa"
],
"sources": [
"cpp/src/FindGitRepos.cpp",
"cpp/src/Queue.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon... |
def define_actions( action ):
"""
Define the list of actions we are using.
Args
action: String with the passed action. Could be "all"
Returns
actions: List of strings of actions
Raises
ValueError if the action is not included in H3.6M
"""
actions = ["walking", "eating", "smoking", "discussio... |
# Withdrawal Request amount must be non-negative
non_negative_amount = \
"""
ALTER TABLE ledger_withdrawalrequest DROP CONSTRAINT IF EXISTS non_negative_amount;
ALTER TABLE ledger_withdrawalrequest ADD CONSTRAINT non_negative_amount CHECK ("amount" >= 0);
ALTER TABLE ledger_withdrawalrequest VALIDATE CONSTRAINT non... |
# Using hash table
# Time Complexity: O(n)
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
checkDict =dict()
final = list()
for i in nums1:
if i not in checkDict:
checkDict[i] = 1
else:
checkDict[... |
# using factorial, reduced the time complexity
# of program from O(2^N) to O(N)
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n - 1)
def computeCoefficient(col, row):
return factorial(row) // (factorial(col) * factorial(row - col))
# Recusrive method to create the ser... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Names():
Chemical_Elemnts = ["Yb", "Pb", "Ca", "Ti", "Mo", "Sn", "Cd", "Ag", "La",
"Cs", "W", "Sb", "Ta", "V", "Fe", "Bi", "Ce", "Nb",
"Cu", "I", "B", "Te", "Al", "Zr", "Gd", "Na", "Ga",
"Cl"... |
# Build a Boolean mask to filter out all the 'LAX' departure flights: mask
mask = df['Destination Airport'] == 'LAX'
# Use the mask to subset the data: la
la = df[mask]
# Combine two columns of data to create a datetime series: times_tz_none
times_tz_none = pd.to_datetime( la['Date (MM/DD/YYYY)'] + ' ' + la['Wheels-... |
"""
Write a Python program to find the second most repeated word in a given string.
"""
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
counts_x = sorted(counts.items(), key=l... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 10:52:04 2019
@author: Nihar
"""
marks=int(input("Enter Marks: "))
if marks >=70:
print("Congrats!Distinction for you")
elif 70 > marks >= 60:
print("Well done! First Class !!")
elif 60 > marks >= 40:
print("You got Second Class")
else:
... |
'''
Given an unsorted array of integers, find the number of longest increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subs... |
# python3
def solve(n, v):
#if sum(v) % 3 != 0:
# return False
res = []
values = []
s = sum(v)//3
for i in range(2**n):
bit = [0 for i in range(n)]
k = i
p = n-1
while k!=0:
bit[p] = (k%2)
k = k//2
p -= 1
... |
# create string and dictionary
lines = ""
occurrences = {}
# prompt for lines
line = input("Enter line: ")
while line:
lines += line + " "
line = input("Enter line: ")
# iterate through each color and store count
for word in set(lines.split()):
occurrences[word] = lines.split().count(word)
# print result... |
"""
Demonstrates swapping the values of two variables
"""
number1 = 65 #Declares a variable named number1 and assigns it the value 65
number2 = 27 #Declares a variable named number2 and assigns it the value 27
temp_number = number1 #Copies the reference of n... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
... |
num = int(input('Digite um número: '))
total = 0
for c in range(1, num + 1):
if num % c == 0:
total += 1
print('{}'.format(c), end=' ')
print('\nO número {} foi divisivel {} vezes'.format(num, total))
if total == 2:
print('É número {} é primo'.format(num))
else:
print('É número {} é composto'.fo... |
# python3
n, m = map(int, input().split())
clauses = [ list(map(int, input().split())) for i in range(m) ]
# This solution tries all possible 2^n variable assignments.
# It is too slow to pass the problem.
# Implement a more efficient algorithm here.
def isSatisfiable():
for mask in range(1<<n):
result = [... |
"""
sentence span mapping to special concepts in amr like name,date-entity,etc.
"""
class Span(object):
def __init__(self,start,end,words,entity_tag):
self.start = start
self.end = end
self.entity_tag = entity_tag
self.words = words
def set_entity_tag(self,entity_tag):
... |
class FlPosition:
def __init__(self, position_data, column_labels, timestamps, conversion):
self.position_data = position_data
self.column_labels = column_labels
self.timestamps = timestamps
self.conversion = conversion
|
class Recipe:
def __init__(self, name, ingredients, yt_link):
self.name = name
self.ingredients = ingredients
self.yt_link = yt_link
self.similarity = 0
self.leftChild = None
self.rightChild = None
class BinarySearchTree:
def __init__(self):
self.root... |
#!/usr/bin/env python3
"""
Poisson distribution
"""
class Poisson:
"""
Class to represent a Poisson distribution
"""
e = 2.7182818285
def __init__(self, data=None, lambtha=1.):
"""
Poisson Constructor
data is a list of the data to be used to estimate the distribution
... |
########################################################################
# Useful classes for implementing quantum heterostructures behavior #
# author: Thiago Melo #
# creation: 2018-11-09 #
# update: 2018-11-09 ... |
def deco(func):
def temp():
print("-"*60)
func()
print("-"*60)
return temp
@deco
def print_h1():
print("body")
def main():
print_h1()
if __name__ == "__main__":
main() |
# linear search on sorted list
def search(L, e):
for i in range(len(L)):
if L[i] == e:
return True
if L[i] > e: # sorted
return False
return False
# O(n) for the loop and O(1) for the lookup to test if e == L[i]
# overall complexity is O(n) where n is len(L) |
def CheckPypi(auth, project):
projectInfo = auth.GetJson("https://pypi.org/pypi/" + project + "/json")
return projectInfo["info"]["version"]
|
#!/usr/bin/env python3
IMG_FOLDER = '/home/tho/.scripts/ws_imgs'
WS_CONFIG = [
{
#'name': '',
'img': ['firefox.png', 'firefox.png'],
'num': 1,
'key': 1,
'static': False
},
{
#'name': '2',
'img': ['moon.png', 'moon.png'],
'num': 2,
'k... |
# Exercise 3:
#
# In this exercise we will create a program that identifies whether someone can
# enter a super secret club.
# Below are the people that are allowed in the club.
# If your name is Bill Gates, Steve Jobs or Jesus, you should be allowed in the
# club.
# If your name is not one of the above, but your name ... |
N, K = [int(a) for a in input().split()]
h = []
for _ in range(N):
h.append(int(input()))
sortedh = sorted(h)
min_ = 1e9
for i in range(N-K+1):
diff = sortedh[i+K-1] - sortedh[i]
min_ = min(min_, diff)
print(min_)
|
# slow version dp
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
sLength, pLength = len(s), len(p)
matrix = [[False] * (pLength+1) for i in range(sLength+1)]
matrix[0][0] = True
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by AKM_FAN@163.com on 2017/11/6
if __name__ == '__main__':
pass |
# -*- coding: utf-8 -*-
"""
Created on Tue May 19 08:27:42 2020
@author: Shivadhar SIngh
"""
def histogram(seq):
count = dict()
for elem in seq:
if elem not in count:
count[elem] = 1
else:
count[elem] += 1
return count |
"""Errors raised by mailmerge."""
class MailmergeError(Exception):
"""Top level exception raised by mailmerge functions."""
class MailmergeRateLimitError(MailmergeError):
"""Reuse to send message because rate limit exceeded."""
|
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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 ... |
Dakota = {"Tipo": "Perro", "Dueño": "Miguel", "Descripcion": "Esta gorda y bien bonita"}
Momo = {"Tipo": "Lemur", "Dueño": "Aang", "Descripcion": "No estoy seguro que sea un lemur, pero vuela"}
Rufus = {"Tipo": "Nutria", "Dueño": "Ron", "Descripcion": "Es pequeño, feo y muestra inteligencia"}
Chimuelo = {"Tipo": "Drago... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
class Friends(object):
def __init__(self, connections):
super(Friends, self).__init__()
self._data = {}
self._add_connections(connections)
def add(self, connection):
is_exists = self.is_exists(connection)
self._add_c... |
def table_service(*args):
text, client, current_channel = args
if text.lower().startswith("tables"):
number = int(text.split()[-1])
result = ""
for i in range(1, 11):
result += f"{number} X {i} = {number*i}\n"
client.chat_postMessage(channel=current_channel, text=resu... |
class Parameters:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def info(self):
print("The parameters, and data-type are: ")
for key,values in self.__dict__.items():
print("{} = {}, {}\n".format(key, values, type(values))) |
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
max_val = max(arr)
while(max_val in arr):
arr.remove(max_val)
print(max(arr)) |
CHECKSUM_TAG = 'CHECKSUM_TAG'
AVSCAN_TAG = 'AVSCAN_TAG'
MAILER_TAG = 'MAILER_TAG'
UNPACK_TAG = 'UNPACK_TAG'
ARKADE5_TAG = 'ARKADE5_TAG'
ARTIFACT_WRITER_TAG = 'ARTIFACT_WRITER_TAG'
class ContainerTagParams:
"""
Parameter class containing dictionaries of {parameter names: image tags} for containers used during ... |
def miFuncion():
print("Mi primera función")
miFuncion()
def imprimirDato(dato):
print(dato)
imprimirDato("a")
def imprimirDatos(*datos):
print(datos)
imprimirDatos("Uno", "Dos", "Tres")
def nombreCompleto(apellido, nombre):
print(nombre, apellido)
nombreCompleto(nombre="Emmanuelle", apell... |
def solution(A):
curSlice = float('-inf')
maxSlice = float('-inf')
for num in A:
curSlice = max(num, curSlice+num)
maxSlice = max(curSlice, maxSlice)
return maxSlice
if __name__ == '__main__':
print(solution([3,2,-6,4,0]))
print(solution([-10]))
|
# -*- coding: utf-8 -*-
"""
File Name: countDigitOne.py
Author : jynnezhang
Date: 2020/4/29 7:38 下午
Description:
从1到n,所有数字含有1的个数
https://leetcode-cn.com/problems/number-of-digit-one/
"""
class Solution:
def countDigitOne(self, n: int) -> int:
number = 0
for i in range(1, n+1):
... |
class Solution:
def XXX(self, head: ListNode) -> ListNode:
o = head
p = None
while head is not None:
if p is not None and head.val == p.val:
p.next = head.next
else:
p = head
head = head.next
return o
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
living
"""
__version__ = '4.0'
content = {
'boymechanic_ankeiler': ['Having fun <#,odd_action#> while <#odd_action#>.'],
'odd_action': [
'<#odd_verbs_gerund#> <#article,odd_descriptor#> <#odd_noun#>',
'<#odd_verbs_gerund#> <#article,odd_noun... |
def taxicab_distance(a, b):
"""
Returns the Manhattan distance of the given points
"""
n = len(a)
d = 0
for i in range(n):
d += abs(a[i] - b[i])
return d
PERIOD = 2 # the period of the sequence
def sequ():
"""
Generates the sequence corresponding to the number of steps to... |
#!/usr/bin/env python3
########################################################################################################################
##### INFORMATION ######################################################################################################
### @PROJECT_NAME: SPLAT: Speech Processing and Lingu... |
# coding=utf-8
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# DP
# f[x][y] = true 表示 s[x:y+1]为回文
# 初始化
left = 0
right = 1
length = len(s)
f = [[False for j in range(length)] for i in... |
def start():
return
def stop():
return
def apply_command(self, c, e, command, arguments):
pass
def on_welcome(self, c, e):
pass
def on_invite(self, c, e):
pass
def on_join(self, c, e):
pass
def on_namreply(self, c, e):
pass
def on_pubmsg(self, c, e):
pass
def on_privmsg(s... |
# Code Challenge 13
open_list = ["[", "{", "("]
close_list = ["]", "}", ")"]
def validate_brackets(str):
stack=[]
for i in str:
if i in open_list:
stack.append(i)
elif i in close_list:
x = close_list.index(i)
if ((len(stack) > 0) ... |
tail = input()
body = input()
head = input()
meerkat = [tail, body, head]
meerkat.reverse()
print(meerkat)
|
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
a<995
b<996
c<997
They tell us there is only one, so we only need to test for existe... |
num = int(input())
for i in range(num):
s = input()
t = input()
p = input()
|
graus = [0,10,20,40,100]
for T in graus:
print("A temperatura é: ",T)
print("a Lista de temperaturas tem ", len(graus), 'elementos')
|
def peopleneeded(Smax, S):
needed = 0
for s in range(Smax+1):
if sum(S[:s+1])<s+1:
needed += s+1-sum(S[:s+1])
S[s] += s+1-sum(S[:s+1])
return needed
def get_output(instance):
inputdata = open(instance + ".in", 'r')
output = open(instance+ ".out", 'w')
T = int(inp... |
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
degree = 1 # outDegree (children) - inDegree (parent)
for node in preorder.split(','):
degree -= 1
if degree < 0:
return False
if node != '#':
degree += 2
return degree == 0
|
"""
Tests as were previously formatted. Leaving here in case I want to revert to more disparate testing.
"""
def test_vehicle_info(client):
mock_file = 'mock_vehicleinfo.json'
output_file = 'output_vehicleinfo.json'
mock_response, correct_output = mocktest_setup(mock_file, output_file)
with patch('server.request... |
'''
字符大小写排序
中文English
给定一个只包含字母的字符串,按照先小写字母后大写字母的顺序进行排序。
一招partiton 走天下
'''
|
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# 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... |
"""
Space : O(n)
Time : O(n)
"""
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
if len(nums) == 0:
return 0
ans = 0
leng = len(nums)-1
one, two = [0] * leng, [0] * leng
# 1st ite... |
class ZoneFilter:
def __init__(self, rules):
self.rules = rules
def filter(self, record):
# TODO Dummy implementation
return [record] |
class HyperparameterGrid():
def __init__(self):
DEFAULT_HYPERPARAMETER_GRID = {
'lr': {
'C': [0.001, 0.01, 0.1, 1],
'penalty': ['l1', 'l2'],
'solver': ['liblinear'],
'intercept_scaling': [1, 1000],
'max_iter': [1000... |
def uniqueElements(myList):
uniqList = []
for _var in myList:
if _var not in uniqList:
uniqList.append(_var)
else:
return "Not Unique"
return "Unique"
print(uniqueElements([2,99,99,12,3,11,223])) |
def magic_square(square):
size_square = len(square)
is_magic = True
wanted_sum = 0
for index in range(0, size_square):
wanted_sum += square[0][index]
for row in range(0, size_square):
current_sum = 0
for col in range(0, size_square):
current_sum += square[row][col]
if current_sum != wanted_sum:
... |
def f(x):
y=1
x=x+y
return x
x=3
y=2
z=f(x)
print("x="+str(x))
print("y="+str(y))
print("z="+str(z)) |
__all__ = [
"mock_generation_data_frame",
"test_get_monthly_net_generation",
"test_rate_limit",
"test_retry",
]
|
test = { 'name': 'q1_2',
'points': 1,
'suites': [ { 'cases': [ {'code': ">>> assert trending_vids.shape[0] == '40379'\n", 'hidden': False, 'locked': False},
{'code': ">>> assert trending_vids.iloc[0, 0] == '25231'\n", 'hidden': False, 'locked': False},
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 6 10:35:39 2021
@author: ELCOT
"""
"""
Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[... |
class Income:
def __init__(self):
self.tranId = ""
self.tradeId = ""
self.symbol = ""
self.incomeType = ""
self.income = 0.0
self.asset = ""
self.time = 0
@staticmethod
def json_parse(json_data):
result = Income()
re... |
def game(input,max_turns):
memory = {}
turncounter = 1
most_recent_number = int(input[-1])
for i in range(len(input)):
memory[int(input[i])] = [turncounter,-1]
turncounter += 1
while turncounter <= max_turns:
if memory[most_recent_number][1] == -1:
most_r... |
# Copyright 2020 Uber Technologies, Inc.
#
# 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 ... |
def is_krampus(n):
p = str(n**2)
l_p = len(p)
for i in range(1, l_p - 1):
p_1 = int(p[:i])
p_2 = int(p[i:])
if p_1 and p_2 and p_1 + p_2 == n:
return True
return False
def test_is_krampus():
assert is_krampus(45)
assert not is_krampus(100)
if __name__ ==... |
def adjacentElementsProduct(inputArray):
first, second = 0, 1
lp = inputArray[first]*inputArray[second]
for index in range(2, len(inputArray)):
first = second
second = index
new_lp = inputArray[first]*inputArray[second]
if new_lp > lp:
lp = new_lp
... |
def y():
pass
def x():
y()
for i in range(10):
x()
|
INSTALLED_APPS = (
'vkontakte_api',
'vkontakte_places',
'vkontakte_users',
'vkontakte_groups',
'vkontakte_comments',
'm2m_history',
)
SOCIAL_API_TOKENS_STORAGES = []
|
#
# PySNMP MIB module AcAlarm (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AcAlarm
# Produced by pysmi-0.3.4 at Wed May 1 11:33:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... |
"""Set up dependency to tensorflow pip package."""
def _find_tf_include_path(repo_ctx):
exec_result = repo_ctx.execute(
[
"python3",
"-c",
"import tensorflow as tf; import sys; " +
"sys.stdout.write(tf.sysconfig.get_include())",
],
quiet = Tru... |
'''
Processing of data via :py:mod:`.json_io`.
Utilities for Excel conversion in :py:mod:`.convert` and :py:mod:`.service_sheet`.
Example code in :py:mod:`.cli_examples` and :py:mod:`.plots`.
'''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.