content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
count = 0
maximum = (-10) ** 9
for _ in range(4):
x = int(input())
if x % 2 == 1:
count += 1
if x > maximum:
maximum = x
if count > 0:
print(count)
print(maximum)
else:
print('NO')
| count = 0
maximum = (-10) ** 9
for _ in range(4):
x = int(input())
if x % 2 == 1:
count += 1
if x > maximum:
maximum = x
if count > 0:
print(count)
print(maximum)
else:
print('NO') |
raio = int(input('Raio: '))
format(r,'.2f')
pi = 3.14159
volume = (4/3)*pi*raio**3
print("Volume = ", format(volume,'.3f'))
#Para o URI:
R = float(input())
format(R,'.2f')
pi = 3.14159
v = (4/3)*pi*R**3
print("VOLUME = "+format(v,'.3f')) | raio = int(input('Raio: '))
format(r, '.2f')
pi = 3.14159
volume = 4 / 3 * pi * raio ** 3
print('Volume = ', format(volume, '.3f'))
r = float(input())
format(R, '.2f')
pi = 3.14159
v = 4 / 3 * pi * R ** 3
print('VOLUME = ' + format(v, '.3f')) |
# -*- coding: utf-8 -*-
# @Time: 2020/7/16 11:38
# @Author: GraceKoo
# @File: interview_8.py
# @Desc: https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4?tpId=13&rp=1&ru=%2Fta%2Fcoding-interviews&qr
# u=%2Fta%2Fcoding-interviews%2Fquestion-ranking
class Solution:
def climbStairs(self, n: int) -> in... | class Solution:
def climb_stairs(self, n: int) -> int:
if 0 <= n <= 2:
return n
dp = [i for i in range(n)]
dp[0] = 1
dp[1] = 2
for i in range(2, n):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[-1]
so = solution()
print(so.climbStairs(3)) |
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
def BackTrack(m, per: list):
if m == n:
if per not in permutation:
permutation.append(per)
return per
for i in range(n):
if not visited[i]:... | class Solution:
def permute_unique(self, nums: List[int]) -> List[List[int]]:
def back_track(m, per: list):
if m == n:
if per not in permutation:
permutation.append(per)
return per
for i in range(n):
if not visited... |
def f(*args):
summ = 0
for i in args:
if isinstance(i, list):
for s in i:
summ += f(s)
elif isinstance(i, tuple):
for s in i:
summ += s
else:
summ += i
return summ
a = [[1, 2, [3]], [1], 3]
b = (1, 2, 3, 4... | def f(*args):
summ = 0
for i in args:
if isinstance(i, list):
for s in i:
summ += f(s)
elif isinstance(i, tuple):
for s in i:
summ += s
else:
summ += i
return summ
a = [[1, 2, [3]], [1], 3]
b = (1, 2, 3, 4, 5)
print(... |
EMPTY_WORDS_PATH = "./palabrasvacias.txt"
# "palabrasvacias.txt"
# "emptywords.txt"
# None
DIRPATH = "/home/agustin/Desktop/Recuperacion/colecciones/RI-tknz-data/"
# "/home/agustin/Desktop/Recuperacion/colecciones/RI-tknz-data/"
# "/home/agustin/Desktop/Recuperacion/colecciones/wiki-small/"
# "/home/agustin/Desktop/Re... | empty_words_path = './palabrasvacias.txt'
dirpath = '/home/agustin/Desktop/Recuperacion/colecciones/RI-tknz-data/'
min_term_length = 3
max_term_length = 25
string_store_criterion = 'MAX'
docnames_size = 50
terms_size = 50
stemming_language = 'spanish'
extract_entities = False
corpus_files_encoding = 'UTF-8'
id_in_docna... |
# loop3
userinput = input("Enter a letter in the range A - C : ")
while (userinput != "A") and (userinput != "a") and (userinput != "B") and (userinput != "b") and (userinput != "C") and (userinput != "c"):
userinput = input("Enter a letter in the range A-C : ")
| userinput = input('Enter a letter in the range A - C : ')
while userinput != 'A' and userinput != 'a' and (userinput != 'B') and (userinput != 'b') and (userinput != 'C') and (userinput != 'c'):
userinput = input('Enter a letter in the range A-C : ') |
COLOR = {
'ORANGE': (255, 121, 0),
'LIGHT_YELLOW': (255, 230, 130),
'YELLOW': (255, 204, 0),
'LIGHT_BLUE': (148, 228, 228),
'BLUE': (51, 204, 204),
'LIGHT_RED': (255, 136, 106),
'RED': (255, 51, 0),
'LIGHT_GREEN': (206, 255, 60),
'GREEN': (153, 204, 0),
'CYAN': (0, 159, 218),
... | color = {'ORANGE': (255, 121, 0), 'LIGHT_YELLOW': (255, 230, 130), 'YELLOW': (255, 204, 0), 'LIGHT_BLUE': (148, 228, 228), 'BLUE': (51, 204, 204), 'LIGHT_RED': (255, 136, 106), 'RED': (255, 51, 0), 'LIGHT_GREEN': (206, 255, 60), 'GREEN': (153, 204, 0), 'CYAN': (0, 159, 218), 'BLUE_PAUL': (0, 59, 111), 'PURPLE': (161, 6... |
# -*- coding: utf-8 -*-
class Solution:
def minDeletionSize(self, A):
return len([col for col in zip(*A) if col != tuple(sorted(col))])
if __name__ == '__main__':
solution = Solution()
assert 1 == solution.minDeletionSize(['cba', 'daf', 'ghi'])
assert 0 == solution.minDeletionSize(['a', 'b'... | class Solution:
def min_deletion_size(self, A):
return len([col for col in zip(*A) if col != tuple(sorted(col))])
if __name__ == '__main__':
solution = solution()
assert 1 == solution.minDeletionSize(['cba', 'daf', 'ghi'])
assert 0 == solution.minDeletionSize(['a', 'b'])
assert 3 == solutio... |
# https://leetcode.com/problems/simplify-path/
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for d in path.split('/'):
if d == '..':
if len(stack) > 0:
stack.pop()
elif d == '.' or d == '':
continue
... | class Solution:
def simplify_path(self, path: str) -> str:
stack = []
for d in path.split('/'):
if d == '..':
if len(stack) > 0:
stack.pop()
elif d == '.' or d == '':
continue
else:
stack.append(... |
# Guess password and output the score
chocolate = 2
playerlives = 1
playername = "Aung"
# this loop clears the screen
for i in range(1, 35):
print()
bonus = 0
numbercorrect = 0
# the player must try to guess the password
print("Now you must ener each letter that you remember ")
print("You will be given 3 times")... | chocolate = 2
playerlives = 1
playername = 'Aung'
for i in range(1, 35):
print()
bonus = 0
numbercorrect = 0
print('Now you must ener each letter that you remember ')
print('You will be given 3 times')
i = 0
while i < 3:
i = i + 1
letter = input('Try number ' + str(i) + ' : ')
if letter == 'A' or letter... |
#!/usr/bin/env python3
def best_stock(data):
return sorted(data.items(), key=lambda x: x[1])[-1][0]
if __name__ == '__main__':
print(best_stock({ "CAL": 42.0, "GOG": 190.5, "DAG": 32.2 }))
assert best_stock({ "CAL": 42.0, "GOG": 190.5, "DAG": 32.2 }) == "GOG"
assert best_stock({ "CAL": 31.4, "GOG": 3... | def best_stock(data):
return sorted(data.items(), key=lambda x: x[1])[-1][0]
if __name__ == '__main__':
print(best_stock({'CAL': 42.0, 'GOG': 190.5, 'DAG': 32.2}))
assert best_stock({'CAL': 42.0, 'GOG': 190.5, 'DAG': 32.2}) == 'GOG'
assert best_stock({'CAL': 31.4, 'GOG': 3.42, 'APL': 170.34}) == 'APL' |
def find_position(matrix, size, symbol):
positions = []
for row in range(size):
for col in range(size):
if matrix[row][col] == symbol:
positions.append([row, col])
return positions
def is_position_valid(row, col, size):
return 0 <= row < size and 0 <= col < size
d... | def find_position(matrix, size, symbol):
positions = []
for row in range(size):
for col in range(size):
if matrix[row][col] == symbol:
positions.append([row, col])
return positions
def is_position_valid(row, col, size):
return 0 <= row < size and 0 <= col < size
def... |
items = {key: {} for key in input().split(", ")}
n = int(input())
for _ in range(n):
line = input().split(" - ")
category, item = line[0], line[1]
items_count = line[2].split(";")
quantity = int(items_count[0].split(":")[1])
quality = int(items_count[1].split(":")[1])
items[category][item] = (... | items = {key: {} for key in input().split(', ')}
n = int(input())
for _ in range(n):
line = input().split(' - ')
(category, item) = (line[0], line[1])
items_count = line[2].split(';')
quantity = int(items_count[0].split(':')[1])
quality = int(items_count[1].split(':')[1])
items[category][item] =... |
cnt = int(input())
for i in range(cnt):
s=input()
a=s.lower()
g=a.count('g')
b=a.count('b')
print(s,"is",end=" ")
if g == b:
print("NEUTRAL")
elif g>b:
print("GOOD")
else:
print("A BADDY") | cnt = int(input())
for i in range(cnt):
s = input()
a = s.lower()
g = a.count('g')
b = a.count('b')
print(s, 'is', end=' ')
if g == b:
print('NEUTRAL')
elif g > b:
print('GOOD')
else:
print('A BADDY') |
print("Enter a character:\n")
ch=input()
while(len(ch)!=1):
print("\nShould Enter single Character...RETRY!")
ch=input()
print(ord(ch))
| print('Enter a character:\n')
ch = input()
while len(ch) != 1:
print('\nShould Enter single Character...RETRY!')
ch = input()
print(ord(ch)) |
class Solution:
def parseTernary(self, expression: str) -> str:
c, values = expression.split('?', 1)
cnt = 0
p = 0
for i in range(len(values)):
if values[i] == ':':
if cnt > 0:
cnt -= 1
else:
p = i
... | class Solution:
def parse_ternary(self, expression: str) -> str:
(c, values) = expression.split('?', 1)
cnt = 0
p = 0
for i in range(len(values)):
if values[i] == ':':
if cnt > 0:
cnt -= 1
else:
p = ... |
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# just use a sliding window
np, ns = len(p), len(s)
res = []
if np > ns: return []
map_ = [0] * 26
for i,x in enumerate(p):
map_[ord(x) - 97] -= 1
map_[ord(s[i])-97]... | class Solution:
def find_anagrams(self, s: str, p: str) -> List[int]:
(np, ns) = (len(p), len(s))
res = []
if np > ns:
return []
map_ = [0] * 26
for (i, x) in enumerate(p):
map_[ord(x) - 97] -= 1
map_[ord(s[i]) - 97] += 1
for i in ... |
memMap = {}
def fibonacci (n):
if (n not in memMap):
if n <= 0:
print("Invalid input")
elif n == 1:
memMap[n] = 0
elif n == 2:
memMap[n] = 1
else:
memMap[n] = fibonacci (n-1) + fibonacci (n-2)
return memMap[n]
def fibonacciSlow (n):
if n <= 0:
print("Invalid inpu... | mem_map = {}
def fibonacci(n):
if n not in memMap:
if n <= 0:
print('Invalid input')
elif n == 1:
memMap[n] = 0
elif n == 2:
memMap[n] = 1
else:
memMap[n] = fibonacci(n - 1) + fibonacci(n - 2)
return memMap[n]
def fibonacci_slow(n... |
def embarque(motorista:str, passageiro:str, saida:dict):
fortwo = {'motorista': motorista, 'passageiro': passageiro}
saida['pessoas'].remove(motorista)
print(f"{fortwo['motorista']} embarcou como motorista")
if passageiro != '':
saida['pessoas'].remove(passageiro)
print(f"{fortwo['passa... | def embarque(motorista: str, passageiro: str, saida: dict):
fortwo = {'motorista': motorista, 'passageiro': passageiro}
saida['pessoas'].remove(motorista)
print(f"{fortwo['motorista']} embarcou como motorista")
if passageiro != '':
saida['pessoas'].remove(passageiro)
print(f"{fortwo['pas... |
class UnfoldingResult:
def __init__(self, solution, error):
self.solution = solution
self.error = error
| class Unfoldingresult:
def __init__(self, solution, error):
self.solution = solution
self.error = error |
# input number of testcases
test=int(input())
for i in range(test):
# input the number of predicted prices for WOT
n=int(input())
# input array of predicted stock price
a=list(map(int,input().split()))
c=0
i=len(a)-1
while(i>=0):
d=a[i]
l=i
p=0
while(a[i]<=d a... | test = int(input())
for i in range(test):
n = int(input())
a = list(map(int, input().split()))
c = 0
i = len(a) - 1
while i >= 0:
d = a[i]
l = i
p = 0
while a[i] <= d and i >= 0:
p += a[i]
i -= 1
c += (l - i) * a[l] - p
continue... |
class node:
def __init__(self,value):
self.data=value
self.next=None
self.prev=None
class DoubleLinkedList:
def __init__(self):
self.head=None
def insertAtBeg(self,value):
newnode = node(value)
if self.head==None:
self.head=newnode
else:
... | class Node:
def __init__(self, value):
self.data = value
self.next = None
self.prev = None
class Doublelinkedlist:
def __init__(self):
self.head = None
def insert_at_beg(self, value):
newnode = node(value)
if self.head == None:
self.head = newn... |
#!usr/bin/python
class Enviroment:
sets = []
banned = [] | class Enviroment:
sets = []
banned = [] |
'''
udata-schema-gouvfr
Integration with schema.data.gouv.fr
'''
__version__ = '1.3.3.dev'
__description__ = 'Integration with schema.data.gouv.fr'
| """
udata-schema-gouvfr
Integration with schema.data.gouv.fr
"""
__version__ = '1.3.3.dev'
__description__ = 'Integration with schema.data.gouv.fr' |
#
# PySNMP MIB module WIENER-CRATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/WIENER-CRATE-MIB
# Produced by pysmi-0.3.4 at Fri Jan 31 21:36:11 2020
# On host bier platform Linux version 5.4.0-3-amd64 by user tin
# Using Python version 3.7.6 (default, Jan 19 2020, 22:34:5... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Source code meta data
__author__ = 'Dalwar Hossain'
__email__ = 'dalwar.hossain@protonmail.com'
# Version
__version__ = '1.1'
__release__ = '1.1'
| __author__ = 'Dalwar Hossain'
__email__ = 'dalwar.hossain@protonmail.com'
__version__ = '1.1'
__release__ = '1.1' |
__version__ = '0.12.1'
__prog_name__ = 'DOLfYN'
__version_date__ = 'May-07-2020'
def ver2tuple(ver):
if isinstance(ver, tuple):
return ver
# ### Previously used FLOATS for 'save-format' versioning.
# Version 1.0: underscore ('_') handled inconsistently.
# Version 1.1: '_' and '#' handled consi... | __version__ = '0.12.1'
__prog_name__ = 'DOLfYN'
__version_date__ = 'May-07-2020'
def ver2tuple(ver):
if isinstance(ver, tuple):
return ver
if isinstance(ver, (float, int)):
return (0, int(ver), int(round(10 * (ver % 1))))
out = []
for val in ver.split('.'):
try:
val ... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
def find_deletions(friends_file_path, new_friends_list):
deleted = ""
f1 = open(friends_file_path, "r")
data2 = new_friends_list
for line in f1:
if data2.find(line) == -1:
print ("--" +line),
deleted += line
f1.close()
return deleted
def find_additions(friends_file_path, new_friends_list):
added = "... | def find_deletions(friends_file_path, new_friends_list):
deleted = ''
f1 = open(friends_file_path, 'r')
data2 = new_friends_list
for line in f1:
if data2.find(line) == -1:
(print('--' + line),)
deleted += line
f1.close()
return deleted
def find_additions(friends_... |
# Copyright 2013 Daniel Stokes, Mitchell Stokes
#
# 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 ... | def get_condition(args):
return CONDITION_LUT[args[0]](*args[1:])
class Alwayscondition:
__slots__ = []
def test(self, data):
return True
class Rangecondition:
__slots__ = ['property', 'min', 'max']
def __init__(self, prop, _min, _max):
self.property = prop
if type(_min) ... |
__title__ = 'pinecone-backend'
__summary__ = 'Domain.'
__version__ = '0.0.1-dev'
__license__ = 'All rights reserved.'
__uri__ = 'http://vigotech.org/'
__author__ = 'VigoTech'
__email__ = 'alliance@vigotech.org'
| __title__ = 'pinecone-backend'
__summary__ = 'Domain.'
__version__ = '0.0.1-dev'
__license__ = 'All rights reserved.'
__uri__ = 'http://vigotech.org/'
__author__ = 'VigoTech'
__email__ = 'alliance@vigotech.org' |
'''
This problem was asked by Facebook.
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular
expression and r... | """
This problem was asked by Facebook.
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular
expression and r... |
def permutations_with_dups(string):
hash_table = {}
permutations = []
for character in string:
if character in hash_table:
hash_table[character] += 1
else:
hash_table[character] = 1
helper('', hash_table, permutations)
return permutations
def helper(string, ... | def permutations_with_dups(string):
hash_table = {}
permutations = []
for character in string:
if character in hash_table:
hash_table[character] += 1
else:
hash_table[character] = 1
helper('', hash_table, permutations)
return permutations
def helper(string, h... |
#
# @lc app=leetcode id=1004 lang=python3
#
# [1004] Max Consecutive Ones III
#
# https://leetcode.com/problems/max-consecutive-ones-iii/description/
#
# algorithms
# Medium (61.32%)
# Likes: 2593
# Dislikes: 40
# Total Accepted: 123.4K
# Total Submissions: 202.1K
# Testcase Example: '[1,1,1,0,0,0,1,1,1,1,0]\n2'... | class Solution:
def longest_ones(self, nums: List[int], k: int) -> int:
if not nums or len(nums) == 0:
return 0
(left, right) = (0, 0)
if nums[right] == 0:
k -= 1
n = len(nums)
max_length = 0
for left in range(n):
while right + 1 <... |
SECRET_KEY = "fake-key"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"rest_email_manager",
]
TEMPLATES = [
{
"BACKEND": "django.template.backends.djan... | secret_key = 'fake-key'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'rest_email_manager']
templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True}]
root_urlconf = 'tests... |
photos = Photo.objects.all()
captions = []
for idx, photo in enumerate(photos):
if idx > 2:
break
thumbnail_path = photo.thumbnail.url
with open("." + thumbnail_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
encoded_string = str(encoded_string)[2:-1]
resp_captions = requests.po... | photos = Photo.objects.all()
captions = []
for (idx, photo) in enumerate(photos):
if idx > 2:
break
thumbnail_path = photo.thumbnail.url
with open('.' + thumbnail_path, 'rb') as image_file:
encoded_string = base64.b64encode(image_file.read())
encoded_string = str(encoded_string)[2:-1]
... |
def quickSort(my_array):
qshelper(my_array, 0, len(my_array) - 1)
return my_array
def qshelper(my_array, start, end):
if start >= end:
return
pivot = start
left = start + 1
right = end
while right >= left:
if my_array[left] > my_array[pivot] and my_array[right] < ... | def quick_sort(my_array):
qshelper(my_array, 0, len(my_array) - 1)
return my_array
def qshelper(my_array, start, end):
if start >= end:
return
pivot = start
left = start + 1
right = end
while right >= left:
if my_array[left] > my_array[pivot] and my_array[right] < my_array[p... |
class Category:
def __init__(self, name):
self.name = name
self.ledger = []
def __str__(self):
l = len(self.name)
n1 = 15-int(l/2)
n2 = 30-(n1+l)
title = "*"*n1+self.name+"*"*n2+"\n"
summary = ""
for item in self.ledger:
a= format(item[... | class Category:
def __init__(self, name):
self.name = name
self.ledger = []
def __str__(self):
l = len(self.name)
n1 = 15 - int(l / 2)
n2 = 30 - (n1 + l)
title = '*' * n1 + self.name + '*' * n2 + '\n'
summary = ''
for item in self.ledger:
... |
#Max value from a list
numbers = []
lenght = int(input("Enter list lenght...\n"))
for i in range(lenght):
numbers.append(float(input("Enter an integer or decimal number...\n")))
print("The min value is: " + str(min(numbers)))
| numbers = []
lenght = int(input('Enter list lenght...\n'))
for i in range(lenght):
numbers.append(float(input('Enter an integer or decimal number...\n')))
print('The min value is: ' + str(min(numbers))) |
#----------------------------------------------------------------------------------------------------------
#
# AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX
#
# NAME: Reconnect by Title
# COLOR: #6b4930
#
#----------------------------------------------------------------------------------------------------------
... | ns = [n for n in nuke.selectedNodes() if n.knob('identifier')]
for n in ns:
try:
n['reconnect_by_title_this'].execute()
except:
pass |
l = ["Camera", "Laptop", "Phone", "ipad", "Hard Disk", "Nvidia Graphic 3080 card"]
# sentence = "~~".join(l)
# sentence = "==".join(l)
sentence = "\n".join(l)
print(sentence)
print(type(sentence)) | l = ['Camera', 'Laptop', 'Phone', 'ipad', 'Hard Disk', 'Nvidia Graphic 3080 card']
sentence = '\n'.join(l)
print(sentence)
print(type(sentence)) |
# Copyright 2021 Google LLC
#
# 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, s... | class Schemamode:
backend = 'BE'
frontend = 'FE'
def make_type(typename, required):
if required:
return [typename]
else:
return ['null', typename]
def add_field(schema, name, field_type):
schema['fields'].append({'name': name, 'type': field_type})
def add_string(schema, name, requ... |
# Roll the Dice #
# November 17, 2018
# By Robin Nash
n = int(input())
m = int(input())
if n > 10:
n = 9
if m > 10:
m = 9
ways = 0
for n in range (1,n+1):
for m in range(1,m+1):
if n + m == 10:
ways+=1
if ways == 1:
print("There is 1 way to get the sum 10.")
e... | n = int(input())
m = int(input())
if n > 10:
n = 9
if m > 10:
m = 9
ways = 0
for n in range(1, n + 1):
for m in range(1, m + 1):
if n + m == 10:
ways += 1
if ways == 1:
print('There is 1 way to get the sum 10.')
else:
print('There are', ways, 'ways to get the sum 10.') |
Carros = ['HRV', 'Polo', 'Jetta', 'Palio', 'Fusca']
itCarros = iter(Carros)
while itCarros:
try:
print(next(itCarros))
except StopIteration:
print('Fim da Lista.')
break | carros = ['HRV', 'Polo', 'Jetta', 'Palio', 'Fusca']
it_carros = iter(Carros)
while itCarros:
try:
print(next(itCarros))
except StopIteration:
print('Fim da Lista.')
break |
def default_colors(n):
n = max(n, 8)
clist = ["#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e", "#e6ab02",
"#a6761d", "#666666"]
return clist[:n]
| def default_colors(n):
n = max(n, 8)
clist = ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666']
return clist[:n] |
def nth_fibonacci_using_recursion(n):
if n < 0:
raise ValueError("n should be a positive number or zero")
else:
if n == 1:
return 0
elif n == 2:
return 1
else:
return nth_fibonacci_using_recursion(n - 2) + nth_fibonacci_using_recursion(n - 1)
... | def nth_fibonacci_using_recursion(n):
if n < 0:
raise value_error('n should be a positive number or zero')
elif n == 1:
return 0
elif n == 2:
return 1
else:
return nth_fibonacci_using_recursion(n - 2) + nth_fibonacci_using_recursion(n - 1)
def nth_fibonacci_using_iterati... |
class OpenInterest:
def __init__(self):
self.symbol = ""
self.openInterest = 0.0
@staticmethod
def json_parse(json_data):
result = OpenInterest()
result.symbol = json_data.get_string("symbol")
result.openInterest = json_data.get_float("openInterest")
... | class Openinterest:
def __init__(self):
self.symbol = ''
self.openInterest = 0.0
@staticmethod
def json_parse(json_data):
result = open_interest()
result.symbol = json_data.get_string('symbol')
result.openInterest = json_data.get_float('openInterest')
return... |
with open("input.txt") as input_file:
time = int(input_file.readline().strip())
busses = input_file.readline().strip().split(",")
def departures(bus):
multiplier = 0
while True:
multiplier += 1
yield multiplier * bus
def next_after(bus, time):
for departure in departures(bus):
... | with open('input.txt') as input_file:
time = int(input_file.readline().strip())
busses = input_file.readline().strip().split(',')
def departures(bus):
multiplier = 0
while True:
multiplier += 1
yield (multiplier * bus)
def next_after(bus, time):
for departure in departures(bus):
... |
# -*- coding: utf-8 -*-
maior = -1
index_maior = -1
for i in range(1, 101):
n = int(input())
if n > maior:
maior = n
index_maior = i
print(maior)
print(index_maior)
| maior = -1
index_maior = -1
for i in range(1, 101):
n = int(input())
if n > maior:
maior = n
index_maior = i
print(maior)
print(index_maior) |
# This sample tests a particularly difficult set of dependent
# assignments that involve tuple packing and unpacking.
# pyright: strict
v1 = ""
v3 = ""
v2, _ = v1, v3
v4 = v2
for _ in range(1):
v1 = v4
v2, v3 = v1, ""
| v1 = ''
v3 = ''
(v2, _) = (v1, v3)
v4 = v2
for _ in range(1):
v1 = v4
(v2, v3) = (v1, '') |
class DNABattleCell:
COMPONENT_CODE = 21
def __init__(self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
def setWidth(self, width):
self.width = width
def setHeight(self, height):
self.height = height
def setWidthHeight(self,... | class Dnabattlecell:
component_code = 21
def __init__(self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def set_width_height(s... |
def median(a):
a = sorted(a)
list_length = len(a)
num = list_length//2
if list_length % 2 == 0:
median_num = (a[num] + a[num + 1])/2
else:
median_num = a[num]
return median_num
| def median(a):
a = sorted(a)
list_length = len(a)
num = list_length // 2
if list_length % 2 == 0:
median_num = (a[num] + a[num + 1]) / 2
else:
median_num = a[num]
return median_num |
class DeviceGroup:
def __init__(self, name):
self.name = name
self.devices = []
def addDevice(self, newDevice):
self.devices.append(newDevice)
# Just thinking through how I want the program to work.
# A diskgroup should be initialized once every time the service is started. ... | class Devicegroup:
def __init__(self, name):
self.name = name
self.devices = []
def add_device(self, newDevice):
self.devices.append(newDevice) |
# -*- coding: utf-8 -*-
USER_ROLE = {
'USER': 0,
'MODERATOR': 1,
'ADMINISTRATOR': 2,
} | user_role = {'USER': 0, 'MODERATOR': 1, 'ADMINISTRATOR': 2} |
a = 1
print("a_module: Hi from my_package/" + __name__ + ".py!")
if __name__ == "__main__":
print("a_module: I was invoked from a script.")
else:
print("a_module: I was invoked from a Pyton module (probably using 'import').")
print("a_module: My name is =", __name__)
| a = 1
print('a_module: Hi from my_package/' + __name__ + '.py!')
if __name__ == '__main__':
print('a_module: I was invoked from a script.')
else:
print("a_module: I was invoked from a Pyton module (probably using 'import').")
print('a_module: My name is =', __name__) |
#
# PySNMP MIB module ZYXEL-MES2110-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-MES2110-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:50:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) ... |
userNum = int(input("Input a number: "))
out = ""
numeralArr = [(1000, "M"), (500, "D"), (100, "C"), (50, "L"), (10, "X"), (5, "V"), (1, "I"), (0, ""), (0, "")]
def convert(num, nums, iters, halfs):
global out
if n... | user_num = int(input('Input a number: '))
out = ''
numeral_arr = [(1000, 'M'), (500, 'D'), (100, 'C'), (50, 'L'), (10, 'X'), (5, 'V'), (1, 'I'), (0, ''), (0, '')]
def convert(num, nums, iters, halfs):
global out
if num >= nums[0] - iters[0]:
out += iters[1] + nums[1]
num -= nums[0] - iters[0]
... |
d = {}
palavra = 'Felipe Schmaedecke'
for l in palavra:
if l in d:
d[l] = d[l] + 1
else:
d[l] = 1
print(d)
| d = {}
palavra = 'Felipe Schmaedecke'
for l in palavra:
if l in d:
d[l] = d[l] + 1
else:
d[l] = 1
print(d) |
class ECA:
def __init__(self, id):
self.id = bin(id)[2:].zfill(8)
self.dict = {}
for i in range(8):
self.dict[bin(7 - i)[2:].zfill(3)] = self.id[i]
self.array = [0 for x in range(199)]
self.array[99] = 1
def step(self):
arr = [0 for x in range(len(s... | class Eca:
def __init__(self, id):
self.id = bin(id)[2:].zfill(8)
self.dict = {}
for i in range(8):
self.dict[bin(7 - i)[2:].zfill(3)] = self.id[i]
self.array = [0 for x in range(199)]
self.array[99] = 1
def step(self):
arr = [0 for x in range(len(se... |
expected_output = {
"service_instance": {
501: {
"interfaces": {
"TenGigabitEthernet0/3/0": {"state": "Up", "type": "Static"},
"TenGigabitEthernet0/1/0": {"state": "Up", "type": "Static"},
}
},
502: {
"interfaces": {"TenGiga... | expected_output = {'service_instance': {501: {'interfaces': {'TenGigabitEthernet0/3/0': {'state': 'Up', 'type': 'Static'}, 'TenGigabitEthernet0/1/0': {'state': 'Up', 'type': 'Static'}}}, 502: {'interfaces': {'TenGigabitEthernet0/3/0': {'state': 'Up', 'type': 'Static'}}}}} |
class KNNClassifier(object):
def __init__(self, k=3, distance=None):
self.k = k
self.distance = distance
def fit(self, x, y):
pass
def predict(self, x):
pass
def __decision_function(self):
pass
| class Knnclassifier(object):
def __init__(self, k=3, distance=None):
self.k = k
self.distance = distance
def fit(self, x, y):
pass
def predict(self, x):
pass
def __decision_function(self):
pass |
'''
Given a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# s... | """
Given a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
"""
class Solution(object):
def swap_pairs(self, head):
if not head or not head.next:
return hea... |
with open("Prob03.in.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
nola = content.pop(0)
for x in content:
x = x.strip(" ")
x = x.split()
add = int(x[0]) + int(x[1])
multi = int(x[0]) * int(x[1])
print( str(add) + " " + str(multi))
| with open('Prob03.in.txt') as f:
content = f.readlines()
content = [x.strip() for x in content]
nola = content.pop(0)
for x in content:
x = x.strip(' ')
x = x.split()
add = int(x[0]) + int(x[1])
multi = int(x[0]) * int(x[1])
print(str(add) + ' ' + str(multi)) |
## Script (Python) "getFotoCapa"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Retorna um nome de arquivo para ser usado como foto da capa
padrao = [ 'capa01.jpg','capa02.jpg','capa03.jpg','capa04.jpg','capa05.jpg', \
... | padrao = ['capa01.jpg', 'capa02.jpg', 'capa03.jpg', 'capa04.jpg', 'capa05.jpg', 'capa06.jpg', 'capa07.jpg']
ultimo = context.portal_catalog.searchResults(portal_type='Programa', sort_on='getData', sort_order='reverse', review_state='published')[0]
imagem = ultimo.getImagem
if not imagem:
imagem = context.portal_url... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class DoubanPipeline(object):
# def __init__(self, server, port):
# pass
# @classmethod
# def from_craw... | class Doubanpipeline(object):
def process_item(self, item, spider):
return item |
#
# PySNMP MIB module CISCO-LAG-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LAG-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:47:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_union, constraints_intersection) ... |
mylist = ["banana", "apple", "pineapple"]
print(mylist)
item = mylist[2]
print(item)
if "banana" in mylist:
print("yes")
else:
print("no")
mylist.append("lemon")
print(mylist)
mylist.insert(2, "grapes")
print(mylist)
# /item = [0] * 5
# print(item)
| mylist = ['banana', 'apple', 'pineapple']
print(mylist)
item = mylist[2]
print(item)
if 'banana' in mylist:
print('yes')
else:
print('no')
mylist.append('lemon')
print(mylist)
mylist.insert(2, 'grapes')
print(mylist) |
# These functions deal with displaying information in CLI
## Check Payment Display
def display_lessons(lessons):
print('displaying lesson payment info')
unpaid_lessons = []
paid_lessons = []
for lesson in lessons:
if lesson['paid'] == 'n':
unpaid_lessons.append(lesson)
elif... | def display_lessons(lessons):
print('displaying lesson payment info')
unpaid_lessons = []
paid_lessons = []
for lesson in lessons:
if lesson['paid'] == 'n':
unpaid_lessons.append(lesson)
elif lesson['paid'] == 'y':
paid_lessons.append(lesson)
for lesson in unp... |
city = input("Enter city name = ")
sales = int(input("Enter sales volume = "))
cities = ["Sofia", "Varna", "Plovdiv"]
index = 4
#Discounts by cities
if 0 <= sales and sales <= 500:
comision = [0.05,0.045,0.055]
elif 500 < sales and sales <= 1000:
comision = [0.07,0.075,0.08]
elif 1000 < sales and sales <= 1000... | city = input('Enter city name = ')
sales = int(input('Enter sales volume = '))
cities = ['Sofia', 'Varna', 'Plovdiv']
index = 4
if 0 <= sales and sales <= 500:
comision = [0.05, 0.045, 0.055]
elif 500 < sales and sales <= 1000:
comision = [0.07, 0.075, 0.08]
elif 1000 < sales and sales <= 10001:
comision = ... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-S
def crypt(line: str) -> str:
result = str()
for symbol in line:
result += chr(ord(symbol) + 1)
return result
print(crypt(input()))
| def crypt(line: str) -> str:
result = str()
for symbol in line:
result += chr(ord(symbol) + 1)
return result
print(crypt(input())) |
class Solution:
# not my soln but its very cool
def threeSum(self, nums: List[int]) -> List[List[int]]:
triplets = set()
neg, pos, zeros = [], [], 0
for num in nums:
if num > 0:
pos.append(num)
elif num < 0:
neg.append(num)
... | class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
triplets = set()
(neg, pos, zeros) = ([], [], 0)
for num in nums:
if num > 0:
pos.append(num)
elif num < 0:
neg.append(num)
else:
zero... |
def change_return(amount,currency):
currency.sort(reverse = True)
counter = 0
amount_counter = [0]*len(currency)
while amount> 0:
amount_counter[counter] = int(amount/currency[counter])
amount -= amount_counter[counter]*currency[counter]
counter += 1
return [(currency[i],amou... | def change_return(amount, currency):
currency.sort(reverse=True)
counter = 0
amount_counter = [0] * len(currency)
while amount > 0:
amount_counter[counter] = int(amount / currency[counter])
amount -= amount_counter[counter] * currency[counter]
counter += 1
return [(currency[i... |
# helpers.py, useful helper functions for wikipedia analysis
# We want to represent known symbols (starting with //) as words, the rest characters
def extract_tokens(tex):
'''walk through a LaTeX string, and grab chunks that correspond with known
identifiers, meaning anything that starts with \ and ends wit... | def extract_tokens(tex):
"""walk through a LaTeX string, and grab chunks that correspond with known
identifiers, meaning anything that starts with \\ and ends with one or
more whitespaces, a bracket, a ^ or underscore.
"""
regexp = '\\\\(.*?)(\\w+|\\{|\\(|\\_|\\^)'
tokens = []
while re... |
def seed_everything(seed=2020):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
seed_everything(42) | def seed_everything(seed=2020):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
seed_everything(42) |
class Solution:
def XXX(self, root: TreeNode) -> int:
if not root:
return 0
self.min_depth = float('inf')
def dfs(root, depth):
if not root:
return
if not root.left and not root.right:
self.min_depth = min(self.min_depth, d... | class Solution:
def xxx(self, root: TreeNode) -> int:
if not root:
return 0
self.min_depth = float('inf')
def dfs(root, depth):
if not root:
return
if not root.left and (not root.right):
self.min_depth = min(self.min_depth... |
#!/usr/bin/env python3
# Find the middle element in the list.
# Create a function called middle_element that has one parameter named lst.
# If there are an odd number of elements in lst, the function
# should return the middle element.
# If there are an even number of elements, the function should
# return the average... | def middle_element(lst):
if len(lst) % 2 == 0:
sum = lst[int(len(lst) / 2)] + lst[int(len(lst) / 2) - 1]
return sum / 2
else:
return lst[int(len(lst) / 2)]
print(middle_element([5, 2, -10, -4, 4, 5])) |
class Microstate():
def __init__(self):
self.index = None
self.label = None
self.weight = 0.0
self.probability = 0.0
self.basin = None
self.coordinates = None
self.color = None
self.size = None
| class Microstate:
def __init__(self):
self.index = None
self.label = None
self.weight = 0.0
self.probability = 0.0
self.basin = None
self.coordinates = None
self.color = None
self.size = None |
intraband_incharge = {
"WEIMIN": None,
"EBREAK": None,
"DEPER": None,
"TIME": None,
}
| intraband_incharge = {'WEIMIN': None, 'EBREAK': None, 'DEPER': None, 'TIME': None} |
program_name = 'giraf'
program_desc = 'A command line utility to access imgur.com.'
| program_name = 'giraf'
program_desc = 'A command line utility to access imgur.com.' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.