text
stringlengths
37
1.41M
# list print list('hello') print ''.join(list('hello')) # hello, different output from above x = [1, 1, 1] x[1] = 2 print x names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl'] del names[2] # delete 'Cecil' element print names name = list('Perl') name[1:] = list('ython') print name numbers = [1, 5] numbers[1:1] = ...
class Calculator: def calculate(self, expression): self.value = expression class Talker: def talk(self): print 'Hi, my value is', self.value # the class inherited earlier will overwrite the method appered in # the class after class TalkingCalculator(Calculator, Talker): pass tc = TalkingCalculator() tc.cal...
import statistics import csv import pandas as pd data = pd.read_csv("StudentsPerformance.csv") reading_score_list = data["reading score"].to_list() mean = statistics.mean(reading_score_list) Reading_Score_STD =statistics.stdev(reading_score_list) Reading_Score_first_STD_start , Reading_Score_first_STD_...
# for loops with lists (from last time) for value in [1, 2, 3, 4, 5]: print(value) for field in ['Thomas', 'Smith', 'cisc456', 'B+', 'senior']: print(field, '\t', sep = '', end = '') # Generate a conversion table from °F to °C, using a for loop with a list from menu_functions import convert_F_to_C print('\n...
# File I/O - opening/closing/reading/writing files. (r, w, a) # write mode - if file doesn't exist, creates new file # if file exists, deletes contents of existing file! my_file = open('test.txt', 'w') my_file.write('This is a simple test of Python file access\n') my_file.close() # read mode - file must a...
def gravity(): Mass1 = float(input('Input first mass in kg')) Mass2 = float(input('Input second mass in kg')) Distance = float(input('How far apart are the two masses in meters?') F = (6.673e-11)*((Mass1*Mass2)/Distance**2) return F
# From last time - using end and sep with print() print(1, 2, 3, sep = ', ') # Escape sequences - \n, \t, \', \", \\ print('Don\'t fall asleep') # Escaping the escape character - \\ # The first print() statement has a problem because the backslash at the # end of the line is being combined with the final quote mark t...
# exception handling # division by 0 error 5 / 0 # value error int('a') # file not found error file = open('non_existent_file.zzz', 'r') # Using try-except to gracefully handle exceptions dividend = 25 def my_function(): # This catches input that can't be converted to a float try: divisor = float(in...
heart_rate = 220 def fat_burning_heart_rate(): user_heart_rate = (heart_rate - user_age) * 0.70 print("Fat burning heart rate for a", user_age, "year-old:", '{0:.1f}'.format(user_heart_rate), "bpm") def get_age(): if user_age > 17 and user_age < 76: return user_age else: raise ValueEr...
#!/usr/bin/env python3 """ Problem: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the s...
def supportsSsl(sequence, hypernet_sequences): for i in range(0, len(sequence) - 2): if sequence[i] != sequence[i + 1] and sequence[i] == sequence[i + 2]: bab = sequence[i + 1] + sequence[i] + sequence[i + 1] for hypernet_sequence in hypernet_sequences: if bab in hype...
#!/usr/bin/env python # encoding: utf-8 """ Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. @author: Jessie @email: jessie....
#!/usr/bin/env python # encoding: utf-8 """ Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. @author: Jessie @email: jessie.JNing@gmail.com """ class Solut...
#!/usr/bin/env python # encoding: utf-8 """ You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? @author: Jessie @email: jessie.JNing@gmail.com """ class Solution(object): def climbStairs(self, n): ...
#!/usr/bin/env python # encoding: utf-8 """ Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (b...
#!/usr/bin/env python # encoding: utf-8 """ Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. @author: Jessie @email: jessie.JNing@gmail.com """ #Definition for singly-linked list. class ListNode(object): def __init__(...
import time glory = 0 health = 100 value = [] inventory = ["Apple","Lantern","Knife"] equipped = [] def main(): intro() next_move() def end(): exit() return None def glory_status(): if glory <=0: print("Your journey achieved nothing. You were forgotten in history. Please try again.") ...
''' break/continue ''' absent = [2, 5] no_book = [7] for student in range(1,11): if student in absent: continue elif student in no_book: print("{}, 교무실로 따라와".format(student)) break print("{}, 책을 읽어보렴.".format(student))
''' 연산 이해하기 ''' print("#1. 단순연산") print(1+1) print(3-2) print(5*2) print(7/3) #파이선 문법 - 일반적으로 7/3은 몫만 출력이되는데, 파이선은 실수로 간주함 print("#2. 특징적인 연산") print(2**3) # 지수승 2^3 print(5%3) # 나머지 print(10%3) print(5//3) # 몫(정수) - 파이선은 몫을 구하기 위한 연산자가 추가로 필요함 print(10//3) print("#3. 비교 연산") print(10 > 3) print(4 >= 7...
''' 클래스 ''' class Unit: def __init__(self, name, hp, damage): self.name = name self.hp = hp self.damage = damage print("{} 유닛이 생성되었습니다.".format(self.name)) print("체력 {}, 공격력 {}".format(self.hp, self.damage)) marine1 = Unit("마린", 40, 5) marine2 = Unit("마린", 40, 5) tank = Unit("탱크", 150, 35) tank.siegemode ...
def next_move(posr, posc, board): # retrieve dirty cell location for i, row in enumerate(board): for j, elem in enumerate(row): if elem == "d": dirt_r, dirt_c = i,j break # get difference between dirt location to move and current loc diff_r, diff_c ...
print("Oscar had a little headache") print("Its fleece was white as {}.".format('snow')) print("And everywhere that Oscar went") # * 10 makes the "." repeat 10 times print("." * 10) #"x" assign different individual letters to different variables end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 =...
print("What is your age?", end=' ') age = input() print("What is your height?", end=' ') height = input() print("What is your weight?", end=' ') weight = input() print(f"Based on the input, you are {age} old, {height} tall and {weight} heavy.")
#!usr/bin/env python3 import sys import re for i in range(1, len(sys.argv)): if re.search('a', sys.argv[i]) or re.search('p', sys.argv[i]): if re.search('a', sys.argv[i]) : print("Option a !") if re.search('p', sys.argv[i]) : print("Option p !") else : print("Err...
# Lab 7 # By Michelle Cantin # Option 1: isSorted def isSorted(xs): if sorted(xs) == xs: return True else: return False # Option 2: isAnagram def isAnagram(stringOne, stringTwo): stringOne = stringOne.replace(" ", "") stringTwo = stringTwo.replace(" ", "") if sorted(stringOne) == s...
cars =[ {"name": "A", "model": "Ball", "milage": 23, "arbitrtion" : "sandra"}, {"name": "B", "model": "Ballll", "milage": 24, "arbitrtion" : "bullock"}, {"name": "C", "model": "Ballllll", "milage": 25, "arbitrtion" : "sandraorteon"}, {"name": "D", "model": "Ballllllll", "milage": 27, "arbitrtion" : "sam...
## Install all the necessary libraries #!pip install bs4 #!pip install requests #!pip install ipywidgets ##Import the libraries from bs4 import BeautifulSoup import requests import pandas as pd from pandas import Series, DataFrame from ipywidgets import FloatProgress from time import sleep from IPython.display import ...
import math import random power_of_two = [3,7,15,31,63] pile = random.randrange(10, 101) turn = random.randrange(0, 2) strategy = random.randrange(0, 2) print('The pile size at the start has %s marbles' %(pile)) def nim(): if strategy == 0: print('Human Wins') else: print('Computer Wins') ...
#drunkard import random import turtle import math drunk = turtle.Turtle() print(drunk) # drunk.shape('turtle') # drunk.turtlesize(.6,.6,.6) print(drunk) turtle.mainloop() def drunkard_walk(n): drunk.circle(5) north_south = 0 east_west = 0 north_south_movement = '' east_west_movement = '' for ...
#Factorial def factorial(n): result = 1 if n == 1: return 1 print(n) result = n * factorial(n-1) return result print(factorial(1)) print(factorial(3)) #Fibonacci def fib(n): if n == 1 or n == 2: return 1 return fib(n-1) + fib(n-2) print(fib(3)) print(fib(10)) #GCD def g...
#Guess and Check cube = 28 for guess in range(cube+1): if guess**3 == cube: print("Cube root of", cube, "is", guess) #better guess and check cube = -28 for guess in range(abs(cube)+1): if guess**3 >= abs(cube): break if guess**3 != abs(cube): print(cube, 'is not a perfect cube') else: ...
import re # (re) means regular expression pattern = r"colour" text = "Everyone like red colour. Red is one of the best colour." text2 = re.sub(pattern,"color",text,count=2) text3 = re.search(pattern,text) print(text2) if text3: print("match") else: print("error")
def largest(a,b): if a > b: return a else: return b result = largest(100,50) print("Greater number is ", result)
from random import randint a = 0 cpoint = 0 ppoint = 0 print("Welcome to rock, paper and scissor.") try: while a < 3: b = ["first", "second", "third"] d = b[a] print("Your turn:") game = ["Rock", "Paper", "Scissor"] print("1.Rock. \n2.Paper. \n3.Scissor") player = ...
# List comprehensions num = [1,2,3,4,5] result = [x*x for x in num] print(result) result1 = [x for x in num if x%2 == 0] print(result1)
marks = 20 if marks >= 80: print("A+") elif marks >= 70: print("A") elif marks >= 60: print("B") elif marks >= 50: print("C") elif marks >= 40: print("C") elif marks >= 33: print("D") elif marks <= 33: print("F")
# 1 x 2 x 3 x .... n. (Factorial (n!)) # 2 x 4 x 5 x .... n. # 1 x 3 x 7 x .... n. print("Enter the number you want to factorial of :") n = int(input()) m = 1 for x in range(1,(n+1),1): m = m * x print(m)
import nltk from nltk.corpus import stopwords RECIPE = """Place the cayenne, black pepper, paprika, ginger, turmeric and cinnamon into a small bowl and mix to combine. Place the lamb in a large bowl and toss together with half of the spice mix. Cover and leave overnight in the fridge""" def process...
import nltk import csv import os import pandas as pd from nltk.tokenize import sent_tokenize, word_tokenize from nltk.tokenize import PunktSentenceTokenizer from nltk.corpus import stopwords import nltk.classify.util from nltk.classify import NaiveBayesClassifier from nltk.corpus import names negative_words = open("sta...
""" Written by : Name: Amit Ovadia, 207634791 Name: Rona Nazarov, 207134446 """ def zeros_list(len): lst = [] for i in range(0, len): lst.append(0) return lst def get_eqs(): print("Please enter the number of equations you would like to enter:") num_eqs = int(input()) m...
#This program finds lines which starts with "From" and then extract the third element han = open("mbox-short.txt") for line in han: line = line.rstrip() words = line.split() #We creat a guardian in case there´s an empty line or ther´s not a word [2] if len(words) < 3: continue elif words[0...
import os import glob import shutil import sys # find current directory and prepare for current_path = os.getcwd() des_path = current_path + "\photos" # if directory \photos doesn't exist create one if not os.path.exists(des_path): os.makedirs(des_path) # counts the files found counter = 0 # search for .jpg .g...
import os import menu import ai import random def hasWon(board, player): win_cons = [ (0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6), ] for win_con in win_cons: if ( board[win_con[0...
deposito = float(input("Informe o valor do depósito: ")) taxa_juros = float(input("Informe a taxa de juros de uma poupança em porcentagem: ")) valor = deposito total = 0 for x in range(12): valor = valor + (deposito * taxa_juros/100) print("Mês %d: R$%.2f" % (x+1, valor)) total= total + valor print("Valor ...
num_1= int(input("Informe o primeiro número: ")) num_2= int(input("Informe o segundo número: ")) resultado = num_1 cont= 0 while resultado >= num_2: resultado = resultado - num_2 cont = cont + 1 print("A divisão de %d por %d é %d e o resto é %d" %(num_1, num_2, cont, resultado))
#finding the fixed point from a sorted array using Binary search method # fixed point is when A[i] = i and in this case it's 7 #index 0 1 2 3 4 5 6 7 8 9 A = [-10, -5, -2, 1, 3, 4, 5, 7, 9, 10 ] # if there is no Fixed point it will return None #iterative way of doing The binary search method def...
# Chapter 5, programming exercise 13 # This is an improved version of a # previous programming problem to make # it batch-oriented. def main(): print("This program will access a file and calculate the total \n number of letters, words, and \n the average word length.") fname = input("Enter filename: ") in...
# Chapter 8, programming exercise 6 # This program determines finds every prime # number less than or equal to n. import math def primeNumber(n): x = math.sqrt(n) i = 2 while i <= x: value = n % i if value == 0: return else: i = i + 1 print("The number...
# Chapter 3, Programming exercise 4 # This program calculates the distance to # a lightning strike based on the time # elapsed between the flash and the sound # of thunder. import math def main (): print("This program calculates the distance to \n a lightning strike based on the time \n between the flash and t...
# Chapter 8, programming exercise 2 # This program prints a table of windchill # values for the National Weather Service. def windchillIndex(temperature, windSpeed): if 50 >= windSpeed >= 3: windchillIndex = 35.74 + 0.6215 * temperature - (35.75 * (windSpeed ** 0.16)) + (0.4275 * temperature) * (windSpeed ...
# Chapter 6, programming exercise 3 # This program caclulates the volume # and surface area of a sphere using # functions. import math def sphereArea(radius): area = 4 * math.pi * (radius ** 2) return area def sphereVolume(radius): volume = 4/3 * math.pi * (radius ** 3) return volume def main(): ...
# Chapter 5, programming exercise 11 # This is an improved version of the # chaos.py program from Chapter 1. def main(): print("This program illustrates a chaotic function.") x = float(input("Enter a decimal number between 0 and 1: ")) y = float(input("Enter another decimal number between 0 and 1: ")...
# futval.py # A program to compute the value of an investment # carried n years into the future def main(): print("This program calculates the future value") print("of an n-year investment.") principal = eval(input("Enter the initial principal: ")) apr = eval(input("Enter the annual interest rate: ")) years = ...
# Chapter 6, programming exercise 9 # This program converts a quiz score # to the corresponding grade. def grade(score): grade = [] for i in range (0, 60): grade.append("F") for i in range (60, 69): grade.append("D") for i in range (70, 79): grade.append("C") for i in range...
""" Signal processing =================== Mostly time series. """ import numpy import pylab import scipy.signal def peaks(y,x=None,what=0,**args): """ Detects the peaks in the time series given by Y (and X if provided). :param x,y: time series input arrays :param what: select what you want -- max/0 or min/1 pe...
import numpy as np from tqdm.auto import tqdm def original_label_strategy(close, window_size=11): """ Data is labeled as per the logic in research paper Label code : BUY => 1, SELL => 2, HOLD => 0 params : df => Dataframe with data col_name => name of column which should be used to dete...
import numpy as np def flatten(x): n=len(x) return np.reshape(x, (n, -1)) # Converts integer labels to binarized labels (1-of-K coding) def binarize_labels(y, n_classes=10): new_y = np.zeros((n_classes, y.shape[0])) for i in range(y.shape[0]): new_y[y[i], i] = 1 return new_y def unbinariz...
#!/usr/bin/env python3 class Solution(object): """ leetCode 20. Valid Parentheses https://leetcode.com/problems/valid-parentheses/ """ def isValid(self, s): """ :type s: str :rtype: bool """ left, right, stack= "({[", ")}]", [] for item in s: ...
"""测试矩形的属性""" import pygame rect = pygame.Rect(100, 50, 180, 120) print("left =", rect.left) print("top =", rect.top) print("width =", rect.width) print("height =", rect.height) # right = left + width print("right =", rect.right) # bottom = top + height print("bottom =", rect.bottom) # centerx = left + width / 2 pr...
import random class Enemy(object): def __init__(self, name="Enemy", hit_points=0, lives=1) -> None: self.name = name self._hit_points = hit_points self._lives = lives def take_damage(self, damage): remaining_points = self._hit_points - damage if remaining_...
def two_sum(start, end, target, data): # returns true if two sum can be found seen = set() for i in range(start, end + 1): diff = target - data[i] if diff in seen: return True seen.add(data[i]) return False def part1(data, preamble): # returns the first number that doesn't have a two_sum ...
# total_comprehension.py my_numbers = [1, 2, 3, 4, 5, 6, 7] my_list = [n * 100 for n in my_numbers] my_list2 = [n for n in my_numbers if n > 3] my_list3 = [n for n in my_numbers if n > 8] my_list4 = [n * 100 for n in my_numbers if n > 3] print("--------------") print("ORIGINAL LIST:", my_numbers) print("------------...
#method Fibonachi import math delta = float(input()) eps = float(input()) interval = [] a = int(input()) interval.append(a) a = int(input()) interval.append(a) def f(x): return x ** 2 + 6 * x + 13 length_interval = interval[1] - interval[0] F = [1, 1] F1 = F2 = Fn = 1 while Fn < (length_interval / eps): ...
class Cell: def __init__(self, x, y): self.north = None self.east = None self.west = None self.south = None self.x = x self.y = y def get_neighbors(self): a_set = [] if self.north is None: a_set.append(0) if self.south is None ...
#!/usr/bin/env python3 import pygame, random class Bloco: def __init__(self, tela, x, y): self.tela = tela self.x = x self.y = y self.color = [random.randint(100,255),random.randint(100,255),random.randint(100,255)] self.tela.addblock(self) def move(self, x, y): ...
# http://mathworld.wolfram.com/DecimalExpansion.html # http://mathworld.wolfram.com/RepeatingDecimal.html def cycle(d): for t in range(1, d): # http://mathworld.wolfram.com/DecimalExpansion.html (7) # t = period # d = denominator if 1 == 10 ** t % d: return t # assum...
# import webbrowser # Simple browser open # webbrowser.open("https://www.github.com/Kronostheus") import requests def req(): # returns a Request object with the return value of the URL res = requests.get('https://automatetheboringstuff.com/files/rj.txt') ...
import os print "=Correct Path=" # since Windows has a different file system than Linux or OS X os.path.join() # is able to output the correct path for the current system path = os.path.join('usr', 'bin', 'spam') print path print "\n=Displaying Curent Working Directory=" # getcwd() gets current directory # chdir()...
import os import filecmp #from dateutil.relativedelta import * #from datetime import date def getData(file): file = open(file, 'r') lines = file.readlines() file.close() lines.remove(lines[0]) file_dict_list = [] for line in lines: file_dict = {} index = line.split(',') file_dict['First'] = index[0] fil...
""" I'm working on writing math formulas in python, but I'm having trouble. Can you help me fix them? Operations in Python: addition: a+b subtraction: a-b negation: -a multiplication: a*b division: a/b integer division: a//b (returns a/b with the decimals chopped off) exponentiation: a**b (...
MyString = "??первый второй третий ?? четвертый пятый шестой ?? седьмой восьмой девятый десятый" # Делим строку по пробельному символу и пишем в Список StringToWork = MyString.split(" ") # Создаем список для новой строки NewString = [] for k in StringToWork: if k != "" and k != "??": New...
# Программа 02.03 - Загадки answer = 0 answer_error = [] print("1. Тело деревянное, одежда рваная, не ест, не пьет, огород стережет.") print("\tA. Пиноккио.") print("\tБ. Огородник.") print("\tB. Пугало.") answer1 = input("Введите букву А, Б или В, соответствующую правильному ответу ") if answer1 == "В": answer += ...
try: num = 2 + 'str' print('number error') except: print('cant add') else: print('No errors') finally: print('always executed') print('continue') ,,, 2+ 2 number error No errors always executed continue 2+ 'str' cant add always executed continue '''
a=int(input('Enter a Number')) b=int(input('Enter a Number')) d=1 i=2 while True: if a%i==0 and b%i==0: a=a//i b=b//i d*=i elif a<=i or b<=i: d=d*a*b break else: i+=1 print(d)
# -*- coding: utf-8 -*- """ Created on Thu Dec 21 12:16:34 2017 @author: mikkopos """ """ Program connect text and numbers""" # Create variable "basename" basename = "station" # empty list for filenames filenames = [] # iterate over numbers and add items to list for number in range(21): #crea...
class Game(object): def __init__(self,list,Z,action="Initial",parent=False , cost = 0): self.list = list self.Z = Z self.children = [] self.cost = cost self.h=0 self.g=0 if parent== False: self.p = False self.depth = 0...
# -*- coding: utf-8 -*- """Function used to compute the loss.""" import numpy as np def compute_loss(y, tx, w): """Calculate the loss. You can calculate the loss using mse or mae. """ N = y.shape[0] dyf = y - tx.dot(w) mse = np.sum(dyf*dyf)/(2*N) #raise NotImplementedError return...
#This is a "guess the number" game import random guessesTaken = 0 print('Hello, friend! What\'s your name?') name = input() number = random.randint(1,20) print('Well, ' + name + ', I\'m thinking of a number between 1 and 20. Guess the number, and you\'ll get a prize!') while guessesTaken < 6: print('Go on, tak...
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: m = len(matrix) if m == 0: return False n = len(matrix[0]) if n == 0: return False if target < matrix[0][0] or target > matrix[m-1][n-1]: return ...
########### x^2+x+41=T ###### ########### CHARLES BABBAGE FUNCTION FOR SECOND ORDER ######## x=0 print("{}\t{}\t{}\t{}".format("D2","D1","T","X")) print("--------------------") for i in range(0,5): x=i T=(x*x)+x +41 if(i==0): print('\t\t{}\t{}'.format(T,i)) elif(i>0 and i<2): ...
def Linear_Search(My_List,key): for i in range(len(My_List)): if(My_List[i]==key): print(key,"is found at index",i) break return -1 My_List=[12,23,45,67,89] print("contents of lists are as follows:") print(My_List) key=eval(input("enter the n...
for i in range(1,10): for j in range(1,i+1): z = i*j print("%d*%d=%d\t"%(i,j,z),end = "") print()
height = int(input("请输入身高")) money = int(input("请输入身价")) face = int(input("请输入颜值")) if height >=180 and money >10000000 and face >=99: print("高富帅") elif height <175 and money >10000000 and face >=99: print("富帅") elif face >=99: print("帅") elif height <=160 and money <100 and face <60: print("渣渣")
list = [] def interface(): print("保安系统版本".center(28,"*")) print("1:新加入的人".center(30," ")) print("2:查找人名".center(30," ")) print("3:修改人名".center(30," ")) print("4:退回的人".center(30," ")) print("5:全部人名".center(30," ")) print("6:退出系统".center(30," ")) def xxx(): while True: fun_num = int(input("请选择功能")) if fun_num...
password = int(input("请输入密码")) if password == 123456: print("登录到界面") else: print("请重新输入密码")
#!/usr/bin/env python # coding: utf-8 # # File # Python allows easy access to files using the built in `open()` method. This method is used for openning both text and binary files for reading and writing. By default, the `open()` method creates an io text wrapper object for reading. Using the optional "b" param allows...
#The next two items allow us to document less #then the full functionality while containing #the full documenation when creating the code #documentation for developers using epydoc. #anything folling this token in docstrings is not #included in documentation produced with this tool. developerinfo_token = "#dev-only#" ...
def numinput(prompt): value = str(input(prompt)) try: value = int(value) return value except ValueError: try: value = float(value) return value except: print('That\'s not a valid value. Please enter a numeric value. Try again.') ...
import pandas as pd import numpy as np # Resources # - https://www.youtube.com/watch?v=1uVWjdAbgBg ''' - Think of DataFrame similar to a row and column spreadsheet but formed from a group of series arrays - Remember indexes are NOT columns because you cant select an entire column. - If you get an "copy" error your mi...
# Resources # - https://docs.python.org/2/library/math.html import math import numpy as np # --- Constants --- # math.pi # pi = 3.141592..., to available precision. math.e # e = 2.718281..., to available precision # --- Trigonometric functions --- # # Return the Euclidean norm, sqrt(x*x + y*y). # This is the l...
import numpy as np # Create np.array([2,3,4]) np.array([[1, 2, 3], [4, 5, 6]], float) # Multi-dimensional array # List Generation np.arange(12) # [0 1 2 3 4 5 6 7 8 9 10 11] np.arange(15,30) # [15 16 17 18 19 20 21 22 23 24 25 26 27 28 29] np.arange(1,4, 0.5) # [1. 1.5 2. 2.5 3. 3.5] np.arange(...
# Resources # - http://scikit-learn.org/0.11/datasets/index.html ''' shape = features * samples samples = how many things you are testing features = attributes you are measured - flowers: petal with, colors - handwriting: 8x8 pixel grid - 64 features Labels/target classes - flowers: different types of flowers - hand...
# http://www.pythoncentral.io/introduction-to-tweepy-twitter-for-python/ # http://altons.github.io/python/2013/01/21/gentle-introduction-to-mongodb-using-pymongo/ from pymongo import MongoClient client = MongoClient() db = client.pymongo doc = {"name":"Alberto","surname":"Negron","twitter":"@Altons"} db.twitter.inse...
import random import string # answer = "methinks it is like a weasel" answer = "life is like a box of chocolates" def infiniteMonkey(answer): length = len(answer) letters = string.ascii_letters[0:26] + " " # Initial string generation attempt = "" for index in range(length): char = random...
#~ Ejercicio 1 print "Por favor indique la cantidad de numeros que quieres asignar" numeros = input() lista = [] for i in range (numeros): numero2= raw_input ("Digame el numero " + str(i+1) + " ") lista.append(numero2) print "La Primera lista es: " , lista nuevalist = [] inicio = 0 for i in lista: inicio =...
''' Return all non-negative integers of length N such that the absolute difference between every two consecutive digits is K. Note that every number in the answer must not have leading zeros except for the number 0 itself. For example, 01 has one leading zero and is invalid, but 0 is valid. You may return the a...
''' Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Examp...
''' Sort entries in a tabular BLAST output file in reverse order. ----------------------------------------------------------- (c) 2013 Allegra Via and Kristian Rother Licensed under the conditions of the Python License This code appears in section 8.4.2 of the book "Managing Biological Data with Python". ...
import math data = [3.53, 3.47, 3.51, 3.72, 3.43] average = sum(data) / len(data) total = 0.0 for value in data: total += (value - average) ** 2 stddev = math.sqrt(total / len(data)) print(stddev) data = [3.53, 3.47, 3.51, 3.72, 3.43] data.sort() mid = len(data) / 2 if len(data) % 2 == 0: median = (data[mid -...
''' Remove duplicates from a file with accession numbers Using a set (faster but distorts order). ----------------------------------------------------------- (c) 2013 Allegra Via and Kristian Rother Licensed under the conditions of the Python License This code appears in section 6.3.4 of the book "Managi...