content stringlengths 7 1.05M |
|---|
# 27 Remove Element
class Solution:
def removeElement(self, nums, val):
nums[:] = [x for x in nums if x != val]
return len(nums)
|
word_list = [
"taken",
"table",
"taxes",
"taste",
"tales",
"tasty",
"tally",
"taboo",
"tacit",
"taxis",
"taper",
"tango",
"tacky",
"taint",
"tawny",
"taker",
"taunt",
"tarot",
"tabor",
"tardy",
"talon",
"tarry",
"tabby",
"taffy",
"tapas",
"tatty",
"tanto",
"tansy",
"talus",
"tater",
"takin",
"tabla",
"taupe",
"talky",
... |
def TiaraCreateTables(con):
# tweet tables
con.query(("create table if not exists tweets("
"id bigint not null,"
"user_id bigint not null,"
"retweets bigint not null,"
"favorites bigint not null,"
... |
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
s1 = sorted(nums1)
s2 = sorted(nums2)
result = []
i1 = i2 = 0
while i1 < len(s1) and i2 < len(s2):
... |
# Write a function called “isOldEnoughToDrink”.
# Given a number, in this case an age, “isOldEnoughToDrink” returns whether a person
# of this given age is old enough to legally drink in the United States.
# Notes:
# The legal drinking age in the United States is 21.
def is_old_enough_to_drink(age):
if age >= 21:
... |
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
def format(wds, L):
wdslen = len(''.join(wds))
l = len(wds) - 1
res = ''
step = (L - w... |
#
# PySNMP MIB module LIVINGSTON-PM-GLOBAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LIVINGSTON-PM-GLOBAL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:56:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
class Solution:
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# 记录修改次数
cnt = 0
# 循环指针
i = 0
while i < len(nums) - 1 and cnt <= 1:
if nums[i] > nums[i + 1]:
cnt += 1
if i... |
class HashTable(object):
"""A hash table is a data structure that can map keys to values. The mapping
between an item and the slot where that item belongs is called the hash
function. In practice there can be hash collisions when the hash function
generates the same index for more than one key. This has... |
#
# PySNMP MIB module ONEACCESS-SHDSL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-SHDSL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:25:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
"""
Problem 2_2:
Write a function 'problem2_2()' that takes a list and does the following to it.
Actually, I've started the function for you below. Your function should do all
of the following, each on a separate line. Recall that lists start numbering
with 0.
0) print the whole list (this doesn't require a while or f... |
def yuvarla(s):
return round(s+0.000001, 0)
def odevnotuhesapla(v):
odevnotu = 50 + v/2
return odevnotu
def orthesapla(v,o,f):
ort = v*0.3 + o*0.2 + f*0.5
return ort
vize = 60
final = 55
odev = odevnotuhesapla(vize)
print('odevnotu: ', odev)
ort = orthesapla(vize, odev, final)
print('ort: '... |
class AtaqueMonstro:
def __init__(
self,
id: int,
nome: str,
quantidade_dado: int,
numero_faces: int,
dano_bonus: int,
acerto: int = 0,
cd: int = 0,
teste: str = None
):
self.__id = id
self.__nome = nome
self._... |
print(map(abs, [1,-2,3,-4]))
l=list(map(abs, [1,-2,3,-4]))
print(l) #>>[1,2,3,4]
def addOne(num):
return num+1
li=list(map(addOne, l))
print(li) #>>[2,3,4,5]
lis = map(addOne, li)
print(lis.__next__()) #>>3
print(lis.__next__()) #>>4
print(lis.__next__()) #>>5
print(lis.__next__()) #>>6
... |
N=int(input())
S=[list(input()) for i in range(N)]
takahashi=0
aoki=0
for s in S:
takahashi+=s.count("R")
aoki+=s.count("B")
print("TAKAHASHI" if takahashi>aoki else "AOKI" if takahashi<aoki else "DRAW") |
class Bunch(object):
"""Convert a dictionary to a class."""
def __init__(self, adict):
self.__dict__.update(adict)
def static_vars(**kwargs):
"""Enable static variables for functions persistent over several calls."""
def decorate(func):
for k in kwargs:
setattr(func, k, kwa... |
# Third order Newton's method
max_steps = 50 ## max number of iterations to use
x0 = 2.
def f(x):
return x**3 - 2.
def fp(x):
return 3*x**2
def fpp(x):
return 6*x
def third_order():
global x
x = []
x.append(x0)
for i in range(max_steps):
x.append(x[i] - f(x[i])/fp(x[i]) - (fpp(x... |
#LeetCode problem 819: Most Common Word
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
ban = set(banned)
words = re.findall(r'\w+', paragraph.lower())
return collections.Counter(w for w in words if w not in ban).most_common(1)[0][0] |
#!/usr/bin/env python
target = 325489
# test values:
# target = 23
# target = 12
# target = 1024
iter = 0
while True:
iter += 1
n = 2 * iter + 1
if n ** 2 >= target:
maxval = n ** 2
break
if __debug__: print(
"Matrix size is {}x{}. Greatest value at [{},{}] is {}".format(n, n, iter, i... |
pattern_zero=[0.0, 0.0099989797, 0.0197938986, 0.0202020202, 0.0293847567, 0.0302009999, 0.0387715539, 0.0399959188, 0.0404040404, 0.0479542904, 0.0495867769, 0.0504030201, 0.056932966, 0.0589735741, 0.060197939, 0.0606060606, 0.0657075809, 0.0681563106, 0.0697887971, 0.0706050403, 0.0742781349, 0.0771349862, 0.0791755... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project: point_set_platform
@Author: anzii.Luo
@Describe:
@Date: 2021/8/3
"""
|
''' Regex Version of strip
Author: <your name>
'''
def restrip(string, chars=None):
'''Given a string, do the same thing as the strip() string method.
If no other arguments are passed other than the string, then
whitespace characters will be removed from the beginning and end
of the string.... |
def letters(word):
ls = set()
for c in word:
ls |= {c}
return ls
def test_letters():
assert letters("book") == {'b', 'k', 'o'}
assert letters("few") == {'f', 'e', 'w'}
def letter_count(word):
lc = {}
for c in word:
if c in lc:
lc[c] += 1
else:
... |
WSStyleSheet = '''
QWidget {
color: #ddd;
background: transparent;
}
QWidget:disabled {
color: #232323;
background-color: transparent;
}
QLineEdit {
border: 1px solid #232323;
border-radius: 4px;
}
QToolTip {
border: 1px solid #232323;
background: #232323;
color: #ddd;
}
QLineEdit:hover, QLineEdit:focus {
... |
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
if not any(costs):
return 0
n, k = len(costs), len(costs[0])
for i in range(1, n):
first, first_idx, second = math.inf, 0, math.inf
for j, val in enumerate(costs[i - 1]):
i... |
libraries = ''
entity_header = '''`timescale 1 ns / 1 ps
module axilite_reg_if #
(
// Width of S_AXI data bus
parameter integer C_S_AXI_DATA_WIDTH = 32,
// Width of S_AXI address bus
parameter integer C_S_AXI_ADDR_WIDTH = 8
)
(
'''
st_in = ' input wire {name},\n'
st_out = ' output wire {na... |
__author__ = "Grzegorz Holak"
def czy_parzysta(liczba):
if not liczba % 2 == 0:
return False
return True
def zrob_parzysta(nieparzysta):
return nieparzysta + 1
def dzielenie(dzielna, dzielnik):
if not czy_parzysta(dzielnik):
dzielnik = zrob_parzysta(dzielnik)
if dzielnik == 0:... |
# Zapfun
# from
# https://siafoo.net/snippet/173
# via https://web.archive.org/web/20110203052513/https://siafoo.net/snippet/173
size(1280,900)
fill(0.2)
rect(0,0,WIDTH,HEIGHT)
fill(1)
stroke(0.2)
strokewidth(1)
font('Zapfino')
for i in range(400):
fontsize(random(30,400))
rotate(random(360))
chars =... |
class Notifier:
pass
class AnotherNotifier:
pass
|
sexo = ''
while sexo != 'M' and sexo != 'F':
r = str(input('informe seu sexo [M/F]: ')).upper().strip()[0]
sexo = r
if r not in 'MF':
print('dados invalidos. por favor, ', end='')
print('Sexo {} registrado com sucesso!'.format(sexo))
# pode ser feito de outra forma
sexo = str(input('informe seu se... |
#!/usr/bin/env python3
def spiral_corners(size):
yield 1
num = 1
sidelen = 3
while sidelen <= size:
for _ in range(4):
num += sidelen - 1
yield num
sidelen += 2
print(sum(spiral_corners(1001)))
|
# V0
# V1
# https://blog.csdn.net/weixin_38111819/article/details/79131409
# https://blog.csdn.net/XX_123_1_RJ/article/details/81021815
# IDEA : DFS
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
... |
class Solution1:
def min_camera_cover(self, root):
self._num_camera = 0
def dfs(node):
if not node:
return 2
left, right = dfs(node.left), dfs(node.right)
if left == 0 or right == 0:
self._num_camera += 1
return 1
... |
#
# PySNMP MIB module ZYXEL-STATIC-ROUTE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-STATIC-ROUTE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:51:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
"""
Preparing higher-resolution data generators for the Jena dataset
"""
# Previously set to 6 (1 point per hour);
# now 3 (1 point per 30 min)
step = 3
lookback = 720
delay = 144
train_gen = generator(
float_data,
lookback=lookback,
delay=delay,
min_index=0,
max_index=200000,
shuffle=True,
... |
class Game:
def __init__(self, pygame, screen):
self.running = True
self.__loadeds__ = []
self.__pygame__ = pygame
self.__screen__ = screen
def __loaded__(self, module):
return (module in self.__loadeds__)
def __use__(self, module):
if not self.__... |
"""
Given a directed graph, check if it contains a cycle.
What's the real time application of this?
Imagine there is a deadlock detection in a system.
Processes can be determined by vertices a&
edge can be - Process is waiting for process B to release the mutex
There are 2 approaches to this:
1. Using color theory
2... |
"""
Given a collection of candidate numbers (candidates) and a target number (target),
find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
... |
"""
Copyright (c) 2016 Alexander Menkin
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at
https://github.com/miloiloloo/diploma_2017_data_generation/blob/master/LICENSE
"""
def unite(parameters):
""" unite n action's execution in one
:param parameters: [(a1, ... |
one = input()
two = input()
one = one.split()
two = two.split()
print("VALOR A PAGAR: R$ {:.2f}".format((float(one[1]) * float(one[2])) + (float(two[1]) * float(two[2]))))
|
##Elias Howell | 10/02/2019 | Lab Assignment #4
##
##Program takes status of buttons and outputs prank configured status of hallway lights
##Algorithm:
## 0)Requests individual button on/off status
## 1)Validates input to ensure input is on or off
## 2)Decides whether or not a hallway light should be on or off accor... |
#-*- coding:utf-8 -*-
class Filter(object):
def __init__(self, all_seeds, ac, re):
self._all = all_seeds
self._accept = ac
self._reject = re |
def test_test():
assert 123 == "123"
def test_test_2():
assert [] == "[]"
|
class FileForm(forms.ModelForm):
class Meta:
model= File
fields= ["name", "filepath"]
|
class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=lambda x: len(x))
dp = {}
ans = 0
for word in words:
dp[word] = 1
for word in words:
for i in range(len(word)):
split = word[:i] + word[i + 1:]
... |
#!/usr/bin/env python3
#-*-coding:utf-8-*-
"""Note:
In Python 3, there is only one integer type int,
which is represented as a long integer, and there is no Long in python2.
"""
class BasicDataType():
str_a = "100"
str_b = "300"
# Note that this is in line with the rules of type string,
# if the str... |
class A(object):
def __init__(self, x):
self.x = x
def __neg__(self):
return A(-self.x)
def __pos__(self):
return A(abs(self.x))
def __invert__(self):
return A(~self.x)
def __add__(self, other):
return A(self.x + other.x)
a1 = A(1)
a2 = A(2)
a3 = A(3)
... |
# 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 isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
stack1 = [p]
stack2 = [q]
w... |
if __name__ == "__main__":
print("Preprocessing data")
|
"""
Project
=======
"""
def f(x: bool = True) -> bool:
"""
Given a boolean, return the opposite.
:param bool x: our boolean parameter.
:return: the opposite of the param.
:rtype: bool
:raises TypeError: if x isn't bool.
"""
if not type(x) == bool:
raise TypeError("No!")
re... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
a = input('Digite algo: ')
print('Qual o tipo? |', type(a))
print('É numeral? |', a.isalnum())
print('É alfabético? |', a.isalpha())
print('É dígito? |', a.isdigit())
print('É minúsculo? |', a.islower())
print('É imprimível? |', a.isprintable())
|
#There are 2N people a company is planning to interview.
#The cost of flying the i-th person to city A is costs[i][0], and
#the cost of flying the i-th person to city B is costs[i][1].
#Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
class Solution:
def two... |
class Calculator:
def __init__(self, a: int, b: int) -> None:
self.a = a
self.b = b
def suma(self) -> int:
return self.a + self.b
def resta(self) -> int:
return self.a - self.b
def multi(self) -> int:
return self.a * self.b
def divicion(sel... |
"""
Time: O(NLogN), N is the number of points.
Space: O(N)
1. Get the angle of each point relative to the "location"
2. Sort the angles
3. Do a sliding window to angles to see what the maximum number of angles within the interval "angle"
[1] For example, angles = [10, 20, 360], angle = 20 we will count 2, but actuall... |
#!/usr/bin/python
#
# Copyright (C) 2011-2016 Michel Dalle
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
class BusinessCountry(object):
"""
Business Country Object used to store business coordinates and count.
Properties: count, list of coordinates.
"""
def __init__(self, count=0, coords=None):
self.count = count
if coords == None:
self.coords = []
else:
self.coords = coords
def addCoord(self, coord):
... |
#!/usr/bin/env python3
# Implements a graph capable of storing edges of type N1 *-$ N2 where * and
# $ are endpoints of type Endpoint.
class Graph:
# Adds a bidirected edges <-> to the graph.
def add_bidirected_edge(self, node1, node2):
raise NotImplementedError
# Adds a directed edge --> to the... |
# coding: utf-8
class TestApp(object):
def setup(self):
pass
def teardown(self):
pass
def test_app(self):
assert True
def test_app2(self):
assert True
|
class BST:
class Node:
def __init__(self, x = None, l = None, r = None):
self.data = x
self.left = l
self.right = r
def is_leaf(self):
return self.left == None and self.right == None
def __str__(self):
return '(' + st... |
class LabeledImage(object):
def __init__(self):
self.height = -1
self.width = -1
self.filename = ""
self.source_id = -1
self.encoded = -1
self.format = str.encode('jpeg')
self.xmins = []
self.xmaxs = []
self.ymins = []
self.ymaxs = [... |
class InvalidConfiguration(Exception):
pass
class RegionNotFound(Exception):
pass
|
#K0 = Startkapital
#p = Zins
#n = Perioden
#K = Endkapital
K0 = float(input("Wieviel Startkapital hast du?"))
p = float(input("Wie hoch ist der Zins?"))
n = float(input("wieviele Perioden legst du an?"))
#berechnung K
K = (K0*(1+p)**n)
print("Das Endkapital nach ", n, " Perioden beträgt: ",K)
|
#
# PySNMP MIB module HPN-ICF-RS485-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-RS485-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:41:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# https://leetcode.com/problems/lru-cache/#
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __repr__(self):
if not self:
return "{}()".format(self.__class__.__name__)
return "{}({})".format(self.__class__.__nam... |
information = {
"site_title": "News Room",
"site_short_name" : "News Room",
"site_name" : "News Room",
"site_motto" : "Get news anywhere",
"site_url" : "https://github.com/arsho",
"site_phone" : "+8801731246426",
"site_email" : "shovon.sylhet@gmail.com",
"site_year" : "2017",
"site_a... |
# coding=utf-8
"""
Base network servers - TODO: Describe
Modules
=======
.. currentmodule:: ultros.core.networks.base.servers
.. autosummary::
:toctree: servers
server
"""
__author__ = "Gareth Coles"
|
def designer_mat1(val, sep, txt):
c = sep
t = txt
for i in range(m // n):
print((c * i).rjust(n + 2, "-") + c + (c * i).ljust(n + 2, "-"))
print("".rjust(n, "-") + t + "".ljust(n, "-"))
for i in range(m // n - 1, -1, -1):
print((c * i).rjust(n + 2, "-") + c + (c * i).ljust(n +... |
#! /usr/bin/python
# -*- coding iso-8859-15
# Entero INT / LONG
a="cadena1"
b="cadena2"
c=a+b
print (a)
print (b)
print (c) |
# slicing string
if False:
frase = 'Curso em Vídeo Python'
print(frase) # Exibe a frase inteira
print(frase[9]) # Exibe o caractere de índice [9] na frase, no caso, a letra "V"
print(frase[9:13]) # Exibe desde o caractere de índice [9] até o [13], porém excluindo este último, ficando "Víde"
prin... |
class Motion():
def __init__(self, serial, map):
self.serial = serial
self.map = map
def move_rel(self):
"""
Move to a new location relative to robot, returns new relative position and error
:return:
"""
pass
def move(self):
"""
Sen... |
'''
Implement a stack class with a max API
Notes:
*
* what went right
* remembered pattern of storing max values in a separate stack
* bugs
* forgot to check for size of max stack before checking top element
'''
class Stack(object):
def __init__(self):
self.arr = []
self.max_arr = []
... |
"""The min_max component."""
DOMAIN = "min_max"
PLATFORMS = ["sensor"]
|
def sample_list(lst, iter_):
return [[lst[i] for i in it] for it in iter_]
# Return a list of all pairs of elements in a list, excluding flips.
def iter_g_2D(n):
assert n >= 2
for i in range(n):
for j in range(i + 1, n):
yield i, j
def iter_gg_3D(n):
assert n >= 3
for i in ... |
def is_numeric(line: str) -> bool:
try:
float(line)
except:
return False
else:
return True
|
#!/usr/bin/env python3
def GenerateEOLTable():
table = [0] * 16
table[ord('\n')] = 1
table[ord('\r')] = 2
line = ', '.join(str(c) for c in table)
line = line + ', // %02X - %02X' % (0, 15)
print('EOLTable:', line)
if __name__ == '__main__':
GenerateEOLTable()
|
def for_I():
for row in range(7):
for col in range(5):
if (col==2) or (row==0 or row==6):
print("*",end=" ")
else:
print(end=" ")
print()
def while_I():
i=0
while i<7:
j=0
while j<5:
if (j==2)... |
# -*- coding: utf-8 -*-
# Copyright 2011 Alf Lervåg. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this l... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#this is a comment
print('Hello World!') #English
|
# General
NAME = 'router'
VERSION = '0.0.0'
# Files
RIDERS_FILE = '{input_dir}/riders.json'
VEHICLES_FILE = '{input_dir}/vehicles.json'
DEPOTS_FILE = '{input_dir}/depots.json'
PARAMS_FILE = '{input_dir}/params.json'
ROUTES_FILE = '{output_dir}/routes.json'
|
class Condition:
COMPARATOR_FUNCS = {
">=": lambda x, y: x >= y,
"<=": lambda x, y: x <= y,
">": lambda x, y: x > y,
"<": lambda x, y: x < y,
"=": lambda x, y: x == y,
"!=": lambda x, y: not x == y
}
def __init__(self, data_spec: str, value, comparator):
... |
# Computes the amount of days of a number of years
years = int(input("years : "))
print(f"\ndays : {years * 365}")
|
#script to count digits in a given no.
print("enter the value of n")
n=int(input())
count=0
while(n!=0):
n=n//10
count+=1
print(count)
|
def get_index(l1, l2):
first = min(l1, l2)
second = max(l1, l2)
return str(int( 26*(first-1) + second - first - (first**2-first)/2 ))
f = open('./1-1000.txt', 'r')
freq_words = f.read().splitlines()
f.close()
frequencies = list(map(lambda x: int(x.split(',')[0]), freq_words))
words = list(map(lambda x: x.... |
start_rule_qualified_type = "Lua_construct.block"
def rename_type(x: str):
if x[0].isupper():
return x.capitalize()
if x == "token":
return "tbnf_token"
return x
def rename_var(x: str):
if x[0].isupper():
return "mk_" + x
return x
|
"""
Leetcode #62
"""
class Solution:
count = 0
def uniquePaths(self, m: int, n: int) -> int:
if not m:
return n
if not n:
return m
matrix = [[1 for x in range(n)] for x in range(m)]
self.count = 0 # reset counter
def helper(a, b):
... |
class Item(object):
def __init__(self, item: dict):
self.id = item.get('id')
self.order_id = item.get('order_id')
self.quantity = item.get('quantity')
self.sale_price = item.get('sale_price')
self.complements = item.get('complements')
self.product = item.get('p... |
# Suppose you have N integers from 1 to N.
# We define a beautiful arrangement as an array that is constructed by these N numbers successfully
# if one of the following is true for the ith position (1 <= i <= N) in this array:
# The number at the ith position is divisible by i.
# i is divisible by the number at the i... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['square']
# Cell
def square(x):
"""Returns the square of $x$, or $x^2$"""
return x*x |
lineList = list()
with open('H:\\q2.txt') as f:
for line in f:
lineList.append(int(line.rstrip('\n')))
print(sum(lineList))
|
def bfs(G, s):
n = len(G)
visited = [False]*n
parent = [None]*n
queue = [s]
visited[s] = True
contador = 0
while queue:
u = queue.pop(0)
for v in range(len(G[u])):
if v<(len(G[u])-1) and not visited[G[u][v]]:
visited[G[u][v]] = True
parent[G[u][v]] = u
a = G[u][v]
... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def tomlplusplus():
http_archive(
name = "tomlplusplus",
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Levenshtein edit distance
# jill-jenn vie et christoph durr - 2014-2015
# snip{
def levenshtein(x, y):
"""Levenshtein edit distance
:param x:
:param y: strings
:returns: distance
:complexity: `O(|x|*|y|)`
"""
n = len(x)
m = len(y)
#... |
# -*- coding: utf-8 -*-
{
'host' : 'code.google.com',
'user' : 'your-name-here@gmail.com',
'data_directory' : './source',
'input_name_format' : '{problem}-{input}-{id}.in',
'output_name_format' : '{problem}-{input}-{id}.out',
'source_names_format' : [],
}
|
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left= left
self.right = right
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, val):
node = Node(val)
temp = self.root
if temp is None:
... |
"""
Module: 'umqtt.simple' on esp8266 v1.10
"""
# MCU: (sysname='esp8266', nodename='esp8266', release='2.2.0-dev(9422289)', version='v1.10-8-g8b7039d7d on 2019-01-26', machine='ESP module with ESP8266')
# Stubber: 1.1.0
robust = None
simple = None
|
#!/usr/bin/env python3
def beolvas(file):
pontszamok = []
with open(file, "rt") as f:
for sor in f:
try:
pontszamok.append(int(sor.rstrip("\n")))
except ValueError:
pass
return pontszamok
def main():
print(beolvas("7_kzh_pontszam_hibas.txt"))
main()
|
# Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY, GROUP BY, HAVING
# (a) Display the number of departments. Each department should be displayed once.
# (b) Find the name and salary of those employees whose salary is between 35000 and 40000.
# (c) Find the name of those employees who live in guwahati, sura... |
# Copyright 2016 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
#!/usr/bin/env python
__author__ = "Peter Maxwell"
__copyright__ = "Copyright 2007-2020, The Cogent Project"
__credits__ = ["Peter Maxwell", "Gavin Huttley"]
__license__ = "BSD-3"
__version__ = "2020.2.7a"
__maintainer__ = "Peter Maxwell"
__email__ = "pm67nz@gmail.com"
__status__ = "Production"
def PamlParser(f):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.