text
stringlengths 37
1.41M
|
---|
"""
# Student class is defined with two different object
class student:
def __init__(self, name, age, subject_1, subject_2, subject_3):
self.name = name
self.age = age
self.sub1 = subject_1
self.sub2 = subject_2
self.sub3 = subject_3
@staticmethod
def marks(numb):
res = numb
print("The mark is", res)
s1 = student("vicky", 24, "Programming", "Database", "Algorithm")
print(s1.name)
print(s1.age)
print(s1.sub1)
print(s1.sub2)
s1.marks(90)
s2 = student("Jay", 25, "IoT", "Networking", "Python")
print(s2.name)
print(s2.age)
print(s2.sub1)
print(s2.sub2)
print(s2.sub3)
s2.marks(100)
# In class we have a function to display the results
class products:
def __init__(self, name, description, price, rating):
self.name = name
self.des = description
self.price = price
self.rate = rating
def display(self):
print(self.name)
print(self.des)
print(self.price)
print(self.rate)
p1 = products("Iphone", "This is Iphone X", 25000, [2, 3, 4, 5, 5])
p1.display()
p2 = products("Xi", "This is Xi 7", 23500, [2, 4, 3, 2, 5])
p2.display()
p3 = products("LENOVO", "This is LENOVO XE", 22900, [2, 5, 5, 2, 5])
p3.display()
"""
"""
# Encapsulation
class student:
def __init__(self, id, name, std):
self.__id = id
self.__name = name
self.__std = std
def display(self):
print(self.__id)
print(self.__name)
print(self.__std)
s1 = student(1, "Vicky", "XII")
s1.display()
s2 = student(2, "John", "XI")
# Alternative method to print the private variables
print(s2._student__id)
print(s2._student__name)
print(s2._student__std)
"""
"""
# Encapsualtion using Setter and Getter Method
class student:
def setId(self,id):
self.id = id
def getId(self):
print(self.id)
def setName(self,name):
self.name = name
def getName(self):
print(self.name)
s = student()
s.setId(100)
s.setName("vicky")
s.getId()
s.getName()
s1 = student()
s1.setId(101)
s1.setName("Peter")
s1.getId()
s1.getName()
"""
"""
#Inheritance
class dog:
def __init__(self, speed, sound, behaviour):
self.spd = speed
self.sound = sound
self.behav = behaviour
class GermanShepard(dog):
def __init__(self, hair, height, speed, sound, behaviour):
super().__init__(speed, sound, behaviour)
self.hair = hair
self.height = height
class Labrador(dog):
def __init__(self, smart_level, speed, sound, behaviour):
#Insted of using Parent class name and self (Dog.) we can use super()
super().__init__(speed, sound, behaviour)
self.smart = smart_level
d=dog("100KM","medium","good")
print(d.spd)
print(d.behav)
print(d.sound)
g = GermanShepard("more", "50", "100KM","medium","good")
print(g.hair)
print(g.height)
l = Labrador("High", "100KM","medium","good")
print(l.smart)
print("Lab", l.behav)
"""
"""
# Polymorphisom
class Dog:
def __init__(self):
pass
def sound(self):
print("BARK BARK")
class Cat:
def __init__(self):
pass
def sound(self):
print("Mewoooooooo")
def callTalk(obj):
obj.sound()
d = Dog()
callTalk(d)
c = Cat()
callTalk(c)
"""
|
# Machine Learning Project
__author__ = 'Eslam Hamouda'
import math
from _operator import itemgetter
import json,sys
#Genres Action | Romance | Horror | Mystry | Sci-Fi
# dummy dataset copied from the IMDb top 250 film with some fabrications.
dataset = dict()
# load the dataset from json file.
with open("recommendation_dataset.json","r") as dataset_file2:
dataset =json.loads(dataset_file2.read())
# calculate the similarity between two films
def GetCosSimilarityForGenres(user_film,dataset_film):
v1_2, v2_2,v1_x_v2 =0,0,0
for i in range(len(user_film[0])):
v1_2 += user_film[0][i] * user_film[0][i]
v2_2 += dataset_film[0][i] * dataset_film[0][i]
v1_x_v2 += user_film[0][i] * dataset_film[0][i]
sim = (v1_x_v2 / (math.sqrt(v1_2) * math.sqrt(v2_2)))
return sim
# some code used for the GUI of this script.
user_film=""
if len(sys.argv) > 1 and sys.argv[1] =="-r": # return the recommended films directly given a film name.
user_film=sys.argv[2]
elif len(sys.argv)>1 and sys.argv[1] =="-list": # return all dataset film names only
for f in dataset.keys():
print(f)
exit(0)
else:
user_film = input("Enter the film name :") # in case you run the script without any arguments you will be asked to enter a film name from the dataset.
# check if the user film in the dataset or not.
if user_film not in dataset.keys():
print("this film is not in the dataset.")
exit(0)
# get the film vector from the dataset
film_attr = dataset[str(user_film)]
final_data = list()
# for each film in the dataset calculate the similarity between it and the user film.
for k,v in dataset.items():
# caculate the similarity based on the film genres.
sim_of_gen = GetCosSimilarityForGenres(film_attr,v)
# then add the total rating of the film to the score.
total_score = (sim_of_gen + v[1])
# don't add the user film itself to avoid recommending it because it's completely similar
if k != user_film:
final_data.append([k,total_score])
# sort the final data by the total score
sorted_data = sorted(final_data,key=itemgetter(1),reverse=True)
# recommend the top 3 films
for i in range(0,3):
print("Film : ",sorted_data[i][0]," | Rate : ", round(sorted_data[i][1],1))
|
"""
Have you ever played "Connect 4"? It's a popular kid's game by the Hasbro company. In this project, your task is create a Connect 4 game in Python.
Before you get started, please watch this video on the rules of Connect 4:
https://youtu.be/utXzIFEVPjA
Author: Ivan Komlev
Date: 2020-10-14
GitHub: https://github.com/Ivan-Komlev/Connect-4
"""
import sys
from termcolor import colored, cprint
import os
from os import system
os.system('color')
bgColor='on_white'
xOffset=10
columns,rows =9,6
#player1name=""
#player2name=""
#Clear screen
print('\x1b[2J')
map = [[0 for i in range(columns)] for j in range(rows)]
#map=[[0]*columns] * rows #Rows [Columns]
#0 = empty space
#1 = red player
#2 = green player
def printMapElement(r,c):
#text = colored(' y:'+str(y)+" ", 'red')#, attrs=['reverse', 'blink']);
if map[r][c]==1:
cprint(" ", 'blue', "on_red", end="");
elif map[r][c]==2:
cprint(" ", 'blue', "on_green", end="");
elif map[r][c]==-1:
cprint("><", 'white', "on_red", end="");
elif map[r][c]==-2:
cprint("><", 'black', "on_green", end="");
else:
cprint(" ", 'blue', bgColor, end="");
return
def findAvalableRow(c):
for r in range(0,rows):
row=rows-r-1
if(map[row][c-1]==0):
return row+1
return -1;#column is full
def markBlocks(won_blocks,turn):
for i in range(0,len(won_blocks)):
map[won_blocks[i][0]][won_blocks[i][1]]=-turn
return won_blocks
def checkIfWon(r,c,turn):# r=1:rows, c=1:columns
r_=r-1 # to start from 0 not from 1
c_=c-1 # to start from 0 not from 1
#check horizontals
won_blocks=[]
count=0
for c_ in range(0,columns):
if(map[r_][c_]==turn):
won_blocks.append([r_,c_])
count+=1
if count==4:
won_blocks=markBlocks(won_blocks,turn)
return True;
else:
count=0
won_blocks=[]
#check vertical
c_=c-1 # to start from 0 not from 1
won_blocks=[]
count=0
for r_ in range(0,rows):
if(map[r_][c_]==turn):
won_blocks.append([r_,c_])
count+=1
if count==4:
won_blocks=markBlocks(won_blocks,turn)
return True;
else:
count=0
won_blocks=[]
#check diagonals
for r_ in range(0,rows-4+1):#rows-4 -------- dont check the imposible
for c_ in range(0,columns-4+1):#columns-4 -------- dont check the imposible
won_blocks=[]
count=0
#check diagonal left to right
c2_=c_
for r2_ in range(r_,r_+4):
if(map[r2_][c2_]==turn):
print("r2_:"+str(r2_)+"c2_:"+str(c2_)+"Found")
won_blocks.append([r2_,c2_])
count+=1
if count==4:
won_blocks=markBlocks(won_blocks,turn)
return True;
else:
count=0
won_blocks=[]
c2_+=1
if c2_==c_+4:
break
won_blocks=[]
count=0
#check diagonal right to left
c3_=columns-c_-1
for r2_ in range(r_,r_+4):
if(map[r2_][c3_]==turn):
won_blocks.append([r2_,c3_])
count+=1
if count==4:
won_blocks=markBlocks(won_blocks,turn)
return True;
else:
count=0
won_blocks=[]
c3_-=1
if c3_<0:
break
return False
def drawTheBoard(rows, columns_):
columns=columns_*2-1
#Drawing Column numbers
print(" "*xOffset,end="")
cprint(" ", 'blue', bgColor, end="")
for j in range(0, columns):
c=(str(int(j/2)+1)+" " if j%2==0 else ' ')
cprint(c, 'blue', bgColor, end="")
cprint(" ", 'blue', bgColor)
#Drawing board top line
print(" "*xOffset,end="")
cprint(" "+u'\u250c', 'blue', bgColor, end="")#left top corner
for j in range(0, columns):
c=(u'\u2500'+u'\u2500' if j%2==0 else u'\u252C')
cprint(c, 'blue', bgColor, end="")
cprint(u'\u2510'+' ', 'blue', bgColor)
for i in range(0, rows):
print(" "*xOffset,end="")
cprint(" "+str(i+1)+u'\u2502', 'blue', bgColor, end="")
for j in range(0, columns):
if j%2==0:
printMapElement(i,int(j/2))
else:
cprint(u'\u2502', 'blue', bgColor, end="")
cprint(u'\u2502'+' ', 'blue', bgColor)
if i<rows-1:
print(" "*xOffset,end="")
cprint(' '+u'\u251C', 'blue', bgColor, end="")
for j in range(0, columns):
c=(u'\u2500'+u'\u2500' if j%2==0 else u'\u253C')#line or cross
cprint(c, 'blue', bgColor, end="")
cprint(u'\u2524'+' ', 'blue', bgColor)
#Drawing board bottom line
print(" "*xOffset,end="")
cprint(" "+u'\u2514', 'blue', bgColor, end="")#left top corner
for j in range(0, columns):
c=(u'\u2500'+u'\u2500' if j%2==0 else u'\u2534')
cprint(c, 'blue', bgColor, end="")
cprint(u'\u2518'+' ', 'blue', bgColor)
return True;
def rules():
print("Welcome to the Connect 4 game.")
print("Rules:")
print("Enter the column you wish to drop your piece in.")
print("When you can connect four pieces vertically, horizontally or diagonally you win")
print("Type 'q' to exit the game.")
def prompter():
turn=1
#Rules
while(True):
color=("Red" if turn==1 else 'Green')
cprint(color+" player, plase enter the column:", color.lower(), end="")
column = input(" ")
if column=="":
cprint('Column is not a number', 'white', 'on_red')
continue
try:
column=int(column)
except (ValueError, TypeError):
if(column=='q' or column=='Q'):
break
else:
cprint('Column is not a number', 'white', 'on_red')
continue
column=int(column)
if column>columns or column<1:
cprint('Column number is outside of range', 'white', 'on_red')
continue
r=findAvalableRow(column)
if r==-1:
#Column is full
cprint('Column is full', 'white', 'on_yellow')
else:
map[r-1][column-1]=turn
if checkIfWon(r,column,turn):
#Clear screen
print('\x1b[2J')
drawTheBoard(rows, columns)
rules()
cprint(color+' won!', 'blue', 'on_white', end="")
break
#Change player
turn+=1
if turn==3:
turn=1
#Clear screen
print('\x1b[2J')
drawTheBoard(rows, columns)
rules()
print()
drawTheBoard(rows, columns)
rules()
print()
prompter()
print(" Bye.")
|
# iterate backwards using char array
def urlify(s, length):
num_spaces = s[:length].count(' ')
url_index = length + 2 * num_spaces - 1
for i in xrange(length - 1, -1, -1):
if s[i] == ' ':
s[url_index] = '0'
s[url_index - 1] = '2'
s[url_index - 2] = '%'
url_index -= 3
else:
s[url_index] = s[i]
url_index -= 1 |
class Dog():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says woof!"
class Cat():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says meow!"
niko = Dog("niko")
felix = Cat("felix")
print(niko.speak())#niko says woof!
print(felix.speak())#felix says meow!
"""
Polymorphism-
Both Nico and Felix share the same method name called Speak.
However, they are different types here ( <class '__main__.Dog'>, <class '__main__.Cat'> )
"""
# Way_1: iterate through different classes and happened to call the same method name
for pet in [niko,felix]:
print(type(pet))
print(type(pet.speak()))
print(pet.speak())
# <class '__main__.Dog'>
# <class 'str'>
# <class '__main__.Cat'>
# <class 'str'>
# Way_2 : Pass in some functions, and called method speak()
# pet and dog share the same method speak()
# pet_speak function takes in different pet object and calls different methods
def pet_speak(pet):
print(pet.speak())
pet_speak(niko)#niko says woof!
pet_speak(felix)#felix says meow! |
import math
# 1 can of paint can cover 5 square meters of wall
wall_height = int(input("Input the height of wall: "))
wall_width = int(input("Input the width of wall: "))
coverage = 5
def paint_calc(height,width,cover):
area = height * width
num_of_cons = math.ceil(area/cover)
print(f"You'll need {num_of_cons} cans of paint")
paint_calc(height=wall_height,width=wall_width,cover=coverage)
|
# https://github.com/Pierian-Data/Complete-Python-3-Bootcamp/blob/master/05-Object%20Oriented%20Programming/02-Object%20Oriented%20Programming%20Homework.ipynb
# Problem 1 計算兩座標的距離 & 斜率
# Fill in the Line class methods to accept coordinates as a pair of tuples and return the slope and distance of the line.
#solution 1 to problem 1
class Line:
def __init__(self,coor1,coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
x1,y1 = self.coor1
x2,y2 = self.coor2
return ((x2-x1)**2 + (y2-y1)**2)**0.5
#((x2-x1)的二次方+(y2-y1)的一次方)開根號 開根號相當於0.5次方
def slope(self):
x1,y1 = self.coor1
x2,y2 = self.coor2
return (y2-y1)/(x2-x1)
c1 = (3,2)
c2 = (8,10)
myline = Line(c1,c2)
print(myline.distance())
print(myline.slope())
#solution 2 to problem 1
class Line02:
def __init__(self,coor1,coor2):
self.x1,self.y1 = coor1
self.x2,self.y2 = coor2
def distance(self):
return ((self.x2-self.x1)**2 + (self.y2-self.y1)**2)**0.5
#((x2-x1)的二次方+(y2-y1)的一次方)開根號 開根號相當於0.5次方
def slope(self):
return (self.y2-self.y1)/(self.x2-self.x1)
c1 = (3,2)#9.433981132056603
c2 = (8,10)#1.6
myline02 = Line02(c1,c2)
print(myline02.distance())
print(myline02.slope())
# Problem 2 計算圓柱體體積(volume)和表面面積
class Cylinder:
pi = 3.14
def __init__(self,height=1,radius=1):
self.height = height
self.radius = radius
def volume(self):
return self.height * 3.14 * (self.radius)**2
def surface_area(self):
top = 3.14 * (self.radius**2)
return (top*2) + (self.radius*2*3.14*self.height)
#圓周長 = 直徑*3.14
#圓面積 = 半徑*半徑*3.14
#表面面積 上下兩個圓面積+ 長方形面積(半徑*2*3.14*height)
# EXAMPLE OUTPUT
mycylinder = Cylinder(2,3)
print(mycylinder.volume())#56.52
print(mycylinder.surface_area())#94.2 |
# # Practice_6: Use a Debugger
# def mutate(a_list):
# b_list = []
# for item in a_list:
# new_item = item * 2
# b_list.append(new_item)
# print(b_list)
# mutate([1,2,3,5,8,13])
"""
Use a Debugger 題目分析
def mutate(a_list):
b_list = []
for item in a_list:
new_item = item * 2
b_list.append(new_item)
print(b_list)
print(a_list)
mutate([1,2,3,5,8,13])
# mutate 是一個function物件,這個function傳入一個叫a_list的list,
# 於是mutate這個物件中有新的變數a_list
# create b_list 變數,是個空陣列
# 迴圈走訪a_list *2,又產生一個新變數new_item
# b_list.append(new_item) 只會將迴圈走訪到的最後一個new_item存入b_list
# print(b_list) [26] 故最後印出b_list只會印出陣列中只有一個項目
# print(a_list) [1, 2, 3, 5, 8, 13] 仍舊印出所有陣列項目
"""
#Practice_6: solution
def mutate(a_list):
b_list = []
for item in a_list:
new_item = item * 2
b_list.append(new_item)
print(b_list)#[2, 4, 6, 10, 16, 26]
mutate([1,2,3,5,8,13])
|
def format_name(f_name,l_name):
"""Take a first and last name and format it to return the title
case version of the name"""
if f_name == "" or l_name == "":
return "You didn't provide valid inputs."
formated_f_name = f_name.title()
formated_l_name = l_name.title()
#print(f"{formated_f_name} {formated_l_name}")
return f"{formated_f_name} {formated_l_name}"
formated_string = format_name("AnGELA","YU")
print(formated_string)
|
def func():
return 1
print(func())#1
def hello():
return "Hello"
print(hello())#Hello
print(type(hello))#<class 'function'>
greet = hello
print(type(greet))
print(greet())#Hello
|
"""
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
You've visited Russia 2 times.
You've been to Moscow and Saint Petersburg.
"""
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris","Lille","Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin","Hamburg","Stuttgart"]
},
]
#TODO: Write the function that will allow new countries
#to be added to the travel_log.
def add_new_country(country_visited,times_visited,cities_visited):
new_country = {}
#new_country[key] = value
new_country["country"] = country_visited
new_country["visits"] = times_visited
new_country["cities"] = cities_visited
travel_log.append(new_country)
# way_2
# new_country = {"country":country_visited,"visits":times_visited,"cities":cities_visited}
# travel_log.append(new_country)
#Do not change the code below
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log) |
from art import logo
print(f"\033[31m{logo}\033[00m")
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def caesar(plain_text,shift_amount,direction_side):
word = ""
if direction == "decode":
shift_amount *= -1
for item in text:
index_number = alphabet.index(item)
position = index_number + shift_amount
while position > 25:
position -=26
letter = alphabet[position]
word += letter
print(word)
end_of_game = False
#while game not end
while not end_of_game:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt :\n ")
text = input("input your message:\n").lower()
shift = int(input("type the shift number:\n"))
caesar(plain_text=text,shift_amount=shift,direction_side=direction)
exit = input("Do you want to exit the game? yes or no ")
if exit == "yes":
end_of_game = True
print("Goodbye")
|
name = input("What's your character's name? ")
print("Your character's name is", name, "\n", end="")
game = input("Would you like to begin the game? Enter Yes or No: ")
print(game)
"Yes" == "yes"
"No" == "no"
if game == "yes":
print(name)
elif game == "no":
quit()
else:
print("Please enter yes or no."
#Y = char_name
#N = quit()
#print(game)
#if input
|
#a = '*'
#b = 0
#while b < 5:
#b = b + 1
#print(a)
#a = a + '*'
#a = '*'
#b = 0
#while b < 5:
#b = b + 1
#print(a)
#a = a + '*'
x = 0
y = 0
r = 25
n = 2*r
while y < n:
x = 0
while x < n:
if (x-r)**2 + (y-r)**2 < r**2:
print('*', end="")
else:
print(' ', end="")
x = x + 1
print()
y = y + 1
#r = x**2 + y**2
#a = '*'
#while x < r:
#x = x + x
#print(a)
#while y < r:
#y = y + y
#print(a)
#b = 4**2 + 6**2
#print(b)
#a = '*'
#x = 4#y = 6
# x**2 + y**2 < r**2
# print "my string", end="")
|
def prime(n):
l = [0]*n
p = 2
while p < n:
if l[p] == 0:
q = 2*p
while q < n:
l[q] = 1
q = q + p
p = p + 1
result = []
i = 2
while i < n:
if l[i] == 0:
result.append(i)
i = i + 1
return result
#print(prime(200))
|
graph={
'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':['H','I'],
'E':['J','K'],
'F':['L','M'],
'G':['N','O'],
'H':[],
'I':[],
'J':[],
'K':[],
'L':[],
'M':[],
'N':[],
'O':[],
}
def dls(start,goal,path,level,maxD):
print("\nCurrent level-->",level)
print("Goal testing for",start)
path.append(start)
if start==goal:
print("goal test successful")
return path
print("goal node testing failed")
if level==maxD:
return False
print("\n Expanding the current node",start)
for child in graph[start]:
if dls(child,goal,path,level+1,maxD):
return path
path.pop()
return False
start='A'
goal=input("enter the goal node to be found")
maxD=int(input("Enter the maximum depth:--"))
path=list()
res=dls(start,goal,path,0,maxD)
if(res):
print("path to the goal node found")
print("path",path)
else:
print("no path available in the given depth limit")
|
#Hello there!!!....myself Rakesh pandey
#Building a TicTacToe game!!!
import os
from time import sleep
#define board
board=[" "," "," "," "," "," "," "," "," "]
def printboard():
print(" ---- " * 3)
print("|", board[0], " ", "|", board[1], " ", "|", board[2], " ", "|")
print(" ---- " * 3)
print("|", board[3], " ", "|", board[4], " ", "|", board[5], " ", "|")
print(" ---- " * 3)
print("|", board[6], " ", "|", board[7], " ", "|", board[8], " ", "|")
print(" ---- " * 3)
flag ="X"
count=0
while True:
if flag=="X":
os.system('cls')
print("Tic-Tac-Toe game!!!!!")
print("Made by RAKESH PANDEY")
printboard()
#Taking input from user for values of X
try:
choice = (int(input("enter the position to fill X \n"))-1)
except ValueError:
print("enter only integer values between 1-9")
sleep(1)
flag = "1"
try:
if flag=="1" :
flag="X"
elif board[choice]==" ":
board[choice]="X"
flag = "0"
count = count+1
else :
print("position already occupied choose another")
sleep(1)
flag="X"
except IndexError:
print("pagal hai kya.....9 hi spaces hai....enter between 1-9")
sleep(1)
flag ='X'
#Checking condition if X wins
xwin = (board[0] == board[1] == board[2] == "X") \
or (board[3] == board[4] == board[5] == "X") \
or (board[6] == board[7] == board[8] == "X") \
or (board[0] == board[3] == board[6] == "X") \
or (board[1] == board[4] == board[7] == "X") \
or (board[2] == board[5] == board[8] == "X") \
or (board[0] == board[4] == board[8] == "X") \
or (board[2] == board[4] == board[6] == "X")
#IF x wins asking for playagain or exit !!!
if (xwin):
os.system('cls')
print("Tic-Tac-Toe game!!!!!")
print("Made by RAKESH PANDEY")
printboard()
print("X won....well played...although little advantage of being first turn !!!")
sleep(3)
play = input("wanna play again??..(yes/no)")
if (play == "yes"):
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
flag = "X"
count = 0
elif (play == "no"):
print("Thanks for playing")
sleep(2)
break
else:
print("cant type properly.....u idiot!!!....play nextime!!! byee!!")
sleep(2)
break
#Checking condition for Draw !!!!
if (count == 9):
os.system('cls')
print("Tic-Tac-Toe game!!!!!")
print("Made by RAKESH PANDEY")
printboard()
print("Match drawn....Both were Fantastic")
sleep(2)
play=input("wanna play again??..(yes/no)")
if(play=="yes"):
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
flag="X"
count=0
elif (play == "no"):
print("Thanks for playing")
sleep(2)
break
else:
print("cant type properly.....u idiot!!!....play nextime!!! byee!!")
sleep(2)
break
if flag=="0":
os.system('cls')
print("Tic-Tac-Toe game!!!!!")
print("Made by RAKESH PANDEY")
printboard()
#Taking input for 0 user !!!
try:
choice = (int(input("enter the position to fill 0 \n"))-1)
except ValueError:
print("enter only integer values between 1-9")
sleep(1)
flag = "1"
try:
if flag=="1" :
flag="0"
elif board[choice]==" ":
board[choice]="0"
flag = "X"
count=count+1
else :
print("position already occupied choose another")
sleep(1)
flag="0"
except IndexError:
print("pagal hai kya.....9 hi spaces hai....enter between 1-9")
sleep(1)
flag = '0'
#Checking condition if 0 wins
owin = (board[0] == board[1] == board[2] == "0") \
or (board[3] == board[4] == board[5] == "0") \
or (board[6] == board[7] == board[8] == "0") \
or (board[0] == board[3] == board[6] == "0") \
or (board[1] == board[4] == board[7] == "0") \
or (board[2] == board[5] == board[8] == "0") \
or (board[0] == board[4] == board[8] == "0") \
or (board[2] == board[4] == board[6] == "0")
# IF x wins asking for playagain or exit !!!
if (owin):
os.system('cls')
print("Tic-Tac-Toe game!!!!!")
print("Made by RAKESH PANDEY")
printboard()
print("0 won....well played 0 are not always loser")
sleep(3)
play = input("wanna play again??..(yes/no)")
if (play == "yes"):
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
flag = "X"
count = 0
elif(play=="no"):
print("Thanks for playing")
sleep(2)
break
else:
print("cant type properly.....u idiot!!!....play nextime!!! byee!!")
sleep(2)
break
|
username=input("enter the user name\t")
password=input("Enter the password\t")
hidden_password=len(password)*"*"
print(f"yeah! your username is {username} \n your secret password is\t{hidden_password}")
|
# .endswith() => metnin parametrede gönderdiğiniz değer ile bitip bitmediğini True / False değer olarak döner.
metin = "murat vuranok"
sonuc = metin.endswith("ok")
if sonuc:
print("metin ok kelimesi ile bitmektedir.")
else:
print("metin ok kelimesi ile bitmemektedir.")
#Ternary kullanımı
print("metin ok kelimesi ile bitmektedir.") if sonuc else print("metin ok kelimesi ile bitmemektedir.")
#metin ok kelimesi ile bitmektedir.
|
import datetime
now = datetime.datetime.now()
print(str(now))
#2019-07-21 10:21:20.236668
print(repr(now))
#datetime.datetime(2019, 7, 21, 10, 22, 2, 890202
class Personel:
def __init__(self,isim):
self.FirstName = isim
def __repr__(self):
return "Personel ( '{}', '{}' )".format(self.FirstName,self.FirstName)
def __str__(self):
return "{}-{}".format(self.FirstName,self.FirstName)
per = Personel("Berke")
print(str(per)) #Berke-Berke
print(repr(per)) #Personel ( 'Berke', 'Berke' )
print(str(per)) #Berke-Berke
print(per.__repr__()) #Personel ( 'Berke', 'Berke' ) #developer için devam niteliğinde kod verir.
print(per.__str__()) #Berke-Berke #son kullanıcı için çıktı verir.
|
# Dısarıdan aldığı ismi ve soyisime göre mail adresi oluşturan metot. ([email protected])
# Kulanıcı 2. parametreye değer girmeyebilir.
def Mail(a,b = None):
mail = ""
if b is None:
mail ="{}@bilgeadam.com".format(a)
else:
mail = "{}.{}@bilgeadam.com".format(a,b)
print(mail)
#isim = input("İlk isminizi giriniz :").lower()
#soyisim = input("Soyisminizi giriniz : ").lower()
Mail(input("İlk isminizi giriniz :").lower())
Mail(input("İlk isminizi giriniz :").lower(),input("Soyisminizi giriniz : ").lower())
|
# Mantıksal Operatorler
#----------------------
# and => Sorguya katılan her bir koşulun sağlanması
# or => Sorguya katılan herhangi bir koşulun sağlanması
# not => Sorgula olumsuzlık katar; True ise False, False ise True döndürür.
user_name = input("Lütfen kullanıcı adınızı giriniz : ")
if user_name == "admin" : # db içerisinde var mı ?
password = input("Lütfen şifrenizi adınızı giriniz : ")
if password == "123":
print("Giriş yaptınız !")
else:
print("Şifreniz yanlış.")
else:
print("Kullanıcı adınız yanlış.")
user_name = input("Lütfen kullanıcı adınızı giriniz : ")
password = input("Lütfen şifrenizi adınızı giriniz : ")
if user_name == "admin" and password == "123":
print("Tebrikler!")
else:
print("Kullanıcı bilgilerinizi kontrol ediniz.") |
try:
number = int(input("Lütfen birinci sayiyi giriniz : "))
number2 = int (input("Lütfen ikinci sayiyi giriniz : "))
toplam = number+number2
fark = number-number2
bolum = number/number2
carpim = number*number2
print("Sayilarin toplamı : ",toplam,
"\nSayıların farkı : ",fark,
"\nSayıların bölümü : ",bolum,
"\nSayıların çarpımı : ",carpim)
except (ValueError,SyntaxError):
print("Value Error hatası veya Syntax Error hatası")
except ZeroDivisionError:
print("Zero Division Error hatası")
except FileExistsError:
print("File Exists Error")
except:
print("Hata mesajı") |
# Tanımlama şekli
# Bir dizinin maksimum index değeri, eleman sayısının bir eksi değeridir.
sehirler = ["ankara","edirne","eskisehir","istanbul","kars","kayseri","istanbul"] #List
# eleman sıra no : 1,2,3,4,5,6,7
# eleman index no : 0,1,2,3,4,5,6
print(sehirler[0])
index = len(sehirler)-1
print(sehirler[index])
print(sehirler[0:4]) # 1. paramatre index değeri, 2.parametre ise verilen index değerinin bir alt değerine kadar yazdırır
print(sehirler[:])
|
#Şifrenin 3 defa yanlış girilmesi durumunda kullanıcıyı uyaran uygulama
#password = "abc123"
#fail_count = 0
#for i in range(3):
# password_user = input("Şifrenizi giriniz : ")
# if (password==password_user):
# print("Giriş Sağlandı")
# break
# else:
# print("Hatalı şifre girdiniz.")
# fail_count+=1
# if(fail_count==3):
# print("Şifrenizi 3 kez hatalı girdiniz. Hesabınız bloke edilmiştir.")
# break
from builtins import print
for i in range(3):
parola = input("Şifrenizi giriniz : ")
if i == 2 :
print("Şifrenizi 3 defa yanlış girdiniz.")
elif not parola :
print("Parola boş geçilemez !!")
elif len(parola) in range(3,8):
print("Parolanız : ",parola,"olarak belirlenmiştir!")
break
else:
print("WTF") |
def fib1(n):
"""in tabe ozve n om donbale fibonachi ra midahad"""
if n==1 or n==2:
return 1
return fib1(n-1)+fib1(n-2)
list1=[]
def fib2(n):
"""in tabe listi az n ozve avval donbale fibonachi ra midahad"""
i=n
while n:
if fib1(n) not in list1:
list1.append(fib1(n))
n -=1
if i>1:
list1.append(1)
list2=list1.copy()
list1.clear()
return list2
|
'069'
a=('Germany','France','UK','Spain','Italy')
print(a)
b=input('\nplease enter one of the vountries above: ')
i=0
for name in a:
if b.upper()==name.upper():
print(i)
i+=1
'070'
j=0
c=int(input('now enter a number (from 0 to 4): '))
for value in a:
if j==c:
print(value)
j+=1
'071'
sports=['football','hockey']
a=input('whats your favorite sport?: ')
sports.append(a)
sports.sort()
print(sports)
'072'
list1=['chemistry','physics','math','sports','history','geography']
print(list1)
a=input("which one of these don't you like?: ")
if a.lower() in list1:
list1.remove(a.lower())
print(list1)
'073'
i=1
dict1={}
print('please enter 4 items: ')
while(i<=4):
a=input('please enter item number '+str(i) + ' : ')
dict1[i]=a
i+=1
print(dict1)
a=input('enter which one you want to get rid of: ')
if a in dict1.values():
for key in dict1:
if a == dict1[key]:
b=key
dict1.pop(b)
list2=[]
for value1 in dict1.values():
list2.append(value1)
print(list2)
list2.sort()
dict2={}
l=0
for value in list2:
for k in dict1:
if dict1[k]==value:
l+=1
dict2[l]=value
print(dict2)
'074'
list1=['red','blue','purple','yellow','green','pink','orange','brown','black','grey']
print (list1)
a=int(input('please enter starting number:(between 0 and 4) '))
b=int(input('please enter ending number:(between 5 and 9) '))
print(list1[a:b])
'075'
list1=[123,542,234,678]
for a in list1:
print(str(a)+'\n')
a=int(input('please enter a three digit number: '))
i=0
if a in list1:
while(i<=3):
if list1[i]==a:
print('the position is:(from 0 to 3) ' + str(i))
i+=1
else:
print('this number is not on the list')
'076'
list1=[]
i=3
while i>1:
a=input('please enter a name to add to your list: ')
list1.append(a)
i-=1
e=''
i=0
while(e!='no'):
a=input('please enter a name to add to your list: ')
e=input('do you want to add more people?: ').lower()
list1.append(a)
for value in list1:
i+=1
print('you have invited ' + str(i) + ' people to your party')
'077'
print(list1)
a=input('enter one of the names on the list: ')
i=0
for value in list1:
if value==a:
print('this is the position on the list: '+str(i))
i+=1
b=input('do you still want them on the list?: ')
if b.lower()=='no':
list1.remove(a)
print(list1)
'078'
list1=['Show1','Show2','Show3','Show4']
print(list1)
a=input('enter another TV show: ')
b=int(input('where do you want to put it?:(from 0 to 4) '))
list1.insert(b,a)
print(list1)
'079'
nums=[]
i=0
while i<=2:
a=int(input('enter a number: '))
i+=1
nums.append(a)
print(nums)
b=input('do you want the last number you entered?: ')
if b.lower()=='no':
nums.pop()
print(nums)
|
# Comparison of the Kalman filter and the histogram filter.
# 06_f_kalman_vs_histogram_filter
# Claus Brenner, 29 NOV 2012
from distribution import *
from math import sqrt
from matplotlib.mlab import normpdf
from pylab import plot, show, ylim
def move(distribution, delta):
"""Returns a Distribution that has been moved (x-axis) by the amount of
delta."""
"""Returns a Distribution that has been moved (x-axis) by the amount of
delta."""
d = distribution
moved_distribution = Distribution(d.start()+delta,d.values[:])
"""when a function pass parameter through the parenthese in inner, we have to use
the data from the passed Obeject, rather than just create manutelly, because
manutelly created data pass only in this specify case.
how? find the class.py about the data extracted way."""
#moved_distribution = Distribution.triangle(d.start()+1+delta,2)
# --->>> Insert your code here.
return moved_distribution # Replace this by your own result.
# --->>> Copy your previous code here.
return distribution # Replace this by your own result.
def convolve(a, b):
"""Convolve distribution a and b and return the resulting new distribution."""
# --->>> Copy your previous code here.
multi_value = []
Dist_List = []
#d = Distribution()
# --->>> Put your code here.
""" enumerate() returns a tuple containing a count (from start which defaults
to 0) and the values obtained from iterating over iterable.
the second way to construct a loop is for value in list, which take directally
the value, no more list[i] needed to represent the value"""
for i,a_val in enumerate(a.values):
for b_val in b.values:
multi_value.append(a_val*b_val)
Dist_List.append(Distribution(a.start()+b.start()+i,multi_value[:]))
"""i hier is to move step every loop """
multi_value = []# clear the list to avoid data confused
"""if you use a container in a loop, remenber to take care, if
if the container should be clear after used?"""
d = Distribution.sum(Dist_List[:])
return d # Replace this by your own result.
return a # Replace this by your own result.
def multiply(a, b):
"""Multiply two distributions and return the resulting distribution."""
multi_value = []
"""two kurve which need one for loop can use this way to decide a start and end
point"""
start = a.start() if a.start()>b.start() else b.start()
stop = a.stop() if a.stop()<b.stop() else b.stop()
for i in xrange(start,stop):
multi_value.append(a.value(i)*b.value(i))
d = Distribution(start,multi_value)
Distribution.normalize(d)#the normalize function dont need to write ourself, just
#use it, but my way kann
return d
# --->>> Copy your previous code here.
return a # Modify this to return your result.
# Helpers.
#
class Density:
def __init__(self, mu, sigma2):
self.mu = float(mu)
self.sigma2 = float(sigma2)
def histogram_plot(prediction, measurement, correction):
"""Helper to draw all curves in each filter step."""
plot(prediction.plotlists(*arena)[0], prediction.plotlists(*arena)[1],
color='#C0C0FF', linestyle='steps', linewidth=5)
plot(measurement.plotlists(*arena)[0], measurement.plotlists(*arena)[1],
color='#C0FFC0', linestyle='steps', linewidth=5)
plot(correction.plotlists(*arena)[0], correction.plotlists(*arena)[1],
color='#FFC0C0', linestyle='steps', linewidth=5)
def kalman_plot(prediction, measurement, correction):
"""Helper to draw all curves in each filter step."""
plot([normpdf(x, prediction.mu, sqrt(prediction.sigma2))
for x in range(*arena)], color = 'b', linewidth=2)
plot([normpdf(x, measurement.mu, sqrt(measurement.sigma2))
for x in range(*arena)], color = 'g', linewidth=2)
plot([normpdf(x, correction.mu, sqrt(correction.sigma2))
for x in range(*arena)], color = 'r', linewidth=2)
#
# Histogram filter step.
#
def histogram_filter_step(belief, control, measurement):
"""Bayes filter step implementation: histogram filter."""
# These two lines is the entire filter!
prediction = convolve(belief, control)
correction = multiply(prediction, measurement)
return (prediction, correction)
#
# Kalman filter step.
#
def kalman_filter_step(belief, control, measurement):
"""Bayes filter step implementation: Kalman filter."""
# --->>> Put your code here.
# Prediction.
prediction = Density(belief.mu + control.mu, belief.sigma2 + control.sigma2) # hier a=1
# Correction.
K = prediction.sigma2/(prediction.sigma2+measurement.sigma2)
Mu = prediction.mu+K*(measurement.mu-prediction.mu)
Sigma2 = (1- K)*prediction.sigma2
correction = Density(Mu,Sigma2) # Replace
return (prediction, correction)
#
# Main
#
if __name__ == '__main__':
arena = (0,200)
Dist = Distribution.gaussian # Distribution.triangle or Distribution.gaussian.
# Start position. Well known, so the distribution is narrow.
position = Dist(10, 1) # Histogram
position_ = Density(10, 1) # Kalman
# Controls and measurements.
controls = [ Dist(40, 10), Dist(70, 10) ] # Histogram
controls_ = [ Density(40, 10**2), Density(70, 10**2) ] # Kalman
measurements = [ Dist(60, 10), Dist(140, 20) ] # Histogram
measurements_ = [ Density(60, 10**2), Density(140, 20**2) ] # Kalman
# This is the filter loop.
for i in xrange(len(controls)):
# Histogram
(prediction, position) = histogram_filter_step(position, controls[i], measurements[i])
histogram_plot(prediction, measurements[i], position)
# Kalman
(prediction_, position_) = kalman_filter_step(position_, controls_[i], measurements_[i])
kalman_plot(prediction_, measurements_[i], position_)
ylim(0.0, 0.06)
show()
|
#coding:utf-8
import random
import time
def regiun():
'''生成身份证前六位'''
#列表里面的都是一些地区的前六位号码
first_list = ['360881','360802','120101','130102','440881','110100','110101','110102','110103','110104','110105','110106','110107','110108','110109','110111']
first = random.choice(first_list)
return first
def year():
'''生成年份'''
now = time.strftime('%Y')
#1948为第一代身份证执行年份,now-18直接过滤掉小于18岁出生的年份
second = random.randint(1948,int(now)-18)
age = int(now) - second
return second
def month():
'''生成月份'''
three = random.randint(1,12)
#月份小于10以下,前面加上0填充
if three < 10:
three = '0' + str(three)
return three
else:
return three
def day():
'''生成日期'''
four = random.randint(1,28)
#日期小于10以下,前面加上0填充
if four < 10:
four = '0' + str(four)
return four
else:
return four
def id_card1():
'''生成身份证后四位'''
#后面序号低于相应位数,前面加上0填充
five = random.randint(100,999)
first = regiun()
second = year()
three = month()
four = day()
temp = str(first)+str(second)+str(three)+str(four)+str(five)
temp_list = []
for i in temp:
temp_list.append(i)
power = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
refNumber = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"]
result = 0
for i in range(len(power)):
result += power[i] * int(temp_list[i])
id_card = temp + refNumber[(result%11)]
return id_card
#print id_card
|
try:
a = 5/0
print(a)
except ZeroDivisionError as err:
print('Ты тупой - делишь на ноль')
print('123')
while True:
try:
number = int(input("Введите число:"))
print("Число умноженное на 5: {0}".format(number*5))
print("10 делим на {0} = {1} ".format(number, 10/number))
break
except ValueError:
print("Дурак - тебе же сказанно введи ЧИСЛО.\
ЧИСЛО ЧИСЛО Я СКАЗАЛ")
except ZeroDivisionError:
print('Ты тупой - делишь на ноль. Введи нормальное число')
finally:
print("Ты все равно тупой")
# raise ZeroDivisionError
class TupoyError(Exception): pass
try:
name = input('Введи имя')
if name == 'Арсен':
raise TupoyError
except TupoyError:
print('Вы ввели Арсен - это очень прекрасно. Фатальная ошибка') |
print("Good boys")
p = 5
print(p)
b = p
print(b, p)
p = 'Halid'
b = 'Gadzhi'
d = "50"
p = 5
p = p * 10
p = str(p) + d
boo = False
h = 'Halid'
g = (h + ' ') * 10
print(b[::-1], p, g[:-1])
print(len(h))
str1 = "кошки, собаки,арбузы, грызуны"
lis = str1.split(',')
print(lis)
lis2 = ['halid','gadzhi','isa','aliomar']
print(lis2)
str2 = '. '.join(lis2)
print(str2)
str4 = "lalalalaalalaa\
alaldlasldal"
print(str4)
stih = """У лукоморье дум зеленый,
А ты у нас такой соленый,
Вай фай не смог поймать я сам
Русалку попросил в вотсап"""
print(stih)
print(stih.endswith('вотс'))
print(stih.lower())
print(stih.replace('соленый','зеленый')) |
name = 'Абдурахман'
age = 14
coolness = 20.3
print(name + " красавчик " + "Его возраст: " + str(age)
+ " Он крут на " + str(coolness) + "%")
print("%10.7s красавчик. Его возраст %10.5d лет. \
Его крутость %10.2f%%" % (name, age,coolness))
print("{0:ы^20s} красавчик. Его возраст {0} лет. \
Его крутость {0}%".format(name, age, coolness))
real = {'нападающий':'Роналдо','полузащитник':'Абдурахман',
'защитник':'Пеппа','вратарь':'Навас'}
print('В реале нападающий - {0[нападающий]}. \
Вратарь - {0[вратарь]}. А еще есть парень - {1}'.format(real, 'Али'))
print('{n} {p} {d}'.format(n="Али",p="хороший",d="мужичара"))
dog = "Мухта"
dog_count = 1
print('У нас {0} {1}{2}'.format(dog_count,dog,
'р' if dog_count == 1 else 'ра'))
|
import random
def get_card(player):
while True:
yield player.pop()
def play(player1,player2):
k = 0
global player1_count, player2_count
for card1, card2 in zip(get_card(player1), get_card(player2)):
k += 2
print(card1,card2)
if card1[0] > card2[0]:
player1_count += k
break
elif card1[0] < card2[0]:
player2_count += k
break
m = ["Черви", "Пики", "Бубны","Крести"]
deck = [(num, mast) for num in range(2,15) for mast in m]
# print(deck)
random.shuffle(deck)
# print(deck)
player1 = deck[:len(deck)//2]
player2 = deck[len(deck)//2:]
# print(player1,'---',player2)
player1_count = 0
player2_count = 0
while True:
play(player1, player2)
print(player1_count,player2_count)
input()
if not player1 or not player2:
break
|
menu = {
"breakfast": {
'hours': '8:00',
'items': [ 'Яихница','Чай']
},
'lunch': {
'hours': '12:00',
'items': ['Шамбургер', 'Суп', 'Компот']
}
}
print(menu)
import json
menu_json = json.dumps(menu)
print(menu_json)
with open('menu.json','wt',encoding='utf-8') as f1:
f1.write(menu_json)
menu2 = json.loads(menu_json)
print(menu2)
with open('menu.json', 'rt',encoding='utf-8') as f2:
menu3 = f2.read()
menu3 = json.loads(menu3)
print(menu3)
|
price = {"энергия":1542,"отопление":1542,"горячая вода":92}
def show_price(usluga):
print("цена на {0} = {1}".format(usluga, price[usluga]))
def est_usluga(usluga):
if usluga in price:
return True
else:
return False |
class Chert:
count = 0
@classmethod
def show_count(cls):
print("У нас на районе {0} черта".format(cls.count))
def __init__(self,name,hair,strengh):
self.name = name
self.hair = hair
self.heeyar = True
self.strengh = strengh
self.__jaguar = 5
Chert.count += 1
@property
def jaguar(self):
print("Возвращает колличество ягуара")
return self.__jaguar
@jaguar.setter
def jaguar(self,something):
self.__jaguar = something
def strike(self,target):
if self.__jaguar > 0:
print("{0} кидает ягуар в {1}".format(self.name, target))
self.__jaguar -= 1
else:
print("Кончилась яга")
def __str__(self):
return self.name
def __len__(self):
return self.hair
def __iadd__(self, other):
self.jaguar += other
return self
def __lt__(self,other):
return self.hair < other.hair
said = Chert('chert',100,12)
said.strike('бабушку')
for i in range(1,13):
said.strike('бабушку')
print(said.jaguar)
said.jaguar += 5
for i in range(1,13):
said.strike('бабушку')
n = 5
tagir = Chert('Тагуха-Ашшашитн',169,12)
tagir += 5
print(tagir.jaguar)
print(tagir)
print(len(tagir))
print(Chert.count)
Chert.show_count()
print(said < tagir) |
import sqlite3
def create_db():
curs.execute("""CREATE TABLE IF NOT EXISTS questions
(type VARCHAR(50) PRIMARY KEY,
question VARCHAR(250))""")
ins = "INSERT OR REPLACE INTO questions VALUES(?, ?)"
curs.execute(ins,('shmot','За шмот поясни?'))
curs.execute(ins,('age','Сколько тебе есть?'))
curs.execute(ins,('children','Цп есть?'))
curs.execute(ins,('location','Откуда ты?'))
curs.execute("""CREATE TABLE IF NOT EXISTS peoples
(name VARCHAR(50) PRIMARY KEY,
shmot VARCHAR(50),
age VARCHAR(50),
children VARCHAR(50),
location VARCHAR(50))""")
curs.execute("INSERT OR REPLACE INTO peoples VALUES('Расул','да','да','да','да')")
conn.commit()
def know_you(name):
curs.execute("SELECT name FROM peoples WHERE name = ?",(name,))
raws = curs.fetchall()
for raw in raws:
if name in raw:
print(1)
return True
else:
print(2)
return False
def show_info(name):
curs.execute("SELECT * FROM peoples WHERE name = ?",(name,))
raws = curs.fetchall()
print("Я о тебе все знаю. Ты за шмот {0[1]}. Тебе лет {0[2]}. У тебя есть цп {0[3]}. Ты из {0[4]}".format(raws[0]))
def add_man(name):
pass
conn = sqlite3.connect('pahan.db')
curs = conn.cursor()
create_db()
print("Я пахан? А ты?")
name = input()
if know_you(name):
show_info(name)
else:
add_man(name)
curs.close()
conn.close() |
example=input("Give input: ")
def pal(example):
b=example[::-1]
if example==b:
return "True"
return "false"
print(pal(example)) |
import mysql.connector # to connect python to a mysql database
import requests # will allow us to send HTTP requests to get HTML files
from requests import get
from bs4 import BeautifulSoup # will help us parse the HTML files
import pandas as pd # will help us assemble the data into a DataFrame to clean and analyze it
import numpy as np # will add support for mathematical functions and tools for working with arrays
import math # to check for nan float values
# To make sure we get English-translated titles from all the movies we scrape
headers = {"Accept-Language": "en-US, en;q=0.5"}
# Requesting the URL to get the contents of the page
url = "https://www.imdb.com/search/title/?groups=top_1000&ref_=adv_prv&ref"
results = requests.get(url, headers=headers)
# Make the content we grabbed easy to read by using BeautifulSoup
soup = BeautifulSoup(results.text, "html.parser")
# initialize empty lists where we will store our data
titles = []
years = []
time = []
imbd_ratings = []
metascores = []
votes = []
us_gross = []
# On the IMBD website, each movie div has the class lister-item mode-advanced.
# We will need the scraper to find all of the divs with this class
movie_div = soup.find_all('div', class_='lister-item mode-advanced')
# We need to loop the scraper to iterate for all movies
for container in movie_div:
# Add the elements based on their tags in the div
name = container.h3.a.text
titles.append(name)
year = container.h3.find('span', class_='lister-item-year').text
years.append(year)
runtime = container.find('span', class_='runtime').text if container.p.find('span', class_='runtime') else '-' # Find the runtime, or put a dash if no runtime is listed
time.append(runtime)
imbd = float(container.strong.text)
imbd_ratings.append(imbd)
m_score = container.find('span', class_='metascore').text if container.find('span', class_='metascore') else '-1' # I am setting -1 if there is no score because we need to convert this datatype to an int and can't do so with '-'
metascores.append(m_score)
# Some movies have votes and gross earnings, while others do not. This code block addresses this issue
nv = container.find_all('span', attrs={'name': 'nv'})
vote = nv[0].text
votes.append(vote)
grosses = nv[1].text if len(nv) > 1 else '-'
us_gross.append(grosses)
# We will build a DataFrame using pandas to store our data in a table.
movies = pd.DataFrame({
'movie': titles,
'year': years,
'timeMin': time,
'imbd': imbd_ratings,
'metascore': metascores,
'votes': votes,
'us_grossMillions': us_gross,
})
# Cleaning up the data as everything except for imbd ratings is being stored as an object.
# Converting years to an int.
movies['year'] = movies['year'].str.extract('(\d+)').astype(int)
# Converting time to an int.
movies['timeMin'] = movies['timeMin'].str.extract('(\d+)').astype(int)
# Converting metascore to an int.
movies['metascore'] = movies['metascore'].astype(int)
# Converting votes to an int and removing commas
movies['votes'] = movies['votes'].str.replace(',', '').astype(int)
# Converting gross data to float and removing the dollar signs and the Ms.
movies['us_grossMillions'] = movies['us_grossMillions'].map(lambda x: x.lstrip('$').rstrip('M'))
movies['us_grossMillions'] = pd.to_numeric(movies['us_grossMillions'], errors='coerce')
# movies.to_csv('top50movies.csv')
# Adding the movies to a mysql database
# Inistializing the connection to the mysql db
mydb = mysql.connector.connect(
host="localhost",
user="james",
password="be7crh",
database="webscraperdb"
)
mycursor = mydb.cursor()
# Give each movie a rank. Need this as the rank is the ID in the database.
movierank = []
rank_count = 0
for x in movies['movie']:
movierank.append(rank_count)
rank_count += 1
""" # catch all us_grossMillions that show nan
for x in movies['us_grossMillions']:
if math.isnan(x):
movies['us_grossMillions'][x] = float(-1) """
""" for x in movierank:
print("INSERT INTO top_50_movies (place, name, years, timeMin, imbd, metascore, votes, us_grossMillions) VALUES ({}, {}, {}, {}, {}, {}, {}, {})".format(x, movies['movie'][x], movies['year'][x], movies['timeMin'][x], movies['imbd'][x], movies['metascore'][x], movies['votes'][x], movies['us_grossMillions'][x]))
"""
for x in movierank:
if math.isnan(movies['us_grossMillions'][x]):
sql = "INSERT INTO top_50_movies (place, name, years, timeMin, imbd, metascore, votes, us_grossMillions) VALUES ({}, '{}', {}, {}, {}, {}, {}, {})".format(x, movies['movie'][x], movies['year'][x], movies['timeMin'][x], movies['imbd'][x], movies['metascore'][x], movies['votes'][x], -1)
else:
sql = "INSERT INTO top_50_movies (place, name, years, timeMin, imbd, metascore, votes, us_grossMillions) VALUES ({}, '{}', {}, {}, {}, {}, {}, {})".format(x, movies['movie'][x], movies['year'][x], movies['timeMin'][x], movies['imbd'][x], movies['metascore'][x], movies['votes'][x], movies['us_grossMillions'][x])
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record inserted.") |
# Listing_8-4.py
# Copyright Warren & Carter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# A loop using range()
for looper in range (1, 5):
print looper, "times 8 =", looper * 8
# 运行为times 8 = 8
# times 8 = 16
# times 8 = 24
# times 8 = 32
|
""" Write a function that computes the volume of a sphere given its radius.
Formula is 4/3 pi r^3 """
from math import pi
def vol(rad):
return (4/3)*pi*(rad**3)
print(vol(2))
""" Write a function that checks whether a number is in a given range (inclusive of high and low) """
def ran_check(num,low,high):
return num>=low and num<=high
def ran_check1(num,low,high):
return num in range(low,high+1)
print(ran_check(3,2,7))
print(ran_check1(3,2,7))
""" Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters. """
s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
def up_low(s):
print(f'Original string : {s}')
u,l = 0,0
for char in s:
if char.isupper():
u+=1
elif char.islower():
l+=1
else:
pass
return u,l
count = up_low(s)
print(f'No. of Lower case Characters : {count[0]}')
print(f'No. of Lower case Characters : {count[1]}')
def up_low1(s):
print(f'Original string : {s}')
dict = {'upper':0, 'lower':0}
for char in s:
if char.isupper():
dict['upper']+=1
elif char.islower():
dict['lower']+=1
else:
pass
return dict
count = up_low1(s)
print(f'No. of Lower case Characters : {count["upper"]}')
print(f'No. of Lower case Characters : {count["lower"]}')
""" Write a Python function that takes a list and returns a new list with unique elements of the first list. """
sample_list = [1,1,1,1,2,2,3,3,3,3,4,5]
def unique_list(lst):
unique = []
for item in lst:
if item not in unique:
unique.append(item)
return unique
print( unique_list(sample_list) )
def unique_list1(lst):
return list(set(lst))
print( unique_list1(sample_list) )
""" Write a Python function to multiply all the numbers in a list. """
sample_list = [1, 2, 3, -4]
def multiply(lst):
prod = 1
for num in sample_list:
prod *= num
return prod
print( multiply(sample_list) )
""" Write a Python function that checks whether a word or phrase is palindrome or not. """
def palindrome(s):
s = s.replace(' ','')
half_length = int(len(s)/2)
for i in range(0, half_length):
for j in range(len(s)-1, half_length+2, -1):
if s[i].lower() != s[j].lower():
return False
return True
print(palindrome('madam madam'))
def palindrome1(s):
s = s.replace(' ','')
return s==s[::-1]
print(palindrome1('madam madam'))
""" Write a Python function to check whether a string is pangram or not. (Assume the string passed in does not have any punctuation) """
import string
def ispangram(str1, alphabet = string.ascii_lowercase):
alphaset = set(alphabet)
str1 = str1.replace(' ','')
str1 = str1.lower()
str1 = set(str1)
return str1 == alphaset
print(ispangram('The quick brown fox jumps over the lazy dog'))
print(ispangram('This is random')) |
""" SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order
spy_game([1,2,4,0,0,7,5]) --> True
spy_game([1,0,2,4,0,5,7]) --> True
spy_game([1,7,2,0,4,5,0]) --> False """
from os import truncate
def spy_game(nums):
code = [0,0,7,'x']
for num in nums:
if num == code[0]:
code.pop(0)
return len(code) == 1
print(spy_game([1,2,4,0,0,7,5]))
print(spy_game([1,0,2,4,0,5,7]))
print(spy_game([1,7,2,0,4,5,0]))
""" COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number
count_primes(100) --> 25 """
import time
start_time = time.time()
def count_primes(num):
primes = [2] # already added 2 to prime list. Can chack only for odd prime numbers then
x = 3
if num < 2: # for the case of num = 0 or 1
return 0
while x <= num:
for y in primes: # test all odd factors up to x-1 TRICK
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
print(count_primes(100))
print("Process finished --- %s seconds ---" % (time.time() - start_time))
""" PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter¶
print_big('a')
out: *
* *
*****
* *
* *
HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns.
For purposes of this exercise, it's ok if your dictionary stops at "E". """
def print_big(letter):
patterns = {1:' * ', 2:' * * ', 3:'* *', 4:'*****', 5:'**** ', 6:' * ', 7:' * ', 8:'* * ', 9:'* '}
alphabet = {'A':[1,2,4,3,3], 'B':[5,3,5,3,5], 'C':[4,9,9,9,4], 'D':[5,3,3,3,5], 'E':[4,9,4,9,4]}
for pattern in alphabet[letter.upper()]:
print(patterns[pattern])
print_big('b') |
"""Create a dictionary and perform some modifications to it"""
birthmonths = {
'Radhila' : 'August',
'Akash' : 'March',
'Anjali' : 'Jan',
'Saahil' : 'April'
}
print('Anjali\'s birth month is:', birthmonths['Anjali'])
del birthmonths['Radhila']
print('The number of contents in the dictionary is:', (len(birthmonths)))
birthmonths['Preeti'] = 'Feb'
birthmonths['San'] = 'July'
for x,y in birthmonths.items():
print('Wish {} in {}'.format(x,y))
|
#!/Users/Radhika/Documents/Udemy/anaconda/bin/python
"""WAP that prints the numbers from 1 to 100, but
- for multiples of 3 print “Fizz” instead of the number and
- for the multiples of 5 print “Buzz” and
- for numbers which are multiples of both 3 and 5 print “FizzBuzz”"""
for x in range (1,100+1):
if ((x % 3) == 0) and ((x % 5) == 0):
print("FizzBuzz")
elif ((x % 5) == 0):
print("Buzz")
elif ((x % 3) == 0):
print("Fizz")
else:
print(x) |
def celsius_to_fahrenheit(celsius):
fahrenheit = celsius * 9/5 + 32
print("{}°C to {}°F".format(celsius, fahrenheit))
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
print("{}°F to {}°C".format(fahrenheit, celsius))
def menu():
print("Program do konwersji temperatury w różnych skalach. Jaką konwersje chcesz wykonać?")
print("1) Stopnie Celsjusza na Fahrenheita")
print("2) Stopnie Fahrenheita na Celsjusza")
while True:
try:
user_options = int(input("Wybierz: "))
except ValueError:
print("Musisz podać numer opcji!")
continue
if not 1 <= user_options <= 2:
print("Nie istnieje taka opcja.")
continue
else:
break
while True:
try:
value = float(input("Podaj wartość: "))
except ValueError:
print("Musisz podać liczbę!")
continue
break
if user_options == 1:
celsius_to_fahrenheit(value)
elif user_options == 2:
fahrenheit_to_celsius(value)
menu()
|
class MailChimpBaseException(Exception):
pass
class MailChimpError(MailChimpBaseException):
""" Represents an error returned from the MailChimp API. """
def __init__(self, message, code):
MailChimpBaseException.__init__(self, message)
self.code = code
class MailChimpGroupingNotFound(MailChimpBaseException):
""" A specified grouping name was not found in the mailchimp list. """
pass
class MailChimpEmailNotFound(MailChimpBaseException):
""" A specified email address was not found in the mailchimp list. """
pass
class MailChimpEmailUnsubscribed(MailChimpBaseException):
pass
|
import sys
import math
def draw(l1,l2,w1,w2):
for i in range(len(w2)):
o=[]
for j in range(len(w1)):
if i == l2:
o.append(w1[j])
elif j == l1:
o.append(w2[i])
else:
o.append(" ")
print(' '.join(o))
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
w1,w2 = input().split()
w1 = w1.upper()
w2 = w2.upper()
br = False
for i in range(len(w1)):
for j in range(len(w2)):
if w1[i] == w2[j]:
draw(i,j,w1,w2)
br = True
break
if br:
break
|
#!/usr/bin/python2
"""
Reads one or more hex encoded values from a file (split by newlines),
writes them to the specified subdir using the SHA1 of the contents as
the file name.
"""
import os
import sys
import hashlib
def main(args=None):
if args is None:
args = sys.argv
if len(args) != 3:
print("Usage: %s input_file target_dir" % (args[0]))
return 1
input_file = args[1]
target_dir = args[2]
for vec in open(input_file).readlines():
vec = vec.strip()
vec_bin = vec.decode('hex')
sha1 = hashlib.sha1()
sha1.update(vec_bin)
hash = sha1.hexdigest()
out_file = open(os.path.join(target_dir, hash), 'w')
out_file.write(vec_bin)
if __name__ == '__main__':
sys.exit(main())
|
# receive integer
number = int(input())
# write a function if the number is perf or not
def is_number_perfect(num=number):
is_perfect = False
if num < 0:
return "It's not so perfect."
summary_of_divisors = 0
for numbers in range(1, num):
if num % numbers == 0:
summary_of_divisors += numbers
if summary_of_divisors == num:
return "We have a perfect number!"
else:
return "It's not so perfect."
print(is_number_perfect())
|
distance_in_meters = int(input())
kilometres = distance_in_meters / 1000
print(f"{kilometres:.2f}")
|
data = input()
targeted_cities = {}
# {'Tortuga': [345000, 1250], 'Santo Domingo': [240000, 630], 'Havana': [410000, 1100]}
while not data == "Sail":
city, population, gold = data.split("||")
population = int(population)
gold = int(gold)
if city in targeted_cities:
targeted_cities[city][0] += population
targeted_cities[city][1] += gold
else:
targeted_cities[city] = [population, gold]
data = input()
event = input()
while not event == "End":
command = event.split("=>")
action = command[0]
if action == "Plunder":
town = command[1]
people = int(command[2])
gold = int(command[3])
print(f"{town} plundered! {gold} gold stolen, {people} citizens killed.")
targeted_cities[town][0] -= people
targeted_cities[town][1] -= gold
if targeted_cities[town][0] <= 0 or targeted_cities[town][1] <= 0:
print(f"{town} has been wiped off the map!")
targeted_cities.pop(town)
elif action == "Prosper":
town = command[1]
gold_added = int(command[2])
if gold_added < 0:
print("Gold added cannot be a negative number!")
event = input()
continue
targeted_cities[town][1] += gold_added
print(f"{gold_added} gold added to the city treasury. {town} now has {targeted_cities[town][1]} gold.")
event = input()
if len(targeted_cities) > 0:
print(f"Ahoy, Captain! There are {len(targeted_cities)} wealthy settlements to go to:")
targeted_cities = dict(sorted(targeted_cities.items(), key=lambda kvp: (- kvp[1][1], kvp[0])))
for town in targeted_cities:
people = targeted_cities[town][0]
gold = targeted_cities[town][1]
print(f"{town} -> Population: {people} citizens, Gold: {gold} kg")
else:
print("Ahoy, Captain! All targets have been plundered and destroyed!") |
student_academy = {}
n = int(input())
sum_of_grades = 0
best_students = {}
for _ in range(n):
student_name = input()
grade = float(input())
if student_name not in student_academy:
student_academy[student_name] = []
student_academy[student_name].append(grade)
for student, grades in student_academy.items():
for grade in grades:
sum_of_grades += grade
avg = sum_of_grades / len(grades)
if avg < 4.50:
del student
else:
best_students[student] = avg
sum_of_grades = 0
sorted_best_students = sorted(best_students.items(), key=lambda kvp: kvp[1], reverse=True)
for hui, grade in sorted_best_students:
print(f"{hui} -> {grade:.2f} ")
# 5
# John
# 5.5
# John
# 4.5
# Alice
# 6
# Alice
# 3
# George
# 5 |
percent_number = int(input())
def loading_bar(percent=percent_number):
list_of_percents = []
list_of_percent_in_str = ""
if percent < 100:
for number in range(1, percent + 1):
if number % 10 == 0:
list_of_percents.append("%")
for element in list_of_percents:
list_of_percent_in_str += element
while len(list_of_percent_in_str) < 10:
list_of_percent_in_str += "."
else:
for number in range(1, percent + 1):
if number % 10 == 0:
list_of_percents.append("%")
for element in list_of_percents:
list_of_percent_in_str += element
print(f"{percent}% Complete!")
print(f"[{list_of_percent_in_str}]")
if len(list_of_percents) < 10:
while len(list_of_percents) < 10:
list_of_percents.append(".")
print(f"{percent}% [{list_of_percent_in_str}]")
print("Still loading...")
return exit()
print(loading_bar()) |
first = int(input())
second = int(input())
third = int(input())
forth = int(input())
summary = first + second
summary1 = int(summary / third)
result = summary1 * forth
print(f"{result:.0f}") |
list_of_employee_happiness = list(map(lambda num: int(num), input().split(" ")))
# [1, 2, 3, 4, 2, 1]
happiness_improvement_factor = int(input())
multiplying_happiness = list(map(lambda num: num * happiness_improvement_factor, list_of_employee_happiness))
# [3, 6, 9, 12, 6, 3]
filtered = list(filter(lambda num: num >= (sum(multiplying_happiness) / len(multiplying_happiness)), multiplying_happiness))
# [9,12]
if len(filtered) >= len(multiplying_happiness) / 2:
print(f"Score: {len(filtered)}/{len(multiplying_happiness)}. Employees are happy!")
else:
print(f"Score: {len(filtered)}/{len(multiplying_happiness)}. Employees are not happy!") |
first_number = int(input())
second_number = int(input())
def factorial_division(num1=first_number, num2=second_number):
first_number_factorial = 1
second_number_factorial = 1
for number1 in range(1, num1 + 1):
first_number_factorial *= number1
for number2 in range(1, num2 + 1):
second_number_factorial *= number2
final_result = first_number_factorial / second_number_factorial
print(f"{final_result:.2f}")
return exit()
print(factorial_division()) |
n_in_str = input()
result = n_in_str.split(" ")
numbers_list = []
opposite_list = []
for index in result:
numbers_list.append(int(index))
for numbers in numbers_list:
opposite_list.append(numbers * (-1))
print(opposite_list) |
our_neighborhood = list(map(int, input().split("@")))
# 10, 10, 10, 2
command = input()
cupid_location = 0
house_count = 0
is_mission_successful = True
while not command == "Love!":
jump = command.split()[0]
length_of_jump = command.split()[1]
cupid_location += int(length_of_jump)
if cupid_location > len(our_neighborhood) - 1:
cupid_location = 0
our_neighborhood[cupid_location] -= 2
if our_neighborhood[cupid_location] == 0:
print(f"Place {cupid_location} has Valentine's day.")
if our_neighborhood[cupid_location] < 0:
our_neighborhood[cupid_location] = 0
print(f"Place {cupid_location} already had Valentine's day.")
command = input()
print(f"Cupid's last position was {cupid_location}.")
for house in our_neighborhood:
if house != 0:
house_count += 1
is_mission_successful = False
if is_mission_successful:
print("Mission was successful.")
else:
print(f"Cupid has failed {house_count} places.") |
test_data = [ [1], [1, 2], [3, 4] ]
def backtrack(data, data_index, result=[], current_res=[], target_len=3):
if len(current_res) == target_len:
result.append(','.join(map(str, current_res)))
return
if data_index >= len(data):
return
for i in range(len(data[data_index])):
current_res.append(data[data_index][i])
backtrack(data, data_index + 1, result, current_res, target_len)
current_res.pop()
return result
print(backtrack(test_data, 0)) |
#!/usr/bin/python
def trims(s):
while s[:1] == ' ':
s = s[1:]
while s[-1:] == ' ':
s = s[:-1]
return s
#
print(trims(' heloo '))
|
class Matrices:
def matrix(self, rows):
rows = int(rows)
# let's hope there won't be wrong column input
return [[float(j) for j in input().split()] for i in range(rows)]
def multiply_by_const(self):
rows, columns = input('Enter size of matrix: ').split()
print('Enter matrix:')
matr = self.matrix(rows)
multip = int(input('Enter constant: '))
prod = []
for row in range(int(rows)):
prod.append([matr[row][column] * multip for column in range(int(columns))])
print('The result is:\n')
for _ in prod:
print(*_)
def muliply_matr(self):
rows_1, columns_1 = input('Enter size of first matrix: ').split()
print('Enter first matrix:')
matr_1 = self.matrix(rows_1)
rows_2, columns_2 = input('Enter size of second matrix: ').split()
print('Enter second matrix:')
matr_2 = self.matrix(rows_2)
if int(columns_1) != int(rows_2):
print('The operation cannot be performed.\n')
return 0
prod = [[0 for j in range(int(columns_2))] for i in range(int(rows_1))]
# iterate through rows of matr_1
for i in range(len(matr_1)):
# iterate through columns of matr_2
for j in range(len(matr_2[0])):
# iterate through rows of matr_2
for k in range(len(matr_2)):
prod[i][j] += matr_1[i][k] * matr_2[k][j]
for _ in prod:
print(*_)
def add_matrices(self):
rows_1, columns_1 = input('Enter size of first matrix: ').split()
print('Enter first matrix:')
matr_1 = self.matrix(rows_1)
rows_2, columns_2 = input('Enter size of second matrix: ').split()
print('Enter second matrix:')
matr_2 = self.matrix(rows_2)
if rows_2 != rows_1 or columns_2 != columns_1:
print('The operation cannot be performed.\n')
return 0
summ = []
for row in range(int(rows_1)):
summ.append([matr_1[row][column] + matr_2[row][column] for column in range(int(columns_1))])
print('The result is:\n')
for _ in summ:
print(*_)
def transpose(self, choice):
rows, columns = input('Enter size of matrix: ').split()
print('Enter matrix:')
matr = self.matrix(rows)
if choice == '1':
matr = self.main_diagonal(matr)
elif choice == '2':
matr = self.side_diagonal(matr)
elif choice == '3':
matr = self.vertical_line(matr)
elif choice == '4':
matr = self.horizontal_line(matr)
else:
print('Sorry, no such operation')
return 0
print('The result is:')
for _ in matr:
print(*_)
# on main diagonal
# def transposeMatrix(m):
# return map(list, zip(*m))
def main_diagonal(self, matrix):
# result = []
# # iterate through rows
# for i in range(len(X)):
# # iterate through columns
# for j in range(len(X[0])):
# result[j][i] = X[i][j]
return [[matrix[column][row] for column in range(len(matrix[0]))] for row in range(len(matrix))]
def side_diagonal(self, matrix):
# reverse and then same as main diagonal and then again reverse
matrix = [[matrix[row][-column] for column in range(1, len(matrix[0]) + 1)] for row in range(len(matrix))]
matrix = [[matrix[column][row] for column in range(len(matrix[0]))] for row in range(len(matrix))]
return [[matrix[row][-column] for column in range(1, len(matrix[0]) + 1)] for row in range(len(matrix))]
def vertical_line(self, matrix):
return [[matrix[row][-column] for column in range(1, len(matrix[0]) + 1)] for row in range(len(matrix))]
def horizontal_line(self, matrix):
return [[matrix[-row][column] for column in range(len(matrix[0]))] for row in range(1, len(matrix) + 1)]
def determinant_recursive(self, matrix, total=0):
# Section 1: store indices in list for row referencing
indices = list(range(len(matrix)))
if len(matrix) == 1:
return matrix[0][0]
# Section 2: when at 2x2 submatrices recursive calls end
if len(matrix) == 2 and len(matrix[0]) == 2:
val = matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]
return val
# Section 3: define submatrix for focus column and
# call this function
for fc in indices: # A) for each focus column, ...
# find the submatrix ...
copy_matrix = matrix[:] # B) make a copy, and ...
copy_matrix = copy_matrix[1:] # ... C) remove the first row
height = len(copy_matrix) # D)
for i in range(height):
# E) for each remaining row of submatrix ...
# remove the focus column elements
copy_matrix[i] = copy_matrix[i][0:fc] + copy_matrix[i][fc + 1:]
sign = (-1) ** (fc % 2) # F)
# G) pass submatrix recursively
sub_det = self.determinant_recursive(copy_matrix)
# H) total all returns from recursion
total += sign * matrix[0][fc] * sub_det
return total
# and yeah, this doesn't cover 1 1 case
# not gonna lie, didn't quite get it, but i'll just save, so i could use it in future
# def determinant_fast(self, matrix):
# # Section 1: Establish n parameter and copy A
# n = len(matrix)
# copy = matrix[:]
#
# # Section 2: Row ops on A to get in upper triangle form
# for fd in range(n): # A) fd stands for focus diagonal
# for i in range(fd + 1, n): # B) only use rows below fd row
# if copy[fd][fd] == 0: # C) if diagonal is zero ...
# copy[fd][fd] == 1.0e-18 # change to ~zero
# # D) cr stands for "current row"
# crScaler = copy[i][fd] / copy[fd][fd]
# # E) cr - crScaler * fdRow, one element at a time
# for j in range(n):
# copy[i][j] = copy[i][j] - crScaler * copy[fd][j]
#
# # Section 3: Once copy is in upper triangle form ...
# product = 1.0
# for i in range(n):
# # ... product of diagonals is determinant
# product *= copy[i][i]
#
# return product
# i geuss cheating, but, whatever, it would take too much time to invent the bike, when i could just analyse it
def getMatrixMinor(self, m, i, j):
return [row[:j] + row[j + 1:] for row in (m[:i] + m[i + 1:])]
def getMatrixDeternminant(self, m):
# base case for 2x2 matrix
if len(m) == 2:
return m[0][0] * m[1][1] - m[0][1] * m[1][0]
determinant = 0
for c in range(len(m)):
determinant += ((-1) ** c) * m[0][c] * self.getMatrixDeternminant(self.getMatrixMinor(m, 0, c))
return determinant
def getMatrixInverse(self, m):
determinant = self.getMatrixDeternminant(m)
# special case for 2x2 matrix:
if len(m) == 2:
return [[m[1][1] / determinant, -1 * m[0][1] / determinant],
[-1 * m[1][0] / determinant, m[0][0] / determinant]]
# find matrix of cofactors
cofactors = []
for r in range(len(m)):
cofactorRow = []
for c in range(len(m)):
minor = self.getMatrixMinor(m, r, c)
cofactorRow.append(((-1) ** (r + c)) * self.getMatrixDeternminant(minor))
cofactors.append(cofactorRow)
cofactors = self.main_diagonal(cofactors)
for r in range(len(cofactors)):
for c in range(len(cofactors)):
cofactors[r][c] = cofactors[r][c] / determinant
for i in cofactors:
print(*i)
def menu(self):
while True:
choice = input("""1. Add matrices
2. Multiply matrix by a constant
3. Multiply matrices
4. Transpose matrix
5. Calculate a determinant
6. Inverse matrix
0. Exit
Your choice: """)
if choice == '1':
self.add_matrices()
elif choice == '2':
self.multiply_by_const()
elif choice == '3':
self.muliply_matr()
elif choice == '4':
choice = input("""\n1. Main diagonal
2. Side diagonal
3. Vertical line
4. Horizontal line
Your choice: """)
self.transpose(choice)
elif choice == '5':
rows, columns = input('Enter size of matrix: ').split()
print('Enter matrix:')
matr = self.matrix(rows)
print('The result is:', self.determinant_recursive(matr), sep='\n')
elif choice == '6':
rows, columns = input('Enter size of matrix: ').split()
print('Enter matrix:')
matr = self.matrix(rows)
self.getMatrixInverse(matr)
elif choice == '0':
break
else:
print('Sorry, no such choice\n')
Matrices().menu() |
"""
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Note:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S doesn't contain \ or "
"""
# 2020-9-17
class Solution:
def reverseOnlyLetters(self, S: str) -> str:
tmpSeq = [0 for _ in range(len(S))]
characterRecord = []
for i, c in enumerate(S):
if c.isalpha():
characterRecord.append(c)
else:
tmpSeq[i] = c
# print(characterRecord)
for i, c in enumerate(tmpSeq):
if c == 0:
tmpSeq[i] = characterRecord.pop()
return "".join(tmpSeq)
def reverseOnlyLetters2(self, S: str) -> str:
stack = []
for i, c in enumerate(S):
if c.isalpha():
stack.append(c)
ret = []
for i, c in enumerate(S):
if c.isalpha():
ret.append(stack.pop())
else:
ret.append(c)
return "".join(ret)
# test
S = "Test1ng-Leet=code-Q!"
test = Solution()
res = test.reverseOnlyLetters2(S)
print(res == "Qedo1ct-eeLg=ntse-T!") |
# coding:utf-8
"""
685. Redundant Connection II
Hard
769
210
Add to List
Share
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.
The given input is a directed graph that started as a rooted tree with N nodes (with distinct values 1, 2, ..., N), with one additional directed edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] that represents a directed edge connecting nodes u and v, where u is a parent of child v.
Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.
Example 1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given directed graph will be like this:
1
/ \
v v
2-->3
Example 2:
Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]
Output: [4,1]
Explanation: The given directed graph will be like this:
5 <- 1 -> 2
^ |
| v
4 <- 3
Note:
The size of the input 2D-array will be between 3 and 1000.
Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.
"""
# 2020-7-28
class Solution(object):
def findRedundantDirectedConnection(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
canA = [-1, -1]
canB = [-1, -1]
fa = [0 for i in range(len(edges)+1)]
for edge in edges:
if fa[edge[1]] == 0:
fa[edge[1]] = edge[0]
else:
canA[0] = fa[edge[1]]
canA[1] = edge[1]
canB[0] = fa[edge[0]]
canB[1] = edge[1]
edge[1] = 0
# print(canA, canB)
fa = [i for i in range(len(edges)+1)]
for edge in edges:
if edge[1] == 0: continue
child, father = edge[1], edge[0]
if self.find(fa, father) == child:
if canA[0] == -1: return edge
return canA
fa[child] = father
return canB
def find(self, fa, x):
while x != fa[x]:
fa[x] = fa[fa[x]]
x = fa[x]
return x
edgesCollections = [
[[1,2], [2,3], [3,4], [4,1], [1,5]],
[[1,2], [1,3], [2,3]]
]
test = Solution()
for edges in edgesCollections:
ret = test.findRedundantDirectedConnection(edges)
print(ret) |
# Quiz 1 - Plot J(theta_0, theta_1)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
# the error function
def J(a, b):
# test data
data = np.array([[0.5, 0.9], [0.3, 0.7], [1.1, 2.3], [2.0, 4.3], [3.5, 6.8], [4.1, 8], [0, 0.1], [5.8, 11]])
temp = 0
for i in data:
temp += (a + b * i[0] - i[1]) ** 2
return temp / (2 * len(data))
def main():
# make a 3-D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#create range of x, y, and z
theta_0 = np.linspace(-3, 5, 30)
theta_1 = np.linspace(0, 3, 30)
X, Y = np.meshgrid(theta_0, theta_1)
Z = J(X, Y)
# plot and label the graph
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm)
ax.set_xlabel('theta_0')
ax.set_ylabel('theta_1')
ax.set_zlabel('J')
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 10:53:15 2019
@author: andrewpauling
"""
def snowfall(idx):
"""
snowfall from maykut and untersteiner 1971
"""
snow = 0
if idx <= 118 or idx >= 301:
snow = 2.79e-4
elif idx >= 119 and idx <= 149:
snow = 1.61e-3
elif idx > 229:
snow = 4.16e-3
else:
snow = 0.0
return snow
|
import threading
lock=threading.Lock() #创建一个线程锁(互斥锁)
num=100
#买票
def sale(name):
lock.acquire() #设置锁
global num
if num>0:
num=num-1
print(name,"卖出一张票,还剩",num,"张票")
lock.release() #释放锁
#程序执行时,程序本身就是一个线程,叫主线程
#手动创建的线程,叫子线程
#主线程的执行中,不会等待子线程执行完毕,就会直接执行后面的代码
#售票窗口(2个线程)
while 1==1:
if num>0:
ta=threading.Thread(target=sale,args=("A窗口",))
tb=threading.Thread(target=sale,args=("B窗口",))
ta.start()
tb.start()
ta.join() #等待子线程执行完毕之后再执行主线程后面的内容
tb.join() #等待子线程执行完毕之后再执行主线程后面的内容
else:
break
print("票已经卖完") |
# -------------------------Python 运算符-------------------------------
# 什么是运算符?
# 本章节主要说明Python的运算符。举个简单的例子 4 +5 = 9 。 例子中,4 和 5 被称为操作数,"+" 称为运算符。
# Python语言支持以下类型的运算符:
# 算术运算符
# 比较(关系)运算符
# 赋值运算符
# 逻辑运算符
# 位运算符
# 成员运算符
# 身份运算符
# 运算符优先级
# ------Python算术运算符------
# 以下假设变量: a=10,b=20:
# + 加 - 两个对象相加 a + b 输出结果 30
# - 减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -10
# * 乘 - 两个数相乘或是返回一个被重复若干次的字符串 a * b 输出结果 200
# / 除 - x除以y b / a 输出结果 2
# % 取模 - 返回除法的余数 b % a 输出结果 0
# ** 幂 - 返回x的y次幂 a**b 为10的20次方, 输出结果 100000000000000000000
# // 取整除 - 返回商的整数部分(向下取整) >>> 9//2 4 >>> -9//2 -5
# a = 21
# b = 10
# c = 0
# c = a + b
# print ("1 - 21 + 10 的值为:", c)
# c = a - b
# print ("2 - 21 - 10 的值为:", c )
# c = a * b
# print ("3 - 21 * 10 的值为:", c )
# c = a / b
# print ("4 - 21 / 10 的值为:", c)
# c = a % b
# print ("5 - 21 % 10 的值为:", c)
# # 修改变量 a 、b 、c
# a = 2
# b = 3
# c = a**b
# print ("6 - 2**3 的值为:", c)
# a = 10
# b = 5
# c = a//b
# print ("7 - 10//5 的值为:", c)
# -------Python比较运算符------
# 以下假设变量a为10,变量b为20:
# == 等于 - 比较对象是否相等 (a == b) 返回 False。
# != 不等于 - 比较两个对象是否不相等 (a != b) 返回 true.
# <> 不等于 - 比较两个对象是否不相等。python3 已废弃。 (a <> b) 返回 true。这个运算符类似 != 。
# > 大于 - 返回x是否大于y (a > b) 返回 False。
# < 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。 (a < b) 返回 true。
# >= 大于等于 - 返回x是否大于等于y。 (a >= b) 返回 False。
# <= 小于等于 - 返回x是否小于等于y。 (a <= b) 返回 true。
# a = 21
# b = 10
# c = 0
# if a == b :
# print ("1 - a 等于 b")
# else:
# print ("1 - a 不等于 b")
# if a != b :
# print ("2 - a 不等于 b")
# else:
# print ("2 - a 等于 b")
# if a < b :
# print ("4 - a 小于 b")
# else:
# print ("4 - a 大于等于 b")
# if a > b :
# print ("5 - a 大于 b")
# else:
# print ("5 - a 小于等于 b")
# # 修改变量 a 和 b 的值
# a = 5
# b = 20
# if a <= b :
# print ("6 - a 小于等于 b")
# else:
# print ("6 - a 大于 b")
# if b >= a :
# print ("7 - b 大于等于 a")
# else:
# print ("7 - b 小于 a")
# ------Python赋值运算符------
# = 简单的赋值运算符 c = a + b 将 a + b 的运算结果赋值为 c
# += 加法赋值运算符 c += a 等效于 c = c + a
# -= 减法赋值运算符 c -= a 等效于 c = c - a
# *= 乘法赋值运算符 c *= a 等效于 c = c * a
# /= 除法赋值运算符 c /= a 等效于 c = c / a
# %= 取模赋值运算符 c %= a 等效于 c = c % a
# **= 幂赋值运算符 c **= a 等效于 c = c ** a
# //= 取整除赋值运算符 c //= a 等效于 c = c // a
# a = 21
# b = 10
# c = 0
# c = a + b
# print ("1 - a + b 的值为:", c)
# c += a
# print ("2 - c += a 的值为:", c)
# c *= a
# print ("3 - c *= a 的值为:", c)
# c /= a
# print ("4 - c /= a 的值为:", c)
# c = 2
# c %= a
# print ("5 - c %= a 的值为:", c)
# c **= a
# print ("6 - c **= a 的值为:", c)
# c //= a
# print ("7 - c //= a 的值为:", c)
# ------Python位运算符------
# 下表中变量 a 为 60,b 为 13,二进制格式如下:
# a = 0011 1100
# b = 0000 1101
# -----------------
# a&b = 0000 1100
# a|b = 0011 1101
# a^b = 0011 0001
# ~a = 1100 0011
# & 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 (a & b) 输出结果 12 ,二进制解释: 0000 1100
# | 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。 (a | b) 输出结果 61 ,二进制解释: 0011 1101
# ^ 按位异或运算符:当两对应的二进位相异时,结果为1 (a ^ b) 输出结果 49 ,二进制解释: 0011 0001
# ~ 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。~x 类似于 -x-1 (~a ) 输出结果 -61 ,二进制解释: 1100 0011,在一个有符号二进制数的补码形式。
# << 左移动运算符:运算数的各二进位全部左移若干位,由 << 右边的数字指定了移动的位数,高位丢弃,低位补0。 a << 2 输出结果 240 ,二进制解释: 1111 0000
# >> 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,>> 右边的数字指定了移动的位数 a >> 2 输出结果 15 ,二进制解释: 0000 1111
# a = 60 # 60 = 0011 1100
# b = 13 # 13 = 0000 1101
# c = 0
# c = a & b; # 12 = 0000 1100
# print ("1 - a & b 的值为:", c)
# c = a | b; # 61 = 0011 1101
# print ("2 - a | b 的值为:", c)
# c = a ^ b; # 49 = 0011 0001
# print ("3 - a ^ b 的值为:", c)
# c = ~a; # -61 = 1100 0011
# print ("4 - ~a 的值为:", c)
# c = a << 2; # 240 = 1111 0000
# print ("5 - a << 2 的值为:", c)
# c = a >> 2; # 15 = 0000 1111
# print ("6 - a >> 2 的值为:", c)
# ------Python逻辑运算符------
# Python语言支持逻辑运算符,以下假设变量 a 为 10, b为 20
# and x and y 布尔"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。 (a and b) 返回 20。
# or x or y 布尔"或" - 如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。 (a or b) 返回 10。
# not not x 布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 not(a and b) 返回 False
# a = 10
# b = 20
# if a and b :
# print ("1 - 变量 a 和 b 都为 true")
# else:
# print ("1 - 变量 a 和 b 有一个不为 true")
# if a or b :
# print ("2 - 变量 a 和 b 都为 true,或其中一个变量为 true")
# else:
# print ("2 - 变量 a 和 b 都不为 true")
# # 修改变量 a 的值
# a = 0
# if a and b :
# print ("3 - 变量 a 和 b 都为 true")
# else:
# print ("3 - 变量 a 和 b 有一个不为 true")
# if a or b :
# print ("4 - 变量 a 和 b 都为 true,或其中一个变量为 true")
# else:
# print ("4 - 变量 a 和 b 都不为 true")
# if not( a and b ):
# print ("5 - 变量 a 和 b 都为 false,或其中一个变量为 false")
# else:
# print ("5 - 变量 a 和 b 都为 true")
# ------Python成员运算符------
# 除了以上的一些运算符之外,Python还支持成员运算符,测试实例中包含了一系列的成员,包括字符串,列表或元组。
# in 如果在指定的序列中找到值返回 True,否则返回 False。 x 在 y 序列中 , 如果 x 在 y 序列中返回 True。
# not in 如果在指定的序列中没有找到值返回 True,否则返回 False。 x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。
# a = 10
# b = 20
# list = [1, 2, 3, 4, 5 ];
# if ( a in list ):
# print ("1 - 变量 a 在给定的列表中 list 中")
# else:
# print ("1 - 变量 a 不在给定的列表中 list 中")
# if ( b not in list ):
# print ("2 - 变量 b 不在给定的列表中 list 中")
# else:
# print ("2 - 变量 b 在给定的列表中 list 中")
# # 修改变量 a 的值
# c = 2
# if ( c in list ):
# print ("3 - 变量 c 在给定的列表中 list 中")
# else:
# print ("3 - 变量 c 不在给定的列表中 list 中")
# ------Python身份运算符------
# 身份运算符用于比较两个对象的存储单元
# is is 是判断两个标识符是不是引用自一个对象 x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False
# is not is not 是判断两个标识符是不是引用自不同对象 x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False。
# a = 20
# b = 20
# if ( a is b ):
# print ("1 - a 和 b 有相同的标识")
# else:
# print ("1 - a 和 b 没有相同的标识")
# if ( a is not b ):
# print ("2 - a 和 b 没有相同的标识")
# else:
# print ("2 - a 和 b 有相同的标识")
# # 修改变量 b 的值
# c = 30
# if ( a is c ):
# print ("3 - a 和 c 有相同的标识")
# else:
# print ("3 - a 和 c 没有相同的标识")
# if ( a is not c ):
# print ("4 - a 和 c 没有相同的标识")
# else:
# print ("4 - a 和 c 有相同的标识")
# ------Python运算符优先级------
# ** 指数 (最高优先级)
# ~ + - 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
# * / % // 乘,除,取模和取整除
# + - 加法减法
# >> << 右移,左移运算符
# & 位 'AND'
# ^ | 位运算符
# <= < > >= 比较运算符
# <> == != 等于运算符
# = %= /= //= -= += *= **= 赋值运算符
# is is not 身份运算符
# in not in 成员运算符
# not and or 逻辑运算符
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("(a + b) * c / d 运算结果为:", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("((a + b) * c) / d 运算结果为:", e)
e = (a + b) * (c / d); # (30) * (15/5)
print ("(a + b) * (c / d) 运算结果为:", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("a + (b * c) / d 运算结果为:", e)
|
"""Contains a tool for converting decimal numbers to binary strings"""
def dec2bin(x, num_dig, wrap_in_quotes=True):
s = bin(x)
s = s.replace("0b", "")
assert(num_dig >= len(s))
if len(s) < num_dig:
num_zeros = num_dig - len(s)
s = "0" * num_zeros + s
if wrap_in_quotes:
return '"' + s + '"'
return s
def test_dec2bin():
x = dec2bin(8, 12, False)
assert(x == "000000001000")
x = dec2bin(13, 16, False)
assert(x == "0000000000001101")
x = dec2bin(255, 24, False)
assert(x == "000000000000000011111111")
x = dec2bin(255, 24, True)
assert(x == '"000000000000000011111111"')
|
'''
Created on 11.01.2018
@author: tfuss001
'''
def dreh(lst):
if len(lst) == 1:
return lst
else:
print(str(lst[1:]) + "+" + str(lst[0]))
return dreh(lst[1:]) +[lst[0]]
lst=[1,2,3,4,5]
print(dreh(lst))
|
# Copyright (c) Vera Galstyan Jan 2018
numbers = list(range(1,10))
for number in numbers:
if number == 1:
print("1st")
elif number == 2:
print("2nd")
elif number == 3:
print("3rd")
else:
print(str(number) + "th") |
"""
Axis class
==========
Axis is a named ordered collection of values.
For these doctests to run we are going to import numcube.Axis and numpy.
>>> from numcube import Axis
>>> import numpy as np
Creation
--------
To create an Axis object, you have to supply it with name and values. Name must be a string,
values must be convertible to one-dimensional numpy array. The values should be of the same type,
otherwise they are converted to the most flexible type.
- initialized by explicit values:
(note: dtype=object is not necessary, it is here to pass the doctests below in both Python 2 and Python 3)
>>> months = Axis("month", ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"])
>>> months
Axis('month', ['jan' 'feb' 'mar' 'apr' 'may' 'jun' 'jul' 'aug' 'sep' 'oct' 'nov' 'dec'])
- initialized from a range:
>>> years = Axis("year", range(2010, 2020))
>>> years
Axis('year', [2010 2011 2012 2013 2014 2015 2016 2017 2018 2019])
Properties
----------
- 'name' returns a string
>>> months.name
'month'
- 'values' returns a numpy array
note: this is commented out since this test is not portable between Python 2 and Python 3
#>>> months.values # doctest: +NORMALIZE_WHITESPACE
array(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
'oct', 'nov', 'dec'])
- str(years) converts the axis to its string representation
>>> str(years)
"Axis('year', [2010 2011 2012 2013 2014 2015 2016 2017 2018 2019])"
- len(axis) returns the number of values
>>> len(months)
12
Slicing, indexing, filtering
----------------------------
The returned object is also Axis with the same name and subset of values.
>>> months[0:4]
Axis('month', ['jan' 'feb' 'mar' 'apr'])
>>> months[-1]
Axis('month', ['dec'])
>>> months[::2]
Axis('month', ['jan' 'mar' 'may' 'jul' 'sep' 'nov'])
When accessing values by their indices, you have to provide double square brackets!
>>> months[[0, 2, 4]]
Axis('month', ['jan' 'mar' 'may'])
The values can be repeated using repeated indices.
>>> months[[1, 2, 1, 2]]
Axis('month', ['feb' 'mar' 'feb' 'mar'])
To filter axis by index, you can also use method take(), which is similar to numpy.take().
>>> months.take([0, 2, 4])
Axis('month', ['jan' 'mar' 'may'])
You can filter the axis by using logical values in a numpy array.
>>> years[np.array([True, False, True, False, True, False, True, False, True, False])]
Axis('year', [2010 2012 2014 2016 2018])
The previous example was not very useful by itself. But numpy array of logical values is
the result of logical expression with axis values. Now this is much more useful.
>>> years[years.values % 2 == 0] # even years
Axis('year', [2010 2012 2014 2016 2018])
>>> years[(years.values >= 2013) & (years.values <= 2016)] # note the single '&', do not confuse with C/C++ '&&' style
Axis('year', [2013 2014 2015 2016])
To filter axis by logical values, you can also use method compress(), which is similar to numpy.compress().
In this case you do not need to convert logical values to numpy array.
>>> years.compress([True, False, True, False, True, False, True, False, True, False])
Axis('year', [2010 2012 2014 2016 2018])
Renaming
--------
We can rename the axis. Renaming returns a new axis (do not forget to assign it to a new variable!),
the original axis remains unchanged.
>>> m = months.rename("M")
>>> m
Axis('M', ['jan' 'feb' 'mar' 'apr' 'may' 'jun' 'jul' 'aug' 'sep' 'oct' 'nov' 'dec'])
This is the original axis, still with the old name:
>>> months
Axis('month', ['jan' 'feb' 'mar' 'apr' 'may' 'jun' 'jul' 'aug' 'sep' 'oct' 'nov' 'dec'])
Sorting
-------
Sorting is one of the places where numcube API and numpy API differs. Numcube sorting returns a copy
of the axis which is analogy to numpy.sort(array) function. On the other hand array.sort() sorts the
array in-place. The reason is that numcube aims to support immutability as much as possible.
>>> persons = Axis("person", ["Steve", "John", "Alex", "Peter", "Linda"])
>>> sorted_persons = persons.sort()
>>> sorted_persons
Axis('person', ['Alex' 'John' 'Linda' 'Peter' 'Steve'])
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
"""
|
#!/usr/bin/env python3
"""deep NN performing binary classififcation"""
import numpy as np
class DeepNeuralNetwork:
"""Deep Neural Network Class"""
def __init__(self, nx, layers):
"""nx is number of input values"""
if type(nx) is not (int):
raise TypeError("nx must be an integer")
if nx < 1:
raise ValueError("nx must be a positive integer")
"""layers list reping num nodes in each layer"""
if type(layers) is not (list) or len(layers) <= 0:
raise TypeError("layers must be a list of positive integers")
self.L = len(layers)
self.nx = nx
self.cache = {}
self.weights = {}
for i_lyr in range(self.L):
mWts = "W" + str(i_lyr + 1)
mB = "b" + str(i_lyr + 1)
if type(layers[i_lyr]) is not (int) or layers[i_lyr] < 1:
raise TypeError("layers must be a list of positive integers")
self.weights[mB] = np.zeros((layers[i_lyr], 1))
if i_lyr == 0:
self.weights[mWts] = (np.random.randn(layers[i_lyr], nx)
* np.sqrt(2 / nx))
else:
self.weights[mWts] = (np.random.randn(layers[i_lyr],
layers[i_lyr - 1])
* np.sqrt(2 / layers[i_lyr - 1]))
|
#!/usr/bin/env python3
"""function calculates the integral of a polynomial"""
def poly_integral(poly, C=0):
"""function calculates the integral of a polynomial"""
coIndex = 0
dePoly = []
try:
if len(poly) < 1:
return None
except TypeError:
return None
# code checking if C is int
if not (type(C) is int or type(C) is float):
return None
coIndex = 0
for p, coef in enumerate(poly):
if not (type(coef) is int or type(coef) is float):
return None
if coef != 0:
coIndex = p + 1
# print("{}, {}".format(coef, coIndex))
# change code to C + integral of poly
# for pow, coef in enumerate(poly):
# i_pow = coef_whole(coef / (pow + 1))
# dePoly = ([C] + [i_pow])
dePoly = [C] + [coef_whole(coef / (exp + 1))
for exp, coef in enumerate(poly)]
# print("{}".format(dePoly))
return dePoly[:coIndex + 1]
def coef_whole(num):
"""If a coefficient is a whole number represent as an int"""
if num.is_integer():
return int(num)
else:
return num
|
#!/usr/bin/env python3
"""function adds two arrays, element-wise"""
def add_arrays(arr1, arr2):
"""add arrays if same size"""
if len(arr1) != len(arr2):
return (None)
newList = []
for i in range(len(arr1)):
newList.append(arr1[i] + arr2[i])
return (newList)
|
#!/usr/bin/env python3
"""
calculates the specificity each class in a confusion matrix
"""
import numpy as np
def specificity(confusion):
"""
confusion is a confusion numpy.ndarray of shape (classes, classes)
classes is the number of classes
"""
for m in range(confusion.shape[0]):
negfp = np.delete(confusion, m, 1)
negfn = np.delete((negfp), m, 0)
tNFP = np.delete(confusion, m, 0).sum()
return negfn / tNFP
|
#!/usr/bin/env python3
"""
Initialize cluster centroids for K-means
"""
import numpy as np
def initialize(X, k):
"""
Initialize cluster centroid for K-means
:param X: np.ndarray, shape(n, d)
contains data set used for K-means
:param k: pos integer containing the num clusters
:return: np.ndarray, of shape (k, d)
"""
if type(X) != np.ndarray or len(X.shape) != 2:
return None
if type(k) != int or k <= 0 or k >= X.shape[0]:
return None
n, d = X.shape
min_X = X.min(axis=0)
max_X = X.max(axis=0)
return np.random.uniform(min_X, max_X, size=(k, d))
|
#!/usr/bin/env python3
"""
Function determines if a markov chain is absorbing
"""
import numpy as np
def absorbing(P):
"""
determines if a markov chain is an absorbing chain
:param P: np.ndarray, (n,n), transition matrix
n: num of states in the markov chain
:return: True or False
"""
if not isinstance(P, np.ndarray) or (len(P.shape) != 2):
return False
if P.shape[0] != P.shape[1] or P.shape[0] < 1:
return False
if ((np.where(P < 0, 1, 0).any()
or not np.where(np.isclose(P.sum(axis=1), 1), 1, 0).any())):
# long if statement use double parens
return False
if (np.all(np.diag(P) == 1)):
# absorbing proven if matrix diagnol all = 1
return True
if not (np.any(np.diagonal(P) == 1)):
# if the diagnol returned is not all 1s return False
return False
for i in (range(P.shape[0])):3
# account for the transitioning from state i to state j
for j in (range(P.shape[1])):
# verify above NUll does not apply
if ((i == j) and (i + 1 < len(P))):
# prob of transitionin from i to j and j to i
if (P[i][j + 1] == 0 and P[i + j][j] == 0):
return False
return True
|
#!/usr/bin/env python3
"""
function that calculates cost of NN using L2
"""
import numpy as np
def l2_reg_cost(cost, lambtha, weights, L, m):
"""
cost: cost of the network without L2 regularization
lambtha: regularization parameter
weights: dictionary of weights and biases (numpy.ndarrays) of NN
L: num layers in NN
m: num data points used
"""
weights_sum = 0
for key, num in weights.items(): # weights id a key value dict
if (key[0] == "W"):
num = weights[key]
weights_sum += np.linalg.norm(num)
L2_Cost = (cost + (lambtha / (2 * m)) * weights_sum)
return(L2_Cost)
|
#!/usr/bin/env python3
"""
calculates the marginal probability of obtaining the data
"""
import numpy as np
from scipy import math, special
def intersection(x, n, P, Pr):
"""
calculates the intersection of obtaining this data
with the various hypothetical probabilities
"""
factor = math.factorial
factNX = (factor(n) / (factor(x) * factor(n - x)))
likelihood = factNX * (P**x) * ((1 - P)**(n - x))
return likelihood * Pr
def marginal(x, n, P, Pr):
"""
calculates the marginal probability of obtaining the data
"""
return np.sum(intersection(x, n, P, Pr))
def posterior(x, n, P, Pr):
"""
calculates the posterior probability for the various
hypothetical probabilities of developing severe side
effects given the data
"""
return intersection(x, n, P, Pr) / marginal(x, n, P, Pr)
def posterior(x, n, p1, p2):
"""
calculates the posterior probability that the probability
of developing severe side effects falls within a specific
range given the data:
:param x: num of patients with sever side effects
:param n: tot num patients observed
:param p1: lower bound range
:param p2: upper bound range
:return: posterior probability that p is within the range
[p1, p2] given x and n
"""
if not isinstance(n, int) or n < 1:
raise ValueError("n must be a positive integer")
if not isinstance(x, int) or x < 0:
m = "x must be an integer that is greater than or equal to 0"
raise ValueError(m)
if x > n:
raise ValueError("x cannot be greater than n")
if not isinstance(p1, float) or p1 < 0 or p1 > 1:
raise ValueError("p1 must be a float in the range [0, 1]")
if not isinstance(p2, float) or p2 < 0 or p2 > 1:
raise ValueError("p2 must be a float in the range [0, 1]")
if p2 <= p1:
raise ValueError("p2 must be greater than p1")
inter = intersection(x, n, p1, p2)
return ((special.expn(inter, p2)) / (special.expn(inter, p1)))
|
#!/usr/bin/env python3
"""function normalizes(standardizes) a matrix"""
import numpy as np
def normalize(X, m, s):
"""
X is numpy.ndarray of shape (d, nx) to normalize
m is numpy.ndarray of shape (nx,) contains features of X
s is numpy.ndarray of shape (nx,) contains Std Dev of X
d id the num of data points
nx is num of features
"""
normX = (X - m) / s
return (normX)
|
#!/usr/bin/env python3
"""
Function that calculates the definiteness of a matrix
"""
import numpy as np
def definiteness(matrix):
"""
calculates definiteness of a matrix
:param matrix: list of lists
:return: the string: Positive definite,
Positive semi-definite, Negative semi-definite,
Negative definite, or Indefinite
"""
# check if np.ndarray
if not isinstance(matrix, np.ndarray):
raise TypeError("matrix must be a numpy.ndarray")
# check if symmetrical
if not np.all(np.transpose(matrix) == matrix):
return None
if len(matrix.shape) != 2:
return None
if (matrix.shape[0] != matrix.shape[1]):
return None
definite = (np.linalg.eigvals(matrix))
if all(definite == 0):
return None
if all(definite > 0):
return "Positive definite"
if all(definite < 0):
return "Negative definite"
if any(definite > 0) and any(definite == 0):
return "Positive semi-definite"
if any(definite < 0) and any(definite == 0):
return "Negative semi-definite"
elif not (any(definite < 0)
and any(definite == 0) and any(definite > 0)):
return "Indefinite"
else:
return "None"
def transpose_matrix(matrix):
"""
transpose given matrix
:param matrix: list of lists
:return: transposed matrix
"""
return [[row[m] for row in matrix] for m in range(len(matrix[0]))]
|
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
student_grades = np.random.normal(68, 15, 50)
"""data format"""
bin_edges = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
plt.hist(student_grades, align='mid', bins=bin_edges, edgecolor='black')
"""graph design"""
plt.ylabel('Number of Students')
plt.xlabel('Grades')
plt.title('Project A')
plt.xlim(0, 100)
plt.xticks(bin_edges)
plt.ylim(0, 30)
plt.show()
|
#!/usr/bin/env python3
"""Class represents a binomial distribution"""
class Binomial:
"""Class represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""Binomial distribution"""
if data is None:
if n <= 0:
raise ValueError("n must be a positive value")
if p <= 0 or p >= 1:
raise ValueError("p must be greater than 0 and less than 1")
self.n = int(n)
self.p = float(p)
else:
if type(data) is not list:
raise TypeError("data must be a list")
if len(data) < 2:
raise ValueError("data must contain multiple values")
mean = sum(data) / len(data)
vari = sum([(m - mean) ** 2 for m in data]) / len(data)
self.p = -1 * (vari / mean - 1)
n = mean / self.p
self.n = round(n)
self.p *= n / self.n
def pmf(self, k):
"""Calculates value of PMF for given number k"""
if type(k) is not int:
k = int(k)
if k > self.n or k < 0:
return 0
return (m_factorial(self.n) / m_factorial(k) / m_factorial(self.n - k)
* self.p ** k * (1 - self.p) ** (self.n - k))
def cdf(self, k):
"""Calculates value CDF for given number k """
c_prob = 0
if type(k) is not int:
k = int(k)
if k > self.n or k < 0:
return 0
for m in range(0, k + 1):
c_prob += self.pmf(m)
return c_prob
def m_factorial(m):
"""factorial of m"""
if m == 1 or m == 0:
return 1
else:
return m * m_factorial(m-1)
|
#!/usr/bin/env python3
"""Class represents a normal distribution"""
class Normal:
"""Class represents a normal distribution"""
def __init__(self, data=None, mean=0., stddev=1.):
"""Normal Distribution"""
if data is None:
if stddev <= 0:
raise ValueError("stddev must be a positive value")
self.mean = float(mean)
self.stddev = float(stddev)
else:
if type(data) is not list:
raise TypeError("data must be a list")
if len(data) < 2:
raise ValueError("data must contain multiple values")
self.mean = float(sum(data) / len(data))
self.stddev = float((sum([(x - self.mean) ** 2 for x in data])
/ (len(data))) ** .5)
def z_score(self, x):
"""Calculates z-score of x-value"""
return (x - self.mean) / self.stddev
def x_value(self, z):
"""Calculates x-value of z-score"""
return z * self.stddev + self.mean
def pdf(self, x):
"""Calculates value of pdf at x"""
return (pow(2.7182818285, ((x - self.mean) ** 2 /
(-2 * self.stddev ** 2))) /
(2 * 3.1415926536 * self.stddev ** 2) ** .5)
def cdf(self, x):
"""Calculates value of CDF for x-value"""
m = (x - self.mean) / (self.stddev * 2 ** .5)
return (1 + (m - m ** 3 / 3 + m ** 5 / 10 - m ** 7
/ 42 + m ** 9 / 216) * 2 / 3.1415926536 ** .5) / 2
|
#!/usr/bin/env python3
""" Write script that displays the up coming launch"""
import requests
if __name__ == '__main__':
# need url
url = "https://api.spacexdata.com/v4/launches/upcoming"
# request url
launchData = requests.get(url).json()
# set date type for unbound value comparison
date = float('inf')
# set for loop to iterate through launches
for idx, launch in enumerate(launchData):
if date > launch["date_unix"]:
date = launch["date_unix"]
launchIdx = idx
# get data based on launchData[launchIdx]
upLaunch = launchData[launchIdx]
# name
name = upLaunch["name"]
# date in local time
dateLocal = upLaunch["date_local"]
# rocket: need url, request.get, json, rocket name
rocket = upLaunch["rocket"]
rocketUrl = "https://api.spacexdata.com/v4/rockets/{}".format(rocket)
rocketData = requests.get(rocketUrl).json()
rocketName = rocketData["name"]
# launch pad: need url, request.get, json, launch pad name
launchPad = upLaunch["launchpad"]
launchPadUrl = "https://api.spacexdata.com/v4/launchpads/{}".\
format(launchPad)
launchPadData = requests.get(launchPadUrl).json()
launchPadName = launchPadData["name"]
# launch pad locality
launchPadLoc = launchPadData["locality"]
# Print name, (date in local time), rocket name,
# launch pad name, (lunch pad locality)
print("{} ({}) {} - {} ({})".format(name, dateLocal,
rocketName, launchPadName,
launchPadLoc))
|
# https://www.hackerrank.com/challenges/python-string-formatting
def print_formatted(number):
# your code goes here
l = len(bin(number)[2:])
for i in range(1,number+1):
i_octal = oct(i)[2:]
i_hex = hex(i)[2:].swapcase()
i_bi = bin(i)[2:]
i_str = str(i)
print(i_str.rjust(l),i_octal.rjust(l),i_hex.rjust(l),i_bi.rjust(l))
if __name__ == '__main__':
n = int(input())
print_formatted(n) |
import random
s=["самовар", "весна", "лето"]
w=random.choice(s)
word=list(w)
l=random.choice(w)
lett=word.index(l)
word[lett]='?'
print(''.join(word))
a=input('Введите букву:')
if a==l:
print('Победа!')
print('Слово:', w)
else:
print('Увы!Попробуйте в другой раз.')
print('Слово:', w)
|
#Se crea la clase padre, donde ésta misma tomará posteriormente los métodos para las clases hijas .
class Juego:
__vidas = 0
#Método constructor, el cual contiene la palabra init, seguida de sus respectivos atributos, con sus reglas para crear el mismo método.
def __init__(self, vidas):
self.__vidas = vidas
#Método llamado Juega, con su respectivo retorno.
def Juega(self):
return 0
#Método que se utiliza para restarle vidas al usuario, en cada una de las oportunidades de las que tiene y se equivoca.
def QuitarVida(self):
self.__vidas = self.__vidas - 1
if (self.__vidas>0):
return 0
else:
return False
#Clase JuegaAdivinaNumero con sus respectivos atributos.
class JuegaAdivinaNumero(Juego):
__numeroAdivinar = 0
__intentos = 0
#Método que se utiliza para actualizar el método del jugador.
def ActualizarRecord(self):
self.__intentos = self.__intentos+1
#Segundo método constructor, junto a su estructura.
def __init__(self, vidas, numeroAdivinar):
super().__init__(vidas)
self.__numeroAdivinar = numeroAdivinar
#Método Juega junto al bucle while donde se realizan una serie de condiciones poara evaluar las vidas, el récord, y los intentos del jugador (usuario).
def Juega(self):
while True:
numero = int(input("Escribe el numero a adivinar"))
if (numero==self.__numeroAdivinar):
print("Acertaste!")
self.ActualizarRecord()
print("Intentos: ", self.__intentos)
break
else:
if self.QuitarVida():
if numero > self.__numeroAdivinar:
#Mensaje que se manda al usuario para hacerle saber que el número que debe adivinar, es menor que el que ingresó.
print("Intentalo de nuevo. El numero a adivinar es menor")
# Mensaje que se manda al usuario para hacerle saber que el número que debe adivinar, es mayor que el que ingresó.
else:
print("Intentalo de nuevo. El numero a adivinar es mayor")
else:
self.ActualizarRecord()
print("Intentos: ", self.__intentos)
break
#Pruebas unitarias que ayudan a la ejecución del programa.
if __name__=='__main__':
import doctest
doctest.testmod() |
import random
# controlled by player
class Rocket(object):
ver_velocity = 0
hor_velocity = 0
max_speed = 3
def __init__(self, x, y):
self.weapon = 'red'
self.x = x
self.y = y
def move(self, ver, hor):
if ver != 0 or self.ver_velocity !=0:
if ver != 0 and abs(self.ver_velocity) < self.max_speed:
self.ver_velocity += ver
else:
self.ver_velocity -= self.ver_velocity/abs(self.ver_velocity)
if hor != 0 or self.hor_velocity != 0:
if hor != 0 and abs(self.hor_velocity) < self.max_speed:
self.hor_velocity += hor
else:
self.hor_velocity -= self.hor_velocity/abs(self.hor_velocity)
self.x += self.hor_velocity
self.y += self.ver_velocity
class Projectile(object):
def __init__(self, x, y, power, ver, hor,type):
self.ver_velocity = ver
self.hor_velocity = hor
self.power = power
self.x = x
self.y = y
def move(self):
self.x += self.hor_velocity
self.y += self.ver_velocity
class Weapon(Rocket):
def __init__(self):
self.type = "red"
self.power = 1
def fire(self):
if self.type == "red":
if self.power == 1:
drawer.projectiles.append(Projectile(self.x,self.y,-4,0,'red'))
elif self.power == 2:
drawer.projectiles.append(Projectile(self.x+2, self.y, -4, 0,'red'))
drawer.projectiles.append(Projectile(self.x-2, self.y, -4, 0,'red'))
elif self.power == 3:
drawer.projectiles.append(Projectile(self.x+3, self.y, -4, 0,'red'))
drawer.projectiles.append(Projectile(self.x, self.y, -4, 0,'red'))
drawer.projectiles.append(Projectile(self.x-3, self.y, -4, 0,'red'))
elif self.type == "green":
pass
class Drawer(object):
rockets = []
projectiles = []
drawer = Drawer() |
import os #used for path making
import io #used for encoding option when writing
from make_articles_dico import make_articles_dico
from scrape_article_content import scrape_article_content
papers_dico = {"huffingtonpost" : 'http://huffingtonpost.com'}
def scraping(papers_dico):
#make_articles_dico=fct : (paper_name, papers_dico) as (str,dict) -> dict
#scrape_article_content = fct : (article_url) as str -> str
#Makes a file for each article from each newspaper
for paper_name in list(papers_dico) :
articles_dico=make_articles_dico(paper_name, papers_dico) #Returns a dictionary {article_name : article_url}
print(articles_dico) #à enlever
if not os.path.exists(paper_name): #Checks if a folder named after the newspaper exists
os.makedirs(paper_name)
print("%s in the making" %paper_name) #à enlever
articles_list = "%s/articles_list.txt" %paper_name
output_list = io.open(articles_list, "w", encoding="utf8")
for article_name in list(articles_dico) :
output_list.write(papername + "\n")
file_name = "%s\%s.txt" %(paper_name, article_name)
content=scrape_article_content(articles_dico[article_name]) #Returns the body of the article
output = io.open(file_name,"w", encoding="utf8")
output.write(content)
output.close()
output_list.close()
|
#!/usr/bin/env python
# coding: utf-8
# # Lab 07: The Internet
#
# - **Name**: Colton R. Crum
# - **Netid**: ccrum
# ## Activity 1: SpeedTest
#
# For the first activity, you are to measure the speed of various networking technologies by using the [SpeedTest] website. You are to use the following three connection types:
#
# 1. **Wired connection from your laptop or a lab machine**
#
# 2. **Wireless connection from your laptop**
#
# 3. **Cellular connection from your phone (make sure you are using 4G/LTE and not WiFi)**
#
#
# To test the speed of each connection, simply go to the website on the appropriate device: www.speedtest.net and hit the `Go` button. This will measure your **Ping**, **Download**, and **Upload** speeds to generate a result such as:
#
# <img src="https://www.speedtest.net/result/8129841449.png">
# <img src="https://www.speedtest.net/result/8129848300.png">
#
# [SpeedTest]: https://www.speedtest.net/
# ### Speed Tests
#
# Run the [SpeedTest] on each connection type a few times to get a representative sample and then complete the table below:
#
# | Connection Type | Ping (ms) | Download (Mbps) | Upload (Mbps) |
# |-----------------|-----------|-----------------|---------------|
# | Wireless | 1 | 91.49 | 80.59 |
# | Wired | 1 | 843.90 | 931.06 |
# | Cellular | 27 | 40.40 | 5.12 |
#
# <center><font color="red"></font></center>
#
# [SpeedTest]: https://www.speedtest.net/
# ### Analysis
#
# After completing the table above with your speed tests, analyze the results by answering the following questions:
#
# 1. Which connection type had the best **latency**? Explain.
#
# <font color="red">The wired desktop connection and the wireless connection both had the best latency, at 1 ms. Latency is a measure of delay, or how quickly the service responds to my request. </font>
#
# 2. Which connection type had the best **bandwidth**? Explain.
#
# <font color="red">The wired desktop connection had the best bandwidth, at 843.90 Mbps download and 931.06 Mbps upload. It had almost ten times more bandwidth than a wireless connection, and over twenty times more than my cellular connection. This measures the amount or capacity of data we can transfer over a period of time. The wireless connection and cellular connection are slower than the wired connection because wireless connections are slowed down by interference from other devices emitting radio waves. </font>
#
# 3. What difference (if any) did you notice between **download** and **upload** speeds? Discuss why this could be.
#
# <font color="red">On the cellular and wireless connections, the download speed was faster than the upload speed, and sometimes a lot more (8 times greater for cellular). However, with the wired connection, the upload speed was faster. These connections carry upstream and downstream data, and the bandwidth being used on both channels changes with the amount of traffic. At Notre Dame, there would be more students on a wireless connection, making a wired connection not only faster because of the wire, but also since less bandwidth is being used by other users. This would account for some of the differences between upload and download speeds. </font>
#
# 4. Overall, which connection type was the **best**? Explain.
#
# <font color="red">The wired connection was the best overall. It had the fastest latency, and largest bandwidth, making it a superior connection to any of the others.</font>
# ## Activity 2: Bandwidth and Latency
#
# For the second activity, you are to write two functions that you can utilize to perform your own **bandwidth** and **latency** measurements. The first is `measure_bandwidth`, which uses [requests] to download data from a web server, while the second is `measure_latency` which uses a low-level [socket] to connect to a remote server. For timing, we will use Python's [time] module:
#
# current_time = time.time()
#
# [requests]: http://docs.python-requests.org/en/master/
# [socket]: https://docs.python.org/3/library/socket.html
# [time]: https://docs.python.org/3/library/time.html
# ### Measure Bandwidth
# In[26]:
import requests
import time
def measure_bandwidth(url):
''' Measure bandwidth by doing the following:
1. Record start time.
2. Download data specified by url.
3. Record end time.
4. Compute bandwidth:
bandwidth = (Amount of Data / Elapsed Time) / 2**20
'''
start_time = time.time()
response = requests.get(url)
end_time = time.time()
bandwidth = ((len(response.content) / ((end_time) - (start_time)) / (2**20)))
return bandwidth
# In[70]:
URLS = {
'Slack': 'https://downloads.slack-edge.com/releases_x64/SlackSetup.exe',
'Discord' : 'https://dl.discordapp.net/apps/win/0.0.305/DiscordSetup.exe',
'Firefox': 'https://download-installer.cdn.mozilla.net/pub/firefox/releases/66.0/linux-x86_64/en-US/firefox-66.0.tar.bz2'
}
for url in URLS:
print('Downloaded {} with bandwidth of {:.2f} MBps'.format(url, measure_bandwidth(URLS[url])))
# ### Measure Latency
# In[71]:
import socket
import time
def measure_latency(domain):
''' Measure latency by doing the following:
1. Create streaming internet socket.
2. Record start time.
3. Connect to specified domain at port 80.
4. Record end time.
5. Compute latency:
latency = Elapsed Time * 1000
'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
start_time = time.time()
s.connect((domain, 80))
end_time = time.time()
latency = (((end_time) - (start_time)) *1000)
return latency
# In[72]:
DOMAINS = [
'facebook.com',
'cnn.com',
'google.com',
'nd.edu',
'amazon.co.uk',
'baidu.com',
'europa.eu',
'yahoo.co.jp',
]
# In[69]:
for domain in DOMAINS:
print('Connection to {} has latency of {:.2f} ms'.format(domain, measure_latency(domain)))
# ### Analysis
#
# After writing the `measure_bandwidth` and `measure_latency` functions above and testing them, answer the following questions:
#
# 1. Which applications had the best bandwidth? How do these bandwidth measurements compare to the ones you had in Activity 1? What explains the differences?
#
# <font color="red">Discord had the best bandwidth at 6.18 MBps, followed by Firefox and Slack, 3.36 MBps and 1.33 MBps respectively. These bandwidths are far worse than the ones in activity 1. This is because we never tested bandwidth for downloading something in activity 1, whereas this activity was a real world test of bandwidth, even against downloads from different urls.</font>
#
# 2. Which domains had the best latency? Which ones had the worst latency? What explains these differences?
#
# <font color="red">CNN.com had the best latency at 8.01 ms, and yahoolco.jp had the worst latency at 296.45 ms. CNN is located in the United States, making the distance much shorter than Yahoo Japan, where its servers are located in Asia. This distance affects the responsiveness of the service. </font>
# ## Activity 3: EggHead's Adventure
#
# For the last activity, you are play the following educational game created by the [Office of Digital Learning] as an experiment:
#
# - [Introduction to Networks](https://s3.us-east-2.amazonaws.com/cs4all/cs4all-game/story_html5.html)
#
# - [Network Toolkit](https://s3.us-east-2.amazonaws.com/cs4all/Network-toolkit/story_html5.html)
#
# Once you have completed the game, please fill out the following [survey](https://goo.gl/forms/AfUJ5b4cQfVqwCof1).
#
# [Office of Digital Learning]: https://online.nd.edu/
|
def main():
message = 'GUVF VF ZL FRPERG ZRFFNTR'
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for key in range(len(letters)):
translated = ''
for symbol in message:
if symbol in letters:
num = letters.find(symbol)
num = num - key
if num < 0:
num = num + len(letters)
translated = translated + letters[num]
#prueba con cada índice, todas las posibilidades
else:
translated = translated + symbol
print('Key #%s: %s' % (key,translated))
#import <filename>
#<filename>.main()
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 29 10:11:50 2014
@author: 11111042
"""
def buscar(n):
list1 = ["Life","The Universe","Everything","Jack","Jill","Life","Jill"]
count = 0
for i in range(1,len(list1)):
if count<len(list1) and list1[count]!=n:
count = count + 1
if count<len(list1):
print list[count]
else:
print "Not found"
|
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 22 10:01:03 2014
@author: 11111042
"""
def quickSort(lista):
menorLista = []
pivotLista = []
mayorLista = []
if len(lista) <= 1:
return lista
else:
pivot = lista[0]
for i in lista:
if i < pivot:
menorLista.append(i)
elif i > pivot:
mayorLista.append(i)
else:
pivotLista.append(i)
menorLista = quickSort(menorLista)
mayorLista = quickSort(mayorLista)
return menorLista + pivotLista + mayorLista
#no cambia la lista, sino retorna una nueva lista
def mergeSort(lista, inicio, fin):
if inicio < fin:
mitad = (inicio+fin)/2
mergeSort(lista, inicio, mitad)
mergeSort(lista, mitad+1, fin)
merge(lista, inicio, mitad, fin)
#no retorna una nueva lista, sino cambia la lista
def merge(listaT, inicio, mitad, fin):
#listaT = lista temporal
#listaTO = lista temporal ordenada
listaTO = []
indice1 = inicio
indice2 = mitad+1
while indice1 <= mitad and indice2 <= fin:
if listaT[indice1] < listaT[indice2]:
listaTO.append(listaT[indice1])
indice1 = indice1+1
else:
listaTO.append(listaT[indice2])
indice2 = indice2+1
while indice1 <= mitad:
listaTO.append(listaT[indice1])
indice1 = indice1+1
while indice2 <= fin:
listaTO.append(listaT[indice2])
indice2 = indice2+1
for i, value in enumerate(listaTO):
listaT[inicio+i] = value
def main():
lista1 = [4,1,2,5,3,9,7,6,8,0]
lista2 = [9,2,6,1,7,3,8,0,5,4]
print "Quick Sort :", quickSort(lista1)
mergeSort(lista2, 0, len(lista2)-1)
print "Merge Sort :", lista2
if __name__=="__main__":
main() |
# -*- coding: cp1252 -*-
def main():
nombre = input("Ingrese su nombre: ")
password = input("Ingrese su clave: ")
if nombre == "Andrea" and password == "12345":
print ("Bienvenida", nombre)
elif nombre == "Fred" and password == "Rock": #else_ if es lo mismo que elif
print ("Bienvenido", nombre)
else:
print ("No está en lista")
if __name__=="__main__":
main() |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 15 10:20:52 2014
@author: 11111042
"""
def buscarSecuencial(lista, n):
listaAuxiliar = []
for i in range(0,len(lista)):
if lista[i] == n:
listaAuxiliar.append(i)
return listaAuxiliar
def buscarRecursivo(lista, n, indice):
if indice == 1:
return -1
else:
if lista[indice] == n:
return indice
else:
return buscarRecursivo(lista, n, indice-1)
def main():
lista = [10,15,8,4,8]
print buscarSecuencial(lista, 8)
#indice = len(lista)-1
#print buscarRecursivo(lista, 1, indice)
if __name__=="__main__":
main() |
from weatbag import words
class Tile:
def __init__(self):
self.challenge_completed = False
self.minutes = "40"
def describe(self):
print("You see two children who you notice now are a boy and a girl.\n"
"They are playing and running around a raft.\n")
if not self.challenge_completed:
self.challenge()
else:
print("\nThe children will take you to the western island!")
def challenge(self):
print("You ask them to give it to you."
"The little boy laughs and replies: \n"
"So you think you are brave enough to go to that island? "
"Very well, but we cannot give you our raft. "
"What we can do is transport you there ourselves. But first you "
"must answer this:\n\n"
"Ignore weight and weather variables and listen carefully.\n"
"It takes me exactly one hour to transport a person to "
"the island.\n"
"It takes my sister double that time.\n"
"If we combine our power, "
"how many minutes will it take to transport you to the island?\n"
"For your answer, type a number followed by 'minutes'.\n")
def action(self, player, do):
if not self.challenge_completed:
try:
if do[1] == "minutes":
if do[0] == self.minutes:
print("Your answer has pleased me and my sister! "
"\nLet's go!")
print("The brother and sister will take you to the "
"island.")
self.challenge_completed = True
else:
print("We're afraid this is not the correct answer. "
"Try another one.")
elif (do[0] in words.take) and (do[1] == "sister" or
do[1] == "girl"):
print("You bastard! Let my sister down!\n"
"What kind of an asshole are you? "
"Taking advantage of little children?\n"
"We will transport you for free.\n")
print("The brother and sister will take you "
"to the island!")
self.challenge_completed = True
elif (do[0] in words.take) and (do[1] == "brother" or
do[1] == "boy"):
print("You bastard, put me down!\n"
"We will trasnport you for free!\n")
print("The brother and sister will take you "
"to the island!")
self.challenge_completed = True
elif (do[0] in words.take) and not self.challenge_completed:
print("I told you we won't give you our raft, "
"you have to find the correct amount of time!\n")
except:
print("Please try typing a number, like '42 minutes'\n.")
else:
print("Sorry, I don't understand.")
def leave(self, player, direction):
if direction == "w" and not self.challenge_completed:
print ("You can't go there by swimming, that part is full of "
"electric eels.")
return False
else:
return True
|
import projection_virtual_side
def sort_asterix(pattern, convert=str):
"""
Function to create a sorting function for a given pattern using a callable to convert what ever is found with asterix.
Parameters
----------
pattern : str
Pattern to sort for.
If there is no asterix in the pattern, the `convert` will be called on the whole pattern.
If there is *one* asterix in the pattern, `convert` will be called on what ever is in the asterix.
If there are multiple asterix in the pattern, `convert` will be call consecutivly (NOT IMPLEMENTED YET).
convert : Callable, optional
Some callable which should be applied. Default is `str`.
Returns
-------
func : callable
Function that converts a given argument.
TODO
----
* Implement multiple asterix
* go to index based slicing
"""
n_asterix = pattern.count('*')
if n_asterix == 0:
return lambda x: convert(x)
elif n_asterix == 1:
i = pattern.find('*')
return lambda x: convert(x.replace(pattern[:i], '').replace(pattern[ i +1:], ''))
else:
raise UserWarning('Not implemented yet')
# import re
# for i in re.finditer('\*', pattern):
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 6 17:00:45 2018
@author: wmy
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
import math
import sklearn
import sklearn.datasets
from opt_utils import load_params_and_grads, initialize_parameters, \
forward_propagation, backward_propagation
from opt_utils import compute_cost, predict, predict_dec, \
plot_decision_boundary, load_dataset
from testCases import *
class DeepNeuralNetwork():
def __init__(self, name, layer_list):
self.name = name
self.Parameters_Init(layer_list)
# it will be used when plot the costs picture
self.iteration_unit = 1000
print("You created a deep neural network named '" + self.name + "'")
print('The layer list is ' + str(self.layer_list))
pass
def Parameters_Init(self, layer_list):
self.layer_list = layer_list[:]
np.random.seed(3)
self.parameters = {}
# number of layers in the network
self.L = len(layer_list) - 1
for l in range(1, self.L + 1):
self.parameters['W' + str(l)] = np.random.randn(layer_list[l], \
layer_list[l-1]) * np.sqrt(2 / layer_list[l-1])
self.parameters['b' + str(l)] = np.zeros((layer_list[l], 1))
assert(self.parameters['W' + str(l)].shape == (layer_list[l], \
layer_list[l-1]))
assert(self.parameters['b' + str(l)].shape == (layer_list[l], 1))
return self.parameters
def Sigmoid(self, x):
s = 1 / (1 + np.exp(-x))
return s
def ReLU(self, x):
s = np.maximum(0, x)
return s
def Forward_Propagation(self, X):
# copy the dataset X (or A0)
self.dataset = {}
self.dataset['X'] = X[:]
# the number of datasets
self.m = X.shape[1]
# the caches for hidden and output layers
self.caches = []
assert(self.L == len(self.parameters) // 2)
A_now = X
for l in range(1, self.L):
A_prev = A_now
W = self.parameters['W' + str(l)]
b = self.parameters['b' + str(l)]
Z = np.dot(W, A_prev) + b
A_now = self.ReLU(Z)
# cache : (Zl, Al, Wl, bl)
cache = (Z, A_now, W, b)
self.caches.append(cache)
WL = self.parameters['W' + str(self.L)]
bL = self.parameters['b' + str(self.L)]
ZL = np.dot(WL, A_now) + bL
# the output layer use sigmoid activation function
self.AL = self.Sigmoid(ZL)
cache = (ZL, self.AL, WL, bL)
self.caches.append(cache)
# check the shape
assert(self.AL.shape == (1, X.shape[1]))
return self.AL, self.caches
def Compute_Cost(self, Y):
assert(self.m == Y.shape[1])
# - (y * log(a) + (1-y) * log(1-a))
logprobs = np.multiply(-np.log(self.AL),Y) + \
np.multiply(-np.log(1 - self.AL), 1 - Y)
# the average of the loss function
cost = 1.0/self.m * np.nansum(logprobs)
cost = np.squeeze(cost)
assert(cost.shape == ())
self.cost = cost
return self.cost
def Backward_Propagation(self, Y):
# copy the dataset Y
self.dataset['Y'] = Y[:]
self.grads = {}
assert(self.L == len(self.caches))
assert(self.m == self.AL.shape[1])
m = self.m
# the number of layers
L = self.L
Y = Y.reshape(self.AL.shape)
(ZL, AL, WL, bL) = self.caches[-1]
(ZL_prev, AL_prev, WL_prev, bL_prev) = self.caches[-2]
# compute the grads of layer L
self.grads['dZ' + str(L)] = AL - Y
self.grads['dW' + str(L)] = 1.0/m * \
np.dot(self.grads['dZ' + str(L)], AL_prev.T)
self.grads['db' + str(L)] = 1.0/m * \
np.sum(self.grads['dZ' + str(L)], axis=1, keepdims = True)
for l in reversed(range(L - 1)):
# the layer l + 1
current_cache = self.caches[l]
(Z_current, A_current, W_current, b_current) = current_cache
if l != 0:
before_cache = self.caches[l - 1]
(Z_before, A_before, W_before, b_before) = before_cache
else:
# A0
A_before = self.dataset['X']
behind_cache = self.caches[l + 1]
(Z_behind, A_behind, W_behind, b_behind) = behind_cache
# compute the grads of layer l + 1
dA = np.dot(W_behind.T, self.grads['dZ' + str(l + 2)])
dZ = np.multiply(dA, np.int64(A_current > 0))
dW = 1.0/m * np.dot(dZ, A_before.T)
db = 1.0/m * np.sum(dZ, axis=1, keepdims = True)
self.grads['dA' + str(l + 1)] = dA
self.grads['dZ' + str(l + 1)] = dZ
self.grads['dW' + str(l + 1)] = dW
self.grads['db' + str(l + 1)] = db
return self.grads
def Update_Parameters(self, learning_rate):
assert(self.L == len(self.parameters) // 2)
L = self.L
for l in range(L):
# W = W - a * dW
self.parameters["W" + str(l + 1)] = self.parameters["W" + str(l + 1)] - \
learning_rate * self.grads["dW" + str(l + 1)]
# b = b - a * db
self.parameters["b" + str(l + 1)] = self.parameters["b" + str(l + 1)] - \
learning_rate * self.grads["db" + str(l + 1)]
return self.parameters
def Train(self, X, Y, iterations = 3000, learning_rate = 0.0075, print_cost = False):
self.learning_rate = learning_rate
self.costs = []
self.Forward_Propagation(X)
cost = self.Compute_Cost(Y)
print ("Cost after iteration %i: %f" %(0, cost))
self.Query(X, Y)
self.costs.append(cost)
for i in range(1, iterations+1):
self.Forward_Propagation(X)
cost = self.Compute_Cost(Y)
self.Backward_Propagation(Y)
self.Update_Parameters(learning_rate)
if print_cost and i % (10*self.iteration_unit) == 0:
print ("Cost after iteration %i: %f" %(i, cost))
self.Query(X, Y)
if i % self.iteration_unit == 0:
self.costs.append(cost)
print('finished!')
self.PlotCosts()
return self.costs
def Query(self, X, Y):
m = X.shape[1]
p = np.zeros((1,m), dtype = np.int)
probs, caches = self.Forward_Propagation(X)
for i in range(0, probs.shape[1]):
if probs[0,i] > 0.5:
p[0,i] = 1
else:
p[0,i] = 0
#print("Accuracy: " + str(100*np.sum((p == Y)/m)) + '%')
print("Accuracy: " + str(100 * np.mean((p[0,:] == Y[0,:]))) + '%')
return p
def Predict(self, X):
m = X.shape[1]
p = np.zeros((1,m), dtype = np.int)
probs, caches = self.Forward_Propagation(X)
for i in range(0, probs.shape[1]):
if probs[0,i] > 0.5:
p[0,i] = 1
else:
p[0,i] = 0
return p
def PlotCosts(self):
plt.plot(np.squeeze(self.costs))
plt.ylabel('cost')
plt.xlabel('iterations (per ' + str(self.iteration_unit) + ')')
plt.title("Learning rate =" + str(self.learning_rate))
plt.show()
def Dropout_Init(self, keep_prob_list):
self.keep_prob_list = keep_prob_list
pass
def Forward_Propagation_Dropout(self, X):
# choose the random seed
np.random.seed(1)
# copy the dataset X (or A0)
self.dataset = {}
self.dataset['X'] = X[:]
self.m = X.shape[1]
# the caches for hidden and output layers
self.caches = []
self.D = {}
assert(self.L == len(self.parameters) // 2)
A_now = X
for l in range(1, self.L):
A_prev = A_now
W = self.parameters['W' + str(l)]
b = self.parameters['b' + str(l)]
Z = np.dot(W, A_prev) + b
A_now = self.ReLU(Z)
# dropout
self.D['D' + str(l)] = np.random.rand(A_now.shape[0], \
A_now.shape[1])
self.D['D' + str(l)] = (self.D['D' + str(l)] < \
self.keep_prob_list[l - 1])
A_now = A_now * self.D['D' + str(l)]
A_now = A_now / self.keep_prob_list[l - 1]
# cache : (Zl, Al, Wl, bl)
cache = (Z, A_now, W, b)
self.caches.append(cache)
WL = self.parameters['W' + str(self.L)]
bL = self.parameters['b' + str(self.L)]
ZL = np.dot(WL, A_now) + bL
# the output layer use sigmoid activation function
self.AL = self.Sigmoid(ZL)
cache = (ZL, self.AL, WL, bL)
self.caches.append(cache)
# check the shape
assert(self.AL.shape == (1, X.shape[1]))
return self.AL, self.caches
def Backward_Propagation_Dropout(self, Y):
# copy the dataset Y
self.dataset['Y'] = Y[:]
self.grads = {}
assert(self.L == len(self.caches))
assert(self.m == self.AL.shape[1])
m = self.m
# the number of layers
L = self.L
Y = Y.reshape(self.AL.shape)
(ZL, AL, WL, bL) = self.caches[-1]
(ZL_prev, AL_prev, WL_prev, bL_prev) = self.caches[-2]
# compute the grads of layer L
self.grads['dZ' + str(L)] = AL - Y
self.grads['dW' + str(L)] = 1.0/m * \
np.dot(self.grads['dZ' + str(L)], AL_prev.T)
self.grads['db' + str(L)] = 1.0/m * \
np.sum(self.grads['dZ' + str(L)], axis=1, keepdims = True)
for l in reversed(range(L - 1)):
# the layer l + 1
current_cache = self.caches[l]
(Z_current, A_current, W_current, b_current) = current_cache
if l != 0:
before_cache = self.caches[l - 1]
(Z_before, A_before, W_before, b_before) = before_cache
else:
# A0
A_before = self.dataset['X']
behind_cache = self.caches[l + 1]
(Z_behind, A_behind, W_behind, b_behind) = behind_cache
# compute the grads of layer l + 1
dA = np.dot(W_behind.T, self.grads['dZ' + str(l + 2)])
# dropout
dA = dA * self.D['D' + str(l + 1)]
dA = dA / self.keep_prob_list[l]
# dropout finished
dZ = np.multiply(dA, np.int64(A_current > 0))
dW = 1.0/m * np.dot(dZ, A_before.T)
db = 1.0/m * np.sum(dZ, axis=1, keepdims = True)
self.grads['dA' + str(l + 1)] = dA
self.grads['dZ' + str(l + 1)] = dZ
self.grads['dW' + str(l + 1)] = dW
self.grads['db' + str(l + 1)] = db
return self.grads
def Train_Dropout(self, X, Y, keep_prob_list, iterations = 3000, learning_rate = 0.0075, print_cost = False):
self.Dropout_Init(keep_prob_list)
self.learning_rate = learning_rate
self.costs = []
self.Forward_Propagation(X)
cost = self.Compute_Cost(Y)
print ("Cost after iteration %i: %f" %(0, cost))
self.Query(X, Y)
self.costs.append(cost)
for i in range(1, iterations+1):
self.Forward_Propagation_Dropout(X)
cost = self.Compute_Cost(Y)
self.Backward_Propagation_Dropout(Y)
self.Update_Parameters(learning_rate)
if print_cost and i % (10*self.iteration_unit) == 0:
print ("Cost after iteration %i: %f" %(i, cost))
self.Query(X, Y)
if i % self.iteration_unit == 0:
self.costs.append(cost)
print('finished!')
self.PlotCosts()
return self.costs
def L2_Regularization_Init(self, lambda_list):
self.lambda_list = lambda_list[:]
pass
def Compute_Cost_L2_Regularization(self, Y):
m = Y.shape[1]
cross_entropy_cost = self.Compute_Cost(Y)
L2_regularization_cost = 0.0
for l in range(1, self.L + 1):
Wl = self.parameters['W' + str(l)]
L2_regularization_cost += 1.0/m * \
self.lambda_list[l - 1]/2 * np.sum(np.square(Wl))
cost = cross_entropy_cost + L2_regularization_cost
cost = np.squeeze(cost)
assert(cost.shape == ())
self.cost = cost
return self.cost
def Backward_Propagation_L2_Regularization(self, Y):
# copy the dataset Y
self.dataset['Y'] = Y[:]
self.grads = {}
assert(self.L == len(self.caches))
assert(self.m == self.AL.shape[1])
m = self.m
# the number of layers
L = self.L
Y = Y.reshape(self.AL.shape)
(ZL, AL, WL, bL) = self.caches[-1]
(ZL_prev, AL_prev, WL_prev, bL_prev) = self.caches[-2]
# compute the grads of layer L
self.grads['dZ' + str(L)] = AL - Y
# L2 regularization
self.grads['dW' + str(L)] = 1.0/m * \
np.dot(self.grads['dZ' + str(L)], AL_prev.T)
self.grads['dW' + str(L)] += self.lambda_list[-1] / m * WL
# L2 regularization finished
self.grads['db' + str(L)] = 1.0/m * \
np.sum(self.grads['dZ' + str(L)], axis=1, keepdims = True)
for l in reversed(range(L - 1)):
# the layer l + 1
current_cache = self.caches[l]
(Z_current, A_current, W_current, b_current) = current_cache
if l != 0:
before_cache = self.caches[l - 1]
(Z_before, A_before, W_before, b_before) = before_cache
else:
# A0
A_before = self.dataset['X']
behind_cache = self.caches[l + 1]
(Z_behind, A_behind, W_behind, b_behind) = behind_cache
# compute the grads of layer l + 1
dA = np.dot(W_behind.T, self.grads['dZ' + str(l + 2)])
dZ = np.multiply(dA, np.int64(A_current > 0))
# L2 regularization
dW = 1.0/m * np.dot(dZ, A_before.T)
dW += self.lambda_list[l] / m * W_current
# L2 regularization finished
db = 1.0/m * np.sum(dZ, axis=1, keepdims = True)
self.grads['dA' + str(l + 1)] = dA
self.grads['dZ' + str(l + 1)] = dZ
self.grads['dW' + str(l + 1)] = dW
self.grads['db' + str(l + 1)] = db
return self.grads
def Train_L2_Regularization(self, X, Y, lambda_list, iterations = 3000, learning_rate = 0.0075, print_cost = False):
self.L2_Regularization_Init(lambda_list)
self.learning_rate = learning_rate
self.costs = []
self.Forward_Propagation(X)
cost = self.Compute_Cost_L2_Regularization(Y)
print ("Cost after iteration %i: %f" %(0, cost))
self.Query(X, Y)
self.costs.append(cost)
for i in range(1, iterations + 1):
self.Forward_Propagation(X)
cost = self.Compute_Cost_L2_Regularization(Y)
self.Backward_Propagation_L2_Regularization(Y)
self.Update_Parameters(learning_rate)
if print_cost and i % (10*self.iteration_unit) == 0:
print ("Cost after iteration %i: %f" %(i, cost))
self.Query(X, Y)
if i % self.iteration_unit == 0:
self.costs.append(cost)
print('finished!')
self.PlotCosts()
return self.costs
def J(self, X, Y, parameters):
# the number of datasets
m = X.shape[1]
assert(self.L == len(parameters) // 2)
A_now = X
for l in range(1, self.L):
A_prev = A_now
W = parameters['W' + str(l)]
b = parameters['b' + str(l)]
Z = np.dot(W, A_prev) + b
A_now = self.ReLU(Z)
pass
WL = parameters['W' + str(self.L)]
bL = parameters['b' + str(self.L)]
ZL = np.dot(WL, A_now) + bL
# the output layer use sigmoid activation function
AL = self.Sigmoid(ZL)
# check the shape
assert(AL.shape == (1, X.shape[1]))
# Cost
logprobs = np.multiply(-np.log(AL),Y) + \
np.multiply(-np.log(1 - AL), 1 - Y)
cost = 1.0/m * np.sum(logprobs)
return cost
def Dictionary_To_Vector(self, parameters):
keys = []
count = 0
for l in range(1, self.L + 1):
for key in ['W' + str(l), 'b' + str(l)]:
new_vector = np.reshape(parameters[key], (-1,1))
keys = keys + [key]*new_vector.shape[0]
if count == 0:
theta = new_vector
else:
theta = np.concatenate((theta, new_vector), axis=0)
count = count + 1
return theta, keys
def Vector_To_Dictionary(self, theta):
parameters = {}
star = 0
for l in range(1, self.L + 1):
parameters['W' + str(l)] = \
theta[star:star + self.parameters['W' + str(l)].shape[0] * \
self.parameters['W' + str(l)].shape[1]].reshape(self.parameters['W' + str(l)].shape)
star = star + self.parameters['W' + str(l)].shape[0] * \
self.parameters['W' + str(l)].shape[1]
parameters['b' + str(l)] = \
theta[star:star + self.parameters['b' + str(l)].shape[0] * \
self.parameters['b' + str(l)].shape[1]].reshape(self.parameters['b' + str(l)].shape)
star = star + self.parameters['b' + str(l)].shape[0] * \
self.parameters['b' + str(l)].shape[1]
return parameters
def Gradients_To_Vector(self, gradients):
count = 0
for l in range(1, self.L + 1):
for key in ['dW' + str(l), 'db' + str(l)]:
new_vector = np.reshape(gradients[key], (-1,1))
if count == 0:
theta = new_vector
else:
theta = np.concatenate((theta, new_vector), axis=0)
count = count + 1
pass
pass
return theta
def Gradient_Check(self, parameters, gradients, X, Y, epsilon = 1e-7):
# Set-up variables
parameters_values, _ = self.Dictionary_To_Vector(parameters)
grad = self.Gradients_To_Vector(gradients)
num_parameters = parameters_values.shape[0]
J_plus = np.zeros((num_parameters, 1))
J_minus = np.zeros((num_parameters, 1))
gradapprox = np.zeros((num_parameters, 1))
# Compute gradapprox
for i in range(num_parameters):
# J plus
thetaplus = np.copy(parameters_values)
thetaplus[i][0] += epsilon
J_plus[i]= self.J(X, Y, self.Vector_To_Dictionary(thetaplus))
# J minus
thetaminus = np.copy(parameters_values)
thetaminus[i][0] -= epsilon
J_minus[i] = self.J(X, Y, self.Vector_To_Dictionary(thetaminus))
# Compute gradapprox[i]
gradapprox[i] = (J_plus[i] - J_minus[i]) / (2 * epsilon)
pass
numerator = np.linalg.norm(grad - gradapprox)
denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox)
difference = numerator / denominator
if difference > 1e-7:
print ("\033[93m" + "There is a mistake in the backward propagation! difference = " + str(difference) + "\033[0m")
else:
print ("\033[92m" + "Your backward propagation works perfectly fine! difference = " + str(difference) + "\033[0m")
return difference
def Check_The_Gradient(self, X, Y, epsilon = 1e-7):
print('Gradient checking...please wait.')
self.Forward_Propagation(X)
self.Backward_Propagation(Y)
parameters = self.parameters
gradients = self.grads
difference = self.Gradient_Check(parameters, gradients, X, Y, epsilon = epsilon)
return difference
def Random_Mini_Batches(self, X, Y, mini_batch_size = 64, seed = 0):
np.random.seed(seed)
m = X.shape[1]
mini_batches = []
# Step 1: Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X = X[:, permutation]
shuffled_Y = Y[:, permutation].reshape((1,m))
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
# number of mini batches of size mini_batch_size in your partitionning
num_complete_minibatches = math.floor(m/mini_batch_size)
for k in range(0, num_complete_minibatches):
mini_batch_X = shuffled_X[:, k * mini_batch_size : (k+1) * mini_batch_size]
mini_batch_Y = shuffled_Y[:, k * mini_batch_size : (k+1) * mini_batch_size]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
# Handling the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X = shuffled_X[:, num_complete_minibatches * mini_batch_size: ]
mini_batch_Y = shuffled_Y[:, num_complete_minibatches * mini_batch_size: ]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def Initialize_Velocity(self):
self.v = {}
for l in range(1, self.L + 1):
self.v["dW" + str(l)] = np.zeros((self.parameters['W' + str(l)].shape[0], \
self.parameters['W' + str(l)].shape[1]))
self.v["db" + str(l)] = np.zeros((self.parameters['b' + str(l)].shape[0], \
self.parameters['b' + str(l)].shape[1]))
return self.v
def Update_Parameters_Momentum(self, beta, learning_rate):
for l in range(1, self.L + 1):
# compute velocities
self.v["dW" + str(l)] = beta * self.v['dW' + str(l)] + \
(1 - beta) * self.grads['dW' + str(l)]
self.v["db" + str(l)] = beta * self.v['db' + str(l)] + \
(1 - beta) * self.grads['db' + str(l)]
# update parameters
self.parameters["W" + str(l)] = self.parameters["W" + str(l)] - \
learning_rate * self.v["dW" + str(l)]
self.parameters["b" + str(l)] = self.parameters["b" + str(l)] - \
learning_rate * self.v["db" + str(l)]
return self.parameters, self.v
def Initialize_Adam(self):
self.v = {}
self.s = {}
# Initialize v, s. Input: "parameters". Outputs: "v, s".
for l in range(1, self.L + 1):
self.v["dW" + str(l)] = np.zeros((self.parameters["W" + str(l)].shape[0], \
self.parameters["W" + str(l)].shape[1]))
self.v["db" + str(l)] = np.zeros((self.parameters["b" + str(l)].shape[0], \
self.parameters["b" + str(l)].shape[1]))
self.s["dW" + str(l)] = np.zeros((self.parameters["W" + str(l)].shape[0], \
self.parameters["W" + str(l)].shape[1]))
self.s["db" + str(l)] = np.zeros((self.parameters["b" + str(l)].shape[0], \
self.parameters["b" + str(l)].shape[1]))
return self.v, self.s
def Update_Parameters_Adam(self, t, learning_rate = 0.01, beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8):
self.v_corrected = {}
self.s_corrected = {}
# Perform Adam update on all parameters
for l in range(1, self.L + 1):
# Moving average of the gradients. Inputs: "v, grads, beta1". Output: "v".
self.v["dW" + str(l)] = beta1 * self.v["dW" + str(l)] + (1 - beta1) * self.grads['dW' + str(l)]
self.v["db" + str(l)] = beta1 * self.v["db" + str(l)] + (1 - beta1) * self.grads['db' + str(l)]
# Compute bias-corrected first moment estimate. Inputs: "v, beta1, t". Output: "v_corrected".
self.v_corrected["dW" + str(l)] = self.v["dW" + str(l)] / (1 - beta1 ** t)
self.v_corrected["db" + str(l)] = self.v["db" + str(l)] / (1 - beta1 ** t)
# Moving average of the squared gradients. Inputs: "s, grads, beta2". Output: "s".
self.s["dW" + str(l)] = beta2 * self.s["dW" + str(l)] + (1 - beta2) * (self.grads['dW' + str(l)] ** 2)
self.s["db" + str(l)] = beta2 * self.s["db" + str(l)] + (1 - beta2) * (self.grads['db' + str(l)] ** 2)
# Compute bias-corrected second raw moment estimate. Inputs: "s, beta2, t". Output: "s_corrected".
self.s_corrected["dW" + str(l)] = self.s["dW" + str(l)] / (1 - beta2 ** t)
self.s_corrected["db" + str(l)] = self.s["db" + str(l)] / (1 - beta2 ** t)
# Update parameters. Inputs: "parameters, learning_rate, v_corrected, s_corrected, epsilon". Output: "parameters".
self.parameters["W" + str(l)] = self.parameters["W" + str(l)] - learning_rate * self.v_corrected["dW" + str(l)] / (np.sqrt(self.s_corrected["dW" + str(l)]) + epsilon)
self.parameters["b" + str(l)] = self.parameters["b" + str(l)] - learning_rate * self.v_corrected["db" + str(l)] / (np.sqrt(self.s_corrected["db" + str(l)]) + epsilon)
return self.parameters, self.v, self.s
def Train_Gradient_Descent(self, X, Y, learning_rate = 0.0007, mini_batch_size = 64, epsilon = 1e-8, num_epochs = 10000, print_cost = True):
self.costs = []
self.learning_rate = learning_rate
self.Forward_Propagation(X)
cost = self.Compute_Cost(Y)
print ("Cost after iteration %i: %f" %(0, cost))
self.Query(X, Y)
self.costs.append(cost)
seed = 10
for i in range(1, num_epochs + 1):
seed = seed + 1
minibatches = self.Random_Mini_Batches(X, Y, mini_batch_size, seed)
for minibatch in minibatches:
(minibatch_X, minibatch_Y) = minibatch
self.Forward_Propagation(minibatch_X)
cost = self.Compute_Cost(minibatch_Y)
self.Backward_Propagation(minibatch_Y)
self.Update_Parameters(learning_rate)
if print_cost and i % (10*self.iteration_unit) == 0:
print ("Cost after iteration %i: %f" %(i, cost))
self.Query(X, Y)
if i % self.iteration_unit == 0:
self.costs.append(cost)
print('finished!')
self.PlotCosts()
return self.costs
def Train_Momentum(self, X, Y, learning_rate = 0.0007, mini_batch_size = 64, beta = 0.9, epsilon = 1e-8, num_epochs = 10000, print_cost = True):
self.costs = []
self.learning_rate = learning_rate
self.Forward_Propagation(X)
cost = self.Compute_Cost(Y)
print ("Cost after iteration %i: %f" %(0, cost))
self.Query(X, Y)
self.costs.append(cost)
# Initialize the optimizer
self.Initialize_Velocity()
seed = 10
for i in range(1, num_epochs + 1):
seed = seed + 1
minibatches = self.Random_Mini_Batches(X, Y, mini_batch_size, seed)
for minibatch in minibatches:
(minibatch_X, minibatch_Y) = minibatch
self.Forward_Propagation(minibatch_X)
cost = self.Compute_Cost(minibatch_Y)
self.Backward_Propagation(minibatch_Y)
self.Update_Parameters_Momentum(beta=beta, learning_rate=learning_rate)
if print_cost and i % (10*self.iteration_unit) == 0:
print ("Cost after iteration %i: %f" %(i, cost))
self.Query(X, Y)
if i % self.iteration_unit == 0:
self.costs.append(cost)
print('finished!')
self.PlotCosts()
return self.costs
def Train_Adam(self, X, Y, learning_rate = 0.0007, mini_batch_size = 64, beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8, num_epochs = 10000, print_cost = True):
self.costs = []
self.learning_rate = learning_rate
self.Forward_Propagation(X)
cost = self.Compute_Cost(Y)
print ("Cost after iteration %i: %f" %(0, cost))
self.Query(X, Y)
self.costs.append(cost)
# Initialize the optimizer
self.Initialize_Adam()
t = 0
seed = 10
# Optimization loop
for i in range(1, num_epochs + 1):
seed = seed + 1
minibatches = self.Random_Mini_Batches(X, Y, mini_batch_size, seed)
for minibatch in minibatches:
# Select a minibatch
(minibatch_X, minibatch_Y) = minibatch
self.Forward_Propagation(minibatch_X)
cost = self.Compute_Cost(minibatch_Y)
self.Backward_Propagation(minibatch_Y)
# Adam counter
t = t + 1
self.Update_Parameters_Adam(t, learning_rate, beta1, beta2, epsilon)
if print_cost and i % (10*self.iteration_unit) == 0:
print ("Cost after iteration %i: %f" %(i, cost))
self.Query(X, Y)
if i % self.iteration_unit == 0:
self.costs.append(cost)
print('finished!')
self.PlotCosts()
return self.costs
pass
train_X, train_Y = load_dataset()
plt.show()
a = DeepNeuralNetwork("Model without optimization", [train_X.shape[0], 10, 3, 1])
for i in range(1500):
a.Forward_Propagation(train_X)
a.Backward_Propagation(train_Y)
a.Update_Parameters(0.35)
if i % 50 == 0:
plt.title("Model without optimization")
axes = plt.gca()
axes.set_xlim([-1.5,2.5])
axes.set_ylim([-1,1.5])
plot_decision_boundary(lambda x: a.Predict(x.T), train_X, np.squeeze(train_Y))
plt.show()
a.Query(train_X, train_Y)
|
# by eric
# 2018-08-16
# inspired by cheetah software
import numpy as np
import matplotlib.pyplot as plt
from math import pi, sin
def circular(y0, yf, x):
if (x<0) | (x>1):
print('phase out of range')
y = y0 + (yf - y0) * (sin((x - 0.5)*pi) + 1)/2
return y
class FootSwingTrajectory:
def __init__(self):
self._p0 = np.zeros(3)
self._pf = np.zeros(3)
self._p = np.zeros(3)
self._height = 0
def setInitialPosition(self, p0):
self._p0 = p0
def setFinalPosition(self, pf):
self._pf = pf
def setHeight(self, h):
self._height = h
def computeSwingTrajectoryCircular(self, phase):
# x轨迹
self._p[0] = circular(self._p0[0], self._pf[0], phase)
# y轨迹
self._p[1] = circular(self._p0[1], self._pf[1], phase)
# 高度轨迹
if phase < 0.5:
zp = circular(self._p0[2], (self._p0[2]+self._height), 2*phase)
else:
zp = circular((self._p0[2]+self._height), self._pf[2], (2*phase-1))
self._p[2] = zp
def main():
"""
test circular()
"""
y0 = 0
yf = 1
t = []
y = []
for x in range(10):
t.append(0.1*x)
y.append(circular(y0,yf,(0.1*x)))
plt.figure(1)
plt.plot(t,y)
plt.show()
"""
test FootSwingTrajectory
"""
fsTra = FootSwingTrajectory()
tmp1 = np.zeros(3)
tmp2 = np.zeros(3)
tmp1[0] = 0
tmp1[1] = 0.5
tmp1[2] = 0
fsTra.setInitialPosition(tmp1)
print(fsTra._p0)
tmp2[0] = 1
tmp2[1] = 0.5
tmp2[2] = -0.1
fsTra.setFinalPosition(tmp2)
fsTra.setHeight(0.2)
print(fsTra._p0)
print(fsTra._pf)
print(fsTra._height)
tt = []
xx = []
yy = []
zz = []
for idx in range(10):
phase = 0.1*idx
fsTra.computeSwingTrajectoryCircular(phase)
tt.append(phase)
xx.append(fsTra._p[0])
yy.append(fsTra._p[1])
zz.append(fsTra._p[2])
plt.figure(2)
plt.plot(tt,xx)
plt.figure(3)
plt.plot(tt,yy)
plt.figure(4)
plt.plot(tt,zz)
plt.show()
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.