content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def main():
n = int(input())
a = list(map(int,input().split()))
count2 = 0
count4 = 0
for e in a:
if e%2 == 0:
count2 += 1
if e%4 == 0:
count4 += 1
if n == 3 and count4:
print("Yes")
return
if count2 == n:
print("Yes")
r... | def main():
n = int(input())
a = list(map(int, input().split()))
count2 = 0
count4 = 0
for e in a:
if e % 2 == 0:
count2 += 1
if e % 4 == 0:
count4 += 1
if n == 3 and count4:
print('Yes')
return
if count2 == n:
print('Yes')
... |
class Node:
def __init__(self, game, parent, action):
self.game = game
self.parent = parent
self.action = action
self.player = game.get_current_player()
self.score = game.get_score()
self.children = []
self.visits = 0
def is_leaf(self):
... | class Node:
def __init__(self, game, parent, action):
self.game = game
self.parent = parent
self.action = action
self.player = game.get_current_player()
self.score = game.get_score()
self.children = []
self.visits = 0
def is_leaf(self):
return no... |
def product(x, y):
ret = list()
for _x in x:
for _y in y:
ret.append((_x, _y))
return ret
print(product([1, 2, 3], ["a", "b"]))
| def product(x, y):
ret = list()
for _x in x:
for _y in y:
ret.append((_x, _y))
return ret
print(product([1, 2, 3], ['a', 'b'])) |
# configuration
class Config:
DEBUG = True
# db
SQLALCHEMY_DATABASE_URI = 'mysql://root:root@localhost/djangoapp'
SQLALCHEMY_TRACK_MODIFICATIONS = False
| class Config:
debug = True
sqlalchemy_database_uri = 'mysql://root:root@localhost/djangoapp'
sqlalchemy_track_modifications = False |
class VaultConfig(object):
def __init__(self):
self.method = None
self.address = None
self.username = None
self.namespace = None
self.studio = None
self.mount_point = None
self.connect = False
| class Vaultconfig(object):
def __init__(self):
self.method = None
self.address = None
self.username = None
self.namespace = None
self.studio = None
self.mount_point = None
self.connect = False |
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Garfield Lee Freeman (@shinmog)
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = r'''
'''
FACTS = r'''
notes:
- As this is a facts module, check mode is not supported.
options:
search_type:
descripti... | class Moduledocfragment(object):
documentation = '\n'
facts = "\nnotes:\n - As this is a facts module, check mode is not supported.\noptions:\n search_type:\n description:\n - How to interpret the value given for the primary param.\n choices:\n - exact\n - su... |
#!/usr/bin/env python3
class Canvas(object):
def __init__(self, width, height):
self.width = width
self.height = height
self._area = []
for _ in range(height):
self._area.append([c for c in ' ' * width])
def _inside_canvas(self, x, y):
return 0 < x <= self.... | class Canvas(object):
def __init__(self, width, height):
self.width = width
self.height = height
self._area = []
for _ in range(height):
self._area.append([c for c in ' ' * width])
def _inside_canvas(self, x, y):
return 0 < x <= self.width and 0 < y <= self.... |
'''
Praveen Manimaran
CIS 41A Spring 2020
Exercise A
'''
height = 2.9
width = 7.1
height = height// 2
width = width// 2
area = height*width
print("height: ",height)
print("width: ",width)
print("area: ",area) | """
Praveen Manimaran
CIS 41A Spring 2020
Exercise A
"""
height = 2.9
width = 7.1
height = height // 2
width = width // 2
area = height * width
print('height: ', height)
print('width: ', width)
print('area: ', area) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Solution:
def longestPalindrome(self,s):
dp = [[False for _ in range(len(s))] for _ in range(len(s))]
l,r = 0,0
for head in range(len(s)-2,0,-1):
for tail in range(head,len(s)):
if s[head] == s[tail] and (tail-he... | class Solution:
def longest_palindrome(self, s):
dp = [[False for _ in range(len(s))] for _ in range(len(s))]
(l, r) = (0, 0)
for head in range(len(s) - 2, 0, -1):
for tail in range(head, len(s)):
if s[head] == s[tail] and (tail - head < 3 or dp[head + 1][tail - ... |
#!/usr/bin/env python3
def part1():
data = open('day8_input.txt').read().splitlines()
one = 2 # 2 segments light up to display 1
four = 4
seven = 3
eight = 7
output = [i.rpartition('|')[2].strip() for i in data]
counter = 0
for i in range(len(output)):
strings = output[i... | def part1():
data = open('day8_input.txt').read().splitlines()
one = 2
four = 4
seven = 3
eight = 7
output = [i.rpartition('|')[2].strip() for i in data]
counter = 0
for i in range(len(output)):
strings = output[i].split()
for string in strings:
length = len(s... |
valores = input().split()
x, y = valores
x = float(x)
y = float(y)
if(x == 0.0 and y == 0.0):
print('Origem')
if(x == 0.0 and y != 0.0):
print('Eixo Y')
if(x != 0.0 and y == 0.0):
print('Eixo X')
if(x > 0 and y > 0):
print('Q1')
if(x < 0 and y > 0):
print('Q2')
if(x < 0 and y < 0):
pr... | valores = input().split()
(x, y) = valores
x = float(x)
y = float(y)
if x == 0.0 and y == 0.0:
print('Origem')
if x == 0.0 and y != 0.0:
print('Eixo Y')
if x != 0.0 and y == 0.0:
print('Eixo X')
if x > 0 and y > 0:
print('Q1')
if x < 0 and y > 0:
print('Q2')
if x < 0 and y < 0:
print('Q3')
if x ... |
#! python3
# Configuration file for cf-py-importer
globalSettings = {
# FQDN or IP address of the CyberFlood Controller. Do NOT prefix with https://
"cfControllerAddress": "your.cyberflood.controller",
"userName": "your@login",
"userPassword": "yourPassword"
}
| global_settings = {'cfControllerAddress': 'your.cyberflood.controller', 'userName': 'your@login', 'userPassword': 'yourPassword'} |
#OPCODE_Init = b"0"
OPCODE_ActivateLayer0 = b"1"
OPCODE_ActivateLayer1 = b"2"
OPCODE_ActivateLayer2 = b"3"
OPCODE_ActivateLayer3 = b"4"
OPCODE_NextAI = b"5"
OPCODE_NewTournament = b"6"
OPCODE_Exit = b"7" | opcode__activate_layer0 = b'1'
opcode__activate_layer1 = b'2'
opcode__activate_layer2 = b'3'
opcode__activate_layer3 = b'4'
opcode__next_ai = b'5'
opcode__new_tournament = b'6'
opcode__exit = b'7' |
greek_alp = {
"Alpha" : "Alp",
"Beta" : "Bet",
"Gamma" : "Gam",
"Delta" : "Del",
"Epsilon" : "Eps",
"Zeta" : "Zet",
"Eta" : "Eta",
"Theta" : "The",
"Iota" : "Iot",
"Kappa" : "Kap",
"Lambda" : "Lam",
"Mu" : "Mu ",
"Nu" : "Nu ",
"Xi" : "Xi ",
"Omicron" : "Omi",
"Pi" : "Pi ",
"Rho" : "Rho",
"Sigma" : "Si... | greek_alp = {'Alpha': 'Alp', 'Beta': 'Bet', 'Gamma': 'Gam', 'Delta': 'Del', 'Epsilon': 'Eps', 'Zeta': 'Zet', 'Eta': 'Eta', 'Theta': 'The', 'Iota': 'Iot', 'Kappa': 'Kap', 'Lambda': 'Lam', 'Mu': 'Mu ', 'Nu': 'Nu ', 'Xi': 'Xi ', 'Omicron': 'Omi', 'Pi': 'Pi ', 'Rho': 'Rho', 'Sigma': 'Sig', 'Tau': 'Tau', 'Upsilon': 'Ups', '... |
data = ["React", "Angular", "Svelte", "Vue"]
# or
data = [
{"value": "React", "label": "React"},
{"value": "Angular", "label": "Angular"},
{"value": "Svelte", "label": "Svelte"},
{"value": "Vue", "label": "Vue"},
]
| data = ['React', 'Angular', 'Svelte', 'Vue']
data = [{'value': 'React', 'label': 'React'}, {'value': 'Angular', 'label': 'Angular'}, {'value': 'Svelte', 'label': 'Svelte'}, {'value': 'Vue', 'label': 'Vue'}] |
FONT = "Arial"
FONT_SIZE_TINY = 8
FONT_SIZE_SMALL = 11
FONT_SIZE_REGULAR = 14
FONT_SIZE_LARGE = 16
FONT_SIZE_EXTRA_LARGE = 20
FONT_WEIGHT_LIGHT = 100
FONT_WEIGHT_REGULAR = 600
FONT_WEIGHT_BOLD = 900
| font = 'Arial'
font_size_tiny = 8
font_size_small = 11
font_size_regular = 14
font_size_large = 16
font_size_extra_large = 20
font_weight_light = 100
font_weight_regular = 600
font_weight_bold = 900 |
person = ('Nana', 25, 'piza')
# unpack mikonim person ro
# chandta ro ba ham takhsis midim
name, age, food = person
print(name)
print(age)
print(food)
person2 = ["ali", 26, "eli"]
name, age, food = person2
print(name)
print(age)
print(food)
# dictionary order nadare o nmishe tekrari dasht
dic = {'banana', 'bluebe... | person = ('Nana', 25, 'piza')
(name, age, food) = person
print(name)
print(age)
print(food)
person2 = ['ali', 26, 'eli']
(name, age, food) = person2
print(name)
print(age)
print(food)
dic = {'banana', 'blueberry'}
dic.add('kiwi')
print(dic)
lis = [1, 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 8, 6]
no_duplicate = set(lis)
print(no_... |
# -*- coding: utf-8 -*-
def main():
n = int(input())
a_score, b_score = 0, 0
for i in range(n):
ai, bi = map(int, input().split())
if ai > bi:
a_score += ai + bi
elif ai < bi:
b_score += ai + bi
else:
a_score += ai
b_score +... | def main():
n = int(input())
(a_score, b_score) = (0, 0)
for i in range(n):
(ai, bi) = map(int, input().split())
if ai > bi:
a_score += ai + bi
elif ai < bi:
b_score += ai + bi
else:
a_score += ai
b_score += bi
print(a_score... |
UPWARDS = 1
UPDOWN = -1
FARAWAY = 1.0e39
SKYBOX_DISTANCE = 1.0e6
| upwards = 1
updown = -1
faraway = 1e+39
skybox_distance = 1000000.0 |
class Solution:
def checkStraightLine(self, coordinates: [[int]]) -> bool:
(x1, y1), (x2, y2) = coordinates[:2]
for i in range(2, len(coordinates)):
x, y = coordinates[i]
if (y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1):
return False
return True
| class Solution:
def check_straight_line(self, coordinates: [[int]]) -> bool:
((x1, y1), (x2, y2)) = coordinates[:2]
for i in range(2, len(coordinates)):
(x, y) = coordinates[i]
if (y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1):
return False
return True |
#coding: utf-8
LEFT = 'left'
X = 'x'
RIGHT = 'right'
WIDTH = 'width'
MAX_WIDTH = 'max_width'
MIN_WIDTH = 'min_width'
INNER_WIDTH = 'inner_width'
CENTER = 'center'
TOP = 'top'
Y = 'y'
BOTTOM = 'bottom'
HEIGHT = 'height'
MAX_HEIGHT = 'max_height'
MIN_HEIGHT = 'min_height'
INNER_HEIGHT = 'inner_height'
MIDDLE = 'middle'
G... | left = 'left'
x = 'x'
right = 'right'
width = 'width'
max_width = 'max_width'
min_width = 'min_width'
inner_width = 'inner_width'
center = 'center'
top = 'top'
y = 'y'
bottom = 'bottom'
height = 'height'
max_height = 'max_height'
min_height = 'min_height'
inner_height = 'inner_height'
middle = 'middle'
grid_size = 'gri... |
class Solution:
def validPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]:
return self._validPalindrome(s, l + 1, r) or self._validPalindrome(s, l, r - 1)
l += 1
r -= 1
return True
... | class Solution:
def valid_palindrome(self, s: str) -> bool:
(l, r) = (0, len(s) - 1)
while l < r:
if s[l] != s[r]:
return self._validPalindrome(s, l + 1, r) or self._validPalindrome(s, l, r - 1)
l += 1
r -= 1
return True
def _valid_pa... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
ary = []
self.traverse(root, ary)
... | class Solution:
def is_valid_bst(self, root: Optional[TreeNode]) -> bool:
ary = []
self.traverse(root, ary)
return self.is_valid(ary)
def traverse(self, root, ary):
if root.left is not None:
self.traverse(root.left, ary)
ary.append(root.val)
if root.... |
def solution(N, P):
ans = []
for c in P:
ans.append('S' if c == 'E' else 'E')
return ''.join(ans)
def main():
T = int(input())
for t in range(T):
N, P = int(input()), input()
answer = solution(N, P)
print('Case #' + str(t+1) + ': ' + answer)
if __name__ == '__main... | def solution(N, P):
ans = []
for c in P:
ans.append('S' if c == 'E' else 'E')
return ''.join(ans)
def main():
t = int(input())
for t in range(T):
(n, p) = (int(input()), input())
answer = solution(N, P)
print('Case #' + str(t + 1) + ': ' + answer)
if __name__ == '__m... |
# https://codeforces.com/problemset/problem/1220/A
n, s = int(input()), input()
ones = s.count('n')
zeros = (n-(ones*3))//4
print(f"{'1 '*ones}{'0 '*zeros}") | (n, s) = (int(input()), input())
ones = s.count('n')
zeros = (n - ones * 3) // 4
print(f"{'1 ' * ones}{'0 ' * zeros}") |
# Reverse Nodes in k-Group: https://leetcode.com/problems/reverse-nodes-in-k-group/
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
# k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k the... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_k_group(self, head: ListNode, k: int) -> ListNode:
count = 0
cur = head
while count < k and cur:
cur = cur.next
count += 1
... |
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
h = {}
for i in s:
h[i] = h.get(i, 0) + 1
for j in t:
if h.get(j, 0) == 0:
return False
else:
h[j] -= 1
for k in h:
if h[k] >= 1:
... | class Solution:
def is_anagram(self, s: str, t: str) -> bool:
h = {}
for i in s:
h[i] = h.get(i, 0) + 1
for j in t:
if h.get(j, 0) == 0:
return False
else:
h[j] -= 1
for k in h:
if h[k] >= 1:
... |
#!/usr/bin/env python
# descriptors from http://www.winning-homebrew.com/beer-flavor-descriptors.html
aroma_basic = [
'malty', 'grainy', 'sweet',
'corn', 'hay', 'straw',
'cracker', 'bicuity',
'caramel', 'toast', 'roast',
'coffee', 'espresso', 'burnt',
'alcohol', 'tobacco', 'gunpowder',
'lea... | aroma_basic = ['malty', 'grainy', 'sweet', 'corn', 'hay', 'straw', 'cracker', 'bicuity', 'caramel', 'toast', 'roast', 'coffee', 'espresso', 'burnt', 'alcohol', 'tobacco', 'gunpowder', 'leather', 'pine', 'grass', 'dank', 'piney', 'floral', 'perfume']
aroma_dark_fruit = ['raisins', 'currant', 'plum', 'dates', 'prunes', '... |
def get_fact(i):
if i==1:
return 1
else:
return i*get_fact(i-1)
t=int(input())
for i in range(t):
x=int(input())
print(get_fact(x)) | def get_fact(i):
if i == 1:
return 1
else:
return i * get_fact(i - 1)
t = int(input())
for i in range(t):
x = int(input())
print(get_fact(x)) |
# /Users/dvs/Dropbox/Code/graphql-py/graphql/parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.5'
_lr_method = 'LALR'
_lr_signature = 'CDC982EBD105CCA216971D7DA325FA06'
_lr_action_items = {'BRACE_L':([0,8,10,11,21,23,24,25,26,27,28,29,30,31,32,33,36,37,50,51,52,58,59,61,67,68,70,... | _tabversion = '3.5'
_lr_method = 'LALR'
_lr_signature = 'CDC982EBD105CCA216971D7DA325FA06'
_lr_action_items = {'BRACE_L': ([0, 8, 10, 11, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 36, 37, 50, 51, 52, 58, 59, 61, 67, 68, 70, 71, 73, 80, 81, 82, 83, 87, 90, 91, 92, 96, 98, 99, 103, 107, 108, 109, 110, 111, 112, 113... |
a = list(map(int, input().split()))
if sum(a) < 22:
print("win")
else:
print("bust")
| a = list(map(int, input().split()))
if sum(a) < 22:
print('win')
else:
print('bust') |
# for holding settings for use later
class IndividualSetting:
settingkey = ""
settingvalue = ""
| class Individualsetting:
settingkey = ''
settingvalue = '' |
#!/usr/bin/env python3
class Evaluate:
def __init__(self):
self.formula = []
self.result = ''
self.error = False
def eval(self, expression):
if (self.percent(expression)):
return self.result
if (self.sum(expression)):
return self.result
... | class Evaluate:
def __init__(self):
self.formula = []
self.result = ''
self.error = False
def eval(self, expression):
if self.percent(expression):
return self.result
if self.sum(expression):
return self.result
if self.substract(expression... |
def covert(df, drop, rename, inflow_source):
print(df)
result = df.copy()
outflow = []
inflow = []
for _, row in df.iterrows():
if row.get(inflow_source) >= 0:
inflow.append(row.get(inflow_source))
outflow.append(0)
else:
inflow.append(0)
... | def covert(df, drop, rename, inflow_source):
print(df)
result = df.copy()
outflow = []
inflow = []
for (_, row) in df.iterrows():
if row.get(inflow_source) >= 0:
inflow.append(row.get(inflow_source))
outflow.append(0)
else:
inflow.append(0)
... |
#-*-python-*-
def guild_python_workspace():
native.new_http_archive(
name = "org_pyyaml",
build_file = "//third-party:pyyaml.BUILD",
urls = [
"https://pypi.python.org/packages/4a/85/db5a2df477072b2902b0eb892feb37d88ac635d36245a72a6a69b23b383a/PyYAML-3.12.tar.gz",
],
... | def guild_python_workspace():
native.new_http_archive(name='org_pyyaml', build_file='//third-party:pyyaml.BUILD', urls=['https://pypi.python.org/packages/4a/85/db5a2df477072b2902b0eb892feb37d88ac635d36245a72a6a69b23b383a/PyYAML-3.12.tar.gz'], strip_prefix='PyYAML-3.12', sha256='592766c6303207a20efc445587778322d7f73... |
#
# PySNMP MIB module ENGENIUS-CLIENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENGENIUS-CLIENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:02:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ... |
# Habibu-R-ahman
# 7th Jan, 2021
a = float(input())
salary = money = percentage = None
if a <= 400:
salary = a * 1.15
percentage = 15
elif a <= 800:
salary = a * 1.12
percentage = 12
elif a <= 1200:
salary = a * 1.10
percentage = 10
elif a <= 2000:
salary = a * 1.07
percentage = 7
else... | a = float(input())
salary = money = percentage = None
if a <= 400:
salary = a * 1.15
percentage = 15
elif a <= 800:
salary = a * 1.12
percentage = 12
elif a <= 1200:
salary = a * 1.1
percentage = 10
elif a <= 2000:
salary = a * 1.07
percentage = 7
else:
salary = a * 1.04
percenta... |
def arbitage(plen):
lst1=list(permutations(lst,plen))
for j in [[0]+list(i)+[0] for i in lst1]:
val=1
length=len(j)
print([x+1 for x in j])
index=0
for k in j:
if index+1>=length:
break
print("index:{}, index+1:{},val:{}".format(j[i... | def arbitage(plen):
lst1 = list(permutations(lst, plen))
for j in [[0] + list(i) + [0] for i in lst1]:
val = 1
length = len(j)
print([x + 1 for x in j])
index = 0
for k in j:
if index + 1 >= length:
break
print('index:{}, index+1:{}... |
class Http:
def __init__(self, session):
self.session = session
async def download(self, url: str):
async with self.session.get(url, timeout=10) as res:
if res.status == 200:
return await res.read()
else:
return None
async def get_hea... | class Http:
def __init__(self, session):
self.session = session
async def download(self, url: str):
async with self.session.get(url, timeout=10) as res:
if res.status == 200:
return await res.read()
else:
return None
async def get_he... |
# Pretty lame athlete model
LT = 160
REST_HR = 50
MAX_HR = 175
| lt = 160
rest_hr = 50
max_hr = 175 |
class User:
def __init__(self, id, first_name, last_name, email, account_creation_date):
self.id = id
self.first_name = first_name
self.last_name = last_name
self.email = email
self.account_creation_date = account_creation_date | class User:
def __init__(self, id, first_name, last_name, email, account_creation_date):
self.id = id
self.first_name = first_name
self.last_name = last_name
self.email = email
self.account_creation_date = account_creation_date |
frase = 'Curso em video Python'
print(frase[5::2])
print('''jfafj aj fjaljsfkjasj fkasjfkaj sfjsajfljslkjjf
a fsjdfjs flasjfkldjfdjsfjasjfjaskjfsjfk sdkf
sjfsd fskjfs asfjlkds fjsf sdjflksjfslfs
s fslfjklsdjfsjfjlsjfklsjkfksldfk dsjfsdf''')
| frase = 'Curso em video Python'
print(frase[5::2])
print('jfafj aj fjaljsfkjasj fkasjfkaj sfjsajfljslkjjf\na fsjdfjs flasjfkldjfdjsfjasjfjaskjfsjfk sdkf \nsjfsd fskjfs asfjlkds fjsf sdjflksjfslfs\ns fslfjklsdjfsjfjlsjfklsjkfksldfk dsjfsdf') |
BRANCHES = {
'AdditiveExpression' : {
"!" : ['MultiplicativeExpression',
'_Add_Sub_MultiplicativeExpression_Star'],
"(" : ['MultiplicativeExpression',
'_Add_Sub_MultiplicativeExpression_Star'],
"+" : ['MultiplicativeExpression',
'_Add_Sub_MultiplicativeExpression_Star'],
... | branches = {'AdditiveExpression': {'!': ['MultiplicativeExpression', '_Add_Sub_MultiplicativeExpression_Star'], '(': ['MultiplicativeExpression', '_Add_Sub_MultiplicativeExpression_Star'], '+': ['MultiplicativeExpression', '_Add_Sub_MultiplicativeExpression_Star'], '-': ['MultiplicativeExpression', '_Add_Sub_Multiplica... |
class Solution:
def minSteps(self, s: str, t: str) -> int:
res = 0
dic = {}
for _ in s:
if _ in dic:
dic[_] += 1
else:
dic[_] = 1
for _ in t:
if _ in dic:
dic[_] -= 1
if not dic[_]:
... | class Solution:
def min_steps(self, s: str, t: str) -> int:
res = 0
dic = {}
for _ in s:
if _ in dic:
dic[_] += 1
else:
dic[_] = 1
for _ in t:
if _ in dic:
dic[_] -= 1
if not dic[_]:
... |
# * Daily Coding Problem August 25 2020
# * [Easy] -- Google
# * In linear algebra, a Toeplitz matrix is one in which the elements on
# * any given diagonal from top left to bottom right are identical.
# * Write a program to determine whether a given input is a Toeplitz matrix.
def checkDiagonal(mat, i, j):
r... | def check_diagonal(mat, i, j):
res = mat[i][j]
i += 1
j += 1
rows = len(mat)
cols = len(mat[0])
while i < rows and j < cols:
if mat[i][j] != res:
return False
i += 1
j += 1
return True
def is_toeplitz(mat):
rows = len(mat)
cols = len(mat[0])
f... |
# Initialize sum
sum = 0
# Add 0.01, 0.02, ..., 0.99, 1 to sum
i = 0.01
while i <= 1.0:
sum += i
i = i + 0.01
# Display result
print("The sum is", sum) | sum = 0
i = 0.01
while i <= 1.0:
sum += i
i = i + 0.01
print('The sum is', sum) |
print('-' * 15)
medida = float(input('Digite uma distancia em metros:'))
centimetros = medida * 100
milimetros = medida * 1000
print('A media de {} corresponde a {:.0f} e {:.0f}'.format(medida, centimetros, milimetros)) | print('-' * 15)
medida = float(input('Digite uma distancia em metros:'))
centimetros = medida * 100
milimetros = medida * 1000
print('A media de {} corresponde a {:.0f} e {:.0f}'.format(medida, centimetros, milimetros)) |
def exponentiation(base, exponent):
if isinstance(base, str) or isinstance(exponent, str):
return "Trying to use strings in calculator"
solution = float(base) ** exponent
return solution
| def exponentiation(base, exponent):
if isinstance(base, str) or isinstance(exponent, str):
return 'Trying to use strings in calculator'
solution = float(base) ** exponent
return solution |
# Curbrock's Revenge (5501)
SABITRAMA = 1061005 # NPC ID
CURBROCKS_HIDEOUT_VER3 = 600050020 # MAP ID
CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 # MAP ID 3
sm.setSpeakerID(SABITRAMA)
if sm.getFieldID() == CURBROCKS_ESCAPE_ROUTE_VER3:
sm.sendSayOkay("Please leave before reaccepting this quest again.")
else:
sm.s... | sabitrama = 1061005
curbrocks_hideout_ver3 = 600050020
curbrocks_escape_route_ver3 = 600050050
sm.setSpeakerID(SABITRAMA)
if sm.getFieldID() == CURBROCKS_ESCAPE_ROUTE_VER3:
sm.sendSayOkay('Please leave before reaccepting this quest again.')
else:
sm.sendNext('The rumors are true. Curbrock has returned, and the ... |
#
# PySNMP MIB module CISCOSB-SECSD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-SECSD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:06:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
#
# @lc app=leetcode id=680 lang=python3
#
# [680] Valid Palindrome II
#
# @lc code=start
class Solution:
def validPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]:
pre, las = s[l:r], s[l + 1:r + 1]
return pre[::-1] == p... | class Solution:
def valid_palindrome(self, s: str) -> bool:
(l, r) = (0, len(s) - 1)
while l < r:
if s[l] != s[r]:
(pre, las) = (s[l:r], s[l + 1:r + 1])
return pre[::-1] == pre or las[::-1] == las
else:
l += 1
r... |
# Space/Time O(n), O(nLogn)
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# Sort intervals
intervals.sort(key=lambda x:x[0])
# start merged list and go through intervals
merged = [intervals[0]]
for si, ei in inter... | class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for (si, ei) in intervals:
(sm, em) = merged[-1]
if si <= em:
merged[-1] = (sm, max(em, ei))
else:
... |
start_range = int(input())
stop_range = int(input())
for x in range(start_range, stop_range + 1):
print(f"{(chr(x))}", end=" ") | start_range = int(input())
stop_range = int(input())
for x in range(start_range, stop_range + 1):
print(f'{chr(x)}', end=' ') |
def brackets(sequence: str) -> bool:
brackets_dict = {"]": "[", ")": "(", "}": "{", ">": "<"}
stack = []
for symbol in sequence:
if symbol in "[({<":
stack.append(symbol)
elif symbol in "])}>":
if brackets_dict[symbol] != stack.pop():
return False
... | def brackets(sequence: str) -> bool:
brackets_dict = {']': '[', ')': '(', '}': '{', '>': '<'}
stack = []
for symbol in sequence:
if symbol in '[({<':
stack.append(symbol)
elif symbol in '])}>':
if brackets_dict[symbol] != stack.pop():
return False
... |
def merge(left, right):
m = []
i,j = 0,0
k = 0
while i < len(left) and j < len(right):
# print(left,right,left[i], right[j])
if left[i] <= right[j]:
m.append(left[i])
i+=1
else:
m.append(right[j])
j +=1
if i < len(le... | def merge(left, right):
m = []
(i, j) = (0, 0)
k = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
m.append(left[i])
i += 1
else:
m.append(right[j])
j += 1
if i < len(left):
m.extend(left[i:])
if j < len(ri... |
# T Y P E O F V E R B S
def pert_subjective_verbs(texts_tokens):
total_verbs = 0
total_subj_verbs = 0
return
def pert_report_verbs(text_tokens):
return
def pert_factive_verbs(text_tokens):
return
def pert_imperative_commands(text_tokens):
return | def pert_subjective_verbs(texts_tokens):
total_verbs = 0
total_subj_verbs = 0
return
def pert_report_verbs(text_tokens):
return
def pert_factive_verbs(text_tokens):
return
def pert_imperative_commands(text_tokens):
return |
load("@rules_python//python:defs.bzl", "py_test")
pycoverage_requirements = [
"//tools/pycoverage",
]
def pycoverage(name, deps):
if not name or not deps:
fail("Arguments 'name' and 'deps' are required")
py_test(
name = name,
main = "pycoverage_runner.py",
srcs = ["//tools... | load('@rules_python//python:defs.bzl', 'py_test')
pycoverage_requirements = ['//tools/pycoverage']
def pycoverage(name, deps):
if not name or not deps:
fail("Arguments 'name' and 'deps' are required")
py_test(name=name, main='pycoverage_runner.py', srcs=['//tools/pycoverage:pycoverage_runner'], imports... |
filename = "test2.txt"
tree = [None]*16
with open(filename) as f:
line = f.readline().strip().strip('[]')
for c in line:
if c == ',':
continue
for line in f:
n = line.strip().strip('[]')
print(n) | filename = 'test2.txt'
tree = [None] * 16
with open(filename) as f:
line = f.readline().strip().strip('[]')
for c in line:
if c == ',':
continue
for line in f:
n = line.strip().strip('[]')
print(n) |
class Solution:
def searchMatrix(self, matrix, target):
i, j, r = 0, len(matrix[0]) - 1, len(matrix)
while i < r and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
j -= 1
elif matrix[i][j] < target:
... | class Solution:
def search_matrix(self, matrix, target):
(i, j, r) = (0, len(matrix[0]) - 1, len(matrix))
while i < r and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
j -= 1
elif matrix[i][j] < target:... |
def setUpModule() -> None:
print("[Module sserender Test Start]")
def tearDownModule() -> None:
print("[Module sserender Test End]") | def set_up_module() -> None:
print('[Module sserender Test Start]')
def tear_down_module() -> None:
print('[Module sserender Test End]') |
print('begin program')
# This program says hello and asks for my name.
print('Hello, World!')
print('What is your name?')
myName = input()
print('It is good to meet you, ' + myName)
print('end program')
| print('begin program')
print('Hello, World!')
print('What is your name?')
my_name = input()
print('It is good to meet you, ' + myName)
print('end program') |
#!/usr/bin/env python
'''
primes.py
@author: Lorenzo Cipriani <lorenzo1974@gmail.com>
@contact: https://www.linkedin.com/in/lorenzocipriani
@since: 2017-10-23
@see:
'''
primesToFind = 1000000
num = 0
found = 0
def isPrime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0: return Fa... | """
primes.py
@author: Lorenzo Cipriani <lorenzo1974@gmail.com>
@contact: https://www.linkedin.com/in/lorenzocipriani
@since: 2017-10-23
@see:
"""
primes_to_find = 1000000
num = 0
found = 0
def is_prime(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
return False
... |
class ExportingTemplate():
def __init__(self, exporting_template_name=None, channel=None, target_sample_rate=None, duration=None, created_date=None, modified_date=None, id=None):
self.exporting_template_name = exporting_template_name
self.channel = channel
self.target_sample_rate = target_sa... | class Exportingtemplate:
def __init__(self, exporting_template_name=None, channel=None, target_sample_rate=None, duration=None, created_date=None, modified_date=None, id=None):
self.exporting_template_name = exporting_template_name
self.channel = channel
self.target_sample_rate = target_sam... |
# Given an array of strings strs, group the anagrams together. You can return the answer in any order.
# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
# Example 1:
# Input: strs = ["eat","tea","tan","ate","nat... | class Solution:
def group_anagrams(self, strs):
result = []
lst = []
for i in strs:
a = sorted(i)
if a in lst:
x = lst.index(a)
result[x].append(i)
else:
lst.append(a)
result.append([i])
... |
instructions = []
for line in open('input.txt', 'r').readlines():
readline = line.strip()
instructions.append((readline[0], int(readline[1:])))
directions = {
'E': [1, 0],
'S': [0, -1],
'W': [-1, 0],
'N': [0, 1],
}
direction = 'E'
x, y = 0, 0
for action, value in instructions:
if action in [*directions]:
x ... | instructions = []
for line in open('input.txt', 'r').readlines():
readline = line.strip()
instructions.append((readline[0], int(readline[1:])))
directions = {'E': [1, 0], 'S': [0, -1], 'W': [-1, 0], 'N': [0, 1]}
direction = 'E'
(x, y) = (0, 0)
for (action, value) in instructions:
if action in [*directions]:... |
a = [ 1, 2, 3, 4, 5 ]
print(a)
print(a[0])
for i in range(len(a)):
print(a[i])
a.append(10)
a.append(20)
print(a) | a = [1, 2, 3, 4, 5]
print(a)
print(a[0])
for i in range(len(a)):
print(a[i])
a.append(10)
a.append(20)
print(a) |
def buble_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
nums[i], nums[i - 1] = nums[i - 1], nums[i]
def check_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
return False
return True
def main():
count_nums = int(input()... | def buble_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
(nums[i], nums[i - 1]) = (nums[i - 1], nums[i])
def check_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
return False
return True
def main():
count_nums = int(inpu... |
def temperature_statistics(t):
mean = sum(t)/len(t)
return mean, (sum((val-mean)**2 for val in t)/len(t))**0.5
print(temperature_statistics([4.4, 4.2, 7.0, 12.9, 18.5, 23.5, 26.4, 26.3, 22.5, 16.6, 11.2, 7.3])) | def temperature_statistics(t):
mean = sum(t) / len(t)
return (mean, (sum(((val - mean) ** 2 for val in t)) / len(t)) ** 0.5)
print(temperature_statistics([4.4, 4.2, 7.0, 12.9, 18.5, 23.5, 26.4, 26.3, 22.5, 16.6, 11.2, 7.3])) |
# Helper function to print out relation between losses and network parameters
# loss_list given as: [(name, loss_variable), ...]
# named_parameters_list using pytorch function named_parameters(): [(name, network.named_parameters()), ...]
def print_loss_params_relation(loss_list, named_parameters_list):
loss_variabl... | def print_loss_params_relation(loss_list, named_parameters_list):
loss_variables = {}
for (name, loss) in loss_list:
if loss.grad_fn is None:
variables_ = []
else:
def recursive_sub(loss):
r = []
if hasattr(loss, 'next_functions'):
... |
# %% [287. Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for i, v in enumerate(nums, 1):
if v in nums[i:]:
return v
| class Solution:
def find_duplicate(self, nums: List[int]) -> int:
for (i, v) in enumerate(nums, 1):
if v in nums[i:]:
return v |
def staircase(n):
asteriscos = 1
# Write your code here
for espacios in range(n, 0, -1):
for i in range (espacios):
print(' ', end='')
for j in range(asteriscos):
print('*', end='')
print()
asteriscos+=2
staircase(7)
| def staircase(n):
asteriscos = 1
for espacios in range(n, 0, -1):
for i in range(espacios):
print(' ', end='')
for j in range(asteriscos):
print('*', end='')
print()
asteriscos += 2
staircase(7) |
#!/usr/bin/env python
class Host(object):
def __init__(self, name, groups,region, image, tags, size, meta=None):
self.name = name
self.groups = groups
self.meta = meta or {}
self.region = region
self.image = image
self.tags = tags
self.size = size
swifty_ho... | class Host(object):
def __init__(self, name, groups, region, image, tags, size, meta=None):
self.name = name
self.groups = groups
self.meta = meta or {}
self.region = region
self.image = image
self.tags = tags
self.size = size
swifty_hosts = [host(name='swift... |
'''
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: 1
'''
#Approach 1: Priority Queues
'''
Algorithm
A... | """
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: 1
"""
"\nAlgorithm\n\nA) Sort the given meetings by t... |
#!/usr/bin/env python3.5
#-*- coding: utf-8 -*-
def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
main()
| def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
main() |
class Libro:
def __init__(self, paginas, tapa,nombre, autor, genero, isbn):
self.paginas = paginas
self.tapa = tapa
self.nombre= nombre
self.autor = autor
self.genero = genero
self.isbn = isbn
def set_nombre(self,nombre):
self.nombre = nombre
def set... | class Libro:
def __init__(self, paginas, tapa, nombre, autor, genero, isbn):
self.paginas = paginas
self.tapa = tapa
self.nombre = nombre
self.autor = autor
self.genero = genero
self.isbn = isbn
def set_nombre(self, nombre):
self.nombre = nombre
def... |
#
# @lc app=leetcode id=68 lang=python3
#
# [68] Text Justification
#
class Solution:
def split(self, words: List[str], maxWidth: int) -> List[List[str]]:
if not words:
return []
lines, cur_len = [[words[0]]], len(words[0])
for w in words[1:]:
if cur_len + 1 + len(w) ... | class Solution:
def split(self, words: List[str], maxWidth: int) -> List[List[str]]:
if not words:
return []
(lines, cur_len) = ([[words[0]]], len(words[0]))
for w in words[1:]:
if cur_len + 1 + len(w) <= maxWidth:
lines[-1].append(w)
... |
def update_data(hyper_params):
return dict(
train=dict(
samples_per_gpu=hyper_params['batch_size'],
workers_per_gpu=hyper_params['workers_per_gpu'],
dataset=dict(
root_dir=hyper_params['dataset_root'],
cifar_type=hyper_params['dataset_name'... | def update_data(hyper_params):
return dict(train=dict(samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict(root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], noise_mode=hyper_params['noise_mode'], noise_ratio=hyper_params['noise_ratio... |
class Person:
def __init__(self, name, age=21, gender='unspecified',
occupation='unspecified'):
self.name = name
self.gender = gender
self.occupation = occupation
if age >= 0 and age <= 120:
self.age = age
else:
self.age = 21
def... | class Person:
def __init__(self, name, age=21, gender='unspecified', occupation='unspecified'):
self.name = name
self.gender = gender
self.occupation = occupation
if age >= 0 and age <= 120:
self.age = age
else:
self.age = 21
def greets(self, gre... |
def obj_sort_by_lambda(obj_list, lmbd):
new_obj_list = obj_list.copy()
new_obj_list.sort(key=lmbd)
return new_obj_list
def obj_sort_by_property_name(obj_list, prop_name):
return obj_sort_by_lambda(obj_list, lambda x:getattr(x, prop_name))
def obj_list_decrypt(obj_list, enc):
new_obj_list = []
... | def obj_sort_by_lambda(obj_list, lmbd):
new_obj_list = obj_list.copy()
new_obj_list.sort(key=lmbd)
return new_obj_list
def obj_sort_by_property_name(obj_list, prop_name):
return obj_sort_by_lambda(obj_list, lambda x: getattr(x, prop_name))
def obj_list_decrypt(obj_list, enc):
new_obj_list = []
... |
class InvalidUrl(Exception):
pass
class UnableToGetPage(Exception):
pass
class UnableToGetUploadTime(Exception):
pass
class UnableToGetApproximateNum(Exception):
pass
| class Invalidurl(Exception):
pass
class Unabletogetpage(Exception):
pass
class Unabletogetuploadtime(Exception):
pass
class Unabletogetapproximatenum(Exception):
pass |
# *******************************************************************************************
# *******************************************************************************************
#
# Name : error.py
# Purpose : Error class
# Date : 13th November 2021
# Author : Paul Robson (paul@robsons.org.uk)
#
# ***... | class Hplexception(Exception):
def __str__(self):
msg = Exception.__str__(self)
return msg if HPLException.LINE <= 0 else '{0} ({1}:{2})'.format(msg, HPLException.FILE, HPLException.LINE)
HPLException.FILE = None
HPLException.LINE = 0
if __name__ == '__main__':
x = hpl_exception('Error !!')
... |
# coding=utf-8
worker_thread_pool = None
key_loading_thread_pool = None
key_holder = None
is_debug = False
is_debug_requests = False
is_no_validate = False
is_only_validate_key = False
is_override = False
is_preview_filename = False
is_resize = False
thread_num = 1
src_dir = None
dest_dir = None
filename_pattern =... | worker_thread_pool = None
key_loading_thread_pool = None
key_holder = None
is_debug = False
is_debug_requests = False
is_no_validate = False
is_only_validate_key = False
is_override = False
is_preview_filename = False
is_resize = False
thread_num = 1
src_dir = None
dest_dir = None
filename_pattern = None
filename_repla... |
from_ = 1
to_ = 999901
# to_ = 1
output_file = open("result.txt", "w", encoding="utf-8")
for i in range(from_, to_ + 1, 100):
input_file = open("allTags/" + str(i) + ".txt", "r", encoding="utf-8")
data = input_file.read()
ind = 0
for j in range(100):
ind = data.find("class=\"i-tag\"", ind)
... | from_ = 1
to_ = 999901
output_file = open('result.txt', 'w', encoding='utf-8')
for i in range(from_, to_ + 1, 100):
input_file = open('allTags/' + str(i) + '.txt', 'r', encoding='utf-8')
data = input_file.read()
ind = 0
for j in range(100):
ind = data.find('class="i-tag"', ind)
data = da... |
#!/usr/bin/env python3
''' In this question , we are going to find the longest common substring, among two given substrings. in order to solve this question
we will be making use of dynamic programming. so we will create a matrix with all 0s in the initial row and column
Step 1: we need to initialise a matrix with siz... | """ In this question , we are going to find the longest common substring, among two given substrings. in order to solve this question
we will be making use of dynamic programming. so we will create a matrix with all 0s in the initial row and column
Step 1: we need to initialise a matrix with size len(String)+1, len(st... |
'''
Author : Govind Patidar
DateTime : 10/07/2020 11:30AM
File : AllPageLocators
'''
class AllPageLocators():
def __init__(self, driver):
'''
:param driver:
'''
self.driver = driver
'''Home page locator'''
# get XPATH current temperature text
text_curr_temp = '... | """
Author : Govind Patidar
DateTime : 10/07/2020 11:30AM
File : AllPageLocators
"""
class Allpagelocators:
def __init__(self, driver):
"""
:param driver:
"""
self.driver = driver
'Home page locator'
text_curr_temp = '/html/body/div/div[1]/h2'
curr_temp = 'tempera... |
word = input()
out = ''
prev = ''
# remove same letters which are the same as the previous
for x in word:
if x != prev:
out+=x
prev = x
print(out)
| word = input()
out = ''
prev = ''
for x in word:
if x != prev:
out += x
prev = x
print(out) |
#
# PySNMP MIB module TPLINK-IPADDR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-IPADDR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:17:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, single_value_constraint, constraints_union, value_size_constraint) ... |
#Programa que leia um nome completo e diga o primeiro e ultimo nome
nome = input('Digite seu nome completo: ').title()
splt = nome.split()
print(splt[0],splt[-1]) | nome = input('Digite seu nome completo: ').title()
splt = nome.split()
print(splt[0], splt[-1]) |
def binary_search(ary, tar):
head = 0
tail = len(ary) - 1
found = False
while head <= tail and not found:
mid = (head + tail) / 2
if ary[mid] == tar:
found = True
elif ary[mid] < tar:
head = mid + 1
elif ary[mid] > tar:
tail = mid - 1... | def binary_search(ary, tar):
head = 0
tail = len(ary) - 1
found = False
while head <= tail and (not found):
mid = (head + tail) / 2
if ary[mid] == tar:
found = True
elif ary[mid] < tar:
head = mid + 1
elif ary[mid] > tar:
tail = mid - 1... |
# example solution.
# You are not expected to make a nice plotting function,
# you can simply call plt.imshow a number of times and observe
print(faces.DESCR) # this shows there are 40 classes, 10 samples per class
print(faces.target) #the targets i.e. classes
print(np.unique(faces.target).shape) # another way to se... | print(faces.DESCR)
print(faces.target)
print(np.unique(faces.target).shape)
x = faces.images
y = faces.target
fig = plt.figure(figsize=(16, 5))
idxs = [0, 1, 2, 11, 12, 13, 40, 41]
for (i, k) in enumerate(idxs):
ax = fig.add_subplot(2, 4, i + 1)
ax.imshow(X[k])
ax.set_title(f'target={y[k]}') |
#python 3.5.2
def areAnagram(firstWord, secondWord):
firstList = list(firstWord)
secondList = list(secondWord)
result = True
if len(firstList) == len(secondList) and result:
#Sort both list alphabetically
firstList.sort()
secondList.sort()
i = 0
length =... | def are_anagram(firstWord, secondWord):
first_list = list(firstWord)
second_list = list(secondWord)
result = True
if len(firstList) == len(secondList) and result:
firstList.sort()
secondList.sort()
i = 0
length = len(firstList)
while i < length:
if fir... |
#!/bin/zsh
'''
Regex Search
Write a program that opens all .txt files in a folder and searches for any line
that matches a user-supplied regular expression. The results should be printed to the screen.
''' | """
Regex Search
Write a program that opens all .txt files in a folder and searches for any line
that matches a user-supplied regular expression. The results should be printed to the screen.
""" |
''' Q1. Write a python code for creating a password for E-Aadhar card. The details used are the
first 4 letters of your name, date and month of your birth. The task is to generate a password
with the lambda function and display it.'''
name = input("Input your name (as on your Aadhar)\n")
dob = input("Please enter you... | """ Q1. Write a python code for creating a password for E-Aadhar card. The details used are the
first 4 letters of your name, date and month of your birth. The task is to generate a password
with the lambda function and display it."""
name = input('Input your name (as on your Aadhar)\n')
dob = input("Please enter your ... |
# !/usr/bin/env python
# coding: utf-8
'''
Description:
'''
| """
Description:
""" |
def getSampleMetadata(catalogName, tagName, digest):
return {
'schemaVersion': 2,
'mediaType': 'application/vnd.docker.distribution.manifest.v2+json',
'config': {
'mediaType': 'application/vnd.docker.container.image.v1+json',
'size': 1111,
'digest': digest
},
'layers': [
{... | def get_sample_metadata(catalogName, tagName, digest):
return {'schemaVersion': 2, 'mediaType': 'application/vnd.docker.distribution.manifest.v2+json', 'config': {'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 1111, 'digest': digest}, 'layers': [{'mediaType': 'application/vnd.docker.image.ro... |
class Solution:
def count(self, s, target):
ans = 0
for i in s:
if i == target:
ans += 1
return ans
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0 for i in range(n+1)] for j in range(m+1)]
for s in strs:
zer... | class Solution:
def count(self, s, target):
ans = 0
for i in s:
if i == target:
ans += 1
return ans
def find_max_form(self, strs: List[str], m: int, n: int) -> int:
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
for s in strs:
... |
# remove nth node from end
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# brute
# create a new linked list without that element
# Time O(n)
# Space O(n)
# optimal
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.n... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode:
if head.next == None:
return None
start = list_node()
start.next = head
slow = f... |
def readFile(fileName):
try:
with open(fileName,'r') as f:
print (f.read())
except FileNotFoundError:
print (f'File {fileName} is not found')
readFile('1.txt')
readFile('2.txt')
readFile('3.txt')
| def read_file(fileName):
try:
with open(fileName, 'r') as f:
print(f.read())
except FileNotFoundError:
print(f'File {fileName} is not found')
read_file('1.txt')
read_file('2.txt')
read_file('3.txt') |
'''
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Examples:
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
Notes:
* The number can be negative already, in which case no change is required.
* Zero (0... | """
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Examples:
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
Notes:
* The number can be negative already, in which case no change is required.
* Zero (0... |
cards = {'SPADE' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'],
'HEART' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'],
'CLUB' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'],
'DIAMOND' : ['1', '2', '3', '4', '5', '6',... | cards = {'SPADE': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'HEART': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'CLUB': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'DIAMOND': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.