content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# by Kami Bigdely
# Replace magic numbers with named constanst
def calculation(charge1, charge2, distance):
constant = 8.9875517923*1e9
return constant * charge1 * charge2 / (distance**2)
# First Section
# Given two point charges, calcualte the electric force exerted on them.
q1 = int(input('Enter ... | def calculation(charge1, charge2, distance):
constant = 8.9875517923 * 1000000000.0
return constant * charge1 * charge2 / distance ** 2
q1 = int(input('Enter a value of charge q1: '))
q2 = int(input('Enter a value of charge q2: '))
distance = int(input('Enter the distance be10tween two charges: '))
print('Elect... |
class IDataset(object):
def __init__(self):
pass
def train(self):
raise RuntimeError("No implementation found!")
def val(self):
raise RuntimeError("No implementation found!")
def test(self):
raise RuntimeError("No implementation found!")
| class Idataset(object):
def __init__(self):
pass
def train(self):
raise runtime_error('No implementation found!')
def val(self):
raise runtime_error('No implementation found!')
def test(self):
raise runtime_error('No implementation found!') |
class A:
def z(self):
return self
def y(self, t):
return len(t)
#Funcion que abriremos desde el archivo main.py
def main_puzzle():
a = A
y = a.z
print(y(a)) #Muestra por pantalla <class '__main__.A'> ya que la funcion z devuelve self
aa = a()
print(aa is a()) #Impri... | class A:
def z(self):
return self
def y(self, t):
return len(t)
def main_puzzle():
a = A
y = a.z
print(y(a))
aa = a()
print(aa is a())
z = aa.y
print(z(()))
print(a().y((a,)))
print(A.y(aa, (a, z)))
print(aa.y((z, 1, 'z'))) |
#define MAX(x,y) (((x) > (y)) ? (x) : (y))
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
class solution:
def maxProfit(prices:list[int])->int:
pricesSize = len(prices)
dp_sell_out = []
dp_sell_with = []
dp_buy = []
#current action is not selling, next step cou... | class Solution:
def max_profit(prices: list[int]) -> int:
prices_size = len(prices)
dp_sell_out = []
dp_sell_with = []
dp_buy = []
dp_sell_out.append(0)
dp_sell_with.append(0)
dp_buy.append(-prices[0])
for i in range(1, pricesSize):
dp_sel... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
curr_node = head
curr_new = new_head = ListNode(0)
prev = None
wh... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
curr_node = head
curr_new = new_head = list_node(0)
prev = None
while curr_node:
if curr_n... |
# This program subtracts one number from another
# Author: Isabella Doyle
first = int(input("Enter the first number:")) # requests input of integer from user
second = int(input("Enter the second number:")) # requests input of integer from user
# prints sum below
print(first - second) | first = int(input('Enter the first number:'))
second = int(input('Enter the second number:'))
print(first - second) |
def test_get_uptimez(client):
response = client.get("/uptimez/")
assert response.status_code == 200
def test_get_healthz(client):
response = client.get("/healthz/")
assert response.status_code == 200
| def test_get_uptimez(client):
response = client.get('/uptimez/')
assert response.status_code == 200
def test_get_healthz(client):
response = client.get('/healthz/')
assert response.status_code == 200 |
print("Hello world")
print("Adios")
def suma(a,b):
return a+b
print(suma(2,3))
print("Esto es una feature") | print('Hello world')
print('Adios')
def suma(a, b):
return a + b
print(suma(2, 3))
print('Esto es una feature') |
t = int(input())
for _ in range(t) :
n, k = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
if(k > arr[0]) :
print(abs(k-arr[0]))
else :
print(0) | t = int(input())
for _ in range(t):
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
if k > arr[0]:
print(abs(k - arr[0]))
else:
print(0) |
# -*- coding: utf-8 -*-
"""
stocks_correlation.providers.quandl
This module define the normalized columns
of the DataFrame the providers return
"""
DATAFRAME_COLUMNS = ['date', 'open', 'high', 'low', 'close']
CORREL_COMPUTE_COLUMNS = DATAFRAME_COLUMNS[1:]
def filter_dates(df, start_date, end_date):
"""Filters ... | """
stocks_correlation.providers.quandl
This module define the normalized columns
of the DataFrame the providers return
"""
dataframe_columns = ['date', 'open', 'high', 'low', 'close']
correl_compute_columns = DATAFRAME_COLUMNS[1:]
def filter_dates(df, start_date, end_date):
"""Filters the DataFrame so that all t... |
a = int(input("Enter the First Number: "))# Inputing the first number
b = int(input("Enter the seconf Number: "))#inputing the second number
if(a>=b):#cheking if the first
print(a, "is greater")
else:
print(b, "is greater")
| a = int(input('Enter the First Number: '))
b = int(input('Enter the seconf Number: '))
if a >= b:
print(a, 'is greater')
else:
print(b, 'is greater') |
__name__ = "pairwisedist"
__author__ = """Guy Teichman"""
__email__ = "guyteichman@gmail.com"
__version__ = "1.1.0"
__license__ = "Apache"
| __name__ = 'pairwisedist'
__author__ = 'Guy Teichman'
__email__ = 'guyteichman@gmail.com'
__version__ = '1.1.0'
__license__ = 'Apache' |
"""
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words,
find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers
as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, ... | """
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words,
find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers
as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, ... |
MAJOR = 1
MINOR = 11
RELEASE = 10
VERSION = '%d.%d.%d' % (MAJOR, MINOR, RELEASE)
def num(versionstring=VERSION):
"""Convert the version string of the form 'X.Y.Z' to an integer 100000*X + 100*Y + Z for version comparison"""
(major, minor, release) = versionstring.split('.')
return 100*100*int(major) +... | major = 1
minor = 11
release = 10
version = '%d.%d.%d' % (MAJOR, MINOR, RELEASE)
def num(versionstring=VERSION):
"""Convert the version string of the form 'X.Y.Z' to an integer 100000*X + 100*Y + Z for version comparison"""
(major, minor, release) = versionstring.split('.')
return 100 * 100 * int(major) + ... |
"""
Standardize Mobile Number Using Decorators
https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem
"""
def wrapper(f):
def fun(l):
# complete the function
for i, n in enumerate(l):
if len(n) == 10: n= "+91" + n
elif len(n) == 11 and n.st... | """
Standardize Mobile Number Using Decorators
https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem
"""
def wrapper(f):
def fun(l):
for (i, n) in enumerate(l):
if len(n) == 10:
n = '+91' + n
elif len(n) == 11 and n.startswith('0'... |
#returns the set of reachable vertices assuming G is represented via adjacency lists.
# Assumes that the graph is a dictionary and each adjacency list is a set.
def reachable(G,v):
rset = set()
def dfs(w):
rset.add(w)
for ngh in G[w]:
if not (ngh in rset):
dfs(ngh)
return
dfs(v)
return(rset)
G = {}
G... | def reachable(G, v):
rset = set()
def dfs(w):
rset.add(w)
for ngh in G[w]:
if not ngh in rset:
dfs(ngh)
return
dfs(v)
return rset
g = {}
G[0] = {1, 2, 3}
G[1] = {0, 3}
G[2] = {}
G[3] = {1, 4, 2}
G[4] = {5, 6}
G[5] = {4}
G[7] = {5, 6}
G[6] = {5, 7}
pri... |
#
# PySNMP MIB module ADSL-LINE-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADSL-LINE-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:58:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (adsl_atuc_perf_data_entry, adsl_atur_interval_entry, adsl_atuc_interval_entry, adsl_line_alarm_conf_profile_entry, adsl_line_entry, adsl_line_conf_profile_entry, adsl_atur_perf_data_entry, adsl_mib) = mibBuilder.importSymbols('ADSL-LINE-MIB', 'adslAtucPerfDataEntry', 'adslAturIntervalEntry', 'adslAtucIntervalEntry', '... |
def fahrenheit_to_celsius(F):
C = 0
# Your code goes here: calculate the temperature in Celsius,
# store in a variable (we called it C), and return it.
return C
| def fahrenheit_to_celsius(F):
c = 0
return C |
base_datapath = '/Work19/2020/lijunjie/LRS3/AV_model_database/'
with open(base_datapath+'pretrain_dataset.txt', 'r') as tr:
lines = tr.readlines()
for line in lines:
info = line.strip().split('.')
num1 = info[0].strip().split('-')[1]
num2 = info[0].strip().split('-')[2]
new_lin... | base_datapath = '/Work19/2020/lijunjie/LRS3/AV_model_database/'
with open(base_datapath + 'pretrain_dataset.txt', 'r') as tr:
lines = tr.readlines()
for line in lines:
info = line.strip().split('.')
num1 = info[0].strip().split('-')[1]
num2 = info[0].strip().split('-')[2]
new_lin... |
"""Our first program in Python"""
#print is the function to show to the user all we want
print('Welcome to Python')
#input is the functions that we use to recive data from the user
name = input('Give me your name')
#We can print the data we recive
print('Hello ', name)
| """Our first program in Python"""
print('Welcome to Python')
name = input('Give me your name')
print('Hello ', name) |
# Copyright (c) 2021 by Don Deel. All rights reserved.
"""
Shared data for fishem and its modules.
All Redfish and Swordfish objects are shared as JSON objects in a
dictionary named "fish". Redfish resource path names are used as
keys to access objects in this dictionary, and these objects can
contain nested elements... | """
Shared data for fishem and its modules.
All Redfish and Swordfish objects are shared as JSON objects in a
dictionary named "fish". Redfish resource path names are used as
keys to access objects in this dictionary, and these objects can
contain nested elements. Examples are shown here:
Key (path) ... |
def entry(**kwargs):
return '\n'.join([
"Welcome to SAMi",
"What would you like? REPLY",
"1 = Resources",
"2 = Talk to a friend",
"3 = Charge your phone",
])
def resources_1(**kwargs):
return '\n'.join([
"Welcome to resources: TEXT",
"1 = Food",
... | def entry(**kwargs):
return '\n'.join(['Welcome to SAMi', 'What would you like? REPLY', '1 = Resources', '2 = Talk to a friend', '3 = Charge your phone'])
def resources_1(**kwargs):
return '\n'.join(['Welcome to resources: TEXT', '1 = Food', '2 = Shelters', '3 = Bathroom/Showers'])
def resources_shelters_1(**... |
def aumentar(preco=0, taxa=0, formatado=False):
res = preco + (preco * taxa / 100)
return res if formatado is False else moeda(res)
def diminuir(preco=0, taxa=0, formatado=False):
res = preco - (preco * taxa / 100)
return res if formatado is False else moeda(res)
def dobro(preco=0, formatado=False):... | def aumentar(preco=0, taxa=0, formatado=False):
res = preco + preco * taxa / 100
return res if formatado is False else moeda(res)
def diminuir(preco=0, taxa=0, formatado=False):
res = preco - preco * taxa / 100
return res if formatado is False else moeda(res)
def dobro(preco=0, formatado=False):
r... |
class Queue:
def __init__(self, initial_size = 10):
self.arr = [0 for _ in range(initial_size)]
self.next_index = 0;
self.front_index = -1;
self.queue_size = 0;
def enqueue(self, value):
if(self.queue_size) == len(self.arr):
self.handle_queue_capacity_full();
self.arr[self.next_index... | class Queue:
def __init__(self, initial_size=10):
self.arr = [0 for _ in range(initial_size)]
self.next_index = 0
self.front_index = -1
self.queue_size = 0
def enqueue(self, value):
if self.queue_size == len(self.arr):
self.handle_queue_capacity_full()
... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
node = self
output = ""
while node != None:
output += str(node.val)
output += " "
node = node.next
return output
| class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
node = self
output = ''
while node != None:
output += str(node.val)
output += ' '
node = node.next
return output |
#Unicode characters and strings
#1960s/1970s ---> we assumed one byte is one character and went it with
# a byte and character were assumed to be the same thing
#ASCII goes up to 127
print(ord('H'))
print(ord('e'))
print(ord('\n'))
print(ord('G'))
#UTF-16 - fixed length, two byes
#UTF-32 - fixed length, four... | print(ord('H'))
print(ord('e'))
print(ord('\n'))
print(ord('G')) |
"""
Various constants used
Unit abreviations are appended to the name, but powers are not
specified. For instance, the gravitational constant has units "Mpc^3
msun^-1 s^-2", but is called "G_const_Mpc_Msun_s".
Most of these numbers are from google calculator.
SHOULD MOVE TO ASTROPY.UNITS AT S... | """
Various constants used
Unit abreviations are appended to the name, but powers are not
specified. For instance, the gravitational constant has units "Mpc^3
msun^-1 s^-2", but is called "G_const_Mpc_Msun_s".
Most of these numbers are from google calculator.
SHOULD MOVE TO ASTROPY.UNITS AT S... |
description = 'MIRA2 monochromator'
group = 'lowlevel'
includes = ['base', 'mslit2', 'sample', 'alias_mono']
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(
co_m2tt = device('nicos.devices.entangle.Sensor',
visibility = (),
tangodevice = tango_base + 'mono2/m2tt_enc',
... | description = 'MIRA2 monochromator'
group = 'lowlevel'
includes = ['base', 'mslit2', 'sample', 'alias_mono']
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(co_m2tt=device('nicos.devices.entangle.Sensor', visibility=(), tangodevice=tango_base + 'mono2/m2tt_enc', unit='deg'), mo_m2tt=device('nicos.d... |
# Divided OF two number
while True:
a = int(input("Enter The Dividend Number : "))
b = int(input("Enter The Divisor Number : "))
if a > b:
quotient = int(a / b)
print("Quotirnt Number Of :", quotient)
else:
Quotient = int(b / a)
print("Quotirnt Number Of : 0.",... | while True:
a = int(input('Enter The Dividend Number : '))
b = int(input('Enter The Divisor Number : '))
if a > b:
quotient = int(a / b)
print('Quotirnt Number Of :', quotient)
else:
quotient = int(b / a)
print('Quotirnt Number Of : 0.', Quotient) |
IMPAR = []
PAR = []
for i in range(15):
X = int(input())
if X % 2 == 0:
PAR.append(X)
elif X % 2 != 0:
IMPAR.append(X)
if len(PAR) == 5:
Y = 0
for j in PAR:
print('par[{}] = {}'.format(Y,j))
Y += 1
PAR = []
if len(IMPAR) == 5:
Y... | impar = []
par = []
for i in range(15):
x = int(input())
if X % 2 == 0:
PAR.append(X)
elif X % 2 != 0:
IMPAR.append(X)
if len(PAR) == 5:
y = 0
for j in PAR:
print('par[{}] = {}'.format(Y, j))
y += 1
par = []
if len(IMPAR) == 5:
... |
# The MIT License
# Copyright (c) 2015 Tom Pollard
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge... | def compute_oasis(pd_dataframe):
"""
Takes Pandas DataFrame as an argument and computes Oxford Acute
Severity of Illness Score (OASIS) (http://oasisicu.com/)
The DataFrame should include only measurements taken over the first 24h
from admission. pd_dataframe should contain the following columns:
... |
class UserRepositoryDependencyMarker: # pragma: no cover
pass
class ProductRepositoryDependencyMarker: # pragma: no cover
pass
| class Userrepositorydependencymarker:
pass
class Productrepositorydependencymarker:
pass |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Option:
def __init__(self, name, number, y):
self.name=name
self.number=number
self.y=y
| class Option:
def __init__(self, name, number, y):
self.name = name
self.number = number
self.y = y |
# $Id: module_index.py 2790 2008-02-29 08:33:14Z cpbotha $
class emp_test:
kits = ['vtk_kit']
cats = ['Tests']
keywords = ['test', 'tests', 'testing']
help = \
"""Module to test DeVIDE extra-module-paths functionality.
"""
| class Emp_Test:
kits = ['vtk_kit']
cats = ['Tests']
keywords = ['test', 'tests', 'testing']
help = 'Module to test DeVIDE extra-module-paths functionality.\n ' |
'''
N = int(input())
notas100 = N//100
notas50 = (N-(notas100*100))//50
notas20 = (N-(notas100*100+notas50*50))//20
notas10 = (N-(notas100*100+notas50*50+notas20*20))//10
notas5 = (N-(notas100*100+notas50*50+notas20*20+notas10*10))//5
notas2 = (N-(notas100*100+notas50*50+notas20*20+notas10*10+notas5*5))//2
notas1 = (N-... | """
N = int(input())
notas100 = N//100
notas50 = (N-(notas100*100))//50
notas20 = (N-(notas100*100+notas50*50))//20
notas10 = (N-(notas100*100+notas50*50+notas20*20))//10
notas5 = (N-(notas100*100+notas50*50+notas20*20+notas10*10))//5
notas2 = (N-(notas100*100+notas50*50+notas20*20+notas10*10+notas5*5))//2
notas1 = (N-... |
# https://binarysearch.com/problems/Longest-Anagram-Subsequence
class Solution:
def solve(self, a, b):
letters = set(list(a)).intersection(set(list(b)))
length = 0
for i in letters:
length += min(a.count(i),b.count(i))
return length
| class Solution:
def solve(self, a, b):
letters = set(list(a)).intersection(set(list(b)))
length = 0
for i in letters:
length += min(a.count(i), b.count(i))
return length |
t = int(input())
while t > 0:
t -= 1
n,m,s = map(int, input().strip().split(' '))
k = (s+m-1)%n
if(k==0):
print (n)
else:
print (k) | t = int(input())
while t > 0:
t -= 1
(n, m, s) = map(int, input().strip().split(' '))
k = (s + m - 1) % n
if k == 0:
print(n)
else:
print(k) |
'''
Description : Input In Function By .format Method
Function Date : 14 Feb 2021
Function Author : Prasad Dangare
Input : Int
Output : Int
'''
# defination of function, use of .format method
def Addition(no1, no2):
ans = no1 + no2
return ans
def main():
... | """
Description : Input In Function By .format Method
Function Date : 14 Feb 2021
Function Author : Prasad Dangare
Input : Int
Output : Int
"""
def addition(no1, no2):
ans = no1 + no2
return ans
def main():
print('enter first number')
value1 = int(input())
print(... |
#cameraCoords syntax: [x1 (oben links),y1,x2 (unten rechts),y2,zoomLevel]
def moveCamera(cameraCoords, move,worldSize):
if cameraCoords[0]+move[0] <= 1 and move[0] < 0:
cameraCoords[0] -= cameraCoords[0]%1
cameraCoords[2] -= cameraCoords[2]%1
while cameraCoords[0] > 1:
ca... | def move_camera(cameraCoords, move, worldSize):
if cameraCoords[0] + move[0] <= 1 and move[0] < 0:
cameraCoords[0] -= cameraCoords[0] % 1
cameraCoords[2] -= cameraCoords[2] % 1
while cameraCoords[0] > 1:
cameraCoords[0] -= 1
cameraCoords[2] -= 1
elif cameraCoords[... |
def display_board( state ):
print("-------------")
print("| %i | %i | %i |" % (state[0], state[1], state[2]))
print("-------------")
print("| %i | %i | %i |" % (state[3], state[4], state[5]))
print("-------------")
print("| %i | %i | %i |" % (state[6], state[7], state[8]))
print("-------------")
def move_up(sta... | def display_board(state):
print('-------------')
print('| %i | %i | %i |' % (state[0], state[1], state[2]))
print('-------------')
print('| %i | %i | %i |' % (state[3], state[4], state[5]))
print('-------------')
print('| %i | %i | %i |' % (state[6], state[7], state[8]))
print('-------------... |
a = input ("Digite algo")
print(a.isalpha())
print(a.isalnum())
print(a.isascii())
print(a.isdecimal())
print(a.isdigit())
print(a.isidentifier())
print(a.islower())
| a = input('Digite algo')
print(a.isalpha())
print(a.isalnum())
print(a.isascii())
print(a.isdecimal())
print(a.isdigit())
print(a.isidentifier())
print(a.islower()) |
class Node:
def __init__(self, val=0):
self.value = val
self.next = None
class LinkList:
c = 10
def __init__(self, *args):
self.val = (*args,)
self.head = self.__constructLinklist()
#self.printLinklist(self.head)
# self.pre = self.revserlinklist()
#... | class Node:
def __init__(self, val=0):
self.value = val
self.next = None
class Linklist:
c = 10
def __init__(self, *args):
self.val = (*args,)
self.head = self.__constructLinklist()
def print_linklist(self, head):
while head is not None:
print(head... |
"""
Question 59 :
Print a unicode string "hello world".
Hints : Use u'string format to define unicode string
"""
# Solution :
unicode_string = u"hello world!"
print(unicode_string)
"""
Output :
hello world
""" | """
Question 59 :
Print a unicode string "hello world".
Hints : Use u'string format to define unicode string
"""
unicode_string = u'hello world!'
print(unicode_string)
'\nOutput : \n hello world\n' |
"""
PASSENGERS
"""
numPassengers = 4084
passenger_arriving = (
(4, 8, 15, 6, 6, 0, 9, 7, 7, 4, 1, 0), # 0
(4, 11, 5, 5, 2, 0, 7, 10, 6, 8, 2, 0), # 1
(11, 10, 4, 1, 1, 0, 5, 9, 13, 5, 1, 0), # 2
(5, 5, 9, 5, 1, 0, 6, 8, 7, 3, 2, 0), # 3
(5, 10, 8, 7, 1, 0, 8, 16, 10, 3, 3, 0), # 4
(6, 12, 7, 1, 4, 0, 10, ... | """
PASSENGERS
"""
num_passengers = 4084
passenger_arriving = ((4, 8, 15, 6, 6, 0, 9, 7, 7, 4, 1, 0), (4, 11, 5, 5, 2, 0, 7, 10, 6, 8, 2, 0), (11, 10, 4, 1, 1, 0, 5, 9, 13, 5, 1, 0), (5, 5, 9, 5, 1, 0, 6, 8, 7, 3, 2, 0), (5, 10, 8, 7, 1, 0, 8, 16, 10, 3, 3, 0), (6, 12, 7, 1, 4, 0, 10, 6, 6, 5, 4, 0), (9, 12, 6, 2, 5, 0... |
'''
__program__: Taking user input from the user
__author__: Abhinav Anil
__submittedTo__: dataSciTech
__email__: dataascii@gmail.com
__instagram__: @data.sci_
'''
#Taking the user name, PAN card number to validate the information for the user details.
while(1):
name = input("\n Enter your name : ")
if name.... | """
__program__: Taking user input from the user
__author__: Abhinav Anil
__submittedTo__: dataSciTech
__email__: dataascii@gmail.com
__instagram__: @data.sci_
"""
while 1:
name = input('\n Enter your name : ')
if name.isalpha() == False:
print('Invalid Name, Sorry you cannot proceed.')
break
... |
peoples = {
'first_name': 'le',
'last_name': 'xiaoyuan',
'age': 21,
'city': 'dawu'
}
print(peoples['first_name'])
print(peoples['last_name'])
print(peoples['age'])
print(peoples['city'])
for people in peoples.values():
print(people)
lucky_number = {
'lexiaoyuan': 6,
'benjamin': 66,
'l... | peoples = {'first_name': 'le', 'last_name': 'xiaoyuan', 'age': 21, 'city': 'dawu'}
print(peoples['first_name'])
print(peoples['last_name'])
print(peoples['age'])
print(peoples['city'])
for people in peoples.values():
print(people)
lucky_number = {'lexiaoyuan': 6, 'benjamin': 66, 'lexiaoyuanbeta': 666, 'yege': 6666,... |
# Problem! you teach children about how to calculate the area and perimeter of the square
# and you will solve 20 questions about the way to find area and perimeter. to teach them.
# but that will consume the time, so you want to write a program to reduce the time
# when calculating all 20 quests.
# Now try to solve it... | def calc(x):
side_length = x
print(f'area = {sideLength ** 2}')
print(f'perimeter = {sideLength * 4}')
calc(int(input()))
calcs = lambda x: (x ** 2, x * 4)
(c1, c2) = calcs(int(input()))
print(f'area = {c1}\nperimeter = {c2}')
def calc2(x):
return (x ** 2, x * 4)
(a, b) = calcs(int(input()))
print(str(... |
class PullRequest:
"""
This class models a pull-request.
"""
@staticmethod
def __initialize_files(files_string):
return files_string.split("|")
def __init__(self, data):
self.pr_id = data[0]
self.pull_number = data[1]
self.requester_login = data[2]
self.... | class Pullrequest:
"""
This class models a pull-request.
"""
@staticmethod
def __initialize_files(files_string):
return files_string.split('|')
def __init__(self, data):
self.pr_id = data[0]
self.pull_number = data[1]
self.requester_login = data[2]
self.... |
# *** these filters do NOT see ping messages, nor do routers see them ***
# *** global imports are NOT accessible, do imports in __init__ and bind them to an attribute ***
class Filters(Base):
def __init__(self, logger):
# init parent class
super().__init__(logger)
# some... | class Filters(Base):
def __init__(self, logger):
super().__init__(logger)
self.random = __import__('random')
self.base64 = __import__('base64')
self._thread = __import__('_thread')
self.time = __import__('time')
self.started = 0
self.data_received = {}
... |
class HwndSourceParameters(object):
"""
Contains the parameters that are used to create an System.Windows.Interop.HwndSource object using the System.Windows.Interop.HwndSource.#ctor(System.Windows.Interop.HwndSourceParameters) constructor.
HwndSourceParameters(name: str)
HwndSourceParameters(name: str,wid... | class Hwndsourceparameters(object):
"""
Contains the parameters that are used to create an System.Windows.Interop.HwndSource object using the System.Windows.Interop.HwndSource.#ctor(System.Windows.Interop.HwndSourceParameters) constructor.
HwndSourceParameters(name: str)
HwndSourceParameters(name: str,width... |
#-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softwa... | """
Python module 'pydoc' causes the inclusion of Tcl/Tk library even in case
of simple hello_world script. Most of the we do not want this behavior.
This hook just removes this implicit dependency on Tcl/Tk.
"""
def hook(mod):
for (i, m) in enumerate(mod.pyinstaller_imports):
if m[0] == 'Tkinter':
... |
number = input("Enter a series of number, using separator you like: ")
separator = ""
for char in number:
if not char.isnumeric():
separator = separator + char
print(separator)
str = 0;
sum = 0
for char in number:
if char not in separator:
str = str * 10 + int(char)
if char == number[... | number = input('Enter a series of number, using separator you like: ')
separator = ''
for char in number:
if not char.isnumeric():
separator = separator + char
print(separator)
str = 0
sum = 0
for char in number:
if char not in separator:
str = str * 10 + int(char)
if char == number[len(... |
{
"includes": [
"../common.gypi"
],
"targets": [
{
"target_name": "libgdal_ogr_pgdump_frmt",
"type": "static_library",
"sources": [
"../gdal/ogr/ogrsf_frmts/pgdump/ogrpgdumplayer.cpp",
"../gdal/ogr/ogrsf_frmts/pgdump/ogrpgdumpdatasource.cpp",
"../gdal/ogr/ogrsf_frmts/pgdump/ogrpgdumpdriver.c... | {'includes': ['../common.gypi'], 'targets': [{'target_name': 'libgdal_ogr_pgdump_frmt', 'type': 'static_library', 'sources': ['../gdal/ogr/ogrsf_frmts/pgdump/ogrpgdumplayer.cpp', '../gdal/ogr/ogrsf_frmts/pgdump/ogrpgdumpdatasource.cpp', '../gdal/ogr/ogrsf_frmts/pgdump/ogrpgdumpdriver.cpp'], 'include_dirs': ['../gdal/og... |
class Human(object):
def __init__(self, mark, io):
self.mark = mark
self.io = io
def sanitize_user_input(self, user_input):
try:
sanitized_input = int(user_input)
except TypeError:
sanitized_input = 0
except ValueError:
sanitized_inpu... | class Human(object):
def __init__(self, mark, io):
self.mark = mark
self.io = io
def sanitize_user_input(self, user_input):
try:
sanitized_input = int(user_input)
except TypeError:
sanitized_input = 0
except ValueError:
sanitized_inpu... |
def razbi_stevilo(n, st):
s = []
st = str(st)
while len(st) > n:
stevilo = st[:n]
s.append(stevilo)
st = st[1:]
return s #seznam 13 mestnih steil podanih v nizu
def razbi_stevke(n):
sez_stevk = []
for stevka in n:
sez_stevk.append(int(stevka))
sez_stevk.sort... | def razbi_stevilo(n, st):
s = []
st = str(st)
while len(st) > n:
stevilo = st[:n]
s.append(stevilo)
st = st[1:]
return s
def razbi_stevke(n):
sez_stevk = []
for stevka in n:
sez_stevk.append(int(stevka))
sez_stevk.sort()
return sez_stevk
def max_zmnozek(... |
class Solution:
def longestMountain(self, A: List[int]) -> int:
'''
T: O(n) and S: O(1)
'''
if len(A) < 3: return 0
maxLen = 0
for i in range(1, len(A)-1):
left, right = i - 1, i + 1
if (A[left] < A[i]) and (A[i] > A[right]):
... | class Solution:
def longest_mountain(self, A: List[int]) -> int:
"""
T: O(n) and S: O(1)
"""
if len(A) < 3:
return 0
max_len = 0
for i in range(1, len(A) - 1):
(left, right) = (i - 1, i + 1)
if A[left] < A[i] and A[i] > A[right]:
... |
# Loan repayment calculation service
# This is the program calculating the loan repayment amount for clients.
#
# Input parameters:
# principal(p) : Only integers equal or greater than one million are allowed
# years(y) : Only integers equal or greater than one are allowed
# annual interest rate(r) : Only floating poin... | print('Welcome to loan repayment calculation service')
p = int(input('How much is the principal? (We only count over one million won.) '))
y = int(input('How many years is the repayment period? '))
r = float(input('What percent is the interest rate? '))
d = (1 + r / 100) ** y * p * (r / 100) // ((1 + r / 100) ** y - 1)... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 12:58:44 2020
@author: SELICLO1
"""
def HammingDistance(a,b):
mm = 0
for i,s in enumerate(a):
if s != b[i]: mm+= 1
return mm
a = 'GTCTGGGCCGTGCGGACTTGTTGCGGATGATACAAGGGCTTCACTACGTCGAAGTAAGTTACCAATTATACAAGCTACCGGTGTAGAATGGTGAGTAGGTCCGCTTATAGCCCGCGC... | """
Created on Wed Aug 26 12:58:44 2020
@author: SELICLO1
"""
def hamming_distance(a, b):
mm = 0
for (i, s) in enumerate(a):
if s != b[i]:
mm += 1
return mm
a = 'GTCTGGGCCGTGCGGACTTGTTGCGGATGATACAAGGGCTTCACTACGTCGAAGTAAGTTACCAATTATACAAGCTACCGGTGTAGAATGGTGAGTAGGTCCGCTTATAGCCCGCGCGGTGTAC... |
a = int(input("Enter the first no : "))
b = int(input("Enter the second no : "))
c = a+b
print("sum of",a,'+',b,'=',c)
print("The first no is: %d and second number is: %d and the sum is: %d"%(a,b,c))
print("%d + %d = %d"%(a,b,c))
print("%-10d + %-10d = %-10d"%(a,b,c))
print("%-10f + %-10f = %-10f"%(a,b,c))
prin... | a = int(input('Enter the first no : '))
b = int(input('Enter the second no : '))
c = a + b
print('sum of', a, '+', b, '=', c)
print('The first no is: %d and second number is: %d and the sum is: %d' % (a, b, c))
print('%d + %d = %d' % (a, b, c))
print('%-10d + %-10d = %-10d' % (a, b, c))
print('%-10f + %-10f = %-10f' % ... |
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def kth_to_last(k, linked_list):
pointer1, pointer2 = linked_list, linked_list
for _ in range(k):
if not pointer1:
return None
pointer1 = pointer1.next
while pointer1:... | class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def kth_to_last(k, linked_list):
(pointer1, pointer2) = (linked_list, linked_list)
for _ in range(k):
if not pointer1:
return None
pointer1 = pointer1.next
while point... |
print("-- Strings -- ")
print()
mystring = "hello"
myfloat = 10.0
myint = 20
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)
print()
nome = 'Teste... | print('-- Strings -- ')
print()
mystring = 'hello'
myfloat = 10.0
myint = 20
if mystring == 'hello':
print('String: %s' % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print('Float: %f' % myfloat)
if isinstance(myint, int) and myint == 20:
print('Integer: %d' % myint)
print()
nome = 'Teste'
i... |
def General(project):
feature_vectors = get_featrures(projects)
h_clusters = BIRCH(projects,feature_vectors)
for level in h_clusters.levels:
if level.depth == h_clusters.max_depth:
for cluster in level.clusters:
level.cluster.bell = bellwether(cluster.projects)
el... | def general(project):
feature_vectors = get_featrures(projects)
h_clusters = birch(projects, feature_vectors)
for level in h_clusters.levels:
if level.depth == h_clusters.max_depth:
for cluster in level.clusters:
level.cluster.bell = bellwether(cluster.projects)
e... |
"""
LC89. Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation... | """
LC89. Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation... |
# Sudoku Solver: https://leetcode.com/problems/sudoku-solver/
# Write a program to solve a Sudoku puzzle by filling the empty cells.
# A sudoku solution must satisfy all of the following rules:
# Each of the digits 1-9 must occur exactly once in each row.
# Each of the digits 1-9 must occur exactly once in e... | class Solution:
def solve_sudoku(self, board) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def can_add_val(value, r, c):
return value not in row[r] and value not in col[c] and (value not in sqr[sqr_index(r, c)])
def add_to_board(value... |
abi = """[
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "_hashSender",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "_hashId",
"type": "uint256"
},
{
"indexed": false,
... | abi = '[\n\t{\n\t\t"anonymous": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"indexed": true,\n\t\t\t\t"internalType": "address",\n\t\t\t\t"name": "_hashSender",\n\t\t\t\t"type": "address"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "uint256",\n\t\t\t\t"name": "_hashId",\n\t\t\t\t"type": "uint25... |
# import contact: click on chart to draw a contact that gets pinged by sonar
colors = {'GRN':color(51, 255, 0), 'RED':color(193, 49, 36), 'BLK':color(10)}
def setup():
size(480, 480)
background(colors['BLK'])
fill(colors['RED'])
ellipse(240, 240, 430, 430)
fill(10)
ellipse(240, 240, 420, 420)
... | colors = {'GRN': color(51, 255, 0), 'RED': color(193, 49, 36), 'BLK': color(10)}
def setup():
size(480, 480)
background(colors['BLK'])
fill(colors['RED'])
ellipse(240, 240, 430, 430)
fill(10)
ellipse(240, 240, 420, 420)
def draw():
stroke(colors['GRN'])
if mousePressed:
fill(co... |
def debug_policy_plot():
qq_right = []
x_vec = np.arange(vagent.max_q[0])
for xx in x_vec:
vagent.q[0] = xx
vsensor.update(vscene,vagent)
vobservation = local_observer(vsensor,vagent) #todo: generalize
qq_right.append(RL.compute_q_eval(vobservation.reshape([1... | def debug_policy_plot():
qq_right = []
x_vec = np.arange(vagent.max_q[0])
for xx in x_vec:
vagent.q[0] = xx
vsensor.update(vscene, vagent)
vobservation = local_observer(vsensor, vagent)
qq_right.append(RL.compute_q_eval(vobservation.reshape([1, -1])))
qq_right = np.reshap... |
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
sum = 0
for i in shift:
if i[0] == 0:
sum += i[1]
else:
sum -= i[1]
sum = sum % len(s)
return s[sum:]+s[:sum]
| class Solution:
def string_shift(self, s: str, shift: List[List[int]]) -> str:
sum = 0
for i in shift:
if i[0] == 0:
sum += i[1]
else:
sum -= i[1]
sum = sum % len(s)
return s[sum:] + s[:sum] |
"""
netparse.table
This module provides the necessary abstraction to take a TABLE pattern
output and generate an accurate datastructure based off it.
For further reading, please check out this article:
https://pyability.com/the-curse-of-the-cli/
"""
class ParseTable:
def __init__(self, unstructured_data, patte... | """
netparse.table
This module provides the necessary abstraction to take a TABLE pattern
output and generate an accurate datastructure based off it.
For further reading, please check out this article:
https://pyability.com/the-curse-of-the-cli/
"""
class Parsetable:
def __init__(self, unstructured_data, patte... |
# Based on MicroPython config option, comparison of str and bytes
# or vice versa may issue a runtime warning. On CPython, if run as
# "python3 -b", only comparison of str to bytes issues a warning,
# not the other way around (while exactly comparison of bytes to
# str would be the most common error, as in sock.recv(3)... | if '123' == b'123' or b'123' == '123':
print('FAIL')
raise SystemExit
print('PASS') |
class Solution:
def toGoatLatin(self, S: str) -> str:
words = S.split()
res = []
for i, w in enumerate(words):
if w[0].lower() not in "aeiou":
w = w[1:] + w[0]
w += "ma" + ("a" * (i + 1))
res.append(w)
return ' '.join(res)
if __n... | class Solution:
def to_goat_latin(self, S: str) -> str:
words = S.split()
res = []
for (i, w) in enumerate(words):
if w[0].lower() not in 'aeiou':
w = w[1:] + w[0]
w += 'ma' + 'a' * (i + 1)
res.append(w)
return ' '.join(res)
if __n... |
# the interface
# class, or the interface
# data type
# interface data types
# are inspired from
# the typescript language
# example
# f = Interface(types)
# f.create(data)
class InterfaceObject():
def __init__(self, object_info):
# the passed in values
# to create a new object
... | class Interfaceobject:
def __init__(self, object_info):
self.values = object_info
def get_item(self, property_):
if property_ in self.values:
return self.values[property_]
else:
raise key_error(f'Cannot find {property_}')
def set_item(self, property_, value... |
"""
Standard disk mounted on a CIM_ComputerSystem.
"""
def EntityOntology():
return (["Name"],)
| """
Standard disk mounted on a CIM_ComputerSystem.
"""
def entity_ontology():
return (['Name'],) |
def rotflip():
yield "rot1"
yield "rot2"
yield "rot3"
yield "rot4"
yield "flip"
yield "rot1"
yield "rot2"
yield "rot3"
yield "rot4"
raise ValueError("aaaaa")
i = 0
#for i,a in enumerate(rotflip()):
a_gen = rotflip()
while True:
a = a_gen.__next__()
print(a)
i += 1
... | def rotflip():
yield 'rot1'
yield 'rot2'
yield 'rot3'
yield 'rot4'
yield 'flip'
yield 'rot1'
yield 'rot2'
yield 'rot3'
yield 'rot4'
raise value_error('aaaaa')
i = 0
a_gen = rotflip()
while True:
a = a_gen.__next__()
print(a)
i += 1
if i == 6:
break |
marks = {}
for _ in range(int(input())):
line = input().split()
marks[line[0]] = sum(map(float, line[1:])) / 3
print('%.2f' % marks[input()]) | marks = {}
for _ in range(int(input())):
line = input().split()
marks[line[0]] = sum(map(float, line[1:])) / 3
print('%.2f' % marks[input()]) |
# A script to recursively find the greatest common divisor of two numbers
def greatest_divisor(first, second):
assert first == int(first) and second == int(second) and first != 0 and second != 0, 'Numbers provided must be nonzero integers'
if first < 0:
first = -first
if second < 0:
secon... | def greatest_divisor(first, second):
assert first == int(first) and second == int(second) and (first != 0) and (second != 0), 'Numbers provided must be nonzero integers'
if first < 0:
first = -first
if second < 0:
second = -second
if first >= second:
return gcd_ordered(first, sec... |
def main():
card_number = input("Enter credit card number: ")
print_card_value(card_number)
def print_card_value(card_number):
if check_for_sum(card_number) == False:
print("INVALID")
elif check_for_amex(card_number) == True:
print("AMEX")
elif check_for_master(card_number) == T... | def main():
card_number = input('Enter credit card number: ')
print_card_value(card_number)
def print_card_value(card_number):
if check_for_sum(card_number) == False:
print('INVALID')
elif check_for_amex(card_number) == True:
print('AMEX')
elif check_for_master(card_number) == True:... |
best_bpsp = float("inf")
n_feats = 64
scale = 3
resblocks = 3
K = 10
plot = ""
log_likelihood = True
collect_probs = False
| best_bpsp = float('inf')
n_feats = 64
scale = 3
resblocks = 3
k = 10
plot = ''
log_likelihood = True
collect_probs = False |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
1->2->3->4
... | class Solution:
def reorder_list(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
1->2->3->4
1->4->2->3
"""
if head == None:
return
stack = []
node = head
length = 0
... |
def countArrangement(n: int) -> int:
options = [[] * n for _ in range(n)]
for i in range(1, n + 1):
for j in range(1, i):
if i % j == 0:
options[i-1].append(j)
for j in range(i, n+1, i):
options[i-1].append(j)
options.sort(key=len)
taken ... | def count_arrangement(n: int) -> int:
options = [[] * n for _ in range(n)]
for i in range(1, n + 1):
for j in range(1, i):
if i % j == 0:
options[i - 1].append(j)
for j in range(i, n + 1, i):
options[i - 1].append(j)
options.sort(key=len)
taken = s... |
S = 'I want that Farm House to be in my name, comprende? Also, I want Chocolates.'
D = {}
#SS = S.split()
for item in S:
if item in D:
D[item] = D[item] + 1
else:
D[item] = 1
print(D)
| s = 'I want that Farm House to be in my name, comprende? Also, I want Chocolates.'
d = {}
for item in S:
if item in D:
D[item] = D[item] + 1
else:
D[item] = 1
print(D) |
class TestSessOverallResults:
def __init__(self):
self._recall = -1.
self._precision = -1.
self._f_measure = -1.
def __str__(self):
rez = '\nRecall : ' + str(self.recall)
rez += '\nPrecision : ' + str(self.precision)
rez += '\nF-measure : ' + str... | class Testsessoverallresults:
def __init__(self):
self._recall = -1.0
self._precision = -1.0
self._f_measure = -1.0
def __str__(self):
rez = '\nRecall : ' + str(self.recall)
rez += '\nPrecision : ' + str(self.precision)
rez += '\nF-measure : ' + str(... |
def dfs(node,parent):
for child in graph[node]:
if child!=parent:
dfs(child,node)
taken,nottaken=1,0
for neigh in graph[node]:
if neigh!=parent:
taken+=dp[neigh][0]
nottaken+=dp[neigh][1]
dp[node][1]=min(taken,nottaken)
dp[node][0]=nottaken
if __... | def dfs(node, parent):
for child in graph[node]:
if child != parent:
dfs(child, node)
(taken, nottaken) = (1, 0)
for neigh in graph[node]:
if neigh != parent:
taken += dp[neigh][0]
nottaken += dp[neigh][1]
dp[node][1] = min(taken, nottaken)
dp[node... |
# Application condition
waitFor.id == max_used_id and not cur_node_is_processed
# Reaction
wait_for_touch_sensor_code = "while (!ecrobot_get_touch_sensor(NXT_PORT_S" + waitFor.Port + ")) {}\n"
code.append([wait_for_touch_sensor_code])
id_to_pos_in_code[waitFor.id] = len(code) - 1
cur_node_is_processed = True
| waitFor.id == max_used_id and (not cur_node_is_processed)
wait_for_touch_sensor_code = 'while (!ecrobot_get_touch_sensor(NXT_PORT_S' + waitFor.Port + ')) {}\n'
code.append([wait_for_touch_sensor_code])
id_to_pos_in_code[waitFor.id] = len(code) - 1
cur_node_is_processed = True |
print('Event')
#-------------Lorem
for i in [5,4,5]:
print(i) | print('Event')
for i in [5, 4, 5]:
print(i) |
# 4-6. Odd Numbers: Use the third argument of the range() function to make a list
# of the odd numbers from 1 to 20. Use a for loop to print each number.
for i in range(1,21):
if i%2!=0:
print(i) | for i in range(1, 21):
if i % 2 != 0:
print(i) |
class ResponseObject():
def __init__(self, status=500, msg="Unknown Error", data=None):
self.status = status
self.msg = msg
if data:
self.data = data
else:
self.data = {}
self.response = { "status" : self.status, "msg" : self.msg, "data" : self.data ... | class Responseobject:
def __init__(self, status=500, msg='Unknown Error', data=None):
self.status = status
self.msg = msg
if data:
self.data = data
else:
self.data = {}
self.response = {'status': self.status, 'msg': self.msg, 'data': self.data} |
class Settings:
PROJECT_TITLE: str = "Book store"
PROJECT_VERSION: str = "0.1.1"
settings = Settings()
| class Settings:
project_title: str = 'Book store'
project_version: str = '0.1.1'
settings = settings() |
__all__ = [
'api_exception',
'update_webhook_400_response_exception',
'retrieve_webhook_400_response_exception',
'create_webhook_400_response_exception',
] | __all__ = ['api_exception', 'update_webhook_400_response_exception', 'retrieve_webhook_400_response_exception', 'create_webhook_400_response_exception'] |
"""
An example of a procedural style FizzBuzz program.
For coding interviews, this is okay, but in general,
I do NOT recommend this approach to coding as it is
nearly impossible to test its correctness.
"""
for x in range(1, 101):
if x % 15 is 0:
print("FizzBuzz")
elif x % 3 is 0:
print("Fizz")
el... | """
An example of a procedural style FizzBuzz program.
For coding interviews, this is okay, but in general,
I do NOT recommend this approach to coding as it is
nearly impossible to test its correctness.
"""
for x in range(1, 101):
if x % 15 is 0:
print('FizzBuzz')
elif x % 3 is 0:
print(... |
# simple calculator
# This function adds two numbers
def add(x, y):
return float(x) + float(y)
# This function subtracts two numbers
def subtract(x, y):
return float(x) - float(y)
# This function multiplies two numbers
def multiply(x, y):
return float(x) * float(y)
# This function divides two numbers
de... | def add(x, y):
return float(x) + float(y)
def subtract(x, y):
return float(x) - float(y)
def multiply(x, y):
return float(x) * float(y)
def divide(x, y):
try:
return float(x) / float(y)
except ValueError:
return 0
except ZeroDivisionError:
return 0
finally:
... |
class Stop:
"""
Represents each one of the physical stops in a GTFS dataset (from https://developers.google.com/transit/gtfs/reference/)
Fields
______
* **id** `(stop_id)` **Required** - The stop_id field contains an ID that uniquely identifies a stop, station, or station entrance. Multiple routes... | class Stop:
"""
Represents each one of the physical stops in a GTFS dataset (from https://developers.google.com/transit/gtfs/reference/)
Fields
______
* **id** `(stop_id)` **Required** - The stop_id field contains an ID that uniquely identifies a stop, station, or station entrance. Multiple routes... |
DEFAULT_MOD = 10 ** 9 + 7
def mod_permutation(n, k, mod=DEFAULT_MOD):
if k >= mod:
return 0
ret = 1
for i in range(n, n - k, -1):
ret = (ret * i) % mod
return ret
def mod_factorial(n, mod=DEFAULT_MOD):
if n >= mod:
return 0
else:
return mod_permutation(n, n, m... | default_mod = 10 ** 9 + 7
def mod_permutation(n, k, mod=DEFAULT_MOD):
if k >= mod:
return 0
ret = 1
for i in range(n, n - k, -1):
ret = ret * i % mod
return ret
def mod_factorial(n, mod=DEFAULT_MOD):
if n >= mod:
return 0
else:
return mod_permutation(n, n, mod)
... |
# -*- coding: utf-8 -*-
n = int(input("Enter one number: "))
if n < 0:
print("please enter a positive ")
else:
while n != 1:
print(int(n))
if n % 2 != 0:
n = 3 * n + 1
else:
n /= 2
print("result ", int(n))
| n = int(input('Enter one number: '))
if n < 0:
print('please enter a positive ')
else:
while n != 1:
print(int(n))
if n % 2 != 0:
n = 3 * n + 1
else:
n /= 2
print('result ', int(n)) |
"""
Modified from https://github.com/facebookresearch/fvcore
"""
__all__ = ["Registry"]
class Registry:
"""A registry providing name -> object mapping, to support
custom modules.
To create a registry (e.g. a backbone registry):
.. code-block:: python
BACKBONE_REGISTRY = Registry('BACKBONE')... | """
Modified from https://github.com/facebookresearch/fvcore
"""
__all__ = ['Registry']
class Registry:
"""A registry providing name -> object mapping, to support
custom modules.
To create a registry (e.g. a backbone registry):
.. code-block:: python
BACKBONE_REGISTRY = Registry('BACKBONE')
... |
"""The protocol_*.py files in this package are based on PySerial's file
test/handlers/protocol_test.py, modified for different behaviors. The call
serial.serial_for_url("XYZ://") looks for a class Serial in a file named protocol_XYZ.py in this
package (i.e. directory).
This package init file will be loaded as part of... | """The protocol_*.py files in this package are based on PySerial's file
test/handlers/protocol_test.py, modified for different behaviors. The call
serial.serial_for_url("XYZ://") looks for a class Serial in a file named protocol_XYZ.py in this
package (i.e. directory).
This package init file will be loaded as part of... |
def create_authority_hints(default_hints, trust_chains):
"""
:param default_hints: The authority hints provided to the entity at startup
:param trust_chains: A list of TrustChain instances
:return: An authority_hints dictionary
"""
intermediates = {trust_chain.iss_path[1] for trust_chain in tr... | def create_authority_hints(default_hints, trust_chains):
"""
:param default_hints: The authority hints provided to the entity at startup
:param trust_chains: A list of TrustChain instances
:return: An authority_hints dictionary
"""
intermediates = {trust_chain.iss_path[1] for trust_chain in tru... |
{"query": {"function_score": {"query": {
"bool": {"should": [{"multi_match": {"query": "python", "fields": ["nickname^2", "username^4"]}}],
"filter": {"range": {"follower_count": {"gte": "50000", "lte": "100000"}}}}},
"field_value_factor": {"field": "follower_count", "modifier": "log1p", "missing":... | {'query': {'function_score': {'query': {'bool': {'should': [{'multi_match': {'query': 'python', 'fields': ['nickname^2', 'username^4']}}], 'filter': {'range': {'follower_count': {'gte': '50000', 'lte': '100000'}}}}}, 'field_value_factor': {'field': 'follower_count', 'modifier': 'log1p', 'missing': 0, 'factor': 1}, 'boo... |
def restart():
prompt = input("Type [y] to play again or any other key to quit. ")
if prompt.lower() == "y":
return True
else:
return False
| def restart():
prompt = input('Type [y] to play again or any other key to quit. ')
if prompt.lower() == 'y':
return True
else:
return False |
#!/usr/bin/env python3
try:
checksum = 0
while True:
numbers = [int(n) for n in input().split()]
checksum += max(numbers) - min(numbers)
except EOFError:
print(checksum)
| try:
checksum = 0
while True:
numbers = [int(n) for n in input().split()]
checksum += max(numbers) - min(numbers)
except EOFError:
print(checksum) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.