content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
__version__ = "2.11.2"
version = __version__
| __version__ = '2.11.2'
version = __version__ |
def method1(X, Y):
m = len(X)
n = len(Y)
L = [[None] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
els... | def method1(X, Y):
m = len(X)
n = len(Y)
l = [[None] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
... |
def combination(n, r):
r = min(n - r, r)
result = 1
for i in range(n, n - r, -1):
result *= i
for i in range(1, r + 1):
result //= i
return result
N, A, B = map(int, input().split())
v_list = list(map(int, input().split()))
v_list.sort(reverse=True)
mean_max = sum(v_list[:A]) / A
... | def combination(n, r):
r = min(n - r, r)
result = 1
for i in range(n, n - r, -1):
result *= i
for i in range(1, r + 1):
result //= i
return result
(n, a, b) = map(int, input().split())
v_list = list(map(int, input().split()))
v_list.sort(reverse=True)
mean_max = sum(v_list[:A]) / A
c... |
variable1 = input('Variable 1:')
variable2 = input('Variable 2:')
variable1, variable2 = variable2, variable1
print(f"Variable 1: {variable1}")
print(f"Variable 2: {variable2}") | variable1 = input('Variable 1:')
variable2 = input('Variable 2:')
(variable1, variable2) = (variable2, variable1)
print(f'Variable 1: {variable1}')
print(f'Variable 2: {variable2}') |
# Copyright 2014 Google Inc. 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 the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | {'targets': [{'target_name': 'ctmalloc_lib', 'type': 'static_library', 'sources': ['wtf/AsanHooks.cpp', 'wtf/AsanHooks.h', 'wtf/Assertions.h', 'wtf/Atomics.h', 'wtf/BitwiseOperations.h', 'wtf/ByteSwap.h', 'wtf/Compiler.h', 'wtf/config.h', 'wtf/CPU.h', 'wtf/malloc.cpp', 'wtf/PageAllocator.cpp', 'wtf/PageAllocator.h', 'w... |
def main():
# Manage input file
input = open(r"C:\Users\lawht\Desktop\Github\ROSALIND\Bioinformatics Stronghold\Complementing a Stand of DNA\Complementing a Stand of DNA\rosalind_revc.txt","r")
DNA_string = input.readline(); # take first line of input file for counting
# Take in input file of DNA stri... | def main():
input = open('C:\\Users\\lawht\\Desktop\\Github\\ROSALIND\\Bioinformatics Stronghold\\Complementing a Stand of DNA\\Complementing a Stand of DNA\\rosalind_revc.txt', 'r')
dna_string = input.readline()
print(reverse_complement(DNA_string))
input.close()
def reverse_complement(s):
sc = ''... |
"""
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# ... | """
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
2
/
3
return [3,2,1].
"""
class Solution(object):
def postorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def part_1(program):
i = 0
while i < len(program):
opcode, a, b, dest = program[i:i+4]
i += 4
assert opcode in {1, 2, 99}, f'Unexpected opcode: {opcode}'
if opcode == 1:
val = program[a] + program[b]
elif opcod... | def part_1(program):
i = 0
while i < len(program):
(opcode, a, b, dest) = program[i:i + 4]
i += 4
assert opcode in {1, 2, 99}, f'Unexpected opcode: {opcode}'
if opcode == 1:
val = program[a] + program[b]
elif opcode == 2:
val = program[a] * program... |
# Copyright 2021 Duan-JM, Sun Aries
# 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 writi... | opencv_shared_libs = False
opencv_tag = '4.5.0'
opencv_so_version = '4.5'
opencv_modules = ['calib3d', 'features2d', 'flann', 'highgui', 'video', 'videoio', 'imgcodecs', 'imgproc', 'core']
opencv_third_party_deps = ['liblibjpeg-turbo.a', 'liblibpng.a', 'liblibprotobuf.a', 'libquirc.a', 'libtegra_hal.a', 'libzlib.a', 'l... |
# Copyright (C) 2007-2012 Red Hat
# see file 'COPYING' for use and warranty information
#
# policygentool is a tool for the initial generation of SELinux policy
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the ... | te_types = '\ntype TEMPLATETYPE_rw_t;\nfiles_type(TEMPLATETYPE_rw_t)\n'
te_rules = '\nmanage_dirs_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\nmanage_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\nmanage_lnk_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\n'
i... |
"""
Compartmentalize:
[ ascii art input ]
---------------
| maybe some |
| sort of auxillary |
| drawing program |
|
|
\ /
v
[ lex/parser ] --> [ translater ]
--------- ----------
| grammar | | notes literals|
| to numerical |
... | """
Compartmentalize:
[ ascii art input ]
---------------
| maybe some |
| sort of auxillary |
| drawing program |
|
|
\\ /
v
[ lex/parser ] --> [ translater ]
--------- ----------
| grammar | | notes literals|
| to numerical |
... |
if __name__ == "__main__":
"""
Pobierz podstawe i wysokosc trojkata i wypisz pole.
"""
print("podaj podstawe i wysokosc trojkata:")
a = int(input())
h = int(input())
print(
"pole trojkata o podstawie ", a, " i wysokosci ", h, " jest rowne ", a * h / 2
)
"""
Pobierz dlu... | if __name__ == '__main__':
'\n Pobierz podstawe i wysokosc trojkata i wypisz pole.\n '
print('podaj podstawe i wysokosc trojkata:')
a = int(input())
h = int(input())
print('pole trojkata o podstawie ', a, ' i wysokosci ', h, ' jest rowne ', a * h / 2)
' \n\tPobierz dlugosci bokow prostokat... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | """Gabbi specific exceptions."""
class Gabbidataloaderror(ValueError):
"""An exception to alert when data streams cannot be loaded."""
pass
class Gabbiformaterror(ValueError):
"""An exception to encapsulate poorly formed test data."""
pass
class Gabbisyntaxwarning(SyntaxWarning):
"""A warning abo... |
logo = """
_____________________
| _________________ |
| | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------.
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
| ___ ___ ___ ___ | | | ______ | || | ... | logo = "\n _____________________\n| _________________ |\n| | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------. \n| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |\n| ___ ___ ___ ___ | | | ______ | || | ... |
fd = open('f',"r")
buffer = fd.read(2)
print("first 2 chars in f:",buffer)
fd.close()
| fd = open('f', 'r')
buffer = fd.read(2)
print('first 2 chars in f:', buffer)
fd.close() |
# from http://www.voidspace.org.uk/python/weblog/arch_d7_2007_03_17.shtml#e664
def ReadOnlyProxy(obj):
class _ReadOnlyProxy(object):
def __getattr__(self, name):
return getattr(obj, name)
def __setattr__(self, name, value):
raise AttributeError("Attributes can't be set on t... | def read_only_proxy(obj):
class _Readonlyproxy(object):
def __getattr__(self, name):
return getattr(obj, name)
def __setattr__(self, name, value):
raise attribute_error("Attributes can't be set on this object")
for name in dir(obj):
if not name[:2] == '__' == n... |
settings = {"velocity_min": 1,
"velocity_max": 3,
"x_boundary": 800,
"y_boundary": 800,
"small_particle_radius": 5,
"big_particle_radius": 10,
"number_of_particles": 500,
"density_min": 2,
"density_max": 20
} | settings = {'velocity_min': 1, 'velocity_max': 3, 'x_boundary': 800, 'y_boundary': 800, 'small_particle_radius': 5, 'big_particle_radius': 10, 'number_of_particles': 500, 'density_min': 2, 'density_max': 20} |
'''8. Write a Python program to count occurrences of a substring in a string.'''
def count_word_in_string(string1, substring2):
return string1.count(substring2)
print(count_word_in_string('The quick brown fox jumps over the lazy dog that is chasing the fox.', "fox")) | """8. Write a Python program to count occurrences of a substring in a string."""
def count_word_in_string(string1, substring2):
return string1.count(substring2)
print(count_word_in_string('The quick brown fox jumps over the lazy dog that is chasing the fox.', 'fox')) |
test = {
"name": "q2",
"points": 1,
"hidden": True,
"suites": [
{
"cases": [
{
"code": r"""
>>> sample_population(test_results).num_rows
3000
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> "Test Result" in sample_population(test_results).labe... | test = {'name': 'q2', 'points': 1, 'hidden': True, 'suites': [{'cases': [{'code': '\n\t\t\t\t\t>>> sample_population(test_results).num_rows\n\t\t\t\t\t3000\n\t\t\t\t\t', 'hidden': False, 'locked': False}, {'code': '\n\t\t\t\t\t>>> "Test Result" in sample_population(test_results).labels\n\t\t\t\t\tTrue\n\t\t\t\t\t', 'hi... |
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
stack = []
for char in s:
if char == '{' or char == '[' or char == '(':
stack.append(char)
else:
... | class Solution:
def is_valid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
stack = []
for char in s:
if char == '{' or char == '[' or char == '(':
stack.append(char)
else:
... |
def read_data():
rules = dict()
your_ticket = None
nearby_tickets = []
state = 0
with open('in') as f:
for line in map(lambda x: x.strip(), f.readlines()):
if line == '':
state += 1
continue
if line == 'your ticket:':
co... | def read_data():
rules = dict()
your_ticket = None
nearby_tickets = []
state = 0
with open('in') as f:
for line in map(lambda x: x.strip(), f.readlines()):
if line == '':
state += 1
continue
if line == 'your ticket:':
co... |
mapping = {
"settings": {
"index": {
"max_result_window": 15000,
"analysis": {
"analyzer": {
"default": {
"type": "custom",
"tokenizer": "whitespace",
"filter": ["english_s... | mapping = {'settings': {'index': {'max_result_window': 15000, 'analysis': {'analyzer': {'default': {'type': 'custom', 'tokenizer': 'whitespace', 'filter': ['english_stemmer', 'lowercase']}, 'autocomplete': {'type': 'custom', 'tokenizer': 'whitespace', 'filter': ['lowercase', 'autocomplete_filter']}, 'symbols': {'type':... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 26 15:06:57 2021
@author: user24
"""
file = "./data/tsuretsuregusa.txt"
with open(file, "r", encoding="utf_8") as fileobj:
while True:
# set line as value of the file line
line = fileobj.readline()
# removes any white space at the end of strin... | """
Created on Mon Jul 26 15:06:57 2021
@author: user24
"""
file = './data/tsuretsuregusa.txt'
with open(file, 'r', encoding='utf_8') as fileobj:
while True:
line = fileobj.readline()
aline = line.rstrip()
if aline:
print(aline)
else:
break |
'''
https://www.hackerrank.com/challenges/strings-xor/submissions/code/102872134
Given two strings consisting of digits 0 and 1 only, find the XOR of the two strings.
'''
def strings_xor(s, t):
res = ""
for i in range(len(s)):
if s[i] != t[i]:
res += '1'
else:
res += '0'... | """
https://www.hackerrank.com/challenges/strings-xor/submissions/code/102872134
Given two strings consisting of digits 0 and 1 only, find the XOR of the two strings.
"""
def strings_xor(s, t):
res = ''
for i in range(len(s)):
if s[i] != t[i]:
res += '1'
else:
res += '0'... |
__description__ = "Gearman RPC broker"
__config__ = {
"gearmand.listen_address": dict(
description = "IP address to bind to",
default = "127.0.0.1",
),
"gearmand.user": dict(
display_name = "Gearmand user",
description = "User to run the gearmand procses as",
default... | __description__ = 'Gearman RPC broker'
__config__ = {'gearmand.listen_address': dict(description='IP address to bind to', default='127.0.0.1'), 'gearmand.user': dict(display_name='Gearmand user', description='User to run the gearmand procses as', default='nobody'), 'gearmand.pidfile': dict(display_name='Gearmand pid fi... |
bot_token = ''
waiting_timeout = 5 # Seconds
admin_id = ""
channel_id = ""
bitly_access_token = ""
vars_file = ""
| bot_token = ''
waiting_timeout = 5
admin_id = ''
channel_id = ''
bitly_access_token = ''
vars_file = '' |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.5'
_lr_method = 'LALR'
_lr_signature = '5E2BB3531AA676A6BB1D06733251B2F3'
_lr_action_items = {'COS':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,... | _tabversion = '3.5'
_lr_method = 'LALR'
_lr_signature = '5E2BB3531AA676A6BB1D06733251B2F3'
_lr_action_items = {'COS': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 6... |
# The following is a list of gene-plan combinations which should
# not be run
BLACKLIST = [
('8C58', 'performance'), # performance.xml make specific references to 52DC
('7DDA', 'performance') # performance.xml make specific references to 52DC
]
IGNORE = {
'history' : ['uuid', 'creationTool', 'creationD... | blacklist = [('8C58', 'performance'), ('7DDA', 'performance')]
ignore = {'history': ['uuid', 'creationTool', 'creationDate'], 'genome': ['uuid', 'creationTool', 'creationDate'], 'attempt': ['description'], 'compared': ['description']} |
track = dict(
author_username='alexisbcook',
course_name='Data Cleaning',
course_url='https://www.kaggle.com/learn/data-cleaning',
course_forum_url='https://www.kaggle.com/learn-forum/172650'
)
lessons = [ {'topic': topic_name} for topic_name in
['Handling missing values', #1
... | track = dict(author_username='alexisbcook', course_name='Data Cleaning', course_url='https://www.kaggle.com/learn/data-cleaning', course_forum_url='https://www.kaggle.com/learn-forum/172650')
lessons = [{'topic': topic_name} for topic_name in ['Handling missing values', 'Scaling and normalization', 'Parsing dates', 'Ch... |
"""
https://leetcode.com/problems/3sum/
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A... | """
https://leetcode.com/problems/3sum/
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A... |
# !usr/bin/python
# -*- coding: UTF-8 -*-
class Image:
def __init__(self, name, path, url):
self.name = name
self.path = path
self.url = url
@property
def full_path(self):
return self.path + self.name
def __str__(self):
return self.name
def __repr__(self... | class Image:
def __init__(self, name, path, url):
self.name = name
self.path = path
self.url = url
@property
def full_path(self):
return self.path + self.name
def __str__(self):
return self.name
def __repr__(self):
return f' {{ Name: {self.name}, \... |
def metade(preco,sit):
if sit==True:
return (f'R${preco/2}')
else:
return preco/2
def dobro(preco,sit):
if sit==True:
return (f'R${preco * 2}')
else:
return preco * 2
def aumentar(preco,r,sit):
if sit==True:
return (f'R${preco * (100 + r)/100}')
else:
... | def metade(preco, sit):
if sit == True:
return f'R${preco / 2}'
else:
return preco / 2
def dobro(preco, sit):
if sit == True:
return f'R${preco * 2}'
else:
return preco * 2
def aumentar(preco, r, sit):
if sit == True:
return f'R${preco * (100 + r) / 100}'
... |
""" Test filters used by test_toolbox_filters.py.
"""
def filter_tool( context, tool ):
"""Test Filter Tool"""
return False
def filter_section( context, section ):
"""Test Filter Section"""
return False
def filter_label_1( context, label ):
"""Test Filter Label 1"""
return False
def filt... | """ Test filters used by test_toolbox_filters.py.
"""
def filter_tool(context, tool):
"""Test Filter Tool"""
return False
def filter_section(context, section):
"""Test Filter Section"""
return False
def filter_label_1(context, label):
"""Test Filter Label 1"""
return False
def filter_label_2... |
word=input("enter any word:")
d={}
for x in word:
d[x]=d.get(x,0)+1
for k,v in d.items():
print(k,"occured",v,"times") | word = input('enter any word:')
d = {}
for x in word:
d[x] = d.get(x, 0) + 1
for (k, v) in d.items():
print(k, 'occured', v, 'times') |
#!/usr/bin/env python3
average = 0
score = int(input('Enter first score: '))
score += int(input('Enter second score: '))
score += int(input('Enter third score: '))
average = score / 3.0
average = round(average, 2)
print(f'Total Score: {score}')
print(f'Average Score: {average}')
| average = 0
score = int(input('Enter first score: '))
score += int(input('Enter second score: '))
score += int(input('Enter third score: '))
average = score / 3.0
average = round(average, 2)
print(f'Total Score: {score}')
print(f'Average Score: {average}') |
"""restrictive_growth_strings.py: Constructs the lexicographic
restrictive growth string representation of all the way to partition a set,
given the length of the set."""
__author__ = "Justin Overstreet"
__copyright__ = "oversj96.github.io"
def set_to_zero(working_set, index):
"""Given a set and an index, set ... | """restrictive_growth_strings.py: Constructs the lexicographic
restrictive growth string representation of all the way to partition a set,
given the length of the set."""
__author__ = 'Justin Overstreet'
__copyright__ = 'oversj96.github.io'
def set_to_zero(working_set, index):
"""Given a set and an index, set al... |
"""
Author: Sean Toll
Test simulation functionality
"""
print("Test")
| """
Author: Sean Toll
Test simulation functionality
"""
print('Test') |
def binary_tree(r):
"""
:param r: This is root node
:return: returns tree
"""
return [r, [], []]
def insert_left(root, new_branch):
"""
:param root: current root of the tree
:param new_branch: new branch for a tree
:return: updated root of the tree
"""
t = root.pop(1)
i... | def binary_tree(r):
"""
:param r: This is root node
:return: returns tree
"""
return [r, [], []]
def insert_left(root, new_branch):
"""
:param root: current root of the tree
:param new_branch: new branch for a tree
:return: updated root of the tree
"""
t = root.pop(1)
if... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... | """
calculate AUC
"""
def calc_auc(raw_arr):
"""
calculate AUC
:param raw_arr:
:return:
"""
arr = sorted(raw_arr, key=lambda d: d[0], reverse=True)
(pos, neg) = (0.0, 0.0)
for record in arr:
if abs(record[1] - 1.0) < 1e-06:
pos += 1
else:
neg += 1... |
def is_valid(r, c, size):
if 0 <= r < size and 0 <= c < size:
return True
return False
count_presents = int(input())
n = int(input())
matrix = []
nice_kids_count = 0
given_to_nice = 0
for _ in range(n):
data = input().split()
matrix.append(data)
nice_kids_count += data.count("V")
santa_... | def is_valid(r, c, size):
if 0 <= r < size and 0 <= c < size:
return True
return False
count_presents = int(input())
n = int(input())
matrix = []
nice_kids_count = 0
given_to_nice = 0
for _ in range(n):
data = input().split()
matrix.append(data)
nice_kids_count += data.count('V')
santa_row =... |
# Setup
opt = ["yes", "no"]
directions = ["left", "right", "forward", "backward"]
# Introduction
name = input("What is your name, HaCKaToOnEr ?\n")
print("Welcome to Toonslate island , " + name + " Let us go on a Minecraft quest!")
print("You find yourself in front of a abandoned mineshaft.")
print("Can yo... | opt = ['yes', 'no']
directions = ['left', 'right', 'forward', 'backward']
name = input('What is your name, HaCKaToOnEr ?\n')
print('Welcome to Toonslate island , ' + name + ' Let us go on a Minecraft quest!')
print('You find yourself in front of a abandoned mineshaft.')
print('Can you find your way to explore the sh... |
#Julian Conneely, 21/03/18
#WhileIF loop with increment
#first 5 is printed
#then it is decreased to 4
#as it is not satisfying i<=2
#it moves on
#then 4 is printed
#then it is decreased to 3
#as it is not satisfying i<=2,it moves on
#then 3 is printed
#then it is decreased to 2
#as now i<=2 has completely satisfied, ... | i = 5
while True:
print(i)
i = i - 1
if i <= 2:
break |
MIN_CONF = 0.3
NMS_THRESH = 0.3
USE_GPU = False
MIN_DISTANCE = 50
WEIGHT_PATH = "yolov3-tiny.weights"
CONFIG_PATH = "yolov3-tiny.cfg" | min_conf = 0.3
nms_thresh = 0.3
use_gpu = False
min_distance = 50
weight_path = 'yolov3-tiny.weights'
config_path = 'yolov3-tiny.cfg' |
def f(x, y):
"""
Args:
x (Foo
y (Bar : description
""" | def f(x, y):
"""
Args:
x (Foo
y (Bar : description
""" |
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
k = 0
for n in nums:
k ^= n
return k | class Solution:
def single_number(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
k = 0
for n in nums:
k ^= n
return k |
expected_output = {
"address_family":{
"ipv4":{
"bfd_sessions_down":0,
"bfd_sessions_inactive":1,
"bfd_sessions_up":0,
"intf_down":1,
"intf_up":1,
"num_bfd_sessions":1,
"num_intf":2,
"state":{
"all":{
"sessions":2,... | expected_output = {'address_family': {'ipv4': {'bfd_sessions_down': 0, 'bfd_sessions_inactive': 1, 'bfd_sessions_up': 0, 'intf_down': 1, 'intf_up': 1, 'num_bfd_sessions': 1, 'num_intf': 2, 'state': {'all': {'sessions': 2, 'slaves': 0, 'total': 2}, 'backup': {'sessions': 1, 'slaves': 0, 'total': 1}, 'init': {'sessions':... |
class Stack():
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.item... | class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len... |
hola = True
adiosguillermomurielsanchezlafuente = True
if (adiosguillermomurielsanchezlafuente
and hola):
print("ok con nombre muy largo")
| hola = True
adiosguillermomurielsanchezlafuente = True
if adiosguillermomurielsanchezlafuente and hola:
print('ok con nombre muy largo') |
for i in range(1, int(input()) + 1):
quadrado = i ** 2
cubo = i ** 3
print(f'{i} {quadrado} {cubo}')
print(f'{i} {quadrado + 1} {cubo + 1}')
| for i in range(1, int(input()) + 1):
quadrado = i ** 2
cubo = i ** 3
print(f'{i} {quadrado} {cubo}')
print(f'{i} {quadrado + 1} {cubo + 1}') |
Scale.default = Scale.chromatic
Root.default = 0
Clock.bpm = 120
var.ch = var(P[1,5,0,3],8)
~p1 >> play('m', amp=.8, dur=PDur(3,8), rate=[1,(1,2)])
~p2 >> play('-', amp=.5, dur=2, hpf=2000, hpr=linvar([.1,1],16), sample=1).often('stutter', 4, dur=3).every(8, 'sample.offadd', 1)
~p3 >> play('{ ppP[pP][Pp]}', amp=.8,... | Scale.default = Scale.chromatic
Root.default = 0
Clock.bpm = 120
var.ch = var(P[1, 5, 0, 3], 8)
~p1 >> play('m', amp=0.8, dur=p_dur(3, 8), rate=[1, (1, 2)])
~p2 >> play('-', amp=0.5, dur=2, hpf=2000, hpr=linvar([0.1, 1], 16), sample=1).often('stutter', 4, dur=3).every(8, 'sample.offadd', 1)
~p3 >> play('{ ppP[pP][Pp]}'... |
def namedArgumentFunction(a, b, c):
print("the values are a: {}, b: {}, c: {}".format(a,b,c))
namedArgumentFunction(100, 200, 300) # positional arguments
namedArgumentFunction(c=3, a=1, b=2) # named arguments
#namedArgumentFunction(181, a=102, b=103) # mix of position + name error
namedArgumentFunction(101... | def named_argument_function(a, b, c):
print('the values are a: {}, b: {}, c: {}'.format(a, b, c))
named_argument_function(100, 200, 300)
named_argument_function(c=3, a=1, b=2)
named_argument_function(101, b=102, c=103) |
# Basic String Operations (Title)
# Reading
# Iterating over a String with the 'for' Loop (section)
# General Format:
# for variable in string:
# statement
# statement
# etc.
name = 'Juliet'
for ch in name:
print(ch)
# This program counts the number of times the letter T
# ... | name = 'Juliet'
for ch in name:
print(ch)
def main():
count = 0
my_string = input('Enter a sentence: ')
for ch in my_string:
if ch == 'T' or ch == 't':
count += 1
print(f'The letter T appears {count} times.')
if __name__ == '__main__':
main()
my_string = 'Roses are red'
ch =... |
height = int(input())
apartments = int(input())
is_first = True
isit = 0
for f in range(height, 0, -1):
for s in range(0, apartments, 1):
if is_first == True:
isit += 1
print(f"L{f}{s}", end=" ")
if isit == apartments:
is_first = False
cont... | height = int(input())
apartments = int(input())
is_first = True
isit = 0
for f in range(height, 0, -1):
for s in range(0, apartments, 1):
if is_first == True:
isit += 1
print(f'L{f}{s}', end=' ')
if isit == apartments:
is_first = False
cont... |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/twice-counter/0
def sol(words):
h = {}
res = 0
for word in words:
h[word] = h[word] + 1 if word in h else 1
for word in h:
if h[word] == 2:
res+=1
return res | def sol(words):
h = {}
res = 0
for word in words:
h[word] = h[word] + 1 if word in h else 1
for word in h:
if h[word] == 2:
res += 1
return res |
class Solution:
# Reverse Format String (Accepted), O(1) time and space
def reverseBits(self, n: int) -> int:
s = '{:032b}'.format(n)[::-1]
return int(s, 2)
# Bit Manipulation (Top Voted), O(1) time and space
def reverseBits(self, n: int) -> int:
ans = 0
for i in range(3... | class Solution:
def reverse_bits(self, n: int) -> int:
s = '{:032b}'.format(n)[::-1]
return int(s, 2)
def reverse_bits(self, n: int) -> int:
ans = 0
for i in range(32):
ans = (ans << 1) + (n & 1)
n >>= 1
return ans |
def count_frequency(a):
freq = dict()
for items in a:
freq[items] = a.count(items)
return freq
def solution(data, n):
frequency = count_frequency(data)
for key, value in frequency.items():
if value > n:
data = list(filter(lambda a: a != key, data))
... | def count_frequency(a):
freq = dict()
for items in a:
freq[items] = a.count(items)
return freq
def solution(data, n):
frequency = count_frequency(data)
for (key, value) in frequency.items():
if value > n:
data = list(filter(lambda a: a != key, data))
return data
prin... |
# Copyright 2020 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | def nested_method():
return 'nested'
def root_method():
return 'root'
def another_root_method():
return 'another root' |
inventory = {'croissant': 19, 'bagel': 4, 'muffin': 8, 'cake': 1}
print(f'{inventory =}')
stock_list = inventory.copy()
print(f'{stock_list =}')
stock_list['hot cheetos'] = 25
stock_list.update({'cookie' : 18})
stock_list.pop('cake')
print(f'{stock_list =}') | inventory = {'croissant': 19, 'bagel': 4, 'muffin': 8, 'cake': 1}
print(f'inventory ={inventory!r}')
stock_list = inventory.copy()
print(f'stock_list ={stock_list!r}')
stock_list['hot cheetos'] = 25
stock_list.update({'cookie': 18})
stock_list.pop('cake')
print(f'stock_list ={stock_list!r}') |
#Program to change a given string to a new string where the first and last chars have been exchanged.
string=str(input("Enter a string :"))
first=string[0] #store first index element of string in variable
last=string[-1] #store last index element of string in var... | string = str(input('Enter a string :'))
first = string[0]
last = string[-1]
new = last + string[1:-1] + first
print(new) |
"""
Class hierarchy for company management
"""
class Company:
def __init__(self, company_name, location):
self.company_name = company_name
self.location = location
def __str__(self):
return f"Company: {self.company_name}, {self.location}"
def __repr(self):
return f"Company... | """
Class hierarchy for company management
"""
class Company:
def __init__(self, company_name, location):
self.company_name = company_name
self.location = location
def __str__(self):
return f'Company: {self.company_name}, {self.location}'
def __repr(self):
return f'Compan... |
# Make sure to rename this file as "config.py" before running the bot.
verbose=True
api_token='0000000000:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# Enter the user ID and a readable name for each user in your group.
# TODO make balaguer automatically collect user IDs.
# But that's only useful if the bot actuall... | verbose = True
api_token = '0000000000:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
all_users = {0: 'Readable Name', 0: 'Readable Name', 0: 'Readable Name', 0: 'Readable Name'}
admins = [0, 0, 0, 0]
approved_groups = [-0, -0] |
class GameException(Exception):
pass
class GameFlowException(GameException):
pass
class EndProgram(GameFlowException):
pass
class InvalidPlayException(GameException):
pass
| class Gameexception(Exception):
pass
class Gameflowexception(GameException):
pass
class Endprogram(GameFlowException):
pass
class Invalidplayexception(GameException):
pass |
# Copyright 2018 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Partial response utilities for an Endpoints v1 over webapp2 service.
Grammar of a fields partial response string:
fields: selector [,select... | """Partial response utilities for an Endpoints v1 over webapp2 service.
Grammar of a fields partial response string:
fields: selector [,selector]*
selector: path [(fields)]?
path: name [/name]*
name: [A-Za-z_][A-Za-z0-9_]* | \\*
Examples:
fields=a
Response includes the value of the "a" field.
fields=a... |
def count_vowels(txt):
vs = "a, e, i, o, u".split(', ')
return sum([1 for t in txt if t in vs])
print(count_vowels('Hello world')) | def count_vowels(txt):
vs = 'a, e, i, o, u'.split(', ')
return sum([1 for t in txt if t in vs])
print(count_vowels('Hello world')) |
class GroupTransform:
"""
GroupTransform
"""
def __init__(self):
pass
def getTransform(self):
pass
def getTransforms(self):
pass
def setTransforms(self, transforms):
pass
def size(self):
pass
def push_back(self, transform):
pass
de... | class Grouptransform:
"""
GroupTransform
"""
def __init__(self):
pass
def get_transform(self):
pass
def get_transforms(self):
pass
def set_transforms(self, transforms):
pass
def size(self):
pass
def push_back(self, transform):
pas... |
class KarmaCard(object):
info = {'type': ['number', 'wild'],
'trait': ['4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A', '2', '3', '10', 'draw'],
'order': ['4:4', '4:3', '4:2', '4:1', '5:4', '5:3', '5:2', '5:1', '6:4', '6:3', '6:2', '6:1',
'7:4', '7:3', '7:2', '7:1', ... | class Karmacard(object):
info = {'type': ['number', 'wild'], 'trait': ['4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A', '2', '3', '10', 'draw'], 'order': ['4:4', '4:3', '4:2', '4:1', '5:4', '5:3', '5:2', '5:1', '6:4', '6:3', '6:2', '6:1', '7:4', '7:3', '7:2', '7:1', '8:4', '8:3', '8:2', '8:1', '9:4', '9:3', '9:2',... |
#!/usr/bin/env python
# pylint: disable=too-few-public-methods
"""Reusable string literals."""
class DockerAuthentication:
"""
https://github.com/docker/distribution/blob/master/docs/spec/auth/token.md
https://github.com/docker/distribution/blob/master/docs/spec/auth/scope.md
"""
DOCKERHUB_URL_... | """Reusable string literals."""
class Dockerauthentication:
"""
https://github.com/docker/distribution/blob/master/docs/spec/auth/token.md
https://github.com/docker/distribution/blob/master/docs/spec/auth/scope.md
"""
dockerhub_url_pattern = '{0}?service={1}&scope={2}&client_id=docker-registry-clie... |
def test_see_for_top_level(result):
assert (
"usage: vantage [-a PATH] [-e NAME ...] [-v KEY=[VALUE] ...] [--verbose] [-h] COMMAND..."
in result.stdout_
)
| def test_see_for_top_level(result):
assert 'usage: vantage [-a PATH] [-e NAME ...] [-v KEY=[VALUE] ...] [--verbose] [-h] COMMAND...' in result.stdout_ |
def wordBreakDP(word, dic):
n = len(word)
if word in dic:
return True
if len(dic) == 0:
return False
dp = [False for i in range(n + 1)]
dp[0] = True
for i in range(1, n + 1):
for j in range(i - 1, -1, -1):
if dp[j] == True:
substring = word[j:i... | def word_break_dp(word, dic):
n = len(word)
if word in dic:
return True
if len(dic) == 0:
return False
dp = [False for i in range(n + 1)]
dp[0] = True
for i in range(1, n + 1):
for j in range(i - 1, -1, -1):
if dp[j] == True:
substring = word[j... |
file1= "db_breakfast_menu.txt"
file2= "db_lunch_menu.txt"
file3= "db_dinner_menu.txt"
file4 = "db_label_text.txt"
retail = []
title = []
label = []
with open(file1, "r") as f:
data = f.readlines()
for line in data:
w = line.split(":")
title.append(w[1])
for line in data:
w... | file1 = 'db_breakfast_menu.txt'
file2 = 'db_lunch_menu.txt'
file3 = 'db_dinner_menu.txt'
file4 = 'db_label_text.txt'
retail = []
title = []
label = []
with open(file1, 'r') as f:
data = f.readlines()
for line in data:
w = line.split(':')
title.append(w[1])
for line in data:
w = line.split('$')
price... |
class Guesser:
def __init__(self, number, lives):
self.number = number
self.lives = lives
def guess(self,n):
if self.lives < 1:
raise Exception("Omae wa mo shindeiru")
match = n == self.number
if not match:
self.lives -= 1
return match | class Guesser:
def __init__(self, number, lives):
self.number = number
self.lives = lives
def guess(self, n):
if self.lives < 1:
raise exception('Omae wa mo shindeiru')
match = n == self.number
if not match:
self.lives -= 1
return match |
def get_assign(user_input):
key, value = user_input.split("gets")
key = key.strip()
value = int(value.strip())
my_dict[key] = value
print(my_dict)
def add_values(num1, num2):
return num1 + num2
print("Welcome to the Adder REPL.")
my_dict = dict()
while True:
user_input = input("???")
... | def get_assign(user_input):
(key, value) = user_input.split('gets')
key = key.strip()
value = int(value.strip())
my_dict[key] = value
print(my_dict)
def add_values(num1, num2):
return num1 + num2
print('Welcome to the Adder REPL.')
my_dict = dict()
while True:
user_input = input('???')
... |
"""
Solution for
Sort Integers by The Power Value: https://leetcode.com/problems/sort-integers-by-the-power-value/
"""
class Solution:
def getKth(self, lo: int, hi: int, k: int) -> int:
# Can I calculate the power of an integer?
# if two ints have same power, sort by the ints
# power of 1... | """
Solution for
Sort Integers by The Power Value: https://leetcode.com/problems/sort-integers-by-the-power-value/
"""
class Solution:
def get_kth(self, lo: int, hi: int, k: int) -> int:
def calculate_steps(range_int: int) -> int:
steps = 0
while range_int != 1:
i... |
try:
for i in ['a', 'b', 'c']:
print(i ** 2)
except TypeError:
print("An error occured!")
x = 5
y = 0
try:
z = x /y
print(z)
except ZeroDivisionError:
print("Can't devide by zero")
finally:
print("All done")
def ask():
while True:
try:
val = int(input("Input a... | try:
for i in ['a', 'b', 'c']:
print(i ** 2)
except TypeError:
print('An error occured!')
x = 5
y = 0
try:
z = x / y
print(z)
except ZeroDivisionError:
print("Can't devide by zero")
finally:
print('All done')
def ask():
while True:
try:
val = int(input('Input an ... |
NR_CLASSES = 10
hyperparameters = {
"number-epochs" : 30,
"batch-size" : 100,
"learning-rate" : 0.005,
"weight-decay" : 1e-9,
"learning-decay" : 1e-3
}
| nr_classes = 10
hyperparameters = {'number-epochs': 30, 'batch-size': 100, 'learning-rate': 0.005, 'weight-decay': 1e-09, 'learning-decay': 0.001} |
class DoublyLinkedList:
""" Private Node Class """
class _Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __str__(self):
return self.value
def __init__(self):
self.head = None
self.tai... | class Doublylinkedlist:
""" Private Node Class """
class _Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __str__(self):
return self.value
def __init__(self):
self.head = None
self.t... |
#!/usr/bin/python3
'''
BubbleSort.py
by Xiaoguang Zhu
'''
array = []
print("Enter at least two numbers to start bubble-sorting.")
print("(You can end inputing anytime by entering nonnumeric)")
# get numbers
while True:
try:
array.append(float(input(">> ")))
except ValueError: # exit inputing
break
print("\nTh... | """
BubbleSort.py
by Xiaoguang Zhu
"""
array = []
print('Enter at least two numbers to start bubble-sorting.')
print('(You can end inputing anytime by entering nonnumeric)')
while True:
try:
array.append(float(input('>> ')))
except ValueError:
break
print("\nThe array you've entered was:")
print... |
medida = float(input("uma distancai em metros: "))
cm = medida * 100
mm = medida * 1000
dm = medida / 10
dam = medida * 1000000
hm = medida / 100
km = medida * 0.001
ml = medida * 0.000621371
m = medida * 100000
print("A medida de {:.0f}m corresponde a {:.0f} mm \n{:.0f} cm \n{:.0f} dm \n{:.0f} dam \n{:.0f} hm \n{:.2f... | medida = float(input('uma distancai em metros: '))
cm = medida * 100
mm = medida * 1000
dm = medida / 10
dam = medida * 1000000
hm = medida / 100
km = medida * 0.001
ml = medida * 0.000621371
m = medida * 100000
print('A medida de {:.0f}m corresponde a {:.0f} mm \n{:.0f} cm \n{:.0f} dm \n{:.0f} dam \n{:.0f} hm \n{:.2f}... |
def create_supervised_data(env, agents, num_runs=50):
val = []
# the data threeple
action_history = []
predict_history = []
mental_history = []
character_history = []
episode_history = []
traj_history = []
grids = []
ep_length = env.maxtime
filler = env.get_filler()
obs = env.reset(setting=setting, nu... | def create_supervised_data(env, agents, num_runs=50):
val = []
action_history = []
predict_history = []
mental_history = []
character_history = []
episode_history = []
traj_history = []
grids = []
ep_length = env.maxtime
filler = env.get_filler()
obs = env.reset(setting=setti... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists: list):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists) == 0:
return None... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def merge_k_lists(self, lists: list):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists) == 0:
return None
if len(lists) == 1:
... |
def create_path(path:str):
"""
:param path:path is the relative path from the pixel images folder
:return: return the relative path from roots of project
"""
return current_path + path
#a function name is before the parameters and after the def
#function parameters: the values that the function kn... | def create_path(path: str):
"""
:param path:path is the relative path from the pixel images folder
:return: return the relative path from roots of project
"""
return current_path + path |
def rep_hill(x, n):
"""Dimensionless production rate for a gene repressed by x.
Parameters
----------
x : float or NumPy array
Concentration of repressor.
n : float
Hill coefficient.
Returns
-------
output : NumPy array or float
1 / (1 + x**n)
"""
return... | def rep_hill(x, n):
"""Dimensionless production rate for a gene repressed by x.
Parameters
----------
x : float or NumPy array
Concentration of repressor.
n : float
Hill coefficient.
Returns
-------
output : NumPy array or float
1 / (1 + x**n)
"""
return... |
n = int(input())
vip_guest = set()
regular_guest = set()
for _ in range(n):
reservation_code = input()
if reservation_code[0].isdigit():
vip_guest.add(reservation_code)
else:
regular_guest.add(reservation_code)
command = input()
while command != "END":
if command[0].isdigit():
... | n = int(input())
vip_guest = set()
regular_guest = set()
for _ in range(n):
reservation_code = input()
if reservation_code[0].isdigit():
vip_guest.add(reservation_code)
else:
regular_guest.add(reservation_code)
command = input()
while command != 'END':
if command[0].isdigit():
vi... |
class alttprException(Exception):
pass
class alttprFailedToRetrieve(Exception):
pass
class alttprFailedToGenerate(Exception):
pass
| class Alttprexception(Exception):
pass
class Alttprfailedtoretrieve(Exception):
pass
class Alttprfailedtogenerate(Exception):
pass |
EXPECTED_TABULATED_HTML = """
<table>
<thead>
<tr>
<th>category</th>
<th>date</th>
<th>downloads</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">2.6</td>
<td align="left">2018-08-15</td>
<td align="right">51</t... | expected_tabulated_html = '\n<table>\n <thead>\n <tr>\n <th>category</th>\n <th>date</th>\n <th>downloads</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td align="left">2.6</td>\n <td align="left">2018-08-15</td>\n <td align="r... |
# Runtime: 84 ms, faster than 22.95% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree.
# Memory Usage: 23.1 MB, less than 91.67% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# ... | class Solution:
def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None:
return None
if root is p or root is q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAnce... |
load(
"//tensorflow/core/platform:rules_cc.bzl",
"cc_library",
)
def poplar_cc_library(**kwargs):
""" Wrapper for inserting poplar specific build options.
"""
if not "copts" in kwargs:
kwargs["copts"] = []
copts = kwargs["copts"]
copts.append("-Werror=return-type")
cc_library(**kwargs)
| load('//tensorflow/core/platform:rules_cc.bzl', 'cc_library')
def poplar_cc_library(**kwargs):
""" Wrapper for inserting poplar specific build options.
"""
if not 'copts' in kwargs:
kwargs['copts'] = []
copts = kwargs['copts']
copts.append('-Werror=return-type')
cc_library(**kwargs) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Question:
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also t... | """
Question:
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have s... |
# Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module provides a model for a monitoring station, and tools
for manipulating/modifying station data
"""
class MonitoringStation:
"""This class represents a river level monitoring station"""
def __init__(self, station_id, measure_id... | """This module provides a model for a monitoring station, and tools
for manipulating/modifying station data
"""
class Monitoringstation:
"""This class represents a river level monitoring station"""
def __init__(self, station_id, measure_id, label, coord, typical_range, river, town):
self.station_id =... |
a = input("Enter the string:")
b = a.find("@")
c = a.find("#")
print("The original string is:",a)
print("The substring between @ and # is:",a[b+1:c]) | a = input('Enter the string:')
b = a.find('@')
c = a.find('#')
print('The original string is:', a)
print('The substring between @ and # is:', a[b + 1:c]) |
def fahrenheit_to_celsius(F):
'''
Function to compute Celsius from Fahrenheit
'''
K = fahrenheit_to_kelvin(F)
C = kelvin_to_celsius(K)
return C
| def fahrenheit_to_celsius(F):
"""
Function to compute Celsius from Fahrenheit
"""
k = fahrenheit_to_kelvin(F)
c = kelvin_to_celsius(K)
return C |
def read_lines(file_path):
with open(file_path, 'r') as handle:
return [line.strip() for line in handle]
def count_bits(numbers):
counts = [0] * len(numbers[0])
for num in numbers:
for i, bit in enumerate(num):
counts[i] += int(bit)
return counts
lines = read_lines('test... | def read_lines(file_path):
with open(file_path, 'r') as handle:
return [line.strip() for line in handle]
def count_bits(numbers):
counts = [0] * len(numbers[0])
for num in numbers:
for (i, bit) in enumerate(num):
counts[i] += int(bit)
return counts
lines = read_lines('test.t... |
famous_name = "albert einstein"
motto = "A person who never made a mistake never tried anything new."
message = famous_name.title() + "once said, " + '"' + motto + '"'
print(message) | famous_name = 'albert einstein'
motto = 'A person who never made a mistake never tried anything new.'
message = famous_name.title() + 'once said, ' + '"' + motto + '"'
print(message) |
JIRA_DOMAIN = {'RD2': ['innodiv-hwacom.atlassian.net','innodiv-hwacom.atlassian.net'],
'RD5': ['srddiv5-hwacom.atlassian.net']}
API_PREFIX = 'rest/agile/1.0'
# project_id : column_name
STORY_POINT_COL_NAME = {'10005': 'customfield_10027',
'10006': 'customfield_10027',
... | jira_domain = {'RD2': ['innodiv-hwacom.atlassian.net', 'innodiv-hwacom.atlassian.net'], 'RD5': ['srddiv5-hwacom.atlassian.net']}
api_prefix = 'rest/agile/1.0'
story_point_col_name = {'10005': 'customfield_10027', '10006': 'customfield_10027', '10004': 'customfield_10026'} |
class PixelMeasurer:
def __init__(self, coordinate_store, is_one_calib_block, correction_factor):
self.coordinate_store = coordinate_store
self.is_one_calib_block = is_one_calib_block
self.correction_factor = correction_factor
def get_distance(self, calibration_length):
distance... | class Pixelmeasurer:
def __init__(self, coordinate_store, is_one_calib_block, correction_factor):
self.coordinate_store = coordinate_store
self.is_one_calib_block = is_one_calib_block
self.correction_factor = correction_factor
def get_distance(self, calibration_length):
distanc... |
# Programming for the Puzzled -- Srini Devadas
# You Will All Conform
# Input is a vector of F's and B's, in terms of forwards and backwards caps
# Output is a set of commands (printed out) to get either all F's or all B's
# Fewest commands are the goal
caps = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B... | caps = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F']
cap2 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'F', 'F']
def please_conform(caps):
start = 0
forward = 0
backward = 0
intervals = []
for i in range(len(caps)):
if caps[start] != caps[i]:
int... |
s=input()
t=input()
ss=sorted(map(s.count,set(s)))
tt=sorted(map(t.count,set(t)))
print('Yes' if ss==tt else 'No')
| s = input()
t = input()
ss = sorted(map(s.count, set(s)))
tt = sorted(map(t.count, set(t)))
print('Yes' if ss == tt else 'No') |
def anagrams(word, words):
agrams = []
s1 = sorted(word)
for i in range (0, len(words)):
s2 = sorted(words[i])
if s1 == s2:
agrams.append(words[i])
return agrams | def anagrams(word, words):
agrams = []
s1 = sorted(word)
for i in range(0, len(words)):
s2 = sorted(words[i])
if s1 == s2:
agrams.append(words[i])
return agrams |
#!/usr/bin/env python
"""
WhatIsCode
This extremely simple script was an inspiration driven by a combination of
Paul Ford's article on Bloomberg Business Week, "What is Code?"[1] and
Haddaway's song, "What is Love"[2]. It is probably best enjoyed while
watching an 8-bit demake of the song[3], or 16-bit if you prefer... | """
WhatIsCode
This extremely simple script was an inspiration driven by a combination of
Paul Ford's article on Bloomberg Business Week, "What is Code?"[1] and
Haddaway's song, "What is Love"[2]. It is probably best enjoyed while
watching an 8-bit demake of the song[3], or 16-bit if you prefer[4]. :-)
[1] http://ww... |
initialScore = int(input())
def count_solutions(score, turn):
if score > 50 or turn > 4:
return 0
if score == 50:
return 1
result = count_solutions(score + 1, turn + 1)
for i in range(2, 13):
result += 2 * count_solutions(score + i, turn + 1)
return result
print(count... | initial_score = int(input())
def count_solutions(score, turn):
if score > 50 or turn > 4:
return 0
if score == 50:
return 1
result = count_solutions(score + 1, turn + 1)
for i in range(2, 13):
result += 2 * count_solutions(score + i, turn + 1)
return result
print(count_solut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.