text
stringlengths
37
1.41M
import json import re # This functions takes .txt file as input # and returns tweets as a list of json def parse_tweets(tweet_files): twt_data = [] for tweet_file in tweet_files: tweets_file = open(tweet_file, "r") for line in tweets_file: try: tweet = json.loads(line) twt_data.append(tweet) except: continue print('\tSuccessfully parsed data into json format') return twt_data # This function extracts hashtags and urls from tweets data def extract_hashtags_urls(twt_data): # Extract hashtags and urls into separate files htfile = 'hashtags.txt' urlfile = 'urls.txt' htoutfile = open(htfile, 'w',encoding="utf-8") urloutfile = open(urlfile, 'w',encoding="utf-8") for i in range(len(twt_data)): # Extracting hashtags if re.match(r"401", str(twt_data[i])): continue ht = twt_data[i].get('entities').get('hashtags') for j in range(len(ht)): htoutfile.write(ht[j].get('text')) htoutfile.write('\n') # Extracting urls (expanded urls only) url = twt_data[i].get('entities').get('urls') for k in range(len(url)): urloutfile.write(url[k].get('expanded_url')) urloutfile.write(' ') print('\n...............Extraction is done................') # Main Activity if __name__ == '__main__': #Parsing the data print('\n...............Parsing data....................') tweet_files = ["tweets_tech.json", "tweets_tech-1.json", "tweets_tech-2.json"] tweets_data = parse_tweets(tweet_files) #Extracting hashtags and urls print('\n........Extracting hashtags and urls..........') extract_hashtags_urls(tweets_data)
n = 5 arr = [2,3,6,6,5] arr1 = [] [arr1.append(x) for x in arr if x not in arr1] arr1.sort() print(arr1[-2])
from klampt import * from klampt.math import vectorops #attractive force constant attractiveConstant = 100 #repulsive distance repulsiveDistance = 0.1 # repulsive constant - alters the strength of the repulsive force repulsiveConstant = .009; #time step to limit the distance traveled timeStep = 0.01 class Circle: def __init__(self,x=0,y=0,radius=1): self.center = (x,y) self.radius = radius def contains(self,point): return (vectorops.distance(point,self.center) <= self.radius) def distance(self,point): return (vectorops.distance(point,self.center) - self.radius) def force(q,target,obstacles): """Returns the potential field force for a robot at configuration q, trying to reach the given target, with the specified obstacles. Input: - q: a 2D point giving the robot's configuration - robotRadius: the radius of the robot - target: a 2D point giving the robot's target - obstacles: a list of Circle's giving the obstacles """ #basic target-tracking potential field implemented here # calculate the attractive force due to the goal f = vectorops.mul(vectorops.sub(target,q),attractiveConstant) for obstacle in obstacles: dist = obstacle.distance(q); # only add the repulsive force if the obstacle is "within" range if dist > repulsiveDistance: continue magnitude = (1.0/dist - 1/repulsiveDistance); # alter the magnitude to have a repulsiveConstant and to # divide by square of repulsiveDistance # Dividing by the square strengthens the repulsive force # The repuslvieConstant scales the strength of the repulsive force linearly magnitude = repulsiveConstant * magnitude / (dist**2); # set the direction of repulsive force away from the obstacle direction = vectorops.unit(vectorops.sub(q, obstacle.center)); f = vectorops.madd(f, direction, magnitude); #limit the norm of f if vectorops.norm(f) > 1: f = vectorops.unit(f) return f def start(): # Below are the points I tried # They all succeeded # The bottom point is the original #return (.5,0) #return (.2,-.5) #return (-.3,-.5) #return (-0.5,0) #return (-.25,.25) #return (-.1,.5) #return (-.1,.8) #return (-.05,1.3) #return (-.05,.8) return (0.06,0.6) def target(): return (0.94,0.5) def obstacles(): # If I make the circles slightly larger it causes my field # approach to fail, as it discovers the local minima at the # crevasse of the circles # comment the two lines below and uncomment the oringinal obstacles # to get it to work again return [Circle(0.5,0.25,0.24), Circle(0.5,0.75,0.25)] #return [Circle(0.5,0.25,0.2), # Circle(0.5,0.75,0.2)]
s = "Hey there! what should this string be?" print(s, "\n") #Panjang harusnya 20 s = s[:20] print(s) print("panjang dari s = %d" % len(s), "\n") #Huruf pertama 'a' harusnya di index no 8 s = s.replace("there", "thera") print(s) print("Kemunculan a pertama = %d" % s.index("a"), "\n") #Jumlah huruf a seharusnya 2 print("a muncul %d kali" % s.count("a"), "\n") #Memotong string berdasarkan index print("Lima karakter pertama adalah '%s'" % s[:5]) #Start to 5 print("Lima karakter berikutnya adalah '%s' " % s[5:10]) # 5 to 10 print("Karakter ketiga belas adalah '%s' " % s[12]) # 12 print("Karakter dengan indeks ganjil adalah '%s' " % s[1::2]) #(0-based indexing) print("Lima karakter terakhir adalah '%s' " % s[-5:]) # 5th-from-last to end print("\n") #Konverikan ke upercase print("String dalam huruf besar: '%s' " % s.upper()) print("\n") #Konversi ke lowercase print("String dalam huruf kecil: '%s' " % s.lower()) print("\n") #Cek bagaimana string itu dimulai s = s.replace("Hey", "Str") print(s) if s.startswith("Str"): print("String dimulai dengan 'Str'.Good!") #Cek bagaimana string diakhiri print("\n") s = s.replace("shou", "ome!") print(s) if s.endswith("ome!"): print("String diakhiri dengan 'ome!'.Good!") #Pisahkan string menjadi tiga string yang terpisah, #masing-masing hanya berisi satu kata print("\n") print("Pisahkan kata-kata dari string tersebut: '%s' " % s.split(" "))
# Assignment 7.1 - Guilherme Ferreira # Use words.txt as the file name fname = raw_input("Enter file name: ") try: fh = open(fname) except: print "Error: Name of the file invalid!" exit() for line in fh: print line.rstrip().upper()
#!/usr/bin/env python3 def decode_row(data): return binary(0, 127, 'F', 'B', data[:7]) def decode_column(data): return binary(0, 7, 'L', 'R', data[7:]) def getID(row: int, column: int) -> int: return 8 * row + column # def binary_search(lth: int, hth: int, llt: str, hlt: str, data: str) -> int: # lower, higher = lth, hth # for c in data: # middle = (lower + higher) // 2 # if c == llt: # higher = middle # elif c == hlt: # lower = middle # else: # raise Exception(f'Fucked up {c}') # if data[-1] == llt: # return lower # else: # return higher def binary(lth: int, hth: int, llt: str, hlt: str, data: str) -> int: n = 0 for c in data: if c == llt: ... elif c == hlt: n = n | 0x1 else: raise Exception('Foo') n <<= 1 return n >> 1 def main(): with open('input', 'r') as fd: data = [line.strip() for line in fd] dd = [] maxID = 0 for d in data: r = decode_row(d) c = decode_column(d) i = getID(r, c) if i > maxID: maxID = i dd.append({'r': r, 'c': c, 'id': i, 'txt': d}) print('Part1 -> ', maxID) # Part 2 # ids = [e['id'] for e in dd] dd = sorted(dd, key=lambda e: e['id']) print(dd) for i in range(len(dd)-1): if dd[i+1]['id'] - dd[i]['id'] == 2: print('Part2 -> ', dd[i]['id'] + 1) if __name__ == '__main__': main()
import os __author__ = 's.jahreiss' def get_file_list(dir_path, file_extensions): """ Returns a list of all available files in the file system under the specified path with the specified file extensions. :return: All available files in the filesystem with the specified file extensions under the specified file path. """ files = [] for file_name in os.listdir(dir_path): for file_extension in file_extensions: if file_name.endswith(file_extension): files.append(file_name) return files
import random def computer_guess(x): low=1 high =x feedback='' while feedback!='c': guess = random.randint(low, high) print(f"Computer guesses: {guess}") feedback=input("h, c or l").lower() if feedback=='h': high =guess elif feedback=='l': low = guess print(f"Hurray Computer guessed it right which is: {guess}") computer_guess(10)
import sqlite3 conn = sqlite3.connect(':memory:') # Clase conectar BD class Conectar(): # Funcion crear tablas def CrearTablas(self): c = conn.cursor() #Crear tabla de cines c.execute('''CREATE TABLE CINE (id_cine int PRIMARY KEY, nombreCine text )''') # Crear tabla de peliculas c.execute('''CREATE TABLE PELICULA (id_pelicula int PRIMARY KEY, nombrePeli text )''') # Crear tabla de cines con referencia a película c.execute('''CREATE TABLE PELI_CINE (id_cine int, id_pelicula int, PRIMARY KEY (id_cine, id_pelicula), FOREIGN KEY(id_pelicula) REFERENCES PELICULA(id_pelicula) )''') # Crear tabla de funciones c.execute('''CREATE TABLE FUNCION (id_funcion int PRIMARY KEY, id_cine int, id_pelicula, hora int, min int, FOREIGN KEY(id_cine, id_pelicula) REFERENCES PELI_CINE(id_cine, id_pelicula) )''') # Crear tabla de entradas c.execute('''CREATE TABLE ENTRADA (id_entrada INTEGER PRIMARY KEY AUTOINCREMENT, id_funcion int, cantidad int, FOREIGN KEY(id_funcion) REFERENCES FUNCION(id_funcion) )''') # cerrar conexion conn.commit() c.close() # funcion insertar elementos <<<<<<< HEAD def inserts(self): ======= def InsertarE(self): >>>>>>> 0eeae41f4e4a8d18ec59b9cf5fdf34a49ac64ae0 c = conn.cursor() # ingresar cines c.execute("INSERT into CINE values (1,'CinePlaneta')") c.execute("INSERT into CINE values (2,'CineStark')") # ingresar películas c.execute("INSERT into PELICULA values (1,'IT')") c.execute("INSERT into PELICULA values (2,'La hora Final')") c.execute("INSERT into PELICULA values (3,'Desaparecido')") c.execute("INSERT into PELICULA values (4,'Deep el Pulpo')") #ingresar peliculas por cine cinePlaneta c.execute("INSERT into PELI_CINE values (1,1)") c.execute("INSERT into PELI_CINE values (1,2)") c.execute("INSERT into PELI_CINE values (1,3)") c.execute("INSERT into PELI_CINE values (1,4)") #ingresar peliculas por cine cinestark c.execute("INSERT into PELI_CINE values (2,3)") c.execute("INSERT into PELI_CINE values (2,4)") #ingresar funciones de cine Cineplaneta c.execute("INSERT into FUNCION values (1,1,1,19,0)") c.execute("INSERT into FUNCION values (2,1,1,20,30)") c.execute("INSERT into FUNCION values (3,1,1,22,0)") c.execute("INSERT into FUNCION values (4,1,2,21,0)") c.execute("INSERT into FUNCION values (5,1,3,20,0)") c.execute("INSERT into FUNCION values (6,1,3,23,0)") c.execute("INSERT into FUNCION values (7,1,4,16,0)") #ingresar funciones de cine cineStark c.execute("INSERT into FUNCION values (8,2,3,21,0)") c.execute("INSERT into FUNCION values (9,2,3,23,0)") c.execute("INSERT into FUNCION values (10,2,4,16,0)") c.execute("INSERT into FUNCION values (11,2,4,20,0)") c.close() # Funcion listar cines <<<<<<< HEAD def listar_Cines(self): ======= def listarCines(self): >>>>>>> 0eeae41f4e4a8d18ec59b9cf5fdf34a49ac64ae0 c = conn.cursor() c.execute("SELECT * FROM CINE") R = c.fetchall() pass # funcion listar peliculas <<<<<<< HEAD def listar_peliculas(self, id_cine): ======= def listarPeliculas(self, id_cine): >>>>>>> 0eeae41f4e4a8d18ec59b9cf5fdf34a49ac64ae0 c = conn.cursor() c.execute("""SELECT PELICULA.id_pelicula, nombrePeli FROM PELICULA JOIN PELI_CINE ON PELICULA.id_pelicula = PELI_CINE.id_pelicula WHERE id_cine = (?)""", (id_cine,) ) R = c.fetchall() x = [] for r in R: x.append(Pelicula(r[0],r[1])) c.close() return x # funcion listar funciones <<<<<<< HEAD def listar_funciones(self, id_cine, id_pelicula): ======= def listarFunciones(self, id_cine, id_pelicula): >>>>>>> 0eeae41f4e4a8d18ec59b9cf5fdf34a49ac64ae0 c = conn.cursor() c.execute("""SELECT id_funcion, id_cine, id_pelicula, hora, min FROM FUNCION WHERE id_cine = (?) and id_pelicula = (?)""", (id_cine, id_pelicula) ) R = c.fetchall() x = [] for r in R: x.append(Funcion(r[0],r[3],r[4])) c.close() return x #Funcion añadir entrada <<<<<<< HEAD def anadir_entrada(self, id_pelicula, id_funcion, cantidad): ======= def anadirEntrada(self, id_pelicula, id_funcion, cantidad): >>>>>>> 0eeae41f4e4a8d18ec59b9cf5fdf34a49ac64ae0 c = conn.cursor() c.execute("""INSERT INTO ENTRADA(id_funcion, cantidad) VALUES (?, ?)""", (id_funcion, cantidad) ) x = Entrada(c.lastrowid, id_pelicula, id_funcion, cantidad) c.close() return x # funcion listar entradas <<<<<<< HEAD def listar_entradas(self, id_funcion): ======= def listarEntradas(self, id_funcion): >>>>>>> 0eeae41f4e4a8d18ec59b9cf5fdf34a49ac64ae0 c = conn.cursor() c.execute("""SELECT E.id_entrada, F.id_pelicula, E.id_funcion, E.cantidad FROM ENTRADA E JOIN FUNCION F ON E.id_funcion = F.id_funcion WHERE id_funcion = ? """, (id_funcion) ) R = c.fetchall() x = [] for r in R: x.append(Entrada(r[0], r[1], r[2], r[3])) c.close() return x
#1.create a function printstr(str), which takes a string as an argument, and prints it a = "The" b = "Marathon" c = "continues" d= a+ " " + b+ " "+ c print (d)
#2.create a function changedata(mylist), which take a list as argument and changes the values in mylist. Display the contents of the list myBasket = ['apples', 'oranges', 'pineapple'] def changedata(mylist): mylist.append("cherry") mylist.append("kiwi") for item in mylist: print (item) mylist[0] = "Guava" mylist[2] = "pear" for item in mylist: print (item) changedata(myBasket)
# coding=utf-8 import json data = { "id": "10000011", "name": "lichang", "age": 25, "game": { "id": "123456", "type": "poke" }, "family": [ {"role": "father", "age": 50}, {"role": "mather", "age": 49} ] } # 将json字符串解析成python对象 jsonParseBean = json.dumps(data) # 将python对象转换成json字符串 jsonString = json.loads(jsonParseBean) # 解析数据展示 print('before parse, the original data is : ', data) print('after parse ,the data is : ', jsonParseBean) print('after parse, exchange to json again, the data is : ', jsonString)
from buildings import Building class City: def __init__(self, name, mayor, year_est, all_buildings): self.name = name self.mayor = mayor self.year_est = year_est self.all_buildings = list() def new_building(self): self.all_buildings.append() building_1 = Building("101 Avenue", "5") building_2 = Building("102 Avenue", "6") building_3 = Building("103 Avenue", "7") building_4 = Building("104 Avenue", "8") building_5 = Building("105 Avenue", "9")
#!/usr/bin/env python from math import sin from random import gauss # Generates data from a fictional sensor, complete with measurement # noise. def generate_sensor_data(n=1000, noise=0.05): return [sin(x * 0.01) + gauss(0.0, noise) for x in xrange(n)] # Print some sensor data to a file. def print_sensor_data(data, filename): with open(filename, 'w') as f: for i in range(len(data)): f.write('{0}\t{1}\n'.format(i, data[i]))
#!usr/bin/python3 # -*- coding: utf-8 -*- # author zzZ5 ''' python自带的装饰器 ''' # import time # def time_it(func): # # 创建一个时间装饰器, 用于计算函数运行的时间. # def call_func(): # start_time = time.time() # func() # stop_time = time.time() # print("运行时间是{}".format(stop_time-start_time)) # return call_func # # 用@方法的方式使用装饰器 # @time_it # def test(): # print("----test----") # for i in range(1000): # pass # test() ''' 在店里买咖啡, 需要选择咖啡容量(罗老师, 别这样), 选择是否添加牛奶, 摩卡等, 这时就可以使用装饰者模式. ''' class Beverage(): ''' 饮料父类 ''' def __init__(self): self._description = "Unknown beverage" self._cost = 0 def get_description(self): # 获取饮料的描述 return self._description def get_cost(self): # 获取饮料的价格 return self._cost class Condiment(Beverage): ''' 调料父类, 继承自Beverage并不是为了继承行为, 而是为了类型匹配 ''' def get_description(): pass def get_cost(): pass class DarkRoast(Beverage): # 深焙咖啡类, 并初始化描述和价格 def __init__(self): self._description = "DarkRoast" self._cost = 12.5 class Espresso(Beverage): # 浓缩咖啡类, 并初始化描述和价格 def __init__(self): self._description = "Espresso" self._cost = 13.8 class Mocha(Condiment): # 配料摩卡, 并初始化描述和价格 def __init__(self, beverage): self.beverage = beverage self._cost = 2.5 def get_description(self): return self.beverage.get_description() + ", Mocha" def get_cost(self): return round(self.beverage.get_cost() + self._cost, 2) class Whip(Condiment): # 配料奶泡, 并初始化描述和价格 def __init__(self, beverage): self.beverage = beverage self._cost = 1.4 def get_description(self): return self.beverage.get_description() + ", whip" def get_cost(self): return round(self.beverage.get_cost() + self._cost, 2) # 新建一个深焙咖啡, 并添加摩卡和奶泡 beverage1 = DarkRoast() beverage1 = Mocha(beverage1) beverage1 = Whip(beverage1) # 新建一个浓缩咖啡, 并添加两次奶泡 beverage2 = Espresso() beverage2 = Whip(beverage2) beverage2 = Whip(beverage2) print(beverage1.get_description(), " ¥", beverage1.get_cost()) # 输出结果: DarkRoast, Mocha, whip ¥ 16.4 print(beverage2.get_description(), " ¥", beverage2.get_cost()) # 输出结果: Espresso, whip, whip ¥ 16.6
#!usr/bin/python3 # -*- coding: utf-8 -*- # author zzZ5 def singleton(cls): # 函数装饰器实现单例模式 _instance = {} def inner(): if cls not in _instance: _instance[cls] = cls() return _instance[cls] return inner @singleton class Test(): def __init__(self): pass test1 = Test() test2 = Test() print(id(test1) == id(test2)) # =====================================分割线===================================== # class Singleton(): # # 类装饰器实现单例模式 # def __init__(self, cls): # self._cls = cls # self._instance = {} # def __call__(self): # # 类被调用时会触发此方法 # if self._cls not in self._instance: # self._instance[self._cls] = self._cls() # return self._instance[self._cls] # @Singleton # class Test(): # def __init__(self): # pass # test1 = Test() # test2 = Test() # print(id(test1) == id(test2)) # =====================================分割线===================================== # class Singleton(): # # new关键字实现单例模式 # _instance = None # def __new__(cls, *args, **kw): # # 在新建类实例时调用该方法 # if cls._instance is None: # cls._instance = object.__new__(cls, *args, **kw) # return cls._instance # def __init__(self): # pass # singleton1 = Singleton() # singleton2 = Singleton() # print(id(singleton1) == id(singleton2)) # =====================================分割线===================================== # class Singleton(type): # # metaclass实现单例模式 # _instances = {} # def __call__(cls, *args, **kwargs): # if cls not in cls._instances: # cls._instances[cls] = super( # Singleton, cls).__call__(*args, **kwargs) # return cls._instances[cls] # class Test(metaclass=Singleton): # pass # test1 = Test() # test2 = Test() # print(id(test1) == id(test2))
from vec import Vec def list2vec(L): """Given a list L of field elements, return a Vec with domain {0...len(L)-1} whose entry i is L[i] """ return Vec(set(range(len(L))), dict((k,L[k]) for k in range(len(L)))) def zero_vec(D): """Returns a zero vector with the given domain """ return Vec(D, dict())
#!/usr/bin/env python3 def date_fashion(you, date): if you >= 8 and date <= 2 or you <=2 and date >= 8: return 0 elif you >= 8 or date >= 8: return 2 elif you <= 2 or date <= 2: return 0 else: return 1
#!/usr/bin/env python3 def lucky_sum(a, b, c): sum = a + b + c if a == 13: return 0 elif b == 13: return a elif c == 13: return a + b else: return sum
#!/usr/bin/env python3 import math for num in range(1999,3201): if num %7 == 0 and num %5 != 0: print (num, end=',')
# -*- coding: utf-8 -*- """ Created on Sun Mar 17 14:52:28 2019 @author: Carlos """ import os import sys from pathlib import Path import numpy as np import datetime def query_yes_no(question, default="yes"): ''' Ask a yes/no question via raw_input() and return their answer. :param question: is a string that is presented to the user. :param default: is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). :return: True for "yes" or False for "no". ''' valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") def check_overwrite(directory): ''' Checks if file exists: If yes, asks user for overwriting privileges. If user alow overwriting: proceed execution If user deny overwriting: exit program If not, proceed execution. :param directory: string with folder directory path ''' if os.path.isfile(str(Path(directory))): if query_yes_no('File already exists!! Do you wish to ovewrite it?', 'no'): pass else: print('Exiting.......') sys.exit(1) def saveDict(dictObj, dirpath, filename='foo.dat', obs=''): ''' Saves a dictionary in a txt file. Cannot be recovered. If the dict values are arrays, consider using saveDataDict. :param dictObj: dict name :param dirpath: directory to save file as str or Path object from pathlib. :param filename: name of the txt file to save. :param obs: string to add to the header. :return: nothing ''' dirpath = Path(dirpath) file = open(str(Path(dirpath) / filename), 'w') file.write('# ===File generated by filemanip.saveDict()===\n') file.write('# Date: ' + str(datetime.datetime.now()) +'\n') file.write('# Obs.: ' + str(obs) + '\n') try: for i in dictObj: line = '' line += '{0} : {1} \n'.format(i, dictObj[i]) file.write(line) except: print('save failed.') file.close() def saveDataDict(data, dirpath, filename='foo.dat', obs='', header=''): ''' Saves a dict in a txt file. With a header based on the dict keys. :param data: dictionary with data. All dict values must have the save length. :param dirpath: directory to save file as str or Path object from pathlib. :param filename: name of the txt file to save. :param obs: string to add to the header. :param header: string to be used as header. Overwrites auto header generation based on dict keys. :return: nothing ''' dirpath = Path(dirpath) check_overwrite(str(dirpath / filename)) file = open(str(Path(dirpath) / filename), 'w') file.write('# ===File generated by myModules.saveDict===\n') file.write('# Date: ' + str(datetime.datetime.now()) +'\n') file.write('# Obs.: ' + str(obs) + '\n') if header=='': header = '#H ' for i in list(data.keys()): if i == list(data.keys())[-1]: header += str(i) + '\n' else: header += str(i) + ', ' file.write(str(header)) for j in range(0, len(data[max(data, key=len)])): line = '' for i in list(data.keys()): if i == list(data.keys())[-1]: try: line += str(data[i][j]) + '\n' except IndexError: line += '\n' else: try: line += str(data[i][j]) + ', ' except IndexError: line += ', ' file.write(line) file.close() def getDataDict(fullpath): ''' Extract data from file saved by myModules.saveDict. :param fullpath: directory path of the file to read. :return: dictionary with the data (values are numpy arrays). ''' # Get Header file = open(str(Path(fullpath)), 'r') header = file.readline() while header[0:2] != '#H': header = file.readline() header = header[3:-1] # Removes #H and \n header = header.split(', ') # file = open(str(Path(fullpath)), 'r') # line = file.readline() # while line[0] == '#': # line = file.readline() # line = line[:-1] # line.split(', ') # get data data = np.genfromtxt(str(Path(fullpath)), delimiter=',') # return {n:data[:, header.index(n)] for n in header} datadict = dict() for name in header: if np.isin('nan', data[:, header.index(name)]): first_nan = np.where(np.isnan(data[: ,header.index(name)]))[0][0] datadict[name] = data[:first_nan, header.index(name)] else: datadict[name] = data[:, header.index(name)] return datadict def changeFilesName(fileList, separator, values2keep, ask=True): ''' ''' for filePath in fileList: try: a = filePath.name.split('.') ext = a[-1] name = ''.join(a[0:-1]) except: name = filePath.name a = name.split(separator) nameNew ='' for idx in values2keep: nameNew = nameNew + a[idx] + '_' nameNew = nameNew[:-1] + '.' + ext print('OLD NAME = ' + filePath.name) print('NEW NAME = ' + nameNew) print('\n') if not ask: filePath.rename(filePath.parent / nameNew) if ask: y = query_yes_no('Change names?', default="yes") else: print('Files renamed!') return if y or not ask: changeFilesName(fileList, separator, values2keep, ask=False)
# Josh Lim # Comp Sci 30 P4 # 01/09/2020 # File to run code import map from player import Player import action as act import os def intro(): """Function for intro sequence and accepting name""" print("Welcome to escape room") name = input("Name: ").title # gets the name of the player os.system('cls') # clears the terminal return name # returns the name of the player player = Player(intro()) # creates an instance of player class escapeRoom = map.map # sets game map to equal escape escape room arrayMaxX = map.findMax(escapeRoom) + 1 # finds max x arrayMaxY = map.findMax(escapeRoom) # finds max y def play(): """Function to run the game""" # while the player hasn't won nor gave up... while not player.win and not player.giveUp: # sets action flag to false to tell if player has inputed a action or # an invalid input actionFlag = False room = map.tileAt(player.y, player.x) # gets where the player is if player.win is True: # if player won break elif player.giveUp is True: # if player gave up break elif player.turnCounter >= 91: # if player exceeds 91 turns print("You have surpassed 90 turns and ran out of time, you lose") break else: print("Turn " + str(player.turnCounter)) # prints turn counter # highlights the players position on the map map.highlightPos(player.y, player.x, escapeRoom) print("\n" + room.desc + "\n") # prints the tile description # generates available actions availableActions = room.availableActions(arrayMaxX, arrayMaxY) print("What would you like to do? \n") for a in availableActions: # prints out available actions print( "{}: {} \t ".format(a.hotKey[0].title(), a.name.title()), end="" ) # prints actions on a new line if the last key was search if a.name == "search": print("") userIn = input("\nAction: ") # gets the user input os.system('cls') # clears terminal # checks if user input is equal to available actions hot key for a in availableActions: if userIn in a.hotKey: player.turnCounter += 1 # adds one to turn counter action = a # sets the action object to a actionFlag = True # sets the action flag to true # if player enter an invalid input or no input if not actionFlag: print("Invalid input") # if player enter a valid input else: player.doAction(action, room, **a.kwargs) # execute action room.modifyPlayer(player) # modify player play() # plays game
#loops now friends = ["Rolf", "Jen", "Bob", "Anne"] for friend in range(4): print(f"{friends} is my friend.") # grades = [35, 67, 98, 100, 100] total = 0 amount = len(grades) for grade in grades: total += grade print(total / amount)
import itertools def twoNumberSum(array, targetSum): hash_table = {} for xx in range(0,len(array)): for yy in range(1,len(array)): dt = tuple(sorted([array[xx],array[yy]])) if dt in hash_table.keys() or array[xx]==array[yy]: pass else: hash_table[dt] = array[xx]+array[yy] dd = [k for k,v in hash_table.items() if v==targetSum] return(list(itertools.chain(*dd)))
# sumPrimes.py # Author: Joey Willhite # Date: 10/25/2013 import math import time def sumPrimes(maxPrime, dispInc): # A function to calculate the sum of all of the primes below a given number. Used to solve problem 10 suspected=3 primes=[2, suspected] primeSum=5 print('Count:1, Prime Located:2' ) print('Count:2, Prime Located:3' ) multiples=dict() """initially populate multiples list with multiples of 3""" for i in range(3, maxPrime, 3): multiples[i]=1 print('Added multiples of 3 to skip database') """Begin method""" start=time.clock() while suspected<maxPrime: suspected +=2 isComposite=0 try: multiples[suspected] except KeyError: """Otherwise, begin primality testing""" for a in primes: """Check if suspected prime is divisible by any primes less than or equal to the square root of the suspected prim""" if a>=math.sqrt(suspected): break if suspected%a==0: isComposite=1 if not (bool(isComposite)): """If there are no divisible primes, ad the suspected prime to the prime list, and add to the prime sum""" primes.append(suspected) primeSum+=suspected """Also, add any multiples of the newly discovered prime that are less than the maxPrime to the multiples dictionary so that they are not checked for primality""" temp=2 while temp*primes[len(primes)-1]<=maxPrime: multiples[temp*primes[len(primes)-1]]=1 temp+=1 """message printing""" if len(primes)%dispInc==0: print('Count:' +str(len(primes))+ ', Prime Located:' + str(primes[len(primes)-1])) print('Sum:' + str(primeSum)) print('Current Runtime:' +str((time.clock()-start))) print() print('Last suspected prime:' + str(suspected)) print('Total runtime:' + str(time.clock()-start)) print('Total sum:' + str(primeSum))
num = 4 print(num) # complex numbers:first one will be the real part # of the complex number, while the second value # will be the imaginary part. #used to solve quadratic equations that = 0 or #squareroot 0 com = complex(10, -2) print(com) #finding the length of a string str = 'a string' print(len(str)) #accessing characters in a string name = 'monika angel' #getting the first character first = name[0] print(first) #getting the last character last = name[0-1] print(last) #gets last character in string print(name[-1]) #maybe we can #create a for loop that reverses everything # if we substitute the 1 w an i and increase print(name[-12]) newstr = "this-is-a-string" print(newstr[0:4]) #slices to only have 'this' print(newstr[8:len(newstr)]) # prints everything from beginning to the end by # getting the string length #[start:end:step] print("Skipping splits") print(newstr[0:5]) print(newstr[0:5:2]) print(newstr[0:5:4]) #reversing a string #if we reverse a string we switch the start and end indices print(newstr[len(newstr):0:-1]) #to print the whole string we do print(newstr[:]) #to reverse the whole string we do print(newstr[::-1]) #we can do floor division which gets you the smallest float integer print(5.5//4.5) #is checks if two things are the same objects #and is not check if theyre not x = ["apple", "banana", "cherry"] y = x print(x is y) #= Assign #+= Add #-= Subtract #*= Multiply #/= Divide #//= Divide, Floor #**= Raise power #%= Take Modulo #|= OR #&= AND #^= XOR #>>= Right-shift #<<= Left-shift
#1 первый способ list def printMat(a, n, m): for i in range(n): for k in range(m): print(a[i][k], end = "\t") print() a = [] n = int(input('n = ')) m = int(input('m = ')) for i in range(n): a.append([]) for j in range(m): a[i].append(int(input('Enter element: '))) b = [] while(True): n1 = int(input('n1 = ')) m1 = int(input('m1 = ')) if(n1 == n): break else: print("Invalid data! Try again") for i in range(n1): b.append([]) for j in range(m1): b[i].append(int(input('Enter element: '))) print("Initial matrix 1:") printMat(a, n, m) print("\nInitial matrix 2:") printMat(b, n1, m1) for i in range(n): for k in range(m1): a[i].append(b[i][k]) print("\nResult: ") printMat(a, n, m + m1)
def f(x): if(x % 5 == 0): return x / 5 else: return x + 1 n = float(input("Enter value = ")) print(f(n))
print("Enter set1 : ") set1 = set([int(x) for x in input().split()]) print("set1 : ",set1) print("Enter set2 : ") set2 = set([int(x) for x in input().split()]) print("set2 : ",set2) res = set1.intersection(set2) s = sum(res) print("\nintersection : ", res, "\nSum : ",s)
from tkinter import * class App: def __init__(self): self.master = Tk() self.master.wm_title("Entry Name") # Text field storing text details self.text_field = Entry(self.master) self.text_field.pack() self.text_field.focus_set() self.text_value = None # button grabbing the text value accept = Button(self.master, text="Ok", fg="red", width=10, command=self.grab_value) accept.pack() self.master.mainloop() # Fetch text entry def grab_value(self): self.text_value = self.text_field.get() self.master.destroy()
import pygame pygame.init() screenwidth=int(input("Enter the screen size in pixels : ")) win= pygame.display.set_mode((screenwidth,screenwidth)) caption=pygame.display.set_caption("Basic Movements") x=250 y=250 width=50 height=20 vel=10 run=True while run: pygame.time.delay(100) for event in pygame.event.get(): if event.type==pygame.QUIT: run=False keys=pygame.key.get_pressed() if keys[pygame.K_LEFT] and x>vel: x-=vel if keys[pygame.K_RIGHT] and x<screenwidth-width-vel: x+=vel if keys[pygame.K_UP] and y>vel: y-=vel if keys[pygame.K_DOWN] and y<screenwidth-height-vel: y+=vel win.fill((0,0,0)) pygame.draw.rect(win,(255,0,0),(x,y,width,height)) pygame.display.update() pygame.quit()
#!/usr/bin/python3 matrix = [] for i in range(len(matrix)): for j in range(len(matrix[i])): print('matrix[{}][{}] = {}'.format(i, j, matrix[i][j])) for i, row in enumerate(matrix): for j, col in enumerate(row): print('matrix[{}][{}] = {}'.format(i, j, col))
from math import sqrt number = 0 for i in range(10): number = i ** 2 if i % 2 == 0: continue # continue here print(str(round(sqrt(number))) + ' squared is equal to ' + str(number))
from dataclasses import dataclass """ Since version 3.7, Python offers data classes. There are several advantages over regular classes or other alternatives like returning multiple values or dictionaries: - a data class requires a minimal amount of code - you can compare data classes because __eq__ is implemented for you - you can easily print a data class for debugging because __repr__ is implemented as well - data classes require type hints, reduced the chances of bugs """ @dataclass class Card: rank: str suit: str card = Card("Q", "hearts") print(card == card) # True print(card.rank) # 'Q' print(card) Card(rank='Q', suit='hearts')
""" def get_secret_code(password): if password != "bicycle": return None else: return "42" secret_code = get_secret_code("unicycle") if secret_code is None: print("Wrong password.") else: print("The secret code is {}".format(secret_code)) """ def get_secret_code(password): if password != "bicycle": raise ValueError else: return "42" try: secret_code = get_secret_code("unicycle") print("The secret code is {}".format(secret_code)) except ValueError: print("Wrong password.")
name = "Jeremy" age = 25 # String formatting using concatenation print("My name is " + name + ", and I am " + str(age) + " years old.") # String formatting using multiple prints print("My name is ", end="") print(name, end="") print(", and I am ", end="") print(age, end="") print(" years old.") # String formatting using join print(''.join(["My name is ", name, ", and I am ", str(age), " years old"])) # String formatting using modulus operator print("My name is %s, and I am %d years old." % (name, age)) # String formatting using format function with ordered parameters print("My name is {}, and I am {} years old".format(name, age)) # String formatting using format function with named parameters print("My name is {n}, and I am {a} years old".format(a=age, n=name)) # String formatting using f-Strings (Python 3.6+) print(f"My name is {name}, and I am {age} years old")
original_list = [1, 2, 3, 4, 5] def square(number): return number ** 2 squares = map(square, original_list) squares_list = list(squares) print(squares) # Returns [1, 4, 9, 16, 25]
from functools import cmp_to_key import locale my_list = ["leaf", "cherry", "fish"] # Brute force method using bubble sort my_list = ["leaf", "cherry", "fish"] size = len(my_list) for i in range(size): for j in range(size): if my_list[i] < my_list[j]: temp = my_list[i] my_list[i] = my_list[j] my_list[j] = temp # Generic list sort *fastest* my_list.sort() # Casefold list sort my_list.sort(key=str.casefold) # Generic list sorted my_list = sorted(my_list) # Custom list sort using casefold (>= Python 3.3) my_list = sorted(my_list, key=str.casefold) # Custom list sort using current locale my_list = sorted(my_list, key=cmp_to_key(locale.strcoll)) # Custom reverse list sort using casefold (>= Python 3.3) my_list = sorted(my_list, key=str.casefold, reverse=True)
another_str = "The * operator" # Using a list outside the unpacking var2 = [*another_str] print(type(var2)) # List # Using a tuple # Tuples ends with a comma var3 = (*another_str,) print(type(var3)) # Tuple
import os folder = '.' filepaths = [os.path.join(folder, f) for f in os.listdir(folder)] print(filepaths) # os.scandir() function (available for Python >= 3.5 or with the scandir module) filepaths = [f.path for f in os.scandir('.') if f.is_file()] dirpaths = [f.path for f in os.scandir('.') if f.is_dir()] print(filepaths) print(dirpaths)
l = [1, 2, 3] magic_number = 4 for n in l: if n == magic_number: print("Magic number found") break else: print("Magic number not found")
import operator people = [ {'name': 'John', "age": 64}, {'name': 'Janet', "age": 34}, {'name': 'Ed', "age": 24}, {'name': 'Sara', "age": 64}, {'name': 'John', "age": 32}, {'name': 'Jane', "age": 34}, {'name': 'John', "age": 99}, ] people.sort(key=operator.itemgetter('age')) people.sort(key=operator.itemgetter('name')) print(people)
x = range(5) print(x) print(type(x)) l = list(range(5, 20, 3)) print(l) for n in x: print(n) t = tuple(x) print(t) l2 = list(range(5, 20, 3)) print(l2) print(list(range(5, 10, 1))) print(list(range(5, 10))) print(list(range(-5, 5))) print(list(range(5, -5))) print(list(range(5, -5, -1)))
from collections import Counter myList = [1, 1, 2, 3, 4, 5, 3, 2, 3, 4, 2, 1, 2, 3] print(Counter(myList))
def print_each_item(items): # check whether items is an Iterable try: iter(items) except TypeError as e: raise ( TypeError( f"'items' should be iterable but is of type: {type(items)}") .with_traceback(e.__traceback__) ) # if items is iterable, check whether it contains items else: if items: for item in items: print(item) # if items doesn't contain any items, raise a ValueError else: raise ValueError("'items' should not be empty")
class Square(object): def __init__(self, length): self._length = length @property def length(self): return self._length @length.setter def length(self, value): self._length = value @length.deleter def length(self): del self._length r = Square(5) r.length # automatically calls getter r.length = 6 # automatically calls setter
import numpy as np print(np.random.rand(10)) # array print(np.random.rand(3, 4)) # 3x4 matrix # To generate random numbers in a normal distribution, use the randn() function from np.random: print(np.random.randn(10)) print(np.random.randn(3, 4)) # To generate random integers between a low and high value, use the randint() function from np.random: print(np.random.randint(1, 100, 10)) print(np.random.randint(1, 100, (2, 3))) # To set a seed value in NumPy, do the following: np.random.seed(42) print(np.random.rand(4))
# -*- coding: utf-8 -*- """ Created on Sun Mar 8 16:52:51 2020 @author: Max """ import pandas as pd def data_fill_from_df(data,fill_table,data_id): """like vlookup, try to fill a table with another table as a reference""" for index, row in fill_table.iterrows(): for col in fill_table.columns[1:]: data[col][data[data_id]==row[0]]=row[col] return data def fillna_with_preced_record(table,col,order_col): new_
# UI TEXT STRINGS -- TODO WRITE FOR DIFFERENT LANGUAGES # TODO - organize these so they aren't random lists / strings, and instead consolidated in some dictionaries or something PURPOSES_OF_PACKAGE_TUTORIAL_STEP = [ "Let's talk about what we can do with this package.", "* We can get a 'mask' of the current moon phase", "* We can use this mask to create an image of the current moon phase.", "* We can save this image as is.", "* We can get custom images from outside sources, like urls, files, or instagram posts.", "* We can use these images as masks together with the mask we got from the moonphase, and create collages." ] IMPORT_CLASS_TUTORIAL_STEP = [ "To use this package, it needs to be imported into wherever we're running it. Considering you're already running this tutorial, you've probably already imported it in one way or another.", "So, the first line in your code should read:", "{}", "This import statement imports a class called MoonMaskUI, which is what we'll use to interact with the package.", ] INITIALIZE_UI_TUTORIAL_STEP = [ "Now that we have the class MoonMaskUI imported, let's use it. We do this like this:", "{}", "This code makes a new variable, which we're choosing to call 'ui', and sets it equal to an instance of our class.", "Now, we will be able to use this variable 'ui' to make an image." ] SET_MOON_PHASE_TUTORIAL_STEP = [ "Since we're here to get the moonphase, let's start there. To get the current moonphase, we call a method 'set_moon_phase' on our ui.", "{}", "This method will ask for current moon phase from the nasa repository of images, and use it to create a mask, which will later be used to make an image.", ] INTRO_SAVE_COLLAGE_TUTORIAL_STEP = ["Now that we've set the moonphase mask, let's see what it looks like when transformed to an image.", "We will try this command:", "{}", "This method will make an image and (depending on how we're running this script) show it to us." ] SET_POSITIVE_SPACE_TUTORIAL_STEP = [ "Now, let's try customizing this moonphase image a bit. Let's change the positive space in the moon.", "Take a look at the little sketch above for what part we are considering the 'positive space' in an image of a full moon.", "Now, we change this positive space to having a yellow color like this:", "{}" ] SET_POSITIVE_SPACE_COMMAND = "ui.set_positive_space(color='yellow')" #TODO set command_prompt icons for these command2-4 in the way you're setting the others SET_POSITIVE_SPACE_COMMAND2 = ">> ui.set_positive_space(url='https://upload.wikimedia.org/wikipedia/en/2/27/Bliss_%28Windows_XP%29.png')" SET_POSITIVE_SPACE_COMMAND3 = ">> ui.set_positive_space(instagram_url='https://www.instagram.com/p/Bjo2ftsH2KC/')" SET_POSITIVE_SPACE_COMMAND4 = ">> ui.set_positive_space(filename='i_am_not_a_real_file.jpg')" LETS_SAVE_TUTORIAL_STEP = [ "Let's save this to take a look at it.", "{}" ] SET_NEGATIVE_SPACE_TUTORIAL_STEP = [ "Now let's change the negative space to yellow with this command:", "Take a look at the little sketch above for what part we are considering the 'negative space' in an image of a full moon.", "{}" ] SET_MAIN_IMAGE_TUTORIAL_STEP = [ "Finally, let's change the 'main image' here. The 'main image' is what these masks are being 'pasted' onto.", "We change the main image like this:", "{}", "We are using a different way of declaring the color here -- it's in 'RGB' format." ] MORE_INFO = [ "In this tutorial, we only changed the colors of the positive space, negative space, and main image.", "We used the keyword argument 'color' to do this, like ", "{}", "To use images instead of colors, we can use different keyword arguments, like 'url', 'instagram_url', and 'filename'.", "For example:", SET_POSITIVE_SPACE_COMMAND2, SET_POSITIVE_SPACE_COMMAND3, SET_POSITIVE_SPACE_COMMAND4, "If you'd like to play around with these different keyword arguments, please give it a try outside of this tutorial!" ] SET_NEGATIVE_SPACE_COMMAND = "ui.set_negative_space(color='yellow')" SET_MAIN_IMAGE_COMMAND = "ui.set_main_image(color=(240, 128, 128))" SAVE_COLLAGE_COMMAND = "ui.save_collage(filename='moon')" TUTORIAL_PROMPT_FOR_COMMAND = "Type out the command from above (the command after '>>>'. For this tutorial, you'll have to exactly match it. If you get stuck and need to exit, remember that ctrl-c will get you out of this tutorial." TUTORIAL_TRY_AGAIN_PROMPT = "That doesn't match '{}', please try again:" SET_MOON_PHASE_COMMAND = "ui.set_moon_phase()" IMPORT_UI_COMMAND = "from moonmask.moonmask_ui import MoonMaskUI" INITIALIZE_UI_COMMAND = "ui = MoonMaskUI()" THIS_IS_A_TUTORIAL_MESSAGE = "This is a small tutorial on how to use it. For more info on this package, please head over to https://github.com/spacerest/moonmask/README.md" FINISHED_TUTORIAL_MESSAGE = "Well, this is the end of the moonmask tutorial! For more info on this package, please head over to https://github.com/spacerest/moonmask/README.md. If anything isn't working, please submit an issue on github. Thanks! :)" NAVIGATION_REMINDER = "To exit this tutorial you can press ctrl-C at any time. To go back in the tutorial you can scroll up ^." USER_SUCCESS_MESSAGE = "Nice :)" CREDITS_LIST = ["Thanks to Ernie Wright of Nasa for creating the moon visualizations that the generated moon masks are based on. Check out his visualizations here: https://svs.gsfc.nasa.gov/cgi-bin/search.cgi?person=105 ","Thanks to Joan Stark for the ascii art used in this tutorial. I read a nice interview by her here: http://www.lastplace.com/ASCIIart/starkascii.htm.", "If you'd like to help on this project and get added to this credits list, please contact me <3 (my github username is spacerest)"] SHOW_INFO = "Welcome to moonmask! You can use this package to get a 'mask' of the moonphase for a particular day. You can use this mask to create an image of the current moon phase, or to make a collage using your own photos." PRESS_ENTER_TO_CONTINUE = "(Please press enter to continue...)" SAVE_COLLAGE_CONFIRMATION = "If you're running this tutorial locally, a sample image of your collage should have opened up just now. If you're running this tutorial on an online repl like repl.it, then you won't see any image until the end of the tutorial. Anyway, if an image opened up, it is a temporary file that has just opened up to show you what the current image looks like. There should also be a saved version of the image by this name: " OVERWRITE_FILENAME_NOTICE = "Since you haven't specified a different filename, it will be saved as '{}.jpg'. If you already have a file called '{}.jpg', this will probably overwrite your original file." HOW_TO_NAME_FILENAME = "To specify a unique filename, you can write filename='mycustomfilename' in the arguments of your method call. For example: ui.save_collage(filename='mycustomfilename') will save a file called 'mycustomfilename.jpg'" CANCEL_OPTION = "If you'd like to cancel this operation and knowing what you know now, type 'c' and then press enter. Otherwise, just press enter." WHITESPACE = "\n" CANCEL_CONFIRMATION = "You've requested to cancel, so the method you called will not be completed as dialed." PROMPT_FOR_USERNAME = "Please enter your instagram username here and then press enter:\n\n" PROMPT_FOR_PASSWORD = "Please enter your instagram password below and then press enter (don't worry that the cursor doesn't move while you type):\n\n" SET_POSITIVE_SPACE_CONFIRMATION = "You have updated the positive space in your collage." SET_MAIN_IMAGE_CONFIRMATION = "You have updated the main image in your collage." SET_MOON_PHASE_CONFIRMATION = "You have set a moonphase for the date: " SET_NEGATIVE_SPACE_CONFIRMATION = "You have updated the negative space in your collage." SIGNING_INTO_INSTAGRAM_WARNING = "Some notes about this: In how this package is currently set up, you need to type your username and password in the command line to log into Instagram. Do this at your own risk... As a general rule of thumb, it's obviously not good to type your passwords just anywhere. If you want a more secure way of getting your photo to instagram, just email the file to yourself to get it to your phone." INSTAGRAM_BOT_WARNING = "Another note: This package uses a python package called InstagramAPI that isn't officially approved by Instagram. Using it may violate terms of service with Instagram, and you might run into some issues 'verifying' your login." INSTAGRAM_BRAND_GROWTH_RAMBLE= "A last note: Instagram doesn't like 3rd party API packages like this, since they're often used to automate accounts to create brand growth (and because bots can be annoying when used in certain ways). By using this InstagramAPI package, you *may* be violating some Instagram rules." SAVING_INSTAGRAM_SESSION_MESSAGE = "Would you like to save your instagram login for next time? This means that your instagram information (including your username and password and the 'object' that is your instagram account information), will be saved so that you don't need to login next time." PROMPT_FOR_INSTAGRAM_CAPTION = "If you would like to include a caption with this post, please type it below and press enter. If you don't want one, just type nothing and press enter." INSTAGRAM_POST_FINAL_CHECK = "OK, you're about to try to post your collage to instagram. You'll probably see some messages from the InstagramAPI package here (like 429 and 404 errors). You can probably ignore those, but if something ends up not working, they could be clues as to why the post didn't work.\n\nIf you'd like to go ahead and try to post your image to instagram, type 'y' and press enter. Otherwise, just press enter to cancel.\n\n" INSTAGRAM_POST_ATTEMPT_CONFIRMATION = "If you didn't see any major errors, then your picture must have posted to instagram! Check you account. If there *were* issues, don't worry too much about it and just email your picture to yourself if you'd like to post it somewhere." SKIP_TEXT_MATCH = "pass"
# Time Complexity : O(M * N) # Space Complexity : O(M * N) # Did this code successfully run on Leetcode : YES # Any problem you faced while coding this : Logic class Solution: def findDiagonalOrder(self, matrix): if (matrix == [] or len(matrix) == 0): return [] m = len(matrix) n = len(matrix[0]) i = 0; r = 0; c = 0 direction = 1 result = [] while i < m*n: result.append(matrix[r][c]) # entering the traversed value to the resultant list if direction == 1: if c == n -1: # at last column r = r + 1 direction = -1 elif r == 0: # at First row c = c + 1 direction = -1 else: r = r - 1 c = c + 1 else: if r == m-1: # at Last row c = c + 1 direction = 1 elif c == 0: # at First column r = r + 1 direction = 1 else: r = r + 1 c = c - 1 i += 1 return result matrix = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] output = Solution() print(output.findDiagonalOrder(matrix))
#-*- coding:utf-8 -*- ##在命令行中运行python,粘贴下面三段以导入 # import sys # sys.path.append('/home/vetains/pywork/pycore') # import chapter13 as c13 # class C(object): # '''a class''' # def __init__(self): # pass # def A(self): # print 'a' # # c=C() # print C.__class__ # class P(object): # def __init__(self): # print 'this is P' # class C(P): # def __init__(self): # P.__init__(self) # print 'this is C' # # class C(P): # def __init__(self): # super(C,self).__init__() #super()方法不需要知道父类 # print 'this is C' # c=C() # class RoundFloat(float): # def __new__(cls,val): # return float.__new__(cls,round(val,2)) # class RoundFloat(float): # def __new__(cls,val): # return super(RoundFloat,cls).__new__(cls,round(val,2)) # # #经典类的多重继承MRO # class P1: # def foo(self): # print 'P1-foo()' # # class P2: # def foo(self): # print 'P2-foo()' # def bar(self): # print 'P2-bar()' # # class C1(P1,P2): # pass # # class C2(P1,P2): # def bar(self): # print 'C2-bar()' # # class GC(C1,C2): # pass # # gc=GC() # gc.foo() #P1-foo() # gc.bar() #P2-bar(),略过了C2的bar(),深度优先 # #新式类的多重继承MRO # class P1(object): # def foo(self): # print 'P1-foo()' # # class P2(object): # def foo(self): # print 'P2-foo()' # def bar(self): # print 'P2-bar()' # # class C1(P1,P2): # pass # # class C2(P1,P2): # def bar(self): # print 'C2-bar()' # # class GC(C1,C2): # pass # # gc=GC() # gc.foo() #P1-foo() # gc.bar() #C2-bar() 广度优先 # #hasattr(),getattr(),setattr(),delattr() # class myClass(object): # def __init__(self): # self.foo=42 # # mc=myClass() # print hasattr(mc,'foo') # print getattr(mc,'foo') # # print getattr(mc,'bar') #getattr()不存在的属性会报错 # setattr(mc,'bar','64') #setattr(实例,属性,值)增加一个属性和对应的值 # print dir(mc) #检查实例mc里的属性,已经多出例'bar' # print getattr(mc,'bar') # mc2=myClass() # print hasattr(mc2,'bar') #在另一个实例里并没有属性'bar',说明上一步的set只是实例属性 # delattr(mc,'foo') # print hasattr(mc,'foo') # print hasattr(mc2,'foo') #mc2里仍有'foo',所以delattr也只是删除该实例的属性 # #RoundFloatManual # class RFM(object): # def __init__(self,val): # assert isinstance(val,float),'value must be float' # self.value=round(val,2) # # def ___str__(self): #未赋值给__repr__时,只有print时才能显示结果 # return '%.2f'%self.value # # __repr__=___str__ #赋值给__repr__后,直接调用实例也能返回结果 # #Time60 # class Time60(object): # 'calculate hours and minutes' # def __init__(self,h,m): # self.hour=h # self.min=m # # def ___str__(self): # return '%d : %d'%(self.hour,self.min) # # __repr__=___str__ # # def __add__(self,other): # '处理了分钟数大于60的情况' # if self.min+other.min>=60: # return self.__class__(self.hour+other.hour+1,self.min+other.min-60) # else: # return self.__class__(self.hour+other.hour,self.min+other.min) # # def __iadd__(self,other): # if self.min+other.min>=60: # self.hour=self.hour+other.hour+1 # self.min=self.min+other.min-60 # else: # self.hour+=other.hour # self.min++other.min # return self # #RandSeq.py # from random import choice # # class RandSeq(object): # def __init__(self,seq): # self.data=seq # # def __iter__(self): # return self # # def next(self): # return choice(self.data) # #anyIter.py # class AnyIter(object): # def __init__(self,data,safe=False): # self.safe=safe # self.iter=iter(data) #iter(data)返回一个迭代器 # # def __iter__(self): # return self # # def next(self,howmany=1): # retval=[] # for eachitem in range(howmany): # try: # retval.append(self.iter.next()) # except StopIteration: # if self.safe: # break # else: # raise # return retval # #多类型类定制 # class NumStr(object): # def __init__(self,Num=0,Str=''): # self.__num=Num # self.__str=Str # # def __str__(self): # # return '[%d :: %s]'%(self.__num,self.__str) #使用%s会没有单引号 如[1 :: abc] # return '[%d :: %r]'%(self.__num,self.__str) #使用%r会有单引号 [1 :: 'abc'] # # __repr__=__str__ # # def __add__(self,other): # if isinstance(other,NumStr): # return self.__class__(self.__num+other.__num,self.___str+other.__str) # else: # raise TypeError,'should add an object in same class' # # def __mul__(self,num): # if isinstance(num,int): # return self.__class__(num*self.__num,num*self.__str) # else: # raise TypeError,'should mul an int number' # # def __nonzero__(self): # return self.__num or len(self.__str) #实例为默认值时返回0?False值 # # def _norm_cval(self,cmpres): # 接受cmp()result 为参数 # return cmp(cmpres,0) #cmp()策略为:cmp(数字)+cmp(字符串)=和,再将cmp(和,0) # # def __cmp__(self,other): # if isinstance(other,NumStr): # return self._norm_cval(cmp(self.__num,other.__num)+cmp(self.__str,other.__str)) # else: # raise TypeError,'should compare the same class object' # #包装与授权 # class Wrap(object): # def __init__(self,obj): # self.__data=obj # def get(self): # return self.__data # def __repr__(self): # return str(self.__data) # def __str__(self): # return str(self.__data) # def __getattr__(self,attr): # return getattr(self.__data,attr) # #包装标准类型 # from time import time,ctime # # class timeWrapme(object): # '''ctime:创建时间,mtime:修改时间,atime:访问时间''' # # def __init__(self,obj): # '''包装初始化,获得对象并记录时间''' # self.__data=obj # self.__ctime=self.__mtime=self.__atime=time() # # def get(self): # '''获取对象实体,更改访问时间''' # self.__atime=time() # return self.data # # def gettimeval(self,t_type): # '''获取'cma'中的某个时间的值''' # if not isinstance(t_type,str) or t_type[0] not in 'cma': # raise TypeError,'只能访问 [c]创建时间,[m]修改时间,[a]访问时间' # else: # print self,'_%s__%stime'%(self.__class__.__name__,t_type[0]) # return getattr(self,\ # '_%s__%stime'%(self.__class__.__name__,t_type[0])) # # def gettimestr(self,t_type): # '''获取时间的字符串''' # return ctime(self.gettimeval(t_type)) # # def set(self,obj): # '''修改,更新修改时间和访问时间''' # self.__mtime=self.__atiem=time() # self.__data=obj # # def __repr__(self): # '''访问,更新访问时间''' # self.__atime=time() # return str(self.__data) # # def __str__(self): # '''访问,更新访问时间''' # self.__atime=time() # return str(self.__data) # # def __getattr__(self,attr): # '''运用属性,更新访问时间''' # self.__atime=time() # return getattr(self.__data,attr) # # l=[1,2,3] # tw=timeWrapme(l) # print tw.gettimestr('c') # #描述符-使用文件来存储属性 # import os,pickle # # class FileDescr(object): # saved=[] # # def __init__(self,name=None): # self.name=name # # def __get__(self,obj,typ=None): # if self.name not in FileDescr.saved: # raise AttributeError,'%r used before assignment'%self.name # # try: # f=open(self.name,'r') # val=pickle.load(f) # f.close() # return val # except (pickle.UnpicklingError,IOError,EOFError,AttributeError,IndexError),e: # raise AttributeError,'could not read %r'%self.name # # def __set__(self,obj,val): # f=open(self.name,'w') # try: # pickle.dump(val,f) # FileDescr.saved.append(self.name) # except (TypeError,pickle.PicklingError),e: # raise AttributeError,'could not pickle %r'%self.name # finally: # f.close() # # def __delete__(self,obj): # try: # os.unlink(self.name) # FileDescr.saved.remove(self.name) # except (OSError,ValueError),e: # pass # # class m(object): # foo=FileDescr('foo') # bar=FileDescr('bar') #不懂pickle,例子意义不明 #property()内建函数 # class PX(object): # def __init__(self,x): # self.__x=~x # # def get_x(self): # return ~self.__x # # x=property(get_x) # # class HideX(object): # def __init__(self,x): # self.__x=x # # def get_x(self): # return ~self.__x # # def set_x(self,x): # self.__x=~x # # x=property(get_x,set_x) # '''property(fget,fset,fdel,fdoc),因而默认第一个参数为fget,以此类推. # 所以调用属性会自动执行get_x,设置属性会自动执行set_x''' # # #HideX 类里的方法还可以采用修饰符@property的方式 # class HideX1(object): # def __init__(self,x): # self.__x=x # # @property # def x(): # def fget(self): # return ~self.__x # # def fset(self): # self.__x=~x # # return locals() #locals()函数返回一个包含所有函数方法名和对应对象的字典 # #元类示例 # from warnings import warn # # class ReqStrSugRepr(type): #需要__str__ 建议__repr__ # def __init__(cls,name,bases,attrd): # super(ReqStrSugRepr,cls).__init__(name,bases,attrd) # # if '__str__' not in attrd: # raise TypeError("Class requires overriding of __str__()") # # if '__repr__' not in attrd: # warn("Class suggests overriding of __repr__\n",stacklevel=3) # # print '***Defined ReqStrSugRepr (meta)class\n' # # class Foo(object): # __meatclass__=ReqStrSugRepr # # def __str__(self): # return 'Instance of class',self.__class__.__name__ # # def __repr__(self): # return self.__class__.__name__ # # print '***Defined Foo class\n' # # class Bar(object): # __metaclass__=ReqStrSugRepr # # def __str__(self): # return 'Instance of class',self.__class__.__name__ # # print '***Defined Bar class\n' # # class FooBar(object): # __metaclass__=ReqStrSugRepr # # print '***Defined FooBar class\n' # # 13-3 类定制 # #dollarize()函数 # def dollarize(money): # '''返回美元字符串,两位小数,支持千位逗号,以及$前负号''' # if not isinstance(money,float) and not isinstance(money,int): # raise TypeError,'输入浮点数或整型' # # roundNum=round(money,2) #约数 # intStr=str(roundNum).split('.')[0] #获取约数的整数部分 # floatStr=str(roundNum).split('.')[1] #约数的小数部分 # # #千位逗号 # intStrList_R=[i for i in reversed(list(intStr))] #整数部分字符串的倒序列表 # # if roundNum<0: # intStrList_R.remove('-') # '''除去负号,负号对千位逗号有干扰 # 负号增加了列表长度,使得 -,123,123 的情况出现''' # # i=3 #第一个逗号在倒序列表的第三个索引位,此后为7,11,15...每次+4 # while i<len(intStrList_R): #一直到i超出了整数字符串的长度 # intStrList_R.insert(i,',') # i+=4 # intStrList_R.reverse() # intStr=''.join(intStrList_R) # # if len(floatStr) is 1: #如果小数部分只剩一位,则补加一个0 # floatStr=floatStr+'0' # # if not roundNum<0: # return '$'+intStr+'.'+floatStr # else: # return '-$'+intStr+'.'+floatStr #上端列表已经省略intStr的负号 # # # print dollarize(-11.95555555557) # # class MoneyFmt(object): # def __init__(self,money,special=False): # if not isinstance(money,int) and not isinstance(money,float): # raise TypeError,'参数为整型或浮点型' # else: # self.money=money # self.special=special # # def update(self,anotherMoney): # if not isinstance(anotherMoney,int) and not isinstance(anotherMoney,float): # raise TypeError,'参数为整型或浮点型' # else: # self.money=anotherMoney # # def __nonzero__(self): # #return self.money #所以是返回数值还是返回布尔值? # '''答:这个直接返回数值,但__nonzer__只接受布尔值或整型返回, # 所以让它返回布尔值就好''' # return bool(self.money) # # def __repr__(self): # if not self.money<0: # return '$'+str(self.money) # else: # return '-$'+str(self.money)[1:] # # def __str__(self): # '''print时显示处理过的形式,解释在上方dollarize()函数中''' # roundNum=round(self.money,2) # intStr=str(roundNum).split('.')[0] # floatStr=str(roundNum).split('.')[1] # # intStrList_R=[i for i in reversed(list(intStr))] # # if roundNum<0: # intStrList_R.remove('-') # # i=3 # while i<len(intStrList_R): # intStrList_R.insert(i,',') # i+=4 # intStrList_R.reverse() # intStr=''.join(intStrList_R) # # if len(floatStr) is 1: # floatStr=floatStr+'0' # # if not roundNum<0: # return '$'+intStr+'.'+floatStr # else: # if not self.special: #self.special==False时 # return '-$'+intStr+'.'+floatStr # else: #self.special==True时 # return '<-$'+intStr+'.'+floatStr+'>' # #千位逗号的,数学方法的,另一种实现 # def douHao(num): # douNums=len(str(int(num)))/3 #判断逗号的个数 # if len(str(int(num)))%3==0: #如果数字长度为3的倍数,逗号个数会少一个 # douNums-=1 # # floatStr='' # if isinstance(num,float): #如果是浮点数,要把小数部分摘出来 # floatStr='.'+str(num).split('.')[1] # num=int(num) #只处理整数部分 # # result='' # for i in range(douNums+1)[::-1]: #假如douNum是3,列表应为[3,2,1,0] # # newStr=str(num/(1000**i)) #1500/1000=1 得到'1,' # if i!=0: # newStr=newStr+',' # # result+=newStr # num=num%(1000**i) #继续处理1500%1000=500 # # return result+floatStr # # print douHao(123456.89) # #13-4 用户注册 # import shelve # import wx # from time import ctime,time # import sys # # class My_DB(object): # '''数据库类,在实例化操作时加载已经保存的用户信息,提供访问函数来添加或更新数据库信息. # 数据修改后,数据库会在垃圾回收时将新信息保存到磁盘''' # def __init__(self,name): # self.db=shelve.\ # open('/home/vetains/pywork/pycore/chapter13.dat') #打开数据库 # self.name=name # if self.name in self.db.keys(): # self.info=self.db[self.name] # else: # self.db[self.name]='' # self.info='' # # def LookOrUpdate(self,newInfo=None): # '''newInfo有值时更新数据库,否则直接返回数据库内的info''' # if newInfo: #调用方法时若给了newInfo,则更新info # self.info=newInfo # return self.info # # def __del__(self): # '''数据库类被垃圾回收时保存信息到磁盘''' # self.db[self.name]=self.info # self.db.close() # # # #更新7-5的代码,运用上信息数据库类,修改主要在welcome函数里 # # class Creation(wx.Frame): # '''一个询问界面''' # def __init__(self): # wx.Frame.__init__(self,None,-1,'一个询问',pos=(60,60),size=(250,300)) # panel=wx.Panel(self,-1) # self.text1=wx.StaticText(panel,label='你是否要注册一个账户?', # pos=(50,50),size=(180,40)) # self.button1=wx.Button(panel,label='是',pos=(60,100),size=(40,25)) # self.button1.Bind(wx.EVT_BUTTON,self.LogOnClick) # self.button2=wx.Button(panel,label='否',pos=(100,100),size=(40,25)) # self.button2.Bind(wx.EVT_BUTTON,self.QuitClick) # # def QuitClick(self,event): # self.Destroy() # def LogOnClick(self,enent): # logon=LogOn() # logon.Show() # self.Destroy() # # class LogOn(wx.Frame): # '''一个注册界面''' # def __init__(self): # wx.Frame.__init__(self,None,-1,'创建账户',size=(400,250)) # panel=wx.Panel(self,-1) # #用户名与密码文本框 # db=shelve.open(r'/home/vetains/pywork/pycore/chapter7.dat') # now=ctime(time()) #now是由ctime()返回的 # self.text1=wx.StaticText(panel,label='用户名:',pos=(50,50),size=(50,25)) # self.text2=wx.StaticText(panel,label='密码:',pos=(50,70),size=(50,25)) # self.textCtrl1=wx.TextCtrl(panel,pos=(105,50),size=(75,25)) # self.textCtrl2=wx.TextCtrl(panel,pos=(105,70),size=(75,25)) # self.name=str(self.textCtrl1.GetValue()) # self.password=str(self.textCtrl2.GetValue()) # #注册按钮 # self.button1=wx.Button(panel,label='注册',pos=(65,100),size=(40,30)) # # self.button1.Bind(wx.EVT_BUTTON,lambda event,\ # # n=self.name,p=self.password:self.CreateClick(event,n,p)) # self.button1.Bind(wx.EVT_BUTTON,self.CreateClick) # #取消按钮 # self.button2=wx.Button(panel,label='取消',pos=(105,100),size=(40,30)) # self.button2.Bind(wx.EVT_BUTTON,self.QuitClick) # # def QuitClick(self,event): # '''取消事件''' # self.Destroy() # # def CreateClick(self,event): # '''注册事件''' # name=str(self.textCtrl1.GetValue()) # password=str(self.textCtrl2.GetValue()) # # db=shelve.open(r'/home/vetains/pywork/pycore/chapter7.dat') # now=ctime(time()) #now是由ctime()返回的字符串 # newUser={'password':password,'time':now} # db[name]=newUser # db.close() # self.Destroy() # # class adminMenue(wx.Frame): # def __init__(self): # wx.Frame.__init__(self,None,-1,'管理菜单',size=(600,600)) # panel=wx.Panel(self,-1) # db=shelve.open('/home/vetains/pywork/pycore/chapter7.dat') # nameList=[] # pwList=[] # timeList=[] # for eachKey in db.keys(): # nameList.append(eachKey) # pwList.append(db[eachKey]['password']) # timeList.append(db[eachKey]['time']) # db.close() # nameStr='名单列表:\n'+'\n'.join(nameList) # pwStr='密码列表:\n'+'\n'.join(pwList) # timeStr='登录时间:\n'+'\n'.join(timeList) # self.text1=wx.StaticText(panel,label=nameStr,pos=(50,50),size=(200,200)) # self.text2=wx.StaticText(panel,label=pwStr,pos=(150,50),size=(200,200)) # self.text3=wx.StaticText(panel,label=timeStr,pos=(250,50),size=(200,200)) # # class Main(wx.Frame): # '''主界面''' # def __init__(self): # wx.Frame.__init__(self,None,-1,'主界面',size=(360,240)) # panel=wx.Panel(self,-1) # #用户名 # self.text1=wx.StaticText(panel,label='用户名:',pos=(10,10),size=(100,50)) # self.textCtrl1=wx.TextCtrl(panel,pos=(100,10),size=(100,10)) # # name=str(textCtrl1.GetValue()) #像这样直接获取文本框的文本是不可行的. # #密码 # self.text2=wx.StaticText(panel,label='密码:',pos=(10,60),size=(100,50)) # self.textCtrl2=wx.TextCtrl(panel,pos=(100,60),size=(100,0)) # # password=str(textCtrl2.GetValue()) # # #登录按钮 # self.logInButton=wx.Button(panel,-1,label='登录',pos=(30,180),size=(100,50)) # self.logInButton.Bind(wx.EVT_BUTTON,self.logInClick) # #菜单按钮 # self.adminMenuButton=wx.Button(panel,-1,label='菜单管理',pos=(130,180),size=(100,50)) # self.adminMenuButton.Bind(wx.EVT_BUTTON,self.adminMenuClick) # #退出按钮 # self.quitButton=wx.Button(panel,-1,label='退出',pos=(230,180),size=(100,50)) # self.quitButton.Bind(wx.EVT_BUTTON,self.quitClick) # # def adminMenuClick(self,event): # '''菜单按钮事件''' # admin=adminMenue() # admin.Show() # # def quitClick(self,event): # '''退出按钮事件''' # sys.exit() # # def logInClick(self,event): # '''登录按钮事件''' # # name=str(self.textCtrl1.GetValue()) # password=str(self.textCtrl2.GetValue()) # # db=shelve.open('/home/vetains/pywork/pycore/chapter7.dat') # keyList=db.keys() # db.close() # # if name in keyList: # # db=shelve.open('/home/vetains/pywork/pycore/chapter7.dat') # dbPassword=db[name]['password'] # db.close() # # if password==dbPassword: # '''用户名已存在且密码正确则唤起欢迎界面''' # self.welcome(name,password) # else: # '''密码错误唤起密码错误界面''' # self.refuse(name) # else: # '''用户名不存在则询问是否注册''' # creation=Creation() # creation.Show() # # def welcome(self,name,password): # '''欢迎界面||因13-4而增加了内容''' # # def fix(event): # '''修改按钮事件''' # newInfo=str(textCtrl1.GetValue()) # infoDB.LookOrUpdate(newInfo) # # def quit(event): # '''退出按钮事件''' # welcomeWin.Destroy() # # welcomeApp=wx.App() # welcomeWin=wx.Frame(None,title='欢迎!',size=(400,400)) # panel=wx.Panel(welcomeWin,-1) # # welStr='欢迎,%s,你的上次登录时间为' # text1=wx.StaticText(panel,label=welStr%name,pos=(50,50),size=(500,20)) # db=shelve.open('/home/vetains/pywork/pycore/chapter7.dat') # lastTime=db[name]['time'] #上次登录时间 # now=ctime(time()) #更新登录时间 # db[name]={'password':password,'time':now} # db.close() # text2=wx.StaticText(panel,label=lastTime,pos=(50,80),size=(250,20)) # #调用数据库类 # infoDB=My_DB(name) # text3=wx.StaticText(panel,label='储存的信息为:',pos=(50,105),size=(250,20)) # #显示储存信息的文本框,可修改,默认值为信息 value=infoDB.info # textCtrl1=wx.TextCtrl(panel,value=infoDB.info,pos=(50,130),size=(250,20)) # #设置修改储存信息的按钮 # FixButton=wx.Button(panel,label='修改',pos=(50,155),size=(50,45)) # FixButton.Bind(wx.EVT_BUTTON,fix) # #设置退出按钮 # QuitButton=wx.Button(panel,label='退出',pos=(105,155),size=(50,45)) # QuitButton.Bind(wx.EVT_BUTTON,quit) # # # welcomeWin.Show() # welcomeApp.MainLoop() # # def refuse(self,name): # '''密码错误界面''' # refuseApp=wx.App() # refuseWin=wx.Frame(None,title='密码错误!',size=(200,200)) # panel=wx.Panel(refuseWin,-1) # text1=wx.StaticText(panel,label='%s,密码错误'%name,pos=(50,50),size=(50,10)) # refuseWin.Show() # refuseApp.MainLoop() # # # def test(): # '''执行函数''' # app=wx.App() # main=Main() # main.Show() # app.MainLoop() # # if __name__=='__main__': # test() # # 13-5 几何,Point类,记录X,Y坐标点 # class Point(object): # def __init__(self,x=0,y=0): # self.x=x # self.y=y # # def __str__(self): # return '(%s,%s)'%(str(self.x),str(self.y)) # # __repr__=__str__ # # 13-6 直线或斜线类 # from math import sqrt # # class Line(object): # '''线段类''' # def __init__(self,x1=0,y1=0,x2=0,y2=0): # self.x1=x1 # self.y1=y1 # self.x2=x2 # self.y2=y2 # # def __str__(self): # return '起点(%s,%s),终点(%s,%s)'%(self.x1,self.y1,self.x2,self.y2) # # __repr__=__str__ # # # def __set__(self,obj,newx1,newy1,newx2,newy2): # # self.x1=newx1 #所以__set__这种描述符到底有什么用 # # self.y1=newy1 # # self.x2=newx2 # # self.y2=newy2 # # # def length(self): # '''线段长度''' # length=sqrt((self.x1-self.x2)**2+(self.y1-self.y2)**2) # return '线段长度为:%s'%str(length) # # def slope(self): # '''线段斜率''' # try: # slope=float(self.y2-self.y1)/float(self.x2-self.x1) # return '线段斜率为:%s'%str(slope) # except ZeroDivisionError: # return '竖直线无斜率' #13-7 数据类 # #13-8 堆栈 等学完了《数据结构与算法》,回来试试不用列表的解决办法 # class Stack(object): # '''堆栈类,借助列表实现,last-in-first-out,LIFO''' # def __init__(self,seq=[]): # self.StackList=list(seq) # # def __str__(self): # return str(self.StackList) # # __repr__=__str__ # # def push(self,elem): # '''向堆栈中压入一个数据项''' # self.StackList.append(elem) # # def pop(self): # '''从堆栈中移出一个数据项''' # return self.StackList.pop() # # def isempty(self): # '''判断堆栈是否为空,返回0或1''' # if bool(len(self.StackList)): # return 1 # else: # return 0 # # def peek(self): # '''取出堆栈顶部的数据项,但不移除''' # return self.StackList[-1] # #13-9 队列类/ # class Queue(object): # '''队列类,先进先出,first-in-first-out,FIFO''' # def __init__(self,seq=[]): # self.QueueList=list(seq) # # def __str__(self): # return str(self.QueueList) # # __repr__=__str__ # # def enqueue(self,elem): # '''在列表的尾部加入一个新的元素''' # self.QueueList.append(elem) # # def dequeue(self): # '''在列表的头部取出一个元素,返回它并将它移除''' # # elem=self.QueueList[0] # # del self.QueueList[0] # # return elem # return self.QueueList.pop(0) # #13-10 堆栈和队列 # class SAQ(object): # def __init__(self,seq=[]): # self.SAQList=list(seq) # # def __str__(self): # return str(self.SAQList) # # __repr__=__str__ # # def shift(self): # '''返回并删除列表中的第一个元素''' # return self.SAQList.pop(0) # # def upshift(self,elem): # '''在列表的头部压入一个新的元素''' # self.SAQList.insert(0,elem) # # def push(self,elem): # '''在列表尾部加上一个新元素''' # self.SAQList.append(elem) # # def pop(self): # '''返回并删除列表中的最后一个元素''' # return self.SAQList.pop() # #13-11 电子商务 # '''顾客类User,存货清单类Item,购物车类Cart。可以将多个货物放在购物车里,顾客可以有多个购物车''' # # class User(object): # '''顾客类''' # def __init__(self,name): # self.name=name # self.Hand={} #手里的购物车,默认有0个购物车 # # def getCart(self): # '''获得一个购物车''' # i=len(self.Hand.keys())+1 #这是手里的第i个购物车 # self.Hand[i]=Cart() # # def getItem(self,item,i=1): # '''往第i个购物车里添加货物''' # if isinstance(item,Item): # self.Hand[i].append(item) # else: # raise TypeError,'只能往购物车里添加已有的货物' # # def askItemPrice(self,item): # '''询问单件货物价格''' # if isinstance(item,Item): # return '货物%s的价格是 %s'%(item.name,str(item.price)) # else: # raise TypeError,'没有这个货物' # # def askAllMoney(self,i=1): # '''询问第i个购物车里的货物总价''' # if i>len(self.Hand): # raise IndexError,'你没有这个购物车' # else: # return '这个购物车里的货物总价为:%s'%str(self.Hand[i].money()) # # def askNums(self,i=1): # '''询问车里的货物数量''' # return '购物车里的货物数量为:%s'%str(self.Hand[i].nums()) # # class Item(object): # '''货物类,两个属性,名字和价格''' # def __init__(self,name,price): # self.name=name # if isinstance(price,int) or isinstance(price,float): # self.price=float(price) # else: # raise TypeError,'价格应为整型或浮点型' # # class Cart(list): # '''购物车类,可以查询车内的货物数量和总价格''' # def __init__(self): # super(Cart,self).__init__() # # def nums(self): # '''返回购物车内货物数量''' # return len(self) # # def money(self): # '''购物车里的货物总价格''' # MoneySum=0 # for i in self: # MoneySum+=i.price # return MoneySum # # def main(): # '''主体函数,模拟一次购物过程''' # mike=User('Mike') #客户Mike # item1=Item('apple',1.50) # item2=Item('pear',2.50) # item3=Item('banana',3.40) # itemList=[item1,item2,item3] # # print '货物总览:' # print '-'*20 # for i in range(3): #购物菜单 # print itemList[i].name # print '-'*20 # # mike.getCart() # print 'Mike获得一辆购物车' # print # # print 'Mike询问了货物1的价格: '+mike.askItemPrice(item1) # print 'Mike询问了货物2的价格: '+mike.askItemPrice(item2) # print 'Mike询问了货物3的价格: '+mike.askItemPrice(item3) # print # # print 'Mike把货物1,2放入了购物车' # mike.getItem(item1) # mike.getItem(item2) # print # # print 'Mike询问了当前购物车里的货物的货物数目和总价格' # print mike.askNums() # print mike.askAllMoney() # print # # print 'Mike获得第二辆购物车' # mike.getCart() # print # # print 'Mike继续购买3个苹果和3个香蕉' # for i in range(3): # mike.getItem(item1,i=2) # mike.getItem(item3,i=2) # # print 'Mike询问了第二辆购物车里的货物数目和总价格' # print mike.askNums(2) # print mike.askAllMoney(2) # print # # print '此时购物车1的情况是:' # print mike.askNums(1) # print mike.askAllMoney(1) # # if __name__=='__main__': # main() # 13-12 聊天室
import sys class tic_tac_toe(object): def __init__(self): self.board = [0] * 9 self.pattern = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) self.player = True # X moves first, 1=X, 2=O def printboard(self, board=None): def getchar(n): if n == 0: return ' ' if n == 1: return 'X' if n == 2: return 'O' if not board: board = self.board for i in range(3): for j in range(3): print(getchar(board[i * 3 + j]), end='|') print() print('===========') def eval(self, board=None): if not board: board = self.board for x, y, z in self.pattern: if 0 != board[x] == board[y] == board[z]: return 1 if board[x] == 1 else -1 return 0 def terminal(self, board=None): if not board: board = self.board return 0 not in board or self.eval(board) != 0 def alphabeta(self, board=None, player=None, alpha=-99999, beta=99999): if not board: board = self.board if player is None: player = self.player if self.terminal(board): return self.eval(board), None if player: best = -99999, None for empty in range(9): if board[empty] != 0: continue board[empty] = 1 v, _ = self.alphabeta(board, False, alpha, beta) board[empty] = 0 if v > best[0]: best = v, empty if best[0] >= beta: return best alpha = max(alpha, best[0]) else: best = 99999, None for empty in range(9): if board[empty] != 0: continue board[empty] = 2 v, _ = self.alphabeta(board, True, alpha, beta) board[empty] = 0 if v < best[0]: best = v, empty if best[0] <= alpha: return best beta = min(beta, best[0]) return best def start(self, ai_move=False): board = self.board if not ai_move: self.printboard() while True: if ai_move: _, x = self.alphabeta() else: x = int(input('Position: ')) - 1 if not (0 <= x <= 8 and board[x] == 0): print('Invalid') continue board[x] = 1 if self.player else 2 self.printboard() if self.terminal(): break self.player, ai_move = not self.player, not ai_move if self.eval() == 0: print('Tie') elif self.player: print('X wins') else: print('O wins') game = tic_tac_toe() if len(sys.argv) == 1: game.start() else: game.start(True)
#!/usr/bin/env python from random import * print("Script for generating two dimensional coordinate data") print("Data is stored in a txt file where each line has a pair of coordinates, delimited by a colon") #print("Max distance in each dimension from previous point is 0.05") print("Domain of each dimension is (-5.0, 5.0)") #print("WARNING!: This script does not validate input or handle errors") #filename = raw_input("Name of data file: ") #n = int(raw_input("Number of coordinate pairs to generate: ")) n = 200 x = 0.0 z = 0.0 def distance(p1, p2): return sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2) with open("test_data.txt", "w+") as f: for i in range(n): newx = 10.0 * random() - 5.0 newz = 10.0 * random() - 5.0 if newx > 5.0: newx = 5.0 elif newx < -5.0: newx = -5.0 if newz > 5.0: newz = 5.0 elif newz < -5.0: newz = -5.0 deltax = (newx - x) / 100.0 deltaz = (newz - z) / 100.0 for j in range(100): f.write("{0}:{1}\n".format(x + (j + 1) * deltax, z + (j + 1) *deltaz)) x = newx z = newz
my_list = [5, 12, -8, 3, 16, 2] # вывести массив print(my_list) # list + list, list * number another_list = ['five', 'four', 'ten'] print(my_list + another_list) print(my_list * 2) # разрезание print(my_list[2:5]) my_list.sort() print(my_list)
#!/usr/bin/env python3 # ^3^ coding=utf-8 # # author: superzyx # date: 2019/09/08 # usage: the forth one of exams # 4.请使用Python代码对[23, 14, 12, 21, 45, 99, 34, 42]排序, 请使用冒泡排序 list01 = [23, 14, 12, 21, 45, 99, 34, 42] for i in range(len(list01)): for j in range(len(list01) - i - 1): if list01[j] > list01[j+1]: list01[j], list01[j+1] = list01[j+1], list01[j] print(list01)
#!/usr/bin/env python3 # ^3^ coding=utf8 # # author:superzyx # date:2019/08/10 # usage: sort qiuckly def sortq(list01): if len(list01) < 2: return list01 else: nu = list01[0] listr = [i for i in list01[1:] if i > nu] listl = [r for r in list01[1:] if r < nu] return sortq(listl) + [list01[0]] + sortq(listr) a = sortq([2, 4, 3, 0]) print(a) betw = 0 def sortq_advance(i): if i == None: return None else: if i > betw: listr.append(i)
#!/usr/bin/env python3 # ^3^ coding=utf8 # # author:superzyx # date:2019/08/09 # usage: OS module learning d = {'mike': 10, 'lucy': 2, 'ben': 30} d = dict(sorted(d.items(), key=lambda list: list[1], reverse=True)) print(d)
#!/usr/bin/env python3 # ^3^ coding= utf8 # # author: superzyx # date: 2019/08/19 # usage: random function import random tuple01 = (0, 1, 2, 3) a = random.choice(tuple01) print(a) random.shuffle(tuple01) print(tuple01) # m = 1 # while m != 9: # m = random.uniform(1,9) # print(m)
#!/usr/bin/env python3 # ^3^ coding=utf8 # # author: superzyx # date: 2019/08/15 # usage: many_inherit # class A: # def __init__(self, name, sex): # self.name = name # self.sex = sex # # class B(A): # def __init__(self, name, sex, age): # A.__init__(self,name,sex) # # self.name = name # # self.sex = sex # self.age = age # # class C(A): # def __init__(self, name, sex, hobby): # A.__init__(self,name,sex) # # self.name = name # # self.sex = sex # self.hobby = hobby # class D(B,C): # def __init__(self, name, sex, age, hobby): # B.__init__(self,name,sex,age) # C.__init__(self,name,sex,hobby) # # d = D('hh',1,1,1) class Father: def __init__(self,name): self.name = name @property def fightSon(self): return '{} fight !!'.format(self.name) @fightSon.setter def fightSon(self, name): self.name = name @fightSon.deleter def fightSon(self): print('hehe') class Son(Father): def __init__(self,name,nu): super(Son, self).__init__(name) self.nu = nu def jj(self): print('llll') son = Son('狗子',1) son.fightSon = '大明' print(son.fightSon) if hasattr(Father, son.fightSon): print('ahdsja') else: print('kkkk')
# equal or not a = input("enter the first number") b = input("enter the second number") if (a==b): print("numbers are equal") else print("numbers are not equal")
#python program to creat a tuple with different data types tuplex=("tuple",3.2,1) print(tuplex) ('tuple', 3.2, 1) >>>
#python program to creat a list of empty dictionaries n = 5 1 = [{} for _ in range(n)] print(1) output {} {} {} {} {}
# equal or not a = input("enter a number") b = input("enter a number") if (a==b): print("numbers are equal") else: print("numbers are not equal")
import sys import string import random snakes = { 8: 4, 18: 1, 26: 10, 54: 36, 60: 23, 90: 48, 92: 25, 97: 87, 99: 63 } # ladder takes you up from 'key' to 'value' ladders = { 3: 20, 6: 14, 11: 28, 15: 34, 17: 74, 22: 37, 38: 59, 49: 67, 57: 76, 61: 78, 73: 86, 81: 98, 88: 91 } def get_players_name(): name=input() return name def get_dice_value(min_dice, max_dice): dicevalue=random.randint(min_dice,max_dice) print("its " +str(dicevalue)+"\n") return dicevalue def check_snake_ladder(c_position): if c_position in snakes: c_pos=snakes[c_position] print("player got snake he went down to: "+str(c_pos)) elif c_position in ladders: c_pos=ladders[c_position] print("player got ladder he moved up to: "+str(c_pos)) else: c_pos=c_position return c_pos def check_win(c_posi): if c_posi==100: return True return False def check_invalid(current_pos, old_pos): if current_pos>100: curr_pos=old_pos return old_pos return current_pos no_ppl=int(input("how many players? ")) no_dice=int(input("how many dices:1/2? ")) pplname={} if no_dice==1: max_dice_value=6 min_dice_value=1 else: max_dice_value=12 min_dice_value=2 players=[]*no_ppl for i in range(no_ppl): print("Enter Player "+str(i+1)+" name:") players.append(get_players_name()) print( "Each player will start with 0. Exact 100 needs to be done for the home. Lets start:") current_position=[0]*no_ppl for k in range(no_ppl): dictt={k:players[k]} pplname.update(dictt) i=0 old_pos=[0]*no_ppl while(True): input("Hit Enter to roll dice. "+players[i]+" is playing:") dice_value=get_dice_value(min_dice_value, max_dice_value) old_pos[i]=current_position[i] current_position[i]+=dice_value current_position[i]=check_invalid(current_position[i], old_pos[i]) win_check=check_win(current_position[i]) if win_check==True: print(players[i]+ " has reached max value and won the match") sys.exit() current_position[i]=check_snake_ladder(current_position[i]) print(players[i]+" moved to:"+str(current_position[i])) if i==no_ppl-1: i=0 else: i+=1
n = float(input("Informe um Numero: ")) div = 0 if (n%2 == 0): m = n while m != 0: div = n / m if div == 0: print("O Numero Nao eh Primo") break else: print("O Numero Eh Primo") m -= 1
soma = 0 x = 0 numero = 0 while True: numero = float(input("Informe um Numero ou 0 para sair: ")) if numero == 0: break soma += numero x += 1 print ("A Soma e = %3.2f e a Media = %3.2f "%(soma,(soma/x)))
PD = 0 QT = 0 total = 0 while True: PD = int(input("Informe Codigo do Produto ou 0 para Sair: ")) if PD == 0: break QT = float(input("Informe Quantidade desejada: ")) if PD == 1: total += (0.50 * QT) elif PD == 2: total += (1.00 * QT) elif PD == 3: total += (4.00 * QT) elif PD == 5: total += (7.00 * QT) elif PD == 9: total += (8.00 * QT) else: print("Codigo Invalido") break print("O Total das Compras = R$ %4.2f"%total)
#IST 440 # Drive Train (Team 02) # Author: Ghansyam Patel, Rahul Manoharan, and Klaus # Date: 10/03/2016 #Unit-Testing #GoPiGo Robot for DriveTrain #Unit tests added by Klaus Herchenroder from gopigo import * import sys #Import Unit Test import unittest #Returns Value True def IsTrue(): return True #Returns p indicating car is in park def InPark(): return 'p' #Returns r indicating car is in reverse def InReverse(): return 'r' #Returns n indicating car is in neutral def InNeutral(): return 'n' #Returns z indicating car is stoping def Stop(): return 'z' class IsRunning(): #Checks if return value is true def TrueTest(self): self.assertTrue(IsTrue()) #Checks if car is in park def ParkTest(self): self.assertEqual(InPark(), mode) #Checks if car is in reverse def ReverseTest(self): self.assertEqual(InReverse(), mode) #Checks if car is in neutral def NeutralTest(self): self.assertEqual(InNeutral(), mode) #Checks if car is stoping def StopTest(self): self.assertEqual(Stop(), mode) #Displays the Start Up Screen print('Welcome to the DriveTrain System') print('Press:') print('p to Park the Car') print('r to Reverse the Car') print('n to Neutral') print('d to Drive the Car') print('l to Move the Car Left') print('r to Move the Car Right') print('i to Increase the Speed') print('e to Decrease the Speed') print('z to Exit the Drive Mode') car = ' ______' car1= ' /___ __\\___' car2= ' /___________ /' car3= ' O----------O' #Unit test for code is running if TrueTest(): #While car is running while True: print('Drive Mode:') mode = raw_input() if (mode == 'p'): #Tests if the car is recieveing park input if ParkTest(): stop() #Car In The Park Mode elif (mode == 'r'): #Tests if the car is recieveing reverse input if ReverseTest(): bwd() #Car Reversing elif (mode == 'n'): #Tests if the car is recieveing neutral input if NeutralTest(): stop() #Car In The Neutral Mode elif (mode == 'd'): fwd() #Car Moving Forward elif (mode == 'l'): left() #Car Turning Left elif (mode == 't'): right() #Car Turning Right elif (mode == 'i'): increase_speed() #Increasing The Car Speed elif (mode == 'e'): decrease_speed() #Car Turning Left elif (mode == 'z'): #Tests if the car is recieveing stop input if StopTest(): stop() #Car Stops before Exiting Drive Mode print('Exiting Drive Mode') #Leaving Drive Mode print(car) #Printing Car print(car1) #Printing Car print(car2) #Printing Car print('Good Bye!') #Exiting Message! sys.exit() else: #Prints message if no mode exists for input print('Wrong Drive Mode Command, Please Try Again') time.sleep(.1) if __name__ == '__main__': unittest.main()
# Section06 # 파이썬 함수식 및 람다(lambda) # 함수 정의 방법 # def 함수명(parameter): # code # 함수 호출 # 함수명(parameter) # 함수 선언 위치 중요 # 예제1 def hello(world): print("Hello", world) hello("Python!") hello(7777) # 예제2 def hello_return(world): val = "Hello " + str(world) return val strr = hello_return("Python!!!!!") print(strr) # 예제3(다중리턴) def func_mul(x): y1 = x * 100 y2 = x * 200 y3 = x * 300 return y1, y2, y3 val1, val2, val3 = func_mul(100) print(val1, val2, val3) # 예제3-2(데이터 타입 변환) def func_mul2(x): y1 = x * 100 y2 = x * 200 y3 = x * 300 return [y1, y2, y3] lt = func_mul2(100) print(lt, type(lt)) # 예제4 # *args, *kwargs def args_func(*args): for t in args: print(t) args_func('kim', "Park", 'Lee') # 예제4-2 def args_func2(*args): for i,v in enumerate(args): print(i, v) args_func2('Kim', 'Park', 'Choi') # kwargs def kwargs_func(**kwargs): for k, v in kwargs.items(): print(k, v) kwargs_func(name1="Kim", name2="Park", name3="Lee") # 전체 혼합 def example_mul(arg1, arg2, *args, **kwargs): print(arg1, arg2, args, kwargs) example_mul(10, 20) example_mul(10, 20, 'park', 'kim') example_mul(10, 20, 'kim', 'park', age1=24, age2=35) # 중첩함수(클로저) def nested_func(num): def func_in_func(num): print(num) print("in func") func_in_func(num + 10000) nested_func(10000) # 파이썬 데코레이터 검색해서 배우기 (클로저) def decorator_function(original_function): def wrapper_function(): return original_function() return wrapper_function def display(): print("display 함수가 실행되었습니다.") decorated_display = decorator_function(display) decorated_display()
from re import sub from string import punctuation def count_words(sentence): word_count = {} sentence = sub(f"[{punctuation}]".replace("'", ""), " ", sentence.lower()) sentence = [word.strip("'") for word in sentence.split()] for word in sentence: word_count[word] = sum(1 for w in sentence if w == word) return word_count
def leap_year(year): check1 = is_divisible(year, 4) and not is_divisible(year, 100) check2 = is_divisible(year, 400) return check1 or check2 def is_divisible(a: int, b: int) -> bool: return (a % b) == 0
def response(hey_bob): phrase = hey_bob.strip() response = "Whatever." if phrase.isupper() and phrase.endswith("?"): response = "Calm down, I know what I'm doing!" elif phrase.isupper(): response = "Whoa, chill out!" elif phrase.endswith("?"): response = "Sure." elif not phrase: response = "Fine. Be that way!" return response
# Реализовать два небольших скрипта: # а) итератор, генерирующий целые числа, начиная с указанного, # б) итератор, повторяющий элементы некоторого списка, определенного заранее. # Подсказка: использовать функцию count() и cycle() модуля itertools. # Обратите внимание, что создаваемый цикл не должен быть бесконечным. # Необходимо предусмотреть условие его завершения. # Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл. # Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено. from itertools import count from itertools import cycle def my_count_func(start, stop): for el in count(start): if el > stop: break else: print(el) def my_cycle_func(my_list, iteration): i = 0 iter = cycle(my_list) while i < iteration: print(next(iter)) i+=1 my_count_func(start = int(input("Введите стартовое число: ")), stop = int(input("Введите конечное число: "))) my_cycle_func(my_list = input('Введите список через пробел: ').split(), iteration = int(input("Введите количество итераций: ")))
#!/usr/bin/env python3 """ Module provides a Van class, a subtype of Vehicle class. """ from vehicle import Vehicle class Van(Vehicle): """ Subtype of the Vehicle class. Contains additional attributes of make and model, num of passengers. Supports polymorphic behaviour of method get_description. """ def __init__(self, make_model, mpg, num_passengers, vin): """ (Van, str, str, str, str) -> str, str, bool, str, str Initializes with make-model, mpg, num_passengers, vin. """ super().__init__(mpg, vin) # Init Vehicle class self.__make_model = make_model self.__num_passengers = num_passengers def get_description (self): """ (Van) -> str Returns description of car as a formatted string. """ spacing = ' ' description = '{0:<22}{1}passengers: {2:>2}{1}{3}'.format( self.__make_model, spacing, self.__num_passengers, \ Vehicle.get_description(self) ) return description
class SystemInterface : '''Provides all the methods that any user interface would need for interacting with the system (API)''' def __init__(self) : pass def create (self) : # returns pass def num_avail_vehicles (self, vehicle_type) : # returns pass def get_vehicle (self, vin) : # returns pass def get_vehicle_types (self) : # returns pass def get_vehicle_costs (self, vehicle_type) : # returns pass def get_avail_vehicles (self, vehicle_type) : # returns pass def is_reserved (self, vin) : # returns pass def find_reservation (self, credit_card) : # returns pass def add_reservation (self, vin) : # returns pass def cancel_reservation (self, credit_card) : # returns pass def calc_rental_cost (self, vehicle_type, rental_period, want_insurance, miles_driving) : # returns pass class Van (Vehicle) : '''subclass maintains specific information for vehicle type. Stores the maximum number of passengers''' def __init__(self) : pass def create (self, make_model, mpg, num_passengers, vin) : # returns pass def get_description (self) : # returns pass class Car (Vehicle) : '''Subclass maintains specific information for vehicle type. Stores maximum number of passengers and number of doors''' def __init__(self) : pass def create (self, make_model, mpg, num_passengers, num_doors, vin) : # returns pass def get_description (self) : # returns pass class Reservations : '''aggregating class has methods for maintaining it's collection of objects.''' def __init__(self) : pass def create (self, vehicles) : # returns pass def is_reserved (self, vin) : # returns pass def get_vin_for_reserved (self, credit_card) : # returns pass def add_reservation (self, resv) : # returns pass def find_reservation (self, name, addr) : # returns pass def cancel_reservation (self, credit_card) : # returns pass class VehicleCosts : '''aggregating class has methods for maintaining it's collection of objects, returns the cost of a specific vehicle type as a single string for display''' def __init__(self) : pass def create (self, vehicle_types) : # returns pass def get_vehicle_cost (self, vehicle_type) : # returns pass def add_vehicle_cost (self, veh_type, veh_cost) : # returns pass def cal_rental_cost (self, vehicle_type, rental_period, want_insurance, miles_driving) : # returns pass class Vehicles : '''aggregating class maintains a collection of the corresponding object type. Has aggregating class has methods for maintaining it's collection of objects.''' def __init__(self) : pass def create (self) : # returns pass def get_vehicle (self, vin) : # returns pass def add_vehicle (self, vehicle) : # returns pass def num_avail_vehicles (self, vehicle_type) : # returns pass def get_avail_vehicles (self, vehicle_type) : # returns pass def unreserve_vehicle (self, vin) : # returns pass class VehicleCost : '''It's create(__init__) method is passed six arguments; the daily/weekly/weekend rates, the number of free miles, the per mile charge, and the daily insurance rate to initialize the object with''' def __init__(self) : pass def create (self, daily_rate, weekly_rate, weekend_rate, free_miles, per_mile_chrg, insur_rate) : # returns pass def get_daily_rate (self) : # returns pass def get_weekly_rate (self) : # returns pass def get_weekend_rate (self) : # returns pass def get_free_daily_miles (self) : # returns pass def get_per_mile_charge (self) : # returns pass def get_insurance_rate (self) : # returns pass def get_costs (self) : # returns pass class RentalAgencyUI : '''Text-based user interface. Initialized with a reference to the system interface''' def __init__(self) : pass def create (self, system) : # returns pass def start (self) : # returns pass class Truck (Vehicle) : '''subclass maintains specific information for vehicle type. Stores it's length and the number of rooms of stoage it can hold''' def __init__(self) : pass def create (self, mpg, length, num_rooms, vin) : # returns pass def get_description (self) : # returns pass class Vehicle : '''superclass maintains vehicle's type, VIN, and resrevation status''' def __init__(self) : pass def create (self, mpg, vin) : # returns pass def get_type (self) : # returns pass def get_vin (self) : # returns pass def get_description (self) : # returns pass def is_reserved (self) : # returns pass def set_reserved (self, resreved) : # returns pass class Reservation : def __init__(self) : pass def create (self, name, address, credit_card, vin) : # returns pass def get_name (self) : # returns pass def get_addr (self) : # returns pass def get_credit_card (self) : # returns pass def get_vin (self) : # returns pass
fruits=['apple','pear',5] #outputs all print(fruits) #outputs fruit at index number 0 print(fruits[0]) #to append towards the end of the list fruits.append('Grapes') #to remove from list fruits.remove(5) #to change item in list fruits[2]="Guava"
## Finds the largest palindrome number obtained after multiplying two three digit numbers def is_palindrome(str): if str== reversed(str): return True return False def reverse_int(n): return int(str(n)[::-1]) n=10201 for i in range(999, 100, -1): for j in range(i,100, -1): num=i*j #print str(num), reversed(str(num)) if (num == reverse_int(num)) and (num > n): n=num print n
# coding: utf-8 # In[164]: import numpy as np from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt # Load the data set data = np.loadtxt('C:/Users/Mina Alpu/Desktop/polynome.data') # Separate the input from the output X = data [:, 0] Y = data [:, 1] N = len(X) def visualize(w, X, Y): plt.plot(X,Y, 'r.') x = np.linspace(0., 1., 100) y = np.polyval(w, x) plt.plot(x, y, 'g-') plt.title('Polynomial regression with order' + str(len(w)-1)) plt.show() #degrees ranging from 1 to 20 def cal_error(): for i in range(1, 21): w = np.polyfit(X, Y, i) visualize(w, X, Y) y_pred = np.polyval(w,X) training_error = mean_squared_error(y_pred, Y) print("training error: ", training_error) cal_error() #split the dataset as a training and test x_split = np.hsplit(X, [11]) y_split = np.hsplit(Y, [11]) x_split[0] #for X train set x_split[1] #for X test set y_split[0] #for Y train set y_split[1] #for Y test set def test_error(): for i in range(1, 21): w = np.polyfit(x_split[0], y_split[0], i) visualize(w, x_split[0], y_split[0]) y_predicted = np.polyval(w, x_split[1]) test_error = mean_squared_error(y_predicted, y_split[1]) print("test error: ", test_error) #from cross validation test_error() x_split = np.hsplit(X, 2) #for k=2 y_split = np.hsplit(Y, 2) x_test = x_split[1] x_train = np.hstack ((x_split[i] for i in range(2) if not i==1)) print("if fold 1 is not observed, X training data: ", x_train) print(x_test) y_train = np.hstack ((y_split[i] for i in range(2) if not i==1)) print("if fold 1 is not observed, Y training data", y_train) x_train1 = np.hstack ((x_split[i] for i in range(2) if not i==0)) print("if first fold is not observed, X training data: ", x_train1) y_train1 = np.hstack ((y_split[i] for i in range(2) if not i==0)) print("if first fold is not observed, Y training data: ", y_train1)
# Python program to add two binary numbers. # Driver code # Declaring the variables a = "1101" b = "100" # Calculating binary value using function sum = bin(int(a, 2) + int(b, 2)) # Printing result print(sum[2:])
alphabets=" abcdefghijklmnopqrstuvwxyz" num=int(input("Enter the number of alphabet you want:")) alphai=input("Enter the alphabet:") num_ans=alphabets[num] alphai_ans = alphabets.index(alphai) suffix="0" if num == 1: suffix="st" elif num == 21: suffix="st" elif num == 2: suffix="nd" elif num == 22: suffix="nd" elif num == 3: suffix="rd" elif num == 23: suffix="rd" else: suffix="th" print() print("The "+str(num)+suffix+" alphabet is= "+num_ans.upper()) if alphai_ans == 1: suffix="st" elif alphai_ans == 21: suffix="st" elif alphai_ans == 2: suffix="nd" elif alphai_ans == 22: suffix="nd" elif alphai_ans == 3: suffix="rd" elif alphai_ans == 23: suffix="rd" else: suffix="th" print() print(alphai.upper()+" is "+str(alphai_ans)+suffix+" alphabet")
""" An example usage of the python 'requests' module, which will permit us to retrieve data from wikipedia pages. """ import requests API_URL = 'https://en.wikipedia.org/w/api.php' PARAMS = { # "opensearch" is the method we are using "action" : "opensearch", "namespace": "0", # "search" is the search term we are searching by "search" : "totalitarian", # "limit" is the maximum amount of results we expect to see "limit" : "5", "format" : "json" } if __name__ == "__main__": # performing 'get' request request_guy = requests.get(url=API_URL, params=PARAMS) data = request_guy.json() """ The action "opensearch" returns 3 parts: 0. the search term 1. various titles associated with the search 2. {not currently available} descriptions related to their respective titles 3. links to the titles' respective articles at wikipedia """ print("Search term: " + data[0]) print("Titles: " + str(data[1])) print("Descriptions: " + str(data[2])) print("Links: " + str(data[3])) print("======================================") # testing page parsing S = requests.Session() URL = "https://en.wikipedia.org/w/api.php" PARAMS = { "action": "parse", "page": "List of totalitarian regimes", "format": "json", "section" : 1 #"prop" : "sections" } R = S.get(url=URL, params=PARAMS) DATA = R.json() new_data = (DATA["parse"]["text"]["*"]).split('<li') for datum in new_data: print(datum) print("=========")
# import from rubikMoves and import random """ Contains functions that produce a randomly scrambled Rubik's Cube""" from rubikMoves import * import random def scrambleAlgorithm(): # returns a scramble algorithm for the cube numMoves = 25 moveList = ["R", "R'", "R2", "L", "L'", "L2", "U", "U'", "U2", "D", "D'", "D2", "F", "F'", "F2", "B", "B'", "B2"] scramble = [] prevMove = "0" while len(scramble) < numMoves: move = random.choice(moveList) if move[0] != prevMove[0]: # to prevent rotating the same face twice in a row scramble.append(move) prevMove = move return scramble def reverseAlg(alg): # reverses the algorithm rAlg = [] for i in range(len(alg)-1, -1, -1): if "2" in alg[i]: rAlg.append(alg[i]) elif "'" in alg[i]: rAlg.append(alg[i][0]) elif "'" not in alg[i]: rAlg.append(alg[i] + "'") return rAlg def scrambleCube(scramble): # returns the scrambled cube solvedU = \ [[0, 1, 2], [3, 4, 5], [6, 7, 8]] solvedL = \ [[9, 10, 11], [12, 13, 14], [15, 16, 17]] solvedF = \ [[18, 19, 20], [21, 22, 23], [24, 25, 26]] solvedR = \ [[27, 28, 29], [30, 31, 32], [33, 34, 35]] solvedB = \ [[36, 37, 38], [39, 40, 41], [42, 43, 44]] solvedD = \ [[45, 46, 47], [48, 49, 50], [51, 52, 53]] cube = [solvedU, solvedL, solvedF, solvedR, solvedB, solvedD] c = Cube(cube) assert(type(c) == Cube) makeMoves(c, scramble) return c def testScramble(): print("Testing scrambler...", end="") s = scrambleAlgorithm() c = scrambleCube(s) r = reverseAlg(s) makeMoves(c, r) assert(str(c) == str(solved)) assert(isinstance(c, Cube)) cube = c.getListCube() assert(isinstance(cube, list)) print("Passed!") testScramble()
import sys def fizzBuzz(fizz, buzz, num): if num % fizz == 0 and num % buzz == 0: print("FizzBuzz") elif num % fizz == 0: print("Fizz") elif num % buzz == 0: print ("Buzz") else: print(num) def main(): for i in range(1,101): fizzBuzz(3, 5, i) if __name__=="__main__": main()
import numpy as np def sigmoid(x): return 1/(1+np.exp(-x)) def sigmoid_prime(x): y=sigmoid(x) return y(1-y) class Network(): def __init__(self, num_layers,num_neurons_each_layer,first_neurons_input): # input: # num_layers = int # num_neurons_each_layer = [] each num represents number of neurons in each layer respectively # first_neurons_input self.neurons=[] # each an np.array represent the values of the neuron self.weights=[] # each an np.array represent the weight values self.bias=np.ones(num_layers) #bias self.outputs=np.zeros(num_neurons_each_layer[-1]) # an np.array of the neuron number in last layer self.input_neurons=first_neurons_input for _num_layer in range(num_layers): self.neurons.append(np.zeros(num_neurons_each_layer[_num_layer])) self.weights.append(np.zeros((num_neurons_each_layer[_num_layer-1]+1 if _num_layer>0 else len(first_neurons_input)+1,num_neurons_each_layer[_num_layer]))) def predict(self, first_neurons_input,act_func): for _ in range(len(self.neurons)): if _==0: self.neurons[_]=act_func(np.dot(np.append(self.input_neurons,np.array((1))),self.weights[_])) else: self.neurons[_]=act_func(np.dot(np.append(self.neurons[_-1],np.array((1))),self.weights[_])) return self.neurons[-1] def layout(self): print('# of Neuron for layer {} \t: {}\n{}'.format(0,len(self.input_neurons),self.input_neurons)) for _ in range(len(self.neurons)): print('Weight Matrix #{}:\n{}'.format(_+1,self.weights[_])) print('# of Neuron for layer {} \t: {}\n{}'.format(_+1,len(self.neurons[_]),self.neurons[_])) if __name__=='__main__': network=Network(4,[6,5,6,3],[2,3,4]) network.layout() print(network.predict([2,3,4],sigmoid)) print()
array=[]; # input print ("Enter any 6 Numbers for Unsorted Array : "); for i in range(0, 6): n=input(); array.append(int(n)); # Sorting print("") for i in range(1, 6): temp=array[i] j=i-1; while(j>=0 and temp<array[j]): array[j+1]=array[j]; j-=1; array[j+1]=temp; # Output for i in range(0,6): print(array[i]);
# You might know some pretty large perfect squares. But what about the NEXT one? # Complete the findNextSquare method that finds the next integral perfect square # after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer. # If the parameter is itself not a perfect square then -1 should be returned. # You may assume the parameter is positive. # Examples: # findNextSquare(121) --> returns 144 # findNextSquare(625) --> returns 676 # findNextSquare(114) --> returns -1 since 114 is not a perfect def find_next_square(sq): import math num = math.sqrt(sq) print(num) if num.is_integer(): return ((num*2)+1) + sq else: return -1 # There is a bus moving in the city, and it takes and drop some people in each bus stop. # You are provided with a list (or array) of integer arrays (or tuples). Each integer array # has two items which represent number of people get into bus (The first item) and number of # people get off the bus (The second item) in a bus stop. # Your task is to return number of people who are still in the bus after the last bus # station (after the last array). Even though it is the last bus stop, the bus is not empty # and some people are still in the bus, and they are probably sleeping there :D def number(bus_stops): on = 0 off = 0 for x in range(len(bus_stops)): for y in range(len(bus_stops[x])): if y == 0: on += bus_stops[x][y] else: off += bus_stops[x][y] if on - off <= 0: return 0 else: return on - off #Lit Comprehension def number2(bus_stops): return sum([stop[0] - stop[1] for stop in bus_stops]) # Given: an array containing hashes of names # Return: a string formatted as a list of names separated by commas except # for the last two names, which should be separated by an ampersand. # Example: # namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ]) # # returns 'Bart, Lisa & Maggie' # namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ]) # # returns 'Bart & Lisa' # namelist([ {'name': 'Bart'} ]) # # returns 'Bart' # namelist([]) # # returns '' def namelist(names): s = '' l = [] for n in names: l.append(n.values()) name_list = [name for n in l for name in n] for i in range(len(name_list)): if i == len(name_list)-1 and i != 0: s += ' & ' + name_list[i] elif i == 0: s += name_list[i] else: s += ', ' + name_list[i] return s # Your task is to write a function which returns the sum of following # series upto nth term(parameter). # Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... # Rules: # You need to round the answer to 2 decimal places and return it as String. # If the given value is 0 then it should return 0.00 # You will only be given Natural Numbers as arguments. # Examples: # SeriesSum(1) => 1 = "1.00" # SeriesSum(2) => 1 + 1/4 = "1.25" # SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57" def series_sum(n): num = 1 denom = 4 terms = [1] while len(terms) < n: new_num = num/denom terms.append(new_num) denom += 3 if sum(terms) == 0: return str(format(0, '.2f')) elif n == 0: return str(format(0, '.2f')) else: return str(format(sum(terms), '.2f')) #List comprehension def series_sum2(n): return '{:.2f}'.format(sum(1.0/(3 * i + 1) for i in range(n))) # As the name may already reveal, it works basically like a Fibonacci, # but summing the last 3 (instead of 2) numbers of the sequence to generate the next. # And, worse part of it, regrettably I won't get to hear non-native Italian # speakers trying to pronounce it :( # So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting # input (AKA signature), we have this sequence: # [1, 1 ,1, 3, 5, 9, 17, 31, ...] # But what if we started with [0, 0, 1] as a signature? # As starting with [0, 1] instead of [1, 1] basically shifts the common Fibonacci sequence # by once place, you may be tempted to think that we would get the same sequence # shifted by 2 places, but that is not the case and we would get: # [0, 0, 1, 1, 2, 4, 7, 13, 24, ...] # Well, you may have guessed it by now, but to be clear: you need to create a fibonacci # function that given a signature array/list, returns the first n elements - signature # included of the so seeded sequence. # Signature will always contain 3 numbers; n will always be a non-negative number; if n == 0, then # return an empty array (except in C return NULL) and be ready for anything else # which is not clearly specified def tribonacci(signature, n): seq = [signature[0], signature[1], signature[2]] if n == 1: return [signature[0]] elif n == 2: return [signature[0], signature[1]] elif n == 0: return [] while len(seq) < n: seq.append(seq[-1] + seq[-2] + seq[-3]) return seq # ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything # but exactly 4 digits or exactly 6 digits. # If the function is passed a valid PIN string, return true, else return false. # eg: # validate_pin("1234") == True # validate_pin("12345") == False # validate_pin("a234") == False def validate_pin(pin): l = list(pin) nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] if len(pin) == 0: return False elif len(l) != 4 and len(l) != 6: return False for i in range(len(l)): if l[i] not in nums: return False return True #List comprehension def validate_pin2(pin): return len(pin) in (4, 6) and pin.isdigit() # Write a function that when given a URL as a string, parses out just the # domain name and returns it as a string. For example: # domain_name("http://github.com/carbonfive/raygun") == "github" # domain_name("http://www.zombie-bites.com") == "zombie-bites" # domain_name("https://www.cnet.com") == "cnet" def domain_name(url): symbols = ['/', '.', ':'] prefix = ['www', 'http', 'https'] l = list(url) for x in symbols: while x in l: l.insert(l.index(x), '#') l.remove(x) m = ''.join(l) m = list(m.split('#')) for x in m: n = '' if n in m: m.remove(n) for x in prefix: while x in m: if x in prefix: m.remove(x) return m[0] # Some numbers have funny properties. For example: # 89 --> 8¹ + 9² = 89 * 1 # 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2 # 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51 # Given a positive integer n written as abcd... (a, b, c, d... being digits) # and a positive integer p # we want to find a positive integer k, if it exists, such as the sum of the # digits of n taken to the successive powers of p is equal to k * n. # In other words: # Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k # If it is the case we will return k, if not return -1. # Note: n and p will always be given as strictly positive integers def dig_pow(n, p): str_num = list(str(n)) for i in range(len(str_num)): str_num[i] = int(str_num[i]) prod = 0 i = 0 while i < len(str_num): prod += str_num[i]**p p += 1 i += 1 result = str(prod/n).split('.') if result[0] == '0': return -1 elif int(result[1]) > 0: return -1 else: return int(result[0]) # You are going to be given a word. Your job is to return the middle # character of the word. If the word's length is odd, return the middle character. # If the word's length is even, return the middle 2 characters. # #Examples: # Kata.getMiddle("test") should return "es" # Kata.getMiddle("testing") should return "t" # Kata.getMiddle("middle") should return "dd" # Kata.getMiddle("A") should return "A" def get_middle(s): if len(s) == 1: return s elif len(s) == 2: return s[:2] if len(s) % 2 != 0: return s[len(s)//2] else: return s[(len(s)//2)-1] + s[len(s)//2] # You have an array of numbers. # Your task is to sort ascending odd numbers but even numbers must be on their places. # Zero isn't an odd number and you don't need to move it. If you have an # empty array, you need to return it. # Example # sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] def sort_array(source_array): odds = list(filter(lambda x: x % 2 == 1, source_array)) odds.sort() j = 0 for i in range(len(source_array)): if source_array[i] % 2 == 1: source_array[i] = odds[j] j += 1 return source_array # There are n soldiers standing in a line. Each soldier is assigned a unique rating value. # You have to form a team of 3 soldiers amongst them under the following rules: # Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). # A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) # where (0 <= i < j < k < n). # Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). # Example 1: # Input: rating = [2,5,3,4,1] # Output: 3 # Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). # Example 2: # Input: rating = [2,1,3] # Output: 0 # Explanation: We can't form any team given the conditions. # Example 3: # Input: rating = [1,2,3,4] # Output: 4 # Constraints: # n == rating.length # 1 <= n <= 200 # 1 <= rating[i] <= 10^5 def numTeams(rating): '''I am so ashamed of this, give me some time to refactor T_T''' from itertools import permutations if rating == sorted(rating): return len(rating) perms = list(permutations(rating)) for i in range(len(perms)): perms[i] = perms[i][:3] l = list(filter(lambda x: x[0] < x[1] and x[1] < x[2], perms)) m = list(filter(lambda x: x[0] > x[1] and x[1] > x[2], perms)) l = list(filter(lambda x: rating.index(x[0]) < rating.index(x[1]), l)) l = list(filter(lambda x: rating.index(x[1]) < rating.index(x[2]), l)) l = list(filter(lambda x: rating.index(x[0]) < rating.index(x[1]), l)) l = list(filter(lambda x: rating.index(x[0]) < rating.index(x[2]), l)) print(l) m = list(filter(lambda x: rating.index(x[0]) < rating.index(x[2]), m)) m = list(filter(lambda x: rating.index(x[1]) < rating.index(x[2]), m)) m = list(filter(lambda x: rating.index(x[0]) < rating.index(x[1]), m)) m = list(filter(lambda x: rating.index(x[0]) < rating.index(x[2]), m)) print(m) result = [] for x in l: if x not in result: result.append(x) for x in m: if x not in result: result.append(x) return len(result) def num_teams(rating): '''More optimized solution for num_teams :)''' import pdb # pdb.set_trace() teams = 0 x = 0 while x <= len(rating)-2: y = x + 1 while y <= len(rating)-1: z = y + 1 while z < len(rating): if rating[x] < rating[y] and rating[y] < rating[z]: teams += 1 elif rating[x] > rating[y] and rating[y] > rating[z]: teams += 1 z += 1 y += 1 x += 1 print(teams) return teams # Given a collection of distinct integers, return all possible permutations. # Example: # Input: [1,2,3] # Output: # [ # [1,2,3], # [1,3,2], # [2,1,3], # [2,3,1], # [3,1,2], # [3,2,1] # ] def permute(nums): from itertools import permutations return permutations(nums) # Write a function to delete a node in a singly-linked list. You will not be given # access to the head of the list, instead you will be given access to the node to # be deleted directly. # It is guaranteed that the node to be deleted is not a tail node in the list. def deleteNode(linked_list, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next
from Classes import ComplexNumbers as cn while True: print("Complex calculator") print("Enter first real part and then complex part") fr = int(input()) fi = int(input()) print("Enter an operation: +, -, *, /, mag, conj") option = input() operation = None first = cn.CN(fr, fi) if(not (option == "mag" or option == "conj")): print("Enter second real part and the complex part") sr = int(input()) si = int(input()) second = cn.CN(sr, si) if(option == "+"): operation = first + second elif (option == "-"): operation = first - second elif (option == "*"): operation = first*second elif (option == "/"): operation = first/second print("Value of operation: " + operation.show()) elif(option == "mag"): operation = first.mag() print("Value of operation: " + operation) elif(option == "conj"): operation = first.conjugate() print("Value of operation: " + operation.show()) else: print("Wrong value of operation. Try Again")
print("Enter first name, last name and birthyear") data = input() name, lastName, birthYear = data.split(" ") print("First name: " + name , ", Last name: " + lastName + ", Year of birth: " + birthYear)
def read_file(): """ open and read file given for assignment two and return an array of a list of integers in the file """ thefile = open('C:/Documents and Settings/steven/repos/Python-Codes/Algo_One_Stanford/assignment_2_QuickSort.txt' , 'r') # initializing the array to be returned array = [] for line in thefile: # only take entries that has length greater than zero if len(line[:-1]) != 0: array.append(int(line[:-1])) return array #### for problem no.1 : counting no. of comparisons when first element is #### always chosen as pivots. # initializing global variable for no. of comparisons comparisons_1 = 0 def quicksort_one(array): """ a divide and conquer sorting algorithm that sort an array in ascending order by choosing the first element as pivot and partitioning the array input: any array with length n output: sorted array """ n = len(array) # keeping track the number of comparisons made between the # pivot and other elements in the array during the whole sorting process. global comparisons_1 # base case if n < 2: return array # recursive case else: # always choose the first element as pivot pivot = array[0] # idx keep track of the border between # elements smaller than pivot and those greater than pivot idx = 1 # jdx keep track of the border between partitioned part # and unpartitioned part for jdx in range(idx, n): # increment comparision comparisons_1 += 1 # the current checking element smaller than pivot if array[jdx] < pivot: # swap position with the idx element array[jdx], array[idx] = array[idx], array[jdx] # increment idx by one idx += 1 # place the pivot at the correct (final) position array[0], array[idx-1] = array[idx-1], array[0] #recursively using quicksort on part left and right of pivot return quicksort_one(array[:idx-1]) + [pivot] + quicksort_one(array[idx:]) the_array = read_file() quicksort_one(the_array) print comparisons_1 #### for problem no.2 : counting no. of comparisons when last element is #### always chosen as pivots. comparisons_2 = 0 def quicksort_two(array): """ a divide and conquer sorting algorithm that sort an array in ascending order by choosing the last element as pivot and partitioning the array input: any array with length n output: sorted array """ n = len(array) # keeping track the number of comparisons made between the # pivot and other elements in the array during the whole sorting process. global comparisons_2 # base case if n < 2: return array # recursive case else: # always choose the first element as pivot pivot = array[-1] # swap position of the pivot with the first element array[0], array[-1] = pivot, array[0] # idx keep track of the border between # elements smaller than pivot and those greater than pivot idx = 1 # jdx keep track of the border between partitioned part # and unpartitioned part for jdx in range(idx, n): # increment comparision comparisons_2 += 1 # the current checking element smaller than pivot if array[jdx] < pivot: # swap position with the idx element array[jdx], array[idx] = array[idx], array[jdx] # increment idx by one idx += 1 # place the pivot at the correct (final) position array[0], array[idx-1] = array[idx-1], array[0] #recursively using quicksort on part left and right of pivot return quicksort_two(array[:idx-1]) + [pivot] + quicksort_two(array[idx:]) the_array = read_file() quicksort_two(the_array) print comparisons_2 #### for problem no.3 : counting no. of comparisons when the "Median of Three" #### rule is used to choose pivots. from math import ceil comparisons_3 = 0 def quicksort_three(array): """ a divide and conquer sorting algorithm that sort an array in ascending order. The "median of three" (median of the first, last and the median of the element) is used to choose the pivot. input: any array with length n output: sorted array """ n = len(array) # keeping track the number of comparisons made between the # pivot and other elements in the array during the whole sorting process. global comparisons_3 # base case if n < 2: return array # recursive case else: #initialize a list to store the 3 elements that the pivot will be chosen from. pivot_candidates = [] # find the index of the median element med_index = (int(ceil(n/2.0))-1) # put the first, last and the middle element into the list pivot_candidates.append(array[0]) pivot_candidates.append(array[-1]) pivot_candidates.append(array[med_index]) # sort the the list sorted_candidates = sorted(pivot_candidates) # i know this is not a good idea... # always choose the middle element of the list as pivot pivot = sorted_candidates[1] # find the pivot index if pivot == array[0]: pivot_index = 0 elif pivot == array[-1]: pivot_index = -1 else: pivot_index = med_index # swap position of the pivot with the first element array[0], array[pivot_index] = pivot, array[0] # idx keep track of the border between # elements smaller than pivot and those greater than pivot idx = 1 # jdx keep track of the border between partitioned part # and unpartitioned part for jdx in range(idx, n): # increment comparision comparisons_3 += 1 # the current checking element smaller than pivot if array[jdx] < pivot: # swap position with the idx element array[jdx], array[idx] = array[idx], array[jdx] # increment idx by one idx += 1 # place the pivot at the correct (final) position array[0], array[idx-1] = array[idx-1], array[0] #recursively using quicksort on part left and right of pivot return quicksort_three(array[:idx-1]) + [pivot] + quicksort_three(array[idx:]) the_array = read_file() quicksort_three(the_array) print comparisons_3
import json import requests def pretty_print(data, indent=4): """ prints a python dictionary in more readable indented format. The default indent levels is set at four. """ if type(data) == dict: return json.dumps(data, indent=indent, sort_keys=True) else: print data def api_get_request(url): """ In this exercise, you want to call the last.fm API to get a list of the top artists in Spain. Once you've done this, return the name of the number 1 top artist in Spain. """ # this url specifically access data from website, pinpointing Spain as country. url = 'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&api_key=c0871d3a08f3a1a3525b9e2c3dd2ecd7&format=json' # extract data from url and assign it to variable named "data". data = requests.get(url).text # convert data to python dict format in order to be able to access data with keys. data = json.loads(data) # better readability pretty_print(data) # extract wanted info by penatrating multi-level dict in the data # index zero because topartist ranked first topartist_spain = data['topartists']['artist'][0]['name'] # return the top artist in Spain return topartist_spain
# Problem Set 1 [Paying off Credit Card Debt] from MIT Intro to CS 6.00 # Name:Vivian D # Time Spent: 45 mins #Problem 1, Paying the Minimum """ Use raw_input() to ask for the following three floating point numbers: 1. the outstanding balance on the credit card 2. annual interest rate 3. minimum monthly payment rate For each month, print the minimum monthly payment, remaining balance, principle paid in the format shown in the test cases below. All numbers should be rounded to the nearest penny. Finally, print the result, which should include the total amount paid that year and the remaining balance. format: Enter the outstanding balance on your credit card: 4800 Enter the annual credit card interest rate as a decimal: .2 Enter the minimum monthly payment rate as a decimal: .02 Month: 1 Minimum monthly payment: $96.0 Principle paid: $16.0 Remaining balance: $4784.0 Month: 2 Minimum monthly payment: $95.68 Principle paid: $15.95 Remaining balance: $4768.05 """ # Taking inputs from users balance = float(raw_input("Please enter the outstanding balance on your credit card: ")) annual_int_rate = float(raw_input("Please enter the annual credit card interest rate as a decimal: ")) min_pay_rate = float(raw_input("Please enter the minimum monthly payment rate as a decimal: ")) # defining initial value month = 0 tot_paid = 0 # computation of the payments for a calendar year for itr in range(1, 13): month += 1 min_payment = min_pay_rate * balance interest_paid = (annual_int_rate/12.0 * balance) principle_paid = min_payment - interest_paid balance -= principle_paid tot_paid += principle_paid + interest_paid print "Month: " + str(month) print "mininum monthly payment: " + "$" + str(round(min_payment, 2)) print "Principle paid: " + "$" + str(round(principle_paid, 2)) print "Your remaining balance: " + "$" + str(round(balance, 2)) print "RESULT: " print "Total Amount Paid: " + "$" + str(round(tot_paid, 2)) print "Your Remaining Balance: " + "$" + str(round(balance, 2))
n = 0 for n in range(10): print ("Perulangan for Python ke - ", (n)) n+=1 n = 0 while(n<=10): print ("Perulangan for Python ke - ", (n)) n+=1 n = 0 while(n<=10): print ("Perulangan for Python ke - ", (n)) n+=1 if n==1: break
import pandas as pd import math import csv # print 했을 때 다보이는 방법 pd.set_option("display.max_rows", 10000) path = "C:/workspaces/python-project/yong-in/data/" year = 2011 start = 4344 end = 6535 csv_path = path+str(year)+".csv" # 한글이 있어 오류가 생기므로 engine='python' 을 코드에 넣어줌 df = pd.read_csv(csv_path,header=1,engine='python') df_np = df.values for data in df_np: print(data)
''' For linked list 1->2->3->2->1, the code below first makes the list to be 1->2->3->2<-1 and the second 2->None, then make 3->None, for even number linked list: 1->2->2->1, make first 1->2->2<-1 and then the second 2->None, and lastly do not forget to make the first 2->None (If forget it still works while the idea behind is a little bit different). ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @return {boolean} def isPalindrome(self, head): if not head: return True #find mid node fast = slow = head while fast.next and fast.next.next: #set up fast speeds is twice to slow slow = slow.next fast = fast.next.next #reverse second half p = slow.next last = None slow.next = None #not needed, but clearer ''' last is before the second half (a none insert into the beginning of the second half ) 1->2->3->4->5->6->7 => none->5->6->7 then we can reverse the second half like reverse linked list problem ''' ''' <Stephen> def reverseLinkedListIterative(self, head): if not head or not head.next: return None preCurrent = None currentNode = head while currentNode: nextNode = currentNode.next currentNode.next = preCurrent preCurrent = currentNode #so after reversing the list. the preCurrent node is the first node of the reversed list.(iterative) currentNode = nextNode return preCurrent ''' while p: #p equals to currentNode above next = p.next p.next = last last = p #last equals to preCurrent above p = next #check palindrome #check palindrome p1 = last #since iterate last to the "last" node of the origin node, last is the last node of the original list p2 = head while p1 : if not (p1.val == p2.val): return False p1, p2 = p1.next, p2.next return True ''' #resume linked list(optional) p, last = last, None while p: next = p.next p.next = last last, p = p, next slow.next = last return p1 is None '''
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 01:20:14 2020 @author: Oshi """ class dummybank_API: def __init__(self): #assunimg 5 digit bank accoount number self.my_dict = {12345:1234, 22222:2345} #hardcoding the dictionary for testing self.account_number = None self.pin = None def enter_values(self,account_num,pin): #input from bank database or staff self.my_dict[account_num] = pin #not implemented in current code def check_valid_account(self,account_num): if(account_num in self.my_dict): print("Accepted\n") return True else: print("Swipe card again/enter number again\n") return False def check_pin(self,account_num,pin): if(self.my_dict[account_num]== pin): print("Correct Pin\n") return True else: print("invalid Pin - Enter again\n") return False
from random import * class Bag(): def __init__(self): self.data = [] print('Creating bag...') def add(self,item): self.data.append(item) print('Added an item to the bag') def removeItem(self,item): if item in self.data: self.data.remove(item) print('Removed an item from the bag') else: print('Could not remove, item not found in bag') def contains(self,item): if item in self.data: return True else: return False def numItems(self): return len(self.data) def grab(self): if self.data: print('Pulled an item from the bag') index = randrange(len(self.data)) return self.data[index] else: print('Bag is empty, cannot pull an item') def __str__(self): if self.data: return ', '.join(map(str,self.data)) def main(): #creating bag bag = Bag() #testing functions on empty bag bag.removeItem('h') bag.contains('h') bag.grab() print(bag.numItems()) #adding items to bag, then testing functions bag.add('h') bag.add(19) print(bag.numItems()) bag.contains('h') bag.__str__() print(bag.grab()) bag.removeItem(19) bag.contains(19) bag.__str__() if __name__ == '__main__': main()
# print the replacment fields in the order I want, otherwise it would replace # {} in the order of 0, 1, 2, 3, 4 , ..., #V this way flops it backwards #formatter ="{3} {2} {1} {0}" #V this way is standard formatter = "{} {} {} {}" # print the print(formatter.format(1, 2, 3, 4)) print(formatter.format("one", "two", "three", "four")) print(formatter.format(True, False, False, True)) print(formatter.format(formatter, formatter, formatter, formatter)) print(formatter.format( "Try your", "Own text here", "Maybe a poem", "Or a song about fear" )) print(formatter.format(3,2,1,0)) print() print() print() print()
# This line prints a string print("I will now count my chickens:") # This line prints a string and computation print("Hens", float(25 + 30 / 6)) # This line prints a string and computation print("Roosters", float(100 - 25 * 3 % 4)) # This line prints a string print("Now I will count the eggs:") # This line does computation print(float(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)) # This line prints a string print("Is it true that 3 + 2 < 5 - 7?") # This line prints a string and computation print(3 + 2 < 5 - 7) # This line prints a string and computation print("What is 3 + 2?", float(3 + 2)) # This line prints a string and computation print("What is 5 - 7?", float(5 - 7)) # This line prints a string print("Oh, that's why it's False.") # This line prints a string print("How about some more.") # This line prints a string and computation print("Is it greater?", 5 > -2) # This line prints a string and computation print("Is it greater or equal?", 5.0 >= -2.0) # This line prints a string and computation print("Is it less or equal?", 5 <= -2)
""" Utility used by the Network class to actually train. Based on: https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py """ from keras.datasets import mnist, cifar10 from keras.models import Sequential from keras.layers import Dense, Dropout from keras.utils.np_utils import to_categorical from keras.callbacks import EarlyStopping # Helper: Early stopping. early_stopper = EarlyStopping(patience=5) def get_cifar10(): """Retrieve the CIFAR dataset and process the data.""" # Set defaults. nb_classes = 10 batch_size = 64 input_shape = (3072,) # Get the data. (x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train = x_train.reshape(50000, 3072) x_test = x_test.reshape(10000, 3072) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 # convert class vectors to binary class matrices y_train = to_categorical(y_train, nb_classes) y_test = to_categorical(y_test, nb_classes) return (nb_classes, batch_size, input_shape, x_train, x_test, y_train, y_test) def get_mnist(): """Retrieve the MNIST dataset and process the data.""" # Set defaults. nb_classes = 10 batch_size = 128 input_shape = (784,) # Get the data. (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 # convert class vectors to binary class matrices y_train = to_categorical(y_train, nb_classes) y_test = to_categorical(y_test, nb_classes) return (nb_classes, batch_size, input_shape, x_train, x_test, y_train, y_test) def compile_model(network, nb_classes, input_shape): """Compile a sequential model. Args: network (dict): the parameters of the network Returns: a compiled network. """ # Get our network parameters. nb_layers = network['nb_layers'] nb_neurons = network['nb_neurons'] activation = network['activation'] optimizer = network['optimizer'] model = Sequential() # Add each layer. for i in range(nb_layers): # Need input shape for first layer. if i == 0: model.add(Dense(nb_neurons, activation=activation, input_shape=input_shape)) else: model.add(Dense(nb_neurons, activation=activation)) model.add(Dropout(0.2)) # hard-coded dropout # Output layer. model.add(Dense(nb_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model def train_and_score(network, dataset): """Train the model, return test loss. Args: network (dict): the parameters of the network dataset (str): Dataset to use for training/evaluating """ if dataset == 'cifar10': nb_classes, batch_size, input_shape, x_train, \ x_test, y_train, y_test = get_cifar10() elif dataset == 'mnist': nb_classes, batch_size, input_shape, x_train, \ x_test, y_train, y_test = get_mnist() model = compile_model(network, nb_classes, input_shape) model.fit(x_train, y_train, batch_size=batch_size, epochs=10000, # using early stopping, so no real limit verbose=0, validation_data=(x_test, y_test), callbacks=[early_stopper]) score = model.evaluate(x_test, y_test, verbose=0) return score[1] # 1 is accuracy. 0 is loss.
from matplotlib import pyplot as matplot from matplotlib import animation as matani def plotfun(z1,z2,maxy): fig = matplot.figure() axes = matplot.axes(xlim=(0,len(z1)), ylim = (0,maxy)) line, = axes.plot([],[], lw=2) def init(): line.set_data([], []) return line, def animate(j): x = z1[1:j] y = z2[1:j] line.set_data(x,y) return line, anim = matani.FuncAnimation(fig, animate, init_func=init, frames = len(z1), interval=20, blit=True) matplot.show()