content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""
1431. Kids With the Greatest Number of Candies
Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that
the ith kid has.
For each kid check if there is a way to distribute extraCandies among the kids such that
he or she can have the great... | """
1431. Kids With the Greatest Number of Candies
Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that
the ith kid has.
For each kid check if there is a way to distribute extraCandies among the kids such that
he or she can have the greatest number of candies am... |
l1= []
l2 = []
i = int(input())
for a in range (0,i):
a = input()
if (a[0]=='1'):
l1.append(a[-1])
elif (a[0]=='2'):
l2.append(a[-1])
elif (a[0] == '5'):
for b in range (0,len(l1)):
print (l1[b], end = " ")
print()
elif (a[0] == '6'):
for b in rang... | l1 = []
l2 = []
i = int(input())
for a in range(0, i):
a = input()
if a[0] == '1':
l1.append(a[-1])
elif a[0] == '2':
l2.append(a[-1])
elif a[0] == '5':
for b in range(0, len(l1)):
print(l1[b], end=' ')
print()
elif a[0] == '6':
for b in range(0, l... |
# Write a function to rotate an array. You are given the array arr,
# n, the size of an array, and d, the number of elements to pivot on
# [1,2,3,4,5,6,7], n = 7, d = 2
# [3,4,5,6,7,1,2]
def rotate_array(arr, n, d):
if n == 0:
return None
elif n == 1:
return arr
return arr[d:] + arr[:d... | def rotate_array(arr, n, d):
if n == 0:
return None
elif n == 1:
return arr
return arr[d:] + arr[:d]
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6, 7]
arr2 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
n = 10
d = 3
print(rotate_array(arr2, n, d)) |
class Solution:
def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
graph = collections.defaultdict(list)
innodes = collections.defaultdict(list)
indegrees = [0] * n
for u, v in prerequisites:
indegrees[v] += 1
... | class Solution:
def check_if_prerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
graph = collections.defaultdict(list)
innodes = collections.defaultdict(list)
indegrees = [0] * n
for (u, v) in prerequisites:
indegrees[v] +=... |
class APIError(Exception):
"""Represents an error returned in a response to a fleet API call
This exception will be raised any time a response code >= 400 is returned
Attributes:
code (int): The response code
message(str): The message included with the error response
http_error(goo... | class Apierror(Exception):
"""Represents an error returned in a response to a fleet API call
This exception will be raised any time a response code >= 400 is returned
Attributes:
code (int): The response code
message(str): The message included with the error response
http_error(goo... |
"""Base vocabulary map & EOS & UNK (PAD) token"""
# Author: Ziqi Yuan <1564123490@qq.com>
class Vocab:
def __init__(self, pretrain_embedding_path):
self.vocab = []
self.dict = []
with open(pretrain_embedding_path) as file:
for index, line in enumerate(file):
wo... | """Base vocabulary map & EOS & UNK (PAD) token"""
class Vocab:
def __init__(self, pretrain_embedding_path):
self.vocab = []
self.dict = []
with open(pretrain_embedding_path) as file:
for (index, line) in enumerate(file):
(word, embedding) = (line.split()[0], lin... |
# Rotting Oranges
# https://leetcode.com/problems/rotting-oranges/
# In a given grid, each cell can have one of three values:
# the value 0 representing an empty cell;
# the value 1 representing a fresh orange;
# the value 2 representing a rotten orange.
# Every minute, any fresh orange that is adjacent (4-direction... | def oranges_rotting(grid):
minute_count = 0
def create_set(grid, target_value):
result = set()
for y in range(len(grid)):
for x in range(len(grid[0])):
if grid[y][x] == target_value:
result.add((x, y))
return result
rotten_os = create_... |
def travel(n,I,O):
l1=[]
#print(I,O)
for i in range(n):
l4=[]
for j in range(n):
if i==j:
l4.append(1)
else:
l4.append(0)
l1.append(l4)
#print(l1)
#print(l1[0].index(1))
for out in range(n):
incoming=out
... | def travel(n, I, O):
l1 = []
for i in range(n):
l4 = []
for j in range(n):
if i == j:
l4.append(1)
else:
l4.append(0)
l1.append(l4)
for out in range(n):
incoming = out
outgoing = out
while incoming != 0:
... |
class UriTemplates:
"""Entities uri templates."""
ENTITY = '/entities/{0}'
ENTITIES = '/entities'
| class Uritemplates:
"""Entities uri templates."""
entity = '/entities/{0}'
entities = '/entities' |
# Here 'n' is the number of rows and columns
def pattern(n):
for a in range(n):
print("* "*n,end="\n")
pattern(5)
'''
this will return
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
| def pattern(n):
for a in range(n):
print('* ' * n, end='\n')
pattern(5)
'\n\nthis will return \n\n* * * * *\n* * * * *\n* * * * *\n* * * * *\n* * * * *\n\n' |
# ... client initialization left out
data_client = client.data
file_path = "characterizations/CdTe1.json"
dataset_id = 1
data_client.upload(dataset_id, file_path) | data_client = client.data
file_path = 'characterizations/CdTe1.json'
dataset_id = 1
data_client.upload(dataset_id, file_path) |
"""
BASICS
Ensures the existance and correct location of keys
"""
# Ensures the existance of the main keys
# COMPLETE (large dict): Complete JSON directory with all tags and subtags
def ensure_main_keys(COMPLETE):
K = COMPLETE.keys()
if {"user", "password", "Solver", "Variables", "Equation", "Initial Condi... | """
BASICS
Ensures the existance and correct location of keys
"""
def ensure_main_keys(COMPLETE):
k = COMPLETE.keys()
if {'user', 'password', 'Solver', 'Variables', 'Equation', 'Initial Conditions', 'Boundary Conditions'}.issubset(set(K)):
return True
return False
def keys_missing(COMPLETE):
... |
# Python Loops
# for [iterator] in [sequence]
# [sequence] = range(start, end, step)
print ("\nLoop with range")
evenodd = lambda n : "even" if n % 2 == 0 else "odd"
for i in range(1, 11):
print (i, "is " + str(evenodd(i)))
print ("\nLoop in range with step")
for i in range(1, 11, 2):
print (i, "is " + str(ev... | print('\nLoop with range')
evenodd = lambda n: 'even' if n % 2 == 0 else 'odd'
for i in range(1, 11):
print(i, 'is ' + str(evenodd(i)))
print('\nLoop in range with step')
for i in range(1, 11, 2):
print(i, 'is ' + str(evenodd(i)))
print('\nLoop through list')
flist = [0.1, 1.1, 2.1, 3.1, 4.1, 5.1]
for i in flis... |
path = "input.txt"
file = open(path)
input = file.readlines()
file.close()
all_fish = [[int(x) for x in line.split(",")] for line in input][0]
for i in range(80):
new = 0
for idx in range(len(all_fish)):
if all_fish[idx] == 0:
all_fish[idx] = 6
new += 1
else:
... | path = 'input.txt'
file = open(path)
input = file.readlines()
file.close()
all_fish = [[int(x) for x in line.split(',')] for line in input][0]
for i in range(80):
new = 0
for idx in range(len(all_fish)):
if all_fish[idx] == 0:
all_fish[idx] = 6
new += 1
else:
... |
def test1_3():
n = 1
while True:
time1 = 100*n**2
time2 = 2**n
if time1 >= time2:
n += 1
else:
break
print(n, time1, time2)
test1_3()
| def test1_3():
n = 1
while True:
time1 = 100 * n ** 2
time2 = 2 ** n
if time1 >= time2:
n += 1
else:
break
print(n, time1, time2)
test1_3() |
def numDepthIncreases():
'''
Problem: https://adventofcode.com/2021/day/1/
'''
with open("data.txt") as f:
data = f.readlines()
num_depth_increases = 0
for i, line in enumerate(data):
if i > 0 and i <= len(data):
if int(line.strip('\n')) > int(data[i-1].str... | def num_depth_increases():
"""
Problem: https://adventofcode.com/2021/day/1/
"""
with open('data.txt') as f:
data = f.readlines()
num_depth_increases = 0
for (i, line) in enumerate(data):
if i > 0 and i <= len(data):
if int(line.strip('\n')) > int(data[i - 1].strip('\... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
FileName: 344. Reverse String.py
Description:
Author: Kimberly Gao
Date: 2021/07/13 11:21 AM
Version: 0.1
Runtime: 412 ms (5.16%)
Memory Usage: 18.5 MB (64.61%)
"""
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Two pointers: he... | """
FileName: 344. Reverse String.py
Description:
Author: Kimberly Gao
Date: 2021/07/13 11:21 AM
Version: 0.1
Runtime: 412 ms (5.16%)
Memory Usage: 18.5 MB (64.61%)
"""
class Solution:
def reverse_string(self, s: List[str]) -> None:
"""
Two pointers: head & tail
:type s: List[str]
... |
"""
RENDER
"""
render_camera = 'cam1'
render_lights = 'light1'
"""
MATERIAL
"""
mat = 'phong1'
mat_color = ''
"""
INSTANCES
"""
inst_state = 1
inst_tra = 'viz6/null_tra'
inst_tx = 'r'
inst_ty = 'g'
inst_tz = 'b'
inst_rot = 'viz6/null_rot'
inst_rx = 'r'
inst_ry = 'g'
inst_rz = 'b'
inst_sca = 'viz6/null_sca'
ins... | """
RENDER
"""
render_camera = 'cam1'
render_lights = 'light1'
'\nMATERIAL\n'
mat = 'phong1'
mat_color = ''
'\nINSTANCES\n'
inst_state = 1
inst_tra = 'viz6/null_tra'
inst_tx = 'r'
inst_ty = 'g'
inst_tz = 'b'
inst_rot = 'viz6/null_rot'
inst_rx = 'r'
inst_ry = 'g'
inst_rz = 'b'
inst_sca = 'viz6/null_sca'
inst_sx = 'r'
in... |
class ServiceReviewHistory:
def __init__(self, org_uuid, service_uuid, service_metadata, state, reviewed_by, reviewed_on, created_on,
updated_on):
self._org_uuid = org_uuid
self._service_uuid = service_uuid
self._service_metadata = service_metadata
self._state = stat... | class Servicereviewhistory:
def __init__(self, org_uuid, service_uuid, service_metadata, state, reviewed_by, reviewed_on, created_on, updated_on):
self._org_uuid = org_uuid
self._service_uuid = service_uuid
self._service_metadata = service_metadata
self._state = state
self._... |
class Solution:
def XXX(self, n: int) -> str:
dp = '1'
for i in range(n-1):
s, cur_char, cnt, dp = dp, dp[0], 0, ''
for index in range(len(s)):
if s[index] == cur_char: cnt += 1
else:
dp += str(cnt) + cur_char
... | class Solution:
def xxx(self, n: int) -> str:
dp = '1'
for i in range(n - 1):
(s, cur_char, cnt, dp) = (dp, dp[0], 0, '')
for index in range(len(s)):
if s[index] == cur_char:
cnt += 1
else:
dp += str(cnt... |
def starts_with_vowel(word: str) -> bool:
return word[0].lower() in "aeiou"
def translate_word(word: str) -> str:
if starts_with_vowel(word):
return word + "yay"
vowel_index = 0
for index, letter in enumerate(word):
if starts_with_vowel(letter):
vowel_index = index
... | def starts_with_vowel(word: str) -> bool:
return word[0].lower() in 'aeiou'
def translate_word(word: str) -> str:
if starts_with_vowel(word):
return word + 'yay'
vowel_index = 0
for (index, letter) in enumerate(word):
if starts_with_vowel(letter):
vowel_index = index
... |
BuildSettingInfo = provider()
def _string_imp(ctx):
value = ctx.build_setting_value
label = ctx.label.name
print("evaluated value for " + label + ": " + value)
return BuildSettingInfo(value = value)
string_flag = rule(
implementation = _string_imp,
# https://docs.bazel.build/versions/main/skyl... | build_setting_info = provider()
def _string_imp(ctx):
value = ctx.build_setting_value
label = ctx.label.name
print('evaluated value for ' + label + ': ' + value)
return build_setting_info(value=value)
string_flag = rule(implementation=_string_imp, build_setting=config.string(flag=True)) |
for _ in range(int(input())):
tot = 0
lst = list(map(int, input().split()))
for i in range(1, len(lst)):
if lst[i] > lst[i - 1] * 2:
tot += (lst[i] - 2 * lst[i - 1])
print(tot)
| for _ in range(int(input())):
tot = 0
lst = list(map(int, input().split()))
for i in range(1, len(lst)):
if lst[i] > lst[i - 1] * 2:
tot += lst[i] - 2 * lst[i - 1]
print(tot) |
BASE_URL = 'http://www.travelpayouts.com'
API_DATA_URL = 'http://api.travelpayouts.com/data'
def whereami(client, ip, locale='en', callback=None):
locale = locale if locale in ['en', 'ru', 'de', 'fr', 'it', 'pl', 'th'] else 'en'
params = {
'ip': ip,
'locale': locale
}
if callback:
... | base_url = 'http://www.travelpayouts.com'
api_data_url = 'http://api.travelpayouts.com/data'
def whereami(client, ip, locale='en', callback=None):
locale = locale if locale in ['en', 'ru', 'de', 'fr', 'it', 'pl', 'th'] else 'en'
params = {'ip': ip, 'locale': locale}
if callback:
params['callback'] ... |
class ModuleAggregator:
def __init__(self, registry_name) -> None:
self.registry_name = registry_name
self._registry = {}
def __getitem__(self, key):
if isinstance(key, str):
return self._registry[key]
return key
def register(self, name=None):
def wrappe... | class Moduleaggregator:
def __init__(self, registry_name) -> None:
self.registry_name = registry_name
self._registry = {}
def __getitem__(self, key):
if isinstance(key, str):
return self._registry[key]
return key
def register(self, name=None):
def wrap... |
parrot = 'NORWEGIAN BLUE'
print(parrot)
print(parrot[3])
print(parrot[4])
print()
print(parrot[3])
print(parrot[6])
print(parrot[8])
print()
print(parrot[-4:])
print()
number = '9,243;365:248 978;269'
separators = number[1::4]
print(separators) | parrot = 'NORWEGIAN BLUE'
print(parrot)
print(parrot[3])
print(parrot[4])
print()
print(parrot[3])
print(parrot[6])
print(parrot[8])
print()
print(parrot[-4:])
print()
number = '9,243;365:248 978;269'
separators = number[1::4]
print(separators) |
class User:
'''
class that generates new instances of users
'''
user_list = [] #empty user list
def __init__(self,username,password):
self.username = username
self.password = password
def registration(self):
'''
registration method adds users to the system
... | class User:
"""
class that generates new instances of users
"""
user_list = []
def __init__(self, username, password):
self.username = username
self.password = password
def registration(self):
"""
registration method adds users to the system
"""
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# class Solution(object):
# def swapPairs(self, head):
# """
# :type head: ListNode
# :rtype: ListNode
# """
class Solution(object):
# de... | class Solution(object):
def swap_pairs(self, head):
dummy_head = list_node(-1)
dummyHead.next = head
prev = dummyHead
while prev.next and prev.next.next:
a = prev.next
b = prev.next.next
(prev.next, b.next, a.next) = (b, a, b.next)
pre... |
app_name = 'price_analysis'
urlpatterns = []
| app_name = 'price_analysis'
urlpatterns = [] |
# -*- coding: utf-8 -*-
class Model(object):
pass
class NullModel(Model):
def __init__(self):
pass
@property
def name(self):
return ''
| class Model(object):
pass
class Nullmodel(Model):
def __init__(self):
pass
@property
def name(self):
return '' |
#
# PySNMP MIB module HUAWEI-PWE3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-PWE3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:45:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, constraints_union, value_size_constraint, value_range_constraint) ... |
""" Copyright 2017 Akamai Technologies, 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 ... | """ Copyright 2017 Akamai Technologies, 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 ... |
#**kwagrs use for complex agrument like dictionary store string values
def func(**kwargs):
for key, value in kwargs.items():
print("{} : {} ".format(key,value))
dict = {"Manish":"Male","Rashmi":"Female"}
func(**dict)
| def func(**kwargs):
for (key, value) in kwargs.items():
print('{} : {} '.format(key, value))
dict = {'Manish': 'Male', 'Rashmi': 'Female'}
func(**dict) |
nome1 = 'Felipe'
nome2 = 'Schmaedecke'
for n in nome1:
if n not in nome2:
print(n, end=' ')
for n in nome2:
if n not in nome1:
print(n, end=' ')
| nome1 = 'Felipe'
nome2 = 'Schmaedecke'
for n in nome1:
if n not in nome2:
print(n, end=' ')
for n in nome2:
if n not in nome1:
print(n, end=' ') |
#The code is to take in numbers which are even and odd in the provided set
even_numbers = []
odd_numbers = []
for number in range(0,1001):
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
print(even_numbers)
print("\n")
print("\n")
print(odd_numbers) | even_numbers = []
odd_numbers = []
for number in range(0, 1001):
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
print(even_numbers)
print('\n')
print('\n')
print(odd_numbers) |
#
# PySNMP MIB module AC-ANALOG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AC-ANALOG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:54:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) ... |
#!/usr/bin/env python
def get_help_data_12575():
"""
Sensor Inventory help.
Data store of information to be presented when a help request is made for port 12576.
Returns a list of dictionaries associated with various requests supported on that port.
"""
help_data = [
{
... | def get_help_data_12575():
"""
Sensor Inventory help.
Data store of information to be presented when a help request is made for port 12576.
Returns a list of dictionaries associated with various requests supported on that port.
"""
help_data = [{'root': 'parameter', 'endpoint': 'parameter/{id}',... |
# -*- coding: utf-8 -*-
"""
File processing
@author: Dazhuang
"""
def insert_line(lines):
lines.insert(0, "Blowin' in the wind\n")
lines.insert(1, "Bob Dylan\n\n")
lines.append("\n\n1962 by Warner Bros. Inc.")
return ''.join(lines)
with open('Blowing in the wind.txt', 'r+') as f:
lines = f.readlin... | """
File processing
@author: Dazhuang
"""
def insert_line(lines):
lines.insert(0, "Blowin' in the wind\n")
lines.insert(1, 'Bob Dylan\n\n')
lines.append('\n\n1962 by Warner Bros. Inc.')
return ''.join(lines)
with open('Blowing in the wind.txt', 'r+') as f:
lines = f.readlines()
string = insert... |
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses")
print(f"You have {boxes_of_crackers} boxes of crackers")
print("That's a lot")
print("Get a blanket\n")
print("We can just give the function numbers directly")
cheese_and_crackers(20, 30)
print("Or, we can use ... | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f'You have {cheese_count} cheeses')
print(f'You have {boxes_of_crackers} boxes of crackers')
print("That's a lot")
print('Get a blanket\n')
print('We can just give the function numbers directly')
cheese_and_crackers(20, 30)
print('Or, we ca... |
class Solution:
def rob(self, nums):
n = len(nums)
if n == 1:
return nums[0]
dpa = [0] * (n + 1)
dpb = [0] * (n + 1)
for i in range(2, n + 1):
dpa[i] = max(dpa[i - 1], dpa[i - 2] + nums[i - 2])
dpb[i] = max(dpb[i - 1], dpb[i - 2] + nums[i ... | class Solution:
def rob(self, nums):
n = len(nums)
if n == 1:
return nums[0]
dpa = [0] * (n + 1)
dpb = [0] * (n + 1)
for i in range(2, n + 1):
dpa[i] = max(dpa[i - 1], dpa[i - 2] + nums[i - 2])
dpb[i] = max(dpb[i - 1], dpb[i - 2] + nums[i ... |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = 'Zhiquan Wang'
__date__ = '2018/8/15 10:44'
class MessageType(object):
login_request = u'LoginRequest'
login_reply = u'LoginReply'
attack_request = u'AttackRequest'
attack_reply = u'AttackReply'
game_info = u'GameInfo'
class JsonAttribu... | __author__ = 'Zhiquan Wang'
__date__ = '2018/8/15 10:44'
class Messagetype(object):
login_request = u'LoginRequest'
login_reply = u'LoginReply'
attack_request = u'AttackRequest'
attack_reply = u'AttackReply'
game_info = u'GameInfo'
class Jsonattribute(object):
msg_type = u'msg_type'
lr_usr... |
#!/usr/bin/python3
# Because I decided to use the ThreadingMixIn in the HTTPServer
# we will need to persist the data on disk...
# DB_FILE = ':memory:'
DB_FILE = 'db.sqlite3'
| db_file = 'db.sqlite3' |
"""
Variables Globales.
Elle permettent de rendre le code plus digeste.
On pourrais en theorie les remplaces par leurs nombres respectif mais ce serais illisible.
"""
NULL = (0)
BOAT = (1)
DESTROYED = (2)
HIT_SUCCESS = (3)
HIT_MISS = (4)
DIRECTION_UP = (5)
DIRECTION_DOWN = (6)
DIRECTION_LEFT = (7)
DIRECTIO... | """
Variables Globales.
Elle permettent de rendre le code plus digeste.
On pourrais en theorie les remplaces par leurs nombres respectif mais ce serais illisible.
"""
null = 0
boat = 1
destroyed = 2
hit_success = 3
hit_miss = 4
direction_up = 5
direction_down = 6
direction_left = 7
direction_right = 8
boat_carrier = 9
... |
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
d = {}
def dfs(node, level):
if level not in d:
d[level] = []
d[level].append(node.val)
if node.left:
dfs(node.left, level + 1)... | class Solution:
def zigzag_level_order(self, root: TreeNode) -> List[List[int]]:
d = {}
def dfs(node, level):
if level not in d:
d[level] = []
d[level].append(node.val)
if node.left:
dfs(node.left, level + 1)
if node.r... |
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
# Primes are hard....recycle code from problem 7...
n = 2
limit = 1000
primes = []
prime = 0
primeSum = 0
while prime <= limit:
for i in range(2,n):
if (n % i) == 0:
break
else:
... | n = 2
limit = 1000
primes = []
prime = 0
prime_sum = 0
while prime <= limit:
for i in range(2, n):
if n % i == 0:
break
else:
primes.append(n)
prime = n
prime_sum += n
n += 1
print('THE LAST PRIME ADDED WAS: ' + str(prime))
print("SO I'LL JUST GO AHEAD AND SUBTRAC... |
"""
Sharingan project
We will try to find your visible basic footprint from social media as much as possible
"""
| """
Sharingan project
We will try to find your visible basic footprint from social media as much as possible
""" |
# String Literals
hello_world = "Hello, World"
hello_world_two = " Hello World "
print(hello_world[1])
print(hello_world[0:5])
# Length of the string
print(len(hello_world))
# Strip
print(hello_world_two)
print(hello_world_two.strip())
# Lower
print(hello_world.lower())
# Upper
print(hello_world.upper())
# Replace... | hello_world = 'Hello, World'
hello_world_two = ' Hello World '
print(hello_world[1])
print(hello_world[0:5])
print(len(hello_world))
print(hello_world_two)
print(hello_world_two.strip())
print(hello_world.lower())
print(hello_world.upper())
print(hello_world.replace('H', 'J'))
print(hello_world.split(',')) |
"""
This program calculates an exponential using the fast exponential algorithm.
"""
def fast_exponential(base: int, exponent: int) -> int:
if not isinstance(base, int):
raise ValueError("Invalid Base")
if not isinstance(exponent, int):
raise ValueError("Invalid Exponent")
if exponent < 0:... | """
This program calculates an exponential using the fast exponential algorithm.
"""
def fast_exponential(base: int, exponent: int) -> int:
if not isinstance(base, int):
raise value_error('Invalid Base')
if not isinstance(exponent, int):
raise value_error('Invalid Exponent')
if exponent < 0... |
# -*- coding: utf-8 -*-
#
# Copyright 2014 Jaime Gil de Sagredo Luna
#
# 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 a... | """The `errors` module contains all exceptions used by Booby."""
class Boobyerror(Exception):
"""Base class for all Booby exceptions."""
pass
class Fielderror(BoobyError):
"""This exception is used as an equivalent to :class:`AttributeError`
for :mod:`fields`.
"""
pass
class Validationerror(... |
#Needs more comments
#Node class
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def getData(self):
return self.data
#Adjanceny List graph implementation
class ALGraph:
#initialize list
def __init__(self):
self.table = []
#ad... | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def get_data(self):
return self.data
class Algraph:
def __init__(self):
self.table = []
def insert_vertex(self, data):
temp = node(data)
self.table.append(temp)
de... |
"""
Name: polynom.py
Goal: operations with of polynoms
Author: HOUNSI madouvi antoine-sebastien
Date: 8/03/2022
"""
class Polynom:
def mult(self, P1, P2):
""" Multiplication between P1 and P2 """
maxArray = [x for x in P1]
minArray = [x for x in P2]
if len(P1) == 1... | """
Name: polynom.py
Goal: operations with of polynoms
Author: HOUNSI madouvi antoine-sebastien
Date: 8/03/2022
"""
class Polynom:
def mult(self, P1, P2):
""" Multiplication between P1 and P2 """
max_array = [x for x in P1]
min_array = [x for x in P2]
if len(P1) == ... |
"""
Calculate minimum steps of raffle shuffle (alternating shuffle)
of a deck of cards to get to max degree of disorder.
Disorder of a = sum(abs(i-a[i]) for i in range(...))
"""
def steps(n):
deck = [*range(n)]
p = []
for _ in range(n):
deck = deck[::2] + deck[1::2]
p += sum(abs(i-deck[i... | """
Calculate minimum steps of raffle shuffle (alternating shuffle)
of a deck of cards to get to max degree of disorder.
Disorder of a = sum(abs(i-a[i]) for i in range(...))
"""
def steps(n):
deck = [*range(n)]
p = []
for _ in range(n):
deck = deck[::2] + deck[1::2]
p += (sum((abs(i - de... |
FLOWERS = r"""
vVVVv vVVVv
(___) vVVVv (___) vVVVv
~Y~ (___) ~Y~ (___)
\| \~Y~/ \| \~Y~/
\\|// \\|// \\|// \\|//
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"""
SAMPLE = r"""
.--. ... | flowers = '\n \n vVVVv vVVVv \n (___) vVVVv (___) vVVVv\n ~Y~ (___) ~Y~ (___)\n \\| \\~Y~/ \\| \\~Y~/\n \\\\|// \\\\|// \\\\|// \\\\|//\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ \n'
sample = '\n ... |
s = float(input('Digite o salario do funcionario: R$ '))
if s>1250:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora.'.format(s,s+(s*10/100)))
else:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora'.format(s,s+(s*15/100)))
| s = float(input('Digite o salario do funcionario: R$ '))
if s > 1250:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora.'.format(s, s + s * 10 / 100))
else:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora'.format(s, s + s * 15 / 100)) |
# Data Type in Python is an attribute of data which tells the interpreter how the programmer intends to use the data
# There are three numeric data types in Python:
# Integers
# Integers (e.g. 2, 4, 20)
# - Boolean (e.g. False and True, acting like 0 and 1)
# Floating Point Numbers (e.g. 3.0, 5.2)
# Complex Number... | positive_integer = 34
negative_integer = -3237937
big_integer = 62733287329879274032843048
print(positive_integer)
print(negative_integer)
print(big_integer)
print('**********************************************************')
my_boolean_value1 = True
my_boolean_value2 = False
print(myBooleanValue1)
print(myBooleanValue... |
class Quadrilatero:
def __init__(self, lado1, lado2):
self.__lado1 = lado1
self.__lado2 = lado2
def retangulo():
pass
def retangulo():
pass
def retangulo():
pass | class Quadrilatero:
def __init__(self, lado1, lado2):
self.__lado1 = lado1
self.__lado2 = lado2
def retangulo():
pass
def retangulo():
pass
def retangulo():
pass |
#creating a node
class Node:
def __init__(self,data):
self.value=data
self.left=None
self.right=None
#function to check if the tree is a mirror image of another tree
def isMirror(troot1, troot2):
if troot1 == None and troot2 == None:
return True;
if (troot1 != None and t... | class Node:
def __init__(self, data):
self.value = data
self.left = None
self.right = None
def is_mirror(troot1, troot2):
if troot1 == None and troot2 == None:
return True
if troot1 != None and troot2 != None:
if troot1.value == troot2.value:
return is_m... |
# pylint: skip-file
# pylint: disable=too-many-instance-attributes
class GcloudResourceBuilder(object):
''' Class to wrap the gcloud deployment manager '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
clusterid,
project,
r... | class Gcloudresourcebuilder(object):
""" Class to wrap the gcloud deployment manager """
def __init__(self, clusterid, project, region, zone, verbose=False):
""" Constructor for gcloud resource """
self.clusterid = clusterid
self.project = project
self.region = region
se... |
"""
0758. Bold Words in String
Easy
Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between <b> and </b> tags become bold.
The returned string should use the least number of tags possible, and of course the tags should form a valid combination.
For example, g... | """
0758. Bold Words in String
Easy
Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between <b> and </b> tags become bold.
The returned string should use the least number of tags possible, and of course the tags should form a valid combination.
For example, g... |
# Outputs strings with inverted commas
# Author: Isabella Doyle
message = 'John said "hi", I said "bye.'
print(message) | message = 'John said "hi", I said "bye.'
print(message) |
# 000758_02_02_ifStatements.py
print("000758_02_02_ifStatements:01")
if 10 > 5:
print("10 greater than 5")
print("Program ended")
print("")
print("000758_02_02_ifStatements:02:nested")
num = 12
if num > 5:
print("Bigger than 5")
if num <= 47:
print("Between 5 and 47")
print("")
print("000758_02_02_... | print('000758_02_02_ifStatements:01')
if 10 > 5:
print('10 greater than 5')
print('Program ended')
print('')
print('000758_02_02_ifStatements:02:nested')
num = 12
if num > 5:
print('Bigger than 5')
if num <= 47:
print('Between 5 and 47')
print('')
print('000758_02_02_ifStatements:q.03:nested')
num =... |
PREFIX = "/api"
CORS_POLICY = {"origins": ("*",), "max_age": 3600}
class Base:
def __init__(self, request, context=None):
self.request = request
@property
def _index(self):
return self.request.registry.settings["pyfapi.es.index"]
def _result(self, result):
return {"result": ... | prefix = '/api'
cors_policy = {'origins': ('*',), 'max_age': 3600}
class Base:
def __init__(self, request, context=None):
self.request = request
@property
def _index(self):
return self.request.registry.settings['pyfapi.es.index']
def _result(self, result):
return {'result': r... |
# Exer 8
# # Creating a list of nice places to visit
places_to_visit = ['island', 'australia', 'cananda', 'thailand']
print(places_to_visit)
# putting the list into alphabetic order
print(sorted(places_to_visit))
# putting the list back to its original order
print(places_to_visit)
# putting the list backwards
place... | places_to_visit = ['island', 'australia', 'cananda', 'thailand']
print(places_to_visit)
print(sorted(places_to_visit))
print(places_to_visit)
places_to_visit.reverse()
print(places_to_visit)
places_to_visit.sort()
print(len(places_to_visit)) |
def print_matrix(matrix):
for row in matrix:
for elem in row:
print(elem, end='\t')
print()
print(__name__)
if __name__ == "__main__":
print("Something to run as stand alone script")
| def print_matrix(matrix):
for row in matrix:
for elem in row:
print(elem, end='\t')
print()
print(__name__)
if __name__ == '__main__':
print('Something to run as stand alone script') |
"""
In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
If it is, return the index of the largest element, otherwise return -1.
Example 1:
Input: nums = [3, 6, 1, 0]
Output: 1
Explanat... | """
In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
If it is, return the index of the largest element, otherwise return -1.
Example 1:
Input: nums = [3, 6, 1, 0]
Output: 1
Explanat... |
class Solution:
"""
https://leetcode.com/problems/reverse-words-in-a-string-iii/
Given a string, you need to reverse the order of characters in each
word within a sentence while still preserving whitespace and
initial word order.
Example 1:
Input: "Let's take LeetCode contest"
... | class Solution:
"""
https://leetcode.com/problems/reverse-words-in-a-string-iii/
Given a string, you need to reverse the order of characters in each
word within a sentence while still preserving whitespace and
initial word order.
Example 1:
Input: "Let's take LeetCode contest"
... |
#!/usr/bin/env python3
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
__all__ = [
'datastructures',
'exception',
'funcs',
'info',
'kprobe',
'... | __all__ = ['datastructures', 'exception', 'funcs', 'info', 'kprobe', 'prog', 'socket_filter', 'tc', 'util'] |
l=[]
print(l)
l.append(10)
print(l)
l.append(11)
print(l) | l = []
print(l)
l.append(10)
print(l)
l.append(11)
print(l) |
# coding = utf-8
# @time : 2019/6/30 6:41 PM
# @author : alchemistlee
# @fileName: filter_long_tk.py
# @abstract:
if __name__ == '__main__':
input_zh = '/root/workspace/translate_data/my_corpus_v6.zh-cut.processed6-bpe-v6-2-.test'
input_en = '/root/workspace/translate_data/my_corpus_v6.en.tok.processed6-... | if __name__ == '__main__':
input_zh = '/root/workspace/translate_data/my_corpus_v6.zh-cut.processed6-bpe-v6-2-.test'
input_en = '/root/workspace/translate_data/my_corpus_v6.en.tok.processed6-bpe-v6-2-.test'
out_zh = '/root/workspace/translate_data/my_corpus_v6.zh-cut.processed6-bpe-v6-2-filter3.test'
ou... |
#
# @lc app=leetcode id=677 lang=python3
#
# [677] Map Sum Pairs
#
# @lc code=start
class MapSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = {}
def insert(self, key, val):
self.d[key] = val
def sum(self, prefix):
return sum(... | class Mapsum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = {}
def insert(self, key, val):
self.d[key] = val
def sum(self, prefix):
return sum((self.d[i] for i in self.d if i.startswith(prefix))) |
#
# PySNMP MIB module Fore-frs-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-frs-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:04:09 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,... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ... |
## pure function: has no side effect and returns a value based on their arguments
def pure_function(x,y):
temp = x + 2*y
return temp / y + 2*x
##impure function
some_list = []
def impure(arg):
some_list.append(arg) | def pure_function(x, y):
temp = x + 2 * y
return temp / y + 2 * x
some_list = []
def impure(arg):
some_list.append(arg) |
# coding: utf-8
"""
sentry_riemann
"""
VERSION = '0.0.4'
| """
sentry_riemann
"""
version = '0.0.4' |
class Solution(object):
def brokenCalc(self, X, Y):
res = 0
while Y > X:
res += Y % 2 + 1
Y = Y // 2 if Y % 2 == 0 else (Y + 1)//2
return res + X - Y
def main():
startValue = 2
target = 3
startValue = 5
target = 8
startValue = 3
target = 10
startValue ... | class Solution(object):
def broken_calc(self, X, Y):
res = 0
while Y > X:
res += Y % 2 + 1
y = Y // 2 if Y % 2 == 0 else (Y + 1) // 2
return res + X - Y
def main():
start_value = 2
target = 3
start_value = 5
target = 8
start_value = 3
target ... |
'''
Created on Nov 14, 2017
@author: jschm
'''
class Fraction(object):
'''Defines an immutable rational number with common arithmetic operations.
'''
def __init__(self, numerator=0, denominator=1):
#default values for fraction is 0
'''Constructs a rational number (fraction) initialized to ... | """
Created on Nov 14, 2017
@author: jschm
"""
class Fraction(object):
"""Defines an immutable rational number with common arithmetic operations.
"""
def __init__(self, numerator=0, denominator=1):
"""Constructs a rational number (fraction) initialized to zero or a user
specified value.
... |
"""
The dictionaries are blocks and they the present by '{}' , inside every block is
represented by two elements, one key and one value, separated by ':' and with ','
separated every block
Example: name = {key1:value1, key2:value2,.......}
And inside the values you can have tuple, list, numbers, strings, all types of d... | """
The dictionaries are blocks and they the present by '{}' , inside every block is
represented by two elements, one key and one value, separated by ':' and with ','
separated every block
Example: name = {key1:value1, key2:value2,.......}
And inside the values you can have tuple, list, numbers, strings, all types of d... |
'''
Created on Nov 22, 2010
@author: johantenbroeke
'''
| """
Created on Nov 22, 2010
@author: johantenbroeke
""" |
# First we'll start an undo action, then Ctrl-Z will undo the actions of the whole script
editor.beginUndoAction()
# Do a Python regular expression replace, full support of Python regular expressions
# This replaces any three uppercase letters that are repeated,
# so ABDABD, DEFDEF or DGBDGB etc. the first 3 char... | editor.beginUndoAction()
editor.rereplace('([A-Z]{3})\\1', '\\1')
editor.rereplace('<br/>\\s*\\r\\n\\s*<br/>', '<br/>\r\n')
editor.endUndoAction() |
"""Define function to sort and merge an unsorted array."""
def mergesort(arr):
"""Define merge sort."""
left = arr[:len(arr)//2]
right = arr[len(arr)//2:]
if len(left) > 1:
left = mergesort(left)
if len(right) > 1:
right = mergesort(right)
lst = []
i, j = 0, 0
while i ... | """Define function to sort and merge an unsorted array."""
def mergesort(arr):
"""Define merge sort."""
left = arr[:len(arr) // 2]
right = arr[len(arr) // 2:]
if len(left) > 1:
left = mergesort(left)
if len(right) > 1:
right = mergesort(right)
lst = []
(i, j) = (0, 0)
wh... |
class Product(object):
def __init__(self, product_name:str, global_id, price, description="") -> None:
self.product_id = global_id
self.product_name = product_name
self.description = description
self.price = price
print("created product {0.product_name}".format(se... | class Product(object):
def __init__(self, product_name: str, global_id, price, description='') -> None:
self.product_id = global_id
self.product_name = product_name
self.description = description
self.price = price
print('created product {0.product_name}'.format(self))
... |
# Modify the previous program such that only multiples of three or five are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17
num = int(input("Enter number: "))
def bubbles_sum(num):
sum = 0
for a in range(1, num + 1):
sum = sum + a
if (a % 3 == 0 or a % 5 == 0) :
sum = s... | num = int(input('Enter number: '))
def bubbles_sum(num):
sum = 0
for a in range(1, num + 1):
sum = sum + a
if a % 3 == 0 or a % 5 == 0:
sum = sum + a
print(sum) |
# The channel to send the log messages to
CHANNEL_NAME = "voice-log"
# The bot token
BOT_TOKEN = "NDI3NTIyNzMxNjgxsasdsagsadshvbn,.fgsfgjfkLHEGROoAxA"
| channel_name = 'voice-log'
bot_token = 'NDI3NTIyNzMxNjgxsasdsagsadshvbn,.fgsfgjfkLHEGROoAxA' |
"""Contains some global switches"""
# Master switches: turn them on (True) to immediately switch phase
master_proceed_to_day = False
master_proceed_to_dawn = False
master_proceed_to_night = False
master_proceed_to_nomination = False
def init_switches():
"""Initialize (reset) these global switches"""
global m... | """Contains some global switches"""
master_proceed_to_day = False
master_proceed_to_dawn = False
master_proceed_to_night = False
master_proceed_to_nomination = False
def init_switches():
"""Initialize (reset) these global switches"""
global master_proceed_to_day
global master_proceed_to_night
global ma... |
# use the function blackbox(lst) that is already defined
lst = ["a", "b", "c"]
blackbox_lst = blackbox(lst)
print("modifies" if id(lst) == id(blackbox_lst) else "new")
| lst = ['a', 'b', 'c']
blackbox_lst = blackbox(lst)
print('modifies' if id(lst) == id(blackbox_lst) else 'new') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 22 17:46:31 2022
@author: victor
"""
bikes = []
bikes.append('trek')
bikes.append('giant')
bikes.append('redline')
print(bikes) | """
Created on Sat Jan 22 17:46:31 2022
@author: victor
"""
bikes = []
bikes.append('trek')
bikes.append('giant')
bikes.append('redline')
print(bikes) |
expected_output = {
"instance": {
"default": {
"vrf": {
"EVPN-BGP-Table": {
"address_family": {
"l2vpn evpn": {
"prefixes": {
"[3][40.0.0.3:164][0][32][40.0.0.7]/17": {
... | expected_output = {'instance': {'default': {'vrf': {'EVPN-BGP-Table': {'address_family': {'l2vpn evpn': {'prefixes': {'[3][40.0.0.3:164][0][32][40.0.0.7]/17': {'table_version': '234', 'nlri_data': {'route-type': '3', 'rd': '40.0.0.3:164', 'eti': '0', 'ip_len': '32', 'orig_rtr_id': '40.0.0.7', 'subnet': '17'}, 'availabl... |
"""Generated config, with scaler.
Date: 2022-01-09
Change: f = 48, n = 128 with relative error constrain in 1e-3.
added zero_mask = 1e-10.
The scaler directly save the reciprocal, have some problems in the round of its reciprocal.
The error evaluation method changed for both plain-text and cipher-text.
"""
sigmoid_co... | """Generated config, with scaler.
Date: 2022-01-09
Change: f = 48, n = 128 with relative error constrain in 1e-3.
added zero_mask = 1e-10.
The scaler directly save the reciprocal, have some problems in the round of its reciprocal.
The error evaluation method changed for both plain-text and cipher-text.
"""
sigmoid_co... |
def get_colnames(score: str):
colnames = {
"charlson": {
"aids": "AIDS or HIV",
"ami": "acute myocardial infarction",
"canc": "cancer any malignancy",
"cevd": "cerebrovascular disease",
"chf": "congestive heart failure",
"copd": "chron... | def get_colnames(score: str):
colnames = {'charlson': {'aids': 'AIDS or HIV', 'ami': 'acute myocardial infarction', 'canc': 'cancer any malignancy', 'cevd': 'cerebrovascular disease', 'chf': 'congestive heart failure', 'copd': 'chronic obstructive pulmonary disease', 'dementia': 'dementia', 'diab': 'diabetes withou... |
#!/usr/bin/env python
'''
Test Templates
'''
regList = ["A", "B", "C", "D", "E", "F", "H", "L", "HL", "PC", "SP"]
cpuTestFile = '''
namespace GameBoyEmulator.Desktop.Tests {
[TestFixture]
public class CPUTest {
private const int RUN_CYCLES = 10;
{TESTS}
}
}
'''
baseTestTemplate = '''
... | """
Test Templates
"""
reg_list = ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'L', 'HL', 'PC', 'SP']
cpu_test_file = '\nnamespace GameBoyEmulator.Desktop.Tests {\n [TestFixture]\n public class CPUTest {\n private const int RUN_CYCLES = 10;\n\n {TESTS}\n }\n}\n'
base_test_template = '\n [Test]\n ... |
#Start of code
x=['a','e','i','o','u','A','E','I','O','U']
y=input("Enter an Alphabet: ")
if y in x:
print(y,"is a vowel")
else:
print(y,"is not a vowel")
#End of code
| x = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
y = input('Enter an Alphabet: ')
if y in x:
print(y, 'is a vowel')
else:
print(y, 'is not a vowel') |
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'utils.authenticate.GoogleBackend',
]
| authentication_backends = ['django.contrib.auth.backends.ModelBackend', 'utils.authenticate.GoogleBackend'] |
N, M = map(int, input().split())
A = []
B = []
for i in range(N):
A.append(list(map(int, input().split())))
for i in range(N):
B.append(list(map(int, input().split())))
C = []
for i in range(N):
tmp = []
for j in range(M):
a = A[i][j]
b = B[i][j]
tmp.append(a ^ b)
C.append(... | (n, m) = map(int, input().split())
a = []
b = []
for i in range(N):
A.append(list(map(int, input().split())))
for i in range(N):
B.append(list(map(int, input().split())))
c = []
for i in range(N):
tmp = []
for j in range(M):
a = A[i][j]
b = B[i][j]
tmp.append(a ^ b)
C.append(... |
def get_fisnar_commands(**kwargs):
"""
get a list of the fisnar commands with a specified filter
:param xyz: set to True to only return commands that take in x, y, and z coordinates
:type xyz: bool
"""
filters = [] # list to store filters
kwarg_keys = ["xyz"]
for key in kwargs: # tr... | def get_fisnar_commands(**kwargs):
"""
get a list of the fisnar commands with a specified filter
:param xyz: set to True to only return commands that take in x, y, and z coordinates
:type xyz: bool
"""
filters = []
kwarg_keys = ['xyz']
for key in kwargs:
if isinstance(kwargs[key... |
contacts = {}
running = True;
while running:
command = input('enter A(dd) D(elete) F(ind) Q(uit)')
if command == 'A' or command == 'a':
name = input('enter a new name');
print('enter a phone number for', name, end=':')
number=input()
contacts[name] = number
elif command == ... | contacts = {}
running = True
while running:
command = input('enter A(dd) D(elete) F(ind) Q(uit)')
if command == 'A' or command == 'a':
name = input('enter a new name')
print('enter a phone number for', name, end=':')
number = input()
contacts[name] = number
elif command == 'D... |
class Atom:
def __init__(self, symbol, atoms, neutr):
self.symbol = str(symbol)
self.atoms = int(atoms)
self.neutrons = int(neutr)
self.protons = int(0)
self.mass = int(0)
def proton_number(self):
self.protons = self.atoms - self.neutrons
return self.prot... | class Atom:
def __init__(self, symbol, atoms, neutr):
self.symbol = str(symbol)
self.atoms = int(atoms)
self.neutrons = int(neutr)
self.protons = int(0)
self.mass = int(0)
def proton_number(self):
self.protons = self.atoms - self.neutrons
return self.pro... |
#!/usr/bin/env python3
xList = [ int( x ) for x in input().split() ]
xList = sorted( xList )
medianIndex = len( xList ) // 2
if len( xList ) % 2 == 0:
print( ( xList[medianIndex-1] + xList[medianIndex] ) / 2. )
else:
print( float( xList[ medianIndex ] ) )
| x_list = [int(x) for x in input().split()]
x_list = sorted(xList)
median_index = len(xList) // 2
if len(xList) % 2 == 0:
print((xList[medianIndex - 1] + xList[medianIndex]) / 2.0)
else:
print(float(xList[medianIndex])) |
class Box(object):
def __init__(self, side, height):
self._side = side
self._height = height
def volume(self):
return self._side * self._side * self._height
def __lt__(self, other):
return self.volume() < other
def __eq__(self, other):
return self.volume() == o... | class Box(object):
def __init__(self, side, height):
self._side = side
self._height = height
def volume(self):
return self._side * self._side * self._height
def __lt__(self, other):
return self.volume() < other
def __eq__(self, other):
return self.volume() == ... |
ROCK, PAPER, SCISSORS = range(3)
class RpsCandidate:
"""
Abstract base class for candidates for the
Pi In The Sky: Rock Paper Scissors Competition
"""
def __init__(self):
pass
def getNextMove(self):
"""
Get the next move in the game
Returns:
the ne... | (rock, paper, scissors) = range(3)
class Rpscandidate:
"""
Abstract base class for candidates for the
Pi In The Sky: Rock Paper Scissors Competition
"""
def __init__(self):
pass
def get_next_move(self):
"""
Get the next move in the game
Returns:
th... |
class Card():
ranks = [str(n) for n in range(2, 10)] + list('TJQKA')
rank_tran = {rank: n for n, rank in enumerate(ranks, 2)}
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self._numrank = self.rank_tran[rank]
def __eq__(self, other):
return self._num... | class Card:
ranks = [str(n) for n in range(2, 10)] + list('TJQKA')
rank_tran = {rank: n for (n, rank) in enumerate(ranks, 2)}
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self._numrank = self.rank_tran[rank]
def __eq__(self, other):
return self._num... |
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
# def helper(countA, countB, idx, cur_cost):
# if idx == len(costs):
# return cur_cost
# if countA < len(costs) // 2 and countB < len(costs) // 2:
# return min(helper(countA + 1... | class Solution:
def two_city_sched_cost(self, costs: List[List[int]]) -> int:
a_minus_b = sorted([(a - b, a, b) for (a, b) in costs])
return sum([cost[1] for cost in a_minus_b[:len(costs) // 2]] + [cost[2] for cost in a_minus_b[len(costs) // 2:]]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.