text
stringlengths
5
121k
class Solution(object): def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ res, d = [], {} begin, end = 0, 0 for item in p: d[item] = d.get(item, 0) + 1 counter = len(d) while end < len(s): ...
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: List[int] """ xorian = nums[0] for item in nums[1:]: xorian ^= item bit_set = 1 while xorian & bit_set == 0: bit_set <<= 1...
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ rows = len(matrix) cols = len(matrix[0]) result = [] top = 0 bottom = rows-1 left =0 right = cols-1 ...
import argparse from ping import PingUtil def hello(): argParser = argparse.ArgumentParser() argParser.add_argument('-p', '--ping', nargs= "+", help="Ping IP Addresses.") argParser.add_argument('-t', '--telnet', nargs="+", help="Telnet command") args = argParser.parse_args() para...
""" Python Is Easy course @Pirple.com Homework Assignment #1: Variables Patrick Kalkman / patrick@simpletechture.nl Details: What's your favorite song? Think of all the attributes that you could use to describe that song. That is: all of it's details or "meta-data". These are attributes like "Artist", "Year Released"...
import matplotlib.pyplot as plt import random cities = [] N2 = 10 for i in range(N2): for j in range(N2): c = [i/float(N2-1), j/float(N2-1)] cities.append(c) N = len(cities) print(N) print(cities) def dist (x, y): return ( (x[0]-y[0])**2 + (x[1]-y[1])**2 ) ** 0.5 def globaldist (chromosome): acum =...
import pandas as pd iris = pd.read_csv('./Iris_Data.csv', index_col =0) print('The iris species include: \n {}'.format(iris.head())) print('The sepal_length of Iris-setosa is: {}'.format(iris['sepal_length'][1])) print('The sepal_lengths of the first five species of iris flowers are: \n{}'. format(iris.iloc[...
""" Kalman Filter """ import numpy as np __author__ = "Olve Drageset, Andre Gramlich" def kalman_filter(mu_t_minus_1, sigma_t_minus_1, u_t, z_t): """ Given as input a previous believed pose, previous covariance matrix, control input, and sensor correction on pose, determine a new believed pose an...
""" Ejercicio 2 =========== """ try: n1 = float(input('Enter the first number: ')) n2 = float(input('Enter the second number: ')) op = str(input('Enter the operator (+,-,*,/): ')) if op == '+': res = n1 + n2 elif op == '-': res = n1 - n2 elif op == '*': res = n1 * n2 ...
import math def is_prime(n): if n < 2: return False elif n < 4: return True else: for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True T = int(input().strip()) for t in range(T): n = int(input().strip()) pri...
import sys def getMoneySpent(keyboards, drives, s): max_price = 0 for k in keyboards: for d in drives: if k + d > max_price and k + d <= s: max_price = k + d return max_price if max_price > 0 else -1 s, n, m = input().strip().split(' ') s, n, m = [int(s), int(n...
import sys def solve(year): days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if year == 1918: days_in_months[1] = 15 elif year >= 1700 and year <= 1917: if year % 4 == 0: days_in_months[1] = 29 else: if year % 400 == 0 or (year % 4 == 0 and ...
""" Given a list of strings words, concatenate the strings in camel case format. Example 1 Input words = ["java", "beans"] Output "javaBeans" Example 2 Input words = ["Go", "nasa"] Output "goNasa" """ class Solution: def solve(self, words): s = '' l=[] for i in range(len(word...
""" Unique Occurrences Given a list of integers nums, return true if the number of occurrences of every value in the array is unique, otherwise return false. Note: Numbers can be negative. Example 1 Input nums = [5, 3, 1, 8, 3, 1, 1, 8, 8, 8] Output True Explanation Yes, there is 1 occurrence of 5, 2 occur...
x = 3 x = x * x print (x) y = float (raw_input ('Pick a number: ')) print (y * y)
""" Module Description: 19-删除链表的倒数第 N 个结点 Solution: Date: 2021-03-11 13:39:13 Author: Wang P Problem:# 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 # # 进阶:你能尝试使用一趟扫描实现吗? # 示例 1: # 输入:head = [1,2,3,4,5], n = 2 # 输出:[1,2,3,5] # # 示例 2: # 输入:head = [1], n = 1 ...
""" Module Description: 92-反转链表 II Solution: Date: 2021-03-15 19:06:58 Author: Wang P Problem:# 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 # # 说明: # 1 ≤ m ≤ n ≤ 链表长度。 # # 示例: # # 输入: 1->2->3->4->5->NULL, m = 2, n = 4 # 输出: 1->4->3->2->5->NULL # Related Topi...
""" Module Description: 二分查找算法 Problem: Solution: Date: 2020/1/20 Author: Wang P """ def binary_search(arr, target): n = len(arr) left = 0 right = n - 1 while left <= right: mid = (left + right) // 2 if arr[mid] < target: left = mid + 1 elif arr[mid] > target: ...
''' PICASSO PROJECT --------------- Your job is to make a cool picture. You must use multiple colors. You must have a coherent picture. No abstract art with random shapes. You must use multiple types of graphic functions (e.g. circles, rectangles, lines, etc.) Somewhere you must include a WHILE or FOR loop to create a ...
np.random.seed(0) X = 2.5 * np.random.randn(100) + 1.5 res = 0.5 * np.random.randn(100) y = 2 + 0.3 * X + res df = pd.DataFrame( {'X': X, 'y': y} ) xmean = np.mean(X) ymean = np.mean(y) df['xycov'] = (df['X'] - xmean) * (df['y'] - ymean) df['xvar'] = (df['X'] - xmean)**2 ...
import pandas as pd def quarter_volume(): data=pd.read_csv('apple.csv',header=0,parse_dates=['Date'],index_col=[0]) data_3m=data.resample('Q-DEC').sum() second_volume=data_3m.sort_values(by='Volume')['Volume'][-2] return second_volume print(quarter_volume)
import random def ask_user_and_check_number(): user_number=int(input("Enter a number between 0 and 9: ")) if user_number in magic_numbers: print("You got the number correct!!") if user_number not in magic_numbers: print("You totally got the number WRONG!") magic_numbers = [random.randint(0...
""" Description: Ancient implementation of Caesar/ROTxx/Vigenere ciphers. Author: DrunkenAlcoholic Date: June 2019 """ sAlphabet = 'aBcDeFgHiJkLmNoPqRsTuVwXyZAbCdEfGhIjKlMnOpQrStUvWxYz0123456789' iAlphaBet = len(sAlphabet) def caesar(sSource, iShift, bDecrypt = False): sResult = '' for cChar in sSource: ...
ENGLISH = (0.0749, 0.0129, 0.0354, 0.0362, 0.1400, 0.0218, 0.0174, 0.0422, 0.0665, 0.0027, 0.0047, 0.0357, 0.0339, 0.0674, 0.0737, 0.0243, 0.0026, 0.0614, 0.0695, 0.0985, 0.0300, 0.0116, 0.0169, 0.0028, 0.0164, 0.0004) FRENCH = (0.0840, 0.0106, 0.0303, 0.0418, 0.1726, 0.0112, 0....
''' Created on Sep 1, 2016 @author: galeotti ''' def youngest(ages): if len(ages) == 0: return None min_age = None for name in ages.keys(): age = ages[name] if age < min_age: min_age = age return min_age def oldest(ages): if len(ages) == 0: return None...
def CoinFlipStreaks(): import random, sys trials = 100000 numberOfStreaks = 0 minStreak = 6 for experimentNumber in range(trials): flips = 100 flipList = [] for i in range(flips): if random.randint(0,1) == 0: flipList += 'H' ...
'''this program draws a five corner star''' import turtle wn = turtle.Screen() dstar = turtle.Turtle dstar.pencolor('blue') angle = 40 for i in range(5): dstar.right(angle) dstar.forward(100)
str1 = 'this is a sample string.' print('original string>>', str1,'\n\n') print('atfer usig capitalising>>',str1.capitalize()) print('using count method for "is" in the given string>>', str1.count('is')) print('\n\n') print('looking fo specfic string literal with spaces>>', str1.count(' is '),'\n') print('using f...
""" Created on Mon Jan 28 16:46:57 2019 @author: Kanel.Soeng """ my_dict = { "key1":"value1", "key2": "value2" } my_dict my_dict["key1"] fruits = {"Apple": 3, "Banna": 1.75, "Cherry": 2} fruits fruits["Cherry"] new_dict = { "k1":147, "k2":[15, 25, 35], ...
""" Created on Wed Mar 13 07:03:54 2019 @author: Kanel.Soeng """ True true False false type(True) 10 > 9 3 == 2 7 < 5 l = [1,2,3,4, -1,-3] for i in l: if -3 >= 1 : print(i) else: print("none") number = 23 guess = int(input('Enter an integer : ')) if guess == number: prin...
""" I won the grant for being the most awesome. This is how my reward is calculated. My earnings start at $1 and can be doubled or tripled every month. Doubling the amount can be applied every month and tripling the amount can be applied every other month. Write a program to maximize payments given the number of month...
def greet(*names): for name in names: print("Hello", name) greet("monica","leon","sheema")
class Add: num_1 = 4 num_2 = 5 def __init__(self,num_3): self.num_3 = num_3 def num(self): return self.num_1 + self.num_2 + self.num_3 add = Add(6) print(add.num())
my_list = [1,2,3,4,5,6,7,8,9,10] print(my_list[::-1]) my_tuple = (1,2,3,4,5,6,7,8,9,10) print(my_tuple[::-1]) my_str = "1,2,3,4,5,6,7,8,9,01" print(my_str[::-1])
from tkinter import Tk,Button,Label,StringVar,Entry,DoubleVar window =Tk() window.title('Character&word counter') window.configure(background='red') ...
even = [2, 4, 6, 8] odd = [1, 3, 5, 7, 9] numbers = [even, odd] for number_list in numbers: print(number_list) for value in number_list: print(value)
swears = open("swears.csv", "r") key = swears.read() split = key.split(",") message = 'poop' def bad_word_test(): for word in split: if message == word: return True return False if bad_word_test(): print('bad word') else: print("child of god")
num=int(input("Enter a number : ")) i=1 print("The factors of ",num,"are :-") while i<=num: if num%i==0: print(i) i+=1
str=input("Enter a string : ") for x in range(len(str)): print(str[x]) for element in str: print(element)
li=[] for i in range(0,6): val=input("enter the elements") li.append(val) if 12 in li: print("it is present") else: print("it is not present")
""" Name: sumList.py Description: sums all the digits in the list Version: 1.0.0 Python: 3.3.5 """ __author__ = "Spencer Dockham" __date__ = "10/29/2014" def checkString(string): for ch in string: if ch not in numbet: return False return True def addString(string): total = 0 stri...
def board_is_present(board): """validate board exists""" if board: return True else: return False def validate_length(board): """validate length of the board""" if len(board) is 9: return True else: return False def validate_characters(board): """validate player and server characters""" allowed_cha...
message = "Eric" print("Hello " + message + ", would you like to learn some Python today?" ) print(message.title()) print(message.upper()) print(message.lower()) message = "Albert Einstein once said, 'A person who never made a mistake never tried anything new.'" print(message) famous_person = "Albert Einstein" famou...
males = float(input('How many men are in your class?')) females = float(input('How many women are in your class?')) totalclass = males + females percentm = males / totalclass percentf = 1-percentm print(format(percentm, '.1%'), "of students are male in your class, and", format(percentf, '.1%'), "are female.")
celsius = float(input('Please enter todays temperature (in celsius): ')) fahr = 9 / 5 * celsius + 32 print("Today's temperature in degrees fahrenheit is", format(fahr, '.0f'), 'degrees.')
print("START*******") import nltk import random nltk.download('book') from nltk.book import * from nltk import word_tokenize,sent_tokenize debug = False if debug: print ("Getting information from file madlib_test.txt...\n") fname = "madlibtest2.txt" tok_lst = text2[:151] print (type(tok_lst)) ta...
from printdescribe import print2 class SalaryError(ValueError): pass class HourError(ValueError): _message = "Hours out of range!" def __init__(self): ValueError.__init__(self) def __str__(self): print(HourError._message) return HourError._message class Worker: ...
from collections import Counter import matplotlib.pyplot as plt from sklearn.feature_extraction.text import CountVectorizer from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer import string def print2(*args): """ Function that print descriptive s...
from printdescribe import print2 class Patients: def __init__(self, name, id, gender): self.name = name self.id = id self.gender = gender def __eq__(self, other): return self.name == other.name and self.id == other.id\ and type(self) == type(other) ...
import json def print2(*args): for arg in args: print(arg, end='\n\n') params = {"sep":"\n\n", "end":"\n\n"} with open('myfile.json', 'r') as json_file: jsonData = json.load(json_file) type(jsonData) for key, value in jsonData.items(): print(f'{key} : {value}', **params) w...
import os from functools import wraps def print2(*args): for arg in args: print(arg, end='\n\n') sp = {"sep": "\n\n", "end": "\n\n"} def mycounter(func): """ """ @wraps(func) def mywrapper(*args, **kwargs): result = func(*args, **kwargs) mywrapper.count += 1 ...
import os from sqlalchemy import create_engine, MetaData, Table, select print(engine.table_names()) """ survey = Table('Survey', metadata, autoload=True, autoload_with=engine) ssmt = select([survey]) print(ssmt) results = connection.execute(ssmt).fetchall() print(results) print(results[0]) print(results[...
from pandas import DataFrame import re, string from datetime import datetime eassy = """This is the begining of time. But with all good and noble intention comes failure, only work hard as you and others can and expect the best. Be careful while going slowly on a journey of life.""" ...
import matplotlib.pyplot as plt import pandas as pd weather2 = weather1.reindex(year) print(weather2) weather3 = weather1.reindex(year).ffill() print(weather3) common_names = names_1981.reindex(names_1881.index) print(common_names.shape) common_names = common_names.dropna() print(common_names.shape) ...
import numpy as np from sympy import * x = symbols('x') expr = 2 * x**3 - 2 * x - 5 print("Given expression : {}".format(expr)) expr_diff = expr.diff(x) print("Derivative of expression with respect to x : {}".format(expr_diff.doit())) f = lambdify(x,expr,'numpy') f_diff = lambdify(x,expr_diff,'numpy') ...
birthday = input('What\'s your birthday?') age = 2021 - int(birthday) -1 print(f'your age is {age}')
complex print(bin(7)) print(bin(5)) print(int('0b101',2))
import csv import json from os import path print("This script is designed to create a list of dictionaries from a CSV File.") print("This script assumes you can meet the following requirements to run:") print(" 1) The file you are working with has clearly defined headers.") print(" 2) You can review the headers ('.h...
__date__ = '2019/4/21 0021 21:21' __author__ = 'Lee7' class Goods: def __init__(self): self.original_price = 100 self.discount = 0.8 @property def price(self): new_price = self.original_price * self.discount return new_price ...
__date__ = ' 2019/5/7 12:37' __author__ = 'lee7goal' some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] flattened = [x.__float__() for tup in some_tuples for x in tup] print(flattened) flattened2 = [[x for x in tup] for tup in some_tuples] print(tuple(flattened2))
import paths import parts import maze import random import os import time clear = lambda: os.system("cls") def hacking(): num1 = random.randint(1, 100) num2 = random.randint(1, 5) * num1 sum = num1 + num2 multiple = num2 // num1 maze.rprint("It seems that the door got stuck when Heavy cra...
' file traverse then rename the date from MM-DD-YYYY to MM-DD-YYYY ' __author__ = 'Bob' import os, re path = os.path.join(os.path.abspath('.'), 'renameDatesDatas') filePaths = os.listdir(path) def findAmericanDate(str): regex = r''' ((0\d)|(1[012])) #MM - ...
' display inventory ' __author__ = 'Bob Bao' def displayInventory(dic): print('Inventory:') totalNum = 0 for k, v in dic.items(): print(k,' ',v) totalNum += v print('Total number of items: ', totalNum) def addToInventory(inventory, addedItems): for k1, v1 in addedItems.items():...
"""Utilities for working with files (e.g. creation of dated folders) """ import os from datetime import datetime class FileUtils(object): @staticmethod def ensure_dir(dir_path: str) -> None: """Create directory (including parent directories) if it does not exist. :param dir_path: dir...
import csv import matplotlib.pyplot as plt import numpy as np from collections import Counter MY_FILE = "sample_sfpd_incident_all.csv" def parse(raw_file, delimiter): """Parses a raw CSV file to a JSON-like object.""" opened_file = open(raw_file) csv_data = csv.reader(opened_file,delimiter=delimiter) pa...
class A: def m1(self): print("method 1") def m2(self): print("method 2") class B(A): def m1(self): print("called from B") def m3(self): print("method 3") def m4(self): return "method 4" class C(B): def __init__(self,a,b): print("...
from random import choice def primeRange(mini, maxi): l=[True for i in range(maxi)] l[0], l[1]=False, False for a in range (2,int(maxi/2)+1): if l[a]: for i in range (a*a,maxi,a): if l[i]==1: l[i]=False final=[] ...
import numpy as np class Controller(): def __init__(self): self.gain = 2.0 pass def angle_control_commands(self, dist, angle): omega = 0. ...
def maximum(num1, num2): if num1 >= num2: return num1 else: return num2 n1 = int(input("Enter the number:")) n2 = int(input("Enter the number:")) print(maximum(n1,n2))
import requests from twilio.rest import Client STOCK_NAME = "TSLA" COMPANY_NAME = "Tesla Inc" STOCK_ENDPOINT = "https://www.alphavantage.co/query" NEWS_ENDPOINT = "https://newsapi.org/v2/everything" STOCK_API_KEY = "STOCK_API_KEY" NEWS_API_KEY = "NEWS_API_KEY" account_sid = "account_sid" auth_token = "auth_token" ...
def findRestaurant( list1, list2): for item in list1: if item in list2: return item r=findRestaurant(["Shogun","Tapioca Express","Burger King","KFC"],["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]) print (r) def sebsequence(a,b): sum=0 j...
def isPerfectSquare(num): """ :type num: int :rtype: bool """ if num == 1: return True for i in range(num): if i * i == num: return True return False r1=isPerfectSquare(16) r2=isPerfectSquare(1) r3=isPerfectSquare(15) print (r1) print (r2) print (r3)
import unittest class TestCount: def __init__(self,a,b): self.a=a self.b=b def doadd(self): return self.a + self.b class TestUt(unittest.TestCase): def setUp(self): print ("before...") def testdoadd(self): i=TestCount(1,2) print (i) self.ass...
import unittest class cal(): def __init__(self, a, b): self.a = int(a) self.b = int(b) def caladd(self): return self.a + self.b def caldiv(self): return (self.a)/(self.b) class test_unit(unittest.TestCase): def setUp(self): print("before everyrun") def tea...
def restr(str): r=str.split(" ") rr=[i[::-1] for i in r] return ' '.join(rr) r=restr("hi hello world") print (r) def all(str): return str[::-1] r=all("hi hello world") print (r) """Input : str = "geeks quiz practice code" Output : str = "code practice quiz geeks""" def a1(str): a=str.split(" ...
def computepay(h, r): if h <= 40: return h * r else: return (40 * r) + ((h - 40) * r * 1.5) hrs = float(input("Enter Hours:")) rate = float(input("Enter Rate:")) print(computepay(hrs, rate))
import math import random def primality1(n): """give a positive integer n, testing primality. It proclaim n a prime as soon as it have rejected all candidate up to sqrt(n). """ for i in xrange(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def primality2(n):...
""" 约定:图的存储方法 这里的图采用邻接表的方法存储。有两种可行的方式: 1. 边无权重: 采用集合存储该点可到达的点集 2. 边有权重: 采用字典(点:边的权重)存储该点可到达的点集 例: V = a, b, c, d, e, f, g, h = range(8) E = [ set([b, c, f]), set([e]), set([d]), set([a, h]), set([f, g, h]), set([b, g]), set(), set([g]) ] G = (V, E) """ from collections import deque inf = float("inf") def bfs...
with open("input.txt", "r") as fd: inputlines = fd.read().splitlines() def splitr(route): jj = route.split(")") main = jj[0] ob = jj[1] return main, ob all_dict = {} for route in inputlines: main, ob = splitr(route) if ob not in all_dict: all_dict[ob] = main dp = {} def count(ob...
import pandas as pd movie_file = "Resources/movie_scores.csv" movie_file_pd = pd.read_csv(movie_file) movie_file_pd.head() movie_file_pd.columns imdb_table = movie_file_pd[["FILM", "IMDB", "IMDB_norm", "IMDB_norm_round", "IMDB_user_vote_count"]] imdb_table.head...
"""Send an email message from the user's account. """ from email.mime.text import MIMEText import httplib2 import base64 from apiclient import discovery import credentials def SendMessage(service, user_id, message): """Send an email message. Args: service: Authorized Gmail API service instance. us...
import re class Util(): def __init__(self): pass def detectarDataExpressaoRegular(texto): date_pattern = re.compile(''' ([12][0-9]|3[0-1]|0?[1-9]) # to detect days from 1 to 31 ([./-]) # to detect different separations (1[0-2]|...
import re def date_is_valid(day: int, month: int, year: int) -> bool: return (month not in (2, 4, 6, 9, 11) or day < 31 and month in (4, 6, 9, 11) or month == 2 and day == 29 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) or month == 2 and d...
def calculate(a,c,b=0): if c=='t': area=0.5*a*b elif c=='c': area=3.14*a*a elif c=='s': area=a*a elif c=='r': area=a*b return area if __name__ == '__main__': print("if you want to calculate area of shape input char from below") ...
try: jumlah = int(input("Jumlah : ")) data = [] for i in range(jumlah): data.append(int(input("Data ke {} : ".format(i+1)))) data.sort(reverse=True) print(data) except: print("Input tidak Valid")
try: jumlah = int(input("Jumlah : ")) data = [] for i in range(jumlah): data.append(input("Data ke {} : ".format(i+1))) data.sort() for i in data: print("[{}] {} ({} karakter)".format(data.index(i),i,len(i))) except: print("Input tidak Valid")
j=1 while (j<=10): i = 1 print("Printing the following table of ", j) while(i<=10): print( j, "times", i, j*i) i=i+1 j =j+1
import tictactoe, ankur import sys def unpack(b): l = [1,2,3,4,5,6,7,8,9] for elem in b['x']: l.remove(elem) for elem in b['o']: l.remove(elem) return {' ':l,'x':b['x'],'o':b['o']} def printboard(board): nboard = unpack(board) for j in range(3): for i in range(1+3*j,4+3*j): ...
class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ def middleNode(head): slow, fast = head, head while fast is not None and fast.next is not None: s...
from typing import List def exist(board: List[List[str]], word: str) -> bool: if not board or not board[0]: return False directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def check(i, j, k): if word[k] != board[i][j]: return False if k == len(word) - 1: return True visited.add((i, ...
class ParkingSystem: def __init__(self, big: int, medium: int, small: int): self.spaces = [big, medium, small] def addCar(self, carType: int) -> bool: if self.spaces[carType - 1]: self.spaces[carType - 1] -= 1 return True return False if __name__ == '__ma...
x=int(input()) if(x==1): print("1") elif(x>1 and x<4): print("NO SOLUTION") else: for i in range(2,x+1,2): print(i, end=" ") for i in range(1,x+1,2): print(i, end=" ")
def f(n): if n == 0: return 1 else: index = n - 1 sum = 1 while (index >= 0): sum = sum + f(index) print("index = " , sum) index = index - 1 return sum print(f(30))
def fact(n): if n==1: return 1 return n*fact(n-1) print(fact(1)) print(fact(5)) print(fact(100))
import pdb def foo(s): n = int(s) pdb.set_trace() return 10/n def main(): foo('0') main()
class Cupcake: """A cupcake.""" cache = {} def __init__(self, name, flavor, price): self.name = name self.flavor = flavor self.price = price self.qty = 0 self.cache[name] = self def add_stock(self, amount): self.qty = ( self.qty + ...
"""Usage: led.py [-h] pin=PIN Demonstarte a blining LED on given PIN Arguments: PIN The PIN number [default: 3]. Options: -h --help """ from docopt import docopt import time import grovepi import sys class LED(object): def __init__(self, pin=3): """ Connect the LED to a digital port. 3...
def my_square(x): """takes a value and returns the square of it by using ** """ return(x ** 2) def my_square2(y): """takes a value and returns the square of it by using ** """ return(y ** 2) print(my_square(5)) print(my_square2(6))
import numpy as np def read_strings(): filepath = "Day2P1.txt" stringList = [] with open(filepath) as fp: for line in fp: stringList.append(line) return stringList def frequency_count(text): elem, count = np.unique(tuple(text), return_counts=True) print(count) ...
def rescaling(results, mean, std): """ Scale back the results that have previously been standardized. :param results: results of shape (None, 2) :param mean: vector of mean values (one per initial feature) :param std: vector of std values (one per initial feature) :return: re...