content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def setZeroes(self, matrix):
dummy1=[1]*len(matrix)
dummy2=[1]*len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]==0:
dummy1[i]=0
dummy2[j]=0
for i in range... | class Solution:
def set_zeroes(self, matrix):
dummy1 = [1] * len(matrix)
dummy2 = [1] * len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
dummy1[i] = 0
dummy2[j] = 0
f... |
N=int(input("Enter the number of test cases:"))
for i in range(0,N):
L,D,S,C=map(int,input().split())
for i in range(1,D):
if(S>=L):
S+=C*S
break
if L<= S:
print("ALIVE AND KICKING")
else:
print("DEAD AND ROTTING") | n = int(input('Enter the number of test cases:'))
for i in range(0, N):
(l, d, s, c) = map(int, input().split())
for i in range(1, D):
if S >= L:
s += C * S
break
if L <= S:
print('ALIVE AND KICKING')
else:
print('DEAD AND ROTTING') |
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = second = math.inf
for i in nums:
if i <=first:
first = i
elif i<=second:
second = i
else:
return True
return False | class Solution:
def increasing_triplet(self, nums: List[int]) -> bool:
first = second = math.inf
for i in nums:
if i <= first:
first = i
elif i <= second:
second = i
else:
return True
return False |
DynamoTable # unused import (dynamo_query/__init__.py:8)
DynamoRecord # unused variable (dynamo_query/__init__.py:12)
create # unused function (dynamo_query/data_table.py:119)
memo # unused variable (dynamo_query/data_table.py:137)
filter_keys # unused function (dynamo_query/data_table.py:299)
get_column # unused... | DynamoTable
DynamoRecord
create
memo
filter_keys
get_column
drop_duplicates
sanitize_key
compute_key
sanitize
get_field_names
DynamoAutoscaler
deregister_auto_scaling
register_auto_scaling
get_last_evaluated_key
reset_start_key
get_raw_responses
DynamoTable
delete_table
invalidate_cache
cached_batch_get
batch_get_recor... |
preamble = [int(input()) for _ in range(25)]
for _ in range(975):
x = int(input())
valid = False
for i, a in enumerate(preamble[:-1]):
for b in preamble[i+1:]:
if a + b == x:
valid = True
if not valid:
print(x)
break
preamble = preamble[1:] + [... | preamble = [int(input()) for _ in range(25)]
for _ in range(975):
x = int(input())
valid = False
for (i, a) in enumerate(preamble[:-1]):
for b in preamble[i + 1:]:
if a + b == x:
valid = True
if not valid:
print(x)
break
preamble = preamble[1:] + [... |
# https://www.codechef.com/AUG21C/problems/SPCTRIPS
for T in range(int(input())):
n,c=int(input()),0
for x in range(1,n+1):
for y in range(x,n+1,x): c+=((n-(x+y))//y+1)
print(c) | for t in range(int(input())):
(n, c) = (int(input()), 0)
for x in range(1, n + 1):
for y in range(x, n + 1, x):
c += (n - (x + y)) // y + 1
print(c) |
class QuizBrain:
def __init__(self, a_list):
self.question_number = 0
self.question_list = a_list
self.score = 0
def still_has_questions(self):
"""Checks if their still have more questions"""
if self.question_number < 12:
"""Checks if their still have more qu... | class Quizbrain:
def __init__(self, a_list):
self.question_number = 0
self.question_list = a_list
self.score = 0
def still_has_questions(self):
"""Checks if their still have more questions"""
if self.question_number < 12:
'Checks if their still have more que... |
ignore_validation = {
"/api/v1/profile": ("POST", "PUT"),
"/api/v1/exchange": "GET",
"/api/v1/validation": "GET",
"/api/v1/meals/search" : "GET",
"/api/v1/meals/browse" : "GET"
} | ignore_validation = {'/api/v1/profile': ('POST', 'PUT'), '/api/v1/exchange': 'GET', '/api/v1/validation': 'GET', '/api/v1/meals/search': 'GET', '/api/v1/meals/browse': 'GET'} |
class Node(object):
def __init__(self, id, x, y):
self.__id = id
self.__x = x
self.__y = y
self.reset()
@property
def id(self):
return self.__id
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
@prop... | class Node(object):
def __init__(self, id, x, y):
self.__id = id
self.__x = x
self.__y = y
self.reset()
@property
def id(self):
return self.__id
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
@pro... |
# -*- coding: utf-8 -*-
"""
Author : Chris Azzara
Purpose : A simple number guessing game. This program will try to guess a secret number between 1 - 100
The user will enter whether the guess is too high or too low or correct. The program uses the binary search algorithm to narrow the search space.
"""
prin... | """
Author : Chris Azzara
Purpose : A simple number guessing game. This program will try to guess a secret number between 1 - 100
The user will enter whether the guess is too high or too low or correct. The program uses the binary search algorithm to narrow the search space.
"""
print('Number Guessing Game!'... |
load("//bazel/rules/image:png_to_xpm.bzl", "png_to_xpm")
load("//bazel/rules/image:xpm_to_ppm.bzl", "xpm_to_ppm")
load("//bazel/rules/image:ppm_to_mask.bzl", "ppm_to_mask")
load("//bazel/rules/image:ppm_to_xpm.bzl", "ppm_to_xpm")
load("//bazel/rules/image:xpm_to_xbm.bzl", "xpm_to_xbm")
load("//bazel/rules/image:png_mir... | load('//bazel/rules/image:png_to_xpm.bzl', 'png_to_xpm')
load('//bazel/rules/image:xpm_to_ppm.bzl', 'xpm_to_ppm')
load('//bazel/rules/image:ppm_to_mask.bzl', 'ppm_to_mask')
load('//bazel/rules/image:ppm_to_xpm.bzl', 'ppm_to_xpm')
load('//bazel/rules/image:xpm_to_xbm.bzl', 'xpm_to_xbm')
load('//bazel/rules/image:png_mir... |
# -*- coding: utf-8 -*-
"""
fairsearchdeltr.models
~~~~~~~~~~~~~~~
This module contains the primary objects that power fairsearchdeltr.
"""
class TrainStep(object):
"""The :class:`TrainStep` object, which is a representation of the parameters in each step of the training.
Contains a `timestamp`, `omega`, `om... | """
fairsearchdeltr.models
~~~~~~~~~~~~~~~
This module contains the primary objects that power fairsearchdeltr.
"""
class Trainstep(object):
"""The :class:`TrainStep` object, which is a representation of the parameters in each step of the training.
Contains a `timestamp`, `omega`, `omega_gradient`, `loss`, `lo... |
a = {'a': 1, 'b': 2}
b = a
del b['a']
print(a)
print(b)
c = 5
del a
del b, c
| a = {'a': 1, 'b': 2}
b = a
del b['a']
print(a)
print(b)
c = 5
del a
del b, c |
class Keys():
ERROR = 'ERROR'
DEBUG = 'DEBUG'
WARN = 'WARN'
INFO = 'INFO'
URL = 'url'
TAG = 'tag'
MESSAGE = 'message'
LOG_LEVEL = 'level'
REQUEST_METHOD = 'method'
RESPONSE_STATUS = 'status'
PAGE = 'page'
SHOW = 'show'
ALL = 'all'
| class Keys:
error = 'ERROR'
debug = 'DEBUG'
warn = 'WARN'
info = 'INFO'
url = 'url'
tag = 'tag'
message = 'message'
log_level = 'level'
request_method = 'method'
response_status = 'status'
page = 'page'
show = 'show'
all = 'all' |
#
# Copyright(c) 2019-2020 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
class PresentationPolicy:
def __init__(self, standard_log, group_begin_func):
self.standard = standard_log
self.group_begin = group_begin_func
def std_log_entry(msg_id, msg, log_result, html_node):
p... | class Presentationpolicy:
def __init__(self, standard_log, group_begin_func):
self.standard = standard_log
self.group_begin = group_begin_func
def std_log_entry(msg_id, msg, log_result, html_node):
pass
def group_log_begin(msg_id, msg, html_node):
return (html_node, html_node)
null_policy... |
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator == 0:
return '0'
if numerator ^ denominator < 0:
result = '-'
else:
result = ''
numerator = abs(numerator)
denominator = abs(denomin... | class Solution:
def fraction_to_decimal(self, numerator: int, denominator: int) -> str:
if numerator == 0:
return '0'
if numerator ^ denominator < 0:
result = '-'
else:
result = ''
numerator = abs(numerator)
denominator = abs(denominator)
... |
class Tags(object):
"""A class to manage various AirWatch device tag functionalities"""
def __init__(self, client):
self.client = client
def get_id_by_name(self, name, og_id):
# mdm/tags/search?name={name}
response = self._get(path='/tags/search', params={'name':str(name), 'organiz... | class Tags(object):
"""A class to manage various AirWatch device tag functionalities"""
def __init__(self, client):
self.client = client
def get_id_by_name(self, name, og_id):
response = self._get(path='/tags/search', params={'name': str(name), 'organizationgroupid': str(og_id)})
r... |
def factors(x):
result = []
i = 1
while i*i <= x:
if x % i == 0:
result.append(i)
if x//i != i:
result.append(x//i)
i += 1
return result
for _ in range(int(input())):
a, b = [int(i) for i in input().split()]
m = 0
x = 0
for i in range(a, b + 1):
result = factors(i)
if ... | def factors(x):
result = []
i = 1
while i * i <= x:
if x % i == 0:
result.append(i)
if x // i != i:
result.append(x // i)
i += 1
return result
for _ in range(int(input())):
(a, b) = [int(i) for i in input().split()]
m = 0
x = 0
for ... |
# 92. Reverse Linked List II
# Runtime: 59 ms, faster than 5.80% of Python3 online submissions for Reverse Linked List II.
# Memory Usage: 14.7 MB, less than 5.82% of Python3 online submissions for Reverse Linked List II.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=No... | class Solution:
def __init__(self) -> None:
self._left_node: ListNode = None
self._stop: bool = False
def reverse_between(self, head: ListNode, left: int, right: int) -> ListNode:
if head is None:
return None
self._left_node = head
self._recurse_reverse(head... |
def conta_letras(frase, contar="vogais"):
''' Account the amount of consonants or vowels that the sentence has'''
lista_ord_vogais = [65, 69, 73, 79, 85, 97, 101, 105, 111, 117]
lista_ord_cosoantes = [66, 67, 68, 70, 71, 72, 74, 75, 76, 77, 78, 80,
81, 82, 83, 84, 86, 87, 88, 89, 90, 98, 99, 100, 102,... | def conta_letras(frase, contar='vogais'):
""" Account the amount of consonants or vowels that the sentence has"""
lista_ord_vogais = [65, 69, 73, 79, 85, 97, 101, 105, 111, 117]
lista_ord_cosoantes = [66, 67, 68, 70, 71, 72, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 98, 99, 100, 102, 103, ... |
class SingletonMeta(type):
def __init__(cls, name, bases, namespace):
super().__init__(name, bases, namespace)
cls.instance = None
def __call__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super().__call__(*args, **kwargs)
return cls.instance
cla... | class Singletonmeta(type):
def __init__(cls, name, bases, namespace):
super().__init__(name, bases, namespace)
cls.instance = None
def __call__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super().__call__(*args, **kwargs)
return cls.instance
clas... |
# Solution by PauloBA
def digital_root(n):
n = str(n)
ls = []
ans = 0
for i in n:
ls.append(int(i))
for i in ls:
ans = ans + i
if ans < 10:
return ans
else:
return digital_root(ans)
print(digital_root(24)) | def digital_root(n):
n = str(n)
ls = []
ans = 0
for i in n:
ls.append(int(i))
for i in ls:
ans = ans + i
if ans < 10:
return ans
else:
return digital_root(ans)
print(digital_root(24)) |
def gcd(a, b):
if min(a, b) == 0:
return max(a, b)
a_1 = max(a, b) % min(a, b)
return gcd(a_1, min(a, b))
def lcm(a, b):
return (a * b) // gcd(a, b) | def gcd(a, b):
if min(a, b) == 0:
return max(a, b)
a_1 = max(a, b) % min(a, b)
return gcd(a_1, min(a, b))
def lcm(a, b):
return a * b // gcd(a, b) |
class HelloMixin:
def display(self):
print('HelloMixin hello')
class SuperHelloMixin:
def display(self):
print('SuperHello hello')
class A(SuperHelloMixin, HelloMixin):
pass
if __name__ == '__main__':
a = A()
a.display()
| class Hellomixin:
def display(self):
print('HelloMixin hello')
class Superhellomixin:
def display(self):
print('SuperHello hello')
class A(SuperHelloMixin, HelloMixin):
pass
if __name__ == '__main__':
a = a()
a.display() |
def isPalindrome(string):
return string == string[::-1]
# OR
# left_pos = 0
# right_pos = len(string) - 1
#
# while right_pos >= left_pos:
# if(string[left_pos] != string[right_pos]):
# return False
# left_pos += 1
# right_pos -= 1
#
# re... | def is_palindrome(string):
return string == string[::-1]
print(is_palindrome('aza')) |
def select_rows(df, where):
"""Performs a series of rows selection in a DataFrame
Pandas provides several methods to select rows.
Using lambdas allows to select rows in a uniform and
more flexible way.
Parameters
----------
df: DataFrame
DataFrame whose rows should be selected
... | def select_rows(df, where):
"""Performs a series of rows selection in a DataFrame
Pandas provides several methods to select rows.
Using lambdas allows to select rows in a uniform and
more flexible way.
Parameters
----------
df: DataFrame
DataFrame whose rows should be selected
... |
# Semigroup = non-empty set with an associative binary operation
# using addition
print((2 + 3) + 4 == 2 + (3 + 4) == 9)
# We get a property of closure, because the number we get is still a number of the same set,
# natural numbers, including 0
# (2 + 3) + 4
# 2 + (3 + 4)
# 9
| print(2 + 3 + 4 == 2 + (3 + 4) == 9) |
# The MIT License
#
# Copyright (c) 2008 James Piechota
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... | class Error(Exception):
"""Base exception class.
Contains a string with an optional error message."""
def __init__(self, message):
self._message = message
def __str__(self):
return self._message
def __repr__(self):
return self._message
def __unicode__(self):
re... |
class Solution:
def maxPower(self, s: str) -> int:
power = []
i, temp = 1, ""
for s_char in s:
if s_char == temp:
i += 1
else:
power.append( i )
i = 1
temp = s_char
power.append(i)
r... | class Solution:
def max_power(self, s: str) -> int:
power = []
(i, temp) = (1, '')
for s_char in s:
if s_char == temp:
i += 1
else:
power.append(i)
i = 1
temp = s_char
power.append(i)
return ... |
def multiprocess_state_generator(video_frame_generator, stream_sha256):
"""Returns a packaged dict object for use in frame_process"""
for frame in video_frame_generator:
yield {'mode': 'video', 'main_sequence': True} | def multiprocess_state_generator(video_frame_generator, stream_sha256):
"""Returns a packaged dict object for use in frame_process"""
for frame in video_frame_generator:
yield {'mode': 'video', 'main_sequence': True} |
# Used Python for handling large integers
for _ in range(int(input())):
a,b = list(map(int,input().split()))
print(a*b)
| for _ in range(int(input())):
(a, b) = list(map(int, input().split()))
print(a * b) |
def solution(a, b):
answer = ''
month = {0:0, 1:31, 2:29, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
day = {1:'FRI',2:'SAT',3:'SUN', 4:'MON',5:'TUE',6:'WED', 0:'THU'}
d = 0
for i in range(0, a):
d += month[i]
d += b
answer = day[(d % 7)]
return answer | def solution(a, b):
answer = ''
month = {0: 0, 1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
day = {1: 'FRI', 2: 'SAT', 3: 'SUN', 4: 'MON', 5: 'TUE', 6: 'WED', 0: 'THU'}
d = 0
for i in range(0, a):
d += month[i]
d += b
answer = day[d % 7]
... |
# Function to calculate median
def calcMedian(arr, startIndex, endIndex):
index = ( startIndex + endIndex ) // 2
if (endIndex - startIndex + 1) % 2 == 0:
# return median for even no of elements
return ( arr[index] + arr[index + 1] ) // 2
else:
# return median for odd no of elements
... | def calc_median(arr, startIndex, endIndex):
index = (startIndex + endIndex) // 2
if (endIndex - startIndex + 1) % 2 == 0:
return (arr[index] + arr[index + 1]) // 2
else:
return arr[index]
n = int(input())
x = list(map(int, input().split()))
X.sort()
q1 = calc_median(X, 0, n // 2 - 1)
q2 = ca... |
# -*- coding: utf-8 -*-
# Initial permutation matrix
PI = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
6... | pi = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7]
cp_1 = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2... |
"""
Classes for IMPACTS P3 Instruments
"""
class P3(object):
"""
"""
def __init__(self, filepath, date):
pass
def readfile(self, filepath, ):
pass | """
Classes for IMPACTS P3 Instruments
"""
class P3(object):
"""
"""
def __init__(self, filepath, date):
pass
def readfile(self, filepath):
pass |
class Solution:
# @param {integer[]} nums
# @return {integer}
def singleNumber(self, nums):
a = set(nums)
a = sum(a)*2
singleNumber = a - sum(nums)
return singleNumber
| class Solution:
def single_number(self, nums):
a = set(nums)
a = sum(a) * 2
single_number = a - sum(nums)
return singleNumber |
#!/usr/bin/env python3
# Transistors.
"2N3904"
"2SC1815" # NPN?
"2SA9012"
"2SA1015" # PNP?
| """2N3904"""
'2SC1815'
'2SA9012'
'2SA1015' |
# coding: utf-8
__all__ = ['EikonError']
class EikonError(Exception):
"""
Base class for exceptions specific to Eikon platform.
"""
def __init__(self, code, message):
"""
Parameters
----------
code: int
message: string
Indicate the sort direction. ... | __all__ = ['EikonError']
class Eikonerror(Exception):
"""
Base class for exceptions specific to Eikon platform.
"""
def __init__(self, code, message):
"""
Parameters
----------
code: int
message: string
Indicate the sort direction. Possible values a... |
class Car:
# constructor
def __init__(self,name,fuel,consumption,passengers,capacity):
self.name = name
self.fuel = fuel
self.consumption = consumption
self.km = 0.0
self.passengers = passengers
self.capacity = capacity
# Behavior
def print_car(sel... | class Car:
def __init__(self, name, fuel, consumption, passengers, capacity):
self.name = name
self.fuel = fuel
self.consumption = consumption
self.km = 0.0
self.passengers = passengers
self.capacity = capacity
def print_car(self):
print(f'--- Car {self.... |
name = "pyilmbase"
version = "2.1.0"
description = \
"""
IlmBase Python bindings
"""
variants = [
["platform-linux"]
]
requires = [
"ilmbase-%s" % (version),
"python",
"boost"
]
uuid = "repository.pyilmbase"
def commands():
env.PATH.prepend("{root}/bin")
env.LD_LIBRARY_PATH.pre... | name = 'pyilmbase'
version = '2.1.0'
description = '\n IlmBase Python bindings\n '
variants = [['platform-linux']]
requires = ['ilmbase-%s' % version, 'python', 'boost']
uuid = 'repository.pyilmbase'
def commands():
env.PATH.prepend('{root}/bin')
env.LD_LIBRARY_PATH.prepend('{root}/lib')
env.PYTHONPA... |
vector = [{"name": "John Doe", "age": 37}, {"name": "Anna Doe", "age": 35}]
# for item in vector:
# print(item["name"])
print(list(map(lambda item: item["name"], vector)))
| vector = [{'name': 'John Doe', 'age': 37}, {'name': 'Anna Doe', 'age': 35}]
print(list(map(lambda item: item['name'], vector))) |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 9 19:48:15 2019
@author: Utente
"""
#Exercises Chapter 3
#3.2 do_four
def do_twice(func, arg):
func(arg)
func(arg)
def print_twice(arg):
print(arg)
print(arg)
def do_four(func, arg):
do_twice(func, arg... | """
Created on Sat Feb 9 19:48:15 2019
@author: Utente
"""
def do_twice(func, arg):
func(arg)
func(arg)
def print_twice(arg):
print(arg)
print(arg)
def do_four(func, arg):
do_twice(func, arg)
do_twice(func, arg)
do_twice(print_twice, 'cazzo vuoi')
print('')
do_four(print_twice, 'cazzo vuoi'... |
class FormattedWord:
def __init__(self, word, capitalize=False) -> None:
self.word = word
self.capitalize = capitalize
class Sentence(list):
def __init__(self, plain_text):
for word in plain_text.split(' '):
self.append(FormattedWord(word))
def __str__(self) -> str:
... | class Formattedword:
def __init__(self, word, capitalize=False) -> None:
self.word = word
self.capitalize = capitalize
class Sentence(list):
def __init__(self, plain_text):
for word in plain_text.split(' '):
self.append(formatted_word(word))
def __str__(self) -> str:
... |
"""
mat data format
{
1989: {
'AKS': {
2: (0.0534,0.1453) # age 2 (maturation rate, adult equivalent factor),
3: (0.0534,0.1453), # same format for age 3,
4: (0.0534,0.1453) # same format for age 4
},
...
},
...
}
"""
def parse_mat(file):
yea... | """
mat data format
{
1989: {
'AKS': {
2: (0.0534,0.1453) # age 2 (maturation rate, adult equivalent factor),
3: (0.0534,0.1453), # same format for age 3,
4: (0.0534,0.1453) # same format for age 4
},
...
},
...
}
"""
def parse_mat(file):
year... |
casa = float(input('Valor da casa: R$'))
salario = float(input('Salario do comprador R$'))
anos = int(input('Quantos anos de financiamento? '))
prestacao = casa / (anos * 12)
minimo = salario * 30 / 100
print('Para pagar uma casa de R${:.2f} em {} anos'.format(casa, anos))
if prestacao < minimo:
print('Emprestimo ... | casa = float(input('Valor da casa: R$'))
salario = float(input('Salario do comprador R$'))
anos = int(input('Quantos anos de financiamento? '))
prestacao = casa / (anos * 12)
minimo = salario * 30 / 100
print('Para pagar uma casa de R${:.2f} em {} anos'.format(casa, anos))
if prestacao < minimo:
print('Emprestimo p... |
class AutomatonListHelper:
'''
' Removes repeated elements from a list
'
' @param list array List that will be iterate
'
' @return list
'''
@staticmethod
def removeDuplicates(array):
final_list = []
for num in array:
if num not in final_list:
... | class Automatonlisthelper:
"""
' Removes repeated elements from a list
'
' @param list array List that will be iterate
'
' @return list
"""
@staticmethod
def remove_duplicates(array):
final_list = []
for num in array:
if num not in final_list:
... |
#! /usr/bin/python3
def print_sorted_dictionary_pairs(dict):
for key in sorted(dict):
print(key, dict[key])
def add_or_change_dictionary_value(dict, key, value):
dict[key] = value
def delete_dictionary_entry(dict, key):
if key in dict:
del dict[key]
else:
print(key, 'not found... | def print_sorted_dictionary_pairs(dict):
for key in sorted(dict):
print(key, dict[key])
def add_or_change_dictionary_value(dict, key, value):
dict[key] = value
def delete_dictionary_entry(dict, key):
if key in dict:
del dict[key]
else:
print(key, 'not found in dictionary')
def... |
########################################################################
def clamp(value, minimum=0.0, maximum=1.0):
return min(maximum, max(minimum, value))
########################################################################
def find_all_by_name(name, list_entities):
name = name.lower()
for entity i... | def clamp(value, minimum=0.0, maximum=1.0):
return min(maximum, max(minimum, value))
def find_all_by_name(name, list_entities):
name = name.lower()
for entity in list_entities:
if entity.match(name):
yield entity
def double_find_by_name(name, list_entities):
"""First try to find an... |
def printPacket(packet):
print(packet.to_json())
| def print_packet(packet):
print(packet.to_json()) |
# -*- coding: utf-8 -*-
#-----------
#@utool.indent_func('[harn]')
@profile
def test_configurations(ibs, acfgstr_name_list, test_cfg_name_list):
r"""
Test harness driver function
CommandLine:
python -m ibeis.expt.harness --exec-test_configurations --verbtd
python -m ibeis.expt.harness --e... | @profile
def test_configurations(ibs, acfgstr_name_list, test_cfg_name_list):
"""
Test harness driver function
CommandLine:
python -m ibeis.expt.harness --exec-test_configurations --verbtd
python -m ibeis.expt.harness --exec-test_configurations --verbtd --draw-rank-cdf --show
Example:
... |
#
# PySNMP MIB module IANA-PWE3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-PWE3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:30:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) ... |
# expected data for tests using FBgn0031208.gff and FBgn0031208.gtf files
# list the children and their expected first-order parents for the GFF test file.
GFF_parent_check_level_1 = {'FBtr0300690':['FBgn0031208'],
'FBtr0300689':['FBgn0031208'],
'CG11023:1':['FB... | gff_parent_check_level_1 = {'FBtr0300690': ['FBgn0031208'], 'FBtr0300689': ['FBgn0031208'], 'CG11023:1': ['FBtr0300689', 'FBtr0300690'], 'five_prime_UTR_FBgn0031208:1_737': ['FBtr0300689', 'FBtr0300690'], 'CDS_FBgn0031208:1_737': ['FBtr0300689', 'FBtr0300690'], 'intron_FBgn0031208:1_FBgn0031208:2': ['FBtr0300690'], 'in... |
def user_class(row_series):
"""
Defines the user class for this trip list.
This function takes a single argument, the pandas.Series with person, household and
trip_list attributes, and returns a user class string.
"""
# print row_series
if row_series["hh_id"] == "simpson":
return "... | def user_class(row_series):
"""
Defines the user class for this trip list.
This function takes a single argument, the pandas.Series with person, household and
trip_list attributes, and returns a user class string.
"""
if row_series['hh_id'] == 'simpson':
return 'not_real'
return 're... |
# 1. Even Numbers
# Write a program that receives a sequence of numbers (integers), separated by a single space.
# It should print a list of only the even numbers. Use filter().
def filter_even(iters):
return list(filter(lambda x: x % 2 == 0, iters))
nums = map(int, input().split())
print(filter_even(nums))
| def filter_even(iters):
return list(filter(lambda x: x % 2 == 0, iters))
nums = map(int, input().split())
print(filter_even(nums)) |
class Foo:
def __init__(self, id):
self.id = id
def __str__(self):
return 'Foo instance id: {}'.format(self.id)
class Bar:
def __init__(self, id):
self.id = id
def __str__(self):
return 'Bar instance id: {}'.format(self.id)
class Baz:
def __init__(self, id):
... | class Foo:
def __init__(self, id):
self.id = id
def __str__(self):
return 'Foo instance id: {}'.format(self.id)
class Bar:
def __init__(self, id):
self.id = id
def __str__(self):
return 'Bar instance id: {}'.format(self.id)
class Baz:
def __init__(self, id):
... |
#===========================================================================
#
# Convert decoded data to MQTT messages.
#
#===========================================================================
#===========================================================================
def convert( config, data ):
# List of t... | def convert(config, data):
msgs = []
if hasattr(data, 'battery'):
topic = config.mqttBattery % data.location
payload = {'time': data.time, 'battery': data.battery}
msgs.append((topic, payload))
if hasattr(data, 'signal'):
topic = config.mqttRssi % data.location
payloa... |
def special_sort(alphabet, s):
a = {c: i for i, c in enumerate(alphabet)}
return ''.join(sorted(list(s), key=lambda x: a[x.lower()]))
a = 'wvutsrqponmlkjihgfedcbaxyz'
t = 'camelCasE'
print(special_sort(a, t))
| def special_sort(alphabet, s):
a = {c: i for (i, c) in enumerate(alphabet)}
return ''.join(sorted(list(s), key=lambda x: a[x.lower()]))
a = 'wvutsrqponmlkjihgfedcbaxyz'
t = 'camelCasE'
print(special_sort(a, t)) |
# Next Greater Element I: https://leetcode.com/problems/next-greater-element-i/
# The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
# You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
# F... | class Solution:
def next_greater_element(self, nums1, nums2):
next_greater = {}
stack = []
for num in nums2:
while len(stack) > 0 and num > stack[-1]:
nextGreater[stack.pop()] = num
stack.append(num)
result = []
for num in nums1:
... |
'''
@Date: 2019-12-22 20:38:38
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors : ywyz
@LastEditTime : 2019-12-22 20:52:02
'''
strings = input("Enter the first 12 digits of an ISBN-13 as a string: ")
temp = 1
total = 0
for i in strings:
if temp % 2 == 0:
total += 3 * int(i)... | """
@Date: 2019-12-22 20:38:38
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors : ywyz
@LastEditTime : 2019-12-22 20:52:02
"""
strings = input('Enter the first 12 digits of an ISBN-13 as a string: ')
temp = 1
total = 0
for i in strings:
if temp % 2 == 0:
total += 3 * int(i)... |
# Generator used for all the Skinned Lanterns lantern variants!
lanterns = ["pufferfish", "zombie", "creeper", "skeleton", "wither_skeleton",
"bee", "jack_o_lantern", "ghost", "inky", "pinky", "blinky", "clyde", "pacman",
"paper_white", "paper_yellow", "paper_orange", "paper_blue", "paper_light_blue",
"paper_cyan", "p... | lanterns = ['pufferfish', 'zombie', 'creeper', 'skeleton', 'wither_skeleton', 'bee', 'jack_o_lantern', 'ghost', 'inky', 'pinky', 'blinky', 'clyde', 'pacman', 'paper_white', 'paper_yellow', 'paper_orange', 'paper_blue', 'paper_light_blue', 'paper_cyan', 'paper_lime', 'paper_green', 'paper_red', 'paper_pink', 'paper_brow... |
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for num in counter:
print(num) | def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for num in counter:
print(num) |
__strict__ = True
class SpotifyOauthError(Exception):
pass
class SpotifyRepositoryError(Exception):
def __init__(self, http_status: int, body: str):
self.http_status = http_status
self.body = body
def __str__(self):
return 'http status: {0}, code:{1}'.format(str(self.http_status... | __strict__ = True
class Spotifyoautherror(Exception):
pass
class Spotifyrepositoryerror(Exception):
def __init__(self, http_status: int, body: str):
self.http_status = http_status
self.body = body
def __str__(self):
return 'http status: {0}, code:{1}'.format(str(self.http_status)... |
# program numbers
BASIC = 140624
GOTO = 158250875866513204219300194287615
VARIABLES = 6198727823
| basic = 140624
goto = 158250875866513204219300194287615
variables = 6198727823 |
ENV_NAMES = {
"PASSWORD": "DECT_MAIL_EXTRACT_PASSWORD",
"USERNAME": "DECT_MAIL_EXTRACT_USER",
"SERVER": "DECT_MAIL_EXTRACT_SERVER",
}
| env_names = {'PASSWORD': 'DECT_MAIL_EXTRACT_PASSWORD', 'USERNAME': 'DECT_MAIL_EXTRACT_USER', 'SERVER': 'DECT_MAIL_EXTRACT_SERVER'} |
@customop('numpy')
def my_softmax(x, y):
probs = numpy.exp(x - numpy.max(x, axis=1, keepdims=True))
probs /= numpy.sum(probs, axis=1, keepdims=True)
N = x.shape[0]
loss = -numpy.sum(numpy.log(probs[numpy.arange(N), y])) / N
return loss
def my_softmax_grad(ans, x, y):
def grad(g):
N = x... | @customop('numpy')
def my_softmax(x, y):
probs = numpy.exp(x - numpy.max(x, axis=1, keepdims=True))
probs /= numpy.sum(probs, axis=1, keepdims=True)
n = x.shape[0]
loss = -numpy.sum(numpy.log(probs[numpy.arange(N), y])) / N
return loss
def my_softmax_grad(ans, x, y):
def grad(g):
n = x... |
""" This file was made for exercise 9-11"""
class Users:
def __init__(self, first_name, last_name, email, username):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.username = username
self.login_attempts = 0
def describe_user(self):
... | """ This file was made for exercise 9-11"""
class Users:
def __init__(self, first_name, last_name, email, username):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.username = username
self.login_attempts = 0
def describe_user(self):
... |
class MdFile():
def __init__(self, file_path, base_name, title, mdlinks):
self.uid = 0
self.file_path = file_path
self.base_name = base_name
self.title = title if title else base_name
self.mdlinks = mdlinks
def __str__(self):
return f'{self.uid}: {self.file_pat... | class Mdfile:
def __init__(self, file_path, base_name, title, mdlinks):
self.uid = 0
self.file_path = file_path
self.base_name = base_name
self.title = title if title else base_name
self.mdlinks = mdlinks
def __str__(self):
return f'{self.uid}: {self.file_path},... |
#/* *** ODSATag: MinVertex *** */
# Find the unvisited vertex with the smalled distance
def minVertex(G, D):
v = 0 # Initialize v to any unvisited vertex
for i in range(G.nodeCount()):
if G.getValue(i) != VISITED:
v = i
break
for i in range(G.nodeCount()): # Now find small... | def min_vertex(G, D):
v = 0
for i in range(G.nodeCount()):
if G.getValue(i) != VISITED:
v = i
break
for i in range(G.nodeCount()):
if G.getValue(i) != VISITED and D[i] < D[v]:
v = i
return v
def dijkstra(G, s, D):
for i in range(G.nodeCount()):
... |
config = {
# --------------------------------------------------------------------------
# Database Connections
# --------------------------------------------------------------------------
'database': {
'default': 'auth',
'connections': {
# SQLite
# 'auth': {
... | config = {'database': {'default': 'auth', 'connections': {'auth': {'driver': 'mysql', 'dialect': 'pymysql', 'host': '127.0.0.1', 'port': 3306, 'database': 'uvicore_test', 'username': 'root', 'password': 'techie', 'prefix': 'auth_'}}}} |
data = open('output_dataset_ALL.txt').readlines()
original = open('dataset_ALL.txt').readlines()
#data = open('dataset.txt').readlines()
out = open('output_gcode_merged.gcode', 'w')
for j in range(len(data)/4):
i = j*4
x = data[i].strip()
y = data[i+1].strip()
z = original[i+2].strip()
e = original... | data = open('output_dataset_ALL.txt').readlines()
original = open('dataset_ALL.txt').readlines()
out = open('output_gcode_merged.gcode', 'w')
for j in range(len(data) / 4):
i = j * 4
x = data[i].strip()
y = data[i + 1].strip()
z = original[i + 2].strip()
e = original[i + 3].strip()
out.write('G1... |
def adder_model(a, b):
"""
My golden reference model
"""
return my_adder(a, b)
def my_adder(a, b):
"""
My golden reference model
"""
return a + b | def adder_model(a, b):
"""
My golden reference model
"""
return my_adder(a, b)
def my_adder(a, b):
"""
My golden reference model
"""
return a + b |
##
# Copyright 2018, Ammar Ali Khan
# Licensed under MIT.
##
# Application configuration
APPLICATION_NAME = ''
APPLICATION_VERSION = '1.0.1'
# HTTP Port for web streaming
HTTP_PORT = 8000
# HTTP page template path
HTML_TEMPLATE_PATH = './src/common/package/http/template'
# Capturing device index (used for web camera... | application_name = ''
application_version = '1.0.1'
http_port = 8000
html_template_path = './src/common/package/http/template'
capturing_device = 0
use_pi_camera = True
width = 640
height = 480
resolution = [WIDTH, HEIGHT]
frame_rate = 24
database_name = 'database.db'
storage_directory = './dataset/'
unknown_prefix = '... |
Total_Fuel_Need =0
Data_File = open("Day1_Data.txt")
Data_Lines = Data_File.readlines()
for i in range(len(Data_Lines)):
Data_Lines[i] = int(Data_Lines[i].rstrip('\n'))
Total_Fuel_Need += int(Data_Lines[i] / 3) - 2
print(Total_Fuel_Need)
| total__fuel__need = 0
data__file = open('Day1_Data.txt')
data__lines = Data_File.readlines()
for i in range(len(Data_Lines)):
Data_Lines[i] = int(Data_Lines[i].rstrip('\n'))
total__fuel__need += int(Data_Lines[i] / 3) - 2
print(Total_Fuel_Need) |
# This sample tests the special-case handling of Self when comparing
# two functions whose signatures differ only in the Self scope.
class SomeClass:
def __str__(self) -> str:
...
__repr__ = __str__
| class Someclass:
def __str__(self) -> str:
...
__repr__ = __str__ |
lines = open("input").read().strip().splitlines()
print("--- Day11 ---")
class Seat:
directions = [
(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if (dx, dy) != (0, 0)
]
def __init__(self, x, y, dx, dy):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
def... | lines = open('input').read().strip().splitlines()
print('--- Day11 ---')
class Seat:
directions = [(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if (dx, dy) != (0, 0)]
def __init__(self, x, y, dx, dy):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
def p1(part2=False):
... |
#list = [1,2,3,4,5]
arr = list(range(1,6))
count = 0
#print(arr)
#for i in arr:
#print(i)
list = ["a","b","c","d","e"]
for index in range(len(arr)):
print(f'Phan tu tai vi tri {index} cua arr la : {list[index]}')
count += 1
print(count)
| arr = list(range(1, 6))
count = 0
list = ['a', 'b', 'c', 'd', 'e']
for index in range(len(arr)):
print(f'Phan tu tai vi tri {index} cua arr la : {list[index]}')
count += 1
print(count) |
def baseline3(X):
return (
X['ABS']
| X['INT']
| X['UINT']
| (X['TDEP'] > X['TDEP'].mean())
| (X['FIELD'] > X['FIELD'].mean())
| ((X['UAPI']+X['TUAPI']) > (X['UAPI']+X['TUAPI']).mean())
| (X['EXPCAT'] > 0)
| (X['RBFA'] > 0)
| (X['CONDCALL'] > 0... | def baseline3(X):
return X['ABS'] | X['INT'] | X['UINT'] | (X['TDEP'] > X['TDEP'].mean()) | (X['FIELD'] > X['FIELD'].mean()) | (X['UAPI'] + X['TUAPI'] > (X['UAPI'] + X['TUAPI']).mean()) | (X['EXPCAT'] > 0) | (X['RBFA'] > 0) | (X['CONDCALL'] > 0) | (X['SYNC'] > X['SYNC'].mean()) | (X['AFPR'] > 0) |
def search_in_rotated_array(alist, k, leftix=0, rightix=None):
if not rightix:
rightix = len(alist)
midpoint = (leftix + rightix) / 2
aleft, amiddle = alist[leftix], alist[midpoint]
if k == amiddle:
return midpoint
if k == aleft:
return leftix
if aleft > amiddle:
... | def search_in_rotated_array(alist, k, leftix=0, rightix=None):
if not rightix:
rightix = len(alist)
midpoint = (leftix + rightix) / 2
(aleft, amiddle) = (alist[leftix], alist[midpoint])
if k == amiddle:
return midpoint
if k == aleft:
return leftix
if aleft > amiddle:
... |
"""
Program functionalities module
"""
def create_transaction(day, value, type, description):
"""
:return: a dictionary that contains the data of a transaction
"""
return {'day': day, 'value': value, 'type': type, 'description': description}
def get_day(transaction):
"""
:retur... | """
Program functionalities module
"""
def create_transaction(day, value, type, description):
"""
:return: a dictionary that contains the data of a transaction
"""
return {'day': day, 'value': value, 'type': type, 'description': description}
def get_day(transaction):
"""
:return: the day of ... |
'''
https://www.codingame.com/training/easy/brackets-extreme-edition
'''
e = input()
d = {')': '(', ']': '[', '}': '{'}
s = []
for c in e:
if c in d.values():
s.append(c)
elif c in d.keys():
if len(s) == 0:
print("false")
exit(0)
else:
... | """
https://www.codingame.com/training/easy/brackets-extreme-edition
"""
e = input()
d = {')': '(', ']': '[', '}': '{'}
s = []
for c in e:
if c in d.values():
s.append(c)
elif c in d.keys():
if len(s) == 0:
print('false')
exit(0)
elif d[c] == s.pop():
... |
#!/usr/bin/env python
# from .api import SteamAPI
class SteamUser(object):
def __init__(self, steam_id=None, steam_api=None, **kwargs):
self.steam_id = steam_id
self.steam_api = steam_api
self.__dict__.update(**kwargs)
self._friends = None
self._games = None
self._... | class Steamuser(object):
def __init__(self, steam_id=None, steam_api=None, **kwargs):
self.steam_id = steam_id
self.steam_api = steam_api
self.__dict__.update(**kwargs)
self._friends = None
self._games = None
self._profile_data = None
self._profile_data_items... |
def parse_map(_map):
""" Returns a dictionary where from you can look
up which center a given orbiter has """
orbits = {}
for orbit in _map.split("\n"):
center, orbiter = orbit.split(")")
orbits[orbiter] = center
return orbits
def count_orbits(_map):
orbits = parse_map(_map)
orbiters = orbits.keys()
i ... | def parse_map(_map):
""" Returns a dictionary where from you can look
up which center a given orbiter has """
orbits = {}
for orbit in _map.split('\n'):
(center, orbiter) = orbit.split(')')
orbits[orbiter] = center
return orbits
def count_orbits(_map):
orbits = parse_map(_map)
... |
class Solution:
def solve(self, matrix):
if matrix[0][0] == 1: return -1
R,C = len(matrix),len(matrix[0])
bfs = deque([[0,0]])
dists = {(0,0): 1}
while bfs:
r,c = bfs.popleft()
if (r,c) == (R-1,C-1): return dists[r,c]
for nr,n... | class Solution:
def solve(self, matrix):
if matrix[0][0] == 1:
return -1
(r, c) = (len(matrix), len(matrix[0]))
bfs = deque([[0, 0]])
dists = {(0, 0): 1}
while bfs:
(r, c) = bfs.popleft()
if (r, c) == (R - 1, C - 1):
return... |
class Solution:
def rob(self, nums: list[int]) -> int:
if len(nums) == 0:
return 0
max_loot: list[int] = [0 for _ in nums]
for index, num in enumerate(nums):
if index == 0:
max_loot[index] = num
elif index == 1:
max_loot[in... | class Solution:
def rob(self, nums: list[int]) -> int:
if len(nums) == 0:
return 0
max_loot: list[int] = [0 for _ in nums]
for (index, num) in enumerate(nums):
if index == 0:
max_loot[index] = num
elif index == 1:
max_loot[... |
async def processEvent(event):
# Do event processing here ...
return event
| async def processEvent(event):
return event |
#!/usr/bin/env python
# coding=utf-8
"""
# pyORM : Implementation of managers.py
Summary :
<summary of module/class being implemented>
Use Case :
As a <actor> I want <outcome> So that <justification>
Testable Statements :
Can I <Boolean statement>
....
"""
__version__ = "0.1"
__author__ = 'Tony Flu... | """
# pyORM : Implementation of managers.py
Summary :
<summary of module/class being implemented>
Use Case :
As a <actor> I want <outcome> So that <justification>
Testable Statements :
Can I <Boolean statement>
....
"""
__version__ = '0.1'
__author__ = 'Tony Flury : anthony.flury@btinternet.com'
__c... |
print("\nAverage is being calculated\n")
APITimingFile = open("APITiming.txt", "r")
APITimingVals = APITimingFile.readlines()
sum = 0
for i in APITimingVals:
sum += float(i[slice(len(i)-2)])
print("\nThe average time of start providing is " + str(round(sum/len(APITimingVals), 4)) + "\n")
| print('\nAverage is being calculated\n')
api_timing_file = open('APITiming.txt', 'r')
api_timing_vals = APITimingFile.readlines()
sum = 0
for i in APITimingVals:
sum += float(i[slice(len(i) - 2)])
print('\nThe average time of start providing is ' + str(round(sum / len(APITimingVals), 4)) + '\n') |
class OrderLog:
def __init__(self, size):
self.log = list()
self.size = size
def __repr__(self):
return str(self.log)
def record(self, order_id):
self.log.append(order_id)
if len(self.log) > self.size:
self.log = self.log[1:]
def get_last(self, i):
... | class Orderlog:
def __init__(self, size):
self.log = list()
self.size = size
def __repr__(self):
return str(self.log)
def record(self, order_id):
self.log.append(order_id)
if len(self.log) > self.size:
self.log = self.log[1:]
def get_last(self, i):... |
#
# PySNMP MIB module OADHCP-SERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OADHCP-SERVER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:22:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
sample_split=1.0
data_loader_usage = 'Training'
training_data = "train_train"
evaluate_data = "privatetest"
| sample_split = 1.0
data_loader_usage = 'Training'
training_data = 'train_train'
evaluate_data = 'privatetest' |
# This function checks if year is a leap year.
def isLeapYear(year):
if year%100 == 0:
return True if year%400 == 0 else False
elif year%4 == 0:
return True
else:
return False
# This function returns the number of days in a month
def monthDays(year, month):
MONTHDAYS = (31, 28, ... | def is_leap_year(year):
if year % 100 == 0:
return True if year % 400 == 0 else False
elif year % 4 == 0:
return True
else:
return False
def month_days(year, month):
monthdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
if month == 2 and is_leap_year(year):
re... |
#encoding:utf-8
subreddit = 'wtf'
t_channel = '@reddit_wtf'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'wtf'
t_channel = '@reddit_wtf'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
programming_languages = ["Python", "Scala", "Haskell", "F#", "C#", "JavaScript"]
for lang in programming_languages:
if (lang == "Haskell"):
continue
print("Found Haskell !!!", end='\n') # this statement will never be executed
print(lang, end=' ') | programming_languages = ['Python', 'Scala', 'Haskell', 'F#', 'C#', 'JavaScript']
for lang in programming_languages:
if lang == 'Haskell':
continue
print('Found Haskell !!!', end='\n')
print(lang, end=' ') |
inc = 1
num = 1
for x in range (5,0,-1):
for y in range(x,0,-1):
print(" ",end="")
print(str(num)*inc)
num += 2
inc += 2 | inc = 1
num = 1
for x in range(5, 0, -1):
for y in range(x, 0, -1):
print(' ', end='')
print(str(num) * inc)
num += 2
inc += 2 |
n = int(input())
a = list(map(int, input().split()))
k_max = 0
g_max = 0
for k in range(2, max(a) + 1):
gcdness = 0
for elem in a:
if elem % k == 0:
gcdness += 1
if gcdness >= g_max:
g_max = gcdness
k_max = k
print(k_max) | n = int(input())
a = list(map(int, input().split()))
k_max = 0
g_max = 0
for k in range(2, max(a) + 1):
gcdness = 0
for elem in a:
if elem % k == 0:
gcdness += 1
if gcdness >= g_max:
g_max = gcdness
k_max = k
print(k_max) |
# 326. Power of Three
# ttungl@gmail.com
# Given an integer, write a function to determine if it is a power of three.
# Follow up:
# Could you do it without using any loop / recursion?
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
... | class Solution(object):
def is_power_of_three(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and 3 ** 19 % n == 0
if n <= 0:
return False
while n % 3 == 0:
n /= 3
return n == 1 |
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
result = ""
for index in range(n):
digitsLeft = n - index - 1
for c in range(1, 27):
if k - c <= digitsLeft * 26:
k -= c
result += chr(ord('a') + c -1... | class Solution:
def get_smallest_string(self, n: int, k: int) -> str:
result = ''
for index in range(n):
digits_left = n - index - 1
for c in range(1, 27):
if k - c <= digitsLeft * 26:
k -= c
result += chr(ord('a') + c ... |
a_val = int(input())
b_val = int(input())
def gcd(a, b):
if b > a:
a, b = b, a
if a % b == 0:
return b
else:
return gcd(b, a % b)
def reduce_fraction(n, m):
divider = gcd(n, m)
return int(n / divider), int(m / divider)
result = reduce_fraction(a_val, b_val)
print(*resul... | a_val = int(input())
b_val = int(input())
def gcd(a, b):
if b > a:
(a, b) = (b, a)
if a % b == 0:
return b
else:
return gcd(b, a % b)
def reduce_fraction(n, m):
divider = gcd(n, m)
return (int(n / divider), int(m / divider))
result = reduce_fraction(a_val, b_val)
print(*res... |
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 0
elif n < 0:
return (1.0 / x) ** abs(n)
else:
return x ** n
s = Solution()
print(s.myPow(2.00000, 10)) | class Solution:
def my_pow(self, x: float, n: int) -> float:
if n == 0:
return 0
elif n < 0:
return (1.0 / x) ** abs(n)
else:
return x ** n
s = solution()
print(s.myPow(2.0, 10)) |
MOD = 998244353
r, c, n = map(int, input().split())
dp = [[0] * (1 << c) for _ in range(r + 1)]
dp[0][0] = 1
for row in range(r):
for bit_prev in range(1 << c):
bit_prev <<= 1
for bit in range(1 << c):
bit <<= 1
count = 0
for i in range(c + 1):
i... | mod = 998244353
(r, c, n) = map(int, input().split())
dp = [[0] * (1 << c) for _ in range(r + 1)]
dp[0][0] = 1
for row in range(r):
for bit_prev in range(1 << c):
bit_prev <<= 1
for bit in range(1 << c):
bit <<= 1
count = 0
for i in range(c + 1):
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.