text stringlengths 37 1.41M |
|---|
X = [1 , 1.05 , 1.10 , 1.15 , 1.20 , 1.25]
Y = [0.682689 , 0.706282 , 0.728668 , 0.749856 , 0.769861 , 0.788700]
n = len(Y)
h = X[1] - X[0]
#################################################################
# TWO POINT APPROXIMATION
print("\n\nTwo point approximation of derivative")
print("\nx0\tForward Difference f'(x0)")
Forward_difference = []
Backward_difference = []
for i in range(n - 1):
FD = (Y[i + 1] - Y[i]) / h
Forward_difference.append(FD)
for i in range(1 , n):
BD = (Y[i] - Y[i - 1]) / h
Backward_difference.append(BD)
for i in range(n - 1):
print(X[i] , "\t" , Forward_difference[i])
print("\nx0\tBackward Difference f'(x0)")
for i in range(1 , n):
print(X[i] , "\t" , Backward_difference[i - 1])
#################################################################
#THREE POINT APPROXIMATION
print("\n\nThree point approximation")
Right_end = []
for i in range(n - 2):
re = (-3 * Y[i] + 4 * Y[i + 1] - Y[i + 2]) / (2 * h)
Right_end.append(re)
print("\nx0\tRight end approximation f'(x0)")
for i in range(n - 2):
print(X[i] , "\t" , Right_end[i])
Mid_Point = []
for i in range(1 , n - 1):
m = (Y[i + 1] - Y[i - 1]) / (2 * h)
Mid_Point.append(m)
print("\nx0\tMid_point approximation f'(x0)")
for i in range(1 , n - 1):
print(X[i] , "\t" , Mid_Point[i - 1])
Left_end = []
for i in range(2 , n):
le = (3 * Y[i] - 4 * Y[i - 1] + Y[i - 2]) / (2 * h)
Left_end.append(le)
print("\nx0\tLeft end approximation f'(x0)")
for i in range(n - 2):
print(X[i + 2] , "\t" , Left_end[i])
#################################################################
# FIVE POINT APPROXIMATION
print("\n\nFive point approximation")
Right_end = []
for i in range(n - 4):
re = (-25 * Y[i] + 48 * Y[i + 1] -36 * Y[i + 2] + 16 * Y[i + 3] - 3 * Y[i + 4]) / (12 * h)
Right_end.append(re)
print("\nx0\tRight end approximation f'(x0)")
for i in range(n - 4):
print(X[i] , "\t" , Right_end[i])
Mid_Point = []
for i in range(2 , n - 2):
m = (Y[i - 2] -8 * Y[i - 1] + 8 * Y[i + 1] - Y[i + 2]) / (12 * h)
Mid_Point.append(m)
print("\nx0\tMid_point approximation f'(x0)")
for i in range(2 , n - 2):
print(X[i] , "\t" , Mid_Point[i - 2])
Left_end = []
for i in range(4 , n):
le = (25 * Y[i] - 48 * Y[i - 1] + 36 * Y[i - 2] - 16 * Y[i - 3] + 3 * Y[i - 4]) / (12 * h)
Left_end.append(le)
print("\nx0\tLeft end approximation f'(x0)")
for i in range(n - 4):
print(X[i + 4] , "\t" , Left_end[i])
#################################################################
# THREE POINT APPROXIMATION FOR SECOND DERIVATIVE
print("\n\nThree point approximation for second derivative")
MID_POINT_SD = []
for i in range(1 , n - 1):
ss = (Y[i - 1] - 2 * Y[i] + Y[i + 1]) / (h * h)
MID_POINT_SD.append(ss)
print("\nx0\tMid Point approximation f''(x0)")
for i in range(1 , n - 1):
print(X[i] , "\t" , MID_POINT_SD[i - 1])
|
import pandas as pd
(a , b , TOL , N) = (0 , 1 , 0.01 , 4)
def f(x):
return (x ** 3) + (4 * x * x) - 10
data = []
pd.options.display.float_format = "{:,.10f}".format
def bisection(a , b , N = 100 , TOL = 10 ** -5):
n = 1
while n <= N:
p = a + (b - a) / 2
data.append([n , a , b , p , f(p) , (b - a) / (2 * p)])
if(f(p) == 0 or ((b - a) / 2) < TOL):
print("Root occurs at {}".format(round(p , 10)))
break
if(f(a) * f(p) < 0):
b = p
else:
a = p
n += 1
table = pd.DataFrame(data , columns = ['n' , 'an' , 'bn' , 'p' , 'f(p)' , 'relative error'])
print(table.to_string(index = 0))
if(n - 1 == N):
print("Method failed after {} iterations".format(N))
bisection(a , b , N , TOL)
|
'''2nd assignment
dijkstra's alg
class priorityqueue:
#constructor creates a heap
def enqueue(self, item):
def dequeue(self, item):
def isEmpty(self:
Height balanced AVL trees
Balance is maintained in each node
and is called balance. Subtrees are referenced as aleft andright.
Build an AVL tree
Balanceof eery node must be 0, -1, 1.
Balance, (node), is height (right) - height (left)
Empty tree has height 0. A leafe node has height 1.
Values: 50, 75, 85.
Implementation of recursively inserted AVL trees. Remain balance.
1) two rotations are necessary. Pass to it a root node and return a new root.
2) Find pivot, add a flag called pivotFound to the AVL tree class.
the only reason for teh pivotFound varialbe, is to avoid adjusting balances
higher in the tree.
3) write __insert recursive function
4) adjust balancees up to pivot node
5) if we find pivot has -2 or 2 balance, do case 3.
6) at the end of __insert make sure you return the root node.
'''
class AVLTree:
def check(self):
self.root.check()
class AVLNode:
def check(self):
compBalance = depth(self.right) - depth(self.left)
#depth is a recursive function, not a method
def depth(root):
if root = None:
return 0
return max(depth(root.left), depth(self.right))
'''
11/2/2015
'''
def depth(node):
if node==None:
return 0
return 1+ max(depth(node.left), depth(node.right))
AVLNode(item, balance)
# In AVL tree class::
def check(self):
self.root.check()
#in AVL node class:
def check(self):
lh = depth(self.left)
rh = depth(self.right)
balance = rh-lh
if self.balance != balance:
print(repr(self))
raise Exception("Balance Problem")
if self.left != None:
self.left.check()
if self.right != None:
self.right.check()
#Part of AVL Tree class:
def __insert(root,item):
if root == None:
return AVLNode(item)
if item < root.item:
root.left = __insert(root.left, item)
if item > root.item:
root.right = __insert(root.right, item)
return root |
"""
This File is for Mini Project in EED379 :Internet Of Things
Course : Internet Of Things EED379
Component : Mini Project
Topic: Home Automation using Google Assistant
Authors: Ojas Srivastava
Yatharth Jain
Code Component Description : This code is client side for the Raspberry Pi Node.
This program will fetch information from ThingSpeak Cloud and load it on to the
program variables. Upon doing this the program will use the status sent by the cloud to
switch ON or OFF our LED.
"""
# Importing Important Libraries
import urllib.request as urllib2 #urllib for oppening any URL and fetching data from there
import json #All URLs return information in the form of JSON. This librart will help us decode it from JSON to Python object
import time
######Libraries specific to Rpi <TO BE FILLED>
import RPi.GPIO as GPIO
#Defining GLOBAL variables
READ_API_KEY= #Our READ API key for ThingSpeak Cloud
CHANNEL_ID= #Our Channel ID for ThingSpeak Cloud
#####GPIO
GPIO_pin = 6 #Enter as per #Pin connect to LED
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_pin,GPIO.OUT)
def switch_on():
GPIO.output(GPIO_pin,GPIO.HIGH)
print("LED is ON \n")
def switch_off():
GPIO.output(GPIO_pin,GPIO.LOW)
print("LED is OFF \n")
#main function is used as the fetcher of data and the command center for the Rpi
def main():
#print ("http status code=%s" % (conn.getcode())) #used to get the status code from the server, status code:200 is success
i=1
while(True):
print(i)
i+=1
conn = urllib2.urlopen("<Thing Speak Channel URL here>")
#opening my ThngSpeak URL which gives data in GET mode.
response = conn.read() #read the information presented in the URL
data=json.loads(response) #the information is in JSON format and hence needs to be unpacked
#print (data)
#The data is in dictionary format and we will access the "feeds" Key
temp=data['feeds'] #accessing "feeds" key
dic = temp[0]
f = dic["field1"]
print ("Status is:" + f) #printing the current status
if (f=="2"):
switch_on()
elif(f=="1"):
switch_off()
if (f=="3"): #ADD THIS FUNCTIONALITY TO IFTT :Ojas
switch_off()
break
#time.sleep(1) #pause for 1 second
conn.close() #close connection
if __name__ == '__main__':
main()
|
# Diccionarios
countriesCapitals={"Alemania":"Berlin","Colombia":"Bogota","Francia":"Paris","España":"Madrid"}
#print (countriesCapitals["Alemania"])
# Agregar elementos
countriesCapitals["Italia"]="Lisboa"
# Modificar valores, se sobreescriben
countriesCapitals["Italia"]="Roma"
# Eliminar elementos
del countriesCapitals["España"]
diccionario1={"Cristiano": 7,"Apellido":"Ronaldo","Balon de oro":{"años":[2012,2013,2014,2015,2016]}}
print(diccionario1.keys())
print(diccionario1.values())
print(len(diccionario1))
print(diccionario1["Balon de oro"]) |
welcome=print("Bienvenido al programa, Inserte numeros cada vez mayores")
number=int(input("Inserte el primer numero entero: "))
while number>0:
number1=int(input("Inserte el siguiente numero: "))
print("Numero anterior ",str(number)," Siguiente numero ",str(number1))
number=number1
print(number)
print(number1)
if number<0 or number1<0:
print("Error, Solo se aceptan numeros positivos")
if number<number1:
print("Fin del programa")
break;
|
# Continue
name="Pildoras informaticas"
counter=0
print(len(name))
for letter in name:
if letter==" ":
continue
counter+=1
print(counter)
# Pass , Rompe un bucle, hace un clase nula,no se tiene en cuenta
# Else , Funciona cuando el bucle termina
email=input("introduce tu email: ")
arroba=False
for i in email:
if i=="@":
a=True
break;# Al llegar al la @ se acaba el bucle
else:
arroba=False
print(arroba) |
def encrypt_this(text):
print(text)
result = ""
for word in text.split(' '):
if len(word) == 1:
w = str(ord(word))
result += w + " "
if len(word) == 2:
w = str(ord(word[0])) + word[1]
result += w + " "
if len(word) == 3:
w = str(ord(word[0])) + word[2] + word[1]
result += w + " "
if len(word) > 3:
second = word[-1]
last = word[1]
left = 2
right = len(word) - 1
mid = word[left:right]
w = str(ord(word[0])) + second + mid + last
result += w + " "
return result.rstrip()
|
from operator import itemgetter
def meeting(s):
names = []
result = ""
split = s.split(";")
for name in split:
name = name.split(":")
firstname = name[0].upper()
lastname = name[1].upper()
out = [firstname, lastname]
names.append(out)
# sort by last name, then first name
names_sort = sorted(names, key=itemgetter(1, 0))
for names in names_sort:
firstname = names[0]
lastname = names[1]
result = result + "(" + lastname + ", " + firstname + ")"
return result |
def street_fighter_selection(fighters, initial_position, moves):
if len(moves) == 0:
return []
result = []
cur_pos = list(initial_position)
fighter_row = 0
for move in moves:
print("Current Pos {}".format(cur_pos))
if move == "left":
if cur_pos[0] > 0:
cur_pos[0] = cur_pos[0] - 1
result.append(fighters[fighter_row][cur_pos[0]])
print("Appending {}".format(fighters[fighter_row][cur_pos[0]]))
continue
if cur_pos[0] == 0:
cur_pos[0] = len(fighters[0]) - 1
result.append(fighters[fighter_row][cur_pos[0]])
print("Appending {}".format(fighters[fighter_row][cur_pos[0]]))
continue
if move == "right":
if cur_pos[0] < len(fighters[fighter_row]) - 1:
cur_pos[0] = cur_pos[0] + 1
result.append(fighters[fighter_row][cur_pos[0]])
print("Appending {}".format(fighters[fighter_row][cur_pos[0]]))
continue
if cur_pos[0] == len(fighters[fighter_row]) - 1:
cur_pos[0] = 0
result.append(fighters[fighter_row][cur_pos[0]])
print("Appending {}".format(fighters[fighter_row][cur_pos[0]]))
continue
if move == "up":
if fighter_row == 0:
result.append(fighters[fighter_row][cur_pos[0]])
print("Appending {}".format(fighters[fighter_row][cur_pos[0]]))
continue
else:
fighter_row = fighter_row - 1
result.append(fighters[fighter_row][cur_pos[0]])
print("Appending {}".format(fighters[fighter_row][cur_pos[0]]))
continue
if move == "down":
if fighter_row == 1:
result.append(fighters[fighter_row][cur_pos[0]])
print("Appending {}".format(fighters[fighter_row][cur_pos[0]]))
continue
else:
fighter_row = fighter_row + 1
result.append(fighters[fighter_row][cur_pos[0]])
print("Appending {}".format(fighters[fighter_row][cur_pos[0]]))
continue
print(result)
return result |
import string
import re
def is_pangram(s):
letters = ['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']
sentence = []
for l in s:
l = l.lower()
if re.match("[a-z]",l):
if l not in sentence:
sentence.append(l)
sentence.sort()
if letters == sentence:
return True
else:
return False
|
# Write a program which accept number from user and print that number of $ & *
#on screen.
#Input : 5
#Output : $ * $ * $ * $ * $ *
#Input : 3
#Output : $ * $ * $ *
#Input : -3
#Output : $ * $ * $ *
def main():
no=int(input("Enter the number : "))
for i in range(no):
print("$"+"\t"+"*"+"\t",end = '')
if __name__=="__main__":
main() |
# Write a program which accept string from user and copy the
# contents of that string into another string. (Implement strncpy() function)
# Input : “Marvellous Multi OS”
# 10
# Output : “Marvellous
def StrNCpyX(strs,no):
list1=list(strs) # to convert string into array(list)
i=0
while i<no:
print(list1[i] , end ='')
i+=1
def main():
print("Enter the string : ")
str=input()
print("Enter the number : ")
no=int(input())
StrNCpyX(str,no)
if __name__=="__main__":
main() |
# Accept N numbers from user and display summation of digits of each
# number.
# Input : N : 6
# Elements : 8225 665 3 76 953 858
# Output : 17 17 3 13 17 21
def DigitsSum(arr,no):
Sum=0
for x in range(0,no):
No=arr[x]
while No !=0:
Digit=No%10
Sum=Sum+Digit
No=No//10 # here // is called as floor which is used to round off values if value is 7.5 then it becomes the 7
print(str(Sum) , end='' +"\t")
Sum=0
def main():
arr=[]
size=int(input("Enter the N value : "))
print("Enter the N elements : ")
for x in range(0,size):
item=int(input())
arr.append(item)
print(arr)
DigitsSum(arr,size)
if __name__=="__main__":
main()
|
import pandas as pd
import sqlalchemy as sq
def get_database_connection():
"""
Used to retrive database configuration from file
"""
db = pd.read_csv('dbconfig.csv')
for line, row in db.iterrows():
username = row['username']
password = row['password']
server = row['server']
port = row['port']
dbname = row['dbname']
return username, password, server, port, dbname
def create_connection_engine(username, password, server, port, dbname):
engine = sq.create_engine(
'postgresql://' + str(username) + ':' + str(password) + '@' + str(server) + ':' + str(port) + '/' + str(
dbname) + '')
return engine
def get_data_from_database_for_sql(sql_query):
"""
:param sql_query: SQL query which needs to be executed in database
:returns: data from database for the sql query in the input in pandas dataframe format
"""
username, password, server, port, dbname = get_database_connection()
engine=create_connection_engine(username, password, server, port, dbname)
dataframe = pd.read_sql(sql_query, engine)
return dataframe
def push_to_database(sql_query):
"""
:param sql_query: SQL query which needs to be executed in database
:returns: data from database for the sql query in the input in pandas dataframe format
"""
username, password, server, port, dbname = get_database_connection()
engine=create_connection_engine(username, password, server, port, dbname)
con=engine.connect()
con.execute(sql_query)
def insert_data_to_database(dataframe, table_name, method='append'):
"""
:param dataframe: input dataframe to be loaded to database
:param table_name: destination table
:param method: optional field
"""
username, password, server, port, dbname = get_database_connection()
engine=create_connection_engine(username, password, server, port, dbname)
dataframe.to_sql(table_name,engine,index=False, if_exists=method)
def get_api_configurations(query):
api_authentication_query = query
df_api_auth = get_data_from_database_for_sql(api_authentication_query)
for line,row in df_api_auth.iterrows():
username = str(row['username'])
password = str(row['pwd'])
api_endpoint = str(row['endpoint'])
tablename=str(row['tablename'])
return username, password, api_endpoint,tablename
|
# -*- coding: utf-8 -*-
"""
@author: Asish Yadav
"""
dicti = {1:'bed', 2:'bath' , 3:'bedbath' , 4:'and' , 5:'beyond'}
arr = []
string = "bedbathandbeyond"
p = 0
for i in range(len(string)):
for key in dicti:
if string[p:i+1] == dicti[key]:
arr.append(string[p:i+1])
p = i+1
print (arr)
|
# - * - coding:utf8 - * - -
'''
@ Author : Tinkle G
'''
def checkdigits(s):
try:
float(s)
return True
except:
return False
def checkdigits_(s):
return any(char.isdigit() for char in s)
def jaccard_distance(tem,que):
cnt = 0
ret = []
for idx in range(len(que)):
if tem[idx] == que[idx] or tem[idx] == '*':
cnt +=1
ret.append(tem[idx])
else:
ret.append('*')
return cnt,ret
def edit_distance(tem,que):
ret = []
for idx in range(len(que)):
if tem[idx] == que[idx]:
ret.append(tem[idx])
else:
ret.append('*')
return ret |
print('''pick one:
foarfece
hartie
piatra''')
print(" ")
print(" ")
while True:
game_dict = {"piatra" : 1, "foarfece" : 2, "hartie" : 3}
player1 = input("Player A: ")
player2 = input("Player B: ")
a = game_dict.get(player1)
b = game_dict.get(player2)
dif = a-b
if dif in [-1, 2] :
print("player A wins ")
if input("Doriti sa mai incercati?, y sau n \n") == "y" :
continue
else:
print("jocul s-a sfarsit")
print(" ")
break
elif dif in [-2, 1] :
print("player B wins")
if input("Doriti sa mai incercati?, y sau n \n") == "y" :
continue
else:
print("jocul s-a sfarsit")
print(" ")
break
else :
print("egalitate, mai incercati \n")
print(" ")
|
# handles horizontal rotation
def horizontal_move_checker(num, list, index):
if num > len(list[index[0]]) - 1:
num = 0
if num < 0:
num = len(list[index[0]]) - 1
return num
# prevents vertical movement off the board
def vertical_move_checker(num, list, index):
if num > len(list) - 1:
num = num - 1
if num < 0:
num = 0
return num
def super_street_fighter_selection(fighters, position, moves):
index = list(position) # holds the current space on the character list
move_order = [] # return value
for move in moves:
# handles upward moves
if move == "up":
index[0] = index[0] - 1
index[0] = vertical_move_checker(index[0], fighters, index)
# if space is empty revert the move
if fighters[index[0]][index[1]] == "":
index[0] = index[0] + 1
# handles downward moves
if move == "down":
index[0] = index[0] + 1
index[0] = vertical_move_checker(index[0], fighters, index)
# if space is empty revert the move
if fighters[index[0]][index[1]] == "":
index[0] = index[0] - 1
# handles leftward moves
if move == "left":
index[1] = index[1] - 1
index[1] = horizontal_move_checker(index[1], fighters, index)
# continue moving left untill were at a fighter
while fighters[index[0]][index[1]] == "":
index[1] = index[1] - 1
index[1] = horizontal_move_checker(index[1], fighters, index)
# handles rightward moves
if move == "right":
index[1] = index[1] + 1
index[1] = horizontal_move_checker(index[1], fighters, index)
# continue moving right untill were at a fighter
while fighters[index[0]][index[1]] == "":
index[1] = index[1] + 1
index[1] = horizontal_move_checker(index[1], fighters, index)
# add the fighter at the new postion to our return value
move_order.append(fighters[index[0]][index[1]])
return move_order
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 20:01:42 2020
@author: Julio
"""
''' Using numpy.zeros '''
from numpy import zeros
student_numb = int(input("Enter number of students: "))
gpa = zeros(student_numb,float)
i = 0
while i < student_numb:
gpa[i] = float(input("Enter the GPA of student: "))
i = i + 1
average = sum(gpa)/len(gpa)
print("Average GPA of class is: \n", average) |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 18:16:38 2020
@author: Julio
"""
''' We are creating a 3D function '''
import numpy as np
import matplotlib.pyplot as plt
''' Creating a 2D function: sinusoidal 2D '''
# Like solutions of wave or Schr. equations.
# Rectangular boundary conditions
def fsin(x, y, m, n):
z = np.sin( m*np.pi*x)*np.sin(n*np.pi*y)
return z
# Defining the domain of x and y
x_domain = np.arange( -1, 1.01, 0.01 )
y_domain = np.arange( -1, 1.01, 0.01 )
# Using the command "len" will give is the size of an array
# Number of data points
nx = len(x_domain)
ny = len(y_domain)
# Using an empty 2D array to store the 'results'
z_range = np.zeros((nx,ny))
# defining parameters
m = 1.55
n = 0.55
for i in range(0,nx):
for j in range(0,ny):
z_range[i,j] = fsin(x_domain[i], y_domain[j], m, n )
''' Plotting it in 2D '''
plt.imshow( z_range, cmap=plt.cm.jet, interpolation='nearest' )
plt.show()
|
#for the print of star
i=1
#spacing
j=2
while (i>=1):
a=" "*j+"*"*i+" "*j
print(a)
i+=2
j-=1
if i>5:
break;
j=1
i=3
while i>=1:
a=" "*j+"*"*i+" "*j
print(a)
j+=1
i-=2 |
# 定义一个列表
a = [1,2,3,4,5,6]
# 循环打印所有元素
for i in a:
print(i)
|
def isprime(n):
n *= 1.0
if n %2 == 0 and n != 2 or n % 3 == 0 and n != 3:
return False
for b in range(1, int((n ** 0.5 + 1) / 6.0 + 1)):
if n % (6 * b - 1) == 0:
return False
if n % (6 * b + 1) == 0:
return False
return True
def main():
f = open('pi.txt', 'r')
d = f.readline(7)
while True:
n = f.readline(1)
if len(n):
d = d[1:7] + n
if d == d[::-1]:
if isprime(int(d)):
print d
break # remove this break to see more solutions
else:
break
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import os
import sys
class Replacer:
_BOTH_CASE_CHARS = """
а,a
е,e
о,o
р,p
с,c
х,x
"""
_UPPERCASE_CHARS = """
З,3
К,K
М,M
Н,H
Т,T
"""
_LOWERCASE_CHARS = "у,y"
def __init__(self):
self.replacements = []
for char_list in (self._UPPERCASE_CHARS, self._LOWERCASE_CHARS):
for pair in self.parse_replacements(char_list):
self.replacements.append(pair)
for pair in self.parse_replacements(self._BOTH_CASE_CHARS, convert=True):
self.replacements.append(pair)
@staticmethod
def parse_replacements(s: str, convert: bool = False):
out = []
for line in re.split("[\r\n]+", s):
line = line.strip()
if len(line) < 3:
continue
chars = re.split("[,]+", line)
if len(chars) > 1:
out.append(chars)
if convert:
out.append(list(map(lambda x: x.upper(), chars)))
return out
def replace(self, s: str):
for replacement_pair in self.replacements:
s = s.replace(*replacement_pair)
return s
if __name__ == '__main__':
target = ""
try:
target = sys.argv[1]
except IndexError:
raise ValueError("You need to specify file or string!")
string = target
if os.path.isfile(target):
with open(file=target, mode="r", encoding="utf-8") as f:
string = f.read()
f.close()
replacer = Replacer()
output = replacer.replace(string)
if not os.path.isfile(target):
print(output)
else:
target1, target2 = os.path.splitext(target)
with open(file="{}_cyr2lat.{}".format(target1, target2), mode="w", encoding="utf-8") as f:
f.write(output)
f.close()
|
import random
import sys
import string
a=string.ascii_lowercase
b=string.ascii_uppercase
c=string.digits
d=string.punctuation
def gen():
print("Enter the password length")
e = int(input())# Enter password length
f = random.randint(1,e-3)
g = random.randint(1,e-f-2)
h = random.randint(1,e-f-g-1)
i = e-f-g-h
a_1 = random.choices(a,weights=None,cum_weights=None,k=f)
a_2 = random.choices(b,weights=None,cum_weights=None,k=g)
a_3 = random.choices(c,weights=None,cum_weights=None,k=h)
a_4 = random.choices(d,weights=None,cum_weights=None,k=i)
pas = a_1 + a_2 + a_3 + a_4
random.shuffle(pas)
random.shuffle(pas)
pas_string = ''.join(map(str ,pas))
print("Here is your strong password: ",pas_string)
x = "start"
while x == "start" :
gen()
print("Type 'start' to generate another password or type anything to close")
x = input()
else:
print("Thank you for using my software................... Have a nice day")
sys.exit()
|
import pprint
import random
import warnings
import numpy as np
from strategy import Game
pp = pprint.PrettyPrinter(indent=4)
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
def get_user_input():
pay_to_play = input(
"\nHow much would you like to bet? Input an amount with numbers and\ndecimals"\
"only (e.g. 1.50).\n >> "
)
try:
buyin_fee = float(pay_to_play)
except:
print("Unknown input. Using default value: $1.50")
buyin_fee = 1.50
see_each_move = input("\nWould you like to see each move? Y/N:\n >> ")
if see_each_move == "Y":
verbose = True
elif see_each_move == "N":
verbose = False
else:
print("Unknown input. Using default value: verbose = False")
verbose = False
simple_or_strategic = input("\nChoose a mode:\n1) Strategic\n2) Simple\n >> ")
if simple_or_strategic == "1":
turn = "strategic"
elif simple_or_strategic == "2":
turn = "simple"
else:
print("Unknown input. Using default value: strategic")
turn = "strategic"
return buyin_fee, verbose, turn
def main():
print("--- STRATEGIC SOLITAIRE ---")
fee, output, mode = get_user_input()
# Set up betting info
payout = 0
buyin_fee = fee
place_amount = buyin_fee * 0.3
bonus_amount = buyin_fee * 3
seed = 84 # Set to None for random state; 84 for win state
random.seed(seed)
verbose = output
turn = mode
play = Game()
play.simulate(turn=turn, verbose=verbose)
if play.win():
result = 1
payout += (52 * place_amount) + bonus_amount
print(f"\nYou won! Total winnings: {payout - buyin_fee}\n")
else:
result = 0
placed = [
np.sum([1 for card in play.ace_stacks[i].cards])
for i in list(play.ace_stacks.keys())
]
payout += np.sum(placed) * place_amount
print(f"\nYou lost! Try again. Total winnings: {payout - buyin_fee}\n")
return
if __name__ == "__main__":
main()
|
"""
A Python list is similar to an array in other languages. In Python, an empty
list can be created in the following ways
"""
my_list = []
my_list = list()
"""
As you can see, you can create the list using square brackets or by using the
Python built-in, list. A list contains a list of elements, such as strings,
integers, objects or a mixture of types. Let’s take a look at some examples:
"""
my_list = [1,2,3]
my_list2 = ["a", "b", "c"]
my_list3 = ["a", 1, "Python", 5]
"""
The first list has 3 integers, the second has 3 strings and the third has a
mixture. You can also create lists of lists like this:
"""
"""
A nested list is simply a list that occurs as an element of another list
(which may of course itself be an element of another list, etc.). Common reasons
nested lists arise are: They're matrices (a list of rows, where each row is
itself a list, or a list of columns where each column is itself a list).
"""
my_nested_list = [my_list, my_list2]
my_nested_list
#Output
"""
[[1, 2, 3], ['a', 'b', 'c']]
"""
|
# This subprogram calculate digit sum
import sys
import os
if __name__ == '__main__':
# Get process arguments
argv = sys.argv[1::]
result = 0
if len(argv) >= 2:
for i in argv:
result += int(i)
print('Result: ' + str(result)) |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import *
def qqplot(x_array, qpoints = 100):
## Standarlize the dataset
x_array_norm = (x_array - np.mean(x_array))/np.std(x_array)
## Here only consider 99 points. So that we will consider 1%, 2%,...,99%
x_leng = len(x_array)
quantiles = [(1.0 * i/100) for i in range(1, qpoints)]
## initialization the placeholders for the normal distribution and customized data
normal = np.empty(qpoints - 1)
result = np.empty(qpoints - 1)
for k in range(0, qpoints - 1):
q = quantiles[k]
## This is the way to calculate the qth quantile, both value and position.
i = q *(x_leng + 1) - 1
j = int(np.floor(i))
res = x_array_norm[j] + (x_array_norm[j + 1]-x_array_norm[j])*(i - j)
result[k] = res
normal[k] = norm.ppf(q)
return result, normal
if __name__ == "__main__":
data_points = sorted(np.random.normal(0, 1, 100))
result, normal = qqplot(data_points)
plt.plot(np.linspace(-2,2,100), np.linspace(-2,2,100), '-')
plt.plot(result, normal, '.')
plt.show()
|
# coding:utf-8
import time
def fibrac(x):
if (x == 1 or x == 2):
return 1
return fibrac(x - 1) + fibrac(x - 2)
start = time.clock()
a = fibrac(45);
end = time.clock()
print("=======", a);
print("=======", (end-start)*1000);
|
#
# @lc app=leetcode.cn id=7 lang=python
#
# [7] 整数反转
#
# https://leetcode-cn.com/problems/reverse-integer/description/
#
# algorithms
# Easy (32.22%)
# Total Accepted: 111.9K
# Total Submissions: 347.4K
# Testcase Example: '123'
#
# 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
#
# 示例 1:
#
# 输入: 123
# 输出: 321
#
#
# 示例 2:
#
# 输入: -123
# 输出: -321
#
#
# 示例 3:
#
# 输入: 120
# 输出: 21
#
#
# 注意:
#
# 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
#
#
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
def reverse1(st):
return st[::-1]
result = 0
if x < 0:
x = -x
s = '{0}'.format(x)
result = int(reverse1(s))*-1
else:
s = '{0}'.format(x)
result = int(reverse1(s))
if result < -2147483648 or result > 2147483647:
return 0
else:
return result
|
#
# @lc app=leetcode.cn id=231 lang=python3
#
# [231] 2的幂
#
# https://leetcode-cn.com/problems/power-of-two/description/
#
# algorithms
# Easy (44.89%)
# Total Accepted: 16.1K
# Total Submissions: 35.9K
# Testcase Example: '1'
#
# 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
#
# 示例 1:
#
# 输入: 1
# 输出: true
# 解释: 2^0 = 1
#
# 示例 2:
#
# 输入: 16
# 输出: true
# 解释: 2^4 = 16
#
# 示例 3:
#
# 输入: 218
# 输出: false
#
#
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n<0:
return False
# 将输入的数字转为二进制,同时转为字符串
temp="{0:b}".format(n)
# 如果二进制字符串只有一个1,那么这个数就是2的幂
if temp.count('1')==1:
return True
else:
return False
神仙='''
def isPowerOfTwo(self, n):
return (n>0) and (n & (n-1))==0
神仙题。。没见过就不会,见过就会了。
重点在于对位运算符的理解
解法 1:& 运算,同 1 则 1。 return (n > 0) && (n & -n) == n;
解释:2 的幂次方在二进制下,只有 1 位是 1,其余全是 0。例如:8---00001000。负数的在计算机中二进制表示为补码 (原码 -> 正常二进制表示,原码按位取反 (0-1,1-0),最后再 + 1。然后两者进行与操作,得到的肯定是原码中最后一个二进制的 1。例如 8&(-8)->00001000 & 11111000 得 00001000,即 8。 建议自己动手算一下,按照这个流程来一遍,加深印象。
解法 2:移位运算:把二进制数进行左右移位。左移 1 位,扩大 2 倍;右移 1 位,缩小 2 倍。 return (n>0) && (1<<30) % n == 0;
解释:1<<30 得到最大的 2 的整数次幂,对 n 取模如果等于 0,说明 n 只有因子 2。
'''
|
print("I will now count my chickens.")
print("Hens", 25.0 + 30.0 /6.0) # order of operation 30/6 = 5 plus 25 = 30
print ("Roosters", 100.0 - 25.0 * 3.0 % 4.0)
print("Now I will count the eggs")
print( 3.0 + 2.0 + 1.0 -5.0 + 4.0 % 2.0 -1.0 / 4.0 + 6.0)
print("Is it true that 3.0 + 2.0 < 5.0 - 7.0?")
print (3.0 + 2.0 < 5.0 - 7.0)
print("What is 3 + 2?", 3.0 + 2.0)
print ("What is 5 -7?" , 5.0 - 7.0 )
print("Oh, thats why its False.")
print("How about some more.")
print ("is it greater?" , 5.0 > -2.0)
print ("Is it greater than or equal?" , 5.0 >= -2.0)
print ("is it less than or equal?" , 5.0 <= -2.0)
|
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def show(self):
print "Show Person Details"
def rev(self,name):
st=""
for i in range(len(name),0,-1):
st=st+name[i-1]
print("kkk: "+st)
def list_fr(self):
fr=["apple","banana"]
map(lambda n:n[::-1],fr)
p1=Person("Abc",123)
print p1.age
del p1.age
p1.age=10
print p1.age
print p1.name
p1.show()
p1.rev("abc")
p1.list_fr() |
"""
This file will contain the GameModel, used to...model the game model in the model/controller/view framework. Technically
this is an abstract class and/or informal interface, which will be implemented by specific game models for flexibility.
TODO should the controller ask the model for text, or should the model tell the controller when text changes? I'm going
TODO to have the model call the controller when text changes
started 7/28/20 by Andrew Curry
"""
from typing import Dict
# from game_controller.game_controller import GameController
class GameModel:
"""
An informal interface that describes what game models will need to implement.
TODO description
"""
def game_launched(self) -> Dict[str, str]:
"""
What to do when the game is launched/opened. Returns the initial texts to be displayed.
TODO necessary?
:return: The initial output texts
"""
pass
def player_quit(self):
"""
What to do when the user is quitting. Takes care of business in the model and tells the controller.
TODO necessary?
:return:
"""
pass
def load_scenario_data(self, scenario: str = "default"):
"""
Load the starting data for the given scenario - rooms, flags, events, commands, descs, etc.
:param scenario: The name (or filename?) of the scenario to be loaded
:return:
"""
pass
def load_save_file(self, filename):
"""
Load the flag data from the given save file
:param filename: the name of the save file
:return:
"""
pass
def game_start(self) -> dict:
"""
Indicates that gameplay can start. Called by the game controller to allow actual gameplay logic to begin
:return: the initial texts to show to the player (or false if game couldn't start)
"""
pass
def game_stop(self):
"""
Indicates that gameplay will stop. Caled by the game controller to end/pause gamemplay logic
:return:
"""
pass
def update(self, input_text: str) -> Dict[str, str]:
"""
The core gameplay logic. Called by the controller when there's input to be processed.
:return: The dict of text(s) to be displayed on screen.
"""
pass
def is_playing(self):
"""
Called by the controller to determine if the game has been quit.
:return: True if gameplay will continue, False otherwise
"""
pass
def set_controller(self, controller):
"""
Called by the controller to connect itself to the model.
(I don't know if this is necessary but it seems safer?)
:param controller: The GameController
:return:
"""
pass
# end class GameModel
|
"""
This file is for code relating to commands - they connect an expected input pattern to an in-game effect.
- Started 5/25/20, by Andrew Curry
- reworked 7/28/20, to put the text parsing logic in here, as well as minor refactoring and including how command data
is loaded
- tweaked text parsing to allow for multiple possible string literal matches (eg [["get, "take], "ye", "flask"]
"""
# imports ------
from enum import Enum
# from scenario_data import command_data # obviously this is bad lul
# helper code/classes/variables/etc
class PatElm:
"""
Stands for Pattern Elements. TODO consider renaming?
These are keywords (ish) used to give instructions to the text parsing logic.
"""
ANY_ONE_WORD = "_ANY_ONE_WORD" # any ONE word will satisfy this part of the pattern
ANY_AT_LEAST_ONE_WORD = "_ANY_AT_LEAST_ONE_WORD" # as long as there is at least an element in this position,
# any input will satisfy this condition
ANY_NONE_OKAY = "_ANY_NONE_OKAY" # the parser will confirm any input once it gets to this element of the pattern
# - even if there is nothing
ANY_ALPHA = "_ANY_ALPHA" # any word without numeric characters
ANY_NUMBER = "_ANY_NUMBER" # any 'word' with only numeric characters (0 - 9)
ANY_CHARACTER = "_ANY_CHARACTER" # any single character
ANY_LETTER = "_ANY_LETTER" # any single letter character
ANY_DIGIT = "_ANY_DIGIT" # any single numerical digit character
END = "_END" # make sure the input is done
# end PatElm enum class
class Command:
"""
The Command class, essetinally representing input that the game (through rooms) anticipates the player to input.
Each command object has: a command-key for itself (string?), an event-key for the event it triggers (string?), and
a list representing a pattern of expected input
"""
# class-level stuff ------------
@classmethod
def find_match(cls, input_text: str, commands: list): # TODO can't specify list of commands?
"""
Takes the user's text and finds the first command it matches in the list.
:param input_text: the player's input text
:param commands: the possible commands the game is expecting right now. They will be checked in order; if there
are multiple matches only the first is returned. There should be a catch-all ("i didn't understand that")
command at the end.
:return: the FIRST command that matches what the player input.
TODO maybe i'll have it raise an exception if the list runs out
"""
# convert the text string to a list
input_list = input_text.split() # TODO make this it's own function if things get more complicated
# check each command
for cmd in commands:
matched = cmd.check_input(input_list)
if matched:
return cmd # return the right command
# end find_match function -----------------------------------------------
# instance-level stuff ----------
def __init__(self, key: str, event_key: str, pattern: list = []):
"""
The constructor.
:param key: the unique identifier for this command (string?)
:param event_key: the unique identifier for the event triggered by this command (string?)
:param pattern: a list representing a pattern of expected input, used to see if the user's text input matches
"""
self.key = key # do they need to know their own keys?
self.event_key = event_key
self.pattern = pattern
# end init ------------------------------------------
def __str__(self):
"""
The to-string method.
:return a string representation of this object
"""
return "<(" + str(self.key) + " " + str(self.event_key) + ")" + " " + str(self.pattern) + ">"
# end __str__ function
def check_input(self, input_list: list): # TODO how to indicate list of only strings?
"""
Determines if the given player input matches with this command. NOTE: this was transferred from another module
so there may be problems with this code later.
Also this used to make everything lower case but I made the view force lower case so it's unneeded?
:param input_list: a list of strings, each string being a word from the player's input
:return: True if the given input matches this command, False otherwise
"""
# basically keep going through the input and command until we find something that doesn't match
# or if we find certain escape sequences in the command (like ANY)
p_length = len(self.pattern) # does this actually save time?
input_length = len(input_list)
for i in range(0, p_length): # dont use for p in self.pattern cuz we need to get input_list[i] later too
p = self.pattern[i] # the current pattern element #TODO better name than p?
if p == PatElm.ANY_NONE_OKAY:
return True
# see if the input is not long enough
if i >= input_length:
return p == PatElm.END # is it supposed to be the end?
# we know there's at least one word left
if p == PatElm.ANY_AT_LEAST_ONE_WORD:
return True
if p == PatElm.ANY_ONE_WORD:
continue # we're good so far, keep checking
# now we can safely get the current word
word = input_list[i]
if p == PatElm.ANY_CHARACTER:
if len(word) == 1:
continue
else:
return False
if p == PatElm.ANY_LETTER:
if len(word) == 1 and word.isalpha():
continue
else:
return False
if p == PatElm.ANY_DIGIT:
if len(word) == 1 and word.isdigit():
continue
else:
return False
if p == PatElm.ANY_ALPHA:
# print("DEBUG: got to if p == ANY_ALPHA, word is:", word)
if word.isalpha():
continue
else:
return False
if p == PatElm.ANY_NUMBER:
if word.isdigit():
continue
else:
return False
# at this point we're only looking for exact matches
# OR lists of possible matches (first cuz lists can't .lower())
if isinstance(p, list):
if word in p:
continue
else:
return False
if p == word:
continue
else:
return False
# end for loop
return True # if we get to the end, we haven't found a problem yet
# end check_input method
# end class Command
# test functions TODO do these belong here?
def test_text_parsing():
"""
what it looks like
:return:
"""
commands = list()
commands.append(Command('c1', 'e1', ['go', 'dennis', PatElm.END]))
commands.append(Command('c2', 'e2', ['go', 'dennis', PatElm.ANY_AT_LEAST_ONE_WORD]))
commands.append(Command('c3', 'e3', ['get', 'ye', 'flask', PatElm.ANY_NONE_OKAY]))
commands.append(Command('c4', 'e4', [PatElm.ANY_NUMBER, 'swag', PatElm.END]))
commands.append(Command('c5', 'e5', [PatElm.ANY_CHARACTER, PatElm.ANY_LETTER, PatElm.ANY_DIGIT, PatElm.ANY_NONE_OKAY]))
commands.append(Command('c_end', 'e_end', [PatElm.ANY_NONE_OKAY]))
for cmd in commands:
print(cmd)
print("\n\n\n\n")
input1 = "go dennis"
print(input1 + " " + str(Command.find_match(input1, commands)))
input2 = "go dennis again okay just do it"
print(input2 + " " + str(Command.find_match(input2, commands)))
input3 = "get ye flask"
print(input3 + " " + str(Command.find_match(input3, commands)))
input4 = "420 swag"
print(input4 + " " + str(Command.find_match(input4, commands)))
input5 = "a b 3 afsdklfasdjkfasfd"
print(input5 + " " + str(Command.find_match(input5, commands)))
input6 = "this should fail"
print(input6 + " " + str(Command.find_match(input6, commands)))
input7 = "a a a a a a a a"
print(input7 + " " + str(Command.find_match(input7, commands)))
# end test_input_parsing function
|
number = float(input("실수입력 >>"))
print(number * 3)
|
#주석문..코드상의 결과에 영항을 미치지 않음
#그 코드의 설명을 적는다
def typecheck(val):
print(type(val))
p = 0 #p 정수변수
s = "i love you" #s는 문자열 변수
w = 2.5 #w는 실수 변수
d = True #d는 부울 변수(True, False)
print(p)
print(s)
print(w)
print(d)
result = type(p)
print(type(p), type(s), type(w), type(d))
typecheck(p)
typecheck(s)
typecheck(w)
typecheck(d)
typecheck(result)
|
#2020년 나이를 기반으로 학년계산
birth = int(input("태어난 년도를 입력하세요 >>"))
age = 2020 - int(birth) + 1
print(age,"세")
if age <= 26 and age >= 20:
print("대학생")
elif age < 20 and age >= 17:
print("고등학생")
elif age < 17 and age >= 14:
print("중학생")
elif age < 14 and age >= 8:
print("초등학생")
else:
print("학생이 아님") |
#두수를 입력 받아 대소관계 비교
num1 = int(input("첫번째 수를 입력하시오\n"))
num2 = int(input("두번째 수를 입력하시오\n"))
if num1 > num2:
print(num1, ">", num2)
elif num1 < num2:
print(num1, "<", num2)
else:
print(num1, "==", num2) |
# SCRIPT: replaceNeg.py
# AUTHOR: Sahar Kausar
# CONTACT: saharkausar@gmail.com
#
# Anita Borg - Python Certification Course
#
# DESCRIPTION: Input a list of integers containing both positive and negative numbers.
# You have to print a list in which all the negative integers of this list are replaced by their
# squares and all the positive numbers are left as it is.
# Note: This problem can also be done without using list comprehension but since this is a
# challenge on List Comprehension, you need to complete this using a single list comprehension statement.
"""
Sample Input1:
2 -3 4 5 -1
Sample Output1:
[2, 9, 4, 5, 1]
"""
#Accepts a list of numbers from the user and stores them in a list
enterInput = [int(m) for m in input("Please enter a list of integers separated by a space: ").split()]
#Squares the numbers if they are negative from the inputted list
new_list = [m**2 if m < 0 else m for m in enterInput]
#Prints out the new list
print(new_list)
|
#-----------------------------------------------------------------#
# SCRIPT: listGen.py
# AUTHOR: Sahar Kausar
# CONTACT: saharkausar@gmail.com
#
# Anita Borg - Python Certification Course
#
# DESCRIPTION: A Python program which accepts a sequence of comma-separated numbers from the user and generates a list and a tuple with those numbers.
"""
Sample data: 3, 5, 7, 23
Output:
List: ['3, '5', '7', '23']
Tuple: ('3, '5', '7', '23')
"""
gen = input("Sample sequence: 3,5,7,23 \nPlease enter a desired sequence of comma-separated numbers: ")
genList = gen.split(",")
genTuple = tuple(genList)
print("Output: \nList:",genList,"\nTuple:",genTuple)
|
# SCRIPT: computePerf.py
# AUTHOR: Sahar Kausar
# CONTACT: saharkausar@gmail.com
#
# Anita Borg - Python Certification Course
#
# DESCRIPTION: Compute the performance of list comprehension vs. a for loop.
# Write two functions and use the Python time module to measure their execution time.
import time
#Code for testing list comprehension
start_comp = time.time()
list_comp = [i for i in range (1450000)]
final_comp = (time.time() - start_comp)
#Code for testing for loop
start_loop = time.time()
list_loop = []
for m in range(1450000):
list_loop.append(m)
final_loop = (time.time() - start_loop)
#Prints the result
print("The time taken to execute creating a list using list comprehension was {} hs while it was {} hs for a for loop!".format(final_comp, final_loop))
print("It is quicker to create a list using list comprehension than a for loop!")
|
# SCRIPT: cipherClient.py
# AUTHOR: Sahar Kausar
# CONTACT: saharkausar@gmail.com
#
# Anita Borg - Python Certification Course
#
# DESCRIPTION: A Python program that decodes hidden messages, specifically - Caesar Ciphers utilizing the standard English alphabet.
# Our Caesar Cipher will be based on shifting all the letters to the right by three positions.
# So the encryption translates as follows:
# Plain English Alphabet: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
# Cipher: 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
# In our code the word “CAT” becomes “ZXQ” and “HELLO” becomes “EBIIL”.
#
# NOTE: This file is the client file (cipherClient.py) that should be used in tandem with the server file (cipherServer.py)
"""
Sample Scenario 1:
Client sends: Jlkqv Mvqelk
Server sends back:
Received: Jlkqv Mvqelk
Translation: monty python
Sample Scenario 2:
Client sends:
QEXKH VLR XKFQXYLOD
Server sends back:
Received: QEXKH VLR XKFQXYLOD
Translation: thank you anitaborg
Received: f zlria dl clo pljb QXZLP
Translation: I COULD GO FOR SOME TACOS
"""
#Imports the socket module
import socket
client_socket = socket.socket()
#Binds the socket object to local host 4000 as a socket server
client_socket.connect(("localhost", 4000))
#Input taken from the user to store in a variable 'init_msg'
init_msg = input("Please enter a string of text to decode: ")
#Sends the 'init_msg' string to the server to begin the caesar cipher shift
client_socket.send(init_msg.encode())
#Output from the server that is received as a response (input into the client socket)
new_msg = client_socket.recv(1024)
#Prints out the decrypted message
print(new_msg.decode())
#Closes the connection
client_socket.close()
|
from tkinter import *
import math
class Risanje:
def __init__(self,master):
# ustvarimo platno
self.platno=Canvas(master,width=500,height=500)
self.platno.pack() #z pack umestiš na platno
#piramida(self.platno,8,400,50,20)
#tarca(self.platno,8,150,200,10)
#trikotnik(self.platno,7,250,250,160)
torta(self.platno,[30,15,20,35],250,250,100)
menu = Menu(okno)
menuNarisi = Menu(menu, tearoff=0)
menuPobrisi = Menu(menu, tearoff=0)
okno.config(menu=menu)
menu.add_cascade(label='Narisi', menu=menuNarisi)
menuNarisi.add_command(label = 'Piramida', command = self.piramida)
def piramida(platno, n, x, y, d):
for i in range(n):
platno.create_rectangle(x-(i+1)*d,y+i*d,x+(i+1)*d,y+(i-1)*d,fill="orange",outline="")
def tarca(platno,n,x,y,d):
for i in range(n,0,-1):
barva="white"if i%2== 0 else "black"
platno.create_oval(x-i*d, y-i*d, x+i*d, y+i*d, fill=barva, outline="black")
def trikotnik(platno,n,x,y,d):
if n==1:
platno.create_polygon(x,y,x+d,y,x+d/2,y-d*math.sqrt(3)/2, fill="",outline="black")
else:
trikotnik(platno,n-1,x,y,d/2)
trikotnik(platno,n-1,x+d/2,y,d/2)
trikotnik(platno,n-1,x+d/4,y-d*math.sqrt(3)/4,d/2)
barve=["blue","red","black","orange"]
def torta(platno,podatki,x,y,r):
zacetni=0
for i in range(len(podatki)):
koncni = podatki[i] / sum(podatki) * 360
platno.create_arc(x+r,y+r,x-r,y-r,start=zacetni,extent=koncni,style=PIESLICE,fill=barve[i],outline="black")
zacetni+=koncni
okno = Tk()
app = Risanje(okno)
okno.mainloop()
|
"""
Nick Conway Wyss Institute 02-02-2010
Parses a basecall file
The basecall file is parsed as follows since it is a tab delimited text
file
FLOWCELL# LANE# IMAGE# BEAD# N Xtab FLAG
0 1 2 3 length-1
one basecall file per lane
N is the read sequence of a bead containing X bases
Xtab indicates that X tabbed fields exist for a given read
the number of beads flagged per lane in a given basecall file is in the
*.hit_summary file
in a tab delimited fashion
Since each basecall file is for a given lane of a given flowcell,
searching is simple
"""
class BaseCall:
def __init__(self,filename):
"""
initializes the class opens the file and
loads the first entry of the class
expects the file "filename" to be tab delimited
"""
self.file = open(filename, 'r')
# the current entry read from the basecall file
self._entry = 0
self._EOF = False
# read the first entry
self.read_entry()
# flag_index is the index of the last field in a line
self._flag_index = len(self._entry)-1
#
self._base_count = self._flag_index - 6 + 1 # 6 fields minimum
#end def
def open(self,filename):
"""
Open the basecall file and get the file descriptor
"""
self.file = open(filename, 'r')
# end def
def close(self):
"""
Close the basecall file descriptor pointer
"""
self.file.close()
#end def
def base_count(self):
"""
returns the number of bases read per bead in a basecall file
this is a reflection on the line length
"""
return self._base_count
# end def
def read_entry(self):
"""
return a tuple of data from an entry in the basecall file
loads data into the class variable
"""
basecall_line = self.file.readline()
# split the line by fields
basecall_columns = basecall_line.split()
self._EOF = not (len(basecall_columns))
if (self._EOF): # breaks the loop when a line length is zero
# indicating EOF
#print 'breaking'
#print 'a'+ base_call_line + 'b'
print('STATUS: reached end of basescall file, line of zero length')
self._entry = [] # if no longer reading a line
# end if
else:
self._entry = basecall_columns
# end else
# end def
def isEOF(self):
return self._EOF
#end def
def get_entry(self):
return self._entry
# end def
def get_flowcell(self):
return int(self._entry[0])
#end
def get_lane(self):
return int(self._entry[1])
# end def
def get_image_num(self):
return int(self._entry[2])
# end def
def get_bead_num(self):
return int(self._entry[3])
# end def
def get_flag(self):
"""
Return 1 if flagged
0 otherwise
A line is flagged as a "1" if the bead is to be released or a match
in some sense.
Return the flag of current entry
"""
return int(self._entry[self._flag_index])
# end def
def seek_image(self,image_num):
"""
Read lines until we get a line that has something in it
This is a little weak as far as exceptions go
"""
while True:
self.read_entry()
if (len(self._entry) == 0):
break
# end if
elif self.get_image_num() == image_num:
break
# end elif
# end while
# end def
|
##This program is used to determine the most frequent k-mer (using k=3 as an example) in a given DNA sequence.
import itertools
def countkmers(sequence, k = 3):
bases = ["A","T","C","G"]
kms = [''.join(x) for x in itertools.product('ATGC', repeat=3)] ## create all possible conbinations of k-mers as a dictionary
Possible_kmers = dict.fromkeys(kms,0) ## assign all values as 0 in the dictionary
for key in Possible_kmers:
for i in range(len(sequence)-k+1):
if sequence[i:i+k] == key:
Possible_kmers[key] += 1
return Possible_kmers
most = countkmers("CGGAGGACTCTAGGTAACGCTTATCAGGTCCATAGGACATTCA",3)
print(most)
print type(most) ## output will be <type 'dict'>
print(max(most,key=most.get)) ##output will be the most frequenct kmer
|
import sys
sum = 0
n = 0
#sum input values
for number in open('data.txt'):
suma+=float(number)
new_change
n +=1
print suma/n
new_sth
#comment
## Hi! I'm just writting a comment!! Did not modify anything else!! :-)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
dummy = ListNode(0, head)
newbegin = dummy
for i in range(left-1):
newbegin = newbegin.next
tmphead = newbegin.next
for i in range(right-left):
lasthead = tmphead.next
newbegin.next, lasthead.next, tmphead.next = lasthead, newbegin.next, lasthead.next
return dummy.next
|
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def quickSort(nums, l, r):
if l >= r: return
flag = nums[r] # random better
s = l
for i in range(l, r):
if nums[i] < flag:
if i != s:
nums[i], nums[s] = nums[s], nums[i]
s += 1
nums[s], nums[r] = nums[r], nums[s]
quickSort(nums, l, s-1)
quickSort(nums, s+1, r)
def quickSort1(nums):
quickSort(nums, 0, len(nums)-1)
# quickSort1(nums)
# -----------------worst O(n^2)
def mergeSort(nums, l, r):
if l == r: return nums[l:l+1]
mid = (l + r) >> 1
n1 = mergeSort(nums, l, mid)
n2 = mergeSort(nums, mid+1, r)
i, j = 0, 0
f = l
while i < (mid - l + 1) and j < (r - mid):
if n1[i] < n2[j]:
nums[f] = n1[i]
i += 1
else:
nums[f] = n2[j]
j += 1
f += 1
while i < (mid - l + 1):
nums[f] = n1[i]
i += 1
f += 1
while j < (r - mid):
nums[f] = n2[j]
j += 1
f += 1
return nums[l:r+1]
# res = mergeSort(nums, 0, len(nums)-1)
# ------------
def down(nums, i, l):
lson = i<<1
rson = i<<1 | 1
if lson > l: return
j = lson
if rson <= l and nums[rson] > nums[lson]: j = rson
if nums[i] < nums[j]:
nums[i], nums[j] = nums[j], nums[i]
down(nums, j, l)
def buildHeap(nums, l):
for i in range(l>>1, 0, -1):
down(nums, i, l)
def heapSort(nums):
l = len(nums)
nums.insert(0, 0)
buildHeap(nums, l)
while l > 1:
nums[1], nums[l] = nums[l], nums[1]
l -= 1
down(nums, 1, l)
nums.pop(0)
# heapSort(nums)
return nums
|
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.d[key].append((value, timestamp))
def get(self, key: str, timestamp: int) -> str:
if not key in self.d: return ""
if self.d[key][0][1] > timestamp: return ""
n = len(self.d[key])
l, r = 0, n-1
while l <= r:
mid = (l+r) >> 1
if self.d[key][mid][1] > timestamp:
r = mid - 1
elif self.d[key][mid][1] == timestamp:
return self.d[key][mid][0]
else:
l = mid + 1
return self.d[key][r][0]
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
|
class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
x = click[0]
y = click[1]
m = len(board)
n = len(board[0])
a = board[x][y]
if a == 'M':
board[x][y] = 'X'
elif a == 'E':
num = 0
R = []
for i in range(-1,2):
for j in range(-1,2):
if x+i>=0 and x+i<m and y+j>=0 and y+j<n:
if board[x+i][y+j] == 'M':
num = num+1
elif board[x+i][y+j] == 'E':
R.append(x+i)
R.append(y+j)
if num:
board[x][y] = str(num)
else:
board[x][y] = 'B'
while R:
i = R.pop()
j = R.pop()
self.updateBoard(board, [j,i])
return board
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
fast = head
slow = head
reco = []
while fast.next:
reco.append(slow.val)
fast = fast.next
if fast.next:
fast = fast.next
slow = slow.next
while slow.next:
slow = slow.next
if slow.val != reco.pop():
return False
return True
# 修改列表,反转后半,比较,O(1)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
lmin = self.minDepth(root.left)
rmin = self.minDepth(root.right)
if lmin and rmin:
return min(lmin,rmin)+1
elif not lmin and not rmin:
return 1
elif lmin:
return lmin+1
else:
return rmin+1
|
################################
# CPE 101
# Section: 15
# Lab 1, Problem Set 1
# Name: Tyler Lian
# Cal Poly ID: tklian
################################
if __name__ == "__main__":
#### Problem #1 ####
# initialize variables
original_number = 0
# obtains user input and makes the string an int
user = input("Enter a number: ")
number = int(user)
# makes variable 'original_number' have the same value as 'number'
original_number = number
# uses the math equation for problem 1 on variable 'number'
number = number * 2
number = number + 10
number = number / 2
number = number - original_number
number = int(number)
# prints final output
print(number)
#### Problem #2 ####
# initializes the variables
user1, user2, sum1, sum2, sum3, sum4, sum5, sum6, sum7, sum8, finalsum, finalnum = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
# obtains user input
user1 = input("Enter a number: ")
user2 = input("Enter a number: ")
# applies math equation for problem 2 to user inputted variables
sum1 = int(user1) + int(user2)
sum2 = sum1 + int(user2)
sum3 = sum2 + sum1
sum4 = sum3 + sum2
sum5 = sum4 + sum3
sum6 = sum5 + sum4
sum7 = sum6 + sum5
sum8 = sum7 + sum6
# adds together all the sums created
finalsum = int(user1) + int(user2) + sum1 + sum2 + sum3 + sum4 + sum5 + sum6 + sum7 + sum8
# divides the final value by the 7th sum
finalnum = finalsum / sum5
# outputs the final value
print(finalnum)
#### Problem #3 ####
# initializes variables
number = ""
subtract = 0
# gets input from user
number = input("Enter a number: ")
number = int(number)
# splits number into 4 parts
a = number // 1000
b = (number - 1000 * a) // 100
c = (number - 1000 * a - 100 * b) // 10
d = (number - 1000 * a - 100 * b - 10 * c)
# rearranges the original number backwards
number2 = str(d) + str(b) + str(c) + str(a)
# turns strings into int variables
number2 = int(number2)
# subtracts smaller number from larger number
big = max(number,number2)
small = min(number,number2)
subtract = big - small
# splits the int into 4 parts
a = subtract // 1000
b = (subtract - 1000 * a) // 100
c = (subtract - 1000 * a - 100 * b) // 10
d = (subtract - 1000 * a - 100 * b - 10 * c)
# adds together individual digits
finishedsum = a + b + c + d
# splits the int into 2 parts
a = finishedsum // 10
b = (finishedsum - 10 * a)
# adds the variables together
final = a + b
#prints the final output
print(final)
#### Problem #4 ####
# initialized variables
a, b, c, d, e, f, g = 0, 0, 0, 0, 0, 0, 0
# obtains user input
number = input("Enter a number: ")
number = int(number)
# removes the numbers after the decimal point
number = number / 7
number = number * (10 ** 6)
number = int(number)
# seperates all the digits apart
a = number // 1000000
b = (number - 1000000 * a) // 100000
c = (number - 1000000 * a - 100000 * b) // 10000
d = (number - 1000000 * a - 100000 * b - 10000 * c) // 1000
e = (number - 1000000 * a - 100000 * b - 10000 * c - 1000 * d) // 100
f = (number - 1000000 * a - 100000 * b - 10000 * c - 1000 * d - 100 * e) // 10
g = (number - 1000000 * a - 100000 * b - 10000 * c - 1000 * d - 100 * e - 10 * f)
# adds all the digits together
final = b + c + d + e + f + g
# outputs answer
print(final) |
################################
# CPE 101
# Section: 15
# Lab 1, Problem Set 1
# Name: Tyler Lian
# Cal Poly ID: tklian
################################
if __name__ == "__main__":
# initializes variables
number = ""
subtract = 0
# gets input from user
number = input("Enter a number: ")
number = int(number)
# splits number into 4 parts
a = number//1000
b = (number - 1000 * a)//100
c = (number - 1000 * a - 100 * b)//10
d = (number - 1000 * a - 100 * b - 10 * c)
# rearranges the original number backwards
number2 = str(d) + str(b) + str(c) + str(a)
# turns strings into int variables
number2 = int(number2)
# subtracts smaller number from larger number
big = max(number,number2)
small = min(number,number2)
subtract = big - small
# splits the int into 4 parts
a = subtract//1000
b = (subtract - 1000 * a) // 100
c = (subtract - 1000 * a - 100 * b) // 10
d = (subtract - 1000 * a - 100 * b - 10 * c)
# adds together individual digits
finishedsum = a + b + c + d
# splits the int into 2 parts
a = finishedsum // 10
b = (finishedsum - 10 * a)
# adds the variables together
final = a + b
#prints the final output
print(final) |
import functions
number_list = []
i = 0
while i !=3:
numstr = input("Enter a number: ")
numint = int(numstr)
if functions.input_ok(numint):
number_list.append(numint)
i += 1
else:
print("Input must be less than one hundred and greater than zero")
for j in number_list:
functions.convert_to_text(j)
|
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enque(self, item):
self.items.append(item)
def dequeue(self):
if len(self.items) < 1:
return None
return self.items.pop()
def print_stack(self):
print(self.items)
def size(self):
return len(self.items)
q = Queue()
q.enque(2)
q.enque(1)
q.enque(4)
q.enque(45)
q.enque(76)
q.enque(30)
print(q.size())
q.print_stack()
q.dequeue()
print(q.size())
q.print_stack()
print(q.isEmpty())
|
cardNumber = int(input("Enter your credit card number without spaces: "))
def isValid(number):
number = str(number)
cardIsValid = False
result = sumDoubleEvenLocation(number) + sumOddLocation(number)
prefix = isPrefix(number, "4") or isPrefix(number, "5") or isPrefix(number, "6") or isPrefix(number, "37")
# getDigit(number)
# getPrefix(number, k)
if (len(number) >= 13 and len(number) <=16) and (result%10 == 0) and prefix == True:
cardIsValid = True
return cardIsValid
def sumDoubleEvenLocation(number):
temp = []
count = 0
count1 = 0
for i in number[::2]:
temp.append(i)
temp = [int(a) for a in temp]
while count < len(temp):
temp[count] = temp[count]*2
count += 1
temp = [str(a) for a in temp]
while count1 < len(temp):
if len(temp[count1]) == 2:
temp[count1] = sum([int(x) for x in temp[count1]])
count1 += 1
return sum([int(x) for x in temp])
# def getDigit(number):
def sumOddLocation(number):
addition = 0
for i in number[::-2]:
addition += int(i)
return addition
def isPrefix(number, d):
prefix = False
if getSize(d) == 1 and (number[0] == "4" or number[0] == "5" or number[0] == "6"):
prefix = True
elif getSize(d) == 2 and (number[0] == "3" and number[1] =="7"):
prefix = True
return prefix
def getSize(d):
return len(str(d))
def getPrefix(number, k):
newNumber = ""
i = 0
if len(number) < k:
newNumber = number
else:
while i < k:
newNumber += (number[i])
i += 1
return newNumber
print(isValid(cardNumber)) |
name = input("Enter your name: ")
print("Hello " + name + "!")
age = input("How old are you?: ")
print("Therefore, " + name + " is " + age + " years old!")
num1 = input("Type in a number: ")
num2 = input("Type in another number: ")
result = float(num1) + float(num2)
print(result) |
from abc import ABCMeta, abstractmethod
# Definition of mothods to build complex objects
class JourneyBuilder(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def transportType(transport):
"Transport type"
@staticmethod
@abstractmethod
def originLocation(origin):
"Origin location"
@staticmethod
@abstractmethod
def destinyLocation(destiny):
"Destiny location"
@staticmethod
@abstractmethod
def arrival(arrival):
"Arrival time"
@staticmethod
@abstractmethod
def getInformation():
"Return the whole journey information"
|
import os
import matplotlib.pyplot as plt
from Perceptron import perceptron
from LogisticRegression import logistic_regression
from DataReader import *
data_dir = "../data/"
train_filename = "train.txt"
test_filename = "test.txt"
img_index = 0
def visualize_features(X, y):
'''This function is used to plot a 2-D scatter plot of training features.
Args:
X: An array of shape [n_samples, 2].
y: An array of shape [n_samples,]. Only contains 1 or -1.
Returns:
No return. Save the plot to 'train_features.*' and include it
in submission.
'''
### YOUR CODE HERE
global img_index
ones = []
fives = []
for i in range(y.shape[0]):
if y[i]==1:
ones.append(X[i])
else:
fives.append(X[i])
ones = np.array(ones)
fives = np.array(fives)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.scatter(fives[:,0], fives[:,1], c='b', label='Features of digit 5')
plt.scatter(ones[:,0], ones[:,1], c='y', label='Features of digit 1')
plt.legend()
plt.savefig('train_features_img' + str(img_index) + '.png')
plt.gcf().clear()
img_index += 1
### END YOUR CODE
def visualize_result(X, y, W):
'''This function is used to plot the linear model after training.
Args:
X: An array of shape [n_samples, 2].
y: An array of shape [n_samples,]. Only contains 1 or -1.
W: An array of shape [n_samples,].
Returns:
No return. Save the plot to 'train_result.*' and include it
in submission.
'''
### YOUR CODE HERE
global img_index
slope = -(W[0]/W[2])/(W[0]/W[1])
intercept = -W[0]/W[2]
boundary = []
x_vals = np.linspace(-1,0.2,num=2)
for i in x_vals:
boundary.append((slope*i) + intercept)
plt.plot(x_vals, boundary, c='r', label='Decision Boundary')
ones = []
fives = []
for i in range(y.shape[0]):
if y[i]==1:
ones.append(X[i])
else:
fives.append(X[i])
ones = np.array(ones)
fives = np.array(fives)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.scatter(fives[:,0], fives[:,1], c='b', label='Features of digit 5')
plt.scatter(ones[:,0], ones[:,1], c='y', label='Features of digit 1')
plt.legend()
plt.savefig('test_features_img' + str(img_index) + '.png')
plt.gcf().clear()
img_index += 1
### END YOUR CODE
def main():
# ------------Data Preprocessing------------
# Read data for training.
global img_index
raw_data = load_data(os.path.join(data_dir, train_filename))
raw_train, raw_valid = train_valid_split(raw_data, 1000)
train_X, train_y = prepare_data(raw_train)
valid_X, valid_y = prepare_data(raw_valid)
# Visualize training data.
visualize_features(train_X[:, 1:3], train_y)
# ------------Perceptron------------
perceptron_models = []
min_validation_error = 1000
best_perceptron = None
for max_iter in [10, 20, 50, 100, 200]:
# Initialize the model.
perceptron_classifier = perceptron(max_iter=max_iter)
perceptron_models.append(perceptron_classifier)
# Train the model.
perceptron_classifier.fit(train_X, train_y)
print('Max interation:', max_iter)
print('Weights after training:',perceptron_classifier.get_params())
print('Training accuracy(in %):', perceptron_classifier.score(train_X, train_y))
print('Validation accuracy(in %):', perceptron_classifier.score(valid_X, valid_y))
print()
if (min_validation_error > perceptron_classifier.score(valid_X, valid_y)):
min_validation_error = perceptron_classifier.score(valid_X, valid_y)
best_perceptron = perceptron_classifier
# Visualize the the 'best' one of the five models above after training.
### YOUR CODE HERE
visualize_result(train_X[:,1:3], train_y, best_perceptron.get_params())
### END YOUR CODE
# Use the 'best' model above to do testing.
### YOUR CODE HERE
raw_test_data = load_data(os.path.join(data_dir, test_filename))
test_X, test_y = prepare_data(raw_test_data)
print('Testing accuracy(in %):', perceptron_classifier.score(test_X, test_y))
print()
# ### END YOUR CODE
# ------------Logistic Regression------------
# Check GD, SGD, BGD
logisticR_classifier = logistic_regression(learning_rate=0.5, max_iter=100)
logisticR_classifier.fit_GD(train_X, train_y)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
print()
plt.plot(logisticR_classifier.errors)
plt.show()
logisticR_classifier.fit_BGD(train_X, train_y, 1000)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
print()
plt.plot(logisticR_classifier.errors)
plt.show()
logisticR_classifier.fit_SGD(train_X, train_y)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
print()
plt.plot(logisticR_classifier.errors)
plt.show()
logisticR_classifier.fit_BGD(train_X, train_y, 1)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
print()
plt.plot(logisticR_classifier.errors)
plt.show()
logisticR_classifier.fit_BGD(train_X, train_y, 10)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
print()
plt.plot(logisticR_classifier.errors)
plt.show()
# Explore different hyper-parameters.
## YOUR CODE HERE
print('Tuning hyper-parameters...')
errors = []
for learning_rate in np.linspace(0,10,num=100):
logisticR_classifier = logistic_regression(learning_rate, max_iter=100)
logisticR_classifier.fit_BGD(train_X, train_y, 10)
accuracy = logisticR_classifier.score(valid_X, valid_y)
errors.append(100-accuracy)
plt.xlabel('Learning Rate')
plt.ylabel('Error')
plt.plot(errors)
plt.savefig('variation_learning_rate_img' + str(img_index) + '.png')
plt.gcf().clear()
img_index += 1
errors = []
for iter in range(0,1000,100):
logisticR_classifier = logistic_regression(learning_rate=0.5, max_iter=iter)
logisticR_classifier.fit_BGD(train_X, train_y, 10)
accuracy = logisticR_classifier.score(valid_X, valid_y)
errors.append(100-accuracy)
plt.plot(range(0,1000,100), errors)
plt.xlabel('Iterations')
plt.ylabel('Error')
plt.savefig('variation_max_iters_img' + str(img_index) + '.png')
plt.gcf().clear()
img_index += 1
best_logisticR = logistic_regression(learning_rate=10, max_iter=220)
best_logisticR.fit_GD(train_X, train_y)
## END YOUR CODE
# Visualize the your 'best' model after training.
## YOUR CODE HERE
visualize_result(train_X[:, 1:3], train_y, best_logisticR.get_params())
## END YOUR CODE
# Use the 'best' model above to do testing.
## YOUR CODE HERE
raw_test_data = load_data(os.path.join(data_dir, test_filename))
test_X, test_y = prepare_data(raw_test_data)
print('Testing accuracy(in %):', best_logisticR.score(test_X, test_y))
print()
## END YOUR CODE
if __name__ == '__main__':
main() |
number = int(input("Введите число: "))
result = int(number) + int(str(number) + str(number)) + int(str(number) + str(number) + str(number))
print(result)
|
def add(n):
n += 1
return n
def main():
n = 1
print(n)
n = add(n)
print(n)
if __name__ == '__main__':
main() |
import Mahjong
from Mahjong import Tile
class Player:
MAX_HAND_SIZE = 13
''' defines a new player'''
def __init__(self, name: str, turn: int):
self.name = id
''' player's tiles'''
''' open is a tuple (triplet as a list, position to be tilted)'''
self.open = []
''' closed is just a list of tiles in hand'''
self.closed = []
''' discards is just a list of tiles discarded'''
self.discards = []
self.next_tile = None
''' player's points'''
self.points = 250
'''turn is the player's turn position (which position the player is for Ton)'''
self.turn = turn
''' richi is the turn the player called richi, only based off the players turns, not off the
rounds turns. Turn 0 is first discard!!!'''
self.richi = -1
''' adds the start tiles when starting a game'''
def deal(self, tiles: [Tile]):
self.closed.extend(tiles)
''' draws a single tile'''
def draw_tile(self, tile: Tile):
self.next_tile = tile
'''discards the n tile in the open hand'''
def discard_tile(self, n: int):
'''safety net'''
if n < 0 and n >= len(self.closed):
return
self.discards.append(self.closed[n])
del self.closed[n]
''' discards the next tile'''
def pass_tile(self):
self.discards.append(self.next_tile)
self.next_tile = None
''' inserts the next tile into the hand'''
''' insertion sort since no need to resort everything'''
def insert_tile(self):
for i in range(len(self.closed)):
if self.next_tile > self.closed[i]:
continue
self.closed.insert(i, self.next_tile)
self.next_tile = None
return
'''special case if the tile belongs at the end of the list i.e, bigger than everything else'''
self.closed.append(self.next_tile)
self.next_tile = None
''' resets the hand for next game'''
def clear_hand(self):
self.closed = []
self.open = []
self.discards = []
self.next_tile = None
''' makes a richi call if conditions are met'''
def call_richi(self):
if len(self.open) == 0 and self.next_tile != None:
self.richi = len(self.discards)
''' allow cancelling of richi if its the turn we called it'''
def cancel_richi(self):
if len(self.discards) <= self.richi:
self.richi = -1
'''COMPLICATED STUFF BELOW'''
''' returns whether or not a tile t can be combined into a triple'''
def can_pon(self, t: Tile) -> bool:
return (sum(item == t for item in self.closed) >= 2)
'''calls a triple on a tile t'''
''' position is the position of the tile to be tilted, zero based indexing'''
def pon(self, t: Tile, p: int):
'''delete 2 copies of the tile from the hand'''
self.delete_tile(t)
self.delete_tile(t)
self.open.append(([t.copy(), t.copy(), t.copy()], p))
''' can make an open quad'''
def can_open_kan(self, t: Tile):
return (sum(item == t for item in self.closed) >= 3)
''' make an open quad'''
def open_kan(self, t: Tile, p: int):
'''delete 3 copies of the tile from the hand'''
self.delete_tile(t)
self.delete_tile(t)
self.delete_tile(t)
self.open.append(([t.copy(), t.copy(), t.copy(), t.copy()], p))
''' can make a closed quad from hand'''
def can_closed_kan(self):
''' if we have 4 of a kind in the closed hand'''
for i in range(len(self.closed)-3):
if ((self.closed[i] == self.closed[i+1]) and (self.closed[i] == self.closed[i+2]) and
(self.closed[i] == self.closed[i+3])):
return True
'''if we have a triple and we draw the fourth'''
if (sum(item == self.next_tile for item in self.closed) == 3):
return True
return False
''' make a closed kan from hand with tile starting from position p'''
def closed_kan(self, p: int):
'''handle index out of bounds error easily with a try except block'''
''' case where we draw the fourth tile and have 3 in hand'''
try:
if sum(item == self.next_tile for item in self.closed) == 3:
if ((self.closed[p] == self.next_tile) and (self.closed[p+1] == self.next_tile) and
(self.closed[p+2] == self.next_tile)):
'''add a set of 4 to our open hand'''
self.open.append(([self.next_tile.copy(), self.next_tile.copy(), self.next_tile.copy(),
self.next_tile.copy()], 3))
'''delete 3 copies of tile from our hand'''
for i in range(3):
self.delete_tile(self.next_tile)
'''delete the next tile'''
self.next_tile = None
except IndexError:
pass
'''handle index out of bounds errors easily with a try except block'''
''' case where we have 4 in a row in hand'''
try:
''' if there are 4 copies of the selected tile'''
if ((self.closed[p] == self.closed[p+1]) and (self.closed[p] == self.closed[p+2]) and
(self.closed[p] == self.closed[p+3])):
''' add 4 copies to open hand'''
self.open.append(([self.closed[p].copy(), self.closed[p].copy(), self.closed[p].copy(),
self.closed[p].copy()], 3))
''' delete 4 copies of the tile'''
for i in range(4):
self.delete_tile(self.closed[p])
except IndexError:
return
'''returns whether or not a tile can be added to a triple to become a quad'''
def can_added_kan(self):
''' check every triplet in open hand'''
for tup in self.open:
''' if the triplet is a pon'''
if ((tup[0][0] == tup[0][1]) and (tup[0][0] == tup[0][2])):
'''if the triplet tile is in our closed hand or our next tile'''
if ((tup[0][0] == self.next_tile) or (tup[0][0] in self.closed)):
return True
return False
'''make an added kan'''
''' P HERE IS THE POSITION OF THE TRIPLET IN THE OPEN HAND'''
def added_kan(self, p: int):
''' if the triplet is a pon'''
if (self.open[p][0][0] == self.open[p][0][1] and len(self.open[p][0])<4):
'''if the next tile is the same as the triple'''
if self.open[p][0][0] == self.next_tile:
'''add next tile to the triplet and get rid of our next tile'''
self.open[p][0].append(self.next_tile)
self.next_tile = None
''' if the the last tile is in our hand'''
if self.open[p][0][0] in self.closed:
self.open[p][0].append(self.open[p][0][0])
'''delete tile from closed hand'''
del self.closed[self.closed.index(self.open[p][0][0])]
''' returns whether or not a tile can be eaten'''
def can_chi(self, t: Tile) -> bool:
if t.num == 0:
return False
if Tile(t.num-2, t.suit) in self.closed and Tile(t.num-1, t.suit) in self.closed:
return True
if Tile(t.num-1, t.suit) in self.closed and Tile(t.num+1, t.suit) in self.closed:
return True
if Tile(t.num+1, t.suit) in self.closed and Tile(t.num+2, t.suit) in self.closed:
return True
return False
''' eats a consecutive triple'''
''' position p is where the consecutive starts for the chi'''
''' always position 0 to be tilted'''
def chi(self, t: Tile, p: int):
if self.closed[p].suit != t.suit:
return
''' if our case is 1,2 eat 3'''
if self.closed[p].num == t.num-2 and Tile(t.num-1, t.suit) in self.closed:
self.open.append(([t, self.closed[p], Tile(t.num-1, t.suit)], 0))
del self.closed[p]
self.delete_tile(Tile(t.num-1, t.suit))
'''if our case is 2,4 eat 3'''
if self.closed[p].num == t.num-1 and Tile(t.num+1, t.suit) in self.closed:
self.open.append(([t, self.closed[p], Tile(t.num+1, t.suit)], 0))
del self.closed[p]
self.delete_tile(Tile(t.num+1, t.suit))
''' if our case is 4, 5 eat 3'''
if self.closed[p].num == t.num+1 and Tile(t.num+2, t.suit) in self.closed:
self.open.append(([t, self.closed[p], Tile(t.num+2, t.suit)], 0))
del self.closed[p]
self.delete_tile(Tile(t.num+2, t.suit))
''' deletes a tile t from closed hand'''
''' used for the different calls'''
def delete_tile(self, t: Tile):
for i in range(len(self.closed)):
if self.closed[i] == t:
del self.closed[i]
return
''' sorts the closed hand'''
def sort(self):
''' make our buckets and add our tiles into the buckets'''
buckets = []
for i in range(len(Tile.SUITS)):
buckets.append([])
for t in self.closed:
buckets[t.get_placement()].append(t)
'''clear our hand'''
self.closed = []
''' sort within each bucket and add back into hand'''
for b in buckets:
b.sort(key = lambda x: x.num)
self.closed.extend(b)
if __name__ == '__main__':
mg = Mahjong.Mahjong(1)
round = mg.Round(0)
round.start()
p = Player('A', 0)
for i in range(3):
p.deal(round.deal(4))
print(len(p.closed))
p.sort()
for i in p.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
print('')
p.draw_tile(round.draw())
print('draw is: ' + p.next_tile.to_string().replace('\n', ' '), end = ' ')
p.insert_tile()
print('')
for i in p.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
print('')
print('discarding the 5th tile...')
p.discard_tile(5)
for i in p.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
print('')
print('\n')
print('pon tests')
p2 = Player('B', 1)
p2.closed = [Tile(0, 'TON'), Tile(0, 'TON')]
print('P2 can pon:', Tile(0, 'TON') in p2.closed)
p2.pon(Tile(0, 'TON'), 1)
print('P2 closed hand:')
for i in p2.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
print('P2 open hand:')
for i in p2.open:
print(i)
print('\n')
print('chi tests')
p3 = Player('C', 2)
p3.closed = [Tile(1, 'Man'), Tile(2, 'Man'), Tile(3, 'Man'), Tile(7, 'Man'), Tile(8, 'Man'),
Tile(9, 'Man'), Tile(0, 'TON'), Tile(0, 'TON'), Tile(0, 'TON')]
print('P3 can chi 1 man:', p3.can_chi(Tile(1, 'Man')))
print('P3 can chi 2 man:', p3.can_chi(Tile(2, 'Man')))
print('P3 can chi 3 man:', p3.can_chi(Tile(3, 'Man')))
print('P3 can chi 4 man:', p3.can_chi(Tile(4, 'Man')))
print('P3 can chi 5 man:', p3.can_chi(Tile(5, 'Man')))
print('P3 can chi 6 man:', p3.can_chi(Tile(6, 'Man')))
print('P3 can chi 7 man:', p3.can_chi(Tile(7, 'Man')))
print('P3 can chi 8 man:', p3.can_chi(Tile(8, 'Man')))
print('P3 can chi 9 man:', p3.can_chi(Tile(9, 'Man')))
print('P3 can chi TON:', p3.can_chi(Tile(0, 'TON')))
#p3.chi(Tile(2, 'Man'), 0)
for i in p3.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
print('\n')
print('kan tests:')
p3.next_tile = Tile(0, 'TON')
print('P3 can open kan 1 man:', p3.can_open_kan(Tile(1, 'Man')))
print('P3 can open kan 9 man:', p3.can_open_kan(Tile(9, 'Man')))
print('P3 can open kan TON:', p3.can_open_kan(Tile(0, 'TON')))
print('P3 can closed kan TON:', p3.can_closed_kan())
p3.closed_kan(0)
print('P3.closed =')
for i in p3.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
print()
p3.closed_kan(9)
print('P3.closed =')
for i in p3.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
print()
p3.closed_kan(6)
print('P3.closed =')
for i in p3.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
print()
print('P3.open =')
for t in p3.open:
for i in t[0]:
print(i.to_string().replace('\n', ' '), end = ' ')
print('\n')
print('added kan tests:')
p4 = Player('D', 3)
p4.closed = [Tile(1, 'Man'), Tile(2, 'Man'), Tile(3, 'Man'), Tile(7, 'Man'), Tile(8, 'Man'),
Tile(9, 'Man')]
p4.next_tile = Tile(0, 'TON')
p4.open = [([Tile(1, 'Man'), Tile(1, 'Man'), Tile(1, 'Man')], 2),
([Tile(0, 'TON'), Tile(0, 'TON'), Tile(0, 'TON')], 1),
([Tile(2, 'Man'), Tile(3, 'Man'), Tile(4, 'Man')], 0)]
print('P4.closed =')
for i in p4.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
print()
print('P4 can added kan:', p4.can_added_kan())
p4.added_kan(0)
print('P4.open =')
for t in p4.open:
for i in t[0]:
print(i.to_string().replace('\n', ' '), end = ' ')
p4.added_kan(1)
print()
print('P4.open =')
for t in p4.open:
for i in t[0]:
print(i.to_string().replace('\n', ' '), end = ' ')
p4.added_kan(2)
print()
print('P4.open =')
for t in p4.open:
for i in t[0]:
print(i.to_string().replace('\n', ' '), end = ' ')
print()
print('P4.closed =')
for i in p4.closed:
print(i.to_string().replace('\n', ' '), end = ' ')
|
# 7-7. Infinity: Write a loop that never ends, and run it (To end the loop, press
# ctrl-C or close the window displaying the output )
count = 1
while count <= 5:
print(count) |
# 8-6. City Names: Write a function called city_country() that takes in the name
# of a city and its country The function should return a string formatted like this:
# "Santiago, Chile"
# Call your function with at least three city-country pairs, and print the value
# that’s returned
def describe_city(city, country):
a = print('"{}", "{}"'.format(city,country))
return a
city_name = input("enter the name of city.. \n")
country_name = input("enter the name of Country.. \n")
print("\n")
describe_city(city_name,country_name) |
# Create a new list from a two list using the following condition
# Given a two list of numbers, write a program to create a new list such that the new list should contain odd numbers from the first list and even numbers from the second list.
# Given:
# list1 = [10, 20, 25, 30, 35]
# list2 = [40, 45, 60, 75, 90]
# Expected Output:
# result list: [25, 35, 40, 60, 90]
def mergelist(lista,listb):
returnlist = []
for num in lista:
if( num % 2 != 0):
print(num)
returnlist.append(num)
for num in listb:
if( num % 2 == 0):
print(num)
returnlist.append(num)
return returnlist
list1 = [10, 20, 25, 30, 35]
list2 = [40, 45, 60, 75, 90]
mergelist(list1,list2)
|
# 7-6. Three Exits: Write different versions of either Exercise 7-4 or Exercise 7-5
# that do each of the following at least once:
# • Use a conditional test in the while statement to stop the loop
# • Use an active variable to control how long the loop runs
# • Use a break statement to exit the loop when the user enters a 'quit' value
loop_flag = True
pizza = []
while loop_flag:
pizza_topping = input("Enter pizza topping : \n")
if pizza_topping == "quit":
print("Code has stopped working....")
break
else:
print("Continue adding toppings... \n")
pizza.append(pizza_topping)
print("\n")
for ingredients in pizza:
print(ingredients,end=" ") |
# 7-5. Movie Tickets: A movie theater charges different ticket prices depending on
# a person’s age If a person is under the age of 3, the ticket is free; if they are
# between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is
# $15 Write a loop in which you ask users their age, and then tell them the cost
# of their movie ticket
loop_flag = True
while loop_flag:
input_age = int(input("Enter the age : \n"))
if 0 <= input_age < 3:
print("go home")
elif 3 <= input_age <= 12:
print("Ticket value is $10")
break
else:
print("Ticket Value is $15")
break
|
# from requests.api import options
# import streamlit as st
# import pandas as pd
# import numpy as np
# import requests
# # Draw a title and some text to the app:
# '''
# # Data Product Manager - Decision Dashboard
# Below results are for .
# '''
# ticker_option = add_tickerbox = st.sidebar.selectbox(
# "Select your Ticker?",
# ("BTCUSDT", "ETHUSDT", "DOTUSDT", "SOLUSDT",'UBER')
# )
# st.header(ticker_option)
# # add_chartbox = st.sidebar.selectbox(
# # "Select the chart?",
# # ("CandleStick", "ATR", "Goldencross")
# # )
# sentiment_option = add_sentimenttracker = st.sidebar.selectbox(
# "Select the sentiment tracker?",
# ("wallstreetbets", "tweepy", "stocktwits")
# )
# # st.header(sentiment_option)
# with st.beta_container():
# st.write("CandleStick chart with options to select")
# # You can call any Streamlit command, including custom components:
# st.bar_chart(np.random.randn(50, 3))
# # st.write("This is outside the container")
# df = pd.DataFrame(
# np.random.randn(10, 20),
# columns=('col %d' % i for i in range(20)))
# st.dataframe(df.style.highlight_max(axis=0))
# if sentiment_option == "stocktwits":
# st.subheader("Results from Stockwits")
# symbol = st.sidebar.text_input("Symbol", value='UBER', max_chars=8)
# pass
# r = requests.get(f"https://api.stocktwits.com/api/2/streams/symbol/{symbol}.json")
# data = r.json()
# for message in data['messages']:
# st.image(message['user']['avatar_url'])
# st.write(message['user']['username'])
# st.write(message['created_at'])
# st.write(message['body'])
# if sentiment_option == "wallstreetbets":
# st.subheader("Results from Wallstreetbets")
|
import time
import argparse
from OuriIA import *
from OuriBoard import *
#players
MINIMAX = "Minimax"
ALPHABETA = "Alphabeta"
PLAYER = "Player"
#levels of analysis and correspondent search depth
MINIMAX_5 = 7
MINIMAX_15 = 9
MINIMAX_30 = 10
ALPHABETA_5 = 11
ALPHABETA_15 = 13
ALPHABETA_30 = 15
def match_level(algorithm, level):
if algorithm == MINIMAX:
if level == 1:
return MINIMAX_5
elif level == 2:
return MINIMAX_15
else:
return MINIMAX_30
else:
if level == 1:
return ALPHABETA_5
elif level == 2:
return ALPHABETA_15
else:
return ALPHABETA_30
def switch_turns(board):
board.player_turn = board.get_opponent(board.player_turn)
def menu(t):
print("\n WELCOME TO OURI GAME\n\n")
print("Choose a GAME MODE:")
print(" 1- player vs ia")
print(" 2- ia vs ia")
mode = input("Option:")
if mode == str(1):
print("\nChoose the ALGORITHM you want to play against:")
print(" 1- Minimax")
print(" 2- Alphabeta")
algo = input("Option:")
if algo == str(1):
algo = MINIMAX
else:
algo = ALPHABETA
print("\nChoose the LEVEL OF ANALYSIS of the algorithm:")
print(" 1- 5 seconds")
print(" 2- 15 seconds")
print(" 3- 30 seconds")
level = input("Option:")
if mode == str(1):
player_vs_ia(t, algo, int(level))
else:
ia_vs_ia(t, int(level))
def ia_vs_ia(t, level):
if t == 1:
board = Board(MINIMAX, ALPHABETA, MINIMAX)
else:
board = Board(MINIMAX, ALPHABETA, ALPHABETA)
ia = IA(match_level(MINIMAX, level)) #minimax
ia2 = IA(match_level(ALPHABETA, level)) #alphabeta
while True:
board.display_board()
if board.game_over():
print("\n-------------------------------END-------------------------------")
board.display_board()
print(board.winner)
break
if board.player_turn == MINIMAX:
print("Minimax turn")
start_time = time.time()
move = ia.minimax(board, ia.depth, MINIMAX)
print("--- %s seconds ---" % round(time.time() - start_time))
if move != -1:
print("Best move: ", 6-move, "\n")
board.make_move(move)
if not board.opponent_empty():
switch_turns(board)
else:
print("Alphabeta turn")
start_time = time.time()
move = ia2.alphaBeta(board, ia2.depth, ALPHABETA)
print("--- %s seconds ---" % round(time.time() - start_time))
if move != -1:
print("Best move: ", 6-move, "\n")
board.make_move(move)
if not board.opponent_empty():
switch_turns(board)
def player_vs_ia(t, algo, level):
if t == 1:
board = Board(algo, PLAYER, algo)
else:
board = Board(algo, PLAYER, PLAYER)
ia = IA(match_level(algo, level)) #minimax or alphabeta
while True:
board.display_board()
if board.game_over():
print("\n-------------------------------END-------------------------------")
board.display_board()
print(board.winner)
break
if board.player_turn == PLAYER:
moves = board.possible_moves()
if moves:
pit = input("->Player move: ")
while int(pit)-1 not in moves:
print("Invalid move!")
pit = input("->Player move:")
board.make_move(int(pit)-1)
if not board.opponent_empty():
switch_turns(board)
else:
print("Computer turn...")
start_time = time.time()
if board.player_turn == MINIMAX:
move = ia.minimax(board, ia.depth, MINIMAX)
if board.player_turn == ALPHABETA:
move = ia.alphaBeta(board, ia.depth, ALPHABETA)
print("--- %s seconds ---" % round(time.time() - start_time))
if move != -1:
print("Best move: ", 6-move, "\n")
board.make_move(move)
if not board.opponent_empty():
switch_turns(board)
if __name__=='__main__':
parser = argparse.ArgumentParser(description='Ouri')
parser.add_argument('-p', help="Computer plays first", action="store_true")
parser.add_argument('-s', help="Player plays first", action="store_false")
args = parser.parse_args()
#program starts first
if args.p == True:
menu(1)
else:
menu(2)
|
import numpy as np
from cs231n.layers import *
from cs231n.fast_layers import *
from cs231n.layer_utils import *
class ThreeLayerConvNet(object):
"""
A three-layer convolutional network with the following architecture:
conv - relu - 2x2 max pool - affine - relu - affine - softmax
The network operates on minibatches of data that have shape (N, C, H, W)
consisting of N images, each with height H and width W and with C input
channels.
"""
def __init__(self, inputDim = (3, 32, 32), numFilters = 32, filterSize = 7,
hiddenDim = 100, numClasses = 10, weightScale = 1e-3, reg = 0.0,
dtype = np.float32):
"""
Initialize a new network.
Inputs:
- input_dim: Tuple (C, H, W) giving size of input data
- num_filters: Number of filters to use in the convolutional layer
- filter_size: Size of filters to use in the convolutional layer
- hidden_dim: Number of units to use in the fully-connected hidden layer
- num_classes: Number of scores to produce from the final affine layer.
- weight_scale: Scalar giving standard deviation for random initialization
of weights.
- reg: Scalar giving L2 regularization strength
- dtype: numpy datatype to use for computation.
"""
self.params = {}
self.reg = reg
self.dtype = dtype
############################################################################
# TODO: Initialize weights and biases for the three-layer convolutional #
# network. Weights should be initialized from a Gaussian with standard #
# deviation equal to weight_scale; biases should be initialized to zero. #
# All weights and biases should be stored in the dictionary self.params. #
# Store weights and biases for the convolutional layer using the keys 'W1' #
# and 'b1'; use keys 'W2' and 'b2' for the weights and biases of the #
# hidden affine layer, and keys 'W3' and 'b3' for the weights and biases #
# of the output affine layer. #
############################################################################
## Initialising parameters.
self.params['W1'] = np.random.normal(loc = 0, scale = weightScale, size = (numFilters, inputDim[0], filterSize, filterSize))
self.params['b1'] = np.zeros(numFilters)
## Assuming the output of the convolutional layer is the same as the input and then reduced by a factor of 4 after applying 2*2 max pooling.
self.params['W2'] = np.random.normal(loc = 0, scale = weightScale, size = ((numFilters * inputDim[1] * inputDim[2]) / 4, hiddenDim))
self.params['b2'] = np.zeros(hiddenDim)
self.params['W3'] = np.random.normal(loc = 0, scale = weightScale, size = (hiddenDim, numClasses))
self.params['b3'] = np.zeros(numClasses)
############################################################################
# END OF YOUR CODE #
############################################################################
for k, v in self.params.iteritems():
self.params[k] = v.astype(dtype)
def loss(self, X, y = None):
"""
Evaluate loss and gradient for the three-layer convolutional network.
Input / output: Same API as TwoLayerNet in fc_net.py.
"""
W1, b1 = self.params['W1'], self.params['b1']
W2, b2 = self.params['W2'], self.params['b2']
W3, b3 = self.params['W3'], self.params['b3']
# pass conv_param to the forward pass for the convolutional layer
numFilters = W1.shape[0]
filterSize = W1.shape[2]
convParam = {'stride': 1, 'pad': (filterSize - 1) / 2}
# pass pool_param to the forward pass for the max-pooling layer
poolParam = {'poolHeight': 2, 'poolWidth': 2, 'stride': 2}
scores = None
############################################################################
# TODO: Implement the forward pass for the three-layer convolutional net, #
# computing the class scores for X and storing them in the scores #
# variable. #
############################################################################
## Applying the convolutional layer, followed by a reLu non-linearity which
## is then followed by a max-pooling layer.
maxPoolOut, maxPoolCache = conv_relu_pool_forward(X, W1, b1, convParam, poolParam)
## Reshaping the above output so that affine transformation (fully connected
## layers) can be used.
maxPoolOut = maxPoolOut.reshape(maxPoolOut.shape[0], maxPoolOut.shape[1] * maxPoolOut.shape[2] * maxPoolOut.shape[3])
## Applying the affine transformation.
reLuOut, reLuCache = affine_relu_forward(maxPoolOut, W2, b2)
## Applying the final affine transformation.
fcOut, fcCache = affine_forward(reLuOut, W3, b3)
scores = fcOut
############################################################################
# END OF YOUR CODE #
############################################################################
if y is None:
return scores
loss, grads = 0, {}
############################################################################
# TODO: Implement the backward pass for the three-layer convolutional net, #
# storing the loss and gradients in the loss and grads variables. Compute #
# data loss using softmax, and make sure that grads[k] holds the gradients #
# for self.params[k]. Don't forget to add L2 regularization! #
############################################################################
## Softmax Layer (Forward + Backward).
loss, dScores = softmax_loss(scores, y)
## Adding regularisation to the loss.
for j in range(0, 3):
loss += 0.5 * self.reg * np.sum(self.params['W' + str(j + 1)] * self.params['W' + str(j + 1)])
## Backproping through the last fully-connected layer.
dReluOut, grads['W3'], grads['b3'] = affine_backward(dScores, fcCache)
## Backproping through the hidden layer.
dMaxPoolOut, grads['W2'], grads['b2'] = affine_relu_backward(dReluOut, reLuCache)
## Reshaping the gradient matrix.
dMaxPoolOut = dMaxPoolOut.reshape(dMaxPoolOut.shape[0], numFilters, X.shape[2] / 2, X.shape[3] / 2)
## Backproping through the convolutional layer.
dX, grads['W1'], grads['b1'] = conv_relu_pool_backward(dMaxPoolOut, maxPoolCache)
############################################################################
# END OF YOUR CODE #
############################################################################
return loss, grads
pass
|
#Sign your name: DannyH
'''
1. Make the following program work.
'''
print("This program takes three numbers and returns the sum.")
Total = 0
for i in range(3):
NumberBeingAdded = float(input("Enter a number: "))
Total += NumberBeingAdded
print("The total is:",Total)
'''
2. Write a Python program that will use a FOR loop to print the even.
numbers from 2 to 100, inclusive.
'''
print('Watch in amazement as the odd numbers from 2-100 are printed.')
for i in range (2,101,2):
print(i)
'''
3. Write a program that will use a WHILE loop to count from
10 down to, and including, 0. Then print the words Blast off! Remember, use
a WHILE loop, don't use a FOR loop.
'''
NumbersLeft = 10
while NumbersLeft >= 0:
print(NumbersLeft)
NumbersLeft -= 1
print("Blastoff!")
'''
4. Write a program that prints a random integer from 1 to 10 (inclusive).
'''
import random
random=random.randint(1,10)
print("Your random number is:", random)
'''
5. Write a Python program that will:
* Ask the user for seven numbers
* Print the total sum of the numbers
* Print the count of the positive entries, the count of entries equal to zero,
and the count of negative entries. Use an if, elif, else chain, not just three
if statements.
'''
total = 0
PositiveCount = 0
NegetiveCount =0
ZeroCount = 0
print("You are going to enter seven numbers")
for i in range (7):
userinput=float(input("Number to enter."))
if userinput > 1:
PositiveCount += 1
elif userinput < 1:
NegetiveCount += 1
elif userinput == -0:
print("Why would you even enter -0?") #I just wanted to make an easter egg ok but Python dosn't understand when you type -0 :(
ZeroCount += 1
else:
ZeroCount +=1
total += userinput
print("The total of your numbers is:", total)
print("You had this many positive numbers:", PositiveCount)
print("You had this many negetive numbers:", NegetiveCount)
print("You had this many zeros:", ZeroCount) |
class Animal:
def __init__(self, species, age, name, gender, weight, life_expectancy):
self.species = species
self.age = age
self.name = name
self.gender = gender
self.weight = weight
self.is_alive = True
self.life_expectancy = life_expectancy
def grow(self, weight, days):
self.weight += weight
self.age += days
def eat(self, food):
self.weight += food
def dying(self):
if self.is_alive:
self.is_alive = False
def chance_of_dying(self):
return((self.age // 365) / self.life_expectancy)
|
def collatz(z):
if z == 1:
print("Three cheers to Collatz!")
elif z%2 == 0:
print(int(z/2))
collatz(int(z/2))
else:
print(3*z+1)
collatz(3*z+1)
def colWhile(z):
i = 0
while z != 1:
if z%2 == 0:
z = int(z/2)
else:
z = 3*z + 1
i += 1
return True, i
print(colWhile(5692874)) |
# Linear and Polynomial Regression
#
# This file is made by Faris D Qadri at 03.03.21
# Property of PCINU Germany e. V. @winter project 2020
# Github: https://github.com/NUJerman
# Source code: https://towardsdatascience.com/random-forest-in-python-24d0893d51c0
#
# In this file I will explain you how to use linear and polynomial regression
# I will be using Bike_Sharing_hourly.csv as the dataframe
#
# Contact person:
# Mail: abangfarisdq@gmail.com
# Linkedin: Faris Qadri
#
# Enjoy!!!
# NB: I only make the code more readable and easier to use. All credits goes to source
## Early visualisation at the data
# Pandas is used to see the data
import pandas as pd
# Data
print("==============================================================================\n")
print("Dataframe head:")
df = pd.read_csv("temperature.csv")
print(df.head())
# Statistical data insight
print("\ndf.describe result:")
print(df.describe())
print("==============================================================================\n")
# Use datetime for dealing with dates
import datetime
## making Timestamp readable
# Get years, months, and days
years = df["year"]
months = df["month"]
days = df["day"]
# List and then convert to datetime object
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year,
month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
## Visualization using matplotlib
# Import matplotlib for visualization
import matplotlib.pyplot as plt
# %matplotlib inline # Please input this command if you are using Jupiter
# Set the style
# Set up the plotting layout
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (10,10))
fig.autofmt_xdate(rotation = 45)
# Actual max temperature measurement
ax1.plot(dates, df["actual"])
ax1.set_xlabel(""); ax1.set_ylabel("Temperature"); ax1.set_title("Max Temp")
# Temperature from 1 day ago
ax2.plot(dates, df["temp_1"])
ax2.set_xlabel(""); ax2.set_ylabel("Temperature"); ax2.set_title("Previous Max Temp")
# Temperature from 2 days ago
ax3.plot(dates, df["temp_2"])
ax3.set_xlabel("Date"); ax3.set_ylabel("Temperature"); ax3.set_title("Two Days Prior Max Temp")
# Friend Estimate
ax4.plot(dates, df["friend"])
ax4.set_xlabel("Date"); ax4.set_ylabel("Temperature"); ax4.set_title("Friend Estimate")
## This is where the fun begins
# One-hot encode categorical data
df = pd.get_dummies(df)
df.head(5)
# Use numpy to convert to arrays
import numpy as np
# Labels are the values we want to predict
labels = np.array(df["actual"])
# Remove the labels from the df
# axis 1 refers to the columns
df = df.drop("actual", axis = 1)
# Saving feature names for later use
df_list = list(df.columns)
# Convert to numpy array
df = np.array(df)
# Using Skicit-learn to split data into training and testing sets
from sklearn.model_selection import train_test_split
# Split the data into training and testing sets
train_df, test_df, train_labels, test_labels = train_test_split(df, labels, test_size = 0.25,
random_state = 42)
# Shape and size
print("Training Features Shape:", train_df.shape)
print("Training Labels Shape:", train_labels.shape)
print("Testing Features Shape:", test_df.shape)
print("Testing Labels Shape:", test_labels.shape)
print("\n==============================================================================\n")
# The baseline predictions are the historical averages
baseline_preds = test_df[:, df_list.index("average")]
# Baseline errors, and display average baseline error
baseline_errors = abs(baseline_preds - test_labels)
print("Average baseline error: ", round(np.mean(baseline_errors), 2),
"degrees.")
print("\n==============================================================================\n")
## Train the model
# Import the model we are using
from sklearn.ensemble import RandomForestRegressor
# Instantiate model
rf = RandomForestRegressor(n_estimators= 1000, random_state=42)
# Train the model on training data
rf.fit(train_df, train_labels);
## Making predictions on test data
# Use the forest's predict method on the test data
predictions = rf.predict(test_df)
# Calculate the absolute errors
errors = abs(predictions - test_labels)
# Print out the mean absolute error (mae)
print("Mean Absolute Error:", round(np.mean(errors), 2), "degrees.")
print("\n==============================================================================\n")
## Calculating accuracy of the model
# Calculate mean absolute percentage error (MAPE)
mape = 100 * (errors / test_labels)
# Calculate and display accuracy
accuracy = 100 - np.mean(mape)
print("Model accuracy:", round(accuracy, 2), "%.")
print("\n==============================================================================\n")
# Get numerical feature importances
importances = list(rf.feature_importances_)
# List of tuples with variable and importance
df_importances = [(feature, round(importance, 2)) for feature, importance in zip(df_list, importances)]
# Sort the feature importances by most important first
df_importances = sorted(df_importances, key = lambda x: x[1], reverse = True)
# Print out the feature and importances
[print("Variable: {:20} Importance: {}".format(*pair)) for pair in df_importances];
print("\n==============================================================================\n")
## Predictions
# Dates of training values
months = df[:, df_list.index("month")]
days = df[:, df_list.index("day")]
years = df[:, df_list.index("year")]
# List and then convert to datetime object
dates = [str(int(year)) + "-" + str(int(month)) + "-" + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, "%Y-%m-%d") for date in dates]
# Dataframe with true values and dates
true_data = pd.DataFrame(data = {"date": dates, "actual": labels})
# Dates of predictions
months = test_df[:, df_list.index("month")]
days = test_df[:, df_list.index("day")]
years = test_df[:, df_list.index("year")]
# Column of dates
test_dates = [str(int(year)) + "-" + str(int(month)) + "-" + str(int(day)) for year, month, day in zip(years, months, days)]
# Convert to datetime objects
test_dates = [datetime.datetime.strptime(date, "%Y-%m-%d") for date in test_dates]
# Dataframe with predictions and dates
predictions_data = pd.DataFrame(data = {"date": test_dates, "prediction": predictions})
## Plotting actual values
# Plot the actual values
plt.plot(true_data["date"], true_data["actual"], "b-", label = "actual")
# Plot the predicted values
plt.plot(predictions_data["date"], predictions_data["prediction"], "ro", label = "prediction")
plt.xticks(rotation = "60");
plt.legend()
|
#!/usr/bin/python3
def weight_average(my_list=[]):
if len(my_list) == 0 or my_list is None:
return 0
dividendo = 0
divisor = 0
for i in range(len(my_list)):
dividendo += my_list[i][0] * my_list[i][1]
divisor += my_list[i][1]
return dividendo / divisor
|
class Shoe(object):
def __init__(self,brand,model,color,size):
self.brand = brand
self.model = model
self.color = color
self.size = size
self.tied = False
self.steps = 0
def tie(self):
self.tied = True
print "{} {}'s laces are now tied, phew!\n".format(self.brand,self.model)
def untie(self):
self.tied = False
print "{} {}'s laces have been untied! Watch your step!\n".format(self.model,self.brand)
def run(self):
if not self.tied:
print "{} {}'s must be tied in order to run!\n".format(self.model,self.brand)
return
self.steps += 1
print "{} {}'s are somehow running! {} steps have been taken so far!\n".format(self.brand,self.model,self.steps)
return self
def display(self):
print "Brand: {}\nModel:{}\nColor:{}\nSize:{}\nLaces Tied:{}\n".format(
self.brand,
self.model,
self.color,
self.size,
self.tied
)
# Nike = Shoe(
# "Nike",
# "Air",
# "White",
# 12
# )
# Nike.display()
# Jordan = Shoe(
# "Jordan",
# "Air",
# "Blue",
# 11
# )
# Jordan.run()
# Tims = Shoe(
# "Timberland",
# "Classic",
# "Brown",
# 10
# )
# Tims.tie()
# Tims.run().run().run()
###############################################################
class Dog(object):
def __init__(self,name,breed,sound):
self.name = name
self.breed = breed
self.sound = sound
def bark(self):
print "{} says {}".format(self.name,self.sound)
class Chihuahua(Dog):
def __init__(self,name,breed,sound):
super(Chihuahua,self).__init__(name,breed,sound);
def bark(self):
print self.name+" the "+self.breed+" says *"+self.sound.lower()+"*";
class Mastiff(Dog):
def __init__(self,name,breed,sound):
super(Mastiff,self).__init__(name,breed,sound);
def bark(self):
print self.name+" the "+self.breed+" says *"+self.sound.upper()+"*";
# chihuahua = Chihuahua(
# "Peanut",
# "Chihuahua",
# "RUFF"
# )
# chihuahua.bark()
# mastiff = Mastiff(
# "Macho",
# "Mastiff",
# "rawr"
# )
# mastiff.bark()
###############################################################
def myVarArgs(*args):
for i in args:
print i
# myVarArgs(20,30,40)
def myKwargs(**args):
for i in args:
if i == "firstName":
print "First Name: "+args[i]
elif i == "lastName":
print "Last Name: "+args[i]
elif i == "address":
print "Address: "+args[i]
myKwargs(
firstName="John",
lastName="Smith",
address="123 Dojo Ave."
) |
import random
class Coin:
def __init__(self):
self.__sideup = 'Heads'
def flip(self):
if random.randint(0,1) == 0:
self.__sideup = 'Heads'
else:
self.__sideup = 'Tails'
def get_sideup(self):
return self.__sideup
coin = Coin()
|
def apply_transformations(df, transformations):
"""
Apply transformations to pandas data frame
:param df: Pandas data frame on which to apply transformations
:type df: Pandas data frame
:param transformations: A dictionary of transformations.
Example: transformations={
"RENAME:Billingcycle": "BillingCycle",
"ID": 1234,
"AccountNumber": lambda row: row['AccountNumber'].strip(),
"CustomerName": lambda row: "{} {}".format(row["FirstName"].strip(), row["LastName"].strip()[:100]),
"Address": lambda row: ctds.SqlVarChar(row["Address"].encode("utf-16le")),
"FILTER:CheckEmpty": lambda row: row['AccountNumber'].strip() != ""}
:type transformations: dict
:return: A generator object that returns rows as a dictionary
"""
for column, transformation in transformations.items():
if ':' in column:
(operation, col) = column.split(':')
if operation == 'FILTER':
df = df[df.apply(transformation, axis=1)]
elif operation == 'RENAME':
df.rename(columns={col: transformation}, inplace=True)
elif callable(transformation):
df[column] = df.apply(transformation, axis=1, result_type='reduce')
else:
df[column] = transformation
for record in df.to_dict('records'):
yield record
|
print("整数値を3つ入力してください")
x = int(input("1つ目の値:"))
y = int(input("2つ目の値:"))
z = int(input("3つ目の値:"))
if x==y==z:
print("同じ値です")
else:
print("最大の値は{}です。".format(max([x,y,z]))) |
print("0~100 までの 得点(整数値) を2 つ入力してください")
x = int(input("1つ目の得点:"))
y = int(input("2つ目の得点:"))
if x>=60 and y >=60:
print("合格です")
else:
print("不合格です") |
print("文字を2つ入力してください。")
x = str(input("1つの文字"))
y = str(input("2つの文字"))
if x==y:
print("同じ文字です")
else:
print("異なる文字です") |
import math
# # Create a function called calc_dollars. In the function body, define a dictionary
# # and store it in a variable named piggyBank. The dictionary should have the
# # following keys defined. quarters,dimes, nickels, and pennies
# # For each coin type, give yourself as many as you like.
def calc_dollars():
piggyBank = {
"quarters": 77,
"dimes": 107,
"nickels": 71,
"pennies": 7
}
# Once you have given yourself a large stash of coins in your piggybank,
# look at each key and perform the appropriate math on the integer value
# to determine how much money you have in dollars. Store that value in a
# variable named dollarAmount and print it.
dollarAmount = {
} |
from urllib2 import urlopen
import json
import numpy as np#kind of array for fast manipulation
def crimeWeight(lati, longi, hr):#latitude longitude hour
#basically this function will return crime weight at the given latitude in 200 meter radius.
url = "https://data.phila.gov/resource/sspu-uyfa.json?$$app_token=bF12rIkELtbJ8PXnuzuZTWmVF"
radius = "200"
locationUrl = url + ("&$where=within_circle(shape,%s,%s,%s)" % (lati, longi, radius))
#To select points from a database within a certain distance from a given latitude/longitude point, within a selection circle,
response = urlopen(locationUrl)#opens url , The return value from urlopen() gives access to the headers from the HTTP server through the info() method,
#and the data for the remote resource via methods like read() and readlines().
data = json.loads(response.read().decode('utf-8'))#UTF-8 most commonly used encodings, UTF stands for “Unicode Transformation Format”, and the '8' means that 8-bit
Crime_type_100 = 0
Crime_type_200 = 0
Crime_type_300 = 0
Crime_type_400 = 0
Crime_type_500 = 0
Crime_type_600 = 0
Crime_type_other = 0
rdata = []#will store hours(time)
labels = []#kind of crime
for d in data:
u = d.get("ucr_general")#int in the form of string ,representing crime rate
if u != "":
u = int(u)
u = u - (u % 100)
if not (u == 700 or u == 1000 or u == 1100 or u == 1200 or u == 1300 or u ==1500 or (u > 1500 and u <= 2400) or u == 2600):
if(hr==int(d.get('hour_')))
if u == 100:
Crime_type_100 += 1
elif u == 200:
Crime_type_200 += 1
elif u == 300:
Crime_type_300 += 1
elif u == 400:
Crime_type_400 += 1
elif u == 500:
Crime_type_500 += 1
elif u == 600:
Crime_type_600 += 1
else:
Crime_type_other += 1
#print "CrimeType-homicides = " + str(Crime_type_100)
#print "CrimeType-rapes = " + str(Crime_type_200)
#print "CrimeType-robberies = " + str(Crime_type_300)
#print "CrimeType-assaults = " + str(Crime_type_400)
#print "CrimeType-burglaries = " + str(Crime_type_500)
#print "CrimeType-thefts = " + str(Crime_type_600)
#print "CrimeType-crimes = " + str(Crime_type_other)
crimeWt = (Crime_type_100*7 + Crime_type_200*6 + Crime_type_300*5 + Crime_type_400*4 + Crime_type_500*3 + Crime_type_600*2 + Crime_type_other*1)
return crimeWt;
|
"""
Draw a circle out of squares
"""
import turtle
frank = turtle.Turtle()
def square(t):
for i in range(4):
t.fd(100) # move forward 100 units
t.rt(90)
t.speed(10) # turn right 90 degrees
def draw_art():
# Instantiate a Screen object, window. Then customize window.
window = turtle.Screen()
window.bgcolor("white")
frank = turtle.Turtle()
# frank.shape("turtle") # see Turtle doc
# frank.color("yellow") # see Turtle doc
# Draw a circle with 36 squares. We rotate each square by 10 degrees at a time.
for i in range(36):
square(frank)
t.right(10)
window.exitonclick()
square(frank)
window = turtle.Screen()
window.bgcolor("white")
window.exitonclick()
|
# Python 2.7
# 6
# More Passing Arguments
# The definition for a function can have several parameters,
# because of this, a function call may need several arguments.
# There are several ways to pass arguments to your functions...
# Positional Arguments
# need to be in the same order the parameters were written
# Keyword Arguments
# where each argument consists of a variable name and a value;
# and lists and dictionaries of values
# KEYWORD ARGUMENTS
# a name-value pair that you pass to a function. You directly associate the name
# and the value within the argument, so when you pass to the function,
# there is no confusion. Keyword arguments allow free you from having to worry
# about the correct order of your arguments in the function call.
# Consider the function from our previous example, showing info about macroinvertebrates(or bugs)
def describe_bug(bug_type, bug_name):
"""Display information about a macroinvertebrate"""
print("\nI collected a " + bug_type + ".")
print("This " + bug_type + "'s order is " + bug_name.title() + ".")
describe_bug(bug_type= 'dragonfly larvae', bug_name= 'anisoptera')
# The function describe_bug() has not changed.
# When we call the function, we clearly state which parameter each argument
# should be matched with. When Python reads the function call, it knows to store
# the argument 'dragonfly larvae' in the parameter bug_type and the argument 'anisoptera'
# in bug_name. The output correctly displays that we have a dragonfly larvae
# of the order 'anisoptera'.
# Unlike positional arguments,the order of keyword arguments is no matter,
# because Python knows where each value should go.
|
"""
A simple interactive calculator program
Operators handled: addition (+), subtraction (-), multiplication (*), division (/)
"""
# initial user input/variables
number1 = raw_input("Give me a number: ")
number2 = raw_input("Give me another number: ")
# uncomment below to convert string input to integers (to make calculation of numbers work)
## number1 = int(raw_input("Give me a number: "))
## number2 = int(raw_input("Give me another number: "))
operation = raw_input("Which operation do you want me to perform? ")
# explain conditions and blocks of code
if operation == "+":
answer = number1 + number2
elif operation == "-":
answer = number1 - number2
elif operation == "*":
answer = number1 * number2
elif operation == "/":
answer = number1 / number2
print(answer)
|
# Python 2.7
# Directions:
# Make a dictionary called favorite_cities.
# Think of three names to use as keys (or ask three real people),
# and store at least one favorite city for each person.
# Finally, loop through the dictionary, then print each person's name
# and their favorite cities.
# To help you get started...
favorite_cities = {
'key1': ['value1', 'value2', 'value3'],
'key2': ['value1', 'value2', 'value3'],
'key3': ['value1', 'value2', 'value3'],
}
# Now loop through the dictionary to relay the dictionary's data
# Look to the example on the favorite languages poll
# Here's the first line to help you get started
for name, cities in favorite_cities.items():
###########################
# Example from Python Crash Course by Eric Matthes
# Let's look at the favorite languages poll example we did in class...
# Showing similar objects in a dictionary, with a nested list to show more than one favorite lang
# where we look at a poll taken from a population for favorite programming languages
# This will be VERY similar to the favorite_cities dictionary
# To see the code below run, just take out the comments on each line (be careful of indentation).
#favorite_languages = {
# 'jen': ['python', 'ruby'],
# 'sarah': ['c'],
# 'edward': ['ruby', 'go'],
# 'phil': ['python', 'haskell'],
# }
#
#for name, languages in favorite_languages.items():
# print("\n" + name.title() + "'s favorite languages are:")
# for language in languages:
# print("\t" + language.title())
|
# Add the calculator with turtle
import turtle
frank = turtle.Turtle()
number1 = int(raw_input("Please give me a number "))
number2 = int(raw_input("Please give me a number "))
operation = raw_input("What operation would you like me to perform? ")
if operation == '+':
answer = number1 + number2
elif operation == '-':
answer = number1 - number2
elif operation == '*':
answer = number1 * number2
elif operation == '/':
answer = number1 / number2
frank.write(answer, move = True, font = ("Arial", 100, "bold"))
turtle.mainloop()
|
"""
A simple program checking height requirements for a rollercoaster.
Objective:
multi-way condition statement
"""
# Ask user for their name
# The value gets stored in the variable, name
name = raw_input("What is your name? ")
# Ask user for their height
# The value gets stored in the variable, height
# concatenate the variable, name with a string
print(name + ", Approximately how tall are you? (in inches)")
height = float(raw_input())
# we can merge the two lines above into just one line:
#height = float(raw_input(name + ", How tall are you, in inches? "))
# Check if the user's height is any less than 38
if height < 38:
# if the value of height is below, then return this...
print("You do not meet the rollercoaster's height requirements!" +
"\nTry again next year!")
# Check if the user's height is any number above 38
elif height > 38:
# if the value of height is above, then return this...
print("You are tall enough to ride the rollercoaster!")
|
import turtle
frank = turtle.Turtle()
def calc(number1, number2, operation, color):
if operation == "+":
answer = number1 + number2
elif operation == "-":
answer = number1 - number2
elif operation == "*":
answer = number1 * number2
elif operation == "/":
answer = number1 / number2
frank.pencolor(color)
frank.write(answer, move=True, font = ("Arial", 100, "bold"))
turtle.mainloop()
print("\n Check out the turtle window to see the answer!")
calc(int(raw_input("Give me a number: ")),
int(raw_input("Give me another number: ")),
raw_input("What operation? "),
raw_input("Type in a color: ")
)
|
"""
Example exercise on python lists:
how they're structured and what you can do with them.
"""
foods = ['apple']
foods.append('orange')
foods.extend(('yams','bannanas','tomatoes','TOES'))
#foods = [apples,orange,yams,bannanas,tomatoes]
print(foods[1])
if'apple' in foods:
print("TRUE")
for food in foods:
print food.title()
print(foods)
|
# Using a while loop with lists
# Python 2.7
# Objective: move items from one list to another
# Consider a list of newly registered but unverified users of a website. After we
# verify these users, we need to move them to seperate list of confirmed users.
# From what we just learned, we can use a while loop to pull users
# from the list of unconfirmed users as we verify them and then add them to a
# seperate list of confirmed users.
# Create a new python file named, confirm_users.py
# Let's start with the users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['albert', 'ada', 'watson', 'crick']
confirmed_users = []
# We need to verify each user until there are no more unconfimed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
# All confirmed users displayed
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
|
# Choose your own adventure game
# WIZARD MOUNTAIN
# To be run in Python 2.7
# Change the functions, raw_input(), to input(), if you run in Python 3 or higher
# a text-based choose your own adventure game
# This adventure is like an upside down tree with branches
# this program is full of blocks of code, known as branches, or code branches
# Make sure to visit every branch to make sure all of the code works
def parachute_fail():
print("\nyour parachute fails! Good luck!")
def wizard_mtn():
print("\nYou land on the mountain, known as WIZARD MOUNTAIN")
def water():
print("\nYou make a rough landing in the water! You put on your floaties and wait for rescue.")
def curl():
print("Good thinking! Your plane crashes.")
print("You are unconscious, but safe.")
print("You are; however, in an unknown area with a lonely tree next to you.")
choice = raw_input("\nA) Wake up, or B) Keep sleeping ")
if choice == 'A':
print("\nYou wake up, somewhere between the time of sunrise and noon.")
print("You notice your plane and its parts are more than halfway beneath the ground!")
print("You try to stand up...")
choice = raw_input("Type, huh? ")
if choice == 'huh?':
print("You are not standing up.")
print("You are actually stuck, halfway beneath some sand.")
print("You see a tree limb branching from the lonely tree that looks to be in reach.")
choice = raw_input("Do you reach for the branch? or Do you look around some more?" + " Type REACH or LOOK. ")
if choice == 'REACH':
print("You are able to pull yourself out of the sand!")
print("But, your journey is just beginning...")
elif answer2 == 'LOOK':
print("\nOops! You hesitated. You find that you are in quicksand and you should have reached for the branch!")
print(
"""
_____ ___ ___ ___ _____
/ ___| / | / |/ | | ___|
| | / /| | / /| /| | | |__
| | _ / ___ | / / |__/ | | | __|
| |_| | / / | | / / | | | |___
\_____/ /_/ |_| /_/ |_| |_____|
_____ _ _ _____ _____
/ _ \ | | / / | ___| | _ \
| | | | | | / / | |__ | |_| |
| | | | | | / / | __| | _ /
| |_| | | |/ / | |___ | | \ \
\_____/ |___/ |_____| |_| \_\
"""
)
else:
print("Sorry, I can't understand you. ")
raw_input("\n\nPress the enter key to exit and run the program again!")
if choice == 'B':
print("You never wake from your slumber ")
print(
"""
_____ ___ ___ ___ _____
/ ___| / | / |/ | | ___|
| | / /| | / /| /| | | |__
| | _ / ___ | / / |__/ | | | __|
| |_| | / / | | / / | | | |___
\_____/ /_/ |_| /_/ |_| |_____|
_____ _ _ _____ _____
/ _ \ | | / / | ___| | _ \
| | | | | | / / | |__ | |_| |
| | | | | | / / | __| | _ /
| |_| | | |/ / | |___ | | \ \
\_____/ |___/ |_____| |_| \_\
"""
)
raw_input("\n\nPress the enter key to exit and import the file name to run the program again!")
def valley():
print("\nYou safely land in the middle of the goat herd.")
def goat_ride():
print("\nThe trusty goat takes you to the nearest town. You are safe!")
def goat_herder():
print("\nYou become a successful goat herder and make millions.")
def bad_wizard():
print("\nThe object captures you and throws you into a magical stew paired with frog legs and magic chicken wings")
def good_wizard():
print("\nA magical wizard comes from the object with a coconut and healing potion for you.")
print("in a booming voice, the magical wizard explains, " + "Welcome to Wizard Mountain!!! " + " I suggest you explore this magical monstrousity!")
def answer_ab():
print("Please type 'A' or 'B'")
def demise():
print("You end your tumble at the end of the slope.")
print("You have reached your breaking point.")
raw_input("\n\npress the enter key to exit.")
def jagged_rock():
print("""you manage to suddenly stop your flight by clutching the jagged rock.
You realize your hands and arms are super slimey.
but... why?
You spot an opening in the ground next to the rock.
The hole is just big enough for you to crawl through""")
def spikey_tree():
print("You barely hang on to a spikey tree")
print("\nOUCH! The tree is too spikey. You must let go of your grip and you continue your tumultuous tumble down the treacherous slope")
print("You end up in a...")
raw_input("\n\npress the enter key to exit.")
def hole():
print("\nyou crawl through the hole")
print("After a few minutes of shuffling down the hole, you plumet and land with a splash into an underground lake.")
def snail_demise():
print("Draco spits out an acidic goo that covers you")
print("You are unable to move and are stuck on this rock, hearing Draco's tales of his snail trails, until the end of your days")
print(
"""
_____ ___ ___ ___ _____
/ ___| / | / |/ | | ___|
| | / /| | / /| /| | | |__
| | _ / ___ | / / |__/ | | | __|
| |_| | / / | | / / | | | |___
\_____/ /_/ |_| /_/ |_| |_____|
_____ _ _ _____ _____
/ _ \ | | / / | ___| | _ \
| | | | | | / / | |__ | |_| |
| | | | | | / / | __| | _ /
| |_| | | |/ / | |___ | | \ \
\_____/ |___/ |_____| |_| \_\
"""
)
raw_input("\n\npress the enter key to exit.")
print("""
You take your trusty propellar plane out for a joy ride.
Suddenly, the plane's propeller stops working and you are hurtling towards the ground!
You quickly spot a parachute next to you.
What do you do?
"""
)
print("\n**HINT** When making decisions, please type your answer as an uppercase letter.")
choice = raw_input("\nA) Quickly put on the parachute, B) Try to steer the plane towards the nearest body of water, or C) Curl up into a ball ")
# First branch of story
if choice == "A":
print("\nYou jump out of the plane! You pull the string to open up the parachute. To your right, you see a mansion on top of a mysterious mountain. To your left, you see a goat herd in the valley. What do you do? ")
choice = raw_input("A) Steer right or B) Steer left ")
if choice == "A":
wizard_mtn()
print("You see an object in the distance.")
choice = raw_input("\nA) Go to object? or B) Hike towards the mansion ")
if choice == "A":
print("\nYou are weary from the excitement and your health is low from the landing.")
good_wizard()
choice = raw_input("\nExplore WIZARD MOUNTAIN? 'Y' or 'N' ")
if choice == 'Y':
print("You begin your exploration of Wizard Mountain.")
print("You are a little dizzy and sick from your landing.")
print("You spot a bottle of opened motion-sickness meds curiously lying on a rock to your left.")
choice = raw_input("ingest the contents of the motion-sickness bottle? 'Y' or 'N' ")
if choice == 'Y':
print("Bad move? Yes!")
print("The contents of the bottle was not what it said it was!")
print("You begin to feel even more woozy and disoriented.")
print("You see a light at the corner of your eye and a fuzzy dark figure appear to your left.")
choice = raw_input("A) Go towards the light, or B) Ask the fuzzy dark figure for help ")
if choice == 'A':
print("You head towards the light")
print("Uh Oh, the light source was the horizon of a steep hill!")
choice = raw_input("You begin tumbling towards certain death.. Is this your demise? 'Y' or 'N' ")
if choice == 'Y':
demise()
elif choice =='N':
print("""
You are a fighter!
Though, your ungraceful tumble down the steep slope past spikey trees and jagged rocks promises certain death
""")
choice = raw_input("A) Grab hold of a passing spikey tree, or B) Clutch a jagged rock? ")
if choice == 'A':
spikey_tree()
demise()
elif choice == 'B':
jagged_rock()
choice = raw_input("A) Take a closer look at the rock, or B) Travel down the hole ")
if choice == 'A':
print("""
Gross!
The rock is full of slimey snails!
You hear a tiny voice coming from one of these slimey snails
"""
)
choice = raw_input("Listen to the talkative snail? 'Y' or 'N' ")
if choice == 'Y':
print("The snail tells you tales of wonder about WIZARD MOUNTAIN")
print("This is a place of treasure far as the eye can see, good wizards, bad wizards, and a terrible silicon breathing dragon")
print("The snail tells you its name, 'Draco' ")
print("Draco: What is your name?")
name = raw_input()
print("Draco: " + name + " You seem a bit battered, to say the least ")
print("So, " + name)
choice = raw_input(" Do you need my help? 'Y' or 'N' ")
if choice == 'Y':
print("Draco: Next to this rock is a hole. I suggest you head down it")
print("You will find the reason of your life's journey starting there.")
hole()
elif choice == 'N':
snail_demise()
elif choice == 'B':
hole()
elif choice == 'B':
bad_wizard()
else:
bad_wizard()
elif choice == "B":
valley()
choice = raw_input("A) Ride a goat to the nearest town or B) Become a goat herder")
if choice == "A":
goat_ride()
elif choice == "B":
goat_herder()
else:
parachute_fail()
elif choice == "B":
# Second branch of the story
water()
elif choice == "C":
# Third branch of the story
curl()
|
"""
Calls methods from the Turtles class to
output a simple turtle race using Turtle Graphics
"""
import turtle
from racer_class import Turtles
# Calling methods from Turtles class
# methods:
# Defines All Turtles
red = Turtles(turtle) # __init__()
green = Turtles(turtle) # __init__()
blue = Turtles(turtle) # __init__()
# Sets Racer Characteristics
red.looks('red', 'turtle') # looks()
green.looks('green', 'turtle') # looks()
blue.looks('blue', 'turtle') # looks()
# Set Starting Positions
red.start(-160, 90) # start()
green.start(-160, 60) # start()
blue.start(-160, 30) # start()
# And they're off!!!
for turn in range(100):
red.go() # go()
green.go() # go()
blue.go() # go()
|
"""
Draw a circle out of squares
"""
import turtle
def draw_square(frank):
for i in range(4):
frank.forward(100) # move forward 100 units
frank.right(90) # turn right 90 degrees
def draw_art():
# Instantiate a Screen object, window. Then customize window.
window = turtle.Screen()
window.bgcolor("white")
frank = turtle.Turtle()
# frank.shape("turtle") # see Turtle doc
# frank.color("yellow") # see Turtle doc
frank.speed(10)
# Draw a circle with 36 squares. We rotate each square by 10 degrees at a time.
for i in range(36):
draw_square(frank)
frank.right(10)
window.exitonclick() # click on the window to exit
# Invoke the procedure!
draw_art()
|
# Python 2.7
# Example from Python Crash Course by Eric Matthes
# Using break to Exit a loop
# So far, we've looked at stopping a while loop by using a flag variable
# You can also use a BREAK statement...
# To exit a while loop immediately without running any remaining code in the loop,
# regardless of the results of any conditional test, use the break statement.
# The break statement directs the flow of your program
# You can use it to control which lines of code are executed and which aren't,
# so the program only executes code that you want it to, when you want it to
# Think of the term abstraction?
# Let's look at an example
# Consider a program that asks the user about places they've visited.
# To stop the while loop in this program by calling break as soon
# as the user enters the 'quit' value:
prompt = ("\nPlease enter the name of a city you have visited:")
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = raw_input(prompt)
if city == 'quit':
break
else:
print("I'd love to go " + city.title() + "!")
# this loop that starts with a "while True" will run continuously
# until it reaches a break statement
# You can use the break statement in any Python loops.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.