Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
100
3.06M
# -*- coding: utf-8 -*- """ Created on Wed Sep 18 13:13:09 2019 Psudo : 1.Get a Dataset 2.arbitarily choose K centroids in random 3.Assign the closest data points by distance to a centroid/cluster 4.Compute mean of the datapoints in the clusters excluding the centroids 5.The mean would be...
n1=int(input('digite seu numero: ')) n2= n1*2 n3= n1*3 n4= n1**(1/2) print(f'o dobro do seu numero e {n2} o triplo e {n3} a raiz quadrada dele e {n4}')
import unittest from problems.FibonacciGenerator import FibonacciGenerator class TestFibonacciGenerator(unittest.TestCase): def test_Fibonacci(self): self.assertEqual(0, fibonacci(1)) self.assertEqual(1, fibonacci(2)) self.assertEqual(1, fibonacci(3)) self.assertEqual(2, fibonacci(...
import find_min def secondsmallestNumber(array): v = find_min.findMin(array) for i in array: if v == i: array.remove(i) maxi = find_min.findMin(array) return maxi array = [3,1,6,9,3] print(secondsmallestNumber(array))
# Python Unittest # unittest.mock � mock object library # unittest.mock is a library for testing in Python. # It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. # unittest.mock provides a core Mock class removing the need to create a host of stu...
# coding:utf-8 # python3 # original: u"杨仕航" # modified: @kevinqqnj import logging import numpy as np from queue import Queue, LifoQueue import time import copy # DEBUG INFO WARNING ERROR CRITICAL logging.basicConfig(level=logging.WARN, format='%(asctime)s %(levelname)s %(message)s') # format='%(as...
class Track(): """creates the tracks for all of the cars""" # makes sure pixel resolution is high def __init__(self, rows, cols, width, height, timeStep): self.rows = rows # number of horizontal lanes self.cols = cols # number of vertical lanes self.width = width # pixels wides ...
# Tuples are immutable print("============ tuples ============") print() tuples = (12345, 54321, 'hello!') print(tuples) u = tuples, (1, 2, 3, 4, 5) print(u) # The statement t = 12345, 54321, 'hello!' is an example of tuple packing: # the values 12345, 54321 and 'hello!' # are packed together in a tuple. The revers...
class Solution(object): def intersectionSizeTwo(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ intervals.sort() filtered_intervals=[] #print intervals for interval in intervals: while filtered_intervals and filtered_int...
""" Ejercicio 4.1: Debugger Ingresá y corré el siguiente código en tu IDE: def invertir_lista(lista): '''Recibe una lista L y la develve invertida.''' invertida = [] i=len(lista) while i > 0: # tomo el último elemento i=i-1 invertida.append (lista.pop(i)) # return invertida l ...
import game, population import random # config parameters # Population n_cars = 10 start = (50,50) # Brain layers = 10 neurons = 20 # evolution mutation_rate = 0.10 parents_to_keep = 0.33 # generate the brains # brains = [] # for i in range(0, n_cars): # seed = random.random() # brains += [population.NeuronBr...
sq1 = raw_input("inserer une sequence ADN :") i=0 n=len(sq1)-1 x=0 while i<n : if sq1[i]==sq1[n] : x=x+1 i=i+1 if x == (len(sq1)-1)/2 : print "cette sequence est un palindrome" else : print"cette sequence n'est pas un palindrome"
import gensim import numpy as np import copy from tqdm.auto import tqdm from utils import log, intersection_align_gensim from gensim.matutils import unitvec class GlobalAnchors(object): def __init__(self, w2v1, w2v2, assume_vocabs_are_identical=False): if not assume_vocabs_are_identical: w2v1,...
#!/usr/bin/env python # coding: utf-8 # # IBM HR Employee Attrition & Performance. # ## [Please star/upvote in case you find it helpful.] # In[ ]: from IPython.display import Image Image("../../../input/pavansubhasht_ibm-hr-analytics-attrition-dataset/imagesibm/image-logo.png") # ## CONTENTS ::-> # [ **1 ) Expl...
import re v=input("Enter the password to check:") if(len(v)>=8): if(bool(re.match('((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*]).{8,30})',v))==True): print("Good going Password is Strong.") elif(bool(re.match('((\d*)([a-z]*)([A-Z]*)([!@#$%^&*]*).{8,30})',v))==True): print("try Something strong...
number = 0 variables = "" def fizz_buzz(num, var): fizzarray = [] # doneTODO: Create an empty array outside the loop to store data var = variables num = number while num < 100: # Reset var to prevent issues of adding buzz to buzz or buzz to fizzbuz var = "" #print(num) ...
# 반복문 a = ['cat', 'cow', 'tiger'] for animal in a: print(animal, end=' ') else: print('') # 복합 자료형을 사용하는 for문 l = [('루피', 10), ('상디', 20), ('조로', 30)] for data in l: print('이름: %s, 나이: %d' % data) for name, age in l: print('이름: {0}, 나이: {1}'.format(name, age)) l = [{'name': '루피', 'age': 30}, {'name'...
import open3d as o3d import numpy as np def degraded_copy_point_cloud(cloud, normal_radius, n_newpc): """ 与えられた点群データからPoisson表面を再構成し、頂点データからランダムに点を取り出して 新たな点群を作成する. Parameters ---------- cloud : open3d.geometry.PointCloud 入力点群 normal_radius : float 法線ベクトル計算時の近傍半径(Poisson表面...
class Parent: def printlastname(self): print('Aggarwal') class Child(Parent): #inherited Parent class def print_name(self): print('Rohan') def printlastname(self): #overwriting parent function print('Aggar') bucky=Child() bucky.print_name() bucky.printlastname()
from __future__ import print_function class Node: def __init__(self, value, next=None): self.value = value self.next = next def print_list(self): temp = self while temp is not None: print(temp.value, end=" ") temp = temp.next print() def reverse_every_k_elements2(head, k): '''...
sumofsquares = 0 squareofsum = 0 for x in range(1,101): sumofsquares = sumofsquares + (x**2) squareofsum = squareofsum + x squareofsum = squareofsum ** 2 print( squareofsum - sumofsquares) #269147
import re def headers_to_dict(data): global headers for value in data: try: hea_data = re.findall(r'(.*?): (.*?)\n', value)[0] headers.setdefault(hea_data[0], hea_data[1]) except IndexError: hea_data = value.split(': ', 1) headers.setdef...
# 输入:input() #name = input() #print(name) #name = input('请输入你的名字:') #阻塞式 #print(name) ''' 练习: 游戏:捕鱼达人 输入参与游戏者用户名 输入密码: 充值: 500 ''' print(''' ********************* 捕鱼达人 ********************* ''') username = input('请输入参与游戏者的用户名:\n') password = input('输入密码:\n') print('%s请充值才能进入游戏\n' %username) coins =...
import numpy as np import pandas as pd from os import system class Table(): def __init__(self): self.table = [[' ',' ',' '], [' ',' ',' '], [' ',' ',' ']] def getMoves(self): moves = [] for x in range(3): for y in range(3): ...
import pytest import serverly.utils from serverly.utils import * def test_parse_role_hierarchy(): e1 = { "normal": "normal", "admin": "normal" } e2 = { "normal": "normal", "admin": "normal", "staff": "admin", "root": "staff", "god": "staff", } ...
class Solution(object): def toHex(self, num): """ :type num: int :rtype: str """ if num == 0: return '0' # letter map mp = '0123456789abcdef' ans = '' for _ in range(8): # get last 4 digits # num & 1111b ...
import math from random import randint import pygame as pg from pygame import mixer as mx """ INITIALISING PYGAME """ pg.init() """ CREAITNG SCREEN """ screen = pg.display.set_mode((800, 600)) """ BACKGROUND MUSIC """ # mx.music.load('lofi_background.wav') # mx.music.set_volume(0.8) # mx.music.play(-1)...
""" This is an interactive demonstration for information retrieval. We will encode a large corpus with 500k+ questions. This is done once and the result is stored on disc. Then, we can enter new questions. The new question is encoded and we perform a brute force cosine similarity search and retrieve the top 5 question...
#!/usr/bin/env python3 # # Copyright (C) 2020-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this fil...
""" Rosechelle Joy C. Oraa 2013-11066 CMSC 128 AB-3L """ import sys """ numToWords() accepts an input number and outputs its equivalent in words temp_num : input by the user """ def numToWords(temp_num): if len(temp_num)>7: #if number inputed is greater than 7 digits: invalid print 'Invalid: input can o...
from collections import defaultdict from math import exp, log import pandas as pd # optional class Elo: """Base class to generate elo ratings Includes the ability for some improvements over the original methodology: * k decay: use a higher update speed early in the season * crunch/carryover...
class Human(object): def __init__(self, name): self.name = name def walk(self): print (self.name + " is walking") def get_name(self): return (self. name) def set_name(self, name): if len(name) <= 10: self.name = name human_a = Human("alan") print (human_a.name) human_a.set_name('bob') prin...
#!/usr/bin/python import urllib2 site = raw_input("site : ") # http://www.google.com/ ---> this must be in this form list = open((raw_input("list with folders : "))) # a textfile , one folder/line for folder in list : try : url = site+folder urllib2.urlopen(url).read() msg = "[-] folder " + ...
#INPUT """Our input is the fahrenheit temperature from the woman""" fahrenheit_value = float(input("Please Enter the Fahrenheit temperature: \n")) #PROCESSING """The conversion from fahrenheit to celsius""" celsius_value = (fahrenheit_value - 32) * (5/9) print(round(celsius_value, 2)) #OUTPUT """Output is the ...
adj=[] row, col = key // n, key % n if (col - 1) >= 0: adj.append((row*n) + (col - 1)) if (col + 1) < n: adj.append((row*n) + (col + 1)) if (row - 1) >= 0: adj.append((row-1)*n + col) if (row + 1) < n: adj.append((row + 1)*n + col) return adj def find_path(source, arr, ...
#!/usr/bin/env python3 ''' @author Michele Tomaiuolo - http://www.ce.unipr.it/people/tomamic @license This software is free - http://www.gnu.org/licenses/gpl.html ''' import sys class TicTacToe: NONE = '.' PLR1 = 'X' PLR2 = 'O' DRAW = 'None' OUT = '!' def __init__(self, side=3): self....
from django import template register = template.Library() @register.filter(name='star_multiply') def star_multiply(value, arg: str = '★', sep: str = ' ') -> str: """ Размножитель символов :param value: количество символов в пакете :param arg: повторяемый символ :param sep: разделитель между симво...
n = int(input()) s = [input() for _ in range(3)] ans = 0 for v in zip(*s): len_ = len(set(v)) ans += len_ - 1 # if len_ == 3: # ans += 2 # elif len_ == 2: # ans += 1 # else: # # len_ == 1 # ans += 0 print(ans)
#Nhap vao ba so a, b, c a = int(input(" Nhap vao gia tri a=")); b = int(input(" nhap vao gia trị b =")); c = int(input(" nhap vao gia trị c =")); if a <= b <= c: print("%d %d %d" % (a, b, c)) elif a <= c <= b: print("%d %d %d" % (a, c, b)) elif b <= a <= c: print("%d %d %d" % (b, a, c)) elif b <= c <= a: ...
print "Each game console cost 22000" money = input("How much money do you have in your account now? Php ") y=(money)/22000 print "The number of game consoles with a price of Php 22000 you can buy is ", y n = (money) - y*22000 print "After buying the consoles, you will have", n,"pesos left on your account" e = 22...
""" Merge k sorted arrays <3,5,7> <0,6> <0,6,28> Approach 1 : merge sort Approach 2 : use a min heap(size<=k) to keep current min elements from each array Each node in the heap is a tuple (value, array_index, element_index) : pop min element from min heap to add to output array : push...
# -*- coding: utf-8 -*- """ Created on Tue May 30 17:49:57 2017 @author: brummli """ import matplotlib as mpl mpl.use('Agg') import numpy as np import matplotlib.pyplot as plt from dataLoader import dataPrep """ Calculates standard statistics :params: data: numpy array containing the data of form (examples,times...
''' You've built an inflight entertainment system with on-demand movie streaming. Users on longer flights like to start a second movie right when their first one ends, but they complain that the plane usually lands before they can see the ending. So you're building a feature for choosing two movies whose total runti...
import time stat1=dict() stat2=dict() #numbers_sizes = (i*10**exp for exp in range(4, 8, 1) for i in range(1, 11, 5)) numbers_sizes = [10**exp for exp in range(4, 10, 1)] print(str(numbers_sizes)) for input in numbers_sizes: # prog 1 start_time=time.time() cube_numbers=[] for n in range(0,input): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from numpy import random, exp, dot, array #%% Neural Network class Neural_Network(): #%% Sigmoid function def φ(self, x): return 1/(1 + exp(-x)) # Sigmoid function's derivative def dφ(self, x): return exp(x)/ (1 + ...
#! /usr/bin/python # -*- coding: utf-8 -*- import numpy as np data = np.array([[5., 7., 12.], [6., 5., 10.], [3., 4., 8.], [2., 4., 6.]]) s_mean = np.zeros(data.shape) for i in range(data.shape[1]): s_mean[:, i] = data[:, i].mean() print("水準平均 " + str(s_mean))...
import asyncio import sys async def on_recv(reader, writer, name, loop): i = 0 while True: data = await reader.read(100) if data == b'stop': break data = data.decode() print(f'{name}-{i}: {data}') await asyncio.sleep(1.0) resp = f'{name}-{i}-{dat...
# Question 1 # i=1 # while i<=1000: # if i%2==0: # print("nav") # if i%7==0: # print("gurukul") # if i%21==0: # print("navgurukul") # i=i+1 # Question 2 # Number_of_students=input("enter a name:") # Ek_student_ka_kharcha=int(input("enter a spending amount:")) # if Ek_student_ka_kharcha<=50000: # print("H...
################## #time_test #Author:@Rooobins #Date:2019-01-03 ################## import time a = "Sat Mar 28 22:24:24 2016" print(time.time()) print(time.localtime(time.time())) print(time.asctime(time.localtime(time.time()))) print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) print(time.strftime("%a...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def com_bv(node): #print node.val if node.left is None and node.right is None: node.bv=0 elif node.left is None and node.right is not None: node.bv=com_bv(node.right)+1 elif node.left is not None and node.rig...
salário = float(input('Digite o valor do salário: R$')) if salário <= 1250: salário *= 1.15 else: salário *= 1.10 print('O salário inicial será aumentado para R${:.2f}'.format(salário))
class Solution(object): def threeSum(self, nums): result = [] nums.sort() #중복제거 간소화 하기 위해 정렬 for i in range(len(nums)-2): #중복 일 경우 건너 뜀 if i > 0 and nums[i] == nums[i - 1]: continue left, right = i + 1, len(nums) - 1 ...
from sklearn import datasets, neighbors import numpy as np # Load iris data from 'datasets module' iris = datasets.load_iris() # Get data-records and record-labels in arrays X and Y X = iris.data y = iris.target # Create an instance of KNeighborsClassifier and then fit training data clf = neighbors.KNeighborsClassif...
s = input() dic = [] i0 = 0 st = False for i in range(len(s)): if s[i].islower(): continue if st: dic.append(s[i0 : i + 1]) st = False else: i0 = i st = True dic = [w.lower() for w in dic] dic.sort() for w in dic: w_ls = list(w) w_ls[0] = w_ls[0].upper() ...
even_message = "an even number: " odd_message = "an odd number: " numbers = range(1, 10) finished = False for i in numbers: print ("processing number " , i, ", finished: ", finished) if i % 2 == 0: print (even_message, i) else: print (odd_message, i) finished = True print ("all numbers pro...
#!/usr/bin/env python3 from librip.gens import gen_random from librip.iterators import Unique data1 = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2] data2 = gen_random(1, 3, 10) data3 = gen_random(1,9,15) data = ['a', 'A', 'b', 'B'] # Реализация задания 2 for i in Unique(data1): print(i, end=', ') print() #for i in d...
from person import Pessoa class Medico(Pessoa): __crm: str = '' __salario: int = 0 __especialidades: [str] = [] def __init__( self, nome: str, rg: str, cpf: str, crm: str, telefone: str, salario: int, especialidades: [str] ): ...
v= raw_input().rstrip() evenB = oddB = '' for l, m in enumerate(v): if l & 1 == 0: evenB += m else: oddB += m print(evenB + " " + oddB)
# write a programm to print the multiplication table of the number entered by the user. number=int(input("enter the number")) i=1 while i<=10: print(i*number) i=i+1 # ask the user to enter 10 number using only one input statement and add them to the list list=[] for name in range(10): number=input("enter t...
################### ## Variable Domains ################### domain = (1,2,3,4) ###################################################### ## Definition of a state (i.e., what the variables are ###################################################### start_state = [ None,1 ,None,3 , 4 ,None...
import random print(" I will flip a coin 1000 times. Guess how many times it will comp up heads. (Press Enter to begin") input() flips = 0 # a counter variable to keep track of how many flips has been made heads = 0 # another counter variable to keep track of how many heads pop from the while loop in the if statement....
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.0 # kernelspec: # display_name: drlnd # language: python # name: drlnd # --- # # Navigation # # --- # # In this notebook, you will learn...
import sys #Recursive function that returns a generator with all combinations def get_all_splits(array): if len(array) > 1: for sub in get_all_splits(array[1:]): yield [' '.join([array[0],sub[0]])] + sub[1:] yield [array[0]] + sub else: yield array def ...
def words(sentence): lib = {} count = 0 sentence_list = sentence.split() length = len(sentence_list) for word in sentence_list: for i in range(length): if sentence_list[i].isdigit() == True: if sentence_list[i] == word: count+=1 ...
#!/usr/bin/python # @BEGIN_OF_SOURCE_CODE # @SPOJ BISHOPS C++ "Simple Math" from sys import stdin while True: line = stdin.readline() if line == '': break; n = int(line) if n == 1: print 1 else: print 2*n-2 # @END_OF_SOURCE_CODE
import unittest from src.guest import Guest from src.room import Room from src.song import Song class TestGuest(unittest.TestCase): def setUp(self): self.guest = Guest("Katy", 20) def test_guest_has_name(self): self.assertEqual("Katy", self.guest.guest_name) def test_guest_has_cash(sel...
""" link: https://leetcode.com/problems/find-k-pairs-with-smallest-sums problem: 用 nums1, nums2 中元素组成元素对 (u,v), 其中 u ∈ nums1,v ∈ nums2,求所有元素对中和最小的前 k 对 solution: 小根堆。因为 (nums[i], nums[j]) < (nums[i], nums[j+1]),可以肯定前者未出堆时后者入堆也没有意义,在前者出堆再将后者入堆 保持堆大小为 n,而不需要 mn,时间复杂度(klogn) """ class Solution: def kSmal...
# ch2_01_numeric.py # print("숫자형: 정수") a = 123 a = -178 a = 0 print("숫자형: 실수") a = 1.2 a = -3.48 a = 4.24e10 a = 4.24e-10 print("숫자형: 8진수와 16진수") a = 0o177 a a = 0x8FF a a = 0xABC a print("숫자형: 연산자와 연산") a = 3 b = 4 a + b a * b a / b a ** b a % b a // b 14 // 3 14 % 3 """ Author: redwo...
lists1 = [] n = 0 var_1 = int(input("Введите число: ")) var_lenth = int(len(str(var_1))) while n < var_lenth: var_01 = var_1 % 10 lists1.insert(n, var_01) var_1 = var_1 // 10 n += 1 print(max(lists1))
""" POO - Herança Múltipla É a possibilidade de uma classe herdar de múltiplas classes. Desse modo, a classe filha herda todos os atributos e métodos das super classes. OBS: A Herança Múltipla pode ser feita de duas maneiras: - Multiderivação Direta; - Multiderivação Indireta. # Exemplo de Multiderivação Di...
class AhoNode: def __init__(self): self.goto = {} self.out = [] self.fail = None def aho_create_forest(patterns): root = AhoNode() for path in patterns: node = root for symbol in path: node = node.goto.setdefault(symbol, AhoNode()) node.out.app...
# -*- coding: utf-8 -*- import appex import unicodedata import clipboard def erase_dakuten(char: chr) -> chr: myDict = { 'が': 'か', 'ぎ': 'き', 'ぐ': 'く', 'げ': 'け', 'ご': 'こ', 'ざ': 'さ', 'じ': 'し', 'ず': 'す', 'ぜ': 'せ', 'ぞ': 'そ', 'だ': 'た', 'ぢ': 'ち', 'づ': 'つ', 'で': 'て', 'ど': 'と', 'ば': 'は', '...
# Tram a = int(input()) inputs = [input() for i in range(a)] min_cap = 0 num = 0 for i in inputs: c = i.split() num += int(c[1]) - int(c[0]) if num > min_cap: min_cap = num print(min_cap)
#This python script automatically arranges the files in your folder #The files will be grouped according to their file type #The file type that can be grouped are audios, videos, images, and documents import os from pathlib import Path FILETYPE = { "AUDIO":['.m4a','.m4b','.mp3','.wav','.flac','.cda'], "D...
class Stack(): def __init__(self,items=[]): self.items = [] def push(self,data): i = self.items.append(data) return i def pop(self): i = self.items.pop() return i def is_empty(self): return len(self.items)==0 def peek(self): if not sel...
# Create a program that prints the average of the values in the list: # a = [1, 2, 5, 10, 255, 3] a = [1, 2, 5, 10, 255, 3] sum = 0 for count in a: sum += count avg = sum / len(a) print avg
import numpy as np import math # Gaussian Elimination Partial Pivoting # Input GEPP(Ax = b) def GEPP(A, b): n = len(A) if b.size != n: raise ValueError("Invalid argument: incompatible sizes between A & b.", b.size, n) for k in xrange(n-1): maxindex = abs(A[k:,k]).argmax() + k if A[...
from room import Room from character import Character def battle(player, npc): fighting = True print("You are now battling " + npc.name) while fighting: user_input = input("What would you like to do?") if user_input == 'fight': npc.take_damage(player.attack) print(...
""" Testing for Hilbert transform methods that use wavelets at their core Using the math relation a^2 / (a^2 + x^2) (Lorentz/Cauchy) has an analytical Hilbert transform: x^2 / (a^2 + x^2) """ import numpy as np from numpy.testing import assert_array_almost_equal from hilbert.wavelet import hilbert_haar, _haar_matri...
import paho.mqtt.client as mqtt import sys import json local_broker = "broker" # broker is host name local_port = 1883 # standard mqtt port local_topic = "signs" # topic is image with open("keys.json") as json_file: keys = json.load(json_file) # dictionary of signs signs = { "30": { "label": "30_k...
from flask import Flask from flask.globals import request app = Flask(__name__) productList = [ {'id': 1, 'name': 'IPhone X', 'price': 10500000}, {'id': 2, 'name': 'IPhone 11', 'price': 11500000}, {'id': 3, 'name': 'IPhone 12', 'price': 12500000}, ] @app.route('/') def index(): html = '<ul>' for ...
def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes def pfactorize(a,primes,b,pfactors = []): if a==1: return pfactors if a==2: pf...
# \r sirve para eliminar lo anterior escrito print("Hola \r mundo") # \n sirve para generar un salto de linea print("Hola \n mundo") # \t sirve para una tabulacion print("\tHola mundo") # \\ si queremos usar el caracter \ o algun caracter especial print("Hola \\ mundo")
class Participants(): ## Constants used for validation MINIMUM_NAME_LENGTH = 3 # Used to validate team member's name MAXIMUM_NAME_LENGTH = 10 MINIMUM_HOUSEHOLD_SIZE = 2 MAXIMUM_HOUSEHOLD_SIZE = 5 ## Constructor for the set containing participant's names. # @param the_participants...
wagons_n = int(input()) train = [0] * wagons_n while True: command = input() if command == 'End': break tokens = command.split(" ") instructions = tokens[0] if instructions == 'add': count = int(tokens[1]) train[-1] += count elif instructions == 'insert': index...
''' We do not need it in Python, but... ''' class Stack: def __init__(self): self._data = [] self._top = 0 def __len__(self): return self._top def __repr__(self): return f"<Stack: [{', '.join([str(i) for i in self._data[:self._top]])}]>" def push(self, item): ...
''' Created on 25 Nov 2020 @author: aki ''' """ import tkinter as tk root = tk.Tk() root.title("image demonstration") #iconbitmap only works with black and white images # root.iconbitmap("/home/aki/Downloads/icons/antenna.xbm") img = tk.PhotoImage(file='/home/aki/Downloads/icons/antenna.png') root.tk.call('wm', 'ic...
def fibTab(n): table=[0]*(n+1) table[1]=1 i,j,k=0,1,2 while (k<=n+1): if k==n+1: table[j]+=table[i] break table[j]+=table[i] table[k]+=table[i] i+=1;j+=1;k+=1 return table[n] print(fibTab(50)) # Time and space Complexity O(n)
"""DXF Ruler Generator. This module generates DXF files for laser cutting and engraving custom sized rulers, which can be easily manufactured at the nearest FabLab. Example ------- Generate a 7cm ruler: $ python -m dxf_ruler_generator 7 This will create a 'ruler_7cm.dxf' on the current working directory. """ i...
class MyClass (object): # class MyClass and, by default, inherits from object pass class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return 'Person: {} - Age: {}'.format(self.name, self.age) class PF(Person): def __init__(self, ...
#!/usr/bin/env python import datetime import pandas as pd from tabulate import tabulate class TravelRoute: def __init__(self, destination, dangerous, urgency, dimension, weight): self.destination = destination self.dangerous = dangerous self.urgency = urgency self.dimension = float...
import re from collections import Counter from aoc_utils import aoc_utils from tests import cases def find_all_coordinates(x1, y1, x2, y2, part_one=False): points = [] dx = x1 - x2 dy = y1 - y2 # Like 2,2 -> 2,1 if dx == 0: for y in range(min([y2, y1]), max([y2, y1]) + 1): ...
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
140