content stringlengths 7 1.05M |
|---|
#https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/880/
#%%
input=-123
output=321
class Solution:
def reverse(self, x: int) -> int:
string=list(str(abs(x)))
string.reverse()
if x>=0:
temp=int(''.join(string)... |
#py_list_comp_1.py
print([str(x)+"!" for x in [y for y in range(10)]])
|
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
max_index = 0
for index, num in enumerate(nums):
if num > nums[max_index]:
max_index = index
for index, num in enumerate(nums):
if index == max_index:
co... |
SCRIPT=r'''
import sys,time
fi=open(sys.argv[1])
time.sleep(8)
fo=open(sys.argv[2],'w')
fo.write(fi.read())
fi.close()
fo.close()
'''
|
# SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries LLC
# SPDX-FileCopyrightText: 2021 James Carr
#
# SPDX-License-Identifier: MIT
"""
`adafruit_simplemath`
================================================================================
Math utility functions
* Author(s): Dan Halbert, J... |
def dot(n,m):
r=['+'+'---+'*n]
for _ in range(m):
r.append('|'+' o |'*n)
r.append('+'+'---+'*n)
return '\n'.join(r) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverTree(self, root: TreeNode) -> None:
# there are two nodes to find
self.nodes = []
self.inorder(root)
... |
def biggest_cycle_before(limit):
num = longest = 1
for n in range(3, limit, 2):
if n % 5 == 0:
continue
p = 1
while (10 ** p) % n != 1:
p += 1
if p > longest:
num, longest = n, p
print(num)
if __name__ == "__main__":
biggest_cycle_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__version__ = "2.0.3"
__author__ = "Amir Zeldes"
__copyright__ = "Copyright 2015-2018, Amir Zeldes"
__license__ = "MIT License"
|
t = int(input())
answer = []
for a in range(t):
n = int(input())
count = [0 for i in range(26)]
for j in range(n):
line = list(input())
for k in line:
count[ord(k)-97] += 1
ans = True
for k in count:
if(k%n != 0):
ans = False
break
... |
class LogSystem:
def __init__(self):
self.time_position_dict = {"Year": 0, "Month": 1,
"Day": 2, "Hour": 3,
"Minute": 4, "Second": 5}
self.logs = {}
def put(self, id, timestamp):
self.logs[timestamp] = id
def r... |
n1 = int(input('Digite um número: '))
dob = n1*2
trip = n1*3
raiz = n1**(0.5)
print('O número digitado foi: {} \nO dobro é {} \nO triplo é {} \nSua raiz quadrade é {:.2f}'.format(n1, dob, trip, raiz))
|
a = 'AJisa'
a = a.upper()
print(a)
a = a.lower()
print(a)
n = "89*"
print(n.isnumeric())
print(n.isalpha()) |
# pylint: skip-file
class GitRebase(GitCLI):
''' Class to wrap the git merge line tools
'''
# pylint: disable=too-many-arguments
def __init__(self,
path,
branch,
rebase_branch,
ssh_key=None):
''' Constructor for GitPush '''
... |
"""Common values used for testing.
"""
SYSTEM_RAM_GB_MAIN = 64
SYSTEM_RAM_GB_SMALL = 2
SYSTEM_RAM_GB_TOO_SMALL = 1
OSM_PBF_GB_US = 10.4
OSM_PBF_GB_CO = 0.2
# Scaled below the 2GB threshold...
OSM_PBF_GB_USWEST = 1.99
# Should always use flat file, even w/out SSD
OSM_PBF_GB_ALWAYS_FLAT_FILE = 30.1 |
#entrada
x, y = str(input()).split()
x = int(x)
y = int(y)
#saída
for i in range(1, y + 1):
if i % x == 0:
print(i)
else:
print(i, end=' ')
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: tag
short_description: Manage Tag objects of Tag
description:
- Returns the Tags for given filter criteria.
- Cre... |
# Acorn 2.0: Cocoa Butter
# Booleans are treated as integers
# Allow hex
#Number meta class
class N():
def __init__(self,n):
try:
self.n = float(n)
if(self.n.is_integer()):
self.n = int(n)
except:
self.n = int(n,16)
def N(self):
retur... |
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
G = [0 for _ in range(n+1)]
G[0] = G[1] = 1
# 2...n
for i in range(2, n+1):
# 0...i
for j in range(1, i+1):
G[i] += G[j-1]*G[i-j]
r... |
input = """
dummy.
c(0,0).
d :- c(_,a_long__but_still_nice_constant), dummy.
"""
output = """
dummy.
c(0,0).
d :- c(_,a_long__but_still_nice_constant), dummy.
"""
|
COM = ['wink', 'double blink', 'close your eyes', 'jump']
def commands(binary_str):
handshake = []
for couple in zip(binary_str[::-1],COM):
if couple[0] == '1':
handshake.append(couple[1])
if binary_str[0] == '1':
handshake = handshake[::-1]
return handshake
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
u = set("abcdefghijklmnopqrstuvwxyz")
a = {"a", "b", "d", "i", "x"}
b = {"d", "e", "h", "i", "n", "u"}
c = {"e", "f", "m", "n"}
d = {"a", "c", "h", "k", "r", "s", "w", "x"}
bu = u.difference(b)
x = (a.difference(c)... |
#List of constants accessed in our main transit_tracker.py script
#URL for downloading data
URL = 'https://www.psrc.org/sites/default/files/2014-hhsurvey.zip'
#list of age ranges used to make labels
AGE_RANGE_LIST = list(range(0,12))
#List of education ranges used to make labels
EDU_RANGE_LIST = list(range(0,7))
#Tool... |
# 字符串txt是否包含字符串ptn
txt = input('字符串txt:')
ptn = input('字符串ptn:')
if ptn in txt:
print('ptn包含于txt。')
else:
print('txt不包含ptn。') |
class DestinationDirectoryError(Exception):
pass
def add_ssh_prefix(cmd: list[str], remote_host: str) -> list:
"""
Prefix a command with "ssh <remote_address>" for remote use
:param cmd: Command to be run remotely
:param remote_host: Remote machine address
:return: Command with prefix
"""
... |
SHARES = [
0.5, 0.6, 0.7, 0.8, 0.9,
0.91, 0.92, 0.93, 0.94,
0.95, 0.96, 0.97, 0.98,
0.99, 1.0
]
def pop(items):
return items[0], items[1:]
def get_quantiles(records, shares=SHARES):
if not shares:
return
counts = [count for _, count in records]
total = sum(counts)
acc... |
'''
Probem Task : A number is said to be Harshad if it's exactly divisible by
the sum of its digits. Create a function that determines whether a number
is a Harshad or not.
Problem Link : https://edabit.com/challenge/Rrauvu8afRbjqPM8L
'''
sum=0
def harshad(n):
global sum
if(n>0):
rem=... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 2 09:34:42 2018
@author: Manu
TYPES OF VARIABLES
"""
#***********STRINGS*******************
#%%
#Use formate in order to crate a template
name= "Manuel"
city= "Avila (Spain)"
template = "I'm {}, I live in {}".format(name,city)
print(template)
#%... |
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php or see LICENSE file.
# Copyright 2007-2008 Brisa Team <brisa-develop@garage.maemo.org>
""" Facilities for python properties generation.
"""
def gen_property_with_default(name, fget=None, fset=None, doc=""):
""" Generates a property... |
'''
Created: 2019-09-23 12:12:08
Author : YukiMuraRindon
Email : rinndonn@outlook.com
-----
Description:给定一个整数,写一个函数来判断它是否是 3 的幂次方。
'''
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
elif n / 3 == 0 :
return False
else:
... |
def dechiffrer(message, cle_chiffrement):
int(cle_chiffrement)
resultat = ""
for lettre in message:
resultat = resultat + chr(ord(lettre) - cle_chiffrement)
return resultat
def chiffrer(message, cle_chiffrement):
return dechiffrer(message, -cle_chiffrement)
if __name__ == "__ma... |
"""
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2
⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
"""
clas... |
print('''Crie um programa que vai ler vários números e colocar em uma lista.
Depois disso, mostre:
A) Quantos números foram digitados.
B) A lista de valores, ordenada de forma descrescente.
C) Se o valor 5 foi digitado e está ou não na lista.''')
num = cont = 0
li = []
while True:
no = 1
keep = 'a'
cont +=... |
a,b = 10,20
print(a+b) #Output: 30
print(a*b) #Output: 200
print(b/a) #Output: 2.0
print(b%a) #Output: 0 |
# -*- coding: utf-8 -*-
MSG_DATE_SEP = ">>>:"
END_MSG = "THEEND"
ALLOWED_KEYS = [
'q',
'e',
's',
'z',
'c',
'',
]
|
"""
Implement a function meetingPlanner that given the availability, slotsA and slotsB, of two people and a meeting duration dur, returns the earliest time slot that works for both of them and is of duration dur. If there is no common time slot that satisfies the duration requirement, return null.
Time is given in a U... |
# coding: utf-8
class Service:
pass
|
""" https://adventofcode.com/2018/day/11 """
def readFile():
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return int(f.read())
def getPowerlevel(x, y, serial):
rackId = x + 10
powerLevel = (rackId * y + serial) * rackId
return (int(powerLevel / 100) % 10) - 5
def createGrid(... |
class View(dict):
"""A View contains the content displayed in the main window."""
def __init__(self, d=None):
"""
View constructor.
Keyword arguments:
d=None: Initial keys and values to initialize the view with.
Regardless of the value of d, keys 'songs', 'artists' an... |
def search(list, platform):
for i in range(len(list)):
if list[i] == platform:
return True
return False
fruit = ['banana', 'grape', 'apple', 'plam']
print(fruit)
frut = input('input to see if it exists: ')
if search(fruit, frut):
print("fruit is found")
else:
print("fruiit does no... |
# -*- coding: utf-8 -*-
def theaudiodb_albumdetails(data):
if data.get('album'):
item = data['album'][0]
albumdata = {}
albumdata['album'] = item['strAlbum']
if item.get('intYearReleased',''):
albumdata['year'] = item['intYearReleased']
if item.get('strStyle','')... |
"""
Zadanie jak powyżej. Funkcja powinna dostarczyć drogę króla w postaci tablicy zawierającej
kierunki (liczby od 0 do 7) poszczególnych ruchów króla do wybranego celu.
"""
def first_digit(number):
while number > 9:
number //= 10
return number
def king_recursion(T, w, k, visited=[]):
visited.ap... |
class State:
state = {}
@staticmethod
def init():
State.state = {
"lowres_frames": None,
"highres_frames": None,
"photopath": "",
"frame": 0,
"current_photo": None,
"share_code": "",
"preview_image_width": 0,
... |
#!/usr/bin/env python3
"""Making a Box.
Create a function that creates a box based on dimension n.
Source:
https://edabit.com/challenge/dy3WWJr34gSGRPLee
"""
def make_box(n: int, character: str = '#') -> list:
"""Create a box on dimension n using character."""
box = []
for i in range(n):
if i i... |
expected_output = {
'tracker_name': {
'tcp-10001': {
'status': 'UP',
'rtt_in_msec': 2,
'probe_id': 2
},
'udp-10001': {
'status': 'UP',
'rtt_in_msec': 1,
'probe_id': 3
}
}
}
|
"""
coax.exceptions
~~~~~~~~~~~~~~~
"""
class InterfaceError(Exception):
"""An interface error occurred."""
class ReceiveError(Exception):
"""A receive error occurred."""
class InterfaceTimeout(Exception):
"""The interface timed out."""
class ReceiveTimeout(Exception):
"""The receive operation timed... |
def is_funny(string):
data = list(zip(string, reversed(string)))
for i in range(len(string)-1):
if abs(ord(data[i+1][0]) - ord(data[i][0])) != \
abs(ord(data[i+1][1]) - ord(data[i][1])):
return "Not Funny"
return "Funny"
N = int(input())
for i in range(N):
print(is_fu... |
#
# Common methods for the a2gtrad and a2advrad scripts.
#
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 08/13/2014 3393 nabowle Initial creation to contain common
# ... |
#!/usr/bin/env python
def mtx_pivot(mtx) -> list:
piv=[]
pivr=[[] for c in mtx[0]]
for r,row in enumerate(mtx):
for c,col in enumerate(row):
pivr[c]+=[col]
piv+=pivr
return piv |
# #class
# # terms
# # i. features/attributes
# # ii. methods
# # i. a class with args
# # ii a class without args
# # task
# # crate a person class
# # features; age, sex, name, occupation, height
# class Person(object):
# """
# docstring for Person:
# """
# def __init__(self, name, age, occupation, heig... |
"""
LC 6014
You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s.
Return the lexicographically largest repeatLimitedString possible.
A str... |
def add_native_methods(clazz):
def floatToRawIntBits__float__(a0):
raise NotImplementedError()
def intBitsToFloat__int__(a0):
raise NotImplementedError()
clazz.floatToRawIntBits__float__ = staticmethod(floatToRawIntBits__float__)
clazz.intBitsToFloat__int__ = staticmethod(intBitsToFloa... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 04_device.ipynb (unless otherwise specified).
__all__ = ['versions']
# Cell
def versions():
"Checks if GPU enabled and if so displays device details with cuda, pytorch, fastai versions"
print("GPU: ", torch.cuda.is_available())
if torch.cuda.is_available() == True:
... |
class PDB_container:
'''
Use to read a pdb file from a cocrystal structure and parse
it for further use
Note this class cannot write any files and we do not want any
files to be added by this class
This is good for IO management although the code might be hard to
understand
'''
... |
def method():
if True:
return 1
else:
return 2
def method2():
x = 2
if x:
y = 3
z = 1
|
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General P... |
"""
https://leetcode.com/problems/reverse-integer
"""
# define an input for testing purposes
x = 1534236469
# actual code to submit
test = []
for i in str(x):
test += i
for z in range(len(test)):
if test[-1] == "0":
test.pop(-1)
else:
break
if test == []:
test.append("0")
if test[0... |
class Fluorescence:
def __init__(self, user_input, input_ceon):
self.user_input = user_input
self.input_ceons = [input_ceon]
self.number_trajectories = user_input.n_snapshots_ex
self.child_root = 'nasqm_fluorescence_'
self.job_suffix = 'fluorescence'
self.parent_rest... |
# André Roche - Project Euler Problem 5 24-Feb-18. More info @ https://projecteuler.net/problem=5
def gcd(a, b) :
if a == 0: return b
if b == 0: return a
if a < 0: a = -a
if b < 0: b = -b
while b != 0:
a, b = b, a%b
return a
result = 2
for i in range(2,21) :
res... |
#
# PySNMP MIB module COMPANY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COMPANY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:26:32 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, 0... |
input_tokenizer = {}
input_tokenizer['en-bg'] = '-l en -a'
input_tokenizer['en-cs'] = '-l en -a'
input_tokenizer['en-de'] = '-l en -a'
input_tokenizer['en-el'] = '-l en -a'
input_tokenizer['en-hr'] = '-l en -a'
input_tokenizer['en-it'] = '-l en -a'
input_tokenizer['en-nl'] = '-l en -a'
input_tokenizer['en-pl'] = '-l en... |
# -*- coding: utf-8 -*-
#LoginForm
FORGOTTEN_PASS_BUTTON_TEXT = u"Passwort vergessen"
INVALID_LOGIN_TEXT = u"Benutzername / Kennwort ungültig"
LOGIN_ATTEMPTS_RESET_TEXT = u"Login Versuche zurücksetzen."
LOGIN_BUTTON_TEXT = u"Login"
LOGIN_HELP_TEXT = u"Von hier können Sie aus in Ihre Mitarbeiter-Account einloggen. Beid... |
"""
The TreeNode represents node in a Tree.
This module is perfect for Binary Tree but their implementation needs restructuring of the TreeNode
for other Tree types.
"""
class TreeNode(object):
"""
Node in a Tree has arguments
data,link[0]-leftlink,link[0]-right link
emptiness of a TreeNode is indicated by self... |
#Task No. 3
def FindPath(graph,start,end,path=[]):
path = path + [start];
if (start == end):
return path
if (start not in graph):
return None
for node in graph[start]:
if node not in path:
path = FindPath(graph,node,end,path)
if path:
... |
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class linkedList:
def __init__(self):
self.head=None
self.tail=None
def __iter__ (self):
curNode = self.head
while curNode:
yield curNode
curN... |
#!/usr/bin/env python3
class Node:
def __init__(self, value, left=None, right=None) -> None:
self.value = value
self.left = left
self.right = right
def right_most_child_with_parent(self):
parent, curr = None, self
while curr.right:
parent = curr
c... |
#!/usr/bin/python
def is_member(item_to_check, list_to_check):
'''
Checks if an item is in a list
'''
for list_item in list_to_check:
if item_to_check == list_item:
return(True)
return(False)
|
"""Generics support via go_generics.
A Go template is similar to a go library, except that it has certain types that
can be replaced before usage. For example, one could define a templatized List
struct, whose elements are of type T, then instantiate that template for
T=segment, where "segment" is the concrete type.
"... |
def includeme(config):
# config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('hitori_boards', r'/hitori_boards')
config.add_route('hitori_board', r'/hitori_boards/{board_id:\d+}')
config.add_route('hitori_board_solve', r'/hitori_boards/{boar... |
vetor = []
i = 1
while(i <= 100):
valor = int(input())
vetor.append(valor)
i = i + 1
print(max(vetor))
print(vetor.index(max(vetor)) + 1) |
def test_length_ko_1_adb(style_checker):
"""Check length-ko-1.adb
"""
style_checker.set_year(2006)
p = style_checker.run_style_checker('gnat', 'length-ko-1.adb')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, """\
length-ko-1.adb:50:80: (style) this line... |
"""Constants for dice-ml package."""
class BackEndTypes:
Sklearn = 'sklearn'
Tensorflow1 = 'TF1'
Tensorflow2 = 'TF2'
Pytorch = 'PYT'
class SamplingStrategy:
Random = 'random'
Genetic = 'genetic'
KdTree = 'kdtree'
|
"""Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário.
No final, mostre o conteúdo da estrutura na tela."""
aluno = {}
nome = str(input('Nome: '))
aluno['Nome'] = nome
media = float(input(f'Média de {nome}: '))
aluno['Média'] = media
if media >= 7:
aluno['Situação'] = ... |
class BasePairType:
def __init__( self, nt1, nt2, Kd, match_lowercase = False ):
'''
Two sequence characters that get matched to base pair, e.g., 'C' and 'G';
and the dissociation constant K_d (in M) associated with initial pair formation.
match_lowercase means match 'x' to 'x', '... |
# 상 우 하 좌
dx = [0, 1, 0, -1]
dy = [-1, 0, 1, 0]
mat = [
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0],
[0, 1, 0, 0]
]
queue = []
for y in range(4):
for x in range(4):
if mat[y][x] == 1:
queue.append((y, x))
result = 0
while queue:
ny, nx = queue.pop(0)
for i in range(4):
... |
def getdefaultencoding(space):
"""Return the current default string encoding used by the Unicode
implementation."""
return space.wrap(space.sys.defaultencoding)
def setdefaultencoding(space, w_encoding):
"""Set the current default string encoding used by the Unicode
implementation."""
encoding = spac... |
class StructLayoutAttribute(Attribute, _Attribute):
"""
Lets you control the physical layout of the data fields of a class or structure.
StructLayoutAttribute(layoutKind: LayoutKind)
StructLayoutAttribute(layoutKind: Int16)
"""
def __init__(self, *args):
""" x.__init__(...) initial... |
#lista de cores para menu:
#cor da letra
limpa = '\033[m'
Lbranco = '\033[30m'
Lvermelho = '\033[31m'
Lverde = '\033[32m'
Lamarelo = '\033[33m'
Lazul = '\033[34m'
Lroxo = '\033[35m'
Lazulclaro = '\033[36'
Lcinza = '\033[37'
#Fundo
Fbranco = '\033[40m'
Fvermelho = '\033[41m'
Fverde = '\033[42m'
Famarelo = '\033[43m'
F... |
def get_user_id(user_or_id):
if type(user_or_id) is str or type(user_or_id) is int:
return str(user_or_id)
elif hasattr(user_or_id, '__getitem__') and 'user_id' in user_or_id:
return str(user_or_id['user_id'])
elif hasattr(user_or_id, 'user_id'):
return str(user_or_id.user_id)
re... |
load("@io_bazel_rules_docker//container:container.bzl", _container_push = "container_push")
def container_push(*args, **kwargs):
"""Creates a script to push a container image to a Docker registry. The
target name must be specified when invoking the push script."""
if "registry" in kwargs:
fail(
... |
#!/usr/bin/env python
class bresenham:
def __init__(self, start, end):
self.start = list(start)
self.end = list(end)
self.path = []
self.steep = abs(self.end[1]-self.start[1]) > abs(self.end[0]-self.start[0])
if self.steep:
# print 'Steep'
self.start = self.swap(self.start[0],self.start[1])
self.... |
#
# PySNMP MIB module PROXY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PROXY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:33:35 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... |
def removcaract(cnpj):
documento = []
for x in cnpj:
if x.isnumeric():
documento.append(x)
documento = ''.join(documento)
return documento
|
#!/usr/bin/env python
"""
_DQMCat_
"""
__all__ = []
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def condition(divisor) -> bool:
return sum((num - 1) // divisor + 1 for num in nums) <= threshold
lo, hi = 1, max(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if... |
# import numpy as np
# import matplotlib.pyplot as plt
#
# def f(t):
# return np.exp(-t) * np.cos(2*np.pi*t)
#
# t1 = np.arange(0.0, 5.0, 0.1)
# t2 = np.arange(0.0, 5.0, 0.02)
#
# plt.figure("2suplot")
# plt.subplot(211)
# plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
#
# plt.subplot(212)
# plt.plot(t2, np.cos(2*np.pi*... |
__author__ = 'maartenbreddels'
matplotlib = """import pylab
import numpy as np
import os
import json
import sys
name = "{name}" if len(sys.argv) == 1 else sys.argv[1]
filename_grid = name + "_grid.npy"
filename_grid_vector = name + "_grid_vector.npy"
filename_grid_selection = name + "_grid_selection.npy"
filename_m... |
"""This program finds the total number of possible combinations that can be used to
climb statirs . EG : for 3 stairs ,combination and output will be 1,1,1 , 1,2 , 2,1 i.e 3 . """
def counting_stairs(stair_number):
result = stair_number
# This function uses Recursion.
if(stair_number <=1):
... |
def parse_eval_info(cur_eval_video_info):
length_eval_info = len(cur_eval_video_info)
cur_epoch = int(cur_eval_video_info[0].split(' ')[2].split('-')[1])
cur_video_auc = float(cur_eval_video_info[-1].split(' ')[-3].split('-')[1].split(',')[0])
return cur_epoch, cur_video_auc
file = '/home/mry/Desktop... |
class ExitMixin():
def do_exit(self, _):
'''
Exit the shell.
'''
print(self._exit_msg)
return True
def do_EOF(self, params):
print()
return self.do_exit(params)
|
class Solution:
def calculateSum(self, N, A, B):
A_count = N//A
B_count = N//B
result = A*A_count*(1+A_count)//2 + B*B_count*(1+B_count)//2
a = min(A,B)
b = max(A,B)
while a > 0:
b, a= a, b%a
lcm = (A*B)//b
AB_count = (N - N%lcm)//lc... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Children, obj[8]: Education, obj[9]: Occupation, obj[10]: Income, obj[11]: Bar, obj[12]: Coffeehouse, obj[13]: Restaurant20to50, obj[14]: Direction_same, obj[15]: Dista... |
class Cup:
def __init__(self,size,quantity):
self.size = size
self.quantity = quantity
def status(self):
return self.size-self.quantity
def fill(self, quantity):
if self.quantity<=self.status():
self.quantity+=quantity
cup = Cup(100, 50)
print(cup.status())
... |
__author__ = 'croxis'
def convertToPatches(model):
"""Sets up a model for autotesselation."""
for node in model.find_all_matches("**/+GeomNode"):
geom_node = node.node()
num_geoms = geom_node.get_num_geoms()
for i in range(num_geoms):
geom_node.modify_geom(i).make_pa... |
class BinaryConfusionMatrix:
def __init__(self, pos_tag="SPAM", neg_tag="OK"):
self.pos_tag = pos_tag
self.neg_tag = neg_tag
self.tp = 0
self.tn = 0
self.fp = 0
self.fn = 0
def as_dict(self):
return {"tp": self.tp, "tn": self.tn, "fp": self.fp, "fn": self... |
def karp_rabin(text, word, n, m):
MOD = 257
A = random.randint(2, MOD - 1)
Am = pow(A, m, MOD)
def generate(t):
return sum(ord(c) * pow(A, i, MOD) for i, c in enumerate(t[::-1])) % MOD
text += '$'
hash_text, hash_word = generate(text[1:m + 1]), generate(word[1:])
for i in range(1, n - m + 2):
if h... |
class Programa:
def __init__(self, nome, ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
def dar_like(self):
self._likes += 1
@property
def nome(self):
return self._nome
@nome.se... |
n = 1000000
# n = 100
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
primes = []
for i in range(2,n+1):
if prime[i]:
primes.append(i)
count = 0
ans = 0
for index,elem in enumerate(prime... |
STARLARK_BINARY_PATH = {
"java": "external/io_bazel/src/main/java/net/starlark/java/cmd/Starlark",
"go": "external/net_starlark_go/cmd/starlark/*/starlark",
"rust": "external/starlark-rust/target/debug/starlark-repl",
}
STARLARK_TESTDATA_PATH = "test_suite/"
|
#
# @lc app=leetcode id=868 lang=python3
#
# [868] Binary Gap
#
# @lc code=start
class Solution:
def binaryGap(self, N: int) -> int:
s = bin(N)
res = 0
i = float('inf')
for j, n in enumerate(s[2:]):
if n == '1':
res = max(res, j - i)
i = j... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.