text
stringlengths
37
1.41M
import random print("The generated password having 10 characters is : ") s1="ABCDEFGHIJKLMNOPQRSTUVWXYZ" s2="!@#$%^&*" s3="1234567890" s4="abcdefghijklmnopqrstuvwxyz" s5=s1+s2+s3+s4; upper_string=random.choice(s1)#It ensures at least 1 upper case character lower_string=random.choice(s4)#It ensures at least 1 lower case...
import string import os os.chdir('./Files/Alphabet/') letters = string.ascii_lowercase for letter in letters: with open(letter + '.txt','w+')as file: file.write(letter) # To check and create directory you can use """ if not os.path.exists("Alphabet"): os.makedirs("Alphabet") """ # Then you could u...
import sqlite3 import pandas as pd data = pd.read_csv("./Files/ten-more-countries.txt") conn = sqlite3.connect("./Files/database.db") cur = conn.cursor() for index, row in data.iterrows(): print(row["Country"], row["Area"]) cur.execute("INSERT INTO countries VALUES(NULL,?,?,NULL)",(row["Country"], row["Area"...
d = {"a": list(range(1,11)), "b": list(range(11, 21)), "c": list(range(21, 31))} print("b has value {}".format(d["b"])) print("c has value {}".format(d["c"])) print("a has value {}".format(d["a"])) # Ardit Solution: for key, value in d.items(): print(key, " has value ", value)
peopleD = { "Jane Smith": {"Age":23, "Address":"123 Fake St"}, "Slim Dusty": {"age":44} } #print(peopleD) peopleL = { "people" :[ {"Name": "Jane Smith", "Age":23, "A...
max_count = int(input("Max number >>> ")) delimeter = int(input("Delimiter >>> ")) current_count = 0 while True: if current_count == max_count: break current_count = current_count + 1 if current_count % delimeter == 0: continue print(current_count)
# -*- coding: utf-8 -*- # Форматированный вывод import math pi = math.pi y = 2 z = pi * y print('Умножение {a:.5f} на {b:d} дает {c:.3f}'.format(a=pi, b=y, c=z))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Python 3.5.3 from numpy import zeros, log def rectangular(f, a, b, n, rec='left'): if rec == 'left': get_node = lambda i: i elif rec == 'right': get_node = lambda i: i + 1 elif rec == 'mid': get_node = lambda i: i + 0.5 else: ...
from sys import * from array_list import * #a SongFile contains a title, artist, song, and number #title is a string #artist is a string #album is a string #number is an int class Song: def __init__(self, title, artist, album): self.number = 0 #int - value will be changed self.title = tit...
import random def myiter(): num = random.random() if num < 0.1: #print("%.5s" % self.num) raise StopIteration new = random.random() while abs(new - num) < 0.4: #print("%.5s" % new) print("*", end='') new = random.random() num = new yield new a = myiter()...
class Enemy(object): life = 3 #attack function to take life def attack(self): print("ouch!") self.life -= 1 #checks life to see if it is less than 0 def checkLife(self): if self.life <= 0: print("I am dead") else: print(str(self.life) + " life left") vampire = Enemy() vampire.attack() vampir...
class LRUCache: def __init__(self, capacity: int): self.d = {} # map key to DLQ node self.q = DLQ() self.cap = capacity def get(self, key: int) -> int: if key in self.d: node = self.d[key] self.q.mark_mru(node) return node.v else: ...
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: m = len(matrix) n = len(matrix[0]) i, j = 0, m * n - 1 while i <= j: mid = (i + j) // 2 z = matrix[mid // n][mid % n] if target < z: j = mid - 1 ...
import time start = time.time() # Python program for implementation of heap Sort count = 0 # To heapify subtree rooted at index i. # n is size of heap def heapify(arr, n, i): global count count += 1 largest = i # Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # See if...
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import pandas as pd class plotting: def plot_decision_boundary(model, X, y): """ Plots the decision boundary created by a model predicting on X. This function has been adapted from two phenomenal resources: "...
# name: pa2pre.py # purpose: Student's add code to preprocessing of the data # Recall that any preprocessing you do on your training # data, you must also do on any future data you want to # predict. This file allows you to perform any # preprocessing you need on my undisclosed test data NB_CLASSES=10 from tensor...
"""Defines the parameters of the algorithm. This module contains the defintion of the class that handles all parameters of the algorithm. """ import robinmax_utils as utils class RobinmaxArgs: """ The parameter class. Contains all the parameters necessary for the algorithm. """ def __init__(self, ...
import pygame from decimal import Decimal from .Constantes import altura_tela, largura_tela class Ponto(): """ A classe Ponto define um ponto no espac ̧o a partir das coordenadas retangulares x e y. """ def __init__(self, x, y): self.x = x #referente a coordenada retangular x, no caso, o índic...
import numpy as np # An error function allows us to tell how far a point is from the # boundary line. With discrete functions, we can only tell whether a # point is misclassified or not. But with a continuous function we can # also tell by what magnitude the point is misclassified (using the # error function). This ...
Variable.py >>> 2 + 2 4 >>> 50 - 5 * 6 20 >>> (50 - 5 * 6) / 4 5.0 >>> round(5.0) 5 >>> 5.123456 5.123456 >>> round(5.123456,2) 5.12 >>> 17 / 3 5.666666666666667 >>> 17 // 3 5 >>> 18 // 4 4 >>> 20 // 5 4 >>> 17 % 3 2 >>> 17 * 4 % 3 2 addition = 75 + 25 subtraction = 204 - 204 multiplication = 100 * 0.5 division = 9...
a = [0, [1, [2, [3,[4,[5,None]]]]]] b = [6,[7,[8,[9,[10,[11, None]]]]]] c = a while c: c[0] = a[0] + b[0] c = c[1] b = b[1] a = a[1] print(c[0]) print(c) while c : print(c[0], end='') c = c[1]
def reverse(x): result = [] for i in x: num = str(i) result.append(int(num[::-1])) return result def isPrime(x): rev = reverse(x) maxResult = max(rev) arr = [True for i in range(maxResult+1)] arr[1] = False for i in range(2,maxResult+1): if arr[i] == True: ...
import heapq heap = [] while True: x = int(input()) if x > 0 : heapq.heappush(heap, x) elif x == 0 : print(heap) print(heapq.heappop(heap)) heap = [] elif x == -1: break
def DFS(x): # 전위순회 if x > 7: return else: DFS((x * 2)) print(x) DFS((x*2)+1) if __name__ == "__main__": DFS(1)
def hi(name): print('hi,', name) hi('jiwon') hi('python') def hi_return(name): val = 'Hi, ' + str(name) return val print(hi_return('apple')) def func_mul(x): y1 = x * 100 y2 = x * 200 y3 = x * 300 return y1,y2,y3 val1 = func_mul(100) print(type(val1)) def args_ex(*args): for idx,v...
class Environment(): def __init__(self, floors): self.floors = floors + 1 self.turns = 0 self.elevators = [] self.users = [] def addUser(self, user): self.users.append(user) print(f'U{len(self.users)}| {user.getState()}') def getUserById(self, i): ...
from RobotArm import RobotArm robotArm = RobotArm('exercise 12') robotArm.speed = 2 # Jouw python instructies zet je vanaf hier: loopA = 0 # Waarde van while loop positie = 1 # Waarde van de positie van het blokje waar de grijpklauw is gebleven totaalPositie = 10 # Waarde van het aantal posities while loopA <= 8: # ...
def newtroot(): pass #ask user for a positive number num = float(input("Give me a positive number " )) #Ask the user to guess the square root of the number... guess = float(input("guess the square root ")) guess2 = ((num / guess) + guess) / 2 guess3 = ((num / guess2) + guess2) / 2 guess4 = ((num / guess3) + gues...
from datetime import date class Person(object): def __init__(self, name, year_of_birth): self.name = name self.year_of_birth = year_of_birth @property def age(self): age = date.today().year - self.year_of_birth return age
i=int(input()) if ( i%4==0 and i%100!=0 ) or (i%400==0 ) : print('yes') else: print('no')
i=sorted("kabali") i=str(i) o=int(input()) a=list() count=0 for j in range(0,o): u=str(input()) u=sorted(u) u=str(u) a.append(u) for h in a: if h in i: count+=1 print(count)
""" Author : VILLIN Victor . Date : 2020-06-02 . File : q1.py . Description : None Observations : None """ # == Imports == import itertools # ============= def prime_numbers(max): """ :param max: max>2 , maximum prime value to find, from 0 :return: list of all primes < max """ assert max > 1 ...
from sympy import * import sympy def area(): theta = sympy.Symbol('theta', real = True) p1 = (5*cos(2*theta), 5*sin(2*theta)) p2 = (10*cos(theta), 10*sin(theta)) a = (2, 0) tri = sympy.geometry.Polygon(p1, p2, a) max_area = 0 s_diff = sympy.solve(sympy.diff(tri.area, t...
# Problem 2 from math import sqrt, sin, cos, pi # Initialize points at T = 0 O = [0, 0] A = [2, 0] P1 = [5, 0] P2 = [10, 0] # Return coordinates of the rotated point regarding the parameter "angle" def rotate(point, angle): rotated_point = [point[0]*cos(angle) - point[1]*sin(angle), point[1]*sin(angle...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 31 22:47:08 2021 @author: m.yuta """ import sympy as sym theta = sym.Symbol("theta", real=True) #Aの座標を定義 A_x = 2 A_y = 0 #P1,P2の各座標をthetaを用いて定義 P1_x = 5 * sym.cos(2*theta) P1_y = 5 * sym.sin(2*theta) P2_x = 10 * sym.cos(theta) P2_y = 10 * sym.sin...
nums = [4, 8, 15, 69, 16, 23, 42] print("The smallest number in this list is:", min(nums)) #SOLVED
def main(): #Disclaimers# print("----------------------------------------") print("----CSGO Trade up Profit Calculator-----") print("------Author: Piotr Rajchel, 2020-------") print("--------------Ver.1.0-------------------\n") print("This program will tell you the percentage\nof profitability a...
T = int(input()) for i in range(T): N = int(input()) for j in range(2, N//2+1): if (N%j==0): print("no") break elif (j==N//2): print("yes")
import time # WEEK 1 # Week 1 Assignment1 ''' 6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out. ''' text = "X-DSPAM-Confidence: 0.8475" numf = text[text.find('0'):text.find('5'...
""" Specify number of players Size of Action Sets Number of turns Simultaneous or Sequential Decisions """ from random import choice #TODO: register moves for player, class Game: """ A Generalised N-Player, M-Move, K-Turn Game """ def __init__(self, players=1, moves=2, turns=1, preconditions=None, name=Non...
""" Defintions for Core Transform Operators """ from re import sub from acab.abstract.rule.transform import TransformOp class RegexOp(TransformOp): def __init__(self): super().__init__() def __call__(self, value, pattern, replacement, data=None, engine=None): """ Substitute value pattern with...
def has_number(n: int): def _has_number(i: int): for j in map(int, str(i)): if n == j: return True return False return _has_number def is_divisible_by(n: int): def _is_divisible_by(i: int): return 0 == i % n return _is_divisible_by def fizzbuzz(n: ...
# -*- coding utf-8 -*- from stack import Stack from queue_ import Queue class Graph(object): def __init__(self, initial_graph=None): '''Pass in a graph in the form of a dictionary with the nodes as key, and a dictoinary containing edges as keys and wieghts as values {1:{2:100, 3:299}, ...
# -*- coding utf-8 -*- END_OF_WORD = '$' class Node(object): """Node object. Has a value and a list of nodes that could come next.""" def __init__(self, value=None): """ Each node will contain the letter at that node and a list of node that come next. """ self.value ...
from math import sqrt class Point(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return repr((self.x, self.y)) def distance(point1, point2): return sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2) def min_point_pair_2d(points, low, hi...
# o(n) from collections import defaultdict def counting_sort(a, key=lambda x: x): b, c = [], defaultdict(list) for x in a: c[key(x)].append(x) for k in range(min(c), max(c) + 1): b.extend(c[k]) return b def main(): seq = [1, 5, 3, 4, 5, 1000, 2] seq = counting_sort(seq) p...
# coding=utf-8 class Point(object): def __init__(self, x, y): self.x = x self.y = y Mid = Point(0, 0) def quad(point): """确定象限""" if point.x >= 0 and point.y >= 0: return 1 elif point.x <= 0 and point.y >= 0: return 2 elif point.x <= 0 and point.y <= 0: ...
# Exercise 2 vowels = ['a', 'e', 'i', 'o', 'u'] numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] inputStr = input() vowelsNum = 0 digitsNum = 0 digitsSum = 0 repeatedCharDict = {} for i in range(len(inputStr)): character = inputStr[i] charNum = 1 if character.lower() in vowels: vowelsN...
number = int(input()) for i in range(1,number*2): if i <=number: print("*" * i) else: print("*" * (number*2 -i))
# adding a class as super class for class Z and A class T: def do_job(self,**kwargs): # do nothing actually pass class A(T): def do_job(self,**kwargs): super().do_job(**kwargs) print('I am walking ...') class Z(T): def do_job(self, n,**kwargs): super(Z, self).do_...
# inputStr = list(input()) # # # def sumdigit(inputStr): # while len(inputStr) > 1: # result = sum(map(int, inputStr)) # inputStr = list(str(result)) # return int(inputStr[0]) # # # print(sumdigit(inputStr)) # ---------------------------------------------------------------------- # number = int...
def beautiful_num(): my_bool=True counter = 1 my_num = 0 number=int(input()) while my_bool: my_num +=counter if(number_of_divisors(my_num)>number): return my_num counter +=1 def number_of_divisors(number): return len([i for i in range(1,number+1) if number%...
class IndentMaker: def __init__(self): self.tab_num = -1 def __enter__(self): self.tab_num += 1 return self def __exit__(self, exc_type, exc_val, exc_tb): self.tab_num -= 1 if exc_type is not None or exc_val is not None or exc_tb is not None: return True...
# Write a procedure, shift_n_letters which takes as its input a lowercase # letter, a-z, and an integer n, and returns the letter n steps in the # alphabet after it. Note that 'a' follows 'z', and that n can be positive, #negative or zero. def shift_n_letters(letter, n): letter = ord(letter) total = letter + n...
# Write a procedure download_time which takes as inputs a file size, the # units that file size is given in, bandwidth and the units for # bandwidth (excluding per second) and returns the time taken to download # the file. # Your answer should be a string in the form # "<number> hours, <number> minutes, <number> second...
# Name: James Dietz # Date: 11/12/2012 # Comment: Fermat's PRP test. import random def test(): print("Program to perform the Fermat PRP test in Python.") n = int(input("Please enter the number to test: ")) print() prp = [] composite = 0 print("The chance of failure for the Fermat PRP test is ")...
import numpy as np #import matplotlib.plyplot as plt import pandas as pd from sklearn.preprocessing import LabelEncoder, OneHotEncoder def sigmoid(x): return 1.0/(1 + np.exp(-x)) def sigmoid_derivative(x): return x * (1.0 - x) class NeuralNetwork: def __init__(self, x, y): self.input = x ...
def fibo_recursion(n): if n <= 1: return n else: return(fibo_recursion(n-1) + fibo_recursion(n-2)) value = 12 if value <= 0: print("Enter a positive integer") else: for i in range(value): print(fibo_recursion(i))
# a) def is_prime(n): if n > 1: for x in range(2,n): if (n % x) == 0: print(False) break else: print(True) else: print(False) is_prime(3) # b) def is_prime_dos(n): if n == 2 or n ==3: return print(True) if n % 2 == 0 or n % 3 == 0: ...
def dequeue(self): if(self.rear == -1): print("Error- queue empty") else: out = self.queue[self.front] self.front += 1 if(self.front > self.rear): self.front = -1 self.rear = -1 return out return -1
""" This script uses the Vision API's label detection capabilities to find a label based on an image's content. To run the example, install the necessary libraries by running: pip install -r requirements.txt Run the script on an image to get a label, E.g.: ./label.py <path-to-image> """ im...
# 时间片轮转 from builtins import range, len, float class Process: def __init__(self, name, arrive_time, serve_time, ready=False, over=False): self.name = name # 进程名 self.arrive_time = arrive_time # 到达时间 self.serve_time = serve_time # 需要服务的时间 self.left_serve_time = serve_tim...
#!/usr/bin/python import math from copy import deepcopy # function to clean outlier data of 10% def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Re...
#!/usr/bin/python # -*- coding: utf-8 -*- class ListNode: def __init__(self, x): self.var = x self.next = None class Solution: def reverseList(self, head:ListNode) ->ListNode: pre = None cur = head while cur: nextnode = cur.next cur.next = pre ...
#!/usr/bin/python # -*- coding: utf-8 -*- # 232-用栈实现队列 from collections import deque class Stack: def __init__(self): self.items = deque() def push(self, val): return self.items.append(val) def pop(self): return self.items.pop() def top(self): return self.items[-1] ...
# Created by: Julie Nguyen # Created on: Oct 2017 # Created for: ICS3U # This program is a guessing game where the user must input the number 5 (the correct number) in order to # win # Modified on: Oct 2017 # added an if statement, removed constant of 5 and replaced it with random integer code import ui from numpy im...
import Tkinter from Tkinter import * from PIL import ImageTk, Image import tkFileDialog import os # Aqui capturo cual es el path del programa. Las imagenes y el .txt tienen que estar en el mismo # directorio. Las imagenes porque las busca en este path, y el .txt en realidad solo para que # sea mas rapido encontrarlo :...
SUBLIST, SUPERLIST, EQUAL, UNEQUAL = 1, 2, 3, 4 def check_lists(one, two): if one == two: return EQUAL len_1 = len(one) len_2 = len(two) if len_1 > len_2: for ii in range(len_1): if one[ii:len_2+ii] == two: return SUPERLIST for ii in range(len_2): ...
GRADE_LEVELS = 9 class School: def __init__(self, school_name): self.db = list(map(lambda x: [], [None] * GRADE_LEVELS)) def grade(self, grade): return self.db[grade][:] def add(self, name, grade): self.db[grade].append(name) def sort(self): return [(i, tuple(self.db...
def largest_palindrome(min_factor=1, max_factor=1): max_product = 0 data = {} for ii in range (min_factor, max_factor+1): for jj in range (ii, max_factor+1): product = ii * jj if ''.join(reversed(str(product))) == str(product): max_product = max(max_product, p...
def doc_is_exist(directories): """ doc_is_exist(directories) Function for input number of document directories: dictionary of document shelf's """ doc_number = input('\nВведите номер документа:\n') if [doc_list for doc_list in directories.values() if doc_number in doc_list]: ...
from ClassStack import Stack def balanced(brackits_str: str) -> str: balanced_stack = Stack(brackits_str) empty_stack = Stack('') brackits_open = ['[', '(', '{'] brackits_list = ['[]', '()', '{}'] if balanced_stack.size() % 2 != 0: return 'Несбалансированно' empty_stack.push(balanced_s...
import sys import pygame as pg class Game(object): """ A single instance of this class is responsible for managing which individual game state is active and keeping it updated. It also handles many of pygame's nuts and bolts (managing the event queue, framerate, updating the display, etc.). ...
# utilizzo del loop for, molto simile al foreach di Java nomi = ["Alberto", "Luisa", "Gianni"] for nome in nomi: print(nome.lower()) # python l'indentazione come carattere per la interconnessione del codice, analogo utilizzo di ; in C # la funzione range() di python permette di creare una array con valori nume...
''' approach #1 ''' filepath = 'last_movie.txt' with open(filepath, 'w') as file: print(file.write('first line')) with open(filepath, 'r') as file: print(file.readline()) with open(filepath, 'a') as file: file.write('\n'+'Song') with open(file...
# Google braille_translation.py """ Braille Translation Part of the Google secret interview process =================== Because Commander Lambda is an equal-opportunity despot, she has several visually-impaired minions. But she never bothered to follow intergalactic standards for workplace accommodations, so those m...
class User: def __init__(self, name): self.name = name self.movie = [] def __repr__(self): return "<User {}>".format(self.name) return "<User {}>".format(self.movie) # gather the list of movies that has been watched # itterate through the list # then iterate thr...
import sqlite3 class Database: def __init__(self, db): self.conn = sqlite3.connect(db) self.cur = self.conn.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS books(id integer primary key,title text,author text,year integer,isbn integer)") self.conn.commit() def insert_data(...
# Pre-processes the input image by removing noise and draws the contours for coloured squares in the image """ Team Id: HC#3266 Author List: Aman Bhat T, Hemanth Kumar M, Mahantesh R, Nischith B.O. Filename: preprocess.py Theme: Homecoming Functions: preprocess Global Variables: colour_contours, font, kernel ...
#!/bin/python3 def ping_pong(n): ''' return a for-loop solution ''' res = [] for i in range(1, n+1): print(check_value(i)) res.append(check_value(i)) return res # def ping_pong(n): # ''' return a generator solution ''' # value = get_value(n) # for _ in get_value(n): # ...
# Flip all bits def flip(bits): if (len(bits) > 0): if (bits[0] == 0): return [1, flip(bits[1])] else: return [0, flip(bits[1])] else: return [] def main(): # Immutable list of 32 bits (zeroes) bits = [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [...
class CreateStudent: def __init__(self, Name, Surname, Password, Email, Address, conctactNumber, studentId): self.Name = Name self.Surname = Surname self.Password = Password self.Email = Email self.Address = Address self.conctactNumber = conctactN...
k = "ilyadaersan" s = "abbcd" kullanıcı = input("kullanıcı adınızı girin") sifre = input("sifreyi girin") if kullanıcı == k and sifre != s: print("kullanıcı adı doğru fakat sifre yanlış") elif sifre == s and kullanıcı != k: print("sifre doğru fakat kullanıcı adı hatalı") elif sifre != s and kullanıc...
class Tokens: """ Management of given tokens. """ def __init__(self, tokenfilepath): """ Arguments: tokenfilepath -- path to the file defining tokens and their inverse image """ self.__tokentree = TokenTree() self.__words = dict() for l in open(tokenfilepath): if not l.startswith("#") and len(...
#汉罗塔游戏 #n层数,x轴,y轴,z轴 def hanoi(n ,x , y , z): if n == 1: print(x ,'--->', z) else: hanoi(n-1 ,x ,z ,y ) #将前n-1个盘子从x移动到y上 print(x,'--->',z) hanoi(n-1 ,y ,x , z) n = int(input("请输入汉罗塔层数")) hanoi(n , "x" , "y" , "z" )
# f = open("new.txt","r") # print(f.read()) # f.close() f = open("new.txt","r") # 往里面输入 for line in f: if "1" in line: print("this is the hello say hello") else: print(line) f.close()
import unittest from city_function import region class CityTest(unittest.TestCase): def test_city_country(self): city_country = region("Cairo","Egypt") self.assertEqual(city_country,"Cairo Egypt") def test_country_city_population(self): city_country_pop = region("cairo","Egypt...
__author__ = "Sanju Sci" __email__ = "sanju.sci9@gmail.com" from Arrays import gcd, print_array from Arrays.reverse import reverse # Using temp array https://www.geeksforgeeks.org/array-rotation/ # Time complexity : O(n) # Auxiliary Space : O(d) def left_rotate_s1(arr, d): """ This function is used to left...
import time import schedule class Scheduler(object): def __init__(self): schedule.every(1).minutes.do(self.job) schedule.every().hour.do(self.job) schedule.every().day.at("17:06").do(self.job) schedule.every(1).to(2).minutes.do(self.job) schedule.every().monday.do(self.jo...
import numpy as np import pandas as pd from sklearn.decomposition import PCA #Function to categorize based on median def categorizeNumpyArray(NArr): fq=NArr.describe()["25%"] mid=NArr.describe()["50%"] tq=NArr.describe()["75%"] categoryArr=list() for i in range(len(NArr)): if (NArr[i]<...
#!/usr/bin/python3 """Calculate term frequency.""" import sys import string def read_file(path_to_file): """ Load file into data """ data = [] with open(path_to_file) as input_file: data = data + list(input_file.read()) return data def filter_chars_and_normalize(data): """ R...
#!/usr/bin/python3 import sys, re, operator, string, inspect def read_stop_words(): """ This function can only be called from a function named extract_words.""" # Meta-level data: inspect.stack() if inspect.stack()[1][3] != 'extract_words': return None with open('../stop_words.txt') a...
""" This is the unit test for calc_viewing_direction which calculates the direction from the animal's location to a spot on the dome given the camera's direction and the pixel coordinates of the spot in a photo taken with the camera. Calls to this function look like this: calc_viewing_direction(photo_point, camera_dir...
def necklaces(N): for n in range(2 ** N): yield "{0:0{digits}b}".format(n, digits=N) def has_N_white_beads(necklace, N): return necklace.count("1") == N def flip(necklace): return necklace[::-1] def rotate(string, steps): return string[steps:] + string[:steps] def better_than_al...
largest = None smallest = None while True: input_str = input("Enter a number: ") if input_str == "done": break try: parsed_integer = int(input_str) if largest is None or parsed_integer > largest: largest = parsed_integer if smallest is None or parsed_integer < ...
""" Esta clase preceptron tendra 3 metodos: 1. - Inicializar el perceptron Pesos iniciales aleatorios. 2. - Calculo de la salido del perceptron 3. - Entrenamiento """ import numpy as np import matplotlib.pyplot as plt # Funciones anonimas o funciones lambda def sigmoid(): return lambda x: 1 / ...
import sqlite3 from sqlite3 import Error class DataBase: def __init__(self, dbname='mydatabase.db'): self.dbname = dbname self.check_reatebase() def check_reatebase(self): try: self.conn = sqlite3.connect(self.dbname, check_same_thread=False) se...
def city_country(city, country): """Return a string like this 'Santiago, Chile'.""" return(city.title() + ", " + country.title()) city = city_country('shanghai', 'china') print(city) city = city_country('beijing', 'china') print(city) city = city_country('tokyo', 'japan') print(city)
person = { 'first_name': 'jimmy', 'last_name': 'chen', 'age': 23, 'city': 'shanghai' } print(person['first_name']) print(person['last_name']) print(person['age']) print(person['city'])
######################## #Name: Cherie Hua #AndrewID: cxhua #Section: O ####################### import sys, math, copy, string, random, time from cmu_112_graphics import * # copied (with modifications) from https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html from fractions import Fraction #from https://docs.p...