text
stringlengths
37
1.41M
while True: player_name = input(""" What is your name? > """) if len(player_name) > 15 or len(player_name) < 3: print("ass name") elif input(f"Are you sure {player_name} is your name? > ").lower() == "yes": break else: pass print(f"Welcome {player_name}") print(""" You wake up to the sound of leaves rustling outside their window. Your bedroom is cluttered with junk ranging from clothes to action figures. It seemed like you had awoken around midnight. Being parched you decide to... """) while True: choice_1 = input(""" 1. Go downstairs and take a drink. 2. Stay in bed and sleep the night. > """) if choice_1 == "1": print(""" You make your way down the stairs carefully as to not wake up your parents. You make your way towards the kitchen after passing through the spacious living room. You grab your favorite Lightning McQueen water cup and drink out of it. Out of the corner of your eye you think you see a fleeting figure go past your kitchen window.. You shrug it off thinking it's just your eyesight since you didn't grab your glasses. You quickly and quietly make your way back upstairs into your bed... """) break elif choice_1 == "2": print(""" You slowly fall back asleep. Closing your eyes and trying to resume the dream you were dreaming..""") break else: pass print(f""" "Wake up {player_name}!" """) while True: choice_2 = input(""" """)
m=int(input("enter no of rows")) n=int(input("enter no of columns")) a = [] print("enter elemnts") for i in range(m): l1=[] for j in range(n): b=int(input()) l1.append(b) a.append(l1) print(a)
class Temp: ''' Celsius to Fahrenheit:   (°C × 9/5) + 32 = °F Fahrenheit to Celsius:   (°F − 32) x 5/9 = °C''' @staticmethod def temp_CtoF(c): f=(c*9/5)+32 print(f) @staticmethod def temp_FtoC(fr): c=(fr-32)*5/9 print(c)
import numpy as np def func(x): f = 0.2+25*x-200*np.power(x, 2)+675*np.power(x, 3)-900*np.power(x, 4)+400*np.power(x, 5) return (f) # a & b = limits of integration # n = number of segments def simpson(a, b, n): h = (b - a) / n x = [] y = [] for i in range(0, n+1): x.append(a+i*h) y.append(func(x[i])) # Applying formula fo simpson 1/3 res = 0 i = 0 while i <= n: if i == 0 or i == n: # first term res += y[i] elif i % 2 != 0: res += 4 * y[i] # second term else: res += 2 * y[i] # third term i += 1 res = res * (h / 3) return res n = int(input("Indicate number of segments\n")) a = float(input("provide a bound\n")) b = float(input("provide b bound\n")) print("Approximate value for " + str(n) + " segments is %.4f" % simpson(a, b, n))
import numpy as np from math import * # np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)}) def quadFunc(x): result = v2[0] + v2[1] * x + (v2[2] * np.power(x, 2)) return result def cubFunc(x): result = v2[0] + v2[1] * x + (v2[2] * np.power(x, 2)) + (v2[3] * np.power(x, 3)) return result def quartFunc(x): result = v2[0] + v2[1] * x + (v2[2] * np.power(x, 2)) + (v2[3] * np.power(x, 3)) + (v2[4] * np.power(x, 4)) return result print("Polynomial Regression Method") numPoints = int(input("Enter the number of points to evaluate\n")) x = [] y = [] xy = [] x2 = [] x3 = [] x4 = [] x5 = [] x6 = [] x7 = [] x8 = [] x2y = [] x3y = [] x4y = [] sumX = 0 sumY = 0 sumXY = 0 sumX2 = 0 sumX3 = 0 sumX4 = 0 sumX5 = 0 sumX6 = 0 sumX7 = 0 sumX8 = 0 sumX2Y = 0 sumX3Y = 0 sumX4Y = 0 for i in range(numPoints): x.append(float(input("Enter x" + str(i) + "\t"))) sumX += x[i] y.append(float(input("Enter y" + str(i) + "\t"))) sumY += y[i] xy.append(x[i] * y[i]) sumXY += xy[i] x2.append(x[i] * x[i]) sumX2 += x2[i] x3.append(np.power(x[i], 3)) sumX3 += x3[i] x4.append(np.power(x[i], 4)) sumX4 += x4[i] x5.append(np.power(x[i], 5)) sumX5 += x5[i] x6.append(np.power(x[i], 6)) sumX6 += x6[i] x7.append(np.power(x[i], 7)) sumX7 += x7[i] x8.append(np.power(x[i], 8)) sumX8 += x8[i] x2y.append(x2[i] * y[i]) sumX2Y += x2y[i] x3y.append(x3[i] * y[i]) sumX3Y += x3y[i] x4y.append(x4[i] * y[i]) sumX4Y += x4y[i] # QUADRATIC # matrix of coefficients matrix = np.zeros((3, 3)) vector = np.zeros(3) matrix[0, 0] = numPoints matrix[0, 1] = sumX matrix[0, 2] = sumX2 for r in range(1, 3): for c in range(0, 2): matrix[r, c] = matrix[r - 1, c + 1] matrix[1, 2] = sumX3 matrix[2, 2] = sumX4 matrix[2, 1] = matrix[1, 2] vector[0] = sumY vector[1] = sumXY vector[2] = sumX2Y # inverse matrix multiplication inverse = np.linalg.inv(matrix) v2 = np.zeros(3) v2 = np.matmul(inverse, vector) # Calculation of error begins e2 = 0 st = 0 for i in range(numPoints): e2 += np.power(y[i] - quadFunc(x[i]), 2) st += np.power((y[i] - sumY / numPoints), 2) r2 = (st - e2) / st r = np.power(r2, 1 / 2) print("f(x)= " + str(v2[0]) + " + " + str(v2[1]) + "x + " + str(v2[2]) + "x2 ") print("r2 = " + str(r2)) print("r = " + str(r)) # CUBIC # matrix of coefficients matrix2 = np.zeros((4, 4)) vector2 = np.zeros(4) matrix2[0, 0] = numPoints matrix2[0, 1] = sumX matrix2[0, 2] = sumX2 matrix2[0, 3] = sumX3 for c in range(0, 3): matrix2[1, c] = matrix2[0, c + 1] matrix2[1, 3] = sumX4 for c in range(0, 3): matrix2[2, c] = matrix2[1, c + 1] matrix2[2, 3] = sumX5 for c in range(0, 3): matrix2[3, c] = matrix2[2, c + 1] matrix2[3, 3] = sumX6 vector2[0] = sumY vector2[1] = sumXY vector2[2] = sumX2Y vector2[3] = sumX3Y # inverse matrix multiplication inverse2 = np.linalg.inv(matrix2) v2 = np.zeros(4) v2 = np.matmul(inverse2, vector2) # Calculation of error begins e2 = 0 st = 0 for i in range(numPoints): e2 += np.power(y[i] - cubFunc(x[i]), 2) st += np.power((y[i] - sumY / numPoints), 2) r2 = (st - e2) / st r = np.power(r2, 1 / 2) print("f(x)= " + str(v2[0]) + " + " + str(v2[1]) + "x + " + str(v2[2]) + "x2 + " + str(v2[3]) + "x3 ") print("r2 = " + str(r2)) print("r = " + str(r)) # QUARTIC # matrix of coefficients matrix3 = np.zeros((5, 5)) vector2 = np.zeros(5) matrix3[0, 0] = numPoints matrix3[0, 1] = sumX matrix3[0, 2] = sumX2 matrix3[0, 3] = sumX3 matrix3[0, 4] = sumX4 for c in range(0, 4): matrix3[1, c] = matrix3[0, c + 1] matrix3[1, 4] = sumX5 for c in range(0, 4): matrix3[2, c] = matrix3[1, c + 1] matrix3[2, 4] = sumX6 for c in range(0, 4): matrix3[3, c] = matrix3[2, c + 1] matrix3[3, 4] = sumX7 for c in range(0, 4): matrix3[4, c] = matrix3[3, c + 1] matrix3[4, 4] = sumX8 print(matrix3) vector2[0] = sumY vector2[1] = sumXY vector2[2] = sumX2Y vector2[3] = sumX3Y vector2[4] = sumX4Y # inverse matrix multiplication inverse2 = np.linalg.inv(matrix3) v2 = np.zeros(5) v2 = np.matmul(inverse2, vector2) # Calculation of error begins e2 = 0 st = 0 for i in range(numPoints): e2 += np.power(y[i] - quartFunc(x[i]), 2) st += np.power((y[i] - sumY / numPoints), 2) r2 = (st - e2) / st r = np.power(r2, 1 / 2) print("f(x)= " + str(v2[0]) + " + " + str(v2[1]) + "x + " + str(v2[2]) + "x2 + " + str(v2[3]) + "x3 +" + str(v2[4]) + "x4") print("r2 = " + str(r2)) print("r = " + str(r))
# Exercise 5.1 student_heights = input("Enter the list of Students height: ").split() for x in range(0, len(student_heights)): student_heights[x] = int(student_heights[x]) height = 0 for height1 in student_heights: height += height1 #print(height) total = 0 for total1 in student_heights: total += 1 #print(total) average = round(height /total) print(average) # Exercise 5.2 student_scores = input("Enter the list of Student score: ").split() for high in range(0, len(student_scores)): student_scores[high] = int(student_scores[high]) marks = 0 for x in student_scores: if x > marks: marks = x print(f"The highest score in the class is: {marks}") # Exercise 5.3 #1st Method value = 0 for x in range(2,101,2): value += x print(value) #2nd Method value = 0 for x in range(0,101): if x % 2 ==0: value += x print(value) #Exercise 5.4 - FizzBuzz for x in range(1,101): if x % 3 == 0 and x % 5 ==0: print("FizzBuzz") elif x % 3 == 0: print("Fizz") elif x % 5 == 0: print("Buzz") else: print(x)
n = int(input()) rballs = [] bballs = [] for _ in range(n): number, color = map(str, input().split()) number = int(number) if color == "R": rballs.append(number) else: bballs.append(number) # print(rballs, bballs) rballs = sorted(rballs) bballs = sorted(bballs) for r in rballs: print(r) for b in bballs: print(b)
ns = list(input()) for n in ns: if n == "7": print("Yes") break else: print("No")
class FixLenIter(object): def __init__(self, iterator, length): self.iter = iterator self.length = length self.count = 0 def __next__(self): if self.count < self.length: self.count += 1 return next(self.iter) else: self.count = 0 raise StopIteration() def __iter__(self): return self
run_player1 =int(input("ENTER RUN SCORE BY PLAYER1 IN 60 BALLS :")) run_player2 =int(input("ENTER RUN SCORE BY PLAYER2 IN 60 BALLS :")) run_player3 =int(input("ENTER RUN SCORE BY PLAYER3 IN 60 BALLS :")) STRIKE_RATE1 =run_player1 * 100 /60 STRIKE_RATE2 =run_player1 * 100 /60 STRIKE_RATE3 =run_player1 * 100 /60 print("STRIKE RATE OF PLAYER1 IS : ",STRIKE_RATE1) print("STRIKE RATE OF PLAYER2 IS : ",STRIKE_RATE2) print("STRIKE RATE OF PLAYER3 IS : ",STRIKE_RATE3) print("RUN SCORED BY PLAYER1 IF HE PLAY 60 BALL MORE : ",run_player1*2) print("RUN SCORED BY PLAYER2 IF HE PLAY 60 BALL MORE : ",run_player2*2) print("RUN SCORED BY PLAYER3 IF HE PLAY 60 BALL MORE : ",run_player2*2) print("Maximum Six hit by PLayer 1 : ",run_player1//6) print("Maximum Six hit by PLayer 2 : ",run_player2//6) print("Maximum Six hit by PLayer 3 : ",run_player3//6)
import sqlite3 as sql import add import display import printTopdf user_name=None password=None cur=None flag=None def sql_conn(): try: conn=sql.connect("course_db.db") cur=conn.cursor() except Exception as e: print(e) print("Error") query="create table if not exists admin(user_name char(100), pass char(20),primary key(user_name));" cur.execute(query) sql_conn() def displayChoice(): print("\n"*10) c=""" $ $ $ $ $ $ $ $ welcome $ $ $ $ $ $ $ $ """ print(c) print() x="""********************************* * 1: Add Details * * 2: Display * * 3: Print to pdf * * 0: Exit * ********************************* """ print(x) ch=int(input("\nEnter your choice:")) if (ch==1): add.insertDetails() input() displayChoice() elif (ch==2): display.display() input() displayChoice() elif (ch==3): printTopdf.savePdf() displayChoice() elif (ch==0): exit() else: print("Please enter valid option") displayChoice() def loginUser(): flag=False conn=sql.connect("course_db.db") cur=conn.cursor() user_name=input("Uername:") password=input("Password:") if (user_name=="" and password==""): print("Please check username and password") else : query_1="select * from admin" cur.execute(query_1) rows=cur.fetchall() #op in tuple for row in rows: if (row[0]==user_name and row[1]==password): flag=True #print("User valid") break else: flag=False if(flag==True): print("\n"*4) displayChoice() else: loginUser() if __name__ == '__main__': main()
import turtle def make_paddle(coords): paddle = turtle.Turtle() paddle.speed(0) paddle.shape("square") paddle.color("white") paddle.shapesize(stretch_wid=5, stretch_len=1) paddle.penup() paddle.goto(coords[0], coords[1]) return paddle def make_ball(): ball = turtle.Turtle() ball.speed(0) ball.shape("square") ball.color("white") ball.penup() ball.goto(0, 0) return ball
def add(a,b): c = a + b return c def sub(a,b): c = a - b return c def mult(a,b): c = a * b return c def div(a,b): c = a / b return c menu = ''' Simple calc made by Dave 01. Add \n 02. Subtract \n 03. Multiply \n 04. Divide ''' print(menu) # inputs num1 = int(input('Enter a number:')) num2 = int(input('Enter a number 2:')) # get values from the func added = add(num1,num2) subtracted = sub(num1,num2) multplied = mult(num1,num2) division = div(num1,num2) # print outout print(f"The sum of {num1} and {num2} is {added}") print(f"The diffrence of {num1} and {num2} is {subtracted}") print(f"The mutiple of {num1} and {num2} is {multplied}") print(f"The Quotient of {num1} and {num2} is {division}") # operaters ''' maths addation + sub - division / mult * ----------------- logical oparetors And && Or || Not != ''' # condations # if # else #elif dave_age = 16 sam_age = 21 if sam_age < 18: print('You are under age') else: print("You are an adult")
from collections import Counter n = int(input()) word = [] for o in range(n): word.append(input()) counts = [] print(len(set(word))) print(*Counter(word).values())
s = raw_input("enter a string") lwr = '' upp = '' evn = '' odd = '' sorted_lower = '' sorted_upper = '' sorted_even = '' sorted_odd = '' new_s_sorted = '' for t in s: if t.islower() == True: lwr += t sorted_lower = sorted(lwr) sorted_lower_string = ''.join(sorted_lower) new_s_sorted += sorted_lower_string for t in s: if t.isupper() == True: upp += t sorted_upper = sorted(upp) sorted_upper_string = ''.join(sorted_upper) new_s_sorted += sorted_upper_string for t in s: if t.isdigit() == True and ((int(t))%2) != 0: odd += t sorted_odd = sorted(odd) sorted_odd_string = ''.join(sorted_odd) new_s_sorted += sorted_odd_string for t in s: if t.isdigit() == True and ((int(t))%2) == 0: evn += t sorted_even = sorted(evn) sorted_even_string = ''.join(sorted_even) new_s_sorted += sorted_even_string print(new_s_sorted)
# 4.23 friday all_words = input("Type in: ") all_words_split = all_words.split(' ') single_words = [] for i in all_words_split: if i not in single_words: single_words.append(i) else: continue single_words.sort() print((' ').join(single_words))
def fab3(max): n, a, b = 0, 0, 1 while n < max: print('begin') yield b # print b # yield from range(10) # yield 'third' print('+++') a, b = b, a + b n = n + 1 f=fab3(5) print("f是一个可迭代对象,并没有执行函数") print(f) print('fab3返回的是一个iterable 对象,可以用for循环获取值') print(f.__next__()) print('-------') print(f.__next__()) # for n in f: # print(n) # print('-------')
exp = input() stack = [] for x in exp: if x.isdecimal(): stack.append(int(x)) else: num2 = stack.pop() num1 = stack.pop() if x == '+': res = num1 + num2 elif x == '*': res = num1 * num2 elif x == '/': res = num1 / num2 elif x == '-': res = num1 - num2 stack.append(res) print(stack.pop())
import abc class Formatter(abc.ABC): """ Base abstract class for formatters. """ @abc.abstractmethod def emit(self, column_names, data): """ Format and print data from the iterable source. :param column_names: names of the columns :type column_names: list :param data: iterable data source, one tuple per object with values in order of column names :type data: list or tuple """
def multyply(A, B): res = [[0 for i in range(len(A))] for j in range(len(B))] for i in range(len(A)): for j in range(len(B[0])): res[i][j] = sum([A[i][k] * B[k][j] for k in range(len(B))]) return res def fast_pow(a, m): c = 1 while m > 0: if m & 1: c *= a a = a * a m >>= 1 return c def matrix_fast_pow(a, m): c = [[1 for _i in range(len(a))] for _j in range(len(a[0]))] while m > 0: if m & 1: c = multyply(c, a) a = multyply(a, a) m >>= 1 return c
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys,os import getpass #作业要求编写登陆窗口 #输入用户名密码 #认证成功显示欢迎信息 #输错三次锁定 #登陆 注册 #user_name = open("User_Name.log","w") #创建一个用户名文件 只能用一种模式打开 #user_name.close() #user_password = open("User_Password.log","w") #创建一个用户密码文件 #user_password.close() #lock_user = open("Lock_User.log","w") #创建一个被锁定用户文件 #lock_user.close() #用户注册 #print("请输入login?还是register?") while True : chose = input("请输入l?还是r?") #选择 if chose == 'l' : print("登陆") Name = input("请输入用户名:") print(Name) user_name = open("User_Name.log", 'r') #读文件 user_password = open("User_Password.log", 'r') #同上 lock_user = open("Lock_User.log","r") #同上 user_name_list = user_name.readlines() #将列表转换为列表格式 user_password_list = user_password.readlines() #同上 lock_user_list = lock_user.readlines() #同上 #Append_format = #passwd = user_name_list.index(Name) # 索引对应名字的序号 #print("他的名字:", passwd) for Lock_List in lock_user_list : #循环读出每一个字符串 lock_list = Lock_List.strip('\n') #去除字符串中的(\n) if Name == lock_list : sys.exit("对不起,%s 已经被锁定,不能登陆"%(Name)) else: print("user_name%s user_password%s Lock_user %s"%(user_name_list,user_password_list,lock_user_list)) i = 0 for Name_List in user_name_list: #读出每一个字符串,便于处理 name_list = Name_List.strip('\n') #对每一个字符串去除{\n} print("次数: %d 用户名:%s"%(i,name_list)) if Name == name_list : #判断是否存在 count = 0 while count < 3: #三次机会 password = input("请输入密码:") for Password_List in user_password_list : #读出每一个字符串 password_list = Password_List.strip('\n') #去除\n if password == password_list: print("恭喜你登陆成功。") sys.exit(0) else: continue #没有即结束这次循环 print("您输入的密码错误%s,还有%d次机会"%(Name,2-count)) count +=1 else: lock_name = open("Lock_User.log","a") #添加锁定账户 lock_name.write(Name + '\n') lock_name.close() sys.exit("您已经三次输入错误,您的帐号将被锁定。") else: pass i +=1 else: pass print("--->",name_list) else: pass else: print("注册") user_name = open("User_Name.log",'a') name = input("请输入用户名:") user_name.write(name + '\n' ) #print(user_name.readlines()) #user_name.close() #user_name = open("User_Name.log", 'r') print("请确认用户名 %s"%(name)) user_password = open("User_Password.log","a") password = input("请输入密码:") user_password.write(password + '\n') user_name.close() user_password.close() ''' lock_file = open("account_lock","w") lock_file.write("ZhangSan\n") lock_file.write("ZhangSan1\n") lock_file.write("ZhangSan2\n") lock_file.close() user_file = open("account","w") user_file.write("wxl\n") user_file.write("123456\n") user_file.close() i = 0 while i<3: name = input("请输入用户名:") lock_file = open("account_lock","r") lock_list = lock_file.readlines() for lock_line in lock_list: lock_line = lock_line.strip('\n') if name == lock_line: sys.exit("用户 %s 已经被锁定,退出"%(name)) user_file = open("account","r") user_list = user_file.readlines() print(user_list) user = user_list[0].strip('\n') password = user_list[1].strip('\n') print("user:%s password%s"%(user,password)) for user_line in user_list: #user = user_line.strip("\n").split() #password = user_line.strip("\n").split() #print("user %s password %s"%(user,password)) if name == user : j = 0 while j<3: passwd = input("请输入密码:") if passwd == password: print("用户 %s 登陆成功"%(name)) sys.exit(0) else: if j!=2 : print("用户 %s 密码错误,请重新输入,还有%d 次机会"%(name,2-j)) j +=1 else: lock_file.write(name + "\n") sys.exit("用户 %s 达到最大登陆次数,将被锁定并退出"%(name)) else: pass else: if i != 2: print("用户名 %s 不存在,请重新输入,还有%d次机会"%(name,2-i)) i += 1 else: sys.exit("用户 %s 不存在,退出"%name) lock_file.close() user_file.close() '''
import random #랜덤 숫자를 생성하거나 다양한 랜덤 관련 함수를 제공하는 모듈 min = 0 max = 99 flag = 0 answer = random.randrange(0,100) # 0부터 99까지의 난수를 발생시킨 뒤, answer에 저장한다 for i in range(1,11): # 기회를 10번 부여하기 때문에 구간을 range(1,11)로 설정 print("숫자 입력(범위: %d~%d): "%(min,max),end = '') guess = int(input()) if(answer > guess): print(" 틀렸습니다. 더 큰 숫자입니다!\n") min = guess # 정답이 추측보다 커서 메세지를 출력하고 추측 값을 최소로 함 elif (answer < guess): print(" 틀렸습니다. 더 작은 숫자입니다!\n") max = guess # 정답이 추측보다 작아서 메세지를 출력하고 추측 값을 최대로 함 else: print(" 정답입니다!! ",i,"번 만에 맞췄네요~~") flag = 1 break # 정답을 맞추면 메세지를 출력하고 flag를 1로 설정한 후 반복문 탈출 if (flag != 1): print("----- 시도 횟수 초과 -----") # 정답 조건의 flag = 1을 거치지 않은 경우는 정답을 못맞힌 채 # 횟수 초과로 인해 반복문을 탈출한 경우이기 때문에 횟수 초과 메세지 출력 print("\n게임 끝!!")
def sum(n): # 1부터 n까지의 합을 구하는 순환 알고리즘 print(n) if n < 1: return 0; else: return n + sum(n-1) # 재귀 호출 def asterisk(i): # 별을 출력하는 순환 알고리즘 if i > 1: asterisk(i/2) asterisk(i/2) print("*",end='') # asterisk(i)가 호출 될 때, i가 1보다 클 시 asterisk(i/2)를 두번 호출한다. print('sum(5)의 실행결과:',sum(5),'\n') # 5+4+3+2+1 asterisk(5) # 총 15개의 별이 출력. print('\n')
#Read file and print in uppercase fname = raw_input("Enter file name: ") fh = open(fname) fh = fh.read() fupper = fh.upper() fupper = fupper.rstrip() print fupper
def rev_of_str(string): S = len(string) arr = [None]*S # print len(arr) for i in string: S = S - 1 arr[S] = i print ''.join(arr) T = int(raw_input()) for i in range(T): rev_of_str(raw_input())
""" Notes of interaction with contact """ class Note(): def __init__(self, note, datetime=None): self.datetime = datetime self.note = note def __str__(self): # dont assume note is str, cast; just first 7 chars return str(self.note)[:7] + ( "..." if len(str(self.note)) > 7 else "") # just first 7 chars """ XXX Tests to create: Note 1) note creation with just text... right one created? verify note & str representation 2) note creation with text and datetime... right one created? verify note & date & str representation 3) note creation non-text object verify note & str representation 4) empty note creation Notes 1) notes creation... empty verify notes empty and string representation 2) notes creation... one verify notes & str representation 3) notes creation... 4 notes verify notes & str representation 4) empty notes + append verify notes and str representation """ class Notes(): def __init__(self, *notes): self.notes = [Note(n) for n in notes] def append(self, note): self.notes.append(note) def __str__(self): if len(self.notes) < 1: return "[]" return ("[[" + str(self.notes[0]) + "],...[" + str(self.notes[-1]) + "]]")
import unittest import blackjack_class class TestDeck(unittest.TestCase): def test_deckcards(self): """ This test case tests function deck_cards of class Deck. It returns the list of 52 shuffled deck of cards.. :return: None """ expected_list = [ 'HA', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'HT', 'HJ', 'HQ', 'HK', 'SA', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'ST', 'SJ', 'SQ', 'SK', 'DA', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'DT', 'DJ', 'DQ', 'DK', 'CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CT', 'CJ', 'CQ', 'CK', ] testing_class = blackjack_class.Deck() self.assertEqual(testing_class.deck_cards().sort(), expected_list.sort()) def test_dealcards(self): """ This test case tests function deal_cards of class Deal. It checks if the result contains three lists and it also checks the length of each list. :return: None """ deck = [ 'HA', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'HT', 'HJ', 'HQ', 'HK', 'SA', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'ST', 'SJ', 'SQ', 'SK', 'DA', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'DT', 'DJ', 'DQ', 'DK', 'CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CT', 'CJ', 'CQ', 'CK', ] test_class = blackjack_class.Deal() num_cards = test_class.deal_cards(deck) self.assertEqual(len(num_cards), 3) self.assertEqual(len(num_cards[0]),2) self.assertEqual(len(num_cards[1]),2) self.assertEqual(len(num_cards[2]),48) def test_pointcalc(self): """ This test case tests function point_calc of class Calculation. It checks if the result contains the calculation of cards and give total points. :return: None """ lst = ['SA', 'D2', 'HT', 'S9'] test_class = blackjack_class.Calculation() total_points = test_class.point_calc(lst) self.assertEqual(total_points, 22) lst = ['HA', "D2", 'HJ'] test_class = blackjack_class.Calculation() total_points = test_class.point_calc(lst) self.assertEqual(total_points, 13) lst = ['SA', 'HA', "DA"] test_class = blackjack_class.Calculation() total_points = test_class.point_calc(lst) self.assertEqual(total_points, 13) def test_playerhit(self): """ This test case tests function player_hit of class Player. It checks if the result contains three lists after player say Hit.The first list contains number of cards in player hand, second list contains the number of cards left in the deck and third list contains total points of players hand. :return: None """ deck = [ 'H5', 'H6', 'H7', 'H8', 'H9', 'HT', 'HJ', 'HQ', 'HK', 'SA', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'ST', 'SJ', 'SQ', 'SK', 'DA', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'DT', 'DJ', 'DQ', 'DK', 'CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CT', 'CJ', 'CQ', 'CK', ] player_deck = ['HA', 'H2', ] test_class = blackjack_class.Player() result = test_class.player_hit(player_deck,deck) self.assertEqual(len(result[0]),3) self.assertEqual(len(result[1]),47) self.assertEqual(result[2],18) def test_dealerhit(self): """ This test case tests function dealer_hit of class Dealer. It checks if the result contains three lists after dealer say Hit.The first list contains number of cards in dealer hand, second list contains the number of cards left in the deck and the third list contains total points of dealers hand. It tests both the scenarios if the dealer has less than 16 points or more than 16 points in hand. :return: """ deck = [ 'H5', 'H6', 'H7', 'H8', 'H9', 'HT', 'HJ', 'HQ', 'HK', 'SA', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'ST', 'SJ', 'SQ', 'SK', 'DA', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'DT', 'DJ', 'DQ', 'DK', 'CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CT', 'CJ', 'CQ', 'CK', ] dealer_deck = ['HA', 'H2', ] test_class = blackjack_class.Dealer() result = test_class.dealer_hit(dealer_deck,deck) self.assertEqual(len(result[0]),3) self.assertEqual(len(result[1]),47) self.assertEqual(result[2],18) deck = [ 'H5', 'H6', 'H7', 'H8', 'H9', 'H10', 'HJ', 'HQ', 'HK', 'SA', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'ST', 'SJ', 'SQ', 'SK', 'DA', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'DT', 'DJ', 'DQ', 'DK', 'CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CT', 'CJ', 'CQ', 'CK', ] result =[] dealer_deck = ['HJ', 'HK', ] test_class = blackjack_class.Dealer() result = test_class.dealer_hit(dealer_deck,deck) self.assertEqual(len(result[0]),2) self.assertEqual(len(result[1]),48) self.assertEqual(result[2],20)
''' print out binary place value patterns ''' import argparse def placevalue_patterner(function, height, width, placevalue, offset_y=0): ''' create a visualization of a place value pattern ''' visual = [] for i in range(offset_y, offset_y + height): row = '' for j in range(width): value = function(i, j) binary = '{0:b}'.format(int(value)) if len(binary) > placevalue and binary[-1 * placevalue] == '1': row += '*' else: row += ' ' visual.append(row) return '\n'.join(visual) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('function', help='The function to plot, e.g. "x ** 2 * y ** 2"', type=lambda s: eval('lambda x, y: {}'.format(s))) parser.add_argument('placevalue', type=int) parser.add_argument('width', type=int) parser.add_argument('height', type=int) args = parser.parse_args() print(placevalue_patterner(args.function, args.height, args.width, args.placevalue))
names = ['John', 'Kenny', 'Tom', 'Bob', 'Dilan'] ## CREATE YOUR FUNCTION HERE def sort_names(nombres): nombres.sort() return nombres print(sort_names(names))
""" https://onlinejudge.u-aizu.ac.jp/#/courses/lesson/1/ALDS1/11/ALDS1_11_C """ class Node(): def __init__(self, adjs=[], v=None): self.adjacents = adjs self.value = v self.visited = False self.distance = -1 class Graph(): def __init__(self, nodes=[]): #, head=None): self.head = None self.nodes = nodes def bfs(graph): queue = [] queue.append(graph.head) graph.head.distance = 0 graph.head.visited = True while len(queue) > 0: node = queue.pop(0) for idx in node.adjacents: child = graph.nodes[idx] if not child.visited: queue.append(child) child.distance = node.distance + 1 child.visited = True def main(): n = int(input()) graph = Graph(nodes=[None]*(n+1)) # THE 0th NODE IS DUMMY SINCE NODES ARE GIVEN WITH 1 ORIGIN for i in range(n): line = list(map(int, input().split())) node = Node(adjs=line[2:]) graph.nodes[i+1] = node graph.head = graph.nodes[1] bfs(graph) for i, node in enumerate(graph.nodes[1:]): print(i+1, node.distance) if __name__ == '__main__': main()
cadena = input("Introduce una cadena a comparar: ") cadena = cadena.lower() if cadena[0] == cadena[-1]: caracter_distintos = len(cadena) - cadena.count(cadena[0]) mensaje = f"La cadena introducida tiene {caracter_distintos} caracteres distintos a los de inicio y fin" else: caracteres_iguales_inicio = cadena.count(cadena[0]) - 1 caracteres_iguales_final = cadena.count(cadena[-1]) -1 caracteres_iguales_total = caracteres_iguales_inicio - caracteres_iguales_final mensaje = f"La cadena introducida tiene {caracteres_iguales_total} caracteres iguales" print(mensaje)
inicio = 1 final =1000 def isPrime(num): if (num < 1): return False elif (num == 2): return True else: for i in range(2,num): if (num%i == 0): return False return True for numero in range(inicio, final): if(isPrime(numero)): print(numero)
class Vehiculo: def __init__(self, CAR): print("Objeto vehiculo creado") self.__CAR = CAR self.__encendido = False # __ pone los atributos en privado e igual con las funciones. def __del__(self): print("Destruye el objeto", self.__CAR) def encender(self): self.__encendido = True def apagar(self): self.__encendido = False def estado(self): if self.__encendido: print("El coche está encendido") else: print("El coche está apagado") #Herencia class Electrico(Vehiculo): def __init__(self, CAR): super().__init__(CAR) self.__bateria = 0 def cargar(self): self.__bateria = 100 def descargar(self): self.__bateria = 0 def estadoBateria(self): print(f"Bateria {self.__bateria} %")
students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def names(arr): for elem in range(len(arr)): print arr[elem]["first_name"] + " " + arr[elem]["last_name"] names(students) users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } def usersII(obj): for key in obj: print key.upper() for i in range(len(obj[key])): print str(i) + " - " + obj[key][i]["first_name"].upper() + " " + obj[key][i]["last_name"].upper() + " - " + str(len(obj[key][i]["first_name"]) +len(obj[key][i]["last_name"])) usersII(users) # Pair Program: # Kennedy Dessousa # Kristeen Cal
import random def coinToss(num): recordList = [] heads = 0 tails = 0 count = 0 head_count = 0 tail_count = 0 for amount in range(num): flip = random.randint(0, 1) head_tail_str = "It's a head!" if flip == 0 else "It's a tail!" if (flip == 0): head_tail_str recordList.append("Heads") head_count = head_count + 1 else: head_tail_str recordList.append("Tails") tail_count = tail_count + 1 count = count + 1 print "Attempt #{}: Throwing a coin... {} ... Got {} head(s) so far and {} tail(s) so far".format(count, head_tail_str, head_count, tail_count) coinToss(15)
""" This script is a basic look at the lifecycle of a Python class. A python class has 4 main stages: 1. Definition 2. Initialization 3. Access and Manipulation 4. Destruction """ print('script start') class basic(): print('Stage 1: class definition start') prop1 = 1 def __init__(self): print('class basic __init__') self.prop2 = 2 def my_method(self): print('class basic my_method') return(self.prop1, self.prop2) @classmethod def cls_method(cls): print('class basic cls_method') return(cls.prop1) def __del__(self): print('class basic __del__') print('Stage 1: class definition end') print('class access and manipulation start') print(basic.prop1) print(basic.cls_method()) print('class access and manipulation end') print('Stage 2: object creation start') b = basic() c = basic() print('Stage 2: object creatin end') print('Stage 3: object access and manipulation start') print(b.my_method()) print(b.prop2) print(b.my_method()) print('Stage 3: object access and manipulation end') print('Stage 4: object destruction start') del(b) c = 12 print('Stage 4: object destruction end') print('script end')
"""Build a sentiment analysis / polarity model Sentiment analysis can be casted as a binary text classification problem, that is fitting a linear classifier on features extracted from the text of the user messages so as to guess wether the opinion of the author is positive or negative. In this examples we will use a movie review dataset. """ # Author: Olivier Grisel <[email protected]> # License: Simplified BSD import matplotlib.pyplot as plt import numpy as np import sys from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.svm import LinearSVC from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.datasets import load_files from sklearn.cross_validation import train_test_split from sklearn import metrics from sklearn.linear_model import SGDClassifier class ReturnValues(object): def __init__(self, y0, y1, y2, y3, y4, y5, y6, y7, y8, y9): self.y0 = y0 self.y1 = y1 self.y2 = y2 self.y3 = y3 self.y4 = y4 self.y5 = y5 self.y6 = y6 self.y7 = y7 self.y8 = y8 self.y9 = y9 def autolabel(rects): for rect in rects: h = rect.get_height() ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h), ha='center', va='bottom') def RunCompare(): if __name__ == "__main__": # NOTE: we put the following in a 'if __name__ == "__main__"' protected # block to be able to use a multi-core grid search that also works under # Windows, see: http://docs.python.org/library/multiprocessing.html#windows # The multiprocessing module is used as the backend of joblib.Parallel # that is used when n_jobs != 1 in GridSearchCV # the training data folder must be passed as first argument movie_reviews_data_folder = sys.argv[1] dataset = load_files(movie_reviews_data_folder, shuffle=False) print("n_samples: %d" % len(dataset.data)) # split the dataset in training and test set: docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.25, random_state=None) #print (docs_train) # TASK: Build a vectorizer / classifier pipeline that filters out tokens # that are too rare or too frequent # SGD Logistic MACHINES pipeline3 = Pipeline([ ('vect', TfidfVectorizer(min_df=1, max_df=0.95)), ('clf', SGDClassifier(loss='log')), ]) pipeline4 = Pipeline([ ('vect', TfidfVectorizer(min_df=2, max_df=0.95)), ('clf', SGDClassifier(loss='log')), ]) pipeline6 = Pipeline([ ('vect', TfidfVectorizer(min_df=3, max_df=0.95)), ('clf', SGDClassifier(loss='log')), ]) # SUPPORT VECTOR MACHINES pipeline = Pipeline([ ('vect', TfidfVectorizer(min_df=1, max_df=0.95)), ('clf', LinearSVC(C=1000)), ]) pipeline2 = Pipeline([ ('vect', TfidfVectorizer(min_df=2, max_df=0.95)), ('clf', LinearSVC(C=1000)), ]) pipeline5 = Pipeline([ ('vect', TfidfVectorizer(min_df=3, max_df=0.95)), ('clf', LinearSVC(C=1000)), ]) #print (pipeline) #NAIVE BAYES text_clf = Pipeline([('vect', TfidfVectorizer(min_df=1, max_df=0.95)), ('clf', MultinomialNB()), ]) text_clf2 = Pipeline([('vect', TfidfVectorizer(min_df=2, max_df=0.95)), ('clf', MultinomialNB()), ]) text_clf3 = Pipeline([('vect', TfidfVectorizer(min_df=3, max_df=0.95)), ('clf', MultinomialNB()), ]) # TASK: Build a grid search to find out whether unigrams or bigrams are # more useful. # Fit the pipeline on the training set using grid search for the parameters parameters = {'vect__ngram_range': [(1, 1), (1, 2)], } parameters2 = {'vect__ngram_range': [(1, 1), (1, 2)], 'clf__alpha': (1e-2, 1e-3), } parameters3 = {'vect__ngram_range': ((1, 1), (1, 2)), #bigrams 'clf__alpha': (1e-2, 1e-3), #'clf__alpha': (0.00001, 0.000001), } #Linear SVM with tf=1,2,3 grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1) grid_search2 = GridSearchCV(pipeline2, parameters, n_jobs=-1) grid_search3 = GridSearchCV(pipeline5, parameters, n_jobs=-1) #Multinomial NB with tf=1,2,3 gs_clf = GridSearchCV(text_clf, parameters2, n_jobs=-1) gs_clf2 = GridSearchCV(text_clf2, parameters2, n_jobs=-1) gs_clf3 = GridSearchCV(text_clf3, parameters2, n_jobs=-1) #SGD Log Reg with tf=1,2,3 grid_classification=GridSearchCV(pipeline3, parameters3, n_jobs=-1) grid_classification2=GridSearchCV(pipeline4, parameters3, n_jobs=-1) grid_classification3=GridSearchCV(pipeline6, parameters3, n_jobs=-1) #TF-1 grid_search.fit(docs_train, y_train) gs_clf.fit(docs_train, y_train) grid_classification.fit(docs_train,y_train) #TF-2 grid_search2.fit(docs_train, y_train) gs_clf2.fit(docs_train, y_train) grid_classification2.fit(docs_train,y_train) #TF-3 grid_search3.fit(docs_train, y_train) gs_clf3.fit(docs_train, y_train) grid_classification3.fit(docs_train,y_train) # TASK: print the cross-validated scores for the each parameters set # explored by the grid search print(grid_search.grid_scores_) print (gs_clf.grid_scores_) print (grid_classification.grid_scores_) #print (grid_classification.grid_scores_) # TASK: Predict the outcome on the testing set and store it in a variable # named y_predicted #TF-1 y_predicted = grid_search.predict(docs_test) y_predicted2=gs_clf.predict(docs_test) y_predicted3=grid_classification.predict(docs_test) #TF-2 y_predicted4 = grid_search2.predict(docs_test) y_predicted5=gs_clf2.predict(docs_test) y_predicted6=grid_classification2.predict(docs_test) #TF-3 y_predicted7 = grid_search3.predict(docs_test) y_predicted8=gs_clf3.predict(docs_test) y_predicted9=grid_classification3.predict(docs_test) # Print the classification report #Linear SVM 1,2,3 print(metrics.classification_report(y_test, y_predicted, target_names=dataset.target_names)) print(metrics.classification_report(y_test, y_predicted4, target_names=dataset.target_names)) print(metrics.classification_report(y_test, y_predicted7, target_names=dataset.target_names)) ErrorProtect = y_test Lin1 = y_predicted Lin2 = y_predicted4 Lin3 = y_predicted7 #Multinomail NB 1,2,3 print(metrics.classification_report(y_test, y_predicted2, target_names=dataset.target_names)) print(metrics.classification_report(y_test, y_predicted5, target_names=dataset.target_names)) print(metrics.classification_report(y_test, y_predicted8, target_names=dataset.target_names)) NB1 = y_predicted2 NB2 = y_predicted5 NB3 = y_predicted8 #SGD Log Reg 1,2,3 print(metrics.classification_report(y_test, y_predicted3, target_names=dataset.target_names)) print(metrics.classification_report(y_test, y_predicted6, target_names=dataset.target_names)) print(metrics.classification_report(y_test, y_predicted9, target_names=dataset.target_names)) SGD1 = y_predicted3 SGD2 = y_predicted6 SGD3 = y_predicted9 # Print and plot the confusion matrix cm = metrics.confusion_matrix(y_test, y_predicted) print("Linear SVM-1:", cm) cm4 = metrics.confusion_matrix(y_test, y_predicted4) print("Linear SVM-2:", cm4) cm7 = metrics.confusion_matrix(y_test, y_predicted7) print("Linear SVM-3:", cm7) cm2 = metrics.confusion_matrix(y_test, y_predicted2) print("MultinomialNB-1:", cm2) cm5 = metrics.confusion_matrix(y_test, y_predicted5) print("MultinomialNB-2:", cm5) cm8 = metrics.confusion_matrix(y_test, y_predicted8) print("MultinomialNB-3:", cm8) cm3 = metrics.confusion_matrix(y_test, y_predicted3) print("SGD LG-1:", cm3) cm6 = metrics.confusion_matrix(y_test, y_predicted6) print("SGD LG-2:", cm6) cm9 = metrics.confusion_matrix(y_test, y_predicted9) print("SGD LG-3:", cm9) return ReturnValues(ErrorProtect,Lin1, Lin2, Lin3, NB1, NB2, NB3, SGD1, SGD2, SGD3) # Create the Graphs if __name__ == "__main__": HistogramData = [] Result = [] Result2 = [] Result3 = [] Result4 = [] Result5 = [] Result6 = [] Result7 = [] Result8 = [] Result9 = [] Average = 10 for i in range(0,Average): HistogramData.append(RunCompare()) for i in range(0,Average): if HistogramData[i] != None: print("\n") print("\n") TestValues = HistogramData[i].y0 Lin1 = HistogramData[i].y1 Lin2 = HistogramData[i].y2 Lin3 = HistogramData[i].y3 NB1 = HistogramData[i].y4 NB2 = HistogramData[i].y5 NB3 = HistogramData[i].y6 SGD1 = HistogramData[i].y7 SGD2 = HistogramData[i].y8 SGD3 = HistogramData[i].y9 NumValues = len(TestValues) Count = 0 Count2 = 0 Count3 = 0 Count4 = 0 Count5 = 0 Count6 = 0 Count7 = 0 Count8 = 0 Count9 = 0 for i in range(0,NumValues): if TestValues[i] == Lin1[i] : Count = Count + 1 if TestValues[i] == Lin2[i]: Count2 = Count2 + 1 if TestValues[i] == Lin3[i]: Count3 = Count3 + 1 if TestValues[i] == NB1[i]: Count4 = Count4 + 1 if TestValues[i] == NB2[i]: Count5 = Count5 + 1 if TestValues[i] == NB3[i]: Count6 = Count6 + 1 if TestValues[i] == SGD1[i]: Count7 = Count7 + 1 if TestValues[i] == SGD2[i]: Count8 = Count8 + 1 if TestValues[i] == SGD3[i]: Count9 = Count9 + 1 Result.append(Count/float(NumValues)) Result2.append(Count2/float(NumValues)) Result3.append(Count3/float(NumValues)) Result4.append(Count4/float(NumValues)) Result5.append(Count5/float(NumValues)) Result6.append(Count6/float(NumValues)) Result7.append(Count6/float(NumValues)) Result8.append(Count6/float(NumValues)) Result9.append(Count6/float(NumValues)) Count = 0 Count2 = 0 Count3 = 0 Count4 = 0 Count5 = 0 Count6 = 0 Count7 = 0 Count8 = 0 Count9 = 0 print(Result) print(Result2) print(Result3) print(Result4) print(Result5) print(Result6) print(Result7) print(Result8) print(Result9) for i in range(0,Average): Count = Count + Result[i] Count2 = Count2 + Result2[i] Count3 = Count3 + Result3[i] Count4 = Count4 + Result4[i] Count5 = Count5 + Result5[i] Count6 = Count6 + Result6[i] Count7 = Count7 + Result7[i] Count8 = Count8 + Result8[i] Count9 = Count9 + Result9[i] Count = Count/10.0 Count2 = Count2/10.0 Count3 = Count3/10.0 Count4 = Count4/10.0 Count5 = Count5/10.0 Count6 = Count6/10.0 Count7 = Count7/10.0 Count8 = Count8/10.0 Count9 = Count9/10.0 N = 3 ind = np.arange(N) width = 0.27 fig = plt.figure() ax = fig.add_subplot(111) TimesFound1 = [Count, Count4, Count7] TimesFound2 = [Count2, Count5, Count8] TimesFound3 = [Count3, Count6, Count9] TF1 = ax.bar(ind, TimesFound1, width, color='b', align = 'center') TF2 = ax.bar(ind+width, TimesFound2, width, color = 'r', align = 'center') TF3 = ax.bar(ind+width*2, TimesFound3, width, color = 'k', align = 'center') ax.set_xticks(ind) ax.set_xticklabels( ('Linear SVM', 'Naive Bayes', 'SGD LR') ) ax.legend( (TF1[0], TF2[0], TF3[0]), ('TF = 1', 'TF = 2', 'TF = 3') ) plt.grid(True) plt.ylabel("Accuracy Percentage") plt.xlabel("Sentiment Analysis Methods") plt.title("Comparison of Accuracy between Sentiment Analysis Methods \n on Movie Review Data for different values of TF") autolabel(TF1) autolabel(TF2) autolabel(TF3) plt.show()
#! /usr/bin/python import random my_list = list(range(26)) print my_list print random.choice(my_list) print random.choice([(0,1), (2,3), (4,5), (6,7),(8,9)]) my_int = 4 my_iter = list(range(10)) def nchoices(my_iter, my_int): ran_list = [] i = 0 while i < my_int: ran_list.append(random.choice(my_iter)) i += 1 return ran_list print nchoices(my_iter, my_int)
#!/usr/bin/env python my_string = "Hello there" print my_string[1:5] #returns ello print my_string[2] my_list = list(range(1,6)) print my_list print my_list[1:3] print my_list[1:len(my_list)] # the list has 5 items we need to use 4 # leave off the first number, we start at 0 # leave off the last number, we go to the end # [:] returns all of my list my_new_list = [4,2,3,1,5] my_sorted_list = my_new_list[:] #way to copy a list so you can keep the original print my_new_list print my_sorted_list print sorted(my_sorted_list) #returns my_sorted_list, but sorted new_list = list(range(20)) # creates a list with a range from 0 - 19 print new_list print new_list[::2] # go from beginning to end and add two at each time print new_list[2::2] # starts at index 2 and moves two at a time print "Nebraska"[::-1] # reverses the string by starting at the back instead of the front print new_list[::-1] print new_list[::-2] # returns the list backwards moving two at a time print new_list[2:8:-1] # wont work because we start at 2 and count backwards print new_list[8:2:-1] # says start at 8 and work your way back one at a time until reach two print new_list[7-1] # starts at 7 and works down to 2
#!/usr/bin/env python #Collections are variable types that collect bits of data together aka interables #strings and lists aList = [1,2,3] aList.append([4,5]) #returns[1,2,3[4,5]] print aList # range method our_list= list(range(10)) #returns 0-9 print our_list print our_list + [10,11,12] #returns 0-12 print our_list #why does this show our_list as 0-9 after adding the other list??? our_list = our_list + [10,11,12] print our_list list_1 = ["Dogs","Cats","Snakes"] list_2 = ["Ferrets","Mice","Rats"] list_3 = list_1 + list_2 print list_3 # .extend() # .insert() our_list.extend(range(13,21)) #returns the updated list between 0 and 20 print our_list alpha = list("acdf") #notice that alpha takes a string but returns a list print alpha alpha.insert(1, 'b') print alpha alpha.insert(4, 'e') print alpha
#! /usr/bin/python import random COLORS = ['yellow','blue','red','green','orange'] class Monster(object): min_hit_pts = 1 max_hit_pts = 1 min_experience = 1 max_experience = 1 weapon = 'sword' sound = 'snort' def __init__(self, **kwargs): self.hit_points = random.randint(self.min_hit_pts, self.max_hit_pts) self.experience = random.randint(self.min_experience, self.max_experience) self.color = random.choice(COLORS) for key, value in kwargs.items(): setattr(self, key, value) def battlecry(self): return self.sound.upper() #Goblin subclass of Monster or it extends monster. class Goblin(Monster): max_hit_pts = 3 max_experience = 2 pass
#imports the ability to get a random number (we will learn more about this later!) from random import * #Create the list of words you want to choose from. first = ['Jason', 'Alison', 'Tim','Abcde', 'Luna','Harry','John' ,'Gabriel'] last = ['Todd', 'Nikols','Lovegood','Morozov','Reyes','Malfoy','Amari'] #Generates a random integer. randofirst = randint(0, len(first)-1) randolast = randint(0, len(last)-1) print(first[randofirst] + ' ' + last[randolast])
"""Restaurant rating lister.""" import sys def import_file(file_name): """Return file object""" restaurant_ratings = open(file_name) return restaurant_ratings file_name = import_file(sys.argv[1]) def adding_to_restaurants_dict(file_name): """Adding restaurant names to dictionary""" reviews = {} for rating in file_name: rating = rating.rstrip() name, score = rating.split(":") reviews[name] = score return reviews dictionary_reviews = adding_to_restaurants_dict(file_name) def add_user_restaurant_score(reviews): """Returns dictionary with user input""" new_restaurant_name = raw_input("Enter a restaurant name: ") new_score = raw_input("Enter " + new_restaurant_name + "'s rating: ") reviews[new_restaurant_name] = new_score return reviews user_restaurants = add_user_restaurant_score(dictionary_reviews) def sorting_restaurants(reviews): """Prints sorted dictionary""" sorted_reviews = sorted(reviews.items()) for restaurant_name, score in sorted_reviews: print "{} is rated at {}".format(restaurant_name, score) sorting_restaurants(user_restaurants)
import os # operating system, "os"為"標準函式庫"裡面就有的東西可以直接import進來"這個模組" # Refactor 重構, 重新把架構都寫成funcion, 和有一個main() function程式的進入點 # 讀取檔案 def read_file(filename): # 把檔名設成參數比較靈活, 可讀別的檔案 products = [] # 先創一個空清單 with open(filename, 'r', encoding = 'utf-8') as f: #之前寫得檔案用utf-8寫, 所以讀取也要用utf-8才讀的到 for line in f: # 讀取檔案f, 會一行一行讀取, 把暫時變數稱作"line"(任意名稱都可) if '商品,價格' in line: continue # 功能是"直接跳到下一迴"然後繼續 ; break是直接跳出迴圈 name, price = line.strip().split(',') # 先strip掉換行符號\n, 再用','去切割 # 由左至右: line先strip()在split() # split()這個函式可以用來切割東西 # split()裡面填"字串", 則依照"填的那個字串"做切割 # split()切割完的結果是"清單" # 因為已經知道切完的結果會有"左右兩塊"(去看讀取的檔案就知), 所以等號左邊的暫時變數可以這樣設定" name, price " # strip()可以把換行符號(\n)、空白去掉 products.append([name, price]) return products #讀完資料要回傳products # 讓使用者輸入 def user_input(products): while True: name = input('請輸入商品名稱: ') if name == 'q': #quite break price = input('請輸入商品價格: ') # 放在break下面是因為在商品名稱輸入"q"之後就要跳出迴圈了, 不用再問價格 products.append([name, price]) print(products) return products # 印出所有購買紀錄 def print_products(products): for p in products: print(p[0], '的價格是', p[1]) # note1: 'abc' + '123' = 'abc123' # note2: 'abc' * 3 = 'abcabcabc' #寫入檔案 def write_file(filename, products): with open(filename, 'w', encoding = 'utf-8') as f: # 電腦原先如果沒有products.txt就會產生此檔案, 有的話會覆蓋掉舊檔案 # 明確告訴電腦要用"utf-8"這個編碼就要加encoding = 'utf-8', 這樣如果要寫入中文比較不會出錯 # 這邊也要注意一下讀取檔案的程式也是要用'utf-8'編碼讀取才不會發生錯誤 f.write('商品,價格\n') for p in products: f.write(p[0] + ',' + p[1] + '\n') # 這一行才是真正的開始寫入 # 要把把資料寫入檔案f就要這樣寫: f.write() # \n是"換行符號" def main(): products = [] # 加這個很重要, 如果一開始沒檔案走到else印完'找不到檔案.....'之後的"products = user_input(products)"裡面會有一段"products.append([name, price])"就會根本不知道要append到哪裡(因為根本還沒有"product這個清單"可以append) filename = 'products.csv' if os.path.isfile(filename): # 檢查檔案在不在 # os這個模組裡面"的"path模組裡面"的"isfile()這個功能 的意思 # isfile()這個功能可以檢查檔案在不在 # isfile('products.csv')這個寫法可確定在跟"這個pythont程式"相同資料夾內有沒有要找的那個檔案(相對路徑) # isfile()如果要確定別的地方的檔案在不在, 就要填"絕對路徑" print('yeah! 找到檔案了!') products = read_file(filename) print(products) else: print('找不到檔案.....') products = user_input(products) print_products(products) write_file('products.csv', products) main()
filename = open('words.txt', 'r') lst = list(filename) myword = 'silver' for n in range(len(lst)): diff = 0 for i in range(6): if lst[n][i] != myword[i]: diff = diff + 1 if diff == 1: print(lst[n]) ''' def main(): word = "wallet" parent = "XXXXX" print(neighbors(word, parent)) def neighbors(myword, parent): outerlst = [] temp = [] for n in range(len(lst)): diff = 0 for i in range(6): if lst[n][i] != myword[i]: diff = diff + 1 if diff == 1: temp.append(lst[n]) temp.sort() outerlst.append(temp) if myword != parent: outerlst.append(-1) outerlst.append("?") else: outerlst.append("0") outerlst.append("head") return outerlst main() '''
def setUpCanvas(root): root.title("Wolfram's cellular automata: A Tk/Python Graphics Program") canvas = Canvas(root, width = 1270, height = 780, bg = 'black') canvas.pack(expand = YES, fill = BOTH) return canvas def displayStatistics(): print('RUN TIME = %6.2F'% round(clock()-START_TIME, 2), 'seconds.') root.title('THE FRACTAL FLOWER IS COMPLETE.') def frange(start, stop, step): i = start while i < stop: yield i i+= step def line(x1, y1, x2, y2, kolor = 'WHITE', width = 1): #you need to place a for loop in this function canvas.create_line(x1, y1, x2, y2, width = width, fill = kolor) def drawFlower(cx, cy, radius): #make this recursive #base case if radius < 3: return #set color kolor = 'GREEN' width = 2 if radius <240: kolor = 'WHITE' width = 1 if radius < 10: kolor = 'RED' width = 1 #draw flower for t in frange(0, 6.28, 0.9): cx1 = cx cy1 = cy for k in range(7): if random() < 0.2: t+=0.2 else: t-=0.2 x = cx1 + radius/7*sin(t) y = cy1 + radius/7*cos(t) line(cx1, cy1, x, y, kolor, width) cx1 = x cy1 = y drawFlower(x, y, radius/3) canvas.update() from tkinter import Tk, Canvas, BOTH, YES from math import sin, cos, atan2, pi, hypot from random import random from time import clock root = Tk() canvas = setUpCanvas(root) WIDTH = root.winfo_screenwidth() HEIGHT = root.winfo_screenheight() START_TIME = clock() def main(): drawFlower(WIDTH/2, HEIGHT/2-50, 240) displayStatistics() canvas.update() root.mainloop() if __name__ == '__main__': main()
def diamond(height): """Return a string resembling a diamond of specified height (measured in lines). height must be an even integer. """ outStr = "" for i in range(1, height//2+1,1): tmpStr = "/"*i + "\\"*i outStr += tmpStr.center(height) + "\n" for i in range(height//2, 0, -1): tmpStr = "\\"*i + "/"*i outStr += tmpStr.center(height) + "\n" return outStr[:-1]
""" Exercise 4 """ import hashlib def genpasswd(password): """ Accepts a password and generate new one """ sha1 = hashlib.sha1(password.encode('utf-8')) hashstring = sha1.hexdigest() return hashstring[:6] def findcollision(x0): """ Finds two input passwords which give the same output from genpasswd """ (x1, x2) = (genpasswd(x0), genpasswd(genpasswd(x0))) i = 1 while x1 != x2: i = i + 1 x1 = genpasswd(x1) x2 = genpasswd(genpasswd(x2)) x2 = x1 x1 = x0 for j in range(i): if genpasswd(x1) == genpasswd(x2): print("genpasswd({}) = genpasswd({}) = {}".format(x1, x2, genpasswd(x1))) return (x1, x2) x1 = genpasswd(x1) x2 = genpasswd(x2) print("fail") def main(): """ The main method """ passwords = "q1dff2" (x1, x2) = findcollision(passwords) if __name__ == "__main__": main()
# Define a class which has at least two methods: # getString: to get a string from console input # printString: to print the string in upper case. # Also please include simple test function to test the class methods. import unittest class String(): def _init_(self): self.str1 = "" def get_String(self): self.str1 = input('Enter a string: ') def print_String(self): print(self.str1.upper()) str1 = String() str1.get_String() str1.print_String()
#!/usr/bin/env python # coding: utf-8 # In[1]: # start's with a string before = "This is the euro symbol: €" type(before) # In[2]: import numpy as np import pandas as pd # In[3]: # encode it to a different encoding, replacing characters that raise errors after = before.encode('utf-8', errors='replace') type(after) # In[4]: after # In[5]: # converting it back to utf-8 print(after.decode('utf-8')) # In[6]: print(after.decode('ascii')) # In[7]: before = "This is the euro symbol: €" after = before.encode('ascii',errors= 'replace') print(after.decode('ascii')) # # Reading file with encoding problems # In[8]: import os os.chdir('D:/python using jupyter/Data Preprocessing') kickstarter_2016 = pd.read_csv('ks-projects-201612.csv') # In[12]: import chardet with open('ks-projects-201612.csv','rb') as rawdata: result = chardet.detect(rawdata.read(10000)) print(result) # In[13]: # as it is given in the form of 'Windows-1252' with confidence given 0.73 kickstarter_2016 = pd.read_csv('ks-projects-201612.csv',encoding='Windows-1252') # In[14]: kickstarter_2016.head(5) # In[ ]: # hence now it is reading properly
a = int(input("enter a number: ")) if a > 0 : print (a) else : print(-a)
# example 3 # 2*x**2+6*x-20 a = 2 b = 6 c = -20 delta = b ** 2 - 4 * a * c roots1 = (-b - delta ** 0.5) / (2 * a) roots2 = (-b + delta ** 0.5) / (2 * a) print ("roots1:", roots1) print ("roots2:", roots2)
# example 4 celcius = float(input("temperature value : ", )) fahrenheit = celcius * 1.8 + 32 print (fahrenheit)
# for i in range(100): # print(i) # range() 函数可创建一个整数列表,一般用在 for 循环中。 # start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5 # stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5 # step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1) for_list = ['a', 'b'] for a in for_list: print(a) data = [6, 3, 7, 9, 1, 3, 5] # data.sort() data2 = sorted(data) # sort 与 sorted 区别: # sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。 # list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值, # 而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。 print(data) print(data2)
######################################################################## ## ## CS 101 Lab ## Program # ## Name ## Email ## ## PROBLEM : Describe the problem ## ## ALGORITHM : ## 1. Write out the algorithm ## ## ERROR HANDLING: ## Any Special Error handling to be noted. Wager not less than 0. etc ## ## OTHER COMMENTS: ## Any special comments ## ######################################################################## #import modules needed import random def play_again() -> bool: ''' Asks the user if they want to play again, returns False if N or NO, and True if Y or YES. Keeps asking until they respond yes ''' again = input('Do you want to play again? Y/Yes/N/No') if(again.upper() == "Y" or again.upper() == "YES"): return True elif(again.upper() == "N" or again.upper() == "NO"): return False else: print("Please enter a correct value") play_again() def get_wager(bank : int) -> int: ''' Asks the user for a wager chip amount. Continues to ask if they result is <= 0 or greater than the amount they have ''' while(True): wager = int(input('How many chips do you want to wager? ==>')) if(wager < 1): print('The wager amount must be greater than 0. Please enter again') elif(wager > bank): print('The wager amount cannot be greater than how much you have') elif(wager <= bank) or (wager > 0): break else: print('incorrect input please enter a number') return wager def get_slot_results() -> tuple: ''' Returns the result of the slot pull ''' reel1 = random.randint(1, 10) reel2 = random.randint(1, 10) reel3 = random.randint(1, 10) return (reel1, reel2, reel3) def get_matches(reela, reelb, reelc) -> int: ''' Returns 3 for all 3 match, 2 for 2 alike, and 0 for none alike. ''' if reela == reelb == reelc: return 3 elif (reela == reelb) or (reela == reelc) or (reelb == reelc): return 2 else: return 0 def get_bank() -> int: ''' Returns how many chips the user wants to play with. Loops until a value greater than 0 and less than 101 ''' while(True): chips = int(input('How many chips do you want to start with? ==>')) if(chips < 1): print('Too Low a value, you can only choose 1 - 100 chips') elif(chips > 101): print('Too High a value, you can only choose 1 - 100 chips') elif(chips <= 101) or (chips > 1): break else: print('incorrect input please enter a proper input') return chips def get_payout(wager, matches): ''' Returns how much the payout is.. 10 times the wager if 3 matched, 3 times the wager if 2 match, and negative wager if 0 match ''' if(matches == 3): return wager * 10 if(matches == 2): return wager * 3 if(matches == 0): return wager * -1 else: return 0 if __name__ == "__main__": playing = True while playing: bank = get_bank() while bank > 0: wager = get_wager(bank) reel1, reel2, reel3 = get_slot_results() matches = get_matches(reel1, reel2, reel3) payout = get_payout(wager, matches) bank = bank + payout print("Your spin", reel1, reel2, reel3) print("You matched", matches, "reels") print("You won/lost", payout) print("Current bank", bank) print() print("You lost all", 0, "in", 0, "spins") print("The most chips you had was", 0) playing = play_again()
name = input("Hello Human what is your name? > ") print(f"Hell {name}, nice to meet you")
import unittest #You need this module import ordinal_drm #This is the script you want to test class ordinal_drm_test(unittest.TestCase): def identical_test(self): self.assertEqual("1st", myscript.myfunction(1)) self.assertEqual("2nd", myscript.myfunction(2)) self.assertEqual("3rd", myscript.myfunction(3)) self.assertEqual("8th", myscript.myfunction(8)) self.assertEqual("11th", myscript.myfunction(11)) self.assertEqual("12th", myscript.myfunction(12)) self.assertEqual("13th", myscript.myfunction(13)) self.assertEqual("18th", myscript.myfunction(18)) self.assertEqual("21st", myscript.myfunction(21)) self.assertEqual("22nd", myscript.myfunction(22)) self.assertEqual("23rd", myscript.myfunction(23)) self.assertEqual("28th", myscript.myfunction(28)) def not_identical_test(self): thing1=myscript.myfunction(1) thing2=myscript.myfunction(10) self.assertNotEqual(thing1, thing2) def integer_test(self): self.assertEqual("Must enter an integer!", myscript.myfunction("three")) self.assertEqual("Must enter an integer!", myscript.myfunction("third")) self.assertEqual("Must enter an integer to produce ordinal!", myscript.myfunction("3rd")) if __name__ == '__main__': #Add this if you want to run the test with this script. unittest.main()
class Clock(object): def __init__(self, hour, minutes): self.minutes = minutes self.hour = hour @classmethod def at(cls, hour, minutes=0): return cls(hour, minutes) def __str__(self): return "The time is %s hours and %s minutes" % (self.hour, self.minutes) def __add__(self,minutes): selfTime = self.hour * 60 + self.minutes newMinutes = selfTime + minutes self.hour = newMinutes / 60 if self.hour >23: self.hour = self.hour -24 if self.hour <0: self.hour +24 self.minutes = newMinutes % 60 def __sub__(self,minutes): selfTime = self.hour * 60 + self.minutes newMinutes = selfTime - minutes self.hour = newMinutes / 60 if self.hour >23: self.hour -24 if self.hour <0: self.hour +24 self.minutes = newMinutes % 60 def __eq__(self, other): return self.hour == other.hour and self.minutes == other.minutes def __ne__(self, other): return self.hour != other.hour or self.minutes != other.minutes
#control flow #how to take input from a user #multiple input - loops var= input("how many apples") print(var) name= input("what is your name") print(" hello" + name) num= input() #control flow includes---- # if statement #elif statement #else statement #example- grade='a' if grade=='A' : print("very good") elif grade=='B': # you can say else if print('good') else : print('you can do better')
userinput = input('Put in a phrase which you want converted into an acronym. ') listt = userinput.split() acronym = '' for i in listt: acronym = acronym + i[0].upper() print (acronym)
# Nama: Zaid # NIM: 0110220085 # Kelas: TI 03 def jumlah_batas(nums, batas): # Tulis kode fungsi jumlah_batas() di bawah ini # Hapus pass jika implementasi sudah dibuat jumlah = 0 for i in range(len(nums)): if nums[i] > batas: jumlah += nums[i] return jumlah def list_nonvokal(s): # Tulis kode fungsi list_nonvokal() di bawah ini # Hapus pass jika implementasi sudah dibuat huruf='aAiIeEeoOuU' nonvokal=[] for i in s: if i not in huruf: nonvokal += i return nonvokal def list_modify(alist, command, position, value=None): # Tulis kode fungsi list_modify() di bawah ini # Hapus pass jika implementasi sudah dibuat pass # Mulai baris ini hingga baris paling bawah # digunakan untuk mengetes fungsi yang telah dibuat. # Tidak perlu mengubah bagian ini. # Ketika dijalankan, program akan menampilkan contoh # pemanggilan fungsi dan solusi yang seharusnya. # Cocokkan hasil pemanggilan fungsi dengan solusi # yang seharusnya. def test(): r = jumlah_batas([8, 7, 6, 10, 1], 5) print(f"jumlah_batas([8, 7, 6, 10, 1], 5) = {r} \n(solusi: 31)") print() r = jumlah_batas([1, -7, -10, 1], -5) print(f"jumlah_batas([1, -7, -10, 1], -5) = {r} \n(solusi: 2)") print() r = list_nonvokal('Halo') print(f"list_nonvokal('Halo') = {r} \n(solusi: ['H', 'l'])") print() r = list_nonvokal('AAAAAooooo') print(f"list_nonvokal('AAAAAooooo') = {r} \n(solusi: [])") print() r = list_nonvokal('Saya cinta programming') print(f"list_nonvokal('Saya cinta programming') = {r} \n(solusi: ['S', 'y', ' ', 'c', 'n', 't', ' ', 'p', 'r', 'g', 'r', 'm', 'm', 'n', 'g'])") print() r = list_modify(['ayam', 'ikan', 'kucing'], 'add', 'start', 'bebek') print(f"list_modify(['ayam', 'ikan', 'kucing'], 'add', 'start', 'bebek') = {r} \n(solusi: ['bebek', 'ayam', 'ikan', 'kucing'])") print() r = list_modify(['ayam', 'ikan', 'kucing'], 'add', 'end', 'bebek') print(f"list_modify(['ayam', 'ikan', 'kucing'], 'add', 'end', 'bebek') = {r} \n(solusi: ['ayam', 'ikan', 'kucing', 'bebek'])") print() r = list_modify(['ayam', 'ikan', 'kucing'], 'remove', 'start') print(f"list_modify(['ayam', 'ikan', 'kucing'], 'remove', 'start') = {r} \n(solusi: ['ikan', 'kucing'])") print() r = list_modify(['ayam', 'ikan', 'kucing'], 'remove', 'end') print(f"list_modify(['ayam', 'ikan', 'kucing'], 'remove', 'end') = {r} \n(solusi: ['ayam', 'ikan'])") print() if __name__ == '__main__': test()
PI = 3.14 radius = float(input('반지름을 입력하세요: ')) def circle_area_circum(radius): area = PI * (radius ** 2) length = 2 * PI * radius return '원의 면적은 {}, 원의 둘레는 {} 입니다.' .format(area,length) print(circle_area_circum(radius))
""" CP5632 Practical 4 Warm-up with Lists """ numbers = [3, 1, 4, 1, 5, 9, 2] numbers[0] # 3 numbers[-1] # 2 numbers[3] # 1 numbers[:-1] # [3, 1, 4, 1, 5, 9] numbers[3:4] # [1] 5 in numbers # True 7 in numbers # False "3" in numbers # False numbers + [6, 5, 3] # [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] # Change the first element of numbers to "ten" (the string, not the number 10) numbers[0] = "ten" # Change the last element of numbers to 1 numbers[-1] = 1 # Get all the elements from numbers except the first two (slice) numbers[2:] # Check if 9 is an element of numbers 9 in numbers
""" CP5632 Practical 3 Program to get password from user and display it as asterisks """ def main(): password = get_password() display_asterisks(password) def display_asterisks(password): """Replace password characters with asterisks""" for i in range(0, len(password)): print("*", end="") def get_password(): """Validate password given by user""" password = input("Enter your password: ") while len(password) < 6: print("Password must have 6 or more characters") password = input("Enter your password: ") return password main()
""" CP5632 Practical 5 Program to count word occurences in a string provided by the user """ def main(): word_counts = {} text_input = input("Text: ").lower() word_list = text_input.split() for word in word_list: if word not in word_counts: word_count = word_list.count(word) word_counts[word] = word_count word_list = list(word_counts.keys()) word_list.sort() for word in word_list: print("{:{}} : {}".format(word, len(max(word_list, key=len)), word_counts[word])) main()
""" CP5632 Practical 5 Program to get names and emails from the user and add them to dictionary """ def main(): email_collection = {} email = input("Email: ") while email != "": parts = (email.split("@")[0].split(".")) name = " ".join(parts).title() verify_name = input("Is your name {}? (y/n) ".format(name)).lower() if verify_name == "n": name = input("Name: ") email_collection[name] = email email = input("Email: ") print() for name, email in email_collection.items(): print("{} ({})".format(name, email)) main()
"""CP5632 Practical 6 - Client code for Guitar class""" from prac_06.guitar import Guitar def main(): """Code to add guitars from user to a list and display the result""" print("My guitars!") guitars = [] is_loop_running = True while is_loop_running: name = input("\nName: ") year = input("Year: ") cost = input("Cost: $") guitar = Guitar(name, year, cost) guitars.append(guitar) print(guitar, " added") add_another = input("\nDo you want to add another guitar? (y/n) ").lower() if add_another == "n": is_loop_running = False print("\nThese are my guitars:") for i, guitar in enumerate(guitars, 1): print("Guitar {}: {} ({}), worth $ {:,.2f} {}". format(i, guitar.name, guitar.year, guitar.cost, "(vintage)" if guitar.is_vintage() else "")) main()
import os import pandas as pd import numpy as np import random import time #this method is meant to process the iris.csv data & get it ready for machine learning def process(): #reading the data os.chdir("/Users/64000340/Desktop/iris-species") df = pd.read_csv("Iris.csv") k = 3 #number of classes #assigning discrete values to the type of plant transformed = [] transformer = {"Iris-setosa": 0, "Iris-virginica": 1, "Iris-versicolor": 2} for index in list(df["Species"]): transformed.append(transformer.get(index)) #appending the new discrete value column into the dataframe df['species_value'] = transformed df = df.drop('Species', axis = 1) #getting means & standard deviations ready for feature scaling tb = df.describe() means = [] stds = [] for col in tb.columns: means.append(round(tb[col][1], 2)) stds.append(round(tb[col][2], 2)) #used to indicate which values can be scaled. ''' In order to be scaled, the feature must be a continuous or quantitative variable like Height & so forth. The indicator dictionary tells the function feature scale what each variable is. C = Categorical, and Q = Quantitative ''' indicator = {'Id': "C", 'SepalLengthCm' : "Q", 'SepalWidthCm': 'Q' , 'PetalLengthCm' : "Q", 'PetalWidthCm' : "Q", 'species_value' : 'C'} df_scaled = featureScale(means, stds, df, indicator) answers = list(df['species_value']) df_scaled = df_scaled.drop('species_value', 1) X, Y = convert_to_np(df, answers, k) X_train, Y_train, X_CV, Y_CV, X_test, Y_test = give_train_cv_test(X, Y) os.chdir("/Users/64000340/PycharmProjects/Iris") #creating new files with the training, cv, and test data with open("Train/X_train.mat", 'w') as f: np.savetxt(f, X_train) with open("Train/Y_train.mat", 'w') as f: np.savetxt(f, Y_train) with open("CV/X_CV.mat", 'w') as f: np.savetxt(f,X_CV ) with open("CV/Y_CV.mat", 'w') as f: np.savetxt(f, Y_CV) with open("Test/X_test.mat", 'w') as f: np.savetxt(f, X_test ) with open("Test/Y_test.mat", 'w') as f: np.savetxt(f, Y_test) ''' The Function below will alter the original dataframe ''' #returns the dataframe after it has been scaled def featureScale(means, stds, df, indicator): temp_df = df colIndex = 0 #iterating over columns to check the type of variable the column is for col in df.columns: if(indicator.get(col) == 'C'): print(col, "is a categorical variable") else: for i in range(len(list(df[col]))): #subtracting by the mean & finding the z-score temp_df[col][i] -= means[colIndex] temp_df[col][i] /= stds[colIndex] colIndex+=1 return df #creates a one hot vector for answer labels & converts all data into numpy def convert_to_np(df, answers, k): #getting the label into a one hot vector Y = np.zeros((1, k)) for val in answers: list = [0] * 3 list[val] = 1 Y = np.vstack((np.array(list), Y)) Y = Y[:np.shape(Y)[0] - 1] return df.values, Y #returns def give_train_cv_test(X, Y): X_train = np.zeros((1, np.shape(X)[1])) Y_train = np.zeros((1, np.shape(Y)[1])) X_CV = np.zeros((1, np.shape(X)[1])) Y_CV = np.zeros((1, np.shape(Y)[1])) total = np.shape(X)[0] #total amount to begin with while (np.shape(X)[0] > 0.2 * total): random_number = random.randrange(0, np.shape(X)[0]) #appending the items X_train = np.vstack((X_train, X[random_number, :])) Y_train = np.vstack((Y_train, Y[random_number, :])) #removing the number from the list if(random_number == np.shape(X)[0] - 1): X = X[:random_number] Y = Y[:random_number] else: X = np.vstack((X[:random_number], X[random_number + 1:])) Y = np.vstack((Y[:random_number], Y[random_number + 1:])) total = np.shape(X)[0] while (np.shape(X)[0] > 0.5 * total): random_number = random.randrange(0, np.shape(X)[0]) #appending items X_CV = np.vstack((X_CV, X[random_number, :])) Y_CV = np.vstack((Y_CV, Y[random_number, :])) #removing the numbers if(random_number == np.shape(X)[0] - 1): X = X[:random_number] Y = Y[:random_number] else: X = np.vstack((X[:random_number], X[random_number + 1:])) Y = np.vstack((Y[:random_number], Y[random_number + 1:])) X_test = X Y_test = Y return X_train[1:], Y_train[1:], X_CV[1:], Y_CV[1:], X_test, Y_test start = time.time() process() print(time.time() - start)
print("Welcome to BMI calculator.") Gender = input("Put in your gender: ") Weight = input("Put in your weight in KG: ") Height = input("Put in your height in CM: ") Weight = float(Weight) Height = float(Height) Height_Squared = Height * Height BMI = Weight / Height_Squared BMI_Formula_Completed = BMI * 10000 BMI_Formula_Completed = str(BMI_Formula_Completed) print("You have a BMI score of " + BMI_Formula_Completed + ".") BMI_Formula_Completed = float(BMI_Formula_Completed) if BMI_Formula_Completed <= 18.4: print("You are underweight, your health risk is malnutrition risk.") elif BMI_Formula_Completed <= 18.5: print("You are normal weight, your health risk is low risk.") elif BMI_Formula_Completed <= 25: print("You are overweight, your health risk is enhanced risk.") elif BMI_Formula_Completed >= 30: print("You are moderately obese , your health risk is medium risk.") elif BMI_Formula_Completed >= 35: print("You are severely obese , your health risk is high risk.") elif BMI_Formula_Completed >= 40: print("You are very severley obese , your health risk is very high risk.") #over weight var = [23.7,22.4,29.4] dict ={} for x in var: if x not in dict: dict[x]=" BMI_OverWeight" else: dict[x]="BMI_Category" print(dict)
a = [1, 2, 3, 1, 5, 7, 8, 2, 3, 4] # Example of a row n = len(a) d = [] # Row holding max sequence for every digit in "a" for i in range(n): d.append(1) for j in range(1, i): if a[j] < a[i] and d[j] + 1 > d[i]: d[i] = d[j] + 1 ans = 0 for i in range(1, n): ans = max(ans, d[i]) print(a) print(d) print(max(d))
# toy dataset included to scify from sklearn import datasets #importing datasets from sklearn import numpy as np iris = datasets.load_iris() #getting the iris flower dataset into iris #check whether dataset loaded #print(iris) data = iris.data #data features 150*4 2D array target = iris.target #target labels 150 1d array #check whether data loaded #print(data) #print(iris) train_data = np.delete(data, [0,50,100], axis=0) #delete unvanted data use axis fordelete rows not columns #print(train_data) train_target = np.delete(target,[0,50,100]) #print(train_target) from sklearn.neighbors import KNeighborsClassifier clsfr = KNeighborsClassifier() #loading the KNN to clsfr #KNN is somtypes of brain in MLwe can use another types as well #training beginning line below line is execute training process using provided data clsfr.fit(train_data,train_target) # training the KNN model #introduce test_data to early removed data test_data = data[[0,50,100]] test_target = target[[0,50,100]] #print(test_data) #now test it works using we early removed data result = clsfr.predict(test_data) print("predicted result : " ,result)
import random, pylab # Helper function 1 def flip(): ''' flip one coin ''' return random.choice(['H', 'T']) def flipCoins(numCoins=1000): ''' flip numCoins coins 10 times each and return res per coin ''' res = [] for i in range(numCoins): aCoin = [] for j in range(10): # flip each coin 10 times aCoin.append(flip()) res.append(aCoin) return res # Helper function 2 def countH(aCoin): counter = 0 for i in range(len(aCoin)): if aCoin[i] == 'H': counter += 1 return counter # Helper function 3 def minHeads(allCoins): numHeads = 10 # max num heads per coin coinIndex = 0 for i in range(len(allCoins)): freqOfH = countH(allCoins[i]) if freqOfH < numHeads: numHeads = freqOfH coinIndex = i return coinIndex def pick3(allCoins): c1 = allCoins[0] cRand = random.choice(allCoins) minIndex = minHeads(allCoins) cMin = allCoins[minIndex] nu1 = countH(c1) / float(len(c1)) nuRand = countH(cRand) / float(len(cRand)) nuMin = countH(cMin) / float(len(cMin)) return [nu1, nuRand, nuMin] # run experiement for 100,000 times nu1s, nuRands, nuMins = [], [], [] for i in range(100000): coins = flipCoins() freqOfHs = pick3(coins) nu1s.append(freqOfHs[0]) nuRands.append(freqOfHs[1]) nuMins.append(freqOfHs[2]) print 'Avergae of nu1s = ' + str(sum(nu1s)/ len(nu1s)) print 'Avergae of nuRands = ' + str(sum(nuRands)/ len(nuRands)) print 'Avergae of nuMins = ' + str(sum(nuMins)/ len(nuMins)) pylab.hist(nuMins) pylab.xlabel('nu 1') pylab.show() pylab.hist(nuMins) pylab.xlabel('nu Rand') pylab.show() pylab.hist(nuMins) pylab.xlabel('nu Min') pylab.show() # output # Avergae of nu1s = 0.499936 # Avergae of nuRands = 0.500076 # Avergae of nuMins = 0.037596
def f1(self, x, y): return min(x,y) def f2(self, x): return x+10 class C: f = f1 def g(self): return repr(self) + "Hello world" h = g print(f1(0,1,2)) x = C(); print(x.f(4,5)) print(x.g()) print(x.h()) x.h = f2 print(x.h(0, 6))
# basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] fruit = set(basket) print(fruit) def judge(a, b): if( a in b): print(a, "in", b) else: print(a, "not in", b) judge('orange', fruit) judge("applee", fruit) a = set('abcd') b = set('cdef') # 集合的简单操作 print(a) print(b) print(a-b) print(a | b) print(a & b) print(a ^ b) c = {x for x in 'gdafgrdgdsdgregsefsff' if x not in 'grdsca'} print(c)
# def fib(n): """这个函数打印斐波那契数列""" a,b = 0,1 while(a < n): print(a, end = ' ') a,b = b, a+ b print() def fib2(n): """这个函数返回斐波那契数列""" result = [] a,b = 0,1 while(a < n): result.append(a) a,b = b, a+ b return result fib(100) fib(1000) res1 = fib2(100) print(res1)
# for num in range(2, 10): if(num % 2 == 0): print(num, "是一个偶数"); continue print(num, "不是一个偶数")
import numpy as np import matplotlib.pyplot as plot import pandas from prediction_parameters.cost import cost_function from prediction_parameters.hypothesis import hypothesis dataframe = pandas.read_csv('houses_data.csv') # function to plot cost def plot_cost(theta): x2 = np.linspace(-0.5, 2.5) y2 = [cost_function(x, training_data=dataframe) for x in x2] axes[1].set_ylim(0, 3.5) axes[1].set_xlim(-0.5, 2.5) axes[1].set_title('Cost Function') axes[1].set_xlabel(r'$\theta$') axes[1].set_ylabel(r'$J(\theta)$') axes[1].scatter(theta, cost_function(theta, dataframe), label='cost') axes[1].legend(loc='upper left') axes[1].plot(x2, y2) # function to plot prediction def plot_prediction(theta): x1 = np.linspace(0.0, 5.0) y1 = np. linspace(0.0, 5.0) axes[0].set_ylim(0, 5.0) axes[0].set_title('House Prices') axes[0].set_xlabel('Area(feet$^2$)') axes[0].set_ylabel('Price') axes[0].scatter(dataframe.area, dataframe.price) axes[0].plot(dataframe.area, theta * dataframe.price, color='red', label='prediction') axes[0].legend(loc='upper left') # Visualize cost and hypothesis functions fig, axes = plot.subplots(nrows=1, ncols=2, figsize=(5,5)) # Plot the graphs plot_prediction(theta=1.0) plot_cost(theta=1.0) fig.tight_layout() def update(theta = 1.0): axes[0].clear() axes[1].clear() plot_prediction(theta) plot_cost(theta) interact(update)
#!/usr/bin/env python # coding: utf-8 # ### Note # * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. # In[9]: # Dependencies and Setup import pandas as pd import numpy as np # File to Load (Remember to Change These) school_data_to_load = "Resources/schools_complete.csv" student_data_to_load = "Resources/students_complete.csv" # Read School and Student Data File and store into Pandas DataFrames school_data = pd.read_csv(school_data_to_load) student_data = pd.read_csv(student_data_to_load) # Combine the data into a single dataset. school_data_complete = pd.merge(student_data, school_data, how="left", on=["school_name", "school_name"]) # ## District Summary # # * Calculate the total number of schools # # * Calculate the total number of students # # * Calculate the total budget # # * Calculate the average math score # # * Calculate the average reading score # # * Calculate the percentage of students with a passing math score (70 or greater) # # * Calculate the percentage of students with a passing reading score (70 or greater) # # * Calculate the percentage of students who passed math **and** reading (% Overall Passing) # # * Create a dataframe to hold the above results # # * Optional: give the displayed data cleaner formatting # In[14]: total_schools = school_data_complete["school_name"].nunique() total_schools # In[25]: total_students=school_data_complete["Student ID"].nunique() total_students # In[30]: total_budget = school_data_complete['budget'].sum() total_budget # In[31]: average_math_score = school_data_complete['math_score'].mean() average_math_score # In[33]: average_reading_score = school_data_complete['reading_score'].mean() average_reading_score # In[36]: passing_math = len(school_data_complete[school_data_complete['math_score'] >= 70]) passing_math # In[38]: percent_passing_math = passing_math/total_students * 100 percent_passing_math # In[39]: passing_reading = len(school_data_complete[school_data_complete['reading_score'] >= 70]) passing_reading # In[40]: percent_passing_reading = passing_reading/total_students * 100 percent_passing_reading # In[43]: percent_overall_passing = (average_math_score + average_reading_score)/2 percent_overall_passing # In[60]: district_summary_df = pd.DataFrame({"Total Schools": [total_schools], "Total Students": [total_students], "Total Budget": [total_budget], "Average Math Score": [average_math_score], "Average Reading Score": [average_reading_score], "Passing Math": [percent_passing_math], "Passing Reading": [percent_passing_reading], "Overall Passing Rate": [percent_overall_passing] }) district_summary_df # ## School Summary # In[ ]: # * Create an overview table that summarizes key metrics about each school, including: # * School Name # * School Type # * Total Students # * Total School Budget # * Per Student Budget # * Average Math Score # * Average Reading Score # * % Passing Math # * % Passing Reading # * % Overall Passing (The percentage of students that passed math **and** reading.) # # * Create a dataframe to hold the above results # In[64]: grouped_school_df = school_data_complete.groupby(["school_name"]) schoolType = grouped_school_df["type"].first() schoolType # In[66]: totalStudents = grouped_school_df["Student ID"].count() totalStudents # In[69]: totalSchoolBudget = grouped_school_df["budget"].first() totalSchoolBudget # In[71]: perStudentBudget = totalSchoolBudget / totalStudents perStudentBudget # In[80]: averageMathScore = grouped_school_df["math_score"].mean() averageMathScore # In[78]: averageReadingScore = grouped_school_df["reading_score"].mean() averageReadingScore # In[83]: passingMath = school_data_complete[school_data_complete["math_score"] >= 70].groupby(["school_name"])["math_score"].count() passingMath percentPassingMath = passingMath / totalStudents * 100 percentPassingMath # In[85]: passingRead = school_data_complete[school_data_complete["reading_score"] >= 70].groupby(["school_name"])["reading_score"].count() percentPassingReading = passingRead / totalStudents * 100 percentPassingReading # In[87]: percentOverallPassingRate = (percentPassingMath + percentPassingReading) / 2 percentOverallPassingRate # In[89]: school_summary_df = pd.DataFrame({"School Type": schoolType, "Total Students": totalStudents, "Total School Budget": totalSchoolBudget, "Per Student Budget": perStudentBudget, "Average Math Score": averageMathScore, "Average Reading Score": averageReadingScore, "Passing Math": percentPassingMath, "Passing Reading": percentPassingReading, "Overall Passing Rate": percentOverallPassingRate}) school_summary_df # In[91]: school_summary_df = school_summary_df.sort_values(["Overall Passing Rate"], ascending=False) school_summary_df # In[93]: # top 5 schools school_summary_df.head() # In[ ]: # In[ ]: # In[ ]: # ## Top Performing Schools (By % Overall Passing) # * Sort and display the top five performing schools by % overall passing. # In[ ]: # ## Bottom Performing Schools (By % Overall Passing) # * Sort and display the five worst-performing schools by % overall passing. # In[98]: school_summary_df = school_summary_df.sort_values(["Overall Passing Rate"], ascending=True) school_summary_df[["School Type", "Total Students", "Total School Budget", "Per Student Budget","Average Math Score", "Average Reading Score", "Passing Math", "Passing Reading","Overall Passing Rate"]].head() school_summary_df # ## Math Scores by Grade # * Create a table that lists the average Reading Score for students of each grade level (9th, 10th, 11th, 12th) at each school. # # * Create a pandas series for each grade. Hint: use a conditional statement. # # * Group each series by school # # * Combine the series into a dataframe # # * Optional: give the displayed data cleaner formatting # In[110]: grade9th_ds = school_data_complete.loc[school_data_complete["grade"] == "9th"].groupby(["school_name"])["math_score"].mean() grade10th_ds = school_data_complete.loc[school_data_complete["grade"] == "10th"].groupby(["school_name"])["math_score"].mean() grade11th_ds = school_data_complete.loc[school_data_complete["grade"] == "11th"].groupby(["school_name"])["math_score"].mean() grade12th_ds = school_data_complete.loc[school_data_complete["grade"] == "12th"].groupby(["school_name"])["math_score"].mean() grade_summary_df = pd.DataFrame({"9th": grade9th_ds, "10th": grade10th_ds, "11th": grade11th_ds, "12th": grade12th_ds}) grade_summary_df[["9th", "10th", "11th", "12th"]] # In[104]: grade9th_ds.head() grade10th_ds.head() # ## Reading Score by Grade # * Perform the same operations as above for reading scores # In[111]: grade9th_ds = school_data_complete.loc[school_data_complete["grade"] == "9th"].groupby(["school_name"])["reading_score"].mean() grade10th_ds = school_data_complete.loc[school_data_complete["grade"] == "10th"].groupby(["school_name"])["reading_score"].mean() grade11th_ds = school_data_complete.loc[school_data_complete["grade"] == "11th"].groupby(["school_name"])["reading_score"].mean() grade12th_ds = school_data_complete.loc[school_data_complete["grade"] == "12th"].groupby(["school_name"])["reading_score"].mean() grade_summary_df = pd.DataFrame({"9th": grade9th_ds, "10th": grade10th_ds, "11th": grade11th_ds, "12th": grade12th_ds}) grade_summary_df[["9th", "10th", "11th", "12th"]] # ## Scores by School Spending # * Create a table that breaks down school performances based on average Spending Ranges (Per Student). Use 4 reasonable bins to group school spending. Include in the table each of the following: # * Average Math Score # * Average Reading Score # * % Passing Math # * % Passing Reading # * Overall Passing Rate (Average of the above two) # In[118]: spending_bins = [0, 585, 615, 645, 675] group_names = ["<$585", "$585-615", "$615-645", "$645-675"] group_names spending_bins # In[132]: school_summary_df["Per Student Budget"] = school_summary_df["Per Student Budget"].apply (lambda x:x.replace('$', '').replace(',', '')).astype("float") school_summary_df = school_summary_df.reset_index() school_summary_df["Spending_Ranges (Per Student)"] = pd.cut(school_summary_df["Per Student Budget"], spending_bins, labels=group_names) grouped_spend_df = school_summary_df.groupby(["Spending Ranges (Per Student)"]) spending_summary_df = grouped_spend_df.mean() # Display Summary spending_summary_df[["Average Math Score", "Average Reading Score", "Passing Math", "Passing Reading", "Overall Passing Rate"]] Spending_summary_df # ## Scores by School Size # * Perform the same operations as above, based on school size. # In[130]: school_summary_df = school_summary_df.reset_index() school_summary_df["School Size"] = pd.cut(school_summary_df["Total Students"], labels=group_names) grouped_size_df = school_summary_df.groupby(["School Size"]) size_summary_df = grouped_size_df.mean() size_summary_df[["Average Math Score", "Average Reading Score", "Passing Math", "Passing Reading", "Overall Passing Rate"]] # ## Scores by School Type # * Perform the same operations as above, based on school type # In[24]: # In[134]: school_summary_df = school_summary_df.reset_index() grouped_type_df = school_summary_df.groupby(["School Type"]) type_summary_df = grouped_type_df.mean() type_summary_df[["Average Math Score", "Average Reading Score", "Passing Math", "Passing Reading", "Overall Passing Rate"]] # In[ ]:
import random import board class AI: def __init__(self, acontroller): ''' Initializes ai class ''' self.controller = acontroller self.board = board.Board(self.controller) def initialize(self): ''' Initializes the ai and creates a new board object to experiment on. ''' self.player = self.controller.playon.get_who_is_playing() self.cur_player = self.controller.playon.get_who_is_playing() self.enemy = self.get_enemy(self.player) self.board.initialize_board() self.board.add_where_pieces(self.controller.board.get_pieces()) def switch_players(self): ''' Returns which player is the enemy to the ai. ''' if self.player == 'A': self.enemy = self.get_enemy(self.player) self.player = 'B' else: self.enemy = self.get_enemy(self.player) self.player = 'A' def get_enemy(self, player): ''' Returns the opponent ''' if player == 'A': return 'B' else: return 'A' def possible_moves(self): ''' Get all possible moves. Check whether every possible move can result in a win. Result in a win: return the winning move Or else: return possble moves list, sorted with the moves which are likely to be optimal at the start, (according distance to center, and than to height) to optimize alpha-beta pruning in the recursive_eval method According to documentation about sorted and lambda https://docs.python.org/3/howto/sorting.html#sortinghowto https://docs.python.org/3/reference/expressions.html#lambda ''' possible_moves_list = [] for x in range(self.board.get_width()): y = 0 while y < self.board.get_height() - 1 and self.board.get_pieces( )[x][y] != '0': y += 1 if self.board.get_pieces()[x][y] == '0': if self.controller.playon.determine_win( self.player, (x, y), False, self.board) == True: return [float('inf'), (x, y)] else: possible_moves_list.append((x, y)) possible_moves_list_sorted = sorted( possible_moves_list, key= lambda move: (abs(((self.board.get_width() // 2) - move[0])), move[1]) ) return possible_moves_list_sorted def make_decision_random(self): ''' Returns a winning move. If no winning move, return random move. ''' self.initialize() possible_moves_list = self.possible_moves() if float('inf') in possible_moves_list: return possible_moves_list[1] else: return random.choice(possible_moves_list) def make_decision_smart(self, depth): ''' Returns the best move given a player and a board. For the 1st 2 moves, the ai will play at the center. For the remaining moves, check whether a move can win Win: return move No win: return list containing all possible moves For every move in the list, use the recursive_eval method to recursively evaulate the move's score. We will then prioritise center by mutiplying the center's piece score by 4 during early game, and return the best move with the max score. As the pieces on the board increase, the possiblities will decrease and we can gradually increase the search depth while maintaining a reasonable computation time ''' self.initialize() if self.controller.board.get_num_pieces() < 2: if self.board.get_pieces()[3][0] == '0': return (self.board.get_width() // 2, 0) else: return (self.board.get_width() // 2, 1) elif 15 < self.controller.board.get_num_pieces() <= 20: depth += 2 elif 20 < self.controller.board.get_num_pieces() <= 25: depth += 4 elif self.controller.board.get_num_pieces() > 25: depth += 6 possible_moves_scores = {} possible_moves_list = self.possible_moves() if float('inf') in possible_moves_list: return possible_moves_list[1] else: max_score = -float('inf') for possible_move in possible_moves_list: x, y = possible_move self.board.add_piece(x, y, self.player) self.switch_players() node_score = self.recursive_eval(max_score, float('inf'), depth) possible_moves_scores[possible_move] = node_score max_score = max(max_score, node_score) self.switch_players() self.board.remove_piece(x, y) print("AI's possible moves scores:\n{}\n".format( possible_moves_scores)) if self.controller.board.get_num_pieces() < 10: for move in possible_moves_list: if move[0] == self.board.get_width() // 2: possible_moves_scores[move] *= 4 max_move = [ move for move, score in possible_moves_scores.items() if score == max(possible_moves_scores.values()) ][0] return max_move def recursive_eval(self, a, b, depth): ''' Uses minimax algorithm optimized with alpha beta pruning. Minimax: Uses a tree search algorithm and returns the best possible move, presuming both sides will play optimally. you 3 (Your score) / \ opp 3 6 (Opponent: Opponent will play the best move, and return the move which minimizes your score. 3/6 will return 3) / \ / \ you 3 1 6 2 (Final level: return your base score according to the eval score method. As you will play your best move, you will return your best score in the branch. 3/1 will return 3, 6/2 will return 6) Alpha beta pruning: Does not search a branch when the branch results in a worse score than the present score. Upon evaluating the lower left tree: you / \ opp 3 (Beta is opponent present min score: 3) / \ / \ you 3 1 As you proceed with the lower right branch: you 3 / \ opp 3 10 (Beta is opponent present min score: 3) / \ / \ you 3 1 10 X (Alpha is your present max score: 10) As alpha 10 is greater than beta 3: X does not need to be evaluated as evaluating X will not change the decision. Getting a 10 on the right branch entails that the right branch is better than all the moves on the left branch. Hence the opponent, which aim to play the best move by minimizing you score, will never play the left move. Now evaluating the right branch: opp / \ you 3 (Alpha is your present maximum: 3) / \ / \ opp 3 10 (Alpha is 3 gets recursively passed down) / \ / \ / \ / \ you 3 1 10 X 2 1 Opponent get a score = 2 on the right branch opp 3 / \ you 3 2 (Alpha your present maximum: 3) / \ / \ opp 3 10 2 X (Beta is opponent present min score: 2) / \ / \ / \ / \ while alpha is 3 you 3 1 10 X 2 1 X X As alpha 3 is greater than beta 2: Xs does not need to be evaluated as evaluating Xs will not change the decision. For you, getting a maximum 2 on the right branch entails that the right branch is worst than all the moves on the left branch. Hence the opponent, which aim to play the best move by minimizing you score, will return a move with score 2 or less. As your present move with score 3 is better than score 2, you will now definitely choose the left move despite any score given by the Xs. ''' if depth == 0: possibles_move_list = self.possible_moves() if float('inf') in possibles_move_list: return float('inf') else: max_score = -float('inf') for possible_move in possibles_move_list: x, y = possible_move self.board.add_piece(x, y, self.player) max_score = max( max_score, self.eval_score(self.player, self.board.get_new_piece())) self.board.remove_piece(x, y) a = max(a, max_score) if b <= a: break return max_score elif self.player == self.cur_player: ''' Maximizes the score if the player's move being looked at is the ai ''' possibles_move_list = self.possible_moves() if float('inf') in possibles_move_list: return float('inf') else: max_score = -float('inf') for possible_move in possibles_move_list: x, y = possible_move self.board.add_piece(x, y, self.player) self.switch_players() max_score = max(max_score, self.recursive_eval(a, b, depth - 1)) self.switch_players() self.board.remove_piece(x, y) a = max(a, max_score) if a >= b: break return max_score else: ''' Assumes the opponent will minimize the ai's score ''' possibles_move_list = self.possible_moves() if float('inf') in possibles_move_list: return -float('inf') else: min_score = float('inf') for possible_move in possibles_move_list: x, y = possible_move self.board.add_piece(x, y, self.player) self.switch_players() min_score = min(min_score, self.recursive_eval(a, b, depth - 1)) self.switch_players() self.board.remove_piece(x, y) b = min(b, min_score) if b <= a: break return min_score def eval_score(self, aplayer, apiece, prioritise_center=True): ''' Check whether possble move can win in a direction using possible_win_in_a_dirct method. For player A, arrangement 0,A,0,0 can possible win, in the horizontal direction, but not arrangement B,A,0,B. Cannot possibly win: delete in list Remaining possibles_move_list will contain those moves which can possibly win and we will evaluate those moves Those directions which can't create a win are discounted. Then the remaining directions are evaluated using multiplier_in_a_dirctn, with direct connections in a direction multiplied by 4. For player A, arrangement A,A will give 4 points, while A,A,A will give 16 points. Multiplier_in_a_dirctn take into account gaps as well, with '0's multiplied by 2. For player A, arrangement A,A,B will give 16 points, while A,A,0 will give 32 points. The method will recurse up to 1 zero in a direction, with any connection beyond the zero mulitplying the score by 2. For player A, arrangement the last A in A,0,A will multiply the score by 2. Both A,0,A,0 and A,0,A,B will give 8 points, as we do not take into account the 2nd zero (or anything beyond) Then eval_score will sum up the scores in every direction to give the total scores. To prioritise center, the total score will be multiplied by the the piece's distance to center, where a piece closer to the center will get a greater score. More examples in testing_ai.py uldr, ud, urdl lr, piece, lr urdl, ud, uldr uldr = connections to the up, left / down, right urdl = connections to up, right / down, left ud = connections to up / down lr = connections to left / right ''' self.dirtn_score = {'uldr': 1, 'urdl': 1, 'lr': 1, 'ud': 1} self.connections_dirtn = {'uldr': 0, 'urdl': 0, 'lr': 0, 'ud': 0} self.directions_coords = { 'uldr': ((-1, 1), (1, -1)), 'urdl': ((1, 1), (-1, -1)), 'lr': ((-1, 0), (1, 0)), 'ud': ((0, -1), (0, 1)) } for dirtns in self.directions_coords.copy(): for a_dirtn in self.directions_coords.copy()[dirtns]: self.connections_dirtn[ dirtns] += self.possible_win_in_a_dirctn( a_dirtn, self.player, apiece) if self.connections_dirtn[dirtns] < 3: del self.directions_coords[dirtns] for dirtns in self.directions_coords: for a_dirtn in self.directions_coords[dirtns]: self.dirtn_score[dirtns] *= self.multiplier_in_a_dirctn( a_dirtn, self.player, apiece) total_score = sum(self.dirtn_score.values()) if prioritise_center == True: distance_to_center = abs(apiece[0] - self.board.get_width() // 2) if distance_to_center == 0: center_multiplier = 2.5 elif distance_to_center == 1: center_multiplier = 2 elif distance_to_center == 2: center_multiplier = 1.5 else: center_multiplier = 1 total_score *= center_multiplier return total_score def multiplier_in_a_dirctn(self, adirection, aplayer, apiece, zero_num=0): ''' checks for connections in a given direction and only stops if it encounters two zeroes or one of the enemies pieces. Returns a score which has a multiplier that is halved if a zero has already been encountered in that direction. ''' new_piece = (apiece[0] + adirection[0], apiece[1] + adirection[1]) new_x, new_y = new_piece[0], new_piece[1] if new_x >= self.board.get_width() or new_y >= self.board.get_height( ) or new_x < 0 or new_y < 0: return 1 elif zero_num == 1: if self.board.get_pieces()[new_x][new_y] == self.player: return 2 * self.multiplier_in_a_dirctn(adirection, self.player, new_piece, 1) else: return 1 else: if self.board.get_pieces()[new_x][new_y] == '0': return 2 * self.multiplier_in_a_dirctn(adirection, self.player, new_piece, 1) else: return 4 * self.multiplier_in_a_dirctn(adirection, self.player, new_piece) def possible_win_in_a_dirctn(self, adirection, aplayer, apiece): ''' Adds up connections in a direction, and counts empty spaces as a connection. ''' new_piece = (apiece[0] + adirection[0], apiece[1] + adirection[1]) new_x, new_y = new_piece[0], new_piece[1] if new_x >= self.board.get_width() or new_y >= self.board.get_height( ) or new_x < 0 or new_y < 0: return 0 elif self.board.get_pieces()[new_x][new_y] not in (self.player, '0'): return 0 else: return 1 + self.possible_win_in_a_dirctn(adirection, self.player, new_piece)
# In this lesson we are taking a few steps back to look at linear regression, # from a simple idea of fitting a straight line through data to ridge regression # on our next lesson # The boston dataset is perfect to play around with regression. # The boston dataset has the median home price of several areas in Boston. # It also has other factors that might impact housing prices, # for example, crime rate. # First Import the datasets from sklearn import datasets boston = datasets.load_boston() print(boston.data) print(boston.target) # First, import the LinearRegression object and create an object: from sklearn.linear_model import LinearRegression lr = LinearRegression() # Now, it's as easy as passing the independent # and dependent variables to the method of LinearRegression: lr.fit(boston.data, boston.target) LinearRegression(copy_X=True, fit_intercept=True, normalize=False) # Now, to get the predictions, do the following: predictions = lr.predict(boston.data) # So, going back to the data, we can see which factors have a negative # relationship with the outcome, and also the factors that have a # positive relationship. For example, and as expected, an increase # in the per capita crime rate by town has a negative relationship # with the price of a home in Boston. The per capita # crime rate is the first coefficient in the regression. print("The Coefficients" , lr.coef_) print(predictions) # we minimize the error term. This is done by minimizing # the residual sum of squares. # The LinearRegression object can automatically normalize (or scale) the inputs: lr2 = LinearRegression(normalize=True) lr2.fit(boston.data, boston.target) LinearRegression(copy_X=True, fit_intercept=True, normalize=True) predictions2 = lr2.predict(boston.data) # In this section , we'll look at how well our regression # fits the underlying data. # We look at a regression in the last display , but didn't pay much attention # to how well we actually did it. # The first question after we fit the model was clearly # "How well does the model fit?" In this section, we'll examine this question. # Evaluation the linear Regression Model # The lr object will have a lot of useful methods now that the model has been fit. import matplotlib.pyplot as plt import numpy as np f = plt.figure(figsize=(7, 5)) ax = f.add_subplot(111) ax.hist(boston.target - predictions, bins=50) ax.set_title("Histogram of Residuals.") # The error terms should be normal, with a mean of 0. # The residuals are the errors; therefore, this plot should be approximately # normal. Visually, it's a good t, though a bit skewed. We can also look # at the mean of the residuals, which should be very close to 0: plt.show() # print("The mean is ", np.mean(boston.target - predictions)) # Q-Q plot. # Here, the skewed values we saw earlier are a bit clearer. from scipy.stats import probplot f = plt.figure(figsize=(7, 5)) ax = f.add_subplot(111) probplot(boston.target - predictions, plot=ax) plt.show() # We can also look at some other metrics of the t; # mean squared error (MSE) and mean absolute deviation (MAD) are # wo common metrics. # Let's de ne each one in Python and use them. def MSE(target, predictions): squared_deviation = np.power(target - predictions, 2) return np.mean(squared_deviation) print("MSE is ", MSE(boston.target, predictions)) print("MSE after normalisation ", MSE(boston.target, predictions2))
#1.加總分(total), 排名(rank) #2.使用subject為主 students = { 'Chang': { 'Math': 90, 'Chinese': 85, 'English': 60 }, 'Thang': { 'Math': 85, 'Chinese': 70, 'English': 92 }, 'Chen': { 'Math': 90, 'Chinese': 93, 'English': 95 } } subjects = {} # 加總分 for key, values in students.items(): students[key]['total'] = 0 for sub, score in values.items(): if sub != 'total': students[key]['total'] += score # 設定排名 for key in students.keys(): students[key]['rank'] = 1 for compareKey in students.keys(): if students[key]['total'] < students[compareKey]['total']: students[key]['rank'] += 1 # 以科目為主 for key, values in students.items(): for sub, score in values.items(): subjects.setdefault(sub, {}) subjects[sub][key] = score print(students) print(subjects)
# -*- coding: utf-8 -*- """ Created on Tue Mar 14 22:24:42 2017 @author: bushnelf """ import Game import CardSet import RandomComputerPlayer class RandomGame(Game.Game): def __init__(self, numplayers, numrounds=10): Game.Game.__init__(self, numplayers) self._numrounds = numrounds def playrounds(self, numrounds): for gameround in range(numrounds): print("********** Round " + str(gameround) + " ********") print("!!! Before") for pbidx in range(len(self.playerboards)): pb = self.playerboards[pbidx] card = pb.player.choosecardtoplay(self, pbidx) pb.readytoplay(card) print("Player board " + pb.player.name + ":") print(pb) self.playallcards() print("!!! After") for pbidx in range(len(self.playerboards)): pb = self.playerboards[pbidx] print("Player board " + pb.player.name + ":") print(pb) if self.endturn(): # we have a winner (or a bunch of losers) break print("!!! Post turn") for pbidx in range(len(self.playerboards)): pb = self.playerboards[pbidx] print("Player board " + pb.player.name + ":") print(pb) if __name__ == '__main__': g = RandomGame(3) for rcpi in range(3): rcp = RandomComputerPlayer.RandomComputerPlayer("Random Player " + str(rcpi+1)) g.playerboards[rcpi].player = rcp cs = CardSet.CardSet(3) g.cardlist = cs.getcardset() g.sendcardlisttoboards() for dnr in range(3): pb = g.playerboards[dnr] c = pb.player.choosecardtodiscard(g, dnr, ["hand"]) pb.discard(c, ["hand"]) c = pb.player.choosecardtosendtorecovery(g, dnr) pb.sendtorecovery(c) g.playrounds(20)
# -*- coding: utf-8 -*- """ Created on Sun Jan 22 21:48:40 2017 @author: bushnelf """ import random # import Player class PlayerBoard(object): """ PlayerBoard - where a player's "in play", "recovery zone", and discarded cards are kept, along with the player's victory points and any special tokens (disabled et al). Oh, and the player's hand. """ def __init__(self, name): self._name = name # These are all lists of cards. self._inplay = [] self._discards = [] self._recovery = [] self._hand = [] self._redalert = False self._disabled = 0 self._protected = 0 self._victorypoints = 1 # everyone starts with 1 self._player = None self._last_round_card = None self._vp_lost_this_round = 0 self._doubleplay = 0 @property def inplay(self): return self._inplay @property def discards(self): return self._discards @property def recoveryzone(self): if self.checkredalert(): return self._inplay else: return self._recovery @property def hand(self): return self._hand @hand.setter def hand(self, val): self._hand = val @property def redalert(self): return self._redalert @property def disabled(self): return self._disabled @disabled.setter def disabled(self, val): if val < 0: val = 0 self._disabled = val @property def protected(self): return self._protected @protected.setter def protected(self, val): if val < 0: val = 0 self._protected = val @property def victorypoints(self): return self._victorypoints @victorypoints.setter def victorypoints(self, val): if val < 0: val = 0 if val < self._victorypoints: self.vp_lost_this_round += self._victorypoints - val self._victorypoints = val @property def player(self): return self._player @player.setter def player(self, val): self._player = val # To do: last round's card can have a continuing effect, so # keep track of it, and implement methods to handle it in the # individual card classes. @property def lastroundcard(self): return(self._last_round_card) @lastroundcard.setter def lastroundcard(self, val): self._last_round_card = val @property def vp_lost_this_round(self): return(self._vp_lost_this_round) @vp_lost_this_round.setter def vp_lost_this_round(self, val): self._vp_lost_this_round = val @property def doubleplay(self): return(self._doubleplay) @doubleplay.setter def doubleplay(self, val): if val < 0: val = 0 self._doubleplay = val def defense(self, game, pbidx, effect): """ Check whether the card in play or from last round have a defense against opponents' attacks. effect: main_effect, vp_theft, card_discard, card_theft """ defense = False if len(self.inplay) > 0: defense = self.inplay[0].defense(game, pbidx, effect, "this") if not defense: # if we've already established a defense, we're done if self.lastroundcard is not None: defense = \ self.lastroundcard.defense(game, pbidx, effect, "last") if self.player is not None: plnm = self.player.name else: plnm = "Nohbody" print("Player " + plnm + " defense is " + str(defense)) return(defense) def ignore_main_effect(self, game, attkpbidx, addl_fx): fx = ["main_effect"] if addl_fx is not None: fx.extend(addl_fx) return(self.defense(game, attkpbidx, fx)) def readytoplay(self, card): """ Move a card from your hand to the "in play" area. Not quite the same as playing, since the card is put in the "in play" area face down & not revealed till all players have placed their chosen card in their respective "in play" areas. """ if not self.checklost() and card is not None: self.hand.remove(card) self.inplay.append(card) def endplay(self): """ The card in the "in play" area has been played, so move it to the "recovery" area. Make sure this is done after the recover step, as we don't want the card going directly to the player's hand. """ if self.checklost(): if self.player is None: plnm = "Nohbody" else: plnm = self.player.name print("Player " + plnm + " lost!") self.victorypoints = 0 elif self.checkredalert(): if len(self._hand) == 0: lastcard = self.inplay[0] self.hand.append(lastcard) self.inplay.remove(lastcard) else: if len(self.inplay) == 0: self.lastroundcard = None for card in self.recoveryzone: self.hand.append(card) self.recoveryzone.remove(card) for card in self.inplay: self.lastroundcard = card self.recoveryzone.append(card) self.inplay.remove(card) self.protected -= 1 self.disabled -= 1 self.vp_lost_this_round = 0 self._doubleplay -= 1 def recover(self): """ Move the card(s) from the recovery zone to the player's hand. """ for card in self.recoveryzone: self.hand.append(card) self.recoveryzone.remove(card) def sendtorecovery(self, card): if card is not None: self.recoveryzone.append(card) self.hand.remove(card) def discard(self, card, piledescr): """ Discarding may be done from either the hand or the recovery zone. """ if card is not None: if self.player is None: plynm = "Nohbody" else: plynm = self.player.name print(plynm + " discarding " + card.title) # First, check if we have a redirect for discards if len(self.inplay) == 0 or len(self.inplay) > 0 and not \ self.inplay[0].redirect(self, "discard"): if ("hand" in piledescr) and (card in self.hand): self.hand.remove(card) elif ("inplay" in piledescr) and (card in self.inplay): self.inplay.remove(card) elif ("recovery" in piledescr) and (card in self.recoveryzone): self.recoveryzone.remove(card) else: print("Throw an exception here - trying to discard " + card.title) # to do self.discards.append(card) def addtohand(self, card): self._hand.append(card) def checkredalert(self): """ If there is only 1 card in the combined piles of In Play, Recovery Zone, and Hand, then the board is in red alert mode. """ # Want to use hidden fields instead of properties, since # hand & recovery properties mutate when only one card # is left (i.e. board is in red alert state). totalcards = len(self._hand) + len(self._inplay) \ + len(self._recovery) if totalcards == 1: self._redalert = True if len(self._recovery) > 0: # can be only one - ship to inplay card = self._recovery[0] self._inplay.append(card) self._recovery.remove(card) print("Red Alert " + self.player.name + "-> recovery 2 play") elif totalcards > 1: # This covers "recovering" from red alert - back to normal self._redalert = False return(self._redalert) def checklost(self): """ No cards except in discard pile => you have lost """ return (len(self.hand) + len(self.inplay) + len(self.recoveryzone) == 0) def checkrecoveryforsymbol(self, symbol): """ If a card in the recovery zone has a given symbol, return true """ inrec = False for card in self.recoveryzone: # for sym in card.symbols: # if sym == symbol: if symbol in card.symbols: inrec = True break return(inrec) def returndiscardtohand(self, game, pbidx): """ For random computer players, we will just grab a card at random and return it to our hand. For human players, this will be more involved, most likely. """ card = self.player.choosecardtoretrievefromdiscard(game, pbidx) if card is not None: self.hand.append(card) self.discards.remove(card) def removerandomcardfromgame(self, game, pbidx, deck): """ Remove the specified card from the specified deck and do not place it anywhere else. """ # Might re-work this later to allow multiple entries in deck. # Not clear it's needed. if "hand" in deck: pickfrom = self.hand elif "recovery" in deck: pickfrom = self.recoveryzone elif "inplay" in deck: pickfrom = self.inplay elif "discards" in deck: pickfrom = self.discards rng = len(pickfrom) if rng > 0: remvidx = random.randint(0, rng-1) del pickfrom[remvidx] def cardbyindex(self, cardidx, deck="hand"): card = None if cardidx >= 0: if deck == "hand": card = self.hand[cardidx] elif deck == "recovery": card = self.recoveryzone[cardidx] return(card) def handresoltot(self): """ This is needed in case we have a tie among victory points and hand size. """ tot = 0 # print(" Starting handresoltot") for card in self._hand: # print("handresoltot adding " + card.title + "(" + # str(card.rank) + ")") tot += card.rank return(tot) # def printinplay(self): # retstr = " ---- In play:\n" # for card in self.inplay: # retstr += card.title + ": " + str(card.rank) + "\n" # return(retstr) # # def printhand(self): # retstr = " ---- Hand:\n" # for card in self.hand: # retstr += card.title + ": " + str(card.rank) + "\n" # return(retstr) # # def printrecover(self): # retstr = " ---- Recovery Zone:\n" # if self.checkredalert(): # retstr += " [same as in play]\n" # # remove this later # for card in self._recovery: # retstr += card.title.upper() + ", " + str(card.rank) + "\n" # else: # for card in self.recoveryzone: # retstr += card.title + ": " + str(card.rank) + "\n" # return(retstr) # # def printdiscards(self): # retstr = " ---- Discards:\n" # for card in self.discards: # retstr += card.title + ": " + str(card.rank) + "\n" # return(retstr) def shortprint(self, deck): if deck == "hand": deckstr = "H" cardlist = self.hand elif deck == "recovery": deckstr = "RZ" cardlist = self.recoveryzone elif deck == "inplay": deckstr = "IP" cardlist = self.inplay elif deck == "discards": deckstr = "D" cardlist = self.discards retstr = deckstr + ": " for card in cardlist: retstr += str(card.rank) + " " return(retstr) def printinplay(self): return(self.shortprint("inplay")) def printhand(self): return(self.shortprint("hand")) def printrecover(self): return(self.shortprint("recovery")) def printdiscards(self): return(self.shortprint("discards")) def __str__(self): if self.checkredalert(): ramsg = "Red Alert\n" else: ramsg = "Normal\n" return(ramsg + "VP: " + str(self.victorypoints) + "\n" + self.printinplay() + self.printhand() + self.printrecover() + self.printdiscards()) if __name__ == '__main__': import Card c1 = Card.Card("Precision Strike", 34) c1.add_symbol("Weapons") c2 = Card.Card("Shields", 3) c3 = Card.Card("Cloaking Device", 4) pb = PlayerBoard("Player 1") if pb.checklost(): print("No cards => you lost") pb.addtohand(c1) if pb.checkredalert(): print("One card => red alert") pb.addtohand(c2) pb.addtohand(c3) # assert(not pb.checkredalert()) print(pb) print("++++++++++++ Playing Precision Strike") pb.readytoplay(c1) print(pb) print("++++++++++++ Ending play / recovering") pb.endplay() # get it in the recovery area print(pb) if pb.checkrecoveryforsymbol("Weapons"): print("Recovery zone has symbol Weapons (expected)") if pb.checkrecoveryforsymbol("People"): print("Recovery zone has symbol People (NOT expected)") print("++++++++++++ Discarding from recovery zone") pb.discard(c1, ["recovery"]) print(pb) print("++++++++++++ Playing Shields") pb.readytoplay(c2) print(pb) print("++++++++++++ Ending play / recovering") pb.endplay() # get it in the recovery area print(pb) print("++++++++++++ Recovering from recovery zone") pb.recover() # get it back in the hand print(pb) print("++++++++++++ This should fail.") try: c4 = Card.Card("Evasive Action", 8) # This should fail pb.readytoplay(c4) print(pb) except Exception: print("Caught exception as expected") pb.victorypoints = 5 print("VP: " + str(pb.victorypoints)) pb.victorypoints = -1 print("VP: " + str(pb.victorypoints) + " (should be 0)")
a = [["abc0001","Bobby",100], ["abc0002","Larry",400], ["abc0003","Dan",150], ["abc0004","Billy",200], ["abc0005","Sid",350]] def balance(v): for b in a: if (b[0] == v): name=b[1] bal=b[2] print("Hello "+name) print("Your balance is: "+ str(bal)) else: print("This ID is not registered with the bank.") def deposit(v): dep = int (input("Enter amount you want to deposit: ")) for c in a: if(c[0] == v): bal=c[2] bal = bal + dep print("Your current balance is: "+ str(bal)) else: print("This ID is not registered with the bank.") def drawCash(v): draw = int (input("Enter amount you want to draw: ")) for d in a: if(d[0] == v): bal=d[2] bal = bal - draw print("You Current balance is: "+ str(bal)) else: print("This ID is not registered with the bank.") def main(): ID = input("Enter your ID ") print("Cash Withdrawl - Press 1 ") print("Cash Deposit - Press 2") print("Check Balance - Press 3") Enter = int(input("Enter your input: ")) if(Enter == 1): drawCash(ID) elif(Enter == 2): deposit(ID) elif(Enter == 3): balance(ID) else: print("Enter the correct option") main()
#!/usr/bin/env python # coding: utf-8 # In[1]: print("Hello") # In[3]: print("Hello python") # In[6]: print(""" Hello Every one How are you? How is everything going on""") # In[7]: """ Hello Every one How are you? How is everything going on""" # In[8]: print('Hello world') # In[9]: print("python's world") # In[11]: print('Hello\tpython') # In[12]: print('Hello\npython') # In[14]: print('Hello\"python') # In[16]: name = "xyz" marks = 90 age = "21" print("The name of person is",name,"marks is",marks,"age is",age) # In[20]: print("The name of person is %s marks is %f age is %d",(name,marks,age)) # In[26]: print("The name of person is %10s marks is %10f age is %10d",(name,marks,age)) # In[27]: print(f"The name of person is {name} the marks is {90.867} age is{age}") # In[28]: a = 10 b = 10 a == b # In[29]: c = 10 a == c # In[30]: c<=a # In[32]: a >= b # In[34]: a = get_ipython().getoutput('b') # In[35]: str1 = "pythonprogramming" "a" in str1 # In[37]: str1 = "pythonprogramming" "b" not in str1 # In[38]: a = 10 b = 10 a == b # In[39]: a is b # In[40]: id(a) # In[41]: id(b) # In[42]: x=1.2 y=1 x==y # In[43]: x is y # In[44]: id(x) # In[45]: id(y) # In[ ]:
# Austin Whitley # Assignment 4 # Birthday Dictionary # Used as global to it can be used program wide birthdayDictionary = {"Austin":"08/07/1994", "Nathan":"06/07/1994", "Blake":"06/18/1962","Brandy":"03/04/2964"} def main(): functionDictionary = {"Look Up a Birthday": lookUpBirthday, "Add a New Birthday": addBirthday, "Change a Birthday":changeBirthday, "Delete a Birthday": deleteBirthday} print("\nWelcome to the Birthday Log\n") displayFunctions(functionDictionary) chooseOption(functionDictionary) # Function controls the flow of the program and calls the other functions when the option is inputed def chooseOption(functionDictionary): # functionDictionary = {"Look Up a Birthday": lookUpBirthday, "Add a New Birthday": addBirthday, # "Change a Birthday":changeBirthday, "Delete a Birthday": deleteBirthday} # Function used to display the options for the program functionList = [] # Input used to choose option optionChosen = str(input("Enter the number for the option you choose ('q' to quit or 'd' to display dictionary):")) print("\n") # Loop used to take take the values of the functionDictionary and put into list # functionList is a list of functions that were stored in the dictionary for function in functionDictionary.values(): functionList.append(function) # If else's used to take the user input and decide what function to use # I need to use the string anwsers first, when i tried to put them last i kept getting errors concering # how i convert the answers to ints for the other options if optionChosen.lower() == "q": print("Goodbye") # Added this option just to be able to display the birthday dictionary elif optionChosen.lower() == "d": displayBirthdays() displayFunctions(functionDictionary) chooseOption(functionDictionary) elif int(optionChosen) == 1: # This takes the option chossen and subtract 1 to find the correct index for the function list functionList[int(optionChosen)-1]() # Display the options for the program after the intial option chossen has run displayFunctions(functionDictionary) # Recall the function and this process continues until the 'q' is entered to quit chooseOption(functionDictionary) elif int(optionChosen) == 2: functionList[int(optionChosen) -1]() displayFunctions(functionDictionary) chooseOption(functionDictionary) elif int(optionChosen) == 3: functionList[int(optionChosen) -1]() displayFunctions(functionDictionary) chooseOption(functionDictionary) elif int(optionChosen) == 4: functionList[int(optionChosen) -1]() displayFunctions(functionDictionary) chooseOption(functionDictionary) else: print("You entered an incorrect option. Please try again") chooseOption(functionDictionary) # Function is used to display the main options for the program # functionsDictionary is a dictionary that keys are the discription of the option and the value # is the actual function def displayFunctions(functionDictionary): count = 1 print("\nOptions:") for functionName in functionDictionary.keys(): print(f"{count}: {functionName}") count = count + 1 print("\n") # Function to display birthday for testing def displayBirthdays(): print("\nBIRTHDAYS") for name, birthday in birthdayDictionary.items(): print("-------------------------") print(f"{name}: {birthday}") print("-------------------------") print("\n") # Function to add birthday def addBirthday(): name = input("Enter a name: ") birthday = input("Enter a birthday: ") birthdayDictionary[name.title()] = birthday # Function to look up the birthday for a name def lookUpBirthday(): # For loop used for displaying names for users to choose from names = [] for name in birthdayDictionary.keys(): names.append(name) print(f"Options:\n{names}\n") # User is asked to input name they would like to see birthday of birthdayToLookUp = input("Enter a name you would like to see the birtday for: ").title() # If name is in list it shows the birthday for the names if birthdayToLookUp in names: birthday = birthdayDictionary[birthdayToLookUp] print(f"\n{birthdayToLookUp}'s birthday is {birthday}\n") # Else the user will be asked to try again andthe function is recalled else: print("Please enter a valid name") lookUpBirthday() # Function used to change a birthday def changeBirthday(): names = [] # For loop used to display a name for users to choose from for name in birthdayDictionary.keys(): names.append(name) print(f"Options:\n{names}") # Takes user input to choose the name that the borthday should be changed nameToChange = input("Which name would you like change the birthday: ").title() # If the name inputed is in the list it will change the birthday for the given name in the dicitonary if nameToChange in names: birthday = input("Enter new birthday: ") birthdayDictionary[nameToChange] = birthday # Else it will ask the user to try again and the function is recalled else: print("Please enter a valid name") changeBirthday() # Function used to delete birthday def deleteBirthday(): # for loop to make a list of names to display for choosing names = [] for name in birthdayDictionary.keys(): names.append(name) print(f"Options:\n{names}") # Takes user input then checks to see if name is in list nameToDelete = input("Enter the name you would like to remove: ") if nameToDelete.title() in names: # If its in the list it deletes the dictionary entry del birthdayDictionary[nameToDelete] else: # Else it recalls function until a name inputed correctly print("Please enter a valid name") deleteBirthday() main()
import re phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') mo = phoneNumRegex.search('My number is 415-555-4242.') print('Phone number found. Area code: ' + mo.group(1) + ' number: ' + mo.group(2))
# -*- coding: utf-8 -*- """ Created on Thu Apr 4 00:21:26 2019 @author: Anik Paul Gomes """ """ This script reads text file which contains list of dictonary and converts into csv file. So that validity of the calculations can be checked in excel for shorter amount of data """ #Added square brackets in the beginning and at the end of the text file to make it #list of dictionaries before converting into csv. from pathlib import Path import pandas as pd import ast #Reads text file into toCSV using pathlib module toCSV = Path('language_data.txt').read_text() #Converts string representation of dictionary into dictionary toCSV = ast.literal_eval(toCSV) #Converts dictionary into data frame data = pd.DataFrame(toCSV) #dataframe to csv data.to_csv('language_data.csv')
#!/usr/bin/env python3 from PIL import Image img = Image.open('./maps.jpg') width = int(input("Enter the width: ")) height = int(input("Enter the height: ")) resized_img = img.resize((width, height), Image.ANTIALIAS) resized_img.save('./maps_new.jpg')
#!/usr/bin/env python3 a = int(input("Введите число: ")) symb = input("Введите символ: ") b = int(input("Введите второе число: ")) if symb == '+': result = a + b print(result) print("Результат: ") elif symb == '-': result = a - b print("Результат: ") print(result) elif symb == '*': result = a * b print("Результат: ") print(result) elif symb == '/': result = a / b print("Результат: ") print(result)
import pygame import constants import platforms class Level(): """ This is a generic super-class used to define a level. Create a child class for each level with level-specific info. """ def __init__(self, player): """ Constructor. Pass in a handle to player. Needed for when moving platforms collide with the player. """ # Lists of sprites used in all levels. Add or remove # lists as needed for your game. self.platform_list = None self.enemy_list = None # Background image self.background = None # How far this world has been scrolled left/right self.world_shift = 0 self.level_limit = -1000 self.platform_list = pygame.sprite.Group() self.enemy_list = pygame.sprite.Group() self.player = player # Update everythign on this level def update(self): """ Update everything in this level.""" self.platform_list.update() self.enemy_list.update() def draw(self, screen): """ Draw everything on this level. """ # Draw the background # We don't shift the background as much as the sprites are shifted # to give a feeling of depth. screen.fill(constants.BLACK) screen.blit(self.background,(self.world_shift // 3,0)) # Draw all the sprite lists that we have self.platform_list.draw(screen) self.enemy_list.draw(screen) def shift_world(self, shift_x): """ When the user moves left/right and we need to scroll everything: """ # Keep track of the shift amount self.world_shift += shift_x # Go through all the sprite lists and shift for platform in self.platform_list: platform.rect.x += shift_x for enemy in self.enemy_list: enemy.rect.x += shift_x def shift_world_y(self, shift_y): self.world_shift += shift_y for platform in self.platform_list: platform.rect.y += shift_y for enemy in self.enemy_list: enemy.rect.y += shift_y # Create platforms for the level class Level_01(Level): """ Definition for level 1. """ def __init__(self, player): """ Create level 1. """ # Call the parent constructor Level.__init__(self, player) self.background = pygame.transform.scale(pygame.image.load("background_4.png").convert_alpha(), (1366,768)) self.background.set_colorkey(constants.WHITE) self.level_limit = -2500 # Array with type of platform, and x, y location of the platform. level = [#Bottom Border [platforms.RED_MIDDLE, -9, 743], [platforms.RED_MIDDLE, 16, 743], [platforms.RED_MIDDLE, 41, 743], [platforms.RED_MIDDLE, 66, 743], [platforms.RED_MIDDLE, 91, 743], [platforms.RED_MIDDLE, 116, 743], [platforms.RED_MIDDLE, 141, 743], [platforms.RED_MIDDLE, 166, 743], [platforms.RED_MIDDLE, 191, 743], [platforms.RED_MIDDLE, 216, 743], [platforms.RED_MIDDLE, 241, 743], [platforms.RED_MIDDLE, 266, 743], [platforms.RED_MIDDLE, 291, 743], [platforms.RED_MIDDLE, 316, 743], [platforms.RED_MIDDLE, 341, 743], [platforms.RED_MIDDLE, 366, 743], [platforms.RED_MIDDLE, 391, 743], [platforms.RED_MIDDLE, 416, 743], [platforms.RED_MIDDLE, 441, 743], [platforms.RED_MIDDLE, 466, 743], [platforms.RED_MIDDLE, 491, 743], [platforms.RED_MIDDLE, 516, 743], [platforms.RED_MIDDLE, 541, 743], [platforms.RED_MIDDLE, 566, 743], [platforms.RED_MIDDLE, 591, 743], [platforms.RED_MIDDLE, 616, 743], [platforms.RED_MIDDLE, 641, 743], [platforms.RED_MIDDLE, 666, 743], [platforms.RED_MIDDLE, 691, 743], [platforms.RED_MIDDLE, 716, 743], [platforms.RED_MIDDLE, 741, 743], [platforms.RED_MIDDLE, 766, 743], [platforms.RED_MIDDLE, 791, 743], [platforms.RED_MIDDLE, 816, 743], [platforms.RED_MIDDLE, 841, 743], [platforms.RED_MIDDLE, 866, 743], [platforms.RED_MIDDLE, 891, 743], [platforms.RED_MIDDLE, 916, 743], [platforms.RED_MIDDLE, 941, 743], [platforms.RED_MIDDLE, 966, 743], [platforms.RED_MIDDLE, 991, 743], [platforms.RED_MIDDLE, 1016, 743], [platforms.RED_MIDDLE, 1041, 743], [platforms.RED_MIDDLE, 1066, 743], [platforms.RED_MIDDLE, 1091, 743], [platforms.RED_MIDDLE, 1116, 743], [platforms.RED_MIDDLE, 1141, 743], [platforms.RED_MIDDLE, 1166, 743], [platforms.RED_MIDDLE, 1191, 743], [platforms.RED_MIDDLE, 1216, 743], [platforms.RED_MIDDLE, 1241, 743], [platforms.RED_MIDDLE, 1266, 743], [platforms.RED_MIDDLE, 1291, 743], [platforms.RED_MIDDLE, 1316, 743], [platforms.RED_MIDDLE, 1341, 743], #Right Border [platforms.RED_MIDDLE, 1341, 743], [platforms.RED_MIDDLE, 1341, 718], [platforms.RED_MIDDLE, 1341, 693], [platforms.RED_MIDDLE, 1341, 668], [platforms.RED_MIDDLE, 1341, 643], [platforms.RED_MIDDLE, 1341, 618], [platforms.RED_MIDDLE, 1341, 593], [platforms.RED_MIDDLE, 1341, 568], [platforms.RED_MIDDLE, 1341, 543], [platforms.RED_MIDDLE, 1341, 518], [platforms.RED_MIDDLE, 1341, 493], [platforms.RED_MIDDLE, 1341, 468], [platforms.RED_MIDDLE, 1341, 443], [platforms.RED_MIDDLE, 1341, 418], [platforms.RED_MIDDLE, 1341, 393], [platforms.RED_MIDDLE, 1341, 368], [platforms.RED_MIDDLE, 1341, 343], [platforms.RED_MIDDLE, 1341, 318], [platforms.RED_MIDDLE, 1341, 293], [platforms.RED_MIDDLE, 1341, 268], [platforms.RED_MIDDLE, 1341, 243], [platforms.RED_MIDDLE, 1341, 218], [platforms.RED_MIDDLE, 1341, 193], [platforms.RED_MIDDLE, 1341, 168], [platforms.RED_MIDDLE, 1341, 143], [platforms.RED_MIDDLE, 1341, 118], [platforms.RED_MIDDLE, 1341, 93], [platforms.RED_MIDDLE, 1341, 68], [platforms.RED_MIDDLE, 1341, 43], [platforms.RED_MIDDLE, 1341, 18], [platforms.RED_MIDDLE, 1341, -7], #Left Border [platforms.RED_MIDDLE, 0, 743], [platforms.RED_MIDDLE, 0, 718], [platforms.RED_MIDDLE, 0, 693], [platforms.RED_MIDDLE, 0, 668], [platforms.RED_MIDDLE, 0, 643], [platforms.RED_MIDDLE, 0, 618], [platforms.RED_MIDDLE, 0, 593], [platforms.RED_MIDDLE, 0, 568], [platforms.RED_MIDDLE, 0, 543], [platforms.RED_MIDDLE, 0, 518], [platforms.RED_MIDDLE, 0, 493], [platforms.RED_MIDDLE, 0, 468], [platforms.RED_MIDDLE, 0, 443], [platforms.RED_MIDDLE, 0, 418], [platforms.RED_MIDDLE, 0, 393], [platforms.RED_MIDDLE, 0, 368], [platforms.RED_MIDDLE, 0, 343], [platforms.RED_MIDDLE, 0, 318], [platforms.RED_MIDDLE, 0, 293], [platforms.RED_MIDDLE, 0, 268], [platforms.RED_MIDDLE, 0, 243], [platforms.RED_MIDDLE, 0, 218], [platforms.RED_MIDDLE, 0, 193], [platforms.RED_MIDDLE, 0, 168], [platforms.RED_MIDDLE, 0, 143], [platforms.RED_MIDDLE, 0, 118], [platforms.RED_MIDDLE, 0, 93], [platforms.RED_MIDDLE, 0, 68], [platforms.RED_MIDDLE, 0, 43], [platforms.RED_MIDDLE, 0, 18], [platforms.RED_MIDDLE, 0, -7], #Top Border [platforms.RED_MIDDLE, -9, 0], [platforms.RED_MIDDLE, 16, 0], [platforms.RED_MIDDLE, 41, 0], [platforms.RED_MIDDLE, 66, 0], [platforms.RED_MIDDLE, 91, 0], [platforms.RED_MIDDLE, 116, 0], [platforms.RED_MIDDLE, 141, 0], [platforms.RED_MIDDLE, 166, 0], [platforms.RED_MIDDLE, 191, 0], [platforms.RED_MIDDLE, 216, 0], [platforms.RED_MIDDLE, 241, 0], [platforms.RED_MIDDLE, 266, 0], [platforms.RED_MIDDLE, 291, 0], [platforms.RED_MIDDLE, 316, 0], [platforms.RED_MIDDLE, 341, 0], [platforms.RED_MIDDLE, 366, 0], [platforms.RED_MIDDLE, 391, 0], [platforms.RED_MIDDLE, 416, 0], [platforms.RED_MIDDLE, 441, 0], [platforms.RED_MIDDLE, 466, 0], [platforms.RED_MIDDLE, 491, 0], [platforms.RED_MIDDLE, 516, 0], [platforms.RED_MIDDLE, 541, 0], [platforms.RED_MIDDLE, 566, 0], [platforms.RED_MIDDLE, 591, 0], [platforms.RED_MIDDLE, 616, 0], [platforms.RED_MIDDLE, 641, 0], [platforms.RED_MIDDLE, 666, 0], [platforms.RED_MIDDLE, 691, 0], [platforms.RED_MIDDLE, 716, 0], [platforms.RED_MIDDLE, 741, 0], [platforms.RED_MIDDLE, 766, 0], [platforms.RED_MIDDLE, 791, 0], [platforms.RED_MIDDLE, 816, 0], [platforms.RED_MIDDLE, 841, 0], [platforms.RED_MIDDLE, 866, 0], [platforms.RED_MIDDLE, 891, 0], [platforms.RED_MIDDLE, 916, 0], [platforms.RED_MIDDLE, 941, 0], [platforms.RED_MIDDLE, 966, 0], [platforms.RED_MIDDLE, 991, 0], [platforms.RED_MIDDLE, 1016, 0], [platforms.RED_MIDDLE, 1041, 0], [platforms.RED_MIDDLE, 1066, 0], [platforms.RED_MIDDLE, 1091, 0], [platforms.RED_MIDDLE, 1116, 0], [platforms.RED_MIDDLE, 1141, 0], [platforms.RED_MIDDLE, 1166, 0], [platforms.RED_MIDDLE, 1191, 0], [platforms.RED_MIDDLE, 1216, 0], [platforms.RED_MIDDLE, 1241, 0], [platforms.RED_MIDDLE, 1266, 0], [platforms.RED_MIDDLE, 1291, 0], [platforms.RED_MIDDLE, 1316, 0], [platforms.RED_MIDDLE, 1341, 0], #Left Stairs Step 1 [platforms.RED_MIDDLE, 141, 718], [platforms.RED_MIDDLE, 166, 718], [platforms.RED_MIDDLE, 191, 718], [platforms.RED_MIDDLE, 216, 718], [platforms.RED_MIDDLE, 241, 718], [platforms.RED_MIDDLE, 266, 718], [platforms.RED_MIDDLE, 291, 718], [platforms.RED_MIDDLE, 316, 718], [platforms.RED_MIDDLE, 341, 718], [platforms.RED_MIDDLE, 366, 718], [platforms.RED_MIDDLE, 391, 718], [platforms.RED_MIDDLE, 416, 718], [platforms.RED_MIDDLE, 441, 718], [platforms.RED_MIDDLE, 466, 718], [platforms.RED_MIDDLE, 491, 718], [platforms.RED_MIDDLE, 516, 718], [platforms.RED_MIDDLE, 541, 718], [platforms.RED_MIDDLE, 566, 718], [platforms.RED_MIDDLE, 591, 718], [platforms.RED_MIDDLE, 616, 718], [platforms.RED_MIDDLE, 641, 718], [platforms.RED_MIDDLE, 666, 718], [platforms.RED_MIDDLE, 691, 718], [platforms.RED_MIDDLE, 716, 718], [platforms.RED_MIDDLE, 741, 718], [platforms.RED_MIDDLE, 766, 718], #Left Stairs Step 2 [platforms.RED_MIDDLE, 166, 693], [platforms.RED_MIDDLE, 191, 693], [platforms.RED_MIDDLE, 216, 693], [platforms.RED_MIDDLE, 241, 693], [platforms.RED_MIDDLE, 266, 693], [platforms.RED_MIDDLE, 291, 693], [platforms.RED_MIDDLE, 316, 693], [platforms.RED_MIDDLE, 341, 693], #Left Stairs Step 3 [platforms.RED_MIDDLE, 191, 668], [platforms.RED_MIDDLE, 216, 668], [platforms.RED_MIDDLE, 241, 668], [platforms.RED_MIDDLE, 266, 668], [platforms.RED_MIDDLE, 291, 668], #Left Stairs Step 4 [platforms.RED_MIDDLE, 216, 643], [platforms.RED_MIDDLE, 241, 643], [platforms.RED_MIDDLE, 266, 643], [platforms.RED_MIDDLE, 291, 643], #Left Stairs Step 5 [platforms.RED_MIDDLE, 241, 618], [platforms.RED_MIDDLE, 266, 618], [platforms.RED_MIDDLE, 291, 618], #Right AI Base Spot and pillar [platforms.RED_MIDDLE, 1166, 718], [platforms.RED_MIDDLE, 1166, 693], [platforms.RED_MIDDLE, 1166, 668], [platforms.RED_MIDDLE, 1166, 643], [platforms.RED_MIDDLE, 1166, 618], [platforms.RED_MIDDLE, 1166, 593], [platforms.RED_MIDDLE, 1166, 568], [platforms.RED_MIDDLE, 1166, 543], [platforms.RED_MIDDLE, 1166, 518], [platforms.RED_MIDDLE, 1166, 493], [platforms.RED_MIDDLE, 1166, 468], [platforms.RED_MIDDLE, 1166, 443], [platforms.RED_MIDDLE, 1191, 718], [platforms.RED_MIDDLE, 1191, 693], [platforms.RED_MIDDLE, 1191, 668], [platforms.RED_MIDDLE, 1191, 643], [platforms.RED_MIDDLE, 1191, 618], [platforms.RED_MIDDLE, 1191, 593], [platforms.RED_MIDDLE, 1191, 568], [platforms.RED_MIDDLE, 1191, 543], [platforms.RED_MIDDLE, 1191, 518], [platforms.RED_MIDDLE, 1191, 493], [platforms.RED_MIDDLE, 1191, 468], [platforms.RED_MIDDLE, 1191, 443], #Jumping platforms [platforms.RED_MIDDLE, 1216, 668], [platforms.RED_MIDDLE, 1316, 593], [platforms.RED_MIDDLE, 1216, 518], [platforms.RED_MIDDLE, 866, 718], [platforms.RED_MIDDLE, 891, 718], [platforms.RED_MIDDLE, 916, 718], [platforms.RED_MIDDLE, 941, 718], [platforms.RED_MIDDLE, 966, 718], [platforms.RED_MIDDLE, 991, 718], [platforms.RED_MIDDLE, 1016, 718], [platforms.RED_MIDDLE, 1041, 718], [platforms.RED_MIDDLE, 1066, 718], [platforms.RED_MIDDLE, 1091, 718], [platforms.RED_MIDDLE, 1116, 718], [platforms.RED_MIDDLE, 1141, 718], [platforms.RED_MIDDLE, 1091, 593], [platforms.RED_MIDDLE, 1116, 593], [platforms.RED_MIDDLE, 1141, 593], [platforms.RED_MIDDLE, 1091, 568], [platforms.RED_MIDDLE, 1116, 568], [platforms.RED_MIDDLE, 1141, 568], [platforms.RED_MIDDLE, 1091, 543], [platforms.RED_MIDDLE, 1116, 543], [platforms.RED_MIDDLE, 1141, 543], [platforms.RED_MIDDLE, 1091, 518], [platforms.RED_MIDDLE, 1116, 518], [platforms.RED_MIDDLE, 1141, 518], [platforms.RED_MIDDLE, 1091, 493], [platforms.RED_MIDDLE, 1116, 493], [platforms.RED_MIDDLE, 1141, 493], [platforms.RED_MIDDLE, 1091, 468], [platforms.RED_MIDDLE, 1116, 468], [platforms.RED_MIDDLE, 1141, 468], [platforms.RED_MIDDLE, 1091, 443], [platforms.RED_MIDDLE, 1116, 443], [platforms.RED_MIDDLE, 1141, 443], [platforms.RED_MIDDLE, 1066, 593], [platforms.RED_MIDDLE, 1066, 568], [platforms.RED_MIDDLE, 1066, 543], [platforms.RED_MIDDLE, 1066, 518], [platforms.RED_MIDDLE, 1066, 493], [platforms.RED_MIDDLE, 1066, 468], [platforms.RED_MIDDLE, 1066, 443], #First upper platform [platforms.RED_MIDDLE, 891, 368], [platforms.RED_MIDDLE, 891, 343], [platforms.RED_MIDDLE, 866, 368], [platforms.RED_MIDDLE, 866, 343], [platforms.RED_MIDDLE, 841, 368], [platforms.RED_MIDDLE, 841, 343], [platforms.RED_MIDDLE, 816, 368], [platforms.RED_MIDDLE, 816, 343], [platforms.RED_MIDDLE, 791, 368], [platforms.RED_MIDDLE, 791, 343], [platforms.RED_MIDDLE, 766, 368], [platforms.RED_MIDDLE, 766, 343], [platforms.RED_MIDDLE, 741, 368], [platforms.RED_MIDDLE, 741, 343], [platforms.RED_MIDDLE, 716, 368], [platforms.RED_MIDDLE, 716, 343], [platforms.RED_MIDDLE, 691, 368], [platforms.RED_MIDDLE, 691, 343], [platforms.RED_MIDDLE, 666, 368], [platforms.RED_MIDDLE, 666, 343], [platforms.RED_MIDDLE, 641, 368], [platforms.RED_MIDDLE, 641, 343], #Gap is above here [platforms.RED_MIDDLE, 616, 368], [platforms.RED_MIDDLE, 616, 343], [platforms.RED_MIDDLE, 616, 318], [platforms.RED_MIDDLE, 591, 368], [platforms.RED_MIDDLE, 591, 343], [platforms.RED_MIDDLE, 591, 318], [platforms.RED_MIDDLE, 591, 293], [platforms.RED_MIDDLE, 566, 368], [platforms.RED_MIDDLE, 566, 343], [platforms.RED_MIDDLE, 566, 318], [platforms.RED_MIDDLE, 541, 368], [platforms.RED_MIDDLE, 541, 343], [platforms.RED_MIDDLE, 516, 368], [platforms.RED_MIDDLE, 516, 343], [platforms.RED_MIDDLE, 491, 368], [platforms.RED_MIDDLE, 491, 343], [platforms.RED_MIDDLE, 466, 368], [platforms.RED_MIDDLE, 466, 343], [platforms.RED_MIDDLE, 441, 368], [platforms.RED_MIDDLE, 441, 343], [platforms.RED_MIDDLE, 416, 368], [platforms.RED_MIDDLE, 416, 343], [platforms.RED_MIDDLE, 391, 368], [platforms.RED_MIDDLE, 391, 343], [platforms.RED_MIDDLE, 366, 368], [platforms.RED_MIDDLE, 366, 343], [platforms.RED_MIDDLE, 341, 368], [platforms.RED_MIDDLE, 341, 343], [platforms.RED_MIDDLE, 316, 368], [platforms.RED_MIDDLE, 316, 343], [platforms.RED_MIDDLE, 291, 368], [platforms.RED_MIDDLE, 291, 343], [platforms.RED_MIDDLE, 266, 368], [platforms.RED_MIDDLE, 266, 343], [platforms.RED_MIDDLE, 241, 368], [platforms.RED_MIDDLE, 241, 343], #Second upper platform [platforms.RED_MIDDLE, 866, 218], [platforms.RED_MIDDLE, 891, 218], [platforms.RED_MIDDLE, 841, 218], [platforms.RED_MIDDLE, 816, 218], [platforms.RED_MIDDLE, 791, 218], [platforms.RED_MIDDLE, 766, 218], [platforms.RED_MIDDLE, 741, 218], [platforms.RED_MIDDLE, 716, 218], [platforms.RED_MIDDLE, 691, 218], [platforms.RED_MIDDLE, 491, 218], [platforms.RED_MIDDLE, 466, 218], [platforms.RED_MIDDLE, 441, 218], [platforms.RED_MIDDLE, 416, 218], [platforms.RED_MIDDLE, 391, 218], #Gap is above here [platforms.RED_MIDDLE, 366, 193], [platforms.RED_MIDDLE, 366, 218], [platforms.RED_MIDDLE, 341, 218], [platforms.RED_MIDDLE, 341, 168], [platforms.RED_MIDDLE, 341, 193], [platforms.RED_MIDDLE, 316, 218], [platforms.RED_MIDDLE, 316, 193], [platforms.RED_MIDDLE, 291, 218], [platforms.RED_MIDDLE, 266, 218], [platforms.RED_MIDDLE, 241, 218], [platforms.RED_MIDDLE, 141, 218], [platforms.RED_MIDDLE, 166, 218], [platforms.RED_MIDDLE, 191, 218], [platforms.RED_MIDDLE, 216, 218], #Third Upper platform [platforms.RED_MIDDLE, 16, 91], [platforms.RED_MIDDLE, 41, 91], [platforms.RED_MIDDLE, 66, 91], [platforms.RED_MIDDLE, 91, 91], [platforms.RED_MIDDLE, 116, 91], [platforms.RED_MIDDLE, 141, 91], [platforms.RED_MIDDLE, 166, 91], [platforms.RED_MIDDLE, 191, 91], [platforms.RED_MIDDLE, 216, 91], [platforms.RED_MIDDLE, 241, 91], [platforms.RED_MIDDLE, 491, 91], [platforms.RED_MIDDLE, 516, 91], [platforms.RED_MIDDLE, 541, 91], [platforms.RED_MIDDLE, 566, 91], [platforms.RED_MIDDLE, 591, 91], [platforms.RED_MIDDLE, 616, 91], [platforms.RED_MIDDLE, 641, 91], [platforms.RED_MIDDLE, 666, 91], [platforms.RED_MIDDLE, 691, 91], [platforms.RED_MIDDLE, 716, 91], [platforms.RED_MIDDLE, 741, 91], [platforms.RED_MIDDLE, 766, 91], [platforms.RED_MIDDLE, 791, 91], [platforms.RED_MIDDLE, 816, 91], [platforms.RED_MIDDLE, 841, 91], [platforms.RED_MIDDLE, 866, 91], [platforms.RED_MIDDLE, 891, 91], [platforms.RED_MIDDLE, 916, 91], [platforms.RED_MIDDLE, 941, 91], [platforms.RED_MIDDLE, 966, 91], [platforms.RED_MIDDLE, 991, 91], [platforms.RED_MIDDLE, 1016, 91], [platforms.RED_MIDDLE, 1041, 91], [platforms.RED_MIDDLE, 1066, 91], [platforms.RED_MIDDLE, 1091, 91], [platforms.RED_MIDDLE, 1116, 91], [platforms.RED_MIDDLE, 1141, 91], [platforms.RED_MIDDLE, 1166, 91], [platforms.RED_MIDDLE, 1191, 91], [platforms.RED_MIDDLE, 1216, 91], [platforms.RED_MIDDLE, 1241, 91], [platforms.RED_MIDDLE, 1266, 91], [platforms.RED_MIDDLE, 1291, 91], [platforms.RED_MIDDLE, 1316, 91], [platforms.RED_MIDDLE, 1341, 91], [platforms.RED_MIDDLE, 1016, 216], [platforms.RED_MIDDLE, 1041, 216], [platforms.RED_MIDDLE, 1066, 216], [platforms.RED_MIDDLE, 1091, 216], [platforms.RED_MIDDLE, 1116, 216], [platforms.RED_MIDDLE, 1141, 216], [platforms.RED_MIDDLE, 1166, 216], [platforms.RED_MIDDLE, 1191, 216], [platforms.RED_MIDDLE, 1216, 216], [platforms.RED_MIDDLE, 1241, 216], [platforms.RED_MIDDLE, 1266, 216], [platforms.RED_MIDDLE, 1291, 216], [platforms.RED_MIDDLE, 1316, 216], [platforms.RED_MIDDLE, 1341, 216], [platforms.RED_MIDDLE, 1066, 341], [platforms.RED_MIDDLE, 1091, 341], [platforms.RED_MIDDLE, 1116, 341], [platforms.RED_MIDDLE, 1141, 341], [platforms.RED_MIDDLE, 1166, 341], [platforms.RED_MIDDLE, 1191, 341], [platforms.RED_MIDDLE, 1216, 341], [platforms.RED_MIDDLE, 1241, 341], [platforms.RED_MIDDLE, 1266, 341], [platforms.RED_MIDDLE, 1291, 341], [platforms.RED_MIDDLE, 1316, 341], [platforms.RED_MIDDLE, 1341, 341], ] # Go through the array above and add platforms for platform in level: block = platforms.Platform(platform[0]) block.rect.x = platform[1] block.rect.y = platform[2] block.player = self.player self.platform_list.add(block) #First horizontal platform block = platforms.MovingPlatform(platforms.STONE_PLATFORM_MIDDLE) block.rect.x = 425 block.rect.y = 545 block.boundary_left = 350 block.boundary_right = 530 block.change_x = 2 block.player = self.player block.level = self self.platform_list.add(block) #Second horizontal platform block = platforms.MovingPlatform(platforms.STONE_PLATFORM_MIDDLE) block.rect.x = 670 block.rect.y = 545 block.boundary_left = 570 block.boundary_right = 850 block.change_x = 4 block.player = self.player block.level = self self.platform_list.add(block) #Raccoon block = platforms.MovingPlatform(platforms.RACCOON) block.rect.x = 1000 block.rect.y = 698 block.boundary_left = 880 block.boundary_right = 1040 block.change_x = 13 block.player = self.player block.level = self self.platform_list.add(block) #second vertical platform block = platforms.MovingPlatform(platforms.STONE_PLATFORM_MIDDLE) block.rect.x = 968 block.rect.y = 500 block.boundary_top = 380 block.boundary_bottom = 610 block.change_y = 5 block.player = self.player block.level = self self.platform_list.add(block) #Beginning vertical platform block = platforms.MovingPlatform(platforms.STONE_PLATFORM_MIDDLE) block.rect.x = 66 block.rect.y = 500 block.boundary_top = 380 block.boundary_bottom = 618 block.change_y = 3 block.player = self.player block.level = self self.platform_list.add(block)
from turtle import Screen from snake import Snake # Importar la clase Snake from food import Food # Importar clase food from scoreboard import Scoreboard # Importar clase score import time screen = Screen() # Ventana screen.setup(width=600, height=600) # Tamaño de la ventana screen.bgcolor("black") # Color de fondo de la ventana screen.title("Snake") # Titulo de la ventana screen.tracer(0) # Sin trancision en ventana snake = Snake() # Clase snake food = Food() # Clase food score = Scoreboard() screen.listen() # Movimiento de la serpiente screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") game_is_on = True # Activar el juego while game_is_on: # Mientras el juego este activado screen.update() # Actualizar ventana time.sleep(0.1) # Tiempo de transicion snake.move() # Actualizacion de la serpiente # Detectar food if snake.head.distance(food) < 25: food.refresh() snake.extend() score.increase_score() #print("nom nom") # Detectar pared if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: game_is_on = False score.game_over() # Detectar cuerpo de serpiente for segment in snake.segments[1:]: if snake.head.distance(segment) < 10: game_is_on = False score.game_over() screen.exitonclick() # Salir con un clic
""" Quick go to work with denied persons list Versions 01a - use a classic read file format, rather than an csv style """ import csv def ascii_file_no_lines(filename): """ check how many lines in ascii file # http://gsp.humboldt.edu/OLM/Courses/GSP_318/03_3_ReadingFiles.html """ TheFile = open(filename, "r") TheLine = "r@nd@nw@rd" # <= a starting assignment that won't be used numlines = 0 while (TheLine != ""): TheLine = TheFile.readline() # read the next line in the file numlines += 1 TheFile.close() return("File has {} lines.".format(numlines)) def clean_string(a_string): """ clean up a single ascii a_string This is the key tidy up function! Is used in convert_ascii_to_csvtable """ # remove left and right " z_string = a_string.rstrip('\n') b_string = z_string.lstrip('"') c_string = b_string.rsplit('"') # remove empty ''. ' '. ' ', etc. spacer = ' ' spacer_list = [] for i in range(1, 10): new_spacer = spacer * i spacer_list.append(new_spacer) d_list = [] for item in c_string: if item not in spacer_list: d_list.append(item) # need to remove empty columns created by '', '', # pass return d_list def convert_ascii_to_csvtable(filename, max_lines): """ convert an ascii file to a csv file # http://gsp.humboldt.edu/OLM/Courses/GSP_318/03_3_ReadingFiles.html """ table = [] TheFile = open(filename, "r") TheLine = "r@nd@nw@rd" # <= a starting assignment that won't be used numlines = 0 while (TheLine != "") and numlines < max_lines: TheLine = TheFile.readline() # read the next line in the file table.append(clean_string(TheLine)) numlines += 1 TheFile.close() return table def remove_empty_rows_and_cols(table): """ A bespoke function to remove cases of 2 empty columns between columns with data It could be done in Excel usually, but done as practice here In real life you would want this if files had hundreds of columns """ body = table[1:] header = table[:1] # remove empty remove_empty_rows for row in body: if row == ['']: body.remove(row) # establish ranges len_body = len(body) for item in header: len_header = len(item) new_table = [] # first create a new body. (Much less confusing to create new one than replace rows in old one) for i in range(len_body): new_row = [] for j in range(len_header): if body[i][j] != header[0][j]: new_row.append(body[i][j]) new_table.append(new_row) # now have to remove ''s in len_header. Will do as above for ease another_row = [] for i in range(len_header): if header[0][i] != '': another_row.append(header[0][i]) new_table.insert(0, another_row) return new_table def write_csv_file(csv_table, file_name): """ USED FROM RICE MOOC - thank you! Input: Nested list csv_table and a string file_name Action: Write fields in csv_table into a comma-separated CSV file with the name file_name HOWEVER: there are several empty columns. It is simply easier to just delete these in Excel! THE ALTERNATIVE would be to read as list of dictionaries and delete ('','') pairs - but not worth it """ with open(file_name, 'w', newline='') as csv_file: csv_writer = csv.writer(csv_file, delimiter=',', quoting=csv.QUOTE_MINIMAL) for row in csv_table: csv_writer.writerow(row) # = = = Test and develop code below where input_file = ("/Users/RAhmed/Atom_projects/Dictionaries_practice/denied_persons_list.txt") output_file = ("/Users/RAhmed/Atom_projects/Dictionaries_practice/denied_persons_list.csv") deny01_length = ascii_file_no_lines(input_file) print(deny01_length) deny01 = convert_ascii_to_csvtable(input_file, 40) # print(deny01) deny02 = remove_empty_rows_and_cols(deny01) print(deny02) deny03 = write_csv_file(deny02, output_file)
""" Data wrangling for this project. DATA SOURCE FILES are given in code book. They have been downloaded and stored locally. REPLICATING THIS?: Need to add your own correct file paths and file names. """ import csv import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # utility functions for data wrangling def read_csv_file(file_name): """ Given a CSV file, read the data into a nested list Input: String corresponding to comma-separated CSV file Output: Lists of lists consisting of the fields in the CSV file """ with open(file_name, newline='') as csv_file: # don't need to explicitly close the file now csv_table = [] csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: csv_table.append(row) return csv_table def write_csv_file(csv_table, file_name): """ Input: Nested list csv_table and a string file_name Action: Write fields in csv_table into a comma-separated CSV file with the name file_name """ with open(file_name, 'w', newline='') as csv_file: csv_writer = csv.writer(csv_file, delimiter=',', quoting=csv.QUOTE_MINIMAL) for row in csv_table: csv_writer.writerow(row) def has_these_col_variables(data_file, category_list, position_of_index): """ Idea: > Creates a list of the actual indices you want, from a large csv file that has numerous indices including many you do not want > With this list you can compare a number of csv files to see whether they have the same indices NOTE: > Will need the categories_list entries to be actual variables responses Why?: > Use this list of indices for making data files that only have the data you want Input: > data_file: a (large) csv file of data with a header row. (String) > category_list: a list of the variables by which you want to select your subset of data. (List of strings) > position_of_index: the numerical position in each row that has the index you wish to list. (Integer) Output: > A list of strings that has the indices you want Mutates input?: > No """ output_list = [] for row in data_file: index = 0 for category in category_list: if category in row: index += 1 if index == len(category_list): output_list.append(row[position_of_index]) return output_list def simple_get_desired_indices(data_file, position_of_index): """ Idea: > Creates a list of the actual indices you want, from a large csv file that has numerous indices including many you do not want > With this list you can compare a number of csv files to see whether they have the same indices NOTE: > Will need the categories_list entries to be actual variables responses Why?: > Use this list of indices for making data files that only have the data you want Input: > data_file: a (large) csv file of data with a header row. (String) > position_of_index: the numerical position in each row that has the index you wish to list. (Integer) > rows_to_pop: the number of leading/header rows to pop in the output_list, to just get list of indices Output: > A list of strings that has the indices you want Mutates input?: > No """ output_list = [] for row in data_file: output_list.append(row[position_of_index]) # you also have header value that has to be removed output_list.pop(0) return output_list def has_these_row_variables(data_file, category_list, input_index, output_index): """ Idea: > Creates a list of the actual indices you want, from a large csv file that has numerous indices including many you do not want > Here, the item in the category list may or may not be in the row > With this list you can compare a number of csv files to see whether they have the same indices NOTE: > Will need the categories_list entries to be actual variables responses Why?: > Use this list of indices for making data files that only have the data you want Input: > data_file: a (large) csv file of data with a header row. (String) > category_list: a list of the variables by which you want to select your subset of data. (List of strings) > position_of_index: the numerical position in each row that has the index you wish to list. (Integer) Output: > A list of strings that has the indices you want Mutates input?: > No """ output_list = [] for row in data_file: if row[input_index] in category_list: output_list.append(row[output_index]) return output_list def cat_and_years_only(data_file, responses_list): """ Idea: > Creates a file only of the actual observations you want, from a large csv file that has numerous observations including many you do not want Why?: > This file is easier to manage than (e.g.) a 100,000 observation file, 99% of which you don't care about NOTE: > Will need the categories_list entries to be responses you want Input: > data_file: a (large) csv file of data with a header row. (String) > category_list: a list of the variables by which you want to select your subset of data. (List of strings) Output: > A much smaller file? Mutates input?: > No """ header = data_file[0] output_list = [] for row in data_file: index = 0 for response in responses_list: if response in row: index += 1 if index == len(responses_list): output_list.append(row) # put back header output_list.insert(0, header) return output_list # = = = data wrangling below here = = = # STEP 1: check same local authority data in each file print("\nStep 1") # get huge csv file with all UK childhood obesity data, filename = '/Users/RAhmed/data store/NCMPLocalAuthorityProfile-DistrictUA.data.csv' data_file = read_csv_file(filename) # get correct local authority indices in 2015/16 for the 'Prevalence of obesity' category for 4-5 year olds category_list = ['Reception: Prevalence of obesity', 'District & UA', '4-5 yrs', '2015/16'] list_2015_45 = has_these_col_variables(data_file, category_list, 4) print("Number of local authorities in obesity data for 4-5-year olds:", len(list_2015_45)) # get correct local authority indices in 2015/16 for the 'Prevalence of obesity' category for 10-11 year olds category_list = [ 'Year 6: Prevalence of overweight (including obese)', 'District & UA', '10-11 yrs', '2015/16'] list_2015_1011 = has_these_col_variables(data_file, category_list, 4) print("Number of local authorities in obesity data for 10-11-year olds:", len(list_2015_1011)) # check that the data for 4-5-year olds and 10-11-year olds is for same local authorities. If so result is True print("Obesity data for 4-5-year olds is same as for 10-11-year olds?:", list_2015_45.sort() == list_2015_1011.sort()) # get csv file with UK local authority deprivation data (IMD). filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/IMD.csv' data_file = read_csv_file(filename) # Check same local authorities with IMD data as for childhood obesity data. If so result is True list_2015_IMD = simple_get_desired_indices(data_file, 0) print("Number of local authorities in IMD data:", len(list_2015_IMD)) # check that the data IMD is for same local authorities.If so result is True print("Local authorities in IMD files same as for obesity data?:", list_2015_IMD.sort() == list_2015_1011.sort()) # get csv file with UK local authority household gross domestic income per head (GDHIph). filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/2015_LA_GDHI_perhead.csv' data_file = read_csv_file(filename) # Check same local authorities with GDHIph data as for childhood obesity data. If so result is True category_list = ['North East', 'North West', 'Yorkshire and The Humber', 'East Midlands', 'West Midlands', 'East of England', 'London', 'South East', 'South West'] list_2015_GDHIph = has_these_row_variables(data_file, category_list, 0, 1) print("Number of local authorities in GDHI data:", len(list_2015_GDHIph)) # check that the data IMD is for same local authorities.If so result is True print("Local authorities in GDHI file same as for obesity data?:", list_2015_GDHIph.sort() == list_2015_1011.sort()) # STEP 2: need to pare down the multi-year, nearly 100,000 entries for childhood obesity data to just the # two categories (4-5-year olds, 10-11-year olds) I want for the given year. # Needs a dedicated function called cat_and_years_only print("\nStep 2") # for 4-5-year olds filename = '/Users/RAhmed/data store/NCMPLocalAuthorityProfile-DistrictUA.data.csv' data_file = read_csv_file(filename) # the following responses will get the observations you need for 4-5-year olds responses_list = ['Reception: Prevalence of obesity', 'District & UA', '4-5 yrs', '2015/16'] obesity_45 = cat_and_years_only(data_file, responses_list) print("Visual check of file below:") print(obesity_45[:2]) # <= visually check content # <= check correct length. (Subtract 1 due to header) print("Number of local authorities in new file for 4-5-year old data:", len(obesity_45) - 1) # write to a permanent file write_csv_file(obesity_45, '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/obesity_45.csv') # for 10-11-year olds # the following responses will get the observations you need for 10-11-year olds responses_list = ['Year 6: Prevalence of obesity', 'District & UA', '10-11 yrs', '2015/16'] obesity_1011 = cat_and_years_only(data_file, responses_list) print("Visual check of file below:") print(obesity_1011[:2]) # <= visually check content # <= check correct length. (Subtract 1 due to header) print("Number of local authorities in new file for 10-11-year old data:", len(obesity_1011) - 1) # write to a permanent file write_csv_file(obesity_1011, '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/obesity_1011.csv') # STEP 3: harmonise name of key local authority index across all files. Use name given in (both) obesity_45 & obesity_1011 print("\nStep 3") filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/obesity_1011.csv' data_file = read_csv_file(filename) common_index_name = data_file[0][4] print("Common index name will be this: ", common_index_name) # this checks header, gives name in correct location and checks, for IMD data filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/IMD.csv' data_file = read_csv_file(filename) data_file[0][0] = common_index_name newname = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/IMD_CI.csv' write_csv_file(data_file, newname) # this checks header, gives name in correct location and checks, for GDHI data filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/2015_LA_GDHI_perhead.csv' data_file = read_csv_file(filename) data_file[0][1] = common_index_name newname = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/2015_LA_GDHI_perhead_CI.csv' write_csv_file(data_file, newname) # STEP 4: for 4-5-year olds, import obesity data in pandas and only keep the variables I want # and merge with IMD and GHDI data print("\nStep 4") filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/obesity_45.csv' df = pd.read_csv(filename, low_memory=False) df45 = df[['Area Code', 'Parent Name', 'Area Name', 'Value']] filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/IMD_CI.csv' df = pd.read_csv(filename, low_memory=False) dfIMD = df[['Area Code', 'IMD - Average score', 'IMD - Proportion of LSOAs in most deprived 10% nationally']] filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/2015_LA_GDHI_perhead_CI.csv' df = pd.read_csv(filename, low_memory=False) dfGDHI = df[['Area Code', '2015']] df45 = pd.merge(df45, dfIMD, on='Area Code') df45 = pd.merge(df45, dfGDHI, on='Area Code') # rename some header titles df45 = df45.rename({'Value': 'Obesity proportion', '2015': 'GDHI'}, axis='columns') # STEP 5: for 10-11-year olds, do as for 4-5-year olds print("\nStep 5") filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/obesity_1011.csv' df = pd.read_csv(filename, low_memory=False) df1011 = df[['Area Code', 'Parent Name', 'Area Name', 'Value']] filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/IMD_CI.csv' df = pd.read_csv(filename, low_memory=False) dfIMD = df[['Area Code', 'IMD - Average score', 'IMD - Proportion of LSOAs in most deprived 10% nationally']] filename = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/2015_LA_GDHI_perhead_CI.csv' df = pd.read_csv(filename, low_memory=False) dfGDHI = df[['Area Code', '2015']] df1011 = pd.merge(df1011, dfIMD, on='Area Code') df1011 = pd.merge(df1011, dfGDHI, on='Area Code') # rename some header titles df1011 = df1011.rename({'Value': 'Obesity proportion', '2015': 'GDHI'}, axis='columns') # Progress check: ^^^ so to now you have a dataframe for 4-5-year old obesity and for 10-11-year old obesity # Each has obesity data merged with IMD data and GDHI data # STEP 6: for dataframe 4-5-year olds, merge the other social deprivation data in an automated way print("\nStep 6") pathname = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/' file_list = ['Income.csv', 'Income Deprivation Affecting Children Index (IDACI).csv', 'Employment.csv', 'Education, Skills and Training.csv', 'Health Deprivation and Disability.csv', 'Crime.csv', 'Barriers to Housing and Services.csv', 'Living Environment.csv'] for file in file_list: filename = pathname + file df = pd.read_csv(filename, low_memory=False) # Need to standardise index name in all social deprivation index files to 'Area Code' df = df.rename({'Local Authority District code (2013)': 'Area Code'}, axis='columns') var_base = file.split(".")[0] var_1 = var_base + ' - Average score' var_2 = var_base + ' - Proportion of LSOAs in most deprived 10% nationally' df = df[['Area Code', var_1, var_2]] df45 = pd.merge(df45, df, on='Area Code') df1011 = pd.merge(df1011, df, on='Area Code') # print("Visually check df45:\n", df45.head(2)) print("Visually check df1011:\n", df1011.head(2)) # STEP 7: shorten name of Parent Name entries, as too long for plotting (delete ' region') # Also, change Parent Name to Region # Also, shorten Yorkshire and the Humber print("\nStep 7") df45['Parent Name'] = df45['Parent Name'].map(lambda x: str(x)[:-7]) df45 = df45.rename({'Parent Name': 'Region'}, axis='columns') df1011['Parent Name'] = df1011['Parent Name'].map(lambda x: str(x)[:-7]) df1011 = df1011.rename({'Parent Name': 'Region'}, axis='columns') df45 = df45.replace(to_replace='Yorkshire and the Humber', value='Yorks and Humber') df1011 = df1011.replace(to_replace='Yorkshire and the Humber', value='Yorks and Humber') # STEP 8: for df45 and df1011, write dataframes to a csv file that will be used in the study print("\nStep 8") newname45 = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/study_data45.csv' df45.to_csv(newname45, index=False) newname1011 = '/Users/RAhmed/WesleyanMOOC/W_data_store/csv_files/study_data1011.csv' df1011.to_csv(newname1011, index=False)
""" Quick function to split bills """ def split_bill(cost): split_cost = cost / 2 print("{} dollars".format(split_cost)) return # Split a 5 dinner cost split_bill(5)
num=int(input("Enter the Year:")) if num > 0: if (num % 4) == 0: if(num % 100) == 0: if(num % 400) == 0: print("{0} is a Leap Year".format(num)) else: print("{0} is not a Leap Year".format(num)) else: print("{0} is a Leap Year".format(num)) else: print("{0} is not a Leap Year".format(num)) else: print("Enter Valid Year")
#!/usr/bin/python # coding: utf-8 import unittest import operator from string_subtraction import StringNumber # There are other ways to do this but thought it would be fun working out # the problems of a class with dynamically created methods class StringNumberEqualityTests(unittest.TestCase): """Shell class for dyanmically generated tests""" pass @classmethod def initialize_equality_tests(cls): zero = StringNumber("0") pos1 = StringNumber("1230") pos2 = StringNumber("456") neg1 = StringNumber("-345") neg2 = StringNumber("-11234") test_items = [ (zero, zero, operator.eq, True), (zero, zero, operator.lt, False), (zero, zero, operator.le, True), (zero, zero, operator.gt, False), (zero, zero, operator.ge, True), (zero, zero, operator.ne, False), (pos1, pos2, operator.eq, False), (pos1, pos2, operator.lt, False), (pos1, pos2, operator.le, False), (pos1, pos2, operator.gt, True), (pos1, pos2, operator.ge, True), (pos1, pos2, operator.ne, True), (pos2, pos1, operator.eq, False), (pos2, pos1, operator.lt, True), (pos2, pos1, operator.le, True), (pos2, pos1, operator.gt, False), (pos2, pos1, operator.ge, False), (pos2, pos1, operator.ne, True), (pos1, neg1, operator.eq, False), (pos1, neg1, operator.lt, False), (pos1, neg1, operator.le, False), (pos1, neg1, operator.gt, True), (pos1, neg1, operator.ge, True), (pos1, neg1, operator.ne, True), (neg1, pos1, operator.eq, False), (neg1, pos1, operator.lt, True), (neg1, pos1, operator.le, True), (neg1, pos1, operator.gt, False), (neg1, pos1, operator.ge, False), (neg1, pos1, operator.ne, True), (neg1, neg2, operator.eq, False), (neg1, neg2, operator.lt, False), (neg1, neg2, operator.le, False), (neg1, neg2, operator.gt, True), (neg1, neg2, operator.ge, True), (neg1, neg2, operator.ne, True), (neg2, neg1, operator.eq, False), (neg2, neg1, operator.lt, True), (neg2, neg1, operator.le, True), (neg2, neg1, operator.gt, False), (neg2, neg1, operator.ge, False), (neg2, neg1, operator.ne, True), ] def my_generator(x, y, op, answer): def test(self): self.assertEqual(op(x,y), answer, "{0} {1} {2} not {3}".format(x, op, y, answer)) return test operator_nice_names = { operator.eq : "equals", operator.lt : "less than", operator.le : "less than or equal", operator.gt : "greater than", operator.ge : "greater than or equal", operator.ne : "not equal to" } for x, y, op, answer in test_items: test_name = "test_{0}_{2}_{1}_{3}".format(x, y, operator_nice_names[op].replace(" ", "_"), answer ) test = my_generator(x, y, op, answer) setattr(StringNumberEqualityTests, test_name, test) # Dynamically assign test methods to class on import StringNumberEqualityTests.initialize_equality_tests() class StringNumberTests(unittest.TestCase): def test_pos_short_number_construction(self): number = StringNumber("1") self.assertEqual("1", str(number)) def test_neg_short_number_construction(self): number = StringNumber("-1") self.assertEqual("-1", str(number)) def test_pos_number_construction(self): number = StringNumber("123") self.assertEqual("123", str(number)) def test_neg_number_construction(self): number = StringNumber("-123") self.assertEqual("-123", str(number)) def test_zero_number_construction(self): number = StringNumber("0") self.assertEqual("0", str(number)) def test_neg_zero_number_construction(self): number = StringNumber("-0") self.assertEqual("-0", str(number)) def test_bad_string_construction(self): with self.assertRaises(ValueError): StringNumber("12b") def test_empty_string_construction(self): with self.assertRaises(ValueError): StringNumber("12b") def test_none_construction(self): with self.assertRaises(ValueError): StringNumber(None) def test_pos_pos_pos_subtraction(self): number = StringNumber("40") - StringNumber("20") self.assertEqual("20", str(number)) def test_pos_pos_zero_subtraction(self): number = StringNumber("40") - StringNumber("40") self.assertEqual("0", str(number)) def test_pos_neg_pos_subtraction(self): number = StringNumber("40") - StringNumber("-20") self.assertEqual("60", str(number)) def test_pos_pos_neg_subraction(self): number = StringNumber("40") - StringNumber("100") self.assertEqual("-60", str(number)) def test_pos_zero_pos_subtraction(self): number = StringNumber("40") - StringNumber("0") self.assertEqual("40", str(number)) def test_neg_pos_neg_subtraction(self): number = StringNumber("-40") - StringNumber("20") self.assertEqual("-60", str(number)) def test_neg_neg_neg_subtraction(self): # import pdb # pdb.set_trace() number = StringNumber("-40") - StringNumber("-20") self.assertEqual("-20", str(number)) def test_neg_neg_zero_subtraction(self): number = StringNumber("-40") - StringNumber("-40") self.assertEqual("0", str(number)) def test_neg_neg_pos_subtraction(self): number = StringNumber("-40") - StringNumber("-60") self.assertEqual("20", str(number)) def test_neg_zero_neg_subtraction(self): number = StringNumber("-40") - StringNumber("0") self.assertEqual("-40", str(number)) def test_zero_zero_zero_subtraction(self): number = StringNumber("0") - StringNumber("0") self.assertEqual("0", str(number)) def test_basic_addition(self): number = StringNumber("1") + StringNumber("2") self.assertEqual("3", str(number)) def test_carryover(self): number = StringNumber("7") + StringNumber("8") self.assertEqual("15", str(number)) def test_diff_length_numbers(self): number = StringNumber("4") + StringNumber("20") self.assertEqual("24", str(number)) def test_zero_plus_one_addition(self): number = StringNumber("0") + StringNumber("1") self.assertEqual("1", str(number)) def test_zero_addition(self): number = StringNumber("0") + StringNumber("0") self.assertEqual("0", str(number)) if __name__ == "__main__": unittest.main()
sum = 0.0 print(" i\t sum") for i in range(1, 11): sum += 1.0 / i print("%2d %6.1f" % (i , sum)) ''' #using while loop sum = 0.0 i = 1 while i < 11: sum += 1.0 / i print("%2d %6.1f" % (i , sum)) i +=1 '''
#!/usr/bin/env python3 # FIXME -- convert into float farenheit = 0 while farenheit <= 10: celcius = (farenheit - 32)/1.8 print("Farenheit Celcius") print("%d \t\t\t %d" %(farenheit, celcius)) farenheit = farenheit + 10 """farenheit = 0.0 print("Farenheit Celcius") while farenheit <= 10: celcius = (farenheit - 32.0) /1.8 print("%5.1f %7.2f" %(farenheit,celcius)) farenheit = farenheit + 25"""
# Import csv and os modules import csv import os # Identify file for analysis PyBank_file = os.path.join(".", "Resources", "budget_data.csv") # Identify file for output output_file = os.path.join(".", "analysis", "PyBankAnalysis.txt") # OPEN CSV FILE with open(PyBank_file, 'r') as csvfile: # READ CSV FILE csv_read = csv.reader(csvfile, delimiter=',') # Take out title row in file csv_title = next(csv_read) # Initialize variables total_amount = 0 avg_change = 0 greatest_increase = 0 greatest_losses = 0 profit_date = "" loss_date = "" # Create & define lists for dates, amounts & profit change by month dates = [] amount = [] profit_change_by_month = [] # Loop through the file to create separate lists for row in csv_read: # Append lists with each row's value dates.append(row[0]) amount.append(row[1]) # Find TOTAL MONTHS: length of 'dates' list (without title row) total_months = len(list(dates)) # Loop through 'amount' list to find first and last values & add value to total amount for x in range(len(amount)): # Find NET TOTAL AMOUNT of Profit/Losses by looping through and adding each value total_amount += int(amount[x]) # Find first and last monthly amounts in 'amount' list first_amount = int(amount[0]) last_amount = int(amount[total_months - 1]) # Calculate changes in Profit/Losses change = last_amount - first_amount # Find AVERAGE OF CHANGES in Profit/Losses avg_change = change / (total_months - 1) # Round average change to 2 decimal places rounded_avg_change = round(avg_change, 2) # Find profit change by month by looping through 'amount' list # Set current month equal to current index current_month = int(amount[x]) # Set previous month equal to previous index (set for next row) previous_month = int(amount[x - 1]) # Add values to a new 'profit change' list to hold monthly changes profit_change_by_month.append(current_month - previous_month) # Set current month equal to 0 (resetting for next row) current_month = 0 # Find GREATEST INCREASE IN PROFITS over period greatest_increase = max(profit_change_by_month) # Find GREATEST INCREASE IN LOSSES over period greatest_losses = min(profit_change_by_month) # Loop through 'profit change' list to find indexes of values for index in range(len(profit_change_by_month)): # Find profit index if greatest_increase == profit_change_by_month[index]: profit_index = index # Find losses index if greatest_losses == profit_change_by_month[index]: loss_index = index # Find DATES that correspond with the profit/loss values (from 'dates' list) profit_date = dates[profit_index] loss_date = dates[loss_index] # OUTPUT RESULTS # Print findings for user in terminal print("FINCANCIAL ANALYSIS:") print("--------------------") print(f"Total Months: {total_months} months") print(f"Net Total Amount: ${total_amount}") print(f"Average Change: ${rounded_avg_change}") print(f"Greatest Increase in Profits: {profit_date}, ${greatest_increase}") print(f"Greatest Increase in Losses: {loss_date}, ${greatest_losses}") # Define descriptions for output descriptions = ["Total Months", "Net Total Amount", "Average Change", "Greatest Increase in Profits", "Greatest Profit Month", "Greatest Increase in Losses", "Greatest Loss Month"] # Define output values output_values = [total_months, total_amount, rounded_avg_change, greatest_increase, profit_date, greatest_losses, loss_date] # Zip output values & descriptions together clean_output = zip(descriptions, output_values) # Write to output file with open(output_file, 'w', newline = '') as new_csv: # Write ouput to a file csv_write = csv.writer(new_csv, delimiter=',') # Write title row csv_write.writerow(["Financial Analysis"]) csv_write.writerow(["--------------------"]) # Write all output rows csv_write.writerows(clean_output) # Notify user that results were output print("The results were saved into PyBankAnalysis.txt.")