content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
boxes = """cvfueihajytpmrdkgsxfqplbxn
cbzueihajytnmrdkgtxfqplbwn
cvzucihajytomrdkgstfqplqwn
cvzueilajytomrdkgsxfqwnbwn
cvzueihajytomrdkgsgwqphbwn
wuzuerhajytomrdkgsxfqplbwn
cyzueifajybomrdkgsxfqplbwn
cvzueihajxtomrdkgpxfqplmwn
ivzfevhajytomrdkgsxfqplbwn
cvzueihajytomrdlgsxfqphbbn
uvzueihajjtomrdkgsxfqpobwn
cvzupihajyto... | boxes = 'cvfueihajytpmrdkgsxfqplbxn\ncbzueihajytnmrdkgtxfqplbwn\ncvzucihajytomrdkgstfqplqwn\ncvzueilajytomrdkgsxfqwnbwn\ncvzueihajytomrdkgsgwqphbwn\nwuzuerhajytomrdkgsxfqplbwn\ncyzueifajybomrdkgsxfqplbwn\ncvzueihajxtomrdkgpxfqplmwn\nivzfevhajytomrdkgsxfqplbwn\ncvzueihajytomrdlgsxfqphbbn\nuvzueihajjtomrdkgsxfqpobwn\ncvz... |
# T Y P E O F V E R B S
def pert_subjective_verbs(texts_tokens):
total_verbs = 0
total_subj_verbs = 0
return
def pert_report_verbs(text_tokens):
return
def pert_factive_verbs(text_tokens):
return
def pert_imperative_commands(text_tokens):
return | def pert_subjective_verbs(texts_tokens):
total_verbs = 0
total_subj_verbs = 0
return
def pert_report_verbs(text_tokens):
return
def pert_factive_verbs(text_tokens):
return
def pert_imperative_commands(text_tokens):
return |
"""
AnalysisPipeline operators
"""
class AnalysisOperation:
"""
An analysis task performed by an AnalysisPipeline.
This is an internal class that facilitates keeping track of a
function, arguments, and keyword arguments that together represent a
single operation in a pipeline.
Parameters
... | """
AnalysisPipeline operators
"""
class Analysisoperation:
"""
An analysis task performed by an AnalysisPipeline.
This is an internal class that facilitates keeping track of a
function, arguments, and keyword arguments that together represent a
single operation in a pipeline.
Parameters
... |
load("@rules_python//python:defs.bzl", "py_test")
pycoverage_requirements = [
"//tools/pycoverage",
]
def pycoverage(name, deps):
if not name or not deps:
fail("Arguments 'name' and 'deps' are required")
py_test(
name = name,
main = "pycoverage_runner.py",
srcs = ["//tools... | load('@rules_python//python:defs.bzl', 'py_test')
pycoverage_requirements = ['//tools/pycoverage']
def pycoverage(name, deps):
if not name or not deps:
fail("Arguments 'name' and 'deps' are required")
py_test(name=name, main='pycoverage_runner.py', srcs=['//tools/pycoverage:pycoverage_runner'], imports... |
filename = "test2.txt"
tree = [None]*16
with open(filename) as f:
line = f.readline().strip().strip('[]')
for c in line:
if c == ',':
continue
for line in f:
n = line.strip().strip('[]')
print(n) | filename = 'test2.txt'
tree = [None] * 16
with open(filename) as f:
line = f.readline().strip().strip('[]')
for c in line:
if c == ',':
continue
for line in f:
n = line.strip().strip('[]')
print(n) |
class Solution:
def searchMatrix(self, matrix, target):
i, j, r = 0, len(matrix[0]) - 1, len(matrix)
while i < r and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
j -= 1
elif matrix[i][j] < target:
... | class Solution:
def search_matrix(self, matrix, target):
(i, j, r) = (0, len(matrix[0]) - 1, len(matrix))
while i < r and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
j -= 1
elif matrix[i][j] < target:... |
def setUpModule() -> None:
print("[Module sserender Test Start]")
def tearDownModule() -> None:
print("[Module sserender Test End]") | def set_up_module() -> None:
print('[Module sserender Test Start]')
def tear_down_module() -> None:
print('[Module sserender Test End]') |
print('begin program')
# This program says hello and asks for my name.
print('Hello, World!')
print('What is your name?')
myName = input()
print('It is good to meet you, ' + myName)
print('end program')
| print('begin program')
print('Hello, World!')
print('What is your name?')
my_name = input()
print('It is good to meet you, ' + myName)
print('end program') |
""" Mehmet Said Turken 180401030"""
dosya = open("veriler.txt.txt", "r")
veri = []
for i in dosya.read().split():
veri.append(int(i))
n = len(veri)
yitoplam = sum(veri)
def x_degerleri(list, n):
valuex = []
for i in range(13):
x = 0
for k in range(n):
... | """ Mehmet Said Turken 180401030"""
dosya = open('veriler.txt.txt', 'r')
veri = []
for i in dosya.read().split():
veri.append(int(i))
n = len(veri)
yitoplam = sum(veri)
def x_degerleri(list, n):
valuex = []
for i in range(13):
x = 0
for k in range(n):
x += (k + 1) ** i
... |
#!/usr/bin/env python
'''
primes.py
@author: Lorenzo Cipriani <lorenzo1974@gmail.com>
@contact: https://www.linkedin.com/in/lorenzocipriani
@since: 2017-10-23
@see:
'''
primesToFind = 1000000
num = 0
found = 0
def isPrime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0: return Fa... | """
primes.py
@author: Lorenzo Cipriani <lorenzo1974@gmail.com>
@contact: https://www.linkedin.com/in/lorenzocipriani
@since: 2017-10-23
@see:
"""
primes_to_find = 1000000
num = 0
found = 0
def is_prime(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
return False
... |
class ExportingTemplate():
def __init__(self, exporting_template_name=None, channel=None, target_sample_rate=None, duration=None, created_date=None, modified_date=None, id=None):
self.exporting_template_name = exporting_template_name
self.channel = channel
self.target_sample_rate = target_sa... | class Exportingtemplate:
def __init__(self, exporting_template_name=None, channel=None, target_sample_rate=None, duration=None, created_date=None, modified_date=None, id=None):
self.exporting_template_name = exporting_template_name
self.channel = channel
self.target_sample_rate = target_sam... |
# -*- coding: utf-8 -*-
"""
indico_payment_stripe
~~~~~~~~~~~~~~~~~~~~~
Indico plugin for Stripe payment support.
:license: MIT
"""
RELEASE = False
__version_info__ = ('0', '0', '1')
__version__ = '.'.join(__version_info__)
__version__ += '-dev' if not RELEASE else ''
__author__ = 'NeIC'
__homepa... | """
indico_payment_stripe
~~~~~~~~~~~~~~~~~~~~~
Indico plugin for Stripe payment support.
:license: MIT
"""
release = False
__version_info__ = ('0', '0', '1')
__version__ = '.'.join(__version_info__)
__version__ += '-dev' if not RELEASE else ''
__author__ = 'NeIC'
__homepage__ = 'https://github.com/n... |
# Based on container/push.bzl from rules_docker
# Also based on pkg/pkg.bzl from bazel_tools
# Copyright 2015, 2017 The Bazel Authors. All rights reserved.
#
# 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 t... | load('@io_bazel_rules_docker//container:layer_tools.bzl', _get_layers='get_from_target')
def _quote(filename, protect='='):
"""Quote the filename, by escaping = by \\= and \\ by \\"""
return filename.replace('\\', '\\\\').replace(protect, '\\' + protect)
def _impl(ctx):
image = _get_layers(ctx, ctx.label.... |
# Given an array of strings strs, group the anagrams together. You can return the answer in any order.
# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
# Example 1:
# Input: strs = ["eat","tea","tan","ate","nat... | class Solution:
def group_anagrams(self, strs):
result = []
lst = []
for i in strs:
a = sorted(i)
if a in lst:
x = lst.index(a)
result[x].append(i)
else:
lst.append(a)
result.append([i])
... |
instructions = []
for line in open('input.txt', 'r').readlines():
readline = line.strip()
instructions.append((readline[0], int(readline[1:])))
directions = {
'E': [1, 0],
'S': [0, -1],
'W': [-1, 0],
'N': [0, 1],
}
direction = 'E'
x, y = 0, 0
for action, value in instructions:
if action in [*directions]:
x ... | instructions = []
for line in open('input.txt', 'r').readlines():
readline = line.strip()
instructions.append((readline[0], int(readline[1:])))
directions = {'E': [1, 0], 'S': [0, -1], 'W': [-1, 0], 'N': [0, 1]}
direction = 'E'
(x, y) = (0, 0)
for (action, value) in instructions:
if action in [*directions]:... |
a = [ 1, 2, 3, 4, 5 ]
print(a)
print(a[0])
for i in range(len(a)):
print(a[i])
a.append(10)
a.append(20)
print(a) | a = [1, 2, 3, 4, 5]
print(a)
print(a[0])
for i in range(len(a)):
print(a[i])
a.append(10)
a.append(20)
print(a) |
def buble_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
nums[i], nums[i - 1] = nums[i - 1], nums[i]
def check_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
return False
return True
def main():
count_nums = int(input()... | def buble_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
(nums[i], nums[i - 1]) = (nums[i - 1], nums[i])
def check_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
return False
return True
def main():
count_nums = int(inpu... |
def temperature_statistics(t):
mean = sum(t)/len(t)
return mean, (sum((val-mean)**2 for val in t)/len(t))**0.5
print(temperature_statistics([4.4, 4.2, 7.0, 12.9, 18.5, 23.5, 26.4, 26.3, 22.5, 16.6, 11.2, 7.3])) | def temperature_statistics(t):
mean = sum(t) / len(t)
return (mean, (sum(((val - mean) ** 2 for val in t)) / len(t)) ** 0.5)
print(temperature_statistics([4.4, 4.2, 7.0, 12.9, 18.5, 23.5, 26.4, 26.3, 22.5, 16.6, 11.2, 7.3])) |
"""Top-level package for diffcalc-core."""
__author__ = """Diamond Light Source Ltd. - Scientific Software"""
__email__ = "scientificsoftware@diamond.ac.uk"
__version__ = "0.3.0"
| """Top-level package for diffcalc-core."""
__author__ = 'Diamond Light Source Ltd. - Scientific Software'
__email__ = 'scientificsoftware@diamond.ac.uk'
__version__ = '0.3.0' |
# Helper function to print out relation between losses and network parameters
# loss_list given as: [(name, loss_variable), ...]
# named_parameters_list using pytorch function named_parameters(): [(name, network.named_parameters()), ...]
def print_loss_params_relation(loss_list, named_parameters_list):
loss_variabl... | def print_loss_params_relation(loss_list, named_parameters_list):
loss_variables = {}
for (name, loss) in loss_list:
if loss.grad_fn is None:
variables_ = []
else:
def recursive_sub(loss):
r = []
if hasattr(loss, 'next_functions'):
... |
# %% [287. Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for i, v in enumerate(nums, 1):
if v in nums[i:]:
return v
| class Solution:
def find_duplicate(self, nums: List[int]) -> int:
for (i, v) in enumerate(nums, 1):
if v in nums[i:]:
return v |
def staircase(n):
asteriscos = 1
# Write your code here
for espacios in range(n, 0, -1):
for i in range (espacios):
print(' ', end='')
for j in range(asteriscos):
print('*', end='')
print()
asteriscos+=2
staircase(7)
| def staircase(n):
asteriscos = 1
for espacios in range(n, 0, -1):
for i in range(espacios):
print(' ', end='')
for j in range(asteriscos):
print('*', end='')
print()
asteriscos += 2
staircase(7) |
#!/usr/bin/env python
class Host(object):
def __init__(self, name, groups,region, image, tags, size, meta=None):
self.name = name
self.groups = groups
self.meta = meta or {}
self.region = region
self.image = image
self.tags = tags
self.size = size
swifty_ho... | class Host(object):
def __init__(self, name, groups, region, image, tags, size, meta=None):
self.name = name
self.groups = groups
self.meta = meta or {}
self.region = region
self.image = image
self.tags = tags
self.size = size
swifty_hosts = [host(name='swift... |
'''
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: 1
'''
#Approach 1: Priority Queues
'''
Algorithm
A... | """
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: 1
"""
"\nAlgorithm\n\nA) Sort the given meetings by t... |
#!/usr/bin/env python3.5
#-*- coding: utf-8 -*-
def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
main()
| def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
main() |
# -*- coding: UTF-8 -*-
#
# You are given an n x n 2D matrix representing an image.
#
# Rotate the image by 90 degrees (clockwise).
#
# Note:
# You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
#
# Example 1:
#
# Gi... | class Rotateimage:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
length = len(matrix)
for i in range(length // 2):
j = length - 1 - i
cache = matrix[i]
... |
class Libro:
def __init__(self, paginas, tapa,nombre, autor, genero, isbn):
self.paginas = paginas
self.tapa = tapa
self.nombre= nombre
self.autor = autor
self.genero = genero
self.isbn = isbn
def set_nombre(self,nombre):
self.nombre = nombre
def set... | class Libro:
def __init__(self, paginas, tapa, nombre, autor, genero, isbn):
self.paginas = paginas
self.tapa = tapa
self.nombre = nombre
self.autor = autor
self.genero = genero
self.isbn = isbn
def set_nombre(self, nombre):
self.nombre = nombre
def... |
#
# @lc app=leetcode id=68 lang=python3
#
# [68] Text Justification
#
class Solution:
def split(self, words: List[str], maxWidth: int) -> List[List[str]]:
if not words:
return []
lines, cur_len = [[words[0]]], len(words[0])
for w in words[1:]:
if cur_len + 1 + len(w) ... | class Solution:
def split(self, words: List[str], maxWidth: int) -> List[List[str]]:
if not words:
return []
(lines, cur_len) = ([[words[0]]], len(words[0]))
for w in words[1:]:
if cur_len + 1 + len(w) <= maxWidth:
lines[-1].append(w)
... |
"""
Build microservices with Python
"""
__author__ = "Vlad Calin"
__email__ = "vlad.s.calin@gmail.com"
__version__ = "0.12.0"
| """
Build microservices with Python
"""
__author__ = 'Vlad Calin'
__email__ = 'vlad.s.calin@gmail.com'
__version__ = '0.12.0' |
#
# Copyright 2020- IBM Inc. All rights reserved
# SPDX-License-Identifier: Apache2.0
#
class K8sNamespace:
"""
Represents a K8s Namespace, storing its name and labels
"""
def __init__(self, name):
self.name = name
self.labels = {} # Storing the namespace labels in a dict as key-value ... | class K8Snamespace:
"""
Represents a K8s Namespace, storing its name and labels
"""
def __init__(self, name):
self.name = name
self.labels = {}
def __eq__(self, other):
if isinstance(other, K8sNamespace):
return self.name == other.name
return NotImplemen... |
class Solution(object):
def numEquivDominoPairs(self, dominoes):
"""
:type dominoes: List[List[int]]
:rtype: int
"""
hashmap = dict()
for a, b in dominoes:
key = tuple([min(a, b), max(a, b)])
hashmap[key] = hashmap.setdefault(key, 0) + 1
... | class Solution(object):
def num_equiv_domino_pairs(self, dominoes):
"""
:type dominoes: List[List[int]]
:rtype: int
"""
hashmap = dict()
for (a, b) in dominoes:
key = tuple([min(a, b), max(a, b)])
hashmap[key] = hashmap.setdefault(key, 0) + 1
... |
def update_data(hyper_params):
return dict(
train=dict(
samples_per_gpu=hyper_params['batch_size'],
workers_per_gpu=hyper_params['workers_per_gpu'],
dataset=dict(
root_dir=hyper_params['dataset_root'],
cifar_type=hyper_params['dataset_name'... | def update_data(hyper_params):
return dict(train=dict(samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict(root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], noise_mode=hyper_params['noise_mode'], noise_ratio=hyper_params['noise_ratio... |
class Person:
def __init__(self, name, age=21, gender='unspecified',
occupation='unspecified'):
self.name = name
self.gender = gender
self.occupation = occupation
if age >= 0 and age <= 120:
self.age = age
else:
self.age = 21
def... | class Person:
def __init__(self, name, age=21, gender='unspecified', occupation='unspecified'):
self.name = name
self.gender = gender
self.occupation = occupation
if age >= 0 and age <= 120:
self.age = age
else:
self.age = 21
def greets(self, gre... |
"""
Test group missing the last item
.. pii: Group 2 - Annotation 1
.. pii_types: id, name
"""
| """
Test group missing the last item
.. pii: Group 2 - Annotation 1
.. pii_types: id, name
""" |
def obj_sort_by_lambda(obj_list, lmbd):
new_obj_list = obj_list.copy()
new_obj_list.sort(key=lmbd)
return new_obj_list
def obj_sort_by_property_name(obj_list, prop_name):
return obj_sort_by_lambda(obj_list, lambda x:getattr(x, prop_name))
def obj_list_decrypt(obj_list, enc):
new_obj_list = []
... | def obj_sort_by_lambda(obj_list, lmbd):
new_obj_list = obj_list.copy()
new_obj_list.sort(key=lmbd)
return new_obj_list
def obj_sort_by_property_name(obj_list, prop_name):
return obj_sort_by_lambda(obj_list, lambda x: getattr(x, prop_name))
def obj_list_decrypt(obj_list, enc):
new_obj_list = []
... |
# -*- coding: utf-8 -*-
"""Top-level package for appliapps."""
__author__ = """Lars Malmstroem"""
__email__ = 'lars@malmstroem.net'
__version__ = '0.1.0'
| """Top-level package for appliapps."""
__author__ = 'Lars Malmstroem'
__email__ = 'lars@malmstroem.net'
__version__ = '0.1.0' |
class InvalidUrl(Exception):
pass
class UnableToGetPage(Exception):
pass
class UnableToGetUploadTime(Exception):
pass
class UnableToGetApproximateNum(Exception):
pass
| class Invalidurl(Exception):
pass
class Unabletogetpage(Exception):
pass
class Unabletogetuploadtime(Exception):
pass
class Unabletogetapproximatenum(Exception):
pass |
# *******************************************************************************************
# *******************************************************************************************
#
# Name : error.py
# Purpose : Error class
# Date : 13th November 2021
# Author : Paul Robson (paul@robsons.org.uk)
#
# ***... | class Hplexception(Exception):
def __str__(self):
msg = Exception.__str__(self)
return msg if HPLException.LINE <= 0 else '{0} ({1}:{2})'.format(msg, HPLException.FILE, HPLException.LINE)
HPLException.FILE = None
HPLException.LINE = 0
if __name__ == '__main__':
x = hpl_exception('Error !!')
... |
# coding=utf-8
worker_thread_pool = None
key_loading_thread_pool = None
key_holder = None
is_debug = False
is_debug_requests = False
is_no_validate = False
is_only_validate_key = False
is_override = False
is_preview_filename = False
is_resize = False
thread_num = 1
src_dir = None
dest_dir = None
filename_pattern =... | worker_thread_pool = None
key_loading_thread_pool = None
key_holder = None
is_debug = False
is_debug_requests = False
is_no_validate = False
is_only_validate_key = False
is_override = False
is_preview_filename = False
is_resize = False
thread_num = 1
src_dir = None
dest_dir = None
filename_pattern = None
filename_repla... |
from_ = 1
to_ = 999901
# to_ = 1
output_file = open("result.txt", "w", encoding="utf-8")
for i in range(from_, to_ + 1, 100):
input_file = open("allTags/" + str(i) + ".txt", "r", encoding="utf-8")
data = input_file.read()
ind = 0
for j in range(100):
ind = data.find("class=\"i-tag\"", ind)
... | from_ = 1
to_ = 999901
output_file = open('result.txt', 'w', encoding='utf-8')
for i in range(from_, to_ + 1, 100):
input_file = open('allTags/' + str(i) + '.txt', 'r', encoding='utf-8')
data = input_file.read()
ind = 0
for j in range(100):
ind = data.find('class="i-tag"', ind)
data = da... |
#!/usr/bin/env python3
''' In this question , we are going to find the longest common substring, among two given substrings. in order to solve this question
we will be making use of dynamic programming. so we will create a matrix with all 0s in the initial row and column
Step 1: we need to initialise a matrix with siz... | """ In this question , we are going to find the longest common substring, among two given substrings. in order to solve this question
we will be making use of dynamic programming. so we will create a matrix with all 0s in the initial row and column
Step 1: we need to initialise a matrix with size len(String)+1, len(st... |
'''
Author : Govind Patidar
DateTime : 10/07/2020 11:30AM
File : AllPageLocators
'''
class AllPageLocators():
def __init__(self, driver):
'''
:param driver:
'''
self.driver = driver
'''Home page locator'''
# get XPATH current temperature text
text_curr_temp = '... | """
Author : Govind Patidar
DateTime : 10/07/2020 11:30AM
File : AllPageLocators
"""
class Allpagelocators:
def __init__(self, driver):
"""
:param driver:
"""
self.driver = driver
'Home page locator'
text_curr_temp = '/html/body/div/div[1]/h2'
curr_temp = 'tempera... |
word = input()
out = ''
prev = ''
# remove same letters which are the same as the previous
for x in word:
if x != prev:
out+=x
prev = x
print(out)
| word = input()
out = ''
prev = ''
for x in word:
if x != prev:
out += x
prev = x
print(out) |
#
# PySNMP MIB module TPLINK-IPADDR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-IPADDR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:17:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, single_value_constraint, constraints_union, value_size_constraint) ... |
""" Write a method/function DISPLAYWORDS() in python to read lines
from a text file STORY.TXT,
using read function
and display those words, which are less than 4 characters. """
F = open("story.txt", "r")
value = F.read()
lines = value.split()
count = 0
for i in lines:
if len(i) < 4:
print(i... | """ Write a method/function DISPLAYWORDS() in python to read lines
from a text file STORY.TXT,
using read function
and display those words, which are less than 4 characters. """
f = open('story.txt', 'r')
value = F.read()
lines = value.split()
count = 0
for i in lines:
if len(i) < 4:
print(i)
coun... |
#Programa que leia um nome completo e diga o primeiro e ultimo nome
nome = input('Digite seu nome completo: ').title()
splt = nome.split()
print(splt[0],splt[-1]) | nome = input('Digite seu nome completo: ').title()
splt = nome.split()
print(splt[0], splt[-1]) |
name = "chris alan"
name = name.title()
name = "1 w 2 r 3g"
# Complete the solve function below.
def solve(string):
"""
Capitalizing function
"""
list_strings = string.rstrip().split(" ")
result = ""
for item in list_strings:
if item[0].isalpha():
item = item.title()
... | name = 'chris alan'
name = name.title()
name = '1 w 2 r 3g'
def solve(string):
"""
Capitalizing function
"""
list_strings = string.rstrip().split(' ')
result = ''
for item in list_strings:
if item[0].isalpha():
item = item.title()
result += item + ' '
return resu... |
def binary_search(ary, tar):
head = 0
tail = len(ary) - 1
found = False
while head <= tail and not found:
mid = (head + tail) / 2
if ary[mid] == tar:
found = True
elif ary[mid] < tar:
head = mid + 1
elif ary[mid] > tar:
tail = mid - 1... | def binary_search(ary, tar):
head = 0
tail = len(ary) - 1
found = False
while head <= tail and (not found):
mid = (head + tail) / 2
if ary[mid] == tar:
found = True
elif ary[mid] < tar:
head = mid + 1
elif ary[mid] > tar:
tail = mid - 1... |
# example solution.
# You are not expected to make a nice plotting function,
# you can simply call plt.imshow a number of times and observe
print(faces.DESCR) # this shows there are 40 classes, 10 samples per class
print(faces.target) #the targets i.e. classes
print(np.unique(faces.target).shape) # another way to se... | print(faces.DESCR)
print(faces.target)
print(np.unique(faces.target).shape)
x = faces.images
y = faces.target
fig = plt.figure(figsize=(16, 5))
idxs = [0, 1, 2, 11, 12, 13, 40, 41]
for (i, k) in enumerate(idxs):
ax = fig.add_subplot(2, 4, i + 1)
ax.imshow(X[k])
ax.set_title(f'target={y[k]}') |
#python 3.5.2
def areAnagram(firstWord, secondWord):
firstList = list(firstWord)
secondList = list(secondWord)
result = True
if len(firstList) == len(secondList) and result:
#Sort both list alphabetically
firstList.sort()
secondList.sort()
i = 0
length =... | def are_anagram(firstWord, secondWord):
first_list = list(firstWord)
second_list = list(secondWord)
result = True
if len(firstList) == len(secondList) and result:
firstList.sort()
secondList.sort()
i = 0
length = len(firstList)
while i < length:
if fir... |
#!/bin/zsh
'''
Regex Search
Write a program that opens all .txt files in a folder and searches for any line
that matches a user-supplied regular expression. The results should be printed to the screen.
''' | """
Regex Search
Write a program that opens all .txt files in a folder and searches for any line
that matches a user-supplied regular expression. The results should be printed to the screen.
""" |
''' Q1. Write a python code for creating a password for E-Aadhar card. The details used are the
first 4 letters of your name, date and month of your birth. The task is to generate a password
with the lambda function and display it.'''
name = input("Input your name (as on your Aadhar)\n")
dob = input("Please enter you... | """ Q1. Write a python code for creating a password for E-Aadhar card. The details used are the
first 4 letters of your name, date and month of your birth. The task is to generate a password
with the lambda function and display it."""
name = input('Input your name (as on your Aadhar)\n')
dob = input("Please enter your ... |
# Follow up for N-Queens problem.
# Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution(object):
result = 0
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
cols = []
self.search(n, cols)
... | class Solution(object):
result = 0
def total_n_queens(self, n):
"""
:type n: int
:rtype: int
"""
cols = []
self.search(n, cols)
return self.result
def search(self, n, cols):
if len(cols) == n:
self.result += 1
return
... |
# !/usr/bin/env python
# coding: utf-8
'''
Description:
'''
| """
Description:
""" |
# -*- coding: utf-8 -*-
"""
PRTG Exceptions
"""
class PrtgException(Exception):
"""
Base PRTG Exception
"""
pass
class PrtgBadRequest(PrtgException):
"""
Bad request
"""
pass
class PrtgBadTarget(PrtgException):
"""
Invalid target
"""
pass
class PrtgUnknownRespons... | """
PRTG Exceptions
"""
class Prtgexception(Exception):
"""
Base PRTG Exception
"""
pass
class Prtgbadrequest(PrtgException):
"""
Bad request
"""
pass
class Prtgbadtarget(PrtgException):
"""
Invalid target
"""
pass
class Prtgunknownresponse(PrtgException):
"""
... |
def getSampleMetadata(catalogName, tagName, digest):
return {
'schemaVersion': 2,
'mediaType': 'application/vnd.docker.distribution.manifest.v2+json',
'config': {
'mediaType': 'application/vnd.docker.container.image.v1+json',
'size': 1111,
'digest': digest
},
'layers': [
{... | def get_sample_metadata(catalogName, tagName, digest):
return {'schemaVersion': 2, 'mediaType': 'application/vnd.docker.distribution.manifest.v2+json', 'config': {'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 1111, 'digest': digest}, 'layers': [{'mediaType': 'application/vnd.docker.image.ro... |
class Solution:
def count(self, s, target):
ans = 0
for i in s:
if i == target:
ans += 1
return ans
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0 for i in range(n+1)] for j in range(m+1)]
for s in strs:
zer... | class Solution:
def count(self, s, target):
ans = 0
for i in s:
if i == target:
ans += 1
return ans
def find_max_form(self, strs: List[str], m: int, n: int) -> int:
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
for s in strs:
... |
# remove nth node from end
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# brute
# create a new linked list without that element
# Time O(n)
# Space O(n)
# optimal
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.n... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode:
if head.next == None:
return None
start = list_node()
start.next = head
slow = f... |
def readFile(fileName):
try:
with open(fileName,'r') as f:
print (f.read())
except FileNotFoundError:
print (f'File {fileName} is not found')
readFile('1.txt')
readFile('2.txt')
readFile('3.txt')
| def read_file(fileName):
try:
with open(fileName, 'r') as f:
print(f.read())
except FileNotFoundError:
print(f'File {fileName} is not found')
read_file('1.txt')
read_file('2.txt')
read_file('3.txt') |
'''
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Examples:
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
Notes:
* The number can be negative already, in which case no change is required.
* Zero (0... | """
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Examples:
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
Notes:
* The number can be negative already, in which case no change is required.
* Zero (0... |
cards = {'SPADE' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'],
'HEART' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'],
'CLUB' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'],
'DIAMOND' : ['1', '2', '3', '4', '5', '6',... | cards = {'SPADE': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'HEART': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'CLUB': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'DIAMOND': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12... |
CR_ATTACHMENT_AVAILABLE = 'cr_available'
CR_ATTACHMENT_REQUEST = 'cr_request'
TRR_ATTACHMENT_AVAILABLE = 'trr_available'
TRR_ATTACHMENT_REQUEST = 'trr_request'
ATTACHMENT_TYPE_CHOICES = [
[CR_ATTACHMENT_AVAILABLE, 'CR attachment available'],
[CR_ATTACHMENT_REQUEST, 'CR attachment request'],
[TRR_ATTACHMENT_... | cr_attachment_available = 'cr_available'
cr_attachment_request = 'cr_request'
trr_attachment_available = 'trr_available'
trr_attachment_request = 'trr_request'
attachment_type_choices = [[CR_ATTACHMENT_AVAILABLE, 'CR attachment available'], [CR_ATTACHMENT_REQUEST, 'CR attachment request'], [TRR_ATTACHMENT_AVAILABLE, 'T... |
# Description: Sample Code to Run mypy
# Variables without types
i:int = 200
f:float = 2.34
str = "Hello"
# A function without type annotations
def greet(name:str)-> str:
return str + " " + name
if __name__ == '__main__':
greet("Dilbert")
| i: int = 200
f: float = 2.34
str = 'Hello'
def greet(name: str) -> str:
return str + ' ' + name
if __name__ == '__main__':
greet('Dilbert') |
class GameObject:
def __init__(self, *, x=0, y=0, size=None):
self.x = x
self.y = y
self.size = size
self.half_width = self.size[0] / 2.
def to_rect(self):
"""Return the gameobject to be display by qs.anim"""
return [[self.x, self.y], self.size]
def update(s... | class Gameobject:
def __init__(self, *, x=0, y=0, size=None):
self.x = x
self.y = y
self.size = size
self.half_width = self.size[0] / 2.0
def to_rect(self):
"""Return the gameobject to be display by qs.anim"""
return [[self.x, self.y], self.size]
def update... |
"""Top-level package for ZotUtil."""
__author__ = """Cheng Cui"""
__email__ = "cheng.cui.95@gmail.com"
__version__ = "0.1.1"
| """Top-level package for ZotUtil."""
__author__ = 'Cheng Cui'
__email__ = 'cheng.cui.95@gmail.com'
__version__ = '0.1.1' |
numbers = [1,45,31,12,60]
for number in numbers:
if number % 8 == 0:
# Reject the list
print("The numbers are unacceptable")
break
else:
print("List okay!") | numbers = [1, 45, 31, 12, 60]
for number in numbers:
if number % 8 == 0:
print('The numbers are unacceptable')
break
else:
print('List okay!') |
class WeatherResponse(object):
"""
Specifies the response to be sent for one weather object.
"""
def __init__(self, *args, **kwargs):
"""
Set values for object.
:param args:
:param kwargs:
"""
self.temp = kwargs.get("temp", None)
self.temp_units ... | class Weatherresponse(object):
"""
Specifies the response to be sent for one weather object.
"""
def __init__(self, *args, **kwargs):
"""
Set values for object.
:param args:
:param kwargs:
"""
self.temp = kwargs.get('temp', None)
self.temp_units ... |
file = "01.data.txt"
f = open(file)
data = f.read()
f.close()
lines = data.split("\n")
readings = []
for line in lines:
readings.append(int(line))
print(readings)
# count all the increases
# have a counter
counter = 0
# each time number icreases increment the counter
for i in range(1, len(readings)):
pr... | file = '01.data.txt'
f = open(file)
data = f.read()
f.close()
lines = data.split('\n')
readings = []
for line in lines:
readings.append(int(line))
print(readings)
counter = 0
for i in range(1, len(readings)):
previous = readings[i - 1]
current = readings[i]
is_greater = current > previous
if is_grea... |
class EmptyDiscretizeFunctionError(ValueError):
"""Raise in place of empty discretize function when loading dataset."""
def __init__(self):
message = self.message()
super(EmptyDiscretizeFunctionError, self).__init__(message)
@staticmethod
def message():
return "Please ... | class Emptydiscretizefunctionerror(ValueError):
"""Raise in place of empty discretize function when loading dataset."""
def __init__(self):
message = self.message()
super(EmptyDiscretizeFunctionError, self).__init__(message)
@staticmethod
def message():
return 'Please pass disc... |
"""
spam
~~~~
Toy functions for testing.
"""
def spam_eggs():
pass
def spam_bacon():
pass
def spam_baked_beans():
pass
| """
spam
~~~~
Toy functions for testing.
"""
def spam_eggs():
pass
def spam_bacon():
pass
def spam_baked_beans():
pass |
'''
Machine Learning
* Machine Learning is making the computer learn from studying data and statistics.
* Machine Learning is a step into the direction of artificial intelligence (AI).
* Machine Learning is a program that analyses data and learns to predict the outcome.
Where To Start?
* In this tutorial we will go... | """
Machine Learning
* Machine Learning is making the computer learn from studying data and statistics.
* Machine Learning is a step into the direction of artificial intelligence (AI).
* Machine Learning is a program that analyses data and learns to predict the outcome.
Where To Start?
* In this tutorial we will go... |
class Subscriber:
"""
Class that defines a subscriber to a specific event
"""
def __init__(self, callback_method, program, event_type, object_id):
self._callback_method = callback_method
self._program = program
self._event_type = event_type
self._object_id = object_id
... | class Subscriber:
"""
Class that defines a subscriber to a specific event
"""
def __init__(self, callback_method, program, event_type, object_id):
self._callback_method = callback_method
self._program = program
self._event_type = event_type
self._object_id = object_id
... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"expand_dim_to_3": "00_core.ipynb",
"parametric_ellipse": "00_core.ipynb",
"elliplise": "00_core.ipynb",
"EllipticalSeparabilityFilter": "00_core.ipynb"}
modules = ["core.py"]
doc... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'expand_dim_to_3': '00_core.ipynb', 'parametric_ellipse': '00_core.ipynb', 'elliplise': '00_core.ipynb', 'EllipticalSeparabilityFilter': '00_core.ipynb'}
modules = ['core.py']
doc_url = 'https://AtomScott.github.io/circle_finder/'
git_url = 'https:/... |
LOG = []
def flush_log(filename):
with open(filename, 'w') as logfile:
for l in LOG:
logfile.write("%s\n" % l)
def log_message(msg):
LOG.append(msg) | log = []
def flush_log(filename):
with open(filename, 'w') as logfile:
for l in LOG:
logfile.write('%s\n' % l)
def log_message(msg):
LOG.append(msg) |
is_correct = executor_result["is_correct"]
test_feedback = executor_result["test_feedback"]
test_comments = executor_result["test_comments"]
congrats = executor_result["congrats"]
feedback = ""
output = (test_comments + "\n" + test_feedback).strip()
if output == "":
output = "No issues!"
if is_correct:
feedb... | is_correct = executor_result['is_correct']
test_feedback = executor_result['test_feedback']
test_comments = executor_result['test_comments']
congrats = executor_result['congrats']
feedback = ''
output = (test_comments + '\n' + test_feedback).strip()
if output == '':
output = 'No issues!'
if is_correct:
feedback... |
"""
Given an array of integers nums and an integer threshold, we will choose
a positive integer divisor and divide all the array by it and sum the
result of the division. Find the smallest divisor such that the result
mentioned above is less than or equal to threshold.
Each result of division is... | """
Given an array of integers nums and an integer threshold, we will choose
a positive integer divisor and divide all the array by it and sum the
result of the division. Find the smallest divisor such that the result
mentioned above is less than or equal to threshold.
Each result of division is... |
"""
Manages the character's self regeneration.
--
Author : DrLarck
Last update : 18/07/19
"""
# charcter regen
class Character_regen:
"""
Manages the character's self regeneration.
- Attribute :
`health` : Represents the health regen per turn.
`ki` : Represents the ki regen per turn.
"""
... | """
Manages the character's self regeneration.
--
Author : DrLarck
Last update : 18/07/19
"""
class Character_Regen:
"""
Manages the character's self regeneration.
- Attribute :
`health` : Represents the health regen per turn.
`ki` : Represents the ki regen per turn.
"""
def __init__... |
## \file OutputFormat.py
# \author Dong Chen
# \brief Provides the function for writing outputs
## \brief Writes the output values to output.txt
# \param theta dependent variables (rad)
def write_output(theta):
outputfile = open("output.txt", "w")
print("theta = ", end="", file=outputfile)
print(theta, file... | def write_output(theta):
outputfile = open('output.txt', 'w')
print('theta = ', end='', file=outputfile)
print(theta, file=outputfile)
outputfile.close() |
# LevPy: A Python JSON level-loader
# for easier level abstraction
# in text-based py games
# Copyright (c) Finn Lancaster 2021
# Please Keep in mind that the JSONvar name must
# also be the same as the function that
# contains more data on it in LevPy.py
# Valid JSON, names can be anything, with data after the
# ... | jso_nvar = '{"":""}' |
class Solution:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
func = lambda x : sum(int(ch) ** 2 for ch in str(x))
seen = set()
while True:
if n == 1:
return True
if n in seen:
return False
... | class Solution:
def is_happy(self, n):
"""
:type n: int
:rtype: bool
"""
func = lambda x: sum((int(ch) ** 2 for ch in str(x)))
seen = set()
while True:
if n == 1:
return True
if n in seen:
return False
... |
# STACKS, QUEUES & HEAPS
# Stacks
'''
A stack is a last in first out (LIFO) data structure.
- Push an item onto the stack
- Pop an item out of the stack
All push and pop operations are to/from the top of the stack.
The only way to access the bottom items in the stack is to
first remove all items above it
Peek - g... | """
A stack is a last in first out (LIFO) data structure.
- Push an item onto the stack
- Pop an item out of the stack
All push and pop operations are to/from the top of the stack.
The only way to access the bottom items in the stack is to
first remove all items above it
Peek - getting an item on top of the stack... |
SETTINGS = {
'app': {
'schema': 'http://',
'host': 'localhost',
'port': 9000
}
}
| settings = {'app': {'schema': 'http://', 'host': 'localhost', 'port': 9000}} |
__name__ = "python-crud"
__version__ = "0.1.3"
__author__ = "Derek Merck"
__author_email__ = "derek.merck@ufl.edu"
__desc__ = "CRUD endpoint API with Python",
__url__ = "https://github.com/derekmerck/pycrud",
| __name__ = 'python-crud'
__version__ = '0.1.3'
__author__ = 'Derek Merck'
__author_email__ = 'derek.merck@ufl.edu'
__desc__ = ('CRUD endpoint API with Python',)
__url__ = ('https://github.com/derekmerck/pycrud',) |
"""
.. module:: build_features.py
:synopsis:
"""
| """
.. module:: build_features.py
:synopsis:
""" |
#!/usr/bin/env python
__author__ = "Kishori M Konwar"
__copyright__ = "Copyright 2013, MetaPathways"
__credits__ = ["r"]
__version__ = "1.0"
__maintainer__ = "Kishori M Konwar"
__status__ = "Release"
exit_code=0
| __author__ = 'Kishori M Konwar'
__copyright__ = 'Copyright 2013, MetaPathways'
__credits__ = ['r']
__version__ = '1.0'
__maintainer__ = 'Kishori M Konwar'
__status__ = 'Release'
exit_code = 0 |
edges = {
(1,'q'):1
}
accepting = [1]
def fsmsim(string, current, edges, accepting):
if string == "":
return current in accepting
else:
letter = string[0]
if (current, letter) in edges:
destination = edges[(current, letter)]
remaining_string = string[1:]
... | edges = {(1, 'q'): 1}
accepting = [1]
def fsmsim(string, current, edges, accepting):
if string == '':
return current in accepting
else:
letter = string[0]
if (current, letter) in edges:
destination = edges[current, letter]
remaining_string = string[1:]
... |
class Solution(object):
def flipAndInvertImage(self, A):
for row in A:
for i in xrange((len(row) + 1) / 2):
# ~ operator (not operator) x*-1-1 <- gets the element on the oposite side
row[i], row[~i] = ~row[~i] ^ 1, row[i] ^ 1
return A
| class Solution(object):
def flip_and_invert_image(self, A):
for row in A:
for i in xrange((len(row) + 1) / 2):
(row[i], row[~i]) = (~row[~i] ^ 1, row[i] ^ 1)
return A |
class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = str(first + '.' + last + '@company.com').lower() # see that we don't need to input all the
# attributes. Some of th... | class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = str(first + '.' + last + '@company.com').lower()
Employee.num_of_emps += 1
def fullname(self):
return '... |
numbers_of_electrons = int(input())
electrons = []
cell_number = 1
while numbers_of_electrons > 0:
possible_electrons = 2*cell_number**2
if possible_electrons > numbers_of_electrons:
electrons.append(numbers_of_electrons)
break
electrons.append(possible_electrons)
numbers_of_electrons -... | numbers_of_electrons = int(input())
electrons = []
cell_number = 1
while numbers_of_electrons > 0:
possible_electrons = 2 * cell_number ** 2
if possible_electrons > numbers_of_electrons:
electrons.append(numbers_of_electrons)
break
electrons.append(possible_electrons)
numbers_of_electron... |
# Jerry Landeros
def userInput():
number = int(input("Please enter a number: "))
return number
def primeChecker(number):
if number > 1:
for i in range(2, number):
if (number % i) == 0:
print(number, "is not a prime number.")
break
else:
... | def user_input():
number = int(input('Please enter a number: '))
return number
def prime_checker(number):
if number > 1:
for i in range(2, number):
if number % i == 0:
print(number, 'is not a prime number.')
break
else:
print(number, '... |
def print_welcome():
return """
<h1>Hello world!</h1>
<p>
<h3>This API is intended for FoodExplorer application.</h2>
"""
def print_man():
return """
<h3>api/v1/food</h3>
<p>POST method</p>
<p>form data berisi image</p>
<h3>api/v1/food?q={query}</h3>
<p>GET method</p>
<p>sear... | def print_welcome():
return '\n<h1>Hello world!</h1>\n<p>\n<h3>This API is intended for FoodExplorer application.</h2>\n\n'
def print_man():
return '\n <h3>api/v1/food</h3>\n <p>POST method</p>\n <p>form data berisi image</p>\n\n <h3>api/v1/food?q={query}</h3>\n <p>GET method</p>\n <p... |
"""Solution to 2.7: Intersection."""
def intersect(list_one, list_two):
length_one = len(list_one)
length_two = len(list_two)
diff = abs(length_one - length_two)
head_one = list_one.head
head_two = list_two.head
while range(max(length_one, length_two)):
if diff > 0:
di... | """Solution to 2.7: Intersection."""
def intersect(list_one, list_two):
length_one = len(list_one)
length_two = len(list_two)
diff = abs(length_one - length_two)
head_one = list_one.head
head_two = list_two.head
while range(max(length_one, length_two)):
if diff > 0:
diff -= ... |
_base_ = [
'../_base_/models/deeplabv3_unet_s5-d16.py',
'./dataset.py', '../_base_/default_runtime.py',
'./schedule_20k.py'
]
model = dict(
decode_head=dict(
num_classes=2,loss_decode=dict(
_delete_=True, type='LovaszLoss', loss_weight=1.0, per_image=True)
# type='CrossEn... | _base_ = ['../_base_/models/deeplabv3_unet_s5-d16.py', './dataset.py', '../_base_/default_runtime.py', './schedule_20k.py']
model = dict(decode_head=dict(num_classes=2, loss_decode=dict(_delete_=True, type='LovaszLoss', loss_weight=1.0, per_image=True)), auxiliary_head=dict(num_classes=2, loss_decode=dict(_delete_=True... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n ) :
if ( n == 1 ) :
return True
i = 1
for i in range ( 1 , n ) :
if arr [ i - 1... | def f_gold(arr, n):
if n == 1:
return True
i = 1
for i in range(1, n):
if arr[i - 1] < arr[i]:
if i == n:
return True
j = i
while arr[j] < arr[j - 1]:
if i > 1 and arr[j] < arr[i - 2]:
return False
j += 1
if j == n:
... |
# Maria O Sullivan
# Project Euler 5
# https://projecteuler.net/problem=5
i = 20
while 1:
i+=20
#i remainder 11 equals 0
if i%11==0 and i%12==0 and i%13==0 and i%14==0 and i%15==0\
and i%15==0 and i%16==0 and i%17==0 and i%18==0 and i%19==0:
print(i)
break
... | i = 20
while 1:
i += 20
if i % 11 == 0 and i % 12 == 0 and (i % 13 == 0) and (i % 14 == 0) and (i % 15 == 0) and (i % 15 == 0) and (i % 16 == 0) and (i % 17 == 0) and (i % 18 == 0) and (i % 19 == 0):
print(i)
break |
#
# Problem: Create a function that takes a message as a list of characters and reverses the order of the words
# in-place.
#
# For example:
# message = [ 'c', 'a', 'k', 'e', ' ',
# 'p', 'o', 'u', 'n', 'd', ' ',
# 's', 't', 'e', 'a', 'l' ]
#
# reverse_words(message)
#
# print ''.join(messa... | def reverse_characters(chars, start_index, end_index):
while start_index < end_index:
(chars[start_index], chars[end_index]) = (chars[end_index], chars[start_index])
start_index += 1
end_index -= 1
def reverse_words(chars):
"""
Solution: Reverse each character to get the words in the r... |
"""
Copyright 2018 Akshit Grover
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 ... | """
Copyright 2018 Akshit Grover
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 ... |
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __repr__(self):
return str(self.data)
def insert(self, data):
"""
- If value is less then root node, find empty leaf and insert into le... | class Treenode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __repr__(self):
return str(self.data)
def insert(self, data):
"""
- If value is less then root node, find empty leaf and insert into le... |
HTML_CODE_OPEN = "<code>"
HTML_CODE_CLOSE = "</code>"
HTML_NEW_LINE = "\n"
ETH_NULL_ADDRESS = '0x0000000000000000000000000000000000000000'
ETH_WETH_ADDRESS = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
| html_code_open = '<code>'
html_code_close = '</code>'
html_new_line = '\n'
eth_null_address = '0x0000000000000000000000000000000000000000'
eth_weth_address = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' |
question_data = [
{"category": "Science & Nature", "type": "boolean", "difficulty": "medium",
"question": "The Neanderthals were a direct ancestor of modern humans.",
"correct_answer": "False", "incorrect_answers": ["True"]},
{"category": "Science & Nature", "type": "boolean", "difficulty": "medium",
... | question_data = [{'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'The Neanderthals were a direct ancestor of modern humans.', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'The Do... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.