content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 10:39:07 2020
@author: BK
"""
| """
Created on Thu Nov 12 10:39:07 2020
@author: BK
""" |
#
## https://leetcode.com/problems/longest-substring-without-repeating-characters/
#
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if s is None:
raise ValueError('Parameter should be a String.')
if len(s) < 2:
return len(s)
st... | class Solution(object):
def length_of_longest_substring(self, s):
"""
:type s: str
:rtype: int
"""
if s is None:
raise value_error('Parameter should be a String.')
if len(s) < 2:
return len(s)
start = last_max_len = 0
for idx in range(len(... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... | def find_decision(obj):
if obj[10] <= 19:
if obj[9] <= 2:
if obj[14] <= 2.0:
if obj[7] > 0:
if obj[6] <= 4:
if obj[2] <= 3:
if obj[12] > 0.0:
if obj[3] > 0:
... |
###Database
#database typy Option:(mongodb, mysql, redis)
DB_TYPE = 'mongdb'
#database ip
DB_HOST = 'localhost'
#database port
DB_PORT = '1'
#username
#USERNAME = None
#passward
#PASSWARD = None
#database name
DB_DBNAME = 'quickspy'
###
| db_type = 'mongdb'
db_host = 'localhost'
db_port = '1'
db_dbname = 'quickspy' |
x = 1
while True:
x = input("Number:\n> ")
if int(x) == 0:
break
| x = 1
while True:
x = input('Number:\n> ')
if int(x) == 0:
break |
#!/usr/bin/env python
# coding: utf-8
# # *section 4: Strings*
#
# ### writer : Faranak Alikhah 1954128
# ### 12.Check Subset:
#
#
# In[ ]:
num_testCase=int(input())
for i in range(num_testCase):
num_testCase1=int(input())
a=set(input().split())
num_testCase2=int(input())
b=set(input().split())
... | num_test_case = int(input())
for i in range(num_testCase):
num_test_case1 = int(input())
a = set(input().split())
num_test_case2 = int(input())
b = set(input().split())
print(a.issubset(b)) |
# Exercise 105 - Parsing and Generating Dictionaries
'''Write a program that has a grades() function that can receive multiple grades
from students and will return a dictionary with the following information:
- Number of notes
- The highest grade
- The lowest grade
- The class average
- The situation (optional)
Als... | """Write a program that has a grades() function that can receive multiple grades
from students and will return a dictionary with the following information:
- Number of notes
- The highest grade
- The lowest grade
- The class average
- The situation (optional)
Also add the docstrings of this function for query by the... |
# Test case for PR#183; print of a recursive PyStringMap causes a JVM stack
# overflow.
g = globals()
print(g)
| g = globals()
print(g) |
###########################################################################
#
# Copyright 2019 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/... | custom_dimension_schema = [{'name': 'accountName', 'type': 'STRING'}, {'name': 'accountId', 'type': 'STRING'}, {'name': 'propertyName', 'type': 'STRING'}, {'name': 'propertyId', 'type': 'STRING'}, {'name': 'id', 'type': 'STRING'}, {'name': 'name', 'type': 'STRING'}, {'name': 'index', 'type': 'STRING'}, {'name': 'scope'... |
def score_hand(player_one: list, player_two: list):
if len(player_one) != 7 or len(player_two) != 7:
raise RuntimeError('invalid hands')
# pairs
player_one_pairs = player_one[1]
player_two_pairs = player_two[1]
player_one_has_pairs = len(player_one_pairs)
player_two_has_pairs = len(pla... | def score_hand(player_one: list, player_two: list):
if len(player_one) != 7 or len(player_two) != 7:
raise runtime_error('invalid hands')
player_one_pairs = player_one[1]
player_two_pairs = player_two[1]
player_one_has_pairs = len(player_one_pairs)
player_two_has_pairs = len(player_two_pairs... |
'''
Title : Zipped!
Subdomain : Built-Ins
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
n, x = map(int, input().split())
sheet = []
for _ in range(x):
sheet.append(map(float, input().split()) )
for i in zi... | """
Title : Zipped!
Subdomain : Built-Ins
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
"""
(n, x) = map(int, input().split())
sheet = []
for _ in range(x):
sheet.append(map(float, input().split()))
for i in zip(*sheet):
print(sum(i) / len(i)) |
class Solution:
def minIncrementForUnique(self, A: List[int]) -> int:
ans = 0
minAvailable = 0
A.sort()
for a in A:
ans += max(minAvailable - a, 0)
minAvailable = max(minAvailable, a) + 1
return ans
| class Solution:
def min_increment_for_unique(self, A: List[int]) -> int:
ans = 0
min_available = 0
A.sort()
for a in A:
ans += max(minAvailable - a, 0)
min_available = max(minAvailable, a) + 1
return ans |
#
# PySNMP MIB module HPN-ICF-ARP-RATELIMIT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-ARP-RATELIMIT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:37:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
expected_output = {'current-eta-records': 0,
'excess-packets-received': 60,
'excess-syn-received': 0,
'total-eta-fnf': 2,
'total-eta-idp': 2,
'total-eta-records': 4,
'total-eta-splt': 2,
'total-packets-out-of-order': 0,
'total-packets-received': 80,
'total-packets-retransmitted': 0}
| expected_output = {'current-eta-records': 0, 'excess-packets-received': 60, 'excess-syn-received': 0, 'total-eta-fnf': 2, 'total-eta-idp': 2, 'total-eta-records': 4, 'total-eta-splt': 2, 'total-packets-out-of-order': 0, 'total-packets-received': 80, 'total-packets-retransmitted': 0} |
class SomeSingleton(object):
__instance__ = None
def __new__(cls, *args,**kwargs):
if SomeSingleton.__instance__ is None:
SomeSingleton.__instance__ = object.__new__(cls)
return SomeSingleton.__instance__
def __init__(self,f=0,y=0):
self.f = f
self.y= y
def ... | class Somesingleton(object):
__instance__ = None
def __new__(cls, *args, **kwargs):
if SomeSingleton.__instance__ is None:
SomeSingleton.__instance__ = object.__new__(cls)
return SomeSingleton.__instance__
def __init__(self, f=0, y=0):
self.f = f
self.y = y
... |
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
hw = 0
while n != 0:
if n % 2 == 1:
hw += 1
n //= 2
return hw
| class Solution(object):
def hamming_weight(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
hw = 0
while n != 0:
if n % 2 == 1:
hw += 1
n //= 2
return hw |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 5 03:41:18 2019
@author: srishti
"""
print("Hello")
| """
Created on Fri Jul 5 03:41:18 2019
@author: srishti
"""
print('Hello') |
# import os
# BANK_URL = os.environ['BANK_URL']
# TRANSACTION_URL = os.environ['TRANSACTION_URL']
# UNDERWRITER_URL = os.environ['UNDERWRITER_URL']
# USER_URL = os.environ['USER_URL']
# applications_url = f"http://{UNDERWRITER_URL}/applications"
# registration_url = f"http://{USER_URL}/users/registration"
# login_url... | applications_url = 'http://localhost/applications'
registration_url = 'http://localhost/users/registration'
login_url = 'http://localhost/login'
bank_url = 'http://localhost/banks'
branch_url = 'http://localhost/branches'
transaction_url = 'http://localhost/transactions' |
# noinspection PyShadowingBuiltins,PyUnusedLocal
def compute(x, y):
"""The problem sets the parameters as integers in the range 0-100.
We'll raise an exception if we receive a type other than int, or if the value
of that int is not in the right range"""
if type(x) != int or type(y) != int:
raise... | def compute(x, y):
"""The problem sets the parameters as integers in the range 0-100.
We'll raise an exception if we receive a type other than int, or if the value
of that int is not in the right range"""
if type(x) != int or type(y) != int:
raise type_error('The types of both arguments must be ... |
for _ in range(int(input())):
a=input()
b=input()
s={}
ans=0
for i in range(26):
s[a[i]]=i+1
temp=[]
for j in b:
temp.append(s[j])
for k in range(len(temp)-1):
ans+=abs(temp[k]-temp[k+1])
print(ans) | for _ in range(int(input())):
a = input()
b = input()
s = {}
ans = 0
for i in range(26):
s[a[i]] = i + 1
temp = []
for j in b:
temp.append(s[j])
for k in range(len(temp) - 1):
ans += abs(temp[k] - temp[k + 1])
print(ans) |
def isPalindrome(str):
result = False
if str == str[::-1]:
result = True
return result
print("Please enter a string: ")
x = input()
flag = isPalindrome(x)
if flag:
print(x, "is a Palindrome")
else:
print(x, "is NOT a Palindrome")
| def is_palindrome(str):
result = False
if str == str[::-1]:
result = True
return result
print('Please enter a string: ')
x = input()
flag = is_palindrome(x)
if flag:
print(x, 'is a Palindrome')
else:
print(x, 'is NOT a Palindrome') |
"""
File: similarity.py
Name: Calvin Chen
----------------------------
This program compares short dna sequence, s2,
with sub sequences of a long dna sequence, s1
The way of approaching this task is the same as
what people are doing in the bio industry.
"""
def main():
"""
First, enter a long DNA sequence and... | """
File: similarity.py
Name: Calvin Chen
----------------------------
This program compares short dna sequence, s2,
with sub sequences of a long dna sequence, s1
The way of approaching this task is the same as
what people are doing in the bio industry.
"""
def main():
"""
First, enter a long DNA sequence and ... |
class Node:
def __init__(self, val):
self.val = val
self.next = None
def add(self, val):
if not self.next:
self.next = Node(val)
else:
self.next.add(val)
def remove(self, val):
if self.next.val == val:
self.next = self.next.next
... | class Node:
def __init__(self, val):
self.val = val
self.next = None
def add(self, val):
if not self.next:
self.next = node(val)
else:
self.next.add(val)
def remove(self, val):
if self.next.val == val:
self.next = self.next.next
... |
"""
@author: magician
@file: getattr_demo.py
@date: 2020/1/14
"""
class LazyDB(object):
"""
LazyDB
"""
def __init__(self):
self.exists = 5
def __getattr__(self, name):
value = 'Value for %s' % name
setattr(self, name, value)
return value
class LoggingLazyDB... | """
@author: magician
@file: getattr_demo.py
@date: 2020/1/14
"""
class Lazydb(object):
"""
LazyDB
"""
def __init__(self):
self.exists = 5
def __getattr__(self, name):
value = 'Value for %s' % name
setattr(self, name, value)
return value
class Logginglazydb(La... |
# File: factorial_recursion.py
# Purpose: Example: FActorial using recursion
# Programmer: Amal Shehu
# Course: Practice
# Date: Sunday 28th August 2016, 11:10 PM
num = int(input("Enter a number")) # Convert to an int
def factorial(num):
if (num == 0):
return
else:
re... | num = int(input('Enter a number'))
def factorial(num):
if num == 0:
return
else:
return num * factorial(num - 1)
result = factorial(num)
print(result) |
UNKNOWN_WORD = "<unk>"
embedding_dimension = 50
min_count = 5
window_size = 3
sample = 1e-3
negative = 5
vocab_size = None
train_words = None
# Special parameters
MIN_SENTENCE_LENGTH = 3 | unknown_word = '<unk>'
embedding_dimension = 50
min_count = 5
window_size = 3
sample = 0.001
negative = 5
vocab_size = None
train_words = None
min_sentence_length = 3 |
#!/usr/bin/python
DNB_YEARLY_PERCENTAGE = 2.10 / 100
DNB_MONTHLY_PERCENTAGE = DNB_YEARLY_PERCENTAGE / 12
DNB_FEE = 50
DNB_INITIAL_PAYMENT = 10000
NORDEA_YEARLY_PERCENTAGE = 2.15 / 100
NORDEA_MONTHLY_PERCENTAGE = NORDEA_YEARLY_PERCENTAGE / 12
NORDEA_FEE = 65
NORDEA_INITIAL_PAYMENT = 0
def months_until_paid_out(credit... | dnb_yearly_percentage = 2.1 / 100
dnb_monthly_percentage = DNB_YEARLY_PERCENTAGE / 12
dnb_fee = 50
dnb_initial_payment = 10000
nordea_yearly_percentage = 2.15 / 100
nordea_monthly_percentage = NORDEA_YEARLY_PERCENTAGE / 12
nordea_fee = 65
nordea_initial_payment = 0
def months_until_paid_out(credit_sum, monthly_payment... |
text="ANCHE TU BRUTO FIGLIO MIO?";
s=4;
result="";
text=text.upper();
for i in range(len(text)):
c = text[i];
if(c.isupper()):
result+=chr((ord(c)+s-65)%26+65);
else:
result+=chr((ord(c)+s-97)%26+97);
print(result);
| text = 'ANCHE TU BRUTO FIGLIO MIO?'
s = 4
result = ''
text = text.upper()
for i in range(len(text)):
c = text[i]
if c.isupper():
result += chr((ord(c) + s - 65) % 26 + 65)
else:
result += chr((ord(c) + s - 97) % 26 + 97)
print(result) |
# -*- encoding: utf-8 -*-
'''
@project : LeetCode
@File : diameterOfBinaryTree.py
@Contact : 9824373@qq.com
@Desc :
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2020-03-10 zhan 1.0 None
'''
# Definition f... | """
@project : LeetCode
@File : diameterOfBinaryTree.py
@Contact : 9824373@qq.com
@Desc :
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2020-03-10 zhan 1.0 None
"""
class Treenode:
def __init__(self, x... |
#!/usr/bin/env python
# -- coding: utf-8 --
"""
Copyright (c) 2019. All rights reserved.
Created by C. L. Wang on 2020/1/9
"""
dlatents_dir = 'latent_representations'
generated_dir = 'generated_images'
result_dir = 'results'
| """
Copyright (c) 2019. All rights reserved.
Created by C. L. Wang on 2020/1/9
"""
dlatents_dir = 'latent_representations'
generated_dir = 'generated_images'
result_dir = 'results' |
render = ez.Node()
aspect2D = ez.Node()
camera = ez.Camera(parent=render)
camera.y = -20
# Create collision shapes:
# Collision Sphere:
sphere = ez.collision.shapes.Sphere(0.25, parent=render)
sphere.parent = None
sphere.parent = render
# Collide from mask 2:
ez.collision.set_mask(sphere, ez.mask[2])
# Set what sph... | render = ez.Node()
aspect2_d = ez.Node()
camera = ez.Camera(parent=render)
camera.y = -20
sphere = ez.collision.shapes.Sphere(0.25, parent=render)
sphere.parent = None
sphere.parent = render
ez.collision.set_mask(sphere, ez.mask[2])
ez.collision.set_from_mask(sphere, ez.mask[1])
sphere.pos = (0, 0, 0)
sphere.show()
sph... |
while True:
senha=int(input('digite sua senha : '))
if senha==2:
print('acesso permitido')
break
else:
print('senha invalida, tente novamente') | while True:
senha = int(input('digite sua senha : '))
if senha == 2:
print('acesso permitido')
break
else:
print('senha invalida, tente novamente') |
#!/usr/bin/env python3
def myFunc(x, y):
if not isinstance(x, (int, float)):
raise TypeError('x has wrong type')
if not isinstance(y, (int, float)):
raise TypeError('y has wrong type')
else:
print(x + y)
myFunc(1, 3)
| def my_func(x, y):
if not isinstance(x, (int, float)):
raise type_error('x has wrong type')
if not isinstance(y, (int, float)):
raise type_error('y has wrong type')
else:
print(x + y)
my_func(1, 3) |
phonetic_alphabet = {"alpha": "A", "adam": "A", "boy": "B", "bravo": "B", "charlie": "C",
"delta": "D", "david": "D", "echo": "E", "edward": "E", "foxtrot": "F", "frank": "F",
"golf": "G", "george": "G", "hotel": "H", "henry": "H", "india": "I", "ida": "I",
"aida": "I", "juliette": "J", "john": "J", "kilo":... | phonetic_alphabet = {'alpha': 'A', 'adam': 'A', 'boy': 'B', 'bravo': 'B', 'charlie': 'C', 'delta': 'D', 'david': 'D', 'echo': 'E', 'edward': 'E', 'foxtrot': 'F', 'frank': 'F', 'golf': 'G', 'george': 'G', 'hotel': 'H', 'henry': 'H', 'india': 'I', 'ida': 'I', 'aida': 'I', 'juliette': 'J', 'john': 'J', 'kilo': 'K', 'king'... |
def decrypt(ciphertext, s):
pltext = ""
for i in range(len(ciphertext)):
char = ciphertext[i]
if (char.isupper()):
pltext += chr((ord(char) - s-65) % 26 + 65)
else:
pltext += chr((ord(char) - s - 97) % 26 + 97)
return pltext
ciphertext = "EXXEG... | def decrypt(ciphertext, s):
pltext = ''
for i in range(len(ciphertext)):
char = ciphertext[i]
if char.isupper():
pltext += chr((ord(char) - s - 65) % 26 + 65)
else:
pltext += chr((ord(char) - s - 97) % 26 + 97)
return pltext
ciphertext = 'EXXEGOEXSRGI'
s = 4
p... |
###############################################################################
# Copyright (c) 2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory
# Written by Francesco Di Natale, dinatale3@llnl.gov.
#
# LLNL-CODE-734340
# All rights reserved.
# This file is part ... | """Module that defines containers for storing various types of information."""
class Record(object):
"""A container class for holding general information."""
def __init__(self):
"""Initialize an empty Record."""
self._info = {}
def get(self, key, default=None):
"""
Get inf... |
# A non-empty array A consisting of N integers is given.
# A permutation is a sequence containing each element from 1 to N once, and only once.
# For example, array A such that:
# A[0] = 4
# A[1] = 1
# A[2] = 3
# A[3] = 2
# is a permutation, but array A such that:
# A[0] = 4
# A[1] = 1
# ... | def perm_check(A):
memo = {}
limit = len(A)
for element in A:
if not 1 <= element <= limit:
return 0
elif element in memo:
return 0
else:
memo[element] = True
return 1 |
ITCH_BASE = "itch.io"
ITCH_URL = f"https://{ITCH_BASE}"
ITCH_API = f"https://api.{ITCH_BASE}"
# Extracts https://user.itch.io/name to {'author': 'user', 'game': 'name'}
ITCH_GAME_URL_REGEX = r"^https:\/\/(?P<author>[\w\d\-_]+).itch.io\/(?P<game>[\w\d\-_]+)$"
ITCH_BROWSER_TYPES = [
"games",
"tools",
"game-... | itch_base = 'itch.io'
itch_url = f'https://{ITCH_BASE}'
itch_api = f'https://api.{ITCH_BASE}'
itch_game_url_regex = '^https:\\/\\/(?P<author>[\\w\\d\\-_]+).itch.io\\/(?P<game>[\\w\\d\\-_]+)$'
itch_browser_types = ['games', 'tools', 'game-assets', 'comics', 'books', 'physical-games', 'soundtracks', 'game-mods', 'misc'] |
"""
Tile providers.
This file is autogenerated! It is a python representation of the leaflet
providers defined by the leaflet-providers.js extension to Leaflet
(https://github.com/leaflet-extras/leaflet-providers).
Credit to the leaflet-providers.js project (BSD 2-Clause "Simplified" License)
and the Leaflet Provider... | """
Tile providers.
This file is autogenerated! It is a python representation of the leaflet
providers defined by the leaflet-providers.js extension to Leaflet
(https://github.com/leaflet-extras/leaflet-providers).
Credit to the leaflet-providers.js project (BSD 2-Clause "Simplified" License)
and the Leaflet Provider... |
class Solution:
"""
@param words: the n strings
@param target: the target string
@return: The ans
"""
def the_longest_common_prefix(self, words, target):
# write your code here
ans = 0
for word in words:
same = 0
for j in range(0, len(target)):
... | class Solution:
"""
@param words: the n strings
@param target: the target string
@return: The ans
"""
def the_longest_common_prefix(self, words, target):
ans = 0
for word in words:
same = 0
for j in range(0, len(target)):
if j > len(word) ... |
class DogeyError(Exception):
""" The base Dogey Exception, expect this as the main type of Dogey-specific errors such as InvalidCredentialsError. """
pass
class DogeyCommandError(Exception):
def __init__(self, command_name: str, message: str, *args):
""" The basic Dogey exception for commands, exp... | class Dogeyerror(Exception):
""" The base Dogey Exception, expect this as the main type of Dogey-specific errors such as InvalidCredentialsError. """
pass
class Dogeycommanderror(Exception):
def __init__(self, command_name: str, message: str, *args):
""" The basic Dogey exception for commands, exp... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n=int(input())
o=dict(zip('tminp',[0,1,1,2,3]))
a=sorted(enumerate([input().split()for _ in[0]*n]),key=lambda x:(o[x[1][1][2]],x[0]))
for x in a:print(x[1][0])
| """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n = int(input())
o = dict(zip('tminp', [0, 1, 1, 2, 3]))
a = sorted(enumerate([input().split() for _ in [0] * n]), key=lambda x: (o[x[1][1][2]], x[0]))
for x in a:
print(x[1][0]) |
sys_name = "XSS'OR"
sys_copyright = "@evilcos.me"
def sys(req):
return {
'sys_name': sys_name,
'sys_copyright': sys_copyright,
}
| sys_name = "XSS'OR"
sys_copyright = '@evilcos.me'
def sys(req):
return {'sys_name': sys_name, 'sys_copyright': sys_copyright} |
instrument_familes = {
'Strings': ['Guitar', 'Banjo', 'Sitar'],
'Percussion': ['Conga', 'Cymbal', 'Cajon'],
'woodwinds': ['Flute', 'Oboe', 'Clarinet']
}
class KeyError(Exception):
def __init__(self, key):
self.key = key
def __str__(self) -> str:
return f"Key {self.key} does not exist"
def print... | instrument_familes = {'Strings': ['Guitar', 'Banjo', 'Sitar'], 'Percussion': ['Conga', 'Cymbal', 'Cajon'], 'woodwinds': ['Flute', 'Oboe', 'Clarinet']}
class Keyerror(Exception):
def __init__(self, key):
self.key = key
def __str__(self) -> str:
return f'Key {self.key} does not exist'
def prin... |
def intersection(l1, l2):
res = [v for v in l1 if v in l2]
return res
def divide_into_primes(num, base=2, seq=None):
if seq is None:
seq = []
if num == 1:
return seq
for i in range(base, num+1):
if not num % i:
seq.append(i)
return divide_into_primes... | def intersection(l1, l2):
res = [v for v in l1 if v in l2]
return res
def divide_into_primes(num, base=2, seq=None):
if seq is None:
seq = []
if num == 1:
return seq
for i in range(base, num + 1):
if not num % i:
seq.append(i)
return divide_into_prime... |
#!/usr/bin/env python
# Copyright 2016-2021 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | """
This module contains all WORC-related Exceptions
"""
class Worcerror(Exception):
"""
This is the base class for all WORC related exceptions. Catching this
class of exceptions should ensure a proper execution of WORC.
"""
pass
class Worcnotimplementederror(WORCError, NotImplementedError):
"... |
def check(cmd, mf):
m = mf.findNode('uuid')
if m:
return dict(expected_missing_imports=set(['netbios', 'win32wnet']))
| def check(cmd, mf):
m = mf.findNode('uuid')
if m:
return dict(expected_missing_imports=set(['netbios', 'win32wnet'])) |
s = set()
for _ in range(int(input())):
s.add(input())
print (len(s))
# one line solution
print ( len(set([str(input()) for _ in range(int(input()))])) )
# https://www.hackerrank.com/challenges/py-set-add/problem | s = set()
for _ in range(int(input())):
s.add(input())
print(len(s))
print(len(set([str(input()) for _ in range(int(input()))]))) |
params = input().split(" ")
params = [int(param) for param in params]
if params[0] == params[1]:
for i in range(1, params[0] + 1):
print(input())
exit(0)
else:
all_gnomes = set(range(1, params[0] + 1))
remaining_gnomes = []
sorted = True
prev_gnome = -1
for _ in range(params[1]):... | params = input().split(' ')
params = [int(param) for param in params]
if params[0] == params[1]:
for i in range(1, params[0] + 1):
print(input())
exit(0)
else:
all_gnomes = set(range(1, params[0] + 1))
remaining_gnomes = []
sorted = True
prev_gnome = -1
for _ in range(params[1]):
... |
"""
Write a program that, given an ASCII binary matrix of 0's and 1's like this:
0000000000000000
0000000000000000
0000011001110000
0000001111010000
0000011001110000
0000011011100000
0000000000110000
0000101000010000
0000000000000000
0000000000000000
0000000000000000
Outputs the smallest cropped sub-matrix that still... | """
Write a program that, given an ASCII binary matrix of 0's and 1's like this:
0000000000000000
0000000000000000
0000011001110000
0000001111010000
0000011001110000
0000011011100000
0000000000110000
0000101000010000
0000000000000000
0000000000000000
0000000000000000
Outputs the smallest cropped sub-matrix that still... |
pointer=-1
lock=0
def setSeq(data) :
if lock == 1:
exit(2)
globals()['pointer']=-1
globals()['data']=data.split(',')
globals()['lock']=1
def raw_input() :
globals()['pointer']+=1
try:
return data[pointer]
except IndexError:
exit(0)
def open(path,mode) :
exit(3)
| pointer = -1
lock = 0
def set_seq(data):
if lock == 1:
exit(2)
globals()['pointer'] = -1
globals()['data'] = data.split(',')
globals()['lock'] = 1
def raw_input():
globals()['pointer'] += 1
try:
return data[pointer]
except IndexError:
exit(0)
def open(path, mode):
... |
result = 0
for i in range(1000):
if i%3==0 or i%5==0:
result += i
print(result) | result = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
result += i
print(result) |
"""
Get input from user via console or command line
-----------------------------------------------
Output: (string)
"""
name = input('What is your name? ')
print('Hello {}!'.format(name)) | """
Get input from user via console or command line
-----------------------------------------------
Output: (string)
"""
name = input('What is your name? ')
print('Hello {}!'.format(name)) |
text = input()
sum = 0
for symbol in text:
if symbol == "a":
sum += 1
elif symbol == "e":
sum += 2
elif symbol == "i":
sum += 3
elif symbol == "o":
sum += 4
elif symbol == "u":
sum += 5
print(sum) | text = input()
sum = 0
for symbol in text:
if symbol == 'a':
sum += 1
elif symbol == 'e':
sum += 2
elif symbol == 'i':
sum += 3
elif symbol == 'o':
sum += 4
elif symbol == 'u':
sum += 5
print(sum) |
"""
Remove Item
There are several methods to remove items from a list:
"""
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
| """
Remove Item
There are several methods to remove items from a list:
"""
thislist = ['apple', 'banana', 'cherry']
thislist.remove('banana')
print(thislist) |
debt = 95000
interest_percent = .059
yearly_salary = None
hourly_salary = 20
debt_repayment_percent = .2
debt_repayment_length = 0
work_days = 261
work_hours = 8
interest = 0
if yearly_salary and hourly_salary is not None:
if yearly_salary != hourly_salary * work_days * work_hours:
raise ValueError('only y... | debt = 95000
interest_percent = 0.059
yearly_salary = None
hourly_salary = 20
debt_repayment_percent = 0.2
debt_repayment_length = 0
work_days = 261
work_hours = 8
interest = 0
if yearly_salary and hourly_salary is not None:
if yearly_salary != hourly_salary * work_days * work_hours:
raise value_error('only... |
max_len = 79
str_plier = 2
foo = "Oh oh oh oh you don't know, Joe."*str_plier
curr_len = len(foo)
if curr_len > max_len:
print("Danger, Will Robinson!!!")
print("Your sentiment is {} ".format(curr_len-max_len)+"characters too long!")
else:
print("What a lovely sentiment!\n"+ foo+"\nIn only {} characters!".... | max_len = 79
str_plier = 2
foo = "Oh oh oh oh you don't know, Joe." * str_plier
curr_len = len(foo)
if curr_len > max_len:
print('Danger, Will Robinson!!!')
print('Your sentiment is {} '.format(curr_len - max_len) + 'characters too long!')
else:
print('What a lovely sentiment!\n' + foo + '\nIn only {} chara... |
#!/usr/bin/env python3
# compute nim values using negamax and a dictionary
# that holds values already computed RBH 2019
# version 2.0 December 2020 new features
# - verbose option, showing win/loss value once it is known
# - move initialization of the start position outside the main loop
# - tidying, e.g. pad... | def get_piles():
while True:
raw = input('nim game pile sizes (eg. 3 5 7) ')
try:
dim = tuple((int(x) for x in raw.split()))
if len(dim) > 0 and all((d >= 0 for d in dim)):
return dim
except ValueError:
pass
print('invalid, try ag... |
TEMPERATURE = 0x01
GAS = 0x02
VOLTAGE = 0x04
DELAY = 0x10
TEST_SUCCESS = 0x3F
ERROR_RELAY_OPEN = 0x04
ERROR_RELAY_CLOSED = 0x08
MODE_CONFIG = 0x80
MODE_RUN = 0x40
MODE_ERROR = 0xC0
MODE_TIMEOUT = 0x00
WRITE = 0x20
def print_status(state):
if(state&MODE_ERROR == MODE_ERROR):
print("ERROR MODE")
elif(state&MOD... | temperature = 1
gas = 2
voltage = 4
delay = 16
test_success = 63
error_relay_open = 4
error_relay_closed = 8
mode_config = 128
mode_run = 64
mode_error = 192
mode_timeout = 0
write = 32
def print_status(state):
if state & MODE_ERROR == MODE_ERROR:
print('ERROR MODE')
elif state & MODE_ERROR == MODE_TIM... |
# TODO write docs
class SceneDrawer(object):
def __init__(self, device, register):
self.device = device
self.background_color = "black"
self.entity_register = register
def draw(self, scene):
for entity in scene.entities:
if entity.drawer is not None:
... | class Scenedrawer(object):
def __init__(self, device, register):
self.device = device
self.background_color = 'black'
self.entity_register = register
def draw(self, scene):
for entity in scene.entities:
if entity.drawer is not None:
entity.drawer.dra... |
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 16
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
n = pow(2,1000)
digitSum = sum(int(i) for i in str(n))
return digitSum
if __name__ == "__main__":
print(run())
| """
Solution to Project Euler problem 16
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
n = pow(2, 1000)
digit_sum = sum((int(i) for i in str(n)))
return digitSum
if __name__ == '__main__':
print(run()) |
"""
Loop.
The loop() function causes draw() to execute
repeatedly. If noLoop is called in setup()
the draw() is only executed once. In this example
click the mouse to execute loop(), which will
cause the draw() to execute repeatedly.
"""
y = 100
def setup():
"""
The statements in the setup() function
r... | """
Loop.
The loop() function causes draw() to execute
repeatedly. If noLoop is called in setup()
the draw() is only executed once. In this example
click the mouse to execute loop(), which will
cause the draw() to execute repeatedly.
"""
y = 100
def setup():
"""
The statements in the setup() function
ru... |
"""align.py
Aligning two sequences. The elements of the sequences are stings or string like
elements, it is not clear to me what interface for the class is expected in the
latter case.
Originally written by Alex Plotnick.
"""
def align(a, b, d=-5, s=lambda x,y: x==y, key=lambda x: x, gap=None):
"""Find the glo... | """align.py
Aligning two sequences. The elements of the sequences are stings or string like
elements, it is not clear to me what interface for the class is expected in the
latter case.
Originally written by Alex Plotnick.
"""
def align(a, b, d=-5, s=lambda x, y: x == y, key=lambda x: x, gap=None):
"""Find the g... |
content = '''package main
import (
"context"
"github.com/qsock/qim/lib/proto/ret"
)
type Server struct{}
func (*Server) Ping(ctx context.Context, req *ret.NoArgs) (*ret.NoArgs, error) {
return new(ret.NoArgs), nil
}'''
def gen(name, srv_dir) :
with open(srv_dir+"/handle.go", "w") as f:
f.write(conte... | content = 'package main\n\nimport (\n\t"context"\n\t"github.com/qsock/qim/lib/proto/ret"\n)\n\ntype Server struct{}\n\nfunc (*Server) Ping(ctx context.Context, req *ret.NoArgs) (*ret.NoArgs, error) {\n\treturn new(ret.NoArgs), nil\n}'
def gen(name, srv_dir):
with open(srv_dir + '/handle.go', 'w') as f:
f.w... |
# Source : https://leetcode.com/problems/symmetric-tree/
# Author : penpenps
# Time : 2019-07-09
# Revert right node firstly, then compare with left node
# Time Complexity: O(n)
# Space Complexity: O(n)
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def is_symmetric(self, root: TreeNode) -> bool:
def revert(node):
if not node:
return
(node.left, node.right) = (node.right, node.lef... |
#!/usr/bin/python3
class MyList(list):
"""extended version of list
"""
def print_sorted(self):
"""prints the list in ascending order
"""
copy = self[:]
copy.sort()
print(copy)
| class Mylist(list):
"""extended version of list
"""
def print_sorted(self):
"""prints the list in ascending order
"""
copy = self[:]
copy.sort()
print(copy) |
"""
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.ans = None
... | """
"""
class Solution:
def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.ans = None
def recurse(node):
if not node:
return False
left = recurse(node.left)
right = recurse(node.right)
... |
result = [
{0: 0, 1: 'var 1'},
{0: 0, 1: 'var 2'}
]
| result = [{0: 0, 1: 'var 1'}, {0: 0, 1: 'var 2'}] |
result = 0
"""
i = 0
while i < 4:
nr = int(input("Please give me the number: "))
result += nr
i += 1
print("The result of adding numbers is: ", result)
"""
for i in range(1000):
if (i%2 == 0):
print(i, " is even number")
print("The result of adding numbers is: ", resu... | result = 0
'\ni = 0\nwhile i < 4:\n nr = int(input("Please give me the number: "))\n result += nr\n i += 1\n \nprint("The result of adding numbers is: ", result)\n'
for i in range(1000):
if i % 2 == 0:
print(i, ' is even number')
print('The result of adding numbers is: ', result) |
# https://github.com/lord63-forks/python-patterns/blob/patch-3/lazy_evaluation.py
def lazy_property(fn):
"""Decorator that makes a property lazy-evaluated."""
attr_name = '_lazy_' + fn.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr_name):
setattr(self, attr_... | def lazy_property(fn):
"""Decorator that makes a property lazy-evaluated."""
attr_name = '_lazy_' + fn.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazy_property
... |
description = 'memograph readout'
group = 'optional'
devices = dict(
t_in_fak40 = device('nicos_mlz.devices.memograph.MemographValue',
hostname = 'memograph02.care.frm2',
group = 1,
valuename = 'T_in MIRA',
description = 'inlet temperature memograph',
fmtstr = '%.2F',
... | description = 'memograph readout'
group = 'optional'
devices = dict(t_in_fak40=device('nicos_mlz.devices.memograph.MemographValue', hostname='memograph02.care.frm2', group=1, valuename='T_in MIRA', description='inlet temperature memograph', fmtstr='%.2F', warnlimits=(-1, 17.5), unit='degC'), t_out_fak40=device('nicos_m... |
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
print(S[0])
stack = []
for i in S:
if i=="#":
if len(stack)==0:
continue
stack.pop()
else:
s... | class Solution:
def backspace_compare(self, S: str, T: str) -> bool:
print(S[0])
stack = []
for i in S:
if i == '#':
if len(stack) == 0:
continue
stack.pop()
else:
stack.append(i)
s = ''
... |
# Tram, Minh
# mqt0029
# 1001540029
# 2019-05-13
#---------#---------#---------#---------#---------#--------#
class InternalError( Exception ) : pass
class LexicalError( Exception ) : pass
class SemanticError( Exception ) : pass
class SyntacticError( Exception ) : pass
#---------#---------#---------#---------#----... | class Internalerror(Exception):
pass
class Lexicalerror(Exception):
pass
class Semanticerror(Exception):
pass
class Syntacticerror(Exception):
pass |
def coord(x,y):
if x > 0 and y > 0:
i = "I"
elif x > 0 and y < 0:
i = "IV"
elif x < 0 and y < 0:
i = "III"
elif x < 0 and y > 0:
i = "II"
print(f"O ponto ({x:.0f}, {y:.0f}) pertence ao quadrante: {i}")
print(" ")
def main():
a = float(input("Digite um valor p... | def coord(x, y):
if x > 0 and y > 0:
i = 'I'
elif x > 0 and y < 0:
i = 'IV'
elif x < 0 and y < 0:
i = 'III'
elif x < 0 and y > 0:
i = 'II'
print(f'O ponto ({x:.0f}, {y:.0f}) pertence ao quadrante: {i}')
print(' ')
def main():
a = float(input('Digite um valor ... |
# -*- coding: utf-8 -*-
"""
Created on 31 Dec 2020 12:18:55
@author: jiahuei
"""
__version__ = "0.4.0"
| """
Created on 31 Dec 2020 12:18:55
@author: jiahuei
"""
__version__ = '0.4.0' |
#!/usr/bin/env python3
m = int(input())
if m < 100:
print("00")
elif m <= 5000:
print(str(m//100).zfill(2))
elif m <= 30000:
print(m//1000 + 50)
elif m <= 70000:
print((m//1000 - 30)//5 + 80)
else:
print(89) | m = int(input())
if m < 100:
print('00')
elif m <= 5000:
print(str(m // 100).zfill(2))
elif m <= 30000:
print(m // 1000 + 50)
elif m <= 70000:
print((m // 1000 - 30) // 5 + 80)
else:
print(89) |
# to compute modular power
# Iterative Function to calculate
# (x^y)%p in O(log y)
def power(x, y, p) :
res = 1 # Initialize result
# Update x if it is more
# than or equal to p
x = x % p
while (y > 0) :
# If y is odd, multiply
# x with result
... | def power(x, y, p):
res = 1
x = x % p
while y > 0:
if y & 1 == 1:
res = res * x % p
y = y >> 1
x = x * x % p
return res |
"""Utility class for formatting Slack Messages."""
def wrap_slack_code(str):
"""Format code."""
return f"`{str}`"
def wrap_code_block(str):
"""Format code block."""
return f"```\n{str}\n```"
def wrap_quote(str):
"""Format quote."""
return f"> {str}\n"
def wrap_emph(str):
"""Format em... | """Utility class for formatting Slack Messages."""
def wrap_slack_code(str):
"""Format code."""
return f'`{str}`'
def wrap_code_block(str):
"""Format code block."""
return f'```\n{str}\n```'
def wrap_quote(str):
"""Format quote."""
return f'> {str}\n'
def wrap_emph(str):
"""Format emph."... |
#print excepation information as a msg in program
try:
print(10/0)
except ZeroDivisionError as msg:
print("the type of error:",msg.__class__)
| try:
print(10 / 0)
except ZeroDivisionError as msg:
print('the type of error:', msg.__class__) |
'''Defines the `checkstyle_aspect`.
'''
load("//java:providers/JavaCompilationInfo.bzl", "JavaCompilationInfo")
load(
"//java:common/extract/toolchain_info.bzl",
"extract_java_runtime_toolchain_class_path_separator",
"extract_checkstyle_toolchain_info",
)
_JAVA_RUNTIME_TOOLCHAIN_TYPE = "@dwtj_rules_java//... | """Defines the `checkstyle_aspect`.
"""
load('//java:providers/JavaCompilationInfo.bzl', 'JavaCompilationInfo')
load('//java:common/extract/toolchain_info.bzl', 'extract_java_runtime_toolchain_class_path_separator', 'extract_checkstyle_toolchain_info')
_java_runtime_toolchain_type = '@dwtj_rules_java//java/toolchains/j... |
"""Common constants used across image quality modules."""
VALID_MASK_FORMAT = 'valid_mask_%s'
CERTAINTY_MASK_FORMAT = 'certainty_mask_%s'
PREDICTIONS_MASK_FORMAT = 'predictions_mask_%s'
ORIG_IMAGE_FORMAT = 'orig_name=%s'
PATCH_SIDE_LENGTH = 84
REMOTE_MODEL_CHECKPOINT_PATH = "https://storage.googleapis.com/microscope-... | """Common constants used across image quality modules."""
valid_mask_format = 'valid_mask_%s'
certainty_mask_format = 'certainty_mask_%s'
predictions_mask_format = 'predictions_mask_%s'
orig_image_format = 'orig_name=%s'
patch_side_length = 84
remote_model_checkpoint_path = 'https://storage.googleapis.com/microscope-im... |
expected_output = {
"interface_name": "Gi1/0/1",
"if_id": "75",
"phy_registers": {
"0": {
"register_number": "0000",
"hex_bit_value": "1140",
"register_name": "Control Register",
"bits": "0001000101000000",
},
"1": {
"regist... | expected_output = {'interface_name': 'Gi1/0/1', 'if_id': '75', 'phy_registers': {'0': {'register_number': '0000', 'hex_bit_value': '1140', 'register_name': 'Control Register', 'bits': '0001000101000000'}, '1': {'register_number': '0001', 'hex_bit_value': '796d', 'register_name': 'Control STATUS', 'bits': '0111100101101... |
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
l = set(nums1)
ret = [i for i in nums2 if i in l]
return list(set(ret)) | class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
l = set(nums1)
ret = [i for i in nums2 if i in l]
return list(set(ret)) |
# Class attributes ...
#
# Use dot to assign values to a class instance
class Point:
""" a 2D point """
p = Point()
p.x = 1
p.y = 2
assert p.x == 1
assert p.y == 2 | class Point:
""" a 2D point """
p = point()
p.x = 1
p.y = 2
assert p.x == 1
assert p.y == 2 |
"""API endpoints."""
class Endpoint(object):
API_PREFIX = '/api/'
VEHICLES = API_PREFIX + 'vehicles/' # ?dealer=AAA?model=XXX?fuel=YYY?transmission=ZZZ
DEALERS_CLOSEST_LIST = API_PREFIX + 'dealers/' # ?dealer=AAA?model=XXX?fuel=YYY?transmission=ZZZ?latitude=LLL?longitude=OOO
DEALER_CLOSEST = API_PREF... | """API endpoints."""
class Endpoint(object):
api_prefix = '/api/'
vehicles = API_PREFIX + 'vehicles/'
dealers_closest_list = API_PREFIX + 'dealers/'
dealer_closest = API_PREFIX + 'dealers/closest/'
dealers_in_polygon = API_PREFIX + 'dealers/polygon/'
bookings_create = API_PREFIX + 'bookings/cre... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 6 20:34:16 2019
@author: sodatab
MITx: 6.00.1x
"""
"""
01.2-Finger While Exercise 02
----------------------------
2. Convert the following into code that uses a while loop.
prints Hello!
prints 10
prints 8
prints 6
prints 4
prints 2
"""
"""Answ... | """
Created on Sun Oct 6 20:34:16 2019
@author: sodatab
MITx: 6.00.1x
"""
'\n01.2-Finger While Exercise 02\n----------------------------\n2. Convert the following into code that uses a while loop.\n\nprints Hello!\nprints 10\nprints 8\nprints 6\nprints 4\nprints 2\n'
'Answer Script:'
num = 12
print('Hello!')
while n... |
def solution(N):
b_rep = '{:b}'.format(N)
counter = 0
res = 0
prev_val = 0
count = False
for val in b_rep:
val = int(val)
if val - prev_val == -1:
count = True
counter += 1
if val - prev_val == 0 and count:
counter += 1
if val -... | def solution(N):
b_rep = '{:b}'.format(N)
counter = 0
res = 0
prev_val = 0
count = False
for val in b_rep:
val = int(val)
if val - prev_val == -1:
count = True
counter += 1
if val - prev_val == 0 and count:
counter += 1
if val -... |
x = 30;
y = 3;
## addition
print("x + y : ",x + y);
## we can use + for concatenate string
print("Hello, " + "World!");
## Subtraction
print("x - y : ",x - y);
## Division
print("x / y : ",x / y);
## here division operator always return float type number
## Multiplication
print("x * y : ",x*y);
# we can use * oper... | x = 30
y = 3
print('x + y : ', x + y)
print('Hello, ' + 'World!')
print('x - y : ', x - y)
print('x / y : ', x / y)
print('x * y : ', x * y)
print("'word '*5 : ", 'word' * 5)
print('x%6 : ', x % 6)
print('x//7 : ', x // 7)
print('2**4 : ', 2 ** 4) |
class YAMLEmptyError(Exception):
"""The yaml configs file is empty, nothing to read from there."""
class BadInputs(Exception):
"""Bad inputs"""
class PeaFailToStart(SystemError):
"""When pea is failed to started"""
class GRPCServerError(Exception):
"""Can not connect to the grpc gateway"""
class... | class Yamlemptyerror(Exception):
"""The yaml configs file is empty, nothing to read from there."""
class Badinputs(Exception):
"""Bad inputs"""
class Peafailtostart(SystemError):
"""When pea is failed to started"""
class Grpcservererror(Exception):
"""Can not connect to the grpc gateway"""
class Bad... |
#!/usr/bin/env python3
# Please make sure this file can be executed.
# chmod +x hello.py
print('Hello World!!')
| print('Hello World!!') |
def seta(n):
for i in range(n):
if i == n - 1:
print((2 * n) * '*', end='')
print((i + 1) * '*')
else:
print((2 * n) * ' ', end='')
print((i + 1) * '*')
for j in range(n - 1, 0, -1):
print((2 * n) * ' ',end='')
print(j * '*')
seta(1... | def seta(n):
for i in range(n):
if i == n - 1:
print(2 * n * '*', end='')
print((i + 1) * '*')
else:
print(2 * n * ' ', end='')
print((i + 1) * '*')
for j in range(n - 1, 0, -1):
print(2 * n * ' ', end='')
print(j * '*')
seta(10) |
'''input
atcoder beginner contest
ABC
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem A
if __name__ == '__main__':
a, b, c = input().split()
result = a[0] + b[0] + c[0]
print(result.upper())
| """input
atcoder beginner contest
ABC
"""
if __name__ == '__main__':
(a, b, c) = input().split()
result = a[0] + b[0] + c[0]
print(result.upper()) |
file = open("AAPL.txt", "r")
lines = file.readlines()
prices = []
for line in lines:
price = float(line)
prices.append(price)
print(price)
print(prices) | file = open('AAPL.txt', 'r')
lines = file.readlines()
prices = []
for line in lines:
price = float(line)
prices.append(price)
print(price)
print(prices) |
'''
Problem Description:
--------------------
The program reads a file and counts
the number of blank spaces in a text file.
'''
print(__doc__)
print('-'*25)
fileName=input('Enter file name: ')
k=0
with open(fileName,'r')as f:
for line in f:
words=line.split()
for i in words:
for letter in i:
... | """
Problem Description:
--------------------
The program reads a file and counts
the number of blank spaces in a text file.
"""
print(__doc__)
print('-' * 25)
file_name = input('Enter file name: ')
k = 0
with open(fileName, 'r') as f:
for line in f:
words = line.split()
for i in words:
... |
functions = {
'Add': (2, lambda p: p[0] + p[1]),
'Minus': (2, lambda p: p[0] - p[1]),
'UnaryMinus': (1, lambda p: -p[0]),
'Divide': (2, lambda p: p[0] / p[1]),
'Multiply': (2, lambda p: p[0] * p[1]),
'Modulo': (2, lambda p: p[0] % p[1]),
'EqualTo': (2, lambda p: p[0] == p[1]),
'NotEqualT... | functions = {'Add': (2, lambda p: p[0] + p[1]), 'Minus': (2, lambda p: p[0] - p[1]), 'UnaryMinus': (1, lambda p: -p[0]), 'Divide': (2, lambda p: p[0] / p[1]), 'Multiply': (2, lambda p: p[0] * p[1]), 'Modulo': (2, lambda p: p[0] % p[1]), 'EqualTo': (2, lambda p: p[0] == p[1]), 'NotEqualTo': (2, lambda p: p[0] != p[1]), ... |
class Features:
NOTEBOOKS = 'app.features.notebooks'
class Deployment:
SITE = 'app.deployment.site'
class Branding:
PRIVACY = 'app.configuration.privacy'
LICENSE = 'app.configuration.license'
HEADER_LOGO_ID = 'app.configuration.header.logo.file.id'
FOOTER_LOGO_ID = 'app.configuration.footer.lo... | class Features:
notebooks = 'app.features.notebooks'
class Deployment:
site = 'app.deployment.site'
class Branding:
privacy = 'app.configuration.privacy'
license = 'app.configuration.license'
header_logo_id = 'app.configuration.header.logo.file.id'
footer_logo_id = 'app.configuration.footer.lo... |
"""This problem was asked by Snapchat.
You are given an array of length N, where each element i represents the number of ways
we can produce i units of change. For example, [1, 0, 1, 1, 2] would indicate that
there is only one way to make 0, 2, or 3 units, and two ways of making 4 units.
Given such an array, determ... | """This problem was asked by Snapchat.
You are given an array of length N, where each element i represents the number of ways
we can produce i units of change. For example, [1, 0, 1, 1, 2] would indicate that
there is only one way to make 0, 2, or 3 units, and two ways of making 4 units.
Given such an array, determ... |
WIDTH = 512
HEIGHT = 336
FPS = 50
PIX_FOR_BRIX = 16
STEPS_FOR_CYCLE = 16
N_STEP_FOR_TEST = 5
BLACK = (0, 0, 0)
BKGR = (0, 0, 0)
| width = 512
height = 336
fps = 50
pix_for_brix = 16
steps_for_cycle = 16
n_step_for_test = 5
black = (0, 0, 0)
bkgr = (0, 0, 0) |
# -*- coding: utf-8 -*-
"""
.. module:: pytfa
:platform: Unix, Windows
:synopsis: Thermodynamics-based Flux Analysis
.. moduleauthor:: pyTFA team
Pre-tuned configurations for faster solving
"""
def dg_relax_config(model):
"""
:param model:
:return:
"""
# grbtune output on a hard model :
... | """
.. module:: pytfa
:platform: Unix, Windows
:synopsis: Thermodynamics-based Flux Analysis
.. moduleauthor:: pyTFA team
Pre-tuned configurations for faster solving
"""
def dg_relax_config(model):
"""
:param model:
:return:
"""
if model.solver.interface.__name__ == 'optlang.gurobi_interf... |
"""
PASSENGERS
"""
numPassengers = 3217
passenger_arriving = (
(6, 3, 5, 3, 2, 0, 6, 8, 4, 2, 4, 0), # 0
(5, 11, 6, 2, 1, 0, 7, 9, 7, 3, 1, 0), # 1
(3, 8, 6, 4, 3, 0, 5, 12, 3, 7, 1, 0), # 2
(6, 6, 6, 5, 3, 0, 3, 7, 5, 5, 3, 0), # 3
(1, 4, 7, 4, 4, 0, 7, 11, 9, 6, 3, 0), # 4
(5, 11, 5, 5, 0, 0, 5, 9, 4, 4... | """
PASSENGERS
"""
num_passengers = 3217
passenger_arriving = ((6, 3, 5, 3, 2, 0, 6, 8, 4, 2, 4, 0), (5, 11, 6, 2, 1, 0, 7, 9, 7, 3, 1, 0), (3, 8, 6, 4, 3, 0, 5, 12, 3, 7, 1, 0), (6, 6, 6, 5, 3, 0, 3, 7, 5, 5, 3, 0), (1, 4, 7, 4, 4, 0, 7, 11, 9, 6, 3, 0), (5, 11, 5, 5, 0, 0, 5, 9, 4, 4, 1, 0), (3, 8, 16, 3, 2, 0, 7, 12... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.