content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# The following is the homework 4 for course MIS3500
# This assignment is Home Work 4
def file_read():
add = 0 # variable for adding total
counter = 0 # counter to understand how many counts are there
prices = []
buy = 0
iterative_profit = 0
total_profit = 0
first_buy = 0
file = open("... | def file_read():
add = 0
counter = 0
prices = []
buy = 0
iterative_profit = 0
total_profit = 0
first_buy = 0
file = open('AAPL.txt', 'r')
lines = file.readlines()
for line in lines:
price = float(line)
prices.append(price)
add += price
counter += 1... |
# -*- coding: utf-8 -*-
# @Time : 2021-07-31 19:34
# @Author : Ze Yi Sun
# @Site : BUAA
# @File : question.py
# @Software: PyCharm
class Question(object):
def __init__(self, statement: str):
self.statement = statement
def show(self):
return "None"
def check_correctness(self, answer: str) -... | class Question(object):
def __init__(self, statement: str):
self.statement = statement
def show(self):
return 'None'
def check_correctness(self, answer: str) -> bool:
return True
class Choicequestion(Question):
def __init__(self, statement: str, correct_answer: set):
... |
class Solution:
def countSubstrings(self, s: str) -> int:
p = len(s)
dp = [[i,i+1] for i in range(len(s))]
for i in range(1, len(s)):
for j in dp[i-1]:
if j-1 >= 0 and s[j-1] == s[i]:
p += 1
dp[i].append(j-1)
... | class Solution:
def count_substrings(self, s: str) -> int:
p = len(s)
dp = [[i, i + 1] for i in range(len(s))]
for i in range(1, len(s)):
for j in dp[i - 1]:
if j - 1 >= 0 and s[j - 1] == s[i]:
p += 1
dp[i].append(j - 1)
... |
'''
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
'''
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
#
r... | """
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
"""
class Solution:
def min_path_sum(self, grid: List[List[int]]) -> int:
row = len... |
artifacts = {
"io_bazel_rules_scala_scala_library": {
"artifact": "org.scala-lang:scala-library:2.11.12",
"sha256": "0b3d6fd42958ee98715ba2ec5fe221f4ca1e694d7c981b0ae0cd68e97baf6dce",
},
"io_bazel_rules_scala_scala_compiler": {
"artifact": "org.scala-lang:scala-compiler:2.11.12",
... | artifacts = {'io_bazel_rules_scala_scala_library': {'artifact': 'org.scala-lang:scala-library:2.11.12', 'sha256': '0b3d6fd42958ee98715ba2ec5fe221f4ca1e694d7c981b0ae0cd68e97baf6dce'}, 'io_bazel_rules_scala_scala_compiler': {'artifact': 'org.scala-lang:scala-compiler:2.11.12', 'sha256': '3e892546b72ab547cb77de4d840bcfd05... |
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
| alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien) |
# The opcode tables were taken from Mammon_'s Guide to Writing Disassemblers in Perl, You Morons!"
# and the bastard project. http://www.eccentrix.com/members/mammon/
INSTR_PREFIX = 0xF0000000
ADDRMETH_MASK = 0x00FF0000
ADDRMETH_A = 0x00010000 # Direct address with segment prefix
ADDRMETH_B = 0x00020000 # VEX.v... | instr_prefix = 4026531840
addrmeth_mask = 16711680
addrmeth_a = 65536
addrmeth_b = 131072
addrmeth_c = 196608
addrmeth_d = 262144
addrmeth_e = 327680
addrmeth_f = 393216
addrmeth_g = 458752
addrmeth_h = 524288
addrmeth_i = 589824
addrmeth_j = 655360
addrmeth_l = 720896
addrmeth_m = 786432
addrmeth_n = 851968
addrmeth_o... |
class StubCursor(object):
column = 0
row = 0
def __iter__(self):
return iter([self.row, self.column])
@property
def coords(self):
return self.row, self.column
@coords.setter
def coords(self, coords):
self.row, self.column = coords
| class Stubcursor(object):
column = 0
row = 0
def __iter__(self):
return iter([self.row, self.column])
@property
def coords(self):
return (self.row, self.column)
@coords.setter
def coords(self, coords):
(self.row, self.column) = coords |
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
def sub(self):
return self.a - self.b
def add2(self, a, b):
... | class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
def sub(self):
return self.a - self.b
def add2(self, a, b):
... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'verbose_libraries_build%': 0,
'instrumented_libraries_jobs%': 1,
'instrumented_libraries_cc%': '<!(cd <(DEPTH) && pwd -P)/<(m... | {'variables': {'verbose_libraries_build%': 0, 'instrumented_libraries_jobs%': 1, 'instrumented_libraries_cc%': '<!(cd <(DEPTH) && pwd -P)/<(make_clang_dir)/bin/clang', 'instrumented_libraries_cxx%': '<!(cd <(DEPTH) && pwd -P)/<(make_clang_dir)/bin/clang++'}, 'libdir': 'lib', 'ubuntu_release': '<!(lsb_release -cs)', 'co... |
# Write a Python program to add an item in a tuple
tuplex = ('physics', 'chemistry', 1997, 2000)
tuple = tuplex + (5,)
print(tuple)
#2nd method
tuple = tuplex[:3] + (23,56,7)
print(tuple)
#3rd method
listx = list(tuplex)
listx.append(30)
tuplex = tuple(listx)
print(tuplex) | tuplex = ('physics', 'chemistry', 1997, 2000)
tuple = tuplex + (5,)
print(tuple)
tuple = tuplex[:3] + (23, 56, 7)
print(tuple)
listx = list(tuplex)
listx.append(30)
tuplex = tuple(listx)
print(tuplex) |
contador = 0
file = open("funciones_matematicas.py","w")
funcs = {}
def print_contador():
print(contador)
def aumentar_contador():
global contador
contador += 1
def crear_funcion():
ecuacion = input("Ingrese ecuacion: ")
def agregar_funcion():
f = open("funciones_matematicas.py","w")
ecuacion = input("Ingrese ... | contador = 0
file = open('funciones_matematicas.py', 'w')
funcs = {}
def print_contador():
print(contador)
def aumentar_contador():
global contador
contador += 1
def crear_funcion():
ecuacion = input('Ingrese ecuacion: ')
def agregar_funcion():
f = open('funciones_matematicas.py', 'w')
ecuac... |
N = int(input())
a = sorted(map(int, input().split()), reverse=True)
print(sum([a[n] for n in range(1, N * 2, 2)]))
| n = int(input())
a = sorted(map(int, input().split()), reverse=True)
print(sum([a[n] for n in range(1, N * 2, 2)])) |
def solution(lottos, win_nums):
answer = []
zeros=0
for i in lottos:
if(i==0) : zeros+=1
correct = list(set(lottos).intersection(set(win_nums)))
_dict = {6:1,5:2,4:3,3:4,2:5,1:6,0:6}
answer.append(_dict[len(correct)+zeros])
answer.append(_dict[len(correct)])
return answer
| def solution(lottos, win_nums):
answer = []
zeros = 0
for i in lottos:
if i == 0:
zeros += 1
correct = list(set(lottos).intersection(set(win_nums)))
_dict = {6: 1, 5: 2, 4: 3, 3: 4, 2: 5, 1: 6, 0: 6}
answer.append(_dict[len(correct) + zeros])
answer.append(_dict[len(corre... |
class Solution:
def solve(self, path):
ans = []
for part in path:
if part == "..":
if ans: ans.pop()
elif part != ".": ans.append(part)
return ans
| class Solution:
def solve(self, path):
ans = []
for part in path:
if part == '..':
if ans:
ans.pop()
elif part != '.':
ans.append(part)
return ans |
# https://www.codewars.com/kata/523a86aa4230ebb5420001e1
def letterCounter(word):
letters = {}
for letter in word:
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
return letters
def anagrams(word, words):
anag = []
wordMap = letterCounter... | def letter_counter(word):
letters = {}
for letter in word:
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
return letters
def anagrams(word, words):
anag = []
word_map = letter_counter(word)
for w in words:
if wordMap == lette... |
# %%
def Naive(N):
is_prime = True
if N <= 1 :
is_prime = False
else:
for i in range(2, N, 1):
if N % i == 0:
is_prime = False
return(is_prime)
def main():
N = 139
print(f"{N} prime ? : {Naive(N)}")
if __name__=="__main__":
main()... | def naive(N):
is_prime = True
if N <= 1:
is_prime = False
else:
for i in range(2, N, 1):
if N % i == 0:
is_prime = False
return is_prime
def main():
n = 139
print(f'{N} prime ? : {naive(N)}')
if __name__ == '__main__':
main() |
'''
313B. Ilya and Queries
dp, 1300, https://codeforces.com/contest/313/problem/B
'''
sequence = input()
length = len(sequence)
m = int(input())
dp = [0] * length
if sequence[0] == sequence[1]:
dp[1] = 1
for i in range(1, length-1):
if sequence[i] == sequence[i+1]:
dp[i+1] = dp[i] + 1
else:
... | """
313B. Ilya and Queries
dp, 1300, https://codeforces.com/contest/313/problem/B
"""
sequence = input()
length = len(sequence)
m = int(input())
dp = [0] * length
if sequence[0] == sequence[1]:
dp[1] = 1
for i in range(1, length - 1):
if sequence[i] == sequence[i + 1]:
dp[i + 1] = dp[i] + 1
else:
... |
def has_adjacent_digits(password):
digit = password % 10
while password != 0:
password = password // 10
if digit == password % 10:
return True
else:
digit = password % 10
return False
def has_two_adjacent_digits(password):
adjacent_digits = {}
digit ... | def has_adjacent_digits(password):
digit = password % 10
while password != 0:
password = password // 10
if digit == password % 10:
return True
else:
digit = password % 10
return False
def has_two_adjacent_digits(password):
adjacent_digits = {}
digit =... |
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]
| def all_perms(str):
if len(str) <= 1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm) + 1):
yield (perm[:i] + str[0:1] + perm[i:]) |
# Copyright 2010 Google 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 applicable law or agreed to ... | def riff_wave__checks(WAVE_block):
fmt_chunk = None
fact_chunk = None
data_chunk = None
if 'fmt ' not in WAVE_block._named_chunks:
WAVE_block.warnings.append('expected one "fmt " block, found none')
else:
fmt_chunk = WAVE_block._named_chunks['fmt '][0]
if 'fact' not in WAVE_block... |
#!/usr/bin/env python
# coding: utf-8
# # 7: Dictionaries Solutions
#
# 1. Below are two lists, `keys` and `values`. Combine these into a single dictionary.
#
# ```python
# keys = ['Ben', 'Ethan', 'Stefani']
# values = [1, 29, 28]
# ```
# Expected output:
# ```python
# {'Ben': 1, 'Ethan': 29, 'Stefani': 28}
# ```
# ... | keys = ['Ben', 'Ethan', 'Stefani']
values = [1, 29, 28]
my_dict = dict(zip(keys, values))
print(my_dict)
dict1 = {'Ben': 1, 'Ethan': 29}
dict2 = {'Stefani': 28, 'Madonna': 16, 'RuPaul': 17}
"\nIn Python 3.9+, we can use `dict3 = dict1 | dict2`\nIn Python 3.5+ we can use `dict3 = {**dict1, **dict2}`\nBut I'll show you t... |
np = int(input('Say a number: '))
som = 0
for i in range(1,np):
if np%i == 0:
print (i),
som += i
if som == np:
print('It is a perfect number!')
else:
print ('It is not a perfect number')
| np = int(input('Say a number: '))
som = 0
for i in range(1, np):
if np % i == 0:
(print(i),)
som += i
if som == np:
print('It is a perfect number!')
else:
print('It is not a perfect number') |
stormtrooper = r'''
,ooo888888888888888oooo,
o8888YYYYYY77iiiiooo8888888o
8888YYYY77iiYY8888888888888888
[88YYY77iiY88888888888888888888]
88YY7iYY888888888888888888888888
... | stormtrooper = "\n ,ooo888888888888888oooo,\n o8888YYYYYY77iiiiooo8888888o\n 8888YYYY77iiYY8888888888888888\n [88YYY77iiY88888888888888888888]\n 88YY7iYY888888888888888888888888\n ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeZeroSumSublists(self, head: ListNode) -> ListNode:
stack = []
cur = head
while cur:
stack.append(cur)
... | class Solution:
def remove_zero_sum_sublists(self, head: ListNode) -> ListNode:
stack = []
cur = head
while cur:
stack.append(cur)
s = 0
for i in range(len(stack) - 1, -1, -1):
s += stack[i].val
if s == 0:
... |
# add your QUIC implementation here
IMPLEMENTATIONS = { # name => [ docker image, role ]; role: 0 == 'client', 1 == 'server', 2 == both
"quicgo": {"url": "martenseemann/quic-go-interop:latest", "role": 2},
"quicly": {"url": "janaiyengar/quicly:interop", "role": 2},
"ngtcp2": {"url": "ngtcp2/ngtcp2-interop:... | implementations = {'quicgo': {'url': 'martenseemann/quic-go-interop:latest', 'role': 2}, 'quicly': {'url': 'janaiyengar/quicly:interop', 'role': 2}, 'ngtcp2': {'url': 'ngtcp2/ngtcp2-interop:latest', 'role': 2}, 'quant': {'url': 'ntap/quant:interop', 'role': 2}, 'mvfst': {'url': 'lnicco/mvfst-qns:latest', 'role': 2}, 'q... |
#
# PySNMP MIB module ADTRAN-AOS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS
# Produced by pysmi-0.3.4 at Mon Apr 29 16:58:35 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, 09:... | (ad_shared, ad_identity_shared) = mibBuilder.importSymbols('ADTRAN-MIB', 'adShared', 'adIdentityShared')
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_... |
chars_to_remove = ["-", ",", ".", "!", "?"]
with open('text.txt') as text_file:
for i, line in enumerate(text_file):
if i % 2 == 0:
for char in line:
if char in chars_to_remove:
line = line.replace(char, '@')
print(' '.join(reversed(line.split()))... | chars_to_remove = ['-', ',', '.', '!', '?']
with open('text.txt') as text_file:
for (i, line) in enumerate(text_file):
if i % 2 == 0:
for char in line:
if char in chars_to_remove:
line = line.replace(char, '@')
print(' '.join(reversed(line.split())... |
# (C) Datadog, Inc. 2019
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
STANDARD = [
'sap_hana.backup.latest',
'sap_hana.connection.idle',
'sap_hana.connection.open',
'sap_hana.connection.running',
'sap_hana.cpu.service.utilized',
'sap_hana.disk.free',
'sap... | standard = ['sap_hana.backup.latest', 'sap_hana.connection.idle', 'sap_hana.connection.open', 'sap_hana.connection.running', 'sap_hana.cpu.service.utilized', 'sap_hana.disk.free', 'sap_hana.disk.size', 'sap_hana.disk.used', 'sap_hana.disk.utilized', 'sap_hana.file.service.open', 'sap_hana.memory.row_store.free', 'sap_h... |
def boxes_packing(length, width, height):
total=[sorted((i,j,k)) for i,j,k in zip(length, width, height)]
res=sorted(total, key=lambda x: -min(x))
for i,j in enumerate(res[1:]):
if any((k-l)<=0 for k,l in zip(res[i], j)):
return False
return True | def boxes_packing(length, width, height):
total = [sorted((i, j, k)) for (i, j, k) in zip(length, width, height)]
res = sorted(total, key=lambda x: -min(x))
for (i, j) in enumerate(res[1:]):
if any((k - l <= 0 for (k, l) in zip(res[i], j))):
return False
return True |
{
'includes': [ '../common.gyp' ],
'targets': [
{
'target_name': 'libjpeg',
'type': 'static_library',
'include_dirs': [
'.',
],
'sources': [
'ckconfig.c',
'jcapimin.c',
'jcapistd.c',
'jccoefct.c',
'jccolor.c',
'jcdctmgr.c',
... | {'includes': ['../common.gyp'], 'targets': [{'target_name': 'libjpeg', 'type': 'static_library', 'include_dirs': ['.'], 'sources': ['ckconfig.c', 'jcapimin.c', 'jcapistd.c', 'jccoefct.c', 'jccolor.c', 'jcdctmgr.c', 'jchuff.c', 'jcinit.c', 'jcmainct.c', 'jcmarker.c', 'jcmaster.c', 'jcomapi.c', 'jcparam.c', 'jcphuff.c', ... |
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'target_defaults': {
'defines': [
'_LIB',
'XML_STATIC', # Compile for static linkage.
],
'include_dirs': [
'files/lib'... | {'target_defaults': {'defines': ['_LIB', 'XML_STATIC'], 'include_dirs': ['files/lib'], 'dependencies': []}, 'conditions': [['OS=="linux" or OS=="freebsd"', {'targets': [{'target_name': 'expat', 'type': 'settings', 'link_settings': {'libraries': ['-lexpat']}}]}, {'targets': [{'target_name': 'expat', 'type': '<(library)'... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
_SNAKE_TO_CAMEL_CASE_TABLE = {
"acceleration_status": "accelerationStatus",
"accelerator_arn": "acceleratorArn",
"accept_st... | _snake_to_camel_case_table = {'acceleration_status': 'accelerationStatus', 'accelerator_arn': 'acceleratorArn', 'accept_status': 'acceptStatus', 'acceptance_required': 'acceptanceRequired', 'access_log_settings': 'accessLogSettings', 'access_logs': 'accessLogs', 'access_policies': 'accessPolicies', 'access_policy': 'ac... |
N, *S = open(0).read().split()
t = 1
f = 1
for s in S:
if s == 'AND':
f = t + f * 2
elif s == 'OR':
t = t * 2 + f
print(t)
| (n, *s) = open(0).read().split()
t = 1
f = 1
for s in S:
if s == 'AND':
f = t + f * 2
elif s == 'OR':
t = t * 2 + f
print(t) |
# %% [1221. Split a String in Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings/)
class Solution:
def balancedStringSplit(self, s: str) -> int:
res = cnt = 0
for c in s:
cnt += (c == "L") * 2 - 1
res += not cnt
return res
| class Solution:
def balanced_string_split(self, s: str) -> int:
res = cnt = 0
for c in s:
cnt += (c == 'L') * 2 - 1
res += not cnt
return res |
words = ['cat', 'window', "defenestrate"]
for w in words :
print(w, len(w))
users = ['A', "B", "C"]
for i in users :
print(i)
for i in range(5):
print(i) | words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
users = ['A', 'B', 'C']
for i in users:
print(i)
for i in range(5):
print(i) |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Valid Braces
#Problem level: 4 kyu
valid = {'(': ')', '[': ']', '{': '}'}
def validBraces(string):
li=[]
for item in string:
if item in valid: li.append(item)
elif li and valid[li[-1]] == item: li.pop()
else: return False
r... | valid = {'(': ')', '[': ']', '{': '}'}
def valid_braces(string):
li = []
for item in string:
if item in valid:
li.append(item)
elif li and valid[li[-1]] == item:
li.pop()
else:
return False
return False if li else True |
summultiples = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
summultiples += i
print(summultiples)
| summultiples = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
summultiples += i
print(summultiples) |
def say_hello(name: str = 'Lucas'):
print(f'Hello {name} ')
def ask_age():
user_age = input('Age?')
return user_age
def say_hello_mp(name, age_user=25):
print(f'Hello {name} {age_user}')
if __name__ == '__main__':
say_hello()
say_hello(123)
print(say_hello('Pierre'))
say_hello_m... | def say_hello(name: str='Lucas'):
print(f'Hello {name} ')
def ask_age():
user_age = input('Age?')
return user_age
def say_hello_mp(name, age_user=25):
print(f'Hello {name} {age_user}')
if __name__ == '__main__':
say_hello()
say_hello(123)
print(say_hello('Pierre'))
say_hello_mp(age_use... |
def foo(t1, t2, t3):
return str(t1)+str(t2)
res = foo(t1,t2,t3)
print("Testing output!")
| def foo(t1, t2, t3):
return str(t1) + str(t2)
res = foo(t1, t2, t3)
print('Testing output!') |
'''
@file: __init__.py.py
@author: qxLiu
@time: 2020/3/14 9:37
'''
| """
@file: __init__.py.py
@author: qxLiu
@time: 2020/3/14 9:37
""" |
def set(name):
ret = {
'name': name,
'changes': {},
'result': False,
'comment': ''
}
current_name = __salt__['c_hostname.get_hostname']()
if name == current_name:
ret['result'] = True
ret['comment'] = "Hostname \"{0}\" already set.".format(name)
r... | def set(name):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
current_name = __salt__['c_hostname.get_hostname']()
if name == current_name:
ret['result'] = True
ret['comment'] = 'Hostname "{0}" already set.'.format(name)
return ret
if __opts__['test'] is True... |
class Solution:
def canCross(self, stones: List[int]) -> bool:
n = len(stones)
# dp[i][j] := True if a frog can make a size j jump to stones[i]
dp = [[False] * (n + 1) for _ in range(n)]
dp[0][0] = True
for i in range(1, n):
for j in range(i):
k = stones[i] - stones[j]
if k ... | class Solution:
def can_cross(self, stones: List[int]) -> bool:
n = len(stones)
dp = [[False] * (n + 1) for _ in range(n)]
dp[0][0] = True
for i in range(1, n):
for j in range(i):
k = stones[i] - stones[j]
if k > n:
con... |
class PPSTimingCalibrationModeEnum:
CondDB = 0
JSON = 1
SQLite = 2
| class Ppstimingcalibrationmodeenum:
cond_db = 0
json = 1
sq_lite = 2 |
a = input()
i = ord(a)
for i in range(i-96):
print(chr(i+97),end=" ")
| a = input()
i = ord(a)
for i in range(i - 96):
print(chr(i + 97), end=' ') |
n=int(input("From number"))
n1=int(input("To number"))
for i in range(n,n1):
for j in range(2,i):
if i%j==0:
break
else:
print(i)
| n = int(input('From number'))
n1 = int(input('To number'))
for i in range(n, n1):
for j in range(2, i):
if i % j == 0:
break
else:
print(i) |
# Recursive implementation to find the gcd (greatest common divisor) of two integers using the euclidean algorithm.
# For more than two numbers, e.g. three, you can box it like this: gcd(a,gcd(b,greatest_common_divisor.c)) etc.
# This runs in O(log(n)) where n is the maximum of a and b.
# :param a: the first integer
# ... | def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b) |
def _build(**kwargs):
kwargs.setdefault("mac_src", '00.00.00.00.00.01')
kwargs.setdefault("mac_dst", '00.00.00.00.00.02')
kwargs.setdefault("mac_src_step", '00.00.00.00.00.01')
kwargs.setdefault("mac_dst_step", '00.00.00.00.00.01')
kwargs.setdefault("arp_src_hw_addr", '01.00.00.00.00.01')
kwarg... | def _build(**kwargs):
kwargs.setdefault('mac_src', '00.00.00.00.00.01')
kwargs.setdefault('mac_dst', '00.00.00.00.00.02')
kwargs.setdefault('mac_src_step', '00.00.00.00.00.01')
kwargs.setdefault('mac_dst_step', '00.00.00.00.00.01')
kwargs.setdefault('arp_src_hw_addr', '01.00.00.00.00.01')
kwargs... |
#Weird algorithm for matrix multiplication. just addition will produce result matrix
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
row = [0] * n
col = [0] * m
ans = 0
for r,c in indices:
row[r] += 1
col[c] += 1
fo... | class Solution:
def odd_cells(self, n: int, m: int, indices: List[List[int]]) -> int:
row = [0] * n
col = [0] * m
ans = 0
for (r, c) in indices:
row[r] += 1
col[c] += 1
for i in range(n):
for j in range(m):
ans += (row[i] +... |
unavailable_dict = {
"0": {
("11", "12", "13"): [
"message_1",
"message_4"
],
("21", "22", "23"): [
"message_3",
"message_6"
],
("24",): [
"message_2",
"message_5"
],
("0", "blank",): [
... | unavailable_dict = {'0': {('11', '12', '13'): ['message_1', 'message_4'], ('21', '22', '23'): ['message_3', 'message_6'], ('24',): ['message_2', 'message_5'], ('0', 'blank'): ['message_7']}, '1': {('11', '12', '13'): ['message_8'], ('21', '22', '23'): ['message_9'], ('0', 'blank'): ['message_10']}, '2': {('0', 'blank')... |
# In theory, RightScale's API is discoverable through ``links`` in responses.
# In practice, we have to help our robots along with the following hints:
RS_DEFAULT_ACTIONS = {
'index': {
'http_method': 'get',
},
'show': {
'http_method': 'get',
'extra_path':... | rs_default_actions = {'index': {'http_method': 'get'}, 'show': {'http_method': 'get', 'extra_path': '/%(res_id)s'}, 'create': {'http_method': 'post'}, 'update': {'http_method': 'put', 'extra_path': '/%(res_id)s'}, 'destroy': {'http_method': 'delete', 'extra_path': '/%(res_id)s'}}
alert_actions = {'disable': {'http_meth... |
'''
Created on Oct 1, 2011
@author: jose
'''
| """
Created on Oct 1, 2011
@author: jose
""" |
# Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
def __str__(self):
return "({} -> {})".format(self.label,
[nb.label for nb in self.neighbors])
def __repr__(self):
... | class Undirectedgraphnode:
def __init__(self, x):
self.label = x
self.neighbors = []
def __str__(self):
return '({} -> {})'.format(self.label, [nb.label for nb in self.neighbors])
def __repr__(self):
return self.__str__()
class Solution:
def clone_graph(self, node):
... |
class Salary:
def __init__(self,pay,bonus):
self.pay=pay
self.bonus=bonus
def annual(self):
return (self.pay*12)+self.bonus
class employee:
def __init__(self,name,age,pay,bonus):
self.name=name
self.age=age
self.pay=pay
self.bonus=bonus
... | class Salary:
def __init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus
def annual(self):
return self.pay * 12 + self.bonus
class Employee:
def __init__(self, name, age, pay, bonus):
self.name = name
self.age = age
self.pay = pay
self.bonus... |
# Christian Piper
# 11/11/19
# This will accept algebra equations on the input and solve for the variable
def main():
equation = input("Input your equation: ")
variable = input("Input the variable to be solved for: ")
solveAlgebraEquation(equation, variable)
def solveAlgebraEquation(equation, variable):
... | def main():
equation = input('Input your equation: ')
variable = input('Input the variable to be solved for: ')
solve_algebra_equation(equation, variable)
def solve_algebra_equation(equation, variable):
collector = ['', '', '', '', '', '']
iteration = 0
for char in equation:
if char == ... |
# Location of exported xml playlist from itunes
# Update username and directory to their appropriate path e.g C:/users/bob/desktop/file.xml
xml_playlist_loc = 'C:/users/username/directory/_MyMusic_.xml'
# name of user directory where your Music folder is located
# example: C:/users/bob/music/itunes
music_folder_dir = '... | xml_playlist_loc = 'C:/users/username/directory/_MyMusic_.xml'
music_folder_dir = 'name' |
def backtickify(s):
return '`{}`'.format(s)
def bind_exercises(g, exercises, start=1):
for i, ex in enumerate(exercises):
qno = i + start
varname = 'q{}'.format(qno)
assert varname not in g
g[varname] = ex
yield varname
| def backtickify(s):
return '`{}`'.format(s)
def bind_exercises(g, exercises, start=1):
for (i, ex) in enumerate(exercises):
qno = i + start
varname = 'q{}'.format(qno)
assert varname not in g
g[varname] = ex
yield varname |
#
# PySNMP MIB module RBN-CONFIG-FILE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-CONFIG-FILE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:44:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, constraints_union, value_size_constraint) ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
dummy = ListNode(-1)
dummy.next = head
def t(d):
if d.ne... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def remove_elements(self, head: ListNode, val: int) -> ListNode:
dummy = list_node(-1)
dummy.next = head
def t(d):
if d.next:
if d.next.va... |
# nxn chessboard
n = 10
# number of dragons on the chessboard
dragons = 10
solution = [-1]*n
captured = [[0 for i in range(n)] for i in range(n)]
number = 0
local_calls = 0
total_calls = 0
def init():
global captured
def isCaptured(x, y):
global captured
return captured[x][y]
def capture(... | n = 10
dragons = 10
solution = [-1] * n
captured = [[0 for i in range(n)] for i in range(n)]
number = 0
local_calls = 0
total_calls = 0
def init():
global captured
def is_captured(x, y):
global captured
return captured[x][y]
def capture(x, y):
for i in range(n):
captured[i][y] += 1
ca... |
class ApiException(Exception):
pass
class Forbidden(ApiException):
def __init__(self, message):
self.message = message
self.status_code = 403
class NotFound(ApiException):
def __init__(self, message):
self.message = message
self.status_code = 404
class BadRequest(A... | class Apiexception(Exception):
pass
class Forbidden(ApiException):
def __init__(self, message):
self.message = message
self.status_code = 403
class Notfound(ApiException):
def __init__(self, message):
self.message = message
self.status_code = 404
class Badrequest(ApiExce... |
#
# Copyright (C) 2018 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | def test(name, input0, input1, input2, output0, input0_data, input1_data, input2_data, output_data):
model = model().Operation('SELECT', input0, input1, input2).To(output0)
quant8 = data_type_converter().Identify({input1: ['TENSOR_QUANT8_ASYMM', 1.5, 129], input2: ['TENSOR_QUANT8_ASYMM', 0.5, 127], output0: ['T... |
NAME='nagios'
CFLAGS = []
LDFLAGS = []
LIBS = []
GCC_LIST = ['nagios']
| name = 'nagios'
cflags = []
ldflags = []
libs = []
gcc_list = ['nagios'] |
class Solution:
def find_permutation(self, S):
S = sorted(S)
self.res = []
visited = [False] * len(S)
self.find_permutationUtil(S, visited, '')
return self.res
def find_permutationUtil(self, S, visited, str):
if len(str) == len(S):
self.res.append(str... | class Solution:
def find_permutation(self, S):
s = sorted(S)
self.res = []
visited = [False] * len(S)
self.find_permutationUtil(S, visited, '')
return self.res
def find_permutation_util(self, S, visited, str):
if len(str) == len(S):
self.res.append(s... |
s = set(map(int, input().split()))
print(s)
print("max is: ",max(s))
print("min is: ",min(s))
| s = set(map(int, input().split()))
print(s)
print('max is: ', max(s))
print('min is: ', min(s)) |
def transact(environment, t, to_agent, from_agent, settlement_type, amount, description):
"Function that ensures a correct transaction between agents"
environment.measurement['period'].append(t)
environment.measurement['to_agent'].append(to_agent)
environment.measurement['from_agent'].append(from_agent)... | def transact(environment, t, to_agent, from_agent, settlement_type, amount, description):
"""Function that ensures a correct transaction between agents"""
environment.measurement['period'].append(t)
environment.measurement['to_agent'].append(to_agent)
environment.measurement['from_agent'].append(from_ag... |
class NSGA2:
def __init__(self, initializer, evaluator, selector, crossover, mutator, stopper):
self.initializer = initializer
self.evaluator = evaluator
self.selector = selector
self.crossover = crossover
self.mutator = mutator
self.stopper = stopper
self.po... | class Nsga2:
def __init__(self, initializer, evaluator, selector, crossover, mutator, stopper):
self.initializer = initializer
self.evaluator = evaluator
self.selector = selector
self.crossover = crossover
self.mutator = mutator
self.stopper = stopper
self.po... |
class RetrievalError(Exception):
pass
class SetterError(Exception):
pass
class ControlError(SetterError):
pass
class AuthentificationError(Exception):
pass
class TemporaryAuthentificationError(AuthentificationError):
pass
class APICompatibilityError(Exception):
pass
class APIError(Ex... | class Retrievalerror(Exception):
pass
class Settererror(Exception):
pass
class Controlerror(SetterError):
pass
class Authentificationerror(Exception):
pass
class Temporaryauthentificationerror(AuthentificationError):
pass
class Apicompatibilityerror(Exception):
pass
class Apierror(Exceptio... |
# Based on largest_rectangle_in_histagram 84
def maximal_rectrangle_in_matrix(matrix):
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
# Append extra 0 to the end, to mark the end of the curr row
curr_row = [0] * (len(matrix[0]) + 1)
ans = 0
for row in range(len(matrix)):
for ... | def maximal_rectrangle_in_matrix(matrix):
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
curr_row = [0] * (len(matrix[0]) + 1)
ans = 0
for row in range(len(matrix)):
for column in range(len(matrix[0])):
if matrix[row][column] == '1':
curr_row[column] += ... |
# A program to check if the number is odd or even
def even_or_odd(num):
if num == "q":
return "Invalid"
elif num % 2 == 0:
return "Even"
else:
return "Odd"
while True:
try:
user_input = float(input("Enter then number you would like to check is odd or even"))
except... | def even_or_odd(num):
if num == 'q':
return 'Invalid'
elif num % 2 == 0:
return 'Even'
else:
return 'Odd'
while True:
try:
user_input = float(input('Enter then number you would like to check is odd or even'))
except ValueError or TypeError:
user_input = 'q'
... |
class Solution:
def minCut(self, s: str) -> int:
if not s:
return 0
memo = dict()
def helper(l,r):
if l > r:
return 0
minVal = float('inf')
for i in range(l,r+1,1):
strs = s[l:i+1]
if strs == str... | class Solution:
def min_cut(self, s: str) -> int:
if not s:
return 0
memo = dict()
def helper(l, r):
if l > r:
return 0
min_val = float('inf')
for i in range(l, r + 1, 1):
strs = s[l:i + 1]
if s... |
'''https://practice.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1
Cyclically rotate an array by one
Basic Accuracy: 64.05% Submissions: 66795 Points: 1
Given an array, rotate the array by one position in clock-wise direction.
Example 1:
Input:
N = 5
A[] = {1, 2, 3, 4, 5}
Output:
5 1 2 3 4
E... | """https://practice.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1
Cyclically rotate an array by one
Basic Accuracy: 64.05% Submissions: 66795 Points: 1
Given an array, rotate the array by one position in clock-wise direction.
Example 1:
Input:
N = 5
A[] = {1, 2, 3, 4, 5}
Output:
5 1 2 3 4
E... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def max_min(v):
m_min, m_max = min(v[0], v[-1]), max(v[0], v[-1])
for i in v[1:len(v)-1]:
if i<m_min:
m_min = i
elif i > m_max:
m_max = i
return m_min, m_max
if __name__ == '__main__':
m_min, m_max = max_min([9, ... | def max_min(v):
(m_min, m_max) = (min(v[0], v[-1]), max(v[0], v[-1]))
for i in v[1:len(v) - 1]:
if i < m_min:
m_min = i
elif i > m_max:
m_max = i
return (m_min, m_max)
if __name__ == '__main__':
(m_min, m_max) = max_min([9, 3, 4, 7, 2, 0])
print(m_min, m_max) |
string = [x for x in input()]
string_list_after = []
index = 0
power = 0
for el in range(len(string)):
if string[index] == ">":
expl = int(string[el + 1])
power += int(expl)
string.pop(el+1)
string.append('')
power -= 1
while power > 0:
index = el
... | string = [x for x in input()]
string_list_after = []
index = 0
power = 0
for el in range(len(string)):
if string[index] == '>':
expl = int(string[el + 1])
power += int(expl)
string.pop(el + 1)
string.append('')
power -= 1
while power > 0:
index = el
... |
#A more compact version of the algorithm that can be executed parallelly.
list1 = [0x58, 0x76, 0x54, 0x3a, 0xbe, 0x58, 0x76, 0x54, 0xbe, 0xcd, 0x45, 0x66, 0x85, 0x65]
# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
# Par=4: bulk bulk bulk bulk bulk bulk bulk bulk bu... | list1 = [88, 118, 84, 58, 190, 88, 118, 84, 190, 205, 69, 102, 133, 101]
def parallel_roling_mac_hash(list, par):
multiplier = 16777619
hash = [0 for x in range(par)]
mult_powers = [multiplier ** (x + 1) for x in range(par)]
list_length = len(list)
bulk = list_length // par
rest = list_length %... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# In[4]:
def fib(n):
a, b = 0,1
while a < n:
print(a)
a, b = b, a + b
# In[8]:
def primos(n):
numbers = [True, True] + [True] * (n-1)
last_prime_number = 2
i = last_prime_number
while last_prime_number**2 <= n:
... | def fib(n):
(a, b) = (0, 1)
while a < n:
print(a)
(a, b) = (b, a + b)
def primos(n):
numbers = [True, True] + [True] * (n - 1)
last_prime_number = 2
i = last_prime_number
while last_prime_number ** 2 <= n:
i += last_prime_number
while i <= n:
numbers[... |
class CliError(RuntimeError):
pass
| class Clierror(RuntimeError):
pass |
#!/usr/bin/env python
__author__ = "Giuseppe Chiesa"
__copyright__ = "Copyright 2017-2021, Giuseppe Chiesa"
__credits__ = ["Giuseppe Chiesa"]
__license__ = "BSD"
__maintainer__ = "Giuseppe Chiesa"
__email__ = "mail@giuseppechiesa.it"
__status__ = "PerpetualBeta"
def write_with_modecheck(file_handler, data):
if f... | __author__ = 'Giuseppe Chiesa'
__copyright__ = 'Copyright 2017-2021, Giuseppe Chiesa'
__credits__ = ['Giuseppe Chiesa']
__license__ = 'BSD'
__maintainer__ = 'Giuseppe Chiesa'
__email__ = 'mail@giuseppechiesa.it'
__status__ = 'PerpetualBeta'
def write_with_modecheck(file_handler, data):
if file_handler.mode == 'w':... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class BaseEmitter(object):
'''Base for emitters of the *data-migrator*.
Attributes:
manager (BaseManager): reference to the manager that is calling this
emitter to export objects from that manager
model_class (Model): reference to the ... | class Baseemitter(object):
"""Base for emitters of the *data-migrator*.
Attributes:
manager (BaseManager): reference to the manager that is calling this
emitter to export objects from that manager
model_class (Model): reference to the model linked to the class
extension (str... |
class Stack(object):
def __init__(self):
self.stack = []
def is_empty(self):
return not self.stack
def push(self, v):
self.stack.append(v)
def pop(self):
data = self.stack[-1]
del self.stack[-1]
return data
def peek(self):
return self.stac... | class Stack(object):
def __init__(self):
self.stack = []
def is_empty(self):
return not self.stack
def push(self, v):
self.stack.append(v)
def pop(self):
data = self.stack[-1]
del self.stack[-1]
return data
def peek(self):
return self.stac... |
array = [0,0,1,1,1,1,2,2,2,2,3,3]
indexEqualCurrentUsage = []
for index in range(len(array)):
if array[index] == 1:
indexEqualCurrentUsage.append(index)
print(indexEqualCurrentUsage) | array = [0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3]
index_equal_current_usage = []
for index in range(len(array)):
if array[index] == 1:
indexEqualCurrentUsage.append(index)
print(indexEqualCurrentUsage) |
### do not use these settings and passwords for production!
# these settings are required to connect the postgres-db to metabase
POSTGRES_USER='postgres'
POSTGRES_PASSWORD='1234'
POSTGRES_HOST='postgresdb'
POSTGRES_PORT='5432'
POSTGRES_DB_NAME='postgres'
| postgres_user = 'postgres'
postgres_password = '1234'
postgres_host = 'postgresdb'
postgres_port = '5432'
postgres_db_name = 'postgres' |
# # Sunny data
# outFeaturesPath = "models/features_40_sun_only"
# outLabelsPath = "models/labels_sun_only"
# imageFolderName = 'IMG_sun_only'
# features_directory = '../data/'
# labels_file = '../data/driving_log_sun_only.csv'
# modelPath = 'models/MsAutopilot_sun_only.h5'
# NoColumns = 3 # steering value index in csv... | out_features_path = 'models/features_40_fog_only'
out_labels_path = 'models/labels_fog_only'
image_folder_name = 'IMG_fog_only'
features_directory = '../data/'
labels_file = '../data/driving_log_fog_only.csv'
no_columns = 3
model_path_foggy = 'models/MsAutopilot_foggy.h5'
model_path_sun_only = 'models/MsAutopilot_sun_o... |
with open('inputs/input2.txt') as fin:
raw = fin.read()
def parse(raw):
start = [(x[:3], int(x[4:])) for x in (raw.split('\n'))]
return start
a = parse(raw)
def part_1(arr):
indices = set()
acc = 0
i = 0
while i < len(arr):
pair = arr[i]
if i in indices:
bre... | with open('inputs/input2.txt') as fin:
raw = fin.read()
def parse(raw):
start = [(x[:3], int(x[4:])) for x in raw.split('\n')]
return start
a = parse(raw)
def part_1(arr):
indices = set()
acc = 0
i = 0
while i < len(arr):
pair = arr[i]
if i in indices:
break
... |
################################ A Library of Functions ##################################
##################################################################################################
#simple function which displays a matrix
def matrixDisplay(M):
for i in range(len(M)):
for j in range(len... | def matrix_display(M):
for i in range(len(M)):
for j in range(len(M[i])):
print(M[i][j], end=' ')
print()
def matrix_product(L, M):
if len(L[0]) != len(M):
print('Matrix multiplication not possible.')
else:
print('Multiplying the two matrices: ')
p = [[0 ... |
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
def DFS(root):
if not root: return 0
if not root.left and not root.right : return int(root.val)
if root.left: root.left.val = 10 * root.val + root.left.val
if root.right: root.right.val = 1... | class Solution:
def sum_numbers(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if not root:
return 0
if not root.left and (not root.right):
return int(root.val)
if root.left:
root.left.val = 10 * root.val + root.le... |
class OrderCodeAlreadyExists(Exception):
pass
class DealerDoesNotExist(Exception):
pass
class OrderDoesNotExist(Exception):
pass
class StatusNotAllowed(Exception):
pass
| class Ordercodealreadyexists(Exception):
pass
class Dealerdoesnotexist(Exception):
pass
class Orderdoesnotexist(Exception):
pass
class Statusnotallowed(Exception):
pass |
# -*- coding: utf-8 -*-
# Copyright (c) 2017-18 Richard Hull and contributors
# See LICENSE.rst for details.
_DIGITS = {
' ': 0x00,
'-': 0x01,
'_': 0x08,
'\'': 0x02,
'0': 0x7e,
'1': 0x30,
'2': 0x6d,
'3': 0x79,
'4': 0x33,
'5': 0x5b,
'6': 0x5f,
'7': 0x70,
'8': 0x7f,
... | _digits = {' ': 0, '-': 1, '_': 8, "'": 2, '0': 126, '1': 48, '2': 109, '3': 121, '4': 51, '5': 91, '6': 95, '7': 112, '8': 127, '9': 123, 'a': 125, 'b': 31, 'c': 13, 'd': 61, 'e': 111, 'f': 71, 'g': 123, 'h': 23, 'i': 16, 'j': 24, 'l': 6, 'n': 21, 'o': 29, 'p': 103, 'q': 115, 'r': 5, 's': 91, 't': 15, 'u': 28, 'v': 28... |
# merge sort
# h/t https://www.thecrazyprogrammer.com/2017/12/python-merge-sort.html
# h/t https://www.youtube.com/watch?v=Nso25TkBsYI
def merge_sort(array):
n = len(array)
if n > 1:
mid = n//2
left = array[0:mid]
right = array[mid:n]
print(mid, left, right, array)
... | def merge_sort(array):
n = len(array)
if n > 1:
mid = n // 2
left = array[0:mid]
right = array[mid:n]
print(mid, left, right, array)
merge_sort(left)
merge_sort(right)
merge(left, right, array, n)
def merge(left, right, array, array_length):
right_len... |
# Lucas Sequence Using Recursion
def recur_luc(n):
if n == 1:
return n
if n == 0:
return 2
return (recur_luc(n-1) + recur_luc(n-2))
limit = int(input("How many terms to include in Lucas series:"))
print("Lucas series:")
for i in range(limit):
print(recur_luc(i))
| def recur_luc(n):
if n == 1:
return n
if n == 0:
return 2
return recur_luc(n - 1) + recur_luc(n - 2)
limit = int(input('How many terms to include in Lucas series:'))
print('Lucas series:')
for i in range(limit):
print(recur_luc(i)) |
#
# PySNMP MIB module RBN-SYS-SECURITY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-SYS-SECURITY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:53:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ... |
lines = open('input.txt').read().splitlines()
matches = {'(': ')', '[': ']', '{': '}', '<': '>'}
penalty = {')': 3, ']': 57, '}': 1197, '>': 25137}
costs = {')': 1, ']': 2, '}': 3, '>': 4}
errors = []
incpl_costs = []
for i, l in enumerate(lines):
expected_closings = []
for c in l:
if c in matches.key... | lines = open('input.txt').read().splitlines()
matches = {'(': ')', '[': ']', '{': '}', '<': '>'}
penalty = {')': 3, ']': 57, '}': 1197, '>': 25137}
costs = {')': 1, ']': 2, '}': 3, '>': 4}
errors = []
incpl_costs = []
for (i, l) in enumerate(lines):
expected_closings = []
for c in l:
if c in matches.key... |
# Given a sorted array of integers, find the starting and ending position of a given target value.
# Your algorithm's runtime complexity must be in the order of O(log n).
# If the target is not found in the array, return [-1, -1].
# For example,
# Given [5, 7, 7, 8, 8, 10] and target value 8,
# return [3, 4].
... | def search_range(numbers, target):
result = [-1, -1]
if len(numbers) == 0:
return result
low = 0
high = len(numbers) - 1
while low <= high:
mid = low + (high - low) // 2
if numbers[mid] >= target:
high = mid - 1
else:
low = mid + 1
if low <... |
# https://leetcode.com/problems/climbing-stairs/
# ---------------------------------------------------
# Runtime Complexity: O(n)
# Space Complexity: O(1)
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
prev_prev = 1
prev = 2
cur = 0
f... | class Solution:
def climb_stairs(self, n: int) -> int:
if n <= 2:
return n
prev_prev = 1
prev = 2
cur = 0
for i in range(3, n + 1):
cur = prev_prev + prev
(prev_prev, prev) = (prev, cur)
return cur
solution = solution()
print(solut... |
def urlify(s, i):
p1, p2 = len(s) - 1, i
while p1 >= 0 and p2 >= 0:
if s[p2] != " ":
s[p1] = s[p2]
else:
for i in reversed("%20"):
s[p1] = i
p1 -= 1
p1 -= 1
p2 -= 1
| def urlify(s, i):
(p1, p2) = (len(s) - 1, i)
while p1 >= 0 and p2 >= 0:
if s[p2] != ' ':
s[p1] = s[p2]
else:
for i in reversed('%20'):
s[p1] = i
p1 -= 1
p1 -= 1
p2 -= 1 |
# Example 1:
# Input: candidates = [2,3,6,7], target = 7
# Output: [[2,2,3],[7]]
# Explanation:
# 2 and 3 are candidates, and 2 + 2 + 3 = 7.
# Note that 2 can be used multiple times.
# 7 is a candidate, and 7 = 7.
# These are the only two combinations.
# Example 2:
# Input: candidates = [2,3,5], target = 8
# Output: [... | class Solution:
def combination_sum(self, candidates: List[int], target: int) -> List[List[int]]:
comb = [[] if i > 0 else [[]] for i in range(target + 1)]
for candidate in candidates:
for i in range(candidate, len(comb)):
comb[i].extend((comb + [candidate] for comb in c... |
#################################################
# Unit helpers #
#################################################
class Length(float):
unit2m = dict(mm=0.001, cm=0.01, dm=0.1, m=1, km=1000)
def __new__(cls, val, unit):
return float.__new__(cls, val)
def __init... | class Length(float):
unit2m = dict(mm=0.001, cm=0.01, dm=0.1, m=1, km=1000)
def __new__(cls, val, unit):
return float.__new__(cls, val)
def __init__(self, val, unit):
assert unit in Length.unit2m, 'Unknown units'
self.unit = unit
def __str__(self):
return f'{float(self... |
command = input()
student_ticket = 0
standard_ticket = 0
kid_ticket = 0
while command != "Finish":
seats = int(input())
ticket_type = input()
tickets_sold = 0
while seats > tickets_sold:
tickets_sold += 1
if ticket_type == "student":
student_ticket += 1
elif ticke... | command = input()
student_ticket = 0
standard_ticket = 0
kid_ticket = 0
while command != 'Finish':
seats = int(input())
ticket_type = input()
tickets_sold = 0
while seats > tickets_sold:
tickets_sold += 1
if ticket_type == 'student':
student_ticket += 1
elif ticket_ty... |
META_SITE_DOMAIN = 'www.geocoptix.com'
META_USE_OG_PROPERTIES = True
META_USE_TWITTER_PROPERTIES = True
META_TWITTER_AUTHOR = 'geocoptix'
META_FB_AUTHOR_URL = 'https://facebook.com/geocoptix'
| meta_site_domain = 'www.geocoptix.com'
meta_use_og_properties = True
meta_use_twitter_properties = True
meta_twitter_author = 'geocoptix'
meta_fb_author_url = 'https://facebook.com/geocoptix' |
class Toggle_Button(QPushButton):
sent_fix = pyqtSignal(bool, int, bool)
def __init__(self, currentRowCount):
QPushButton.__init__(self, "ON")
# self.setFixedSize(100, 100)
self.currentRowCount = self.rowCount()
self.setStyleSheet("background-color: green")
self.setChecka... | class Toggle_Button(QPushButton):
sent_fix = pyqt_signal(bool, int, bool)
def __init__(self, currentRowCount):
QPushButton.__init__(self, 'ON')
self.currentRowCount = self.rowCount()
self.setStyleSheet('background-color: green')
self.setCheckable(True)
self.toggled.conne... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.