content stringlengths 7 1.05M |
|---|
r"""
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
... |
'''
Write a Python program to parse a string to Float or Integer.
'''
varStr = input("Enter a number: ")
print("The string above was parsed an an integer", int(varStr)) |
# Compute the Factorial of a given value (n!)
# multiply all whole numbers from our chosen number
# down to 1.
# 4! = 4 * 3 * 2 * 1
# 1 * 1 = 1
# 1 * 2 = 2
# 2 * 3
# iterative approach
def fact_i(n):
# set a end point fact initial value
fact = 1
# loop from 1 to n+1 using an index
for i in range(1, ... |
def indent_dotcode(dotcode, indent):
return '\n'.join(['%s%s' % (indent, line)
for line in dotcode.split('\n')])
def sphinx_format(dotcode):
dotcode = indent_dotcode(dotcode, ' ')
warning_comment = '.. Autogenerated graphviz code. Do not edit manually.'
dotcode = "%s\n\n.. graphviz::\n\n%s" ... |
"""Small utility functions"""
def string_is_true(s: str) -> bool:
return s.lower() == 'true'
|
# -*- coding: utf-8 -*-
class BaseEndpoint:
"""
A class used to implement base functionality for Lacework API Endpoints
"""
def __init__(self,
session,
object_type,
endpoint_root="/api/v2"):
"""
:param session: An instance of the HttpS... |
# coding: UTF-8
class MyBaseException(Exception):
def __init__(self, message):
self.message = message
class FileNotExistException(MyBaseException):
def __init__(self, message=""):
MyBaseException.__init__(self, message)
class SettingException(MyBaseException):
"""
設定はしてない場合、または設定間違... |
#!/usr/bin/env python
#
# String Parser.
# file : Parser.py
# author : Tom Regan <noreply.tom.regan@gmail.com>
# since : 2011-07-28
# last modified : 2011-08-04
class BaseParser(object):
def parse(self, line):
pass
class Parser(BaseParser):
def parse(self, line):
""... |
"""Escriba un algoritmo que permita saber cuál es el día de la semana,
utilizando el siguiente método y después conviértalo a Python:
Conserve las dos últimas cifras del año.
Añada 1/4 de esta cifra, ignorando el resto: división entera.
Añada el día del mes.
Según el mes, añada el valor indicado:
Enero = 1
Febrero = 4
... |
def cal(n, data):
for x in range(1, n+1):
if (n % x == 0):
tmp = data[:x]
for y in range(x, n, x):
if data[y:y+x] != tmp:
break
if(y+x >= n):
return x
return n
n = int(input())
data = list(input())
print(ca... |
def resolve():
'''
code here
'''
N = int(input())
As = [int(item) for item in input().split()]
As.sort()
max_num = max(As)
res = 10**9 + 1
if max_num % 2 == 0:
if max_num //2 in As:
res = max_num //2
else:
for item in As:
if a... |
#!/usr/bin/python3
for i in range(1,10):
for j in range(1,10):
print("%d * %d = %d "%(j,i,i*j), end="")
print("")
|
def heapify(arr, n, i):
"""This is to max heapify
Parameters:
arr(list): List of integers
n(int): Length of list
i(int): Root element
"""
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[i] < arr[left]:
larges... |
expected_output = {
'vrf': {
'default': {
'interface': {
'GigabitEthernet0/0/0/0': {
'counters': {
'joins': 18,
'leaves': 5
},
'enable': True,
'interne... |
def XXX(self, root):
if root is None:
return 0
level = 0
stack = [root]
while stack:
level += 1 # 每下一层,层数+1
n = len(stack)
# 拿到当前层下一层全部节点到队列
for i in range(n):
if stack[i].left:
stack.append(... |
#!/usr/bin/python3
# 文件名:fibo.py
# 裴波那契(fibonacci)数列模块
def fib(n): # 定义到n的裴波那契数列
a,b = 0,1
while b < n:
print(b,end=' ')
a,b = b,a+b
print()
def fib2(n): # 返回到n的裴波那契数列
result = []
a,b = 0,1
while b < n:
result.append(b)
a,b = b,a+b
return result
|
while True:
n=int(input('ENTER A NUMBER TO CHECK DIVISIBILITY: '))
for i in range (2,n):
if n%i == 0:
print('THE ENTER NO. IS DIVISIBLE BY: ',i)
|
# SCENARIO: Calculator - Do a substraction
# GIVEN a running calculator app
type(Key.WIN + "calculator" + Key.ENTER)
wait("1471901583292.png")
# AND '5' is displayed
click("1471901439420.png")
wait("1471901563200.png")
# WHEN I click on '-', '1', '='
click("1471901612968.png")
click("1471901595751.png")
click... |
"""Tests for the module 'api_v1'."""
# TODO enable when new test(s) will be added
# from f8a_jobs.api_v1 import *
class TestApiV1Functions(object):
"""Tests for the module 'api_v1'."""
def setup_method(self, method):
"""Set up any state tied to the execution of the given method in a class."""
... |
numero = soma_dos_numeros = quantidade_numeros = 0
while numero != 999:
numero = int(input("Diga um valor: ").strip())
if numero != 999:
soma_dos_numeros += numero
quantidade_numeros += 1
print("Acabou!")
print(f"A soma dos {quantidade_numeros} números digitados foi {soma_dos_numeros}.")
|
DbName = "FantasyDraftHost.db"
tables = {
"leagues": {
"name": "Leagues",
"columnIndexes": {
"Id": 0,
"Name": 1
}
},
"playerPositions": {
"name": "PlayerPositions",
"columnIndexes": {
"Id": 0,
"PlayerId": 1,
... |
class parent:
def myMethod(self):
print("调用父类方法")
class child(parent):
def myMethod(self):
print("调用子类方法")
def __myPrivateMethod(self):
print("这个是我的私有方法")
# 调用
c = child() # 子类实例
c.myMethod() # 子类调用重写方法
super(child, c).myMethod() # 用子类对象调用父类已被覆盖的方法
# c.myPrivateMethod() # 报错,外部不能调用私有方法
|
a = [100,2,1,3,5,200,300,400,2,3,0,1,23,24,56,30,500,20,1000,3000]
#print(a.index(max(a)))
b = []
for i in range(0,9):
b.append(a.index(max(a)))
a[a.index(max(a))] = 0
print(b) |
"""
core/exceptions.py
useful custom exceptions for
different cases
author: @alexzander
"""
class core_Exception(Exception):
def __init__(self, message=""):
self.message = message
class HTTP_RequestError(core_Exception):
""" handles the http stuff"""
pass
... |
class MovieCard:
def __init__(self, price):
self._price = price
self._tickets = 10 if price == 70 else 15 # assume price = 70 or 100 only
@property
def tickets(self):
return self._tickets
def redeem_ticket(self, qty=1):
if qty > 2:
raise ValueError("Ma... |
'''
# O(N^2)
# it is hard to pass the test big cases
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
sizeOfNums = len(nums)
for i in range(sizeOfNums):
for j in range(i+1, s... |
#!/usr/bin/env python
# _*_ coding: utf-8
# See LICENSE for details.
class BaseConfig:
def __init__(self, logger=None, BaseConfig=None):
self
self.logger = logger
self.stageing = False
self.config_directory = None
self.default_key_type = 'RSA'
# TODO: Support 'ECDS... |
# Team 5
def save_to_excel(datatables: list, directory=None):
pass
def open_excel():
pass
|
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
nodes = preorder.split(",")
cnt = 1
for i, x in enumerate(nodes):
if x == "#":
cnt -= 1
if cnt == 0:
return i == len(nodes) - 1
else:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Where is my access point? Console Script.
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://dev... |
# -*- coding: utf-8
class Document:
__slots__ = ('root',)
def __init__(self):
self.root = None
|
def includeme(config):
config.add_static_view('static', 'static', cache_max_age=None)
config.add_route('home', '/')
config.add_route('auth', '/auth')
config.add_route('portfolio', '/portfolio')
config.add_route('detail', '/portfolio/{symbol}')
config.add_route('add', '/add')
config.add_route... |
print("BMI Calculator")
print("=" * 20)
height = input("Enter height (m): ")
weight = input("Enter weight (kg): ")
try:
height = float(height)
weight = float(weight)
except ValueError:
print("One or more invalid values entered.")
exit(1)
print("Your BMI is %d." % int((weight / (height ** 2))))
# 35.5... |
class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
if(n==0):
return 0
dp = [0]*n
dp[0] = nums[0]
for i in range(1,n):
if(i == 1):
dp[i] = max(nums[0], nums[1])
... |
def bmw_finder_price_gt_25k(mileage, price):
if price > 25000:
return 1
else:
return 0
def bmw_finder_price_gt_20k(mileage, price):
if price > 20000:
return 1
else:
return 0
def bmw_finder_price_gt_cutoff_price(cutoff_price):
def c(x,p):
if p > cutoff_pric... |
logs = """Log: Log file open, 15/01/{} 00:00:00
Log: GPsyonixBuildID 190326.60847.228380
Log: Command line:
Init: WinSock: version 1.1 (2.2), MaxSocks=32767, MaxUdp=65467
Log: ... running in INSTALLED mode
Warning: Warning, Unknown language extension . Defaulting to INT
Init: Language extension: INT
Init: Language ex... |
STATS = [
{
"num_node_expansions": 1733,
"plan_length": 142,
"search_time": 1.66,
"total_time": 1.66
},
{
"num_node_expansions": 2128,
"plan_length": 153,
"search_time": 1.93,
"total_time": 1.93
},
{
"num_node_expansions": 2114,... |
LINE_DICT_TEMPLATE = {
'kind': '',
'buy_cur': '',
'buy_amount': 0,
'sell_cur': '',
'sell_amount': 0,
'fee_cur': '',
'fee_amount': 0,
'exchange': 'Bitshares',
'mark': -1,
'comment': '',
'order_id': '',
}
# CSV format is ccGains generic format
HEADER = 'Kind,Date,Buy currency,... |
globalval=6
def checkglobalvalue():
return globalval
def localvariablevalue():
globalval=8
return globalval
print ("This is global value",checkglobalvalue())
print ("This is global value",globalval)
print ("This is local value",localvariablevalue())
print ("This is global value",globalval)
|
class Logger:
def __init__(self, simulator, time, image_analyzer, speed_controller,
car, gyro, asservissement, sequencer, handles, tachometer):
self.tachometer = tachometer
self.handles = handles
self.time = time
self.image_analyzer = image_analyzer
self.seq... |
"""
Algorithms to find biconnected components in the graph considering
only dovetails overlaps.
Adapted using the networkx biconnected module:
networkx/networkx/algorithms/components/biconnected.py
"""
# Copyright (C) 2011-2013 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Piet... |
total = 0
for line in open('input.txt'):
l, w, h = [int(side) for side in line.split('x')]
sides = [2*(l+w), 2*(w+h), 2*(h+l)]
total += min(sides) + l*w*h
print(total)
|
def missions_per_year(df):
'''
From a dataframe with the 'Year' column,
Plot a graph showing the number of missions per year
'''
missions_per_year = df.Year.value_counts()
plt.plot(missions_per_year.sort_index())
plt.show()
def missions_per_week(df):
'''
From a dataframe with the '... |
def sum_func(a, *args):
s = a+sum(args)
print(s)
sum_func(10)
sum_func(10,20)
sum_func(10,20,30)
sum_func(10, 20, 30, 40)
|
DATA = [
{
'name': 'Facundo',
'age': 72,
'organization': 'Platzi',
'position': 'Technical Mentor',
'language': 'python',
},
{
'name': 'Luisana',
'age': 33,
'organization': 'Globant',
'position': 'UX Designer',
'language': 'javas... |
# 81. Search in Rotated Sorted Array II
"""
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).
Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., n... |
TAG_MAP = {
('landuse', 'forest'): {"TYPE": "forest", "DRAW_TYPE": "plane"},
('natural', 'wood'): {"TYPE": "forest", "SUBTYPE": "natural", "DRAW_TYPE": "plane"}
}
def find_type(tags):
keys = list(tags.items())
return [TAG_MAP[key] for key in keys if key in TAG_MAP]
|
#
# PySNMP MIB module Webio-Digital-MIB-US (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Webio-Digital-MIB-US
# Produced by pysmi-0.3.4 at Mon Apr 29 21:32:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
raspberry = True
display_device = "/dev/fb1"
mouse_device = "/dev/input/event0"
mouse_driver = "TSLIB"
if raspberry:
mouse_type = "pitft_touchscreen"
touch_xmin = 345
touch_xmax = 3715
touch_ymin = 184
touch_ymax = 3853
else:
mouse_type = "pygame"
if raspberry:
screen_fullscreen = True
els... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def CheckChangeOnUpload(*args):
return _CommonChecks(*args)
def CheckChangeOnCommit(*args):
return _CommonChecks(*args)
def _CommonChecks(input_api,... |
messages = ["<b>Shoulder-arm stretch</b>Time to do Shoulder arm stretch, keep one arm horizontally stretched in front of your chest. Push this arm with your other arm towards you until you feel a mild tension in your shoulder. Hold this position briefly, and repeat the exercise for your other arm. Don't do this more th... |
myfile=open('country.txt')
print(myfile.read())
myfile.close()
#with open('country.txt',mode='r') as myfile:
# print(myfile.read())
with open('country.txt',mode='a') as f:
print(f.write("'IN':'INDIAN'"))
|
# -*- coding: utf-8 -*-
"""
FIXME
"""
|
class Solution:
def skipAndClose(self, startIndex, step, count):
"""
:type startIndex: int
:type step: int
:type count: int
:rtype: List[int]
"""
inputArray = list(range(1, count+1))
itemLeft = 0
result = []
while(len(inputArray) > 0... |
L_af = "af" # Afrikaans
L_am = "am" # Amharic
L_ar = "ar" # Arabic
L_az = "az" # Azerbaijani
L_be = "be" # Belarusian
L_bg = "bg" # Bulgarian
L_bn = "bn" # Bengali
L_bs = "bs" # Bosnian
L_ca = "ca" # Catalan
L_ceb = "ceb" # Chechen
L_co = "co" # Corsican
L... |
alunos = list()
dados = list()
while True:
dados.append(str(input('Nome: ').capitalize().strip()))
dados.append(float(input('Nota 1: ')))
dados.append(float(input('Nota 2: ')))
alunos.append(dados[:])
dados.clear()
ask = str(input('Deseja continuar? [S/N]: ')).upper().strip()
if ask in 'nN':... |
km = float(input('Quantos Km percorrido: '))
diaria = int(input('Quantos dias alugado: '))
total = (diaria * 60) + (km * .15)
print(f'Foram percorridos {km}km e {diaria} diarias, total de R${total:.2f}')
|
n = int(input())
phonebook=dict()
for _ in range(n):
q = list(map(str,list(input().split())))
name = q[0]
phone = int(q[1])
phonebook[name]=phone
try:
while True:
query = input()
if query!="":
if query in phonebook:
st = query+'='+str(phonebook[query])
... |
#Validación del break
def run():
for i in range(10000):
print(i)
if i == 5678:
break
if __name__ == '__main__':
run() |
__author__ = 'deadblue'
mime_types = {
'svg': 'image/svg+xml',
'png': 'image/png',
'webp': 'image/webp'
} |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.36
工具: python == 3.7.3
"""
"""
思路:
利用zip和set函数进行求解
结果:
执行用时 : 84 ms, 在所有 Python3 提交中击败了11.93%的用户
内存消耗 : 13.1 MB, 在所有 Python3 提交中击败了87.27%的用户
"""
class Solution:
def longestCommonPrefix(self, strs):
res... |
#
# PySNMP MIB module MSSSERVER8260-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MSSSERVER8260-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:15:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
nums = map(float, input().split())
count_values = {}
for num in nums:
if num not in count_values:
count_values[num] = 0
count_values[num] += 1
for key, value in count_values.items():
print(f"{key} - {value} times")
|
algo = input('Digite algo: ')
print('O tipo primitivo deste valor é: {}'.format(type(algo)))
print('Só tem espaços? {}'.format(algo.isspace()))
print('É um número? {}'.format(algo.isnumeric()))
print('É alfabetico? {}'.format(algo.isalpha()))
print('É alfanumerico? {}'.format(algo.isalnum()))
print('Está em maiúsculo... |
def get_ranges(data):
# create a list of all valid ranges
list_of_ranges = {}
for line in data:
if line == "":
break
l = []
key = line.split(":")[0]
line = line.split()
lower, upper = line[-1].split("-")
l.append((int(lower), int(upper)))
l... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "... |
########################
#### Initialisation ####
########################
input_ex1 = []
with open("inputs/day5_1.txt") as inputfile:
for line in inputfile.readlines():
input_ex1.append(int(line.strip()))
########################
#### Part one ####
########################
sample_input = [0,
... |
'''
Probem Task : This program will return number of solutions to quadratic equation.
Problem Link : https://edabit.com/challenge/o2AKq4xy3nfZabKXL
'''
def solutions(a,b,c):
if ((b**2 - 4*a*c) > 0):
return 2
elif ((b**2 - 4*a*c)==0):
return 1
else:
return 0
if __name__ == ... |
"""
For extracting parameters from a dictionary of substance properties.
"""
class MissingParameterError(Exception):
"""Raised when a parameter of a substance is required but not supplied."""
def __init__(self, substance, parameter):
self.substance = substance
self.parameter = parameter
... |
# -*- coding: utf-8 -*-
n = int(input())
p, q, r, s, x, y = map(int, input().split())
i, j = map(int, input().split())
res = 0
for k in range(1, n + 1):
res += ((p * i + q * k) % x) * ((r * k + s * j) % y)
print(res) |
# encoding: utf-8
# module time
# from (built-in)
# by generator 1.145
"""
This module provides various functions to manipulate time values.
There are two standard representations of time. One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer
or a floating point number (to represent... |
#Forma simprificada
'''viajem = float(input('Qual a distancia da sua viajem? '))
print('Você está prestes a começar uma viajem de {}!'.format(viajem))
valor = viajem * 0.45 if viajem >= 200 else viajem * 0.50
print('Sua viajem custará R${}!'.format(valor))'''
viajem = float(input('Qual a distancia da sua viajem? '))
i... |
"""
PyLHC
~~~~~~~~~~~~~~~~
PyLHC is a script collection for the optics measurements and corrections group (OMC) at CERN.
:copyright: pyLHC/OMC-Team working group.
:license: MIT, see the LICENSE.md file for details.
"""
__title__ = "pylhc"
__description__ = "An accelerator physics script collection for the OMC team at... |
class Solution(object):
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
if length < 2:
return 0
bound_x = min(nums)
bound_y = max(nums)
bucket_range = max(1, int((bound_y - bound_x - 1) / (le... |
# 2. define a function called “add” that returns the sum of two numbers
def addi(n1, n2):
sum=n1+n2
print(sum)
return sum
addi(2, 4) |
duo_prim = {
"NRES": {"NRES", "GRU-CC", "POA", "HMB", "DS-XX"},
"GRU-CC": {"GRU-CC", "POA", "HMB", "DS-XX"},
"HMB": {"HMB", "DS-XX"},
"POA": {"POA"},
"DS-XX": {"DS-XX"},
}
duo_sec = {
"GSO",
"RUO",
"RS-XX",
"NMDS",
"GS-XX",
"NPU",
"PUB",
"COL-XX",
"IRB",
"TS-... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 19:19:34 2019
@author: sercangul
"""
N = map(int,input().split())
A = list(map(int, input().strip().split(' ')))
mean = sum(A)/len(A)
i=0
X=0
while i<len(A):
X = X + ((A[i] - mean)**2)
i = i+1
STD = (X/len(A)) ** (0.5)
print(round((STD... |
class Enemy:
def __init__(self, name, health, damage):
self.name = name
self.health = health
self.damage = damage
def isActive(self):
return self.health > 0
class KillerJackal(Enemy):
def __init__(self):
super().__init__(name="Killer-Jackal", health=30, damage=50)
... |
superbowl_wins = [
['1', 'Pittsburgh', '6'],
['2', 'Dallas', '5'],
['3', 'Paris', '16'],
['4', 'Wembo CLub', '25'],
]
for row in superbowl_wins:
print (row[1] + " had " + row[2] + " wins")
print("========================")
for row in superbowl_wins:
for el in row:
print (el)
print('')
|
"""557. Reverse Words in a String III
https://leetcode.com/problems/reverse-words-in-a-string-iii/
Given a string, you need to reverse the order of characters in each word
within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat e... |
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left, right = 0, len(numbers) - 1
while left <= right:
sum = numbers[left] + numbers[right]
if sum == target:
return [left + 1, right + 1]
elif sum < target:
... |
# int()
# float()
# str()
# bool()
number_input = input("number: ")
print(type(number_input))
number_input = int(number_input)
print(type(number_input))
# Falsy Values
print(bool(0))
print(bool(0.0))
print(bool(''))
print(bool(()))
print(bool([]))
print(bool({}))
print(bool(set()))
print(bool(complex()))
print(bool(... |
def surrender():
i01.setHandSpeed("left", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("right", 0.75, 0.85, 0.95, 0.85)
i01.setArmSpeed("left", 0.75, 0.85, 0.95, 0.85)
i01.setHeadSpeed(0.65, 0.65)
i01.moveHead(90,90)
i01.moveArm("left",90,139,15,79)... |
# coding:utf-8
# 版权信息: All rights Reserved, Designed By XHal.cc
# 代码作者: Hal
# 创建时间: 2021/1/31 17:13
# 文件版本: V1.0.0
# 功能描述: 程序的组织结构 - 计算机的流程控制: 顺序结构
# 顺序结构: 程序从上到下顺序地执行代码,中间没有任何的判断和跳转,直到程序结束
'''把大象装进冰箱,一共分几步'''
print (' -------程序开始------- ')
print (' 1. 把冰箱门打开 ')
print (' 2. 把大象放进去 ')
print (' 3. 把冰箱门关上 ')
print ('... |
'''
Created on June 5, 2012
@author: Jason Huang
'''
'''
Question 1 / 1.
There are N objects kept in a row. The ith object is at position x_i. You want to partition them into K groups. You want to move all objects belonging to the same group to the same position. Objects in two different groups may be placed ... |
def tidy_label(data, label):
label = label or [''] * len(data)
label = label[:len(data)]
return ['{:2}'.format(str(i)[:2]) for i in label]
def bar_generate_canvas(y, max_height=None, max_length=None):
height, length = int(max(y)) + 1, y.shape[0]
height = max(height, max_height) if max_height else ... |
class URLS():
BASE_URL = "http://automationpractice.com/index.php"
CONTACT_PAGE_URL = 'http://automationpractice.com/index.php?controller=contact'
LOGIN_PAGE_URL = 'http://automationpractice.com/index.php?controller=authentication&back=my-account'
REGISTRATION_PAGE_URL = 'http://automationpractice.com/i... |
#
# PySNMP MIB module APPIAN-STRATUM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPIAN-STRATUM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:23:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
class Solution:
def majorityElement(self, nums):
c1, c2, cnt1, cnt2 = 0, 1, 0, 0
for num in nums:
if num == c1:
cnt1 += 1
elif num == c2:
cnt2 += 1
elif not cnt1:
c1, cnt1 = num, 1
elif not cnt2:
... |
#!/usr/bin/env python3
""" Field identifying and parsing.
The contents of this module allow the specifcation of formats of arrays
of bytes (similar to the python's struct module), but with more
granularity.
Each field basically has two properties: a name and a size (in bytes).
Each field has ba... |
class Node:
# Each node is a tree
def __init__(self, value):
self.data = value
self.right = None
self.left = None
def insert(self, value):
if self.data:
if value < self.data:
if self.left is None:
self.left = Node(value)
... |
'''
Statement
Chess knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. The complete move therefore looks like the letter L. Given two different squares of the chessboard, determine whether a knight can go from the first squ... |
# Crie um programa que vai:
# Ler vários números
# E perguntar se o usuário quer continuar a cada repetição
# Crie 3 listas:
# 1 - Receber todos os valores;
# 2 - Receber apenas valores pares;
# 3 - Receber apenas valores ímpares;
# No final mostre o restultado das 3 listas na... |
def strAppend(suffix):
return lambda x : x + suffix
|
numerals = {
"I": 1,
"IV": 4,
"V": 5,
"IX": 9,
"X": 10,
"XL": 40,
"L": 50,
"XC": 90,
"C": 100,
"CD": 400,
"D": 500,
"CM": 900,
"M": 1000
}
def checkio(inp, output=""):
next = max([e for e in numerals if numerals[e]<=inp], key=lambda x: numerals[x])
output = o... |
root_folder = '/var/www/'
charset = '<meta charset="utf-8">'
def application(env, start_response):
scripts = open(root_folder+'scripts.js', 'r').read()
forms = open(root_folder+'forms.html', 'r').read()
if env['REQUEST_METHOD'] == 'POST':
if env.get('CONTENT_LENGTH'): env_len = int(env.get('CONTENT_... |
class Solution:
def crackSafe(self, n: int, k: int) -> str:
# worst case k ** n
def dfs(cur, seen, total):
if len(seen) == total:
return cur
for i in range(k):
temp = cur[-n + 1: ] + str(i) if n != 1 else str(i)
if temp not in s... |
LANGUAGES = ['Auto', 'Afrikaans', 'Albanian', 'Amharic', 'Arabic', 'Armenian', 'Azerbaijani', 'Basque', 'Belarusian', 'Bengali',
'Bosnian', 'Bulgarian', 'Catalan', 'Cebuano', 'Chichewa', 'Chinese (Simplified)', 'Chinese (Traditional)', 'Corsican',
'Croatian', 'Czech', 'Danish', 'Dutch', 'English', 'Esperanto'... |
class Validator(object):
"""
Create the Validator instance to register config. You can either pass a flask application in directly
here to register this extension with the flask app, or call init_app after creating
this object (in a factory pattern).
:param app: A flask application
"""
def _... |
# -*- coding: utf-8 -*-
"""
@author: Hareem Akram
"""
# [Reddit credentials]
c_id = 'client id from https://www.reddit.com/prefs/apps'
secret = 'client secret from https://www.reddit.com/prefs/apps'
agent = 'osint project'
usr = 'reddit username'
pwd = 'reddit password'
# [Twitter credentials]
# apply for developer ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.