text
stringlengths
37
1.41M
import numpy as np def to_pixel_no(coordinate): row = coordinate[1] column = coordinate[0] if row % 2 == 0: return 20 * row + column else: return 20 * row + 19 - column def pixel_to_matrix_cord(pixel_no): row = int(pixel_no / 20) column = pixel_no % 20 if row % 2 == 1: column = 19 - column return (column, row) # x, y def to_zigzag_layout(color_array): """ counters the effect of the zigzag layout that every even row has its pixels in reversed order if the pixels are set in ascending order """ c_zigzag = color_array.copy() c_zigzag[1::2] = c_zigzag[1::2, ::-1] return c_zigzag def rotate(cords, center, rotrad=0): x = cords[0] y = cords[1] cx = center[0] cy = center[1] x = int(np.round(np.cos(rotrad)*(x-cx) + np.sin(rotrad)*(y-cy))) + cx y = int(np.round(-np.sin(rotrad)*(x-cx) + np.cos(rotrad)*(y-cy))) + cy return x, y
from random import random from random import choice from collections import deque from sys import argv import re # Global Vars row = 0 col = 0 num_blocking_squares = 0 word_dictionary = "" # Unless otherwise noted, board is a string for inputs # Generates empty crossword board (string with boundaries represented as ?) def generate_board(): global row global col board = "" for c in range(col+2): board += "?" for r in range(row): board += "?" for c in range(col): board += "-" board += "?" for c in range(col+2): board += "?" # Takes boundaries into account (effective board size) row += 2 col += 2 return board # Prints board as grid (space between each spot in grid) def display(board): print_string = "" col_count = 0 for char in board: if char == "?": continue print_string += char+" " col_count += 1 if col_count == col-2: print_string += "\n" col_count = 0 print(print_string) # Given location of a blocking square, propagate blocking squares that MUST be there # Board is a list def propagate_blocking_squares(board, square_index): num_added = 0 loc_added = set() loc_added.add(square_index) while len(loc_added) != 0: # 180 degree rotation index = loc_added.pop() reflect_index = len(board)-index-1 if board[reflect_index] != "#": num_added += 1 board[reflect_index] = "#" loc_added.add(reflect_index) # Must be > 3 spaces away from edge/on edge # If distance is less, then blocked squares must be used # Top Edge if index < col*4: new_index = index-col while board[new_index] != "?": if board[new_index] != "#": board[new_index] = "#" num_added += 1 loc_added.add(new_index) new_index = new_index-col # Bottom Edge if index > len(board)-col*4: new_index = index+col while board[new_index] != "?": if board[new_index] != "#": board[new_index] = "#" num_added += 1 loc_added.add(new_index) new_index = new_index+col # Left Edge if index-(index//col*col) < 4: new_index = index-1 while board[new_index] != "?": if board[new_index] != "#": board[new_index] = "#" num_added += 1 loc_added.add(new_index) new_index = new_index-1 # Right Edge if ((index//col+1)*col) - index < 4: new_index = index+1 while board[new_index] != "?": if board[new_index] != "#": board[new_index] = "#" num_added += 1 loc_added.add(new_index) new_index = new_index+1 # Must be three spaces away from other blocked squares # Means cannot allow for only one or two spaces between blocked squares for step in range(2, 4): # Up up_check_row = index - col*step if up_check_row >= 0 and board[up_check_row] == "#": for fill in range(up_check_row, index, col): if board[fill] != "#": board[fill] = "#" loc_added.add(fill) num_added += 1 # Down down_check_row = index + col*step if down_check_row < len(board) and board[down_check_row] == "#": for fill in range(index, down_check_row, col): if board[fill] != "#": board[fill] = "#" loc_added.add(fill) num_added += 1 # Left left_check_col = index - step if left_check_col >= 0 and board[left_check_col] == "#": for fill in range(left_check_col, index): if board[fill] != "#" and board[fill] != "?": board[fill] = "#" loc_added.add(fill) num_added += 1 # Right right_check_col = index + step if right_check_col < col and board[right_check_col] == "#": for fill in range(index, right_check_col): if board[fill] != "#" and board[fill] != "?": board[fill] = "#" loc_added.add(fill) num_added += 1 return board, num_added # Add initial blocking squares (from input conditions) def initial_blocking_squares(word_list, board): board = list(board) # Number of blocking squares specified by input count = 0 # Locations of blocking squares specified by input blocking_square_locations = [] for word_info in word_list: word_info = word_info.lower() # Find start row and col start_row = int(word_info[1:word_info.find("x")]) start_col = int( ''.join([word_info[i] for i in range(word_info.find("x")+1, len(word_info)) if word_info[i].isdigit()])) # Finds input word (including #) word = "".join([word_info[i] for i in range(word_info.find("x") + 1, len(word_info)) if word_info[i].isalpha() or word_info[i] == "#"]) # Horizontal index = 0 if word_info[0] == "h": for c in range(start_col, start_col+len(word)): loc = (start_row+1)*col+1+c if word[index] == "#": blocking_square_locations.append(loc) count += 1 board[loc] = word[index].upper() index += 1 # Vertical elif word_info[0] == "v": for r in range(start_row, start_row+len(word)): loc = (r+1)*col+start_col+1 if word[index] == "#": blocking_square_locations.append(loc) count += 1 board[loc] = word[index].upper() index += 1 # Propagates input blocking squares for loc in blocking_square_locations: board, add = propagate_blocking_squares(board, loc) count += add return ''.join(board), count # Generates a list of blank spaces from input board that could be blocking squares (taking into account initial states) def viable_blanks(board): blanks = list() for index in range(len(board)): # Can't pick center if num_blocking_squares % 2 == 0 and index == len(board)//2: continue # If blank if board[index] == "-": # If a letter is not < 3 spaces away if helper(board, index-1, index-4, -1) and helper(board, index+1, index+4, 1) and \ helper(board, index-col, index-4*col, -col) and helper(board, index+col, index+4*col, col): # Reflects and does the same check reflect_index = len(board)-1-index if board[reflect_index] == '-': board[index] = "#" if helper(board, reflect_index-1, reflect_index-4, -1) and helper(board, reflect_index+1, reflect_index+4, 1) and \ helper(board, reflect_index-col, reflect_index-4*col, -col) and helper(board, reflect_index+col, reflect_index+4*col, col): # heappush(blanks, (abs(len(board)//2-index), index)) blanks.append(index) board[index] = "-" return blanks # Viable_blanks helper; returns true if start is a valid spot for a blocking square def helper(board, start, stop, step): letters_between = False is_boundary = False for check_index in range(start, stop, step): # Checks to see if spot is too close to a letter near a blocking square (leading to a word <3 char) if board[check_index].isalpha(): letters_between = True if board[check_index] == "?" or board[check_index] == "#": is_boundary = True break if is_boundary and letters_between: return False return True # Adds all blocking squares through guess and check (randomly select a square, and if it doesn't work abort) # Initial count is from input conditions # Recursive (some arrangements make it impossible to place more squares, need to backtrack) def add_blocking_squares(board, count): board = list(board) if count == num_blocking_squares: return "".join(board) if num_blocking_squares % 2 == 1 and board[len(board)//2] != "#": board[len(board)//2] = "#" count += 1 blanks = viable_blanks(board) result = None while result is None: new_count = count # Bad end cases: no viable places for more blocking squares, or too many blocking squares if len(blanks) == 0 or new_count > num_blocking_squares: return None spot = choice(blanks) new_board = board.copy() new_board[spot] = "#" new_board, add = propagate_blocking_squares(new_board, spot) # Special case in which an odd board has its center filled by propagating w/ even # blocking squares if new_board[len(board)//2] == "#" and num_blocking_squares % 2 == 0 and len(board) % 2 == 1: blanks.remove(spot) blanks.remove(len(board)-spot-1) continue new_count += add+1 result = add_blocking_squares(new_board, new_count) if result is None: blanks.remove(spot) blanks.remove(len(board)-spot-1) if result is not None: return result # Checks to make sure the board isn't split into two def check(board): if "-" not in set(board): return True rand_index = int(random()*len(board)) while board[rand_index] != "-": rand_index = int(random()*len(board)) board = list(board) board[rand_index] = "#" fringe = deque() fringe.append(rand_index) while len(fringe) != 0: index = fringe.popleft() if "-" not in set(board): return True # Get Children # Right if board[index+1] != "#" and board[index+1] != "?": fringe.append(index+1) board[index+1] = "#" # Left if board[index-1] != "#" and board[index-1] != "?": fringe.append(index-1) board[index-1] = "#" # Up if board[index-col] != "#" and board[index-col] != "?": fringe.append(index-col) board[index-col] = "#" # Down if board[index+col] != "#" and board[index+col] != "?": fringe.append(index+col) board[index+col] = "#" return False # Initial Setup (takes command line arguments and sets global variables) # Returns initial board, which contains all input words, blocking squares, and propagated squares # Count is the number of initial blocking squares def initial_setup(): global row global col global num_blocking_squares global word_dictionary row = int(argv[1][:argv[1].find("x")]) col = int(argv[1][argv[1].find("x") + 1:]) num_blocking_squares = int(argv[2]) word_dictionary = argv[3] board, count = initial_blocking_squares(argv[4:], generate_board()) return board, count # Gets all blank spots (used for build crossword) def all_blanks(board): blanks = list() for index in range(len(board)): if board[index] == "-": blanks.append(index) return blanks # Builds the crossword given the input dictionary (horizontal only) def horizontal_build_crossword(board): board = list(board) # Puts all words into a list words = list() for item in open(word_dictionary): words.append(item.rstrip()) blanks = all_blanks(board) while len(blanks) != 0: search = r"" spot = choice(blanks) # Finds starting spot while board[spot] != "#" and board[spot] != "?": spot -= 1 spot += 1 starting_spot = spot # Creates regex string while board[spot] != "#" and board[spot] != "?": if board[spot] == "-": search += r"\w" blanks.remove(spot) else: search += board[spot] spot += 1 word = "" # Searches for an appropriate word while len(word) == 0: for result in re.finditer(r"^"+search+"$", choice(words), re.I): if result.group(0).isalpha(): word = result.group(0) words.remove(word) index = 0 # Puts in board while board[starting_spot] != "#" and board[starting_spot] != "?": board[starting_spot] = word[index].upper() index += 1 starting_spot += 1 display(board) # Builds the crossword given the input dictionary def build_crossword(board, words): board = list(board) # Puts all words into a list blanks = all_blanks(board) if len(blanks) == 0: return board search = r"" initial_spot = choice(blanks) spot = initial_spot while board[spot] != "#" and board[spot] != "?": spot -= 1 spot += 1 starting_spot = spot while board[spot] != "#" and board[spot] != "?": if board[spot] == "-": search += r"\w" blanks.remove(spot) else: search += board[spot] spot += 1 word = "" while len(word) == 0: for result in re.finditer(r"^"+search+"$", choice(words), re.I): if result.group(0).isalpha(): word = result.group(0) words.remove(word) index = 0 new_board = board.copy() while new_board[starting_spot] != "#" and new_board[starting_spot] != "?": new_board[starting_spot] = word[index].upper() index += 1 starting_spot += 1 result = build_crossword(new_board, words) if result is not None: return result # Main # Makes initial board with blocking squares board_main, count_main = initial_setup() end_board = add_blocking_squares(board_main, count_main) while not check(end_board): end_board = add_blocking_squares(board_main, count_main) # Generates the rest of the board # words_list = list() # for item in open(word_dictionary): # words_list.append(item.rstrip()) # end_board = build_crossword(end_board, words_list) horizontal_build_crossword(end_board) # result = None # while result is None: # new_board = deepcopy(board_main) # result = add_blocking_squares(board_main, count_main) # display(result) # Tests to see if my input reading works # board_test, count_test = initial_setup() # print(row) # print(col) # print(num_blocking_squares) # print(word_dictionary) # display(board_test) # print(count_test)
class Guess: def __init__(self, word): self.secretWord = word self.numTries = 0 self.guessedChars = [] self.currentStatus = '_'*len(self.secretWord) self.currentword = '_'*len(self.secretWord) self.indexnumL =[] def display(self): return 'Current: '+ self.currentStatus+'\n'+'Tries: '+ str(self.numTries) def guess(self, character): self.guessedChars += [character] character = character.lower() if self.secretWord == self.currentStatus: return True elif character in self.secretWord: indexnum = 0 self.indexnumL = [] while self.secretWord.find(character,indexnum)!=-1: indexnum = self.secretWord.find(character,indexnum) self.indexnumL += [indexnum] indexnum += 1 for i in self.indexnumL: if i == len(self.currentword)-1: self.currentword = self.currentword[:-1]+character else: self.currentword = self.currentword[:i]+character+self.currentword[i+1:] self.currentStatus = self.currentword return False elif self.secretWord.find(character) ==-1: self.numTries += 1 return False
#fname=input("Enater file name ") handle=open("mbox-short.txt") lst=list() count=0 for line in handle: line=line.rstrip() if not line.startswith("From "):continue print(line) lst=line.split() #print(lst[1]) count+=1 print("There were", count, "lines in the file with From as the first word")
import pandas as pd import matplotlib.pyplot as plt # 使用matplotlip呈现店铺总数排名前十的国家 file_path = "./starbucks_store_worldwide.csv" df = pd.read_csv(file_path) print(df.info()) country_data = df.groupby(by="Country") print(country_data) country_brand_count = country_data["Store Number"].count().sort_values(ascending=False)[:10] print(country_brand_count) _x = country_brand_count.index _y = country_brand_count.values plt.figure(figsize=(20, 8), dpi=80) plt.xticks(range(len(_x)), _x) plt.bar(range(len(_x)), _y) plt.show()
import pandas as pd df = pd.read_csv("./dogNames2.csv") # print(df.head()) # print(df.info()) # dataframe中排序的fangfa,默认升序,可以用ascending来使其逆序 # 按照某一列进行排序 # df = df.sort_values(by="Count_AnimalName") df = df.sort_values(by="Count_AnimalName", ascending=False) # print(df) # pandas取行或者列的注意事项 # - 方括号中写数组,表示取行,对行进行操作 # - 方括号中写字符串,表示取列索引,对列进行操作 print(df[:20]) # 取前20行内容 print(df["Row_Labels"]) # 取Row_Labels这一列的数据 print(df[:100]["Row_Labels"]) # 取前一百数据中的Row_Labels这列对应数据 print(" " * 50) # pandas的布尔索引,&且 |或 # print(df[df["Count_AnimalName"] > 800]) # print(df[(df["Count_AnimalName"] > 800) & (df["Count_AnimalName"] < 1000)]) print(df[(df["Row_Labels"].str.len() > 4) & (df["Count_AnimalName"] > 700)])
import math def optional_params(x, y=0): return x + y def optional_params_pitfalls(x, y=[]): y.append(x) return y def optional_params_pitfalls_alternate(x, y=None): if y is None: y = [] y.append(x) return y def using_args(*numbers_to_sum): return sum(numbers_to_sum) def using_kwargs(**keywords): if "hello" in keywords: print("hello {}".format(keywords["hello"])) if "goodbye" in keywords: print("goodbye {}".format(keywords["goodbye"])) for key in keywords.keys(): print("the keyword {} was found in **keywords!".format(key)) def get_primes(number): while True: if _is_prime(number): yield number number += 1 def _is_prime(number): if number > 1: if number == 2: return True if number % 2 == 0: return False for current in range(3, int(math.sqrt(number) + 1), 2): if number % current == 0: return False return True return False
import numpy as np def addition_feature_combiner(fv_word1, fv_word2): """ Returns the element-wise addition of the feature vectors for each word. :param fv_word1: the feature vector for the first word of the co-occurrence pair :param fv_word2: the feature vector for the second word of the co-occurrence pair :return: a single feature vector representing word1 and word2 """ return np.add(fv_word1, fv_word2) def bitwise_or_feature_combiner(fv_word1, fv_word2): """ Returns the bitwise OR of the feature vectors for each word. NOTE: if this feature combiner is used, then feature vectors must be binary vectors. :param fv_word1: the feature vector for the first word of the co-occurrence pair :param fv_word2: the feature vector for the second word of the co-occurrence pair :return: a single feature vector representing word1 and word2 """ return np.bitwise_or(fv_word1, fv_word2) def where_greater_feature_combiner(fv_word1, fv_word2): """ Returns a vector containing the greatest of the two values between fv_word1 and fv_word2 at each position. :param fv_word1: the feature vector for the first word of the co-occurrence pair :param fv_word2: the feature vector for the second word of the co-occurrence pair :return: a single feature vector representing word1 and word2 """ a = np.array(fv_word1, copy=False) b = np.array(fv_word2, copy=False) return np.where(a > b, a, b)
import pandas as pd import numpy as np import multiprocessing __all__ = ['parallel_groupby'] def parallel_groupby(gb, func, ncpus=4, concat=True): """Performs a Pandas groupby operation in parallel. Results is equivalent to the following: res = [] for (name, group) in gb: res.append(func((name, group))) df = pd.concat(got) OR df = gb.apply(func) Parameters ---------- gb : pandas.core.groupby.DataFrameGroupBy Generator from calling df.groupby(columns) func : function Function that is called on each group taking one argument as input: a tuple of (name, groupDf) ncpus : int Number of CPUs to use for processing. Returns ------- df : pd.DataFrame Example ------- ep = groupby_parallel(posDf.groupby(['ptid', 'IslandID'], partial(findEpitopes, minSharedAA=5, minOverlap=7))""" with multiprocessing.Pool(ncpus) as pool: queue = multiprocessing.Manager().Queue() result = pool.starmap_async(func, [(name, group) for name, group in gb]) got = result.get() if concat: out = pd.concat(got) else: out = got return out
def main(): text = input("Text: ") letter = count_letter(text) words = count_words(text) sentence = count_sentence(text) # Coleman-Liau指数 L = int(letter) * 100 / int(words) S = int(sentence) * 100 / int(words) index = float(0.0588 * L - 0.296 * S - 15.8) # 四捨五入 if index % 1 < 0.55: grade = int(index) else: grade = int(index) + 1 if index < 1: print("Before Grade 1") elif 1 <= grade and grade < 17: print("Grade {0}" .format(grade)) else: print("Grade 16+") # 入力されたテキストの文字数を数える def count_letter(text): count = int(len(text)) # 記号は文字とみなさない count -= text.count('-') count -= text.count('\'') count -= text.count(':') count -= text.count(';') count -= text.count(',') count -= text.count('.') count -= text.count('?') count -= text.count('!') count -= text.count(' ') return count # 入力されたテキストの単語数を数える def count_words(text): count = text.count(' ') + 1 return count # 入力されたテキストの文章の数を数える def count_sentence(text): count = text.count('.') count += text.count('!') count += text.count('?') return count if __name__ == "__main__": main()
ticket = 37750; def ticket_cal(adults,children): cost = ticket*adults+(ticket/3)*children with_tax_cost = cost + (cost*0.07) final_cost = with_tax_cost - (with_tax_cost*0.1) return final_cost a = int(input("Enter the number of Adults ")) c = int(input("Enter the number of childrens")) x = ticket_cal(a,c) print("Total Ticket Cost:",x)
from matplotlib import pyplot as plt #%matplotlib inline #plotting to our canvas x = [5,8,10] y = [12,16,6] x2 = [6,9,11] y2= [6,15,7] #plt.plot(x, y) plt.plot(x,y,'g',label="girls",linewidth = 3) plt.plot(x2,y2,'r',label="boys",linewidth = 3) #plt.plot([1,2,9],[1,9,6],[1,9,6]) #showing waht we plotted plt.title("first line chart ") plt.xlabel("Student roll number ") plt.ylabel("Age of Student ") plt.legend() plt.grid(True,color="b") plt.show()
#!/usr/bin/env python3 import sys from multiprocessing import Process,Queue queue = Queue(maxsize=5) def f1(): queue.put('hello shiyanlou') def f2(): #if queue.empty() is not True: data = queue.get() print(data) #else: # print('Queue is empty!') def main(): Process(target=f1).start() Process(target=f2).start() if __name__ == '__main__': main()
def factorial(n): return 1 if(n==0 or n==1) else n*factorial(n-1) num =5 print("factorial of ",num,"is",factorial(num))
def printaph(list1): z = len(list1) maxx = 0 #ls = [] for i in range(len(list1)): if(maxx<len(list1[i])): maxx = len(list1[i]) #print(maxx) for i in range(maxx): for j in range(len(list1)): if(len(list1[j])<maxx): if(len(list1[j])+i>=maxx): print(list1[j][maxx-i-1],end="") else: print(" ",end="") elif(len(list1[j])==maxx): print(list1[j][maxx-i-1],end="") print(" ") list1 = ["VIKAS","KINGKHAN","AMAN"] printaph(list1)
def result(char): mean = int(len(char)/2) print(char[0:mean:2]) cases = int(input()) for i in range(0,cases): n=input() result(n)
from tkinter import Tk from tkinter import Label import time import sys root = Tk() root.title = ("Digital Clock") def get_time(): timeVar = time.strftime ('%H:%M:%S %p') clock.config(text=timeVar) clock.after(200, get_time) clock = Label(root, font = ("Calibri",90), background = "black", foreground = "white" ) clock.pack() get_time() root.mainloop()
""" Es la estructura más simple que proporciona Pandas, y se asemeja a una columna en una hoja de cálculo de Excel. Un objeto Series tiene dos componentes principales: un índice y un vector de datos. Ambos componentes son listas con la misma longitud. """ import pandas as pd import numpy as np indice = range(5) nombres = ['Nayro','Claudia','Kevin','Santiago','Kelly'] serie_ejemplo = pd.Series(index=indice, data=nombres) # print(serie_ejemplo) # print(serie_ejemplo[2]) # otro ejemplo numeros = np.arange(-10,10,1) # Crear un rango de -10 a 9 contando uno a uno serie_ejemplo = pd.Series(index=numeros, data=numeros**2) # x**2 devuelve el valor de cada elemento de x elevado al cuadrado # print(serie_ejemplo)
# def person(name,*data): print(name) print(data) person('Pranik',21,'Amravati',7058187989) #Code2 def person1(name,**data): print(name) for i,j in data.items(): print(i,j) person1('Pranik',21,'Amravati',7058187989)
class Board: # INIT def __init__(self, screen = None, hint = True): self.__board = self.__clean_board() # Initializing an empty board self.__player = 0 # Initializing the first player (white) self.__valid_moves = self.__get_valid_moves() # Have to know self.__screen = screen # Can play with graph and console too self.__hint = hint # Show valid moves for player self.__alphabet_coords = { "A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7 } # Alphabet coords for console # PRIVATE METHODS def __clean_board(self): new_board = [] for row_idx in range(8): new_board.append([]) for col_idx in range(8): new_board[row_idx].append(None) #Initializing the center values new_board[3][3]="w" new_board[3][4]="b" new_board[4][3]="b" new_board[4][4]="w" return new_board def __get_dcboard(self): deepc_board = [] for row_idx in range(8): line = [] for col_idx in range(8): line.append(self.__board[row_idx][col_idx]) deepc_board.append(line) return deepc_board def __load_board(self, path): new_board = self.__clean_board() with open(path) as in_file: row_idx = 0 for line in in_file: assert(row_idx < 8) for col_idx in range(8): act_field = line[col_idx] new_board[row_idx][col_idx] = \ act_field if act_field != "-" else None row_idx += 1 return new_board def __get_valid_moves(self): valid_moves = [] colour = "w" if self.__player == 0 else "b" for row_idx in range(8): for col_idx in range(8): if not self.__board[row_idx][col_idx]: neighbours = [] for ri in range(max(0,row_idx-1),min(row_idx+2,8)): for ci in range(max(0,col_idx-1),min(col_idx+2,8)): if self.__board[ri][ci]: neighbours.append((ri,ci)) for neighbour in neighbours: neigh_row = neighbour[0] neigh_col = neighbour[1] if self.__board[neigh_row][neigh_col] == colour: continue else: delta_row = neigh_row - row_idx delta_col = neigh_col - col_idx tmp_row = neigh_row tmp_col = neigh_col while 0 <= tmp_row <= 7 and 0 <= tmp_col <= 7: if self.__board[tmp_row][tmp_col] == None: break if self.__board[tmp_row][tmp_col] == colour: valid_moves.append((row_idx,col_idx)) break tmp_row += delta_row tmp_col += delta_col return valid_moves def __is_valid_move(self, move_row, move_col): return (move_row, move_col) in self.__valid_moves def __make_a_move(self, move_row, move_col): if self.__is_valid_move(move_row, move_col): colour = "w" if self.__player == 0 else "b" new_board = self.__get_dcboard() # we have to use "deep" copy new_board[move_row][move_col] = colour # move neighbours =[] for row_idx in range(max(0,move_row-1),min(move_row+2,8)): for col_idx in range(max(0,move_col-1),min(move_col+2,8)): if new_board[row_idx][col_idx] != None: neighbours.append((row_idx,col_idx)) swap_discs = [] # collect tiles for switch for neighbour in neighbours: neigh_row = neighbour[0] neigh_col = neighbour[1] if new_board[neigh_row][neigh_col] != colour: line = [] delta_row = neigh_row - move_row delta_col = neigh_col - move_col tmp_row = neigh_row tmp_col = neigh_col while 0 <= tmp_row <= 7 and 0 <= tmp_col <= 7: line.append((tmp_row,tmp_col)) if new_board[tmp_row][tmp_col] == None: break if new_board[tmp_row][tmp_col] == colour: for disc in line: swap_discs.append(disc) break tmp_row += delta_row tmp_col += delta_col for disc in swap_discs: new_board[disc[0]][disc[1]] = colour return new_board # TODO: invalid move case return None # --- --- --- --- --- --- --- --- --- --- --- --- --- # PUBLIC METHODS def show_board(self, outline=False): # It can be showed on consloe if not self.__screen: print(" ",*sorted(self.__alphabet_coords.keys())) for row_idx in range(8): print(row_idx+1,"| ", end="") for col_idx in range(8): act_field = self.__board[row_idx][col_idx] if act_field: print(act_field+" ", end="") else: ch = " " if self.__is_valid_move(row_idx,col_idx) \ and self.__hint: ch = "-" print(ch+" ", end="") print("|",row_idx+1) print(" ",*sorted(self.__alphabet_coords.keys())) else: try: # TODO: Make draw depend screen resolution # If we want an outline on the board then draw one if outline: screen.create_rectangle(50,50,450,450,outline="#111") # Drawing the intermediate lines for i in range(7): line_shift = 50+50*(i+1) # Horizontal line screen.create_line(50,line_shift,450,line_shift,fill="#111") # Vertical line screen.create_line(line_shift,50,line_shift,450,fill="#111") screen.update() except: print("Dude..WTF") def move(self): row_idx = col_idx = -1 if not self.__screen: # Console # TODO: Use regexp for input field = input("Take one valid field please: ") row_idx = int(field[1])-1 col_idx = self.__alphabet_coords[field[0]] else: # Screen # TODO: Handle click event pass assert(-1 < row_idx < 8 and -1 < col_idx < 8) self.__board = self.__make_a_move(row_idx, col_idx) self.__player = 1 - self.__player self.__valid_moves = self.__get_valid_moves() # Save actual state of board to a given PATH def save_game(self, path="out.txt"): with open(path, "w") as out_file: for x_coord in range(8): for y_coord in range(8): act_field = self.__board[x_coord][y_coord] if act_field: out_file.write(act_field) else: out_file.write("-") out_file.write("\n") # Load a game from a given path def load_game(self, path): try: self.__board = self.__load_board() except: print("WHAT now..")
import turtle def draw_squares(some_turtle): for i in range(1,5): some_turtle.circle(100) some_turtle.right(40) def draw_circles(some_turtle): for i in range(1,5): some_turtle.circle(100) some_turtle.right(40) def draw_shapes(): #BG COLOR window = turtle.Screen() window.bgcolor("white") #TURTLE COLOR brad = turtle.Turtle() brad.shape("turtle") brad.color("pink") brad.speed(6) #GO TURTLE GO for i in range(1,37): draw_squares(brad) #brad.right(10) ## angie = turtle.Turtle() ## angie.shape("arrow") ## angie.color("purple") ## angie.circle(100) ## ## arthur = turtle.Turtle() ## arthur.shape("turtle") ## arthur.color("magenta") ## ## t = 0 ## while t < 3: ## arthur.forward(100) ## arthur.left(120) ## t += 1 window.exitonclick() draw_shapes()
from random import choice #from random method import choice #choice will randomize word from list below def open_and_read_file(file_path): """Takes file path as string; returns text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ contents = open(file_path).read() return contents # open_and_read_file("green-eggs.txt") def make_chains(text_string): """Takes input text as string; returns _dictionary_ of markov chains. A chain will be a key that consists of a tuple of (word1, word2) and the value would be a list of the word(s) that follow those two words in the input text. For example: >>> make_chains("hi there mary hi there juanita") {('hi', 'there'): ['mary', 'juanita'], ('there', 'mary'): ['hi'], ('mary', 'hi': ['there']} """ chains = {} words = text_string.split() #splits the text string into individual words in list #split will return a list, always words.append(None) #append None to words list becuase it's a marker to stop. Terminate. for i in range(len(words)-2): #for index in range of the length of words -2 to allow for 3 variables #in the end bi_gram = (words[i], words[i + 1]) # makes key, which is a tuple of a word and the next consecutive word chains[bi_gram] = chains.get(bi_gram, []) # a["berry"] = a.get("berry", []) # will check for existence of bi_gram key, and if it doesn't exist, # add it as key + empty string as value chains[bi_gram].append(words[i + 2]) #will append a possible consecutive word. # chains[bi_gram] is REPRESENTING the value. So we are appending to # the value which is a LIST. Therefore you can append to it! return chains def make_text(chains): """Takes dictionary of markov chains; returns random text.""" text = "" bi_gram = choice(chains.keys()) first, second = bi_gram third = choice(chains[bi_gram]) text += first + " " + second while third: text += " " + third bi_gram = (second, third) first, second = bi_gram third = choice(chains[bi_gram]) return text input_path = "gettysburg.txt" # Open the file and turn it into one long string input_text = open_and_read_file(input_path) # Get a Markov chain chains = make_chains(input_text) # Produce random text random_text = make_text(chains) print random_text
def create_num(all_num): print("------1-----") a,b = 0,1 current_num = 0 while current_num < all_num: print("------2-----") # print(a) yield a #如果函数当中有yield语句,那么这个就不再是函数,而是一个生成器的模板 a,b = b, a+b current_num+=1 print("------3-----") #如果在调用函数的时候,发现函数中与yield,那么此时不再是调用函数,而是创建一生成器 obj = create_num(10) obj2 = create_num(2) ret = next("obj:",ret) print(ret) ret = next(obj) print("obj:",ret) # for num in obj: # print(num)
# Shi-Tomasi Algorithm to find specified amount of corners # R = min(λ1, λ2) import cv2 as cv import numpy as np if __name__ == "__main__": img = cv.imread('../../assets/test10.jpg') img = cv.resize(img, None, fx=.5, fy=.5) cv.imshow("Original Image", img) gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # detecting corners using good features corners = cv.goodFeaturesToTrack(gray_img, 100, 0.05, 25) # second param is how many corners we want corners = np.float32(corners) # for each corner coordiantes, draw a filled circles for item in corners: x, y = item.ravel() img = cv.circle(img, (x, y), 5, (255, 0, 0), -1) cv.imshow('Corners Detected Image', img) cv.waitKey(0) cv.destroyAllWindows() # doc: https://docs.opencv.org/3.4/d4/d8c/tutorial_py_shi_tomasi.html
# captcha simulation / bot recognizing simulation # asking user to select the quarter with no face in # a tiny project with use of mouse handling in opencv import cv2 as cv import numpy as np GREEN = (0, 153, 0) RED = (0, 0, 255) TARGET = None # number of the quarter with no face DETECTED = -1 # -1: not chosen, 0: wrong choice, 1: correct def draw_quarter(q, sample, img): row = q // 2 col = q % 2 x_range = slice(row * height // 2, (row + 1) * height // 2) y_range = slice(col * width // 2, (col + 1) * width // 2) quadrant = cv.imread('../../assets/test%d.jpg'%sample) quadrant = cv.resize(quadrant, (width // 2, height // 2)) img[x_range, y_range] = quadrant def draw_image(img): global TARGET TESTS_COUNT = 8 # number of sample images containing face tests = np.arange(TESTS_COUNT) + 1 # first 8 images are faces (look at assets folder) # image quarters numbers # [0 | 1] # [2 | 3] quarters = np.arange(4) # quarters numbers: [0, 1, 2, 3] # assigning 3 random "face images" to 3 random quarters for _ in range(3): sample = np.random.choice(tests) # random item from samples numbers array index = np.where(tests == sample) # index of the random value tests = np.delete(tests, index) q = np.random.choice(quarters) index = np.where(quarters == q) quarters = np.delete(quarters, index) draw_quarter(q, sample, img) # placing the main image with no face TARGET = quarters[0] # only one spot left target_pic = np.random.randint(9, 16) # images 9 to 15 are pictures without face (test9.jpg , ... , test15.jpg) draw_quarter(TARGET, target_pic, img) # passing a random picture out of 6 pictures which could be the target def detect_quadrant(event, x, y, flags, param): global DETECTED top_left = None selected_quadrant = None if event == cv.EVENT_LBUTTONDOWN: if x > width / 2: if y > height / 2: # bottom right quarter top_left = (width // 2, height // 2) selected_quadrant = 3 else: # top right quarter top_left = (width // 2, 0) selected_quadrant = 1 else: if y > height / 2: # bottom left quarter top_left = (0, height // 2) selected_quadrant = 2 else: # top left quarter top_left = (0, 0) selected_quadrant = 0 img = param["img"] if top_left: x, y = top_left if TARGET == selected_quadrant: # drawing a "✓" on target point1 = (x + 50, y + height // 4) point2 = (x + width // 4 - 50, y + height // 2 - 50) point3 = (x + width // 2 - 50, y + 50) img = cv.line(img, point1, point2, GREEN, 10) img = cv.line(img, point2, point3, GREEN, 10) DETECTED = 1 else: # drawing a "X" on selected quadrant bottom_left = x, y + height // 2 top_right = x + width // 2, y bottom_right = x + width // 2, y + height // 2 original_copy = img.copy() img = cv.line(img, top_left, bottom_right, RED, 10) img = cv.line(img, top_right, bottom_left, RED, 10) DETECTED = 0 if __name__ == "__main__": width, height = 750, 600 # img size img = np.zeros((height, width, 3), np.uint8) title = 'Which image does NOT contain any face ?' cv.namedWindow(title) cv.setMouseCallback(title, detect_quadrant, {"img": img}) draw_image(img) original_copy = img.copy() while True: key = cv.waitKey(1) if key == 27: break cv.imshow(title, img) if DETECTED == 1: cv.waitKey(1000) draw_image(img) original_copy = img.copy() DETECTED = -1 elif not DETECTED: cv.waitKey(1000) img[:] = original_copy[:] DETECTED = -1 cv.destroyAllWindows() # you can customize this project with more images
# -*- coding: utf-8 -*- # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ # 遍历:左->右->根节点 if not root: return [] path = [] path += self.binaryTreePaths(root.left) path += self.binaryTreePaths(root.right) # 叶子节点 if not root.left and not root.right: path.append(str(root.val)) # 非叶子节点 else: for i, p in enumerate(path): path[i] = '{}->{}'.format(root.val, path[i]) return path if __name__ == '__main__': s = Solution() t1 = TreeNode(1) t1.left = TreeNode(2) t1.right = TreeNode(3) t1.right.right = TreeNode(4) t1.right.right.right = TreeNode(5) r1 = s.binaryTreePaths(t1) print ''
# List teman rio sebanyak 10 chingu = ['Sonny', 'Bagus', 'Attar', 'Alvin', 'Ano', 'Ryan', 'Raka', 'Nanda', 'Wahyu', 'Tito'] # menampilakan list indeks nomor 1,3,5 print(chingu[1], chingu[3], chingu[5]) # Mengganti list 2,5,9 chingu[2] = 'Ahmed' chingu[4] = 'Rahmat' chingu[9] = 'Rizal' print(chingu) # Menambah 2 teman rio pada list chingu.extend(["Alda", "William"]) print(chingu) # Menampilkan semua teman rio dengan perulangan print("Teman rio : ada {} orang".format(len(chingu))) for teman in chingu: print(teman) # Menampilkan Panjang list print(len(chingu))
al = input("Sayı Giriniz: ") bul = len(str(al)) say = 0 for i in range(bul): say = say + int(al[i]) ** int(bul) if say == al: print("{} armstrong sayısıdır".format(al)) else: print("{} armstrong sayısı değildir.".format(al))
#!/usr/bin/env python # -*- coding: utf-8 -*- # 删除字符串中不需要的字符 s = ' hello world \n' print(s.rstrip() + '|') print(s.lstrip()) t = '-----hello=====' print(t.lstrip('-')) print(t.lstrip('-h')) print(t.strip('-=')) # with open('README.md') as f: # lines = (line.strip() for line in f) # for line in lines: # 这样会报错 ValueError: I/O operation on closed file. # print(line) with open('README.md') as f: lines = (line.strip() for line in f) # 不需要预先读取所有数据放到一个临时的列表中去 for line in lines: print(line)
#!/usr/bin/env python # -*- coding: utf-8 -*- # 过滤序列元素 from itertools import compress mylist = [1, 4, -5, 10, -7, 2, 3, -1] print [i for i in mylist if i > 2] print (i for i in mylist if i > 2) print [i if i > 0 else 0 for i in mylist] print (i if i > 0 else 0 for i in mylist) values = ['1', '2', '-3', '-', '4', 'N/A', '5'] def is_int(val): try: int(val) return True except ValueError: return False # filter 和 compress 都是返回迭代器, 需要用list()将其转为list print filter(is_int, values) addresses = [ '5412 N CLARK', '5148 N CLARK', '5800 E 58TH', '2122 N CLARK', '5645 N RAVENSWOOD', '1060 W ADDISON', '4801 N BROADWAY', '1039 W GRANVILLE', ] counts = [0, 3, 10, 4, 1, 7, 6, 1] _bools = [n > 5 for n in counts] # _bools = [] # 这里为空或是长度大于addresses都不会报错 print list(compress(addresses, _bools))
#!/usr/bin/env python # -*- coding: utf-8 -*- # 删除序列相同元素并保持顺序 # hashable def dedupe(items): seen = set() for item in items: if item not in seen: yield item seen.add(item) def dedupe2(items, key=None): seen = set() for item in items: val = key(item) if key else item if val not in seen: yield item seen.add(val)
def max2(x,y): if x > y : print(x) else : print(y) def min2(x,y): if x< y : print(x) else : print(y) def my_max(x): print(max(x)) def my_min(x): print(min(x)) max2(4,8) min2(4,8) max2('a','b') max2([1,5],[2,4]) my_max([1,2,3]) my_min('addfasfd1')
#Tugas no 1 prongkom minggu 3 #list 10 konco dulur konco = ['ilham','fairuz','fasya','tasya','yayuk', 'kinor','azzam','dio','maul','maman'] #menampilkan isi list temen no 4,6,7 print(konco[4]) print(konco[6]) print(konco[7]) #Ganti nama konco list 3 5 9 konco[3] = 'nadhira' konco[5] = 'noor' konco[9] = 'fadhila' print(konco) #Menambah 2 nama konco konco.append('juminem') konco.append('kolluy') print(konco) #menampilkan semua teman dengan perulangan for i in konco: print('{}' .format (i))
values = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } numbers = ['MCMXC', 'MMVIII', 'MDCLXVI'] def solution(roman): decimal = 0 for i in range(len(roman)-1): if (value := values[roman[i]]) >= values[roman[i+1]]: decimal += value else: decimal -= value return decimal + values[roman[-1]] for n in numbers: print(solution(n))
import pandas as pd df = pd.read_csv('GPAdata.csv') suma = 0 sumb = 0 sumc = 0 sumf = 0 for index,item in df.iterrows(): if item['評価'] == 'A': suma += item['単位数'] elif item['評価'] == 'B': sumb += item['単位数'] elif item['評価'] == 'C': sumc += item['単位数'] elif item['評価'] == 'D': sumf += item['単位数'] elif item['評価'] == 'F': sumf += item['単位数'] GPA = (4.0*suma + 3.0*sumb + 2.0*sumc) / (suma+sumb+sumc+sumf) print('Your GPA is','{:.2f}'.format(GPA))
from tkinter import * import pyttsx3 import datetime import speech_recognition as sr import wikipedia import webbrowser import os engine=pyttsx3.init('sapi5') voices=engine.getProperty('voices') engine.setProperty('voice',voices[0].id) def speak(audio): engine.say(audio) engine.runAndWait() def wish(): tim=int(datetime.datetime.now().hour) if tim >=0 and tim<12: speak("Good Morning sir!") elif tim >=12 and tim < 18: speak("Good Afternoon sir!") else: speak("Good Evening sir!") speak("I am friday , please tell how may i help you") def takecommand(): r=sr.Recognizer() with sr.Microphone() as source: print("Listening....") r.pause_threshold=1 audio=r.listen(source) try: print("Recognizing...") query=r.recognize_google(audio,language='en-in') print(f"You Said : {query}\n") except Exception as e: print("Could not recognize , Please say that again") return "None" return query def closee(): exit() def main(): wish() try: while True: query=takecommand().lower() if 'wikipedia' in query: speak("Searching wikipedia...") query=query.replace("wikipedia","") results=wikipedia.summary(query,sentences=2) speak("Accoring to wikipedia..") print(results) speak(results) elif 'open youtube' in query: webbrowser.open("youtube.com") elif 'open gmail' in query: webbrowser.open("gmail.com") elif 'open linkedin' in query: webbrowser.open("linkedin.com") elif 'google' in query: webbrowser.open("google.com") elif 'quora' in query: webbrowser.open("quora.com") elif 'github' in query: webbrowser.open("github.com") elif 'stackoverflow' in query: webbrowser.open("stackoverflow.com") elif 'the time' in query: strTime=datetime.datetime.now().strftime("%H:%M:%S") speak(f"sir, the time is {strTime}") elif 'open sublime' in query: spath="C:\\Program Files\\Sublime Text 3\\sublime_text.exe" os.startfile(spath) elif 'open dev' in query: dpath="C:\\Program Files (x86)\\Dev-Cpp\\devcpp.exe" os.startfile(dpath) elif 'quit' in query: exit() except Exception as e: speak("Please try again sir.") root=Tk() root.title("F.R.I.D.A.Y") root.geometry("400x240") root.minsize(400,240) root.maxsize(400,240) root.configure(background="light grey") Label(root,text="Welcome to Virtual Assistant",font="comicsansms 20 bold",bg="light blue").pack(pady=10) Button(root,text="Start",command=main,font="comicsansms 15 bold",pady=5).pack(pady=10) Button(root,text="End",command=closee,font="comicsansms 15 bold",pady=5).pack(pady=10) root.mainloop()
#!/usr/bin/env python3 from local_align import local_align, all_alignment class recordAligner: #These default delimiters render as ^^, ^_, and the space character in tools such as less #They are the delimiters for: #30/^^: classificationRecordSet #31/^_: classificationRecord #32/ : classificationObject def __init__(self, delimiters = [30,31,32], case_sensitive = False): self.delimiters = delimiters self.case_sensitive = case_sensitive def align(self, recordA, recordB): LA = local_align(recordA, recordB) NW = all_alignment(LA, recordA, recordB) #print("A:",recordA[0:50]) # #print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") #print("B:",recordB[0:50]) #print("NW:",NW[0:50]) self.alignments = {} p1 = 0 p2 = 0 l1 = len(recordA) l2 = len(recordB) f1 = [0,0,0,-1] f2 = [0,0,0,-1] n_pos = 0 d1 = True d2 = True while p1 < l1 and p2 < l2: c1 = NW[n_pos][0] ord1 = None ord2 = None if c1 is not None: p1 += 1 ord1 = ord(recordA[c1]) d1 = True if ord1 == self.delimiters[0]: f1[0] += 1 f1[1] = 0 f1[2] = 0 f1[3] = -1 elif ord1 == self.delimiters[1]: f1[1] += 1 f1[2] = 0 f1[3] = -1 elif ord1 == self.delimiters[2]: f1[2] += 1 d1 = False f1[3] += 1 else: d1 = False f1[3] += 1 c2 = NW[n_pos][1] if c2 is not None: p2 += 1 ord2 = ord(recordB[c2]) d2 = True if ord2 == self.delimiters[0]: f2[0] += 1 f2[1] = 0 f2[2] = 0 f2[3] = -1 elif ord2 == self.delimiters[1]: f2[1] += 1 f2[2] = 0 f2[3] = -1 elif ord2 == self.delimiters[2]: f2[2] += 1 d2 = False f2[3] += 1 else: d2 = False f2[3] += 1 #print("C1:",c1,"Ord1:",ord1,"C2:",c2,"Ord2:",ord2,"n_pos:",n_pos,"F1:",f1,"F2:",f2,"D1:",d1,"D2:",d2) if c1 is not None and not d1 and c2 is not None and not d2 and chr(ord1).lower() == chr(ord2).lower(): #print("In loop, C1:",c1,"Ord1:",ord1,"C2:",c2,"Ord2:",ord2,"n_pos:",n_pos,"F1:",f1,"F2:",f2) D = self.alignments for i in range(len(f1)-1): if f1[i] not in D: D[f1[i]] = {} if f2[i] not in D[f1[i]]: D[f1[i]][f2[i]] = {} D = D[f1[i]][f2[i]] D[f1[-1]] = f2[-1] n_pos += 1 #print("Final:",self.alignments) if __name__ == "__main__": A = "abc|def|ghi" B = "abc|def|ghi" RA = recordAligner(delimiters = [ord('|'), ord('^'), 32]) RA.align(A,B) print("A:",A,"B:",B) print(RA.alignments) print() A = "abc|def|ghi" B = "abc|de^f|ghi" RA = recordAligner(delimiters = [ord('|'), ord('^'), 32]) RA.align(A,B) print("A:",A,"B:",B) print(RA.alignments) print() A = "abc|def|gh ij" B = "abc|def|gh j" RA = recordAligner(delimiters = [ord('|'), ord('^'), 32]) RA.align(A,B) print("A:",A,"B:",B) print(RA.alignments) print() A = "abc|def" B = "g|def" RA = recordAligner(delimiters = [ord('|'), ord('^'), 32]) RA.align(A,B) print("A:",A,"B:",B) print(RA.alignments) print()
vowels = ["A", "E", "I", "O", "U"] string = "facetiously" vowel_count = 0 for char in string.upper(): if char in vowels: vowel_count += 1 print("The number of vowels is: " + str(vowel_count))
import matplotlib.pyplot as plt x=[1,2,3,10,8,9,5] y=[1,2,3,4,5,6,7] plt.scatter(x,y , label = 'scatter' , color='g' ,s=25, marker='x') plt.xlabel('x axis') plt.ylabel('y axis') plt.title('Scatter plot') plt.legend() plt.show()
## python 2.7 by Jeremy Benisek # How do you feel? # Start with 0 and False ageinted = 0 ageintstatus = False # Input your name name = raw_input("Enter your name please: ") # Print a Welcome message with inputed name print "Hello and Welcome",name # While True, if false re-enter age with a number while True: age = raw_input("Enter your age in years: ") try: ageinted = float(age) ageintstatus = True except: print "Something didn't work right" if ageintstatus == True: howdoesitfeel = raw_input("How does it feel to be your age: ") print str(ageinted) + "?" print str(howdoesitfeel) + " is how it feels to be " + str(ageinted) break else: print "You didn't enter a number" else: print "failed"
Score = raw_input("Enter Grade Score: ") try: ScoreFloated = float(Score) if ScoreFloated >= 0.9: print "A" elif ScoreFloated >= 0.8: print "B" elif ScoreFloated >= 0.7: print "C" elif ScoreFloated >= 0.6: print "D" elif ScoreFloated < 0.6: print "F" except: print "Bad input"
''' Kullanıcının girdiği iki sayının ortalamasın alan program 1 Başla 2 Sayı Al "Birinci Sayıyı Girin:", sayi1 3 Sayı Al "İkinci Sayıyı Girin:", sayi2 4 ort = (sayi1+sayi2)/2 5 Yaz ort 6 Bitir ''' ''' 15. Satır: input() fonksiyonu ile kullanıcıdan veri alınıyor. bu veri int() fonksiyonu ile tamsayıya dönüştürülüyor ve bu sayı sayi1 değişkenine atanıyor. ''' sayi1 = int(input("Birinci Sayıyı Girin:")) sayi2 = int(input("İkinci Sayıyı Girin:")) ort = (sayi1 + sayi2) / 2 print(ort)
import math # matematik fonksiyonlarını ugulamada kullanabilmek için math kütüphanesini ekliyoruz ''' Öğenci vize notunu girdikten sonra dersi geçmek(50) için alması gereken notu yazan program ''' vize = 100 while vize >= 0 and vize <= 100: vize = int(input("Vize Notunuz:")) final = 0 final = math.ceil((40 - vize * 0.4) / 0.6) if final < 40: final = str(final)+" alman yetiyor ama kuralar gereği 40 " print("Geçmek için en az ", final, "almalısın")
""" Test script using pytest for validator_if Author: Varisht Ghedia """ from validator import validate_if def test_size_one(): """ Test that password is of size 1. """ assert validate_if("a") == True def test_size_twentyone(): """ Test that password cannot be of size more than 20 """ assert validate_if("a"*21) == False def test_size_twenty(): """ Test that password is of size 20. """ assert validate_if("a"*20) == True def test_latin_start(): """ Test that password starts with latin characters. """ assert validate_if("éáíúópaodsipas") == True def test_number_start(): """ Test that password doesn't starts with number. """ assert validate_if("2éáíúópaodsipas") == False def test_character_start(): """ Test that password doesn't starts with special characters. """ assert validate_if("!éáíúópaodsipas") == False def test_latin_end(): """ Test that password ends with latin characters. """ assert validate_if("éáíúópaodsipas") == True def test_number_end(): """ Test that password ends with number. """ assert validate_if("éáíúópaodsipas2") == True def test_character_end(): """ Test that password doesn't end with special characters. """ assert validate_if("éáíúópaodsipas!") == False def test_dot_minus(): """ Test that password can contain "." "-". """ assert validate_if("éáíúóp.ds-ipas") == True def test_special_chars(): """ Test that password cannot contain other special characters. """ assert validate_if("éáíúópao!!dsipas") == False
import random ai = random.randint(1,4) print("gissa på ett av valen från menyn") meny = 0 while meny != 5: print("tryck på 1 för att gissa på hjärter ♥") print("tryck på 2 för att gissa på spader ♠ ") print("tryck på 3 för att gissa på klöver ♣ ") print("tryck på 4 för att gissa på ruter ♦ ") print("tryck på 5 för att avsluta") try: meny = int(input("välj en siffra för att fortsätta ")) except: print("du måste gissa på en siffra ifrån menyn")
from sqlite3.dbapi2 import Cursor import mysql.connector as mysql import csv connection = mysql.connect( host='localhost', user='root', password='', database='sales' ) cursor = connection.cursor() create_query = ''' CREATE TABLE salesperson( id INT(255) NOT NULL AUTO_INCREMENT, firstname VARCHAR(200) NOT NULL, lastname VARCHAR(200) NOT NULL, email VARCHAR(200) NOT NULL, city VARCHAR(200) NOT NULL, state VARCHAR(200) NOT NULL, PRIMARY KEY (id) ) ''' cursor.execute('DROP TABLE IF EXISTS salesperson') cursor.execute(create_query) with open('./salespeople.csv', 'r') as f: csv_data = csv.reader(f) for row in csv_data: row_tuple = tuple(row) cursor.execute( 'INSERT INTO salesperson(firstname, lastname, email, city, state) VALUES ("%s", "%s", "%s", "%s", "%s")', row_tuple) connection.commit() cursor.execute('SELECT * FROM salesperson LIMIT 10') print(cursor.fetchall()) connection.close()
#Panda Data Frames import numpy as np import pandas as pd from numpy.random import randn np.random.seed(101) #Defining a seed for the random func df = pd.DataFrame(randn(5,4),index="A B C D E".split(),columns ="W X Y Z".split()) #the randn would create a 5x4 Matrix with random values and index just like in Series but written with splits for easier handeling, Labels are for rows and columns are to lable columns print(df) #Dataframe operations df["neu"] = df["W"] + df["Y"] #not only can you just make new columns in the dataframes, you could also add the existing frames to each other print(df) df.drop("neu",axis=1) #to show/use the data frame without a specific lable "axis=1" for colomns and "axis=0" for rows, this does not delete a thing df.drop("neu",axis=1,inplace=True) #only by defining inplace as True can we delete something #selecting from a dataframe print(df["W"]) #to get the column W, btw this keeps the index print(df[["W","Z"]]) #to get more than one colomns print(df.W) #or it could be used like this print(df.loc["A"])#to get a row print(df.iloc[2])#this will get the row "C" since it has the indx 2 in the row list print(df.loc["B","Y"]) #to get the value of the row B from the y columns print(df.loc[["A","B"],["W","Y"]]) #to get a subset print(df>0) #this would print a dataframe with the boolean value of True where the number is > 0 print(df[df>0]) #to print a dataframe of the dataframe where the value is True if the number > 0 (NaN would be given if the cell is <0) print(df["W"]>0) #this would only print the boolean values of the "W" Column print(df[df["W"]>0]) #meanwhile this would print the entre data frame except the lines where in "W" a number is negativ (Here C would be ignored) print(df[df["W"]>0][["Y"]]) #get the Column "Y" where the "W" has postiv values print(df[df["W"]>0][["Y","X","Z"]]) #you can also get more than one column at a time print(df[(df["W"]>0) & (df["Y"]>1)]) #to add more conditions one need to use "&" instead of "and" since "and" doesnt work with a Dataframe of value like the one we have here print(df[(df["W"]>0) | (df["Y"]>1)]) #using the or condition #Datframe index Operations new = "NY LA LV LN DC".split() df["Cities"] = new #to add a new column print(df) df.set_index("Cities",inplace=True) #to turn Cities into the index print(df) #Multi indexing outter = ["G1","G1","G1","G2","G2","G2"]#by repeating G1 for example we defined that the first 3 sub_indexs are in G1 inner = [1,2,3,1,2,3] hier_indx = list(zip(outter,inner)) #to combine the two lists hier_indx = pd.MultiIndex.from_tuples(hier_indx) #defining the Multiindex df = pd.DataFrame(np.random.randn(6,2),index=hier_indx,columns="A B".split()) print(df) df.index.names = ["Groups" , "Numbers"] #giving names to index columns print(df) #Selecting from Multi indexing print(df.loc["G1"].loc[2]) #we'd get 2 Values here since the "2" is an inner index used twice print(df.xs(["G1",1])) #xs is for getting the cross section print(df.xs(1,level="Numbers"))
""" Умова: Нехай число N - кількість хвилин, відрахованих після півночі. Скільки годин і хвилин буде показувати цифровий годинник, якщо за відлік взяти 00:00? Програма повинна виводити два числа: кількість годин (від 0 до 23) і кількість хвилин (від 0 до 59). Візьміть до уваги, що починаючи з півночі може пройти декілька днів, тому число N може бути достатньо великим. Вхідні дані: 1 ціле число, що вводить користувач Вихідні дані: вивести два числа. Перше - години, друге - хвилини. """ a = int(input()) a = int(a % 1440) print(a // 60) print(a % 60)
number1 = int(input("Enter the first number:")) number2 = int(input("Enter the second number")) number3 = int(input("Enter the third number")) if (number1 < number2) and (number2 < number3): print(number1) elif (number1 < number3) and (number3 < number2): print(number1) elif (number2 < number1) and (number1 < number3): print(number2) elif (number2 < number3) and (number3 < number1): print(number2) elif (number3 < number1) and (number1 < number2): print(number3) elif (number3 < number2) and (number2 < number1): print(number3) elif (number1 == number2) and (number1 < number3): print(number1) elif (number1 == number3) and (number1 < number2): print(number1) elif (number3 == number2) and (number3 < number1): print(number2) else: print(number1)
# Modified starter code from Laura # %% # Step 1: Import modules used in this script import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl from sklearn.linear_model import LinearRegression import datetime import json import urllib.request as req import urllib import dataretrieval.nwis as nwis import geopandas as gpd import fiona from shapely.geometry import Point import contextily as ctx # %% # Step 2: Set up any functions that will be used in this script def model_2wk_predict(precip1, precip2, temp1, temp2): """Function that makes 1 and 2 week flow predictions based on a regression model. The model should be built on 1 week time lagged flows, precip, and temperature, all weekly average variables. The model should be named 'model'. The two predictions are saved to an array and printed. Inputs = (ints or floats) average weekly value for model variables, all normalized: precip1 = expected average precip for next week in inches precip2 = expected average precip for two weeks from now in inches temp1 = expected average temp for next week in fahrenheit temp1 = expected average temp for two weeks from now in fahrenheit Output = (array) array containing two values which represent 1 and 2 week forecast based on the regression model model_predictions[0] = 1 week prediciton of average natural log flow model_predictions[1] = 2 week prediciton of average natural log flow """ flow = data['flow_tm1_nm'].iloc[-1] precip1_nm = (precip1 - data['precip'].mean()) / data['precip'].std() precip2_nm = (precip1 - data['precip'].mean()) / data['precip'].std() temp1_nm = (temp1 - data['airtemp'].mean()) / data['airtemp'].std() temp2_nm = (temp1 - data['airtemp'].mean()) / data['airtemp'].std() model_predictions = np.zeros(2) for i in range(0, 2): log_flow = model.intercept_ \ + model.coef_[0] * flow \ + model.coef_[1] * precip1_nm\ + model.coef_[2] * temp1_nm model_predictions[i] = np.exp(log_flow) print('AR model ', i+1, ' week forecast is ', model_predictions[i].round(2), ' cfs') flow = (log_flow - data['flow_log'].mean()) / data['flow_log'].std() precip1_nm = precip2_nm temp1_nm = temp2_nm return model_predictions # %% # Step 3: Make a map to orient ourselves # Dataset 1: USGS stream gauges # Download Gauges II USGS stream gauge dataset here: # https://water.usgs.gov/GIS/metadata/usgswrd/XML/gagesII_Sept2011.xml#stdorder # Read in using geopandas file = os.path.join('../data/GIS_files', 'gagesII_9322_sept30_2011.shp') gages = gpd.read_file(file) # Filter to only AZ gauges gages.columns gages.STATE.unique() gages_AZ = gages[gages['STATE'] == 'AZ'] # Dataset 2: Watershed boundaries for the Lower Colorado # Download WBD_15_HU2_GDB.gdb from USGS here: # https://www.usgs.gov/core-science-systems/ngp/national-hydrography/access-national-hydrography-products # https://viewer.nationalmap.gov/basic/?basemap=b1&category=nhd&title=NHD%20View # Read in using geopandas file = os.path.join('../data/GIS_files', 'WBD_15_HU2_GDB.gdb') fiona.listlayers(file) HUC6 = gpd.read_file(file, layer="WBDHU6") # Filter to only Verde River Watershed HUC6.columns HUC6.name.unique() HUC6_Verde = HUC6[HUC6['name'] == 'Verde'] # Dataset 3: Major rivers/streams # Download USA Rivers and Streams from Esri here: # https://hub.arcgis.com/datasets/esri::usa-rivers-and-streams?geometry=-115.952%2C31.858%2C-109.014%2C33.476 # Read in using geopandas file = os.path.join('../data/GIS_files', 'USA_Rivers_and_Streams.shp') rivers_USA = gpd.read_file(file) # Filter to only AZ rivers_USA.columns rivers_USA.State.unique() rivers_AZ = rivers_USA[rivers_USA['State'] == 'AZ'] # Filter to only Verde rivers_AZ.columns rivers_AZ.Name.unique() river_Verde = rivers_AZ[rivers_AZ['Name'] == 'Verde River'] # Dataset 4: Add point location of our stream gage # https://waterdata.usgs.gov/nwis/inventory/?site_no=09506000&agency_cd=USGS # Stream gauge: 34.44833333, -111.7891667 point_list = np.array([[-111.7891667, 34.44833333]]) # Make point into spatial feature point_geom = [Point(xy) for xy in point_list] point_geom # Make a dataframe of the point point_df = gpd.GeoDataFrame(point_geom, columns=['geometry'], crs=HUC6.crs) # Re-project datasets to match gages_AZ points_project = point_df.to_crs(gages_AZ.crs) HUC6_project = HUC6.to_crs(gages_AZ.crs) HUC6_Verde_project = HUC6_Verde.to_crs(gages_AZ.crs) rivers_AZ_project = rivers_AZ.to_crs(gages_AZ.crs) river_Verde_project = river_Verde.to_crs(gages_AZ.crs) # Plot projected datasets together fig, ax = plt.subplots(figsize=(5, 7)) # Set map extent to zoom in on Verde River watershed xlim = ([-1600000, -1300000]) ylim = ([1250000, 1600000]) ax.set_xlim(xlim) ax.set_ylim(ylim) # Draw layers in specified order using zorder HUC6_project.boundary.plot(ax=ax, color=None, edgecolor='black', zorder=1, label='Watersheds (HUC2)', linewidth=0.75) HUC6_Verde_project.boundary.plot(ax=ax, color=None, edgecolor='black', linewidth=2, zorder=2) rivers_AZ_project.plot(ax=ax, linewidth=0.5, color='b', label='Rivers/Streams', zorder=3) river_Verde_project.plot(ax=ax, linewidth=2, color='b', zorder=4) gages_AZ.plot(ax=ax, markersize=40, marker='^', color='limegreen', edgecolor='black', label='USGS stream gage', zorder=5) points_project.plot(ax=ax, color='yellow', marker='^', edgecolor='black', markersize=70, label='Verde River forecast gage', zorder=6) # Set map title and axes names ax.set_title('Verde River Watershed') ax.set_xlabel('Easting (m)') ax.set_ylabel('Northing (m)') ax.ticklabel_format(style="sci", scilimits=(0,0)) ax.legend(loc='upper right', fontsize=7) # Add Topo basemap and reproject basemap to match gages_AZ ctx.add_basemap(ax, crs=gages_AZ.crs, url=ctx.providers.OpenTopoMap) plt.show() # Save Figure fig.savefig("VerdeWatershed_Map", bbox_inches='tight') # %% # Step 4: Read in USGS streamflow data and create dataframe of avg weekly flow # Use nwis.get_record function instead of saving a local file # Change stop_date each week station_id = "09506000" USGS_start = "2016-12-25" USGS_stop = "2020-11-21" data_flow = nwis.get_record(sites=station_id, service='dv', start=USGS_start, end=USGS_stop, parameterCd='00060') # Rename columns data_flow.columns = ['flow', 'code', 'site_no'] # Make index a recognized datetime format instead of string data_flow.index = data_flow.index.strftime('%Y-%m-%d') data_flow['datetime'] = pd.to_datetime(data_flow.index) # Aggregate flow values to weekly flow_weekly = data_flow.resample("W-SAT", on='datetime').mean() # %% # Step 5: Read in Mesowest precip data # Change demotoken to your token when running mytoken = 'ee2e11fb217d4d42b54782f4f101a397' # This is the base url that will be the start final url base_url = "http://api.mesowest.net/v2/stations/timeseries" # Specific arguments for the data that we want # Change end date each week args = { 'start': '201612250000', 'end': '202011210000', 'obtimezone': 'UTC', 'vars': 'precip_accum_since_local_midnight', 'stids': 'C4534', 'units': 'precip|in', 'token': mytoken} apiString = urllib.parse.urlencode(args) fullUrl = base_url + '?' + apiString response = req.urlopen(fullUrl) responseDict = json.loads(response.read()) # Pull out date and temperature data dateTime = responseDict['STATION'][0]['OBSERVATIONS']['date_time'] precip = responseDict['STATION'][0]['OBSERVATIONS']['precip_accum_since_local_midnight_set_1'] # Create dataframe data_precip = pd.DataFrame({'Precip': precip}, index=pd.to_datetime(dateTime)) # Aggregate to weekly precip_weekly = data_precip.resample('W-SAT').mean() precip_weekly['Precip'] = precip_weekly['Precip'].replace(np.nan, 0) # Make index a recognized datetime format instead of string precip_weekly.index = precip_weekly.index.strftime('%Y-%m-%d') # %% # Step 6: Read in Mesowest temperature data # Change demotoken to your token when running mytoken = 'ee2e11fb217d4d42b54782f4f101a397' # This is the base url that will be the start final url base_url = "http://api.mesowest.net/v2/stations/timeseries" # Specific arguments for the data that we want # Change end date each week args = { 'start': '201612250000', 'end': '202011210000', 'obtimezone': 'UTC', 'vars': 'air_temp', 'stids': 'QVDA3', 'units': 'temp|F', 'token': mytoken} apiString = urllib.parse.urlencode(args) fullUrl = base_url + '?' + apiString response = req.urlopen(fullUrl) responseDict = json.loads(response.read()) # Pull out date and temperature data dateTime = responseDict['STATION'][0]['OBSERVATIONS']['date_time'] airT = responseDict['STATION'][0]['OBSERVATIONS']['air_temp_set_1'] # Create dataframe data_temp = pd.DataFrame({'AirTemp': airT}, index=pd.to_datetime(dateTime)) # Aggregate to weekly temp_weekly = data_temp.resample('W-SAT').mean() # Make index a recognized datetime format temp_weekly.index = temp_weekly.index.strftime('%Y-%m-%d') # %% # Step 7: Combine datasets into one dataframe data = flow_weekly.copy() data['precip'] = precip_weekly['Precip'] data['airtemp'] = temp_weekly['AirTemp'] # %% # Step 8: Setup the arrays used to build regrssion model # This model uses a single 1 week time lag of flow, precip, and temp # We will predict natural log of flow data['flow_log'] = np.log(data['flow']) # Create column of normalized log flow for plotting data['flow_log_nm'] = (data['flow_log'] - data['flow_log'].mean()) / data['flow_log'].std() # Shift log flow to create column of 1 week lagged log flow data['flow_tm1'] = data['flow_log'].shift(1) # Remove first row since it is missing lagged flow data = data.iloc[1:] # 1st model input variable: normalized lagged flow data['flow_tm1_nm'] = (data['flow_tm1'] - data['flow_tm1'].mean()) / data['flow_tm1'].std() # 2nd model input variable: normalized precip data['precip_nm'] = (data['precip'] - data['precip'].mean()) / data['precip'].std() # 3rd model input variable: normalized temp data['airtemp_nm'] = (data['airtemp'] - data['airtemp'].mean()) / data['airtemp'].std() # %% # Step 9: Pick what portion of the time series to use as training data # For this AR model, training = 2017-2018, testing = 2019-2020 train = data['2017-01-07':'2018-12-29'][['flow_log', 'flow_tm1_nm', 'precip_nm', 'airtemp_nm']] test = data['2019-01-05':][['flow_log', 'flow_tm1_nm', 'precip_nm', 'airtemp_nm']] # %% # Step 10: Fit linear regression model model = LinearRegression() x = train[['flow_tm1_nm', 'precip_nm', 'airtemp_nm']] y = train['flow_log'].values model.fit(x, y) r_sq = np.round(model.score(x, y), 2) print('coefficient of determination:', np.round(r_sq, 2)) print('intercept:', np.round(model.intercept_, 2)) print('slope:', np.round(model.coef_, 2)) # %% # Step 11: Set up prediction functions to view model performance q_pred_train = model.predict(train[['flow_tm1_nm', 'precip_nm', 'airtemp_nm']]) q_pred_test = model.predict(test[['flow_tm1_nm', 'precip_nm', 'airtemp_nm']]) # %% # Step 12: Generate plots to visualize regression model and datasets # This step is optional, not neccessary to generate the forecasts. # Set plot style and sublot layout plt.style.use('classic') fig, ax = plt.subplots(1, 3, figsize=(12, 4)) ax = ax.flatten() fig.tight_layout() plt.subplots_adjust(hspace=0.5, wspace=0.2) # PLOT 1: Model Period ax[0].plot(train['flow_log'], 'orange', label='training period', linewidth=6) ax[0].plot(test['flow_log'], 'greenyellow', label='testing period', linewidth=6) ax[0].plot(data['flow_log'], 'b', label='observed flow', linewidth=1) ax[0].set(title="Model Period (2017-2020)", xlabel="Date", ylabel="Weekly Avg Natual Log Flow [cfs]", xlim=['2017-01-07', '2020-11-21']) ax[0].legend(fontsize=8) plt.setp(ax[0].get_xticklabels(), rotation=45) # PLOT 2: Normalized Predictive Variables ax[1].plot(data['flow_log_nm'], 'navy', label='observed flow') ax[1].plot(data['flow_tm1_nm'], 'cornflowerblue', label='lagged flow') ax[1].plot(data['precip_nm'], 'forestgreen', label='precip') ax[1].plot(data['airtemp_nm'], 'orange', label='temperature') ax[1].set(title="Normalized Predictive Variables", xlabel="Date", xlim=['2017-01-07', '2018-12-29']) ax[1].legend(fontsize=8) plt.setp(ax[1].get_xticklabels(), rotation=45) # PLOT 3: Model Performance ax[2].scatter(np.sort(test['flow_log']), np.sort(q_pred_test), color='m', edgecolor='purple', label='Model Predictions') ax[2].plot([0,9], [0,9], color='blue', alpha=0.5) ax[2].set(title="Model Performance - Testing Period", xlabel="Observed Natural Log Flow", ylabel="Simulated Natural Log Flow", xlim = [3,9], ylim = [3,9]) ax[2].legend(fontsize=8) plt.setp(ax[2].get_xticklabels(), rotation=45) plt.show() # Save Figure fig.savefig("Regression_Model_Visualization", bbox_inches='tight') # %% # Step 13: Forecast predictions # Manually input expected precipitation and temperture for the next two weeks precip_1wk = 0 precip_2wk = 0 temp_1wk = 50 temp_2wk = 50 # Call function to make prediction model_predictions = model_2wk_predict(precip_1wk, precip_2wk, temp_1wk, temp_2wk) # %% # Step 14: Make predictions for 16 week forecast # Predictions will be based on weekly flow in 2019, which was a low flow year # For this year, I will assume max weekly flow of 200 cfs flow_2019 = data["2019-08-31":"2019-12-14"] lt_forecast = np.zeros(16) for i in range(0, 16): if flow_2019['flow'].iloc[i] <= 200: lt_forecast[i] = flow_2019['flow'].iloc[i].round(0) print('lt_week', i+1, ' = ', flow_2019['flow'].iloc[i].round(0)) else: lt_forecast[i] = 200 print('lt_week', i+1, ' = 200 cfs') # %%
# %% import os import numpy as np import pandas as pd import matplotlib as plt # we can name our rows and columns an refer to them by name # we don't have to have just 1 datatype # Three things - Series, DataFrames, Indices # loc is using row names, iloc is using row numbers # %% 9/29 in class exercise data = np.ones((7,3)) data_frame = pd.DataFrame(data, columns = ['data1', 'data2', 'data3'], index=['a','b','c','d','e','f','g']) print(data) print(data_frame) # %% A) Change the values for all of the vowel rows to 3 #Method1 data_frame.loc["a"] *= 3 data_frame.loc["e"] *= 3 print(data_frame) #Method2 - changes data not dataframe data[0:1] = [3., 3., 3.] data[4:5] = [3., 3., 3.] print(data) #Method3 - using mask with conditional statement data[(data_frame.index=='a') | (data_frame.index=='e')]=3 print(data) #Method4 - using list of row names [] data_frame.loc[['a','e']]=3 # %% B) multiply the first 4 rows by 7 #method1 data_frame.loc[['a','b','c','d']]*=7 print(data_frame) #method2 data_frame=data_frame.iloc[:4,:] * 7 # %% C) Make the dataframe into a checkerboard of 0's and 1's using loc data_frame.loc[['a','c','e','g'],['data1','data3']]=0 data_frame.loc[['b','d','f'],['data2']]=1 print(data_frame) # %% D) Do the same thing without using loc data_frame.iloc[0:8:2,0:3:2] = 0 data_frame.iloc[1:8:2,1:3:2] = 1 print(data_frame) # %%
def add_fns(f_and_df, g_and_dg): """Return the sum of two polynomials.""" def add(n, derived): return f_and_df(n, derived) + g_and_dg(n, derived) return add def mul_fns(f_and_df, g_and_dg): """Return the product of two polynomials.""" def mul(n, derived): f, df = lambda x: f_and_df(x, False), lambda x: f_and_df(x, True) g, dg = lambda x: g_and_dg(x, False), lambda x: g_and_dg(x, True) if derive: return f(x) * dg(x) + df(x) * g(x) else: return f(x) * g(x) return mul def poly_zero(f_and_df): """Return a zero of polynomial f_and_df, which returns: f(x) for f_and_df(x, False) df(x) for f_and_df(x, True) >>> q = quadratic(1, 6, 8) >>> round(poly_zero(q), 5) # Round to 5 decimal places -2.0 >>> round(poly_zero(quadratic(-1, -6, -9)), 5) -3.0 """ return find_zero(lambda x: f_and_df(x, False), lambda x: f_and_df(x, True))
def g(n): """Return the value of G(n), computed recursively. >>> g(1) 1 >>> g(2) 2 >>> g(3) 3 >>> g(4) 10 >>> g(5) 22 """ if n <= 3 : return n else : return g(n-1) + 2* g(n-2) + 3 * g(n-3) def g_iter(n): """Return the value of G(n), computed iteratively. >>> g_iter(1) 1 >>> g_iter(2) 2 >>> g_iter(3) 3 >>> g_iter(4) 10 >>> g_iter(5) 22 """ if n <= 3: return n else: i = 2 pre, curr, next = 1, 2, 3 while i < n : pre, curr, next = curr, next, next + 2*curr + 3*pre i += 1 return curr def has_seven(k): """Returns True if at least one of the digits of k is a 7, False otherwise. >>> has_seven(3) False >>> has_seven(7) True >>> has_seven(2734) True >>> has_seven(2634) False >>> has_seven(734) True >>> has_seven(7777) True """ if k==7 : return True elif k % 10 == 7 : return True elif k > 10: return has_seven(k // 10) return False def pingpong(n): """Return the nth element of the ping-pong sequence. >>> pingpong(7) 7 >>> pingpong(8) 6 >>> pingpong(15) 1 >>> pingpong(21) -1 >>> pingpong(22) 0 >>> pingpong(30) 6 >>> pingpong(68) 2 >>> pingpong(69) 1 >>> pingpong(70) 0 >>> pingpong(71) 1 >>> pingpong(72) 0 >>> pingpong(100) 2 """ def up(k,i): k, i = k + 1, i + 1 if i % 7== 0 or has_seven(i): return down(k,i) elif i != n: return up(k, i) else: return k def down(k,i): k, i = k - 1, i + 1 if i % 7== 0 or has_seven(i): return up(k,i) elif i != n: return down(k,i) else: return k return up(1,1)
## Trees, Dictionaries ## ######### # Trees # ######### import inspect # Tree definition - same Data Abstraction but different implementation from lecture def tree(root, branches=[]): #for branch in branches: # assert is_tree(branch) return lambda dispatch: root if dispatch == 'root' else list(branches) def root(tree): return tree('root') def branches(tree): return tree('branches') def is_tree(tree): try: tree_data = inspect.getargspec(tree) assert tree_data == inspect.getargspec(lambda dispatch: None) return all([is_tree(branch) for branch in branches(tree)]) except: return False def is_leaf(tree): return not branches(tree) def print_tree(t, indent=0): """Print a representation of this tree in which each node is indented by two spaces times its depth from the root. >>> print_tree(tree(1)) 1 >>> print_tree(tree(1, [tree(2)])) 1 2 >>> print_tree(numbers) 1 2 3 4 5 6 7 """ print(' ' * indent + str(root(t))) for branch in branches(t): print_tree(branch, indent + 1) numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])]) # Q1 def countdown_tree(): """Return a tree that has the following structure. >>> print_tree(countdown_tree()) 10 9 8 7 6 5 """ return tree(10, [tree(9, [tree(8)]), tree(7, [tree(6, [tree(5)])])]) # Q2 def size_of_tree(t): """Return the number of entries in the tree. >>> print_tree(numbers) 1 2 3 4 5 6 7 >>> size_of_tree(numbers) 7 """ if is_leaf(t): return 1 return 1 + sum([size_of_tree(branch)for branch in branches(t)]) ################ # Dictionaries # ################ # Q3 def counter(message): """ Returns a dictionary of each word in message mapped to the number of times it appears in the input string. >>> x = counter('to be or not to be') >>> x['to'] 2 >>> x['be'] 2 >>> x['not'] 1 >>> y = counter('run forrest run') >>> y['run'] 2 >>> y['forrest'] 1 """ word_list = message.split() result_dict = {} for word in word_list: if word in result_dict: result_dict[word] += 1 else: result_dict[word] = 1 return result_dict
while True: # main program while True: answer = input('Run again? (y/n): ') if answer in ('y', 'n'): break print('Invalid input.') if answer == 'y': continue else: print('Goodbye') break
# 기존 계획(Naver Shopping API 활용) 폐지, webbrowser 모듈 활용, url open에 집중 # User가 후기를 본 후 제품명을 입력하면, 해당 제품의 Naver Shopping 사이트로 연결 import io import os import sys import webbrowser as wb class Shopping: def goToShopSite(self): url = 'https://search.shopping.naver.com/search/all?query=' + self.finalProduct wb.open(url) userChoice = input('다른 결과가 필요하시다면 제품명을 입력해 주세요 (제품명 or Exit): ') while userChoice != 'Exit': url = 'https://search.shopping.naver.com/search/all?query=' + userChoice wb.open(url) userChoice = input('다른 결과가 필요하시다면 제품명을 입력해 주세요 (제품명 or Exit): ')
num = int(input("Input the number for calculating the factorial:").strip()) fact = 1 i=1 print(type(num)) while i <=num: fact = fact*i i = i + 1 print (fact)
# -*- coding: utf-8 -*- """ Created on Sat May 2 01:07:45 2020 @author: Moon """ import csv # read data with open('C:/Users/ED/Desktop/covid/COVID-19/Date/list_state.csv', newline='') as csvfile: rows = csv.reader(csvfile) for list_state in rows: print(list_state) with open('C:/Users/ED/Desktop/covid/COVID-19/Date/list_date.csv', newline='') as csvfile: rows = csv.reader(csvfile) for list_date in rows: print(list_date) with open('C:/Users/ED/Desktop/covid/COVID-19/Date/la.csv', newline='') as csvfile: rows = csv.reader(csvfile) for la in rows: print(la) mix_three = [] for i in range(len(list_state)): for j in range(118*i, 118*i+118): mix_three.append([list_state[i], list_date[j], la[j]]) # write data with open('C:/Users/ED/Desktop/covid/COVID-19/Date/mix_three.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) for row in mix_three: writer.writerow(row)
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt #loading the dataset dataset=pd.read_csv('Social_Network_Ads.csv') x=dataset.iloc[:,[2,3]].values y=dataset.iloc[:,4].values #Visualizing the dataset dataset.iloc[:,[2,3]].count().plot(kind='bar') #Describing dataset.describe() #head and tail of dataset dataset.head(5) dataset.tail(5) #spliting the dataset from sklearn.cross_validation import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,random_state=0) #feature Scaling from sklearn.preprocessing import StandardScaler sc_x=StandardScaler() x_train=sc_x.fit_transform(x_train) x_test=sc_x.transform(x_test) #Building the svm model from sklearn.svm import SVC #classifier=SVC(kernel='linear',random_state=0) #accuracy=90 #classifier.fit(x_train,y_train) #changing the kernel to rbf accuracy Checking classifier=SVC(kernel='rbf',random_state=0) #accuracy=93 classifier.fit(x_train,y_train) #changing the kernel to poly accuracy Checking #classifier=SVC(kernel='poly',degree=3,random_state=0) #accuracy=86 #classifier.fit(x_train,y_train) #changing the kernel to poly accuracy Checking #classifier=SVC(kernel='sigmoid',random_state=0) #accuracy=74 #overfitted #classifier.fit(x_train,y_train) #Prediction y_pred=classifier.predict(x_test) #Evaluating the model usind confusion matrix from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test,y_pred) #Accuracy accuracy=classifier.score(x_test,y_test) #Applying k-Fold cross validation from sklearn.model_selection import cross_val_score kfoldaccuracy=cross_val_score(estimator=classifier,X=x_train,y=y_train,cv=10) kfoldaccuracy.mean() kfoldaccuracy.std() #implementing the grid search to find the best model and best hyperparameters from sklearn.model_selection import GridSearchCV parameters=[{'C':[1,10,100,1000],'kernel':['linear']}, {'C':[1,10,100,1000],'kernel':['rbf'], 'gamma':[0.5,0.1,0.2,0.4,0.3,0.6,0.7]}, {'C':[1,10,100,1000],'kernel':['poly'],'degree':[2,3,4], 'gamma':[0.5,0.1,0.2]}] grid_search=GridSearchCV(estimator=classifier,param_grid=parameters, scoring='accuracy',n_jobs=-1,cv=10) grid_search=grid_search.fit(x_train,y_train) best_accuracy=grid_search.best_score_ best_model=grid_search.best_params_ #Visualizing the classifier training set from matplotlib.colors import ListedColormap x_set,y_set=x_train,y_train x1,x2=np.meshgrid(np.arange(start=x_set[:,0].min()-1,stop=x_set[:,0].max()+1,step=0.01), np.arange(start=x_set[:,1].min()-1,stop=x_set[:,1].max()+1,step=0.01)) plt.contourf(x1,x2,classifier.predict(np.array(([x1.ravel(),x2.ravel()])).T).reshape(x1.shape),alpha=0.75,cmap=ListedColormap(('red','green'))) plt.xlim(x1.min(),x1.max()) plt.ylim(x2.min(),x2.max()) for i,j in enumerate(np.unique(y_set)): plt.scatter(x_set[y_set==j,0],x_set[y_set==j,1],c=ListedColormap(('red','green'))(i),label=j) plt.title('SVM Training Set') plt.xlabel('Ages') plt.ylabel('Estimated Salary') plt.legend() plt.show() #Visualizing the classifier Testing set from matplotlib.colors import ListedColormap x_set,y_set=x_test,y_test x1,x2=np.meshgrid(np.arange(start=x_set[:,0].min()-1,stop=x_set[:,0].max()+1,step=0.01), np.arange(start=x_set[:,1].min()-1,stop=x_set[:,1].max()+1,step=0.01)) plt.contourf(x1,x2,classifier.predict(np.array(([x1.ravel(),x2.ravel()])).T).reshape(x1.shape),alpha=0.75,cmap=ListedColormap(('red','green'))) plt.xlim(x1.min(),x1.max()) plt.ylim(x2.min(),x2.max()) for i,j in enumerate(np.unique(y_set)): plt.scatter(x_set[y_set==j,0],x_set[y_set==j,1],c=ListedColormap(('red','green'))(i),label=j) plt.title('SVM Test Set') plt.xlabel('Ages') plt.ylabel('Estimated Salary') plt.legend() plt.show()
# Write your function, here. def char_count(target, string): res = 0 i = 0 while i < len(string): char = string[i] if char == target: res += 1 i += 1 return res print(char_count("a", "App Academy")) # > 1 print(char_count("c", "Chamber of Secrets")) # > 1 print(char_count("b", "big fat bubble")) # > 4
# Write your function, here. def is_empty(dictionary): return len(list(dictionary)) == 0 # Solution 2 def is_empty(d): return not d print(is_empty({})) # > True print(is_empty({"a": 1})) # > False
# Write your function, here. def is_valid_hex_code(code): if code[0] != "#" or len(code) != 7: return False i = 1 while i < len(code): c = code[i].lower() if not c.isdigit(): if c != "a" and c != "b" and c != "c" and c != "d" and c != "e" and c != "f": return False i += 1 return True ## Here's another variant, with the for loop. ## You'll learn more about this tomorrow. def is_valid_hex_code_with_for(color): if color[0] != "#" or len(color) != 7: return False color_chars = list("abcdef0123456789") for char in color[1:].lower(): if char not in color_chars: return False return True print(is_valid_hex_code("#CD5C5C")) # > True print(is_valid_hex_code("#EAECEE")) # > True print(is_valid_hex_code("#eaecee")) # > True print(is_valid_hex_code("#CD5C58C")) # Prints False # Length exceeds 6 print(is_valid_hex_code("#CD5C5Z")) # Prints False # Not all alphabetic characters in A-F print(is_valid_hex_code("#CD5C&C")) # Prints false # Contains unacceptable character print(is_valid_hex_code("CD5C5C")) # Prints False # Missing #
# It's time to put your knowledge of lists, tuples and dictionaries together. In this exercise, you will complete the basic statistics calculations for # Minimum # Maximum # Mean # Median # Mode # Follow the instructions in the code comments. Be sure to test your work by running your code! # You will likely need to look at the Python documentation to complete this activity. (Search 'dictionary', go to 'Built-in Types', scroll down to 'Mapping Types - dict'.) # After Step 1, you should see this in the terminal: # ('min', 'max', 'mean', 'median', 'mode') # (1, 9, 5.0, None, None) # (12, 99, 43.666666666666664, None, None) # In Step 2, the expected median values are 5 and 35.5. Median is the middle element. When the list has an odd length it's as easy as taking the value at the middle index on the sorted list. When the length is even, it's the average of the two numbers closest to the middle. # In Step 3, the expected mode values are 1 and 23. Mode is the element which is most repeated. # BONUS A is really whatever you want to do. It is recommended that you add fringe cases (e.g. a list of a single number like zero or all numbers are the same). # BONUS B is to revisit the mode function and return nothing if more than one number is repeated the most number of times (like sample1). When successful, this would result in (1, 9, 5.0, 5, None) for the first call to analyze. # STEP 1: Complete analyze function to return 5 values: # - minimum # - maximum # - mean (a.k.a. average) # - median (center point) # - mode (most repeated) def analyze(nums): return (min(nums), max(nums), sum(nums) / len(nums), median(nums), mode(nums)) # STEP 2: Complete median function to return center number # WITHOUT using built-in function def median(nums): # if there are no numbers, then exit right away if len(nums) == 0: return 0 # sort numbers and find the middle orderedNums = sorted(nums) midIndex = len(orderedNums) // 2 # if there's an odd number, use the number in the middle if len(orderedNums) % 2 == 1: return orderedNums[midIndex] # if there's an even number, use average of two elements in the middle return (orderedNums[midIndex] + orderedNums[midIndex - 1]) / 2 # STEP 3: Complete mode function to return most-repeated number # WITHOUT using built-in function def mode(nums): # build a dictionary to track the element counts lookup = dict.fromkeys(nums, 0) for x in nums: lookup[x] += 1 # make parallel arrays of the numbers (elements) and counts counts = list(lookup.values()) elements = list(lookup.keys()) # find the largest count and its position highCount = max(counts) highAt = counts.index(highCount) # BONUS B: Catch special case where more than one value repeats the most counts.sort() if len(nums) > 1 and (len(counts) == 1 or counts[-2] == highCount): return # mode is the number corresponding to the highest count return elements[highAt] # DO NOT EDIT - sample data for checking your work sample1 = 1, 2, 3, 4, 5, 6, 7, 8, 9 sample2 = [37, 45, 23, 65, 75, 34, 23, 23, 23, 65, 12, 99] print(("min", "max", "mean", "median", "mode")) print(analyze(sample1)) print(analyze(sample2)) # BONUS A: Print more samples as you see fit print(analyze([0])) print(analyze([1, 1, 1, 1, 1]))
def cap_space(string): res = "" i = 0 while i < len(string): char = string[i] if char.isupper(): res += " " res += char i += 1 return res.lower() print(cap_space("helloWorld")) #> "hello world" print(cap_space("iLoveMyTeapot")) #> "i love my teapot" print(cap_space("stayIndoors")) #> "stay indoors"
# Create your function, here. def increment(num): return num + 1 print(increment(0)) # > 1 print(increment(9)) # > 10 print(increment(-3)) # > -2
# dictionary tut dict = {"key" : "val", "jey2":"val"} dict["key"] # prints out "val" associated with key #dictionaries are non sequential so printing a dict would give different results every time it is done #dictionary problem ques = "Enter Customer ? " ques2 = "Customer Name: " dict_list = [] while (True): ans = input(ques) if ans == 'y': name = input(ques2) name.strip() nameList = name.split() newDict = {"fname" : nameList[0], "lname" : nameList[1]} dict_list.append(newDict) else: break for dict in dict_list: print(dict["fname"] + " " + dict["lname"]) # Done
import socket from typing import Any def port_validation(value: Any, check_open: bool = False) -> bool: #check if the port is correct try: # converting to int number value = int(value) if 1 <= value <= 65535: # if Port Busy if check_open: return check_port_open(value) print(f"Correct Port {value}") return True print(f"Wrong Value {value} for the Port") return False except ValueError: print(f"Value {value} is not a number") return False def check_port_open(port: int) -> bool: #check if the port busy or if its avaliable sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1', port)) sock.close() if result == 0: print(f"Port {port} Busy") return False else: print(f"Port {port} Free") return True def ip_validation(address: str) -> bool: #check IP V4 error_message = f"Wrong ip-address {address}" ok_message = f"correct ip-address {address}" try: socket.inet_pton(socket.AF_INET, address) except AttributeError: # no inet_pton here, sorry try: socket.inet_aton(address) except socket.error: print(error_message) return False return address.count('.') == 3 except socket.error: # not a valid address print(error_message) return False print(ok_message) return True
def convert_to_minutes(num_hours): """(int) -> int Return the number of minutes there are in num_hours hours. >>> convert_to_minutes(2) 120 """ result = num_hours * 60 return result def convert_to_seconds(num_hours): """(int) -> int Return the number of seconds there are in num_hours hours. >>> convert_to_minutes(2) 7200 """ minutes = convert_to_minutes(num_hours) seconds = minutes * 60 return seconds minutes = convert_to_minutes(2) seconds = convert_to_seconds(2)
x=3 if(x%2!=0) print("x is odd") else: print("x is invalid")
#https://www.interviewbit.com/problems/combinations/ def combinations(A,B): final_arr = [] combinationsUtil(A,B,1,0,[],final_arr) return final_arr def combinationsUtil(A,B,num,level,cur_list,final_arr): if level==B: final_arr.append(cur_list) return for i in xrange(num,A+1): temp_list = cur_list+[i] combinationsUtil(A,B,i+1,level+1,temp_list,final_arr) return print combinations(1,1)
def squareRoot(A): if A <= 1: return A start = 0 end = A while start <= end: mid = (start+end)/2 res = A/mid if res == mid: return mid if res < mid: end = mid-1 if res > mid: start = mid+1 return mid if mid*mid < A else mid-1 print squareRoot(226)
#https://www.interviewbit.com/problems/combination-sum-ii/ """ def combSumII(A,B): A.sort() print A final_result = [] combSumIIUtil(A,0,B,[],final_result) #combSumIIUtil(A,B,[],final_result) return final_result def combSumIIUtil(A,cur_sum,target,stri,final_result): #print "A:",A,"cur_sum:",cur_sum,"target:",target,"stri:",stri,"final_result:",final_result if len(A)==0: if cur_sum==target: final_result.append(stri) return if cur_sum+A[0] <= target: combSumIIUtil(A[1:],cur_sum+A[0],target,stri+[A[0]],final_result) low=temp=0 while temp < len(A) and A[temp] == A[low]: temp += 1 combSumIIUtil(A[temp:],cur_sum,target,stri,final_result) else: low=temp= 0 while temp < len(A) and A[temp] == A[low]: temp += 1 combSumIIUtil(A[temp:],cur_sum,target,stri,final_result) return A = [10,1,2,7,6,1,5] B = 8 A = [1, 1,2, 5, 6, 7, 10] #print combSumII(A,B) A = [ 8, 10, 6, 11, 1, 16, 8 ] B = 28 A = [1, 6, 8, 8, 10, 11, 16] #print combSumII(A,B) A = [ 17, 8, 17, 20, 20, 18, 14, 15, 20, 3 ] B = 14 A = [3, 8, 14, 15, 17, 17, 18, 20, 20, 20] #print combSumII(A,B) A = [ 15, 8, 15, 10, 19, 18, 10, 3, 11, 7, 17 ] B = 33 #print combSumII(A,B) A = [2,3,6,7] B = 7 print combSumII(A,B) """ def combinationSum(A,B): A.sort() final_arr = [] combinationSumUtility(A,0,0,B,[],final_arr) return final_arr def combinationSumUtility(A,index,sumi,target,stri,final_arr): if sumi == target: final_arr.append(stri) return if index >= len(A): return if sumi+A[index] <= target: combinationSumUtility(A,index+1,sumi+A[index],target,stri+[A[index]],final_arr) temp = index while temp < len(A) and A[temp] == A[index]: temp += 1 combinationSumUtility(A,temp,sumi,target,stri,final_arr) return A = [10,1,2,7,6,1,5] B = 8 print combinationSum(A,B)
#https://www.interviewbit.com/problems/counting-triangles/ #Find all possible triangle def greatersum(A): n = len(A) if n < 3: return 0 A.sort() #Below approach is based on the fact that for A<=B<=C, to be a valid triangle #Following condition must be true, A+B > C count = 0 low = 0 high = n-1 while high > 1: count += sumGreaterthank(A[:high],A[high]) high -= 1 return count #Count the number of pairs with sum greater than k def sumGreaterthank(A,k): low = 0 high = len(A)-1 count = 0 while low < high: if A[low]+A[high] > k: count += high-low high -= 1 else: low += 1 return count A = [1,1,1,2,2] print greatersum(A) #print sumGreaterthank(A[:2],1)
#https://www.interviewbit.com/problems/nearest-smaller-element/ INF = 10**10 def nearestSmallerElem(A): stack = [] top = -1 G = [] for val in A: while top >= 0 and stack[top] >= val: stack.pop() top -= 1 if top == -1: G.append(-1) else: G.append(stack[top]) stack.append(val) top += 1 return G def nearestSmallerElem03(A): queue = [A[0]] G = [-1] front = 0 top = 0 for i in xrange(1,len(A)): while front < len(queue) and A[i] < queue[front]: front += 1 if front <= top: temp = top while temp >= front and queue[temp] >= A[i]: temp -= 1 if temp >= front: G.append(queue[temp]) else: G.append(-1) else: G.append(-1) queue.append(A[i]) top += 1 return G def nearestSmallerElem02(A): mini = INF stack = [] for i in xrange(len(A)): j = i-1 while j >= 0 and A[j]>=A[i]: j -= 1 if j >= 0 and A[j] < A[i]: stack.append(A[j]) else: stack.append(-1) return stack A = [4, 5, 2, 10, 8] #print nearestSmallerElem(A) A = [3, 2, 1] #print nearestSmallerElem(A) A = [ 34, 35, 27, 42, 5, 28, 39, 20, 28 ] #print A #print nearestSmallerElem(A) A = [ 39, 27, 11, 4, 24, 32, 32, 1 ] #print A #print nearestSmallerElem(A) A = [ 8, 23, 22, 16, 22, 7, 7, 27, 35, 27, 32, 20, 5, 1, 35, 28, 20, 6, 16, 26, 48, 34 ] print A print nearestSmallerElem(A)
#https://www.interviewbit.com/problems/sorted-permutation-rank/ def sortedPermRank(A): strLookup = sorted(list(A)) n = len(A) print strLookup,n rank = i = 0 lookup = [] while i < n: x = strLookup.index(A[i]) minus = 0 print "lookup:",lookup, for j in lookup: if j < x: minus += 1 print "A[i]:",A[i],"Index:",x,"minus:",minus, lookup.append(x) x -= minus y = factorial(n-i-1) print "x:",x,"n-i-1:",n-i-1,"y:",y rank += x*y i += 1 return (rank+1)%1000003 def factorial(B): mult = 1 while B: mult *= B B -= 1 return mult #print sortedPermRank('Utkarsh') #print factorial(20) print sortedPermRank("DTNGJPURFHYEW") #print factorial(11)
def primeSum02(A): if A%2!=0: return i = 2 while i <= A/2: if prime02(i) and prime02(A-i): return i,A-i i += 1 return def prime02(x): if x<2: return False if x==2: return True if x%2==0: return False p = 3 while p*p <= x: if x%p==0: return False p += 2 return True def primeSum(A): if A%2!=0: return lookup = [2] i = 3 while i<A: if prime(i,lookup): lookup.append(i) i += 2 print lookup new_lookup = set(lookup) for i in lookup: if A-i in new_lookup: return i,A-i return def prime(x,lookup): sqrt = int(x**(0.5)) i,temp = 0,lookup n = len(temp) while i < n and temp[i] <= sqrt: if x%temp[i]==0: return False i += 1 return True def primeSieve(N): prime = [True for i in range(N+1)] p = 2 while p*p <= N: if prime[p]==True: #Update all multiples of p, starting from 2nd multiple for i in range(p*2,N+1,p): prime[i] = False p += 1 if prime[2]==True and prime[N-2]==True: return 2,N-2 for p in xrange(3,N,2): if prime[p]==True and prime[N-p]==True: return p,N-p return """ print primeSum(16) #print primeSum(10**10+16) print primeSum(378) print primeSum(4) print primeSum(1000) #print primeSum(1048574) #print primeSum(16777214) print primeSieve(10) print primeSieve(16777214) """ print primeSum02(16777214) print primeSum02(378) print primeSum02(4) print primeSum02(12)
def mergeIntervals(A,B): n = len(A) temp = [[A[i],B[i]] for i in range(n)] temp = sorted(temp,key=lambda item:item[0],reverse=True) print temp stack = [] while len(temp)>1: top1 = temp.pop() top2 = temp.pop() if top2[0] < top1[1]: top1[1] = max(top1[1],top2[1]) temp.append(top1) else: stack.append(top1) temp.append(top2) print stack print temp A = [6,1,2,4] B = [8,9,4,7] A = [1,3,8] B = [2,6,10] mergeIntervals(A,B)
#[?] 1부터 1,000까지의 정수 중 13의 배수의 갯수(건수, 횟수) # 갯수 알고리즘(Count Algorithm) : 주어진 범위에 주어진 조건에 해당하는 자료들의 갯수 #[1] Input count = 0 # 갯수를 저장할 변수를 0으로 초기화 #[2] Process : 갯수 알고리즘의 영역 -> 주어진 범위에 주어진 조건(필터링) for i in range(1,1000): #주어진 범위 if i % 13 == 0: #주어진 조건: 13의 배수면 갯수를 증가 # count = count + 1 count += 1 #count 변수 #[3] Output print(f'1부터 1,000까지의 정수 중 13의 배수의 개수 : {count}')
""" A convenience log function, behaves similar to print() """ from logging import getLogger def log(*args, level="info", name=None): # TODO basic logger formatting logger = getLogger(name=name) message = " ".join([str(a) for a in args]) level = level.lower() if level == "exception" or level == "error": logger.exception(message) elif level == "warning": logger.warning(message) elif level == "info": logger.info(message) elif level == "debug": logger.debug(message) else: raise TypeError( "level must be one of 'debug', 'info', 'warning', 'error', or 'exception' (case insensitive)" ) def get_log_func(name, level="info"): def _log(*args, level=level): log(*args, name=name, level=level) return _log
import sqlite3 #import os from sqlite3 import Error '''the function below called create_connection() returns a Connection object which represents an SQLite3 database specified by the database file parameter db_file.''' def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return conn def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) def main(): #change the path you want to place the database in your computer # db = r"C:\Users\Che\Desktop\ProjectPBD\TOGIT0817\vent\StreamingCatalogSystem.db" #db = r"C:\Users\murta\OneDrive\Documents\GitHub\StreamingApplication\StreamingCatalogSystem.db" db = r"E:\Conestoga\PythonForBigData\Project_code_git\StreamingCatalogSystem.db" sql_person_table = """CREATE TABLE IF NOT EXISTS Person ( PersonID INTEGER PRIMARY KEY, FirstName TEXT NOT NULL, LastName TEXT NOT NULL, EMAIL TEXT NOT NULL, USER_ID TEXT NOT NULL, Password TEXT NOT NULL, Access_Count INTEGER DEFAULT 0 );""" sql_AdminLogin_table = """CREATE TABLE IF NOT EXISTS AdminLogin ( UserId INTEGER PRIMARY KEY, USER_ID TEXT NOT NULL, Password TEXT NOT NULL, Access_Count INTEGER DEFAULT 0, FOREIGN KEY (USER_ID) REFERENCES Person (USER_ID) );""" sql_UserLogin_table = """CREATE TABLE IF NOT EXISTS UserLogin ( UserId INTEGER PRIMARY KEY, USER_ID TEXT NOT NULL, Password TEXT NOT NULL, Access_Count INTEGER DEFAULT 0, FOREIGN KEY (USER_ID) REFERENCES Person (USER_ID) );""" sql_Artist_table = """CREATE TABLE IF NOT EXISTS Artist ( ArtistID INTEGER PRIMARY KEY, Artist_Name TEXT );""" sql_Genre_table = """CREATE TABLE IF NOT EXISTS Genre ( GenreId INTEGER PRIMARY KEY, Genre_Type TEXT );""" sql_Movies_table = """CREATE TABLE IF NOT EXISTS Movies ( Movie_ID INTEGER PRIMARY KEY, Title TEXT, Artist_Name TEXT, ReleasedDate INTEGER, Duration TEXT, Genre_Type INTEGER, MovieLikes INTEGER DEFAULT 0, FOREIGN KEY (Artist_Name) REFERENCES Artist (Artist_Name) FOREIGN KEY (Genre_Type) REFERENCES Genre (Genre_Type) );""" sql_Series_table = """CREATE TABLE IF NOT EXISTS Series ( Series_ID INTEGER PRIMARY KEY, Title TEXT, Artist_Name TEXT, ReleasedDate INTEGER, NumSeason INTEGER, NumEpisode INTEGER, Genre_Type INTEGER, SeriesLikes INTEGER DEFAULT 0, FOREIGN KEY (Genre_Type) REFERENCES Genre (Genre_Type) FOREIGN KEY (Artist_Name) REFERENCES Artist (Artist_Name) );""" sql_Logs_table = """CREATE TABLE IF NOT EXISTS Logs ( LogId INTEGER PRIMARY KEY, USER_ID TEXT, Movie_ID INTEGER, WatchedTime DateTime, FOREIGN KEY (USER_ID) REFERENCES Person (USER_ID) FOREIGN KEY (Movie_ID) REFERENCES Movies (Movie_ID) );""" # create a database connection conn = create_connection(db) # create tables if conn is not None: # create person table create_table(conn, sql_person_table) # create admin table create_table(conn, sql_AdminLogin_table) # create user table create_table(conn, sql_UserLogin_table) # create artist table create_table(conn, sql_Artist_table) # create genre table create_table(conn, sql_Genre_table) # create movies table create_table(conn, sql_Movies_table) # create series table create_table(conn, sql_Series_table) # create logs table create_table(conn, sql_Logs_table) else: print("Error! cannot create the database connection.") if __name__ == '__main__': main()
from pyspark import SparkContext from numpy import array from pyspark.mllib.clustering import KMeans, KMeansModel ############################################ #### PLEASE USE THE GIVEN PARAMETERS ### #### FOR TRAINING YOUR KMEANS CLUSTERING ### #### MODEL ### ############################################ NUM_CLUSTERS = 4 SEED = 0 MAX_ITERATIONS = 100 INITIALIZATION_MODE = "random" sc = SparkContext() def get_clusters(data_rdd, num_clusters=NUM_CLUSTERS, max_iterations=MAX_ITERATIONS, initialization_mode=INITIALIZATION_MODE, seed=SEED): # TODO: # Use the given data and the cluster pparameters to train a K-Means model # Find the cluster id corresponding to data point (a car) # Return a list of lists of the titles which belong to the same cluster # For example, if the output is [["Mercedes", "Audi"], ["Honda", "Hyundai"]] # Then "Mercedes" and "Audi" should have the same cluster id, and "Honda" and # "Hyundai" should have the same cluster id # Segregate the data into titles and points #titles = [] #points = [] #for x in data_rdd.collect(): # titles.append(x[0]) # points.append(x[1:]) # Convert lists to RDD #titles_rdd = sc.parallelize(titles) #points_rdd = sc.parallelize(points) titles_rdd = data_rdd.map(lambda x: x[0]) points_rdd = data_rdd.map(lambda x: x[1:]) #for x in points_rdd.collect(): # print(x) # Build the model (cluster the data) clusters = KMeans.train( points_rdd, num_clusters, maxIterations=max_iterations, initializationMode=initialization_mode, seed=seed) # Identify which cluster does each point belong to, and map it to respective titles cluster = clusters.predict(points_rdd).zip(titles_rdd).collect() #print(cluster) # Group the titles of each clusters and aggregate the titles from collections import defaultdict res = defaultdict(list) for k, v in cluster: res[k].append(v) result = [v for k,v in res.items()] #print(result) #new_rdd.filter(lambda r: r[1] == value).collect() #.filter(lambda x: x[1] in rownums).map(lambda x: x[0]) #.toDF('cluster', 'title') #print(result_df) #for x in predict_rdd.collect(): # print(x) return result if __name__ == "__main__": f = sc.textFile("dataset/cars.data") # TODO: Parse data from file into an RDD data_rdd = f.map(lambda line: line.split(",")) #for x in data_rdd.collect(): # print(x[0]) # print(x[1:]) clusters = get_clusters(data_rdd) for cluster in clusters: print(','.join(cluster))
#!/usr/bin/python3 user_input = float(input("Enter Number: ")) if user_input > 100: print("Greater") elif user_input == 100: print("Is the same") else: print("Smaller")
# DEFINIZIONE DELLA FUNZIONE CHE CONTROLLA CHE I DUE NUMERI # SIANO COMPRESI FRA DUE ESTREMI DATI # estremo1 => estremo inferiore # estremo2 => estremo superiore def verifica(estremo1,estremo2): numero = int(input("Inserire un numero da " + str(estremo1) + " a " + str(estremo2) + ": ")) while(numero < estremo1 or numero > estremo2): numero = int(input("Hai inserito un numero non valido. Inserisci un numero fra " + str(estremo1) + " e " + str(estremo2) + ": ")) return numero # CHIAMATA DELLA FUNZIONE "verifica" per tre differenti estremi numero1 = verifica(0,10) numero2 = verifica(20,30) numero3 = verifica(40,50) if(numero1%2 == 0 and numero2%2 == 0 and numero3%2 == 0): print("Il prodotto dei numeri immessi è: " + str(numero1 * numero2 * numero3)) else: print("I numeri non sono entrambi pari")
# Esercizio_1 somma_pari = 0 somma_dispari = 0 numero = 0 risposta = str(input("Vuoi inserire un numero? ")) while(risposta == "si"): numero = int(input("Inserisci un numero intero: ")) if numero % 2 == 0: somma_pari = somma_pari + numero else: somma_dispari = somma_dispari + numero risposta = str(input("Vuoi inserire un altro numero: ")) print("La somma dei numeri pari e': " , somma_pari) print("La somma dei numeri dispari e': " , somma_dispari)
from queue import Queue from threading import Thread def loop(fn, input, output) -> None: while True: work = input.get() if work: output.put(fn(work)) input.task_done() if not work: break class ThreadPool(object): def __init__(self, target, num_threads=10): self._pending = 0 # definitely not thread-safe self._threads = [] self._input = Queue() # thread-safe self._output = Queue() # thread-safe for i in range(0, num_threads): t = Thread(target=loop, args=(target, self._input, self._output)) t.start() self._threads.append(t) def __iter__(self): return self def __next__(self): if not self._pending: raise StopIteration self._pending -= 1 return self._output.get() def join(self): for x in range(0, len(self._threads)): self._input.put(None) self._input.join() for t in self._threads: t.join() def submit(self, work): self._pending += 1 self._input.put(work)
def encrypt_messege(messege, x): e_messege = "" if type(x) != int: raise ValueError() for l in messege: e_messege += chr(ord(l)+x)#(Char value of l) + x return e_messege #print encrypt_messege("Meeting at 5PM tomorrow.", 6) def left_aligned_triangle(): hight = int(raw_input("Enter hight: ")) for i in range(1,hight+1): print "*"*i #left_aligned_triangle() def right_aligned_triangle(): hight = int(raw_input("Enter hight: ")) for i in range(1,hight+1): print " "*(hight-i) + "*"*(i) #right_aligned_triangle() def diamond(): hight = int(raw_input("Enter hight: ")) for i in range(1,hight+1): print "*"*i + (" "*(hight-i) + "*"*(i)) #diamond() def moby_ave_index(c): moby = '''Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off - then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me.''' indi = 0.0 occ = 0.0 length = len(moby) for index in range(length): if c == moby[index]: indi += index occ += 1.0 if occ == 0: retrurn False return (indi/occ)/length print moby_ave_index('.')
#!/usr/bin/env python3 def parse(line): # 1-3 b: cdefg parts = line.split() # 000 11 22222 p_count = tuple(map(int, parts[0].split("-"))) p_char = parts[1][0] # drop colon password = parts[2] # (1,3), 'b', 'cdefg' return p_count, p_char, password def checkpass(p_count, p_char, password): """checks count of instances of p_char in password vs constraints""" return p_count[0] <= password.count(p_char) <= p_count[1] def checkpass2(p_count, p_char, password): """checks password characters at indexes p_count contain p_char only once""" # password is 1-indexed targets = (password[p_count[0] - 1], password[p_count[1] - 1]) return targets.count(p_char) == 1 with open("input2") as fp: lines = [parse(line.strip()) for line in fp.readlines()] def part1(): return len([1 for line in lines if checkpass(*line)]) def part2(): return len([1 for line in lines if checkpass2(*line)]) print("#1", part1()) print("#2", part2()) # sample = """\ # 1-3 a: abcde # 1-3 b: cdefg # 2-9 c: ccccccccc # """.splitlines() # print("#sample", sum([1 if checkpass(*parse(line)) else 0 for line in sample])) # print("#sample2", sum([1 if checkpass2(*parse(line)) else 0 for line in sample]))
# Do not change these lines friend1 = "Mary" friend2 = "Mohammad" friend3 = "Mike" friends = [] # Add your code below... # 1) Use the appropriate List method to add the # three friends names to the 'friends' List friends.append(friend1) friends.append(friend2) friends.append(friend3) # print( friends ) # 2) Use the for loop to print the values of 'friends' # one by one for value in friends: print( value )
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ n = len(nums) for i in range(n): for j in range(i+1, n): if nums[i] + nums[j] == target: return [i, j] def twoSum2(self, nums, target): num_map = {} for i in range(len(nums)): if (target - nums[i]) in num_map.keys(): return [num_map[target-nums[i]], i] else: num_map[nums[i]] = i s = Solution() print s.twoSum([2, 7, 11, 15], 9) print s.twoSum2([2, 7, 11, 15], 9)
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ # just quick sort nums.sort() for i in range(len(nums)-1): if nums[i] == nums[i+1]: return nums[i] def findDuplicate2(self, nums): # O(n) version n = len(nums)-1 found = 0 for i in range(len(nums)): if nums[i] > 2*n: return i elif nums[i] <= n: nums[nums[i]] += n else: nums[nums[i] - n] += n for i in range(len(nums)): if nums[i] > 2*n: return i s = Solution() import pdb pdb.set_trace() print s.findDuplicate2([1, 3, 4, 2, 2]) print s.findDuplicate2([1, 2, 3, 3, 4])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ dups = [] n = len(nums) for val in nums: nums[(val - 1) % n] += n for (idx, val) in enumerate(nums): if val > 2 * n: dups.append(idx + 1) return dups s = Solution() print(s.findDuplicates([4, 3, 2, 7, 8, 2, 3, 1]))
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ s_map = {} t_map = {} for c in s: cnt = s_map.get(c, 0) s_map[c] = cnt+1 for c in t: cnt = t_map.get(c, 0) t_map[c] = cnt+1 return self._check(s_map, t_map) and self._check(t_map, s_map) def _check(self, map1, map2): for key in map1.keys(): if not map2.has_key(key): return False if map2[key] != map1[key]: return False return True s = Solution() print s.isAnagram("a", "ab") print s.isAnagram("anagram", "naagram") print s.isAnagram("rat", "car")
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def rotate(self, matrix): if not matrix: return None n = len(matrix) ans = [[0] * n for _ in range(n)] for i in range(n-1, -1, -1): row = matrix[i] for j in range(n): col = n-1-i ans[j][col] = row[j] for i in range(n): for j in range(n): matrix[i][j] = ans[i][j] def rotate2(self, matrix): ''' in place version ''' if not matrix: return None n = len(matrix) matrix.reverse() for i in range(0, n): for j in range(i, n): tmp = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = tmp print matrix s = Solution() matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] s.rotate2(matrix)
#!/usr/bin/env python # -*- coding: utf-8 -*- import math class Solution(object): def bulbSwitch_tle(self, n): tot = 0 for x in range(1, n+1): cnt = 0 i = 1 while i*i <= x: if x % i == 0: cnt += 2 if x/i != i else 1 i += 1 tot += 1 if cnt%2 == 1 else 0 return tot def bulbSwitch(self, n): return int(math.sqrt(n)) s = Solution() import pdb pdb.set_trace() print s.bulbSwitch(3) print s.bulbSwitch(6) print s.bulbSwitch(1)
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def maxArea(self, height): n = len(height) if n <= 1: return 0 i, j = 0, n-1 maxW = 0 while i < j: h = min(height[i], height[j]) maxW = max(maxW, (j-i)*h) while height[i]<=h and i < j: i+=1 while height[j]<=h and i < j: j-=1 return maxW s = Solution() print s.maxArea([3, 5, 2, 6, 5])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ tot = self.count(head) if tot == n: head = head.next return head cur = head for _ in range(tot - n % tot - 1): cur = cur.next if cur.next: cur.next = cur.next.next else: head = None return head def count(self, head): cnt = 0 while head.next: cnt += 1 head = head.next return cnt def removeNthFromEnd2(self, head, n): # much elegant solution ptr1, ptr2 = head, head while n: ptr2 = ptr2.next n -= 1 if not ptr2: return head.next ptr2 = ptr2.next while ptr2: ptr1 = ptr1.next ptr2 = ptr2.next ptr1.next = ptr1.next.next return head s = Solution() a1 = ListNode(1) a2 = ListNode(2) a3 = ListNode(3) a4 = ListNode(4) a5 = ListNode(5) a1.next = a2 a2.next = a3 a3.next = a4 a4.next = a5 def print_list(a): ret = "" while a: ret += str(a.val) + " " a = a.next return ret print(print_list(s.removeNthFromEnd2(a1, 2)))
#!/usr/bin/env python # -*- coding : utf-8 -*- class Solution(object): def minimumTotal(self, triangle): """ :type triangle: List[List[int]] :rtype: int """ n = len(triangle) if n == 0: return 0 if n == 1: return triangle[0][0] dp = triangle[-1][:] for i in range(n-2, -1, -1): arr = triangle[i] for j in range(len(arr)): dp[j] = min(arr[j]+dp[j], arr[j]+dp[j+1]) return dp[0] s = Solution() print s.minimumTotal([ [2], [3,4], [6,5,7], [4,1,8,3] ])
import torch import torchvision from torchvision.datasets import MNIST # Download training dataset dataset = MNIST(root='data/', download=True) len(dataset) #The dataset has 60,000 images which can be used to train the model. #There is also an additonal test set of 10,000 images which can be created by passing train=False #to the MNIST class test_dataset = MNIST(root='data/', train=False) len(test_dataset) dataset[0] import matplotlib.pyplot as plt image, label = dataset[0] plt.imshow(image, cmap='gray') print('Label:', label) image, label = dataset[10] plt.imshow(image, cmap='gray') print('Label:', label) import torchvision.transforms as transforms # MNIST dataset (images and labels) dataset = MNIST(root='data/', train=True, transform=transforms.ToTensor()) img_tensor, label = dataset[0] print(img_tensor.shape, label) print(img_tensor[:,10:15,10:15]) print(torch.max(img_tensor), torch.min(img_tensor)) # Plot the image by passing in the 28x28 matrix plt.imshow(img_tensor[0,10:15,10:15], cmap='gray'); #Training set - used to train the model i.e. compute the loss and adjust the weights of the model using gradient descent. #Validation set - used to evaluate the model while training, adjust hyperparameters (learning rate etc.) and pick the best version of the model. #Test set - used to compare different models, or different types of modeling approaches, and report the final accuracy of the model. from torch.utils.data import random_split train_ds, val_ds = random_split(dataset, [50000, 10000]) len(train_ds), len(val_ds) from torch.utils.data import DataLoader batch_size = 128 train_loader = DataLoader(train_ds, batch_size, shuffle=True) val_loader = DataLoader(val_ds, batch_size) #Model import torch.nn as nn input_size = 28*28 num_classes = 10 # Logistic regression model model = nn.Linear(input_size, num_classes) print(model.weight.shape) model.weight print(model.bias.shape) model.bias for images, labels in train_loader: print(labels) print(images.shape) outputs = model(images) break #This leads to an error, because our input data does not have the right shape. Our images are of the shape 1x28x28, but we need them to be vectors of size 784 i.e. we need to flatten them out. We'll use the .reshape method of a tensor, which will allow us to efficiently 'view' each image as a flat vector, without really chaging the underlying data. #To include this additional functionality within our model, we need to define a custom model, by extending the nn.Module class from PyTorch. class MnistModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(input_size, num_classes) def forward(self, xb): xb = xb.reshape(-1, 784) out = self.linear(xb) return out model = MnistModel() print(model.linear.weight.shape, model.linear.bias.shape) list(model.parameters()) for images, labels in train_loader: outputs = model(images) break print('outputs.shape : ', outputs.shape) print('Sample outputs :\n', outputs[:2].data) #Softmax Function import torch.nn.functional as F # Apply softmax for each output row probs = F.softmax(outputs, dim=1) # Look at sample probabilities print("Sample probabilities:\n", probs[:2].data) # Add up the probabilities of an output row print("Sum: ", torch.sum(probs[0]).item()) max_probs, preds = torch.max(probs, dim=1) print(preds) print(max_probs) labels #Now the preds and labels do not match. #Calculate accuracy def accuracy(outputs, labels): _, preds = torch.max(outputs, dim=1) return torch.tensor(torch.sum(preds == labels).item() / len(preds)) accuracy(outputs, labels) #Accuracy is good for humans #cROSS ENTROPY FOR classification loss_fn = F.cross_entropy # Loss for current batch of data loss = loss_fn(outputs, labels) print(loss) #Since the cross entropy is the negative logarithm of the predicted probability of the correct label averaged over all training samples, one way to interpret the resulting number e.g. 2.23 is look at e^-2.23 which is around 0.1 as the predicted probability of the correct label, on average. Lower the loss, better the model. class MnistModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(input_size, num_classes) def forward(self, xb): xb = xb.reshape(-1, 784) out = self.linear(xb) return out def training_step(self, batch): images, labels = batch out = self(images) # Generate predictions loss = F.cross_entropy(out, labels) # Calculate loss return loss def validation_step(self, batch): images, labels = batch out = self(images) # Generate predictions loss = F.cross_entropy(out, labels) # Calculate loss acc = accuracy(out, labels) # Calculate accuracy return {'val_loss': loss, 'val_acc': acc} def validation_epoch_end(self, outputs): batch_losses = [x['val_loss'] for x in outputs] epoch_loss = torch.stack(batch_losses).mean() # Combine losses batch_accs = [x['val_acc'] for x in outputs] epoch_acc = torch.stack(batch_accs).mean() # Combine accuracies return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()} def epoch_end(self, epoch, result): print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format(epoch, result['val_loss'], result['val_acc'])) model = MnistModel() def evaluate(model, val_loader): outputs = [model.validation_step(batch) for batch in val_loader] return model.validation_epoch_end(outputs) def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD): history = [] optimizer = opt_func(model.parameters(), lr) for epoch in range(epochs): # Training Phase for batch in train_loader: loss = model.training_step(batch) loss.backward() optimizer.step() optimizer.zero_grad() # Validation phase result = evaluate(model, val_loader) model.epoch_end(epoch, result) history.append(result) return history result0 = evaluate(model, val_loader) result0 history1 = fit(5, 0.001, model, train_loader, val_loader) history2 = fit(5, 0.001, model, train_loader, val_loader) history3 = fit(5, 0.001, model, train_loader, val_loader) history4 = fit(5, 0.001, model, train_loader, val_loader) history5 = fit(5, 0.001, model, train_loader, val_loader) # Replace these values with your results history = [result0] + history1 + history2 + history3 + history4 + history5 accuracies = [result['val_acc'] for result in history] plt.plot(accuracies, '-x') plt.xlabel('epoch') plt.ylabel('accuracy') plt.title('Accuracy vs. No. of epochs'); # Define test dataset test_dataset = MNIST(root='data/', train=False, transform=transforms.ToTensor()) img, label = test_dataset[0] plt.imshow(img[0], cmap='gray') print('Shape:', img.shape) print('Label:', label) img.unsqueeze(0).shape def predict_image(img, model): xb = img.unsqueeze(0) yb = model(xb) _, preds = torch.max(yb, dim=1) return preds[0].item() img, label = test_dataset[0] plt.imshow(img[0], cmap='gray') print('Label:', label, ', Predicted:', predict_image(img, model)) img, label = test_dataset[10] plt.imshow(img[0], cmap='gray') print('Label:', label, ', Predicted:', predict_image(img, model)) img, label = test_dataset[193] plt.imshow(img[0], cmap='gray') print('Label:', label, ', Predicted:', predict_image(img, model)) # LAbel 2 predicted 8 img, label = test_dataset[1839] plt.imshow(img[0], cmap='gray') print('Label:', label, ', Predicted:', predict_image(img, model)) test_loader = DataLoader(test_dataset, batch_size=256) result = evaluate(model, test_loader) result
def calculObj(data, function1, function2) : """ Calcul des fonctions objectifs pour chaque observation data -> vecteurs d'entrée function1, function2 -> fonctions objectifs à minimiser return : même dataframe avec valeurs des fonctions objectifs pour chaque observation """ x1 = data['x1'] x2 = data['x2'] f1 = list() f2 = list() for i, j in zip(x1, x2) : f1.append(function1(i, j)) f2.append(function2(i, j)) data['f1'] = f1 data['f2'] = f2 return data
import argparse import sys import time class LetterNode(): __slots__ = ('children', 'val', 'isEndValue') def __init__(self, val, isEndValue, children): """Creates a new LetterNode val -- The letter in this node isEndValue -- Bool determining if a word ends at this node children -- A list of child letter nodes """ self.val = val self.isEndValue = isEndValue self.children = children class Configuration(): """Represents a 'swipe' on the board. A valid configuration is either an english word or the beginning of one. """ __slots__ = ('position', 'blocks', 'word', 'parent') def __init__(self, position, blocks, word, parent=None): """Creates a new configuration position -- The index of the current tile, that is the last one in a 'swipe' blocks -- A list of all blocks from the board. Blocks that are already in use for this configuration have a value of None word -- The word built by this configurations 'swipe' parent -- The config that led to this one. This allows for tracing a 'swipe' back to the start (Default None) """ self.position = position self.blocks = blocks self.word = word self.parent = parent def __cmp__(self, other): pass def isValid(self, wordTree): """Determines if this configuration is valid. Validity Rules: - No block can be used twice - A block ending with '-' can only be the first block in a word - A block beginning with '-' can only the last block in a word - The blocks must make up a word in the word tree, or must be the beginning of a word in the word tree wordTree -- A tree representing all valid words """ length = len(self.word) for i, block in enumerate(self.word): if block is None: #The same block was used twice return False if i != 0 and block.endswith("-"): #A block ending with a '-' must be the first block in a word return False elif i != length-1 and block.startswith("-"): #A block beginning with '-' must be the last block in a word return False #Turn the blocks into a string wholeWord = "".join(self.word).replace("-", "") current = wordTree for character in wholeWord: if character in current: current = current[character].children else: return False return True def isWord(self, wordTree): """Determines if the configuration represents an english word wordTree -- A tree representing all valid words """ wholeWord = "".join(self.word).replace("-", "") current = wordTree length = len(wholeWord) - 1 for i, character in enumerate(wholeWord): if i == length: if(character in current): return current[character].isEndValue else: return False if character in current: current = current[character].children else: return False def getDescendents(self, board): """Returns a list of configurations that descend from this one. Descendents represent continuing the swipe to an adjacent block. board -- The board this onfig is on """ neighborPositions = [] #top middle if self.position >= board.width: neighborPositions += [self.position - board.width] #bottom middle if self.position < (board.height - 1) * board.width: neighborPositions += [self.position + board.width] #left if self.position % board.width != 0: neighborPositions += [self.position - 1] #top left if self.position >= board.width: neighborPositions += [self.position - board.width - 1] #bottom left if self.position < (board.height - 1) * board.width: neighborPositions += [self.position + board.width - 1] #right if self.position % board.width != board.width - 1: neighborPositions += [self.position + 1] #top right if self.position >= board.width: neighborPositions += [self.position - board.width + 1] #bottom right if self.position < (board.height - 1) * board.width: neighborPositions += [self.position + board.width + 1] descendents = [] for position in neighborPositions: blocksCopy = self.blocks[:] blocksCopy[position] = None if self.blocks[position] is not None: for grouping in self.blocks[position].split('/'): #Allows for alternate letters separated by the '/' character newConfig = Configuration(position, blocksCopy, self.word + [grouping], parent = self) descendents += [newConfig] return descendents class Board(): __slots__ = ('blocks', 'width', 'height') _MAX_LETTER_WIDTH = 3 def __init__(self, blocks, width, height): """Creates a new board blocks -- A list of blocks from the board ordered from left to right, top to bottom. In many cases a block is a single letter, but it can also be a combination of symbols representing special rules for the block width -- The width of the board height -- Theh height of the board """ self.blocks = blocks self.width = width self.height = height def __str__(self): """ Returns a string representation of the baord """ result = "" for row in range(self.height): for col in range(self.width): block = self.blocks[row * self.width + col] result += format(block, '^' + str(Board._MAX_LETTER_WIDTH)) result += '\n' return result def solve(self, wordTree): """Returns a list of words that this board contains wordTree -- A tree representing all words """ foundWords = [] for blockPosition in range(len(self.blocks)): adjustedBlocks = self.blocks[:] adjustedBlocks[blockPosition] = None #Mark off the current letter as used newConfig = Configuration(blockPosition, adjustedBlocks, [self.blocks[blockPosition]]) possibilities = [newConfig] while possibilities: currentConfig = possibilities.pop(0) if not currentConfig.isValid(wordTree): continue possibilities += currentConfig.getDescendents(self) if currentConfig.isWord(wordTree) and "".join(currentConfig.word) not in foundWords: foundWords.append("".join(currentConfig.word)) return foundWords def populateWords(wordFile): """Return a word tree using the words from the provided file. wordFile -- The file to read """ root = {} for word in open(wordFile): currentPos = root length = len(word.strip()) - 1 for i, character in enumerate(word.strip()): if character in currentPos: if i == length: currentPos[character].isEndValue = True currentPos = currentPos[character].children else: newNode = LetterNode(character, i == length, {}) currentPos[character] = newNode currentPos = newNode.children return root def printWordTree(words): for key in words.keys(): print(key + ": ", end="") _printWordTreeHelper(words[key].children) print() print() def _printWordTreeHelper(root): if root: for key in root.keys(): print('{' + key + ": ", end="") _printWordTreeHelper(root[key].children) print(", ", end="") print('}', end="") else: print("{}", end="") def isValidDimension(value): """Determines if the value provided is a valid board dimension. Throws an argparse.ArgumentTypeError if the argument is not an integer and greater than zero. value -- The value being checked """ try: i = int(value) if i <= 0: raise ValueError() return i except ValueError: raise argparse.ArgumentTypeError("%s is not an integer greater than zero" % value) def main(): parser = argparse.ArgumentParser(description="Finds words on provided board") parser.add_argument('width', type=isValidDimension, help="the width of the board") parser.add_argument('height', type=isValidDimension, help="the height of the board") parser.add_argument('blocks', help="the blocks on the board from left to right, top to bottom. These should be comma delimited with no spaces") #parser.add_argument('form', choices=['list','grids']) parser.add_argument('--count', dest='count', type=int, default=100) parser.add_argument('--sort', dest='sort', choices=['largest','smallest','none'], default='largest') parser.add_argument('--words', dest='words', default='wordsEn.txt', help="name of the file that contains a list of words to look for") parser.add_argument('--interactive', dest='interactive', default=False, action='store_true', help="determines if the program should dump out text or step through interactively") args = parser.parse_args() blocks = args.blocks.split(',') b = Board(blocks, args.width, args.height) words = populateWords(args.words) solution = b.solve(words) if args.sort == 'largest': solution.sort(key=len, reverse=True) elif args.sort == 'smallest': solution.sort(key=len) printed_count = 0 incorrect = set() if args.interactive: print("Press enter to advance") for word in solution: if printed_count >= args.count and args.count >= 0: break sys.stdout.write(word + "\n") printed_count += 1 if args.interactive and printed_count != 0: #user_input = input("enter to continue (q to quit, x to mark word as incorrect)") #if user_input == 'q': # break #if user_input == 'x': # incorrect.add(word) while True: line = sys.stdin.readline() sys.stdin.write("\r") sys.stdin.flush() sys.stdout.write("\r") sys.stdout.flush() break if __name__ == "__main__": main()