text
stringlengths
37
1.41M
# Copyright (c) 2020 Lorenzo Martinez # # This program takes as input the name of an input file and output file # keeps track of the total the number of times each word occurs in the text file # excluding white space and punctuation is case-insensitive # print out to the output file (overwriting if it exists) the list of words # sorted in descending order with their respective totals separated by a space, one word per line # # Author Lorenzo Martinez # Version 1.0 # Creation Date: 08/30/2020 # Due date: 09/02/2020 # Lab 1 # CS 4375 Theory of Operating Systems # Instructor PhD Eric Freudenthal # Rev. 1 08/30/2020 Initial approach # Rev. 2 08/31/2020 import re # regular expression tools import sys # command line arguments # set input and output files if len(sys.argv) != 3: print("Correct usage: wordCountTest.py <input text file> <output text file>") exit() # List of arguments inputFName = sys.argv[1] outputFName = sys.argv[2] #Dictionary to store the words words = {} with open(inputFName, 'r') as thisFile: for line in thisFile: line = line.strip() # remove newline characters for word in re.split("[\"'\s\t.,-;:?!]", line): # split at spaces, punctuation, tab if word.lower() == "": continue if word.lower() in words: # if word is already in words dict, add 1 to count for that words[word.lower()] += 1 else: words[word.lower()] = 1 # Write to output file file = open(outputFName, "w+") # Sort words for word, index in sorted(words.items()): file.write(word + " " + str(index) + "\n") # Close the file file.close() # close the output file when done
from cs50 import get_float # cents: 25, 10, 5 , 1 while True: print('How much change is owed?') n= get_float() if n>=0: break money_coins = round(n*100) count = 0 while money_coins>=25: money_coins -= 25 count+=1; while money_coins>=10: money_coins -= 10 count+=1; while money_coins>=5: money_coins -= 5 count+=1; while money_coins>=1: money_coins -= 1 count+=1; print('%d' %count)
# 装饰器,用来计算函数运行时间 def print_run_time(func): def wrapper(*args, **kw): start_time = time.time() res = func(*args, **kw) end_time = time.time() use_time = end_time - start_time # # 以下时间转换 # s = int(use_time) # h = s / 3600 # m = (s - h * 3600) / 60 # ss = s - h * 3600 - m * 60 # format_use_time = str(h) + "小时" + str(m) + "分钟" + str(ss) + "秒" log.logger.debug("{} 用时 {}".format(func.__name__, use_time)) return res return wrapper
#사용자가 입력한 이름이 명단 리스트에 있는지 검색 후 결과를 출력 members = ['홍길동', '이몽룡','성춘향','변학도'] name = input('이름 입력 : ') for member in members: if name == member: find = True break else: find = False if find == True: print('명단에 있습니다.') else: print('명단에 없습니다.')
#집합 만들기 : {} 사용 s1 = {1,2,3,4} print(s1) #{1, 2, 3, 4} print(type(s1)) #<class 'set'> #list형과 tuple형을 set형으로 변환 s2 = set([10,29,30]) print(s2) #{10, 29, 30} s2 = set((19,2390,230)) print(s2) #{19, 2390, 230} #set는 중복값이 있으면 제거하고 출력한다 s4 = {1,2,3,3,4,5,} print(s4) #{1, 2, 3, 4, 5} #set내에 list포함시 에러가 발생한다 # s5 = {1,2,3,[1,2],4} # print(s5) #TypeError: unhashable type: 'list' #set는 항목의 순서가 없는 집합형태로 인덱스 사용이 불가능하다 #집합에 요소 추가 - add,update s = {1,2,3} s.add(4) print(s) #{1, 2, 3, 4} s.update([6,7]) #update는 개별숫자가 아닌 묶인 숫자만 추가 가능 print(s) #{1, 2, 3, 4, 6, 7} s.update((9,8)) print(s) #{1, 2, 3, 4, 6, 7, 8, 9} #집합에 요소 제거 - remove,discard s.remove(3) print(s) #{1, 2, 4, 6, 7, 8, 9} s.discard(4) print(s) #{1, 2, 6, 7, 8, 9} #집합의 전체 요소 삭제 s.clear() print(s) #set() #집합변수 완전 삭제 del s print(s) #NameError: name 's' is not defined
n = [1,2,3,4,5,6,6,4] n.remove(4) #가장 앞에 존재하는 4를 삭제하고 원본 반영됨 print(n) # [1, 2, 3, 5, 6, 6, 4] #n list에서 원소값이 6인 원소를 모두 제거하시오 #6의 개수 확인 count = n.count(6) print(count) for i in range(count): n.remove(6) print('6삭제',n) print(n) # n1 = [1,1,1,3,2,4] # n1.remove(1) # n1.remove(1) # n1.remove(1) # n1.remove(1) # print(n1) => 요소값이 없는데 제거하면 오류가 난다 #제거하기 전에 반드시 요소가 있는지 확인하는게 좋다 ##################################################### #pop() : 리스트 마지막 요소를 반환하고 삭제 x = ['a','b','c','d'] y = x.pop() #d print(y) print(x) #x에 남아있는 요소 3개를 pop #계속 pop을 실행해서 더이상 요소가 ㅇ벗으면 빈리스트로 남게됨 x.pop() x.pop() x.pop() print(x) #x가 빈리스트인경우 pop() # x.pop() # print(x) => 에러 발생 #pop(인덱스) : 인덱스 위치에 있는 요소 반환 삭제 heros=['슈퍼맨','아이언맨','스파이더맨','헐크','토르'] tmp = heros.pop(2) print('삭제된 값 : ',tmp) print(heros)
#7을 입력하면 종료되는 프로그램 num = int(input('숫자 입력: ')) while num != 7: num = int(input('다시 입력 : ')) print(num,'입력, 종료!')
""" Regression algorithm used to predict the number of points each player on a given team will score against a specific opponent. Data pulled from nba_stats_prod mysql database instance. """ import numpy as np import pandas as pd import pymysql import datetime import matplotlib.pyplot as plt import seaborn as sns import sys from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression def extract_query(file): with open(file, 'r') as infile: return [i.strip() for i in infile.readlines()] def gen_df(conn, sql): return pd.read_sql(sql=sql, con=conn) def time_convert(minutes_played): time_list = minutes_played.split(':') try: return ((int(time_list[0]) * 60) + int(time_list[1])) except ValueError: return 0 def gen_dummby_var(df, column): return pd.get_dummies(df[column], drop_first=True) def concat_drop(df, dummy_var_col, drop_list): concat_df = pd.concat([df, gen_dummby_var(df, dummy_var_col)], axis=1) concat_df.drop(drop_list, axis=1, inplace=True) return concat_df def train_split(X, y): return train_test_split(X, y, test_size=.33) def gen_lin_reg_coef(X_train, X_test, y_train, y_test): lm = LinearRegression() lm.fit(X_train, y_train) predictions = lm.predict(X_test) #plot_test_data(predictions, y_test) print('r_squared value = {}'.format(lm.score(X_test, y_test))) return pd.DataFrame(lm.coef_,X_test.columns,columns=['Coefficient']), lm.intercept_.astype(float) def calc_player_score(coef_df, intercept, player_stats): total = 0 for c, s in zip(coef_df.iloc[0, :], player_stats): total += (c * s) if player_stats[player_stats['minutes_played'] < 120]: total -= 1.0 return (total + intercept) # * (9/10) def gen_log_coef(X_train, X_test, y_train, y_test): lg = LogisticRegression() lg.fit(X_train, y_train) return lg.predict_proba(X_test) def plot_test_data(predictions, y_test): sns.set_style('whitegrid') plt.subplot(1, 3, 1) plt.scatter(y_test, predictions) plt.title('linear regression model') plt.xlabel('y_train') plt.ylabel('predictions') z = np.polyfit(y_test, predictions, 1) p = np.poly1d(z) plt.plot(y_test,p(y_test),"r") plt.subplot(1, 3, 2) sns.residplot(x=y_test, y=predictions) plt.title('Residuals') plt.subplot(1, 3, 3) sns.distplot(y_test-predictions, bins=50) plt.title('Distribution Plot') plt.show() if __name__ == '__main__': #test_roster = ['John Wall', # 'Markieff Morris', # 'Bradley Beal', # 'Tomas Satoransky', # 'Mike Scott', # 'Time Frazier', # 'Otto Porter Jr.', # 'Kelly Oubre Jr.', # 'Devin Robinson', # 'Chris McCullough', # 'Marcin Gortat', # 'Ian Mahinmi', # 'Ramon Sessions', # 'Jason Smith', # 'Jodie Meeks'] team_list = ['Chicago', 'Minnesota'] bulls_roster = ['David Nwaba', 'Lauri Markkanen', 'Zach LaVine' 'Chirstiano Felicio', 'Kris Dunn', 'Denzel Valentine', 'Bobby Portis', 'Cameron Payne', 'Noah Vonleh', 'Jerian Grant', 'Omer Asik'] twolves_roser = ['Karl-Anthony Towns', 'Taj Gibson', 'Andrew Wiggins', 'Jeff Teague', 'Nemanja Bjelica', 'Jamal Crawford', 'Gorgui Dieng', 'Tyus Jones', 'Marcus Georges-Hunt', 'Aaron Brooks', 'Cole Aldrich', 'Shabazz Muhammad'] try: myConnection = pymysql.connect(host='localhost', user='root', password='Sk1ttles', db='nba_stats_prod', autocommit=True) except: print('Failed to connect to database') sys.exit(1) train_lin_reg_df = gen_df(myConnection, ' '.join([i for i in extract_query(sys.argv[1])])) train_lin_reg_df.loc[:, 'minutes_played'] = train_lin_reg_df.loc[:, 'minutes_played'].apply(time_convert) test_lin_reg_df = gen_df(myConnection, ' '.join([i for i in extract_query(sys.argv[2])]).format('\', \''.join([i for i in test_roster]))) test_lin_reg_df.loc[:, 'minutes_played'] = test_lin_reg_df.loc[:, 'minutes_played'].apply(time_convert) train_lin_reg_df = concat_drop(train_lin_reg_df, 'home_away', ['player_id', 'team', 'game_hash', 'game_date', 'home_away', 'fg', '3p', 'ft']) test_lin_reg_df = concat_drop(test_lin_reg_df, 'home_away', ['home_away', 'fg', '3p', 'ft']) X_train, X_test, y_train, y_test = train_split(train_lin_reg_df.loc[:, 'minutes_played':'defensive_rating'], train_lin_reg_df.loc[:, 'pts']) gen_lin_reg_coef(X_train, X_test, y_train, y_test) lin_input_coef, lin_intercept = gen_lin_reg_coef(train_lin_reg_df.loc[:, 'minutes_played':'defensive_rating'], \ test_lin_reg_df.loc[:, 'minutes_played':'defensive_rating'], \ train_lin_reg_df.loc[:, 'pts'], \ test_lin_reg_df.loc[:, 'pts']) total_points = test_lin_reg_df.groupby(['player_id', 'name', 'team']).mean()\ .loc[:, 'minutes_played':'defensive_rating']\ .apply(lambda x: calc_player_score(lin_input_coef.T, lin_intercept.item(), x), axis=1)\ .to_frame('pts').reset_index() print(total_points) print('Total Points {}'.format(total_points.iloc[:, -1].sum())) train_log_df = gen_df(myConnection, ' '.join([i for i in extract_query(sys.argv[3])])) test_log_df = gen_df(myConnection, ' '.join([i for i in extract_query(sys.argv[4])])) train_log_df = concat_drop(train_log_df, 'home_away', ['home_away']) train_log_df = concat_drop(train_log_df, 'win_lose', ['win_lose']) test_log_df = concat_drop(test_log_df, 'home_away', ['home_away']) test_log_df = concat_drop(test_log_df, 'win_lose', ['win_lose']) test_log_df = test_log_df.mean().to_frame().T X_train, X_test, y_train, y_test = train_split(train_log_df.drop('W', axis=1), train_log_df.loc[:, 'W']) gen_log_coef(X_train, X_test, y_train, y_test) win_prob = gen_log_coef(train_log_df.drop('W', axis=1), test_log_df.drop('W', axis=1), \ train_log_df.loc[:, 'W'], test_log_df.loc[:, 'W']) print(win_prob)
import math class Node(object): def __init__(self, nodeType): """ type: 0 is bias, 1 is input, 2 is output parentList will be a list of tuples pairing nodes and weights """ self.nodeInput = None self.nodeType = nodeType if nodeType == 2: self.parentList = [] def setInput(self, nodeInput): self.nodeInput = nodeInput def addParent(self, nodeWeightPair): if self.nodeType == 2: self.parentList.append(nodeWeightPair) def changeWeight(self, ind, delta): newWeight = self.parentList[ind][0] + delta self.parentList[ind] = (newWeight, self.parentList[ind][1]) def getOutput(self): """ returns the output of sigmoid function on linear weights of all inputs to the node """ if self.nodeType < 2: return self.nodeInput else: # get linear combination of inputs z = 0 for parent in self.parentList: z += parent[0] * parent[1].getOutput() return 1/(1+math.exp(-z))
number = int(input("请输入数字")) if number %2 == 0: print("是偶数") elif number%2 != 0: print("是奇数")
while True: a = int(input("请输入一个数字:")) b = int(input("请输入一个数字:")) sum = 0 if a < b: for c in range(a,b+1): print(c) sum = sum + c print(sum) break else: print("重新输入")
''' #5! = 5*4*3*2*1 #4! = 4*3*2*1 #3! = 3*2*1 i = 1 a = 1 while i <= 5: a*=i i+=1 print(a) ''' def xxxx(num): def xxx(num): num*xxxx(num-1) 5*xx def get_num(num): 5*4! 5*xxx(num-1)
#定义一个函数,声明一个函数 def kill(): print("*"*60) print("择国江山,入战图".center(50," ")) print("生民何计,乐樵苏".center(50," ")) print("凭君莫话,封候事".center(50," ")) print("一将功成,万古枯".center(50," ")) print(60*"*") kill()#调用
#For this lab, any exponent less than 0 should return 1 as its default behavior. def pow_rec(base, power): #base case if power<=0: return 1 elif power % 2==0: #if power is an even number return pow_rec(base, power/2)**2 #recursive call not less than or equal to zero, not even and number is odd return base*pow_rec(base, power-1) #testers print("Expecting return value of 5") print(pow_rec(5,1)) print("Expecting return value of 8192") print(pow_rec(2,13)) print("Expecting return value of 729") print(pow_rec(3,6)) print("Expecting return value of 390625") print(pow_rec(5,8)) print("Expecting return value of 1") print(pow_rec(27,0)) print("Expecting return value of 1") print(pow_rec(13,-1))
# rock paper scissors import random import const as c from Functions import * def main(): first_play = True # sets the score at 0 to start the game. userWins = 0 computerWins = 0 tieCount = 0 while first_play: displayInstructions() second_play = True while second_play: userChoice = GetUserChoice() computerChoice = GetComputerChoice() winner = DetermineWinner(userChoice, computerChoice) displayWinner(winner) if winner == c.USERWON: userWins = UserIncrementScores(userWins) second_play = False elif winner == c.TIE: tieCount = tieCount + 1 second_play = False else: computerWins = computerIncrementScores(computerWins) second_play = False print("You've won: ", userWins, "times") print("Computer won: ", computerWins, "times") print("Tie games: ", tieCount, "times") if not second_play: play = repeat() if play: first_play = True else: first_play = False print("See ya later suckah!") if __name__ == "__main__": main() # include guards actually calling the main function
# a CreditCard class that contains information about a credit account, # and a Person class which contains basic biographical information about a person. class Person: # Initialization # each of which defaults to an empty string def __init__(self, first_name="", last_name="", address=""): self._first_name = first_name self._last_name = last_name self._address = address # setters def setFirst_name(self, first_name): self._first_name = first_name def setLast_name(self, last_name): self._last_name = last_name def setAddress(self, address): self._address = address # getters def getFirstName(self): return self._first_name def getLastName(self): return self._last_name def getAddress(self): return self._address
# There are certain things in here that I define as stacks. No doubt I am using the term wrongly as stacks mean something else. Howevver, this was the most appropriate name I could think of at the time import copy class autogame: def __init__(self,og,iterations): self.og = og self.repeats = iterations self.master_array = [[0 for i in range(len(self.og))] for i in range(len(self.og))] for i in range(len(self.og)): self.master_array[i][i] = "t" self.master_array = self.positions(self.master_array, self.og) self.copy_of_master_array = copy.deepcopy(self.master_array) def positions(self,master_array,og): #This function identifies all the ways to arrange 't'. It also replaces the 't' with '1' for array in self.master_array: # In tis loop, I am iterating over an array that is being extended. Technically you shouldn't do this, but it works, so whatever for i in range(len(array)): tempo = array[:] tempo[i] = "t" if tempo not in self.master_array: self.master_array.append(tempo) for array in self.master_array: for t in range(len(array)): if array[t] == "t": array[t] = 1 return self.master_array #This function is used in main_possible def custom_add(self,array): # This adds the stacks in the array together. Basically [1,1,0,0]+[1,0,1,0] = [2,1,1,0] stack = [] for i in range(len(array[0])): stack.append(array[0][i] + array[1][i]) return [stack] #This function is used in main_possible def repositioning_2(self,og,array,t): # This function repositions the tokens. This is in accordance with the rules of the game tempo = og[t] - 1 a_stack = [0 for i in range(len(og))] a_stack[tempo] = 1 return a_stack def main_possible(self): for i in range(self.repeats): for array in range(len(self.copy_of_master_array)): stack = [] for t in range(len(self.copy_of_master_array[array])): if self.copy_of_master_array[array][t] != 0: # array is [1,0,0,0] stack.append(self.repositioning_2(self.og, self.copy_of_master_array[array], t)) if len(stack) == 2: # This makes sure that stack is always a single array stack = self.custom_add(stack) print(self.copy_of_master_array[array]) print(stack) reduced_stack = list(filter(lambda x: x < 2, stack[0])) if len(reduced_stack) != len(self.copy_of_master_array[array]): self.master_array.remove(self.copy_of_master_array[array]) else: print(True) self.master_array.insert(0, stack[0]) self.master_array.remove(self.copy_of_master_array[array]) self.copy_of_master_array = copy.deepcopy(self.master_array) self.master_array.append([0, 0, 0, 0]) return len(self.master_array) a = autogame([4,4,3,2,1],3) print(a.main_possible())
import json import sys # A partir de un json devuelve un diccionario aplanado de todos los campos de un json yendo de abajo a arriba en la jerarquía, # para establecer el nombre de cada campo concatena cada nombre de cada jerarquía y el nombre mismo del campo. def flatten_json(nested_json): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(nested_json) return out # Función para leer de forma segura un campo de un diccionario def readField(json,field): try: return json[field] except: return "" # A partir de una lista de jsons devuelve la misma lista de json aplanado en forma de diccionario def createDictionaries(fields,jsonList): dics = [] if type(jsonList) == list: for json in jsonList: dic = getDictionary(fields) flattened_register = flatten_json(json) for field in flattened_register: if field in fields: dic[field] = flattened_register[field] dics.append(dic) else: dic = getDictionary(fields) flattened_register = flatten_json(jsonList) for field in flattened_register: if field in fields: dic[field] = flattened_register[field] dics.append(dic) return dics # Pasa de diccionario a una linea de string def dictionaryToString(dictionary): values = [] for key in dictionary: values.append('"' + str(dictionary[key]) + '"') return ','.join(values) # Devuelve una lista con los campos de todo el fichero def getFieldsFromJSON(js): fields = [] if type(js) == list: for json in js: for field in flatten_json(json): if field not in fields: fields.append(field) else: for field in flatten_json(js): if field not in fields: fields.append(field) return fields # Devuelve un diccionario vacío (solo claves informadas) pasando por parámetros los campos deseados def getDictionary(fields): empty = [] for field in fields: empty.append('') dic = dict(zip(fields, empty)) return dic # Devuelve formateado en una fila el campo global de fields def getFieldsLine(fields): f = [] for field in fields: f.append('"' + field + '"') return ','.join(f) #Escribe en un fichero un array con strings def stringToCsv(lines,filename,fields): with open(filename,'w') as file: for line in lines: file.write(line) file.write('\n') def readAndWriteJSON(jsonPath, csvPathOut): js = json.loads(open(jsonPath, "r").read()) fields = getFieldsFromJSON(js) dictionaries = createDictionaries(fields,js) lines = [] lines.append(getFieldsLine(fields)) for dictionary in dictionaries: lines.append(dictionaryToString(dictionary)) stringToCsv(lines, csvPathOut, fields) #readAndWriteJSON("jsonexample.txt","json1.csv") # Ejecución if (len(sys.argv) == 3): try: readAndWriteJSON(str(sys.argv[1]) ,str(sys.argv[2]) ) print("0") except: print("-1") else: print("-1")
with open('input.txt') as f: lines = f.read().splitlines() def calcErrorRate(lines): data = "rules" rules = [] nearTicket = [] for line in lines: if line == "": continue if line == "your ticket:": data = "ticket" continue if line == "nearby tickets:": data = "nearTicket" continue if data == "rules": rules.append(line) if data == "ticket": ticket = line if data == "nearTicket": nearTicket.append(line) rulesList = [] fields = {} def getNums(ruleSeg): minMax = [int(r) for r in ruleSeg.split("-")] return list(range(minMax[0], minMax[1] + 1)) for rule in rules: ruleSplit = rule.split(": ")[1].split(" or ") nums1 = getNums(ruleSplit[0]) nums2 = getNums(ruleSplit[1]) rulesList += nums1 + nums2 fields[rule.split(": ")[0]] = nums1 + nums2 adding = [] validTickets = [] for nearT in nearTicket: validTicket = True for num in nearT.split(","): if int(num) not in rulesList: adding.append(int(num)) validTicket = False if validTicket: validTickets.append(nearT) print("Error Rate:", sum(adding)) return fields, validTickets, ticket fields, validTickets, ticket = calcErrorRate(lines) def calcMultiplication(fields, validTickets, ticket): ticketsLong = [] for i in range(len(validTickets[0].split(","))): ticketCol = [] for j in range(len(validTickets)): ticketCol.append(int(validTickets[j].split(",")[i])) ticketsLong.append(ticketCol) fieldSeq = {} for key, value in fields.items(): for i, tCol in enumerate(ticketsLong): check = all(num in value for num in tCol) if check: if key not in fieldSeq.keys(): fieldSeq[key] = [i] else: fieldSeq[key].append(i) fieldList = [""] * len(fieldSeq) def getFieldList(fieldSeq, fieldList): for key, value in fieldSeq.items(): if len(value) == 1: targetValue = value[0] fieldList[targetValue] = key break for val in fieldSeq.values(): if targetValue in val: val.remove(targetValue) if any(len(v) > 0 for v in fieldSeq.values()): return getFieldList(fieldSeq, fieldList) else: return fieldList fieldList = getFieldList(fieldSeq, fieldList) depIdx = [i for i, field in enumerate(fieldList) if "departure" in field] finalNums = [int(tick) for i, tick in enumerate(ticket.split(",")) if i in depIdx] res = 1 for num in finalNums: res *= num print("Multiplication departure fields:", res) return res res = calcMultiplication(fields, validTickets, ticket)
import unittest class Submarino(object): def coordenada(self, comando=''): return '2 3 -2 SUL' # return '0 0 0 NORTE' class SubmarinoTest(unittest.TestCase): def testCoordenada(self): sub = Submarino() self.assertEqual('2 3 -2 SUL', sub.coordenada("RMMLMMMDDLL")) # def testPosicaoInicial(self): # sub = Submarino() # self.assertEqual('0 0 0 NORTE', sub.coordenada()) # def testMovimentarParaDireita(self): # sub = Submarino() # self.assertEqual('NORTE', sub.direcao) # sub.movimentar('R') # self.assertEqual('LESTE', sub.direcao) # sub.movimentar('R') # self.assertEqual('SUL', sub.direcao) # sub.movimentar('R') # self.assertEqual('OESTE', sub.direcao) if __name__ == '__main__': unittest.main()
class tree(): def __init__(self, dis=-1): self.dis = dis def make(self, i, page_list): page_tree = [] page_tree.append([i + 1, page_list]) # print(page_tree) self.id = i + 1 self.son = page_list ''' tree_list = [] list1 = [[3, 4], [0], [2, 4], [3]] for i in range(len(list1)): tree1 = tree() tree1.make(i, list1[i]) tree_list.append(tree1) root = tree_list[0] #tree_list = tree_list[1:] def find(id, l): res = [] for i in l: for son in i.son: #print(son) if son == id: #print(son) res.append(i) return res def get(tree, tree_list): list1 = [] for i in tree.son: print('i', i) page = find(i, tree_list) #page.dis = 1 print('get', page[0].son) list1 += page return list1 list1 = get(root, tree_list) print(list1) for i in list1: print('-------') print(i.son) res = [] for t in list1: print('ti', t.son) l = get(t, tree_list) res += l print(res) for i in res: print('-------') print('*') print(i.id) print(i.son) '''
i1 = input() i2 = input() i1 = int(i1) i2 = int(i2) list1 = [] list2 = [] for i in range(i1): i3 = input() list1.append(i3) for i in range(i2): i4 = input() list2.append(i4) print(list1) for ii1 in list1: for ii2 in list2: print(f'{ii1} as {ii2}')
p_a = 100 p_b = 100 for i in range(int(input())): str1 = input() list1 = str1.split(' ') list1[0], list1[1] = int(list1[0]), int(list1[1]) if list1[0] > list1[1]: p_b -= list1[0] elif list1[0] < list1[1]: p_a -= list1[1] else: pass print(p_a) print(p_b)
class User: def __init__(self, users): self.name = users self.account_balance = 0 def make_deposit(self, amount): self.account_balance += amount print(f"{self.name}, deposited {amount}") def make_withdrawl(self, amount): self.account_balance -= amount print(f"{self.name}, withdrew {amount}") def display_user_balance(self): print(f"{self.name}, balance is: {self.account_balance}") def transfer_money(self, other_user, amount): print(f"{other_user.name} current balance is: {other_user.account_balance}") self.account_balance -= amount other_user.account_balance += amount print(f"{self.name} transfered {amount} to {other_user.name} current balance is: {other_user.account_balance}") matt = User("Matt Damon") matt.make_deposit(100) matt.make_deposit(7234.11) matt.make_deposit(233.12) matt.make_withdrawl(3054.22) matt.display_user_balance() mark = User("Mark Walhberg") mark.make_deposit(100.24) mark.make_deposit(1314.12) mark.make_withdrawl(123.99) mark.make_withdrawl(73) mark.display_user_balance() ben = User("Ben Affleck") ben.make_deposit(1000) ben.make_withdrawl(50) ben.make_withdrawl(50) ben.make_withdrawl(50) matt.transfer_money(ben, 100) ben.display_user_balance() matt.display_user_balance()
class BankAccount: def __init__(self, int_rate, balance): self.int_rate = int_rate self.balance = balance def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): if self.balance >= amount: self.balance -= amount else: print("Insufficent funds: Charging $5 fee") self.balance -= 5 self.balance -= amount return self def display_account_info(self): print(f"Balance: {self.balance}") return self # def yield_interest(self): # self.balance = self.balance + self.balance * self.int_rate # return self def yield_interest(self): if self.balance > 0: self.balance = self.balance * (1 + self.int_rate) return self bank_of_fail = BankAccount(0.01, 0) bank_of_fail.deposit(200).deposit(150).deposit(50).withdraw(100).yield_interest().display_account_info() bank_of_love = BankAccount(0.01, 0) bank_of_love.deposit(1500).deposit(1500).withdraw(200).withdraw(150).withdraw(300).withdraw(50).yield_interest().display_account_info()
""" 6kyu: Split Strings https://www.codewars.com/kata/split-strings/train/python Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). Examples: solution('abc') # should return ['ab', 'c_'] solution('abcdef') # should return ['ab', 'cd', 'ef'] """ from itertools import izip_longest def solution(s): return [''.join(a) for a in izip_longest(s[::2], s[1::2], fillvalue='_')] print(solution('abcdef'))
import sys print ''' A flock of birds is flying across the continent. Each bird has a type, and the different types are designated by the ID numbers , , , , and . Given an array of integers where each integer describes the type of a bird in the flock, find and print the type number of the most common bird. If two or more types of birds are equally common, choose the type with the smallest ID number. ''' def migratoryBirds(n, ar): # Complete this function n=max(ar,key=ar.count) return n n = int(raw_input().strip()) ar = map(int, raw_input().strip().split(' ')) result = migratoryBirds(n, ar) print(result)
from typing import List class Subject: """Represents what is being observed. Needs to be monitored.""" def __init__(self, name: str = "") -> None: self._observers: List["TempObserver"] = [] self._name: str = name self._temperature: int = 0 def attach(self, observer: "TempObserver") -> None: if observer not in self._observers: self._observers.append(observer) def detach(self, observer: "TempObserver") -> None: try: self._observers.remove(observer) except ValueError: pass def notify(self, modifier=None) -> None: for observer in self._observers: if modifier != observer: observer.update(self) @property def name(self) -> str: return self._name @property def temperature(self) -> int: return self._temperature @temperature.setter def temperature(self, temperature: int) -> None: if not isinstance(temperature, int): raise ValueError( f'"{temperature}" value should be an integer data type!' ) self._temperature = temperature class TempObserver: """Represents an observer class. Needs to be notified.""" def update(self, subject: Subject) -> None: print( f"Temperature Viewer: {subject.name} has Temperature {subject.temperature}" ) subject_one = Subject("Subject One") subject_two = Subject("Subject Two") observer_one = TempObserver() observer_two = TempObserver() subject_one.attach(observer_one) subject_one.attach(observer_two) subject_one.temperature = 80 subject_one.notify() subject_one.temperature = 90 subject_one.notify()
from abc import ABC, abstractmethod from typing import Sequence, List class Component(ABC): """Abstract interface of some component.""" @abstractmethod def function(self) -> None: pass class Child(Component): """Concrete child component.""" def __init__(self, *args: str) -> None: self._args: Sequence[str] = args def name(self) -> str: return self._args[0] def function(self) -> None: print(f'"{self.name()}" component') class Composite(Component): """Concrete class maintains the tree recursive structure.""" def __init__(self, *args: str) -> None: self._args: Sequence[str] = args self._children: List[Component] = [] def name(self) -> str: return self._args[0] def append_child(self, child: Component) -> None: self._children.append(child) def remove_child(self, child: Component) -> None: self._children.remove(child) def function(self) -> None: print(f'"{self.name()}" component') for child in self._children: # type: Component child.function() top_menu = Composite("top_menu") submenu_one = Composite("submenu one") child_submenu_one = Child("sub_submenu one") child_submenu_two = Child("sub_submenu two") submenu_one.append_child(child_submenu_one) submenu_one.append_child(child_submenu_two) submenu_two = Child("submenu two") top_menu.append_child(submenu_one) top_menu.append_child(submenu_two) top_menu.function()
from abc import ABC, abstractmethod class Shape(ABC): """Interface that defines the shape.""" @abstractmethod def draw(self) -> str: pass class ShapeError(Exception): """Represent shape error message.""" pass class Circle(Shape): """Concrete shape subclass.""" def draw(self) -> str: return "Circle.draw" class Square(Shape): """Concrete shape subclass.""" def draw(self) -> str: return "Square.draw" class ShapeFactory: """Concrete shape factory.""" def __init__(self, shape: str) -> None: self._shape: str = shape def get_shape(self) -> Shape: if self._shape == "circle": return Circle() if self._shape == "square": return Square() raise ShapeError(f'Could not find shape "{self._shape}"') class Pet(ABC): """Abstraction of a pet.""" @abstractmethod def speak(self) -> str: """Interface for a pet to speak.""" pass class Dog(Pet): """A simple dog class.""" def __init__(self, name: str) -> None: self._dog_name: str = name def speak(self) -> str: return f"{self._dog_name} says Woof!" class Cat(Pet): """A simple cat class.""" def __init__(self, name: str) -> None: self._cat_name: str = name def speak(self) -> str: return f"{self._cat_name} says Meow!" def get_pet(pet: str) -> Pet: """The factory method.""" return {"dog": Dog("Hope"), "cat": Cat("Faith")}[pet] if __name__ == "__main__": factory: ShapeFactory = ShapeFactory(shape="circle") circle: Shape = factory.get_shape() # returns our shape circle.draw() # draw a circle # returns Cat class object get_pet("cat")
#CLASSES# #es para representar un punto en el espacio #estoy definiendo una nueva calse de cosas llamada "Point" class Point: # El "init" sirve para decirle a python, despues de crear la clas, que es lo que necesito para esta #self es el objeto de la clase que recien cree y despues con x, y defino atributos para ese objeto. def __init__(self, x, y): #voy aguardar x e y en self. self.x = x self.y = y #Y aca lo llevo a la practica. Si imprimo p.x y p.y. se van a imprimir los dos valores que defini en point p = Point(3, 5) #Aca imprimo el valor x de mi point print(p.x) #Aca imprimo el valor y de mi punto print(p.y)
#variable x que guarda el numero 28 x = -28 #funciones condicionales #si x es mayor que cero, imprimi "x es positive" if x > 0: print("x is positive") #en otro caso, si x es menor que cero, imprimi "x is negative" elif x < 0: print("x is negative") #en cualquier otro caso, imprimi "x is zero" else: print("x is zero") #indentation es important en python. Es decir, que en que posicion escribo las cosas importa.
#sorting characters in a string string = str(input()) def alphabet_soup (string): create_list = string get = list (create_list) get.sort() join = ''.join(get) return join print (alphabet_soup(string))
#add items to list and then sort from largest to smallest number. Shout out to AR items = [4,1,2,12,98,58] #user to add items to list def user_input (items): user_in = (int(input("Enter an integer: "))) items.append(user_in) return items #sort function with AR def sort(items): empty_list = [] for i in range (0, len(items)): empty_list.append(max(items)) items.remove(max(items)) return empty_list #print results print (sort(items))
import random def lev_del(word): r = random.randint(0, len(word) -1) w = word[:r] + word[r+1:] assert(len(w) == len(word) - 1) return w def lev_add(word): l = chr(ord('a') + random.randint(0,25)) r = random.randint(1, len(word) -1) w = word[:r] + l + word[r:] assert(len(w) == len(word) + 1) return w def lev_subst(word): l = chr(ord('a') + random.randint(0,25)) r = random.randint(1, len(word) -1) w = word[:r] + l + word[r+1:] assert(len(w) == len(word)) return w def lev2(word): r = random.randint(0,2) if r == 0: return lev_del(lev_del(word)) elif r == 1: return lev_add(lev_add(word)) else: return lev_subst(word) for n in range(2,100): words = set([lev2('Levenshtein') for i in range(n)]) text = 'What do the words %s all have in common?' % ', '.join(words) print '%3d: %3d %s' % (n, len(text), text) if len(text) > 140: break good_text = text print '-' * 80 print good_text
print('calResult') a = float(input('Please Enter a:')) b = float(input('Please Enter b:')) c = float(input('Please Enter c:')) Result = ((4.2*a)+(2.8*b))/(((5*b)/a)-(7*c)) print('Result is '+str(Result))
import psycopg2 import sys #connect to the database conn=psycopg2.connect(database='tcount', user="postgres", password="pass", host="localhost", port="5432") curs=conn.cursor() #if there is no argument on the command line get the words and counts in ascending order if len(sys.argv) == 1: sql = "SELECT word, count FROM tweetwordcount ORDER by lower(word) ASC;" curs.execute(sql) #put the results in a results array recs = curs.fetchall() #build the output string by looping through the records prstr = "" for rec in recs: prstr += "(" + rec[0] + ", " + str(rec[1]) + "), " print prstr[:-2] #if there is an argument on the command line get the count for the supplied word elif len(sys.argv) == 2: word = sys.argv[1] sql = "SELECT count FROM tweetwordcount WHERE word='%s';"%(word) curs.execute(sql) recs = curs.fetchall() for rec in recs: cnt = int(rec[0]) print 'Total number of occurrences of "%s": %d'%(word, cnt) else: print "please enter zero or one argument" conn.commit() conn.close()
"""File with implementation of StartWriter and EndWriter classes.""" import turtle from constants import BLOCK_PIXEL_SIZE class StartWriter(turtle.Turtle): """A class to write informations for the player at the start of the game.""" def __init__(self, maze_size): turtle.Turtle.__init__(self) self.maze_border = ((maze_size - 1) // 2) * BLOCK_PIXEL_SIZE self.color("orange") self.penup() self.hideturtle() self.speed(0) self.goto(-self.maze_border, self.maze_border+BLOCK_PIXEL_SIZE) class EndWriter(turtle.Turtle): """A class to write informations for the player at the end of the game.""" def __init__(self, maze_size): turtle.Turtle.__init__(self) self.maze_border = ((maze_size - 1) // 2) * BLOCK_PIXEL_SIZE self.color("red") self.penup() self.hideturtle() self.speed(0) self.goto(-self.maze_border, -self.maze_border-(BLOCK_PIXEL_SIZE * 2))
from enum import IntEnum class HasState(object): """ This interface allows a read-only access to states of a Thing. All implementations of this interface must to have a 'state' property and declare a concrete list (enumeration) of all states possible. Also it's needed to mention that if the device provides both ``has_state`` and ``is_active`` capabilities, than all of its states can be mapped onto two big categories of states: either "active" or "inactive" states. In such case, an additional ``is_active`` field is provided. For more information, see documentation for IsActive capability and docs for specific device type or implementation. 'unknown' state is considered as an 'inactive' binary state. Things are must to preserve their last known state even after they become unavailable. And all client classes must to be ready to this fact (i.e. analyze a time of the last update in last_updated property, analyze an availability status in is_available property and so on). """ _capability_name = 'has_state' class States(IntEnum): """ Possible states of the thing. Must be overridden in derived classes with 'unknown' state preserved """ unknown = -1 @property def state(self) -> 'States': """ Return a current state of the Thing :return: an instance of self.State """ raise NotImplementedError()
""" This module contains definition of Has Color Temperature capability """ class HasColorTemperature(object): """ Color Temperature devices are devices that have the "color temperature" property. The color temperature is expressed in Kelvins and can take integer values from 1000 to 10000 including. The color temperature of light source or other Actuator can be set with ``set_color_temp`` command. If the Thing doesn't support specified color temperature value (i.e. it's too low or too high for this Thing), then the color temperature will be set to the nearest supported value. """ _capability_name = 'has_color_temp' _commands = ('set_color_temp',) @property def color_temp(self) -> int: """ Returns the current color temperature of a Thing in Kelvins :return: the current color temperature in Kelvins """ raise NotImplementedError()
""" This module contains definition of Has Volume capability """ class HasVolume(object): """ Has Value devices are devices that have the "volume" property - the measure of loudness, i.e. of how loud its sound is. Volume is an integer value in the range from 0 (zero) to 100 including. Actuator Has Volume devices are able to change their volume with a set_volume command. """ _capability_name = 'has_volume' _commands = ('set_volume', ) @property def volume(self) -> int: """ Returns the value of volume (loudness) for this Thing in integers from 0 to 100 including. :return: the current volume (loudness) for this Thing """ raise NotImplementedError()
""" This module contains definition of Has Color HSB capability """ from .has_brightness import HasBrightness class HasColorHSB(HasBrightness): """ Has Color HSB devices are devices that have a "color" property. The current color is specified using three components: hue, saturation and brightness. Each component has its own property with a corresponding name. Actuator Has Color devices are able to change their color with a set_color command. Usually Color HSB profile is implemented by RGB Light Bulbs. """ _capability_name = 'has_color_hsb' _commands = ('set_color', ) + HasBrightness._commands @property def color_hue(self) -> float: """ Returns the "hue" color component in floating-point values from 0.0 to 360.0 including :return: the "hue" color component """ raise NotImplementedError() @property def color_saturation(self) -> float: """ Returns the "saturation" color component in floating-point values from 0.0 to 100.0 including :return: the "saturation" color component """ raise NotImplementedError()
a = 'é' b = 'MELHOR' c = 'que' d = 'FEITO' e = 'perfeito' print(f'{a.upper()} {b.lower()} {d.upper()} {c.lower()} {e.lower()}')
#!python # 2018 - Alessandro Di Filippo - CNR IMAA """ This function calculates the datalogger uncertainty for a specific temperature value using the calibration coefficients and the datalogger id. First it finds the resistance of the PRT using the calibration coefficients and the quadratic equation. An if statement determines the datalogger used, then calculates the voltage measured by the datalogger using the equation in the PTU, different for each datalogger. Both dataloggers have different uncertainties over different temperature ranges so these are determined by an if statement. The process is then effectively done in reverse to find the dataloggers effect uncertainty in temperature. For the CR3000 the measured voltage is then set to 0, this is done so that the fixed resistor uncertainties, which are not relevant to measurements recorded using the CR3000, are also 0. The function input parameters are: - t type: float desc: temperature - c0 type: float desc: - c1 type: float desc: - c2 type: float desc: - dlid type: float desc: datalogger id-type (CR23X, CR3000) The function output parameters are: - terr type: numpy array desc: datalogger uncertainty - measuredv type: numpy array desc: measured V - measuredr type: numpy array desc: measured R """ import numpy as np def errorestimation3(t, c0, c1, c2, dlid): fixedr = 10000 # fixed resistor used in CR23X interface in ohms fixedv = 1800 # Voltage used in CR23X interface in mV fullscalerange = 400 # full scle range used in CR23X +-200mV # estimates the resistance across the sensor by working backwards from the cal. equation measuredr = (-c1 + np.sqrt(c1 ** 2 - 4 * c2 * (c0 - t))) / (2 * c2) measuredv = 0 # if dl=CR23X if dlid == 1: # estimates v across sensor, from the resistance across the sensor and reference v and fixed resistor measuredv = (fixedv * measuredr) / (measuredr + fixedr) if t >= 0 and t <= 40: # u for 0<t<40, see CR23X specification sheet dlerr = 0.00015 else: # u outside the range 0<t<40, see CR23X specification sheet dlerr = 0.0002 # u in v = u(dl)*full scale range verr = dlerr * fullscalerange # uses relationship of v and r to find u(r) rerr = -fixedr / (1 - (fixedv / (measuredv + verr))) # if dl=CR3000 elif dlid == 2: # estimates v measured by the datalogger using the resistance accross the PRT from the calibration equation # the excitation current of 167 micro amps and Ohm's law measuredv = 167e-6 * measuredr if t >= 0 and t <= 40: # u for 0<t<40, see CR3000 specification sheet dlerr = 0.0002 elif t < -25 or t > 50: # u for outside the range -25<t<50, see CR3000 specification sheet dlerr = 0.0003 else: # u within the range -25<t<50 but outside 0<t<40, see CR3000 specification sheet dlerr = 0.00025 # u in v = u(dl)*(measured v + offset) verr = dlerr * (measuredv + 1.5 * (6.67e-6) + 1e-6) # error in resistance which is used to calculate the error in temperature using the calibration equation rerr = (measuredv + verr) / 167e-6 # sets measured v output to 0, this is so that when it comes to calculating the uncertainty from the fixed # resistor this is 0, as no fixed resistor is used with the CR3000 datalogger measuredv = 0 terr = c0 + (c1) * (rerr) + (c2) * (rerr) ** 2 - t return terr, measuredv, measuredr
""" Checks if a specific word exists in ANY of the ground truth or machine results. """ import os import sys import json import argparse from tqdm import tqdm from collections import Counter from typing import List, Dict, Any, Tuple import preproc.util def main(args): if not os.path.exists(args.machine_dir): print(f"Path does not exist: {args.machine_dir}") sys.exit(1) if not os.path.exists(args.gt_dir): print(f"Path does not exist: {args.gt_dir}") sys.exit(1) gt_counter = load_and_count_json(args.gt_dir) machine_counter = load_and_count_json(args.machine_dir) result = find_untranscribed_words(gt_counter, machine_counter) for x in result: print(x) return 0 def find_untranscribed_words( gt: Counter, machine: Counter ) -> List[Dict[str, any]]: """ Finds untranscribed words. That is, we find if there exist words in the GT which never occur in the machine transcription. :param gt: Counter of GT words. :param machine: Counter of machine words. :return: List of word/counts which occur in GT but not (or infrequently) in the machine transcription. """ result: List[Dict[str, any]] = [] for word, gt_count in gt.most_common(): if word not in machine: machine_count = 0 else: machine_count = machine[word] if gt_count > 0 and machine_count == 0: r = {"word": word, "machine": machine_count, "gt": gt_count} result.append(r) return result def load_and_count_json(fqn: str) -> Counter: """ Loads a json file and counts the occurrence of words. :param fqn: Path to the json file. :return: Counter of words. """ ls = os.listdir(fqn) counter = Counter() for i in tqdm(range(len(ls))): filename = ls[i] with open(os.path.join(fqn, filename), "r") as f: A = json.load(f) for B in A["results"]: for C in B["alternatives"]: for D in C["words"]: word = D["word"] word = preproc.util.canonicalize_word(word) if word != "": counter[word] += 1 return counter if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "machine_dir", type=str, help="Location of the predicted json transcriptions.", ) parser.add_argument( "gt_dir", type=str, help="Location of the ground truth json transcription.", ) main(parser.parse_args())
""" This script converts the ground truth transcriptions from TXT format into a structured JSON format, matching the Google Speech API format. """ import os import re import json import argparse import pandas as pd from typing import Dict, Tuple, List from tqdm import tqdm from pandas import DataFrame import preproc.util import preproc.config import evaluation.config def main(args): # Load the metadata file. meta = pd.read_csv(preproc.config.meta_fqn, sep="\t") # For each test-set row, check if the gold and audio file exists. count = 0 for i, row in meta.iterrows(): asr_test = row["asr_test"] gold_path = row["gold_path"] hash_ = row["hash"] if asr_test: count += 1 _, results = gt2dict(gold_path) # Confirm if audio file exists. flac_fqn = os.path.join( "/vol0/psych_audio/jasa_format/flac", f"{hash_}.flac" ) if not os.path.exists(flac_fqn): print(f"Audio does not exist: flac_fqn") continue # Write the GT json file. out_fqn = os.path.join(args.output_dir, f"{hash_}.json") with open(out_fqn, "w") as f: json.dump(results, f, indent=2, separators=(",", ": ")) def gt2dict(trans_fqn: str) -> (List[str], Dict): """ Converts a ground truth human transcription file in the format: X [TIME: MM:SS] Transcribed sentence containing various words like this. where X is T=therapist or P=patient and MM:SS is the time. :param trans_fqn: Full path to the ground truth transcription. :return: Full path to the audio file for this transcription. Dictionary containing the transcriptions, in the same format as Google Speech API. """ # Create the mapping of audio filename to hash. with open(trans_fqn, "r") as f: lines = f.readlines() lines = [x.strip() for x in lines] # Remove newlines. audio_filenames = None results = [] for line_no, line in enumerate(lines): # First four lines are header data. # First line is in the format: `Audio filename: XXX` where XXX is a variable-length audio filename. if line_no == 0 and "audio" in line.lower(): # Find start index of the filename. idx = line.find(":") + 1 stripped_line = line[idx:].strip() if " " in stripped_line: audio_filenames = stripped_line.split(" ") else: audio_filenames = [stripped_line] elif "[TIME:" in line: # Extract the speaker ID and time. speaker_id = line[0].upper() subphrases = preproc.util.get_subphrases(line) for phrase in subphrases: time_str, text = phrase mm, ss = preproc.util.get_mmss_from_time(time_str) ts = f"{mm * 60 + ss}.000s" words = [] for x in text.split(" "): if len(x) > 0: words.append(x) # Compose the JSON entries. words_label = [ {"startTime": ts, "word": x, "speakerTag": speaker_id} for x in words ] label = { "alternatives": [ {"transcript": text, "words": words_label} ], "languageCode": "en-us", } results.append(label) results = {"results": results} return audio_filenames, results if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "output_dir", type=str, help="Location to store the output JSON files." ) parser.add_argument( "--no_meta_check", action="store_true", help="Used for code development only.", ) args = parser.parse_args() main(args)
#content def c_peg(): return "O" def c_empty(): return "_" def c_blocked(): return "X" def is_empty(e): return e==c_empty() def is_peg(e): return e==c_peg() def is_blocked(e): return e==c_blocked() #position #Tuple(line,column) def make_pos(l,c): return (l,c) def pos_l(pos): return pos[0] def pos_c(pos): return pos[1] #move #List[pos_i,pos_f] def make_move(i,f): return [i,f] def move_initial(move): return move[0] def move_final(move): return move[1] # Return the coordinates of the position in the middle of the move def move_middle(move): # Lines of the initial and final positions involved in the move l_initial = pos_l(move_initial(move)) l_final = pos_l(move_final(move)) # Columns of the initial and final positions involved in the move c_initial = pos_c(move_initial(move)) c_final = pos_c(move_final(move)) l = ( l_initial + l_final ) // 2 c = ( c_initial + c_final ) // 2 return make_pos(l,c) #board #List of Lists of content def board_dim(board): return (len(board),len(board[0])) def board_lines(board): return board_dim(board)[0] def board_cols(board): return board_dim(board)[1] def pos_content(board,position): return board[pos_l(position)][pos_c(position)] def change_pos_content(board,position,content): board[pos_l(position)][pos_c(position)]=content # Checks if "move" is a correct play in given board # *!* check if move positions have the same row or column? def can_move(board,move): # Getting the content of the board in the initial, middle and final # positions of the movement initial_content = pos_content(board,move_initial(move)) middle_content = pos_content(board,move_middle(move)) final_content = pos_content(board,move_final(move)) return is_peg(initial_content) and is_peg(middle_content) and is_empty(final_content) #returns all the moves that can be made INTO the position. #to get all the moves that can be made FROM the position, switch pos and i_pos in lines 'm=make_move()' def position_moves(pos,board): moves=[] #not in left border if pos_c(pos)>=2: i_pos=make_pos(pos_l(pos),pos_c(pos)-2) m=make_move(i_pos,pos) if can_move(board,m): moves=moves+[m] #not in upper border if pos_l(pos)>=2: i_pos=make_pos(pos_l(pos)-2,pos_c(pos)) m=make_move(i_pos,pos) if can_move(board,m): moves=moves+[m] #not in right border if pos_c(pos)<=board_cols(board)-3: i_pos=make_pos(pos_l(pos),pos_c(pos)+2) m=make_move(i_pos,pos) if can_move(board,m): moves=moves+[m] #not in lower border if pos_l(pos)<=board_lines(board)-3: i_pos=make_pos(pos_l(pos)+2,pos_c(pos)) m=make_move(i_pos,pos) if can_move(board,m): moves=moves+[m] return moves #returns a list with all the available moves in a board def board_moves(board): moves=[] for i in range(board_lines(board)): for j in range(board_cols(board)): pos = make_pos(i,j) content = pos_content(board, pos) # If that position is empty, find possible moves if is_empty(content): moves=moves+position_moves(pos,board) return moves #returns a copy of a board def board_cpy(board): board_cpy=[] for i in range(board_lines(board)): line_cpy=[] for j in range(board_cols(board)): line_cpy=line_cpy+[pos_content(board,make_pos(i,j))] board_cpy=board_cpy+[line_cpy] return board_cpy #makes a move, initial board remains the same (makes a copy) def board_perform_move(board,move): if not can_move(board,move): return False board_cp=board_cpy(board) change_pos_content(board_cp,move_initial(move),c_empty()) change_pos_content(board_cp,move_middle(move),c_empty()) change_pos_content(board_cp,move_final(move),c_peg()) return board_cp #returns the number of pieces in a board. This should only be called in the initial #board, then remove 1 piece for each move made def board_pieces(board): pieces_number=0 for i in range(board_lines(board)): for j in range(board_cols(board)): if is_peg(pos_content(board,make_pos(i,j))): pieces_number = pieces_number + 1 return pieces_number def print_board(board): for r in board: print(r) if __name__ == "__main__": O = c_peg() X = c_blocked() _ = c_empty() b1 = [ [_,O,X], [O,O,_], [_,O,X] ] """ b1 = [[_,O,X],[O,O,_],[_,O,X]] """ print(b1)
from matplotlib import pyplot as plt import numpy as np from pathlib import Path """ The algorithm assumes that, under a white light source, the average colour in a scene should be achromatic (grey, [128, 128, 128]). You do not need to apply any pre or post processing steps. For the calculation or processing, you are not allowed to use any available code or any dedicated library function except standard Numpy functions . """ def greyworld_correction(img): _img = img.copy() original_shape = _img.shape M, N = original_shape[0], original_shape[1] # Reshape image to (3, MN) — list of RGB 3-tuples, tranposed _img = _img.reshape(M*N, 3).T print(_img.shape) # Convert RBG to xyz (LMS) space with a transformation matrix (von Kries) # https://ixora.io/projects/colorblindness/color-blindness-simulation-research/ B = np.array([[0.31399022, 0.63951294, 0.04649755], [0.15537241, 0.75789446, 0.08670142], [0.01775239, 0.10944209, 0.87256922]]) B_inv = np.array([[5.47221205, -4.64196011, 0.16963706], [-1.12524192, 2.29317097, -0.1678952], [0.02980163, -0.1931807, 1.1636479]]) # Apply the RGB -> LMS transformation to iamge using python's dot operator _img = B @ _img # Calculate the average colour value for each channel mean_rgb = np.mean(_img, axis=1) f = 2.0 # Scaling factor that depends on scene # Loop through the RGB values and apply greyworld adjustments (divide RGB by mean RGB) adj_img = [] for pixel in _img.T: adj_img.append([ pixel[0] / (f * mean_rgb[0]), pixel[1] / (f * mean_rgb[1]), pixel[2] / (f * mean_rgb[2]), ]) # Convert the list of output pixels to an array and transpose adj_img = np.array(adj_img).T # Convert back to RGB colourspace adj_img = B_inv @ adj_img # Reshape into a 2D image adj_img = adj_img.T.reshape(original_shape) return adj_img if __name__ == "__main__": IMG_PATH = Path('awb.jpg') # Read the image img = plt.imread(IMG_PATH) print(f"{IMG_PATH}: {img.shape}") conv_img = greyworld_correction(img) # Calculate average pixel values for both images M, N = img.shape[0], img.shape[1] mean_rgb_orig = np.mean(img.reshape(M*N, 3).T, axis=1) mean_rgb_conv = np.mean(conv_img.reshape(M*N, 3).T, axis=1) print(mean_rgb_orig, mean_rgb_conv) fig, axes = plt.subplots(1, 2) axes[0].imshow(img) axes[1].imshow(conv_img) # Remove axes and fill the available space axes[0].axis('off') axes[1].axis('off') plt.tight_layout() plt.show()
#!/usr/bin/env python listIndex = [9,19,25,100,200,321] mylist = [[],[],[],[],[],[],[]] def findIndex(index,data): min = 0 max = len(index) -1 while(min <= max): mid = (max + min) // 2 if data > index[mid]: min = mid + 1 else: max = mid -1 return max + 1 def searchBlock(mylist,data): for i in range(0,len(mylist)): if data == mylist[i]: return i return -1 def insert(index,value): item = findIndex(index,value) if searchBlock(mylist[item],value) >= 0: print value, 'is already exist in list',item return False else: mylist[item].append(value) return True def search(index,value): item = findIndex(index,value) location = searchBlock(mylist[item],value) if location >= 0: print value,'is in block',item,'location:',location else: print 'can not find',value if __name__=='__main__': data = [0,2,3,201,1,3,4,14,14,23,34,56,78,90,100,198,340,324,67,890,0,-123,45,67,89,3,5,90,45,67] for i in range(0,len(data)): insert(listIndex,data[i]) print mylist[0] print mylist[1] print mylist[2] print mylist[3] print mylist[4] print mylist[5] print mylist[6] search(listIndex, 0) search(listIndex, 7) search(listIndex, 56) search(listIndex, 11) search(listIndex, 324)
#!/usr/bin/python import time import random # This function in mergesort algorithm divides the list into various sublists # and then sorts by later merging into give sorted array. def mergeSort(array): if len(array) > 1: mid = len(array)//2 leftArr = array[:mid] rightArr = array[mid:] mergeSort(leftArr) mergeSort(rightArr) i = 0 j = 0 k = 0 while i < len(leftArr) and j < len(rightArr): if leftArr[i] <= rightArr[j]: array[k] = leftArr[i] i += 1 else: array[k] = rightArr[j] j += 1 k += 1 while i < len(leftArr): array[k] = leftArr[i] i += 1 k += 1 while j < len(rightArr): array[k] = rightArr[j] j += 1 k += 1 return array # The main function is called when the code block is executed. def main(): array = [] for _ in range(100): temp = random.randint(0, 500) array.append(temp) tBefore = time.time() y = mergeSort(array) tAfter = time.time() print('Sorted Array : ' ,y) totaltime = tAfter - tBefore print('Execution Time [Merge sort algorithm]: ',totaltime) if __name__ == '__main__': main()
#!/usr/bin/python import unittest from .. import wordtree class TestWordTree(unittest.TestCase): def test_empty_dictionary(self): tree = wordtree.WordTree([]) self.assertEqual(0, tree.count()) def test_count_one_entry(self): tree = wordtree.WordTree(['as']) self.assertEqual(1, tree.count()) def test_word_one_entry(self): tree = wordtree.WordTree(['as']) self.assertTrue(tree.is_word('as')) def test_not_word_prefix_one_entry(self): tree = wordtree.WordTree(['as']) self.assertFalse(tree.is_word('a')) def test_not_word_suffix_one_entry(self): tree = wordtree.WordTree(['as']) self.assertFalse(tree.is_word('astatine')) def test_prefix_one_entry(self): tree = wordtree.WordTree(['as']) self.assertTrue(tree.is_prefix('a')) def test_not_prefix_one_entry(self): tree = wordtree.WordTree(['as']) self.assertFalse(tree.is_prefix('z')) def test_count_two_entries(self): tree = wordtree.WordTree(['as', 'at']) self.assertEquals(2, tree.count()) def test_word_two_entries(self): tree = wordtree.WordTree(['as', 'at']) self.assertTrue(tree.is_word('as')) self.assertTrue(tree.is_word('at')) def test_longer_words(self): tree = wordtree.WordTree(['astatine', 'asterisk', 'at', 'as', 'ass']) self.assertTrue(tree.is_word('as')) self.assertTrue(tree.is_word('at')) self.assertTrue(tree.is_word('ass')) self.assertFalse(tree.is_word('astatin')) def test_longer_prefixes(self): tree = wordtree.WordTree(['astatine', 'asterisk', 'at', 'as', 'ass']) self.assertTrue(tree.is_prefix('as')) self.assertTrue(tree.is_prefix('astatin')) self.assertFalse(tree.is_prefix('astatinf')) self.assertFalse(tree.is_prefix('astatines'))
# user = [] # list_user = [["ngoc","[email protected]","123"]] # # def login(): # pass # # def register(): # username = raw_input("username: ") # username = nullValidator(username, "username") # # email = raw_input("email: ") # email = nullValidator(email, "email") # # # password= raw_input("password: ") # password = nullValidator(password, "password") # # while True: # password2 = raw_input("Re-enter password: ") # if password == password2: # print "Dang ky thanh cong" # user.append(username) # user.append(email) # user.append(password) # list_user.append(user) # print list_user # else: # print "Password khong trung" # # # def nullValidator(input, message): # while True: # if input == "": # print message + " khong duoc de null" # input = raw_input("Hay nhap lai " + message +" :") # return input # else: # break # # # while True: # print "1.Dang ky" # print "2.Dang nhap" # # choice = raw_input("Nhap lua chon cua ban: ") # if choice == "1": # register() # if choice == "2": # login() while True: email = raw_input("") check = False for i in range(len(email)): if email[i] == "@": print "Dung" check = True domain = email[(i+1):] print domain while True: for char in domain: check2 = False if char == ".": print "Co ." check2 = True break if check2: break if not check2: print "Phai co dau cham" break if check2: break if not check: print "Not found"
list_user = [] ["Ngoc", "[email protected]", "123"] ["Uyen", "[email protected]", "123"] list_user = [["Ngoc", "[email protected]", "123"], ["Uyen", "[email protected]", "123"]] # def none(input): # while True: # check=False # username=input("username:") # if username=="": # print("Khong duoc de trong") # check=True # return check while True: while True: check = False username = input("username:") if username == "": print("Khong duoc de trong") check = True else: break while True: check1 = False email = input("email:") if email == "": print("Khong duoc de trong") check1 = True else: check3 = False for char in email: if char == "@": check3 = True x = email check4 = False for i in range(len(email)): if email[i] == "@": domain = x[(i + 1):] check4 = False while True: for char1 in domain: if char1 == ".": check4 = True break if check4: break if check4 == False: print("Email phai co dau cham") if check3: break if check3 == False: print("email phai co @") while True: check2 = False password = input("password:") if password == "": print("Khong duoc de trong") check = True else: password2 = input("password2:") if password == password2: print ("Dang ky thanh cong") break else: print ("Nhap lai password") user = [username, email, password] list_user.append(user) print(list_user)
import numpy as np import scipy.stats as st def mean_intervals(data, confidence=0.95, axis=None): """ Compute the mean, the confidence interval of the mean, and the tolerance interval. Note that the confidence interval is often misinterpreted [3]. References: [1] https://en.wikipedia.org/wiki/Confidence_interval [2| https://en.wikipedia.org/wiki/Tolerance_interval [3] https://en.wikipedia.org/wiki/Confidence_interval#Meaning_and_interpretation """ confidence = confidence / 100.0 if confidence > 1.0 else confidence assert(0 < confidence < 1) a = 1.0 * np.array(data) n = len(a) # Both s=std() and se=sem() use unbiased estimators (ddof=1). m = np.mean(a, axis=axis) s = np.std(a, ddof=1, axis=axis) se = st.sem(a, axis=axis) t = st.t.ppf((1 + confidence) / 2., n - 1) ci = np.c_[m - se * t, m + se * t] ti = np.c_[m - s * t, m + s * t] assert(ci.shape[1] == 2 and ci.shape[0] == np.size(m, axis=None if axis is None else 0)) assert(ti.shape[1] == 2 and ti.shape[0] == np.size(m, axis=None if axis is None else 0)) return m, ci, ti def mean_confidence_interval(data, confidence=0.95, axis=None): """ Compute the mean and the confidence interval of the mean. """ m, ci, _ = mean_intervals(data, confidence, axis=axis) return m, ci def mean_tolerance_interval(data, confidence=0.95, axis=None): """ Compute the tolerance interval for the data. """ m, _, ti = mean_intervals(data, confidence, axis=axis) return m, ti
#### 람다 표현식 # # 일반 함수 # def add(a, b): # return a + b # print(add(3, 7)) # # 람다 표현식으로 구현한 add() 메서드 # print((lambda a, b: a + b)(3, 7)) # ## 내장 함수에서 자주 사용되는 람다 함수 # array = [('홍길동', 50), ('이순신', 32), ('아무개', 74)] # def my_key(x): # return x[1] # print(sorted(array, key = my_key)) # print(sorted(array, key = lambda x: x[1])) ## 여러 개의 리스트에 적용 list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9, 10] # map 함수 : 각각의 원소에 함수를 적용하고자 할 때 사용 result = map(lambda a, b: a + b, list1, list2) print(list(result))
# Pirma užduotis class first: # Sukūriama klasė first def summing_function(self, n, a, b): # Sukūriama funkcija summing_function, kuriai perduodami trys parametrai n, a, b try: given_text=list(n) # given_text yra n kintamojo listas positive_symbols=list(a) # positive_symbols yra a kintamojo listas negative_symbols=list(b) # negative_symbols yra b kintamojo listas temp_negative=0 # Priskiriama 0 reikšmė kintamiesiems, kuriuos naudosiu cikle temp_positive=0 try: for symbol in given_text: # Pradedu for ciklą for negative in negative_symbols: # Pradedu antrą ciklą neigiamų simbolių radimui if (symbol==negative): # Jeigu yra rastas neigiamas simbolis, tai prie temp_negative yra pridedamas 1 temp_negative+=1 for positive in positive_symbols: # Pradedu trečią ciklą teigiamų simbolių radimui if (symbol==positive): # Jeigu yra rastas teigiamas simbolis, tai prie temp_positive yra pridedamas 1 temp_positive+=1 except: print("Problema su ciklu!") result=temp_positive-temp_negative # Sukurtas result kintamasis, kuriame yra atimama negative suma iš positive print("Jūsų rezultatas: "+str(result)) except: print("Bandykite iš naujo!") fi=first() # Priskiriamas kintamasis klasei fi.summing_function("vienas du trys", "vn ", "ayds") # Iškviečiama summing_function funkcija, kai programa yra paleidžiama fi.summing_function("keturiolika", "ktur", "ila")
# Prompt user for input integer = int(input("Enter an integer: ")) # Determine and display if integer is divisible by 2 and 5 if (integer % 2) == 0 and (integer % 5) == 0: print("Integer: " + str(integer) + ", is divisible by 2 and 5") else: print("Integer: " + str(integer) + ", is not divisible by 2 and 5") # Determine and display if integer is divisible by 2 or 5 if (integer % 2) == 0 or (integer % 5) == 0: print("Integer: " + str(integer) + ", is divisible by 2 or 5") else: print("Integer: " + str(integer) + ", is not divisible by 2 or 5") # Determine and display if integer is not divisible by 2 or 5 if (integer % 2) != 0 or (integer % 5) != 0: print("Integer: " + str(integer) + ", is not divisible by 2 or 5") else: print("Integer: " + str(integer) + ", is divisible by 2 or 5")
# Prompt user to enter full name user_name = input("Enter your full name: ") # Validate to ensure user enters an input if len(user_name) == 0: print("You haven’t entered anything. Please enter your full name.") # Validate to ensure full name is not less than 4 characters elif len(user_name) < 4: print("You have entered less than 4 characters. Please make sure that you have entered your name and surname."); # Validate to ensure full name is not more than 25 characters elif len(user_name) > 25: print("You have entered more than 25 characters. Please make sure that you have only entered your full name"); # If all validations pass, print out Thank you for entering your name else: print("Thank you for entering your name.")
#!/usr/bin/env python # coding=utf-8 import sys def fun(): offen = "" total = 0 vehicles = "" word = None for line in sys.stdin: word,count = line.strip().rsplit("\t",1) num = count.split(",")[0] vehicle = count.split(",")[1] if offen == word: total += int(num) vehicles+=","+vehicle else: if offen: print(offen + "\t" + str(total)+"\t"+vehicles) offen = word vehicles =vehicle total = int(num) if offen == word: print( offen+ "\t" + str(total)+"\t"+vehicles) if __name__ == "__main__": fun()
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: # will be forwarding over at each step carry = 0 # variable for final result final_result = ListNode(0) # var to use in order to move towards the next node at each iteration pointer = final_result # note any update in pointer will reflect on final_result #iterate over the linked lists while l1 or l2 or carry: # get the digits from the individual nodes # use if statement to handle when val is None first_number = l1.val if l1.val else 0 second_number = l2.val if l2.val else 0 # add both numbers and any potential carry summation = first_number + second_number + carry # get the digit of the solution number = summation % 10 # get the carry with floor division carry = summation // 10 # store the result to the pointer pointer.next = ListNode(number) # move the pointer to the next node pointer = pointer.next # move the nodes of the list to the next if not none l1 = l1.next if l1 else None l2 = l2.next if l2 else None return result.next # Time Complexity: O(max(l1.len, l2.len))
#!/usr/bin/env python # coding=utf-8 class Node(object): def __init__(self, data=None): self.data = data self.next_node = None def get_data(self): return self.data def set_data(self, data): self.data = data def get_next(self): return self.next_node def set_next(self, node): self.next_node = node def has_next(self): return bool(self.next_node) class SingleLinkedList(object): def __init__(self): self.head = None self.size = 1 def __str__(self): p = self.head while p: print p.get_data(), p = p.get_next() return '' def add(self, data): node = Node(data) if not self.head: self.head = node return p = self.head while p.get_next(): p = p.get_next() p.set_next(node) self.size += 1 def length(self): return self.size def search(self, data): p = self.head while p.get_next(): if p.get_data() == data: return True p = p.get_next() return False def print_list(self): p = self.head while p: print p.data p = p.get_next() def remove(self, data): if self.head.get_data() == data: self.head.set_next(self.head.get_next()) print "Deleted data from list {}".format(data) return True p = self.head q = self.head.get_next() while q: if q.get_data() == data: p.set_next(q.get_next()) print "Deleted data from the list {}".format(data) return True print "Maybe the data you're trying to delete is not in the list." return False def insert_at_pos(self, data, pos): node = Node(data) if pos < 0 or pos > self.size + 1: # In an ideal world, this should throw ValueError. print "Cannot insert beyod the length of the list." if pos == 0: return self.insert_at_head(data) if pos == self.size: return self.insert_at_end(data) p = self.head q = self.head.get_next() for i in range(1, self.size): if i == pos: p.set_next(node) node.set_next(q) self.size += 1 print "Node inserted at position {}".format(pos) return p = q q = q.get_next() return def insert_at_head(self, data): node = Node(data) node.set_next(self.head) self.head = node self.size += 1 def insert_at_end(self, data): node = Node(data) p = self.head while p.get_next(): p = p.get_next() p.set_next(node) self.size += 1 if __name__ == '__main__': a = SingleLinkedList() a.add(1) a.add(2) a.add(3) a.add(4) # Print the list print a # Length of the list. print "Length of the list is {}".format(a.length()) # search node in list print a.search(2) a.remove(2) print a a.insert_at_head('a') print a a.insert_at_end('b') print a a.insert_at_pos('z', 4) print a
from os import system system("cls") satuan = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' ] def terbilang (n): if n % 1 > 0: cari_koma = str(n).find('.') angka_belakang_koma = str(n)[cari_koma+1:] angka_depan_koma = str(n)[0:cari_koma] int_angka_belakang_koma = int(angka_belakang_koma) int_angka_depan_koma = int(angka_depan_koma) return terbilang(int_angka_depan_koma)+" point " "+terbilang(int_angka_belakang_koma) elif n < 10: # satuan return satuan[int(n)] elif n >= 1_000_000_000: # milyar if n // 1_000_000_000 == 1: return " one billion " + terbilang(n % 1_000_000_000) if n % 1_000_000_000 != 0 else '' else: return terbilang(n // 1_000_000_000) + ' billion ' + terbilang(n % 1_000_000_000) if n % 1_000_000_000 != 0 else '' elif n >= 1_000_000: # jutaan if n // 1_000_000 == 1: return " one million " + terbilang(n % 1_000_000) if n % 1_000_000 != 0 else '' else: return terbilang(n // 1_000_000) + ' million ' + terbilang(n % 1_000_000) if n % 1_000_000 != 0 else '' elif n >= 1000: # ribuan if n // 1000 == 1: return " a thousand " + terbilang(n % 1000) if n % 1000 != 0 else '' else: return terbilang(n // 1000) + ' thousand ' + terbilang(n % 1000) if n % 1000 != 0 else '' elif n >= 100: # ratusan if n // 100 == 1: return " hundred " + terbilang(n % 100) if n % 100 != 0 else '' else: return terbilang(n // 100) + ' hundred ' + terbilang(n % 100) if n % 100 != 0 else '' elif n >= 20: # puluhan if n // 10 == 2: return ' twenty '+ terbilang(n%10) if n // 10 == 3: return ' fhirty '+ terbilang(n%10) if n // 10 == 4: return ' forty '+ terbilang(n%10) if n // 10 == 5: return ' fifty '+ terbilang(n%10) if n // 10 == 8: return ' eight '+ terbilang(n%10) else: return terbilang(n//10)+ 'ty' else: # belasan if n == 10: return 'ten' elif n == 11: return 'eleven' elif n == 12: return 'twelve' elif n == 13: return 'thirteen' elif n == 15: return 'fifteen' else: return terbilang(n % 10) + ("teen" if (n % 10 != 8) else "een" n = float(input("masukkan nilai : ")) print(f'{n if n%1>0 else int(n)} -> {terbilang(n)}')
import unittest from aids.linked_list.linked_list import LinkedList class LinkedListTestCase(unittest.TestCase): ''' Unit tests for the Linked List data structure ''' def setUp(self): self.test_linked_list = LinkedList() def test_stack_initialization(self): self.assertTrue(isinstance(self.test_linked_list, LinkedList)) def test_linked_list_is_empty(self): self.assertTrue(self.test_linked_list.is_empty()) def test_linked_list_size(self): self.test_linked_list.add(1) self.test_linked_list.add(2) self.assertEqual(self.test_linked_list.size(), 2) def test_linked_list_add(self): self.test_linked_list.add(1) self.assertEqual(self.test_linked_list.head.get_data(), 1) def test_linked_list_search(self): self.test_linked_list.add(1) self.test_linked_list.add(2) self.test_linked_list.add(3) self.test_linked_list.add(4) self.assertTrue(self.test_linked_list.search(3)) def test_linked_list_search_false(self): self.test_linked_list.add(1) self.test_linked_list.add(2) self.test_linked_list.add(3) self.test_linked_list.add(4) self.assertFalse(self.test_linked_list.search(11)) def test_linked_list_search_empty(self): self.assertFalse(self.test_linked_list.search(3)) def test_linked_list_remove_first(self): self.test_linked_list.add(1) self.test_linked_list.add(2) self.test_linked_list.add(3) self.test_linked_list.add(4) self.test_linked_list.remove(1) self.assertEqual(self.test_linked_list.head.get_data(), 2) def test_linked_list_remove_last(self): self.test_linked_list.add(1) self.test_linked_list.add(2) self.test_linked_list.add(3) self.test_linked_list.add(4) self.test_linked_list.remove(4) self.assertEqual(self.test_linked_list.size(), 3) def test_linked_list_remove(self): self.test_linked_list.add(1) self.test_linked_list.add(2) self.test_linked_list.add(3) self.test_linked_list.add(4) self.test_linked_list.remove(3) self.assertEqual(self.test_linked_list.size(), 3) def tearDown(self): pass
''' Implementation of Stack data structure ''' class Stack(object): def __init__(self): ''' Initialize stack ''' self.items = [] def is_empty(self): ''' Return True if stack if empty else False ''' return self.items == [] def push(self, item): ''' Push item to stack ''' self.items.append(item) def pop(self): ''' Pop item from stack ''' return self.items.pop() def peek(self): ''' Return value of item on top of stack ''' return self.items[-1] def __len__(self): ''' Return number of items in stack ''' return len(self.items)
''' Implementation of queue data structure ''' class Queue(object): def __init__(self): ''' Initialize queue ''' self.items = [] def is_empty(self): ''' Return True if queue if empty else False ''' return self.items == [] def enqueue(self, item): ''' Push item to queue ''' self.items.insert(0,item) def dequeue(self): ''' Pop item from queue ''' return self.items.pop() def __len__(self): ''' Return number of items in queue ''' return len(self.items)
import unittest from aids.strings.is_palindrome import is_palindrome class IsPalindromeTestCase(unittest.TestCase): ''' Unit tests for is_palindrome ''' def setUp(self): pass def test_is_palindrome_true_empty_string(self): self.assertTrue(is_palindrome('')) def test_is_palindrome_true(self): self.assertTrue(is_palindrome('madam')) def test_is_palindrome_false(self): self.assertFalse(is_palindrome('xxyyzz')) def tearDown(self): pass if __name__ == '__main__': unittest.main()
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Mon Feb 2 20:34:12 2015 @author: Markus Pfundstein, Thomas Meijers, Cornelis Boon """ from argparse import ArgumentParser from collections import OrderedDict from collections import Counter import string def sort_ngrams(ngrams): return OrderedDict(sorted(ngrams.items(), key=lambda x: x[1], reverse=True)) def make_grams(words, n): """ make n-grams from list of words """ return [string.join(words[i:i+n]) for i in xrange(len(words)-n+1)] def read_words(file_in): """ returns list of all words in file_in """ with open(file_in) as f: return [w for w in f.read().split()] def parse_ngrams(splitted_line, n): """ parses a file and makes (unsorted) frequency table of n-grams """ n_grams_frequency = {} if n < 1: return n_grams_frequency if n > 1: splitted_line = make_grams(splitted_line, n) return splitted_line def print_ngrams(n_grams, m = None): """ prints n grams """ idx = 0 for word, freq in n_grams.items(): if idx is m: break idx += 1 print '{} {}\n'.format(word, freq) if __name__ == "__main__": # here code for program parser = ArgumentParser(description='Assignment A, Step 1') parser.add_argument('-corpus', dest ='input_file', type=str, help='Path to corpus file') parser.add_argument('-n', dest='n', type=int, help='Length of word-sequences to process (n-grams)') parser.add_argument('-m', dest='m', type=int, default=None, help='Number of n-grams to show in output') args = parser.parse_args() lines = read_words(args.input_file) n_grams_frequency = Counter(parse_ngrams(lines, args.n)) freq_sum = sum(n_grams_frequency.values()) print 'sum: {}'.format(freq_sum) # sort n_grams by value in descending order n_grams_frequency = sort_ngrams(n_grams_frequency) print_ngrams(n_grams_frequency, args.m)
#Liam Collins #2/15/18 #favorites.py word = input('Enter your favorite word: ') num = int(input('Enter your favorite number: ')) i = 0 while i < num: print(word) i += 1 for i in range (0,num): print(word)
import math day1_data = open('day1_data.txt') """First, read the data and convert to list of integers. Next, convert the module masses to fuel. Finally, add all of the fuel to obtain the total for for the Fuel Counter Upper. """ def create_module_list(data): module_list = [int(i) for i in data] return module_list def convert_mass_to_fuel(module_list): fuel_list = [math.floor(mass / 3) - 2 for mass in module_list] return fuel_list def sum_total_fuel(fuel_list): total_fuel = sum(fuel_list) return total_fuel fuel_list = convert_mass_to_fuel(create_module_list(day1_data)) sum_total_fuel(fuel_list)
import sys from os import path from random import randint from binarySearch import binarySearch # Add algorithms directory to path sys.path.insert(0, \ r"D:\\github-projects\\algorithms\\quicksort\\python") from quicksort import quicksort sys.path.pop(0) ELEMENTS = 10 def testEmpty(): print("Running testEmpty():") arr = [] key = 1 assert(binarySearch(arr, key) == -1) print("***** PASS *****") def testInOrder(): arr = [] print("\nRunning testInOrder:") # Insert elements in order for i in range(ELEMENTS): arr.append(i) # Ensure we can find every element for i in range(ELEMENTS): assert(binarySearch(arr, i) != -1) print("***** PASS *****") def testRandom(): arr = [] # Range for random integers low, high = 0, 1000 print("\nRunning testRandom:") # Insert random elements for _ in range(ELEMENTS): arr.append(randint(low, high)) # Sort array quicksort(arr) # Ensure we can find all the elements in the array for num in arr: if (binarySearch(arr, num) == -1): print("Error: number {} not found in array".format(\ num)) #assert(binarySearch(arr, num) != -1) print("***** PASS *****") def main(): testEmpty() testInOrder() testRandom() if __name__ == "__main__": main() def template(): print("\nRunning template:") print("***** PASS *****")
# bayesNet.py import itertools import util class CPT(): """ A table that represents the conditional probabilities. This has two components, the dependencyList and the probTable. dependencyList is a list of nodes that the CPT depends on. probTable is a table of length 2^n where n is the length of dependencyList. It represents the probability values of the truth table created by the dependencyList as the boolean values, in the same order. That is to say is the depencyList contains A and B then probTable will have 4 values corresponding to (A, B) = (0, 0), (0, 1), (1, 0), (1, 1) in that order. """ def __init__(self, dependencies, probabilities): self.dependencyList = dependencies self.probTable = probabilities # print(self.dependencyList) # print(self.probTable) class BayesNetwork(): """ A network represented as a dictionary of nodes and CPTs """ def __init__(self, network): """ Constructor for the BayesNetwork class. By default it only takes in the network Feel free to add things to this if you think they will help. """ self.network = network # print(self.network) "*** YOUR CODE HERE ***" # print(self.network['B'].probTable) def singleInference(self, A, B): """ Return the probability of A given B using the Bayes Network. Here B is a tuple of (node, boolean). """ "*** YOUR CODE HERE ***" # self.network1 = network e = [] e.append(B) value = self.enum_ask(A, e, self.network) value = self.network1['False'] + self.network1['True'] value = round(self.network1['True']/value,4) return value util.raiseNotDefined() def enum_ask(self,X, e, bn): # return 0 self.network1 = util.Counter() cnt = 0 e_1 = [] e_2 = [] e_1.extend(e) e_2.extend(e) for x_i in X: for i in range(0,2): vars = [] vars.extend(bn.keys()) if cnt == 0: e_1.append((x_i, False)) cnt = (cnt + 1)%2 self.network1['False'] = self.enum_all(vars, e_1) else: e_2.append((x_i, True)) cnt = (cnt + 1)%2 self.network1['True'] = self.enum_all(vars, e_2) return self.network1 util.raiseNotDefined() def enum_all(self, vars, e): if len(vars) == 0: return 1.0 Y = vars[0] Y_e = self.search_in_e(Y, e) if len(Y_e) > 0: Y_ref = self.network[Y] dep_list_Y = Y_ref.dependencyList # print(dep_list_Y) probTable_Y = Y_ref.probTable parent_val = self.search_in_e(dep_list_Y, e) # print(Y_e[0][1]) # print(parent_val) if len(parent_val) == 0: if Y_e[0][1] == True: vars.remove(Y) return (probTable_Y[0] * self.enum_all(vars, e)) elif Y_e[0][1] == False: vars.remove(Y) return ((1 - probTable_Y[0]) * self.enum_all(vars, e)) if len(parent_val) == 1: if Y_e[0][1] == False: if parent_val[0][1] == False: vars.remove(Y) return ((1 - probTable_Y[0]) * self.enum_all(vars,e)) elif parent_val[0][1] == True: vars.remove(Y) return ((1 - probTable_Y[1]) * self.enum_all(vars,e)) elif Y_e[0][1] == True: if parent_val[0][1] == False: vars.remove(Y) return (probTable_Y[0] * self.enum_all(vars,e)) elif parent_val[0][1] == True: vars.remove(Y) return (probTable_Y[1] * self.enum_all(vars,e)) if len(parent_val) == 2: if Y_e[0][1] == False: vars.remove(Y) if (parent_val[0][1] == False) and (parent_val[1][1] == False): return ((1 - probTable_Y[0]) * self.enum_all(vars,e)) elif parent_val[0][1] == False and parent_val[1][1] == True: return ((1 - probTable_Y[1]) * self.enum_all(vars,e)) elif parent_val[0][1] == True and parent_val[1][1] == False: return ((1 - probTable_Y[2]) * self.enum_all(vars, e)) else: return ((1 - probTable_Y[3]) * self.enum_all(vars,e)) elif Y_e[0][1] == True: vars.remove(Y) if parent_val[0][1] == False and parent_val[1][1] == False: return ((probTable_Y[0]) * self.enum_all(vars,e)) elif parent_val[0][1] == False and parent_val[1][1] == True: return ((probTable_Y[1]) * self.enum_all(vars,e)) elif parent_val[0][1] == True and parent_val[1][1] == False: return ((probTable_Y[2]) * self.enum_all(vars, e)) else: return ((probTable_Y[3]) * self.enum_all(vars,e)) # return 1 if len(Y_e) == 0: e_y_1 = [] e_y_2 = [] sum = 0 e_y_1.extend(e) e_y_2.extend(e) Y_ref = self.network[Y] dep_list_Y = Y_ref.dependencyList probTable_Y = Y_ref.probTable # print(dep_list_Y) if len(dep_list_Y) == 0: e_y_1.append((Y, True)) e_y_2.append((Y, False)) vars.remove(Y) vars1 = [] vars1.extend(vars) vars2 = [] vars2.extend(vars) sum = sum + (probTable_Y[0] * self.enum_all(vars1, e_y_1)) + ((1 - probTable_Y[0]) * self.enum_all(vars2, e_y_2)) if len(dep_list_Y) == 1: e_y_1.append((Y, True)) e_y_2.append((Y, False)) vars.remove(Y) vars1 = [] vars1.extend(vars) vars2 = [] vars2.extend(vars) parent_val = self.search_in_e(dep_list_Y, e) # print(parent_val) if parent_val[0][1] == False: sum = sum + (probTable_Y[0] * self.enum_all(vars1,e_y_1)) + ((1 - probTable_Y[0]) * self.enum_all(vars2,e_y_2)) else: sum = sum + (probTable_Y[1] * self.enum_all(vars1,e_y_1)) + ((1 - probTable_Y[1]) * self.enum_all(vars2,e_y_2)) if len(dep_list_Y) == 2: # print("We are here") e_y_1.append((Y, True)) e_y_2.append((Y, False)) vars.remove(Y) vars1 = [] vars2 = [] vars1.extend(vars) vars2.extend(vars) # print(e_y_1," ",e_y_2) parent_val = self.search_in_e(dep_list_Y, e) # print(parent_val) if parent_val[0][1] == False and parent_val[1][1] == False: sum = sum + (probTable_Y[0] * self.enum_all(vars1, e_y_1)) + ((1 - probTable_Y[0]) * self.enum_all(vars2, e_y_2)) elif parent_val[0][1] == False and parent_val[1][1] == True: sum = sum + (probTable_Y[1] * self.enum_all(vars1, e_y_1)) + ((1 - probTable_Y[1]) * self.enum_all(vars2, e_y_2)) elif parent_val[0][1] == True and parent_val[1][1] == False: sum = sum + (probTable_Y[2] * self.enum_all(vars1, e_y_1)) + ((1 - probTable_Y[2]) * self.enum_all(vars2, e_y_2)) else: sum = sum + (probTable_Y[3] * self.enum_all(vars1, e_y_1)) + ((1 - probTable_Y[3]) * self.enum_all(vars2, e_y_2)) return sum # util.raiseNotDefined() def search_in_e(self, dep_list, e): list_ele = [] for e_search in e: for ele in dep_list: if ele == e_search[0]: list_ele.append(e_search) return list_ele def multipleInference(self, A, observations): """ Return the probability of A given the list of observations.Observations is a list of tuples. """ "*** YOUR CODE HERE ***" e = [] # print(type(observations)) cnt = 0 e.append((observations[0],observations[1])) e.append((observations[2],observations[3])) # print(e) # for obs in observations: # print(obs) # # e.append((obs[0],obs[1])) # e.append(observations) # print(e) value = self.enum_ask(A, e, self.network) value1 = self.network1['False'] + self.network1['True'] # value = round(self.network1['True']) value = round(self.network1['True']/value1,4) # if value == 0.4394: # value *= value1 # print(value) return value util.raiseNotDefined()
from pygame.locals import * import sys import random class EventControl(): """ Controls the game's events, e.g. what happens when a mouse button is pressed, or when a keyboard key is pressed (well, for now it's only that). Later, if more events are used, it'd be a good idea to separate "user input events" from other events. """ def __init__(self, events, bacteria, config, pygame, infobox, screentext): self.events = events self.infobox = infobox self.screentext = screentext self.bacteria = bacteria self.config = config self.pygame_state = pygame self.isPaused = False def process_events(self): """ Gathers and processes all events and returns changed lists of bacteria and game parameters. """ for self.event in self.events: self.manage_mouse() if not hasattr(self.event, 'key'): continue self.manage_keyboard() return self.bacteria, self.config, self.infobox, self.screentext def manage_mouse(self): """ Gathers all methods devoted to proess mouse input. """ self.mouse_bacteria() def manage_keyboard(self): """ Gathers all methods devoted to proess keyboard input. """ self.key_pause() self.key_quit() def mouse_bacteria(self): """ Decides what happens after clicking on a bacterium cell. Temporarily, for testing purposes, it randomly colors a clicked cell. """ if (self.event.type == self.pygame_state.MOUSEBUTTONDOWN and self.event.button == 1): pos = self.pygame_state.mouse.get_pos() clicked_on_bacterium = False # prev_clicked_bact = None for bact in self.bacteria: bact.highlighted = False if bact.rect.collidepoint(pos): clicked_on_bacterium = True self.mouse_hud_show() self.infobox.show_info(bact) bact.highlighted = True prev_clicked_bact = self.bacteria.index(bact) bact.draw_from_shapes() if clicked_on_bacterium is False: self.mouse_hud_hide() def mouse_hud_show(self): self.infobox.shown = True def mouse_hud_hide(self): self.infobox.shown = False def key_pause(self): """ Controls game pausing and unpausing using keyboard. """ if (self.event.type == self.pygame_state.KEYDOWN and self.event.key == K_p): if self.config.CELLS_MOVING is True: self.config.CELLS_MOVING = False for bact in self.bacteria: bact.original_speed = bact.speed bact.speed = 0 self.screentext.shown = True else: self.config.CELLS_MOVING = True self.screentext.shown = False def key_quit(self): """ Controls exiting the game using keyboard. """ if (self.event.type == self.pygame_state.QUIT or self.event.key == K_ESCAPE): self.pygame_state.quit() sys.exit()
drama = "Titanic" documentary = "March of the Penguins" comedy = "Step Brothers" dramedy = "Crazy, Stupid, Love" user_drama = input("Do you like dramas? (answer y/n) ") user_doc = input("Do you like documentaries? (answer y/n) ") user_comedy = input("Do you like comedies? (answer y/n) ") if user_drama == "y" and user_doc == "y" and user_comedy == "y": print("You might enjoy {}, {}, or {}".format(drama, documentary, comedy)) elif user_doc == "n" and user_drama == "y" and user_comedy == "y": print("You might enjoy {}".format(dramedy)) elif user_doc == "y" and user_drama != "y" and user_comedy != "y": print("You might enjoy {}".format(documentary)) elif user_comedy == "y" and user_doc != "y" and user_drama != "y": print("You might enjoy {}".format(comedy)) elif user_drama == "y" and user_doc != "y" and user_comedy != "y": print("You might enjoy {}".format(drama)) else: print("You might want to try a good book instead!")
#BEGINNING OF CALCULATOR # 1) use if-statements to complete this calculator program with 4 operations # Example run (what it should look like): # 0 - add # 1 - subract # 2 - multiply # 3 - divide # Enter a number to choose an operation: # 1 # Enter your first input: 10 # Enter your second input: 4 # 10 - 4 = 6 # 2) add a fifth operation, power, that does a to the power of b # 3) add a sixth operation, square root, that only asks for 1 input number and outputs its sqrt # 4) seventh operation, factorial(a), one input # 5) eighth operation, fibonacci(a), one input # 6) talk to instructors when finished print(" 0 - add") print(" 1 - subract") print(" 2 - multiply") print(" 3 - divide") print(" 4 - power") print(" 5 - square root") print(" 6 - factorial()") print(" 7 - fibonacci()") print("Enter a number to choose an operation: \n") op = input() if op=='0' or op=='1' or op=='2' or op=='3' or op=='4': a = int(input("Enter your first input: ")) b = int(input("Enter your second input: ")) if op=='0': print("a + b =",a+b) elif op=='1': print("a - b =",a-b) elif op=='2': print("a * b =",a*b) elif op=='3': print("a / b =",a/b) else : print("a ^ b =",a**b) else : a = int(input("Enter your input: ")) if op=='5': print("a^1/2 =",a**(1/2)) elif op=='6': num=1 ans=1 while num<=a: ans*=num num+=1 print("factorial(",a,")=",ans) else : f=[1]*50 num=2 while num<=a: f[num]=f[num-2]+f[num-1] num+=1 print("fibonacci(",a,")=",f[a-1]) #END OF CALCULATOR
def min_max_number(A): #A is a list sorted_list= sorted(A) minimum = sorted_list[0] maximum = sorted_list[-1] if minimum==maximum: return len(A) else: return [minimum,maximum]
import sys def findGcd(x,y): gcd=1; factors=[]; for i in range(1,x+1): if x%i==0: factors.append(i); for f in factors: if (y%f==0) and (f>gcd): gcd=f; return gcd; def main(argv): gcd=findGcd(int(argv[1]),int(argv[2])); print gcd; if __name__ == '__main__': main(sys.argv);
def main(): text=raw_input("Enter text :"); text=text.lower(); position=int(raw_input('Shift By / Enter 0 to exit:')) while position!=0: shiftedText=''; if position<1 : position=position+26 for char in text: if char==' ': shiftedText=shiftedText+str(char); else: ascii=ord(char); ascii=(ascii+position)%122; if ascii < 97: ascii=ascii+96; shiftedText=shiftedText+str(chr(ascii)); print shiftedText position=int(raw_input('Shift By / Enter 0 to exit:')) if __name__ == '__main__': main()
a = 98 b = 56 if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b)) else: print('not found')
# DESAFIO 039 # identificar tempo de alistamento militar # ENTRADA: ano de nascimento # SAÍDA: status / anos que faltam / anos que passaram from datetime import date anoN = int(input('Informe o ano de seu nascimento: ')) idade = date.today().year - anoN if idade < 18: print('Você ainda não pode se alistar! Faltam {} anos.'.format(18-idade)) elif idade == 18: print('Ano de alistamento para você. Boa Sorte!') elif idade > 18: print('Voce não pode mais se alistar! Passaram-se {} anos.'.format(idade-18))
# DESAFIO 050 # soma de 6 numeros pares s = 0 for i in range(0, 6): num = int(input('Informe um valor: ')) if num % 2 == 0: s += num print('Soma dos numeros inteiros: {}'.format(s))
""" DESAFIO 069 ANALISE DE DADOS """ cont = 's' p18 = h = m20 = 0 while True: idade = int(input('Informe sua idade: ')) sexo = str(input('e informe o sexo [F / M]')).strip()[0].lower() if idade > 18: p18 += 1 if sexo in 'm': h += 1 if sexo in 'f' and idade < 20: m20 += 1 cont = str(input('Deseja continuar [s/n]: ')).strip()[0].lower() if cont not in 's': break print('Tem {} pessoas maiores de 18 anos\n' 'Tem {} homens\n' 'Tem {} mulheres com menos de 20 anos'.format(p18, h, m20))
# 递归 # 学习目标 ''' 哪些问题适合用递归解决 怎么用递归方式写程序 *****递归的三大法则 for 循环是一种迭代 递归也是一种迭代 一、什么是递归 递归是一种解决问题的方法,它把一个问题分解为越来越小的子问题,直到问题的规模小到可以被很简直接解决 通常为了达到分解问题的效果,递归过程中要引入一个***代用自身的函数*** [1,2]和[3,3] [6,4] 计算一个列表的和 [1,2,3,4,5,6,7] 迭代求和 ''' # def list_sun(my_list): # the_sum = 0 # for num in my_list: # the_sum = the_sum + num # return the_sum # print(list_sun([1,2,3,4,5,6,7])) ''' 不能使用循环 ,计算和------》递归 (((1+2)+3)+4) 列表中的第一个元素和剩余所有的元素列表的和之和 listSum(num_list) =first(num_list)+listSum(rest[numlist]) 转换成python num_list[0]+num_list[1:] ''' # 自身调用自身的函数叫做 --递归函数 # def list_sum(num_list): # #函数结束运行的必要条件,否则就是一个死循环 # if len(num_list)==1: # return num_list[0] # else: # print(num_list[0]+list_sum(num_list[1:])) # return num_list[0]+list_sum(num_list[1:]) # print(list_sum([1,2,3,4,5,6,7])) ''' 二递归的三大定律 1.递归算法必须有个基本结束条件(长度为1的列表) 2.递归算法必须改变自己的状态并向基本结束条件演进 3.递归算法必须递归地调用自身(核心) 三练习 1.用list_sum计算数列[2,4,6,8,10] 要进行多少次递归调用? 2+sum(4,6,8,10) 4+sum(6,8,10) 6+sum(8,10) 8+sum(10) 2.计算某个数的阶乘的递归算法(最合适的基本结束条件) 0 的阶乘等于1 5! = 5*4*3*2*1 ''' # def fact(n): # if n==1 or n==0: # return 1 # else: # return n*fact(n-1) # print(fact(0)) ''' 四、递归的方式解决的--LeetCode 第405题 给定一个整数,编写一个算法将这个数装换成十六进制数。 对于负整数。我们通常使用补码运算方法 给定一个整数,转换成任意进制表示的字符串格式 769 转换成 字符串 769 str = '0123456789' 769/10 = 76 余 9 76/10 = 7 余 6 7/10 = 0 余 7 str[9]+str[6]+str[7] ''' # 2,8,10,16 # def to_str(num,base): # convert_str='0123456789' # if num<base: # return convert_str[num] # else: # print(convert_str[num % base]) # return to_str(num//base,base) + convert_str[num % base] # print(to_str(769,10)) # print(to_str(769,2)) # print(to_str(769,8)) # print(to_str(769,16)) ''' 301 3*16^2 + 0 + 1*16^0 1401 1*8^3 + 4*8^2 + 0 + 1*8^0 967 => 769 栈 后进先出 ------------ 底 967 顶 769 ------------ 可以用栈的方式实现递归 ''' # 引入栈 from pythonds.basic.stack import Stack # 实例化一个栈 s = Stack() def to_str(num,base): convert_str = "0123456789ABCDEF" while num > 0: if num < base: s.push(convert_str[num]) else: s.push(convert_str[num%base]) num = num//base result = "" while not s.isEmpty(): result = result + s.pop() return result print(to_str(769,10))
d = int(input('Por Quantos dias o senhor pretende alugar o carro ? ')) k = float(input('Quantos km você pretende percorrer ao todo ?')) t = (k * 0.15) + (60 * d) print (f'Nesse caso, alugando o carro durante {d} dias e percorrendo {k} KM, \no senhor pagará R${t} ao todo')
""" tests Player Class """ from Player.Player import Player from io import StringIO from unittest import mock def test_create_Player_1(): Player('1', 'Player1') def test_create_Player_2(): Player('2', 'Player2') def test_get_Player_1_name(): player1 = Player('1', 'Player1') name = player1.name assert(name == 'Player1') def test_get_Player_1_character(): player1 = Player('1', 'Player1') character = player1.character assert(character == '1') def test_get_Player_2_name(): player2 = Player('2', 'Player2') name = player2.name assert(name == 'Player2') def test_get_Player_2_character(): player2 = Player('2', 'Player2') character = player2.character assert(character == '2') def test_add_win(): player = Player('1', 'Player') player.add_win() player.add_win() player.add_win() wins = player.record[player.WINS] assert(wins == 3) def test_add_lose(): player = Player('1', 'Player') player.add_lose() player.add_lose() losses = player.record[player.LOSSES] assert(losses == 2) def test_add_draw(): player = Player('1', 'Player') player.add_draw() draws = player.record[player.DRAWS] assert(draws == 1) class Test_Print(): @mock.patch('sys.stdout', new_callable=StringIO) def test_print_record(self, mock_stdout): player = Player('1', 'Player') player.add_win() player.add_win() player.add_lose() player.print_record() console = "Player Record: Wins: 2 | Losses: 1 | draws: 0\n" assert (mock_stdout.getvalue() == console)
import math r = input("radius?") area= math.pi*int(r)*int(r) print ("Area:", area)
flock_sheep = [5, 7, 300, 90, 24, 50, 75] print ("Hello, my name is Nam, and here are my ship sizes ", flock_sheep) biggest = max(flock_sheep) print ("Now my biggest sheep has size ", biggest, "let's sheer it") sheep_no = flock_sheep.index(biggest) flock_sheep[sheep_no] = 8 print ("After sheering, here is my flock ", flock_sheep) growth = 50 for i in range(len(flock_sheep)): flock_sheep[i] += growth print ("One month has passed, now here is my flock ", flock_sheep)
import math n = int(input("input a number ")) if n == 0: print ("Factorial is: 1") else: print ("Factorial is: ", math.factorial(n))
#1 price_list = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock_list = {"banana": 6, "apple": 0, "orange": 32, "pear": 15 } item_list = list(price_list) details = {} for fruit in item_list: price = price_list[fruit] stock = stock_list[fruit] details[fruit] = {'price: ': price, 'stock: ': stock} for x in details: print(x) for y in details[x]: print (y, ':', details[x][y])
#Integer addition, subtraction, multiplication and division num1 = int(input("please enter a number:")) num2 = int(input("please anter a number:")) res1 = num1 + num2 res2 = num1 - num2 res3 = num1 * num2 res4 = float(num1) / float(num2) print("%d + %d = %d" %(num1,num2,res1)) print("%d - %d = %d" %(num1,num2,res2)) print("%d * %d = %d" %(num1,num2,res3)) print("%d / %d = %f" %(num1,num2,res4))
import operator import sys ''' This assignment contains only one problem, and requires you to write a standalone Python program that can be directly executed, not just a function. Here are some basic facts about tennis scoring: A tennis match is made up of sets. A set is made up of games. To win a set, a player has to win 6 games with a difference of 2 games. At 6-6, there is often a special tie-breaker. In some cases, players go on playing till one of them wins the set with a difference of two games. Tennis matches can be either 3 sets or 5 sets. The player who wins a majority of sets wins the match (i.e., 2 out 3 sets or 3 out of 5 sets) The score of a match lists out the games in each set, with the overall winner's score reported first for each set. Thus, if the score is 6-3, 5-7, 7-6 it means that the first player won the first set by 6 games to 3, lost the second one 5 games to 7 and won the third one 7 games to 6 (and hence won the overall match as well by 2 sets to 1). You will read input from the keyboard (standard input) containing the results of several tennis matches. Each match's score is recorded on a separate line with the following format: Winner:Loser:Set-1-score,...,Set-k-score, where 2 <= k <= 5 For example, an input line of the form Williams:Muguruza:3-6,6-3,6-3 indicates that Williams beat Muguruza 3-6, 6-3, 6-3 in a best of 3 set match. The input is terminated by a blank line. You have to write a Python program that reads information about all the matches and compile the following statistics for each player: Number of best-of-5 set matches won Number of best-of-3 set matches won Number of sets won Number of games won Number of sets lost Number of games lost You should print out to the screen (standard output) a summary in decreasing order of ranking, where the ranking is according to the criteria 1-6 in that order (compare item 1, if equal compare item 2, if equal compare item 3 etc, noting that for items 5 and 6 the comparison is reversed). For instance, given the following data Djokovic:Murray:2-6,6-7,7-6,6-3,6-1 Murray:Djokovic:6-3,4-6,6-4,6-3 Djokovic:Murray:6-0,7-6,6-7,6-3 Murray:Djokovic:6-4,6-4 Djokovic:Murray:2-6,6-2,6-0 Murray:Djokovic:6-3,4-6,6-3,6-4 Djokovic:Murray:7-6,4-6,7-6,2-6,6-2 Murray:Djokovic:7-5,7-5 Williams:Muguruza:3-6,6-3,6-3 your program should print out the following Djokovic 3 1 13 142 16 143 Murray 2 2 16 143 13 142 Williams 0 1 2 15 1 12 Muguruza 0 0 1 12 2 15 You can assume that there are no spaces around the punctuation marks ":", "-" and ",". Each player's name will be spelled consistently and no two players have the same name. ''' ''' 1. Number of best-of-5 set matches won 2. Number of best-of-3 set matches won 3. Number of sets won 4. Number of games won 5. Number of sets lost 6. Number of games lost Djokovic:Murray:2-6,6-7,7-6,6-3,6-1 ''' def compute(a,names,winner,looser): winnersets =0 for i in range(len(a)): #print (i,end = '') if i% 4 == 0: names[winner][3] += int(a[i]) #fix the 4th and 6th requirement names[looser][5] += int(a[i]) if a[i] < a[i+2]: #fix 5th and 3rd requirement names[winner][4] += 1 names[looser][2] += 1 else : winnersets += 1 #calculate wheather best of 5 or 3 names[looser][4] += 1 #fix 5th and 3rd requirement names[winner][2] += 1 elif a[i].isdigit(): names[looser][3] += int(a[i]) #fix the 4th and 6th requirement names[winner][5] += int(a[i]) if winnersets == 3: #increment best of 5 field if true : 1st requirement names[winner][0] +=1 elif winnersets == 2: #increment best of 3 field if true : 2nd requirement names[winner][1] +=1 def process(): names = {} #this will store players and respective 1 2 3 4 5 6 requirements while 1: a = input() if a.strip() == "": #termination condition break count = 0 name ='' for i in range(len(a)): if (a[i] != ':') and (count < 2) : #get the player names name += a[i] if a[i] == ':' and count<2 : count += 1 if name not in list(names.keys()): names[name] = [0,0,0,0,0,0] if count == 1: winner = name #identify winner from count ==1 else: looser = name #identify looser from count ==2 name='' if count == 2: compute(a[i+1 :],names,winner,looser) #compute the requirements of the players break names1 = sorted(names.items(), key=operator.itemgetter(1),reverse =True) #sort for e in names1: print(e[0],e[1][0],e[1][1],e[1][2],e[1][3],e[1][4],e[1][5]) #display process()
#Author: Listen #!/usr/bin/env python3 #-*- coding:utf-8 -*- import matplotlib.pyplot as plt import numpy as np import random def scatter1(): x= np.array([x for x in range(1,21)]) y= x**2 colors=['green','yellow','blue','red','orange','purple','cyan'] random_colors=random.sample(colors,7) fig=plt.figure() plt.scatter(x, y, s=100, c=random_colors, alpha=0.8) plt.savefig('../savefig/color_scatter1.png') plt.show() scatter1() def scatter3(): N = 80 colors = ['green', 'yellow', 'blue', 'red', 'orange', 'purple', 'cyan'] random_colors = random.sample(colors, 7) x = np.random.rand(N) y = np.random.rand(N) area = np.pi * (15* np.random.rand(N))**2 plt.scatter(x, y, s=area, c=random_colors, alpha=0.8) plt.savefig('../savefig/color_scatter3.png') plt.show() scatter3()
# -*- coding: utf-8 -*- """ Created on Sat Jan 09 13:36:18 2016 @author: Zhongxiang Dai """ import numpy as np import matplotlib.pyplot as plt import copy import networkx as nx import random import math # MCMC (Simulated Annealing) solution for Traveling Salesman problem # start from city 1 to city N #N = 50 # the number of cities # simulate a distance matrix # distance = np.random.rand(N, N) # distance = (distance + distance.T) / 2.0 # ind_diag = range(N) # distance[ind_diag, ind_diag] = 0 #print(distance) '''CHANGE THESE BOIZ RIGHT HERE''' ITER0 = 30 ITER1 = 4000 ITER2 = 2000 '''Keep ITER0 relatively low, and ITER1 about two times as much as ITER2 For reference, 500 : 100000 : 50000 took about 1.5 mintues for a random input of size 200 while 50 : 10000 : 5000 took about 12 seconds for a random input of size 200 I'm guessing that 30 : 10000 : 5000 is optimal for decent time, but feel free to reduce them or increase the last two values if you want for time ''' ''' MAKE SURE THAT the input is a fully connected graph that has weighted edges returns list of edges that solver will travel to starting and ending with location 0 (which should be soda hall) (we can also return the distance if necessary) ''' # Calculate total distance for a given sequence def mcmc_solver(G, start): distance = nx.to_numpy_matrix(G) node_names = list(G.nodes) start_index = 0 for i in range(len(node_names)): if node_names[i] == start: start_index = i break soda = list(G.nodes)[start_index] print(start_index, soda) def swap_weights(a,b): nl = list(G.nodes) nl.remove(a) nl.remove(b) for v in nl: repl_weight = G.edges[a, v]['weight'] G.edges[a, v]['weight'] = G.edges[b, v]['weight'] G.edges[b, v]['weight'] = repl_weight #print(distance) if len(G.nodes()) == 1: return node_names[start_index] if len(G.nodes()) == 2: return [node_names[start_index], node_names[1 - start_index], node_names[start_index]] def cal_dist(distance, L): d = 0 for i in range(len(L)): d = d + distance[L[i % N], L[(i + 1) % N]] return d T = float(pow(2, -8)) # free parameters, inversely related to the probability of rejection if the direction is wrong N = len(G.nodes()) swap_weights(0, start_index) L = np.append(np.arange(N), [0]) # initial route sequence print(L) print (cal_dist(distance, L)) # initial distance dist_all = [] for i in range(ITER0): c = np.random.choice(math.ceil((N - 1)/2), size = 1, replace=False) a = np.random.randint(1, N - 1, size = c) b = np.random.randint(1, N - 1, size = c) d_t = cal_dist(distance, L) dist_all.append(d_t) L_tmp = copy.copy(L) for k in range(c[0]): L_tmp[[a[k], b[k]]] = L_tmp[[b[k], a[k]]] delta_d = cal_dist(distance, L_tmp) - d_t p = min(1, np.exp(-1 * delta_d / T)) u = np.random.rand() if u < p: L = L_tmp for i in range(ITER1): a = np.random.randint(1, N - 1) b = np.random.randint(1, N - 1) if a == b: b = (a + 1)%N d_t = cal_dist(distance, L) dist_all.append(d_t) L_tmp = copy.copy(L) L_tmp[[a, b]] = L_tmp[[b, a]] delta_d = cal_dist(distance, L_tmp) - d_t p = min(1, np.exp(-1 * delta_d / T)) u = np.random.rand() if u < p: L = L_tmp for j in range(ITER2): a = np.random.randint(1, N - 1) b = (a + 1)%N d_t = cal_dist(distance, L) dist_all.append(d_t) L_tmp = copy.copy(L) L_tmp[[a, b]] = L_tmp[[b, a]] delta_d = cal_dist(distance, L_tmp) - d_t p = min(1, np.exp(-1 * delta_d / T)) u = np.random.rand() if u < p: L = L_tmp #swap_weights(0, start_index) soda_index = list(L).index(soda) L[0] = soda L[len(L) - 1] = soda L[soda_index] = 0 print(list(L)) print (cal_dist(distance, L)) # final distance plt.plot(dist_all) plt.show() return([node_names[i] for i in L]) # def christo_solver(G): # distance_matrix = list(nx.to_numpy_matrix(G)) # TSP = christofides.compute(distance_matrix) '''Uncomment this for testing purposes''' # N = 25 # G = nx.complete_graph(N) # for (u, v) in G.edges(): # G.edges[u, v]['weight'] = random.randint(0, 10) # mcmc_solver(G, N%9) # print(christo_solver(G))
class Dog: nationality="Kenyan" def __init__ (self, color,breed,height): self.color= color self.breed= breed self.height= height def pet(self): return f'The dog is a {self.color}, {self.breed} which is {self.height} tall'
class Zoo : def __init__(self, liste): self._liste=liste def __str__(self): return ''.join([l._animal_type+" " for l in self._liste]) def add_animal(self, a): return self._liste.append(a) def dosomething(self): for l in self._liste: print(l.dosomething(), end=",") def __add__(self, other): if isinstance(other, Zoo): return Zoo(self._liste+other._liste) else: return None
# -*- coding: utf-8 -*- """ Created on Tue Aug 18 17:09:46 2020 @author: Ana """ #Napišite program u kojem se učitava prirodan broj, ko #ji se zatim ispisuje u inverznom (obrnutom) poretku znamenaka. #Ne pretvarati početni broj u string. #Koristite funkciju „Obrni” koja prima jedan broj i #vraća broj u inverznom poretku. def Obrni(broj): reverse = 0 while broj > 0: znamenka = broj % 10 reverse = reverse * 10 + znamenka broj = broj // 10 print(reverse) broj = int(input("Unesite broj: ")) Obrni(broj)
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 10:51:09 2020 @author: Ana """ #Napišite program koji učitava riječ i #ispisuje novu riječ dobivenu tako da se iz unesene r #iječi izbriše svaki treći znak. string = "majmun" #treba izbacit svako treci znak majmun # 123456 triba izbacit j i n for i in range(1,len(string),3): print(string[i]) print(string)
# -*- coding: utf-8 -*- """ Created on Sat Aug 15 16:57:38 2020 @author: Ana """ # Učitati niz X od n članova ispisati one #članove niza X koji su veći od prvog (zadnjeg) člana niza. niz = [] n = int(input("Unesite koliki zelite da vam bude niz")) for j in range(0,n): broj = input("Unesite brojeve: ") niz.append(broj) pocetni_broj = niz[0] print(niz) for i in range(0,len(niz)): if(pocetni_broj < niz[i]): print(niz[i]) for i in range(0,n): if(niz[i-1] < niz[i]): print(niz[i])
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 00:09:58 2020 @author: Ana """ #Napišite program koji učitava riječ i ispisuje broj samoglasnika string = input("Unesite rijec:") suma = 0 samoglasnici = "aeiou" for j in range(len(string)): if (string[j] =="a" or string[j]=="e" or string[j]=="i" or string[j]=="o" or string[j] =="u"): suma +=1 print(suma)
# -*- coding: utf-8 -*- """ Created on Sat Aug 15 16:11:12 2020 @author: Ana """ #Učitati članove niza. Ispisati: članove niza # koji su veći od slijedećeg člana. niz = [] N = int(input("Unesite broj")) for j in range(0, N): broj = int(input("Unesite broj ")) niz.append(broj) for i in range(0,N -1): if(niz[i] > niz[i+1]): print(niz[i])
# -*- coding: utf-8 -*- """ Created on Tue Aug 18 13:04:43 2020 @author: Ana """ #Napišite program u kojem korisnik unosi broj, #a program ispisuje je li suma znamenki paran ili neparan broj. ##Koristiti funkciju „SumaZnamenki” koja prima # broj i vraća njegovu sumu znamenki. def SumaZnamenki(broj): suma = 0 while broj > 0: suma += broj % 10 broj =broj // 10 print(suma) if (suma % 2 ==0): print("paran") else: print("Neparan") broj = int(input("Unesite broj po zelji: ")) SumaZnamenki(broj)