content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""
Created on May 4 - 2019
---Based on the 2-stage stochastic program structure
---Assumption: RHS is random
---read stoc file (.sto)
---save the distributoin of the random variables and return the
---random variables
@author: Siavash Tabrizian - stabrizian@smu.edu
"""
class readstoc:
d... | """
Created on May 4 - 2019
---Based on the 2-stage stochastic program structure
---Assumption: RHS is random
---read stoc file (.sto)
---save the distributoin of the random variables and return the
---random variables
@author: Siavash Tabrizian - stabrizian@smu.edu
"""
class Readstoc:
def __init__(self, name)... |
#********************************************************************
# Filename: FibonacciSearch.py
# Author: Javier Montenegro (https://javiermontenegro.github.io/)
# Copyright:
# Details: This code is the implementation of the fibonacci search algorithm.
#*******************************************************... | def fibonacci_search(arr, val):
fib_n_2 = 0
fib_n_1 = 1
fib_next = fib_N_1 + fib_N_2
length = len(arr)
if length == 0:
return 0
while fibNext < len(arr):
fib_n_2 = fib_N_1
fib_n_1 = fibNext
fib_next = fib_N_1 + fib_N_2
index = -1
while fibNext > 1:
... |
class HostAssignedStorageVolumes(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_host_assigned_volumes(idx_name)
class HostAssignedStorageVolumesColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_hosts()
| class Hostassignedstoragevolumes(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_host_assigned_volumes(idx_name)
class Hostassignedstoragevolumescolumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_hosts() |
class Input:
"""
Input prototype
"""
def __init__(self, mod_opts=None):
self.name = ""
self.pretty_name = ""
self.help = ""
self.image_large = ""
self.image_small = ""
self.opts = mod_opts
if mod_opts:
if 'name' in mod_opts:
... | class Input:
"""
Input prototype
"""
def __init__(self, mod_opts=None):
self.name = ''
self.pretty_name = ''
self.help = ''
self.image_large = ''
self.image_small = ''
self.opts = mod_opts
if mod_opts:
if 'name' in mod_opts:
... |
def checkBingo(c):
for x in range(5):
if c[(x * 5) + 0] == c[(x * 5) + 1] == c[(x * 5) + 2] == c[(x * 5) + 3] == c[(x * 5) + 4] == True:
return True
if c[x + 0] == c[x + 5] == c[x + 10] == c[x + 15] == c[x + 20] == True:
return True
return False
def part2(path):
p_in... | def check_bingo(c):
for x in range(5):
if c[x * 5 + 0] == c[x * 5 + 1] == c[x * 5 + 2] == c[x * 5 + 3] == c[x * 5 + 4] == True:
return True
if c[x + 0] == c[x + 5] == c[x + 10] == c[x + 15] == c[x + 20] == True:
return True
return False
def part2(path):
p_input = []
... |
# 207-course-schedule.py
#
# Copyright (C) 2019 Sang-Kil Park <likejazz@gmail.com>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) ->... | class Solution:
def can_finish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = {k[1]: [] for k in prerequisites}
for pr in prerequisites:
graph[pr[1]].append(pr[0])
visited = set()
traced = set()
def visit(vertex):
if vertex i... |
def main():
n = int(input("Enter a number: "))
for i in range(3, n + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime: print(f"{i} ", end="")
print()
if __name__ == '__main__':
main()
| def main():
n = int(input('Enter a number: '))
for i in range(3, n + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime:
print(f'{i} ', end='')
print()
if __name__ == '__main__':
main... |
class Registry(object):
def __init__(self, name):
super(Registry, self).__init__()
self._name = name
self._module_dict = dict()
@property
def name(self):
return self._name
@property
def module_dict(self):
return self._module_dict
def __len__(self):
return len(self.module_dict)
def get(self, ke... | class Registry(object):
def __init__(self, name):
super(Registry, self).__init__()
self._name = name
self._module_dict = dict()
@property
def name(self):
return self._name
@property
def module_dict(self):
return self._module_dict
def __len__(self):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
Instrucciones
1. Ordenar la siguiente lista de valores por medio de ciclos y/o validaciones
arreglo = [54,26,93,17,77,31,44,55,20]
Resultado
arreglo = [54,26,93,17,77,31,44,55,20]
arreglo = [17, 2... | """
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
Instrucciones
1. Ordenar la siguiente lista de valores por medio de ciclos y/o validaciones
arreglo = [54,26,93,17,77,31,44,55,20]
Resultado
arreglo = [54,26,93,17,77,31,44,55,20]
arreglo = [17, 20, 26, 31, 44, 54, 55, 77, 93]
"""
a = [54, 26,... |
'''
293. Flip Game
=========
You are playing the following Flip Game with your friend: Given a string that
contains only these two characters: + and -, you and your friend take turns to
flip two consecutive "++" into "--". The game ends when a person can no longer
make a move and therefore the other person will be the ... | """
293. Flip Game
=========
You are playing the following Flip Game with your friend: Given a string that
contains only these two characters: + and -, you and your friend take turns to
flip two consecutive "++" into "--". The game ends when a person can no longer
make a move and therefore the other person will be the ... |
test_patterns = '''
Given source text and a list of pattens,
look for matches for each patterns within the
text and print them to stdout'''
# Look for each pattern in the text and print the results.
| test_patterns = '\nGiven source text and a list of pattens,\nlook for matches for each patterns within the\ntext and print them to stdout' |
# Source : https://leetcode.com/problems/range-sum-of-bst/
# Author : foxfromworld
# Date : 27/04/2021
# Second attempt (recursive)
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
self.retV = 0
def sub_rangeSumBST(root):
if root:
if low <= root.val <= high:
... | class Solution:
def range_sum_bst(self, root: TreeNode, low: int, high: int) -> int:
self.retV = 0
def sub_range_sum_bst(root):
if root:
if low <= root.val <= high:
self.retV += root.val
if low < root.val:
sub_rang... |
class IntegerString:
def __init__(self) -> None:
self.digits = bytearray([0])
self._length = 0
def __init__(self, digits: bytearray) -> None:
self.digits = digits
self._length = len(self.digits)
@property
def length(self):
return self._length
def add(se... | class Integerstring:
def __init__(self) -> None:
self.digits = bytearray([0])
self._length = 0
def __init__(self, digits: bytearray) -> None:
self.digits = digits
self._length = len(self.digits)
@property
def length(self):
return self._length
def add(self)... |
# format the date in January 1, 2022 form
def format_date(date):
return date.strftime('%B %d, %Y')
# format plural word
def format_plural(total, word):
if total != 1:
return word + 's'
return word
| def format_date(date):
return date.strftime('%B %d, %Y')
def format_plural(total, word):
if total != 1:
return word + 's'
return word |
# Transliteration rules for Chakma ASCII to Chakma
Description = u'Chakma ASCII to Unicode conversion'
TRANS_LIT_RULES = CCP_UNICODE_TRANSLITERATE = u"""
$letter = [\u11103-\u11126];
$evowel = \u1112C;
$virama = \u11133;
\u0000 > \u0020 ; # null
\u000D > \u000D ; # Carriage return
\u0020 > \u0020 ; # sp... | description = u'Chakma ASCII to Unicode conversion'
trans_lit_rules = ccp_unicode_transliterate = u'\n\n $letter = [α3-α6];\n $evowel = αC;\n $virama = α3;\n\n \x00 > ; # null\n \r > \r ; # Carriage return\n > ; # space\n ! > \x00u0021 ; # !\n ## > α2 ; # # PROBLEM\n #$ > α1 ; # $ PROBLEM\n % > % ; # %\... |
# -*- coding: utf-8 -*-
class Visitor:
def visit(self, manager):
self.begin_visit(manager)
manager.visit(self)
return self.end_visit(manager)
def begin_visit(self, manager):
pass
def end_visit(self, manager):
pass
def begin_chapter(self, chapter):
pas... | class Visitor:
def visit(self, manager):
self.begin_visit(manager)
manager.visit(self)
return self.end_visit(manager)
def begin_visit(self, manager):
pass
def end_visit(self, manager):
pass
def begin_chapter(self, chapter):
pass
def end_chapter(se... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
... | class Solution:
def right_side_view(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
output = []
stack = [(root, 0)]
prev_depth = 0
while stack:
(node, depth) = stack.pop(0)
if depth != prev_depth:
outpu... |
_base_ = ["./common_base.py", "./renderer_base.py"]
# -----------------------------------------------------------------------------
# base model cfg for self6d-v2
# -----------------------------------------------------------------------------
refiner_cfg_path = "configs/_base_/self6dpp_refiner_base.py"
MODEL = dict(
... | _base_ = ['./common_base.py', './renderer_base.py']
refiner_cfg_path = 'configs/_base_/self6dpp_refiner_base.py'
model = dict(DEVICE='cuda', WEIGHTS='', REFINER_WEIGHTS='', PIXEL_MEAN=[0, 0, 0], PIXEL_STD=[255.0, 255.0, 255.0], SELF_TRAIN=False, FREEZE_BN=False, WITH_REFINER=False, LOAD_DETS_TRAIN=False, LOAD_DETS_TRAI... |
#
# PySNMP MIB module RADLAN-SOCKET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-SOCKET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:49:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, value_range_constraint, single_value_constraint) ... |
RATING_DATE = 'rating_date'
ANALYSTS_MIN_MEAN_SUCCESS_RATE = 'ANALYSTS_MIN_MEAN_SUCCESS_RATE'
DAYS_SINCE_ANALYSTS_ALERT = 'DAYS_SINCE_ANALYSTS_ALERT'
QUESTIONABLE_SOURCES = []
EMISSIONS = 'emissions'
| rating_date = 'rating_date'
analysts_min_mean_success_rate = 'ANALYSTS_MIN_MEAN_SUCCESS_RATE'
days_since_analysts_alert = 'DAYS_SINCE_ANALYSTS_ALERT'
questionable_sources = []
emissions = 'emissions' |
# Source and destination file names.
test_source = "cyrillic.txt"
test_destination = "xetex-cyrillic.tex"
# Keyword parameters passed to publish_file.
writer_name = "xetex"
# Settings
settings_overrides['language_code'] = 'ru'
# use "smartquotes" transition:
settings_overrides['smart_quotes'] = True
| test_source = 'cyrillic.txt'
test_destination = 'xetex-cyrillic.tex'
writer_name = 'xetex'
settings_overrides['language_code'] = 'ru'
settings_overrides['smart_quotes'] = True |
# Leetcode 101. Symmetric Tree
#
# Link: https://leetcode.com/problems/symmetric-tree/
# Difficulty: Easy
# Complexity:
# O(N) time | where N represent the number of nodes in the tree
# O(N) space | where N represent the number of nodes in the tree
# Definition for a binary tree node.
# class TreeNode:
# def _... | class Solution:
def is_symmetric(self, root: Optional[TreeNode]) -> bool:
def is_mirror(root1, root2):
if not root1 and (not root2):
return True
if root1 and root2:
if root1.val == root2.val:
return is_mirror(root1.left, root2.rig... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-07-09 19:40:06
# Description:
class Solution:
def isValid(self, s: str) -> bool:
n = len(s)
if n == 0:
return True
if n % 2 != 0:
return False
while '()' in ... | class Solution:
def is_valid(self, s: str) -> bool:
n = len(s)
if n == 0:
return True
if n % 2 != 0:
return False
while '()' in s or '{}' in s or '[]' in s:
s = s.replace('{}', '').replace('()', '').replace('[]', '')
if s == '':
... |
'''
Numerical validations.
All functions are boolean.
'''
def is_int(string: str) -> bool:
'''
Returns True if the string argument represents a valid integer.
'''
try:
int(string)
except ValueError:
return False
else:
return True
def is_float(string: str) -> bool:
... | """
Numerical validations.
All functions are boolean.
"""
def is_int(string: str) -> bool:
"""
Returns True if the string argument represents a valid integer.
"""
try:
int(string)
except ValueError:
return False
else:
return True
def is_float(string: str) -> bool:
... |
def method1(ll: list) -> int:
inversionCount = 0
for i in range(len(ll) - 1):
for j in range(i + 1, len(ll)):
if ll[i] > ll[j]:
inversionCount = inversionCount + 1
return inversionCount
if __name__ == "__main__":
"""
from timeit import timeit
ll = [1, 9, 6,... | def method1(ll: list) -> int:
inversion_count = 0
for i in range(len(ll) - 1):
for j in range(i + 1, len(ll)):
if ll[i] > ll[j]:
inversion_count = inversionCount + 1
return inversionCount
if __name__ == '__main__':
'\n from timeit import timeit\n ll = [1, 9, 6, ... |
"""
Exceptions raised in the sublp package.
"""
__all__ = [
'SublpException',
'ProjectNotFoundError',
'ProjectsDirectoryNotFoundError',
'UnmatchedInputString'
]
class SublpException(Exception):
"""Root exception type for sublp module."""
pass
class ProjectNotFoundError(SublpException, IOErro... | """
Exceptions raised in the sublp package.
"""
__all__ = ['SublpException', 'ProjectNotFoundError', 'ProjectsDirectoryNotFoundError', 'UnmatchedInputString']
class Sublpexception(Exception):
"""Root exception type for sublp module."""
pass
class Projectnotfounderror(SublpException, IOError):
"""
Rais... |
class DumbCRC32(object):
def __init__(self):
self._remainder = 0xffffffff
self._reversed_polynomial = 0xedb88320
self._final_xor = 0xffffffff
def update(self, data):
bit_count = len(data) * 8
for bit_n in range(bit_count):
bit_in = data[bit_n >> 3] & (1 << (bit_n & 7))
self._remainder ^= 1 if bit_in... | class Dumbcrc32(object):
def __init__(self):
self._remainder = 4294967295
self._reversed_polynomial = 3988292384
self._final_xor = 4294967295
def update(self, data):
bit_count = len(data) * 8
for bit_n in range(bit_count):
bit_in = data[bit_n >> 3] & 1 << (b... |
"""
@Author Jay Lee
Credits to joeld at stackoverflow for the examples and also the link to the
blender build script for the bcolors class
link: https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
"""
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'... | """
@Author Jay Lee
Credits to joeld at stackoverflow for the examples and also the link to the
blender build script for the bcolors class
link: https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
"""
class Bcolors:
header = '\x1b[95m'
okblue = '\x1b[94m'
... |
# Leetcode 36. Valid Sudoku
#
# Link: https://leetcode.com/problems/valid-sudoku/
# Difficulty: Medium
# Complexity:
# O(9^2) time
# O(9^2) space
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
width, height = len(board[0]), len(board)
rows = collections.defaultdict(set)
... | class Solution:
def is_valid_sudoku(self, board: List[List[str]]) -> bool:
(width, height) = (len(board[0]), len(board))
rows = collections.defaultdict(set)
cols = collections.defaultdict(set)
boxs = collections.defaultdict(set)
for row in range(height):
for col ... |
filename="data2.txt"
file=open(filename, "r")
rs=file.read()
fs=rs.split(",")
il=[]
for i in fs:
il.append(int(i))
i=0
while i<len(il):
moved=False
if il[i]==1:
il[il[i+3]]=il[il[i+1]]+il[il[i+2]]
moved=True
elif il[i]==2:
il[il[i+3]]=il[il[i+1]]*il[il[i+2]]
moved=Tru... | filename = 'data2.txt'
file = open(filename, 'r')
rs = file.read()
fs = rs.split(',')
il = []
for i in fs:
il.append(int(i))
i = 0
while i < len(il):
moved = False
if il[i] == 1:
il[il[i + 3]] = il[il[i + 1]] + il[il[i + 2]]
moved = True
elif il[i] == 2:
il[il[i + 3]] = il[il[i +... |
class Post:
def __init__(self, index, title, subtitle, body):
self.id = index
self.title = title
self.subtitle = subtitle
self.body = body | class Post:
def __init__(self, index, title, subtitle, body):
self.id = index
self.title = title
self.subtitle = subtitle
self.body = body |
# Rwapple -
#Lesson 1: saying hello
# Chapter one of the book.
Print ('Hello, World!')
| print('Hello, World!') |
# Write your solution here
word = input("Please type in a word: ")
char = input("Please type in a character: ")
index = word.find(char)
if (char in word and index < len(word)-2):
print(word[index:index+3]) | word = input('Please type in a word: ')
char = input('Please type in a character: ')
index = word.find(char)
if char in word and index < len(word) - 2:
print(word[index:index + 3]) |
def multi_bracket_validation(str):
open_brackets = tuple('({[')
close_brackets = tuple(')}]')
map = dict(zip(open_brackets, close_brackets))
queue = []
for i in str:
if i in open_brackets:
queue.append(map[i])
elif i in close_brackets:
if not queue o... | def multi_bracket_validation(str):
open_brackets = tuple('({[')
close_brackets = tuple(')}]')
map = dict(zip(open_brackets, close_brackets))
queue = []
for i in str:
if i in open_brackets:
queue.append(map[i])
elif i in close_brackets:
if not queue or i != que... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_simulation_1.py
# Create Date: 2015-03-02 23:19:56
# Usage: AC_simulation_1.py
# Descripton:
class Solution:
# @return an integer
def romanToInt(self, s):
val = {'I': 1, 'V': 5, 'X': 10, '... | class Solution:
def roman_to_int(self, s):
val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
ret = 0
for i in range(len(s)):
if i > 0 and val[s[i]] > val[s[i - 1]]:
ret += val[s[i]] - 2 * val[s[i - 1]]
else:
ret +... |
"""A python implementation of the PageRank algorithm.
Requirements:
------------
None
Usage:
------------
python3 page_rank.py
NB: this code was developed and tested with python 3.7
Disclaimer: this code is intended for teaching purposes only.
"""
def page_rank(G, d=0.85, tolerance=0.01, max_iterations=50):... | """A python implementation of the PageRank algorithm.
Requirements:
------------
None
Usage:
------------
python3 page_rank.py
NB: this code was developed and tested with python 3.7
Disclaimer: this code is intended for teaching purposes only.
"""
def page_rank(G, d=0.85, tolerance=0.01, max_iterations=50):
... |
__version__ = "0.7.1"
def version():
return __version__
| __version__ = '0.7.1'
def version():
return __version__ |
lista = [1, 3, 5, 7]
lista_animal = ['cachorro', 'gato', 'elefante']
print(lista)
print(type(lista))
print(lista_animal[1]) | lista = [1, 3, 5, 7]
lista_animal = ['cachorro', 'gato', 'elefante']
print(lista)
print(type(lista))
print(lista_animal[1]) |
class Credentials:
"""
Class that generates new instances of credentials.
"""
def __init__(self,username,password):
self.username = username
self.password = password
| class Credentials:
"""
Class that generates new instances of credentials.
"""
def __init__(self, username, password):
self.username = username
self.password = password |
# The version number is stored here here so that:
# 1) we don't load dependencies by storing it in the actual project
# 2) we can import it in setup.py for the same reason as 1)
# 3) we can import it into all other modules
__version__ = '0.0.1'
| __version__ = '0.0.1' |
class Solution:
def isConvex(self, points):
def direction(a, b, c): return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
d, n = 0, len(points)
for i in range(n):
a = direction(points[i], points[(i + 1) % n], points[(i + 2) % n])
if not d: d = a
... | class Solution:
def is_convex(self, points):
def direction(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
(d, n) = (0, len(points))
for i in range(n):
a = direction(points[i], points[(i + 1) % n], points[(i + 2) % n])
if n... |
"""
[2017-05-29] Challenge #317 [Easy] Collatz Tag System
https://www.reddit.com/r/dailyprogrammer/comments/6e08v6/20170529_challenge_317_easy_collatz_tag_system/
# Description
Implement the [Collatz Conjecture tag system described
here](https://en.wikipedia.org/wiki/Tag_system#Example:_Computation_of_Collatz_sequenc... | """
[2017-05-29] Challenge #317 [Easy] Collatz Tag System
https://www.reddit.com/r/dailyprogrammer/comments/6e08v6/20170529_challenge_317_easy_collatz_tag_system/
# Description
Implement the [Collatz Conjecture tag system described
here](https://en.wikipedia.org/wiki/Tag_system#Example:_Computation_of_Collatz_sequenc... |
#! -*- coding: utf-8 -*-
SIGBITS = 5
RSHIFT = 8 - SIGBITS
MAX_ITERATION = 1000
FRACT_BY_POPULATIONS = 0.75
| sigbits = 5
rshift = 8 - SIGBITS
max_iteration = 1000
fract_by_populations = 0.75 |
def in_radius(signal, lag=6):
n = len(signal) - 6
r = []
for m in range(n):
a = sqrt((signal[m] - signal[m + 2]) ** 2 + (signal[m + 1] - signal[m + 3]) ** 2)
b = sqrt((signal[m] - signal[m + 4]) ** 2 + (signal[m + 1] - signal[m + 5]) ** 2)
c = sqrt((signal[m + 2] - signal[m + 4]) **... | def in_radius(signal, lag=6):
n = len(signal) - 6
r = []
for m in range(n):
a = sqrt((signal[m] - signal[m + 2]) ** 2 + (signal[m + 1] - signal[m + 3]) ** 2)
b = sqrt((signal[m] - signal[m + 4]) ** 2 + (signal[m + 1] - signal[m + 5]) ** 2)
c = sqrt((signal[m + 2] - signal[m + 4]) ** ... |
# Determine the sign of number
n = float(input("Enter a number: "))
if n > 0:
print("Positive.")
elif n < 0:
print("Negative.")
else:
print("STRAIGHT AWAY ZERROOO.")
| n = float(input('Enter a number: '))
if n > 0:
print('Positive.')
elif n < 0:
print('Negative.')
else:
print('STRAIGHT AWAY ZERROOO.') |
def simpleFun(dim, device):
"""
Args:
dim: integer
device: "cpu" or "cuda"
Returns:
Nothing.
"""
x = torch.rand(dim, dim).to(device)
y = torch.rand_like(x).to(device)
z = 2*torch.ones(dim, dim).to(device)
x = x * y
x = x @ z
del x
del y
del z
## TODO: Implement the function abov... | def simple_fun(dim, device):
"""
Args:
dim: integer
device: "cpu" or "cuda"
Returns:
Nothing.
"""
x = torch.rand(dim, dim).to(device)
y = torch.rand_like(x).to(device)
z = 2 * torch.ones(dim, dim).to(device)
x = x * y
x = x @ z
del x
del y
del z
time_fun(f=simpleFun... |
# https://codeforces.com/problemset/problem/520/A
n = int(input())
s = sorted(set(list(input().upper())))
flag = 0
if len(s) == 26:
for i in range(len(s)):
if chr(65 + i) != s[i]:
flag = 1
break
print("YES") if flag == 0 else print("NO")
else:
print("NO") | n = int(input())
s = sorted(set(list(input().upper())))
flag = 0
if len(s) == 26:
for i in range(len(s)):
if chr(65 + i) != s[i]:
flag = 1
break
print('YES') if flag == 0 else print('NO')
else:
print('NO') |
{
'targets':[
{
'target_name': 'native_module',
'sources': [
'src/native_module.cc',
'src/native.cc'
],
'conditions': [
['OS=="linux"', {
'cflags_cc': [ '-std=c++0x' ]
}]
]
} ... | {'targets': [{'target_name': 'native_module', 'sources': ['src/native_module.cc', 'src/native.cc'], 'conditions': [['OS=="linux"', {'cflags_cc': ['-std=c++0x']}]]}]} |
level = 3
name = 'Pacet'
capital = 'Cikitu'
area = 91.94
| level = 3
name = 'Pacet'
capital = 'Cikitu'
area = 91.94 |
# Function to calculate the mask of a number.
def split(n):
b = []
# Iterating the number by digits.
while n > 0:
# If the digit is lucky digit it is appended to the list.
if n % 10 == 4 or n % 10 == 7:
b.append(n % 10)
n //= 10
# Return the mask.
return b
# Inp... | def split(n):
b = []
while n > 0:
if n % 10 == 4 or n % 10 == 7:
b.append(n % 10)
n //= 10
return b
(x, y) = [int(x) for x in input().split()]
a = split(y)
for i in range(x + 1, 1000000):
if split(i) == a:
print(i)
break |
class Hunk(object):
""" Parsed hunk data container (hunk starts with @@ -R +R @@) """
def __init__(self):
self.startsrc = None #: line count starts with 1
self.linessrc = None
self.starttgt = None
self.linestgt = None
self.invalid = False
self.desc = ''
... | class Hunk(object):
""" Parsed hunk data container (hunk starts with @@ -R +R @@) """
def __init__(self):
self.startsrc = None
self.linessrc = None
self.starttgt = None
self.linestgt = None
self.invalid = False
self.desc = ''
self.text = [] |
class Player:
""" Behavior to have a paddle controlled by the player """
def __init__(self, upKey, downKey):
""" Initialize the Player """
self.upKey = upKey
self.downKey = downKey
def start(self):
""" Connect the player input """
self.inputH... | class Player:
""" Behavior to have a paddle controlled by the player """
def __init__(self, upKey, downKey):
""" Initialize the Player """
self.upKey = upKey
self.downKey = downKey
def start(self):
""" Connect the player input """
self.inputHandler.register(self.upK... |
## Model parameters
model_hidden_size = 256
model_embedding_size = 256
model_num_layers = 3
## Training parameters
learning_rate_init = 1e-4
#speakers_per_batch = 64
speakers_per_batch = 128
utterances_per_speaker = 10
| model_hidden_size = 256
model_embedding_size = 256
model_num_layers = 3
learning_rate_init = 0.0001
speakers_per_batch = 128
utterances_per_speaker = 10 |
fyrst_number = int(input())
second_number = int(input())
third_number = int(input())
if fyrst_number > second_number and fyrst_number > third_number:
print(fyrst_number)
elif second_number > fyrst_number and second_number > third_number:
print(second_number)
else:
print(third_number)
| fyrst_number = int(input())
second_number = int(input())
third_number = int(input())
if fyrst_number > second_number and fyrst_number > third_number:
print(fyrst_number)
elif second_number > fyrst_number and second_number > third_number:
print(second_number)
else:
print(third_number) |
class OGCSensor:
""" This class represents the SENSOR entity of the OCG Sensor Things model.
For more info: http://developers.sensorup.com/docs/#sensors_post
"""
def __init__(self, name: str, description: str, metadata, encoding: str = "application/pdf"):
self._id = None # the id is assign... | class Ogcsensor:
""" This class represents the SENSOR entity of the OCG Sensor Things model.
For more info: http://developers.sensorup.com/docs/#sensors_post
"""
def __init__(self, name: str, description: str, metadata, encoding: str='application/pdf'):
self._id = None
self._name = ... |
s1 = input().upper()
s2 = input().upper()
def sol(s1, s2):
i = 0
while i < len(s1):
if ord(s1[i]) < ord(s2[i]):
return -1
elif ord(s1[i]) > ord(s2[i]):
return 1
i += 1
return 0
print(sol(s1, s2)) | s1 = input().upper()
s2 = input().upper()
def sol(s1, s2):
i = 0
while i < len(s1):
if ord(s1[i]) < ord(s2[i]):
return -1
elif ord(s1[i]) > ord(s2[i]):
return 1
i += 1
return 0
print(sol(s1, s2)) |
lexy_copts = select({
"@bazel_tools//src/conditions:windows": ["/std:c++latest"],
"@bazel_tools//src/conditions:windows_msvc": ["/std:c++latest"],
"//conditions:default": ["-std=c++20"],
})
| lexy_copts = select({'@bazel_tools//src/conditions:windows': ['/std:c++latest'], '@bazel_tools//src/conditions:windows_msvc': ['/std:c++latest'], '//conditions:default': ['-std=c++20']}) |
class URLInfo:
def __init__(self, domain, subject):
self.domain = domain
self.subject = subject
def __str__(self):
result = ""
result += f"domain: {self.domain}\n"
result += f"subject: {self.subject}\n"
return result
| class Urlinfo:
def __init__(self, domain, subject):
self.domain = domain
self.subject = subject
def __str__(self):
result = ''
result += f'domain: {self.domain}\n'
result += f'subject: {self.subject}\n'
return result |
def insertion_sorting(input_array):
for i in range(len(input_array)):
value, position = input_array[i], i
while position > 0 and input_array[position-1] > value:
input_array[position] = input_array[position - 1]
position = position - 1
input_array[position] = value
... | def insertion_sorting(input_array):
for i in range(len(input_array)):
(value, position) = (input_array[i], i)
while position > 0 and input_array[position - 1] > value:
input_array[position] = input_array[position - 1]
position = position - 1
input_array[position] = va... |
A=[3,5,7]
B=[1,8]
C=[]
counter=0
while len(A)>0 and len(B)>0:
if A[0] <= B[0]:
C[counter]=A[0]
A=A[1:]
counter=counter+1
else:
C[counter]=B[0]
B=B[1:]
counter=counter+1
print(C)
| a = [3, 5, 7]
b = [1, 8]
c = []
counter = 0
while len(A) > 0 and len(B) > 0:
if A[0] <= B[0]:
C[counter] = A[0]
a = A[1:]
counter = counter + 1
else:
C[counter] = B[0]
b = B[1:]
counter = counter + 1
print(C) |
"""Source module to create ``Assumption`` space from.
This module is a source module to create ``Assumption`` space and its
sub spaces from.
The formulas of the cells in the ``Assumption`` space are created from the
functions defined in this module.
The ``Assumption`` space is the base space of the assumption spaces
... | """Source module to create ``Assumption`` space from.
This module is a source module to create ``Assumption`` space and its
sub spaces from.
The formulas of the cells in the ``Assumption`` space are created from the
functions defined in this module.
The ``Assumption`` space is the base space of the assumption spaces
... |
name = str(input('digite seu name: ')).upper()
if name == 'LUZIA':
print(f'{name} good night')
else:
print(f'hello {name}')
| name = str(input('digite seu name: ')).upper()
if name == 'LUZIA':
print(f'{name} good night')
else:
print(f'hello {name}') |
"""
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The n... | """
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The n... |
# All participants who ranked A-th or higher get a T-shirt.
# Additionally, from the participants who ranked between
# (A+1)-th and B-th (inclusive), C participants chosen uniformly at random get a T-shirt.
A, B, C, X = map(int, input().split())
if(X <= A):
print(1.000000000000)
elif(X > A and X <= B):
print(... | (a, b, c, x) = map(int, input().split())
if X <= A:
print(1.0)
elif X > A and X <= B:
print(C / (B - A))
else:
print(0.0) |
cifar10_config = {
'num_clients': 100,
'model_name': 'Cifar10Net', # Model type
'round': 1000,
'save_period': 200,
'weight_decay': 1e-3,
'batch_size': 50,
'test_batch_size': 256, # no this param in official code
'lr_decay_per_round': 1,
'epochs': 5,
'lr': 0.1,
'print_freq':... | cifar10_config = {'num_clients': 100, 'model_name': 'Cifar10Net', 'round': 1000, 'save_period': 200, 'weight_decay': 0.001, 'batch_size': 50, 'test_batch_size': 256, 'lr_decay_per_round': 1, 'epochs': 5, 'lr': 0.1, 'print_freq': 5, 'alpha_coef': 0.01, 'max_norm': 10, 'sample_ratio': 1, 'partition': 'iid', 'dataset': 'c... |
class ConnectedClientsList(list):
"""A response class representing the clients connected
to the router at this time (or that have been recently connected).
"""
pass
class ConnectedClientsListItem(object):
"""A client entry in the :class:`ConnectedClientsList`."""
LEASE_TIME_PERMANENT = 'Perma... | class Connectedclientslist(list):
"""A response class representing the clients connected
to the router at this time (or that have been recently connected).
"""
pass
class Connectedclientslistitem(object):
"""A client entry in the :class:`ConnectedClientsList`."""
lease_time_permanent = 'Permane... |
# Problem: Set Matrix Zeros
# Difficulty: Medium
# Category: Array
# Leetcode 73: https://leetcode.com/problems/set-matrix-zeroes/description/
# Description:
"""
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution... | """
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solutio... |
def insertion_sort(a, n):
"""
insertion sort algorithm
# outer loop from left to right start from 1
# inner loop from right to left end to right counter eq 0
start outer loop:
1. compare 2 elements
2. and swap
3. and decrement right counter
# let l be left_cnf
# let r be right... | def insertion_sort(a, n):
"""
insertion sort algorithm
# outer loop from left to right start from 1
# inner loop from right to left end to right counter eq 0
start outer loop:
1. compare 2 elements
2. and swap
3. and decrement right counter
# let l be left_cnf
# let r be right... |
# OpenWeatherMap API Key
weather_api_key = "9cfaeb3dbd4832137f0fb5f0e12ca0f4"
# Google API Key
g_key = "AIzaSyBwiWBdcMksrxnWzcOvCM1cjxhqV8017_A"
| weather_api_key = '9cfaeb3dbd4832137f0fb5f0e12ca0f4'
g_key = 'AIzaSyBwiWBdcMksrxnWzcOvCM1cjxhqV8017_A' |
input = """
zwanzig(A) :- A=5*4.
fuenf(A) :- 20=A*4.
eins(A) :- 3=2+A.
"""
output = """
zwanzig(A) :- A=5*4.
fuenf(A) :- 20=A*4.
eins(A) :- 3=2+A.
"""
| input = '\nzwanzig(A) :- A=5*4.\nfuenf(A) :- 20=A*4.\n\neins(A) :- 3=2+A.\n'
output = '\nzwanzig(A) :- A=5*4.\nfuenf(A) :- 20=A*4.\n\neins(A) :- 3=2+A.\n' |
"""A module for the ProjectListing class."""
class ProjectListing:
"""A class to respresent a projects listing."""
def __init__(self, response):
self.response = response
def can_access_project(self, project: str):
"""Check if the provided project ID is in the response."""
return ... | """A module for the ProjectListing class."""
class Projectlisting:
"""A class to respresent a projects listing."""
def __init__(self, response):
self.response = response
def can_access_project(self, project: str):
"""Check if the provided project ID is in the response."""
return a... |
class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return self.length * self.length
unittest = Square(88)
print(unittest.area())
unittest2 = Shape()
print((unittest2.area... | class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return self.length * self.length
unittest = square(88)
print(unittest.area())
unittest2 = shape()
print(unittest2.area... |
# TESTS FOR COLOURABLE
# graph with no vertices
g0 = Graph(0)
print(str(colourable(g0)) + "... should be TRUE")
# graph with one vertice (no edge)
g1 = Graph(1)
g1.matrix[0][0] = True
print(str(colourable(g1)) + "... should be FALSE")
# graph with one vertice (and edge)
g2 = Graph(1)
print(str(colourable(g2)) + "..... | g0 = graph(0)
print(str(colourable(g0)) + '... should be TRUE')
g1 = graph(1)
g1.matrix[0][0] = True
print(str(colourable(g1)) + '... should be FALSE')
g2 = graph(1)
print(str(colourable(g2)) + '... should be TRUE')
g3 = graph(2)
print(str(colourable(g3)) + '... should be TRUE')
g4 = graph(2)
g4.matrix[0][0] = True
pri... |
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
ret = set()
for i, v in enumerate(nums):
j, k = i + 1, len(nums) - 1
while j < k:
if nums[j] + nums[k] == -v:
ret.add((v, nums[j], nums[k]))
if nums[j] + nums[k] > -v:
k -= 1... | class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
ret = set()
for (i, v) in enumerate(nums):
(j, k) = (i + 1, len(nums) - 1)
while j < k:
if nums[j] + nums[k] == -v:
ret.add((v, nums[j], nums[k]))... |
'''
(C) Copyright 2021 Steven;
@author: Steven kangweibaby@163.com
@date: 2021-06-30
'''
| """
(C) Copyright 2021 Steven;
@author: Steven kangweibaby@163.com
@date: 2021-06-30
""" |
with open('day13/input.txt', 'r') as file:
timestamp = int(file.readline())
data = str(file.readline()).split(',')
data_1 = [int(x) for x in data if x != 'x']
res = sorted([(x - timestamp % x, x) for x in data_1], key=lambda x: x[0])
data_2 = [(int(x), data.index(x)) for x in data if x != 'x']
superbus_t... | with open('day13/input.txt', 'r') as file:
timestamp = int(file.readline())
data = str(file.readline()).split(',')
data_1 = [int(x) for x in data if x != 'x']
res = sorted([(x - timestamp % x, x) for x in data_1], key=lambda x: x[0])
data_2 = [(int(x), data.index(x)) for x in data if x != 'x']
superbus_time = d... |
#O(n) Space and time Complexity
# Maintain a frequency map as {prefix_Sum:frequency of this prefix sum}
# While looping the array:
#0. hash_map[current_prefix_sum] += 1
#1. If (current_prefix_sum - k) exists in the map, it means there is a subarray found hence increment the counter.
class Solution:
def subarraySu... | class Solution:
def subarray_sum(self, nums: List[int], k: int) -> int:
d = {}
D[0] = 1
s = 0
c = 0
for i in range(len(nums)):
s = s + nums[i]
if s - k in D:
c += D[s - k]
if s in D:
D[s] += 1
el... |
# Here's a challenge for you to help you practice
# See if you can fix the code below
# print the message
# There was a single quote inside the string!
# Use double quotes to enclose the string
print("Why won't this line of code print")
# print the message
# There was a mistake in the function name
print('This line ... | print("Why won't this line of code print")
print('This line fails too!')
print('I think I know how to fix this one')
name = input('Please tell me your name: ')
print(name) |
POST_ACTIONS = [
'oauth.getAccessToken',
'oauth.getRequestToken',
'oauth.verify',
'comment.digg',
'comment.bury',
'shorturl.create',
'story.bury',
'story.digg',
]
| post_actions = ['oauth.getAccessToken', 'oauth.getRequestToken', 'oauth.verify', 'comment.digg', 'comment.bury', 'shorturl.create', 'story.bury', 'story.digg'] |
N = input()
before = ""
count = 1
for s in N:
if before == -1:
before = s
else:
if before == s:
count += 1
if count >= 3:
print("Yes")
exit()
else:
before = s
count = 1
print("No")
| n = input()
before = ''
count = 1
for s in N:
if before == -1:
before = s
elif before == s:
count += 1
if count >= 3:
print('Yes')
exit()
else:
before = s
count = 1
print('No') |
class Optimizer:
pass
class RandomRestartOptimizer(Optimizer):
def __init__(self, N=10):
self.N=N | class Optimizer:
pass
class Randomrestartoptimizer(Optimizer):
def __init__(self, N=10):
self.N = N |
class Solution(object):
def license_key_formatiing(self, S, K):
"""
You are given a license key represented as a string S which consists only alphanumeric character and dashes.
The string is separated into N+1 groups by N dashes.
:type S: str
:type K: int
:rtype: str... | class Solution(object):
def license_key_formatiing(self, S, K):
"""
You are given a license key represented as a string S which consists only alphanumeric character and dashes.
The string is separated into N+1 groups by N dashes.
:type S: str
:type K: int
:rtype: st... |
class Piece(object):
BLACK = 'X'
WHITE = 'O'
def __init__(self, position, state):
self.x = position[0]
self.y = position[1]
self.state = state
@property
def other_side(self):
"""The opposite side of this piece.
Returns:
str: Whatever the other s... | class Piece(object):
black = 'X'
white = 'O'
def __init__(self, position, state):
self.x = position[0]
self.y = position[1]
self.state = state
@property
def other_side(self):
"""The opposite side of this piece.
Returns:
str: Whatever the other s... |
AUTH_USER_MODEL = 'users.User'
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validat... | auth_user_model = 'users.User'
auth_password_validators = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contr... |
class AlgorithmConfigurationProvider:
def __init__(self, chromosome_config, left_range_number, right_range_number, population_number,
epochs_number, selection_amount, elite_amount, selection_method, is_maximization):
self.__chromosome_config = chromosome_config
self.__left_range_... | class Algorithmconfigurationprovider:
def __init__(self, chromosome_config, left_range_number, right_range_number, population_number, epochs_number, selection_amount, elite_amount, selection_method, is_maximization):
self.__chromosome_config = chromosome_config
self.__left_range_number = left_range... |
def get_ids_and_classes(tag):
attrs = tag.attrs
if 'id' in attrs:
ids = attrs['id']
if isinstance(ids, list):
for subitem in ids:
yield subitem
else:
yield ids
if 'class' in attrs:
classes = attrs['class']
if isinstance(classes... | def get_ids_and_classes(tag):
attrs = tag.attrs
if 'id' in attrs:
ids = attrs['id']
if isinstance(ids, list):
for subitem in ids:
yield subitem
else:
yield ids
if 'class' in attrs:
classes = attrs['class']
if isinstance(classes,... |
def testHasMasterPrimary(nodeSet, up):
masterPrimaryCount = 0
for node in nodeSet:
masterPrimaryCount += int(node.monitor.hasMasterPrimary)
assert masterPrimaryCount == 1
| def test_has_master_primary(nodeSet, up):
master_primary_count = 0
for node in nodeSet:
master_primary_count += int(node.monitor.hasMasterPrimary)
assert masterPrimaryCount == 1 |
"""
Kata Sort deck of cards - Use a sort function to put cards in order
#1 Best Practices: zebulan, Unnamed, acaccia, j_codez, Mr.Child, iamchingel (plus 8 more warriors)
def sort_cards(cards):
return sorted(cards, key="A23456789TJQK".index)
."""
def sort_cards(cards):
"""Sort a deck of cards."""
a_buck... | """
Kata Sort deck of cards - Use a sort function to put cards in order
#1 Best Practices: zebulan, Unnamed, acaccia, j_codez, Mr.Child, iamchingel (plus 8 more warriors)
def sort_cards(cards):
return sorted(cards, key="A23456789TJQK".index)
."""
def sort_cards(cards):
"""Sort a deck of cards."""
a_bucke... |
###################################
# File Name : dir_normal_func.py
###################################
#!/usr/bin/python3
def normal_func():
pass
if __name__ == "__main__":
p = dir(normal_func())
print ("=== attribute ===")
print (p)
| def normal_func():
pass
if __name__ == '__main__':
p = dir(normal_func())
print('=== attribute ===')
print(p) |
# -*- coding: mbcs -*-
"""
=========================================
PyQus 0.1.0
Author: Pedro Jorge De Los Santos
E-mail: delossantosmfq@gmail.com
https://github.com/JorgeDeLosSantos/pyqus
=========================================
"""
| """
=========================================
PyQus 0.1.0
Author: Pedro Jorge De Los Santos
E-mail: delossantosmfq@gmail.com
https://github.com/JorgeDeLosSantos/pyqus
=========================================
""" |
dividendo=int(input("Dividendo: "))
divisor=int(input("Divisor: "))
if dividendo>0 and divisor>0:
cociente=0
residuo=dividendo
while (residuo>=divisor):
residuo-=divisor
cociente+=1
print(residuo)
print(cociente)
| dividendo = int(input('Dividendo: '))
divisor = int(input('Divisor: '))
if dividendo > 0 and divisor > 0:
cociente = 0
residuo = dividendo
while residuo >= divisor:
residuo -= divisor
cociente += 1
print(residuo)
print(cociente) |
"""
adam_objects.py
"""
class AdamObject(object):
def __init__(self):
self._uuid = None
self._runnable_state = None
self._children = None
def set_uuid(self, uuid):
self._uuid = uuid
def set_runnable_state(self, runnable_state):
self._runnable_state = runnable_... | """
adam_objects.py
"""
class Adamobject(object):
def __init__(self):
self._uuid = None
self._runnable_state = None
self._children = None
def set_uuid(self, uuid):
self._uuid = uuid
def set_runnable_state(self, runnable_state):
self._runnable_state = runnable_... |
# Sudoku Solver :https://leetcode.com/problems/sudoku-solver/
# Write a program to solve a Sudoku puzzle by filling the empty cells.
# A sudoku solution must satisfy all of the following rules:
# Each of the digits 1-9 must occur exactly once in each row.
# Each of the digits 1-9 must occur exactly once in e... | class Solution:
def solve_sudoku(self, board) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def can_add_val(value, r, c):
return value not in row[r] and value not in col[c] and (value not in sqr[sqr_index(r, c)])
def add_to_board(value... |
class FunctionMetadata:
def __init__(self):
self._constantReturnValue = ()
def setConstantReturnValue(self, value):
self._constantReturnValue = (value,)
def hasConstantReturnValue(self):
return self._constantReturnValue
def getConstantReturnValue(self):
return self._co... | class Functionmetadata:
def __init__(self):
self._constantReturnValue = ()
def set_constant_return_value(self, value):
self._constantReturnValue = (value,)
def has_constant_return_value(self):
return self._constantReturnValue
def get_constant_return_value(self):
retur... |
# https://www.codewars.com/kata/578553c3a1b8d5c40300037c/train/python
# Given an array of ones and zeroes, convert the equivalent binary value
# to an integer.
# Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
# Examples:
# Testing: [0, 0, 0, 1] ==> 1
# Testing: [0, 0, 1, 0] ==> 2
# Tes... | def binary_array_to_number(arr):
total = 0
i = 1
for num in arr[::-1]:
total += i * num
i *= 2
return total |
class Solution:
def rob(self, nums: List[int]) -> int:
def rob(l: int, r: int) -> int:
dp1 = 0
dp2 = 0
for i in range(l, r + 1):
temp = dp1
dp1 = max(dp1, dp2 + nums[i])
dp2 = temp
return dp1
if not nums:
return 0
if len(nums) < 2:
return nums... | class Solution:
def rob(self, nums: List[int]) -> int:
def rob(l: int, r: int) -> int:
dp1 = 0
dp2 = 0
for i in range(l, r + 1):
temp = dp1
dp1 = max(dp1, dp2 + nums[i])
dp2 = temp
return dp1
if not num... |
array = ['a', 'b', 'c']
def decorator(func):
def newValueOf(pos):
if pos >= len(array):
print("Oops! Array index is out of range")
return
func(pos)
return newValueOf
@decorator
def valueOf(index):
print(array[index])
valueOf(10)
| array = ['a', 'b', 'c']
def decorator(func):
def new_value_of(pos):
if pos >= len(array):
print('Oops! Array index is out of range')
return
func(pos)
return newValueOf
@decorator
def value_of(index):
print(array[index])
value_of(10) |
numero = 5
fracao = 6.1
online = True
texto = "Armando"
| numero = 5
fracao = 6.1
online = True
texto = 'Armando' |
maior = 0
pos = 0
for i in range(1, 11):
val = int(input())
if val > maior:
maior = val
pos = i
print('{}\n{}'.format(maior, pos))
| maior = 0
pos = 0
for i in range(1, 11):
val = int(input())
if val > maior:
maior = val
pos = i
print('{}\n{}'.format(maior, pos)) |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 14 09:42:46 2019
@author: ASUS
"""
class Solution:
def uniqueMorseRepresentations(self, words: list) -> int:
self.M = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","... | """
Created on Sun Jul 14 09:42:46 2019
@author: ASUS
"""
class Solution:
def unique_morse_representations(self, words: list) -> int:
self.M = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.