content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def XXX(self, x: int) -> int:
if x >=0 :
out_x = int(str(x)[::-1])
else:
out_x = -int(str(-x)[::-1])
if (out_x>-(2)**31) and (out_x<2**31-1):
return out_x
else:
return 0
| class Solution:
def xxx(self, x: int) -> int:
if x >= 0:
out_x = int(str(x)[::-1])
else:
out_x = -int(str(-x)[::-1])
if out_x > -2 ** 31 and out_x < 2 ** 31 - 1:
return out_x
else:
return 0 |
class Road():
def __init__(self):
self.curves = []
self.curve_table = {} | class Road:
def __init__(self):
self.curves = []
self.curve_table = {} |
# coding=utf-8
"""
Make this module executable with python -m racetrax
"""
| """
Make this module executable with python -m racetrax
""" |
#!/usr/bin/env python3
#
# game_keyboard_mapping.py
# Include keyboard mappings for different games, i.e.
# converting bunch of button names into MultiDiscrete action
# lists
#
# Structure:
# game_name: [
# (possible_button_for_action1, another_possible_button_for_action1),
# (possible_button_for_action2),
# ...... | key_mapping = {'Downwell': [('left shift',), ('a', 'left'), ('d', 'right')], 'CoTN_Bard': [('left',), ('right',), ('down',), ('up',)], 'SuperHexagon': [('a', 'left'), ('d', 'right')], 'BindingOfIsaac': [('left',), ('right',), ('up',), ('down',), ('a',), ('d',), ('s',), ('w',), ('e',), ('q',), ('space',)], 'BosonX': [('... |
n=int(input("enter a number\n"))
if n%7==0:
print("Divisible by 7")
else:
print("Not Divisible by 7")
| n = int(input('enter a number\n'))
if n % 7 == 0:
print('Divisible by 7')
else:
print('Not Divisible by 7') |
# complex_function_grapher.py
class ComplexFunctionGrapher(object):
# Derivatives of this class can graph complex-valued functions
# of a complex variable in a variety of ways.
def __init__(self, window_min=None, window_max=None):
self.window_min = complex(real=-10.0, imag=-10.0) if window_min... | class Complexfunctiongrapher(object):
def __init__(self, window_min=None, window_max=None):
self.window_min = complex(real=-10.0, imag=-10.0) if window_min is None else window_min
self.window_max = complex(real=10.0, image=10.0) if window_max is None else window_max
def graph_function(self, fu... |
"""
Arithmetic Functions
Arithmetic Functions are functions that work on individual numbers, lists, and arrays: in either symbolic or algebraic forms.
"""
| """
Arithmetic Functions
Arithmetic Functions are functions that work on individual numbers, lists, and arrays: in either symbolic or algebraic forms.
""" |
def main():
# input
S = input()
# compute
# output
print(S[0].upper() + S[1:].lower())
if __name__ == '__main__':
main()
| def main():
s = input()
print(S[0].upper() + S[1:].lower())
if __name__ == '__main__':
main() |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
start, end = m, n
d... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverse_between(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
(start, end) = (m, n)
... |
def test_verify_site(client):
content = client.get('/google11a50bcc62df11b5.html').content
assert '11a50bcc62df11b5' in str(content)
| def test_verify_site(client):
content = client.get('/google11a50bcc62df11b5.html').content
assert '11a50bcc62df11b5' in str(content) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumNumbers(self, root, string=''):
"""
:type root: TreeNode
:rtype: int
"""
i... | class Solution(object):
def sum_numbers(self, root, string=''):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return int(string or 0)
if root.left and root.right:
return self.sumNumbers(root.left, string + str(root.val)) + self.sumNumb... |
# Even number is divisible by 2 and odd number is not. Using the remainder of the number when divided by two we can find even or odd or using AND operation with 1.
#using % operator
a=int(input())
if a%2==0:
print("Even")
else:
print("Odd")
#using & operator
a=int(input())
if a & 1:
print("Odd")
else:
print... | a = int(input())
if a % 2 == 0:
print('Even')
else:
print('Odd')
a = int(input())
if a & 1:
print('Odd')
else:
print('Even') |
class Config(object):
max_len = 512 - 2
num_sample = 50
processed_path = "data/processed/dev.json"
def __init__(self):
pass
config = Config() | class Config(object):
max_len = 512 - 2
num_sample = 50
processed_path = 'data/processed/dev.json'
def __init__(self):
pass
config = config() |
def look_and_say(s):
output = []
i = 0
while i < len(s):
# Find a run of the form s[i:j] of length j - i > 0.
j = i + 1
while j < len(s) and s[j] == s[i]:
j += 1
output.append(str(j - i))
output.append(s[i])
i = j
return ''.join(output)
def m... | def look_and_say(s):
output = []
i = 0
while i < len(s):
j = i + 1
while j < len(s) and s[j] == s[i]:
j += 1
output.append(str(j - i))
output.append(s[i])
i = j
return ''.join(output)
def main():
seed = '1113122113'
for i in range(40):
... |
class DiscreteFuzzyNumberMembershipOutOfBounds(Exception):
"""
An Exception which indicates that the membership values entered are not between 0 and 1.
"""
def __init__(self, message: str = "The membership functions of the labels as well as the alpha-cuts thresholds "
... | class Discretefuzzynumbermembershipoutofbounds(Exception):
"""
An Exception which indicates that the membership values entered are not between 0 and 1.
"""
def __init__(self, message: str='The membership functions of the labels as well as the alpha-cuts thresholds must be between 0 and 1.'):
su... |
#
# @lc app=leetcode id=201 lang=python3
#
# [201] Bitwise AND of Numbers Range
#
# @lc code=start
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
while n > m:
n = n & (n - 1)
return n
# @lc code=end
# Accepted
# 8266/8266 cases passed(48 ms)
# Your runtime beats 9... | class Solution:
def range_bitwise_and(self, m: int, n: int) -> int:
while n > m:
n = n & n - 1
return n |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""
IdaSplode settings
"""
#
# Default color for instructions.
# Format: 0xRRGGBB
#
COLOR_INS_RESET = 0xffffff
#
# Color to set an instruction if it was executed during the run.
# Format: 0xRRGGBB
#
COLOR_INS_EXECUTED = 0xeeeeee
#
# Color to set... | """
IdaSplode settings
"""
color_ins_reset = 16777215
color_ins_executed = 15658734
color_ins_enhanced = 13421772
color_data_reference = 13434828
color_ins_trace_a_only = 16764108
color_ins_trace_b_only = 13421823
color_ins_trace_both = 15658734
section_name_dynamic = '.idasplode'
database_auto_load_most_recent = True
... |
dset = [(1,'L','Cerebellum-vermis',None,True,None),
(1,'R','Cerebellum-VI',None,True,True),
(1,'L','Cingulate-posterior',None,None,True),
(1,'R','Cingulate-posterior',None,None,True),
(1,'R','IFG-pars opercularis',None,None,True),
(1,'R','IFG-pars triangularis',None,None,True),
... | dset = [(1, 'L', 'Cerebellum-vermis', None, True, None), (1, 'R', 'Cerebellum-VI', None, True, True), (1, 'L', 'Cingulate-posterior', None, None, True), (1, 'R', 'Cingulate-posterior', None, None, True), (1, 'R', 'IFG-pars opercularis', None, None, True), (1, 'R', 'IFG-pars triangularis', None, None, True), (1, 'R', 'L... |
#!/usr/bin/env python
#-------------------------------------------------------------------------------
class Solution:
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int... | class Solution:
def flood_fill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
if sr >= 0 and sr < len(image) and (sc >= 0) and (sc < len(image[0])):
... |
def almostIncreasingSequence(sequence):
def helper(newArray):
# print(newArray)
if len(newArray)<2:
return True
for i in range(len(newArray)-1):
if newArray[i] >= newArray[i+1]:
return False
return True
i = 0
j = i+1
whil... | def almost_increasing_sequence(sequence):
def helper(newArray):
if len(newArray) < 2:
return True
for i in range(len(newArray) - 1):
if newArray[i] >= newArray[i + 1]:
return False
return True
i = 0
j = i + 1
while i < len(sequence) - 1:
... |
N = int(input())
v_list = list(map(int, input().split()))
c_list = list(map(int, input().split()))
ans = 0
for i in range(N):
v = v_list[i]
c = c_list[i]
if v > c:
ans += v -c
print(ans)
| n = int(input())
v_list = list(map(int, input().split()))
c_list = list(map(int, input().split()))
ans = 0
for i in range(N):
v = v_list[i]
c = c_list[i]
if v > c:
ans += v - c
print(ans) |
def hoopCount(n):
""" hoop_count == PEP8 (forced mixedCase by CodeWars) """
return 'Great, now move on to tricks' if n >= 10 else\
'Keep at it until you get it'
| def hoop_count(n):
""" hoop_count == PEP8 (forced mixedCase by CodeWars) """
return 'Great, now move on to tricks' if n >= 10 else 'Keep at it until you get it' |
# Keep track of Lexer position
class Position:
# index -> int index of the position
# ln_number -> int line number of the position
# col_number -> int column number of the position
# f_name -> string file name of the position
# f_text -> string text (input)
def __init__(self, index, ln_number, c... | class Position:
def __init__(self, index, ln_number, col_number, f_name, f_text):
self.index = index
self.lnNumber = ln_number
self.colNumber = col_number
self.fName = f_name
self.fText = f_text
def advance(self, current_char=None):
self.index += 1
self.... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 6, 2015
# Question: 094-Binary-Tree-Inorder-Traversal
# Link: https://leetcode.com/problems/binary-tree-inorder-traversal/
# ========================================... | class Solution:
def inorder_traversal(self, root):
if not root:
return []
else:
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right) |
test_list = []
n = None
while n != 0:
n = int(input())
if n !=0:
test_list.append(n)
c = 1
for value in test_list:
cedules = [0]*4
while 0 < value <= 10000:
if value//50 > 0:
cedules[0] += value//50
value=value%50
elif value//10 > 0:
cedul... | test_list = []
n = None
while n != 0:
n = int(input())
if n != 0:
test_list.append(n)
c = 1
for value in test_list:
cedules = [0] * 4
while 0 < value <= 10000:
if value // 50 > 0:
cedules[0] += value // 50
value = value % 50
elif value // 10 > 0:
... |
# -*- coding:utf-8 -*-
"""
@author: SiriYang
@file: __init__.py
@createTime: 2021-01-22 16:12:10
@updateTime: 2021-01-22 16:12:10
@codeLines: 0
"""
| """
@author: SiriYang
@file: __init__.py
@createTime: 2021-01-22 16:12:10
@updateTime: 2021-01-22 16:12:10
@codeLines: 0
""" |
a,b=input().split()
bSum,ans=0,0
for i in b: bSum+=int(i)
for i in a: ans+=int(i)*bSum
print(ans) | (a, b) = input().split()
(b_sum, ans) = (0, 0)
for i in b:
b_sum += int(i)
for i in a:
ans += int(i) * bSum
print(ans) |
#Create a script that checks a list against countries_clean.txt
#and creates a list with items that were in that file
checklist = ["Portugal", "Germany", "Munster", "Spain"]
with open("countries_clean.txt", "r") as file:
content = file.readlines()
content = [i.rstrip('\n') for i in content]
checked = [i for i in... | checklist = ['Portugal', 'Germany', 'Munster', 'Spain']
with open('countries_clean.txt', 'r') as file:
content = file.readlines()
content = [i.rstrip('\n') for i in content]
checked = [i for i in content if i in checklist]
print(checked) |
# import sys
# class Solution:
# def lengthOfLIS(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# data = nums
# memo = {}
# i = 0
# last = -1111111
# rt = self.recursion(data, i, last, memo)
# return rt
# def... | class Solution:
def length_of_lis(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
data = nums
data_len = len(data)
if data_len == 0:
return 0
sub_answer = [1] * data_len
for index_forward in range(1, data_len):
f... |
"""Given a string,S of length N that is indexed from 0 to N-1,
print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line
Note 0 is considered to be an even index.
input format
The first line contains an integer, T (the number of test cases).
Each line i of the T subsequent lines... | """Given a string,S of length N that is indexed from 0 to N-1,
print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line
Note 0 is considered to be an even index.
input format
The first line contains an integer, T (the number of test cases).
Each line i of the T subsequent lines... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
curre... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def right_side_view(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
cur... |
def sum_multiples_of_3_or_5_below_n(n):
"""
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.
"""
return sum(x for x in range(n) if (x % 3 == 0 or x % 5 == 0))
def problem001():
"""
Find the sum of al... | def sum_multiples_of_3_or_5_below_n(n):
"""
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.
"""
return sum((x for x in range(n) if x % 3 == 0 or x % 5 == 0))
def problem001():
"""
Find the sum of all... |
# The cli_spec is used by runAM.cli to build build argparse arguments.
cli_spec = {
'__main_parser': {
'help': '=== runAM (run Arista Module) CLI help ===\n To enable autocomplete run: eval "$(register-python-argcomplete runAM)"',
'add_argument': [
{
'arg_name': '--ec... | cli_spec = {'__main_parser': {'help': '=== runAM (run Arista Module) CLI help ===\n To enable autocomplete run: eval "$(register-python-argcomplete runAM)"', 'add_argument': [{'arg_name': '--echo', 'arg_short_name': '-e', 'action': 'store_true', 'default': True, 'help': 'Print child module output if available.'}]}, ... |
class Solution:
def removeInvalidParentheses(self, s):
r = []
self.remove(s, r, 0, 0, "()")
return r
def remove(self, s, r, li, lj, c):
cnt = 0
for i, e in enumerate(s[li:], start=li):
cnt += (1, -1, 0)[c.find(e)]
if cnt < 0:
for j... | class Solution:
def remove_invalid_parentheses(self, s):
r = []
self.remove(s, r, 0, 0, '()')
return r
def remove(self, s, r, li, lj, c):
cnt = 0
for (i, e) in enumerate(s[li:], start=li):
cnt += (1, -1, 0)[c.find(e)]
if cnt < 0:
... |
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
roomVisited = set()
keys = []
# Enter room 0
roomVisited.add(0)
for k in rooms[0]:
keys.append(k)
while keys:
# use the first key to unlock the door
... | class Solution:
def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool:
room_visited = set()
keys = []
roomVisited.add(0)
for k in rooms[0]:
keys.append(k)
while keys:
key = keys.pop(0)
if key in roomVisited:
continu... |
def read_gold_data(data_path: str):
return [
line.strip() for line in open(data_path)
]
def read_pred_data(data_str: str):
return data_str.split("\n")
| def read_gold_data(data_path: str):
return [line.strip() for line in open(data_path)]
def read_pred_data(data_str: str):
return data_str.split('\n') |
# define acronyms
acronyms = {
'AFK': 'Away From Keyboard',
'BBIAB': 'Be Back In A Bit',
'BBL': 'Be Back Later',
'BBS': 'Be Back Soon',
'BRB': 'Be Right Back',
'IDK': 'I Dont Know',
'KISS': 'Keep It Simple Stupid',
'LOL': 'Laughing Out Loud'
}
# get acronym from user input
acr = input(... | acronyms = {'AFK': 'Away From Keyboard', 'BBIAB': 'Be Back In A Bit', 'BBL': 'Be Back Later', 'BBS': 'Be Back Soon', 'BRB': 'Be Right Back', 'IDK': 'I Dont Know', 'KISS': 'Keep It Simple Stupid', 'LOL': 'Laughing Out Loud'}
acr = input('enter acronym: ')
result = acronyms.get(acr, '!404!')
print('result is:', result) |
output_header = ["image_names", "emergency_or_not"]
# =================================================================================
# Cornell Birdcall Identification
# =================================================================================
BIRD_CODE = {
'aldfly': 0, 'ameavo': ... | output_header = ['image_names', 'emergency_or_not']
bird_code = {'aldfly': 0, 'ameavo': 1, 'amebit': 2, 'amecro': 3, 'amegfi': 4, 'amekes': 5, 'amepip': 6, 'amered': 7, 'amerob': 8, 'amewig': 9, 'amewoo': 10, 'amtspa': 11, 'annhum': 12, 'astfly': 13, 'baisan': 14, 'baleag': 15, 'balori': 16, 'banswa': 17, 'barswa': 18,... |
def probability(num, den):
if den == 0:
return 0
return num / den
def matrixEdges(matrx, n):
edges = dict()
mylist = []
for i in range(n):
for j in range(n):
var = matrix[i][j]
if var not in edges:
edges[var] = []
if i - 1 >= 0:
... | def probability(num, den):
if den == 0:
return 0
return num / den
def matrix_edges(matrx, n):
edges = dict()
mylist = []
for i in range(n):
for j in range(n):
var = matrix[i][j]
if var not in edges:
edges[var] = []
if i - 1 >= 0:
... |
class WSApiException(Exception):
"""
Webservice exception from api.
"""
pass
| class Wsapiexception(Exception):
"""
Webservice exception from api.
"""
pass |
"""
Module to implement predicate classes.
Class of every predicate registered to ``Q`` is defined here.
"""
| """
Module to implement predicate classes.
Class of every predicate registered to ``Q`` is defined here.
""" |
elastic_mapping = {
"mappings":{
"patients":{
"_source":{
"enabled": True
},
"properties":{
"active":{
"type":"boolean"
},
"sex":{
"type":"keyword"
},
"yr_birth":{
... | elastic_mapping = {'mappings': {'patients': {'_source': {'enabled': True}, 'properties': {'active': {'type': 'boolean'}, 'sex': {'type': 'keyword'}, 'yr_birth': {'type': 'date'}, 'address': {'type': 'object', 'properties': {'add_date': {'type': 'keyword'}, 'communty': {'type': 'keyword'}, 'town': {'type': 'keyword'}, '... |
# Language: Python 3
# Author: Konstantin Kuchenmeister
# returns the length of a linked list
def getLength(head):
arr = []
while head is not None:
arr.append(head.data)
head = head.next
return len(arr)
# Intuition: Compare the two linkedlists pair/elementwise. If the numbe... | def get_length(head):
arr = []
while head is not None:
arr.append(head.data)
head = head.next
return len(arr)
def compare_lists(llist1, llist2):
counter = 0
length = get_length(llist1)
while llist1 is not None and llist2 is not None:
if llist1.data == llist2.data:
... |
hutang = 10000
bayar = 5000
sisaHutang = hutang - bayar
print ("Sisa hutang anda adalah ", sisaHutang)
| hutang = 10000
bayar = 5000
sisa_hutang = hutang - bayar
print('Sisa hutang anda adalah ', sisaHutang) |
"""Top-level package for dojo-cli."""
__author__ = """Robnet Kerns"""
__email__ = "robnet@jataware.com"
__version__ = "0.1.7"
| """Top-level package for dojo-cli."""
__author__ = 'Robnet Kerns'
__email__ = 'robnet@jataware.com'
__version__ = '0.1.7' |
"""Search Engine Keywords Highlighter"""
__version__ = '0.4'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/django-sekh'
| """Search Engine Keywords Highlighter"""
__version__ = '0.4'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/django-sekh' |
range = xrange; input = raw_input
ans = (0, -10**5)
for i in range(int(input())):
ans = max(ans, (int(input()), -i-1))
print(-ans[1])
| range = xrange
input = raw_input
ans = (0, -10 ** 5)
for i in range(int(input())):
ans = max(ans, (int(input()), -i - 1))
print(-ans[1]) |
# Copyright (c) 2021 Ben Maddison. All rights reserved.
#
"""aspa.neighbors Module."""
class _BaseNeighborType(object):
def __repr__(self):
try:
return self.name
except AttributeError:
return super().__repr__()
class _Customer(_BaseNeighborType):
name = "Customer"
c... | """aspa.neighbors Module."""
class _Baseneighbortype(object):
def __repr__(self):
try:
return self.name
except AttributeError:
return super().__repr__()
class _Customer(_BaseNeighborType):
name = 'Customer'
class _Provider(_BaseNeighborType):
name = 'Provider'
cl... |
manifest = "path_to_manifest_containing_tsvs"
with open(manifest+"/train.tsv",'r') as train_tsv, \
open(manifest+"/valid.tsv",'r') as val_tsv,\
open(manifest+"/dict.ltr.txt",'w') as dict_ltr,\
open(manifest+"/valid.wrd",'w') as wrd_val_out,\
open(manifest+"/train.wrd",'w') as wrd_train_out,\
open(manifest+"/valid.... | manifest = 'path_to_manifest_containing_tsvs'
with open(manifest + '/train.tsv', 'r') as train_tsv, open(manifest + '/valid.tsv', 'r') as val_tsv, open(manifest + '/dict.ltr.txt', 'w') as dict_ltr, open(manifest + '/valid.wrd', 'w') as wrd_val_out, open(manifest + '/train.wrd', 'w') as wrd_train_out, open(manifest + '/... |
#!/usr/bin/env python3
numRows = int( input() )
numColumns = int( input() )
rowList = []
matchRowIndexTuple = None
for rowIndex in range( numRows ):
thisRow = input()
# check for matching
for existingRowIndex, existingRowVal in enumerate( rowList ):
# print( 'thisRow = {}'.format( thisRow ) )
# print( 'existing... | num_rows = int(input())
num_columns = int(input())
row_list = []
match_row_index_tuple = None
for row_index in range(numRows):
this_row = input()
for (existing_row_index, existing_row_val) in enumerate(rowList):
if thisRow == existingRowVal:
match_row_index_tuple = (existingRowIndex, rowInde... |
{
"includes": [
"common.gypi"
],
"targets": [
{
"target_name": "tests",
"type": "executable",
"sources": [
"<!@(find ../test/ -name '*.cpp' ! -name 'writer_tests.cpp' ! -name 'writer_test_cases.cpp' ! -name 'testcase.cpp')"
],
"include_dirs": [
"../include/"... | {'includes': ['common.gypi'], 'targets': [{'target_name': 'tests', 'type': 'executable', 'sources': ["<!@(find ../test/ -name '*.cpp' ! -name 'writer_tests.cpp' ! -name 'writer_test_cases.cpp' ! -name 'testcase.cpp')"], 'include_dirs': ['../include/', '../test/include/']}, {'target_name': 'writer_tests', 'type': 'execu... |
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
l=len(primes)
i=[-1]*l
v=[1]*l
res=[1]*n
for k in xrange(n):
x=min(v)
res[k]=x
... | class Solution(object):
def nth_super_ugly_number(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
l = len(primes)
i = [-1] * l
v = [1] * l
res = [1] * n
for k in xrange(n):
x = min(v)
... |
# Just for npm
{
"targets": [{"target_name":"nop","type":"<(library)"}],
}
| {'targets': [{'target_name': 'nop', 'type': '<(library)'}]} |
#Chess knight moves like the letter L.
# It can move two cells horizontally and one cell vertically, or two cells vertically and one cells horizontally.
# Given two different cells of the chessboard, determine whether a knight can go from the first cell to the second in one move.
r = int(input("r =?"))
if r <1 or r >8... | r = int(input('r =?'))
if r < 1 or r > 8:
print('Invalid')
exit()
c = int(input('c = ?'))
if c < 1 or c > 8:
print('Invalid')
exit()
r = int(input('R = ?'))
if R < 1 or R > 8:
print('Invalid')
exit()
c = int(input('C = ?'))
if C < 1 or C > 8:
print('Invalid')
exit()
if R == r - 2 and (C ... |
# Not available in py3
#import dateutil
# This is not exactly ISO 8601, but close.
# Unfortunately datetime can't parse its own .isoformat() output
# (d'oh!)
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
def datetime_to_iso(d):
#return d.isoformat()
return d.strftime(DATETIME_FORMAT)
def iso_to_datetime(s):
... | datetime_format = '%Y-%m-%dT%H:%M:%S.%f'
def datetime_to_iso(d):
return d.strftime(DATETIME_FORMAT)
def iso_to_datetime(s):
return d.strptime(s, DATETIME_FORMAT)
def shortened_id(id_):
return id_[4:8] |
#!/usr/bin/env python3
class Laboratory():
"""
AmesPAHdbPythonSuite laboratory class
"""
def __init__(self, d=None, **keywords):
return None
| class Laboratory:
"""
AmesPAHdbPythonSuite laboratory class
"""
def __init__(self, d=None, **keywords):
return None |
"""
LINK: https://leetcode.com/problems/plus-one/
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the... | """
LINK: https://leetcode.com/problems/plus-one/
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the... |
def quickPower(a, n):
if n == 0:
return 1
if n == 1:
return a
if n % 2 == 0:
return quickPower(a, n / 2) * quickPower(a, n / 2)
else:
return quickPower(a, n - 1) * a
| def quick_power(a, n):
if n == 0:
return 1
if n == 1:
return a
if n % 2 == 0:
return quick_power(a, n / 2) * quick_power(a, n / 2)
else:
return quick_power(a, n - 1) * a |
class InternalServerException(Exception):
pass
class SchemaValidationException(Exception):
pass
class ObjectAlreadyExistsException(Exception):
pass
class UpdatingModelException(Exception):
pass
class DeletingModelException(Exception):
pass
class ObjectDoesNotExistException(Exception):
... | class Internalserverexception(Exception):
pass
class Schemavalidationexception(Exception):
pass
class Objectalreadyexistsexception(Exception):
pass
class Updatingmodelexception(Exception):
pass
class Deletingmodelexception(Exception):
pass
class Objectdoesnotexistexception(Exception):
pass
... |
# -*- coding: utf-8 -*-
"""Top-level package for Kawaii Reagan."""
__author__ = """Kawaii Gator"""
__email__ = 'kawaiigator@420blaze.it'
__version__ = '0.1.0'
| """Top-level package for Kawaii Reagan."""
__author__ = 'Kawaii Gator'
__email__ = 'kawaiigator@420blaze.it'
__version__ = '0.1.0' |
# Given an integer , n and n space-separated integers as input, create
# a tuple, t of those n integers. Then compute and print the result of hash(t) .
# Note : hash() is one of the functions in the __builtins__ module,
# so it need not be imported.
if __name__ == '__main__':
n = int ( input ( ) )
t =... | if __name__ == '__main__':
n = int(input())
t = tuple(map(int, input().split(' ')))
h = hash(t)
print(h) |
class Solution:
def isNumber(self, s: str) -> bool:
try:
float(s)
return True
except:
return False
# n : the length of input string
## Time Complexity: O( n )
#
# Although it seems O(1) at forst glimpse,
# but float(s) does che... | class Solution:
def is_number(self, s: str) -> bool:
try:
float(s)
return True
except:
return False
def test_bench():
test_data = ['.', '-+3', '1.23', '1.3e5', '-.', '+.3']
'\n False\n False\n True\n True\n False\n True\n '
for s... |
with open("input", "r") as f:
lines = f.readlines()
dots = []
folds = []
dots_list_finished = False
for line in lines:
line = line.strip()
if not line:
# empty line between list of dots and fold instructions
dots_list_finished = True
continue
if not dots_list_finished:
... | with open('input', 'r') as f:
lines = f.readlines()
dots = []
folds = []
dots_list_finished = False
for line in lines:
line = line.strip()
if not line:
dots_list_finished = True
continue
if not dots_list_finished:
(x, y) = line.split(',')
dots.append((int(x), int(y)))
... |
#
# PySNMP MIB module EFDMIM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EFDMIM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:44:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
# -*- coding: utf-8 -*-
"""Top-level package for Ovito Client."""
__author__ = """Ben Lindsay"""
__email__ = 'benjlindsay@gmail.com'
__version__ = '0.3.2'
| """Top-level package for Ovito Client."""
__author__ = 'Ben Lindsay'
__email__ = 'benjlindsay@gmail.com'
__version__ = '0.3.2' |
SECS_IN_HOUR = 60 * 60
def secs_to_hours(value):
return '{0:.1f}'.format(value / SECS_IN_HOUR)
| secs_in_hour = 60 * 60
def secs_to_hours(value):
return '{0:.1f}'.format(value / SECS_IN_HOUR) |
class EXTENSION_ERROR(Exception):
def __init__(self, expected_ext, given_ext, message):
self.message = message
self.expected_ext = expected_ext
self.given_ext = given_ext
super().__init__(self.message)
def __str__(self):
return "%s Expected '%s' but '%s' is given." % (... | class Extension_Error(Exception):
def __init__(self, expected_ext, given_ext, message):
self.message = message
self.expected_ext = expected_ext
self.given_ext = given_ext
super().__init__(self.message)
def __str__(self):
return "%s Expected '%s' but '%s' is given." % (s... |
DEFAULT_DB = "default" # this is the managed db for auth, users
PRISMA_DB = "prisma" # this is the unmanaged db for TD models
class PrismaRouter:
"""
A router to control db operations
"""
def db_for_read(self, model, **hints):
if not model._meta.managed:
return PRISMA_DB
... | default_db = 'default'
prisma_db = 'prisma'
class Prismarouter:
"""
A router to control db operations
"""
def db_for_read(self, model, **hints):
if not model._meta.managed:
return PRISMA_DB
return DEFAULT_DB
def db_for_write(self, model, **hints):
if not model.... |
class Graph:
def __init__(self):
self.name_to_id = {}
self.id_to_name = {}
self.node_count = 0
self.adj_list = {}
self.inv_adj_list = {}
self.dfs_current_run = 0
self.visited = {}
self.dfs_current_path = []
def add_node(self, node):
node ... | class Graph:
def __init__(self):
self.name_to_id = {}
self.id_to_name = {}
self.node_count = 0
self.adj_list = {}
self.inv_adj_list = {}
self.dfs_current_run = 0
self.visited = {}
self.dfs_current_path = []
def add_node(self, node):
node ... |
{
"metadata": {
"name": "Random Forest Variable Importance"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"import pandas as pd\n",
"import numpy as np\n",
"import pylab as pl\n",
"import ra... | {'metadata': {'name': 'Random Forest Variable Importance'}, 'nbformat': 3, 'nbformat_minor': 0, 'worksheets': [{'cells': [{'cell_type': 'code', 'collapsed': false, 'input': ['import pandas as pd\n', 'import numpy as np\n', 'import pylab as pl\n', 'import random'], 'language': 'python', 'metadata': {}, 'outputs': [], 'p... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | class Uvplabels:
feature_not_supported_msg = '(Not supported in this edition)'
feature_not_supported_icon = 'ERROR'
feature_not_supported_by_packing_mode_msg = '(Not supported by the packing mode)'
packing_device_warning = "If you don't see your Cuda GPU in the list, make sure you have latest GPU driver... |
class Solution:
def print2largest(self,A,N):
A.sort(reverse=True)
for i in range(1,N):
if A[i]!=A[i-1]:
return A[i]
return -1
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
ob=Solution()
print(ob.print2largest(a,... | class Solution:
def print2largest(self, A, N):
A.sort(reverse=True)
for i in range(1, N):
if A[i] != A[i - 1]:
return A[i]
return -1
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
ob = solution()
print(ob.... |
# Make a function that takes in the arguments height and weight and returns BMI
____
____
# Use the function to calculate the BMI of a person with height 62 inches and a weight of 105 lbs
# Save this in an object name bmi_calc
# ____ = ____
# Display the BMI
# ____
| ____
____ |
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
a, aop = 0, '+'
b, bop = 0, None
nv = 0
for c in s:
if '0' <= c <= '9': # construct the value
nv = nv * 10 + (ord(c) - ord('0'))
elif c == ' ': continue
elif c == '+':
if bop is not None:
nv = b * nv... | class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
(a, aop) = (0, '+')
(b, bop) = (0, None)
nv = 0
for c in s:
if '0' <= c <= '9':
nv = nv * 10 + (ord(c) - ord('0'))
elif c == ' ':
co... |
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
output = 0
index = matrix[0].index(min(matrix[0]))
temp = []
for i in range(0, len(matrix), 1):
if matrix[i].index(min(matrix[i])) == index or matrix[i].index(min(matrix[i])) == index + 1 or matr... | class Solution:
def min_falling_path_sum(self, matrix: List[List[int]]) -> int:
output = 0
index = matrix[0].index(min(matrix[0]))
temp = []
for i in range(0, len(matrix), 1):
if matrix[i].index(min(matrix[i])) == index or matrix[i].index(min(matrix[i])) == index + 1 or ... |
class LazyString(object):
"""Behaves like a string, but no instance is created until the string is actually used.
Takes a function which should be a string factory and a set of arguments to pass
to the factory. Whenever the string is accessed or manipulated the factory is called
to create the actual st... | class Lazystring(object):
"""Behaves like a string, but no instance is created until the string is actually used.
Takes a function which should be a string factory and a set of arguments to pass
to the factory. Whenever the string is accessed or manipulated the factory is called
to create the actual st... |
class A:
def __init__(self, x):
self.x = x
def __add__(self, y):
return self.x + y
def __len__(self):
return 10
def __iter__(self):
return iter(range(10))
def __str__(self):
return "bla"
a = A(3)
assert a + 1 == 4
assert len(a) == 10
i = 0
for j in a:... | class A:
def __init__(self, x):
self.x = x
def __add__(self, y):
return self.x + y
def __len__(self):
return 10
def __iter__(self):
return iter(range(10))
def __str__(self):
return 'bla'
a = a(3)
assert a + 1 == 4
assert len(a) == 10
i = 0
for j in a:
... |
# The words listed below will be ignored when considering thesaurizing
# They need to remain unchanged to maintain proper sentence structure
WORDS = [
"the",
"of",
"and",
"a",
"to",
"in",
"is",
"you",
"that",
"it",
"he",
"was",
"for",
"on",
"are",
"as",
"with",
"his",
"they",
"I... | words = ['the', 'of', 'and', 'a', 'to', 'in', 'is', 'you', 'that', 'it', 'he', 'was', 'for', 'on', 'are', 'as', 'with', 'his', 'they', 'I', 'at', 'be', 'this', 'have', 'from', 'or', 'one', 'had', 'by', 'but', 'not', 'what', 'why', 'all', 'were', 'we', 'when', 'your', 'can', 'said', 'there', 'use', 'an', 'each', 'which'... |
class PerformanceLogger:
def __init__(self):
self.min_valid_loss = float("inf")
self.min_valid_epoch = -1
self.min_valid_train_loss = float("inf")
self.min_valid_test_loss = float("inf")
self.min_valid_valid_acc = 0
self.min_valid_test_acc = 0
self.min_test_l... | class Performancelogger:
def __init__(self):
self.min_valid_loss = float('inf')
self.min_valid_epoch = -1
self.min_valid_train_loss = float('inf')
self.min_valid_test_loss = float('inf')
self.min_valid_valid_acc = 0
self.min_valid_test_acc = 0
self.min_test_l... |
#Write a Python program to get a string which is n (non-negative integer) copies of a given string.
def newest(string,n):
return string*n
print(newest('odks',4))
print(newest('Gabriel',9))
print(newest('I love you',10)) | def newest(string, n):
return string * n
print(newest('odks', 4))
print(newest('Gabriel', 9))
print(newest('I love you', 10)) |
"""
dictionary.py
Words used across the project, sorted in alphabetical order.
"""
# A
D_A_STAR = 'A*'
D_ANGLE = 'angle'
D_ANGLE_NOISE = 'angle_noise'
D_AVG = 'avg'
# C
D_CLAMPED_ABS = 'clamped_abs'
D_CLAMPED_LINEAR = 'clamped_linear'
D_COS = 'cos'
# D
D_DIST_TO_TARGET = 'distance_to_target'
D_DISTANCE = 'distance'... | """
dictionary.py
Words used across the project, sorted in alphabetical order.
"""
d_a_star = 'A*'
d_angle = 'angle'
d_angle_noise = 'angle_noise'
d_avg = 'avg'
d_clamped_abs = 'clamped_abs'
d_clamped_linear = 'clamped_linear'
d_cos = 'cos'
d_dist_to_target = 'distance_to_target'
d_distance = 'distance'
d_distance_avg... |
HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Max-Age": "3600",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0",
}
SCHEMA_NAMES = ["Recipe", "WebPage"... | headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}
schema_names = ['Recipe', 'WebPage']
syntaxes = ['json-ld'... |
""" Lomuto Partition : We are given an array and we have to put all elements smaller than this element to left and
bigger to the right. We assume that the pivot is always the last element in the array
If we are given a pivot element we can swap the pivot ad high to use this algorithm"""
"""Implementation"""
... | """ Lomuto Partition : We are given an array and we have to put all elements smaller than this element to left and
bigger to the right. We assume that the pivot is always the last element in the array
If we are given a pivot element we can swap the pivot ad high to use this algorithm"""
'Implementation'
def lo... |
"""
Python trove classifiers and classifiers groups
"""
# pylint: disable=too-few-public-methods
class TroveClassifier:
"""
Base class for trove classifiers
"""
def __init__(self, parent, path):
self.parent = parent
self.path = path
self.name = path[-1]
def __repr__(self):... | """
Python trove classifiers and classifiers groups
"""
class Troveclassifier:
"""
Base class for trove classifiers
"""
def __init__(self, parent, path):
self.parent = parent
self.path = path
self.name = path[-1]
def __repr__(self):
return ' :: '.join(self.path)
c... |
def get_register_class(register):
return register.name.lower() + "_reg"
def get_register_inst(register):
return register.name
def get_field_inst(field):
return field.name
| def get_register_class(register):
return register.name.lower() + '_reg'
def get_register_inst(register):
return register.name
def get_field_inst(field):
return field.name |
"""
Vk reader exe - https://github.com/Moonquit/vkdreader/releases/download/1.0/vkdreader.exe
This directory contains the files used for compiling to exe. You can compile it yourself using pyinstaller:
> cd vkdreader/app
> pip install -r requirements.txt
> pyinstaller --onefile --icon=icon.ico main.py
The compiled ex... | """
Vk reader exe - https://github.com/Moonquit/vkdreader/releases/download/1.0/vkdreader.exe
This directory contains the files used for compiling to exe. You can compile it yourself using pyinstaller:
> cd vkdreader/app
> pip install -r requirements.txt
> pyinstaller --onefile --icon=icon.ico main.py
The compiled ex... |
a = int(input())
b = int(input())
buf = "no"
for i in range(9999):
if i % 2:
if b == i:
buf = "yes"
else:
if a == i:
buf = "yes"
if buf != "no":
break
print(buf)
| a = int(input())
b = int(input())
buf = 'no'
for i in range(9999):
if i % 2:
if b == i:
buf = 'yes'
elif a == i:
buf = 'yes'
if buf != 'no':
break
print(buf) |
class Solution:
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
data = []
flip = lambda s: s[::-1] if len(s) <= k else s[:k][::-1] + s[k:]
for c in range(0, len(s), 2 * k):
data.append(flip(s[c:c + 2 * k]))
... | class Solution:
def reverse_str(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
data = []
flip = lambda s: s[::-1] if len(s) <= k else s[:k][::-1] + s[k:]
for c in range(0, len(s), 2 * k):
data.append(flip(s[c:c + 2 * k]))
... |
n = int(input())
output = 0
for i in range(n):
polyhedron = input()
polyhedron = polyhedron.lower()
if polyhedron == "tetrahedron":
output += 4
elif polyhedron == "cube":
output += 6
elif polyhedron == "octahedron":
output += 8
elif polyhedron == "dodecahedron"... | n = int(input())
output = 0
for i in range(n):
polyhedron = input()
polyhedron = polyhedron.lower()
if polyhedron == 'tetrahedron':
output += 4
elif polyhedron == 'cube':
output += 6
elif polyhedron == 'octahedron':
output += 8
elif polyhedron == 'dodecahedron':
o... |
##################################################################################################
# PURPOSE: Deriving XGBoost regression moodel from example data
# WARNING: Runnig this script reguires inclusion of the following external modules (libraries):
# os, datetime (dt), time, sys, pickle, pandas (... | input_path = os.path.normpath('<location/directorry of input data>')
output_path = os.path.normpath('<location/directorry of output data>')
data_folder = 'PICKLE'
data_set = '<file name>'
data_version = '<data version time stamp>'
data_variant = '<data variant>'
data_source = os.path.join(input_path, 'PICKLE', data_set... |
x_nocollinearity = predictors.drop(['dewtemp_F','wind_mph','wind_dir','windgust_dir','SOLIN_Wm2','prec_occur'],axis=1)
x_train_bal, y_train_bal, x_test_bal, y_test_bal = dataprep_pipeline(x_nocollinearity, y, verbose=False)
# Using the same Random Forest classifier as above, just changing the training data.
forest_no... | x_nocollinearity = predictors.drop(['dewtemp_F', 'wind_mph', 'wind_dir', 'windgust_dir', 'SOLIN_Wm2', 'prec_occur'], axis=1)
(x_train_bal, y_train_bal, x_test_bal, y_test_bal) = dataprep_pipeline(x_nocollinearity, y, verbose=False)
forest_nocollinearity = random_forest_classifier(n_estimators=10, max_depth=2)
forest_no... |
# python3
seq = [int(i) for i in input().split()]
search_seq = [int(i) for i in input().split()]
n = seq[0]
seq = seq[1:]
def binary_search(seq, elt, r):
l = 0
while l<=r:
m = (l+r)//2
if elt > seq[m]:
l = m + 1
elif elt < seq[m]:
r = m - 1
else:
... | seq = [int(i) for i in input().split()]
search_seq = [int(i) for i in input().split()]
n = seq[0]
seq = seq[1:]
def binary_search(seq, elt, r):
l = 0
while l <= r:
m = (l + r) // 2
if elt > seq[m]:
l = m + 1
elif elt < seq[m]:
r = m - 1
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 19:02:11 2021
@author:
"""
class GenericParams(object):
def __init__(self, filename=None):
self.filename = filename
#function to map timestamp and provide mapping between Ground Truth Data and Perception Data
def TimeStamp_Mapping(inputData_LG... | """
Created on Tue Feb 23 19:02:11 2021
@author:
"""
class Genericparams(object):
def __init__(self, filename=None):
self.filename = filename
def time_stamp__mapping(inputData_LG):
print('Entering in TimeStampMatching function')
stamping_lg = []
nano_id = 0
for idx i... |
MyNumb = 12346789
Answer = False
for i in str(MyNumb):
if i == '5':
Answer = True
break
if Answer == 1:print ('YES')
else:print('NO') | my_numb = 12346789
answer = False
for i in str(MyNumb):
if i == '5':
answer = True
break
if Answer == 1:
print('YES')
else:
print('NO') |
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
lis = s.split()
if len(lis)==0:
return 0
else:
return (len(lis[-1]))
| class Solution(object):
def length_of_last_word(self, s):
"""
:type s: str
:rtype: int
"""
lis = s.split()
if len(lis) == 0:
return 0
else:
return len(lis[-1]) |
#!python
if __name__ == '__main__':
print("ASDF not defined")
print("bye")
| if __name__ == '__main__':
print('ASDF not defined')
print('bye') |
# -*- coding: utf-8 -*-
PAGSEGURO_API_URL = 'https://ws.pagseguro.uol.com.br/v2/checkout'
PAGSEGURO_PAYMENT_URL = 'https://pagseguro.uol.com.br/v2/checkout/payment.html'
PAGSEGURO_NOTIFICATION_URL = 'https://ws.pagseguro.uol.com.br/v2/transactions/notifications/'
| pagseguro_api_url = 'https://ws.pagseguro.uol.com.br/v2/checkout'
pagseguro_payment_url = 'https://pagseguro.uol.com.br/v2/checkout/payment.html'
pagseguro_notification_url = 'https://ws.pagseguro.uol.com.br/v2/transactions/notifications/' |
num = list(map(int, input('Enter N & K: ').split()))
arr = list(map(int, input('Enter numbers: ').split()))
sum1 = 0
for i in range(num[1]):
sum1 += arr[i]
print(sum1)
| num = list(map(int, input('Enter N & K: ').split()))
arr = list(map(int, input('Enter numbers: ').split()))
sum1 = 0
for i in range(num[1]):
sum1 += arr[i]
print(sum1) |
def solve_me_first(a,b):
return a + b
num1 = input()
num2 = input()
res = solve_me_first(num1, num2)
print(res)
| def solve_me_first(a, b):
return a + b
num1 = input()
num2 = input()
res = solve_me_first(num1, num2)
print(res) |
class Solution:
def findComplement(self, num: int) -> int:
return int(f'{num:b}'.replace('0', 'a').replace('1', '0').replace('a', '1'), base=2)
# return num ^ (2**num.bit_length() - 1)
# return num ^ ((1<<num.bit_length()) - 1)
c = Solution().findComplement
print(f'''
{c(5)}
{c(1)}... | class Solution:
def find_complement(self, num: int) -> int:
return int(f'{num:b}'.replace('0', 'a').replace('1', '0').replace('a', '1'), base=2)
c = solution().findComplement
print(f'\n{c(5)}\n{c(1)}\n') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.