text
stringlengths
37
1.41M
def greet(lang): if lang == 'es': print ('Hola') elif lang == 'fr': print ('Bonjour') else: print ('Hello') greet('en') greet('es') greet('fr')
''' Take input of negative and positive integers. Output numbers, negative numbers first, then positive integers, preserving order Why? How might this be used? What's the size of the input? Any other requirements? Solution brainstorm: Scan input twice, once for negative, once for positive values, output values in order Scan once, use two stacks, one for positive, one for negatives Scan once, use two output arrays Generator with a position marker? ''' # Input X = [4, -2, 5, -1, 6, -3 ] # Sample output Y = [-2, -1, -3, 4, 5, 6 ] # Answer buffer A = [] # scan twice for x in X: if x < 0: A.append(x) for x in X: if x >= 0: A.append(x) print ('Input ', X) print ('Answer 1', A) assert A == Y negative=[] positive=[] for x in X: if x < 0: negative.append(x) else: positive.append(x) import numpy as np A2 = np.concatenate( [ negative, positive ] ).tolist() print ('Answer 2', A2)
import random import re # Take an input and remove all the spaces, then convert it entirely to # lowercase. Then, make sure that the last char of the string is a number or # letter. def cleanse(input): input = (input.replace(" ","")).lower() if re.match('[0-9a-zA-Z]', input[len(input)-1]): return input class Roller(object): def __init__(self): self.bonus = 0 # Take list of dice in the form [[positive][negative]] and output an array # of integers equal to the rolls that result. def rollDice(self, dice): rolls = [] if len(dice[0]) > 0: for roll in dice[0]: if 'd' not in roll: self.bonus += int(roll) continue request = roll.split('d') n = int(request[0]) sides = int(request[1]) for i in range(n): rolls.append(random.randint(1,sides)) if len(dice[1]) > 0: for roll in dice[1]: if 'd' not in roll: self.bonus -= int(roll) continue request = roll.split('d') n = int(request[0]) sides = int(request[1]) for i in range(n): rolls.append(random.randint(1,sides) * -1) return rolls # Take a list of dice rolls and the dice that generated those rolls and # generate a pretty string def parseDice(self, dice, rolls): if self.bonus == 0: op = '' strBonus = '' elif self.bonus >= 1: op = '+' strBonus = str(self.bonus) else: op = '-' strBonus = str(abs(self.bonus)) rollStr = ' '.join(str(i) for i in rolls) + " %s %s" % (op, strBonus) posList = [] # list of positive dice posNums = '' for n in dice[0]: if 'd' in n: posList.append(n) dice[0].remove(n) posDice = '+'.join(posList) if len(dice[0]) > 0: posNums = "+" + '+'.join(dice[0]) negList = [] # list of 'negative dice' negNums = '' if len(dice[1]) > 0: for n in dice[1]: if 'd' in n: negList.append(n) dice[1].remove(n) negDice = "-" + '-'.join(negList) if len(dice[1]) > 0: negNums = "-" + '-'.join(dice[1]) else: negDice = '' return(str(sum(rolls) + self.bonus) + ' (' + posDice + negDice + posNums + negNums + '): ' + rollStr) # Take multiple dice rolls and return them each as a string in a list, so that # '1d10 + 2d6' gives [[1d10, 2d6],[]] and '1d10 + 2d12 - 1d6' gives [[1d10, 2d12],[1d6]] def multiples(self, input): res = [[],[]] # res[0] = boons, res[1] = banes pos = input.split('+') for i in pos: temp = i.split('-') if len(temp) > 1: res[0].append(temp[0]) res[1] += temp[1:] else: res[0] += temp return res def splitDice(self, unit): dice = re.search('[0-9]*d[0-9]*', unit) if dice: new = unit.split(dice.group()) return new + [dice.group()] else: return [] def module(self): go = True verify = True # Loop for rolling dice while go: input = raw_input("Roll condition: ") input = cleanse(input) dice = [[],[]] if input == 'exit' or input == 'quit': go = False print("Quitting module.") break elif input.count('d') > 0: dice = self.multiples(input) else: dice[0].append(input) rolls = self.rollDice(dice) if rolls == []: print("Error - format not recognized.") verify = False if verify: result = self.parseDice(dice, rolls) self.bonus = 0 print result
""" https://www.pyimagesearch.com/2015/11/16/hog-detectmultiscale-parameters-explained/ --image switch is the path to our input image that we want to detect pedestrians in. --win-stride is the step size in the x and y direction of our sliding window. --padding switch controls the amount of pixels the ROI is padded with prior to HOG feature vector extraction and SVM classification. To control the scale of the image pyramid (allowing us to detect people in images at multiple scales), we can use the --scale argument. --mean-shift can be specified if we want to apply mean-shift grouping to the detected bounding boxes. -- Default USAGE $ python main_hog.py --image images/person_010.bmp --The smaller winStride is, the more windows need to be evaluated (which can quickly turn into quite the computational burden): $ python main_hog.py --image images/person_010.bmp --win-stride="(4, 4)" -- winStride is the less windows need to be evaluated (allowing us to dramatically speed up our detector). However, if winStride gets too large, then we can easily miss out on detections entirely: $ python main_hog.py --image images/person_010.bmp --win-stride="(16, 16)" -- A smaller scale will increase the number of layers in the image pyramid and increase the amount of time it takes to process your image: $ python detectmultiscale.py --image images/person_010.bmp --scale 1.01 """ from __future__ import print_function import argparse import datetime from imutils import paths import imutils import cv2 def get_hog_features(trainingSetPath, win_stride, padding, mean_shift, scale): # evaluate the command line arguments (using the eval function like # this is not good form, but let's tolerate it for the example) winStride = eval(win_stride) padding = eval(padding) meanShift = True if mean_shift > 0 else False # initialize the HOG descriptor/person detector hog = cv2.HOGDescriptor() #hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) # CHECK FOR IT! # initialize the local binary patterns descriptor along with the data and label lists labels = [] data = [] test_labels = [] test_data = [] # loop over the training images for imagePath in paths.list_files(trainingSetPath, validExts=(".png",".ppm")): # open image img = cv2.imread(imagePath, cv2.IMREAD_GRAYSCALE) # resized_image = cv2.resize(img, (32, 32)) # RESIZING rects, weights = hog.detectMultiScale(img, winStride=winStride, padding=padding, scale=scale, useMeanshiftGrouping=meanShift) print (rects) # get hog features """STAYED HERE!""" # extract the label from the image path, then update the # label and data lists labels.append(imagePath.split("/")[-2]) data.append(weights) if __name__ == '__main__': # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-t", "--training", required=True, help="path to training dataset") ap.add_argument("-w", "--win-stride", type=str, default="(8, 8)", help="window stride") ap.add_argument("-p", "--padding", type=str, default="(16, 16)", help="object padding") ap.add_argument("-s", "--scale", type=float, default=1.05, help="image pyramid scale") ap.add_argument("-m", "--mean-shift", type=int, default=-1, help="whether or not mean shift grouping should be used") args = vars(ap.parse_args()) get_hog_features(args["training"], args["win_stride"], args["padding"],args["mean_shift"], args["scale"])
# Convert C To F C=eval(input("Enter the Temperature in Cel. : ")) F =(C*9/5)+32 print(f"The Temperature : {F} in F")
# reverse of digit n= eval(input("Enter the no.")) d=0 rev=0 while n!=0: d=n%10 rev=rev*10+d n//=10 print(rev)
# Funcionalidad relacionada con el menú """ Autores: Nicolás Olabarría Fecha: 9 de Junio de 2021 Tema: Menú """ import pandas as pd def menu(): """ The menu() function asks for a route and stores it in a string variable. :return: A list of strings with the routes to the files """ # Mensajes utilizados en el menú message_option = '¿Cómo quiere leer las direcciones de los datasets?[man/txt]: ' message_not_valid = 'Opción no válida. Introdúzcalo de nuevo\n' print( 'Puedes introducir los datos manualmente (man), o si los tienes en un .txt hacerlo de manera automática (txt)') option = input(message_option) while option.upper() != 'MAN' and option.upper() != 'TXT': print(message_not_valid) option = input(message_option) route = [] if option.upper() == 'MAN': route = lectura_manual() elif option.upper() == 'TXT': route = lectura_txt() return route def lectura_manual(): """ Lectura de las rutas de manera manual. :return: Devuelve una lista de rutas introducidas de manera manual. """ message_done = 'Si quiere terminar el proceso escribe "Done"\n' message_route = 'Introduzca la dirección del archivo: ' print(message_done) command = input(message_route) route = [] if command.upper() != 'DONE': while command.upper() != 'DONE': while True: try: data = pd.read_csv(command) break except FileNotFoundError: print('La dirección no es correcta') command = input(message_route) route.append(command) command = input(message_route) return route def lectura_txt(): """ Función para la lectura de las rutas de manera automática. :return: Devuelve una lista de rutas sacadas de un archivo .txt. """ txt_route = input('Introduzca la ruta del archivo: ') while True: try: with open(txt_route, 'r') as route_file: route = [] i = 1 for line in route_file.readlines(): print('Ruta ', i, ':', line) i+=1 line = line.replace("\n", "") route.append(line) break except FileNotFoundError: txt_route = input('La ruta no es válida, introdúzcala de nuevo: ') return route
# Project 1 for Numerical Algorithms #Charles Rohart, Ingrid Odlen, Laroy Sjödahl, Niklas Lindeke import CSplines as CS from numpy import * """ Testing environment for the Cubic Spline algorithm """ class dtest: """ Test class devised to investigate the relationship of the first and second derivative between two adjacent points """ def __init__(self): self.y = CS.CSplines(CS.spline()[1],CS.spline()[0])()[1] self.x = CS.CSplines(CS.spline()[1],CS.spline()[0])()[0] def deriv(self): """ Testing the Cubic Spline property f''i-1(xi) = f''i(xi) """ if len(self.x) == len(self.y): holds = 0 for i in range(0,len(self.x)-8,8): # Assuming Polyfit Returns the vector containing [Ax^3 + Bx^2 + Cx + D] as [ A B C D] left = polyfit(self.x[i:i+4],self.y[i:i+4],3) right = polyfit(self.x[i+4:i+8],self.y[i+4:i+8],3) first_left = left * [3,2,1,0] first_right = right * [3,2,1,0] second_left = first_left * [2,1,0,0] second_right = first_right * [2,1,0,0] x = self.x[i:i+4] for j in range(0,len(x),1): # righteval should be equal to lefteval if this prperty holds righteval = x[j]*second_right[0] + second_right[1]*x[j] lefteval = x[j]*second_left[0] + second_left[1]*x[j] if righteval == lefteval: holds=+1 else: return "x and y coordinates don't match" holds = str(holds) return "The property held " + holds + " times over the spline." class speed: """ tests the overall speed of __call__ in CSplines, I think would be the easiest to use when testing different versions of functions """ def testAlgoSpeed(self): a=array([]) c=CS.CSplines(CS.spline()[1],CS.spline()[0]) for i in range(30): c.tic() c() a=append(a,c.toc()) average=0 Tsum=0 for i in range(30): Tsum+=a[i] average=Tsum/30 print("Average time over ",str(30)," tries is: ",str(average))
import twitter import sys from collections import Counter def collect_hashtags(tweets): """ Retieve the hashtags of a list of tweets """ hashtags = Counter() for tweet in tweets: hashtags.update([hashtag['text'] for hashtag in tweet.get('entities').get('hashtags')]) return hashtags if __name__ == "__main__": token = twitter.authenticate() search = sys.argv[1] count = int(sys.argv[2]) or 15 tweets = twitter.get_tweets(search, token, count) #for tweet in tweets: # print('{} : {}'.format(tweet.get('id'), tweet.get('text'))) # print('Hashtags : {}'.format(", ".join([tag['text'] for tag in tweet.get('entities').get('hashtags')]))) print(collect_hashtags(tweets))
"""Скрипт, принимающий на вход json-файл, в котором указанны параметры предметов культурного наследия, и возвращающая для каждого типа кол-во предметов и среднее значения года создания""" import json from collections import namedtuple Result = namedtuple('Result', 'count average') data = {} # json_data into data with open('10_data_gov_ru.json', 'r', encoding='utf8') as f: json_data = json.load(f) # print(json_data) """ json_data - список из словарей (один словарь - один предмет культурного наследия) следующего вида: [{'global_id': 19666571, 'system_object_id': '7033', 'ID': '7033', 'AISID': '9689', 'ObjectNameOnDoc': '<Могила> Мартынова Алексея Васильевича (1868-1934)', 'EnsembleNameOnDoc': 'Новодевичье кладбище', 'SecurityStatus': 'объект культурного наследия', 'Category': 'регионального значения', 'ObjectType': 'Могила'}, ..., {...}] """ def get_year(string: str)->int: """ return the last year(YYYY) detected in a json_data_dict['ObjectNameOnDoc'] :param string :return: integer >>> get_year('- Жилой дом для служащих с магазином, 1896 г., гражданский инженер О.Ф.Дидио') 1896 """ c = '' for char in string: if char.isdigit(): c += char return int(c[-4:]) # subgenerator def averager(): total = 0 count = 0 average_year = None while True: term = yield if term is None: break total += term count += 1 average_year = total/count return Result(count, average_year) # delegator def grouper(results, key): while True: results[key] = yield from averager() # client code def client(data): results = {} for keys, values in data.items(): group = grouper(results, keys) next(group) for value in values: group.send(value) else: group.send(None) report(results) # print formatted result def report(results): for key, result in sorted(results.items()): print('{:40} {:10} шт среднее: {:.0f} г '.format(key, result.count, result.average)) # json-file(json_data) processed into one dictionary(data) in the format presented below # data = {'Могила': [], ... 'Скульптура': []} for dictionaries in json_data: data[dictionaries['ObjectType']] = [] # data = {'Могила': [1949, 1874,], ... 'Скульптура': [1945]} for dictionaries in json_data: data[dictionaries['ObjectType']].append(get_year(dictionaries['ObjectNameOnDoc'])) if __name__ == '__main__': client(data) import doctest doctest.testmod()
a=int(input("Enter first no.= ")) b=int(input("Enter second no.= ")) c=int(input("Enter third no.= ")) if(a>b and a>c): print(a) elif(a>b and a<c): print(c) else: print(b)
import requests #import os from datetime import datetime api_key = '12f3fe0150a34c3e74ba3e458f6e0b7d' location = input("Enter the city name: ") complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+location+"&appid="+api_key api_link = requests.get(complete_api_link) api_data = api_link.json() #create variables to store and display data temp_city = ((api_data['main']['temp']) - 273.15) weather_desc = api_data['weather'][0]['description'] hmdt = api_data['main']['humidity'] wind_spd = api_data['wind']['speed'] date_time = datetime.now().strftime("%d %b %Y | %I:%M:%S %p") file = open("output.txt", "w") l=str("\n-------------------------------------------------------------\n") print(l) file.write(str(l)) s="Weather Stats for - {} || {}".format(location.upper(), date_time) print(s) file.write(str((s))) file.write(l) print (l) m ="Current temperature is: {:.2f} deg C\n".format(temp_city) print(m) file.write(m) o = ("Current Weather desc :"+weather_desc+"\n") print(o) file.write(o) p = ("Current Humidity :"+str(hmdt)+'%\n') print(p) file.write(p) q = ("Current Wind Speed :"+str(wind_spd)+'kmph\n') print(q) file.write(q) file.close()
from pandas import DataFrame dframe = DataFrame({'city': ['Alma', 'Brian Head', 'Fox Park'], 'altitude':[3158,3000,2752]}) state_map = {'Alma':'Colorado', 'Brian Head':'Utah', 'Fox Park':'Wyoming'} print (dframe) dframe['state'] = dframe['city'].map(state_map)#state_mapのcityに紐づいたデータの列が出来る print (dframe) dframe['key1'] = [0,1,2]#key1に0,1,2を追加
VERTICAL, HORIZONTAL = 0, 1 MOVE_UP, MOVE_DOWN, MOVE_LEFT, MOVE_RIGHT = "u", "d", "l", "r" VALID_NAMES = {"Y", "B", "O", "W", "G", "R"} # Message text: INVALID_ORIENTATION = "You had entered an invalid orientation" CAUSE_THE_CAR = "Causes the car to go" UP = "up" DOWN = "down" LEFT = "left" RIGHT = "right" class Car: """ Add class description here """ def __init__(self, name, length, location, orientation): """ A constructor for a Car object :param name: A string representing the car's name :param length: A positive int representing the car's length. :param location: A tuple representing the car's head (row, col) location :param orientation: One of either 0 (VERTICAL) or 1 (HORIZONTAL) """ self.__name = name self.__length = length self.__location = location self.__orientation = orientation self.__location_h = location[1] self.__location_v = location[0] def car_coordinates(self): """ :return: A list of coordinates(tuples) the car is in """ output = [] if self.__orientation is VERTICAL: # Case for Vertical Orientation for v in range(self.__length): output.append((self.__location_v + v, self.__location_h)) elif self.__orientation is HORIZONTAL: # Case for Vertical Orientation for h in range(self.__length): output.append((self.__location_v, self.__location_h + h)) else: return INVALID_ORIENTATION return output def possible_moves(self): """ :return: A dictionary of strings describing possible movements permitted by this car. """ result = {} if self.__orientation is VERTICAL: # Case for Vertical Orientation result['u'] = CAUSE_THE_CAR + UP result['d'] = CAUSE_THE_CAR + DOWN if self.__orientation is HORIZONTAL: # Case for Vertical Orientation result['l'] = CAUSE_THE_CAR + LEFT result['r'] = CAUSE_THE_CAR + RIGHT return result def movement_requirements(self, movekey): """ :param movekey: A string representing the key of the required move. :return: A list of cell locations which must be empty in order for this move to be legal. """ result = [] if movekey == MOVE_UP: result.append((int(self.car_coordinates()[0][0]) - 1, self.car_coordinates()[0][1])) if movekey == MOVE_DOWN: result.append(((int(self.car_coordinates()[-1][0])) + 1, self.car_coordinates()[-1][1])) if movekey == MOVE_LEFT: result.append((self.car_coordinates()[0][0], int(self.car_coordinates()[0][1]) - 1)) if movekey == MOVE_RIGHT: result.append((self.car_coordinates()[-1][0], int(self.car_coordinates()[-1][1]) + 1)) return result def move(self, movekey): """ :param movekey: A string representing the key of the required move. :return: True upon success, False otherwise """ # Tests for restricted movesr,r if self.__orientation == HORIZONTAL \ and movekey not in [MOVE_RIGHT, MOVE_LEFT]: return False if self.__orientation == VERTICAL \ and movekey not in [MOVE_UP, MOVE_DOWN]: return False # Moves the car if movekey == MOVE_RIGHT: # Move Right self.__location = (self.__location_v, self.__location_h + 1) if movekey == MOVE_LEFT: # Move Left self.__location = (self.__location_v, self.__location_h - 1) if movekey == MOVE_UP: # Move up self.__location = (self.__location_v - 1, self.__location_h) if movekey == MOVE_DOWN: # Move Down self.__location = (self.__location_v + 1, self.__location_h) self.__location_v, self.__location_h = self.__location return True # If everything is cool, return def get_name(self): """ :return: The name of this car. """ return self.__name
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def largestValues(self, root: TreeNode) -> List[int]: if not root: return [] result = [] self.helper(root, result) return result def helper(self, node: TreeNode, result: List[int]): queue = [node] while queue: currentMax, next = float('-inf'), [] for i in range(len(queue)): n = queue[i] if n.val > currentMax: currentMax = n.val if n.left: next.append(n.left) if n.right: next.append(n.right) result.append(currentMax) queue = next
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reversePrint(self, head: ListNode) -> List[int]: result = [] self.helper(result, head) return result def helper(self, result: List[int], node: ListNode): if node == None: return [] elif node.next == None: result.append(node.val) else: self.helper(result, node.next) result.append(node.val)
def extract_bits(number): str_num = bin(number) str_num = str_num.replace("0b", "") bits = [int(x) for x in str_num] bits.reverse() return bits def extract_8_bits(number): str_num = bin(number) str_num = str_num.replace("0b", "") bits = [int(x) for x in str_num] return [0] * (8 - len(bits)) + bits def extract_flags(val, n_flags): flags = [bool(b) for b in extract_8_bits(val)] return [False] * (n_flags - len(flags)) + flags # please dont call this def flags_to_val(flags): flags = ([0] * (8 - len(flags))) + flags val = [i * (2 ** int(r)) for i, r in zip(flags, range(0, len(flags)))] return sum(val) # Returns the decimal value of a bit sequence starting with the highest bit def flags_to_val_2(flags): val = [i * (2 ** r) for i, r in zip(flags, range(len(flags) - 1, -1, -1))] return sum(val) # Returns the decimal value of a bit sequence starting with the lowest bit def flags_to_val_low(flags): val = [i * (2 ** int(r)) for i, r in zip(flags, range(0, len(flags)))] return sum(val) def is_negative(number, n_digits): bits = extract_bits(number) if len(bits) < n_digits: return False return bits[n_digits - 1] == 1 # negative, last bit == 1 def extract_2byteFrom16b(num): highbyte = apply_higher_byte_mask(num) lowebyte = apply_lower_byte_mask(num) return lowebyte, highbyte def make_16b_binary(highByte, lowByte): return (highByte << 8) + lowByte def add_binary_overflow(x, y, maxlen): return (x + y) % (2 ** maxlen) def add_binary_overflow_255(x, y): return (x + y) & 0b11111111 def apply_mask(number, mask): return number & mask def apply_lower_byte_mask(number): return number & 0xFF def apply_higher_byte_mask(number): return (number >> 8) & 0xFF
import numpy as np def pad_image(img, size, value): # Measure difference from the desired width width = size-img.shape[0] # Check if even or odd if(width%2!=0): width_b = int(width/2) width_a = width_b+1 else: width_b = int(width/2) width_a = width_b # check if even or odd height = size-img.shape[1] if(height%2!=0): height_b = int(height/2) height_a = height_b+1 else: height_b = int(height/2) height_a = height_b # Padding with the folowing dimension pad_width = ((width_b,width_a),(height_b,height_a),(0,0)) # Do padding img_new = np.pad(img, pad_width=pad_width, mode="constant", constant_values=value) return img_new
#! usr/bin/env python3.7 from random import random from tkinter import * def hide_show(): if label.winfo_viewable(): label.grid_remove() else: label.grid() root = Tk() label = Label(text='Я здесь!') # Выводит текст label.grid() button = Button(command=hide_show, text='Спрятать/Показать') # кнопка которая прячет текс при нажатии button.grid() root.mainloop()
#!/usr/bin/python import os from random import * class Board(): def __init__(self): self.cell = [" "," "," "," "," "," "," "," "," "," "] def display(self): print (" %s | %s | %s " %(self.cell[1], self.cell[2],self.cell[3])) print ("-----------") print (" %s | %s | %s " %(self.cell[4], self.cell[5],self.cell[6])) print ("-----------") print (" %s | %s | %s " %(self.cell[7], self.cell[8],self.cell[9])) def initial_board(self): x = randint(1,9) y = randint(1,9) if self.cell[x] == " ": self.cell[x] = 2 if self.cell[y] == " ": self.cell[y] = 2 def update_cell(self, cell_no): if self.cell[cell_no] == " ": self.cell[cell_no] = 2 def rmove(self,n): if self.cell[n] == " ": if (self.cell[n-1] == " ") and (self.cell[n-2] != " "): self.cell[n] = self.cell[n-2] self.cell[n-2] = " " elif (self.cell[n-2] == " ") and (self.cell[n-1] != " "): self.cell[n] = self.cell[n-1] self.cell[n-1] = " " elif (self.cell[n-2] != " ") and (self.cell[n-1] != " ") and (self.cell[n-2] == self.cell[n-1]): self.cell[n] = self.cell[n-2] + self.cell[n-1] self.cell[n-2] = " " self.cell[n-1] = " " elif self.cell[n-2] != self.cell[n-1]: self.cell[n] = self.cell[n-1] self.cell[n-1] = self.cell[n-2] self.cell[n-2] = " " elif self.cell[n] != " ": if (self.cell[n-1] == " ") and (self.cell[n-2]!= " ") and (self.cell[n-2]!= self.cell[n]): self.cell[n-1] = self.cell[n-2] self.cell[n-2] = " " elif (self.cell[n-1] == " ") and (self.cell[n-2]!= " ") and (self.cell[n-2] == self.cell[n]): self.cell[n] = self.cell[n-2] + self.cell[n] self.cell[n-2] = " " elif (self.cell[n-2] == " ") and (self.cell[n-1] == self.cell[n]): self.cell[n] = self.cell[n-1] + self.cell[n] self.cell[n-1] = " " elif (self.cell[n-2] == self.cell[n-1]) and (self.cell[n-1] == self.cell[n]): self.cell[n] = self.cell[n-1] + self.cell[n] self.cell[n-1] = self.cell[n-2] self.cell[n-2] = " " elif (self.cell[n-2] != " ") and (self.cell[n-1]!= " ") and (self.cell[n-2] == self.cell[n-1]) and (self.cell[n-1] != self.cell[n]): self.cell[n-1] = self.cell[n-2] + self.cell[n-1] self.cell[n-2] = " " elif (self.cell[n-2] != " ") and (self.cell[n-1]!= " ") and (self.cell[n] == self.cell[n-1]) and (self.cell[n-1] != self.cell[n-2]): self.cell[n] = self.cell[n] + self.cell[n-1] self.cell[n-1] = self.cell[n-2] self.cell[n-2] = " " def lmove(self,n): if self.cell[n] == " ": if (self.cell[n+1] == " ") and (self.cell[n+2] != " "): self.cell[n] = self.cell[n+2] self.cell[n+2] = " " elif (self.cell[n+2] == " ") and (self.cell[n+1] != " "): self.cell[n] = self.cell[n+1] self.cell[n+1] = " " elif (self.cell[n+2] != " ") and (self.cell[n+1] != " ") and (self.cell[n+2] == self.cell[n+1]): self.cell[n] = self.cell[n+2] + self.cell[n+1] self.cell[n+2] = " " self.cell[n+1] = " " elif self.cell[n+2] != self.cell[n+1]: self.cell[n] = self.cell[n+1] self.cell[n+1] = self.cell[n+2] self.cell[n+2] = " " elif self.cell[n] != " ": if (self.cell[n+1] == " ") and (self.cell[n+2]!= " ") and (self.cell[n+2]!= self.cell[n]): self.cell[n+1] = self.cell[n+2] self.cell[n+2] = " " elif (self.cell[n+1] == " ") and (self.cell[n+2]!= " ") and (self.cell[n+2] == self.cell[n]): self.cell[n] = self.cell[n+2] + self.cell[n] self.cell[n+2] = " " elif (self.cell[n+2] == " ") and (self.cell[n+1] == self.cell[n]): self.cell[n] = self.cell[n+1] + self.cell[n] self.cell[n+1] = " " elif (self.cell[n+2] == self.cell[n+1]) and (self.cell[n+1] == self.cell[n]): self.cell[n] = self.cell[n+1] + self.cell[n] self.cell[n+1] = self.cell[n+2] self.cell[n+2] = " " elif (self.cell[n+2] != " ") and (self.cell[n+1]!= " ") and (self.cell[n] == self.cell[n+1]) and (self.cell[n+1] != self.cell[n+2]): self.cell[n] = self.cell[n] + self.cell[n+1] self.cell[n+1] = self.cell[n+2] self.cell[n+2] = " " elif (self.cell[n+2] != " ") and (self.cell[n+1]!= " ") and (self.cell[n+2] == self.cell[n+1]) and (self.cell[n] != self.cell[n+2]): self.cell[n+1] = self.cell[n+2] + self.cell[n+1] self.cell[n+2] = " " def umove(self,n): if self.cell[n] == " ": if (self.cell[n+3] == " ") and (self.cell[n+6] != " "): self.cell[n] = self.cell[n+6] self.cell[n+6] = " " elif (self.cell[n+6] == " ") and (self.cell[n+3] != " "): self.cell[n] = self.cell[n+3] self.cell[n+3] = " " elif (self.cell[n+6] != " ") and (self.cell[n+3] != " ") and (self.cell[n+6] == self.cell[n+3]): self.cell[n] = self.cell[n+6] + self.cell[n+3] self.cell[n+6] = " " self.cell[n+3] = " " elif self.cell[n+6] != self.cell[n+3]: self.cell[n] = self.cell[n+3] self.cell[n+3] = self.cell[n+6] self.cell[n+6] = " " elif self.cell[n] != " ": if (self.cell[n+3] == " ") and (self.cell[n+6]!= " ") and (self.cell[n+6]!= self.cell[n]): self.cell[n+3] = self.cell[n+6] self.cell[n+6] = " " elif (self.cell[n+3] == " ") and (self.cell[n+6]!= " ") and (self.cell[n+6] == self.cell[n]): self.cell[n] = self.cell[n+6] + self.cell[n] self.cell[n+6] = " " elif (self.cell[n+6] == " ") and (self.cell[n+3] == self.cell[n]): self.cell[n] = self.cell[n+3] + self.cell[n] self.cell[n+3] = " " elif (self.cell[n+6] == self.cell[n+3]) and (self.cell[n+3] == self.cell[n]): self.cell[n] = self.cell[n+3] + self.cell[n] self.cell[n+3] = self.cell[n+6] self.cell[n+6] = " " elif (self.cell[n+6] != " ") and (self.cell[n+3]!= " ") and (self.cell[n+6] == self.cell[n+3]) and (self.cell[n+3] != self.cell[n]): self.cell[n+3] = self.cell[n+6] + self.cell[n+3] self.cell[n+6] = " " elif (self.cell[n+6] != " ") and (self.cell[n+3]!= " ") and (self.cell[n+6] != self.cell[n+3]) and (self.cell[n+3] == self.cell[n]): self.cell[n] = self.cell[n] + self.cell[n+3] self.cell[n+3] = self.cell[n+6] self.cell[n+6] = " " def dmove(self,n): if self.cell[n] == " ": if (self.cell[n-3] == " ") and (self.cell[n-6] != " "): self.cell[n] = self.cell[n-6] self.cell[n-6] = " " elif (self.cell[n-6] == " ") and (self.cell[n-3] != " "): self.cell[n] = self.cell[n-3] self.cell[n-3] = " " elif (self.cell[n-6] != " ") and (self.cell[n-3] != " ") and (self.cell[n-6] == self.cell[n-3]): self.cell[n] = self.cell[n-6] + self.cell[n-3] self.cell[n-6] = " " self.cell[n-3] = " " elif self.cell[n-6] != self.cell[n-3]: self.cell[n] = self.cell[n-3] self.cell[n-3] = self.cell[n-6] self.cell[n-6] = " " elif self.cell[n] != " ": if (self.cell[n-3] == " ") and (self.cell[n-6]!= " ") and (self.cell[n-6]!= self.cell[n]): self.cell[n-3] = self.cell[n-6] self.cell[n-6] = " " elif (self.cell[n-3] == " ") and (self.cell[n-6]!= " ") and (self.cell[n-6] == self.cell[n]): self.cell[n] = self.cell[n-6] + self.cell[n] self.cell[n-6] = " " elif (self.cell[n-6] == " ") and (self.cell[n-3] == self.cell[n]): self.cell[n] = self.cell[n-3] + self.cell[n] self.cell[n-3] = " " elif (self.cell[n-6] == self.cell[n-3]) and (self.cell[n-3] == self.cell[n]): self.cell[n] = self.cell[n-3] + self.cell[n] self.cell[n-3] = self.cell[n-6] self.cell[n-6] = " " elif (self.cell[n-6] != " ") and (self.cell[n-3]!= " ") and (self.cell[n-6] == self.cell[n-3]) and (self.cell[n-3] != self.cell[n]): self.cell[n-3] = self.cell[n-6] + self.cell[n-3] self.cell[n-6] = " " elif (self.cell[n-6] != " ") and (self.cell[n-3]!= " ") and (self.cell[n-6] != self.cell[n-3]) and (self.cell[n-3] == self.cell[n]): self.cell[n] = self.cell[n] + self.cell[n-3] self.cell[n-3] = self.cell[n-6] self.cell[n-6] = " " def right_move(self): gameboard.rmove(3) gameboard.rmove(6) gameboard.rmove(9) def left_move(self): gameboard.lmove(1) gameboard.lmove(4) gameboard.lmove(7) def up_move(self): gameboard.umove(1) gameboard.umove(2) gameboard.umove(3) def down_move(self): gameboard.dmove(7) gameboard.dmove(8) gameboard.dmove(9) def user_choice(self,user_input): if user_input == "u": gameboard.up_move() elif user_input == "d": gameboard.down_move() elif user_input == "l": gameboard.left_move() elif user_input == "r": gameboard.right_move() def win_check(self, num): for i in range(1,10): if self.cell[i] == num: return True def reset(self): self.cell = [" "," "," "," "," "," "," "," "," "," "] gameboard = Board() select_game = int(raw_input("select the game board to play for: 4, 8, 16, 32,64 :- ")) gameboard.initial_board() gameboard.display() while True: user_input = raw_input("select the move u for upward direction, d for downwards, l for left and r for Right: ") gameboard.user_choice(user_input) y = randint(1,9) gameboard.update_cell(y) os.system("clear") print " playing game board for: %s \n"%(select_game) gameboard.display() if gameboard.win_check(select_game): print "You Win!!! \n" play_again = raw_input("Would you like to play again? (Y/N) > ").upper() if play_again == "Y": gameboard.reset() select_game = int(raw_input("select the game board to play for: 4, 8, 16,32,64 :- ")) gameboard.initial_board() gameboard.display() continue else: break
# -*- coding: utf-8 -*- """ This is HW for stable-matching algorithm. """ import random def stable_matching(men, women): """ :param men: list :param women: list :return: list """ assert isinstance(men, list) or isinstance(men, tuple) assert isinstance(women, list) or isinstance(women, tuple) n = len(men) assert n == len(women) matched = [] husband = [0 for _ in range(n)] men_copy = [] for m, item in enumerate(men): men_copy.append([0, item]) unmatched_men = list(range(n)) women_invert = [[0 for i in range(n)] for j in range(n)] for w in range(n): for p, m in enumerate(women[w]): women_invert[w][m-1] = p while len(unmatched_men) > 0: m = unmatched_men.pop(0) idx, m_pref = men_copy[m] assert idx < n w = m_pref[idx]-1 men_copy[m][0] = idx+1 w_husband = husband[w]-1 if w_husband == -1: pass elif women_invert[w][m] < women_invert[w][w_husband]: matched.remove((w_husband+1, w+1)) unmatched_men.append(w_husband) else: unmatched_men.append(m) continue husband[w] = m+1 matched.append((m+1, w+1)) return matched def verify_matching(matched_list, men, women): n = len(matched_list) assert n == len(men) assert n == len(women) husband = [-1 for _ in range(n)] women_invert = [[-1 for i in range(n)] for j in range(n)] for man, woman in matched_list: husband[woman-1] = man-1 for w in range(n): for p, m in enumerate(women[w]): women_invert[w][m-1] = p for m, w in matched_list: m -= 1 w -= 1 for w_candidate in men[m]: w_candidate -= 1 if w_candidate == w: break m_candidate = husband[w_candidate] m_candidate_rank = women_invert[w_candidate][m_candidate] m_rank = women_invert[w_candidate][m] if m_rank < m_candidate_rank: return False return True if __name__ == "__main__": # m = ((3, 2, 1), (3, 2, 1), (3, 2, 1)) # w = ((1, 2, 3), (1, 2, 3), (1, 2, 3)) m = [] w = [] n = int(input()) arr = list(range(1, n + 1)) for i in range(n): random.shuffle(arr) m.append(arr[:]) random.shuffle(arr) w.append(arr[:]) matched = stable_matching(m, w) print(verify_matching(matched, m, w))
class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ index = len(s)//2 for i in range(index): j = len(s)-1-i temp = s[i] s[i] = s[j] s[j] = temp
# Rope # to do: # - insert # - delete # - substring # - concatenation def to_rope(string): return Rope(string) class Rope: def __init__(self, string): self.string = string def __str__(self): return "abc" assert str(to_rope("abc")) == "abc"
Ex1: tuple1 = (10, 20, 30, 40, 50) tuple1 = tuple(reversed(tuple1)) print(tuple1) EX2: tuple1 = ("Orange", [10, 20, 30], (5, 15, 25)) print(tuple1[1][1]) Ex3: tuple1 = (10, 20, 30, 40) a, b, c, d = (10, 20, 30, 40) print(a, b, c, d) Ex4: tuple1 = (11, 22, 33, 44, 55, 66) tuple2 = tuple1[3:-1] print(tuple2) Ex5: tuple1 = (11, [22, 33], 44, 55) tuple1[1][0]=222 print(tuple1) Ex6: tuple1 = (50, 10, 60, 70, 50) print(tuple1.count(50)) ex7: My_tuple = (50,) print(My_tuple)
from collections import deque my_string = 'abracadabra' my_deque = deque(my_string) my_deque.appendleft('5') my_deque.append('5') print(my_deque)
#List #Ex1: list1 = [100, 200, 300, 400, 500] list1.reverse() print('Reversed list:', list1) #Ex2: list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40] list1[2][2].insert(1,'7000') print(list1[2][2]) #Ex3: list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"] list1[2][1][2].extend('hij') print(list1) #Ex4: list1 = [5, 10, 15, 20, 25, 50, 20] print(list1[3]) list1[3] = 200 print(list1)
"""Python Set Exercise""" # Exercise 1: Return a new set of identical items from a given two set set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} print(set1 & set2) # Exercise 2: Returns a new set with all items from both sets by removing duplicates set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} print(set1.union(set2)) # Exercise 3: Given two Python sets, update the first set with items that exist only in the first set and not in the second set set1 = {10, 20, 30} set2 = {20, 40, 50} print(set1.difference(set2)) # Exercise 4: Remove items 10, 20, 30 from the following set at once set1 = {10, 20, 30, 40, 50} print(set1 - {10, 20, 30}) # Exercise 5: Return a set of all elements in either A or B, but not both set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} print(set1 ^ set2)
def isPrimeNumber(num): if num > 1: seq = int(num**0.5) for x in range(2, seq): if (num % x) == 0: print("the number is not prime") return else: primeNumber = "the number is prime" print(primeNumber) else: print("A prime number is a natural number greater than 1") isPrimeNumber(num)
# Exercise 1: Below are the two lists convert it into the dictionary keys = ['Ten', 'Twenty', 'Thirty'] values = [10, 20, 30] # Expected output: {'Ten': 10, 'Twenty': 20, 'Thirty': 30} x = dict(zip(keys, values)) print("Exercise 1, output:", x) # Exercise 2: Create a new dictionary with the following keys from a below dictionary # Given dictionary: sampleDict = { # "name": "Kelly", # "age":25, # "salary": 8000, # "city": "New york" # } # Keys: "name", "salary" # Expected output: {'name': 'Kelly', 'salary': 8000} sampleDict = { "name": "Kelly", "age":25, "salary": 8000, "city": "New york" } x = {"name": sampleDict["name"], "salary": sampleDict["salary"]} print("Exercise 2, output:", x) # Exercise 3*: Access the value of key ‘history’ from the below dict sampleDict = { "class":{ "student":{ "name":"Mike", "marks":{ "physics":70, "history":80 } } } } # Expected output: 80 x = sampleDict["class"]["student"]["marks"]["history"] print("Exercise 3, output:", x) # Exercise 4*: Change Brad’s salary to 8500 from a given Python dictionary sampleDict = { 'emp1': {'name': 'Jhon', 'salary': 7500}, 'emp2': {'name': 'Emma', 'salary': 8000}, 'emp3': {'name': 'Brad', 'salary': 6500} } # Expected output: sampleDict = { # 'emp1': {'name': 'Jhon', 'salary': 7500}, # 'emp2': {'name': 'Emma', 'salary': 8000}, # 'emp3': {'name': 'Brad', 'salary': 8500} # } sampleDict["emp3"]["salary"] = 8500 print("Exercise 4, output:", sampleDict)
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) count_odd = 0 count_even = 0 for x in numbers: if not x % 2: count_even += 1 else: count_odd += 1 print ("Number of even_numbers :", count_even) print ("Number of odd_numbers :", count_odd)
# Exercise 1: Return a new set of identical items from a given two set set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} # Expected output: {40, 50, 30} x = set1.intersection(set2) print("Exercise 1, output:", x) # Exercise 2: Returns a new set with all items from both sets by removing duplicates set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} # Expected output: {70, 40, 10, 50, 20, 60, 30} x = set1.union(set2) print("Exercise 2, output:", x) # Exercise 3: Given two Python sets, update the first set with items that exist only in the first set and not in the second set. set1 = {10, 20, 30} set2 = {20, 40, 50} # Expected output: {10, 30} x = set1.difference(set2) print("Exercise 3, output:", x) # Exercise 4: Remove items 10, 20, 30 from the following set at once set1 = {10, 20, 30, 40, 50} # Expected output: {40, 50} x = set1.symmetric_difference({10, 20, 30}) print("Exercise 4, output:", x) # Exercise 5: Return a set of all elements in either A or B, but not both set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} # Expected output: {20, 70, 10, 60} x = set1.symmetric_difference(set2) print("Exercise 5, output:", x)
import re statement = 'Please contact us at: levon-grigoryan@gmail.com, lgrigor@submarine.com' pattern = re.compile(r'[:,]') address = pattern.split(statement) print(address)
var = 1 while var == 0: num = raw_input("Enter a number :") print "You entered: ", num print "Good bye!\n\n\n" fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print 'Then fruits is :', fruits[index] print "Good bye!\n\n\n" print tuple('abcd');
''' Tara Walton tara1984 Test 1 Calculate a global sum using multiple processes ''' import sys import multiprocessing as mp def readfile(fname): '''Reads a text file; returns a list of integers''' f = open(fname, 'r') contents = f.read() numbers = contents.split() for i in range(len(numbers)): numbers[i] = int(numbers[i]) #total = sum(numbers) #print("Total: ", total) #for check return numbers def subtotal(numbers, q): '''Add the correct arguments to calculate the total of a list of numbers''' sub = sum(numbers) q.put(sub) return sub #return the total def main(num_processes): fname = "randnums.txt" numlist = readfile(fname) #numlist is a list of integers #Your code here to determine which numbers from numlist to send #to each process, start the processes, get the subtotals, calculate #the global sum, and print the global sum que = mp.Queue() #a place to store subtotals length = len(numlist) #how many numbers to sum pCount = mp.cpu_count() #number of processors on the computer in use procs = [] #to accumulate processes for joining perSub = length//pCount #amt of numbers in an even split remNum = length%pCount #remaining numbers after even split x=0 #print(numlist[x:x+perSub]) #slice of list test for i in range(0, num_processes-1): #n processes p = mp.Process(target=subtotal, args=[numlist[x:x+perSub], que]) procs.append(p) x+=perSub px = mp.Process(target=subtotal, args=[numlist[x:x+perSub+remNum], que]) procs.append(px) for p in procs: p.start() for p in procs: p.join() result = [que.get() for p in procs] sumTot = sum(result) print("Grand Total:", sumTot) if __name__ == "__main__": #Your code here # 1. Get number of processes from the command line num = int(sys.argv[1]) # 2. Call main() with the number of processes as an argument main(num) print("Program Complete")
#!/usr/bin/env python3 """ Collects the sensor configuration file to be parsed and reads it into a list """ import sys import os config_path = "./config/" def get_command_line_config_file(): """Collects configuration file to be use by command line argument, prompting the user or by using the default test file. Returns config file to be opened. """ try: configfile = sys.argv[1] except IndexError: print("You need to enter a config file name") return False return configfile def open_file(file): """Opens a config file to be read in. Returns a file handle or False Args: file: """ o_file = False file = "config/" + file try: o_file = open(file, 'r') except FileNotFoundError: print("Sorry I could not find the config file: \"%s\"" % file) except OSError: print("Did not understand '%s'. Try again."% (file)) return o_file def file_to_list(file_handle): """Takes a opened file handle and converts the content into a list then closes the file Args: file_handle: """ file_list = [] for line in file_handle: line = line.strip() file_list.append(line) file_handle.close() return file_list def prompt_for_config_file(): """ Request the DAQ configuration file from user :return: """ # TODO add some input validation here # Only allow files from the local config directory # only alpha numeric, dash, underscore, period - "my-config_file.txt" return input("Enter the configuration file: ") def get_config_file(config_path): """Collects the configuration file from a user prompt or from the command line. Then returns an opened file handle. """ opened_config_file = False file = get_command_line_config_file() # Fetch from the command line if possible # Loop over until we open a configuration file while not file: file_list_msg = "| Available configuration files in " + config_path + " |" msg_divider = "" for i in range(0, len(file_list_msg)): msg_divider = msg_divider + "-" print(msg_divider) print(file_list_msg) print(msg_divider) config_file_list = list_config_dir(config_path) for a_config_file in config_file_list: print(" - %s"%(a_config_file)) print(msg_divider) file = prompt_for_config_file() # Check if it can be opened and open it if you can opened_config_file = open_file(file) if not opened_config_file: file = False return opened_config_file def close_config_file(file): """Close the config file if it is still open """ if file.closed: return True elif file.opened: print("file still opened closing file") file.close() return True else: print("Can't close file?") return False def list_config_dir(config_path): """List the contents of the config directory """ config_files = os.listdir(config_path) #for file in config_files: # print(file) return config_files def main(): print("This script should be run from the start file.") print("As a test it can be ran alone and will return the contents of any file provided.") opened_config_file = get_config_file(config_path) # File contents to list so we can close the file now file_list = file_to_list(opened_config_file) close_config_file(opened_config_file) # list the contents of the file with line count count = 0 for i in file_list: count = count + 1 print(count, i) if __name__ == "__main__": main()
# Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). # Example 1: # Input: [1,3,5,4,7] # Output: 3 # Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. # Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. # Example 2: # Input: [2,2,2,2,2] # Output: 1 # Explanation: The longest continuous increasing subsequence is [2], its length is 1. # Note: Length of the array will not exceed 10,000. class Solution: def findLengthOfLCIS(self, nums): """ :type nums: List[int] :rtype: int """ #Edge Cases if not nums: return 0 if len(nums) == 1: return 1 if len(nums) == 2: if nums[-1] > nums[0]: return 2 else: return 1 dp = [0] * len(nums) dp[0] = 1 for i in range(1, len(nums)): if nums[i] > nums[i-1]: dp[i] = dp[i-1] + 1 else: dp[i] = 1 return max(dp)
# -*- coding: utf-8 -*- import numpy as np from .datatuple import DataTuple __all__ = [ 'floatX', 'split_dataframe_to_arrays', 'split_numpy_array', 'slice_length', 'merge_slices', 'merge_slice_indices', 'merge_slice_masks', 'minibatch_indices_iterator', 'adaptive_density', ] def floatX(array): """Enforce the value type of ``array`` to default float type. Parameters ---------- array : numpy.ndarray Numpy array, whose value type should be enforced to default float type. If a number is specified, it will be converted to 0-dimensional numpy array. Returns ------- numpy.ndarray The converted numpy array. """ from madoka import config return np.asarray(array, dtype=config.floatX) def split_dataframe_to_arrays(df, label_as_int=False): """Split data frame to numpy arrays, with ``label`` column splitted. Parameters ---------- df : pandas.DataFrame Original data frame, which is expected to contain ``label`` column. label_as_int : bool If set to True, will discretize the labels into int32, according to condition ``labels >= 0.5``. Returns ------- DataTuple The splitted numpy arrays, where the first represents features without labels, and the second represents the labels. If the returned features only contain one column, it will be flatten. """ features = df.drop('label', axis=1, inplace=False) labels = df['label'] if label_as_int: labels = np.asarray(labels >= 0.5, dtype=np.int32) else: labels = labels.values features = features.values if features.shape[1] == 1: features = features.flatten() return DataTuple(features, labels) def split_numpy_array(array_or_arrays, right_portion=None, right_size=None, shuffle=True): """Split numpy arrays into two halves, by portion or by size. Parameters ---------- array_or_arrays : numpy.ndarray | tuple[numpy.ndarray] | DataTuple Numpy array, a tuple of numpy arrays, or a ``DataTuple`` instance. right_portion : float Portion of the right half. Ignored if ``right_size`` is specified. right_size : int Size of the right half. shuffle : bool Whether or not to shuffle before split? Returns ------- (numpy.ndarray, numpy.ndarray) | (DataTuple, DataTuple) Splitted training and validation data. If the given data is a single array, returns the splitted data in a tuple of single arrays. Otherwise a tuple of ``DataTuple`` instances. """ if isinstance(array_or_arrays, np.ndarray): direct_value = True data_count = len(array_or_arrays) elif isinstance(array_or_arrays, (tuple, list, DataTuple)): direct_value = False data_count = len(array_or_arrays[0]) else: raise TypeError( '%r is neither a numpy array, nor a tuple of arrays.' % array_or_arrays ) if right_size is None: if right_portion is None: raise ValueError('At least one of "right_portion", "right_size" ' 'should be specified.') if right_portion < 0.5: right_size = data_count - int(data_count * (1.0 - right_portion)) else: right_size = int(data_count * right_portion) if right_size < 0: right_size = 0 if right_size > data_count: right_size = data_count if shuffle: indices = np.arange(data_count) np.random.shuffle(indices) get_train = lambda v: v[indices[: -right_size]] get_valid = lambda v: v[indices[-right_size:]] else: get_train = lambda v: v[: -right_size, ...] get_valid = lambda v: v[-right_size:, ...] if direct_value: return (get_train(array_or_arrays), get_valid(array_or_arrays)) else: return (DataTuple(*(get_train(v) for v in array_or_arrays)), DataTuple(*(get_valid(v) for v in array_or_arrays))) def _slice_length_sub(start, stop, step): if step > 0: ret = (stop - start + step - 1) // step elif step < 0: ret = (start - stop - step - 1) // (-step) else: raise ValueError('Step of slice cannot be 0.') if ret < 0: ret = 0 return ret def slice_length(length, slice_): """Compute the length of slice.""" start, stop, step = slice_.indices(length) return _slice_length_sub(start, stop, step) def merge_slices(length, *slices): """Merge multiple slices into one. When we slice some object with the merged slice, it should produce exactly the same output as if we slice the object with original slices, one after another. That is to say, if we have: merged_slice = merge_slices(len(array), slice1, slice2, ..., sliceN) Then these two arrays should be the same: array1 = array[slice1][slice2]...[sliceN] array2 = array[merged_slice] Parameters ---------- length : int Length of the array that will be sliced. *slices : tuple[slice] Sequence of slices to be merged. Returns ------- slice """ if isinstance(length, slice): raise TypeError('`length` is not specified.') # deal with degenerated situations. if not slices: return slice(0, None, None) if len(slices) == 1: return slices[0] # merge slices def merge_two(slice1, slice2): start1, stop1, step1 = slice1.indices(length) # compute the actual length of slice1 length1 = _slice_length_sub(start1, stop1, step1) # if the length becomes zero after applying slice1, we can stop here # by returning an empty slice if length1 <= 0: return None # now, apply slice2 on the slice1 start2, stop2, step2 = slice2.indices(length1) length2 = _slice_length_sub(start2, stop2, step2) if length2 <= 0: return None # shift slice2 by slice1 step = step1 * step2 start = start1 + start2 * step1 assert(0 <= start <= length - 1) stop = start1 + stop2 * step1 assert ((stop - start) * step >= 0) if step < 0: # special fix: here stop <= -1 indicates to include all data # before start if stop <= -1: stop = None else: # special fix: here stop >= n indicates to include all data # after start if stop >= length: stop = None return slice(start, stop, step) ret = slices[0] for s in slices[1:]: ret = merge_two(ret, s) if ret is None: return slice(0, 0, None) return ret def merge_slice_indices(length, slice_, indices): """Merge a slice and integral indices. This method merges a slice and integral indices, so that if we have: merged = merge_slice_indices(len(array), slice_, indices) Then the following two arrays should be same: array1 = array[slice_][indices] array2 = array[merged] Parameters ---------- length : int Length of the array that will be indexed. slice_ : slice Slice of the array. indices : np.ndarray Indices on the slice of the array. Returns ------- np.ndarray """ if not isinstance(indices, np.ndarray): indices = np.asarray(indices, dtype=np.int) # inspect the slice to get start, stop and step start, stop, step = slice_.indices(length) assert(0 <= start <= length-1) assert(-1 <= stop <= length) slen = _slice_length_sub(start, stop, step) # merge the slice and the indices indices_is_neg = indices < 0 if np.any(indices_is_neg): indices = indices + indices_is_neg * slen return start + indices * step def merge_slice_masks(length, slice_, masks): """Merge a slice and boolean masks. This method merges a slice and boolean masks, so that if we have: merged = merge_slice_masks(len(array), slice_, masks) Then the following two arrays should be same: array1 = array[slice_][masks] array2 = array[merged] Parameters ---------- length : int Length of the array that will be indexed. slice_ : slice Slice of the array. masks : np.ndarray Masks on the slice of the array. Returns ------- np.ndarray[int] Indices of the chosen elements. """ if len(masks) != slice_length(length, slice_): raise TypeError('Length of masks != slice: %r != %r.' % (len(masks), slice_)) if not isinstance(masks, np.ndarray): masks = np.asarray(masks, dtype=np.bool) return merge_slice_indices(length, slice_, np.where(masks)[0]) def minibatch_indices_iterator(length, batch_size, ignore_incomplete_batch=False): """Iterate through all the mini-batch indices. Parameters ---------- length : int Total length of data in an epoch. batch_size : int Size of each mini-batch. ignore_incomplete_batch : bool Whether or not to ignore the final batch if it contains less than ``batch-size`` number of items? Yields ------ np.ndarray Indices of each mini-batch. The last mini-batch may contain less indices than `batch_size`. """ start = 0 stop1 = (length // batch_size) * batch_size while start < stop1: yield np.arange(start=start, stop=start + batch_size, dtype=np.int) start += batch_size if not ignore_incomplete_batch and start < length: yield np.arange(start=start, stop=length, dtype=np.int) def adaptive_density(values, bins=1000, pscale=10, plimit=.05): """Compute the density histogram of given values, with adaptive range. It is often the case where outliers which consists only a small portion of the data, but expanding the range of data vastly. This function computes the density histogram with adaptive range, so that these outliers can be discarded. Parameters ---------- values : np.ndarray Values whose density should be computed. bins : int Number of bins of the density. pscale : float Scaling factor to consider the shrink of density percentile having significant effect on shrinking the range of data. For example, if `pscale == 10`, then if we can shrink the range of data by 10% with only stripping the densities of top 0.5% and bottom 0.5%, then we could regard it a significant shrinkage. plimit : float At most this percentile of densities can be shrinked. This limit should apply to the sum of top and bottom percentile. Returns ------- (np.ndarray, np.ndarray, float, float) Density values in each bin, the edges of these bins, as well as the stripped densities at the left and the right. The length of edges will be one more than the length of density values. """ hist, edges = np.histogram(values, bins=bins, density=True) pwidth = edges[1] - edges[0] left = 0 right = len(hist) pleft = 0.0 pright = 0.0 candidate = None while pleft + pright <= plimit and left < right: if pright <= pleft: right -= 1 pright += hist[right] * pwidth else: pleft += hist[left] * pwidth left += 1 p_data = float(left + len(hist) - right) / len(hist) if pleft + pright <= plimit and p_data <= (pleft + pright) * pscale: candidate = (left, right) if candidate: left, right = candidate left_stripped = np.sum(hist[:left]) * pwidth right_stripped = np.sum(hist[right:]) * pwidth hist_sum = np.sum(hist) hscale = (hist_sum - (left_stripped + right_stripped)) / hist_sum vmin = edges[left] vmax = edges[right] vstripped = values[(values >= vmin) & (values <= vmax)] hist, edges = np.histogram(vstripped, bins=bins, density=True) hist *= hscale else: left_stripped = 0.0 right_stripped = 0.0 return hist, edges, left_stripped, right_stripped
""" This file contains helper methods """ def validate_email(email): if '@' in email and '.com' in email: return True raise ValueError("Invalid email address -- " + email) def input_prompt(): """ renders display for receiving user input """ return input(">>> ") def user_response_controller(bank_request, user_response): """ processes user's response for bank's request sent : bank_request --> what is user currently requesting for : user_response --> what a user wants to actually do amongst the options in the above bank_requests """ user_response = validate_user_input_to_int(user_response) if user_response == "error": return ['resend_same_bank_request', 'No valid option choosen'] if user_response >= 1 and user_response <= bank_request.get('available_options'): return user_response else: return ['resend_same_bank_request', 'Selected option not found'] def validate_user_input_to_int(user_input): """ validates user input against type integer & automatically converts and returns the value : user_input --> value entered by user """ try: return int(user_input) except Exception: return "error" def reason_for_resend(why): print("ERROR ERROR".center(60, " ")) print(why.center(61, " ")) print( "Do ensure, you're inserting the right options as needed\n\n".center(30, " "))
from Libreria_Num_Complejos import * #verificar la longitud de un vestor def lenght(vector, vetor1): if len(vector) == len(vetor1): return True else: return False #suma de vectores def sumVector(vector, vector1): """funcion que suma vectores (list, list)-> list""" if lenght(vector, vector1) == True: vectoR = [] for dimension in range(len(vector)): vectoR = vectoR + [complexsum(vector[dimension], vector1[dimension])] return vectoR #inversa de un vector def inverseVector(vector): """funcion que saca el inverso de un vector (list, list)-> list""" vectoR = [] for dimension in range(len(vector)): vectoR = vectoR + [inverse(vector[dimension])] return vectoR #escalar por un vector def escVector(a, vector): """ determina el el producto esclar de un vector""" esTupla = isinstance(vector[0], tuple) if esTupla == True: for dimension in range(len(vector)): vector[dimension] = complexproduc(vector[dimension], a) else: for dimension in range(len(vector)): for j in range(len(vector[0])): vector[dimension][j] = complexproduc(vector[dimension][j], a) return vector #suma de dos matrices def sumMatrix(mat, mat1): """"funcion que suma matrices (list2d, list2d)->list2d""" if lenght(mat, mat1) and lenght(mat[0], mat1[0]) == True: for row in range(len(mat)): mat1[row] = sumVector(mat[row], mat1[row]) return mat1 return "dimensiones diferentes" #inversa de una matriz def inverseMatrix(mat): """funcion que saca la inversa de una matriz (list2d)->list2d""" for row in range(len(mat)): for column in range(len(mat[0])): mat[row][column] = inverse(mat[row][column]) return mat #multiplicacion escalar matriz def escMatrix(a, mat): """funcion que determina el producto escalar por una matriz (list, int)->list2d""" for row in range(len(mat)): mat[row] = escVector(a, mat[row]) return mat #matriz transpuesta def transMatriz(mat): """funncion que calcula la transpuesta (list2d)->list2d""" m = len(mat) n = len(mat[0]) trans = [[0 for j in range(m)] for i in range(n)] for row in range(m): for column in range(n): trans[column][row] = mat[row][column] return trans #conjugada de una matriz def conjugateMatriz(mat): """funcion que calcula la conjugada de una matriz (list2d)->list2d""" if isinstance(mat[0], tuple) == True: mat = cambio_vector_horizontal(mat) conju = [[0 for j in range(len(mat[0]))] for i in range(len(mat))] for row in range(len(mat)): for column in range(len(mat[0])): conju[row][column] = conjugado(mat[row][column]) return conju #adjunta de una matriz def adjuntaMatVec(mat): """matriz que determina la adjunta de una matriz o vector (list2d)->list2d""" mat1 = conjugateMatriz(mat) mat1 = transMatriz(mat1) return mat1 # producto matrizes def producMatrizes(mat, mat1): """funcion que hace la multiplicacion entre matrices (list2d,list2d)->list2d""" if len(mat[0]) == len(mat1): matR = [[(0,0) for j in range(len(mat1[0]))]for i in range(len(mat))] for row in range(len(mat)): for column in range(len(mat1[0])): for i in range(len(mat[0])): matR[row][column] = complexsum(matR[row][column], complexproduc(mat[row][i], mat1[i][column])) return matR else: return "las matricces no se pueden multiplicar por sus dimensiones" # cambia la horientacion del vector def cambio_vector_horizontal(vector): """funcion que cambia el sentido del vetor (list)->list""" vector1 = [[(0,0) for j in range(1)] for i in range(len(vector))] for i in range(len(vector)): vector1[i][0] =tuple(vector[i]) return vector1 # ACCION DE UNA MATRIZ SOBRE VECTOR def accion_Mat_Vector(mat, vector): """funcion que hace la accion de una matriz sobre un vector (list2d,list)->list2d""" if isinstance(vector[0], tuple) == True: vector = cambio_vector_horizontal(vector) matR = producMatrizes(mat, vector) return matR #PRODUCTO INTERNO DOS VECTORES def productopunto(vector, vector1): """funcion que determina el producto punto entre vectores (list,list)->int""" total = (0, 0) if isinstance(vector[0], tuple) and isinstance(vector1[0], tuple) == True: vector = cambio_vector_horizontal(vector) vector1 = cambio_vector_horizontal(vector1) elif isinstance(vector[0], tuple)==True: vector = cambio_vector_horizontal(vector) elif isinstance(vector1[0], tuple) == True: vector1 = cambio_vector_horizontal(vector1) for i in range(len(vector)): for j in range(len(vector1[0])): total = complexsum(total, complexproduc(vector1[i][j], vector[i][j])) return total #NORMA DE UN VECTOR def complexVectorNorma(vector): """determina la norma de un vector (list)-> int""" suma = 0 if isinstance(vector[0], tuple) == True: vector = cambio_vector_horizontal(vector) for i in range(len(vector)): for j in range(len(vector[0])): suma = suma + round(modulo(vector[i][j])**2, 3) suma = (round(math.sqrt(suma), 3)) return suma #Distancia entre dos vectores def distanciaVectores(vector, vector1): """determina la distancia entre dos vectore (list)->int""" if isinstance(vector[0], tuple) and isinstance(vector1[0], tuple) == True: vector = cambio_vector_horizontal(vector) vector1 = cambio_vector_horizontal(vector1) for fila in range(len(vector)): for columna in range(len(vector[0])): vector[fila][columna] = complexresta(vector[fila][columna], vector1[fila][columna]) distancia = complexVectorNorma(vector) return distancia # Revisar matriz Unitaria def unitaria(mat): """revisa si un matris es unitaria (list2d)-> boolean""" mat1 = adjuntaMatVec(mat) Munitaria = [[(0, 0) for j in range(len(mat[0]))] for i in range(len(mat))] for i in range(len(mat)): for j in range(len(mat[0])): if i == j: Munitaria[i][j] = (1, 0) mat2 = producMatrizes(mat, mat1) mat2= escMatrix((1/mat2[0][0][0]), mat2) if mat2 == Munitaria: return True else: return False # Revisar matriz Hermitania def esHermitania(mat): """determina si una matriz es hermitania (list2d)-> boolean""" mat1 = adjuntaMatVec(mat) if mat1 == mat: return True else: return False # producto tensor def tensorProduct(mat, mat1): """determina el prodcuto tensor entre dos marices (list2d,list2d)-> boolean""" mat2 = [[(0, 0) for j in range(len(mat[0]))] for i in range(len(mat))] for i in range(len(mat)): for j in range(len(mat1)): a = mat[i][j] mat2[i][j] = escMatrix(a, mat1) return mat2
#Implementation of Two Player Tic-Tac-Toe game in Python. ''' We will make the board using dictionary in which keys will be the location(i.e : top-left,mid-right,etc.) and initialliy it's values will be empty space and then after every move we will change the value according to player's choice of move. ''' theBoard = {'7': ' ' , '8': ' ' , '9': ' ' , '4': ' ' , '5': ' ' , '6': ' ' , '1': ' ' , '2': ' ' , '3': ' ' } instructionBoard = {'7': '7' , '8': '8' , '9': '9' , '4': '4' , '5': '5' , '6': '6' , '1': '1' , '2': '2' , '3': '3' } board_keys = [] boardtype = int for key in theBoard: board_keys.append(key) ''' We will have to print the updated board after every move in the game and thus we will make a function in which we'll define the printBoardType1 function so that we can easily print the board everytime by calling this function. ''' def printBoardType1(board): print(' '+board['7'] + ' | ' + board['8'] + ' | ' + board['9']+' ') print('---+---+---') print(' '+board['4'] + ' | ' + board['5'] + ' | ' + board['6']+' ') print('---+---+---') print(' '+board['1'] + ' | ' + board['2'] + ' | ' + board['3']+' ') def printBoardType2(board): print(' '+board['1'] + ' | ' + board['2'] + ' | ' + board['3']+' ') print('---+---+---') print(' '+board['4'] + ' | ' + board['5'] + ' | ' + board['6']+' ') print('---+---+---') print(' '+board['7'] + ' | ' + board['8'] + ' | ' + board['9']+' ') def printWinner(turn): global boardtype globals()['printBoardType'+str(boardtype)](theBoard) print("\nGAME OVER\n") print(" !!! " +turn+ " WON !!! ") print() def gameStart(): global boardtype choice = input("Top-Down [Default: 1] or Bottom-Top [2]? ") print() if choice == str(1) or 'top-down' in choice.lower(): boardtype = 1 elif choice == str(2) or 'bottom-top' in choice.lower(): boardtype = 2 else: boardtype = 1 print("For each turn, the player, X or O, is to choose a position between 1 and 9, and if it is filled, they are to choose a new location, if all locations are filled up, and no one has won, it is a DRAW. If counters are 3 in a row, forming a straight line, the respective player for the counters, X or O, will WIN the game") print() globals()['printBoardType'+str(boardtype)](instructionBoard) # Now we'll write the main function which has all the gameplay functionality. def game(): global boardtype turn = 'X' count = 0 for i in range(10): print() globals()['printBoardType'+str(boardtype)](theBoard) print() print() move = input("It's your turn, " +turn+". Which position would you like to move to? ") if move: if (type(move) != str): print('Invalid Input') continue elif move.isnumeric(): if (int(move) not in [1, 2, 3, 4, 5, 6, 7, 8, 9]): print('Invalid Input') continue elif theBoard[move] == ' ': theBoard[move] = turn count += 1 else: print("That place is already filled.\nWhich position would you like to move to? ") continue else: print('Invalid Input') # Now we will check if player X or O has won,for every move after 5 moves. if count >= 5: if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ': # across the top printWinner(turn) break elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ': # across the middle printWinner(turn) break elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ': # across the bottom printWinner(turn) break elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ': # down the left side printWinner(turn) break elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ': # down the middle printWinner(turn) break elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ': # down the right side printWinner(turn) break elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ': # diagonal printWinner(turn) break elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ': # diagonal printWinner(turn) break # If neither X nor O wins and the board is full, we'll declare the result as 'tie'. if count == 9: print("\nGAME OVER\n") print("It's a TIE") # Now we have to change the player after every move. if turn == 'X': turn = 'O' else: turn = 'X' else: print('Invalid Input') # Now we will ask if player wants to restart the game or not. restart = input("Do want to Play Again [Y/N]?") if "y" in restart.lower(): for key in board_keys: theBoard[key] = " " gameStart() game() if __name__ == "__main__": gameStart() game()
# This file represents a very simple implementation of an sklearn Linear Regression in Python. # This is from Dataquest's "Linear Regression for Machine Learning" course. # Very simple, but powerful for certain types of problems. # Dropping NA values and one of the features (feature with very low variance in the dataset) clean_test = test[final_corr_cols.index].dropna() features = features.drop('Open Porch SF') # Creating Linear Regression model and training on training data lr = LinearRegression() lr.fit(train[features], train['SalePrice']) # Making predictions on train and test set based on the model train_predictions = lr.predict(train[features]) test_predictions = lr.predict(clean_test[features]) # Calculating the mean squared error on train and test set train_mse = mean_squared_error(train_predictions, train['SalePrice']) test_mse = mean_squared_error(test_predictions, clean_test['SalePrice']) # Calculating root mean squared error (RMSE) based on the above # RMSE used due to being in same units as the target column train_rmse_2 = np.sqrt(train_mse) test_rmse_2 = np.sqrt(test_mse) # Printing our root mean squared error print(train_rmse_2) print(test_rmse_2)
# -------------------------------- Task --------------------------------------------------- # Given a Book class and a Solution class, write a MyBook class that does the following: # Inherits from Book # Has a parameterized constructor taking these 3 parameters: # *string title # *string author # *int price # Implements the Book class' abstract display() method so it prints these 3 lines: # 1. Title:, a space, and then the current instance's title. # 2. Author, a space, and then the current instance's author. # 3. Price, a space, and then the current instance's price. # # Note: Because these classes are being written in the same file, you must not use an access modifier # (e.g.: ) when declaring MyBook or your code will not execute. #----------------------------------------------------------------------------------------------------- #----------------------- HackerRank creates Book ABC (Abstract Base Class) --------------------------- class Book(object, metaclass=ABCMeta): def __init__(self,title,author): self.title=title self.author=author @abstractmethod def display(): pass #------------------------------------------------------------------------------------------------------ #-------------------------------------- SOLUTION ------------------------------------------------------ #Write MyBook class class MyBook(Book): # Initializing subclass def __init__(self,title,author,price): # Inheriting title and author definitions from Book class super().__init__(title,author) # Defining price self.price = price # Creating display method for the MyBook subclass def display(self): # Printing desired output print("Title:" , self.title) print("Author:" , self.author) print("Price:" , self.price) # ------------------------------------ END SOLUTION --------------------------------------------------- # ------------------------- HackerRank Input and MyBook instantiation --------------------------------- title=input() author=input() price=int(input()) new_novel=MyBook(title,author,price) new_novel.display() # -----------------------------------------------------------------------------------------------------
from game_square import GameSquare from random import randint class GameBoard(object): def __init__(self, rows: int, columns: int, number_of_values: int): self.board = [] for i in range(rows): self.board.append([]) for j in range(columns): self.board[i].append(GameSquare(randint(0, number_of_values - 1), i, j)) def get_right_neighbours(self, square: GameSquare) -> list: row = square.row column = square.column neighbours = [] if row < len(self.board) - 1: neighbours.append(self.board[row + 1][column]) if column < len(self.board[0]) - 1: neighbours.append(self.board[row + 1][column + 1]) if column < len(self.board[0]) - 1: neighbours.append(self.board[row][column + 1]) return neighbours def get_square(self, row, column) -> GameSquare: if row < len(self.board) and column < len(self.board[0]): return self.board[row][column] return None def is_all_board_with_same_value(self) -> bool: value = self.get_square(0, 0).value for i in range(len(self.board)): for j in range(len(self.board[0])): if self.board[i][j].value != value: return False return True
x = '' if type(x) == int: if x >= 100: print "That's big number!" if x < 100: print "That's small number!" if type(x) == str: if len(x) >= 50: print "Long sentence" if len(x) < 50: print "Short sentence" if type(x) == list: if len(x) >= 10: print "Big list" if len(x) < 10: print "Short list"
import numpy as np def kmeans(x, k): ''' KMEANS K-Means clustering algorithm Input: x - data point features, n-by-p maxtirx. k - the number of clusters OUTPUT: idx - cluster label ctrs - cluster centers, K-by-p matrix. iter_ctrs - cluster centers of each iteration, (iter, k, p) 3D matrix. ''' # YOUR CODE HERE N, P = x.shape # begin answer random_permutation = np.random.permutation(N) center_indices = random_permutation[0:k] x_origin = x x = np.reshape(x, [N, 1, P]) flag = True iter_ctrs = [] centers = x_origin[center_indices] cur = k for i in range(k): while centers[i] in centers[:i]: centers[i] = x_origin[cur] cur += 1 iter_ctrs.append(centers) while(flag): # [N, k, P] x_diff = x - centers # (N, k) x_dist = np.sum((x_diff*x_diff), axis=2) # Assign the cluster for each point indices = np.argmin(x_dist, axis=1) new_centers = np.zeros((k, P)) flag = False for cur_k in range(k): new_centers[cur_k] = np.mean( x_origin[indices == cur_k, :], axis=0 ) if (new_centers[cur_k] == centers[cur_k]).min() == 0: flag = True #print(centers) centers = new_centers iter_ctrs.append(new_centers) ctrs = centers idx = indices iter_ctrs = np.array(iter_ctrs) # end answer return idx, ctrs, iter_ctrs
# # @lc app=leetcode.cn id=437 lang=python3 # # [437] 路径总和 III # # @lc code=start # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def pathSum(self, root: TreeNode, sum: int) -> int: if not root: return 0 def dfs(node: TreeNode, prev_sum: int): if not node: return 0 return int(node.val == prev_sum) + dfs(node.left, prev_sum - node.val) + dfs(node.right, prev_sum - node.val) return dfs(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum) # @lc code=end
def count_stair_ways(n): if n == 1: return 1 elif n == 2: return 2 else: return count_stair_ways(n-1) + count_stair_ways(n-2) def count_k(n, k): if n == 0: return 1 else: if n >= k: return add_k(count_k, n, k) else: return count_k(n, k-1) def add_k(f, n, k): i = 1 a = 0 while i <= k: a += f(n-i, k) i += 1 return a
def is_sorted(n): """ >>> is_sorted(2) True >>> is_sorted(22222) True >>> is_sorted(9876543210) True >>> is_sorted(9087654321) False """ if n // 10 == 0: return True else: if n % 10 <= (n//10) % 10: return is_sorted(n // 10) else: return False def mario_number(level): """ Return the number of ways that Mario can traverse the level, where Mario can either hop by one digit or two digits each turn. A level is defined as being an integer with digits where a 1 is something Mario can step on and 0 is something Mario cannot step on. >>> mario_number(10101) 1 >>> mario_number(11101) 2 >>> mario_number(100101) 0 """ if level == 1: return 1 elif level // 100 % 10 == 0: return (level // 10 % 10) * mario_number(level // 10) else: return (level // 10 % 10) * mario_number(level // 10) + mario_number(level // 100) def make_change(n): """Write a function, make_change that takes in an integer amount, n, and returns the minimum number of coins we can use to make change for that n, using 1-cent, 3-cent, and 4-cent coins. Look at the doctests for more examples. >>> make_change(5) 2 >>> make_change(6) # tricky! Not 4 + 1 + 1 but 3 + 3 2 """ if n == 0: return 0 elif n != 6 and n >=4: return make_change(n - 4) + 1 elif n >= 3: return make_change(n - 3) + 1 else: return make_change(n - 1) + 1 def elephant(name, age, can_fly): """ >>> chris = elephant("Chris Martin", 38, False) >>> elephant_name(chris) "Chris Martin" >>> elephant_age(chris) 38 >>> elephant_can_fly(chris) False """ def select(command): if command == 'name': return name elif command == 'age': return age else: return can_fly return select def elephant_name(e): return e("name") def elephant_age(e): return e("age") def elephant_can_fly(e): return e("can_fly")
a=list(map(int,input().split())) x=a[0] y=a[1] x=x^y y=x^y x=x^y print(x, end=' ') print(y)
num=int(input()) b=1 if num==0: print('1') else: for i in range(1,num+1): b=b*i print(b)
def binary_search(list,target): first = 0 last = len(list)-1 while first <= last: midpoint = (first + last)//2 if list[midpoint] == target: return midpoint elif list[midpoint] < target: first = midpoint + 1 else: last = midpoint - 1 return None def verify(index): if index is not None: print(index) else: print("target not found") numbers = [1,2,3,4,5,6,7,8,9,10] result = binary_search(numbers,21) verify(result) result = binary_search(numbers,6) verify(result)
s=input("Enter word:") vowels="AEIOUaeiou" count=0 for x in s: if x in vowels: count +=1 print("Vowels:",count)
def sumofmulti(limit): for i in range(1,limit+1): if (i % 3 == 0 or i % 5 == 0): print(i,end=" ") limit = int(input("Enter a number: ")) print("The multiples of 3 and 5 of",limit,"is ") sumofmulti(limit)
num_1 = float(input("Enter a number: ")) if num_1 % 2 == 0: print("The number is even") else: print("The number is odd") """ The Answer of Q.2 is 1 3 4 8 9 10 11 The Answer of Q.3 is 1 4 The Answer of Q.4 is 0 1 3 4 5 6 """
A=[23,54,22,98,45,65,37,31,82,64] even=0 odd=0 for x in A: if x%2==0: even +=1 else: odd +=1 print("There are:",even,"even numbers") print("There are:",odd,"odd numbers")
import numpy as np def L2(v, *args): """Returns the computed L2 norm of a vector v. INPUTS ======= v: list, vector in form of list of numbers *args: optional, list vector of weights & must be same length at v RETURNS ======== L2: float L2 norm of a vector v EXAMPLES ========= >>> L2([3,4]) 5.0 """ s = 0.0 # Initialize sum if len(args) == 0: # No weight vector for vi in v: s += vi * vi else: # Weight vector present w = args[0] # Get the weight vector if (len(w) != len(v)): # Check lengths of lists raise ValueError("Length of list of weights must match length of target list.") for i, vi in enumerate(v): s += w[i] * w[i] * vi * vi return np.sqrt(s) def test_L2(): assert L2([3,4]) == 5.0 test_L2() def test_L2_types(): try: L2([3,4],[3,3,3]) except ValueError as err: assert(type(err) == ValueError) test_L2_types() def test_L2_weighted(): assert L2([3,4],[1,1]) == 5.0 test_L2_weighted()
# A 3-dimensional vector class to be used in the development of # computer simulations of various physical systems. # # # The 3-dimensional vector represents a standard cartesian vector # given by <b> xi + yj +zk</b> where <b>i</b>, <b>j</b>, and <b>k</b> are unit # vectors in the x, y, and z direction respectively. # # This code is developed from the original java script from Iain A. Bertram # @author Joseph Cairns # @version 1.0 import numpy as np class PhysicsVector: def __init__(self, x, y, z): self.x = x self.y = y self.z = z # Method to return a string of the vector in the xi + yj + zk format def return_string(self): return str(self.x)+'i + '+str(self.y)+'j + '+str(self.z)+'k' # Method to return a simple string of the vector in the form x y z separated by spaces def return_simple_string(self): return str(self.x)+' '+str(self.y)+' '+str(self.z) # Method to return the vector as a list in the form [x,y,z] def return_list(self): return [self.x,self.y,self.z] # Method that prints the string in the xi + yj + zk format def print_vector(self): print(str(self.x)+'i + '+str(self.y)+'j + '+str(self.z)+'k') # Method that sets the x component of the vector to a particular value def set_x(self, x): self.x = x # Method that sets the y component of the vector to a particular value def set_y(self, y): self.y = y # Method that sets the z component of the vector to a particular value def set_z(self, z): self.z = z # Method that returns the x component of the vector def get_x(self): return self.x # Method that returns the y component of the vector def get_y(self): return self.y # Method that returns the z component of the vector def get_z(self): return self.z # Method that sets the x, y and z components of the vector to particular values def set_vector(self, x, y, z): self.x = x self.y = y self.z = z # Method that increases the desired vector by another vector def increase_by(self, vector): self.x = self.x + vector.x self.y = self.y + vector.y self.z = self.z + vector.z # Method that decreases the desired vector by another vector def decrease_by(self, vector): self.x = self.x - vector.x self.y = self.y - vector.y self.z = self.z - vector.z # Method that scales the vector by a scalar def scale_by(self, scalar): self.x = self.x * scalar self.y = self.y * scalar self.z = self.z * scalar # Method that scales a given vector by a scalar def scale(u, scalar): x = u.x * scalar y = u.y * scalar z = u.z * scalar return PhysicsVector(x, y, z) # Method that calculates the unit vector of the given vector (i.e. same direction # but with magnitude scaled to 1) def get_unit_vector(self): mag = self.magnitude() vector = PhysicsVector(self.x, self.y, self.z) vector.scale_by(1./mag) return vector # Method that calculates the magnitude of a vector def magnitude(self): return np.sqrt(PhysicsVector.dot(self,self)) # Method that returns the dot product of two vectors def dot(u, v): return (u.x * v.x) + (u.y * v.y) + (u.z * v.z) # Method that returns the cross product of two vectors def cross(u, v): a = u.y*v.z - u.z*v.y b = u.x*v.z - u.z*v.x c = u.x*v.y - u.y*v.x return PhysicsVector(a,b,c) # Method that returns the addition of two vectors def add(u, v): x = u.x + v.x y = u.y + v.y z = u.z + v.z return PhysicsVector(x, y, z) # Method that returns the subtraction of two vectors def subtract(u, v): x = u.x - v.x y = u.y - v.y z = u.z - v.z return PhysicsVector(x, y, z)
def create_txt(filename): fp = open(filename,"w+") ch = input('输入字符串:\n').upper() while ch != '#': fp.write(ch) ## fp.write('\n') fp.seek(0,0) print(fp.read()) ch = input('').upper() fp.close() def merge_txt(): with open('111.txt') as fp: a = fp.read() with open('222.txt') as fp: b = fp.read() with open('333.txt','w+') as fp: l = list(a + b) l.sort() s = '' s = s.join(l) fp.write(s) fp.seek(0,0) print(fp.read()) create_txt('111.txt') create_txt('222.txt') merge_txt()
for i in range(100,1000): s=str(i) one=int(s[-1]) ten=int(s[-2]) hun=int(s[-3]) if i == one**3+ten**3+hun**3: print(i) for i in range(100,1000): if i == (i//100)**3+((i%100)//10)**3+(i%100%10)**3: print(i) def Narcissus(): for each in range(100,1000): temp = each sum = 0 while temp: sum = sum + (temp%10)**3 temp = temp // 10 if sum == each: print(each,end = '\t') print('所有水仙花数分别是:',end = '\n') Narcissus()
class Pagination(object): def __init__(self): self.links = [] self.cursor = 0 def add_item(self, link): if link in self.links: return self.links.append(link) def reset_next(self): self.cursor = 0 def has_next(self): return self.cursor <= len(self.links) - 1 def get_next(self): if self.has_next() is False: raise ValueError('Pagination.get_next() cursor is out of bounds') link = self.links[self.cursor] self.cursor += 1 return link def is_empty(self): return len(self.links)
#################################### # instructions #################################### instructions = ''' Use the record button to record music played to the microphone. Music sheet will be created from this music. Use the upload button to upload previously saved music. Music sheet will be created from this. Once in the sheet music screen, you can either: play, edit or save the music. Edit the music by clicking on a note and then using the following commands: - Up and Down to change the note (eg. A -- > B) - Left and Right to change the note duration (eg. 1/4 --> 1/2) - 'c' key to copy the note right beside it by shifting the rest - 'v' key to create a note above the selected one ''' #################################### # help mode #################################### def mousePressed(event, data): pass def keyPressed(event, data): if event.keysym == "Escape": data.mode = "home" def timerFired(data): pass def redrawAll(canvas, data): canvas.create_rectangle(0, 0, data.width, data.height, fill = "white", width = 0) canvas.create_text(data.width // 2, data.height // 12, text = "Instructions", fill = "black", font = "DTNoted 35") canvas.create_text(data.width // 2, 1 * data.height // 8, text = instructions, fill = "grey80", anchor = "n", font = "Calibri 16 bold") canvas.create_text(3 * data.width // 4, 15 * data.height // 16, text = "Esc to go Home", anchor = "w", fill = "grey80", font = "Calibri 16 bold")
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split df = pd.read_csv('Boston_Housing.csv')#import the data set train,test= train_test_split(df, test_size= 0.20, random_state=1)#Split 80% of data as the training set and rest as the test set train=train.values#convert test and train set into numpy array test=test.values x_train,y_train=train[:,0:3] ,train[:,3]#Divide test set into feature matrix and response matrix x_test,y_test = test[:,0:3] ,test[:,3] x_train= np.c_[np.ones(391),x_train]#arrange x by settiing x[0]=1 as given x array x_test= np.c_[np.ones(98), x_test] #find transpose xtrain_transpose=np.transpose(x_train) #find matrix multiplication of x transpose and x xt_x=xtrain_transpose.dot(x_train) #find inverse of the above multiplication xt_xInverse=np.linalg.inv(xt_x) #find multification of the x transpose and y xt_y=xtrain_transpose.dot(y_train) #Find the parameter value(beta_hat) beta_hat=xt_xInverse.dot(xt_y) #Predict the response values for both test and train set y_hat=x_train.dot(beta_hat) y_hat_test=x_test.dot(beta_hat) residual_error_train=y_train-y_hat residual_error_test=y_test-y_hat_test #print(residual_error) plt.title('Residual errors') plt.xlabel('Predicted Value') plt.ylabel('Actual Value') plt.scatter(y_hat, y_train,color = "b", marker = ".", s = 60) #plotting residual errors for training set plt.scatter(y_hat_test, y_test,color = "r", marker = "*", s = 60) #plotting residual errors for test set plt.show() #displaying the plot
# Remove Specified Item # The remove() method removes the specified item. # Example # Remove "banana": thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) # Remove Specified Index # The pop() method removes the specified index. # Example # Remove the second item: thislist = ["apple", "banana", "cherry"] thislist.pop(1) print(thislist) # If you do not specify the index, the pop() method removes the last item. # Example # Remove the last item: thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) # The del keyword also removes the specified index: # Example # Remove the first item: thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist) # The del keyword can also delete the list completely. # Example # Delete the entire list: thislist = ["apple", "banana", "cherry"] del thislist # Clear the List # The clear() method empties the list. # The list still remains, but it has no content. # Example # Clear the list content: thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist)
# Append Items # To add an item to the end of the list, use the append() method: # Example # Using the append() method to append an item: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) # Insert Items # To insert a list item at a specified index, use the insert() method. # The insert() method inserts an item at the specified index: # Example # Insert an item as the second position: thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) # Note: As a result of the examples above, the lists will now contain 4 items. # Extend List # To append elements from another list to the current list, use the extend() method. # Example # Add the elements of tropical to thislist: thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) print(thislist) # The elements will be added to the end of the list. # Add Any Iterable # The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.). # Example # Add elements of a tuple to a list: thislist = ["apple", "banana", "cherry"] thistuple = ("kiwi", "orange") thislist.extend(thistuple) print(thislist)
# Loop Through a Dictionary # You can loop through a dictionary by using a for loop. # When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } # Example # Print all key names in the dictionary, one by one: for x in thisdict: print(x) # Example # Print all values in the dictionary, one by one: for x in thisdict: print(thisdict[x]) # Example # You can also use the values() method to return values of a dictionary: for x in thisdict.values(): print(x) # Example # You can use the keys() method to return the keys of a dictionary: for x in thisdict.keys(): print(x) # Example # Loop through both keys and values, by using the items() method: for x, y in thisdict.items(): print(x, y)
""" 10. Desenvolva um gerador de tabuada, capaz de gerar a tabuada de qualquer número inteiro entre 1 a 10. O usuário deve informar de qual numero ele deseja ver a tabuada. A saída deve ser conforme o exemplo abaixo: Tabuada de 5: 5 X 1 = 5 5 X 2 = 10 ... 5 X 10 = 50 """ num = int(input('Digite o numero :')) print('Tabuada de', num, ':') i = 0 for x in range(1, 11): i += 1 print(num, 'X', i, '=',num * i)
# Loop Through a Tuple # You can loop through the tuple items by using a for loop. # Example # Iterate through the items and print the values: thistuple = ("apple", "banana", "cherry") for x in thistuple: print(x) # Learn more about for loops in our Python For Loops Chapter. # Loop Through the Index Numbers # You can also loop through the tuple items by referring to their index number. # Use the range() and len() functions to create a suitable iterable. # Example # Print all items by referring to their index number: thistuple = ("apple", "banana", "cherry") for i in range(len(thistuple)): print(thistuple[i]) # ADVERTISEMENT # Using a While Loop # You can loop through the list items by using a while loop. # Use the len() function to determine the length of the tuple, # then start at 0 and loop your way through the tuple items by refering to their indexes. # Remember to increase the index by 1 after each iteration. # Example # Print all items, using a while loop to go through all the index numbers: thistuple = ("apple", "banana", "cherry") i = 0 while i < len(thistuple): print(thistuple[i]) i = i + 1
# Python Indentation # Indentation refers to the spaces at the beginning of a code line. # Where in other programming languages the indentation in code is for readability only, # the indentation in Python is very important. # Python uses indentation to indicate a block of code. # Example: if 5 > 2: print("Five is greater than two!")
""" 10.Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit. Fórmula : (C × (9/5)) + 32 = F """ cel = float(input('Digite a temperatura em Celsius:')) print('A temperatura em Fahrenheit é: ', (cel * (9/5)) + 32)
""" 8.Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.""" hr = float(input('Digite o valor ganho por cada hora trabalhada: ')) qtde = float(input('Digite a quantidade de horas trabalhadas no mês: ')) amount = hr * qtde currency = '{:,.2f}'. format(amount) print('O salário bruto total referente ao mês trabalhado é: ', 'R$', currency)
""" 16. A série de Fibonacci é formada pela seqüência 0,1,1,2,3,5,8,13,21,34,55,... Faça um programa que gere a série até que o valor seja maior que 500. """ n = 1 u_1 = 1 u_2 = 1 count = 0 lista = [1, 1] for vic in range(n, 14): count = u_1 + u_2 u_1 = count u_2 = (count - u_2) lista.append(count) print(lista)
""" 8.Palíndromo. Um palíndromo é uma seqüência de caracteres cuja leitura é idêntica se feita da direita para esquerda ou vice−versa. Por exemplo: OSSO e OVO são palíndromos. Em textos mais complexos os espaços e pontuação são ignorados. A frase SUBI NO ONIBUS é o exemplo de uma frase palíndroma onde os espaços foram ignorados. Faça um programa que leia uma seqüência de caracteres, mostre−a e diga se é um palíndromo ou não. """ frase = input('Escreva uma frase: ').upper().replace(' ', '') fraseinvertida = frase[::-1] if frase == fraseinvertida: print('É um palíndromo: {} = {}.'.format(frase, fraseinvertida)) else: print('Não é palíndromo.')
""" 10. Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo compreendido por eles. """ n1 = int(input('Digite um numero: ')) n2 = int(input('Digite um numero: ')) for i in range(n1 + 1, n2): print(i, end=' ')
''' 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。 在 S 上反复执行重复项删除操作,直到无法继续删除。 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 输入:"abbaca" 输出:"ca" 解释: 例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。 之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。 思路:用栈实现,遍历str,如果栈为空,则入栈,如果栈顶元素和字符串元素相等,则stack.pop栈顶元素,如果不等,就入栈 ''' ''' join函数: 作用: 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串 语法: 'sep'.join(seq) 参数说明 sep:分隔符。可以为空 seq:要连接的元素序列、字符串、元组、字典 上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串 返回值:返回一个以分隔符sep连接各个元素后生成的字符串 ''' class Solution: def removeDuplicates(self, S: str) -> str: stack = [] i = 0 while i < len(S): if stack: if stack[len(stack)-1] == S[i]: stack.pop() else: stack.append(S[i]) else: stack.append(S[i]) i += 1 return "".join(stack) if __name__ == '__main__': s = Solution() print(s.removeDuplicates('abbac'))
import math from random import seed from random import randint class Deck: def __init__(self, name): self.name = name self.deck = [] def splitDeck(self): firstHalf = [] secondHalf = [] for i in range(0, math.floor(len(self.deck)/2)): firstHalf.append(self.deck[i]) for j in range(math.floor(len(self.deck)/2), len(self.deck)): secondHalf.append(self.deck[j]) return firstHalf, secondHalf def zipperShuffle(self): #right left zipper shuffle firstHalf = self.splitDeck()[0] secondHalf = self.splitDeck()[1] deck = [] for i in range(0, len(firstHalf)): deck.append(secondHalf[i]) deck.append(firstHalf[i]) if len(self.deck)%2 != 0: deck.append(secondHalf[len(secondHalf)-1]) self.deck = deck def addCard(self, cardSuit, cardTitle): card = Card(cardSuit, cardTitle) self.deck.append(card) def printCards(self): for i in range(0, len(self.deck)): print(self.deck[i].getCard()) def getCards(self): deck = [] for i in range(0, len(self.deck)): deck.append(self.deck[i].getCard()) return deck def newDeck(self): if self.deck == []: for i in range(0,3): suitDict = {0 : "Diamonds", 1 : "Hearts", 2 : "Clubs", 3 : "Spades"} cardSuit = suitDict[i] for j in range(2, 15): titleDict = {11 : "Jack", 12 : "Queen", 13 : "King", 14 : "Ace"} if j > 10: cardTitle = titleDict[j] self.deck.append(Card(cardTitle, cardSuit)) else: cardTitle = str(j) self.deck.append(Card(cardTitle, cardSuit)) else: self.deck = [] self.newDeck() def shuffle(self): #a not really random shuffle, but a good attempt at making something that resembles random. seed = 1 cards = [] for i in range(0, randint(0,10)): for j in range(0, randint(0,15)): self.zipperShuffle() cards.append(self.deck.pop()) for k in range(0, len(cards)): self.deck.append(cards[k]) class Card: def __init__(self, cardSuit , cardTitle): self.cardSuit = cardSuit self.cardTitle = cardTitle def setSuit(self, cardSuit): self.cardSuit = cardSuit def setTitle(self, cardTitle): self.cardTitle = cardTitle def getCard(self): return self.cardSuit + " of " + self.cardTitle def main(): deck1 = Deck("Spalding") deck1.addCard("Ace", "Spades") deck1.addCard("2", "Clubs") deck1.addCard("3", "Diamonds") deck1.addCard("4", "Hearts") deck1.addCard("5", "Spades") deck1.addCard("6", "Clubs") deck1.printCards() print('\n') deck1.zipperShuffle() deck1.printCards() print("\n") print(deck1.getCards()) deck1.newDeck() deck1.printCards() print('\n') deck1.shuffle() deck1.printCards() main()
#Multiple Linear Regression with Gradient Descent Algorithm in Linear Algebra Style #more than one input variable """ File: Patients.txt schema: id,name,age,wgt,hgt,cholestral features:age,wgt,hgt label: continuous type- cholestarl """ #step1: read data and seperate features and labels f=open("C:/Users/ic762755/Desktop/mystuff/patients.txt") hdr=f.readline() data=f.readlines() x=[] y=[] for line in data: w=line.strip().lower().split(",") ins=[float(v) for v in w[2:-1]] x.append(ins) y.append(float(w[-1])) import numpy as np x=np.array(x) ones=np.ones(x.shape[0]) X=np.c_[ones,x] Y=np.c_[y] print(X) print(Y) #Define Random Weights np.random.seed(90) w=2*np.random.random((X.shape[1],1))-1 print(w.shape) #functions for prediction.loss(mse),derivative def predict(x,w): return x.dot(w) def loss(y,ycap): return ((y-ycap)**2).mean() def derivative(x,y,w): ycap=predict(x,w) return (x.T.dot(y-ycap))/x.shape[0] #Step4: perform trails whether loss is decreasing #trail 1 ycap1=predict(X,w) print(loss(y,ycap1)) grad=derivative(X,Y,w) w+=grad*0.02 #trail 2 ycap2=predict(X,w) print(loss(y,ycap2)) grad=derivative(X,Y,w) w+=grad*0.02 """Observation from above trails is instead of decrement of loss, loss got increased. So scaling is required""" #step 5: Scaling def sd(x): return (((x-x.mean())**2).sum()/(x.size-1))**0.5 def scale(x): return (x-x.mean())/sd(x) def scaleMatrix(x): for i in range(x.shape[1]): col=x[:,i] x[:,i]=scale(col) o=np.ones(x.shape[0]) return np.c_[o,x] #creating seperate instances for feature and label matrices ins=np.array(x) out=np.array(Y) X=scaleMatrix(ins) YL=scaleMatrix(out) YL=out print(X) print(YL) print(ins) print(out) #Step 6: Train the Model def train(x,y,w,alpha,iter,conv=1e-9): ploss=0 flag=0 for i in range(iter): ycap=predict(x,w) closs=loss(y,ycap) if i%1000==0: print("loss at iteration",i+1,closs) diff=abs(ploss-closs) if(diff<conv): print("Training completed after",i+1,"iterations") flag=1 break grad=derivative(x,y,w) w+=grad*alpha ploss=closs if(flag==0): print("Training not completed run few more iterations") return w theta=np.array(w) theta=train(X,YL,theta,0.02,1000000) print(w) print(theta) #Step 7: Accuracy testing based on closeness expectation between actual and predicted labels def accuracy(y,ycap,closeness): de=100-closeness dist=abs(y-ycap)/abs(y)*100 pcnt=dist[dist<=de].size n=y.shape[0] return pcnt/n*100 ycap=predict(X,theta) print(ycap) yc=ycap*sd(Y)+Y.mean() print(yc) accuracy(Y,yc,95) np.c_[Y,yc,abs(Y-yc)/abs(Y)*100] #step 9: Apply predictions on new data new=open("C:/Users/ic762755/Desktop/mystuff/newpatient.txt") hd=new.readline() data=new.readlines() p=[] for line in data: a=line.strip().lower().split(",") ins=[float(v) for v in a[2:]] p.append(ins) P=np.array(p) print(P) #Scaling new data with train data mean and standard deviation for i in range(P.shape[1]): s=sd(x[:,i]) m=x[:,i].mean() P[:,i]=(P[:,i]-m)/s print(P) o=np.ones(len(data)) P=np.c_[o,P] pcap=predict(P,theta) print(pcap) chols=pcap*sd(Y)+Y.mean() chols=chols.ravel() chols res=[d.strip()+","+str(c) for d,c in list(zip(data,chols))] res outfile=open("C:/Users/ic762755/Desktop/mystuff/newpatient.txt",'w') hdr='"Id","Name","Age","Weight","Height","Cholestrals"' outfile.write(hdr+"\n") for line in res: outfile.write(line+"\n") outfile.close()
#!/usr/bin/env python class Clock: def __init__(self, decimal_hours, decimal_minutes): self.minutes = decimal_hours*60 + decimal_minutes def _to_dec(self): decimal_hours = (self.minutes//60) % 24 decimal_minutes = (self.minutes - (decimal_hours*60)) % 60 return (decimal_hours, decimal_minutes) def add(self, y): self.minutes += y return self def __eq__(self, other): return str(self) == str(other) def __repr__(self): return "%02d:%02d" % (self._to_dec()) if __name__ == '__main__': import sys, time c = Clock(0,0) if len(sys.argv) == 2: i = float(sys.argv[1]) else: i = 1 while True: c.add(1); print c time.sleep(i)
import json from collections import Counter as counter # TODO no need for this global variable, place it in __ini__ method class TweetRank: """ TF: Term Frequency, which measures how frequently a term occurs in a document. Since every document is different in length, it is possible that a term would appear much more times in long documents than shorter ones. Thus, the term frequency is often divided by the document length (aka. the total number of terms in the document) as a way of normalization: # TF(t) = (Number of times term t appears in a document) / (Total number of terms in the document). IDF: Inverse Document Frequency, which measures how important a term is. While computing TF, all terms are considered equally important. However it is known that certain terms, such as "is", "of", and "that", may appear a lot of times but have little importance. Thus we need to weigh down the frequent terms while scale up the rare ones, by computing the following: IDF(t) = log_e(Total number of documents / Number of documents with term t in it). TF-IDF = TF*IDF """ # TODO create a method, generateTF(), that calculates the Term Frequency # TODO create a method, generateIDF(), that calculates the Inverse Document Frequency def __init__(self): self.selftweetDictionay = {} self.invertedIndex = {} self.hashtags = [] self.tweetsById = {} self.tweetFilePath = "../tweetFile.txt" # gather 1000 tweets # NOTE search for a way to use all tweets. # TODO the loop on row 40 is redundant, combine with loop on line 45 for tweet, n in enumerate(TWEETFILE): if n == 10000: break tweetDictionay[n] = tweet # TODO separate code in loop below, its doing too much for singleTweet in tweetDictionay: try: tweet = json.loads(tweetDictionay[singleTweet]) if "entities" in tweet: for tags in tweet['entities']['hashtags']: if tags and 'text' in tags: try: # collect all hashtags from a tweet hashtags.append(tags['text']) except AttributeError: print('\n\n' + 'Attribute Error') print(tags) # aggregate tags hashtagCount = counter(hashtags) #TODO - don't have to store entire tweet, we can store only the tweet id and retrive the entire tweet throuh the Twitter API # dict of tweets where key = tweet id, value: tweet tweetsById[tweet["id"]] = tweet for k, v in hashtagCount.items(): if k in invertedIndex: invertedIndex[k][0] += v # TODO too much data duplication, fix it # store individual count of tag per document invertedIndex[k][1].append([tweet["id"], v]) else: invertedIndex[k] = [v, [[tweet["id"], v]]] except TypeError: print("Type Error occurred") print(singleTweet) continue # TODO fix how rank is been calculated. # turn indivivual count into rank for k, v in invertedIndex.items(): for doc in v[1]: doc[1] = float(doc[1]) / float(v[0]) def searchByTagText(self, tag): """ :rtype: object """ try: # NOTE come up with a clever way to use the ranking # OBSERVATION: some tweets have more than one tag return {tag: TweetRank.tweetsById[TweetRank.invertedIndex[tag][1][0][0]]["text"]} except: return "not found" def searchByTagTweet(self, tag): """ :rtype: object """ try: return {tag: TweetRank.tweetsById[TweetRank.invertedIndex[tag][1][0][0]]} except: return "not found"
#def greet(name = 'Reddy',time = 'afternoon'): #print(f'Good {time} {name}, hope you are well') #name = input('enter your name:') #time = input('enter the time of day:') #greet(name='vijeet') def area(radius): return 3.142 * radius * radius def vol(area,length): print(area*length) radius = int(input('enter a radius:')) length = int(input('enter a length:')) #area_calc = area(radius) vol(area(radius), length)
# Faster sin/cos function by using a lookup table # Example code for Daniel Shiffman made by Ewoud Dronkert # https://twitter.com/ednl # https://github.com/ednl # Only needed for lookup table generation and validation from math import sin, cos, tau # Quadrants and circle below are not in degrees but in "index units" as defined by the step # If every integer degree is needed, then step = 1 and most of the code can be simplified # If fractional degrees are also needed, then this code needs to be modified! step = 3 # step in degrees, must divide 90 quad1 = 90 // step # first quadrant 90 degrees [integer] quad2 = 180 // step # second quadrant 180 degrees [integer] quad3 = 270 // step # third quadrant 270 degrees [integer] circle = 360 // step # a full circle 360 degrees [integer] d2r = tau / 360 # degrees to radians factor [float] i2r = step * d2r # index to radians factor [float] # From index to degrees def index2deg(a): return a * step # From index to radians def index2rad(a): return a * i2r # Generate the lookup table with index 0..quad1 inclusive (= 0..90 degrees inclusive) # In real code, this could (should) be a list of literal values # Use the minimum amount of decimals necessary, choice here: 5 sintable = [round(sin(index2rad(i)), 5) for i in range(quad1 + 1)] # Another possibility would be to make these values integers by multiplying them # by the number of decimals needed, while making sure that the maximum value (1 * 10^dec) # stays within the standard integer range of your platform (e.g. 32767). But then the # code using these values would have to be modified to take this scaling into account. # Give sine of argument 'a' given in "index units" by using lookup table # Argument 'a' is in stepped degrees where in this example the step is 3, so: # a = -1 => -3 degrees # a = 0 => 0 degrees # a = 1 => 3 degrees # a = 30 => 90 degrees # a = 31 => 93 degrees # Argument 'a' can be any integer but needs to be normalised, so this is slow for very # big (positive or negative) values. It depends on the CPU and language implementation # whether "mod" is faster than repeated adding/subtracting. On modern architectures, # mod is definitely faster, but on the Apple II+? I have no idea :) def sinlookup(a): # Normalise 'a' to the range 0..circle inclusive while a < 0: a += circle while a > circle: a -= circle # Value of 'a' is now in the range 0..360 degrees inclusive # Map each quadrant onto the first quadrant which is in the lookup table # Each time, "greater than" is good because the lookup table includes 90 degrees if a > quad3: return -sintable[circle - a] # double mirror if a > quad2: return -sintable[a - quad2] # shift and mirror if a > quad1: return sintable[quad2 - a] # mirror return sintable[a] # direct value # Same for cosine def coslookup(a): while a < 0: a += circle while a > circle: a -= circle if a > quad3: return sintable[a - quad3] # shift if a > quad2: return -sintable[quad3 - a] # double mirror if a > quad1: return -sintable[a - quad1] # shift and mirror return sintable[quad1 - a] # mirror # Test for a wide range of "index units" # and display difference between lookup value and calculation for i in range(-quad1, circle + quad1 + 1, 10): s1 = sinlookup(i) s2 = round(sin(index2rad(i)), 5) c1 = coslookup(i) c2 = round(cos(index2rad(i)), 5) print("index", i, "degrees", index2deg(i), "sin-err", s1 - s2, "cos-err", c1 - c2)
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ outCalls = set() inCalls = set() outTexts = set() inTexts = set() for entry in calls: outCalls.add(entry[0]) inCalls.add(entry[1]) for entry in texts: outTexts.add(entry[0]) inTexts.add(entry[1]) output = outCalls.difference(inCalls).difference(outTexts).difference(inTexts) telemarketers = list(output) telemarketers.sort() print("These numbers could be telemarketers:") for num in telemarketers: print(num)
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Get the CSV file. signals_file = pd.read_csv('signals-1.csv', header=None) # Observe some basic information. number_of_signals = len(signals_file.loc[:, 0]) size_of_signal = len(signals_file.loc[0, :]) print('Number of signals: %s' %(number_of_signals)) print('Size of signal: %s datapoints' %(size_of_signal)) # Now, analyze each signal, one by one, and classify it. # In the 101th column of the csv file, I will manually enter a 0 or 1. # A 0 will signify that the data is not valid, and the reverse for a 1. individual_signal_index = 700 print('Observing signal #%s' %(individual_signal_index + 1)) # Exclude the 101th column, or 100th index, because that is where I will be storing the classification. individual_signal = signals_file.loc[individual_signal_index, 0:99] x = np.linspace(0, 100, 100) fig = plt.figure() ax0 = fig.add_subplot(111) ax0.set_title('Signal #%s' %(individual_signal_index + 1)) ax0.scatter(x, individual_signal) plt.show()
# coding: utf-8 # In[2]: import matplotlib.pyplot as plt from sklearn import datasets # our support vector machine classifier! from sklearn import svm # load digits dataset digits = datasets.load_digits() # In[3]: # let's see what this dataset is all about print digits.DESCR # In[15]: # let's see what keys this digits object has print digits.keys() # Let's see what classes we want to put digits into print digits.target_names # In[7]: # Let's pic one and see what it looks like first_digit = digits.data[0] print first_digit # But what do all of those columns mean!?!?! # Let's go to the whiteboard and find out... # in each quadrant how many pixels/boxes are filled in (turned on) # In[5]: # let's see what the first digit was tagged as print digits.target[0] # In[6]: # now let's see what digits.images[0] is # it's just the first_digit array reshaped as an 8 x 8 matrix print digits.images[0] # In[102]: # let's instantiate our Support Vector Classifier # C is the error threshold # Gamma is a tuning parameter related to the gradient descent by... # controling the speed / distance at which we step through gradient descent classifier = svm.SVC(gamma=.0001, C=100) # how many data points do we have? print len(digits.data) # In[113]: # let's create a training set of the first 1597 of the 1797 data points x_training, y_training = digits.data[:-97], digits.target[:-97] # now let's train the classifier on the training data classifier.fit(x_training, y_training) # In[114]: print "Prediction {}".format(classifier.predict(digits.data[1590])) print digits.target[1590] # In[115]: # show the image plt.imshow( digits.images[1600], cmap=plt.cm.gray_r, interpolation="nearest" ) plt.show() # In[116]: # Wow!!!! Let's see what the accuracy is # Let's go from digits.data[-200] all the way to digits.data[-1] correct = 0 indices = range(-200, 0) for i in indices: # if we were correct if classifier.predict(digits.data[i])[0] == digits.target[i]: correct += 1 accuracy = float(correct) / len(indices) print "Accuracy: {}".format(accuracy) # In[117]: # Let's try using kNN from sklearn.neighbors import KNeighborsClassifier knn_clf = KNeighborsClassifier(n_neighbors=25) # train the classifier knn_clf.fit(x_training, y_training) # Let's see what the accuracy is # Let's go from digits.data[-200] all the way to digits.data[-1] correct = 0 indices = range(-200, 0) for i in indices: # if we were correct if knn_clf.predict(digits.data[i])[0] == digits.target[i]: correct += 1 accuracy = float(correct) / len(indices) print "Accuracy: {}".format(accuracy) # In[118]: # Let's try with Logistic Regression from sklearn.linear_model import LogisticRegression log_reg = LogisticRegression() log_reg.fit(x_training, y_training) # Let's see what the accuracy is # Let's go from digits.data[-200] all the way to digits.data[-1] correct = 0 indices = range(-200, 0) for i in indices: # if we were correct if log_reg.predict(digits.data[i])[0] == digits.target[i]: correct += 1 accuracy = float(correct) / len(indices) print "Accuracy: {}".format(accuracy) # In[ ]:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- print(abs(-10)) print(int('123')) print(int(12.34)) print(float('12.34')) print(str(123)) print(bool(1)) print(bool('')) print(hex(1080)) # 定义函数 def my_abs(x): if not isinstance(x, (int, float)): raise TypeError("bad operand type") if x >= 0: return x; else: return -x; print(my_abs(199)) # print(my_abs("A")) # pass可以用来作为占位符, # 比如现在还没想好怎么写函数的代码,就可以先放一个pass,让代码能运行起来。 def nop(): pass import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny r = move(100, 100, 60, math.pi / 6) print(r) def quadratic(a, b, c): if not isinstance((a, b, c), int): raise TypeError("Bad Operand type") delta = b * b - 4 * a * c if (delta) > 0: print("此方程有双实根") x1 = (-b + math.sqrt(delta)) / a * 2 x2 = (b + math.sqrt(delta)) / a * 2 return x1, x2 elif delta == 0: print("此方程有单实根") return -b / a * 2 else: print("此方程没有根") return None def power(x, n=2): s = 1 while n > 0: s *= x n -= 1 return s print(power(5, 2)) def add_end(L=None): if L == None: L = [] L.append('end') return L print(add_end()) print(add_end()) # 可变参数 def calc(numbers): sum = 0 for n in numbers: sum += n * n return sum # 调用的时候,需要先组装出一个list或tuple print(calc([1, 2, 3])) print(calc((1, 2, 3))) def calc(*numbers): sum = 0 for n in numbers: sum += n * n return sum print(calc(1, 2, 3, 4)) # 在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传入 num = [1, 2, 3, 4] print(calc(*num)) # 关键字参数 def person(name, age, **kw): if 'city' in kw: pass if 'job' in kw: pass print("name:", name, "age:", age, "other:", kw) person('Michael', 30) person("Adam", 45, gender="M", job="Engineer") # 可以先组装出一个dict,然后,把该dict转换为关键字参数传进去 extra = {'city': 'Beijing', 'job': 'Engineer'} # print(*extra) print(extra) # **extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数, # kw将获得一个dict, # 注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra person("Tom", 24, **extra) # 命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数。 def person(name, age, *, city, job): print(name, age, city, job) person('Jack', 24, city='Beijing', job='Engineer') # 如果没有可变参数,就必须加一个*作为特殊分隔符。 # 如果缺少*,Python解释器将无法识别位置参数和命名关键字参数 def person(name, age, *args, city="Taiyuan", job): print(name, age, args, city, job) person('Jack', 24, job='Engineer') # 组合参数 # 顺序:必选参数、默认参数、可变参数、命名关键字、关键字参数 def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) f1(1, 2) f1(1, 2, 3) f1(1, 2, 3, 'a', 'b') f1(1, 2, 3, 'a', 'b', x=99) f2(1, 2, d=99, ext=None) args = (1, 2, 3, 4) kw = {'d': 99, 'x': '#'} f1(*args, **kw) args = (1, 2, 3) kw = {'d': 20, 'x': '#'} f2(*args,**kw) # 递归函数 def fact(n): if n==1: return 1; return n*fact(n-1) print(fact(5)) # 尾递归 :防止栈溢出 # 尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式 def fact(n): return fact_iter(n,1) def fact_iter(num,product): if num==1: return product return fact_iter(num-1,num*product) # 利用递归函数移动汉诺塔: def move(n, a, b, c): if n == 1: print('move', a, '-->', c) else: move(n-1, a, c, b) move(1, a, b, c) move(n-1, b, a, c) move(3, 'A', 'B', 'C')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 传入函数 def add(x, y, f): return f(x) + f(y) print(add(5, -6, abs)) # map/reduce def f(x): return x * x r = map(f, [1, 2, 3, 4, 5, 6, 7, 8]) # Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list print(list(r)) print(list(map(str, [1, 2, 3]))) from functools import reduce def fn(x, y): return x * 10 + y print(reduce(fn, [1, 3, 5, 7, 9])) def char2num(s): digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return digits[s] print(reduce(fn, map(char2num, '13579'))) def str2int(s): DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def fn(x, y): return 10 * x + y def char2num(s): return DIGITS[s] return reduce(fn, map(char2num, s)) print(str2int("11010")) DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def char2num(s): return DIGITS[s] def str2int(s): return reduce(lambda x, y: x * 10 + y, map(char2num, s)) print(str2int("998")) def normalize(name): return name[:1].upper() + name[1:].lower() L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2) def prod(L): def fn(x, y): return x * y return reduce(fn, L) print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) if prod([3, 5, 7, 9]) == 945: print('测试成功!') else: print('测试失败!') def str2float(s): DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2num(s): return DIGITS[s] def fn(x, y): return x * 10 + y i = s.index('.') s = s[:i] + s[i + 1:] return reduce(fn, map(str2num, s)) / (10 ** (len(s) - i)) # 这里s已经减去了'.',所以小数部分位数不需要在减1 # print('123.456'.__len__()) # print('123.456'.index('.')) print('str2float(\'123.456\') =', str2float('123.456')) if abs(str2float('123.456') - 123.456) < 0.00001: print('测试成功!') else: print('测试失败!') # filter def is_odd(n): return n % 2 == 1 print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))) def not_empty(s): return s and s.strip() print(list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))) # 全体素数的表示 def _odd_iter(): n = 1 while True: n += 2 yield n def _not_divisible(n): return lambda x: x % n > 0 def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) yield n it = filter(_not_divisible(n), it) for n in primes(): if n < 1000: print(n) else: break def is_palindrome(n): k = str(n) return k == k[::-1] output = filter(is_palindrome, range(1, 1000)) print('1~1000:', list(output)) if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: print('测试成功!') else: print('测试失败!') # sorted r = sorted([36, 5, -12, 9, -21], key=abs, reverse=True) print(r) r = sorted(['bob', 'about', 'Zoo', 'Credit']) print(r) # 默认使用ASCII码进行排序 r = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower) print(r) L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_name(t): return t[0].lower() L2 = sorted(L, key=by_name) print(L2) def by_score(t): return -t[1] L2 = sorted(L, key=by_score) print(L2) # 函数作为返回值 # 常见的求和函数 def calc_sum(*args): ax = 0 for n in args: ax += n return ax def lazy_sum(*args): def sum(): ax = 0 for n in args: ax += n return ax return sum f = lazy_sum(1, 3, 5, 7, 9) print(f) print(f()) # 当我们调用lazy_sum()时,每次调用都会返回一个新的函数,即使传入相同的参数 f1 = lazy_sum(1, 3, 5, 7, 9) f2 = lazy_sum(1, 3, 5, 7, 9) print(f1 == f2) # 闭包 Closure def count(): fs = [] for i in range(1, 4): def f(): return i * i fs.append(f) return fs # 返回list # 返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量。 f1, f2, f3 = count() print(f1()) print(f2()) print(f3()) def count(): def f(j): def g(): return j * j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f() return fs # 这里返回的并不是内部的函数 f1, f2, f3 = count() print(f1()) print(f2()) print(f3()) # def createCounter(): # global i # i=0 # def counter(): # global i # i=i+1 # return i # return counter # def createCounter(): # n=[0] # def counter(): # n[0]=n[0]+1 # return n[0] # return counter def createCounter(): def iter(): n = 1 while 1: yield n n += 1 it = iter() def counter(): return next(it) return counter # 这里调用counter是为了将函数变成可重复调用的,并且会保存上一次的调用结果数据,对本次调用产生影响 # 测试: counterA = createCounter() print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 counterB = createCounter() if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]: print('测试通过!') else: print('测试失败!') # 匿名函数 r = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) f = lambda x: x * x print(f) # 同样,也可以把匿名函数作为返回值返回,比如: def build(x, y): return lambda: x * x + y * y print(build(1, 10)) # 直接返回的匿名函数无法直接执行 f = build(1, 10) print(f) print(f()) L = list(filter(lambda x: x % 2 == 1, range(1, 20))) print(L) # 装饰器 import time def now(): print(time.asctime(time.localtime(time.time()))) f = now f() print(now.__name__) # 现在,假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志, # 但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式, # 称之为“装饰器”(Decorator)。 def log(func): def wrapper(*args, **kw): print("call %s():" % func.__name__) return func(*args, **kw) # 最终要返回原函数 return wrapper # 把@log放到now()函数的定义处,相当于执行了语句: # now = log(now) # # 次标注的函数需要在标注之前 @log def now(): print(time.asctime(time.localtime(time.time()))) now() def log(text): def decorator(func): def wrapper(*args, **kw): print("%s %s():" % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator @log('execute') def now(): print(time.asctime(time.localtime(time.time()))) now() now = log('final')(now) # final wrapper(): print(now.__name__) # 因为返回的那个wrapper()函数名字就是'wrapper', # 所以,需要把原始函数的__name__等属性复制到wrapper()函数中, # 否则,有些依赖函数签名的代码执行就会出错。 # 不需要编写wrapper.__name__ = func.__name__这样的代码, # Python内置的functools.wraps就是干这个事的, # 所以,一个完整的decorator的写法如下: import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): # wrapper.__name__ = func.__name__ print("%s %s():" % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator @log(text='execute') def now(): print(time.asctime(time.localtime(time.time()))) log('final')(now)() print("练习 metric") def metric(func): @functools.wraps(func) def wrapper(*args, **kw): start = time.time() func(*args, **kw) end = time.time() print('%s executed in %s ms' % (func.__name__, end - start)) return func(*args, **kw) return wrapper # 测试 @metric def fast(x, y): time.sleep(0.0012) return x + y; @metric def slow(x, y, z): time.sleep(0.1234) return x * y * z; f = fast(11, 22) s = slow(11, 22, 33) if f != 33: print('测试失败!') elif s != 7986: print('测试失败!') from inspect import isfunction def logger(arg=''): if type(arg) == str or not arg: def decorator(fn): @functools.wraps(fn) def wrapper(*args, **kw): print(arg + "begin call") fw = fn(*args, **kw) print(arg + "end call") return fw return wrapper return decorator if isfunction(arg): @functools.wraps(arg) def wrapper(*args, **kw): print("begin call") fw = arg(*args, **kw) print("end call") return fw return wrapper @logger('excute') def a(name): return name @logger def b(name): return name A = a('Test A') print(A) print() B = b('Test B') print(B) # 偏函数 def int2(x, base=2): return int(x, base) print(int2('1000000')) import functools int2 = functools.partial(int, base=2) print(int2('1000000')) max2 = functools.partial(max, 10) # 会把10作为*args的一部分自动加到左边 print(max2(5, 6, 7))
import random import pygame import dependencies.consts as c def distance(p1: (int, int), p2: (int, int)) -> float: return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** .5 class Dot: """ Class used to create a dot object. """ def __init__(self, name: str, r_size: int, color: (int, int, int), size_change: int = 0, max_move_speed: int = 5, pos: (int, int) = None): """ Initializes dot object. :param name: Name of dot. :param r_size: Radius size of dot. :param color: Color of dot. :param size_change: The amount by which our dot size is changed. :param pos: Position of dot. """ self.name = name self.r_size = r_size self.color = color self.size_change = size_change if pos: self.pos_x = pos[0] self.pos_y = pos[1] else: self.pos_x = random.randint(r_size, c.SCREEN_WIDTH - r_size) self.pos_y = random.randint(r_size, c.SCREEN_HEIGHT - r_size) self.max_move_speed = max_move_speed self.move = random.randint(-max_move_speed, max_move_speed) self.move_direction = random.randint(0, 1) def disp(self, screen) -> None: """ Displays dot on screen. :return: None """ pygame.draw.circle(screen, self.color, (self.pos_x, self.pos_y), self.r_size) def collision(self, pos_x, pos_y) -> bool: """ Detect collison. :return: True/False. """ if distance((self.pos_x, self.pos_y), (pos_x, pos_y)) <= c.CIRCLE_R_SIZE + self.r_size: return True else: return False def determine_move(self): self.move = random.randint(-self.max_move_speed, self.max_move_speed) * c.MULT self.move_direction = random.randint(0, 1) def move_pos(self): if self.move_direction: self.pos_x += self.move if self.pos_x < self.r_size: self.pos_x = self.r_size if self.pos_x > c.SCREEN_WIDTH - self.r_size: self.pos_x = c.SCREEN_WIDTH - self.r_size else: self.pos_y += self.move if self.pos_y < self.r_size: self.pos_y = self.r_size if self.pos_y > c.SCREEN_HEIGHT - self.r_size: self.pos_y = c.SCREEN_HEIGHT - self.r_size
''' File name: homicide_year_sort.py @author: Simen Davanger Wilberg Date created: 4/30/2017 Date last modified: 5/8/2017 Finds the number of homicides for each year, and sorts the list in a descending orders. ''' def sort_years(homicide_array,outfile): f = open(outfile,"a") years = [[x, 0] for x in range(1980,2015)] # Count up homicides for each year. for homicide in homicide_array: for year in years: if homicide.year == year[0]: year[1] += 1 break # Sort years based on the count, descending years.sort(key=lambda x: x[1], reverse=True) # write years with most homicides. f.write('Years with most homicides:\n') for x in range(5): f.write('[' + str(years[x][0]) + ', ' + str(years[x][1]) + ']\n') # write years with least homicides. f.write('\n') f.write('Years with least homicides:\n') for x in range(len(years)-1, len(years)-6, -1) : f.write('[' + str(years[x][0]) + ', ' + str(years[x][1]) + ']\n') # Initialize years, will hold the homicide count of several years. year80s = 0 year90s = 0 year2000s = 0 year2010s = 0 for x in range(len(years)): if str(years[x][0]).startswith('198'): year80s += years[x][1] elif str(years[x][0]).startswith('199'): year90s += years[x][1] elif(str(years[x][0]).startswith('200')): year2000s += years[x][1] elif(str(years[x][0]).startswith('201')): year2010s += years[x][1] f.write('\n') # f.writeresult. f.write('Average homicides/year:\n') f.write('1980-1989: ' + str(year80s / 10) + '/year\n') f.write('1990-1999: ' + str(year90s / 10) + '/year\n') f.write('1999-2009: ' + str(year2000s / 10) + '/year\n') f.write('2009-2014: ' + str(year2010s / 5) + '/year\n') f.write("\n") f.close()
import sys sys.stdin = open("cons_input.txt") N = int(input()) global_max = 0 temp_max = float(input()) for _ in range(N-1): now = float(input()) temp_max *= now if temp_max > global_max: global_max = temp_max if temp_max < 1: temp_max = now print(round(global_max, 3))
import sys sys.stdin = open("n_root_input.txt") def digitroot(n): if n < 10: return n return digitroot(n//10) + n%10 def recurse(n): answer = n while answer >9: answer = digitroot(n) return answer print(recurse(65536))
places = ['los angeles', 'cremona', 'berlin', 'paris', 'tokyo'] print(places) #print your list in its original order print(sorted(places)) #use sorted() to print your list in alphabetical order print(places) #show that your list is still in its original order print(sorted(places,reverse=True)) #use sorted() to print your list in reverse alphabetical order print(places) #show that your list is still in its original order places.reverse() print(places) # use reverse() method to change the order of your list places.reverse() print(places) #print the list to show it's back to its original order places.sort() print(places) #use sort() to change your list so it's stored in alphabetical order. print the list to show that its order has been changed places.sort(reverse=True) print(places) # use sort() to change your list so it's stored in reverse alphabetical order and then show it
names = ['mozart', 'beethoven', 'bach'] for name in names: message = f'{name.title()}, i would like to invite you to chicken dinner!' print(message) message = f'{names.pop(1)} can`t make it' print(message) names.append('haydn') for name in names: message = f'{name.title()}, i would like to invite you to chicken dinner!' print(message)
#SQUARE-MATRIX-MULTIPLY def square_matrix_multiply(A,B): len_row = len(A) len_col = len(A[0]) C = [[0 for _ in range(len(A))] for _ in range(len(B[0]))] for i in range(len_row): for j in range(len(B[0])): for k in range(len_col): C[i][j] += A[i][k] * B[k][j] return C A = [[1,2,3], [5,6,7]] B = [[1,1],[2,2],[3,3]] print(square_matrix_multiply(A,B))
favorite_places = { 'kim': ['los angeles', 'japan', 'korea'], 'park': ['paris', 'spain', 'cheongju'], 'kang': ['busan', 'park', 'gym'], } for name, places in favorite_places.items(): print(name + ": ") for place in places: print("\t" + place)
def build_profile(first, last, **user_info): """build a dictionary containing every thing we know about a user.""" profile ={} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('eric', 'kim', country = 'korea', sex = 'male', does_love_counts = 'yes') print(user_profile)
def swap(arr,x,y): temp = arr[x] arr[x] = arr[y] arr[y] = temp return arr def quickSort(arr,low,high): if low<high: #print("The arr before sort:",arr[low:high+1]) pivot = arr[low] i = low+1 j = low+1 while j <= high: if arr[j]<=pivot: if i!=j: swap(arr,i,j) i = i+1 j = j+1 #print("The pivot is :",pivot) swap(arr,low,i-1) #print(arr[low:high+1]) quickSort(arr,low,i-2) quickSort(arr,i,high) return arr #l = [3,8,2,5,1,4,7,6] l = [] f = open("./IntegerArray.txt") while True: line = f.readline() if line!='': l.append(int(line.strip('\n'))) if not line: break quickSort(l,0,len(l)-1) print(l)
import threading import random import time class Philosopher(threading.Thread): running = True def __init__(self, name, forkOnLeft, forkOnRight): threading.Thread.__init__(self) self.name = name self.forkOnLeft = forkOnLeft self.forkOnRight = forkOnRight def run(self): while (self.running): time.sleep(random.uniform(1, 5)) print("%s jest głodny. \n" % self.name) self.dine() def dine(self): fork1, fork2 = self.forkOnLeft, self.forkOnRight while (self.running): fork1.acquire(True) locked = fork2.acquire(False) if locked: break fork1.release() print("%s odkłada widelce. \n" % self.name) fork1, fork2 = fork2, fork1 else: return self.dining() fork2.release() fork1.release() def dining(self): print("%s zaczyna jeść. \n" % self.name) time.sleep(random.uniform(1, 10)) print("%s kończy jeść i zaczyna rozmyślać. \n" % self.name) self.running = False def main(): numPhilosophers = int(input("Dla ilu filozofów przygotować stół? Maksymalnie możemy obsłużyć 10 \n")) forks = [threading.Lock() for n in range(numPhilosophers)] philos = ["Arystoteles", "Kant", "Euler", "Russel", "Monteskiusz", "Hegel", "Hobbes", "Nietzsche", "Wittgenstein", "Shoppenhauer"] philosophers = [Philosopher(philos[i], forks[i % numPhilosophers], forks[(i - 1) % numPhilosophers]) \ for i in range(numPhilosophers)] Philosopher.running = True for p in philosophers: p.start() for p in philosophers: p.join() print("Wszyscy się najedli.") main()
string1 = input() string2 = input() def anagram(s1, s2): all = list(s1+s2) a = list(set(s2) - set(s1)) b = list(set(s1) - set(s2)) c = list(a+b) # removing different char result = list(set(all)-set(c)) return c agr = anagram(string1, string2) ooutput = str(len((agr))) + " # " + "removing " + str(agr) print(ooutput)
#Multiple Linear Regression #Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:,[0,1]].values #now we will have 3 columns as 0,1,2 as index y = dataset.iloc[:,4].values #Encoding the categorical variables #from sklearn.preprocessing import LabelEncoder, OneHotEncoder #labelencoder_X = LabelEncoder() #X[:,3] = labelencoder_X.fit_transform(X[:,3])#we have categorical column as 2 #onehotencoder = OneHotEncoder(categorical_features = [3]) #X = onehotencoder.fit_transform(X).toarray() #Avoiding the dummy variable trap #X = X[:,1:] #Splitting the dataset into training and test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .20,random_state = 0 ) #Fitting the Multiple Linear Regression to the training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) #regressor is fitted to training set #Predicting the Test set results y_pred = regressor.predict(X_test) #using the backward elimination techinique to get best predictor #import statsmodels.formula.api as sm #def backwardElimination(x, sl): # numVars = len(x[0]) # for i in range(0, numVars): # regressor_OLS = sm.OLS(y, x).fit() # maxVar = max(regressor_OLS.pvalues).astype(float) # if maxVar > sl: # for j in range(0, numVars - i): # if (regressor_OLS.pvalues[j].astype(float) == maxVar): # x = np.delete(x, j, 1) # print(regressor_OLS.summary()) # return x # #SL = 0.05 #X_opt = X[:, [0, 1, 2,3]] #X_Modeled = backwardElimination(X_opt, SL) #Backward elimination told us that we need R&D and administration so we will put in X set #I am commenting this backward elimination portion
from numpy import * import numpy as np import matplotlib.pyplot as plt def IP(a, b): if len(a) != len(b): return -1 else: n = len(a) ans = 0 for i in range(n): ans += a[i]*b[i] return ans def steepest(A, b): x = [0 for i in range(len(b))] step = 10 Xaxis = [i for i in range(step+1)] x1 = [0] x2 = [0] y1 = [1]*(step+1) y2 = [2]*(step+1) while step > 0: r = (mat(b).T - mat(A)*mat(x).T).T.tolist()[0] alpha = IP(r, r)/IP((mat(A)*mat(r).T).T.tolist()[0], r) x = (mat(x)+alpha*mat(r)).tolist()[0] x1.append(x[0]) x2.append(x[1]) step-=1 return x
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Solution: def reverse(self, x: int) -> int: if x == 0: return x is_negetive = x < 0 if is_negetive: x = -x new_x = 0 while x: new_x = new_x * 10 + x % 10 x //= 10 if new_x > 2**31: return 0 return -new_x if is_negetive else new_x