content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Agent:
'''
Base class for all agents
'''
def __init__(self, player):
self.player = player
pass
def get_next_action(self, game_env):
'''
Evaluates the game environment and returns the next best action according to the agent
Arguments:
... | class Agent:
"""
Base class for all agents
"""
def __init__(self, player):
self.player = player
pass
def get_next_action(self, game_env):
"""
Evaluates the game environment and returns the next best action according to the agent
Arguments:
... |
class InvalidTag(Exception):
pass
class IgnoreObject(Exception):
def __init__(self, original_exception=None, trback=None, *args, **kwargs):
super(Exception, self).__init__(*args, **kwargs)
self.original_exception = original_exception
self.trback = trback
class UnknownProtocol(Except... | class Invalidtag(Exception):
pass
class Ignoreobject(Exception):
def __init__(self, original_exception=None, trback=None, *args, **kwargs):
super(Exception, self).__init__(*args, **kwargs)
self.original_exception = original_exception
self.trback = trback
class Unknownprotocol(Exceptio... |
commands = {
'app': {
'label': 'Application',
'actions': {
'neweditor': {
'label': 'New SQL editor',
'description': 'Open new SQL editor',
'icon': 'document-new-symbolic',
'shortcut': '<Control>N',
'callback'... | commands = {'app': {'label': 'Application', 'actions': {'neweditor': {'label': 'New SQL editor', 'description': 'Open new SQL editor', 'icon': 'document-new-symbolic', 'shortcut': '<Control>N', 'callback': 'win.docview.add_worksheet'}, 'switch_editor1': {'label': 'Switch to editor 1', 'shortcut': '<Alt>1', 'callback': ... |
"""Wrapper service for kraken api."""
class ApiService:
"""Serivce for kraken api call."""
def __init__(self):
"""Create service object."""
pass
| """Wrapper service for kraken api."""
class Apiservice:
"""Serivce for kraken api call."""
def __init__(self):
"""Create service object."""
pass |
# squares = []
# for value in range(1,11):
# squares.append(value ** 2);
# print(squares);
squares = [value ** 2 for value in range(1,11)]
print(squares) | squares = [value ** 2 for value in range(1, 11)]
print(squares) |
"""
LeetCode Problem: 79. Word Search
Link: https://leetcode.com/problems/word-search/
Language: Python
Written by: Mostofa Adib Shakib
Number of rows = M
Number of columns = N
Average time complexity: O(M*N * dfs complexity)
Space Complexity: O(M*N)
Worst-case time complexity:
If the dfs traverses in a zigzag fash... | """
LeetCode Problem: 79. Word Search
Link: https://leetcode.com/problems/word-search/
Language: Python
Written by: Mostofa Adib Shakib
Number of rows = M
Number of columns = N
Average time complexity: O(M*N * dfs complexity)
Space Complexity: O(M*N)
Worst-case time complexity:
If the dfs traverses in a zigzag fash... |
# Copyright (C) 2016-2017 Perceval Wajsburt <perceval.wajsburt@gmail.com>
#
# This module is part of SublimeTerm and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
class SpecialChar:
NEW_LINE = '\n'
TAB = '\t'
BEL = '\x07'
BACKSPACE = '\x08'
DEL = '\x7f'
... | class Specialchar:
new_line = '\n'
tab = '\t'
bel = '\x07'
backspace = '\x08'
del = '\x7f'
up = '\x1bOA'
down = '\x1bOB'
left = '\x1bOD'
right = '\x1bOC'
escape = '\x1b' |
class Passenger:
def __init__(self, passenger_id, source, destination, spawn_time, controller):
self.passenger_id = passenger_id
self.destination = destination
self.source = source
self.spawn_time = spawn_time
self.current_stop = source
self.controller = controller
... | class Passenger:
def __init__(self, passenger_id, source, destination, spawn_time, controller):
self.passenger_id = passenger_id
self.destination = destination
self.source = source
self.spawn_time = spawn_time
self.current_stop = source
self.controller = controller
... |
n = int(input())
x = int(input())
li = list(map(int, input().split()))
l = [0]*n
print(*l,sep=" ")
if (x):
print("YES")
else:
print("NO") | n = int(input())
x = int(input())
li = list(map(int, input().split()))
l = [0] * n
print(*l, sep=' ')
if x:
print('YES')
else:
print('NO') |
print("holis")
#TODO agregar la linea intermedia
print("holis")
#print("holis")
print("holis")
print("holis")
#TODO agregar la linea numero 6 | print('holis')
print('holis')
print('holis')
print('holis') |
class TrainingStatus:
NEW = "NEW"
NEW_LOAD_MODEL = "NEW_LOAD_MODEL"
STARTED = "STARTED"
FINISHED = "FINISHED"
| class Trainingstatus:
new = 'NEW'
new_load_model = 'NEW_LOAD_MODEL'
started = 'STARTED'
finished = 'FINISHED' |
#
# PySNMP MIB module ALTIGA-HARDWARE-STATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALTIGA-HARDWARE-STATS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:21:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (al_hardware_mib_module,) = mibBuilder.importSymbols('ALTIGA-GLOBAL-REG', 'alHardwareMibModule')
(al_stats_hardware, al_hardware_group) = mibBuilder.importSymbols('ALTIGA-MIB', 'alStatsHardware', 'alHardwareGroup')
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetS... |
def Adj2GraphID(adj):
n = adj.shape[0]
GraphID = str(n)+"_"
binID = ''
for i in range(n):
for j in range(i+1,n):
binID += str(int(adj[i][j]))
GraphID += hex(int(binID,2)).split('x')[1]
return GraphID.upper()
def GraphID2Adj(GraphID):
n_str, hexID = GraphID.split("_")
... | def adj2_graph_id(adj):
n = adj.shape[0]
graph_id = str(n) + '_'
bin_id = ''
for i in range(n):
for j in range(i + 1, n):
bin_id += str(int(adj[i][j]))
graph_id += hex(int(binID, 2)).split('x')[1]
return GraphID.upper()
def graph_id2_adj(GraphID):
(n_str, hex_id) = Graph... |
#-*- coding: utf-8 -*-
class INSERT(object):
def __init__(self, schema, target):
self._sql = u"INSERT INTO {}.{}".format(
schema, target)
def VALUES(self, fields):
values = ", ".join(["%(" + field + ")s" for field in fields])
self._sql += "({}) values({})".format(", ".joi... | class Insert(object):
def __init__(self, schema, target):
self._sql = u'INSERT INTO {}.{}'.format(schema, target)
def values(self, fields):
values = ', '.join(['%(' + field + ')s' for field in fields])
self._sql += '({}) values({})'.format(', '.join(fields), values)
self._sql +... |
def calculateEMA(period, data):
returnData = {}
emaList = []
key = 'ema' + str(period)
if data:
historicalEma = data[0]
e = 2/(period + 1)
for i in range(len(data)):
ema = (data[i] - historicalEma) * e + historicalEma
historicalEma = ema
emaLi... | def calculate_ema(period, data):
return_data = {}
ema_list = []
key = 'ema' + str(period)
if data:
historical_ema = data[0]
e = 2 / (period + 1)
for i in range(len(data)):
ema = (data[i] - historicalEma) * e + historicalEma
historical_ema = ema
... |
"""
Tema: Complejidad Algoritmica. Conteo abstracto
Curso: Pensamiento Computacional, 2da entrega.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
def f(x):
respuesta = 0
for i in range(1000):
print(i)
respuesta += 1
for i in range(x):
respuesta += x
... | """
Tema: Complejidad Algoritmica. Conteo abstracto
Curso: Pensamiento Computacional, 2da entrega.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
def f(x):
respuesta = 0
for i in range(1000):
print(i)
respuesta += 1
for i in range(x):
respuesta += x
... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... | def test():
assert 'pivot_table' in __solution__, 'Make sure you are using the pivot_table function.'
msg = "The tidied_lego dataframe contains the incorrect columns. Are you using the correct index column when pivoting? \nExpected ['set_num', 'name', 'year', 'num_parts', 'theme_id'], but got {0}".format(li... |
############################################################
#
# uploadhaddocks
# Copyright (C) 2017, Richard Cook
# Released under MIT License
# https://github.com/rcook/upload-haddocks
#
############################################################
__project_name__ = "upload-haddocks"
__version__ = "0.5"
__descriptio... | __project_name__ = 'upload-haddocks'
__version__ = '0.5'
__description__ = 'Fix up Haskell documentation and upload it to Hackage' |
# standard libraries
pass
# third party libraries
pass
# first party libraries
pass
alphanumeric = 'abcdefghijklmnopqrstuvwxyz' \
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
'123456789'
# alphanumerics unlikely to be mistaken for each other
legible = 'abcdefghijkmnopqrstuvwxyz' \
'ABCDEFGH... | pass
pass
pass
alphanumeric = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789'
legible = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789' |
self.description = "Upgrade packages with various reasons"
lp1 = pmpkg("pkg1")
lp1.reason = 0
lp2 = pmpkg("pkg2")
lp2.reason = 1
for p in lp1, lp2:
self.addpkg2db("local", p)
p1 = pmpkg("pkg1", "1.0-2")
p2 = pmpkg("pkg2", "1.0-2")
for p in p1, p2:
self.addpkg(p)
self.args = "-U %s" % " ".join([p.filename() for p... | self.description = 'Upgrade packages with various reasons'
lp1 = pmpkg('pkg1')
lp1.reason = 0
lp2 = pmpkg('pkg2')
lp2.reason = 1
for p in (lp1, lp2):
self.addpkg2db('local', p)
p1 = pmpkg('pkg1', '1.0-2')
p2 = pmpkg('pkg2', '1.0-2')
for p in (p1, p2):
self.addpkg(p)
self.args = '-U %s' % ' '.join([p.filename() ... |
class Interval:
def __init__(self, start=0, end=0):
self.start = start
self.end = end
| class Interval:
def __init__(self, start=0, end=0):
self.start = start
self.end = end |
PATH_TRAIN = "../../data/train.csv"
PATH_VALID = "../../data/valid.csv"
PICKLES_PATH = "./pickles"
TRAIN = "../../data/train.tsv"
TEST = "../../data/test.tsv"
DEV = "../../data/dev.tsv"
| path_train = '../../data/train.csv'
path_valid = '../../data/valid.csv'
pickles_path = './pickles'
train = '../../data/train.tsv'
test = '../../data/test.tsv'
dev = '../../data/dev.tsv' |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def deps(repo_mapping = {}):
if "com_github_nodejs_http_parser" not in native.existing_rules():
http_archive(
name = "com_github_nodejs_http_parser",
# This commit includes fix for
# https://github.com/... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def deps(repo_mapping={}):
if 'com_github_nodejs_http_parser' not in native.existing_rules():
http_archive(name='com_github_nodejs_http_parser', urls=['https://github.com/nodejs/http-parser/archive/4f15b7d510dc7c6361a26a7c6d2f7c3a17f8d878... |
def BaseHTTPRequestHandler(*args, **kwargs): pass
def Camera(*args, **kwargs): pass
def GSprint(*args, **kwargs): pass
def GSversion(*args, **kwargs): pass
def GW(*args, **kwargs): pass
def GlowWidget(*args, **kwargs): pass
def HTTPServer(*args, **kwargs): pass
def INTERACT_PERIOD(*args, **kwargs): pass
def MAX_RENDERS... | def base_http_request_handler(*args, **kwargs):
pass
def camera(*args, **kwargs):
pass
def g_sprint(*args, **kwargs):
pass
def g_sversion(*args, **kwargs):
pass
def gw(*args, **kwargs):
pass
def glow_widget(*args, **kwargs):
pass
def http_server(*args, **kwargs):
pass
def interact_per... |
spreadsheet = [[5806,6444,1281,38,267,1835,223,4912,5995,230,4395,2986,6048,4719,216,1201],
[74,127,226,84,174,280,94,159,198,305,124,106,205,99,177,294],
[1332,52,54,655,56,170,843,707,1273,1163,89,23,43,1300,1383,1229],
[5653,236,1944,3807,5356,246,222,1999,4872,206,5265,5397,5220,5538,286,917],
[3512,3132,2826,3664,... | spreadsheet = [[5806, 6444, 1281, 38, 267, 1835, 223, 4912, 5995, 230, 4395, 2986, 6048, 4719, 216, 1201], [74, 127, 226, 84, 174, 280, 94, 159, 198, 305, 124, 106, 205, 99, 177, 294], [1332, 52, 54, 655, 56, 170, 843, 707, 1273, 1163, 89, 23, 43, 1300, 1383, 1229], [5653, 236, 1944, 3807, 5356, 246, 222, 1999, 4872, 2... |
#!/usr/bin/python
# coding=UTF-8
"""
Criado em 16 de Janeiro de 2017
Descricao: esta biblioteca possui as seguintes funcoes:
readArq_DadosTemporais: esta funcao faz a leitura do arquivo Arquivo_DadosTemporais gerado pela funcao criaArq_DadosTemporais, retornando os parametros e tabelas nela contidos.
re... | """
Criado em 16 de Janeiro de 2017
Descricao: esta biblioteca possui as seguintes funcoes:
readArq_DadosTemporais: esta funcao faz a leitura do arquivo Arquivo_DadosTemporais gerado pela funcao criaArq_DadosTemporais, retornando os parametros e tabelas nela contidos.
readArq_Etime: esta funcao realiza a... |
a = [0]
for i in range(1000000):
a[0] = i
| a = [0]
for i in range(1000000):
a[0] = i |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
ret = [[]... | class Solution:
def level_order_bottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
ret = [[] for _ in range(self.getHeight(root))]
self.dfs(root, ret, self.getHeight(root) - 1)
return ret
def get_height(self, root):
if root ... |
pkgname = "nasm"
pkgver = "2.15.05"
pkgrel = 0
build_style = "gnu_configure"
make_cmd = "gmake"
make_dir = "."
make_check_target = "test"
hostmakedepends = ["gmake"]
checkdepends = ["perl"]
pkgdesc = "80x86 assembler designed for portability and modularity"
maintainer = "q66 <q66@chimera-linux.org>"
license = "BSD-2-Cl... | pkgname = 'nasm'
pkgver = '2.15.05'
pkgrel = 0
build_style = 'gnu_configure'
make_cmd = 'gmake'
make_dir = '.'
make_check_target = 'test'
hostmakedepends = ['gmake']
checkdepends = ['perl']
pkgdesc = '80x86 assembler designed for portability and modularity'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'BSD-2-Cl... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
l=[]
l1=list1
l2=list2
... | class Solution:
def merge_two_lists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
l = []
l1 = list1
l2 = list2
while l1:
l.append(l1.val)
l1 = l1.next
while l2:
l.append(l2.val)
l2 = l2.next... |
class CifsBcVersionControl(basestring):
"""
Versions of CIFS BranchCache that are currently supported.
"""
@staticmethod
def get_api_name():
return "cifs-bc-version-control"
| class Cifsbcversioncontrol(basestring):
"""
Versions of CIFS BranchCache that are currently supported.
"""
@staticmethod
def get_api_name():
return 'cifs-bc-version-control' |
# coding: utf-8
n = int(input())
sta = [i for i in ''.join(input().split()).split('0') if i != '']
ans = 0
for i in sta:
ans += 2+len(i)-1
if ans != 0:
print(ans-1)
else:
print(0)
| n = int(input())
sta = [i for i in ''.join(input().split()).split('0') if i != '']
ans = 0
for i in sta:
ans += 2 + len(i) - 1
if ans != 0:
print(ans - 1)
else:
print(0) |
#Question Link
#https://practice.geeksforgeeks.org/problems/find-pair-given-difference/0
for _ in range(t):
L,N = map(int,input().split())
arr = list(map(int,input().split()))
arr.sort()
flag = -1
i =0
j = L-1
for i in range(len(arr)):
for j in range(i+1,len(arr)):
if ... | for _ in range(t):
(l, n) = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
flag = -1
i = 0
j = L - 1
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[j] - arr[i] == N:
flag = 1
break
print(fl... |
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dict = {}
for word in strs:
sorted_word = ''.join(sorted(word[:]))
if sorted_word in dict:
dict[sorted_word].append(wor... | class Solution(object):
def group_anagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dict = {}
for word in strs:
sorted_word = ''.join(sorted(word[:]))
if sorted_word in dict:
dict[sorted_word].append(w... |
def glen(generator):
"""
len implementation for generators.
"""
return sum(1 for _ in generator) | def glen(generator):
"""
len implementation for generators.
"""
return sum((1 for _ in generator)) |
'''
https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0
'''
def sort_z_o_t(A):
count = [0 for i in range(3)]
for i in A:
count[i] += 1
aIdx = 0
for i, n in enumerate(count):
while n > 0:
A[aIdx] = i
n -= 1
aIdx += 1
if __name... | """
https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0
"""
def sort_z_o_t(A):
count = [0 for i in range(3)]
for i in A:
count[i] += 1
a_idx = 0
for (i, n) in enumerate(count):
while n > 0:
A[aIdx] = i
n -= 1
a_idx += 1
if __na... |
def for_a():
"""printing small 'a' using for loop"""
for row in range(7):
for col in range(4):
if col==3 and row!=0 or col==0 and row not in(0,2,3,6) or row==3 and col in(1,2) or row==6 and col in(1,2) or row==0 and col in(1,2):
print("*",end=" ")
else:
... | def for_a():
"""printing small 'a' using for loop"""
for row in range(7):
for col in range(4):
if col == 3 and row != 0 or (col == 0 and row not in (0, 2, 3, 6)) or (row == 3 and col in (1, 2)) or (row == 6 and col in (1, 2)) or (row == 0 and col in (1, 2)):
print('*', end=' ... |
class Algorithm:
def __init__(self, np, ic, h, force, params):
self.np = np
self.h = h
self.sq2h = np.sqrt(2 * h)
self.sqh2 = np.sqrt(h / 2)
self.h2 = h / 2
self.force = force
self.acc = 0
fres = self.force(ic)
self.v, self.f, self.ff = (
... | class Algorithm:
def __init__(self, np, ic, h, force, params):
self.np = np
self.h = h
self.sq2h = np.sqrt(2 * h)
self.sqh2 = np.sqrt(h / 2)
self.h2 = h / 2
self.force = force
self.acc = 0
fres = self.force(ic)
(self.v, self.f, self.ff) = (fre... |
expected_output = {
'type': {
'BYTE': {
'allocated': 7045122,
'allocations': 737743,
'frees': 734750,
'requested': 6877514,
},
'BYTE*': {
'allocated': 29128,
'allocations': 345,
'frees': 309,
'req... | expected_output = {'type': {'BYTE': {'allocated': 7045122, 'allocations': 737743, 'frees': 734750, 'requested': 6877514}, 'BYTE*': {'allocated': 29128, 'allocations': 345, 'frees': 309, 'requested': 27112}, 'PArray': {'allocated': 0, 'allocations': 180, 'frees': 180, 'requested': 0}, 'Summary': {'allocated': 7969955, '... |
class Solution:
def validPalindrome(self, s: str) -> bool:
def isValid (s,i,j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
i ,j = 0,len(s)
while i < j:
if s[i] != s[j]:
return isValid(s, i + 1, j) or isValid(s, i , j - 1... | class Solution:
def valid_palindrome(self, s: str) -> bool:
def is_valid(s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
(i, j) = (0, len(s))
while i < j:
... |
class QueryDeviceGroupsInDTO(object):
def __init__(self):
self.accessAppId = None
self.pageNo = None
self.pageSize = None
self.name = None
def getAccessAppId(self):
return self.accessAppId
def setAccessAppId(self, accessAppId):
self.accessAppId = accessAppI... | class Querydevicegroupsindto(object):
def __init__(self):
self.accessAppId = None
self.pageNo = None
self.pageSize = None
self.name = None
def get_access_app_id(self):
return self.accessAppId
def set_access_app_id(self, accessAppId):
self.accessAppId = acce... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... | """
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
# parsetab.py
# This file is automatically generated. Do not edit.
_lr_method = 'LALR'
_lr_signature = 'XP\xd6":$v\xd1\xacQ\xe2\x1d\xc8\x10T\xa2'
_lr_action_items = {'VOID':([118,261,15,238,171,3,50,37,359,33,170,24,68,197,284,328,361,12,2,141,39,29,73,173,232,288,222,60,166,8,21,281,82,135,65,168,239,0,13,388,27,2... | _lr_method = 'LALR'
_lr_signature = 'XPÖ":$vѬQâ\x1dÈ\x10T¢'
_lr_action_items = {'VOID': ([118, 261, 15, 238, 171, 3, 50, 37, 359, 33, 170, 24, 68, 197, 284, 328, 361, 12, 2, 141, 39, 29, 73, 173, 232, 288, 222, 60, 166, 8, 21, 281, 82, 135, 65, 168, 239, 0, 13, 388, 27, 278, 4, 16, 333, 187, 231, 9, 53, 280, 279, 354,... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author JourWon
# @date 2021/12/29
# @file pyIf.py
if __name__ == "__main__":
n = 10
if n < 0:
print(-1)
elif n == 0:
print(0)
else:
print(1) | if __name__ == '__main__':
n = 10
if n < 0:
print(-1)
elif n == 0:
print(0)
else:
print(1) |
n=int(input())
s=input()
s=s.split(' ')
m=int(input())
v=0
p=0
b=input()
b=b.split(' ')
for x in range(0,m):
a=int(b[x])
for i in range(0,n):
if a==int(s[i]):
v=v+i+1
p=p+n-i
print(str(v)+' '+str(p)) | n = int(input())
s = input()
s = s.split(' ')
m = int(input())
v = 0
p = 0
b = input()
b = b.split(' ')
for x in range(0, m):
a = int(b[x])
for i in range(0, n):
if a == int(s[i]):
v = v + i + 1
p = p + n - i
print(str(v) + ' ' + str(p)) |
# Uzd. Nr.3
num = int(input("Please Enter a number that you would like to check: ")) #input a number to check
if num > 1: # to exclude all numbers < 2, those are not prime numbers
for i in range(2, int(num**0.5)+1): #loop for checking the number (square root)
# same result will be ### for... | num = int(input('Please Enter a number that you would like to check: '))
if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print(f'{num} is not a prime, it divides by {i}')
break
else:
print(f' {num} is a prime number')
else:
print(f'{num} is not a ... |
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
len1, len2 = len(s), len(t)
if len1 != len2:
return False
elif len1 == 1:
if s!= t:
return False
else:
return True
else:
dict1 = {}
... | class Solution:
def is_anagram(self, s: str, t: str) -> bool:
(len1, len2) = (len(s), len(t))
if len1 != len2:
return False
elif len1 == 1:
if s != t:
return False
else:
return True
else:
dict1 = {}
... |
"""
Problem Statement
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
? Find the sum of all the multiples of 3 or 5 below 1000 ?
Solution
- Loop through to the number below the given digit
- Find all multiples of 3 then of 5 and app... | """
Problem Statement
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
? Find the sum of all the multiples of 3 or 5 below 1000 ?
Solution
- Loop through to the number below the given digit
- Find all multiples of 3 then of 5 and app... |
# Lecture 9.1, slide 10
def sqrtBi(x, eps):
low = 0.0
high = max(1, x)
ans = (high + low) / 2.0
while abs(ans ** 2 - x) >= eps:
if ans ** 2 < x:
low = ans
else:
high = ans
ans = (high + low) / 2.0
return ans | def sqrt_bi(x, eps):
low = 0.0
high = max(1, x)
ans = (high + low) / 2.0
while abs(ans ** 2 - x) >= eps:
if ans ** 2 < x:
low = ans
else:
high = ans
ans = (high + low) / 2.0
return ans |
def dir2tree(dirs):
result = None
for dir in dirs:
if dir['parent_id']== None:
result = Node(dir['id'], dir['name'])
else:
result.add_parent(dir['parent_id'], Node(dir['id'], dir['name']))
return result
class Node:
def __init__(self, id, name):
self.id = ... | def dir2tree(dirs):
result = None
for dir in dirs:
if dir['parent_id'] == None:
result = node(dir['id'], dir['name'])
else:
result.add_parent(dir['parent_id'], node(dir['id'], dir['name']))
return result
class Node:
def __init__(self, id, name):
self.id ... |
# http://codingbat.com/prob/p149391
def xyz_there(str):
for i in range(len(str)-2):
if (str[i:i+3] == "xyz"):
if ( i == 0 or (i != 0 and str[i-1] != '.') ):
return True
return False
| def xyz_there(str):
for i in range(len(str) - 2):
if str[i:i + 3] == 'xyz':
if i == 0 or (i != 0 and str[i - 1] != '.'):
return True
return False |
def extractTigertranslationsOrg(item):
'''
Parser for 'tigertranslations.org'
'''
ttmp = item['title'].replace("10 Years", "<snip> years").replace("10 Years Later", "<snip> years")
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(ttmp)
if not (chp or vol) or "preview" in item['title'].lower():
retu... | def extract_tigertranslations_org(item):
"""
Parser for 'tigertranslations.org'
"""
ttmp = item['title'].replace('10 Years', '<snip> years').replace('10 Years Later', '<snip> years')
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(ttmp)
if not (chp or vol) or 'preview' in item['title'... |
expected_output = {
"instance": {
"isp": {
"level": {
1: {
"lspid": {
"router-5.00-00": {
"lsp": {
"seq_num": "0x00000003",
"checksum": "0x807... | expected_output = {'instance': {'isp': {'level': {1: {'lspid': {'router-5.00-00': {'lsp': {'seq_num': '0x00000003', 'checksum': '0x8074460', 'local_router': False, 'holdtime': 457, 'attach_bit': 0, 'p_bit': 0, 'overload_bit': 0}, 'area_address': '49', 'nlpid': ['0xcc'], 'hostname': 'router-5', 'ip_address': '172.16.186... |
a = [1, 2, 3, 4, 5,]
print(*a)
for i in a:
print(i, end=' ') | a = [1, 2, 3, 4, 5]
print(*a)
for i in a:
print(i, end=' ') |
#
# This file contains the Python code from Program 16.21 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm16_21.txt
#
class Algorithms(... | class Algorithms(object):
def critical_path_analysis(g):
n = g.numberOfVertices
earliest_time = array(n)
earliestTime[0] = 0
g.topologicalOrderTraversal(Algorithms.EarliestTimeVisitor(earliestTime))
latest_time = array(n)
latestTime[n - 1] = earliestTime[n - 1]
... |
# Some basic tests
DataManager = tools.dynamicImportDev('dataManager').Manager
# traininigDataFun, trainingData = tools.importData('training')
# trainingDataProvider = DataProvider(
# data = traininigDataFun,
# bz = env.training.bz,
# stochasticSampling = False,
# indexingShape = [trainingData.shape[0... | data_manager = tools.dynamicImportDev('dataManager').Manager
(validation_data_fun, validation_data) = tools.importData('validation')
print(len(validationData))
validation_data_provider = data_manager(data=validationDataFun, bz=env.training.bz, stochasticSampling=False, reshuffle=True, indexingShape=[len(validationData)... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
data = {}
output = []
for i in range(len(nums)):
v = target - nums[i]
if v in data.values():
output.append(nums.index(v))
output.append(i)
... | class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
data = {}
output = []
for i in range(len(nums)):
v = target - nums[i]
if v in data.values():
output.append(nums.index(v))
output.append(i)
data[i... |
def to_ini(settings = {}):
"""
Custom Ansible filter to print out a YAML dictionary in the INI file format.
Similar to the built-in to_yaml/to_json filters.
"""
s = ''
# loop through each section
for section in settings:
# print the section header
s += '[%s]\n' % section
... | def to_ini(settings={}):
"""
Custom Ansible filter to print out a YAML dictionary in the INI file format.
Similar to the built-in to_yaml/to_json filters.
"""
s = ''
for section in settings:
s += '[%s]\n' % section
for option in settings[section]:
if isinstance(settin... |
DATA = """
:|'Autauga County, AL' 01001 'Autauga County, AL' 01001
'Chilton County, AL' 01021
'Dallas County, AL' 01047
'Elmore County, AL' 01051
'Lowndes County, AL' 01085
'Montgomery County, AL' 01101
:|'Baldwin County, AL' 01003 'Baldwin County, AL' 01003
'Clarke County, AL' 01025
'Escambia County, AL' 01053
... | data = "\n:|'Autauga County, AL' 01001 'Autauga County, AL' 01001\n 'Chilton County, AL' 01021\n 'Dallas County, AL' 01047\n 'Elmore County, AL' 01051\n 'Lowndes County, AL' 01085\n 'Montgomery County, AL' 01101\n:|'Baldwin County, AL' 01003 'Baldwin County, AL' 01003\n 'Clarke County, AL' 01025\n 'Escambia County, AL'... |
EXAMPLE = True
MYSQL_HOST = "development.com"
VERSION = 1
AGE = 15
NAME = "MIKE"
IMAGE_1 = "aaa"
IMAGE_2 = "bbb"
IMAGE_4 = "a"
IMAGE_5 = "b"
| example = True
mysql_host = 'development.com'
version = 1
age = 15
name = 'MIKE'
image_1 = 'aaa'
image_2 = 'bbb'
image_4 = 'a'
image_5 = 'b' |
total_secs = int(input("How many seconds, in total?"))
hours = total_secs // 3600
secs_still_remaining = total_secs / 60
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining / 60
print("Hrs=", hours, " mines=", minutes,
"secs=", secs_finally_remaining)
n... | total_secs = int(input('How many seconds, in total?'))
hours = total_secs // 3600
secs_still_remaining = total_secs / 60
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining / 60
print('Hrs=', hours, ' mines=', minutes, 'secs=', secs_finally_remaining)
name = int(input('What is your name?'... |
"""
86. Binary Search Tree Iterator
https://www.lintcode.com/problem/binary-search-tree-iterator/description
"""
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
Example of iterate a tree:
iterator = BSTIterator(root)
while itera... | """
86. Binary Search Tree Iterator
https://www.lintcode.com/problem/binary-search-tree-iterator/description
"""
'\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\nExample of iterate a tree:\niterator = BSTIterator(root)\nwhil... |
class Solution:
def minSwap(self, A: [int], B: [int]) -> int:
swap, keep = 1, 0
for i in range(1, len(A)):
if A[i] <= A[i - 1] or B[i] <= B[i - 1]:
# swap
nswap = keep + 1
nkeep = swap
elif A[i] > B[i - 1] and B[i] > A[i - 1]:
... | class Solution:
def min_swap(self, A: [int], B: [int]) -> int:
(swap, keep) = (1, 0)
for i in range(1, len(A)):
if A[i] <= A[i - 1] or B[i] <= B[i - 1]:
nswap = keep + 1
nkeep = swap
elif A[i] > B[i - 1] and B[i] > A[i - 1]:
nk... |
# -*- coding: utf-8 -*-
""" utils.py
Various utilities
"""
__author__ = 'Jared M Smith'
__license__ = 'MIT'
__version__ = '0.1.0'
__maintainer__ = 'Jared M Smith'
__email__ = 'jared@jaredsmith.io'
def format_keywords(keywords):
fmt_keywords = []
for term_breakdown in keywords:
kwd = "".join(term_b... | """ utils.py
Various utilities
"""
__author__ = 'Jared M Smith'
__license__ = 'MIT'
__version__ = '0.1.0'
__maintainer__ = 'Jared M Smith'
__email__ = 'jared@jaredsmith.io'
def format_keywords(keywords):
fmt_keywords = []
for term_breakdown in keywords:
kwd = ''.join(term_breakdown)
fmt_keywor... |
price_vegetables = float(input())
price_fruits = float(input())
kg_vegetables = int(input())
kg_fruits = int(input())
print(str((price_fruits*kg_fruits + price_vegetables*kg_vegetables)/1.94))
| price_vegetables = float(input())
price_fruits = float(input())
kg_vegetables = int(input())
kg_fruits = int(input())
print(str((price_fruits * kg_fruits + price_vegetables * kg_vegetables) / 1.94)) |
with open('abc.txt', 'w+') as file:
file.write('linha 1\n')
file.write('linha 2\n')
file.write('linha 3\n')
file.seek(0)
print(file.read()) | with open('abc.txt', 'w+') as file:
file.write('linha 1\n')
file.write('linha 2\n')
file.write('linha 3\n')
file.seek(0)
print(file.read()) |
#
# PySNMP MIB module CISCO-TN3270SERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TN3270SERVER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:57:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection) ... |
"""This module implements mock Flask-User v0.6 classes
to warn the developer that they are using v0.6 API calls
against an incompatible v1.0+ Flask-User install.
"""
# Author: Ling Thio <ling.thio@gmail.com>
# Copyright (c) 2013 Ling Thio
LEGACY_ERROR =\
"""
Flask-User Legacy ERROR:
----------------------------------... | """This module implements mock Flask-User v0.6 classes
to warn the developer that they are using v0.6 API calls
against an incompatible v1.0+ Flask-User install.
"""
legacy_error = '\nFlask-User Legacy ERROR:\n-----------------------------------\nYou are trying to use the Flask-User v0.6 API\nagainst an _incompatible_ ... |
class Car:
"""
This class represents an Car
"""
def __init__(self, brand, model, reg_no):
"""
Initalizing the Car with arguments
brand
model
reg_no
"""
# instance attribute
self.brand = brand
self.model = model
self.reg_no =... | class Car:
"""
This class represents an Car
"""
def __init__(self, brand, model, reg_no):
"""
Initalizing the Car with arguments
brand
model
reg_no
"""
self.brand = brand
self.model = model
self.reg_no = reg_no
Car.count +=... |
MAGIC = [20210318223204031831, 1145141919810]
BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
def encode(msg: str) -> str:
temp = 0
for m in msg:
temp = temp * 256 + ord(m)
temp = (temp ^ MAGIC[0]) + MAGIC[1]
msg = ''
while temp:
msg = BASE58[temp % 58] + msg
... | magic = [20210318223204031831, 1145141919810]
base58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
def encode(msg: str) -> str:
temp = 0
for m in msg:
temp = temp * 256 + ord(m)
temp = (temp ^ MAGIC[0]) + MAGIC[1]
msg = ''
while temp:
msg = BASE58[temp % 58] + msg
... |
"""
Stores settings related to Unreal importing process
"""
PNG_CACHE_FILE_SUFFIX = ".CACHE.PNG"
bUsePNGCache = True
| """
Stores settings related to Unreal importing process
"""
png_cache_file_suffix = '.CACHE.PNG'
b_use_png_cache = True |
def binary_search(arr, item):
low = 0
high = len(arr)-1
result = -1
while (low <= high):
mid = (low + high)//2
if item == arr[mid]:
result = mid
high = mid - 1
elif (item < arr[mid]):
high = mid - 1
else:
low = mid + 1
return result
| def binary_search(arr, item):
low = 0
high = len(arr) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if item == arr[mid]:
result = mid
high = mid - 1
elif item < arr[mid]:
high = mid - 1
else:
low = mid + 1
r... |
n = int(input())
if n == 1:
print('x')
elif n % 2 == 0:
for x in range(n//2):
print(" " * x + "\\" + " " * 2*(n//2-(x+1)) + "/")
for x in range(n//2):
print(" " * (n//2-(x+1)) + "/" + " " * 2*x + "\\")
elif (n % 2) == 1:
for i in range(n//2):
print(" " * i + "\\" + " " * (2*(n//... | n = int(input())
if n == 1:
print('x')
elif n % 2 == 0:
for x in range(n // 2):
print(' ' * x + '\\' + ' ' * 2 * (n // 2 - (x + 1)) + '/')
for x in range(n // 2):
print(' ' * (n // 2 - (x + 1)) + '/' + ' ' * 2 * x + '\\')
elif n % 2 == 1:
for i in range(n // 2):
print(' ' * i + '... |
#!/usr/bin/python
line = "Przykladoy tekst do zadania z przedmiotu Python"
allWords = line.split()
result = sum(len(x) for x in allWords)
print(result)
| line = 'Przykladoy tekst do zadania z przedmiotu Python'
all_words = line.split()
result = sum((len(x) for x in allWords))
print(result) |
params={
'enc_type': 'lstm',
'dec_type': 'lstm',
'nz': 32,
'ni': 128,
'enc_nh': 512,
'dec_nh': 512,
'log_niter': 50,
'dec_dropout_in': 0.5,
'dec_dropout_out': 0.5,
'batch_size': 32,
'epochs': 100,
'test_nepoch': 5,
'train_data': 'datasets/snli_data/snli.train.txt',
... | params = {'enc_type': 'lstm', 'dec_type': 'lstm', 'nz': 32, 'ni': 128, 'enc_nh': 512, 'dec_nh': 512, 'log_niter': 50, 'dec_dropout_in': 0.5, 'dec_dropout_out': 0.5, 'batch_size': 32, 'epochs': 100, 'test_nepoch': 5, 'train_data': 'datasets/snli_data/snli.train.txt', 'val_data': 'datasets/snli_data/snli.valid.txt', 'tes... |
while True:
s = input("[>] Enter string (for exit enter empty string): ")
if s:
print(f"[+] Lenght of string: {len(s)}")
else:
break
| while True:
s = input('[>] Enter string (for exit enter empty string): ')
if s:
print(f'[+] Lenght of string: {len(s)}')
else:
break |
for i in range(int(input())):
fact=1
a=int(input())
for j in range(1,a+1,1):
fact=fact*j
print(fact) | for i in range(int(input())):
fact = 1
a = int(input())
for j in range(1, a + 1, 1):
fact = fact * j
print(fact) |
class ReloadProError(Exception):
"""Raised when the Re:load Pro returns an err status."""
class ReloadPro(object):
def __init__(self, f):
self.f = f
# Handler functions for overtemp and undervolt conditions
self.on_overtemp = lambda: None
self.on_undervolt = lambda: None
d... | class Reloadproerror(Exception):
"""Raised when the Re:load Pro returns an err status."""
class Reloadpro(object):
def __init__(self, f):
self.f = f
self.on_overtemp = lambda : None
self.on_undervolt = lambda : None
def _command(self, cmd, expected):
self.f.write(cmd + '\n... |
createElement = React.createElement
createContext = React.createContext
forwardRef = React.forwardRef
Component = ReactComponent = React.Component
useState = React.useState
useEffect = React.useEffect
useContext = React.useContext
useReducer = React.useReducer
useCallback = React.useCallback
useMemo = Re... | create_element = React.createElement
create_context = React.createContext
forward_ref = React.forwardRef
component = react_component = React.Component
use_state = React.useState
use_effect = React.useEffect
use_context = React.useContext
use_reducer = React.useReducer
use_callback = React.useCallback
use_memo = React.u... |
class dotLoadCommonAttributes_t(object):
# no doc
aPartFilter=None
AutomaticPrimaryAxisWeight=None
BoundingBoxDx=None
BoundingBoxDy=None
BoundingBoxDz=None
CreateFixedSupportConditionsAutomatically=None
FatherId=None
LoadAttachment=None
LoadDispersionAngle=None
LoadGroupId=None
ModelObject=None
PartNames=N... | class Dotloadcommonattributes_T(object):
a_part_filter = None
automatic_primary_axis_weight = None
bounding_box_dx = None
bounding_box_dy = None
bounding_box_dz = None
create_fixed_support_conditions_automatically = None
father_id = None
load_attachment = None
load_dispersion_angle =... |
class Graph:
def __init__(self, vertices):
self.__nodes = vertices
self.__edges = {}
def add_edges(self, node1,node2):
if (min(node1,node2),max(node1,node2)) in self.__edges:
self.__edges[(min(node1,node2),max(node1,node2))] += 1
else:
self.__edges[(min(... | class Graph:
def __init__(self, vertices):
self.__nodes = vertices
self.__edges = {}
def add_edges(self, node1, node2):
if (min(node1, node2), max(node1, node2)) in self.__edges:
self.__edges[min(node1, node2), max(node1, node2)] += 1
else:
self.__edges[... |
lista = []
listaPar = []
listaImpar = []
continuar ='s'
while continuar in 'Ss':
valor = int(input('Insira o seu numero : '))
lista.append(valor)
if valor % 2 == 0 :
listaPar.append(valor)
if valor % 2 == 1 :
listaImpar.append(valor)
continuar = str(input('Continuar [S/N] ?'))
print(... | lista = []
lista_par = []
lista_impar = []
continuar = 's'
while continuar in 'Ss':
valor = int(input('Insira o seu numero : '))
lista.append(valor)
if valor % 2 == 0:
listaPar.append(valor)
if valor % 2 == 1:
listaImpar.append(valor)
continuar = str(input('Continuar [S/N] ?'))
print... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 17:25:24 2021
@author: Mahmu
"""
| """
Created on Thu Jun 3 17:25:24 2021
@author: Mahmu
""" |
"""
This module provides the different constants pertaining to the ``accounts`` app.
"""
OTP_CODE_LENGTH = 6
# Documentation string for OTP_CODE_LENGTH defined above.
"""
The length of the ``code`` field of :class:`apps.accounts.models.OTP`.
"""
CSRF_TOKEN_LENGTH = 32
# Documentation string for CSRF_TOKEN_LENGTH ... | """
This module provides the different constants pertaining to the ``accounts`` app.
"""
otp_code_length = 6
'\nThe length of the ``code`` field of :class:`apps.accounts.models.OTP`.\n\n'
csrf_token_length = 32
'\nThe length of the ``csrf_token``. ``csrf_token`` is used in the implementation of the\n**Double Submit Co... |
name = "S - Interfering Lines"
description = "Oscilloscope lines overlap"
knob1 = "Number of Lines"
knob2 = "Outer Spread"
knob3 = "Center Spread"
knob4 = "Color"
released = "March 21 2017"
| name = 'S - Interfering Lines'
description = 'Oscilloscope lines overlap'
knob1 = 'Number of Lines'
knob2 = 'Outer Spread'
knob3 = 'Center Spread'
knob4 = 'Color'
released = 'March 21 2017' |
"""General-purpose routines.
It seemed a shame for the ``api`` module to have to import large legacy
modules to offer simple date handling, so this small module holds the
routines instead.
"""
def jday(year, mon, day, hr, minute, sec):
"""Return two floats that, when added, produce the specified Julian date.
... | """General-purpose routines.
It seemed a shame for the ``api`` module to have to import large legacy
modules to offer simple date handling, so this small module holds the
routines instead.
"""
def jday(year, mon, day, hr, minute, sec):
"""Return two floats that, when added, produce the specified Julian date.
... |
"""
space : O(n)
time : O(n)
"""
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
if k < 0:
return 0
ans = 0
hashmap = {}
for i in nums:
if i not in hashmap:
hashmap[i] = 1
else:
hashmap[... | """
space : O(n)
time : O(n)
"""
class Solution:
def find_pairs(self, nums: List[int], k: int) -> int:
if k < 0:
return 0
ans = 0
hashmap = {}
for i in nums:
if i not in hashmap:
hashmap[i] = 1
else:
hashmap[i... |
def precision_S(y_test, y_pred):
corr_negative, corr_issue, corr_solution = 0, 0, 0
count_negative, count_issue, count_solution = 0, 0, 0
for i, prediction in enumerate(y_pred):
if prediction[0] == 1:
count_negative += 1
if y_test[i][0] == 1:
corr_negative += ... | def precision_s(y_test, y_pred):
(corr_negative, corr_issue, corr_solution) = (0, 0, 0)
(count_negative, count_issue, count_solution) = (0, 0, 0)
for (i, prediction) in enumerate(y_pred):
if prediction[0] == 1:
count_negative += 1
if y_test[i][0] == 1:
corr_ne... |
def cmn_denom(num, denom):
while num % denom != 0:
old_num = num
old_denon = denom
num = old_denon
denom = old_num % old_denon
return denom
class Fraction:
def __init__(self, num, denom):
self.num = num
self.denom = denom
def __str__(self)... | def cmn_denom(num, denom):
while num % denom != 0:
old_num = num
old_denon = denom
num = old_denon
denom = old_num % old_denon
return denom
class Fraction:
def __init__(self, num, denom):
self.num = num
self.denom = denom
def __str__(self):
retu... |
"""
Functions related to the (m,n) vsh mode indices
"""
def rmax_to_lmax(rmax):
"""obtain lmax from rmax"""
lmax = int(-1 + (1+rmax)**0.5)
return lmax
def lmax_to_rmax(lmax):
"""obtain rmax from lmax"""
rmax = lmax*(lmax + 2)
return rmax
def reduced_index(n, m):
r = n*(n+2) - n + m - 1;
... | """
Functions related to the (m,n) vsh mode indices
"""
def rmax_to_lmax(rmax):
"""obtain lmax from rmax"""
lmax = int(-1 + (1 + rmax) ** 0.5)
return lmax
def lmax_to_rmax(lmax):
"""obtain rmax from lmax"""
rmax = lmax * (lmax + 2)
return rmax
def reduced_index(n, m):
r = n * (n + 2) - n ... |
jill = 10
iack = 10
print(str(iack)+" "+str(jill))
for i in range(iack):
print(i)
for j in range(jill):
print(jill + j*2)
print("0 0")
| jill = 10
iack = 10
print(str(iack) + ' ' + str(jill))
for i in range(iack):
print(i)
for j in range(jill):
print(jill + j * 2)
print('0 0') |
"""
Author: Shreck Ye
Date: June 15, 2019
Time complexity: O(N)
"""
class Solution:
def fib(self, N: int) -> int:
fn, fnp1 = 0, 1
for _ in range(N):
fn, fnp1 = fnp1, fn + fnp1
return fn
| """
Author: Shreck Ye
Date: June 15, 2019
Time complexity: O(N)
"""
class Solution:
def fib(self, N: int) -> int:
(fn, fnp1) = (0, 1)
for _ in range(N):
(fn, fnp1) = (fnp1, fn + fnp1)
return fn |
#for defining n inputs from the user
print('enter 0 to stop.\n')
def enter(x):
while x:
x=input()
x=input()
enter(x)
#------------------ done ---------------------------
| print('enter 0 to stop.\n')
def enter(x):
while x:
x = input()
x = input()
enter(x) |
"""
LeetCode Problem 111. Container With Most Water
Link: https://leetcode.com/problems/container-with-most-water/
Language: Python
Written by: Mostofa Adib Shakib
"""
"""
Time Complexity: O(n)
Space Complexity: O(1)
we need to take the minimum of the two heights
Traverse two pointers one from the left hand side and ... | """
LeetCode Problem 111. Container With Most Water
Link: https://leetcode.com/problems/container-with-most-water/
Language: Python
Written by: Mostofa Adib Shakib
"""
'\nTime Complexity: O(n)\nSpace Complexity: O(1)\n\nwe need to take the minimum of the two heights\nTraverse two pointers one from the left hand side an... |
""" proc.py -> Class definition for a Process """
class Process(object):
"""
Class that represents a simple process conforming just of:
1. Letter id.
2. Number of memory units.
"""
#Constants representing the number of minimum and maximum units
#each process could request.
MIN_UNITS = 2
MAX_UNITS = 15
... | """ proc.py -> Class definition for a Process """
class Process(object):
"""
Class that represents a simple process conforming just of:
1. Letter id.
2. Number of memory units.
"""
min_units = 2
max_units = 15
def __init__(self, letter_id, units):
self.letter_id = letter_id
sel... |
def f():
x = 8
def g():
nonlocal x
x = 9
return x
| def f():
x = 8
def g():
nonlocal x
x = 9
return x |
'''
Leser filer gitt filnavn
'''
| """
Leser filer gitt filnavn
""" |
# area_of_n-sided_polygon.py
# https://www.codewars.com/kata/5727500a20c7f837fc001869/train/python
# We use the "shoelace formula" to calculate the area.
# https://www.101computing.net/the-shoelace-algorithm/
def area_polygon(vertex):
if len(vertex) < 3:
return -1
a = vertex[len(vertex) - 1][0]*vertex... | def area_polygon(vertex):
if len(vertex) < 3:
return -1
a = vertex[len(vertex) - 1][0] * vertex[0][1]
b = vertex[len(vertex) - 1][1] * vertex[0][0]
for i in range(len(vertex) - 1):
a += vertex[i][0] * vertex[i + 1][1]
b += vertex[i][1] * vertex[i + 1][0]
return round(abs(a - ... |
add_library('opencv_processing')
img = None
opencv = None
def setup():
img = loadImage("test.jpg")
size(img.width, img.height, P2D)
opencv = OpenCV(this, img)
def draw():
opencv.loadImage(img)
opencv.brightness(int(map(mouseX, 0, width, -255, 255)))
image(opencv.getOutput(), 0, 0)
| add_library('opencv_processing')
img = None
opencv = None
def setup():
img = load_image('test.jpg')
size(img.width, img.height, P2D)
opencv = open_cv(this, img)
def draw():
opencv.loadImage(img)
opencv.brightness(int(map(mouseX, 0, width, -255, 255)))
image(opencv.getOutput(), 0, 0) |
def controllo_input(n):
if len(n) < 4:
raise TypeError("Errore: il numero deve avere minimo 4 cifre")
def ordina_crescente(n):
return "".join(sorted(n))
def ordina_decrescente(n):
return "".join(reversed(sorted(n)))
def costante_kaprekar(n):
iterazioni_max_kaprekar = 7
for i in range(i... | def controllo_input(n):
if len(n) < 4:
raise type_error('Errore: il numero deve avere minimo 4 cifre')
def ordina_crescente(n):
return ''.join(sorted(n))
def ordina_decrescente(n):
return ''.join(reversed(sorted(n)))
def costante_kaprekar(n):
iterazioni_max_kaprekar = 7
for i in range(ite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.