content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
with open("zad3.txt", "w") as plik:
for i in range(0,11,1):
plik.write(str(i)+'\n')
with open("zad3.txt", "r") as plik:
for i in plik:
print(i, end="") | with open('zad3.txt', 'w') as plik:
for i in range(0, 11, 1):
plik.write(str(i) + '\n')
with open('zad3.txt', 'r') as plik:
for i in plik:
print(i, end='') |
'''
Problem 019
You are given the following information, but you may prefer to do some research
for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A... | """
Problem 019
You are given the following information, but you may prefer to do some research
for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A... |
a = 2 ** 62
b = 2 ** 63
c = 0 ** 0
d = 0 ** 1
e = 1 ** 999999999
f = 1 ** 999999999999999999999999999
g = 1 ** (-1)
h = 0 ** (-1)
i = 999999999999999 ** 99999999999999999999999999999
j = 2 ** 10
k = 10 ** 10
l = 13 ** 3
m = (-3) ** 3
n = (-3) ** 4
| a = 2 ** 62
b = 2 ** 63
c = 0 ** 0
d = 0 ** 1
e = 1 ** 999999999
f = 1 ** 999999999999999999999999999
g = 1 ** (-1)
h = 0 ** (-1)
i = 999999999999999 ** 99999999999999999999999999999
j = 2 ** 10
k = 10 ** 10
l = 13 ** 3
m = (-3) ** 3
n = (-3) ** 4 |
class State:
'Defined state of cell in grid world'
def __init__(self, pos=[0,0], reward= -1, movable=True, absorbing=False, agent_present=False):
self.pos = pos
self.reward = reward
self.movable = movable
self.absorbing = absorbing
self.v_pi = []
self.v_pi_mean = ... | class State:
"""Defined state of cell in grid world"""
def __init__(self, pos=[0, 0], reward=-1, movable=True, absorbing=False, agent_present=False):
self.pos = pos
self.reward = reward
self.movable = movable
self.absorbing = absorbing
self.v_pi = []
self.v_pi_me... |
# File: minemeld_consts.py
#
# Copyright (c) 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 applica... | minemeld_success_test_connectivity = 'Test Connectivity Passed'
minemeld_err_test_connectivity = 'Test Connectivity Failed'
minemeld_err_invalid_config_param = 'Check input parameter. For example: Endpoint: https://host:port User: admin Password: ****'
minemeld_vault_id_not_found = 'File not found for given vault id'
... |
PRIVILEGE_CHOICES = [
('Users.manageUser', 'Manage Users'),
('Sales.manage', 'Manage Sales'),
('Sales.docs', 'Manage Documents'),
]
| privilege_choices = [('Users.manageUser', 'Manage Users'), ('Sales.manage', 'Manage Sales'), ('Sales.docs', 'Manage Documents')] |
__all__ = [
'q1_words_score',
'q2_default_arguments'
]
| __all__ = ['q1_words_score', 'q2_default_arguments'] |
# This example shows one of the possibilities of the canvas:
# the ability to access all existing objects on it.
size(550, 300)
fill(1, 0.8)
strokewidth(1.5)
# First, generate some rectangles all over the canvas, rotated randomly.
for i in range(3000):
grob = rect(random(WIDTH)-25, random(HEIGHT)-25,50, 50)
... | size(550, 300)
fill(1, 0.8)
strokewidth(1.5)
for i in range(3000):
grob = rect(random(WIDTH) - 25, random(HEIGHT) - 25, 50, 50)
grob.rotate(random(360))
sorted_grobs = list(canvas)
def compare(a, b):
v1 = a.bounds[0][1]
v2 = b.bounds[0][1]
if v1 > v2:
return 1
elif v1 < v2:
retu... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Created by Ross on 19-1-8
def solve(n: int):
if n <= 0:
return -1
table = [0, 1]
if n < 2:
return table[n]
fib1 = table[0]
fib2 = table[1]
fib_n = 0
for i in range(2, n + 1):
fib_n = fib1 + fib2
fib1 = fib2
... | def solve(n: int):
if n <= 0:
return -1
table = [0, 1]
if n < 2:
return table[n]
fib1 = table[0]
fib2 = table[1]
fib_n = 0
for i in range(2, n + 1):
fib_n = fib1 + fib2
fib1 = fib2
fib2 = fib_n
return fib_n
if __name__ == '__main__':
for i in r... |
numbe = 1125
strnumbe = str(numbe)
sumOfDigit = 0
productOfDigit = 1
listdigits = list(map(int, strnumbe))
for elemen in listdigits:
sumOfDigit = sumOfDigit+elemen
productOfDigit = productOfDigit*elemen
if(sumOfDigit == productOfDigit):
print('The given number', strnumbe, 'is spy number')
else:
... | numbe = 1125
strnumbe = str(numbe)
sum_of_digit = 0
product_of_digit = 1
listdigits = list(map(int, strnumbe))
for elemen in listdigits:
sum_of_digit = sumOfDigit + elemen
product_of_digit = productOfDigit * elemen
if sumOfDigit == productOfDigit:
print('The given number', strnumbe, 'is spy number')
else:
... |
number = int(input())
if number == 1:
print("Monday")
elif number == 2:
print("Tuesday")
elif number == 3:
print("Wednesday")
elif number == 4:
print("Thursday")
elif number == 5:
print("Friday")
elif number == 6:
print("Saturday")
elif number == 7:
print("Sunday")
else:
... | number = int(input())
if number == 1:
print('Monday')
elif number == 2:
print('Tuesday')
elif number == 3:
print('Wednesday')
elif number == 4:
print('Thursday')
elif number == 5:
print('Friday')
elif number == 6:
print('Saturday')
elif number == 7:
print('Sunday')
else:
print('Error') |
def to_role_name(feature_name):
return feature_name.replace("-", "_")
def to_feature_name(role_name):
return role_name.replace("_", "-")
def resource_name(prefix, cluster_name, resource_type, component=None):
name = ''
if (not prefix) or (prefix == 'default'):
if component is None:
... | def to_role_name(feature_name):
return feature_name.replace('-', '_')
def to_feature_name(role_name):
return role_name.replace('_', '-')
def resource_name(prefix, cluster_name, resource_type, component=None):
name = ''
if not prefix or prefix == 'default':
if component is None:
nam... |
number_of_wagons = int(input())
train = [0 for x in range(number_of_wagons)]
command = input()
while command != 'End':
current_task = command.split(' ')
task = current_task[0]
if task == 'add':
num_of_people = int(current_task[1])
train[-1] += num_of_people
if task == 'insert':
... | number_of_wagons = int(input())
train = [0 for x in range(number_of_wagons)]
command = input()
while command != 'End':
current_task = command.split(' ')
task = current_task[0]
if task == 'add':
num_of_people = int(current_task[1])
train[-1] += num_of_people
if task == 'insert':
w... |
class UwsgiconfException(Exception):
"""Base for exceptions."""
class ConfigurationError(UwsgiconfException):
"""Configuration related error."""
class RuntimeConfigurationError(ConfigurationError):
"""Runtime configuration related error."""
| class Uwsgiconfexception(Exception):
"""Base for exceptions."""
class Configurationerror(UwsgiconfException):
"""Configuration related error."""
class Runtimeconfigurationerror(ConfigurationError):
"""Runtime configuration related error.""" |
# constants
PERCENTAGE_BUILTIN_SLOTS = 0.20
# Time
FOUNTAIN_MONTH = 'FOUNTAIN:MONTH'
FOUNTAIN_WEEKDAY = 'FOUNTAIN:WEEKDAY'
FOUNTAIN_HOLIDAYS = 'FOUNTAIN:HOLIDAYS'
FOUNTAIN_MONTH_DAY = 'FOUNTAIN:MONTH_DAY'
FOUNTAIN_TIME = 'FOUNTAIN:TIME'
FOUNTAIN_NUMBER = 'FOUNTAIN:NUMBER'
FOUNTAIN_DATE = 'FOUNTAIN:DATE'
# Location
F... | percentage_builtin_slots = 0.2
fountain_month = 'FOUNTAIN:MONTH'
fountain_weekday = 'FOUNTAIN:WEEKDAY'
fountain_holidays = 'FOUNTAIN:HOLIDAYS'
fountain_month_day = 'FOUNTAIN:MONTH_DAY'
fountain_time = 'FOUNTAIN:TIME'
fountain_number = 'FOUNTAIN:NUMBER'
fountain_date = 'FOUNTAIN:DATE'
fountain_city = 'FOUNTAIN:CITY'
fou... |
# 246. Strobogrammatic Number
# ttungl@gmail.com
# A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
# Write a function to determine if a number is strobogrammatic. The number is represented as a string.
# For example, the numbers "69", "88", and "818" are all... | class Solution(object):
def is_strobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
maps = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
(l, r) = (0, len(num) - 1)
if not num:
return True
while l <= r:
if num[r]... |
# https://leetcode.com/problems/multiply-strings/
# Given two non-negative integers num1 and num2 represented as strings, return the
# product of num1 and num2, also represented as a string.
# Note: You must not use any built-in BigInteger library or convert the inputs to
# integer directly.
########################... | class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == '0' or num2 == '0':
return '0'
if num1 == '1':
return num2
if num2 == '1':
return num1
(n1, n2) = (len(num1), len(num2))
multi = [0] * (n1 + n2)
for i in r... |
# -*- coding: utf-8 -*-
"""
the common functionalities
"""
def get_value_from_dict_safe(d, key, default=None):
"""
get the value from dict
args:
d: {dict}
key: {a hashable key, or a list of hashable key}
if key is a list, then it can be assumed the d is a nested dict
d... | """
the common functionalities
"""
def get_value_from_dict_safe(d, key, default=None):
"""
get the value from dict
args:
d: {dict}
key: {a hashable key, or a list of hashable key}
if key is a list, then it can be assumed the d is a nested dict
default: return value if th... |
# Handling negation: "not good", "not worth it"
def hack(rev):
for i in range(0, len(rev)):
line = rev[i].split()
for it in range(0, len(line)):
if line[it] == 'no' or line[it] == 'not' or line[it] == 'nope' or line[it] == 'never' or line[it] == "isn't" or line[it] == "don't" or line[it] == "dont" or line[... | def hack(rev):
for i in range(0, len(rev)):
line = rev[i].split()
for it in range(0, len(line)):
if line[it] == 'no' or line[it] == 'not' or line[it] == 'nope' or (line[it] == 'never') or (line[it] == "isn't") or (line[it] == "don't") or (line[it] == 'dont') or (line[it] == "wasn't"):
... |
print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n")
num = int(input("Enter a number: "))
if num % 2 == 0:
print("{} is an even number".format(num))
else:
print("{} is an odd number".format(num)) | print('Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n')
num = int(input('Enter a number: '))
if num % 2 == 0:
print('{} is an even number'.format(num))
else:
print('{} is an odd number'.format(num)) |
_input = [int(num) for num in input().split(" ")]
river_width = _input[0]
max_jump_length = _input[1]
stones = [int(stone) for stone in input().split(" ")]
| _input = [int(num) for num in input().split(' ')]
river_width = _input[0]
max_jump_length = _input[1]
stones = [int(stone) for stone in input().split(' ')] |
#Compute the max depth of a binary tree
class Tree:
def __init__(self, val,left = None, right = None):
self.val = val
self.left = left
self.right = right
root = Tree(4, left = Tree(3), right=Tree(5, left= Tree(4)))
def maxDepth(root):
if root is None:
return 0
ret... | class Tree:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
root = tree(4, left=tree(3), right=tree(5, left=tree(4)))
def max_depth(root):
if root is None:
return 0
return max(max_depth(root.left) + 1, max_depth(root.right)... |
lst=list(map(int, input().split()))
if sum(lst)==180 and 0 not in lst:
print('YES')
else:
print('NO')
| lst = list(map(int, input().split()))
if sum(lst) == 180 and 0 not in lst:
print('YES')
else:
print('NO') |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
current_max=nums[0]
global_max=nums[0]
for i in range(1,len(nums)):
current_max=max(nums[i],current_max+nums[i])
global_max=max(current_max,global_max)
return global_max | class Solution:
def max_sub_array(self, nums: List[int]) -> int:
current_max = nums[0]
global_max = nums[0]
for i in range(1, len(nums)):
current_max = max(nums[i], current_max + nums[i])
global_max = max(current_max, global_max)
return global_max |
'''
BITONIC POINT
Given an array. The task is to find the bitonic point of the array.
The bitonic point in an array is the index before which all the numbers
are in increasing order and after which, all are in decreasing order.
'''
def bitonic(a, n):
l = 1
r = n - 2
while(l <= r):
m = (l + r) // 2... | """
BITONIC POINT
Given an array. The task is to find the bitonic point of the array.
The bitonic point in an array is the index before which all the numbers
are in increasing order and after which, all are in decreasing order.
"""
def bitonic(a, n):
l = 1
r = n - 2
while l <= r:
m = (l + r) // 2
... |
class Solution:
def nthUglyNumber(self, n):
dp = [0] * n
dp[0] = 1
p2 = 0
p3 = 0
p5 = 0
for i in range(1, n):
dp[i] = min(2 * dp[p2], 3 * dp[p3], 5 * dp[p5])
if dp[i] >= 2 * dp[p2]:
p2 += 1
if dp[i] >= 3 * dp[p3]:
... | class Solution:
def nth_ugly_number(self, n):
dp = [0] * n
dp[0] = 1
p2 = 0
p3 = 0
p5 = 0
for i in range(1, n):
dp[i] = min(2 * dp[p2], 3 * dp[p3], 5 * dp[p5])
if dp[i] >= 2 * dp[p2]:
p2 += 1
if dp[i] >= 3 * dp[p3]:... |
"""
Check that `yield from`-statement takes an iterable.
"""
# pylint: disable=missing-docstring
def to_ten():
yield from 10 # [not-an-iterable]
| """
Check that `yield from`-statement takes an iterable.
"""
def to_ten():
yield from 10 |
class SpatialExtent:
def __init__(self):
self.bbox = ""
class TemporalExtent:
def __init__(self):
self.interval = ""
| class Spatialextent:
def __init__(self):
self.bbox = ''
class Temporalextent:
def __init__(self):
self.interval = '' |
ascii_brand = """
[49m[K[0m[12C[48;5;102m [3C [49m
[11C[48;5;102m [17C [49m
[10C[48;5;102m [7C[48;5;209m [7C[48;5;102m [49m
[9C[48;5;102m [21C [49m
[7C[48;5;102m [8C[48;5;209m [48;5;203m [12C[48;5;102m [49m
[7C[48;5;102m [9C[48;5;209m [14C[48... | ascii_brand = '\n\x1b[49m\x1b[K\x1b[0m\x1b[12C\x1b[48;5;102m \x1b[3C \x1b[49m\n\x1b[11C\x1b[48;5;102m \x1b[17C \x1b[49m\n\x1b[10C\x1b[48;5;102m \x1b[7C\x1b[48;5;209m \x1b[7C\x1b[48;5;102m \x1b[49m\n\x1b[9C\x1b[48;5;102m \x1b[21C \x1b[49m\n\x1b[7C\x1b[48;5;102m \x1b[8C\x1b[48;5;209m \... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 6, 2015
# Question: 001-Two-Sum
# Link: https://leetcode.com/problems/two-sum/
# ==============================================================================
# Giv... | class Solution:
def two_sum(self, nums, target):
dic = {}
for i in nums:
dic[i] = target - i
for i in nums:
if dic.get(dic[i]) is not None:
idx1 = nums.index(i)
if dic[i] != i:
return sorted([idx1 + 1, nums.index(di... |
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
result, curr = 0, 0
for i, val in sorted(
x for interval in intervals for x in [(interval[0], 1), (interval[1], -1)]
):
curr += val
... | class Solution:
def min_meeting_rooms(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
(result, curr) = (0, 0)
for (i, val) in sorted((x for interval in intervals for x in [(interval[0], 1), (interval[1], -1)])):
curr += val
result = m... |
dados = list()
pessoas = list()
pesados = list()
leves = list()
maior = menor = 0
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Peso: ')))
pessoas.append(dados[:])
dados.clear()
continuar = ' '
while continuar not in 'SN':
continuar = str(input('Deseja continua... | dados = list()
pessoas = list()
pesados = list()
leves = list()
maior = menor = 0
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Peso: ')))
pessoas.append(dados[:])
dados.clear()
continuar = ' '
while continuar not in 'SN':
continuar = str(input('Deseja continua... |
# Futu Algo: Algorithmic High-Frequency Trading Framework
# Copyright (c) billpwchan - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Bill Chan <billpwchan@hotmail.com>, 2021
class Settings:
# APP SETTINGS
ENABLE_... | class Settings:
enable_custom_title_bar = True
menu_width = 240
left_box_width = 240
right_box_width = 240
time_animation = 500
btn_left_box_color = 'background-color: rgb(44, 49, 58);'
btn_right_box_color = 'background-color: #ff79c6;'
menu_selected_stylesheet = '\n border-left: 22px... |
# search for the 1000th prime number and print it
# author Zhou Fang Version: 1.0
# Problem 1.
# Write a program that computes and prints the 1000th prime number.
number_prime = 1
i = 3
while number_prime < 1000:
divider = 3
status = 1
while status:
if i % divider != 0 and divider < i/2:
... | number_prime = 1
i = 3
while number_prime < 1000:
divider = 3
status = 1
while status:
if i % divider != 0 and divider < i / 2:
divider = divider + 2
elif divider >= i / 2:
number_prime = number_prime + 1
prime_num = i
print('it is the %d th pr... |
class Components(object):
"""Represents an OpenAPI Components in a service."""
def __init__(
self, schemas=None, responses=None, parameters=None,
request_bodies=None):
self.schemas = schemas and dict(schemas) or {}
self.responses = responses and dict(responses) or {}
... | class Components(object):
"""Represents an OpenAPI Components in a service."""
def __init__(self, schemas=None, responses=None, parameters=None, request_bodies=None):
self.schemas = schemas and dict(schemas) or {}
self.responses = responses and dict(responses) or {}
self.parameters = pa... |
class Mixin(object):
def _send_neuron(self, *args):
return self._send_entity('Neuron', *args)
def _send_synapse(self, *args):
return self._send_entity('Synapse', *args)
def send_synapse(self, source_neuron_id, target_neuron_id, weight):
"""Send a synapse to the simulator to connec... | class Mixin(object):
def _send_neuron(self, *args):
return self._send_entity('Neuron', *args)
def _send_synapse(self, *args):
return self._send_entity('Synapse', *args)
def send_synapse(self, source_neuron_id, target_neuron_id, weight):
"""Send a synapse to the simulator to connec... |
print("welcome to SBI bank ATM")
restart=('y')
chances = 3
balance = 1000
while chances>0:
restart=('y')
pin = int(input("please enter your secret number"))
if pin == 1234:
print('you entered your pin correctly\n')
while restart not in ('n','N','no','NO'):
print('press ... | print('welcome to SBI bank ATM')
restart = 'y'
chances = 3
balance = 1000
while chances > 0:
restart = 'y'
pin = int(input('please enter your secret number'))
if pin == 1234:
print('you entered your pin correctly\n')
while restart not in ('n', 'N', 'no', 'NO'):
print('press 1 for... |
# encoding: utf-8
"""Basic token types for use by parsers."""
class Token(object):
def __lt__(self, other):
return self.length < len(other)
def __len__(self):
return self.length
class InlineToken(Token):
"""Inline token definition."""
__slots__ = ('annotation', 'match')
def __init__(self, annotation,... | """Basic token types for use by parsers."""
class Token(object):
def __lt__(self, other):
return self.length < len(other)
def __len__(self):
return self.length
class Inlinetoken(Token):
"""Inline token definition."""
__slots__ = ('annotation', 'match')
def __init__(self, annotat... |
A = [[1, 2], [3, 4], [5, 6]]
B = max(A)
V = 1 | a = [[1, 2], [3, 4], [5, 6]]
b = max(A)
v = 1 |
class config_library:
def __init__(self, default):
self.path = default.path + "/system/library/"
self.ignore = ['__pycache__', '__init__.py']
def get(self):
return self | class Config_Library:
def __init__(self, default):
self.path = default.path + '/system/library/'
self.ignore = ['__pycache__', '__init__.py']
def get(self):
return self |
"""
OptimalK module.
This module is used to determine the best number of clusters in functional
data.
"""
| """
OptimalK module.
This module is used to determine the best number of clusters in functional
data.
""" |
f = open("/home/vleite/Desktop/range.txt", "w")
f.write("x range:\n")
for x in range(0, 55296, 64):
f.write(str(x) + "-" + str(x + 64) + "\n")
f.write("y range:\n")
for x in range(0, 46080, 64):
f.write(str(x) + "-" + str(x + 64) + "\n")
f.write("z range:\n")
for x in range(0, 514, 64):
f.write(str(x) +... | f = open('/home/vleite/Desktop/range.txt', 'w')
f.write('x range:\n')
for x in range(0, 55296, 64):
f.write(str(x) + '-' + str(x + 64) + '\n')
f.write('y range:\n')
for x in range(0, 46080, 64):
f.write(str(x) + '-' + str(x + 64) + '\n')
f.write('z range:\n')
for x in range(0, 514, 64):
f.write(str(x) + '-'... |
class Solution(object):
def runningSum(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
add_nums = 0
running_sum = []
for x in nums:
add_nums = add_nums + x
running_sum.append(add_nums)
return runnin... | class Solution(object):
def running_sum(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
add_nums = 0
running_sum = []
for x in nums:
add_nums = add_nums + x
running_sum.append(add_nums)
return running_sum |
pkgname = "libmodplug"
pkgver = "0.8.9.0"
pkgrel = 0
build_style = "gnu_configure"
configure_args = ["--enable-static"]
hostmakedepends = ["pkgconf"]
pkgdesc = "MOD playing library"
maintainer = "q66 <q66@chimera-linux.org>"
license = "custom:none"
url = "http://modplug-xmms.sourceforge.net"
source = f"$(SOURCEFORGE_SI... | pkgname = 'libmodplug'
pkgver = '0.8.9.0'
pkgrel = 0
build_style = 'gnu_configure'
configure_args = ['--enable-static']
hostmakedepends = ['pkgconf']
pkgdesc = 'MOD playing library'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'custom:none'
url = 'http://modplug-xmms.sourceforge.net'
source = f'$(SOURCEFORGE_SI... |
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
maxRes = 0
strs = ''
for i in range(len(s)):
pos = strs.find(s[i])
if pos != -1:
if res > maxRes:
... | class Solution:
def length_of_longest_substring(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
max_res = 0
strs = ''
for i in range(len(s)):
pos = strs.find(s[i])
if pos != -1:
if res > maxRes:
... |
# Copyright (c) 2008, Michael Lunnay <mlunnay@gmail.com.au>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND T... | """Custom exception heirachy for jsonrpc."""
class Jsonrpcerror(Exception):
def __init__(self, code, msg, data=None):
self.code = code
self.message = msg
self.data = data
def __str__(self):
out = 'JSON-RPCError(%d:%s)' % (self.code, self.message)
if self.data:
... |
# O(1) constant time!
def print_one_item(items):
print(items[0])
# liniar O(n)
def print_every_item(items):
for item in items:
print(item)
# n = number of steps
# quadratic O(n^2)
def print_pairs(items):
for item_one in items:
for item_two in items:
print(item_one, item_two)... | def print_one_item(items):
print(items[0])
def print_every_item(items):
for item in items:
print(item)
def print_pairs(items):
for item_one in items:
for item_two in items:
print(item_one, item_two)
def do_a_bunch_of_stuff(items):
last_idx = len(items) - 1
middle_idx =... |
class Aranet4Exception(BaseException):
"""
Base exception for pyaranet4
"""
pass
class Aranet4NotFoundException(Aranet4Exception):
"""
Exception that occurs when no suitable Aranet4 device is available
"""
pass
class Aranet4BusyException(Aranet4Exception):
"""
Exception that ... | class Aranet4Exception(BaseException):
"""
Base exception for pyaranet4
"""
pass
class Aranet4Notfoundexception(Aranet4Exception):
"""
Exception that occurs when no suitable Aranet4 device is available
"""
pass
class Aranet4Busyexception(Aranet4Exception):
"""
Exception that oc... |
# Time: O(n)
# Space: O(c), c is the max of nums
# counting sort, inplace solution
class Solution(object):
def sortEvenOdd(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def partition(index, nums):
for i in xrange(len(nums)):
j = i
... | class Solution(object):
def sort_even_odd(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def partition(index, nums):
for i in xrange(len(nums)):
j = i
while nums[i] >= 0:
j = index(j)
... |
# https://leetcode.com/problems/shortest-common-supersequence/
# Reference
# https://www.geeksforgeeks.org/print-shortest-common-supersequence/
# https://www.youtube.com/watch?v=823Grn4_dCQ&list=PL_z_8CaSLPWekqhdCPmFohncHwz8TY2Go&index=25&ab_channel=AdityaVerma
class Solution(object):
# Runtime: 368 ms, faste... | class Solution(object):
def shortest_common_supersequence(self, str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
def longest_common_subsequence(str1, str2):
dp = [[0] * (len(str2) + 1) for i in range(len(str1) + 1)]
for i in r... |
# content of test_example.py (adapted from https://docs.pytest.org)
def inc(x):
"""Functionality that we want to test"""
return x + 1
def test_inc():
# This will give an error
# assert inc(3) == 5
# This will not
# (to see this: comment assertion line above,
# uncomment line below and re... | def inc(x):
"""Functionality that we want to test"""
return x + 1
def test_inc():
assert inc(4) == 5 |
word = input()
times = int(input())
def repeat():
text = ""
for _ in range(times):
text += word
print(text)
repeat()
| word = input()
times = int(input())
def repeat():
text = ''
for _ in range(times):
text += word
print(text)
repeat() |
class STLException(Exception):
pass
class STLParseException(Exception):
pass
class STLOfflineException(Exception):
pass | class Stlexception(Exception):
pass
class Stlparseexception(Exception):
pass
class Stlofflineexception(Exception):
pass |
class TypeDeclaration:
def __init__(self, file_path):
self.file_path = file_path
self.types_declared = set()
def add_type_declared(self, new_type):
if type(new_type) == set:
self.types_declared = self.types_declared.union(new_type)
else:
self.types_d... | class Typedeclaration:
def __init__(self, file_path):
self.file_path = file_path
self.types_declared = set()
def add_type_declared(self, new_type):
if type(new_type) == set:
self.types_declared = self.types_declared.union(new_type)
else:
self.types_decla... |
'''
- Leetcode problem: 797
- Difficulty: Medium
- Brief problem description:
Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any
order.
The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for ... | """
- Leetcode problem: 797
- Difficulty: Medium
- Brief problem description:
Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any
order.
The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for ... |
#Dictionary adalah stuktur data yang bentuknya seperti kamus.
#Ada kata kunci kemudian ada nilaninya. Kata kunci harus unik,
#sedangkan nilai boleh diisi denga apa saja.
# Membuat Dictionary
ira_abri = {
"nama": "ira abri",
"umur": 19,
"hobi": ["makan", "jalan", "ngemoll"],
"menikah": False,... | ira_abri = {'nama': 'ira abri', 'umur': 19, 'hobi': ['makan', 'jalan', 'ngemoll'], 'menikah': False, 'sosmed': {'facebook': 'iraabri', 'twitter': '@irakode'}}
print('Nama saya adalah %s' % ira_abri['nama'])
print('Twitter: %s' % ira_abri['sosmed']['twitter']) |
class WorkBot:
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get("https://app.daily.dev/")
self.WebDriverWait(self.driver).until(document_initialised)
el = self.driver.find_element_by_xpath("/html/body/div/main/div/article/a")
# names = [name.text for name ... | class Workbot:
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get('https://app.daily.dev/')
self.WebDriverWait(self.driver).until(document_initialised)
el = self.driver.find_element_by_xpath('/html/body/div/main/div/article/a')
for e in el:
prin... |
# This code is written in Python
# This code prints the line number next to each line in the file
FileName = "file1.txt"
f = open(FileName,"r")
fileContent = f.read()
number_of_lines = 0
line_by_line = fileContent.split("\n")
number_of_lines = len(line_by_line)
print("The number of lines in the file are : ")
print... | file_name = 'file1.txt'
f = open(FileName, 'r')
file_content = f.read()
number_of_lines = 0
line_by_line = fileContent.split('\n')
number_of_lines = len(line_by_line)
print('The number of lines in the file are : ')
print(number_of_lines)
new_contents = ''
line_index = 1
for line in line_by_line:
new_contents = newC... |
class Event:
def __init__(self):
self._callee_list = set()
def __iadd__(self, fct):
return self._callee_list.add(fct)
def __isub__(self, fct):
return self._callee_list.remove(fct)
def __call__(self, sender, *event_args):
for callee in self._callee_list:
... | class Event:
def __init__(self):
self._callee_list = set()
def __iadd__(self, fct):
return self._callee_list.add(fct)
def __isub__(self, fct):
return self._callee_list.remove(fct)
def __call__(self, sender, *event_args):
for callee in self._callee_list:
ca... |
# https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/
def get_lps(pat):
n = len(pat)
lps = [0] * n # longest proper prefix which is also suffix
i = 1
l = 0
while i < n:
if pat[i] == pat[l]:
l += 1
lps[i] = l
i += 1
else:
if 0 < l:
l = lps[l-1]
e... | def get_lps(pat):
n = len(pat)
lps = [0] * n
i = 1
l = 0
while i < n:
if pat[i] == pat[l]:
l += 1
lps[i] = l
i += 1
elif 0 < l:
l = lps[l - 1]
else:
i += 1
return lps
def find(text, pat):
res = []
n = le... |
class ParsingSuccess:
def __init__(self, string, rule_type, start_pos, end_pos, children):
self.string = string
self.rule_type = rule_type
self.start_pos = start_pos
self.end_pos = end_pos
self.children = children
@property
def match_string(self):
r... | class Parsingsuccess:
def __init__(self, string, rule_type, start_pos, end_pos, children):
self.string = string
self.rule_type = rule_type
self.start_pos = start_pos
self.end_pos = end_pos
self.children = children
@property
def match_string(self):
return sel... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Pinentry(AutotoolsPackage):
"""pinentry is a small collection of dialog programs that allow GnuPG to
read p... | class Pinentry(AutotoolsPackage):
"""pinentry is a small collection of dialog programs that allow GnuPG to
read passphrases and PIN numbers in a secure manner.
There are versions for the common GTK and Qt toolkits as well as for
the text terminal (Curses).
"""
homepage = 'https://gnupg.org/rela... |
def information(*args):
for arg in args:
print(arg)
information(1, 3, 6, 7, "Abelardo")
def users(**kwargs):
for k in kwargs.values():
print(k)
users(name="bob", age=19)
| def information(*args):
for arg in args:
print(arg)
information(1, 3, 6, 7, 'Abelardo')
def users(**kwargs):
for k in kwargs.values():
print(k)
users(name='bob', age=19) |
def sqr(n):
if (n**.5)%1==0:
return True
return False
l=[]
for d in range(2,1001):
if sqr(d)==False:
y=1
while True:
x=1+d*y*y
if sqr(x)==True:
print(x**.5,"^2 -",d,"*",y,"^2 = 1")
l.append(int(x**.5))
... | def sqr(n):
if n ** 0.5 % 1 == 0:
return True
return False
l = []
for d in range(2, 1001):
if sqr(d) == False:
y = 1
while True:
x = 1 + d * y * y
if sqr(x) == True:
print(x ** 0.5, '^2 -', d, '*', y, '^2 = 1')
l.append(int(x **... |
def soma_numeros(primeiro, segundo):
return primeiro + segundo
print(soma_numeros(15, 15))
| def soma_numeros(primeiro, segundo):
return primeiro + segundo
print(soma_numeros(15, 15)) |
def dict_eq(d1, d2):
return (all(k in d2 and d1[k] == d2[k] for k in d1)
and all(k in d1 and d1[k] == d2[k] for k in d2))
assert dict_eq(dict(a=2, b=3), {'a': 2, 'b': 3})
assert dict_eq(dict({'a': 2, 'b': 3}, b=4), {'a': 2, 'b': 4})
assert dict_eq(dict([('a', 2), ('b', 3)]), {'a': 2, 'b': 3})
a = {'g... | def dict_eq(d1, d2):
return all((k in d2 and d1[k] == d2[k] for k in d1)) and all((k in d1 and d1[k] == d2[k] for k in d2))
assert dict_eq(dict(a=2, b=3), {'a': 2, 'b': 3})
assert dict_eq(dict({'a': 2, 'b': 3}, b=4), {'a': 2, 'b': 4})
assert dict_eq(dict([('a', 2), ('b', 3)]), {'a': 2, 'b': 3})
a = {'g': 5}
b = {'a... |
DISCORD_WEBHOOK_URL = 'https://discord.com/api/webhooks/{webhook_id}/{webhook_token}'
DISCORD_WEBHOOK_RELAY_PARAMS = [
'webhook_id',
'webhook_token',
'content',
]
| discord_webhook_url = 'https://discord.com/api/webhooks/{webhook_id}/{webhook_token}'
discord_webhook_relay_params = ['webhook_id', 'webhook_token', 'content'] |
class Forbidden(Exception):
pass
class InternalServerError(Exception):
pass | class Forbidden(Exception):
pass
class Internalservererror(Exception):
pass |
# -*- coding: utf-8 -*-
"""
test_nsct
----------------------------------
Tests for `nsct` module.
"""
class TestNsct(object):
@classmethod
def set_up(self):
pass
@classmethod
def tear_down(self):
pass
| """
test_nsct
----------------------------------
Tests for `nsct` module.
"""
class Testnsct(object):
@classmethod
def set_up(self):
pass
@classmethod
def tear_down(self):
pass |
print('calculate area of a circle')
def circle():
radius = input('enter radius')
radius = float(radius)
area = 3.14*radius*radius
print ('area is ')
print (area)
circle()
| print('calculate area of a circle')
def circle():
radius = input('enter radius')
radius = float(radius)
area = 3.14 * radius * radius
print('area is ')
print(area)
circle() |
h = list(map(int, input().rstrip().split()))
word = input()
h = [h[ord(l) - ord("a")] for l in set(word)]
print(max(h) * len(word))
| h = list(map(int, input().rstrip().split()))
word = input()
h = [h[ord(l) - ord('a')] for l in set(word)]
print(max(h) * len(word)) |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "com_fasterxml_jackson_module_jackson_module_paranamer",
artifact = "com.fasterxml.jackson.module:jackson-module-paranamer:2.9.6",
artifact_sha256 = "dfd66598c0094d9... | load('//:import_external.bzl', import_external='safe_wix_scala_maven_import_external')
def dependencies():
import_external(name='com_fasterxml_jackson_module_jackson_module_paranamer', artifact='com.fasterxml.jackson.module:jackson-module-paranamer:2.9.6', artifact_sha256='dfd66598c0094d9a7ef0b6e6bb3140031fc833f6c... |
"""Version and details for pcraft"""
__description__ = "Pcraft"
__url__ = "https://www.github.com/devoinc/pcraft"
__version__ = "0.1.4"
__author__ = "Sebastien Tricaud"
__author_email__ = "sebastien.tricaud@devo.com"
__license__ = "MIT"
__maintainer__ = __author__
__maintainer_email__ = __author_email__
| """Version and details for pcraft"""
__description__ = 'Pcraft'
__url__ = 'https://www.github.com/devoinc/pcraft'
__version__ = '0.1.4'
__author__ = 'Sebastien Tricaud'
__author_email__ = 'sebastien.tricaud@devo.com'
__license__ = 'MIT'
__maintainer__ = __author__
__maintainer_email__ = __author_email__ |
#!/usr/bin/env python
def plot(parser, args):
"""
To do.
"""
pass
if __name__ == "__main__":
plot()
| def plot(parser, args):
"""
To do.
"""
pass
if __name__ == '__main__':
plot() |
# A game is a sequence of scores (positive for the home team,
# negative for the visiting team).
# For example, in American football, the set of valid scores is
# {2,3,6,7,8,-2,-3,-6,-7,-8}.
# For rugby, the set of valid scores in {3,5,7,-3,-5,-7}
# A tie-less game is one in which the teams are never in a tie
# (except... | def number_of_tieless_games(scoring_events, n):
"""
Takes in an iterable, scoring_events, containing the possible scores in the
game. For example, for football, it would be {1,-1}.
For rugby union, it would be [3,5,7,-3,-5,-7].
Negative points represent points for the away team, positive points
... |
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex == 0:
return [1]
s = [1]
for i in range(1, rowIndex + 1):
s = [sum(x) for x in zip([0] + s, s + [0])]
return s
| class Solution:
def get_row(self, rowIndex: int) -> List[int]:
if rowIndex == 0:
return [1]
s = [1]
for i in range(1, rowIndex + 1):
s = [sum(x) for x in zip([0] + s, s + [0])]
return s |
#!/usr/bin/env python
class AsciiFileReader:
def __init__(self, infile):
self.infile = infile
def readInt(self):
assert False
| class Asciifilereader:
def __init__(self, infile):
self.infile = infile
def read_int(self):
assert False |
coordinates_E0E1E1 = ((123, 109),
(123, 111), (123, 112), (123, 114), (124, 109), (124, 110), (125, 108), (125, 109), (125, 114), (126, 108), (126, 109), (127, 69), (127, 79), (127, 99), (127, 101), (127, 108), (128, 72), (128, 73), (128, 74), (128, 75), (128, 76), (128, 77), (128, 79), (128, 93), (128, 98), (128, 10... | coordinates_e0_e1_e1 = ((123, 109), (123, 111), (123, 112), (123, 114), (124, 109), (124, 110), (125, 108), (125, 109), (125, 114), (126, 108), (126, 109), (127, 69), (127, 79), (127, 99), (127, 101), (127, 108), (128, 72), (128, 73), (128, 74), (128, 75), (128, 76), (128, 77), (128, 79), (128, 93), (128, 98), (128, 10... |
def countWords(s):
count=1
for i in s:
if i==" ":
count+=1
return count
print(countWords("Hello World This is Rituraj")) | def count_words(s):
count = 1
for i in s:
if i == ' ':
count += 1
return count
print(count_words('Hello World This is Rituraj')) |
def imprime(nota_fiscal):
print(f"Imprimindo nota fiscal {nota_fiscal.cnpj}")
def envia_por_email(nota_fiscal):
print(f"Enviando nota fiscal {nota_fiscal.cnpj} por email")
def salva_no_banco(nota_fiscal):
print(f"Salvando nota fiscal {nota_fiscal.cnpj} no banco") | def imprime(nota_fiscal):
print(f'Imprimindo nota fiscal {nota_fiscal.cnpj}')
def envia_por_email(nota_fiscal):
print(f'Enviando nota fiscal {nota_fiscal.cnpj} por email')
def salva_no_banco(nota_fiscal):
print(f'Salvando nota fiscal {nota_fiscal.cnpj} no banco') |
#Write a function that accepts a string and a character as input and returns the
#number of times the character is repeated in the string. Note that
#capitalization does not matter here i.e. a lower case character should be
#treated the same as an upper case character.
def count_character(line, character):
count =... | def count_character(line, character):
count = 0
for x in line.lower():
if x == character.lower():
count += 1
return count
print(count_character('supernovas are so awesome', 's')) |
"""
Fragments of user mutations
"""
AUTH_PAYLOAD_FRAGMENT = '''
id
token
user {
id
}
'''
USER_FRAGMENT = '''
id
'''
| """
Fragments of user mutations
"""
auth_payload_fragment = '\nid\ntoken\nuser {\n id\n}\n'
user_fragment = '\nid\n' |
def partfast(n):
# base case of the recursion: zero is the sum of the empty tuple
if n == 0:
yield []
return
# modify the partitions of n-1 to form the partitions of n
for p in partfast(n-1):
p.append(1)
yield p
p.pop()
if p and (len(p) < 2 or p[-2] > p[-1... | def partfast(n):
if n == 0:
yield []
return
for p in partfast(n - 1):
p.append(1)
yield p
p.pop()
if p and (len(p) < 2 or p[-2] > p[-1]):
p[-1] += 1
yield p |
mass_list = list(open('d01.in').read().split())
base_fuel = 0
total_fuel = 0
def calculate_fuel(mass):
return int(mass) // 3 - 2
for mass in mass_list:
fuel = calculate_fuel(mass)
base_fuel += fuel
while (fuel >= 0):
total_fuel += fuel
fuel = calculate_fuel(fuel)
print('P1:', base_fu... | mass_list = list(open('d01.in').read().split())
base_fuel = 0
total_fuel = 0
def calculate_fuel(mass):
return int(mass) // 3 - 2
for mass in mass_list:
fuel = calculate_fuel(mass)
base_fuel += fuel
while fuel >= 0:
total_fuel += fuel
fuel = calculate_fuel(fuel)
print('P1:', base_fuel)
p... |
f=open('t.txt','r')
l=f.readlines()
d={}
for i in (l):
k=i.strip()
m = list(k)
if(m[0]=='R'):
d[k] = []
j=k
else:
d[j].append(k)
p=[]
for i in d.keys():
m=d[i]
k=''.join(x for x in m)
d[i]=list(k)
l1 = k.count('G')
l2 = k.count('C')
l = len(d[i])
per =... | f = open('t.txt', 'r')
l = f.readlines()
d = {}
for i in l:
k = i.strip()
m = list(k)
if m[0] == 'R':
d[k] = []
j = k
else:
d[j].append(k)
p = []
for i in d.keys():
m = d[i]
k = ''.join((x for x in m))
d[i] = list(k)
l1 = k.count('G')
l2 = k.count('C')
l =... |
def sign(val):
if val == 0:
return 0
return 1 if val > 0 else -1
def linear_interpolation(val, x0, y0, x1, y1):
return y0 + ((val - x0) * (y1 - y0))/(x1 - x0) | def sign(val):
if val == 0:
return 0
return 1 if val > 0 else -1
def linear_interpolation(val, x0, y0, x1, y1):
return y0 + (val - x0) * (y1 - y0) / (x1 - x0) |
def bbox_xywh2cxcywh(bbox):
cx = bbox[0] + bbox[2] / 2
cy = bbox[1] + bbox[3] / 2
return (cx, cy, bbox[2], bbox[3])
| def bbox_xywh2cxcywh(bbox):
cx = bbox[0] + bbox[2] / 2
cy = bbox[1] + bbox[3] / 2
return (cx, cy, bbox[2], bbox[3]) |
class Block(object):
def __init__(self, name) -> None:
super().__init__()
self.__name__ = name
| class Block(object):
def __init__(self, name) -> None:
super().__init__()
self.__name__ = name |
"""
# All classes should extend Veggies and override the following methods
def __str__(selt)
"""
class Veggies :
def __str__(self):
assert False, 'This method should be overrided.'
class BlackOlives(Veggies) :
def __str__(self):
return 'Black Olives'
class Garlic(Veggies) :
... | """
# All classes should extend Veggies and override the following methods
def __str__(selt)
"""
class Veggies:
def __str__(self):
assert False, 'This method should be overrided.'
class Blackolives(Veggies):
def __str__(self):
return 'Black Olives'
class Garlic(Veggies):
def __... |
def subsets(l):
if not l:
return [[]]
else:
all_subsets = []
for i in range(len(l)):
sub_subsets = subsets(l[:i] + l[i + 1:])
[all_subsets.append(subset) for subset in sub_subsets if subset not in all_subsets]
if l not in all_subsets:
a... | def subsets(l):
if not l:
return [[]]
else:
all_subsets = []
for i in range(len(l)):
sub_subsets = subsets(l[:i] + l[i + 1:])
[all_subsets.append(subset) for subset in sub_subsets if subset not in all_subsets]
if l not in all_subsets:
a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class SizeError( Exception ):
pass
| class Sizeerror(Exception):
pass |
"""Package contains objects representing a wordsearch board."""
class Line:
"""Represents a directionless character line on a word search board."""
def __init__(self, index, characters=""):
"""Initialize instance with provided starting characters."""
self.index = index
self.characters... | """Package contains objects representing a wordsearch board."""
class Line:
"""Represents a directionless character line on a word search board."""
def __init__(self, index, characters=''):
"""Initialize instance with provided starting characters."""
self.index = index
self.characters ... |
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
'''
-5 -2 1 4 5 6 7 9 11
<3 = 0
3 -> 1
4 -> 2+1
5 -> 3+2+1
6 -> 4+3+2+1
n -> n(n+1)/2 -n - (n-1)
-> (n^2 - 3n + 2)/2
'''
def getCount(n):
... | class Solution:
def number_of_arithmetic_slices(self, nums: List[int]) -> int:
"""
-5 -2 1 4 5 6 7 9 11
<3 = 0
3 -> 1
4 -> 2+1
5 -> 3+2+1
6 -> 4+3+2+1
n -> n(n+1)/2 -n - (n-1)
-> (n^2 - 3n + 2)/2
"""
def get_count(n):
... |
class HelperError(Exception):
pass
class BaseHelper(object):
def get_current_path(self):
raise HelperError('you have to customized YourHelper.get_current_path')
def get_params(self):
raise HelperError('you have to customized YourHelper.get_params')
def get_body(self):
raise... | class Helpererror(Exception):
pass
class Basehelper(object):
def get_current_path(self):
raise helper_error('you have to customized YourHelper.get_current_path')
def get_params(self):
raise helper_error('you have to customized YourHelper.get_params')
def get_body(self):
raise... |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxsofar = nums[0]
maxendinghere = nums[0]
for i in range(1, len(nums)):
maxendinghere = max(nums[i], nums[i] + maxendinghere)
maxsofar = max(maxsofar, maxendinghere)
return m... | class Solution:
def max_sub_array(self, nums: List[int]) -> int:
maxsofar = nums[0]
maxendinghere = nums[0]
for i in range(1, len(nums)):
maxendinghere = max(nums[i], nums[i] + maxendinghere)
maxsofar = max(maxsofar, maxendinghere)
return maxsofar |
map = [200090710, 200090610]
sm.sendSay("Where would you like to go? \r\n#L0#Victoria Island#l\r\n#L1#Orbis#l")
sm.warp(map[answer], 0) | map = [200090710, 200090610]
sm.sendSay('Where would you like to go? \r\n#L0#Victoria Island#l\r\n#L1#Orbis#l')
sm.warp(map[answer], 0) |
class DependenceNode:
def __init__(self):
self.parents = []
self.children = []
self.inter_parents = []
self.inter_children = []
self.fictitious_parents = []
self.fictitious_children = []
self.ast = None
def add_parent(self, parent):
self.parents.... | class Dependencenode:
def __init__(self):
self.parents = []
self.children = []
self.inter_parents = []
self.inter_children = []
self.fictitious_parents = []
self.fictitious_children = []
self.ast = None
def add_parent(self, parent):
self.parents.... |
def longest_consec(strarr, k):
output,n = None ,len(strarr)
if n == 0 or k > n or k<=0 :
return ""
for i in range(n-k+1):
aux = ''
for j in range(i,i+k):
aux += strarr[j]
if output == None or len(output) < len(aux):
output = aux
return output | def longest_consec(strarr, k):
(output, n) = (None, len(strarr))
if n == 0 or k > n or k <= 0:
return ''
for i in range(n - k + 1):
aux = ''
for j in range(i, i + k):
aux += strarr[j]
if output == None or len(output) < len(aux):
output = aux
return... |
_CUDA_TOOLKIT_PATH = "CUDA_TOOLKIT_PATH"
_VAI_CUDA_REPO_VERSION = "VAI_CUDA_REPO_VERSION"
_VAI_NEED_CUDA = "VAI_NEED_CUDA"
_DEFAULT_CUDA_TOOLKIT_PATH = "/usr/local/cuda"
# Lookup paths for CUDA / cuDNN libraries, relative to the install directories.
#
# Paths will be tried out in the order listed below. The first s... | _cuda_toolkit_path = 'CUDA_TOOLKIT_PATH'
_vai_cuda_repo_version = 'VAI_CUDA_REPO_VERSION'
_vai_need_cuda = 'VAI_NEED_CUDA'
_default_cuda_toolkit_path = '/usr/local/cuda'
cuda_lib_paths = ['lib64/', 'lib64/stubs/', 'lib/x86_64-linux-gnu/', 'lib/x64/', 'lib/', '']
cuda_include_paths = ['include/', 'include/cuda/']
def g... |
f = open("demo.txt", "r")#read file
print(f.read())
c=open("demosfile.txt","r")
print(c.read())
w= open("demo.txt", "a") #update file with additional data
w.write("Now the file has one more line!")
ow = open("demo.txt", "w") #delete entire content and add new content
ow.write("Woops! I have deleted the content!"... | f = open('demo.txt', 'r')
print(f.read())
c = open('demosfile.txt', 'r')
print(c.read())
w = open('demo.txt', 'a')
w.write('Now the file has one more line!')
ow = open('demo.txt', 'w')
ow.write('Woops! I have deleted the content!')
new = open('demosfile.txt', 'w')
new.write('a new file is created with python program an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.