content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# TYPE OF OPERATORS IN PYTHON
# Arithmetic
# Assignment
# Comparison
# Logical
# Membership
# Identity
# Bitwise
# Arithmetic operators: Used to perform arithmetic operations between variables
# +, -, *, /, %, **, //
x = 10
y = 20
# Arithmetic Operators
print('Arithmetic Operators')
print(x+y)
print(x-y)
print(x*y)
pr... | x = 10
y = 20
print('Arithmetic Operators')
print(x + y)
print(x - y)
print(x * y)
print(x ** y)
print(x / y)
print(x // y)
print(x % y)
print()
print('Assignment operators')
x = 100
x += 10
a = 5
a += 5
print(a)
a **= 5
print(a)
print()
print('Comparison Operators')
val = 10
num1 = 20
compare = val == num1
print(compa... |
# You are given a two-digit integer n. Return the sum of its digits.
# Example
# For n = 29, the output should be
# addTwoDigits(n) = 11.
def addTwoDigits(n):
sum1 = 0
for i in str(n):
sum1 += int(i)
return sum1
print(addTwoDigits(29))
| def add_two_digits(n):
sum1 = 0
for i in str(n):
sum1 += int(i)
return sum1
print(add_two_digits(29)) |
# $Id: md1.py,v 1.8 2020/04/22 21:39:41 baaden Exp baaden $
# Script (c) 2020 by Marc Baaden, <baaden@smplinux.de>
#
# UnityMol python script to visualize the Covid-19 spike protein
# activate specific commands to simplify interactive raytracing of the scene
doRT = False;
absolutePath = "C:/Users/ME/fair_covid_molvis... | do_rt = False
absolute_path = 'C:/Users/ME/fair_covid_molvisexp/ex3_mdtraj/'
in_vr = UnityMolMain.inVR()
Application.runInBackground = True
UnityMolMain.allowIDLE = False
if doRT:
bg_color('gray')
UnityMolMain.disableSurfaceThread = True
UnityMolMain.raytracingMode = True
Screen.SetResolution(1920, 1080... |
def a(x):
if x == 1:
print("x is 1")
else:
print("x is not 1")
| def a(x):
if x == 1:
print('x is 1')
else:
print('x is not 1') |
def mergeSort(lst, start, end):
if start < end:
mid = start + (end - start) // 2
mergeSort(lst, start, mid)
mergeSort(lst, mid + 1, end)
merge(lst, start, end, mid)
def merge(lst, start, end, mid):
temp = lst[start: end + 1]
left = 0
right = mid + 1 - start
index = ... | def merge_sort(lst, start, end):
if start < end:
mid = start + (end - start) // 2
merge_sort(lst, start, mid)
merge_sort(lst, mid + 1, end)
merge(lst, start, end, mid)
def merge(lst, start, end, mid):
temp = lst[start:end + 1]
left = 0
right = mid + 1 - start
index =... |
class Person:
pass
class Male(Person):
def getGender(self):
return 'Male'
class Female(Person):
def getGender(self):
return 'Female'
print(Male().getGender())
print(Female().getGender()) | class Person:
pass
class Male(Person):
def get_gender(self):
return 'Male'
class Female(Person):
def get_gender(self):
return 'Female'
print(male().getGender())
print(female().getGender()) |
# input = ["a", "a", "b", "b", "c", "c", "c"]
# o/p = a2b2c3
# O(n) time complexity
string_chr = ["a", "a", "b", "b", "c", "c", "c"]
def stringCompression(string_chr):
newString = ''
count = 1
for i in range(len(string_chr)-1):
print(i)
print(string_chr[i])
if string_chr[i] == str... | string_chr = ['a', 'a', 'b', 'b', 'c', 'c', 'c']
def string_compression(string_chr):
new_string = ''
count = 1
for i in range(len(string_chr) - 1):
print(i)
print(string_chr[i])
if string_chr[i] == string_chr[i + 1]:
count += 1
else:
new_string += str... |
def compare_schema_resources(available_resources, schema_resources, version):
_available = set(_r.name for _r in available_resources if _r.is_available(version))
_schema = set(schema_resources)
unexpected = list(_available.difference(_schema))
missing = list(_schema.difference(_available))
match = ... | def compare_schema_resources(available_resources, schema_resources, version):
_available = set((_r.name for _r in available_resources if _r.is_available(version)))
_schema = set(schema_resources)
unexpected = list(_available.difference(_schema))
missing = list(_schema.difference(_available))
match =... |
#paste your api_hash and api_id from my.telegram.org
api_hash = " b59675804753a20366ac24e38dd3ea35"
api_id = "1347448"
entity = "tgcloud"
| api_hash = ' b59675804753a20366ac24e38dd3ea35'
api_id = '1347448'
entity = 'tgcloud' |
'''
A Python program to check whether a specifi ed value iscontained in a group of values.
'''
def isVowel (inputStr):
vowelTuple = ('1', '5', '8', '3', '9')
for vowel in vowelTuple:
if inputStr == vowel:
return True
return False
def main ():
myStr = input ("E... | """
A Python program to check whether a specifi ed value iscontained in a group of values.
"""
def is_vowel(inputStr):
vowel_tuple = ('1', '5', '8', '3', '9')
for vowel in vowelTuple:
if inputStr == vowel:
return True
return False
def main():
my_str = input('Enter a letter')
i... |
n = int(input('n: '))
soma = 0
cont = 0
while cont < n:
numeros = int(input('numero: '))
soma += numeros
cont += 1
media = soma / n
print('soma e igual: {}, e a media: {:.2f}'.format(soma, media))
| n = int(input('n: '))
soma = 0
cont = 0
while cont < n:
numeros = int(input('numero: '))
soma += numeros
cont += 1
media = soma / n
print('soma e igual: {}, e a media: {:.2f}'.format(soma, media)) |
'''
MIT License
Copyright (c) 2019 lewis he
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, pub... | """
MIT License
Copyright (c) 2019 lewis he
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dist... |
def format_interval(t):
mins, s = divmod(int(t), 60)
h, m = divmod(mins, 60)
if h:
return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)
else:
return '{0:02d}:{1:02d}'.format(m, s)
def decode_format_dict(fm):
elapsed_str = format_interval(fm['elapsed'])
remaining = (fm['total'] - fm['n']) /... | def format_interval(t):
(mins, s) = divmod(int(t), 60)
(h, m) = divmod(mins, 60)
if h:
return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)
else:
return '{0:02d}:{1:02d}'.format(m, s)
def decode_format_dict(fm):
elapsed_str = format_interval(fm['elapsed'])
remaining = (fm['total'] - f... |
# Initialize search space
# Initialize model
while not objective_reached and not bugdget_exhausted:
# Obtain new hyperparameters
suggestion = GetSuggestions()
# Run trial with new hyperparameters; collect metrics
metrics = RunTrial(suggestion)
# Report metrics
Report(metrics)
| while not objective_reached and (not bugdget_exhausted):
suggestion = get_suggestions()
metrics = run_trial(suggestion)
report(metrics) |
# Settings
DEBUG = True
# Setting TESTING to True disables @login_required checks
TESTING = False
CACHE_TYPE = 'simple'
## SQLite Connection
SQLALCHEMY_DATABASE_URI = 'sqlite:///db.sqlite'
# Local PostgreSQL Connection
# SQLALCHEMY_DATABASE_URI = 'postgresql://puser:Password1@localhost/devdb'
SECRET_KEY = 'a9eec0e0... | debug = True
testing = False
cache_type = 'simple'
sqlalchemy_database_uri = 'sqlite:///db.sqlite'
secret_key = 'a9eec0e0-23b7-4788-9a92-318347b9a39a'
sqlalchemy_track_modifications = False
mail_default_sender = 'info@flaskproject.us'
mail_server = 'smtp.postmarkapp.com'
mail_port = 25
mail_use_tls = True
mail_username... |
# OGC GeoTIFF
specURL = "http://docs.opengeospatial.org/is/19-008r4/19-008r4.html"
fout = open("../mappings/19-008r4.csv","w") # output file
fin = open("../specifications/19-008r4.txt","r") # input file
elementList = []
# processing the input file
for line in fin:
tokens = line.split()
for token in tokens:
... | spec_url = 'http://docs.opengeospatial.org/is/19-008r4/19-008r4.html'
fout = open('../mappings/19-008r4.csv', 'w')
fin = open('../specifications/19-008r4.txt', 'r')
element_list = []
for line in fin:
tokens = line.split()
for token in tokens:
if token.endswith(','):
token = token.replace(','... |
STUDENT_CODE_DEFAULT = 'analysis.py,qlearningAgents.py,valueIterationAgents.py'
PROJECT_TEST_CLASSES = 'reinforcementTestClasses.py'
PROJECT_NAME = 'Project 3: Reinforcement learning'
BONUS_PIC = False
| student_code_default = 'analysis.py,qlearningAgents.py,valueIterationAgents.py'
project_test_classes = 'reinforcementTestClasses.py'
project_name = 'Project 3: Reinforcement learning'
bonus_pic = False |
def findLongestWord(s, d):
def isSubsequence(x):
iterator_of_s = iter(s)#all chars of s
return all(c in iterator_of_s for c in x)
return max(sorted(filter(isSubsequence, d)) + [''], key=len)
if __name__ == "__main__":
s = "abpcplea"
d = ["ale","apple","monkey","plea"]
print(findLon... | def find_longest_word(s, d):
def is_subsequence(x):
iterator_of_s = iter(s)
return all((c in iterator_of_s for c in x))
return max(sorted(filter(isSubsequence, d)) + [''], key=len)
if __name__ == '__main__':
s = 'abpcplea'
d = ['ale', 'apple', 'monkey', 'plea']
print(find_longest_wo... |
class Config:
'''
General configuration parent class
'''
pass
class ProdConfig(Config):
'''
Production configuration child class
Args:
config:The parent configuration class
with general configuration settings
'''
pass
class DevConfig(Config):
'''
Devel... | class Config:
"""
General configuration parent class
"""
pass
class Prodconfig(Config):
"""
Production configuration child class
Args:
config:The parent configuration class
with general configuration settings
"""
pass
class Devconfig(Config):
"""
Devel... |
## Just to use the same value of a variable in more than just one file;
## That way, will only need to change value here
SIZE = 600 # Size of game board, in pixels
ROWS = 20 # How many rows the playable game will have
DELAY = 50 # Delay time for the game execution, in milliseconds
TICK = 10 # Essentially, it's how man... | size = 600
rows = 20
delay = 50
tick = 10 |
def sanitize(string):
newString = ""
flag = False
for letter in string:
if letter == '@':
flag = True
elif letter == ' ':
flag = False
if flag:
continue
else:
... | def sanitize(string):
new_string = ''
flag = False
for letter in string:
if letter == '@':
flag = True
elif letter == ' ':
flag = False
if flag:
continue
elif letter != ' ':
new_string += letter
return newString.strip()
def... |
class Solution:
def countElements(self, arr: List[int]) -> int:
table = set(arr)
return sum(x + 1 in table for x in arr)
| class Solution:
def count_elements(self, arr: List[int]) -> int:
table = set(arr)
return sum((x + 1 in table for x in arr)) |
if __name__ == "__main__":
# Initialization
haystack = "Hello, Budgie!"
print(haystack)
# Concatenation
joined = "It is -> " + haystack + " <- It was"
print(joined)
# Characters
text = "abc"
first = text[0]
print("{0}'s first character is {1}.".format(text, first))
# Searc... | if __name__ == '__main__':
haystack = 'Hello, Budgie!'
print(haystack)
joined = 'It is -> ' + haystack + ' <- It was'
print(joined)
text = 'abc'
first = text[0]
print("{0}'s first character is {1}.".format(text, first))
needle = 'Budgie'
first_index_of = haystack.find(needle)
sec... |
#
# PySNMP MIB module CTRON-SFPS-SIZE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SFPS-SIZE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:31:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint) ... |
s = 'abc12321cba'
print(s.replace('a', ''))
s = 'abc12321cba'
print(s.translate({ord('a'): None}))
print(s.translate({ord(i): None for i in 'abc'}))
# removing spaces from a string
s = ' 1 2 3 4 '
print(s.replace(' ', ''))
print(s.translate({ord(i): None for i in ' '}))
# remove substring from string
s = 'ab12abc... | s = 'abc12321cba'
print(s.replace('a', ''))
s = 'abc12321cba'
print(s.translate({ord('a'): None}))
print(s.translate({ord(i): None for i in 'abc'}))
s = ' 1 2 3 4 '
print(s.replace(' ', ''))
print(s.translate({ord(i): None for i in ' '}))
s = 'ab12abc34ba'
print(s.replace('ab', ''))
s = 'ab\ncd\nef'
print(s.replace('\n... |
# author: WatchDogOblivion
# description: TODO
# WatchDogs List Utility
class ListUtility(object):
@staticmethod
def group(lst, groupSize):
#type: (list, int) -> list
finalList = []
groupSizeList = range(0, len(lst), groupSize)
for groupSizeIndex in groupSizeList:
finalList.append(lst[group... | class Listutility(object):
@staticmethod
def group(lst, groupSize):
final_list = []
group_size_list = range(0, len(lst), groupSize)
for group_size_index in groupSizeList:
finalList.append(lst[groupSizeIndex:groupSizeIndex + groupSize])
return finalList |
# Union of list
a = ["apple","Orange"]
b = ["Banana","Chocolate"]
c = list(set().union(a,b))
print(c) | a = ['apple', 'Orange']
b = ['Banana', 'Chocolate']
c = list(set().union(a, b))
print(c) |
def part1(code):
i = 0;
while i < 7 * 365:
i = i << 2 | 0b10;
return i - 7 * 365
def part2(code):
...
def parse(line):
xs = line.strip().split()
if len(xs) < 3:
xs.append("")
for i in (1, 2):
try:
xs[i] = int(xs[i])
except ValueError:
... | def part1(code):
i = 0
while i < 7 * 365:
i = i << 2 | 2
return i - 7 * 365
def part2(code):
...
def parse(line):
xs = line.strip().split()
if len(xs) < 3:
xs.append('')
for i in (1, 2):
try:
xs[i] = int(xs[i])
except ValueError:
pass... |
def generateWholeBodyMotion(cs, cfg, fullBody=None, viewer=None):
raise NotImplemented("TODO")
| def generate_whole_body_motion(cs, cfg, fullBody=None, viewer=None):
raise not_implemented('TODO') |
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
last_occ = {}
stack = []
visited = set()
for i in range(len(s)):
last_occ[s[i]] = i
for i in range(len(s)):
if s[i] not in visited:
while (stack and stack[-1] > s[i] an... | class Solution:
def remove_duplicate_letters(self, s: str) -> str:
last_occ = {}
stack = []
visited = set()
for i in range(len(s)):
last_occ[s[i]] = i
for i in range(len(s)):
if s[i] not in visited:
while stack and stack[-1] > s[i] and... |
[
{"created_at": "Thu Nov 30 21:16:44 +0000 2017", "favorite_count": 268, "hashtags": [], "id": 936343262088097795, "id_str": "936343262088097795", "lang": "en", "retweet_count": 82, "source": "<a href=\"http://bufferapp.com\" rel=\"nofollow\">Buffer</a>", "text": "Automation (not immigrants, @realDonaldTrump) could el... | [{'created_at': 'Thu Nov 30 21:16:44 +0000 2017', 'favorite_count': 268, 'hashtags': [], 'id': 936343262088097795, 'id_str': '936343262088097795', 'lang': 'en', 'retweet_count': 82, 'source': '<a href="http://bufferapp.com" rel="nofollow">Buffer</a>', 'text': 'Automation (not immigrants, @realDonaldTrump) could elimina... |
#
# PySNMP MIB module ENTERASYS-DIAGNOSTIC-MESSAGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-DIAGNOSTIC-MESSAGE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:48:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
x:str = "Hello"
y:str = "World"
z:str = ""
z = x + y
z = x[0]
x = y = z
| x: str = 'Hello'
y: str = 'World'
z: str = ''
z = x + y
z = x[0]
x = y = z |
lines = open('input.txt', 'r').readlines()
# part one
grid = dict()
for line in lines:
# extract coord
(x1, y1, x2, y2) = [int(coord) for coord_string in line.split(" -> ") for coord in coord_string.split(",")]
# parallel to x-axis
if x1 == x2:
for y in range(min(y1,y2), max(y1,y2)+1):
... | lines = open('input.txt', 'r').readlines()
grid = dict()
for line in lines:
(x1, y1, x2, y2) = [int(coord) for coord_string in line.split(' -> ') for coord in coord_string.split(',')]
if x1 == x2:
for y in range(min(y1, y2), max(y1, y2) + 1):
if (x1, y) not in grid:
grid[x1, ... |
query = input('Pick a number less than the magnitude of 10^8. Note- any multiple of 7 will give an unusual answer. Use a number that is not a multiple '
'of 7 for the best results. ')
print('\nYou have picked the number ' + str(query) + '. To demonstrate the cyclic nature of the number 142857, let\'s '
... | query = input('Pick a number less than the magnitude of 10^8. Note- any multiple of 7 will give an unusual answer. Use a number that is not a multiple of 7 for the best results. ')
print('\nYou have picked the number ' + str(query) + ". To demonstrate the cyclic nature of the number 142857, let's begin by multiplying "... |
# This program displays a person's
# name and address
print('Kate Austen')
print('123 Full Circle Drive')
print('Ashville, NC 28899') | print('Kate Austen')
print('123 Full Circle Drive')
print('Ashville, NC 28899') |
# Inserting a new node in DLL at end
# 7 step procedure
#Node class
class Node:
def __init__(self, next = None, prev = None, data = None):
self.next = next
self.prev = prev
self.data = data
#DLL class
class DoublyLinkedList:
def __init__(self):
self.head = None
def append... | class Node:
def __init__(self, next=None, prev=None, data=None):
self.next = next
self.prev = prev
self.data = data
class Doublylinkedlist:
def __init__(self):
self.head = None
def append(self, new_data):
new_node = node(data=new_data)
last = self.head
... |
a = 0
a += 5 #Suma en asignacion
a -= 10 #Resta en asignacion
a *= 2 #Producto de asignacion
a /= 2 #Division de asignacion
a %= 2 #Modulo de asinacion
a **= 10
numero_magico = 12345679
numero_usuario = int(input("Numero entre 1 y 9: "))
numero_usuario *= 9
numero_magico *= numero_usuario
print (numero_magico)
| a = 0
a += 5
a -= 10
a *= 2
a /= 2
a %= 2
a **= 10
numero_magico = 12345679
numero_usuario = int(input('Numero entre 1 y 9: '))
numero_usuario *= 9
numero_magico *= numero_usuario
print(numero_magico) |
'''Faca um Programa que leia um numero de 0 a 9999 e mostre na tela cada um dos gigitos separados
Ex: 1834
4 Unidades , 3 Dezenas , 8 Centenas , 1 Milhar
'''
numero = input('Digite um Numero de O a 9999: ')
print('\033[31m {} \033[m,Unidades '.format(numero[3]))
print('\033[32m {} \033[m,Dezenas '.format(numero[2]))... | """Faca um Programa que leia um numero de 0 a 9999 e mostre na tela cada um dos gigitos separados
Ex: 1834
4 Unidades , 3 Dezenas , 8 Centenas , 1 Milhar
"""
numero = input('Digite um Numero de O a 9999: ')
print('\x1b[31m {} \x1b[m,Unidades '.format(numero[3]))
print('\x1b[32m {} \x1b[m,Dezenas '.format(numero[2]))
pr... |
# import pytest
class TestNameSpace:
def test___call__(self): # synced
assert True
def test___len__(self): # synced
assert True
def test___getitem__(self): # synced
assert True
def test___setitem__(self): # synced
assert True
def test___delitem__(self): # s... | class Testnamespace:
def test___call__(self):
assert True
def test___len__(self):
assert True
def test___getitem__(self):
assert True
def test___setitem__(self):
assert True
def test___delitem__(self):
assert True
def test___iter__(self):
ass... |
def part_1():
for i in input:
if (2020-i) in input:
return (2020-i)*i
def part_2():
for i in range(len(input)):
for j in range(i, len(input)):
if (2020 - input[i] - input[j]) in input:
return (2020-input[i]-input[j]) * input[i] * input[j]
... | def part_1():
for i in input:
if 2020 - i in input:
return (2020 - i) * i
def part_2():
for i in range(len(input)):
for j in range(i, len(input)):
if 2020 - input[i] - input[j] in input:
return (2020 - input[i] - input[j]) * input[i] * input[j]
if __name_... |
# https://leetcode.com/problems/max-increase-to-keep-city-skyline/description/
# input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
# output: 35
def build_top_or_bottom(grid):
top_or_bottom = []
for i in range(len(grid[0])):
highest_building = 0
for j in range(len(grid)):
if... | def build_top_or_bottom(grid):
top_or_bottom = []
for i in range(len(grid[0])):
highest_building = 0
for j in range(len(grid)):
if grid[j][i] > highest_building:
highest_building = grid[j][i]
top_or_bottom.append(highest_building)
return top_or_bottom
def... |
lines = open("day 13/Toon D - Python/input", "r").readlines()
coordinates = [[int(coor) for coor in line.replace('\n', '').split(',')]
for line in lines if "," in line]
folds = [line[11:].replace('\n', '').split('=')
for line in lines if '=' in line]
for element in folds:
element[1] = int(el... | lines = open('day 13/Toon D - Python/input', 'r').readlines()
coordinates = [[int(coor) for coor in line.replace('\n', '').split(',')] for line in lines if ',' in line]
folds = [line[11:].replace('\n', '').split('=') for line in lines if '=' in line]
for element in folds:
element[1] = int(element[1])
def fold(coor... |
expected_output = {
'ids': {
'1': {
'no_of_failures': 11,
'no_of_success': 0,
'probe_id': 1,
'return_code': 'Timeout',
'rtt_stats': 'NoConnection/Busy/Timeout',
'start_time': '07:10:18 UTC Fri Oct 22 2021'
},
'2': {
... | expected_output = {'ids': {'1': {'no_of_failures': 11, 'no_of_success': 0, 'probe_id': 1, 'return_code': 'Timeout', 'rtt_stats': 'NoConnection/Busy/Timeout', 'start_time': '07:10:18 UTC Fri Oct 22 2021'}, '2': {'delay': '3239998/3240718/3240998', 'destination': '10.50.10.100', 'no_of_failures': 0, 'no_of_success': 46, ... |
#! /usr/bin/env/python3
# -*- coding: utf-8 -*-
first_line = set(sorted(''.join([a for a in input() if a.isalnum()])))
second_line = set(sorted(''.join([a for a in input() if a.isalnum()])))
print(first_line)
print(second_line)
for i in second_line:
if i not in first_line:
print("We can't do it")
... | first_line = set(sorted(''.join([a for a in input() if a.isalnum()])))
second_line = set(sorted(''.join([a for a in input() if a.isalnum()])))
print(first_line)
print(second_line)
for i in second_line:
if i not in first_line:
print("We can't do it")
break
else:
print('We can do it') |
#!/usr/bin/env python
# -------------------------------------------
# Compass Data object, corresponds to Compass_Data.h in old code
# -------------------------------------------
class CompassData:
def __init__(self, head=0):
self.heading = head
self.pitch = 0
self.roll = 0
self.tem... | class Compassdata:
def __init__(self, head=0):
self.heading = head
self.pitch = 0
self.roll = 0
self.temperature = 0
self.check_sum = 0 |
class Pessoa:
species = 'Human'
age = None
def __init__(self, name, sex):
self.sex = sex
self.name = name
def p_data(self):
print(
f'''
{self.name}
{self.age}
{self.species}
{self.sex}''')
class Elder(Pessoa):
age = '>60'
class Adult(Pessoa):
age = '18 t... | class Pessoa:
species = 'Human'
age = None
def __init__(self, name, sex):
self.sex = sex
self.name = name
def p_data(self):
print(f'\n{self.name}\n{self.age}\n{self.species}\n{self.sex}')
class Elder(Pessoa):
age = '>60'
class Adult(Pessoa):
age = '18 to 59'
class Te... |
class Solution:
def findWords(self, words: List[str]) -> List[str]:
first, second, third = set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")
result = []
for word in words:
first_letter = word[0].lower()
group = first
if first_letter in second:
... | class Solution:
def find_words(self, words: List[str]) -> List[str]:
(first, second, third) = (set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm'))
result = []
for word in words:
first_letter = word[0].lower()
group = first
if first_letter in second:
... |
L = [[0]*5 for i in range(3)]
n = int(input())
for i in range(n):
I = list(map(int,input().split()))
for j in range(3):
L[j][I[j]]+=1
for i in range(3):
L[i][0] = L[i][1]*1 + L[i][2]*2 + L[i][3]*3
L[i][4] = i+1
L.sort(key = lambda t: (-t[0], -t[3], -t[2], -t[1]))
if len(L) > 1 and L[0][:-1] ==... | l = [[0] * 5 for i in range(3)]
n = int(input())
for i in range(n):
i = list(map(int, input().split()))
for j in range(3):
L[j][I[j]] += 1
for i in range(3):
L[i][0] = L[i][1] * 1 + L[i][2] * 2 + L[i][3] * 3
L[i][4] = i + 1
L.sort(key=lambda t: (-t[0], -t[3], -t[2], -t[1]))
if len(L) > 1 and L[0... |
def part1():
with open('07_input.txt', 'r') as f:
lines = f.read().split('\n')
visited = []
acc = 0
ip = 0
while True:
if str(ip) in visited:
break
else:
visited.append(str(ip))
op, arg = lines[ip].split(' '... | def part1():
with open('07_input.txt', 'r') as f:
lines = f.read().split('\n')
visited = []
acc = 0
ip = 0
while True:
if str(ip) in visited:
break
else:
visited.append(str(ip))
(op, arg) = lines[ip].split(' ... |
class Leaderboard:
def __init__(self):
self.scores = defaultdict()
def addScore(self, playerId: int, score: int) -> None:
if playerId not in self.scores:
self.scores[playerId] = 0
self.scores[playerId] += score
def top(self, K: int) -> int:
values = [v for _, v... | class Leaderboard:
def __init__(self):
self.scores = defaultdict()
def add_score(self, playerId: int, score: int) -> None:
if playerId not in self.scores:
self.scores[playerId] = 0
self.scores[playerId] += score
def top(self, K: int) -> int:
values = [v for (_,... |
class Book:
def __init__(self, name, author, pages):
self.name = name
self.author = author
self.pages = pages
def name(self):
return self.name
def author(self):
return self.name
def pages(self):
return self.name
book = Book("My Book", "Me", 200)
print... | class Book:
def __init__(self, name, author, pages):
self.name = name
self.author = author
self.pages = pages
def name(self):
return self.name
def author(self):
return self.name
def pages(self):
return self.name
book = book('My Book', 'Me', 200)
print(... |
x = input("Give me a number: ")
y = input ("Give me a word: ")
out = "Output: "+str(x)+" "+str(y)
if x == 0 or x > 1:
if y[-2:] ==('ly'):
out = out [:-1]+'ies'
elif y[-2:] == "us":
out = out[:-2]+"i"
elif y[-2:] == "sh" or y[-2:] == "ch":
out += "es"
else:
out +="s"
... | x = input('Give me a number: ')
y = input('Give me a word: ')
out = 'Output: ' + str(x) + ' ' + str(y)
if x == 0 or x > 1:
if y[-2:] == 'ly':
out = out[:-1] + 'ies'
elif y[-2:] == 'us':
out = out[:-2] + 'i'
elif y[-2:] == 'sh' or y[-2:] == 'ch':
out += 'es'
else:
out += '... |
class MarkdownEmitter(object):
def initialize(self, filename, title, author, date):
self.file = open(filename, "w")
self.file.write(title)
self.file.write("\n======================================================================\n\n")
self.file.write("## %s (%s) ##" % (author, date... | class Markdownemitter(object):
def initialize(self, filename, title, author, date):
self.file = open(filename, 'w')
self.file.write(title)
self.file.write('\n======================================================================\n\n')
self.file.write('## %s (%s) ##' % (author, date)... |
n = int(input())
t = list(map(int, input().split()))
m = int(input())
drink = [tuple(map(int, input().split())) for _ in range(m)]
for i in range(m):
ans = 0
for j in range(n):
if drink[i][0] == j + 1:
ans += drink[i][1]
else:
ans += t[j]
print(ans)
| n = int(input())
t = list(map(int, input().split()))
m = int(input())
drink = [tuple(map(int, input().split())) for _ in range(m)]
for i in range(m):
ans = 0
for j in range(n):
if drink[i][0] == j + 1:
ans += drink[i][1]
else:
ans += t[j]
print(ans) |
#!/usr/bin/env python
'''
Name : APO Config, apoconfig.py
Author: Nickalas Reynolds
Date : Fall 2017
Misc : Config File for apo output
'''
config={
'pprint' : True,\
'commentline' : '#',\
'includefields': True,\
'header' : '',\
'interfielddelimiter': ' ',\
'intrafielddelimiter': ['','... | """
Name : APO Config, apoconfig.py
Author: Nickalas Reynolds
Date : Fall 2017
Misc : Config File for apo output
"""
config = {'pprint': True, 'commentline': '#', 'includefields': True, 'header': '', 'interfielddelimiter': ' ', 'intrafielddelimiter': ['', ':', ':', ''], 'fields': ['Name', 'RA', 'Dec', 'Magnitude'], ... |
def open_file(file):
with open(file) as f:
data = [x.strip() for x in f.readlines()]
return data
def get_gama_eps_in_str(data):
gamma = ''
eps = ''
for i in range(len(data[0])):
bit_value = 0
for j in range(len(data)):
bit_value += int(data[j][i])
ma... | def open_file(file):
with open(file) as f:
data = [x.strip() for x in f.readlines()]
return data
def get_gama_eps_in_str(data):
gamma = ''
eps = ''
for i in range(len(data[0])):
bit_value = 0
for j in range(len(data)):
bit_value += int(data[j][i])
max_occ... |
class SiteType:
def __init__(self):
pass
Communication = "CommunicationSite"
Team = "TeamSite"
| class Sitetype:
def __init__(self):
pass
communication = 'CommunicationSite'
team = 'TeamSite' |
#
# PySNMP MIB module CXOperatingSystem-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXOperatingSystem-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:33:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ... |
#!/usr/bin/env python3
# ~*~ coding: utf-8 ~*~
# Now modify the grades program from section Dictionaries so that it uses
# file I/O to keep a record of the students.
assignments = ['hw ch 1', 'hw ch 2', 'quiz ', 'hw ch 3', 'test']
students = { }
def load_grades(gradesfile):
inputfile = open(gradesfile, "r")
... | assignments = ['hw ch 1', 'hw ch 2', 'quiz ', 'hw ch 3', 'test']
students = {}
def load_grades(gradesfile):
inputfile = open(gradesfile, 'r')
grades = []
while True:
student_and_grade = inputfile.readline()
student_and_grade = student_and_grade[:-1]
if not student_and_grade:
... |
class Solution:
def containsDuplicate(self, nums: list) -> bool:
hs = set()
for n in nums:
if n not in hs:
hs.add(n)
else:
return True
return False | class Solution:
def contains_duplicate(self, nums: list) -> bool:
hs = set()
for n in nums:
if n not in hs:
hs.add(n)
else:
return True
return False |
# The file containing all the group API methods
def change_group_name():
row = db(db.group_data.id == request.vars.group_id).select().first()
row.update_record(group_name = request.vars.group_name)
return "ok"
def add_group():
t_id = db.group_data.insert(
group_owner = request.vars.group_owner,
... | def change_group_name():
row = db(db.group_data.id == request.vars.group_id).select().first()
row.update_record(group_name=request.vars.group_name)
return 'ok'
def add_group():
t_id = db.group_data.insert(group_owner=request.vars.group_owner, group_name=request.vars.group_name)
r = db(db.group_data... |
'''
This contains the entity definition for three contiguous numbers.
This would be useful for something like a phone number area code.
'''
THREE_DIGIT_PATTERN = [[['NUM'], ['NUM'], ['NUM']]]
ENTITY_DEFINITION = {
'patterns': THREE_DIGIT_PATTERN,
'spacing': {
'default': '',
}
}
| """
This contains the entity definition for three contiguous numbers.
This would be useful for something like a phone number area code.
"""
three_digit_pattern = [[['NUM'], ['NUM'], ['NUM']]]
entity_definition = {'patterns': THREE_DIGIT_PATTERN, 'spacing': {'default': ''}} |
#def jogar():
print(40 * "*")
print("Bem vindo ao jogo da FORCA")
print(40 * "*")
palavra_secreta = 'banana'
enforcou = False
acertou = False
while not enforcou and not acertou:
chute = input("Qual letra? ")
print('jogando...')
# if __name__ == "main":
# jogar()
| print(40 * '*')
print('Bem vindo ao jogo da FORCA')
print(40 * '*')
palavra_secreta = 'banana'
enforcou = False
acertou = False
while not enforcou and (not acertou):
chute = input('Qual letra? ')
print('jogando...') |
num = 7
step = 2
begin = 41
num *= step
for i in range(begin, begin+num, step):
print(i, end=',')
| num = 7
step = 2
begin = 41
num *= step
for i in range(begin, begin + num, step):
print(i, end=',') |
campaign = {
'type': ['object', 'null'],
'properties': {
'asset_id': {'type': 'integer'},
'asset_name': {'type': 'string'},
'modified_time': {'type': 'string'},
'version_number': {'type': 'integer'},
}
}
owner = {
'type': ['object', 'null'],
'properties': {
'... | campaign = {'type': ['object', 'null'], 'properties': {'asset_id': {'type': 'integer'}, 'asset_name': {'type': 'string'}, 'modified_time': {'type': 'string'}, 'version_number': {'type': 'integer'}}}
owner = {'type': ['object', 'null'], 'properties': {'asset_id': {'type': 'integer'}, 'first_name': {'type': 'string'}, 'l... |
# Note that the performance of the solutions below will not be great,
# since we use python lists here, while linked lists would be a better
# structure to use for such recursive solutions.
#
# Note also that such implementations are prone to stack overflow, since
# when recursion is used as a substitute for a loop, th... | def list_filter(lst, pred):
if not lst:
return []
(fst, *rest) = lst
if pred(fst):
return [fst] + list_filter(rest, pred)
else:
return list_filter(rest, pred)
def count_runs(lst):
if not lst:
return []
else:
(fst, *rest) = lst
for (index, elem) in... |
### Group the People Given the Group Size They Belong To - Solution
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
id_and_person = collections.defaultdict(list)
for person, id_ in enumerate(groupSizes):
id_and_person[id_].append(person)
final... | class Solution:
def group_the_people(self, groupSizes: List[int]) -> List[List[int]]:
id_and_person = collections.defaultdict(list)
for (person, id_) in enumerate(groupSizes):
id_and_person[id_].append(person)
final_group = tuple((val[i:i + key] for (key, val) in id_and_person.i... |
def cost_d(channel, amount):
return channel["outpol"]["base"] * 1000 + amount * channel["outpol"]["rate"]
def dist_d(channel, amount):
return 1
| def cost_d(channel, amount):
return channel['outpol']['base'] * 1000 + amount * channel['outpol']['rate']
def dist_d(channel, amount):
return 1 |
# Funcoes
# escopos dentro e fora
def funcao():
# escopo local
n1 = 4
print(f'N1 dentro vale {n1}')
n1 = 2
# escopo global
funcao()
print(f'N1 global vale {n1}')
| def funcao():
n1 = 4
print(f'N1 dentro vale {n1}')
n1 = 2
funcao()
print(f'N1 global vale {n1}') |
class EmptySubjectStorage:
def is_concurrency_safe(self):
return False
def is_persistent(self):
return False
def load(self):
return {}, {}
def store(self, inserts=[], updates=[], deletes=[]):
pass
def set(self, prop, old_value_default=None):
return Non... | class Emptysubjectstorage:
def is_concurrency_safe(self):
return False
def is_persistent(self):
return False
def load(self):
return ({}, {})
def store(self, inserts=[], updates=[], deletes=[]):
pass
def set(self, prop, old_value_default=None):
return (Non... |
#
# PySNMP MIB module HH3C-FC-FLOGIN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-FC-FLOGIN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:13:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ... |
def desenha(linha):
while linha > 0:
coluna = 1
while coluna <= linha:
print('*', end = "")
coluna = coluna + 1
print()
linha = linha - 1
desenha(5) | def desenha(linha):
while linha > 0:
coluna = 1
while coluna <= linha:
print('*', end='')
coluna = coluna + 1
print()
linha = linha - 1
desenha(5) |
# Momijigaoka | Unfamiliar Hillside
if sm.getFieldID() == 807040100:
sm.warp(807000000, 1)
else:
sm.warp(807040100, 0) | if sm.getFieldID() == 807040100:
sm.warp(807000000, 1)
else:
sm.warp(807040100, 0) |
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i*i)
'''
==>range(lower_limit , upper_limit , incerment / Decrement)
lower_limit is inclusive
upper_limit is not included
==>range(upper_limit)
''' | if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i * i)
'\n==>range(lower_limit , upper_limit , incerment / Decrement)\nlower_limit is inclusive\nupper_limit is not included\n\n==>range(upper_limit)\n' |
def get_token(fi='dont.mess.with.me'):
with open(fi, 'r') as f:
return f.readline().strip()
t = get_token() | def get_token(fi='dont.mess.with.me'):
with open(fi, 'r') as f:
return f.readline().strip()
t = get_token() |
choices = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
print('\n')
print('|' + choices[0] + '|' + choices[1] + '|' + choices[2] + '|')
print('----------')
print('|' + choices[3] + '|' + choices[4] + '|' + choices[5] + '|')
print('----------')
print('|' + choices[6] + '|' + choices[7] + '|' + choices[8] + '|')
| choices = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
print('\n')
print('|' + choices[0] + '|' + choices[1] + '|' + choices[2] + '|')
print('----------')
print('|' + choices[3] + '|' + choices[4] + '|' + choices[5] + '|')
print('----------')
print('|' + choices[6] + '|' + choices[7] + '|' + choices[8] + '|') |
class Solution:
def majorityElement(self, nums: list[int]) -> int:
current = 0
count = 0
for num in nums:
if count == 0:
current = num
count = 1
continue
if num == current:
count += 1
else:
... | class Solution:
def majority_element(self, nums: list[int]) -> int:
current = 0
count = 0
for num in nums:
if count == 0:
current = num
count = 1
continue
if num == current:
count += 1
else:
... |
#
# Binomial heap (Python)
#
# Copyright (c) 2018 Project Nayuki. (MIT License)
# https://www.nayuki.io/page/binomial-heap
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restrictio... | class Binomialtree:
def __init__(self, key):
self.key = key
self.children = []
self.order = 0
def add_at_end(self, t):
self.children.append(t)
self.order = self.order + 1
class Binomialheap:
def __init__(self):
self.trees = []
def extract_min(self):
... |
class NotFoundException(Exception):
pass
class ExistsException(Exception):
pass
class InvalidFilter(Exception):
pass
class IncorrectFormatException(Exception):
pass
| class Notfoundexception(Exception):
pass
class Existsexception(Exception):
pass
class Invalidfilter(Exception):
pass
class Incorrectformatexception(Exception):
pass |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: audit.py
ERR_AUDIT_SUCCESS = 0
ERR_AUDIT_DISABLE_FAILED = 1
ERR_AUDIT_ENABLE_FAILED = 2
ERR_AUDIT_UNKNOWN_TYPE = 3
ERR_AUDIT_EXCEPTION = 4
ERR_AUDIT_... | err_audit_success = 0
err_audit_disable_failed = 1
err_audit_enable_failed = 2
err_audit_unknown_type = 3
err_audit_exception = 4
err_audit_process_not_found = 5
err_audit_open_process_failed = 6
err_audit_module_base_not_found = 7
err_audit_read_memory_failed = 8
err_audit_memory_alloc_failed = 9
err_audit_pattern_mat... |
print(1+42
+246
+287
+728
+1434
+1673
+1880
+4264
+6237
+9799
+9855
+18330
+21352
+21385
+24856
+36531
+39990
+46655
+57270
+66815
+92664
+125255
+156570
+182665
+208182
+212949
+242879
+273265
+380511
+391345
+411558
+539560
+627215
+693160
+730145
+741096
+773224
+814463
+931722
+992680
+1069895
+1087009
+1143477
+11... | print(1 + 42 + 246 + 287 + 728 + 1434 + 1673 + 1880 + 4264 + 6237 + 9799 + 9855 + 18330 + 21352 + 21385 + 24856 + 36531 + 39990 + 46655 + 57270 + 66815 + 92664 + 125255 + 156570 + 182665 + 208182 + 212949 + 242879 + 273265 + 380511 + 391345 + 411558 + 539560 + 627215 + 693160 + 730145 + 741096 + 773224 + 814463 + 93172... |
features = [
{"name": "ntp", "ordered": True, "section": ["ntp server "]},
{"name": "vlan", "ordered": True, "section": ["vlan "]},
]
| features = [{'name': 'ntp', 'ordered': True, 'section': ['ntp server ']}, {'name': 'vlan', 'ordered': True, 'section': ['vlan ']}] |
backpack = False
dollars = .50
if backpack and dollars >= 1.0:
print('Ride the bus!')
| backpack = False
dollars = 0.5
if backpack and dollars >= 1.0:
print('Ride the bus!') |
t = int(input())
for i in range(t):
n, a, b, k = map(int, input().split())
f = 0
c = max(a, b)
d = min(a, b)
if c % d != 0:
f = n//c + n//d - 2 * (n//(c*d))
if c % d == 0:
f = n//d - n//c
if k <= f:
print("Win")
else:
print("Lose")
| t = int(input())
for i in range(t):
(n, a, b, k) = map(int, input().split())
f = 0
c = max(a, b)
d = min(a, b)
if c % d != 0:
f = n // c + n // d - 2 * (n // (c * d))
if c % d == 0:
f = n // d - n // c
if k <= f:
print('Win')
else:
print('Lose') |
#!/usr/bin/env python3
# Author : Chris Azzara
# Purpose : Repeatedly ask user to input an IP address and add it to a list.
# If the user enters in 10.10.3.1 or 10.20.5.2, warn user not to use this IP
# If the user enters a 'q', exit the loop and display the list of IP Addresses
# This script assu... | menu = "Enter in an IP Address or type 'q' to quit!\n"
ip_addrs = []
choice = ''
while choice.lower() != 'q':
choice = input(menu)
if choice == '10.10.3.1':
print("Error: That is the Gateway's IP address")
elif choice == '10.20.5.2':
print("Error: That is the DNS server's IP address")
el... |
#
# PySNMP MIB module CISCO-ATM-SWITCH-CUG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SWITCH-CUG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
__author__ = 'rramchandani'
class TimeOutException(Exception):
message = "There was a system timeout before operation could be able to complete."
class BuildError(Exception):
message = "Invalid Build ID"
class LoginError(Exception):
message = "It's mandatory be logged in; to execute this operation."
c... | __author__ = 'rramchandani'
class Timeoutexception(Exception):
message = 'There was a system timeout before operation could be able to complete.'
class Builderror(Exception):
message = 'Invalid Build ID'
class Loginerror(Exception):
message = "It's mandatory be logged in; to execute this operation."
cla... |
#Program to implement Round Robin
print("Round Robin Scheduling algorithm")
print("================================")
headers = ['Processes','Arrival Time','Burst Time','Completion Time','Waiting Time',
'Turn-Around Time']
out = []
quantum = int(input("Enter value for quantum := "))
N = int(input("Enter ... | print('Round Robin Scheduling algorithm')
print('================================')
headers = ['Processes', 'Arrival Time', 'Burst Time', 'Completion Time', 'Waiting Time', 'Turn-Around Time']
out = []
quantum = int(input('Enter value for quantum := '))
n = int(input('Enter number of processes := '))
bt = []
t = 0
for ... |
conjunto = set()
print(conjunto)
conjunto = {1,2,3}
conjunto.add(4)
conjunto.add(0)
conjunto.add('H')
conjunto.add('A')
conjunto.add('Z')
print(conjunto)
grupo = {'Hector', 'Juan', 'Mario'}
print('Hector' in grupo)
test = {'Hector', 'Hector', 'Hector'}
print(test)
# CASTEO
l = [1,2,3,3,2,1]
c = set(l)
print(c)
l ... | conjunto = set()
print(conjunto)
conjunto = {1, 2, 3}
conjunto.add(4)
conjunto.add(0)
conjunto.add('H')
conjunto.add('A')
conjunto.add('Z')
print(conjunto)
grupo = {'Hector', 'Juan', 'Mario'}
print('Hector' in grupo)
test = {'Hector', 'Hector', 'Hector'}
print(test)
l = [1, 2, 3, 3, 2, 1]
c = set(l)
print(c)
l = [1, 2,... |
n = list()
def notas(notes,sit=False):
report = dict()
report['Total'] = len(notes)
report['Highest'] = max(notes)
report['Lowest'] = min(notes)
report['Avg'] = sum(notes)/len(notes)
return report
quant = int(input("How many notes do you want to register: "))
for c in range(0,quant):
n.ap... | n = list()
def notas(notes, sit=False):
report = dict()
report['Total'] = len(notes)
report['Highest'] = max(notes)
report['Lowest'] = min(notes)
report['Avg'] = sum(notes) / len(notes)
return report
quant = int(input('How many notes do you want to register: '))
for c in range(0, quant):
n.... |
# -*- coding: utf-8 -*-
class Solution:
def totalHammingDistance(self, nums):
result = 0
for digit in range(32):
partial = 0
for num in nums:
partial += (num >> digit) & 1
result += partial * (len(nums) - partial)
return result
if __n... | class Solution:
def total_hamming_distance(self, nums):
result = 0
for digit in range(32):
partial = 0
for num in nums:
partial += num >> digit & 1
result += partial * (len(nums) - partial)
return result
if __name__ == '__main__':
solu... |
# initialize objects that control robot components
left_motor = Motor(1)
right_motor = Motor(2)
gyro = Gyro()
# create a controller object and set its goal
controller = PID(0.2, 0.002, 0.015, time, gyro)
controller.set_goal(0) # the goal is 0 because we want to head straight
while True:
# get the contr... | left_motor = motor(1)
right_motor = motor(2)
gyro = gyro()
controller = pid(0.2, 0.002, 0.015, time, gyro)
controller.set_goal(0)
while True:
controller_value = controller.get_value()
arcade_drive(controller_value, 0, left_motor, right_motor) |
def ask(prompt):
'''Get a number from the user.'''
while True:
ans = input(prompt)
if ans.upper().startswith("Q"):
return "Q"
if ans.isdigit():
return int(ans)
print("Sorry, invalid response. Please try again.") | def ask(prompt):
"""Get a number from the user."""
while True:
ans = input(prompt)
if ans.upper().startswith('Q'):
return 'Q'
if ans.isdigit():
return int(ans)
print('Sorry, invalid response. Please try again.') |
word = input("Enter your string: ")
dic = {}
length = len(word)
count = 0
lcount = 2
while True:
for elm in range(count,length):
if lcount >length:
break
temp = word[count:lcount]
if len(temp)%2 == 0:
atemp = temp[0:(len(temp)//2)]
btemp = temp[(len(t... | word = input('Enter your string: ')
dic = {}
length = len(word)
count = 0
lcount = 2
while True:
for elm in range(count, length):
if lcount > length:
break
temp = word[count:lcount]
if len(temp) % 2 == 0:
atemp = temp[0:len(temp) // 2]
btemp = temp[len(tem... |
class Menu:
def __init__(self, rdoc, on_add=None):
self.rdoc = rdoc
self.element = rdoc.element('nav')
vn = '#' + self.element.varname
self.rule_menu = rdoc.stylesheet.rule(vn)
self.rule_item = rdoc.stylesheet.rule(vn + ' > li')
self.rule_item_hover = rdoc.stylesheet... | class Menu:
def __init__(self, rdoc, on_add=None):
self.rdoc = rdoc
self.element = rdoc.element('nav')
vn = '#' + self.element.varname
self.rule_menu = rdoc.stylesheet.rule(vn)
self.rule_item = rdoc.stylesheet.rule(vn + ' > li')
self.rule_item_hover = rdoc.stylesheet... |
word1 = 'ox'
word2 = 'owl'
word3 = 'cow'
word4 = 'sheep'
word5 = 'flies'
word6 = 'trots'
word7 = 'runs'
word8 = 'blue'
word9 = 'red'
word10 = 'yellow'
word9 = 'The ' + word9
passcode = word8
passcode = word9
passcode = passcode + ' f'
passcode = passcode + word1
passcode = passcode + ' '
passcode = pass... | word1 = 'ox'
word2 = 'owl'
word3 = 'cow'
word4 = 'sheep'
word5 = 'flies'
word6 = 'trots'
word7 = 'runs'
word8 = 'blue'
word9 = 'red'
word10 = 'yellow'
word9 = 'The ' + word9
passcode = word8
passcode = word9
passcode = passcode + ' f'
passcode = passcode + word1
passcode = passcode + ' '
passcode = passcode + word6
pri... |
sigma_s = 1
N_d = 32
N_c = 8
K = 50
P_FA = 0.05
SNR = 10
SNR_LOW = -20
SNR_UP = 6
SNR_STEP = 2
SNR_NOISE = 1
P_H1 = 0.2
NUM_STATISTICS = 1000
#NUM_STATISTICS = 100000
| sigma_s = 1
n_d = 32
n_c = 8
k = 50
p_fa = 0.05
snr = 10
snr_low = -20
snr_up = 6
snr_step = 2
snr_noise = 1
p_h1 = 0.2
num_statistics = 1000 |
#Open file and store data
data = []
with open('inputs\input5.txt') as f:
data = f.readlines()
data = [line.strip() for line in data]
#Define Functions with Binary Conversions
def splitRowCol(boardingPass):
return(boardingPass[0:7],boardingPass[7:])
def convToBinary(inputStr,convToZero=["F","L"],convToOne... | data = []
with open('inputs\\input5.txt') as f:
data = f.readlines()
data = [line.strip() for line in data]
def split_row_col(boardingPass):
return (boardingPass[0:7], boardingPass[7:])
def conv_to_binary(inputStr, convToZero=['F', 'L'], convToOne=['B', 'R']):
input_str = list(inputStr)
for char_i... |
class Core(object):
def foo(self):
pass
c = Core()
| class Core(object):
def foo(self):
pass
c = core() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.