content stringlengths 7 1.05M |
|---|
alphabets=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#function to apply the algorithm
def encode_decode(start_text, shift_amount, cipher_direction):
... |
#
# @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
temp = ListNode(0)
temp.nex... |
class AsyncBaseCache:
def __init__(self, location, params, loop=None):
self._params = params
self._location = location
self._loop = loop
self._key_prefix = self._params.get('PREFIX', '')
async def init(self, *args, **kwargs):
return self
async def get(self, key: st... |
def Read(filename):
file = open("lists.txt",'r')
line = file.readlines()
l=[]
for i in range(len(line)):
p = line[i].replace("\n","")
q = p.split(',')
l.append(q)
for j in range(len(l)): # changing price & quantity into int data type
for k in range(len(l[j])... |
peso = float(input('Digite o seu peso: '))
altura = float(input('Digite a sua altura: '))
imc = peso / altura ** 2
print('O seu IMC está em {:.2f}'.format(imc))
if imc < 18.5:
print('Você está abaixo do peso.')
elif imc < 25:
print('Você está no peso ideal.')
elif imc < 30:
print('Você está com sobrepeso.')... |
# SUMPOS
for i in range(int(input())):
x,y,z=map(int,input().split())
if((x+y==z)or(x+z==y)or(y+z==x)):
print("YES")
else:
print("NO") |
#!/usr/bin/env python3
class SpotMicro:
_spanish_bark = "guau-guau"
_japanese_bark = "wan-wan"
_german_bark = "wuff-wuff"
_english_bark = "woof-woof"
def bark_in_spanish(self):
return self._spanish_bark
def bark_in_japanese(self):
return self._japanese_bark
def bark_in_g... |
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
... |
MISSING_DATAGRABBER = "Either *data_grabber* or *base_dir* inputs must be provided to {object_name} object's instansiation."
MUTUALLY_EXCLUSIVE = """Inputs {in1} and {in2} are mutually exclusive"""
BASE_DIR_AND_PARTICIPANT_REQUIRED = """If derivatives is not provided, base_dir and participant_label are required"""
|
def greet_user():
"""显示简单的问候语"""
print("Hello!")
greet_user()
def greet_user(username):
"""显示简单的问候语"""
print("Hello" + username.title() + "!")
greet_user('jen')
|
# For the code which builds PDFs we need to give it a directory where
# it can find the custom font.
FONT_DIRECTORY = '/usr/share/fonts/TTF'
# Which accounts are sending approval requests to managers via e-mail.
SENDING_APPROVAL_MANAGERS = {
"BF": True
}
# Which accounts are sending approval requests via e-mail.
S... |
def can_sum_basic(target, numbers):
if target == 0:
return True
if target < 0:
return False
for i in numbers:
reminder = target - i
if can_sum_basic(reminder, numbers):
return True
return False
def can_sum_memo(target, numbers, memo=dict()):
if targ... |
def ask_until_y_or_n(question):
var = ''
while not var in ['Y', 'y', 'N', 'n', 0, 1]:
var = input(question + ' (Y/N) ')
return var in ['y', 'Y', 1]
def delete_duplicate(list):
seen = set()
seen_add = seen.add
return [x for x in list if not (x in seen or seen_add(x))]
def delete_non_nu... |
def solve():
n = int(input())
a = list(map(int,input().split()))
s = int(input())
limit = 1 << n
subset = 0
flag = True
for mask in range(limit):
subset = 0
for i in range(n):
f = 1 << i
if f&mask:
subset += a[i]
if subset =... |
# -*- coding: utf-8 -*-
""" Project
@author: Michael Howden (michael@sahanafoundation.org)
@date-created: 2010-08-25
Project Management
"""
prefix = request.controller
resourcename = request.function
response.menu_options = [
[T("Home"), False, URL(r=request, f="index")],
[T("Gap... |
# 用Java/C/C++/Python语言之一定义栈的数据结构,
# 并在该类型中实现一个能够得到栈的最小元素的getMin和最大元素的getMax函数。
# 要求在该栈中,调用getMin、getMax, push及pop的时间复杂度都是O(1)。
class StackNode:
def __init__(self, i, min, max):
self.i = i
self.min = min
self.max = max
class Stack:
def __init__(self):
self.elements = []
d... |
a = 5 # 5 is an object
b = {'x': 5, 'y': 3} # dicts are objects
c = "hello" # strings are objects too
d = c # two variables sharing an object
e = c.lower() # should generate a new object
f = 8 * b['y'] - 19 # what happens here?
for obj in (a, b, b['x'], b['y']... |
class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
return 0
preMax = 0
curMax = nums[0]
idx = 1
while idx < len(nums):
preMax, curMax = curMax, max(preMax + nums[idx], curMax)
idx += 1
return max(preMax, curMax)
... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# iterate over list take the target for comparison
# store the index in an output array
# store the diff in another variable
# iterate over the other elements and check if the diff is there in the given list... |
'''
Clase que modela la entidad "Automovil"
'''
class Automobile:
def __init__(self, id, marca, modelo, año, version):
self.__id=id
self.__marca=marca
self.__modelo=modelo
self.__año=año
self.__version=version
def get_automobile(self):
data = {"id":self.__id,... |
# This data was taken from:
# https://github.com/fivethirtyeight/data/blob/master/hate-crimes/hate_crimes.csv
#
# Data info:
# Index | Attribute Name | Details
# ---------------------------------------------------------------------------------------------------
# 0 | state ... |
# Created by MechAviv
# [Lilin] | [1202000]
# Snow Island : Ice Cave
if "clear" not in sm.getQuestEx(21019, "helper"):
sm.setSpeakerID(1202000)
sm.flipSpeaker()
sm.sendNext("You've finally awoken...!")
sm.setSpeakerID(1202000)
sm.setPlayerAsSpeaker()
sm.sendSay("And you are...?")
sm.se... |
def compute_likelihood_normal(x, mean_val, standard_dev_val):
""" Computes the log-likelihood values given a observed data sample x, and
potential mean and variance values for a normal distribution
Args:
x (ndarray): 1-D array with all the observed data
mean_val (scalar): value of mean for which t... |
class WWSHCError(BaseException): pass
class WWSHCNotExistingError(WWSHCError): pass
class NoSuchGroup(WWSHCNotExistingError): pass
class NoSuchClass(WWSHCNotExistingError): pass
class NoSuchUser(WWSHCNotExistingError): pass
class AlreadyInContacts(WWSHCError): pass
|
# -*- coding:utf-8 -*-
def max_subarray_sum(arr, *args):
"""最大子数组和问题。给定一个数组,求最大子数组的和。
Args:
arr(list): 给定数组
args(tuple): (left, right)数组第一个元素下标和数组最后一个元素下标
Returns:
max_sum(int): 最大子数组和
"""
assert len(args) == 0 or len(args) == 2
if len(args) == 0:
return max_s... |
"""
Terrarium Library
The pallete module contains visualization parameters
"""
# Sentinel-2 L2A RGB Visualization Parameters
S2TRUECOLOR = {
'min': 0,
'max': 255,
'bands': ['TCI_R', 'TCI_G', 'TCI_B']
}
# NDVI color palette
ndvipalette = [
'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718',
... |
# -*- 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... |
class CModel_robot_input():
def __init__(self):
self.gACT = 0
self.gGTO = 0
self.gSTA = 0
self.gOBJ = 0
self.gFLT = 0
self.gPR = 0
self.gPO = 0
self.gCU = 0
|
# -*- coding: utf-8 -*-
# Ingestion service: create a metaproject (tag) with user-defined name in given space
def process(transaction, parameters, tableBuilder):
"""Create a project with user-defined name in given space.
"""
# Prepare the return table
tableBuilder.addHeader("success")
tableBuilde... |
#!/usr/bin/python
DIR = "data_tmp/"
FILES = []
FILES.append("02_attk1_avg20_test")
FILES.append("02_attk1_avg40_test")
FILES.append("02_attk1_avg50_test")
FILES.append("02_attk1_avg60_test")
FILES.append("02_attk1_avg80_test")
FILES.append("03_attk1_opt20_test")
FILES.append("03_attk1_opt40_test")
FILES.append("03_a... |
def coord():
i = mc.ls(sl=1, fl=1)
cp = []
for j in i:
val = tuple(mc.xform(j, q=1, t=1, ws=True))
cp.append(val)
print('___________________________\n')
cp = [tuple([round(x/2, 3) for x in j]) for j in cp]
cp = str(cp)
cp = cp.replace('.0)', ')')
cp = cp.replace('.0,', ',... |
# Copyright 2022 The Magma Authors.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARR... |
def tribonacci(n):
if n < 4:
return 1
return tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3)
def tallest_player(nba_player_data):
list = []
max_pies, max_pulgadas = [0,0]
for key, value in nba_player_data.items():
pies, pulgadas = value[3].split('-')
if(int(pies) > ma... |
# -*- coding: utf-8 -*-
"""
This package contains all the knowledge compilation to be used by the
interpreter, represented as abstraction patterns.
"""
|
"""Provide exception classes"""
class PipenException(Exception):
"""Base exception class for pipen"""
class PipenSetDataError(PipenException, ValueError):
"""When trying to set input data to processes with input_data already set
using Pipen.set_data()."""
class ProcInputTypeError(PipenException, TypeE... |
"""
PASSENGERS
"""
numPassengers = 4240
passenger_arriving = (
(6, 15, 5, 5, 5, 0, 5, 11, 6, 6, 3, 0), # 0
(8, 9, 4, 8, 4, 0, 10, 5, 10, 3, 4, 0), # 1
(2, 12, 9, 1, 2, 0, 12, 8, 10, 7, 3, 0), # 2
(6, 9, 9, 2, 3, 0, 12, 14, 4, 4, 6, 0), # 3
(9, 11, 16, 5, 2, 0, 7, 9, 7, 3, 2, 0), # 4
(3, 9, 8, 8, 2, 0, 9, ... |
a=list(map(int,input().split()))
n=len(a)
lo=0
h=1
prod=0
for i in range(0,n):
m=1
for j in range(i,n):
m=m*a[j]
prod=max(prod,m)
#print(prod)
print(prod)
|
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd_v1(self, head: ListNode, n: int) -> ListNode:
'''
传统思路:
先遍历一遍,统计数量
然后第二遍... |
# Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
#OBS: Os Números Primos são números naturais maiores do que 1 que possuem somente dois divisores, ou seja,
# são divisíveis por 1 e por ele mesmo. 1!= PRIMO.
#Código da 'Interface Gráfica'
print('\033[1;4;35m', '=*'*10, 'NÚMEROS PRI... |
AUTHOR = 'Nathan Shafer'
SITENAME = 'Lotechnica'
SITESUBTITLE = "Technical writings by Nathan Shafer"
SITEURL = 'https://blog.lotech.org'
PATH = 'content'
STATIC_PATHS = ['images', 'static']
STATIC_EXCLUDES = ['.sass-cache']
AUTHOR_SAVE_AS = ''
USE_FOLDER_AS_CATEGORY = True
# Locale settings
TIMEZONE = 'America/Phoe... |
# 19. Write a program in Python to enter length in centimeter and convert it into meter and kilometer.
len_cm=int(input("Enter length in centimeter: "))
len_m=len_cm/100
len_km=len_cm/100000
print("Length in meter= ",len_m,"\nLength in kilometer= ",len_km)
|
#Binary Search Tree
#BST OPERATIONS
#INSERT --> FIND --> DELETE-->GET SIZE -->TRAVERSALS
#BST INSERT
#START AT ROOT
#ALWAYS INSERT NODE AS LEAF
#BST FIND
#START AT ROOT
#RETURN DATA IF FOUND :
# ELSE RETURN FALSE
#DELETE
#3 POSSIBLE CASES
#LEAF NODE
#1 CHILD
#2 CHILDR... |
class ParkingPermitBaseException(Exception):
pass
class PermitLimitExceeded(ParkingPermitBaseException):
pass
class PriceError(ParkingPermitBaseException):
pass
class InvalidUserZone(ParkingPermitBaseException):
pass
class InvalidContractType(ParkingPermitBaseException):
pass
class NonDraf... |
# Finding duplicate articles
# this will print out articles that have
# the same titles. for each match, it will print 2x -> 1,5 & 5,1
def dedupe(n):
a = d[n]
for key,value in d.items():
if a == value and key != n:
print(f'{key} <-> {n}')
articles = u.articles.all()
d = {}
for a in articl... |
def for_five():
"""We are creating user defined function with numerical pattern of five with "*" symbol"""
row=7
col=5
for i in range(row):
for j in range(col):
if i==0 or j==0 and i<4 or ((i==3 or i==6) and j%4!=0) or j==4 and (i>3 and i<6) or i==5 and j==0:
p... |
# https://leetcode-cn.com/explore/interview/card/bytedance/242/string/1016/
# 字符串的排列
class Solution:
def calindex(self, s1, s2):
return ord(s1) - ord(s2)
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2): return False
# 采用数组来记录... |
fib = [0,1]
i = 1
print(fib[0])
while fib[i]<=842040:
print(fib[i])
i +=1
fib.append(fib[i-1] + fib[i-2]) |
"""
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:
Choosing any x with 0 < x < n and n % x == 0.
Replacing the number n on the chalkboard with n - x.
Also, if a player cannot make a mo... |
############################
# General Settings
############################
# crop_size: crop size for the input image, center crop
crop_size = 178
# image_size: input/output image resolution, test output is 2x
image_size = 64
# Establish convention for real and fake probability labels during training
real_prob = 1... |
text_errors=["error","Error","Failed","failed"]
purple_text=[" ____",
" / _ | Frida 15.0.13 - A world-class dynamic instrumentation toolkit",
" | (_| |",
" > _ | Commands:",
" /_/ |_| help -> Displays the help system",
#" . . . . object? -> Display information about 'obj... |
def convert_dict_2_list(data):
"""
:param data: a dict of goods, e.g:{
1: {"name": "洗发水", "price": 22},
2: {"name": "牙膏", "price": 15},
},
:return: a list of goods , e.g:[{"id": 1, "name": "洗发水", "price": 22}]
"""
goods = []
for _ in data:
goods.append(... |
'''
Created on Feb 12, 2019
@author: jcorley
'''
class Recipe:
'''
Stores basic information for a recipe.
'''
def __init__(self, name, categories, timeToCook, timeToPrep, ingredients, instructions, servings):
'''
Create a new recipe with the provided information.
... |
x = float(input())
if x >= 0 and x <= 25:
print("Intervalo [0,25]")
elif x > 25 and x <= 50:
print("Intervalo (25,50]")
elif x > 50 and x <= 75:
print("Intervalo (50,75]")
elif x > 75 and x <= 100:
print("Intervalo (75,100]")
else:
print("Fora de intervalo")
|
# Hidden Street : Destroyed Temple of Time Entrance (927020000) | Used in Luminous' Intro
PHANTOM = 2159353
sm.lockInGameUI(True)
sm.curNodeEventEnd(True)
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.sendNext("The heavens have set the perfect stage for our final confrontation.")
sm.sendDelay(500)
sm.f... |
class VidscraperError(Exception):
"""Base error for :mod:`vidscraper`."""
pass
class UnhandledVideo(VidscraperError):
"""
Raised by :class:`.VideoLoader`\ s and :doc:`suites </api/suites>` if a
given video can't be handled.
"""
pass
class UnhandledFeed(VidscraperError):
"""
Rais... |
# Problem: Counting the number of negative numbers.
# You are given a 2-dimensional array with integers.
# Example Input:
# [[-4, -3, -1, 1],
# [-2, -2, 1, 2],
# [-1, 1, 2, 3],
# [ 1, 2, 4, 5]]
# Write a function, count_negatives(input), which finds and returns the number of negative integers in th array.
# ... |
# LeetCode 824. Goat Latin `E`
# acc | 99% | 14'
# A~0h19
class Solution:
def toGoatLatin(self, S: str) -> str:
vowels = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
S = [w+"ma"+"a"*(i+1) if w[0] in vowels else w[1:] +
w[0]+"ma"+"a"*(i+1) for i, w in enumerate(S.split())]
... |
# Refaça o desafio 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.
número = int(input('Digite um número: '))
print(f'\n===== TABUADA de {número} =====\n')
for tabuada in range(1, 11):
print(f'{número} x {tabuada:>2} = {número * tabuada}')
|
#!c:\Python36\python.exe
print ("Content-Type: text/html") # Header
print ()
print ("<html><head><title>Server test</title></head>")
print ("<b>Hello</b>")
print ("</html>") |
class DummyTransport(object):
def __init__(self, *args, **kargs):
self.called_count = 0
def perform_request(self, method, url, params=None, body=None):
self.called_count += 1
self.url = url
self.params = params
self.body = body
class DummyTracer(object):
def __init... |
# coding=utf-8
"""Day 018 - String II - Useful functions
This example covers a bunch of great String functions.
"""
def run():
# These functions below are not in-place. The value of the variables does not change.
# The first letter of the first word to up
print("marcos".capitalize())
# >>> 'Marco... |
# coding: utf-8
#########################################################################
# 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> #
# author yeeku.H.lee kongyeeku@163.com #
# #
# version... |
""" This file changes the global settings logic.
Do not do any changes here, unless you know what you
are doing.
"""
# Mode standard is 'f'
MODE='f'
FILE_TARGET='your file.ext' # Target file, where the software writes the buffer.
LOG=True
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
stack = []
for i in range(n):
x = [int(i) for i in input().split(' ')]
if x[0]==1:
if stack:
m = max(stack[-1],x[1])
stack.append(m)
else:
stack.append(x[1])
elif x... |
# Harmonica notes and holes.
dic_notes = {
'E3': 164.81,
'F3': 174.61,
'F#3': 185.00,
'G3': 196.00,
'G#3': 207.65,
'A3': 220.00,
'A#3': 233.08,
'B3': 246.94,
'C4': 261.63,
'C#4': 277.18,
'D4': 293.66,
'D#4': 311.13,
'E4': 329.63,
'F4': 349.23,
'F#4': 369.99,
'G4': 392.00,
'G#4': 415.30,
'A4': 440.00,
'A#4': 466.16,... |
"""DEPICTION initialization module."""
name = 'depiction'
__version__ = '0.0.1'
|
'''stub for savings.py exercise.'''
def savingGrowth(deposit, interestPercentage, goal):
'''Print the account balance for each year until it reaches
or passes the goal.
>>> savingGrowth(100, 8.0, 125)
Year 0: $100.00
Year 1: $108.00
Year 2: $116.64
Year 3: $125.97
'''
# code here!
... |
def transformacion(c):
t = (c * (9/5))+32
print(t)
transformacion(100)
|
#
# PySNMP MIB module CT-FASTPATH-DHCPSERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CT-FASTPATH-DHCPSERVER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:13:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
'''
Backward and forward
====================
The sign outside reads: Name no one man.
"Escape. We must escape." Staring at the locked door of his cage, Beta Rabbit, spy and brilliant mathematician, has a revelation. "Of course! Name no one man - it's a palindrome! Palindromes are the key to opening this lock!"
To ... |
def upload_file_to_bucket(client, file, bucket):
client.upload_file(file, bucket)
def get_objecturls_from_bucket(client, bucket):
"""
params:
- bucket: s3 bucket with target contents
- client: initialized s3 client object
"""
next_token = ''
urls = []
base_kwargs = {
'Buck... |
class Solution:
def findMaxForm(self, strs, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
strs.sort(key=len)
dic = {}
dic[(0, 0)] = 0
for s in strs:
zeroes = s.count('0')
ones = len(s... |
class CalcEvent():
__handlers = None
def __init__(self):
self.__handlers = []
def add_handler(self, handler):
self.__handlers.append(handler)
def button_clicked(self, text: str):
for handler in self.__handlers:
handler(text) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
for n in range (2,25):
for i in range(2, n):
if n % i == 0:
break
else:
print(n) |
def ordena(lista):
tamanho_lista = len(lista)
for i in range(tamanho_lista - 1):
menor_visto = i
for j in range(i + 1, tamanho_lista):
if lista[j] < lista[menor_visto]:
menor_visto = j
lista[i], lista[menor_visto] = lista[menor_visto], lista[i]
return lis... |
print('Insira o valor de 3 angulos de um triangulo: ')
a1 = float(input('Valor 1: '))
a2 = float(input('Valor 2: '))
a3 = float(input('Valor 3: '))
if a1 + a2 + a3 != 180:
print('Os valores não formam um triangulo. "A soma dos angulos internos de um triangulo sempre é igual a 180."')
elif a1 == 90 or a2 == 90 or a3... |
f = open('raven.txt', 'r')
# create an empty dictionary
count = {}
for line in f:
for word in line.split():
# remove punctuation
word = word.replace('_', '').replace('"', '').replace(',', '').replace('.', '')
word = word.replace('-', '').replace('?', '').replace('!', '').replace("'", "")
... |
def whitenoise_add_middleware(MIDDLEWARE):
insert_after = "django.middleware.security.SecurityMiddleware"
index = 0
MIDDLEWARE = list(MIDDLEWARE)
if insert_after in MIDDLEWARE:
index = MIDDLEWARE.index(insert_after) + 1
MIDDLEWARE.insert(index, "whitenoise.middleware.WhiteNoiseMiddleware")
... |
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository")
load("@build_stack_rules_proto//:deps.bzl",
"bazel_skylib",
"build_bazel_rules_swift"
)
load("//swift:zlib.bzl", "ZLIB_BUILD_FILE_CONTENT")
load("//swift:grpc_swift.bzl", "GRPC_SWIFT_BUILD_FILE_CONTENT")
load("//swift:swift_protobuf.bzl",... |
# This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def removeDuplicatesFromLinkedList(linkedList):
# Write your code here.
# Have two pointers
# 1. Current Node
# 2. Next Node
# Check if the current node is equal to th... |
def sumDigits(num, base=10):
return sum([int(x, base) for x in list(str(num))])
print(sumDigits(1))
print(sumDigits(12345))
print(sumDigits(123045))
print(sumDigits('fe', 16))
print(sumDigits("f0e", 16))
|
# Problem: Rotate Image
# Difficulty: Medium
# Category: Array
# Leetcode 48: https://leetcode.com/problems/rotate-image/description/
# Description:
"""
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have... |
def maxSubArraySum(arr,N):
maxm_sum=arr[0]
curr_sum=0
for ele in arr:
curr_sum+=ele
if curr_sum>0:
if curr_sum>maxm_sum:
maxm_sum=curr_sum
else:
if curr_sum>maxm_sum:
maxm_sum=curr_sum
curr... |
__all__ = ['OrderLog', 'OrderLogTruncated']
class OrderLog:
def __init__(self):
self._key = None
self._data = None
def get_key(self):
return self._key
def set_key(self, key):
if not isinstance(key, int):
raise ValueError('Date must be in int format')
s... |
#coding: utf-8
''' mbinary
#######################################################################
# File : hammingDistance.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-12-17 17:36
# Description:
hamming distance is the numbe... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_23.py
@time: 2019/5/3 15:54
@desc:
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class So... |
# Constants
repo_path = '/Users/aaron/git/gittle'
repo_url = 'git@friendco.de:friendcode/gittle.git'
# RSA private key
key_file = open('/Users/aaron/git/friendcode-conf/rsa/friendcode_rsa') |
text0 = 'パトカー'
text1 = 'タクシー'
ans = ''
for i in range(len(text0)):
ans += text0[i]
ans += text1[i]
print(ans)
|
# 1.Reverse the order of the items in an array.
# Example:
# a = [1, 2, 3, 4, 5]
# Result:
# a = [5, 4, 3, 2, 1]
def reverseFunction(aList):
return aList.reverse()
a=[1,2,3,4,5]
reverseFunction(a)
print(a)
# 2. Get the number of occurrences of var b in array a.
# Example:
# a = [1, 1, ... |
class Converter():
def __init__(self):
self.alpha = [chr(k) for k in range(65,91)] #Set an array of chars going to the letter A to the Z
def calculate(self, seq, b):
if not 2 <= b <= 36: #Bases range is [2,36]
return None
else:
out = []
sequence = seq
base = b
itr = 0 #Keep track of the number o... |
#create mongoDB client
#TODO: what port is db on?????
client = MongoClient('localhost', 27017)
#get the database from mongoDB client
database = client.database
#get the tables from the database
users = database.users
#function that handles client-server connections
#creates a thread for a connected client
def cl... |
class Player():
def __init__(self):
self.points = 0
self.developmentCards = []
self.resourceCards = []
self.roads = []
self.settlements = []
self.cities = []
""" How a player picks up cards at the beginning of a turn """
def pickupResources():
return... |
"""Data Structure introduction - Stack"""
class MyStack:
"""A blueprint to implement basic stack operations"""
def __init__(self,size = 10):
"""Intialize"""
self.stack = []
self.size =size
def __str__(self):
"""Pythonic way of converting objects to string"""
return ... |
sum_of_the_squares = 0
square_of_the_sum = 0
for i in range(0,100):
sum_of_the_squares = sum_of_the_squares + (i+1)**2
square_of_the_sum = square_of_the_sum + (i+1)
print((square_of_the_sum**2) - sum_of_the_squares)
|
WEB_URL = "https://replicate.ai"
DOCS_URL = WEB_URL + "/docs"
PYTHON_REFERENCE_DOCS_URL = DOCS_URL + "/reference/python"
YAML_REFERENCE_DOCS_URL = DOCS_URL + "/reference/yaml"
REPOSITORY_VERSION = 1
HEARTBEAT_MISS_TOLERANCE = 3
EXPERIMENT_STATUS_RUNNING = "running"
EXPERIMENT_STATUS_STOPPED = "stopped"
|
class Solution:
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
if image[sr][sc] != newColor:
self.helper(image, sr, sc, newColor, im... |
demo_schema = [
{
'name': 'SUMLEV',
'type': 'STRING'
},
{
'name': 'STATE',
'type': 'STRING'
},
{
'name': 'COUNTY',
'type': 'STRING'
... |
print('Nota do aluno')
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda '))
media = float(nota1 + nota2) / 2
print('A média do aluno é:{} '.format(media))
|
"""Task class definition"""
class Task:
"""Task class, representing a task"""
def __init__(self, num, name):
self.num = num
self.name = name
def __str__(self):
return '['+self.str_num()+'] '+self.name
def str_num(self):
"""Prepends zeroes to the task id to make it a 3-... |
# https://leetcode.com/problems/check-if-word-equals-summation-of-two-words
alphabet = {
'a': '0',
'b': '1',
'c': '2',
'd': '3',
'e': '4',
'f': '5',
'g': '6',
'h': '7',
'i': '8',
'j': '9',
}
def get_numerical_value(word):
list_of_chars = []
for char in word:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.