text
stringlengths
37
1.41M
from threading import Thread class InputReader(Thread): def run(self): self.line_of_text = input() print("Enter some text and press enter: ") thread = InputReader() thread.start() count = result = 1 while thread.is_alive(): result = count * count count += 1 print("calculated squares up to {0} * {0} = {1}".format( count, result)) print("while you typed '{}'".format(thread.line_of_text))
import math def distance(p1, p2): return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2) def perimeter(polygon): perimeter = 0 points = polygon + [polygon[0]] for i in range(len(polygon)): perimeter += distance(points[i], points[i+1]) return perimeter
class EMail: def __init__(self, from_addr, to_addr, subject, message): self.from_addr = from_addr self.to_addr = to_addr self.subject = subject self.message = message email = EMail("[email protected]", "[email protected]", "You Have Mail!", "Here's some mail for you!") template = """ From: <{0.from_addr}> To: <{0.to_addr}> Subject: {0.subject} {0.message}""" print(template.format(email))
import math def merge_sort(arr: list) -> list: if len(arr) < 2: return arr length = len(arr) middle = math.floor(length / 2) left = arr[0:middle] right = arr[middle:] return merge(merge_sort(left), merge_sort(right)) # left and right will always be ordered! def merge(left: list, right: list) -> list: results = [] while len(left) and len(right): if left[0] <= right[0]: results.append(left.pop(0)) else: results.append(right.pop(0)) # left or right is empty arr at this moment return results + left + right merge_sort_test_arr = [7, 8, 4, 5, 7, 8, 9, 1, 2, 3, 7, 8] print(merge_sort(merge_sort_test_arr)) print(merge_sort([1])) print(merge_sort([2, 1])) print(merge_sort([2, 1, 3])) # find median element from 2 sorted lists arr1 = [4, 6, 7, 3] arr2 = [2, 8, 9] def median_finder(array_1: list, array_2: list): array_1 = merge_sort(array_1) array_2 = merge_sort(array_2) counter = math.ceil( len(array_1 + array_2) / 2.0 ) results = [] while counter > 0: counter -= 1 if array_1[0] <= array_2[0]: results.append(array_1.pop(0)) else: results.append(array_2.pop(0)) return results[-1] print(median_finder(arr1, arr2))
class Property: def __init__(self, square_feet='', beds='', baths='', **kwargs): super().__init__(**kwargs) self.square_feet = square_feet self.num_bedrooms = beds self.num_baths = baths def display(self): print("PROPERTY DETAILS") print("================") print("square footage: {}".format(self.square_feet)) print("bedrooms: {}".format(self.num_bedrooms)) print("bathrooms: {}".format(self.num_baths)) print() @staticmethod def prompt_init(): return dict(square_feet=input("Enter the square feet: "), beds=input("Enter number of bedrooms: "), baths=input("Enter number of baths: "))
class CoffeeMachine: def __init__(self, water_amount, milk_amount, coffee_beans_amount, cups_amount, money): self.water = water_amount self.milk = milk_amount self.coffee = coffee_beans_amount self.cups = cups_amount self.money = money def __getitem__(self, item): return getattr(self, item) def __setitem__(self, key, value): return setattr(self, key, value) def __str__(self): return 'Machine bot v 0.1.7 alpha.' COFFEE_RECIPES = { # water, milk, coffee, cost 'espresso': {"water": 250, "milk": 0, "coffee": 16, "money": 4, "cups": 1}, 'latte': {"water": 350, "milk": 75, "coffee": 20, "money": 7, "cups": 1}, 'cappuccino': {"water": 200, "milk": 100, "coffee": 12, "money": 6, "cups": 1}, } def make_coffee(self, coffee_type): """ Makes coffee if possible, subtracts used resources from machine :param coffee_type:string """ if self.check_resources(coffee_type): for key, value in self.COFFEE_RECIPES[coffee_type].items(): if key == 'money': self[key] += value else: self[key] -= value # self.print_current_machine_resources() # self.machine_start_state() else: print('Not enough resources to make this coffee type. Sorry') # self.machine_start_state() def machine_start_state(self): self.print_current_machine_resources() while True: user_input = input('Write action (buy, fill, take):') if user_input in ['buy', 'fill', 'take']: self.execute_machine_command(user_input) def execute_machine_command(self, command): if command == 'buy': self.do_buy_coffee() elif command == 'fill': self.do_fill_machine() elif command == 'take': self.do_take_money_from_machine() else: self.machine_start_state() def print_current_machine_resources(self): print('\n') print('The coffee machine has:') print(f'{self.water} of water') print(f'{self.milk} of milk') print(f'{self.coffee} of coffee beans') print(f'{self.cups} of disposable cups') print(f'{self.money} of money') print('\n') def check_resources(self, coffee_type): resources_to_check = ['water', 'milk', 'coffee', 'cups'] for resource in resources_to_check: if self[resource] <= self.COFFEE_RECIPES[coffee_type][resource]: return False return True def do_buy_coffee(self): coffee_codes = { '1': 'espresso', '2': 'latte', '3': 'cappuccino' } # while True: user_input = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ') if user_input in coffee_codes.keys(): self.make_coffee(coffee_codes[user_input]) else: pass def do_fill_machine(self): try: self.water += int(input('Write how many ml of water do you want to add: ')) self.milk += int(input('Write how many ml of milk do you want to add: ')) self.coffee += int(input('Write how many grams of coffee beans do you want to add: ')) self.cups += int(input('Write how many disposable cups of coffee do you want to add: ')) # self.print_current_machine_resources() # self.machine_start_state() except Exception as e: print('RETARD') # self.machine_start_state() def do_take_money_from_machine(self): print('I gave you ${}'.format(self.money)) self.money = 0 # self.print_current_machine_resources() # self.machine_start_state() costa_ricca = CoffeeMachine(400, 540, 120, 9, 550) # costa_ricca.machine_start_state() def main(): while True: action = input('Write action (buy, fill, take, remaining, exit):') if action == 'buy': costa_ricca.do_buy_coffee() elif action == 'fill': costa_ricca.do_fill_machine() elif action == 'take': costa_ricca.do_take_money_from_machine() elif action == 'remaining': costa_ricca.print_current_machine_resources() elif action == 'exit': break else: raise ValueError(f'Unknown command {action}') if __name__ == '__main__': main()
# Code Listing #2 """ Thumbnail converter using producer-consumer architecture: 1. Producers are a specialized class of workers (threads) producing the data. They may receive the data from a specific source(s), or generate the data themselves. 2. Producers add the data to a shared synchronized queue. In Python, this queue is provided by the Queue class in the aptly named queue module. 3. Another set of specialized class of workers, namely consumers, wait on the queue to get (consume) the data. Once they get the data, they process it and produce the results. 4. The program comes to an end when the producers stop generating data and the consumers are starved of data. Techniques like timeouts, polling, or poison pills can be used to achieve this. When this happens, all threads exit, and the program completes. """ import threading import time import string import random import urllib.request from queue import Queue from PIL import Image class ThumbnailURL_Generator(threading.Thread): """ Worker class that generates image URLs """ def __init__(self, queue, sleep_time=1, ): self.sleep_time = sleep_time self.queue = queue # A flag for stopping self.flag = True # sizes self._sizes = (240, 320, 360, 480, 600, 720) # URL scheme self.url_template = 'https://dummyimage.com/%s/%s/%s.jpg' threading.Thread.__init__(self, name='url producer') def __str__(self): return 'Producer' def get_size(self): return '%dx%d' % (random.choice(self._sizes), random.choice(self._sizes)) @staticmethod def get_color(): return ''.join(random.sample(string.hexdigits[:-6], 3)) # We start a thread using its start method, though the overridden method in the Thread subclass is run. # This is because, in the parent Thread class, the start method sets up some state, # and then calls the run method internally. This is the right way to call the thread's run method. # It should never be called directly. def run(self): """ Main thread function """ while self.flag: # generate image URLs of random sizes and fg/bg colors url = self.url_template % (self.get_size(), ThumbnailURL_Generator.get_color(), ThumbnailURL_Generator.get_color()) # Add to queue print(self, 'Put', url) self.queue.put(url) time.sleep(self.sleep_time) def stop(self): """ Stop the thread """ self.flag = False class ThumbnailURL_Consumer(threading.Thread): """ Worker class that consumes URLs and generates thumbnails """ def __init__(self, queue): self.queue = queue self.flag = True threading.Thread.__init__(self, name='consumer') def __str__(self): return 'Consumer' def thumb_image(self, url, size=(64, 64), format='.png'): """ Save image thumbnails, given a URL """ im = Image.open(urllib.request.urlopen(url)) # filename is last part of URL minus extension + '.format' filename = url.split('/')[-1].split('.')[0] + '_thumb' + format im.thumbnail(size, Image.ANTIALIAS) im.save(filename) print(self, 'Saved', filename) def run(self): """ Main thread function """ while self.flag: url = self.queue.get() print(self, 'Got', url) self.thumb_image(url) def stop(self): """ Stop the thread """ self.flag = False self.join() if __name__ == '__main__': q = Queue(maxsize=200) producers, consumers = [], [] for i in range(2): t = ThumbnailURL_Generator(q) producers.append(t) t.start() for i in range(2): t = ThumbnailURL_Consumer(q) consumers.append(t) t.start()
def sum_two_smallest_numbers(numbers): min1 = 0 min2 = 0 min1 = min(array) array.remove(min1) min2 = min(array) numbers = min1 + min2 return (numbers)
class Solution: def numberOfSteps (self, num: int) -> int: step_count = 0 while(num > 0): #Check if number is even and divide by 2 if num%2 == 0: num = num//2 #Check if number is odd and subtract by 1 else: num = num - 1 step_count += 1 return step_count sol = Solution() print(sol.numberOfSteps(14))
class Solution: def fizzBuzz(self, n: int): result_arr = [] for val in range(1, n + 1): if val%3 == 0 and val%5 == 0: result_arr.append('FizzBuzz') elif val%3 == 0: result_arr.append('Fizz') elif val%5 == 0: result_arr.append('Buzz') else: result_arr.append(f'{val}') return result_arr sol = Solution() print(sol.fizzBuzz(15))
class Solution: def containsDuplicate(self, nums): charObj = {} for val in nums: if val in charObj: return True else: charObj[val] = 1 return False sol = Solution() print(sol.containsDuplicate([1,2,3,1]))
import unittest from index import sol class Testing(unittest.TestCase): #Check for input 'I speak Goat Latin' def test_toGoatLatin_input1(self): self.assertEqual(sol.toGoatLatin('I speak Goat Latin'), 'Imaa peaksmaaa oatGmaaaa atinLmaaaaa') #Check for input 'The quick brown fox jumped over the lazy dog' def test_toGoatLatin_input2(self): self.assertEqual(sol.toGoatLatin('The quick brown fox jumped over the lazy dog'), 'heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa') #Check for input 'Good morning' def test_toGoatLatin_input3(self): self.assertEqual(sol.toGoatLatin('Good morning'), 'oodGmaa orningmmaaa') if __name__ == '__main__': unittest.main()
import numpy as np import scipy.stats as ss def add_noise(X, noise, seed = None): """Adds Gaussian noise to a point cloud.""" np.random.seed(seed = seed) X_noise = np.random.normal(scale = noise, size = X.shape) return X + X_noise # =============================================================== # ----------------------- SHAPES IN 2D ------------------------ # =============================================================== def two_adjacent_circles(N, r = 1, noise = 0, seed = None): """Generates sample points of two circles with \ radius `r` and `1-r`.""" np.random.seed(seed = seed) s,t = np.random.uniform(0, 2*np.pi, [2, N // 2]) x = np.hstack([r*np.cos(s) + r, (1-r)*np.cos(t) + (1+r)]) y = np.hstack([r*np.sin(s), (1-r)*np.sin(t)]) X = np.vstack((x,y)).T X_noise = add_noise(X, noise, seed = seed) return X_noise def circle(N, noise = 0, seed = None): """Generates sample points of circle with \ radius 1 and gaussian noise with of scale `scale`.""" np.random.seed(seed=seed) t = np.random.uniform(0, 2*np.pi, size = N) x = np.cos(t) y = np.sin(t) X = np.vstack((x,y)).T X_noise = add_noise(X, noise, seed = seed) return X_noise def vonmises_circles(N, kappa, noise = 0, seed = None): """Generates von Mises distributed sample points on \ the of circle.""" np.random.seed(seed = seed) if kappa == 0: t = np.random.uniform(0, 2*np.pi, size = N) else: t = ss.vonmises(kappa = kappa).rvs(size = N) noise_x, noise_y = np.random.normal(scale = noise, size = [2, N]) x = np.cos(t) + noise_x y = np.sin(t) + noise_y X = np.vstack((x,y)).T X_noise = add_noise(X, noise, seed = seed) return X_noise def annulus(N, r, noise = 0, seed = None): """Generates sample points of a 2-dimensional \ Annulus with inner radius `r`. Outside radius is taken to be 1.""" np.random.seed(seed = seed) u,v = np.random.uniform(0, 1, [2,N]) phi = 2*np.pi*u r = np.sqrt((1-r**2)*v + r**2) x = r*np.cos(phi) y = r*np.sin(phi) X = np.vstack((x,y)).T X_noise = add_noise(X, noise, seed = seed) return X_noise def sinoidal_trajectory(N, shift, noise = 0, seed = None): """Generates sample points of a 2-dimensional \ ellipse generated by sin(t) and sin(t+s).""" t = np.random.uniform(0, 2*np.pi, N) x = np.sin(t) y = np.sin(t - shift) X = np.vstack((x,y)).T X_noise = add_noise(X, noise, seed = seed) return X_noise # =============================================================== # -------------------- SHAPES IN 3D -------------------------- # =============================================================== def cylinder(N, height, noise = 0, seed = None): """Generates sample points of a cylinder in 3D \ with unit radius and height `height`.""" np.random.seed(seed=seed) u,v = np.random.uniform(0, 1, [2,N]) phi = 2*np.pi*u x = np.cos(phi) y = np.sin(phi) z = np.random.uniform(0, height, N) X = np.vstack((x,y,z)).T X_noise = add_noise(X, noise, seed = seed) return X_noise def torus(N, r, noise = 0, seed = None): """Generates sample points of a cylinder in 3D \ with radius of revolution being 1 and outer radius 'r'""" np.random.seed(seed=seed) u,v = np.random.uniform(0, 2*np.pi, [2,N]) x = (1 + r*np.cos(v))*np.cos(u) y = (1 + r*np.cos(v))*np.sin(u) z = r*np.sin(v) X = np.vstack((x,y,z)).T X_noise = add_noise(X, noise, seed = seed) return X_noise # =============================================================== # ---------------- N-DIMENSIONAL SHAPES ---------------------- # =============================================================== def box(N, dim = 2, noise = 0, seed = None): """Generates sample points of a unit-box in dimenseion `dim`.""" np.random.seed(seed=seed) X = np.random.uniform(0, 2*np.pi, [N, dim]) X_noise = add_noise(X, noise, seed = seed) return X_noise def sphere(N, dim = 2, noise = 0, seed = None): """Generates sample points of a unit sphere in dimenseion `dim`. CAUTION: The parameter `dim` referes to the embedding dimension, not the intrinsic dimension of the sphere! """ np.random.seed(seed=seed) pre_X = np.random.normal(size = (N, dim)) X = (pre_X.T / np.linalg.norm(pre_X, axis=1)).T X_noise = add_noise(X, noise, seed = seed) return X_noise def _coordinates_to_pointcloud(*args): pass
r=int(input("radius is")) pi=3.142 A=pi*r*r print("area of the circle",A)
########################################################## # Exposureness # # This function measures the exposureness of the images. # ########################################################## import cv2 import numpy as np ############################################################################ # This function measures the exposureness of the image and returns the # # exposureness as a feature of the image for further use. # # # # input: image_paths: list of N elements containing image paths # # # # output: exposures: a N x D list of histograms of color distribution of # # the images. (N = number of image paths. D = 8) # ############################################################################ def exposureness(image_paths): exposures = [] for path in image_paths: img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) img = np.array(img) img = np.floor(img/16) histogram = np.histogram(img, bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) histogram = histogram[0] / np.linalg.norm(histogram[0]) if exposures == []: exposures = [histogram] else: exposures = np.concatenate((exposures, [histogram]), axis = 0) return exposures ################################################### # Test # # This is for testing the function and # # demonstrating how to use the function. # ################################################### if __name__ == '__main__': paths = [] path = '../data/good/a-house-near-the-lake-shore-3218137.jpg' paths.append(path) paths.append('../data/bad/a-house-near-the-lake-shore-3218137-dark.jpg') paths.append('../data/bad/a-house-near-the-lake-shore-3218137-bright.jpg') exposures = exposureness(paths) print(exposures) print ("complete")
import openpyxl import win32com.client as win32 from NumberGenerator import NumberGenerator import datetime import time import sched import sys class Email: def __init__(self): self.book = 0 self.emails = "" # Generate the numbers and insert them into the numbers array in the order we want them to appear in the game num = NumberGenerator() num.generate_numbers() num.fill_lists() num.view_numbers(num.numbers) self.numbers = [num.first, num.second, num.third, num.fourth, num.fifth, num.sixth] # Get the emails from a spreadsheet and into a string, ready to be sent def get_emails(self, path_to_excel): self.book = openpyxl.load_workbook(path_to_excel) sheet = self.book.active email_string = '' # Loop through the names in the spreadsheet, tidying them up for row in sheet.iter_rows('A{}:A{}'.format(sheet.min_row, sheet.max_row)): for cell in row: email = cell.value.replace('<', '') email = email.replace('>', '') email = email.strip() if email[-1] != ';': email = email + ';' email_string += email self.emails = email_string def send_email(self, subject, round_number): # win32 is an old-ish library, allows the program to interact with any Microsoft apps open e.g. Outlook # There is no login here, it will simply use the account that's using the current instance of Outlook to send the emails #so the emails will look like they came from you outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.Bcc = self.emails mail.Subject = subject # Convoluted way of having the signature picture at the top of the bingo emails # You'll have to make the pictures yourself and paste the link to it from your directory here attachment = mail.Attachments.Add("PATH-TO-PICTURE") attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyId1") mail.HTMLBody = "<html><body>Test image <img src=""cid:MyId1""></body></html>" #mail.HTMLBody = """ # <html> # <head></head> # <body> # <font color="DarkBlue" size=-1 face="Arial"> # <p style="text-align:center;"><img src="cid:MyId1" alt="Logo"></p> # <p>Hello everyone,</p> # <p> # Just a quick reminder that tomorrow Bingo will be on, raising money for CHARITY-NAME, so don't forget your change!<br/> # Your sellers on each floor will be as follows:<br/> # <ul style="list-style-type:disc"> # <li>Top Floor: ENTER-NAME</li> # <li>First Floor: ENTER-NAME</li> # <li>Bottom Floor: ENTER-NAME</li> # </ul> # </p> # <p>Good luck to everyone!</p> # <p>Many thanks,<br/>ENTER-NAME</p> # </body> # </html> # """ mail.HTMLBody = """ <html> <head></head> <body> <font color="DarkBlue" size=-1 face="Arial"> <p style="text-align:center;"><img src="cid:MyId1" alt="Logo"></p> {0} <h5>RULES</h5> <ul style="list-style-type:disc"> <li>£1 per ticket</li> <liFirst round begins @ 1.30pm, Thursday 5th April</li> <li>1 round every 30 mins</li> <li>13 numbers per round</li> <li>There will be no more than 6 rounds</li> <li>If there are multiple winners in the same round, one winner will be selected on the order of the numbers in the round</li> <li>If no winner is found after the 6 rounds, there will be a rollover to the next week</li> <li>You have half an hour between rounds to check your ticket and call BINGO</li> <li>If you have BINGO and fail to call it before the next round starts, you may lose your chance to claim your winning ticket</li> <li>You need a full house to win. (EVERY number on your ticket must have been called)</li> <li>Reply back to this email address with “BINGO” as soon as you get a full house</li> </ul> </font> </body> </html> """.format(self.format_numbers(round_number)) mail.Send() # Format the numbers to fit in with the email def format_numbers(self, round): email_numbers = "" for i in range(0, round): round_numbers = str(self.numbers[i]) round_numbers = round_numbers.replace(", ", " - ") round_numbers = round_numbers.replace("[", "") round_numbers = round_numbers.replace("]", "") email_numbers = """<p style="text-align:center;color:black;font-size:30px">{0}</p>""".format(round_numbers) + email_numbers email_numbers = """<h4 style="text-align:center;text-decoration: underline;">Round {0}</h4>""".format(i + 1) + email_numbers return email_numbers # Initialise the email email = Email() # Make sure you have an up-to-date mailing list email.get_emails("BingoMailingList.xlsx") # Scheduler class allows you to keep the program running, and every x seconds it will perform an operation # In this example, every 1800 seconds (30 minutes) an email is sent out to everyone scheduler = sched.scheduler(time.time, time.sleep) scheduler.enter(0, 1, email.send_email, ("Bingo Round 1", 1,)) scheduler.enter(1800, 1, email.send_email, ("Bingo Round 2", 2,)) scheduler.enter(3600, 1, email.send_email, ("Bingo Round 3", 3,)) scheduler.enter(5400, 1, email.send_email, ("Bingo Round 4", 4,)) scheduler.enter(7200, 1, email.send_email, ("Bingo Round 5", 5,)) scheduler.enter(9000, 1, email.send_email, ("Bingo Round 6", 6,)) scheduler.run() #print(email.emails)
""" Author : Sahil Ajmera Summer class """ from math import * from PriorityQueue import PQ class Summer: __slots__ = 'path_color' def __init__(self): self.path_color = (255, 0, 0) def getNeighbour(self, x, y, rows_max, columns_max, pixels): """ List of neighbors of a particular x and y :param x:Input x :param y: Input y :param end_columns:Max value that can be attained by a y :param end_rows: Max value that can be attained by a x :return: list of neighbors of a particular x and y """ list_of_neighbours = [] end_columns = columns_max end_rows = rows_max neighbours = [(1, 0), (0, 1), (1, 1), (-1, 1), (1, -1), (-1, -1), (0, -1), (-1, 0)] for values in neighbours: pt_1_x = x + values[0] pt_1_y = y + values[1] if pt_1_x >= 0 and\ pt_1_x < end_rows and\ pt_1_y >= 0 and\ pt_1_y < end_columns and\ pixels[pt_1_x, pt_1_y] != (205, 0, 101) and\ pt_1_x < end_columns and\ pt_1_y < end_rows: list_of_neighbours.append((pt_1_x, pt_1_y)) return list_of_neighbours def search_for_path(self, obj, start,final): """ Final path calculating function :param start:Start point :param final:Point to be reached :return:Final path from Start to final """ # To keep track of g values cost_so_far = {} # Priority queue initialization s = PQ() # To keep track of predecessors to help in backtracking predecessor = {} # Insert start point into the priority queue s.put(start, 0) # g value of start is 0 cost_so_far[start] = 0 # f value of start is 0 + h(start) f_value = {} f_value[start] = obj.calculateh(start[0], start[1], final[0], final[1]) final_path_list = [] # Exiting condition when no path is found while not s.empty(): # Fetch the element in the priority queue with the lowest g(n) + h(n) value point_explored = s.get() # To keep the final path final_path_list = [] # Exiting condition for when there exists a path between the start point and end point supplied to this function if point_explored == final: #Backtracking to find the actual path from the start point to the final point curr = final while curr != start: final_path_list.insert(0, curr) curr = predecessor[curr] final_path_list.insert(0, start) break # Get the neighbours of the element fetched from the priority queue neighbour_list = self.getNeighbour(int(point_explored[0]),int(point_explored[1]),obj.elevation_end_rows,obj.elevation_end_columns, obj.pixels) # Loop through all the neighbours of fetched element for neighbour in neighbour_list: # Calculate g value for the neighbour calculated_g_value = cost_so_far[point_explored] + obj.calculateg(neighbour[0], neighbour[1], point_explored[0], point_explored[1]) # Calculate h value for the neighbour calculated_h_value = obj.calculateh(neighbour[0], neighbour[1], final[0], final[1]) # If neighbour not already in queue or neighbour calculated f value less than than its tracked f value till now if neighbour not in cost_so_far or \ calculated_g_value + calculated_h_value < f_value[neighbour]: cost_so_far[neighbour] = calculated_g_value f_value[neighbour] = calculated_g_value + calculated_h_value s.put(neighbour, calculated_g_value + calculated_h_value) predecessor[neighbour] = point_explored return final_path_list def calulate_dist(self, object_orien, final_path): """ Calculates distance of final_path_found :param final_path:final path obtained by traversal :return:None """ dist = 0 for index in range(len(final_path) - 1): dist = dist + self.path_length(object_orien, final_path[index], final_path[index + 1]) print("Distance:"+str(dist)) def path_length(self, object_orien, start_point, end_point): """ Returns the path_length :param object_orien:orienteering class object :param start_point:point x1,y1,z1 :param end_point:point x2,y2,z2 :return:distance between x1,y1,z1 and x2,y2,z2 """ return sqrt((start_point[0]-end_point[0])**2 + (start_point[0]-end_point[1])**2 + (float(object_orien.elevation_info[start_point[0]][start_point[1]])-float(object_orien.elevation_info[end_point[0]][end_point[1]]))**2)
#!/usr/bin/python import sys from classInflationCalc import * def get_value(myPrompt): while True: try: myValue = float(input(myPrompt)) except Exception: print "Please enter correct value or simple 0" continue else: break return myValue print "Let's calculate the effect of yearly inflation on your monthly budget.\n" Amount = get_value(" How much is the monthly budget in today's dollars? ") Period = get_value(" How long is the period to calculate inflation effect? ") Rate = get_value(" What's the expected inflation rate? ") x = inflation_calc(Amount, Period, Rate, 'yes') x.annual_calc() #print "\nAt {}% inflation rate, the original ${} budget should grow, annually compounded, to:".format(Rate, int(Amount))
#!/usr/bin/env python #coding=utf-8 ''' 功能: 删除多余的 jpg 或 xml 文件 ''' import os import sys # jpg_path = "JPEGImages" # xml_path = "Annotations" jpg_path = "jpg" xml_path = "xml" xmls = os.listdir(xml_path) jpgs = os.listdir(jpg_path) if len(xmls) < len(jpgs): print "jpgs is odd..." for jpg in jpgs: pos = jpg.find(".jpg") xml_right = jpg[:pos]+".xml" if xml_right not in xmls: print "remove %s..." % xml_right os.remove(os.path.join(xml_path, xml_right)) elif len(xmls) > len(jpgs): print "xmls is odd..." for xml in xmls: pos = xml.find(".xml") jpg_right = xml[:pos]+".jpg" if jpg_right not in jpgs: print "remove %s..." % xml os.remove(os.path.join(jpg_path, jpg_right))
customer_age = int(input("How old is the customer? ")) cost = 0 if customer_age <= 3: cost = 0 print("Your cost for a customer who is " + str(customer_age) + " years old") print("is $" + format(cost, ",.2f")) else: if 4 <= customer_age <= 11: cost = .99 * customer_age print("Your cost for a customer who is " + str(customer_age) + " years old") print("is $" + format(cost, ",.2f")) else: if 12 <= customer_age <= 61: cost = 12.89 print("Your cost for a customer who is " + str(customer_age) + " years old") print("is $" + format(cost, ",.2f")) else: print("The price is 9.89")
# -*- coding: utf-8 -*- """ Created on Tue Feb 18 20:38:59 2020 @author: Dora """ name = ['Erina','Queenie','Hank','Sana','Yuna',] verb = ['玩','看','寫','摺','吃'] noun = ['Jacket','Computer','Tape','Horse','Sibling'] import random def random_list(list1): word = random.sample(list1,1)[0] return word def random_sentence(name,verb,noun): sentence = random_list(name) + random_list(verb) + random_list(noun) return sentence for _ in range(10): print(random_sentence(name,verb,noun))
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 19:06:13 2020 @author: Dora """ import random answer = random.randint(1,10) times=0 while times < 5: guess = int(input("what number do you guess?")) times= times + 1 if guess < 1 or guess > 10: print("try again") else: if answer < guess: if times == 5: print("guess more than 5 times") else: print("guess smaller") elif answer > guess: if times == 5: print ("guess more than 5 times") else: print("guess bigger") else : print("you win") print("you guess ",times,"times") break
''' Created For Mega Projects Repository Problem: Pig Latin is a game of alterations played on the English language game. To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules. @author: Sambit ''' sentence = raw_input("Enter a sentence \n") for word in sentence.split(): if word[0] in "aeiou": print word + "way" else: print word[1:] + "-" + word[0] + "ay"
#working with shapes #triangle print(" /|") print(" / |") print(" / |") print(" / |") print(" /____|") #square shape1 = "_" shape2 = "|" #rectangle print(shape1 * 4) for i in shape2: print(i + ' ' + i) print(i + ' ' + i) print(i + ' ' + i) print(i + ' ' + i) print(shape1*4)
from square import Square from piece import Piece import itertools import pygame as pg from move import Move from constants import WHITE, BLACK, SQUARES class Board: def __init__(self, xAxis, yAxis): self.xAxis = xAxis self.yAxis = yAxis self.width = len(xAxis) self.height = len(yAxis) self.squares = self.initialise_squares() self.pieces = self.initialise_pieces() def initialise_squares(self): squareNames = [] for y in range(self.height): for x in range(self.width): squareNames.append(str(self.xAxis[x]) + str(self.yAxis[y])) squares = [Square(str(squareNames[s])) for s in range(SQUARES)] return squares def initialise_pieces(self): colours = itertools.cycle((WHITE, BLACK)) pawnNames = itertools.cycle(("wp","bp")) rookNames = itertools.cycle(("wR","bR")) knightNames = itertools.cycle(("wN","bN")) bishopNames = itertools.cycle(("wB","bB")) queenNames = itertools.cycle(("wQ","bQ")) kingNames = itertools.cycle(("wK","bK")) pawnStarts = ["A2", "A7", "B2", "B7", "C2", "C7", "D2", "D7", "E2", "E7", "F2", "F7", "G2", "G7", "H2", "H7"] rookStarts = ["A1", "A8", "H1", "H8"] knightStarts = ["B1", "B8", "G1", "G8"] bishopStarts = ["C1", "C8", "F1", "F8"] queenStarts = ["D1", "D8"] kingStarts = ["E1", "E8"] pawns = [Piece("PAWN", next(colours), next(pawnNames), pawnStarts[x]) for x in range(0, 16)] rooks = [Piece("ROOK", next(colours), next(rookNames), rookStarts[x]) for x in range(0, 4)] knights = [Piece("KNIGHT", next(colours), next(knightNames), knightStarts[x]) for x in range(0, 4)] bishops = [Piece("BISHOP", next(colours), next(bishopNames), bishopStarts[x]) for x in range(0, 4)] queens = [Piece("QUEEN", next(colours), next(queenNames), queenStarts[x]) for x in range(0, 2)] kings = [Piece("KING", next(colours), next(kingNames), kingStarts[x]) for x in range(0, 2)] pieces = pawns + rooks + knights + bishops + queens + kings loadImages(pieces) for square in self.squares: for piece in pieces: if square.name == piece.squareName: piece.square = square square.occupant = piece return pieces def setup_pieces(self): return 0 def defaultBoardState(self): return 0 def getPiece(self, currentSquare): for square in self.squares: if square.name == currentSquare: piece = self.getOccupant(square) if piece: break return piece def getOccupant(self, square): for piece in self.pieces: if square.occupant == piece: return piece def getPieceToCapture(self, moveTo): for square in self.squares: if square.name != moveTo: continue if square.isOccupied(): pieceToCapture = square.getOccupant() else: pieceToCapture = None return pieceToCapture def removeCapturedPiece(self, capturedPiece): self.pieces.remove(capturedPiece) def makeMove(self, move): pieceToMove = self.getPiece(move.moveFrom) # TODO jj - needs something to check move is valid for the type of piece validMove = True if pieceToMove: # Is the square we are moving to occupied? pieceToCapture = self.getPieceToCapture(move.moveTo) if pieceToCapture: # If the pieces are of opposing colours the piece is captured if pieceToCapture.colour != pieceToMove.colour: pieceToCapture.captured = True # If the pieces are of the same colour the move is invalid if pieceToCapture.colour == pieceToMove.colour: validMove = False if validMove: # Clear the old square for square in self.squares: if square.occupant == pieceToMove: square.occupant = None pieceToMove.squareName = move.moveTo if pieceToCapture: self.removeCapturedPiece(pieceToCapture) # Update piece and square lists for square in self.squares: for piece in self.pieces: if square.name == piece.squareName: piece.square = square square.occupant = piece def loadImages(pieces): for piece in pieces: piece.image = pg.image.load("images/" + piece.name + ".png")
class Runner: def __init__(self, program): self.program = program self.i = 0 def read(self): op = self.program[self.i] self.i += 1 return op def peek(self): return self.program[self.i] def run(self): while True: opcode = self.read() if opcode == 1: a, b, c = self.read(), self.read(), self.read() self.program[c] = self.program[a] + self.program[b] elif opcode == 2: a, b, c = self.read(), self.read(), self.read() self.program[c] = self.program[a] * self.program[b] elif opcode == 99: return def solution(): with open("input", "r") as f: inp = [int(x) for x in f.read().strip().split(",")] # Day 1 p = [x for x in inp] p[1] = 12 p[2] = 2 r = Runner(p) r.run() print(r.program[0]) # Day 2 for noun in range(100): for verb in range(100): p = [x for x in inp] p[1] = noun p[2] = verb # Day 1 r = Runner(p) r.run() if r.program[0] == 19690720: print(noun * 100 + verb) return if __name__ == '__main__': solution()
import string import random #This function generated passwords that contain numbers, uppercase and lowercase letters, and other characters with a length between 4 and 16 characters. #The purpose is to have high level security passwords def generatePassword(): #characters variable will store letters, numbers and special characters characters = string.ascii_letters + string.digits + string.punctuation #Password variable contains the characters concatenated generated between 4 and 16 characters by random way password = "".join(random.choice(characters) for i in range(random.randint(4,16))) #print the password generated print ("The password generated is: ", password) generatePassword()
1.Question 1 Q1)When Python is running in the interactive mode and displaying the chevron prompt (>>>) - what question is Python asking you? 1)What is your favourite color? 2)What Python script would you like me to run? 3)What is the next machine language instruction to run? 4)What Python statement would you like me to run? Answer: 2)What Python script would you like me to run? 2.Question 2 What will the following program print out: >>> x = 15 >>> x = x + 5 >>> print(x) 1)20 2)5 3)15 4)"print x" 5)x + 5 Answer: 1)20 3.Question 3 Python scripts (files) have names that end with: 1).py 2).exe 3).png 4).doc Answer: 1).py 4.Question 4 Which of these words is a reserved word in Python ? 1)for 2)names 3)pizza 4)payroll Answer: 1)for 5.Question 5 What is the proper way to say “good-bye” to Python? 1)// stop 2)while 3)#EXIT 4)quit() Answer: 4)quit() 6.Question 6 Which of the parts of a computer actually executes the program instructions? 1)Input/Output Devices 2)Secondary Memory 3)Main Memory 4)Central Processing Unit Answer:4)Central Processing Unit 7.Question 7 What is "code" in the context of this course? 1)A sequence of instructions in a programming language 2)A set of rules that govern the style of programs 3)A way to encrypt data during World War II 4)A password we use to unlock Python features Answer:1)A sequence of instructions in a programming language 8.Question 8 A USB memory stick is an example of which of the following components of computer architecture? 1)Secondary Memory 2)Main Memory 3)Central Processing Unit 4)Output Device Answer:1)Secondary Memory 9.Question 9 What is the best way to think about a "Syntax Error" while programming? 1)The computer has used GPS to find your location and hates everyone from your town 2)The computer is overheating and just wants you to stop to let it cool down 3)The computer did not understand the statement that you entered 4)The computer needs to have its software upgraded Answer:3)The computer did not understand the statement that you entered 10.Question 10 Which of the following is not one of the programming patterns covered in Chapter 1? 1)Sequential Steps 2)Repeated Steps 3)Conditional Steps 4)Random steps Answer: 4)Random steps
"""The string defining the points of the quadrilateral has the next form: "#LB1:1#RB4:1#LT1:3#RT4:3" LB - Left Bottom point LT - Left Top point RT - Right Top point RB - Right Bottom point numbers after letters are the coordinates of a point. Write a function figure_perimetr() that calculates the perimeter of a quadrilateral""" import re def figure_perimetr(data): coordinates_dict = {} p = 0 for coordinate in re.findall(r'\w{2}\d:\d', data): point_name = re.findall(r'\w{2}', coordinate)[0] point = re.findall(r'\d', coordinate) coordinates_dict[point_name] = point keys = coordinates_dict.keys() opposite_point = "" for key in keys: if key == "LB": opposite_point = "RB" elif key == "LT": opposite_point = "RT" elif key == "RB": opposite_point = "RT" else: key = "LB" opposite_point = "LT" xy1 = coordinates_dict.get(key) xy2 = coordinates_dict.get(opposite_point) p += ((int(xy2[0]) - int(xy1[0])) ** 2 + (int(xy2[1]) - int(xy1[1])) ** 2) ** 0.5 return p
"""Imagine you are creating an application that shows the data about all different types of vehicles present. It takes the data from APIs of different vehicle organizations in XML format and then displays the information. But suppose at some time you want to upgrade your application with a Machine Learning algorithms that work beautifully on the data and fetch the important data only. But there is a problem, it takes data in JSON format only. It will be a really poor approach to make changes in Machine Learning Algorithm so that it will take data in XML format. For solving the problem we defined above, you can use Adapter Method that helps by creating an Adapter object. To use an adapter in your code: Client should make a request to the adapter by calling a method on it using the target interface. Using the Adaptee interface, the Adapter should translate that request on the adaptee. Result of the call is received the client and he/she is unaware of the presence of the Adapter’s presence.""" class MotorCycle: """Class for MotorCycle""" def __init__(self): self.name = "MotorCycle" def TwoWheeler(self): return "TwoWheeler" class Truck: def __init__(self): self.name = "Truck" def EightWheeler(self): return "EightWheeler" class Car: def __init__(self): self.name = "Car" def FourWheeler(self): return "FourWheeler" class Adapter: """ Adapts an object by replacing methods. Usage: motorCycle = MotorCycle() motorCycle = Adapter(motorCycle, wheels = motorCycle.TwoWheeler) """ def __init__(self, obj, **adapted_methods): """We set the adapted methods in the object's dict""" self._object = obj self.__dict__.update(adapted_methods) def __getattr__(self, attr): return getattr(self._object, attr) def original_dict(self): return self.__dict__
"""'s3ooOOooDy' has exams. He wants to study hard this time. He has an array of studying hours per day for the previous exams. He wants to know the length of the maximum non-decreasing contiguous subarray of the studying days, to study as much before his current exams. Example: For a = [2,2,1,3,4,1] the answer is 3. [input] array.integer a The number of hours he studied each day. [output] integer The length of the maximum non-decreasing contiguous subarray. """ def studying_hours(a): day_counter = 0 studying_hours = a[0] subbarray_length = [] for element in a: if element >= studying_hours: studying_hours = element day_counter+=1 else: subbarray_length.append(day_counter) day_counter = 1 studying_hours = element subbarray_length.append(day_counter) return max(subbarray_length)
"""Write the function day_of_week(day) whose input parameter is a number or string representation of number. The function returns the corresponding day of the week if the input parameter is in the range of 1 to 7, namely · in the case when the input parameter is 5 the function should be displayed the message – "Friday" · in the case when the input parameter is not in the range of 1 to 7 the function should be displayed the message – "There is no such day of the week! Please try again." · in the case of incorrect data the function should be displayed the message - "You did not enter a number! Please try again." Note: in the function you must use the "try except" construct. Function example: day_of_week(2) # output: "Tuesday" day_of_week(11) # output: "There is no such day of the week! Please try again." day_of_week("Monday") # output: "You did not enter a number! Please try again.""" def day_of_week(day): days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] try: if day == 0 or day == "6": raise IndexError else: return days_of_week[day - 1] except IndexError: return f"There is no such day of the week! Please try again." except TypeError: return f"You did not enter a number! Please try again."
"""In user.json file we have information about users in format [{“id”: 1, “name”: “userName”, “department_id”: 1}, ...], in file department.json are information about departments in format: [{“id”: 1, “name”: “departmentName”}, ...]. Function user_with_department(csv_file, user_json, department_json) should read from json files information and create csv file in format: header line - user, department next lines : <userName>, <departmentName> If file department.json doesn't contain department with department_id from user.json we generate DepartmentName exception. Create appropriate json-schemas for user and department. If schema for user or department doesn't satisfy formats described above we should generate InvalidInstanceError exception To validate instances create function validate_json(data, schema)""" import json import jsonschema import csv def unpack_json(file): import json with open(file) as json_file: data = json.load(json_file) return data def validate_json(data, schema, data_type): from jsonschema import validate try: validate(data, schema) except jsonschema.exceptions.ValidationError: raise InvalidInstanceError(data_type) def user_with_department(csv_file, user_json, department_json): schema_user = { "type": "object", "properties": { "id": {"type": "number"}, "name": {"type": "string"}, "department_id": {"type": "number"}, }, "required": ["department_id", "name", "id"] } schema_dep = { "type": "object", "properties": { "id": {"type": "number"}, "name": {"type": "string"}, }, "required": ["name", "id"] } user_data = unpack_json(user_json) department_data = unpack_json(department_json) try: with open(csv_file, mode="w") as csv_result: headers = {"name": None, "department": None} writer = csv.writer(csv_result, delimiter=",") writer.writerow(headers.keys()) for each in user_data: validate_json(each, schema_user, "user") headers["name"] = each["name"] dep_id = each["department_id"] dep_id_check = False for el in department_data: validate_json(el, schema_dep, "department") if el["id"] == dep_id: headers["department"] = el["name"] writer.writerow(headers.values()) dep_id_check = True if not dep_id_check: raise DepartmentName(dep_id) except DepartmentName as e: print(e) except InvalidInstanceError as b: print(b) class DepartmentName(Exception): def __init__(self, dep_id): self.dep_id = dep_id def __str__(self): return f"Department with id {self.dep_id} doesn't exists" class InvalidInstanceError(Exception): def __init__(self, data_type): self.data_type = data_type def __str__(self): return f"Error in {self.data_type} schema"
import matplotlib.pyplot as plt from pandas.plotting import scatter_matrix def explore_data(data): data.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4, s=data["population"]/100, label="population", figsize=(10, 7), c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True) plt.legend() plt.show() print(data.corr()) attributes = ["median_house_value", "median_income", "total_rooms", "housing_median_age"] scatter_matrix(data[attributes], figsize=(12, 8)) data.plot(kind="scatter", x="median_income", y="median_house_value", alpha=0.1)
""" 题目: 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 Longest Common Prefix """ class Solution: def longestCommonPrefix(self,strs): len0 = len(strs) if len0 == 0:#判断strs是否为空 return '' list_len = []#初始化存放每个子串的长度 # 找出最短的字符串长度min_len for i in range(len0): list_len.append(len(strs[i])) list_len.sort()#升序排序 # 取出最短的子串com_str # 我这里是直接取第一个子串的前min_len com_str = strs[0][0:list_len[0]]#直接取第一个子串的前min_len b0 = com_str for s in strs:#遍历strs子元素 for i in range(list_len[0]):#比较子元素与com_str,找出最长公共前缀 if s[i] != com_str[i]:# 判断到有不等的地方 a0 = s[0:i] if len(b0) >= len(a0):# 上一个最长公共前缀是否比现在长 b0 = a0 return b0 s = Solution() a = s.longestCommonPrefix(["flower","flow","flight"]) print(a) # 大牛方法 """ 通过zip(*strs)将上述list分解为下面的元组,然后通过for循环,迭代取值,取出每个元组, 并通过set将每个元组进行合并,我们知道set中不会出现相同的数,也就是三个字符直接合并后为1个,则表示为相同字符,否则不相同,直接退出循环即可。 strs=["flower","flow","flight"] 通过zip可分解为: ('f', 'f', 'f') ('l', 'l', 'l') ('o', 'o', 'i') ............... """ class Solution: def longestCommonPrefix(self, strs): res = ''#初始化最长公共前缀 if len(strs) == 0: return '' # zip()函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表 for each in zip(*strs):#对每个子元素的每个字母进行遍历 # 利用集合创建一个无序不重复元素集 if len(set(each)) == 1:#若每个子元素的该字母为公共字母,则取集合后长度为1,则将该字母添加到res中 res += each[0] else: return res return res s = Solution() a = s.longestCommonPrefix(["flower","flow","flight"]) print(a)
''' 基于select方法的IO多路复用网络并发 重点代码!! ''' from select import select from socket import * HOST = "0.0.0.0" PORT = 2021 ADDR = (HOST, PORT) def main(): sock = socket() sock.bind(ADDR) sock.listen(5) print("listen the port %d" % PORT) sock.setblocking(False) rlist = [sock] wlist = [] xlist = [] # 循环接收客户端连接 while True: rs, ws, xs = select(rlist, wlist, xlist) # 逐个取值,分情况讨论 for r in rs: if r is sock: # 如果拿出来的r是sock类型 connfd, addr = r.accept() # 连接客户端 print("Connect from", addr) sock.setblocking(False) # 将客户端套接字添加到监控列表 rlist.append(connfd) # 将客户端添加到select监控中 else: data = r.recv(1024).decode() # 客户端退出 if not data: rlist.remove(r) # 删除监控列表中已退出的客户端 r.close() continue print(data) r.send(b"OK") if __name__ == '__main__': main()
# 필요한 모듈 import import socket import random # multiply와 add에 따른 숫자를 계산하는 함수 def instruction(num, inst): i = random.randint(-1, 4) if inst == 'multiply': return num * i elif inst == 'add': return num + i TCP_IP = '10.0.2.15' TCP_PORT = 5001 # 3개의 client를 허용한다. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((TCP_IP, TCP_PORT)) sock.listen(3) # client의 정보를 출력 conn1, addr1 = sock.accept() print('Connection address 1 : ' + str(addr1)) conn2, addr2 = sock.accept() print('Connection address 2 : ' + str(addr2)) conn3, addr3 = sock.accept() print('Connection address 3 : ' + str(addr3)) # 3개의 클라이언트가 접속하면 준비가 되었다는 메시지를 클라이언트에 전송 message = "Okay... All players have gathered. Start the game.\n" conn1.send(message.encode()) conn2.send(message.encode()) conn3.send(message.encode()) while True: # 1~100의 난수를 10개 만들에 리스트에 저장 number = [random.randint(1, 100) for i in range(10)] # 클라이언트로부터 숫자를 입력받기 위한 안내 메시지 생성 message = "Please select 1 number from 1 to 10." # 클라이언트로부터 준비되었다는 것을 recv를 통해 확인 conn1.recv(1024) # 이전에 생성한 메시지 전송 conn1.send(message.encode()) # 클라이언트로부터 숫자를 수신 num1 = conn1.recv(1024) # 만들어준 난수를 리스트에서 가져와 클라이언트로 전송 num1 = number[int(num1.decode()) - 1] conn1.send(str(num1).encode()) # 클라이언트로부터 준비되었다는 것을 recv를 통해 확인 conn2.recv(1024) # 이전에 생성한 메시지 전송 conn2.send(message.encode()) # 클라이언트로부터 숫자를 수신 num2 = conn2.recv(1024) # 만들어준 난수를 리스트에서 가져와 클라이언트로 전송 num2 = number[int(num2.decode()) - 1] conn2.send(str(num2).encode()) # 클라이언트로부터 준비되었다는 것을 recv를 통해 확인 conn3.recv(1024) # 이전에 생성한 메시지 전송 conn3.send(message.encode()) # 클라이언트로부터 숫자를 수신 num3 = conn3.recv(1024) # 만들어준 난수를 리스트에서 가져와 클라이언트로 전송 num3 = number[int(num3.decode()) - 1] conn3.send(str(num3).encode()) # 클라이언트로부터 연산을 입력받기 위한 안내 메시지 생성 message = "Do you want multiply or add...?" # 안내메시지를 송신하고 연산을 클라이언트로부터 수신 conn1.send(message.encode()) instruction1 = conn1.recv(1024).decode() # instruction 함수를 이용해 연산값 저장 result1 = instruction(num1, instruction1) # 안내메시지를 송신하고 연산을 클라이언트로부터 수신 conn2.send(message.encode()) instruction2 = conn2.recv(1024).decode() # instruction 함수를 이용해 연산값 저장 result2 = instruction(num2, instruction2) # 안내메시지를 송신하고 연산을 클라이언트로부터 수신 conn3.send(message.encode()) instruction3 = conn3.recv(1024).decode() # instruction 함수를 이용해 연산값 저장 result3 = instruction(num3, instruction3) # 조건을 설정하고 알맞는 메시지를 송신 if result1 > result2: if result1 > result3: conn1.send('Congratulations. Wou won!'.encode()) conn2.send('Unfortunately, you have been defeated.'.encode()) conn3.send('Unfortunately, you have been defeated.'.encode()) else: conn3.send('Congratulations. Wou won!'.encode()) conn1.send('Unfortunately, you have been defeated.'.encode()) conn2.send('Unfortunately, you have been defeated.'.encode()) else: if result2 > result3: conn2.send('Congratulations. Wou won!'.encode()) conn1.send('Unfortunately, you have been defeated.'.encode()) conn3.send('Unfortunately, you have been defeated.'.encode()) else: conn3.send('Congratulations. Wou won!'.encode()) conn1.send('Unfortunately, you have been defeated.'.encode()) conn2.send('Unfortunately, you have been defeated.'.encode()) conn1.close() conn2.close() conn3.close()
''' Faça um programa para calcular a situação de um aluno. O programa deve calcular a média das duas avaliações do aluno e apresentar: A média alcançada, arredondada para uma casa decimal (ex., "7.5") A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; A mensagem "Reprovado", se a média for menor do que sete; A mensagem "Aprovado com Distinção", se a média for igual a dez. Entrada: 7 Saida: Média: 7.8 8.5 Aprovado ''' nota1 = float(input()) nota2 = float(input()) media = (nota1 + nota2) / 2 print("Média: %.1f" % media) if media == 10 : print("Aprovado com Distinção") elif media >= 7 : print("Aprovado") else: print("Reprovado")
# Assumption : Array is sorted def binary_search(arr, item, start, end): mid = int((start + end) / 2) if start > end: return -1 elif arr[mid] == item: return mid elif arr[mid] > item: return binary_search(arr, item, start, mid - 1) else: return binary_search(arr, item, mid + 1, end) arr = [1, 2, 3, 4, 5] index = binary_search(arr, 5, 0, len(arr) - 1) if index >= 0: print("Position : {}".format(index + 1)) else: print("Not found !")
# Dutch National Flag problem : Segregate numbers 0, 1, 2 def segregate_numbers(arr): m = 0 j = len(arr) - 1 i = 0 while i <= j: if arr[i] == 0: swap(arr, i, m) i += 1 m += 1 elif arr[i] == 1: i += 1 else: while arr[j] == 2: j = j - 1 if i < j: swap(arr, i, j) def swap(arr, i, j): temp = arr[j] arr[j] = arr[i] arr[i] = temp arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] segregate_numbers(arr) print(arr)
def find_next_greater_element(arr): print("Input Array : {}".format(arr)) stack = [] for i in arr: while len(stack) > 0 and stack[len(stack) - 1] < i: print("Next Greater element for {} is {} ".format(stack.pop(), i)) stack.append(i) while len(stack) != 0: print("Next Greater element for {} Doesn't exist ".format(stack.pop())) arr = [1, 2, 3, 4, 5] find_next_greater_element(arr)
num=int(input("enter a number:")) print(num) if X > 0 and y > 0: print("quadrant:1") elif x > 0 and y < 0: print("quadrant 4") elif x > 0 and y < 0: print("quadrant 3") else: print("quadrant 2")
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs city = "" while city not in ("chicago", "new york city", "washington"): city = input("Please choose a city from Chicago, New York City or Washington:").lower() # TO DO: get user input for month (all, january, february, ... , june) month = "" while month not in ("january", "february", "march", "april", "may", "june", "all"): month = input("If you would like to filter the data by month, please type a month between January and June (inclusive). If not, please type 'all'.:").lower() # TO DO: get user input for day of week (all, monday, tuesday, ... sunday) day = "" while day not in ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "All"): day = input("If you would like to filter the data by day, please type a day of the week (Monday, Tuesday, etc.). If not, please type 'all.':").title() print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # Load the correct csv based on user selected city df = pd.read_csv(CITY_DATA[city]) # Convert the 'Start Time' column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # Create new columns for the month and day of the week from the new 'Start Time' column df['Month'] = df['Start Time'].dt.month df['Day of Week'] = df['Start Time'].dt.weekday_name # filter by month if needed if month != 'all': # use the index from this list to get the integer value of the month months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 # filter by month df = df[df['Month'] == month] # filter by day of week if needed if day != 'All': df = df[df['Day of Week'] == day] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # TO DO: display the most common month months = ['January', 'February', 'March', 'April', 'May', 'June'] most_common_month = months[int(df.mode()['Month'][0]) - 1] print("The month where the most rides started was: {}".format(most_common_month)) # TO DO: display the most common day of week most_common_day = df.mode()['Day of Week'][0] print("The day of the week where the most rides started was: {}".format(most_common_day)) # TO DO: display the most common start hour df['Start Hour'] = df['Start Time'].dt.hour most_common_start_hour = int(df.mode()['Start Hour'][0]) print("The hour that most rides started was: {}".format(most_common_start_hour)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # TO DO: display most commonly used start station most_common_start_station = df.mode()['Start Station'][0] print("The most common station users started thier trip from was: {}".format(most_common_start_station)) # TO DO: display most commonly used end station most_common_end_station = df.mode()['End Station'][0] print("The most common station users ended their trip with was: {}".format(most_common_end_station)) # TO DO: display most frequent combination of start station and end station trip df['Start Station - End Station'] = df['Start Station'] + " - " + df['End Station'] most_common_trip = df.mode()['Start Station - End Station'][0] print("The most common trip occured between this start and end station: {}".format(most_common_trip)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # TO DO: display total travel time total_travel_time = df['Trip Duration'].sum() / 60 / 60 /24 print("The total time (in days) of all trips was: {}".format(total_travel_time)) # TO DO: display mean travel time mean_travel_time = (df['Trip Duration'].mean()) / 60 print("The average time (in min) of all trips was: {}".format(mean_travel_time)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types if 'User Type' in df.columns: user_breakdown = df['User Type'].value_counts() print("Here is the breakdown of Users:\n {}".format(user_breakdown)) else: print("This data does not contain user type data. Skipping calculation...\n") # TO DO: Display counts of gender if 'Gender' in df.columns: gender_breakdown = df['Gender'].value_counts() print("Here is the breakdown of Gender:\n {}".format(gender_breakdown)) else: print("This data does not contain gender data. Skipping calculation...") # TO DO: Display earliest, most recent, and most common year of birth if 'Birth Year' in df.columns: min_birth_year = df['Birth Year'].min() max_birth_year = df['Birth Year'].max() most_common_birth_year = df['Birth Year'].mode() print("The oldest user was born in: {}".format(int(min_birth_year))) print("The youngest user was born in: {}".format(int(max_birth_year))) print("The most common birth year was: {}".format(int(most_common_birth_year))) else: print("This data does not contain birth year data. Skipping calculation...") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def display_data(data): i = 0 while True: see_data = input("Would you like to see 5 rows of raw data?(yes or no):").lower() if see_data != "yes": break else: print(data[i:i+5]) i += 5 def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) display_data(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
# импорт вебдрайвер и времени from selenium import webdriver #подключение библиотеки селект для выбора элементов из списка from selenium.webdriver.support.ui import Select import time import math #Создаем переменную с ссылкой на страницу link = "http://suninjuly.github.io/selects1.html" #Создаем переменную, в котором путь до вебдрайвера browser = webdriver.Chrome('/Users/alexnder/Documents/python/chromedriver') #Получение ссылки для взаимодействие с вебдрайвером browser.get(link) try: #Поиск двух чисел n1 = browser.find_element_by_id('num1') n2 = browser.find_element_by_id('num2') #Перевод чисел в инт n1_2 = int(n1.text) n2_2 = int(n2.text) #Сложение чисел и перевод их суммы в стр sum = n1_2 + n2_2 sum = str(sum) #Поиск селекта browser.find_element_by_class_name('custom-select').click() #Подключение селекта. Поиск по всем значениям селекта нужное значение select = Select(browser.find_element_by_tag_name("select")) select.select_by_value(sum) #Поиск и нажатие на кнопку browser.find_element_by_class_name('btn-default').click() finally: time.sleep(15) browser.quit() #Закрытие теста
#!/usr/bin/python # -*- coding:utf-8 -*- import pygame from pygame.sprite import Sprite class Alien(Sprite): """表示单个外星人的类""" def __init__(self,ai_settings,screen): """初始化外星人并设置其起始位置""" super(Alien,self).__init__() #继承Sprite self.screen=screen self.ai_settings=ai_settings #加载外星人图像,并设置其rect属性 self.image=pygame.image.load('images/alien.bmp') self.rect=self.image.get_rect() #每个外星人最开始都在屏幕左上角附近,左边距设置为外星人的宽度,上边距设置为外星人的高度 self.rect.x=self.rect.width self.rect.y=self.rect.height #存储外星人的准确位置 self.x=float(self.rect.x) def blitme(self): """在指定位置绘制外星人""" self.screen.blit(self.image,self.rect) def check_edges(self): """如果外星人位于屏幕左边缘或者右边缘,则返回True""" screen_rect=self.screen.get_rect() if self.rect.right>=screen_rect.right: return True elif self.rect.left<=0: return True def update(self): """向左或右移动外星人""" self.x+=(self.ai_settings.alien_speed_factor* self.ai_settings.fleet_direction) self.rect.x=self.x
def solve(heads,legs): error_msg="No solution" chicken_count=0 rabbit_count=0 #Start writing your code here # R + C = 35 --> heads # 4R + 2C = 94 --> legs #-- R = 12 AND C = 23 #Populate the variables: chicken_count and rabbit_count # Let's look at invalid condition if legs%2 != 0 or heads == 0 or heads >= legs: print(error_msg) else: # since we know R+C=heads and 4R + 2C = legs #hence by reducing this equation we get R = (legs - 2heads)/2 rabbit_count = (legs - 2 * heads)//2 # we also know that C = heads - R, deduced from the above equation chicken_count = heads - rabbit_count print(chicken_count,rabbit_count) # Use the below given print statements to display the output # Also, do not modify them for verification to work #print(chicken_count,rabbit_count) #print(error_msg) #Provide different values for heads and legs and test your program solve(3,12)
import numpy as np import matplotlib.pyplot as plt import machine_learning_algorithms as mla # 2d example data set from Coursera course Machine Learning # linear regression is used to estimate the prices of houses in dependence # on the size of the house in square feet and on the number of bedrooms data = np.loadtxt("data/house_prices.txt", delimiter=",") X = data[:, 0:2] y = data[:, 2] def plotCostHistory (X, y, standardization=False, iterations=50, learningRate=1e-7, regularization=0.0): lr = mla.LinearRegression(X, y, standardization) costHistory = lr.gradientDescent(iterations=iterations, learningRate=learningRate, regularization=regularization) plt.figure() ax = plt.gca() plt.subplots_adjust(top=0.95, bottom=0.13, left=0.13, right=0.98) plt.rcParams.update({"font.size": 18}) plt.plot(np.arange(1, iterations+1), costHistory, color="black") plt.text(0.4, 0.9, "learning rate = " + str(learningRate), transform=ax.transAxes) plt.text(0.4, 0.8, "regularization = " + str(regularization), transform=ax.transAxes) plt.xlabel("number of iterations") plt.ylabel(r"cost function $J$") plt.grid(color="lightgray") plt.show() def plotData (X, y, size=True, bedrooms=True, standardization=False, iterations=50, learningRate=1e-7, regularization=0.0): lr = mla.LinearRegression(X, y, standardization) lr.gradientDescent(iterations=iterations, learningRate=learningRate, regularization=regularization) if size == True: plt.figure() ax = plt.gca() plt.subplots_adjust(top=0.98, bottom=0.14, left=0.23, right=0.97) plt.rcParams.update({"font.size": 18}) plt.scatter(X[:, 0], y, color="black", marker="x", zorder=2) plt.scatter(X[:, 0], lr.predict(X), color="red", zorder=3) plt.text(0.60, 0.25, r"$\theta_0$ = " + str(np.around(lr.theta[0], 1)), transform=ax.transAxes) plt.text(0.60, 0.15, r"$\theta_1$ = " + str(np.around(lr.theta[1], 1)), transform=ax.transAxes) plt.text(0.60, 0.05, r"$\theta_2$ = " + str(np.around(lr.theta[2], 1)), transform=ax.transAxes) plt.xlabel(r"house size in ft$^2$") plt.ylabel("house price in $") plt.grid(color="lightgray") plt.show() if bedrooms ==True: plt.figure() ax = plt.gca() plt.subplots_adjust(top=0.98, bottom=0.14, left=0.23, right=0.97) plt.rcParams.update({"font.size": 18}) plt.scatter(X[:, 1], y, color="black", marker="x", zorder=2) plt.scatter(X[:, 1], lr.predict(X), color="red", zorder=3) plt.text(0.05, 0.90, r"$\theta_0$ = " + str(np.around(lr.theta[0], 1)), transform=ax.transAxes) plt.text(0.05, 0.80, r"$\theta_1$ = " + str(np.around(lr.theta[1], 1)), transform=ax.transAxes) plt.text(0.05, 0.70, r"$\theta_2$ = " + str(np.around(lr.theta[2], 1)), transform=ax.transAxes) plt.xlabel(r"number of bedrooms") plt.ylabel("house price in $") plt.grid(color="lightgray") plt.show() plotCostHistory(X, y, standardization=True, learningRate=1) plotData(X, y, size=True, bedrooms=True, standardization=True, learningRate=1)
#!/usr/bin/env python # coding: utf-8 """ 求100w以内的素数 质数(Prime number),又称素数,指在大于1的自然数中,除了1和该数自身外,无法被其他自然数整除的数(也可定义为只有1与该数本身两个因数的数)。 简单来说就是,只能除以1和自身的数(需要大于1)就是质数。举个栗子,5这个数,从2开始一直到4,都不能被它整除,只有1和它本身(5)才能被5整除,所以5就是一个典型的质数。 """ p = [] max_num = 100 for i in range(2, max_num): for j in range(2, i): if i % j == 0: break else: p.append(i) print(f'{max_num} 以内有 {len(p)}个素数')
#Binary Tree's Insertion and traversal class Node(): def __init__(self,data): self.left = None self.right = None self.data = data def preorder(self,i=0): print "Level::%s Value::%s"%(i,self.data) if self.left: self.left.preorder(i=i+1) if self.right: self.right.preorder(i=1+1) def postorder(self,i=0): if self.left: self.left.postorder(i=i+1) if self.right: self.right.postorder(i=i+1) print "Level::%s Value::%s"%(i,self.data) def inorder(self,i=0): if self.data: if self.left: self.left.inorder(i=i+1) print "Level::%s Value::%s"%(i,self.data) if self.right: self.right.inorder(i=i+1) """ Compute the height of a tree--the number of nodes along the longest path from the root node down to the farthest leaf node """ def height(self,node): if node is None: return 0 else: # Compute the height of each subtree lheight = self.height(node.left) rheight = self.height(node.right) #Use the larger one if lheight > rheight : print "lehight::",lheight+1 return lheight+1 else: print "rheight::",rheight+1 return rheight+1 c = Node(1) c.left = Node(2) c.right = Node(3) c.left.left = Node(4) c.left.right = Node(5) print "*************PREORDER*************" c.preorder() print "*************POSTORDER*************" c.postorder() print "*************INORDER*************" c.inorder() print "*************HEIGHT*************" c.height(c) # =============================== END ======================== ''' # Binary Search Tree class Node: def __init__(self,key): self.left = None self.right = None self.val = key def get(self): return self.val # A utility function to insert a new node with the given key def insert(root,node): if root is None: root = node else: # print "ROOT VAL::",r.val # print "NODE VAL::",node.values if root.val < node.val: if root.right is None: root.right = node else: insert(root.right, node) else: if root.left is None: root.left = node else: insert(root.left, node) # A utility function to do inorder tree traversal def inorder(root,i=0): if root: inorder(root.left,i=i+1) print "Level::%s Value::%s"%(i,root.val) inorder(root.right,i=1+1) # A utility function to do preorder tree traversal def preorder(root,i=0): print "Level::%s Value::%s"%(i,root.val) if root.left: preorder(root.left,i=i+1) if root.right: preorder(root.right,i=1+1) # A utility function to do postorder tree traversal def postorder(root,i=0): if root.left: postorder(root.left,i=i+1) if root.right: postorder(root.right,i=1+1) print "Level::%s Value::%s"%(i,root.val) # A utility function to do SEARCH of NODE in a given tree def lookup(root, data, parent=None): """ Lookup node containing data @param data node data object to look up @param parent node's parent @returns node and node's parent if found or None, None """ try: if data < root.val: if root.left is None: return None, None return lookup(root.left,data, root.val) elif data > root.val: if root.right is None: return None, None return lookup(root.right,data, root.val) else: return root.val, parent except Exception as e: print e def child_count(root): count=0 lchild=0 rchild=0 if root.left: child_count(root.left) count+=1 lchild+=1 if root.right: child_count(root.right) count+=1 rchild+=1 print count,lchild,rchild return count,lchild,rchild r = Node(50) #print r.get() insert(r,Node(30)) insert(r,Node(20)) insert(r,Node(40)) insert(r,Node(70)) insert(r,Node(60)) insert(r,Node(80)) # print r.get() insert(r,Node(-2)) # insert(r,Node(2)) node,parent = lookup(r,70) print "SEARCHD NODE is::: %s and PARENT NODE of SEARCHED NODE is ::: %s"%(node, parent) print "******* IN-ORDER ****************" inorder(r) print "================================" print "******* PRE-ORDER ****************" preorder(r) print "================================" print "******* POST-ORDER ****************" postorder(r) child_count(r) '''
''' print "hello" l = [10,20,30] try: import prasit x = int(raw_input("Enter 1st Number::")) y = int(raw_input("Enter 1st Number::")) s =x/y print s print l[0] except ValueError: print "GOT Value Error..." except ZeroDivisionError: print "GOT ZeroDivError..." except IndexError: print "GOT Index Error..." except Exception as e: print "Got SOME OTHER Exception...." print e else: print "NO EXCEPTION generated...." finally: print "Am in Finally... I do execute all the time..." print "Rest of the APPS go from here....." ''' # ========================================================================== # CLOSURE: ''' def outer(): state =10 def inner(): return state return inner inn = outer() r = inn() print r ''' #================================================================================ # DECORATORS: ''' def add10(f): def decor(*args): return f(*args)+10 return decor @add10 @add10 def add(a,b): return a+b s =add(2,3) print "SUM is::",s print add.__name__ ''' # paramiterized decorators: ''' def addn(n): def decor(f): def reality(*args): return f(*args)+n return reality return decor @addn(70) @addn(40) def add(a,b): return a+b s =add(2,3) print "SUM is::",s print add.__name__ ''' #======================================================== # PICKLE: ''' import pickle l = [10,20,[30,40],'hello',{1:2,3:4},60,70] fout = open('C:\Prasit\serealized.dat','w') pickle.dump(l,fout) fout.close() fin = open('C:\Prasit\serealized.dat','r') L = pickle.load(fin) fin.close() print L ''' # =============================================================================== ''' import sys import os if len(sys.argv)!= 2: print "Application need ONE integer input from CLI..." sys.exit(1) child1 = os.fork() if child1 == 0: print "CHILD_1 started PID::",os.getpid() os.execvp('python',['python','fillmatrix.py',sys.argv[1]]) child2 = os.fork() if child2 == 0: print "CHILD_2 started PID::",os.getpid() os.execvp('python',['python','fillmatrix.py',sys.argv[1]]) child3 = os.fork() if child3 == 0: print "CHILD_3 started PID::",os.getpid() os.execvp('python',['python','fillmatrix.py',sys.argv[1]]) r=1 while True: try: pid = os.wait() print "Process",pid[0],"comleted",r except OSError: print "****** GAME is OVER *****" os.exit(0) r=r+1 ''' # ======================================================================== ''' import os curr_dir = os.getcwd() listdir = os.listdir(curr_dir) d ={} cache_file_name={} for i in listdir: if i.endswith(('py','pyc')): cache_file_name[i]={} print cache_file_name user_file_name = raw_input("Enter the file name::") if cache_file_name.has_key(user_file_name): print "YOUR FILE IS PRESENT..." file_path = os.path.join(curr_dir,user_file_name) print file_path FR = open(file_path,'r') read_file = FR.read() read_lines = read_file.split('\n') if_count =0 for_count =0 for i in read_lines: if i.__contains__('if'): if_count+=1 if i.__contains__('for'): for_count+=1 print "Number of IF Loop is:",if_count print "Number of FOR loop is",for_count print "**************************************************" cache_file_name[user_file_name]['if']=if_count cache_file_name[user_file_name]['for']=for_count else: print "YOUR FILE IS NOT PRESENT...Select another file.." print cache_file_name ''' # ============================================================================= def depth(d, level=1): if not isinstance(d, dict) or not d: return level return max(depth(d[k], level + 1) for k in d) d ={'a':{'aa':{'aaa':{'aaaa':{}}}}} c = depth(d,level=1) print c
import re ''' # Write a script to count numbers of words available in a given string pra = 'Prasit is a boy. He lives in Bangalore. He is from Kolkata' d ={} pra_list = pra.split(' ') #print pra_list for x in pra_list: print x,pra_list.count(x) # Write a script to count number of words which begins with Upper case alphabet if x[0].isupper(): print x,pra_list.count(x) # Write a script to swap FIRST and LAST character of every word of a given string. tmp = x[1:-1] print tmp print x[-1:]+ tmp+ x[:1] # Write a script to remove duplicate words available in a given string. #print set(pra_list) # Write a script to find frequency occurrence of words of a given string if x in d.keys(): d[x]+=1 else: d[x]=1 print d ''' mat1 = [] mat2 = [] x = [1,2,3] y= [4,5,6] w = [7,8,9] z = [4,6,8] mat1.append(x) mat1.append(y) mat2.append(w) mat2.append(z) print mat1,mat2 result = [[0,0,0],[0,0,0],[0,0,0]] for i in range(len(mat1)): for j in range(len(mat1[0])): print mat1[i][j] print mat2[i][j] result[i][j]=mat1[i][j]+mat2[i][j] for r in result: print r ''' # write a script to find smallest integer out of 3 integer. x =[10,34,54,23,56] print min(x),type(x[0]) '''
import pandas as pd # Takes a dataframe, the column to groupby, and a list of columns # Normalizes them within each group def normalize_by_columns(df: pd.DataFrame, groupby: str, columns: list) -> pd.DataFrame: ids = df[groupby].unique() output_df = pd.DataFrame() for current_id in ids: current = df.loc[df[groupby] == current_id] current[columns] = current[columns].apply(lambda x: (x - x.min()) / (x.max() - x.min())) output_df = output_df.append(current) return output_df
import random P = [] for i in range(0,13): P.append( [0]*13 ) CantCajones = int(input("ingrese la cantidad de cajones : ")) CantAgujeros = int(input("ingrese la cantidad de agujeros : ")) for cajon in range(1, CantCajones+1): print("ingrese cordenadas (fila, columna) de cajon", cajon) fila = int(input("fila: ")) columna = int(input("columna: ")) P[fila][columna] = 1 while (fila == 12 and columna == 0) or (fila == 0 and columna == 12) or (P[fila][columna] == 1) : print("error, ingrese las cordenadas") fila = int(input("fila:")) columna = int(input("columna:")) P[fila][columna] = 1 print() for agujero in range(1, CantAgujeros+1): print("ingrese cordenadas (fila, columna) de agujero", agujero) fila = int(input("fila: ")) columna = int(input("columna: ")) P[fila][columna] = 2 while agujero == cajon : print("error, ingrese las cordenadas") fila = int(input("fila:")) columna = int(input("columna:")) P[fila][columna] = 2 print() print() for i in range(0,13): for j in range (0, 13): print(str.rjust(str(P[i][j]), 4), end = "") print(); print() input()
import os os.system('cls') import string from random import randint as azar #Benjajaja 2 sello #kenneth 1 sello """ Contraseña = PericoLosPalotes31* Numero al azar -> 5 Encriptacion Cesar -> UjwnhtQtxUfqtyjx31* Intercalacion de mayusculas -> UjWnHtQtXUFqTyJx31* Agregacion de numero al azar -> 5UjWnHtQtXUFqTyJx31* * = ? # = ! $ = & & = $ ! = # ? = * Salt = #$%Fg6Der%4dfgdf Contraseña Final = 5UjWnHtQtXUFqTyJx31?#$%Fg6Der%4dfgdf """ salt = "#$&Fg6Der$4dfgdf" abecedario = list(string.ascii_lowercase) contrasena = input('Ingrese contrasena a encriptar: ') num = azar(1,len(abecedario)) cesar = [] #el for itera en cada elemento de 'contrasena', #y cada elemento queda en la variable 'letra' for letra in contrasena: cesar.append(letra) input(f"cesar: {cesar}") input(f"abecedario: {abecedario}") simbolos = ['*','#','$','&','!','?'] encriptado = [] print('num es ',num) for i in range(len(contrasena)): for j in range(len(abecedario)): if contrasena[i].lower() == abecedario[j]: if j+num < len(abecedario): if contrasena[i].isupper(): letra = abecedario[j+num].upper() else: letra = abecedario[j+num] encriptado.append(letra) else: dif = j + num - len(abecedario) if contrasena[i].isupper(): letra = abecedario[dif].upper() else: letra = abecedario[dif] encriptado.append(letra) if contrasena[i].isdigit(): encriptado.append(contrasena[i]) if contrasena[i] in simbolos: encriptado.append(contrasena[i]) input(f"encriptado {encriptado}") for i in range(len(encriptado)): if i%2 == 0: encriptado[i] = encriptado[i].upper() for i in range(len(encriptado)): if encriptado[i] in simbolos: for j in range(len(simbolos)): if encriptado[i] == simbolos[j]: input(f"pos simbolo ( {len(simbolos)}-1 ) - {j} = {(len(simbolos)-1) - j}") encriptado[i] = simbolos[(len(simbolos)-1) - j] break print("su contrasena encriptada es: ",str(num)+ "".join(encriptado) + salt)
# -*- coding: utf-8 -*- """ Created on Tue Aug 3 02:42:11 2021 @author: Omen 15 """ ''' Se pide realizar un programa en Python que lea dos Strings compuestos por palabras separadas por un espacio en blanco y ya ordenadas alfabéticamente, y que genere un tercer string (resultado) que contenga todas las palabras ordenadas. Ejemplo: String 1: BANANA CASA LUNA MARQUESINA TORRE ZAPATO. String 2: ARENA FLOR GONDOLA LAPIZ NARANJA PLATANO VIVIENDA. Resultado: ARENA BANANA CASA FLOR GONDOLA LAPIZ LUNA MARQUESINA NARANJA PLATANO TORRE VIVIENDA ZAPATO. Observaciones: - Cada string está terminado en un punto y el string resultante debe terminar en punto (uno solo). - Las palabras tienen solo letras mayúsculas y no existen tildes (vocales acentuadas) ni la letra Ñ. - No es necesario utilizar arreglos (PERO PUEDEN USARSE). - Ayuda: El computador sabe que “LAPIZ” es menor que “LUNA”. - No utilizar función sort del Python. ''' string1 = 'BANANA CASA LUNA MARQUESINA TORRE ZAPATO.' string2 = 'ARENA FLOR GONDOLA LAPIZ NARANJA PLATANO VIVIENDA.' string3 = '' sw = True #string1 = input('') #string2 = input('') while sw == True: stringIndice1 = string1.find(' ') stringIndice2 = string2.find(' ') if stringIndice1 == -1: if string1.find('.') != -1: palabra1 = string1[0: ] else: palabra1 = string1[0:stringIndice1] if stringIndice2 == -1: if string2.find('.') != -1: palabra2 = string2[0: ] else: palabra2 = string2[0:stringIndice2] if palabra1.find('.') == -1 and palabra2.find('.') == -1: if palabra1 < palabra2: string3 = string3 + palabra1 + ' ' string1 = string1[stringIndice1 + 1: ] else: string3 = string3 + palabra2 + ' ' string2 = string2[stringIndice2 + 1: ] else: if palabra1.find('.') == -1: if palabra1 < palabra2: string3 = string3 + palabra1+ ' ' string1 = string1[stringIndice1 + 1: ] else: string3 = string3 + palabra2[0:len(palabra2)-1] + ' ' string2 = 'á.' else: if palabra2 < palabra1: string3 = string3 + palabra2 + ' ' string2 = string2[stringIndice2 + 1: ] else: string3 = string3 + palabra1[0:len(palabra1)-1] + ' ' string1 = 'á.' if palabra1.find('.') != -1 and palabra2.find('.') != -1: sw = False print(string3) input()
""" Given an integer,n, perform the following conditional actions: If n is odd, print Weird If n is even and in the inclusive range of 2 to 5, print Not Weird If n is even and in the inclusive range of 6 to 20 , print Weird If n is even and greater than 20 , print Not Weird """ N = int(input()) if N%2==0 : if N in range(2,6): print("Not Weird") if N in range (6,21): print("Weird") if N>20 : print ("Not Weird") else: print("Weird")
import requests import pandas as pd import datetime import wbdata import plotly.express as px # Get all sources from the World Bank API sources = requests.get("http://api.worldbank.org/v2/sources?per_page=100&format=json") sourcesJSON = sources.json() # View the JSON response print("JSON Response: \n",sourcesJSON) # Parse through the response to see the source names and ID numbers for i in sourcesJSON[1]: if i["name"] == "International Debt Statistics": print("\n") print("The source ID for International Debt Statistics is " + i["id"]) else: pass # View all the source names and IDs print(i["id"],i["name"]) # Requesting the indicators for the topic External Debt indicators = requests.get("http://api.worldbank.org/v2/indicator?format=json&source=6") indicatorsJSON = indicators.json() # The total number of indicators print("There are " + str(indicatorsJSON[0]["total"]) + " IDS indicators") # Get all External Debt indicators, with a per_page parameter of 500. indicators = requests.get("http://api.worldbank.org/v2/indicator?format=json&source=6&per_page=500") indicatorsJSON = indicators.json() # View ALL the indicators print("All the indicators: \n",indicatorsJSON) # Parse through the response to see the Indicator IDs and Names print("Indicator IDs and Names: \n") for i in indicatorsJSON[1]: IDSindicators = (i["id"],i["name"]) print(IDSindicators) # View the indicator ids and names # Use the indicator code to define the "indicator" variable indicator = "DT.DOD.DLXF.CD" # Parse through the response to get the "sourceNote" or definition for the desired indicator print("Source Note: \n") for dict_entity in indicatorsJSON[1]: if dict_entity["id"] == indicator: print(dict_entity["sourceNote"]) else: pass # Requesting the countries dlocations = requests.get("http://api.worldbank.org/v2/sources/6/country?per_page=300&format=JSON") dlocationsJSON = dlocations.json() # Parse through the response to see the country IDs and names dlocations = dlocationsJSON["source"][0]["concept"][0]["variable"] listLen = int(len(dlocations)) # Create dataframe with country values df = pd.DataFrame(columns=["id", "value"]) for i in range(0,listLen): code = dlocations[i]["id"] name = dlocations[i]["value"] df = df.append({"id":code, "value":name}, ignore_index = True) dlocationsList = df # First few rows in the dataframe print("Location/Countries: \n",dlocationsList.head(n=10)) # Get the full list of the creditor codes and names # We'll use a query like the one above, but in the get request we will replace "country" with "counterpart-area." # Requesting the locations (Using the same query as above) clocations = requests.get("http://api.worldbank.org/v2/sources/6/counterpart-area?per_page=300&format=JSON") clocationsJSON = clocations.json() # Parse through the response to see the location IDs and names clocations = clocationsJSON["source"][0]["concept"][0]["variable"] listLen = int(len(clocations)) # Create dataframe with location values df = pd.DataFrame(columns=["id", "value"]) for i in range(0,listLen): code = clocations[i]["id"] name = clocations[i]["value"] df = df.append({"id":code, "value":name}, ignore_index = True) clocationsList = df # First few rows in the dataframe print(clocationsList.head(n=10)) # Selecting the indicator indicatorSelection = {"DT.DOD.DLXF.CD":"ExternalDebtStock"} # Select the countries or regions locationSelection = ["ECA","SSA","SAS","LAC","MNA","EAP"] # Selecting the time frame timeSelection = (datetime.datetime(2009, 1, 1), datetime.datetime(2019, 12, 31)) # Making the API call and assigning the resulting DataFrame to "EXD" EXD = wbdata.get_dataframe(indicatorSelection, country = locationSelection, data_date = timeSelection, convert_date = False) # Print the first 5 lines of the DataFrame print("External Debt Data: \n",EXD.head()) # Reshape the data EXDreshaped = pd.DataFrame(EXD.to_records()) # Creating a function that will change units to billions and round to 0 decimal places def formatNum(x): y = x/1000000000 z = round(y) return(z) # Running the function on the desired data column EXDreshaped.ExternalDebtStock = formatNum(EXDreshaped.ExternalDebtStock) # Renaming column headers EXDclean = EXDreshaped.rename(index=str, columns={ "date":"Year", "country":"Region" }) # Remove the "(excluding high income)" from each of the region names EXDclean["Region"] = EXDclean["Region"].str.replace("excluding high income","").str.replace(")","").str.replace("(","") print(EXDclean.head()) # Defining the data source source = EXDclean # Creating the chart chart = px.line(EXDclean, x="Year", y="ExternalDebtStock", color="Region", color_discrete_sequence = px.colors.qualitative.Vivid, title="Regional Long-term External Debt Stock (excluding High-Income countries)(USD billion)") chart.update_layout(plot_bgcolor="white") # Displaying the chart chart.show()
class Dog: def __init__(self, name, month, day, year, speakText): # Constructor of the class # self references the object itself self.name = name self.month = month self.day = day self. year = year self.speakText = speakText def __str__(self): # the str() operator was overloaded # such methods also called Magic Methods in Python return 'Dog name: ' + self.name + '\n' + \ 'Birth-date: ' + self.birthDate() + '\n' + \ 'Bark type: ' + self.speakText def speak(self): # Accessor method # returns the speakText return self.speakText def getName(self): # Accessor method # returns the name of the Dog return self.name def birthDate(self): # Accessor method # returns a string representing the birthday date return str(self.month) + '/' + str(self.day) + '/' + str(self.year) def changeBark(self, bark): # Mutator method # changes the speakText of the Dog object self.speakText = bark def main(): boyDog = Dog('Mesa', 5, 15, 2004, 'WOOOOF') girlDog = Dog('Sequoia', 5, 6, 2004, 'barkbark') print(str(boyDog)) print(str(girlDog)) boyDog.changeBark('woofywoofy') print(boyDog.speak()) print(str(boyDog)) if __name__ == "__main__": # evaluates to True if the script was run from a shell main()
class cal3 : def __init__(self,P,R,T): self.n1 =P self.n2 = R self.n3 = T def callinterest(self): self.interest =((self.n1*self.n2*self.n3/100)) def display(self): print("interest of given parameters:",self.interest) c=cal3(100,30,2) c.callinterest() c.display()
a =int(input('Enter first number : ')) b = int(input('Enter second number : ')) for num in range(a, b-3, -3): print (num)
n1= 100 n2 = int(input("enter a number")) if n1<n2 : print("n2 is greater than 100:") elif n1>n2: print("n2 is less than 100:") if n2 %2==0: print("it is even") else : print("it is odd")
# calculator in Python(v0.2) def div(num1, num2): return num1 / num2 # main res = div(5, 3) print(res)
import numpy as np import csv import random import time '''load csv file as data resource''' def loadCsv(filename): lines = csv.reader(open(filename, "rb")) dataset = list(lines) return dataset ''' clean the dataset delete the first row and first column, because the first colmun is id, the first row is header. ''' def clean(dataset): dataset.pop(0) for i in range(0,len(dataset)): dataset[i].pop(0) for j in range(1,len(dataset[i])): dataset[i][j] = float(dataset[i][j]) return dataset ''' splite the input dataset to train dataset and test dataset by some ratio ''' def splitDataset(dataset, splitRatio): trainSize = int(len(dataset) * splitRatio) trainSet = [] copy = list(dataset) while len(trainSet) < trainSize: index = random.randrange(len(copy)) trainSet.append(copy.pop(index)) return [trainSet, copy] ''' Divides a set on a specific column.Can handle numeric or nominal values eg. divideset(my_data, 2, 0.04) will divide the my_data to two sets based on the 2nd column's value, those >=0.04 will be in one set, otherwise in another set ''' def divideset(rows,column,value): # Make a function that tells us if a row is in the first group (true) or the second group (false) split_function=None if isinstance(value,int) or isinstance(value,float): # check if the value is a number i.e int or float split_function=lambda row:row[column]>=value else: split_function=lambda row:row[column]==value # Divide the rows into two sets and return them set1=[row for row in rows if split_function(row)] set2=[row for row in rows if not split_function(row)] return (set1,set2) ''' given a dataset, return a dictionary. the key is the class name (the class name is in the first column) the value is the number of this class in whole dataset ''' def uniquecounts(rows): results={} for row in rows: # The result is the first column r=row[0] if r not in results: results[r]=0 results[r]+=1 return results ''' Entropy is the sum of p(x)log(p(x)) across all the different possible results, return the entropy for a dataset ''' def entropy(rows): from math import log log2=lambda x:log(x)/log(2) results=uniquecounts(rows) # Now calculate the entropy ent=0.0 for r in results.keys(): p=float(results[r])/len(rows) ent=ent-p*log2(p) return ent ''' col: the column number to be tested value: the criteria to divide the set, eg. if x> 0.04 go to right node, otherwise left results: if it is a internal node, result is 'None', if it is a leaf node, result will contains the class name and the number of intances tb and fb are decisionnodes, which are the next nodes in the tree if the result is true or false, respectively (e.g. go to node tb or fb). ''' class decisionnode: def __init__(self,col=-1,value=None,results=None,tb=None,fb=None): self.col=col self.value=value self.results=results self.tb=tb self.fb=fb ''' Build the decision tree recursively. rows is the set, either whole dataset or part of it in the recursive call, scoref is the method to measure heterogeneity. By default it's entropy. ''' def buildtree(rows,scoref=entropy): if len(rows)==0: return decisionnode() #len(rows) is the number of units in a set current_score=scoref(rows) # Set up some variables to track the best criteria best_gain=0.0 best_criteria=None best_sets=None column_count=len(rows[0]) #count the # of attributes/columns #start from the 2nd column, since the 1st column is the class name #for each column, find the distinct values in that colulmn for col in range(1,column_count): # Generate the list of all possible different values in the considered column global column_values column_values={} for row in rows: column_values[row[col]]=1 # Now try dividing the rows up for each value in this column for value in column_values.keys(): #the 'values' here are the keys of the dictionnary (set1,set2)=divideset(rows,col,value) #define set1 and set2 as the 2 children set of a division # Information gain p=float(len(set1))/len(rows) #p is the size of a child set relative to its parent gain=current_score-p*scoref(set1)-(1-p)*scoref(set2) #cf. formula information gain if gain>best_gain and len(set1)>0 and len(set2)>0: #set must not be empty best_gain=gain best_criteria=(col,value) best_sets=(set1,set2) # Create the sub branches if best_gain>0: trueBranch=buildtree(best_sets[0]) falseBranch=buildtree(best_sets[1]) return decisionnode(col=best_criteria[0],value=best_criteria[1], tb=trueBranch,fb=falseBranch) else: return decisionnode(results=uniquecounts(rows)) '''print the tree recursively''' def printtree(tree,indent=''): # Is this a leaf node? if tree.results!=None: print(str(tree.results)) else: print(str(tree.col)+':'+str(tree.value)+'? ') # Print the branches print indent + 'T->', printtree(tree.tb,indent+' ') print indent+'F->', printtree(tree.fb,indent+' ') '''classify a test case using the tree model''' def classify(observation,tree): if tree.results!=None: return tree.results else: v=observation[tree.col] branch=None if isinstance(v,int) or isinstance(v,float): if v>=tree.value: branch=tree.tb else: branch=tree.fb else: if v==tree.value: branch=tree.tb else: branch=tree.fb return classify(observation,branch) ''' compare the result of prediction with the true class, return the prediction accuracy ''' def getAccuracy(testSet, predictions): correct = 0 for i in range(len(testSet)): if testSet[i][0] == predictions[i]: correct += 1 return (correct/float(len(testSet))) * 100.0 def main(): filename = 'train.csv' my_data = clean(loadCsv(filename)) splitRatio = 0.67 print 'decision tree' accuracy_list = [] time_list = [] for k in range(10): trainingSet, testSet = splitDataset(my_data, splitRatio) start = time.time() tree=buildtree(trainingSet) correct = 0 for i in range(len(testSet)): result = classify(testSet[i][1:],tree) if list(result.keys())[0] == testSet[i][0]: correct += 1 end = time.time() time_used = end - start accuracy = correct/float(len(testSet)) * 100.0 time_list.append(time_used) accuracy_list.append(accuracy) return [time_list, accuracy_list]
def CountingSort(alist, largest, key): #key - функція визначення розряду сортування c = [0] * (largest + 1) #заповнюємо нулями масив підрахунків for i in range(len(alist)): c[key(alist, i)] = c[key(alist, i)] + 1 # додавання індексів, пошук місця c[0] = c[0] - 1 # зменшуємо перший еоемент для початку відліку з нуля for i in range(1, largest + 1): c[i] = c[i] + c[i - 1] result = [None] * len(alist) for i in range(len(alist) - 1, -1, -1): # заповсення масиу результату з кінця result[c[key(alist, i)]] = alist[i] c[key(alist, i)] = c[key(alist, i)] - 1 return result def RadixSort(unsorted, base=10):# base - система числення if unsorted == []: return def key_factory(digit, base):#виділення розряду def key(alist, index): return ((alist[index] // (base ** digit)) % base) return key largest = max(unsorted) exp = 0 #номер найсильнішого розряду while base ** exp <= largest: sorted_a = CountingSort(unsorted, base - 1, key_factory(exp, base)) exp = exp + 1 return sorted_a
#if (num %2 == 0): # print("numero exit() contador = 0 while contador <= 10: if contador % 2 == 0: print(contador) contador += 1 exit () num = 0 while true: if num == 5: break num += 1
''' Created on 2018年8月30日 @author: huowolf ''' #=============================================================================== # 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 # 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 #=============================================================================== class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ flag=[] for i,num in enumerate(nums): pair=target-num for j in range(i+1,len(nums)): if nums[j]==pair: flag.append(i) flag.append(j) return flag nums=[2, 7, 11, 15] target=9 l=Solution().twoSum(nums, target) print(l) assert l==[0,1] nums=[3,2,4] target=6 l=Solution().twoSum(nums, target) print(l) assert l==[1,2]
#买卖股票的最佳时机 II #=============================================================================== # 输入: [7,1,5,3,6,4] # 输出: 7 # 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 # 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。 #=============================================================================== #贪心算法,总是做出在当前看来是最好的选择,不从整体最优上加以考虑,也就是说,只关心当前最优解 #当今天的价格比前一天的价格高,也就是利润>0,那么就进行一笔交易。能赚一笔是一笔,苍蝇再小也是肉嘛 class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ max_profit=0 for i in range(len(prices)-1): if(prices[i+1]>prices[i]): max_profit+=(prices[i+1]-prices[i]) return max_profit if __name__ == '__main__': prices=[7,1,5,3,6,4] max_profit=Solution().maxProfit(prices) print(max_profit)
#Kim Hewson #18/09/14 #Stretch exercise one length=int(input("Enter length (m): ")) width=int(input("Enter width (m): ")) cost=((length-2)*(width-2))*10 print("The cost to turf your garden will be £{0}".format(cost))
import turtle import time pen = turtle.Turtle() class Star(object): def __init__(self, x=0, y=0, arm_length=2, color="red"): """creates a line starting from the coordinates given by beg to the coordinates given by end.""" self.pencolor = color self.x = x self.y = y self.arm_length = arm_length self.color=color self.tag = "Star" self.x1 = x+ arm_length/3.236 self.y1 = y+ arm_length/2.35 def __str__(self): return "%s x:%s, y:%s, arm:%s, color:%s" % (self.tag,self.x,self.y,self.arm_length, self.color) def draw(self, pen): pen.pencolor(self.color) pen.fillcolor(self.color) if pen.pos() != (self.x1, self.y1): pen.up() pen.goto(self.x1, self.y1) pen.down() pen.begin_fill() for i in range(5): pen.forward(self.arm_length) pen.right(144) pen.forward(self.arm_length) pen.end_fill() class Rectangle(object): def __init__(self, xc = 0, yc = 0, w =100, h =100, color = "black"): self.color = color self.x =xc self.y =yc self.w =w self.h = h x1=xc-w/2 y1=yc-h/2 x2=xc+w/2 y2=yc+h/2 self.beg = x1, y1 self.end = x2, y2 self.tag = "Rectangle" def __str__(self): string = "This is a Rectangle with para" + str(self.beg[0]) return "%s x:%s, y:%s, width:%s, height:%s, color:%s" % (self.tag,self.x,self.y,self.w, self.h,self.color) def draw(self, pen): pen.pencolor(self.color) pen.fillcolor(self.color) if pen.pos() != self.beg: pen.up() pen.goto(self.beg) pen.down() pen.begin_fill() self.mid1 = self.beg[0], self.end[1] self.mid2 = self.end[0],self.beg[1] pen.goto(self.mid1) pen.goto(self.end) pen.goto(self.mid2) pen.goto(self.beg) pen.end_fill() class Flag(object): def __init__(self, file_object): self.rectangles=[]; self.stars =[]; self.file_object=file_object flag_config_file = open(self.file_object, 'r') count=1 lineNum=1 starLineNum=1 for line in flag_config_file.readlines(): if count==1: rectangleNum=line.split(",") lineNum=count+int(rectangleNum[0].strip()) elif count<=lineNum: rectangleConfig=line.split(",") drawRectangle = Rectangle(int(rectangleConfig[0].strip()),int(rectangleConfig[1].strip()),int(rectangleConfig[2].strip()),int(rectangleConfig[3].strip()),rectangleConfig[4].strip()) self.rectangles.append(drawRectangle) """print(drawRectangle)""" elif count>lineNum and count>starLineNum: starNum=line.split(",") starLineNum=count+int(starNum[0].strip()) elif count<=starLineNum: starConfig=line.split(",") drawStar = Star(int(starConfig[0].strip()),int(starConfig[1].strip()),int(starConfig[2].strip()),starConfig[3].strip()) self.stars.append(drawStar) """print(drawStar)""" else: break count=count+1 def __str__(self): string1 = "Rectangles \n" string2 = "Stars \n" for i in self.rectangles: tmp = " %s \n" % (i) string1= string1 + tmp for j in self.stars: tmp = " %s \n" % (j) string2= string2 + tmp return string1+string2 def draw(self, pen): for i in self.rectangles: i.draw(pen) for j in self.stars: j.draw(pen) def main(): drawFlag = Flag("senegal.txt") drawFlag.draw(pen) time.sleep(4) print(drawFlag) pen.clear() drawFlag = Flag("panama.txt") drawFlag.draw(pen) print(drawFlag) time.sleep(4) main()
# def square_plus_one(a,b): # result = a * b + 1 # return result # # print(square_plus_one(2,3)) # def give_zhi_something(a,b): # return a + b # import math # # def quadratic(a,b,c): # x_1 = (-b + math.sqrt(math.pow(b,2)-(4*a*c)))/2*a # x_2 = (-b - math.sqrt(math.pow(b,2)-(4*a*c)))/2*a # return x_1, x_2 # # print(quadratic(1,2,-3)) #session3 # # def calculate_bmi(weight,height): # bmi = 703*(weight/height**2) # if bmi >= 30: # return 'you are obese.' # else: # if bmi >= 25: # return 'you are overweight.' # else: # if bmi >= 18.5: # return 'you have a normal weight.' # else: # return 'you are underweight.' # weight = input('Your weight is (in pounds):') # height = input('Your height is (in inches):') # weight = float(weight) # height = float(height) # # print(calculate_bmi(weight,height)) #recursion example: # def fab(n): # """" # Function will return nth Fabunacci number. # """ # if n==1 or n==2: # return 1 # else: # return fab(n-2) + fab(n-1) # # print(fab(1)) # print(fab(2)) # print(fab(3)) # print(fab(4)) # # for i in range(1, 11): # print('The {}th Fabonacci number is {}.'.format(i,fab(i)))
tekst = input("Podaj tekst: ") licznik = 0 pomiedzy_nawiasami = False for lit in tekst: if lit == '>': pomiedzy_nawiasami = False if pomiedzy_nawiasami: licznik += 1 if lit == '<': pomiedzy_nawiasami = True print(licznik)
def podwojenie(liczba): return liczba * 2 def pomniejszenie(liczba): return liczba / 2 def zwieksz(liczba, operacja): return operacja(liczba) + 1 # zwieksz_lambda = lambda liczba: liczba + 1 # print(zwieksz(1)) # print(zwieksz_lambda(2)) wynik = zwieksz(100, podwojenie) wynik2 = zwieksz(100, pomniejszenie) wynik3 = zwieksz(100, lambda x: x * 1.23) # x to argument lokalny, który dotyczy tylko i wylącznie lambdy print(wynik) print(wynik2) print(wynik3)
x = 0 while x < 100: print(x ** 2) x = x + 1 # można też zapisać x += 1 # po wyprintowaniu x^2 printujemy każdą następną x+1, aż x osiągnie 99
a=int(input()) b=int(input()) if a < 1 or b < 1: print("Exception") elif a%b==0: p=True else: p=False print(int(p))
from collections import deque predence = { '^' : 3, '*' : 2, '/' : 2, '+' : 1, '-' : 1 } for _ in range(int(input())): n = int(input()) infix = input().strip() stack = deque() postfix = "" for i in infix: if 'A' <= i <= 'Z': postfix += i elif i == '(': stack.append(i) elif i == ')': topElem = stack.pop() while topElem != '(': postfix += topElem topElem = stack.pop() else: while stack and stack[-1] != '('and predence[stack[-1]] >= predence[i]: postfix += stack.pop() stack.append(i) while stack: postfix += stack.pop() print(postfix)
import xml.etree.ElementTree as ET contents = [] while True: line = input() if line == "</expr>": contents.append(line) break else: contents.append(line) contents = list(filter(None, contents)) s = ''.join(contents) root = ET.fromstring(s) # compute = s.find('sum|div|prod|sub') for child in root: c = child.tag if c == "sum": s = 0 for compute in child.findall('.//elem'): s += int(compute.text) print(s) if c == "div": d = 0 l = child.findall('.//elem') d += int(l[0].text) // int(l[1].text) print(d) if c == "sub": sub = 0 l = child.findall('.//elem') l1 = int(l[0].text) for compute in child.findall('.//elem'): sub += int(compute.text) print(sub - l1) if c == "prod": p = 1 for compute in child.findall('.//elem'): p *= int(compute.text) print(p) """ XML parse plus series computation Evaluate an expression given in XML format. Keys will be Expr- contains the entire expression. Elem – contains the digit, sum, Prod- contains two or more keys whose evaluation needs to be summed or multiplied respectively. Sub will contain 2 keys or more, where the second key onwards will have to be subtracted from the first one. Div- will contain 2 keys in which first key will need to be divided by second. S i/p <expr> <sum> <elem>4</elem> <elem>6</elem> </sum> <div> <elem>6</elem> <elem>3</elem> </div> <sub> <elem>10</elem> <elem>3</elem> <elem>3</elem> </sub> <prod> <elem>2</elem> <elem>3</elem> <elem>5</elem> </prod> </expr> """
n = int(input()) table = [0] * (n+1) table[0] = 1 print("3\n") for i in range(3, n+1): table[i] += table[i-3] print(table[i], table[i-3]) print("\n\n5\n") for i in range(5, n+1): table[i] += table[i-5] print(table[i], table[i-5]) print("\n\n10\n") for i in range(10, n+1): table[i] += table[i-10] print(table[i], table[i-10]) print(table[n]) """ Consider a game where a player can score 3 or 5 or 10 points in a move. Given a total score n, find number of ways to reach the given score. Examples: Input: n = 20 Output: 4 There are following 4 ways to reach 20 (10, 10) (5, 5, 10) (5, 5, 5, 5) (3, 3, 3, 3, 3, 5) Input: n = 13 Output: 2 There are following 2 ways to reach 13 (3, 5, 5) (3, 10) Solution: This problem is a variation of coin change problem and can be solved in O(n) time and O(n) auxiliary space. The idea is to create a table of size n+1 to store counts of all scores from 0 to n. For every possible move (3, 5 and 10), increment values in table. """
import string alpha = string.ascii_lowercase s = input() for i in s: print(alpha[int(i)],end="")
""" Responsible for producing the regular expression for a given R(i,j,k) Simplyfies the regular expression produced Returns a string """ class R_IJK: """ Initalize all constant variables """ def __init__(self): self.EMPTY_SET = '!' self.UNION_SYMBOL = 'U' self.EMPTY_STRING = 'e' self.IGNORE = True self.result_recorder = {} """ Creates a blank record to record results """ def Create_Recorder(self, num_of_states): for x in range(0, num_of_states + 1): self.result_recorder[str(x)] = [] """ Called by an outside source to solve R(i,j,k) Creates a dictionary to record the results of solver Returns the dictionary with the result stored in it """ def Solver(self, i, j, k, path_values): if (k == 0): search_str = str(i) + str(j) formatted_return_str = path_values[search_str] recorded_str = "R(" + str(i) + ", " + str(j) + ", " + str(k) + ")" saved_str = recorded_str + " = " + formatted_return_str + "\n" if saved_str not in self.result_recorder[str(k)]: self.result_recorder[str(k)].append(saved_str) return formatted_return_str else: str_1 = self.Solver(i, j, k - 1, path_values) str_2 = self.Solver(i, k, k - 1, path_values) str_3 = self.Solver(k, k, k - 1, path_values) str_4 = self.Solver(k, j, k - 1, path_values) curr_case_str = "R(" + str(i) + "," + str(j) + "," + str(k) + ")" rec_eq_str = "R(" + str(i) + "," + str(j) + "," + str(k) + ") = " + \ "R(" + str(i) + "," + str(j) + "," + str(k - 1) + ") " + self.UNION_SYMBOL + " " + \ "R(" + str(i) + "," + str(k) + "," + str(k - 1) + ")" + \ "R(" + str(k) + "," + str(k) + "," + str(k - 1) + ")*" + \ "R(" + str(k) + "," + str(j) + "," + str(k - 1) + ")" formatted_return_str = self.EMPTY_SET unformated_formatted_return_str = (" " * len(curr_case_str)) + " = (" + str_1 + " " + self.UNION_SYMBOL + " " + str_2 + str_3 + '*' + str_4 + ')' part_1_is_empty = (str_1 == self.EMPTY_SET) part_2_is_empty = (str_2 == self.EMPTY_SET or str_3 == self.EMPTY_SET or str_4 == self.EMPTY_SET) if (not part_1_is_empty and part_2_is_empty): formatted_return_str = str_1 elif (part_1_is_empty and not part_2_is_empty): formatted_return_str = self.Formatter(str_1, str_2, str_3, str_4, self.IGNORE) elif (not part_1_is_empty and not part_2_is_empty): formatted_return_str = self.Formatter(str_1, str_2, str_3, str_4) saved_str = rec_eq_str + "\n" + unformated_formatted_return_str + "\n" + curr_case_str + " = " + formatted_return_str + "\n\n" if saved_str not in self.result_recorder[str(k)]: self.result_recorder[str(k)].append(saved_str) return formatted_return_str """ Formats the second porition of the string """ def Formatter(self, str_1, str_2, str_3, str_4, ignore_str_1 = False): kleene_star = '*' resulting_str = "" my_str_1 = str_1 my_str_2 = str_2 my_str_3 = str_3 my_str_4 = str_4 if (my_str_2 == my_str_3): kleene_star = '*' if (self.EMPTY_STRING in my_str_3 and self.UNION_SYMBOL in my_str_3) else '+' my_str_2 = "" elif (my_str_4 == my_str_3): kleene_star = '*' if (self.EMPTY_STRING in my_str_3 and self.UNION_SYMBOL in my_str_3) else '+' my_str_4 = "" elif (my_str_2 == my_str_3 and my_str_4 == my_str_3 and self.EMPTY_STRING in my_str_3 and self.UNION_SYMBOL in my_str_3): my_str_4 = "" my_str_2 = "" kleene_star = '*' if (self.EMPTY_STRING in my_str_3 and self.UNION_SYMBOL in my_str_3): e_index = my_str_3.find(self.EMPTY_STRING) u_index = my_str_3.find(self.UNION_SYMBOL) my_str_3 = my_str_3[u_index + 2:] #Guarenteed that 'e' is always before union if (my_str_3[-1] == ')'): my_str_3 = my_str_3[:-1] if (my_str_2 == my_str_3): kleene_star = '+' my_str_2 = "" elif (my_str_4 == my_str_3): kleene_star = '+' my_str_4 = "" if (my_str_3 == self.EMPTY_STRING): kleene_star = "" my_str_3 = "" if (my_str_2 == self.EMPTY_STRING): my_str_2 = "" if (my_str_4 == self.EMPTY_STRING): my_str_4 = "" if (len(my_str_3) != 1): my_str_3 = '(' + my_str_3 + ')' rhs_str = my_str_2 + my_str_3 + kleene_star + my_str_4 if (rhs_str == ""): rhs_str = self.EMPTY_STRING if ignore_str_1: resulting_str = rhs_str else: rhs_has_left = False if (kleene_star == '*'): rhs_has_left = ((my_str_4 == "" and (my_str_1 == my_str_2)) or (my_str_2 == "" and (my_str_1 == my_str_4))) if (my_str_1 == rhs_str or rhs_has_left): resulting_str = rhs_str else: resulting_str = '(' + my_str_1 + " " + self.UNION_SYMBOL + " " + rhs_str + ')' return resulting_str """ Writes the results to a file """ def Write_To_File(self, file_name): txt_file = open(file_name, 'w') for y in range(len(self.result_recorder) - 1, -1, -1): if y != 0: txt_file.write("\n\nPassing through " + str(y) + " intermediate states.\n\n") else: txt_file.write("\n\nPassing through no intermediate states.\n\n") for z in self.result_recorder[str(y)]: txt_file.write(z + "\n") txt_file.close()
#multiplicationTable(n) = [[1, 2, 3, 4, 5 ], # [2, 4, 6, 8, 10], # [3, 6, 9, 12, 15], # [4, 8, 12, 16, 20], # [5, 10, 15, 20, 25]] def table(n): collist=[] for j in range(1,n+1): rowlist=[] for i in range(1,n+1): rowlist.append(i*j) collist.append(rowlist) return collist print(table(5))
#a e i o u def vowel_count(sting): count=0 for i in range(len(sting)): if sting[i].lower() in "aeiou": count+=1 return count a="i love potato" print(vowel_count(a))
quistion=input("Please enter the base at the square root : ") quistion2=input("Please enter an indeces from the square root : ") quistion3=quistion for i in range(1,int(quistion2)): quistion3=int(quistion3)*int(quistion) #print(quistion) print(quistion3)
def math1(num): result=1 if num<=0: return 0 for i in range(1,num+1): result=result*i return result print(math1(0)) #8!=40,320 # No.2=============================================================================================================================== def math2(num2): if num2<=1: return 1 else: return (num2*math2(num2-1)) print(math2(8))
def dagaghyoung(n): if 360%(180-n)==0: return "yes" else: return "no" n=int(input()) alist=[] for i in range(n): m=int(input()) alist.append(m) for i in alist: print(dagaghyoung(i))
#coding=cp949 def hello(n): word="hello" index=0 for i in range(len(n)): if index==5: return "Yes" if n[i]==word[index]: index+=1 if index<5: return "No" else: return "Yes" m=input() print(hello(m))
f=input() s=input() if sorted(f)==sorted(s): print("anagram") # sorted(f) else: print("not anagram")
#a,b,c : start a b end c divisor def divisor(a,b,c): dlist=[] for i in range(a,b+1): if i%c==0: dlist.append(i) return dlist[-1] print(divisor(1,100,13)) #lambda========================================= divisor2=lambda a,b,c:b-b%c print(divisor2(1,100,13))
# array a=array([]) # list a=[2,3,4] # tuple a=(2,3,4) # dictionary a={1:'a',2:'b'} a=[1,2,3,4] print(a) print(a[0]) print(a[2]) print(len(a)) a[2]=100 print(a) b=['Babo',2,1,9] print(b) b[0]='BIBI' print(b) print(b*3) print(b.index(9)) print(2 in b) print('Babo' in b) #=============================================================================== # cha a={a,b,c} # printf(%s,a[0]) #=============================================================================== food=[] food.append('food') print(food) food.append('fighter') print(food) food.insert(1,1) print(food) potato="test" print(potato) tube=(1,2,3,4) print(tube) tube=1,2,3,4 print(tube) print(type(tube)) a,b=3,4 print(a) print(b) print(type(a))
num=int(input("input your number : ")) if num<0: print("This is negative number.") elif num>0: print("This is positive number.") elif num==0: print("This is 0") else: print("Please input number!!!!!!!")
''' 功能:nonlocal的使用(必须在函数内层里面) ''' def foo(): b = 123 #内层函数 def bar(): nonlocal b#必须先定义 不能定义附值一起弄 b = 456 print("b=", b) #调用内层函数 bar() print("b=", b) #主函数 foo()
#Summary: This Program is meant to take the same gene sequence and put it through #three reading frames in order to figure out which is best for reading. #The input is a gene, the gene then goes through the reading frames and is transcribed #and then translated into protein, all within the program. #The output: In each reading frame the gene is changed and broken up into codons, #each codon is matched to the according protein and that is printed out. #if there are any starts or stops inbetween it will be pointed out in the specific reading frame. #The intended purpose is to give all options for reading the gene and let the #user decide which is most effective for their purpose. import BioDNA def main(): print ("\n ---+++ Central Dogma +++---\n") AAtable = BioDNA.makeAminoAcidTable() for (tripleRNA, AAcode) in AAtable.items(): print (tripleRNA, AAcode) DNA = "ATGTGTACGCAAATGATATCGTATTAG"; print("-"*40) print (" DNA: 5'", DNA, "3'") # --------- TRANSCRIBE -------------------------- mRNA=BioDNA.transcribe(DNA) print(" ", "|"*len(mRNA)) print("mRNA: 5'", mRNA, "3'") print("\n==============================================================") print("Reading Frame #1") # --------- TRANSLATE Reading Frame #1 -------------------------- p=BioDNA.translate(mRNA, AAtable) print("RNA length:",len(mRNA)) print("RNA: ",mRNA,) print(" "," | "*(len(mRNA)//3)) print("Protein:", p,"\n") #most blocks of the if statements are the same throughout the readings #the only thing that changes is the gene. stop=p.find("***") if stop == len(p)-3: print("There is a stop codon at the end") else: print("There is no stop codon") #this searches for the index of the start find=mRNA.find("AUG") if find == 0: print("There is a met at", find) else: print("There is no Met at the start") #below I look through the middle midend=len(p)-3 mid=p[3:midend] mid_start=mid.find("Met") if mid_start >=0: print("there is a Met inbetween at position,", mid_start+3) else: print("there is no Met inbetween") mid_end=mid.find("***") if mid_end >=0: print("there is a *** inbetween at position,", mid_end+3) else: print("there is no *** inbetween") print("-"*40) print("==============================================================\n") print("\n==============================================================") print("Reading Frame #2") # --------- TRANSLATE Reading Frame #2 -------------------------- #Essentially the same codes as the last one but specific to this gene mRNA2=mRNA[1:] e=BioDNA.translate(mRNA2, AAtable) print("RNA length: ", len(mRNA2),"bp") print("RNA: 5'", mRNA2, "3'") print(" "," | "*(len(mRNA2)//3)) print("Protein:",e,"\n") find2=e.find("Met") end=e.find("***") if end == len(p)-3: print("There is a stop at the end") else: print("There is no stop at the end") if find2 == 0: print("There is a Met at", find2) else: print("There is no Met at the start") #ALl the text below till the next reading frame is specifically for the middle #of the code. midend1=len(e)-3 mid1=e[3:midend1] mid_start1=mid1.find("Met") #Checking the middle below if mid_start1 >=0: print("there is a start inbetween at position,", mid_start1+3) else: print("there is no Met inbetween") mid_end1=mid1.find("***") if mid_end1 >=0: print("there is a *** inbetween at position,", mid_end1+3) else: print("there is no *** inbetween") print("==============================================================\n") print ("\n==============================================================") print ("Reading Frame #3") # --------- TRANSLATE Reading Frame #3 -------------------------- mRNA3=mRNA2[1:] len3=len(mRNA3) print("RNA length: ",len3,"bp") t=BioDNA.translate(mRNA3, AAtable) mRNA3=BioDNA.transcribe(mRNA3) print("RNA: ",mRNA3) print(" ", " | "*(len(mRNA3)//3)) print("Protein:",t,"\n") find3=t.find("Met") finish=t.find("***") if finish == len(t)-3: print("There is a stop at the end") else: print("There is no stop codon") if find3 == 0: print("There is a met at", find3) else: print("There is no Met at the start") midend2=len(t)-3 mid2=t[3:midend2] mid_start2=mid2.find("Met") if mid_start2 >=0: print("there is a Met inbetween at position,", mid_start2+3) else: print("There is no Met inbetween") mid_end2=mid2.find("***") if mid_end2 >=0: print("there is a *** inbetween at position,", mid_end2+3) else: print("there is no *** in the middle") print ("==============================================================\n") # --- end main() --------- #--------------------------------------------------------- # Python starts here ("call" the main() function at start if __name__ == '__main__': main() #---------------------------------------------------------
from tkinter import * class About(Toplevel): def __init__(self): Toplevel.__init__(self) self.title("About") self.geometry("650x450+600+200") self.resizable(False, False) # frames self.top = Frame(self, height=100, bg='#a5b5c4') self.top.pack(fill=X) # self.bottom = Frame(master, height=500, bg='#e9e3ff') self.bottom = Frame(self, height=350, bg='#e6e39c') self.bottom.pack(fill=X) # top frame design self.top_image = PhotoImage(file='icons/about.png') self.top_image_label = Label(self.top, image=self.top_image, bg='#a5b5c4') self.top_image_label.place(x=200, y=26) # heading self.heading = Label(self.top, text='About', font='times 18 bold', bg='#a5b5c4', fg='black') self.heading.place(x=280, y=40) self.text= Label(self.bottom, text='Hey! thank you for taking the time to go though my project\n This project ' 'was build as a part of my internship \n For any queries you can write me' ' at \n: [email protected]', font='Sans 14 bold', bg='#e6e39c') self.text.place(x=40, y=100)
# 문제 : 해달이는 1부터 100까지의 숫자를 분류하려 한다. # 리스트 "mul2"에는 2의 배수, 리스트 "mul3"에는 3의 배수, # 리스트 "mul6"에는 6의 배수를 넣고 # 나머지 수는 모두 더해서 출력하려고 한다. 해달이를 도와주자 # 사용할 개념 : 리스트 , for, range, if, %, append, += mul2 = [] mul3 = [] mul6 = [] result = 0 for i in range(1,101): if (i % 6 == 0): mul6.append(i) for i in range(1,101): if (i % 3 == 0): if(i % 6 !=0): mul3.append(i) for i in range(1,101): if (i % 2 == 0): if(i % 6 !=0): mul2.append(i) for i in range(1,101): if(i % 2 ==1): if(i % 3 !=0): result += i print("mul2 : ",mul2) print("mul3 : ",mul3) print("mul6 : ",mul6) print("others : ",result)
m=input("Enter number of rows: ") n=input("Enter number of columns: ") a=[[0 for x in range(n)] for y in range(m)] print "Enter the matrix elements:\n" for i in range(0,m): for j in range(0,n): a[i][j]=input() print "\nThe input matrix is:\n" for i in range(0,m): for j in range(0,n): print a[i][j], print "\n" print "\nThe transpose is:\n" for i in range(0,n): for j in range(0,m): print a[j][i], print "\n"
#!/usr/bin/python3 n=input("Enter number of list items required:") list1=set() for i in range(n): x=raw_input("Enter item:") list1.add(x) n=input("Enter number of list items required:") list2=set() for i in range(n): x=raw_input("Enter item:") list2.add(x) print("List1:", list1) print("List2:", list2) print("OR:",list1 | list2) print("AND:",list1.intersection(list2)) print("DIFFERENCE:",list1.difference(list2)) print("SYMMETRIC DIFFERENCE:",list1.symmetric_difference(list2))
import itertools class NoFieldsError(Exception): pass class FormatError(Exception): pass def recursive_hierarchy(elements, fields): if not fields: return elements nodes = [] # Clone fields and remove first element fields = fields[:] field = fields.pop(0) # Sort elements by current field to allow grouping ordered_elements = sorted(elements, key=lambda k: k[field]) for k, g in itertools.groupby(ordered_elements, lambda el: el[field]): node = { 'title': k, 'nodes': recursive_hierarchy(list(g), fields) } nodes.append(node) return nodes def build_hierarchy(elements, fields): """Takes a list of dicts and groups them in an hierarchical way respecting the order provied by "fields". First field is used to group the first layer. :param elements: list of JSON objects :param fields: list of fields to use as grouping keys. Order matters :return: a JSON list with the format [ {title: "something1", nodes:[{title: "something2", nodes:[...]}]}] """ if not fields: raise NoFieldsError('Please provide an iterable of key strings') elif not isinstance(fields, list): raise FormatError("The 'fields' parameter must be of type <list>") return recursive_hierarchy(elements, fields)
#!/usr/bin/env python """ Script to automatically add inline code comments Read in the code to be processed from a provided filename or from stdin. Read in the user’s GTP_API_KEY from an environment variable. Split out the preamble code before the first function definition, such as /^def / for python or /^\s*(public|private) / for java. Split the code into chunks beginning with each function definition line. For each non-preamble chunk, construct a Codex prompt consisting of the contents of autocomment-example.txt followed by the code chunk and the line "Same function with verbose inline comments:". - Use Temperature 0, with a Stop sequence of "Original code:", to make Codex stop after it finishes generating the commented code. - Call the Codex API with the constructed prompt using the user’s GTP_API_KEY. API calls look like: ``` data = json.dumps({ "prompt": prompt, "max_tokens": 1500, "temperature": 0, "stop": "Original code:" }) headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(GPT_API_KEY) } response = requests.post('https://api.openai.com/v1/engines/davinci-codex/completions', headers=headers, data=data) ``` The response is json, and the output we want is in ['choices'][0]['text']. - Replace the original code chunk with the commented one, move on to the next chunk, and repeat the same process. - If the script was called with a filename, output the commented code to a .new file. Otherwise output it to stdout. """ import json import os import re import requests import sys GPT_API_KEY = os.environ['GPT_API_KEY'] """ The algorithm above should be divided into modular functions. The top-level functions are: - read_code - split_into_chunks - comment_chunk - comment_code - comment_code_from_file - comment_code_from_stdin """ def read_code(filename): """ Read code from a file or stdin and return it as a string """ # If filename is not None, open it for reading if filename: with open(filename, 'r') as f: # Read the code from the file code = f.read() # Otherwise read the code from stdin else: code = sys.stdin.read() # Return the code return code def split_into_chunks(code): """ Split code into chunks, each chunk being a function definition """ # Create an empty list to store chunks chunks = [] # Create a string to store the current chunk chunk = '' # For each line in the code for line in code.splitlines(): # If the line is a python or java function definition if re.match(r'^\s*(def|public|private)\s', line): # Add the current chunk to the list of chunks chunks.append(chunk) # And reset the current chunk chunk = '' # Add the line to the current chunk chunk += line + '\n' # Add the last chunk to the list of chunks chunks.append(chunk) # Return the list of chunks return chunks def comment_chunk(chunk): """ Comment a single chunk of code """ prompt = open('autocomment-example.txt', 'r').read() prompt += '\n' + chunk + '\nSame function with verbose inline comments:\n' #print(prompt) data = json.dumps({ "prompt": prompt, "max_tokens": 1500, "temperature": 0, "stop": "Original code:" }) headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(GPT_API_KEY) } response = requests.post('https://api.openai.com/v1/engines/davinci-codex/completions', headers=headers, data=data) print(response.json()['choices'][0]['text']) return response.json()['choices'][0]['text'] def comment_code(code): """ Comment code, given as a string. """ # Split code into chunks chunks = split_into_chunks(code) # Comment each chunk commented_chunks = [comment_chunk(chunk) for chunk in chunks] # Return the joined chunks return '\n'.join(commented_chunks) def comment_code_from_file(filename): """ Comment code from a file, outputting to a .new file. """ # Read the code from the file code = read_code(filename) # Comment the code commented_code = comment_code(code) # Open the new file with open(filename + '.new', 'w') as f: # Write the commented code to the file f.write(commented_code) def comment_code_from_stdin(): """ Comment code from stdin """ # Read code from stdin code = read_code(None) # Comment code commented_code = comment_code(code) # Print commented code print(commented_code) if __name__ == '__main__': # If there is only one argument if len(sys.argv) == 1: # Call the function to comment code from stdin comment_code_from_stdin() # If there is more than one argument else: # Call the function to comment code from file comment_code_from_file(sys.argv[1])
"""main_a3.py """ import re import os import nltk from nltk.corpus import wordnet as wn from nltk.corpus import PlaintextCorpusReader # NLTK stoplist with 3136 words (multilingual) STOPLIST = set(nltk.corpus.stopwords.words()) # Vocabulary with 234,377 English words from NLTK ENGLISH_VOCABULARY = set(w.lower() for w in nltk.corpus.words.words()) # The five categories from Brown that we are using BROWN_CATEGORIES = ('adventure', 'fiction', 'government', 'humor', 'news') # Global place to store Brown vocabularies so you calculate them only once BROWN_VOCABULARIES = None def is_content_word(word): """A content word is not on the stoplist and its first character is a letter.""" return word.lower() not in STOPLIST and word[0].isalpha() class Text(object): def __init__(self, path, name=None): """Takes a file path, which is assumed to point to a file or a directory, extracts and stores the raw text and also stores an instance of nltk.text.Text.""" self.name = name if os.path.isfile(path): self.raw = open(path).read() elif os.path.isdir(path): corpus = PlaintextCorpusReader(path, '.*.mrg') self.raw = corpus.raw() self.text = nltk.text.Text( nltk.word_tokenize(self.raw)) def __len__(self): return len(self.text) def __getitem__(self, i): return self.text[i] def __str__(self): name = '' if self.name is None else " '%s'" % self.name return "<Text%s tokens=%s>" % (name, len(self)) def token_count(self): """Just return the length of the text.""" return len(self) def type_count(self): """Returns the type count, with minimal normalization by lower casing.""" # an alternative would be to use the method nltk.text.Text.vocab() return len(set([w.lower() for w in self.text])) def sentence_count(self): """Return number of sentences, using the simplistic measure of counting period, exclamation marks and question marks.""" # could also use nltk.sent.tokenize on self.raw return len([t for t in self.text if t in '.!?']) def most_frequent_content_words(self): """Return a list with the 25 most frequent content words and their frequencies. The list has (word, frequency) pairs and is ordered on the frequency.""" dist = nltk.FreqDist([w for w in self.text if is_content_word(w.lower())]) return dist.most_common(n=25) def most_frequent_bigrams(self, n=25): """Return a list with the 25 most frequent bigrams that only contain content words. The list returned should have pairs where the first element in the pair is the bigram and the second the frequency, as in ((word1, word2), frequency), these should be ordered on frequency.""" filtered_bigrams = [b for b in list(nltk.bigrams(self.text)) if is_content_word(b[0]) and is_content_word(b[1])] dist = nltk.FreqDist([b for b in filtered_bigrams]) return dist.most_common(n=n) def concordance(self, word): self.text.concordance(word) ## new methods for search part of assignment 3 def search(self, pattern): return re.finditer(pattern, self.raw) def find_sirs(self): answer = set() for match in self.search(r"\bSir \S+\b"): answer.add(match.group()) return sorted(answer) def find_brackets(self): answer = set() # use a non-greedy match on the characters between the brackets for match in self.search(r"([\(\[\{]).+?([\)\]\}])"): brackets = "%s%s" % (match.group(1), match.group(2)) # this tests for matching pairs if brackets in ['[]', '{}', '()']: answer.add(match.group()) return sorted(answer) def find_roles(self): answer = set() for match in re.finditer(r"^([A-Z]{2,}[^\:]+): ", self.raw, re.MULTILINE): answer.add(match.group(1)) return sorted(answer) def find_repeated_words(self): answer = set() for match in self.search(r"(\w{3,}) \1 \1"): answer.add(match.group()) return sorted(answer) def apply_fsa(self, fsa): i = 0 results = [] while i < len(self): match = fsa.consume(self.text[i:]) if match: results.append((i, match)) i += len(match) else: i += 1 return results class Vocabulary(): """Class to store all information on a vocabulary, where a vocabulary is created from a text. The vocabulary includes the text, a frequency distribution over that text, the vocabulary items themselves (as a set) and the sizes of the vocabulary and the text. We do not store POS and gloss, for those we rely on WordNet. The vocabulary is contrained to those words that occur in a standard word list. Vocabulary items are not normalized, except for being in lower case.""" def __init__(self, text): self.text = text.text # keeping the unfiltered list around for statistics self.all_items = set([w.lower() for w in text]) self.items = self.all_items.intersection(ENGLISH_VOCABULARY) # restricting the frequency dictionary to vocabulary items self.fdist = nltk.FreqDist(t.lower() for t in text if t.lower() in self.items) self.text_size = len(self.text) self.vocab_size = len(self.items) def __str__(self): return "<Vocabulary size=%d text_size=%d>" % (self.vocab_size, self.text_size) def __len__(self): return self.vocab_size def frequency(self, word): return self.fdist[word] def pos(self, word): # do not volunteer the pos for words not in the vocabulary if word not in self.items: return None synsets = wn.synsets(word) # somewhat arbitrary choice to make unknown words nouns, returning None # or 'UNKNOWN' would have been fine too. return synsets[0].pos() if synsets else 'n' def gloss(self, word): # do not volunteer the gloss (definition) for words not in the vocabulary if word not in self.items: return None synsets = wn.synsets(word) # make a difference between None for words not in vocabulary and words # in the vocabulary that do not have a gloss in WordNet return synsets[0].definition() if synsets else 'NO DEFINITION' def kwic(self, word): self.text.concordance(word)
# Write a function that takes in a potentially invalid Binary Search Tree (BST) and returns # a boolean representing whether the BST is valid. # Each BST node has an integer value , a left child node, anda right child # node. A node is said to be a valid BST node if and only if it satisfies the BST property: # its value is strictly greater than the values of every node to its left; its value is less # than or equal to the values of every node to its right; and its children nodes are either # valid BST nodes themselves or None / null . # A BST is valid if and only if all of its nodes are valid BST nodes. class BST: def __init__(self, value): self.value = value self.left = None self.right = None def validateBst(tree): # Write your code here. return validateBstHelper(tree, float("-inf"),float("inf")) def validateBstHelper(tree,minValue,maxValue): if tree is None: return True if tree.value < minValue or tree.value>= maxValue: return False return validateBstHelper(tree.left,minValue,tree.value) and validateBstHelper(tree.right,tree.value,maxValue)
# It's photo day at the local school, and you're the photographer assigned to take class # photos. The class that you'll be photographing has an even number of students, and all # these students are wearing red or blue shirts. In fact, exactly half of the class is wearing # red shirts, and the other half is wearing blue shirts. You're responsible for arranging the # students in two rows before taking the photo. Each row should contain the same # number of the students and should adhere to the following guidelines: # • All students wearing red shirts must be in the same row. # • All students wearing blue shirts must be in the same row. # • Each student in the back row must be strictly taller than the student directly in # front of them in the front row. # You're given two input arrays: one containing the heights of all the students with red # shirts and another one containing the heights of all the students with blue shirts. These # arrays will always have the same length, and each height will be a positive integer. Write # a function that returns whether or not a class photo that follows the stated guidelines # can be taken. # Note: you can assume that each class has at least 2 students. # Sample Input: # redShirtHeights = [5, 8, 1, 3, 4] # blueShirtHeights = [6, 9, 2, 4, 5] # Sample Output: # true def classPhotos(redShirtHeights, blueShirtHeights): # Write your code here. redShirtHeights.sort() blueShirtHeights.sort() countr,countb=0,0 for i in range(len(redShirtHeights)): if redShirtHeights[i]> blueShirtHeights[i]: countr+=1 elif blueShirtHeights[i]>redShirtHeights[i] : countb+=1 if countr == len(redShirtHeights) or countb == len(redShirtHeights): return True else: return False