content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Link to problem : https://leetcode.com/problems/remove-element/
class Solution:
def removeElement(self, nums ,val):
count = 0
for i in range(len(nums)):
if(nums[i] != val):
nums[count] = nums[i]
count += 1
return count | class Solution:
def remove_element(self, nums, val):
count = 0
for i in range(len(nums)):
if nums[i] != val:
nums[count] = nums[i]
count += 1
return count |
while True:
n = int(input())
if not n: break
s = 0
for i in range(n):
s += [int(x) for x in input().split()][1] // 2
print(s//2)
| while True:
n = int(input())
if not n:
break
s = 0
for i in range(n):
s += [int(x) for x in input().split()][1] // 2
print(s // 2) |
new_minimum_detection = input("What is the minimum confidence?: ")
with open('object_detection_webcam.py', 'r') as file:
lines = file.readlines()
for line in lines:
if line[0:18] == ' min_detection_':
line = ' min_detection_confidence = '+new_minimum_detection+' ###EDITED BY SETTINGS PROGRAM###\n'
print(line)
#for line in lines:
#print(line, end='') | new_minimum_detection = input('What is the minimum confidence?: ')
with open('object_detection_webcam.py', 'r') as file:
lines = file.readlines()
for line in lines:
if line[0:18] == ' min_detection_':
line = ' min_detection_confidence = ' + new_minimum_detection + ' ###EDITED BY SETTINGS PROGRAM###\n'
print(line) |
# class Student(object):
# def __init__(self, name, score):
# self.name = name
# self.score = score
# def print_score(self):
# print('%s: %s' % (self.name, self.score))
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
fyp = Student('fyp', 59)
print("fyp===>", fyp)
print("fyp===>", fyp.name)
print("fyp===>", fyp.score)
| class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
fyp = student('fyp', 59)
print('fyp===>', fyp)
print('fyp===>', fyp.name)
print('fyp===>', fyp.score) |
#
# 359. Logger Rate Limiter
#
# Q: https://leetcode.com/problems/logger-rate-limiter/
# A: https://leetcode.com/problems/logger-rate-limiter/discuss/473779/Javascript-Python3-C%2B%2B-hash-table
#
class Logger:
def __init__(self):
self.m = {}
def shouldPrintMessage(self, t: int, s: str) -> bool:
m = self.m
if not s in m or 10 <= t - m[s]:
m[s] = t
return True
return False
| class Logger:
def __init__(self):
self.m = {}
def should_print_message(self, t: int, s: str) -> bool:
m = self.m
if not s in m or 10 <= t - m[s]:
m[s] = t
return True
return False |
for t in range(int(input())):
a=int(input())
s=input()
L=[]
for i in range(0,a*8,8):
b=s[i:i+8]
k=0
for i in range(8):
if b[i] == 'I':
k += 2**(7-i)
L.append(k)
print("Case #"+str(t+1),end=": ")
for i in L:
print(chr(i),end="")
print() | for t in range(int(input())):
a = int(input())
s = input()
l = []
for i in range(0, a * 8, 8):
b = s[i:i + 8]
k = 0
for i in range(8):
if b[i] == 'I':
k += 2 ** (7 - i)
L.append(k)
print('Case #' + str(t + 1), end=': ')
for i in L:
print(chr(i), end='')
print() |
# A program to display a number of seconds in other units
data = 75475984
changedData = data
years = 0
days = 0
hours = 0
minutes = 0
seconds = 0
now = 0
if data == 0:
now = 1
for i in range(100):
if changedData >= 31556952:
years += 1
changedData -= 31556952
for i in range(365):
if changedData >= 86400:
days += 1
changedData -= 86400
for i in range(24):
if changedData >= 3600:
hours += 1
changedData -= 3600
for i in range(60):
if changedData >= 60:
minutes += 1
changedData -= 60
for i in range(60):
if changedData >= 1:
seconds += 1
changedData -= 1
if years or days or hours or minutes or seconds >= 1:
print("Years: " + str(years) + "\nDays: " + str(days) + "\nHours: " + str(hours) + "\nMinutes: " + str(minutes) +
"\nSeconds: " + str(seconds))
elif now == 1:
print("Now!")
else:
print("Something Went Wrong")
| data = 75475984
changed_data = data
years = 0
days = 0
hours = 0
minutes = 0
seconds = 0
now = 0
if data == 0:
now = 1
for i in range(100):
if changedData >= 31556952:
years += 1
changed_data -= 31556952
for i in range(365):
if changedData >= 86400:
days += 1
changed_data -= 86400
for i in range(24):
if changedData >= 3600:
hours += 1
changed_data -= 3600
for i in range(60):
if changedData >= 60:
minutes += 1
changed_data -= 60
for i in range(60):
if changedData >= 1:
seconds += 1
changed_data -= 1
if years or days or hours or minutes or (seconds >= 1):
print('Years: ' + str(years) + '\nDays: ' + str(days) + '\nHours: ' + str(hours) + '\nMinutes: ' + str(minutes) + '\nSeconds: ' + str(seconds))
elif now == 1:
print('Now!')
else:
print('Something Went Wrong') |
nombre=input("nombre del archivo? ")
f=open(nombre,"r")
palabras=[]
for linea in f:
palabras.extend(linea.split())
print(palabras)
| nombre = input('nombre del archivo? ')
f = open(nombre, 'r')
palabras = []
for linea in f:
palabras.extend(linea.split())
print(palabras) |
# %% [278. First Bad Version](https://leetcode.com/problems/first-bad-version/)
class Solution:
def firstBadVersion(self, n):
lo, up = 0, n
while up - lo > 1:
mid = (lo + up) // 2
if isBadVersion(mid):
up = mid
else:
lo = mid
return up
| class Solution:
def first_bad_version(self, n):
(lo, up) = (0, n)
while up - lo > 1:
mid = (lo + up) // 2
if is_bad_version(mid):
up = mid
else:
lo = mid
return up |
# dataset settings
data_root = 'data/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (256, 512)
train_pipeline = [
dict(type='LoadImageFromFile_Semi'),
dict(type='LoadAnnotations_Semi'),
dict(type='RandomCrop_Semi', crop_size=crop_size, cat_max_ratio=0.75),
dict(type='RandomFlip_Semi', prob=0.5),
dict(type='PhotoMetricDistortion_Semi'),
dict(type='Normalize_Semi', **img_norm_cfg),
dict(type='DefaultFormatBundle_Semi'),
dict(
type='Collect',
keys=['img_v0_0', 'img_v0_1', 'img_v0_1_s', 'img_v1_0', 'img_v1_1', 'img_v1_1_s', 'gt'],
meta_keys=(),
),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1024, 512),
# img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75],
flip=False,
transforms=[
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
],
),
]
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
train=dict(
type='CityscapesSemiDataset',
data_root=data_root,
img_dir='cityscapes/leftImg8bit_sequence_down_2x/train',
ann_dir='cityscapes/gtFine_down_2x/train',
split='splits/train_unsup_1-30.txt',
split_unlabeled='splits/train_unsup_all.txt',
pipeline=train_pipeline,
),
val=dict(
type='CityscapesDataset',
data_root=data_root,
img_dir='cityscapes/leftImg8bit_sequence_down_2x/val',
ann_dir='cityscapes/gtFine_down_2x/val',
split='splits/val.txt',
pipeline=test_pipeline,
),
)
| data_root = 'data/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (256, 512)
train_pipeline = [dict(type='LoadImageFromFile_Semi'), dict(type='LoadAnnotations_Semi'), dict(type='RandomCrop_Semi', crop_size=crop_size, cat_max_ratio=0.75), dict(type='RandomFlip_Semi', prob=0.5), dict(type='PhotoMetricDistortion_Semi'), dict(type='Normalize_Semi', **img_norm_cfg), dict(type='DefaultFormatBundle_Semi'), dict(type='Collect', keys=['img_v0_0', 'img_v0_1', 'img_v0_1_s', 'img_v1_0', 'img_v1_1', 'img_v1_1_s', 'gt'], meta_keys=())]
test_pipeline = [dict(type='LoadImageFromFile'), dict(type='MultiScaleFlipAug', img_scale=(1024, 512), flip=False, transforms=[dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img'])])]
data = dict(samples_per_gpu=2, workers_per_gpu=2, train=dict(type='CityscapesSemiDataset', data_root=data_root, img_dir='cityscapes/leftImg8bit_sequence_down_2x/train', ann_dir='cityscapes/gtFine_down_2x/train', split='splits/train_unsup_1-30.txt', split_unlabeled='splits/train_unsup_all.txt', pipeline=train_pipeline), val=dict(type='CityscapesDataset', data_root=data_root, img_dir='cityscapes/leftImg8bit_sequence_down_2x/val', ann_dir='cityscapes/gtFine_down_2x/val', split='splits/val.txt', pipeline=test_pipeline)) |
P, T = map(int, input().split())
solved = 0
for _ in range(P):
flag = True
for _ in range(T):
test1 = input().strip()
test = test1[0].lower() + test1[1:]
if test == test1.lower():
continue
else:
flag = False
if flag:
solved += 1
print(solved) | (p, t) = map(int, input().split())
solved = 0
for _ in range(P):
flag = True
for _ in range(T):
test1 = input().strip()
test = test1[0].lower() + test1[1:]
if test == test1.lower():
continue
else:
flag = False
if flag:
solved += 1
print(solved) |
def nb_year(p0, percent, aug, p):
year = 0
while p0 < p:
p0 = int(p0 + p0*(percent/100) + aug)
year += 1
print(p0)
return year
print(nb_year(1000, 2, 50, 1200)) | def nb_year(p0, percent, aug, p):
year = 0
while p0 < p:
p0 = int(p0 + p0 * (percent / 100) + aug)
year += 1
print(p0)
return year
print(nb_year(1000, 2, 50, 1200)) |
# custom exceptions for ElasticSearch
class SearchException(Exception):
pass
class IndexNotFoundError(SearchException):
pass
class MalformedQueryError(SearchException):
pass
class SearchUnavailableError(SearchException):
pass
| class Searchexception(Exception):
pass
class Indexnotfounderror(SearchException):
pass
class Malformedqueryerror(SearchException):
pass
class Searchunavailableerror(SearchException):
pass |
print("Digite um numero...")
numero = int(input()); numero
numeroSucessor = print(numero + 1);
numeroAntecessor = print(numero - 1);
print("o seu valor eh {}, seu sucessor eh {} e o seu antecessor eh {}".format(numero, numeroSucessor, numeroAntecessor));
| print('Digite um numero...')
numero = int(input())
numero
numero_sucessor = print(numero + 1)
numero_antecessor = print(numero - 1)
print('o seu valor eh {}, seu sucessor eh {} e o seu antecessor eh {}'.format(numero, numeroSucessor, numeroAntecessor)) |
host_='127.0.0.1'
port_=8086
user_='user name'
pass_ ='user password'
protocol='line'
air_api_key="air api key"
weather_api_key="weather_api_key" | host_ = '127.0.0.1'
port_ = 8086
user_ = 'user name'
pass_ = 'user password'
protocol = 'line'
air_api_key = 'air api key'
weather_api_key = 'weather_api_key' |
MASTER_KEY = "masterKey"
BASE_URL = "http://127.0.0.1:7700"
INDEX_UID = "indexUID"
INDEX_UID2 = "indexUID2"
INDEX_UID3 = "indexUID3"
INDEX_UID4 = "indexUID4"
INDEX_FIXTURE = [
{"uid": INDEX_UID},
{"uid": INDEX_UID2, "options": {"primaryKey": "book_id"}},
{"uid": INDEX_UID3, "options": {"uid": "wrong", "primaryKey": "book_id"}},
]
| master_key = 'masterKey'
base_url = 'http://127.0.0.1:7700'
index_uid = 'indexUID'
index_uid2 = 'indexUID2'
index_uid3 = 'indexUID3'
index_uid4 = 'indexUID4'
index_fixture = [{'uid': INDEX_UID}, {'uid': INDEX_UID2, 'options': {'primaryKey': 'book_id'}}, {'uid': INDEX_UID3, 'options': {'uid': 'wrong', 'primaryKey': 'book_id'}}] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Inyourshoes(object):
def __init__(self, nlp, object):
self.object = object
self.matcher = object.matcher.Matcher(nlp.vocab)
self.matcher.add("Inyourshoes", None,
#what i would do
[{'LOWER': 'what'},
{'LOWER': 'i'},
{'LOWER': 'would'},
{'LOWER': 'do'}],
# if i were you
[{'LOWER': 'if'},
{'LOWER': 'i'},
{'LOWER': 'were'},
{'LOWER': 'you'}],
# i would not
[{'LOWER': 'i'},
{'LOWER': 'would'},
{'LOWER': 'not'}]
)
def __call__(self, doc):
matches = self.matcher(doc)
for match_id, start, end in matches:
sents = self.object.tokens.Span(doc, start, end).sent
sent_start, sent_end = sents.start, sents.end
opinion = self.object.tokens.Span(doc, sent_start, sent_end, label = "INYOURSHOES")
doc._.opinion.append(opinion,)
return doc
| class Inyourshoes(object):
def __init__(self, nlp, object):
self.object = object
self.matcher = object.matcher.Matcher(nlp.vocab)
self.matcher.add('Inyourshoes', None, [{'LOWER': 'what'}, {'LOWER': 'i'}, {'LOWER': 'would'}, {'LOWER': 'do'}], [{'LOWER': 'if'}, {'LOWER': 'i'}, {'LOWER': 'were'}, {'LOWER': 'you'}], [{'LOWER': 'i'}, {'LOWER': 'would'}, {'LOWER': 'not'}])
def __call__(self, doc):
matches = self.matcher(doc)
for (match_id, start, end) in matches:
sents = self.object.tokens.Span(doc, start, end).sent
(sent_start, sent_end) = (sents.start, sents.end)
opinion = self.object.tokens.Span(doc, sent_start, sent_end, label='INYOURSHOES')
doc._.opinion.append(opinion)
return doc |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_len = start = 0
m = {}
for end, char in enumerate(s):
if m.get(char, -1) >= start: # if in the current range
start = m[char] + 1
max_len = max(max_len, end - start + 1)
m[char] = end
return max_len
if __name__ == "__main__":
solver = Solution()
print(solver.lengthOfLongestSubstring("abcabcbb"))
print(solver.lengthOfLongestSubstring("bbbbbb"))
print(solver.lengthOfLongestSubstring("pwwkew"))
| class Solution:
def length_of_longest_substring(self, s: str) -> int:
max_len = start = 0
m = {}
for (end, char) in enumerate(s):
if m.get(char, -1) >= start:
start = m[char] + 1
max_len = max(max_len, end - start + 1)
m[char] = end
return max_len
if __name__ == '__main__':
solver = solution()
print(solver.lengthOfLongestSubstring('abcabcbb'))
print(solver.lengthOfLongestSubstring('bbbbbb'))
print(solver.lengthOfLongestSubstring('pwwkew')) |
if __name__ == "__main__":
null = "null"
placeholder = null
undefined = "undefined"
| if __name__ == '__main__':
null = 'null'
placeholder = null
undefined = 'undefined' |
# optimized_primality_test : O(sqrt(n)) - if x divide n then n/x = y which divides n as well, so we need to check only
# numbers from 1 to sqrt(n). sqrt(n) is border because sqrt(n) * sqrt(n) gives n, which then implies that values after
# sqrt(n) need to be multiplied by values lesser then sqrt(n) which we already checked
def primality_test(num):
i = 2
while i*i <= num:
if num % i == 0:
return False
i += 1
return True
print(primality_test(6793)) | def primality_test(num):
i = 2
while i * i <= num:
if num % i == 0:
return False
i += 1
return True
print(primality_test(6793)) |
Elements_Symbols_Reverse = {
"H":"Hydrogen",
"He":"Helium",
"Li":"Lithium",
"Be":"Beryllium",
"B":"Boron",
"C":"Carbon",
"N":"Nitrogen",
"O":"Oxygen",
"F":"Fluorine",
"Ne":"Neon",
"Na":"Sodium",
"Mg":"Magnesium",
"Al":"Aluminium",
"Si":"Silicon",
"P":"Phosphorus",
"S":"Sulphur",
"Cl":"Chlorine",
"Ar":"Argon",
"K":"Potassium",
"Ca":"Calcium",
"Sc":"Scandium",
"Ti":"Titanium",
"V":"Vanadium",
"Cr":"Chromium",
"Mn":"Manganese",
"Fe":"Iron",
"Co":"Cobalt",
"Ni":"Nickel",
"Cu":"Copper",
"Zn":"Zinc",
"Ga":"Gallium",
"Ge":"Germanium",
"As":"Arsenic",
"Se":"Selenium",
"Br":"Bromine",
"Kr":"Krypton",
"Rb":"Rubidium",
"Sr":"Strontium",
"Y":"Yttrium",
"Zr":"Zirconium",
"Nb":"Niobium",
"Mo":"Molybdenum",
"Tc":"Technetium",
"Ru":"Ruthenium",
"Rh":"Rhodium",
"Pd":"Palladium",
"Ag":"Silver",
"Cd":"Cadmium",
"In":"Indium",
"Sn":"Tin",
"Sb":"Antimony",
"Te":"Tellurium",
"I":"Iodine",
"Xe":"Xenon",
"Cs":"Caesium",
"Ba":"Barium",
"La":"Lanthanum",
"Ce":"Cerium",
"Pr":"Praseodymium",
"Nd":"Neodymium",
"Pm":"Promethium",
"Sm":"Samarium",
"Eu":"Europium",
"Gd":"Gadolinium",
"Tb":"Terbium",
"Dy":"Dysprosium",
"Ho":"Holmium",
"Er":"Erbium",
"Tm":"Thulium",
"Yb":"Ytterbium",
"Lu":"Lutetium",
"Hf":"Halfnium",
"Ta":"Tantalum",
"W":"Tungsten",
"Re":"Rhenium",
"Os":"Osmium",
"Ir":"Iridium",
"Pt":"Platinum",
"Au":"Gold",
"Hg":"Mercury",
"Tl":"Thallium",
"Pb":"Lead",
"Bi":"Bismuth",
"Po":"Polonium",
"At":"Astatine",
"Rn":"Radon",
"Fr":"Francium",
"Ra":"Radium",
"Ac":"Actinium",
"Th":"Thorium",
"Pa":"Protactinium",
"U":"Uranium",
"Np":"Neptunium",
"Pu":"Plutonium",
"Am":"Americium",
"Cm":"Curium",
"Bk":"Berkelium",
"Cf":"Californium",
"Es":"Einsteinium",
"Fm":"Fermium",
"Md":"Mendelevium",
"No":"Nobelium",
"Lr":"Lawrencium",
"Rf":"Rutherfordium",
"Db":"Dubnium",
"Sg":"Seaborgium",
"Bh":"Bohrium",
"Hs":"Hassium",
"Mt":"Meitnerium",
"Ds":"Darmstadtium",
"Rg":"Roentgenium",
"Cn":"Copernicium",
"Nh":"Nihonium",
"Fl":"Flerovium",
"Mc":"Moscovium",
"Lv":"Livermorium",
"Ts":"Tennessine",
"Og":"Oganesson"
}
| elements__symbols__reverse = {'H': 'Hydrogen', 'He': 'Helium', 'Li': 'Lithium', 'Be': 'Beryllium', 'B': 'Boron', 'C': 'Carbon', 'N': 'Nitrogen', 'O': 'Oxygen', 'F': 'Fluorine', 'Ne': 'Neon', 'Na': 'Sodium', 'Mg': 'Magnesium', 'Al': 'Aluminium', 'Si': 'Silicon', 'P': 'Phosphorus', 'S': 'Sulphur', 'Cl': 'Chlorine', 'Ar': 'Argon', 'K': 'Potassium', 'Ca': 'Calcium', 'Sc': 'Scandium', 'Ti': 'Titanium', 'V': 'Vanadium', 'Cr': 'Chromium', 'Mn': 'Manganese', 'Fe': 'Iron', 'Co': 'Cobalt', 'Ni': 'Nickel', 'Cu': 'Copper', 'Zn': 'Zinc', 'Ga': 'Gallium', 'Ge': 'Germanium', 'As': 'Arsenic', 'Se': 'Selenium', 'Br': 'Bromine', 'Kr': 'Krypton', 'Rb': 'Rubidium', 'Sr': 'Strontium', 'Y': 'Yttrium', 'Zr': 'Zirconium', 'Nb': 'Niobium', 'Mo': 'Molybdenum', 'Tc': 'Technetium', 'Ru': 'Ruthenium', 'Rh': 'Rhodium', 'Pd': 'Palladium', 'Ag': 'Silver', 'Cd': 'Cadmium', 'In': 'Indium', 'Sn': 'Tin', 'Sb': 'Antimony', 'Te': 'Tellurium', 'I': 'Iodine', 'Xe': 'Xenon', 'Cs': 'Caesium', 'Ba': 'Barium', 'La': 'Lanthanum', 'Ce': 'Cerium', 'Pr': 'Praseodymium', 'Nd': 'Neodymium', 'Pm': 'Promethium', 'Sm': 'Samarium', 'Eu': 'Europium', 'Gd': 'Gadolinium', 'Tb': 'Terbium', 'Dy': 'Dysprosium', 'Ho': 'Holmium', 'Er': 'Erbium', 'Tm': 'Thulium', 'Yb': 'Ytterbium', 'Lu': 'Lutetium', 'Hf': 'Halfnium', 'Ta': 'Tantalum', 'W': 'Tungsten', 'Re': 'Rhenium', 'Os': 'Osmium', 'Ir': 'Iridium', 'Pt': 'Platinum', 'Au': 'Gold', 'Hg': 'Mercury', 'Tl': 'Thallium', 'Pb': 'Lead', 'Bi': 'Bismuth', 'Po': 'Polonium', 'At': 'Astatine', 'Rn': 'Radon', 'Fr': 'Francium', 'Ra': 'Radium', 'Ac': 'Actinium', 'Th': 'Thorium', 'Pa': 'Protactinium', 'U': 'Uranium', 'Np': 'Neptunium', 'Pu': 'Plutonium', 'Am': 'Americium', 'Cm': 'Curium', 'Bk': 'Berkelium', 'Cf': 'Californium', 'Es': 'Einsteinium', 'Fm': 'Fermium', 'Md': 'Mendelevium', 'No': 'Nobelium', 'Lr': 'Lawrencium', 'Rf': 'Rutherfordium', 'Db': 'Dubnium', 'Sg': 'Seaborgium', 'Bh': 'Bohrium', 'Hs': 'Hassium', 'Mt': 'Meitnerium', 'Ds': 'Darmstadtium', 'Rg': 'Roentgenium', 'Cn': 'Copernicium', 'Nh': 'Nihonium', 'Fl': 'Flerovium', 'Mc': 'Moscovium', 'Lv': 'Livermorium', 'Ts': 'Tennessine', 'Og': 'Oganesson'} |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
'''
Created on Jan 8, 2020
@author: ballance
'''
class TestData(object):
def __init__(self,
teststatus,
toolcategory : str,
date : str,
simtime : float = 0.0,
timeunit : str = "ns",
runcwd : str = ".",
cputime : float = 0.0,
seed : str = "0",
cmd : str = "",
args : str = "",
compulsory : int = 0,
user : str = "user",
cost : float = 0.0
):
self.teststatus = teststatus
self.simtime = simtime
self.timeunit = timeunit
self.runcwd = runcwd
self.cputime = cputime
self.seed = seed
self.cmd = cmd
self.args = args
self.compulsory = compulsory
self.date = date
self.user = user
self.cost = cost
self.toolcategory = toolcategory
| """
Created on Jan 8, 2020
@author: ballance
"""
class Testdata(object):
def __init__(self, teststatus, toolcategory: str, date: str, simtime: float=0.0, timeunit: str='ns', runcwd: str='.', cputime: float=0.0, seed: str='0', cmd: str='', args: str='', compulsory: int=0, user: str='user', cost: float=0.0):
self.teststatus = teststatus
self.simtime = simtime
self.timeunit = timeunit
self.runcwd = runcwd
self.cputime = cputime
self.seed = seed
self.cmd = cmd
self.args = args
self.compulsory = compulsory
self.date = date
self.user = user
self.cost = cost
self.toolcategory = toolcategory |
def even_numbers(numbers):
even = []
for num in numbers:
if num % 2 == 0:
even.append(num)
return even
def odd_numbers(numbers):
odd = []
for num in numbers:
if num % 2 != 0:
odd.append(num)
return odd
def sum_numbers(numbers):
sum = 0
for num in numbers:
sum = sum + num
return sum
# getSumOfOddNumbers 30
def sum_even_numbers(numbers):
even = []
for num in numbers:
if num % 2 == 0:
even.append(num)
return sum(even)
def sum_odd_numbers(numbers):
odd = []
for num in numbers:
if num % 2 != 0:
odd.append(num)
return sum(odd)
def map_logic_numbers(numbers):
list_new = []
for num in numbers:
if num % 2 == 0:
list_new.append(num + 1)
else:
list_new.append(num + 2)
return list_new
list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(even_numbers(list_numbers))
print(odd_numbers(list_numbers))
print(sum_numbers(list_numbers))
print(sum_odd_numbers(list_numbers))
print(sum_even_numbers(list_numbers))
print(map_logic_numbers(list_numbers)) | def even_numbers(numbers):
even = []
for num in numbers:
if num % 2 == 0:
even.append(num)
return even
def odd_numbers(numbers):
odd = []
for num in numbers:
if num % 2 != 0:
odd.append(num)
return odd
def sum_numbers(numbers):
sum = 0
for num in numbers:
sum = sum + num
return sum
def sum_even_numbers(numbers):
even = []
for num in numbers:
if num % 2 == 0:
even.append(num)
return sum(even)
def sum_odd_numbers(numbers):
odd = []
for num in numbers:
if num % 2 != 0:
odd.append(num)
return sum(odd)
def map_logic_numbers(numbers):
list_new = []
for num in numbers:
if num % 2 == 0:
list_new.append(num + 1)
else:
list_new.append(num + 2)
return list_new
list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(even_numbers(list_numbers))
print(odd_numbers(list_numbers))
print(sum_numbers(list_numbers))
print(sum_odd_numbers(list_numbers))
print(sum_even_numbers(list_numbers))
print(map_logic_numbers(list_numbers)) |
'''
disjoint set forest implementation, uses union by rank and path compression
worst case T.C for find_set is O(logn) in first find_set operation
T.C for union and create_set is O(1)
'''
class Node:
# the identity of node(member of set) is given by data, parent_link, rank
def __init__(self, data=None, rank=None, parent_link=None):
self.data = data
self.rank = rank
self.parent_link = parent_link
class DisjointSet:
# dictionary is important here because here I need to map data to node
def __init__(self, node_map):
self.node_map = node_map
# create a new set i.e create a node, make it point to itself and set rank
def create_set(self, data):
node = Node(data, 0) # setting the data and rank
node.parent_link = node # since its the only node in the set
self.node_map[data] = node # creating the data to node mapping
# returns the data contained in the representative_node
def find_set(self, data):
# getting the node containing data
node = self.node_map[data]
representative_node = self.find_representative(node)
return representative_node.data
# returns the representative_node of the node passed as agrument in fun
# this method is also responsible for path compression, here I am using
# recusive approach to perform the path compression
def find_representative(self, node):
# getting the parent of the given node
parent = node.parent_link
# check if the parent is the root (i.e. representative_node) or not
if parent == node: # if root, then parent will be same as node
return parent
# set the parent_link of each node in the path to the root
node.parent_link = self.find_representative(node.parent_link)
return node.parent_link
# performs the union using using by rank method
def union(self, data1, data2):
# get the node corrosponding to data1 and data2
node1 = self.node_map[data1]
node2 = self.node_map[data2]
# check if both data1 and data2 belongs to same set or not
# for this I need to know the representative_node of each data1 & data2
rep1 = self.find_representative(node1)
rep2 = self.find_representative(node2)
if rep1.data == rep2.data:
return False # False indicates, there is not need to perform union
# the tree with higher rank should become the final representative_node
if rep1.rank >= rep2.rank:
# if rank of both set is same then final rank will increase by 1
# else the rank would be same as rep1's rank
rep1.rank = 1 + rep1.rank if rep1.rank == rep2.rank else rep1.rank
# set the parent_link of set2 to representative_node of set1
rep2.parent_link = rep1
else:
# setting the parent_link of set1 to representative_node of set2
rep1.parent_link = rep2
return True # represents that union happened successfully
| """
disjoint set forest implementation, uses union by rank and path compression
worst case T.C for find_set is O(logn) in first find_set operation
T.C for union and create_set is O(1)
"""
class Node:
def __init__(self, data=None, rank=None, parent_link=None):
self.data = data
self.rank = rank
self.parent_link = parent_link
class Disjointset:
def __init__(self, node_map):
self.node_map = node_map
def create_set(self, data):
node = node(data, 0)
node.parent_link = node
self.node_map[data] = node
def find_set(self, data):
node = self.node_map[data]
representative_node = self.find_representative(node)
return representative_node.data
def find_representative(self, node):
parent = node.parent_link
if parent == node:
return parent
node.parent_link = self.find_representative(node.parent_link)
return node.parent_link
def union(self, data1, data2):
node1 = self.node_map[data1]
node2 = self.node_map[data2]
rep1 = self.find_representative(node1)
rep2 = self.find_representative(node2)
if rep1.data == rep2.data:
return False
if rep1.rank >= rep2.rank:
rep1.rank = 1 + rep1.rank if rep1.rank == rep2.rank else rep1.rank
rep2.parent_link = rep1
else:
rep1.parent_link = rep2
return True |
'''# from app.game import determine_winner
# FYI normally we'd have this application code (determine_winner()) in another file,
# ... but for this exercise we'll keep it here
def determine_winner(user_choice, computer_choice):
return "rock" # todo: write logic here to make the tests pass!
if user_choice == computer_choice:
return None
elif user_choice == "rock" and computer_choice == "scissors"
winner = "rock"
def test_determine_winner():
assert determine_winner("rock", "rock") == None
assert determine_winner("rock", "paper") == "paper"
assert determine_winner("rock", "scissors") == "rock"
assert determine_winner("paper", "rock") == "paper"
assert determine_winner("paper", "paper") == None
assert determine_winner("paper", "scissors") == "scissors"
assert determine_winner("scissors", "rock") == "rock"
assert determine_winner("scissors", "paper") == "scissors"
assert determine_winner("scissors", "scissors") == None
''' | """# from app.game import determine_winner
# FYI normally we'd have this application code (determine_winner()) in another file,
# ... but for this exercise we'll keep it here
def determine_winner(user_choice, computer_choice):
return "rock" # todo: write logic here to make the tests pass!
if user_choice == computer_choice:
return None
elif user_choice == "rock" and computer_choice == "scissors"
winner = "rock"
def test_determine_winner():
assert determine_winner("rock", "rock") == None
assert determine_winner("rock", "paper") == "paper"
assert determine_winner("rock", "scissors") == "rock"
assert determine_winner("paper", "rock") == "paper"
assert determine_winner("paper", "paper") == None
assert determine_winner("paper", "scissors") == "scissors"
assert determine_winner("scissors", "rock") == "rock"
assert determine_winner("scissors", "paper") == "scissors"
assert determine_winner("scissors", "scissors") == None
""" |
N = int(input())
a = list(map(int, input().split()))
for i, _ in sorted(enumerate(a), key=lambda x: x[1], reverse=True):
print(i + 1)
| n = int(input())
a = list(map(int, input().split()))
for (i, _) in sorted(enumerate(a), key=lambda x: x[1], reverse=True):
print(i + 1) |
class Environment:
def __init__(self, width=1000, height=1000):
self.width = width
self.height = height
self.agent = None
self.doors = []
def add_door(self, door):
self.doors.append(door)
def get_env_size(self):
size = (self.height, self.width)
return size
| class Environment:
def __init__(self, width=1000, height=1000):
self.width = width
self.height = height
self.agent = None
self.doors = []
def add_door(self, door):
self.doors.append(door)
def get_env_size(self):
size = (self.height, self.width)
return size |
# custom exceptions
class PybamWarn(Exception):
pass
class PybamError(Exception):
pass
| class Pybamwarn(Exception):
pass
class Pybamerror(Exception):
pass |
################################################################################
# Copyright (c) 2015-2018 Skymind, Inc.
#
# This program and the accompanying materials are made available under the
# terms of the Apache License, Version 2.0 which is available at
# https://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# SPDX-License-Identifier: Apache-2.0
################################################################################
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: graph
class OpType(object):
TRANSFORM = 0
ACCUMULATION = 1
INDEX_ACCUMULATION = 2
SCALAR = 3
BROADCAST = 4
PAIRWISE = 5
ACCUMULATION3 = 6
SUMMARYSTATS = 7
SHAPE = 8
AGGREGATION = 9
RANDOM = 10
CUSTOM = 11
GRAPH = 12
VARIABLE = 30
BOOLEAN = 40
LOGIC = 119
| class Optype(object):
transform = 0
accumulation = 1
index_accumulation = 2
scalar = 3
broadcast = 4
pairwise = 5
accumulation3 = 6
summarystats = 7
shape = 8
aggregation = 9
random = 10
custom = 11
graph = 12
variable = 30
boolean = 40
logic = 119 |
'''Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise.
For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3.
Note that if there are no 0s, then the longest contiguous segment of 0s is considered to have length 0. The same applies if there are no 1s.'''
class Solution:
def checkZeroOnes(self, l0: str) -> bool:
self.l0 = l0
temp = 1
num_1 = 0
num_0 = 0
for i in range(1,len(l0)):
curr_1 = 0
curr_0 = 0
if(int(l0[i]) - int(l0[i-1]) == 0):
temp+=1
elif(int(l0[i]) - int(l0[i-1] )== -1):
curr_1 = temp
if(curr_1 > num_1 ):
num_1 = curr_1
temp = 1
else:
curr_0 = temp
if(curr_0 > num_0 ):
num_0 = curr_0
temp = 1
if(l0[-1] == '0'):
if(num_0 < temp):
num_0 = temp
else:
if(num_1 < temp):
num_1 = temp
if(num_1 > num_0):
return True
else:return False
| """Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise.
For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3.
Note that if there are no 0s, then the longest contiguous segment of 0s is considered to have length 0. The same applies if there are no 1s."""
class Solution:
def check_zero_ones(self, l0: str) -> bool:
self.l0 = l0
temp = 1
num_1 = 0
num_0 = 0
for i in range(1, len(l0)):
curr_1 = 0
curr_0 = 0
if int(l0[i]) - int(l0[i - 1]) == 0:
temp += 1
elif int(l0[i]) - int(l0[i - 1]) == -1:
curr_1 = temp
if curr_1 > num_1:
num_1 = curr_1
temp = 1
else:
curr_0 = temp
if curr_0 > num_0:
num_0 = curr_0
temp = 1
if l0[-1] == '0':
if num_0 < temp:
num_0 = temp
elif num_1 < temp:
num_1 = temp
if num_1 > num_0:
return True
else:
return False |
class UndergroundSystem(object):
def __init__(self):
# record the customer's starting trip
# card ID: [station, t]
self.customer_trip = {}
# record the average travel time from start station to end station
# (start, end): [t, times]
self.trips = {}
def checkIn(self, id, stationName, t):
self.customer_trip[id] = [stationName, t]
def checkOut(self, id, stationName, t):
# get the check in information of the customer
start_station, start_t = self.customer_trip[id]
del self.customer_trip[id]
# the trip information
# stationName => end_station
# t => end_t
trip = (start_station, stationName)
travel_time = t - start_t
# store / update the trip information
if trip not in self.trips:
self.trips[trip] = [travel_time, 1]
else:
# another way to write that is store the total traveling time and the number of travels
# so that you do not need to calculate the avg time everytime
avg_t, times = self.trips[trip]
self.trips[trip] = [
(avg_t * times + travel_time) / (times + 1.0), times + 1]
def getAverageTime(self, startStation, endStation):
return self.trips[(startStation, endStation)][0]
# Your UndergroundSystem object will be instantiated and called as such:
# obj = UndergroundSystem()
# obj.checkIn(id,stationName,t)
# obj.checkOut(id,stationName,t)
# param_3 = obj.getAverageTime(startStation,endStation)
| class Undergroundsystem(object):
def __init__(self):
self.customer_trip = {}
self.trips = {}
def check_in(self, id, stationName, t):
self.customer_trip[id] = [stationName, t]
def check_out(self, id, stationName, t):
(start_station, start_t) = self.customer_trip[id]
del self.customer_trip[id]
trip = (start_station, stationName)
travel_time = t - start_t
if trip not in self.trips:
self.trips[trip] = [travel_time, 1]
else:
(avg_t, times) = self.trips[trip]
self.trips[trip] = [(avg_t * times + travel_time) / (times + 1.0), times + 1]
def get_average_time(self, startStation, endStation):
return self.trips[startStation, endStation][0] |
# Black list for auto vote cast
Blacklist_team = ["Royal Never Give Up", "NAVI"]
Blacklist_game = ["CSGO"]
Blacklist_event = []
# Program debug
debugLevel = 0
# Switch of auto vote cast function
autoVote = True
# Cycle of tasks (seconds)
cycleTime = 1800
| blacklist_team = ['Royal Never Give Up', 'NAVI']
blacklist_game = ['CSGO']
blacklist_event = []
debug_level = 0
auto_vote = True
cycle_time = 1800 |
print("Calorie Calulator")
FAT = float(input("Enter grams of fat: "))
CARBOHYDRATES = float(input("Enter grams of Carbohydrates: "))
PROTEIN= float(input("Enter grams of Protein: "))
Fatg = 9 * FAT
print("Number of calories from Fat is: " + str(Fatg))
Protieng = 4 * PROTEIN
print("Number of calories from Protein is: " + str(Protieng))
Carbohydratesg = 4 * CARBOHYDRATES
print("Number of calories from Carbohydrates is: " + str(Carbohydratesg))
totalCalorie = Fatg + Protieng + Carbohydratesg
print("Total number of Calories is: " + str(totalCalorie))
| print('Calorie Calulator')
fat = float(input('Enter grams of fat: '))
carbohydrates = float(input('Enter grams of Carbohydrates: '))
protein = float(input('Enter grams of Protein: '))
fatg = 9 * FAT
print('Number of calories from Fat is: ' + str(Fatg))
protieng = 4 * PROTEIN
print('Number of calories from Protein is: ' + str(Protieng))
carbohydratesg = 4 * CARBOHYDRATES
print('Number of calories from Carbohydrates is: ' + str(Carbohydratesg))
total_calorie = Fatg + Protieng + Carbohydratesg
print('Total number of Calories is: ' + str(totalCalorie)) |
# sudoku solver with backtracking algorithm...
board = [[4,0,0,0,1,0,3,0,0],
[0,6,0,4,0,7,0,0,0],
[0,5,0,0,3,2,1,4,0],
[9,0,4,0,0,1,0,8,5],
[0,0,6,0,0,0,9,0,0],
[3,1,0,7,0,0,6,0,4],
[0,4,9,5,7,0,0,3,0],
[0,0,0,1,0,4,0,7,0],
[0,0,1,0,9,0,0,0,2]]
def findEmpty():
for i in range(0,9):
for j in range(0,9):
if board[i][j]==0:
return (i,j)
return None
def printBoard():
print("\n"*3)
for i in range(1,10):
for j in range(1,10):
print(board[i-1][j-1],end = '')
if j%3==0:
print(" | ",end = '')
print("\n",end='')
if i%3==0 and i!=9:
print("_"*17)
print("\n"*3)
def valid(bo, num, pos):
# Check row
for i in range(len(bo[0])):
if bo[pos[0]][i] == num and pos[1] != i:
return False
# Check column
for i in range(len(bo)):
if bo[i][pos[1]] == num and pos[0] != i:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x * 3, box_x*3 + 3):
if bo[i][j] == num and (i,j) != pos:
return False
return True
def solveSudoku():
pos = findEmpty()
if pos==None:
printBoard()
return True
(row,col) = pos
for no in range(1,10):
#print ("working at position",pos)
if valid(board,no,pos):
board[row][col] = no
if solveSudoku()==True:
return True
board[row][col] = 0
return False
printBoard()
boo = solveSudoku()
if boo:
print("puzzle solved")
else:
print("Sorry, this puzzle can't be solved")
| board = [[4, 0, 0, 0, 1, 0, 3, 0, 0], [0, 6, 0, 4, 0, 7, 0, 0, 0], [0, 5, 0, 0, 3, 2, 1, 4, 0], [9, 0, 4, 0, 0, 1, 0, 8, 5], [0, 0, 6, 0, 0, 0, 9, 0, 0], [3, 1, 0, 7, 0, 0, 6, 0, 4], [0, 4, 9, 5, 7, 0, 0, 3, 0], [0, 0, 0, 1, 0, 4, 0, 7, 0], [0, 0, 1, 0, 9, 0, 0, 0, 2]]
def find_empty():
for i in range(0, 9):
for j in range(0, 9):
if board[i][j] == 0:
return (i, j)
return None
def print_board():
print('\n' * 3)
for i in range(1, 10):
for j in range(1, 10):
print(board[i - 1][j - 1], end='')
if j % 3 == 0:
print(' | ', end='')
print('\n', end='')
if i % 3 == 0 and i != 9:
print('_' * 17)
print('\n' * 3)
def valid(bo, num, pos):
for i in range(len(bo[0])):
if bo[pos[0]][i] == num and pos[1] != i:
return False
for i in range(len(bo)):
if bo[i][pos[1]] == num and pos[0] != i:
return False
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if bo[i][j] == num and (i, j) != pos:
return False
return True
def solve_sudoku():
pos = find_empty()
if pos == None:
print_board()
return True
(row, col) = pos
for no in range(1, 10):
if valid(board, no, pos):
board[row][col] = no
if solve_sudoku() == True:
return True
board[row][col] = 0
return False
print_board()
boo = solve_sudoku()
if boo:
print('puzzle solved')
else:
print("Sorry, this puzzle can't be solved") |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T E X A M P L E S
#
# Copyright (c) 2017 Thom Janssen <https://github.com/thomgb>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyxyz.org/flat
# -----------------------------------------------------------------------------
#
# BinaryData.py
#
# Shows how to read and write binary data. More here:
#
# https://www.devdungeon.com/content/working-binary-data-python
# Creates empty bytes.
empty_bytes = bytes(4)
print(type(empty_bytes))
print(empty_bytes)
# Casts bytes to bytearray.
mutable_bytes = bytearray(empty_bytes)
print(mutable_bytes)
mutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification:
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)
s = b'bla'
print(s.decode('utf8'))
| empty_bytes = bytes(4)
print(type(empty_bytes))
print(empty_bytes)
mutable_bytes = bytearray(empty_bytes)
print(mutable_bytes)
mutable_bytes = bytearray(b'\x00\x0f')
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)
s = b'bla'
print(s.decode('utf8')) |
# import math
# import numpy as np
def lagrange(f, xs, x):
ys = [f(i) for i in xs]
n = len(xs)
y = 0
for k in range(0, n):
t = 1
for j in range(0, n):
if j != k:
s = (x - xs[j]) / (xs[k] - xs[j])
t = t * s
y = y + t * ys[k]
return y
def difference_quotient(f, xs):
res = 0
n = len(xs)
for k in range(n):
t = 1
for j in range(n):
if j != k:
t *= (xs[k] - xs[j])
res += f(xs[k]) / t
return res
def newtown(f, xs, x):
n = len(xs)
y = f(xs[0])
for k in range(1, n):
t = difference_quotient(f, xs[:k + 1])
for j in range(k):
t *= (x - xs[j])
y += t
return y
def piecewise_linear(f, xs, x):
interval = [0, 1]
if x < xs[0]:
interval = [xs[0], xs[1]]
elif x > xs[-1]:
interval = [xs[-2], xs[-1]]
else:
for i in range(len(xs) - 1):
if x >= xs[i] and x <= xs[i + 1]:
interval = [xs[i], xs[i + 1]]
break
return lagrange(f, interval, x)
# print(lagrange(lambda x: 1 / (1 + x * x), np.linspace(-5, 5, 11), 0.5))
# print(lagrange(lambda x: 1 / (1 + x * x), np.linspace(-5, 5, 11), 4.5))
# print(piecewise_linear(lambda x: 1 / (1 + x * x), np.linspace(-5, 5, 11), 0.5))
# print(piecewise_linear(lambda x: 1 / (1 + x * x), np.linspace(-5, 5, 11), 4.5))
# print(
# difference_quotient(lambda x: x * x * x - 4 * x, (np.arange(5))[1:]),
# difference_quotient(lambda x: x * x * x - 4 * x, [1, 2]),
# difference_quotient(lambda x: x * x * x - 4 * x, [1, 2, 3])
# )
# print(newtown(lambda x: x * x * x - 4 * x, (np.arange(5))[1:], 5))
# print(newtown(lambda x: math.sqrt(x), [1, 4, 9], 5))
| def lagrange(f, xs, x):
ys = [f(i) for i in xs]
n = len(xs)
y = 0
for k in range(0, n):
t = 1
for j in range(0, n):
if j != k:
s = (x - xs[j]) / (xs[k] - xs[j])
t = t * s
y = y + t * ys[k]
return y
def difference_quotient(f, xs):
res = 0
n = len(xs)
for k in range(n):
t = 1
for j in range(n):
if j != k:
t *= xs[k] - xs[j]
res += f(xs[k]) / t
return res
def newtown(f, xs, x):
n = len(xs)
y = f(xs[0])
for k in range(1, n):
t = difference_quotient(f, xs[:k + 1])
for j in range(k):
t *= x - xs[j]
y += t
return y
def piecewise_linear(f, xs, x):
interval = [0, 1]
if x < xs[0]:
interval = [xs[0], xs[1]]
elif x > xs[-1]:
interval = [xs[-2], xs[-1]]
else:
for i in range(len(xs) - 1):
if x >= xs[i] and x <= xs[i + 1]:
interval = [xs[i], xs[i + 1]]
break
return lagrange(f, interval, x) |
#! /usr/bin/env python3
'''
Problem 52 - Project Euler
http://projecteuler.net/index.php?section=problems&id=052
'''
def samedigits(x,y):
return set(str(x)) == set(str(y))
if __name__ == '__main__':
maxn = 6
x = 1
while True:
for n in range(2, maxn+1):
if not samedigits(x, x * n):
break
else:
print([x * i for i in range(1, maxn+1)])
break
x += 1
| """
Problem 52 - Project Euler
http://projecteuler.net/index.php?section=problems&id=052
"""
def samedigits(x, y):
return set(str(x)) == set(str(y))
if __name__ == '__main__':
maxn = 6
x = 1
while True:
for n in range(2, maxn + 1):
if not samedigits(x, x * n):
break
else:
print([x * i for i in range(1, maxn + 1)])
break
x += 1 |
'''
Given an array of integers what is the length of the longest subArray containing no more than two
distinct values such that the distinct values differ by no more than 1
For Example:
arr = [0, 1, 2, 1, 2, 3] -> length = 4; [1,2,1,2]
arr = [1, 2, 3, 4, 5] -> length = 2; [1,2]
arr = [1, 1, 1, 3, 3, 2, 2] -> length = 4; [3,3,2,2]
arr = [1, 1, 2, 2, 1, 2, 3, 3, 2, 2, 3, 3] -> length = 7; [2, 3, 3, 2, 2, 3, 3]
'''
# def get_max_len(arr):
# # code here
# # dict containing the last occurance of that element
# elem = {arr[0]:0}
# max_len = 0
# first = 0
# for i in range(1,arr):
# if arr[i] in elem:
# # Storing the latest occurence
# elem[arr[i]] = i
# else:
# for ele in elem:
# if abs(arr[i] - ele)==1:
# if len(elem) == 1:
# max_len = max(max_len, i+1)
# elem[arr[i]] = i
# elif len(elem) == 2:
# max_len = max(max_len, i-first)
# # Deleted the previous element and arr[i] is added to elem
# elem = {ele:elem[ele], arr[i]:i}
# break
# else:
# if len(elem)==1:
# elem = {arr[i]:i}
# if len(elem) == 2:
# # Contains the value and its first and last occurence in the list
# class Node:
# def __init__(self, data):
# self.data = data
# self.last = None
# self.next = None
# class Queue:
# def __init__(self):
# self.head = None
# def insert(self, val):
# if self.head == None:
# self.head = Node(val, first)
# else:
# new_node = Node(val, first)
# self.head.next = new_node
arr = list(map(int, input().strip().split()))
print(get_max_len(arr)) | """
Given an array of integers what is the length of the longest subArray containing no more than two
distinct values such that the distinct values differ by no more than 1
For Example:
arr = [0, 1, 2, 1, 2, 3] -> length = 4; [1,2,1,2]
arr = [1, 2, 3, 4, 5] -> length = 2; [1,2]
arr = [1, 1, 1, 3, 3, 2, 2] -> length = 4; [3,3,2,2]
arr = [1, 1, 2, 2, 1, 2, 3, 3, 2, 2, 3, 3] -> length = 7; [2, 3, 3, 2, 2, 3, 3]
"""
arr = list(map(int, input().strip().split()))
print(get_max_len(arr)) |
#!/usr/bin/env python3
#
# --- Day 21: Dirac Dice / Part Two ---
#
# Now that you're warmed up, it's time to play the real game.
#
# A second compartment opens, this time labeled Dirac dice. Out of it falls
# a single three-sided die.
#
# As you experiment with the die, you feel a little strange. An informational
# brochure in the compartment explains that this is a quantum die: when you
# roll it, the universe splits into multiple copies, one copy for each possible
# outcome of the die. In this case, rolling the die always splits the universe
# into three copies: one where the outcome of the roll was 1, one where it was
# 2, and one where it was 3.
#
# The game is played the same as before, although to prevent things from
# getting too far out of hand, the game now ends when either player's score
# reaches at least 21.
#
# Using the same starting positions as in the example above,
# player 1 wins in 444356092776315 universes, while player 2 merely wins
# in 341960390180808 universes.
#
# Using your given starting positions, determine every possible outcome.
# Find the player that wins in more universes; in how many universes
# does that player win?
#
#
# --- Solution ---
#
# This is mostly a start from scratch... First we count the possible outcomes
# from a 3 rolls and how many these outcomes happen. Then we prepare a function
# that will simulate every possible way the game will go. At given positions,
# scores and turn, for each possible rolls outcome, we calculate new results
# and two things may happen: either we finish the game with the new scores,
# or we should simulate recurrently the game with a new set of conditions.
# As a result, we simply count the numbers of times there was a win for each
# of all possible rolls. After about 30 seconds it gives us the right answer.
#
INPUT_FILE = 'input.txt'
GOAL = 21
PLAYER_1 = 0
PLAYER_2 = 1
CACHE = {}
def game(possibilities, positions, scores, turn=0):
uuid = ((tuple(positions), tuple(scores), turn))
if uuid in CACHE:
return CACHE[uuid]
player = PLAYER_1 if turn % 2 == 0 else PLAYER_2
turn = (turn + 1) % 2
wins = [0, 0]
for roll, times in possibilities.items():
new_positions = positions.copy()
new_scores = scores.copy()
new_position = (positions[player] + roll) % 10
new_positions[player] = new_position
new_scores[player] += (new_position + 1)
if new_scores[PLAYER_1] < GOAL and new_scores[PLAYER_2] < GOAL:
win1, win2 = game(possibilities, new_positions, new_scores, turn)
wins[0] += win1 * times
wins[1] += win2 * times
else:
if new_scores[PLAYER_1] >= GOAL:
wins[PLAYER_1] += times
else:
wins[PLAYER_2] += times
CACHE[uuid] = wins
return wins
def main():
positions = [int(line.strip().split()[-1]) - 1
for line in open(INPUT_FILE, 'r')]
scores = [0, 0]
possibilities = {} # 3x roll result -> how many times it can happen
for dice1 in [1, 2, 3]:
for dice2 in [1, 2, 3]:
for dice3 in [1, 2, 3]:
result = dice1 + dice2 + dice3
if result not in possibilities:
possibilities[result] = 1
else:
possibilities[result] += 1
wins = game(possibilities, positions, scores, turn=0)
print(max(wins))
if __name__ == '__main__':
main()
| input_file = 'input.txt'
goal = 21
player_1 = 0
player_2 = 1
cache = {}
def game(possibilities, positions, scores, turn=0):
uuid = (tuple(positions), tuple(scores), turn)
if uuid in CACHE:
return CACHE[uuid]
player = PLAYER_1 if turn % 2 == 0 else PLAYER_2
turn = (turn + 1) % 2
wins = [0, 0]
for (roll, times) in possibilities.items():
new_positions = positions.copy()
new_scores = scores.copy()
new_position = (positions[player] + roll) % 10
new_positions[player] = new_position
new_scores[player] += new_position + 1
if new_scores[PLAYER_1] < GOAL and new_scores[PLAYER_2] < GOAL:
(win1, win2) = game(possibilities, new_positions, new_scores, turn)
wins[0] += win1 * times
wins[1] += win2 * times
elif new_scores[PLAYER_1] >= GOAL:
wins[PLAYER_1] += times
else:
wins[PLAYER_2] += times
CACHE[uuid] = wins
return wins
def main():
positions = [int(line.strip().split()[-1]) - 1 for line in open(INPUT_FILE, 'r')]
scores = [0, 0]
possibilities = {}
for dice1 in [1, 2, 3]:
for dice2 in [1, 2, 3]:
for dice3 in [1, 2, 3]:
result = dice1 + dice2 + dice3
if result not in possibilities:
possibilities[result] = 1
else:
possibilities[result] += 1
wins = game(possibilities, positions, scores, turn=0)
print(max(wins))
if __name__ == '__main__':
main() |
# write recursively
# ie
# 10 > 7+3 or 5+5
# 7+3 is done
# 5+5 -> 3 + 2 + 5
# 3+ 2 + 5 -> 3 + 2 + 3 + 2 is done
# if the number youre breaking is even you get 2 initially, if its odd you get 1 more sum
def solve():
raise NotImplementedError
if __name__ == '__main__':
print(solve())
| def solve():
raise NotImplementedError
if __name__ == '__main__':
print(solve()) |
guest = input()
host = input()
pile = input()
print("YES" if sorted(pile) == sorted(guest + host) else "NO")
| guest = input()
host = input()
pile = input()
print('YES' if sorted(pile) == sorted(guest + host) else 'NO') |
# -*- coding: utf-8 -*-
def write_out(message):
with open('/tmp/out', 'w') as f:
f.write("We have triggered.")
f.write(message)
| def write_out(message):
with open('/tmp/out', 'w') as f:
f.write('We have triggered.')
f.write(message) |
class Arithmatic:
#This function does adding to integer
def Add(self, x, y):
return x + y
#This fnction does su
def Subtraction(self, x, y):
return x - y
| class Arithmatic:
def add(self, x, y):
return x + y
def subtraction(self, x, y):
return x - y |
def category(cat):
def set_cat(cmd):
cmd.category = cat.title()
return cmd
return set_cat | def category(cat):
def set_cat(cmd):
cmd.category = cat.title()
return cmd
return set_cat |
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
def isValid(str1, str2, num):
if not num:
return True
res = str(int(str1) + int(str2))
# print(str1, str2, res, num)
str1, str2 = str2, res
l = len(res)
return num.startswith(res) and isValid(str1, str2, num[l:])
n = len(num)
for i in range(1, n // 2 + 1):
if num[0] == '0' and i > 1: return False
sub1 = num[:i]
for j in range(1, n):
if max(i, j) > n - i - j: break
if num[i] == '0' and j > 1: break
sub2 = num[i:i + j]
if isValid(sub1, sub2, num[i + j:]):
return True
return False
| class Solution:
def is_additive_number(self, num: str) -> bool:
def is_valid(str1, str2, num):
if not num:
return True
res = str(int(str1) + int(str2))
(str1, str2) = (str2, res)
l = len(res)
return num.startswith(res) and is_valid(str1, str2, num[l:])
n = len(num)
for i in range(1, n // 2 + 1):
if num[0] == '0' and i > 1:
return False
sub1 = num[:i]
for j in range(1, n):
if max(i, j) > n - i - j:
break
if num[i] == '0' and j > 1:
break
sub2 = num[i:i + j]
if is_valid(sub1, sub2, num[i + j:]):
return True
return False |
if __name__ == '__main__':
if (1!=1) : print("IF")
else : print("InnerElse")
else: print("OuterElse")
| if __name__ == '__main__':
if 1 != 1:
print('IF')
else:
print('InnerElse')
else:
print('OuterElse') |
num = int(input())
lista = [[0] * num for i in range(num)]
for i in range(num):
for j in range(num):
if i < j:
lista[i][j] = 0
elif i > j:
lista[i][j] = 2
else:
lista[i][j] = 1
for r in lista:
print(' '.join([str(elem) for elem in r]))
| num = int(input())
lista = [[0] * num for i in range(num)]
for i in range(num):
for j in range(num):
if i < j:
lista[i][j] = 0
elif i > j:
lista[i][j] = 2
else:
lista[i][j] = 1
for r in lista:
print(' '.join([str(elem) for elem in r])) |
def aumentar(preco=0, taxa=0, formato=False):
res = preco + (preco * taxa/100)
return res if formato is False else moeda(res)
def diminuir(preco=0, taxa=0, formato=False):
res = preco - (preco * taxa/100)
return res if formato is False else moeda(res)
def dobro(preco=0, formato=False):
res = preco * 2
return res if not formato else moeda(res)
def metade(preco=0, formato=False):
res = preco / 2
return res if not formato else moeda(res)
def moeda(p=0, m='R$'):
return f'{m}{p:>.2f}' .replace('.', ',')
| def aumentar(preco=0, taxa=0, formato=False):
res = preco + preco * taxa / 100
return res if formato is False else moeda(res)
def diminuir(preco=0, taxa=0, formato=False):
res = preco - preco * taxa / 100
return res if formato is False else moeda(res)
def dobro(preco=0, formato=False):
res = preco * 2
return res if not formato else moeda(res)
def metade(preco=0, formato=False):
res = preco / 2
return res if not formato else moeda(res)
def moeda(p=0, m='R$'):
return f'{m}{p:>.2f}'.replace('.', ',') |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the message will be displayed
assert first_author_name == dataset_description["Authors"][0]["Name"],\
'That is not the authors name from the original dictionary'
assert "first_author_name = output" in __solution__,\
'Did you just typed the name in?'
__msg__.good("Well done!")
| def test():
assert first_author_name == dataset_description['Authors'][0]['Name'], 'That is not the authors name from the original dictionary'
assert 'first_author_name = output' in __solution__, 'Did you just typed the name in?'
__msg__.good('Well done!') |
class PartyAnimal:
x = 0
def party(self):
self.x = self.x + 1
print(f'So far {self.x}')
an = PartyAnimal()
an.party()
an.party()
an.party()
print(dir(an))
| class Partyanimal:
x = 0
def party(self):
self.x = self.x + 1
print(f'So far {self.x}')
an = party_animal()
an.party()
an.party()
an.party()
print(dir(an)) |
with open("./build-scripts/opcodes.txt", "r") as f:
opcodes = f.readlines()
opcodes_h = open("./src/core/bc_data/opcodes.txt", "w")
opcodes_h.write("enum au_opcode {\n")
callbacks_h = open("./src/core/bc_data/callbacks.txt", "w")
callbacks_h.write("static void *cb[] = {\n")
dbg_h = open("./src/core/bc_data/dbg.txt", "w")
dbg_h.write("const char *au_opcode_dbg[AU_MAX_OPCODE] = {\n")
num_opcodes = 0
for opcode in opcodes:
if opcode == "\n" or opcode.startswith("#"):
continue
opcode = opcode.strip()
opcodes_h.write(f"AU_OP_{opcode} = {num_opcodes},\n")
callbacks_h.write(f"&&CASE(AU_OP_{opcode}),\n")
dbg_h.write(f"\"{opcode}\",\n")
num_opcodes += 1
opcodes_h.write("};\n")
callbacks_h.write("};\n")
dbg_h.write("};\n") | with open('./build-scripts/opcodes.txt', 'r') as f:
opcodes = f.readlines()
opcodes_h = open('./src/core/bc_data/opcodes.txt', 'w')
opcodes_h.write('enum au_opcode {\n')
callbacks_h = open('./src/core/bc_data/callbacks.txt', 'w')
callbacks_h.write('static void *cb[] = {\n')
dbg_h = open('./src/core/bc_data/dbg.txt', 'w')
dbg_h.write('const char *au_opcode_dbg[AU_MAX_OPCODE] = {\n')
num_opcodes = 0
for opcode in opcodes:
if opcode == '\n' or opcode.startswith('#'):
continue
opcode = opcode.strip()
opcodes_h.write(f'AU_OP_{opcode} = {num_opcodes},\n')
callbacks_h.write(f'&&CASE(AU_OP_{opcode}),\n')
dbg_h.write(f'"{opcode}",\n')
num_opcodes += 1
opcodes_h.write('};\n')
callbacks_h.write('};\n')
dbg_h.write('};\n') |
# lets make a Player class
class Player:
def __init__(self, name, starting_room):
self.name = name
self.current_room = starting_room
| class Player:
def __init__(self, name, starting_room):
self.name = name
self.current_room = starting_room |
#!/usr/local/bin/python3
# Frequency queries
def freqQuery(queries):
result = []
numbers = {}
occurrences = {}
for operation, value in queries:
if operation == 1:
quantity = numbers.get(value, 0)
if quantity > 0:
occurrences[quantity] = occurrences[quantity] - 1
numbers[value] = numbers.get(value, 0) + 1
occurrences[numbers[value]] = occurrences.get(numbers[value], 0) + 1
elif operation == 2:
quantity = numbers.get(value, 0)
if quantity > 0:
numbers[value] = quantity - 1
occurrences[quantity] = occurrences[quantity] - 1
occurrences[quantity - 1] = occurrences.get(quantity - 1, 0) + 1
else:
result.append(1) if occurrences.get(value) else result.append(0)
return result
| def freq_query(queries):
result = []
numbers = {}
occurrences = {}
for (operation, value) in queries:
if operation == 1:
quantity = numbers.get(value, 0)
if quantity > 0:
occurrences[quantity] = occurrences[quantity] - 1
numbers[value] = numbers.get(value, 0) + 1
occurrences[numbers[value]] = occurrences.get(numbers[value], 0) + 1
elif operation == 2:
quantity = numbers.get(value, 0)
if quantity > 0:
numbers[value] = quantity - 1
occurrences[quantity] = occurrences[quantity] - 1
occurrences[quantity - 1] = occurrences.get(quantity - 1, 0) + 1
else:
result.append(1) if occurrences.get(value) else result.append(0)
return result |
#GuestList:
names = ['tony','steve','thor']
message = ", You are invited!"
print(names[0]+message)
print(names[1]+message)
print(names[2]+message)
| names = ['tony', 'steve', 'thor']
message = ', You are invited!'
print(names[0] + message)
print(names[1] + message)
print(names[2] + message) |
general = {
'provide-edep-targets' : True,
}
edeps = {
'zmdep-b' : {
'rootdir': '../zmdep-b',
'export-includes' : '../zmdep-b',
'buildtypes-map' : {
'debug' : 'mydebug',
'release' : 'myrelease',
},
},
}
subdirs = [ 'libs/core', 'libs/engine' ]
tasks = {
'main' : {
'features' : 'cxxprogram',
'source' : 'main/main.cpp',
'includes' : 'libs',
'use' : 'engine zmdep-b:service',
'rpath' : '.',
'configure' : [
dict(do = 'check-headers', names = 'iostream'),
],
},
}
buildtypes = {
'debug' : {
'cflags.select' : {
'default': '-fPIC -O0 -g', # gcc/clang
'msvc' : '/Od',
},
},
'release' : {
'cflags.select' : {
'default': '-fPIC -O2', # gcc/clang
'msvc' : '/O2',
},
},
'default' : 'debug',
}
| general = {'provide-edep-targets': True}
edeps = {'zmdep-b': {'rootdir': '../zmdep-b', 'export-includes': '../zmdep-b', 'buildtypes-map': {'debug': 'mydebug', 'release': 'myrelease'}}}
subdirs = ['libs/core', 'libs/engine']
tasks = {'main': {'features': 'cxxprogram', 'source': 'main/main.cpp', 'includes': 'libs', 'use': 'engine zmdep-b:service', 'rpath': '.', 'configure': [dict(do='check-headers', names='iostream')]}}
buildtypes = {'debug': {'cflags.select': {'default': '-fPIC -O0 -g', 'msvc': '/Od'}}, 'release': {'cflags.select': {'default': '-fPIC -O2', 'msvc': '/O2'}}, 'default': 'debug'} |
#exercicio 63
termos = int(input('Quantos termos vc quer na sequencia de fibonacci? '))
c = 1
sequencia = 1
sequencia2 = 0
while c != termos:
fi = (sequencia+sequencia2) - ((sequencia+sequencia2)-sequencia2)
print ('{}'.format(fi), end='- ')
sequencia += sequencia2
sequencia2 = sequencia - sequencia2
c += 1 | termos = int(input('Quantos termos vc quer na sequencia de fibonacci? '))
c = 1
sequencia = 1
sequencia2 = 0
while c != termos:
fi = sequencia + sequencia2 - (sequencia + sequencia2 - sequencia2)
print('{}'.format(fi), end='- ')
sequencia += sequencia2
sequencia2 = sequencia - sequencia2
c += 1 |
##Create a target array in the given order
def generate_target_array(nums, index):
length_of_num = len(nums)
target_array = []
for i in range(0, length_of_num):
if index[i] >= length_of_num:
target_array.append(nums[i])
else:
target_array.insert(index[i], nums[i])
return target_array
if __name__ == "__main__":
nums = [0, 1, 2, 3, 4]
index = [0, 1, 2, 2, 1]
print(*generate_target_array(nums, index)) | def generate_target_array(nums, index):
length_of_num = len(nums)
target_array = []
for i in range(0, length_of_num):
if index[i] >= length_of_num:
target_array.append(nums[i])
else:
target_array.insert(index[i], nums[i])
return target_array
if __name__ == '__main__':
nums = [0, 1, 2, 3, 4]
index = [0, 1, 2, 2, 1]
print(*generate_target_array(nums, index)) |
def Capital_letter(func): #This function receive another function
def Wrapper(text):
return func(text).upper()
return Wrapper
@Capital_letter
def message(name):
return f'{name}, you have received a message'
print(message('Yery')) | def capital_letter(func):
def wrapper(text):
return func(text).upper()
return Wrapper
@Capital_letter
def message(name):
return f'{name}, you have received a message'
print(message('Yery')) |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
class Encumbrance:
speed_multiplier = 1
to_hit_modifier = 0
@classmethod
def get_encumbrance_state(cls, weight, capacity):
if weight <= capacity:
return Unencumbered
elif weight <= 1.5 * capacity:
return Burdened
elif weight <= 2 * capacity:
return Stressed
elif weight <= 2.5 * capacity:
return Strained
elif weight <= 3 * capacity:
return Overtaxed
else:
return Overloaded
@classmethod
def modify_speed(cls, speed):
return speed * cls.speed_multiplier
@classmethod
def modify_hit(cls, to_hit):
return to_hit + cls.to_hit_modifier
@classmethod
def describe(cls):
return cls.__name__.lower()
class Unencumbered(Encumbrance):
speed_multiplier = 1
to_hit_modifier = 0
class Burdened(Encumbrance):
speed_multiplier = 0.75
to_hit_modifier = -1
class Stressed(Encumbrance):
speed_multiplier = 0.5
to_hit_modifier = -3
class Strained(Encumbrance):
speed_multiplier = 0.25
to_hit_modifier = -5
class Overtaxed(Encumbrance):
speed_multiplier = 0.125
to_hit_modifier = -7
class Overloaded(Encumbrance):
speed_multiplier = 0
to_hit_modifier = -9
| class Encumbrance:
speed_multiplier = 1
to_hit_modifier = 0
@classmethod
def get_encumbrance_state(cls, weight, capacity):
if weight <= capacity:
return Unencumbered
elif weight <= 1.5 * capacity:
return Burdened
elif weight <= 2 * capacity:
return Stressed
elif weight <= 2.5 * capacity:
return Strained
elif weight <= 3 * capacity:
return Overtaxed
else:
return Overloaded
@classmethod
def modify_speed(cls, speed):
return speed * cls.speed_multiplier
@classmethod
def modify_hit(cls, to_hit):
return to_hit + cls.to_hit_modifier
@classmethod
def describe(cls):
return cls.__name__.lower()
class Unencumbered(Encumbrance):
speed_multiplier = 1
to_hit_modifier = 0
class Burdened(Encumbrance):
speed_multiplier = 0.75
to_hit_modifier = -1
class Stressed(Encumbrance):
speed_multiplier = 0.5
to_hit_modifier = -3
class Strained(Encumbrance):
speed_multiplier = 0.25
to_hit_modifier = -5
class Overtaxed(Encumbrance):
speed_multiplier = 0.125
to_hit_modifier = -7
class Overloaded(Encumbrance):
speed_multiplier = 0
to_hit_modifier = -9 |
_base_ = [
'../_base_/models/r50_multihead.py',
'../_base_/datasets/imagenet_color_sz224_4xbs64.py',
'../_base_/default_runtime.py',
]
# model settings
model = dict(
backbone=dict(frozen_stages=4),
head=dict(num_classes=1000))
# optimizer
optimizer = dict(
type='SGD',
lr=0.01,
momentum=0.9, weight_decay=1e-4, nesterov=True,
paramwise_options={
'(bn|ln|gn)(\d+)?.(weight|bias)': dict(weight_decay=0.),
},
)
# learning policy
lr_config = dict(policy='step', step=[30, 60, 90])
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=90)
| _base_ = ['../_base_/models/r50_multihead.py', '../_base_/datasets/imagenet_color_sz224_4xbs64.py', '../_base_/default_runtime.py']
model = dict(backbone=dict(frozen_stages=4), head=dict(num_classes=1000))
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001, nesterov=True, paramwise_options={'(bn|ln|gn)(\\d+)?.(weight|bias)': dict(weight_decay=0.0)})
lr_config = dict(policy='step', step=[30, 60, 90])
runner = dict(type='EpochBasedRunner', max_epochs=90) |
n = int(input())
if n == 2:
print(2)
else:
if n%2 == 0:
n -= 1
for i in range(n, 1, -2):
flag = True
size = int(pow(i,0.5))
for j in range(3, size+1):
if i % j == 0:
flag = False
break
if flag:
print(i)
break | n = int(input())
if n == 2:
print(2)
else:
if n % 2 == 0:
n -= 1
for i in range(n, 1, -2):
flag = True
size = int(pow(i, 0.5))
for j in range(3, size + 1):
if i % j == 0:
flag = False
break
if flag:
print(i)
break |
height = int(input())
for i in range(height,0,-1):
for j in range(i,height):
print(end=" ")
for j in range(1,i+1):
if(i%2 != 0):
c = chr(i+64)
print(c,end=" ")
else:
print(i,end=" ")
print()
# Sample Input :- 5
# Output :-
# E E E E E
# 4 4 4 4
# C C C
# 2 2
# A
| height = int(input())
for i in range(height, 0, -1):
for j in range(i, height):
print(end=' ')
for j in range(1, i + 1):
if i % 2 != 0:
c = chr(i + 64)
print(c, end=' ')
else:
print(i, end=' ')
print() |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: moveoperators.py
#
# Tests: plots - Pseudocolor, Mesh, FilledBoundary
# operators - Erase, Isosurface, Reflect, Slice, Transform
#
# Defect ID: '1837
#
# Programmer: Brad Whitlock
# Date: Thu Apr 17 16:45:46 PST 2003
#
# Modifications:
# Eric Brugger, Thu May 8 12:57:56 PDT 2003
# Remove a call to ToggleAutoCenterMode since it no longer exists.
#
# Kathleen Bonnell, Thu Aug 28 14:34:57 PDT 2003
# Remove compound var name from subset plots.
#
# Kathleen Bonnell, Wed Mar 17 07:33:40 PST 2004
# Set default Slice atts, as these have changed.
#
# Kathleen Bonnell, Wed May 5 08:13:22 PDT 2004
# Modified Slice atts to get same picture as defaults have changed.
#
# Brad Whitlock, Tue Jan 17 12:14:21 PDT 2006
# Added runTest4.
#
# Mark C. Miller, Wed Jan 20 07:37:11 PST 2010
# Added ability to swtich between Silo's HDF5 and PDB data.
#
# Kathleen Biagas, Thu Jul 11 08:18:42 PDT 2013
# Removed legacy sytle annotation setting.
#
# Kathleen Biagas, Mon Dec 19 15:45:38 PST 2016
# Use FilledBoundary plot for materials instead of Subset.
#
# ----------------------------------------------------------------------------
def InitAnnotation():
# Turn off all annotation except for the bounding box.
a = AnnotationAttributes()
TurnOffAllAnnotations(a)
a.axes2D.visible = 1
a.axes2D.xAxis.label.visible = 0
a.axes2D.yAxis.label.visible = 0
a.axes2D.xAxis.title.visible = 0
a.axes2D.yAxis.title.visible = 0
a.axes3D.bboxFlag = 1
SetAnnotationAttributes(a)
def InitDefaults():
# Set the default reflect operator attributes.
reflect = ReflectAttributes()
reflect.SetReflections(1, 1, 0, 0, 0, 0, 0, 0)
SetDefaultOperatorOptions(reflect)
slice = SliceAttributes()
slice.project2d = 0
slice.SetAxisType(slice.XAxis)
slice.SetFlip(1)
SetDefaultOperatorOptions(slice)
def setTheFirstView():
# Set the view
v = View3DAttributes()
v.viewNormal = (-0.695118, 0.351385, 0.627168)
v.focus = (-10, 0, 0)
v.viewUp = (0.22962, 0.935229, -0.269484)
v.viewAngle = 30
v.parallelScale = 17.3205
v.nearPlane = -70
v.farPlane = 70
v.perspective = 1
SetView3D(v)
#
# Test operator promotion, demotion, and removal.
#
def runTest1():
OpenDatabase(silo_data_path("noise.silo"))
# Set up a plot with a few operators.
AddPlot("Pseudocolor", "hardyglobal")
AddOperator("Isosurface")
AddOperator("Slice")
AddOperator("Reflect")
DrawPlots()
setTheFirstView()
# Take a picture of the initial setup.
Test("moveoperator_0")
# Move the reflect so that it is before the slice in the pipeline.
# The pipeline will be: Isosurface, Reflect, Slice
DemoteOperator(2)
DrawPlots()
Test("moveoperator_1")
# Move the reflect operator back so that the pipeline matches the
# initial configuration: Isosurface, Slice, Reflect
PromoteOperator(1)
DrawPlots()
Test("moveoperator_2")
# Remove the slice operator from the middle, resulting in:
# Isosurface, Reflect
RemoveOperator(1)
DrawPlots()
Test("moveoperator_3")
# Remove the Isosurface operator, resulting in: Reflect
RemoveOperator(0)
DrawPlots()
Test("moveoperator_4")
# Remove the Reflect operator
RemoveOperator(0)
DrawPlots()
Test("moveoperator_5")
DeleteAllPlots()
#
# Test removing an operator from more than one plot at the same time.
#
def runTest2():
all = 1
# Set up a couple plots of globe
OpenDatabase(silo_data_path("globe.silo"))
AddPlot("Pseudocolor", "u")
AddPlot("Mesh", "mesh1")
# Add a reflect operator to both plots.
AddOperator("Reflect", all)
DrawPlots()
Test("moveoperator_6")
# Remove the operator from both plots.
RemoveOperator(0, all)
DrawPlots()
Test("moveoperator_7")
DeleteAllPlots()
#
# Test setting attributes for multiple operators of the same type.
#
def runTest3():
# Set up a couple plots of globe
OpenDatabase(silo_data_path("globe.silo"))
AddPlot("Pseudocolor", "u")
pc = PseudocolorAttributes()
pc.SetOpacityType(pc.Constant)
pc.opacity = 0.2
SetPlotOptions(pc)
AddPlot("FilledBoundary", "mat1")
# The subset plot is the active plot, add a couple transform
# operators to it.
AddOperator("Transform")
AddOperator("Transform")
# Set the attributes for the *first* transform operator.
# This results in a full size globe translated up in Y.
t0 = TransformAttributes()
t0.doTranslate = 1
t0.translateY = 15
SetOperatorOptions(t0, 0)
DrawPlots()
Test("moveoperator_8")
# Set the attributes for the *second* transform operator.
# The plot has been translated, now scale it. Since it has already
# been translated, this will also translate it a little in Y.
t1 = TransformAttributes()
t1.doScale = 1
t1.scaleX = 0.5
t1.scaleY = 0.5
t1.scaleZ = 0.5
SetOperatorOptions(t1, 1)
Test("moveoperator_9")
# Demote the last operator to reverse the order of the transformations.
DemoteOperator(1)
# Make the pc plot opaque again
SetActivePlots(0)
pc.SetOpacityType(pc.FullyOpaque)
SetPlotOptions(pc)
DrawPlots()
Test("moveoperator_10")
DeleteAllPlots()
#
# Test that removing an operator using the RemoveOperator(i) method causes
# the vis window to get redrawn.
#
def runTest4():
OpenDatabase(silo_data_path("curv2d.silo"))
AddPlot("Pseudocolor", "d")
AddOperator("Isosurface")
DrawPlots()
Test("moveoperator_11")
RemoveOperator(0)
Test("moveoperator_12")
DeleteAllPlots()
#
# Set up the environment and run all of the tests.
#
def runTests():
InitAnnotation()
InitDefaults()
runTest1()
runTest2()
runTest3()
runTest4()
# Run the tests.
runTests()
Exit()
| def init_annotation():
a = annotation_attributes()
turn_off_all_annotations(a)
a.axes2D.visible = 1
a.axes2D.xAxis.label.visible = 0
a.axes2D.yAxis.label.visible = 0
a.axes2D.xAxis.title.visible = 0
a.axes2D.yAxis.title.visible = 0
a.axes3D.bboxFlag = 1
set_annotation_attributes(a)
def init_defaults():
reflect = reflect_attributes()
reflect.SetReflections(1, 1, 0, 0, 0, 0, 0, 0)
set_default_operator_options(reflect)
slice = slice_attributes()
slice.project2d = 0
slice.SetAxisType(slice.XAxis)
slice.SetFlip(1)
set_default_operator_options(slice)
def set_the_first_view():
v = view3_d_attributes()
v.viewNormal = (-0.695118, 0.351385, 0.627168)
v.focus = (-10, 0, 0)
v.viewUp = (0.22962, 0.935229, -0.269484)
v.viewAngle = 30
v.parallelScale = 17.3205
v.nearPlane = -70
v.farPlane = 70
v.perspective = 1
set_view3_d(v)
def run_test1():
open_database(silo_data_path('noise.silo'))
add_plot('Pseudocolor', 'hardyglobal')
add_operator('Isosurface')
add_operator('Slice')
add_operator('Reflect')
draw_plots()
set_the_first_view()
test('moveoperator_0')
demote_operator(2)
draw_plots()
test('moveoperator_1')
promote_operator(1)
draw_plots()
test('moveoperator_2')
remove_operator(1)
draw_plots()
test('moveoperator_3')
remove_operator(0)
draw_plots()
test('moveoperator_4')
remove_operator(0)
draw_plots()
test('moveoperator_5')
delete_all_plots()
def run_test2():
all = 1
open_database(silo_data_path('globe.silo'))
add_plot('Pseudocolor', 'u')
add_plot('Mesh', 'mesh1')
add_operator('Reflect', all)
draw_plots()
test('moveoperator_6')
remove_operator(0, all)
draw_plots()
test('moveoperator_7')
delete_all_plots()
def run_test3():
open_database(silo_data_path('globe.silo'))
add_plot('Pseudocolor', 'u')
pc = pseudocolor_attributes()
pc.SetOpacityType(pc.Constant)
pc.opacity = 0.2
set_plot_options(pc)
add_plot('FilledBoundary', 'mat1')
add_operator('Transform')
add_operator('Transform')
t0 = transform_attributes()
t0.doTranslate = 1
t0.translateY = 15
set_operator_options(t0, 0)
draw_plots()
test('moveoperator_8')
t1 = transform_attributes()
t1.doScale = 1
t1.scaleX = 0.5
t1.scaleY = 0.5
t1.scaleZ = 0.5
set_operator_options(t1, 1)
test('moveoperator_9')
demote_operator(1)
set_active_plots(0)
pc.SetOpacityType(pc.FullyOpaque)
set_plot_options(pc)
draw_plots()
test('moveoperator_10')
delete_all_plots()
def run_test4():
open_database(silo_data_path('curv2d.silo'))
add_plot('Pseudocolor', 'd')
add_operator('Isosurface')
draw_plots()
test('moveoperator_11')
remove_operator(0)
test('moveoperator_12')
delete_all_plots()
def run_tests():
init_annotation()
init_defaults()
run_test1()
run_test2()
run_test3()
run_test4()
run_tests()
exit() |
gibber = input("What's the gibberish?: ")
direction = input("Left/Right?: ")
retry = int(input("How much do you want to try?: "))
charlist = "abcdefghijklmnopqrstuvwxyz "
dictionary = {}
index = 0
for e in charlist:
dictionary[e] = index
index += 1
jump = 1
if direction == "Right":
for cycle in range(retry):
notsecret = ""
for char in gibber:
index = dictionary[char]
notsecret += charlist[(index - jump) % len(dictionary)]
jump += 1
print(notsecret)
else:
for cycle in range(retry):
notsecret = ""
for char in gibber:
index = dictionary[char]
notsecret += charlist[(index + jump) % len(dictionary)]
jump += 1
print(notsecret)
| gibber = input("What's the gibberish?: ")
direction = input('Left/Right?: ')
retry = int(input('How much do you want to try?: '))
charlist = 'abcdefghijklmnopqrstuvwxyz '
dictionary = {}
index = 0
for e in charlist:
dictionary[e] = index
index += 1
jump = 1
if direction == 'Right':
for cycle in range(retry):
notsecret = ''
for char in gibber:
index = dictionary[char]
notsecret += charlist[(index - jump) % len(dictionary)]
jump += 1
print(notsecret)
else:
for cycle in range(retry):
notsecret = ''
for char in gibber:
index = dictionary[char]
notsecret += charlist[(index + jump) % len(dictionary)]
jump += 1
print(notsecret) |
def find(f, df, ddf, a, b, eps):
fa = f(a)
dfa = df(a)
ddfa = ddf(a)
fb = f(b)
dfb = df(b)
ddfb = ddf(b)
if not (
(fa * fb < 0) and
((dfa > 0 and dfb > 0) or (dfa < 0 and dfb < 0)) and
((ddfa > 0 and ddfb > 0) or (ddfa < 0 and ddfb < 0))
):
return
currx = a if fa * ddfa > 0 else b
print(f"X={currx}; F(X)={f(currx)}")
shouldStop = False
while True:
prevx = currx
currx = prevx - f(prevx)**2 / (f(prevx + f(prevx)) - f(prevx))
print(f"X={currx}; F(X)={f(currx)}")
if abs(currx - prevx) < 2 * eps:
if shouldStop:
break
shouldStop = True
| def find(f, df, ddf, a, b, eps):
fa = f(a)
dfa = df(a)
ddfa = ddf(a)
fb = f(b)
dfb = df(b)
ddfb = ddf(b)
if not (fa * fb < 0 and (dfa > 0 and dfb > 0 or (dfa < 0 and dfb < 0)) and (ddfa > 0 and ddfb > 0 or (ddfa < 0 and ddfb < 0))):
return
currx = a if fa * ddfa > 0 else b
print(f'X={currx}; F(X)={f(currx)}')
should_stop = False
while True:
prevx = currx
currx = prevx - f(prevx) ** 2 / (f(prevx + f(prevx)) - f(prevx))
print(f'X={currx}; F(X)={f(currx)}')
if abs(currx - prevx) < 2 * eps:
if shouldStop:
break
should_stop = True |
class Card:
# Game card.
def __init__(self, number, color, ability, wild):
# Number on the face of the card
self.number = number
# Which color is the thing
self.color = color
# Draw 2 / Reverse etc
self.ability = ability
# Wild card?
self.wild = wild
def __eq__(self, other):
return (self.number == other.number) and (self.color == other.color) and (self.ability == other.ability) and (self.wild == other.wild)
cards = [
Card(0, (255, 0, 0), None, None),
Card(1, (255, 0, 0), None, None),
Card(2, (255, 0, 0), None, None),
Card(3, (255, 0, 0), None, None),
Card(4, (255, 0, 0), None, None),
Card(5, (255, 0, 0), None, None),
Card(6, (255, 0, 0), None, None),
Card(7, (255, 0, 0), None, None),
Card(8, (255, 0, 0), None, None),
Card(9, (255, 0, 0), None, None),
Card(1, (255, 0, 0), None, None),
Card(2, (255, 0, 0), None, None),
Card(3, (255, 0, 0), None, None),
Card(4, (255, 0, 0), None, None),
Card(5, (255, 0, 0), None, None),
Card(6, (255, 0, 0), None, None),
Card(7, (255, 0, 0), None, None),
Card(8, (255, 0, 0), None, None),
Card(9, (255, 0, 0), None, None),
# Ability cards
Card("d2", (255, 0, 0), "d2", None),
Card("d2", (255, 0, 0), "d2", None),
Card("skip", (255, 0, 0), "skip", None),
Card("skip", (255, 0, 0), "skip", None),
Card("rev", (255, 0, 0), "rev", None),
Card("rev", (255, 0, 0), "rev", None),
#Green
Card(0, (0, 255, 0), None, None),
Card(1, (0, 255, 0), None, None),
Card(2, (0, 255, 0), None, None),
Card(3, (0, 255, 0), None, None),
Card(4, (0, 255, 0), None, None),
Card(5, (0, 255, 0), None, None),
Card(6, (0, 255, 0), None, None),
Card(7, (0, 255, 0), None, None),
Card(8, (0, 255, 0), None, None),
Card(9, (0, 255, 0), None, None),
Card(1, (0, 255, 0), None, None),
Card(2, (0, 255, 0), None, None),
Card(3, (0, 255, 0), None, None),
Card(4, (0, 255, 0), None, None),
Card(5, (0, 255, 0), None, None),
Card(6, (0, 255, 0), None, None),
Card(7, (0, 255, 0), None, None),
Card(8, (0, 255, 0), None, None),
Card(9, (0, 255, 0), None, None),
# Ability cards
Card("d2", (0, 255, 0), "d2", None),
Card("d2", (0, 255, 0), "d2", None),
Card("skip", (0, 255, 0), "skip", None),
Card("skip", (0, 255, 0), "skip", None),
Card("rev", (0, 255, 0), "rev", None),
Card("rev", (0, 255, 0), "rev", None),
# Blue
Card(0, (0, 0, 255), None, None),
Card(1, (0, 0, 255), None, None),
Card(2, (0, 0, 255), None, None),
Card(3, (0, 0, 255), None, None),
Card(4, (0, 0, 255), None, None),
Card(5, (0, 0, 255), None, None),
Card(6, (0, 0, 255), None, None),
Card(7, (0, 0, 255), None, None),
Card(8, (0, 0, 255), None, None),
Card(9, (0, 0, 255), None, None),
Card(1, (0, 0, 255), None, None),
Card(2, (0, 0, 255), None, None),
Card(3, (0, 0, 255), None, None),
Card(4, (0, 0, 255), None, None),
Card(5, (0, 0, 255), None, None),
Card(6, (0, 0, 255), None, None),
Card(7, (0, 0, 255), None, None),
Card(8, (0, 0, 255), None, None),
Card(9, (0, 0, 255), None, None),
# Ability cards
Card("d2", (0, 0, 255), "d2", None),
Card("d2", (0, 0, 255), "d2", None),
Card("skip", (0, 0, 255), "skip", None),
Card("skip", (0, 0, 255), "skip", None),
Card("rev", (0, 0, 255), "rev", None),
Card("rev", (0, 0, 255), "rev", None),
# Yellow
Card(0, (250, 192, 32), None, None),
Card(1, (250, 192, 32), None, None),
Card(2, (250, 192, 32), None, None),
Card(3, (250, 192, 32), None, None),
Card(4, (250, 192, 32), None, None),
Card(5, (250, 192, 32), None, None),
Card(6, (250, 192, 32), None, None),
Card(7, (250, 192, 32), None, None),
Card(8, (250, 192, 32), None, None),
Card(9, (250, 192, 32), None, None),
Card(1, (250, 192, 32), None, None),
Card(2, (250, 192, 32), None, None),
Card(3, (250, 192, 32), None, None),
Card(4, (250, 192, 32), None, None),
Card(5, (250, 192, 32), None, None),
Card(6, (250, 192, 32), None, None),
Card(7, (250, 192, 32), None, None),
Card(8, (250, 192, 32), None, None),
Card(9, (250, 192, 32), None, None),
# Ability cards
Card("d2", (250, 192, 32), "d2", None),
Card("d2", (250, 192, 32), "d2", None),
Card("skip", (250, 192, 32), "skip", None),
Card("skip", (250, 192, 32), "skip", None),
Card("rev", (250, 192, 32), "rev", None),
Card("rev", (250, 192, 32), "rev", None),
] | class Card:
def __init__(self, number, color, ability, wild):
self.number = number
self.color = color
self.ability = ability
self.wild = wild
def __eq__(self, other):
return self.number == other.number and self.color == other.color and (self.ability == other.ability) and (self.wild == other.wild)
cards = [card(0, (255, 0, 0), None, None), card(1, (255, 0, 0), None, None), card(2, (255, 0, 0), None, None), card(3, (255, 0, 0), None, None), card(4, (255, 0, 0), None, None), card(5, (255, 0, 0), None, None), card(6, (255, 0, 0), None, None), card(7, (255, 0, 0), None, None), card(8, (255, 0, 0), None, None), card(9, (255, 0, 0), None, None), card(1, (255, 0, 0), None, None), card(2, (255, 0, 0), None, None), card(3, (255, 0, 0), None, None), card(4, (255, 0, 0), None, None), card(5, (255, 0, 0), None, None), card(6, (255, 0, 0), None, None), card(7, (255, 0, 0), None, None), card(8, (255, 0, 0), None, None), card(9, (255, 0, 0), None, None), card('d2', (255, 0, 0), 'd2', None), card('d2', (255, 0, 0), 'd2', None), card('skip', (255, 0, 0), 'skip', None), card('skip', (255, 0, 0), 'skip', None), card('rev', (255, 0, 0), 'rev', None), card('rev', (255, 0, 0), 'rev', None), card(0, (0, 255, 0), None, None), card(1, (0, 255, 0), None, None), card(2, (0, 255, 0), None, None), card(3, (0, 255, 0), None, None), card(4, (0, 255, 0), None, None), card(5, (0, 255, 0), None, None), card(6, (0, 255, 0), None, None), card(7, (0, 255, 0), None, None), card(8, (0, 255, 0), None, None), card(9, (0, 255, 0), None, None), card(1, (0, 255, 0), None, None), card(2, (0, 255, 0), None, None), card(3, (0, 255, 0), None, None), card(4, (0, 255, 0), None, None), card(5, (0, 255, 0), None, None), card(6, (0, 255, 0), None, None), card(7, (0, 255, 0), None, None), card(8, (0, 255, 0), None, None), card(9, (0, 255, 0), None, None), card('d2', (0, 255, 0), 'd2', None), card('d2', (0, 255, 0), 'd2', None), card('skip', (0, 255, 0), 'skip', None), card('skip', (0, 255, 0), 'skip', None), card('rev', (0, 255, 0), 'rev', None), card('rev', (0, 255, 0), 'rev', None), card(0, (0, 0, 255), None, None), card(1, (0, 0, 255), None, None), card(2, (0, 0, 255), None, None), card(3, (0, 0, 255), None, None), card(4, (0, 0, 255), None, None), card(5, (0, 0, 255), None, None), card(6, (0, 0, 255), None, None), card(7, (0, 0, 255), None, None), card(8, (0, 0, 255), None, None), card(9, (0, 0, 255), None, None), card(1, (0, 0, 255), None, None), card(2, (0, 0, 255), None, None), card(3, (0, 0, 255), None, None), card(4, (0, 0, 255), None, None), card(5, (0, 0, 255), None, None), card(6, (0, 0, 255), None, None), card(7, (0, 0, 255), None, None), card(8, (0, 0, 255), None, None), card(9, (0, 0, 255), None, None), card('d2', (0, 0, 255), 'd2', None), card('d2', (0, 0, 255), 'd2', None), card('skip', (0, 0, 255), 'skip', None), card('skip', (0, 0, 255), 'skip', None), card('rev', (0, 0, 255), 'rev', None), card('rev', (0, 0, 255), 'rev', None), card(0, (250, 192, 32), None, None), card(1, (250, 192, 32), None, None), card(2, (250, 192, 32), None, None), card(3, (250, 192, 32), None, None), card(4, (250, 192, 32), None, None), card(5, (250, 192, 32), None, None), card(6, (250, 192, 32), None, None), card(7, (250, 192, 32), None, None), card(8, (250, 192, 32), None, None), card(9, (250, 192, 32), None, None), card(1, (250, 192, 32), None, None), card(2, (250, 192, 32), None, None), card(3, (250, 192, 32), None, None), card(4, (250, 192, 32), None, None), card(5, (250, 192, 32), None, None), card(6, (250, 192, 32), None, None), card(7, (250, 192, 32), None, None), card(8, (250, 192, 32), None, None), card(9, (250, 192, 32), None, None), card('d2', (250, 192, 32), 'd2', None), card('d2', (250, 192, 32), 'd2', None), card('skip', (250, 192, 32), 'skip', None), card('skip', (250, 192, 32), 'skip', None), card('rev', (250, 192, 32), 'rev', None), card('rev', (250, 192, 32), 'rev', None)] |
#!/usr/bin/env python3
def get_input() -> list[str]:
with open('./input', 'r') as f:
return [v for v in [v.strip() for v in f.readlines()] if v]
def _get_input_raw() -> list[str]:
with open('./input', 'r') as f:
return [v.strip() for v in f.readlines()]
def get_input_by_chunks() -> list[list[str]]:
raw_input = _get_input_raw()
lists = [list()]
for imp in raw_input:
if imp:
lists[-1].append(imp)
else:
lists.append(list())
return lists
yes_questions_count = 0
for chunk in get_input_by_chunks():
yes_questions = set('abcdefghijklmnopqrstuvwxyz')
for line in chunk:
yes_questions = yes_questions.intersection(set(line))
yes_questions_count += len(yes_questions)
print(yes_questions_count)
| def get_input() -> list[str]:
with open('./input', 'r') as f:
return [v for v in [v.strip() for v in f.readlines()] if v]
def _get_input_raw() -> list[str]:
with open('./input', 'r') as f:
return [v.strip() for v in f.readlines()]
def get_input_by_chunks() -> list[list[str]]:
raw_input = _get_input_raw()
lists = [list()]
for imp in raw_input:
if imp:
lists[-1].append(imp)
else:
lists.append(list())
return lists
yes_questions_count = 0
for chunk in get_input_by_chunks():
yes_questions = set('abcdefghijklmnopqrstuvwxyz')
for line in chunk:
yes_questions = yes_questions.intersection(set(line))
yes_questions_count += len(yes_questions)
print(yes_questions_count) |
#Anagram Detection
#reads 2 strings
st1 = input("Enter a string: ")
st2 = input("Enter another string: ")
#check if their lengths are equal
if len(st1) == len(st2):
#create a list
n = len(st1)-1
list1 = list()
while n >= 0:
list1.append(st1[n])
n -= 1
m = len(st2)-1
list2 = list()
while m >= 0:
list2.append(st2[m])
m -= 1
#sort the list
list1.sort()
list2.sort()
#check if lists are equal and print the result
print("Anagram") if list1 == list2 else print("Not an anagram")
else:
print("Not an anagram")
| st1 = input('Enter a string: ')
st2 = input('Enter another string: ')
if len(st1) == len(st2):
n = len(st1) - 1
list1 = list()
while n >= 0:
list1.append(st1[n])
n -= 1
m = len(st2) - 1
list2 = list()
while m >= 0:
list2.append(st2[m])
m -= 1
list1.sort()
list2.sort()
print('Anagram') if list1 == list2 else print('Not an anagram')
else:
print('Not an anagram') |
TURNS = {"R": -1j, "L": 1j}
instructions = tuple((inst[0], int(inst[1:])) for inst in open("input").read().strip().split(", "))
position, direction = (0 + 0j), (0 + 1j)
visited_locations = set()
first_twice_location = 0 + 0j
for turn, dist in instructions:
direction *= TURNS[turn]
for _ in range(dist):
visited_locations.add(position)
position += direction
if not first_twice_location and position in visited_locations:
first_twice_location = position
print(f"Answer part one: {int(abs(position.real) + abs(position.imag))}")
print(f"Answer part two: {int(abs(first_twice_location.real) + abs(first_twice_location.imag))}")
| turns = {'R': -1j, 'L': 1j}
instructions = tuple(((inst[0], int(inst[1:])) for inst in open('input').read().strip().split(', ')))
(position, direction) = (0 + 0j, 0 + 1j)
visited_locations = set()
first_twice_location = 0 + 0j
for (turn, dist) in instructions:
direction *= TURNS[turn]
for _ in range(dist):
visited_locations.add(position)
position += direction
if not first_twice_location and position in visited_locations:
first_twice_location = position
print(f'Answer part one: {int(abs(position.real) + abs(position.imag))}')
print(f'Answer part two: {int(abs(first_twice_location.real) + abs(first_twice_location.imag))}') |
#!/usr/bin/env python3
# Define n
n = 5
# Store Outputs
sum = 0
facr = 1
# Loop
for i in range(1,n+1):
sum = sum + i
facr = facr * i
print(n,sum,facr)
| n = 5
sum = 0
facr = 1
for i in range(1, n + 1):
sum = sum + i
facr = facr * i
print(n, sum, facr) |
AppLayout(header=header_button,
left_sidebar=None,
center=center_button,
right_sidebar=None,
footer=footer_button)
| app_layout(header=header_button, left_sidebar=None, center=center_button, right_sidebar=None, footer=footer_button) |
class Result:
def __init__(self, result: bool, error = None, item = None, list = [], comment = None):
self.result = result
self.error = error
self.item = item
self.list = list
self.comment = comment
| class Result:
def __init__(self, result: bool, error=None, item=None, list=[], comment=None):
self.result = result
self.error = error
self.item = item
self.list = list
self.comment = comment |
# Copyright 2019 StreamSets Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Set up batch and record
batch = sdc.createBatch()
record = sdc.createRecord('bindings test')
record.value = {}
# Test constants
record.value['batchSize'] = sdc.batchSize
record.value['numThreads'] = sdc.numThreads
record.value['lastOffsets'] = sdc.lastOffsets
record.value['params'] = sdc.userParams
# Test sdcFunctions
record.value['isStopped()'] = sdc.isStopped()
record.value['pipelineParameters()'] = sdc.pipelineParameters()
record.value['isPreview()'] = sdc.isPreview()
record.value['createMap()'] = sdc.createMap(False)
record.value['createListMap()'] = sdc.createMap(True)
record.value['getFieldNull()-false'] = sdc.getFieldNull(record, '/isStopped()')
record.value['getFieldNull()-null'] = sdc.getFieldNull(record, '/not-a-real-fieldpath')
records_list = [record]
# Error
batch.addError(record, 'this is only a test')
# Event
eventRecord = sdc.createEvent('new test event', 123)
batch.addEvent(eventRecord)
# Test batch methods
record.value['batch.size()'] = batch.size()
record.value['batch.errorCount()'] = batch.errorCount()
record.value['batch.eventCount()'] = batch.eventCount()
# public void add(ScriptRecord scriptRecord)
batch.add(record)
# public void add(ScriptRecord[] scriptRecords)
batch.add(records_list)
# Process the batch and commit new offset
batch.process('newEntityName', 'newEntityOffset')
| batch = sdc.createBatch()
record = sdc.createRecord('bindings test')
record.value = {}
record.value['batchSize'] = sdc.batchSize
record.value['numThreads'] = sdc.numThreads
record.value['lastOffsets'] = sdc.lastOffsets
record.value['params'] = sdc.userParams
record.value['isStopped()'] = sdc.isStopped()
record.value['pipelineParameters()'] = sdc.pipelineParameters()
record.value['isPreview()'] = sdc.isPreview()
record.value['createMap()'] = sdc.createMap(False)
record.value['createListMap()'] = sdc.createMap(True)
record.value['getFieldNull()-false'] = sdc.getFieldNull(record, '/isStopped()')
record.value['getFieldNull()-null'] = sdc.getFieldNull(record, '/not-a-real-fieldpath')
records_list = [record]
batch.addError(record, 'this is only a test')
event_record = sdc.createEvent('new test event', 123)
batch.addEvent(eventRecord)
record.value['batch.size()'] = batch.size()
record.value['batch.errorCount()'] = batch.errorCount()
record.value['batch.eventCount()'] = batch.eventCount()
batch.add(record)
batch.add(records_list)
batch.process('newEntityName', 'newEntityOffset') |
def select_outside(low, high, *values):
result = []
for v in values:
if (v < low) or (v > high):
result.append(v)
return result
print(select_outside(0, 1.0, 0.3, -0.2, -0.5, 0.4, 1.7))
| def select_outside(low, high, *values):
result = []
for v in values:
if v < low or v > high:
result.append(v)
return result
print(select_outside(0, 1.0, 0.3, -0.2, -0.5, 0.4, 1.7)) |
'''
Python tuple is a sequence,
which can store heterogeneous data
types such as integers, floats, strings,
lists, and dictionaries. Tuples are written
with round brackets and individual objects
within the tuple are separated by a comma.
The two biggest differences between a tuple
and a list are that a tuple is immutable
and allows you to embed one tuple inside another.
There are many ways to input values
into the tuple most of them are not so
friendly and here goes the easilest one
'''
a=[]
n=int(input('Enter size of tuple: '))
for i in range(n):
a.append(int(input('Enter Element: ')))
print(f'\nElements of the variable are: {a}')
print(f'Type of what we created is: {type(a)}')
a=tuple(a)
print(f'\nElements of the tuple are: {a}')
print(f'Type of what we created is: {type(a)}')
#other ways to create and print Tuples:
tuple1 = () # An empty tuple.
tuple2 = (1, 2, 3) # A tuple containing three integer objects.
# A tuple containing string objects.
tuple3 = ("America", "Israel","Canada", "Japan")
# A tuple containing an integer, a string, and a boolean object.
tuple4 = (100, "Italy", False)
# A tuple containing another tuple.
tuple5 = (50, ("America", "Canada", "Japan"))
# The extra comma, tells the parentheses are used to hold a singleton tuple.
tuple6 = (25,)
print(f'\n Empty tuple: {tuple1}')
print(f'\n Tuple containing three integer objects: {tuple2}')
print(f'\n Tuple containing string objects: {tuple3}')
print(f'\n Tuple containing an integer, a string, and a boolean objects: {tuple4}')
print(f'\n Tuple containing another tuple: {tuple5}')
print(f'\n Tuple containing singleton object: {tuple6}')
| """
Python tuple is a sequence,
which can store heterogeneous data
types such as integers, floats, strings,
lists, and dictionaries. Tuples are written
with round brackets and individual objects
within the tuple are separated by a comma.
The two biggest differences between a tuple
and a list are that a tuple is immutable
and allows you to embed one tuple inside another.
There are many ways to input values
into the tuple most of them are not so
friendly and here goes the easilest one
"""
a = []
n = int(input('Enter size of tuple: '))
for i in range(n):
a.append(int(input('Enter Element: ')))
print(f'\nElements of the variable are: {a}')
print(f'Type of what we created is: {type(a)}')
a = tuple(a)
print(f'\nElements of the tuple are: {a}')
print(f'Type of what we created is: {type(a)}')
tuple1 = ()
tuple2 = (1, 2, 3)
tuple3 = ('America', 'Israel', 'Canada', 'Japan')
tuple4 = (100, 'Italy', False)
tuple5 = (50, ('America', 'Canada', 'Japan'))
tuple6 = (25,)
print(f'\n Empty tuple: {tuple1}')
print(f'\n Tuple containing three integer objects: {tuple2}')
print(f'\n Tuple containing string objects: {tuple3}')
print(f'\n Tuple containing an integer, a string, and a boolean objects: {tuple4}')
print(f'\n Tuple containing another tuple: {tuple5}')
print(f'\n Tuple containing singleton object: {tuple6}') |
'''Exceptions.
:copyright: 2021, Jeroen van der Heijden <jeroen@cesbit.com>
'''
class CompileError(Exception):
pass
class KeywordError(CompileError):
pass
class ReKeywordsChangedError(CompileError):
pass
class NameAssignedError(CompileError):
pass
class MissingRefError(CompileError):
pass
class MissingStartError(CompileError):
pass
class UnusedElementError(CompileError):
pass
class ParseError(Exception):
pass
class MaxRecursionError(ParseError):
pass
| """Exceptions.
:copyright: 2021, Jeroen van der Heijden <jeroen@cesbit.com>
"""
class Compileerror(Exception):
pass
class Keyworderror(CompileError):
pass
class Rekeywordschangederror(CompileError):
pass
class Nameassignederror(CompileError):
pass
class Missingreferror(CompileError):
pass
class Missingstarterror(CompileError):
pass
class Unusedelementerror(CompileError):
pass
class Parseerror(Exception):
pass
class Maxrecursionerror(ParseError):
pass |
class sensorVariables:
def __init__(self):
self.elevation = None
self.vfov = None
self.north = None
self.roll = None
self.range = None
self.azimuth = None
self.model = None
self.fov = None
self.type = None
self.version = None
@classmethod
def DroneSensor(cls):
cls.elevation = "0.0"
cls.vfov = "60"
cls.north = "227"
cls.roll = "0.0"
cls.range = None
cls.azimuth = "46"
cls.model = "Drone Camera"
cls.fov = None
cls.type = "r-e"
cls.version = "0.6"
return cls | class Sensorvariables:
def __init__(self):
self.elevation = None
self.vfov = None
self.north = None
self.roll = None
self.range = None
self.azimuth = None
self.model = None
self.fov = None
self.type = None
self.version = None
@classmethod
def drone_sensor(cls):
cls.elevation = '0.0'
cls.vfov = '60'
cls.north = '227'
cls.roll = '0.0'
cls.range = None
cls.azimuth = '46'
cls.model = 'Drone Camera'
cls.fov = None
cls.type = 'r-e'
cls.version = '0.6'
return cls |
glossary = {
'and' : 'Logical and operator',
'or' : 'Logical or operator',
'False' : 'Boolean false value',
'True' : 'Boolean true value',
'for' : 'To create for loop',
}
print("and: " + glossary['and'] + "\n")
print("or: " + glossary['or'] + "\n")
print("False: " + glossary['False'] + "\n")
print("True: " + glossary['True'] + "\n")
print("for: " + glossary['for']) | glossary = {'and': 'Logical and operator', 'or': 'Logical or operator', 'False': 'Boolean false value', 'True': 'Boolean true value', 'for': 'To create for loop'}
print('and: ' + glossary['and'] + '\n')
print('or: ' + glossary['or'] + '\n')
print('False: ' + glossary['False'] + '\n')
print('True: ' + glossary['True'] + '\n')
print('for: ' + glossary['for']) |
def test_add():
class Number:
def __add__(self, other):
return 4 + other
def __radd__(self, other):
return other + 4
a = Number()
assert 3 + a == 7
assert a + 3 == 7
| def test_add():
class Number:
def __add__(self, other):
return 4 + other
def __radd__(self, other):
return other + 4
a = number()
assert 3 + a == 7
assert a + 3 == 7 |
MinZoneNum = 0
MaxZoneNum = 999
UberZoneEntId = 0
LevelMgrEntId = 1000
EditMgrEntId = 1001
| min_zone_num = 0
max_zone_num = 999
uber_zone_ent_id = 0
level_mgr_ent_id = 1000
edit_mgr_ent_id = 1001 |
allwords=[]
for category in bag_of_words.keys():
for word in bag_of_words[category].keys():
if word not in allwords:
allwords.append(word)
freq_term_matrix=[]
for category in bag_of_words.keys():
new=[]
for column in range(0,len(allwords)):
if allwords[column] in bag_of_words[category].keys():
new.append(bag_of_words[category][allwords[column]])
else:
new.append(0)
freq_term_matrix.append(new)
file=open("example.txt","w")
array=["can","could","may","might","must","will"]
file.write("\t")
for x in range(0,len(array)):
file.write("\t"+array[x])
tfidf = TfidfTransformer()
fitted=tfidf.fit(freq_term_matrix)
file.write("\n")
x=0
for category in bag_of_words.keys():
file.write(category+"\t")
for word in array:
file.write(str(freq_term_matrix[x][allwords.index(word)])+"\t")
file.write("\n")
x+=1
file.close() | allwords = []
for category in bag_of_words.keys():
for word in bag_of_words[category].keys():
if word not in allwords:
allwords.append(word)
freq_term_matrix = []
for category in bag_of_words.keys():
new = []
for column in range(0, len(allwords)):
if allwords[column] in bag_of_words[category].keys():
new.append(bag_of_words[category][allwords[column]])
else:
new.append(0)
freq_term_matrix.append(new)
file = open('example.txt', 'w')
array = ['can', 'could', 'may', 'might', 'must', 'will']
file.write('\t')
for x in range(0, len(array)):
file.write('\t' + array[x])
tfidf = tfidf_transformer()
fitted = tfidf.fit(freq_term_matrix)
file.write('\n')
x = 0
for category in bag_of_words.keys():
file.write(category + '\t')
for word in array:
file.write(str(freq_term_matrix[x][allwords.index(word)]) + '\t')
file.write('\n')
x += 1
file.close() |
fh = open("Headlines", 'r')
Word = input("Type your Word Here:")
S = " "
count = 1
while S:
S = fh.readline()
L = S.split()
if Word in L:
print("Line Number:", count, ":", S)
count += 1
| fh = open('Headlines', 'r')
word = input('Type your Word Here:')
s = ' '
count = 1
while S:
s = fh.readline()
l = S.split()
if Word in L:
print('Line Number:', count, ':', S)
count += 1 |
string = "ugknbfddgicrmopn"
string = "aaa"
string = "jchzalrnumimnmhp"
string = "haegwjzuvuyypxyu"
string = "dvszwmarrgswjxmb"
def check_vowels(string):
vowels = 0
vowels += string.count("a")
vowels += string.count("e")
vowels += string.count("i")
vowels += string.count("o")
vowels += string.count("u")
return vowels >= 3
def check_doubles(string):
for i in range(len(string)-1):
if string[i] == string[i+1]:
return True
return False
def check_barred(string):
barred = 0
barred += string.count("ab")
barred += string.count("cd")
barred += string.count("pq")
barred += string.count("xy")
return barred > 0
nbr_nice = 0
with open("input.txt") as f:
string = f.readline().strip()
while string != "":
nice = check_vowels(string) and check_doubles(string) and not check_barred(string)
print(string,"->",nice)
if nice:
nbr_nice += 1
string = f.readline().strip()
print(nbr_nice) | string = 'ugknbfddgicrmopn'
string = 'aaa'
string = 'jchzalrnumimnmhp'
string = 'haegwjzuvuyypxyu'
string = 'dvszwmarrgswjxmb'
def check_vowels(string):
vowels = 0
vowels += string.count('a')
vowels += string.count('e')
vowels += string.count('i')
vowels += string.count('o')
vowels += string.count('u')
return vowels >= 3
def check_doubles(string):
for i in range(len(string) - 1):
if string[i] == string[i + 1]:
return True
return False
def check_barred(string):
barred = 0
barred += string.count('ab')
barred += string.count('cd')
barred += string.count('pq')
barred += string.count('xy')
return barred > 0
nbr_nice = 0
with open('input.txt') as f:
string = f.readline().strip()
while string != '':
nice = check_vowels(string) and check_doubles(string) and (not check_barred(string))
print(string, '->', nice)
if nice:
nbr_nice += 1
string = f.readline().strip()
print(nbr_nice) |
def lonely_integer(m):
answer = 0
for x in m:
answer = answer ^ x
return answer
a = int(input())
b = map(int, input().strip().split(" "))
print(lonely_integer(b))
| def lonely_integer(m):
answer = 0
for x in m:
answer = answer ^ x
return answer
a = int(input())
b = map(int, input().strip().split(' '))
print(lonely_integer(b)) |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def main():
age = 30
print(age)
print(30)
# Variable name snake case
friend_age = 23
print(friend_age)
PI = 3.14159
print(PI)
RADIANS_TO_DEGREES = 180/PI
print(RADIANS_TO_DEGREES)
if __name__ == "__main__":
main() | def main():
age = 30
print(age)
print(30)
friend_age = 23
print(friend_age)
pi = 3.14159
print(PI)
radians_to_degrees = 180 / PI
print(RADIANS_TO_DEGREES)
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
# Every time function slice return a new object
students = ['Tom', 'Mary', 'Ken', 'Billy', 'Mike']
# Get continuously subset of a range
slice1 = students[0:3]
print(slice1)
slice2 = students[:3]
print(slice2)
slice3 = students[-3:] # last three
print(slice3)
slice4 = students[2:4] # 3rd & 4th
print(slice4)
slice5 = students[:] # copy
print(slice5)
# Discontinuous subset skipped by a step
print(list(range(100)[0:20:2]))
print(list(range(100)[::5]))
# string can be sliced
print('abcde'[0:3])
| students = ['Tom', 'Mary', 'Ken', 'Billy', 'Mike']
slice1 = students[0:3]
print(slice1)
slice2 = students[:3]
print(slice2)
slice3 = students[-3:]
print(slice3)
slice4 = students[2:4]
print(slice4)
slice5 = students[:]
print(slice5)
print(list(range(100)[0:20:2]))
print(list(range(100)[::5]))
print('abcde'[0:3]) |
class LogHolder():
def __init__(self, dirpath, name):
self.dirpath = dirpath
self.name = name
self.reset(suffix='train')
def write_to_file(self):
with open(self.dirpath + f'{self.name}-metrics-{self.suffix}.txt', 'a') as file:
for i in self.metric_holder:
file.write(str(i) + ' ')
with open(self.dirpath + f'{self.name}-loss-{self.suffix}.txt', 'a') as file:
for i in self.loss_holder:
file.write(str(i) + ' ')
def init_files(self, dirpath, name):
metric_file = open(dirpath + f'{name}-metrics-{self.suffix}.txt', 'w')
loss_file = open(dirpath + f'{name}-loss-{self.suffix}.txt', 'w')
metric_file.close()
loss_file.close()
return None
def write_metric(self, val):
if type(val) == list:
self.metric_holder.extend(val)
else:
self.metric_holder.append(val)
def write_loss(self, val):
self.loss_holder.append(val)
def reset(self, suffix):
self.metric_holder = []
self.loss_holder = []
self.suffix = suffix
self.init_files(self.dirpath, self.name) | class Logholder:
def __init__(self, dirpath, name):
self.dirpath = dirpath
self.name = name
self.reset(suffix='train')
def write_to_file(self):
with open(self.dirpath + f'{self.name}-metrics-{self.suffix}.txt', 'a') as file:
for i in self.metric_holder:
file.write(str(i) + ' ')
with open(self.dirpath + f'{self.name}-loss-{self.suffix}.txt', 'a') as file:
for i in self.loss_holder:
file.write(str(i) + ' ')
def init_files(self, dirpath, name):
metric_file = open(dirpath + f'{name}-metrics-{self.suffix}.txt', 'w')
loss_file = open(dirpath + f'{name}-loss-{self.suffix}.txt', 'w')
metric_file.close()
loss_file.close()
return None
def write_metric(self, val):
if type(val) == list:
self.metric_holder.extend(val)
else:
self.metric_holder.append(val)
def write_loss(self, val):
self.loss_holder.append(val)
def reset(self, suffix):
self.metric_holder = []
self.loss_holder = []
self.suffix = suffix
self.init_files(self.dirpath, self.name) |
# This program calculates the sum of a series
# of numbers entered by the user.
max = 5 # The maximum number
# Initialize an accumulator variable.
total = 0.0
# Explain what we are doing.
print('This program calculates the sum of')
print(max, 'numbers you will enter.')
# Get the numbers and accumulate them.
for counter in range(max):
number = int(input('Enter a number: '))
total = total + number
# Display the total of the numbers.
print('The total is', total)
| max = 5
total = 0.0
print('This program calculates the sum of')
print(max, 'numbers you will enter.')
for counter in range(max):
number = int(input('Enter a number: '))
total = total + number
print('The total is', total) |
class Solution:
def maximum69Number (self, num: int) -> int:
try:
numstr = list(str(num))
numstr[numstr.index('6')]='9'
return int("".join(numstr))
except:
return num | class Solution:
def maximum69_number(self, num: int) -> int:
try:
numstr = list(str(num))
numstr[numstr.index('6')] = '9'
return int(''.join(numstr))
except:
return num |
class CurvedUniverse():
def __init__(self, shape_or_k = 0):
self.shapes = {'o': -1, 'f': 0, 'c': 1}
self.set_shape_or_k(shape_or_k)
def set_shape_or_k(self, shape_or_k):
if type(shape_or_k) == str:
self.__dict__['shape'] = shape_or_k
self.__dict__['k'] = self.shapes[shape_or_k]
else:
self.__dict__['k'] = shape_or_k
self.__dict__['shape'] = [k for shape, k in self.shapes.items() if k == shape_or_k][0]
def __setattr__(self, name, value):
if name == 'shape' or name == 'k':
self.set_shape_or_k(value)
else:
self.__dict__[name] = value | class Curveduniverse:
def __init__(self, shape_or_k=0):
self.shapes = {'o': -1, 'f': 0, 'c': 1}
self.set_shape_or_k(shape_or_k)
def set_shape_or_k(self, shape_or_k):
if type(shape_or_k) == str:
self.__dict__['shape'] = shape_or_k
self.__dict__['k'] = self.shapes[shape_or_k]
else:
self.__dict__['k'] = shape_or_k
self.__dict__['shape'] = [k for (shape, k) in self.shapes.items() if k == shape_or_k][0]
def __setattr__(self, name, value):
if name == 'shape' or name == 'k':
self.set_shape_or_k(value)
else:
self.__dict__[name] = value |
keep_going = "y"
while keep_going.startswith("y"):
a_name = input("Enter a name: ").strip()
with open("users.txt", "a") as file:
file.write(a_name + "; ")
keep_going = input("Insert another name? (y/n) ").strip() | keep_going = 'y'
while keep_going.startswith('y'):
a_name = input('Enter a name: ').strip()
with open('users.txt', 'a') as file:
file.write(a_name + '; ')
keep_going = input('Insert another name? (y/n) ').strip() |
# Conditional Statements in Python
# If-else statements
age = int(input("Input your age: "))
if age > 17:
print("You are an adult")
else:
print("You are a minor")
#If-elif-else statements
number = int(input("Input a number: "))
if number > 5:
print("Is greater than 5")
elif number == 5:
print("Is equal to 5")
else:
print("Is less than 5") | age = int(input('Input your age: '))
if age > 17:
print('You are an adult')
else:
print('You are a minor')
number = int(input('Input a number: '))
if number > 5:
print('Is greater than 5')
elif number == 5:
print('Is equal to 5')
else:
print('Is less than 5') |
# Your App secret key
SECRET_KEY = "TXxWqZHAILwElJF2bKR8"
DEFAULT_FEATURE_FLAGS: Dict[str, bool] = {
# Note that: RowLevelSecurityFilter is only given by default to the Admin role
# and the Admin Role does have the all_datasources security permission.
# But, if users create a specific role with access to RowLevelSecurityFilter MVC
# and a custom datasource access, the table dropdown will not be correctly filtered
# by that custom datasource access. So we are assuming a default security config,
# a custom security config could potentially give access to setting filters on
# tables that users do not have access to.
"ROW_LEVEL_SECURITY": True,
}
SUPERSET_WEBSERVER_PORT = 8088
FAVICONS = [{"href": "/static/assets/images/favicon.png"}]
APP_ICON = "/static/assets/images/superset-logo-horiz.png"
APP_ICON_WIDTH = 126
# When using LDAP Auth, setup the LDAP server
# AUTH_LDAP_SERVER = "ldap://ldapserver.new"
# Uncomment to setup OpenID providers example for OpenID authentication
# OPENID_PROVIDERS = [
# { 'name': 'Yahoo', 'url': 'https://open.login.yahoo.com/' },
# { 'name': 'Flickr', 'url': 'https://www.flickr.com/<username>' },
# ---------------------------------------------------
# Babel config for translations
# ---------------------------------------------------
# Setup default language
BABEL_DEFAULT_LOCALE = "en"
# Your application default translation path
BABEL_DEFAULT_FOLDER = "superset/translations"
# The allowed translation for you app
LANGUAGES = {
"en": {"flag": "us", "name": "English"},
"es": {"flag": "es", "name": "Spanish"},
"it": {"flag": "it", "name": "Italian"},
"fr": {"flag": "fr", "name": "French"},
"zh": {"flag": "cn", "name": "Chinese"},
"ja": {"flag": "jp", "name": "Japanese"},
"de": {"flag": "de", "name": "German"},
"pt": {"flag": "pt", "name": "Portuguese"},
"pt_BR": {"flag": "br", "name": "Brazilian Portuguese"},
"ru": {"flag": "ru", "name": "Russian"},
"ko": {"flag": "kr", "name": "Korean"},
}
# Turning off i18n by default as translation in most languages are
# incomplete and not well maintained.
LANGUAGES = {}
# Default cache timeout (in seconds), applies to all cache backends unless
# specifically overridden in each cache config.
CACHE_DEFAULT_TIMEOUT = 60 * 60 * 24 # 1 day
# The SQLAlchemy connection string.
# SQLALCHEMY_DATABASE_URI = 'mysql://superset:superset@10.10.2.1:3306/superset'
# Requires on MySQL
# CREATE USER 'superset'@'%' IDENTIFIED BY '8opNioe2ax1ndL';
# GRANT ALL PRIVILEGES ON *.* TO 'superset'@'%' WITH GRANT OPTION; | secret_key = 'TXxWqZHAILwElJF2bKR8'
default_feature_flags: Dict[str, bool] = {'ROW_LEVEL_SECURITY': True}
superset_webserver_port = 8088
favicons = [{'href': '/static/assets/images/favicon.png'}]
app_icon = '/static/assets/images/superset-logo-horiz.png'
app_icon_width = 126
babel_default_locale = 'en'
babel_default_folder = 'superset/translations'
languages = {'en': {'flag': 'us', 'name': 'English'}, 'es': {'flag': 'es', 'name': 'Spanish'}, 'it': {'flag': 'it', 'name': 'Italian'}, 'fr': {'flag': 'fr', 'name': 'French'}, 'zh': {'flag': 'cn', 'name': 'Chinese'}, 'ja': {'flag': 'jp', 'name': 'Japanese'}, 'de': {'flag': 'de', 'name': 'German'}, 'pt': {'flag': 'pt', 'name': 'Portuguese'}, 'pt_BR': {'flag': 'br', 'name': 'Brazilian Portuguese'}, 'ru': {'flag': 'ru', 'name': 'Russian'}, 'ko': {'flag': 'kr', 'name': 'Korean'}}
languages = {}
cache_default_timeout = 60 * 60 * 24 |
N, Q = tuple(map(int, input().split()))
LRT = [tuple(map(int, input().split())) for _ in range(Q)]
A = [0 for _ in range(N)]
for left, right, t in LRT:
for i in range(left - 1, right):
A[i] = t
print(*A, sep="\n")
| (n, q) = tuple(map(int, input().split()))
lrt = [tuple(map(int, input().split())) for _ in range(Q)]
a = [0 for _ in range(N)]
for (left, right, t) in LRT:
for i in range(left - 1, right):
A[i] = t
print(*A, sep='\n') |
# AUTHOR: Dharma Teja
# Python3 Concept:sum of digits in given number
# GITHUB: https://github.com/dharmateja03
number=int(input()) #enter input
l=list(str(number))
nums=list(map(int,l))
print(sum(nums))
| number = int(input())
l = list(str(number))
nums = list(map(int, l))
print(sum(nums)) |
class DataThing:
def __init__(self, _x):
self.y = int(input("Enter a Y Value: "))
self.x = _x
def __str__(self):
ret = "{} {}".format(self.x, self.y)
return ret
def createSome():
x = int(input("Enter a X Value: "))
ret = DataThing(x)
return ret
########### Tester ###############
a = DataThing(5)
print(a)
b = createSome()
print(b) | class Datathing:
def __init__(self, _x):
self.y = int(input('Enter a Y Value: '))
self.x = _x
def __str__(self):
ret = '{} {}'.format(self.x, self.y)
return ret
def create_some():
x = int(input('Enter a X Value: '))
ret = data_thing(x)
return ret
a = data_thing(5)
print(a)
b = create_some()
print(b) |
class Graph():
def __init__(self, vertices):
self.V=vertices
self.graph=[[0 for col in range(vertices)] for row in range(vertices)]
def printSolution(self, dist):
print ("Vertex \tDistance from Source")
for node in range(self.V):
print (node, "\t\t\t", dist[node])
def minDistance(self, dist, SPT):
min = float('inf')
min_index=0
for v in range(self.V):
if dist[v] < min and SPT[v] == False:
min = dist[v]
min_index = v
return min_index
def dijkstra(self,source):
dist= [float('inf')] * self.V
dist[source]=0
SPT=[False] * self.V
for _ in range(self.V):
u=self.minDistance(dist, SPT)
SPT[u]=True
for v in range(self.V):
if self.graph[u][v] > 0 and SPT[v] == False and dist[v] > dist[u] + self.graph[u][v]:
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
g=Graph(6)
g.graph=[[0,50,10,0,45,0],[0,0,15,0,10,0],[20,0,0,15,0,0],[0,20,0,0,35,0],[0,0,0,30,0,0],[0,0,0,3,0,0]]
g.dijkstra(0)
| class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for col in range(vertices)] for row in range(vertices)]
def print_solution(self, dist):
print('Vertex \tDistance from Source')
for node in range(self.V):
print(node, '\t\t\t', dist[node])
def min_distance(self, dist, SPT):
min = float('inf')
min_index = 0
for v in range(self.V):
if dist[v] < min and SPT[v] == False:
min = dist[v]
min_index = v
return min_index
def dijkstra(self, source):
dist = [float('inf')] * self.V
dist[source] = 0
spt = [False] * self.V
for _ in range(self.V):
u = self.minDistance(dist, SPT)
SPT[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and SPT[v] == False and (dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
g = graph(6)
g.graph = [[0, 50, 10, 0, 45, 0], [0, 0, 15, 0, 10, 0], [20, 0, 0, 15, 0, 0], [0, 20, 0, 0, 35, 0], [0, 0, 0, 30, 0, 0], [0, 0, 0, 3, 0, 0]]
g.dijkstra(0) |
#input_column: b,string,VARCHAR(100),100,None,None
#input_type: SET
#output_column: b,string,VARCHAR(100),100,None,None
#output_type: EMITS
#!/bin/bash
ls -l /tmp
| ls - l / tmp |
class BaseGenerator:
pass
class CharGenerator(BaseGenerator):
pass
| class Basegenerator:
pass
class Chargenerator(BaseGenerator):
pass |
# The self keyword is used when you want a method or
# attribute to be for a specific object. This means that,
# down below, each Tesla object can have different maxSpeed
# and colors from each other.
class Tesla:
def __init__(self, maxSpeed=120, color="red"):
self.maxSpeed = maxSpeed
self.color = color
def change(self, c):
self.color = c
p1 = Tesla(140, "blue")
p2 = Tesla(100, "blue")
# Notice how, when we use the self keyword, each object can
# have different attributes even though they are from the
# same class.
p1.change("green")
print(p1.color) # prints "green"
p2.change("yellow")
print(p2.color) # prints "yellow"
| class Tesla:
def __init__(self, maxSpeed=120, color='red'):
self.maxSpeed = maxSpeed
self.color = color
def change(self, c):
self.color = c
p1 = tesla(140, 'blue')
p2 = tesla(100, 'blue')
p1.change('green')
print(p1.color)
p2.change('yellow')
print(p2.color) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.