content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
nome = input('Qual o seu nome? ')
sobrenome = input('Qual o seu sobrenome? ')
print('Seja bem-vindo(a), {} {}!'.format(nome, sobrenome))
print('Ordem natural: {0} {1}'.format(nome, sobrenome))
print('Ordem inversa: {1} {0}'.format(nome, sobrenome))
print('Outra forma: {0} {1} {other}'.format(nome, sobrenome, other = 'S... | nome = input('Qual o seu nome? ')
sobrenome = input('Qual o seu sobrenome? ')
print('Seja bem-vindo(a), {} {}!'.format(nome, sobrenome))
print('Ordem natural: {0} {1}'.format(nome, sobrenome))
print('Ordem inversa: {1} {0}'.format(nome, sobrenome))
print('Outra forma: {0} {1} {other}'.format(nome, sobrenome, other='San... |
# import time
# import os
# import stat
# import random
# import string
#
# import pytest
#
# import cattle
#
# from kubernetes import client as k8sclient, config as k8sconfig
#
BASE_URL = "http://%ip%:9333/v1"
token = ""
fqdn = ""
create_param = {
'fqdn': '',
'hosts': ["1.1.1.1", "2.2.2.2"]
}
update_param = ... | base_url = 'http://%ip%:9333/v1'
token = ''
fqdn = ''
create_param = {'fqdn': '', 'hosts': ['1.1.1.1', '2.2.2.2']}
update_param = {'fqdn': '', 'hosts': ['3.3.3.3']}
def set_token_fqdn(result):
global token, fqdn
token = result['token']
fqdn = result['data']['fqdn']
def get_token_fqdn():
return (token,... |
a, b, i = 0, 1, 2
fibo = [a, b]
while i < 100:
i = i + 1
a, b = b, a+b
fibo.append(b)
| (a, b, i) = (0, 1, 2)
fibo = [a, b]
while i < 100:
i = i + 1
(a, b) = (b, a + b)
fibo.append(b) |
# Recursive solution for permutation
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result = []
self.permu_helper(nums, [], result)
return result
def permu_helper(self, new_list, temp, result):
if len(new_list) == 0:
result.append(temp)
... | class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result = []
self.permu_helper(nums, [], result)
return result
def permu_helper(self, new_list, temp, result):
if len(new_list) == 0:
result.append(temp)
return
for i in range(... |
rankDict = {
'1': 'A',
'11': 'J',
'12': 'Q',
'13': 'K'
}
class Rank:
def __init__(self, number):
if not (1 <= number <= 13):
raise Exception("number is out of range")
self.number = number
def __str__(self):
return rankDict.get(str(self.number), str(self.number))
| rank_dict = {'1': 'A', '11': 'J', '12': 'Q', '13': 'K'}
class Rank:
def __init__(self, number):
if not 1 <= number <= 13:
raise exception('number is out of range')
self.number = number
def __str__(self):
return rankDict.get(str(self.number), str(self.number)) |
def server(host, port, symmetricKey):
sockVanilla = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockVanilla.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sockVanilla.bind((host, port))
sockVanilla.listen(5)
while True:
sockClientVanilla, source = sockVanilla.accept()
... | def server(host, port, symmetricKey):
sock_vanilla = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockVanilla.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sockVanilla.bind((host, port))
sockVanilla.listen(5)
while True:
(sock_client_vanilla, source) = sockVanilla.accept()
... |
name_list= ['Sharon','Mic','Josh','Hannah','Hansel']
height_list = [172,166,187,200,166]
weight_list = [59.5,65.6,49.8,64.2,47.5]
size_list = ['M','L','S','M','S']
bmi_list = []
for i in range(len(name_list)):
bmi = weight_list[i]/((height_list[i]/100)**2)
bmi_list.append('{:.2f}'.format(bmi))
print("{:<10} {... | name_list = ['Sharon', 'Mic', 'Josh', 'Hannah', 'Hansel']
height_list = [172, 166, 187, 200, 166]
weight_list = [59.5, 65.6, 49.8, 64.2, 47.5]
size_list = ['M', 'L', 'S', 'M', 'S']
bmi_list = []
for i in range(len(name_list)):
bmi = weight_list[i] / (height_list[i] / 100) ** 2
bmi_list.append('{:.2f}'.format(bm... |
def get_fuel(fuel):
fuel = ((fuel // 3) - 2)
if fuel <= 0:
return 0
return fuel + get_fuel(fuel)
total = 0
with open("d1.txt", "r") as f:
for line in f:
total += get_fuel(int(line))
print(total)
| def get_fuel(fuel):
fuel = fuel // 3 - 2
if fuel <= 0:
return 0
return fuel + get_fuel(fuel)
total = 0
with open('d1.txt', 'r') as f:
for line in f:
total += get_fuel(int(line))
print(total) |
print("""
Note!
A matrix is said to be sparse matrix if most of the elements of that matrix are 0.
It implies that it contains very less non-zero elements.
""")
# To check whether the given matrix is the sparse matrix or not,
# we first count the number of zero elements present in the matrix.
# Then calculate ... | print('\nNote!\nA matrix is said to be sparse matrix if most of the elements of that matrix are 0.\nIt implies that it contains very less non-zero elements.\n')
matrix = []
row = int(input('Enter row size of the matrix: '))
column = int(input('Enter column size of the matrix: '))
for i in range(row):
a = []
for... |
"""
15740 : A+B - 9
URL : https://www.acmicpc.net/problem/15750
Input #1 :
1 2
Output #1 :
3
Input #2 :
-60 40
Output #2 :
-20
Input #3 :
-999999999 1000000000
Output #3 :
1
Input #4 :
1099511627776 1073741824
Output #4 :
... | """
15740 : A+B - 9
URL : https://www.acmicpc.net/problem/15750
Input #1 :
1 2
Output #1 :
3
Input #2 :
-60 40
Output #2 :
-20
Input #3 :
-999999999 1000000000
Output #3 :
1
Input #4 :
1099511627776 1073741824
Output #4 :
... |
def impares_no_intervalo(intervalo: tuple, lista: list):
inicial, final = intervalo
return [numero for numero in lista if numero % 2 != 0 and inicial <= numero <= final]
limite = (0,10)
l = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# --- OUTPUT ---
# [1, 3, 5, 7, 9]
print(impares_no_intervalo(... | def impares_no_intervalo(intervalo: tuple, lista: list):
(inicial, final) = intervalo
return [numero for numero in lista if numero % 2 != 0 and inicial <= numero <= final]
limite = (0, 10)
l = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(impares_no_intervalo(limite, l)) |
# -- coding:utf-8--
class DL(object):
def __init__(self):
self.dlcs = 0
def q(self):
self.dlcs = self.dlcs + 1
print(str(self.dlcs))
def a(self):
self.dlcs = 0
print(str(self.dlcs))
hi = DL()
hi.q()
hi.q()
hi.q()
hi.q()
hi.q()
hi.a() | class Dl(object):
def __init__(self):
self.dlcs = 0
def q(self):
self.dlcs = self.dlcs + 1
print(str(self.dlcs))
def a(self):
self.dlcs = 0
print(str(self.dlcs))
hi = dl()
hi.q()
hi.q()
hi.q()
hi.q()
hi.q()
hi.a() |
#
# This file contains the Python code from Program 8.20 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm08_20.txt
#
class OpenScatterT... | class Openscattertablev2(OpenScatterTable):
def withdraw(self, obj):
if self._count == 0:
raise ContainerEmpty
i = self.findInstance(obj)
if i < 0:
raise KeyError
while True:
j = (i + 1) % len(self)
while self._array[j]._state == self.... |
# CodeWars Count_Of_Positives_/_Sum_Of_Negatives
def count_positives_sum_negatives(arr):
null_list = []
sum_of_positives = 0
sum_of_negatives = 0
if arr == [0, 0] or arr == []:
return null_list
for i in arr:
if i > 0:
sum_of_positives += 1
elif i < 0:
... | def count_positives_sum_negatives(arr):
null_list = []
sum_of_positives = 0
sum_of_negatives = 0
if arr == [0, 0] or arr == []:
return null_list
for i in arr:
if i > 0:
sum_of_positives += 1
elif i < 0:
sum_of_negatives += i
else:
c... |
"""
best time to use this times you're pretty sure list is almost sorted
o(n)
worst case(o(n^2))
"""
array = [99, 44, 6, 2, 1, 5, 63, 87, 283, 40]
def insertionSort(array):
count = 0
for i in range(1, len(array)):
first = array[i]
last = array[i-1] # store the last element which is sorted
... | """
best time to use this times you're pretty sure list is almost sorted
o(n)
worst case(o(n^2))
"""
array = [99, 44, 6, 2, 1, 5, 63, 87, 283, 40]
def insertion_sort(array):
count = 0
for i in range(1, len(array)):
first = array[i]
last = array[i - 1]
count += 1
if first < last:... |
class Student:
email = 'default@redi-school.org'
def __init__(self, name, birthday, courses):
# class public attributes
self.full_name = name
self.first_name = name.split(' ')[0]
self.birthday = birthday
self.courses = courses
self.attendance = []
# Objects
joh... | class Student:
email = 'default@redi-school.org'
def __init__(self, name, birthday, courses):
self.full_name = name
self.first_name = name.split(' ')[0]
self.birthday = birthday
self.courses = courses
self.attendance = []
john = student('John Schneider', '2010-04-05', ['... |
"""
Creational :
Builder => every builders designed patterns has director class to attach
each side of objects
"""
class Director:
__builder = None
def set_builder(self, builder):
self.__builder = builder
def get_car(self):
car = Car()
body = self.... | """
Creational :
Builder => every builders designed patterns has director class to attach
each side of objects
"""
class Director:
__builder = None
def set_builder(self, builder):
self.__builder = builder
def get_car(self):
car = car()
body = self.__... |
class NumArray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.nums = [0] * len(nums)
self.sums = [0] * (len(nums) + 1)
for i, num in enumerate(nums):
self.update(i, num)
def update(s... | class Numarray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.nums = [0] * len(nums)
self.sums = [0] * (len(nums) + 1)
for (i, num) in enumerate(nums):
self.update(i, num)
def update... |
def get_ip_address(request):
"""use request object to fetch client machine's IP Address"""
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR") ### Real IP address of client Machine
... | def get_ip_address(request):
"""use request object to fetch client machine's IP Address"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def phone_num_val(phone_n... |
# Task
# Given sets of integers, M and N, print their symmetric difference in ascending order.
# The term symmetric difference indicates those values that exist in either M or N but do not
# exist in both.
#
# Input Format
# The first line of input contains an integer, M.
# The second line contains M space-separated i... | (m, m_set) = (int(input()), set(input().split()))
(n, n_set) = (int(input()), set(input().split()))
values_in_m = m_set.difference(n_set)
values_in_n = n_set.difference(m_set)
m_union_n = values_in_m.union(values_in_n)
for number in sorted((int(i) for i in m_union_n)):
print(number) |
SOC_IRAM_LOW = 0x4037c000
SOC_IRAM_HIGH = 0x403e0000
SOC_DRAM_LOW = 0x3fc80000
SOC_DRAM_HIGH = 0x3fce0000
SOC_RTC_DRAM_LOW = 0x50000000
SOC_RTC_DRAM_HIGH = 0x50002000
SOC_RTC_DATA_LOW = 0x50000000
SOC_RTC_DATA_HIGH = 0x50002000
| soc_iram_low = 1077395456
soc_iram_high = 1077805056
soc_dram_low = 1070071808
soc_dram_high = 1070465024
soc_rtc_dram_low = 1342177280
soc_rtc_dram_high = 1342185472
soc_rtc_data_low = 1342177280
soc_rtc_data_high = 1342185472 |
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_first(self, data):
node = Node(data, self.head)
self.head = node
def __repr__(self):
return str(sel... | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class Linkedlist:
def __init__(self):
self.head = None
def insert_first(self, data):
node = node(data, self.head)
self.head = node
def __repr__(self):
return str(self.h... |
"""Configuration Values"""
# DRIVER = 'mysql+pymysql://'
# URL_PARAMS = {
# 'username': 'root',
# 'password': 'root',
# 'host': 'localhost',
# 'port': '3306',
# 'database_name': 'hydro'
# }
# URL = DRIVER + '{username}:{password}@{host}:{port}/{database_name}'.format(
# **URL_PARAMS)
class ... | """Configuration Values"""
class Config(object):
secret_key = ''.join('4ed2e994cba06266df65170068c57ae7227482ddac10cfbd49d35f8e28b5fa0b')
send_file_max_age_default = 0 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# Base exception class
class QlibException(Exception):
pass
class RecorderInitializationError(QlibException):
"""Error type for re-initialization when starting an experiment"""
class LoadObjectError(QlibException):
"""Error type ... | class Qlibexception(Exception):
pass
class Recorderinitializationerror(QlibException):
"""Error type for re-initialization when starting an experiment"""
class Loadobjecterror(QlibException):
"""Error type for Recorder when can not load object"""
class Expalreadyexisterror(Exception):
"""Experiment a... |
"""
Given an integer n and an integer start.
Define an array nums where nums[i] = start + 2*i (0-indexed) and
n == nums.length.
Return the bitwise XOR of all elements of nums.
Example:
Input: n = 5, start = 0
Output: 8
Explanation... | """
Given an integer n and an integer start.
Define an array nums where nums[i] = start + 2*i (0-indexed) and
n == nums.length.
Return the bitwise XOR of all elements of nums.
Example:
Input: n = 5, start = 0
Output: 8
Explanation... |
#! /usr/bin/env python3
"""control the whitespaces in string"""
s = 'The Little Price'
# justify string to be at least width wide
# by adding whitespaces
width = 20
s1 = s.ljust(width)
s2 = s.rjust(width)
s3 = s.center(width)
print(s1) # 'The Little Price '
print(s2) # ' The Little Price'
print(s3) # ' T... | """control the whitespaces in string"""
s = 'The Little Price'
width = 20
s1 = s.ljust(width)
s2 = s.rjust(width)
s3 = s.center(width)
print(s1)
print(s2)
print(s3)
print(s3.lstrip())
print(s3.rstrip())
print(s3.strip()) |
"""exercism armstrong numbers module."""
def is_armstrong_number(number):
"""
Determine if the number provided is an Armstrong Number.
An Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits
:param number int - Number to check.
:return b... | """exercism armstrong numbers module."""
def is_armstrong_number(number):
"""
Determine if the number provided is an Armstrong Number.
An Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits
:param number int - Number to check.
:return bo... |
"""Generic Models."""
class CaseInsensitiveString(str):
"""A case insensitive string to aid comparison."""
def __eq__(self, other: object) -> bool:
"""Determine whether this object and another object are equal.
Parameters:
other: The object to compare this one to.
Raises... | """Generic Models."""
class Caseinsensitivestring(str):
"""A case insensitive string to aid comparison."""
def __eq__(self, other: object) -> bool:
"""Determine whether this object and another object are equal.
Parameters:
other: The object to compare this one to.
Raises:... |
def make_withdraw(balance):
"""Return a withdraw function with a starting balance."""
def withdraw(amount):
nonlocal balance
if amount > balance:
return 'Insufficient funds'
balance = balance - amount
return balance
return withdraw
def make_withdraw_list(balance)... | def make_withdraw(balance):
"""Return a withdraw function with a starting balance."""
def withdraw(amount):
nonlocal balance
if amount > balance:
return 'Insufficient funds'
balance = balance - amount
return balance
return withdraw
def make_withdraw_list(balance... |
#!/usr/bin/env python
class DataHelper:
"""
Helper to retrieve data from particular nodes
"""
@staticmethod
def get_bucket(root, parents):
"""Get bucket name from root and parent nodes"""
path = root.get("path", "")
if path:
# assume path like /pools/default
... | class Datahelper:
"""
Helper to retrieve data from particular nodes
"""
@staticmethod
def get_bucket(root, parents):
"""Get bucket name from root and parent nodes"""
path = root.get('path', '')
if path:
return path.split('/')[-1]
else:
return ... |
"""
You are given an m x n integer matrix heights representing the height of each unit cell in a continent.
The Pacific ocean touches the continent's left and top edges,
and the Atlantic ocean touches the continent's right and bottom edges.
Water can only flow in four directions: up, down, left, and right.
Water fl... | """
You are given an m x n integer matrix heights representing the height of each unit cell in a continent.
The Pacific ocean touches the continent's left and top edges,
and the Atlantic ocean touches the continent's right and bottom edges.
Water can only flow in four directions: up, down, left, and right.
Water fl... |
# [Grand Athenaeum]
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.sendNext("Supposedly the White Mage was last seen in Ellin Forest. If that's true, there must be evidence.")
sm.sendSay("Ephenia the Fairy Queen's dwelling is nearby. I'll see if she knows anything.")
sm.startQuest(parentID) | sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.sendNext("Supposedly the White Mage was last seen in Ellin Forest. If that's true, there must be evidence.")
sm.sendSay("Ephenia the Fairy Queen's dwelling is nearby. I'll see if she knows anything.")
sm.startQuest(parentID) |
# reference.py
# This script is for image references
cookieurl = ["https://media1.tenor.com/images/45fe45f75ec523c2abf4e75ca2ac2fe2/tenor.gif?itemid=11797931",
"https://media1.tenor.com/images/de6a49b999216fbda779cd27a24919c3/tenor.gif?itemid=19073253"]
cookiesurl = ["https://media1.tenor.com/images/30c8c... | cookieurl = ['https://media1.tenor.com/images/45fe45f75ec523c2abf4e75ca2ac2fe2/tenor.gif?itemid=11797931', 'https://media1.tenor.com/images/de6a49b999216fbda779cd27a24919c3/tenor.gif?itemid=19073253']
cookiesurl = ['https://media1.tenor.com/images/30c8ce96272fe73f58841164a179f6d1/tenor.gif?itemid=17729544', 'https://me... |
def D():
n = int(input())
neighbours = [None] #Asi puedo manejar numero de personas como index
for i in range(n):
neighbours.append([int(x) for x in input().split()])
visited = set()
ans = [None,1]
visited.add(1)
a , b = neighbours[1][0] , neighbours[1][1]
if(b in neighbours[a]):
ans+=[a,b]
else:
ans... | def d():
n = int(input())
neighbours = [None]
for i in range(n):
neighbours.append([int(x) for x in input().split()])
visited = set()
ans = [None, 1]
visited.add(1)
(a, b) = (neighbours[1][0], neighbours[1][1])
if b in neighbours[a]:
ans += [a, b]
else:
ans +=... |
# Count total cars per company
# My Solution
df.groupby('company').count()
# Given Solution
df['company'].value_counts()
| df.groupby('company').count()
df['company'].value_counts() |
'''
Python Program to Remove the Duplicate Items from a List
'''
lst = [3,5,2,7,5,4,3,7,8,2,5,4,7,2,1]
print(lst)
def method():
new_lst = []
for item in lst:
if item not in new_lst:
new_lst.append(item)
print(new_lst)
method()
| """
Python Program to Remove the Duplicate Items from a List
"""
lst = [3, 5, 2, 7, 5, 4, 3, 7, 8, 2, 5, 4, 7, 2, 1]
print(lst)
def method():
new_lst = []
for item in lst:
if item not in new_lst:
new_lst.append(item)
print(new_lst)
method() |
# this module is the template of all environment in this project
# some basic and common features are listed in this class
class ENVError(Exception):
def __init__(self, value_):
self.__value = value_
def __str__(self):
print('Environment error occur: ' + self.__value)
class ENV:
def __ini... | class Enverror(Exception):
def __init__(self, value_):
self.__value = value_
def __str__(self):
print('Environment error occur: ' + self.__value)
class Env:
def __init__(self):
pass
def reset(self):
raise env_error('You have not defined the reset function of environm... |
'''Identify whether the given input is polindrome'''
def is_polindrome_word(input_word):
"""Check whether the given word is polindrome or not"""
status = True
input_word = input_word.replace(' ', '').lower()
index = 0
while index < (len(input_word)/2):
if input_word[index] != input_word[(in... | """Identify whether the given input is polindrome"""
def is_polindrome_word(input_word):
"""Check whether the given word is polindrome or not"""
status = True
input_word = input_word.replace(' ', '').lower()
index = 0
while index < len(input_word) / 2:
if input_word[index] != input_word[ind... |
#Given two strings s and t, determine if they are isomorphic.
#
#Two strings are isomorphic if the characters in s can be replaced to get t.
#
#All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character... | class Solution(object):
def is_isomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict1 = {}
dict2 = {}
if len(s) != len(t):
return False
for i in xrange(len(s)):
if s[i] in dict1 and dict1[s[i]] != t[i]:
re... |
C_ENDINGS = ('.c', '.i', )
CXX_ENDINGS = ('.cpp', '.cxx', '.cc', '.c++', '.CPP', '.CXX', '.C', '.CC', '.C++', '.ii', )
OBJC_ENDINGS = ('.m', '.mi', )
OBJCXX_ENDINGS = ('.mm', '.mii', )
FORTRAN_ENDINGS = ('.f', '.for', '.ftn', '.f77', '.f90', '.f95', '.f03', '.f08',
'.F', '.FOR', '.FTN', '.F77', '.F90', '.F95',... | c_endings = ('.c', '.i')
cxx_endings = ('.cpp', '.cxx', '.cc', '.c++', '.CPP', '.CXX', '.C', '.CC', '.C++', '.ii')
objc_endings = ('.m', '.mi')
objcxx_endings = ('.mm', '.mii')
fortran_endings = ('.f', '.for', '.ftn', '.f77', '.f90', '.f95', '.f03', '.f08', '.F', '.FOR', '.FTN', '.F77', '.F90', '.F95', '.F03', '.F08')
... |
#Python solution for AoC qn 2
f = open("2.txt","r")
strings = f.readlines()
#Part 1
freq_total = {
"2":0,
"3":0
}
for s in strings:
s = s.strip().lower()
freq_indv = {}
#Count how many of each letter is inside
for ch in s:
if ch in freq_indv:
freq_indv[ch]+=1
el... | f = open('2.txt', 'r')
strings = f.readlines()
freq_total = {'2': 0, '3': 0}
for s in strings:
s = s.strip().lower()
freq_indv = {}
for ch in s:
if ch in freq_indv:
freq_indv[ch] += 1
else:
freq_indv[ch] = 1
found = {'2': False, '3': False}
for ch in freq_indv... |
class Solution:
@staticmethod
def naive(prices):
maxReturn = 0
minVal = prices[0]
for i in range(1,len(prices)):
if prices[i]-minVal > maxReturn:
maxReturn = prices[i]-minVal
if prices[i]<minVal:
minVal = prices[i]
return m... | class Solution:
@staticmethod
def naive(prices):
max_return = 0
min_val = prices[0]
for i in range(1, len(prices)):
if prices[i] - minVal > maxReturn:
max_return = prices[i] - minVal
if prices[i] < minVal:
min_val = prices[i]
... |
'''
subsets and subarrays
subarrays:
a = [10,20,30]
=> [
[10], [20], [30]
[10,20], [10,20,30], [20,30],
]
subsets:
a = [10,20,30]
=> [
[], [10,20,30]
[10], [20], [30], [10, 20], [10, 30], [20, 30]
]
'''
def print_subsets(a):
limit = 2 ** len(a)
for i in ra... | """
subsets and subarrays
subarrays:
a = [10,20,30]
=> [
[10], [20], [30]
[10,20], [10,20,30], [20,30],
]
subsets:
a = [10,20,30]
=> [
[], [10,20,30]
[10], [20], [30], [10, 20], [10, 30], [20, 30]
]
"""
def print_subsets(a):
limit = 2 ** len(a)
for i in r... |
# -*- coding: utf-8 -*-
# blue to red diverging set
blue_to_red_diverging = ['#d7191c', '#fdae61', '#ffffbf', '#abd9e9', '#2c7bb6']
# red oragne sequential single hue:
orange_sequential = ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c',
'#f16913', '#d94801', '#a63603', '#7f2704']
# blue s... | blue_to_red_diverging = ['#d7191c', '#fdae61', '#ffffbf', '#abd9e9', '#2c7bb6']
orange_sequential = ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c', '#f16913', '#d94801', '#a63603', '#7f2704']
blue_sequential = ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b']
mp... |
'''
Author : Hemant Rana
Date : 30th Aug 2020
link : https://leetcode.com/problems/container-with-most-water
'''
class Solution:
def maxArea(self, height: List[int]) -> int:
h_len=len(height)
max_area=0
b,e=0,h_len-1
while(b<e):
area=min(height[b],height[e])*(e-... | """
Author : Hemant Rana
Date : 30th Aug 2020
link : https://leetcode.com/problems/container-with-most-water
"""
class Solution:
def max_area(self, height: List[int]) -> int:
h_len = len(height)
max_area = 0
(b, e) = (0, h_len - 1)
while b < e:
area = min(height[b], hei... |
class Struct(object):
def __init__(self, data=None, **kwds):
if not data:
data = {}
for name, value in data.items():
if name:
setattr(self, name, self._wrap(value))
for name, value in kwds.items():
if name:
setattr(self, nam... | class Struct(object):
def __init__(self, data=None, **kwds):
if not data:
data = {}
for (name, value) in data.items():
if name:
setattr(self, name, self._wrap(value))
for (name, value) in kwds.items():
if name:
setattr(self... |
"""
This includes constants that may be used in the connectivity_libs module.
"""
WEBTIMEOUT = 5
NUM_OF_WORKER_PROCESSES = 4
REGEX_IP = r'(?P<ip_address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))'
REGEX_EMAIL = r'[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a... | """
This includes constants that may be used in the connectivity_libs module.
"""
webtimeout = 5
num_of_worker_processes = 4
regex_ip = '(?P<ip_address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))'
regex_email = '[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[... |
##To find the kth maximum number in an array.
lst=[]
len=int(input("Enter the length of the array.\n"))
for i in range(0,len):
e=input("Enter the element.\n")
lst.append(e)
k=int(input("Enter the value of k\n"))
lst.sort(reverse=True)
f=k-1
print(lst[f])
| lst = []
len = int(input('Enter the length of the array.\n'))
for i in range(0, len):
e = input('Enter the element.\n')
lst.append(e)
k = int(input('Enter the value of k\n'))
lst.sort(reverse=True)
f = k - 1
print(lst[f]) |
__all__ = ['status_in_range', 'response_time_under',
'response_time_above', 'status_must_be']
def status_must_be(value: int = None, expected: int = 200) -> bool:
"""
Validates the status code of a HTTP call is as expected.
"""
return value == expected
def status_in_range(value: int, lower... | __all__ = ['status_in_range', 'response_time_under', 'response_time_above', 'status_must_be']
def status_must_be(value: int=None, expected: int=200) -> bool:
"""
Validates the status code of a HTTP call is as expected.
"""
return value == expected
def status_in_range(value: int, lower: int=100, upper:... |
# create a list of movies
list_of_movies = None
list_of_movies = [
'Toy Story',
'Lion King',
'Coco'
]
# cycle through each movie title in the list of movies
# starting from the first item and ending at the last item
for movie_title in list_of_movies:
print('***{}***'.format(movie... | list_of_movies = None
list_of_movies = ['Toy Story', 'Lion King', 'Coco']
for movie_title in list_of_movies:
print('***{}***'.format(movie_title))
word = ''
for letter in movie_title:
print(' {}'.format(letter))
word += letter
print('The letters create the word variable >>{}'.format(wor... |
'''
Run through and ensure that all the required programs are installed on the system
and functioning
'''
| """
Run through and ensure that all the required programs are installed on the system
and functioning
""" |
def solution(n, computers):
def dfs(n, s, metrix, visited):
stack = [s]
visited.add(s)
while stack:
this = stack[-1]
remove = True
for i in range(n):
if this == i:
continue
if i in visited:
... | def solution(n, computers):
def dfs(n, s, metrix, visited):
stack = [s]
visited.add(s)
while stack:
this = stack[-1]
remove = True
for i in range(n):
if this == i:
continue
if i in visited:
... |
def is_paired(input_string: str) -> bool:
input_string = clean_input_string(input_string)
if len(input_string) % 2 != 0:
return False
while input_string:
if not remove_bracket(input_string[0], input_string):
return False
return True
def remove_bracket(bracket: str, inpu... | def is_paired(input_string: str) -> bool:
input_string = clean_input_string(input_string)
if len(input_string) % 2 != 0:
return False
while input_string:
if not remove_bracket(input_string[0], input_string):
return False
return True
def remove_bracket(bracket: str, input_str... |
def _(string):
"""Emulates gettext method"""
return string
__version__ = "0.8.2"
__description__ = _("EncFS GUI managing tool")
__generic_name__ = _("EncFS manager")
| def _(string):
"""Emulates gettext method"""
return string
__version__ = '0.8.2'
__description__ = _('EncFS GUI managing tool')
__generic_name__ = _('EncFS manager') |
def test_oops(client):
url = f'/fake-path'
response = client.get(url)
assert response.status_code == 404 | def test_oops(client):
url = f'/fake-path'
response = client.get(url)
assert response.status_code == 404 |
#-*- coding: utf-8 -*-
class ValueDefinition:
str_val_dict = {}
val_str_dict = {}
@classmethod
def get(cls, data):
if not cls.val_str_dict:
cls.val_str_dict = dict(zip(cls.str_val_dict.values(), cls.str_val_dict.keys()))
if type(data) == str:
return cls.str_val_d... | class Valuedefinition:
str_val_dict = {}
val_str_dict = {}
@classmethod
def get(cls, data):
if not cls.val_str_dict:
cls.val_str_dict = dict(zip(cls.str_val_dict.values(), cls.str_val_dict.keys()))
if type(data) == str:
return cls.str_val_dict.get(data)
e... |
strip_words = [
'Kind',
'MAE',
'Pandemisch'
]
skip_names = [
'Water'
]
ignore_names = [
'alfalfa',
'ali',
'belladonna',
'cold',
'drank',
'gas',
'hot',
'linn',
'sepia',
'skin',
'slow',
'stol',
'ultra',
'vicks',
'vitamine',
'yasmin'
]
# re... | strip_words = ['Kind', 'MAE', 'Pandemisch']
skip_names = ['Water']
ignore_names = ['alfalfa', 'ali', 'belladonna', 'cold', 'drank', 'gas', 'hot', 'linn', 'sepia', 'skin', 'slow', 'stol', 'ultra', 'vicks', 'vitamine', 'yasmin'] |
class Solution:
def canJump(self, nums) -> bool:
"""
nums: List[int]
Given an array of non-negative integers, you are initially
positioned at the first index of the array.
Each element in the array represents your maximum jump length at that
position.
... | class Solution:
def can_jump(self, nums) -> bool:
"""
nums: List[int]
Given an array of non-negative integers, you are initially
positioned at the first index of the array.
Each element in the array represents your maximum jump length at that
position.
De... |
#!/usr/bin/env python
esInputs = "/home/matthieu/.emulationstation/es_input.cfg"
esSettings = '/home/matthieu/.emulationstation/es_settings.cfg'
recalboxConf = "/home/matthieu/recalbox/recalbox.conf"
retroarchRoot = "/home/matthieu/recalbox/configs/retroarch"
retroarchCustom = retroarchRoot + '/retroarchcustom.cfg'
r... | es_inputs = '/home/matthieu/.emulationstation/es_input.cfg'
es_settings = '/home/matthieu/.emulationstation/es_settings.cfg'
recalbox_conf = '/home/matthieu/recalbox/recalbox.conf'
retroarch_root = '/home/matthieu/recalbox/configs/retroarch'
retroarch_custom = retroarchRoot + '/retroarchcustom.cfg'
retroarch_custom_ori... |
def set_timer():
# WIP
pass
| def set_timer():
pass |
def check_inputs(number_of_models, model_1_inputs, model_2_inputs=None):
"""Checks that the user inputs make logical sense
e.g. have they specified the number of models to be 2
but only given data for one model."""
# check model comparison information
# check model 2 is added if number of models ... | def check_inputs(number_of_models, model_1_inputs, model_2_inputs=None):
"""Checks that the user inputs make logical sense
e.g. have they specified the number of models to be 2
but only given data for one model."""
if number_of_models == 2 and model_2_inputs is None:
raise value_error('Expect mo... |
class Stack:
def __init__(self):
self.data = []
def push(self, value):
self.data.append(value)
def pop(self):
return self.data.pop()
def peek(self):
if len(self.data) > 0:
return self.data[-1:][0]
else:
return None
def size(self):
... | class Stack:
def __init__(self):
self.data = []
def push(self, value):
self.data.append(value)
def pop(self):
return self.data.pop()
def peek(self):
if len(self.data) > 0:
return self.data[-1:][0]
else:
return None
def size(self):
... |
class Ingredient():
def __init__(self, amount, unit, name):
self.amount = self.convert_to_decimal(amount)
self.unit = unit
self.name = name
def convert_to_decimal(self, amount):
try:
return float(amount)
except ValueError:
num, denom = amount.split('/')
return float(num) ... | class Ingredient:
def __init__(self, amount, unit, name):
self.amount = self.convert_to_decimal(amount)
self.unit = unit
self.name = name
def convert_to_decimal(self, amount):
try:
return float(amount)
except ValueError:
(num, denom) = amount.spl... |
""" This is an AWS Lambda function to demonstrate the import of Lambda Layers
"""
# from lambdalayer import lambdalayer
def main(event, context):
"""Handler method for the AWS Lambda Function."""
print(f"*** Lambda 2: Execution of AWS Lambda function starts. ***")
print(f"*** Lambda 2: Trying to invoke ... | """ This is an AWS Lambda function to demonstrate the import of Lambda Layers
"""
def main(event, context):
"""Handler method for the AWS Lambda Function."""
print(f'*** Lambda 2: Execution of AWS Lambda function starts. ***')
print(f'*** Lambda 2: Trying to invoke Lambda Layer. ***')
print(f'*** Lambd... |
"""Helper module to define static html outputs"""
__all__ = [
'add_header',
'row',
'rows',
'fig',
'card',
'card_deck',
'card_rows',
'title',
'div',
'table_from_df',
'hide',
'tabs',
'input'
]
def add_header(html:str, title="explainerdashboard")->str:
"""Turns a ... | """Helper module to define static html outputs"""
__all__ = ['add_header', 'row', 'rows', 'fig', 'card', 'card_deck', 'card_rows', 'title', 'div', 'table_from_df', 'hide', 'tabs', 'input']
def add_header(html: str, title='explainerdashboard') -> str:
"""Turns a html snippet into a full html layout by adding <html>... |
# Return the Nth Even Number
# nthEven(1) //=> 0, the first even number is 0
# nthEven(3) //=> 4, the 3rd even number is 4 (0, 2, 4)
# nthEven(100) //=> 198
# nthEven(1298734) //=> 2597466
# The input will not be 0.
def nth_even(n):
return 2 * (n - 1)
def test_nth_even():
assert nth_even(1) == 0
assert ... | def nth_even(n):
return 2 * (n - 1)
def test_nth_even():
assert nth_even(1) == 0
assert nth_even(2) == 2
assert nth_even(3) == 4
assert nth_even(100) == 198
assert nth_even(1298734) == 2597466 |
# https://www.codechef.com/problems/GOODBAD
for T in range(int(input())):
l,k=map(int,input().split())
s,c,b=input(),0,0
for i in s:
if(i>='A' and i<='Z'): c+=1
if(i>='a' and i<='z'): b+=1
if(c<=k and b<=k): print("both")
elif(c<=k): print("chef")
elif(b<=k): print("brother")
... | for t in range(int(input())):
(l, k) = map(int, input().split())
(s, c, b) = (input(), 0, 0)
for i in s:
if i >= 'A' and i <= 'Z':
c += 1
if i >= 'a' and i <= 'z':
b += 1
if c <= k and b <= k:
print('both')
elif c <= k:
print('chef')
elif b... |
x = """
.loader {
position: absolute;
top: 50%;
left: 50%;
margin-left: -HALFWIDTHpx;
margin-top: -HALFWIDTHpx;
width: 0;
height: 0;
visibility: initial;
transition: all .3s ease;
color: #fff;
font-family: Helvetica, Arial, sans-serif;
font-size: 2rem;
background-color: white;
border-radius:... | x = '\n.loader {\n position: absolute;\n top: 50%;\n left: 50%;\n margin-left: -HALFWIDTHpx;\n margin-top: -HALFWIDTHpx;\n width: 0;\n height: 0;\n visibility: initial;\n transition: all .3s ease;\n color: #fff;\n font-family: Helvetica, Arial, sans-serif;\n font-size: 2rem;\n background-color: white;\n b... |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
treeSum = 0
def solve(self, root):
def preOrder(root):
if root:
self.treeSum += root.val
preO... | class Solution:
tree_sum = 0
def solve(self, root):
def pre_order(root):
if root:
self.treeSum += root.val
pre_order(root.right)
pre_order(root.left)
return root
pre_order(root)
return self.treeSum |
# 2.3.4 Iterators
class SequenceIterator:
"""An iterator for any of Python's sequence types."""
def __init__(self,sequence):
"""Create an iterator for the given sequence."""
self._seq = sequence # keep a reference to the underlying data
self._k = -1 # will increment to 0 ... | class Sequenceiterator:
"""An iterator for any of Python's sequence types."""
def __init__(self, sequence):
"""Create an iterator for the given sequence."""
self._seq = sequence
self._k = -1
def __next__(self):
"""Return the next element, or else raise StopIteration error."... |
class Service:
def __init__(self, name, connector_func, state_processor_method=None,
batch_size=1, tags=None, names_previous_services=None,
names_required_previous_services=None,
workflow_formatter=None, dialog_formatter=None, response_formatter=None,
... | class Service:
def __init__(self, name, connector_func, state_processor_method=None, batch_size=1, tags=None, names_previous_services=None, names_required_previous_services=None, workflow_formatter=None, dialog_formatter=None, response_formatter=None, label=None):
self.name = name
self.batch_size =... |
text = input()
command = input()
while command != 'Decode':
current_command = command.split('|')
action = current_command[0]
if action == 'Move':
num_of_letters = int(current_command[1])
substring = text[:num_of_letters]
text = text[num_of_letters:] + substring
elif action ==... | text = input()
command = input()
while command != 'Decode':
current_command = command.split('|')
action = current_command[0]
if action == 'Move':
num_of_letters = int(current_command[1])
substring = text[:num_of_letters]
text = text[num_of_letters:] + substring
elif action == 'In... |
"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "... | """
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "... |
# To implement a stack using a list
# Made by Nouman
stack=[]
def push(x):
stack.append(x)
print("Stack: ", stack)
print(x," pushed into stack")
def pop():
x=stack.pop()
print("\nPopped: ",x)
print("Stack :",stack)
size=int(input("Enter size of stack: "))
print("\nEnter elements into stack: ")
for i in range... | stack = []
def push(x):
stack.append(x)
print('Stack: ', stack)
print(x, ' pushed into stack')
def pop():
x = stack.pop()
print('\nPopped: ', x)
print('Stack :', stack)
size = int(input('Enter size of stack: '))
print('\nEnter elements into stack: ')
for i in range(size):
x = int(input('\n... |
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(' ')
if len(pattern) != len(words): return False
w_to_p = {}
p_to_w = {}
for i, w in enumerate(words):
if pattern[i] not in p_to_w: p_to_w[pattern[i]] = w
if w not in ... | class Solution:
def word_pattern(self, pattern: str, s: str) -> bool:
words = s.split(' ')
if len(pattern) != len(words):
return False
w_to_p = {}
p_to_w = {}
for (i, w) in enumerate(words):
if pattern[i] not in p_to_w:
p_to_w[pattern[... |
class Solution:
@staticmethod
def naive(nums,target):
left,right = 0,len(nums)-1
while right>left+1:
mid = (left+right)//2
if nums[mid]>target:
right = mid
elif nums[mid]<target:
left = mid
else:
retu... | class Solution:
@staticmethod
def naive(nums, target):
(left, right) = (0, len(nums) - 1)
while right > left + 1:
mid = (left + right) // 2
if nums[mid] > target:
right = mid
elif nums[mid] < target:
left = mid
else... |
"""Define mapping of litex components to generated zephyr output"""
class Mapping:
"""Mapping from litex component to generated zephyr output
:param name: Name of the mapping, only used during debugging
:type name: str
"""
def __init__(self, name):
self.name = name
| """Define mapping of litex components to generated zephyr output"""
class Mapping:
"""Mapping from litex component to generated zephyr output
:param name: Name of the mapping, only used during debugging
:type name: str
"""
def __init__(self, name):
self.name = name |
#
# PySNMP MIB module CISCO-WAN-MG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-MG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) ... |
#!/usr/local/bin/python3.3
def echo(message):
print(message)
return
echo('Direct Call')
x = echo
x('Indirect Call')
def indirect(func, arg):
func(arg)
indirect(echo, "Argument Call")
schedule = [(echo, 'Spam'), (echo, 'Ham')]
for (func, arg) in schedule:
func(arg)
def make(label):
def echo(me... | def echo(message):
print(message)
return
echo('Direct Call')
x = echo
x('Indirect Call')
def indirect(func, arg):
func(arg)
indirect(echo, 'Argument Call')
schedule = [(echo, 'Spam'), (echo, 'Ham')]
for (func, arg) in schedule:
func(arg)
def make(label):
def echo(message):
print(label + '... |
class SqlQueries:
address_table_insert = ("""
SELECT DISTINCT address1 AS address1
, address2 AS address2
, address3 AS address3
, city AS city
, zip_code AS zip_code
, country AS country
, state AS state
FROM staging_restaurants
WHERE address... | class Sqlqueries:
address_table_insert = '\n SELECT DISTINCT address1 AS address1\n , address2 AS address2\n , address3 AS address3\n , city AS city\n , zip_code AS zip_code\n , country AS country\n , state AS state\n FROM staging_restaurants\n WHERE ad... |
"""
Unittests
=========
Tests are built for usage with **py.test**.
In data fixtures, not all settings and Sass sources will compile with
libsass. Some of them contains some errors for test needs.
* ``boussole.txt``: Is not an usable settings file, just a dummy file for base
backend tests;
* ``boussole.json``: Is ... | """
Unittests
=========
Tests are built for usage with **py.test**.
In data fixtures, not all settings and Sass sources will compile with
libsass. Some of them contains some errors for test needs.
* ``boussole.txt``: Is not an usable settings file, just a dummy file for base
backend tests;
* ``boussole.json``: Is ... |
class SketchGalleryOptions(Enum, IComparable, IFormattable, IConvertible):
"""
Enumerates all the sketch options.
enum SketchGalleryOptions,values: SGO_Arc3Point (6),SGO_ArcCenterEnds (7),SGO_ArcFillet (9),SGO_ArcTanEnd (8),SGO_Circle (5),SGO_CircumscribedPolygon (4),SGO_Default (0),SGO_FullEllipse (12)... | class Sketchgalleryoptions(Enum, IComparable, IFormattable, IConvertible):
"""
Enumerates all the sketch options.
enum SketchGalleryOptions,values: SGO_Arc3Point (6),SGO_ArcCenterEnds (7),SGO_ArcFillet (9),SGO_ArcTanEnd (8),SGO_Circle (5),SGO_CircumscribedPolygon (4),SGO_Default (0),SGO_FullEllipse (12),SGO_I... |
def generateHTML(colors):
print(colors)
node1 = f"""id: '1',
label: 'Theme 1',
x: 7,
y: 1,
size: 1,
color: '{colors[0]}'"""
node2 = f"""id: '2',
label: 'Theme 2',
x: 12,
y: 1,
size: 1,
color: '{colors[1]}'"""
node3 = f"""i... | def generate_html(colors):
print(colors)
node1 = f"id: '1',\n label: 'Theme 1',\n x: 7,\n y: 1,\n size: 1,\n color: '{colors[0]}'"
node2 = f"id: '2',\n label: 'Theme 2',\n x: 12,\n y: 1,\n size: 1,\n color: '{colors[1]}'"
node3 = f"id... |
def for_S():
""" Upper case Alphabet letter 'S' pattern using Python for loop"""
for row in range(7):
for col in range(5):
if row%3==0 and col>0 and col<4 or col==0 and row%3!=0 and row<3 or col==4 and row%3!=0 and row>3:
pri... | def for_s():
""" Upper case Alphabet letter 'S' pattern using Python for loop"""
for row in range(7):
for col in range(5):
if row % 3 == 0 and col > 0 and (col < 4) or (col == 0 and row % 3 != 0 and (row < 3)) or (col == 4 and row % 3 != 0 and (row > 3)):
print('*', end=' ')
... |
# DROP TABLES
arrivals_drop = "DROP TABLE IF EXISTS arrivals;"
airports_drop = "DROP TABLE IF EXISTS airports;"
countries_drop = "DROP TABLE IF EXISTS countries;"
temp_drop = "DROP TABLE IF EXISTS temp;"
# CREATE TABLES
arrivals_create = ("""CREATE TABLE IF NOT EXISTS arrivals (
arrival_id serial PRIMARY KEY,
country_... | arrivals_drop = 'DROP TABLE IF EXISTS arrivals;'
airports_drop = 'DROP TABLE IF EXISTS airports;'
countries_drop = 'DROP TABLE IF EXISTS countries;'
temp_drop = 'DROP TABLE IF EXISTS temp;'
arrivals_create = 'CREATE TABLE IF NOT EXISTS arrivals (\narrival_id serial PRIMARY KEY,\ncountry_id int,\nvisa_type int,\ncount i... |
command = input()
numbers = [int(x) for x in input().split()]
parity = 0 if command == 'Even' else 1
result = sum(filter(lambda x: x % 2 == parity, numbers))
print(result * len(numbers))
| command = input()
numbers = [int(x) for x in input().split()]
parity = 0 if command == 'Even' else 1
result = sum(filter(lambda x: x % 2 == parity, numbers))
print(result * len(numbers)) |
class ListNode:
def __init__(self, data, link=None):
self.data = data
self.link = link
| class Listnode:
def __init__(self, data, link=None):
self.data = data
self.link = link |
temperature =int(input("Enter Temperature: "))
if temperature > 30:
print("It's a hot day")
elif temperature < 10:
print("It's a cold day")
else:
print("it's neither hot nor cold")
| temperature = int(input('Enter Temperature: '))
if temperature > 30:
print("It's a hot day")
elif temperature < 10:
print("It's a cold day")
else:
print("it's neither hot nor cold") |
TRACKS = 'tracks'
STUDIES = 'studies'
EXPERIMENTS = 'experiments'
SAMPLES = 'samples'
SCHEMA_URL_PART1 = 'https://raw.githubusercontent.com/fairtracks/fairtracks_standard/'
SCHEMA_URL_PART2 = '/current/json/schema/fairtracks.schema.json'
TOP_SCHEMA_FN = 'fairtracks.schema.json'
TERM_ID = 'term_id'
ONTOLOGY = 'ontolo... | tracks = 'tracks'
studies = 'studies'
experiments = 'experiments'
samples = 'samples'
schema_url_part1 = 'https://raw.githubusercontent.com/fairtracks/fairtracks_standard/'
schema_url_part2 = '/current/json/schema/fairtracks.schema.json'
top_schema_fn = 'fairtracks.schema.json'
term_id = 'term_id'
ontology = 'ontology'... |
class Constant():
def __init__(self, value):
self._value = value
def __call__(self):
return self._value
y = Constant(5)
print((y()))
| class Constant:
def __init__(self, value):
self._value = value
def __call__(self):
return self._value
y = constant(5)
print(y()) |
print(2, type(2))
print(3.5, type(3.5))
print([], type([]))
print(True, type(True))
print(None, type(None))
# code to put in a for-each loop for the Pattern Loop Exercise
| print(2, type(2))
print(3.5, type(3.5))
print([], type([]))
print(True, type(True))
print(None, type(None)) |
def create_dimension_competitors(cursor):
cursor.execute('''CREATE TABLE dimension_competitors
( company_name text,
company_permalink text,
competitor_name text,
competitor_permalink text,
extracted_at text
)''') | def create_dimension_competitors(cursor):
cursor.execute('CREATE TABLE dimension_competitors\n ( company_name text,\n company_permalink text,\n competitor_name text,\n competitor_permalink text,\n extracted_at text\n )') |
name_1 = input()
name_2 = input()
delimiter = input()
print(f"{name_1}{delimiter}{name_2}") | name_1 = input()
name_2 = input()
delimiter = input()
print(f'{name_1}{delimiter}{name_2}') |
def f(x):
for i in reversed([20, 19, 18, 17, 16, 15, 14, 13, 12, 11]):
if x % i != 0:
return False
return True
i = 20
while f(i) == False:
i += 20
print(i)
| def f(x):
for i in reversed([20, 19, 18, 17, 16, 15, 14, 13, 12, 11]):
if x % i != 0:
return False
return True
i = 20
while f(i) == False:
i += 20
print(i) |
a=int(input("Enter any number "))
for x in range(1,a+1):
print(x)
| a = int(input('Enter any number '))
for x in range(1, a + 1):
print(x) |
class String:
"""Javascript methods for strings."""
def char_at(string, index):
"""Returns the character at a specified index in a string."""
return string[index]
def trim(string):
"""Removes whitespace from both sides of a string."""
return string.strip()
def... | class String:
"""Javascript methods for strings."""
def char_at(string, index):
"""Returns the character at a specified index in a string."""
return string[index]
def trim(string):
"""Removes whitespace from both sides of a string."""
return string.strip()
def includes... |
def pre_order(root):
ret = []
stack, node = [], root
while stack or node:
if node:
ret.append(node.val)
stack.append(node)
node = node.left
else:
node = stack.pop()
node = node.right
return ret
def in_order(root):
ret = []... | def pre_order(root):
ret = []
(stack, node) = ([], root)
while stack or node:
if node:
ret.append(node.val)
stack.append(node)
node = node.left
else:
node = stack.pop()
node = node.right
return ret
def in_order(root):
ret =... |
# Keep a dictionary that has items ordered in a deque structure
class DequeDict:
# Entry that holds the key, value
class DequeEntry:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
# Helpful for ... | class Dequedict:
class Dequeentry:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
def __repr__(self):
return '(k={}, v={})'.format(self.key, self.value)
def __init__(self):
... |
#
# Copyright (C) 2000-2005 by Yasushi Saito (yasushi.saito@gmail.com)
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distr... | def generate_doc(name, suffix='', append=0):
if append:
fp = open(name + '_doc.py', 'a+')
else:
fp = open(name + '_doc.py', 'w')
fp.write('# automatically generated by generate_docs.py.\n')
fp.write('doc' + suffix + '=" "\n')
fp.close()
generate_doc('area')
generate_doc('arrow')
... |
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
if not points or len(points) == 1:
return 0
time = 0
for index,cur_point in enumerate(points):
if index == len(points) - 1:
return time
next_point = points[i... | class Solution:
def min_time_to_visit_all_points(self, points: List[List[int]]) -> int:
if not points or len(points) == 1:
return 0
time = 0
for (index, cur_point) in enumerate(points):
if index == len(points) - 1:
return time
next_point =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.