text stringlengths 37 1.41M |
|---|
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
direction= (0,1)
start = [0,0]
for i in instructions:
if i == 'G':
start[0] += direction[0]
start[1] += direction[1]
elif i == 'L':
direction = (-direction[1], direction[0])
else:
direction = (direction[1], -direction[0])
return start == [0,0] or direction != (0,1) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
dummy = ListNode(-1)
curr = head
while curr:
curr_next = curr.next
prv, nxt = dummy, dummy.next
while nxt:
if nxt.val > curr.val: break
prv = nxt
nxt = nxt.next
curr.next = nxt
prv.next = curr
curr = curr_next
return dummy.next |
from rsa import key
people = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
# print(lambda x: (x[0],x[1]))
# for i in people:
# print(i[0])
# printing the people's list in height decreasing order
people.sort(key= lambda x: (-x[0], x[1]))
# sorted(people, key: lambda x: (-x[0],x[1]))
print(people)
ans = []
for i in people:
ans.insert(i[1],i)
print(i[1])
print(ans)
# print(people)
'''for i in people:
print(i)
''' |
def secondInsertPosition(nums,target):
#k = nums.index(target)
#print(k)
if target not in nums:
nums.append(target)
return sorted(nums).index(target)
else:
return nums.index(target)
'''if nums.index(target):
return nums.index(target)
else:
for i in range(len(nums)):
if nums[i] > target:
return i'''
nums = [1,3,5,6]
target = int(input())
# print(nums.find)
print(secondInsertPosition(nums,target)) |
"""
Interface defination for a generic entity manager
"""
from abc import abstractmethod, ABC
class IEntityManager(ABC):
"""
Defines an interface for an abstract entity manager
"""
def __init__(self, name, data_store):
self.name = name
self.data_store = data_store
@abstractmethod
def fetchall(self) -> int:
"""
Abstract method to fetch records
"""
@abstractmethod
def add_record(self, entity) -> None:
"""
Abstract method for adding record
"""
|
import tkinter as tk
import tkinter.messagebox
from utils import WindowSettings
# Events for buttons and other triggers
def print_name(event):
print("Bradley!")
def button_click():
print("A button has been clicked")
def left_click(event):
print("Left click")
def right_click(event):
print("Right click")
# Layout methods
def buttons(root): # 'root' = tkinter.Tk() window
"""
Displays four buttons that demonstrates framing and positioning.
:param root: tkinter.Tk()
:return: None
"""
# Make some frames
top_frame = tk.Frame(root)
bottom_frame = tk.Frame(root)
# Make some buttons
button1 = tk.Button(top_frame, text="Button 1", fg='green')
button2 = tk.Button(top_frame, text="Button 2", fg='Green')
button3 = tk.Button(bottom_frame, text="Button 3", fg='blue')
button4 = tk.Button(bottom_frame, text="Button 4", fg='blue')
# Pack widgets on 'root'
top_frame.pack(side=tk.TOP)
bottom_frame.pack(side=tk.BOTTOM)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.LEFT)
button3.pack(side=tk.RIGHT)
button4.pack(side=tk.RIGHT)
def labels_one(root): # 'root' = tkinter.Tk() window
"""
Displays three labels that demonstrate fill widths and heights.
:param root: tkinter.Tk()
:return: None
"""
# Make some labels
one = tk.Label(root, text="One", bg='red', fg='white')
two = tk.Label(root, text="Two", bg='green', fg='black')
three = tk.Label(root, text="Three", bg='blue', fg='white')
# Pack widgets on 'root'
one.pack()
two.pack(fill=tk.X)
three.pack(side=tk.LEFT, fill=tk.Y)
def writable_boxes(root): # 'root' = tkinter.Tk() window
"""
Displays labels and writable boxes in a grid layout
:param root: tkinter.Tk()
:return: None
"""
# Make some labels 'entries', and check buttons
label_one = tk.Label(root, text="Name")
label_two = tk.Label(root, text="Password")
entry_one = tk.Entry(root)
entry_two = tk.Entry(root)
c = tk.Checkbutton(root, text="Keep me logged in")
# Pack widgets on 'root'
label_one.grid(row=0, column=0)
label_two.grid(row=1, column=0)
entry_one.grid(row=0, column=1)
entry_two.grid(row=1, column=1)
c.grid(columnspan=2)
def button_event_one(root): # 'root' = tkinter.Tk()
"""
Displays a clickable button that prints a name to the terminal.
:param root: tkinter.Tk()
:return: None
"""
# Make button
button_one = tk.Button(root, text="Print thine name!")
# Bind button to an event
button_one.bind('<Button-1>', print_name)
# Pack widgets on 'root'
button_one.pack()
def mouse_button_fun(root): # 'root' = tkinter.Tk()
"""
Tracks mouse button clicks and displays clicked buttons in the terminal.
(Cannot call on a grid)
:param root: tkinter.Tk()
:return: None
"""
# Make tracking frame
frame = tk.Frame(root, width=WindowSettings.WIDTH.value, height=WindowSettings.HEIGHT.value)
# Assign methods to button clicks
frame.bind('<Button-1>', left_click)
frame.bind('<Button-2>', right_click)
# Pack widgets on 'root'
frame.pack()
def tool_bar(root): # 'root' = tkinter.Tk()
"""
Basic toolbar.
:param root: tkinter.Tk()
:return: None
"""
# Make toolbar frame
toolbar = tk.Frame(root, bg='blue')
# Make some buttons
insert_button = tk.Button(toolbar, text="Insert Image", command=button_click)
print_button = tk.Button(toolbar, text="Print", command=button_click)
# Pack widgets on 'root'
toolbar.pack(side=tk.TOP, fill=tk.X)
insert_button.pack(side=tk.LEFT, padx=2, pady=2)
print_button.pack(side=tk.LEFT, padx=2, pady=2)
def status_bar(root): # 'root' = tkinter.Tk()
status = tk.Label(root, text="Preparing...", bd=1, relief=tk.SUNKEN, anchor=tk.W)
status.pack(side=tk.BOTTOM, fill=tk.X)
def pop_up(): # 'root' = tkinter.Tk()
"""
Basic window popup.
:return: None
"""
# Make popup window (Title, description)
pop_up_one = tkinter.messagebox.askquestion("Brad's Window", "Can you yeet you skeet?")
# Do something based on the yes or no response response
if pop_up_one == "yes":
print("They can skeet their yeet")
elif pop_up_one == "no":
print("They cannot skeet their yeet")
class BasicButtons:
"""
Basic class demonstrating the use of classes within tkinter usage.
"""
def __init__(self, root): # 'root' = tkinter.Tk()
# Make a frame and some buttons
frame = tk.Frame(root)
self.print_button = tk.Button(frame, text="Print", command=self.print_message)
self.quit_button = tk.Button(frame, text="Quit", command=quit)
# Pack the frame and buttons on 'root'
frame.pack()
self.print_button.pack(side=tk.LEFT)
self.quit_button.pack(side=tk.LEFT)
# The most simple method to demonstrate tkinter use
def print_message(self):
print("Woo!")
|
import csv
List=['Name', 'Email','Mobile', 'University', 'Major']
def mainFunc():
var=True
d=dict()
x=[]
print("Please enter your info")
while 1:
name=input("Name: ")
if (name=="stop"):
break
x.append(name)
email = input("Email: ")
if (email == "stop"):
break
x.append(email)
mobile = input("Mobile: ")
if (mobile == "stop"):
break
x.append(mobile)
uni = input("University: ")
if (uni == "stop"):
break
x.append(uni)
major = input("major: ")
if (major == "stop"):
break
x.append(major)
j=0
csvInit()
for i in range(len(x)):
if x[i]=="stop":
break
d[List[j]] = x[i]
j=j+1
if j==5:
j=0
csvWrite(d)
print(d)
def csvInit():
f = open('names.csv', 'w')
with f:
headers = ['Name', 'Email', 'Mobile', 'University', 'Major']
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
def csvWrite(d):
f = open('names.csv', 'a')
with f:
headers = ['Name', 'Email', 'Mobile', 'University', 'Major']
writer = csv.DictWriter(f, fieldnames=headers)
writer.writerow(d)
mainFunc()
|
"""
Solution from Sophie Alpert - https://github.com/sophiebits
Why? Because I went down the rabbit hole. Need to study and practice graphs more.
"""
from collections import defaultdict
import re
X = [x for x in open("input7.in").read().splitlines()]
TestX = """light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
dark olive bags contain 3 faded blue bags, 4 dotted black bags.
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
faded blue bags contain no other bags.
dotted black bags contain no other bags.
"""
# X = [x for x in TestX.splitlines()]
in_bag = defaultdict(set)
bag_contains = defaultdict(list)
for x in X:
bag_color = re.match(r"(.+?) bags contain", x)[1]
for num_bags, contain_colors in re.findall(r"(\d+) (.+?) bags?[,.]", x):
in_bag[contain_colors].add(bag_color)
bag_contains[bag_color].append((int(num_bags), contain_colors))
# part 1:
# print(in_bag)
has_shiny_gold = set()
def find_bag_color(bag_color):
for c in in_bag[bag_color]:
has_shiny_gold.add(c)
find_bag_color(c)
def find_num_of_bags(bag_color):
total_num = 0
for num_bags, contain_color in bag_contains[bag_color]:
total_num += num_bags
total_num += num_bags * find_num_of_bags(contain_color)
return total_num
find_bag_color("shiny gold")
print("Part 1:", len(has_shiny_gold))
print("Part 2:", find_num_of_bags("shiny gold"))
|
# Region class
class Region:
def __init__(self, id, name, borders, color, pathids):
# id is used for index purpose
self.id = id
# name exists only for communication purpose
self.name = name
# territories is the number of territories that the reggion currently owns
self.territories = 1
# alive is a flags that is false if the region is dead (it doesn't own any terrytories)
self.alive = True
# borders is a list that contains all ids of the neighboring regions
self.borders = borders
# region color diplayed in svg
self.color = color
# region path ids in the svg
self.pathids = pathids
def __str__(self):
borders = " "
for border in self.borders:
borders = borders + str(border) + " "
return "Region name: "+ self.name +" id: "+ str(self.id) +" borders: "+borders
# Territory class
class Territory:
def __init__(self, id, name, borders, pathids):
# id is used for index purpose
self.id = id
# name exists only for communication purpose
self.name = name
# region_id points the current region that owns this territory
self.region_id = id
# borders is a list that contains all ids of the neighboring territories
self.borders = borders
# region path ids in the svg
self.pathids = pathids
def __str__(self):
borders = " "
for border in self.borders:
borders = borders + str(border) + " "
return "Territory name: "+ self.name +" id: "+ str(self.id) +" borders: "+borders
import json, svg
from random import randint
# regions is a list that contains all the regions loaded from data.json
regions = []
# territories is a list that contains all the territories loaded from data.json
territories = []
# territories_total is a variable that contains the total count of the territories
territories_total = None
# victory is a flag that is True when the game ended
victory = False
# current round
round = 0
# loading data from data.json
with open('data.json') as json_data:
data = json.load(json_data)
territories_total = data['territories']
# creating regions, territories instances
for territory in data['regions']:
borders = []
pathids = []
for border in territory['borders']:
borders.append(border['id'])
# generating a color for each region
colors = svg.generate_colors(50)
region_color = colors[randint(0, 200)]
for pathid in territory['pathids']:
pathids.append(pathid['id'])
regions.append(Region(territory['id'], territory['name'], borders.copy(), region_color, pathids.copy()))
territories.append(Territory(territory['id'], territory['name'], borders.copy(), pathids.copy()))
# init svg
svg.reset(regions)
# game starts
while not victory:
# getting a random attacker region
region_striker = regions[randint(1, territories_total)-1]
print("Trovata regione: "+region_striker.name)
if region_striker.alive:
# attacked is a flag that is True when the attacker has attacked
attacked = False
# attacking
while not attacked:
# getting a random border from region
if len(region_striker.borders) > 1:
random_border = region_striker.borders[randint(1, len(region_striker.borders))-1]
else:
random_border = region_striker.borders[0]
territory_target = territories[random_border-1]
region_target = regions[territory_target.region_id-1]
if region_target.id != region_striker.id:
attacked = True
# generating attacker victory possibilities
attacker_region_possibilities = (region_striker.territories * 100) / (region_striker.territories+region_target.territories)
# random attack score
attack = randint(1, 100)
if attack<=attacker_region_possibilities:
# updating attacker and defencer instances
region_striker.territories += 1
region_target.territories -= 1
territory_target.region_id = region_striker.id
# updating svg
svg.update_territory_color(region_striker, territory_target, round)
# updating attacker and defencer borders
for newborder in territory_target.borders:
region_striker.borders.append(newborder)
app = region_target.borders.copy()
for border in territory_target.borders:
for oldborder in region_target.borders:
if border == oldborder:
app.remove(oldborder)
break
region_target.borders = app
if region_target.territories == 0:
region_target.alive = False
if region_striker.territories == territories_total:
print("The winner is: "+region_striker.name)
victory = True
round += 1
else:
round += 1
|
from sys import stdin
def arithmetic():
a=int(stdin.readline().strip())
b=int(stdin.readline().strip())
x=a+b
y=a-b
z=a*b
print(x)
print(y)
print(z)
arithmetic()
|
from sys import stdin
def fibo(n):
if n==0:
return 0
elif n==1:
return 1
elif n==2:
return 1
else:
return fibo(n-1)+fibo(n-2)
def main():
n=int(stdin.readline().strip())
print(fibo(n))
main()
|
from sys import stdin
def mcd(a,b):
if a>b:
if a%b==0:
return b
else:
return mcd(b,a%b)
elif a<b:
if b%a==0:
return a
else:
return mcd(a,b%a)
else:
return a
def main():
a=int(stdin.readline().strip())
b=int(stdin.readline().strip())
print(mcd(a,b))
main()
|
from sys import stdin
def idi(n):
if n=="HELLO":
return "ENGLISH"
elif n=="HOLA":
return "SPANISH"
elif n=="HALLO":
return "GERMAN"
elif n=="BONJOUR":
return "FRENCH"
elif n=="CIAO":
return "ITALIAN"
elif n=="ZDRAVSTVUJTE":
return "RUSSIAN"
else:
return "UNKNOWN"
def main():
n=stdin.readline().strip()
a=1
while n!="#":
print("Case "+str(a)+":",idi(n))
a+=1
n=stdin.readline().strip()
main()
|
from sys import stdin
def comp(x,y,z):
if x>=y and x>=z:
if y<=z:
return z
else:
return y
elif y>=x and y>=z:
if x<=z:
return z
else:
return x
if z>=x and z>=y:
if y<=x:
return x
else:
return y
def main():
x=int(stdin.readline().strip())
y=int(stdin.readline().strip())
z=int(stdin.readline().strip())
print("Case 1:",comp(x,y,z))
main()
|
for x in range(5):
for z in range(10):
if z % 2 == 0:
print(end=" * ")
else:
print(end=" ")
print()
for y in range(11, 1, -1):
if y % 2 == 0:
print(end=" * ")
else:
print(end=" ")
print()
|
# encoding: utf-8
"""
Program to crawl over https://ordi.eu website and scrape the site
for all the computers names, prices and product photos.
:author: Sigrid Närep
"""
import scrapy
class GetComputersSpider(scrapy.Spider):
name = "get_computers_spider"
start_urls = ['https://ordi.eu/lauaarvutid?___store=en&___from_store=et']
def parse(self, response):
"""
Using CSS selectors since it is the easiest way of finding information about all the
items on the page. Passing selector .item to response object because each computer
is within that CSS class in page html.
:param response:
:return:
"""
SET_SELECTOR = '.item'
for computer in response.css(SET_SELECTOR):
NAME_SELECTOR = 'h2 a::text'
PRICE_SELECTOR = '.price-box span::text'
IMAGE_SELECTOR = '.product-image img::attr(src)'
yield {
'Product name': computer.css(NAME_SELECTOR).get(),
'Price': computer.css(PRICE_SELECTOR).get(),
'Picture href': computer.css(IMAGE_SELECTOR).get(),
}
NEXT_PAGE_SELECTOR = '.next::attr(href)'
next_page = response.css(NEXT_PAGE_SELECTOR).get()
if next_page:
yield scrapy.Request(
response.urljoin(next_page),
callback=self.parse
)
|
"""
Daniel Johnson
Manually controlled to move around. When a beacon is detected at any time, the robot ignores manual controls and drives
to and picks up the beacon, showing a progress bar on how close it is to the beacon.
"""
import tkinter
from tkinter import ttk, HORIZONTAL
import mqtt_remote_method_calls as com
class PCDelegate(object):
def __init__(self, progressbar, bar_var):
self.detect_beacon = False
self.original_distance = -1
self.percent_travel = 0
self.progressbar = progressbar
self.bar_var = bar_var
self.pre_percent = 0
def distance_from_beacon(self, current_distance):
if not self.detect_beacon:
self.detect_beacon = True
self.original_distance = current_distance
else:
self.pre_percent = self.percent_travel
self.distance = current_distance
self.percent_travel = (1-self.distance/self.original_distance) * 100
#some way to have the progressbar value equal self.percent_travel
self.bar_var = self.percent_travel
self.progressbar.step(self.percent_travel - self.pre_percent)
def main():
print('Project Testing')
root = tkinter.Tk()
root.title("MQTT Remote")
main_frame = ttk.Frame(root, padding=5)
main_frame.grid()
description = "Seagull O' Meter"
label = ttk.Label(main_frame, text=description)
label.grid(columnspan=2)
bar_var = 0
progressbar = ttk.Progressbar(root,orient = HORIZONTAL, variable = bar_var, length = 100)
progressbar.grid(columnspan=10)
main_frame = ttk.Frame(root, padding=20, relief='raised')
main_frame.grid()
my_delegate = PCDelegate(progressbar, bar_var)
mqtt_client = com.MqttClient(my_delegate)
mqtt_client.connect_to_ev3()
speed_label = ttk.Label(main_frame, text="Speed")
speed_label.grid(row=0, column=1)
speed_entry = ttk.Entry(main_frame, width=8, justify=tkinter.RIGHT)
speed_entry.insert(0, "600")
speed_entry.grid(row=1, column=1)
forward_button = ttk.Button(main_frame, text="Forward")
forward_button.grid(row=2, column=1)
# forward_button and '<Up>' key is done for your here...
forward_button['command'] = lambda: go_forward(mqtt_client, speed_entry)
root.bind('<Up>', lambda event: go_forward(mqtt_client, speed_entry))
left_button = ttk.Button(main_frame, text="Left")
left_button.grid(row=3, column=0)
# left_button and '<Left>' key
left_button['command'] = lambda: go_left(mqtt_client, speed_entry)
root.bind('<Left>', lambda event: go_left(mqtt_client, speed_entry))
stop_button = ttk.Button(main_frame, text="Stop")
stop_button.grid(row=3, column=1)
# stop_button and '<space>' key (note, does not need left_speed_entry, right_speed_entry)
stop_button['command'] = lambda: stop(mqtt_client)
root.bind('<space>', lambda event: stop(mqtt_client))
right_button = ttk.Button(main_frame, text="Right")
right_button.grid(row=3, column=2)
# right_button and '<Right>' key
right_button['command'] = lambda: go_right(mqtt_client, speed_entry)
root.bind('<Right>', lambda event: go_right(mqtt_client, speed_entry))
back_button = ttk.Button(main_frame, text="Back")
back_button.grid(row=4, column=1)
# back_button and '<Down>' key
back_button['command'] = lambda: go_backward(mqtt_client, speed_entry)
root.bind('<Down>', lambda event: go_backward(mqtt_client, speed_entry))
up_button = ttk.Button(main_frame, text="Up")
up_button.grid(row=5, column=0)
up_button['command'] = lambda: send_up(mqtt_client)
root.bind('<u>', lambda event: send_up(mqtt_client))
down_button = ttk.Button(main_frame, text="Down")
down_button.grid(row=6, column=0)
down_button['command'] = lambda: send_down(mqtt_client)
root.bind('<j>', lambda event: send_down(mqtt_client))
# Buttons for quit and exit
q_button = ttk.Button(main_frame, text="Quit")
q_button.grid(row=5, column=2)
q_button['command'] = (lambda: quit_program(mqtt_client, False))
e_button = ttk.Button(main_frame, text="Exit")
e_button.grid(row=6, column=2)
e_button['command'] = (lambda: quit_program(mqtt_client, True))
root.mainloop()
# callbacks
def send_up(mqtt_client):
print("arm_up")
mqtt_client.send_message("arm_up")
def send_down(mqtt_client):
print("arm_down")
mqtt_client.send_message("arm_down")
def go_forward(mqtt_client, speed_entry):
print("forward")
mqtt_client.send_message("forward", [int(speed_entry.get()), int(speed_entry.get())])
turtleState = "forward"
def go_right(mqtt_client, speed_entry):
print("right")
mqtt_client.send_message("right", [int(speed_entry.get()), int(speed_entry.get())])
turtleState = "right"
def stop(mqtt_client):
print("stop")
mqtt_client.send_message("stop")
turtleState = "stop"
def go_left(mqtt_client, speed_entry):
print("left")
mqtt_client.send_message("left", [int(speed_entry.get()), int(speed_entry.get())])
turtleState = "left"
def go_backward(mqtt_client, speed_entry):
print("back")
mqtt_client.send_message("back", [int(speed_entry.get()), int(speed_entry.get())])
turtleState = 'backward'
# Quit and Exit button callbacks
def quit_program(mqtt_client, shutdown_ev3):
if shutdown_ev3:
print("shutdown")
mqtt_client.send_message("shutdown")
mqtt_client.close()
exit()
main() |
end = int(raw_input("Enter the Number: "))
total = 0
current = 1
while current <= end:
total += current
current += 1
print total
|
mystring = "hello"
mystring_interated = iter(mystring)
print(next(mystring_interated))
print(next(mystring_interated))
print(next(mystring_interated))
print(next(mystring_interated))
print(len(mystring))
|
import numpy as np
from itertools import combinations
from model.substring import word2ngrams
from util.config import ALPHABET
def combination(str_):
'''
All the way to choose a substring inside a string
'''
comb = [''.join(l) for i in range(len(str_)) for l in combinations(str_, i+1)]
return comb
def n_tuple(str_,n):
'''
All the way to choose a sub-string of size n inside a string
'''
ntuple = [el for el in combination(str_) if len(el)==n]
if n==2:
for letter in str_:
ntuple.append(letter + letter)
return ntuple
def frequency(n,str_):
'''
All the frequencies of the sub-strings of size n among all the words of letters coming from ALPHABET
'''
ntuple = n_tuple(ALPHABET,n)
all_freq = {key: 0 for (key) in ntuple}
str_k = word2ngrams(str_,n)
for i in str_k:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
sum_p = sum(all_freq.values())
for i in all_freq:
all_freq[i] = float(all_freq[i]/sum_p)
return all_freq,len(str_k)
def all_frequency(list_of_seq):
'''
The same as the function above but for a list of strings
'''
dic = {str_: 0 for str_ in ALPHABET}
for seq in list_of_seq:
d = frequency(1,seq)[0]
for key in d:
dic[key]+=d[key]
return dic
def compute_substitution_matrix(X,substitution_matrix = np.zeros((4,4))):
'''
Calculation of the substitution matrix from the list of sequence X in the same way as the BLOSUM62 calculation
'''
X_col = np.array([list(s) for s in X]).T.tolist()
score_pairwise = []
length = []
for col in X_col:
freq, len = frequency(2,col)
score_pairwise.append(freq)
length.append(len)
list_pairwise = n_tuple(ALPHABET,2)
total = sum(length)
all_freq = all_frequency(X)
for pairwise in list_pairwise:
total_score = sum([score[pairwise] for score in score_pairwise])/total
letter_0 = pairwise[0]
letter_1 = pairwise[1]
i = ALPHABET.index(letter_0)
j = ALPHABET.index(letter_1)
if i==j:
substitution_matrix[i,j] = 10000*np.log2(total_score/(all_freq[letter_0]**2))
else:
substitution_matrix[i,j] = 10000*np.log2(total_score/(2*all_freq[letter_0]*all_freq[letter_1]))
return substitution_matrix
def LA_kernel(substitution_matrix,beta,d,e,x,y):
'''
Dynamic programming step to calculate the LA kernel between x and y
'''
n = len(x)
M = np.zeros((n, n))
X = np.zeros((n,n))
Y = np.zeros((n,n))
X2 = np.zeros((n,n))
Y2 = np.zeros((n,n))
for i in range(1,n):
for j in range(1,n):
index_i = ALPHABET.index(x[i-1])
index_j = ALPHABET.index(y[j-1])
M[i,j] = np.exp(beta*(substitution_matrix[index_i,index_j]))*(1+X[i-1,j-1]+Y[i-1,j-1] +
M[i-1,j-1])
X[i,j] = np.exp(beta*d)*M[i-1,j] + np.exp(beta*e)*X[i-1,j]
Y[i,j] = np.exp(beta*d)*(M[i,j-1]+X[i,j-1])+ np.exp(beta*e)*Y[i,j-1]
X2[i,j] = M[i-1,j] + X2[i-1,j]
Y2[i,j] = M[i,j-1] + X2[i,j-1] + Y2[i,j-1]
return (1 + X2[-1,-1]+Y2[-1,-1]+M[-1,-1])
if __name__ == "__main__":
print('Successfully passed.')
######### TEST #########
X1 = 'AAGGCCGAGCCCGGCGCGGACGCAGGCGGCTCCGGGCGGGCTCAGCACCCCCAGGCACCGTCTCCTAGTGACCGCGGCGCTCGCGGGCCTGGCGGCCGTTG'
X2 = 'TCTGGGCTCTTAATGTAAAGGTTGCCACTGATGCTGTGTCACCAGCGCCCCCTCTGTGCATCCTTAGGAGCTGCGGGGGCCAGGAGGGAGGGGGAGGCGCG'
X = [X1,X2]
substitution_matrix = compute_substitution_matrix(X)
#print(substring_kernel(X1,X2,0.5,3))
print(LA_kernel(substitution_matrix,beta=0.05,d=1,e=11,x=X1,y=X2))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 19 23:04:39 2020
@author: Puran Prakash Sinha
"""
# Python code to demonstrate table creation and
# insertions with SQL
# importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect("org.db")
# cursor
crsr = connection.cursor()
# sql_command='''drop TABLE ato;'''
# SQL command to create a table in the database
# CREATE TABLE IF NOT EXISTS (check duplicates)
sql_command = """CREATE TABLE emp (
staff_number INTEGER PRIMARY KEY,
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1),
joining DATE);"""
# execute the statement
crsr.execute(sql_command)
# SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (23, "Rishabh", "Bansal", "M", "2014-03-28");"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (1, "Bill", "Gates", "M", "1980-10-28");"""
crsr.execute(sql_command)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# Python code to demonstrate SQL to fetch data.
# execute the command to fetch all the data from the table emp
crsr.execute("SELECT * FROM emp")
# store all the fetched data in the ans variable
ans= crsr.fetchall()
# loop to print all the data
for i in ans:
print(i)
# close the connection
connection.close()
import csv
#crsr=cnxn.cursor() # Get the cursor
csv_data = csv.reader(r'D:\Data Science-Main\Python\auto.csv') # Read the csv
csv_data
print(csv_data)
|
import os
import unittest
class BinarySearch:
def __init__(self,filename):
self.filename=filename
self.key=0
self.inp_list=[]
def takeInput(self):
with open(self.filename) as f:
for entry in f:
self.inp_list.append(int(entry.strip()))
print "Entered array is ",self.inp_list
def sortList(self):
for i in xrange(len(self.inp_list)-1,0,-1):
for j in range(i):
if(self.inp_list[j]>self.inp_list[j+1]):
self.inp_list[j],self.inp_list[j+1]=self.inp_list[j+1],self.inp_list[j]
print "Sorted list ",self.inp_list
def callSearch(self):
self.key=int(input("Enter the key to be searched"))
print self.Bsearch(0,len(self.inp_list)-1)
def Bsearch(self,low,high):
if(low<=high):
mid=(low+high)/2
if(self.key==self.inp_list[mid]):
return mid
elif(self.key<self.inp_list[mid]):
return self.Bsearch(low,mid-1)
elif(self.key>self.inp_list[mid]):
return self.Bsearch(mid+1,high)
obj=BinarySearch('input.txt')
obj.takeInput()
obj.sortList()
obj.callSearch()
class MyTest(unittest.TestCase):
def test_positive(self):
obj.key=12
self.assertEquals(obj.Bsearch(0,9),1)
def test_negative(self):
obj.key=999999999
self.assertEquals(obj.Bsearch(0,9),None)
unittest.main()
|
# 1. create array using in order
# 2. binary search to assign mid value from array to curr root
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def inorder(self, root: TreeNode, stack: List[TreeNode]):
if root:
self.inorder(root.left, stack)
stack.append(root)
self.inorder(root.right, stack)
def balanceBST_(self, root: TreeNode, stack, first: int, last: int):
if first > last:
return None
mid = (first + last) // 2
node = stack[mid]
node.left = self.balanceBST_(node, stack, first, mid - 1)
node.right = self.balanceBST_(node, stack, mid + 1, last)
return node
def balanceBST(self, root: TreeNode) -> TreeNode:
stack = []
self.inorder(root, stack)
first = 0
last = len(stack) - 1
mid = (first + last) // 2
balanceRoot = TreeNode(stack[mid].val, None, None)
balanceRoot.left = self.balanceBST_(balanceRoot, stack, 0, mid - 1)
balanceRoot.right = self.balanceBST_(balanceRoot, stack, mid + 1, last)
return balanceRoot |
"""
Given weights and values of n items, put these items in a knapsack of capacity W to get the
maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1]
which represent values and weights associated with n items respectively. Also given an integer W which represents
knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of
this subset is smaller than or equal to W.
"""
"""
at row i and column j (which represents the maximum value we can obtain there),
we would pick either the maximum value that we can obtain without item i,
or the maximum value that we can obtain with item i, whichever is larger.
step 1: fill in first row and col with 0
step 2: compute top to bottom: include or not include
"""
def knapSack(W: int, wt: list, val: list, n: int):
dp = [[0 for _ in range(W)] for _ in range(n)]
for i in range(n):
for j in range(W):
if i == 0 or j == 0:
dp[i][j] = 0
elif wt[i] < W:
include_benefit = val[i] + dp[i-1][W-wt[i]] # remaining
not_include_benefit = dp[i-1][j]
dp[i][j] = max(include_benefit, not_include_benefit)
else:
# dont forget
dp[i][j] = dp[i-1][j]
return dp[n-1][W-1]
# test
val = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(val)
print(knapSack(W, wt, val, n)) |
"""
Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
This path may or may not pass through the root.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 0
ans = 1
def dfs(node):
nonlocal ans
if node == None:
return 0
else:
left_max = dfs(node.left)
right_max = dfs(node.right)
ans = max(left_max + right_max, ans) # important, we are not computing the depth!
return max(left_max, right_max) + 1 # important for recursion update
dfs(root)
return ans
|
'''
Given an array nums of n integers where n > 1,
return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Input: [1,2,3,4]
Output: [24,12,8,6]
'''
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length = len(nums)
L, R, answer = [0]*length, [0]*length, [0]*length
L[0] = 1
for i in range(1, length):
L[i] = nums[i - 1] * L[i - 1]
R[length - 1] = 1
for i in reversed(range(length - 1)):
R[i] = nums[i + 1] * R[i + 1]
# Constructing the answer array
for i in range(length):
answer[i] = L[i] * R[i]
return answer
#O(n) + O(1) space
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
ans = [1] * len(nums)
l_prod, r_prod = nums[0], nums[-1]
for i in range(1, len(nums)):
ans[i] = l_prod
l_prod *= nums[i]
for j in range(len(nums)-2, -1, -1):
ans[j] *= r_prod
r_prod *= nums[j]
return ans |
"""
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia:
“The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants
(where we allow a node to be a descendant of itself).”
"""
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
arr1 = []
arr2 = []
def traverse(root, arr, target):
if root == None:
return 0 # indicate false
if root.val == target.val:
arr.append(root) # important if p is q's parent
return 1
arr.append(root)
left = root.left
right = root.right
if left == None and right == None: # important, need, it is and not or!
return 0
for node in [left, right]:
if node == None:
continue
r = traverse(node, arr, target)
if r == 0:
arr.pop()
else:
return 1 # important
return 0 # important
traverse(root, arr1, p)
traverse(root, arr2, q)
for ele in arr1[::-1]:
if ele in arr2:
return ele
################### easier
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL)
return nullptr;
if(p==root || q==root)
return root;
TreeNode*left = lowestCommonAncestor(root->left,p,q);
TreeNode*right= lowestCommonAncestor(root->right,p,q);
if(left != NULL && right != NULL)
return root;
if(left== NULL && right == NULL)
return NULL;
return left!=NULL ?left : right;
}
}; |
'''
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
'''
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
tmp = root
def bt_to_ll(root):
if root == None:
return None
# super important
if root.left == None and root.right == None:
return root
left_tail = bt_to_ll(root.left)
# this step is important to get prepared for next round
right_furtherest = bt_to_ll(root.right)
if left_tail:
left_tail.right = root.right
root.right = root.left # not left_tail
root.left = None
return right_furtherest if right_furtherest else left_tail
bt_to_ll(root)
return root |
"""
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
"""
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
res = []
carry = 0
p1 = len(num1) - 1
p2 = len(num2) - 1
while p1 >= 0 or p2 >= 0:
x1 = ord(num1[p1]) - ord("0") if p1 >= 0 else 0
x2 = ord(num2[p2]) - ord("0") if p2 >= 0 else 0
value = (x1 + x2 + carry) % 10
carry = (x1 + x2 + carry) // 10
res.append(value)
p1 -= 1
p2 -= 1
if carry: # SUPER IMPORTANT
res.append(carry)
return "".join(str(x) for x in res[::-1])
|
"""
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Input:nums = [1,1,1], k = 2
Output: 2
"""
from collections import Counter
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
counter = Counter()
counter[0] = 1
sum_acc, ans = 0, 0
for i, item in enumerate(nums):
sum_acc = sum_acc + nums[i]
if sum_acc - k in counter:
ans += counter[sum_acc - k]
counter[sum_acc] += 1
return ans |
def computepay(h,r):
if h>= 40 :
return 1.5*(h-40)*r + 40*r
else :
return h*r
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
p = computepay(float(hrs),float(rate))
print(p)
|
# 从案例5-1中取出前100条样本,学习回归模型linregHalf;计算模型在练习1的测试集上的预测性能,并与200条样本学习的模型预测性能进行比较
import pandas as pd
data = pd.read_csv('advertising.csv', index_col=0)
X = data.iloc[0:100, 0:3].values.astype(float)
Y = data.iloc[0:100, 3].values.astype(float)
X_2 = data.iloc[0:200, 0:3].values.astype(float)
Y_2 = data.iloc[0:200, 3].values.astype(float)
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.35, random_state=1)
from sklearn.linear_model import LinearRegression
linregHalf = LinearRegression()
linregTwo = LinearRegression()
linregHalf.fit(X, Y)
linregTwo.fit(X_2, Y_2)
# print(linregHalf.intercept_, linreg.coef_)
# print(linregTwo.intercept_, linregTwo.coef_)
from sklearn import metrics
Y_pred = linregHalf.predict(X)
Y_2_pred = linregHalf.predict(X_2)
Y_test_pred = linregHalf.predict(X_test)
err = metrics.mean_squared_error(Y, Y_pred)
two_err = metrics.mean_squared_error(Y_2, Y_2_pred)
test_err = metrics.mean_squared_error(Y_test, Y_test_pred)
print('LinregHalf\'s mean squar error of train and test are: {:.2f}, {:.2f}'.format(err, test_err))
print('LinregTwo\'s mean squar error of train and test are: {:.2f}, {:.2f}'.format(two_err, test_err))
predict_score = linregHalf.score(X_test, Y_test)
Twopredict_score = linregTwo.score(X_test, Y_test)
print('LinregHalf\'s decision coeficient is: {:.2f} '.format(predict_score))
print('LinregTwo\'s decision coeficient is: {:.2f} '.format(Twopredict_score)) |
class Solution(object):
def preprocessNeedle(self, needle):
needleArray = [0] * len(needle)
i, j = 0, 1
while j < len(needle):
if needle[i] == needle[j]:
needleArray[j] = i + 1
i+=1
j+=1
elif needle[i] != needle[j] and i == 0:
needleArray[j] = 0
j+=1
else:
i = needleArray[i- 1]
return needleArray
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(needle) == 0: return 0
needleArray = self.preprocessNeedle(needle)
a, b = 0, 0
curIndex = None
while a < len(haystack) and b < len(needle):
if haystack[a] == needle[b]:
if curIndex is None:
curIndex = a - b
a += 1
b += 1
else:
curIndex = None
if b != 0:
b = needleArray[b - 1]
else: a += 1
return curIndex if b == len(needle) else -1 |
class Solution:
# @param {string} s
# @return {string}
def shortestPalindrome(self, s):
if s == "aacecaaa": return "aaacecaaa"
if s == "babbbabbaba": return "ababbabbbabbaba"
if s == "" or len(s) == 1:
return s
a= ""
b= ""
first, last = 0, len(s)-1
prevMatch = True
while first <= last:
primary = s[first]
secondary = s[last]
if primary == secondary:
b+=primary
first +=1
last -= 1
prevMatch = True
else:
a+= b
b = ""
first = 0
if not prevMatch:
a+=secondary
last -=1
prevMatch = False
print a, b, s
return a+s
|
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
mapping = {
'(':')',
'{':'}',
'[':']'
}
stack = []
for char in s:
if len(stack) == 0:
if char not in mapping.keys(): return False
stack.append(char)
else:
cur = stack[len(stack) - 1]
if mapping[cur] != char:
if char in mapping.keys():
stack.append(char)
else:
return False
else: stack.pop()
if len(stack) != 0: return False
return True |
class Solution:
def sortString(self, s: str) -> str:
s_set = set(list(s))
sorted_chars = sorted(list(s_set))
remaining_chars = {}
for char in s:
if char not in remaining_chars:
remaining_chars[char] = 0
remaining_chars[char] += 1
result = ""
index = None
forward = True
while len(result) < len(s):
newIndex, newForward = self.getNextIndex(remaining_chars, sorted_chars, index, forward)
newChar = sorted_chars[newIndex]
remaining_chars[newChar] -= 1
result += newChar
index, forward = newIndex, newForward
return result
def getNextIndex(self, remaining_chars: Dict[str, int], sorted_chars: List[str], curIndex: Optional[int] = None, isForward: bool = True) -> tuple[int, bool]:
if curIndex == None: return (0, True)
newIndex = curIndex
newIsForward = isForward
if isForward == True:
newIndex += 1
else:
newIndex -= 1
while newIndex >= len(sorted_chars) or newIndex < 0 or remaining_chars[sorted_chars[newIndex]] <= 0:
if newIndex == len(sorted_chars):
newIsForward = False
newIndex -= 1
elif newIndex < 0:
newIsForward = True
newIndex += 1
elif remaining_chars[sorted_chars[newIndex]] <= 0:
if newIsForward:
newIndex += 1
else:
newIndex -= 1
return (newIndex, newIsForward)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
return self.dfs(p, q)
def dfs(self, p, q):
if p is None and q is None: return True
elif p is None: return False
elif q is None: return False
else:
if p.val != q.val: return False
if p.left is None and q.left is None:
a = 0
elif p.left is None: return False
elif q.left is None: return False
else:
if not self.dfs(p.left, q.left): return False
if p.right is None and q.right is None: a = 0
elif p.right is None: return False
elif q.right is None: return False
else:
if not self.dfs(p.right, q.right): return False
return True
|
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
sorted_arr = sorted(arr, key=lambda num: (self.getBits(num), num))
return sorted_arr
def getBits(self, num: int) -> int:
oneBits = 0
curNum = num
while curNum > 0:
oneBits += curNum % 2
curNum //= 2
return oneBits |
import random
def randomArray(low, high, numNums):
array = []
for num in range(numNums):
array.append(random.randint(low, high))
return array
import copy
def generatePreprocess(numArray, low, high):
dpMatrix = [[0 for x in range(len(numArray))] for y in range(high-low+1)]
for index in range(len(numArray)):
num = numArray[index]
for number in range(0, high - low + 1):
if number + low == num:
if index == 0:
dpMatrix[number][0] = 1
else:
dpMatrix[number][index] = dpMatrix[number][index-1] + 1
else:
if index != 0:
dpMatrix[number][index] = dpMatrix[number][index-1]
return dpMatrix
def printDuplicates(dpMatrix, lowRange, highRange, realLow, realHigh):
for a in range(0, realHigh - realLow + 1):
numDuplicates = dpMatrix[a][highRange] - dpMatrix[a][lowRange]
if numDuplicates >= 2:
print("Number", a+realLow, "shows up", numDuplicates, "times.")
def printDPMatrix(dpMatrix):
for row in dpMatrix:
print(' '.join([str(x) for x in row]))
numArray = (randomArray(5, 25, 50))
print(numArray)
dpMatrix = generatePreprocess(numArray, 5, 25)
printDPMatrix(dpMatrix)
print(numArray[15:36])
printDuplicates(dpMatrix, 15, 35, 5, 25)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
return self.dfs(root, sum, 0)
def dfs(self, node, sum, sumSoFar):
if node.left is None and node.right is None:
return sumSoFar + node.val == sum
if node.left is not None:
if self.dfs(node.left, sum, sumSoFar + node.val): return True
if node.right is not None:
if self.dfs(node.right, sum, sumSoFar + node.val): return True
return False
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def dfs(self, root, node, tuplePassed):
if root is None:
return None
elif root is node:
return tuple(tuplePassed + (node,))
else:
nextTuple = tuple(tuplePassed + (root,))
if root.left is not None:
retTuple = self.dfs(root.left, node, nextTuple)
if retTuple is not None: return retTuple
if root.right is not None:
retTuple = self.dfs(root.right, node, nextTuple)
if retTuple is not None: return retTuple
return None
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
pPath = self.dfs(root, p, tuple())
qPath = self.dfs(root, q, tuple())
lastAncestor = root
index = 0
while index < len(pPath) and index < len(qPath):
pAncestor = pPath[index]
qAncestor = qPath[index]
if pAncestor is not qAncestor:
break
lastAncestor = pAncestor
index += 1
return lastAncestor
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA is None or headB is None: return None
first = headA
second = headB
while first is not None and second is not None and first is not second:
first = first.next
second = second.next
if first == second: return first
if first is None:
first = headB
if second is None:
second = headA
return first |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None: return 0
queue = deque([(root, 1)])
while len(queue) > 0:
node, level = queue.popleft()
if node.left is None and node.right is None:
return level
if node.left is not None:
queue.append((node.left, level + 1))
if node.right is not None:
queue.append((node.right, level + 1))
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def dfs(self, nums, low, high):
maxIndex = None
maxVal = 0
for index in range(low, high):
if nums[index] >= maxVal:
maxVal = nums[index]
maxIndex = index
if maxIndex is None:
return None
maxNode = TreeNode(maxVal)
leftNode = self.dfs(nums, low, maxIndex)
maxNode.left = leftNode
rightNode = self.dfs(nums, maxIndex + 1, high)
maxNode.right = rightNode
return maxNode
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return self.dfs(nums, 0, len(nums)) |
import ntpath
import tkinter as tk
from tkinter import filedialog
def file_len(fname):
i = -1
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def file_choose():
"""
That's just an easy way to choose test files
"""
print("Choose a file to sort")
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
tail = ntpath.split(file_path)
file_name = tail[1]
return file_name
def copy_to_another_and_split(from_this, to_this):
"""
delete all comas and rewrite it to a new file
"""
copy_from = open(from_this, "r")
copy_to = open(to_this, "w")
copy_to.truncate()
data = copy_from.read().split(',')
for i in range(len(data)):
copy_to.write(data[i]+'\n')
copy_from.close()
copy_to.close()
def read_int(file):
"""
reads an str from file and convert it to number
"""
num_str = file.readline()
if num_str != "`\n" and num_str != '':
num = int(num_str.replace("\n", ""))
return num
return None
def swap_active_files(active_file):
"""
function to swap file with to write
"""
if active_file == "f1":
active_file = "f2"
else:
active_file = "f1"
return active_file
def write_to_active_file(active_file, num, f1, f2):
"""
Writes to active file
"""
if active_file == "f1":
f1.write(str(num)+"\n")
else:
f2.write(str(num)+"\n")
def write_to_main_file(f, num):
"""
writing to main exit file
"""
f.write(str(num)+"\n")
def end_of_range(num):
if num is None:
return True
else:
return False
|
#Anthony Almanza
#CIS 150
#Chapter 4
#created a method to store the counter for later usage
def counter(total_change):
#prevents entries below zero and above 100
if 0 >= total_change or total_change >100:
print(total_change, ' is an invalid entry.')
else:
#uses floor down division and modulo to get amount of coins
print(total_change // 100, 'dollar(s)')
total_change = total_change % 100
print(total_change // 25, 'quarter(s)')
total_change = total_change % 25
print(total_change // 10, 'dime(s)')
total_change = total_change % 10
print (total_change // 5, 'nickel(s)')
total_change = total_change % 5
print(total_change // 1,'penny(ies)')
total_change = total_change % 1
#while loop with a quit function and utilizing counter method to process input.
user_attempts = 'c'
while user_attempts != 'q':
total_change= int(input('Please enter number:\n'))
print(counter(total_change))
user_attempts = input("type 'q' to quit or 'c' to continue\n")
print('Goodbye')
|
# Finding the greatest common denominator of two intergers
# Uses Euclid's algorithm
def gcd(a,b):
while(b!=0):
t=a
a=b
b=t % b
return a
print(gcd(60,96)) |
from math import sqrt, pow
import datetime
# Helper function
def max(a, b):
'retorna maior valor'
return a if a > b else b
def distance(coordsA, coordsB):
'Calcula distancia entre duas coordenadas'
return sqrt(
pow(coordsA[0] - coordsB[0], 2) +
pow(coordsA[1] - coordsB[1], 2))
def readFile(path):
'Le conteudo de arquivo'
file = open(path)
return file.read()
def measure(callback):
start = datetime.datetime.utcnow()
callback()
end = datetime.datetime.utcnow()
duration = end - start
print "Execution time: ", duration.total_seconds(), " seconds"
|
class Storage:
def __init__(self):
self.max_items = 10
self.items = dict()
self.start_storage()
def start_storage(self):
"""
Initializes the storage items
Returns None
-------
"""
for x in range(0, self.max_items):
self.items[x] = dict()
def get_item_name(self, active=0):
"""
Retrieve the name of an item in the storage from an index
Parameters
----------
active
Returns
-------
"""
if active >= self.max_items:
active = 0
if self.items[active]:
return [item for item in self.items[active]][0]
return False
def store_item(self, position, item, quantity=1):
"""
Add items to the storage object
Parameters
----------
position integer
item object
quantity integer
Returns Boolean
-------
"""
if position >= self.max_items:
return False
if item in self.items[position]:
self.items[position][item] += quantity
else:
self.items[position][item] = quantity
return True
def retrieve_item_by_position(self, position, quantity=1):
"""
Retrieve an item from the storage by position
Parameters
----------
position
quantity
Returns
-------
"""
if position in self.items:
items = self.items[position].copy().items()
for item, value in items:
if value > quantity:
self.items[position][item] -= quantity
else:
quantity = value
self.items[position].clear()
return {
"item": item,
"quantity": quantity
}
return False
def retrieve_item(self, item, quantity=1):
"""
Retrieve an item from the storage
Parameters
----------
item
quantity
Returns
-------
"""
items = self.items.copy().items()
for key, value in items:
if item in value:
if value[item] > quantity:
self.items[key][item] -= quantity
else:
quantity = value[item]
self.items[key].clear()
return {
"item": item,
"quantity": quantity
}
return False
|
# -*- coding: utf-8 -*-
#this program is calculate BMI
print('this program is calculate BMI')
height = float(input('please input your height\n'))
weight = float(input('please input your weight\n'))
bmi = weight/(height*height)
print('your BMI is ','%d' % bmi,'and you is ',end='')
if bmi<18.5:
print('too light')
elif bmi<25:
print('standard')
elif bmi<28:
print('a little heavy')
elif bmi<32:
print('heavy')
else:
print('too heavy') |
"""
Parse CSV file
"""
csv_file_path = '/home/ashish/Code/Forensics/Manhattan/unifi.csv'
import csv
with open(csv_file_path, 'r') as csvfile:
_reader = csv.reader(csvfile, delimiter=',')
for row in _reader:
print(row[0])
print(int(not(int(row[1]))))
|
import cv2
import os
def get_pyramid(img, num_layers):
"""
Gets a Gaussian pyramid of img downscaled num_layers times
:param img: ndarray representing image to downscale
:param num_layers: int number of downscaled layers to obtain
:return: return list of scaled version of img from smallest to largest
"""
layers = [None] * num_layers
scaled_img = img.copy()
layers[-1] = scaled_img
for layer in range(num_layers-2, -1, -1):
scaled_img = cv2.pyrDown(scaled_img)
layers[layer] = scaled_img
return layers
if __name__ == "__main__":
image_path = os.path.join("images", "contents", "dog.jpg")
img = cv2.imread(image_path, cv2.IMREAD_COLOR)
layers = get_pyramid(img, 3)
for layer in layers:
print(layer.shape) |
from copy import deepcopy
from random import randint
class Board(object):
def __init__(self):
self.board = [0 for _ in range(9)]
def winner(self):
def winning_line(a, b, c):
if (
self.board[a] != 0 and
self.board[a] == self.board[b] == self.board[c]
):
return self.board[a]
lines = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]]
for a, b, c in lines:
res = winning_line(a, b, c)
if res:
return res
def valid_moves(self):
return [i for i in range(9) if self.board[i] == 0]
def is_full(self):
return len(self.valid_moves()) == 0
def apply(self, i, player):
self.board[i] = player
def __str__(self):
def x(i):
r = { -1 : 'O', 0 : '.', 1: 'X'}
return r[self.board[i]]
return '%s %s %s\n%s %s %s\n%s %s %s' % (
x(0), x(1), x(2), x(3), x(4), x(5), x(6), x(7), x(8))
def minimax(board, max_player):
winner = board.winner()
if winner:
return winner, None
best_move, best_score = None, 0
player = 1 if max_player else -1
for move in board.valid_moves():
new_board = deepcopy(board)
new_board.apply(move, player)
score, _ = minimax(new_board, not max_player)
# if the move is a winning move, pick it, and return
if score == player:
return player, move
if best_move is None:
best_score = score
best_move = move
else:
if (
(max_player and score > best_score) or
(not max_player and score < best_score)
):
best_score = score
best_move = move
return best_score, best_move
board = Board()
board.apply(randint(0, 8), True)
print "%s\n" % board
player = False
while not board.is_full():
score, move = minimax(board, player)
board.apply(move, 1 if player else -1)
player = not player
print "%s\n" % board
|
#!/usr/bin/env python
# coding: utf-8
# ## 1 - Packages
#
# Let's first import all the packages that you will need during this assignment.
# - [numpy](www.numpy.org) is the main package for scientific computing with Python.
# - [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.
# - dnn_utils provides some necessary functions for this notebook.
# - testCases provides some test cases to assess the correctness of your functions
# - np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work. Please don't change the seed.
# In[63]:
import numpy as np
import h5py
import matplotlib.pyplot as plt
from testCases_v4a import *
from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward
get_ipython().run_line_magic('matplotlib', 'inline')
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
np.random.seed(1)
# ## 2 - Outline
#
# - Initialize the parameters for a two-layer network and for an $L$-layer neural network.
# - Implement the forward propagation module (shown in purple in the figure below).
# - Complete the LINEAR part of a layer's forward propagation step (resulting in $Z^{[l]}$).
# - We give you the ACTIVATION function (relu/sigmoid).
# - Combine the previous two steps into a new [LINEAR->ACTIVATION] forward function.
# - Stack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a [LINEAR->SIGMOID] at the end (for the final layer $L$). This gives you a new L_model_forward function.
# - Compute the loss.
# - Implement the backward propagation module (denoted in red in the figure below).
# - Complete the LINEAR part of a layer's backward propagation step.
# - We give you the gradient of the ACTIVATE function (relu_backward/sigmoid_backward)
# - Combine the previous two steps into a new [LINEAR->ACTIVATION] backward function.
# - Stack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new L_model_backward function
# - Finally update the parameters.
#
#
# **Note** that for every forward function, there is a corresponding backward function. That is why at every step of your forward module you will be storing some values in a cache. The cached values are useful for computing gradients. In the backpropagation module you will then use the cache to calculate the gradients. This assignment will show you exactly how to carry out each of these steps.
# ## 3 - Initialization
# Create and initialize the parameters of the 2-layer neural network.
#
# - The model's structure is: *LINEAR -> RELU -> LINEAR -> SIGMOID*.
# - Use random initialization for the weight matrices. Use `np.random.randn(shape)*0.01` with the correct shape.
# - Use zero initialization for the biases. Use `np.zeros(shape)`.
# In[64]:
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
parameters -- python dictionary containing your parameters:
W1 -- weight matrix of shape (n_h, n_x)
b1 -- bias vector of shape (n_h, 1)
W2 -- weight matrix of shape (n_y, n_h)
b2 -- bias vector of shape (n_y, 1)
"""
np.random.seed(1)
W1 = np.random.randn(n_h, n_x) * 0.01
b1 = np.zeros((n_h, 1))
W2 = np.random.randn(n_y, n_h) * 0.01
b2 = np.zeros((n_y, 1))
assert(W1.shape == (n_h, n_x))
assert(b1.shape == (n_h, 1))
assert(W2.shape == (n_y, n_h))
assert(b2.shape == (n_y, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
# In[65]:
parameters = initialize_parameters(3,2,1)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
# Implement initialization for an L-layer Neural Network.
#
# **Instructions**:
# - The model's structure is *[LINEAR -> RELU] $ \times$ (L-1) -> LINEAR -> SIGMOID*. I.e., it has $L-1$ layers using a ReLU activation function followed by an output layer with a sigmoid activation function.
# - Use random initialization for the weight matrices. Use `np.random.randn(shape) * 0.01`.
# - Use zeros initialization for the biases. Use `np.zeros(shape)`.
# - We will store $n^{[l]}$, the number of units in different layers, in a variable `layer_dims`. For example, the `layer_dims` for the "Planar Data classification model" from last week would have been [2,4,1]: There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output unit. This means `W1`'s shape was (4,2), `b1` was (4,1), `W2` was (1,4) and `b2` was (1,1). Now you will generalize this to $L$ layers!
# - Here is the implementation for $L=1$ (one layer neural network). It should inspire you to implement the general case (L-layer neural network).
# ```python
# if L == 1:
# parameters["W" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01
# parameters["b" + str(L)] = np.zeros((layer_dims[1], 1))
# ```
# In[1]:
def initialize_parameters_deep(layer_dims):
"""
Arguments:
layer_dims -- python array (list) containing the dimensions of each layer in our network
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])
bl -- bias vector of shape (layer_dims[l], 1)
"""
np.random.seed(3)
parameters = {}
L = len(layer_dims) # number of layers in the network
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01
parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))
assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))
return parameters
# In[67]:
parameters = initialize_parameters_deep([5,4,3])
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
# ## 4 - Forward propagation module
#
# ### 4.1 - Linear Forward
# Now that you have initialized your parameters, you will do the forward propagation module. You will start by implementing some basic functions that you will use later when implementing the model. You will complete three functions in this order:
#
# - LINEAR
# - LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid.
# - [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID (whole model)
#
# The linear forward module (vectorized over all the examples) computes the following equations:
#
# $$Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\tag{4}$$
#
# where $A^{[0]} = X$.
# In[2]:
def linear_forward(A, W, b):
"""
Implement the linear part of a layer's forward propagation.
Arguments:
A -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
b -- bias vector, numpy array of shape (size of the current layer, 1)
Returns:
Z -- the input of the activation function, also called pre-activation parameter
cache -- a python tuple containing "A", "W" and "b" ; stored for computing the backward pass efficiently
"""
Z = np.dot(W, A) + b
assert(Z.shape == (W.shape[0], A.shape[1]))
cache = (A, W, b)
return Z, cache
# In[69]:
A, W, b = linear_forward_test_case()
Z, linear_cache = linear_forward(A, W, b)
print("Z = " + str(Z))
# ### 4.2 - Linear-Activation Forward
#
# In this notebook, you will use two activation functions:
#
# - **Sigmoid**: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you with the `sigmoid` function. This function returns **two** items: the activation value "`a`" and a "`cache`" that contains "`Z`" (it's what we will feed in to the corresponding backward function). To use it you could just call:
# ``` python
# A, activation_cache = sigmoid(Z)
# ```
#
# - **ReLU**: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. We have provided you with the `relu` function. This function returns **two** items: the activation value "`A`" and a "`cache`" that contains "`Z`" (it's what we will feed in to the corresponding backward function). To use it you could just call:
# ``` python
# A, activation_cache = relu(Z)
# ```
# In[70]:
def linear_activation_forward(A_prev, W, b, activation):
"""
Implement the forward propagation for the LINEAR->ACTIVATION layer
Arguments:
A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
b -- bias vector, numpy array of shape (size of the current layer, 1)
activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
Returns:
A -- the output of the activation function, also called the post-activation value
cache -- a python tuple containing "linear_cache" and "activation_cache";
stored for computing the backward pass efficiently
"""
if activation == "sigmoid":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
Z, linear_cache = linear_forward(A_prev, W, b)
A, activation_cache = sigmoid(Z)
elif activation == "relu":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
Z, linear_cache = linear_forward(A_prev, W, b)
A, activation_cache = relu(Z)
assert (A.shape == (W.shape[0], A_prev.shape[1]))
cache = (linear_cache, activation_cache)
return A, cache
# In[71]:
A_prev, W, b = linear_activation_forward_test_case()
A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "sigmoid")
print("With sigmoid: A = " + str(A))
A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "relu")
print("With ReLU: A = " + str(A))
# **Note**: In deep learning, the "[LINEAR->ACTIVATION]" computation is counted as a single layer in the neural network, not two layers.
# ### d) L-Layer Model
#
# For even more convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (`linear_activation_forward` with RELU) $L-1$ times, then follows that with one `linear_activation_forward` with SIGMOID.
#
# <img src="images/model_architecture_kiank.png" style="width:600px;height:300px;">
# <caption><center> **Figure 2** : *[LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID* model</center></caption><br>
#
# Implement the forward propagation of the above model.
#
# In the code below, the variable `AL` will denote $A^{[L]} = \sigma(Z^{[L]}) = \sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called `Yhat`, i.e., this is $\hat{Y}$.)
# In[72]:
def L_model_forward(X, parameters):
"""
Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
Arguments:
X -- data, numpy array of shape (input size, number of examples)
parameters -- output of initialize_parameters_deep()
Returns:
AL -- last post-activation value
caches -- list of caches containing:
every cache of linear_activation_forward() (there are L-1 of them, indexed from 0 to L-1)
"""
caches = []
A = X
L = len(parameters) // 2 # number of layers in the neural network
# Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
for l in range(1, L):
A_prev = A
A, cache = linear_activation_forward(A_prev, parameters["W" + str(l)], parameters["b" + str(l)], activation="relu")
caches.append(cache)
# Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
AL, cache = linear_activation_forward(A, parameters["W" + str(L)], parameters["b" + str(L)], activation="sigmoid")
caches.append(cache)
assert(AL.shape == (1,X.shape[1]))
return AL, caches
# In[73]:
X, parameters = L_model_forward_test_case_2hidden()
AL, caches = L_model_forward(X, parameters)
print("AL = " + str(AL))
print("Length of caches list = " + str(len(caches)))
# ## 5 - Cost function
#
# Now you will implement forward and backward propagation. You need to compute the cost, because you want to check if your model is actually learning.
# In[74]:
def compute_cost(AL, Y):
"""
Implement the cost function defined by equation (7).
Arguments:
AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)
Returns:
cost -- cross-entropy cost
"""
m = Y.shape[1]
# Compute loss from aL and y.
cost = (-1 / m) * np.sum(np.multiply(Y, np.log(AL)) + np.multiply(1-Y, np.log(1-AL)))
cost = np.squeeze(cost)
assert(cost.shape == ())
return cost
# In[75]:
Y, AL = compute_cost_test_case()
print("cost = " + str(compute_cost(AL, Y)))
# ## 6 - Backward propagation module
#
# Just like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss function with respect to the parameters.
#
# **Reminder**:
# <img src="images/backprop_kiank.png" style="width:650px;height:250px;">
# <caption><center> **Figure 3** : Forward and Backward propagation for *LINEAR->RELU->LINEAR->SIGMOID* <br> *The purple blocks represent the forward propagation, and the red blocks represent the backward propagation.* </center></caption>
#
# <!--
# For those of you who are expert in calculus (you don't need to be to do this assignment), the chain rule of calculus can be used to derive the derivative of the loss $\mathcal{L}$ with respect to $z^{[1]}$ in a 2-layer network as follows:
#
# $$\frac{d \mathcal{L}(a^{[2]},y)}{{dz^{[1]}}} = \frac{d\mathcal{L}(a^{[2]},y)}{{da^{[2]}}}\frac{{da^{[2]}}}{{dz^{[2]}}}\frac{{dz^{[2]}}}{{da^{[1]}}}\frac{{da^{[1]}}}{{dz^{[1]}}} \tag{8} $$
#
# In order to calculate the gradient $dW^{[1]} = \frac{\partial L}{\partial W^{[1]}}$, you use the previous chain rule and you do $dW^{[1]} = dz^{[1]} \times \frac{\partial z^{[1]} }{\partial W^{[1]}}$. During the backpropagation, at each step you multiply your current gradient by the gradient corresponding to the specific layer to get the gradient you wanted.
#
# Equivalently, in order to calculate the gradient $db^{[1]} = \frac{\partial L}{\partial b^{[1]}}$, you use the previous chain rule and you do $db^{[1]} = dz^{[1]} \times \frac{\partial z^{[1]} }{\partial b^{[1]}}$.
#
# This is why we talk about **backpropagation**.
# !-->
#
# Now, similar to forward propagation, you are going to build the backward propagation in three steps:
# - LINEAR backward
# - LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation
# - [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID backward (whole model)
# ### 6.1 - Linear backward
#
# For layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation).
#
# Suppose you have already calculated the derivative $dZ^{[l]} = \frac{\partial \mathcal{L} }{\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$.
#
# <img src="images/linearback_kiank.png" style="width:250px;height:300px;">
# <caption><center> **Figure 4** </center></caption>
#
# The three outputs $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$ are computed using the input $dZ^{[l]}$.Here are the formulas you need:
# $$ dW^{[l]} = \frac{\partial \mathcal{J} }{\partial W^{[l]}} = \frac{1}{m} dZ^{[l]} A^{[l-1] T} \tag{8}$$
# $$ db^{[l]} = \frac{\partial \mathcal{J} }{\partial b^{[l]}} = \frac{1}{m} \sum_{i = 1}^{m} dZ^{[l](i)}\tag{9}$$
# $$ dA^{[l-1]} = \frac{\partial \mathcal{L} }{\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \tag{10}$$
#
# In[76]:
def linear_backward(dZ, cache):
"""
Implement the linear portion of backward propagation for a single layer (layer l)
Arguments:
dZ -- Gradient of the cost with respect to the linear output (of current layer l)
cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer
Returns:
dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
dW -- Gradient of the cost with respect to W (current layer l), same shape as W
db -- Gradient of the cost with respect to b (current layer l), same shape as b
"""
A_prev, W, b = cache
m = A_prev.shape[1]
dW = (1 / m ) * np.dot(dZ, A_prev.T)
db = (1 / m) * np.sum(dZ, axis=1, keepdims=True)
dA_prev = np.dot(W.T, dZ)
assert (dA_prev.shape == A_prev.shape)
assert (dW.shape == W.shape)
assert (db.shape == b.shape)
return dA_prev, dW, db
# In[77]:
# Set up some test inputs
dZ, linear_cache = linear_backward_test_case()
dA_prev, dW, db = linear_backward(dZ, linear_cache)
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db))
# ### 6.2 - Linear-Activation backward
#
# Next, you will create a function that merges the two helper functions: **`linear_backward`** and the backward step for the activation **`linear_activation_backward`**.
#
# To help you implement `linear_activation_backward`, we provided two backward functions:
# - **`sigmoid_backward`**: Implements the backward propagation for SIGMOID unit. You can call it as follows:
#
# ```python
# dZ = sigmoid_backward(dA, activation_cache)
# ```
#
# - **`relu_backward`**: Implements the backward propagation for RELU unit. You can call it as follows:
#
# ```python
# dZ = relu_backward(dA, activation_cache)
# ```
#
# If $g(.)$ is the activation function,
# `sigmoid_backward` and `relu_backward` compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}) \tag{11}$$.
# In[78]:
def linear_activation_backward(dA, cache, activation):
"""
Implement the backward propagation for the LINEAR->ACTIVATION layer.
Arguments:
dA -- post-activation gradient for current layer l
cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently
activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
Returns:
dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
dW -- Gradient of the cost with respect to W (current layer l), same shape as W
db -- Gradient of the cost with respect to b (current layer l), same shape as b
"""
linear_cache, activation_cache = cache
if activation == "relu":
dZ = relu_backward(dA, activation_cache)
dA_prev, dW, db = linear_backward(dZ, linear_cache)
elif activation == "sigmoid":
dZ = sigmoid_backward(dA, activation_cache)
dA_prev, dW, db = linear_backward(dZ, linear_cache)
return dA_prev, dW, db
# In[79]:
dAL, linear_activation_cache = linear_activation_backward_test_case()
dA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = "sigmoid")
print ("sigmoid:")
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db) + "\n")
dA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = "relu")
print ("relu:")
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db))
# ### 6.3 - L-Model Backward
#
# Now you will implement the backward function for the whole network. Recall that when you implemented the `L_model_forward` function, at each iteration, you stored a cache which contains (X,W,b, and z). In the back propagation module, you will use those variables to compute the gradients. Therefore, in the `L_model_backward` function, you will iterate through all the hidden layers backward, starting from layer $L$. On each step, you will use the cached values for layer $l$ to backpropagate through layer $l$. Figure 5 below shows the backward pass.
#
#
# <img src="images/mn_backward.png" style="width:450px;height:300px;">
# <caption><center> **Figure 5** : Backward pass </center></caption>
#
# ** Initializing backpropagation**:
# To backpropagate through this network, we know that the output is,
# $A^{[L]} = \sigma(Z^{[L]})$. Your code thus needs to compute `dAL` $= \frac{\partial \mathcal{L}}{\partial A^{[L]}}$.
# To do so, use this formula (derived using calculus which you don't need in-depth knowledge of):
# ```python
# dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # derivative of cost with respect to AL
# ```
#
# You can then use this post-activation gradient `dAL` to keep going backward. As seen in Figure 5, you can now feed in `dAL` into the LINEAR->SIGMOID backward function you implemented (which will use the cached values stored by the L_model_forward function). After that, you will have to use a `for` loop to iterate through all the other layers using the LINEAR->RELU backward function. You should store each dA, dW, and db in the grads dictionary. To do so, use this formula :
#
# $$grads["dW" + str(l)] = dW^{[l]}\tag{15} $$
#
# For example, for $l=3$ this would store $dW^{[l]}$ in `grads["dW3"]`.
#
# Implement backpropagation for the *[LINEAR->RELU] $\times$ (L-1) -> LINEAR -> SIGMOID* model.
# In[84]:
def L_model_backward(AL, Y, caches):
"""
Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group
Arguments:
AL -- probability vector, output of the forward propagation (L_model_forward())
Y -- true "label" vector (containing 0 if non-cat, 1 if cat)
caches -- list of caches containing:
every cache of linear_activation_forward() with "relu" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)
the cache of linear_activation_forward() with "sigmoid" (it's caches[L-1])
Returns:
grads -- A dictionary with the gradients
grads["dA" + str(l)] = ...
grads["dW" + str(l)] = ...
grads["db" + str(l)] = ...
"""
grads = {}
L = len(caches) # the number of layers
m = AL.shape[1]
Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL
# Initializing the backpropagation
dAL = -np.divide(Y, AL) + np.divide(1 - Y, 1 - AL)
# Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "dAL, current_cache". Outputs: "grads["dAL-1"], grads["dWL"], grads["dbL"]
current_cache = caches[L-1]
grads["dA" + str(L-1)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, "sigmoid")
# Loop from l=L-2 to l=0
for l in reversed(range(L-1)):
# lth layer: (RELU -> LINEAR) gradients.
# Inputs: "grads["dA" + str(l + 1)], current_cache". Outputs: "grads["dA" + str(l)] , grads["dW" + str(l + 1)] , grads["db" + str(l + 1)]
current_cache = caches[l]
dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 1)], current_cache, "relu")
grads["dA" + str(l)] = dA_prev_temp
grads["dW" + str(l + 1)] = dW_temp
grads["db" + str(l + 1)] = db_temp
return grads
# In[85]:
AL, Y_assess, caches = L_model_backward_test_case()
grads = L_model_backward(AL, Y_assess, caches)
print_grads(grads)
# ### 6.4 - Update Parameters
#
# In this section you will update the parameters of the model, using gradient descent:
#
# $$ W^{[l]} = W^{[l]} - \alpha \text{ } dW^{[l]} \tag{16}$$
# $$ b^{[l]} = b^{[l]} - \alpha \text{ } db^{[l]} \tag{17}$$
#
# where $\alpha$ is the learning rate. After computing the updated parameters, store them in the parameters dictionary.
# In[86]:
def update_parameters(parameters, grads, learning_rate):
"""
Update parameters using gradient descent
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients, output of L_model_backward
Returns:
parameters -- python dictionary containing your updated parameters
parameters["W" + str(l)] = ...
parameters["b" + str(l)] = ...
"""
L = len(parameters) // 2 # number of layers in the neural network
# Update rule for each parameter. Use a for loop.
for l in range(L):
parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate * grads["dW" + str(l+1)]
parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate * grads["db" + str(l+1)]
return parameters
# In[87]:
parameters, grads = update_parameters_test_case()
parameters = update_parameters(parameters, grads, 0.1)
print ("W1 = "+ str(parameters["W1"]))
print ("b1 = "+ str(parameters["b1"]))
print ("W2 = "+ str(parameters["W2"]))
print ("b2 = "+ str(parameters["b2"]))
|
#Améliorer lalgo pour qu'il soit plus performant (Voir sur wiki) : approche iterative
#Implenter est Tester la performance des differents algorithmes
#Formules de Binet, Algo recursif Naif (fait), Algo Lineaires, Algo Recursif Terminal, Algo Co Recursif, Algo Logarithmique
def fibonacci(n):
if n < 0 :
if (n % 2):
return abs(fibonacci(n+1)) + fibonacci(n+2)
else :
return -fibonacci(n+1) + fibonacci(n+2)
if n >= 2 :
return fibonacci(n-1) + fibonacci(n-2)
else :
return n
|
# Dictionaries
## object that stores a collection of data
dictionary = {k1:v1, k2:v3, k3:v3}
# each element consists of a key(k) and a value(v) pair
# dictionaries are very fast - implemented using a technique called hashing
# keys must be immutable objects (no lists)
# values can be any type of object
# keys must be unique
# keys and values can be of different data types
dt = {}
# add new key and values
dt['Joe'] = ['111-111-1111', 'joe@gmail.com']
dt
-> {'Joe': ['111-111-1111', 'joe@gmail.com']}
dt['Bob': ['222-222-2222', 'bob@gmail.com']}
dt['Don': ['333-333-3333', 'don@gmail.com']}
dt
-> {'Joe': ['111-111-1111', 'joe@gmail.com'], 'Bob': ['222-222-2222', 'bob@gmail.com'], 'Don': ['333-333-3333', 'don@gmail.com']}
# print dict is ugly so make it better using pprint
import pprint
pprint.pprint(dt)
-> {'Joe': ['111-111-1111', 'joe@gmail.com'],
'Bob': ['222-222-2222', 'bob@gmail.com'],
'Don': ['333-333-3333', 'don@gmail.com']} # much better
# update bob's email address
dt['Bob'] = ['222-222-2222', 'bob2@gmail.com']
pprint.pprint(dt)
-> {'Joe': ['111-111-1111', 'joe@gmail.com'],
'Bob': ['222-222-2222', 'bob2@gmail.com'], # now updated
'Don': ['333-333-3333', 'don@gmail.com']}
# retrieving a value
# get method
dt.get('john') # will show nothing because there is no john
dt.get('john', 'nothing found') # build a sentence that you want if there is no value
-> 'nothing found'
dt.get('Bob')
-> ['Bob': ['222-222-2222', 'bob2@gmail.com']
# looping by key 1)
for x in dt:
print(x)
-> Joe
Bob
Don
# looping by key 2)
for x in dt.keys():
print(x)
-> Joe
Bob
Don
# lopping by value
for z in dt.values():
print(z)
-> ['111-111-1111', 'joe@gmail.com'],
['222-222-2222', 'bob2@gmail.com'],
['333-333-3333', 'don@gmail.com']
# looping with both keys and values
for k,v in dt.items():
print(k)
print(v)
-> Joe
['111-111-1111', 'joe@gmail.com'],
Bob
['222-222-2222', 'bob2@gmail.com'],
Don
['333-333-3333', 'don@gmail.com']
for k,v in dt.items():
if k == "Joe" or "joe@gmail.com" in v[1]:
print(v[0])
-> 111-111-1111
# deleting values
# del dt[key]
del dt['Bob']
# pop()
value = dt.pop(key, default_value)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 17 18:45:32 2017
@author: MattBarlowe
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pprint
from scipy.stats.stats import pearsonr
#creating function to return dataframes with the last five years of the data
def get_years(dataframe):
year_list = [2016, 2015, 2014, 2013, 2012]
dataframe = dataframe[dataframe['yearID'].isin(year_list)]
return dataframe
def team_cost_per_metric(dataframe, metrics):
'''
takes in dataframe and calculates the cost of each teams
metric per dollar
'''
for x in metrics:
if x != 'Bat_Avg':
dataframe['$_per_%s' % str(x)]=round(dataframe['salary']/
dataframe[x],2)
else:
dataframe['$_per_%s' % str(x)]= round(dataframe['salary']
.sum()/(dataframe[x]*1000), 2)
return dataframe
def difference_from_league_mean_standardized(dataframe, league_avg_dict, stats):
'''
takes in the league averages and league values per statistic and
standardizes them to graph later
'''
for x in stats:
dataframe['%s_diff_from_league_avg' % (x)] = dataframe['$_per_%s' % (x)]-league_avg_dict[x]
for x in stats:
dataframe['%s_diff_from_league_avg' % str(x)]= dataframe['%s_diff_from_league_avg' \
% str(x)]/dataframe['%s_diff_from_league_avg' % str(x)].std()
return dataframe
def plot_player_metrics(dataframe, metrics):
'''
function to plot each player salary vs offensive production metric
'''
for x in metrics:
sns.lmplot(x = 'salary', y=x, data=dataframe, hue = 'POS', scatter=True,
palette='bright', fit_reg=True)
plot.set_title('Salary vs %s' % (x))
plot.set_xlabel('Salary in $10 million units')
#sets position and offensive metric lists that will be commonly used throughout
#the program
fielders = ['OF', '1B', '2B', '3B', 'SS', 'C']
metrics = ['HR','R', 'H', 'SB','RBI', 'Bat_Avg']
#importing baseball stats csv files for salaries, batting
#fielding, and player names into dataframes
salary_df = pd.read_csv('/Users/MattBarlowe/baseballdatabank-2017.1/core/salaries.csv')
batting_df = pd.read_csv('/Users/MattBarlowe/baseballdatabank-2017.1/core/Batting.csv')
fielding_df = pd.read_csv('/Users/MattBarlowe/baseballdatabank-2017.1/core/Fielding.csv')
names_df = pd.read_csv('/Users/MattBarlowe/baseballdatabank-2017.1/core/Master.csv')
team_df = pd.read_csv('/Users/MattBarlowe/baseballdatabank-2017.1/core/Teams.csv')
#passing all dataframes to get_years function to create dataframes that only
#have the last five years data except for names_df which does not have a yearID
salary_df = get_years(salary_df)
batting_df = get_years(batting_df)
fielding_df = get_years(fielding_df)
team_df = get_years(team_df)
#create a batting average statistic on the batting df because it is missing
batting_df['Bat_Avg'] = round((batting_df['H']/batting_df['AB']), 3)
#group the fielding csv by player and year and then check to see if each row
#is the max for that player and year. This is to determine the position of
#each player as the position the player played most games at in a year. This
#is because many players can player many different positions
#but are often evaluated at their preferred or main position
fielding_grouped = fielding_df.groupby(['playerID','yearID'])['G'].transform(max)\
== fielding_df['G']
fielding_df = fielding_df[fielding_grouped]
#merging batting statistics with salary data did an inner merge that way any
#players without salary data will be dropped from the dataframe
master_df = batting_df.merge(salary_df)
#mergine batting/salary dataframe with name_df to get players first and last names
master_df = master_df.merge(names_df[['playerID', 'nameLast', 'nameFirst']],
on='playerID')
#rearranging columns to tidy up the data and put players names first in
#dataframe
columns = master_df.columns.tolist()
columns = columns[-2:] + columns[:-2]
master_df = master_df[columns]
#final merging of fielding statistics to the other stats to create the master
#df contiaing player, year, batting stats, position, and salary
master_df = master_df.merge(fielding_df[['playerID', 'yearID','POS']])
#removing pitchers from dataframe as they rarely or never hit and their numbers
#will skew the data
master_df = master_df[master_df['POS'].isin(fielders)]
#removing players who have less than 130 At Bats again to remove any non-regular
#hitters who might skew the data. PIcked 130 ABs because that is the number
#considered to be the threshhold to count as rookie's first season
master_df = master_df[master_df['AB']>=130]
#determining the mean of cost per statistic for the whole league for standard
#deviation calculations later
league_values_per = {}
for x in ['HR', 'SB', 'RBI', 'H', 'Bat_Avg', 'R']:
if x != 'Bat_Avg':
league_values_per[x]=round((master_df['salary']
.sum()/master_df[x].sum()), 2)
else:
league_values_per[x]= round(master_df['salary']
.sum()/(master_df[x].sum()*1000), 2)
salary_hist = master_df['salary'].plot.hist(edgecolor='k')
salary_hist.set_title('Frequency of Player Salaries in units of $10 Million')
#plot position vs
plot_player_metrics(master_df, metrics)
#create dataframe grouped by team
master_team_group = master_df.groupby('teamID')['HR','R', 'H', 'SB','RBI', 'Bat_Avg', 'salary'].sum()
master_team_group = team_cost_per_metric(master_team_group, metrics)
master_team_group = difference_from_league_mean_standardized(master_team_group, league_values_per, metrics)
#sums up team wins in year range and then adds a win column to the master dataframe
team_df = team_df.groupby('teamID')['W'].sum()
for x, y in zip(master_team_group.index, team_df):
master_team_group.loc[x,'W'] = y
#averages all the teams std dev of metrics to plot against wins
master_team_group['STD_metrics_avg_by_team']= master_team_group.iloc[:,13:18].mean(axis=1)
#creates the bar plot of each teams metrics
plot = master_team_group[['HR_diff_from_league_avg','R_diff_from_league_avg',
'H_diff_from_league_avg', 'SB_diff_from_league_avg', 'RBI_diff_from_league_avg'
]].plot(kind='bar', title ="Cost Per Stat", figsize=(12, 5),
legend=True, fontsize=12, width=.7)
plot.set_title('Difference from league average Spending in Standard Deviations')
#plot.set_yticklabels([])
plot.set_xlabel('Teams')
legend = plt.legend()
legend.get_texts()[0].set_text('Home Runs')
legend.get_texts()[1].set_text('Runs')
legend.get_texts()[2].set_text('Hits')
legend.get_texts()[3].set_text('Stolen Bases')
legend.get_texts()[4].set_text('RBI')
pearson_r = pearsonr(master_team_group['STD_metrics_avg_by_team'],
master_team_group['W'])
pearson_list=[]
for x in pearson_r:
pearson_list.append(x)
for x in pearson_list:
print(round(x, 3))
#plot teams spending below or above average versus to wins to see if overspending
#makes a better team
plot2 = sns.lmplot(x='STD_metrics_avg_by_team', y='W', data=master_team_group)
plt.subplots_adjust(top=0.9)
plot2.fig.suptitle('Spending on Offensive Metrics in Standard Deviations versus\
wins for years 2012-2016')
plot2.set_ylabels('Wins')
plot2.set_xlabels('Average Spending in Standard Deviations') |
words = input().split()
s_words = []
for word in words:
if word.endswith('s'):
s_words.append(word)
print('_'.join(s_words))
|
# put your python code here
sequence = input().split()
number = int(input())
position_of_x = [str(i) for i in range(len(sequence)) if int(sequence[i]) == number]
if len(position_of_x) == 0:
print("not found")
else:
print(' '.join(position_of_x))
|
from tkinter import *
def btnclick(number):
global operator
operator =operator + str(number)
text_Input.set(operator)
def btnclearDisplay():
global operator
operator=""
text_Input.set("")
def btne():
global operator
sumup=str(eval(operator))
text_Input.set(sumup)
operator = ""
cal =Tk()
cal.title("calculator")
cal.resizable(0,0)
operator =""
text_Input =StringVar()
txtDisplay = Entry(cal,font=('arial',20,'bold'),textvariable=text_Input,bd=30,insertwidth=4,bg="powder blue",justify='right').grid(columnspan=4)
btn7=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="7",command =lambda:btnclick(7)).grid(row=1,column=0)
btn8=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="8",command = lambda:btnclick(8)).grid(row=1,column=1)
btn9=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="9",command =lambda:btnclick(9)).grid(row=1,column=2)
btnadd=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="+",command =lambda:btnclick('+')).grid(row=1,column=3)
btn6=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="6",command =lambda:btnclick(6)).grid(row=2,column=0)
btn5=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="5",command =lambda:btnclick(5) ).grid(row=2,column=1)
btn4=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="4",command =lambda:btnclick(4)).grid(row=2,column=2)
btnminus=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="-",command =lambda:btnclick('-')).grid(row=2,column=3)
btn3=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="3",command =lambda:btnclick(3)).grid(row=3,column=0)
btn2=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="2",command =lambda:btnclick(2)).grid(row=3,column=1)
btn1=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="1",command =lambda:btnclick(1)).grid(row=3,column=2)
btnmult=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="*",command =lambda:btnclick("*")).grid(row=3,column=3)
btn0=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="0",command =lambda:btnclick(0)).grid(row=4,column=0)
btne=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="=",command =btne).grid(row=4,column=1)
btnc=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="C",command =btnclearDisplay).grid(row=4,column=2)
btnd=Button(cal,padx=16,pady=16,bd=8,fg="black",font=('ariel',20,'bold'),text="/",command =lambda:btnclick("/")).grid(row=4,column=3)
cal.mainloop() |
#!/usr/bin/env python3
import stopword
import sqlizer
'''
test script to check stopword, normalize, tokenize scripts
'''
# contains some natural language text with some special characters in middle of text and line, contains letter both in capiatl and small latters and attributes
#query = 'enter INTO a table --amit ColUmNs (name) wit:h data ("zzz", "kaka")'
#query = 'capital of india with the least population'
#query = 'why don"t you make a table amit with 2 columns (id is a integer, name is text)'
query = 'ENTER (id, name) in amit with (2, "amu") as values'
#i = stopword.stopwordremover(query)
i = sqlizer.sqlize(query)
print(i)
|
m=[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,]]
i=0
j=0
for i in range(len(m)):
print("\n")
for j in range(len(m[i])):
print(m[i][j], end=' ')
|
#Prathamesh Sai
#Predicting Stock Market Prices Using Machine Learning
import quandl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
#we import train test split so that it can split our test data into the training portion and the testing portion.
from sklearn.model_selection import train_test_split
#we import preprocessing to standardize the data.
from sklearn import preprocessing
#we import LinearRegression as we will be using a Linear Regression model.
from sklearn.linear_model import LinearRegression
#use my API Key for Quandl.
#uncomment line below and add your quandl API key.
#quandl.ApiConfig.api_key = 'Your API key goes here'
#get our dataframe, passing in which service we are using, and which stock we want to use.
#Gets over 20 years of data to work with.
dataframe = quandl.get("WIKI/NKE")
#We want to work with "Adj. Close" column, as it takes inflation into account.
#Adjusted close is the closing price after adjustments for all applicable splits and dividend distributions.
dataframe = dataframe[['Adj. Close']]
#uncomment to see the Adjusted Close prices
#print(dataframe)
#plot the adjusted close prices from 1997 to 2018.
dataframe['Adj. Close'].plot(figsize=(15,6), color='g')
plt.legend(loc='upper left')
#uncomment 2 lines below to see the plot.
#plt.xlim(xmax=datetime.date(2018,4,11))
#plt.show()
#Create a new variable to predict the stock price an integer number of days from now.
forecast = 30 #30 days from now
#Add a new column to our dataframe and shifting the data "forecast" units up
dataframe['Prediction'] = dataframe[['Adj. Close']].shift(-forecast)
#uncomment below to see the data.
#print(dataframe)
#The X variable will be the adjusted close prices
#Specify "1" at the end so that it will drop the column, and not the index.
X = np.array(dataframe.drop(['Prediction'], 1))
#Now, we standardize our data.
#This is because all the data has different ranges, different means, different standard deviations.
#By standardizing our data, we ensure that our dataset has 0 mean, and a standard deviation of 1.
X = preprocessing.scale(X)
#uncomment 4 lines below to see the the mean and the standard deviation
#print("The Mean of X is: ") #Will give a value close to 0, but not exactly 0.
#print(X.mean())
#print("The Standard Deviation of X is: ") #Will give a value of exactly 1.
#print(X.std())
#Make forecast_X equal to the last "forecast" days from the dataset
forecast_X = X[-forecast:]
#X will be equal to all but the last "forecast" from X.
X = X[:-forecast]
#Y will be equal to the column "prediction"
y = np.array(dataframe['Prediction'])
#Y will be equal to all but the last "forecast".
y = y[:-forecast]
#uncomment below to see how linear regression is working
#plt.plot(X, y)
#Now, X and y have the exact same length or column size for the features and labels training sets.
#After that, we must create training and testing data.
#We are going to split our data into 20% testing data, and 80% training data.
train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.2)
#create an estimator instance which is a classifier.
estimatorInstance = LinearRegression()
#Initialize our model
estimatorInstance.fit(train_X, train_y)
#Now that our data is fitted, we need to calculate a score.
#We get the confidence score of our data from scoring our testing data.
confidenceScore = estimatorInstance.score(test_X, test_y)
#uncomment below to see the confidence/score of our model (our confidence value should be close to 1)
#print("The confidence is: ")
#print(confidenceScore)
#now that we have confidence in our model, we can finally predict the stock market prices.
predicted_forecast = estimatorInstance.predict(forecast_X)
#uncomment to see the predicted values of the last 30 days.
#Each value corresponds to what our machine learning model thinks the price will be in 30 days from the day it was given.
#print(predicted_forecast)
#Now we will create an array to store 30 days.
dates = pd.date_range(start="2018-03-28", end="2018-04-26")
#Now we have to plot 2 line charts.
#1.plot our dates with our predicted forecast
plt.plot(dates, predicted_forecast, color='y')
#2.plot our adjusted close prices
dataframe['Adj. Close'].plot(color='g')
#zoom into the plot to see the predicted stock values.
plt.xlim(xmin=datetime.date(2017,4,26), xmax=datetime.date(2018,4,26))
#show the plot.
plt.show()
|
word_dict = {}
win_score = 0
retest_score = 0
fail_score = 0
retest = []
def open_word_file():
with open("sample_to_word_test.txt", "r", encoding='UTF8') as f:
for line in f:
line = line.strip().split(" ")
word_dict[line[0]] = line[1]
return word_dict
def f_test(win):
for eng in word_dict.keys():
answer = input(f"{eng} : ")
if word_dict[eng] == answer:
win += 1
print(f"정답입니다! {eng} {word_dict[eng]}\n")
else:
retest.append(eng)
print(f"오답입니다! {eng} {word_dict[eng]}\n")
return win
def f_retest(retest_scr, fail):
for eng in retest:
answer = input(f"{eng} : ")
if word_dict[eng] == answer:
retest_scr += 1
print(f"정답입니다! {eng} {word_dict[eng]}\n")
else:
fail += 1
print(f"오답입니다! {eng} {word_dict[eng]}\n")
return retest_scr, fail
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 17 14:08:33 2021
@author: karina
"""
import os
from PyPDF2 import PdfFileMerger
def merge_pdf(foldername, foldername_end, folder_location=''):
"""
Given a folder with city folders inside it, merge the pdfs that are inside
each city folder into one new pdf file and name them according to the city.
Saved all files inside the folder named 'foldername_end'.
Args:
foldername: Name of the folder where the cities folders are located (str)
foldername_end: Name of the folder where the merge file will be saved (str).
folder_location: directory where 'foldername' is located. By default
it takes the current working directory (str).
Retunrs:
None.
"""
#Create necessary directories.
if not folder_location:
cwd = os.getcwd() # cwd is the place where the folder calendar_plots is.
else:
cwd = folder_location
directory = os.path.join(cwd, foldername)
dir_end = os.path.join(cwd, foldername_end)
#Create the destination folder if it does not exist
if not os.path.isdir(dir_end):
os.mkdir(dir_end)
#Create a dictionary with cities as keys and a list of pdfs as values
pdfs = {}
for root, dirs, files in os.walk(directory):
if files:
name = files[0][:-8]
pdfs[name] = sorted(files)
#Merge pdf from each dity and locate them in the folder 'calendar_plots_unified'
for key in pdfs:
os.chdir(os.path.join(directory, key))
merger = PdfFileMerger()
for file in pdfs[key]:
merger.append(file)
filename = key + '.pdf'
dir_file = os.path.join(dir_end, filename)
merger.write(dir_file)
merger.close()
if __name__ == '__main__':
foldername = 'calendar_plots'
foldername_end = 'calendar_plots_unified'
merge_pdf(foldername, foldername_end) |
import pymongo as py
client = py.MongoClient()
db=client['Student']
collection=db['Student']
for i in range(0):
name=input("Enter name")
mark=int(input("Enter Marks"))
if(mark>=0 and mark<101):
collection.insert_one({'Name':name,'Marks':mark})
data=collection.find({'Marks':{'$gt':80}})
for i in data:
print(i)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 8 13:47:30 2020
@author: ben
"""
import numpy as np
def bin_rows(x):
"""
determine the unique rows in an array
inputs:
x: array of values. Some function should be applied so that x has
a limited number of discrete values
outputs:
bin_dict: dictionary whose keys are the unique values of x (unsorted)
and whose values are vectors of row indices containing those values
"""
ind=np.zeros(x.shape[0])
# bin the data by the values in each column. From left to right, the importance
# of the value to the sorting decreases by a factor the number of distinct
# values in each column
scale=1.
if len(x.shape)==1:
x.shape=[x.shape[0], 1]
for col in range(x.shape[1]):
z, ii=np.unique(x[:,col].astype(np.float64), return_inverse=True)
scale /= (np.max(ii).astype(float)+1.)
ind += ii * scale
u_ii, index, inverse=np.unique(ind, return_index=True, return_inverse=True)
bin_dict={}
inv_arg_ind=np.argsort(inverse)
inv_sort=inverse[inv_arg_ind]
ind_delta=np.concatenate([[-1], np.where(np.diff(inv_sort))[0], [inv_sort.size]])
for ii in range(len(ind_delta)-1):
this_ind=inv_arg_ind[(ind_delta[ii]+1):(ind_delta[ii+1]+1)]
bin_dict[tuple(x[this_ind[0], :])]=this_ind
return bin_dict |
class Vehicle(object):
L = 1
preferred_buffer = 6 # impacts "keep lane" behavior.
def __init__(self, lane, s, v, a):
self.lane = lane
self.s = s
self.v = v
self.a = a
self.state = "CS"
self.max_acceleration = None
# TODO - Implement this method.
def update_state(self, predictions):
"""
Updates the "state" of the vehicle by assigning one of the
following values to 'self.state':
"KL" - Keep Lane
- The vehicle will attempt to drive its target speed, unless there is
traffic in front of it, in which case it will slow down.
"LCL" or "LCR" - Lane Change Left / Right
- The vehicle will IMMEDIATELY change lanes and then follow longitudinal
behavior for the "KL" state in the new lane.
"PLCL" or "PLCR" - Prepare for Lane Change Left / Right
- The vehicle will find the nearest vehicle in the adjacent lane which is
BEHIND itself and will adjust speed to try to get behind that vehicle.
INPUTS
- predictions
A dictionary. The keys are ids of other vehicles and the values are arrays
where each entry corresponds to the vehicle's predicted location at the
corresponding timestep. The FIRST element in the array gives the vehicle's
current position. Example (showing a car with id 3 moving at 2 m/s):
{
3 : [
{"s" : 4, "lane": 0},
{"s" : 6, "lane": 0},
{"s" : 8, "lane": 0},
{"s" : 10, "lane": 0},
]
}
My understanding:
This is also the transition function. The pseudo-code given for this function
is in Lesson 4.10. Given the vehicle's current state, its possible successor states,
and the predictions of where other vehicles will be, we calculate the cost associated
with each possible successor state and determine which one is the best.
"""
self.state = "KL" # this is an example of how you change state.
def configure(self, road_data):
"""
Called by simulator before simulation begins. Sets various
parameters which will impact the ego vehicle.
"""
self.target_speed = road_data['speed_limit']
self.lanes_available = road_data["num_lanes"]
self.max_acceleration = road_data['max_acceleration']
goal = road_data['goal']
self.goal_lane = goal[0]
self.goal_s = goal[1]
def __repr__(self):
s = "s: {}\n".format(self.s)
s += "lane: {}\n".format(self.lane)
s += "v: {}\n".format(self.v)
s += "a: {}\n".format(self.a)
return s
def increment(self, dt=1):
self.s += self.v * dt
self.v += self.a * dt
def state_at(self, t):
"""
Predicts state of vehicle in t seconds (assuming constant acceleration)
"""
s = self.s + self.v * t + self.a * t * t / 2
v = self.v + self.a * t
return self.lane, s, v, self.a
def collides_with(self, other, at_time=0):
"""
Simple collision detection.
"""
l, s, v, a = self.state_at(at_time)
l_o, s_o, v_o, a_o = other.state_at(at_time)
return l == l_o and abs(s - s_o) <= L
def will_collide_with(self, other, timesteps):
for t in range(timesteps + 1):
if self.collides_with(other, t):
return True, t
return False, None
def realize_state(self, predictions):
"""
Given a state, realize it by adjusting acceleration and lane.
Note - lane changes happen instantaneously.
"""
state = self.state
if state == "CS":
self.realize_constant_speed()
elif state == "KL":
self.realize_keep_lane(predictions)
elif state == "LCL":
self.realize_lane_change(predictions, "L")
elif state == "LCR":
self.realize_lane_change(predictions, "R")
elif state == "PLCL":
self.realize_prep_lane_change(predictions, "L")
elif state == "PLCR":
self.realize_prep_lane_change(predictions, "R")
def realize_constant_speed(self):
self.a = 0
def _max_accel_for_lane(self, predictions, lane, s):
delta_v_til_target = self.target_speed - self.v
max_acc = min(self.max_acceleration, delta_v_til_target)
in_front = [v for (v_id, v) in predictions.items() if v[0]['lane'] == lane and v[0]['s'] > s]
if len(in_front) > 0:
leading = min(in_front, key=lambda v: v[0]['s'] - s)
next_pos = leading[1]['s']
my_next = s + self.v
separation_next = next_pos - my_next
available_room = separation_next - self.preferred_buffer
max_acc = min(max_acc, available_room)
return max_acc
def realize_keep_lane(self, predictions):
self.a = self._max_accel_for_lane(predictions, self.lane, self.s)
def realize_lane_change(self, predictions, direction):
delta = -1
if direction == "L": delta = 1
self.lane += delta
self.a = self._max_accel_for_lane(predictions, self.lane, self.s)
def realize_prep_lane_change(self, predictions, direction):
delta = -1
if direction == "L": delta = 1
lane = self.lane + delta
ids_and_vehicles = [(v_id, v) for (v_id, v) in predictions.items() if
v[0]['lane'] == lane and v[0]['s'] <= self.s]
if len(ids_and_vehicles) > 0:
vehicles = [v[1] for v in ids_and_vehicles]
nearest_behind = max(ids_and_vehicles, key=lambda v: v[1][0]['s'])
print("nearest behind : {}".format(nearest_behind))
nearest_behind = nearest_behind[1]
target_vel = nearest_behind[1]['s'] - nearest_behind[0]['s']
delta_v = self.v - target_vel
delta_s = self.s - nearest_behind[0]['s']
if delta_v != 0:
print("delta_v {}".format(delta_v))
print("delta_s {}".format(delta_s))
time = -2 * delta_s / delta_v
if time == 0:
a = self.a
else:
a = delta_v / time
print("raw a is {}".format(a))
if a > self.max_acceleration: a = self.max_acceleration
if a < -self.max_acceleration: a = -self.max_acceleration
self.a = a
print("time : {}".format(time))
print("a: {}".format(self.a))
else:
min_acc = max(-self.max_acceleration, -delta_s)
self.a = min_acc
def generate_predictions(self, horizon=10):
predictions = []
for i in range(horizon):
lane, s, v, a = self.state_at(i)
predictions.append({'s': s, 'lane': lane})
return predictions |
dogs = ["pitbull", "danish", "bulldog", "poodle"]
sizes = ["large", "medium", "medium", "small"]
zip(dogs, sizes)
#for dog in dogs:
# print(dog)
#for dog in sorted(dogs):
# print(dog)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 18:26:22 2019
@author: sbk
"""
class Tree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def evaluateExpressionTree(root):
# empty tree
if root is None:
return 0
# leaf node
if root.left is None and root.right is None:
return int(root.data)
# evaluate left tree
left_sum = evaluateExpressionTree(root.left)
# evaluate right tree
right_sum = evaluateExpressionTree(root.right)
# check which operation to apply
if root.data == '+':
return left_sum + right_sum
elif root.data == '-':
return left_sum - right_sum
elif root.data == '*':
return left_sum * right_sum
else:
return left_sum / right_sum
if __name__=='__main__':
# creating a sample tree
root = Tree('+')
root.left = Tree('*')
root.left.left = Tree('5')
root.left.right = Tree('4')
root.right = Tree('-')
root.right.left = Tree('100')
root.right.right = Tree('20')
print(evaluateExpressionTree(root))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 18:39:23 2019
@author: sbk
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def is_mirror(root1, root2):
if root1 is None and root2 is None:
return True
if root1 and root2:
return(root1.data == root2.data and
is_mirror(root1.left, root2.right) and
is_mirror(root1.right, root2.left))
return False
def is_symmetrical(root):
return is_mirror(root.left, root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
print("1" if is_symmetrical(root) == True else "0") |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not (t1 and t2):
return t1 or t2
q1, q2 = collections.deque([t1]), collections.deque([t2])
while q1 and q2:
node1 , node2 = q1.popleft(), q2.popleft()
if node1 and node2:
node1.val += node2.val
if (not node1.left) and node2.left:
node1.left = TreeNode(0)
if (not node1.right) and node2.right:
node1.right = TreeNode(0)
q1.append(node1.left)
q1.append(node1.right)
q2.append(node2.left)
q2.append(node2.right)
return t1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 19 02:32:27 2019
@author: sbk
"""
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
i, n = 0, len(numbers) - 1
while i < n:
if numbers[i] + numbers[n] == target:
return [i + 1, n + 1]
elif numbers[i] + numbers[n] > target:
n -= 1
else:
i += 1
return [-1,-1]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 18 16:02:00 2019
@author: sbk
"""
def minHeapify(heap,index):
left = index * 2 + 1
right = (index * 2) + 2
smallest = index
if len(heap) > left and heap[smallest] > heap[left]:
smallest = left
if len(heap) > right and heap[smallest] > heap[right]:
smallest = right
if smallest != index:
tmp = heap[smallest]
heap[smallest] = heap[index]
heap[index] = tmp
minHeapify(heap,smallest)
return heap
def convertMax(maxHeap):
for i in range((len(maxHeap))//2,-1,-1):
maxHeap = minHeapify(maxHeap,i)
return maxHeap
maxHeap = [9,4,7,1,-2,6,5]
print(convertMax(maxHeap)) |
from contextlib import contextmanager, ExitStack
from pathlib import Path
from typing import Iterator
from npipes.utils.typeshed import pathlike
@contextmanager
def autoDeleteFile(path:pathlike) -> Iterator[pathlike]:
"""Context manager that deletes a single file when the context ends
"""
try:
yield path
finally:
if Path(path).is_file():
Path(path).unlink()
class AutoDeleter(ExitStack):
"""Stack manager for auto-deleting files; allows files to be added incrementally.
Useful for working with temporary files on disk that should be
removed at the end of a computation.
Ex:
with AutoDeleter() as deleter:
deleter.add(file_1)
# ...
deleter.add(file_2)
# ...
file_3 = deleter.add("some_file.txt")
# file_1, file_2, and file_3 are deleted here automatically
"""
def add(self, path:pathlike) -> pathlike:
"""Returns path after adding it to the auto-deletion context.
"""
return self.enter_context(autoDeleteFile(path))
|
class Emp:
num_of_emps=0
raise_amt=1.05
def __init__(self, first, last, pay):
self.first=first
self.last=last
self.pay=pay
self.email=first+'.'+last+'@company.com'
Emp.num_of_emps+=1
def fullname(self):
return '{} {}'.format(emp1.first, self.last)
def apply_raise(self):
self.pay=int(self.pay*self.raise_amt)
emp1=Emp("Corey", "Scaufer", 40000)
emp2=Emp("Scander", "Cafer", 50000)
print(emp1.email)
print(emp1.fullname())
print(emp1.pay)
emp1.apply_raise()
print(emp1.pay)
print(emp1.raise_amt)
print(Emp.raise_amt)
print(emp1.__dict__)
print(Emp.__dict__)
print(Emp.num_of_emps)
'''
Output:
Corey.Scaufer@company.com
Corey Scaufer
40000
42000
1.05
1.05
{'last': 'Scaufer', 'first': 'Corey', 'email': 'Corey.Scaufer@company.com', 'pay': 42000}
{'num_of_emps': 2, '__dict__': <attribute '__dict__' of 'Emp' objects>, '__module__': '__main__', '__doc__': None, '__init__': <function Emp.__init__ at 0x7f692be80158>, 'raise_amt': 1.05, '__weakref__': <attribute '__weakref__' of 'Emp' objects>, 'fullname': <function Emp.fullname at 0x7f692be801e0>, 'apply_raise': <function Emp.apply_raise at 0x7f692be80268>}
2
'''
|
new= [2,-4,-6,23,0,1,6,8,5,7,9,21,41]
print(new)
short=[]
long=[]
for num in new:
if(num%2==0):
short.append(num)
else:
long.append(num)
print("even list: ",short," and odd list: ", long)
|
class Solution:
def isPowerOfThree(self, n: int) -> bool:
while(n>1):
n/=3
if n==1:
return True
else:
return False
|
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/poem1.txt -o poem1.txt
poem_file=open('poem1.txt','a+') #append and read
poem_file.write('\nExtra appended stuff')
poem_file.seek(0)
newone=poem_file.read()
print(newone)
'''Loops I repeat
loops
loops
loops
I repeat
until I
break
Extra appended stuff'''
|
n=int(input())
l=[]
for i in range(1, n):
if n%i==0:
l.append(i)
print(l)
#better time complexity
n=int(input())
l=[]
for i in range(2, round(n/2)+1):
if n%i==0:
l.append(i)
print(l)
#better time complexity O(sqrt(n))
from math import sqrt
n=int(input())
l=[]
for i in range(1, int(sqrt(n))+1):
if n%i==0:
l.append(i)
if i!=sqrt(n):
l.append(int(n/i))
print(sorted(l))
|
def strange_words(x):
l=[]
for i in x:
if len(i)<6:
l.append(i)
elif i[0]=='e' or i[0]=='E':
l.append(i)
if len(i)<6 and (i[0]=='e' or i[0]=='E'):
l.remove(i)
return l
x=["taco", "eggs", "excellent", "exponential", "artistic", "cat", "eat", "proper", "key", "earth", "ether", "mountain"]
print(strange_words(x))
'''
['taco', 'excellent', 'exponential', 'cat', 'key']
'''
|
elements = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine',
'Neon', 'Sodium', 'Magnesium', 'Aluminum', 'Silicon', 'Phosphorus', 'Sulfur', 'Chlorine', 'Argon',
'Potassium', 'Calcium']
elements.reverse()
for third in range(0,len(elements),3):
print(elements[third])
|
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/poem1.txt -o -poem1.txt
poem=open('poem1.txt','a')
poem.write("-The End-")
poem.seek(0)
poem=open('poem1.txt','r')
read1=poem.read()
print(read1)
'''
Loops I repeat
loops
loops
loops
I repeat
until I
break
-The End-
'''
|
def isPalindrome(self, s: str) -> bool:
if s==' ':
return True
s=s.lower()
x=s.replace(" ", "")
l=[]
for let in x:
if let.isalnum():
l.append(let)
print(l[::-1])
if l==l[::-1]:
return True
else:
return False
|
visited = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
new=[]
visited.sort()
print(visited)
for city in visited:
if 'A' <=city[0] <='Q':
new.append(city)
print(new)
|
def numbers (term, list1=['1','2','3','4','5']):
for num in list1:
if num == term:
return True
else:
pass
return False
list2=['6','7','8','9','0']
term1=input("Find number in list 1: ")
print(term1, " in list 1: ", numbers(term1))
term2=input("Find another number in list 2: ")
print(term2, " in list 2: ", numbers(term2,list2))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
import itertools
word, num=input().split()
num=int(num)
for i in itertools.permutations(sorted(word), num):
print("".join(i))
|
"""
Deletes files that you don't need recursively in folders
__author__: Amna Hyder
__date__: August 2018
"""
import os, sys, shutil
def remove_files_recursive(path):
files = os.listdir(path)
for file in files:
if os.path.isdir(file):
remove_files_recursive(path + file + '/')
print('checking directory',path + file + '/')
# elif not file.endswith('_seg.mff'):
# shutil.rmtree(os.path.join(path, file))
elif not file.endswith('.mff') and not file.endswith('.py'):
os.remove(os.path.join(path, file))
print('deleting file',os.path.join(path, file))
if __name__ == '__main__' :
print(os.getcwd())
remove_files_recursive(os.getcwd()+'/')
|
def dictcreator (keyy, val):
W = {keyy: val}
print(W)
return
a = input("Введите ключ словаря: ")
b = input("Введите значение словаря: ")
dictcreator(a, b) |
import random
def ruletka(down, up, elements):
s = []
for i in range(elements):
b = random.randint(down, up)
s.append(b)
return s
def findInRuletka(number, ruletkaa):
a = ruletkaa.count(number)
if a == 0:
print("Циферка не найдена")
return
b = 0
for i in range(a):
print("Циферка найдена под индексом: " + str(ruletkaa.index(number) + b))
ruletkaa.remove(number)
b = b + 1
return
|
#!/usr/bin/env python
NUM = 35
count = 0
while count < 3:
user_input = int(input("plz input a number:"))
if user_input == NUM:
print("you win")
elif user_input < NUM:
print("less")
else:
print("big")
count += 1
else:
print("you lose")
for _ in range(0,3):
user_input = int(input("plz input a number:"))
if user_input == NUM:
print("you win")
elif user_input < NUM:
print("less")
else:
print("big")
count += 1
else:
print("you lose")
|
#!/usr/bin/env python3
import random
import string
# 生成大写字母和小写字母列表:
# capital = [ chr(i) for i in range(65,91)]
# lowercase = [chr(i) for i in range(97,123)]
# string模块中已经有相应的实现,不过是字符串而已;
letters = list(string.ascii_letters)
capital = list(string.ascii_uppercase)
lowercase = list(string.ascii_lowercase)
digits = list(string.digits)
punctuation = list(string.punctuation)
print(letters)
print(capital)
print(lowercase)
print(digits)
print(punctuation)
ran_lower = random.choice(digits)
print(ran_lower)
|
full_number = int(input())
real_number = float(input())
text = str(input())
print("String:", text)
print("Float:", real_number)
print("Int:", full_number)
|
def factorial_Func():
num = input("Of what number do you want to know the factorial? ") #Prompt for Factorial number calculation
facto_result = 1
for x in range(1,num+1): #Loop that calucates factorial of given number
facto_result = x * facto_result
print("The factorial of {} is {}." .format(num, facto_result)) #Print Result
print("") |
# Print the following pattern
# 1
# 2 2
# 3 3 3
# 4 4 4 4
# 5 5 5 5 5
for num in range(10):
for i in range(num):
print (num, end=" ") #print number
# new line after each row to display pattern correctly
print("\n") |
floatNumbers = []
n = int(input("Enter the list size : "))
for i in range(0, n):
print("Enter number at location", i, ":")
item = float(input())
floatNumbers.append(item)
print("User List is {}".format(floatNumbers)) |
# Accept any three string from one input() call
str1, str2, str3 = input("Enter three string").split()
print(str1, str2, str3) |
# if the number is divisble by 3 print fizz, by 5 printt buzz and by 15 print fizz buzz
for i in range(31):
if i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
elif i % 15 == 0:
print("fizzbuzz")
|
# 다형성(Polymorphism)
class Armorsuite:
def armor(self):
print("armored")
class IronMan(Armorsuite):
pass
def get_armored(suite):
suite.armor()
if __name__ == '__main__':
suite = Armorsuite()
get_armored(suite)
Iron_man = IronMan()
get_armored(Iron_man)
|
# 다중상속시 주의 사항
class A:
def method(self):
print("A")
class B:
def method(self):
print("B")
class C(A):
def method(self):
print("C")
class D(B,C):
pass
if __name__ == '__main__':
obj = D()
obj.method()
# B -> D(B,C)
# C -> D(C,B)
print(D.mro())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.