content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Continuing from following challenge and using subroutines where appropriate:
1. Create a text file with the following data:
James,Jones,01/01/99
Sarah,Smith,12/12/99
Bobby,Ball,04/04/99
Harry.Hall,06/06/99
2. Create a subroutine to ask the user for the name of the file that they wish to read from
3. Use a loop to r... | """
Continuing from following challenge and using subroutines where appropriate:
1. Create a text file with the following data:
James,Jones,01/01/99
Sarah,Smith,12/12/99
Bobby,Ball,04/04/99
Harry.Hall,06/06/99
2. Create a subroutine to ask the user for the name of the file that they wish to read from
3. Use a loop to r... |
n = 0
try:
i = 0
while True:
m = input()
if m[0] == '+':
n += 1
elif m[0] == '-':
n -= 1
else:
i += (len(m.split(':')[1]) * n)
except:
pass
print(i)
| n = 0
try:
i = 0
while True:
m = input()
if m[0] == '+':
n += 1
elif m[0] == '-':
n -= 1
else:
i += len(m.split(':')[1]) * n
except:
pass
print(i) |
def box(m):
m = m.lower() # converting lowercase
arr = [0] * len(m) # initializing array with same length as the length
i = 0
for n in m:
if not ('a' <= n <= 'z'): # excluding special characters
continue
arr[i] = ord(n) - ord('a') # subtracting ascii character values by a... | def box(m):
m = m.lower()
arr = [0] * len(m)
i = 0
for n in m:
if not 'a' <= n <= 'z':
continue
arr[i] = ord(n) - ord('a')
i += 1
arr_f = arr[0:i]
return arr_f
def lock(arr_f, y):
a = len(arr_f)
k = box(y)
b = 1
while b < a:
k.append(k... |
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... | class Job:
def __init__(self, job: dict):
self.display_name = job.get('displayName')
self.id = job.get('id')
self.group = job.get('group')
self.status = job.get('status')
self.data = job.get('data')
self.description = job.get('description')
self.batch = job.g... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def grpc_rules_repository():
http_archive(
name = "rules_proto_grpc",
urls = ["https://github.com/rules-proto-grpc/rules_proto_grpc/archive/2.0.0.tar.gz"],
sha256 = "d771584bbff98698e7cb3cb31c132ee206a972569f4dc8b65acbdd93... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def grpc_rules_repository():
http_archive(name='rules_proto_grpc', urls=['https://github.com/rules-proto-grpc/rules_proto_grpc/archive/2.0.0.tar.gz'], sha256='d771584bbff98698e7cb3cb31c132ee206a972569f4dc8b65acbdd934d156b33', strip_prefix='rules_... |
class Embed:
def __init__(self, **kwargs):
allowed_args = ("title", "description", "color")
for key, value in kwargs.items():
if key in allowed_args:
setattr(self, key, value)
def set_image(self, *, url: str):
self.image = {"url": url}
def set_thumbnail... | class Embed:
def __init__(self, **kwargs):
allowed_args = ('title', 'description', 'color')
for (key, value) in kwargs.items():
if key in allowed_args:
setattr(self, key, value)
def set_image(self, *, url: str):
self.image = {'url': url}
def set_thumbna... |
a = 7
b = 3
def func1(c,d):
e = c + d
e += c
e *= d
return e
f = func1(a,b)
print (f) | a = 7
b = 3
def func1(c, d):
e = c + d
e += c
e *= d
return e
f = func1(a, b)
print(f) |
a: str
a: bool = True
my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA = 1
| a: str
a: bool = True
my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA = 1 |
class Edge(object):
def __init__(self, u, v, w):
self.__orig = u
self.__dest = v
self.__w = w
def getOrig(self):
return self.__orig
def getDest(self):
return self.__dest
def getW(self):
return self.__w
| class Edge(object):
def __init__(self, u, v, w):
self.__orig = u
self.__dest = v
self.__w = w
def get_orig(self):
return self.__orig
def get_dest(self):
return self.__dest
def get_w(self):
return self.__w |
"""
Subtree of Another Tree:
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s.
A subtree of s is a tree consists of a node in s and all of this node's descendants.
The tree s could also be considered as a subtree of itself.
https://leetco... | """
Subtree of Another Tree:
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s.
A subtree of s is a tree consists of a node in s and all of this node's descendants.
The tree s could also be considered as a subtree of itself.
https://leetco... |
class UltrasonicSensor:
def __init__(self, megapi, slot):
self._megapi = megapi
self._slot = slot
self._last_val = 400
def read(self):
self._megapi.ultrasonicSensorRead(self._slot, self._on_forward_ultrasonic_read)
def get_value(self):
return self._last_val
... | class Ultrasonicsensor:
def __init__(self, megapi, slot):
self._megapi = megapi
self._slot = slot
self._last_val = 400
def read(self):
self._megapi.ultrasonicSensorRead(self._slot, self._on_forward_ultrasonic_read)
def get_value(self):
return self._last_val
de... |
def f(t):
# relation between f and t
return value
def rxn1(C,t):
return np.array([f(t)*C0/v-f(t)*C[0]/v-k*C[0], f(t)*C[0]/v-f(t)*C[1]/v-k*C[1]])
| def f(t):
return value
def rxn1(C, t):
return np.array([f(t) * C0 / v - f(t) * C[0] / v - k * C[0], f(t) * C[0] / v - f(t) * C[1] / v - k * C[1]]) |
#Three Restaurant:
class Restaurant():
"""A simple attempt to make class restaurant. """
def __init__(self, restaurant_name, cuisine_type):
""" This is to initialize name and type of restaurant"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe... | class Restaurant:
"""A simple attempt to make class restaurant. """
def __init__(self, restaurant_name, cuisine_type):
""" This is to initialize name and type of restaurant"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
... |
name = input("what is your name? ")
age = int(input("how old are you {0}? ".format(name)))
if (18 <= age < 31):
print("welcome to holiday")
else:
print("you are not 18-30") | name = input('what is your name? ')
age = int(input('how old are you {0}? '.format(name)))
if 18 <= age < 31:
print('welcome to holiday')
else:
print('you are not 18-30') |
"""The code template to supply to the front end. This is what the user will
be asked to complete and submit for grading.
Do not include any imports.
This is not a REPL environment so include explicit 'print' statements
for any outputs you want to be displayed back to the user.
Use triple single q... | """The code template to supply to the front end. This is what the user will
be asked to complete and submit for grading.
Do not include any imports.
This is not a REPL environment so include explicit 'print' statements
for any outputs you want to be displayed back to the user.
Use triple single q... |
a,b = map(int,input().split())
def multiply(a,b):
return a*b
print(multiply(a,b)) | (a, b) = map(int, input().split())
def multiply(a, b):
return a * b
print(multiply(a, b)) |
class CoordLinkedList:
# a linked list object
def __init__ (self,node=None,y=None,x=None,up=None,down=None,left=None,right=None):
self.up = up
self.down = down
self.left = left
self.right = right
if isinstance(node,(list,set,tuple)) and len(n... | class Coordlinkedlist:
def __init__(self, node=None, y=None, x=None, up=None, down=None, left=None, right=None):
self.up = up
self.down = down
self.left = left
self.right = right
if isinstance(node, (list, set, tuple)) and len(node) == 2:
self.node = tuple(node)
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
data = []
def traverse(node):
if node.left:
... | class Solution:
def kth_smallest(self, root: TreeNode, k: int) -> int:
data = []
def traverse(node):
if node.left:
traverse(node.left)
data.append(node.val)
if node.right:
traverse(node.right)
traverse(root)
return... |
# List custom images
def list_custom_images_subparser(subparser):
list_images = subparser.add_parser(
'list-custom-images',
description=('***List custom'
' saved images of'
... | def list_custom_images_subparser(subparser):
list_images = subparser.add_parser('list-custom-images', description='***List custom saved images of producers/consumers account', help='List custom saved images of producers/consumers account')
group_key = list_images.add_mutually_exclusive_group(required=True)
... |
"""
Use zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix. There's actually a cool trick for this! Feel free to look at the solutions if you can't figure it out.
"""
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
# 0 1 2
# 3 4 5
# 6 7 8
# 9 10 11
#
# Transpose : [data]^T
#
# 0 3 6 9
# 1 4... | """
Use zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix. There's actually a cool trick for this! Feel free to look at the solutions if you can't figure it out.
"""
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))
print(data)
print(data_transpose) |
#
# @lc app=leetcode id=543 lang=python3
#
# [543] Diameter of Binary Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root):
... | class Solution:
def diameter_of_binary_tree(self, root):
self.ans = 0
self.pathfinder(root)
return self.ans
def pathfinder(self, root):
if root is None:
return 0
lh = self.pathfinder(root.left)
rh = self.pathfinder(root.right)
self.ans = max(... |
VISUALIZATION_CONFIG = {
'requirements': ['d3', 'datagramas', 'topojson', 'cartogram'],
'visualization_name': 'datagramas.cartogram',
'figure_id': None,
'container_type': 'svg',
'data': {
'geometry': None,
'area_dataframe': None,
},
'options': {
},
'variables': {
... | visualization_config = {'requirements': ['d3', 'datagramas', 'topojson', 'cartogram'], 'visualization_name': 'datagramas.cartogram', 'figure_id': None, 'container_type': 'svg', 'data': {'geometry': None, 'area_dataframe': None}, 'options': {}, 'variables': {'width': 960, 'height': 500, 'padding': {'left': 0, 'top': 0, ... |
class Solution(object):
def reconstructQueue(self, people):
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
m = int(input())
k = Solution()
array_input = []
for x in range(m):
array_input.append([int... | class Solution(object):
def reconstruct_queue(self, people):
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
m = int(input())
k = solution()
array_input = []
for x in range(m):
array_input.append([int(y) for ... |
def pent_d(n=1, pents=set()):
while True:
p_n = n*(3*n - 1)//2
for p in pents:
if p_n - p in pents and 2*p - p_n in pents:
return 2*p - p_n
pents.add(p_n)
n += 1
print(pent_d())
# Copyright Junipyr. All rights reserved.
# https://github.com/Junipyr | def pent_d(n=1, pents=set()):
while True:
p_n = n * (3 * n - 1) // 2
for p in pents:
if p_n - p in pents and 2 * p - p_n in pents:
return 2 * p - p_n
pents.add(p_n)
n += 1
print(pent_d()) |
n = int(input())
for i in range(n):
vet = list(map(int, input().split()))
partida = vet[0]
qtd = vet[1]
if partida % 2 == 0:
partida += 1
soma = 0
for j in range(qtd):
soma += partida
partida += 2
print(soma)
| n = int(input())
for i in range(n):
vet = list(map(int, input().split()))
partida = vet[0]
qtd = vet[1]
if partida % 2 == 0:
partida += 1
soma = 0
for j in range(qtd):
soma += partida
partida += 2
print(soma) |
# Scrapy settings for Scrapy project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.... | bot_name = 'scrapy_demo'
spider_modules = ['Scrapy.spiders']
newspider_module = 'Scrapy.spiders'
log_level = 'INFO'
closespider_pagecount = 20
user_agent = 'Scrapy Demo'
robotstxt_obey = False
images_expires = 1
images_store = './images'
item_pipelines = {'scrapy.pipelines.images.ImagesPipeline': 1, 'Scrapy.pipelines.B... |
# Copyright 2020 Adobe. All rights reserved.
# This file is licensed 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 ... | load('@io_bazel_rules_docker//container:providers.bzl', 'PushInfo')
load('@io_bazel_rules_docker//skylib:path.bzl', _get_runfile_path='runfile')
load('//skylib:providers.bzl', 'ImagePushesInfo')
load('//skylib/workspace:aspect.bzl', 'pushable_aspect')
def _file_to_runfile(ctx, file):
return file.owner.workspace_ro... |
def changecode():
file1=input("Enter your file name1")
file2=input("Enter your file name2")
with open(file1,"r") as a:
data_a = a.read()
with open(file2,"r") as b:
data_b = b.read()
with open(file1,"w") as a:
a.write(data_b)
with open(file2,"w") as b:
b.... | def changecode():
file1 = input('Enter your file name1')
file2 = input('Enter your file name2')
with open(file1, 'r') as a:
data_a = a.read()
with open(file2, 'r') as b:
data_b = b.read()
with open(file1, 'w') as a:
a.write(data_b)
with open(file2, 'w') as b:
b.wr... |
"""
1119. Remove Vowels from a String
Easy
Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: "aeiou"
Output: ""
Note:
S consists of lowercase English letters only... | """
1119. Remove Vowels from a String
Easy
Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: "aeiou"
Output: ""
Note:
S consists of lowercase English letters only... |
ll=range(5, 20, 5)
for i in ll:
print(i)
print (ll)
x = 'Python'
for i in range(len(x)) :
print(x[i]) | ll = range(5, 20, 5)
for i in ll:
print(i)
print(ll)
x = 'Python'
for i in range(len(x)):
print(x[i]) |
# Function returns nth element of Padovan sequence
def padovan(n):
p = 0
if n > 2:
p = padovan(n-2) + padovan(n-3)
return p
else:
p = 1
return p
def main():
while True:
n = int(input("Enter a number: "))
if n >= 0:
break
print("In... | def padovan(n):
p = 0
if n > 2:
p = padovan(n - 2) + padovan(n - 3)
return p
else:
p = 1
return p
def main():
while True:
n = int(input('Enter a number: '))
if n >= 0:
break
print('Invalid number,try again')
print(f'P({n}) = {padov... |
li = []
for x in range (21):
li.append(x)
print(li)
del(li[4])
print(li)
| li = []
for x in range(21):
li.append(x)
print(li)
del li[4]
print(li) |
routes = {
'{"command": "stats"}' : {"STATUS":[{"STATUS":"S","When":1553711204,"Code":70,"Msg":"BMMiner stats","Description":"bmminer 1.0.0"}],"STATS":[{"BMMiner":"2.0.0","Miner":"16.8.1.3","CompileTime":"Fri Nov 17 17:37:49 CST 2017","Type":"Antminer S9"},{"STATS":0,"ID":"BC50","Elapsed":248,"Calls":0,"Wait":0.00000... | routes = {'{"command": "stats"}': {'STATUS': [{'STATUS': 'S', 'When': 1553711204, 'Code': 70, 'Msg': 'BMMiner stats', 'Description': 'bmminer 1.0.0'}], 'STATS': [{'BMMiner': '2.0.0', 'Miner': '16.8.1.3', 'CompileTime': 'Fri Nov 17 17:37:49 CST 2017', 'Type': 'Antminer S9'}, {'STATS': 0, 'ID': 'BC50', 'Elapsed': 248, 'C... |
class DatabaseNotConnectedException(Exception):
"""This exception is raised when collection is accessed however database is
not connected.
"""
def __init__(self, message: str):
self.message = message
super().__init__(self.message)
| class Databasenotconnectedexception(Exception):
"""This exception is raised when collection is accessed however database is
not connected.
"""
def __init__(self, message: str):
self.message = message
super().__init__(self.message) |
def folder_to_dict(folder):
return {
'id': folder.folder_id,
'name': folder.name,
'class': folder.folder_class,
'total_count': folder.total_count,
'child_folder_count': folder.child_folder_count,
'unread_count': folder.unread_count
}
def item_to_dict(item, inclu... | def folder_to_dict(folder):
return {'id': folder.folder_id, 'name': folder.name, 'class': folder.folder_class, 'total_count': folder.total_count, 'child_folder_count': folder.child_folder_count, 'unread_count': folder.unread_count}
def item_to_dict(item, include_body=False):
result = {'id': item.item_id, 'chan... |
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='sweetberry'
# the names j2, j3, and j4 are the white banks on sweetberry
# Note that here the bank name in the mux position is optional
# as... | config_type = 'sweetberry'
inas = [('sweetberry', '0x40:3', 'j2_1', 5.0, 0.01, 'j2', False), ('sweetberry', '0x40:1', 'j2_2', 5.0, 0.01, 'j2', False), ('sweetberry', '0x40:2', 'j2_3', 5.0, 0.01, 'j2', False), ('sweetberry', '0x40:0', 'j2_4', 5.0, 0.01, 'j2', False), ('sweetberry', '0x41:3', 'j2_5', 5.0, 0.01, 'j2', Fal... |
# Project Euler Problem 4
# Pranav Mital
# function to check if a number is a palindrome
def isPalindrome(n):
flag = 0
str_n = str(n)
for i in range((len(str_n)//2)):
if str_n[i] != str_n[len(str_n)-1-i]:
flag += 1
if flag != 0:
return False
else:
return True
#... | def is_palindrome(n):
flag = 0
str_n = str(n)
for i in range(len(str_n) // 2):
if str_n[i] != str_n[len(str_n) - 1 - i]:
flag += 1
if flag != 0:
return False
else:
return True
largest_palindrome = 0
for i in range(100, 1000):
for j in range(100, 1000):
... |
def f(var=("""
str
""",1)):
pass
anothervar=1
| def f(var=('\nstr\n', 1)):
pass
anothervar = 1 |
class PyFileBuilder:
def __init__(self, name):
self._import_line = None
self._file_funcs = []
self.name = name
def add_imports(self, *modules_names):
import_list = []
for module in modules_names:
import_list.append("import " + module)
if len(import... | class Pyfilebuilder:
def __init__(self, name):
self._import_line = None
self._file_funcs = []
self.name = name
def add_imports(self, *modules_names):
import_list = []
for module in modules_names:
import_list.append('import ' + module)
if len(import_l... |
# Create a program such that when given a non-negative number input, output whether or not if the number is 2 away from a multiple of 10.
# input
num = int(input('Enter a positive number: '))
# processing & output
if (num + 2) % 10 == 0:
print(num, 'is 2 away from a multiple of 10.')
elif (num - 2) % 10 == 0:
... | num = int(input('Enter a positive number: '))
if (num + 2) % 10 == 0:
print(num, 'is 2 away from a multiple of 10.')
elif (num - 2) % 10 == 0:
print(num, 'is 2 away from a multiple of 10.')
else:
print(num, 'is not 2 away from a multiple of 10.') |
#URL:https://www.hackerrank.com/challenges/balanced-brackets/problem?h_r=profile
def check_close(top, ch):
if ch =="(" and top ==")":
return True
if ch =="[" and top =="]":
return True
if ch =="{" and top =="}":
return True
return False
def isBalanced(s):
stack=[]
for ... | def check_close(top, ch):
if ch == '(' and top == ')':
return True
if ch == '[' and top == ']':
return True
if ch == '{' and top == '}':
return True
return False
def is_balanced(s):
stack = []
for ch in s:
if ch == '(' or ch == '[' or ch == '{':
stack... |
def tickets(disabled,users):
'''
cheks if disabeld or not
'''
a = input("are you disabled or not: ")
if a == 'disabled':
disabled = 200
return disabled
elif a == 'not':
users = 500
return users
tickets(200,500)
| def tickets(disabled, users):
"""
cheks if disabeld or not
"""
a = input('are you disabled or not: ')
if a == 'disabled':
disabled = 200
return disabled
elif a == 'not':
users = 500
return users
tickets(200, 500) |
class Solution:
# 1st solution, Lagrange's four square theorem
# O(sqart(n)) time | O(1) space
def numSquares(self, n: int) -> int:
if int(sqrt(n))**2 == n: return 1
for j in range(int(sqrt(n)) + 1):
if int(sqrt(n - j*j))**2 == n - j*j: return 2
while n % 4 =... | class Solution:
def num_squares(self, n: int) -> int:
if int(sqrt(n)) ** 2 == n:
return 1
for j in range(int(sqrt(n)) + 1):
if int(sqrt(n - j * j)) ** 2 == n - j * j:
return 2
while n % 4 == 0:
n >>= 2
if n % 8 == 7:
re... |
#
# PySNMP MIB module CISCO-ATM-SWITCH-FR-RM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SWITCH-FR-RM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) ... |
# Credentials for your Twitter bot account
# 1. Sign into Twitter or create new account
# 2. Make sure your mobile number is listed at twitter.com/settings/devices
# 3. Head to apps.twitter.com and select Keys and Access Tokens
CONSUMER_KEY = '6gTma2ITYHEh7MZMRJaflnxK7'
CONSUMER_SECRET = 'a20hHEbN1qudaR6RAdMCHtPKdOjp... | consumer_key = '6gTma2ITYHEh7MZMRJaflnxK7'
consumer_secret = 'a20hHEbN1qudaR6RAdMCHtPKdOjpjiiNKabXjhj52Ajb4uHz2S'
access_token = '1051987549487534081-quzVSEUw33JJiImQ7mSnyvZvdTsmln'
access_secret = 'Uz5w4bC3heTN3efnA5yuh7lOZZMzYzkZYThykqRgnZUtu' |
numbers=list(range(1,21,2))
for i in range(len(numbers)):
print(numbers[i])
| numbers = list(range(1, 21, 2))
for i in range(len(numbers)):
print(numbers[i]) |
#for c in range(2, 52, 2):
#print(c, end=' ')
#print('Acabo')
for c in range(1, 11):
print(c +c)
| for c in range(1, 11):
print(c + c) |
class Table:
def __init__(self, table):
self._table = table
@property
def name(self):
return self._table.__name__
@property
def thead(self):
all_fields = self._table._meta.fields
return [
field.verbose_name for field in all_fields if field.verbose_name !... | class Table:
def __init__(self, table):
self._table = table
@property
def name(self):
return self._table.__name__
@property
def thead(self):
all_fields = self._table._meta.fields
return [field.verbose_name for field in all_fields if field.verbose_name != 'ID']
... |
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `In... | class Dataprocessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise not_implemented_error()
def get_dev_examples(self, data_dir):
"""Gets... |
class AmazonAnsible:
"""Main class to generate Ansible playbooks from Amazon
Args:
debug (bool, optional): debug option. Defaults to False.
from_file (str, optional): Optional file with all data. Defaults to ''.
"""
class AmazonAnsibleCalculation:
"""Class to generate all Ansible play... | class Amazonansible:
"""Main class to generate Ansible playbooks from Amazon
Args:
debug (bool, optional): debug option. Defaults to False.
from_file (str, optional): Optional file with all data. Defaults to ''.
"""
class Amazonansiblecalculation:
"""Class to generate all Ansible playb... |
"""
Given an array of size n where all elements are distinct and in range from 0 to n-1,
change contents of arr[] so that arr[i] = j is changed to arr[j] = i.
"""
def rearrange(arr: list) -> list:
"""
Simplest approach would be to create and fill a temp array.
But it would require extra space.
In case... | """
Given an array of size n where all elements are distinct and in range from 0 to n-1,
change contents of arr[] so that arr[i] = j is changed to arr[j] = i.
"""
def rearrange(arr: list) -> list:
"""
Simplest approach would be to create and fill a temp array.
But it would require extra space.
In case ... |
in_data = {
u'deliveryOrder': {
u'warehouseCode': u'OTHER',
u'deliveryOrderCode': u'3600120100000',
u'receiverInfo': {
u'detailAddress': u'\u5927\u5382\u680818\u53f7101',
u'city': u'\u4e94\u8fde',
u'province': u'\u5c71\u4e1c',
u'area': u'\u592... | in_data = {u'deliveryOrder': {u'warehouseCode': u'OTHER', u'deliveryOrderCode': u'3600120100000', u'receiverInfo': {u'detailAddress': u'大厂栈18号101', u'city': u'五连', u'province': u'山东', u'area': u'大厂'}, u'senderInfo': {u'detailAddress': u'文三路172号', u'city': u'杭州'}}, u'orderLines': {u'orderLine': [{u'itemId': u'0192010101... |
pkgname = "firmware-ipw2100"
pkgver = "1.3"
pkgrel = 0
pkgdesc = "Firmware for the Intel PRO/Wireless 2100 wifi cards"
maintainer = "q66 <q66@chimera-linux.org>"
license = "custom:ipw2100"
url = "http://ipw2100.sourceforge.net"
source = f"http://firmware.openbsd.org/firmware-dist/ipw2100-fw-{pkgver}.tgz"
sha256 = "e110... | pkgname = 'firmware-ipw2100'
pkgver = '1.3'
pkgrel = 0
pkgdesc = 'Firmware for the Intel PRO/Wireless 2100 wifi cards'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'custom:ipw2100'
url = 'http://ipw2100.sourceforge.net'
source = f'http://firmware.openbsd.org/firmware-dist/ipw2100-fw-{pkgver}.tgz'
sha256 = 'e110... |
'''Generates a javascript string to display flot graphs.
Please read README_flot_grapher.txt
Eliane Stampfer: eliane.stampfer@gmail.com
April 2009'''
class FlotGraph(object):
#constructor. Accepts an array of data, a title, an array of toggle-able data, and the
#width and height of the graph. All of these valu... | """Generates a javascript string to display flot graphs.
Please read README_flot_grapher.txt
Eliane Stampfer: eliane.stampfer@gmail.com
April 2009"""
class Flotgraph(object):
def __init__(self, data=[], title='', toggle_data=[], width='600', height='300'):
self.display_title = title
self.title = ... |
def merge(seq, first, mid, last):
(left, right) = (seq[first: mid], seq[mid: last])
(l, r, curr) = (0, 0, first)
(left_size, right_size) = (len(left), len(right))
while l != left_size and r != right_size:
if left[l] < right[r]:
seq[curr] = left[l]
l += 1
else:
... | def merge(seq, first, mid, last):
(left, right) = (seq[first:mid], seq[mid:last])
(l, r, curr) = (0, 0, first)
(left_size, right_size) = (len(left), len(right))
while l != left_size and r != right_size:
if left[l] < right[r]:
seq[curr] = left[l]
l += 1
else:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Decode:
def __init__(self, length, K, n, weight):
self.K = K
self.length = length
self.n = n
self.weight = weight
self.solution = [False for i in range(0, n + 1)]
def Search(self):
... | class Decode:
def __init__(self, length, K, n, weight):
self.K = K
self.length = length
self.n = n
self.weight = weight
self.solution = [False for i in range(0, n + 1)]
def search(self):
insert = [[False for k in range(0, self.K + 2)] for i in range(0, self.n + ... |
lines = []
with open('input.txt','r') as INPUT:
lines = INPUT.readlines()
M = int(lines[0])
stack = [None]*M
stack_head = -1
with open('output.txt', 'w') as OUTPUT:
for op in lines[1:]:
if op.startswith('+'):
stack_head += 1
stack[stack_head] = op[2:]
eli... | lines = []
with open('input.txt', 'r') as input:
lines = INPUT.readlines()
m = int(lines[0])
stack = [None] * M
stack_head = -1
with open('output.txt', 'w') as output:
for op in lines[1:]:
if op.startswith('+'):
stack_head += 1
stack[stack_head] = op[2:]
elif op.startswit... |
class BaseScraper:
pass
| class Basescraper:
pass |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 17:12:03 2020
@author: kanukuma
"""
def popularNFeatures(numFeatures, topFeatures, possibleFeatures,
numFeatureRequests, featureRequests):
ngramsList = []
resultList = []
for featureRequest in featureRequests:
ngramsList.append( fe... | """
Created on Sun Jun 14 17:12:03 2020
@author: kanukuma
"""
def popular_n_features(numFeatures, topFeatures, possibleFeatures, numFeatureRequests, featureRequests):
ngrams_list = []
result_list = []
for feature_request in featureRequests:
ngramsList.append(featureRequest.split())
print(ngram... |
def is_sequence(x):
""" Returns whether x is a sequence (tuple, list).
:param x: a value to check
:returns: (boolean)
"""
return (not hasattr(x, 'strip') and
hasattr(x, '__getitem__') or
hasattr(x, '__iter__'))
| def is_sequence(x):
""" Returns whether x is a sequence (tuple, list).
:param x: a value to check
:returns: (boolean)
"""
return not hasattr(x, 'strip') and hasattr(x, '__getitem__') or hasattr(x, '__iter__') |
k = int(input())
s = input()
prevlen = 0
ans = 0
for i in range(k, len(s)):
if s[i] == s[i - k]:
prevlen += 1
ans += prevlen
else:
prevlen = 0
print(ans)
| k = int(input())
s = input()
prevlen = 0
ans = 0
for i in range(k, len(s)):
if s[i] == s[i - k]:
prevlen += 1
ans += prevlen
else:
prevlen = 0
print(ans) |
##########################################################################
# Gene prediction pipeline
#
# $Id: AGP.py 2781 2009-09-10 11:33:14Z andreas $
#
# Copyright (C) 2005 Andreas Heger
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public... | """AGP.py - working with AGP files
=====================================================
This module contains a parser for reading from :term:`agp` formatted
files.
Code
----
"""
class Objectposition(object):
def map(self, start, end):
if self.mOrientation:
return (start + self.start, end ... |
# Equality checks should behave the same way as assignment
# Variable equality check
bar == {'a': 1, 'b':2}
bar == {
'a': 1,
'b': 2,
}
# Function equality check
foo() == {
'a': 1,
'b': 2,
'c': 3,
}
foo(1, 2, 3) == {
'a': 1,
'b': 2,
'c': 3,
}
| bar == {'a': 1, 'b': 2}
bar == {'a': 1, 'b': 2}
foo() == {'a': 1, 'b': 2, 'c': 3}
foo(1, 2, 3) == {'a': 1, 'b': 2, 'c': 3} |
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.append(0) # here to make sure stack pop off
stack = [-1]
ans = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
... | class Solution:
def largest_rectangle_area(self, heights: List[int]) -> int:
heights.append(0)
stack = [-1]
ans = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
... |
class TicTacToe:
def __init__(self):
self.cells = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
self.matrix = [self.cells[0:3], self.cells[3:6], self.cells[6:9]]
# Vertical lines list, to be divided in 3 inner lists:
self.v_lines = []
# Diagonal lines:
self.d1_line = ... | class Tictactoe:
def __init__(self):
self.cells = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
self.matrix = [self.cells[0:3], self.cells[3:6], self.cells[6:9]]
self.v_lines = []
self.d1_line = [self.matrix[0][0], self.matrix[1][1], self.matrix[2][2]]
self.d2_line = [self.m... |
#coding=utf-8
'''
Created on 2015-9-24
@author: Devuser
'''
class CITestingTaskPropertyNavBar(object):
'''
classdocs
'''
def __init__(self,request,**args):
self.request=request
self.ci_task=args['ci_task']
if args['property_nav_action'] == 'history':
self.result_ac... | """
Created on 2015-9-24
@author: Devuser
"""
class Citestingtaskpropertynavbar(object):
"""
classdocs
"""
def __init__(self, request, **args):
self.request = request
self.ci_task = args['ci_task']
if args['property_nav_action'] == 'history':
self.result_active = '... |
msg = str(input('Digite uma mensagem'))
n = 0
n = len(msg)
def escreva():
print('-'*n)
print(msg)
print('-'*n)
escreva()
| msg = str(input('Digite uma mensagem'))
n = 0
n = len(msg)
def escreva():
print('-' * n)
print(msg)
print('-' * n)
escreva() |
class UVWarpModifier:
axis_u = None
axis_v = None
bone_from = None
bone_to = None
center = None
object_from = None
object_to = None
uv_layer = None
vertex_group = None
| class Uvwarpmodifier:
axis_u = None
axis_v = None
bone_from = None
bone_to = None
center = None
object_from = None
object_to = None
uv_layer = None
vertex_group = None |
#
# Copyright Cloudlab URV 2020
#
# 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 writin... | _set = set
lithops_config = 'LITHOPS_CONFIG'
stream_stdout = 'STREAM_STDOUT'
redis_expiry_time = 'REDIS_EXPIRY_TIME'
redis_connection_type = 'REDIS_CONNECTION_TYPE'
_default_config = {LITHOPS_CONFIG: {}, STREAM_STDOUT: False, REDIS_EXPIRY_TIME: 300, REDIS_CONNECTION_TYPE: 'pubsubconn'}
_config = _DEFAULT_CONFIG
def se... |
class NotAllowed(Exception):
"""when change class.id"""
class DatabaseException(Exception):
"""Database error"""
class ColumnTypeUnknown(Exception):
"""Variable type unknown"""
class NoFieldException(Exception):
"""Class has no variables"""
class WhereUsageException(Exception... | class Notallowed(Exception):
"""when change class.id"""
class Databaseexception(Exception):
"""Database error"""
class Columntypeunknown(Exception):
"""Variable type unknown"""
class Nofieldexception(Exception):
"""Class has no variables"""
class Whereusageexception(Exception):
"""Detected error... |
'''
Vasya the Hipster
red blue socks
simple one
'''
socks = list(map(int, input().split(' ')))
socks.sort()
diff = socks[0]
left = socks[1]-socks[0]
same = left//2
#output format
s = str(diff) + ' ' + str(same)
print(s)
| """
Vasya the Hipster
red blue socks
simple one
"""
socks = list(map(int, input().split(' ')))
socks.sort()
diff = socks[0]
left = socks[1] - socks[0]
same = left // 2
s = str(diff) + ' ' + str(same)
print(s) |
def fun(a, b, c, d):
return a + b + c + d
def inc(a):
return a + 1
def add(a, b):
return a + b
| def fun(a, b, c, d):
return a + b + c + d
def inc(a):
return a + 1
def add(a, b):
return a + b |
x_arr = []
y_arr = []
for _ in range(3):
x, y = map(int, input().split())
x_arr.append(x)
y_arr.append(y)
for i in range(3):
if x_arr.count(x_arr[i]) == 1:
x4 = x_arr[i]
if y_arr.count(y_arr[i]) == 1:
y4 = y_arr[i]
print(f'{x4} {y4}') | x_arr = []
y_arr = []
for _ in range(3):
(x, y) = map(int, input().split())
x_arr.append(x)
y_arr.append(y)
for i in range(3):
if x_arr.count(x_arr[i]) == 1:
x4 = x_arr[i]
if y_arr.count(y_arr[i]) == 1:
y4 = y_arr[i]
print(f'{x4} {y4}') |
# Methods of Tuple in Python:
# Declaring tuple
tuple = (3, 4, 6, 8, 10, 1, 67)
# Code for printing the length of a tuple
tuple2 = ('Apple', 'Bannana', 'Kiwi')
print('length of tuple2 :', len(tuple2))
# Deleting the tuple
del tuple2
# Printing tuple till 2 index excluding 2
print('tuple[0:2]:', tuple[0:2])
# Disp... | tuple = (3, 4, 6, 8, 10, 1, 67)
tuple2 = ('Apple', 'Bannana', 'Kiwi')
print('length of tuple2 :', len(tuple2))
del tuple2
print('tuple[0:2]:', tuple[0:2])
print('tuple[::-1]:', tuple[::-1])
print('maximum element in tuple:', max(tuple))
print('minimum element in tuple:', min(tuple))
print('Number of times 7 repeated:',... |
encoded_bytes=bytes.fromhex("664B564276757A7274796D477A4D4C7A545057456D47575971566F75585A694F4F454B677771647053544E5452654C6F434C544F6E702E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2... | encoded_bytes = bytes.fromhex('664B564276757A7274796D477A4D4C7A545057456D47575971566F75585A694F4F454B677771647053544E5452654C6F434C544F6E702E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2... |
def solve(data):
result = 0
# Iterates through each value of the list and sums it to the result
for number in data:
result += number
# Returns result (total sum)
return result | def solve(data):
result = 0
for number in data:
result += number
return result |
A = int(input())
B = int(input())
PROD = A*B
print("PROD = " + str(PROD))
| a = int(input())
b = int(input())
prod = A * B
print('PROD = ' + str(PROD)) |
def get_metadata(accessions, metadata_database):
#Quirk - metadata accession has .1 as a part of the accession id
accessions_fixed = []
for accession in accessions:
accessions_fixed.append(accession+'.1')
accessions_data = metadata_database.loc[metadata_database['acc'].isin(accessions_fixed)]
... | def get_metadata(accessions, metadata_database):
accessions_fixed = []
for accession in accessions:
accessions_fixed.append(accession + '.1')
accessions_data = metadata_database.loc[metadata_database['acc'].isin(accessions_fixed)]
return accessions_data
def calc_sens_spec(start, end, genus_regi... |
def clean_dict(json):
"""
Remove keys with the value None from the dictionary
"""
for key, value in list(json.items()):
if value is None:
del json[key]
elif isinstance(value, dict):
clean_dict(value)
return json | def clean_dict(json):
"""
Remove keys with the value None from the dictionary
"""
for (key, value) in list(json.items()):
if value is None:
del json[key]
elif isinstance(value, dict):
clean_dict(value)
return json |
def towerOfHanoi(n, source, auxiliary, destination):
if n == 0:
return 0
# Move n-1 from source to auxiliary using destination
stepCnt1 = towerOfHanoi(n-1, source, destination, auxiliary)
# Move nth disc from source to destination
print(f"{n} {source} -> {destination}")
# move n-1 fro... | def tower_of_hanoi(n, source, auxiliary, destination):
if n == 0:
return 0
step_cnt1 = tower_of_hanoi(n - 1, source, destination, auxiliary)
print(f'{n} {source} -> {destination}')
step_cnt2 = tower_of_hanoi(n - 1, auxiliary, source, destination)
return 1 + stepCnt1 + stepCnt2
tower_of_hanoi... |
# Manas Dash
# 24th July 2020
# the usage of set and max function
# which number is repeated most number of time
numbers = [1, 3, 4, 6, 3, 7, 3, 8, 6, 5, 9, 5, 3, 6, 3, 2, 3]
max_repeated = max(set(numbers), key=numbers.count)
print(f"The number {max_repeated} is repeated maximum number of time in the given list")
... | numbers = [1, 3, 4, 6, 3, 7, 3, 8, 6, 5, 9, 5, 3, 6, 3, 2, 3]
max_repeated = max(set(numbers), key=numbers.count)
print(f'The number {max_repeated} is repeated maximum number of time in the given list') |
class ZileanBackuper(object):
def __init__(self):
self._machines = None
self._linked_databases = None
@classmethod
def backup_linked_databases(cls):
pass
@classmethod
def backup_database(cls, db):
pass
| class Zileanbackuper(object):
def __init__(self):
self._machines = None
self._linked_databases = None
@classmethod
def backup_linked_databases(cls):
pass
@classmethod
def backup_database(cls, db):
pass |
# Copyright 2020 The Private Cardinality Estimation Framework Authors
#
# 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 b... | """Set Generator Base Classes"""
class _Setsizegenerator(object):
"""Get set_size_list from set_size (fixed for each set) and num_sets."""
def __init__(self, num_sets, set_size):
self.num_sets = num_sets
self.set_size = set_size
def __iter__(self):
for _ in range(self.num_sets):
... |
def test_content_create(api_client_authenticated):
response = api_client_authenticated.post(
"/content/",
json={
"title": "hello test",
"text": "this is just a test",
"published": True,
"tags": ["test", "hello"],
},
)
assert response.st... | def test_content_create(api_client_authenticated):
response = api_client_authenticated.post('/content/', json={'title': 'hello test', 'text': 'this is just a test', 'published': True, 'tags': ['test', 'hello']})
assert response.status_code == 200
result = response.json()
assert result['slug'] == 'hello-... |
[
[0.26982777, 0.20175242, 0.10614473, 0.17290444, 0.22056401],
[0.18268971, 0.2363915, 0.26958793, 0.29282782, 0.36225248],
[0.31735855, 0.30254544, 0.28661105, 0.33136132, 0.40489719],
[0.0, 0.0, 0.0, 0.0, 0.0],
[0.15203597, 0.32214688, 0.40445594, 0.45318467, 0.44650059],
[0.20070068, 0.31904... | [[0.26982777, 0.20175242, 0.10614473, 0.17290444, 0.22056401], [0.18268971, 0.2363915, 0.26958793, 0.29282782, 0.36225248], [0.31735855, 0.30254544, 0.28661105, 0.33136132, 0.40489719], [0.0, 0.0, 0.0, 0.0, 0.0], [0.15203597, 0.32214688, 0.40445594, 0.45318467, 0.44650059], [0.20070068, 0.31904263, 0.40822282, 0.487387... |
t=int(input())
for k in range(t):
n=int(input())
a=list(map(int,input().strip().split()))
stack=[]
res={}
for i in a:
res[i]=-1
for j in a:
if len(stack)==0:
stack.append(j)
else:
while len(stack)>0 and stack[-1]<j:
res[stack.pop()]... | t = int(input())
for k in range(t):
n = int(input())
a = list(map(int, input().strip().split()))
stack = []
res = {}
for i in a:
res[i] = -1
for j in a:
if len(stack) == 0:
stack.append(j)
else:
while len(stack) > 0 and stack[-1] < j:
... |
print(int('3') + 3)
print(float('3.2') + 3.5)
print(str(3) + '2')
| print(int('3') + 3)
print(float('3.2') + 3.5)
print(str(3) + '2') |
# Copyright 2019 Eficent Business and IT Consulting Services
# Copyright 2017-2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Stock Picking Return Invoicing",
"summary": "Add an option to refund returned pickings",
"version": "12.0.1.0.1",... | {'name': 'Purchase Stock Picking Return Invoicing', 'summary': 'Add an option to refund returned pickings', 'version': '12.0.1.0.1', 'category': 'Purchases', 'website': 'https://github.com/OCA/account-invoicing', 'author': 'Eficent,Tecnativa,Odoo Community Association (OCA)', 'license': 'AGPL-3', 'installable': True, '... |
def get_regr_coeffs(X, y):
n = X.shape[0]
p = n*(X**2).sum() - X.sum()**2
a = ( n*(X*y).sum() - X.sum()*y.sum() ) / p
b = ( y.sum()*(X**2).sum() - X.sum()*(X*y).sum() ) / p
return a,b
| def get_regr_coeffs(X, y):
n = X.shape[0]
p = n * (X ** 2).sum() - X.sum() ** 2
a = (n * (X * y).sum() - X.sum() * y.sum()) / p
b = (y.sum() * (X ** 2).sum() - X.sum() * (X * y).sum()) / p
return (a, b) |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if root is None:
return 0
layer = [root]
res = 0
whil... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sum_of_left_leaves(self, root: TreeNode) -> int:
if root is None:
return 0
layer = [root]
res = 0
while layer:
node = laye... |
# Binary Search Tree (BST) Implementation
class BSTNode:
def __init__(selfNode, nodeData): # Node Structure
selfNode.nodeData = nodeData
selfNode.left = None
selfNode.right = None
selfNode.parent = None
# Insertion Operation
def insert(selfNode, node):
if selfNode.nod... | class Bstnode:
def __init__(selfNode, nodeData):
selfNode.nodeData = nodeData
selfNode.left = None
selfNode.right = None
selfNode.parent = None
def insert(selfNode, node):
if selfNode.nodeData > node.nodeData:
if selfNode.left is None:
selfNo... |
class Stack:
def __init__(self,size=None,limit=1000):
self.top_item = []
self.size = 0
self.limit = limit
def peek(self):
if not self.is_empty():
return self.value[-1]
else:
print("Stack is empty")
def push(self,value):
#print("Current... | class Stack:
def __init__(self, size=None, limit=1000):
self.top_item = []
self.size = 0
self.limit = limit
def peek(self):
if not self.is_empty():
return self.value[-1]
else:
print('Stack is empty')
def push(self, value):
if self.ha... |
with open("part1.txt", "r") as file:
checksum = 0
for row in file:
large, small = 0, 9999
for entry in row.split("\t"):
entry = int(entry)
if entry > large:
large = entry
if entry < small:
small = entry
checksum += larg... | with open('part1.txt', 'r') as file:
checksum = 0
for row in file:
(large, small) = (0, 9999)
for entry in row.split('\t'):
entry = int(entry)
if entry > large:
large = entry
if entry < small:
small = entry
checksum += l... |
# BUILD FILE SYNTAX: SKYLARK
SE_VERSION = '3.141.59-atlassian-1'
| se_version = '3.141.59-atlassian-1' |
# Python translation of QuadTree from Risk.Platform.Standard
class QuadTree(object): # in decimal degrees dist from centroid to edge
def __init__(self, latDim, longDim, minLatCentroid, minLongCentroid, baseSize):
self.__longDim = longDim
self.__latDim = latDim
self.__minLong = minLongCent... | class Quadtree(object):
def __init__(self, latDim, longDim, minLatCentroid, minLongCentroid, baseSize):
self.__longDim = longDim
self.__latDim = latDim
self.__minLong = minLongCentroid
self.__baseSize = baseSize
self.__minLat = minLatCentroid
self.__baseGrid = [[quad... |
class FtpStyleUriParser(UriParser):
"""
A customizable parser based on the File Transfer Protocol (FTP) scheme.
FtpStyleUriParser()
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return FtpStyleUriParser()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
| class Ftpstyleuriparser(UriParser):
"""
A customizable parser based on the File Transfer Protocol (FTP) scheme.
FtpStyleUriParser()
"""
def zzz(self):
"""hardcoded/mock instance of the class"""
return ftp_style_uri_parser()
instance = zzz()
'hardcoded/returns an instance of the c... |
""" Tuple"""
names = ("rogers","Joan", "Doreen", "Liz", "Peter" )
print(names)
string_tuple = " ".join(str(name) for name in names)
print(string_tuple) | """ Tuple"""
names = ('rogers', 'Joan', 'Doreen', 'Liz', 'Peter')
print(names)
string_tuple = ' '.join((str(name) for name in names))
print(string_tuple) |
def length(t1, n):
t2=t1*n
l=len(t2)
print("Tuple {} has length: {}", t2, l)
length(('1',(5,3)),2)
#Tuple {} length: ('1',(5,3)'1',(5,3)) 4
#note: here .format is missing
def length(t1, n):
t2=t1*n
l=len(t2)
print("Tuple {} has length: {}". format(t2, l))
length(('1',(5,3)),2)
... | def length(t1, n):
t2 = t1 * n
l = len(t2)
print('Tuple {} has length: {}', t2, l)
length(('1', (5, 3)), 2)
def length(t1, n):
t2 = t1 * n
l = len(t2)
print('Tuple {} has length: {}'.format(t2, l))
length(('1', (5, 3)), 2) |
def repeat(character: str, counter: int) -> str:
"""Repeat returns character repeated `counter` times."""
word = ""
for counter in range(counter):
word += character
return word
| def repeat(character: str, counter: int) -> str:
"""Repeat returns character repeated `counter` times."""
word = ''
for counter in range(counter):
word += character
return word |
__author__ = 'Igor Davydenko <playpauseandstop@gmail.com>'
__description__ = 'Flask-Dropbox test project'
__license__ = 'BSD License'
__version__ = '0.3'
| __author__ = 'Igor Davydenko <playpauseandstop@gmail.com>'
__description__ = 'Flask-Dropbox test project'
__license__ = 'BSD License'
__version__ = '0.3' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.