content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python
# AUTHOR: jo
# DATE: 2019-08-12
# DESCRIPTION: Tuse homework assignment #1.
def partitionOnZeroSumAndMax(row):
# Ex. Passing in [1,1,0,1] returns [2,0,1].
# max([2,0,1]) -> 2
localSums = [0]
for val in row:
if val != 0:
localSums.append(localSums.pop() + val)
... | def partition_on_zero_sum_and_max(row):
local_sums = [0]
for val in row:
if val != 0:
localSums.append(localSums.pop() + val)
else:
localSums.append(0)
return max(localSums)
def get_distance_and_max(matrix):
matrix_distance = [[None for row in range(len(matrix))]... |
#!/usr/bin/env python2
def main():
n = input('')
for i in range(0, n):
rows = input('')
matrix = []
for j in range(0, rows):
matrix.append([int(x) for x in raw_input('').split()])
print(weight(matrix, 0, 0))
def weight(matrix, i, j):
#print('weight called with',... | def main():
n = input('')
for i in range(0, n):
rows = input('')
matrix = []
for j in range(0, rows):
matrix.append([int(x) for x in raw_input('').split()])
print(weight(matrix, 0, 0))
def weight(matrix, i, j):
if i < len(matrix) - 1:
return matrix[i][j] ... |
codon_protein = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCG": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UAU": "Tyrosine",
"UAC": "Tyrosine",
"UGU": "Cysteine",
"UGC": "Cysteine",
... | codon_protein = {'AUG': 'Methionine', 'UUU': 'Phenylalanine', 'UUC': 'Phenylalanine', 'UUA': 'Leucine', 'UUG': 'Leucine', 'UCU': 'Serine', 'UCG': 'Serine', 'UCC': 'Serine', 'UCA': 'Serine', 'UAU': 'Tyrosine', 'UAC': 'Tyrosine', 'UGU': 'Cysteine', 'UGC': 'Cysteine', 'UGG': 'Tryptophan', 'UAA': None, 'UAG': None, 'UGA': ... |
# Copyright 2017-2022 Lawrence Livermore National Security, LLC and other
# Hatchet Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT
__version_info__ = ("2022", "1", "0")
__version__ = ".".join(__version_info__)
| __version_info__ = ('2022', '1', '0')
__version__ = '.'.join(__version_info__) |
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAncestor(self, root, p, q):
s, b = sorted([p.val, q.val])
while not s <= root.val <= b:
# Keep searching since ro... | class Solution(object):
def lowest_common_ancestor(self, root, p, q):
(s, b) = sorted([p.val, q.val])
while not s <= root.val <= b:
root = root.left if s <= root.val else root.right
return root |
n = int(input())
nsum = 0
for i in range(1, n+1):
nsum += i
if nsum == 1:
print('BOWWOW')
elif nsum <= 3:
print('WANWAN')
else:
for i in range(2, n+1):
if n % i == 0:
print('BOWWOW')
break
else:
print('WANWAN')
| n = int(input())
nsum = 0
for i in range(1, n + 1):
nsum += i
if nsum == 1:
print('BOWWOW')
elif nsum <= 3:
print('WANWAN')
else:
for i in range(2, n + 1):
if n % i == 0:
print('BOWWOW')
break
else:
print('WANWAN') |
#!/usr/bin/env python3
def find_array_intersection(A, B):
ai = 0
bi = 0
ret = []
while ai < len(A) and bi < len(B):
if A[ai] < B[bi]:
ai += 1
elif A[ai] > B[bi]:
bi += 1
else:
ret.append(A[ai])
v = A[ai]
while ai < len(... | def find_array_intersection(A, B):
ai = 0
bi = 0
ret = []
while ai < len(A) and bi < len(B):
if A[ai] < B[bi]:
ai += 1
elif A[ai] > B[bi]:
bi += 1
else:
ret.append(A[ai])
v = A[ai]
while ai < len(A) and A[ai] == v:
... |
def do_stuff(fn, lhs, rhs):
return fn(lhs, rhs)
def add(lhs, rhs):
return lhs + rhs
def multiply(lhs, rhs):
return lhs * rhs
def exponent(lhs, rhs):
return lhs ** rhs
print(do_stuff(add, 2, 3))
print(do_stuff(multiply, 2, 3))
print(do_stuff(exponent, 2, 3))
| def do_stuff(fn, lhs, rhs):
return fn(lhs, rhs)
def add(lhs, rhs):
return lhs + rhs
def multiply(lhs, rhs):
return lhs * rhs
def exponent(lhs, rhs):
return lhs ** rhs
print(do_stuff(add, 2, 3))
print(do_stuff(multiply, 2, 3))
print(do_stuff(exponent, 2, 3)) |
# A tuple operates like a list but it's initial values can't be modified
# Tuples are declared using the ()
# Use case examples of using Tuple - Dates of the week, Months of the Year, Hours of the clock
# we can create a tuple like this...
monthsOfTheYear = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug... | months_of_the_year = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
print(monthsOfTheYear)
print(monthsOfTheYear[0])
print(monthsOfTheYear[:3])
my_tuple = ('Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun')
print(len(myTuple))
print(sorted(myTuple))
names = ['John', 'Lamin', 'Vicky... |
def solve(array):
even = []
odd = []
for i in range(len(array)):
if array[i] % 2 == 0:
even.append(i)
else:
odd.append(i)
if even:
return f"1\n{even[-1] + 1}"
if len(odd) > 1:
return f"2\n{odd[-1] + 1} {odd[-2] + 1}"
else:
retur... | def solve(array):
even = []
odd = []
for i in range(len(array)):
if array[i] % 2 == 0:
even.append(i)
else:
odd.append(i)
if even:
return f'1\n{even[-1] + 1}'
if len(odd) > 1:
return f'2\n{odd[-1] + 1} {odd[-2] + 1}'
else:
return '-... |
# These constants can be set by the external UI-layer process, don't change them manually
is_ui_process = False
execution_id = ''
task_id = ''
executable_name = 'insomniac'
do_location_permission_dialog_checks = True # no need in these checks if location permission is denied beforehand
def callback(profile_name):
... | is_ui_process = False
execution_id = ''
task_id = ''
executable_name = 'insomniac'
do_location_permission_dialog_checks = True
def callback(profile_name):
pass
hardban_detected_callback = callback
softban_detected_callback = callback
def is_insomniac():
return execution_id == '' |
defaults = '''
const vec4 light = vec4(4.0, 3.0, 10.0, 0.0);
const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0);
const mat4 mvp = mat4(
-0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972,
1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057617... | defaults = '\n const vec4 light = vec4(4.0, 3.0, 10.0, 0.0);\n const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0);\n const mat4 mvp = mat4(\n -0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972,\n 1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057... |
class OutOfService(Exception):
def __init__(self,Note:str=""):
pass
class InternalError(Exception):
def __init__(self,Note:str=""):
pass
class NothingFoundError(Exception):
def __init__(self,Note:str=""):
pass
class DummyError(Exception):
def __init__(self,Note:str=""):... | class Outofservice(Exception):
def __init__(self, Note: str=''):
pass
class Internalerror(Exception):
def __init__(self, Note: str=''):
pass
class Nothingfounderror(Exception):
def __init__(self, Note: str=''):
pass
class Dummyerror(Exception):
def __init__(self, Note: str... |
a = [1, 4, 5, 7, 19, 24]
b = [4, 6, 7, 18, 24, 134]
i = 0
j = 0
ans = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
ans.append(a[i])
i += 1
j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
print(*ans)
| a = [1, 4, 5, 7, 19, 24]
b = [4, 6, 7, 18, 24, 134]
i = 0
j = 0
ans = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
ans.append(a[i])
i += 1
j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
print(*ans) |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue(object):
def __init__(self, size):
self.queue = []
self.size = size
def enqueue(self, value):
'''This function adds an value to the rear end of the queue '''
if(self.isFull() !... | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue(object):
def __init__(self, size):
self.queue = []
self.size = size
def enqueue(self, value):
"""This function adds an value to the rear end of the queue """
if self.isF... |
bill_board = list(map(int, input().split()))
tarp = list(map(int, input().split()))
xOverlap = max(min(bill_board[2], tarp[2]) - max(bill_board[0], tarp[0]), 0)
yOverlap = max(min(bill_board[3], tarp[3]) - max(bill_board[1], tarp[1]), 0)
if xOverlap == 0 or yOverlap == 0:
print((bill_board[2] - bill_boar... | bill_board = list(map(int, input().split()))
tarp = list(map(int, input().split()))
x_overlap = max(min(bill_board[2], tarp[2]) - max(bill_board[0], tarp[0]), 0)
y_overlap = max(min(bill_board[3], tarp[3]) - max(bill_board[1], tarp[1]), 0)
if xOverlap == 0 or yOverlap == 0:
print((bill_board[2] - bill_board[0]) * (... |
'''
Edges in a block diagram computational graph. The edges themselves don't have direction,
but the ports that they attach to may.
'''
class WireConnection:
pass
class NamedConnection(WireConnection):
def __init__(self, target_uid: int, target_port: str):
self.target_uid = target_uid
self.t... | """
Edges in a block diagram computational graph. The edges themselves don't have direction,
but the ports that they attach to may.
"""
class Wireconnection:
pass
class Namedconnection(WireConnection):
def __init__(self, target_uid: int, target_port: str):
self.target_uid = target_uid
self.ta... |
RADIO_ENABLED = ":white_check_mark: **Radio enabled**"
RADIO_DISABLED = ":x: **Radio disabled**"
SKIPPED = ":fast_forward: **Skipped** :thumbsup:"
NO_MATCH = ":x: **No matches**"
SEARCHING = ":trumpet: **Searching** :mag_right:"
PAUSE = "**Paused** :pause_button:"
STOP = "**Stopped** :stop_button:"
LOOP_ENABLED =... | radio_enabled = ':white_check_mark: **Radio enabled**'
radio_disabled = ':x: **Radio disabled**'
skipped = ':fast_forward: **Skipped** :thumbsup:'
no_match = ':x: **No matches**'
searching = ':trumpet: **Searching** :mag_right:'
pause = '**Paused** :pause_button:'
stop = '**Stopped** :stop_button:'
loop_enabled = '**Lo... |
def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('Erro: Por favor, digite um numero valido')
continue
except (KeyboardInterrupt):
print('Entrada interromepida pelo usuario')
return 0
else:
... | def leia_int(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('Erro: Por favor, digite um numero valido')
continue
except KeyboardInterrupt:
print('Entrada interromepida pelo usuario')
return 0
... |
#leia um numero inteiro e
#imprima a soma do sucessor de seu triplo com
#o antecessor de seu dobro
num=int(input("Informe um numero: "))
valor=((num*3)+1)+((num*2)-1)
print(f"A soma do sucessor de seu triplo com o antecessor de seu dobro eh {valor}") | num = int(input('Informe um numero: '))
valor = num * 3 + 1 + (num * 2 - 1)
print(f'A soma do sucessor de seu triplo com o antecessor de seu dobro eh {valor}') |
input = open('input.txt', 'r').read().split("\n")
depths = list(map(lambda s: int(s), input))
increases = 0;
for i in range(1, len(depths)):
if depths[i-2] + depths[i-1] + depths[i] > depths[i-3] + depths[i-2] + depths[i-1]:
increases += 1
print(increases) | input = open('input.txt', 'r').read().split('\n')
depths = list(map(lambda s: int(s), input))
increases = 0
for i in range(1, len(depths)):
if depths[i - 2] + depths[i - 1] + depths[i] > depths[i - 3] + depths[i - 2] + depths[i - 1]:
increases += 1
print(increases) |
class NasmPackage (Package):
def __init__ (self):
Package.__init__ (self, 'nasm', '2.10.07', sources = [
'http://www.nasm.us/pub/nasm/releasebuilds/2.10.07/nasm-%{version}.tar.xz'
])
NasmPackage ()
| class Nasmpackage(Package):
def __init__(self):
Package.__init__(self, 'nasm', '2.10.07', sources=['http://www.nasm.us/pub/nasm/releasebuilds/2.10.07/nasm-%{version}.tar.xz'])
nasm_package() |
'''
Description:
Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree ... | """
Description:
Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree ... |
number_of_drugs = 5
max_id = 1<<5
string_length = len("{0:#b}".format(max_id-1)) -2
EC50_for_0 = 0.75
EC50_for_1 = 1.3
f = lambda x: EC50_for_0 if x=='0' else EC50_for_1
print("[\n", end="")
for x in range(0,max_id):
gene_string = ("{0:0"+str(string_length)+"b}").format(x)
ec50 = list(map(f, list(gene_strin... | number_of_drugs = 5
max_id = 1 << 5
string_length = len('{0:#b}'.format(max_id - 1)) - 2
ec50_for_0 = 0.75
ec50_for_1 = 1.3
f = lambda x: EC50_for_0 if x == '0' else EC50_for_1
print('[\n', end='')
for x in range(0, max_id):
gene_string = ('{0:0' + str(string_length) + 'b}').format(x)
ec50 = list(map(f, list(ge... |
input1='389125467'
input2='496138527'
lowest=1
highest=1000000
class Node:
def __init__(self, val, next_node=None):
self.val=val
self.next=next_node
cups=list(input2)
cups=list(map(int,cups))
lookup_table={}
prev=None
# form linked list from the end node to beginning node
for i in range(len(cups)... | input1 = '389125467'
input2 = '496138527'
lowest = 1
highest = 1000000
class Node:
def __init__(self, val, next_node=None):
self.val = val
self.next = next_node
cups = list(input2)
cups = list(map(int, cups))
lookup_table = {}
prev = None
for i in range(len(cups) - 1, -1, -1):
new = node(cups[... |
def counting_sort(arr):
k = max(arr)
count = [0] * k + [0]
for x in arr:
count[x] += 1
for i in range(1, len(count)):
count[i] = count[i] + count[i-1]
output = [0] * len(arr)
for x in arr:
output[count[x]-1] = x
yield output, count[x]-1
count[x] -= 1
... | def counting_sort(arr):
k = max(arr)
count = [0] * k + [0]
for x in arr:
count[x] += 1
for i in range(1, len(count)):
count[i] = count[i] + count[i - 1]
output = [0] * len(arr)
for x in arr:
output[count[x] - 1] = x
yield (output, count[x] - 1)
count[x] -=... |
number = int(input())
if 100 <= number <= 200 or number == 0:
pass
else:
print('invalid') | number = int(input())
if 100 <= number <= 200 or number == 0:
pass
else:
print('invalid') |
def nth(test, items):
if test > 0:
test -= 1
else:
test = 0
for i, v in enumerate(items):
if i == test: return v
| def nth(test, items):
if test > 0:
test -= 1
else:
test = 0
for (i, v) in enumerate(items):
if i == test:
return v |
# Combinations
class Solution:
def combine(self, n, k):
ans = []
def helper(choices, start, count, ans):
if count == k:
# cloning the list here
ans.append(list(choices))
return
for i in range(start, n + 1):
ch... | class Solution:
def combine(self, n, k):
ans = []
def helper(choices, start, count, ans):
if count == k:
ans.append(list(choices))
return
for i in range(start, n + 1):
choices[count] = i
helper(choices, i + 1, ... |
class PyTime:
def printTime(self,input):
time_in_string = str(input)
length = len(time_in_string)
if length == 3:
hour,minute1,minute2 = time_in_string
hours = "0" + hour
minutes = minute1 + minute2
converted_time = self.calculate... | class Pytime:
def print_time(self, input):
time_in_string = str(input)
length = len(time_in_string)
if length == 3:
(hour, minute1, minute2) = time_in_string
hours = '0' + hour
minutes = minute1 + minute2
converted_time = self.calculateTime(ho... |
# create sets
names = {'anonymous','tazri','farha'};
extra_name = {'tazri','farha','troy'};
name_list = {'solus','xenon','neon'};
name_tuple = ('helium','hydrogen');
print("names : ",names);
# add focasa in names
print("add 'focasa' than set : ");
names.add("focasa");
print(names);
# update method
print("\n\nadd ext... | names = {'anonymous', 'tazri', 'farha'}
extra_name = {'tazri', 'farha', 'troy'}
name_list = {'solus', 'xenon', 'neon'}
name_tuple = ('helium', 'hydrogen')
print('names : ', names)
print("add 'focasa' than set : ")
names.add('focasa')
print(names)
print('\n\nadd extra_name in set with update method : ')
names.update(ext... |
user = int(input("ENTER NUMBER OF STUDENTS IN CLASS : "))
i = 1
marks = []
absent = []
# mark = marks.copy()
print("FOR ABSENT STUDENTS TYPE -1 AS MARKS")
for j in range(user):
student = int(input("ENTER MARKS OF STUDENT {} : ".format(i)))
if student == -1:
absent.append(i)
else:
... | user = int(input('ENTER NUMBER OF STUDENTS IN CLASS : '))
i = 1
marks = []
absent = []
print('FOR ABSENT STUDENTS TYPE -1 AS MARKS')
for j in range(user):
student = int(input('ENTER MARKS OF STUDENT {} : '.format(i)))
if student == -1:
absent.append(i)
else:
marks.append(student)
i += 1... |
def sum_func(num1,num2 =30,num3=40):
return num1 + num2 + num3
print(sum_func(10))
print(sum_func(10,20))
print(sum_func(10,20,30))
| def sum_func(num1, num2=30, num3=40):
return num1 + num2 + num3
print(sum_func(10))
print(sum_func(10, 20))
print(sum_func(10, 20, 30)) |
def variableName(name):
str_name = [i for i in str(name)]
non_acc_chars = [
" ",
">",
"<",
":",
"-",
"|",
".",
",",
"!",
"[",
"]",
"'",
"/",
"@",
"#",
"&",
"%",
"?",
... | def variable_name(name):
str_name = [i for i in str(name)]
non_acc_chars = [' ', '>', '<', ':', '-', '|', '.', ',', '!', '[', ']', "'", '/', '@', '#', '&', '%', '?', '*']
if str_name[0] in str([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]):
return False
for j in range(len(str_name)):
if str_name[j] in ... |
def palindrome(num):
return str(num) == str(num)[::-1]
# Bots are software programs that combine requests
# top Returns a reference to the top most element of the stack
def largest(bot, top):
z = 0
for i in range(top, bot, -1):
for j in range(top, bot, -1):
if palindrome(i ... | def palindrome(num):
return str(num) == str(num)[::-1]
def largest(bot, top):
z = 0
for i in range(top, bot, -1):
for j in range(top, bot, -1):
if palindrome(i * j):
if i * j > z:
z = i * j
return z
print(largest(100, 999)) |
#
# Copyright (c) 2020 Xilinx, Inc. All rights reserved.
# SPDX-License-Identifier: MIT
#
plnx_package_boot = True # Generate Package Boot Images
| plnx_package_boot = True |
#
# PySNMP MIB module AGG-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGG-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:15:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (dev_name, mate_host, unknown_device_trap_contents, pep_name, old_file, reason, result, mate_port, file, sb_producer_port, port, sn_name, host, my_host, minutes, new_file, sb_producer_host, my_port) = mibBuilder.importSymbols('AGGREGATED-EXT-MIB', 'devName', 'mateHost', 'unknownDeviceTrapContents', 'pepName', 'oldFile'... |
nums = [int(input()) for _ in range(int(input()))]
nums_count = [nums.count(a) for a in nums]
min_count, max_count - min(nums_count), max(nums_count)
min_num, max_num = 0, 0
a, b = 0, 0
for i in range(len(nums)):
if nums_count[i] > b:
max_num = nums[i]
elif nums_count[i] == b:
if nums[i] > max_num:
max_num... | nums = [int(input()) for _ in range(int(input()))]
nums_count = [nums.count(a) for a in nums]
(min_count, max_count - min(nums_count), max(nums_count))
(min_num, max_num) = (0, 0)
(a, b) = (0, 0)
for i in range(len(nums)):
if nums_count[i] > b:
max_num = nums[i]
elif nums_count[i] == b:
if nums[... |
# File: phishtank_consts.py
#
# Copyright (c) 2016-2021 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | phishtank_domain = 'http://www.phishtank.com'
phishtank_api_domain = 'https://checkurl.phishtank.com/checkurl/'
phishtank_app_key = 'app_key'
phishtank_msg_query_url = 'Querying URL: {query_url}'
phishtank_msg_connecting = 'Polling Phishtank site ...'
phishtank_service_succ_msg = 'Phishtank Service successfully execute... |
# -*- coding: utf-8 -*-
{
'name': 'Events',
'category': 'Website/Website',
'sequence': 166,
'summary': 'Publish events, sell tickets',
'website': 'https://www.odoo.com/page/events',
'description': "",
'depends': ['website', 'website_partner', 'website_mail', 'event'],
'data': [
... | {'name': 'Events', 'category': 'Website/Website', 'sequence': 166, 'summary': 'Publish events, sell tickets', 'website': 'https://www.odoo.com/page/events', 'description': '', 'depends': ['website', 'website_partner', 'website_mail', 'event'], 'data': ['data/event_data.xml', 'views/res_config_settings_views.xml', 'view... |
Ds = [1, 1.2, 1.5, 2, 4]
file_name = "f.csv"
f = open(file_name, 'r')
for depth in Ds:
print('\n\n DEALING WITH ALL D = ', depth-1)
DATA['below_depth'] = (depth - 1) * HEIGHT
for angle in range(2,90,1):
if angle %5 ==0: continue
if angle >= 50 and angle <=60: continue
f.close... | ds = [1, 1.2, 1.5, 2, 4]
file_name = 'f.csv'
f = open(file_name, 'r')
for depth in Ds:
print('\n\n DEALING WITH ALL D = ', depth - 1)
DATA['below_depth'] = (depth - 1) * HEIGHT
for angle in range(2, 90, 1):
if angle % 5 == 0:
continue
if angle >= 50 and angle <= 60:
c... |
class Db():
def __init__(self, section, host, wiki):
self.section = section
self.host = host
self.wiki = wiki
| class Db:
def __init__(self, section, host, wiki):
self.section = section
self.host = host
self.wiki = wiki |
# a dp method
class Solution:
def longestPalindrome(self, s: str) -> str:
size = len(s)
if size < 2:
return s
dp = [[False for _ in range(size)] for _ in range(size)]
maxLen = 1
start = 0
for i in range(size):
dp[i][i] = True
... | class Solution:
def longest_palindrome(self, s: str) -> str:
size = len(s)
if size < 2:
return s
dp = [[False for _ in range(size)] for _ in range(size)]
max_len = 1
start = 0
for i in range(size):
dp[i][i] = True
for j in range(1, siz... |
#Votes
Voter0 = int(input("Vote:"))
Voter1 = int(input("Vote:"))
Voter2 = int(input("Vote:"))
#Count
def count_votes():
#Accounts
voter0_account = 0
voter1_account = 0
voter2_account = 0
#Total
total = Voter0 + Voter1 + Voter2
#Return
if total > 1:
voter2_account =+ 1
... | voter0 = int(input('Vote:'))
voter1 = int(input('Vote:'))
voter2 = int(input('Vote:'))
def count_votes():
voter0_account = 0
voter1_account = 0
voter2_account = 0
total = Voter0 + Voter1 + Voter2
if total > 1:
voter2_account = +1
print(voter2_account)
else:
print(voter2_... |
otra_coordenada=(0, 1)
new=otra_coordenada.x
print(new) | otra_coordenada = (0, 1)
new = otra_coordenada.x
print(new) |
#!/usr/bin/env python
# coding: utf-8
# Given two arrays, write a function to compute their intersection.
#
# Example 1:
#
# Input: nums1 = [1,2,2,1], nums2 = [2,2]
# Output: [2]
# Example 2:
#
# Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
# Output: [9,4]
# In[1]:
def intersection(nums1, nums2):
return list(... | def intersection(nums1, nums2):
return list(set(nums1) & set(nums2))
print(intersection([4, 9, 5], [9, 4, 9, 8, 4]))
def intersection(nums1, nums2):
stack = []
for i in nums1:
if i not in stack and i in nums2:
stack.append(i)
return stack
print(intersection([4, 9, 5], [9, 4, 9, 8, 4... |
s = 0
for c in range(0, 6):
n = int(input('Digite numero inteiro: '))
if n%2==0:
s += n
print(f'A soma dos valores par e {s}') | s = 0
for c in range(0, 6):
n = int(input('Digite numero inteiro: '))
if n % 2 == 0:
s += n
print(f'A soma dos valores par e {s}') |
#stringCaps.py
msg = "john nash"
print(msg)
# ALL CAPS
msg_upper = msg.upper()
print(msg_upper)
# First Letter Of Each Word Capitalized
msg_title = msg.title()
print(msg_title) | msg = 'john nash'
print(msg)
msg_upper = msg.upper()
print(msg_upper)
msg_title = msg.title()
print(msg_title) |
def create_500M_file(name):
native.genrule(
name = name + "_target",
outs = [name],
output_to_bindir = 1,
cmd = "truncate -s 500M $@",
)
| def create_500_m_file(name):
native.genrule(name=name + '_target', outs=[name], output_to_bindir=1, cmd='truncate -s 500M $@') |
hotels = pois[pois['fclass']=='hotel']
citylondon = boroughs.loc[boroughs['name'] == 'City of London', 'geometry'].squeeze()
cityhotels = hotels[hotels.within(citylondon)]
[fig,ax] = plt.subplots(1, figsize=(12, 8))
base = boroughs.plot(color='lightblue', edgecolor='black',ax=ax);
cityhotels.plot(ax=ax, marker='o', co... | hotels = pois[pois['fclass'] == 'hotel']
citylondon = boroughs.loc[boroughs['name'] == 'City of London', 'geometry'].squeeze()
cityhotels = hotels[hotels.within(citylondon)]
[fig, ax] = plt.subplots(1, figsize=(12, 8))
base = boroughs.plot(color='lightblue', edgecolor='black', ax=ax)
cityhotels.plot(ax=ax, marker='o', ... |
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 |
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 |
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)) |
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... |
# 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: ')) |
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 |
#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) |
# 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... |
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) + ... |
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... |
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' |
# 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) |
# 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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.