content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''
## Questions
### 23. [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
**Example:**
```
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
'''
## Solutions
# Definit... | """
## Questions
### 23. [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
**Example:**
```
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
class Solution:
de... |
# Palace Oasis (2103000) | Ariant Castle (260000300)
ariantCulture = 3900
if sm.hasQuest(ariantCulture):
sm.setQRValue(ariantCulture, "5", False)
sm.sendSayOkay("You used two hands to drink the clean water of the Oasis. "
"Delicious! It quenched your thirst right on the spot.")
| ariant_culture = 3900
if sm.hasQuest(ariantCulture):
sm.setQRValue(ariantCulture, '5', False)
sm.sendSayOkay('You used two hands to drink the clean water of the Oasis. Delicious! It quenched your thirst right on the spot.') |
class Dino:
@staticmethod
def exe1():
print("al carajo 1")
def exe2(self):
print("al carajo 2")
class Car(Dino):
wheels = 0
def __init__(self, color, x, func):
self.color = color
self.f = func
Car.wheels = x
while (True):
print("yey")
Dino.exe1()
din = Dino()
din.exe2()
f = lambda x: x+1
#print(f(2... | class Dino:
@staticmethod
def exe1():
print('al carajo 1')
def exe2(self):
print('al carajo 2')
class Car(Dino):
wheels = 0
def __init__(self, color, x, func):
self.color = color
self.f = func
Car.wheels = x
while True:
print('yey')
Dino.exe1()
din = d... |
# Copyright (c) 2018 - 2020 Institute for High Voltage Technology and Institute for High Voltage Equipment and Grids, Digitalization and Power Economics
# RWTH Aachen University
# Contact: Thomas Offergeld (t.offergeld@iaew.rwth-aachen.de)
# #
# This module is part of CIMPyORM.
# #
# CIMPyORM is licensed un... | def test_parse_meta(acquire_db, dummy_source):
(_, session) = acquire_db
assert dummy_source.tree
assert dummy_source.nsmap == {'cim': 'http://iec.ch/TC57/2013/CIM-schema-cim16#', 'entsoe': 'http://entsoe.eu/CIM/SchemaExtension/3/1#', 'md': 'http://iec.ch/TC57/61970-552/ModelDescription/1#', 'rdf': 'http://... |
with open('inputs/input24.txt') as fin:
raw = fin.read()
def parse(raw):
x = [x for x in raw.splitlines()]
return x
a = parse(raw)
def part_1(data):
dictionary = {}
for a in data:
e = a.count('ne') + a.count('se')
w = a.count('nw') + a.count('sw')
x = e + 2 * (a.count('... | with open('inputs/input24.txt') as fin:
raw = fin.read()
def parse(raw):
x = [x for x in raw.splitlines()]
return x
a = parse(raw)
def part_1(data):
dictionary = {}
for a in data:
e = a.count('ne') + a.count('se')
w = a.count('nw') + a.count('sw')
x = e + 2 * (a.count('e') ... |
num = int(input('Digite um numero: '))
tot = 0
for c in range(1, num +1):
if num% c == 0 :
print('\033[33m', end='')
tot += 1
else:
print('\033[31m',end=' ')
print('{}'.format(c) , end=' ')
print('\n\033[mO numero {} foi divisivel {} vezes'.format(num, tot))
if tot == 2:
print('E... | num = int(input('Digite um numero: '))
tot = 0
for c in range(1, num + 1):
if num % c == 0:
print('\x1b[33m', end='')
tot += 1
else:
print('\x1b[31m', end=' ')
print('{}'.format(c), end=' ')
print('\n\x1b[mO numero {} foi divisivel {} vezes'.format(num, tot))
if tot == 2:
print('... |
__version__ = '0.3.7'
__title__ = 'iam-docker-run'
__description__ = 'Run Docker containers within the context of an AWS IAM Role, and other development workflow helpers.'
__url__ = 'https://github.com/billtrust/iam-docker-run'
__author__ = 'Doug Kerwin'
__author_email__ = 'dwkerwin@gmail.com'
__license__ = 'MIT'
__key... | __version__ = '0.3.7'
__title__ = 'iam-docker-run'
__description__ = 'Run Docker containers within the context of an AWS IAM Role, and other development workflow helpers.'
__url__ = 'https://github.com/billtrust/iam-docker-run'
__author__ = 'Doug Kerwin'
__author_email__ = 'dwkerwin@gmail.com'
__license__ = 'MIT'
__key... |
#!/bin/python3
#
# Copyright (c) 2019 Paulo Vital
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge,... | def fibonacci(n):
if n == 0 or n == 1:
yield 1
yield (fibonacci(n - 1) + fibonacci(n - 2))
if __name__ == '__main__':
end = input('Type a limit number: ')
print('The Fibonacci sequence for {0} is: '.format(end), list(fibonacci(int(end)))) |
NumbersBelow19 = ["One", "Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Ninteen"]
multiplesOf10 = ["Twenty" , "Thirty" , "Fourty" , "Fifty" , "Sixty" , "Seventy" ,"Eighty" , "Ninety"]
singleDigits = ["One", "Two","Thr... | numbers_below19 = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Ninteen']
multiples_of10 = ['Twenty', 'Thirty', 'Fourty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
single_digits = ['One',... |
num = int(input())
first = []
second = []
for i in range(num):
line = input().split(' ')
name = line[0]
t1 = float(line[1])
t2 = float(line[2])
first.append([name, t1])
second.append([name, t2])
first.sort(key=lambda x: x[1])
second.sort(key=lambda x: x[1])
total_time = 0
squad_list_of_lists =... | num = int(input())
first = []
second = []
for i in range(num):
line = input().split(' ')
name = line[0]
t1 = float(line[1])
t2 = float(line[2])
first.append([name, t1])
second.append([name, t2])
first.sort(key=lambda x: x[1])
second.sort(key=lambda x: x[1])
total_time = 0
squad_list_of_lists = [... |
def remdup(a):
return list(set(a))
l=[]
for i in range(0,5):
l.append(input())
print(l)
rev = l[::-1]
print(rev)
print(remdup(l))
print([i for i in range(0,10) if i%2==0])
| def remdup(a):
return list(set(a))
l = []
for i in range(0, 5):
l.append(input())
print(l)
rev = l[::-1]
print(rev)
print(remdup(l))
print([i for i in range(0, 10) if i % 2 == 0]) |
'''
Created on 1.12.2016
@author: Darren
''''''
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array."
'''
| """
Created on 1.12.2016
@author: Darren
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array."
""" |
# This is Pessimistic Error Pruning.
def prune(t):
# If the node is a leaf node, stop pruning.
if t.label != None:
return
L = t.leaf_sum
N = t.N
p = (t.RT + 0.5*L)/N
# When the following condition is satisfied,
# replace the subtree with a leaf node.
if t.RT + 0.5 - (N*p*(1-p))*... | def prune(t):
if t.label != None:
return
l = t.leaf_sum
n = t.N
p = (t.RT + 0.5 * L) / N
if t.RT + 0.5 - (N * p * (1 - p)) ** 0.5 < t.RT + 0.5 * L:
t.label = t.majority
return
prune(t.left)
prune(t.right) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isCousins(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool':
m = {}
def traverse(node, parent=None, depth=0):
... | class Solution:
def is_cousins(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool':
m = {}
def traverse(node, parent=None, depth=0):
if node:
m[node.val] = (parent, depth)
traverse(node.left, node.val, depth + 1)
traverse(node.right, no... |
#To find whether the number is +ve,-ve or 0
x=int(input("Enter a number"))
def check_num(x):
if x>0:
print("The",x,"is positive")
elif x<0:
print("The",x,"is negative")
else:
print("The",x,"is zero")
check_num(x)
| x = int(input('Enter a number'))
def check_num(x):
if x > 0:
print('The', x, 'is positive')
elif x < 0:
print('The', x, 'is negative')
else:
print('The', x, 'is zero')
check_num(x) |
try:
raise Exception()
except Exception as e:
print("hello", str(e))
| try:
raise exception()
except Exception as e:
print('hello', str(e)) |
database = {
'default': 'mysql',
'connections': {
'mysql': {
'name': 'mytodo',
'username': 'root',
'password': '',
'connection': 'mysql:host=127.0.0.1',
},
},
'migrations': 'migrations',
}
| database = {'default': 'mysql', 'connections': {'mysql': {'name': 'mytodo', 'username': 'root', 'password': '', 'connection': 'mysql:host=127.0.0.1'}}, 'migrations': 'migrations'} |
# CONCATENATION
firstName = "Helder"
lastName = "Pereira"
fullName = "Helder" + " " + lastName
print(fullName) | first_name = 'Helder'
last_name = 'Pereira'
full_name = 'Helder' + ' ' + lastName
print(fullName) |
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
sqlmapapi restful interface
by zhangh (zhanghang.org#gmail.com)
'''
# api
task_new = "task/new"
task_del = "task/<taskid>/delete"
admin_task_list = "admin/<taskid>/list"
admin_task_flush = "admin/<taskid>/flush"
option_task_list = "option/<taskid>/list"
option_task_get = ... | """
sqlmapapi restful interface
by zhangh (zhanghang.org#gmail.com)
"""
task_new = 'task/new'
task_del = 'task/<taskid>/delete'
admin_task_list = 'admin/<taskid>/list'
admin_task_flush = 'admin/<taskid>/flush'
option_task_list = 'option/<taskid>/list'
option_task_get = 'option/<taskid>/get'
option_task_set = 'option/... |
def path_initial_steps(path, node):
'''
takes in a list of arcs and a node and returns the list of nodes the node can reach
'''
initial_steps = []
for arc in path:
if arc[0] == node:
initial_steps.append(arc)
return initial_steps
def path_end_points(path, node):
'''
... | def path_initial_steps(path, node):
"""
takes in a list of arcs and a node and returns the list of nodes the node can reach
"""
initial_steps = []
for arc in path:
if arc[0] == node:
initial_steps.append(arc)
return initial_steps
def path_end_points(path, node):
"""
... |
def x():
return 1
x()
| def x():
return 1
x() |
def internet_on():
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Log,Testing Internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
global ledSwitch
global connected
global powerSwitch
try:
powerSwitch = 0
urllib.request.urlopen('http://216.58.207.206')
#urllib.urlopen('htt... | def internet_on():
with open('error_log.csv', 'a') as error_log:
error_log.write('\n{0},Log,Testing Internet connection.'.format(strftime('%Y-%m-%d %H:%M:%S')))
global ledSwitch
global connected
global powerSwitch
try:
power_switch = 0
urllib.request.urlopen('http://216.58.20... |
#
# PySNMP MIB module ATM-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ATM-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:04:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, single_value_constraint, constraints_intersection) ... |
def expectOne(vals):
assert len(vals) == 1
return vals[0]
| def expect_one(vals):
assert len(vals) == 1
return vals[0] |
class CSVDumper:
@classmethod
def dump(self, matrix, encoding='sjis'):
rows = []
for row in matrix:
fields = []
for field in row:
if field is None:
fields.append('')
elif str(field).isdigit():
fields... | class Csvdumper:
@classmethod
def dump(self, matrix, encoding='sjis'):
rows = []
for row in matrix:
fields = []
for field in row:
if field is None:
fields.append('')
elif str(field).isdigit():
fields... |
'''Hercy wants to save money for his first car. He puts money
in the Leetcode bank every day.
He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday,
he will put in $1 more than the day before. On every subsequent Monday,
he will put in $1 more than the previous Monday.
Given n, return... | """Hercy wants to save money for his first car. He puts money
in the Leetcode bank every day.
He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday,
he will put in $1 more than the day before. On every subsequent Monday,
he will put in $1 more than the previous Monday.
Given n, return... |
# Radix Sort is an improvement over Counting Sort
# Counting Sort is highly inefficient with large ranges
# Radix sort sorts digit by digit from least to most significant digit.
# It can be imagined as a bucket sort based on place values.
def radixSort(array, base=10):
# Get the maximum in the array to find the ma... | def radix_sort(array, base=10):
m = max(array)
place_value = 1
while m / placeValue > 0:
occurence = [0] * base
for element in array:
occurence[int(element / placeValue % base)] += 1
for i in range(1, base):
occurence[i] += occurence[i - 1]
temp = [0] ... |
'''
-- Make required Folder & open Integrated CMD in it !
In CMD type :
[To make exact copy of system base python but no modules included!]
-- pip install virtualenv
-- virtualenv [nameOfSubFolderInRequiredFolder] // Here I used VirtualEnvironment
--OR--
To make exact copy of system base p... | """
-- Make required Folder & open Integrated CMD in it !
In CMD type :
[To make exact copy of system base python but no modules included!]
-- pip install virtualenv
-- virtualenv [nameOfSubFolderInRequiredFolder] // Here I used VirtualEnvironment
--OR--
To make exact copy of system base p... |
ME = '''
query getMe {
me {
username
isStaff
isSuperuser
isAgreed
profile {
id
oauthType
name
nameKo
nameEn
bio
bioKo
bioEn
email
phone
organiz... | me = '\nquery getMe {\n me {\n username\n isStaff\n isSuperuser\n isAgreed\n profile { \n id\n oauthType\n name\n nameKo\n nameEn\n bio\n bioKo\n bioEn\n email\n phone\n ... |
# -*- coding: utf-8 -*-
args = input().split()
n1, n2, n3 = list(map (int, args))
average = (lambda a, b, c: (a + b + c)/3)(n1, n2, n3)
result = (lambda av: "Approved" if av >= 6 else "Disapproved")
print(result(average))
| args = input().split()
(n1, n2, n3) = list(map(int, args))
average = (lambda a, b, c: (a + b + c) / 3)(n1, n2, n3)
result = lambda av: 'Approved' if av >= 6 else 'Disapproved'
print(result(average)) |
# leetcode
class Solution:
def isPalindrome(self, s: str) -> bool:
s_cp = s.replace(" ", "").lower()
clean_s = ''
for l in s_cp:
# check if num
if ord(l) >= 48 and ord(l) <= 57:
clean_s += l
elif ord(l) >= 97 and ord(l) <... | class Solution:
def is_palindrome(self, s: str) -> bool:
s_cp = s.replace(' ', '').lower()
clean_s = ''
for l in s_cp:
if ord(l) >= 48 and ord(l) <= 57:
clean_s += l
elif ord(l) >= 97 and ord(l) <= 122:
clean_s += l
return clea... |
'''
Two intervals i1, i2overlap if the following requirements are satisfied:
requirement 1: i1.end >= i2.start
requirement 2: i1.start <= i2.end
We preprocess the list by sorting intervals by starts increasingly.
In this way, requirement 2 i1.start <= i2.start < i2.end is promised.
We only have to compare i1.end with ... | """
Two intervals i1, i2overlap if the following requirements are satisfied:
requirement 1: i1.end >= i2.start
requirement 2: i1.start <= i2.end
We preprocess the list by sorting intervals by starts increasingly.
In this way, requirement 2 i1.start <= i2.start < i2.end is promised.
We only have to compare i1.end with ... |
#
# PySNMP MIB module Nortel-Magellan-Passport-DataCollectionMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-DataCollectionMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:26:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
numbers = [-1,0]
target = -1
hashMap = {}
for index, num in enumerate(numbers):
diff = target - num
if diff in hashMap:
print([hashMap[diff]+1, index+1])
hashMap[num] = index | numbers = [-1, 0]
target = -1
hash_map = {}
for (index, num) in enumerate(numbers):
diff = target - num
if diff in hashMap:
print([hashMap[diff] + 1, index + 1])
hashMap[num] = index |
#SCOPE USING NONLOCAL KEYWORD
x = 10#GLOBAL VARIABLE X
def outer():
x=20#LOCAL VARIABLE X
y=30#LOCAL VARIABLE Y
print("outer func x before inner call:", x)
print("outer func y before inner call:", y)
def inner():
nonlocal y#LOCAL VARIABLE Y REFERS TO ITS ABOVE LEVEL OUTER Y
global x#... | x = 10
def outer():
x = 20
y = 30
print('outer func x before inner call:', x)
print('outer func y before inner call:', y)
def inner():
nonlocal y
global x
x = 30
y = 40
print('inner func x :', x)
print('inner func y :', y)
inner()
print('oute... |
#========================================================================================================
# TOPIC: PYTHON - Modules
#========================================================================================================
# NOTES: * Any Python file is a module.
# * Module is a file with Python ... | country_1 = 'USA'
country_2 = 'China'
country_3 = 'India'
list_world_nations = ['USA', 'China', 'India']
tuple_world_nations = ('USA', 'China', 'India')
dictionary_world_nations = {'Country_1': 'USA', 'Country_1': 'China', 'Country_1': 'India'}
def module_function_add(in_number1, in_number2):
"""This function add ... |
# Define a sum_of_lengths function that accepts a list of strings.
# The function should return the sum of the string lengths.
#
# EXAMPLES
# sum_of_lengths(["Hello", "Bob"]) => 8
# sum_of_lengths(["Nonsense"]) => 8
# sum_of_lengths(["Nonsense", "or", "confidence"]) => 20
def sum... | def sum_of_lengths(array):
sum = 0
for element in array:
sum += len(element)
return sum
print(sum_of_lengths(['Hello', 'Bob']))
print(sum_of_lengths(['Nonsense']))
print(sum_of_lengths(['Nonsense', 'or', 'confidence'])) |
# Generates an infinite series of odd numbers
def odds():
n = 1
while True:
yield n
n += 2
def pi_series():
odd_nums = odds()
approximation = 0
while True:
approximation += (4 / next(odd_nums))
yield approximation
approxim... | def odds():
n = 1
while True:
yield n
n += 2
def pi_series():
odd_nums = odds()
approximation = 0
while True:
approximation += 4 / next(odd_nums)
yield approximation
approximation -= 4 / next(odd_nums)
yield approximation
approx_pi = pi_series()
for x... |
data = [
{'v': 'v0.1', 't': 1391},
{'v': 'v0.1', 't': 1394},
{'v': 'v0.1', 't': 1300},
{'v': 'v0.1', 't': 1321},
{'v': 'v0.1.3', 't': 1491},
{'v': 'v0.1.3', 't': 1494},
{'v': 'v0.1.3', 't': 1400},
{'v': 'v0.1.3', 't': 1421},
{'v': 'v0.1.2', 't': 1291},
{'v': 'v0.1.2', 't': 1294},... | data = [{'v': 'v0.1', 't': 1391}, {'v': 'v0.1', 't': 1394}, {'v': 'v0.1', 't': 1300}, {'v': 'v0.1', 't': 1321}, {'v': 'v0.1.3', 't': 1491}, {'v': 'v0.1.3', 't': 1494}, {'v': 'v0.1.3', 't': 1400}, {'v': 'v0.1.3', 't': 1421}, {'v': 'v0.1.2', 't': 1291}, {'v': 'v0.1.2', 't': 1294}, {'v': 'v0.1.2', 't': 1200}, {'v': 'v0.1.... |
def minimum(a):
b=list[0]
i=0
while i<len(list):
if list[i]<b:
b=list[i]
i=i+1
return(b)
list=[5,3,1,6,5,4,7,6]
print(minimum(list))
| def minimum(a):
b = list[0]
i = 0
while i < len(list):
if list[i] < b:
b = list[i]
i = i + 1
return b
list = [5, 3, 1, 6, 5, 4, 7, 6]
print(minimum(list)) |
__about__="Class method vs Static Method."
class MyClass:
def method(self):
print("Instance of method called", self)
@classmethod
def classmethod(cls):
print("Instance of classmethod called", cls)
@staticmethod
def staticmethod():
print("Instance of staticmethod called")
... | __about__ = 'Class method vs Static Method.'
class Myclass:
def method(self):
print('Instance of method called', self)
@classmethod
def classmethod(cls):
print('Instance of classmethod called', cls)
@staticmethod
def staticmethod():
print('Instance of staticmethod called'... |
'''
Class for adding the expreimental data for the cell model
'''
class Experimental:
def __init__(self):
self.experimental_data = dict()
def define_exp(self, **kwargs):
for exp_type, data in kwargs.items():
self.experimental_data.update({exp_type: data})
| """
Class for adding the expreimental data for the cell model
"""
class Experimental:
def __init__(self):
self.experimental_data = dict()
def define_exp(self, **kwargs):
for (exp_type, data) in kwargs.items():
self.experimental_data.update({exp_type: data}) |
def get_hard_coded_app_id_dict():
# Matches, manually added, from game names to Steam appIDs
hard_coded_dict = {
# Manually fix matches for which the automatic name matching (based on Levenshtein distance) is wrong:
"The Missing": "842910",
"Pillars of Eternity 2": "560130",
"Dr... | def get_hard_coded_app_id_dict():
hard_coded_dict = {'The Missing': '842910', 'Pillars of Eternity 2': '560130', 'Dragon Quest XI': '742120', 'DRAGON QUEST XI: Echoes of an Elusive Age': '742120', 'Dragon Quest XI: Echoes of an Elusive Age': '742120', 'Dragon Quest XI: Shadows of an Elusive Age': '742120', 'Atelier... |
rates = list() # Equals to: rates = []
genres = list()
ages = list()
another_one = True
while another_one:
genre = input('Please enter your genre (either M or F): ')
genres.append(genre)
age = int(input('Type your age: '))
ages.append(age)
rate = input('You rate the product as '
... | rates = list()
genres = list()
ages = list()
another_one = True
while another_one:
genre = input('Please enter your genre (either M or F): ')
genres.append(genre)
age = int(input('Type your age: '))
ages.append(age)
rate = input('You rate the product as 1-unsatisfactory 2-bad 3-regular 4-good 5-grea... |
greetings = ["hey", "howdy", "hi", "hello", "hi there"]
questions = ["how_are_you_feeling", "how_are_you", "what_is_your_name", "how_old_are_you", "where_are_you_from", "are_you_a_boy_or_a_girl", "what_up"]
insults = ["dumb", "stupid", "Ugly", "Retard", "Retarded", "suck"]
complements = ["great", "awesome"]
cuss_wo... | greetings = ['hey', 'howdy', 'hi', 'hello', 'hi there']
questions = ['how_are_you_feeling', 'how_are_you', 'what_is_your_name', 'how_old_are_you', 'where_are_you_from', 'are_you_a_boy_or_a_girl', 'what_up']
insults = ['dumb', 'stupid', 'Ugly', 'Retard', 'Retarded', 'suck']
complements = ['great', 'awesome']
cuss_words ... |
def extractEachKth(inputArray, k):
return [x for i, x in enumerate(inputArray) if (i + 1) % k != 0]
print(extractEachKth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)) | def extract_each_kth(inputArray, k):
return [x for (i, x) in enumerate(inputArray) if (i + 1) % k != 0]
print(extract_each_kth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)) |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '9.3.beta7'
date = '2021-02-07'
banner = 'SageMath version 9.3.beta7, Release Date: 2021-02-07'
| version = '9.3.beta7'
date = '2021-02-07'
banner = 'SageMath version 9.3.beta7, Release Date: 2021-02-07' |
def numsum(n):
''' The recursive sum of all digits in a number
unit a single character is obtained'''
res = sum([int(i) for i in str(n)])
if res < 10: return res
else : return numsum(res)
for n in range(1,101):
response = 'Fizz'*(numsum(n) in [3,6,9]) + \
'Buzz'*(str(n)[-1] in ['5','0'... | def numsum(n):
""" The recursive sum of all digits in a number
unit a single character is obtained"""
res = sum([int(i) for i in str(n)])
if res < 10:
return res
else:
return numsum(res)
for n in range(1, 101):
response = 'Fizz' * (numsum(n) in [3, 6, 9]) + 'Buzz' * (str(n)[-... |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import plotly\n",
"import pandas as pd\n",
"\n",
"from nltk.stem import WordNetLemmatizer\n",
"from nltk.tokenize import word_tokenize\n",
"\n",
"fr... | {'cells': [{'cell_type': 'code', 'execution_count': null, 'metadata': {}, 'outputs': [], 'source': ['import json\n', 'import plotly\n', 'import pandas as pd\n', '\n', 'from nltk.stem import WordNetLemmatizer\n', 'from nltk.tokenize import word_tokenize\n', '\n', 'from flask import Flask\n', 'from flask import render_te... |
# Solution 1
# O(n^2) time / O(1) space
# n - number of buildings
def largestRectangleUnderSkyline(buildings):
maxArea = 0
for pillarIdx in range(len(buildings)):
currentHeight = buildings[pillarIdx]
furthestLeft = pillarIdx
while furthestLeft > 0 and buildings[furthestLeft - 1] >= currentHeight:
... | def largest_rectangle_under_skyline(buildings):
max_area = 0
for pillar_idx in range(len(buildings)):
current_height = buildings[pillarIdx]
furthest_left = pillarIdx
while furthestLeft > 0 and buildings[furthestLeft - 1] >= currentHeight:
furthest_left -= 1
furthest_r... |
t=int(input())
while(t):
t=t-1
n=int(input())
c=0
a=list(map(int,input().split()))
b=[]
b.append(int(a[0]))
for i in range(1,len(a)):
b.append(min(int(a[i]),int(b[i-1])))
for i in range(0,len(a)):
if(int(a[i])==int(b[i])):
c+=1
print(c)
| t = int(input())
while t:
t = t - 1
n = int(input())
c = 0
a = list(map(int, input().split()))
b = []
b.append(int(a[0]))
for i in range(1, len(a)):
b.append(min(int(a[i]), int(b[i - 1])))
for i in range(0, len(a)):
if int(a[i]) == int(b[i]):
c += 1
print(... |
#!/usr/bin/env python3
__author__ = "Mert Erol"
# This signature is required for the automated grading to work.
# Do not rename the function or change its list of parameters!
def visualize(records):
pclass_1 = 0
pclass_1_alive = 0
pclass_2 = 0
pclass_2_alive = 0
pclass_3 = 0
pclass_3_alive = 0
... | __author__ = 'Mert Erol'
def visualize(records):
pclass_1 = 0
pclass_1_alive = 0
pclass_2 = 0
pclass_2_alive = 0
pclass_3 = 0
pclass_3_alive = 0
dataset = records[1]
for p in dataset:
pclass = p[1]
alive = p[0]
if pclass == 1:
pclass_1 += 1
... |
# Dummy class for packages that have no MPI
class MPIDummy(object):
def __init__(self):
pass
def Get_rank(self):
return 0
def Get_size(self):
return 1
def barrier(self):
pass
def send(self, lnlike0, dest=1, tag=55):
pass
def recv(self, source=1, tag=5... | class Mpidummy(object):
def __init__(self):
pass
def get_rank(self):
return 0
def get_size(self):
return 1
def barrier(self):
pass
def send(self, lnlike0, dest=1, tag=55):
pass
def recv(self, source=1, tag=55):
pass
def iprobe(self, sour... |
def gcd(a, b):
factors_a = []
for i in range(1, a+1):
if (a%i) == 0:
factors_a.append(i)
factors_b = []
for i in range(1, b+1):
if (b%i) == 0:
factors_b.append(i)
common_factors = []
for i in factors_a:
if i in factors_b:
common_facto... | def gcd(a, b):
factors_a = []
for i in range(1, a + 1):
if a % i == 0:
factors_a.append(i)
factors_b = []
for i in range(1, b + 1):
if b % i == 0:
factors_b.append(i)
common_factors = []
for i in factors_a:
if i in factors_b:
common_fac... |
# Specialization: Google IT Automation with Python
# Course 01: Crash Course with Python
# Week 3 Module Part 1 - Practice Quiz
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Scripting examples encountered during the Module Part 1 Practice Quiz:
# 02. Fill in the blanks to make the print_prime_f... | def print_prime_factors(number):
factor = 2
while factor <= number:
if number % factor == 0:
print(factor)
number = number / factor
else:
factor += 1
return 'Done'
print_prime_factors(100)
def is_power_of_two(n):
while n % 2 == 0:
if n == 0:
... |
#4: Skriv alle primtal mellem 1 og 100
for primtal in range(2, 101):
for i in range(2, primtal):
if (primtal % i) == 0:
break
else:
print(primtal)
| for primtal in range(2, 101):
for i in range(2, primtal):
if primtal % i == 0:
break
else:
print(primtal) |
class Checkers:
def __init__(self):
pass
def is_operation(self, command):
operations = ['+', '-', 'x', '*', '/',
'plus', 'minus', 'times', 'divide']
for operation in operations:
if operation in command:
return True
| class Checkers:
def __init__(self):
pass
def is_operation(self, command):
operations = ['+', '-', 'x', '*', '/', 'plus', 'minus', 'times', 'divide']
for operation in operations:
if operation in command:
return True |
# noinspection PyUnusedLocal
# skus = unicode string
class InvalidOfferException(Exception):
def __init__(self, expression, message):
self.expression = expression
self.message = message
def checkout(skus):
products = {
'A': productA, 'B': productB, 'C': productC,'D': productD,'E': prod... | class Invalidofferexception(Exception):
def __init__(self, expression, message):
self.expression = expression
self.message = message
def checkout(skus):
products = {'A': productA, 'B': productB, 'C': productC, 'D': productD, 'E': productE, 'F': productF, 'G': productG, 'H': productH, 'I': prod... |
str = "RahulShettyAcademy.com"
str1 = "Consulting firm"
str3 = "RahulShetty"
print(str[1]) #a
print(str[0:5]) # if you want substring in python
print(str+str1) # concatenation
print(str3 in str) # substring check
var = str.split(".")
print(var)
print(var[0])
str4 = " great "
print(str4.strip())
print(str4.ls... | str = 'RahulShettyAcademy.com'
str1 = 'Consulting firm'
str3 = 'RahulShetty'
print(str[1])
print(str[0:5])
print(str + str1)
print(str3 in str)
var = str.split('.')
print(var)
print(var[0])
str4 = ' great '
print(str4.strip())
print(str4.lstrip())
print(str4.rstrip()) |
class Solution:
def secondHighest(self, s: str) -> int:
a = []
for i in s:
if i.isdigit():
a.append(int(i))
stack = [-1]
maxs = max(a)
for i in a:
if i < maxs:
while stack and stack[-1] < i:
stack.pop... | class Solution:
def second_highest(self, s: str) -> int:
a = []
for i in s:
if i.isdigit():
a.append(int(i))
stack = [-1]
maxs = max(a)
for i in a:
if i < maxs:
while stack and stack[-1] < i:
stack.p... |
'''
Fibonacci Sequence
'''
print("Enter a number for Fibonacci")
f = input()
| """
Fibonacci Sequence
"""
print('Enter a number for Fibonacci')
f = input() |
class Duration:
def __init__(self, hours: int = 0, minutes: int = 0, seconds: int = 0):
# setup the class instance and convert any provided times to seconds
self.total_duration: int = (hours * 60 * 60) + (minutes * 60) + seconds
def __add__(self, other):
new_total: int = self.total_dur... | class Duration:
def __init__(self, hours: int=0, minutes: int=0, seconds: int=0):
self.total_duration: int = hours * 60 * 60 + minutes * 60 + seconds
def __add__(self, other):
new_total: int = self.total_duration + other.total_duration
return duration(seconds=new_total)
def get_ho... |
# https://lospec.com/palette-list/pear36
COLORS = [
"#5e315b",
"#8c3f5d",
"#ba6156",
"#f2a65e",
"#ffe478",
"#cfff70",
"#8fde5d",
"#3ca370",
"#3d6e70",
"#323e4f",
"#322947",
"#473b78",
"#4b5bab",
"#4da6ff",
"#66ffe3",
"#ffffeb",
"#c2c2d1",
"#7e7e8... | colors = ['#5e315b', '#8c3f5d', '#ba6156', '#f2a65e', '#ffe478', '#cfff70', '#8fde5d', '#3ca370', '#3d6e70', '#323e4f', '#322947', '#473b78', '#4b5bab', '#4da6ff', '#66ffe3', '#ffffeb', '#c2c2d1', '#7e7e8f', '#606070', '#43434f', '#272736', '#3e2347', '#57294b', '#964253', '#e36956', '#ffb570', '#ff9166', '#eb564b', '#... |
fout = open('output.txt', 'w')
line1 = "This here's the wattle,\n"
fout.write(line1)
line2 = "the emblem of our land.\n"
fout.write(line2)
fout.close()
| fout = open('output.txt', 'w')
line1 = "This here's the wattle,\n"
fout.write(line1)
line2 = 'the emblem of our land.\n'
fout.write(line2)
fout.close() |
def main(fn):
with open(fn, 'r') as f:
lines = [li.strip() for li in f.readlines()]
cmds = list()
for li in lines:
fields = li.split()
cmds.append([fields[0], int(fields[1])])
is_looping, acc = run(cmds)
print(acc)
for i in range(len(cmds)):
if not flip_cmd(cmds... | def main(fn):
with open(fn, 'r') as f:
lines = [li.strip() for li in f.readlines()]
cmds = list()
for li in lines:
fields = li.split()
cmds.append([fields[0], int(fields[1])])
(is_looping, acc) = run(cmds)
print(acc)
for i in range(len(cmds)):
if not flip_cmd(cmds... |
print ('hello world')
print ('hello second time')
print ('Again and Again')
| print('hello world')
print('hello second time')
print('Again and Again') |
#!/usr/bin/env python3
disc_size = [17, 19, 7, 13, 5, 3]
disc_pos = [5, 8, 1, 7, 1, 0]
def solve():
shift_pos = [(disc_pos[i]+i+1)%disc_size[i] for i in range(len(disc_pos))]
t = 0
while max(shift_pos) != 0:
shift_pos = [(shift_pos[i]+1)%disc_size[i] for i in range(len(shift_pos))]
t += 1... | disc_size = [17, 19, 7, 13, 5, 3]
disc_pos = [5, 8, 1, 7, 1, 0]
def solve():
shift_pos = [(disc_pos[i] + i + 1) % disc_size[i] for i in range(len(disc_pos))]
t = 0
while max(shift_pos) != 0:
shift_pos = [(shift_pos[i] + 1) % disc_size[i] for i in range(len(shift_pos))]
t += 1
print(t)
s... |
'''
enable extension for this user
link :
https://bits.bitcoin.org.hk/extensions?usr=dd09c7b0fe33480ab28252c9c9b85c6b&enable=lnurlp
create a lnurlp pay link
needs an admin key
POST /lnurlp/api/v1/links
Headers
{"X-Api-Key": <admin_key>}
Body (application/json)
{"description": <string> "amount": <integer> "max": ... | """
enable extension for this user
link :
https://bits.bitcoin.org.hk/extensions?usr=dd09c7b0fe33480ab28252c9c9b85c6b&enable=lnurlp
create a lnurlp pay link
needs an admin key
POST /lnurlp/api/v1/links
Headers
{"X-Api-Key": <admin_key>}
Body (application/json)
{"description": <string> "amount": <integer> "max": <... |
class Config:
def __init__(self):
self.DARKNET_PATH = "lib/pyyolo/darknet"
self.DATACFG = "data/obj.data"
self.CFGFILE = "cfg/yolo-obj.cfg"
self.WEIGHTFILE_SKETCH = "models/yolo-obj_final_sketch.weights"
self.WEIGHTFILE_TEMPLATES = "models/yolo-obj_45000.weights"
self... | class Config:
def __init__(self):
self.DARKNET_PATH = 'lib/pyyolo/darknet'
self.DATACFG = 'data/obj.data'
self.CFGFILE = 'cfg/yolo-obj.cfg'
self.WEIGHTFILE_SKETCH = 'models/yolo-obj_final_sketch.weights'
self.WEIGHTFILE_TEMPLATES = 'models/yolo-obj_45000.weights'
sel... |
# coding = utf-8
# Create date: 2018-11-6
# Author :Bowen Lee
def test_kernel_headers(ros_kvm_init, cloud_config_url):
command = 'sleep 10; sudo system-docker inspect kernel-headers'
kwargs = dict(cloud_config='{url}test_kernel_headers.yml'.format(url=cloud_config_url),
is_install_to_hard_dr... | def test_kernel_headers(ros_kvm_init, cloud_config_url):
command = 'sleep 10; sudo system-docker inspect kernel-headers'
kwargs = dict(cloud_config='{url}test_kernel_headers.yml'.format(url=cloud_config_url), is_install_to_hard_drive=True)
tuple_return = ros_kvm_init(**kwargs)
client = tuple_return[0]
... |
NAME='router_xmldir'
CFLAGS = []
LDFLAGS = []
LIBS = []
GCC_LIST = ['router_xmldir']
| name = 'router_xmldir'
cflags = []
ldflags = []
libs = []
gcc_list = ['router_xmldir'] |
class Solution:
def brokenCalc(self, X, Y):
res = 0
while X < Y:
res += Y % 2 + 1
Y = (Y + 1) // 2
return res + X - Y | class Solution:
def broken_calc(self, X, Y):
res = 0
while X < Y:
res += Y % 2 + 1
y = (Y + 1) // 2
return res + X - Y |
class RemoteDockerException(RuntimeError):
pass
class InstanceNotRunning(RemoteDockerException):
pass
| class Remotedockerexception(RuntimeError):
pass
class Instancenotrunning(RemoteDockerException):
pass |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
self.ix = 0
self.... | class Solution:
def flip_match_voyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
self.ix = 0
self.flipped = []
self.n = len(voyage)
def preorder(node):
if node:
if node.val == voyage[self.ix]:
self.ix += 1
... |
def run_api_workflow_with_assertions(workflow_specification, current_request, test_context):
current_request_result = current_request(test_context)
if current_request_result is not None and current_request_result["continue_workflow"]:
run_api_workflow_with_assertions(
workflow_specification,... | def run_api_workflow_with_assertions(workflow_specification, current_request, test_context):
current_request_result = current_request(test_context)
if current_request_result is not None and current_request_result['continue_workflow']:
run_api_workflow_with_assertions(workflow_specification, workflow_spe... |
INPUT_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Deriva Demo Input",
"description": ("Input schema for the demo DERIVA ingest Action Provider. This Action "
"Provider can restore a DERIVA backup to a new or existing catalog, "
"or creat... | input_schema = {'$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'Deriva Demo Input', 'description': 'Input schema for the demo DERIVA ingest Action Provider. This Action Provider can restore a DERIVA backup to a new or existing catalog, or create a new DERIVA catalog from a BDBag containing TableSchema.'... |
h,m,s = map(int, input().split())
s += (m*60 + h*3600 + int(input()))
h = s//3600
m = (s%3600)//60
s = (s%3600)%60
if h>23:
h %= 24
print(h,m,s)
| (h, m, s) = map(int, input().split())
s += m * 60 + h * 3600 + int(input())
h = s // 3600
m = s % 3600 // 60
s = s % 3600 % 60
if h > 23:
h %= 24
print(h, m, s) |
#!/usr/bin/env python3
def main():
s = 0
for j in range(1, 1001):
s += j ** j
print(str(s)[-10:])
if __name__ == '__main__':
main()
| def main():
s = 0
for j in range(1, 1001):
s += j ** j
print(str(s)[-10:])
if __name__ == '__main__':
main() |
f = open("thirteen.txt", "r")
lines = [x.strip() for x in f.readlines()]
dots = []
for line in lines:
if line == "":
break
p = line.split(",")
dots.append((int(p[0]), int(p[1])))
folds = [line.split()[2] for line in lines if line.startswith("fold along ")]
fold = folds[0]
dir = fold[0]
line ... | f = open('thirteen.txt', 'r')
lines = [x.strip() for x in f.readlines()]
dots = []
for line in lines:
if line == '':
break
p = line.split(',')
dots.append((int(p[0]), int(p[1])))
folds = [line.split()[2] for line in lines if line.startswith('fold along ')]
fold = folds[0]
dir = fold[0]
line = int(fo... |
class Solution:
# @param A : integer
# @return a list of strings
def fizzBuzz(self, n):
result = []
for i in range(1, n+1):
s = ''
if i %3 == 0:
s += 'Fizz'
if i % 5 == 0:
s += 'Buzz'
if s == ''... | class Solution:
def fizz_buzz(self, n):
result = []
for i in range(1, n + 1):
s = ''
if i % 3 == 0:
s += 'Fizz'
if i % 5 == 0:
s += 'Buzz'
if s == '':
result.append(i)
else:
r... |
class Tag:
_major: str
_minor: str
_separator: str
_factors: dict
def __init__(self, major: str, minor="", separator="", **kwargs):
self._major = major
self._minor = minor
self._separator = separator
self._factors = kwargs
@property
def major(self) -> str:
... | class Tag:
_major: str
_minor: str
_separator: str
_factors: dict
def __init__(self, major: str, minor='', separator='', **kwargs):
self._major = major
self._minor = minor
self._separator = separator
self._factors = kwargs
@property
def major(self) -> str:
... |
def boyer_moore_bad_environment(A, p, m, k):
bad_table = {(i, a): True for i in range(1, m + 1) for a in A}
for i in range(1, m + 1):
for j in range(max(0, i - k), min(i + k, m) + 1):
bad_table[(j, p[i])] = False
return bad_table
def boyer_moore_multi_dim_shift(A, p, m, k):
ready = {a: m + 1 for a i... | def boyer_moore_bad_environment(A, p, m, k):
bad_table = {(i, a): True for i in range(1, m + 1) for a in A}
for i in range(1, m + 1):
for j in range(max(0, i - k), min(i + k, m) + 1):
bad_table[j, p[i]] = False
return bad_table
def boyer_moore_multi_dim_shift(A, p, m, k):
ready = {a... |
# dfir_ntfs: an NTFS parser for digital forensics & incident response
# (c) Maxim Suhanov
__version__ = '1.0.3'
__all__ = [ 'MFT', 'Attributes', 'WSL', 'USN', 'LogFile', 'BootSector', 'ShadowCopy', 'PartitionTable' ]
| __version__ = '1.0.3'
__all__ = ['MFT', 'Attributes', 'WSL', 'USN', 'LogFile', 'BootSector', 'ShadowCopy', 'PartitionTable'] |
# obtain the comma-separated value from the user
csv = input("Enter string: ")
# split the string by the coma and save it in a list
csv = csv.split(',')
# displaying each of the variables
# csv[0] is the name
# csv[1] is the age
# csv[2] is the phone number
print('\n{0:=<30}\nName: {1:30}\nAge: {2:30}\nContact: {3:30... | csv = input('Enter string: ')
csv = csv.split(',')
print('\n{0:=<30}\nName: {1:30}\nAge: {2:30}\nContact: {3:30}\n{4:=<30}\n'.format('', csv[0], csv[1], csv[2], '')) |
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
arr = []
for i in nums:
sq = i*i
arr.append(sq)
return sorted(arr) | class Solution:
def sorted_squares(self, nums: List[int]) -> List[int]:
arr = []
for i in nums:
sq = i * i
arr.append(sq)
return sorted(arr) |
# Fibonacci numbers
def fibs(_to, _from=0):
'''
Returns a given range of fibonacci sequence. Both indexes are included.
fibonacci_sequence[_from:_to]
param _to: int [required] - upper index of requested range
param _from: int [optional] - lower index of requested range
returns: list... | def fibs(_to, _from=0):
"""
Returns a given range of fibonacci sequence. Both indexes are included.
fibonacci_sequence[_from:_to]
param _to: int [required] - upper index of requested range
param _from: int [optional] - lower index of requested range
returns: list - requested range of fibonac... |
def greedy_player_mgt(game_mgr):
game_mgr = game_mgr
def fn_get_action(pieces):
valid_moves = game_mgr.fn_get_valid_moves(pieces, 1)
if valid_moves is None:
return None
candidates = []
for a in range(game_mgr.fn_get_action_size()):
if valid_moves[a]==0:... | def greedy_player_mgt(game_mgr):
game_mgr = game_mgr
def fn_get_action(pieces):
valid_moves = game_mgr.fn_get_valid_moves(pieces, 1)
if valid_moves is None:
return None
candidates = []
for a in range(game_mgr.fn_get_action_size()):
if valid_moves[a] == 0:... |
# Lists in Python are mutable objects that may contain
# any number of items of different types
my_list = [1, "Hello", True, 3.4]
# Python allows negative indexing
my_list = [1, 2, 3, 4, 5, 6]
print(my_list[-1])
# We can access a range of items within the list using slicing
# my_list[start:stop:step]
my_list = ['H', ... | my_list = [1, 'Hello', True, 3.4]
my_list = [1, 2, 3, 4, 5, 6]
print(my_list[-1])
my_list = ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
print(my_list[2:5])
print(my_list[5:])
print(my_list[:-2])
print(my_list[::-1])
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
my_list.insert(2, 7)
print(my_list)
print(my_list.pop... |
l = [2, 5, 6, 5, 11]
def isPal(x):
str_num = str(x)
if len(str_num) == 1:
return True
if len(str_num) % 2 != 0:
mid = int(len(str_num)/2)
front = str_num[:mid]
back = str_num[mid+1:]
else:
mid = int(len(str_num)/2)
front = str_num[:mid]
back =... | l = [2, 5, 6, 5, 11]
def is_pal(x):
str_num = str(x)
if len(str_num) == 1:
return True
if len(str_num) % 2 != 0:
mid = int(len(str_num) / 2)
front = str_num[:mid]
back = str_num[mid + 1:]
else:
mid = int(len(str_num) / 2)
front = str_num[:mid]
bac... |
# take two input numbers
number1 = input("Insert first number : ")
number2 = input("Insert second number : ")
operator = input("Insert operator (+ or - or * or /)")
if operator == '+':
total = number1 + number2
elif operator == '-':
total = number1 - number2
elif operator == '*':
total = number... | number1 = input('Insert first number : ')
number2 = input('Insert second number : ')
operator = input('Insert operator (+ or - or * or /)')
if operator == '+':
total = number1 + number2
elif operator == '-':
total = number1 - number2
elif operator == '*':
total = number2 * number1
elif operator == '/':
... |
# Geometry.py
# Tasks
# Write these functions to calculate following tasks
# 1. Areas ==> Circle, Triangle, Reactangle, Square,..
# 2. Volumes ==> Sphere, Pyramid, Prism, Cone,
def rectangle(width, length):
return width * length
def perimeter_rect(width, length):
return 2*width + 2*length
def triangle(base,... | def rectangle(width, length):
return width * length
def perimeter_rect(width, length):
return 2 * width + 2 * length
def triangle(base, height):
return 0.5 * base * height
def perimeter_triangle(a, b, c):
return a + b + c
if __name__ == '__main__':
print('Geometry.py')
area_rect = rectangle(1... |
def pascal(p):
result = []
for i in range(p):
if i == 0:
result.append([1])
else:
result.append([1] + [result[i - 1][j] + result[i - 1][j + 1] for j in range(len(result[i - 1]) - 1)] + [1])
return result | def pascal(p):
result = []
for i in range(p):
if i == 0:
result.append([1])
else:
result.append([1] + [result[i - 1][j] + result[i - 1][j + 1] for j in range(len(result[i - 1]) - 1)] + [1])
return result |
def encode(key: str, txt: str):
txt_c = ''
for index in range(0, len(txt)):
txt_int = ord(txt[index].lower()) + (ord(key[index % len(key)].upper()) - 65)
if txt_int > 122:
txt_int = txt_int - 26
if txt_int < 97 or txt_int > 122:
txt_c = txt_c + txt[index]
... | def encode(key: str, txt: str):
txt_c = ''
for index in range(0, len(txt)):
txt_int = ord(txt[index].lower()) + (ord(key[index % len(key)].upper()) - 65)
if txt_int > 122:
txt_int = txt_int - 26
if txt_int < 97 or txt_int > 122:
txt_c = txt_c + txt[index]
... |
# Class to store Trie(Patterns)
# It handles all cases particularly the case where a pattern Pi is a subtext of a pattern Pj for i != j
class Trie_Patterns:
def __init__(self, patterns, start, end):
self.build_trie(patterns, start, end)
# The trie will be a dictionary of dictionaries where:
# ... T... | class Trie_Patterns:
def __init__(self, patterns, start, end):
self.build_trie(patterns, start, end)
def build_trie(self, patterns, start, end):
self.trie = dict()
self.trie[0] = dict()
self.node_patterns_mapping = dict()
self.max_node_no = 0
for i in range(len(... |
def trikotniska_stevila(n):
vsota = 0
for i in range(1, n + 1):
vsota += i
return vsota
def najdi():
j = 0
n = 0
st_deliteljev = 0
while st_deliteljev <= 500:
st_deliteljev = 0
j += 1
n = trikotniska_stevila(j)
i = 1
while i <= n ** 0.5:
... | def trikotniska_stevila(n):
vsota = 0
for i in range(1, n + 1):
vsota += i
return vsota
def najdi():
j = 0
n = 0
st_deliteljev = 0
while st_deliteljev <= 500:
st_deliteljev = 0
j += 1
n = trikotniska_stevila(j)
i = 1
while i <= n ** 0.5:
... |
pid_yaw = rm_ctrl.PIDCtrl()
list_LineList = RmList()
variable_X = 0
def start():
global variable_X
global list_LineList
global pid_yaw
robot_ctrl.set_mode(rm_define.robot_mode_chassis_follow)
# rotate gimbal downward so the line is more visible
gimbal_ctrl.pitch_ctrl(-20)
# enable line det... | pid_yaw = rm_ctrl.PIDCtrl()
list__line_list = rm_list()
variable_x = 0
def start():
global variable_X
global list_LineList
global pid_yaw
robot_ctrl.set_mode(rm_define.robot_mode_chassis_follow)
gimbal_ctrl.pitch_ctrl(-20)
vision_ctrl.enable_detection(rm_define.vision_detection_line)
vision... |
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
def product(*x):
sum = 1
if len(x) > 0:
for item in x:
sum = item * sum
print(sum)
def tr... | def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
def product(*x):
sum = 1
if len(x) > 0:
for item in x:
sum = item * sum
print(sum)
def trim(... |
# def form_list():
# with open("words.txt",'r') as f:
# import pdb; pdb.set_trace()
# data=f.readlines()
# form_list()
data=['TEMPERATURE', 'PARTICULAR', 'INSTRUMENT', 'EXPERIMENT', 'EXPERIENCE', 'ESPECIALLY', 'DICTIONARY', 'SUBSTANCE', 'REPRESENT', 'PARAGRAPH', 'NECESSARY', 'DIFFICULT', '... | data = ['TEMPERATURE', 'PARTICULAR', 'INSTRUMENT', 'EXPERIMENT', 'EXPERIENCE', 'ESPECIALLY', 'DICTIONARY', 'SUBSTANCE', 'REPRESENT', 'PARAGRAPH', 'NECESSARY', 'DIFFICULT', 'DETERMINE', 'CONTINENT', 'CONSONANT', 'CONDITION', 'CHARACTER', 'TRIANGLE', 'TOGETHER', 'THOUSAND', 'SYLLABLE', 'SURPRISE', 'SUBTRACT', 'STRAIGHT',... |
#
# PySNMP MIB module HH3C-RADIUS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-RADIUS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:29:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ... |
#!/usr/bin/env python3
# python3 program of subtraction of
# two numbers using 2's complement .
# function to subtract two values
# using 2's complement method
def Subtract(a, b):
# ~b is the 1's Complement of b
# adding 1 to it make it 2's Complement
c = a + (~b + 1)
return c
# Driver code
if __na... | def subtract(a, b):
c = a + (~b + 1)
return c
if __name__ == '__main__':
(a, b) = (56, 22)
print(subtract(a, b)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.