content stringlengths 7 1.05M |
|---|
@six.add_metaclass(BasicTestsMetaclass)
class ResourceListTests(BaseWebAPITestCase):
"""Testing the WatchedReviewGroupResource list API tests."""
fixtures = ["test_users"]
sample_api_url = "users/<username>/watched/review-groups/"
resource = resources.watched_review_group
def compare_item(self, item_rsp, obj):
w... |
# Take string, mirrors its string argument, and print result
def get_mirror(string):
# mirrors string argument
result = string + string[::-1]
return result
# Define main function
def main():
# Prompt user for a string
astring = input('Enter a string: ')
# Obtain mirror stri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def compute_short_chain(number):
"""Compute a short chain
Arguments:
number {int} -- Requested number for which to compute the square
Returns:
int -- Value of the square/short chain for the given number
"""
return number * number
... |
#!/usr/bin/env python3
# with_example02.py
class Sample:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print("type:", type)
print("value:", value)
print("trace:", trace)
def do_something(self):
bar = 1/0
return bar + 10
with Sa... |
class Node():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def __str__(self):
current = self.head
output = ''
while current:
output += f"{ {str(current.value)} } ->"
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 Raphaël Barrois
# This code is distributed under the two-clause BSD license.
__version__ = '0.12.3.1'
__author__ = 'Raphaël Barrois <raphael.barrois+xworkflows@polytechnique.org>'
|
"""Module containing the exception class for describe-get-system proof of concept module."""
class DGSError(Exception):
"""Use to capture error DGS construction."""
class TemplateStorageError(DGSError):
"""Use to capture error for TemplateStorage."""
class AdaptorAuthenticationError(DGSError):
"""Use ... |
N, M = map(int, input().split())
loop = (2**M)
print(1900*loop*M+100*(N-M)*loop)
|
def check_double(number):
if len(str(number))==(len(str(number*2))) and number!=number*2 :
return sorted(str(number)) == sorted(str(number*2))
return False
print(check_double(125874)) |
docs = """django-mc-commands
=======================
[](https://travis-ci.org/mc706/django-angular-scaffold)
[](http://badge.fury.io/py/django-angular-scaffold)
[![... |
DEBUG = False
TESTING = False
PROXY = False # True if app is proxied by Apache or similar.
# Application Settings
BROWSER_NAME = 'Bravo'
DATASET_NAME = 'Example Dataset' # Change to your dataset name
SHOW_POWERED_BY = False
NUM_SAMPLES = 0 # Change to the number of samples ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 04:08:08 2017
@author: Mayur
"""
# =============================================================================
# Problem 4 - Decrypt a Story
#
# For this problem, the graders will use our implementation of the Message,
# PlaintextMessage, and Ciphertext... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CertificateDetails(object):
"""Implementation of the 'CertificateDetails' model.
Specifies details about a certificate.
Attributes:
cert_file_name (string): Specifies the filename of the certificate.
This is unique to each... |
## Coding Conventions
# 'p' variables in p_<fun> are container() type
# possible scopes: package, global, functions, ....
global curr_scope
curr_scope = None
global scope_count
scope_count = 0
global temp_count
temp_count = 0
global label_count
label_count = 0
class ScopeTree:
def __init__(self, parent, scopeNa... |
test=int(input())
for y in range(test):
k,dig0,dig1=input().split()
k,dig0,dig1=int(k),int(dig0),int(dig1)
sum1=dig0+dig1
for i in range(3,k+2):
y=sum1%10
sum1+=y
if(y==2):
ter1=((k-i)//4)
ter1*=20
sum1+=ter1
ter=k-i
... |
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
h = []
for i, li in enumerate(mat):
l = self.countSoider(li)
heapq.heappush(h, (l, i))
ans = []
for _ in range(k):
ans.append(heapq.heappop(h)[1])
return ans... |
# This file is needs to be multi-lingual in both Python and POSIX
# shell which "execfile" or "source" it respectively.
# This file should define a variable VERSION which we use as the
# debugger version number.
VERSION='0.3.6'
|
class Solution(object):
def findReplaceString(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
finds = [S[idx:idx + len(source)] == source for idx, source i... |
# -*- coding: utf-8 -*-
"""
bandwidth
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class CallEngineModifyConferenceRequest(object):
"""Implementation of the 'CallEngineModifyConferenceRequest' model.
TODO: type model description here.
Attributes:
... |
"""
@name: PyHouse/src/Modules/Drivers/test/xml_drivers.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2014-2016 by D. Brian Kimmel
@license: MIT License
@note: Created on Nov 9, 2014
@Summary:
"""
DRIVERS_XML = """
"""
DRIVERS_XSD = """
?xml version="1.0" encoding="... |
tmp = 0
monday_temperatures = [9.1, 8.8, 7.5]
tmp = monday_temperatures.__getitem__(1)
tmp = monday_temperatures[1]
print(tmp) |
'''
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken i... |
class Map:
def __init__(self, filepath):
#first index will be y, second is x
self.data = list()
with open(filepath, "r") as f:
for line in f:
line = line.strip()
self.data.append(line)
self.width = len(self.data[0])
self.height = l... |
# https://www.hackerrank.com/challenges/s10-geometric-distribution-1/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
x,y=map(int,input().split())
z=int(input())
p=x/y
q=1-p
print(round((q**(z-1))*p,3)) |
"""
Used for passing custom exceptions form the configuration_service to the rest of the application.
"""
class ConfigurationError(Exception):
"""Raised when error occurred while loading or saving properties"""
pass
|
MP3_PREVIEW = "mp3_preview"
OGG_PREVIEW = "ogg_preview"
OGG_RELEASE = "ogg_release"
|
MAJOR_COLORS = ['White', 'Red', 'Black', 'Yellow', 'Violet']
MINOR_COLORS = ["Blue", "Orange", "Green", "Brown", "Slate"]
def print_color_code_mapping():
print('{:15} {:15} {:5} \n'.format('Major Color', 'Minor Color', 'Pair No.'))
for major_color_index, major_color in enumerate(MAJOR_COLORS):
for min... |
# coding: utf-8
# Define buildargs for cse api
BUILDARGS = {
'serviceName': 'customsearch',
'version': 'v1',
'developerKey': 'AIzaSyBqjfgcWEdMse4ghRYrbib8qv7avHFrp2Y'
}
# Define cseargs for search
CSEARGS = {
'q': '柯基犬',
'cx': '007397120899702103013:roufggcacti',
# 'num': 30
}
PROXIES = [{
'http': ... |
# 88. Merge Sorted Array
# ttungl@gmail.com
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Note:
# You may assume that nums1 has enough space (size that is greater or equal to m + n)
# to hold additional elements from nums2. The number of elements initialized in nums... |
"""
Happy Cobra - Marirs
Skeleton of a Login & Registration system
MIT License
"""
|
"""
Your job is to create a class Dictionary which you can add words to and their entries. Example:
d = Dictionary()
d.new_entry('Apple', 'A fruit that grows on trees')
print(d.look('Apple'))
A fruit that grows on trees
print(d.look('Banana'))
Can't find entry for Banana
"""
class Dictionary:
def __init__(se... |
CRITICAL_MARK_BEGIN = '<!-- BEGIN: django-critical css ('
CRITICAL_MARK_END = ') END: django-critical css -->'
CRITICAL_ASYNC_MARK = '<!-- django-critical async snippet -->'
CRITICAL_KEY_MARK_BEGIN = '<!-- BEGIN: django-critical key ('
CRITICAL_KEY_MARK_END = ') END: django-critical key -->'
|
l=[]
z=[]
def selection_sort(l):
for i in range(0,5):
MIN=min(l)
z.append(MIN)
l.remove(MIN)
return z
print("Enter Integer list of 5 values")
for i in range(0, 5):
x = int(input())
l.append(x)
print("List is: ",l)
print("Sorted list is: ",selection_sort(l))
|
"""
The ``memory`` taxon groups applets implementing interfaces to memory technology devices (volatile
and non-volatile) that include no functionality beyond manipulating data.
Examples: SPI flash, I²C EEPROM.
Counterexamples: SPI flash on an FPGA board that requires coordinated reset (use taxon
``program``), flash ma... |
load("//tools/jest:jest.bzl", _jest_test = "jest_test")
load("//tools/go:go.bzl", _test_go_fmt = "test_go_fmt")
load("@io_bazel_rules_go//go:def.bzl", _go_binary = "go_binary", _go_library = "go_library", _go_test = "go_test")
load("@npm//@bazel/typescript:index.bzl", _ts_config = "ts_config", _ts_project = "ts_project... |
antenna = int(input())
eyes = int(input())
if antenna>=3 and eyes<=4:
print("TroyMartian")
if antenna<=6 and eyes>=2:
print("VladSaturnian")
if antenna<=2 and eyes<= 3:
print("GraemeMercurian")
|
# test builtin abs function with float args
for val in (
"1.0",
"-1.0",
"0.0",
"-0.0",
"nan",
"-nan",
"inf",
"-inf",
):
print(val, abs(float(val)))
|
'''
Faça um Programa que mostre a mensagem "Alo mundo" na tela.
'''
print('Alô, mundo!')
|
# Big O complexity
# O(log2(n))
# works only on sorted array
# recursive
def binary_search_recursive(arr, arg, left, right):
if right >= left:
middle = left + (right - left) // 2
if arr[middle] == arg:
return middle
elif arr[middle] > arg:
return binary_search_recu... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 26 19:20:16 2022
@author: ARYAMAN
"""
word_list =[]
with open("corncob_caps.txt", "r") as words:
lines = words.readlines()
final_list = []
for l in lines:
final_list.append(l.replace("\n","")) |
s = input("s: ")
t = input("t: ")
if s == t:
print("Same")
else:
print("Different") |
def par(n=0):
if n % 2 == 0:
return True
else:
return False
# Programa principal
num = int(input('Digite um número: '))
if par(num):
print('É PAR.')
else:
print('NÃO É PAR.')
|
'''Deoxyribonucleic acid (DNA) is a chemical found in the nucleus
of cells and carries the "instructions" for the development and functioning of living organisms.
If you want to know more http://en.wikipedia.org/wiki/DNA
In DNA strings, symbols "A" and "T" are complements of each other,
as "C" and "G". You have functi... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# @name : E-ntel - Email Information Gathering
# @url : http://github.com/CybernetiX-S3C
# @author : John Modica (CybernetiX S3C)
R = "\033[%s;31m"
B = "\033[%s;34m"
G = "\033[%s;32m"
W = "\033[%s;38m"
Y = "\033[%s;33m"
E = "\033[0m" |
# dummy wordlist
# by Jeeb
# Information about your version of Wordle
Metadata = {
"name": "Dummy",
"version": "dummy",
"guesses": 4,
"launch": (2222, 2, 16),
"boxes": ["[]", "!!", "<3", " ", " "],
"colors": [0x1666666, 0x1bb9900, 0x1008800, 0xe8e8e8, 0x1222222],
"keyboard": ["a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 08:56:55 2017
@author: Nadiar
"""
balance = 320000
annualInterestRate = 0.2
"""
Monthly interest rate = (Annual interest rate) / 12.0
Monthly payment lower bound = Balance / 12
Monthly payment upper bound =
(Balance x (1 + Monthly interest ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 14:04:56 2021
@author: rowe1
"""
def a_star(start, target, tail, grid, graph, obstacles):
"""
Uses a_star heuristic to find a path from start to target and back to tail.
If such a path exists, return the path from start to target.
If such a path d... |
a = a+1
a += 1
b = b-5
b -= 5
|
class FieldC():
def __init__(self, name, column_type, primary_key, default):
self.name = name
self.column_type = column_type
self.primary_key = primary_key
self.default = default
def __str__(self):
return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type... |
#line = r'''execute if score waveGlowTimer glowTimer matches %s run tag @e[type=!player,type=!dolphin,distance=%s,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}] add madeGlowing'''
#type=!player,type=!dolphin,distance=16..20,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}
line =... |
# Used in setup.py
# -*- coding: utf-8 -*-
VERSION = "0.1.1"
PROJECT_PACKAGE_NAME = "lupupy"
PROJECT_LICENSE = "MIT"
PROJECT_URL = "http://www.github.com/majuss/lupupy"
PROJECT_DESCRIPTION = "A python cli for Lupusec alarm panels."
PROJECT_LONG_DESCRIPTION = (
"lupupy is a python3 interface for"
" the Lupus Ele... |
n,m=map(int,input().split())
x=[i for i in range(1,n+1)]
for i in range(m):
a,b=map(int,input().split())
x[a-1],x[b-1]=x[b-1],x[a-1]
for i in x: print(i,end=' ') |
class DimError(Exception):
code = 1
error_types = dict(
InvalidPoolError=2,
InvalidIPError=3,
InvalidVLANError=4,
InvalidStatusError=5,
InvalidPriorityError=6,
InvalidGroupError=7,
InvalidUserError=8,
InvalidAccessRightError=9,
InvalidZoneError=10,
InvalidViewError=11,
... |
# ------------------------------------------------------------------------------
# Path setup
# Variables ending in _PATH are used as URL paths; those ending with _FSPATH
# are filesystem paths.
# For a single board setup (wakaba style), set SITE_PATH to / and point
# MATSUBA_PATH to /boardname/matsuba.py
# The base... |
def test_standard(hatch, config_file, helpers):
result = hatch('config', 'set', 'project', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
project = "foo"
"""
)
config_file.load()
assert config_file.mod... |
info = {
"name": "smn",
"date_order": "DMY",
"january": [
"uđiv",
"uđđâivemáánu"
],
"february": [
"kuovâ",
"kuovâmáánu"
],
"march": [
"njuhčâ",
"njuhčâmáánu"
],
"april": [
"cuáŋui",
"cuáŋuimáánu"
],
"may": [
... |
"""Dummy class that does not inherit from the required AbstractObjectDetection."""
class ObjectDetection:
"""Dummy class that does not inherit from the required AbstractObjectDetection."""
|
def get_part_of_line(line, delimiter=";"):
try:
del_index = line.index(delimiter)
return line[:del_index], line[del_index + 1 :]
except ValueError:
return line, ""
def is_line_valid(line):
parts = line.split(";")
if not parts[-1] or parts[-1] == "0":
# If the last part ... |
class Solution:
def judgeCircle(self, moves: str) -> bool:
"""String.
Running time: O(n) where n == len(moves).
"""
r, l, u, d = 0, 0, 0, 0
for m in moves:
if m == 'U':
u += 1
elif m == 'D':
d += 1
elif m ==... |
def type(a,b):
if isinstance(a,int) and isinstance(b,int):
return a+b
return 'Not integer type'
print(type(2,3))
print(type('a','boy')) |
obj0 = SystemBusNode()
obj1 = SystemBusDeviceNode(
qom_type = "TYPE_INTERRUPT_CONTROLLER",
system_bus = obj0,
var_base = "interrupt_controller"
)
obj2 = SystemBusDeviceNode(
qom_type = "TYPE_UART",
system_bus = obj0,
var_base = "uart"
)
obj3 = DeviceNode(
qom_type = "TYPE_CPU",
var_ba... |
"""
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Solution:
- It's a typical binary search with a slight variatio... |
FALSE=0
TRUE=1
DBSAVE=1
DBNOSAVE=0
INT_EXIT=0
INT_CONTINUE=1
INT_CANCEL=2
INT_TIMEOUT=3
DBMAXNUMLEN=33
DBMAXNAME=30
DBVERSION_UNKNOWN=0
DBVERSION_46=1
DBVERSION_100=2
DBVERSION_42=3
DBVERSION_70=4
DBVERSION_71=5
DBVERSION_72=6
DBTDS_UNKNOWN=0
DBTXPLEN=16
BCPMAXERRS=1
BCPFIRST=2
BCPLAST=3
BCPBATCH=4
BCPKEEPIDENTITY=8
BC... |
# O(N) where n is len of string
def get_str_zig_zagged(s, numRows):
if numRows == 1:
return s
ret = ''
n = len(s)
cycle_len = numRows*2 - 2
for i in range(numRows):
j = 0
while j +i < n:
ret += s[j+i]
if (i != 0 and i != numRows -1 and j + cycle_len -i... |
"""
A. The reconstructions preserve most of the latent features well:
- shape: ovals shapes are well preserved, whereas squares lose some sharpness
in their edges. Hearts are poorly preserved, as the sharp angles of their edges are lost.
- scale: shape scales are well preserved.
- orientation: orientations a... |
red = 0
black = 1
empty = 2
#Expected Outcome: True
row_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, red, red, red, red, empty, empty],
[red, black, red, black, red, empty, empty],
[black, red, black, red, ... |
class Vertex:
def __init__(self, value):
self.value = value
self.edges = {}
def add_edge(self, vertex, weight=0):
self.edges[vertex] = weight
def get_edges(self):
return list(self.edges.keys())
class Graph:
def __init__(self, directed = False):
self.graph_dict ... |
"""
@author: David Lei
@since: 6/11/2017
https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem
Given the head to a doubly linked list reverse it and return the head of the reversed list.
Both pass :)
"""
def ReverseIterative(head):
if not head:
return head
cur = head
while c... |
class Pessoa:
olhos = 2
def __init__(self, *filhos,nome=None, idade=35):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá {id(self)}'
@staticmethod
def metodo_estatico():
return 42
@classmethod
def n... |
N = int(input())
if N <= 5:
print(N + 2)
elif N == 6:
print('1')
else:
print('2')
|
class ManipulationVelocities(object):
"""
Describes the speed at which manipulations occurs.
ManipulationVelocities(linearVelocity: Vector,angularVelocity: float,expansionVelocity: Vector)
"""
@staticmethod
def __new__(self,linearVelocity,angularVelocity,expansionVelocity):
""" __new__(cls: type,lin... |
# First step printing UI
def drawFields(field):
for row in range(5):
if row % 2 == 0:
fieldRow = int(row / 2)
for column in range(5): # 0,1,2,3,4 --> 0,.,1,.,2
if column % 2 == 0: # 0,2,4
fieldColumn = int(column / 2) # 0,1,2
... |
# print index of string
str_one = 'python land is a place for everyone not just beginner'
# 012345
print(str_one[0]) # print the first letter of our string str-one
print(str_one[-1]) # pring the last letter of our string str_one
# print special range of string
print(str_one[0:4]) # reult will be from index 0 ti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 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.0
#
# Unless... |
# https://leetcode.com/problems/excel-sheet-column-title/
# ---------------------------------------------------
# Runtime Complexity: O(log26(n)) => O(log(n))
# Space Complexity: O(log26(n)) => O(log(n)), if we take into account res, otherwise it's O(1).
class Solution:
def convertToTitle(self, n: int) -> str:
... |
###############################################################################
##
## protoql.py
##
## A language for rapid assembly, querying, and interactive visual rendering
## of common, abstract mathematical structures.
##
## Web: protoql.org
## Version: 0.0.3.0
##
##
####################################... |
#coding=utf-8
'''
更新节点的定位信息:Locate_UpdateDevPosition
request:
{
"user_id":"1", #设备所属的用户
"lat":33.1111111, #经度
"lon":108.1111111, #维度
"dev_id":1, #模块的id
"accuracy":100, #定位经度为100单位cm
"time_s":"2018-02-28 17:23:20.111" #定位时间
"power":100, #电量为百分数
"locate_method":"GPS" #定位方式为GP... |
# Dana jest tablica n liczb. Proszę zaproponować algorytm który stwierdza czy pewna liczba
# występuje w ciągu > (więcej niż) n/2 razy.
def leader(T):
count = 1
leader = T[0]
for i in range(1, len(T)):
if T[i] == leader:
count += 1
else:
if count > 0:
... |
class DataDictException(Exception):
def __init__(self, message, data_dict=None, exc=None):
self._message = message
if data_dict is None:
data_dict = {}
formatted_data_dict = {}
for key, value in data_dict.items():
formatted_data_dict[str(key)] = str(value)
... |
def hello_request(data):
data['type'] = 'hello_request'
return data
def hello_response(data):
data['type'] = 'hello_reply'
return data
def goodbye(data):
data['type'] = 'goodbye'
return data
def ok():
return {'type': 'ok'}
def shout(data):
data['type'] = 'shout'
return data
... |
# The new config inherits a base config to highlight the necessary modification
_base_ = '../cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco.py'
# We also need to change the num_classes in head to match the dataset's annotation
model = dict(
roi_head=dict(
bbox_head=[
dict(type='S... |
class Solution:
def maxCoins(self, piles: List[int]) -> int:
piles=sorted(piles)
n=len(piles)
answer=0
for i in range(int(n/3),n, 2):
answer+=piles[i]
return answer
|
m: int; n: int; i: int; j: int
m = int(input("Qual a quantidade de linhas da matriz? "))
n = int(input("Qual a quantidade de colunas da matriz? "))
mat: [[int]] = [[0 for x in range(n)] for x in range(m)]
for i in range(0, m):
for j in range(0, n):
mat[i][j] = int(input(f"Elemento [{i},{j}]: "))
print("... |
#MenuTitle: Change LayerColor to Purple
# -*- coding: utf-8 -*-
font = Glyphs.font
selectedLayers = font.selectedLayers
for thisLayer in selectedLayers:
thisGlyph = thisLayer.parent
thisGlyph.layers[font.selectedFontMaster.id].color = 8
|
# Line SPW setup for 17B-162 w/ rest frequencies
# SPW $: [Name, Restfreq, Num chans, Chans for uvcontsub]
# Notes for uvcontsub channels:
# - Avoid first and last 5% of channels in a SPW
# - Avoid -80 to -280 km/s for M33
# - Avoid -30 to 30 km/s for MW
# Channel offset b/w cubes made with test_line_imaging.py (ex... |
'''
Input
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!
Example
Sample input:
4
1
2
5
3
Sample output:
1
2
120
6
'''
t=int(input())
... |
VERSION = "0.1a"
class Port(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def __init__(self, portType):
self.portType = portType
return
def isType(self, _type):
if _type == self.portType:
return True
return False
class Component(objec... |
# -*- coding: utf-8 -*-
# Questo è l'elenco di tutte le stringhe usate in Royal Mifia.
# Modificando qui si dovrebbe riuscire a tradurre il gioco e rendere la modifica più semplice.
# Royal: icona
royal_icon = "\U0001F610"
# Royal: nome ruolo
royal_name = "Royal"
# Mifioso: icona
mifia_icon = "\U0001F47F"
# Mifioso... |
number = int(input())
dp = []
dp.append([0, 1])
for n in range(1, number):
dp.append([])
dp[n].append(sum(dp[n-1])) # 0
dp[n].append(dp[n-1][0]) # 1
print(sum(dp[number-1]))
|
#!/usr/bin/env python3
with open('challenge67_data.txt', 'r') as f:
triangle = [[int(i) for i in l.split(' ')] for l in f.readlines()]
longest_paths = [[0] * (i+1) for i in range(len(triangle))]
# edges between x and x + 1
# Algorithm:
# Start at top
# Go to each branch, make note of the longest path to... |
media_filter_parameter_schema = [
{
'name': 'media_id',
'in': 'query',
'required': False,
'description': 'List of integers identifying media.',
'explode': False,
'schema': {
'type': 'array',
'items': {
'type': 'integer',
... |
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
nLen = len(nums) - 1
nums.sort()
fidx = nLen // 2
sidx = nLen // 2 + 1
swapIdx = 0
whi... |
class Request:
def __init__(self,number, time):
self.number = number
self.time = time
|
# abrir y leer archivo
f = open ('input.txt','r')
mensaje = f.read()
f.close()
# divido por linea y guardo en una lista
list_sits = mensaje.split('\n')
def extractRow(row,ini,end):
ini = ini
end = end
distance = end - ini
current = list(row)
for i in current:
distance = int(d... |
"""
[2015-12-09] Challenge #244 [Intermediate] Higher order functions Array language (part 2)
https://www.reddit.com/r/dailyprogrammer/comments/3w324a/20151209_challenge_244_intermediate_higher_order/
Monday's challenge is a prerequisite. Sorry.
# J theory
Adverbs and Conjunctions in J (modifiers as a shorter group ... |
w, h, n = map(int, input().split())
def k_fit_dip(side):
w_k = side // w
h_k = side // h
return w_k * h_k
def size_search():
left = 0
right = 10 ** 14
while right - left > 1:
mid = (right + left) // 2
k_dip = k_fit_dip(mid)
if k_dip >= n:
right =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 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.0
#
# Unless... |
"""
Copy List with Random Pointer
A linked list of length n is given such that each node contains an additional random pointer,
which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes,
where each new node has its value set to ... |
# Tuples is an immutable object in Python. It means once data is set, you cannot change those data.
# Can be used for constant data or dictionary without key (nested tuples)
# Empty Tuple initialization
tup = ()
print(tup)
# Tuple initialization with data
# I didn't like this way thought ;)
tup1 = 'python', 'aws', 's... |
class CombinationIterator:
def __init__(self, characters, combinationLength):
self.characters = characters
self.combinationLength = combinationLength
self.every_comb = self.generate()
def generate(self):
every_comb = []
for i in range(2**len(self.characters)):
string = ""
for j in r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.