text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- """ Created on Mon Aug 31 00:33:31 2020 @author: edris """ # Create an @authenticated decorator that only allows the function to run is user1 has 'valid' set to True: user1 = { 'name': 'Sorna', 'valid': False #changing this will either run or not run the message_friends function. } def...
# -*- coding: utf-8 -*- """ Created on Fri Aug 28 18:56:50 2020 @author: edris """ class Pets(): animals = [] def __init__(self, animals): self.animals = animals def walk(self): for animal in self.animals: print(animal.walk()) class Cat(): is_lazy = True def __init__...
import random import string import re class MysteryWord: def __init__(self): with open("/usr/share/dict/words") as infile: language = infile.readlines() possible_words = [] for word in language: if 4 < len(word) < 10: possible_words.append(word.uppe...
def shell_sort(list): length=len(list) # initial step length step_len=int(round(length/2)) while step_len>0: for i in range(step_len, length): # insertion sort at each step length temp=list[i] j=i while j>=step_len and list[j-step_len]>tem...
''' 선택 정렬 ''' array = [7,5,9,0,3,1,6,2,4,8] for i in range(len(array)): min_index = i # 가장 작은 원소의 인덱스 for j in range(i+1,len(array)): if array[min_index] > array[j]: min_index = j array[i],array[min_index] = array[min_index],array[i] #스와프 print(array) ''' 삽입 정렬 ''' array = [7,5,9,0,3,...
""" You a given a number N. You need to print the pattern for the given value of N. for N=2 the pattern will be 2 2 1 1 2 1 for N=3 the pattern will be 3 3 3 2 2 2 1 1 1 3 3 2 2 1 1 3 2 1 Your Task: Since this is a function problem, you don't need to worry about the te...
''' Your task is to implement the function strstr. The function takes two strings as arguments (s,x) and locates the occurrence of the string x in the string s. The function returns and integer denoting the first occurrence of the string x in s. Your task is to return the index of the pattern presen...
# Your task is to complete all # three functions # if the element is found in the list # function must return true or else # return false def searchEle(a, x): if x in a: return True else: return False # fucntion must return true if # insertion is successful or else # return false def insertEl...
""" Given two strings of lowercase alphabets and a value K, your task is to complete the given function which tells if two strings are K-anagrams of each other or not. Two strings are called K-anagrams if both of the below conditions are true. 1. Both have same number of characters. 2. Two stri...
""" Given a Binary Tree of N edges. The task is to convert this to a Circular Doubly Linked List(CDLL) in-place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted CDLL. The order of nodes in CDLL must be same as Inorder of the given Binary Tr...
class Solution: def count_smaller_elements(self, arr, n, x): count = 0 for elem in arr: if elem <= x: count += 1 return count def main(): t = int(input()) sol = Solution() for _ in range(t): n = int(input()) ...
""" Given a number N, print the first N fibonacci numbers. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains the integer N. Output: Print the first n fibonacci numbers with a space bet...
""" Given a Binary Tree, print Right view of it. Right view of a Binary Tree is set of nodes visible when tree is viewed from right side. """ class Node: def __init__(self,val): self.data = val self.left = None self.right = None def helper(root, level, max_level): if not root: ...
""" Given number of edges 'E' and vertices 'V' of a bidirectional graph. Your task is to build a graph through adjacency list and print the adjacency list for each vertex. Input: The first line of input is T denoting the number of testcases.Then first line of each of the T contains two positive...
class Solution: def is_palindrome(self, s, n): p1 = 0 p2 = n-1 while p1 <= p2: if s[p1] != s[p2]: return "No" p1 += 1 p2 -= 1 return "Yes" def main(): t = int(input()) sol = Solution() for _ in ra...
""" You are in a party of N people, where only one person is known to everyone. Such a person may be present in the party, if yes, (s)he doesn’t know anyone in the party. Your task is to find the stranger (celebrity) in party. You will be given a square matrix M[][] where if an element of row i and ...
""" You are given a linked list of N nodes. The task is to remove the loop from the linked list, if present. User Task: You don't have to read the input, or print the output. Just complete the function removeTheLoop() which has only argument as head reference of the linked list. If you complete...
""" Given a linked list, delete N nodes after skipping M nodes of a linked list until the last of the linked list. User Task: The task is to complete the function skipMdeleteN() which should modify the linked list as required. """ class Node: # Constructor to initialize the node object def ...
""" Given a string S consisting of lowercase Latin Letters. Find the first non repeating character in S. Input: The first line contains T denoting the number of testcases. Then follows description of testcases. Each case begins with a single integer N denoting the length of string. The next lin...
""" Delete xth node from a singly linked list. Your task is to complete the method deleteNode() which takes two arguments: the address of the head of the linked list and an integer x. The function returns the head of the modified linked list. User Task: The task is to complete the function dele...
# Made in Yoo Hyeong Jun # github : https://github.com/cocopambag # email : jhdf1234@naver.com # import time library import time # time.gmtime(time.time()) is returned current time. input("In order to start stopwatch, Please press any key. : ") now = time.gmtime(time.time()) i = 0 # program start ! while True:...
def power_of_2(n): if n%2==0: return "divisible by 2" else: return "not divisible" n = int(input()) print(power_of_2(n))
string = input() string = list(string) string_obj = {} for i in range(0,len(string)): if string[i] not in string_obj: string_obj[string[i]] = 1 else: string_obj[string[i]] = string_obj[string[i]] + 1 for i in string_obj: if string_obj[i]>1: print(i)
#EXERCISE 12 # Two Different Answers # def firstLast(orignal): """ 1. use append like I did which would work with adding multiple values # 2. [orignal[0], orignal[-1]] :param orignal: List :returns: list containing first and last element of list provided """ return [orignal[0], or...
number = input("Give me a number so I can see if its even or odd? :") iseven = int(number) % 2 if (iseven == 0): print("The number is even. ") else: print("The number is odd. ") isfour = int(number) % 4 if (isfour == 0): print("The number is divisable by 4. ") else: print("The number is not divisable...
# calculator question 2 # given a string that represents an expression, return teh result of the expression # guarantees: # the only mathematical operators will be + and * #all nums will be positive single digit numbers ( 0 - 9) # each pair of parentheses will eiyher have two numbers and a single operator or a single...
#queue q 1 class Queue: def __init__(self, arrSize): self.arrSize = arrSize self.arr = [] def enqueue(self, val): if len(self.arr) == 0 or len(self.arr[0]) == 3: newArr = [] newArr.append(val) if(len(self.arr) > 0): self.arr.inser...
class admin(): def __init__(self): self.username=str(input("enter username")) self.password=str(input("enter password")) self.admin={} def createaccount(self): self.admin[self.username]=self.password return self.admin def login(self): name=input("enter username") if name in self.admin: passwor...
print("---Realizar las operaciones basicas---") n1 = int(input("Por favor regaleme el primer numero: ")) n2 = int(input("Por favor regaleme el segundo numero: ")) print(f"la suma de {n1}+{n2} es igual a {n1 + n2}") print(f"la resta de {n1}-{n2} es igual a {n1 - n2}") print(f"la multiplicación de {n1}*{n2} es igu...
print("Inicio del programa") dinero= int(input("Ingrese la cantida de dinero COP: $")) x=1 while x==1: print("billetes de:") print(f"$100k: {int(dinero/100000)}") dinero = dinero%100000 print(f"$50k: {int(dinero/50000)}") dinero = dinero%50000 print(f"$20k: {int(dinero/20000)}") ...
#reutilice el codigo del punto 6 cproducto=int(input("cantidad de productos escogidos: ")) listaproductos = [] for i in range(cproducto): #for in range me sirve para crear un bucle de con la cantidad ya dada listaproductos.append(float(input("Digite el precio de los productos: "))) #.append me sirve para agreg...
print("---Hallar el area y el perimetro de un circulo---") r = float(input("Regaleme el radio del circulo: ")) import math areaT=math.pi * r**2 perimetroT=2*math.pi*r print(f"El area del circulo es: {areaT:2f}") print(f"El perimetro del circulo es: {perimetroT:2f}")
print("---Imprimir los numeros impares positivos---") def generarImpares(n): impares = [] contador = 0 numero = 0 while contador < n: if numero % 2 != 0: impares.append(numero) contador += 1 numero += 1 return impares n = int(input(...
num = float(input("Por favor regaleme un numero decimal: ")) entera = num//1 num %= 1 print(f"la parte entera es {entera}") print(f"la parte decimla es {num:.3f}")
''' Problem Statement: https://www.codechef.com/problems/CSUB Author: hasanseam ''' testCase = int(input()) for i in range(testCase): character = int(input()) mainString = input() result = mainString.count("1") print(int((result*(result+1))/2))
import re verb = ('go', 'stop', 'kill', 'eat') noun = ('door', 'bear', 'princess', 'cabinet') stop = ('the', 'in', 'of', 'from', 'at', 'it') dire = ('north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back') # stuff = raw_input('input string or sth with space:') def scan(stuff): res = [] words ...
#!/usr/bin/env python3 """Continuous time Lotka-Volterra model showing population densities for resources and consumers, over a set time period. Outputs figures showing the variation in population densities over time and a phase portrait for the system.""" __appname__ = "LV1.py" __author__ = "Katie Bickerton <k.bick...
#!/usr/bin/env python3 """Demonstrates how list for loops and list comprehensions can be used for the same tasks - outputing oak species from list and changing output to upper case.""" __appname__ = "oaks.py" __author__ = "Katie Bickerton <k.bickerton18@imperial.ac.uk>" __version__ = "3.5.2" __date__ = "11-Oct-2018" ...
#!/usr/bin/env python3 """Functions exemplifying the use of control statements.""" __appname__ = "test_control_flow.py" __author__ = "Katie Bickerton <k.bickerton18@imperial.ac.uk>" __version__ = "3.5.2" __date__ = "12-Oct-2018" import sys #module for testing functions import doctest def even_or_odd(x=0): #if not spe...
# Ice Cream Flavor Code Encryption # Logan Stenzel # Importing the necessary modules import string import random from Tkinter import * import csv # VARIABLES letter_displacement = 2 #add on variables a_base = 100 a_key = 17 #rescramble variables r_key = 2 r_base = 1 #swap variable s_key = 2 s_base = 5 #xor variab...
from itertools import chain def triplet(xs, number): return xs[number * 3:(number + 1) * 3] def regions(board): for row in range(0, 3): for col in range(0, 3): yield chain.from_iterable((triplet(r, col) for r in triplet(board, row))) def columns(board): column = lambda col: (row[co...
def initialize(): keys = list(range(1, 20)) numstr = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'ninteen'] keys.extend(list(range(20, 110, 10))) num...
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) # Linked List class LinkedList: def __init__(self): self.head = None self.tail = None def __str__(self): cur_head = self.head o...
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ start = 0 end = len(input_list) - 1 while start <= end: ...
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ next_0 = 0 next_2 = len(input_list) - 1 sorted_list = input_list[:] i = 0 while i <= next_2: ...
#!/usr/bin/python """ Jack Weissenberger CSC 222 Assignment 1: Digital Signatures Using python 3.6.4 """ def mod_exp(x, y, N): """ This function performs modular exponentiation, taken from figure 1.4 :param x: n-bit integer :param y: n-bit integer :param N: an integer exponent y :return: x^y m...
""" 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输入: "(]" 输出: false 示例 4: 输入: "([)]" 输出: false 示例 5: 输入: "{[]}" 输出: true 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-parentheses 著作权归领扣网...
""" 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。 在任何情况下,若函数不能进行有效的转换时,请返回 0。 说明: 假设我们的...
# 15-112, Summer 2, Homework 4.1 ################################################################################ # Full name: Brian Lim # Section: B # Andrew ID: blim2 ################################################################################ ##############################################################...
# Create a program that takes an IP address entered at the keyboard # and prints out the number of segments it contains, and the length of each segment. # # An IP address consists of 4 numbers, separated from each other with a full stop. But # your program should just count however many are entered # Examples of the in...
import random count = 0 print("Do you want to start?") number = random.randint(1, 100) while count < 5: user_num = int(input("1-100: ")) count += 1 if user_num < number: print("up!!", "rest-%d" % (5-count)) elif user_num > number: print("down!!", "rest-%d" % (5-count)) else: ...
# You are welcome to write and include any other Python files you want or need # however the game must be started by calling the main function in this file. from graphics import * import sys def Ready(win, title, HowManyRounds): target_color = ["Blue", "Green", "Yellow", "Orange", "Red"] total = 0 #for loop t...
''' Created on Oct 22, 2012 @author: kenobi ''' ####################################################### ## ## Problem I ## ####################################################### print ("Select the type of item to rent:") print ("\t 1 - Movie") print ("\t 2 - Game") type_item = input("Enter your choice: ") if (typ...
####################################################### ## ## Question 1 ## ####################################################### ## Part 1 ##text = raw_input("Enter a string: ") ## ##for letter in text: ## code = ord(letter) ## print letter + "--> ", str(code) ################################...
class Node: def __init__(self, element): self.element = element ## should contains an int value self.next = None ## contains a Node object def __repr__(self): ## This method is recursive, you could use a while loop instead rep = '<Node: ' rep += str(s...
"""This file is a unit test for the get_data function from my_function.py """ import os import unittest import warnings from my_function import get_data class GetDataTestCase(unittest.TestCase): """Three cases unit test for get_data() case: (a) file is present locally case: (b) file is not pr...
class House: def __init__(self, location, house_type, deal_type, price, completion_year): self.location=location self.house_type=house_type self.deal_type=deal_type self.price=price self.completion_year=completion_year def show_detail(self): print("{0} {1}...
people=30 cars=40 buses=15 if cars>people: print"We should take the cars." elif cars<people: print"We should not take the cars" else: print"We cant decide." if buses>cars: print"Thats too many buses." elif buses<cars: print"Maybe we could take the buses." else: print"We still cant decide."...
age=raw_input("How old are you?") height=raw_input("How tall are you?") weight=raw_input("How much do you weight?") print "So you're %s old, %s tall and %s heavy." %(age,height,weight)
lst_nums = [1,2,3,4,5] def do_square(n): return n ** 2 lst_squares = map(do_square, lst_nums) print(list(lst_squares))
# read file, splitout out comments, & whitespace import sys if len(sys.argv) != 2: print("usage: file.py filename") sys.exit(1) filename = sys.argv[1] try: with open(filename) as f: for line in f: # ignore commentss comment_split = line.split("#") # strip ou...
#!/usr/bin/python print 'Checking for pattern "$[followed by digits].[2 digits]" i.e. $xxx.xx' import re s=raw_input("input String: ") if re.search(r"^\$[\d]+[\.][\d]{2}$",s): print('Pattern matched') else: print('Pattern not matched')
# Este programa coge un string y le pone raya al piso # alrededor de cada caracter. Por ejemplo: # Python --> _P_y_t_h_o_n_ def add_underscores(word): new_word = "_" for i in range(len(word)): # Original: new_word = word[i] + "_" new_word = new_word + word[i] + "_" # arreglado return new_wo...
# Loops # While loop # Se repite mientras que una condicion permanezca siendo verdadera n = 0 #while condicion: while n < 5: # Cuerpo: codigo que se repite mientras condicion sea verdad print(n) n = n + 1 # Si no pongo esto, n siempre es 0 y la condición es siempre verdad. # Eso sería un loop infini...
a = input('nombre 1 ') b = input('nombre 2 ') if a[0] == b[0] : print(True) elif a[-1] == b[-1]: print(True) else: print(False)
# El juego de fantasmas from random import randint print ('El juego de fantasmas') te_sientes_valiente = True puntuacion = 0 while te_sientes_valiente: puerta_fantasma = randint(1, 3) print('Tres puertas ante ti...') print('un fantasma detras de una') print('¿Que puerta abres?') puerta = input('1, ...
a = input('letra') while len(a) != 1 : print('debe ser solo una letra') a = input('letra') if a == 'i' or a =='a' or a =='e' or a =='o' or a =='u' : print('es vocal') else: print('no es vocal')
# printing an line and demanding an output name = input("What is your name?\n") # showing the output print(f"hello, {name}")
def square(number): answer = number * number return answer # note: this is not an eror, return an answer # main code starts here : useNumber = input("Enter a number: ") useNumber = float(useNumber) # convert to float numberSquarred = square(useNumber) # call the function and save the result print("The sequ...
# I say thank you Irv Kalb # Allow me to learn to use your source code # Source Code : https://github.com/Apress/learn-to-prog-w-python-3 # By : Source code for 'Learn to Program with Python 3' by Irv Kalb # Author : Salim Suprayogi # Rewrite the code to learn and understand the code # Menulis ula...
def separateRuns(): print("******************") print(someUndeFinedVariable) # will cause a run time error # nameError # someUndeFinedVariable is not defined print() # blank line def getGroceries(): print("milk") print("flour") print("sugar") separateRuns() # call another functi...
"""A function count_words() that takes a file name as its only argument and returns a dictionary mapping each word in the given file to the number of times it occurs in the file’s content. """ import string def count_words(file_name): with open(file_name, 'r') as f: dictionary = {} lines = [] ...
import smtplib import string import time import cred def send_mail(): print ' Setting up Mail...' print '......................' msg= ' The door was opened at : ' tm = time.strftime('%a, %d %b %Y %H:%M:%S %Z(%z)') SUBJECT = 'Alert ' TO = cred.TO FROM = cred.FROM text = msg + tm BODY = string.join(( ...
class Employee: raiseamt = 1.04 empcount = 0 def __init__(self, fname, lname, pay): self.fname = fname self.lname = lname self.pay = pay self.email = fname+lname+"@email.com" Employee.empcount += 1 def fullname(self): return f'{self.fname} {self.lname}' ...
cacheSize = 0 # number 0 =< size =< 30 cities = ["Jeju", "Pangyo", "Seoul", "NewYork", "LA"] # array of characters, maximum value = 100000, only characters time = 0 cache = [] for city in cities: if (city in cache): #hit time += 1 if(len(cache) < cacheSize - 1): cache.append(cit...
def is_palindrome(x): return str(x) == str(x)[::-1] n = 0 for a in range(999, 100, -1): for b in range(a, 100, -1): x = a * b if x > n and is_palindrome(x): n = a * b print n
def digits_sum(num): return sum(map(int,str(num))) def powerful_digit_sum(): max_sum = 1 for a in range(100): for b in range(100): d = digits_sum(a ** b) if d > max_sum: max_sum = d return max_sum
import sys import MySQLdb as mdb import pandas as pd import numpy as np from pandas.io import sql """ This script creates a players table with each player's ID, name, position, and team """ #Create DB def create_db(cur): statement = "CREATE DATABASE fantasy_lineups;" cur.execute(statement); return #create play...
import random from enum import Enum class Method(Enum): PMX = 0 CX = 1 OX1 = 2 OX2 = 3 POS = 4 VR = 5 AP = 6 SCX = 7 class PopulationCreator: def __init__(self, data): self.__method = Method.OX1 self.__data = data def change_method(self, m...
#!/usr/bin/env python3 import argparse import csv from functools import reduce import json import sys def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('input', type=argparse.FileType('r'), nargs='?', default=sys.stdin) parser.add_argument('-o', dest='output', type=argp...
import sys # Grab the first input which is not the filename first_arg = sys.argv[1] # Convert string to UPPER CASE first_arg = first_arg.upper() # Append 3 exclamation points first_arg = first_arg + "!!!" print(first_arg)
#!/usr/bin/env python3 import sys def solve(Q: int, l: "List[int]", r: "List[int]"): # 10^5までの素数を予め計算しておく。 INF = 100100 is_prime = get_prime_numbers_array(INF) is_like = [0] * INF for i in range(INF + 1): if i % 2 == 0: continue if (is_prime[i] and is_prime[int((i+1)/2)...
#!/usr/bin/env python3 import sys import math def solve(N: int): INF = 10000000000000 result = INF for a in range(1, int( math.sqrt(N) ) + 1): if N % a: continue result = min(result, a + int( N / a ) - 2) print(result) return # Generated by 1.1.6 https://github.com/kyu...
import random # loop for the whole game try_again = True while try_again == True: # prompt user for number of dice rolls num_rolls = int(input("Enter number of dice rolls: ")) num_side = int(input("Enter number of sides: ")) # variable for count variable for loop statement count = 0...
#-*- coding: utf-8 -*- ''' Foi feita uma pesquisa de audiência de canal de TV em várias casas de uma certa cidade, num determinado dia. Para cada casa visitada, é fornecido o número do canal (4,5,7,12) e o número de pessoas que o estavam assistindo naquela casa. Se a televisão estivesse desligada, nada era anotado, ou ...
def check_palindrome_permutation(str): freq_char={} count=0 str=str.replace(' ','') for i in str: if i in freq_char: freq_char[i] += 1 else: freq_char[i] =1 for i in freq_char: if freq_char[i]%2==1: count=count+1 if count>2: return False return True str1=input("Enter the string") print(che...
# # @lc app=leetcode.cn id=71 lang=python3 # # [71] 简化路径 # # @lc code=start class Solution: def simplifyPath(self, path: str) -> str: arr = path.split("/") stack = [] for s in arr: if s == "..": if stack: stack.pop() elif s and s !...
from threading import Thread,Condition import time import random class Produtor(Thread): def __init__(self,recurso,condicao): Thread.__init__(self) self.recurso = recurso self.condicao = condicao def run(self): for x in range(5): self.condicao.acquire() ...
# Reverse a number def reverse_num(num): # one way to do it haha # return int(str(num)[::-1]) # more readable string = str(num) r_str = string[::-1] r_num = int(r_str) return r_num print(reverse_num(56))
#!/usr/bin/python # statistics pakage modules mean avg standard deviations etc and perfom only in python 3 ''' statistics is a module we have to install these module for importing in any program . so pip command is used to install modules # install pip ###### pi ###### yum repolist all ###### yum install python-p...
import urllib import urllib2 import urlparse def url_fix(s, charset='utf-8'): """Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user:...
from Deck import Deck class Player: """ A player object """ def __init__(self, name): """ create a new player as input name, with empty score, hand and isActive set to true :param name: name passed from Game.get_players """ self.name = name self.score = ...
avg = 0 for i in range(5): s = int(input()) if s <40: s = 40 avg = avg + s print(int(avg/5))
from queue import Queue class Node(): def __init__(self, value=None): self.value = value self.left = None self.right = None class BinaryTree(): def __init__(self, root=None): self.root = Node(root) def dfs(self, tree): return self.dfs_helper(tree.root, []) ...
from random import random # from random import seed # seed(1) class Matrix(): def __init__(self, rows, cols): self.rows = rows self.cols = cols self.data = list() for i in range(self.rows): self.data.append(list()) for j in range(self.cols): self.data[i].append(0) @staticmethod def...
''' This project explores the use of linear regression to predict stock prices based on historical data from Quandl. ''' import pandas as pd import quandl import os, math, datetime, time, pickle import numpy as np from sklearn import preprocessing, cross_validation, svm from sklearn.linear_model import LinearRegressi...
''' This set of functions are a set of functions I found useful in creating clusters of students and teachers. The first three sections, ELBOW METHOD, GAP STATISTIC, and Alternative to Gap Stat are used to determine the number of clusters. Depending on the sample size these methods gave varying degrees of convincin...
import sympy class MathFunctions: def is_prime(self, num): if sympy.isprime(num): return True return False def inverse_multiplicative(self, e, totiente): for i in range(0, totiente-1): if (i*e) % totiente == 1: return i def generate_random_p...
def pattern(n): x = 0 for i in range(0, n): x += 1 for j in range(0, i + 1): print(x, end=" ") print("\r") pattern(7) #pascal's triangle def pattern(n): for i in range(0, n): for j in range(0, i + 1): print(function(i,j)," ", end="") ...
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import sklearn.metrics as skl from tensorflow.examples.tutorials.mnist import input_data def plot_confusion_matrix(cm, classes,normalize=False,title='Confusion matrix',cmap=plt.cm.Blues): """ This function prints and plots the confusi...