content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Connection:
def __init__(self, unique,ip, hostname):
self.ip = ip
self.hostname = hostname
self.unique = unique
def __str__(self):
return str({"ip":self.ip, "hostname": self.hostname, "unique": self.unique}) | class Connection:
def __init__(self, unique, ip, hostname):
self.ip = ip
self.hostname = hostname
self.unique = unique
def __str__(self):
return str({'ip': self.ip, 'hostname': self.hostname, 'unique': self.unique}) |
def external_service(name, datacenter, node, address, port, token=None):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if token is None:
token = __pillar__['consul']['acl']['tokens']['default']
# Determine if the cluster is ready
if not __salt__["consul.cluster_ready"]():... | def external_service(name, datacenter, node, address, port, token=None):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if token is None:
token = __pillar__['consul']['acl']['tokens']['default']
if not __salt__['consul.cluster_ready']():
ret['result'] = True
ret[... |
#
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. T... | class Refinementcomplexities(object):
"""
An enum-like container of standard complexity settings.
"""
class _Refinementcomplexity(object):
"""
Class which represents a level of mesh refinement complexity. Each
level has a string identifier, a display name, and a float complexity... |
class DumbDriveForward(Autonomous):
nickname = "Dumb drive forward"
def __init__(self, robot):
super().__init__(robot)
self.addSequential(AutoDumbDrive(robot, time=3, speed=-0.4))
class DumbDriveForwardHighGear(CommandGroup):
nickname = "Dumb drive forward high gear"
def __init__(sel... | class Dumbdriveforward(Autonomous):
nickname = 'Dumb drive forward'
def __init__(self, robot):
super().__init__(robot)
self.addSequential(auto_dumb_drive(robot, time=3, speed=-0.4))
class Dumbdriveforwardhighgear(CommandGroup):
nickname = 'Dumb drive forward high gear'
def __init__(se... |
#Write a function name kinetic_energy that accepts an object's mass (in kg) and
#velocity (in m/s) as arguments. The function should return the amount of kinetic
#energy that object has. Write a program that asks the user to enter values for
#mass and velocity, the calls kinetic_energy to get the object's kinetic en... | def main():
print('This program calculates and displays kinetic energy of an object')
print('with the values entered.')
print()
mass = float(input('Enter mass: '))
velocity = float(input('Enter velocity: '))
energy = kinetic_energy(mass, velocity)
print('The kinetic energy is', format(energy... |
def seg(s):
s2 = s[0]
for e in s[1:]:
if e == s2[-1]:
s2 += e
else:
s2 += '/'
s2 += e
print(s)
print(s2)
def seg2():
s2 = []
s = ['a', 'a', 'b', 'b', 'v', 'v', 'c', 'c', 'a', 's']
for e in enumerate(s):
s2.append(e)
s3 = s2[0... | def seg(s):
s2 = s[0]
for e in s[1:]:
if e == s2[-1]:
s2 += e
else:
s2 += '/'
s2 += e
print(s)
print(s2)
def seg2():
s2 = []
s = ['a', 'a', 'b', 'b', 'v', 'v', 'c', 'c', 'a', 's']
for e in enumerate(s):
s2.append(e)
s3 = s2[0]
... |
class Solution:
def subtractProductAndSum(self, n: int) -> int:
prod = 1
sum_ = 0
while n > 0:
last_digit = n % 10
prod *= last_digit
sum_ += last_digit
n //= 10
return prod - sum_
... | class Solution:
def subtract_product_and_sum(self, n: int) -> int:
prod = 1
sum_ = 0
while n > 0:
last_digit = n % 10
prod *= last_digit
sum_ += last_digit
n //= 10
return prod - sum_ |
def test(x):
try:
if x:
print(x)
else:
raise (Exception)
except:
print("wrong")
finally:
print("finally")
print("after finally")
if __name__ == "__main__":
test(None)
test("hello")
| def test(x):
try:
if x:
print(x)
else:
raise Exception
except:
print('wrong')
finally:
print('finally')
print('after finally')
if __name__ == '__main__':
test(None)
test('hello') |
# The example function below keeps track of the opponent's history and plays whatever the opponent played two plays ago. It is not a very good player so you will need to change the code to pass the challenge.
def player(prev_play, opponent_history=[]):
opponent_history.append(prev_play)
guess = "R"
if len... | def player(prev_play, opponent_history=[]):
opponent_history.append(prev_play)
guess = 'R'
if len(opponent_history) > 2:
guess = opponent_history[-2]
return guess |
"""Robot in a grid."""
def robot_path(grid):
"""Return a path for the robot."""
rows = len(grid)
cols = len(grid[0])
valid_paths = []
def traverse_grid(i=0, j=0, path=[]):
if i > rows - 1 or j > cols - 1:
return
if grid[i][j] == 1:
return
if i == ro... | """Robot in a grid."""
def robot_path(grid):
"""Return a path for the robot."""
rows = len(grid)
cols = len(grid[0])
valid_paths = []
def traverse_grid(i=0, j=0, path=[]):
if i > rows - 1 or j > cols - 1:
return
if grid[i][j] == 1:
return
if i == row... |
# Copyright 2021 NVIDIA CORPORATION
# SPDX-License-Identifier: Apache-2.0
#
# Script to generate the GLSL compute functions
#
# uint autogeneratedGetCaseNumber(float sample000, float sample001, float sample010, float sample011,
# float sample100, float sample101, float sample110, float s... | sample000_positive_bit = 1
sample001_positive_bit = 2
sample010_positive_bit = 4
sample011_positive_bit = 8
sample100_positive_bit = 16
sample101_positive_bit = 32
sample110_positive_bit = 64
sample111_positive_bit = 128
bit_map = {'sample000': sample000_positive_bit, 'sample001': sample001_positive_bit, 'sample010': s... |
def view(user, tool):
return True
def create(user, tool):
if user.is_superuser:
return True
return user.is_developer
def change(user, tool):
if user.is_superuser:
return True
return user.is_developer
def delete(user, tool):
if user.is_superuser:
return True
r... | def view(user, tool):
return True
def create(user, tool):
if user.is_superuser:
return True
return user.is_developer
def change(user, tool):
if user.is_superuser:
return True
return user.is_developer
def delete(user, tool):
if user.is_superuser:
return True
return ... |
ingredient1 = "chicken"
ingredient2 = "rice"
Michsays = input ("What is inside this hawker chicken rice?")
if (Michsays == ingredient1 or Michsays == ingredient2):
print("correct!")
else:
print("look again!")
# == takes precedence over or
Michasks = input("How much is the hawker chicken rice?")
floatConvert... | ingredient1 = 'chicken'
ingredient2 = 'rice'
michsays = input('What is inside this hawker chicken rice?')
if Michsays == ingredient1 or Michsays == ingredient2:
print('correct!')
else:
print('look again!')
michasks = input('How much is the hawker chicken rice?')
float_converted_michasks = float(Michasks)
if flo... |
with open("input.txt") as f:
arr = [line.strip() for line in f.readlines()]
feesh = arr[0].split(",")
feesh = [int(num) for num in feesh]
days = 256
max_age = 8
birth_rates = [ [None] * (max_age + 1) for i in range(days + 1)]
#print(feesh)
#print(birth_rates)
def final_feesh(fish_age, day):
print("Age: "... | with open('input.txt') as f:
arr = [line.strip() for line in f.readlines()]
feesh = arr[0].split(',')
feesh = [int(num) for num in feesh]
days = 256
max_age = 8
birth_rates = [[None] * (max_age + 1) for i in range(days + 1)]
def final_feesh(fish_age, day):
print('Age: ' + str(fish_age) + ' Day: ' + str(day))
... |
class Solution:
def flipgame(self, fronts: 'List[int]', backs: 'List[int]') -> 'int':
same_sides = {}
for i in range(len(fronts)):
if fronts[i] == backs[i]:
if fronts[i] not in same_sides:
same_sides[fronts[i]] = 0
same_sides[fronts[i]]... | class Solution:
def flipgame(self, fronts: 'List[int]', backs: 'List[int]') -> 'int':
same_sides = {}
for i in range(len(fronts)):
if fronts[i] == backs[i]:
if fronts[i] not in same_sides:
same_sides[fronts[i]] = 0
same_sides[fronts[i]... |
"""
Given a set and a sum (m) findout whether
there is a subset whose sub is equal to m
Time complexity : O(n*m)
Space complexity : O(n*m)
"""
def solve():
n,m = map(int,input().split())
a = list(map(int,input().split()))
dp = [[0 for i in range(m+1)] for j in range(n+1)]
for i in range(m+1):
... | """
Given a set and a sum (m) findout whether
there is a subset whose sub is equal to m
Time complexity : O(n*m)
Space complexity : O(n*m)
"""
def solve():
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
dp = [[0 for i in range(m + 1)] for j in range(n + 1)]
for i in range(m + ... |
UNSIGNED_CHAR_COLUMN = 251
UNSIGNED_CHAR_LENGTH = 1
UNSIGNED_INT24_COLUMN = 253
UNSIGNED_INT24_LENGTH = 3
UNSIGNED_INT64_COLUMN = 254
UNSIGNED_INT64_LENGTH = 8
UNSIGNED_SHORT_COLUMN = 252
UNSIGNED_SHORT_LENGTH = 2
| unsigned_char_column = 251
unsigned_char_length = 1
unsigned_int24_column = 253
unsigned_int24_length = 3
unsigned_int64_column = 254
unsigned_int64_length = 8
unsigned_short_column = 252
unsigned_short_length = 2 |
"""PostgreSQL utilities"""
def pg_result_to_dict(columns, result, single_object=False):
"""Convert a PostgreSQL query result to a dict"""
resp = []
for row in result:
resp.append(dict(zip(columns, row)))
if single_object:
return resp[0]
return resp
| """PostgreSQL utilities"""
def pg_result_to_dict(columns, result, single_object=False):
"""Convert a PostgreSQL query result to a dict"""
resp = []
for row in result:
resp.append(dict(zip(columns, row)))
if single_object:
return resp[0]
return resp |
info = {
"friendly_name": "Comment (Block)",
"example_template": "comment text",
"summary": "The text within the block is not interpreted or rendered in the final displayed page.",
}
def SublanguageHandler(args, doc, renderer):
pass
| info = {'friendly_name': 'Comment (Block)', 'example_template': 'comment text', 'summary': 'The text within the block is not interpreted or rendered in the final displayed page.'}
def sublanguage_handler(args, doc, renderer):
pass |
def digitize(n):
if n == 0:
return[0]
else:
digits = []
while n > 0:
digits.append(n % 10)
n = (n - n % 10) // 10
return(digits[::-1])
#def digitize(n):
#return list(map(int, str(n)))cc | def digitize(n):
if n == 0:
return [0]
else:
digits = []
while n > 0:
digits.append(n % 10)
n = (n - n % 10) // 10
return digits[::-1] |
#
# PySNMP MIB module CERENT-GLOBAL-REGISTRY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CERENT-GLOBAL-REGISTRY
# Produced by pysmi-0.3.4 at Wed May 1 11:48:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
def metade(valor, formatar=False):
valor = valor / 2
if formatar:
valor = moeda(valor)
return valor
def dobro(valor, formatar=False):
valor *= 2
if formatar:
return moeda(valor)
return valor
def aumentar(valor, porcentagem, formatar=False):
aumenta = valor * (porcentagem ... | def metade(valor, formatar=False):
valor = valor / 2
if formatar:
valor = moeda(valor)
return valor
def dobro(valor, formatar=False):
valor *= 2
if formatar:
return moeda(valor)
return valor
def aumentar(valor, porcentagem, formatar=False):
aumenta = valor * (porcentagem / ... |
print('Accessing private members in Class:')
print('-'*35)
class Human():
# Private var
__privateVar = "this is __private variable"
# Constructor method
def __init__(self):
self.className = "Human class constructor"
self.__privateVar = "this is redefined __private variable"... | print('Accessing private members in Class:')
print('-' * 35)
class Human:
__private_var = 'this is __private variable'
def __init__(self):
self.className = 'Human class constructor'
self.__privateVar = 'this is redefined __private variable'
def show_name(self, name):
self.name = n... |
def CheckPairSum(Arr, Total):
n = len(Arr)
dict_of_numbers = [0] * 1000
# print("Start of loop")
for i in range (n):
difference = Total - Arr[i]
# print difference
if dict_of_numbers[difference] == 1:
print("The pair is"... | def check_pair_sum(Arr, Total):
n = len(Arr)
dict_of_numbers = [0] * 1000
for i in range(n):
difference = Total - Arr[i]
if dict_of_numbers[difference] == 1:
print('The pair is', Arr[i], 'and', difference)
dict_of_numbers[Arr[i]] = 1
arr = [1, 2, 4, 5, 7, 8, 10, -1, 6]
to... |
# NOTE: # noinspection - prefixed comments are for pycharm editor only
# for ignoring PEP 8 style highlights
class PageTitleMixin:
"""Page title mixin class
- for class based views
:argument: -page_title
:methods: - get_page_title()
- get_context_data()
"""
page_title = ''
d... | class Pagetitlemixin:
"""Page title mixin class
- for class based views
:argument: -page_title
:methods: - get_page_title()
- get_context_data()
"""
page_title = ''
def get_page_title(self):
return self.page_title
def get_context_data(self, **kwargs):
cont... |
# Variant DBScan analysis item
# Set variants
vdbscan_variants = pd.DataFrame({'eps': [2,2,3,3], 'mp' : [4,4,5,5]})
# Set column names
vdbscan_column_names = ('ra', 'dec')
# Create Variant DBScan analysis item
ana_vdbscan = skdiscovery.data_structure.table.analysis.VDBScan('VDBScan',vdbscan_variants, vdbscan_column_na... | vdbscan_variants = pd.DataFrame({'eps': [2, 2, 3, 3], 'mp': [4, 4, 5, 5]})
vdbscan_column_names = ('ra', 'dec')
ana_vdbscan = skdiscovery.data_structure.table.analysis.VDBScan('VDBScan', vdbscan_variants, vdbscan_column_names)
sc_vdbscan = stage_container(ana_vdbscan) |
n=int(input("enter number of elements: "))
l=[]
for i in range(n):
l.append(int(input(f"enter l[{i}]: ")))
print(l)
'''
output:
enter number of elements: 6
enter l[0]: 23
enter l[1]: 11
enter l[2]: 67
enter l[3]: 889
enter l[4]: 342
enter l[5]: 23
[23, 11, 67, 889, 342, 23]
'''
| n = int(input('enter number of elements: '))
l = []
for i in range(n):
l.append(int(input(f'enter l[{i}]: ')))
print(l)
'\noutput:\nenter number of elements: 6\nenter l[0]: 23\nenter l[1]: 11\nenter l[2]: 67\nenter l[3]: 889\nenter l[4]: 342\nenter l[5]: 23\n[23, 11, 67, 889, 342, 23]\n' |
"""Top-level package for wyeusk."""
__author__ = """Steve Betts"""
__email__ = 'stevo.betts@gmail.com'
__version__ = '0.1.0'
| """Top-level package for wyeusk."""
__author__ = 'Steve Betts'
__email__ = 'stevo.betts@gmail.com'
__version__ = '0.1.0' |
nun = [[], []]
val = 0
for c in range(0, 8):
val = int(input('Digite um numero: '))
if val % 2 == 0:
num[0].append(val)
else:
num[1].append(val) | nun = [[], []]
val = 0
for c in range(0, 8):
val = int(input('Digite um numero: '))
if val % 2 == 0:
num[0].append(val)
else:
num[1].append(val) |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def prefix(A):
pref = [0] * (len(A)+1)
for i in range(1, len(A)+1):
pref[i] = pref[i-1] + A[i-1]
return pref
def countTotal(P, left, right):
return P[right] - P[left]
def solution(A):
pref = prefix(A)... | def prefix(A):
pref = [0] * (len(A) + 1)
for i in range(1, len(A) + 1):
pref[i] = pref[i - 1] + A[i - 1]
return pref
def count_total(P, left, right):
return P[right] - P[left]
def solution(A):
pref = prefix(A)
n = len(A)
pairs = 0
for i in range(len(A)):
if A[i] == 0:
... |
# https://codeforces.com/problemset/problem/584/A
n, t = map(int, input().split())
if n == 1:
if t < 10:
print(t)
else:
print(-1)
else:
if t < 10:
print(str(t)+'0'*(n-1))
else:
print('1'+'0'*(n-1)) | (n, t) = map(int, input().split())
if n == 1:
if t < 10:
print(t)
else:
print(-1)
elif t < 10:
print(str(t) + '0' * (n - 1))
else:
print('1' + '0' * (n - 1)) |
# Quick Sort
# Time Complexity: O(n^2)
# Space Complexity: O(log(n))
# In-place quick sort does not create subsequences
# its subsequence of the input is represented by a leftmost and rightmost index
def quick_Sort(lst, first, last):
print(lst)
if first >= last: # the lst is sorte... | def quick__sort(lst, first, last):
print(lst)
if first >= last:
return
pivot = lst[last]
lo = first
hi = last - 1
while lo <= hi:
while lo <= hi and lst[lo] < pivot:
lo += 1
while lo <= hi and pivot < lst[hi]:
hi -= 1
if lo <= hi:
... |
# Fibonacci numbers module
def greeting(name="stranger"):
print("Hi {}".format(name))
| def greeting(name='stranger'):
print('Hi {}'.format(name)) |
#split function is used for creat string in to list of String's
# String="10 11 12 13 14 15 16"
#we have to give Raguler Expression as argument of split function
#Know split function will split over string with respact" "
#l=["10","11","12","13","14","15","16"]
# l=String.split(" ")
# String=" 10 12 13 "
#stri... | s = input('Enter String to Split!!!:')
c = input('Enter Char which Respact to Split!!:')
print('List:', s.split(c))
s = input('Enter String :')
print('After Strip String:' + s.strip()) |
def power(number, power=2):
return number ** power
print(power(2, 3)) # 2 * 2 * 2 = 8
print(power(3)) # 3 * 2 = 9
print("------------------")
def showFullName(first, last):
return f"{first} {last}"
print(showFullName(last="Golchinpour", first="Milad"))
| def power(number, power=2):
return number ** power
print(power(2, 3))
print(power(3))
print('------------------')
def show_full_name(first, last):
return f'{first} {last}'
print(show_full_name(last='Golchinpour', first='Milad')) |
data = {}
individual = {}
info = input().split(" -> ")
while "no more time" not in info:
name = info[0]
contest = info[1]
points = int(info[2])
already_in = False
if contest in data:
for i in range(len(data[contest])):
if name == data[contest][i][0]:
already_in ... | data = {}
individual = {}
info = input().split(' -> ')
while 'no more time' not in info:
name = info[0]
contest = info[1]
points = int(info[2])
already_in = False
if contest in data:
for i in range(len(data[contest])):
if name == data[contest][i][0]:
already_in = ... |
# -*-coding: utf-8 -*-
cg_notexists = '15019'
cg_zip_failed = '15009'
vray_notmatch = '15020'
cginfo_failed = '15002'
conflict_multiscatter_vray = '15021'
cg_notmatch = '15013'
camera_duplicat = '15015'
element_duplicat = '15016'
vrmesh_ext_null = "15018"
proxy_enable = "15010"
renderer_notsupport = "15004"
# -------... | cg_notexists = '15019'
cg_zip_failed = '15009'
vray_notmatch = '15020'
cginfo_failed = '15002'
conflict_multiscatter_vray = '15021'
cg_notmatch = '15013'
camera_duplicat = '15015'
element_duplicat = '15016'
vrmesh_ext_null = '15018'
proxy_enable = '15010'
renderer_notsupport = '15004'
camera_null = '15006'
task_folder_... |
"""Test's routes definition."""
routes = [
{'name': 'index', 'pattern': '/'},
{'name': 'secret', 'pattern': '/secret'},
{'name': 'very_secret', 'pattern': '/secret/very'},
]
| """Test's routes definition."""
routes = [{'name': 'index', 'pattern': '/'}, {'name': 'secret', 'pattern': '/secret'}, {'name': 'very_secret', 'pattern': '/secret/very'}] |
#!/usr/bin/env python3
with open("input.txt", "r") as f:
all_groups = [x.strip().split("\n") for x in f.read().split("\n\n")]
anyone = 0
everyone = 0
for group in all_groups:
all = set(group[0])
any = set(group[0])
for person in group[1:]:
all = all.intersection(person)
any.update(*person)
everyone += len... | with open('input.txt', 'r') as f:
all_groups = [x.strip().split('\n') for x in f.read().split('\n\n')]
anyone = 0
everyone = 0
for group in all_groups:
all = set(group[0])
any = set(group[0])
for person in group[1:]:
all = all.intersection(person)
any.update(*person)
everyone += len(... |
class Solution:
def maxScore(self, arr, k):
dp = {'l':[0], 'r':[0]}
curr_sum_left = 0
curr_sum_right = 0
for index in range(0, k):
# for left
curr_sum_left += arr[index]
dp['l'].append(curr_sum_left)
# for right
j = len... | class Solution:
def max_score(self, arr, k):
dp = {'l': [0], 'r': [0]}
curr_sum_left = 0
curr_sum_right = 0
for index in range(0, k):
curr_sum_left += arr[index]
dp['l'].append(curr_sum_left)
j = len(arr) - 1 - index
curr_sum_right += ... |
"""
********************
Singleton Pattern
********************
Description from Wikipedia:
*"the singleton pattern is a software design pattern that
restricts the instantiation of a class to one 'single' instance.
This is useful when exactly one object is needed to coordinate
actions across the system."*
.. warning... | """
********************
Singleton Pattern
********************
Description from Wikipedia:
*"the singleton pattern is a software design pattern that
restricts the instantiation of a class to one 'single' instance.
This is useful when exactly one object is needed to coordinate
actions across the system."*
.. warning... |
# date: 18/06/2020
# Description:
# Given a 32-bit integer,
# swap the 1st and 2nd bit,
# 3rd and 4th bit, up til the 31st and 32nd bit.
# convert from decimal to binary
def convert_to_binary(num):
result=''
while num != 0:
remainder = num % 2 # gives the exact remainder
num = num // 2
... | def convert_to_binary(num):
result = ''
while num != 0:
remainder = num % 2
num = num // 2
result = str(remainder) + result
return result
def swap_bits(num):
results = list(convert_to_binary(num))
out = ''
for i in range(len(results)):
if results[i] == '1':
... |
vectors = { 'NW': (-1, -1), 'N': (-1, 0), 'NE': (-1, 1),
'W' : ( 0, -1), '' : ( 0, 0), 'E' : ( 0, 1),
'SW': ( 1, -1), 'S': ( 1, 0), 'SE': ( 1, 1),
}
class Board:
def __init__(self,grid,directions):
self._nb_row,self._nb_col=(len(grid),len(grid[0]))
s... | vectors = {'NW': (-1, -1), 'N': (-1, 0), 'NE': (-1, 1), 'W': (0, -1), '': (0, 0), 'E': (0, 1), 'SW': (1, -1), 'S': (1, 0), 'SE': (1, 1)}
class Board:
def __init__(self, grid, directions):
(self._nb_row, self._nb_col) = (len(grid), len(grid[0]))
self._size = max(self._nb_row, self._nb_col)
... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... | def find_decision(obj):
if obj[6] <= 6:
if obj[10] > 3:
if obj[11] > 0:
if obj[14] <= 1.0:
if obj[2] <= 2:
if obj[3] <= 2:
return 'False'
elif obj[3] > 2:
i... |
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def findPositions(i, j, attackedColumn = set(), attackedHill = set(), attackedDale = set()):
if i == n-1:
return [[j]]
i += 1
validPos_list = []
... | class Solution:
def solve_n_queens(self, n: int) -> List[List[str]]:
def find_positions(i, j, attackedColumn=set(), attackedHill=set(), attackedDale=set()):
if i == n - 1:
return [[j]]
i += 1
valid_pos_list = []
for k in range(n):
... |
"""Component for the Somfy MyLink device supporting the Synergy API."""
CONF_ENTITY_CONFIG = "entity_config"
CONF_SYSTEM_ID = "system_id"
CONF_REVERSE = "reverse"
CONF_DEFAULT_REVERSE = "default_reverse"
DEFAULT_CONF_DEFAULT_REVERSE = False
DATA_SOMFY_MYLINK = "somfy_mylink_data"
MYLINK_STATUS = "mylink_status"
MYLINK... | """Component for the Somfy MyLink device supporting the Synergy API."""
conf_entity_config = 'entity_config'
conf_system_id = 'system_id'
conf_reverse = 'reverse'
conf_default_reverse = 'default_reverse'
default_conf_default_reverse = False
data_somfy_mylink = 'somfy_mylink_data'
mylink_status = 'mylink_status'
mylink_... |
#! /usr/bin/env python3
with open("input", "r") as fd :
instructions = [x.split(' ') for x in fd.read().split('\n')]
acc = 0
done = [False] * len(instructions)
i = 0
while 0 <= i < len(instructions) and not done[i] :
done[i] = True
instruction, value = instructions[i]
if instruction == "acc" :
... | with open('input', 'r') as fd:
instructions = [x.split(' ') for x in fd.read().split('\n')]
acc = 0
done = [False] * len(instructions)
i = 0
while 0 <= i < len(instructions) and (not done[i]):
done[i] = True
(instruction, value) = instructions[i]
if instruction == 'acc':
acc += int(value)
if... |
class Point3:
"""A point in three-dimensional space."""
def __init__(self, x=0, y=0, z=0):
self.x=x
self.y=y
self.z=z
def __repr__(self):
return f"({self.x},{self.y},{self.z})"
def __str__(self):
return self.__repr__()
def __add__(self, other... | class Point3:
"""A point in three-dimensional space."""
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f'({self.x},{self.y},{self.z})'
def __str__(self):
return self.__repr__()
def __add__(self, other):
... |
def ben_update():
return
def ben_random_tick():
return
| def ben_update():
return
def ben_random_tick():
return |
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, n):
self.width = n
def set_height(self, n):
self.height = n
def get_area(self):
return self.height * self.width
def get_perimeter(self):
... | class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, n):
self.width = n
def set_height(self, n):
self.height = n
def get_area(self):
return self.height * self.width
def get_perimeter(self):
... |
'''
Duplicate the elements of a list.
Example:
* (dupli '(a b c c d))
(A A B B C C C C D D)
'''
#taking input of list elements at a single time seperating by space and splitting each by split() method
demo_list = input("Enter elements seperated by space: ").split()
duplicates_list = list()
list_length = l... | """
Duplicate the elements of a list.
Example:
* (dupli '(a b c c d))
(A A B B C C C C D D)
"""
demo_list = input('Enter elements seperated by space: ').split()
duplicates_list = list()
list_length = len(demo_list)
index = 0
while index < list_length:
for _ in range(2):
duplicates_list.append(de... |
n = int(input())
max_num = -1000000000000
for i in range(n):
num = int(input())
if num > max_num:
max_num = num
print(max_num) | n = int(input())
max_num = -1000000000000
for i in range(n):
num = int(input())
if num > max_num:
max_num = num
print(max_num) |
with open("day-08.txt") as f:
lines = f.read().rstrip().splitlines()
ans = 0
for line in lines:
_, output = line.split(" | ")
for digit in output.split(maxsplit=3):
ans += len(digit) in (2, 3, 4, 7)
print(ans)
| with open('day-08.txt') as f:
lines = f.read().rstrip().splitlines()
ans = 0
for line in lines:
(_, output) = line.split(' | ')
for digit in output.split(maxsplit=3):
ans += len(digit) in (2, 3, 4, 7)
print(ans) |
"""
This file is included in all files
"""
# THIS FILE IS INCLUDED IN ALL FILES
RELEASE = 'Created by BFM v. 5.1'
PATH_MAX = 255
stderr = 0
stdout = 6
# HANDY FOR WRITING
def STDOUT(text):
print(text)
def STDERR(text):
print(text)
# STANDARD OUTPUT FOR PARALLEL COMPUTATION
def LEVEL0():
STDERR('')
de... | """
This file is included in all files
"""
release = 'Created by BFM v. 5.1'
path_max = 255
stderr = 0
stdout = 6
def stdout(text):
print(text)
def stderr(text):
print(text)
def level0():
stderr('')
def level1():
stderr(' ')
def level2():
stderr(' ')
def level3():
stderr(' ... |
'''MIT License
Copyright (c) 2022 Carlos M.C.G. Fernandes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge,... | """MIT License
Copyright (c) 2022 Carlos M.C.G. Fernandes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge,... |
class ApplyMaskBase(object):
def __init__(self):
pass
def apply_mask(self, *arg, **kwargs):
raise NotImplementedError("Please implement in subclass")
| class Applymaskbase(object):
def __init__(self):
pass
def apply_mask(self, *arg, **kwargs):
raise not_implemented_error('Please implement in subclass') |
#
# # Recursive + memo (top-down)
# class Solution(object):
# def rob(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# cache = [-1] * len(nums)
# return self.robHelper(nums, len(nums) - 1, cache)
#
# def robHelper(self, nums, currentHouse, cache):
... | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 0:
return 0
(previous_robbed_money, current_robbed_money) = (0, nums[0])
for i in range(1, len(nums)):
current_robbed_money_holder =... |
a == b
a != b
a < b
a <= b
a > b
a >= b
a is b
a is not b
a in b
a not in b
| a == b
a != b
a < b
a <= b
a > b
a >= b
a is b
a is not b
a in b
a not in b |
# iterator_protocol.py
print("""
The iterator protocol specifies two special methods to be implemented for any object to allow iteration
1. For any object to be iterated over, it must implement the __iter__ method which returns an iterator object.
Any object that returns an iterator is an iterable.
2. An iterator m... | print('\nThe iterator protocol specifies two special methods to be implemented for any object to allow iteration\n\n1. For any object to be iterated over, it must implement the __iter__ method which returns an iterator object.\nAny object that returns an iterator is an iterable.\n\n2. An iterator must implement the __n... |
def quickshort(a,start,end):
if start<end:
pindex = partition(a,start,end)
quickshort(a,start,pindex-1)
quickshort(a,pindex+1,end)
def partition(a,start,end):
middle = int(end/2)
pivot = a[middle]
pindex = start
for i in range(start,middle):
if a[i]>=pivot:
a[i],a[pindex]=a[pindex],a[i]
... | def quickshort(a, start, end):
if start < end:
pindex = partition(a, start, end)
quickshort(a, start, pindex - 1)
quickshort(a, pindex + 1, end)
def partition(a, start, end):
middle = int(end / 2)
pivot = a[middle]
pindex = start
for i in range(start, middle):
if a[i... |
"""Functions for creating `XcodeProjInfo` providers."""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_skylib//lib:sets.bzl", "sets")
load(
"@build_bazel_rules_apple//apple:providers.bzl",
"AppleBundleInfo",
"AppleFrameworkImportInfo",
"IosXcTestBundleInfo",
)
load("@build_bazel_rules_swift... | """Functions for creating `XcodeProjInfo` providers."""
load('@bazel_skylib//lib:paths.bzl', 'paths')
load('@bazel_skylib//lib:sets.bzl', 'sets')
load('@build_bazel_rules_apple//apple:providers.bzl', 'AppleBundleInfo', 'AppleFrameworkImportInfo', 'IosXcTestBundleInfo')
load('@build_bazel_rules_swift//swift:swift.bzl', ... |
"""
A module to show off a long-running function.
This module reads a very large text file and counts the
number of times each word appears in that file
Author: Walker M. White
Date: November 2, 2020
"""
def add_word(word,counts):
"""
Adds a word to a word-count dictionary.
The keys of the dictionari... | """
A module to show off a long-running function.
This module reads a very large text file and counts the
number of times each word appears in that file
Author: Walker M. White
Date: November 2, 2020
"""
def add_word(word, counts):
"""
Adds a word to a word-count dictionary.
The keys of the dictionari... |
#
# Problem: Compare original text vs what was altered and return a dict of
# indexes match_index_mapping the matching elements from the original text
# array to the altered text array.
#
# Algorithm should maximize the number of matches in sequential order.
#
# TODO: consider using dicts/tree instead of arrays
#
cla... | class Matchindexmapping:
def __init__(self, key, value):
self.key = key
self.value = value
def __str__(self):
return f'({self.key}, {self.value})'
def print_all_results(all_results):
print('\nAll Results:')
for (index, result) in enumerate(all_results):
print(str(index... |
# -*- coding: utf-8 -*-
"""
Looping Examples
Intro to Python Workshop
"""
## Iteration 1 - Iconic lyrics
n = 5
while n > 0:
print ("Hello "*3)
print ("How low")
print ("Entertain us!")
## Iteration 2 - Iconic lyrics
n = 0
while n > 0:
print ("Hello"*3)
print ("How low")
print ("E... | """
Looping Examples
Intro to Python Workshop
"""
n = 5
while n > 0:
print('Hello ' * 3)
print('How low')
print('Entertain us!')
n = 0
while n > 0:
print('Hello' * 3)
print('How low')
print('Entertain us!')
while True:
line = input('>Enter something: ')
if line == 'all done':
break
p... |
#!/usr/bin/python3
given_list = [['87', '90', '78', '94'], ['78', '98', '92', '67']]
students = ['Chris', 'Eva']
names_classes = ['Math', 'Chemistry', 'Physics', 'English']
def printing(given_list, name_classes):
"""Printing catalog pandas style but without pandas"""
maxi_names = max(len(str(students[i])) f... | given_list = [['87', '90', '78', '94'], ['78', '98', '92', '67']]
students = ['Chris', 'Eva']
names_classes = ['Math', 'Chemistry', 'Physics', 'English']
def printing(given_list, name_classes):
"""Printing catalog pandas style but without pandas"""
maxi_names = max((len(str(students[i])) for i in range(len(stu... |
"""
Basic GLS Syntax
Version 0.0.1
Josh Goldberg
"""
# Function Definitions
def sayHello():
print("Hello world!")
def combineStrings(a, b):
return a + b
# Class Declarations
class Point:
x = None
y = None
def __init__(self, x, y):
self.x = x
self.y = y
def setX(self, ... | """
Basic GLS Syntax
Version 0.0.1
Josh Goldberg
"""
def say_hello():
print('Hello world!')
def combine_strings(a, b):
return a + b
class Point:
x = None
y = None
def __init__(self, x, y):
self.x = x
self.y = y
def set_x(self, x):
self.x = x
def set_y(self, y):
... |
N, C = map(int, input().split())
l = [tuple(map(int, input().split())) for i in range(N)]
s = set()
for a, b, c in l:
s.add(a)
s.add(b + 1)
d = {}
s = sorted(list(s))
for i, j in enumerate(s):
d[j] = i
m = [0] * (len(s) + 1)
for a, b, c in l:
m[d[a]] += c
m[d[b + 1]] -= c
ans = 0
for i in range(len(... | (n, c) = map(int, input().split())
l = [tuple(map(int, input().split())) for i in range(N)]
s = set()
for (a, b, c) in l:
s.add(a)
s.add(b + 1)
d = {}
s = sorted(list(s))
for (i, j) in enumerate(s):
d[j] = i
m = [0] * (len(s) + 1)
for (a, b, c) in l:
m[d[a]] += c
m[d[b + 1]] -= c
ans = 0
for i in ra... |
print( 1 == 1 or 2 == 2 )
print( 1 == 1 or 2 == 3 )
print( 1 != 1 or 2 == 2 )
print( 2 < 1 or 3 > 6 )
| print(1 == 1 or 2 == 2)
print(1 == 1 or 2 == 3)
print(1 != 1 or 2 == 2)
print(2 < 1 or 3 > 6) |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class llist:
def __init__(self):
self.head = None
def reverse(self, head):
if head is None or head.next is None:
return head
rest = self.reverse(head.next)
head.next.next ... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Llist:
def __init__(self):
self.head = None
def reverse(self, head):
if head is None or head.next is None:
return head
rest = self.reverse(head.next)
head.next.next =... |
texto = input("Ingrese su texto: ")
def SpaceToDash(texto):
return texto.replace(" ", "-")
print (SpaceToDash(texto)) | texto = input('Ingrese su texto: ')
def space_to_dash(texto):
return texto.replace(' ', '-')
print(space_to_dash(texto)) |
nome = 'Fabio Rodrigues Dias'
cores = {'limpa':'\033[m',
'azul':'\033[1;7;34m',
'amarelo':'\033[33m',
'pretoebranco': '\033[7;30m'}
print('Ola!! Muito prazer em te conhecer, {}{}{}'.format(cores['azul'], nome , cores['limpa'])) | nome = 'Fabio Rodrigues Dias'
cores = {'limpa': '\x1b[m', 'azul': '\x1b[1;7;34m', 'amarelo': '\x1b[33m', 'pretoebranco': '\x1b[7;30m'}
print('Ola!! Muito prazer em te conhecer, {}{}{}'.format(cores['azul'], nome, cores['limpa'])) |
"""Warnings"""
# Authors: Jeffrey Wang
# License: BSD 3 clause
class ConvergenceWarning(UserWarning):
"""
Custom warning to capture convergence issues.
"""
class InitializationWarning(UserWarning):
"""
Custom warning to capture initialization issues.
"""
class StabilizationWarning(UserWarning):
"""
Custom w... | """Warnings"""
class Convergencewarning(UserWarning):
"""
Custom warning to capture convergence issues.
"""
class Initializationwarning(UserWarning):
"""
Custom warning to capture initialization issues.
"""
class Stabilizationwarning(UserWarning):
"""
Custom warning to capture stabilization issues.
... |
# Copyright (c) 2018, the R8 project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
def CheckDoNotMerge(input_api, output_api):
for l in input_api.change.FullDescriptionText().splitlines():
... | def check_do_not_merge(input_api, output_api):
for l in input_api.change.FullDescriptionText().splitlines():
if l.lower().startswith('do not merge'):
msg = "Your cl contains: 'Do not merge' - this will break WIP bots"
return [output_api.PresubmitPromptWarning(msg, [])]
return []
... |
# I wouldn't be able to say if this question was hard or easy. It uses the fundamental stuff. No modules.
# However changing the rules of math was mind-boggling
def Part1(part2):
calc = list()
with open("Day18.txt") as f:
for line in f:
operation = line.strip().replace(" ", "")
... | def part1(part2):
calc = list()
with open('Day18.txt') as f:
for line in f:
operation = line.strip().replace(' ', '')
start = 0
parentheses = list()
while True:
for i in range(start, len(operation)):
if operation[i] == '... |
class VCard():
def __init__(self, filename:str):
self.filename = filename
def create(self, display_name:list, full_name:str, number:str, email:str=None):
'''Create a vcf card'''
bp = [1, 2, 0]
pp = [0, 1, 2]
rn = []
for i, j in zip(bp, pp):
rn.insert(i, display_name[j]+";")
fd = self.fi... | class Vcard:
def __init__(self, filename: str):
self.filename = filename
def create(self, display_name: list, full_name: str, number: str, email: str=None):
"""Create a vcf card"""
bp = [1, 2, 0]
pp = [0, 1, 2]
rn = []
for (i, j) in zip(bp, pp):
rn.i... |
#!/usr/bin/env python3
"""genomehubs version."""
__version__ = "2.2.0"
| """genomehubs version."""
__version__ = '2.2.0' |
#
# Copyright (c) 2017 Joy Diamond. All rights reserved.
#
@gem('Quartz.Parse1')
def gem():
require_gem('Quartz.Match')
require_gem('Quartz.Core')
show = true
@share
def parse1_mysql_from_path(path):
data = read_text_from_path(path)
many = []
append = many.append
... | @gem('Quartz.Parse1')
def gem():
require_gem('Quartz.Match')
require_gem('Quartz.Core')
show = true
@share
def parse1_mysql_from_path(path):
data = read_text_from_path(path)
many = []
append = many.append
iterate_lines = z_initialize(path, data)
for s in iter... |
#!/usr/bin/env python3
"""Front Back.
Given a string, return a new string where the
first and last chars have been exchanged.
front_back('code') == 'eodc'
front_back('a') == 'a'
front_back('ab') == 'ba'
"""
def front_back(str_: str) -> str:
"""Swap the first and last characters of a string."""
if len(str_)... | """Front Back.
Given a string, return a new string where the
first and last chars have been exchanged.
front_back('code') == 'eodc'
front_back('a') == 'a'
front_back('ab') == 'ba'
"""
def front_back(str_: str) -> str:
"""Swap the first and last characters of a string."""
if len(str_) > 1:
return f'{s... |
# https://leetcode.com/problems/encode-and-decode-strings/
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
return ''.join(s.replace('|', '||') + ' | ' for s in strs)
def decode(self, s):
... | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
return ''.join((s.replace('|', '||') + ' | ' for s in strs))
def decode(self, s):
"""Decodes a single string to a list of strings.
... |
a = range(2, 10, 2)
b = list(a)
c = [a]
print('')
| a = range(2, 10, 2)
b = list(a)
c = [a]
print('') |
# This si a hello worls script
# written in Python
def main():
print("Hello, world")
if __name__ == "__main__":
main()
| def main():
print('Hello, world')
if __name__ == '__main__':
main() |
# Your code below:
number_list = range(9)
print(list(number_list))
zero_to_seven = range(8)
print(list(zero_to_seven)) | number_list = range(9)
print(list(number_list))
zero_to_seven = range(8)
print(list(zero_to_seven)) |
# Solution to problem 6 #
#Student: Niamh O'Leary#
#ID: G00376339#
#Write a program that takes a user input string and outputs every second word#
string = "The quick broen fox jumps over the lazy dog"
even_words = string.split(' ')[::2] #split the original string. Then use slice to select every second word#
... | string = 'The quick broen fox jumps over the lazy dog'
even_words = string.split(' ')[::2] |
#
# This file is part of pySMT.
#
# Copyright 2014 Andrea Micheli and Marco Gario
#
# 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
... | class Interpolator(object):
def __init__(self):
self._destroyed = False
def binary_interpolant(self, a, b):
"""Returns a binary interpolant for the pair (a, b), if And(a, b) is
unsatisfaiable, or None if And(a, b) is satisfiable.
"""
raise NotImplementedError
def ... |
def left(i):
return 2*i+1
def right(i):
return 2*i+2
def max_heapify(data, size, i):
l = left(i)
r = right(i)
val = data[i]
largest = i
if l < size and data[l] > data[largest]:
largest = l
if r < size and data[r] > data[largest]:
largest = r
if largest != i:
... | def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
def max_heapify(data, size, i):
l = left(i)
r = right(i)
val = data[i]
largest = i
if l < size and data[l] > data[largest]:
largest = l
if r < size and data[r] > data[largest]:
largest = r
if largest != i:... |
# Calculate the standard deviation by taking the square root
port_standard_dev = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
# Print the results
print(str(np.round(port_standard_dev, 4) * 100) + '%')
| port_standard_dev = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
print(str(np.round(port_standard_dev, 4) * 100) + '%') |
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
self.res = 0
self.dfs(root)
return self.res-1
def dfs(self, root):
if not root:
return 0
left = self.dfs(root.left)
right = self.dfs(r... | class Solution:
def diameter_of_binary_tree(self, root: TreeNode) -> int:
if not root:
return 0
self.res = 0
self.dfs(root)
return self.res - 1
def dfs(self, root):
if not root:
return 0
left = self.dfs(root.left)
right = self.dfs... |
def _set_status(task_list, task_name, status):
task = task_list.get_task(task_name)
task.status = status
def done(task_list, args):
_set_status(task_list, args.task, "completed")
return
def start(task_list, args):
_set_status(task_list, args.task, "started")
return
def pause(task_list, arg... | def _set_status(task_list, task_name, status):
task = task_list.get_task(task_name)
task.status = status
def done(task_list, args):
_set_status(task_list, args.task, 'completed')
return
def start(task_list, args):
_set_status(task_list, args.task, 'started')
return
def pause(task_list, args):... |
# coding: utf-8
class ArrayBasedQueue:
def __init__(self):
self.array = []
def __len__(self):
return len(self.array)
def __iter__(self):
for item in self.array:
yield item
# O(1)
def enqueue(self, value):
self.array.append(value)
# O(n)
def deq... | class Arraybasedqueue:
def __init__(self):
self.array = []
def __len__(self):
return len(self.array)
def __iter__(self):
for item in self.array:
yield item
def enqueue(self, value):
self.array.append(value)
def dequeue(self):
try:
... |
#1. Create a greeting for your program.
print("\nSimple Name Generator\n")
#2. Ask the user for the city that they grew up in.
#raw_input() for python v2 , input() for python v3
# Make sure the input cursor shows on a new line
raw_input("Press enter : ")
print("\nSimple Name Generator\n")
city = raw_input("What is the ... | print('\nSimple Name Generator\n')
raw_input('Press enter : ')
print('\nSimple Name Generator\n')
city = raw_input('What is the name of the city you grew up ? : ')
family_name = raw_input('What is your family name ? : ')
print('The name of your new brand is: \n' + city + ' ' + family_name) |
class Solution:
def solve(self, height, blacklist):
blacklist = set(blacklist)
if height in blacklist: return 0
dp = [[0,1]]
MOD = int(1e9+7)
for i in range(1,height+1):
if height-i in blacklist:
dp.append([0,0])
continue
... | class Solution:
def solve(self, height, blacklist):
blacklist = set(blacklist)
if height in blacklist:
return 0
dp = [[0, 1]]
mod = int(1000000000.0 + 7)
for i in range(1, height + 1):
if height - i in blacklist:
dp.append([0, 0])
... |
"""
[A. Is it rated?](https://codeforces.com/contest/1331/problem/A)
"""
print("No") # The contest was not rated
| """
[A. Is it rated?](https://codeforces.com/contest/1331/problem/A)
"""
print('No') |
def addFeatureDataStruc(data):
data['LenCarName']=data['car name'].apply(lambda x: len(x.split()))
newFeat=[ 'cylinders', 'displacement', 'horsepower', 'weight','acceleration','lrScore','LenCarName']
return data[newFeat],data[['mpg']]
| def add_feature_data_struc(data):
data['LenCarName'] = data['car name'].apply(lambda x: len(x.split()))
new_feat = ['cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'lrScore', 'LenCarName']
return (data[newFeat], data[['mpg']]) |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: min_heap.py
@time: 2019/4/29 20:23
@desc:
'''
# please see the comments in max_heap.py
def min_heap(array):
if not array:
return None
length = len(array)
... | """
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: min_heap.py
@time: 2019/4/29 20:23
@desc:
"""
def min_heap(array):
if not array:
return None
length = len(array)
if length == 1:
return array
for i in range(length // 2 - 1, -1, -1):
... |
# -*- coding: utf-8 -*-
#Lists
myList = [1, 2, 3, 4, 5, "Hello"]
print(myList)
print(myList[2])
print(myList[-1])
myList.append("Simo")
print(myList)
#Tuples - like lists, but you cannot modify their values.
monthsOf = ("Jan","Feb","Mar","Apr")
print(monthsOf)
#Dictionary - a collection of related data PAIRS
myDict ... | my_list = [1, 2, 3, 4, 5, 'Hello']
print(myList)
print(myList[2])
print(myList[-1])
myList.append('Simo')
print(myList)
months_of = ('Jan', 'Feb', 'Mar', 'Apr')
print(monthsOf)
my_dict = {'One': 1.35, 2.5: 'Two Point Five', 3: '+', 7.9: 2}
print(myDict)
del myDict['One']
print(myDict) |
SCAN_COMMANDS = {'arp', 'arp-scan', 'fping', 'nmap'}
def rule(event):
# Filter out commands
if event['event'] == 'session.command' and not event.get('argv'):
return False
# Check that the program is in our watch list
return event.get('program') in SCAN_COMMANDS
def title(event):
return '... | scan_commands = {'arp', 'arp-scan', 'fping', 'nmap'}
def rule(event):
if event['event'] == 'session.command' and (not event.get('argv')):
return False
return event.get('program') in SCAN_COMMANDS
def title(event):
return 'User [{}] has issued a network scan with [{}]'.format(event.get('user', 'USE... |
def getPeopleHarvest(req):
try:
# result = req.get("result")
# username = "pescettoe@amvbbdo.com"
# password = "Welcome1!"
# top_level_url = "https://xlaboration.harvestapp.com/people/1514150"
#
# # create an authorization handler
# p = urllib.request.HTTPPass... | def get_people_harvest(req):
try:
q = request('https://xlaboration.harvestapp.com/people/1514150')
q.add_header('Authorization', 'Basic cGVzY2V0dG9lQGFtdmJiZG8uY29tOldlbGNvbWUxIQ==')
q.add_header('Accept', 'application/json')
q.add_header('Content-Type', 'application/json')
a... |
"""
URL: https://codeforces.com/problemset/problem/1421/A
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: bitmasks, math
"""
t = int(input())
for _ in range(t):
a, b = map(int, input().split())
print(a ^ b)
| """
URL: https://codeforces.com/problemset/problem/1421/A
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: bitmasks, math
"""
t = int(input())
for _ in range(t):
(a, b) = map(int, input().split())
print(a ^ b) |
ASCII = [c for c in (chr(i) for i in range(32, 127))]
def cipher(text, key, decode):
op = ''
for i, j in enumerate(text):
if j not in ASCII:
op += j
else:
text_index = ASCII.index(j)
k = key[i % len(key)]
key_index = ASCII.index(k)
if... | ascii = [c for c in (chr(i) for i in range(32, 127))]
def cipher(text, key, decode):
op = ''
for (i, j) in enumerate(text):
if j not in ASCII:
op += j
else:
text_index = ASCII.index(j)
k = key[i % len(key)]
key_index = ASCII.index(k)
i... |
"""This is a 'Hello, world' program."""
def hello():
"""Say, hello."""
print("Hello, World!")
if __name__ == "__main__":
hello()
| """This is a 'Hello, world' program."""
def hello():
"""Say, hello."""
print('Hello, World!')
if __name__ == '__main__':
hello() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.