text
stringlengths 37
1.41M
|
---|
def pattern(n):
for i in range(1,10):
for i in range(0,i):
print("*")
print("\r")
pattern(10)
#not completed |
#a function its self is called recursion
#fibnocci series using recursion
#call afunction inside the same function
#important
def recur_fibo(n):
if n<=1:
return n
else:
return recur_fibo(n-1)+recur_fibo(n-2)
nterms=10 #nterms=int(input("enter number))
if nterms<=0:
print("please enter a positive integer")
else:
print("fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
|
#for loop same
#initialization
#condition
#inc or dec
#inc 1 ,bt not using;no need of 1,loop default the inc
for i in range(1,10): #upp-1
print(i)
|
list=[1,53,4,96,46]
print(list)
oddset=set()
evenset=set()
for i in list:
if(i%2==0):
evenset.add(i)
else:
oddset.add(i)
print("even set",evenset)
print("odd set",oddset) |
#program to accept three integers and print the largest of the three. make use of
#only if statement.
x=float(input("enter the first number:"))
y=float(input("enter the second number:"))
z=float(input("enter the third number:"))
max=x
if(y>max):
max=y
if(z>max):
max=z
print("largest number is", max) |
sal=int(input("enter ur salary"))
year=int(input("enter num of yr of service"))
bonus=(5/100)*sal
if(year>=5):
newsal=sal+bonus
print(newsal)
else:
print("experience lessthan 5")
|
#Create an Animal class using constructor and build a child class for Dog?
class Animal:
def __init__(self,name,age):
self.name=name
self.age=age
def print(self):
print("i'am",self.name)
print(self.age,"years old")
class Dog(Animal):
def __init__(self,name,age,type):
super().__init__(name,age)
self.type=type
def printval(self):
print(self.type)
am=Dog("jacky",5,"dog")
am.print()
am.printval()
|
# to add odd and even elemnts to different set
s={1,8,5,9,4,7,11,100,5,}
print(s)
odd=set()
even=set()
for i in s:
if(i%2==0):
even.add(i)
else:
odd.add(i)
print("even set",even)
print("odd set",odd)
|
#reduce
# import functools
from functools import *
arr=[1,2,3,4,5,6]
total=reduce(lambda num1,num2:num1+num2,arr)
print(total)
#print highest number
highest=reduce(lambda num1,num2:num1 if num1>num2 else num2,arr)
print(highest)
|
#using forloop odd to even number and check sum
low=int(input("enter the low limit"))
upp=int(input("enter the upp limit"))
evensum=0
oddsum=0
for i in range(low,upp+1):
if(i%2==0): #1%2==0
evensum+i
else:
oddsum+i
print(evensum)
print(oddsum) |
#write a program to input a value in kilometers and convert it into miles (1km=0.621371miles)
km=int(input("enter the kilometers:"))
miles=km*0.621371
print(miles) |
#odd or even
def odd():
num1=int(input("enter the num"))
if(num1%2==0):
print("even")
else:
print("odd")
odd() |
# 1. PRINT STATEMENT: [syntax: print()]
print("hello world")
# 2. PRINT BLANK LINES:
print(4 * "\n") # it's print 4 blank lines
""" NOTE:
1. print("\n\n\n\n") this is another print statement to print 4 blank lines """
# 3. PRINT END COMMAND: [syntax : print("", end ="")]
""" NOTE:
1. In python(above 3+ version) every print() statement have end command, the default value of end command
is '\n'. because of that after every print statement next statement comes/print in newline in output.
2. You can end a print statement with any character or string using 'end' parameter.
3. For example if you want to replace end statement with space then the next print statement not printed in newline
because we replaced end statement value i.e \n with space so next statement print along with current print
statement with space. check below print statements"""
print("---print end command start---\n")
print("default print statement,") # here we didn't mention any end command, so the default value is '\n'
print("without end command\n")
print("1st print statement with space end command,", end=' ') # here we replaced '\n' with space by using end command
print("2nd print statement w/o end command\n")
print("1st print statement with space end command,", end=' ') # replaced '\n' with space
print("2nd print statement with character(!) end command", end='!') # replaced '\n' with '!' character, so next print
# statement print beside this.
print("\n---print end command end---\n")
# 4. MAIN FUNCTION: [syntax : def function_name()]
print("--- main() start---\n")
def main(): # here we declare main()
print("main function start")
var1 = 1
print(var1)
var2 = "inside main()"
print(var2)
print("main function end\n")
main() # here we call the main(), if you want to run main() we must call it.
print("outside the main()\n")
print("---main() end---\n")
# 5. DECLARE AND RE-DECLARE VARIABLE:
print("---declare and re-declare start---\n")
var3 = 1 # here we declare the variable with integer
print("var3 value before re-declare:", var3)
var3 = "var3 successfully re-declared" # here we re-declare the variable with string
print("var3 value after re-declare:", var3)
print("\n---declare and re-declare end---\n")
# 6. ATTACH/CONCATENATE VARIABLES:
print("---Concatenate Variables start---\n")
var4 = " string var4 "
var5 = 5
var6 = " string var6 "
var7 = 7
print("concatenate string var4 with integer var5 is: ", var4 + str(var5))
print("concatenate string var4 with string var6 is: ", var4 + var6)
print("concatenate integer with integer is:", str(var5) + str(var7))
print("\n---Concatenate Variables end---\n")
"""NOTE:
1. we can not concatenate string with integer directly, so we use str() method to declare integer value as
string.
2. similarly we can't concatenate integer with integer directly its do addition. so we have to use str() method
to concatenate integer with integer.
"""
# 6. LOCAL AND GLOBAL VARIABLES:
"""NOTE:
1. any variable declared in inside function (var10) is called LOCAL VARIABLE
2. any variable declared in outside function (var8,var9) is called GLOBAL VARIABLE
3. all variables we used in function is must declare before function calling other wise its leeds to error
4. if you declaring a variable as GLOBAL VARIABLE (var11) then you shouldn't declare that variable
before global syntax in inside the function, if you did that leeds to error
5. if you use any local variable (var10) outside function its leeds to error.
6. we can use global variable (var8,var9) inside function but we can't use local variable (var10) outside
function without declaring as global variable (var11).
"""
print("---local and global variable start---\n")
var8 = "var8 is global variable" # here var8 is global variable
var9 = "var9 is global variable"
print(var8)
def main2():
print("\nmain2() start\n")
var8 = "var8 is local variable" # here var8 is local variable. the value of var8 valid inside this function only.
print(var8)
var10 = "var10 is local variable" # var10 is local variable because its define in inside function. if you used
# var10 variable outside the function without define its leeds to error because its local variable.
print(var10)
print(var9) # we printing/calling global variable inside function.
global var11 # make sure that var11 is not declare before this syntax, if you declared its leeds to error.
var11 = "var11 declared as global variable inside function"
print("inside function var11 value:", var11)
print("\nmain2() end\n")
main2()
print(var8)
print("outside function var11 value:", var11)
print("\n---local and global variable end---\n")
# 7. DELETE VARIABLE: [syntax: del variable_name ]
var12 = 12
del var12 # var12 variable is deleted.
# 8. SPECIAL AND ESCAPE CHARACTER:
""" NOTE:
1. In python "\t" and "\n" is called as "SPECIAL CHARACTER" and "\" called as "ESCAPE CHARACTER"
'\t' is a tab
'\n' is a new line
'\' is escape character, it means '\' becomes hide/escape and print content before and next to it.
"""
print("---special and escape character start---\n")
print("1. '\\t'character") # ESCAPE character
print("apple", "\torange") # special character '\t' it's gives space b/w two words.
print("2. '\\n'character") # ESCAPE character
print("apple\n", "orange", "\n") # special character '\n' it's produce new line b/w two words
print("3. '\\'escape character") # ESCAPE character
print("it\'s raining here") # ESCAPE character '\' it's produce single/double quotations.
print("\"hello\"") # ESCAPE character '\' it's produce single/double quotations.
print("'\'hello")
print("\n---special and escape character end---\n")
# 9. RAW STRING: [syntax: print(r"") or print(R"")]
""" NOTE:
1. raw strings means it's print text/value inside the quotation r"" or R"" as it is.
2. its define with R"" or r"".
"""
print("---raw string start---\n")
print(r"hello '\n' and '\t' this is raw string example") # RAW STRING: it's print text after 'r' or 'R' as it is
print(R"hello '\n' and '\t' this is raw string example")
print("\n---raw string end---\n")
# the content b/w """ """ is taken as paragraph or multiple line string, it is used when need to print paragraphs
# syntax: print(""" """). if you not mention print statement with """ """ quotation it is not print in o/p.
|
# import libraries
# -*- coding: utf-8 -*-
import urllib2
from bs4 import BeautifulSoup
# specify the url
quote_page = "http://www.bloomberg.com/quote/SPX:IND"
# query the website and return the html to the variable ‘page’
page = urllib2.urlopen(quote_page)
# parse the html using beautiful soup and store in variable `soup`
soup = BeautifulSoup(page, "html.parser")
# Take out the <div> of name and get its value
name_box = soup.find('h1', attrs={"class": "name"})
name = name_box.text.strip() # strip() is used to remove starting and trailing
print name
|
# Normal library imports
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
# importing requisite information from create_data.py
# 1. show_images(): to display the images so it may be verified if Canny Edge detection worked fine
# 2. grey_images: which is a
from create_data import show_images, gray_images, test_images
def detect_edges(image, low_threshold=50, high_threshold=200):
# Applies the Canny Edge detection algorithm
# Refer: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_canny/py_canny.html
# Thresholds are hyper-parameters chosen such that:
# 1. Shorter than requried lines are not chosen
# 2. Longer lines such that path etc. are also not chosen and are not mistaken for parking spot
return cv2.Canny(image, low_threshold, high_threshold)
edge_images = list(map(lambda image: detect_edges(image), gray_images)) # creating a map and applying the Canny edge detection
# Uncomment the line to display the image, for testing purposes
show_images(edge_images)
###############################################################################################################################
def filter_region(image, vertices):
# The entire image is not required for the training. So we simply remove parts of the image not required/containing paths the network can
# confuse for some parking spot
mask = np.zeros_like(image) # np.zeros_like() creates a matrix of 0s of the same size as the image. Applying the mask on the image
# enables it to multiply the pixel value with 0 (rendering it black)
if len(mask.shape)==2: # No extra channel dimension:
cv2.fillPoly(mask, vertices, 255) # Simply fill the image with BLACK
else:
cv2.fillPoly(mask, vertices, (255,)*mask.shape[2]) # in case, the input image has a channel dimension
# Handle the color dimension equally well
return cv2.bitwise_and(image, mask) # Bitwise_and simply does a 0 whenever the mask has a zero value. So the non-required area is chopped off
def select_region(image):
# The Region of Interest is defined a polygon of user defined number of vertices
# FUTURE UPDATE: include a method to let users dynamically define this region of interest
rows, cols = image.shape[:2]
pt_1 = [cols*0.05, rows*0.90]
pt_2 = [cols*0.05, rows*0.70]
pt_3 = [cols*0.30, rows*0.55]
pt_4 = [cols*0.6, rows*0.15]
pt_5 = [cols*0.90, rows*0.15]
pt_6 = [cols*0.90, rows*0.90]
# the vertices are an array of polygons (i.e array of arrays) and the data type must be integer
vertices = np.array([[pt_1, pt_2, pt_3, pt_4, pt_5, pt_6]], dtype=np.int32)
return filter_region(image, vertices)
# images showing the region of interest only
roi_images = list(map(select_region, edge_images))
# Uncomment this line to test for the region of interest detection
show_images(roi_images)
#######################################################################################################
def hough_lines(image):
# This function applies the Hough Line Transform to the Canny Edge detected image (along with ROI implemented)
return cv2.HoughLinesP(image, rho=0.1, theta=np.pi/10, threshold=15, minLineLength=9, maxLineGap=4)
def draw_lines(image, lines, color=[255, 0, 0], thickness=2, make_copy=True):
# the lines returned by cv2.HoughLinesP has the shape (-1, 1, 4)
if make_copy:
image = np.copy(image) # don't want to modify the original
cleaned = []
for line in lines:
for x1,y1,x2,y2 in line:
if abs(y2-y1) <=1 and abs(x2-x1) >=25 and abs(x2-x1) <= 55:
cleaned.append((x1,y1,x2,y2))
cv2.line(image, (x1, y1), (x2, y2), color, thickness)
print(" No lines detected: ", len(cleaned))
return image
list_of_lines = list(map(hough_lines, roi_images))
line_images = []
for image, lines in zip(test_images, list_of_lines):
line_images.append(draw_lines(image, lines))
show_images(line_images)
#################################
#######################################################################################################
def identify_blocks(image, lines, make_copy=True):
if make_copy:
new_image = np.copy(image)
#Step 1: Create a clean list of lines
cleaned = []
for line in lines:
for x1,y1,x2,y2 in line:
if abs(y2-y1) <=1 and abs(x2-x1) >=25 and abs(x2-x1) <= 55:
cleaned.append((x1,y1,x2,y2))
#Step 2: Sort cleaned by x1 position
import operator
list1 = sorted(cleaned, key=operator.itemgetter(0, 1))
#Step 3: Find clusters of x1 close together - clust_dist apart
clusters = {}
dIndex = 0
clus_dist = 10
for i in range(len(list1) - 1):
distance = abs(list1[i+1][0] - list1[i][0])
# print(distance)
if distance <= clus_dist:
if not dIndex in clusters.keys(): clusters[dIndex] = []
clusters[dIndex].append(list1[i])
clusters[dIndex].append(list1[i + 1])
else:
dIndex += 1
#Step 4: Identify coordinates of rectangle around this cluster
rects = {}
i = 0
for key in clusters:
all_list = clusters[key]
cleaned = list(set(all_list))
if len(cleaned) > 5:
cleaned = sorted(cleaned, key=lambda tup: tup[1])
avg_y1 = cleaned[0][1]
avg_y2 = cleaned[-1][1]
# print(avg_y1, avg_y2)
avg_x1 = 0
avg_x2 = 0
for tup in cleaned:
avg_x1 += tup[0]
avg_x2 += tup[2]
avg_x1 = avg_x1/len(cleaned)
avg_x2 = avg_x2/len(cleaned)
rects[i] = (avg_x1, avg_y1, avg_x2, avg_y2)
i += 1
print("Num Parking Lanes: ", len(rects))
#Step 5: Draw the rectangles on the image
buff = 7
for key in rects:
tup_topLeft = (int(rects[key][0] - buff), int(rects[key][1]))
tup_botRight = (int(rects[key][2] + buff), int(rects[key][3]))
# print(tup_topLeft, tup_botRight)
cv2.rectangle(new_image, tup_topLeft,tup_botRight,(0,255,0),3)
return new_image, rects
# images showing the region of interest only
rect_images = []
rect_coords = []
for image, lines in zip(test_images, list_of_lines):
new_image, rects = identify_blocks(image, lines)
rect_images.append(new_image)
rect_coords.append(rects)
show_images(rect_images)
#######################################################################################################
def draw_parking(image, rects, make_copy = True, color=[255, 0, 0], thickness=2, save = True):
if make_copy:
new_image = np.copy(image)
gap = 15.5
spot_dict = {} # maps each parking ID to its coords
tot_spots = 0
adj_y1 = {0: 20, 1:-10, 2:0, 3:-11, 4:28, 5:5, 6:-15, 7:-15, 8:-10, 9:-30, 10:9, 11:-32}
adj_y2 = {0: 30, 1: 50, 2:15, 3:10, 4:-15, 5:15, 6:15, 7:-20, 8:15, 9:15, 10:0, 11:30}
adj_x1 = {0: -8, 1:-15, 2:-15, 3:-15, 4:-15, 5:-15, 6:-15, 7:-15, 8:-10, 9:-10, 10:-10, 11:0}
adj_x2 = {0: 0, 1: 15, 2:15, 3:15, 4:15, 5:15, 6:15, 7:15, 8:10, 9:10, 10:10, 11:0}
for key in rects:
# Horizontal lines
tup = rects[key]
x1 = int(tup[0]+ adj_x1[key])
x2 = int(tup[2]+ adj_x2[key])
y1 = int(tup[1] + adj_y1[key])
y2 = int(tup[3] + adj_y2[key])
cv2.rectangle(new_image, (x1, y1),(x2,y2),(0,255,0),2)
num_splits = int(abs(y2-y1)//gap)
for i in range(0, num_splits+1):
y = int(y1 + i*gap)
cv2.line(new_image, (x1, y), (x2, y), color, thickness)
if key > 0 and key < len(rects) -1 :
#draw vertical lines
x = int((x1 + x2)/2)
cv2.line(new_image, (x, y1), (x, y2), color, thickness)
# Add up spots in this lane
if key == 0 or key == (len(rects) -1):
tot_spots += num_splits +1
else:
tot_spots += 2*(num_splits +1)
# Dictionary of spot positions
if key == 0 or key == (len(rects) -1):
for i in range(0, num_splits+1):
cur_len = len(spot_dict)
y = int(y1 + i*gap)
spot_dict[(x1, y, x2, y+gap)] = cur_len +1
else:
for i in range(0, num_splits+1):
cur_len = len(spot_dict)
y = int(y1 + i*gap)
x = int((x1 + x2)/2)
spot_dict[(x1, y, x, y+gap)] = cur_len +1
spot_dict[(x, y, x2, y+gap)] = cur_len +2
print("total parking spaces: ", tot_spots, cur_len)
if save:
filename = 'with_parking.jpg'
cv2.imwrite(filename, new_image)
return new_image, spot_dict
delineated = []
spot_pos = []
for image, rects in zip(test_images, rect_coords):
new_image, spot_dict = draw_parking(image, rects)
delineated.append(new_image)
spot_pos.append(spot_dict)
show_images(delineated)
#######################################################################################################
final_spot_dict = spot_pos[1]
def assign_spots_map(image, spot_dict=final_spot_dict, make_copy = True, color=[255, 0, 0], thickness=2):
if make_copy:
new_image = np.copy(image)
for spot in spot_dict.keys():
(x1, y1, x2, y2) = spot
cv2.rectangle(new_image, (int(x1),int(y1)), (int(x2),int(y2)), color, thickness)
return new_image
marked_spot_images = list(map(assign_spots_map, test_images))
show_images(marked_spot_images)
#######################################################################################################
import pickle
with open('spot_dict.pickle', 'wb') as handle:
pickle.dump(final_spot_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)
#######################################################################################################
def save_images_for_cnn(image, folder_name, spot_dict = final_spot_dict):
for spot in spot_dict.keys():
(x1, y1, x2, y2) = spot
(x1, y1, x2, y2) = (int(x1), int(y1), int(x2), int(y2))
#crop this image
# print(image.shape)
spot_img = image[y1:y2, x1:x2]
spot_img = cv2.resize(spot_img, (0,0), fx=2.0, fy=2.0)
spot_id = spot_dict[spot]
filename = 'spot' + str(spot_id) +'.jpg'
print(spot_img.shape, filename, (x1,x2,y1,y2))
cv2.imwrite(os.path.join(folder_name, filename), spot_img)
save_images_for_cnn(test_images[0], 'cnn\\train_cnn\\')
save_images_for_cnn(test_images[1], 'cnn\\test_cnn\\')
|
def check_index(key):
if not isinstance(key,int):raise TypeError
if key<0:raise IndexError
class ArithmeticSequence:
def __init__(self,start=0,step=1):
self.start = start
self.step = step
self.changed = {}
def __getitem__(self,key):
check_index(key)
try:return self.changed[key]
except KeyError:
return self.start + key * self.step
def __setitem__(self,key,value):
check_index(key)
self.changed[key] = value
s = ArithmeticSequence(1,2)
print(s[4])
print(s[2])
a = 2
b = 6
a,b = b,a+b
print(a,b)
|
#!/usr/bin/env python
# list = [num*num for num in range(1,11)]
# print(list)
# list1 = [num*num for num in range(1,11) if num%2 == 0]
# print(list1)
# list2 = [char+num for char in ['a','b','c'] for num in['1','2','3']]
# print(list2)
# list3 = (num*num for num in range(1,6))
# print(list3)
# for li in list3:
# print(li)
# def square(input):
# list = []
# for num in range(input):
# list.append(num*num)
# print(list)
# return list
# for num in square(1000):
# print(num)
# def square(input):
# for num in range(input):
# print('before yield')
# yield num*num
# print('after yield')
# for num in square(5):
# print(num)
# import time
# def timeTest():
# print('timeTest start')
# print('sleep 1 second...')
# time.sleep(1)
# print('timeTest end')
# timeTest()
# def hi(name="yasoob"):
# print("now you are inside the hi() function")
# def greet():
# print("now you are in the greet() function")
# def welcome():
# print("now you are in the welcome() function")
# print("now you are back in the hi() function")
# hi()
# def a_new_decorator(a_func):
# def wrapTheFunction():
# print("I am doing some boring work before executing a_func()")
# a_func()
# print("I am doing some boring work after executing a_func()")
# return wrapTheFunction
# def a_function_requiring_decoration():
# print("I am the function which needs some decoration to remove my foul smell")
# a_function_requiring_decoration()
# #outputs: "I am the function which needs some decoration to remove my foul smell"
# a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
# #now a_function_requiring_decoration is wrapped by wrapTheFunction()
# a_function_requiring_decoration()
# #outputs:I am doing some boring work before executing a_func()
# # I am the function which needs some decoration to remove my foul smell
# # I am doing some boring work after executing a_func()
# def use_logging(func):
# def wrapper():
# print("%s is running" % func.__name__)
# return func()
# return wrapper
# @use_logging
# def foo():
# print("i am foo")
# foo()
# print(foo)
# def int2(num,base=2):
# return int(num,base)
# print(int2('1010'))
# import struct
# s = '459C3800'
# print(s)
# #<是小端,>是大端,f代表浮点数
# print(struct.unpack('<f', bytes.fromhex(s))[0])#小端
# #输出:120.40420532226562
# s = float('6.55563714424545E-10')
# print(struct.pack('<f', s).hex())#小端
# #输出:32333430
# print(struct.pack('>f', s).hex())#大端
# #输出:30343332
# import struct
# print(struct.unpack('!f','459C3800'.decode('hex')))
# from ctypes import *
# def convert(s):
# i = int(s,16)
# cp = pointer(c_int(i))
# fp = cast(cp, POINTER(c_float))
# return fp.contents.value
# print(convert('45151000'))
import datetime
import time
cur_time_minute = datetime.datetime.now().minute
cur_time_second = datetime.datetime.now().second
if cur_time_minute == 0 or cur_time_minute == 30:
sleep_time=0
elif cur_time_minute < 30:
sleep_time = (30-cur_time_minute)*60 - cur_time_second
elif cur_time_minute > 30:
sleep_time = (60-cur_time_minute)*60 - cur_time_second
print(sleep_time)
time.sleep(sleep_time)
while True:
hour_now=datetime.datetime.now().hour
minute_now=datetime.datetime.now().minute
print(hour_now)
print(minute_now)
minute_now=datetime.datetime.now().minute
second_now=datetime.datetime.now().second
if sleep_time == 0 and minute_now == 1 or minute_now == 31:
time.sleep(3600-second_now-60)
else:
time.sleep(3600-second_now)
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
class MyClass(object):
message="hello, developer!"
def show(self):
print(self.message)
print("Here is %s in %s!" % (self.name,self.color))
@staticmethod
def printMessage():
print("printMessage is called")
print(MyClass.message)
@classmethod
def createObj(cls,name,color):
print("Object will be created: %s(%s, %s)"% (cls.__name__,name,color))
return cls()
def __init__ (self,name="unset",color="black"):
print("Constructor is called with param: ",name," ",color)
self.name = name
self.color = color
def __del__(self):
print("Destructor is called for %s!"%self.name)
MyClass.printMessage()
inst = MyClass.createObj("Toby","Red")
print(inst.message)
del inst
"""inst = MyClass()
inst.show()
inst2 = MyClass("Divad")
inst2.show()
inst3 = MyClass("Lisa","Yellow")
inst3.show()
inst4 = MyClass(color="Green")
inst4.show()""" |
import random
import time
nahodne_cislo = []
zadane_cislo = []
def main():
print("Ahoj, vitej ve hre bulls and cows!")
print("Generuji nahodne ctyrciferne cislo (muze zacinat nulou).")
vytvor_nahodne_cislo()
t0 = time.time()
pokus = 0
while nahodne_cislo != zadane_cislo:
pokus += 1
print(16 * "=")
print("Pokus cislo: {} .".format(pokus))
print(16 * "=")
zadane_cislo.clear()
zadej_cislo()
print(41 * "=")
porovnej_cisla(nahodne_cislo, zadane_cislo)
print(41 * "=")
if nahodne_cislo == zadane_cislo:
break
ukonceni = input("Pro ukonceni zadej 'exit',pro pokracovani zadej cokoli jineho a stiskni ENTER : ")
if ukonceni == 'exit':
break
else:
continue
if zadane_cislo == nahodne_cislo:
t1 = time.time() - t0
casy.append(t1)
pokusy.append(pokus)
print("Vyborne, uhodl jsi na pocet pokusu: {} , za cas {} vterin.".format(pokus, t1))
else:
t1 = time.time() - t0
casy.append(-t1)
pokusy.append(-pokus)
print("Nevadi, snad nekdy priste.")
def vytvor_nahodne_cislo():
while len(nahodne_cislo) < 4:
x = random.randint(0, 9)
if x not in nahodne_cislo:
nahodne_cislo.append(x)
def zadej_cislo():
cislo_str = input("Vloz ctyrciferne cislo! : ")
while len(cislo_str) != 4 or cislo_str.isalpha():
cislo_str = input("Neplatne zadani! Vloz ctyrciferne cislo! : ")
for i in range(4):
zadane_cislo.append(int(cislo_str[i]))
def porovnej_cisla(nahodne_cislo, zadane_cislo):
bulls = 0
dohromady = 0
for i in range(0, 4):
if nahodne_cislo[i] == zadane_cislo[i]:
bulls += 1
for i in nahodne_cislo:
if i in zadane_cislo:
dohromady += 1
cows = dohromady - bulls
print("Trefil jsi pocet BULLS: {} a pocet COWS: {} ".format(bulls, cows))
pokusy = []
casy = []
while True:
nahodne_cislo.clear()
zadane_cislo.clear()
main()
konec_hry = input("Pro UKONCENI zadej 'exit', pro NOVOU HRU zadej cokoli : ")
if konec_hry == 'exit':
break
else:
continue
print("Znamenko minus [-] indikuje NEDOHRANOU hru!")
print("POCET pokusu v jednotlivych hrach: {}.".format(pokusy))
print("CASY jednotlivych her [vteriny]: {}.".format(casy))
print("Ukoncuji, nashledanou...") |
"""
This project was created by the right honorable sir Alexander de Poyen-Brown, in
the year of Our Lord two thousand and twenty one for the purpose of being silly.
"""
def sillyText(word, num):
"""
Purpose: To duplicate each character in a string
Parameters: word - the string in question, num - the number of duplications
Return: word - the duplicated word
"""
if len(word) == 0:
return ""
thing = word[0]
word = word[1:]
word = sillyText(word, num)
word = thing * 2 + word
return word
def getUserInput():
"""
Purpose: to validate user Input
Parameters: None
Returns: x - validated user input
"""
x = input("Number of repeats: ")
try:
x = int(x)
except ValueError:
x = getUserInput()
return x
def main():
word = input("Word: ")
num = getUserInput()
silly = sillyText(word, num)
print(silly)
main()
|
# Pograma que da um desconto de 12 porcento de um produto
produto = 'Video Game'
valor = float(input('Entre com o valor do produto: R$'))
desc = (valor * 12) / 100
print(f'Produto: {produto}.\nValor: R${valor}\nDesconto: R${desc}\nTotal a pagar: R${valor - desc}') |
# Peça ao usuario para digitar 3 numero e retorne a somas de ambos
"""num1 = int(input('Entre com um numero: '))
num2 = int(input('Entre com um numero: '))
num3 = int(input('Entre com um numero: '))
soma = num1 + num2 + num3
print(soma)"""
nums = []
cont = 0
while cont < 3:
numeros = int(input('Entre com um numero: '))
nums.append(numeros)
cont += 1
soma = sum(nums)
print(f'A somas dos numeros {nums} é: {soma}')
|
# Convertendo Km/h para milhas
km_h = float(input('Entre com a distancia em KM/h: '))
milhas = km_h / 1.62
print(milhas) |
import sys
import click
#(1)Source: https://stackoverflow.com/questions/20063/whats-the-best-way-to-parse-command-line-arguments
#(2)Source: https://www.youtube.com/watch?v=SDyHLG2ltSY (click watch)
#(3)Source: https://www.youtube.com/watch?v=gR73nLbbgqY (tools for cli)
#(4)Source: https://www.youtube.com/watch?v=hJhZhLg3obk
#(5)Source - Useful: http://zetcode.com/python/click/
#print(len(sys.argv))
#args = sys.argv[1:]
"""if(len(args) > 0):
print("ok")
else:
print("not enough args")"""
#print(type(args[0]))
#for arg in args:
# print(arg)
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', multiple=True, help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
#click.echo('Hello %s!' % name)
#click.echo(name)
print(list(name))
if __name__ == '__main__':
hello()
|
import sys
# total arguments
print("Total arguments passed: " + str(len(sys.argv)))
assert len(sys.argv)==3, "Expected 2 arguments."
s1 = sys.argv[1]
s2 = sys.argv[2]
print("No of characters in both strings: (" + str(len(s1)) + "," + str(len(s2)) + ")")
print("Are they equal? " + str(s1==s2))
counter=0
for char1,char2 in zip(s1,s2):
counter+=1
if char1!=char2:
# Character1,Character2,Position
print(char1 + "," + char2 + "," + str(counter) + "\n") |
# 第一步 以像素为单位,进行带角度的坐标转换 像素相对坐标系
# 第二步 将坐标转化为以毫米为单位 毫米绝对坐标系
# 第三步 加上平移的毫米偏移量,最终毫米绝对坐标系下的坐标
import numpy as np
# a = np.arange(10)
# print(a)
# print(a.shape)
a = np.arange(100).reshape(10, 10)
print(a)
print(a.shape)
a_index = []
for i in range(a.shape[0]):
for j in range(a.shape[1]):
a_index.append([i,j])
print(a_index)
matrix = [[0.6,0.8],[-0.8,0.6]]
b = np.dot(a_index, matrix)
print(b)
|
###############################
# python imports
###############################
from time import time
###############################
# Timing Class
###############################
class Timer:
def __init__(self, precision=3):
'''
(Timing, int) -> (None)
:constructor function for the Timing class, will initialize a
starting time upon the function call
@paramaters the precission paramater must be given a integer
argument, representing the number of decimals ea-
ch float value will have that is logged, default 3
'''
self.precision = precision
self.start = round(time(), self.precision) #start time of the class
self.log = []
def get_log(self):
'''
(Timing) -> (list of floats)
:the getter function for the last recorded time difference
'''
return self.log
def get_start(self):
'''
(Timing) -> (float)
:the getter function for the classes start time
@returns the time recorded when the class was initialized
'''
return self.start
def pop(self, index):
'''
(Timing) -> (float)
:remove a stored lap based on it's index
@returns a float representing the popped value
@exception returns 0.0 if a valid index was given
'''
log_length = len(self.log)
if (index > log_length or (index < 0 and index < -log_length)):
return 0.0
return self.log.pop(index)
def reset(self):
'''
(Timing) -> (None)
:remove the currently stored laps on the Timmer
'''
self.log = []
def time_alive(self):
'''
(Timer) -> (float)
:a function returning the time the Timer class has been
running since being initialize, following the rounding
@returns a float representing time since placed on the heap
'''
temp = round(time(), self.precision) - self.start
return temp
def __eq__(self, other):
'''
(Timer, object) -> (boolean)
'''
#check if the types are the same
if (type(other) != type(self)):
return False
#check to see if the logs of both of the timers are the same
if (self.log != other.log):
return False
return True
def __repr__(self):
'''
(Timing) -> (list of floats)
:the Timing class can be represented by the the list of
logs they hold from the lap function being called
@returns a list of floats representing all the laps
@exception if no laps have been called an empty list of
floats is returned
'''
return self.log
def __str__(self):
'''
(Timing) -> (string)
:the string representation function for the Timer class
@returns a client-friendly string representing the class
'''
return f'Timer(start={self.start}, {self.precision})'
def __del__(self):
'''
(Timing) -> (float)
:the destructor object for the Timing class, released from
memory and returns the total runtime of the counter
'''
temp = round(time(), self.precision) - self.start
return temp |
def show_magicians(list):
# while list:
# print(list)
# 不能自动跳出去
for person in list:
print(person)
personlist = ["linlin","linna","nana"]
show_magicians(personlist)
|
##Codifica strings ao transformá-las em binário, de binário para gray e de gray de volta para string.
#Encodes strings by transforming them into binary, from binary to gray and from gray into string again.
print('Bem-vindo ao Codificador.') #'Welcome to the encoder.'
print('O codificador usa os caracteres dentro da lista encodedChar,') #'The encoder uses characters from the list encodedChar'
print('tanto na codificação quanto na decodificação da string, e') #'when reading input as well as when encoding the string'
print('pode ser customizada dentro do código.\n') #'and can be customized inside the code.'
##Lista de caracteres. Adicione ou remova caracteres de acordo com os que você quer usar.
#List of characters. Add or remove characters to suit your needs.
encodedChar = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/']
def encoder():
##Define as variáveis usadas
#Defines the variables used.
string = input('Insira a sequência de caracteres que deseja codificar: ')
inputChar = list(string)
inputChar.reverse()
value = 0
binary = []
gray = []
codList = []
cod = ''
##Converte o valor do index dos caracteres do input em valor decimal.
#Converts the index value of the input characters into decimal.
for x in encodedChar:
index = 0
while index < len(inputChar):
if inputChar[index] == x:
value += (encodedChar.index(x)) * ((len(encodedChar))**(index))
index += 1
##Converte o valor em decimal para um em binário.
#Converts the decimal value to binary.
divRes = 1
divRem = 1
while divRes != 0:
divRes = value // 2
divRem = value % 2
value = divRes
binary.append(str(divRem))
binary.reverse()
##Converte o valor em binário para gray.
#Converts the binery value to gray.
for i in range(0, (len(binary))):
if i == 0:
gray.append(binary[0])
elif binary[i] != binary[i - 1]:
gray.append('1')
else:
gray.append('0')
gray.reverse()
##Converte o valor em gray para decimal.
#Converts the gray value to decimal
value = 0
for i in range (0, len(gray)):
value += int(gray[i]) * (2**(i))
##Converte o valor decimal para caractere usando seus valores de index.
#Converts the decimal value to characters using their index values.
divRes = 1
divRem = 1
while divRes != 0:
divRes = value // (len(encodedChar))
divRem = value % (len(encodedChar))
value = divRes
codList.append(encodedChar[divRem])
codList.reverse()
##Une os caracteres codificados em uma string.
#Unites the codified characters into a string.
for i in codList:
cod += i
##Mostra a string codificada.
#Prints the encoded string.
print('\nA sequência de caracteres codificadas é: ' + cod)
##Pergunta se o usuário quer codificar outra string.
#Asks if the user wants to encode another string.
again = input('\nInsira 1 se você gostaria de codificar ou decodificar outra sequência de caracteres: ')
if again == '1':
choice()
def decoder():
##Define as variáveis usadas
#Defines the variables used.
string = input('Insira a sequência de caracteres que deseja decodificar: ')
inputChar = list(string)
inputChar.reverse()
value = 0
binary = []
gray = []
codList = []
cod = ''
##Converte o valor do index dos caracteres do input em valor decimal.
#Converts the index value of the input characters into decimal.
for x in encodedChar:
index = 0
while index < len(inputChar):
if inputChar[index] == x:
value += (encodedChar.index(x)) * ((len(encodedChar))**(index))
index += 1
##Converte o valor em decimal para gray.
#Converts the decimal value to gray.
divRes = 1
divRem = 1
while divRes != 0:
divRes = value // 2
divRem = value % 2
value = divRes
gray.append(str(divRem))
gray.reverse()
##Converte o valor em gray para binário.
#Converts the gray value to binary.
for i in range(0,len(gray)):
if i == 0:
binary.append(gray[0])
elif gray[i] != binary[i - 1]:
binary.append('1')
else:
binary.append('0')
binary.reverse()
##Converte o valor em gray para decimal.
#Converts the gray value to decimal
value = 0
for i in range (0, len(binary)):
value += int(binary[i]) * (2**(i))
##Converte o valor decimal para caractere usando seus valores de index.
#Converts the decimal value to characters using their index values.
divRes = 1
divRem = 1
while divRes != 0:
divRes = value // (len(encodedChar))
divRem = value % (len(encodedChar))
value = divRes
codList.append(encodedChar[divRem])
codList.reverse()
##Une os caracteres codificados em uma string.
#Unites the codified characters into a string.
for i in codList:
cod += i
##Mostra a string codificada.
#Prints the encoded string.
print('\nA sequência de caracteres codificadas é: ' + cod)
##Pergunta se o usuário quer codificar outra string.
#Asks if the user wants to encode another string.
again = input('\nInsira 1 se você gostaria de codificar ou decodificar outra sequência de caracteres: ')
if again == '1':
choice()
def choice():
print('Você quer codificar ou decodificar uma string?\n')
print('1. Codificar')
print('2. Decodificar\n')
choice = input()
if choice == '1':
encoder()
elif choice == '2':
decoder()
choice() |
# Recebe o número de itens em uma lista e o valor de cada item e imprime o dobro do valor deles na ordem inversa
# Receives the number of items in a list and each item value, then prints their double in the reverse order
lista = []
n = int(input('Insira o número de itens da lista: '))
for cont in range (1, n + 1):
lista.append(int(input('Insira o item: ')))
lista.reverse()
for i in lista:
print(i * 2) |
import random
import numpy as np
from operator import itemgetter
class RandomSampling(object):
"""This class is used to implement different types of random sampling techniques
"""
def __init__(self,data,num):
print ("Initialzing Random Sampling Class")
self.data=data
self.num=num
def simple_random_sampling(self):
"""This function is used to implement simple random sampling
"""
return random.sample(self.data,self.num)
def uniform_random_sampling(self):
"""This function is used to implement uniform random sampling
"""
random_data=[]
cur=np.random.uniform(0,len(self.data),self.num)
cur=[int(i) for i in cur]
for i in xrange(len(cur)):
random_data.append(self.data[i])
return random_data
def systematic_random_sampling(self):
"""This function is used to implement systematic random sampling
"""
N=len(self.data)
k=N/self.num
index=0
iteration=0
random_data=[]
while (iteration< self.num):
random_data.extend(random.sample(self.data[index:index+k],1))
iteration+=1
index+=k
return random_data
def stratified_random_sampling(self):
"""This function is used to implement stratified random sampling
"""
sorted_data=sorted(self.data,key=itemgetter(9))
random_data=random.sample(sorted_data[0:self.num/2],self.num/2)
random_data.extend(random.sample(sorted_data[(self.num/2)+1:self.num],(self.num/2)-1))
return random_data
def multistage_random_sampling(self):
"""This function is used to implement multistage random sampling
"""
num_cluster=8
random_data=[]
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=(num_cluster), precompute_distances=True, ).fit(self.data)
selected_cluster=random.randint(0,num_cluster-1)
labels=kmeans.labels_.tolist()
for i in xrange(len(labels)):
if labels[i]==selected_cluster:
random_data.append(self.data[i])
return random_data
|
import numpy as np
from .layers import Layer
from tqdm import tqdm
# Neural Network API inspired by sequential model
def batch_iterator(X, y=None, batch_size=64):
"""
Simple batch iterator
From https://github.com/eriklindernoren/ML-From-Scratch/blob/master/mlfromscratch/utils/data_manipulation.py
"""
n_samples = X.shape[0]
for i in np.arange(0, n_samples, batch_size):
begin, end = i, min(i+batch_size, n_samples)
if y is not None:
yield X[begin:end], y[begin:end]
else:
yield X[begin:end]
class NeuralNetwork():
def __init__(self, optimizer, loss_function):
self.layers = []
self.loss_function = loss_function()
self.optimizer = optimizer
self.errors = []
def add_layer(self, layer: Layer):
if self.layers:
layer.set_input_shape(shape=self.layers[-1].output_shape())
# If the layer has weights that needs to be initialized
if hasattr(layer, 'initialize'):
layer.initialize(optimizer=self.optimizer)
# Add layer to the network
self.layers.append(layer)
def _forward(self, X, training=True):
"""
Loops over every layer and does forward propagation
Output of previous layer is input for the next
"""
layer_output = X # First input is X
for layer in self.layers:
layer_output = layer.forward(layer_output, training)
return layer_output
def _train_batch(self, X, y):
y_pred = self._forward(X)
loss = np.mean(self.loss_function.loss(y, y_pred))
loss_grad = self.loss_function.gradient(y, y_pred)
self._backward(loss_grad=loss_grad)
return loss
def _backward(self, loss_grad):
"""
Back propagate through the layers and updates the gradients according to the loss
"""
for layer in reversed(self.layers):
loss_grad = layer.backward(loss_grad)
def fit(self, X, y, n_epochs, batch_size):
for _ in tqdm(range(n_epochs)):
batch_errors = []
for X_batch, y_batch in batch_iterator(X, y, batch_size=batch_size):
loss = self._train_batch(X_batch, y_batch)
batch_errors.append(loss)
avg_batch_error = np.mean(batch_errors)
self.errors.append(avg_batch_error)
return self.errors
def predict(self, X, argmax=True):
"""Forward pass through network for predicting
"""
pred = self._forward(X, training=False)
#print(pred)
if argmax:
return np.argmax(pred, axis=1)
else:
return pred |
if __name__ == '__main__':
s = raw_input()
alphanum = 0
alpha = 0
digit = 0
lower = 0
upper = 0
for i in range(len(s)):
if(s[i].isalnum()):
alphanum+=1
if(s[i].isalpha()):
alpha+=1
if(s[i].isdigit()):
digit+=1
if(s[i].islower()):
lower+=1
if(s[i].isupper()):
upper+=1
if(alphanum>0):
print("True")
else:
print("False")
if(alpha>0):
print("True")
else:
print("False")
if(digit>0):
print("True")
else:
print("False")
if(lower>0):
print("True")
else:
print("False")
if(upper>0):
print("True")
else:
print("False")
|
# High order functions
# son funciones que reciben como prametro a otra funcion
# Existen 3 principales:jilter, map, reduce
from functools import reduce
def run():
my_list = [1,4,5,6,9,13,19,21]
odd = [i for i in my_list if i % 2 != 0]
print(odd)
# Filter: filtra los valores de una lista
odd = list(filter(lambda x: x % 2 != 0, my_list))
print(odd)
my_list = [1,2,3,4,5]
squared = [i**2 for i in my_list]
print(squared)
# map: aplica trnsformacion de valores
squared = list(map(lambda x: x**2, my_list))
print(squared)
my_list = [2, 2, 2, 2, 2]
all_multiplied = reduce(lambda a, b: a * b, my_list)
print(all_multiplied)
# La diferencia entre filter y map:d
# filter devuelve True or False según el valor esté dentro de los criterios buscados o no. En caso de que no cumpla con la condición, no será devuelto y la lista se verá reducida por este filtro.
# Map funciona muy parecido, pero su diferencia radica en que no puede eliminar valores de la lista del array entregado. Es decir, el output tiene la misma cantidad de valores que el input.
# Cómo funciona reduce:
# Reduce toma 2 valores entregados como parámetros y el iterador como otro parámetro. Realiza la función con estos 2 valores, y luego con el resultado de esto y el valor que le sigue en el array. Y así hasta pasar por todos los valores de la lista.
if __name__ == '__main__':
run() |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 00:05:02 2020
@author: Akshat Jain
"""
class Node(object):
def __init__(self , character):
self.character = character
self.leftchild = None
self.rightchild = None
self.middlechild = None
self.value = 0
class TST(object):
def __init__(self):
self.root = None
def put(self , key , value):
self.root = self.putItem(self.root , key , value , 0)
def putItem(self , node , key ,value , index):
c = key[index]
if node == None:
node = Node(c)
if c < node.character:
node.leftchild = self.putItem(node.leftchild , key , value , index)
elif c > node.character:
node.rightchild = self.putItem(node.rightchild , key , value , index)
elif index < len(key)-1:
node.middlechild = self.putItem(node.middlechild , key , value , index+1)
else:
node.value = value
return node
def get(self , key):
node = self.getItem(self.root , key , 0)
if node == None:
return -1
return node.value
def getItem(self , node , key , index):
c = key[index]
if node == None:
return None
if c < node.character :
return self.getItem(node.leftchild , key , index)
elif c > node.character :
return self.getItem(node.rightchild , key , index)
elif index < len(key)-1:
return self.getItem(node.middlechild , key , index+1)
else:
return node
if __name__ == "__main__":
t = TST()
t.put('apple' , 20)
t.put('oranges' , 40)
t.get('oranges')
t.get('apple')
|
str = "Hello man, how are you babe?"
print(str[3])
print(str[3:5])
print(str.split(","))
print(str.lower())
print(str.upper())
print(len(str))
print("What is your name?")
name = input()
print("Your name is " + name)
|
class Person:
def __init__(self,name, family):
self.name = name
self.family = family
def full_name(self):
return(self.name + " "+ self.family)
class Student(Person):
def __init__(self, fname , lname , year_of_birth):
Person.__init__(self,fname, lname)
self.year_of_birth = year_of_birth
def show_year_of_birth(self):
return(self.year_of_birth)
person = Person("soroush","khosravi")
print(person.full_name())
student = Student("farnaz","ostovari",1988)
print(student.full_name())
print(student.show_year_of_birth())
|
n1 = float(input('Digite a nota 1 '))
n2 = float(input('Digite a nota 2 '))
print('A média entre suas notas "{}" "{}" é "{}"'.format(n1, n2, ((n1 + n2) / 2))) |
a = input("enter value of a")
b = input("enter value of b")
val_a = int(a)
val_b = int(b)
y = (val_a + 4 * val_b) * (val_a + 3 * val_b) + val_a*val_a
print(y)
|
#! /usr/bin/env python3
#
# Take a file, extract all trees, midpoint root, calculate height, print
# heights
import argparse
from parsers import Tree
from midpointRoot import midpoint_root
from describe import print_descriptive_statistics
def get_height(tree):
tree = midpoint_root(tree)
return tree.avg_dist(tree.root)
def get_trees(file_handle):
while True:
text_tree = file_handle.readline()
if text_tree == '':
break
else:
try:
tree = Tree(text_tree)
yield tree
except ValueError:
continue
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('tree_file', help="the file containing one or more trees")
args = parser.parse_args()
heights = []
with open(args.tree_file, 'r') as fh:
for tree in get_trees(fh):
heights.append(get_height(tree))
print_descriptive_statistics(heights)
|
#https://www.hackerrank.com/challenges/np-arrays/problem?h_r=next-challenge&h_v=zen
import numpy
def arrays(arr):
# complete this function
# use numpy.array
arrnp = numpy.array(arr,float)
return arrnp[::-1]
arr = input().strip().split(' ')
result = arrays(arr)
print(result) |
#!/bin/python3
import math
import os
import random
import re
import sys
def keyFunc(item,k):
return item[k]
if __name__ == '__main__':
nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
# print(arr[::])
k = int(input())
# arr.sort(key=keyFunc(k))
arr.sort(key=lambda x: x[k])
print('\n'.join([' '.join(['{}'.format(item) for item in row])
for row in arr]))
|
# https://www.hackerrank.com/challenges/py-collections-ordereddict/problem
from collections import OrderedDict
n = int(input())
ordered_dictionary = OrderedDict()
for _ in range(n):
items = input().rpartition(' ')
item_name = items[0]
net_price = int(items[2])
if item_name in ordered_dictionary:
ordered_dictionary[item_name] = ordered_dictionary[item_name] + net_price
else:
ordered_dictionary[item_name] = net_price
for key in ordered_dictionary:
print(key,ordered_dictionary[key]) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 11 12:08:22 2017
@author: yazar
"""
import numpy as np
import pandas as pd
from scipy import linalg
from sklearn import preprocessing
from matplotlib import pyplot as plt
from scipy import optimize
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def _RSS(theta, X, y):
# number of training examples
m = len(y)
theta = theta.reshape(-1, 1)
y = y.reshape(-1, 1)
prediction = np.dot(X, theta)
mean_error = prediction - y
return 1/(2*m) * np.sum(np.power(mean_error, 2))
def _logisticCostFunc(theta, X, y):
""" compute cost for logistic regression
Parameters:
-----------
theta : ndarray, shape (n_features,)
Regression coefficients
X : {array-like}, shape (n_samples, n_features)
Training data. Should include intercept.
y : ndarray, shape (n_samples,)
Target values
Returns
-------
cost : float
cost evaluation using logistic cost function
"""
# number of training examples
m = len(y)
y = y.reshape(-1, 1)
theta = theta.reshape(-1, 1)
J = 1/m * (np.dot(-y.T, np.log(sigmoid(np.dot(X, theta)))) -
np.dot((1-y).T, np.log(1 - sigmoid(np.dot(X, theta)))))
return np.asscalar(J)
def compute_gradient(theta, X, y):
""" Compute gradient. This will be passed to minimization functions
Parameters:
-----------
theta : ndarray, shape (n_features,)
Regression coefficients
X : {array-like}, shape (n_samples, n_features)
Training data. Should include intercept.
y : ndarray, shape (n_samples,)
Target values
Returns
-------
gradient : ndarray, shape (n_features,)
"""
m = len(y)
y = y.reshape(-1, 1)
theta = theta.reshape(-1, 1)
grad = 1/m * np.dot(X.T, sigmoid(np.dot(X, theta)) - y)
return grad.ravel()
def compute_cost(theta, X, y, method='RSS'):
""" Compute cost to be used in gradient descent
Parameters:
-----------
X : {array-like}, shape (n_samples, n_features)
Training data. Should include intercept.
y : ndarray, shape (n_samples,)
Target values
theta : ndarray, shape (n_features,)
Regression coefficients
method : cost calculation method, default to 'RSS'
Only RSS is supported for now
Returns
-------
cost : float
"""
print("cost method is {0}".format(method))
if method == 'RSS':
return _RSS(theta, X, y)
elif method == 'logistic':
return _logisticCostFunc(theta, X, y)
else:
raise ValueError("only 'RSS' and 'Logistic' methods are supported.")
def normalEqn(X, y):
""" Computes the closed-form solution to linear regression
using the normal equations.
Parameters:
-----------
X : {array-like}, shape (n_samples, n_features)
Training data. Should include intercept.
y : ndarray, shape (n_samples,)
Target values
Returns
-------
theta : {array-like}, shape (n_features,)
"""
theta = np.dot(np.dot(linalg.inv(np.dot(X.T, X)), X.T), y)
return theta
def gradient_descent(X, y, theta, learning_rate, num_iters, cost_func='RSS',
):
""" Performs gradient descent to learn theta
theta = gradient_descent(x, y, theta, alpha, num_iters) updates theta
by taking num_iters gradient steps with learning rate alpha
Parameters:
-----------
X : {array-like}, shape (n_samples, n_features)
Training data. Should include intercept.
y : ndarray, shape (n_samples,)
Target values
theta : ndarray, shape (n_features,)
Regression coefficients
learning_rate : float
Controls the speed of convergence, a.k.a alpha
cost_func : cost calculation method, default to 'RSS'
Only RSS is supported for now
num_iters : int
Number of iterations
Returns
-------
calculated theta : ndarray, shape (n_features,)
Regression coefficients that minimize the cost function
cost : ndarray, shape (num_iters,)
Cost calculated for each iteration
"""
print("running gradient descent algorithm...")
# Initialize some useful values
m = len(y) # number of training examples
cost = np.zeros((num_iters,))
y = y.reshape(-1, 1)
for i in range(num_iters):
# Perform a single gradient step on the parameter vector
prediction = np.dot(X, theta) # m size vector
mean_error = prediction - y # m size vector
theta = theta - learning_rate/m * np.dot(X.T, mean_error)
# Save the cost J in every iteration
cost[i] = compute_cost(X, y, theta)
return theta, cost
def plotData(X, y, ax1=None):
train_y = pd.DataFrame(y, columns=['y'])
train = pd.concat((pd.DataFrame(X), train_y), axis=1)
# scatter plot of admitted and non-admitted exam scores
X_admitted = train.ix[train['y'] == 1, train.columns != 'y'].get_values()
X_not_admitted = train.ix[train['y'] == 0,
train.columns != 'y'].get_values()
if ax1 is None:
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
admitted = ax1.scatter(X_admitted[:, 0], X_admitted[:, 1],
color='b', marker='+')
not_admitted = ax1.scatter(X_not_admitted[:, 0], X_not_admitted[:, 1],
color='r', marker='o')
plt.xlabel('exam 1 score')
plt.ylabel('exam 2 score')
plt.legend([admitted, not_admitted], ['admitted', 'Not admitted'])
def plotDecisionBoundary(theta, X, y, poly=False):
"""Plots the data points X and y into a new figure with
the decision boundary defined by theta
plotDecisionBoundary(theta, X,y) plots the data points with + for the
positive examples and o for the negative examples. X is assumed to be
a either
1) Mx3 matrix, where the first column is an all-ones column for the
intercept.
2) MxN, N>3 matrix, where the first column is all-ones
"""
fig = plt.figure()
ax1 = fig.add_subplot(111)
# Plot Data
plotData(X, y, ax1)
if not poly:
# Only need 2 points to define a line, so choose two endpoints
plot_x = np.array([np.min(X[:, 1])-0.1, np.max(X[:, 1])+0.1])
# Calculate the decision boundary line
plot_y = (-1 / theta[2]) * (np.dot(theta[1], plot_x) + theta[0])
# Plot, and adjust axes for better viewing
ax1.plot(plot_x, plot_y)
else:
# Here is the grid range
u_orig = np.linspace(-1, 1.5, 50)
v_orig = np.linspace(-1, 1.5, 50)
# create a dataframe with all combinations of u and v
u = u_orig.repeat(len(u_orig)).reshape(-1, 1)
v = v_orig.reshape(-1, 1).repeat(len(v_orig), axis=1).T.reshape(-1, 1)
df = pd.DataFrame(np.concatenate((u, v), axis=1), columns=['c1', 'c2'])
# create polynomial features
poly = polynomial_features(df, columns=['c1', 'c2'], degree=6)
# add intercept
X = np.concatenate((np.ones((len(poly), 1)),
poly.get_values()), axis=1)
# Evaluate z = theta*x over the grid
z = np.dot(X, theta)
z = z.reshape(len(u_orig), len(v_orig)) # important to transpose z before calling contour
# Plot z = 0
# Notice you need to specify the range [0, 0]
CS = plt.contour(u_orig, v_orig, z)
plt.clabel(CS, inline=1, fontsize=10)
plt.show()
def polynomial_features(df, columns, degree=2, include_bias=False,
copy=True):
""" Convert the columns provided a san input to polynomial features.
Columns in the input dataframe not part of "columns" parameters
are not touched.
Parameters
----------
df : pandas DataFrame
The training/test input samples.
columns: list of columns where polynomial features will be generated
degree: degree of the polynomial that will be generated
include_bias: include bias or not
copy: leave the input dataframe intact when generating output dataframe
Returns
-------
Dataframe with "columns" replaced with polynomials
"""
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree, include_bias=include_bias)
X = df[columns].get_values()
X_poly = poly.fit_transform(X)
target_feature_names = []
power_columns = [zip(df[columns], p) for p in poly.powers_]
for power_column in power_columns:
powers = []
for pair in power_column:
if pair[1] != 0:
if pair[1] == 1:
powers.append('{}'.format(pair[0]))
else:
powers.append('{}^{}'.format(pair[0], pair[1]))
target_feature_names.append('x'.join(powers))
df_poly = pd.DataFrame(X_poly, columns=target_feature_names)
if copy:
df_output = df.copy()
else:
df_output = df
df_output.drop(columns, axis=1, inplace=True)
df_output.reset_index(inplace=True)
return pd.concat((df_output, df_poly), axis=1)
Nfeval = 1
def callbackF(Xi):
global Nfeval
global X_scaled, y
g = compute_gradient(Xi, X_scaled, y)
print ('{0:4d} {1: 3.6f} {2: 3.6f} {3: 3.6f} {4: 3.6f}'.format(Nfeval,
_logisticCostFunc(Xi, X_scaled, y), g[0], g[1], g[2]))
Nfeval += 1
if __name__ == "__main__":
# load data
train = pd.read_csv('ex2data2.txt',
names=['x1', 'x2', 'y']) # pylint: disable-msg=C0103
print('train.shape = {0}'.format(train.shape))
X = train.ix[:, train.columns != 'y'].get_values()
y = train['y'].get_values()
print('Shape of X,y = ({0},{1})'.format(X.shape, y.shape))
plotData(X, y)
# add additional features
train_poly = polynomial_features(train.ix[:, train.columns != 'y'],
['x1', 'x2'], degree=6)
# scale the input to zero mean and standard deviation of 1
# scaler = preprocessing.StandardScaler()
# scaler.fit(train_poly.get_values())
# X_scaled = scaler.transform(train_poly.get_values())
# commented out scaling. It creates very small values causing issues with
# minimization
X_scaled = train_poly.get_values()
# add intercept term to X_scaled
X_scaled = np.concatenate((np.ones((X.shape[0], 1)),
X_scaled), axis=1)
print('Shape of X_scaled: {0}'.format(X_scaled.shape))
# Init Theta
theta = np.zeros((X_scaled.shape[1], ))
print('cost = {}'.format(compute_cost(theta, X_scaled, y, 'logistic')))
print('gradient = {}'.format(compute_gradient(theta, X_scaled, y)))
# [xopt, fopt, gopt, Bopt, func_calls, grad_calls,
# warnflg] = optimize.fmin_bfgs(_logisticCostFunc, theta,
# fprime=compute_gradient,
# args=(X_scaled, y),
# callback=callbackF,
# maxiter=2000,
# full_output=True,
# retall=False)
xopt = optimize.minimize(_logisticCostFunc, theta, # method='Powell',
jac=compute_gradient, args=(X_scaled, y),
callback=callbackF,
options={'gtol': 1e-6, 'disp': True})
print('optimized theta with bfgs= {}'.format(xopt.x))
# calculate minimum cost
# print('minimum cost: {0}'.format(
# _logisticCostFunc(theta_optimized, X_scaled, y)))
# plot data wiht a decision boundary
plotDecisionBoundary(xopt.x, X, y, poly=True)
|
import socket
def draw_board(content):
if len(content) != 9:
# board content len error
return
print('Current board:\n')
print(f'|{content[0]}|{content[1]}|{content[2]}|\n')
print(f'|{content[3]}|{content[4]}|{content[5]}|\n')
print(f'|{content[6]}|{content[7]}|{content[8]}|\n')
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 7777))
# print welcome messag from server
print(client_socket.recv(1024).decode())
# print match info from server
print(client_socket.recv(1024).decode())
# confirmation to server that the player is ready to start
client_socket.send(b'ready')
while True:
board_content = client_socket.recv(11).decode()
print(board_content)
draw_board(board_content)
command = client_socket.recv(6).decode().strip()
if command == 'YES':
while True:
try:
move = int(input('Your turn! Enter a position (1-9)>>>'))
if move in range(1, 10):
if board_content[move-1] != ' ':
# error
print('''That position is not
empty. Please choose another one''')
else:
# user input is valid
break
else:
# error
print('Please enter a value in range 1-9')
except ValueError as err:
# error
print('Move value have wrong type')
client_socket.sendall(str(move).encode())
elif command == 'NO':
print('Wait for the other player move...')
elif command == 'DRAW':
print('It\'s draw')
break
elif command == 'WIN':
print('You win!!!')
break
elif command == 'LOSE':
print('You lose')
break
client_socket.shutdown(socket.SHUT_RDWR)
client_socket.close()
|
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
N = len(nums)
for i in range(N - 1):
# print(output[i])
if nums[i] == nums[i + 1]:
del nums[i]
else:
i += 1
return nums
number_list = [1, 1, 2]
print(Solution.removeDuplicates(Solution, number_list))
|
import math
import sys
testlist = [(1, 3), (2, 5), (10, 6), (14, 15), (13, 14), (45, 81)]
min_distance = sys.maxsize
closest_points = [testlist[0], testlist[1]]
for point in testlist:
i = testlist.index(point) + 1
for second_point in testlist[i:]:
y_length = second_point[1] - point[1]
x_length = second_point[0] - point[0]
distance = math.sqrt(y_length**2 + x_length**2)
if distance < min_distance:
min_distance = distance
closest_points = [point, second_point]
print(closest_points)
|
def list_vertices(g):
# Your code here
vertices = []
for i in g:
vertices.append(i)
return vertices
l = {1:[2, 4], 2:[3, 4], 3:[4], 4:[5], 5:[1]}
print(list_vertices(l)) |
import json
import os
import crypt
import getpass
#Constants
file_name = "data.json"
def login_validation(database_name, user_dict):
'''
returns True if account is found in the database,
and False otherwise.
'''
# account_exists = False
with open(database_name, 'r') as file:
data = file.read()
data += '\n]'
info = json.loads(data)
for account in info:
if account['email'] == user_dict['email'] and account['password'] == user_dict['password']:
return True
print("email and password were not a match")
return False
def email_validation(database_name, user_dict):
'''
returns True if email is in use,
False otherwise
'''
with open(database_name, 'r') as file:
data = file.read()
data += '\n]'
info = json.loads(data)
for account in info:
if account['email'] == user_dict['email']:
print("Email is already in use!")
return True
return False
def detect_user_status():
'''
returns True if user has account,
False otherwise
'''
while True:
_answer = input().lower()
if _answer == 'quit':
quit()
if _answer == 'yes':
return True
break
elif _answer == 'no':
return False
else:
print("please input either 'yes' or 'no'")
def invalid_input(input):
'''
returns True if input error detected,
False otherwise
'''
b_invalid = False
if input == 'exit':
quit()
if input.isspace():
b_invalid = True
if input == '':
b_invalid = True
if len(input) < 4:
b_invalid = True
if b_invalid:
print("please give a valid non empty input >4 characters")
return b_invalid
def database_handler(file_name, user_dictionary):
'''
creates database if the json file isn't created,
and appends to database otherwise
'''
file_path = os.getcwd() + "/{}".format(file_name)
if os.path.exists(file_path) == False:
print("Creating new File")
with open(file_name,"w+") as file:
file.write('[\n')
json.dump(user_dictionary, file, indent=4)
else:
print("Appending")
with open(file_name,"a") as file:
file.write(',\n')
json.dump(user_dictionary, file, indent=4)
def hash_password(password):
return crypt.crypt(password, crypt.METHOD_SHA512)
if __name__ == "__main__":
print("**********************************************************")
print("*********** REMINDER: type 'exit' at any time to quit ***********")
print("**********************************************************")
print("Do you have an account? (yes/no)")
has_account = detect_user_status()
user_dictionary = {"email":"", "password":""}
if not has_account:
while True:
print("Enter an email for your account:")
user_dictionary['email'] = input()
if invalid_input(user_dictionary['email']):
continue
email_used = email_validation(file_name, user_dictionary)
if not email_used:
break
while True:
user_dictionary['password'] = getpass.getpass("enter desired password:")
if invalid_input(user_dictionary['password']):
continue
user_dictionary['password'] = hash_password(user_dictionary['password'])
database_handler(file_name, user_dictionary)
break
else:
while True:
print("Enter your email:")
user_dictionary['email'] = input()
if invalid_input(user_dictionary['email']):
continue
user_dictionary['password'] = getpass.getpass("Enter your password:")
if invalid_input(user_dictionary['password']):
continue
user_dictionary['password'] = hash_password(user_dictionary['password'])
break
login_status = login_validation(file_name, user_dictionary)
if login_status:
print("Login successful")
else:
print("Login failed. Exiting")
#test if files append when you already have an account, and that login only occurs when account is found.
#end
quit()
|
from collections import defaultdict
from heapq import *
def dijkstra(edges, f, t): #edges = lista dei link | f = nodo di partenza (from) | t = nodo di arrivo (to)
g = defaultdict(list) #dizionario dove ad ogni nodo viene fatto corrispondere un nodo raggiungibile da esso e il peso per raggiungerlo
for link in edges: #l = nodo partenza | r = nodo arrivo | c = weight
id = link.id
l = link.start.id
r = link.exit.id
c = len(link.components)
"""
print("------")
print("ID =", id)
print("START =", l)
print("END =", r)
print("WEIGHT =", c)
"""
g[l].append((c,r,id)) #salva per ogni nodo i movimenti che può fare verso un altro nodo e il peso di tale movimento
g[r].append((c,l,id)) #salva anche il collegamento opposto
#print(g)
q, seen, mins = [(0,f,(),None)], set(), {f: 0} #q = lista di tuple (peso per il nodo da raggiungere, nodo da raggiungere, nodi precedenti da attraversare per raggiungerlo, link da cui raggiungerlo) | seen = set dei nodi già visistati | mins = dizionario in cui ad ogni nodo si fa corrispondere la distanza minima per raggiungerlo dal nodo di partenza
while q: #fintanto che è presente qualche elemento in q
#print(q)
(cost,v1,path, link) = heappop(q) #prende ed elimina il nodo con il minor costo da q
#print("cost=",cost,"v1=",v1,"path:",path)
#print (v1 not in seen)
if v1 not in seen: #se il nodo preso non è in seen
seen.add(v1) #viene aggiunto in seen
#print("seen=",seen)
tmpPath = (v1, link)
path += ((v1, link),) #viene aggiunto al path
#print("path=",path)
#print(v1 == t)
if v1 == t: #se il nodo è il punto di arrivo si conclude l'algoritmo
return (cost, path)
for c, v2, lk in g.get(v1, ()): #prende tutti i nodi collegati al nodo v1 | c = costo per il nodo raggiungibile | v2 = nodo raggiungibile | lk = id del link
#print("c=",c,"v2=",v2, "link=",lk)
#print(v2 in seen)
if v2 in seen: continue #se v2 è in seen (quindi è già stato visitato) si passa al prossimo nodo collegato a v1
prev = mins.get(v2, None) #si prende la distanza minima precedente trovata per raggiungere v2 (None se non se fosse trovata una prima)
next = cost + c #si calcola il nuovo costo trovato per raggiungere 2
if prev is None or next < prev: #se il costo precedente non esiteva o è superiore al nuovo costo trovato
#print("link usato")
mins[v2] = next #la distanza minima per v2 viene cambiata nel nuovo costo
heappush(q, (next, v2, path, lk)) #viene aggiunto a q la tupla con (costo minimo per raggiungere v2, v2, percroso minimo per raggiungere v2)
return float("inf")
if __name__ == "__main__":
edges = [
("1", "2", 1),
("1", "2", 1),
("1", "3", 8),
("1", "6", 7),
("2", "3", 2),
("2", "6", 5),
("3", "4", 2),
("3", "5", 2),
("4", "4", 3),
("4", "5", 1),
("5", "6", 1),
("5", "6", 3)
]
print("=== Dijkstra ===")
print (edges)
print ("1 -> 6:")
weight, path = dijkstra(edges, "1", "6")
print ("WEIGHT : "+str(weight))
print ("PATH : "+str(path))
print ("5 -> 2:")
weight, path = dijkstra(edges, "5", "2")
print("WEIGHT : " + str(weight))
print("PATH : " + str(path))
print ("4 -> 6:")
weight, path = dijkstra(edges, "4", "6")
print("WEIGHT : " + str(weight))
print("PATH : " + str(path))
print ("3 -> 4:")
weight, path = dijkstra(edges, "3", "4")
print("WEIGHT : " + str(weight))
print("PATH : " + str(path)) |
#1. Write a code to verify if the string is a palindrome
str1=input("Enter a string:")
if(str1==str1[::-1]):
print("The string is a palindrome")
else:
print("The string is not a palindrome") |
# -*- coding: utf-8 -*-
print "medio de tres numeros"
def entra():
a = int(raw_input("numero 1:"))
b = int(raw_input("numero 2:"))
c = int(raw_input("numero 3:"))
sale(a, b, c)
def sale(a, b, c):
if a < b:
if b < c:
print "el medio es %d" % b
elif a < c:
print "el medio es %d" % c
else:
print "el medio es %d" % a
elif a < c:
print "el medio es %d" % a
elif c < b:
print "el medio es %d" % b
else:
print "el medio es %d" % c
def mein():
entra()
|
# -*- coding: utf-8 -*-
import math
print "ecuacion cuadratica"
def entra():
a = int(raw_input("numero 1:"))
b = int(raw_input("numero 2:"))
c = int(raw_input("numero 3:"))
x = b ^ 2 - 4 * a * c
return calcula(a, b, c, x)
def calcula(a, b, c, x):
if a == 0:
print "no se puede dividir"
else:
x = (-b) + math.sqrt (b) * (-4 * a * c) / 2 * a
x = (-b) - math.sqrt (b) * (-4 * a * c) / 2 * a
if x > 0:
print " es pisitiva"
else:
print "es negativo"
return
entra()
|
#interpolation module
#takes 2 two-dimensional points and interpolates for a point in between them
#author: shulkasr
def interpolate(two_dim_array,interpPoint):
x1 = two_dim_array[0][0] if two_dim_array[0][0] <= two_dim_array[1][0] else two_dim_array[1][0]
y1 = two_dim_array[0][1] if two_dim_array[0][0] <= two_dim_array[1][0] else two_dim_array[1][1]
x2 = two_dim_array[1][0] if two_dim_array[0][0] <= two_dim_array[1][0] else two_dim_array[0][0]
y2 = two_dim_array[1][1] if two_dim_array[0][0] <= two_dim_array[1][0] else two_dim_array[0][1]
print "1:",x1,y1,"2:",x2,y2
slope = (y2-y1)/(x2-x1)
constant = (y1*x2-y2*x1)/(x2-x1)
interPolatedPoint = slope*interpPoint + constant
return interPolatedPoint
def findClosestPoints(windspeed_list,inputPoint):
#assumes sorted windspeed_list
if inputPoint < windspeed_list[0]:
closest1 = -1
closest2 = -1
elif inputPoint > windspeed_list[-1]:
closest1 = -1
closest2 = -1
else:
closest1 = min(windspeed_list, key=lambda x:abs(x-inputPoint))
if closest1==inputPoint:
closest2 = closest1
elif closest1 < inputPoint:
closest2 = windspeed_list[windspeed_list.index(closest1)+1]
elif closest1> inputPoint:
closest2 = windspeed_list[windspeed_list.index(closest1)-1]
return sorted([closest1,closest2])
if __name__ == '__main__':
intPoint = interpolate([(21.4,5),(21,10)],21.1)
print intPoint
print findClosestPoints([0.5,1.0,1.5,2.0,2.5,3.0],4.25)
|
from random import randint
from time import sleep
def hallway():
inventory = []
lockedDoor=5
hallDoors =[1,2,3,4]
doorOption = [ 'N','n','Y','y']
deathDoor = hallDoors.pop(randint(0,len(hallDoors)-1))
keyDoor = hallDoors.pop(randint(0,len(hallDoors)-1))
coinDoor = hallDoors.pop(randint(0,len(hallDoors)-1))
trapDoor = hallDoors.pop(0)
print('You find yourself standing in front of a long, dark hallway.')
print('There are five doors. Two on either side, and one at the end.')
print('As you inspect the hallway you find the doors are numbered, with 5 at the end.')
print('The doors have even numbers on the right, with odd numbers on the left.')
print('The voice returns...')
sleep(10)
print()
print('"One of these doors are locked... make it through..."')
print()
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
doorsOptions = [0,1,2,3,4,5]
doorsUnvisit = [0,1,2,3,4,5]
while doorChoice!=lockedDoor or 'key' not in inventory:
while doorChoice not in doorsOptions:
if doorChoice.isdigit()== True and 0 <= int(doorChoice) <= 5:
doorChoice = int(doorChoice)
else:
print('That is not an option')
print()
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
continue
if doorChoice not in doorsUnvisit:
print('There is nothing left in this room for you.')
print()
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
continue
if doorChoice==0:
print('You find yourself standing in front of a long, dark hallway.')
print('There are five doors. Two on either side, and one at the end.')
print('As you inspect the hallway you find the doors are numbered, with 5 at the end')
print('The doors have even numbers on the right, with odd numbers on the left')
print()
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if doorChoice==lockedDoor and 'key' not in inventory:
print('The door is locked...')
print()
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if doorChoice==0:
print('You find yourself standing in front of a long, dark hallway.')
print('There are five doors. Two on either side, and one at the end.')
print('As you inspect the hallway you find the doors are numbered, with 5 at the end')
print('The doors have even numbers on the right, with odd numbers on the left')
print()
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if doorChoice==trapDoor:
choice=input('You smell an errie oder... Do you open the door?(Y or N): ')
print()
while choice not in doorOption:
choice=input('You smell an errie oder... Do you open the door?(Y or N): ')
print()
if choice=='N' or choice=='n':
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if choice=='Y' or choice=='y':
print('There appears to be the decomposing corpse of the last person...')
print('Better leave now.')
print()
doorsUnvisit.remove(doorChoice)
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if doorChoice==deathDoor:
choice=input('The door handle is hot... Do you open it?(Y or N): ')
print()
while choice not in doorOption:
choice=input('The door handle is hot... Do you open it?(Y or N): ')
print()
if choice=='N' or choice=='n':
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if choice=='Y' or choice=='y':
sleep(3)
print('A monsterous wall of fire pours forth from the open door!')
print('You try to run as a scaley hand shoots out and drags you to your death...')
print()
return False
break
if doorChoice==coinDoor:
choice=input('There is a strong smell of metal... Do you proceed?(Y or N): ')
print()
while choice not in doorOption:
choice=input('There is a strong smell of metal... Do you proceed?(Y or N): ')
print()
if choice=='N' or choice=='n':
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if choice=='Y' or choice=='y':
print('There is only a small nightstand with a latch in the corner.')
print()
choice=input('Do you open it?: ')
print()
while choice not in doorOption:
choice=input('Do you open it?: ')
print()
if choice=='N' or choice=='n':
print('You choose to ignore the dest and proceed back to the hallway.')
print()
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if choice=='Y' or choice=='y':
print('You open the drawer and find some coins!')
inventory+=['coins']
print('"coins" are added to the inventory')
print('You exit and reenter the hallway.')
print()
doorsUnvisit.remove(doorChoice)
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if doorChoice==keyDoor and 'coins' not in inventory:
choice=input('The door is quite warped... enter anyway?(Y or N): ')
print()
while choice not in doorOption:
choice=input('The door is quite warped... enter anyway?(Y or N): ')
print()
if choice=='N' or choice=='n':
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if choice=='Y' or choice=='y':
print('There are strange slots in the wall...')
print('You leave the room since there is nothing you can do.')
print()
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if doorChoice==keyDoor and 'coins' in inventory:
choice=input('The door is quite warped... Enter anyway?(Y or N): ')
print()
while choice not in doorOption:
choice=input('The door is quite warped... Enter anyway?(Y or N): ')
print()
if choice=='N' or choice=='n':
doorChoice=input('Which door do you choose?(only #s 1-5 and press 0 to repeat): ')
print()
if choice=='Y' or choice=='y':
print('There are strange slots in the wall...')
print('You insert the coins into the slots.')
inventory = []
print('There is a loud rumble as gears start to turn and key pops out!')
print()
inventory+=['key']
print('"key" is added to the inventory')
print()
doorChoice=input('Which door do you choose?(only #s and press 0 to repeat): ')
print()
if doorChoice==lockedDoor and 'key' in inventory:
print('You pull out the key and it fits in the door!')
inventory.remove('key')
print('The door opens and you proceed to the next room...')
print()
sleep(3)
return True
break
|
def merge_sort(data_list):
def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left[0])
del left[0]
else:
result.append(right[0])
del right[0]
while len(left) > 0:
result.append(left[0])
del left[0]
while len(right) > 0:
result.append(right[0])
del right[0]
return result
if len(data_list) <= 1:
return data_list
mid = len(data_list) // 2
left_list = data_list[:mid]
right_list = data_list[mid:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return merge(left_list, right_list) |
"""A class for creating a timer widget."""
from kivy.clock import Clock
import kivy.properties as props
from kivy.uix.widget import Widget
class Timer(Widget):
"""Used to dynamically display the current time elapsed on the screen."""
# initializes a timer with 0 seconds.
timeText = props.NumericProperty(0)
def __init__(self, **kwargs):
super(Timer, self).__init__(**kwargs)
# need dt to relate update of time to frames per second
def update_time(self, dt):
"""Updates the time elapsed."""
self.timeText += 1 * dt
def reset_time(self):
"""Resets the time elapsed."""
self.stop_time()
self.timeText = 0
self.start_time()
def start_time(self):
"""Begins a clock interval running at 60 FPS calling update_time"""
Clock.schedule_interval(self.update_time, 1.0 / 60.0)
def stop_time(self):
"""Stops time."""
Clock.unschedule(self.update_time)
|
import turtle
'''
turtle.showturtle()
turtle.color("red")
turtle.forward(120)
turtle.write("1", font=('adobe garamond', 20, 'normal'))
turtle.right(90)
turtle.color("yellow")
turtle.forward(50)
turtle.write(" 2", font=('adobe garamond', 20, 'normal'))
turtle.right(90)
turtle.color("green")
turtle.forward(120)
turtle.write("3", font=('adobe garamond', 20, 'normal'))
turtle.right(90)
turtle.color("blue")
turtle.forward(50)
turtle.write("4", font=('adobe garamond', 20, 'normal')) '''
radius=int(input("Enter the desired radius: "))
halfRadius=radius/2
diameter=2*radius
y_startCord1=0
y_move1=-radius
cubeDiamter=diameter*3
x_start=-(cubeDiamter/2) #+(halfRadius))
x_move1=diameter+(halfRadius)
x_move2=radius+(radius/4)
blue=x_start
black=blue+x_move1
red=black+x_move1
yellow=blue+x_move2
green=black+x_move2
fontSize=radius
'''
circles=[blue, black, red, yellow, green]
colours={blue:"blue", black:"black", red:"red", yellow:"yellow", green:"green"}
for i in range(5):
if i <= 3:
turtle.color(colours[circles[i]])
turtle.goto(circles[i], y_startCord1)
turtle.pendown()
turtle.circle(radius)
turtle.penup()
elif i > 3:
turtle.color(colours[circles[i]])
turtle.goto(circles[i], y_move1)
turtle.pendown()
turtle.circle(radius)
turtle.penup()
'''
ts=turtle.getscreen()
ts.bgcolor("pink")
turtle.pensize(5)
turtle.color("blue")
turtle.penup()
turtle.goto(blue, y_startCord1) #turtle.goto(x, y)
turtle.pendown()
turtle.circle(radius)
turtle.color("black")
turtle.penup()
turtle.goto(black, y_startCord1)
turtle.pendown()
turtle.circle(radius)
turtle.color("red")
turtle.penup()
turtle.goto(red, y_startCord1)
turtle.pendown()
turtle.circle(radius)
turtle.color("yellow")
turtle.penup()
turtle.goto(yellow, y_move1)
turtle.pendown()
turtle.circle(radius)
turtle.color("green")
turtle.penup()
turtle.goto(green, y_move1)
turtle.pendown()
turtle.circle(radius)
turtle.color("maroon")
turtle.penup()
turtle.goto(0, -(diameter+halfRadius))
turtle.pendown()
turtle.write("Olympics", align='center', font=('Calibri', fontSize, 'normal'))
'''turtle.color("yellow")
turtle.write("Olympics", align='center', font=('Calibri', fontSize, 'normal'))
turtle.write("Olympics", align='center', font=('Calibri', fontSize, 'normal'))
turtle.write("Olympics", align='center', font=('Calibri', fontSize, 'normal'))
turtle.write("Olympics", align='center', font=('Calibri', fontSize, 'normal'))
'''
'''
turtle.penup()
turtle.goto(0, 100)
turtle.pendown()
turtle.write("\u6B22\u8FCE \u03b1 \u03b2 \u03b3", font=('adobe garamond', 40, 'bold'))
turtle.write("\u0000\uFFFF")
'''
input("")
|
from tkinter import *
import tkinter
master = Tk()
master.title("AUTOMATED MACHINE LEARNING")
#creating a text label
Label(master, text="AUTOMATED MACHINE LEARNING SYSTEM",font=("times new roman",20),fg="white",bg="maroon",height=2).grid(row=0,rowspan=2,columnspan=8,sticky=N+E+W+S,padx=5,pady=5)
location=StringVar()
Label(master, text='ENTER THE LOCATION OF DATASET').grid(row=2)
e1 = Entry(master,textvariable=location)
e1.grid(row=2,column=1)
y=StringVar()
Label(master, text='ENTER THE PREDICTION COLUMN').grid(row=3)
e1 = Entry(master,textvariable=y)
e1.grid(row=3,column=1)
reg = IntVar()
Checkbutton(master, text='REGRESSION', variable=reg).grid(row=4, sticky=W)
clas = IntVar()
Checkbutton(master, text='CLASSIFICATION', variable=clas).grid(row=5, sticky=W)
Label(master, text='TRAIN_TEST_SPLIT_SIZE [0-100]').grid(row=4,column=1)
Label(master, text='NUMBER OF FOLDS').grid(row=5,column=1)
train_test=IntVar()
num_folds=IntVar()
e1 = Entry(master,textvariable=train_test)
e2 = Entry(master,textvariable=num_folds)
e1.grid(row=4, column=2)
e2.grid(row=5, column=2)
Label(master, text='SCORING METRICS').grid(row=6)
mse = IntVar()
Checkbutton(master, text='MSE', variable=mse).grid(row=7, sticky=W)
mae = IntVar()
Checkbutton(master, text='MAE', variable=mae).grid(row=8, sticky=W)
acc = IntVar()
Checkbutton(master, text='ACCURACY', variable=acc).grid(row=9, sticky=W)
mainloop()
print(reg.get(),clas.get(),num_folds.get(),train_test.get(),mse.get(),mae.get(),acc.get(),y.get(),location.get())
machinelearning(location.get(),y.get(),train_test.get(),num_folds.get(),reg.get(),'mae')
def machinelearning(X,Y,train_test,num_folds,reg,metrics):
def importregressionmodels():
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
models = []
models.append(('LR', LinearRegression()))
models.append(('KNN', KNeighborsRegressor()))
models.append(('CART', DecisionTreeRegressor()))
models.append(('RF', RandomForestRegressor()))
return models
def importclassificationmodels():
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
models = []
models.append(('LR', LogisticRegression()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('RF', RandomForestClassifier()))
models.append(('NB',GaussianNB()))
return models
## IMPORT PANDAS AND NUMPY
import pandas as pd
import numpy as np
## SPLIT THE DATA INTO TRAIN AND TEST
data=pd.read_csv(X)
x=data.drop(Y,axis=1)
y=data[[Y]]
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=train_test)
print('Runnng BASELINE models')
d=reg
if d==0:
## INTIALISING MODELS
models=importclassificationmodels()
results = []
names = []
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
## FOR BINARY AND MULTICLASS CLASSIFICATION:
#print('please enter a number 1 -> Binary Classification 2 -> Multiclass Classification')
#temp=int(input())
if reg==0:
## FOR BINARY CLASSIFICATION
## INPUT FOR KFOLD CROSS VALIDATION AND SCORING METRICS
print('ENTER num_folds FOR KFOLD CROSS VALIDATION')
num_folds = int(input())
seed = 77
print('ENTER THE SCORING METRICS 1 -> PRECISION 2 -> RECALL 3 -> F1-SCORE 4 -> ACCURACY')
f=int(input())
if f==1:
scoring='precision'
elif f==2:
scoring='recall'
elif f==3:
scoring='f1'
elif f==4:
scoring='accuracy'
elif temp==2:
print('ENTER num_folds FOR KFOLD CROSS VALIDATION')
num_folds = int(input())
seed = 77
print('ENTER THE SCORING METRICS 1 -> precision_macro 2 -> precision_micro 3 -> F1-recall_macro 4 -> accuracy')
f=int(input())
if f==1:
scoring='precision_macro'
elif f==2:
scoring='precision_micro'
elif f==3:
scoring='recall_macro'
elif f==4:
scoring='recall_micro'
elif f==5:
scoring='accuracy'
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import accuracy_score
for name, model in models:
kfold = KFold(n_splits=num_folds, random_state=seed)
cv_results = cross_val_score(model, x_train, y_train,scoring=scoring, cv=kfold)
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
print(msg)
### PARAMETER TUNING GRID SEARCH############
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(x_train)
scaledX = scaler.transform(x_train)
##### INITILASE THE VALUES FOR GRID SEARCH FOR VARIOUS PARAMETERS########
k_values = np.array([1,3,5,7,9,11,13,15,17,19,21])
max_depth=np.array([1,2,3,4,5,6,7,8,9])
min_samples_leaf=np.array([2,4,6,8,10,12,14])
param_gridknn = dict(n_neighbors=k_values)
param_griddt=dict(max_depth=max_depth,min_samples_leaf=min_samples_leaf)
## FINDING THE VARIOUS PARAMTERS FOR DIFFERENT MODELS:
for name, model in models:
if name=='KNN':
kfold = KFold(n_splits=num_folds, random_state=seed)
grid = GridSearchCV(estimator=model, param_grid=param_gridknn,cv=kfold)
grid_result = grid.fit(scaledX, y_train)
print("Best: %f using %s for %s" % (grid_result.best_score_, grid_result.best_params_,name))
elif name=='CART':
kfold = KFold(n_splits=num_folds, random_state=seed)
grid = GridSearchCV(estimator=model, param_grid=param_griddt,cv=kfold)
grid_result = grid.fit(scaledX, y_train)
print("Best: %f using %s for %s" % (grid_result.best_score_, grid_result.best_params_,name))
elif name=='RF':
kfold = KFold(n_splits=num_folds, random_state=seed)
grid = GridSearchCV(estimator=model, param_grid=param_griddt,cv=kfold)
grid_result = grid.fit(scaledX, y_train)
print("Best: %f using %s for %s" % (grid_result.best_score_, grid_result.best_params_,name))
######## FOR REGRESSION#############################
elif reg==1:
models=importregressionmodels()
results = []
names = []
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import accuracy_score
num_folds =num_folds
seed = 77
f=metrics
if f=='mse':
scoring='neg_mean_squared_error'
elif f=='mae':
scoring='neg_mean_absolute_error'
elif f=='acc':
scoring='r2'
for name, model in models:
kfold = KFold(n_splits=num_folds, random_state=seed)
cv_results = cross_val_score(model, x_train, y_train, cv=kfold,scoring=scoring)
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
print(msg)
### PARAMETER TUNING GRID SEARCH
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(x_train)
scaledX = scaler.transform(x_train)
## INITILASE THE VALUES FOR GRID SEARCH FOR VARIOUS PARAMETERS
k_values = np.array([1,3,5,7,9,11,13,15,17,19,21])
max_depth=np.array([1,2,3,4,5,6,7,8,9])
min_samples_leaf=np.array([2,4,6,8,10,12,14])
param_gridknn = dict(n_neighbors=k_values)
param_griddt=dict(max_depth=max_depth,min_samples_leaf=min_samples_leaf)
## FINDING THE VARIOUS PARAMTERS FOR DIFFERENT MODELS:
for name, model in models:
if name=='KNN':
kfold = KFold(n_splits=num_folds, random_state=seed)
grid = GridSearchCV(estimator=model, param_grid=param_gridknn,cv=kfold,scoring=scoring)
grid_result = grid.fit(scaledX, y_train)
print("Best: %f using %s for %s" % (grid_result.best_score_, grid_result.best_params_,name))
elif name=='CART':
kfold = KFold(n_splits=num_folds, random_state=seed)
grid = GridSearchCV(estimator=model, param_grid=param_griddt,cv=kfold,scoring=scoring)
grid_result = grid.fit(scaledX, y_train)
print("Best: %f using %s for %s" % (grid_result.best_score_, grid_result.best_params_,name))
elif name=='RF':
kfold = KFold(n_splits=num_folds, random_state=seed)
grid = GridSearchCV(estimator=model, param_grid=param_griddt,cv=kfold,scoring=scoring)
grid_result = grid.fit(scaledX, y_train)
print("Best: %f using %s for %s" % (grid_result.best_score_, grid_result.best_params_,name)) |
def run():
def crea_diccionario(diccionario):
nuevo_diccionario = {}
for asignatura, nota in diccionario.items():
asignatura = asignatura.upper()
if nota >= 7:
nota = 'Aprobado'
nuevo_diccionario[asignatura] = nota
return nuevo_diccionario
asignaturas_notas = {
'Español': 5,
'Matemáticas': 7,
'Inglés': 9,
'Arte': 4
}
print(crea_diccionario(asignaturas_notas))
if __name__ == '__main__':
run()
|
def contar_palabras(cadena):
cadena = cadena.split()
palabras = {}
for palabra in cadena:
if palabra in palabras:
palabras[palabra] += 1
else:
palabras[palabra] = 1
return palabras
#print(palabras)
def mas_repetida(cadena):
palabra_mas_repetida = ''
maxima_frecuencia = 0
for palabra,frecuencia in cadena.items():
if frecuencia > maxima_frecuencia:
palabra_mas_repetida = palabra
maxima_frecuencia = frecuencia
return palabra_mas_repetida , maxima_frecuencia
print(contar_palabras("hola hola hola mundo desde python"))
print(mas_repetida(contar_palabras("hola hola hola mundo desde python")))
|
from functools import reduce
def run():
#map -> map(funcion, objeto_iterable)
""" def elevar_al_cuadrado(numero):
return numero * numero
lista = [1,2,3,4,5]
resultado = list(map(elevar_al_cuadrado, lista))
print(resultado) """
#filter -> filter(funcion, objeto_iterable)
""" def mayor_a_cinco(numero):
return numero > 5
lista = [46,1,2,3,7,8]
resultado = list(filter(mayor_a_cinco, lista))
print(resultado)
def circulo(palabra):
return palabra == 'circulo'
tupla = ('hola','soy','un','circulo','circulo','circulo')
resultado2 = tuple(filter(circulo, tupla))
print(resultado2) """
#reduce -> reduce(funcion, objeto_iterable)
""" lista = [1,2,3,4]
def funcion_acumulador(acumulador, elemento):
return acumulador + elemento
resultado = reduce(funcion_acumulador, lista)
print(resultado) """
lista = ['Python', 'JavaScript', 'C#','C++','Go','Swift','Kotlin']
def funcion_acumulador(acumulador, elemento):
return acumulador + " - " + elemento
resultado = reduce(funcion_acumulador, lista)
print(resultado)
if __name__ == '__main__':
run() |
numeros = [50, 75, 46,100, 22, 80, 65, 8,1]
numeros.sort()
print(f'El número más pequeño de {numeros} es {numeros[0]}')
print(f'El número más grande de {numeros} es {numeros[-1]}') |
n = float(input("Ingresa un numerador: ")) #numerador es el de arriba
m = float(input("Ingresa un denominador: ")) #denominador es el de abajo
c = n/m
r = n%m #módulo -> regresa el residuo de una división
print(f"El resultado de dividir {n} entre {m} es {c} y su residuo es {r}") |
def run():
inmuebles = [
{'año': 2000, 'metros': 100, 'habitaciones': 3, 'garaje': True, 'zona': 'A'}, # 0
{'año': 2012, 'metros': 60, 'habitaciones': 2, 'garaje': True, 'zona': 'B'}, # 1
{'año': 1980, 'metros': 120, 'habitaciones': 4, 'garaje': False, 'zona': 'A'}, # 2
{'año': 2005, 'metros': 75, 'habitaciones': 3, 'garaje': True, 'zona': 'B'}, # 3
{'año': 2015, 'metros': 90, 'habitaciones': 2, 'garaje': False, 'zona': 'A'} # 4
]
precios = []
year = 2021
def calcula_precio_inmueble():
for inmueble in inmuebles:
for clave, valor in inmueble.items():
if inmueble['zona'] == 'A':
precio = (inmueble['metros'] * 1000 + inmueble['habitaciones'] * 5000 + inmueble['garaje'] * 15000) * (1-(year - inmueble['año'])/100)
elif inmueble['zona'] == 'B':
precio = (inmueble['metros'] * 1000 + inmueble['habitaciones'] * 5000 + inmueble['garaje'] * 15000) * (1-(year - inmueble['año'])/100) * 1.5
precios.append(precio)
return precios
def busca_inmueble(presupuesto):
print(f'Precios de los inmuebles {calcula_precio_inmueble()}')
for precio in precios:
if presupuesto >= precio:
print(f'Puede comprar el apartamento de ${precio}\n')
busca_inmueble(94000)
if __name__ == "__main__":
run()
|
monto = float(input("Monto: "))
interes = float(input("Interés: "))
anios = int(input("Años: "))
for i in range(anios):
monto = monto * (1+interes)**anios
print(f"Cantidad de dinero después de {i+1} años $ {monto}") |
print("\n\t Welcome to the Gusess Game\n\n\t You have only three atemps")
import random
for i in range(3):
ran=random.randint(1,6)
number=int(input("enter number > "))
if number==ran:
print("you Guess the number.. Congrats ")
break
else:
print("bad luck")
|
# https://blog.csdn.net/sinat_38321889/article/details/80390238
#selectSort which is a time-consuming sort algorithm.Its Time-complexity is O(N**2)
#1、we just use the simple sort algorithm to get the smallest number per loop,which the time-consuming is O(n)
#2、next we can define a function that a loop to get the small value every loop,and the append the value into a new Array
#to get the minmum value
# 选择排序
def getmin(arr):
min = arr[0];
min_index = 0;
for i in range(0,len(arr)):
if arr[i]<min:
min = arr[i]
min_index = i
return min_index
#SelectSort
def selectSort(arr):
newArr = [];
for i in range(0,len(arr)):
min = getmin(arr);
newArr.append(arr.pop(min))
return newArr;
#test the output
a = [4,6,9,1,3,87,41,5]
print(selectSort(a)) # [1, 3, 4, 5, 6, 9, 41, 87] |
def first_double_string(mot):
dict_char = dict()
for letter in mot:
if letter in dict_char:
dict_char[letter]+=1
print(letter)
return letter
else:
dict_char[letter]=1
return dict_char
first_double_string('abcdefa')
first_double_string('jfslsfjdl')
|
# encoding=utf-8
# -,- 回头理解清楚一下
class Solution(object):
def recur_search(self, left, right, nums, target):
if left == right:
if nums[left] == target:
return left
else:
return -1
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[mid] == nums[left]:
tmp = mid
while nums[tmp] == nums[left] and tmp > left:
tmp = tmp -1
if tmp == left:
return self.recur_search(mid+1,right,nums,target)
else: mid = tmp
if nums[mid] == target:
return mid
if nums[mid] < nums[left]:
if target >= nums[left] or target < nums[mid]:
return self.recur_search(left, mid - 1, nums, target)
else:
return self.bin_search(mid + 1, right, nums, target)
if target >= nums[left] and target < nums[mid]:
return self.bin_search(left, mid - 1, nums, target)
else:
return self.recur_search(mid + 1, right, nums, target)
def bin_search(self, left, right, nums, target):
if target < nums[left] or target > nums[right]:
return -1
if left == right:
if nums[left] == target:
return left
else:
return False
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[mid] > target:
return self.bin_search(left, mid - 1, nums, target)
else:
return self.bin_search(mid + 1, right, nums, target)
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return False
x = self.recur_search(0, len(nums) - 1, nums, target)
if x >= 0:
print x
return True
else: return False
if __name__ == '__main__':
so = Solution()
a = [1,3,1]
tar = 2
print so.search(a,tar)
|
import pandas as pd
import numpy as np
dfx = pd.read_csv("data.csv")
dataset = dfx.values
print(dataset)
res = []
n = dataset.shape[1]-1
for i in range(n):
res.append('Φ')
print("The initial value of hypothesis:")
print(res)
print()
for i in dataset:
if i[-1] == 'Yes':
for j in range(len(i)-1):
if(res[j] == '?'):
pass
elif (res[j] == i[j]) or (res[j]=='Φ'):
res[j] = i[j];
else:
res[j] = '?'
print(res)
else:
print(res)
print("\nFinal Hyposthesis : ",res)
|
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
s = "a b c d e f"
# split adds individual characters to a list
z = s.split()
print(z)
if 'a' in z:
print("A is in z")
else:
print("A is not in z")
for i in z:
print(i)
# sort sorts by ascending order
g = [4, 5, 3, 2, 7]
g.sort()
print(g)
g.reverse()
print(g)
|
"""
This example shows how to use the Mesh class in order
to generate a geometry similar to those that may define
a lifting surface planform.
X ^ B This geometry is positioned in space
| +---+ with two chords simulating the root
| / | and tip chords, using points A and B
| / | b to store their respective leading edge
|/ | coordinates.
+-------+---->
A c Y With the parameters n and m the grid
density in the chordwise and spanwise
directions will be defined.
"""
import numpy as np
import matplotlib.pyplot as plt
from pyvlm.mesh_generator import Mesh
# GEOMETRY DEFINITION #
# Parameters
c = 1 # root chord length
b = 10 # panel span length
n = 10 # number of panels chordwise
m = 20 # number of panels spanwise
# Wing
A = np.array([0, 0]) # root chord leading edge coordinates
B = np.array([c/2, b]) # tip chord leading edge coordinates
leading_edges_coord = [A, B]
chord_lengths = [c, c/2]
mesh = Mesh(leading_edges_coord, chord_lengths, n, m)
Points = mesh.points()
Panels = mesh.panels()
Chordwise_panel_pos = mesh.panel_chord_positions()
Panels_span = mesh.panels_span()
# PRINTING AND PLOTTING
print('\n Point | Coordinates ')
print('--------------------------')
for i in range(0, len(Points)):
print(' %2s |' % i, np.round(Points[i], 2))
print('\n Panel | Chrd % | Span | Points coordinates')
print('----------------------------------------------------------------------')
for i in range(0, len(Panels)):
print(' %3s | %4.1f | %6.2f | '
% (i, 100*Chordwise_panel_pos[i], Panels_span[i]),
np.round(Panels[i][0], 2), np.round(Panels[i][1], 2),
np.round(Panels[i][2], 2), np.round(Panels[i][3], 2))
plt.style.use('ggplot')
plt.xlim(0, c), plt.ylim(0, b)
for i in range(0, len(Points)):
P = Points[i]
plt.plot(P[0], P[1], 'ro')
plt.show()
|
# Translate one language to the other using the translate library!
from translate import Translator
def trans():
global user_statement
user_statement =input('Type the statement you want to translate: ')
print()
langauge_type = input('Which language will you like to translate it to? ')
m = langauge_type.lower() #Converts the user selection to lowercase letters
if m == 'french':
translator = Translator(to_lang="french")
trans = translator.translate(user_statement)
elif m == 'spanish':
translator = Translator(to_lang="spanish")
trans = translator.translate(user_statement)
elif m == 'arabic':
translator = Translator(to_lang="arabic")
trans = translator.translate(user_statement)
elif m == 'hindu':
translator = Translator(to_lang="hindu")
trans = translator.translate(user_statement)
elif m == 'german':
translator = Translator(to_lang="german")
trans = translator.translate(user_statement)
elif m == 'chinese':
translator = Translator(to_lang="chinese")
trans = translator.translate(user_statement)
elif m == 'portugese':
translator = Translator(to_lang="portugese")
trans = translator.translate(user_statement)
elif m == 'english':
translator = Translator(from_lang="spanish", to_lang="english") #Translate from spanish to english if the user input is spanish.
trans = translator.translate(user_statement)
else:
print('Cannot translate your statement into the given language')
return print(trans)
trans()
|
# Write a python program to find sum of the first n positive integers.
# sum = ( n * ( n + 1)) / 2
list=[1,2,3,4,5,6,7,8,9,10]
total=sum(list)
print(f"The sum of the give integer is {total}") |
# 3. BMI 指数测试
weight = float(input('请输入体重(公斤):'))
height = float(input('请输入身高(米):'))
height_square = height ** 2
bmi = weight / height_square
min_weight = height_square * 18.5
max_weight = height_square * 24
print('您的BMI指数为: %.2f ' % bmi)
print('正常体重范围是%.2f公斤 - %.2f公斤 之间' %(min_weight, max_weight))
if bmi < 18.5:
print('体重偏轻')
print('建议您至少增重 %.2f 公斤' % (min_weight - weight))
elif bmi >= 24:
print('体重偏重')
print('建议您至少减重 %.2f 公斤' % (weight - max_weight))
else:
print('体重正常')
|
"""
Program: NumPy_array_math.py
Author: Daniel Meeker
Date: 9/17/2020
This program demonstrates using NumPy in Python.
"""
import numpy as np
if __name__ == '__main__':
array_1 = np.array([[10, 15, 20], [2, 3, 4], [9, 14.5, 18]])
array_2 = np.array([[1, 2, 5], [8, 0, 12], [11, 3, 22]])
array_1_even = array_1 % 2 == 0
array_1_slice = array_1[0:2, 0:2]
array_sum = np.add(array_1, array_2)
array_multiply = np.multiply(array_1, array_2)
# Print array_1 to the console
print(array_1)
# Print array_1's shape
print(array_1.shape)
# Print a 2x2 slice starting at 0,0 and going to 1,1
print(array_1_slice)
# Output a boolean on whether an element is even or odd
print(array_1_even)
# Add the two arrays together elementwise
print(array_sum)
# Multiply the arrays together elementwise
print(array_multiply)
# Print the sum of all elements in array_2
print(array_2.sum())
# Print the product of all elements in array_2
print(array_2.prod())
# Print the max value of all elements in array_2
print(array_2.max())
# Print the min value of all elements in array_2
print(array_2.min())
|
my_votes = int(input("How many votes did you get in the election? "))
total_votes = int(input("What is the total votes in the election? "))
print(f"I received {my_votes / total_votes * 100}% of the total votes.")
my_votes = int(input("How many votes did you get in the election? "))
total_votes = int(input("What is the total votes in the election? "))
percentage_votes = (my_votes / total_votes) * 100
print("I received " + str(percentage_votes)+"% of the total votes.")
counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438}
for key, value in counties_dict.items():
print(f" {key:} county has {value:,} registered voters.)")
voting_data = [``{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}]
for county, reg_vot in voting_data.items():
print(f" {county:} county has {reg_vot:,} registered voters.)") |
#!/usr/bin/env python
# coding: utf-8
"""
A simple VM interpreter.
Code from the post at http://csl.name/post/vm/
This version should work on both Python 2 and 3.
"""
from __future__ import print_function
from collections import deque
from io import StringIO
import sys
import tokenize
def get_input(*args, **kw):
"""Read a string from standard input."""
if sys.version[0] == "2":
return raw_input(*args, **kw)
else:
return input(*args, **kw)
class Stack(deque):
push = deque.append
def top(self):
return self[-1]
class Machine:
log = ""
def __init__(self, code):
self.data_stack = Stack()
self.return_stack = Stack()
self.instruction_pointer = 0
self.code = code
def pop(self):
return self.data_stack.pop()
def push(self, value):
self.data_stack.push(value)
def top(self):
return self.data_stack.top()
def run(self):
while self.instruction_pointer < len(self.code):
opcode = self.code[self.instruction_pointer]
self.instruction_pointer += 1
self.dispatch(opcode)
def dispatch(self, op):
dispatch_map = {
"%": self.mod,
"*": self.mul,
"+": self.plus,
"-": self.minus,
"/": self.div,
"==": self.eq,
"cast_int": self.cast_int,
"cast_str": self.cast_str,
"drop": self.drop,
"dup": self.dup,
"exit": self.exit,
"if": self.if_stmt,
"jmp": self.jmp,
"over": self.over,
"print": self.print,
"println": self.println,
"read": self.read,
"stack": self.dump_stack,
"swap": self.swap,
}
if op in dispatch_map:
dispatch_map[op]()
elif isinstance(op, int):
self.push(op) # push numbers on stack
elif isinstance(op, str) and op[0]==op[-1]=='"':
self.push(op[1:-1]) # push quoted strings on stack
else:
raise RuntimeError("Unknown opcode: '%s'" % op)
# OPERATIONS FOLLOW:
def plus(self):
self.push(self.pop() + self.pop())
def exit(self):
sys.exit(0)
def minus(self):
last = self.pop()
self.push(self.pop() - last)
def mul(self):
self.push(self.pop() * self.pop())
def div(self):
last = self.pop()
self.push(self.pop() / last)
def mod(self):
last = self.pop()
self.push(self.pop() % last)
def dup(self):
self.push(self.top())
def over(self):
b = self.pop()
a = self.pop()
self.push(a)
self.push(b)
self.push(a)
def drop(self):
self.pop()
def swap(self):
b = self.pop()
a = self.pop()
self.push(b)
self.push(a)
def print(self):
self.log+=str(self.pop())
def println(self):
self.log+=str(self.pop())+"\n"
def read(self):
self.push(get_input())
def cast_int(self):
self.push(int(self.pop()))
def cast_str(self):
self.push(str(self.pop()))
def eq(self):
self.push(self.pop() == self.pop())
def if_stmt(self):
false_clause = self.pop()
true_clause = self.pop()
test = self.pop()
self.push(true_clause if test else false_clause)
def jmp(self):
addr = self.pop()
if isinstance(addr, int) and 0 <= addr < len(self.code):
self.instruction_pointer = addr
else:
raise RuntimeError("JMP address must be a valid integer.")
def dump_stack(self):
pass
def parse(text):
# Note that the tokenizer module is intended for parsing Python source
# code, so if you're going to expand on the parser, you may have to use
# another tokenizer.
if sys.version[0] == "2":
stream = StringIO(unicode(text))
else:
stream = StringIO(text)
tokens = tokenize.generate_tokens(stream.readline)
for toknum, tokval, _, _, _ in tokens:
if toknum == tokenize.NUMBER:
yield int(tokval)
elif toknum in [tokenize.OP, tokenize.STRING, tokenize.NAME]:
yield tokval
elif toknum == tokenize.ENDMARKER:
break
else:
raise RuntimeError("Unknown token %s: '%s'" %
(tokenize.tok_name[toknum], tokval))
def constant_fold(code):
"""Constant-folds simple mathematical expressions like 2 3 + to 5."""
while True:
# Find two consecutive numbers and an arithmetic operator
for i, (a, b, op) in enumerate(zip(code, code[1:], code[2:])):
if isinstance(a, int) and isinstance(b, int) \
and op in {"+", "-", "*", "/"}:
m = Machine((a, b, op))
m.run()
code[i:i+3] = [m.top()]
print("Constant-folded %s%s%s to %s" % (a,op,b,m.top()))
break
else:
break
return code
def repl():
print('Hit CTRL+D or type "exit" to quit.')
while True:
try:
source = get_input("> ")
code = list(parse(source))
code = constant_fold(code)
Machine(code).run()
except (RuntimeError, IndexError) as e:
print("IndexError: %s" % e)
except KeyboardInterrupt:
print("\nKeyboardInterrupt")
def test(code = [2, 3, "+", 5, "*", "println"]):
print("Code before optimization: %s" % str(code))
optimized = constant_fold(code)
print("Code after optimization: %s" % str(optimized))
print("Stack after running original program:")
a = Machine(code)
a.run()
a.dump_stack()
print("Stack after running optimized program:")
b = Machine(optimized)
b.run()
b.dump_stack()
result = a.data_stack == b.data_stack
print("Result: %s" % ("OK" if result else "FAIL"))
return result
def examples():
print("** Program 1: Runs the code for `print((2+3)*4)`")
Machine([2, 3, "+", 4, "*", "println"]).run()
print("\n** Program 2: Ask for numbers, computes sum and product.")
Machine([
'"Enter a number: "', "print", "read", "cast_int",
'"Enter another number: "', "print", "read", "cast_int",
"over", "over",
'"Their sum is: "', "print", "+", "println",
'"Their product is: "', "print", "*", "println"
]).run()
print("\n** Program 3: Shows branching and looping (use CTRL+D to exit).")
Machine([
'"Enter a number: "', "print", "read", "cast_int",
'"The number "', "print", "dup", "print", '" is "', "print",
2, "%", 0, "==", '"even."', '"odd."', "if", "println",
0, "jmp" # loop forever!
]).run()
if __name__ == "__main__":
try:
if len(sys.argv) > 1:
cmd = sys.argv[1]
if cmd == "repl":
repl()
elif cmd == "test":
test()
examples()
else:
print("Commands: repl, test")
else:
repl()
except EOFError:
print("")
|
#!/usr/bin/env python
"""
nn.py
Implements feedforward complete artifical neural networks.
Python 2.7.12
A 'from scratch' implementation + a few code snippets from grad school coursework.
"""
import math
import random
def sigmoid(dblX):
"""The sigmoid function. Given input dblX, sigmoid(dblX).
sigmoid(0.0)
0.5
sigmoid(100.0)
1.0
sigmoid(-100.0) < 1.0e-10
True
"""
dblActVal = float(1.0/(1.0 + pow(math.e, -dblX)))
return dblActVal
class Perceptron(object):
"""Implements a unit in a feed-forward neural network."""
def __init__(self, listDblW, dblW0, ix):
"""
listDblW: a list of weights
dblW0: the threshold weight
ix: the index of this perceptron in it's layer
"""
self.listDblW = map(float,listDblW)
self.dblW0 = float(dblW0)
self.ix = int(ix)
def __repr__(self):
tplSFormat = (list(self.listDblW), self.dblW0, self.ix)
return "Perceptron(%r, %r, %r)" % tplSFormat
def input_size(self):
return len(self.listDblW)
class NeuralNetLayer(object):
"""A single layer of a complete neural network"""
def __init__(self, cInputs, listPcpt):
"""
cInputs: number of inputs each perceptron in the layer receives.
same number in a complete network.
listPcpt: list of perceptrons in the layer. The index of each perceptron
must match its zero-indexed position in this list.
"""
self.check_consistency(cInputs, listPcpt)
self.cInputs = int(cInputs)
self.listPcpt = listPcpt
def layer_input_size(self):
"""Returns the number of inputs connected to each unit in this layer."""
return self.cInputs
def layer_output_size(self):
"""Returns the number of units in this layer."""
return len(self.listPcpt)
@classmethod
def check_consistency(cls, cInputs, listPcpt):
for ix,pcpt in enumerate(listPcpt):
if not isinstance(pcpt, Perceptron):
raise TypeError("Expected Perceptron")
if pcpt.input_size() != cInputs:
raise TypeError("Input size mismatch")
if pcpt.ix != ix:
raise ValueError("Index mismatch. Expected %d but found %d"
% (ix, pcpt.ix))
def dot(listDbl1, listDbl2):
"""Takes the dot product of two equal-length lists of floats.
dot([1.0, 2.0, 3.0], [-1.0, 0.25, 4.0])
11.5"""
if len(listDbl1) != len(listDbl2):
print listDbl1
print listDbl2
raise ValueError("Incompatible lengths")
return sum([dbl1*dbl2 for dbl1,dbl2 in zip(listDbl1,listDbl2)])
def output_error(dblActivation,dblTarget):
"""Computes the output error for perceptron activation level
dblActivation and target value dblTarget.
output_error(0.75, -1.0)
-1.75"""
return float(dblTarget - dblActivation)
def hidden_error(listDblDownstreamDelta, pcpt, layerNext):
"""Determines the error on a hidden node from downstream deltas and weights.
pcpt = Perceptron([], 0.0, 0)
listPcpt = [Perceptron([1.5],0,0), Perceptron([2.0],0,1)]
layer = NeuralNetLayer(1, listPcpt)
hidden_error([1.0, 0.75], pcpt, layer)
3.0"""
curIx = pcpt.ix
listNextWeights = map(lambda p: p.listDblW[curIx], layerNext.listPcpt)
return dot(listDblDownstreamDelta, listNextWeights)
def compute_delta(dblActivation, dblError):
"""Computes a delta value from activation and error.
compute_delta(0.5,0.5)
0.125"""
dblActivationDerv = float(dblActivation*(float(1.0) - dblActivation))
return float(dblActivationDerv*dblError)
def update_weight(dblW, dblLearningRate, dblInput, dblDelta):
"""Computes the updated weight.
update_weight(3.0, 0.1, 1.25, 2.0)
3.25"""
dblNewW = float(dblW + (dblLearningRate*dblInput*dblDelta))
return dblNewW
def update_pcpt(pcpt, listDblInputs, dblDelta, dblLearningRate):
"""Updates the perceptron's weights in place, including threshold weights.
pcpt = Perceptron([1.0,2.0,3.0], 4.0, 0)
print pcpt
Perceptron([1.0, 2.0, 3.0], 4.0, 0)
update_pcpt(pcpt, [0.5,0.5,0.5], 0.25, 2.0)
print pcpt
Perceptron([1.25, 2.25, 3.25], 4.5, 0)"""
pcpt.listDblW =\
map(lambda dblInput, dblOldW:
update_weight(dblOldW, dblLearningRate, dblInput, dblDelta),
listDblInputs, pcpt.listDblW)
dblOldW0 = pcpt.dblW0
pcpt.dblW0 = update_weight(dblOldW0, dblLearningRate, 1.0, dblDelta)
return None
def pcpt_activation(pcpt, listDblInput):
"""Compute a perceptron's activation function.
pcpt = Perceptron([0.5,0.5,-1.5], 0.75, 0)
pcpt_activation(pcpt, [0.5,1.0,1.0])
0.5"""
dblNoThreshDotInput = dot(listDblInput, pcpt.listDblW)
dblDotInput = dblNoThreshDotInput + pcpt.dblW0
return sigmoid(dblDotInput)
def feed_forward_layer(layer, listDblInput):
"""Build a list of activation levels for the perceptrons in the layer
recieving input listDblInput.
pcpt1 = Perceptron([-1.0,2.0], 0.0, 0)
pcpt2 = Perceptron([-2.0,4.0], 0.0, 1)
layer = NeuralNetLayer(2, [pcpt1, pcpt2])
listDblInput = [0.5, 0.25]
feed_forward_layer(layer, listDblInput)
[0.5, 0.5]"""
return map(lambda pcpt: pcpt_activation(pcpt, listDblInput), layer.listPcpt)
class NeuralNet(object):
"""An artificial neural network."""
def __init__(self, cInputs, listLayer):
"""Assemble the network from layers listLayer. cInputs specifies
the number of inputs to each node in the first hidden layer of the
network."""
if not self.check_layers(cInputs, listLayer):
raise TypeError("Incompatible neural network layers.")
self.cInputs = cInputs
for layer in listLayer:
if not isinstance(layer, NeuralNetLayer):
raise TypeError("NeuralNet layers must be of type "
"NeuralNetLayer.")
self.listLayer = listLayer
@classmethod
def check_layers(cls, cInputs, listLayer):
if not listLayer:
return False
if cInputs != listLayer[0].layer_input_size():
return False
for layerFst,layerSnd in zip(listLayer[:-1], listLayer[1:]):
if layerFst.layer_output_size() != layerSnd.layer_input_size():
return False
return True
def input_layer(self):
return self.listLayer[0]
def output_layer(self):
return self.listLayer[-1]
def build_layer_inputs_and_outputs(net, listDblInput):
"""Build a pair of lists containing first the list of the input
to each layer in the neural network, and second, a list of output
from each layer in the network.
The list of inputs contains as its first element listDblInput,
the inputs to the first layer of the network.The list of outputs contains
as its last element the output of the output layer.
listCLayerSize = [2,2,1]
net = init_net(listCLayerSize)
build_layer_inputs_and_outputs(net, [-1.0, 1.0])
([[...], [...]], [[...], [...]])"""
lstDblInputs = []
lstDblOutputs = []
curListDblInput = listDblInput
curListDblOutput = []
for layer in net.listLayer:
curListDblOutput = feed_forward_layer(layer, curListDblInput)
lstDblInputs.append(curListDblInput)
lstDblOutputs.append(curListDblOutput)
curListDblInput = curListDblOutput
return (lstDblInputs,lstDblOutputs)
def feed_forward(net, listDblInput):
"""Compute the neural net's output on input listDblInput."""
return build_layer_inputs_and_outputs(net, listDblInput)[-1][-1]
def layer_deltas(listDblActivation, listDblError):
"""Compute the delta values for a layer which generated activation levels
listDblActivation, resulting in error listDblError.
layer_deltas([0.5, 0.25], [0.125, 0.0625])
[0.03125, 0.01171875]"""
return map(compute_delta, listDblActivation,listDblError)
def update_layer(layer, listDblInputs, listDblDelta, dblLearningRate):
"""Update all perceptrons in the neural net layer.
The function updates the perceptrons in the layer in place, and does
not return anything.
listPcpt = [Perceptron([1.0,-1.0],0.0,0), Perceptron([-1.0,1.0],0.0,1)]
layer = NeuralNetLayer(2, listPcpt)
print layer.listPcpt
[Perceptron([1.0, -1.0], 0.0, 0), Perceptron([-1.0, 1.0], 0.0, 1)]
update_layer(layer, [0.5,-0.5], [2.0,2.0], 0.5) # do the update
print layer.listPcpt
[Perceptron([1.5, -1.5], 1.0, 0), Perceptron([-0.5, 0.5], 1.0, 1)]"""
for pcpt, delta in zip(layer.listPcpt,listDblDelta):
update_pcpt(pcpt, listDblInputs, delta, dblLearningRate)
return None
def hidden_layer_error(layer, listDblDownstreamDelta, layerDownstream):
"""Determine the error produced by each node in a hidden layer, given the
next layer downstream and the deltas produced by that layer.
layer = NeuralNetLayer(0, [Perceptron([], 0.0, 0),
Perceptron([], 0.0, 1)])
layerDownstream = NeuralNetLayer(2, [Perceptron([0.75,0.25], 0.0, 0)])
hidden_layer_error(layer, [2.0], layerDownstream)
[1.5, 0.5]"""
return map(lambda pcpt:
hidden_error(listDblDownstreamDelta, pcpt, layerDownstream),
layer.listPcpt)
class Instance(object):
def __init__(self, iLabel, listDblFeatures):
self.iLabel = iLabel
self.listDblFeatures = listDblFeatures
class ImageInstance(Instance):
"""Implements an instance composed of 2D data."""
def __init__(self, iLabel, listListImage):
listDblFeatures = []
self.cRow = len(listListImage)
self.cCol = None
for listDblRow in listListImage:
self.cCol = max(len(listDblRow), self.cCol)
for dblCol in listDblRow:
listDblFeatures.append(dblCol)
super(ImageInstance,self).__init__(iLabel,listDblFeatures)
def reconstruct_image(self):
pass
def distributed_encode_label(iLabel):
"""Generate a distributed encoding of the integer label iLabel.
distributed_encode_label(2)
[0.05, 0.05, 0.95, 0.05, 0.05, 0.05, 0.05]"""
listDblEncodedVector = []
#numberDimensions = 2 # XOR test
numberDimensions = 7 #covertype set
dblNegVal = 0.05
dblPosVal = 0.95
for ix in range(numberDimensions):
if ix is iLabel:
listDblEncodedVector.append(dblPosVal)
else:
listDblEncodedVector.append(dblNegVal)
return listDblEncodedVector
def binary_encode_label(iLabel):
"""Generate a binary encoding of the integer label iLabel.
binary_encode_label(5)
[0.95, 0.05, 0.95, 0.05]"""
curIntLabel = iLabel
lstDblBinary = []
value = None
numberBits = 1
dblNegVal = 0.05
dblPosVal = 0.95
while not(curIntLabel is 0):
if curIntLabel%2 is 0:
value = dblNegVal
else: value = dblPosVal
lstDblBinary.append(value)
curIntLabel = (curIntLabel - curIntLabel%2)/2
curBitLength = len(lstDblBinary)
for ix in range(numberBits - curBitLength):
lstDblBinary.append(dblNegVal)
return lstDblBinary
def distributed_decode_net_output(listDblOutput):
"""Decode the output of a neural network with distributed-encoded outputs.
listDblOutput = [0.23, 0.4, 0.01, 0.2, 0.3, 0.78, 0.51, 0.15, 0.2, 0.1]
distributed_decode_net_output(listDblOutput)
5"""
return listDblOutput.index(max(listDblOutput))
def binary_decode_net_output(listDblOutput):
"""Decode the output of a neural network with binary-encoded outputs.
binary_decode_net_output([0.95, 0.44, 0.01, 0.51])
9
"""
dblThreshold = 0.50
listInterpretation = []
iCurBitSignificance = 1
def convert_to_binary(dblVal):
if dblVal < dblThreshold:
return int(0)
else:
return int(1)
listBinaryValues = map(convert_to_binary, listDblOutput)
for ix in range(len(listBinaryValues)):
listInterpretation.append(iCurBitSignificance)
iCurBitSignificance = iCurBitSignificance*2
iOutput = dot(listBinaryValues,listInterpretation)
return iOutput
def update_net(net, inst, dblLearningRate, listTargetOutputs):
"""Updates the weights of a neural network in place based on one instance and
returns the list of outputs after feeding forward.
The outline is as follows:
- feed forward the instance through the network
- compute deltas
- update weights
"""
listDblInputs = inst.listDblFeatures
dblLayerInputsOutputs = build_layer_inputs_and_outputs(net, listDblInputs)
listDblLayerInputs = dblLayerInputsOutputs[0]
listDblLayerOutputs = dblLayerInputsOutputs[1]
listDblOuputActivations = dblLayerInputsOutputs[-1][-1]
listDblLayerDeltas = []
#backpropagation
#deal with output first
listOutputError = \
map(lambda dblOutputActivation, dblTargetOutput:
output_error(dblOutputActivation, dblTargetOutput),
listDblOuputActivations,listTargetOutputs)
listOutputLayerDeltas = layer_deltas(listDblOuputActivations, listOutputError)
#calculate deltas from the close to output hidden layer towards
#the first hidden layer after the input
listDblLayerDeltas.insert(0, listOutputLayerDeltas) #result in correct order!
listCurError = listOutputError
for ixCurHiddenLayer in reversed(range(len(net.listLayer)-1)):
curLayer = net.listLayer[ixCurHiddenLayer]
downstreamLayer = net.listLayer[ixCurHiddenLayer+1]
listDblDownstreamDelta = listDblLayerDeltas[0]
listDblCurError = \
hidden_layer_error(curLayer, listDblDownstreamDelta, downstreamLayer)
#here we need activation produced by teh current layer
listDblCurActivation = listDblLayerOutputs[ixCurHiddenLayer]
listDblCurDeltas = layer_deltas(listDblCurActivation, listDblCurError)
listDblLayerDeltas.insert(0, listDblCurDeltas)
#update all perceptrons in layers
for layer, listDblInputs, listDblDelta in \
zip(net.listLayer,listDblLayerInputs,listDblLayerDeltas):
update_layer(layer, listDblInputs, listDblDelta, dblLearningRate)
return listDblOuputActivations
def init_net(listCLayerSize, dblScale=0.01):
"""Returns a complete feedforward neural network with zero or more hidden layers
and initialize its weights to random values in (-dblScale,dblScale).
listCLayerSize: specializes the structure of the NN,
[#inputs, #first hidden, #second hidden,...,#outputs]"""
iCurInputs = listCLayerSize[0]
listLayers = []
for cLayerSize in listCLayerSize[1 :]:
listPcpt = []
for ixPcpt in range(cLayerSize):
dblW0 = random.uniform(-dblScale, dblScale)
listDblWeights = map(lambda dummy: random.uniform(-dblScale, dblScale),
range(iCurInputs))
listPcpt.append(Perceptron(listDblWeights, dblW0, ixPcpt))
listLayers.append(NeuralNetLayer(iCurInputs, listPcpt))
iCurInputs = cLayerSize
return NeuralNet(listCLayerSize[0], listLayers)
def print_net(net):
"""Convenience routine for printing a network to standard out."""
for layer in net.listLayer:
print ""
for pcpt in layer.listPcpt:
print pcpt
#break
#break |
'''
Write a Python class to find the three elements that sum to zero
from a list of n real numbers.
Input array: [-25, -10, -7, -3, 2, 4, 8, 10]
Output : [[-10, 2, 8], [-7, -3, 10]]
'''
from itertools import combinations
def sumToZero(inArray):
comb = combinations(inArray, 3)
posibOutComes = list(comb)
res = []
for i in posibOutComes:
if sum(i) == 0:
res.append(list(i))
return res
inArray = [-25, -10, -7, -3, 2, 4, 8, 10]
print(sumToZero(inArray))
|
'''
Write a Python class to find validity of a string of parentheses, '(', ')', '{',
'}', '[' and ']'. These brackets must be close in the correct order, for example
"()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid
'''
def bra(string):
dis = {'[': ']', '{': '}', '(': ')'}
stack = []
for i in string:
if stack:
tos = stack[-1]
stack.pop() if i == dis[tos] else stack.append(i)
else:
stack.append(i)
print("True") if len(stack) == 0 else print("False")
# test
if __name__ == '__main__':
string = "()[{}]"
bra(string)
|
'''
Create a function, is_palindrome, to determine if a supplied word is
the same if the letters are reversed.
'''
def is_palindrome(word1):
word2 = word1[-1::-1]
return "It is palindrome" if word1 == word2 else "It is not palindrome"
word1 = input("Enter the word: ")
word1.lower()
print(is_palindrome(word1))
|
'''
A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
def for_n_digit_numbers(n=3):
limit = calculate_limit(n)
multipliers = []
largest = 0
for i in range(limit, 0, -1):
multipliers.append(i)
for multiplier in multipliers:
product = multiplier * i
if is_palindrome(product) and product > largest:
largest = product
return largest
def calculate_limit(n):
limit = 1
for _ in range(n):
limit *= 10
return limit - 1
def is_palindrome(number):
number_string = str(number)
return number_string == number_string[::-1]
if __name__ == '__main__':
print(for_n_digit_numbers()) # => 906609
|
for i in range(0, 10):
print("In the iteration with the value", i)
for i in range(0, 10):
print("perfect square", i, "is", i*i)
for j in range(1,11):
print(i, "x", j, "=", i*j)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
count = raw_input("Vpiši cifro do katere želiš prešteti: ")
count = int(count)
for num in xrange(1, count):
if num % 3 == 0 and num % 5 == 0:
print "FizzBuzz"
elif num % 3 == 0:
print "Fizz"
elif num % 5 == 0:
print "Buzz"
else:
print num
|
def clean_dict(d):
"""Remove all key, value pairs whose key is "tooltip" or whose value is either None or empty"""
clean = {}
for k, v in d.items():
if isinstance(v, dict):
nested = clean_dict(v)
if len(nested.keys()) > 0 and k != "tooltip":
clean[k] = nested
elif v and k != "tooltip":
clean[k] = v
return clean
|
# 1b qns 4
import math
import tensorflow as tf
import numpy as np
import pylab as plt
seed = 10
tf.set_random_seed(seed)
# Same implementation as question 1
def get_admission_data(small = None):
np.random.seed(seed)
#read and divide data into test and train sets
admit_data = np.genfromtxt('admission_predict.csv', delimiter= ',')
X_data, Y_data = admit_data[1:,1:8], admit_data[1:,-1]
Y_data = Y_data.reshape(Y_data.shape[0], 1)
idx = np.arange(X_data.shape[0])
np.random.shuffle(idx)
X_data, Y_data = X_data[idx], Y_data[idx]
if small is not None:
# experiment with small datasets
X_data = X_data[:small]
Y_data = Y_data[:small]
X_data = (X_data- np.mean(X_data, axis=0))/ np.std(X_data, axis=0)
split = 0.7
#create train set
trainX = X_data[:int(X_data.shape[0]*split)]
trainY = Y_data[:int(Y_data.shape[0]*split)]
#create test set
testX = X_data[:int(X_data.shape[0]*split*-1)]
testY = Y_data[:int(Y_data.shape[0]*split*-1)]
#randomly choose 50 samples from test set
rand = np.random.choice(testX.shape[0], 50, replace=True)
testX = testX[rand]
testY = testY[rand]
return trainX, trainY, testX, testY
# Same implementation as question 1
def gradientDescentOptimizer(trainX, trainY, testX, testY, print_result = False, epochs = 1000, num_layer = 3, num_neuron = 10, with_dropouts = False):
# initialise constants
learning_rate = 10**-3
beta = 10**-3
batch_size = 8
NUM_FEATURES = np.size(trainX,1)
dropout = 0.8
# Create the model
x = tf.placeholder(tf.float32, [None, NUM_FEATURES])
y_ = tf.placeholder(tf.float32, [None, 1])
# Build the graph for the deep net
stddev = 1.0/math.sqrt(NUM_FEATURES)
# hidden layer 1
seed=10
weights_h1 = tf.Variable(tf.truncated_normal([NUM_FEATURES,num_neuron],
stddev=stddev, dtype=tf.float32,seed=seed),
name='weights')
biases_h1 = tf.Variable(tf.zeros([num_neuron]))
h1 = tf.nn.relu(tf.matmul(x, weights_h1) + biases_h1)
if with_dropouts:
h1 = tf.nn.dropout(h1, dropout)
# hidden layer 2
seed=20
weights_h2 = tf.Variable(tf.truncated_normal([num_neuron,num_neuron],
stddev=stddev, dtype=tf.float32,seed=seed),
name='weights')
biases_h2 = tf.Variable(tf.zeros([num_neuron]))
h2 = tf.nn.relu(tf.matmul(h1, weights_h2) + biases_h2)
if with_dropouts:
h2 = tf.nn.dropout(h2, dropout)
# hidden layer 3
seed=30
weights_h3 = tf.Variable(tf.truncated_normal([num_neuron,num_neuron],
stddev=stddev, dtype=tf.float32,seed=seed),
name='weights')
biases_h3 = tf.Variable(tf.zeros([num_neuron]))
h3 = tf.nn.relu(tf.matmul(h2, weights_h3) + biases_h3)
if with_dropouts:
h3 = tf.nn.dropout(h3, dropout)
#output layer
seed=40
weights = tf.Variable(tf.truncated_normal([num_neuron, 1], stddev=stddev, dtype=tf.float32, seed=seed), name='weights')
biases = tf.Variable(tf.zeros([1]), dtype=tf.float32, name='biases')
if num_layer == 3:
y = tf.matmul(h1, weights) + biases
regularization = tf.nn.l2_loss(weights) + tf.nn.l2_loss(weights_h1)
elif num_layer == 4:
y = tf.matmul(h2, weights) + biases
regularization = tf.nn.l2_loss(weights) + tf.nn.l2_loss(weights_h1) + tf.nn.l2_loss(weights_h2)
elif num_layer == 5:
y = tf.matmul(h3, weights) + biases
regularization = tf.nn.l2_loss(weights) + tf.nn.l2_loss(weights_h1) + tf.nn.l2_loss(weights_h2) + tf.nn.l2_loss(weights_h3)
ridge_loss = tf.square(y_ - y)
loss = tf.reduce_mean(ridge_loss + beta*regularization)
#Create the gradient descent optimizer with the given learning rate.
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
train_op = optimizer.minimize(loss)
error = tf.reduce_mean(tf.square(y_ - y))
train_errs = []
test_errs = []
n = trainX.shape[0]
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(epochs):
# shuffle
idx = np.arange(trainX.shape[0])
np.random.shuffle(idx)
trainX, trainY = trainX[idx], trainY[idx]
# implementing mini-batch GD
for s in range(0, n-batch_size, batch_size):
train_op.run(feed_dict={x: trainX[s:s+batch_size], y_: trainY[s:s+batch_size]})
train_err = error.eval(feed_dict={x: trainX, y_:trainY})
train_errs.append(train_err)
test_err = error.eval(feed_dict={x: testX, y_:testY})
test_errs.append(test_err)
if print_result:
print("training iteration %d" %i, end="\r")
if i % 100 == 0:
print('iter %d: train error %g'%(i, train_errs[i]))
print('iter %d: test error %g'%(i, test_errs[i]))
pred = sess.run(y, feed_dict={x:testX})
if print_result:
if epochs >= 20000:
# plot learning curves
plt.figure(1)
plt.xlabel(str(epochs) + ' iterations')
plt.ylabel('Error')
z = 10000
plt.plot(range(z,epochs), train_errs[z:], c="r")
plt.plot(range(z,epochs), test_errs[z:], c="b")
plt.legend(["train error", "test error"],loc='upper left')
plt.figure(2)
plt.xlabel(str(epochs) + ' iterations')
plt.ylabel('Error')
z = 0
plt.plot(range(z,epochs), train_errs[z:], c="r")
plt.plot(range(z,epochs), test_errs[z:], c="b")
plt.legend(["train error", "test error"],loc='upper left')
plt.figure(3)
plt.xlabel('Sample number')
plt.ylabel('Chance to Admit')
plt.plot(testY, c="r")
plt.plot(pred, c="b")
plt.legend(["Target", "Predicted"],loc='upper left')
plt.show()
return test_errs[len(test_errs) -1]
trainX, trainY, testX, testY = get_admission_data()
trainX = np.delete(trainX, 3, 1) # delete 'SOP'
testX = np.delete(testX, 3, 1) # delete 'SOP'
import pandas as pd
df = pd.DataFrame(columns = ['layers', 'dropouts', 'no. of neurons', 'Root Mean Square Error'])
rms = gradientDescentOptimizer(trainX, trainY, testX, testY,
epochs = 1000, num_layer = 3,
num_neuron = 10, with_dropouts = False)
df.loc[0] = [3, False, 10, rms]
layers = [3,4,5]
dropout = [True,False]
for num_layer in layers:
for with_dropouts in dropout:
rms = gradientDescentOptimizer(trainX, trainY, testX, testY,
epochs = 1000, num_layer = num_layer,
num_neuron = 50, with_dropouts = with_dropouts)
df.loc[len(df)] = [num_layer, with_dropouts, 50, rms]
print([num_layer, with_dropouts, 50, rms])
print(df) |
name = input("What's your name?\n")
print("Hi " + name + " How are you?")
user = input() #for saving useres answers
print("Thanks," + name + " Good bye.") |
class Person():
def __init__(self, name, age, idNum):
self.name = name
self.age = age
self.idNum = idNum
def output(self):
print("Your name is " + self.name + " your age is " + self.age + " Your ID num is " + self.idNum)
ana = Person("Ana", "28", "23225655")
class Man(): #New class that is over Child class
def strong(self):
print("Man is strong")
class Child(Person, Man):
pass
kid = Child("Davor", "28", "232555664")
kid.output()
kid.strong() # Now kid object will inherit these features
|
myvarable = 10
if myvarable == 5:
print("This is true, myvariable = 10")
else:
print("this is false myvariable is NOT 10")
print("Lession for Greater, less than, and aqual operator")
enyvar = 150
othervar = 5000
if enyvar >= othervar:
print("enyvar is greater than othervar")
else:
print("No") |
print("This program checks if you are eligbe for loan or not")
salary = int(input("How much is your salary"))
if(salary>1000):
amount = 200
print("You are eligbe to get a bank loan py paying", amount, "monthly")
elif(salary == 1000):
amount=500
print("you are eligbe to get bank loan with higher monthly price", amount, "monthly")
else:
print("Sorry you are not eligbe") |
n = int(input("Введите числo: "))
z = 0
for i in range (1, n+1):
y = 1 / i
if i % 2 ==0:
y = -y
elif i % 2 !=0 or y ==1:
y = y
z += y
print(z)
|
n = int(input("Введите число от 1 до 9 "))
x = n * 10
for i in range (n, x, n):
print(i, end=" ")
|
y = int(input("Введите угол в градусах: "))
x = 30 #Градусы
hours = y // 30
min = y % 30 * 2 # 30gr - 60min, 15gr - xmin => x = 15 * 60 / 30
print(min)
|
x = int(input("Введите число "))
max = x
while x != 0:
x = int(input("введите число "))
if x > max:
max = x
print(max)
|
import math
def area():
a = float(input("Введите a "))
b = float(input("Введите b "))
c = float(input("Введите c "))
d = float(input("Введите d "))
e = float(input("Введите e "))
f = float(input("Введите f "))
g = float(input("Введите g "))
S1 = (a * b) // 2
S2 = (e * d) // 2
x = math.sqrt(f*f - (c*c /4)) # Высота треугольника cgf
S3 = (c * x) / 2
return print("Площадь пятиугольника равна: ", S1 + S2 + S3)
area() |
a=(input("ведите число a "))
b=(input("ведите число b "))
c=(input("ведите число c "))
x=b
z=a
a=x
b=c
c=z
print(a,b,c)
|
a = input("Введите число: ")
length = len(a)
x =""
for i in range(length):
y = a[length -1 - i]
x = x + y
print(int(x)) |
n = int(input("Введите натуральное число n: "))
m = int(input("Введите число m: "))
p = int(input("Введите число p: "))
sum = 0
for i in range(n):
d = int(input("Введите число d: "))
if d <= m:
sum += d
if sum % p == 0:
print("Сумма чисел 'd' кратна числу p")
else:
print("Сумма чисел 'd' не кратна числу p")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.