content stringlengths 7 1.05M |
|---|
n=int(input())
synonymsDict={}
for k in range(0,n):
wordFound=False
word=input(); synon=input()
for j in synonymsDict:
if j==word:
synonymsDict[j]+=f", {synon}"
wordFound=True
if wordFound==False:
synonymsDict[word]=synon
output=""
for k in synonymsDic... |
#!/usr/bin/python3
with open('09_input', 'r') as f:
lines = f.readlines()
nums = [int(l.strip()) for l in lines]
preamble_size = 25
sum_cache = dict()
table = []
for i in range(preamble_size):
row = []
front = nums[i]
for j in range(i+1, preamble_size):
val = front + nums[j]
sum_cac... |
def hashtags(string, hash=True):
hashtags = []
for word in string.replace('\n', '').split():
if word.startswith("#") and word != "#":
if hash:
hashtag = word
else:
hashtag = word.replace("#", "")
hashtags.append(hashtag)
return hash... |
def fact(n):
if (n == 1):
return n;
else:
return n*fact(n-1);
test = int(input())
for i in range (0,test):
val = int(input())
print(fact(val))
##Example Test Case
# Sample input:
# 4
# 1
# 2
# 5
# 3
# Sample output:
#
# 1
# 2
# 120
# 6
|
'''
GEOMETRIC PROGRESSION
Any sequence of elements where the quotient between any two
consecutive elements is equal is termed to be in G.P.
The nth term of an G.P. is defined as (a * r^(n-1))
where a is the first element of the G.P.
r is the common ratio of the G.P.
'''... |
N = int(input())
ans = []
for i in range(N-1, 0, -1):
d = [int(d) for d in str(i)]
if N == i + sum(d):
ans.append(i)
if len(ans) > 0:
print(min(ans))
else:
print(0)
|
n = int(input("Your number is: "))
sum = 0
for x in range(1, n + 1):
sum += x
print(sum) |
"""
This file contains the default config data for the reports system
On start-up thirtybirds loads config data. It loads default configs from config/ unless otherwise specified. New config data can be loaded dynamically at runtime.
Typical usage example:
from config import reports
foo = ClassFoo(reports.foo_conf... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
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 restriction, including without limitation the rights
to use, copy, modify, merge, p... |
class MyIgnorableClass :
def getServiceValue(self, argument) :
return f'ignorable service value: {argument}'
class MyOtherIgnorableClass :
def getServiceValue(self, argument) :
return f'other ignorable service value: {argument}'
|
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
memo = collections.defaultdict(list)
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
memo[nums[i] + nums[j]].append((i, j))
ans = set()
for i in range(n)... |
class CapsuleNetwork(tf.keras.Model):
def __init__(self, no_of_conv_kernels, no_of_primary_capsules, primary_capsule_vector, no_of_secondary_capsules, secondary_capsule_vector, r):
super(CapsuleNetwork, self).__init__()
self.no_of_conv_kernels = no_of_conv_kernels
self.no_of_primary_caps... |
#day 1
# register = []
# with open('day5.txt', mode='r') as f:
# for l in f.readlines():
# register.append(int(l.strip()))
# step_count = 0
# index =0
# while index>=0 and index <len(register):
# step_count+=1
# old_index = index
# index += register[index]
# register[old_index]+=1
# print(... |
class Participant(object):
def __init__(self, id, name, balance, volume):
self.__id = id
self.__name = str(name)
if balance < 0 or volume < 0:
raise ValueError()
self.__balance = float(balance)
self.__volume = int(volume)
@property
def id(self):
... |
class BusException(Exception):
'''
Class to represent an Exception
'''
def __init__(self):
pass |
def authentication(unamePasswordForVerification):
# unamePasswordForVerification = ["rabindra", "rabindra23"]
if ( getAuthenticatedUsersList() != -1 ):
verifiedUsersList = getAuthenticatedUsersList()
for verifiedUsers in verifiedUsersList:
if (verifiedUsers == unamePasswordForVerification):
message = "AUTH... |
test = { 'name': 'eq1',
'points': 0,
'suites': [ { 'cases': [ { 'code': '>>> best_salesperson(["Alice", "Bob", "Cam"], [3, 4, 1.25, 6, "Shift Change", 2, 4, 5.75, "Shift Change", 10, 2, .25, "Shift Change"]) == "Alice"\n'
'True',
... |
# Contents of simple.py
def cells():
1 + 2
|
def largest_non_adjacent(numbers):
if len(numbers) == 0:
return 0
incl = numbers[0]
excl = 0
for i in range(1, len(numbers)):
print(f"incl={incl}, excl={excl}")
incl, excl = excl + numbers[i], max(excl, incl)
return max(incl, excl)
print(largest_non_adjacent([5,5,10,40,50... |
phrase='British Library'
alpha=re.compile('[^a-zA-Z]')
def normalize_keep_case(word):
return re.sub(alpha,'',word)
def mapper(book):
def checker(first, second):
first_word=normalize_keep_case(first[1])
second_word=normalize_keep_case(second[1])
page=first[0]
if [first_wo... |
def findDuplicates(arr):
l = len(arr)
temp = []
isPresent = False
for i in range(1, l):
for j in range(i+1, l):
if arr[i] == arr[j]:
if arr[i] in temp:
break
else:
temp.append(arr[i])
... |
class Solution(object):
# recursive
def maxDepth(self,root):
if not root:
return 0
if not root.children: return 1
return max(self.maxDepth(node) for node in root.children) + 1
# BFS (use a queue, the last level we see will be the depth)
def maxDepth2(self,root)... |
mc_version = "1.12.2"
mc_file_md5 = "8c0443868b9e46c77d39db61c755679d"
of_file_name = "1.12.2_HD_U_E3"
of_json_name = "1.12.2_HD_U_E3"
of_file_md5 = "7EC95C57AC1A224D6EB93BD370E4AC37"
of_build_md5 = "ca404859e7af955dd01a72bb75bd6e11"
minecrift_version_num = "1.12.2"
minecrift_build = "jrbudda-9-r3"
of_file_extension = ... |
# Dictionary full of info
my_info = {"name": "Rex",
"occupation": "dog",
"age": 21,
"hobbies": ["barking", "eating", "sleeping", "loving my owner"],
"wake-up": {"Mon": 5, "Friday": 5, "Saturday": 10, "Sunday": 9}}
# Print out results are stored in the dictionary
print(f'Hell... |
#
# PySNMP MIB module CTRON-SSR-L2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SSR-L2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:15:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
'''
Check whether a given term represents a binary tree
Write a predicate istree which returns true if and only if its argument is a list representing a binary tree.
Example:
* (istree (a (b nil nil) nil))
T
* (istree (a (b nil nil)))
NIL
'''
def isTree(tree):
if len(tree) != 3: # checkin... |
# Copyright (c) 2017 https://github.com/ping
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
__version__ = '0.3.8'
|
maior = menor_de_20_feminino = masc =0
while True:
print('_' * 25)
print('CADASTRE UMA PESSOA')
print('_' * 25)
idade = int(input('Idade: '))
if idade > 18:
maior += 1
sexo = str(input('Sexo: [M/F] ')).strip().upper()
if sexo == 'M':
masc += 1
if idade < 20 and sexo == 'F... |
def setup():
size(500, 300)
background(0)
colorMode(HSB)
t1 = random(0, 10)
t2 = random(0, 10)
t3 = 0
t4 = 100
def draw():
global t1
global t2
global t3
global t4
fill(color(t3, 255, 255))
#noStroke()
x = map(noise(t1), 0, 1, -.5*width, 1.5*width)
y = map(noise(t2), 0,... |
#
# PySNMP MIB module NCD-MIB-1 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NCD-MIB-1
# Produced by pysmi-0.3.4 at Mon Apr 29 20:07:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... |
class CONVERTER:
def __init__(self, endian):
self.endian = endian
def bytes2int(self, bytes):
return int.from_bytes(bytes, byteorder=self.endian) |
mood = False
if mood :
print('go to left')
# print('back away')
else :
print('go to right')
a = 1
b = 2
c = 3
d = []
# account password
if a>b :
print('go to left')
else :
print('go to right') |
messageDigit = [
[0, 2],
[2, 12],
[12, 16],
[16, 19],
[19, 23],
[23, 25],
[25, 41],
[41, 45],
[45, 47],
[47, 51],
[51, 55],
[55, 71],
[71, 88],
[88, 92],
[92, 96],
[96, 101],
[101, 122]
]
fieldLen = [
2,
10,
4,
3,
4,
2,
5,
... |
"""
Module: 'flashbdev' on micropython-esp32-1.14
"""
# MCU: {'ver': '1.14', 'port': 'esp32', 'arch': 'xtensawin', 'sysname': 'esp32', 'release': '1.14.0', 'name': 'micropython', 'mpy': 10757, 'version': '1.14.0', 'machine': 'ESP32 module (spiram) with ESP32', 'build': '', 'nodename': 'esp32', 'platform': 'esp32', 'fam... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self, value):
self.head = Node(value)
def append(self, value):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(valu... |
#
# PySNMP MIB module SONOMASYSTEMS-SONOMA-ATM-DS3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-ATM-DS3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:09:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
# 5927. Reverse Nodes in Even Length Groups
# [5927] Reverse Nodes in Even Length Groups
# https://leetcode-cn.com/problems/reverse-nodes-in-even-length-groups/
# You are given the head of a linked list.
# The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of... |
a = int(input())
b = int(input())
if b > a:
print(tuple(range(a, b))) # [a,b)
if a > b:
print(tuple(range(b, a))) # [b,a)
|
""" Count sequences & characters in aligned fasta files """
def main():
with open(snakemake.input.fasta, "r") as infile:
n_gaps, total_chars = count_gaps(infile)
with open(snakemake.input.ref_accnos, "r") as infile:
num_refs = len(infile.readlines())
with open(snakemake.input.query_accnos,... |
# Note : Finds the index of minimum element of the sublist from lower to upper-1
def find_index(mylist, lower, upper):
'''
Objective : To find the index of minimum element of the sublist from lower to upper-1
parameters :
mylist : The list in which the min index is to be found
lower : The ... |
#
# PySNMP MIB module HH3C-DSP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-DSP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:13:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
mealCost = float(input())
tipPercent = int(input())
taxPercent = int(input())
totalCost = mealCost + (mealCost * (tipPercent/100)) + (mealCost * (taxPercent/100))
print('The total meal cost is', round(totalCost), 'dollars.') |
# Copyright 2021 Google LLC
#
# 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, ... |
class InvertedIndexMapper(InvertedIndex):
def __getitem__(self, key):
return self._get_postings_list(key)
def _get_postings_list(self, term):
"""Gets a postings list (of docIds) for `term`.
This function should not iterate through the index file.
I.e., it should onl... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold(arr, n, m):
max = 0
min = 0
arr.sort()
j = n - 1
for i in range(m):
min += arr[i]
... |
class PaymentLinkInfo:
def __init__(
self,
amountInt,
amountWithFeeInt,
payed,
**kwargs
):
self.__amount = amountInt / 100.0
self.__amountWithFee = amountWithFeeInt / 100.0
self.__payed = payed
@property
def amount(self):
""":rtype: float"""
return self.__amount
@prop... |
"""
Generalization operations on dataframes
=======================================
A generalization replaces some values with a parent value in the taxonomy
of an attribute. The reverse operation is called specialization.
"""
def generalize(data):
print("generalize 2")
|
# LTD simulation models / perturbances
# Attribute name case sensitive.
# Commented and empty lines are ignored during parsing.
# Double quoted variable names in model parameters also ignored
# Perturbances
mirror.sysPerturbances = [
'gen 5 : step Pm 20 -100 rel', # Step generator down
]
mirror.govDelay ={
... |
class Node(object):
def __init__(self, name):
self.name = name;
self.adjacenciesList = [];
self.visited = False;
self.predecessor = None;
class DepthFirstSearch(object): # BFS -> queue + layer by layer algorithm DFS -> stack + goes as deep aspossible into the tree !!!
def dfs(self, node):
... |
N, D, H = map(int, input().split())
dh = [tuple(map(int, input().split())) for _ in range(N)]
def is_ok(n):
for d, h in dh:
if (H - n) / D * d + n >= h:
continue
return False
else:
return True
ng = 0
ok = 10 ** 3
for _ in range(10000):
m = (ok + ng) / 2
if is_ok(m... |
#assignement 1
#write a program that asks and showsthe following from the user:
# 1. Your name
# 2. Your age
# 3. Your favorite color
# 4. Your favorite animal
name = input("please enter your name:\n")
age = input("please enter your age:\n")
color = input("what is your favorite color:\n")
animal = input("what is ... |
#
# PySNMP MIB module FASTPATH-IPV6-LOOPBACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FASTPATH-IPV6-LOOPBACK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:12:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
#new function declaration
def password_check(oldpassword, newpassword):
if newpassword != oldpassword:
if len(newpassword) >= 8:
if newpassword.isalpha()== False:
return True
return False
|
class Animal(object):
pass
class Dog(Animal):
def _init_(self,name):
self.name=name
class Cat(Animal):
def _init_(self,name):
self.name=name
class Person(object):
def _init_(self,name):
self.name=name
self.pet=None
class Employee(Person):
def _init_(self,name,salary):... |
def ncycle(input_iter, n: int):
r"""iterz.ncycle(input_iter)
This will cycle an iterator a certain number of times. Usage:
>>> alist = [1, 2, 4, 8]
>>> for item in iterz.ncycle(alist, 2)
... print(item)
1
2
4
8
1
2
4
8
In fact, it works with any iterable co... |
class Model:
def db_data(self):
print('Model called for data.')
data = 'Model Data.'
return data
class View:
def render(self, data):
print('Rendering model on view :' , data)
class Controller:
def __init__(self):
self.model = Model()
self.view = View()
... |
# -*- coding: utf-8 -*-
@auth.requires_login()
def gerar_exame():
id_consulta = request.args(0) or redirect(URL(c='consulta',
f='todas_consultas'))
consulta = db(db.consultas.id == id_consulta).select().first()
if not consulta:
raise HTTP(404)
p... |
n = (int(input()) - 1) % 8
if n == 0:
print(1)
elif n == 1 or n == 7:
print(2)
elif n == 2 or n == 6:
print(3)
elif n == 3 or n == 5:
print(4)
else:
print(5)
|
input=__import__('sys').stdin.readline;n=int(input());s=input();t=0;b=0
for i in range(n):
if s[i]=='O': t+=i+1+b;b+=1
else: b=0
print(t)
|
"""
NAME
simple string manipulations on the user's name
Ported by Dave LeCompte
"""
def is_yes_ish(answer: str) -> bool:
cleaned = answer.strip().upper()
if cleaned in ["Y", "YES"]:
return True
return False
def main() -> None:
print(" " * 34 + "NAME")
print(" " * 15 + "CREATIVE COMPUTI... |
# Copyright 2020-2021 Vytautas Liuolia
#
# 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... |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-13 14:42
@Project:InterView_Book
@Filename:link_7.py
@description:
利用链表层级打印二叉树
"""
'''
题目描述:
二叉树的打印方式有3种,分别是前序遍历、中序遍历、后序遍历。除此之外,还能按照层级,把处于不同层次的节点从
高到低依次打印
(1)、首先把根结点加入队列
(2)、把队列头节点打印出来,然后将该节点的左右孩子加入队列
(3)、重新执行步骤(2... |
#estrutura de repetição while;
#Criei uma função sem parâmetro e declarei uma variável local com valor zero;
#Após, escreva o comando while e forneça a condição;
#Depois escreva o que quer fazer e incrementa a variável para que o loop não seja infinito.
def estruturaRepeticao():
x = 0
while(x < 9):
pri... |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "org_specs2_classycle",
artifact = "org.specs2:classycle:1.4.3",
jar_sha256 = "9b8cc4f88a5fa8c0e9437ff72f472f9f8e2a7509d94261df6196d5570935d697",
srcjar_sha256... |
def map_to_server_type(predicted_class):
server_type = ''
if (predicted_class == 'two_thousand'):
server_type = 7
elif (predicted_class == 'fifty'):
server_type = 1
elif (predicted_class == 'one_hundred'):
server_type = 2
elif (predicted_class == 'two_hundred'):
serv... |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
try:
if number < 0 :
return 'complex numbers not supported'
elif number >= 0... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Special globbing for js libraries, including and excluding certain files"""
js_glob_exts = (
"gif",
"html",
"jpeg",
"jpg... |
#values added to dictionary recursively to save some time over iterative
def encode(arr,dictionary,ind):
#if gone through whole array
if ind == len(arr):
return dictionary
#if the letter/number has been seen before and exists in dictionary, increase the value by 1
elif arr[ind] in dictionary:
dictionary[arr[ind... |
VERSION = "2.0.1"
if __name__ == "__main__":
print(VERSION)
|
def parse_yaml(input_file):
"""Parse yaml file of configuration parameters."""
with open(input_file, "r") as yaml_file:
params = yaml.load(yaml_file)
return params
params = parse_yaml("preprocess_config.yaml")
ROOT = params["dirs"]["root"]
DATASET = os.path.join(ROOT, params["dirs"]["dataset"])
... |
# -*- Python -*-
"""Repository rule for Openvino configuration.
`openvino_configure` depends on the following environment variables:
* `INTEL_CVSDK_DIR`: The intel cv sdk install path.
* `InferenceEngine_DIR`: The library path which include intel inference engine library path.
"""
_INTEL_CVSDK_DIR = "INTEL_CVSDK... |
class ProcessUtil:
pass
# TODO: in separated classes:
# facade the psutil lib (in this class)
# check for facilitating the Popen call (in Process class that should be instantiable, as well as providing static methods to spawn process returning the raw Popen object)
# keep track of spawned syst... |
"""
Exercise 1
Write a function that reads the words in words.txt and
stores them as keys in a dictionary. It doesn’t matter what
the values are. Then you can use the in operator as a
fast way to check whether a string is in the dictionary.
"""
def function():
with open("words.txt") as fd:
wo... |
class Node():
"""
Class to create a new node.
"""
def __init__(self, data):
"""
Initializes an instance of a node with a *data*
attribute value equal to *data*.
"""
self.data = data
self.nxt = None
class Stack():
"""
Method to generate and modify... |
"""
We need the request object to get the user, so we'll slightly modify the
existing django.contrib.auth.get_user method. To do so we update the
auth middleware to point to our overridden method.
Calling the "patch_middleware_get_user" method somewhere like our urls.py
file takes care of hooking it in appropriately... |
# str - immutable sequence of Unicode codepoints
# str can be specified by delimiting with single quotes or double quotes
print("Python is beautiful")
print('Yes, I agree')
print("Don't you?")
print('"Yes!"')
s = """This is a
multiline
string
with newlines intact"""
print (s)
# Raw strings do not support any esca... |
# O(n*2^n) time | O(n*2^n) space
def powerset(array):
subsets = [[]]
for ele in array:
for i in range(len(subsets)):
currentSubset = subsets[i]
subsets.append(currentSubset + [ele])
return subsets |
nums = {0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten"}
feature = {0: "z", 1: "o", 2: "w", 3: "r", 4: "u", 5: "v", 6: "x", 7: "s", 8: "g", 9: "i", 10: "t"}
class Solution(object):
def originalDigits(self, s):
"""
:type s: ... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( m , n ) :
T = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ]
for i in range ( m + 1 ) :
... |
PHONE_NOT_EMPTY=1000
PHONE_NOT_FORMAT=1001
SMS_ERROR=1002
PHONE_SMS_NOT_EMPTY=1003
|
name= input("Enter file name: ")
fh = open(name)
for line in fh:
#line = line.rstrip()
for letter in line:
letter = letter.upper()
print(letter, end='')
fh.close()
# ou
print("\n=-=-=-=-=-=-=-=-=-=-=-=\n")
fh2 = open(name)
for line2 in fh2:
line2 = line2.rstrip()
print(l... |
# Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
# The successor of a node p is the node with the smallest key greater than p.val.
# Example 1:
# Input: root = [2,1,3], p = 1
# Output: 2
# Explanation: 1's in-order successor node is 2. Note that both p and the return... |
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# 1st soluton
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
d = {}
for w in strs:
key = tuple(sorted(w))
... |
opening = ['(']
closing = [')']
def search(string):
# basis
if not string:
return ""
stack, save = [], []
right = True
opening_num, closing_num = 0, 0
# search string
for idx, char in enumerate(string):
# opening
if char == '(':
stack.append(char)
... |
# Licensed to the White Turing under one or more
# contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except ... |
""" Asked by: Twitter [Hard].
You are given an array of length 24, where each element represents the number of new subscribers during the corresponding hour.
Implement a data structure that efficiently supports the following:
update(hour: int, value: int): Increment the element at index hour by value.
query(start: i... |
"""
面试题59:队列的最大值
题目2:队列的最大值
请定义一个队列并实现函数max得到队列里的最大值,要求函数max、push_back和
pop_front的时间复杂度都是O(1)。
"""
class Queue(object):
def __init__(self):
self.data = []
self.max_data = []
def pop(self):
"""
pop out the head element
:return: head element
"""
if not s... |
class Movie:
def __init__(self,id,title,overview,poster,vote_average,vote_count):
self.id =id
self.title = title
self.overview = overview
self.poster = 'https://image.tmdb.org/t/p/w500/'+ poster
self.vote_average = vote_average
self.vote_count = vote_count
|
Class(className = "Main", body = [
includeExternalFile("external"),
Def(functionName = "mergeStringArray", isStatic=True, returnType = "String", parameterNames = ["stringArray", "separator"], parameterTypes = ["String[]", "string"], body=[
makevar(arrayDimensions=0, variableType="string", initialValue="\"\"", varia... |
lista = []
print('Lista antes: ', lista)
lista.append('a')
lista.append('b')
lista.append('c')
lista.append('d')
lista.append('e')
lista.append('f')
lista.append('g')
lista.append('h')
lista.append('i')
lista.insert(4, "MEIO") #String adicionado a posição 4.
lista.insert(30, 'FIM') #Se o indíce no caso '30' for maio... |
#from .core import DummyInput
#from .core import Input
#from .defaults import create_input, create_pipe_input
__all__ = [
# Base.
"Input",
"DummyInput",
# Defaults.
"create_input",
"create_pipe_input",
]
|
# AC
A,B,C = map(int, input().split())
if C == 0:
if A > B:
print("Takahashi")
else:
print("Aoki")
if C == 1:
if A < B:
print("Aoki")
else:
print("Takahashi")
|
# The least common multiple (L.C.M.) of two numbers
# is the smallest positive integer that is perfectly
# divisible by the two given numbers.
def LCM_Funct(x,y):
if x > y:
greater = x
else:
greater = y
while(True):
if (greater % x == 0 ) and ( greater % y == 0 ):
... |
today = "hello world"
a=input("입력 해보세요: ")
print(a)
#print(today)
'''
default 파산, 기본, 관리되지 않은
>>> def apple(a):
... '입력 값은: '+a
1. 100만원으로 컴퓨터 조립해오기
-> 다나와 사이트 참고!
-> 카테고리
- cpu (컴퓨터 두뇌)
OS (운영체제 하드웨어(마우스, 키보드, 모니터, usb), 소프트웨어(프로그램)를 소통하게 해주는 장치)
OS의 연산(2진수 0,1)을 도와줌.
i3-6666, i5-888, i7-7888
- ram (... |
"""
Widgets from Evaluate category
"""
NAME = "Evaluate"
DESCRIPTION = "Evaluate classification/regression performance."
BACKGROUND = "#C3F3F3"
ICON = "icons/Category-Evaluate.svg"
PRIORITY = 5
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
mod = 1000000007
def find(i, p):
if p... |
"""
1474. Delete N Nodes After M Nodes of a Linked List
Given the head of a linked list and two integers m and n. Traverse the linked list and remove some nodes in the following way:
Start with the head as the current node.
Keep the first m nodes starting with the current node.
Remove the next n nodes
Keep repeating s... |
class ShoutterDiv2:
def count(self, s, t):
c = 0
for n, (i, j) in enumerate(zip(s, t)):
for k, l in zip(s[n + 1 :], t[n + 1 :]):
if i <= k <= j or k <= i <= l:
c += 1
return c
|
t = int(input())
def fill_lists(numbers, colors):
go_up, go_down = [], []
for i in range(len(numbers)):
if colors[i] == 'R':
if numbers[i] > len(numbers):
return [], [], False
go_up.append(numbers[i])
else:
if numbers[i] < 1:
... |
# encoding: utf-8
"""
Topic: 生成器表达式
Desc:
生成器是特定的函数,允许你返回一个值,然后'暂停'代码执行,稍后恢复。
列表解析的一个不足就是要一次性生成所有数据,对大量数据的迭代器是不好的
生成器表达式:生成器 + 列表解析,解决了这个问题
列表解析:
[expr for var in iterable if cond]
生成器表达式:
(expr for var in iterable if cond)
"""
__author__ = 'Xiong Neng'
def my_generate():
# 继续... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.