content stringlengths 7 1.05M |
|---|
"""
112 / 112 test cases passed.
Runtime: 132 ms
Memory Usage: 19.9 MB
"""
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
n = len(graph)
rg = [[] for _ in range(n)]
in_deg = [0] * n
for sr, scs in enumerate(graph):
for sc in scs:
... |
"""
古代的秤,一斤十六两。在终端中获取两,计算几斤零几两。
效果:
请输入总两数:100
结果为:6斤4两
"""
weight = int(input("请输入总两数:"))
jin = weight // 16
liang = weight % 16
print("结果为:" + str(jin) + "斤" + str(liang) + "两")
|
class PNMessageCountResult(object):
def __init__(self, result):
"""
Representation of message count server response
:param result: result of message count operation
"""
self._result = result
self.channels = result['channels']
def __str__(self):
return "M... |
# s: "The quick, superduperlong brown fox jumped over the lazy dog."
# limit: 10
# output: [
# "The quick,",
# "superduperlong",
# "brown fox",
# "jumped",
# "over the",
# "lazy dog.",
# ]
#
# s: ""
# output: [""]
# if single word exceeds limit, count it as its own entry in the output.
abc = "The qui... |
ES_HOST = 'localhost:9200'
ES_INDEX = 'pending-pathway'
ES_DOC_TYPE = 'geneset'
API_PREFIX = 'geneset'
API_VERSION = ''
|
CREATE_REPORTS = ('CREATE TABLE reports '
'(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'
'bug_id INTEGER NOT NULL,'
'current_resolution TEXT,'
'current_status TEXT,'
'opening INTEGER NOT NULL,'
'reporter INTEG... |
"""Authn/z-related exceptions raised by components in this module."""
class InvalidToken(ValueError):
"""Token in request is not valid."""
class MissingToken(ValueError):
"""No token found in request."""
class ConfigurationError(RuntimeError):
"""The application is not configured correctly."""
class... |
class Indent():
"""
indentation context
"""
def __init__(self, autoIndentStream):
self.s = autoIndentStream
self.original_indent = None
def __enter__(self):
s = self.s
self.original_indent = s.indent_str
s.indent_cnt += 1
s.indent_str = s.indent_str... |
"Generate a Kaggle submission file from VW predictions"
loc_preds = "data/shop.preds.txt"
loc_submission = "data/kaggle.submission.csv"
loc_test = "data/testHistory.csv"
def generate_submission(loc_preds, loc_test, loc_submission):
preds = {}
for e, line in enumerate( open(loc_preds) ):
row = line.strip().split("... |
#############################################################################
# Copyright (c) 2017 Rajesh Kudaka
#
# Author: Rajesh Kudaka 4k.rajesh@gmail.com
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies th... |
'''
Author : Arnob Mahmud
Mail : arnob.tech.me @ gmail.com
'''
num = int(input("Enter starting number :"))
n = int(input("Enter ending number :"))
i = num
while i <= n:
print(i)
if i % 13 == 0:
break; # Breaks the loop if the upper condition been right
i = i + 1
|
def make_node():
pass
def make_value_info():
pass
|
categorie="TELEPHONIE - GPS"
all_descr_clean_stem = " ".join(data[data.Categorie1==categorie].Description_cleaned.values)
wordcloud_word = WordCloud(background_color="black", collocations=False).generate_from_text(all_descr_clean_stem)
plt.figure(figsize=(10,10))
plt.imshow(wordcloud_word,cmap=plt.cm.Paired)
plt.axis(... |
####################################################################################################################
# Functions - Lab Exercise 2
#
# Write a function called odds_or_evens that takes a boolean and a list of integers as parameters.
# If the boolean parameter is True, r... |
def minutes_to_hours(seconds, minutes=70):
hours = minutes / 60.0 + seconds / 3600
return hours
print(minutes_to_hours(300, 200))
# oppure si puo' scrivere:
# def minutes_to_hours(seconds, minutes=70):
# hours = minutes / 60.0 + seconds / 3600
# print(hours)
# (minutes_to_hours(300, 200))
# for ... |
# 141, Суптеля Владислав
# 【Дата】:「19.03.20」
# 7. Описати рекурсивную функцію GCD (A, B) цілого типу, яка знаходить найбільший спільний дільник (НСД, greatest common divisor)
# двох цілих позитивних чисел A і B, використовуючи алгоритм Евкліда: НСД (A, B) = НСД (B, A mod B), B ≠ 0; НСД (A, 0) = A,
# де «mod» позначає о... |
def count_values(dictionary):
"""
"""
seen_values = set()
for i in dictionary:
seen_values.add(dictionary[i])
return len(seen_values)
print(count_values({'red': 1, 'green': 1, 'blue': 2, 'yellow': 3, 'purp': 2}))
|
i = 1
for n in range(5):
globals()["w" + str(i)] = "adi"
i += 1
print(w2) |
class Serialreader:
def __init__(self, s):
self.buf = bytearray()
self.s = s
def readline(self):
i = self.buf.find(b"\r")
if i >= 0:
r = self.buf[:i+1]
self.buf = self.buf[i+1:]
return r
while True:
i = max(1, min(2048, sel... |
i = int(input("Enter a number: "))
if i%5 == 0:
print('Hello')
else:
print('Bye')
|
class Helper:
"""
Container for helper functions
"""
@staticmethod
def chunks(l, n):
"""
Yield successive n-sized chunks from l.
"""
for i in range(0, len(l), n):
yield l[i:i + n]
@staticmethod
def find_pattern(header, pattern):
... |
class Users(THE_DATABASE.Model):
# this uses SqlAlchemy to create User classes when pulling data from the database
__tablename__ = 'Users'
username = THE_DATABASE.Column(THE_DATABASE.String(128),primary_key = True)
password = THE_DATABASE.Column(THE_DATABASE.String(64))
def __init__(self,input_user... |
t=int(input())
for i in range(t):
x1,x2,y1,y2,z1,z2=map(int,input().split())
if(x1<=x2 and y1<=y2 and z1>=z2):
print("yes")
else:
print("no")
|
# time 30mins
# cost: 22 mins
# actually i was thinking of it in shower, so takes more time than recorded
class Solution:
"""
@param S: A set of numbers.
@return: A list of lists. All valid subsets.
"""
def subsetsWithDup(self, S):
# recursive
S.sort()
firs... |
def new():
pass
|
"""
Horizontal Split Panel: Left and Right layouts with a movable splitter.
/*
* Copyright 2008 Google Inc.
* Copyright 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
*
* Licensed under the Apache License, Version 2.0 (the "License") you may not
* use this file except in compliance with the License. You m... |
class LeadRecord:
def __init__(self):
self.attributes = {}
def __str__(self):
return "Lead (%s - %s)" % (self.id, self.email)
def __repr__(self):
return self.__str__()
def unwrap(xml):
lead = LeadRecord()
lead.id = xml.find('Id').text
lead.email = xml.find('Email')... |
#
# @lc app=leetcode id=69 lang=python3
#
# [69] Sqrt(x)
#
# https://leetcode.com/problems/sqrtx/description/
#
# algorithms
# Easy (30.94%)
# Total Accepted: 351.7K
# Total Submissions: 1.1M
# Testcase Example: '4'
#
# Implement int sqrt(int x).
#
# Compute and return the square root of x, where x is guaranteed to... |
# def pow2(x):
# return x**2
# for x in map(pow2, range(1,5)):
# print(x)
# for n in map(pow, range(1,10), range(4,0,-1)):
# print(n)
#==========practice=============
#1. 1**2 + 2**2 + 3**2........+9**2
print("pow2 total is: ",sum(map(lambda x: x**2, range(1,10))))
#2. 1**3 + 2**3 + 3**3........+9**3
to... |
# a*x+b=y
def a_line (a,b):
# def arg_y (x):
# y = a*x+b
# return y
y = lambda x:a*x+b
return y
# a=3,b=5
# x=10,y=?
# x=20,y=?
line1 = a_line(3,5)
line2 = a_line(5,10)
print(line1(10))
print(line1(20))
print(line2(10))
print(line2(20)) |
#!/usr/bin/env python
# coding=utf-8
# author: zengyuetian
if __name__ == '__main__':
pass |
class Solution:
def longestAwesome(self, s: str) -> int:
ans = 0
prefix = 0 # binary prefix
prefixToIndex = [len(s)] * 1024
prefixToIndex[0] = -1
for i, c in enumerate(s):
prefix ^= 1 << ord(c) - ord('0')
ans = max(ans, i - prefixToIndex[prefix])
for j in range(10):
ans... |
"""选做)一个小球从100m高度落下,每次弹回原高度一半.
计算:
-- 总共弹起多少次?(最小弹起高度0.01m)
-- 全过程总共移动多少米?
提示:
数据/算法"""
times=0
r=0
hight=float(input("请输入下落的高度:"))
while True:
sum=hight+hight/2
r+=sum
hight=hight/2
if hight<=0.01:
break
times+=1
print("一共弹了%d次,共移动%.9f米"%(times,r))
|
__author__ = 'Tyler Rudie'
class article(object):
Date = ''
Publisher = ''
Title = ''
URL = ''
Term = ''
def __init__(self, Date, Publisher, Title, URL, Term):
self.Date = Date
self.Publisher = Publisher
se... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class CakeError(Exception):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
|
#
# PySNMP MIB module HH3C-EPON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-EPON-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:13:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
#
# PySNMP MIB module COMMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COMMON-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:26:30 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:... |
"""
Author: Resul Emre AYGAN
"""
"""
Project Description: Find The Parity Outlier
You are given an array (which will have a length of at least 3, but could be very large) containing integers.
The array is either entirely comprised of odd integers or entirely comprised of even integers except
for a single integer N.
W... |
class singleton:
def __init__(self, undecoratedClass):
self.undecoratedClass = undecoratedClass
self.instance = None
def __call__(self, *args, **kwargs):
print(self.undecoratedClass.closed)
if self.undecoratedClass.closed is True:
self.instance = None
if se... |
# https://app.codesignal.com/interview-practice/task/dYCH8sdnxGf5aGkez/solutions
def decodeString(string):
final_output = []
for c in string:
if c != ']':
final_output.append(c)
else:
s = []
while(final_output[-1] != '['):
s.append(final_output... |
"Rules to verify and update pip-compile locked requirements.txt"
load("//python:defs.bzl", "py_binary", "py_test")
load("//python/pip_install:repositories.bzl", "requirement")
def compile_pip_requirements(
name,
extra_args = [],
visibility = ["//visibility:private"],
requirements_in = ... |
def is_valid(r, c, size):
if 0 <= r < size and 0 <= c < size:
return True
return False
n = int(input())
matrix = []
for _ in range(n):
matrix.append([int(el) for el in input().split()])
all_directions = {
"up": (-1, 0),
"down": (1, 0),
"left": (0, -1),
"right": (0, 1),
"up_lef... |
'''
Logging module for Sublime Text plugins. Tries to emulate normal Python logger.
by @blopker
'''
debug = False
class Logger(object):
def __init__(self, name):
self.name = name
def debug(self, *messages):
if not debug:
return
self._out('DEBUG', *messages)
def info(... |
# Recursers can create their personal access token at https://www.recurse.com/settings/apps
# To use the tool, create your personal access token and replace the fake access token below.
PERSONAL_ACCESS_TOKEN = "123456"
AUTH_HEADER = {"Authorization": "Bearer {}".format(PERSONAL_ACCESS_TOKEN)}
|
def is_alphanumeric(word: str, valid_punctuation_marks: str = '-') -> bool:
"""
Check if a word contains only alpha-numeric
characters and valid punctuation marks.
Parameters
----------
word: `str`
The given word
valid_punctuation_marks: `str`
Punctuation marks that are val... |
"""
embedeval
~~~~~~~~~
NLP Embedding Evaluation Tool
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
|
# Variables
center_x=50
center_y=50
diameter=10
ellipse(center_x,center_y,diameter,diameter)
# Variables allow us to make changes on them
# Let's make some changes on the variables
diameter=diameter+2
center_x=center_x+diameter
ellipse(center_x,center_y,diameter,diameter)
diameter=diameter+2
center_x=center_x+diamet... |
"""
[07/17/13] Challenge #130 [Intermediate] Foot-Traffic Generator
https://www.reddit.com/r/dailyprogrammer/comments/1ihm0q/071713_challenge_130_intermediate_foottraffic/
# [](#IntermediateIcon) *(Intermediate)*: Foot-Traffic Generator
This week's [Easy] challenge was [#133: Foot-Traffic
Analysis](http://www.reddit.... |
class Solution:
def solve(self, a, b, c):
dp = [[[0]*(len(c)+1) for j in range(len(b)+1)] for i in range(len(a)+1)]
ans = 0
for i in range(1,len(a)+1):
for j in range(1,len(b)+1):
for k in range(1,len(c)+1):
if a[i-1] == b[j-1] == c[k-1]:
... |
"""
Configuration file for the Python Atmospheric data Community Toolkit (ACT)
The values for a number of ACT parameters and the default metadata created
when reading files, correcting fields, etc. is controlled by this single
Python configuration file.
Examples:
---------
from act.config import DEFAULT_DATASTREAM_NAM... |
'''
Given the head of a singly linked list, reverse the list, and return the reversed list.
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head):
cur = head
p... |
#Upon clicking, saves everything in hdf5 queue. Meant to be click after "Start" has already been pressed
def save(arr_in):
# HDF5
try:
hdf5.queue.put_nowait((frame_time, data_cube_corr))
num_cubes_stored += 1 # executed if above was successful
except:
pass
... |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
N = len(A)
if N <= 1: return 0
start_list = []
end_list = []
for i, radius in enumerate(A):
left, right = i - radius, i + radius
start_list... |
n = int(input())
s = input()
def remove(s):
actC = 'a'
actI = -1
for i in range(len(s)):
if i > 0:
if ord(s[i])-ord(s[i-1]) == 1 and s[i] > actC:
actC = s[i]
actI = i
if i < len(s)-1:
if ord(s[i])-ord(s[i+1]) == 1 and s[i] > actC:
... |
class Sender:
def __init__(self):
self.subscribers = []
def __call__(self, *args, **kwargs):
for subscriber in self.subscribers:
subscriber(*args, **kwargs)
def __iadd__(self, handler):
self.subscribers.append(handler)
return self
def __isub__(self, handler... |
config = {
"palette": [255],
"loss": "bce_dice",
"gamma": 2.0, # focal loss gamma
"optimizer": "sgd",
"freeze": False,
"freeze_at": 24,
"dropout_rate": 0.1,
"momentum": 0.9,
"learning_rate": 0.1,
# (216, 320, 1) # (270, 400, 1) # (432, 640, 1)
"image_size": (216, 320, 1),
... |
a = -1
if a > 0:
print("a c'est mieux que zéro")
elif a == 0:
print("a c'est null")
else:
print("la tete sous l'eau") |
"""
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a desce... |
# 6 завдання
buttons = ["alt", "ctrl", "shift"]
button1 = input()
if button1 in buttons:
print("Тривогааа!!!!")
else:
print("Гомера звільнять")
|
class InvestmentProperty:
REQUIRED_KW_ARGS = []
#####################################
# Required args for instantiation:
#####################################
# property (dict):
# list_price=float
# maintenance_costs_monthly:float
# other_costs_monthly:float
# propert... |
__author__ = 'Chetan'
class Actor(object):
def __init__(self):
self.isBusy = False
def occupied(self):
self.isBusy = True
print(type(self).__name__ , "is occupied with current movie")
def available(self):
self.isBusy = False
print(type(sel... |
class UserListSubclass(list):
def __getslice__(self, i, j):
return self.__getitem__(slice(i, j))
def __setslice__(self, i, j, seq):
return self.__setitem__(slice(i, j), seq)
def __delslice__(self, i, j):
return self.__delitem__(slice(i, j))
# Subclass this class if you need to overw... |
li = [123, 456, 567, 789]
param = 456
if param in li:
print(li.index(param))
li = []
if not li:
print('[]')
else:
print('True') |
# https://leetcode.com/problems/remove-duplicates-from-sorted-array/
# Runtime: 138 ms, faster than 47.61% of Python3 online submissions for Remove Duplicates from Sorted Array.
# Memory Usage: 15.6 MB, less than 21.60% of Python3 online submissions for Remove Duplicates from Sorted Array.
class Solution:
def re... |
annual_salary = input("Enter your annual income: ")
if len(annual_salary) < 1 : annual_salary = 150000
annual_salary = float(annual_salary)
total_cost = 1000000.00
semi_annual_raise = 0.07
portion_down_payment = 0.25
r = 0.04
down_payment = total_cost * portion_down_payment
portion_saved = 0
portion_percent = 0.0
por... |
class Timer:
def __init__(self, time, delegate):
self.delegate = delegate
self.time = time
self.elapsed = 0
self.active = True
self.payload = None
self.name = ""
def step(self, dt):
if not self.active:
return
self.elapsed += dt
... |
PROGRAMS = [ { 'desc': 'A time-based quiz game to see how fast you can alphabetize letters.\nTags: short, game, word\n',
'filename': 'alphabetizequiz.py',
'hash': 1042153501,
'name': 'Alphabetize Quiz'},
{ 'desc': 'A deductive logic game where you must guess a number based on clues.\n'... |
class GameState():
def __init__(self):
self.board = [
["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
... |
# Complete the compareTriplets function below.
class Triplets:
def __init__(self):
self.result = [0,0]
def compareTriplets(self, a, b):
if self.problem_clarity(a, b) and self.originality(a, b):
return self.difficulty(a, b)
return None
def problem_clarity(self, a, b):
... |
with open('task3.html', 'w') as f:
f.write('<html><body><table>\n')
for i in range(1, 11):
f.write('<tr>')
for j in range(1, 11):
f.write(f'<td><a href=http://{i*j}.ru>{i*j}</a></td>')
f.write('</tr>\n')
f.write('</table></body></html>')
s = 'Python'
ans = 0
for c in s:
... |
h = set()
history = []
r3 = 65536
r4 = 16098955
while True:
r4 = (r4 + (r3 & 255)) & 16777215
r4 = (r4 * 65899) & 16777215
if r3 < 256:
if len(h) == 0:
print(r4)
if r4 in h:
print(history[-1])
break
h.add(r4)
history.append(r4)
r3 ... |
"""
Tools to update the ISO registry.
"""
def iso_register(iso_code):
"""
Registers Calendar class as country or region in IsoRegistry.
Registered country must set class variables ``iso`` using this decorator.
>>> from workalendar.core import Calendar
>>> @iso_register('MC-MR')
>>> class MyR... |
data = {
"AUG": 'Methionine',
"UUU": 'Phenylalanine',
"UUC": 'Phenylalanine',
"UUA": 'Leucine',
"UUG": 'Leucine',
"UCU": 'Serine',
"UCC": 'Serine',
"UCA": 'Serine',
"UCG": 'Serine',
"UAU": 'Tyrosine',
"UAC": 'Tyrosine',
"UGU": 'Cysteine',
"UGC": 'Cysteine',
"UGG": 'Tryptophan',
"UAA": 'STOP',
"UAG": 'ST... |
class Tuple(tuple):
def __new__(cls, *args):
assert len(args) == 3
return super().__new__(cls, args)
# This doesn't work.
# def __init__(self, *args):
# assert len(args) == 3
# return tuple.__init__(self, args)
# or
# return tuple.__init__(self, *args)
|
primo = 0
while True and primo != 2:
primo = 0
try:
number = int(input(f'\nDigite um número inteiro: '))
for numbers in range(1, number + 1):
result = (number % numbers)
if result == 0:
primo += 1
if primo == 2:
print(f'\nÉ um numer... |
numero = input()
horasTrabalhadas = float(input())
valorHora = float(input())
print(f'NUMBER = {numero}')
print(f'SALARY = U$ {horasTrabalhadas * valorHora:.2f}') |
def bin_hours_per_week(hpw):
"""
Bin the hours per week variable into 0-30, 31-40, 41-50, 50+ bins.
"""
if hpw <= 30:
return 0
elif hpw <= 40:
return 1
elif hpw <= 50:
return 2
return 3
|
class IncorrectFileFormat(Exception):
pass
class NoConfigFileFound(Exception):
pass
|
#
# PySNMP MIB module A3COM-HUAWEI-DHCPR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-DHCPR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:04:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort() #first sort two nums
nums2.sort()
l1, l2 = 0, 0 #use two pointers
N1, N2 = len(nums1), len(nums2)
re... |
class MyObj():
"""docstring for MyObj"""
def __init__(self, name, age):
super(MyObj, self).__init__()
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
o1 = MyObj("Been", 32)
o2 ... |
__all__ = [
'sigmoid',
'sigmoid_grad',
'cross_entropy',
'gini_impurity',
'make_linearly_separable_data',
'predict_by_mode',
]
|
"""
Pagination: select how many results to display.
"""
# Maybe refactor later the same way as variant_filter,
# but maybe not necessary as long as they are so simple.
def pagination_from_request(request):
lim = request.args.get('limit')
off = request.args.get('offset', '0')
assert off.isdigit(), "Argument... |
numbers=[]
f=open("./2020/data/09a.txt","r")
# f=open("./2020/data/test.txt","r")
# tofind=127
tofind=133015568
# preamble=5
preamble=25
for line in f:
numbers.append(int(line))
if len(numbers)>preamble:
for i in range(len(numbers)-1):
count=0
smallest=-1
largest=-1
... |
class FFT:
def __init__(self,filename):
self._base_pattern = [0,1,0,-1]
self._repeating_groups = {}
with open(filename,"r") as file_in:
self.fft_input = file_in.readline().strip('\n')
def run(self, phases):
elements = self.fft_input
for p in range(0,phases):
... |
# JJ Small
# manga_model.py
# This class is a representation of what a manga series has/does
class Manga:
def __init__(self, title: str, volume_count: int) -> None:
self.local_title = title
self.site_title = None
self.site_id = None
self.my_volumes = volume_count
self.is_lic... |
# -*- coding: utf-8 -*-
class Playlist(object):
def __init__(self, library, id, name):
self._library = library
self._id = id
self._name = name
self._tracks = []
self._position = 0
@property
def name(self):
return self._name
@property
def tracks(se... |
# Program is to make ring shift or recycle items of list.
def ring_shift(first,next):
if next < 0:
next = abs(next)
for i in range(next):
first.append(first.pop(0))
else:
for i in range(next):
first.insert(0,first.pop())
values = [9, ... |
class RevitLinkLoadResult(object,IDisposable):
"""
This class stores the results of trying to load a single linked model.
RevitLinkLoadResult(other: RevitLinkLoadResult)
"""
def Dispose(self):
""" Dispose(self: RevitLinkLoadResult) """
pass
def GetCentralModelName(self):
"""
GetCentralModel... |
def is_equal(data):
data_to_compare_with = _ttp_["output_object"].attributes['load']
is_equal = False
if "_anonymous_" in data:
if data["_anonymous_"] == data_to_compare_with:
is_equal = True
elif data == data_to_compare_with:
is_equal = True
return {
... |
#Lista os números para, de forma regressiva, a contar do numero digitado pelo usuário - Sem usar IF
print('Listagem de numeros PARES')
c=2
n=(int(input('\nDigite um número para ver todos os PARES de 1 até ele:\n')))
while c < n+1:
print(f'{c} ',end='')
c +=2 |
def part1(inputMap):
rows = len(inputMap)
cols = len(inputMap[0])
rowIdx = 0
colIdx = 0
trees = 0
while rowIdx < rows - 1:
rowIdx += 1
colIdx += 3
# We went past the end of the column
if colIdx >= cols:
colIdx = colIdx - cols
row = inputMap[rowIdx]
spot = row[colIdx]
if... |
class Job:
name = None
current_work_id = 0
farmer_public_key = None
pool_public_key = None
total_running = 0
total_completed = 0
max_concurrent = 0
max_concurrent_with_start_early = 0
max_plots = 0
temporary2_destination_sync = None
stagger_minutes = None
max_for_phase... |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = "ID INTEGER FLOAT STRING CHAR WS COMMENT1 COMMENT2 POUND DPOUND SYNC VOID FOR GLOBAL TYPE QUALIFIER ELSE IF SHAREDfunction : signature '{' shared_buffer statements '}'signature : GLOBAL VOID ID... |
def power(x,y):
res=1
while(y>0):
if((y&1)==1):
res=res*x
y=y>>1
x=x*x
return res
x=5
y=3
print(power(5,3))
|
# Faça um Programa que peça a temperatura em graus Farenheit, transforme e mostre a temperatura em graus Celsius
# Ivo Dias
# Recebe a temperatura
farenheit = int(input("Informe o valor em Farenheit: "))
# Faz a conversao
celsius = (5 * (farenheit - 32) / 9)
# Mostra na tela
print("A temperatura em Celsius é",celsiu... |
# Time Complexity : O(n) ... O(1) * n
def triangle_number(n):
if n == 1:
return 1
return n + triangle_number(n - 1)
for i in range(1, 11):
print(triangle_number(i)) |
"""
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output:... |
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
break
if i == 0 or nums[i - 1] != nums[i]:
self.twoSumII(nums, i, res)
return res
def t... |
"""
Module viginere.py
"""
class Viginere:
"""
Class for text encryption and decryption
with viginere Cipher.
"""
__author__ = "Temuri Takalandze <me@abgeo.dev>"
__copyright__ = "Copyright 2019, abgeo.dev"
__license__ = "MIT"
__version__ = "0.9"
__maintainer__ = "Temrui Takalandze... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.