content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
coords = []
for ry in range(-2, 3):
for rx in range(2, -3, -1):
x = rx / 4
y = ry / 4
coords.append((x,y))
for p in range(16):
y, x = divmod(p, 4)
top_right = coords[(y+1)*5 + x]
top_left = coords[(y+1)*5 + x + 1]
bottom_left = coords[y*5 + x + 1]
bottom_right = coords[y... | coords = []
for ry in range(-2, 3):
for rx in range(2, -3, -1):
x = rx / 4
y = ry / 4
coords.append((x, y))
for p in range(16):
(y, x) = divmod(p, 4)
top_right = coords[(y + 1) * 5 + x]
top_left = coords[(y + 1) * 5 + x + 1]
bottom_left = coords[y * 5 + x + 1]
bottom_righ... |
"""df[{}] = df[{}].astype({})"""
def run(dfs: dict, settings: dict) -> dict:
"""df[{}] = df[{}].astype({})"""
if 'columns' not in settings:
raise Exception('Missing columns param')
dfs[settings['df']] = dfs[settings['df']].astype(settings['columns'])
return dfs
| """df[{}] = df[{}].astype({})"""
def run(dfs: dict, settings: dict) -> dict:
"""df[{}] = df[{}].astype({})"""
if 'columns' not in settings:
raise exception('Missing columns param')
dfs[settings['df']] = dfs[settings['df']].astype(settings['columns'])
return dfs |
# -*- coding: utf-8 -*-
__author__ = 'Bruno Paes'
__email__ = 'brunopaes05@gmail.com'
__github__ = 'https://www.github.com/Brunopaes'
__status__ = 'Finalised'
class Viginere(object):
@staticmethod
def encrypt(plaintext, key):
key_length = len(key)
key_as_int = [ord(i) for i in key]
pla... | __author__ = 'Bruno Paes'
__email__ = 'brunopaes05@gmail.com'
__github__ = 'https://www.github.com/Brunopaes'
__status__ = 'Finalised'
class Viginere(object):
@staticmethod
def encrypt(plaintext, key):
key_length = len(key)
key_as_int = [ord(i) for i in key]
plaintext_int = [ord(i) for... |
"""
Hash tables :: Day 1 Notes: Arrays
An array:
* Stores a sequence of elements
* Each element must be the same data type
* Occupies a contiguous block of memory
* Can access data in constant time with this equation:
`memory_address = starting_address + index * data_size`
"""
class DynamicArray:
def __init__(... | """
Hash tables :: Day 1 Notes: Arrays
An array:
* Stores a sequence of elements
* Each element must be the same data type
* Occupies a contiguous block of memory
* Can access data in constant time with this equation:
`memory_address = starting_address + index * data_size`
"""
class Dynamicarray:
def __init__(... |
predictor_url = 'http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2'
predictor_file = '../weights/shape_predictor_68_face_landmarks.dat'
p2v_model_gdrive_id = '1op5_zyH4CWm_JFDdCUPZM4X-A045ETex'
sample_image = '../examples/sample.jpg'
| predictor_url = 'http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2'
predictor_file = '../weights/shape_predictor_68_face_landmarks.dat'
p2v_model_gdrive_id = '1op5_zyH4CWm_JFDdCUPZM4X-A045ETex'
sample_image = '../examples/sample.jpg' |
def main(request, response):
name = request.GET.first(b"name")
value = request.GET.first(b"value")
source_origin = request.headers.get(b"origin", None)
response_headers = [(b"Set-Cookie", name + b"=" + value),
(b"Access-Control-Allow-Origin", source_origin),
... | def main(request, response):
name = request.GET.first(b'name')
value = request.GET.first(b'value')
source_origin = request.headers.get(b'origin', None)
response_headers = [(b'Set-Cookie', name + b'=' + value), (b'Access-Control-Allow-Origin', source_origin), (b'Access-Control-Allow-Credentials', b'true'... |
# Leetcode 435. Non-overlapping Intervals
#
# Link: https://leetcode.com/problems/non-overlapping-intervals/
# Difficulty: Medium
# Solution using sorting.
# Complexity:
# O(NlogN) time | where N represent the number of intervals
# O(1) space
class Solution:
def eraseOverlapIntervals(self, intervals: List[List... | class Solution:
def erase_overlap_intervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda pair: pair[0])
result = 0
prev_end = intervals[0][1]
for (start, end) in intervals[1:]:
if start >= prevEnd:
prev_end = end
else:
... |
BOARD_TILE_SIZE = 56 # the size of each board tile
BOARD_PLAYER_SIZE = 20 # the size of each player icon
BOARD_MARGIN = (10, 0) # margins, in pixels (for player icons)
PLAYER_ICON_IMAGE_SIZE = 32 # the size of the image to download, should a power of 2 and higher than BOARD_PLAYER_SIZE
MAX_PLAYERS ... | board_tile_size = 56
board_player_size = 20
board_margin = (10, 0)
player_icon_image_size = 32
max_players = 4
board = {2: 38, 7: 14, 8: 31, 15: 26, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 78: 98, 87: 94, 99: 80, 95: 75, 92: 88, 89: 68, 74: 53, 64: 60, 62: 19, 49: 11, 46: 25, 16: 6} |
def truncate(string, length):
"Ensure a string is no longer than a given length."
if len(string) <= length:
return string
else:
return string[:length]
| def truncate(string, length):
"""Ensure a string is no longer than a given length."""
if len(string) <= length:
return string
else:
return string[:length] |
def insertionSort(arr, size):
for i in range(1, size):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def shakerSort(arr, size):
left = 0
right = size - 1
lastSwap = 0
... | def insertion_sort(arr, size):
for i in range(1, size):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def shaker_sort(arr, size):
left = 0
right = size - 1
last_swap = 0
while ... |
def mergeOverlappingIntervals(intervals):
sortedIntervals = sorted(intervals, key=lambda x: x[0])
overlappingIntervals = []
left = sortedIntervals[0][0]
right = sortedIntervals[0][1]
for i in range(1, len(sortedIntervals)):
if right >= sortedIntervals[i][0]:
right = max(right, so... | def merge_overlapping_intervals(intervals):
sorted_intervals = sorted(intervals, key=lambda x: x[0])
overlapping_intervals = []
left = sortedIntervals[0][0]
right = sortedIntervals[0][1]
for i in range(1, len(sortedIntervals)):
if right >= sortedIntervals[i][0]:
right = max(right... |
# hash
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
count_map = {}
res = []
for num in nums1:
count_map[num] = count_map.get(num, 0) + 1
for num ... | class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
count_map = {}
res = []
for num in nums1:
count_map[num] = count_map.get(num, 0) + 1
for num in nums... |
class GameLogic:
def __int__(self):
self
def add_lander(self, lander):
self.lander = lander
def update(self, delta_time):
self.lander.update_lander(delta_time) | class Gamelogic:
def __int__(self):
self
def add_lander(self, lander):
self.lander = lander
def update(self, delta_time):
self.lander.update_lander(delta_time) |
data = []
with open("data.txt") as file:
data = [int(x) for x in file.read().split(",")]
def part_one(data, noun, verb):
opcode = 0
data_c = data[:]
data_c[1] = noun
data_c[2] = verb
while True:
if data_c[opcode] == 1:
data_c[data_c[opcode + 3]] = data_c[data_c[... | data = []
with open('data.txt') as file:
data = [int(x) for x in file.read().split(',')]
def part_one(data, noun, verb):
opcode = 0
data_c = data[:]
data_c[1] = noun
data_c[2] = verb
while True:
if data_c[opcode] == 1:
data_c[data_c[opcode + 3]] = data_c[data_c[opcode + 1]] ... |
# coding=utf8
"""
Prolog Grammar of ATIS
"""
GRAMMAR_DICTIONARY = {}
ROOT_RULE = 'statement -> [answer]'
GRAMMAR_DICTIONARY['statement'] = ['(answer ws)']
GRAMMAR_DICTIONARY['answer'] = [
'("answer_1(" var "," goal ")")',
'("answer_2(" var "," var "," goal ")")',
'("answer_3(" var "," var "," var "," g... | """
Prolog Grammar of ATIS
"""
grammar_dictionary = {}
root_rule = 'statement -> [answer]'
GRAMMAR_DICTIONARY['statement'] = ['(answer ws)']
GRAMMAR_DICTIONARY['answer'] = ['("answer_1(" var "," goal ")")', '("answer_2(" var "," var "," goal ")")', '("answer_3(" var "," var "," var "," goal ")")', '("answer_4(" var ","... |
var = 'foo'
def ex2():
var = 'bar'
print ('inside the function var is ', var)
ex2()
def ex3():
global var
var = 'bar'
print ('inside the function var is ', var)
ex3()
print ('outside the function var is ', var)
| var = 'foo'
def ex2():
var = 'bar'
print('inside the function var is ', var)
ex2()
def ex3():
global var
var = 'bar'
print('inside the function var is ', var)
ex3()
print('outside the function var is ', var) |
code = bytearray([
0xa9, 0xff,
0x8d, 0x02, 0x60,
0xa9, 0x55, # lda #$55
0x8d, 0x00, 0x60, #sta $6000
0xa9, 0x00, # lda #00
0x8d, 0x00, 0x60, #sta $6000
0x4c, 0x05, 0x80 #jmp 8005 (#lda $55)
])
rom = code + bytearray([0xea] * (32768 - len(code)) )
rom[0x7ffc] = 0x00
rom[0x7ffd] = 0x... | code = bytearray([169, 255, 141, 2, 96, 169, 85, 141, 0, 96, 169, 0, 141, 0, 96, 76, 5, 128])
rom = code + bytearray([234] * (32768 - len(code)))
rom[32764] = 0
rom[32765] = 128
with open('rom.bin', 'wb') as out_file:
out_file.write(rom) |
_sampler = None
def get_sampler():
return _sampler
def set_sampler(sampler):
global _sampler
_sampler = sampler
| _sampler = None
def get_sampler():
return _sampler
def set_sampler(sampler):
global _sampler
_sampler = sampler |
class Node:
def __init__(self,id,parent,val):
self.id=id
self.parent=parent
self.ch1,self.ch2=0,0
self.val=val
self.leaf=True
n=int(input())
orix=[*map(int,input().split())]
x=sorted(orix)
node=dict()
node[1]=Node(1,0,-1)
cnt=1
li=[]
for i in x:
li2=[]
root=node[1]
... | class Node:
def __init__(self, id, parent, val):
self.id = id
self.parent = parent
(self.ch1, self.ch2) = (0, 0)
self.val = val
self.leaf = True
n = int(input())
orix = [*map(int, input().split())]
x = sorted(orix)
node = dict()
node[1] = node(1, 0, -1)
cnt = 1
li = []
for i... |
#!/usr/bin/env python
# coding=utf-8
'''
@Author: John
@Email: johnjim0816@gmail.com
@Date: 2019-11-15 13:46:12
@LastEditor: John
@LastEditTime: 2020-07-29 22:43:12
@Discription:
@Environment:
'''
class Solution:
def singleNumber(self, nums: List[int]) -> int:
seen_once = seen_twice = 0
for num in... | """
@Author: John
@Email: johnjim0816@gmail.com
@Date: 2019-11-15 13:46:12
@LastEditor: John
@LastEditTime: 2020-07-29 22:43:12
@Discription:
@Environment:
"""
class Solution:
def single_number(self, nums: List[int]) -> int:
seen_once = seen_twice = 0
for num in nums:
seen_once = ~se... |
res = 0
i = 0
nb = int(input())
if nb == -1:
while i != 'F':
i = input()
if i != 'F':
res += int(i)
else:
for x in range(nb):
i = int(input())
res += i
print(res) | res = 0
i = 0
nb = int(input())
if nb == -1:
while i != 'F':
i = input()
if i != 'F':
res += int(i)
else:
for x in range(nb):
i = int(input())
res += i
print(res) |
#
# Example file for working with conditional statements
#
def main():
x, y = 10, 100
# conditional flow uses if, elif, else
if x < y:
print("x is smaller than y")
elif x == y:
print("x has same value as y")
else:
print("x is larger than y")
# conditional statements let you use "a if C e... | def main():
(x, y) = (10, 100)
if x < y:
print('x is smaller than y')
elif x == y:
print('x has same value as y')
else:
print('x is larger than y')
result = 'x is less than y' if x < y else 'x is same as or larger than y'
print(result)
if __name__ == '__main__':
main(... |
class AreaLight:
def __init__(self, shape_id, intensity, two_sided = False):
assert(intensity.device.type == 'cpu')
self.shape_id = shape_id
self.intensity = intensity
self.two_sided = two_sided
def state_dict(self):
return {
'shape_id': self.shape_id,
... | class Arealight:
def __init__(self, shape_id, intensity, two_sided=False):
assert intensity.device.type == 'cpu'
self.shape_id = shape_id
self.intensity = intensity
self.two_sided = two_sided
def state_dict(self):
return {'shape_id': self.shape_id, 'intensity': self.int... |
"""
Scaling functions that take PCB and modbus register version numbers, and convert raw
register values into real values.
"""
def scale_5v(value, reverse=False, pcb_version=0):
"""
Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw
value to a... | """
Scaling functions that take PCB and modbus register version numbers, and convert raw
register values into real values.
"""
def scale_5v(value, reverse=False, pcb_version=0):
"""
Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw
value to a ... |
#
# PySNMP MIB module CISCO-VOICE-CAS-MODULE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-CAS-MODULE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) ... |
#
# PySNMP MIB module CISCOSB-rlInterfaces (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-rlInterfaces
# Produced by pysmi-0.3.4 at Wed May 1 12:24:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
def solveQuestion(inputPath):
fileP = open(inputPath, 'r')
fileLines = fileP.readlines()
fileP.close()
newPosition = []
numRows = len(fileLines)
numCols = len(fileLines[0].strip('\n'))
for line in fileLines:
currentLine = []
for grid in line.strip('\n'):
... | def solve_question(inputPath):
file_p = open(inputPath, 'r')
file_lines = fileP.readlines()
fileP.close()
new_position = []
num_rows = len(fileLines)
num_cols = len(fileLines[0].strip('\n'))
for line in fileLines:
current_line = []
for grid in line.strip('\n'):
cu... |
"""
The trick here is that I am using the new_ls parameter as a list to append.
Since this list is created on first call to the function it is the same object that
I append to.
"""
def rc(ls, new_ls=[]):
for x in ls:
if isinstance(x, list):
rc(x, new_ls)
else:
new_ls.append(... | """
The trick here is that I am using the new_ls parameter as a list to append.
Since this list is created on first call to the function it is the same object that
I append to.
"""
def rc(ls, new_ls=[]):
for x in ls:
if isinstance(x, list):
rc(x, new_ls)
else:
new_ls.append(... |
n = int(input())
if n%2 != 0:
print('Weird')
else:
if n in range(2, 6):
print('Not Weird')
if n in range(6, 21):
print('Weird')
if n > 20:
print('Not Weird')
| n = int(input())
if n % 2 != 0:
print('Weird')
else:
if n in range(2, 6):
print('Not Weird')
if n in range(6, 21):
print('Weird')
if n > 20:
print('Not Weird') |
def add_numbers(start, end):
total=0
for i in range(start,end+1):
total=total+i
return total
test1 = add_numbers(333, 777)
print(test1)
| def add_numbers(start, end):
total = 0
for i in range(start, end + 1):
total = total + i
return total
test1 = add_numbers(333, 777)
print(test1) |
MOD = 10 ** 9 + 7
n, k = map(int, input().split())
dp = [0] * (k + 1)
ans = 0
for x in range(k, 0, -1):
dp[x] = pow(k // x, n, MOD)
for i in range(2 * x, k + 1, x):
dp[x] -= dp[i]
ans += dp[x] * x
ans %= MOD
print(ans) | mod = 10 ** 9 + 7
(n, k) = map(int, input().split())
dp = [0] * (k + 1)
ans = 0
for x in range(k, 0, -1):
dp[x] = pow(k // x, n, MOD)
for i in range(2 * x, k + 1, x):
dp[x] -= dp[i]
ans += dp[x] * x
ans %= MOD
print(ans) |
# Bidirectional BFS
class Solution(object):
def minKnightMoves(self, x, y):
offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
q1 = collections.deque([(0, 0)])
q2 = collections.deque([(x, y)])
steps1 = {(0, 0): 0} #steps needed starting from (0, 0)
... | class Solution(object):
def min_knight_moves(self, x, y):
offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
q1 = collections.deque([(0, 0)])
q2 = collections.deque([(x, y)])
steps1 = {(0, 0): 0}
steps2 = {(x, y): 0}
while q1 and q2:
... |
class School:
def __init__(self):
self.list_students = list()
self.list_data = list()
def add_student(self, name, grade):
self.list_students.append({"name": name, "grade": grade})
def roster(self):
return self.sort_student_list_by_name_and_grade()
def grade(self, grad... | class School:
def __init__(self):
self.list_students = list()
self.list_data = list()
def add_student(self, name, grade):
self.list_students.append({'name': name, 'grade': grade})
def roster(self):
return self.sort_student_list_by_name_and_grade()
def grade(self, grad... |
#!/usr/bin/python3
# * Copyright (c) 2020-2021, Happiest Minds Technologies Limited Intellectual Property. All rights reserved.
# *
# * SPDX-License-Identifier: LGPL-2.1-only
PE1_binding_chk = 'ipv4 PE1ID/32 P1ID imp-null'
P1_binding_chk1 = 'ipv4 P1ID/32 PE1ID imp-null'
P1_binding_c... | pe1_binding_chk = 'ipv4 PE1ID/32 P1ID imp-null'
p1_binding_chk1 = 'ipv4 P1ID/32 PE1ID imp-null'
p1_binding_chk2 = 'ipv4 P1ID/32 PE2ID imp-null'
pe2_binding_chk = 'ipv4 PE2ID/32 P1ID imp-null' |
# Url source:
# https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list
numbers = list(range(1, 50))
for i in numbers:
if i < 20:
numbers.remove(i)
print(numbers)
| numbers = list(range(1, 50))
for i in numbers:
if i < 20:
numbers.remove(i)
print(numbers) |
class Solution:
def shortestPathLength(self, graph):
def dp(node, mask):
state = (node, mask)
if state in cache:
return cache[state]
if mask & (mask - 1) == 0:
# Base case - mask only has a single "1", which means
# that onl... | class Solution:
def shortest_path_length(self, graph):
def dp(node, mask):
state = (node, mask)
if state in cache:
return cache[state]
if mask & mask - 1 == 0:
return 0
cache[state] = float('inf')
for neighbor in g... |
def format_dict(data, sep_item=", ", sep_key_value="=", brackets=True):
output = ""
delim = ""
for key, value in data.items():
output += f"{delim}{key}{sep_key_value}{value}"
delim = f"{sep_item}"
return f"{{{output}}}" if brackets else f"{output}"
def powerdict(data): # https://stack... | def format_dict(data, sep_item=', ', sep_key_value='=', brackets=True):
output = ''
delim = ''
for (key, value) in data.items():
output += f'{delim}{key}{sep_key_value}{value}'
delim = f'{sep_item}'
return f'{{{output}}}' if brackets else f'{output}'
def powerdict(data):
n = len(dat... |
#!/usr/bin/env python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | dir = 'website'
for name in os.listdir(dir):
fullname = os.path.join(dir, name)
if os.path.isdir(fullname):
print('{} is a directory'.format(fullname))
else:
print('{} is a file'.format(fullname))
with open('software.csv') as software:
reader = csv.DictReader(software)
for row in rea... |
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
def neighbor8(i, j):
n = len(grid)
for di in (-1, 0, 1):
for dj in (-1, 0, 1):
if di == dj == 0:
... | class Solution:
def shortest_path_binary_matrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
def neighbor8(i, j):
n = len(grid)
for di in (-1, 0, 1):
for dj in (-1, 0, 1):
if di == dj == 0:
... |
first = "Aditya"
last = "Mhambrey"
full = first+" "+last
print(full)
full = f"{first} {last} {2+2} {len(first)}"
print(full)
course = " Python Programming"
print(course.upper())
print(course.lower())
print(course.title()) # First Letter of every Word is capital
print(course.strip()) # Getting rid of white space
prin... | first = 'Aditya'
last = 'Mhambrey'
full = first + ' ' + last
print(full)
full = f'{first} {last} {2 + 2} {len(first)}'
print(full)
course = ' Python Programming'
print(course.upper())
print(course.lower())
print(course.title())
print(course.strip())
print(course.rstrip())
print(course.find('Pro'))
print(course.replace... |
"""
@author: acfromspace
"""
# Time complexity: O(n^2)
# Space complexity: O(n)
def bubble_sort_1(data):
for i in range(len(data)-1, 0, -1):
for j in range(i):
if data[j] > data[j+1]:
data[j], data[j+1] = data[j+1], data[j]
return data
def bubble_sort_2(data):
# %las... | """
@author: acfromspace
"""
def bubble_sort_1(data):
for i in range(len(data) - 1, 0, -1):
for j in range(i):
if data[j] > data[j + 1]:
(data[j], data[j + 1]) = (data[j + 1], data[j])
return data
def bubble_sort_2(data):
last_index = len(data) - 1
is_sorted = False... |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
slow, fast = head, head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if slow == fast:
... | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
(slow, fast) = (head, head)
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if slow == fast:
... |
#Sort an array of 0s, 1s and 2s
#It is a problem from geeksforgeeks and can be solved using python code
#Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array in ascending order.
# Here t is the number of test cases,
# i is an iterative variable,
# n is the number of elements in list,
# x i... | t = int(input())
for i in range(t):
n = int(input())
x = list(map(int, input().split()))
x.sort()
for i in x:
print(i, end=' ')
print() |
# list(map(int, input().split()))
# int(input())
def main():
X = int(input())
if X >= 30:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
| def main():
x = int(input())
if X >= 30:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main() |
class ManageCards:
cards = {}
cards["154-98-11-133-118"] = "1"
cards["64-91-169-137-59"] = "2"
cards["46-245-168-137-250"] = "3"
cards["198-241-168-137-22"] = "4"
cards["127-72-227-41-253"] = "5"
cards["78-4-170-137-105"] = "6"
cards["119-174-226-41-18"] = "7"
cards["98-155-250-41-42"] = "8"
cards["1-112-16... | class Managecards:
cards = {}
cards['154-98-11-133-118'] = '1'
cards['64-91-169-137-59'] = '2'
cards['46-245-168-137-250'] = '3'
cards['198-241-168-137-22'] = '4'
cards['127-72-227-41-253'] = '5'
cards['78-4-170-137-105'] = '6'
cards['119-174-226-41-18'] = '7'
cards['98-155-250-41-42... |
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | """Generates configuration for a single NAT gateway """
def generate_config(context):
"""Generates config."""
prefix = context.env['name']
zone = context.properties['zone']
resources = []
ip_name = prefix + '-ip'
resources.append({'name': ip_name, 'type': 'compute.v1.address', 'properties': {'r... |
'''An e-commerce website wishes to find the lucky customer who will be eligible for full value cash back. For this purpose,a number N is fed to the system. It will return another number that is calculated by an algorithm. In the algorithm, a sequence is generated, in which each number n the sum of the preceding numbers... | """An e-commerce website wishes to find the lucky customer who will be eligible for full value cash back. For this purpose,a number N is fed to the system. It will return another number that is calculated by an algorithm. In the algorithm, a sequence is generated, in which each number n the sum of the preceding numbers... |
class CommonsShared:
# period, step, and episode counter
periods_counter = 1
steps_counter = 1
episode_number = 0
# number of periods considered for calculating short and long term sustainabilities
n_steps_short_term = 1
n_steps_long_term = 4
# number of agents
n_agents = 5
# ... | class Commonsshared:
periods_counter = 1
steps_counter = 1
episode_number = 0
n_steps_short_term = 1
n_steps_long_term = 4
n_agents = 5
max_episode_periods = 10
agents_loop_steps = 20
growing_rate = 0.3
carrying_capacity = 50000
punishment_probability = 1
max_replenishmen... |
"""Top-level package for CY Quant Components."""
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
__author__ = """Gatro CY"""
__email__ = 'cragodn@gmail.com'
__version__ = '0.3.14'
| """Top-level package for CY Quant Components."""
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
__author__ = 'Gatro CY'
__email__ = 'cragodn@gmail.com'
__version__ = '0.3.14' |
def test_ci_placeholder():
# This empty test is used within the CI to
# setup the tox venv without running the test suite
# if we simply skip all test with pytest -k=wrong_pattern
# pytest command would return with exit_code=5 (i.e "no tests run")
# making travis fail
# this empty test is the re... | def test_ci_placeholder():
pass |
if __name__ == '__main__':
x = 1
y = [2]
x, = y
print(x)
| if __name__ == '__main__':
x = 1
y = [2]
(x,) = y
print(x) |
class Decoder:
def __init__(self, alphabet, symbol):
self._alphabet = alphabet
self._symbol = symbol
self._reconstructed_extended_dict = {
int(symbol): letter for letter, symbol in self._alphabet.copy().items()
}
def decode(self, encoded_input):
output = ""
... | class Decoder:
def __init__(self, alphabet, symbol):
self._alphabet = alphabet
self._symbol = symbol
self._reconstructed_extended_dict = {int(symbol): letter for (letter, symbol) in self._alphabet.copy().items()}
def decode(self, encoded_input):
output = ''
last_decoded... |
listanum = [[],[]] #Primeiro colchete numeros pares e segundo colchete numeros impares
valor = 0
for cont in range(1,8):
valor = int(input("Digite um valor: "))
if valor % 2 ==0:
listanum[0].append(valor)
else:
listanum[1].append(valor)
listanum[0].sort()
listanum[1].sort()
print(f"Os numero... | listanum = [[], []]
valor = 0
for cont in range(1, 8):
valor = int(input('Digite um valor: '))
if valor % 2 == 0:
listanum[0].append(valor)
else:
listanum[1].append(valor)
listanum[0].sort()
listanum[1].sort()
print(f'Os numeros pares digitados foram {listanum[0]}')
print(f'Os numeros impare... |
""" --- Day 3: Toboggan Trajectory ---
With the toboggan login problems resolved, you set off toward the airport. While travel by toboggan might be easy, it's certainly not safe: there's very minimal steering and the area is covered in trees. You'll need to see which angles will take you near the fewest trees.
Due to ... | """ --- Day 3: Toboggan Trajectory ---
With the toboggan login problems resolved, you set off toward the airport. While travel by toboggan might be easy, it's certainly not safe: there's very minimal steering and the area is covered in trees. You'll need to see which angles will take you near the fewest trees.
Due to ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | """This module has different wrappers for the data structures."""
class Paginationresult:
"""PaginationResult wraps a data about a certain page in pagination."""
def __init__(self, model_class, items, pagination):
self.model_class = model_class
self.items = items
self.pagination = pagi... |
path = "../data/stockfish_norm.csv"
scores = open( path)
last_scores = open( "last_scores.fea", "w")
for row in scores:
last_scores.write( row.rsplit(" ", 1)[1])
scores.close()
last_scores.close() | path = '../data/stockfish_norm.csv'
scores = open(path)
last_scores = open('last_scores.fea', 'w')
for row in scores:
last_scores.write(row.rsplit(' ', 1)[1])
scores.close()
last_scores.close() |
"""
noop.py: An event filter that does nothing to the input.
"""
def main(event):
return event
| """
noop.py: An event filter that does nothing to the input.
"""
def main(event):
return event |
class MudCommand:
"""
This is the base class for all commands in the MUD.
"""
def __init__(self):
self.info = {}
self.info['cmdName'] = ''
self.info['helpText'] = ''
self.info['useExample'] = ''
def setType(self, type):
self.info['actiontype'] = ... | class Mudcommand:
"""
This is the base class for all commands in the MUD.
"""
def __init__(self):
self.info = {}
self.info['cmdName'] = ''
self.info['helpText'] = ''
self.info['useExample'] = ''
def set_type(self, type):
self.info['actiontype'] = type
d... |
def get_human_readable_time(seconds: float) -> str:
"""Convert seconds into a human-readable string.
Args:
seconds: number of seconds
Returns:
String that displays time in Days Hours, Minutes, Seconds format
"""
prefix = "-" if seconds < 0 else ""
seconds = abs(seconds)
int... | def get_human_readable_time(seconds: float) -> str:
"""Convert seconds into a human-readable string.
Args:
seconds: number of seconds
Returns:
String that displays time in Days Hours, Minutes, Seconds format
"""
prefix = '-' if seconds < 0 else ''
seconds = abs(seconds)
int... |
def mutation(word_list):
if all(i in word_list[0].lower() for i in word_list[1].lower()):
return True
return False
print(mutation(["hello", "Hello"]))
print(mutation(["hello", "hey"]))
print(mutation(["Alien", "line"]))
| def mutation(word_list):
if all((i in word_list[0].lower() for i in word_list[1].lower())):
return True
return False
print(mutation(['hello', 'Hello']))
print(mutation(['hello', 'hey']))
print(mutation(['Alien', 'line'])) |
"""Kata url: https://www.codewars.com/kata/5556282156230d0e5e000089."""
def dna_to_rna(dna: str) -> str:
return dna.replace('T', 'U')
| """Kata url: https://www.codewars.com/kata/5556282156230d0e5e000089."""
def dna_to_rna(dna: str) -> str:
return dna.replace('T', 'U') |
def index(req):
req.content_type = "text/html"
req.add_common_vars()
env_vars = req.subprocess_env.copy()
req.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">')
req.write('<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:l... | def index(req):
req.content_type = 'text/html'
req.add_common_vars()
env_vars = req.subprocess_env.copy()
req.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">')
req.write('<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lan... |
# coding=utf-8
"""
A basic rules engine, as well as a set of standard predicates and transformers.
* Predicates are the equivalent of a conditional. They take the comparable
given in the rule on the left and compare it to the value being tested
on the right, returning a boolean.
* Transformers can be considered a... | """
A basic rules engine, as well as a set of standard predicates and transformers.
* Predicates are the equivalent of a conditional. They take the comparable
given in the rule on the left and compare it to the value being tested
on the right, returning a boolean.
* Transformers can be considered a form of result.... |
class Vehicle:
name = ""
kind = "car"
color = ""
value = 00.00
def description (self):
desc ="%s is a %s %s worth $%.2f." % (self.name,self.color,self.kind,self.value)
return desc
car1 = Vehicle()
car1.name = "Fuso"
car1.color = "grey"
car1.kind = "lorry"
car1.value = 1000
car2 = Vehicle()
car2.name ... | class Vehicle:
name = ''
kind = 'car'
color = ''
value = 0.0
def description(self):
desc = '%s is a %s %s worth $%.2f.' % (self.name, self.color, self.kind, self.value)
return desc
car1 = vehicle()
car1.name = 'Fuso'
car1.color = 'grey'
car1.kind = 'lorry'
car1.value = 1000
car2 = v... |
class ContactHelper:
def __init__(self, app):
self.app = app
def create(self, contact):
wd = self.app.wd
# init contact creation
wd.find_element_by_link_text("add new").click()
# foll contact form
wd.find_element_by_name("firstname").click()
wd.find_elem... | class Contacthelper:
def __init__(self, app):
self.app = app
def create(self, contact):
wd = self.app.wd
wd.find_element_by_link_text('add new').click()
wd.find_element_by_name('firstname').click()
wd.find_element_by_name('firstname').clear()
wd.find_element_by_... |
class Solution(object):
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict = {}
ans = 0
for i in nums:
if i in dict:
continue
label = nums.index(i)
dict[label] = 1
x = i
... | class Solution(object):
def array_nesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict = {}
ans = 0
for i in nums:
if i in dict:
continue
label = nums.index(i)
dict[label] = 1
x = ... |
#
# Copyright (c) 2017 Amit Green. All rights reserved.
#
@gem('Gem.Codec')
def gem():
require_gem('Gem.Import')
PythonCodec = import_module('codecs')
python_encode_ascii = PythonCodec.getencoder('ascii')
@export
def encode_ascii(s):
return python_encode_ascii(s)[0]
| @gem('Gem.Codec')
def gem():
require_gem('Gem.Import')
python_codec = import_module('codecs')
python_encode_ascii = PythonCodec.getencoder('ascii')
@export
def encode_ascii(s):
return python_encode_ascii(s)[0] |
num1 = 1.5
num2 = 6.3
sum = num1 + num2
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
| num1 = 1.5
num2 = 6.3
sum = num1 + num2
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) |
"""This problem was asked by Palantir.
In academia, the h-index is a metric used to calculate the impact of a researcher's papers.
It is calculated as follows:
A researcher has index h if at least h of her N papers have h citations each.
If there are multiple h satisfying this formula, the maximum is chosen.
For e... | """This problem was asked by Palantir.
In academia, the h-index is a metric used to calculate the impact of a researcher's papers.
It is calculated as follows:
A researcher has index h if at least h of her N papers have h citations each.
If there are multiple h satisfying this formula, the maximum is chosen.
For e... |
a = []
while True:
k = 0
resposta = str(input('digite uma expressao qualquer:')).strip()
for itens in resposta:
if itens == '(':
a.append(resposta)
elif itens == ')':
if len(a) == 0:
print('expressao invalida')
k = 1
... | a = []
while True:
k = 0
resposta = str(input('digite uma expressao qualquer:')).strip()
for itens in resposta:
if itens == '(':
a.append(resposta)
elif itens == ')':
if len(a) == 0:
print('expressao invalida')
k = 1
bre... |
# -*- coding: utf-8 -*-
"""XML Utilities.
XML scripts in Python.
* ppx: pretty print XML source in human readable form.
* xp: use XPath expression to select nodes in XML source.
* validate: validate XML source with XSD or DTD.
* transform: transform XML source with XSLT.
"""
# Xul version.
__version_info__ = (... | """XML Utilities.
XML scripts in Python.
* ppx: pretty print XML source in human readable form.
* xp: use XPath expression to select nodes in XML source.
* validate: validate XML source with XSD or DTD.
* transform: transform XML source with XSLT.
"""
__version_info__ = ('2', '4', '0')
__version__ = '.'.join(__ve... |
# Copyright (c) 2019 Damian Grzywna
# Licensed under the zlib/libpng License
# http://opensource.org/licenses/zlib/
__all__ = ('__title__', '__summary__', '__uri__', '__version_info__',
'__version__', '__author__', '__maintainer__', '__email__',
'__copyright__', '__license__')
__title__ =... | __all__ = ('__title__', '__summary__', '__uri__', '__version_info__', '__version__', '__author__', '__maintainer__', '__email__', '__copyright__', '__license__')
__title__ = 'aptiv.digitRecognizer'
__summary__ = 'Small application to recognize handwritten digits on the image using machine learning algorithm.'
__uri__ =... |
class Array:
n = 0
arr = []
def print_array(self):
print(self.arr)
def get_user_input(self):
self.n = int(input('Enter the size of array: '))
print('Enter the elements of array in next line (space separated)')
self.arr = list(map(int, input().split()))
| class Array:
n = 0
arr = []
def print_array(self):
print(self.arr)
def get_user_input(self):
self.n = int(input('Enter the size of array: '))
print('Enter the elements of array in next line (space separated)')
self.arr = list(map(int, input().split())) |
#!/usr/bin/env python3
"""
Xtremeloader reloaded...
Lookup for lx products
sample curl calls:
curl -d 'state=productlist&substate=categorized&category=Cellphone+EPINs' -X POST 'https://loadxtreme.ph/cgi-bin/ajax.cgi'
(refer to xtremeloader repo)
List of cat:
[Cellphone EPINs]
[Internet / Broadband] - Inter... | """
Xtremeloader reloaded...
Lookup for lx products
sample curl calls:
curl -d 'state=productlist&substate=categorized&category=Cellphone+EPINs' -X POST 'https://loadxtreme.ph/cgi-bin/ajax.cgi'
(refer to xtremeloader repo)
List of cat:
[Cellphone EPINs]
[Internet / Broadband] - Internet / Broadband </option... |
def hello(name):
print("hello", name, "!")
hello("xxcfun") | def hello(name):
print('hello', name, '!')
hello('xxcfun') |
# def fun(num):
# if num>5:
# return True
# else:
# return False
fun=lambda x: x>5
l=[1,2,3,4,45,35,43,523]
print(list(filter(fun,l))) | fun = lambda x: x > 5
l = [1, 2, 3, 4, 45, 35, 43, 523]
print(list(filter(fun, l))) |
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.previous = None
def remove_node(self):
if self.next:
self.next.previous = self.previous
if self.previous:
self.previous.next = self.next
self.next = None
... | class Node:
def __init__(self, value):
self.value = value
self.next = None
self.previous = None
def remove_node(self):
if self.next:
self.next.previous = self.previous
if self.previous:
self.previous.next = self.next
self.next = None
... |
path = "./Inputs/day5.txt"
# path = "./Inputs/day5Test.txt"
def part1():
seats = getSeats()
highestSeat = max(seats)
print("Part 1:")
print(highestSeat)
def part2():
seats = getSeats()
# get the missing seat
difference = sorted(set(range(seats[0], seats[-1] + 1)).diff... | path = './Inputs/day5.txt'
def part1():
seats = get_seats()
highest_seat = max(seats)
print('Part 1:')
print(highestSeat)
def part2():
seats = get_seats()
difference = sorted(set(range(seats[0], seats[-1] + 1)).difference(seats))
print('Part 2:')
print(difference[0])
def get_seats():
... |
def max(*args):
if len(args) == 0:
return 'no numbers given'
m = args[0]
for arg in args:
if arg > m:
m = arg
return m
print(max())
print(max(5, 12, 3, 6, 7, 10, 9))
| def max(*args):
if len(args) == 0:
return 'no numbers given'
m = args[0]
for arg in args:
if arg > m:
m = arg
return m
print(max())
print(max(5, 12, 3, 6, 7, 10, 9)) |
def solution(N):
n = 0; current = 1; nex = 1
while n <N-1:
current, nex = nex, current+nex
n +=1
return 2*(current+nex)
| def solution(N):
n = 0
current = 1
nex = 1
while n < N - 1:
(current, nex) = (nex, current + nex)
n += 1
return 2 * (current + nex) |
a = [2012, 2013, 2014]
print (a)
print (a[0])
print (a[1])
print (a[2])
b = 2012
c = [b, 2015, 20.1, "Hello", "Hi"]
print (c[1:4])
| a = [2012, 2013, 2014]
print(a)
print(a[0])
print(a[1])
print(a[2])
b = 2012
c = [b, 2015, 20.1, 'Hello', 'Hi']
print(c[1:4]) |
# SB1 may have terrible calibration (is 2x as faint, and wasn't appropriately
# statwt'd b/c it didn't go through the pipeline)
vis = [#'16B-202.sb32532587.eb32875589.57663.07622001157.ms',
'16B-202.sb32957824.eb33105444.57748.63243916667.ms',
'16B-202.sb32957824.eb33142274.57752.64119381944.ms',
'... | vis = ['16B-202.sb32957824.eb33105444.57748.63243916667.ms', '16B-202.sb32957824.eb33142274.57752.64119381944.ms', '16B-202.sb32957824.eb33234671.57760.62953023148.ms']
contspw = '2,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,22,23,24,25,26,28,29,30,31,32,34,35,36,37,39,42,44,45,47,48,49,50,51,52,53,54,55,56,57,58,59,60,62,... |
class Solution:
def _breakIntoLines(self, words: List[str], maxWidth: int) -> List[List[str]]:
allLines = []
charCount = 0
# list of strings for easy append
currLine = []
for word in words:
wordLen = len(word)
if wordLen + charCount > maxWidth:
... | class Solution:
def _break_into_lines(self, words: List[str], maxWidth: int) -> List[List[str]]:
all_lines = []
char_count = 0
curr_line = []
for word in words:
word_len = len(word)
if wordLen + charCount > maxWidth:
allLines.append(currLine)
... |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = '\xc2\xce\xc6\x9e\xff\xa7\x1b:\xc7O\x919\xdf=}d'
_lr_action_items = {'TAG':([20,25,32,44,45,],[-21,-19,39,-22,-20,]),'LBRACE':([10,13,15,24,],[-9,17,20,-10,]),'RPAREN':([14,18,19,26,31,],[-... | _tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = 'ÂÎÆ\x9eÿ§\x1b:ÇO\x919ß=}d'
_lr_action_items = {'TAG': ([20, 25, 32, 44, 45], [-21, -19, 39, -22, -20]), 'LBRACE': ([10, 13, 15, 24], [-9, 17, 20, -10]), 'RPAREN': ([14, 18, 19, 26, 31], [-11, -12, 24, 34, -13]), 'RBRACE': ([17, 20, 22, 25, 32, 35, 41, 42, 44, 45]... |
class Solution:
def romanToInt(self, s: str) -> int:
symbol_map = {
"I": (0, 1),
"V": (1, 5),
"X": (2, 10),
"L": (3, 50),
"C": (4, 100),
"D": (5, 500),
"M": (6, 1000)
}
position = 0
value = 0
... | class Solution:
def roman_to_int(self, s: str) -> int:
symbol_map = {'I': (0, 1), 'V': (1, 5), 'X': (2, 10), 'L': (3, 50), 'C': (4, 100), 'D': (5, 500), 'M': (6, 1000)}
position = 0
value = 0
for symbol in reversed(s):
if symbol_map[symbol][0] < position:
... |
class PolicyNetwork(ModelBase):
def __init__(self,
preprocessor,
input_size=80*80,
hidden_size=200,
gamma=0.99): # Reward discounting factor
super(PolicyNetwork, self).__init__()
self.preprocessor = preprocessor
self.input_... | class Policynetwork(ModelBase):
def __init__(self, preprocessor, input_size=80 * 80, hidden_size=200, gamma=0.99):
super(PolicyNetwork, self).__init__()
self.preprocessor = preprocessor
self.input_size = input_size
self.hidden_size = hidden_size
self.gamma = gamma
se... |
#!/bin/python
#This script is made to remove ID's from a file that contains every ID of every contig.
def file_opener(of_file):
with open(of_file, 'r') as f:
return f.readlines()
def filter(all, matched):
filterd = []
for a in matched:
if a not in matched:
filterd.append(a... | def file_opener(of_file):
with open(of_file, 'r') as f:
return f.readlines()
def filter(all, matched):
filterd = []
for a in matched:
if a not in matched:
filterd.append(a)
return filterd
def file_writer(data, of_file):
content = ''
for line in data:
content... |
"""
You are given a binary tree and you need to write a function that can determine if it is height-balanced.
A height-balanced tree can be defined as a binary tree in which the left and right subtrees of every node differ in height by a maximum of 1.
"""
#
# Binary trees are already defined with this interface:
# cl... | """
You are given a binary tree and you need to write a function that can determine if it is height-balanced.
A height-balanced tree can be defined as a binary tree in which the left and right subtrees of every node differ in height by a maximum of 1.
"""
def get_height(root):
if root is None:
return 0
... |
# This is to write an escape function to escape text at the MarkdownV2 style.
#
# **NOTE**
# The [1]'s content provides some notes on how strings should be escaped,
# but let the user deal with it himself; there are such things as "the string
# ___italic underline___ should be changed to ___italic underline_\r__,
# wh... | _special_symbols = {'_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'}
def escape(string: str) -> str:
for symbol in _special_symbols:
string = string.replace(symbol, '\\' + symbol)
return string |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def node2num(node):
val = 0
while node:
val = val * 10 + no... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def node2num(node):
val = 0
while node:
val = val * 10 + node.val
node = nod... |
#generator2.py
class Week:
def __init__(self):
self.days = {1:'Monday', 2: "Tuesday",
3:"Wednesday", 4: "Thursday",
5:"Friday", 6:"Saturday", 7:"Sunday"}
def week_gen(self):
for x in self.days:
yield self.days[x]
if(__name__ == "__main__"):... | class Week:
def __init__(self):
self.days = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday'}
def week_gen(self):
for x in self.days:
yield self.days[x]
if __name__ == '__main__':
wk = week()
iter1 = wk.week_gen()
iter2 ... |
s1 = '854'
print(s1.isnumeric()) # -- ISN1
s2 = '\u00B2368'
print(s2.isnumeric()) # -- ISN2
s3 = '\u00BC'
print(s3.isnumeric()) # -- ISN3
s4='python895'
print(s4.isnumeric()) # -- ISN4
s5='100m2'
print(s5.isnumeric()) # -- ISN5
| s1 = '854'
print(s1.isnumeric())
s2 = '²368'
print(s2.isnumeric())
s3 = '¼'
print(s3.isnumeric())
s4 = 'python895'
print(s4.isnumeric())
s5 = '100m2'
print(s5.isnumeric()) |
# class LLNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
class Solution:
def solve(self, node, k):
# Write your code here
n = 0
curr = node
while curr:
curr = curr.next
n += 1
if k%n==0:
... | class Solution:
def solve(self, node, k):
n = 0
curr = node
while curr:
curr = curr.next
n += 1
if k % n == 0:
return node
if k > n:
k = k % n
curr = node
k1 = n - k - 1
while k1 != 0:
curr =... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
if not head:
return [0]
node = head
... | class Solution:
def next_larger_nodes(self, head: ListNode) -> List[int]:
if not head:
return [0]
node = head
stack = [(0, node.val)]
node = node.next
result = [0]
i = 1
while node:
while stack and node.val > stack[-1][-1]:
... |
class Config():
API_KEY = '9b680a8b-22d4-4069-b0e6-f6cc97cd9d71'
API_URL = 'https://api.demo.11b.io'
API_ACCOUNT = 'A00-000-030'
config = Config() | class Config:
api_key = '9b680a8b-22d4-4069-b0e6-f6cc97cd9d71'
api_url = 'https://api.demo.11b.io'
api_account = 'A00-000-030'
config = config() |
'''
One cool aspect of using an outer join is that, because it returns all rows from both merged tables and null where they do not match, you can use it to find rows that do not have a match in the other table. To try for yourself, you have been given two tables with a list of actors from two popular movies: Iron Man 1... | """
One cool aspect of using an outer join is that, because it returns all rows from both merged tables and null where they do not match, you can use it to find rows that do not have a match in the other table. To try for yourself, you have been given two tables with a list of actors from two popular movies: Iron Man 1... |
#
# PySNMP MIB module CISCO-ANNOUNCEMENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ANNOUNCEMENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:50:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) ... |
# Will you make it?
def zero_fuel(distance_to_pump, mpg, fuel_left):
if ( distance_to_pump - mpg*fuel_left )>0:
result = False
else:
result = True
return result
| def zero_fuel(distance_to_pump, mpg, fuel_left):
if distance_to_pump - mpg * fuel_left > 0:
result = False
else:
result = True
return result |
"""
So we gonna need a way to check quest progress.
This might be as simple as checking if Admiral has a Ship or we might have to check if he completed 1-1 4 times while jumping in one leg
I have no idea.
At first I intended to write a simple function for each Quest, but the Admiral can activate and deactivate stuff a... | """
So we gonna need a way to check quest progress.
This might be as simple as checking if Admiral has a Ship or we might have to check if he completed 1-1 4 times while jumping in one leg
I have no idea.
At first I intended to write a simple function for each Quest, but the Admiral can activate and deactivate stuff a... |
def fib(n, calc):
if n == 0 or n == 1:
if len(calc) < 2:
calc.append(n)
return calc[n], calc
elif len(calc)-1 >= n:
return calc[n], calc
elif n >= 2:
res1, c = fib(n-1, calc)
res2, c = fib(n-2, calc)
res = res1 + res2
calc.append(res)
... | def fib(n, calc):
if n == 0 or n == 1:
if len(calc) < 2:
calc.append(n)
return (calc[n], calc)
elif len(calc) - 1 >= n:
return (calc[n], calc)
elif n >= 2:
(res1, c) = fib(n - 1, calc)
(res2, c) = fib(n - 2, calc)
res = res1 + res2
calc.app... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.