text
stringlengths
37
1.41M
a=int(input("Enter number: ")) z="" for x in range(a+1): for y in range(x+1): z=z+str(object=y) print (z) z=""
''' Summary: This program is mainly for parsing the url/html and get its content(title,meta,h1) Author: Srivatsan Ananthakrishnan Reference links: http://www.pythonforbeginners.com/python-on-the-web/web-scraping-with-beautifulsoup/ https://www.crummy.com/software/BeautifulSoup/bs4/doc/ ''' import...
""" Test the parse_env module. """ import unittest from .. import parse_env class ParseEnvTest(unittest.TestCase): """Test the parse_env functions.""" def test_env_as_int__not_set(self) -> None: """env value not set""" self.assertEqual( -10, parse_env.env_as_int({}, ...
se1=input("Enter the first sequence::") se2=input("Enter the second sequence::") seq1=list(se1) seq2=list(se2) def find_identity(a,b): gap(a,b) print(a) print(b) score=0 length=len(a) total_elements=len(a)*len(b) for i in range(0,length): for j in range(0,length): ...
import operator def read_until_number(prompt): original = prompt while True: try: return int(input(prompt)) except Exception: prompt = "Incorrect number. please " + original pass def read_until_operation(prompt): original = prompt whil...
# executemany() method # import the sqlite3 library import sqlite3 # create a new database it the database doesn't aleady exist with sqlite3.connect("new.db") as conn: # get the cursor object used to execute SQL commands c = conn.cursor() c.execute("SELECT city, state, population from population") ...
from math import factorial n = int(input("Digite um número inteiro para cálculo do fatorial: ")) f = factorial(n) print("O fatorial de",n,"é",f)
n = 10 while n > 0: lista = [n] n = n + 10 lista.append(n) print(lista) tam = len(lista) - 1 n = int(input("Digite 0 para decrescentar a lista:")) while tam >= 0: print(lista[tam], end=", ") tam = tam - 1
"""Generate Markov text from text files.""" from random import choice import sys def open_and_read_file(*file_paths): """Take file path as string; return text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ raw_text = "" ...
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): if new_val is None: return node = None ...
# Prints helloworld def printHelloWorld(): print "Hello World" def printSum(a,b): return (a+b) def main(): printHelloWorld() x = printSum(3,5) print x y = printSum(4,9) print y if __name__ == '__main__': main()
""" CTEC 121 <your name> <assignment/lab name> <assignment/lab description """ """ IPO template Input(s): list/description Process: description of what function does Output: return value and description """ def main(): # section 1 ''' # define a string myStr = "Hello World" print() print...
# -*- coding: utf-8 -*- count = input() # 몇번 정수 입력 할것인지 ? inputData=[] # for data in range(0,count): # count만큼 반복할 것. isHoemoonin = 1 scanData = input() inputData.insert(data,scanData) for scanData in inputData: for notation in range(2,65): s=[] a=scanData while a > 0: ...
total = input("How much was the bill? ") total = float(total) service = input("How was the service?: (Good, Fair, or Bad) ") if service == "Good": tip = total * 0.20 if service == "Fair": tip = total * 0.15 if service == "Bad": tip = total * 0.10 totalBill = ("Your total including tip comes to: ") pri...
name = input("What is your name? ") print("Hello,".upper(),name.upper()) total = len(name) print("Your name has".upper(), total, "letters in it!".upper())
nums = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] new_nums = list(filter(lambda x: x > 0, nums)) print("Positive numbers in the list: ",new_nums)
import random import string users = [] #Random string generator def randomString(stringLength=10): """Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) #Email verifyer def email_verify(email): if '@' and '....
''' for i in range (5): word=(input('введите слово: ')) a=len(word) print (a) ''' ''' kol=int(input('kolichestvo')) for i in range (kol): num=int(input('vvedite chislo: ')) if num>0: print('bolshe') elif num<0: print('menshe') else: print (0) ''...
def temp(celsius): msg1 = " degree Celsius are " msg2 = " degrees Fahrenheit." result = (celsius * 9/5) +32 return str(celsius) + msg1 + str(result) + msg2 temp_in_celc = input("Enter a temperature in degrees Celsius: ") Fahrenheit_result = temp(float(temp_in_celc)) print(Fahrenheit_re...
# Si scriva un programma che calcoli il volume # di un cubo o di una sfera in base ad una # scelta effettuata dall'utente. Se l'utente sceglie di # calcolare il volume di un cubo, il programma # chiederà l'input del relativo lato, # altrimenti chiederà il raggio della sfera. import math print( "Calcolo del volume di ...
from typing import Generator from bartpy.bartpy.tree import Tree class Initializer(object): """ The abstract interface for the tree initializers. Initializers are responsible for setting the starting values of the model, in particular: - structure of decision and leaf nodes - variables and v...
# coding=utf-8 import matplotlib.pyplot as plt x_value = list(range(0, 1001)) y_value = [x**3 for x in x_value] plt.plot(x_value, y_value, linewidth=5) # 设置图表的标题 plt.title('Test1', fontsize=20) # 设置x轴的参数名称 plt.xlabel('value', fontsize=14) # 设置y轴的参数名称 plt.ylabel('Cube of Value', fontsize=14) # 设置刻度的大小 plt.show()
#coding=utf-8 class A: #类的变量,可以通过类访问 num=1 a=A() b=A() print a.num a.num=2 print a.num print b.num A.num=5 print a.num print b.num a.age=1 print a.age print '*'*50 #构造函数 class A: def __init__(self): #这个num是实例化才有 self.num=1 a=A() print a.num help(classmethod)
from PIL import Image import pytesseract from difflib import SequenceMatcher import PyPDF2 from OCR import OCR class PyTess(OCR): """ This class is for the use of scanned documents. """ def __init__(self,url): """ The constructor for PyTess class. Parameters: url (st...
""" All sorts of bandit problem environments go here. """ import numpy as np from Ranger import Range from ai.environments import MDP, Domain class Bandit(MDP): """ The simplest multi-armed bandit problem. """ def __init__(self, n_arms=2, distributions=None): super().__init__(states=None, ac...
import unittest def fib(n): #Error handle if n < 0: print("Please Enter a correct input") #base case elif n == 1: return 0 #base cases elif n == 1 or n == 2: return 1 #recursive return else: return (fib(n-1)+fib(n-2)) #Simple factorial ...
from datetime import datetime def main2(): monthsnobi = {"Enero": 31, "Febrero": 28, "Marzo": 31, "Abril": 30, "Mayo": 31, "Junio": 30, "Julio": 31, "Agosto": 31, "Septiembre": 30, "Octubre": 31, "Noviembre": 30, "Diciembre": 31} monthssibi = {"Enero": 31, "Febrero": 29, "Marzo": 31, "Abril...
frase_del_usuario = input("Dime una frase: ") vocales = ["A", "a", "E", "e", "I", "i", "O", "o", "U", "u"] numero_aparicion = 1 for letra in frase_del_usuario: if letra in vocales: frase_del_usuario = frase_del_usuario.replace(letra, str(numero_aparicion), 1) numero_aparicion += 1 print...
clase = "simon perro" respuesta = input("Darwin es un sendo zamuro?") if respuesta == "si": print("Zenda Rata") else: respuesta == "no" print("Claro el nunca haria tal cosa")
def rayitas_de_una_string(string): string_rayitas = "" for letra in string: string_rayitas += "-" return string_rayitas frase_usuario = input("Dime una frase: ") print(rayitas_de_una_string(frase_usuario))
def FindIntersection(strArr): matches = [] for number in strArr[0]: if number.isdigit(): if number not in matches: for number2 in strArr[1]: if number2.isdigit() and number2 == number: matches.append(number) # code goes here ...
lista_numeros = [] respuesta_usuario = "" print("Escribir -Finalizar- para detener el programa") while not respuesta_usuario == "Finalizar": respuesta_usuario = (input("Dime un número")) if not respuesta_usuario == "Finalizar": lista_numeros.append(int(respuesta_usuario)) print("Númer...
import os import csv import numpy as np csvpath = os.path.join('Resources', 'budget_data.csv') dates = [] total = [] list_of_changes = [] initial_change = [0] with open(csvpath, newline= '') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') next(csv_reader) for row in csv_reader: dates....
import psycopg2 #function to create table def create_table(): #Step1: Connecting to Database conn=psycopg2.connect("dbname='<database_name>' user='<user_name>' password=<> host=<> port=<>") #Step2: Create cursor object to access the rows in database cur=conn.cursor() #Step3: SQL Query cur.execu...
#################################### # 58.1 Списковое включение cubes = [i**3 for i in range(5)] print(cubes) #################################### #################################### # 58.2 Списковое включение evens = [i**2 for i in range(10) if i**2 % 2 == 0] print(evens) #################################### ########...
#################################### # 36.1 Комментарии x = 365 y = 7 # this is a comment print(x % y) # find the remainder # print (x // y) # another comment #################################### #################################### # 36.2 Строки документации def shout(word): """ Print a word with an exclam...
#################################### # 21.1 Инструкции else x = 4 if x == 5: print("Yes") else: print("No") #################################### #################################### # 21.2 Инструкции else num = 3 if num == 1: print("One") else: if num == 2: print("Two") else: if num == 3: pr...
######################## # Решение задачи 1.1 'Ваша первая программа': print('Python is fun') ######################## ######################## # Решение задачи 3.2 'Заморозка Мозга!': print((23+27+18)*2) ######################## ######################## # Решение задачи 6.2 'Учебники для Учеников': print(76 % ((18+1...
######################## # Решение задачи 65.3 'Лямбда-функции': x = int(input()) y = (lambda z: z**3)(x) print(y) ######################## ######################## # Решение задачи 66.1 'Сколько им будет лет?': y = [1995, 2004, 2019, 1988, 1977, 1902] r = list(map(lambda x: 2050-x, y)) print(r) #######################...
#################################### # 45.1 Вызов исключений print(1) raise ValueError print(2) #################################### #################################### # 45.2 Вызов исключений name = "123" raise NameError("Invalid name!") #################################### #################################### # 45.3...
class FontTypes: class Font: def __init__(self): self.default_lowercase = 'qwertyuiopasdfghjklzxcvbnm1234567890' self.default_uppercase = self.default_lowercase.upper() self.lowercase_symbols = self.default_lowercase self.uppercase_symbols = self.default...
#dates are very compicated from datetime import datetime current_date=datetime.now() print("Today is "+str(current_date)) print("Day:"+str(current_date.day)) print("Month:"+str(current_date.month)) print("Year:"+str(current_date.year)) #how to write birthdays birthday=input("enter your birthday:dd/mm/yyyy ") b...
from Node import Node from symbolTable import TIPO_DATO as Type class Instruccion: '''This is an abstract class''' class Imprimir(Instruccion): ''' Esta clase representa la instrucción imprimir. La instrucción imprimir únicamente tiene como parámetro una cadena ''' def __init__(self...
import math def meters_to_feet(meters: float) -> float: """ This function takes a float representing a measurement in meters and returns the corresponding value converted to feet. The result is rounded to 2 decimal places. :param meters: A float representing a measurement in meters. :return: ...
#-*- coding: UTF-8 -*- from sys import argv #导入 script, filename = argv #解包 txt = open(filename) #打开指定文件 print "Here's you file %r:" % filename #打印引导句,引用一个变量 print txt.read() #读打开的文件并打印出来 print "Type the filename again:" # 打印引导句 file_again = raw_input(">") #输入文件名 txt_again = open(file_again) #打开输入的文件 print tx...
import urllib from bs4 import BeautifulSoup page = urllib.urlopen("http://www.wunderground.com/history/airport/EPWR/2016/03/14/DailyHistory.html").read() soup = BeautifulSoup(page, 'html.parser') TemperatureTable = soup.findAll('table', attrs={"class": "responsive airport-history-summary-table", "id": "historyTable"}...
''' DCP #14 This problem was asked by Google. The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. Hint: The basic equation of a circle is x2 + y2 = r2. Approach: Monte Carlo Algorithm ''' import random def approximate_pi(iterations=10000): total=0 inside=0 for i in...
''' DCP #9 This problem was asked by Airbnb. Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. Follow-up: Can yo...
def createGenerator(): mylist = range(5) for i in mylist : yield i*2 mygenerator = createGenerator() for i in mygenerator: print(i+3)
import sys import numpy as np import matplotlib.pyplot as plt from shapely.geometry import Point, Polygon def read_data(file): # Read the data for voters and districts # Step 1: Open the file with open(file) as f: contents = f.readlines() contents = [x.strip() for x in contents] # Step 2: G...
import time import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # Define GPIO to use on Pi GPIO_PIR = 7 GPIO.setup(GPIO_PIR, GPIO.IN) # Read output from PIR motion sensor # GPIO.setup(3, GPIO.OUT) #LED output pin print("Starting....") try: while True: if GPIO.input(GPIO_PIR) ...
# gabrielle french, gjfrench@bu.edu # this code changes numeric, non-binary data into nominal data infile = open('DisStudentGrade.csv','r') outfile = open('FinalStudentPer.csv','w') # change Medu from numeric to nominal for line in infile: if line[6] is 0: line[6] = "none" elif line[6] is ...
# -*- coding: utf-8 -*- import numpy as np class Sigmoid(object): def __init__(self): pass def forward(self, X): self.activation = 1 / (np.exp(-X) + 1) return self.activation def backward(self, err_in): return err_in * self.ac...
import numpy as np def zero_pad(X, pad): """ 对数据集X的所有图像四周用0进行填充,填充只针对每个图像的高度和宽度,如图1所示。 参数: X -- 为python numpy多维数组(m, n_H, n_W, n_C),用来表示一批图像,m:图像数量,n_H:图像高度,n_W:图像宽度,n_C:图像通道数量 pad -- 整数,表示在每个图像的四周垂直和水平维度填充增加的维度 返回: X_pad -- 填充后的批量图像多维数组(m, n_H + 2*pad, n_W + 2*pad, n_C) m:图...
# Riddle Python / Загадки на питоне. # # Answers / right / wrong right = 0 wrong = 0 # First riddle flag1 = 0 answer1 = 'утюг' riddle1 = print(('{0:*^30}'.format('ПЕРВАЯ ЗАГАДКА')), """\n В Полотняной стране По реке Простыне Плывет пароход То назад, то вперед, А за ним такая гладь — Ни морщинки не видать. """) while...
numbers = [1,2,3,4,5,6] numbers.sort() for num in numbers: if num % 2 == 0: print(num)
tall_list = input().split(',') new_tall = eval(input()) new_list = [] # 以上勿改 new_list.extend(tall_list) new_list = list(map(int, new_list)) new_list.append(new_tall) new_list.sort() # 以下勿改 for h in new_list: print(h, end=' ')
#!/usr/bin/env python3 # Author: Y_Sun_ys219@ic.ac.uk # Script: loops.py # Desc: for loop in python exercise # Arguments: o # Input:ipython3 loops.py # Output: printed result in python terminal # Date: Oct 2019 """for loop in python exercise""" # print number 1-5 for i in range(5): print(i) #print the elements in...
#!/usr/bin/env python3 # Author: Y_Sun ys219@ic.ac.uk # Script: lc1.py # Desc: practical # Arguments: 0 # Input:ipython3 lc1.py # Output: output list printed in python terminal # Date: Oct 2019 """python practical""" birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House...
def generate_vector_c(c,n): vector = [] for k in range(2*n+1): kth_value = min(k, 2*n-k, c) result = format(kth_value, "02d") print(result, end = " ") vector.append(kth_value) return vector def generate_matrix_n(n): matrix = [] for i in range(n+1): vector = ge...
#!/usr/bin/python3 def sanitize(time_string): if '-' in time_string: splitter = '-' elif ':' in time_string: splitter = ':' else: return(time_string) (mins, secs) = time_string.split(splitter) return (mins + '.' + secs) def open_and_split(file): try: with open(file) as my_file: data = my_file.readlin...
import random def choose_noccer(list): noccer_index=random.randint(0,len(list)-1) noccer=list[noccer_index] list.remove(noccer) return noccer,list #all_hours=['15:45', '15:00','14:00','13:00','12:00','11:00','10:00'] all_hours=['10:00', '11:00','12:00','13:00','14:00','15:00','15:45'] all_noccers=['Ramo...
import pandas as pd import numpy as np # instead of 'how' for dataframe,we use 'join' for series, inner -> intesection, outer -> union # concatenating along an axis arr = np.arange(12).reshape((3,4)) #print(arr) #print(np.concatenate([arr,arr],axis=1)) #axis=1 is along column, concatenated along the columns s1 = pd...
# Dealing with files in python import os import sys def file_wr(filename): if os.path.exists(filename): sys.stderr.write("File exists\n") sys.exit(2) f = open(filename,'w') f.write('aaaaaaaaaaaaaa\n') f.write('bbbbbbbbbbbbbb\n') f.write('cccccccccccccc\n') f.close() def file_r...
import pandas as pd import numpy as np # df1 = pd.DataFrame({'lkey':['a','d','b'], # 'data1':range(3)}) # df2 = pd.DataFrame({'rkey':['a','c','a','b','c','c','b'], # 'data2':range(7)}) # # print(pd.merge(df1,df2,left_on='lkey',right_on='rkey')) # how='inner' by default, gives in...
# def check_fn(): user_in = input("Enter yes/no ").strip() while user_in != 'YES': if user_in == 'YES': print('Accepted') continue elif user_in == 'yes': print(user_in.upper()) break else: print("invalid input.. pls enter a...
# Transpose a list of lists l = [int(x) for x in input().split(',')] ll = [l.append(list(x)) for x in input()] print(ll)
# set trace acts like a breakpoint. When the program hits the point, # where set_trace is called, it enters the debugger # for example import pdb def dict_wr1(filename,d1): f = open(filename,'w') pdb.set_trace() for (k,v) in d1.items(): f.write(str(k)+','+str(v)+'\n') f.close() dict_wr1()
import pandas as pd import numpy as np df1 = pd.DataFrame(np.arange(12).reshape(3,4), columns=list('abcd'), index=['tn','ka','kl']) print(df1) s1 =df1.loc['ka'] print(s1) print(df1-s1) # subtracting s1 to all rows print(df1+s1) # adding s1 to all rows f = lambda x:x.max() - x.m...
import pdb def f1(some_arg): some_other = some_arg + 1 print(some_other) myadd(some_arg, some_other) return f2(some_other) def f2(some_arg): some_other = some_arg + 1 some_other = 2 * some_other - 17 some_arg = 3 * (some_other + 12) myadd(some_arg, some_other) some_other = some_ot...
# dict to implement set functions # intersection, union, subtraction, symm-diff, issubset a = {'a':5, 't':3, 'c':4, 'e':7} b = {'a':3, 'l':9,'e':1, 'd':6} # print(set(a)) # print(set(b)) c,d = [],[] # ad = set(a.items()) # bd = set(b.items()) # print(ad) # print(bd) for (k,v) in a.items(): c.append((k,v)) #print...
# Keywords cannot be overwritten. # But builtins can be overwritten # __builtins__ is a namespace which has methods like map map = 8 #m = list(map(lambda x:x*2, [2,1,4])) n = list(__builtins__.map(lambda x:x*2, [2,1,4])) print(n) print(map) map = __builtins__.map m = list(map(lambda x:x*2, [2,1,4])) print(m)
# What if we want some attributes to be created before the creation of an instance? # this can be done in the constructor #? __init__() -> private, used before the creator of the object - not called by the user #? Called Magic Method because its called automatically class MagicMethods(object): def __init__(se...
#!/usr/bin/python3 def numeroPerfecto(num): '''Funcion que recibe como entrada n numeros enteros positivos, y por cada uno de ellos imprime sus divisores e indica si es perfecto o no. ''' suma = 0 for i in range(1, num): if num % i == 0: suma += i print("divisor=", ...
#!/usr/bin/python3 '''Programa que puede simular el funcionamiento de un display de siete segmentos. ''' numbers = { 1: [[" ", " ", "#"], [" ", " ", "#"], [" ", " ", "#"], [" ", " ", "#"], [" ", " ", "#"]], 2: [["#", "#", "#"], [" ", " ", "#"], ["#", "#", "#"], ...
# A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. # So the thing is if we read left to right as "asasa" AND right to left "asasa" = then we got the point....
#Problema 01 - Corrida de Fórmula 01 #Versão Original elaborada pelo professor Givanaldo Rocha #Desenvolver uma aplicação para simular a dinâmica de uma corrida de Fórmula 1. Serão #duas threads em que uma representa o carro de Felipe Massa e a outra representa o carro #de Lewis Hamilton. As threads possuem as seguinte...
Celsius = float(input()) print("This equal", ((Celsius * 9 / 5) + 32), "Fahrenheit degrees") print("This equal", (Celsius + 273.15), "Kelvin degrees")
import math a = int(input()) b = int(input()) print(a+b) print(a-b) print(b/a) print(a/b) print(a*b) math.log10(a) print(a*b)
print("Mass in grams:") mass = int(input()) print("Temperature in Celsius:") dtemp = int(input()) q = 4.186 * mass * dtemp print("The total energy in Joules: %f" %q)
loaves = int(input("Amount of loaves: ")) price = loaves*3.49 discount = price*0.6 total_price = price - discount print("Price of the bread", price) print("Value of discount:", discount) print("Total price:", total_price)
from math import pi s = float(input ()) print (str(s) + str(pi * s**2))
from math import radians, cos, sin, asin, sqrt print("Enter the latitude and longitude of two points on the Earth in degrees:") lt1 = float(input(" Latitude 1: ")) lt2 = float(input(" Latitude 2: ")) ln1 = float(input(" Longitude 1: ")) ln2 = float(input(" Longitude 2: ")) dln = ln2 - ln1 dlt = lt2 - lt1 ...
for s in range(int(input())): s = input() a = s.count("A") b = s.count("D") if a > b: print("Anton") else: print("Danik")
# Language: Python 3 # Run: python3 elgamal_ecc_6.py 9 201 # Parameter 1: <positive_integer_number> - Number of bits to generate the key # Parameter 2: <integer_number_to_encrypt> - Integer number to encrypt # importing libraries import sys, random # Inverse function - Returning 0 instead of raise an error. Removed g...
# utils.py # Math library # Author: Sébastien Combéfis # Version: February 8, 2018 import math def fact(n): """Computes the factorial of a natural number. Pre: - Post: Returns the factorial of 'n'. Throws: ValueError if n < 0 """ if n < 0: raise ValueError result = 1 whi...
#!/usr/bin/env python3 import sys import copy import numpy from math import gcd if len(sys.argv) != 2: print("usage: solve.py input.txt") exit(1) p1 = 0 p2 = 0 def compute_lcm(a): lcm = a[0] for i in a[1:]: lcm = lcm * i // gcd(lcm, i) return lcm def busadd(bus,earliest): arrival = 0 while ...
print("Welcome to the tip calculator") total=float(input("What was the total bill? ")) groupCount=int(input("How many people are in your group? ")) tipAmount=float(input("What percentage would you like to tip?")) final=(total+(total*(tipAmount*0.01)))/groupCount print(f"Each person should pay {final}")
import numpy as np import matplotlib.pyplot as plt def bland_altman_plot( m1, m2, sd_limit=1.96, ax=None, fig=None, ages=None, point_labels=None, display_labels=None, highlight_points=None, hide_points=None, y_lim=100, title="", x_axis="", scatter_kwds=None, ...
import csv from feature_extraction import calculate_features """ TASK: Prepare data-set from raw text DATA-SET-FORMAT: CSV INPUT: Raw lines from dataset OUTPUT: CSV containing features extracted from dataset """ def dataset_preparation(dump_filename, dataset_filename): # first read the text ...
""" Blinkt-Clocky -- 8 light led clock for the Pimoroni Blinkt! """ from datetime import datetime as dt from time import sleep from blinkt import clear, show, set_pixel, NUM_PIXELS def main(): """The Clocky light displays the hour range, the minute range, the second range, and a clock tick. To read the c...
class binaryTree: def __init__(self,data): self.data=data self.left=None self.right=None def pr(root): if root==None: return print(root.data) pr(root.left) pr(root.right) import queue def inp(): q=queue.Queue() print("enter root") rootD=int(input()) if rootD!=-1: root=binaryTree(rootD) q.put(root) ...
def can_win(board, pos): if pos < 0 or pos > len(board) - 1: return False current_pos_value = board[pos] if is_winning_slot(board, pos - current_pos_value) or is_winning_slot(board, pos + current_pos_value): return True return False def is_winning_slot(board, new_position): if ne...
import sqlite3 import sys import random from random import randrange from datetime import datetime, timedelta, date, time '''Resources for SQLite in python and implementing user logins https://eclass.srv.ualberta.ca/pluginfile.php/5149362/mod_label/intro/SQLite-in-Python-1.pdf -- BEST https://eclass.srv.ualberta.ca/mod...
# Find the smallest number def find_smallest_number(list_of_number): smallest = list_of_number[0] for num in list_of_number: print("current number: " + str(num)) print("smallest is: " + str(smallest)) if num < smallest: print("current is smaller than smallest!!") ...
import re import itertools input = open('day13input2.txt','r') regex = re.compile(r"(.*)\swould\s([a-z]{4}\s\d+)\shappiness\sunits\sby\ssitting\snext\sto\s(.*)\.") gainregex = re.compile("gain") data = [] people = [] maximumHappiness = 0 def happinessValue(person,neighbor): # Iterate through data and find the cor...
""" Loading the boston dataset and examining its target (label) distribution. """ # Load libraries import numpy as np import pylab as pl from sklearn import datasets from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_squared_error from sklearn.cross_validation import train_test_split from ...
import os # open a file/create if exists. # display all the dando #1-whatever. # loop until quit. file = open('dando.txt', 'a+') x = True while x == True: os.system('clear') command = input('DANDO | Go - > ') if command[:1] == 'a': print('a') file.write(command[1:] + '/n') elif comm...
#!/usr/bin/env python # coding: utf-8 '''microondas2.py: demonstração de clousure (este exemplo não funciona) Este exemplo mostra o problema: a variável `tempo` definida no corpo de `montar_painel` não pode ser alterada dentro de `ajustar`. O erro é: UnboundLocalError: local variable 'tempo' referenced before assign...
# Installing Word2 number library !pip install word2number from word2number import w2n import re #Converts words to numbers def word_to_num(string): ''' Converts english words to numbers such as hundred to 100 ''' words = string.split() numbers=[] for word in words: try: nu...