content stringlengths 7 1.05M |
|---|
age = int(input('what is your current age: '))
remain = 90 - age
print(f'You have {remain*365} days, {remain*52} weeks, and {remain*12} months left!') |
class UnionFind:
def __init__(self, n):
self.par = [-1 for i in range(n)]
self.siz = [1 for i in range(n)]
def root(self, x):
if self.par[x] == -1:
return x
else:
self.par[x] = self.root(self.par[x])
return self.par[x]
def is_same(sel... |
#
# PySNMP MIB module CISCO-RMON-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-RMON-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:54:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
"""
A backed-up folder
"""
# pylint: disable=too-many-instance-attributes
class Folder:
"""
A backup folder
"""
def __init__(self):
"""
.
"""
self.__folder_path = None
self.__folder_permissions = None
self.__folder_owner = None
self.__folder_grou... |
ALL = "All tested clients"
OUTLOOK = "Outlook 2007/10/13"
OUTLOOK_EXPRESS = "Outlook 03/Express/Mail"
OUTLOOK_COM = "Outlook.com"
APPLE_MAIL = "Apple Mail 6.5"
IPHONE = "Iphone iOS 7/iPad"
YAHOO = "Yahoo! Mail"
GMAIL = "Google Gmail"
ANDROID = "Android 4 (Gmail)"
|
# works 100%
A = []
def solution(A, K):
if len(A) == 0:
return A
M = K
if K > len(A):
M = K % len(A)
return A[len(A)-M:len(A)] + A[0:len(A)-M]
print(solution(A, 42)) |
a=input('enter a word')
for i in range(len(a)):
print(chr(ord(a[i])-32),end='')
|
def set_template(args):
# Set the templates here
if args.template.find('jpeg') >= 0:
args.data_train = 'DIV2K_jpeg'
args.data_test = 'DIV2K_jpeg'
args.epochs = 200
args.decay = '100'
if args.template.find('EDSR_paper') >= 0:
args.model = 'EDSR'
args.n_resbloc... |
# Python - 2.7.6
def narcissistic(value):
v, nums = value, []
while v > 0:
nums.append(v % 10)
v = v // 10
return sum(map(lambda num: num ** len(nums), nums)) == value
|
#Find the smallest positive number #missing from an unsorted array
#Link to problem https://leetcode.com/explore/interview/card/top-interview-questions-hard/116/array-and-strings/832/
def findMissing(a, n):
for i in range(n) :
# if value is negative or greater than array size then we skip the curren... |
r"""
=======================================================
Cone Ply Piece Optimization Tool (:mod:`desicos.cppot`)
=======================================================
.. currentmodule:: desicos.cppot
Please, refer to the :ref:`CPPOT tutorial <cppot_tutorial>` for more details
about how to use this module.
.. a... |
# import gspread
# from db import database
# import asyncio
# from datetime import datetime
class sheets:
def __init__(self):
"""Initialises the connection to the google sheet using the google sheets API
"""
self.gc1 = gspread.service_account(filename='credantials.json')
s... |
"""Errors thrown by DTOs or DAOs."""
class PlayerNotCreatorError(Exception):
"""
Is raised when a non host tries to execs creator rights.
"""
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 15:06:01 2020
@author: teja
"""
n = int(input())
t = []
d = []
ans = []
for i in range(n):
temp = list(input().split())
t.append(temp[0])
d.append(temp[1])
for i in range(len(t)):
minval = min(t)
minind = t.index(minval)
ans.append()
f... |
def get_reference(node, identifiers):
"""Recurses through yaml node to find the target key."""
if len(identifiers) == 1:
return {identifiers[0]: node[identifiers[0]]}
if not identifiers[0]: # skip over any empties
return get_reference(node, identifiers[1:])
return get_reference(node[... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : 2022424.py
@Contact : huanghoward@foxmail.com
@Modify Time : 2022/4/24 20:14
------------
"""
def solu(a, b, c):
def f(x):
return x ** 3 + a * x ** 2 + b * x - c
up = 1e6
while f(up) < 0:
up = up * 10
l... |
# Sengoku Era Questline | Master Room (811000008)
# Author: Tiger
SUKUNO = 9130124
AYAME = 9130100
if sm.hasQuest(58908) or sm.hasQuestCompleted(58908):
sm.lockInGameUI(False)
sm.hideNpcByTemplateId(9130104, False, False) # respawns princess sakuno's npc
else:
sm.hideNpcByTemplateId(9130104, True, True) #... |
a=int(input("Enter A value:"))
rev=0
while a>0:
rem=a%10
rev=(rev*10)+rem
a=a//10
print("Reeverse value of A is: ",rev)
|
#!/opt/bitnami/python/bin/python
# EASY-INSTALL-SCRIPT: 'XlsxWriter==0.9.3','vba_extract.py'
__requires__ = 'XlsxWriter==0.9.3'
__import__('pkg_resources').run_script('XlsxWriter==0.9.3', 'vba_extract.py')
|
# EXERCÍCIO 48
# Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500.
cont = 0
soma = 0
for num in range (1,501):
if num % 2 == 1 and num % 3 == 0:
soma += num
cont += 1
print(num, end=' ')
print('\n\nA soma de t... |
class Queue:
def __init__(self, first):
self.first = first
self.last = None
self.size = 1
def pop_item(self):
if self.size < 2:
self.size = 0
t = self.first
self.first = None
return t
elif self.size == 2:
self.s... |
#
# PySNMP MIB module FASTTRAKIDERAID-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FASTTRAKIDERAID-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:58:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
""... |
#Write a python program to print out:
#name, preferred pronouns, favorite movie and favorite food
#main functions and print statements
def main():
print("Name: Edison Chen\nPronouns: he/him")
print("My favorite movie is The Matrix")
print("My favorite food is sushi")
#check for main function and call it
if _... |
"""
Cycles are notoriously dangerous bugs in linked lists. There is however a very elegant algorithm
to detect these cycles.
Edge cases:
1. One node linked lists
2. Loops on the first node
3. Loop in a two node linked list
4. Loop on the tail node
"""
def is_cycle(head):
"""Detect a cycle where a ... |
print ("Hola Mundo!!!")
m = [5, 'old', 'new', 8, 'time', 2]
print (m[0])
print (m[-1])
|
# """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
# def get(self, x: int, y: int) -> int:
# def dimensions(self) -> list[]:
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:... |
'''
Pattern 9
Hollow mirrored right triangle
Enter number of rows: 5
*
**
* *
* *
*****
'''
print('Hollow mirrored right triangle:')
rows=int(input('Enter number of rows:'))
for i in range(0,rows+1):
for j in range(i,rows+1):
print(' ',end='')
for j in range(1,i+1):
if i==rows or j==1 o... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"GAMMA": "00_core.ipynb",
"api_settings": "00_core.ipynb",
"nofilt": "00_core.ipynb",
"API": "00_core.ipynb",
"massachusetts_getter": "00_core.ipynb",
"michigan_ge... |
# -*- coding: utf-8 -*-
"""Top-level package for pixie."""
__author__ = """Sabih Hasan"""
__email__ = 'sabih.chr@gmail.com'
__version__ = '0.1.0'
|
# Range: 1 : 100,000
# Time: 28m20.028s
# Written by Alex Vear in 2019
# Public domain. No rights reserved.
startval = 1
endval = 100000
for num in range(startval, endval):
sqr = (num*num)*2
for i in range(startval, endval):
tri = i*(i+1)
if sqr == tri:
sqr = sqr/2
t... |
def quick_sort_channel_logs(channel_logs):
# sort channels to match the server's default chosen positions
if len(channel_logs) <= 1: return channel_logs
else:
return quick_sort_channel_logs([e for e in channel_logs[1:] \
if e.get_channel().position <= channel_logs[0].get_channel().positi... |
"""
Datos de entrada
edad_uno-->e_uno-->int
edad_dos-->e_dos-->int
edad_tres-->e_tres-->int
datos de salida
promedio-->p--float
"""
#Entradas
e_uno=int(input("Digite edad uno: "))
e_dos=int(input("Digite edad dos: "))
e_tres=int(input("Digite edad tres: "))
#Cajanegra
p=(e_uno+e_dos+e_tres)/3#float
#Salida
print (F"El... |
# Bubble Sort
def swap(arr, i, j):
tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
def bubble_sort(arr):
n = len(arr)
is_swapped = True
while is_swapped:
is_swapped = False
for i in range(n-1):
if arr[i] > arr[i+1]:
swap(arr, i, i+1)
is_s... |
"""
Lets start from a node in the initial. DFS through the graph. [0]
When a node is infected, we paint it by color1.
After the DFS is done, we start from another node in the initial. DFS through the graph.
When a node is infected, we paint it by color2.
...
We don't paint the node that we already colored. [1]
The mor... |
async def f():
yield True
x = yield True
def f():
async for fob in oar:
pass
async for fob in oar:
pass
def f():
async with baz:
pass
async with baz:
pass
|
"""
Please input your first name and last name
Then you will have a welcome information :)
This is a python script written by Qi Zhao
"""
usrFirstName = input("Please tell me your first name: ")
usrLastName = input("Please tell me your last name: ")
print(f"Hello {usrFirstName} {usrLastName}")
|
class Printer:
def __init__(self, s):
self.string = s
def __call__(self):
print(self.string)
print_something = Printer("something")
print_something()
# Objects can be made callable by defining a __call__ function.
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 15 12:17:19 2017
@author: scd
"""
#%% global model options
"""
global_option_list = ['APPINFO', 'APPINFOCHG', 'APPSTATUS', 'BNDS_CHK', 'COLDSTART',
'CSV_READ', 'CSV_WRITE', 'CTRLMODE', 'CTRL_HOR', 'CTRL_TIME',
'CTRL_UNITS', 'CV_... |
#-*- coding:utf-8 -*-
__author__ = 'Ulric Qin'
__all__ = [
"api",
"cluster",
"expression",
"group",
"home",
"host",
"nodata",
"plugin",
"strategy",
"template",
"alarm",
"alert_link",
]
|
def mystery(s: str, n: int) -> str:
if n == 0:
return ''
return ''.join(i for i, k in zip(s, bin(n)[2:]) if k == '1')
|
"""
## Questions
### 535. [Encode and Decode TinyURL](https://leetcode.com/problems/encode-and-decode-tinyurl/)
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns... |
devices = {
'fungen':[
'lantz.drivers.keysight.Keysight_33622A.Keysight_33622A',
['TCPIP0::A-33622A-01461.local::inst0::INSTR'], # connecting function generator with ethernet works better for Arb mode
{}
],
'wm':[
'lantz.drivers.bristol.bristol771.Bristol_771',
... |
# Codechef June2020
# EOEO
# The Tom and Jerry Game!
# https://www.codechef.com/problems/EOEO
"""
As usual, Tom and Jerry are fighting. Tom has strength TS and Jerry has strength JS. You are given TS and your task is to find the number of possible values of JS such that Jerry wins the following game.
The game consist... |
class Pessoa:
olhos = 2 #Atributo default (Atributo de Classe)
def __init__(self,*filhos,nome=None,idade=37):
self.nome = nome
self.idade = idade
self.filhos = list(filhos)
def comprimentar(self):
return f'Olá, meu nome é {self.nome}, Tudo bem?'
@staticmethod
def met... |
#
# PySNMP MIB module HUAWEI-SNMP-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-SNMP-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:36:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
def my_decorator(func):
def wrap_func():
func()
return wrap_func
@my_decorator
def hello():
#print('hello baby duck')
print('''
Hello Baby Duck!
..---..
.' _ `.
__..' (o) :
`..__ ;
`. /
; `..---...___
.' `~-. .-')
. ... |
class BinaryHeapNode:
def __init__(self, elem, key, index):
"""
this class represents a generic binary heap node
:param elem: the elem to store
:param key: int, the key to be used as priority function
:param index: int, the index related to the binary node
"""
... |
# Copyright (c) 2021 - present, Timur Shenkao
# All rights reserved.
#
# 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 appl... |
try:
ageStr = input('Enter your age:')
age = int(ageStr)
print('You are', age, 'years old.')
except Exception as esmerelda:
print('Something went wrong: ', esmerelda)
|
x = int(input('podaj liczbe: '))
suma = 0
for i in range(len(str(x))):
suma += int(str(x)[i])
print(suma) |
"""
Introduction
The first century spans from the year 1 up to and including the year 100, The second - from the year 101 up to and including the year 200, etc.
Task :
Given a year, return the century it is in.
Input , Output Examples :
1705 --> 18
1900 --> 19
1601 --> 17
2000 --> 20
Hope you enjoy it .. Awaiting ... |
k = int(input('Quantos quilômetros é sua viagem? '))
if k <= 200:
k1 = k * 0.50
print(f'O preço da passagem ficou em R$ {k1:.2f}')
elif k >= 200:
k2 = k * 0.45
print(f'Que viagem loonga! Sua passagem ficou em R$ {k2:.2f} ') |
test = {
"artifacts": [],
"blocker": None,
"ciTestId": None,
"configXML": None,
"dependsOnMethods": None,
"finishTime": None,
"id": None,
"knownIssue": None,
"message": None,
"messageHashCode": None,
"name": "NAME",
"needRerun": None,
"retry": None,
"startTime": None,
"status": None,
"te... |
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
queue = []
visit = set(deadends) # need visit for every element
if "0000" in visit:
return -1
queue.append("0000")
# for i in range(0,4):
# print(self.turn_down(queue... |
_base_ = [
'./optimizer_cfgs/adam_cfg.py',
'./scheduler_cfgs/multi_step_lr_cfg.py',
'./loss_cfgs/triplet_loss_cfg.py',
]
train_cfg = dict(
save_per_epoch=10,
val_per_epoch=5,
batch_sampler_type='ExpansionBatchSampler',
batch_sampler_cfg=dict(
max_batch_size=64,
batch_size_ex... |
a = list(map(int, input().split()))
b = list(map(int, input().split()))
alice = sum([(1 if a[i] > b[i] else 0) for i in range
(3)])
bob = sum([(1 if a[i] < b[i] else 0) for i in range
(3)])
print(alice, bob)
# Another Solution:
a = list(map(int, input().split()))
b = list(map(int, input().split()))
alice = 0
bob =... |
def seat_id(line):
row = int(''.join('0' if c == "F" else '1' for c in line[:7]), 2)
col = int(''.join('1' if c == "R" else '0' for c in line[7:]), 2)
return row*8+col
print(max(seat_id(line) for line in map(str.rstrip, open('d5.txt')))) |
###OOPS
### Inheritence , Polymorphism, Encapsulation and Abastraction
### Inheritence
##Polymorphism -
# print(type("adsad"))
# print(type(("adsad", "adfsad")))
# Encapsulation
###Abstction
class User:
def __init__( self, name, id):
self.name = name
self.id = id
self.account_bala... |
# Logic
# The required solution can be obtained by simply sorting the arrays. After sorting check if the arrays are exactly same or not.
# If the arrays are same, it's possible to obtain the desired configuration, otherwise it's impossible.
def organizingContainers(container):
rows = [sum(x) for x in container]
... |
"""
Problem: https://www.hackerrank.com/challenges/list-comprehensions/problem
Max Score: 10
Difficulty: Easy
Author: Ric
Date: Nov 13, 2019
"""
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
# arr = []
# for i in range (x + 1):
# for j i... |
class AmiRegionMap(dict):
def __init__(self, more={}):
self['us-east-1'] = {'GENERAL': 'ami-60b6c60a'}
self['us-west-1'] = {'GENERAL': 'ami-d5ea86b5'}
self['us-west-2'] = {'GENERAL': 'ami-f0091d91'}
# TODO: add other regions
# 'eu-west-1'
# 'eu-central-1'
#... |
numOfChocolates = int(input("How many chocolates do you want: "))
if numOfChocolates <= 10:
print("We have enough chocolates for you :D")
bill = numOfChocolates * 15
print(f'Your total bill will be {bill} rupees.')
elif numOfChocolates > 10:
print("We don't have enough chocolates for you D:")
else: prin... |
# General settings for BGI script tools
# Source language
slang = 'ja'
# Destination languages
dlang = ['cn']
# Insertion language
ilang = 'cn'
# Dump file extension
dext = '.txt'
# Source encoding
senc = 'cp932'
# Dump file encoding
denc = 'utf-8'
# Insertion encoding
ienc = 'cp936'
# Copy source line to desti... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 消除序列重复值并保持顺序
Desc :
"""
def dedupe(items):
"""元素都是hashable"""
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
def dedupe2(items, key=None):
"""元素不是hashable的时候"""
seen = set(... |
#* Asked in Microsoft
#? You are given an array of intervals - that is, an array of tuples (start, end).
#? The array may not be sorted, and could contain overlapping intervals. Return another array where the overlapping intervals are merged.
#! For example:
#! [(1, 3), (5, 8), (4, 10), (20, 25)]
#? This input sho... |
'''
The Civil Rights Act of 1964 was one of the most important pieces of legislation ever passed in the USA. Excluding "present" and "abstain" votes, 153 House Democrats and 136 Republicans voted yea. However, 91 Democrats and 35 Republicans voted nay. Did party affiliation make a difference in the vote?
To answer thi... |
class Solution:
def findLonelyPixel(self, k: List[List[str]]) -> int:
x=[]
a=0
y=[]
for i in k:
if i.count("B")==0:
continue
if i.count("B")>1:
y+=[i for i, n in enumerate(i) if n == 'B']
continue
x.a... |
list1 = [1,2,3,4]
def change_list(mode,number):
if mode == 'remove':
list1.remove(number)
elif mode == 'add' and number in list1:
list.append(number)
else:
print('Vy vveli nevernie dannie')
change_list('remove',1)
change_list('add',1)
print(list1)
|
# first line: 1
@memory.cache
def _format_results_to_df(metrics, results, n):
# Format into a dataframe
# Create the metric names and repeat them
n_metrics = len(metrics)
index_names = [*metrics.keys()]*n
# convert to a dataframe
df_res = pd.DataFrame(
results,
index= ... |
#
# @lc app=leetcode id=226 lang=python3
#
# [226] Invert Binary Tree
#
# https://leetcode.com/problems/invert-binary-tree/description/
#
# algorithms
# Easy (60.40%)
# Likes: 2242
# Dislikes: 37
# Total Accepted: 388.6K
# Total Submissions: 641K
# Testcase Example: '[4,2,7,1,3,6,9]'
#
# Invert a binary tree.
# ... |
# vim: set fileencoding=<utf-8> :
# Copyright 2020 John Lees
'''Visualisation of pathogen population structure'''
__version__ = '1.2.2'
|
#
# PySNMP MIB module CISCO-L2-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-L2-CONTROL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:04:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
class ValueTransform:
r"""
Abstract base class for value transforms. See
:class:`coax.value_transforms.LogTransform` for a specific implementation.
"""
__slots__ = ('_transform_func', '_inverse_func')
def __init__(self, transform_func, inverse_func):
self._transform_func = transform_... |
"""Module in which the constants that are used by Dota Responses Bot are declared."""
__author__ = 'Jonarzz'
APP_ID = ''
APP_SECRET = ''
APP_URI = ''
APP_REFRESH_CODE = ''
USER_AGENT = """A tool that finds a Dota 2-related comments with the game heroes\' responses and links to the proper
audio sample fro... |
class Solution:
def judgePoint24(self, nums: List[int]) -> bool:
def generate(a: float, b: float) -> List[float]:
return [a * b,
math.inf if b == 0 else a / b,
math.inf if a == 0 else b / a,
a + b, a - b, b - a]
def dfs(nums: List[float]) -> bool:
if len(... |
class SQueue(object):
def __init__(self, init_len=8):
self.__elem = [0] * init_len
self.__len = init_len
self.__head = 0
self.__num = 0
def __extend(self):
old_len = self.__len
self.__len *= 2
new_elems = [0] * self.__len
for i in range(old_len):
new_elems[i] = self.__elem[(self.__head + i) % old... |
# source: http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip, 2017-01-08
class SUBCLASS:
SC_UNDEFINED = 0x00
SC_VIDEOCONTROL = 0x01
SC_VIDEOSTREAMING = 0x02
SC_VIDEO_INTERFACE_COLLECTION = 0x03
class PROTOCOL:
SC_PROTOCOL_UNDEFINED = 0x00
SC_PROTOCOL_15 = 0x01
class D... |
#! python3
# __author__ = "YangJiaHao"
# date: 2018/2/3
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
tmp = x
rev = 0 # 反转后的数字, 其他语言需要考虑反转后溢出的问题
while tmp:
rev = rev * 10 + ... |
## Script (Python) "getInfografia"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Retorna a lista infografias
pautas = context.portal_vocabularies.getVocabularyByName('PoliticaPublica')
return pautas.getVocabularyDict()
... |
#Faça um Programa que verifique se uma letra digitada é vogal ou consoante
letra = str(input('Digite a letra: '))
if letra == 'a'or letra == 'e' or letra == 'i' or letra == 'o'or letra == 'u':
print('Essa letra é uma vogal')
else:
print('Essa letra é uma consoante') |
def roman_to_int(s):
dic = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
num = 0
for i in range(len(s)):
if i == len(s) - 1:
num += dic[s[i]]
elif dic[s[i]] >= dic[s[i + 1]]:
num += dic[s[i]]
else:
num -= dic[s[i]]
return n... |
def divisor_game(n):
i = -1 # even Alice, odd Bob
while True:
for x in range(1, n):
if n % x == 0:
n -= x
i += 1
break
else:
if i % 2 == 0:
return True
return False
print(divisor_game(3))
|
class Proveedor:
def __init__(self, direccion, telefono, nombre):
self.__Direccion = direccion
self.__Telefono = telefono
self.__Nombre = nombre
def getDireccion(self):
return self.__Direccion
def getTelefono(self):
return self.__Telefono
def getNombre(self):
... |
class ClassInterfaceAttribute(Attribute, _Attribute):
"""
Indicates the type of class interface to be generated for a class exposed to COM,if an interface is generated at all.
ClassInterfaceAttribute(classInterfaceType: ClassInterfaceType)
ClassInterfaceAttribute(classInterfaceType: Int16)
"""
... |
#!/usr/bin/env python3
DICT_PATHS = {}
def n_paths(x, y):
if (x, y) in DICT_PATHS:
return DICT_PATHS[(x, y)]
if x == 0 or y == 0:
paths = 1
else:
paths = n_paths(x - 1, y) + n_paths(x, y - 1)
DICT_PATHS[(x, y)] = paths
return paths
print(n_paths(20, 20))
|
class Config():
def __init__(self):
self.TENSORBOARD_DIR = './tensorboard/'
self.LEARNING_RATE = 0.1
self.STEP_LR_STEP_SIZE = 1
self.STEP_LR_GAMMA = 0.9
self.BATCH_SIZE = 512
self.NUM_EPOCHS = 30
self.EARLY_STOPPING_PATIENCE = 11
self.EMBEDDINGS_SIZE = 128 # "Attention Is all You Need" PAPE... |
#
# PySNMP MIB module CISCO-CDSTV-ISA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CDSTV-ISA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:53:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Complementary DNA
#Problem level: 7 kyu
dna_c = {'A':'T', 'T':'A', 'G':'C', 'C':'G'}
def DNA_strand(dna):
return ''.join(dna_c[x] for x in dna)
|
"""
Статья 83 закона “О выборах депутатов Государственной Думы Федерального Собрания Российской Федерации” определяет
следующий алгоритм пропорционального распределения мест в парламенте.
Необходимо распределить 450 мест между партиями, участвовавших в выборах. Сначала подсчитывается сумма голосов
избирателей, поданны... |
lista = [10, 20, 'amor', 'abacaxi', 80, 'Abioluz', 'Cachorro grande é de arrasar']
print('1: Usando a indexação, escreva na tela a palavra abacaxi')
# exemplo print(lista[3])
print(lista[3])
print('2: Usando a indexação, escreva na tela os seguintes dados: 20, amor, abacaxi')
print(lista[1:4])
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 22:43:39 2020
@author: Ravi
"""
def caesarCipher(s,k):
cipherText = ''
for i in s:
if i.isalpha():
a = 'A' if i.isupper() else 'a'
cipherText += chr( ord(a) +(ord(i)- ord(a)+ k) %26 )
else:
cipherText +=i
... |
""" Who are you code. """
name = ''
while name != 'Lil':
print ('Who are you?')
name = input()
if name == ('Lil'):
print ('Hi Lil')
passwd = ''
while passwd != 'jellyfish':
print('Enter your fish password please')
passwd = input()
if passwd == 'jellyfish':
print('Hello, enjoy!'... |
s1 = "ABCDEF"
s2 = "GHIJKL"
s3 = ""
for i in range(len(s1)):
s3 += s1[i] + s2[i]
print(s3) |
# -*- coding: utf-8 -*-
__title__ = "txt2pdf"
__version__ = "0.6.7"
__author__ = "Julien Maupetit & c4ffein"
__license__ = "MIT"
__copyright__ = "Copyright 2013-2021 Julien Maupetit & c4ffein"
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 15 09:09:49 2021
@author: Martin_Priessner
"""
# Select the ground truth xml in ISBI format
xml_file =r"F:\Martin G-Drive\1.1_Imperial_College\20210715_Tracking\TH10Qu22Dur14\GT9\MAX_2_ISBI.xml"
# Select the location and name of the new generated xml file ... |
power = {'BUSES': {'Area': 3.70399,
'Bus/Area': 3.70399,
'Bus/Gate Leakage': 0.00993673,
'Bus/Peak Dynamic': 2.16944,
'Bus/Runtime Dynamic': 0.23296,
'Bus/Subthreshold Leakage': 0.103619,
'Bus/Subthreshold Leakage with power gating': 0.0388573,
... |
def can_build(platform):
return True
def configure(env):
libpath = "#thirdparty/webrtc/lib/x64/Release/"
libname = "libwebrtc_full"
env.Append(CPPPATH=[libpath])
if env["platform"]== "x11":
env.Append(LIBS=["libwebrtc_full"])
env.Append(LIBPATH=[libpath])
elif env["platform"] == "windows":
... |
a = input()
b = input()
d = dict()
for i in range(len(a)):
if a[i] not in d:
d[a[i]] = 1
else:
d[a[i]] += 1
count = int(0)
for i in range(len(b)):
if b[i] not in d:
count += 1
else:
d[b[i]] -= 1
for i, j in d.items():
count += abs(j)
print(count)
|
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: a root of integer
@return: return a list of integer
"""
def largestValues(self, root):
# write your code here
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.