content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Config:
PROXY_WEBPAGE = "https://free-proxy-list.net/"
TESTING_URL = "https://google.com"
REDIS_CONFIG = {
"host": "redis",
"port": "6379",
"db": 0
}
REDIS_KEY = "proxies"
MAX_WORKERS = 50
NUMBER_OF_PROXIES = 50
RSS_FEEDS = {
"en": [
... | class Config:
proxy_webpage = 'https://free-proxy-list.net/'
testing_url = 'https://google.com'
redis_config = {'host': 'redis', 'port': '6379', 'db': 0}
redis_key = 'proxies'
max_workers = 50
number_of_proxies = 50
rss_feeds = {'en': ['https://www.goal.com/feeds/en/news', 'https://www.eyefo... |
# This file describes some constants which stay the same in every testing environment
# Total number of fish
N_FISH = 70
# Total number of fish species
N_SPECIES = 7
# Total number of time steps per environment
N_STEPS = 180
# Number of possible emissions, i.e. fish movements
# (all emissions are represented with ... | n_fish = 70
n_species = 7
n_steps = 180
n_emissions = 8
step_time_threshold = 5 |
def print_idp(file_name: str, vocabulary_strings: list, theory_strings: list, structure_strings: list) -> None:
"""Takes all contents of vocab and theory as list of strings and prints it as IDP code in file_name
:param file_name: Name of output file
:param vocabulary_strings: list of strings, with every str... | def print_idp(file_name: str, vocabulary_strings: list, theory_strings: list, structure_strings: list) -> None:
"""Takes all contents of vocab and theory as list of strings and prints it as IDP code in file_name
:param file_name: Name of output file
:param vocabulary_strings: list of strings, with every str... |
"""
* Setup and Draw.
*
* The code inside the draw() function runs continuously
* from top to bottom until the program is stopped.
"""
y = 100
def setup():
"""
The statements in the setup() function
execute once when the program begins
"""
size(640, 360) # Size must be the first statement
... | """
* Setup and Draw.
*
* The code inside the draw() function runs continuously
* from top to bottom until the program is stopped.
"""
y = 100
def setup():
"""
The statements in the setup() function
execute once when the program begins
"""
size(640, 360)
stroke(255)
frame_rate(30)
def... |
{
"name": "Custom Apps",
"summary": """Simplify Apps Interface""",
"images": [],
"vesion": "12.0.1.0.0",
"application": False,
"author": "IT-Projects LLC, Dinar Gabbasov",
"support": "apps@itpp.dev",
"website": "https://twitter.com/gabbasov_dinar",
"category": "Access",
"license"... | {'name': 'Custom Apps', 'summary': 'Simplify Apps Interface', 'images': [], 'vesion': '12.0.1.0.0', 'application': False, 'author': 'IT-Projects LLC, Dinar Gabbasov', 'support': 'apps@itpp.dev', 'website': 'https://twitter.com/gabbasov_dinar', 'category': 'Access', 'license': 'Other OSI approved licence', 'depends': ['... |
class Solution:
def getLucky(self, s: str, k: int) -> int:
nums = ''
for char in s:
nums += str(ord(char) - ord('a') + 1)
for i in range(k):
nums = str(sum((int(c) for c in nums)))
return nums | class Solution:
def get_lucky(self, s: str, k: int) -> int:
nums = ''
for char in s:
nums += str(ord(char) - ord('a') + 1)
for i in range(k):
nums = str(sum((int(c) for c in nums)))
return nums |
#from sec.core.models import Meeting
"""
import datetime
class GeneralInfo(models.Model):
id = models.IntegerField(primary_key=True)
info_name = models.CharField(max_length=150, blank=True)
info_text = models.TextField(blank=True)
info_header = models.CharField(max_length=765, blank=True)
class Met... | """
import datetime
class GeneralInfo(models.Model):
id = models.IntegerField(primary_key=True)
info_name = models.CharField(max_length=150, blank=True)
info_text = models.TextField(blank=True)
info_header = models.CharField(max_length=765, blank=True)
class Meta:
db_table = u'general_info'... |
keys = ['red', 'green', 'blue']
values = ['#FF0000','#008000', '#0000FF']
color_dictionary = dict(zip(keys, values))
print(color_dictionary)
| keys = ['red', 'green', 'blue']
values = ['#FF0000', '#008000', '#0000FF']
color_dictionary = dict(zip(keys, values))
print(color_dictionary) |
#!/bin/python
# list
lauguage = 'Python'
lst = list(lauguage)
print(type(lst))
print(lst)
print("-------------------------------")
# [i for i in iterable if expression]
lst = [i for i in lauguage]
print(type(lst))
print(lst)
print("-------------------------------")
add_two_nums = lambda a, b: a + b
print(add_two_num... | lauguage = 'Python'
lst = list(lauguage)
print(type(lst))
print(lst)
print('-------------------------------')
lst = [i for i in lauguage]
print(type(lst))
print(lst)
print('-------------------------------')
add_two_nums = lambda a, b: a + b
print(add_two_nums(2, 3)) |
class Local(object):
__slots__ = ("__storage__", "__ident_func__")
def __init__(self):
object.__setattr__(self, "__storage__", {})
object.__setattr__(self, "__ident_func__", get_ident)
def __iter__(self):
return iter(self.__storage__.items())
def __call__(self, proxy):
"""Create a proxy for a... | class Local(object):
__slots__ = ('__storage__', '__ident_func__')
def __init__(self):
object.__setattr__(self, '__storage__', {})
object.__setattr__(self, '__ident_func__', get_ident)
def __iter__(self):
return iter(self.__storage__.items())
def __call__(self, proxy):
... |
"""
Module: 'json' on esp32_LoBo
MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.24', version='ESP32_LoBo_v3.2.24 on 2018-09-06', machine='ESP32 board with ESP32')
Stubber: 1.0.0
"""
def dump():
pass
def dumps():
pass
def load():
pass
def loads():
pass
| """
Module: 'json' on esp32_LoBo
MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.24', version='ESP32_LoBo_v3.2.24 on 2018-09-06', machine='ESP32 board with ESP32')
Stubber: 1.0.0
"""
def dump():
pass
def dumps():
pass
def load():
pass
def loads():
pass |
def time2sec(timestr):
"""
Conver time specs to seconds
"""
if timestr[-1] == "s":
return int(timestr[0:-1])
elif timestr[-1] == "m":
return int(timestr[0:-1]) * 60
elif timestr[-1] == "h":
return int(timestr[0:-1]) * 60 * 60
else:
return int(timestr)
| def time2sec(timestr):
"""
Conver time specs to seconds
"""
if timestr[-1] == 's':
return int(timestr[0:-1])
elif timestr[-1] == 'm':
return int(timestr[0:-1]) * 60
elif timestr[-1] == 'h':
return int(timestr[0:-1]) * 60 * 60
else:
return int(timestr) |
SERIAL_DEVICE = '/dev/ttyAMA0'
SERIAL_SPEED = 115200
CALIBRATION_FILE = '/home/pi/stephmeter/calibration.json'
TIMEOUT = 300 # 5 minutes
MQTT_SERVER = '192.168.1.2'
MQTT_PORT = 1883
MQTT_TOPIC_PWM = 'traccar/eta'
MQTT_TOPIC_LED = 'traccar/led'
| serial_device = '/dev/ttyAMA0'
serial_speed = 115200
calibration_file = '/home/pi/stephmeter/calibration.json'
timeout = 300
mqtt_server = '192.168.1.2'
mqtt_port = 1883
mqtt_topic_pwm = 'traccar/eta'
mqtt_topic_led = 'traccar/led' |
def example():
print('basic function')
z=3+9
print(z)
#Function with parameter
def add(a,b):
c=a+b
print('the result is',c)
add(5,3)
add(a=3,b=5)
#Function with default parameters
def add_new(a,b=6):
print(a,b)
add_new(2)
def basic_window(width,height,font='TNR',bgc='w',scrollbar=True):... | def example():
print('basic function')
z = 3 + 9
print(z)
def add(a, b):
c = a + b
print('the result is', c)
add(5, 3)
add(a=3, b=5)
def add_new(a, b=6):
print(a, b)
add_new(2)
def basic_window(width, height, font='TNR', bgc='w', scrollbar=True):
print(width, height, font, bgc)
basic_wind... |
class Test:
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
deserunt mollit anim id est laborum.
.. sourcecode:: pycon
>>> # extract 100 LDA topics, using default parameters
>>> lda = LdaModel(corpus=mm, id2word=id2word, num_topics=100, distributed=True)
using distrib... | class Test:
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
deserunt mollit anim id est laborum.
.. sourcecode:: pycon
>>> # extract 100 LDA topics, using default parameters
>>> lda = LdaModel(corpus=mm, id2word=id2word, num_topics=100, distributed=True)
using distrib... |
# This program will compute the factorial of any number given by user
# until user enter some negative values.
n = int(input("please input a number: "))
# the loop for getting user inputs
while n >= 0:
# initializing
fact = 1
# calculating the factorial
for i in range(1, n+1):
fact *= i
... | n = int(input('please input a number: '))
while n >= 0:
fact = 1
for i in range(1, n + 1):
fact *= i
print('%d ! = %d' % (n, fact))
n = int(input('please input a number: ')) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
KanjiVG stub
"""
class KanjiVG:
pass
| """
KanjiVG stub
"""
class Kanjivg:
pass |
class GroupDirectoryError(Exception):
pass
class NoSuchRoleIdError(GroupDirectoryError):
def __init__(self, *args, role_id, **kwargs):
super().__init__(*args, **kwargs)
self.role_id = role_id
class NoSuchRoleNameError(GroupDirectoryError):
def __init__(self, *args, role_name, **kwargs):
... | class Groupdirectoryerror(Exception):
pass
class Nosuchroleiderror(GroupDirectoryError):
def __init__(self, *args, role_id, **kwargs):
super().__init__(*args, **kwargs)
self.role_id = role_id
class Nosuchrolenameerror(GroupDirectoryError):
def __init__(self, *args, role_name, **kwargs):
... |
consultation_mention = [
"rendez-vous pris",
r"consultation",
r"consultation.{1,8}examen",
"examen clinique",
r"de compte rendu",
r"date de l'examen",
r"examen realise le",
"date de la visite",
]
town_mention = [
"paris",
"kremlin.bicetre",
"creteil",
"boulogne.billancou... | consultation_mention = ['rendez-vous pris', 'consultation', 'consultation.{1,8}examen', 'examen clinique', 'de compte rendu', "date de l'examen", 'examen realise le', 'date de la visite']
town_mention = ['paris', 'kremlin.bicetre', 'creteil', 'boulogne.billancourt', 'villejuif', 'clamart', 'bobigny', 'clichy', 'ivry.su... |
class Solution:
def myPow(self, x: float, n: int) -> float:
memo = {}
def power(x,n):
if n in memo:return memo[n]
if n==0: return 1
elif n==1:return x
elif n < 0:
memo[n] = power(1/x,-n)
return memo[n]... | class Solution:
def my_pow(self, x: float, n: int) -> float:
memo = {}
def power(x, n):
if n in memo:
return memo[n]
if n == 0:
return 1
elif n == 1:
return x
elif n < 0:
memo[n] = power... |
def sum_Natural(n):
if n == 0:
return 0
else:
return sum_Natural(n - 1) + n
n = int(input())
result = sum_Natural(n)
print(f"Sum of first {n} natural numbers -> {result}")
| def sum__natural(n):
if n == 0:
return 0
else:
return sum__natural(n - 1) + n
n = int(input())
result = sum__natural(n)
print(f'Sum of first {n} natural numbers -> {result}') |
config = {
'cf_template_description': 'This template is generated with python'
'using troposphere framework to create'
'dynamic Cloudfront templates with'
'different vars according to the'
'PY... | config = {'cf_template_description': 'This template is generated with pythonusing troposphere framework to createdynamic Cloudfront templates withdifferent vars according to thePYTHON_ENV environment variable forECS fargate.', 'project_name': 'demo-ecs-fargate', 'network_stack_name': 'ansible-demo-network'} |
outputdir = "/map"
rendermode = "smooth_lighting"
world_name = "MCServer"
worlds[world_name] = "/data/world"
renders["North"] = {
'world': world_name,
'title': 'North',
'dimension': "overworld",
'rendermode': rendermode,
'northdirection': 'upper-left'
}
renders["East"] = {
'world': world_name,
'title': 'East',
... | outputdir = '/map'
rendermode = 'smooth_lighting'
world_name = 'MCServer'
worlds[world_name] = '/data/world'
renders['North'] = {'world': world_name, 'title': 'North', 'dimension': 'overworld', 'rendermode': rendermode, 'northdirection': 'upper-left'}
renders['East'] = {'world': world_name, 'title': 'East', 'dimension'... |
def load(filename):
lines = [s.strip() for s in open(filename,'r').readlines()]
time = int(lines[0])
busses = [int(value) for value in lines[1].split(",") if value != "x"]
return time,busses
t,busses = load("input")
print(f"Tiempo buscado {t}");
print(busses)
for i in range(t,t+1000):
for bus ... | def load(filename):
lines = [s.strip() for s in open(filename, 'r').readlines()]
time = int(lines[0])
busses = [int(value) for value in lines[1].split(',') if value != 'x']
return (time, busses)
(t, busses) = load('input')
print(f'Tiempo buscado {t}')
print(busses)
for i in range(t, t + 1000):
for b... |
ALL = 'All servers'
def caller_check(servers = ALL):
def func_wrapper(func):
# TODO: To be implemented. Could get current_app and check it. Useful for anything?
return func
return func_wrapper
| all = 'All servers'
def caller_check(servers=ALL):
def func_wrapper(func):
return func
return func_wrapper |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
dp = [0 for i in range(len... | def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
dp = [0 for i in range(len(n... |
#Programming I
#######################
# Mission 5.1 #
# Vitality Points #
#######################
#Background
#==========
#To encourage their customers to exercise more, insurance companies are giving
#vouchers for the distances that customers had clocked in a week as follows:
#########################... | def check_gift(distance):
if distance < 25:
value = 2
elif distance < 50:
value = 5
elif distance < 75:
value = 10
else:
value = 20
print(str(value) + ' eVoucher')
return value
check_gift(distance) |
#program to get all strobogrammatic numbers that are of length n.
def gen_strobogrammatic(n):
"""
:type n: int
:rtype: List[str]
"""
result = helper(n, n)
return result
def helper(n, length):
if n == 0:
return [""]
if n == 1:
return ["1", "0", "8"]
middles = helper(... | def gen_strobogrammatic(n):
"""
:type n: int
:rtype: List[str]
"""
result = helper(n, n)
return result
def helper(n, length):
if n == 0:
return ['']
if n == 1:
return ['1', '0', '8']
middles = helper(n - 2, length)
result = []
for middle in middles:
i... |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '9.6.beta5'
date = '2022-03-12'
banner = 'SageMath version 9.6.beta5, Release Date: 2022-03-12'
| version = '9.6.beta5'
date = '2022-03-12'
banner = 'SageMath version 9.6.beta5, Release Date: 2022-03-12' |
ls = list(input().split())
count = 0
for l in ls:
if l == 1:
count += 1
print(count)
| ls = list(input().split())
count = 0
for l in ls:
if l == 1:
count += 1
print(count) |
def solve(n):
F = [1, 1]
while len(str(F[-1])) < n:
F.append(F[-1] + F[-2])
return len(F)
# n = 3
n = 1000
answer = solve(n)
print(answer)
| def solve(n):
f = [1, 1]
while len(str(F[-1])) < n:
F.append(F[-1] + F[-2])
return len(F)
n = 1000
answer = solve(n)
print(answer) |
def isunique(s):
for i in range(len(s)):
for j in range(len(s)):
if i != j:
if(s[i] == s[j]):
return False
return True
if __name__ == "__main__":
res = isunique("hsjdfhjdhjfk")
print(res)
| def isunique(s):
for i in range(len(s)):
for j in range(len(s)):
if i != j:
if s[i] == s[j]:
return False
return True
if __name__ == '__main__':
res = isunique('hsjdfhjdhjfk')
print(res) |
uctable = [ [ 48 ],
[ 49 ],
[ 50 ],
[ 51 ],
[ 52 ],
[ 53 ],
[ 54 ],
[ 55 ],
[ 56 ],
[ 57 ],
[ 194, 178 ],
[ 194, 179 ],
[ 194, 185 ],
[ 194, 188 ],
[ 194, 189 ],
[ 194, 190 ],
[ 217, 160 ],
[ 217, 161 ],
[ 217, 162 ],
[ 217, 163 ],
[ 217, 164 ],
[ 217, 165 ],
[ 217, 166 ],
... | uctable = [[48], [49], [50], [51], [52], [53], [54], [55], [56], [57], [194, 178], [194, 179], [194, 185], [194, 188], [194, 189], [194, 190], [217, 160], [217, 161], [217, 162], [217, 163], [217, 164], [217, 165], [217, 166], [217, 167], [217, 168], [217, 169], [219, 176], [219, 177], [219, 178], [219, 179], [219, 180... |
"""Top-level package for zeroml."""
__author__ = """kuba cieslik"""
__email__ = 'kubacieslik@gmail.com'
__version__ = '0.3.3'
| """Top-level package for zeroml."""
__author__ = 'kuba cieslik'
__email__ = 'kubacieslik@gmail.com'
__version__ = '0.3.3' |
class LazyDict(dict):
def __init__(self, load_func, *args, **kwargs):
self._load_func = load_func
self._args = args
self._kwargs = kwargs
self._loaded = False
super().__init__()
def load(self):
if not self._loaded:
self.update(self._load_func(*self._a... | class Lazydict(dict):
def __init__(self, load_func, *args, **kwargs):
self._load_func = load_func
self._args = args
self._kwargs = kwargs
self._loaded = False
super().__init__()
def load(self):
if not self._loaded:
self.update(self._load_func(*self._... |
def gcd(a, b):
i = min(a, b)
while i>0:
if (a%i) == 0 and (b%i) == 0:
return i
else:
i = i-1
def p(s):
print(s)
if __name__ == "__main__":
p("input a:")
a = int(input())
p("input b:")
b = int(input())
p("gcd of "+str(a)+" and "+str(b)+" is:")
... | def gcd(a, b):
i = min(a, b)
while i > 0:
if a % i == 0 and b % i == 0:
return i
else:
i = i - 1
def p(s):
print(s)
if __name__ == '__main__':
p('input a:')
a = int(input())
p('input b:')
b = int(input())
p('gcd of ' + str(a) + ' and ' + str(b) + ... |
"""
Tutor allocation algorithm for allocating tutors to the optimal sessions.
"""
__author__ = "Henry O'Brien, Brae Webb"
__all__ = ['allocation', 'doodle', 'model', 'solver', 'csvalidator']
| """
Tutor allocation algorithm for allocating tutors to the optimal sessions.
"""
__author__ = "Henry O'Brien, Brae Webb"
__all__ = ['allocation', 'doodle', 'model', 'solver', 'csvalidator'] |
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
if A[0] >= 0 and A[-1] >= 0:
return [a ** 2 for a in A]
if A[0] <= 0 and A[-1] <= 0:
return [a ** 2 for a in A][::-1]
i = 0
while i < len(A) - 1 and A[i] < 0 and A[i + 1] < 0:
... | class Solution:
def sorted_squares(self, A: List[int]) -> List[int]:
if A[0] >= 0 and A[-1] >= 0:
return [a ** 2 for a in A]
if A[0] <= 0 and A[-1] <= 0:
return [a ** 2 for a in A][::-1]
i = 0
while i < len(A) - 1 and A[i] < 0 and (A[i + 1] < 0):
... |
# pylint: disable=missing-docstring,invalid-name,too-few-public-methods
class A:
myfield: int
class B(A):
pass
class C:
pass
class D(C, B):
pass
a = A()
print(a.myfield)
b = B()
print(b.myfield)
d = D()
print(d.myfield)
c = C()
print(c.myfield) # [no-member]
| class A:
myfield: int
class B(A):
pass
class C:
pass
class D(C, B):
pass
a = a()
print(a.myfield)
b = b()
print(b.myfield)
d = d()
print(d.myfield)
c = c()
print(c.myfield) |
'''
The goal of binary search is to search whether a given number is present in the string or not.
'''
lst = [1,3,2,4,5,6,9,8,7,10]
lst.sort()
first=0
last=len(lst)-1
mid = (first+last)//2
item = int(input("enter the number to be search"))
found = False
while( first<=last and not found):
mid = (first + l... | """
The goal of binary search is to search whether a given number is present in the string or not.
"""
lst = [1, 3, 2, 4, 5, 6, 9, 8, 7, 10]
lst.sort()
first = 0
last = len(lst) - 1
mid = (first + last) // 2
item = int(input('enter the number to be search'))
found = False
while first <= last and (not found):
mid = ... |
# SAME BSTS
# O(N^2) time and space
def sameBsts(arrayOne, arrayTwo):
# Write your code here.
if len(arrayOne) != len(arrayTwo):
return False
if len(arrayOne) == 0:
return True
if arrayOne[0] != arrayTwo[0]:
return False
leftSubtreeFirst = [num for num in arrayOne[1:] if num < arrayOne[0]]
rightS... | def same_bsts(arrayOne, arrayTwo):
if len(arrayOne) != len(arrayTwo):
return False
if len(arrayOne) == 0:
return True
if arrayOne[0] != arrayTwo[0]:
return False
left_subtree_first = [num for num in arrayOne[1:] if num < arrayOne[0]]
right_subtree_first = [num for num in arra... |
consent = """<center><table width="800px"><tr><td>
<font size="16"><b>University of Costa Rica<br/> </font>
INFORMED CONSENT FORM for RESEARCH<br/></b>
<b>Title of Study:</b> Hanabi AI Agents<br/>
<b>Principal Investigator:</b> Dr. Markus Eger <br/>
<h2>What are some general things you should know about re... | consent = '<center><table width="800px"><tr><td>\n<font size="16"><b>University of Costa Rica<br/> </font>\nINFORMED CONSENT FORM for RESEARCH<br/></b>\n<b>Title of Study:</b> Hanabi AI Agents<br/>\n<b>Principal Investigator:</b> Dr. Markus Eger <br/>\n\n\n<h2>What are some general things you should know about research... |
def getNextGreaterElement(array: list) -> None:
if len(array) <= 0:
return
print(bruteForce(array))
print(optimizationUsingSpace(array))
# bruteforce
def bruteForce(array: list) -> list:
'''
time complexicity: O(n^2)
space complexicity: O(1)
'''
greater_element_list = [-1] * len... | def get_next_greater_element(array: list) -> None:
if len(array) <= 0:
return
print(brute_force(array))
print(optimization_using_space(array))
def brute_force(array: list) -> list:
"""
time complexicity: O(n^2)
space complexicity: O(1)
"""
greater_element_list = [-1] * len(array... |
#remove duplicates from an unsorted linked list
def foo(linkedlist):
current_node = linkedlist.head
while current_node is not None:
checker_node = current_node
while checker_node.next is not None:
if checker_node.next.value == current_node.value:
checker_node.next =... | def foo(linkedlist):
current_node = linkedlist.head
while current_node is not None:
checker_node = current_node
while checker_node.next is not None:
if checker_node.next.value == current_node.value:
checker_node.next = checker_node.next.next
else:
... |
description = 'Verify the user can add an element to a page and save it successfully'
pages = ['common',
'index',
'project_pages',
'page_builder']
def setup(data):
common.access_golem(data.env.url, data.env.admin)
index.create_access_project('test')
common.navigate_menu('Pages'... | description = 'Verify the user can add an element to a page and save it successfully'
pages = ['common', 'index', 'project_pages', 'page_builder']
def setup(data):
common.access_golem(data.env.url, data.env.admin)
index.create_access_project('test')
common.navigate_menu('Pages')
project_pages.create_ac... |
##
# A collection of functions to search in lists.
#
##
# Returns the minimum element in a list of integers
def maximum_in_list(list):
# Your task:
# - Check if this function works for all possible integers.
# - Throw a ValueError if the input list is empty (see code below)
# if not list:
# ... | def maximum_in_list(list):
max_element = 0
for element in list:
if element > max_element:
max_element = element
return max_element |
def set_fill_color(red, green, blue):
pass
def draw_rectangle(corner, other_corner):
pass
set_fill_color(red=161, green=219, blue=114)
draw_rectangle(corner=(105,20), other_corner=(60,60))
| def set_fill_color(red, green, blue):
pass
def draw_rectangle(corner, other_corner):
pass
set_fill_color(red=161, green=219, blue=114)
draw_rectangle(corner=(105, 20), other_corner=(60, 60)) |
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
def anchore_extra_deps(configure_go=True):
if configure_go:
go_rules_dependencies()
go_register_toolchains(version = "1.17.1")
| load('@io_bazel_rules_go//go:deps.bzl', 'go_register_toolchains', 'go_rules_dependencies')
def anchore_extra_deps(configure_go=True):
if configure_go:
go_rules_dependencies()
go_register_toolchains(version='1.17.1') |
def checkprime(value: int):
factor = 2
sqrt = value ** 0.5
while factor <= sqrt:
if value % factor == 0:
return False
factor += 1
return True
def sum_primes_under(n: int):
num = 2
sum = 0
while num < n:
if checkprime(num):
sum += num
... | def checkprime(value: int):
factor = 2
sqrt = value ** 0.5
while factor <= sqrt:
if value % factor == 0:
return False
factor += 1
return True
def sum_primes_under(n: int):
num = 2
sum = 0
while num < n:
if checkprime(num):
sum += num
n... |
month = input()
days = int(input())
cost_a = 0
cost_s = 0
if month == "May" or month == "October":
cost_a = days * 65
cost_s = days * 50
if 7 < days <= 14:
cost_s = cost_s * 0.95
if days > 14:
cost_s = cost_s * 0.7
elif month == "June" or month == "September":
cost_a = days * 68.70... | month = input()
days = int(input())
cost_a = 0
cost_s = 0
if month == 'May' or month == 'October':
cost_a = days * 65
cost_s = days * 50
if 7 < days <= 14:
cost_s = cost_s * 0.95
if days > 14:
cost_s = cost_s * 0.7
elif month == 'June' or month == 'September':
cost_a = days * 68.7
... |
## creat fct
def raise_to_power(base_num, pow_num): ## fct take 2 input num
result = 1 ## def var call result is going to store result
for index in range(pow_num): ## specify for loop that loop through range of num
result = result * base_num ## math is going to be store in result
return resu... | def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(2, 3)) |
CENSUS_YEAR = 2017
COMSCORE_YEAR = 2017
N_PANELS = 500
N_CORES = 8
# income mapping for aggregating ComScore data to fewer
# categories so stratification creates larger panels
INCOME_MAPPING = {
# 1 is 0 to 25k
# 2 is 25k to 50k
# 3 is 50k to 100k
# 4 is 100k +
1: 1, # less than 10k and 10k-15k
... | census_year = 2017
comscore_year = 2017
n_panels = 500
n_cores = 8
income_mapping = {1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 3, 7: 4} |
def maximo(a, b, c):
if a > b and a > c:
return a
elif b > c and b > a:
return b
elif c > a and c > b:
return c
elif a == b == c:
return a
| def maximo(a, b, c):
if a > b and a > c:
return a
elif b > c and b > a:
return b
elif c > a and c > b:
return c
elif a == b == c:
return a |
#A loop statement allows us to execute a statement or group of statements multiple times.
def main():
var = 0
# define a while loop
while (var < 5):
print (var)
var = var + 1
# define a for loop
for var in range(5,10):
print (var)
# use a for loop over a collection
days = ["Mon... | def main():
var = 0
while var < 5:
print(var)
var = var + 1
for var in range(5, 10):
print(var)
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for d in days:
print(d)
for var in range(5, 10):
print(var)
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fr... |
KERNAL_FILENAME = "kernel"
INITRD_FILENAME = "initrd"
DISK_FILENAME = "disk.img"
BOOT_DISK_FILENAME = "boot.img"
CLOUDINIT_ISO_NAME = "cloudinit.img"
| kernal_filename = 'kernel'
initrd_filename = 'initrd'
disk_filename = 'disk.img'
boot_disk_filename = 'boot.img'
cloudinit_iso_name = 'cloudinit.img' |
class DES(object):
## Init boxes that we're going to use
def __init__(self):
# Permutation tables and Sboxes
self.IP = (
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
... | class Des(object):
def __init__(self):
self.IP = (58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7)
se... |
"""
Build the CUDA-STREAM benchmark for multiple CUDA compute capabilities.
Make each build available as a SCI-F application.
"""
Stage0 += baseimage(image='nvcr.io/nvidia/cuda:9.1-devel-centos7', _as='devel')
# Install the GNU compiler
Stage0 += gnu(fortran=False)
# Install SCI-F
Stage0 += pip(packages=['scif'], up... | """
Build the CUDA-STREAM benchmark for multiple CUDA compute capabilities.
Make each build available as a SCI-F application.
"""
stage0 += baseimage(image='nvcr.io/nvidia/cuda:9.1-devel-centos7', _as='devel')
stage0 += gnu(fortran=False)
stage0 += pip(packages=['scif'], upgrade=True)
stage0 += packages(ospackages=['c... |
# import math
# def longest_palindromic_contiguous(contiguous_substring):
# start_ptr = 0
# end_ptr = 0
# for i in range(len(contiguous_substring)):
# len_1 = expand_from_center(contiguous_substring, i, i)
# len_2 = expand_from_center(contiguous_substring, i, i + 1)
# max_len = max... | num_gemstones = int(input())
gemstones_colors = ''.join([str(color) for color in input().split(' ')])
num_seconds = [[0 for x in range(num_gemstones + 1)] for y in range(num_gemstones + 1)]
for length in range(1, num_gemstones + 1):
idx_i = 0
idx_j = length - 1
while idx_j < num_gemstones:
if length... |
# unselectGlyphsWithExtension.py
f = CurrentFont()
for gname in f.selection:
if '.' in gname:
f[gname].selected = 0
| f = current_font()
for gname in f.selection:
if '.' in gname:
f[gname].selected = 0 |
# Problem: https://www.hackerrank.com/challenges/s10-weighted-mean/problem
# Score: 30
n = int(input())
arr = list(map(int, input().split()))
weights = list(map(int, input().split()))
print(round(sum([arr[x]*weights[x] for x in range(len(arr))]) / sum(weights), 1))
| n = int(input())
arr = list(map(int, input().split()))
weights = list(map(int, input().split()))
print(round(sum([arr[x] * weights[x] for x in range(len(arr))]) / sum(weights), 1)) |
a = float(raw_input("What is the coefficients a? "))
b = float(raw_input("What is the coefficients b? "))
c = float(raw_input("What is the coefficients c? "))
d = b*b - 4.*a*c
if d >= 0.0:
print("Solutions are real")
elif b == 0.0:
print("Solutions are imaginary")
else:
print("Solutions are complex")
pri... | a = float(raw_input('What is the coefficients a? '))
b = float(raw_input('What is the coefficients b? '))
c = float(raw_input('What is the coefficients c? '))
d = b * b - 4.0 * a * c
if d >= 0.0:
print('Solutions are real')
elif b == 0.0:
print('Solutions are imaginary')
else:
print('Solutions are complex')... |
def separador(mano):
lista_valor = []
lista_suit = []
valor_carta = {'2':1, '3':2, '4':3, '5':4, '6':5, '7':6, '8':7, '9':8, 'T':9, 'J':10, 'Q':11, 'K':12, 'A':13}
for i in mano.split(' '):
lista_valor.append(valor_carta.get(i[0]))
lista_suit.append(i[1])
return(sorted(lista_valor), lista_suit)
def Royal_F... | def separador(mano):
lista_valor = []
lista_suit = []
valor_carta = {'2': 1, '3': 2, '4': 3, '5': 4, '6': 5, '7': 6, '8': 7, '9': 8, 'T': 9, 'J': 10, 'Q': 11, 'K': 12, 'A': 13}
for i in mano.split(' '):
lista_valor.append(valor_carta.get(i[0]))
lista_suit.append(i[1])
return (sorted(... |
substring=input()
word=input()
while substring in word:
word=word.replace(substring,"")
print(word) | substring = input()
word = input()
while substring in word:
word = word.replace(substring, '')
print(word) |
class Solution(object):
def findAllConcatenatedWordsInADict(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
ans = []
self.wordSet = set(words)
for word in words:
self.wordSet.remove(word)
if self.search(word):
... | class Solution(object):
def find_all_concatenated_words_in_a_dict(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
ans = []
self.wordSet = set(words)
for word in words:
self.wordSet.remove(word)
if self.search(word):
... |
# names tuple
names = ('Anonymous','Tazri','Focasa','Troy','Farha','Xenon');
print("names : ",names);
## adding value of names
updating = list(names);
updating.append('solus');
names = tuple(updating);
print("update names : ");
print(names); | names = ('Anonymous', 'Tazri', 'Focasa', 'Troy', 'Farha', 'Xenon')
print('names : ', names)
updating = list(names)
updating.append('solus')
names = tuple(updating)
print('update names : ')
print(names) |
AUTHOR = 'Name Lastname'
SITENAME = "The name of your website"
SITEURL = 'http://example.com'
TIMEZONE = ""
DISQUS_SITENAME = ''
DEFAULT_DATE_FORMAT = '%d/%m/%Y'
REVERSE_ARCHIVE_ORDER = True
TAG_CLOUD_STEPS = 8
PATH = ''
THEME = ''
OUTPUT_PATH = ''
MARKUP = 'md'
MD_EXTENSIONS = 'extra'
FEED_RSS = 'feeds/all.rss.xm... | author = 'Name Lastname'
sitename = 'The name of your website'
siteurl = 'http://example.com'
timezone = ''
disqus_sitename = ''
default_date_format = '%d/%m/%Y'
reverse_archive_order = True
tag_cloud_steps = 8
path = ''
theme = ''
output_path = ''
markup = 'md'
md_extensions = 'extra'
feed_rss = 'feeds/all.rss.xml'
ta... |
instructor = {
"name":"Cosmic",
"num_courses":'4',
"favorite_language" :"Python",
"is_hillarious": False,
44 : "is my favorite number"
}
# Way to check if a key exists in a dict and returns True or False as a response
a = "name" in instructor
print(a)
b = "phone" in instructor
print(b... | instructor = {'name': 'Cosmic', 'num_courses': '4', 'favorite_language': 'Python', 'is_hillarious': False, 44: 'is my favorite number'}
a = 'name' in instructor
print(a)
b = 'phone' in instructor
print(b)
c = instructor.values()
print(c) |
"""
Write a recursive function that implements the run-length compression technique
described in Run-Lenght Decoding Exercise.
Your function will take a list or a string as its only argument.
It should return the run-length compressed list as its only result.
Include a main program that reads a string from the user, ... | """
Write a recursive function that implements the run-length compression technique
described in Run-Lenght Decoding Exercise.
Your function will take a list or a string as its only argument.
It should return the run-length compressed list as its only result.
Include a main program that reads a string from the user, ... |
# Time: O(m * n)
# Space: O(1)
# 419
# Given an 2D board, count how many different battleships are in it.
# The battleships are represented with 'X's, empty slots are represented with
# '.'s.
# You may assume the following rules:
#
# You receive a valid board, made of only battleships or empty slots.
# Battleships ca... | try:
xrange
except NameError:
xrange = range
class Solution(object):
def count_battleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
return sum((board[i][j] == 'X' and (i == 0 or board[i - 1][j] != 'X') and (j == 0 or board[i][j - 1] != 'X') for... |
"""
This module pre-defines colors as defined by the W3C CSS standard:
https://www.w3.org/TR/2018/PR-css-color-3-20180315/
"""
ALICE_BLUE = (240, 248, 255)
ANTIQUE_WHITE = (250, 235, 215)
AQUA = (0, 255, 255)
AQUAMARINE = (127, 255, 212)
AZURE = (240, 255, 255)
BEIGE = (245, 245, 220)
BISQUE = (255, 228, 19... | """
This module pre-defines colors as defined by the W3C CSS standard:
https://www.w3.org/TR/2018/PR-css-color-3-20180315/
"""
alice_blue = (240, 248, 255)
antique_white = (250, 235, 215)
aqua = (0, 255, 255)
aquamarine = (127, 255, 212)
azure = (240, 255, 255)
beige = (245, 245, 220)
bisque = (255, 228, 196)
black = (... |
#!/usr/bin/python3
""" Transforms a list into a string. """
l = ["I", "am", "the", "law"]
print(" ".join(l))
| """ Transforms a list into a string. """
l = ['I', 'am', 'the', 'law']
print(' '.join(l)) |
class Solution:
def twoSum(self, numbers, target):
res = None
left = 0
right = len(numbers) - 1
while left < right:
result = numbers[left] + numbers[right]
if result == target:
res = [left + 1, right + 1]
break
elif ... | class Solution:
def two_sum(self, numbers, target):
res = None
left = 0
right = len(numbers) - 1
while left < right:
result = numbers[left] + numbers[right]
if result == target:
res = [left + 1, right + 1]
break
eli... |
class CaesarShiftCipher:
def __init__(self, shift=1):
self.shift = shift
def encrypt(self, plaintext):
return ''.join(
[self.num_2_char((self.char_2_num(letter) + self.shift) % 26) for letter in plaintext.lower()]
).upper()
def decrypt(self, ciphertext: str) -> str:
... | class Caesarshiftcipher:
def __init__(self, shift=1):
self.shift = shift
def encrypt(self, plaintext):
return ''.join([self.num_2_char((self.char_2_num(letter) + self.shift) % 26) for letter in plaintext.lower()]).upper()
def decrypt(self, ciphertext: str) -> str:
return ''.join([... |
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
def main():
n=6
print(factorial(n))
main()
| def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
def main():
n = 6
print(factorial(n))
main() |
numbers = [int(n) for n in input().split(' ')]
n = len(numbers)
for i in range(n):
for j in range(0, n - i - 1):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
print(' '.join([str(n) for n in numbers])) | numbers = [int(n) for n in input().split(' ')]
n = len(numbers)
for i in range(n):
for j in range(0, n - i - 1):
if numbers[j] > numbers[j + 1]:
(numbers[j], numbers[j + 1]) = (numbers[j + 1], numbers[j])
print(' '.join([str(n) for n in numbers])) |
# coding: utf8
# try something like
def index():
'''main page that allows searching for and displaying audio listings'''
#create search form
formSearch = FORM(INPUT(_id='searchInput', requires=[IS_NOT_EMPTY(error_message='you have to enter something to search for'),
IS_LENGTH(50, error_message='you can\'t have su... | def index():
"""main page that allows searching for and displaying audio listings"""
form_search = form(input(_id='searchInput', requires=[is_not_empty(error_message='you have to enter something to search for'), is_length(50, error_message="you can't have such a long search term, limit is 50 characters")]), inp... |
class Result:
"""Class description."""
def __init__(self):
"""
Initialization of the class.
"""
pass
def __str__(self):
return
| class Result:
"""Class description."""
def __init__(self):
"""
Initialization of the class.
"""
pass
def __str__(self):
return |
class Building(object):
"""Class representing all the data for a building
'attribute name': 'type'
swagger_types = {
'buildingId': 'str',
'nameList': 'list[str]',
'numWashers': 'int',
'numDryers': 'int',
}
'attribute name': 'Attribute name in Swagger Docs'
attribute_map = {
'buildingId': 'buildingId... | class Building(object):
"""Class representing all the data for a building
'attribute name': 'type'
swagger_types = {
'buildingId': 'str',
'nameList': 'list[str]',
'numWashers': 'int',
'numDryers': 'int',
}
'attribute name': 'Attribute name in Swagger Docs'
attribute_map = {
'buildingId': 'buildin... |
# Register the HourglassTree report addon
register(REPORT,
id = 'hourglass_chart',
name = _("Hourglass Tree"),
description = _("Produces a graphical report combining an ancestor tree and a descendant tree."),
version = '1.0.0',
gramps_target_version = '5.1',
status = STABLE,
fname = 'hourglasstree.p... | register(REPORT, id='hourglass_chart', name=_('Hourglass Tree'), description=_('Produces a graphical report combining an ancestor tree and a descendant tree.'), version='1.0.0', gramps_target_version='5.1', status=STABLE, fname='hourglasstree.py', authors=['Peter Zingg'], authors_email=['peter.zingg@gmail.com'], catego... |
class SolidSurfaceLoads:
def sfa(self, area="", lkey="", lab="", value="", value2="", **kwargs):
"""Specifies surface loads on the selected areas.
APDL Command: SFA
Parameters
----------
area
Area to which surface load applies. If ALL, apply load to all
... | class Solidsurfaceloads:
def sfa(self, area='', lkey='', lab='', value='', value2='', **kwargs):
"""Specifies surface loads on the selected areas.
APDL Command: SFA
Parameters
----------
area
Area to which surface load applies. If ALL, apply load to all
... |
class RLPException(Exception):
"""Base class for exceptions raised by this package."""
pass
class EncodingError(RLPException):
"""Exception raised if encoding fails.
:ivar obj: the object that could not be encoded
"""
def __init__(self, message, obj):
super(EncodingError, self).__ini... | class Rlpexception(Exception):
"""Base class for exceptions raised by this package."""
pass
class Encodingerror(RLPException):
"""Exception raised if encoding fails.
:ivar obj: the object that could not be encoded
"""
def __init__(self, message, obj):
super(EncodingError, self).__init... |
def make_car(manufacturer, model, **extra_info):
"""Make a car dictionary using input information."""
car = {}
car['manufacturer'] = manufacturer
car['model'] = model
for key, value in extra_info.items():
car[key] = value
return car
car = make_car('subaru', 'outback', color='blue', to... | def make_car(manufacturer, model, **extra_info):
"""Make a car dictionary using input information."""
car = {}
car['manufacturer'] = manufacturer
car['model'] = model
for (key, value) in extra_info.items():
car[key] = value
return car
car = make_car('subaru', 'outback', color='blue', tow... |
#
# PySNMP MIB module Nortel-Magellan-Passport-PppMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-PppMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:18:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint, constraints_union) ... |
"""
Write a class called MyCounter that counts
how many times it was initialised, so the
following code:
for _ in range(10):
c1 = MyCounter()
print MyCounter.count
should print 10
"""
| """
Write a class called MyCounter that counts
how many times it was initialised, so the
following code:
for _ in range(10):
c1 = MyCounter()
print MyCounter.count
should print 10
""" |
#
# This file contains the Python code from Program 9.8 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm09_08.txt
#
class Tree(Containe... | class Tree(Container):
def accept(self, visitor):
assert isinstance(visitor, Visitor)
self.depthFirstTraversal(pre_order(visitor)) |
x = int(input("Insert some numbers: "))
ev = 0
od = 0
while x > 0:
if x%2 ==0:
ev += 1
else:
od += 1
x = x//10
print("Even numbers = %d, Odd numbers = %d" % (ev,od)) | x = int(input('Insert some numbers: '))
ev = 0
od = 0
while x > 0:
if x % 2 == 0:
ev += 1
else:
od += 1
x = x // 10
print('Even numbers = %d, Odd numbers = %d' % (ev, od)) |
'''A special two digit number is a number such that when the sum of its digits is added to the product of its digits, the result should be equal to the original two-digit number.
Implement a program to accept a two digit number and check whether it is a special two digit number or not.
Input Format
a two digit number... | """A special two digit number is a number such that when the sum of its digits is added to the product of its digits, the result should be equal to the original two-digit number.
Implement a program to accept a two digit number and check whether it is a special two digit number or not.
Input Format
a two digit number... |
def latex_template(name, title):
return '\n'.join((r"\begin{figure}[H]",
r" \centering",
rf" \incfig[0.8]{{{name}}}",
rf" \caption{{{title}}}",
rf" \label{{fig:{name}}}",
r" \vspace{-0.5cm}",... | def latex_template(name, title):
return '\n'.join(('\\begin{figure}[H]', ' \\centering', f' \\incfig[0.8]{{{name}}}', f' \\caption{{{title}}}', f' \\label{{fig:{name}}}', ' \\vspace{-0.5cm}', '\\end{figure}')) |
# @kwargs - extendable parameter list of the form var1=[a1, a2, .., an], var2=[b1, b2, ..., bn], ...
# @value - list of parameter permutations of the form [(a1, b1, ...), (a1, b2, ...), (a2, b1, ...), ...]
def cv_grid(**kwargs):
"""Returns a list of parameter tuples from the grid.
Each tuple is a unique permut... | def cv_grid(**kwargs):
"""Returns a list of parameter tuples from the grid.
Each tuple is a unique permutation of parameters specified in kwargs"""
key_list = list(kwargs.keys())
return __assemble(key_list, kwargs, 0)
def __assemble(key_list, param_select_dict, key_inx):
if key_inx < len(key_list)... |
"""
MIT License
Copyright (c) 2020-2022 EntySec
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, publish, ... | """
MIT License
Copyright (c) 2020-2022 EntySec
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, publish, ... |
"""
ID: duweira1
LANG: PYTHON2
TASK: test
"""
fin = open ('test.in', 'r')
fout = open ('test.out', 'w')
x,y = map(int, fin.readline().split())
sum = x+y
fout.write (str(sum) + '\n')
fout.close()
| """
ID: duweira1
LANG: PYTHON2
TASK: test
"""
fin = open('test.in', 'r')
fout = open('test.out', 'w')
(x, y) = map(int, fin.readline().split())
sum = x + y
fout.write(str(sum) + '\n')
fout.close() |
"""Quiz Game using Dictionary"""
"""
Stpes:
1. Create a dictionary containing questions and answers
2. Loop through diction
3.
"""
question_and_answer = {
"What is the capital of India?": "New Delhi",
"What is the capital of USA?": "Washington",
"What is the capital of UK?": "London",
"Wh... | """Quiz Game using Dictionary"""
'\nStpes:\n 1. Create a dictionary containing questions and answers\n 2. Loop through diction\n 3. \n'
question_and_answer = {'What is the capital of India?': 'New Delhi', 'What is the capital of USA?': 'Washington', 'What is the capital of UK?': 'London', 'What is the capital ... |
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
This file contains indexing suite v2 code
"""
file_name = "indexing_suite/slice.hpp"
code = """// Header file ... | """
This file contains indexing suite v2 code
"""
file_name = 'indexing_suite/slice.hpp'
code = '// Header file slice.hpp\n//\n// Copyright (c) 2003 Raoul M. Gough\n//\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy\n// at ... |
houses = {(0, 0)}
with open('Day 3 - input', 'r') as f:
directions = f.readline()
current_location = [0, 0]
for direction in directions[::2]:
if direction == '^':
current_location[1] += 1
houses.add(tuple(current_location))
elif direction == '>':
current_... | houses = {(0, 0)}
with open('Day 3 - input', 'r') as f:
directions = f.readline()
current_location = [0, 0]
for direction in directions[::2]:
if direction == '^':
current_location[1] += 1
houses.add(tuple(current_location))
elif direction == '>':
current_l... |
class Profile:
def __init__(self, id, username, email, allowed_buy,
first_name, last_name, is_staff, is_current, **kwargs):
self.id = id
self.user_name = username
self.email = email
self.allowed_buy = allowed_buy
self.first_name = first_name
self.last... | class Profile:
def __init__(self, id, username, email, allowed_buy, first_name, last_name, is_staff, is_current, **kwargs):
self.id = id
self.user_name = username
self.email = email
self.allowed_buy = allowed_buy
self.first_name = first_name
self.last_name = last_nam... |
#!/usr/bin/env python
class Graph:
def __init__(self, n, edges):
# n is the number of vertices
# edges is a list of tuples which represents one edge
self.n = n
self.V = set(list(range(n)))
self.E = [set() for i in range(n)]
for e in edges:
v, w = e
... | class Graph:
def __init__(self, n, edges):
self.n = n
self.V = set(list(range(n)))
self.E = [set() for i in range(n)]
for e in edges:
(v, w) = e
self.E[v].add(w)
self.E[w].add(v)
def __str__(self):
ret = ''
ret += 'There are %... |
'''
Adapt the code from one of the functions above to create a new function called 'multiplier'.
The user should be able to input two numbers that are stored in variables.
The function should multiply the two variables together and return the result to a variable in the main program.
The main program should output the ... | """
Adapt the code from one of the functions above to create a new function called 'multiplier'.
The user should be able to input two numbers that are stored in variables.
The function should multiply the two variables together and return the result to a variable in the main program.
The main program should output the ... |
my_dictionary={
'nama': 'Elyas',
'usia': 19,
'status': 'mahasiswa'
}
my_dictionary["usia"]=20
print(my_dictionary) | my_dictionary = {'nama': 'Elyas', 'usia': 19, 'status': 'mahasiswa'}
my_dictionary['usia'] = 20
print(my_dictionary) |
"""
n = 4
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
count: i + 1
f(i, j) = i (i + 1) / 2 + 1 + j
1 + 2 + 3 + 4 + ... + n = n (n + 1) / 2
"""
n = int(input())
# k = 1
# for i in range(n):
# for _ in range(i + 1):
# print(k, end=' ')
# k += 1
# print()
"""
Time Complexity: O(n^2)
Space Complexity: ... | """
n = 4
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
count: i + 1
f(i, j) = i (i + 1) / 2 + 1 + j
1 + 2 + 3 + 4 + ... + n = n (n + 1) / 2
"""
n = int(input())
'\nTime Complexity: O(n^2)\nSpace Complexity: O(1)\n'
for i in range(n):
for j in range(i + 1):
print(i * (i + 1) // 2 + 1 + j, end=' ')
print() |
#!/usr/bin/env python3
#encoding=utf-8
#------------------------------------------------
# Usage: python3 3-decorator2.py
# Description: Tracer call with key-word only
#------------------------------------------------
class Tracer: # state via instance attributes
def __init__(self, func): # ... | class Tracer:
def __init__(self, func):
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
print('call %s to %s' % (self.calls, self.func.__name__))
return self.func(*args, **kwargs)
@Tracer
def spam(a, b, c):
print(a + b + c)
@Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.