text
stringlengths
37
1.41M
import cv2 import matplotlib.pyplot as plt import numpy as np #programa coordenada de bordes funciona y investigar como funciona tanto filtro #https://bretahajek.com/2017/01/scanning-documents-photos-opencv/ imagen = cv2.imread("papel.jpg") rows, cols, channel = imagen.shape print([rows,cols]) #img = np.resize( img, (img.shape[0]//10, img.shape[1]//10) ) def resizes(imagen,rows,cols): return cv2.resize(imagen,(cols//2, rows//2)) # convert to grayscale if rows > 800 and cols > 700: color_img = cv2.resize(imagen, (imagen.shape[1]//2,imagen.shape[0]//2)) else : color_img = imagen.copy() #color_img = resize(img) img = cv2.cvtColor(color_img, cv2.COLOR_RGB2GRAY) rows, cols = img.shape print([rows,cols]) # bilateral filter preserv edges img2 = cv2.bilateralFilter(img,4,25,40,borderType = cv2.BORDER_CONSTANT) cv2.imshow("bilateral filter",img2) #Create black and white image based on adaptive threshold #img2 = cv2.equalizeHist(img) ##cv2.imshow("equalizeHist",img2) img2 = cv2.adaptiveThreshold(img2, 255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 61,7) cv2.imshow("adaptiveThe",img2) #Median filter clears small details #img2 = cv2.medianBlur(img2,11) ##cv2.imshow("medianBlur",img2) #add black border in case that page is touching an image border img2 = cv2.copyMakeBorder(img2,5,5,5,5,cv2.BORDER_CONSTANT, value= [0,0,0]) ##cv2.imshow("copyMkaeBoder",img2) edges = cv2.Canny(img2,150,200) cv2.waitKey(0) cv2.destroyAllWindows() #getting contours contours, hierarchy = cv2.findContours(edges , cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) height = edges.shape[0] width = edges.shape[1] MAX_COUNTOUR_AREA = (width- 10) * (height - 10 ) maxAreaFound = MAX_COUNTOUR_AREA * 0.25 pageContour = np.array([[[5,5]], [[5,height-5]],[[width-5, height-5]],[[width-5,5]]]) print([MAX_COUNTOUR_AREA, maxAreaFound]) for cnt in contours: perimeter = cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt, 0.03 * perimeter, True) if len(approx) == 4 and cv2.isContourConvex(approx): #print(cv2.contourArea(approx)) inprimir el area de cuadrados generados por findContou.. if maxAreaFound < cv2.contourArea(approx) and cv2.contourArea(approx) < MAX_COUNTOUR_AREA : maxAreaFound = cv2.contourArea(approx) pageContour = approx print("------------------------------------------------") print(pageContour) color = (255, 0, 0) for pnt in pageContour: print(pnt) cv2.circle(color_img,(pnt[0,0],pnt[0,1]),10,color) plt.subplot(121),plt.imshow(cv2.cvtColor(color_img, cv2.COLOR_RGB2BGR) ),plt.title("input") plt.subplot(122),plt.imshow(cv2.cvtColor(edges, cv2.COLOR_RGB2BGR)),plt.title("bilateral") plt.show() #print(pageContour) print("llllllllllllllllllllllllllllllllllll") def fourCornersSort(pts): diff = np.diff(pts, axis=1) summ = pts.sum(axis=1) return np.array([pts[np.argmin(summ)],pts[np.argmax(diff)],pts[np.argmax(summ)],pts[np.argmin(diff)]]) def contourOffset(cnt,offset): cnt += offset cnt[cnt<0] = 0 return cnt pageContour = fourCornersSort(pageContour[:,0]) #print(pageContour) pageContour = contourOffset(pageContour,(-5,5)) #print(pageContour) sPoints = pageContour #sPoints = pageContour.dot(rows/ 800) esta linea va con el resize del principio height = max(np.linalg.norm(sPoints[0] - sPoints[1]),np.linalg.norm(sPoints[2] - sPoints[3])) width = max(np.linalg.norm(sPoints[1] - sPoints[2]),np.linalg.norm(sPoints[3] - sPoints[0])) #create target points tPoints = np.array([[0, 0], [0, height],[width, height],[width, 0]], np.float32) sPoints = np.float32(sPoints) #Wraping perspective #print(sPoints) #print(tPoints) #sPoints = 4*sPoints #tPoints = 4*tPoints #print(sPoints) #print(tPoints) for p in sPoints: print(p) cv2.circle(imagen,(int(p[0]*2),int(p[1]*2) ),10,color) cv2.imshow("imagen_real", imagen) cv2.waitKey(0) M= cv2.getPerspectiveTransform(sPoints,tPoints) newImage = cv2.warpPerspective(imagen,M,(int(width),int(height))) #cv2.imshow("salida_affinetrasform",newImage) #cv2.waitKey(0) #print(pageContour) #cv2.imwrite("edges.jpg", edges) #cv2.waitKey(0) #cv2.destroyAllWindows()
numbers = [5, 10, 7, 9] for i in range(len(numbers)): numbers[i] = pow(numbers[i],3) print("Original Numbers:", numbers) print("Min:", min(numbers)) print("Max:", max(numbers)) print("Sum:", sum(numbers)) print("Changed Numbers:", numbers)
""" 第三章 3-2 自行連接LED 從"machine"匯入"Pin"類別的方式 在第16腳接LED """ #從"machine"匯入"Pin"類別 from machine import Pin #匯入"time"模組才能執行sleep() import time #在16腳輸出高電位 led = Pin(16, Pin.OUT) #腳16輸出高電位(亮燈) led.value(1) #腳16輸出低電位(不亮燈) led.value(0) for i in range(3): led.value(0) time.sleep(0.5) led.value(1) time.sleep(0.5)
def RemoveVowels(str): if not str: return "" if str[0] in ['a','e','i','o','u','A','E','I','O','U']: return RemoveVowels(str[1:]) #it recursively looks at the rest of the string else : return str [0] + RemoveVowels(str[1:]) #it adds the character and recursively looks at the rest of the string print (RemoveVowels("beautiful")) #pseudocode #NOVOWELS(str): # If str is empty: # Return str #If str [0] in in ['a','e','i','o','u','A','E','I','O','U']: # Return RemoveVowels # Else: # Return str[0] + noVowels (str[1:]) # Str -> input string
from typing import List, Dict, Tuple, Union class Activities: def __init__(self): self.count = int(input()) self.activities = self.initialize_activities() self.cameron_calendar = [] self.jamie_calendar = [] def initialize_activities(self): activities = [[*[int(val) for val in input().split(" ")], i, None] for i in range(self.count)] sorted_by_time = sorted(activities, key=lambda x: (x[0], x[1])) return sorted_by_time @staticmethod def check_calendar(activity: Tuple[int, int, int, str], calendar: List[Tuple[int, ...]]) -> bool: can_do = True if len(calendar) == 0: return True else: start, end, _, _ = activity l_start, l_end = calendar[-1] if start < l_end: can_do = False return can_do def get_calendar(self) -> str: for activity in self.activities: can_cameron_do = self.check_calendar(activity, self.cameron_calendar) if can_cameron_do is True: self.cameron_calendar.append(activity[:2]) activity[3] = 'C' else: can_jamie_do = self.check_calendar(activity, self.jamie_calendar) if can_jamie_do is True: self.jamie_calendar.append(activity[:2]) activity[3] = 'J' else: return "IMPOSSIBLE" return "".join([act[3] for act in sorted(self.activities, key=lambda a: a[2])]) def main(): test_count = int(input()) for t in range(1, test_count + 1): calendar = Activities() print("Case #{}: {}".format(t, calendar.get_calendar())) if __name__ == "__main__": main()
#I'm getting the name of the file and converting it to a string (even though it is a string already) #this is just for consistency in the code print ("enter the name of the file you would like to decrypt") fileName = input() fileName = str(fileName) #now I am opening the file, this time in read mode. sensitiveFile = open(fileName,'r') #Now I am importing the file as a string using the read method. openFile = sensitiveFile.read() #Now I am prompting for a distance value, getting the input and converting to an int. print ("Enter the distance value: ") distance = input() distance = int(distance) #declaring variable plainText, and converting it to a string (again the type conversion isn't necessary but #this is how I like to do it, it makes much much more sense) Python coding the way we are shown in the text is # taking too many shortcuts for my taste. The code this way is much clearer. plainText = "" plainText = str(plainText) #This is the encryption code, I don't want to explain it all, we both know what it does. for ch in openFile: ordValue = ord(ch) ordValue = int(ordValue) #this line is literally encryption in reverse. cipherValue = ordValue - distance if cipherValue > ord('z'): #I do want to mention that the code on the next line keeps the characters within the ASCII values that #correspond to lowercase letters cipherValue = ord('a') + distance - (ord('z') - ordValue + 1) plainText += chr(cipherValue) #printing the resulting decrypted text print ("This is the decrypted text: ") print(plainText) #prompting for the name of the output file, assigning it to the variable and type conversion. print("enter the save name of the new decrypted file") decryptedFileName = input() decryptedFileName = str(decryptedFileName) #opening the file in write mode, which forces the creation of the output file. #Then writing the encrypted text to the new file decryptedFileName = open(decryptedFileName,'w') decryptedFileName.write(plainText) #closing all files to make sure the buffer is flushed and the files are saved. sensitiveFile.close decryptedFileName.close
#!/usr/bin/python3 """ Returns the perimeter of the island described in grid """ def island_perimeter(grid): """ Returns the perimeter of the island described in grid """ cnt = 0 perim = 0 while cnt < len(grid): mv = 0 while mv < len(grid[0]): if grid[cnt][mv] == 1: perim += 4 if cnt - 1 >= 0 and grid[cnt - 1][mv] == 1: perim -= 1 if cnt + 1 < len(grid) and grid[cnt + 1][mv] == 1: perim -= 1 if mv - 1 >= 0 and grid[cnt][mv - 1] == 1: perim -= 1 if mv + 1 < len(grid[0]) and grid[cnt][mv + 1] == 1: perim -= 1 mv += 1 cnt += 1 return perim
# def is called a function def print_hello_world(): print("Hello") print("World") def print_multiples_of_six(): a = 6 print("6 x 1 =", a * 1) print("6 x 2 =", a * 2) print("6 x 3 =", a * 3) print("6 x 4 =", a * 4) print("6 x 5 =", a * 5) print("6 x 6 =", a * 6) print("6 x 7 =", a * 7) print("6 x 8 =", a * 8) print("6 x 9 =", a * 9) print("6 x 10 =", a * 10) def print_halt(): print("Halt!") user_input = input("Who goes there? ") print("You may pass,", user_input) def print_assignment_practice(): a = 1 print(a) a = a + 1 print(a) a = a * 2 print(a) def print_assignment_practice_two(): number = float(input("Type in a number: ")) integer = int(input("Type in an integer: ")) text = input("Type in a string: ") print("number =", number) print("number is a", type(number)) print("number x 2 =", number * 2) print("integer =", integer) print("integer x 2 =", integer * 2) print("text =", text) print("text is a", type(text)) print("text x 2 =", text * 2) def print_olly_oy(): print("If I say olly, you say oy!") user_input = input("Olly! ") user_input = input("Olly! ") user_input = input("Olly, Olly, Olly! ") # This function calculates times from given distances and rates. def print_rates_times(): print("Input a rate and a distance to calculate time.") rate = float(input("Rate: ")) distance = float(input("Distance: ")) time = (distance / rate) print("Time: ", time) def print_count_to_ten(): a = 0 while a < 10: a = a + 1 print(a) def print_calculate_sum(): a = 1 s = 0 print("Enter numbers to add to the sum.") print("Enter 0 to quit.") while a != 0: print("Current sum: ", s) a = float(input("Number: ")) s = s + a print("Total Sum =", s) def print_infinite_loop(): while 1 == 1: print("Help! I'm stuck in a loop.") def print_fibonacci_sequence(): a = 0 b = 1 count = 0 max_count = 15 while count < max_count: count = count + 1 print(a, b, end=" ") # =" " keeps all on one line. a = a + b b = a + b print() def print_password(): password = str() while password != "let me in": password = input("Password: ") print("Welcome in.") def print_username_and_password(): print("Please enter your username and password.") username = input("Username: ") password = input("Password: ") print("To logout type 'lock'.") command = None input1 = None input2 = None while command != "lock": command = input("What is your command? ") while input1 != username: input1 = input("What is your username? ") while input2 != password: input2 = input("What is your password? ") print("Welcome in.") def print_if_loop_warmup(): n = int(input("Number? ")) if n < 0: print("The absolute value of", n, "is", -n) else: print("The absolute value of", n, "is", n) def print_elif_practice(): a = 0 while a < 9: a = a + 1 if a > 6: print(a, ">", 6) elif a <= 3: print(a, "<=", 3) else: print("Neither tests are true.") def print_higher_or_lower(): number = 24 guess = 1 print("Guess what number I'm thinking of.") while guess != number: guess = int(input("Is it... ")) if guess == number: print("Woo, you got it!") elif guess < number: print("A bit higher.") elif guess > number: print("Too high!") def print_practice_git(): print("Testing testing 123") def print_whats_your_name(): name = input('Your name: ') if name == 'Hannah': print("That is a nice name!") elif name == 'James': print("Sounds like a weirdo to me...") else: print("You have a nice name.") def print_sum_of_two(): input1 = float(input('Pick a number: ')) input2 = float(input('Pick another: ')) sum = input1 + input2 print(sum) if sum > 100: print("That is a big number.") def hello(): print('Hello!') def print_welcome(name): print('Welcome,', name) def area_square(side_length): return(side_length**2) def area_rectangle(width, height): return width * height def area_circle(radius): return(3.14 * radius**2) def positive_input(prompt): number = float(input(prompt)) while number <= 0: print('Must be a positive number.') number = float(input(prompt)) return number def print_area_of_shape(): name = input("What's your name? ") hello() print_welcome(name) shape = input("Would you like to find the area of a square, a rectangle or a circle? ") if shape == 'square': l = float(input('Side Length: ')) print('Side Length =', l, 'so area of the square =', area_square(l)) elif shape == 'rectangle': w = float(input('Width: ')) h = float(input('Height: ')) print('Width =', w, 'and height =', h, 'so area of the rectangle =', area_rectangle(w, h)) elif shape == 'circle': r = float(input('Radius: ')) print('Radius =', r, 'so area of the circle =', area_circle(r)) else: print('Shape not recognised.') if __name__ == '__main__': print_area_of_shape()
from PIL import Image import sys ####################################################### # gets the legth of the message in bits # @param message - the message to encode # @return - the length of the message in bits ####################################################### def getLength(message): # check if the message is empty if len(message) == 0: print("Message has no contents") exit() return len(message) * 8 ############################################################ # encodes the length of the message on the first 11 pixels # @param imageFileName - the path to the image file # @param length - the length of the message # @return - none ############################################################ def encodeLength(imageFileName, length): # open the image and rotate 180 degrees # convert to 'RGB' for compatability im = Image.open(imageFileName).convert('RGB') im = im.rotate(180) pix = im.load() width, height = im.size print("WIDTH: ", width, "HEIGHT: ", height) # convert message length into binary string and check for # extremely large messages that won't fit the image if (length//3) > (width*height): print("Message too large to fit image") exit() print("Length of the message in bits: ", length) # convert the length to a binary string of 32 bits length_string = '{0:032b}'.format(length) string_index = 0 x_value = 0 y_value = 0 # loop through the first 10 pixels for x in range(10): # check for edge of image and increment y if needed if x_value > (width - 1): x_value = 0 y_value += 1 r, g, b = pix[x_value, y_value] # check if the least sig bit of R is what we want # if NOT then R = flip the least sig bit if (r & 1) != int(length_string[string_index]): r = r ^ 1 string_index += 1 # same but for G if (g & 1) != int(length_string[string_index]): g = g ^ 1 string_index += 1 # same but for B if (b & 1) != int(length_string[string_index]): b = b ^ 1 string_index += 1 # write the correct RGB value at the right position pix[x_value, y_value] = (r, g, b) x_value += 1 # 11th pixel which ignores b value if x_value > (width - 1): x_value = 0 y_value += 1 r, g, b = pix[x_value, y_value] # same process as above but for ONLY r and g if (r & 1) != int(length_string[string_index]): r = r ^ 1 string_index += 1 if (g & 1) != int(length_string[string_index]): g = g ^ 1 string_index += 1 pix[x_value, y_value] = (r, g, b) # revert the image to it's original orientation im = im.rotate(180) im.save(imageFileName, "PNG") ####################################################### # loads the message from an input file # @param inputFileName - path to the input file # @return - contents of the file as a string ####################################################### def getMessage(inputFileName): # TEST read as binary file with open(inputFileName, 'r') as file: fileContents = file.read() return fileContents ######################################################################## # converts a character to an 8 bit binary string # @param character - signle character # @return - 8 bit binary string corresponding to the right character ######################################################################## def getbitString(character): bitString = bin(int.from_bytes(character.encode(), 'big')) # remove '0b' from the string bitString = bitString[2:] # pad with leading zeros while(len(bitString) != 8): bitString = '0' + bitString return bitString ####################################################### # encodes the message onto the image # @param imageFileName - path to the input file # @param message - the message to encode # @return - none ####################################################### def encodeMessage(imageFileName, message): # get length and convert to amount of pixels # mod handles uneven situations length = getLength(message) message_length_mod = length % 3 length //= 3 # open image and rotate 180 degrees im = Image.open(imageFileName) im = im.rotate(180) pix = im.load() width, height = im.size # message_counter indexes which character # is currently being written message_counter = 0 string_index = 0 x_value = 0 y_value = 0 # loop through first 11 pixels to get starting x and y value for x in range(11): # check for possible edge pixel if x_value > (width - 1): x_value = 0 y_value += 1 x_value += 1 # convert character at message_counter to 8 bit binary string bitString = getbitString(message[message_counter]) message_counter += 1 # starting at the 12th pixel for x in range(1, length + 1): if x_value > (width - 1): x_value = 0 y_value += 1 r, g, b = pix[x_value, y_value] # check if a full 8 bit string has been written # then reset values and get the next 8 bits if string_index >= 8: string_index = 0 bitString = '' bitString = getbitString(message[message_counter]) message_counter += 1 # check if the least sig bit of R is what we want # if NOT then R = flip the least sig bit if (r & 1) != int(bitString[string_index]): r = r ^ 1 string_index += 1 if string_index >= 8: string_index = 0 bitString = '' bitString = getbitString(message[message_counter]) message_counter += 1 # same for G if (g & 1) != int(bitString[string_index]): g = g ^ 1 string_index += 1 if string_index >= 8: string_index = 0 bitString = '' bitString = getbitString(message[message_counter]) message_counter += 1 # same for B if (b & 1) != int(bitString[string_index]): b = b ^ 1 string_index += 1 # write R G B values and continue to next pixel pix[x_value, y_value] = (r, g, b) x_value += 1 # check for uneven cases if message_length_mod == 1: # check for edge pixel if x_value > (width - 1): x_value = 0 y_value += 1 r, g, b = pix[x_value, y_value] # check if the least sig bit of R is what we want if (r & 1) != int(bitString[string_index]): r = r ^ 1 pix[x_value, y_value] = (r, g, b) elif message_length_mod == 2: # check for edge pixel if x_value > (width - 1): x_value = 0 y_value += 1 r, g, b = pix[x_value, y_value] # check if least sig bit of R is what we want if (r & 1) != int(bitString[string_index]): r = r ^ 1 string_index += 1 # same for G if (g & 1) != int(bitString[string_index]): g = g ^ 1 pix[x_value, y_value] = (r, g, b) # revert the image to it's original orientation im = im.rotate(180) im.save(imageFileName, "PNG") # main def main(): # make sure that all the arguments have been provided if len(sys.argv) < 3: print("USAGE: " + sys.argv[0] + "<IMAGE FILE NAME> <INPUT FILE NAME>") exit(-1) # The image file imageFileName = sys.argv[1] # The input file inputFileName = sys.argv[2] # get message from input file message = getMessage(inputFileName) message_length = getLength(message) # encode length and message from image file encodeLength(imageFileName, message_length) encodeMessage(imageFileName, message) ### Call the main function ### if __name__ == "__main__": main()
#!/usr/bin/env python3 import random print('please enter the Dice you want to roll in the Format ndx,') print('where n is the count of dices, and x is the number of possible values of the dice, e.g. 2d6') diceRaw = input() diceList = diceRaw.split("d") diceFaces = int(diceList[1]) diceCount = int(diceList[0]) diceOut = 0 i = 0 while i < diceCount: diceResult: int = random.randint(1, diceFaces) diceOut: int = diceOut + diceResult i += 1 print(diceOut)
# part 1 function definition # with optional arguments - as discussed together def format_name(first_name, last_name, middle_name=None): if middle_name: full_name = f"{first_name.title()} {middle_name.title()} {last_name.title()}" else: full_name = f"{first_name.title()} {last_name.title()}" return full_name # part 2 here is our 'database' - inconsistent formatting (e.g. web scraped) classic_names = [ {'First Name': 'JOHANN', 'Middle Name': 'Sebastian', 'Last Name': 'bach'}, {'First Name': 'Wolfgang', 'Middle Name': 'Amadeus', 'Last Name': 'Mozart'}, {'First Name': 'Ludwig', 'Middle Name': 'van', 'Last Name': 'Beethoven'}, {'First Name': 'Giuseppe', 'Last Name': 'VERDI'}, {'First Name': 'pyotr', 'Middle Name': 'Ilyich', 'Last Name': 'Tchaikovsky'}, {'First Name': 'Frederic', 'Last Name': 'CHOPIN'}, {'First Name': 'ANTONIO', 'Last Name': 'Vivaldi'}, {'First Name': 'Giacomo', 'Last Name': 'Puccini'}, {'First Name': 'George', 'Middle Name': 'Frideric', 'Last Name': 'handel'}, {'First Name': 'igor', 'Last Name': 'Stravinsky'}, ] # # part 3 A - executing code logic from user input - we did this # f_name = input("tell me your first name: ") # l_name = input("tell me your last name: ") # print(format_name(f_name, l_name)) # print() # ------------------------------------------- # ---------------- YOUR TASK ---------------- # ------------------------------------------- # part 3 B - executing code logic from different input (same function) ''' USING THE SAME FUNCTION THAT WE DEFINED ABOVE (which is also the same one that we used to format names that we received from user input): - write a loop that prints out all the names of the composers neatly formatted. ''' for composer in classic_names: print(format_name(composer.get('First Name'), composer.get('Last Name'), composer.get('Middle Name', None))) print()
class Composer: """ Defining a class for composers""" def __init__(self, name, nationality, period): self.name = name self.nationality = nationality self.period = period def youtube(self): return (f'{self.name} is currently playing on my computer.') Bach = Composer('J.S Bach', 'German', 'Baroque') print(f'The composer is {Bach.name}') print(f'His nationatily is {Bach.nationality}') print(f'His work is characterstic of the {Bach.period} of music') print(Bach.youtube()) Mozart = Composer('W.A. Mozart', 'Austrian', 'Classical' ) print(f'The is composer is {Mozart.name}') print(f'His nationality is {Mozart.nationality}') print(f' The capitol of {Mozart.name} country of origin is Sydney') print(f' His work is characteristic and helped define the {Mozart.period} of music') print(Mozart.youtube()) Debussy = Composer('Claude Debussy', 'French', 'Impressionist') print(f'The composer is {Debussy.name}') print(f'His nationality is {Debussy.nationality}') print(f' He was the first {Debussy.period} composer') print(Debussy.youtube())
''' Create a function called 'americanize' that takes a string as argument, transforms it into ALL CAPS, and then prints it as a subliminal part of the american flag. E.g.: |* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| | * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| |* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| | * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| |* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| | * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| |* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |GOD SAVE THE QUEENOOOOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| The function should always return the name of your favorite US president. ''' def americanize(text): # a length check to keep it good-looking. if len(text) > 45: print("please be concise. big is beautiful, but below 45 chars is top.") return # and now, addressing the flag design and IMPORTANT SPEECH patriot_text = text.upper() print(f"""|* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| | * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| |* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| | * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| |* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| | * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| |* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |{patriot_text:O<45}| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| |OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO| """ ) return "Barack Obama" print(americanize("happy 4th of july all you americans!"))
#!/usr/bin/env python # coding=utf-8 # 我自己的方法就是找到之字形输出的规律 # 更好的方法,是更改index来输入每个字符 class Solution(object): """docstring for """ # def convert(self, s, numRows): # s_num = len(s) # n = 2 * numRows - 2 # l = [] # if s_num <= numRows or numRows == 1 or numRows == 0: # return s # for x in range(0, numRows - 1): # ss = '' # y = x # mid = 0 # while y < s_num or mid < s_num: # if y < s_num: # ss += s[y] # mid = y + (numRows - 1 - x) * 2 # y += n # if mid < s_num and mid != y: # ss += s[mid] # l.append(ss) # ss = '' # end = numRows - 1 # while end < s_num: # ss += s[end] # end += n # l.append(ss) # res = '' # for x in range(numRows): # res += l[x] # return res def convert(self, s, numRows): if numRows == 1 or len(s) <= numRows: return s L = [''] * numRows index, step = 0, 1 for x in s: L[index] += x if index == 0: step = 1 elif index == numRows - 1: step = -1 index += step return ''.join(L) a = Solution() b = a.convert('abcd', 2) print(b)
class solution(object): """docstring for solution""" #方法1 def countBits(self,num): cout=[0] for x in range(num+1): cout.append(bin(x).count('1')) return cout #方法2,x&(x-1)计算1的个数 def countBits(self,num): cout=[] num1=0; for x in range(num+1): while x: x=x&(x-1) num1+=1 cout.append(num1) num1=0 return cout # a=solution() # print(a.countBits(5)) # a=bin(5) # print(type(a)) # print(a.count('1'))
# coding: utf-8 import sqlite3 # 入力の変数を宣言 dbName = input('作るデータベースの名前を入力してください' + '\n') tbName = input('作るテーブルの名前を入力してください' + '\n') # DBの作成とDBを操作するための変数を宣言 conn = sqlite3.connect(dbName + '.db') curs = conn.cursor() # テーブルを作成し、カラムは値・テキストが2つ curs.execute('CREATE TABLE ' + tbName + ' (userID INTEGER, lastName TEXT, firstName TEXT)') # テーブルにレコードを追加 sql = 'INSERT INTO ' + tbName + ' (userID, lastName, firstName) values (?, ?, ?)' # レコードの内容を入力するための変数を宣言 ipID = input('ID(入社日+誕生日)は? => ') lName = input('苗字は? => ') fName = input('名前は? => ') # 入力変数を使いテーブルに追加する構文を作成 sqlData = (ipID, lName, fName) # 構文を実行する curs.execute(sql, sqlData) # 実行結果をDBに反映させる conn.commit() # テーブルの内容を全表示させる構文を宣言 sql = ("SELECT * FROM " + tbName) # 構文を実行する curs.execute(sql) # 実行結果を変数に格納 result = curs.fetchall() # 実行結果を1行ずつ出力させる for userID, lastName, firstName in result: print(userID, lastName, firstName)
# Goncalo Botelho Mateus, 99225 def eh_tabuleiro(tab): # eh_tabuleiro: universal -> booleano """ A funcao recebe um argumento de qualquer tipo e devolve True se for um tabuleiro e False caso contrario, sem nunca gerar erros. """ if type(tab) is tuple and len(tab) == 3: for tup in tab: if type(tup) is tuple and len(tup) == 3: for elem in tup: if not (type(elem) == int and -1 <= elem <= 1): return False else: return False else: return False return True def eh_posicao(pos): # eh_posicao: universal -> booleano """ A funcao recebe um argumento de qualquer tipo e devolve True se for uma posicao e False caso contrario, sem nunca gerar erros. """ return type(pos) == int and 1 <= pos <= 9 def obter_coluna(tab, num): # obter_coluna: tabuleiro x inteiro -> vector """ A funcao recebe um tabuleiro e um inteiro que representa o numero da coluna e devolve um vector com os valores da respetiva coluna. Se um dos argumentos for invalido gera um erro. """ if eh_tabuleiro(tab) and type(num) is int and 1 <= num <= 3: coluna = () for tup in tab: coluna += (tup[num - 1],) else: raise ValueError("obter_coluna: algum dos argumentos e invalido") return coluna def obter_linha(tab, num): # obter_linha: tabuleiro x inteiro -> vector """ A funcao recebe um tabuleiro e um inteiro que representa o numero da linha e devolve um vector com os valores da respetiva linha. Se um dos argumentos for invalido gera um erro. """ if eh_tabuleiro(tab) and type(num) is int and 1 <= num <= 3: linha = tab[num - 1] else: raise ValueError("obter_linha: algum dos argumentos e invalido") return linha def obter_diagonal(tab, num): # obter_diagonal: tabuleiro x inteiro -> vector """ A funcao recebe um tabuleiro e um inteiro que representa o numero da diagonal e devolve um vector com os valores da respetiva diagonal. Se um dos argumentos for invalido gera um erro. """ if eh_tabuleiro(tab) and type(num) is int and 1 <= num <= 2: diag = () if num == 1: for i in range(3): diag += (tab[i][i],) else: for i in range(2, -1, -1): # i vai tomar os valores de 2, 1, 0. diag += (tab[i][-i - 1],) # tab[2][-3] = pos 7, tab[1][-2] = pos 5, tab[0][-1] = pos 3 else: raise ValueError("obter_diagonal: algum dos argumentos e invalido") return diag def tabuleiro_str(tab): # tabuleiro_str: tabuleiro -> cad. carateres """ A funcao recebe um tabuleiro e devolve uma cadeia de caracteres que o representa. Se o argumento for invalido gera um erro. """ if eh_tabuleiro(tab): tab_simb = () # transforma os numeros no tabuleiro nos respetivos simbolos for tup in tab: for elem in tup: if elem == -1: tab_simb += ("O",) elif elem == 1: tab_simb += ("X",) else: tab_simb += (" ",) else: raise ValueError("tabuleiro_str: o argumento e invalido") return " " + tab_simb[0] + " | " + tab_simb[1] + " | " + tab_simb[2] + \ " \n-----------\n" + \ " " + tab_simb[3] + " | " + tab_simb[4] + " | " + tab_simb[5] + \ " \n-----------\n" + \ " " + tab_simb[6] + " | " + tab_simb[7] + " | " + tab_simb[8] + " " def junta_tab(tab): # junta_tab: tabuleiro -> tuplo """ A funcao recebe um tabuleiro e devolve um tuplo contendo os 9 valores inteiros do respetivo tabuleiro, a funcao transforma um tuplo com 3 tuplos (tabuleiro) num tuplo com 9 valores. """ if eh_tabuleiro(tab): tab_junto = () for i in range(3): tab_junto += tab[i] return tab_junto def eh_posicao_livre(tab, pos): # eh_posicao_livre: tabuleiro x posicao -> booleano """ A funcao recebe um tabuleiro uma posicao e devolve True se corresponder a uma posicao livre ou False, caso contrario. Se um dos argumentos for invalido gera um erro. """ if eh_tabuleiro(tab) and eh_posicao(pos): tab_junto = junta_tab(tab) return tab_junto[pos - 1] == 0 else: raise ValueError("eh_posicao_livre: algum dos argumentos e invalido") def obter_posicoes_livres(tab): # obter_posicoes_livres: tabuleiro -> vector """ A funcao recebe um tabuleiro e devolve um vetor com as posicoes livres do respetivo tabuleiro. Se o argumento for invalido gera um erro. """ pos_livres = () if eh_tabuleiro(tab): tab_junto = junta_tab(tab) for pos in range(9): if tab_junto[pos] == 0: pos_livres += (pos + 1,) else: raise ValueError("obter_posicoes_livres: o argumento e invalido") return pos_livres def jogador_ganhador(tab): # jogador_ganhador: tabuleiro -> inteiro """ A funcao recebe um tabuleiro e devolve um inteiro que representa o vencedor do jogo (1: 'X', -1: 'O'). Se o argumento for invalido gera um erro. """ if eh_tabuleiro(tab): for i in range(1, 4): # linha1 - linha 3 linha = obter_linha(tab, i) if linha == (1, 1, 1): return 1 if linha == (-1, -1, -1): return -1 coluna = obter_coluna(tab, i) if coluna == (1, 1, 1): return 1 if coluna == (-1, -1, -1): return -1 for k in range(1, 3): # diagonal 1 - diagonal 2 diagonal = obter_diagonal(tab, k) if diagonal == (1, 1, 1): return 1 if diagonal == (-1, -1, -1): return -1 return 0 # enquanto ou se nao houver nenhum vencedor, retorna 0 else: raise ValueError("jogador_ganhador: o argumento e invalido") def eh_jogador(num): # eh_jogador: inteiro -> booleano """ A funcao recebe um inteiro e devolve True se for um jogador e False, caso contrario. """ return type(num) == int and (num == 1 or num == -1) def separar(tup): # separar: tuplo -> tabuleiro """ A funcao recebe um tuplo contendo 9 valores inteiros e devolve o respetivo tabuleiro. """ # divisao do tuplo em 3 tuplos tab = () tup1 = () for i in range(3): tup1 += (tup[i],) tab += (tup1,) tup2 = () for j in range(3, 6): tup2 += (tup[j],) tab += (tup2,) tup3 = () for k in range(6, 9): tup3 += (tup[k],) tab += (tup3,) # juncao dos 3 tuplos para formar o tabuleiro return tab def marcar_posicao(tab, num, pos): # marcar_posicao: tabuleiro x inteiro x posicao -> tabuleiro """ A funcao recebe um tabuleiro, um inteiro que representa um jogador (1: 'X', -1: 'O') e uma posicao livre e devolve um tabuleiro atualizado com a marca do jogador nessa posicao. Se um dos argumentos for invalido gera um erro. """ if (eh_tabuleiro(tab) and eh_jogador(num) and eh_posicao(pos) and eh_posicao_livre(tab, pos)): tab_junto = junta_tab(tab) tup = () # cpia o tabuleiro original ate a posicao dada como argumento for i in range(pos - 1): tup += (tab_junto[i],) # adicao do novo inteiro na posicao desejada tup += (num,) # copia o resto do tabuleiro original for j in range(pos, 9): tup += (tab_junto[j],) tab_novo = separar(tup) else: raise ValueError("marcar_posicao: algum dos argumentos e invalido") return tab_novo def escolher_posicao_manual(tab): # escolher_posicao_manual: tabuleiro -> posicao """ A funcao recebe um tabuleiro como argumento e le uma posicao introduzida pelo jogador e devolve esta memsma posicao. Se o argumento ou a posicao introduzida for invalida gera um erro. """ if eh_tabuleiro(tab): pos_livre = int(input("Turno do jogador. Escolha uma posicao livre: ")) if eh_posicao(pos_livre) and eh_posicao_livre(tab, pos_livre): return pos_livre else: raise ValueError("escolher_posicao_manual: a posicao introduzida " "e invalida") else: raise ValueError("escolher_posicao_manual: o argumento e invalido") def pos_iguais(tab, pos1, pos2, num): # pos_iguais: tabuleiro x posicao x posicao x inteiro -> booleano """ A funcao recebe um tabuleiro, duas posicoes e um inteiro que representa um jogador (1: 'X', -1: 'O') e devolve True se as posicoes forem iguais e False, caso contrario. """ tab_junto = junta_tab(tab) return tab_junto[pos1] == tab_junto[pos2] == num def vitoria(tab, num): # vitoria: tabuleiro x inteiro -> posicao """ A funcao recebe um tabuleiro e um inteiro que representa um jogador (1: 'X', -1: 'O') e devolve uma posicao livre caso o jogador tenha duas das suas pecas e uma posicao livre na mesma linha. """ livre = obter_posicoes_livres(tab) for pos in livre: # verifica se as pecas em linha (linha, coluna, diagonal) a volta # das posicoes livres sao suas. if pos == 1: if (pos_iguais(tab, 1, 2, num) or pos_iguais(tab, 3, 6, num) or pos_iguais(tab, 4, 8, num)): return pos if pos == 2: if pos_iguais(tab, 0, 2, num) or pos_iguais(tab, 4, 7, num): return pos if pos == 3: if (pos_iguais(tab, 0, 1, num) or pos_iguais(tab, 4, 6, num) or pos_iguais(tab, 5, 8, num)): return pos if pos == 4: if pos_iguais(tab, 0, 6, num) or pos_iguais(tab, 4, 5, num): return pos if pos == 5: if (pos_iguais(tab, 0, 8, num) or pos_iguais(tab, 1, 7, num) or pos_iguais(tab, 2, 6, num) or pos_iguais(tab, 3, 5, num)): return pos if pos == 6: if pos_iguais(tab, 2, 8, num) or pos_iguais(tab, 3, 4, num): return pos if pos == 7: if (pos_iguais(tab, 0, 3, num) or pos_iguais(tab, 4, 2, num) or pos_iguais(tab, 7, 8, num)): return pos if pos == 8: if pos_iguais(tab, 1, 4, num) or pos_iguais(tab, 6, 8, num): return pos if pos == 9: if (pos_iguais(tab, 2, 5, num) or pos_iguais(tab, 4, 0, num) or pos_iguais(tab, 6, 7, num)): return pos def pos_iguais_adv(tab, pos1, pos2, num): # pos_iguais_adv: tabuleiro x posicao x posicao x inteiro -> booleano """ A funcao recebe um tabuleiro, duas posicoes e um inteiro que representa um jogador (1: 'X', -1: 'O') e devolve True se as posicoes forem iguais e tenham a marca do seu adversario e False, caso contrario. """ tab_junto = junta_tab(tab) if num == -1: return tab_junto[pos1] == tab_junto[pos2] == 1 else: return tab_junto[pos1] == tab_junto[pos2] == -1 def bloqueio(tab, num): # bloqueio: tabuleiro x inteiro -> posicao """ A funcao recebe um tabuleiro e um inteiro que representa um jogador (1: 'X', -1: 'O') e devolve uma posicao livre caso o adversario tenha duas das suas pecas e uma posicao livre na mesma linha. """ livre = obter_posicoes_livres(tab) for pos in livre: # verifica se as pecas em linha (linha, coluna, diagonal) a volta # das posicoes livres sao do seu adversario. if pos == 1: if (pos_iguais_adv(tab, 1, 2, num) or pos_iguais_adv(tab, 3, 6, num) or pos_iguais_adv(tab, 4, 8, num)): return pos if pos == 2: if pos_iguais_adv(tab, 0, 2, num) or pos_iguais_adv(tab, 4, 7, num): return pos if pos == 3: if (pos_iguais_adv(tab, 0, 1, num) or pos_iguais_adv(tab, 4, 6, num) or pos_iguais_adv(tab, 5, 8, num)): return pos if pos == 4: if pos_iguais_adv(tab, 0, 6, num) or pos_iguais_adv(tab, 4, 5, num): return pos if pos == 5: if (pos_iguais_adv(tab, 0, 8, num) or pos_iguais_adv(tab, 1, 7, num) or pos_iguais_adv(tab, 2, 6, num) or pos_iguais_adv(tab, 3, 5, num)): return pos if pos == 6: if pos_iguais_adv(tab, 2, 8, num) or pos_iguais_adv(tab, 3, 4, num): return pos if pos == 7: if (pos_iguais_adv(tab, 0, 3, num) or pos_iguais_adv(tab, 4, 2, num) or pos_iguais_adv(tab, 7, 8, num)): return pos if pos == 8: if pos_iguais_adv(tab, 1, 4, num) or pos_iguais_adv(tab, 6, 8, num): return pos if pos == 9: if (pos_iguais_adv(tab, 2, 5, num) or pos_iguais_adv(tab, 4, 0, num) or pos_iguais_adv(tab, 6, 7, num)): return pos def obter_filas(tab, num): # obter_filas: tabuleiro x inteiro -> tuplo """ A funcao recebe um tabuleiro e um inteiro que representa um jogador (1: 'X', -1: 'O') e devolve um tuplo com os numeros das filas que tenham apenas uma das posicoes preenchidas pela sua marca ou do adversario. """ num_linha = () num_coluna = () num_diagonal = () for i in range(1, 4): # linha/coluna 1 - linha/coluna 3 linha = obter_linha(tab, i) if (linha == (num, 0, 0) or linha == (0, num, 0) or linha == (0, 0, num)): num_linha += (i,) coluna = obter_coluna(tab, i) if (coluna == (num, 0, 0) or coluna == (0, num, 0) or coluna == (0, 0, num)): num_coluna += (i,) for j in range(1, 3): # diagonal 1 - diagonal 2 diagonal = obter_diagonal(tab, j) if (diagonal == (num, 0, 0) or diagonal == (0, num, 0) or diagonal == (0, 0, num)): num_diagonal += (j,) return num_linha, num_coluna, num_diagonal def intersecao_linha_coluna(tab, filas): # intersecao_linha_coluna: tabuleiro x tuplo -> tuplo """ A funcao recebe um tabuleiro e um tuplo com os numeros das filas que tenham apenas uma das posicoes preenchidas pela sua marca ou do adversario e retorna as posicoes livres onde as linhas e as colunas se intersetam. """ pos_livres = () for i in filas[0]: for j in filas[1]: # verifica se a posicao de intersecao entre a linha e a coluna # esta livre e se estiver adiciona-a a um tuplo if i == 1 and j == 1: if eh_posicao_livre(tab, 1): pos_livres += (1,) if i == 1 and j == 2: if eh_posicao_livre(tab, 2): pos_livres += (2,) if i == 1 and j == 3: if eh_posicao_livre(tab, 3): pos_livres += (3,) if i == 2 and j == 1: if eh_posicao_livre(tab, 4): pos_livres += (4,) if i == 2 and j == 2: if eh_posicao_livre(tab, 5): pos_livres += (5,) if i == 2 and j == 3: if eh_posicao_livre(tab, 6): pos_livres += (6,) if i == 3 and j == 1: if eh_posicao_livre(tab, 7): pos_livres += (7,) if i == 3 and j == 2: if eh_posicao_livre(tab, 8): pos_livres += (8,) if i == 3 and j == 3: if eh_posicao_livre(tab, 9): pos_livres += (9,) return pos_livres def intersecao_diagonal_linha(tab, filas): # intersecao_diagonal_linha: tabuleiro x tuplo -> tuplo """ A funcao recebe um tabuleiro e um tuplo com os numeros das filas que tenham apenas uma das posicoes preenchidas pela sua marca ou do adversario e retorna as posicoes livres onde as diagonais e as linhas se intersetam. """ pos_livres = () for i in filas[0]: for j in filas[2]: # verifica se a posicao de intersecao entre a diagonal e a linha # esta livre e se estiver adiciona-a a um tuplo if i == 1 and j == 1: if eh_posicao_livre(tab, 1): pos_livres += (1,) if i == 2 and j == 1: if eh_posicao_livre(tab, 5): pos_livres += (5,) if i == 3 and j == 1: if eh_posicao_livre(tab, 9): pos_livres += (9,) if i == 1 and j == 2: if eh_posicao_livre(tab, 3): pos_livres += (3,) if i == 2 and j == 2: if eh_posicao_livre(tab, 5): pos_livres += (5,) if i == 3 and j == 2: if eh_posicao_livre(tab, 7): pos_livres += (7,) return pos_livres def intersecao_diagonal_col(tab, filas): # intersecao_diagonal_col: tabuleiro x tuplo -> tuplo """ A funcao recebe um tabuleiro e um tuplo com os numeros das filas que tenham apenas uma das posicoes preenchidas pela sua marca e retorna as posicoes livres onde as diagonais e as colunas se intersetam. """ pos_livres = () for i in filas[1]: for j in filas[2]: # verifica se a posicao de intersecao entre a diagonal e a coluna # esta livre e se estiver adiciona-a a um tuplo if i == 1 and j == 1: if eh_posicao_livre(tab, 1): pos_livres += (1,) if i == 2 and j == 1: if eh_posicao_livre(tab, 5): pos_livres += (5,) if i == 3 and j == 1: if eh_posicao_livre(tab, 9): pos_livres += (9,) if i == 1 and j == 2: if eh_posicao_livre(tab, 7): pos_livres += (7,) if i == 2 and j == 2: if eh_posicao_livre(tab, 5): pos_livres += (5,) if i == 3 and j == 2: if eh_posicao_livre(tab, 3): pos_livres += (3,) return pos_livres def bifurcacao_aux(tab, num): # bifurcacao_aux: tabuleiro x inteiro -> tuplo """ A funcao recebe um tabuleiro e um inteiro que representa um jogador (1: 'X', -1: 'O') e devolve um tuplo com as posicoes livres das intersecoes entre as filas. """ filas = obter_filas(tab, num) col_linha = intersecao_linha_coluna(tab, filas) diagonal_linha = intersecao_diagonal_linha(tab, filas) diagonal_col = intersecao_diagonal_col(tab, filas) # se nao houver intersecoes entre filas a funcao retorna None if col_linha is None or diagonal_linha is None or diagonal_col is None: return None pos = col_linha + diagonal_linha + diagonal_col return pos def bifurcacao(tab, num): # bifurcacao: tabuleiro x inteiro -> posicao """ A funcao recebe um tabuleiro e um inteiro que representa um jogador (1: 'X', -1: 'O') e devolve a menor posicao livre das intersecoes entre as filas. """ if num == 1: pos = bifurcacao_aux(tab, num) elif num == -1: pos = bifurcacao_aux(tab, num) if not (pos is None or pos == ()): return min(pos) # retorna a menor posicao livre das intersecoes def bloqueio_bifurcacao(tab, num): # bloqueio_bifurcacao: tabuleiro x inteiro -> posicao """ A funcao recebe um tabuleiro e um inteiro que representa um jogador (1: 'X', -1: 'O') e devolve a menor posicao livre das intersecoes entre as filas do seu adversario. """ # verifica se o adversario tem bifurcacoes if num == 1: pos = bifurcacao_aux(tab, -num) elif num == -1: pos = bifurcacao_aux(tab, -num) if not (pos is None or pos == ()): return min(pos) # retorna a menor posicao livre das intersecoes def centro(tab): # centro: tabuleiro -> posicao """ A funcao recebe um tabuleiro e devole a posicao livre que equivale ao centro do tabuleiro(5). """ if eh_posicao_livre(tab, 5): return 5 def canto_oposto_aux(tab, num): # canto_oposto_aux: tabuleiro -> posicao """ A funcao recebe um tabuleiro e devole a posicao livre que equivale ao menor dos cantos opostos a um dos cantos ja preenchido. """ if tab[2][2] == -num and eh_posicao_livre(tab, 1): return 1 if tab[2][0] == -num and eh_posicao_livre(tab, 3): return 3 if tab[0][2] == -num and eh_posicao_livre(tab, 7): return 7 if tab[0][0] == -num and eh_posicao_livre(tab, 9): return 9 def canto_oposto(tab, num): # canto_oposto: tabuleiro -> posicao """ A funcao recebe um tabuleiro e devole a posicao livre que equivale ao menor dos cantos opostos a um dos cantos ja preenchido. """ if num == -1: return canto_oposto_aux(tab, num) else: return canto_oposto_aux(tab, num) def canto_vazio(tab): # canto_vazio: tabuleiro -> posicao """ A funcao recebe um tabuleiro e devole a posicao livre que equivale ao menor dos cantos vazios do tabuleiro. """ if eh_posicao_livre(tab, 1): return 1 elif eh_posicao_livre(tab, 3): return 3 elif eh_posicao_livre(tab, 7): return 7 elif eh_posicao_livre(tab, 9): return 9 def lateral_vazia(tab): # lateral_vazia: tabuleiro -> posicao """ A funcao recebe um tabuleiro e devole a posicao livre que equivale a menor lateral vazia do tabuleiro. """ if eh_posicao_livre(tab, 2): return 2 elif eh_posicao_livre(tab, 4): return 4 elif eh_posicao_livre(tab, 6): return 6 elif eh_posicao_livre(tab, 8): return 8 def basico(tab): # basico: tabuleiro -> posicao """ A funcao recebe um tabuleiro e efetua o modo de jogo 'basico' retornando uma posicao livre. """ if centro(tab): return centro(tab) elif canto_vazio(tab): return canto_vazio(tab) elif lateral_vazia(tab): return lateral_vazia(tab) def normal(tab, num): # normal: tabuleiro -> posicao """ A funcao recebe um tabuleiro e efetua o modo de jogo 'normal' retornando uma posicao livre. """ if vitoria(tab, num): return vitoria(tab, num) elif bloqueio(tab, num): return bloqueio(tab, num) elif centro(tab): return centro(tab) elif canto_oposto(tab, num): return canto_oposto(tab, num) elif canto_vazio(tab): return canto_vazio(tab) elif lateral_vazia(tab): return lateral_vazia(tab) def perfeito(tab, num): # perfeito: tabuleiro -> posicao """ A funcao recebe um tabuleiro e efetua o modo de jogo 'perfeito' retornando uma posicao livre. """ if vitoria(tab, num): return vitoria(tab, num) elif bloqueio(tab, num): return bloqueio(tab, num) elif bifurcacao(tab, num): return bifurcacao(tab, num) elif bloqueio_bifurcacao(tab, num): return bloqueio_bifurcacao(tab, num) elif centro(tab): return centro(tab) elif canto_oposto(tab, num): return canto_oposto(tab, num) elif canto_vazio(tab): return canto_vazio(tab) elif lateral_vazia(tab): return lateral_vazia(tab) def eh_estrategia(estrategia): # eh_estrategia: cad. carateres -> booleano """ A funcao recebe uma cadeia de caracteres e devolve True se for uma estrategia e False caso contrario, sem nunca gerar erros. """ return (estrategia == "basico" or estrategia == "normal" or estrategia == "perfeito") def escolher_posicao_auto(tab, num, estrategia): # escolher_posicao_auto: tabuleiro x inteiro x cad. carateres -> posicao """ A funcao recebe um tabuleiro um inteiro que representa um jogador (1: 'X', -1: 'O') e uma cadeia de carateres correspondente a estrategia e devolve uma posicao escolhida automaticamente de acordo com a estrategia. Se um dos argumentos for invalido gera um erro. """ if eh_tabuleiro(tab) and eh_jogador(num) and eh_estrategia(estrategia): if estrategia == "basico": return basico(tab) elif estrategia == "normal": return normal(tab, num) else: return perfeito(tab, num) else: raise ValueError("escolher_posicao_auto: algum dos argumentos " "e invalido") def jogo_do_galo_aux(simb, estrategia): # jogo_do_galo_aux: cad. carateres x cad. carateres -> tabuleiro """ A funcao recebe duas cadeias de carateres correspondentes a estrategia e ao simbolo do jogador e devolve um tabuleiro. Esta funcao ira imprimir os sucessivos tabuleiros de jogo conforme as jogadas. """ tab = ((0, 0, 0), (0, 0, 0), (0, 0, 0)) if simb == "O": print("Bem-vindo ao JOGO DO GALO.\nO jogador joga com 'O'.") # o ciclo continua enquanto nao ha vencedor while jogador_ganhador(tab) == 0: turno = "Turno do computador (" + estrategia + "):" print(turno) posic_auto = escolher_posicao_auto(tab, 1, estrategia) tab = marcar_posicao(tab, 1, posic_auto) print(tabuleiro_str(tab)) livres = obter_posicoes_livres(tab) ganhador = jogador_ganhador(tab) if ganhador != 0: # verificacao se ja houve vencedor continue # verificacao se ja nao existem posicoes livres, ou seja houve empate if livres == (): break posic_manual = escolher_posicao_manual(tab) tab = marcar_posicao(tab, -1, posic_manual) print(tabuleiro_str(tab)) if simb == "X": print("Bem-vindo ao JOGO DO GALO.\nO jogador joga com 'X'.") while jogador_ganhador(tab) == 0: posic_manual = escolher_posicao_manual(tab) tab = marcar_posicao(tab, 1, posic_manual) print(tabuleiro_str(tab)) livres = obter_posicoes_livres(tab) ganhador = jogador_ganhador(tab) if ganhador != 0: continue if livres == (): break turno = "Turno do computador (" + estrategia + "):" print(turno) posic_auto = escolher_posicao_auto(tab, 1, estrategia) tab = marcar_posicao(tab, -1, posic_auto) print(tabuleiro_str(tab)) return tab def jogo_do_galo(simb, estrategia): # jogo_do_galo: cad. carateres x cad. carateres -> cad. carateres """ A funcao recebe duas cadeias de carateres correspondentes a estrategia e ao simbolo do jogador e devolve uma cadeia de carateres que indica o vencedor do jogo ou o empate. """ if (simb == "O" or simb == "X") and eh_estrategia(estrategia): if estrategia == "basico": tab = jogo_do_galo_aux(simb, estrategia) elif estrategia == "normal": tab = jogo_do_galo_aux(simb, estrategia) elif estrategia == "perfeito": tab = jogo_do_galo_aux(simb, estrategia) if jogador_ganhador(tab) == -1: return "O" elif jogador_ganhador(tab) == 1: return "X" elif jogador_ganhador(tab) == 0: return "EMPATE"
def compare(str, sample): i = 0 #нумератор строки j = 0 #нумератор шаблона if(str == ""): #проверка для пустой строки for s in sample: if(s != "%"): return "NO" length = len(sample) #найдем длину сэмпла k = 1 while k < length: #превращяем все ряды процентов в один процент if(sample[k] == "%" and sample[k-1] == "%"): sample = sample[:k-1] + sample[k:] length -= 1 k -= 1 k +=1 while i < len(str): #идем по строке if(j >= len(sample)): return "NO" #недопуск переполнения индекса if ((str[i] == sample[j] and sample[j] != "[" and sample[j] != "%") or sample[j] == "_"): #символы совпадают или есть _ if(str[i] == chr(39) and sample[j] == "_"): i += 2 else: i += 1 j += 1 elif (str[i] != sample[j] and sample[j] != "[" and sample[j] != "_" and sample[j] != "%"): #если ничего не совпадает и нет спец символов return "NO" elif (sample[j] == "%"): #обрабатываем процент if (i > abs(len(str) - len(sample[j:]))): j += 1 length -= 1 else: i += 1 elif (sample[j] == "["): formula = "" l = j j += 1 while (sample[j] != "]" and j != l): formula += sample[j] j += 1 if j == len(sample): if(sample[l] != str[i]): return "NO" else: j = l formula = "" if (j == l): j += 1 if (str[i] == chr(39)): i += 2 else: i += 1 else: length -= (len(formula) + 1) if (len(formula) == 1): if (str[i] == formula): j += 1 if (str[i] == chr(39)): i += 2 else: i += 1 else: return "NO" elif (len(formula) == 0): j += 1 length -= 1 elif (len(formula) == 2): if(formula[0] == "^" and formula[1] != str[i]): j += 1 if (str[i] == chr(39)): i += 2 else: i += 1 elif (formula[0] == str[i] or formula[1] == str[i]): j += 1 if (str[i] == chr(39)): i += 2 else: i += 1 else: return "NO" else: log = 0 anti = 1 if (formula[0] == "^"): anti = 0 formula = formula[1:] while (formula != "" and log == 0): subformula = "" if(len(formula)>=3): if (formula[1] == "-" and formula[2] != "-"): subformula = formula[:3] formula = formula[3:] if(anti): if (ord(subformula[0]) <= ord(str[i]) and ord(str[i]) <= ord(subformula[2])): log = 1 else: if (ord(subformula[0]) <= ord(str[i]) and ord(str[i]) <= ord(subformula[2])): return "NO" else: subformula = formula formula = "" if(anti): for symb in subformula: if (symb == str[i]): log = 1 else: for symb in subformula: if (symb == str[i]): return "NO" else: subformula = formula formula = "" if (anti): for symb in subformula: if (symb == str[i]): log = 1 else: for symb in subformula: if (symb == str[i]): return "NO" if (log == 1): if(str[i] == chr(39)): i += 2 else: i += 1 j += 1 if(length > len(str)): while length != len(str): if(sample[length-1] == "%"): length -= 1 else: return "NO" return "YES" def pref_func(str): #просто префикс функция p = [0] * len(str) for i in range(1, len(str)): j = p[i - 1] while j > 0 and str[i] != str[j]: j = p[j - 1] if str[i] == str[j]: j += 1 p[i] = j return p N = int(input()) #число строк for i in range(N): command = input() #вводим строку likes = [0]*100 #будем считать какой like наш, их может быть много, берем тот что по середнине p = pref_func("' like '" + chr(256) + command) u = 0 for k in range(len(p)): if p[k] == len("' like '"): likes[u] = k-2*len("' like '") u += 1 likes = [i for i in likes if i != 0] #позиции всех лайков в строке str = command[1:likes[len(likes)//2]] #выделяем что из этого строка а что шаблон sample = command[likes[len(likes)//2] + len("' like '"):len(command) - 1] if(i < N - 1): print(compare(str, sample)) #делаем функцию else: print(compare(str, sample), end="")
from abc import ABC, abstractmethod class AbstractArray(ABC): @abstractmethod def __init__(self): pass @abstractmethod def print(self): pass @abstractmethod def create(self, n): pass def __del__(self): print('Deleted!') class Array(AbstractArray): def __init__(self, array): super().__init__() self.array = array def print(self): print("Array: ", self.array) def create(self, n): data = input("Data: ") if Type(data) == str: self.array.append(data) createString(self.array, n) elif Type(data) == int: self.array.append(int(data)) createInt(self.array, n) elif Type(data) == float: self.array.append(float(data)) createFloat(self.array, n) def createInt(array, n): for i in range(n - 1): data = int(input("Data: ")) array.append(int(data)/(i+2)) def createFloat(array, n): for i in range(n - 1): data = float(input("Data: ")) array.append(data/(i + 2)) def createString(array, n): for i in range(n - 1): data = input("Data: ") array.append(data) def Type(data): try: data = int(data) return type(data) except ValueError: try: data = float(data) return type(data) except ValueError: return type(data)
# 최빈값 구하기 def solution(array): answer = 0 counter = {} # 1. 빈도수 확인 (배열을 돌면서) for number in array: counter[number] = counter.get(number, 0) + 1 # 1개 추가 # 결과 # counter = { # 1: 1, # 2: 1, # 3: 3, # 4: 1, # } print(counter) # 2. 최빈값 개수 확인, 결과값 반환 max_median = -1 max_values = [] # 빈도수가 같으면, 여기에 넣어주기 위해서 for key in counter: key, counter[key] # 숫자와 빈도수 if max_median < counter[key]: # 현재 빈도수가 더 크면, max_values = [key] # max_values를 key로 초기화 max_median = counter[key] # 빈도수로 최신화 elif max_median == counter[key]: # 빈도수가 같으면? max_values.append(key) # 값 목록에 추가 if len(max_values) > 1: answer = -1 else: answer = max_values[0] # 조건표현식 answer = -1 if len(max_values) > 1 else max_values[0] return answer
def sortLexo(words): words.sort() print(words[0]) A = [] string = input() for i in range(0,len(string)): if string[i] not in A: A.append(string[i]) B = [] for i in A: new_str = string.replace(i,"") B.append(new_str) sortLexo(B)
import numpy as np import random N = random.randint(1, 10) A = np.random.randint(0, 100, (N, N)) print("Матрица:\r\n{}".format(A)) a = np.diagonal(A, 1) a_sum = a.sum() print("Элементы которые выше главной диагонали: \n" + str(a) + "\nИх сумма = " + str(a_sum)) b = np.diagonal(A, -1) b_sum = b.sum() print("Элементы которые ниже главной диагонали: \n" + str(b) + "\nИх сумма = " + str(a_sum))
#Classe Bola: Crie uma classe que modele uma bola: #Atributos: Cor, circunferência, material #Métodos: trocaCor e mostraCor class Bola: def __init__(self,cor,circunferencia,material): self.cor = cor self.circunferencia = circunferencia self.material = material def trocaCor(self,cor): self.cor = cor def mostraCor(self): print(self.cor) bola1 = Bola('vermelho',10,'plastico') bola1.mostraCor() bola1.trocaCor('azul') bola1.mostraCor()
#Classe Pessoa: Crie uma classe que modele uma pessoa: #Atributos: nome, idade, peso e altura #Métodos: Envelhercer, engordar, emagrecer, crescer. Obs: Por padrão, a cada ano que nossa pessoa envelhece, sendo a idade dela menor que 21 anos, ela deve crescer 0,5 cm. class pessoa: def __init__(self,nome,idade,peso,altura): self.nome = nome self.idade = idade self.peso = peso self.altura = altura def envelhecer(self): self.idade += 1 if self.idade < 21: self.altura += 0.5 def engordar(self,peso_extra): self.peso += peso_extra def emagrecer(self,peso_perda): self.peso -= peso_perda leonardo = pessoa('Leonardo',17,95,174) print(leonardo.altura) leonardo.envelhecer() print(leonardo.idade)
def twodimrecursive(mat, verbose=True): import logging if verbose: logging.getLogger().setLevel(logging.DEBUG) else: logging.getLogger().setLevel(logging.INFO) def depth(mat): checks = [] depths = [] logging.debug(f'Entering {mat}') # checks will contain each mat's element type # It will represent the 'end condition' for the recursion. # When it is the case that it doesn't have any more lists. Then we'll stop. for item in mat: checks.append(type(item) == list) logging.debug('Checking if subitems are lists') logging.debug(checks) # First, the 'end condition': if not any(checks): logging.debug('This item is not a list anymore. End recursion.') return 1 # the depth of a non-list item else: # if you have remaining lists: # start by filtering the ones you have. filtered_lists = list(filter(lambda x: type(x) == list, mat)) logging.debug(f'Filtered Out: {tuple(filter(lambda x: type(x) != list, mat))}') logging.debug(f'Lists remaining: {tuple(filter(lambda x: type(x) == list, mat))}') for item in filtered_lists: # calculate the max_depth of that list: #logging.debug(f'Entering {item}') depths.append(depth(item)) max_depth = max(depths) logging.debug(f'Accumulating max depth: {max_depth}') # this could have been written as max_depth = max[depth(item) for item in filtered_lists] # accumulate the depth obtained return 1 + max_depth return depth(mat) print(twodimrecursive([[1,2], [1,2,3], [1,[2,[3]]], [2,[[2,[[[3,[5,7]]],[4,5]]],]]]))
player_height = float(input("請輸入球員身高(公尺):")) player_weight = float(input("請輸入球員體重(公斤):")) player_bmi = player_weight / player_height**2 bmi_label = None if player_bmi > 30: bmi_label = 'Obese' if player_bmi <= 30 and player_bmi > 25: bmi_label = 'Overweight' if player_bmi <= 25 and player_bmi > 18.5: bmi_label = 'Normal weight' if player_bmi <= 18.5: bmi_label = 'Underweight' print(player_bmi) print(bmi_label) if True: print("First branch") elif True: print("Second branch") elif True: print("Third branch") user_int = int(input("請輸入一個正整數:")) if user_int % 3 == 0: print("Fizz") if user_int % 5 == 0: print("Buzz") user_int = int(input("請輸入一個正整數:")) if user_int % 15 == 0: print("Fizz Buzz") elif user_int % 5 == 0: print("Buzz") elif user_int % 3 == 0: print("Fizz") else: print(user_int) i = 1 counter = 0 while i <= 10: counter += 1 i += 1 print(counter) i = 1 counter = 0 while i <= 10: if i % 2 == 0: counter += 1 i += 1 print(counter) i = 1 summation = 0 while i <= 100: summation += i i += 1 print(summation) x = int(input("請輸入起始的正整數:")) y = int(input("請輸入終止的正整數")) i = x while i <= y: print(i) i += 1 x = int(input("請輸入起始的正整數:")) y = int(input("請輸入終止的正整數")) i = x while i <= y: if i % 2 == 1: print(i) i += 1
# Define functions for pop toc here # write some pseudo code # write a function if the number is divisible by 3 # def div_3(number): # return number%3 == 0 def div3(num): if num%3 == 0: return True else: return False # write a function if the number is divisible by 5 def div5(num): if num%5 == 0: return True else: return False # write a function if the number is divisible by 3 and 5 def dev35(num): if num%3 == 0 and num%5 == 0: return True else: return False
""" programmer: me program: double for loop """ for i in range(5): print(i) for j in range(20): print(j) print("Done!") print("\n") ''' programmer: me program: average test score ''' num_people = int(input("How many people are taking the test? ")) test_per_person = int(input("How many tests are being averaged? ")) for i in range(num_people): name = input("What is your name? ") sum = 0 for j in range(test_per_person): score = int(input("What is the score on your test? ")) sum += score average = float(sum) / test_per_person print("Average for " + name + ": " + str(round(average, 2))) ''' programmer: me program: for loop + while loop ''' for i in range(4): print("Outer for loop: " + str(i)) x = 6 while x >= 0: print("Inner while loop: " + str(x)) x -= 1
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import shuffle, choice class EpithetManager: """" Class for managing epithets.""" """ Dictionary for names(keys) and epithets. """ dict_epithets = {} """ Current number of used epithets. """ counter = 0 """ Total number of epithets in dictionary. """ len_epithets = 0 @classmethod def set_epithets_dict(cls, filename): """ Initialize dictionary of epithets. At the beginning, keys are random numbers, which will be replaced by usernames on requests. :param filename: filename containing a list of epithets in one column :return: void """ if not cls.dict_epithets: cls.len_epithets = sum(1 for l in open(filename)) keys = [i for i in range(cls.len_epithets)] shuffle(keys) # randomly shuffle keys if epithets ordered by alphabet k = 0 try: with open(filename) as f: for line in f: cls.dict_epithets[keys[k]] = line k += 1 except IOError as e: raise ValueError("Invalid filename!") @classmethod def get_epithet_dict(cls): return cls.dict_epithets @staticmethod def get_epithet(name): """ :param name: username :return: epithet for username picked from <dict_epithets> """ epithet = "" man = True # Check the gender of username. # if name[-1] == u'а': man = False # For the same user return his epithet. # if name in EpithetManager.dict_epithets: epithet = EpithetManager.dict_epithets[name] elif EpithetManager.counter < EpithetManager.len_epithets: epithet = EpithetManager.dict_epithets[EpithetManager.counter] if not man: epithet = EpithetManager.get_woman_epithet(epithet) EpithetManager.dict_epithets[name] = epithet del EpithetManager.dict_epithets[EpithetManager.counter] EpithetManager.counter += 1 else: # If we do not have enough epithets. # epithet = choice(EpithetManager.dict_epithets.values()) e = epithet c = e[-1] ya = 'я' # madness, but unicode ruthless if not man: if repr(c) != repr(ya[-1]): epithet = EpithetManager.get_woman_epithet(epithet) else: if repr(c) == repr(ya[-1]): epithet = EpithetManager.get_man_epithet_from_woman(epithet) print epithet EpithetManager.dict_epithets[name] = epithet return epithet @staticmethod def get_woman_epithet(word): word = word.decode('utf-8') if word[-1] == '\n': word = word[:-1] word = word[:-2] word = ''.join([c for c in word, u'ая']) word = word.encode('utf-8') return word @staticmethod def get_man_epithet_from_woman(word): word = word.decode('utf-8') word = word[:-2] word = ''.join([c for c in word, u'ый']) word = word.encode('utf-8') return word
import streamlit as st # To make things easier later, we're also importing numpy and pandas for # working with sample data. import numpy as np import pandas as pd header = st.beta_container() dataset = st.beta_container() features = st.beta_container() model_training = st.beta_container() st.title('Analysis of telecom data') st.write("Here's our first attempt at using data to create a table:") with dataset: st.header('telecom dataset') st.text('I gathered data from users ability to acess data and network ') text_data = pd.read_csv('processed_telecom.csv') st.write(text_data.head()) st.subheader('Maximum number of uer interaction') User_interaction = pd.DataFrame(text_data['No_of_xDRsessions'].value_counts()) st.bar_chart(User_interaction) st.subheader('Total number of data usage') User_interactionsp = pd.DataFrame(text_data['Total_MB'].value_counts()).head(50) st.bar_chart(User_interactionsp) with features: st.header('The features I created') st.markdown('* ** The first features I created were about data access on different applications') st.markdown('* ** The second features I created were about categorising data') with model_training: st.header('Time to train the model!') st.text('Here is my model that was used to train our dataset using Random Forest Classifier') sel_col, disp_col = st.beta_columns(2) #sel_col.slider('What should be the maximum depth pof model?' min_value= 10, max_value=20, step=10) max_depth = sel_col.slider('What should be the maximum depth pof model?', min_value= 10, max_value=100, value=20, step=10) n_estimators = sel_col.selectbox('How many trees should there be?', options=[100,200,300,'No limit'], index = 0) sel_col.text('Here is a list of features in my data:') sel_col.write(text_data.columns) input_feature = sel_col.text_input('which feature is used as input?','No_of_xDRsessions') if n_estimators =='No limit': regr = RandomForestRegressor(max_depth=maxdepth) else: regr = RandomForestRegressor(max_depth=max_depth, n_estimators=n_estimators) #regr = RandomForestRegressor(max_depth=max_depth,n_estimators=n_estimators) X = text_data[[input_feature]] y =text_data[['trip_distance']] regr.fit(X,y) predictio = regr.predict(y) disp_col.subheader('Mean absolute error of the model is:') disp_col.write(mean_absolute_error(y, prediction)) disp_col.subheader('Mean squared error of the model is:') disp_col.write(mean_squared_error(y, prediction)) disp_col.subheader('R squared score error of the model is:') disp_col.write(r2, score_error(y, prediction))
""" Small, reusable utility functions to be used in other parts of the program. """ from sys import stdin from contextlib import contextmanager import operator from string import ascii_lowercase def contained(string, charset): """ Does a string only contain characters from this set? """ return set(string) < set(charset) @contextmanager def read_file_or_stdin(path): """ Open a file object using a with block. If a filepath is given, open that file, and if not, return sys.stdin. """ if path: f = open(path, 'r') yield f f.close() else: yield stdin def complete(keycounts): """ Take a {key: count} dictionary and fill in each key not already included with a default value of 0. Used for showing the absence of keys in a count. Creates a new dictionary to return. """ new = {} for alpha in ascii_lowercase: try: count = keycounts[alpha] except KeyError: new[alpha] = 0 else: new[alpha] = count return new def display(keycounts, minimum, label=None): """ Print data in columns and show a total at the end. """ total = 0 buffer = [] if label: print(label) for c, n in sorted(keycounts.items(), key=operator.itemgetter(1)): if n >= minimum: buffer.append("'{}' {}".format(c, n)) total += n if len(buffer) >= 3: print_row(buffer) buffer = [] if buffer: print_row(buffer) print("Total:", total) def cache(keycounts): for key, count in keycounts.items(): print("{}:{}".format(key, count)) def uncache(path): keycounts = {} with read_file_or_stdin(path) as f: for line in f: key, count = line.strip().split(':') keycounts[key] = int(count) return keycounts def print_row(strings): print(("{:<9} " * len(strings)).format(*strings))
import util def minify(path): """ Remove whitespace from a data file. Outputs to stdout to be redirected. """ with util.read_file_or_stdin(path) as f: while True: c = f.read(1) if not c: break # EOF if c.isspace(): continue # remove whitespace print(c, end='')
''' 手绘中国象棋 ''' from tkinter import * root = Tk() root.title("中国象棋棋盘手绘") can =Canvas(root,width =400, height =450) can.create_line((0,2),(400,2),width=2) for i in range(10): can.create_line((0,i*50),(400,i*50),width=2) can.create_line((3,0),(3,450),width=2) for i in range(8): can.create_line((i*50,0),(i*50,200),width=2) for i in range(8): can.create_line((i*50,250),(i*50,450),width=2) can.create_line((397,0),(397,450),width=2) can.create_line((150,0),(250,100),width=2) can.create_line((150,100),(250,0),width=2) can.create_line((150,450),(250,350),width=2) can.create_line((150,350),(250,450),width=2) can.create_text(20,220,text="楚河") can.create_text(380,220,text="汉界") can.pack() # 去除窗口边框 root.overrideredirect(True) # geometry 函数来控制窗口大小,它接受一个字符串类型的参数,‘ width x height + xoffset + yoffset ’ root.geometry("400x450+600+200") root.mainloop()
#For loops in python list1 = [["Aman", 1], ["Shubham", 3], ["Rohit", 6], ["Vikram", 10]] #This is list of list tp = ("Aman", "Shubham", "Rohit", "Vikram") #tuple # print(list1[0], list1[1], list1[2]) print("\n") #Using list for item, lollypop in list1: print(item, "eats", lollypop ,"lollypops") print("\n") #Using tuple for item in tp: print(item) print("\n") #To typecast into dictionary dict1 = dict(list1) # print(dict1) for item, lollypop in dict1.items(): print(item, "eats", lollypop, "lollypops") print("\n")
#Exercise 1 #Create a dictionary and take input from the user and return the meaning og the word from the dictionary print("***WELCOME TO THE MINI PYTHON DICTIONARY***") d1 = {"Master":"गुरुजी", "Buisness":"व्यापार", "Yourself":"स्वयं", "Intrested":"इच्छुक"} Search = input("Enter your word:- ") b = Search.capitalize() print(b," = ",d1 [b]) print("***THANKS FOR USING MINI PYTHON DICTIONARY")
# If Else & Elif Conditionals in Python var1 = 6 var2 = 56 var3 = int(input()) if var3 > var2: print("Greater") elif var3 == var2: print("Equal") else: print("Lesser") list1 = [5,6,7,8] if 5 in list1: print("Yes 5 is in the list") if 13 not in list1: print("No it's not in the list") print(15 not in list1) """Program taking age as a input from user: if age>18 => you can drive age<18 => you cannot drive age==18 => you cannot drive age>10 and age<18:- Invalid entry""" print("***Welcome to Indian driving school***") print("Enter your age :-") age = int(input()) if age>18 and age<100: print("You can drive") elif age>10 and age<18: print("You are minor you cannot drive") elif age == 18: print("Sorry we can't decide. so you should come here physically") else: print("Invalid entry")
frequency = 0 found = False seen = set() while not found: with open("input.txt") as f: for line in f: seen.add(frequency) if line[0] == '-': frequency -= int(line[1:]) else: frequency += int(line[1:]) if frequency in seen: print(frequency) found = True break
import generatedata import random # Calculate the edge name for two points def gen_name(point_a, point_b): edge_name = [point_a[0], point_b[0]] if (point_a[0] > point_b[0]): edge_name = [point_b[0], point_a[0]] return edge_name # Calculate the euclidean distance def calc_dist(point_a, point_b): edge_name = gen_name(point_a, point_b) dist = ((point_a[1][0] - point_b[1][0])**2 + (point_a[1][1] - point_b[1][1])**2)**(1/2) return [dist, edge_name] # Calculate the name of the edge def edge_name(point_a, point_b): edge_name = gen_name(point_a, point_b) return ''.join(edge_name) # Create the sorted list of edges. def create_dict_dist(points): dict_edges = {} for i in range(len(points)): point_a = points[i] for j in range(i + 1, len(points)): point_b = points[j] dist = calc_dist(point_a, point_b) dict_edges[''.join(dist[1])] = dist[0] return dict_edges # A Route class that stores all the data for the Route class Route(): # Initialize the route either with predefined initial route or a set of points def __init__(self, points, data = None): # Create a dictionary of edge costs from the points self.dict_dist = create_dict_dist(points) # Set the initial route data if data != None: self.data = data # predefined initial route else: self.data = [point[0] for point in points[1:]] random.shuffle(self.data) # randomized initial route # Set the initial distance self.dist = self.distance(self.data) # Calculate the total distance for the route def distance(self, data): total_dist = 0 first_path = edge_name(["A"], data) total_dist += self.dict_dist[first_path] from_city = str(data[0]) for to_city in data[1:]: name = edge_name(from_city, to_city) total_dist += self.dict_dist[name] from_city = to_city last_path = edge_name(["A"], from_city) total_dist += self.dict_dist[last_path] return total_dist # Get the distance for the current route def get_distance(self): return self.dist # Create a new route with a 2opt swap from i to k def swap_at(self, i, k): new_route = self.data[0:i] new_route.extend(reversed(self.data[i:k+1])) new_route.extend(self.data[k+1:]) return new_route # Set the new route data and distance def set_route(self, new_route, distance): self.data = new_route self.dist = distance # Unit tests if __name__ == "__main__": points = generatedata.parsefile(14,5) route = Route(points) print(route.data) old_d = route.distance(route.data)
from threading import Thread from threading import Lock i = 0 def someThreadFunction1(lock): # Potentially useful thing: # In Python you "import" a global variable, instead of "export"ing it when you declare it # (This is probably an effort to make you feel bad about typing the word "global") global i for j in range (0,1000000): lock.acquire() i += 1 lock.release() def someThreadFunction2(lock): global i for j in range (0,1000000): lock.acquire() i -= 1 lock.release() def main(): lock = Lock() someThread1 = Thread(target = someThreadFunction1, args = ([lock])) someThread1.start() someThread2 = Thread(target = someThreadFunction2, args = ([lock])) someThread2.start() someThread1.join() someThread2.join() print(i) main()
#Rotten tomatoes from rottentomatoes import RT import Main import sqlite3 import json api = '43h3hy2a4r6cuf3h3d4tzkqy' def details(movie,detailinfo): movie_data = RT(api).search(movie) json_data = json.loads(movie_data)[0] detail = json_data[detailinfo] print detail class Rottentomatoes(Main.Datafetch): def __init__(self,movie_name): self.movie = movie_name self.movie_details=RT(api).search(self.movie) def display_name(self): print "Movie" return details(self.movie,'name') def display_description(self): print "Description:" return details(self.movie,'synopsis') def display_year(self): print "Year:" return details(self.movie,'year') def display_rating(self): print "Rating:" return details(self.movie,'mpaa_rating') movie = raw_input("Enter movie name:") movie1 = Rottentomatoes(movie) conn = sqlite3.connect('Seriesmanagerdatabase.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS Rottentomatoes_movie(name text,description text,year int,rating real)''') c.execute("INSERT INTO Rottentomatoes_movie VALUES(movie1.display_name(movie1),movie1.display_description(movie1),movie1.display_year(movie1),movie1.display_rating(movie1))") conn.commit() print "Details from Rottentomatoes:\n" for row in c.execute('SELECT * FROM Rottentomatoes_movie ORDER rating'): print row conn.close()
#!/usr/bin/env python # coding: utf-8 # In[ ]: ''' We are going to predict the closing stock price of the day of a corporetion using the past 60 days stock prices. the coperation will be facebook here. ''' # In[1]: #importing all the needed libraries import math import numpy as np import pandas as pd from sklearn.svm import SVR from sklearn.linear_model import LinearRegression import quandl from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt quandl.ApiConfig.api_key = "azmTPfQgta_kCCnharyU" # In[2]: #fetching the data df=quandl.get("WIKI/FB") print(df.head()) # In[3]: #get the adjusted price df=df[['Adj. Close']] print(df.head()) plt.plot(df) # In[10]: # no of days we wnt to predict in the future(n) forecast_out=30 #we will use the shift method to predict the price in the future #creating the new column shifted n units up df["Prediction"]=df[['Adj. Close']].shift(-forecast_out) #printing the new dataset print(df.head()) print(df.tail()) # In[13]: # creating the independent dataset(X) X=np.array(df.drop(['Prediction'],1)) #remove the ;ast n rows X=X[:-forecast_out] print(X) # In[15]: #creating the dependent dataset(y) # converting the dataframe to numpy array of all the values including the nan values y=np.array(df["Prediction"]) # get all the y values except the last n rows y=y[:-forecast_out] print(y) # In[18]: #spliting the data in train and test set 20% x_train, x_test, y_train, y_test=train_test_split(X,y, test_size=0.2) # In[20]: # create and train the SVM(REgression) svr_rbf=SVR(kernel='rbf',C=1e3,gamma=0.1) svr_rbf.fit(x_train,y_train) # In[21]: #Teting the model(R squared value) svm_confidence=svr_rbf.score(x_test, y_test) print("svm confidence: ",svm_confidence) # In[22]: # create and train the linear regression model lr= LinearRegression() lr.fit(x_train, y_train) # In[24]: #Teting the model(R squared value) lr_confidence=lr.score(x_test, y_test) print("lr confidence: ",lr_confidence) # In[25]: # setx_forecast= equals the last 30 rows from the adj. close x_forecast= np.array(df.drop(['Prediction'],1))[-forecast_out:] print(x_forecast) # In[27]: # print the prediction for the next 30 days(linear regression) lr_prediction = lr.predict(x_forecast) print(lr_prediction) print("\n") # print the prediction for the next 30 days(SVM) svm_prediction = svr_rbf.predict(x_forecast) print(svm_prediction)
n = int(input('How many numbers = ')) x = int(input('x = ')) y = int(input('y = ')) import random A = [x, x, y] print(A) if n < 3: print('Error') exit(0) for i in range(3, n): A.append(A[i - 2] + (A[i - 1] / (2 ** (i - 1))) * A[i - 3]) print('\n{0}' .format(A))
""" This is a base class for wine data set """ from abc import ABCMeta from abc import abstractmethod class Dataset(metaclass=ABCMeta): """ __init__: path is the prefix of the file and will be formatted by subset""" def __init__(self, path, subset='train'): # assert subset in ['train', 'eval'], "subset should be one of ['train', 'eval']" self.path = path.format(subset) self.subset = subset @abstractmethod def get_data(self): pass @abstractmethod def _read_data(self): pass
print("Hello World") message = 'Hello "1" World' print(message) message = "hello 'python' world" print(message) message = message.title() print(message) message = message.upper() print(message) message = message.lower() print(message) print("----------------------------------------------") message2 = "I will print" messageAdd = message2 + " " + message print(messageAdd) print("Languages:\n\tPython\n\tC\n\tJavaScript") print("----------------------------------------------") message = ' python ' print(message) print(message.rstrip()) # 去掉后面的空格 print(message.lstrip()) # 去掉前面的空格 print(message.strip()) # 去掉前后的空格 number = 23 # message = message + number 错误!TypeError: Can't convert 'int' object to str implicitly # 必须先把int数据类型转换成string才能进行"+" message = message + str(number) print(message)
def main(): # write code here receipt = [] total = 0 entered = input("Item (enter \"done\" when finished): ") while entered != "done": item_details = {} item_details["name"] = entered item_details["price"] = float(input("Price: ")) item_details["quantity"] = int(input("Quantity: ")) receipt.append(item_details) entered = input("Item (enter \"done\" when finished): ") print("\n-------------------") print("receipt") print("-------------------") for item in receipt: item_total = item["quantity"] * item["price"] total += item_total print(item["quantity"], item["name"], str("{:.3f}".format(item_total)) + "KD") print("-------------------") print("Total Price: " + str("{:.3f}".format(total)) + "KD") if __name__ == '__main__': main()
#!/usr/bin/python import random loccities = ["Phoenix","San Diego","Ontario","Burbank","Los Angeles","Orange County","Las Vegas","San Jose","San Francisco","Oakland"] forcities = ["Phoenix","London","Rome","Frankfurt","Tokyo","Manila","Madrid","Beijing","Shanghai","Paris","Barcelona","Hong Kong","Singapore","Cancun","Montreal","Istanbul","Munich","Amsterdam","Dubai","Toronto","Mumbai"] def combinate(l,b): s = "" for i in l: for j in l: if i is not j: for k in range(random.randrange(1,5)): s = s + "%s\t%s\t%d\t%d:%s\n" % (i,j,random.randrange(b,b+400),random.randrange(0,23),"{0:02}".format(random.randrange(0,59))); # s = s + "{\"%s\", \"%s\", \"%d\", \"%d:%s\"},\n" % (i,j,random.randrange(b,b+400),random.randrange(0,23),"{0:02}".format(random.randrange(0,59))); return s #print combinate(loccities,100) #print #print combinate(loccities,300) #print #print combinate(forcities,600) #print print combinate(forcities,1000)
def check(str): print(str) print(str[::-1]) str1=raw_input("enter the string:") check(str1)
# Inheritance class Food: def __init__(self, name, price): self.name = name self.price = price print(f"{self.name} Is Created From Base Class") def eat(self): print("Eat Method From Base Class") class Apple(Food): def __init__(self, name, price): super().__init__(name, price) print(f"{self.name} Is Created From Derived Class And Price Is {self.price}") def eat(self): print("Eat Method From Derived Class") food_one = Apple("Apple", 30) food_one.eat()
# PracticalSliceEmail name = input("Enter Your Name: ") email = input("Enter Your Email: ") userName = email[:email.index("@")] print(f"Hello {name} Your Email Is {email} And UserName Is {userName}")
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import SimpleGUICS2Pygame.simpleguics2pygame as simplegui import random import math # declare global variables low = 0 high = 100 secret_number = 0 num_guesses = 0 # helper function to start and restart the game def new_game(): global low, high, secret_number, num_guesses print "New Game. Range is from", low, "to",high num_guesses = int(math.ceil(math.log(high, 2))) print "Number of remaining guesses is", num_guesses, "\n" secret_number = random.randrange(low, high) return # define event handlers for control panel def range100(): global low, high low = 0 high = 100 new_game() return def range1000(): global low, high low = 0 high = 1000 new_game() return def input_guess(guess): global num_guesses num_guesses = num_guesses - 1 int_guess = int(guess) print "Guess was", guess print "Number of remaining guesses is", num_guesses if(secret_number < int_guess): if(num_guesses > 0): print "Lower!\n" else: print "You ran out of guesses. The number was", secret_number, "\n" new_game() elif(secret_number > int_guess): if(num_guesses > 0): print "Higher!\n" else: print "You ran out of guesses. The number was", secret_number, "\n" new_game() else: print "Correct!\n" new_game() return # create frame frame = simplegui.create_frame("Guess the number", 200, 200) # register event handlers for control elements and start frame frame.add_button("Range is [0, 100)", range100, 200) frame.add_button("Range is [0, 1000]", range1000, 200) frame.add_input("Enter a guess", input_guess, 200) # call new_game new_game() frame.start() # always remember to check your completed program against the grading rubric
import pandas as pd from fuzzywuzzy import fuzz from fuzzywuzzy import process from flask import Flask, redirect, url_for, request excel_file = "/home/arjun/Desktop/flask_proj/movies1.xlsx" df = pd.read_excel(excel_file, sheet_name="movies") flag = 0 name = df["movie_title"] genre = df["genres"] actor1 = df["actor_1_name"] actor2 = df["actor_2_name"] print("Welcome to the data set viewer") print("Please input the movie you'd like") movie = input() def checker(movie): max, index = 0, 0 for i in range(len(name)): if fuzz.partial_ratio(movie, name[i]) > max: max = fuzz.partial_ratio(movie, name[i]) index = i else: continue if max == 100: print("Movie found! Here is it's index and genre") print(name[index] + "\t" + genre[index]) elif max < 40: print("We couldn't find your movie, maybe it isnt in the data set") else: print("Is this the movie you were looking for?") print(name[index] + "\t" + genre[index] + "\t" + actor1[index] + "\t" + actor2[index]) print("We thought you'd be interested in these movies too") max, newIndex, i = 0, 0, 0 for i in range(len(actor1)): if i == index: continue elif ((fuzz.token_set_ratio(actor1[i], actor1[index]) + fuzz.token_set_ratio(actor2[i], actor2[index]))/2) > max: max = (fuzz.token_set_ratio(actor1[i], actor1[index]) + fuzz.token_set_ratio(actor2[i], actor2[index]))/2 newIndex = i if max < 70: print("We couldn't match any of the lead actors") else: print(max) print("On the basis of of the lead actors, we thought you might like") print(name[newIndex] + "\t" + genre[newIndex] + "\t" + actor1[newIndex] + actor2[newIndex]) #Because of genres max, newerIndex, i = 0, 0, 0 for i in range(len(actor1)): if i == index: continue elif fuzz.token_set_ratio(genre[i], genre[index]) > max: newerIndex = i max = fuzz.token_set_ratio(genre[i], genre[index]) if max < 50: print("We couldn't match any movie based on genre") else: print("On the basis of of the lead actors, we thought you might like") print(name[newerIndex] + "\t" + genre[newerIndex]) return index, newIndex, newerIndex index, newIndex, newerIndex = checker(movie)
def get_answer(): sum_of_squares = 0 square_of_sum = 0 for i in range(101): sum_of_squares += i ** 2 square_of_sum += i square_of_sum = square_of_sum ** 2 dif = square_of_sum - sum_of_squares return dif if __name__ == '__main__': print(get_answer())
'''3-1. Names: Store the names of a few of your friends in a list called names. Print each person’s name by accessing each element in the list, one at a time.''' # names = ['Friend 1', 'Friend 2', 'Friend 3'] # print(names[0]) # print(names[1]) # print(names[2]) '''3-2. Greetings: Start with the list you used in Exercise 3-1, but instead of just printing each person’s name, print a message to them. The text of each message should be the same, but each message should be personalized with the person’s name''' # names = ['Friend 1', 'Friend 2', 'Friend 3'] # print('Hello ' + names[0]) # print('Hello ' + names[1]) # print('Hello ' + names[2]) '''3-3. Your Own List: Think of your favorite mode of transportation, such as a motorcycle or a car, and make a list that stores several examples. Use your list to print a series of statements about these items, such as “I would like to own a Honda motorcycle.”''' # car = ['Audi', 'BMW', 'Ferrari'] # print('I would like to own ' + car[0]) # print('I would like to own ' + car[1]) # print('I would like to own ' + car[2]) '''3-4. Guest List: If you could invite anyone, living or deceased, to dinner, who would you invite? Make a list that includes at least three people you’d like to invite to dinner. Then use your list to print a message to each person, inviting them to dinner.''' # friends = ['Friend 1', 'Friend 2', 'Friend 3'] # print('Hello ' + friends[0] + '! You are invited at dinner') # print('Hello ' + friends[1] + '! You are invited at dinner') # print('Hello ' + friends[2] + '! You are invited at dinner') '''3-5. Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send out a new set of invitations. You’ll have to think of someone else to invite. • Start with your program from Exercise 3-4. Add a print statement at the end of your program stating the name of the guest who can’t make it. • Modify your list, replacing the name of the guest who can’t make it with the name of the new person you are inviting. • Print a second set of invitation messages, one for each person who is still in your list.''' # friends = ['Friend 1', 'Friend 2', 'Friend 3'] # print(friends[2] + ' will not come') # friends[2] = 'Friend 4' # print('Hello ' + friends[0] + '! You are invited at dinner') # print('Hello ' + friends[1] + '! You are invited at dinner') # print('Hello ' + friends[2] + '! You are invited at dinner') '''3-6. More Guests: You just found a bigger dinner table, so now more space is available. Think of three more guests to invite to dinner. • Start with your program from Exercise 3-4 or Exercise 3-5. Add a print statement to the end of your program informing people that you found a bigger dinner table. • Use insert() to add one new guest to the beginning of your list. • Use insert() to add one new guest to the middle of your list. • Use append() to add one new guest to the end of your list. • Print a new set of invitation messages, one for each person in your list.''' # friends = ['Friend 1', 'Friend 2', 'Friend 3'] # print('Hello ' + friends[0] + '. I just found a bigger dinner table') # print('Hello ' + friends[1] + '. I just found a bigger dinner table') # print('Hello ' + friends[2] + '. I just found a bigger dinner table') # friends.insert(0, 'Friend 4') # friends.insert(2, 'Friend 5') # friends.append('Friend 6') # print('Hello ' + friends[0] + '! You are invited at dinner') # print('Hello ' + friends[1] + '! You are invited at dinner') # print('Hello ' + friends[2] + '! You are invited at dinner') # print('Hello ' + friends[3] + '! You are invited at dinner') # print('Hello ' + friends[4] + '! You are invited at dinner') # print('Hello ' + friends[5] + '! You are invited at dinner') '''3-7. Shrinking Guest List: You just found out that your new dinner table won’t arrive in time for the dinner, and you have space for only two guests. • Start with your program from Exercise 3-6. Add a new line that prints a message saying that you can invite only two people for dinner. • Use pop() to remove guests from your list one at a time until only two names remain in your list. Each time you pop a name from your list, print a message to that person letting them know you’re sorry you can’t invite them to dinner. • Print a message to each of the two people still on your list, letting them know they’re still invited. • Use del to remove the last two names from your list, so you have an empty list. Print your list to make sure you actually have an empty list at the end of your program.''' # print('I can invite only two people for dinner') # popped_1 = friends.pop() # print('Sorry ' + popped_1 + '. I cannot invite you to dinner') # popped_2 = friends.pop() # print('Sorry ' + popped_2 + '. I cannot invite you to dinner') # popped_3 = friends.pop() # print('Sorry ' + popped_3 + '. I cannot invite you to dinner') # popped_4 = friends.pop() # print('Sorry ' + popped_4 + '. I cannot invite you to dinner') # print('Hello ' + friends[0] + '. You are still invited to dinner') # print('Hello ' + friends[1] + '. You are still invited to dinner') # del friends[0] # del friends[0] # print(friends) '''3-8. Seeing the World: Think of at least five places in the world you’d like to visit. • Store the locations in a list. Make sure the list is not in alphabetical order. • Print your list in its original order. Don’t worry about printing the list neatly, just print it as a raw Python list. • Use sorted() to print your list in alphabetical order without modifying the actual list. • Show that your list is still in its original order by printing it. • Use sorted() to print your list in reverse alphabetical order without changing the order of the original list. • Show that your list is still in its original order by printing it again. • Use reverse() to change the order of your list. Print the list to show that its order has changed. • Use reverse() to change the order of your list again. Print the list to show it’s back to its original order. • Use sort() to change your list so it’s stored in alphabetical order. Print the list to show that its order has been changed. • Use sort() to change your list so it’s stored in reverse alphabetical order. Print the list to show that its order has changed.''' # places_to_visit = ['neelum valley', 'hunza valley', 'kalash valley', 'naran valley', 'kaghan valley'] # print('Original List', places_to_visit) # print('Sorted', sorted(places_to_visit)) # print('Original Again', places_to_visit) # places_to_visit.reverse() # print(places_to_visit) # places_to_visit.reverse() # print(places_to_visit) # places_to_visit.sort() # print(places_to_visit) # places_to_visit.sort(reverse=True) # print(places_to_visit) '''3-9. Dinner Guests: Working with one of the programs from Exercises 3-4 through 3-7 (page 46), use len() to print a message indicating the number of people you are inviting to dinner.''' friends = ['Friend 1', 'Friend 2', 'Friend 3'] print('I have invited ' + str(len(friends)) + ' people to dinner')
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. # Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. def maxSub(nums): if len(nums) == 1: return nums[0] temp = curr_max = nums[0] for i in range(1, len(nums)): temp = max(nums[i], nums[i]+temp) curr_max = max(temp, curr_max) return curr_max print(maxSub([-2,1,-3,4,-1,2,1,-5,4])) print(maxSub([1])) print(maxSub([-1]))
# Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. # Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? def missingNo(nums): return sum(i for i in range(len(nums)+1)) - sum(nums) print(missingNo([3,0,1])) print(missingNo([9,6,4,2,3,5,7,0,1])) print(missingNo([0,1]))
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. # You may assume that the array is non-empty and the majority element always exist in the array. ## Hint: What data structure can keep track of two data at the same time? ## Hint: How do you count occurences? ### Hint: What is the element in the middle of the sorted list? How do you know? def majorityElement1(nums): nums = sorted(nums) return nums[len(nums)//2] print(majorityElement1([2,2,1,1,1,2,2])) def majorityElement2(nums): seen = {} for each in nums: if each not in seen: seen[each] = 1 else: seen[each] += 1 max_key = nums[0] for each in seen: if seen[each] > seen[max_key]: max_key = each return max_key print(majorityElement1([2,2,1,1,1,2,2]))
""" Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least 2. """ def water(alist): max = 0 left, right = 0, len(alist)-1 while left < right: if alist[left] < alist[right]: if alist[left] * (right-left) > max: max = alist[left] * (right-left) left += 1 else: if alist[right] * (right-left) > max: max = alist[right] * (right-left) right -= 1 return max print(water([1,8,6,2,5,4,8,3,7]))
# 1.1 Implement an algorithm to determine if a string has all unique characters. What if you # can not use additional data structures? # def uniqueChars1(str): # mydict = {} # for each in str: # if each not in mydict: # mydict[each] = 1 # else: # mydict[each] += 1 # if len(mydict) == len(str): # return True # else: # return False # # print(uniqueChars1("bobert")) # print(uniqueChars1("chars")) # print(uniqueChars1("bb")) # def uniqueChars2(str): # for each in str: # str.remove(each) # if each in str: # return False # return True # # # # print(uniqueChars2("bobert")) # print(uniqueChars2("chars")) # print(uniqueChars2("bb")) # 1.2 Write code to reverse a C-Style String. (C-String means that “abcd” is represented as # five characters, including the null character.) # def cString(str): # return " " + str[::-1] # 1.3 Design an algorithm and write code to remove the duplicate characters in a string # without using any additional buffer. # def removeDupes(s): # b = "" # for each in s: # if each not in b: # b += each # return b # # print(removeDupes("Apple")) # Write a method to decide if two strings are anagrams or not # def isAnagram(s1, s2): # if len(s1) != len(s2): # return False # s1 = list(s1) # s2 = list(s2) # # for each in s1: # if each in s2: # s2.remove(each) # else: # return False # # if s2 == []: # return True # else: # return False # # print(isAnagram("racecar", "racecer"))
#!/usr/bin/python """ This is the code to accompany the Lesson 3 (decision tree) mini-project. Use a Decision Tree to identify emails from the Enron corpus by author: Sara has label 0 Chris has label 1 """ import sys import time sys.path.append("../tools/") from email_preprocess import preprocess ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() print len(features_train[0]) ######################################################### ### your code goes here ### #def classify(features_train, labels_train): ### your code goes here--should return a trained decision tree classifer # from sklearn import tree # clf = tree.DecisionTreeClassifier() # clf.fit(features_train, labels_train) # return clf #clf = classify(features_train, labels_train) #pred = clf.predict(features_test) #from sklearn.metrics import accuracy_score #acc = accuracy_score(pred, labels_test) #print "accuracy is: ",acc ######################################################### ### Code for using min_samples_split def classify(features_train, labels_train, x): from sklearn import tree clf = tree.DecisionTreeClassifier(min_samples_split=x) clf.fit(features_train, labels_train) return clf #x = 2 #clf1 = classify(features_train, labels_train, x) #pred1 = clf1.predict(features_test) #x = 50 #clf2 = classify(features_train, labels_train, x) #pred2 = clf2.predict(features_test) x = 40 clf3 = classify(features_train, labels_train, x) pred3 = clf3.predict(features_test) from sklearn.metrics import accuracy_score #acc_min_samples_split_2 = accuracy_score(pred1, labels_test) #acc_min_samples_split_50 = accuracy_score(pred2, labels_test) acc_min_samples_split_40 = accuracy_score(pred3, labels_test) #print "accuracy with min_samples_split 2 is: ", acc_min_samples_split_2 #print "accuracy with min_samples_split 50 is: ", acc_min_samples_split_50 print "accuracy with min_samples_split 40 is: ", acc_min_samples_split_40 ######################################################### ### Code for entropy calculation is in entropy_calc.py
import time # 当此模块作为程序入口时(模块名为"__main__时可以使用") if __name__ == "__main__": def getNumbers(a): a += "#" r = list() innumber = False iBegin = 0 for i in range(len(a)): ch = a[i] if 48 <= ord(ch) <= 57: if not innumber: innumber = True iBegin = i else: if innumber: innumber = False r.append(a[iBegin:i]) pass return tuple(r) print(time.time()) a = "abc123dx5op0" print(getNumbers(a)) print(time.time()) print(__name__)
A = [] for i in range(1,27): A.append(i) print(A)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ smallH = small = ListNode(0) bigH = big = ListNode(0) while head: nextt = head.next if head.val<x: small.next = head small= small.next else: big.next = head big= big.next head.next = None head = nextt small.next = bigH.next return smallH.next
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ current = head while current and current.next: if current.next.val == current.val: current.next = current.next.next else: current = current.next return head; # arr = [] # curr = head # while curr: # if curr.val in arr: # prev.next = curr.next # else: # arr.append(curr.val) # prev = curr # curr = curr.next # return head
class User: bank_name = "First National Dojo" def __init__(self, name, email): self.name = name self.email = email self.account_balance = 1000 def make_deposit(self, amount): self.account_balance += amount return self def make_withdrawl(self, amount): self.account_balance -= amount return self def display_user_balance(self): self.account_balance return self def transfer_money(self, User2, amount): self.account_balance -= amount User2.account_balance += amount print(self.account_balance, User2.account_balance) Mitch = User("Mitch", "mitch@mitch.mitch") Mac = User("Mac", "mac@mac.mac") Hailey = User("Hailey", "hailey@hailey.hailey") Mitch.make_deposit(5000).make_deposit(500).make_deposit(600).make_withdrawl(1050) print(Mitch.account_balance) Mac.make_deposit(1000).make_deposit(2000).make_withdrawl(500).make_withdrawl(600) print(Mac.account_balance) Hailey.make_deposit(10000).make_withdrawl(300).make_withdrawl(500).make_withdrawl(6000) print(Hailey.account_balance) Mitch.transfer_money(Mac, 500)
# Libraries needed to be imported import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import cm import matplotlib as mpl ## Method to plot Climate (Warming) Stripes and/or Time Series (if asked) : def plot_stripes(Tmax, Tmin, t, station_name, plot_tseries): """ A Python function that takes in max/min data for a given station and plots Climate Stripes and/or Time-Series, if user asks for one. Parameters: - Tmax : Array/List of Maximum Temperature Values. - Tmin : Array/List of Minimum Temperature Values. - t : Array/List of years in the record (might have multiple same values if there are monthly/weekly sub-data). - station_name : String name of the Station. - plot_tseries : Character variable with user choice for either plotting or not plotting Time-series line. Either 'y' or 'n'. Returns: Output Image as either a Climate Stripes with/without a time series. """ ## call figure and define plot titles fig = plt.figure(figsize=(8,6)) plt.title(station_name, fontsize=14) ax = plt.gca() ## Calculate temporal intervals and temperature anomalies : num_t = len(np.unique(t)) start = t[0] AvT = (Tmax+Tmin)/2 Tav = [] for i in np.arange(0,num_t): Tav.append(np.average(AvT[np.where(t==start+i)])) ## calculate anomalies MeanT = np.nanmean(Tav) Tanoms = Tav-MeanT ## Store the anomalies as a 2D matrix for the stripes: heatmap = np.zeros((len(Tav),len(Tav))) for i in range(0,num_t): heatmap[:,i] = Tanoms[i] ## calculate fraction of maximum T for the time-series : X = np.arange(num_t) points = Tav/np.nanmax(AvT)*len(Tav) ## Plot stripes and time-series if necessary : plt.imshow(heatmap[:,:], origin = 'lower', cmap = 'seismic', vmin = np.nanmin(Tanoms), vmax = np.nanmax(Tanoms)) if (plot_tseries == 'y'): plt.plot(X, points, marker = 'o', color='yellow') plt.axis('off') # Suppress the axes # plt.savefig(station_name+'_ClimateStripes_'+str(start)+'_'+str(end)+'.png', bbox_inches='tight',dpi=400) plt.show() ## Read Example Data station_name='Austin' t = np.loadtxt('ClimateStripesData.txt', skiprows=2, usecols=[0]) Tmax = np.loadtxt('ClimateStripesData.txt', skiprows=2, usecols=[2]) Tmin = np.loadtxt('ClimateStripesData.txt', skiprows=2, usecols=[3]) plot_stripes(Tmax = Tmax, Tmin = Tmin, t = t, station_name = station_name, plot_tseries = 'y')
names = ["Вася", "Маша", "Петя", "Валера", "Саша", "Даша"] def find_person(name): while len(names) > 0: if names.pop(0) == name: print( name + ' нашелся') break else: print( name + ' не нашелся') find_person('Саша') find_person('Кирилл')
def insertionSort(ar): var =ar[-1] found = False for i in range(-1, -len(ar)-1, -1): if i == -len(ar) and found == False: ar[0] = var found = True print " ".join(map(str, ar)) if(found == False): ar[i] = ar[i-1] if(ar[i-1] < var): ar[i] = var found = True print " ".join(map(str, ar)) m = input() ar = [int(i) for i in raw_input().strip().split()] insertionSort(ar)
def panagram(sen): sen = sen.lower() string = "abcdefghijklmnopqrstuvwxyz" for char in string: if char not in sen: return False return True """ sen = sen.lower() dic = {} for key in range(97,123): dic[key] = False for char in sen: if ord(char) in dic: dic[ord(char)] = True var =True for index in range(97,123): if dic[index] == False: var = False return var """ sen = raw_input() print panagram(sen) """ ans = panagram(sen) if ans == True: print "panagram" else: print "not panagram" """
#!/usr/bin/env python3 """Derive happiness in oneself from a good day's work""" def poly_derivative(poly): """Derivative func""" if len(poly) == 1: return [0] elif not isinstance(poly, list): return None elif len(poly) == 0: return None else: return [poly[i] * i for i in range(1, len(poly))]
#!/usr/bin/env python3 """Concatenate along axis function""" def cat_matrices2D(mat1, mat2, axis=0): """Concatenates two matrices along specific axis Args: mat1 ([int]): a list of elements. mat2 ([int]): a list of elements. axis (int, optional): Defaults to 0. """ new_matrix = [] if len(mat1[0]) != len(mat2[0]) and axis == 0: return None if len(mat1) != len(mat2) and axis == 1: return None for i in range(len(mat1)): row = [] for j in range(len(mat1[0])): row.append(mat1[i][j]) if axis == 1: for j in range(len(mat2[0])): row.append(mat2[i][j]) new_matrix.append(row) if axis == 0: for i in range(len(mat2)): row = [] for j in range(len(mat2[0])): row.append(mat2[i][j]) new_matrix.append(row) return new_matrix
#!/usr/bin/env python3 """Initialize Poisson""" class Poisson: """Represents a poisson distribution""" def __init__(self, data=None, lambtha=1.): """Constructor method""" if data is None: if lambtha <= 0: raise ValueError("lambtha must be a positive value") self.lambtha = float(lambtha) else: if not isinstance(data, list): raise TypeError("data must be a list") if len(data) < 2: raise ValueError("data must contain multiple values") self.lambtha = float(sum(data) / len(data)) def pmf(self, k): """Probability mass function. Calculates the value of the PMF for a given number of “successes” """ if not isinstance(k, int): k = int(k) if k < 0: return 0 result = 0 factorial = 1 for x in range(1, k + 1): factorial *= x result = ((2.7182818285 ** (-self.lambtha)) * (self.lambtha ** k)) / factorial return result def cdf(self, k): """Cumulative Distribution Function. Calculates the value of the CDF for a given number of “successes” """ if not isinstance(k, int): k = int(k) if k < 0: return 0 result = 0 suma = 0 for i in range(k + 1): factorial = 1 for x in range(1, i + 1): factorial *= x suma += (self.lambtha ** i) / factorial result = (2.7182818285 ** (-self.lambtha)) * suma return result
"""Sabes si es par o impar""" Variable=17 if(Variable%2==0): print("Si es par") else: print("Es impar") """Calculo de año biciesto o no""" Año=2000 if(Año%4==0): print("Su año tiene 366 dias , por lo tanto",Año, "es biciesto") else: print("Su año tiene 365 dias , por lo tanto",Año,"no es biciesto") """Interes compuesto e interes simple""" P=1000 #monto a calcular el interes compuesto en Lempiras o la moneda que quieran R=5 # este sera el % de interes sobre el cual se desea calcular "P" T=3 # Periodo de tiempo en el cual se desea calcular el interes ISimple=(P*R*T)/100 print("Su interes simple en",T,"años sera: L.",ISimple) ICompuesto=(P*((1+R/100)**T-1)) print("Su interes compuesto en",T,"años sera: L.",ICompuesto)
# -*- coding: utf-8 -*- import numpy as np def make_batches(size, batch_size): """ Returns a list of batch indices (tuples of indices). :param size: Size of the dataset (number of examples). :param batch_size: Batch size. :return: List of batch indices (tuples of indices). """ nb_batch = int(np.ceil(size / float(batch_size))) res = [(i * batch_size, min(size, (i + 1) * batch_size)) for i in range(0, nb_batch)] return res
enemy = { 'loc_x': 70, 'loc_y': 50, 'color': 'green', 'health': 100, 'name': 'Vasya' } print(enemy) print("Location X = " + str('loc_x')) print("Location Y = " + str('loc_y')) print("His name is: " + enemy['name']) enemy['rank'] = 'Admiral' print(enemy) del enemy['rank'] print(enemy) enemy['loc_x'] = enemy['loc_x'] +40 enemy['health'] = enemy['health'] - 30 if enemy['health'] < 80: enemy['color'] = 'yellow' print(enemy)
class Hero(): def __init__(self, name, level, model): self.name = name self.level = level self.model = model self.health = 100 def show_hero(self): if(self.health == 0): print( "Hero destroyed!!!") else: description = (self.name + " Level is: " + str(self.level) + " model is: " + self.model + " Health is "+ str(self.health)).title() print(description) def level_up(self): self.level += 1 def move(self): print("Hero " + self.name + " running...") def attack(self): if (self.health>0): self.health = self.health - 20 else: print(self.name + " killed")
from pyspark import SparkConf, SparkContext import collections def parse_data(line): line_split = line.split(",") age = int(line_split[2]) num_friends = int(line_split[3]) return (age, num_friends) conf = SparkConf().setMaster("local").setAppName("FriendsByAge") sc = SparkContext(conf=conf) lines = sc.textFile("file:///SparkCourse/fakefriends.csv") rdd = lines.map(parse_data) total_by_age = rdd.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1])) ave_by_age = total_by_age.mapValues(lambda x: x[0] / x[1]) results = ave_by_age.collect() for result in results: print(result)
#!/usr/bin/env python from ADCDACPi import ADCDACPi import time import RPi.GPIO as GPIO #The ADC DAC Pi uses GPIO pin 22 to control the LDAC pin on the DAC. For normal operation this pin needs to be kept low. To do this we will use the RPi.GPIO library to set pin 22 as an output and make it low. GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) #Next we will create an instance of the ADCDACPi class, call it adcdac and set a DAC gain of 1. adcdac = ADCDACPi(1) while True: adcdac.set_dac_voltage(1, 1.5) time.sleep(0.5) adcdac.set_dac_voltage(1, 0) time.sleep(0.5)
"""Find the sum of all the primes below 2 000 000""" import time start_time = time.time() def is_prime(n): # 1 is not a prime if n <= 1: return False # If n is 2 or 3, it's prime if n <= 3: return True # Check if n is divisible by 2 or 3 if n % 2 == 0 or n % 3 == 0: return False i = 5 # Only check up to the square root of the number while i ** 2 <= n: # Now we can check 6k +- 1 if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True total = 5 for i in range(0, 2_000_000, 6): if is_prime(i+1): total += i if is_prime(i-1): total += i print(f"{total} found in {time.time() - start_time} seconds")
import math from time import time start_time = time() def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def consecutive_quadratics(a, b): consecutive = 0 n = 0 while True: quadratic = (math.pow(n, 2) + (a * n) + b) if is_prime(quadratic): consecutive += 1 n += 1 else: return consecutive largest_consecutive = 0 longest_a_b = (0, 0) for a in range(-999, 1000): for b in range(-1000, 1001): c = consecutive_quadratics(a, b) if c > largest_consecutive: largest_consecutive = c longest_a_b = (a, b) print(f"n^2 + {longest_a_b[0]}n + {longest_a_b[1]} gives the longest consecutive chain".center(64)) print(f"with {largest_consecutive} consecutive primes, the product a*b is {longest_a_b[0] * longest_a_b[1]}".center(64)) print(f"Found in {time()-start_time} seconds".center(64))
print "making the circles out of square" import turtle def draw_square(): window = turtle.Screen() window.bgcolor("red") brad = turtle.Turtle() brad.shape("circle") brad.color("yellow") brad.speed("normal") j = 0 while(j<36): i = 0 while(i<4): brad.forward(100) brad.right(90) i=i+1 brad.right(10) j=j+1 draw_square()
"""Users test model.""" # Django from django.db.utils import IntegrityError from django.test import TestCase # Model from users.models import User class CreateUserTestCase(TestCase): """ Evaluate that the User model allows us to create a user correctly. """ def setUp(self): self.alan = { 'email': 'alanbrito@gmail.com', 'password': '4D186321C1A7', 'first_name': 'Alan', 'last_name': 'Brito' } self.alonso = { 'email': 'alanbrito@gmail.com', 'password': 'A1821C16374D', 'first_name': 'Alonso', 'last_name': 'Brito' } def test_create_user(self): """Verify that the user was created correctly.""" user_alan = User.objects.create(**self.alan) self.assertIsNotNone(user_alan.id) def test_create_user_unique_email(self): """Proof that you cannot create a user with the same email.""" User.objects.create(**self.alan) with self.assertRaises(Exception) as raised: User.objects.create(**self.alonso) # Raise exception duplicate key value violates unique constraint self.assertEqual(IntegrityError, type(raised.exception))
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from scipy.stats import f from scipy.stats import norm ''' This program performs an ANOVA F test followed by individual t tests ''' def main(): # Input parameters Nminusk = 10000 kminus1 = 2 step = 0.001 # Integrate the F-distribution to get the critical value F = 0. integrate = 0 while integrate < 0.95: F += step integrate += f.pdf(F, kminus1, Nminusk)*step if integrate > 0.95: print "F value at 95%% confidence level is %0.1f" % F break # Plot the F-distribution x = np.linspace(0, 100, 1000) plt.plot(x,f.pdf(x, kminus1, Nminusk), color="blue", linewidth=3) plt.axvline(F, color="black", linestyle="--", linewidth=2) plt.xlim(0, 5) plt.xlabel('$x$') plt.ylabel(r'$F(x, %d, %d)$' % (kminus1, Nminusk)) plt.title("$F(x, %d, %d)$ Distribution" % (kminus1, Nminusk)) plt.legend() plt.show() # Calculate the required number of users download_rate_estimate = 0.02 sigma2_s = download_rate_estimate*(1. - download_rate_estimate) N = 5.3792*sigma2_s/(0.1*download_rate_estimate)**2 print "estimate of N = %d" % round(N) # Run the obtained results through the F test input_downloads = [500, 620, 490] download_fractions = [entry/N for entry in input_downloads] print "F test result = %0.4f" % Ftest(download_fractions, sigma2_s, N) # Perform individual t-test print "The 96.6%% confidence interval is = (%0.2f %0.2f)" % (norm.interval(0.966, loc=0, scale=1)) for fraction in download_fractions[1:]: print "t value = %0.2f (for a measured download rate of %0.4f)" % (ttest(N, fraction, N, download_fractions[0]), fraction) return # function to calculate the t value def ttest(N_A, p_A, N_0, p_0): # calculate the variance assuming a Bernoulli distribution variance_A = p_A*(1.-p_A) variance_0 = p_0*(1.-p_0) return (p_A - p_0)/np.sqrt(variance_A/N_A + variance_0/N_0) # function to calculate the F value def Ftest(download_fractions, sigma2_s, N): # number of participating samples k = len(download_fractions) # calculate the global mean global_download_fraction = sum(download_fractions)/k numerator = sum([(local_fraction - global_download_fraction)**2 for local_fraction in download_fractions])/(k - 1) # calculate the variance for each sample assuming a Bernoulli distribution variances = [local_fraction*(1.-local_fraction) for local_fraction in download_fractions] denominator = sum([sigma2_s for sigma2_s in variances])/(N - k) return numerator/denominator if __name__ == '__main__': main()
friends = ['Dylan','Van','Ify','Ben', 'Jermaine'] message = "Hello " + friends[0] + ". " + "How are you?" print(message) message = "Hello " + friends[1] + ". " + "How are you?" print(message) message = "Hello " + friends[2] + ". " + "How are you?" print(message) message = "Hello " + friends[3] + ". " + "How are you?" print(message) message = "Hello " + friends[4] + ". " + "How are you?" print(message)
""" Python AST implementation of the parser For this implementation to work each syntax in extensions to define python_ast_name which is assigned a string of the class in python's ast module for example addition and subtraction is implemented with BinOp so you'd do class Addition(Node): python_ast_name = "BinOp" """ import ast from . import Node def convert(expr:str, class_map): tree = ast.parse(expr, mode="eval").body return _translate_tree(tree, class_map) def _translate_tree(ast_tree, class_map) -> Node: root_type = class_map[type(ast_tree)] ns = {} for name in type(ast_tree)._fields: value = getattr(ast_tree, name) if isinstance(value, ast.AST): value = _translate_tree(value, class_map) ns[name] = value return root_type(**ns)
class Node (object): UNSET_INDEX = -1 def __init__(self, weight): self.index = Node.UNSET_INDEX self.weight = weight self.activate() def __repr__(self): return "<Node %s>" % self.get_index() def get_index(self): return self.index def get_weight(self): assert self.weight return self.weight def set_index(self, index): assert self.get_index() == Node.UNSET_INDEX self.index = index def set_weight(self, weight): self.weight = weight def is_active(self): return self.active def activate(self): self.active = True def deactivate(self): self.active = False class Edge (object): def __init__(self, start, end, distance=1): self.set_nodes(start, end) self.set_distance(distance) def __repr__(self): return "<Edge: %s to %s>" % (self.get_start().get_index(), self.get_end().get_index()) def is_active(self): return self.get_start().is_active() and self.get_end().is_active() def get_nodes(self): return (self.start, self.end) def set_nodes(self, start, end): self.start = start self.end = end def get_start(self): return self.start def get_end(self): return self.end def get_distance(self): return self.distance def get_cost(self): weight = self.get_start().get_weight() * self.get_end().get_weight() distance = self.get_distance() return weight * distance def set_start(self, start): self.start = start def set_end(self, end): self.end = end def set_distance(self, distance): self.distance = distance class Graph (object): def __init__(self): self.nodes = [] self.edges = {} def __iter__(self): for node in self.nodes: yield node def add_node(self, node): if node in self.nodes: message = "This node is already in the graph at position #%d." raise KeyError(message % self.nodes.index(node)) index = len(self.nodes) node.set_index(index) self.nodes.append(node) return index def add_edge(self, edge): start = edge.get_start() end = edge.get_end() if start not in self.edges: self.edges[start] = {} if end not in self.edges[start]: self.edges[start][end] = edge def get_node(self, index): return self.nodes[index] def get_nodes(self): return self.nodes def get_num_nodes(self): return len(self.nodes) def get_index(self, node): return self.nodes.index(node) def index_exists(self, index): return index < len(self.nodes) def get_edges(self): return self.edges def get_edge(self, start, end): return self.edges[start][end] def get_edges_from(self, node): return self.edges[node].values() def get_all_edges(self): return [edge for node in self.get_edges() for edge in self.get_edges_from(node)] def get_num_edges(self): return len(self.get_all_edges()) def get_neighbors(self, node, cache_ok=True): return (edge.get_end() for edge in self.get_edges_from(node)) class Grid (object): def __init__(self, rows, columns): self.rows, self.columns = rows, columns self.tiles = [None] * self.rows * self.columns def __getitem__(self, index): row, column = index return self.tiles[row * self.columns + column] def __setitem__(self, index, node): row, column = index self.tiles[row * self.columns + column] = node def make_graph(self): graph = Graph() # Add the nodes to the graph. for node in self.tiles: graph.add_node(node) # Add the edges to the graph. square = 1 diagonal = sqrt(2) * square neighbors = [(-1, -1, diagonal), (0, -1, square), (1, -1, diagonal), (-1, 0, square), (1, 0, square), (-1, 1, diagonal), (0, 1, square), (1, 1, diagonal)] for y in range(self.rows): for x in range(self.columns): node = self[y, x] for fields in neighbors: dx, dy, distance = fields neighbor = self[y+dy, x+dx] graph.add_edge(Edge(node, neighbor, distance)) graph.add_edge(Edge(neighbor, node, distance)) class PriorityQueue (object): def __init__(self, compare=lambda a, b: a < b): self.heap = [] self.set = set() self.compare = compare def __len__(self): return len(self.heap) def __repr__(self): return str(self.heap) def __contains__(self, item): return item in self.set def push(self, item): self.heap.append(item) self.set.add(item) self._bubble(len(self) - 1) def update(self, item): index = self.heap.index(item) self._bubble(index) def pop(self): set = self.set heap = self.heap compare = self.compare size = len(self) - 1 if not size: first = heap.pop() else: first = heap.pop(0) last = heap.pop() heap.insert(0, last) self._drip(0) set.remove(first) return first def peek(self): return self.heap[0] def empty(self): return len(self) == 0 def _bubble(self, index): heap = self.heap compare = self.compare child = index parent = (child - 1) / 2 while child and compare(heap[child], heap[parent]): heap[child], heap[parent] = heap[parent], heap[child] child, parent = parent, (parent - 1)/2 def _drip(self, index): heap = self.heap compare = self.compare get_parent_child = lambda parent: (parent, 2 * parent + 1) parent, child = get_parent_child(index) size = len(self) - 1 while child < size: if (child < size - 1) and compare(heap[child + 1], heap[child]): child += 1 if compare(heap[child], heap[parent]): heap[child], heap[parent] = heap[parent], heap[child] parent, child = get_parent_child(child) else: break class IndexedPQ (PriorityQueue): def __init__(self, weights, compare=lambda a, b: a < b): PriorityQueue.__init__(self, self._compare) self.weights = weights self.naive_compare = compare def _compare(self, a, b): weights = self.weights compare = self.naive_compare return compare(weights[a], weights[b]) class SearchAlgorithm (object): def __init__(self): self.routes = {} self.visited = {} self.found = False self.searching = False self.start_time = 0 self.search_time = 0 def __str__(self): return "[%s] Search Time: %f" % (self.get_name(), self.get_search_time()) def is_searching(self): return self.searching def was_target_found(self): return self.found def get_search_time(self): return self.search_time def get_route(self): return self.route def get_routes(self): return self.routes def search(self, map): self.searching = True self.start_time = time.time() def target_found(self, routes, source, target): tile = target route = [tile] while tile != source: tile = routes[tile] route.append(tile) self.route = route self.routes = routes self.found = True self.searching = False self.search_time = time.time() - self.start_time def target_not_found(self, routes): self.route = [] self.routes = routes self.found = False self.searching = False self.search_time = time.time() - self.start_time class DepthFirstSearch (SearchAlgorithm): def search(self, map): SearchAlgorithm.search(self, map) source = map.get_source() target = map.get_target() routes = dict() visited = set() dummy = graph.Edge(source, source) edges = [dummy] while edges: edge = edges.pop() start = edge.get_start() end = edge.get_end() routes[end] = start visited.add(end) if end == target: self.target_found(routes, source, target) break # Use comprehensions for performance gains. new_edges = [ edge for edge in map.get_edges_from(end) if edge.is_active() if edge.get_end() not in visited ] edges += new_edges else: self.target_not_found(routes) class BreadthFirstSearch (SearchAlgorithm): def search(self, map): SearchAlgorithm.search(self, map) source = map.get_source() target = map.get_target() routes = {} visited = set([source]) dummy = graph.Edge(source, source) stack = [dummy] while stack: edge = stack.pop(0) start = edge.get_start() end = edge.get_end() routes[end] = start if end == target: self.target_found(routes, source, target) break for edge in map.get_edges_from(end): if not edge.is_active(): continue if edge.get_end() in visited: continue stack.append(edge) visited.add(edge.get_end()) else: self.target_not_found(routes) class A_Star (SearchAlgorithm): def __init__(self, heuristic): self.heuristic = heuristic def search(self, map): SearchAlgorithm.search(self, map) # Define variables in local scope source = map.get_source() target = map.get_target() routes = {} starting_nodes = {source: source} real_costs = {source: 0} estimated_costs = {source: 0} frontier_nodes = IndexedPQ(estimated_costs) frontier_nodes.push(source) heuristic = self.heuristic # Loop through the graph while not frontier_nodes.empty(): closest_node = frontier_nodes.pop() routes[closest_node] = starting_nodes[closest_node] # Check if the target was found if closest_node == target: self.target_found(routes, source, target) break # Add more edges to consider edges_from = map.expand_node(closest_node) if not edges_from: edges_from = map.get_edges_from(closest_node) for edge in edges_from: if not edge.is_active(): continue if edge.get_end() in routes: continue start = edge.get_start() end = edge.get_end() real_cost = real_costs[start] + edge.get_cost() heuristic_cost = heuristic(end, target) if end in frontier_nodes: # Already considering this node; choose the shortest path: if real_cost < real_costs[end]: real_costs[end] = real_cost estimated_costs[end] = real_cost + heuristic_cost starting_nodes[end] = start frontier_nodes.update(end) else: # Haven't been here before; store the edge: real_costs[end] = real_cost estimated_costs[end] = real_cost + heuristic_cost starting_nodes[end] = start frontier_nodes.push(end) else: self.target_not_found(routes) class Dijkstra (A_Star): def __init__(self): A_Star.__init__(self, lambda start, end: 0)
import math import re def mainGame(): print("What range is your number in:") numberChecking = True while ( numberChecking ): try: numberRange = input() minNumber, maxNumber = [int(x)for x in sorted(re.findall('\d+', numberRange)) ] break except ValueError: print("Input the right numbers please!") continue numberChecking = False tries = math.ceil(math.log2(maxNumber-minNumber)) while(True): guessedNumber = (minNumber + maxNumber)//2 if tries == 0: print("Ran out of tries!") break print("Is your number ", guessedNumber, "?") goalNumber = input() low = goalNumber.lower() if low == "y": print("Woah, that  was tricky!") break elif low == "h" : minNumber = guessedNumber + 1 tries -= 1 elif low == "l": maxNumber = guessedNumber tries -= 1 else: print("Input answer please!") continue print("Play again? y/n") checkinginput = True while ( checkinginput ): playAgain = input() if playAgain.lower() == 'y': mainGame() elif playAgain.lower() == 'n': print("Hope you enjoy the game!") quit else: print("please write only y or n") mainGame()
import unittest from seconds import Secs class TestPush(unittest.TestCase): def test_convert_to_secs(self): # From minutes to seconds print("From minutes:") print(f" 2 minutes = {Secs('2m')}") print(f" 5 minutes = {Secs('5 mins')}") print(f" 10 minutes = {Secs('10 minutes')}", "\n") # From hours to seconds print("From hours:") print(f" 1 hour = {Secs('1h')}") print(f" 2 hours = {Secs('2 hrs')}") print(f" 3 hours = {Secs('3 hours')}", "\n") # From days to seconds print("From days:") print(f" 1 day = {Secs('1d')}") print(f" 2 days = {Secs('2 dys')}") print(f" 3 days = {Secs('3 days')}", "\n") # From weeks to seconds print("From weeks:") print(f" 1 week = {Secs('1w')}") print(f" 2 weeks = {Secs('2 wks')}") print(f" 3 weeks = {Secs('3 weeks')}", "\n") # From months to seconds print("From months:") print(f" 1 month = {Secs('1M')}") # It can also be mo print(f" 6 months = {Secs('6 mos')}") print(f" 12 months = {Secs('12 months')}", "\n") # From years to seconds print("From years:") print(f" 1 year = {Secs('1y')}") print(f" 2 years = {Secs('2 yrs')}") print(f" 3 years = {Secs('3 years')}", "\n\n") def test_secs_to_time(self): # From seconds to minutes print("To minutes:") print(f" 60 secs = {Secs(60)}") print(f" 600 secs = {Secs(600, abbrev=True)}", "\n") # From seconds to hours print("To hours:") print(f" 3600 secs = {Secs(3600)}") print(f" 7200 secs = {Secs(7200, abbrev=True)}", "\n") # From seconds to days print("To days:") print(f" 86400 secs = {Secs(86400)}") print(f" 172800 secs = {Secs(172800, abbrev=True)}", "\n") # From seconds to weeks print("To weeks:") print(f" 604800 secs = {Secs(604800)}") print(f" 1209600 secs = {Secs(1209600, abbrev=True)}", "\n") # From seconds to months print("To months:") print(f" 18408600 secs = {Secs(18408600)}") print(f" 110451600 secs = {Secs(110451600, abbrev=True)}", "\n") # From seconds to years print("To years:") print(f" 220903200 secs = {Secs(220903200)}") print(f" 441806400 secs = {Secs(441806400, abbrev=True)}", "\n") if __name__ == '__main__': unittest.main()
import numpy as np from sklearn.datasets import load_iris from sklearn import tree # load_iris() will load all 150 rows of data from the # iris wikipedia table iris = load_iris() # These are the indices of the test data we will be using test_idx = [0, 1, 2, 50, 51, 52, 100, 101, 102] print("The features are: " + str(iris.feature_names)) print("The target names are: " + str(iris.target_names)) print("This is the data from the iris wikipedia page table: ") print("Labels: 0 = setosa, 1 = versicolor, 2 = virginica") for i in range(len(iris.target)): print("Example %d: label %s, features %s" % (i, iris.target[i], iris.data[i])) print("The indices of the 150 rows of data we will be using are: " + str(test_idx)) # Training data train_target = np.delete(iris.target, test_idx) train_data = np.delete(iris.data, test_idx, axis=0) # Testing data test_target = iris.target[test_idx] test_data = iris.data[test_idx] clf = tree.DecisionTreeClassifier() clf.fit(train_data, train_target) print("This is what we predict the result will be: " + str(test_target)) print("This is the result: " + str(clf.predict(test_data))) print("0 = setosa, 1 = versicolor, 2 = virginica")
# coding=utf-8 '''Escribe un programa que pida por teclado dos números y que calcule y muestre su suma solamente si: -los dos son pares -el primero es menor que cincuenta -y el segundo está dentro del intervalo cerrado 100-500. En el caso de que no se cumplan las condiciones, en vez de la suma ha de visualizarse un mensaje de error.''' numeroA = int(input('Introduzca un numero')) numeroB = int(input('Introduzca un numero')) if (numeroA%2 == 0) and (numeroB%2 == 0): if numeroA < 50: if numeroB < 100 > 500: print('La suma de los numeros es:', numeroA + numeroB) else: print ('Alguno de los térnminos es erroneo')
# coding=utf-8 '''Escribe un programa que pida por teclado una cantidad de dinero y que a continuación muestre la descomposición de dicho importe en el menor número de billetes y monedas de 100, 50, 20, 10, 5, 2 y 1 euro. En el caso de que alguna moneda no intervenga en la descomposición no se tiene que visualizar nada en la pantalla. Para una cantidad de 2236 euros la salida que generaría el programa sería: 22 billetes de 100 euros 1 billete de 20 euros 1 billete de 10 euros 1 billete de 5 euros 1 moneda de 1 euro''' '''Propuesto por compañeros''' dinero = int(input("Introduce una cantidad de dinero: ")) def contarDinero(cantidad, valor): if valor <= cantidad & cantidad > 4: contador = cantidad // valor cantidad = cantidad % valor print("Hay ", contador, " billetes de ", valor, "€") return cantidad elif valor <= cantidad & cantidad > 0 & cantidad < 4: contador = cantidad // valor cantidad = cantidad % valor print ("Hay ", contador, " monedas de ", valor, "€") return cantidad else: return cantidad tipos = [500, 200, 100, 50, 20, 10, 5, 2, 1] for x in tipos: dinero = contarDinero(dinero, x)
# coding=utf-8 '''Lee por teclado 5 números enteros positivos, y escribe cuál es el mayor de los números introducidos.''' numeroA = int(input('Introduce un número entero positivo:')) numeroB = int(input('Introduce un número entero positivo:')) numeroC = int(input('Introduce un número entero positivo:')) numeroD = int(input('Introduce un número entero positivo:')) numeroE = int(input('Introduce un número entero positivo:')) #asserts assert isinstance(numeroA,int) assert isinstance(numeroB,int) assert isinstance(numeroC,int) assert isinstance(numeroD,int) assert isinstance(numeroE,int) listaNumeros = (numeroA,numeroB, numeroC, numeroD, numeroE) numeroMayor = max(listaNumeros) print (numeroMayor)
# example 4.5 import random # you must add this at the top of your program to use the random functions def main(): answer = random.randint(1, 10) guess = 0 tooHigh = 0 tooLow = 0 valid = False print("Guess a number between 1 and 10!") while guess != answer: valid = False # reset the flag before prompting for guess while not valid: try: guess = int(input("\nEnter guess: ")) if guess < 1 or guess > 10: print("Guess must be 1-10") else: valid = True except: print("Not an integer!") if guess == answer: print("Correct!!") elif guess > answer: print("Too high!") tooHigh += 1 else: print("Too low!") tooLow += 1 print(tooHigh, "of your guess were too high.") print(tooLow, "of your guess were too low.") print("\nThank you for playing!") main()
def reverseString(inputString): return inputString[::-1] # if __name__ == "__main__": # print(reverseString("apple")) # print(reverseString("nope")) # print(reverseString("1234"))
# Regular expressions import re # Use Inflect for singular-izing words import inflect # Gensim for learning phrases and word2vec import gensim # For some reason, inflect thinks that there is a singular form of 'mass', namely 'mas' # and similarly for gas. Please add any other exceptions to this list! p = inflect.engine() p.defnoun('mass', 'mass|masses') p.defnoun('gas', 'gas|gases') p.defnoun('gas', 'gas|gasses') # Other spelling p.defnoun('gaas', 'gaas') #GaAs ;) p.defnoun('gapless', 'gapless') p.defnoun('haas', 'haas') # Check if a string has digits def hasNumbers(inputString): return any(char.isdigit() for char in inputString) # Return the singular form of a word, if it exists def singularize(word): try: # p.singular_word() returns the singular form, but # returns False if there is no singular form (or already singular) # So, if the word is already singular, just return the word if not p.singular_noun(word): return word else: # And otherwise return the singular version return p.singular_noun(word) except Exception as e: print("Euh? What's this? %s"%word) print("This caused an exception: ", e) return word def stripchars(w, chars): return "".join( [c for c in w if c not in chars] ).strip('\n') # Parse a title into words def parse_title(title): """ # Extract the year year, rest = title.split(' ', 1) year = int(year[0:]) # Then the month month, title = rest.split(' ', 1) month = int(month[0:]) """ # Then, for every word in the title: # 1) Split the title into words, by splitting it on spaces ' ' and on '-' (de-hyphenate words). # 2) Turn each of those resulting words into lowercase letters only # 3) Strip out any weird symbols (we don't want parenthesized words, not ; at the end of a word, etc) # 4) Also, we don't want to have digits.. my apologies to all the material studies on interesting compounds! title = gensim.parsing.preprocessing.remove_stopwords(title) # Remove stopwords words = re.split( ' |-|\\|/', title.lower()) wordlist = [] for i in range(len(words)): w = words[i] # Skip if there is no word, or if we have numbers if len(w) < 1 or hasNumbers(w): continue # If it is (probably) math, let's skip it if w[0] == '$' and w[-1] == '$': continue # Remove other unwanted characters w = stripchars(w, '\\/$(){}.<>,;:_"|\'\n `?!#%') # Get singular form w = singularize(w) # Skip if nothing left, or just an empty space if len(w) < 2 or w == ' ': continue # Append to the list wordlist.append(w) # return year, month, wordlist return wordlist # Previous versions #return year, month [singularize(stripchars(w, ['\\/$(){}.<>,;:"|\'\n '])) for w in re.split(' |-|\\|/',title.lower()) if not hasNumbers(w)] #return year, month, [singularize(w.strip("\\/$|[](){}\n;:\"\',")) for w in re.split(' |-',title.lower()) if not hasNumbers(w)] def get_titles_for_years(all_titles, years): """ Return list of all titles for given years (must be a list, even if only one)""" collectedtitles = [] for k in years: allmonthtitles = [] for m in all_titles[k].keys(): allmonthtitles = allmonthtitles + all_titles[k][m] collectedtitles = collectedtitles + allmonthtitles return collectedtitles def get_ngrams(sentences): """ Detects n-grams with n up to 4, and replaces those in the titles. """ # Train a 2-word (bigram) phrase-detector bigram_phrases = gensim.models.phrases.Phrases(sentences) # And construct a phraser from that (an object that will take a sentence # and replace in it the bigrams that it knows by single objects) bigram = gensim.models.phrases.Phraser(bigram_phrases) # Repeat that for trigrams; the input now are the bigrammed-titles ngram_phrases = gensim.models.phrases.Phrases(bigram[sentences]) ngram = gensim.models.phrases.Phraser(ngram_phrases) ngram.save('ngram.phraser') # !! If you want to have more than 4-grams, just repeat the structure of the # above two lines. That is, train another Phrases on the ngram_phrases[titles], # that will get you up to 8-grams. # Now that we have phrasers for bi- and trigrams, let's analyze them # The phrases.export_phrases(x) function returns pairs of phrases and their # certainty scores from x. bigram_info = {} for b, score in bigram_phrases.export_phrases(sentences): bigram_info[b] = [score, bigram_info.get(b,[0,0])[1] + 1] ngram_info = {} for b, score in ngram_phrases.export_phrases(bigram[sentences]): ngram_info[b] = [score, ngram_info.get(b,[0,0])[1] + 1] # Return a list of 'n-grammed' titles, and the bigram and trigram info return [ngram[t] for t in sentences], bigram_info, ngram_info # !!! THIS SECTION HAS NOT YET BEEN UPDATED # !!! IT WILL WORK, BUT IT TAKES A *VERY* LONG # !!! TIME. HAS TO SWITCH TO LIST COMPREHENSION # Parse abstract into sentences def parse_abstract(file): # Buffer for storing the file abstr = open(file, "r").read() sentences = [] # Clean up abstract abstr.lower() abstr.replace('\'', '') abstr.replace('\"', '') # Extract sentences and split into words end = abstr.find('.') while end != -1: sentence = abstr[:end].replace('\n', ' ') # Sanitize the words words = re.split( ' |-|\\|/', sentence.lower() ) wordlist = [] for i in range(len(words)): w = words[i] # Skip if there is no word, or if we have numbers if len(w) < 1 or hasNumbers(w): continue # If it is (probably) math, let's skip it if w[0] == '$' and w[-1] == '$': continue # Remove other unwanted characters w = stripchars(w, '\\/$(){}.<>,;:_"|\'\n `?!#%') # Get singular form w = singularize(w) # Skip if nothing left, or just an empty space if len(w) < 1 or w == ' ': continue # Append to the list wordlist.append(w) sentences.append( wordlist ) abstr = abstr[end+1:] end = abstr.find('.') return sentences
#!/usr/bin/env python # coding: utf-8 # In[2]: get_ipython().run_line_magic('matplotlib', 'inline') # # # Tensors # -------------------------------------------- # # Tensors are a specialized data structure that are very similar to arrays # and matrices. In PyTorch, we use tensors to encode the inputs and # outputs of a model, as well as the model’s parameters. # # Tensors are similar to NumPy’s ndarrays, except that tensors can run on # GPUs or other specialized hardware to accelerate computing. If you’re familiar with ndarrays, you’ll # be right at home with the Tensor API. If not, follow along in this quick # API walkthrough. # # # # In[3]: import torch import numpy as np # ## Tensor Initialization # # Tensors can be initialized in various ways. Take a look at the following examples: # # ### Directly from data # # Tensors can be created directly from data. The data type is automatically inferred. # # # In[8]: data = [[1, 2],[3, 4]] x_data = torch.tensor(data) x_data # ### From a NumPy array # # Tensors can be created from NumPy arrays (and vice versa - see `bridge-to-np-label`). # # # In[11]: np_array = np.array(data) x_np = torch.from_numpy(np_array) np_array # ### From another tensor: # # The new tensor retains the properties (shape, datatype) of the argument tensor, unless explicitly overridden. # # # In[12]: x_ones = torch.ones_like(x_data) # retains the properties of x_data print(f"Ones Tensor: \n {x_ones} \n") x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data print(f"Random Tensor: \n {x_rand} \n") # ### With random or constant values: # # ``shape`` is a tuple of tensor dimensions. In the functions below, it determines the dimensionality of the output tensor. # # # In[13]: shape = (2,3,) rand_tensor = torch.rand(shape) ones_tensor = torch.ones(shape) zeros_tensor = torch.zeros(shape) print(f"Random Tensor: \n {rand_tensor} \n") print(f"Ones Tensor: \n {ones_tensor} \n") print(f"Zeros Tensor: \n {zeros_tensor}") # -------------- # # # # ## Tensor Attributes # # Tensor attributes describe their shape, datatype, and the device on which they are stored. # # # In[20]: tensor = torch.rand(3,4) print(f"Shape of tensor: {tensor.shape}") print(f"Datatype of tensor: {tensor.dtype}") print(f"Device tensor is stored on: {tensor.device}") # -------------- # # # # ## Tensor Operations # # Over 100 tensor operations, including transposing, indexing, slicing, # mathematical operations, linear algebra, random sampling, and more are # comprehensively described [here](https://pytorch.org/docs/stable/torch.html) # # Each of them can be run on the GPU (at typically higher speeds than on a # CPU). If you’re using Colab, allocate a GPU by going to Edit > Notebook # Settings. # # # # In[18]: # We move our tensor to the GPU if available if torch.cuda.is_available(): tensor = tensor.to('cuda') # Try out some of the operations from the list. # If you're familiar with the NumPy API, you'll find the Tensor API a breeze to use. # # # # ### Standard numpy-like indexing and slicing: # # # In[19]: tensor = torch.ones(4, 4) tensor[:,1] = 0 print(tensor) # ### Joining tensors # You can use ``torch.cat`` to concatenate a sequence of tensors along a given dimension. # See also [torch.stack](https://pytorch.org/docs/stable/generated/torch.stack.html), # another tensor joining op that is subtly different from ``torch.cat``. # # # In[21]: t1 = torch.cat([tensor, tensor, tensor], dim=1) print(t1) # ### Multiplying tensors # # # In[22]: # This computes the element-wise product print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n") # Alternative syntax: print(f"tensor * tensor \n {tensor * tensor}") # This computes the matrix multiplication between two tensors # # # In[23]: print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n") # Alternative syntax: print(f"tensor @ tensor.T \n {tensor @ tensor.T}") # ### In-place operations # Operations that have a ``_`` suffix are in-place. For example: ``x.copy_(y)``, ``x.t_()``, will change ``x``. # # # In[24]: print(tensor, "\n") tensor.add_(5) print(tensor) # <div class="alert alert-info">Note<p>In-place operations save some memory, but can be problematic when computing derivatives because of an immediate loss # of history. Hence, their use is discouraged.</p></div> # # # -------------- # # # # ## Bridge with NumPy # # Tensors on the CPU and NumPy arrays can share their underlying memory # locations, and changing one will change the other. # # # ### Tensor to NumPy array # In[25]: t = torch.ones(5) print(f"t: {t}") n = t.numpy() print(f"n: {n}") # A change in the tensor reflects in the NumPy array. # # # In[26]: t.add_(1) print(f"t: {t}") print(f"n: {n}") # ### NumPy array to Tensor # In[27]: n = np.ones(5) t = torch.from_numpy(n) # Changes in the NumPy array reflects in the tensor. # # # In[28]: np.add(n, 1, out=n) print(f"t: {t}") print(f"n: {n}") # In[ ]:
#!/usr/bin/env python # coding: utf-8 # # Linear Regression in 1D - Prediction # ## Simple linear regression - prediction # # In[1]: import torch w = torch.tensor(2.0, requires_grad=True) b = torch.tensor(-1.0, requires_grad=True) def forward(x): y=w*x+b return y # In[3]: x=torch.tensor([1.0]) yhat=forward(x) yhat # In[4]: x=torch.tensor([[1.0],[2.0]]) forward(x) # ## PyTorch - Class Linear # In[5]: from torch.nn import Linear torch.manual_seed(1) model = Linear(in_features=1, out_features=1) list(model.parameters()) # In[7]: x = torch.tensor([0.0]) yhat = model(x) yhat # In[8]: x=torch.tensor([[1.0],[2.0]]) model(x) # ## PyTorch - Custom Modules # In[9]: import torch.nn as nn class LR(nn.Module): def __init__(self, in_size, output_size): super(LR, self).__init__() self.linear = nn.Linear(in_size, output_size) def forward(self, x): out = self.linear(x) return out # In[13]: model = LR(1, 1) list(model.parameters()) # In[14]: x = torch.tensor([1.0]) yhat = model(x) yhat # In[15]: x=torch.tensor([[1.0],[2.0]]) model(x) # In[16]: model.state_dict() # # Linear Regression Training # # Gradient Descent and cost # # PyTorch Slope # ## Linear Regression PyTorch # # In[31]: import torch w=torch.tensor(-10.0, requires_grad=True) X=torch.arange(-3,3,0.1).view(-1, 1) f = -3*X # In[33]: import matplotlib.pyplot as plt plt.plot(X.numpy(), f.numpy()) plt.show() # In[34]: Y = f+0.1*torch.randn(X.size()) plt.plot(X.numpy(), Y.numpy(), 'ro') plt.show() # In[35]: def forward(x): return w*x def criterion(yhat, y): return torch.mean((yhat-y)**2) # In[36]: lr = 0.1 for epoch in range(4): Yhat = forward(X) loss= criterion(Yhat, Y) loss.backward() w.data = w.data - lr*w.grad.data w.grad.data.zero_() # In[37]: w # In[39]: lr = 0.1 COST=[] for epoch in range(4): Yhat = forward(X) loss= criterion(Yhat, Y) loss.backward() w.data = w.data - lr*w.grad.data w.grad.data.zero_() COST.append(loss.item()) COST # # Linear Regression Training in PyTorch # ## Cost surface # Cost = average loss or total loss # ![image.png](attachment:image.png) # ## PyTorch (hard way) # In[40]: def forward(x): y=w*x+b return y def criterion(yhat, y): return torch.mean((yhat-y)**2) w = torch.tensor(-15.0, requires_grad=True) b = torch.tensor(-10.0, requires_grad=True) X = torch.arange(-3, 3, 0.1).view(-1, 1) f = 1*X-1 Y = f+0.1*torch.rand(X.size()) # In[42]: lr = 0.1 for epoch in range(15): Yhat=forward(X) loss=criterion(Yhat, Y) loss.backward() w.data=w.data-lr*w.grad.data w.grad.data.zero_() b.data=b.data-lr*b.grad.data b.grad.data.zero_() # # Stochastic Gradient Descent and the Data Loader # ## Stochastic Gradient Descent in PyTorch # In[44]: w = torch.tensor(-15.0, requires_grad=True) b = torch.tensor(-10.0, requires_grad=True) X = torch.arange(-3, 3, 0.1).view(-1, 1) f = -3*X import matplotlib.pyplot as plt plt.plot(X.numpy(), f.numpy()) plt.show() # In[45]: Y=f+0.1*torch.randn(X.size()) plt.plot(X.numpy(), Y.numpy(), 'ro') plt.show() # In[46]: def forward(x): y=w*x+b return y def criterion(yhat, y): return torch.mean((yhat-y)**2) # In[54]: lr = 0.1 for epoch in range(4): for x, y in zip(X, Y): yhat=forward(x) loss=criterion(yhat, y) loss.backward() w.data=w.data-lr*w.grad.data w.grad.data.zero_() b.data=b.data-lr*b.grad.data b.grad.data.zero_() # ## Stochastic Gradient Descent DataLoader # In[48]: from torch.utils.data import Dataset class Data(Dataset): def __init__(self): self.x = torch.arange(-3, 3, 0.1).view(-1, 1) self.y = -3*X+1 self.len = self.x.shape[0] def __getitem__(self, index): return self.x[index], self.y[index] def __len__(self): return self.len dataset = Data() # In[49]: len(dataset) # In[50]: #slicing x,y = dataset[0:3] # In[51]: x, y # In[53]: from torch.utils.data import DataLoader dataset=Data() trainloader = DataLoader(dataset=dataset, batch_size=1) # In[55]: for x, y in trainloader: yhat = forward(x) loss = criterion(yhat, y) loss.backward() w.data=w.data-lr*w.grad.data b.data=b.data-lr*b.grad.data w.grad.data.zero_() b.grad.data.zero_() # # Mini-Batch Gradient Descent # ![image.png](attachment:image.png) # ## Mini-Batch Gradient Descent in Pytorch # In[57]: dataset = Data() trainloader = DataLoader(dataset=dataset, batch_size=5) # In[59]: lr=0.1 LOSS = [] for epoch in range(4): for x, y in trainloader: yhat=forward(x) loss = criterion(yhat, y) loss.backward() w.data=w.data-lr*w.grad.data b.data=b.data-lr*b.grad.data w.grad.data.zero_() b.grad.data.zero_() LOSS.append(loss.item()) # # Optimization in PyTorch # In[61]: criterion = nn.MSELoss() trainloader = DataLoader(dataset=dataset, batch_size=1) model = LR(1,1) from torch import nn, optim optimizer = optim.SGD(model.parameters(), lr = 0.01) optimizer.state_dict() # In[62]: for epoch in range(100): for x, y in trainloader: yhat = model(x) loss = criterion(yhat, y) optimizer.zero_grad() loss.backward() optimizer.step() # ![image.png](attachment:image.png) # # Training, Validation and Test Split in PyTorch # In[65]: from torch.utils.data import Dataset, DataLoader class Data(Dataset): def __init__(self, train = True): self.x = torch.arange(-3, 3, 0.1).view(-1, 1) self.f = -3*self.x+1 self.y = self.f+0.1*torch.randn(self.x.size()) self.len = self.x.shape[0] if train == True: self.y[0] = 0 self.y[50:55] = 20 else: pass def __getitem__(self, index): return self.x[index], self.y[index] def __len__(self): return self.len train_data = Data() val_data = Data(train=False) # In[66]: import torch.nn as nn class LR(nn.Module): def __init__(self, input_size, output_size): super(LR, self).__init__() self.linear = nn.Linear(input_size, output_size) def forward(self, x): out=self.linear(x) return out # In[67]: criterion = nn.MSELoss() trainloader = DataLoader(dataset=train_data, batch_size=1) # In[73]: epochs = 10 learning_rates = [0.0001, 0.001, 0.01, 0.1, 1] validation_error = torch.zeros(len(learning_rates)) test_error=torch.zeros(len(learning_rates)) MODELS=[] # In[76]: from torch import optim from tqdm import tqdm for i, learning_rate in tqdm(enumerate(learning_rates)): model = LR(1,1) optimizer = optim.SGD(model.parameters(), lr = learning_rate) for epoch in range(epochs): for x, y in trainloader: yhat = model(x) loss = criterion(yhat, y) optimizer.zero_grad() loss.backward() optimizer.step() yhat=model(train_data.x) loss=criterion(yhat, train_data.y) test_error[i]=loss.item() yhat=model(val_data.x) loss=criterion(yhat, val_data.y) validation_error[i]=loss.item() MODELS.append(model) # In[78]: import numpy as np plt.semilogx(np.array(learning_rates), validation_error.numpy(), label='training cost/total loss') plt.semilogx(np.array(learning_rates), test_error.numpy(), label='validation cost/total loss') plt.ylabel('Cost Total loss') plt.xlabel('learning rate') plt.legend() plt.show() # In[80]: for model, learning_rate in zip(MODELS, learning_rates): yhat = model(val_data.x) plt.plot(val_data.x.numpy(), yhat.detach().numpy(), label='lr:'+str(learning_rate)) plt.plot(val_data.x.numpy(), val_data.y.numpy(), 'or', label='validation data') plt.legend() plt.show() # In[ ]:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 30 09:01:46 2020 @author: student """ # FLAMES game n1=input("Enter the name").lower().replace(" ","") n2=input("Enter the name").lower().replace(" ","") d1=list(set(n1)-set(n2)) d2=list(set(n2)-set(n1)) #removing matchning letters c=d1+d2 #concatination of two list count=len(c) #length of c ''' here count =0 means two name are identically equal so we no need to find flames for those names ''' if count>0: list1=["Friends","Lovers","Affectionate","Marriage","Enemies","Siblings"] ''' here the while loop will iterate untill the length of list should be 1 bcz we have to get only one relationship b/w two members ''' while len(list1)>1: c=count%len(list1) i=c-1 # bcz index is starts from 0 if i>=0: left=list1[:i] right=list1[i+1:] list1=right+left else: list1=list1[:len(list1)-1] print("relationship is",list1[0]) else: print("plz don't enter the same names")
''' Створіть масив А [1..7] за допомогою генератора випадкових чисел і виведіть його на екран. Збільште всі його елементи в 2 рази. Огороднік Марина Олександрівна, І курс, група 122А ''' import numpy as np # імпортуємо бібліотеку numpy для роботи з масивами from random import randint # імпортуємо функцію randint() для генерування випадкових чисел while True: A = np.zeros(7, dtype=int) # ініціалізуємо одновимірний масив нулями розміром 7 for i in range(7): A[i] = randint(0, 10) # циклічно заповнюємо масив випадковими числами в межах від 0 до 10 print(A) for j in range(7): # циклічно збільшуємо кожен елемент масиву вдвічі A[j] = A[j] * 2 print(A) answer = input('Бажаєте запустити ще раз (+) чи за завершити програму (будь-що)? ') if answer == '+': print('') continue else: break
# Научите Анфису отвечать на вопрос «Анфиса, как дела?» случайным образом. # Для этого напишите функцию how_are_you() без параметров (да-да, функции могут не иметь параметров, это нормально). # Пусть она возвращает случайный ответ из списка answers. Можете и сами дописать варианты :) # здесь подключите библиотеку random и дайте ей краткое имя import random as r answers = ['Норм.', 'Лучше всех :)', 'Ну так', 'Отличненько!', 'Ничего, жить буду'] def how_are_you(): return r.choice(answers) print(how_are_you())
# На основе заготовленного кода напишите функцию print_friends_count() для вывода количества друзей. # Аргументом сделайте friends_count. Вызовите эту функцию не менее трёх раз с разными аргументами от 1 до 20. def print_friends_count(friends_count): if friends_count == 1: print('У тебя 1 друг') elif 2 <= friends_count <= 4: print('У тебя ' + str(friends_count) + ' друга') elif friends_count >= 5: print('У тебя ' + str(friends_count) + ' друзей') print_friends_count(5) print_friends_count(16) print_friends_count(20) # Напишите цикл, в котором функция print_friends_count() вызывается c аргументами от 1 до 10. # Код самой функции не изменяйте. def print_friends_count(friends_count): if friends_count == 1: print('У тебя 1 друг') elif 2 <= friends_count <= 4: print('У тебя ' + str(friends_count) + ' друга') elif friends_count >= 5: print('У тебя ' + str(friends_count) + ' друзей') for friends in range(1, 10): print_friends_count(friends)