text
stringlengths
37
1.41M
import random from datetime import datetime # Get the current time and hope that the user set their clock correctly. # h is current hour and m is current minute. h = datetime.now().hour m = datetime.now().minute # n is the (sudo)random number being generated and used for decisions. n = random.randint(1,7) print('Your computer has made the decision for you!') print('Now go to:') # Lazy options (doesn't require leaving campus, even for the sandwich shop). if (n==1): print('Library Cafe') elif (n==2): print('JCR') # Meh options (fairly close to campus). elif (n==3): print('Sandwich shop') elif (n==4): print('Chopstix') elif (n==5): print('Tesco') elif (n==6): print('Burger King') # Adventure options (Prepared to go a long way for food). elif (n==7): print('McDonalds')
# 404. Sum of Left Leaves # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int """ self.sum = 0 self.calculatesum(root) return self.sum def calculatesum(self,root): if root is None: return root if root.left is not None: if root.left.left is None and root.left.right is None: self.sum = self.sum + root.left.val self.calculatesum(root.left) self.calculatesum(root.right)
listdata = [9.96, 1.27, 5.07,6.45, 8.38, 9.29] maxval = max(listdata) minval = min(listdata) print(maxval);print(minval) print('----------------------') txt = 'Alotofthingsoccuerachday' maxval = max(txt) minval = min(txt) print(maxval);print(minval) print('----------------------') maxval = max(2+3, 2*3, 2**3, 3**2) minval = min('abz','a12') print(maxval);print(minval)
listdata=[1,2,3,4] ret1=5 in listdata ret2=2 in listdata print(ret1);print(ret2) strdata='abcde' ret3='c' in strdata ret4='j' in strdata print(ret3);print(ret4)
# 阿当姆斯法 def f(ex, ey): return -ey + ex + 1 N = 11 # 求解次数 h = 0.1 # 步长 y = 1 # y(0)的值为0 def init(y0): n = 0 x0 = 0 ret = [] while 3 > n: x1 = x0 + h k1 = f(x0, y0) k2 = f(x0 + h / 2, y0 + (h / 2) * k1) k3 = f(x0 + h / 2, y0 + (h / 2) * k2) k4 = f(x1, y0 + h * k3) y1 = y0 + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4) print("x{0}={1:0.1f}\t\t\t y{0}={2:0.6f}".format(n+1, x1, y1)) ret.append(y1) n = n + 1 x0 = x1 y0 = y1 return ret re = init(y) ya = re[0] yb = re[1] yc = re[2] i = 3 while i < N: x = i * h yex = yc + (h / 24) * (55 * f(x, yc) - 59 * f(x-h, yb) + 37*f(x-2*h, ya) - 9*f(x-3*h, y)) yim = yc + (h / 24) * (9 * f(x, yex) + 19 * f(x - h, yc) - 5 * f(x - 2 * h, yb) + f(x - 3 * h, ya)) print("x{0}={1:0.1f}\t 显式:y{0}={2:0.6f}\t 隐式:y{0}={3:0.6f}".format(i, x, yex, yim)) y = ya ya = yb yb = yc yc = yim i = i + 1
# Created by RANVIR 04/06/16 #While confi Hardware keep -ve Terminal of Led pin is comman #And connect +ve termina to each pin Of GPIO #As arrange your led accoroding to that place gpio pin list in Pinlist variable import RPi.GPIO as GPIO # Importing RPi as Gpio import time #importing time for dealy control GPIO.setmode(GPIO.BCM) #setting board mode as Board/BCM pinList=[26,19,13,6,5,21,20,16] #Output Pin Decleration for i in pinList: # setting pin out put GPIO.setup(i,GPIO.OUT) def oneByOne(rpt,delay): #Function to glow led on by one for j in range(0,rpt): #Outer loop to controle no of itiration for i in pinList: #Inner loop to controle Led Output GPIO.output(i,GPIO.HIGH) print(" Led "+str(i)+" on") time.sleep(delay) GPIO.output(i,GPIO.LOW) print(" Led "+str(i)+" off") print("Quit") #oneByOne(int(rep),float(delay)) def allOnOneByOne(rpt,delay): #Function to glow led on onc all on then off for j in range(0,rpt): #Outer loop to controle no of itiration for i in pinList: #Inner loop to turn On Led GPIO.output(i,GPIO.HIGH) print(" Led "+str(i)+" on") time.sleep(delay) for i in pinList: #Inner loop to turn Off Led GPIO.output(i,GPIO.LOW) print(" Led "+str(i)+" off") time.sleep(delay) print("Quit") #allOnOneByOne(int(rep),float(delay)) def mainfun(): #Main Function to control user choice men=raw_input("Menu: Please Enter Your Choice \n 1. for One By One Scan \n 2. For On All Onec Then Off \n ") if(int(men)==1): #if User Gives Input 1 then Calling first function rep=raw_input("Enter No Of Repetation= ") delay=raw_input("Enter delay In Sec= ") oneByOne(int(rep),float(delay)) else: #if User Gives Input 2 then Calling Second function rep=raw_input("Enter No Of Repetation= ") delay=raw_input("Enter delay In Sec= ") allOnOneByOne(int(rep),float(delay)) GPIO.cleanup() mainfun() #calling Main function
from abc import ABC, abstractmethod class AbstractClass(ABC): @abstractmethod def do_something(self): print("Some implementation!") # class DoAdd42(AbstractClass): # def do_something(self): # return self.value + 42 # # # class DoMul42(AbstractClass): # def do_something(self): # return self.value * 43 class AnotherSubclass(AbstractClass): def do_something(self): super().do_something() print("Some other!") # x = DoAdd42(1) # y = DoMul42(10) z = AnotherSubclass() print(z.do_something()) # print(x.do_something()) # print(y.do_something())
""" Employee class """ from classes.Qualification import Qualification class Employee: def __init__(self, employee_id, first_name, last_name, ssn, phone, address, city, state, postal_code, employed_by, position, salary, qualifications): self.employee_id: int = employee_id self.first_name: str = first_name self.last_name: str = last_name self.ssn: str = ssn self.phone: str = phone self.address: str = address self.city: str = city self.state: str = state self.postal_code: str = postal_code self.employed_by: str = employed_by self.position: str = position self.salary: int = salary self.qualifications: [Qualification] = qualifications def add_qualification(self, qualification): self.qualifications.append(qualification) def remove_qualification(self, qualification): self.qualifications.remove(qualification) def __str__(self): return ( f"Details for {self.first_name} {self.last_name} ({self.employee_id}):\n" f"\tSocial Security Number: {self.ssn}\n" f"\tPhone Number: {self.phone}\n" f"\tAddress: {self.address} {self.city}, {self.state} {self.postal_code}\n" f"\tEmployer: {self.employed_by}\n" f"\tPosition: {self.position}\n" f"\tSalary: {self.salary}\n" f"\tQualifications: {self.qualifications}" )
__author__="najib" """from chatterbot import ChatBot from chatterbot.trainers import ListTrainer #create a new chat bot Chatnajib = ChatBot("Bot") #training my chatbot bot starts with knowledge from chatterbot.trainers import ListTrainer conversation = ["hello", "hi there!", "how are you?", "great hamdollah", "thank u", "u'are welcom."] trainer = ListTrainer(chatnajib) trainer.train(conversation) #get a reponse reponse = chatnajib.get_response("Good morning") print(reponse)""" from chatterbot import ChatBot chatbot = ChatBot("Ron Obvious") from chatterbot.trainers import ListTrainer conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome." ] trainer = ListTrainer(chatbot) trainer.train(conversation) response = chatbot.get_response("Good morning!") print(response)
import pandas as pd from sklearn import linear_model dataset = pd.read_csv('salary.csv') print("Rows:",dataset.shape[0],"Columns:",dataset.shape[1]) #separating out independent variable X=dataset.iloc[:,:-1].values Y=dataset.iloc[:,1].values #print(X,"\n\n",Y) #splitting dataset into training and test set from sklearn.cross_validation import train_test_split X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0,random_state=0) #print("test X:",X_test,"\ntrain X:\n",X_train) #print("test Y:",Y_test,"\ntrain Y:",Y_train) print(X_train,X_test,Y_train,Y_test) n=len(X_train) sX,sY,sX2,sY2,sXY=0,0,0,0,0 for i in range(n): sX=sX+X_train[i] sY=sY+Y_train[i] sX2=sX2+X_train[i]**2 sY2=sY2+Y_train[i]**2 sXY=sXY+X_train[i]*Y_train[i] #Calculate slope for equation m=(n*sXY-sX*sY)/(n*sX2-sX**2) #Calculate intercept a=(sY/n)-m*(sX/n) #equation print("Equation: ",a,"+",m,"X") #predicting values from test values( test_set) Y_pred=[] #predicted list for i in X_test: pred=a+m*i Y_pred.append(pred) print("Actual:",Y_test,"\nPredicted:",Y_pred) #Finding accuracy x,y=0,0 mean=sY/n for i in range(len(Y_test)): x=x+(Y_pred[i]-mean)**2 y=y+(Y_test[i]-mean)**2 Accuracy=x/y print("Accuracy:",Accuracy*100)
#!/usr/bin/python3 def uniq_add(my_list=[]): history = [] sum = 0 for i in range(len(my_list)): if i == 0: history.append(my_list[i]) sum += my_list[i] if history.count(my_list[i]) == 0: sum += my_list[i] history.append(my_list[i]) return sum
# Introduction to Programming Project 1 # Author: Reisha Puranik # Date: October 11, 2019 def process(eq, op): if op == '/': print("here",eq) index = eq.index('/') op1 = float(eq[index - 1]) op2 = float(eq[index + 1]) result = op1 / op2 del(eq[index - 1:index + 2]) eq.insert(index-1, result) elif op == '*': index = eq.index('*') op1 = float(eq[index - 1]) op2 = float(eq[index + 1]) result = op1 * op2 del(eq[index - 1:index + 2]) eq.insert(index-1, result) elif op == '+': index = eq.index('+') op1 = float(eq[index - 1]) op2 = float(eq[index + 1]) result = op1 + op2 del(eq[index - 1:index + 2]) eq.insert(index - 1, result) elif op == '-': index = eq.index('-') op1 = float(eq[index - 1]) op2 = float(eq[index + 1]) result = op1 - op2 del(eq[index - 1:index + 2]) eq.insert(index-1, result) else: print("Invalid operation") def memory(eqStr): mem = result if op == 'M+': return result + mem elif op == 'M-': return result - mem elif op == 'MR': return result elif op == 'MC': print(" ") def solve(eqStr): eq = eqStr.split() while len(eq) > 1: if '/' in eq: process(eq, '/') elif '*' in eq: process(eq, '*') elif '+' in eq: process(eq, '+') elif '-' in eq: process(eq, '-') return eq[0]
# Python3 implementation to check if # both halves of the string have # at least one different character MAX = 26 # Function which break string into two # halves Increments frequency of characters # for first half Decrements frequency of # characters for second half true if any # index has non-zero value def function(st): global MAX l = len(st) # Declaration and initialization # of counter array counter = [0] * MAX for i in range(l // 2): counter[ord(st[i]) - ord('a')] += 1 for i in range(l // 2, l): counter[ord(st[i]) - ord('a')] -= 1 for i in range(MAX): if (counter[i] != 0): return True return False # Driver function st = "abcasdsabcae" if function(st): print("Yes, both halves differ by at ", "least one character") else: print("No, both halves do not differ at all") # This code is contributed by Ansu Kumari
def odd_even(val): a=val if a%2=0: return("even") else: return("odd") value= int(input("enter any integer:")) read=odd_even(value) print(read)
# -*- coding: utf-8 -*- """ Created on Sun Jan 21 20:22:18 2018 @author: jwright.06 """ a = 0 b = 0 for x in range(1,101): a += x**2 b += x c = b**2 - a print(c)
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ def gcd(a,b): r = a % b while r != 0: a = b b = r r = a % b return b def div(): x = 2 y = 3 while y < 21: if gcd(x,y) == 1: x = x * y y = y + 1 if gcd(x,y) != 1: x = x * y/gcd(x,y) y = y + 1 return x p = div() print(p)
""" File: titanic_survived.py Name: Chia-Lin Ko ---------------------------------- This file contains 3 of the most important steps in machine learning: 1) Data pre-processing 2) Training 3) Predicting """ import math TRAIN_DATA_PATH = 'titanic_data/train.csv' NUM_EPOCHS = 1000 ALPHA = 0.01 def sigmoid(k): """ :param k: float, linear function value :return: float, probability of the linear function value """ return 1/(1+math.exp(-k)) def dot(lst1, lst2): """ : param lst1: list, the feature vector : param lst2: list, the weights : return: float, the dot product of 2 list """ return sum(lst1[i]*lst2[i] for i in range(len(lst1))) def main(): # Milestone 1 training_data = data_pre_processing() # ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'] weights = [0]*len(training_data[0][0]) # Milestone 2 training(training_data, weights) # Milestone 3 predict(training_data, weights) # Milestone 1 def data_pre_processing(): """ Read the training data from TRAIN_DATA_PATH and get ready for training! :return: list[Tuple(data, label)], the value of each data on (['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'], 'Survived') """ training_data = [] with open(TRAIN_DATA_PATH, 'r') as f: is_first = True for line in f: if is_first: is_first = False else: feature_vector, label = feature_extractor(line) training_data.append((feature_vector, label)) return training_data def feature_extractor(line): """ : param line: str, the line of data extracted from the training set : return: list, the feature vector """ data_list = line.split(',') feature_vector = [] label = int(data_list[1]) # ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'] for i in range(len(data_list)): if i == 2: # Pclass feature_vector.append((int(data_list[i])-1)/(3-1)) elif i == 5: # Gender if data_list[i] == 'male': feature_vector.append(0) else: feature_vector.append(1) elif i == 6: # Age if data_list[i].isdigit(): feature_vector.append((float(data_list[i])-0.42)/(80-0.42)) else: feature_vector.append((29.699-0.42)/(80-0.42)) # average age elif i == 7: # SibSp feature_vector.append((int(data_list[i])-0)/(8-0)) elif i == 8: # Parch feature_vector.append((int(data_list[i])-0/(6-0))) elif i == 10: # Fare feature_vector.append((float(data_list[i])-0)/(512.33-0)) elif i == 12: # Embarked if data_list[i] == 'C': feature_vector.append((0-0)/2) elif data_list[i] == 'Q': feature_vector.append((2-0)/2) else: # S and missing value feature_vector.append((1-0)/2) return feature_vector, label # Milestone 2 def training(training_data, weights): """ : param training_data: list[Tuple(data, label)], the value of each data on (['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'], 'Survived') : param weights: list[float], the weight vector (the parameters on each feature) """ for epoch in range(NUM_EPOCHS): cost = 0 for x, y in training_data: ################################# h = sigmoid(dot(x, weights)) cost += -(y*math.log(h)+(1-y)*math.log(1-h)) # w = w - alpha * dL_dw # wi = wi - alpha * (h-y)*xi for i in range(len(x)): weights[i] = weights[i] - ALPHA * (h-y) * x[i] ################################# cost /= (2*len(x)) if epoch%100 == 0: print('Cost over all data:', cost) # Milestone 3 def predict(training_data, weights): """ : param training_data: list[Tuple(data, label)], the value of each data on (['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'], 'Survived') : param weights: list[float], the weight vector (the parameters on each feature) """ acc = 0 num_data = 0 for x, y in training_data: predict = get_prediction(x, weights) print('True Label: ' + str(y) + ' --------> Predict: ' + str(predict)) if y == predict: acc += 1 num_data += 1 print('---------------------------') print('Acc: ' + str(acc / num_data)) def get_prediction(x, weights): """ : param x: list[float], the value of each data on ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'] : param weights: list[float], the weight vector (the parameters on each feature) : return: float, the score of x (if it is > 0 then the passenger may survive) """ k = dot(x, weights) h = sigmoid(k) if h > 0.5: return 1 else: return 0 ''' # other solution if k > 0: return 1 else: return 0 ''' if __name__ == '__main__': main()
""" File: guess_my_number.py Name: ----------------------------- This program plays a Console game "Guess My Number" which asks user to input a number until he/she gets it """ # This number controls when to stop the game import numpy as np SECRET = int(np.random.random_sample()*100) #SECRET = 0 def main(): print('Guess a number from 0-99') while True: guess = int(input('Your guess: ')) if guess < SECRET: print ('Too low') elif guess == SECRET: break else: print ('Too high') print('Congrats! The secret is ' + str(SECRET)) # other solution # guess = int(input('Your guess: ')) # while guess != SECRET: # if guess > SECRET: # print ('Too big') # else: # print ('Too small') # guess = int(input('Your guess: ')) # print ('Congrats! The secret is ' + str(SECRET)) ### DO NOT EDIT THE CODE BELOW THIS LINE ### if __name__ == '__main__': main()
""" File: how_many_lines.py Name: Jerry Liao 2020/09 --------------------------- This file shows how to calculate the number of lines in romeojuliet.txt by Python code """ # This constant shows the file path to romeojuliet.txt FILE = 'text/romeojuliet.txt' def main(): """ This program prints the number of lines in romeojuliet.txt on Console """ count = 0 with open(FILE, 'r') as f: for line in f: count += 1 print('There are ' + str(count) + ' lines in '+str(FILE)) if __name__ == '__main__': main()
""" File: find_max.py Name: -------------------------- This program finds the maximum among all the user inputs. Students can refer to this file when they are doing Problem 2 in Assignment 2 """ # This constant controls when to stop EXIT = -1 def main(): """ This program finds the maximum among user inputs """ print('This program finds the maximum (or -1 to quit)') data = int(input('Your data:')) # This is the first data if data == EXIT: print('No Number') else: maximum = data while True: data = int(input('Value:')) if data == EXIT: break if data > maximum: maximum = data print(maximum) ### DO NOT EDIT THE CODE BELOW THIS LINE ### if __name__ == '__main__': main()
""" File: caesar.py Name: Chia-Lin Ko ------------------------------ This program demonstrates the idea of caesar cipher. Users will be asked to input a number to produce shifted ALPHABET as the cipher table. After that, any strings typed in will be encrypted. """ # This constant shows the original order of alphabetic sequence. ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): """ This program demonstrates the idea of caesar cipher. """ secret_num = int(input('Secret number: ')) cipher = str(input('What\'s the ciphered string? ')) ans = decipher(cipher, secret_num) print('The deciphered string is: ' + str(ans)) def decipher(cipher, secret_num): """ purpose: Decipher the cipher by the given secret number :param cipher: str, the input cipher :param secret_num: int, the secret number :return ans: int, the deciphered string """ # new_alphabet (given the input secret number) new_alphabet = '' for i in range(len(ALPHABET)): new_alphabet += ALPHABET[i-secret_num] # decipher ans = '' # case-insensitive cipher = cipher.upper() for i in range(len(cipher)): cipher_seg = cipher[i] if cipher_seg.isalpha(): ans += ALPHABET[new_alphabet.find(cipher_seg)] else: ans += cipher_seg return ans ##### DO NOT EDIT THE CODE BELOW THIS LINE ##### if __name__ == '__main__': main()
""" File: flip_horizontally.py Name: ------------------------------------ This program shows how to create an empty SimpleImage as well as making a mirrored image of poppy.png by inserting old pixels into the blank new canvas """ from simpleimage import SimpleImage def main(): img = SimpleImage("images/poppy.png") img.show() new_img = SimpleImage.blank(img.width*2, img.height) for x in range(img.width): for y in range(img.height): # Original Image img_pixel = img.get_pixel(x, y) # New Image new_img_pixel1 = new_img.get_pixel(x, y) new_img_pixel2 = new_img.get_pixel(new_img.width-1-x, y) new_img_pixel1.red = img_pixel.red new_img_pixel1.green = img_pixel.green new_img_pixel1.blue = img_pixel.blue new_img_pixel2.red = img_pixel.red new_img_pixel2.green = img_pixel.green new_img_pixel2.blue = img_pixel.blue new_img.show() if __name__ == '__main__': main()
""" File: bouncing_ball.py Name: Chia-Lin Ko ------------------------- This program simulates a bouncing ball at (START_X, START_Y) that has VX as x velocity and 0 as y velocity. Each bounce reduces y velocity to REDUCE of itself. """ from campy.graphics.gobjects import GOval from campy.graphics.gwindow import GWindow from campy.gui.events.timer import pause from campy.gui.events.mouse import onmouseclicked # Constant VX = 3 DELAY = 10 GRAVITY = 1 SIZE = 20 REDUCE = 0.9 START_X = 30 START_Y = 40 CLICK_NUM_LIMIT = 3 WINDOW_WIDTH = 800 WINDOW_HEIGHT = 500 # Global variable click_num = 0 ball_x = START_X ball_y = START_Y window = GWindow(WINDOW_WIDTH, WINDOW_HEIGHT, title='bouncing_ball.py') def main(): """ This program simulates a bouncing ball at (START_X, START_Y) that has VX as x velocity and 0 as y velocity. Each bounce reduces y velocity to REDUCE of itself. """ # set up the initial ball ball = setup_ball() onmouseclicked(bouncing_ball) def setup_ball(): """ This function sets the initial condition of the ball """ ball = GOval(SIZE, SIZE, x=START_X, y=START_Y) ball.filled = True window.add(ball) return ball def bouncing_ball(mouse): """ This function display the bouncing ball :param mouse: """ global click_num, ball_x, ball_y # remove the initial ball ball_remove = window.get_object_at(START_X+SIZE/2, START_Y) window.remove(ball_remove) # the initial condition of the ball when clicking the mouse if ball_x == START_X: ball = setup_ball() vy = 0 # no response for clicking the mouse when the ball is bouncing else: return None # move the ball while click_num < 3: if ball_x > WINDOW_WIDTH: click_num +=1 ball_x = START_X ball = setup_ball() break else: ball.move(VX, vy) ball_x += VX # ball is falling if ball.y < (WINDOW_HEIGHT-SIZE): vy += GRAVITY # ball is bouncing else: if vy > 0: vy = -vy * REDUCE pause(DELAY) if __name__ == "__main__": main()
""" File: my_power_function.py Name: Chia-Lin Ko ------------------------------- This program shows students how to make their own functions by defining def my_power(a, b) """ def main(): print('This program prints a to the power of b.') a = int(input('a: ')) b = int(input('b: ')) print(my_power(a, b)) def my_power(a, b): """ :param a: int, a>0 :param b: int, b>=0 :return : int, a**b """ ans = 1 for i in range(b): ans*=a return ans if __name__ == '__main__': main()
from karel.stanfordkarel import * """ File: CollectNewspaperKarel.py Name: Chia-Lin Ko -------------------------------- This program instructs Karel to walk to the door of its house, pick up the newspaper (represented by a beeper, of course), and then return to its initial position in the upper left corner of the house. """ def main(): """ purpose: Karel will move to the (6,3) from (3,4), pick up the newspaper (beeper), and bring the newspaper back to the initial position of (3,4). pre-condition: Karel is at (3,4), facing East. post-condition: Karel is at (3,4), facing East with the newspaper (beeper). """ move_to_newspaper() bring_newspaper_home() def move_to_newspaper(): """ purpose: Karel will move to the (6,3) from (3,4). pre-condition: Karel is at (3,4), facing East. post-condition: Karel is at (6,3), facing East. """ turn_right() move() turn_left() # facing East move() move() move() def bring_newspaper_home(): """ purpose: Karel will pick up the newspaper (beeper) and bring the newspaper back to the initial position of (3,4). pre-condition: Karel is at (6,3), facing East. post-condition: Karel is at (3,4), facing East with the newspaper (beeper). """ pick_beeper() turn_around() # facing West move() move() move() turn_right() # facing North move() turn_right() put_beeper() # facing East def turn_right(): """ This function turns Karel to the left 3 times. """ for i in range(3): turn_left() def turn_around(): """ This function turns Karel to the left 2 times. """ for i in range(2): turn_left() # DO NOT EDIT CODE BELOW THIS LINE # if __name__ == '__main__': execute_karel_task(main)
""" File: titanic_level1.py Name: ---------------------------------- This file builds a machine learning algorithm from scratch by Python codes. We'll be using 'with open' to read in dataset, store data into a Python dict, and finally train the model and test it on kaggle. This model is the most flexible one among all levels. You should do hyperparameter tuning and find the best model. """ import math TRAIN_FILE = 'titanic_data/train.csv' TEST_FILE = 'titanic_data/test.csv' def data_preprocess(filename: str, data: dict, mode='Train', training_data=None): """ :param filename: str, the filename to be processed :param data: dict[str: list], key is the column name, value is its data :param mode: str, indicating the mode we are using :param training_data: dict[str: list], key is the column name, value is its data (You will only use this when mode == 'Test') :return data: dict[str: list], key is the column name, value is its data """ ############################ # # # TODO: # # # ############################ return data def one_hot_encoding(data: dict, feature: str): """ :param data: dict[str, list], key is the column name, value is its data :param feature: str, the column name of interest :return data: dict[str, list], remove the feature column and add its one-hot encoding features """ ############################ # # # TODO: # # # ############################ return data def normalize(data: dict): """ :param data: dict[str, list], key is the column name, value is its data :return data: dict[str, list], key is the column name, value is its normalized data """ ############################ # # # TODO: # # # ############################ return data def learnPredictor(inputs: dict, labels: list, degree: int, num_epochs: int, alpha: float): """ :param inputs: dict[str, list], key is the column name, value is its data :param labels: list[int], indicating the true label for each data :param degree: int, degree of polynomial features :param num_epochs: int, the number of epochs for training :param alpha: float, known as step size or learning rate :return weights: dict[str, float], feature name and its weight """ # Step 1 : Initialize weights weights = {} # feature => weight keys = list(inputs.keys()) if degree == 1: for i in range(len(keys)): weights[keys[i]] = 0 elif degree == 2: for i in range(len(keys)): weights[keys[i]] = 0 for i in range(len(keys)): for j in range(i, len(keys)): weights[keys[i] + keys[j]] = 0 # Step 2 : Start training # TODO: # Step 3 : Feature Extract # TODO: # Step 4 : Update weights # TODO: return weights
from cs50 import get_int def main(h): # Asks for input while h is smaller or equal to 0 or bigger then 8 while h <= 0 or h > 8: h = get_int("Height: ") # determine width w = h # create piramid for i in range(1, h+1): space = w - i print(" " * space, end="") print("#" * i, end="") print(" ", end="") print("#" * i) if __name__ == "__main__": main(0)
#coding: utf-8 #author:hx ''' ZeroDivisionError 除(或取模)零 (所有数据类型) AttributeError 对象没有这个属性 #open('str.txt','r') FileNotFoundError找不到文件 ImportError 导入模块/对象失败 IndexError 序列中没有此索引(index) KeyError映射中没有这个键( 元组) NameError 未声明/初始化对象 (没有属性) SyntaxError Python 语法错误 IndentationError 缩进错误 TypeError 对类型无效的操作 ValueError 传入无效的参数 ''' ''' 捕获异常的语法结构: try: <语句> #运行别的代码 except <异常名>: <语句> #如果在try部份引发了'name'异常 except <异常名>,<数据>: <语句> #如果引发了'name'异常,获得附加的数据 else: <语句> #如果没有异常发生 finally: #始终会被执行到的代码 <语句> 以上为完整结构,使用的时候至少要有一个try和except代码块。 ''' # # try: # int=2 # except ValueError as e: # print('处理了异常:',e) # else: # print('无异常') # raise TypeError class myException(Exception) : pass [['a',1],['a',2],['b',1],['b',2],...] list1=['a','b','c'] list2=[1,2,3,5] new_list=[] try: for m in list1: for n in list2: if n==3: raise myException new_list.append([m,n]) except myException: pass print(new_list)
class Washer: def __init__(self, water=15, scour=5): self.water = water self.scour = scour def set_water(self, water): self.water = water def set_scour(self, scour): self.scour = scour def add_water(self): print('Add water', self.water) def add_scour(self): print('Add scour', self.scour) def start_wash(self): self.add_water() self.add_scour() print('start wash...') if __name__ =='__main__': #不传递值时,执行默认值 # w = Washer() # w.start_wash() #传递值 wb = Washer(100, 10) #用户修改 wb.set_water(50) wb.set_scour(10) wb.start_wash()
#coding: utf-8 #author: hexi #实例1 #break mystr="asdfghjkl" for i in mystr: if i=='h': break print(i) print("执行成功") #continue ''' mystr="asdfghjkl" for i in mystr: if i=='h': continue print(i) print("执行成功") ''' #实例2 list1=[1,3,5,7] list2=[2,4,6,8] new_list=list() for i in list1: for j in list2: if j==6: break #exit() #退出整个程序 new_list.append([i,j]) else: break print(new_list)
''' FIFO (First in First out) implementation of a queue using circular lists when we deque an element and want to advance the front index use the arithmetic f = (f + 1) % N where N is the size of the list ''' class ArrayQueue: '''Fifo queue implementatio using a Python list as underlying storage.''' DEFAULT_CAPACITY = 10 #queue size def __init__(self): '''create an empty queue.''' self._data = [None]*ArrayQueue.DEFAULT_CAPACITY self._size = 0 #current size of the queue (number of elements present) self._front = 0 #init the front to be 0 def __len__(self): '''Return teh number of elements in the queue.''' return self._size def is_empty(self): '''return true if the queue is empty.''' return self._size == 0 def first(self): '''return but do not remove the element at the front of the queue. raise an exception if the queue is empty.''' if self.is_empty(): raise Empty('Queue is empty') #Empty class from arrayStack.py return self._data[self._front] def dequeue(self): '''remove and return the first elemtent of the queue FIFO raise exception if the queue is empty''' if self.is_empty(): raise Empty('Queue is empty') answer = self._data[self._front] self._data[self._front] = None # help garbade collection, reclaim unused space self._front = (self._front + 1) % len(self._data) #circular implementation self._size -= 1 return answer def enqueue(self, e): '''add an element to the back of the queue.''' if self._size == len(self._data): self._reisze(2*len(self._data)) #double the array size avail = (self._front + self._size) % len(self._data) #compute location of the next opening based on this formula self._data[avail] = e self._size += 1 def _resize(self, cap): '''resize to a new list of capacity >= len(self).''' old = self._data #keep track of existing list self._data = [None]*cap #allocate list withn new capacity walk = self._front for k in range(self._size): #only consider existing elements self._data[k] = old[walk] #shift indices walk = (1 + walk) % len(old) self._front = 0 #front has been realigned
import numpy as np from random import sample #Used for random initialization def choose_k_random_centroids(X, K): """ Function to return K random centroids from the training examples """ random_indices = sample(range(0,X.shape[0]),K) return np.array([X[i] for i in random_indices])
import pygame # ----------- Game Initialization ------------------- pygame.init() displayWidth, displayHeight = 700, 800 gameDisplay = pygame.display.set_mode((displayWidth, displayHeight)) pygame.display.set_caption('Basic Pygame Template') clock = pygame.time.Clock() # ----------- Constants --------------- FPS = 60 backgroundColor = "black" # ----------- Main Game Function --------------- def runGame(): # Game Variables gameRunning = True gameOver = False # ----------- Start Of Game Loop --------------- while gameRunning: gameDisplay.fill(backgroundColor) # ----------- Game Over Menu ------------------- # Use this loop as a template for any other screens you want to add. while gameOver == True: pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: gameOver = False gameRunning = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameRunning = False gameOver = False if event.key == pygame.K_c: runGame() # ----------- Gameplay Handling ------------------- for event in pygame.event.get(): if event.type == pygame.QUIT: gameRunning = False if event.type == pygame.MOUSEBUTTONUP: print(f'Mouse was clicked at {pygame.mouse.get_pos()}') if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT or event.key == ord('a'): print('left') if event.key == pygame.K_RIGHT or event.key == ord('d'): print('right') if event.key == pygame.K_UP or event.key == ord('w'): print('up') if event.key == pygame.K_DOWN or event.key == ord('s'): print('down') if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == ord('a'): print('left stop') if event.key == pygame.K_RIGHT or event.key == ord('d'): print('right stop') if event.key == pygame.K_UP or event.key == ord('w'): print('up stop') if event.key == pygame.K_DOWN or event.key == ord('s'): print('down stop') if event.key == ord('q'): pygame.quit() gameRunning = False exit() # ----------- Game Code ------------------- # Draw # Update pygame.display.update() clock.tick(FPS) if __name__ == "__main__": runGame()
class SimpleBudget: def __init__(self, category, balance): self.balance = balance self.category = category def __str__(self): return f"A {self.category} budget with N{self.balance}" #methods def deposit(self, amount): self.balance += amount print(f"You have successfully deposited N{amount}. Your new balance is N{self.balance}") return self.balance def check_balance(self, amount): if self.balance < amount: return False else: return True def withdraw(self, amount): if self.check_balance(amount) == True: self.balance -= amount print(f"You have successfully withdrawn N{amount}. Your new balance is N{self.balance}") return self.balance else: return "Insufficient Funds. Check balance" def transfer(self, amount, category): if self.check_balance(amount) == True: self.balance -= amount category.balance += amount return f"You have successfully transferred N{amount} to {category.category}" else: return "Insufficient Funds. Check your balance"
ix=1 while ix < 4: print(ix) if ix== 5: break ix +=1 else: print("Else part")
import unittest class Vertex(object): def __init__(self, name): self.neighbors = [] self.name = name def __str__(self): return self.name def bfs(adj): visited = [] for v in adj: to_visit = [v] while to_visit != []: v = to_visit.pop(0) if v not in visited: visited.append(v) for u in v.neighbors: if u not in to_visit: to_visit.append(u) return visited class Test_bfs(unittest.TestCase): def test_bfs_empty(self): adj = [] bfs(adj) def test_bfs_one(self): adj = [Vertex("a")] bfs(adj) def test_bfs_five(self): a = Vertex("a") b = Vertex("b") c = Vertex("c") d = Vertex("d") e = Vertex("e") a.neighbors = [b, c] b.neighbors = [a, e] c.neighbors = [b, d, e] d.neighbors = [a, e] e.neighbors = [b, c] adj = [a, b, c, d, e] self.assertEqual(bfs(adj), [a, b, c, e, d]) if __name__ == "__main__": unittest.main()
import unittest class Node(object): def __init__(self): self.data = None self.node1 = None self.node2 = None def transform(root): if root is None: return root begin, end = _transform(root) return begin def _transform(root): if root is None: return None, None left_begin, left_end = _transform(root.node1) right_begin, right_end = _transform(root.node2) if left_end is not None: _merge(left_end, root) if right_begin is not None: _merge(root, right_begin) if left_begin is None: left_begin = root if right_end is None: right_end = root return left_begin, right_end def _merge(a, b): b.node1 = a a.node2 = b class Test_linked_list(unittest.TestCase): def test_none(self): node = transform(None) self.assertIsNone(node) def test_one(self): node = Node() node.data = 1 return_node = transform(node) self.assertEqual(return_node, node) def test_two(self): a = Node() a.data = 5 b = Node() b.data = 1 a.node1 = b return_node = transform(a) self.assertEqual(return_node.data, 1) self.assertEqual(return_node.node2.data, 5) def test_multiple(self): a = Node() a.data = 5 b = Node() b.data = 3 c = Node() c.data = 1 d = Node() d.data = 4 e = Node() e.data = 7 f = Node() f.data = 6 g = Node() g.data = 8 a.node1 = b a.node2 = e b.node1 = c b.node2 = d e.node1 = f e.node2 = g return_node = transform(a) self.assertEqual(return_node.data, 1) self.assertEqual(return_node.node2.data, 3) self.assertEqual(return_node.node2.node2.data, 4) self.assertEqual(return_node.node2.node2.node2.data, 5) self.assertEqual(return_node.node2.node2.node2.node2.data, 6) self.assertEqual(return_node.node2.node2.node2.node2.node2.data, 7) self.assertEqual(return_node.node2.node2.node2.node2.node2.node2.data, 8) if __name__ == "__main__": unittest.main()
# Old class style class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state class Foo(Borg): def __init__(self,aaa): Borg.__init__(self) self.aaa = aaa # New class style class BorgNew(object): __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state class FooNew(BorgNew): def __init__(self,aaa): super(FooNew,self).__init__() self.aaa = aaa if __name__ == "__main__": print "Old class style:" foo = Foo("aaa") print foo.aaa foo2 = Foo("bbb") print foo.aaa print foo2.aaa print "New class style:" fooNew = FooNew("aaa") print fooNew.aaa fooNew2 = FooNew("bbb") print fooNew.aaa print fooNew2.aaa
# Write a Python program that reads in 3 numbers and displays the following: # a) the average of the three numbers # b) the maximum fo the three numbers print("Please enter three numbers of your choosing.") num1 = float(input("Enter your first number: ")) num2 = float(input("Enter your second number: ")) num3 = float(input("Enter your third number: ")) # Asks user to input three numbers individually if (num1 > num2) and (num1 > num3): maximum = num1 elif (num2 > num1) and (num2 > num3): maximum = num2 else: maximum = num3 # Above is the code for the maximum average = ((num1 + num2 + num3)/3) print ("The average of the three numbers is:", average) print ("The Maximum of the numbers is:", maximum) # Above is the code for the average
x1 = int(input("Enter x1: ")) y1 = int(input("Enter y1: ")) x2 = int(input("Enter x2: ")) y2 = int(input("Enter y2: ")) x = int(input("Enter x: ")) y = int(input("Enter y: ")) if x1 <= x <= x2 and y1 <= y <= y2: print("True") else: print("False")
# Int functions only with integers (Whole number) ways to bypass this is by using Float # Example: Print(Int(8+3.3)) will print only 11 # However, print(float(8+3.3)) will print 11.3 # Text inside of single or double quotes makes the content inside it a string # If an apostrophe is needed in a string, adding a backslash before it. This will not cause any problems # Example: Print('We\'re going to have a great time learning python.) # Concatenating brings things, (strings, links, folders, etc) together in a chain or series # # # # # # Mathematical expressions # +, -, *, /, ** (to the power of) # print('we're going to have some fun learning how to code) This will not work as the ' makes things weird # vs print("we're going to have some fun learning to code") # or print('we\'re going to have some fun learning to code') print(int(8+3.3)) # Vs print(float(8+3.3)) # Other examples print(int(8*9)) print(int(9/3))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # print(abs(10)) # print(abs(-10)) # print(abs(10.12)) # print(min(1,2)) # print(max(2,3)) # print(int(1.22)) # print(int(100)) # print(int('100')) # print(float('100.44')) # print(float(100.44)) # print(float('100')) # print(str(100)) # print(str(100.12)) # print(str(True)) # b = '100' * 1 # print(str('100')) # print(b + 1) def my_abs(x): if x >= 0: return x else: return -x def my_abs2(x): if (not isinstance(x, (int, float))): raise TypeError('bad operand type') if x >= 0: return x else: return -x # print(my_abs(10))
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> print(1,2,3,4,5) 1 2 3 4 5 >>> number=[1,2,3,4,5] >>> print(number) [1, 2, 3, 4, 5] >>> print(*number) 1 2 3 4 5 >>> print("abc") abc >>> print(*"abc") a b c >>> print("a","b","c") a b c >>> def add(x,y): return x+y add(10+20) SyntaxError: invalid syntax >>> add(10,20) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> add(10,20) NameError: name 'add' is not defined >>> def add(x,y): return x+y add(10,10) SyntaxError: invalid syntax >>> def add(x , Y): return x+y >>> >>> add(10,10) Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> add(10,10) File "<pyshell#15>", line 2, in add return x+y NameError: name 'y' is not defined >>> def add(x,y): return x+y >>> >>> add(1,5) 6 >>> add(10,10) 20 >>> >>> >>> def add(*number): total=0 for number in numbers: total = total+number >>> def add(*numbers): total=0 for number in numbers: total = total + number return(total) >>> add(1,2,3,4,5) 1 >>> def add(*number): total = 0 for number in numbers: total = total + number return(total) >>> add(10,10,10,10,10) Traceback (most recent call last): File "<pyshell#37>", line 1, in <module> add(10,10,10,10,10) File "<pyshell#36>", line 3, in add for number in numbers: NameError: name 'numbers' is not defined >>> def add(*numbers): total = 0 for number in numbers: total = total + number return(total) >>> add(10,10,10,10) 40 >>> add(10,100,1000,10000) 11110 >>> >>> >>> >>> def about(name,age,likes): sentence="meet {}! they are {} years old and they likes {}".format(name, age,likes) return sentence >>> dictionary ={"name":"neha","age":23,"likes":"python"} >>> about(**dictionary) 'meet neha! they are 23 years old and they likes python' >>>
# Multiple Linear Regression import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('50_Startups.csv') # Prepare data X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Encode categorical data # Encode IV from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X = LabelEncoder() # Always fit & transform encoder to our dataset's column X[:, 3] = labelencoder_X.fit_transform(X[:, 3]) # Transform 'State' column to 3 different columns with 0 or 1 values (true or false) # Use index of 'State' column (3) onehotencoder = OneHotEncoder(categorical_features = [3]) X = onehotencoder.fit_transform(X).toarray() # Avoid the Dummy Variable Trap # Keep all lines but remove 1st column (REMEMBER: Keep n-1 dummy vars) X = X[:, 1:] # Training set & Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Fit MLR to Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Prediction y_prediction = regressor.predict(X_test) # Build the optimal model using Backward Elimination import statsmodels.formula.api as sm # Add b0 constant (required by statsmodels lib, others handle it) X = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1) def backwardElimination(x, sl): numVars = len(x[0]) for i in range(0, numVars): regressor_OLS = sm.OLS(y, x).fit() maxVar = max(regressor_OLS.pvalues).astype(float) if maxVar > sl: for j in range(0, numVars - i): if (regressor_OLS.pvalues[j].astype(float) == maxVar): x = np.delete(x, j, 1) regressor_OLS.summary() return x # Set Significance Level SL = 0.05 X_optimal = X[:, [0, 1, 2, 3, 4, 5]] X_modeled = backwardElimination(X_optimal, SL) # BACKWARD ELIMINATION ALGORITHM STEP BY STEP X_optimal = X[:, [0, 1, 2, 3, 4, 5]] # Create new regressor regressor_OLS = sm.OLS(endog = y, exog = X_optimal).fit() # Find P-values and choose var with the max one regressor_OLS.summary() # Eliminate it X_optimal = X[:, [0, 1, 3, 4, 5]] # Create new regressor regressor_OLS = sm.OLS(endog = y, exog = X_optimal).fit() # Find P-values and choose var with the max one regressor_OLS.summary() # Eliminate it X_optimal = X[:, [0, 3, 4, 5]] # Create new regressor regressor_OLS = sm.OLS(endog = y, exog = X_optimal).fit() # Find P-values and choose var with the max one regressor_OLS.summary() # Eliminate it X_optimal = X[:, [0, 3, 5]] # Create new regressor regressor_OLS = sm.OLS(endog = y, exog = X_optimal).fit() # Find P-values and choose var with the max one regressor_OLS.summary() # Eliminate it X_optimal = X[:, [0, 3]] # Create new regressor regressor_OLS = sm.OLS(endog = y, exog = X_optimal).fit() # Find P-values and choose var with the max one regressor_OLS.summary()
# Write a class to hold player information, e.g. what room they are in # currently. from item import Food, Egg class Player: def __init__(self, name, current_room): self.name = name self.current_room = current_room self.items = [] self.strength = 100 def travel(self, direction): if getattr(self.current_room, f"{direction}_to"): self.current_room = getattr(self.current_room, f"{direction}_to") print(self.current_room) else: print("You cannot move in that direction") def print_inventory(self): print("You are holding: ") for item in self.items: print(item.name) def eat(self, food_item): if not isinstance(food_item, Food): print(f"You cannot eat {food_item.name}") else: self.strength += food_item.calories print( f"You have eaten {food_item.name}, your strength is now {self.strength}") self.items.remove(food_item) def get_item(self, item): if (self.current_room.items) == []: print("nothing to pick up") else: print(f"you picked up a {self.current_room.items[0].name}") self.items.append(item[0]) self.current_room.items.remove(item[0]) def drop_item(self, item): if (self.items) == []: print("nothing to drop") else: print(f"You dropped a {self.items[0].name}") self.current_room.items.append(item[0]) self.items.remove(item[0]) def get_specific_item(self, item, thing): for i in range(len(self.current_room.items)): if self.current_room.items[i].name == thing: print(f"you picked up a {self.current_room.items[i].name}") self.items.append(item[i]) self.current_room.items.remove(item[i]) break else: print("item does note exist") def drop_specific_item(self, item, thing): for i in range(len(self.items)): if self.items[i].name == thing: print(f"You dropped a {self.items[i].name}") self.current_room.items.append(item[i]) self.items.remove(item[i]) break else: print("item does not exist")
def check(s_1, s_2): s_1 += s_1 if (s_1.count(s_2) != 0): print("YES") # Now Rajat Become Happy. else: print("NO") for i in range(int(input())): s_1 = input() s_2 = input() if len(s_1) == len(s_2): check(s_1, s_2) else: print("NO")
for _ in range(int(input())): distanceNeedToBeCovered = int(input()) x = input() y = input() print("NO") if int(x, 2) & int(y, 2) else print("YES")
for _ in range(int(input())): str1=input() str2=input() new="" if len(str1)!=len(str2): # Check if sizes of two strings are same print("NO") else: new= str1 + str1 # Create a temporary string new by concatenating Str1 with itself if new.count(str2)>0: # checking if str2 is a substring of new if yes then str2 is a rotation of str1 print("YES") else: print("NO")
for _ in range(int(input())): s1 = input() s2 = input() temp = '' if len(s1) != len(s2) : print('No') else: temp = s1+s1 if s2 in temp: print("YES") else: print('NO')
for _ in range(int(input())): N=int(input()) a=int(input(),2) # Converting input to integer from binary string b=int(input(),2) # Converting input to integer from binary string if (a & b)==0: # We used bitwise And Operator # 1 & 1 = 1 print("YES") # 1 & 0 = 0 else: # 0 & 1 = 0 print("NO") # if a & b==0 then there will be a path # 0 & 0 = 0
from Stream.stream import Stream import csv # # # class TextStream(Stream): # def __int__(self, path): # super().__init__(None) # self.path = path # # def get_path(self): # return self.path # # # textStream = TextStream('../data/taxi.csv') # # print(textStream.get_path()) # Use the Person class to create an object, and then execute the printname method: def read_file(path): with open(path, 'r') as f: return f.readlines() read_file('../data/taxi.csv') class TextStream(Stream): def __init__(self, path: str): super().__init__(read_file(path)) print(TextStream('../data/taxi.csv')\ .skip(1).filter(lambda x: str(x).split(",")[1] == 'wed')\ .map(lambda x: str(x).split(",")[1]).item_counter()) print(TextStream('../data/taxi.csv')\ .skip(1).filter(lambda x: str(x).split(",")[1] != 'wed')\ .map(lambda x: str(x).split(",")[1]).item_counter())
#A 3-layer neural network implementation. #Much credit to Tariq Rashid's Make Your Own Neural Network book import numpy import scipy.special import csv class neuralNet: def __init__(self, num_inputs, num_hiddens, num_outputs, learning_rate): self.inodes = num_inputs self.hnodes = num_hiddens self.onodes = num_outputs #Link weight matrices. Initials sampled from a normal #probability distribution self.in_to_hidden = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes)) self.hidden_to_out = numpy.random.normal(0.0, pow(self.onodes, -0.5), (self.onodes, self.hnodes)) self.lr = learning_rate #Activation function self.sigmoid = lambda x: scipy.special.expit(x) pass def train(self, init_inputs, init_targets): inputs = numpy.array(init_inputs, ndmin=2).T targets = numpy.array(init_targets, ndmin=2).T hidden_inputs = numpy.dot(self.in_to_hidden, inputs) hidden_outputs = self.sigmoid(hidden_inputs) #Signals into the output layer final_inputs = numpy.dot(self.hidden_to_out, hidden_outputs) final_outputs = self.sigmoid(final_inputs) output_errors = targets - final_outputs hidden_errors = numpy.dot(self.hidden_to_out.T, output_errors) #Update weights between hidden and output self.hidden_to_out += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs)) #Between input and hidden self.in_to_hidden += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs)) pass def query(self, init_inputs): inputs = numpy.array(init_inputs, ndmin=2).T #Signals to/from hidden hidden_inputs = numpy.dot(self.in_to_hidden, inputs) hidden_outputs = self.sigmoid(hidden_inputs) #Signals to/from final final_inputs = numpy.dot(self.hidden_to_out, hidden_outputs) final_outputs = self.sigmoid(final_inputs) return final_outputs def full_train(self, training_data, epochs): data_file = open(training_data, 'r') data_list = data_file.readlines() data_file.close() for e in range(epochs): for record in data_list: all_values = record.split(',') inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01 targets = numpy.zeros(self.onodes) + 0.01 targets[int(all_values[0])] = 0.99 self.train(inputs, targets) pass pass def test(self, testing_data): data_file = open(testing_data, 'r') data_list = data_file.readlines() data_file.close() scorecard = [] correct_values = [] neural_net_values = [] for record in data_list: all_values = record.split(',') correct_label = int(all_values[0]) correct_values.append(correct_label) #Scale and shift inputs(?) inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01 outputs = self.query(inputs) label = numpy.argmax(outputs) neural_net_values.append(label) if (label == correct_label): scorecard.append(1) else: scorecard.append(0) pass pass scorecard_array = numpy.asarray(scorecard) if correct_values.size < 50: print("Correct values: ", correct_values) if neural_net_values.size <= 50: print("Our net's values:", neural_net_values) if scorecard.size <= 50: print("Scorecard: ", scorecard) print("Performance = ", scorecard_array.sum() / scorecard_array.size) #Simple test without training; currently meaningless #num_input_nodes = 3 #num_hidden_nodes = 50 #num_output_nodes = 3 #learning_rate = 0.4 test_net = neuralNet(784, 200, 10, 0.1) test_net.full_train("mnist-data/mnist_train_full.csv", 5) test_net.test("mnist-data/mnist_test_full.csv") test_net.test("mnist-data/mnist_test_10.csv")
#Thomas Rowley # insert elements either appending or inserting # 2 delete an element either by value or by index # 3 find if something in the list # 4 Find the index where an element is in the list # 5 reverse th eorder of the array x=1 l1="**************************************" l2="* My game *" l3="* *" l4="* 1 - Insert Element *" l5="* 2 - Delete Element *" l6="* 3 - Find Element in List *" l7="* 4 - Find Index of Element *" l8="* 5 - Reverse Order of List *" l9="* 6 - Exit Game *" l10="* List: MJ, Lebron, Curry, Kawhi, KD *" l11="* *" l12="**************************************" playersLIST=["MJ", "Lebron", "Curry", "Kawhi", "KD"] def menu(): print(l1) print(l2) print(l3) print(l4) print(l5) print(l6) print(l7) print(l8) print(l9) print(l10) print(l11) print(l12) print("Please enter your selection from 1 to 6") inputNumber = input() x = int(inputNumber) return x def pause(): print("Do you want to play again?") answer1= input() answer1=answer1.upper() if "Y" in answer1: return True else: return False def addELEMENT(): print("Add element to list.") print("What basketball player would you like to add?") answer= input() print("What position would you like this to be in the list?") answer1= int(input()) playersLIST.insert(answer1, answer) print("Here is the new list.") print(playersLIST) def deleteELEMENT(): print("Delete an element from the list.") print("What basketball player do you want to remove from the list?") print(playersLIST) answer= input() playersLIST.remove(answer) print("Here is the new list.") print(playersLIST) def findELEMENT(): print("Find something in the list.") print("What would you like to find in the list.") print(playersLIST) answer = input() if answer=="MJ": print("Your search is in the list.") if answer !="MJ": print("Your search is not contained in the list.") if answer=="Lebron": print("Your search is in the list.") if answer !="Lebron": print("Your search is not contained in the list.") if answer=="Curry": print("Your search is in the list.") if answer !="Curry": print("Your search is not contained in the list.") if answer=="Kawhi": print("Your search is in the list.") if answer !="Kawhi": print("Your search is not contained in the list.") if answer=="KD": print("Your search is in the list.") if answer !="KD": print("Your search is not contained in the list.") def findINDEX(): print("Find the index of an element.") print(playersLIST) print("Insert the element you would like to index.") answer = str(input()) print(playersLIST.index(answer)) def reverseLIST(): print("Reverse the order of the list.") print(playersLIST) print("Press enter to reverse the order of the list.") answer= input() playersLIST.reverse() print(playersLIST) while x !=6: x = menu() if x==1: convert=True while convert: addELEMENT() convert= pause() if x==2: convert=True while convert: deleteELEMENT() convert= pause() if x==3: convert=True while convert: findELEMENT() convert= pause() if x==4: convert=True while convert: findINDEX() convert= pause() if x==5: convert=True while convert: reverseLIST() convert= pause() if x==6: print("Goodbye thank you for playing!")
answer= str(input()) #input is a function that returns a string while answer == "Peter": print(answer.lower()) # method of Strings (always refer it with a dot) answer= "Changed" answer = answer.lower() print (answer)
#Thomas Rowley #6/7/2021 #Learning how to work with strings # make 3 string variables print them individually #"print st1 + st2" #print st2 + st3 #print st1 + st2 + st3 phrase1 = "Lebron" phrase2 = "<" phrase3 = "Tacko" phrase4 = str(input()) print(phrase1, " ", phrase2, " ", phrase3) print(phrase1, " " + phrase2) print(phrase2, " " + phrase3) print(phrase1, " " + phrase2, " " + phrase3) print(phrase1, " " + phrase2, " " + phrase3, " " + phrase4)
import random print('This is a number guessing game. Guess a number between 1 and 20.') print('You have 6 chances') secret = random.randint(1,20) for i in range(1,7): print ('>> ') guess = int(input()) if guess > secret: print('Guess too high. Try guessing a smaller number') elif guess < secret: print('Guess too low. Try guessing a larger number') else: break # for when the guess is correct. if guess == secret: print('Good Job. You guessed the number in '+ str(i)+' tries.') else: print('You ran out of chances.')
import logging logging.basicConfig(filename = 'debug_log.txt', level = logging.DEBUG, format = '%(asctime)s - %(levelname)s - %(message)s') # by adding the filename argument, we can output all the debug messages to a file instead of printing to console. # this enables storage of debug messages as these are appended and not written over # format :: # asctime << ascii encoded time # levelname << DEBUG level # message << prints out the string we passed into the logging.debug() method # logging.disable(logging.CRITICAL) # this will disable all the logging messages from showing up # this way we dont have to comment out or delete all the print statements if they were used. <<< # logging levels: debug > info > warning > error > CRITICAL (highest) logging.debug('Start ----') def factorial(n): logging.debug('Inside the funciton') fact = 1 for i in range(1,n+1): fact *= i logging.debug('The value of iterator in the loop is %s and the total is %s' % (i,fact)) logging.debug('Value to be returned : %s' % fact) return fact print(factorial(5)) logging.debug('Execution complete')
# gui manipulation using pyautogui module import pyautogui # get screensize print(pyautogui.size()) # returns a tuple of width and height # move mouse cursor to a specific coordinate >> starts at (0,0) at top left and (width-1,height-1) at bottom right # x-coords incrase to the left. y-coords incrs down #pyautogui.moveTo(20,20, duration = 1) # <<< moves the cursor to argument location. duration modifier can be used to slow it down # can use relative movement #pyautogui.moveRel(20,-20,duration = 2) # -20 in y moves upwards. mouse will move relative to current location # can use pyautogui.position() to get the location of the current pointer position # use click(x,y) << to click at a specific location pyautogui.click(501,18) # without args it just clicks at current location # doubleclick/rightclick/middleclick() all available #pyautogui.drag/dragto/dragrel() methods allow for dragging the mouse( ie click and hold) # using the console and pyautogui.displayMousePosition() method << we can continually show the current cursor location
print('Hello World') #expression print(2+2) #expression always evaluate to a single value #BODMAS rule followed by python #they evaluate using operators (mathematical) # data types # integer, ints = whole numbers e.g 2 # floating point numbers, floats = decimal values, 3.14 # strings = array of chars. # strings can be added together and multiplied(repeated) using mathematical operators # e.g 'A'+'B' = 'AB' # e.g 'A'*3 = 'AAA' # variables = containers for values. they are assigned to a values using the '=' (assignment operator) # statements --- do not evaluate to a single value but an expression can be a part of a statement.
# Regressão Linear Múltipla # Base de dados de preços das casas retiradas do Kaggle # "House Sales in King County, USA" # Importando as bibliotecas import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolute_error # Atriuindo o arquivo a variavel "base" base = pd.read_csv('https://raw.githubusercontent.com/wallacecarlis/arquivos/main/house_prices.csv') # Selecionando os atributos previsores "x" x = base.iloc[:, 3:19].values # Selecionando os preços das casas y = base.iloc[:, 2].values # Divisão da base de dados em treino e teste x_treinamento, x_teste, y_treinamento, y_teste = train_test_split(x, y, test_size = 0.3, random_state = 0) # Criando o objeto regressor = LinearRegression() # Treinamento da base: atributos "previsores e respostas" regressor.fit(x_treinamento, y_treinamento) # evidenciando o resultado de 0.70 (correlacao positiva forte) # com mais variáveis ja e possivel se aproximar do preco correto frente a regressão linear simples score = regressor.score(x_treinamento, y_treinamento) # Criando as previsoes (testes) previsoes = regressor.predict(x_teste) # Obtendo a media do erro mae = mean_absolute_error(y_teste, previsoes) # score dos testes regressor.score(x_teste, y_teste) # Parametros regressor.intercept_ # constante regressor.coef_ # coeficiente len(regressor.coef_) # quantidade de coeficientes
with open('guest_book.txt', 'a') as file: while True: ask = input("请输入你的姓名('q'键退出):") if ask == 'q': break ask += '\n' print("您好!" + ask) file.write(ask)
from math import pi, sin, cos Radius = 100.0 Steps = 72 NLongitudes = 10 NLatitudes = 4 def main(): color("green") makeLongitudes() color("yellow") makeLatitudes() def makeLongitudes(): for i in range(NLongitudes): first = None theta = i * (2 * pi / NLongitudes) sint = sin(theta) cost = cos(theta) for s in range(Steps): phi = s * (2 * pi / Steps) r = sin(phi) * Radius y = cos(phi) * Radius x = r * sint z = r * cost if first is None: first = (x, y, z) move(x, y, z) else: draw(x, y, z) draw(*first) def makeLatitudes(): for i in range(NLatitudes): first = None phi = (i + 1) * (pi / (NLatitudes + 1)) y = cos(phi) * Radius r = sin(phi) * Radius for s in range(Steps): theta = s * (2 * pi / Steps) x = r * sin(theta) z = r * cos(theta) if first is None: first = (x, y, z) move(x, y, z) else: draw(x, y, z) draw(*first) def color(c): print ".color", c def move(x, y, z): print ".m ", x, y, z def draw(x, y, z): print ".d ", x, y, z main()
def swap(line, column): swapped_line = line first_variable = find_first_variable(line, column) second_variable = find_second_variable(line, column) swapped_line = swapped_line.replace(second_variable, first_variable) swapped_line = swapped_line.replace(first_variable, second_variable, 1) return swapped_line def find_first_variable(line, column): line_until_column = line[:column] line_from_column = line[column:] start_column = line_until_column.rfind(",") if start_column == -1: start_column = line_until_column.rfind("(") start_column = start_column + 1 end_column = line_from_column.find(",") if end_column == -1: raise IndexError end_column = column + end_column return line[start_column:end_column].lstrip(' ') def find_second_variable(line, column): start_column = column + line[column:].find(",") end_column = line[start_column + 1:].find(",") if end_column == -1: end_column = line[start_column + 1:].find(")") end_column = start_column + end_column + 1 return line[start_column:end_column].lstrip(', ')
from pymongo import MongoClient DB_NAME = 'nba_db' PLAYERS_COL = 'players' # nba_db.players collection TEAMS_COL = 'teams' CURRENT_SEASON = "2015-16" # nba_db.2015-16 collection and current season class NBADatabase: """ Interface that describes the methods of an NBADatabase. """ def get_players(self): """ Return a list of players. """ return def get_seasons(self, season): """ Given a season (ex: "2015-16"), return a list of seasons of each player. A season contains a list of games. """ return def get_teams(self): """ Return a list of teams. """ return def get_player_by_id(self, id): """ Given a player id, return the player with that id. """ return def get_player_by_name(self, full_name): """ Given a player's full name, return the player with that name. """ return def get_player_season_by_id(self, id, season): """ Given a player id and season (format: "2015-16"), return the document of the given season of the player with the given id. A season contains a list of games. """ return def get_player_season_by_name(self, name, season): """ Given a player name and season (format: "2015-16"), return the document of the given season of the player with the given id. A season contains a list of games. """ return class NBAMongoDB(NBADatabase): """ An NBADatabase Implementation that uses a MongoDB database. Attributes: db The MongoDB database created from a MongoClient. """ def __init__(self, host, port): client = MongoClient(host, port) self.db = client[DB_NAME] def get_players(self): players_collection = self.__players_collection() return players_collection.find() def get_seasons(self, season): # TODO: change db name to "2015_16" season_collection = self.__season_collection(season) return season_collection.find() def get_player_by_id(self, id): players_collection = self.__players_collection() player = players_collection.find({"_id": id})[0] return player # TODO: Should return empty player if id is wrong. def get_player_by_name(self, name): players_collection = self.__players_collection() players = players_collection.find() for player in players: if (player['first_name'] + " " + player['last_name']).lower() \ == name.lower(): return player return None def get_player_season_by_id(self, id, season): # TODO: change db name to "2015_16" season_collection = self.__season_collection(season) season = season_collection.find({"_id": id})[0] return season def get_player_season_by_name(self, name, season): player = self.get_player_by_name(name) id = player['_id'] return self.get_player_season_by_id(id, season) def __players_collection(self): """ Return the entire players collection. """ return self.db[PLAYERS_COL] def __season_collection(self, season): """ Given a season, return the entire season collection. """ season_col_name = "season" + season return self.db[season_col_name]
""" Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. """ # O(n) time complexity and O(1) space complexity from typing import List class Solution: def increasingTriplet(self, nums: List[int]) -> bool: num_start, middle_num = float('inf'), float('inf') for num in nums: if num < num_start: num_start = num if num > num_start: middle_num = min(num, middle_num) if num > middle_num: return True return False
from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ self.transpose(matrix) self.reflect(matrix) def transpose(self,matrix): n = len(matrix) for i in range(n): j=i for j in range(j, n): temp = matrix[i][j] matrix[i][j]=matrix[j][i] matrix[j][i]= temp def reflect(self, matrix): n = len(matrix) for i in range(n): for j in range(n // 2): temp = matrix[i][j] matrix[i][j]= matrix[i][n-1-j] matrix[i][n-1-j]=temp
""" Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. Solution We can solve this question by using a set. We traverse the linked list and check if the next node’s value is inside the set. If it is, then we modify the current node’s next value to cur.next.next ( delete the next node). Otherwise, we add cur.next’s value to the set and continue traversing the linked list. """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __str__(self): return str(self.val) + "->" + str(self.next) class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if head is None: return head items = set() items.add(head.val) cur = head while cur and cur.next: if cur.next.val in items: cur.next = cur.next.next else: items.add(cur.next.val) cur = cur.next return head def main(): head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) head.next.next.next = ListNode(2) head.next.next.next.next = ListNode(5) head.next.next.next.next.next = ListNode(5) head.next.next.next.next.next.next = ListNode(5) print(f"Test case one: {head}") print(f"Duplicates deleted: {Solution().deleteDuplicates(head)}") head = ListNode(5) head.next = ListNode(3) head.next.next = ListNode(2) head.next.next.next = ListNode(2) head.next.next.next.next = ListNode(5) head.next.next.next.next.next = ListNode(5) head.next.next.next.next.next.next = ListNode(5) print(f"Test case two: {head}") print(f"Duplicates deleted: {Solution().deleteDuplicates(head)}") main()
# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. # You may assume the two numbers do not contain any leading zero, except the number 0 itself. # Example: # Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 0 -> 8 # Explanation: 342 + 465 = 807. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __str__(self): return str(self.val) + "->" + str(self.next) class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: carry_over = 0 p = newLL = ListNode(0) while l1 or l2 or carry_over: if l1: carry_over += l1.val l1 = l1.next if l2: carry_over += l2.val l2 = l2.next p.next = ListNode(carry_over%10) carry_over //= 10 p = p.next return (f"Result: {newLL.next}") l1_1 = ListNode(2) l1_2 = ListNode(4) l1_3 = ListNode(3) l1_1.next = l1_2 l1_2.next = l1_3 print((f"List1: {l1_1}")) l2_1 = ListNode(5) l2_2 = ListNode(6) l2_3 = ListNode(4) l2_1.next = l2_2 l2_2.next = l2_3 print((f"List2: {l2_1}")) s = Solution() print(s.addTwoNumbers(l1_1,l2_1)) # Output: 7 -> 0 -> 8 # Explanation: 342 + 465 = 807.
""" Given an unsorted integer array nums, find the smallest missing positive integer. """ def firstMissingPositive(nums): nums.sort() if not nums or (nums[-1] < 1) : return 1 for i in range(1, nums[-1]+1): if i not in nums: return i return nums[-1]+1 """ Time/Space: O(n)/O(1) """
""" Write a function reverseArray(A) that takes in an array A and reverses it, without using another array or collection data structure; in-place. Example: A = [10, 5, 6, 9] reverseArray(A) A // [9, 6, 5, 10] """ A = [10, 5, 6, 9] def reverseArray(A): return [list for list in A[::-1]] print(reverseArray(A)) """def reverseArray(A): return [list for list in reversed(A)] print(reverseArray(A))"""
import json from difflib import get_close_matches data = json.load(open("data.json")) def meaning(word): global i word = word.lower() if word in data: return data[word] if word.title() in data: return data[word.tile()] if word.upper() in data: return data[word.upper()] elif len(get_close_matches(word, data.keys())) > 0: print("did you mean by %s?,press y for yes and n for no" % get_close_matches(word,data.keys())[0]) choice = input() crct = get_close_matches(word,data.keys())[0] if choice == "y": return data[crct] else: return "thank you" else: return "word does not exist" choice1 = True while (choice1): word = input("enter a word: ") lst= (meaning(word)) i = 0 if type(lst) != str: print("the meanings are:") for mn in lst: i += 1 print(i,".",mn) else: print(lst) choice1 = input("do you want to continue,press y if yes or n if no: ") if choice1 == 'n': choice1 = False print("thank you :)")
"""Write a program which accept number from user and return addition of digits in that number. Input : 5187934 Output : 37 """ def Sumdigit(num): sum=0 digit=0 while num!=0: digit=num%10 sum=sum+digit num=num//10 return sum def main(): value=int(input("Enter the number:")) add=Sumdigit(value) print("Addition of digits is:",add) if __name__=="__main__": main()
"""Write a program which accept one number and display below pattern. Input : 5 Output : 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5""" def Display(num): i=0 j=0 for i in range(num): for j in range(1,num+1,1): print(j,end=" ") print() def main(): value=int(input("Enter the number:")) Display(value) if __name__=="__main__": main()
"""Write a program which contains filter(), map() and reduce() in it. Python application which contains one list of numbers. List contains the numbers which are accepted from user. Filter should filter out all such numbers which greater than or equal to 70 and less than or equal to 90. Map function will increase each number by 10. Reduce will return product of all that numbers. Input List = [4, 34, 36, 76, 68, 24, 89, 23, 86, 90, 45, 70] List after filter = [76, 89, 86, 90, 70] List after map = [86, 99, 96, 100, 80] Output of reduce = 6538752000 """ import functools as fn Check=lambda brr: brr>=70 and brr<=90 Increment=lambda crr:crr+10 Mul=lambda a,b:a*b def main(): no=0 num=0 rRet=0 arr=[] fRet=[] mRet=[] no=int(input("Enter number of elements:")) print("Enter the Elements:") for i in range(no): num=int(input()) arr.append(num) fRet=filter(Check,arr) print("List After Filter:",fRet) mRet=map(Increment,fRet) print("List After Map:",mRet) rRet=fn.reduce(Mul,mRet) print("Reduces output is:",rRet) if __name__=="__main__": main()
"""Write a program which accept N numbers from user and store it into List. Accept one another number from user and return frequency of that number from List. Input : Number of elements : 11 Input Elements : 13 5 45 7 4 56 5 34 2 5 65 Element to search : 5 Output : 3 """ def Frequency(brr,num1): freq=0 for i in range(len(brr)): if brr[i]==num1: freq=freq+1 return freq def main(): no=0 arr=[] num=int(input("Enter number of elements:")) for i in range(num): no=int(input()) arr.append(no) value=int(input("Enter element to search:")) iRet=Frequency(arr,value) print("Frequency of {} is:{}:".format(value,iRet)) if __name__=="__main__": main()
"""Write a program which accept N numbers from user and store it into List. Return addition of all elements from that List. Input : Number of elements : 6 Input Elements : 13 5 45 7 4 56 Output : 130 """ def Addition(brr): sum=0 for i in range(len(brr)): sum=sum+brr[i] return sum def main(): no=0 arr=[] num=int(input("Enter number of elements:")) for i in range(num): no=int(input()) arr.append(no) iRet=Addition(arr) print("Addition is:",iRet) if __name__=="__main__": main()
from pyquery import PyQuery as pq import requests #输入保存到本地的文件名 filename = input("Please input the name you want to save: ") #提供小说的编号,https://www.biqukan.com/0_790/ 提供0_790就行,输入0_790 book_url = input("Please input url of this novel: ") #获取小说文本内容 def get_txt(url): #获取url的返回值 response = requests.get(url) #获取网页内容 tmp_title = pq(response.text) #通过pyquery的特性,直接取页面中的h1标签文本内容,这个就是小说当前章节标题 title = tmp_title("h1").text() #获取小说内容,#content,是通过id名取值, .是通过类名,这里是通过id名,获取content的文本内容,当前章节的内容 content = tmp_title("#content").text() #返回标题然后换行后内容 return title + "\n" + content #定义download函数 def download(url): #打开文件,编码为utf-8,别名叫file with open(filename,"a+",encoding="utf-8") as file: #调用get_txt这个函数,并且把download函数接收到的url传给get_txt函数,然后把返回的小说标题和内容写入到文件中 file.write(get_txt(url)) #写入两个回车,这样能看出一章是一章 file.write("\n\n") #定义函数将每一章小说都写入到文件中 def input_file(book_name): #拼接url split = "https://www.biqukan.com/" + book_name #h获取页面 a = requests.get(split) #获取网页内容 b = pq(a.text) #获取.listmain类的a标签,就是下一章的连接 links = b(".listmain a") #循环所有的下一章 for i in links[12:]: #调用download函数,拼接每一章的连接 download("https://www.biqukan.com" + i.items()[0][1]) #输出下载中 print("downloading......please wait...") #调用input_file函数,并且把小说编号当做参数传过去 input_file(book_url) #输出下载完成 print("download is done....")
#!/usr/bin/env python # -*- coding:utf-8 -*- name = 'whole global name' ''' 注:此处全局的变量名,写成name,只是为了演示而用 实际上,好的编程风格,应该写成gName之类的名字, 以表示该变量是Global的变量 ''' class Person: name = 'class global name' def __init__(self, newPersonName): # self.name = newPersonName ''' 此处,没有使用self.name 而使得此处的name,实际上仍是局部变量name 虽然此处赋值了,但是后面没有被利用到,属于被浪费了的局部变量name ''' name = newPersonName def sayYourName(self): ''' 此处,之所以没有像之前一样出现: AttributeError: Person instance has no attribute 'name' 那是因为,虽然当前的实例self中,没有在__init__中初始化对应的name变量,实例self中没有对应的name变量 但是由于实例所对应的类Person,有对应的name变量,所以也是可以正常执行代码的 对应的,此处的self.name,实际上是Person.name ''' print('My name is %s' % self.name) print('Name within class Person is actually the global name: %s' % name) print("Only access Person's name via Person.name = %s" % (Person.name)) def selfAndInitDemo(): personInstance = Person('Tim') personInstance.sayYourName() print('whole global name is %s' % name) if __name__ == '__main__': selfAndInitDemo() ''' My name is class global name Name within class Person is actually the global name: whole global name Only access Person's name via Person.name = class global name whole global name is whole global name '''
# -*-coding: utf-8 -*- # @Time : 2021/1/1 15:03 # @Author : Cooper # @FileName: text2.py # @Software: PyCharm import threading import time class myThread(threading.Thread): def __init__(self,name,delay): threading.Thread.__init__(self) self.name=name self.delay=delay def run(self): print("Strating"+self.name) print_time(self.name,self.delay) print("Exiting"+self.name) def print_time(threaName,delay): counter=0 while counter<3: time.sleep(delay) print(threaName,time.ctime()) counter+=1 threads=[] #创建新线程 thread1=myThread("线程1",1) thread2=myThread("线程2",2) #开启新线程 thread1.start() thread2.start() #添加线程到列表 threads.append(thread1) threads.append(thread2) #等待所有线程完成 # for t in threads: # print("t=======",t) # t.join() # print("结束") print("Exiting Main threading")
""" 作者:Oliver 功能:用户输入密码比对账户信息 日期:20190120 版本:1.0 """ name_tup = ("a", "b", "c") password_tup = ("123", "234", "345") input_times = {"a": 0, "b": 0, "c": 0} name = input("请输入你的账户:") while input_times[name] < 3: password = input("请输入你的密码:") if name in name_tup: if password == password_tup[name_tup.index(name)]: print("登陆成功!") exit() else: print("密码错误!") input_times[name] = input_times.get(name, 0) + 1 if input_times[name] >= 3: print("错误次数达到上限,账户已锁定!")
#Michelle Tan #10/27/2020 #Lab 6 def is_lower_101(string): #Takes a single character as input and returns True if the character is lowercase and False otherwise stringInt = ord(string) upperString=chr(stringInt-32) if string.upper() == upperString: return True else: return False def char_rot_13(string): #Takes a single character and returns the rot-13 encoding of the character rot13 = '' alpha = {"a":"n" , "b":"o" ,"c":"p" , "d":"q","e":"r" , "f":"s" , "g":"t" ,"h":"u" , "i":"v", "j":"w", "k":"x" , "l":"y" , "m":"z" ,"n":"a", "o": "b" , "p":"c" ,"q":"d" ,"r":"e" ,"s":"f", "t":"g" ,"u":"h", "v":"i", "w":"j", "x":"k", "y":"l", "z":"m" } if string.islower(): rot13 += alpha.get(string) return rot13 if string.isupper(): string = string.lower() rot13 += alpha.get(string).capitalize() return rot13 if string not in alpha: rot13 += string return rot13
# Michelle Tan # Prof. Turner # Section 01 name = input('What is your name? ') print('Hello ' + name + '!')
#Michelle Tan #Instructor: Turner #Section: 01# #Lab 3 import unittest from logic import * class TestCases(unittest.TestCase): #Testing the is_even function using an even, odd, negative even, negative odd number def test_is_even_1(self): self.assertTrue(is_even(2)) def test_is_even_2(self): self.assertTrue(is_even(-8)) def test_is_even_3(self): self.assertFalse(is_even(73)) def test_is_even_4(self): self.assertFalse(is_even(-35)) #Testing the in_an_interval function using all endpoints, numbers in between the interval, and numbers outside the interval def test_in_an_interval_1(self): self.assertTrue(in_an_interval(2)) def test_in_an_interval_2(self): self.assertTrue(in_an_interval(6)) def test_in_an_interval_3(self): self.assertFalse(in_an_interval(9)) def test_in_an_interval_4(self): self.assertFalse(in_an_interval(47)) def test_in_an_interval_5(self): self.assertTrue(in_an_interval(64)) def test_in_an_interval_6(self): self.assertFalse(in_an_interval(92)) def test_in_an_interval_7(self): self.assertFalse(in_an_interval(12)) def test_in_an_interval_8(self): self.assertTrue(in_an_interval(18)) def test_in_an_interval_9(self): self.assertTrue(in_an_interval(19)) def test_in_an_interval_10(self): self.assertTrue(in_an_interval(101)) def test_in_an_interval_11(self): self.assertTrue(in_an_interval(102)) def test_in_an_interval_12(self): self.assertTrue(in_an_interval(103)) def test_in_an_interval_13(self): self.assertFalse(in_an_interval(104)) def test_in_an_interval_14(self): self.assertFalse(in_an_interval(0)) # Run the unit tests. if __name__ == '__main__': unittest.main()
def guessing_game(no_of_guess, target): ''' A function named guessing_game, it asks for the user guess and prints your guess is higher or lower. This is repeated by the no_of_guess.day2.py Parameters: no_of_guesses and target Returns: the positive difference between the final guess and the correct value @author: Babatunde Koiki Created on 2020-03-24 ''' for _ in range(no_of_guess): # iterates no_of_guesses time yournum = int(input('Enter a number: ')) # gets user input if yournum > target: # checks if input is greater tahn actual value print('Your guess is higher than the correct number') elif yournum < target: # checks if input is lesser print('Your guess is lower than the correct number') else: print('Your guess is equal to the correct number') break return abs(target - yournum) # Returns the positive difference between the final guess and actual value
def GPA_calculator(scores, units): ''' A function named GPA_calculator which computes the GPA of a student Parameter: scores - The score of the student units: The units of each course Returns: The GPA of the student. @author: Babatunde Koiki Created on 2020-03-24 ''' grades = [] for grade in scores: # Loops thriugh all the scores obtained the student if grade >= 70: grades.append(5) # Checks if the score is an A elif grade >= 60: grades.append(4)# Checks if the score is a B elif grade >= 50: grades.append(3)# Checks if the score is a C elif grade >= 45: grades.append(2) # Checks if the score is an D elif grade > 39: grades.append(1) # Checks if the score is an E else: grades.append(0)# Checks if the score is F # Computes the sum of product of every element in grades and units list and divides by sum of units. return sum([grade * unit for grade, unit in zip(grades, units)])/sum(units)
def wrapper(para,n): """ This function takes in a paragraph as a string and aximum number of characters as an integer Returns the wrapped text as a string Created on Tue Apr 7 11:02:34 2020 @author: Babatunde Koiki """ new_text = para.split("\n") final=[] for each in new_text: final.append('\n'.join(each[i:i+n] for i in range(0,len(each),n))) return '\n'.join(final)
def sparse_search(data, search_val): print("Data: " + str(data)) print("Search Value: " + str(search_val)) first = 0 last = len(data)-1 # runs as long as pointer do not intersect. E.G left crosses over right pointer while first <= last: # sets middle index of first to last array mid = (first + last) // 2 # if there is no value at mid it searches for one and then sets it as mid if not data[mid]: left = mid - 1 right = mid + 1 while True: if left < first and right > last: print('{} is not in the dataset. Dataset is empty'.format(search_val)) return elif right <= last and data[right]: mid = right break elif left >= first and data[left]: mid = left break right += 1 left -= 1 # search val found! if data[mid] == search_val: print("{} found at position {}\n".format(search_val, mid)) return # search val less then mid value. Continue with left half of dataset if search_val < data[mid]: last = mid - 1 # search val greater then mid value. Continue with right half of dataset if search_val > data[mid]: first = mid + 1 # ran through entire while loops without a match so it runs the print statement below print("{} is not in the datatset\n".format(search_val)) sparse_search(["A", "", "", "", "B", "", "", "", "C", "", "", "D"], "C") sparse_search(["A", "B", "", "", "E"], "A") sparse_search(["", "X", "", "Y", "Z"], "Z") sparse_search(["A", "", "", "", "B", "", "", "", "C"], "D") sparse_search(["Apple", "", "Banana", "", "", "", "", "Cow"], "Banana") sparse_search(["Alex", "", "", "", "", "Devan", "", "", "Elise", "", "", "", "Gary", "", "", "Mimi", "", "", "Parth", "", "", "", "Zachary"], "Parth") sparse_search(["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], "Parth")
# Filename : test.py # coding=utf-8 __author__ = 'wind' print ('hello world') #事实上Python 为了优化速度,使用了小整数对象池,避免为整数频繁申请和销毁内存空间。而Python 对小整数的定义是 [-5, 257), #只有数字在-5到256之间它们的id才会相等,超过了这个范围就不行了,同样的道理,字符串对象也有一个类似的缓冲池,超过区间范围内自然不会相等了 #如果你需要某个 # Python 函数或语句的快速信息帮助, # 那么你可以使用内建的 help 功能。 # 尤其在你使用带提示符的命令行的时候, # 它十分有用。比如,运行 help(str)——这会显示 str 类的帮助 # help(str) #我几乎可以保证你在每个 # Python 程序中都要用到字符串, # 所以请特别留心下面 这部分的内容。 # 下面告诉你如何在 Python 中使用字符串。 print (r'what\'s your name') #自然字符串 R #Unicode 字符串v u # 字符串是不可变的 # 按字面意义级连字符串 print (r'what\'s' 'your name?') i=5 print i i=i+1 print i # 运算符与表达式 # 幂运算 ** print 3**4 # 取整 print 10//7 # 取余 print 10%7 # 左移 print 2<<3 # 右移 print 16>>3 # 按位与 print 5&3 # 按位或 print 5|3 # 按位异或 print 5^3 # 按位翻转 # not 布尔非 and 布尔与 def foo(): print 'foo click' #foo() #动态语言# a = 5 print a def foo(): a = 10 if(a>10): print 'hellp more than 10' elif 5<a<10 : print "hello less than 10" else: print 'equal' foo() arr = [1,2,3,4] #循环 迭代器 for i in range(10) : print i #def 函数 申明符 def sum (a,b): return a+b print sum(10,2) #lambda 匿名 函数 aa = lambda x,y:x+y print aa(3,3) print 'abcd ' + 'efgh' # class 类 class footall(object): def __init__(self,name,age): self.name = name self.age = age def say(self): print self.name print self.age fo = footall('laowu',12) fo.say() #内建函数 不需要import 的 或者对象 如input ,,raw_input # s = raw_input('请输入年龄') # # print ('输入的年龄为'+s) #input 只能接收python 表达式即你输入字符串的时候必须使用引号将它括起来 s = input('请输入一个任意的东西') print ('任意的东西 为 '+s) #文件 io 操作 file open #file 是一个类型 类似于int ,dict 可以直接实例对象。 #open 是一个内建函数 作用是根据参数来生成一个file 类型并返回 推荐使用open。 # f = open('test.py','r') # # for i in f: # print i # # f.close() #map rediucs os #d对象属性检查 #isinstance() 检查对象的类型 #hassattr() 判断对象是否有某个属性 #type() 查看对象的类型 #id() 获取对象的内存位置 ssss = 12 if (ssss.isinstance(int)): print ('sss is int')
#!/usr/bin/env python # Booleans are statements that take on either True or False as a value. # We can create booleans by comparing two values and seeing if they are equal # This will be False print("Andre the Giant" == "Short") # This is True print("Andre the Giant" == "Andre the Giant") # True and False are special python keywords of the boolean type. # Boolean is abbreviated to bool. print(type(True)) print(type(False)) a = 10 b = 5 # False print(a == b) # True print(a == 10) # Assigning a boolean to a variable c = a == b print(c) # Assign a boolean that evaluates to True to d. # Assign a boolean that evaluates to True to e. # Assign a boolean that evaluates to False to f. # Assign a boolean that evaluates to False to g. d = 1 == 1 e = 2 == 2 f = 3 == 4 g = 4 == 3 print(d == 1) print(e == 2) print(f == 4) print(g == 3)
#!/usr/bin/env python # Let's say we want to take the square root of a number. # Python's math module has a handy function that can do that. # But, we have to import the module before we can use it. import math # Now, we can access the functions in the module by using the module name, then a dot, then the function to use. # The sqrt function in the math module will take the square root of a number. print(math.sqrt(9)) # We can use other functions, too. # The ceil function will always round a number up. print(math.ceil(8.1)) # And the floor function will always round a number down. print(math.floor(11.9)) # Assign the square root of 16 to a. # Assign the ceiling of 111.3 to b. (round up) # Assign the floor of 89.9 to c. (round down) a = math.sqrt(16) b = math.ceil(111.3) c = math.floor(89.9)
#!/usr/bin/env python # Let's assume that Superman is three times more interested in foods having a lot of protein than he is worried about them having too much fat. # We can "weight" the protein number by his criteria, or multiply it by three. # First we'll calculate the weighted value for protein. weighted_protein = food_info["Protein_(g)"] * 3 # And now the weighted value for fat. # We'll give fat a weight of -1, because he wants to avoid foods that have a lot of it, but he cares about foods having a lot of protein three times as much. weighted_fat = -1 * food_info["Lipid_Tot_(g)"] # We can construct our rating by just adding the weighted values. initial_rating = weighted_protein + weighted_fat # Let's say Superman now decides that the food having a lot of protein is only twice as important as the food not being too fatty. # Construct the new rating, and assign it to new_rating new_rating = (food_info["Protein_(g)"] * 2) - food_info["Lipid_Tot_(g)"]
#!/usr/bin/env python # We can use the max() method to find the maximum value in a column. max_protein = food_info["Protein_(g)"].max() # And then we can divide the column by the scalar. normalized_protein = food_info["Protein_(g)"] / max_protein # See how all the values are between 0 and 1 now? print(normalized_protein[0:20]) # Normalize the values in the "Vit_C_(mg)" column, and assign the result to normalized_vitamin_c # Normalize the values in the "Zinc_(mg)" column, and assign the result to normalized_zinc normalized_vitamin_c = food_info["Vit_C_(mg)"] / food_info["Vit_C_(mg)"].max() normalized_zinc = food_info["Zinc_(mg)"] / food_info["Zinc_(mg)"].max()
#!/usr/bin/env python # Define a list of lists data = [["tiger", "lion"], ["duck", "goose"], ["cardinal", "bluebird"]] # Extract the first column from the list first_column = [row[0] for row in data] # Double all of the prices in apple_price, and assign the resulting list to apple_price_doubled. # Subtract 100 from all of the prices in apple_price, and assign the resulting list to apple_price_lowered. apple_price = [100, 101, 102, 105] apple_price_doubled = [price*2 for price in apple_price] apple_price_lowered = [price-100 for price in apple_price]
#!/usr/bin/env python # We can use for loops and if statements to find the smallest value in a list. the_list = [20,50,5,100] # Set smallest_item to a value that is bigger than anything in the_list. smallest_item = 1000 for item in the_list: # Check if each item is less than smallest_item. if item < smallest_item: # If it is, set smallest_item equal to its value. smallest_item = item print(smallest_item) # The first time through the loop above, smallest_item will be set to 20, because 20 < 1000 is True. # The second time through, smallest_item will stay at 20, because 50 < 20 is False. # The third time through, smallest_item will be set to 5, because 5 < 20 is True. # The last time through, smallest_item will stay at 5, because 100 < 5 is False. smallest_item = 1000 a = [500,10,200,5,78,-1,-10,-100,567,890,400,34,-101,895] #Set the smallest_item variable equal to the lowest value in a. Use a for loop to loop through a. for item in a: if item < smallest_item: smallest_item = item print(smallest_item)
#!/usr/bin/env python # We can use the set() function to convert lists into sets. # A set is a data type, just like a list, but it only contains each value once. car_makers = ["Ford", "Volvo", "Audi", "Ford", "Volvo"] # Volvo and ford are duplicates print(car_makers) # Converting to a set unique_car_makers = set(car_makers) print(unique_car_makers) # We can't index sets, so we need to convert back into a list first. unique_cars_list = list(unique_car_makers) print(unique_cars_list[0]) genders_list = [] unique_genders = set() unique_genders_list = [] # Loop through the rows in legislators, and extract the gender column (fourth column) # Append the genders to genders_list. # Then turn genders_list into a set, and assign it to unique_genders # Finally, convert unique_genders back into a list, and assign it to unique_genders_list. for row in legislators: genders_list.append(row[3]) unique_genders = set(genders_list) unique_genders_list = list(unique_genders) print(unique_genders_list[0])
#!/usr/bin/env python class Car(): # The special __init__ function is run whenever a class is instantiated. # The init function can take arguments, but self is always the first one. # Self is a reference to the instance of the class. def __init__(self, car): # Using self before car means that car is an instance property. self.car = car # When we instantiate the class, we pass in any arguments that the __init__ function needs. # We skip the self argument. accord = Car("Honda Accord") # We set self.car in the __init__ function, but can print accord.car here. # self is a reference to the instance of the class. # It lets us interact with the class instance within the class. print(accord.car) # Instance properties are only available to instances, not to the classes. # We couldn't print Car.car, for example. class Team(): name = "Tampa Bay Buccaneers" # Modify the Team class so that name is an instance property. # Make an instance of the class, passing in the value "Tampa Bay Buccaneers" to the __init__ function. # Assign the instance to the variable bucs. class Team(): def __init__(self, name): self.name = name bucs = Team("Tampa Bay Buccaneers")
#!/usr/bin/env python #Read the "crime_rates.csv" file in, split it on the newline character (\n), and store the result into the rows variable # We can split a string into a list. a_string = "This\nis\na\nstring\n" split_string = a_string.split('\n') print(split_string) # Here's another example. string_two = "How much wood\ncan a woodchuck chuck\nif a woodchuck\ncan chuck wood?" split_string_two = string_two.split('\n') print(split_string_two) f = open("crime_rates.csv", "r") a = f.read() rows = a.split('\n')
#!/usr/bin/env python max_val = None data = [-10, -20, -50, -100] for i in data: # If max_val equals None, or i is greater than max_val, then set max_val equal to i. # This ensures that no matter how small the values in data are, max_val will always get changed to a value in the list. # If you are checking if a value equals None and you are using it with and or or, then the None check always needs to come first. if max_val is None or i > max_val: max_val = i # Use a for loop to set min_val equal to the smallest value in income. min_val = None income = [100,700,100,50,100,40,56,31,765,1200,1400,32,6412,987] for i in income: if min_val is None or i < min_val: min_val = i
#!/usr/bin/env python # Let's practice with some list slicing. a = [4,5,6,7,8] # New list containing index 2 and 3. print(a[2:4]) # New list with no elements. print(a[2:2]) # New list containing only index 2. print(a[2:3]) # Assign a slice containing index 2 and 3 from slice_me to slice1. # Assign a slice containing index 1 from slice_me to slice2. # Assign a slice containing index 3 and 4 from slice_me to slice3. slice_me = [7,6,4,5,6] slice1 = slice_me[2:4] slice2 = slice_me[1:2] slice3 = slice_me[3:5]
#!/usr/bin/env python # We can make an empty list with square brackets a = [] # We can also initialize a list with values inside of it b = [1, "I'm a string in a list!", 5.1] c = [1,2,3] d = [5,7,3,2,1] e = ["hello", "world"] f = [10.6, 8.3]