content stringlengths 7 1.05M |
|---|
#
# @lc app=leetcode id=61 lang=python3
#
# [61] Rotate List
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
curr = head
... |
# https://programmers.co.kr/learn/courses/30/lessons/42584
def solution(prices):
answer = []
length = len(prices)
for i in range(length):
now_value = prices[i]
for j in range(i+1, length):
if prices[j] < now_value or j == length -1:
answer.append(j-i)
... |
###############################################################################
# Done: READ the code below. TRACE (by hand) the execution of the code,
# predicting what will get printed. Then run the code
# and compare your prediction to what actually was printed.
# Then mark this _TODO_ as DONE and commit-and-push ... |
i = 0
while True:
open(f'{i}', 'w')
i += 1
|
"""
Terminal client for telegram
"""
__version__ = "0.17.0"
|
# Example: Fetch a single transcription on a recording
my_transcription = api.get_transcription('recordingId', 'transcriptionId')
print(my_transcription)
## {
## 'chargeableDuration': 11,
## 'id' : '{transcriptionId}',
## 'state' : 'completed',
## 'text' : 'Hey t... |
class Solution:
def singleNumber(self, nums: List[int]) -> int:
nums.sort()
i=0
while i <len(nums):
if ((i<len(nums)-2) and nums[i]==nums[i+1] ):
i+=2
else:
return nums[i]
break |
# -*- encoding: utf-8 -*-
{
'name': 'El Salvador - Reportes y funcionalidad extra',
'version': '1.0',
'category': 'Localization',
'description': """ Reportes requeridos y otra funcionalidad extra para llevar un contabilidad en El Salvador. """,
'author': 'Aquih, S.A.',
'website': 'http:... |
"""Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
# .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB
# .. toggle_implementation: DjangoSetting
# .. toggle_default: False
# .. toggle_description: If True, it add... |
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m = len(grid[0])
n = len(grid)
if m == 0 or n == 0:
return 0
for i in range(m):
if i != 0:
grid[0][i] += grid[0][i-1]
for j in range(... |
print("Keep Talking And Nobody Explodes - Kronorox Solvers")
print("On the Subject of Passwords")
print("Version 1.01")
print(" ")
print("Remember to rack through the first six(using the arrows), then move to the second set of letters, and so on")
#Loading the file, opening it, then adding it to the list, then clo... |
class BeaxyIOError(IOError):
def __init__(self, msg, response, result, *args, **kwargs):
self.response = response
self.result = result
super(BeaxyIOError, self).__init__(msg, *args, **kwargs)
|
class Solution(object):
def lengthOfLongestSubstring(self, s):
if not s:
return 0
start, end = 0, 0
seen = set()
ans = 0
while end < len(s):
if s[end] not in seen:
seen.add(s[end])
... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/mayur/ros jade files/catkin_ws/src/Udacity-SDC-Radar-Driver-Micro-Challenge/ros/src/sensing/drivers/can/packages/kvaser/msg/CANESR.msg"
services_str = ""
pkg_name = "kvaser"
dependencies_str = "std_msgs;visualization_msgs"
langs = "gencpp;geneus... |
file = open("input", "r")
good_passwords = 0
for line in file.readlines():
poss, char, word = line.strip().split()
pos_one, pos_two = poss.split("-")
char = char[0]
if (word[int(pos_one) - 1] == char) != (word[int(pos_two) - 1] == char):
good_passwords += 1
print(good_passwords)
|
# Hotel Receptionist (1061100) | Sleepywood Hotel
array = [# Name, MesoCost, Map ID
["Regular", 499, 105000011],
["VIP", 999, 105000012]
]
sm.sendNext("Welcome. We're the Sleepywood Hotel. "
"Our hotel works hard to serve you the best at all times. "
"If you are tired ... |
### Merge Sort
def merge_sort(A):
"""
Given a list A, sort it using merge sort.
First divide the list into two halves, then resursively sort each half.
Return the sorted list.
If the list has length less than 2, return the list since it's already sorted.
"""
n = len(A)
if n < 2:
... |
def init_parse(init):
dicinit = {}
init = open('%s'%init,'r')
lines = init.readlines()
lines = [x.strip( ) for x in lines]
for line in lines:
if line.startswith('#'):
pass
else:
try:
dicinit[line.split(' ')[0]] = line.split(' ')[2]
... |
"""
This is where we should implement any and all job function for the
redis queue. The rq library requires special namespacing in order to work,
so these functions must reside in a separate file.
"""
|
"""
A decorator that makes a class a singleton
"""
# pylint: disable=too-few-public-methods
class Singleton:
"""
A singleton class
"""
instances = {}
def __new__(cls, clz=None):
"""
Returns a new instance ONLY if one does not already exist
"""
if clz is None:
... |
try:
print("Enter the 20 input Number to get summary")
num=[]
for i in range(0, 20):
temp = int(input())
num.append(temp)
print(f"List with Number's : {num}\nlength :{len(num)}")
count_p=0
count_n=0
count_odd=0
count_even=0
count_zero=0
for i in num:
if i>... |
class Solution:
def solve(self, strs):
return sorted(strs, reverse = True)
|
"""
You can uncomment on the setting parameters below
==================================
"""
"""
This parameter is used to determine the specific user to executes the kolla ansible command
"""
# USER_EXEC_KOLLA_COMMAND = "root"
"""
This parameter is used to determine the location of the hosts file
"""
# CONFIG_DIR_HO... |
before_array_dict = [
{"theRealCat": "unavailable",
"code": "callback-http-failure-status",
"nestedDeeply": {
"stillNesting": {
"yetStillNesting": {
"wowSuchNest": True
}
}
},
"details": [{"nextId": "ued-abc123",
"nam... |
class Solution:
def findTheWinner(self, n: int, k: int) -> int:
# edge cases
if n == 1: return 1
if k == 1: return n
# general cases
circle = [i for i in range(1,n+1)]
start = 0
while len(circle) > 1:
start = (start + k -1) % len(circle)
... |
def list_of_multiples (num, length):
return [i*num for i in range(1,length+1)]
#Problem statement: Create a function that takes two numbers as arguments (num, length) and returns a list of multiples of num up to length.
#Problem Link: https://edabit.com/challenge/BuwHwPvt92yw574zB
|
__author__ = 'wangjian'
|
#CB 03/03/2019
#GMIT Data Analytics Programming & Scripting Module 2019
#Problem Sets
#Problem Set 1
#Setting up a user-defined variable 'i', and asking the user to enter a positive integer as 'i'
i = int(input("Please enter a positive integer: "))
#Setting up the 'total' variable, which will track the output value i... |
class NumArray:
def __init__(self, nums: 'List[int]'):
self.sums = [0]
for num in nums:
self.sums.append(self.sums[-1] + num)
def sumRange(self, i: int, j: int) -> int:
return self.sums[j + 1] - self.sums[i]
if __name__ == '__main__':
num_array = NumArray([-... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016, 2017, 2018 Guenter Bartsch
#
# 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.... |
# Requires mock server set up on localhost:3000
# Try out Mockoon for this: https://github.com/mockoon/mockoon
# They even provide sample responses for each API: https://github.com/mockoon/mock-samples
SPOTIFY_WEB_API = "http://localhost:3000/v1"
SPOTIFY_AUTH_API = "http://localhost:3000/v1/auth"
GROUPS_TABLE = "Smoot... |
def cartpole_analytical_derivatives(model, data, x, u=None):
if u is None:
u = model.unone
# Getting the state and control variables
y, th, ydot, thdot = x[0].item(), x[1].item(), x[2].item(), x[3].item()
f = u[0].item()
# Shortname for system parameters
m1, m2, l, g = model.m1, model.... |
plays = ['Hamlet', 'Macbeth', 'King Lear']
plays.insert(1, 'Julius Caesar')
print(plays)
plays.insert(0, 'Romeo & Juliet')
print(plays)
plays.insert(10, "A Midsummer Night's Dreams")
print(plays) |
"""
Problem 1
COORDINATE MATH: Fill in the Line class methods to accept coordinates as a pair of tuples and return the slope and distance of the line.
EXAMPLE OUTPUT
coordinate1 = (3,2)
coordinate2 = (8,10)
li = Line(coordinate1,coordinate2)
"""
class Line:
def __init__(self,coor1,coor2):
self.coo... |
se_colors = {
'TV Application Layer': '#D9D9D9',
'Second Screen Framework': '#B67272',
'Audio Mining': '#F23A3A',
'Content Optimisation': '#00B0F0',
'HbbTV Application Toolkit': '#FF91C4',
'Open City Database': '#61DDFF',
'POIProxy': '#C8F763',
'App Generator': ... |
n = int(input('Digite um número inteiro: '))
b = int(input('Digite: \n[1] para binário \n[2] para octal \n[3] para hexadecimal \n Sua opção: '))
if b == 1:
print('{} convertido para binário é {}'.format(n, bin(n)[2:]))
elif b == 2:
print('{} convertido para octal é {}'.format(n, oct(n)[2:]))
elif b == 3:
pr... |
# from tkinter import *
# janela = Tk()
# texto = "Olá Mundo!, cheguei!"
# label_1 = Label(janela, text = texto, font='Arial:20')
# label_1.place(x=200, y=200)
# janela.geometry('800x600+0+0')
# janela.mainloop()
# ***************************************************************** #
def lin():
print('+=' * 24... |
__author__ = "Børge Jakobsen, Thomas Donegan"
__copyright__ = "Copyright 2019, Brexit boy and SaLmon king"
__credits__ = ["Børge Jakobsen, Thomas Donegan"]
__license__ = "Apache License"
__version__ = "2.0"
__maintainer__ = "Børge Jakobsen, Thomas Donegan"
__status__ = "Development"
class User():
def __init__(self... |
def factorial(num):
if(num == 0): return 1
return num*factorial(num-1)
def main():
#escribe tu código abajo de esta línea
numero = int(input("Dame un número: "))
print(f"El factorial es: {factorial(numero)}")
if __name__=='__main__':
main()
|
class HashTable:
def __init__(self):
self.table = [[] for x in range(13)]
def hash(self, key):
chrcodes = sum([ord(x) for x in key])
return chrcodes % 13
def insert(self, key, data):
# try to get existing key
print(self.hash(key))
for item in self.table[sel... |
class Cliente:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
self.enderecos = []
def insere_enderecos(self, cidade, estado):
self.enderecos.append(Endereco(cidade, estado))
def lista_enderecos(self):
for k in self.enderecos:
print(... |
# Get the plain text matrix (1 * 3 from a 3 letter word)
def get_plain_text_matrix(plain_text):
return [(ord(plain_text[i]) - 65) for i in range(3)]
# Get the key matrix (3 * 3 mtx from a 9 letter word)
def get_key_matrix(key):
mtx = [[0] * 3 for _ in range(3)]
counter = 0
for i in range(3):
f... |
class ShaderNodeBsdfTransparent:
pass
|
'''
Copyright [2017] [taurus.ai]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 20:46:46 2020
@author: Administrator
"""
"""
如何判断一个数是否是2的n次方
"""
def IsPowerof2(n):
if n < 1:
return False
i = 1
while i <= n:
if i == n:
return True
i <<= 1
return False
if __name__ == "__main... |
# auto parse
def auto_json_to_graph_experiment(json_dict):
process_original_json(json_dict)
# tags
normal_merge(json_dict, "Tag", "Chemical", "pk", "tags")
normal_merge(json_dict, "Tag", "Mixture", "pk", "tags")
normal_merge(json_dict, "Tag", "Experiment", "pk", "tags")
# get prop... |
class Employee():
def __init__(self, name, salary):
self.name = name
self.salary = salary
self.is_db_connected = False
def __enter__(self):
print("entered")
self.is_db_connected = True
# must return self because in the with employee as e: e becomes the value re... |
##x = input()
##if str(x)[::-1] == str(x):
## print("yes")
##else:
## print("no")
x = input()
x.replace(" ", "")
l = 0
r = len(x) - 1
output = 'yes'
while l < r:
if x[l] != x[r]:
output = 'no'
break
else:
l += 1
r -= 1
print(output)
|
string1 = input("")
string2 = input("")
lenStrings = len(string1)
arr = [[0]*(lenStrings+1) for n in range(lenStrings+1)]
for i in range(1,lenStrings+1):
for j in range(1,lenStrings+1):
match = arr[i-1][j-1]
if string1[i-1] == string2[j-1]:
match += 1
arr[i][j] = max(arr[i][j-... |
class Solution:
def findMaxAverage(self, nums, k: int) -> float:
# Avoid computations by working with a window of 1. We find the
# average of k-1 elements and add/remove values from the ends.
limit = k-1
start, max_avg = sum(nums[:limit]) / k, -(10 << 30)
for i in range(limit... |
EE_BASE = "https://elections.democracyclub.org.uk/"
"""
Every Election settings
Set CHECK to True to check Every Election to see if there is
an election happening before serving a poling station result
Set CHECK to False to return the value of HAS_ELECTION instead
This is mostly useful in development when we want
t... |
#Faça um Programa que leia um vetor de 10 números reais e mostre-os na ordem inversa
vetor= [1.1,2.3,4.5,6.5,7.6,8.8,9.6,9.5,9.9,8.5]
i=10
for i in range (10):
vetor = vetor + [i]
for i in range (9,-1,-1):
print (vetor[i])
|
# Section 5.15 snippets
# Finding the Minimum and Maximum Values Using a Key Function
'Red' < 'orange'
ord('R')
ord('o')
colors = ['Red', 'orange', 'Yellow', 'green', 'Blue']
min(colors, key=lambda s: s.lower())
max(colors, key=lambda s: s.lower())
# Iterating Backwards Through a Sequence
numbers = [10, 3, 7, 1,... |
#!/usr/bin/python
def Fibonaci_iter(n):
if (n == 0):
return 0
elif (n == 1):
return 1
elif (n > 1):
fn = 0
fn1 = 1
fn2 = 1
while n > 2:
fn = fn1 + fn2
fn1 = fn2
fn2 = fn
n = n - 1
return fn
print(Fibo... |
# Copyright 2021 The Perkeepy 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 applicable law or agreed to in... |
#
# PySNMP MIB module TIMETRA-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:01:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 108,
"id": "25569a41",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import csv \n",
"from statistics import mean"
]
},
{
"cell_type": "code",
"execution_count": 109,
"id": "2cbb873b",
"metadata": {},... |
#
# PySNMP MIB module CISCO-QLLC01-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-QLLC01-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:53:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
# Thrown by WikiData classes
class AppBaseException(Exception):
def __init__(self, message="", tag=None):
Exception.__init__(self, message)
self.tag = tag
def getTag(self):
return self.tag
class WikiDataException(AppBaseException): pass
class WikiWordNotFoundException(WikiD... |
def capitalize(string):
new = ''
for i in range(0,len(string)):
if i == 0:
new += string[i].upper()
elif string[i - 1] == ' ':
new += string[i].upper()
else :
new += string[i]
return new |
numbers = (input("").split())
a=int(numbers[0])
b=int(numbers[1])
if a == b:
print(0)
else:
print(1) |
@bot.command()
async def meme(ctx):
msg = await ctx.send("<a:loading:900379618924716052> Processing")
r = requests.get('https://meme-api.herokuapp.com/gimme')
x = r.text
y = json.loads(x)
title = y["title"]
url = y["url"]
author = y["author"]
embed = discord.Embed(title=f"{title}", color... |
# Constructor with arguments or parameters default
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance(self, point2):
"Calculates distance between current point to given point2"
x = point2.x - self.x
y = point2.y - self.y
d = x**2 ... |
#
# @lc app=leetcode.cn id=108 lang=python3
#
# [108] 将有序数组转换为二叉搜索树
#
# https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/description/
#
# algorithms
# Easy (74.50%)
# Likes: 655
# Dislikes: 0
# Total Accepted: 128.6K
# Total Submissions: 172.5K
# Testcase Example: '[-10,-3,0,5,9]'
#
# ... |
def encode(content: bytes):
p = list(content)
oa = ord('a')
oz = ord('z')
oA = ord('A')
oZ = ord('Z')
for i in range(len(p)):
if oa <= p[i] <= oz:
p[i] = oa + 25 - p[i] + oa
elif oA <= p[i] <= oZ:
p[i] = oA + 25 - p[i] + oA
return bytes(p)
def decode... |
# Write a function def equals(a, b) that checks whether two lists have the same
# elements in the same order.
# FUNCTIONS
def equals(listA, listB):
if len(listA) < len(listB) or len(listA) > len(listB):
return False
equalBool = False
for i in range(len(listA)):
if listA[i] == listB[i]:
... |
def old_test():
core = Core(User='',Password='',ip='192.168.61.2')
core.start()
#gain = Control(parent=core,Name='gain',ValueType=int)
cg = ChangeGroup(parent=core,Id='mygroup')
#create some control objects
for i in range(1,10):
l = Control(parent=core,Name='Mixer6x9Output{}Label'... |
NODE_STATS_UPDATE_INTERVAL_SECONDS = 1
UPDATE_NODES_INTERVAL_SECONDS = 5
MAX_COUNT_OF_GCS_RPC_ERROR = 10
MAX_LOGS_TO_CACHE = 10000
LOG_PRUNE_THREASHOLD = 1.25
|
class Solution(object):
def minTaps(self, n, ranges):
"""
:type n: int
:type ranges: List[int]
:rtype: int
"""
ranges = [(i-r,i+r) for i,r in enumerate(ranges)]
ranges.sort(reverse = True)
watered = 0
ans = 0
while ra... |
# Джокер + Результаты нескольких тиражей
def test_joker_results_for_several_draws(app):
app.ResultAndPrizes.open_page_results_and_prizes()
app.ResultAndPrizes.click_game_joker()
app.ResultAndPrizes.click_results_for_several_draws()
app.ResultAndPrizes.click_ok_for_several_draws_modal_window()
app... |
#Faça um programa que calcule o fatorial de um número inteiro fornecido pelo usuário. Ex.: 5!=5.4.3.2.1=120. A saída deve ser conforme o exemplo abaixo:
num = int(input("Informe um valor inteiro: "))
fat = 1
print('\nFatorial de ', num)
while num > 0:
fat = fat * num
num = num - 1
print('= ',fat)
... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"kcred": "extract.ipynb",
"unzip": "extract.ipynb",
"download_kaggle_dataset": "extract.ipynb"}
modules = ["loader.py"]
doc_url = "https://talosiot-will.github.io/agora/"
git_url = "https... |
# coding=utf-8
#
# @lc app=leetcode id=130 lang=python
#
# [130] Surrounded Regions
#
# https://leetcode.com/problems/surrounded-regions/description/
#
# algorithms
# Medium (23.59%)
# Likes: 875
# Dislikes: 457
# Total Accepted: 157.2K
# Total Submissions: 664.2K
# Testcase Example: '[["X","X","X","X"],["X","O"... |
def generate_python(fields):
pkgSize = 0
pkgStr = '<'
for field in fields:
pkgSize += field.fieldType.length
pkgStr += field.fieldType.charCode
pyStr = 'PACKAGE_LEN = '+str(pkgSize)+'\n'
pyStr += 'PACKAGE_CODE = "'+pkgStr+'"\n'
pyStr += 'PACKAGE_FIELDS = ' + list(
m... |
PLATFORM_COMPILER_FLAGS = [
'-std=c++14',
'-Wall',
'-Wextra',
# For TestCommon.h
'-Wno-pragmas',
]
|
x = 0
score = x
# Question One
print("What are the plants and trees release into the air?")
answer_1 = input("a)air\nb)oxygen\nc)music\nd)zak's fart \n:")
if answer_1.lower() == "b" or answer_1.lower() == "oxygen":
print("Correct")
x = x + 1
else:
print("Incorrect, it's oxygen")
# Question Two
print("... |
class BaseMarkupEngine(object):
def __init__(self, message, obj=None):
self.message = message
self.obj = obj
class BaseQuoteEngine(object):
def __init__(self, post, username):
self.post = post
self.username = username
|
'''
Interpret text as though all letters are off by one key location
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output"""
lut, keys = {' ': ' '}, []
keys.append('`1234567890-=')
keys.append('QWERTYUIOP[]\\'... |
__author__ = "Cauani Castro"
__copyright__ = "Copyright 2015, Cauani Castro"
__credits__ = ["Cauani Castro"]
__license__ = "Apache License 2.0"
__version__ = "1.0"
__maintainer__ = "Cauani Castro"
__email__ = "cauani.castro@hotmail.com"
__status__ = "Examination program"
#funcao recursiva que acumula o resultado em va... |
people_waiting = int(input())
wagon_state = input().split()
len_ = len(wagon_state)
counter = 0
is_full = False
if people_waiting == 0:
print(*wagon_state)
exit(0)
for el in range(len_):
counter = int(wagon_state[el])
if counter == 4:
is_full = True
continue
for people in range(4):
... |
name, age = "Shelby De Oliveira", 29
username = "shelb-doc"
print ('Hello!')
print("Name: {}\nAge: {}\nUsername: {}".format(name, age, username))
|
"""
Entradas
consumo licor --> l -->int
licor preferido --> lp --> int
edad --> e --> int
sexo --> se --> int
seguir --> seg --> int
Salidas
personas que consumen licor --> s--> int
mujeres menores de edad--> Muj_me-->int
hombres que no consumen aguardiente entre 20 y 25 años-->Hom_no_a-->int
promedio edad de quienes ... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# coding: utf8
class Room():
def __init__(self, serv, room_name, admin_username, bot_username, lutra_username, website_url, user_list):
# Class attributes
self.serv = serv
self.room_name = room_name
self.admin_username = admin_username
... |
number0 = int(input("Insira um número: "))
number1 = int(input("Insira outro número: "))
resultado = number0 + number1
print(resultado)
|
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Microsoft.
Given an array of numbers arr and a window of size k, print out the median of each window of size k starting from the left and moving right by one position each time.
For example, given the following array and k = ... |
class Solution:
def productExceptSelf(self, nums: list[int]) -> list[int]:
result = [1] * len(nums)
prefix = 1
for i in range(len(nums)):
result[i] *= prefix
prefix *= nums[i]
postfix = 1
for i in range(len(nums) - 1, -1, -1):
result[i] *= ... |
'''
from os.path import expanduser, exists, split
if __name__ == '__main__':
print('[TPL] Test Extern Features')
import multiprocessing
multiprocessing.freeze_support()
def ensure_hotspotter():
import matplotlib
matplotlib.use('Qt4Agg', warn=True, force=True)
# Look for hotspott... |
MONGO_URI = 'mongodb://steemit:steemit@mongo1.steemdata.com:27017/SteemData'
MONGO_DBNAME = 'SteemData'
# 50 items per page by default
PAGINATION_DEFAULT = 50
# allow 1000 requests per minute
RATE_LIMIT_GET = (1000, 60)
# change status message
STATUS_ERR = 'ERROR'
# change default response fields
EXTRA_RESPONSE_FIE... |
def wait(c):
m = None
while m != 'GO':
m = (c.recv(300).decode().replace('\n','').strip())
pass |
# -*- coding: utf-8 -*-
"""
morse.py
Class for converting between English and morse code
@author: Douglas Daly
@date: 1/6/2017
"""
#
# Class Definition
#
class Morse(object):
"""
Morse Code Translation Class
"""
def __init__(self):
""" Default Constructor
"""
dict_tup ... |
class ResolveEventArgs(EventArgs):
"""
Provides data for loader resolution events,such as the System.AppDomain.TypeResolve,System.AppDomain.ResourceResolve,System.AppDomain.ReflectionOnlyAssemblyResolve,and System.AppDomain.AssemblyResolve events.
ResolveEventArgs(name: str)
ResolveEventArgs(name: str,... |
def pesquisa_binaria(lista, item):
baixo = 0
alto = len(lista) - 1
while baixo <= alto:
meio = (baixo + alto) // 2
chute = lista[meio]
if chute == item:
return meio
elif chute > item:
alto = meio - 1
elif chute < item:
baixo = m... |
# _*_coding : UTF_8_*_
# Author :Jie Shen
# CreatTime :2022/1/17 20:53
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class BuildTree:
def __init__(self):
pass
def build_by_array(self, arr) -> ListNode:
if arr is None... |
# CAN THE WORD BE CONSTRUCTED?
# Write a function 'can_construct(target, word_bank)' that accepts a
# target string and an array of strings.
#
# The function should return a boolean indicating whether ot not the
# 'target' can be constructed by concatenating elements of the 'word_bank' array.
#
# You may reuse e... |
class Mesh(object):
'Common class for all Mesh of the Finite Element Method.'
def __init__(self):
pass
|
"""一个青蛙一次可以跳1级台阶或2级台阶,一共有n级台阶,问青蛙跳到顶部有几种跳法?(递归)"""
# 思路:找规律
# t=1 1
# t = 2 2
# t = 3 3
# t = 4 5
# t = 5 8
# 发现是一个斐波那契数列
# 思路2 递归f(n)
# 考虑最后一跳
# 最后一跳 跳1级台阶,有f(n-1)种跳法
# 最后一跳 跳2级台阶,有f(n-2)种跳法
# 总的跳法种类f(n)=f(n-1)+f(n-2)
def f(n):
# 递归的出口
# 因为有两个递归,所以要写两个递归的出口
if n == 1:
return 1
if n == 2:
... |
# @Author Justin Noddell
# def pagerank( G ):
# params G *** a dict of pages and their respective links
# returns a dict of pages and their respective pagerank values
#
# the purpose of this function is to execute the PageRank function
def pagerank( G ):
P = G.keys() # pages
L = G.values() ... |
'''
MSDP Genie Ops Object Outputs for IOSXE
'''
class MsdpOutput(object):
# 'show ip msdp peer'
ShowIpMsdpPeer = {
'vrf': {
'default': {
'peer': {
'10.1.100.4': {
'session_state': 'Up',
'pe... |
word = input()
while not word == "end":
print(f"{word} = {word[::-1]}")
word = input()
# text = input()
# while text != "end":
# text_reversed = ""
# for ch in reversed(text):
# text_reversed += ch
# print(text + " = " + text_reversed)
# text = input()
|
entrada = int(input())
for i in range(0, entrada):
A, B = input().split(" ")
x, y = int(A), int(B)
if y == 0:
print("divisao impossivel")
else:
resultado = x / y
print(f"{resultado:.1f}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.