content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Write a Python program to count number of substrings from a given string of lowercase alphabets with exactly k distinct (given) characters
"""
def count_k_dist(str1, k):
str_len = len(str1)
result = 0
ctr = [0] * 27
for i in range(0, str_len):
dist_ctr = 0
ctr = [0] * 27
for j in range(i, str_len... | """
Write a Python program to count number of substrings from a given string of lowercase alphabets with exactly k distinct (given) characters
"""
def count_k_dist(str1, k):
str_len = len(str1)
result = 0
ctr = [0] * 27
for i in range(0, str_len):
dist_ctr = 0
ctr = [0] * 27
for... |
def winning_score():
while True:
try:
winning_score = int(input("\nHow many points should "
"declare the winner? "))
except ValueError:
print("\nInvalid input type. Enter a positive number.")
continue
else:
if winnin... | def winning_score():
while True:
try:
winning_score = int(input('\nHow many points should declare the winner? '))
except ValueError:
print('\nInvalid input type. Enter a positive number.')
continue
else:
if winning_score <= 0:
p... |
''' Else Statements
Code that executes if contitions checked evaluates to False.
''' | """ Else Statements
Code that executes if contitions checked evaluates to False.
""" |
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
ret = []
for x in range(left, right + 1):
y = x
while y > 0:
z = y % 10
if z == 0 or x % z != 0:
break;
y //= 10
... | class Solution:
def self_dividing_numbers(self, left: int, right: int) -> List[int]:
ret = []
for x in range(left, right + 1):
y = x
while y > 0:
z = y % 10
if z == 0 or x % z != 0:
break
y //= 10
... |
# -*- coding: utf_8 -*-
__author__ = 'Yagg'
class ShipGroup:
def __init__(self, ownerName, count, shipType, driveTech, weaponTech, shieldTech, cargoTech, cargoType, cargoQuantity):
self.count = count
self.shipType = shipType
self.driveTech = driveTech
self.weaponTech = weaponTech
... | __author__ = 'Yagg'
class Shipgroup:
def __init__(self, ownerName, count, shipType, driveTech, weaponTech, shieldTech, cargoTech, cargoType, cargoQuantity):
self.count = count
self.shipType = shipType
self.driveTech = driveTech
self.weaponTech = weaponTech
self.shieldTech =... |
#!/usr/bin/python3
"""
Analysis for a 4 load cells (2 strain gauges each) wired to give a single differential output.
https://www.eevblog.com/forum/reviews/large-cheap-weight-digital-scale-options/
"""
def deltav(V, R, r0, r1, r2, r3):
"""return the differential output voltage for the 4x load cell"""
i0 = V / (4.... | """
Analysis for a 4 load cells (2 strain gauges each) wired to give a single differential output.
https://www.eevblog.com/forum/reviews/large-cheap-weight-digital-scale-options/
"""
def deltav(V, R, r0, r1, r2, r3):
"""return the differential output voltage for the 4x load cell"""
i0 = V / (4.0 * R + r0 - r3)... |
class MyHookExtension(object):
def post_create_hook(self, archive, product):
pass
def post_ingest_hook(self, archive, product):
pass
def post_pull_hook(self, archive, product):
pass
def post_remove_hook(self, archive, product):
pass
_hook_extensions = {
'myhooks'... | class Myhookextension(object):
def post_create_hook(self, archive, product):
pass
def post_ingest_hook(self, archive, product):
pass
def post_pull_hook(self, archive, product):
pass
def post_remove_hook(self, archive, product):
pass
_hook_extensions = {'myhooks': my_h... |
# return a go-to-goal heading vector in the robot's reference frame
def calculate_gtg_heading_vector( self ):
# get the inverse of the robot's pose
robot_inv_pos, robot_inv_theta = self.supervisor.estimated_pose().inverse().vector_unpack()
# calculate the goal vector in the robot's reference frame
goal = sel... | def calculate_gtg_heading_vector(self):
(robot_inv_pos, robot_inv_theta) = self.supervisor.estimated_pose().inverse().vector_unpack()
goal = self.supervisor.goal()
goal = linalg.rotate_and_translate_vector(goal, robot_inv_theta, robot_inv_pos)
return goal
v = self.supervisor.v_max() / (abs(omega) + 1) *... |
# Time: O(nlogn)
# Space: O(n)
class Solution(object):
def stoneGameVI(self, aliceValues, bobValues):
"""
:type aliceValues: List[int]
:type bobValues: List[int]
:rtype: int
"""
sorted_vals = sorted(((a, b) for a, b in zip(aliceValues, bobValues)), key=sum, reverse=... | class Solution(object):
def stone_game_vi(self, aliceValues, bobValues):
"""
:type aliceValues: List[int]
:type bobValues: List[int]
:rtype: int
"""
sorted_vals = sorted(((a, b) for (a, b) in zip(aliceValues, bobValues)), key=sum, reverse=True)
return cmp(sum... |
# pylint: disable=global-statement,missing-docstring,blacklisted-name
foo = "test"
def broken():
global foo
bar = len(foo)
foo = foo[bar]
| foo = 'test'
def broken():
global foo
bar = len(foo)
foo = foo[bar] |
def parse_input():
fin = open('input_day3.txt','r')
inputs = []
for line in fin:
inputs.append(line.strip('\n'))
return inputs
def plot_path(inputs, path, ref_path=None):
x=0
y=0
c = 0
hits = []
for i in inputs.split(','):
(d, v) = (i[0],int(i[1:]))
fn =... | def parse_input():
fin = open('input_day3.txt', 'r')
inputs = []
for line in fin:
inputs.append(line.strip('\n'))
return inputs
def plot_path(inputs, path, ref_path=None):
x = 0
y = 0
c = 0
hits = []
for i in inputs.split(','):
(d, v) = (i[0], int(i[1:]))
fn ... |
class Solution:
def detectCycle(self, head):
"""O(n) time | O(1) space"""
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast is slow:
return find_cycle(head, slow)
return None
def find_cycle... | class Solution:
def detect_cycle(self, head):
"""O(n) time | O(1) space"""
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast is slow:
return find_cycle(head, slow)
return None
def find_cyc... |
# This file is imported from __init__.py and exec'd from setup.py
__version__ = "1.0.0+dev"
VERSION = (1, 0, 0)
| __version__ = '1.0.0+dev'
version = (1, 0, 0) |
#returns list of groups. group is a list of strings, a string per person.
def getgroups():
with open('Day6.txt', 'r') as file:
groupList = []
currgroup = []
for line in file:
if line not in ['\n', '\n\n']:
currgroup.append(line.strip())
else:
... | def getgroups():
with open('Day6.txt', 'r') as file:
group_list = []
currgroup = []
for line in file:
if line not in ['\n', '\n\n']:
currgroup.append(line.strip())
else:
groupList.append(currgroup)
currgroup = []
... |
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if not root:
return []
... | """
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def level_order(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if not root:
return []
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Exits with status 0"""
if __name__ == '__main__':
exit(0)
| """Exits with status 0"""
if __name__ == '__main__':
exit(0) |
#
# @lc app=leetcode id=342 lang=python
#
# [342] Power of Four
#
# https://leetcode.com/problems/power-of-four/description/
#
# algorithms
# Easy (39.98%)
# Likes: 315
# Dislikes: 141
# Total Accepted: 114.1K
# Total Submissions: 283.1K
# Testcase Example: '16'
#
# Given an integer (signed 32 bits), write a fun... | class Solution(object):
def _is_power_of_four(self, num):
"""
:type num: int
:rtype: bool
"""
if num < 1:
return False
while num != 1:
(left, right) = divmod(num, 4)
if right != 0:
return False
num = lef... |
list1=['Apple','Mango',1999,2000]
print(list1)
del list1[2]
print("After deleting value at index 2:")
print(list1)
list2=['Apple','Mango',1999,2000,1111,2222,3333]
print(list2)
del list2[0:3]
print("After deleting value till index 2:")
print(list2)
| list1 = ['Apple', 'Mango', 1999, 2000]
print(list1)
del list1[2]
print('After deleting value at index 2:')
print(list1)
list2 = ['Apple', 'Mango', 1999, 2000, 1111, 2222, 3333]
print(list2)
del list2[0:3]
print('After deleting value till index 2:')
print(list2) |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 25 22:07:19 2019
@author: penko
Returns information on all maps (e.g. Hanamura) in Overwatch, with options
to return only OWL modes, and unique maps only (due to a quirk of the API).
"""
'''
# packages used in this function
import requests
import numpy as np
import pan... | """
Created on Wed Dec 25 22:07:19 2019
@author: penko
Returns information on all maps (e.g. Hanamura) in Overwatch, with options
to return only OWL modes, and unique maps only (due to a quirk of the API).
"""
'\n# packages used in this function\nimport requests\nimport numpy as np\nimport pandas as pd\n'
def get_m... |
base_vectors = [[0.001178571428571168, 1.9904285714285708, 0.0011071428571440833], [-0.013142857142857345, -0.0018571428571430015, 1.9921428571428583], [-0.0007499999999995843, 0.17799999999999994, -0.00024999999999630873], [-4.440892098500626e-16, -8.881784197001252e-16, 0.1769999999999996]]
n = [8, 8, 6, 6]
origin = ... | base_vectors = [[0.001178571428571168, 1.9904285714285708, 0.0011071428571440833], [-0.013142857142857345, -0.0018571428571430015, 1.9921428571428583], [-0.0007499999999995843, 0.17799999999999994, -0.00024999999999630873], [-4.440892098500626e-16, -8.881784197001252e-16, 0.1769999999999996]]
n = [8, 8, 6, 6]
origin = ... |
def solveProblem(inputPath):
floor = 0
indexFloorInfo = 0
with open(inputPath) as fileP:
valueLine = fileP.readline()
for floorInfo in valueLine:
indexFloorInfo += 1
if floorInfo == '(':
floor += 1
elif floorInfo == ')':
... | def solve_problem(inputPath):
floor = 0
index_floor_info = 0
with open(inputPath) as file_p:
value_line = fileP.readline()
for floor_info in valueLine:
index_floor_info += 1
if floorInfo == '(':
floor += 1
elif floorInfo == ')':
... |
try:
tests=int(input())
k=[]
for i in range(tests):
z=[]
count=0
find,length=[int(x) for x in input().split(" ")]
list1=list(map(int,input().rstrip().split()))
for i in range(len(list1)):
if list1[i]==find:
z.append(i+1)
... | try:
tests = int(input())
k = []
for i in range(tests):
z = []
count = 0
(find, length) = [int(x) for x in input().split(' ')]
list1 = list(map(int, input().rstrip().split()))
for i in range(len(list1)):
if list1[i] == find:
z.append(i + 1)... |
python = {'John':35,'Eric':36,'Michael':35,'Terry':38,'Graham':37,'TerryG':34}
holy_grail = {'Arthur':40,'Galahad':35,'Lancelot':39,'Knight of NI':40, 'Zoot':17}
life_of_brian = {'Brian':33,'Reg':35,'Stan/Loretta':32,'Biccus Diccus':45}
#membership test
print('Arthur' in holy_grail)
if 'Arthur' not in python:
prin... | python = {'John': 35, 'Eric': 36, 'Michael': 35, 'Terry': 38, 'Graham': 37, 'TerryG': 34}
holy_grail = {'Arthur': 40, 'Galahad': 35, 'Lancelot': 39, 'Knight of NI': 40, 'Zoot': 17}
life_of_brian = {'Brian': 33, 'Reg': 35, 'Stan/Loretta': 32, 'Biccus Diccus': 45}
print('Arthur' in holy_grail)
if 'Arthur' not in python:
... |
class Permission:
"""
An object representing a single permission overwrite.
``Permission(role='1234')`` allows users with role ID 1234 to use the
command
``Permission(user='5678')`` allows user ID 5678 to use the command
``Permission(role='9012', allow=False)`` denies users with role ID 9012
... | class Permission:
"""
An object representing a single permission overwrite.
``Permission(role='1234')`` allows users with role ID 1234 to use the
command
``Permission(user='5678')`` allows user ID 5678 to use the command
``Permission(role='9012', allow=False)`` denies users with role ID 9012
... |
def dict_repr(self):
return self.__dict__.__repr__()
def dict_str(self):
return self.__dict__.__str__()
def round_price(price: float, exchange_precision: int) -> float:
"""Round prices to the nearest cent.
Args:
price (float)
exchange_precision (int): number of decimal digits for exch... | def dict_repr(self):
return self.__dict__.__repr__()
def dict_str(self):
return self.__dict__.__str__()
def round_price(price: float, exchange_precision: int) -> float:
"""Round prices to the nearest cent.
Args:
price (float)
exchange_precision (int): number of decimal digits for exch... |
a, b, c = input().split(' ')
a = float(a)
b = float(b)
c = float(c)
areat = (a * c) / 2
areac = 3.14159 * c**2
areatp = (a + b) * c / 2
areaq = b * b
arear = b * a
print(f'TRIANGULO: {areat:.3f}')
print(f'CIRCULO: {areac:.3f}')
print(f'TRAPEZIO: {areatp:.3f}')
print(f'QUADRADO: {areaq:.3f}')
print(f'RETANGULO: {arear:.... | (a, b, c) = input().split(' ')
a = float(a)
b = float(b)
c = float(c)
areat = a * c / 2
areac = 3.14159 * c ** 2
areatp = (a + b) * c / 2
areaq = b * b
arear = b * a
print(f'TRIANGULO: {areat:.3f}')
print(f'CIRCULO: {areac:.3f}')
print(f'TRAPEZIO: {areatp:.3f}')
print(f'QUADRADO: {areaq:.3f}')
print(f'RETANGULO: {arear... |
#! python3
# aoc_05.py
# Advent of code:
# https://adventofcode.com/2021/day/5
# https://adventofcode.com/2021/day/5#part2
#
def hello_world():
return 'hello world'
class ventmap:
def __init__(self, xmax, ymax):
self.xmax = xmax
self.ymax = ymax
self.map = [[0 for i in range(xmax... | def hello_world():
return 'hello world'
class Ventmap:
def __init__(self, xmax, ymax):
self.xmax = xmax
self.ymax = ymax
self.map = [[0 for i in range(xmax)] for j in range(ymax)]
def check_line(x1, y1, x2, y2):
return x1 == x2 or y1 == y2
def find_vents(input, x, y):
mymap =... |
#
# PySNMP MIB module RAQMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAQMON-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:52:12 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')
(single_value_constraint, value_range_constraint, constraints_union, constraints_intersection, value_size_constraint) ... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Coupon_validity, obj[4]: Gender, obj[5]: Age, obj[6]: Children, obj[7]: Education, obj[8]: Occupation, obj[9]: Income, obj[10]: Bar, obj[11]: Coffeehouse, obj[12]: Restaurant20to50, obj[13]: Direction_same, obj[14]: Distance
# {"feature":... | def find_decision(obj):
if obj[0] <= 1:
if obj[10] <= 1.0:
if obj[2] > 0:
if obj[8] <= 14:
if obj[11] <= 2.0:
if obj[7] > 0:
if obj[1] > 0:
if obj[5] <= 4:
... |
def fib(x):
if x < 2:
return x
return fib(x - 1) + fib(x-2)
if __name__ == "__main__":
N = int(input())
while N > 0:
x = int(input())
print(fib(x))
N = N - 1
| def fib(x):
if x < 2:
return x
return fib(x - 1) + fib(x - 2)
if __name__ == '__main__':
n = int(input())
while N > 0:
x = int(input())
print(fib(x))
n = N - 1 |
T = int(input())
for _ in range(T):
for i in range(1, 1001):
print(i**2)
a = int(input())
if a==0:
continue
else:
break | t = int(input())
for _ in range(T):
for i in range(1, 1001):
print(i ** 2)
a = int(input())
if a == 0:
continue
else:
break |
"""Tiered Lists - a simple way to group items into tiers (at insertion time) while maintaining uniqueness."""
class TieredLists(object):
def __init__(self, tiers):
self.tiers = sorted(tiers, reverse=True)
self.bags = {}
for t in self.tiers:
self.bags[t] = set()
def get_tie... | """Tiered Lists - a simple way to group items into tiers (at insertion time) while maintaining uniqueness."""
class Tieredlists(object):
def __init__(self, tiers):
self.tiers = sorted(tiers, reverse=True)
self.bags = {}
for t in self.tiers:
self.bags[t] = set()
def get_tie... |
class BaseException(object):
'''
The base exception class (equivalent to System.Exception)
'''
def __init__(self):
self.message = None
| class Baseexception(object):
"""
The base exception class (equivalent to System.Exception)
"""
def __init__(self):
self.message = None |
"""Module responsible for client implementation """
class ScrollClient:
"""
ScrollClient
------------
Class responsible for client implementation
"""
def __init__(self):
self._comm_channel = None
@property
def comm_channel(self):
return self._comm_channel
... | """Module responsible for client implementation """
class Scrollclient:
"""
ScrollClient
------------
Class responsible for client implementation
"""
def __init__(self):
self._comm_channel = None
@property
def comm_channel(self):
return self._comm_channel
... |
class Name(object):
def __init__(self,
normal: str,
folded: str):
self.normal = normal
self.folded = folded
| class Name(object):
def __init__(self, normal: str, folded: str):
self.normal = normal
self.folded = folded |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
author: meng.xiang
date: 2019-05-08
description:
"""
class CAP_STYLE(object):
round = 1
flat = 2
square = 3
class JOIN_STYLE(object):
round = 1
mitre = 2
bevel = 3
| """
author: meng.xiang
date: 2019-05-08
description:
"""
class Cap_Style(object):
round = 1
flat = 2
square = 3
class Join_Style(object):
round = 1
mitre = 2
bevel = 3 |
n = int(input())
x = list(map(int, input().split()))
m = 0
e = 0
c = 0
for n in x:
m += abs(n)
e += n ** 2
c = max(c, abs(n))
print(m)
print(e ** 0.5)
print(c) | n = int(input())
x = list(map(int, input().split()))
m = 0
e = 0
c = 0
for n in x:
m += abs(n)
e += n ** 2
c = max(c, abs(n))
print(m)
print(e ** 0.5)
print(c) |
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 1:
output = strs[0]
if strs == []:
output = ""
else:
output = ''
j = 0
Flag = T... | class Solution(object):
def longest_common_prefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 1:
output = strs[0]
if strs == []:
output = ''
else:
output = ''
j = 0
flag = ... |
"""
@date: 5-14-16
Description: Creates the conflict and broad outlines of story relations
"""
class Conflict:
def __init__(relation_outline_array=None):
self.conflict_outline = relation_outline_array
def add_relation(relation_outline):
self.conflict_outline.append(relation_outline)
| """
@date: 5-14-16
Description: Creates the conflict and broad outlines of story relations
"""
class Conflict:
def __init__(relation_outline_array=None):
self.conflict_outline = relation_outline_array
def add_relation(relation_outline):
self.conflict_outline.append(relation_outline) |
#!/usr/bin/env python3
# String to be evaluated
s = "azcbobobegghakl"
# Initialize count
count = 0
# Vowels that will be evaluted inside s
vowels = "aeiou"
# For loop to count vowels in var s
for letter in s:
if letter in vowels:
count += 1
# Prints final count to terminal
print("Number of vowels in ... | s = 'azcbobobegghakl'
count = 0
vowels = 'aeiou'
for letter in s:
if letter in vowels:
count += 1
print('Number of vowels in ' + s + ': ' + str(count)) |
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
ls=s.split(" ")
lt=[]
for x in ls:
x=x[::-1]
lt.append(x)
return " ".join(lt) | class Solution(object):
def reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
ls = s.split(' ')
lt = []
for x in ls:
x = x[::-1]
lt.append(x)
return ' '.join(lt) |
def diglet(i_buraco_origem, buracos):
if buracos[i_buraco_origem] == -99:
return 0
else:
i_buraco_destino = buracos[i_buraco_origem] - 1
buracos[i_buraco_origem] = -99
return 1 + diglet(i_buraco_destino, buracos)
def mdc_euclide(a, b):
if b == 0:
return a
else:
... | def diglet(i_buraco_origem, buracos):
if buracos[i_buraco_origem] == -99:
return 0
else:
i_buraco_destino = buracos[i_buraco_origem] - 1
buracos[i_buraco_origem] = -99
return 1 + diglet(i_buraco_destino, buracos)
def mdc_euclide(a, b):
if b == 0:
return a
else:
... |
x = ['happy','sad','cheerful']
print('{0},{1},{2}'.format(x[0],x[1].x[2]))
##-------------------------------------------##
a = "{x}, {y}".format(x=5, y=12)
print(a)
| x = ['happy', 'sad', 'cheerful']
print('{0},{1},{2}'.format(x[0], x[1].x[2]))
a = '{x}, {y}'.format(x=5, y=12)
print(a) |
class UpdateContext:
"""
Used when updating data.
Helps keeping track of whether the data was updated or not.
"""
data: str
data_was_updated: bool = False
def __init__(self,
data: str):
self.data = data
def override_data(self,
new_data: s... | class Updatecontext:
"""
Used when updating data.
Helps keeping track of whether the data was updated or not.
"""
data: str
data_was_updated: bool = False
def __init__(self, data: str):
self.data = data
def override_data(self, new_data: str) -> None:
self.data = new_dat... |
""" MadQt - Tutorials and Tools for PyQt and PySide
All the Code in this package can be used freely for personal and
commercial projects under a MIT License but remember that because
this is an extension of the PyQt framework you will need to abide
to the QT licensing scheme when releasing.
## $MA... | """ MadQt - Tutorials and Tools for PyQt and PySide
All the Code in this package can be used freely for personal and
commercial projects under a MIT License but remember that because
this is an extension of the PyQt framework you will need to abide
to the QT licensing scheme when releasing.
## $MA... |
class Book:
def __init__(self,title,author):
self.title = title
self.author = author
def __str__(self):
return '{} by {}'.format(self.title,self.author)
class Bookcase():
def __init__(self,books=None):
self.books = books
@classmethod
def create_bookcase(cls,book_list)... | class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return '{} by {}'.format(self.title, self.author)
class Bookcase:
def __init__(self, books=None):
self.books = books
@classmethod
def create_bookcase(cls, bo... |
class FileSystemWatcher(Component):
"""
Listens to the file system change notifications and raises events when a directory,or file in a directory,changes.
FileSystemWatcher()
FileSystemWatcher(path: str)
FileSystemWatcher(path: str,filter: str)
"""
def ZZZ(self):
"""hardcoded/mock instance of th... | class Filesystemwatcher(Component):
"""
Listens to the file system change notifications and raises events when a directory,or file in a directory,changes.
FileSystemWatcher()
FileSystemWatcher(path: str)
FileSystemWatcher(path: str,filter: str)
"""
def zzz(self):
"""hardcoded/mock instance o... |
# # Copyright (c) 2017 - The MITRE Corporation
# For license information, see the LICENSE.txt file
__version__ = "1.3.0"
| __version__ = '1.3.0' |
class car():
def __init__(self, make, model, year ):
self.make = make
self.model = model
self.year = year
self.odometer = 0
def describe_car(self):
long_name = str(self.year)+' '+self.make+' '+self.model
return long_name.title()
def read_odometer(self):
... | class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer = 0
def describe_car(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self)... |
expected_output = {
"route-information": {
"route-table": [
{
"active-route-count": "16",
"destination-count": "16",
"hidden-route-count": "0",
"holddown-route-count": "0",
"rt": [
{
... | expected_output = {'route-information': {'route-table': [{'active-route-count': '16', 'destination-count': '16', 'hidden-route-count': '0', 'holddown-route-count': '0', 'rt': [{'rt-announced-count': '1', 'rt-destination': '10.1.0.0', 'rt-entry': {'as-path': 'AS path: I', 'bgp-path-attributes': {'attr-as-path-effective'... |
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
https://projecteuler.net/problem=7
"""
# Cache a few primes to get the algorithm started.
# Note: the odd values allow the step of 2 in next_prime()
primes = [2, 3, 5]
# Shortc... | """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
https://projecteuler.net/problem=7
"""
primes = [2, 3, 5]
def prime_number(count):
"""
Returns the nth prime.
Adapted from code in prob3.py
"""
test_val = pr... |
command = input()
numbers = [int(n) for n in input().split()]
command_numbers = []
def add_command_numbers(num):
if (num % 2 == 0 and command == "Even") or (num % 2 != 0 and command == "Odd"):
command_numbers.append(num)
for n in numbers:
add_command_numbers(n)
print(sum(command_number... | command = input()
numbers = [int(n) for n in input().split()]
command_numbers = []
def add_command_numbers(num):
if num % 2 == 0 and command == 'Even' or (num % 2 != 0 and command == 'Odd'):
command_numbers.append(num)
for n in numbers:
add_command_numbers(n)
print(sum(command_numbers) * len(numbers)) |
class Env(object):
user='test'
password='test'
port=5432
host='localhost'
dbname='todo'
development=False
env = Env()
| class Env(object):
user = 'test'
password = 'test'
port = 5432
host = 'localhost'
dbname = 'todo'
development = False
env = env() |
def get_phase_dir(self):
"""Return the Rotation direction of the stator phases
Parameters
----------
self : LUT
A LUT object
Returns
-------
phase_dir : int
Rotation direction of the stator phase
"""
return self.output_list[0].elec.phase_dir
| def get_phase_dir(self):
"""Return the Rotation direction of the stator phases
Parameters
----------
self : LUT
A LUT object
Returns
-------
phase_dir : int
Rotation direction of the stator phase
"""
return self.output_list[0].elec.phase_dir |
day09 = __import__("day-09")
process = day09.process_gen
rotor = {
0: {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'},
1: {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'},
}
diff = {
'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0),
}
def draw(data, panels):
direction = 'N'
coord = (0, 0)
try:
i... | day09 = __import__('day-09')
process = day09.process_gen
rotor = {0: {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}, 1: {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}}
diff = {'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0)}
def draw(data, panels):
direction = 'N'
coord = (0, 0)
try:
inp = []
g = ... |
# from enum import IntEnum
LEVEL_UNKNOWN_DEATH = int(0)
LEVEL_NOS = int(-1)
LEVEL_FINISHED = int(-2)
LEVEL_MAX = 21
LEVELS_PER_ZONE = 4
TOTAL_ZONES = 5
# class LevelSpecial(IntEnum):
# UNKNOWN_DEATH = 0,
# NOS = -1,
# FINISHED = -2
#
#
# class Level(object):
# @staticmethod
# def fromstr(level_st... | level_unknown_death = int(0)
level_nos = int(-1)
level_finished = int(-2)
level_max = 21
levels_per_zone = 4
total_zones = 5
def from_str(level_str: str) -> int:
"""With level_str in the form x-y, return the level as a number from 1 to 21, or LEVEL_NOS if invalid"""
args = level_str.split('-')
if len(args)... |
class MagicalGirlLevelOneDivTwo:
def theMinDistance(self, d, x, y):
return min(
sorted(
(a ** 2 + b ** 2) ** 0.5
for a in xrange(x - d, x + d + 1)
for b in xrange(y - d, y + d + 1)
)
)
| class Magicalgirllevelonedivtwo:
def the_min_distance(self, d, x, y):
return min(sorted(((a ** 2 + b ** 2) ** 0.5 for a in xrange(x - d, x + d + 1) for b in xrange(y - d, y + d + 1)))) |
test = 1
while True:
n = int(input())
if n == 0:
break
participantes = [int(x) for x in input().split()]
vencedor = [participantes[x] for x in range(n) if participantes[x] == (x + 1)]
print(f'Teste {test}')
test += 1
print(vencedor[0])
print()
| test = 1
while True:
n = int(input())
if n == 0:
break
participantes = [int(x) for x in input().split()]
vencedor = [participantes[x] for x in range(n) if participantes[x] == x + 1]
print(f'Teste {test}')
test += 1
print(vencedor[0])
print() |
# Check if there are two adjacent digits that are the same
def adjacent_in_list(li=()):
for c in range(0, len(li)-1):
if li[c] == li[c+1]:
return True
return False
# Check if the list doesn't get smaller as the index increases
def list_gets_bigger(li=()):
for c in range(0, len(li)-1):
... | def adjacent_in_list(li=()):
for c in range(0, len(li) - 1):
if li[c] == li[c + 1]:
return True
return False
def list_gets_bigger(li=()):
for c in range(0, len(li) - 1):
if li[c] > li[c + 1]:
return False
else:
return True
def password_criteria(n, mini, ... |
FARMINGPRACTICES_TYPE_URI = "https://w3id.org/okn/o/sdm#FarmingPractices"
FARMINGPRACTICES_TYPE_NAME = "FarmingPractices"
POINTBASEDGRID_TYPE_URI = "https://w3id.org/okn/o/sdm#PointBasedGrid"
POINTBASEDGRID_TYPE_NAME = "PointBasedGrid"
SUBSIDY_TYPE_URI = "https://w3id.org/okn/o/sdm#Subsidy"
SUBSIDY_TYPE_NAME = "Subsidy... | farmingpractices_type_uri = 'https://w3id.org/okn/o/sdm#FarmingPractices'
farmingpractices_type_name = 'FarmingPractices'
pointbasedgrid_type_uri = 'https://w3id.org/okn/o/sdm#PointBasedGrid'
pointbasedgrid_type_name = 'PointBasedGrid'
subsidy_type_uri = 'https://w3id.org/okn/o/sdm#Subsidy'
subsidy_type_name = 'Subsidy... |
#
# @lc app=leetcode id=49 lang=python3
#
# [49] Group Anagrams
#
# https://leetcode.com/problems/group-anagrams/description/
#
# algorithms
# Medium (60.66%)
# Likes: 7901
# Dislikes: 277
# Total Accepted: 1.2M
# Total Submissions: 1.9M
# Testcase Example: '["eat","tea","tan","ate","nat","bat"]'
#
# Given an ar... | class Solution:
def group_anagrams(self, strs: List[str]) -> List[List[str]]:
d = {}
for str in strs:
str_sort = ''.join(sorted(str))
if str_sort in d:
d[str_sort].append(str)
else:
d[str_sort] = [str]
return list(d.values(... |
# Copyright (c) 2019 Pavel Vavruska
# 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, publish, d... | class Config:
def __init__(self, fov, is_perspective_correction_on, is_metric_on, pixel_size, dynamic_lighting, texture_filtering):
self.__fov = fov
self.__is_perspective_correction_on = is_perspective_correction_on
self.__is_metric_on = is_metric_on
self.__pixel_size = pixel_size
... |
def dijkstra(graph):
start = "A"
times = {a: float("inf") for a in graph.keys()}
times[start] = 0
a = list(times)
while a:
node_selected = min(a, key=lambda k: times[k])
print("node selected", node_selected)
a.remove(node_selected)
for node, t in graph[node_selected... | def dijkstra(graph):
start = 'A'
times = {a: float('inf') for a in graph.keys()}
times[start] = 0
a = list(times)
while a:
node_selected = min(a, key=lambda k: times[k])
print('node selected', node_selected)
a.remove(node_selected)
for (node, t) in graph[node_selected... |
# Nodes in lattice graph and associated modules
class LatticeNode:
def __init__(self, dimensions: tuple):
self._parents = list()
self._children = list()
self._is_pruned = False
self.superpattern_count = -1
self.dimensions = dimensions
def is_node_pruned(self):
r... | class Latticenode:
def __init__(self, dimensions: tuple):
self._parents = list()
self._children = list()
self._is_pruned = False
self.superpattern_count = -1
self.dimensions = dimensions
def is_node_pruned(self):
return self._is_pruned
def prune_node(self):... |
globalVar = 0
dataset = 'berlin'
max_len = 1024
nb_features = 36
nb_attention_param = 256
attention_init_value = 1.0 / 256
nb_hidden_units = 512 # number of hidden layer units
dropout_rate = 0.5
nb_lstm_cells = 128
nb_classes = 7
frame_size = 0.025 # 25 msec segments
step = 0.01 # 10 msec time step
| global_var = 0
dataset = 'berlin'
max_len = 1024
nb_features = 36
nb_attention_param = 256
attention_init_value = 1.0 / 256
nb_hidden_units = 512
dropout_rate = 0.5
nb_lstm_cells = 128
nb_classes = 7
frame_size = 0.025
step = 0.01 |
# new_user()
# show_global_para()
# run_pdf()
# read_calib_file_new()
# check_latest_scan_id(init_guess=60000, search_size=100)
###################################
def load_xanes_ref(*arg):
"""
load reference spectrum, use it as: ref = load_xanes_ref(Ni, Ni2, Ni3)
each spectrum is two-column array, con... | def load_xanes_ref(*arg):
"""
load reference spectrum, use it as: ref = load_xanes_ref(Ni, Ni2, Ni3)
each spectrum is two-column array, containing: energy(1st column) and absortion(2nd column)
It returns a dictionary, which can be used as: spectrum_ref['ref0'], spectrum_ref['ref1'] ....
"""
... |
# Problem: https://docs.google.com/document/d/1D-3t64PnsEpcF6kKz5ZaquoMMB-r5UyYGyZzM4hjyi0/edit?usp=sharing
def create_dict():
''' Create a dictionary including the roles and their damages. '''
n = int(input('Enter the number of your party members: '))
party = {} # initialize a dictionary named p... | def create_dict():
""" Create a dictionary including the roles and their damages. """
n = int(input('Enter the number of your party members: '))
party = {}
for _ in range(n):
inputs = input('Enter the role and its nominal damage (separated by a space): ').split()
role = inputs[0]
... |
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n == 1:
return 0
noOfBits = (2 ** (n-1) ) / 2
if k <= noOfBits:
return self.kthGrammar(n-1, k)
else:
return int (not self.kthGrammar(n-1, k - noOfBits)) | class Solution:
def kth_grammar(self, n: int, k: int) -> int:
if n == 1:
return 0
no_of_bits = 2 ** (n - 1) / 2
if k <= noOfBits:
return self.kthGrammar(n - 1, k)
else:
return int(not self.kthGrammar(n - 1, k - noOfBits)) |
# Testing
def print_hi(name):
print(f'Hi, {name}')
# Spewcialized max function
# arr = [2, 5, 6, 1, 7, 4]
def my_bad_max(a_list):
temp_max = 0
counter = 0
for index, num in enumerate(a_list):
for other_num in a_list[0:index]:
counter = counter + 1
value = num - other_n... | def print_hi(name):
print(f'Hi, {name}')
def my_bad_max(a_list):
temp_max = 0
counter = 0
for (index, num) in enumerate(a_list):
for other_num in a_list[0:index]:
counter = counter + 1
value = num - other_num
if value > temp_max:
temp_max = va... |
"""
# Definition for a QuadTree node.
class Node:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRig... | """
# Definition for a QuadTree node.
class Node:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRig... |
class ForthException(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class CompileException(ForthException):
pass
| class Forthexception(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Compileexception(ForthException):
pass |
detik_input = int(input())
jam = detik_input // 3600
detik_input -= jam * 3600
menit = detik_input // 60
detik_input -= menit * 60
detik = detik_input
print(jam)
print(menit)
print(detik)
| detik_input = int(input())
jam = detik_input // 3600
detik_input -= jam * 3600
menit = detik_input // 60
detik_input -= menit * 60
detik = detik_input
print(jam)
print(menit)
print(detik) |
word1 = input()
word2 = input()
# How many letters does the longest word contain?
len_word1 = len(word1)
len_word2 = len(word2)
max_len = 0
if len_word1 >= len_word2:
max_len = len_word1
else:
max_len = len_word2
print(max_len)
| word1 = input()
word2 = input()
len_word1 = len(word1)
len_word2 = len(word2)
max_len = 0
if len_word1 >= len_word2:
max_len = len_word1
else:
max_len = len_word2
print(max_len) |
def _(line):
new_indent = 0
for section in line:
if (section != ''):
break
new_indent = new_indent + 1
return new_indent
| def _(line):
new_indent = 0
for section in line:
if section != '':
break
new_indent = new_indent + 1
return new_indent |
class Something:
def __eq__(self, other: object) -> bool:
pass
class Reference:
pass
__book_url__ = "dummy"
__book_version__ = "dummy"
associate_ref_with(Reference)
| class Something:
def __eq__(self, other: object) -> bool:
pass
class Reference:
pass
__book_url__ = 'dummy'
__book_version__ = 'dummy'
associate_ref_with(Reference) |
"""
# COURSE SCHEDULE II
There are a total of n courses you have to take labelled from 0 to n - 1.
Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai.
Given the total number of courses numCourses and a list of the prerequisite... | """
# COURSE SCHEDULE II
There are a total of n courses you have to take labelled from 0 to n - 1.
Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai.
Given the total number of courses numCourses and a list of the prerequisite... |
class RSI(object):
def __init__(self, OHLC, period):
self.OHLC = OHLC
self.period = period
self.gain_loss = self.gain_loss_calc()
def gain_loss_calc(self):
data = self.OHLC["close"]
gain_loss = []
for i in range(1, len(data)):
change = f... | class Rsi(object):
def __init__(self, OHLC, period):
self.OHLC = OHLC
self.period = period
self.gain_loss = self.gain_loss_calc()
def gain_loss_calc(self):
data = self.OHLC['close']
gain_loss = []
for i in range(1, len(data)):
change = float(data[i])... |
class Recipe(object):
"""
This class provides a Recipe for an Order. It is a list (or dictionary) of
tuples (str machineName, int timeAtMachine).
"""
def __init__(self):
"""
recipe is a list (or dictionary) that contains the tuples of time
information for the Recipe.
"""
self.recipe = []
def indexO... | class Recipe(object):
"""
This class provides a Recipe for an Order. It is a list (or dictionary) of
tuples (str machineName, int timeAtMachine).
"""
def __init__(self):
"""
recipe is a list (or dictionary) that contains the tuples of time
information for the Recipe.
"""
self.recipe ... |
# -*- coding: utf8 -*-
__author__ = 'D. Belavin'
class NodeTree:
__slots__ = ['key', 'payload', 'parent', 'left', 'right', 'height']
def __init__(self, key, payload, parent=None, left=None, right=None):
self.key = key
self.payload = payload
self.parent = parent
self.left = le... | __author__ = 'D. Belavin'
class Nodetree:
__slots__ = ['key', 'payload', 'parent', 'left', 'right', 'height']
def __init__(self, key, payload, parent=None, left=None, right=None):
self.key = key
self.payload = payload
self.parent = parent
self.left = left
self.right = r... |
class Member(object):
def __init__(self, interval, membership):
self.interval = interval
self.membership = membership
def is_max(self):
return self.membership == 1.0
def __str__(self):
return str(self.membership) + "/" + str(self.interval)
def __hash__(self):
... | class Member(object):
def __init__(self, interval, membership):
self.interval = interval
self.membership = membership
def is_max(self):
return self.membership == 1.0
def __str__(self):
return str(self.membership) + '/' + str(self.interval)
def __hash__(self):
... |
class SparkConstants:
SIMPLE_CRED = 'org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider'
TEMP_CRED = 'org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider'
CRED_PROVIDER_KEY = 'spark.hadoop.fs.s3a.aws.credentials.provider'
CRED_ACCESS_KEY = 'spark.hadoop.fs.s3a.access.key'
CRED_SECRET_KEY = ... | class Sparkconstants:
simple_cred = 'org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider'
temp_cred = 'org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider'
cred_provider_key = 'spark.hadoop.fs.s3a.aws.credentials.provider'
cred_access_key = 'spark.hadoop.fs.s3a.access.key'
cred_secret_key = '... |
"""Check if string is blank.
Set boolean _blank to _true if string _s is empty, or null, or contains only whitespace ; _false otherwise.
Source: programming-idioms.org
"""
# Implementation author: TinyFawks
# Created on 2016-02-18T16:58:03.22685Z
# Last modified on 2019-09-26T20:40:16.940019Z
# Version 6
blank = s.... | """Check if string is blank.
Set boolean _blank to _true if string _s is empty, or null, or contains only whitespace ; _false otherwise.
Source: programming-idioms.org
"""
blank = s.strip() == '' |
"""
Test no choices given
.. ignored:
"""
| """
Test no choices given
.. ignored:
""" |
#!/usr/bin/env python
"""
_JobSplitting_
A set of algorithms to allocate work to a set of jobs split along lines
like event, run, lumi, file.
"""
__all__ = []
| """
_JobSplitting_
A set of algorithms to allocate work to a set of jobs split along lines
like event, run, lumi, file.
"""
__all__ = [] |
load(":providers.bzl", "PrismaDataModel")
def _prisma_datamodel_impl(ctx):
return [
PrismaDataModel(datamodels = ctx.files.srcs),
DefaultInfo(
files = depset(ctx.files.srcs),
runfiles = ctx.runfiles(files = ctx.files.srcs),
),
]
prisma_datamodel = rule(
impl... | load(':providers.bzl', 'PrismaDataModel')
def _prisma_datamodel_impl(ctx):
return [prisma_data_model(datamodels=ctx.files.srcs), default_info(files=depset(ctx.files.srcs), runfiles=ctx.runfiles(files=ctx.files.srcs))]
prisma_datamodel = rule(implementation=_prisma_datamodel_impl, attrs={'srcs': attr.label_list(all... |
instr = input()
deviate = int(input())
for x in instr:
if x.isalpha():
uni = ord(x)
if x.islower():
x = chr(97 + ((uni + deviate) - 97) % 26)
elif x.isupper():
x = chr(65 + ((uni + deviate) - 65) % 26)
print(x, end="")
print()
| instr = input()
deviate = int(input())
for x in instr:
if x.isalpha():
uni = ord(x)
if x.islower():
x = chr(97 + (uni + deviate - 97) % 26)
elif x.isupper():
x = chr(65 + (uni + deviate - 65) % 26)
print(x, end='')
print() |
def centered_average(nums):
"""
take out 1 value of the smallest and largst
compute and return the mean of the rest
int div --> truncate the floating part?
ASSUME:
+3 ints
pos/neg
unsorted
dupes possible
Intutition:
- computing an average (sum / # of points)
Approac... | def centered_average(nums):
"""
take out 1 value of the smallest and largst
compute and return the mean of the rest
int div --> truncate the floating part?
ASSUME:
+3 ints
pos/neg
unsorted
dupes possible
Intutition:
- computing an average (sum / # of points)
Approac... |
dd, mm, aa = input().split('/')
print(f'{dd}-{mm}-{aa}')
print(f'{mm}-{dd}-{aa}')
print(f'{aa}/{mm}/{dd}')
| (dd, mm, aa) = input().split('/')
print(f'{dd}-{mm}-{aa}')
print(f'{mm}-{dd}-{aa}')
print(f'{aa}/{mm}/{dd}') |
MODULUS_NUM = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787
MODULUS_BITS = 381
LIMB_SIZES = [55, 55, 51, 55, 55, 55, 55]
WORD_SIZE = 64
# Check that MODULUS_BITS is correct
assert(2**MODULUS_BITS > MODULUS_NUM)
assert(2**(MODULUS_BITS - 1) < MODULUS... | modulus_num = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787
modulus_bits = 381
limb_sizes = [55, 55, 51, 55, 55, 55, 55]
word_size = 64
assert 2 ** MODULUS_BITS > MODULUS_NUM
assert 2 ** (MODULUS_BITS - 1) < MODULUS_NUM
tmp = 0
for i in range(0, len(... |
DICTIONARY = {'A': 'awesome', 'C': 'confident', 'B': 'beautiful',
'E': 'eager', 'D': 'disturbing', 'G': 'gregarious',
'F': 'fantastic', 'I': 'ingestable', 'H': 'hippy',
'K': 'klingon', 'J': 'joke', 'M': 'mustache', 'L': 'literal',
'O': 'oscillating', 'N': 'newtoni... | dictionary = {'A': 'awesome', 'C': 'confident', 'B': 'beautiful', 'E': 'eager', 'D': 'disturbing', 'G': 'gregarious', 'F': 'fantastic', 'I': 'ingestable', 'H': 'hippy', 'K': 'klingon', 'J': 'joke', 'M': 'mustache', 'L': 'literal', 'O': 'oscillating', 'N': 'newtonian', 'Q': 'queen', 'P': 'perfect', 'S': 'stylish', 'R': ... |
_ALLOWED_VOLUME_KEYS = ["claim_name", "mount_path"]
def parse(volume_str):
"""Parse combined k8s volume string into a dict.
Args:
volume_str: The string representation for k8s volume,
e.g. "claim_name=c1,mount_path=/path1".
Return:
A Python dictionary parsed from the given vo... | _allowed_volume_keys = ['claim_name', 'mount_path']
def parse(volume_str):
"""Parse combined k8s volume string into a dict.
Args:
volume_str: The string representation for k8s volume,
e.g. "claim_name=c1,mount_path=/path1".
Return:
A Python dictionary parsed from the given vol... |
# find the non-repeating integer in an array
# set operations (including 'in' operation) are O(1) on average, and one loop that runs n times makes O(n)
def single(array):
repeated = set()
not_repeated = set()
for i in array:
if i in repeated:
continue
elif i in not_repeated:
... | def single(array):
repeated = set()
not_repeated = set()
for i in array:
if i in repeated:
continue
elif i in not_repeated:
repeated.add(i)
not_repeated.remove(i)
else:
not_repeated.add(i)
return not_repeated
array1 = [2, 'a', 'l', ... |
def lstrip0(iterable, obj):
i = 0
iterable_list = list(iterable)
while i < len(iterable_list):
if iterable_list[i] != obj:
break
i += 1
for k in range(i, len(iterable_list)):
yield iterable_list[k]
def lstrip(iterable, obj, key_func=None):
if not key_func:
... | def lstrip0(iterable, obj):
i = 0
iterable_list = list(iterable)
while i < len(iterable_list):
if iterable_list[i] != obj:
break
i += 1
for k in range(i, len(iterable_list)):
yield iterable_list[k]
def lstrip(iterable, obj, key_func=None):
if not key_func:
... |
def extendList(val, lst=[]):
lst.append(val)
return lst
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print("list1 = %s" % list1)
print("list2 = %s" % list2)
print("list3 = %s" % list3) | def extend_list(val, lst=[]):
lst.append(val)
return lst
list1 = extend_list(10)
list2 = extend_list(123, [])
list3 = extend_list('a')
print('list1 = %s' % list1)
print('list2 = %s' % list2)
print('list3 = %s' % list3) |
# Given an array nums of integers,
# return how many of them contain an even number of digits.
def find_numbers_easy(nums):
even_number_count = 0
for num in nums:
if len(str(num)) % 2 == 0:
even_number_count += 1
return even_number_count
def find_numbers_hard(nums):
even_numb... | def find_numbers_easy(nums):
even_number_count = 0
for num in nums:
if len(str(num)) % 2 == 0:
even_number_count += 1
return even_number_count
def find_numbers_hard(nums):
even_number_count = 0
for num in nums:
digit_count = 0
while num > 0:
digit_cou... |
# GENERATED VERSION FILE
# TIME: Tue Sep 28 14:27:47 2021
__version__ = '1.0rc1+c42460f'
short_version = '1.0rc1'
| __version__ = '1.0rc1+c42460f'
short_version = '1.0rc1' |
#!/usr/bin/env python3
bag_of_words = __import__('0-bag_of_words').bag_of_words
sentences = ["Holberton school is Awesome!",
"Machine learning is awesome",
"NLP is the future!",
"The children are our future",
"Our children's children are our grandchildren",
... | bag_of_words = __import__('0-bag_of_words').bag_of_words
sentences = ['Holberton school is Awesome!', 'Machine learning is awesome', 'NLP is the future!', 'The children are our future', "Our children's children are our grandchildren", 'The cake was not very good', 'No one said that the cake was not very good', 'Life is... |
x=4
itersLeft=x
Sum=0
while(itersLeft!=0):
Sum=Sum+x
itersLeft=itersLeft-1
print(Sum)
print(itersLeft)
print(str(x)+"**"+" 2 = "+str(Sum))
| x = 4
iters_left = x
sum = 0
while itersLeft != 0:
sum = Sum + x
iters_left = itersLeft - 1
print(Sum)
print(itersLeft)
print(str(x) + '**' + ' 2 = ' + str(Sum)) |
class Solution:
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
i, j, size, sum, min_len = 0, 0, len(nums), 0, len(nums)
if size == 0:
return 0
while j < size:
sum += nums[j]
... | class Solution:
def min_sub_array_len(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
(i, j, size, sum, min_len) = (0, 0, len(nums), 0, len(nums))
if size == 0:
return 0
while j < size:
sum += nums[j]
... |
QUIP_ACCESS_TOKEN = "1ee2demdo33=|03e39j94r4|komes234mfmf+wapdmeodmemdfg2y6hMfAHko=" # This is a fake token :D
QUIP_BASE_URL = "https://platform.quip.com"
ENV = "DEBUG"
LOGS_PREFIX = ":quip.quip:"
USER_JSON = {
"name": "John Doe",
"id": "1234",
"is_robot": False,
"affinity": 0.0,
"desktop_folder_id"... | quip_access_token = '1ee2demdo33=|03e39j94r4|komes234mfmf+wapdmeodmemdfg2y6hMfAHko='
quip_base_url = 'https://platform.quip.com'
env = 'DEBUG'
logs_prefix = ':quip.quip:'
user_json = {'name': 'John Doe', 'id': '1234', 'is_robot': False, 'affinity': 0.0, 'desktop_folder_id': 'abc1234', 'archive_folder_id': 'abc5678', 's... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.