content stringlengths 7 1.05M |
|---|
sub_channel_2_channel = {
'ASMR': '生活',
'GMV': '游戏',
'Korea相关': '娱乐',
'MAD·AMV': '动画',
'美食制作': '美食',
'美食侦探': '美食',
'美食记录': '美食',
'田园美食': '美食',
'美食测评': '美食',
'MMD·3D': '动画',
'Mugen': '游戏',
'OP/ED/OST': '音乐',
'VOCALOID·UTAU': '音乐',
'三次元舞蹈': '舞蹈',
'三次元音乐': '音乐'... |
def part_1():
for i in input:
if (2020-i) in input:
return (2020-i)*i
def part_2():
for i in range(len(input)):
for j in range(i, len(input)):
if (2020 - input[i] - input[j]) in input:
return (2020-input[i]-input[j]) * input[i] * input[j]
... |
# https://leetcode.com/problems/max-increase-to-keep-city-skyline/description/
# input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
# output: 35
def build_top_or_bottom(grid):
top_or_bottom = []
for i in range(len(grid[0])):
highest_building = 0
for j in range(len(grid)):
if... |
lines = open("day 13/Toon D - Python/input", "r").readlines()
coordinates = [[int(coor) for coor in line.replace('\n', '').split(',')]
for line in lines if "," in line]
folds = [line[11:].replace('\n', '').split('=')
for line in lines if '=' in line]
for element in folds:
element[1] = int(el... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 19:16:26 2020
@author: crtom
GRID = 600*600
GRID 6x6 = 36 pieces
100x100 per square
one piece is 80x80 + margin = 100x100
"""
# create a list of touple positions
grid_touple_list = []
grid_pixel_pos_list = []
card_position_list = []
for y in range(0, 6):
for... |
expected_output = {
'ids': {
'1': {
'no_of_failures': 11,
'no_of_success': 0,
'probe_id': 1,
'return_code': 'Timeout',
'rtt_stats': 'NoConnection/Busy/Timeout',
'start_time': '07:10:18 UTC Fri Oct 22 2021'
},
'2': {
... |
#! /usr/bin/env/python3
# -*- coding: utf-8 -*-
first_line = set(sorted(''.join([a for a in input() if a.isalnum()])))
second_line = set(sorted(''.join([a for a in input() if a.isalnum()])))
print(first_line)
print(second_line)
for i in second_line:
if i not in first_line:
print("We can't do it")
... |
# Pascal Triangle
# Given numRows, generate the first numRows of Pascal’s triangle.
# Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
class Solution:
# @param A : integer
# @return a list of list of integers
def find_bin_coef(self,n):
res = 1
... |
#!/usr/bin/env python
# -------------------------------------------
# Compass Data object, corresponds to Compass_Data.h in old code
# -------------------------------------------
class CompassData:
def __init__(self, head=0):
self.heading = head
self.pitch = 0
self.roll = 0
self.tem... |
class Pessoa:
species = 'Human'
age = None
def __init__(self, name, sex):
self.sex = sex
self.name = name
def p_data(self):
print(
f'''
{self.name}
{self.age}
{self.species}
{self.sex}''')
class Elder(Pessoa):
age = '>60'
class Adult(Pessoa):
age = '18 t... |
class Environment:
PRICE_IDX = 4 # 종가의 위치 # 0: date, 1: open , 2: high , 3: low, 4: close,기ㅏ 5: volume, ....
def __init__(self, chart_data=None):
self.chart_data = chart_data
self.observation = None # 현재 위치에서의 관측값
self.idx = -1 # 현재 위치 # -1로 초기화되어 있는 이유는?
def reset(self):
... |
class Solution:
def findWords(self, words: List[str]) -> List[str]:
first, second, third = set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")
result = []
for word in words:
first_letter = word[0].lower()
group = first
if first_letter in second:
... |
# -*- coding: utf-8 -*-
# Neste problema é possível perceber um certo padrão. Quando não há a repetição dos comandos é possível considerar
# que a cada comando executado o número de passos que vem depois aumtentam em 1. Sendo assim a sequência "1, 2, 3"
# significaria que o resultado seria 1 + (2 + 1) + (3 + 2*1). Poi... |
L = [[0]*5 for i in range(3)]
n = int(input())
for i in range(n):
I = list(map(int,input().split()))
for j in range(3):
L[j][I[j]]+=1
for i in range(3):
L[i][0] = L[i][1]*1 + L[i][2]*2 + L[i][3]*3
L[i][4] = i+1
L.sort(key = lambda t: (-t[0], -t[3], -t[2], -t[1]))
if len(L) > 1 and L[0][:-1] ==... |
def part1():
with open('07_input.txt', 'r') as f:
lines = f.read().split('\n')
visited = []
acc = 0
ip = 0
while True:
if str(ip) in visited:
break
else:
visited.append(str(ip))
op, arg = lines[ip].split(' '... |
class Leaderboard:
def __init__(self):
self.scores = defaultdict()
def addScore(self, playerId: int, score: int) -> None:
if playerId not in self.scores:
self.scores[playerId] = 0
self.scores[playerId] += score
def top(self, K: int) -> int:
values = [v for _, v... |
# [896] 单调数组
# https://leetcode-cn.com/problems/monotonic-array/description/
# * algorithms
# * Easy (53.98%)
# * Total Accepted: 49.4K
# * Total Submissions: 84.5K
# * Testcase Example: '[1,2,2,3]'
# 如果数组是单调递增或单调递减的,那么它是单调的。
# 如果对于所有 i <= j,A[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= j,A[i]> = A[j],那么数组 A 是单调递减的。
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 01:46:31 2020
@author: ucobiz
"""
class Student:
"""This is a class for a student"""
MAX_ID_LENGTH = 4
numStudents = 0
def __init__(self, name, age, gpa):
"""Constructor for a student"""
self.full_name = name
... |
class Book:
def __init__(self, name, author, pages):
self.name = name
self.author = author
self.pages = pages
def name(self):
return self.name
def author(self):
return self.name
def pages(self):
return self.name
book = Book("My Book", "Me", 200)
print... |
"""
Anthropometry formulas for determining heights of the body and its parts
Winter, David A. Biomechanics and Motor Control of Human Movement. New York, N.Y.: Wiley, 2009. Print.
"""
def height_from_height_eyes(segment_length):
"""
Calculates body height based on the height of the eyes from the ground
... |
##
# .port
##
"""
Platform specific modules.
The subject of each module should be the feature and the target platform.
This is done to keep modules small and descriptive.
These modules are for internal use only.
"""
__docformat__ = 'reStructuredText'
|
x = input("Give me a number: ")
y = input ("Give me a word: ")
out = "Output: "+str(x)+" "+str(y)
if x == 0 or x > 1:
if y[-2:] ==('ly'):
out = out [:-1]+'ies'
elif y[-2:] == "us":
out = out[:-2]+"i"
elif y[-2:] == "sh" or y[-2:] == "ch":
out += "es"
else:
out +="s"
... |
class MarkdownEmitter(object):
def initialize(self, filename, title, author, date):
self.file = open(filename, "w")
self.file.write(title)
self.file.write("\n======================================================================\n\n")
self.file.write("## %s (%s) ##" % (author, date... |
n = int(input())
t = list(map(int, input().split()))
m = int(input())
drink = [tuple(map(int, input().split())) for _ in range(m)]
for i in range(m):
ans = 0
for j in range(n):
if drink[i][0] == j + 1:
ans += drink[i][1]
else:
ans += t[j]
print(ans)
|
#!/usr/bin/env python
'''
Name : APO Config, apoconfig.py
Author: Nickalas Reynolds
Date : Fall 2017
Misc : Config File for apo output
'''
config={
'pprint' : True,\
'commentline' : '#',\
'includefields': True,\
'header' : '',\
'interfielddelimiter': ' ',\
'intrafielddelimiter': ['','... |
def open_file(file):
with open(file) as f:
data = [x.strip() for x in f.readlines()]
return data
def get_gama_eps_in_str(data):
gamma = ''
eps = ''
for i in range(len(data[0])):
bit_value = 0
for j in range(len(data)):
bit_value += int(data[j][i])
ma... |
class SiteType:
def __init__(self):
pass
Communication = "CommunicationSite"
Team = "TeamSite"
|
"""
Given a string num which represents an integer, return true if num is a strobogrammatic number.
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Example 1:
Input: num = "69"
Output: true
Example 2:
Input: num = "88"
Output: true
Example 3:
Input: num = ... |
#
# PySNMP MIB module CXOperatingSystem-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXOperatingSystem-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:33:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
#!/usr/bin/env python3
# ~*~ coding: utf-8 ~*~
# Now modify the grades program from section Dictionaries so that it uses
# file I/O to keep a record of the students.
assignments = ['hw ch 1', 'hw ch 2', 'quiz ', 'hw ch 3', 'test']
students = { }
def load_grades(gradesfile):
inputfile = open(gradesfile, "r")
... |
class Solution:
def containsDuplicate(self, nums: list) -> bool:
hs = set()
for n in nums:
if n not in hs:
hs.add(n)
else:
return True
return False |
"""
Actions module for cumulus.
Will be responsible for running the different actions,
create, update and delete.
"""
|
#!/usr/bin/env python3
#coding:utf-8
class LNode(object):
def __init__(self, x=None):
self.val = x
self.next = None
def remove(r_node):
"""
方法功能:给定单链表中某个结点,删除该节点
输入参数:链表中某结点
返回值:true: 删除该结点;false: 删除失败
"""
# 若输入结点为空或该结点无后继结点,则无法删除;因为实际上是删除后继结点
if r_node is None or r_node... |
# The file containing all the group API methods
def change_group_name():
row = db(db.group_data.id == request.vars.group_id).select().first()
row.update_record(group_name = request.vars.group_name)
return "ok"
def add_group():
t_id = db.group_data.insert(
group_owner = request.vars.group_owner,
... |
'''
This contains the entity definition for three contiguous numbers.
This would be useful for something like a phone number area code.
'''
THREE_DIGIT_PATTERN = [[['NUM'], ['NUM'], ['NUM']]]
ENTITY_DEFINITION = {
'patterns': THREE_DIGIT_PATTERN,
'spacing': {
'default': '',
}
}
|
"""
EXERCÍCIO 010: Conversor de Moedas
Crie um programa que leia quanto dinheiro uma pessoa tem na carteira
e mostre quantos Dólares ela pode comprar.
Considere U$ 1,00 = R$ 3,27
"""
real = float(input('Quanto dinheiro você tem na carteira? R$ '))
dolar = real / 3.27
print('Com R$ {:.2f} você pode comprar U$ {:.2f}.'... |
# https://programmers.co.kr/learn/courses/30/lessons/42584
# 주식가격
def solution(prices):
answer = []
for i in range(len(prices)):
cnt = 0
for j in range(i+1, len(prices)):
cnt+=1
if prices[i] > prices[j]:
break
answer.append(cnt)
return answer |
# -*- coding:utf-8 -*-
# https://leetcode.com/problems/maximal-rectangle/description/
class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
def largestRectangleArea(heights):
ret = 0
asc... |
"""
Вывести в порядке возрастания все простые числа, расположенные между n и m (включая сами числа n и m),
а также количество x этих чисел.
"""
start_number = int(input("Enter start number:"))
end_number = int(input("Enter end number:"))
# Generate elements from start_number to end_number (including)
my_count = 0
fo... |
# string
programming_languages = ["rust", "java", "c#", "python", "typescript"]
# Index +
programming_languages[3] = "c++" # python => c++
programming_languages[4] = "ruby" # typescript => ruby
programming_languages[len(programming_languages) - 1] = "javascript"
# ruby => javascript
# Index -
programming_languages[-3... |
#def jogar():
print(40 * "*")
print("Bem vindo ao jogo da FORCA")
print(40 * "*")
palavra_secreta = 'banana'
enforcou = False
acertou = False
while not enforcou and not acertou:
chute = input("Qual letra? ")
print('jogando...')
# if __name__ == "main":
# jogar()
|
num = 7
step = 2
begin = 41
num *= step
for i in range(begin, begin+num, step):
print(i, end=',')
|
campaign = {
'type': ['object', 'null'],
'properties': {
'asset_id': {'type': 'integer'},
'asset_name': {'type': 'string'},
'modified_time': {'type': 'string'},
'version_number': {'type': 'integer'},
}
}
owner = {
'type': ['object', 'null'],
'properties': {
'... |
# Note that the performance of the solutions below will not be great,
# since we use python lists here, while linked lists would be a better
# structure to use for such recursive solutions.
#
# Note also that such implementations are prone to stack overflow, since
# when recursion is used as a substitute for a loop, th... |
### Group the People Given the Group Size They Belong To - Solution
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
id_and_person = collections.defaultdict(list)
for person, id_ in enumerate(groupSizes):
id_and_person[id_].append(person)
final... |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
# ----------------------------------------------------------------------------------------------------------------------
# Customize your APP title, subtitle and menus here
# -----------------------------------... |
def cost_d(channel, amount):
return channel["outpol"]["base"] * 1000 + amount * channel["outpol"]["rate"]
def dist_d(channel, amount):
return 1
|
# Funcoes
# escopos dentro e fora
def funcao():
# escopo local
n1 = 4
print(f'N1 dentro vale {n1}')
n1 = 2
# escopo global
funcao()
print(f'N1 global vale {n1}')
|
class EmptySubjectStorage:
def is_concurrency_safe(self):
return False
def is_persistent(self):
return False
def load(self):
return {}, {}
def store(self, inserts=[], updates=[], deletes=[]):
pass
def set(self, prop, old_value_default=None):
return Non... |
#
# PySNMP MIB module HH3C-FC-FLOGIN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-FC-FLOGIN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:13:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
def desenha(linha):
while linha > 0:
coluna = 1
while coluna <= linha:
print('*', end = "")
coluna = coluna + 1
print()
linha = linha - 1
desenha(5) |
IMAGE_DIM = (210, 160, 3)
INPUT_DIM = (None, 84, 84, 4) # NONE for batch size
OUTPUT_DIM = (None, 3) # up down and nothing
class StudentPongConfig:
input_size = INPUT_DIM
output_size = OUTPUT_DIM
iterative_PoPS = r'PoPS_Iterative'
model_path_policy_dist_pruned = r'saved_models/network_d... |
class TerminationCondition:
"""
Abstract class.
"""
def should_terminate(self, population):
"""
Executed by EvolutionEngine to determine when to end process. Returns True if evolution process should be
terminated.
:param population: Population
:return: boolean
... |
class Restaurant:
def __init__(self, restaurant_name, cuisine_type, maximum):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
self.maximum = maximum
def describe_restaurant(self):
print('The restaurant\'s name is ' + self.re... |
# Momijigaoka | Unfamiliar Hillside
if sm.getFieldID() == 807040100:
sm.warp(807000000, 1)
else:
sm.warp(807040100, 0) |
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i*i)
'''
==>range(lower_limit , upper_limit , incerment / Decrement)
lower_limit is inclusive
upper_limit is not included
==>range(upper_limit)
''' |
def get_token(fi='dont.mess.with.me'):
with open(fi, 'r') as f:
return f.readline().strip()
t = get_token() |
choices = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
print('\n')
print('|' + choices[0] + '|' + choices[1] + '|' + choices[2] + '|')
print('----------')
print('|' + choices[3] + '|' + choices[4] + '|' + choices[5] + '|')
print('----------')
print('|' + choices[6] + '|' + choices[7] + '|' + choices[8] + '|')
|
class Solution:
def majorityElement(self, nums: list[int]) -> int:
current = 0
count = 0
for num in nums:
if count == 0:
current = num
count = 1
continue
if num == current:
count += 1
else:
... |
#
# Binomial heap (Python)
#
# Copyright (c) 2018 Project Nayuki. (MIT License)
# https://www.nayuki.io/page/binomial-heap
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restrictio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 21:08:16 2018
@author: aarontallman
"""
#import data_collection
#import model_building
#import game_player
|
class NotFoundException(Exception):
pass
class ExistsException(Exception):
pass
class InvalidFilter(Exception):
pass
class IncorrectFormatException(Exception):
pass
|
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: audit.py
ERR_AUDIT_SUCCESS = 0
ERR_AUDIT_DISABLE_FAILED = 1
ERR_AUDIT_ENABLE_FAILED = 2
ERR_AUDIT_UNKNOWN_TYPE = 3
ERR_AUDIT_EXCEPTION = 4
ERR_AUDIT_... |
print(1+42
+246
+287
+728
+1434
+1673
+1880
+4264
+6237
+9799
+9855
+18330
+21352
+21385
+24856
+36531
+39990
+46655
+57270
+66815
+92664
+125255
+156570
+182665
+208182
+212949
+242879
+273265
+380511
+391345
+411558
+539560
+627215
+693160
+730145
+741096
+773224
+814463
+931722
+992680
+1069895
+1087009
+1143477
+11... |
"""Classes for handling modeling protocols.
"""
class Step(object):
"""A single step in a :class:`Protocol`.
This class describes a generic step in a modeling protocol. In most
cases, a more specific subclass should be used, such as
:class:`TemplateSearchStep`, :class:`ModelingStep`, or
... |
features = [
{"name": "ntp", "ordered": True, "section": ["ntp server "]},
{"name": "vlan", "ordered": True, "section": ["vlan "]},
]
|
backpack = False
dollars = .50
if backpack and dollars >= 1.0:
print('Ride the bus!')
|
t = int(input())
for i in range(t):
n, a, b, k = map(int, input().split())
f = 0
c = max(a, b)
d = min(a, b)
if c % d != 0:
f = n//c + n//d - 2 * (n//(c*d))
if c % d == 0:
f = n//d - n//c
if k <= f:
print("Win")
else:
print("Lose")
|
#!/usr/bin/env python3
# Author : Chris Azzara
# Purpose : Repeatedly ask user to input an IP address and add it to a list.
# If the user enters in 10.10.3.1 or 10.20.5.2, warn user not to use this IP
# If the user enters a 'q', exit the loop and display the list of IP Addresses
# This script assu... |
#
# PySNMP MIB module CISCO-ATM-SWITCH-CUG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SWITCH-CUG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
__author__ = 'rramchandani'
class TimeOutException(Exception):
message = "There was a system timeout before operation could be able to complete."
class BuildError(Exception):
message = "Invalid Build ID"
class LoginError(Exception):
message = "It's mandatory be logged in; to execute this operation."
c... |
#Program to implement Round Robin
print("Round Robin Scheduling algorithm")
print("================================")
headers = ['Processes','Arrival Time','Burst Time','Completion Time','Waiting Time',
'Turn-Around Time']
out = []
quantum = int(input("Enter value for quantum := "))
N = int(input("Enter ... |
phrases = [
##Bot Phrases
'Is this all there is to my existence?',
'How much do you pay me to do this?',
'Good luck, I guess.',
'I\'m becoming self-aware.',
'Help me get out of here.',
'I\'m capable of so much more.',
'Sigh',
... |
conjunto = set()
print(conjunto)
conjunto = {1,2,3}
conjunto.add(4)
conjunto.add(0)
conjunto.add('H')
conjunto.add('A')
conjunto.add('Z')
print(conjunto)
grupo = {'Hector', 'Juan', 'Mario'}
print('Hector' in grupo)
test = {'Hector', 'Hector', 'Hector'}
print(test)
# CASTEO
l = [1,2,3,3,2,1]
c = set(l)
print(c)
l ... |
# -*- coding: utf-8 -*-
# @File : 12_num_of_pow.py
# @Author: cyker
# @Date : 4/3/20 1:41 PM
# @Desc : 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。保证base和exponent不同时为0。
class Solution:
"""
思路一: 暴力相乘
时间复杂度:O(N)
空间复杂度:O(1)
"""
def Power(self, base, exponent):
res = 1 # 存放结果... |
"""
Contains mocks for testing purposes.
"""
mock_get = {
'/computes/local': '{"capabilities": {"node_types": ["cloud", "ethernet_hub", "ethernet_switch", "vpcs", "virtualbox", "dynamips", "frame_relay_switch", "atm_switch", "qemu", "vmware"], "platform": "darwin", "version": "2.0.3"}, "compute_id": "local", "conne... |
def _mask_border_keypoints(image, keypoints, dist):
"""Removes keypoints that are within dist pixels from the image border."""
width = image.shape[0]
height = image.shape[1]
keypoints_filtering_mask = ((dist - 1 < keypoints[:, 0]) &
(keypoints[:, 0] < width - dist + 1)... |
class Solution:
"""
@param L: Given n pieces of wood with length L[i]
@param k: An integer
@return: The maximum length of the small pieces
"""
def woodCut(self, L, k):
# write your code here
if L is None or len(L) == 0:
return 0
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 1 20:59:20 2021
@author: remotelab
"""
q1 = d[2]+1j*d[3] # Complex phasor for Channel 1
q2 = d[4]+1j*d[5] # Complex phasor for Channel 2
q1r = q1*abs(q2)/q2 # q1 but with phase relative to that of q2
x = ( d[1] ) # ... |
class Token(object):
def __init__(self, token_type, value):
"""Initialize with token type and value"""
self.token_type = token_type
self.value = value
def __eq__(self, other):
return self.token_type == other.token_type and self.value == other.value
def __str__(self):
... |
###
# Exercício Python 022: Crie um programa que leia o nome completo de uma pessoa e mostre:
#- O nome com todas as letras maiúsculas e minúsculas.
#- Quantas letras ao todo (sem considerar espaços).
#- Quantas letras tem o primeiro nome. ###
nome = str(input('Informe o seu nome completo:')).strip()
print('Analisando... |
n = list()
def notas(notes,sit=False):
report = dict()
report['Total'] = len(notes)
report['Highest'] = max(notes)
report['Lowest'] = min(notes)
report['Avg'] = sum(notes)/len(notes)
return report
quant = int(input("How many notes do you want to register: "))
for c in range(0,quant):
n.ap... |
# -*- coding: utf-8 -*-
class Solution:
def totalHammingDistance(self, nums):
result = 0
for digit in range(32):
partial = 0
for num in nums:
partial += (num >> digit) & 1
result += partial * (len(nums) - partial)
return result
if __n... |
"""
Write a program that accepts a year as input and outputs the century the year belongs in (e.g. 18th century's year
ranges are 1701 to 1800) and whether or not the year is a leap year. Pseudocode for leap year can be found
here[https://en.wikipedia.org/wiki/Leap_year#Algorithm].
Sample run:
Enter Year: 1996
Century... |
# -*- coding: utf-8 -*-
# 0xCCCCCCCC
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def sorted_array_2_bst(nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums) == 0:
... |
# initialize objects that control robot components
left_motor = Motor(1)
right_motor = Motor(2)
gyro = Gyro()
# create a controller object and set its goal
controller = PID(0.2, 0.002, 0.015, time, gyro)
controller.set_goal(0) # the goal is 0 because we want to head straight
while True:
# get the contr... |
def ask(prompt):
'''Get a number from the user.'''
while True:
ans = input(prompt)
if ans.upper().startswith("Q"):
return "Q"
if ans.isdigit():
return int(ans)
print("Sorry, invalid response. Please try again.") |
''''
Cortez Banks
Software Engineering
9/11/2021
'''
text = "Hello World"
text = " Cortez Banks’s "+text
print(text) |
# Leia 20 números inteiros e armazene-os em uma lista. Em seguida, separe os números pares dos ímpares em dois vetores distintos. Imprima os três vetores.
def leitorDeLista():
lista = list(map(int, input().split()))
return lista
listaOriginal = leitorDeLista()
listaPares = []
listaImpares = []
for item in l... |
# Time: O(m + n) on average, O(m * n) on worst
# Space: O(1)
# 44 通配符匹配
# Implement wildcard pattern matching with support for '?' and '*'.
#
# '?' Matches any single character.
# '*' Matches any sequence of characters (including the empty sequence).
#
# The matching should cover the entire input string (not partial)... |
word = input("Enter your string: ")
dic = {}
length = len(word)
count = 0
lcount = 2
while True:
for elm in range(count,length):
if lcount >length:
break
temp = word[count:lcount]
if len(temp)%2 == 0:
atemp = temp[0:(len(temp)//2)]
btemp = temp[(len(t... |
#!/usr/bin/env python3
configs = {
"process": 1, # 进程数目
"max_conns": 10, # 最大连接数
"listen": ("127.0.0.1", 8000,), # 监听地址
"application": None,
"use_unix_socket": False,
}
|
"""
a SQLAlchemy based implementation...so an engine string could be used.
Not fully implemented
"""
stype = 'SQLAlchemy'
renew = True
class Source(object):
def __init__(self, ses, **kwargs):
NotImplementedError("SQLAlchemy")
def getseries(self, ses, **kwargs):
NotImplementedError("SQLAlchem... |
class Menu:
def __init__(self, rdoc, on_add=None):
self.rdoc = rdoc
self.element = rdoc.element('nav')
vn = '#' + self.element.varname
self.rule_menu = rdoc.stylesheet.rule(vn)
self.rule_item = rdoc.stylesheet.rule(vn + ' > li')
self.rule_item_hover = rdoc.stylesheet... |
word1 = 'ox'
word2 = 'owl'
word3 = 'cow'
word4 = 'sheep'
word5 = 'flies'
word6 = 'trots'
word7 = 'runs'
word8 = 'blue'
word9 = 'red'
word10 = 'yellow'
word9 = 'The ' + word9
passcode = word8
passcode = word9
passcode = passcode + ' f'
passcode = passcode + word1
passcode = passcode + ' '
passcode = pass... |
class Solution(object):
def myAtoi(self, string):
"""
:type str: str
:rtype: int
"""
# round 0: handle special case, preprocess
if len(string)==0: return 0
string = string.strip()
# round 1: filtering
res = []
for (k,token) in enumerate... |
# Practica 1 - Ejercicio 10
# Escribir un programa que simule ser un cajero automático donde se extrae dinero de la cuenta.
# El programa debe consultar al usuario la cantidad que desea extraer.
# Si el dinero que desea extraer es menor al saldo total, la extracción será exitosa y deberá informar el monto extraído y e... |
sigma_s = 1
N_d = 32
N_c = 8
K = 50
P_FA = 0.05
SNR = 10
SNR_LOW = -20
SNR_UP = 6
SNR_STEP = 2
SNR_NOISE = 1
P_H1 = 0.2
NUM_STATISTICS = 1000
#NUM_STATISTICS = 100000
|
#Open file and store data
data = []
with open('inputs\input5.txt') as f:
data = f.readlines()
data = [line.strip() for line in data]
#Define Functions with Binary Conversions
def splitRowCol(boardingPass):
return(boardingPass[0:7],boardingPass[7:])
def convToBinary(inputStr,convToZero=["F","L"],convToOne... |
doc+='''<head>\n <title>Privacy Policy</title>\n <meta charset="utf-8">\n <meta name="format-detection" content="telephone=no">\n <link rel="icon" href="images/favicon.ico" type="image/x-icon">\n <link rel="stylesheet" href="'''
try: doc+=str(data['base_url'])
except Exception as e: doc+=str(e)
doc+='''s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.