text
stringlengths
37
1.41M
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'} newId = input('请输入新的学号') info['id'] = int(newId) print('修改之后的id为:%d'%info['id'])
# 定义类 class Demo: # 定义构造方法 def __init__(self, obj): self.data = obj[:] # 定义索引、分片运算符重载方法 def __getitem__(self, index): return self.data[index] # 创建实例对象,用列表初始化 x = Demo([1, 2, 3, 4]) print(x[1]) # 索引返回单个值 print(x[:]) # 分片返回全部的值 print(x[:2]) # 分片返回部分值 for num in x: # for循环迭代 print(num)
a=10 b=20 #判断a and b if ( a and b ): print("1——变量 a 和 b 都为 true") else: print("1——变量 a 和 b 有一个不为 true") # 判断a or b if ( a or b ): print("2——变量 a 和 b 都为 true,或其中一个变量为 true") else: print("2——变量 a 和 b 都不为 true") # 修改变量 a 的值 a = 0 if ( a and b ): print("3——变量 a 和 b 都为 true") else: print("3——变量 a 和 b 有一个不为 true") if ( a or b ): print("4——变量 a 和 b 都为 true,或其中一个变量为 true") else: print("4——变量 a 和 b 都不为 true") # 判断not( a and b ) if not( a and b ): print("5——变量 a 和 b 都为 false,或其中一个变量为 false") else: print("5——变量 a 和 b 都为 true")
from collections import Counter def all_uniqs(input_str: str): ctr = Counter(input_str) # print(ctr) # print(type(ctr)) for k,v in ctr.items(): # print(k,v) if v >1: return False return True def all_uniqs_no_datastruct(x:str): sorted_x = sorted(x) # print(type(sorted_x)) # print(sorted_x) n = len(x) for i in range(1,n): if sorted_x[i-1]==sorted_x[i]: return False return True if __name__ == "__main__": # all_uniqs('12323') # all_uniqs_no_datastruct('12323') inputs =["","aaasodkc", "abbccdcss", "aaa", "b", "bdes"] for x in inputs: print(f"Input {x} result:{all_uniqs(x)} same as {all_uniqs_no_datastruct(x)}")
#!/usr/bin/python3 """ Task 12 module """ class Student: """ a class that students don't attend GET IT?!?! """ def __init__(self, first_name, last_name, age): ''' in it ''' self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): ''' retrieves dictionary representation of student ''' if type(attrs) is list and all(isinstance(i, str) for i in attrs): newd = dict() for key in list(self.__dict__.keys()): if key in attrs: newd[key] = self.__dict__[key] return newd else: return self.__dict__
#!/usr/bin/python3 """ Task 7 Module """ import json def save_to_json_file(my_obj, filename): """ Writes object to text file using json representation """ with open(filename, 'w', encoding='utf-8') as f: json.dump(my_obj, f)
#!/usr/bin/python3 '''2-matrix_divided docstring''' def matrix_divided(matrix, div): '''Divides a matrix''' if not all(isinstance(li, list) for li in matrix): raise TypeError("matrix must be a matrix (li" "st of lists) of integers/floats") for li in matrix: for x in li: if type(x) not in [int, float]: raise TypeError("matrix must be a matrix (li" "st of lists) of integers/floats") for li in matrix: if len(li) is not len(matrix[0]): raise TypeError("Each row of the matrix must have the same size") if type(div) not in [int, float]: raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") matr = [[None] * len(matrix[0]) for x in range(len(matrix))] for row in range(len(matrix)): for col in range(len(matrix[row])): matr[row][col] = float("{:.2f}".format((matrix[row][col] / div))) return matr
#!/usr/bin/python3 def uniq_add(my_list=[]): sum = 0 if (len(my_list) == 0): return sum new1 = my_list.copy() new1.sort() sum = new1[0] if (len(my_list) == 1): return sum for i in range(1, len(new1)): if new1[i] == new1[i - 1]: continue else: sum += new1[i] return sum
# Note - this will work for Python 2.7, for Python 3 you seem to need to make the list indices integers rather than floats. def median(l): l.sort() if len(l) % 2 == 1: return l[len(l)/2] else: return (l[len(l)/2]+l[len(l)/2 -1])/2.0 #Python 3 version: #def median(l): #l.sort() #if len(l) % 2 == 1: #return l[int(len(l)/2)] #else: #return (l[(len(l)/2)]+l[int(len(l)/2 -1)])/2.0
''' Base class for all tree types, to ensure operations have reasonable guarantees about what's available to use. ''' class Tree: def insert(self, pos, value): ''' Insert a child to the tree with string "value" at position "pos" ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree must define self.insert(pos, value)") def delete(self, pos): ''' Mark a character in a tree as deleted ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree must define self.delete(pos)") def get(self, pos, hash): ''' Return the subtree with hash "hash" from position "pos" ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree must define self.get(pos, hash)") def mark(self, pos, marker): ''' Set a marker on a position ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree must define self.mark(pos, marker)") def __len__(self): ''' Return the length of the internal immutable string ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree must define self.__len__()") # The following are not necessary for Instructions, but are # nice, and may be relied upon by other stuff in the future def markers(self): ''' Returns a dict (keyed on position) of dict[totaltype] = marker. ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree should define self.markers()") def children(self): ''' Returns a dict (keyed on position) of sorted child hash lists. ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree should define self.children()") def flatten(self): ''' Returns a single-level tree that is display-equivalent to self. ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree should define self.flatten()") def trace(self, pos): ''' Given a position in the flat text, compute an (address, position) pair. ''' raise NotImplmentedError("Subclasses of ConcurrenTree.tree.Tree should define self.flatten()")
# By Matthew Thorburn # for EEE4120F Yoda project # User can guess the password in this program, also used for generating target hashes import hashlib import time import os #TargetHash = "1a1dc91c907325c69271ddf0c944bc72" # pass TargetHash = "76a2173be6393254e72ffa4d6df1030a" # passwd #TargetHash = "d79096188b670c2f81b7001f73801117" # passw CHARACTERS = range(97,122) #a-z MAX_LENGTH = 7 def hash(password): global counter, begin counter+=1 hashed = hashlib.md5(password.encode('utf-8')) # need to encode password to 'utf-8' format for md5 to hash nicely. print(hashed.hexdigest()) # can view outputted hash of guessed word if (hashed.hexdigest() == TargetHash): #checks against target end = time.clock() #end timer print("Correct Password found: "+password) print(f"it took you {counter} guesses") print(f"it took: {(end-begin)} seconds") os._exit(1) #ends program else: print("that was not correct") def start(): global begin begin = time.clock() #start timer while(1): guess = input("please enter a password \n") #user can manually guess the password. hash(guess) #check password #initiate global values begin = 0 counter =0 start()
#!/usr/bin/env python # coding: utf-8 # In[1]: x=input('Enter a word: ') x=x[::-1] print(x) # In[ ]:
__author__ = 'pratibh' dict={1:{1:'something',2:'nothing'}} for key,value in dict.items(): print(key) print(value) print("******") for k,v in value.items(): print(k) print(v)
print("enter the following operator") print("1. +") print("2. -") print("3. *") print("4. /") a = input() print("enter the first digit") b = int(input()) print("enter the second digit") c = int(input()) if a == "+" : if b== 56 and c==9: print(77) else: print("sum =",b+c) elif a == "-": print("substraction =",b-c) elif a == "*": if b==45 and c==3: print(555) else: print("muliplicatrion =",b*c) else: if b==56 and c==6: print(4) else: print("division =",b/c)
a = raw_input("Enter a String : ") count = 0 for i in range(0,len(a)): if (a[i]=="a" or a[i]=="e" or a[i]=="o" or a[i]=="u" or a[i]=="i"): count = count+1 print count
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This is a base class for manipulating all sqlite databases. """ #pragma pylint=off # Credits __author__ = 'George Flanagin' __copyright__ = 'Copyright 2017 George Flanagin' __credits__ = 'None. This idea has been around forever.' __version__ = '1.0' __maintainer__ = 'George Flanagin' __email__ = 'me+git@georgeflanagin.com' __status__ = 'continual development.' __license__ = 'MIT' import typing from typing import * import globaldata g = globaldata.GlobalData() class Ship: pass class Ship: TYPES = [ 'pt', 'barge', 'ferry', 'minesweeper', 'destroyer', 'freighter', 'liner', 'submarine', 'tanker', 'supertanker', 'transport', 'cruiser', 'battleship', 'carrier' ] def __init__(self, **kwargs:dict) -> None: """ Build a ship of a given type for a player. """ self.ship_type = kwargs.get('ship_type') self.location = kwargs.get('location') self.owner = kwargs.get('owner') self.civilians = kwargs.get('civilians', 0) self.military = kwargs.get('military', 0) self.fuel = kwargs.get('ore', 0)
# name = input('Tell me your name:') # age = input('...and your age:') # print(name, 'you are', age) # Calculations - need to convert input to a number # inputs automatically gets stored as a string # Calculate the area of a circle (piR^2) radius = input('Enter the radius of your circle (m):') area = 3.142*int(radius)**2 print('The area of your circle is:', area)
grid = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "] ] locationGrid = [ ["0,0", "0,1", "0,2"], ["1,0", "1,1", "1,2"], ["2,0", "2,1", "2,2"] ] player = 1 line = " ------------- " def printLine(): print(line) def printGrid(grid): printLine() textGrid = " | " for r in range(3): for c in range(3): textGrid = textGrid + grid[r][c] + " | " if r < 2: textGrid = textGrid + "\n" + " | " print(textGrid) printLine() def informGameOver(victor): if victor == 0: print("No further moves can be made.") else: print("Player " + str(victor) + " has won the game!") printGrid(grid) exit(0) def isPlayerEntry(entry): if entry == 'X': return True if entry == "O": return True return False def isUncoupied(x, y): if grid[x][y] == " ": return True return False def isValidLocation(entry): isValidCoords = False for row in locationGrid: for cell in row: if cell == entry: isValidCoords = True if isValidCoords: return isUncoupied(int(entry[0]), int(entry[2])) def threeInARow(): for row in grid: if row[0] == row[1] == row[2] and isPlayerEntry(row[0]): return True return False def threeInAColumn(): for c in range(3): if grid[0][c] == grid[1][c] == grid[2][c] and isPlayerEntry(grid[0][c]): return True return False def threeInADiagonal(): if grid[0][0] == grid[1][1] == grid[2][2] and isPlayerEntry(grid[1][1]): return True if grid[0][2] == grid[1][1] == grid[2][0] and isPlayerEntry(grid[1][1]): return True return False def gridIsFull(): for r in range(3): for c in range(3): if grid[r][c] == " ": return False return True def checkForGameOver(): # three in a row if threeInARow(): informGameOver(player) # three in a column if threeInAColumn(): informGameOver(player) # three in a diagonal if threeInADiagonal(): informGameOver(player) if gridIsFull(): informGameOver(0) # Play the game print("Welcome to Tic Tac Toe." + "\n") print("Players have already been assigned markings.") print("Player 1's moves will be maked with an X.") print("Player 2's moves will be maked with an O.") print("\n") print("Moves are made by specifying the location in the grid where a player wants their mark" + "\n") print("The grid locations are as follows") printGrid(locationGrid) print("Player " + str(player) + ", please make the first move." + "\n") while not gridIsFull(): print("Player " + str(player) + ", enter desired location: ") move = input().strip() while not isValidLocation(move): print("Please enter an unoccupoed desired location as it is in this grid:") printGrid(locationGrid) move = input().strip() moveX = int(move[0]) moveY = int(move[2]) if player == 1: grid[moveX][moveY] = "X" else: grid[moveX][moveY] = "O" locationGrid[moveX][moveY] = " " printGrid(grid) checkForGameOver() if player == 1: player = 2 else: player = 1
""" This code simulates the Monty Hall gameshow, in which contestants try to guess which of 3 closed doors contains a cash prize. The odds of choosing the correct door are 1 in 3. As a twist, the host of the show occasionally opens a door after a contestant makes a choice. This door is always one of the two the contestant did not pick, and is also always one of the losing doors. Then, the contestant has the option of keeping the original choice, or swtiching to the other unopened door. Is there any benefit to switching doors?""" import numpy as np def run_sim(nsim=1): sims = simulate_prizedoor(nsim) guesses = simulate_guess(nsim) goatdoors = goat_door(sims, guesses) newguess = switch_guess(guesses, goatdoors) # Run without switching the guess noswitch = win_percentage(guesses, sims) print("Win percentage no switch:", noswitch) # Run with switching the guess switch = win_percentage(newguess, sims) print("Win percentage with switch:", switch) def simulate_prizedoor(nsim=3): """ Generate a random array of 0s, 1s, and 2s that represent the location of the prize""" return np.random.randint(0, 3, (nsim)) def simulate_guess(nsim=3): """ Simulate the contestant's guesses for nsim simulations""" guesses = np.random.randint(0, 3, (nsim)) return guesses def goat_door(sims, guesses): """Simulate the opening of a "goat door" that doesn't contain the prize, and is different from the contestant's guess.""" # Remove the prize door from the list of eligible goat doors. x = [] for si in sims: results = [0, 1, 2] if si in results: results.remove(si) x.extend([results]) # Remove the contestant's guess from the list of eligible goat doors. options = [] goatdoor = [] for gu in range(0, len(guesses)): if guesses[gu] in x[gu]: x[gu].remove(guesses[gu]) options.extend([x[gu]]) goatdoor.extend(np.random.choice(options[gu], 1)) return goatdoor def switch_guess(guesses, goatdoors): """This stragey always switches the guess after a door is opened""" choices = [0, 1, 2] newguess = [] for i in range(0, len(guesses)): used = [guesses[i], goatdoors[i]] newguess.append(list(set(choices) - set(used))) return newguess def win_percentage(guesses, prizedoors): """Calculate the percent of times that a simulation of guesses is correct.""" win_count = 0 for i in range(0, len(guesses)): if guesses[i] == prizedoors[i]: win_count = win_count + 1 win_percent = win_count / len(guesses) * 100 return round(win_percent, 2)
class Solution(object): def helper(self, sets, index,nums): if index == len(nums): return sets num = nums[index] new_sets = [] for old_set in sets: new_set = [n for n in old_set] new_set.append(num) new_sets.append(new_set) sets = sets + new_sets return self.helper(sets, index+1,nums) def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ return self.helper([[]],0,nums) # sets = [[]] # for i in range(len(nums)): # new_sets = [] # for old_set in sets: # new_set = [n for n in old_set] # new_set.append(nums[i]) # new_sets.append(new_set) # for new_set in new_sets: # sets.append(new_set) # return sets s = Solution() nums = [1,2,3,4] s.subsets(nums) #s = [[]] #s2 = [[1]] #for item in s2: # s.append(item) #print(s)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root is None: return True return self.isMirror(root.left, root.right) def isMirror(self,t1, t2): if t1 is None and t2 is None: return True if t1 is None or t2 is None: return False if t1.val != t2.val: return False return self.isMirror(t1.left, t2.right) and self.isMirror(t1.right, t2.left)
from graphviz import Graph class Stack: def __init__(self): self.items = [] def empty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def top(self): return self.items[-1] def size(self): return len(self.items) class Queue: def __init__(self): self.items = [] def empty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) #邻接矩阵表示的图 class MGraph: def __init__(self, vexs=[], matrix=[[]],arcnum=0): self.vexnum = len(vexs) self.arcnum = arcnum self.vexs = vexs self.matrix = matrix self.count = 1 self.visited = [False for i in range(self.vexnum)] self.low = [0 for i in range(self.vexnum)] self.order = [0 for i in range(self.vexnum)] self.m = [0 for i in range(self.vexnum)] self.pre = [0 for i in range(self.vexnum)] self.articul = [] self.count = 1 def reset(self): self.count = 1 self.visited = [False for i in range(self.vexnum)] self.low = [0 for i in range(self.vexnum)] self.order = [0 for i in range(self.vexnum)] self.m = [0 for i in range(self.vexnum)] self.pre = [0 for i in range(self.vexnum)] self.articul = [] def findArticul(self): self.reset() self.visited[0] = True self.order[0] = 1 for v in range(self.vexnum): if self.matrix[0][v] != 0: self.DFSArticul(v) break if self.count < self.vexnum: self.articul.append(0) for i in range(v + 1,self.vexnum): if self.matrix[0][i] != 0 and self.visited[i] == False: self.DFSArticul(i) self.articul = list(set(self.articul)) print(" ".join(str(i) for i in self.articul)) def DFSArticul(self,v): #非递归版 S = Stack() self.visited[v] = True self.count+=1 self.m[v] = self.count self.order[v] = self.count S.push(v) while not S.empty(): v = S.top() w = 0 while w < self.vexnum: if self.matrix[v][w] != 0: #w 是 v 的邻接顶点 if self.visited[w] == False: self.visited[w] = True self.pre[w] = v #v 是 w 的父母 self.count+=1 self.order[w] = self.count self.m[w] = self.count S.push(w) break elif self.order[w] < self.m[v]: self.m[v] = self.order[w] w+=1 if w == self.vexnum: #v 遍历完毕 S.pop() self.low[v] = self.m[v] w = v v = self.pre[w] #w 遍历完成,v 是父母 if v != 0: #根顶点是否为关节点不采用此判断方式 if self.low[w] < self.m[v]: self.m[v] = self.low[w] if self.low[w] >= self.order[v]: self.articul.append(v) #邻接表表示的图 class ALGraph: def __init__(self, vexs=[], matrix=[[]],arcnum=0): self.vexnum = len(vexs) self.arc = [[] for i in range(self.vexnum)] self.vexs = vexs self.visited = [False for i in range(self.vexnum)] for i in range(self.vexnum): for j in range(self.vexnum): if matrix[i][j] != 0: self.arc[i].append(j) def firstNbr(self,v): #v 的第一个邻顶 if self.arc[v] != []: return self.arc[v][0] else: return -1 #-1 表示无邻顶 def nextNbr(self,v,w): #v 的 w 的下一个邻顶 for i in self.arc[v]: if i > w: return i return -1 def BFSGetDist(self,v0=0): #搜索无权图其他点到 v0 的最短路径 Q = Queue() v = v0 path = [[v] for i in range(self.vexnum)] self.visited[v] = True Q.enqueue(v) while not Q.empty(): v = Q.dequeue() for w in self.arc[v]: if self.visited[w] == False: self.visited[w] = True path[w] = path[v] + [w] Q.enqueue(w) for v in range(self.vexnum): if v != v0: print(len(path[v]) - 1,end=' ') print("->".join(str(i) for i in path[v])) vg = Graph('图及其应用') with open('case1.txt') as case: n = int(case.readline()) #n 表示图中的顶点数 for i in range(n): vg.node(name=str(i),color='red') vexs = [str(i) for i in range(n)] matrix = [[0] * n for i in range(n)] edges = case.readlines() arcnum = len(edges) for edge in edges: v1,v2 = map(int, edge.split()) matrix[v1][v2] = 1 matrix[v2][v1] = 1 #无向图 vg.edge(str(v1),str(v2),color='blue') g = MGraph(vexs,matrix,arcnum) alg = ALGraph(vexs,matrix,arcnum) g.findArticul() alg.BFSGetDist(0) vg.view()
""" Use example code if you want to use the Zora robot 1 - You will need to install Python 2.7 - 32 bits (be sure that it is the 32 bits version) You can find the installer here: https://www.python.org/downloads/release/python-2714/ 2 - After installing Python, install the naoqi executable also in Library: pynaoqi-python-2.7-naoqi-x.x-win32.exe 3 - Everything should work if you run Alice.py. """ import time import json from Zora import Zora class Alice: def __init__(self): self.answers = [] # This depends on what Zora robot you have. Make sure the robot is connected (through UTP-cable). self.ZORA_IP = "169.254.58.192" # self.ZORA_IP = "169.254.132.185" # Other Zora robot (of the two) IP. So if you can't connect, uncomment this print("Starting Program for Alice") # Connect to Zora self.zora = Zora(self) self.run() def run(self): self.zora.talk("Hey, I can talk.") self.conversation() self.stand() def conversation(self): # The Zora robot has built-in text to speech (TTS): self.zora.talk("I will ask a question. You can answer me by responding with yes or no. Are you ready?") # The Zora robot also has a (limited by one word) built in speech to text (STT): self.recognizedWord = "" vocabulary = ["yes", "no"] # The range of words that Zora should be able to recognize. For this example this is only yes or no. self.zora.recognize(vocabulary) self.answers = self.recognizedWord print(self.recognizedWord) if self.answers == "yes": self.zora.talk("You said yes") elif self.answers == "no": self.zora.talk("You said no") else: self.zora.talk("I didn't hear you say anything.") def stand(self): # Find more at: http://doc.aldebaran.com/2-1/naoqi/motion/alrobotposture.html self.zora.goToPosture("Crouch") # self.posture_service.goToPosture("Stand") def onReceivedWord(self, word): if(word[1] > 0.3): self.recognizedWord = word[0] Alice()
#!/usr/bin/python3 import platform Windows = platform.system() == 'Windows' def cc_intersection(P0, P1, r0, r1): """ Circle-Circle Intersection P0, P1 are coordinates of circle centers r0, r1 are the radii of said circles Returns ([x1,y1],[x2,y2]) """ from math import sqrt, fabs P2 = [None,None] P3_1 = [None,None] P3_2 = [None,None] d = sqrt((P0[0]-P1[0])**2+(P0[1]-P1[1])**2) a = (r0**2-r1**2+d**2)/(2*d) h = sqrt(fabs(r0**2-a**2)) P2[0] = P0[0]+a*(P1[0]-P0[0])/d P2[1] = P0[1]+a*(P1[1]-P0[1])/d P3_1[0] = P2[0]+h*(P1[1]-P0[1])/d P3_1[1] = P2[1]-h*(P1[0]-P0[0])/d P3_2[0] = P2[0]-h*(P1[1]-P0[1])/d P3_2[1] = P2[1]+h*(P1[0]-P0[0])/d return P3_1, P3_2 def calc_center(p): """ Calculate Center p is a list of intersection points this function turns those points into lines according to y=ax+b raises Exception when the lines don't intersect returns [y,x] """ # lines are sets of two coordinates through which the line travels # eg. l1 = [[1,3],[4,6]] l1 = p[0] l2 = p[1] xdiff = (l1[0][0]-l1[1][0], l2[0][0]-l2[1][0]) ydiff = (l1[0][1]-l1[1][1], l2[0][1]-l2[1][1]) def det(a, b): return a[0]*b[1]-a[1]*b[0] div = det(xdiff, ydiff) if div == 0: raise Exception('Lines don\'t intersect') d = (det(*l1), det(*l2)) x = det(d, xdiff)/div y = det(d, ydiff)/div return [int(round(21-y)), int(round(x))] def location(P0, P1, P2, r0, r1, r2): """ Location P0, P1, P2 are lists containing coordinates of circle centers r0, r1, r2 are integers describing the radii of the circles calls cc_intersection to determine the intersection if three points within p0, p1 and p2 are equal return said point as [x,y] else calculate the center of those points """ p0 = cc_intersection(P0, P1, r0, r1) p1 = cc_intersection(P1, P2, r1, r2) p2 = cc_intersection(P2, P0, r2, r0) p = [p0, p1, p2] for i in range(3): for j in range(2): for k in range(2): p[i][j][k] = round(p[i][j][k]) for i in range(2): for j in range(2): for k in range(2): if p[0][i] == p[1][j] == p[2][k]: return p[0][i] else: return calc_center(p) def dBm_to_m(MHz, dBm): """ Decibel-meter to Meter MHz is an int describing the frequency of the wifi access point in MHz dBm is an int describing the signal strength of said access point in dBm returns the meters as int """ from math import log10 global Windows if platform.system() == 'Windows': dBm = (dBm/2)-100 # FSPL is the factor for the loss of signal strength innate to wifi FSPL = 27.55 meters = round((10**((FSPL-(20*log10(MHz))-dBm)/20))*0.5, 2) if meters > 50: menu() return meters def get_dBm(APName): """ Get Signal Strength APName is a string containing the name of the access point of which you want the signal strength This function runs a command on your system based on the detected Operating System to scan for the access point The result of the scan is written to a file and then read as a list to easily split the contents we need: signal strength and frequency returns the signal strength and frequency as integers """ import subprocess global Windows if platform.system() == 'Windows': netscan = subprocess.run('netsh wlan show networks mode = bssid', shell=True, stdout=subprocess.PIPE) f = open('netscan.txt', 'w') f.write(netscan.stdout.decode('utf-8')) f.close() else: subprocess.run(['sudo iwlist wlo1 scan | grep -i -B 5 {} > ./netscan.txt'.format(APName)], shell=True) f = open('netscan.txt') lines = f.readlines() f.close() frequency = 0 signal = 0 if platform.system() == 'Windows': data = [] for l in range(len(lines)): lines[l] = lines[l].strip() #if 'V1F4' in l: # data.append(l[l.index(l):l.index(l)+6]) if 'Radio type' in lines[l]: freq = lines[l].split(':') freq = freq[1].strip() if freq == '802.11ac': frequency = 5230 else: frequency = 2470 if 'Signal' in lines[l]: sig = lines[l].split(':') sig = sig[1].strip() sig = sig[:-1] signal = int(sig) else: for l in range(len(lines)): lines[l] = lines[l].strip() if 'Frequency:' in lines[l]: freq = lines[l].split(':') freq = freq[1].split(' ') frequency = int(float(freq[0])*1000) if 'Signal' in lines[l]: sig = lines[l].split('=') sig = sig[-1].split(' ') signal = int(sig[0]) return frequency, signal def menu(): """ Menu The same as Main() but Menu() because it used to be a menu in days past asking for names and coordinates of access points In this function you can set the names and coordinates of the access points P0, P1, P2 are the coordinates: [x,y] AP0, AP1, AP2 are the names as string """ print('Scanning...') from termcolor import colored P0 = [14,8] P1 = [2,8] P2 = [10,2] AP0 = 'v1f4ap1' AP1 = 'v1f4ap2' AP2 = 'v1f4ap3' class AccessPointError(Exception): """ An exception to raise when something is not quite right with the access points does nothing else""" pass def get_apNames(): """ Calls get_apCoords for some inexplicable reason... this function might have done something at some point, but it no longer does I don't really have a clue :/""" nonlocal AP0, AP1, AP2 return get_apCoords() def get_apCoords(): """ Get your location uses nonlocal variables as seen below raises (and catches) AccessPointError when any of the access points have the same coordinates catches NameError when something was entered the wrong way, this dates back to when it was a menu calls get_dBm, dBm2m to get the users location returns (and prints) the location of the user as [y,x] """ nonlocal AP0, AP1, AP2, P0, P1, P2 try: if P0 == P1 or P1 == P2 or P2 == P0: raise AccessPointError else: dbP0 = get_dBm(AP0) dbP1 = get_dBm(AP1) dbP2 = get_dBm(AP2) r0 = dBm_to_m(dbP0[0], dbP0[1]) r1 = dBm_to_m(dbP1[0], dbP1[1]) r2 = dBm_to_m(dbP2[0], dbP2[1]) r0 = round(r0, 2) r1 = round(r1, 2) r2 = round(r2, 2) print('\n======[Location Data]=======') print('AP1: {:>4} MHz, {:>3} dBm, distance: {:1.2f}m'.format(dbP0[0], dbP0[1], r0*2)) print('AP2: {:>4} MHz, {:>3} dBm, distance: {:1.2f}m'.format(dbP1[0], dbP1[1], r1*2)) print('AP3: {:>4} MHz, {:>3} dBm, distance: {:1.2f}m'.format(dbP2[0], dbP2[1], r2*2)) l = location(P0, P1, P2, r0, r1, r2) print('You are at: {}'.format(l)) return l # except NameError as e: # print(e) # print(colored('Wrong format', 'red')) # get_apCoords() except AccessPointError: print(colored('Something is wrong with the Access Points coordinates, please re-enter', 'red')) get_apCoords() return get_apNames()
import json from datetime import datetime DEGREE_SYBMOL = u"\N{DEGREE SIGN}C" def format_temperature(temp): """Takes a temperature and returns it in string format with the degrees and celcius symbols. Args: temp: A string representing a temperature. Returns: A string contain the temperature and "degrees celcius." """ temp = str(temp) DEGREE_SYBMOL = u"\N{DEGREE SIGN}C" return f"{temp}{DEGREE_SYBMOL}" def convert_date(iso_string): """Converts and ISO formatted date into a human readable format. Args: iso_string: An ISO date string.. Returns: A date formatted like: Weekday Date Month Year """ d = datetime.strptime(iso_string, "%Y-%m-%dT%H:%M:%S%z") return d.strftime("%A %d %B %Y") def convert_f_to_c(temp_in_farenheit): """Converts an temperature from farenheit to celcius Args: temp_in_farenheit: integer representing a temperature. Returns: An integer representing a temperature in degrees celcius. """ cel = round((((temp_in_farenheit - 32) * 5) / 9),1) return cel def calculate_mean(total_sum, num_items): """Calculates the mean. Args: total: integer representing the sum of the numbers. num_items: integer representing the number of items counted. Returns: An integer representing the mean of the numbers. """ mean = round(total_sum / num_items, 1) return mean def days_in_data(len_dict): """Calculates the number of days in the formatted json data file. Args: len_dict: integer representing the number of days in the forecast. Returns: A list for the number of days in the weather forecast file. """ count_day = 0 days_list = [] for i in range(len_dict): days_list.append(count_day) count_day += 1 return (days_list) def process_weather(forecast_file): """Converts raw weather data into meaningful text. Args: forecast_file: A string representing the file path to a file containing raw weather data. Returns: A string containing the processed and formatted weather data. """ # Load json data file with open(forecast_file) as json_file: json_data = json.load(json_file) # Set Variables, Dictionaries and Lists days_list = [] temp_dict = {} daily_dict = {} num_items = 0 total_sum_min = 0 total_sum_max = 0 days = len(json_data['DailyForecasts']) days_list = days_in_data(days) t_temp_min = 100 t_temp_max = 0 # Pull through the data for day in days_list: num_items += 1 date = convert_date(json_data['DailyForecasts'][day]['Date']) min_temp = convert_f_to_c(json_data['DailyForecasts'][day]['Temperature']['Minimum']['Value']) total_sum_min += min_temp max_temp = convert_f_to_c(json_data['DailyForecasts'][day]['Temperature']['Maximum']['Value']) total_sum_max += max_temp day_desc = json_data['DailyForecasts'][day]['Day']['LongPhrase'] chance_rain_day = json_data['DailyForecasts'][day]['Day']['RainProbability'] night_desc = json_data['DailyForecasts'][day]['Night']['LongPhrase'] chance_rain_night = json_data['DailyForecasts'][day]['Night']['RainProbability'] if min_temp < t_temp_min: t_temp_min = min_temp t_temp_mindate = date else: pass if max_temp > t_temp_max: t_temp_max = max_temp t_temp_maxdate = date else: pass daily_dict[day] = [date, min_temp, max_temp, day_desc, chance_rain_day, night_desc, chance_rain_night] # 0 1 2 3 4 5 6 # print(temp_dict) # print(daily_dict) # Calculate Minimum, Maximum and Mean temperatures mean_min = format_temperature(calculate_mean(total_sum_min, num_items)) # print(mean_min) mean_max = format_temperature(calculate_mean(total_sum_max, num_items)) # print(mean_max) # Format Minimum and Maximum temperatures min_temp_format = format_temperature(t_temp_min) max_temp_format = format_temperature(t_temp_max) ############################################################################################## # Combine string messages to return to user str_Output = "" Output_gen1 = (f"{num_items} Day Overview\n") Output_gen2 = (f" The lowest temperature will be {min_temp_format}, and will occur on {t_temp_mindate}.\n") Output_gen3 = (f" The highest temperature will be {max_temp_format}, and will occur on {t_temp_maxdate}.\n") Output_gen4 = (f" The average low this week is {mean_min}.\n") Output_gen5 = (f" The average high this week is {mean_max}.\n") str_Output = Output_gen1 + Output_gen2 + Output_gen3 + Output_gen4 + Output_gen5 for key, value in daily_dict.items(): Output_daily0 = ("\n") Output_daily1 = (f"-------- {value[0]} --------\n") Output_daily2 = (f"Minimum Temperature: {format_temperature(value[1])}\n") Output_daily3 = (f"Maximum Temperature: {format_temperature(value[2])}\n") Output_daily4 = (f"Daytime: {value[3]}\n") Output_daily5 = (f" Chance of rain: {value[4]}%\n") Output_daily6 = (f"Nighttime: {value[5]}\n") Output_daily7 = (f" Chance of rain: {value[6]}%\n") str_Output = str_Output + Output_daily0 + Output_daily1 + Output_daily2 + Output_daily3 + Output_daily4 + Output_daily5 + Output_daily6 + Output_daily7 str_Output = str_Output +"\n" return str_Output if __name__ == "__main__": print(process_weather("data/forecast_5days_a.json"))
import json input ='''[ {"ID":"001", "x":"2", "name":"Chuck"}, {"ID":"002", "x":"3", "name":"Break"} ]''' input type(input) info=json.loads(input) type(info) info0=info[0] info0['ID'] for item in info: print item['ID'], item['name']
list=[2,3,4,6] count=1 out=[] for num in list: data=num**count out.append(data) count+=1 print(out)
a=int(input("enter the first value=")) b=int(input("enter the second value=")) res=a+b print("result =",res)
# # i=2 # for i in range(10,50): # if(10%i==0): # i+=1 # break # else: # print (i) # for i in range(1,13): # if(i%4==0): # print(i) # else: # print(i,end="\t") # print(i,end=" ") #* #** #*** #**** #n=int(input("enter value for n")) # for row in range(0,n+1): # for col in range(0,row): # print("*",end=" ") # print() #1 # 12 # 123 # 1234 n=int(input("enter thevaluefor n ")) for row in range(0,n+1): for col in range(1,row+1): print(col,end=" ") print()
pattern="ababa" lst=list(pattern) #find the recursive character for i in lst: if i in lst[lst.index(i)+1:]: print(i) break
from tkinter import * import tkinter.messagebox from io import StringIO class Ide: #====================================Attribute=========================================================================== def __init__(self): self.root = Tk() self.root.title("Run Python Code") # set up the title self.root.geometry('600x600') # set up the size color = 'dark green' self.root.configure(bg=color) self.root.resizable(width=True, height=True) #=========================================================================================================================== self.top = Frame(self.root, width=600, height=50, bg=color)#A frame in Tk lets you organize and group widgets. It works like a container. Its a rectangular area in which widges can be placed. self.top.pack(side=TOP) #=================================================================================================================================== self.btn_clear = Button(self.top, text="clear", font=('arial', 25, 'italic'), highlightbackground=color, command=lambda: self.clear_text()) self.btn_clear.pack(side=TOP) self.btn_run = Button(self.top, text="Run", font=('arial', 25, 'italic'), highlightbackground=color, command=lambda: self.run()) self.btn_run.pack(side=TOP) self.message = Text(font=('arial', 20, 'italic'), bd=10, width=88, bg='white') self.message.pack(side=TOP) self.root.mainloop() # ==================================================Functions============================================================= def clear_text(self): self.message.delete("1.0", END) def run(self): try: old_stdout = sys.stdout redirected_output = sys.stdout = StringIO() exec(self.message.get("1.0", END)) sys.stdout = old_stdout tkinter.messagebox.showinfo("Result", redirected_output.getvalue()) except SyntaxError: tkinter.messagebox.showinfo("Result", "SyntaxError: unexpected EOF while parsing") app=Ide() #this command run the program and open the IDE
fname = input("Enter file name: ") fh = open(fname) inp = fh.read() lst = list() for line in inp: line = inp.rstrip() words = line.split() res = [] [res.append(x) for x in words if x not in res] print(sorted(res))
import math class Operacion: def __init__(self,numero): self.__numero=numero def floor(self): a=math.floor(self.__numero) return f"{a}" def ceil(self): b=math.ceil(self.__numero) return f"{b}" def raiz(self): c=math.sqrt(self.__numero) return f"{c}" def factor(self): d=math.factorial(self.__numero) return f"{d}" def potencia(self): pot=int(input("A que potencia lo quieres elevar")) e=math.pow(self.__numero,pot) return f"{e}" SEPARADOR=("-"*40 + "\n") while True: print("ESTE PROGRAMA AYUDA A ELEVAR,DISMINUIR UN ENTERO,OBTENER RAIZ CUADRADA,FACTORIAL Y POTENCIAS") print(SEPARADOR) n=float(input("Dame un numero: ")) #Pedimos un nuemro al usuario print(SEPARADOR) print("QUE DESEAS HACER") menu=int(input("""1:Elevar numero hacia arriba,2:Llevar el numero hacia abajo,3: Obtener la raiz cuadrada del numero, 4: Obtener el factorial, 5: Potenciar numero, 6:SALIR : """)) print(SEPARADOR) #Comienza el menu "if" if menu==1: x=Operacion(n) y=x.ceil() print(f"El entero hacia arriba de {n} es {y}") print(SEPARADOR) elif menu==2: x=Operacion(n) y=x.floor() print(f"El entero hacia abajo de {n} es {y}") print(SEPARADOR) elif menu==3: x=Operacion(n) y=x.raiz() print(f"La raiz del numero {n} es de {y}") print(SEPARADOR) elif menu==4: x=Operacion(n) y=x.factor() print(f"El factorial del numero {n} es de {y}") print(SEPARADOR) elif menu==5: x=Operacion(n) y=x.potencia() print(f"El numero {n} elevado a la potencia dada es {y} ") print(SEPARADOR) elif menu==6: break print("Gracias por usar el programa :3")
from bitarray import bitarray def trim(a): "return a bitarray, with zero bits removed from beginning" try: first = a.index(1) except ValueError: return bitarray() last = len(a) - 1 while not a[last]: last -= 1 return a[first:last+1] def find_last(a, value=True): "find the last occurrence of value, in bitarray." i = len(a) - 1 while not a[i] == bool(value): i -= 1 return i def count_n(a, n): "return the index i for which a[:i].count() == n" i, j = n, a.count(1, 0, n) while j < n: if a[i]: j += 1 i += 1 return i if __name__ == '__main__': # trim assert trim(bitarray()) == bitarray() assert trim(bitarray('000')) == bitarray() assert trim(bitarray('111')) == bitarray('111') assert trim(bitarray('00010100')) == bitarray('101') # find_last assert find_last(bitarray('00010100')) == 5 assert find_last(bitarray('00010111'), 0) == 4 assert find_last(bitarray('0000'), 0) == 3 # count_n a = bitarray('11111011111011111011111001111011111011111011111010111010111') for n in range(0, 48): i = count_n(a, n) assert a[:i].count() == n
a=int(input("")) b=int(input("")) c=int(a-b) if(c<0): c=-c if(c<a): print(c+b)
import pygame, sys from random import randrange import time class Robot: def __init__(self, row, col, name): self.row = row self.col = col self.name = name self.score = 0 def increaseScore(self): self.score += 1 def printScore(self): # print(f"{self.name}'s score: {self.score}") time.sleep(0.2) print(f" New score of {self.name}: {self.score}") # Define globals TILESIZE = 40 MAPWIDTH = 12 MAPHEIGHT = 12 MARGIN = 0.99 DELAY = 100 # Define tiles N = 0 # nothing W = 1 # wall F = 2 # food # Define colors BLACK = (0, 0, 0) BROWN = (160, 82, 45) YELLOW = (255, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) WHITE = (255, 255, 255) # Map tiles with colors TileColour = { N: BLACK, W: BROWN, F: YELLOW, } # Define map map = [[N, W, N, W, W, F, N, W, W, N, W, W], [W, N, W, F, N, N, F, W, N, N, F, W], [N, N, F, N, W, N, W, W, F, F, W, W], [F, F, N, N, N, N, N, N, N, N, N, N], [W, N, W, N, N, N, W, N, N, F, W, N], [N, N, W, N, N, N, W, F, F, W, N, N], [W, N, W, N, N, N, F, W, N, N, F, W], [W, N, W, N, N, N, W, N, N, F, W, N], [F, F, N, N, N, F, N, N, N, N, N, N], [N, W, N, W, W, F, N, N, W, N, W, W], [N, N, W, F, N, N, N, F, F, N, N, N], [W, N, W, F, N, W, F, W, N, N, F, W]] numberOfFoods = 0 # Count number of foods for row in range(MAPHEIGHT): for col in range(MAPWIDTH): if map[row][col] == F: numberOfFoods += 1 # Initialize robots r1 = Robot(3, 4, "Robocop") r2 = Robot(3, 4, "Babur") # Initialize pygame pygame.init() pygame.display.set_caption('2D Robot World') DISPLAY = pygame.display.set_mode((MAPWIDTH * TILESIZE, MAPHEIGHT * TILESIZE)) DISPLAY.fill(WHITE) # Define movement functions def forward(robot): if robot.row != 0 and map[robot.row - 1][robot.col] != W: robot.row -= 1 def backward(robot): if robot.row != 11 and map[robot.row + 1][robot.col] != W: robot.row += 1 def left(robot): if robot.col != 0 and map[robot.row][robot.col - 1] != W: robot.col -= 1 def right(robot): if robot.col != 11 and map[robot.row][robot.col + 1] != W: robot.col += 1 # PLAN algorithm for robots def plan(robot): # If robot is not in the map's limit & there is no wall around, randomly pick a route to navigate num = randrange(0, 4) if num == 0: forward(robot) elif num == 1: backward(robot) elif num == 2: right(robot) else: left(robot) pygame.time.wait(DELAY) # Waits for specified MS # If cell contains food, delete it and increase robot's score def eat(robot): global numberOfFoods if map[robot.row][robot.col] == F: map[robot.row][robot.col] = N robot.increaseScore() robot.printScore() numberOfFoods -= 1 while True: # If foods were all taken, terminate the game if numberOfFoods == 0: pygame.quit() sys.exit() # If user quits, terminate the game for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Call plan algorithms for each robot plan(r1) plan(r2) # Call eat functions for each robot eat(r1) eat(r2) for row in range(MAPHEIGHT): for col in range(MAPWIDTH): pygame.draw.rect(DISPLAY, TileColour[map[row][col]], (col * TILESIZE, row * TILESIZE, TILESIZE * MARGIN, TILESIZE * MARGIN)) # DRAW ROBOT 1 pygame.draw.rect(DISPLAY, RED, (r1.col * TILESIZE, r1.row * TILESIZE, TILESIZE * MARGIN, TILESIZE * MARGIN)) # DRAW ROBOT 2 pygame.draw.rect(DISPLAY, BLUE, (r2.col * TILESIZE, r2.row * TILESIZE, TILESIZE * MARGIN, TILESIZE * MARGIN)) pygame.display.update()
# -*- coding: utf-8 -*- """ Created on Tue Jul 20 20:05:09 2021 @author: hoang 2 """ import random def genChars(): while True: saltAmount=int(input("Nhap kich co Salt toi thieu tu 10-32 ky tu(nhap so^'):")) if saltAmount<10: print("Yeu cau nhap gia tri lon hon 10 va nho hon 32") elif saltAmount>32: print("Yeu cau nhap gia tri nho hon 32 va lon hon 10") else: break letters="" combination="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789∼!@$#%ˆ&∗()_-+={}|[]\:“<>?;’,./" for i in range(saltAmount): letters+=random.choice(combination) return letters
primes = [] isPrime = [True]*200 isPrime[0]=False isPrime[1]=False for i in range(2,200): if isPrime[i]: for x in range(2,200/i): isPrime[x*i]=False for i in range(200): if isPrime[i]: primes.append(i) def ProductOfPrimes(n): div = {} for i in primes: if (n%i==0): div[i]=0 while (n%i==0): div[i]+=1 n=n/i if not div: div[n]=1 return div def sumDivisors(n): div = ProductOfPrimes(n) sum=1 for i in div: sum=sum*(i**(div[i]+1)-1)/(i-1) sum=sum-n return sum isAbundant = [False]*28123 for i in range(28123): if sumDivisors(i)<i: isAbundant[i]=True
# 进程和线程的区别: # 1.进程:每个程序都会有一个进程,负责管理每个程序的各个功能的执行, # 进程只会有一个,而且至少有一个(相当于包工头) # 2.线程:每个进程里面至少有一个线程,称之为 主线程,除此之外还会有其他线程,称之为分线程 # 线程是控制执行任务的最小单位(相当于农民工) # 3.进程 负责控制各个线程 的执行,当程序运行,进程启动;程序关闭,进程结束 # # 主线程和分线程: # 1.代码运行默认在主线程里面 如果需要执行新的任务,可以开辟新线程 # 2.分线程没有个数限制,分线程里面的任务结束后,分线程结束 # # 分线程的使用场景: # 1.当有大量的任务需要执行的时候,可以将任务放入到分线程里面 # 2.当有大量任务需要执行的时候,而任务的执行顺序需要指定的时候,可以使用分线程 # 3.当界面有大量效果需要更新的时候,需要放入到分线程里面 # 同步任务:上一个任务没有完成,下一个任务不能开启 # 异步任务:可以同时执行多个任务,上一个任务没有完成,下一个任务也可以开启 # 分线程和异步的区别: # 1.分线程 可以同时开启多个任务,所有的任务由分线程自己完成 # 2.异步可以同时开启多个任务,但是自己只做一个任务,其他任务命令有他人来完成 # python 里面又两个负责线程的模块,thread,threading # threading在thread模块基础上做了扩展 # thread 线程 import threading # import # 获取当前线程的名称 main 主要的 print('当前线程为',threading.current_thread().name) def myThread(): print('位置1', threading.current_thread().name) print('位置2', threading.current_thread().name) print('位置3', threading.current_thread().name) print('位置4', threading.current_thread().name) print('位置5', threading.current_thread().name) print('位置6', threading.current_thread().name) myThread() class People(object): def Thread_test(self): print('对象方法',threading.current_thread().name) p = People() p.Thread_test() # threading.Thread 开辟一个新的线程 target 目标 name 为分线程名称 sub_thread = threading.Thread(target=myThread,name='newThread') # 开始执行分线程 sub_thread.start() # 确保任务的执行顺序 自己的线程先完成,之后再执行其他线程 sub_thread.join() # 当程序运行时,会先在主线程中执行, 因为在程序刚开始的时候,只有主线程,没有分线程 # 然后会根据情况进入到分先曾中,主线程和分线程的任务是交叉进行的 # (因为是两个路)自己线程的执行情况不会影响对方的线程 # 所以感觉是交叉的 # 分线程代码结束后,会回归到主线程 print('outside1',threading.current_thread().name) print('outside2',threading.current_thread().name) print('outside3',threading.current_thread().name) print('outside4',threading.current_thread().name) print('outside5',threading.current_thread().name)
#条件判断表达式 # 条件判断之if score=81 if score>=60: print('带你去海洋馆') # 条件判断之 if else salary=10000 if salary>=10000: print('哎呦,不错呦') else : print('努力吧') # 条件判断之if elif salary = 40000 # salary 薪水 if salary<=2000: print('Hello,小屌丝') elif salary<=4000: print('Hellow,小青年') elif salary<8000: print('Hellow,小帅哥') elif salary<20000: print('Hellow,小老板') elif salary<60000: print('Hellow,小土豪') # 条件判断表达之 if elif else结构 price = 28000 if price < 300 : print('老年机') elif price < 1000 : print('千元机') elif price < 3000 : print('时尚机') elif price < 10000 : print('豪华机') else : print('轰炸机') # 总结:如果if条件表达式里面写了else,那么这些条件有且只有一个会被执行 # 注意:不管在input里面输入任何内容,他的类型都是字符串类型 count = input ('请输入数量') # 强制类型转化:将被转化对象转化成数字类型 # count = int(count) # if count < 100: # print('少于100') if count.isdigit(): count = int(count) if count > 60: print('及格') else : print('不及格') else: print('输入的内容不正确')
# def binary_search(alist,item): # first = 0 # last = len(alist) - 1 # # while first <= last: # midpoint = (first + last)//2 # # if alist[midpoint] == item: # return True # elif item < alist[midpoint]: # last = midpoint - 1 # else: # first = midpoint + 1 # return False # alist = [0,1,2,3,4,5,6,7,8] # print(binary_search(alist,6)) num = [1,2,4,-1,8,5,3,9,-2] a = []
# 异常处理: 提前将可能会引起错误的代码 # 放入到捕获异常代码块中,一旦 # 发生次错误 不会影响后续代码的执行 # try 尝试 try: list = [1, 2, 3, 4, 5, 6] print(list[100]) dic = {'name': '张三'} print(dic['age']) except KeyError as e : print('捕获了一个key值错误,请仔细检查key值') except IndexError as e : print('捕获了一个索引值错误,索引值超出范围') try: list = [1,2,3,4] print(list[100]) dic = {'name':'Vik'} print(dic['age']) # 捕获任意错误 好处是不需要遍历所有的错误 # 缺点是 不知道错误类型是什么 except Exception as e: print('捕获了一个错误') # 有可能错误的代码块 try: list = [1,2,3] # 捕获了错误的代码块 except Exception as e: print('捕获了一个错误') # 代码没有产生错误的代码块 else: print('没有错误') # 不管有没有错误 一定会进来的代码块 finally 最终的 finally: print('程序结束')
class People(object): # 类属性 name ='' age ='' def __init__(self, fond=''): # 对象属性 self.fond =fond # 对象方法 self def say(self): print('Hello') print(People.name) p1 = People() p1.fond ='学习' print(p1.People) print(p1.name) print(p1.fond) # 对象属性不能通过类名+属性的方式来调用,只能通过对象来调用 # 类属性可以通过类名+属性的方式来调用,也可以通过对象来调用 print(People.fond) p1.say() # 对象可以通过对象+方法名 这种形式类调用 # 也可以通过类名+方法名,然后将对象当成传入方法中这种形式来调用 People.say(p1)
# def quict_sort(alist,start,end): # '''快速排序''' # # #递归的退出条件 # if start >= end: # return # # #设定一个基准元素 # mid = alist[start] # # low = start # high = end # # while low < high: # #如果low跟 high 没有重合,high指向的元素不比基准元素小,则high向左移动 # while low < high and alist[high] >=mid: # high -= 1 # #将high指向的元素放到low的位置上 # alist[low] = alist[high] # # while low < high and alist[low] < mid: # low += 1 # alist[high] = alist[low] # alist[low] = mid # quict_sort(alist,start,low-1) # quict_sort(alist,low+1,end) # # alist = [23,13,45,23,65,25,67,2,46,3] # quict_sort(alist,0,len(alist)-1) # print(alist) # def fibo(n): # if n<3: # return 1 # return fibo(n-1) + fibo(n-2) # for i in range(10): # print(fibo(i))
from random import randint user_num = input('请输入一个数字') # 0 石头 1 剪子 2 布 or或者 and 并且 # 0 1 -1 # 1 2 -1 # 2 0 2 computer_num = randint(0 , 2) print(computer_num) if user_num.isdigit(): user_num = int(user_num) if 0 <= user_num <= 2 : if user_num - computer_num == -1 or user_num - computer_num == 2: print('you win') elif user_num - computer_num == 0 : print('deuce') else : print('you lose') else : print('输入的数值大于有效范围') else : print('输入的内容格式错误,请输入0~2之间的一个数值')
# JSON # [] , () , {} list = [[],[],[]] list = [('a','A'),('b','B'),('c','C')] for x in list: print(x) for x , y in list: print(x , y) # 枚举 enumerate 可以让被遍历元素 添加一个编号(索引值) # for 后面的第一个参数 即为索引值 第二个参数 为被遍历的元素 for x , y in enumerate(list): print(x , y) for x ,( y ,z ) in enumerate(list): print(x , y ,z ) list = [('a','A'),('b','B'),('c','C')] list = [(1 ,[2, 3,]),(4,[5,6]),(7,[8,9])] for index , ( x , [ y , z]) in enumerate(list): print(index , x , y , z) list1 = ['a' , 'b' ,'c'] list2 = ['d','e','f'] # +可以使列表可以和字符串一样进行拼接 list3 = list1 + list2 print(list3) # extend 扩展;添加 list1.extend(list2) print(list1) list1 = [['a'],['b'],['c']] list2 = [['c'],['d'],['e']] # extend 将被合并的集合的所有值给 主动进行合并的集合 # 最终结果 为两个集合的元素个数的总和 list1.extend(list2) print(list1) list1 = [['a'],['b'],['c']] list2 = [['c'],['d'],['e']] # 将list2作为一个整体 给list1 list1的元素的个数等于之前的个数+ 1 list1.append(list2) print(list1) list1 = range(1, 101) list2 = [] for x in list1: if x % 2 == 1: list2.append(x) # print(list2) print(list2) # 列表推导式 list4 = [x for x in list1 if x % 2 ==1] print(list4) list = ['张三','张飞','张益达','关云长','赵子龙'] list5 = [x for x in list if x.startswith('张')] print(list5) list = ['1','2','3'] # reverse 相反的 list.reverse() print(list) list = [1, 2 ,3 ,4 ,5,6,7,8,9,10] some = 0 for x in list: some += x print(some) result = sum(list) print(result) list = [ 1, 3, 5, 7 ,9 ,2 , 4 , 6 , 8, 10] # revsrse 倒序 默认值为Flase list2 = sorted(list , reverse = True) print(list2) list = ['a' , 'b' ,'c'] print(list[0]) list = [['a','b'],['c','d'],['e','f']] print(list[1][0]) list = [ [ ['a'], #[0][0][0] ['b'] #010 ], [ ['c'], #100 ['d'] # 110 ], [ ['e'], # 200 ['f'] # 210 ] ] print(list[2][0][0]) list1 = [ [1 ,2 ,4], [3, 4], [5 ,6]] for x in list1: for y in x : print(y) list = [ [ ['a'], # [0][0][0] ['b'] # 010 ], [ ['c'], # 100 ['d'] # 110 ], [ ['e'], # 200 ['f'] # 210 ] ] for x in list : for y in x : for z in y : print(z) for x , [[y],[z]]in enumerate(list): print(y ,z) # 作业: 获取下面列表当中的每一个值,不必在同一行显示 # list = [(1 ,[2 , 3]) ,( 4 ,[5 ,6 ,7]),(8, [9,10,11,12])] # 作业2:将下面的列表进行排序 排序顺序为 正序 要求不能使用sorted方法 # list = [ 1, 3, 5, 7 ,9 ,2 , 4 , 6 , 8, 10]
class People(object): def __init__(self,name='',age='',sex='',height='',yaowei=''): self.name = name self.age = age self.sex = sex self.height = height self.yaowei = yaowei def sexIsFit(self,other): if self.sex == True and self.sex == other.sex print('同性相斥') return False def sexIsFit(self,other): if self.sex == False and self.sex == other.sex print('都是女的') return False def ageIsFit(self,other): if self.sex == True and self.age > other.age print('姐姐你太大') return False if self.sex == False and self.age < other.age print('弟弟你太小') return False class Man(People): def __init__(self,name,age,sex,height,yaoewei,ysal,house,havlues): super(Man,self).__init__(name,age,sex,height,yaowei) self.house = house self.havlues = havlues self.ysal = ysal def makeFrientWithGril(self,other):
import tkinter as tk class App: def __init__(self,root): # 创建一个框架,然后在里面添加Button按钮组件 # 框架一般使用再复杂的布局中起到将组件分组的作用 frame = tk.Frame(root) frame.pack() # 创建一个按钮组件,fg是foreground的缩写,就是设置前景色的意思 self.hi_there = tk.Button(frame,text = '打招呼',fg = 'blue',command = self.say_hi) self.hi_there.pack(pady = 100,padx=100) def say_hi(self): print('你好,我是初音未来~~') # 创建一个toplevel的根窗口,并把它作为参数实例化App的对象 root = tk.Tk() root.title('打招呼') app = App(root) # 开始主事件循环 root.mainloop()
import json, requests import oauth2 as oauth import os # Customer keys & secret CONSUMER_KEY = "INSERT HERE"; CONSUMER_SECRET = "INSERT HERE"; ACCESS_KEY = "INSERT HERE"; ACCESS_SECRET = "INSERT HERE"; def main(): # prompt user for input query = input("What would you like to search for: "); lang = input("Return only from specific country: "); output = input("Whould you like to ouput tweets to a file: (/home/)"); # clear terminal os.system("clear"); # review selected options print ("Please review your selected options below:"); print ("Search Twitter for: %s" %(query)); if (lang == ""): print ("No country filter set..."); else: print ("Country filter: %s" %(lang)); print ("Outputting result to: %s" %(output)); # wait for user input("Pess ENTER to continue..."); # searching print("Searching...."); queryTwitter(query, lang, output); def OutputToFile(output, text): mode = 'a' if os.path.exists(output) else 'w' with open(output, mode) as f: f.write(text); f.close(); def queryTwitter(query, lang, output): req = "https://api.twitter.com/1.1/search/tweets.json?"; # build request - better way of doing this needed... This will do for now. req += "q=" + query; if (lang.lower() != ""): req += "&" + lang; print("Requesting: %s" %(req)); # query twitter consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET); access_token = oauth.Token(key=ACCESS_KEY, secret=ACCESS_SECRET); client = oauth.Client(consumer, access_token); response, data = client.request(req); tweets = json.loads(data.decode('utf-8')); # check if user wants ouput if (output.lower() != ""): OutputToFile(output, tweets); # need to ouput important lines at top of file # pass output to be printed printIt(tweets); def printIt(result): #print(result); -- debug print("Tweets found: " + result['search_metadata']['count']); # add top 5 tweets. print("Compiled in %s secounds..." %(result['search_metadata']['completed_in'])); if __name__ == "__main__": main();
#Cristina Logg PSET #PART 1 ##################################################### #An API is a set of instructions for interfacing with software (getting it to talk with each other). This API is a set of instructions for getting into Twitter databases. Reading the documentation - we only have a week of tweets and random sampling. import jsonpickle import tweepy import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import os #Change into subfolder as needed. os.chdir('/Users/cristinalogg/Desktop/github/big-data-spring2018/week-04') from twitter_keys import api_key, api_secret auth = tweepy.AppAuthHandler(api_key, api_secret) # wait_on_rate_limit and wait_on_rate_limit_notify are options that tell our API object to automatically wait before passing additional queries if we come up against Twitter's wait limits (and to inform us when it's doing so). api = tweepy.API(auth, wait_on_rate_limit = True, wait_on_rate_limit_notify = True) def auth(key, secret): auth = tweepy.AppAuthHandler(key, secret) api = tweepy.API(auth, wait_on_rate_limit = True, wait_on_rate_limit_notify = True) # Print error and exit if there is an authentication error if (not api): print ("Can't Authenticate") sys.exit(-1) else: return api api = auth(api_key, api_secret) #This is the scraper. This is how we get stuff and write it to a json file. Need to both get the stuff and parse it. def get_tweets( geo, #geo allows us to specify a Location via lat/long and radius out_file, #specify type of file to write to search_term = '', #what search term are you interested in? tweet_per_query = 80000, # tweet_max = 82000, since_id = None, #allows you to create at the front end a manual window, so you can examine the json file and specify it as a sinceID in case you lose connection and have to redo it all over again. max_id = -1, write = False ): tweet_count = 0 #Collect a count of the number of tweets collected. all_tweets = pd.DataFrame() while tweet_count < tweet_max: #giant interator. try: if (max_id <= 0): #If under max, tell it to try to try the first if/else if (not since_id): new_tweets = api.search( q = search_term, rpp = tweet_per_query, geocode = geo ) else: new_tweets = api.search( q = search_term, rpp = tweet_per_query, geocode = geo, since_id = since_id ) else: if (not since_id): new_tweets = api.search( q = search_term, rpp = tweet_per_query, geocode = geo, max_id = str(max_id - 1) ) else: #are there new tweets? new_tweets = api.search( q = search_term, rpp = tweet_per_query, geocode = geo, max_id = str(max_id - 1), since_id = since_id ) if (not new_tweets): print("No more tweets found") break for tweet in new_tweets: #for all new tweets, return tweet and add it to json file all_tweets = all_tweets.append(parse_tweet(tweet), ignore_index = True) if write == True: with open(out_file, 'w') as f: f.write(jsonpickle.encode(tweet._json, unpicklable=False) + '\n') #while a given out file is open and writeable 'w', pass it to the below line as f, write to the file the result of the tweet to a new json array. max_id = new_tweets[-1].id #maximum ID of the tweet we got last, every tweet has a unique ID. tweet_count += len(new_tweets) except tweepy.TweepError as e: # Just exit if any error print("Error : " + str(e)) break print (f"Downloaded {tweet_count} tweets.") return all_tweets # Set a Lat Lon latlng = '42.359416,-71.093993' # Eric's office (ish) # Set a search distance radius = '5mi' # See tweepy API reference for format specifications geocode_query = latlng + ',' + radius # set output file location file_name = 'data/tweet_tryPSet.json' # set threshold number of Tweets. Note that it's possible # to get more than one t_max = 82000 #If you look at the json you can see a giant pile of crap... Now you know why you need to parse it. Also, look at it online via json viewer. def parse_tweet(tweet): p = pd.Series() if tweet.coordinates != None: p['lat'] = tweet.coordinates['coordinates'][0] p['lon'] = tweet.coordinates['coordinates'][1] else: p['lat'] = None p['lon'] = None p['location'] = tweet.user.location p['id'] = tweet.id_str p['content'] = tweet.text p['user'] = tweet.user.screen_name p['user_id'] = tweet.user.id_str p['time'] = str(tweet.created_at) return p tweets = get_tweets( geo = geocode_query, tweet_max = t_max, write = True, out_file = file_name ) #PART 2 ######################################################## tweetdf = pd.read_json('/Users/cristinalogg/Desktop/github/big-data-spring2018/week-04/data/tweet_tryPset.json') tweets.dtypes tweets['location'].unique() loc_tweets = tweets[tweets['location'] != ''] count_tweets = loc_tweets.groupby('location')['id'].count() df_count_tweets = count_tweets.to_frame() df_count_tweets.columns = ['count'] df_count_tweets df_count_tweets.sort_index() bos_list = tweets[tweets['location'].str.contains("Boston Ma$$")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("boston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("BOSTON")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Boston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Cambridge")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Cambridge, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("cambridge")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Cambridge, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("02139")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Cambridge, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Chelsea")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Chelsea, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("ALLSTON")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Allston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("allston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Allston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Bo$ton")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("BOS")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("bos")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("BoStOn")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Brighton")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Brighton, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Brookline")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Brookline, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Charlestown")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Charlestown, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Chelsea")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Chelsea, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("chelsea")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Chelsea, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("CHELSEA")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Chelsea, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("DORCHESTER")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Dorchester, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Dorchester")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Dorchester, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("everett")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Everett, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Everett")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Everett, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Fenway")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Gloucester")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Gloucester, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Harvard University")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Cambridge, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Harvard Square")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Cambridge, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Harvard Medical School")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("inman square")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Cambridge, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Jamaica Plain")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Jamaica Plain, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("jamaica plain")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Jamaica Plain, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Lowell ")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Lowell, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Lynn")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Lynn, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Malden")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Malden, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("malden")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Malden, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Massachusetts, USA")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'MA, USA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Medford")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Medford, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("medford")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Medford, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("New York City")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'New York, NY', inplace = True) bos_list = tweets[tweets['location'].str.contains("Newtonville")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Newtonville, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Revere")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Revere, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Roslindale")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Roslindale, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Somerville")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Somerville, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("somerville")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Somerville, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("United States")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'USA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Watertown")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Watertown, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("watertown")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Watertown, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("West Roxbury")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'West Roxbury, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Allston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Allston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Arlington MA")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Arlington, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Bo$ton")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Concord")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Concord, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Bos")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Davis Square")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Somerville, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("dorchester")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Dorchester, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("EVERETT")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Everett, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Jamaica Plain")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Jamaica Plain, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("jamaica plain")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Jamaica Plain, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Lowell")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Lowell, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Newton,")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Newton, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("MA, USA")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Massachusetts', inplace = True) bos_list = tweets[tweets['location'].str.contains("Boston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Boston, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("MIT")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Cambridge, MA', inplace = True) bos_list = tweets[tweets['location'].str.contains("Dha")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'Other Location', inplace = True) bos_list = tweets[tweets['location'].str.contains("New England")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'New England, USA', inplace = True) bos_list = tweets[tweets['location'].str.contains("New Hampshire")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, 'New Hampshire, USA', inplace = True) bos_list = tweets[tweets['location'].str.contains("New York")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets['location'].replace(bos_list, "New York, NY", inplace = True) loc_tweets = tweets[tweets['location'] != ''] count_tweets = loc_tweets.groupby('location')['id'].count() df_count_tweets = count_tweets.to_frame() df_count_tweets.columns = ['count'] df_count_tweets df_count_tweets.sort_index() # Create a list of colors (from iWantHue) colors = ["#697dc6","#5faf4c","#7969de","#b5b246", "#cc54bc","#4bad89","#d84577","#4eacd7", "#cf4e33","#894ea8","#cf8c42","#d58cc9", "#737632","#9f4b75","#c36960"] # Create a pie chart plt.pie(df_count_tweets['count'], labels=df_count_tweets.index.get_values(), shadow=False, colors=colors) plt.axis('equal') plt.tight_layout() # View the plot plt.show() #PART 3 ######################################################## # Create a filter from df_tweets filtering only those that have values for lat and lon tweets_geo = tweets[tweets['lon'].notnull() & tweets['lat'].notnull()] len(tweets_geo) len(tweets) # Use a scatter plot to make a quick visualization of the data points scatterplot_chart_1 = plt.scatter(tweets_geo['lon'], tweets_geo['lat'], s = 25) plt.title('Locations of Tweets') plt.xlabel('Longitude') plt.ylabel('Latitude') plt.show() #PART 4 ###################################################### def get_tweets2( geo, #geo allows us to specify a Location via lat/long and radius out_file, #specify type of file to write to search_term = 'MBTA', #what search term are you interested in? tweet_per_query = 100, # tweet_max = 82000, since_id = None, #allows you to create at the front end a manual window, so you can examine the json file and specify it as a sinceID in case you lose connection and have to redo it all over again. max_id = -1, write = False ): tweet_count = 0 #Collect a count of the number of tweets collected. all_tweets = pd.DataFrame() while tweet_count < tweet_max: #giant interator. try: if (max_id <= 0): #If under max, tell it to try to try the first if/else if (not since_id): new_tweets = api.search( q = search_term, rpp = tweet_per_query, geocode = geo ) else: new_tweets = api.search( q = search_term, rpp = tweet_per_query, geocode = geo, since_id = since_id ) else: if (not since_id): new_tweets = api.search( q = search_term, rpp = tweet_per_query, geocode = geo, max_id = str(max_id - 1) ) else: #are there new tweets? new_tweets = api.search( q = search_term, rpp = tweet_per_query, geocode = geo, max_id = str(max_id - 1), since_id = since_id ) if (not new_tweets): print("No more tweets found") break for tweet in new_tweets: #for all new tweets, return tweet and add it to json file all_tweets = all_tweets.append(parse_tweet(tweet), ignore_index = True) if write == True: with open(out_file, 'w') as f: f.write(jsonpickle.encode(tweet._json, unpicklable=False) + '\n') #while a given out file is open and writeable 'w', pass it to the below line as f, write to the file the result of the tweet to a new json array. max_id = new_tweets[-1].id #maximum ID of the tweet we got last, every tweet has a unique ID. tweet_count += len(new_tweets) except tweepy.TweepError as e: # Just exit if any error print("Error : " + str(e)) break print (f"Downloaded {tweet_count} tweets.") return all_tweets # Set a Lat Lon latlng = '42.359416,-71.093993' # Eric's office (ish) # Set a search distance radius = '5mi' # See tweepy API reference for format specifications geocode_query = latlng + ',' + radius # set output file location file_name = 'data/tweet_tryPSet_searching.json' # set threshold number of Tweets. Note that it's possible # to get more than one t_max = 82000 #If you look at the json you can see a giant pile of crap... Now you know why you need to parse it. Also, look at it online via json viewer. def parse_tweet(tweet): p = pd.Series() if tweet.coordinates != None: p['lat'] = tweet.coordinates['coordinates'][0] p['lon'] = tweet.coordinates['coordinates'][1] else: p['lat'] = None p['lon'] = None p['location'] = tweet.user.location p['id'] = tweet.id_str p['content'] = tweet.text p['user'] = tweet.user.screen_name p['user_id'] = tweet.user.id_str p['time'] = str(tweet.created_at) return p tweets_search = get_tweets2( geo = geocode_query, tweet_max = t_max, write = True, out_file = file_name ) tweetdf_search = pd.read_json('/Users/cristinalogg/Desktop/github/big-data-spring2018/week-04/data/tweet_tryPSet_searching.json') tweets_search.dtypes #PART 5 ###################################################### tweets_search['location'].unique() loc_tweets2 = tweets_search[tweets_search['location'] != ''] count_tweets2 = loc_tweets2.groupby('location')['id'].count() df_count_tweets2 = count_tweets2.to_frame() df_count_tweets2.columns = ['count'] df_count_tweets2 df_count_tweets2.sort_index() bos_list2 = tweets_search[tweets_search['location'].str.contains("Boston Ma$$")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("boston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("BOSTON")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Boston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Cambridge")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Cambridge, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("cambridge")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Cambridge, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("02139")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Cambridge, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Chelsea")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Chelsea, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("ALLSTON")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Allston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("allston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Allston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Bo$ton")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("BOS")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("bos")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("BoStOn")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Brighton")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Brighton, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Brookline")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Brookline, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Charlestown")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Charlestown, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Chelsea")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Chelsea, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("chelsea")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Chelsea, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("CHELSEA")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Chelsea, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("DORCHESTER")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Dorchester, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Dorchester")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Dorchester, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("everett")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Everett, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Everett")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Everett, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Fenway")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Gloucester")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Gloucester, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Harvard University")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Cambridge, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Harvard Square")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Cambridge, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Harvard Medical School")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("inman square")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Cambridge, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Jamaica Plain")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Jamaica Plain, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("jamaica plain")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Jamaica Plain, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Lowell ")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Lowell, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Lynn")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Lynn, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Malden")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Malden, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("malden")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Malden, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Massachusetts, USA")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'MA, USA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Medford")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Medford, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("medford")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Medford, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("New York City")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'New York, NY', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Newtonville")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Newtonville, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Revere")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Revere, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Roslindale")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Roslindale, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Somerville")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Somerville, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("somerville")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Somerville, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("United States")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'USA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Watertown")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Watertown, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("watertown")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Watertown, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("West Roxbury")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'West Roxbury, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Allston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Allston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Arlington MA")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Arlington, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Bo$ton")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Concord")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Concord, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Bos")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Davis Square")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Somerville, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("dorchester")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Dorchester, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("EVERETT")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Everett, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Jamaica Plain")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Jamaica Plain, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("jamaica plain")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Jamaica Plain, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Lowell")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Lowell, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Newton,")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Newton, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("MA, USA")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Massachusetts', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("Boston")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Boston, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("MIT")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'Cambridge, MA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("New England")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'New England, USA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("New Hampshire")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, 'New Hampshire, USA', inplace = True) bos_list2 = tweets_search[tweets_search['location'].str.contains("New York")]['location'] #for where tweets have location, create a mask, where the string within the locationcon tweets_search['location'].replace(bos_list2, "New York, NY", inplace = True) loc_tweets2 = tweets_search[tweets_search['location'] != ''] count_tweets2 = loc_tweets2.groupby('location')['id'].count() df_count_tweets2 = count_tweets2.to_frame() df_count_tweets2.columns = ['count'] df_count_tweets2 df_count_tweets2.sort_index() # Create a list of colors (from iWantHue) colors = ["#697dc6","#5faf4c","#7969de","#b5b246", "#cc54bc","#4bad89","#d84577","#4eacd7", "#cf4e33","#894ea8","#cf8c42","#d58cc9", "#737632","#9f4b75","#c36960"] # Create a pie chart plt.pie(df_count_tweets2['count'], labels=df_count_tweets2.index.get_values(), shadow=False, colors=colors) plt.axis('equal') plt.title('Pie Chart of Tweets within 5 Miles of MIT containing "MBTA"') plt.tight_layout() # View the plot plt.show() #PART 6 ###################################################### tweets_geo2 = tweets_search[tweets_search['lon'].notnull() & tweets_search['lat'].notnull()] len(tweets_geo2) len(tweets_search) # Use a scatter plot to make a quick visualization of the data points scatterplot_chart_2 = plt.scatter(tweets_geo2['lon'], tweets_geo2['lat'], s = 25) plt.title('Locations of Tweets Containing the Words "MBTA"') plt.xlabel('Longitude') plt.ylabel('Latitude') plt.show() #PART 7 ###################################################### #Write to CSV both tweets and tweets_search tweets[tweets.duplicated(subset = 'content', keep = False)] tweets.drop_duplicates(subset = 'content', keep = False, inplace = True) tweets.to_csv('twitter_data_part1_3.csv', sep=',', encoding='utf-8') tweets_search[tweets_search.duplicated(subset = 'content', keep = False)] tweets_search.drop_duplicates(subset = 'content', keep = False, inplace = True) tweets_search.to_csv('twitter_data_part4_6.csv', sep=',', encoding='utf-8') #EXTRA CREDIT ###################################################### import requests import bs4 response = requests.get('https://en.wikipedia.org/wiki/List_of_countries_by_greenhouse_gas_emissions') print(response.text) soup = bs4.BeautifulSoup(response.text, "html.parser") print(soup.prettify()) # Print the output using the 'prettify' function # Access the title element soup.title # Access the content of the title element soup.title.string # Access data in the first 'p' tag soup.p # Access data in the first 'a' tag soup.a # Retrieve all links in the document (note it returns an array) soup.find_all('a') # Retrieve elements by class equal to link using the attributes argument soup.findAll(attrs={'class':['mw-headline']) # Retrieve a specific link by ID soup.find(id="link3") # Access Data in the table (note it returns an array) soup.find_all('td') data = soup.findAll(attrs={'class':'flagicon'}) for i in data: print(i.string) f = open('soup_extracredit.csv','a') # open new file, make sure path to your data file is correct p = 0 # initial place in array l = len(data)-1 # length of array minus one f.write("Country, Emissions, Percentage\n") #write headers while p < l: # while place is less than length f.write(data[p].string + ", ") # write city and add comma p = p + 1 # increment f.write(data[p].string + "\n") # write number and line break p = p + 1 # increment f.close() # close file
class Usuario: def __init__(self, usuario, senha, id, email): self.usuario = usuario self.senha = senha self.id = id self.email = email ##Método que cria um dicionário com as informações do usuário def __dict__(self): d = dict() d['id'] = self.id d['usuario'] = self.usuario d['senha'] = self.senha d['email'] = self.email ##Método que cria a tupla que será inserida no banco de dados @staticmethod def cria(dados): try: if "id" in dados: id = dados['id'] usuario = dados['usuario'] senha = dados['senha'] email = dados['email'] return Usuario(id=id, usuario=usuario, senha=senha,email=email) except Exception as e: print('Erro ao criar usuário') print(e) ##Método utilizado para criar tuplas com dados do usuário @staticmethod def cria_tupla(registro): try: id = registro[0] usuario = registro[1] senha = registro[2] email = registro[3] return Usuario(id=id, usuario=usuario, senha=senha,email=email) except Exception as e: print('Erro ao criar usuário') print(e)
import numpy import cv2 def draw_box(img, box): tl = (box[0], box[1]) br = (box[0] + box[2], box[1] + box[3]) cv2.rectangle(img, tl, br, (0, 0, 255)) # cv.rectangle(img, box.tl(), box.br(), # cv::Scalar(0x00, 0x00, 0xff)) def help(): print('Call: python3 example_09-02.py') print(' Shows how to use a mouse to draw regions in an image.') # After main in original example. def my_mouse_callback(event, x, y, flags, param): global box, drawing_box image = param if event == cv2.EVENT_MOUSEMOVE: if drawing_box: box[2] = x - box[0] # box.width = x - box.x box[3] = y - box[1] # box.height = y - box.y elif event == cv2.EVENT_LBUTTONDOWN: drawing_box = True box = [x, y, 0, 0] elif event == cv2.EVENT_LBUTTONUP: drawing_box = False if box[2] < 0: box[0] += box[2] box[2] *= -1 if box[3] < 0: box[1] += box[3] box[3] *= -1 draw_box(image, box) if __name__ == '__main__': global box, drawing_box drawing_box = False help() box = [-1, -1, 0, 0] # ...cv::Rect(-1, -1, 0, 0) image = numpy.zeros((200, 200, 3), dtype=numpy.uint8) # cv::Mat image(200, 200, CV_8UC3) # Three extra lines here in original example? cv2.namedWindow('Box Example') cv2.setMouseCallback('Box Example', my_mouse_callback, image) while True: temp = image.copy() if drawing_box: draw_box(temp, box) cv2.imshow('Box Example', temp) if cv2.waitKey(15) == 27: break
# MATH BASIS FOR DETRENDING: # To detrend / flatten a 2d array, we need to understand the problem. We need to find a plane of best fit by regression. # Regression is done between the angle of rotation for each point to fit the height data the best. Thus: # X * Theta = Y must be solved. # X:= coordinate matrix (first column is a vector of ones; second and third are the matrix coordinate) # Theta:= angle of rotation of the plane # Y:= height data, unraveled into a 2d array with only 1 column. # # X * Theta = Y # X_T * X * Theta = X_T * Y # Theta = (X_T * X) ^ -1 * X_T * Y # CODE # import numpy as np def plane_fit(arr): '''m, n describes the shape of the 2d array''' out = np.copy(arr) m,n = out.shape # Creating X X1, X2 = np.mgrid[:m,:n] X = np.hstack( (np.ones((m*n,1)),np.reshape(X1,(m*n,1))) ) X = np.hstack( (X, np.reshape(X2,(m*n,1))) ) # Creating Y Y = np.reshape(out,(m*n,1)) # Fitting for theta theta = np.dot( np.dot( np.linalg.pinv(np.dot(X.transpose(),X)) , X.transpose() ) , Y) plane = np.reshape(np.dot(X,theta) , (m,n)) return plane def subtract_plane(arr): plane = plane_fit(arr) return arr - plane
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('/tmp/data',one_hot=True) #number of nodes in the layer n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 #number of outputs n_classes = 10 batch_size = 100 #input and output placeholders x = tf.placeholder('float', [None,784]) y = tf.placeholder('float') #defining our model def neural_network_model(data): hidden_layer_1 = { 'weights': tf.Variable(tf.random_normal([784,n_nodes_hl1])), 'biases' : tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_layer_2 = { 'weights': tf.Variable(tf.random_normal([n_nodes_hl1,n_nodes_hl2])), 'biases' : tf.Variable(tf.random_normal([n_nodes_hl2]))} hidden_layer_3 = { 'weights': tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl3])), 'biases' : tf.Variable(tf.random_normal([n_nodes_hl3]))} output_layer = { 'weights': tf.Variable(tf.random_normal([n_nodes_hl3,n_classes])), 'biases' : tf.Variable(tf.random_normal([n_classes]))} l1 = tf.add(tf.matmul(data,hidden_layer_1['weights']),hidden_layer_1['biases']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1,hidden_layer_2['weights']),hidden_layer_2['biases']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2,hidden_layer_3['weights']),hidden_layer_3['biases']) l3 = tf.nn.relu(l3) output = tf.add(tf.matmul(l3,output_layer['weights']),output_layer['biases']) return output def train_neural_network(x): prediction = neural_network_model(x) cost = tf.reduce_mean(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y) )) optimizer = tf.train.AdamOptimizer().minimize(cost) hm_epochs = 10 with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for epoch in range(hm_epochs): epoch_loss = 0 for _ in range(int(mnist.train.num_examples/batch_size)): epoch_x,epoch_y = mnist.train.next_batch(batch_size) _,c = sess.run([optimizer,cost],feed_dict ={x:epoch_x,y:epoch_y}) epoch_loss += c print 'Epoch',epoch,'out of',hm_epochs,'Loss: ',epoch_loss correct = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct,'float')) print('Accuracy',accuracy.eval({x:mnist.test.images,y:mnist.test.labels})) train_neural_network(x)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 10 18:36:11 2019 @author: reality """ def encode_keyword(string, cipher): #creating the cipher text key key = cipher #Notes any characters in plain text newInsertor = {} fcounter = -1; for i in string: fcounter = fcounter + 1 if ord(i) < 65 or ord(i) > 122: #If it is other than a letter, notes the character and index newInsertor[fcounter] = i print(newInsertor) #This will create unique key based on the cipher counter = -1; #keep track of each index while counter != len(key)-1: #loop runs until end each index counter = counter +1 #keeps track of the index i = key[counter] if ord(i) < 65 or ord(i) > 122: #If it is other than a letter, notes the character and index continue else: letterIndex = key[counter+1:].find(i) if letterIndex != -1: #if the letter is further in the text, remove it forwardWord = key[counter+1:] forwardWord = forwardWord.replace(i,"") key = key[:counter+1] + forwardWord key = key.replace(" " , "") #This adds the remaining alphabet letters into the key for z in range(97,123): letter = chr(z); if key.find(letter) != -1: continue; key = key + letter; print(key) #This will encrypt the string based on the key alpha = "abcdefghijklmnopqrstuvwxyz" encryptPhrase = "" string = string.replace(" " , "" ) for i in string: if ord(i) < 65 or ord(i) > 122: #If it is other than a letter, notes the character and index continue correctIndex = alpha.find(i); encryptPhrase += key[correctIndex] print(encryptPhrase) #This will add any extra previous symbols back in the encrypted message for i in newInsertor: encryptPhrase = encryptPhrase[0:i] + newInsertor[i] + encryptPhrase[i:] print(encryptPhrase) return encryptPhrase encode_keyword('cogworks 2018', 'python')
f = open("имя файла") #открываю файл с тройками n = sum(1 for x in open('имя файла')) #смотрю количество строк в файле. строки файла - количество наших троек def comb(): #функция, которая на выводе дает всевозможные комбинации троек a = list(map(int,f.readline().split())) #читаем строку, создаем из этого список целых чисел (наши числа в тройке) return (a[0]+a[1], a[1]+a[2],a[0]+a[2]) #мы возвращаем всевозможные комбинации цифр из наших троек s = comb() #получаем одну такую комбинацию сумм для начала for _ in range(n-1): tr = comb() # получаем еще одну комбинацию сумм combinacii = [a+b for a in tr for b in s] #перебираем суммы двух комбинаций, в итоге тут выходит 9 чисел. s1 = [0]*7 #мы будем сортировать полученные суммы комбинаций по остаткам от деления на 7. индекс = остаток от деления for x in combinacii: #перебираем числа из combinaci'й. if x > s1[x%7]: #сортируем числа из cmb по остаткам при делении на 7, запихиваем в s1 самое большое число, подходящее по остатку s1[x%7] = x s = [x for x in s1] #преобразуем s в список print(s[0]) #в конце мы выводим нужное число с нужным остатком. число кратно 7 - остаток 0, значит мы выводим нулевой элемент #0 выведится в случае, если такой суммы нет.
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' dict ''' d1 = {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10 print(d1['a']) del d1['a'] print(d1) d1.clear() print(d1) print(d1.get('a'))
#Function without a param def greetings(): print('Hello World') greetings() #Function with a param def greetings(name): print('Hello {0}'.format(name)) greetings('Amit') #Function which returns a value def add(a, b): return a + b a = 2 b = 3 c = add(a, b) print('{0} + {1} = {2}'.format(a,b,c))
def convertKmToMiles(km): conversionFactor = 0.621371 miles = conversionFactor * km return miles if __name__ == "__main__": print("Welcome to km-to-mile converter program") km = float(input("Enter km? ")) miles = convertKmToMiles(km) print("{} km = {} miles".format(km, miles))
# Relative Figure Encryption cracking method # # NEED TO APPLY A FORM TO GET ALL COMBINATIONS AND # PERMUTATIONS OF ALPHABETS # Libraries import pyperclip as PC import tools.criptoTools as CT import detectarEspanol as DE import relatedFigure as RF # Get all the characters availeable SYMBOLS = """ º\ª1234567890!"·$%&/()=|@#~½¬{[]}?¿'¡`+'ç,.-<^*Ç;:_>·qwertyuiopasdfghjklñzxcvbnmQWERTYUIOPASDFGHJKLÑZXCVBNMł€¶ŧ←↓→øþłĸŋđðßæ«»¢µ""" # Ask for the text to crack and show any possible crack def main(): text = input('Enter the text you want to decode: \n') decode(text) # Find the number of different symbols in a message def numSym(text): stored = '' counter = 0 for symbol in text: if symbol not in stored: stored += symbol counter += 1 return counter # Generate a random alphabet with the characters in SYMBOLS def genAlph(alph): for k in range(len(alph)): for i in range(len(alph)): nAlph += alph[i] for j in range(len(alph)): if j != i: nAlph +=alph[j] # Main decoding function def decode(text):
# Ataque de diccionario a la cifra de sustitución simple import pyperclip, sustitucionSimple, detectarEspanol MODO = False def main(): criptograma = input('Criptograma > ') textoLlano = ataque(criptograma) if textoLlano == None: # ataque() devuelve None si no ha encontrado la clave print('El ataque falló.') else: # El texto llano se muestra en la pantalla y se copia al portapapeles print('Mensaje copiado al portapapeles.') print(textoLlano) pyperclip.copy(textoLlano) def alfabetoSustitucion(clave): # crea un alfabeto de sustitución con la clave nuevaClave = '' clave = clave.upper() alfabeto = list(sustitucionSimple.LETRAS) for i in range(len(clave)): if clave[i] not in nuevaClave: nuevaClave += clave[i] alfabeto.remove(clave[i]) clave = nuevaClave + ''.join(alfabeto) return clave def ataque(mensaje): print('Probando con %s posibles palabras del diccionario...' % len(detectarEspanol.PALABRAS_ESPANOL)) print('(Pulsa Ctrl-C o Ctrl-D para abandonar.)') intento = 1 # Prueba de cada una de las claves posibles for clave in detectarEspanol.PALABRAS_ESPANOL: if intento % 100 == 0 and not MODO: print('%s claves probadas. (%s)' % (intento, clave)) clave = alfabetoSustitucion(clave) textoLlano = sustitucionSimple.descifrarMensaje(clave, mensaje) if detectarEspanol.porcentaje_palabras(textoLlano) > 0.20: # Comprueba con el usuario si el texto tiene sentido print() print('Posible hallazgo:') print('clave: ' + str(clave)) print('Texto llano: ' + textoLlano[:100]) print() print('Pulsa S si es correcto, o Enter para seguir probando:') respuesta = input('> ') if respuesta.upper().startswith('S'): return textoLlano intento += 1 return None if __name__ == '__main__': main()
㖼̐ Ŋ֌W𐄒łH Ȃ lXgwK\[XɂƂ P̒oɎgƂcc 3n^2 - n + 3 (n - d)^2 - n + d = 6n ^2 - 2n - 6nd + 3d^2 + d =3(sqrt(2)n - d)^2 + 6sqrt(2)nd - 6 nd - 2n +d #pentagonal = [] #for i in xrange(1, 10000): # n = i * (3 * i - 1) / 2 # pentagonal.append(n) # #for i in xrange(len(pentagonal)): # for j in xrange(i + 1, len(pentagonal)): # diff = pentagonal[j] - pentagonal[i] # add = pentagonal[i] + pentagonal[j] # if diff in pentagonal and add in pentagonal: # print diff, i, j #߂ē #http://tsumuji.cocolog-nifty.com/tsumuji/2009/04/project-euler-5.html import itertools import math def pentagon(q): x = (1 + math.sqrt(1 + 24 * q)) / 6.0 return int(x) == x pentagonal = [] for i in itertools.count(1): print i, n n = i * (3 * i - 1) / 2 f = False for m in pentagonal: diff = n - m add = n + m if pentagon(diff) and pentagon(add): print diff, n, m f = True break pentagonal.insert(0, n) if f: break
#n is even: # 2 #n is odd: # 2 * n * a % a**2 s = 0 for a in xrange(3, 1001): n = 1 r = [] while True: div = a**2 rem = 2 * n * a % div if rem in r: s += max(r) break else: r.append(rem) n += 2 else: print s
import fractions def num(n): if n % 3 == 0: return 2 * n / 3 else: return 1 N = 100 t = fractions.Fraction(1, num(N)) for i in xrange(N, 2, -1): t = num(i - 1) + t t = 1 / t print 2 + t q = 2 + t sum([int(i) for i in str(q.numerator)])
digit = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] teens = ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] other = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] def print_below_100(number): if number > 19: leading = int(float(number)/10.0) rest = number - leading*10 if rest == 0: return other[leading-2] else: return other[leading-2] + " " + digit[rest-1] elif number > 10: return teens[number-11] elif number == 10: return "ten" else: return digit[number-1] def print_number(number): assert (number <= 1000) if number == 1000: return "one thousand" else: if number < 100: return print_below_100(number) else: leading = int(float(number) / 100.0) rest = number - leading*100 if rest == 0: return digit[leading-1] + " hundred" else: return digit[leading-1] + " hundred and " + print_below_100(rest) print(print_number(342)) print(len(print_number(342).replace(" ", ""))) print(print_number(115)) print(len(print_number(115).replace(" ", ""))) print(print_number(1000)) print(print_number(100)) print(print_number(101)) print(print_number(18)) print(print_number(818)) print(print_number(210)) print(print_number(999)) complete_string = "" for number in range(1,1001): substr = print_number(number) print(substr) complete_string += substr print(len(complete_string.replace(" ", "")))
from datetime import datetime from time import mktime class Date(object): """Some time/date manipulation utilities. """ def __init__(self, datetime): self.datetime = datetime self._diff_date = None @property def diff_date(self): if not self._diff_date: the_date = datetime.fromtimestamp(mktime(self.datetime.timetuple())) self._diff_date = datetime.now() - the_date return self._diff_date
class operation(): def __init__(self,num1,num2): self.number1= num1 self.number2=num2 def display_result(self,result): print('The result is {}'.format(result)) def add_numbers(self): sum = self.number1 + self.number2 self.display_result(sum) def sub_numbers(self): diff = self.number1 - self.number2 self.display_result(diff) def mul_numbers(self): product = self.number1 * self.number2 self.display_result(product) def div_numbers(self): div = self.number1 / self.number2 self.display_result(div) o = operation(5,1) o.add_numbers()
__author__ = 'adam' size=20 def numWays(x,y): if(x==size+1 and y==size+1): return 1 if(x>size): return numWays(x,y+1) if(y>size): return numWays(x+1,y) else: return numWays(x,y+1) + numWays(x+1,y) print numWays(1,1)
__author__ = 'adam' import pandigit import primes import itertools primelist = primes.numpyPrimes(20) def isPrimeDivisible(n): for i in xrange(7): if int(n[1+i:4+i]) % primelist[i]!=0: return False return True count=0 list=[] for i in itertools.permutations('0123456789'): i=''.join(i) if i[0]=='0': continue if isPrimeDivisible(i): list.append(int(i)) print list print sum(list)
__author__ = 'adam' import math n=0 ninefac=math.factorial(9) while (n+1)*ninefac>10**n: n+=1 print(n) factorials=[] for i in range(10): factorials.append(math.factorial(i)) def isFactorial(n): num=str(n) sum=0 for i in num: sum+=factorials[int(i)] return n==sum list=[] for i in range(10**n): if isFactorial(i): list.append(i) print(i) print(sum(list))
#!/usr/bin/env python3 import os import settings import ast def read_sidebar(filename): """ Reads a text file and evaluates it as a python dict. Takes a file, reads it line by line and evaluates it so that the dictionary it holds can be initialised. """ with open(filename, "r") as f: s = f.read() sidebar = ast.literal_eval(s) return sidebar def read_files(filename): """ Reads a file line by line and commits it to a variable. Takes a file and reads it line by line, commiting each line to memory. Returns the variable as a tuple with each line as an item. Args: filename: the location of the file to be read. Returns: Returns the file as a tuple with each line stored as a value. """ with open(filename, mode="r", encoding="utf-8") as f: file_memory = [lines for lines in f] return file_memory def replace_all(text, dic, filtered=None): """ Searches for specific keys in TEXT and replaces them with the value from DIC. Uses a dictionary to find specific keys and replace them with the relevant value pair. DIC holds the key:value look up information. Args: text: is an iterable data set that holds the text search through dic: holds the dictionary that contains the key:value to search filtered: ensures that the list is initialised empty each time """ if filtered is None: filtered = [] for line in text: for key, value in dic.items(): line = line.replace(key, value) filtered.append(line) return filtered def write_file(file_to_write, separator, file_out="output"): """ Takes a list/tupule, joins using a custom separator and writes it to disk with a custom name. Takes a list or tuple, and writes it to a text file using the join command, with the separator as custom input. Args: file_to_write: the list/tuple to write separator: the join separator file_out: the name of the file to write out """ with open(file_out, mode="w", encoding="utf-8") as f: f.write(separator.join(file_to_write)) def portfolio_grid(src="output"): """ Scans for thumbnails, creates thumbnail path and generates the correct html for the portfolio grid as well as the a href link in a dictionary. Args: src: the root path for the function to walk through and search """ thumbs = [] html = [] for root, dirs, files in os.walk(src): for f in files: if "thumb.jpg" in f: thumbs.append(os.path.join(root,f)) thumbs.sort(reverse=True) for item in thumbs: item_split = (item.split("/")) item_slice = item_split[1][3:] alt_text = item_slice.replace("_", " ") project_name = item_split[1] + ".html" image_src = ( os.path.join(item_split[1], item_split[2]) ) html.append( "<div class='item'><a href='{}'><img class='caption' src='{}' alt='{}' /></a></div>".format( project_name, image_src, alt_text ) ) html_joined = " ".join(html) html_dic = {"(%_portfolio_grid_%)": html_joined} return html_dic #~ def insert_img(src="content"): #~ for root, dirs, files in os.walk(src): #~ print(dirs) def get_project_dirs(path="content"): """ Returns project directory names from content folder. Scans given path one level deep for folders, and returns all the folder names as a list of folder names. Args: path: path to search, defaults to "content" """ projects = [] for items in os.listdir(path): if os.path.isdir(os.path.join(path, items)): projects.append(items) return projects def get_project_imgs(projects): """ Returns a tuple of image paths from the given directory. """ image_path = [] for root, dirs, files in os.walk("output/{}".format(proj)): if "images" and proj in root: print(root) print(files)
from typing import List, Optional # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def treeNodeToString(root): if not root: return "[]" output = "" queue = [root] current = 0 while current != len(queue): node = queue[current] current = current + 1 if not node: output += "null, " continue output += str(node.val) + ", " queue.append(node.left) queue.append(node.right) return "[" + output[:-2] + "]" class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if len(preorder) == 0: return None root = TreeNode(preorder[0]) pivot = inorder.index(preorder[0]) # every element below or equal left_index is in left sub tree if len(preorder) == 1: return root root.left = self.buildTree(preorder[1:pivot+1], inorder[:pivot]) root.right = self.buildTree(preorder[pivot+1:], inorder[pivot+1:]) return root if __name__ == "__main__": s = Solution() preorder = [3,9,8,10,5,2,20,15,7] inorder = [10,8,5,9,2,3,15,20,7] t = s.buildTree(preorder, inorder) print(treeNodeToString(t)) preorder = [3,9,8,10,5,20,15,7] inorder = [10,8,5,9,3,15,20,7] t = s.buildTree(preorder, inorder) print(treeNodeToString(t))
class Solution: def spiralOrder(self, matrix: list[list[int]]) -> list[int]: ''' Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7] ''' s.show_result(matrix) bottom = len(matrix) up = 0 right = len(matrix[0]) left = 0 col = 0 row = 0 results = [] rows, cols = bottom, right while len(results) < rows*cols: # right while col < right: print("R") results.append(matrix[row][col]) col += 1 col -= 1 row += 1 up += 1 # down while row < bottom: print("D") results.append(matrix[row][col]) row += 1 row -= 1 col -= 1 right -= 1 # left while col >= left: print("L") results.append(matrix[row][col]) col -= 1 col += 1 row -= 1 bottom -= 1 # up while row >= up: print("U") results.append(matrix[row][col]) row -= 1 row += 1 col += 1 left += 1 return results def show_result(self, matrix) -> None: for i in matrix: for j in i: print("%2d " % j, end="") print() s = Solution() print(s.spiralOrder([[1,2,3,4],[5,6,7,8],[9,10,11,12]])) print(s.spiralOrder([[1,2,3],[5,6,7],[9,10,11]]))
""" Declares a point in a metric space """ class Point: """ Defines a point in a metric space Parameters: ---------- coords : Iterable The point coordinates. metric : Metric The metric used to measure points proximity. """ def __init__(self, coords, metric): self.coords = coords self.metric = metric def distto(self, *others): return self.metric.dist(self, *others) def __getitem__(self, index): return self.coords[index] def __str__(self): return "(" + ", ".join(str(c) for c in self.coords) + ")" def __eq__(self, other): return self.coords == other.coords def __hash__(self): return hash(tuple(self.coords)) @staticmethod def importFrom(path, metric): points = [] with open(path) as f: for line in f: points.append(Point([int(coord) if float(coord).is_integer() else float(coord) for coord in line.split(',')], metric)) return points @staticmethod def exportTo(path, points): with open(path, 'w') as f: for point in points: f.write(', '.join([str(coord) for coord in point.coords]) + '\n') def setMetric(metric, points): for pt in points: pt.metric = metric
#Input/Output Files in Python # When you read a file, you have to close it as well # Open a file myfile = open('myfile.txt') # Read the contents of a file in one huge string contents = myfile.read() print(f"Contents of file {contents}") myfile.seek(0) # to move the cursor back to the starting position contents_again = myfile.read() print(f"Contents of file again : \n{contents_again}") # \nPrint in a new line contents_again1 = myfile.read() print(f"Contents of file again and there's nothing : \n{contents_again1}") myfile.seek(0) # to move the cursor back to the starting position contents_again2 = myfile.read() print(f"Contents of file again after seek(0): \n{contents_again2}") myfile.seek(0) # Error below as this file does not exist #myfile = open('whoops_wrong.txt') #Use readlines() method to get the lines in one single list # with separate object/element to be used for indexing content_readlines = myfile.readlines() print(f"Contents of file using readlines method: \n{content_readlines}") #close the file when done working with it myfile.close() #open a file from different location different_loc_file = open('/Users/kimsi/Documents/Kim_python/myfile_jupiter.txt') read_diff_loc_file = different_loc_file.readlines() print(f"Contents of a different located file using readlines method: \n{read_diff_loc_file}") # To avoid using close method everytime for files, use special with statement # Notice the identation, No longer worry about closing the file with open('myfile.txt') as my_new_file: contents_with = my_new_file.read() print(f"Contents of my NEW file using WITH Statement: \n{contents_with}") # use with with differently_located_file, no worry about closing the file with open('/Users/kimsi/Documents/Kim_python/myfile_jupiter.txt') as NEW_Loc_File: contents_LOC_with = NEW_Loc_File.read() print(f"Contents of my NEW LOCATION file using WITH Statement: \n{contents_LOC_with}") #Permissions in Files (Read/Write/Append) # Use open method's mode as read-only default with open('myfile.txt', mode = 'r') as my_file_mode: contents = my_file_mode.read() print(f"Contents of my file using MODE READ option: \n{contents}") # Use open method's mode as write-only, and see error as below #with open('myfile.txt', mode = 'w') as my_file_mode: #contents = my_file_mode.read() #print(f"Contents of my file using MODE option: \n{contents}") # a is appending to the files with open('myfile.txt', mode = 'a') as f: f.write('\nSIX ON SIXTH') # cannot store the result from write in a variable # The below will error out as the mode is not readable #print(f"Contents of my file using MODE APPEND option: \n{f.read()}") # Read the file after appending with open('myfile.txt', mode = 'r') as my_file_mode: contents_after_append = my_file_mode.read() print(f"Contents of my file using MODE READ after appending: \n{contents_after_append}") # w overwrites the existing files or creates a new one with open('huhulahhd.txt', mode = 'w') as f: f.write("I created gibberish file. Haha!") # read the file after writing with open('huhulahhd.txt', mode = 'r') as my_file_mode: contents_after_write = my_file_mode.read() print(f"Contents of my file using MODE READ after WRITING: \n{contents_after_write}")
a=0 while a<100: a+=1 if a%7==0 or (a-7)%10==0 or a-70<10 and a-70>0: continue print(a)
# ============= Binary search ================ # Time: O(log(n)) # Space: O(1) # Idea: """ [__larger__|_____smaller_____] If target in the larger zone, go left. otherwise, go right. """ class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ """ Corner cases: 1. [0] 0 2. [0] 1 3. [1,2] 2 4. [2,1] 1 5. [4,5,6,7,0,1,2] 5 6. [4,5,6,7,0,1,2] 1 """ left, right = 0, len(nums) - 1 while left <= right: mid = (left + right)//2 if nums[mid] == target: return mid # Larger zone. Floor divison leans toward left, so add equals here. # case [2,1] 1 if nums[mid] >= nums[left]: # Target in the smaller zone? If target == nums[mid], # we won't be here, so add equals to the left. # Also make sense to think that we have to include the # whole range inclusively if nums[left] <= target < nums[mid]: # Go to larger zone right = mid - 1 else: # Go to right half left = mid + 1 # Smaller zone. # Case [5,1,3] 3 else: # Target in the larger zone? # Also make sense to think that we have to include the # whole range inclusively, so add equals to the left end. if nums[mid] < target <= nums[right]: # Go to smaller zone left = mid + 1 else: # go to the other half right = mid - 1 # Didn't find match return -1
""" Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. For example, Given [[0, 30],[5, 10],[15, 20]], return 2. """ # ============= merge intervals =============== # Time: O(nlog(n)) # Space: O(n) # Idea: merge the ones that could share a room, otherwise push into heap # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class IntervalWrapper(object): def __init__(self, i): self.start = i.start self.end = i.end def __cmp__(self, other): return self.end - other.end class Solution(object): def minMeetingRooms(self, intervals): """ :type intervals: List[Interval] :rtype: int """ if not intervals: return 0 intervals.sort(cmp=lambda i1, i2: i1.start - i2.start) heap = [IntervalWrapper(intervals[0])] for i in xrange(1, len(intervals)): min_end = heapq.heappop(heap) if intervals[i].start < min_end.end: heapq.heappush(heap, IntervalWrapper(intervals[i])) else: min_end.end = intervals[i].end heapq.heappush(heap, min_end) return len(heap) # ================ same but with pointers =============== # https://discuss.leetcode.com/topic/35253/explanation-of-super-easy-java-solution-beats-98-8-from-pinkfloyda # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def minMeetingRooms(self, intervals): """ :type intervals: List[Interval] :rtype: int """ if not intervals: return 0 starts, ends = [], [] for i in intervals: starts.append(i.start) ends.append(i.end) starts.sort() ends.sort() rooms = end_pos = 0 for i in xrange(len(starts)): if starts[i] < ends[end_pos]: rooms += 1 else: end_pos += 1 return rooms
""" Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. """ # ============== Bit =============== # Time: O(result) # Space: O(1) """ In this problem, we are asked to divide two integers. However, we are not allowed to use division, multiplication and mod operations. So, what else can we use? Yeah, bit manipulations. Let's do an example and see how bit manipulations work. Suppose we want to divide 15 by 3, so 15 is dividend and 3 is divisor. Well, division simply requires us to find how many times we can subtract the divisor from the the dividend without making the dividend negative. Let's get started. We subtract 3 from 15 and we get 12, which is positive. Let's try to subtract more. Well, we shift 3 to the left by 1 bit and we get 6. Subtracting 6 from 15 still gives a positive result. Well, we shift again and get 12. We subtract 12 from 15 and it is still positive. We shift again, obtaining 24 and we know we can at most subtract 12. Well, since 12 is obtained by shifting 3 to left twice, we know it is 4 times of 3. How do we obtain this 4? Well, we start from 1 and shift it to left twice at the same time. We add 4 to an answer (initialized to be 0). In fact, the above process is like 15 = 3 * 4 + 3. We now get part of the quotient (4), with a remainder 3. Then we repeat the above process again. We subtract divisor = 3 from the remaining dividend = 3 and obtain 0. We know we are done. No shift happens, so we simply add 1 << 0 to the answer. Now we have the full algorithm to perform division. According to the problem statement, we need to handle some exceptions, such as overflow. Well, two cases may cause overflow: divisor = 0; dividend = INT_MIN and divisor = -1 (because abs(INT_MIN) = INT_MAX + 1). Of course, we also need to take the sign into considerations, which is relatively easy. Putting all these together, we have the following code. """ class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if divisor == 0: return 2147483647 if dividend == 0: return 0 if dividend == -2147483648 and divisor == -1: return 2147483647 positive = -1 if (dividend < 0 and divisor < 0) or (dividend > 0 and divisor > 0): positive = 1 dividend = abs(dividend) divisor = abs(divisor) if positive == 1 and dividend < divisor: return 0 result = 0 while dividend >= divisor: shift = 0 while dividend >= (divisor << shift): shift += 1 dividend -= divisor << (shift - 1) result += 1 << (shift - 1) return result*positive
""" Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. Credits: Special thanks to @ts for adding this problem and creating all test cases. """ # ============== string comparator ============== # Time: O(nlog(n) + n) # Space: O(1) class Solution: # @param {integer[]} nums # @return {string} def largestNumber(self, nums): if not nums: return "" def my_cmp(n1, n2): case1 = str(n1) + str(n2) case2 = str(n2) + str(n1) if case1 > case2: return -1 elif case1 < case2: return 1 return 0 # O(nlog(n)) nums.sort(cmp=my_cmp) result = "" # O(n) for n in nums: result += str(n) return result if result[0] != '0' else '0'
""" Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent. Find the number of islands. Have you met this question in a real interview? Yes Example Given graph: [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1] ] return 3. """ # =============== Union Find =============== # Time: O(2*m*n) # Space: O(m*n) # Trap: # 1. initialize count with the # of 1 # 2. row*len_col + col could generate unique number for all cells # 3. use list instead of dict could save a little bit of time class UnionFind(object): def __init__(self, nodes): self.father = [] for n in xrange(nodes): self.father.append(n) def set_count(self, c): self.count = c def query(self): return self.count def find(self, node): if self.father[node] == node: return node f = self.find(self.father[node]) self.father[node] = f return f def union(self, node1, node2): f1 = self.find(node1) f2 = self.find(node2) if f1 != f2: self.father[f2] = f1 self.count -= 1 class Solution: # @param {boolean[][]} grid a boolean 2D matrix # @return {int} an integer def numIslands(self, grid): # Write your code here if not grid or not grid[0]: return 0 len_row = len(grid) len_col = len(grid[0]) uf = UnionFind(len_row*len_col) count = 0 for row in grid: count += row.count(1) uf.set_count(count) delta_x = [0, 0, 1, -1] delta_y = [1, -1, 0, 0] def in_bound(x, y): return 0 <= x < len_row and 0 <= y < len_col for row in xrange(len(grid)): for col in xrange(len(grid[0])): if grid[row][col] == 1: for i in xrange(len(delta_x)): next_row = row + delta_x[i] next_col = col + delta_y[i] if in_bound(next_row, next_col) and grid[next_row][next_col] == 1: uf.union(row*len_col + col, next_row*len_col + next_col) return uf.query()
""" There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. Constraints: The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. You may assume that there are no duplicate edges in the input prerequisites. 1 <= numCourses <= 10^5 """ class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: if numCourses <= 0 or not prerequisites: return True #return self.bt(numCourses, prerequisites) return self.topological_sort(numCourses, prerequisites) def topological_sort(self, numCourses, prerequisites): """ L = Empty list that will contain the sorted elements S = Set of all nodes with no incoming edge while S is non-empty do remove a node n from S add n to tail of L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S if graph has edges then return error (graph has at least one cycle) else return L (a topologically sorted order) https://en.wikipedia.org/wiki/Topological_sorting """ outgoing = collections.defaultdict(set) incoming = collections.defaultdict(int) for p in prerequisites: outgoing[p[0]].add(p[1]) incoming[p[1]] += 1 heads = set(outgoing.keys()) - set(incoming.keys()) while heads: node = heads.pop() neighbors = outgoing[node].copy() for n in neighbors: outgoing[node].remove(n) incoming[n] -= 1 if incoming[n] == 0: heads.add(n) del incoming[n] return len(incoming) == 0 def bt(self, numCourses, prerequisites): """ Time Complexity: Space Complexity: """ d = collections.defaultdict(list) for p in prerequisites: d[p[0]].append(p[1]) for k in d.keys(): if not self.__bt_helper(k, d, set(), set()): return False return True def __bt_helper(self, k, d, path, visited): if k in path: return False if k in visited: return True path.add(k) for n in d.get(k, []): if not self.__bt_helper(n, d, path, visited): return False path.remove(k) visited.add(k) return True """ class GNode(object): """ data structure represent a vertex in the graph.""" def __init__(self): self.inDegrees = 0 self.outNodes = [] class Solution(object): def canFinish(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ from collections import defaultdict, deque # key: index of node; value: GNode graph = defaultdict(GNode) totalDeps = 0 for relation in prerequisites: nextCourse, prevCourse = relation[0], relation[1] graph[prevCourse].outNodes.append(nextCourse) graph[nextCourse].inDegrees += 1 totalDeps += 1 # we start from courses that have no prerequisites. # we could use either set, stack or queue to keep track of courses with no dependence. nodepCourses = deque() for index, node in graph.items(): if node.inDegrees == 0: nodepCourses.append(index) removedEdges = 0 while nodepCourses: # pop out course without dependency course = nodepCourses.pop() # remove its outgoing edges one by one for nextCourse in graph[course].outNodes: graph[nextCourse].inDegrees -= 1 removedEdges += 1 # while removing edges, we might discover new courses with prerequisites removed, i.e. new courses without prerequisites. if graph[nextCourse].inDegrees == 0: nodepCourses.append(nextCourse) if removedEdges == totalDeps: return True else: # if there are still some edges left, then there exist some cycles # Due to the dead-lock (dependencies), we cannot remove the cyclic edges return False """
""" You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Have you met this question in a real interview? Yes Example Given an example n=3 , 1+1+1=2+1=1+2=3 return 3 """ # ============= DP variables ============= # Time: O(n) # Space: O(1) class Solution: """ @param n: An integer @return: An integer """ def climbStairs(self, n): # write your code here if n < 0: return 0 if n == 0: return 1 if n <= 2: return n prev_prev, prev = 1, 2 result = None for i in xrange(2, n): result = prev + prev_prev prev_prev = prev prev = result return result
# ============ Recursive ============ # Time: O(log(n)) # Space: O(log(n)) class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 if n == 1: return x if n < 0: x = 1/x n = -n return self.myPow(x*x, n/2) if n%2 == 0 else x*self.myPow(x*x, n/2) # ============ Iterative ========== # Time: O(log(n)) # Space: O(1) # Idea: """ I couldn't find a clear explanation for an interative Log(n) solution so here's mine. The basic idea is to decompose the exponent into powers of 2, so that you can keep dividing the problem in half. For example, lets say N = 9 = 2^3 + 2^0 = 1001 in binary. Then: x^9 = x^(2^3) * x^(2^0) We can see that every time we encounter a 1 in the binary representation of N, we need to multiply the answer with x^(2^i) where i is the ith bit of the exponent. Thus, we can keep a running total of repeatedly squaring x - (x, x^2, x^4, x^8, etc) and multiply it by the answer when we see a 1. To handle the case where N=INTEGER_MIN we use a long (64-bit) variable. Below is solution: """ class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if x == 0: return 0 if n == 0: return 1 if n == 1: return x result = 1 n_copy = n n_copy = abs(n_copy) while n_copy: if (n_copy&1 == 1): result *= x n_copy >>= 1 x *= x return result if n > 0 else 1/result
""" Numbers keep coming, return the median of numbers at every time a new number added. Have you met this question in a real interview? Yes Clarification What's the definition of Median? - Median is the number that in the middle of a sorted array. If there are n numbers in a sorted array A, the median is A[(n - 1) / 2]. For example, if A=[1,2,3], median is 2. If A=[1,19], median is 1. Example For numbers coming list: [1, 2, 3, 4, 5], return [1, 1, 2, 2, 3]. For numbers coming list: [4, 5, 1, 3, 2, 6, 0], return [4, 4, 4, 3, 3, 3, 3]. For numbers coming list: [2, 20, 100], return [2, 2, 20]. Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. Examples: [2,3,4] , the median is 3 [2,3], the median is (2 + 3) / 2 = 2.5 Design a data structure that supports the following two operations: void addNum(int num) - Add a integer number from the data stream to the data structure. double findMedian() - Return the median of all elements so far. For example: addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2 """ # ============ Lintcode Min&Max Heap =============== # Time: O(nlogn) # Space: O(n) # Trap: int overflow? import heapq class Solution: """ @param nums: A list of integers. @return: The median of numbers """ def medianII(self, nums): # write your code here if not nums: return cur_median = nums[0] left_heap = [] right_heap = [] result = [nums[0]] # O(n) for n in nums[1:]: if n > cur_median: heapq.heappush(right_heap, n) else: heapq.heappush(left_heap, n*-1) # O(log(n)) if len(right_heap) > len(left_heap) + 1: old_median = cur_median cur_median = heapq.heappop(right_heap) heapq.heappush(left_heap, old_median*-1) # O(log(n)) if len(left_heap) > len(right_heap): old_median = cur_median cur_median = heapq.heappop(left_heap)*-1 heapq.heappush(right_heap, old_median) result.append(cur_median) return result # ============= LC ================ # Trap: int overflow? # Time: add - O(log(n)), find - O(1) # Space: O(n) import heapq class MedianFinder(object): def __init__(self): """ initialize your data structure here. """ self.left_heap = [] self.right_heap = [] def addNum(self, num): """ :type num: int :rtype: void """ # Always push to the left heap first, then # give the largets to the right_heap to # maintain the balance heapq.heappush(self.left_heap, num*-1) heapq.heappush(self.right_heap, heapq.heappop(self.left_heap)*-1) # If two heaps has the same # of emelemts before adding the new # one in, the right one will has more after the "shifting", so # shift one back. if len(self.left_heap) < len(self.right_heap): heapq.heappush(self.left_heap, heapq.heappop(self.right_heap)*-1) def findMedian(self): """ :rtype: float """ if not self.left_heap and not self.right_heap: return None if len(self.left_heap) == len(self.right_heap): return (self.right_heap[0] + self.left_heap[0]*-1)/2.0 return self.left_heap[0]*-1.0 # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ######## Resursion with min and max ############## # Running time: 72ms # Time complexity: O(n) # Space complexity: O(n) class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ return self.helper(root, -sys.maxint - 1, sys.maxint) def helper(self, root, min, max): if root is None: return True if ((root.left is not None and root.left.val >= root.val) or root.val >= max): return False if ((root.right is not None and root.right.val <= root.val) or root.val <= min): return False return self.helper(root.left, min, root.val) and self.helper(root.right, root.val, max) ######## Resursion with prev ############## # Running time: 72ms # Time complexity: O(n) # Space complexity: O(n) class Solution(object): prev = None def isValidBST(self, root): if root is None: return True if not self.isValidBST(root.left): return False if (self.prev is not None) and (self.prev.val >= root.val): return False self.prev = root return self.isValidBST(root.right)
""" There are two properties in the node student id and scores, to ensure that each student will have at least 5 points, find the average of 5 highest scores for each person. Have you met this question in a real interview? Yes Example Given results = [[1,91],[1,92],[2,93],[2,99],[2,98],[2,97],[1,60],[1,58],[2,100],[1,61]] Return """ # =========== Heap =========== # Time: # Space: # Trap: an id may not have 5 scores ''' Definition for a Record class Record: def __init__(self, id, score): self.id = id self.score = score ''' import heapq class Solution: # @param {Record[]} results a list of <student_id, score> # @return {dict(id, average)} find the average of 5 highest scores for each person # <key, value> (student_id, average_score) def highFive(self, results): # Write your code here if not results: return {} r = {} for record in results: if record.id in r: heapq.heappush(r[record.id], record.score) if len(r[record.id]) > 5: heapq.heappop(r[record.id]) else: r[record.id] = [record.score] for key, heap in r.iteritems(): cur_sum = 0 for score in heap: cur_sum += score r[key] = cur_sum/5.0 return r
""" Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted. Follow up: Could you do both operations in O(1) time complexity? Example: LFUCache cache = new LFUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.get(3); // returns 3. cache.put(4, 4); // evicts key 1. cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4 """ # ============== double linkedlist + ordered dict ================== # Time: O(1) # Space: O(3cap) # Idea: """ same as bucket. each bucket store the nodes with same frequency, use double linkedlist to store all buckets. in order to make each bucket FIFO and del in O(1), use ordered dict to store keys. move key to the next bucket if next bucket frequency is cur+1, otherwise create a new one. """ class Node(object): def __init__(self, count): self.count = count self.keys = collections.OrderedDict() self.prev = None self.next = None class LFUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.cap = capacity self.value_hash = {} self.node_hash = {} self.head = Node(-1) self.tail = Node(-1) self.head.next = self.tail self.tail.prev = self.head def get(self, key): """ :type key: int :rtype: int """ if key in self.value_hash: self.__increase_count(key) return self.value_hash[key] return -1 def put(self, key, value): """ :type key: int :type value: int :rtype: void """ if self.cap <= 0: return if key in self.value_hash: self.value_hash[key] = value else: if len(self.value_hash) >= self.cap: self.__pop_lfu() self.value_hash[key] = value self.__add_to_head(key) self.__increase_count(key) def __increase_count(self, key): node = self.node_hash[key] cur_count = node.count del node.keys[key] if len(node.keys) == 0: self.__delete_node(node) node = node.prev cur_node = None if node.next.count == cur_count + 1: cur_node = node.next else: cur_node = Node(cur_count + 1) cur_node.next = node.next node.next.prev = cur_node cur_node.prev = node node.next = cur_node cur_node.keys[key] = None self.node_hash[key] = cur_node def __pop_lfu(self): if self.head.next.count == -1: return first_node = self.head.next key, value = first_node.keys.popitem(last=False) if len(first_node.keys) == 0: self.__delete_node(first_node) del self.value_hash[key] del self.node_hash[key] def __add_to_head(self, key): node = None if self.head.next.count == 0: node = self.head.next else: node = Node(0) node.next = self.head.next self.head.next.prev = node self.head.next = node node.prev = self.head node.keys[key] = None self.node_hash[key] = node def __delete_node(self, node): node.prev.next = node.next node.next.prev = node.prev # Your LFUCache object will be instantiated and called as such: # obj = LFUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # ================== Recursion ================= # Time: O(n) # Space: O(n) # Running time: ~80ms class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ result = [] self.helper(root, sum, [], result) return result def helper(self, root, sum, cur_path, result): if root is None: return cur_path.append(root.val) minus_self = sum - root.val if minus_self == 0 and root.left is None and root.right is None: result.append(cur_path) return self.helper(root.left, minus_self, cur_path[:], result) self.helper(root.right, minus_self, cur_path[:], result)
""" Given a binary tree, find the subtree with minimum sum. Return the root of the subtree. Notice LintCode will print the subtree which root is your return node. It's guaranteed that there is only one subtree with minimum sum and the given binary tree is not an empty tree. Have you met this question in a real interview? Yes Example Given a binary tree: 1 / \ -5 2 / \ / \ 0 2 -4 -5 return the node 1. """ # ============= Recursion ============= # Time: O(n) # Space: O(n) """ Definition of TreeNode: class TreeNode: def __init__(self, val): this.val = val this.left, this.right = None, None """ class Solution: # @param {TreeNode} root the root of binary tree # @return {TreeNode} the root of the minimum subtree def findSubtree(self, root): # Write your code here def helper(r, result): if not r: return 0 l_sum = helper(r.left, result) r_sum = helper(r.right, result) cur_sum = l_sum + r_sum + r.val if cur_sum < result[0]: result[0], result[1] = cur_sum, r return cur_sum result = [float('inf'), None] helper(root, result) return result[1]
# Definition for a binary tree node # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None #=============== Stack ==================== # Time: hasNext: O(1) next: # Space: O(h) # Explaination: The average time complexity of next() function is O(1) indeed in your case. As the next function can be called n times at most, and the number of right nodes in self.pushAll(tmpNode.right) function is maximal n in a tree which has n nodes, so the amortized time complexity is O(1). class BSTIterator(object): stack = [] def __init__(self, root): """ :type root: TreeNode """ if root is None: return self.stack.append(root) l = root.left while l: self.stack.append(l) l = l.left def hasNext(self): """ :rtype: bool """ if len(self.stack) > 0: return True return False def next(self): """ :rtype: int """ smallest = self.stack.pop() r = smallest.right if r is not None: self.stack.append(r) l = r.left while l: self.stack.append(l) l = l.left return smallest.val # Your BSTIterator will be called like this: # i, v = BSTIterator(root), [] # while i.hasNext(): v.append(i.next())
#=========== Dict ============ # Time: O(n) # Space: O(n) class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ d = {} for n in nums: if d.has_key(n): return True else: d[n] = n return False #============ Sort ========== # Time: O(nlog(n) + n) # Space: O(1) class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ nums.sort() i = 1 while i < len(nums): if nums[i] == nums[i - 1]: return True i += 1 return False # =========== Set ============= # Time: ? # Space: ? class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ return len(nums) != len(set(nums))
""" Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]] 0 3 | | 1 --- 2 4 Output: 2 Example 2: Input: n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]] 0 4 | | 1 --- 2 --- 3 Output: 1 Note: You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. """ class UnionFind: def __init__(self, nodes): self.fathers = {} self.unique_sets = len(nodes) for n in nodes: self.fathers[n] = n def find(self, node, compress=True): if self.fathers[node] == node: return node # find the real father f = node while self.fathers[f] != f: f = self.fathers[f] # Recursion method sets the father of all # nodes along the path to the new father. # In order to do the same in non-recursive # version, we need to iterate the path # again and set them manually. if compress: node_clone = node while self.fathers[node_clone] != node_clone: node_clone = self.fathers[node_clone] self.fathers[node_clone] = f self.fathers[node] = f return f def union(self, node1, node2): f1 = self.find(node1) f2 = self.find(node2) if f1 != f2: self.fathers[f1] = f2 self.unique_sets -= 1 class Solution: def countComponents(self, n: int, edges: List[List[int]]) -> int: if n <= 0: return 0 if not edges: return n #return self.bfs(n, edges) return self.union_find(n, edges) def bfs(self, n, edges): """ Expand from each unvisited node and count. T: O(N) - visit each node once S: O(N) - worst case all nodes except root are in the q """ neighbors = collections.defaultdict(list) for begin, end in edges: neighbors[begin].append(end) neighbors[end].append(begin) not_visited = set(range(n)) result = 0 while not_visited: node = not_visited.pop() q = collections.deque([node]) while q: cur_level = len(q) for _ in range(cur_level): cur_node = q.popleft() not_visited.discard(cur_node) for n in neighbors.get(cur_node, []): # this could prevent going back if n in not_visited: q.append(n) result += 1 return result def union_find(self, n, edges): uf = UnionFind(range(n)) for begin, end in edges: uf.union(begin, end) return uf.unique_sets
""" Given a set of strings which just has lower case letters and a target string, output all the strings for each the edit distance with the target no greater than k. You have the following 3 operations permitted on a word: Insert a character Delete a character Replace a character Have you met this question in a real interview? Yes Example Given words = ["abc", "abd", "abcd", "adc"] and target = "ac", k = 1 Return ["abc", "adc"] """ # =============== Trie + DP ================ # Time: # Space: # Idea: Same as edit distance, but instead of comparing all the words # with target, build a trie and do dp with every prefix, thus save time. class TrieNode(object): def __init__(self, c=None): self.c = c self.has_word = False self.d = {} class Trie(object): def __init__(self): self.root = TrieNode() def add(self, word): if not word: return cur_node = self.root for c in word: if c in cur_node.d: cur_node = cur_node.d[c] else: new_node = TrieNode(c) cur_node.d[c] = new_node cur_node = new_node cur_node.has_word = True def dfs(self, word_list, target, k): # build the trie for word in word_list: self.add(word) # build the first row dp = [i for i in xrange(len(target) + 1)] result = [] for c, n in self.root.d.iteritems(): self.__helper(n, c, target, dp, result, k) return result def __helper(self, cur_node, cur_word, target, prev_row, result, k): # build the cur dp row cur_row = [len(cur_word)] # i is the pos in the target string # i is 1 behind in the dp list for i in xrange(len(target)): if target[i] == cur_node.c: cur_row.append(prev_row[i]) else: cur_row.append(min(min(prev_row[i + 1], cur_row[i]), prev_row[i]) + 1) # if edit distance <= k if cur_node.has_word and cur_row[-1] <= k: result.append(cur_word) for next_char, next_node in cur_node.d.iteritems(): self.__helper(next_node, cur_word + next_char, target, cur_row, result, k) class Solution: # @param {string[]} words a set of strings # @param {string} target a target string # @param {int} k an integer # @return {string[]} output all the stirngs that meet the requirements def kDistance(self, words, target, k): # Write your code here if not words: return [] if k < 0: return [] if not target: return [word for word in words if len(word) <= k] t = Trie() return t.dfs(words, target, k)
""" Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". """ # ============== window ============== # Time:: O(n) # Space: O(len(p)) class Solution(object): def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ if not s or not p: return [] d = {} needed = len(p) for c in p: d[c] = d[c] + 1 if c in d else 1 result = [] for idx, val in enumerate(s): if val in d: d[val] -= 1 if d[val] >= 0: needed -= 1 if idx < len(p) - 1: continue if idx > len(p) - 1: prev = s[idx - len(p)] if prev in d: d[prev] += 1 if d[prev] > 0: needed += 1 if needed == 0: result.append(idx - len(p) + 1) return result
""" Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1; Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid. IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases). However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address. Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid. Note: You may assume there is no extra space or special characters in the input string. Example 1: Input: "172.16.254.1" Output: "IPv4" Explanation: This is a valid IPv4 address, return "IPv4". Example 2: Input: "2001:0db8:85a3:0:0:8A2E:0370:7334" Output: "IPv6" Explanation: This is a valid IPv6 address, return "IPv6". Example 3: Input: "256.256.256.256" Output: "Neither" Explanation: This is neither a IPv4 address nor a IPv6 address. """ class Solution(object): def validIPAddress(self, IP): """ :type IP: str :rtype: str """ def ipv4(addr): groups = addr.split('.') # must have 4 groups # min ipv4: 0.0.0.0 or 1.1.1.1 if len(groups) != 4 or len(addr) < 7: return False for g in groups: # must have digits and # <= 3 if not g or len(g) > 3: return False # leading zero not allowed if g[0] == '0' and len(g) > 1: return False try: value = int(g) # must between 0 and 255 if value < 0 or value > 255: return False # for case like '-0' if value == 0 and g[0] != '0': return False except: return False return True def ipv6(addr): groups = addr.split(':') # min ipv6: 0:0:0:0:0:0:0:0 if len(groups) != 8 or len(addr) < 15: return False for g in groups: # empty token not allowed if not g or len(g) > 4: return False for c in g: c_ascii = ord(c) # check if digit is valid is_digit, is_upper, is_lower = False, False, False if ord('0') <= c_ascii <= ord('9'): is_digit = True if ord('a') <= c_ascii <= ord('f'): is_lower = True if ord('A') <= c_ascii <= ord('F'): is_upper = True if not (is_digit or is_upper or is_lower): return False return True if ipv4(IP): return "IPv4" if ipv6(IP): return "IPv6" return "Neither" # import re # class Solution(object): # def validIPAddress(self, IP): # if re.match('(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])', IP) is not None: # return "IPv4" # if re.match('(([0-9a-fA-F]{1,4}):){7}([0-9a-fA-F]{1,4})', IP) is not None: # return "IPv6" # return "Neither"
""" Given a string, find the length of the longest substring T that contains at most k distinct characters. For example, Given s = “eceba” and k = 2, T is "ece" which its length is 3. """ # =============== Sliding window ============= # Time: O(n) # Space: O(n) class Solution(object): def lengthOfLongestSubstringKDistinct(self, s, k): """ :type s: str :type k: int :rtype: int """ if not s or k <= 0: return 0 d = {} prev = 0 result = 0 for i in xrange(len(s)): if s[i] in d: d[s[i]] += 1 else: d[s[i]] = 1 while prev < i and len(d) > k: if d[s[prev]] > 1: d[s[prev]] -= 1 else: del d[s[prev]] prev += 1 result = max(result, i - prev + 1) return result # =========== Keep track of last occurance ============ class Solution(object): """ The general idea is to iterate over string s. Always put the character c and its location i in the dictionary d. 1) If the sliding window contains less than or equal to k distinct characters, simply record the return value, and move on. 2) Otherwise, we need to remove a character from the sliding window. Here's how to find the character to be removed: Because the values in d represents the rightmost location of each character in the sliding window, in order to find the longest substring T, we need to locate the smallest location, and remove it from the dictionary, and then record the return value. """ def lengthOfLongestSubstringKDistinct(self, s, k): """ :type s: str :type k: int :rtype: int """ # Use dictionary d to keep track of (character, location) pair, # where location is the rightmost location that the character appears at d = {} low, ret = 0, 0 for i, c in enumerate(s): d[c] = i if len(d) > k: low = min(d.values()) del d[s[low]] low += 1 ret = max(i - low + 1, ret) return ret
""" Given a nested list of integers, return the sum of all integers in the list weighted by their depth. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Have you met this question in a real interview? Yes Example Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1, 4 * 1 * 2 + 1 * 2 * 1 = 10) Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 42 + 63 = 27) """ # ============= Stack ============= # Time: O(N = all nodes) # Space: O(N = all nodes) # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return {boolean} True if this NestedInteger holds a single integer, # rather than a nested list. # """ # # def getInteger(self): # """ # @return {int} the single integer that this NestedInteger holds, # if it holds a single integer # Return None if this NestedInteger holds a nested list # """ # # def getList(self): # """ # @return {NestedInteger[]} the nested list that this NestedInteger holds, # if it holds a nested list # Return None if this NestedInteger holds a single integer # """ class Solution(object): # @param {NestedInteger[]} nestedList a list of NestedInteger Object # @return {int} an integer def depthSum(self, nestedList): # Write your code here if not nestedList: return 0 q = collections.deque(nestedList) result = 0 level = 0 while len(q) > 0: level += 1 cur_len = len(q) for i in xrange(cur_len): cur_node = q.pop() if cur_node.isInteger(): result += cur_node.getInteger() * level else: for next_node in cur_node.getList(): q.appendleft(next_node) return result
""" Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 Show Company Tags Show Tags Show Similar Problems """ # =========== Stack =========== # Time: O(n) # Space: O(n) # NOTICE: """ in Python: 1/-22 = -1(should be 0) """ class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ if not tokens: return 0 pool = set(['+', '-', '*', '/']) stack = [] for t in tokens: if t not in pool: stack.append(int(t)) continue o2 = stack.pop() o1 = stack.pop() cur_val = 0 if t == '+': cur_val += o1 + o2 elif t == '-': cur_val += o1 - o2 elif t == '*': cur_val += o1 * o2 else: # here take care of the case like "1/-22", # in Python 2.x, it returns -1, while in # Leetcode it should return 0 if o1*o2 < 0 and o1 % o2 != 0: cur_val = o1/o2+1 else: cur_val = o1/o2 stack.append(cur_val) return stack.pop()
""" Given an integer array, find a subarray where the sum of numbers is in a given interval. Your code should return the number of possible answers. (The element in the array should be positive) Have you met this question in a real interview? Yes Example Given [1,2,3,4] and interval = [1,3], return 4. The possible answers are: [0, 0] [0, 1] [1, 1] [2, 2] """ # ============== BS ================ # Time: O(nlogn) # Space: O(1) class Solution: # @param {int[]} A an integer array # @param {int} start an integer # @param {int} end an integer # @return {int} the number of possible answer def subarraySumII(self, A, start, end): # Write your code here if not A or start > end: return 0 for i in xrange(1, len(A)): A[i] += A[i - 1] A.sort() result = 0 for a in A: if start <= a <= end: result += 1 small = a - end big = a - start # start <= sums[i] - sums[j - 1] <= end # => sums[i] - start >= sums[j - 1] >= sums[i] - end # => (num of sums[j - 1] < big + 1(<= big)) - (num of sums[j - 1] <= small) result += self.__bs(A, big + 1) - self.__bs(A, small) return result def __bs(self, A, value): lens = len(A) if A[-1] < value: return lens begin, end = 0, lens - 1 while begin + 1 < end: mid = (begin + end)/2 if A[mid] >= value: end = mid - 1 else: begin = mid if end < 0 or (A[end] >= value and A[begin] >= value): return 0 if A[end] < value: return end + 1 return begin + 1