text
stringlengths
37
1.41M
#####函数作用域: ''' L local局部作用域,本地作用域 E enclosing嵌套作用域 G global全局作用域 B built-in内建作用域 for,if,while这些流程控制不会形成自己的作用域 ''' #####得到所有模块的方法,内建作用域 # import sys # print(dir(sys)) #####全局变量 # 全局变量name name = 'while' def outer(): # name = 'for'#嵌套作用域 def inner(): #本地作用域 # name = 'django' age = 18 print(name) print(age) inner() outer()
""" Each ListNode holds a reference to its previous node as well as its next node in the List. """ class ListNode: def __init__(self, value, prev=None, next=None): self.prev = prev self.value = value self.next = next """ Our doubly-linked list class. It holds references to the list's head and tail nodes. """ class DoublyLinkedList: def __init__(self, node=None): self.head = node self.tail = node self.length = 1 if node is not None else 0 def __len__(self): return self.length def print_list(self): current = self.head while current.next: print(current.value) current = current.next print("---") """ Wraps the given value in a ListNode and inserts it as the new head of the list. Don't forget to handle the old head node's previous pointer accordingly. """ def add_to_head(self, value): new_node = ListNode(value, None, self.head) if not self.head and not self.tail: self.head = new_node self.tail = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node # self.head = new_node # last = self.head # while last.next is not None: # last = last.next # last.next = new_node # new_node.prev = last self.length += 1 # return """ Removes the List's current head node, making the current head's next node the new head of the List. Returns the value of the removed Node. """ def remove_from_head(self): removed = self.head.value # if there is no head then there's nothing to remove if self.head is None: return None if not self.head.next: self.head = None self.tail = None self.length -= 1 return removed # new head is the next item of the removed item self.head = self.head.next # fix length self.length -= 1 return removed """ Wraps the given value in a ListNode and inserts it as the new tail of the list. Don't forget to handle the old tail node's next pointer accordingly. """ def add_to_tail(self, value): new_node = ListNode(value) if self.head is None: new_node.prev = None self.head = new_node self.tail = new_node self.length += 1 else: self.tail.next = new_node new_node.prev = self.tail new_node.next = None self.tail = new_node self.length += 1 # current = self.head # while current.next: # current = current.next # current.next = new_node # new_node.prev = current # new_node.next = None # self.tail = new_node # self.length += 1 """ Removes the List's current tail node, making the current tail's previous node the new tail of the List. Returns the value of the removed Node. """ def remove_from_tail(self): removed = self.tail.value if not self.head and not self.tail: return None elif self.head == self.tail: self.head = None self.tail = None self.length -= 1 return removed else: current = self.head while current.next: current = current.next self.tail = current.prev self.tail.next = None self.length -= 1 return removed """ Removes the input node from its current spot in the List and inserts it as the new head node of the List. """ def move_to_front(self, node): if self.length == 0: return elif node == self.head: return elif node == self.tail: prv = node.prev prv.next = None self.tail = prv node.next = self.head node.prev = None self.head.prev = node self.head = node return else: prv = node.prev nxt = node.next prv.next = nxt nxt.prev = prv node.prev = None node.next = self.head self.head.prev = node self.head = node return """ Removes the input node from its current spot in the List and inserts it as the new tail node of the List. """ def move_to_end(self, node): if self.length == 0: self.print_list() return elif self.length == 1: self.print_list() return elif node == self.tail: self.print_list() return elif node == self.head and self.length == 2: nxt = node.next node.prev = nxt node.next = None nxt.prev = None nxt.next = node self.tail = node self.head = nxt return elif node == self.head: self.print_list() nxt = self.head.next nxt.prev = None self.head = nxt node.prev = self.tail node.next = None self.tail = node self.print_list() return else: self.print_list() nxt = node.next prv = node.prev nxt.prev = prv prv.next = nxt node.prev = self.tail self.tail.next = node node.next = None self.tail = node self.print_list() return """ Deletes the input node from the List, preserving the order of the other elements of the List. """ def delete(self, node): current = self.head while current: if current == node and current == self.head: if not current.next: current = None self.head = None self.tail = None self.length -= 1 return else: nxt = current.next current.next = None nxt.prev = None current = None self.head = nxt self.length -= 1 return elif current == node: if current.next: nxt = current.next prv = current.prev prv.next = nxt nxt.prev = prv current.next = None current.prev = None current = None self.length -= 1 return else: prv = current.prev prv.next = None current.prev = None current = None self.tail = prv self.length -= 1 return current = current.next """ Finds and returns the maximum value of all the nodes in the List. """ def get_max(self): current = self.tail mx = self.tail.value while current.prev: self.print_list() if int(current.value) > mx: mx = current.value current = current.prev return mx
import sys import re if len(sys.argv) is not 2: print "Invalid number of arguments. Usage: 'python part3_worldcup1.py worldcup.txt'" file = open(sys.argv[1], 'r') current_line = "" for line in file: junk_match = re.match(r"^\|-|!|\|\d*\|\||\|\}", line) country_match = re.match(r"^.*\{\{fb\|([A-Z]*).*$", line) if not junk_match: if country_match: country = country_match.group(1) place = 0 else: place += 1 for result in line.split(','): year_match = re.match(r"^.*?\|(\d{4})\]\]", result) if year_match: print country + "," + year_match.group(1) + "," + str(place)
#!/usr/bin/python print("Welcome to word counter!") fileInput = input("Enter a file name: ") numWords = 0 with open(fileInput,"r") as doc: for words in doc: wordList = words.split() numWords += len(wordList) print("Number of words: %i" % numWords)
#!/usr/bin/env python3 def merge(l1, l2): i = j = 0 l = [] while i < len(l1) and j < len(l2): if l1[i] <= l2[j]: l.append(l1[i]) i += 1 else: l.append(l2[j]) j += 1 l.extend(l1[i:]) l.extend(l2[j:]) return l if __name__ == '__main__': assert merge([], []) == [] assert merge([1], []) == [1] assert merge([], [1]) == [1] assert merge([1,1,1], [2,2,2]) == [1,1,1,2,2,2] assert merge([1, 4, 5, 6], [2, 3, 5]) == [1, 2, 3, 4, 5, 5, 6]
""" CAP4640/5605 Project 1 - Python Basics Author: Paul Firaza Version: 1/15/2018 Email: n01388082@ospreys.unf.edu """ import csv class State: """ State class contains: - __init__ creates a State object with 6 different datas( State Name, City,Abrv,Population,Region and House Seats ) - setters and getters for each individual data - __gt__ that compares 2 State Object's Name Alphabetically -__str__ pertains different variations of prints which are( 1.)Print Title Format 2.)Print State Format 3.) Searched State Format ) """ def __init__ (self,newname,newcity,newabrv,newpopu,newregion,newseat): """ __init__ Function: - Creates a State Object. Param: - Self(calls itself) - newname(define State's name) - newcity(define State's City) -newabrv(define State Abrv) -newpopu(Define Population) -newregion(Define House Seat No.) """ self.name = newname self.city = newcity self.abrv = newabrv self.popu = newpopu self.region = newregion self.seat = newseat def getName(self): """ getName Function: - Gets the State object's State Name. Param: - Self(calls itself) """ return self.name def getCity(self): """ getCity Function: - Gets the State object's State City. Param: - Self(calls itself) """ return self.city def getAbrv(self): """ getAbrv Function: - Gets the State object's State Abrreviation. Param: - Self(calls itself) """ return self.abrv def getPopu(self): """ getPopu Function: - Gets the State object's Population. Param: - Self(calls itself) """ return self.popu def getRegion(self): """ getRegion Function: - Gets the State object's State Region. Param: - Self(calls itself) """ return self.region def getSeat(self): """ getSeat Function: - Gets the State object's State House Seat No. Param: - Self(calls itself) """ return self.seat def setName(self,newname): """ setName Function: - Replace the State object's State Name. Param: - Self(calls itself) - newname(replacement for current name) """ self.name = newname def setCity(self,newcity): """ setCity Function: - Replace the State object's State City. Param: - Self(calls itself) - newcity(replacement for current city) """ self.city = newcity def setAbrv(self,newabrv): """ setAbrv Function: - Replace the State object's State Abbreviation. Param: - Self(calls itself) - newcity(replacement for current abbreviation) """ self.abrv = newabrv def setPopu(self,newpopu): """ setPopu Function: - Replace the State object's State Population. Param: - Self(calls itself) - newcity(replacement for current population) """ self.popu = newpopu def setRegion(self,newregion): """ setRegion Function: - Replace the State object's State Region. Param: - Self(calls itself) - newcity(replacement for current region) """ self.region = newregion def setSeat(self,newseat): """ setSeat Function: - Replace the State object's State House Seat Numbers. Param: - Self(calls itself) - newcity(replacement for current numbers) """ self.seat = newseat def comma(self): string = "{:,}".format(int(self.popu)) return string def __gt__(self,operator,self2): """ __gt__ Function: - Compare 2 State objects by their State Names Param: - Self(calls itself/1st StateObject) - operator(operator used to compare) - self2(2nd StateObject) """ if(operator == '>'): return self.getName()>self2.getName() elif(operator == '<'): return self.getName()<self2.getName() elif(operator == '='): return self.getName() == self2.getName() def __str__(self,option): """ __str__ Function: - Prints the State objects with various modes based on option which are( 1.)Print Title Format 2.)Print State Format 3.) Searched State Format ) Param: - Self(calls itself/1st StateObject) - option(defines the print style it chooses) """ if(option == 1): print(self.name + ((16-len(self.getName()))*" ")+ self.city + ((14 -len(self.getCity()))*" ") + self.abrv +" " + str(self.popu) + ((16 -len(self.getPopu()))*" ") + self.region + ((16-len(self.getRegion()))*" ") + self.seat) elif(option == 2): print(self.name + ((16-len(self.getName()))*" ")+ self.city + ((14 -len(self.getCity()))*" ") + (5*" ") + self.abrv + (7 *" ") + self.comma() + ((16 - (len(self.getPopu()) + (len(self.getPopu())-1)/3))*" ") + self.region + ((16-len(self.getRegion()))*" ") +(6*" " ) + self.seat) elif(option == 3): print("State Name: " +(7*" ") + self.getName()) print("Capital City: "+(5*" ") + self.getCity()) print("State Abrv: "+ (7*" ") +self.getAbrv()) print("State Population: " + self.comma()) print("Region: "+(11*" ") + self.getRegion()) print("US House Seats: " +(3*" ") +self.getSeat()) def main(): """ Main Function: - Reads a File specified by user input. - Shows the Menu Choices by which they are activated here. Exceptions: IOError - will return "File not Found" """ while True: try: filename = raw_input("Insert File Name: ") f = open(filename) csv_f = csv.reader(f) break except IOError: print("File not Found.") x = 1 count = 0 lexi = False title = [] pjList = [] for row in csv_f: temp = State(row[0],row[1],row[2],row[3],row[4],row[5]) if(count == 0): title.insert(count,temp) else: pjList.insert(count-1,temp) count+=1 while(x != '5'): print("\n1.State Report") print("2.Sort Alphabetically") print("3.Sort by Population") print("4.Find State") print("5.Quit \n") while(count > -1): x = raw_input("Choose an Option: ") if x == '1': State.__str__(title[0],1) option1(pjList) elif x == '2': option2(pjList,0,(len(pjList)-1)) print("\nList ordered by Name.") lexi = True elif x == '3': option3(pjList) print("\nList ordered by Population.") lexi = False elif x == '4': option4(pjList,lexi) elif x == '5': break else: print("Invalid Key") continue break print("Goodbye.Have a NICE DAY!!") def option1(pjList): """ Option 1 Function: - It loops a given list based on its length using the __str__ function in the State Class Param: - pjList: A State object List which contains data from the given file """ print(94 *"-") for row in range(len(pjList)): State.__str__(pjList[row],2) def option2(pjList, low, high): """ Option 2 Function: - A QuickSort variant that organizes the list into alphabetical order Param: - pjList: A State object List which contains data from the given file Return?: - returns an organized list by State Name """ if(low < high): pi = partition(pjList,low,high) option2(pjList,low,pi - 1) option2(pjList,pi+1,high) def option3(pjList): """ Option 3 Function: - A Radix variant that organizes the list into numerical order Param: DLLs pjList: A State object List which contains data from the given file Return?: - returns an organized list by population """ repeat = 0 for w in range(1,len(pjList)): if repeat < int(State.getPopu(pjList[w])): repeat = int(State.getPopu(pjList[w])) pos = 1 while (repeat/pos )> 0: CSort(pjList,pos) pos *= 10 def option4(pjList,lexi): """ Option 4 Function: - Searches States Name in the list and Finds the match. Exact Match Only(Prefixes incompatible) - Uses Binary/Sequential Sort based on the lexi Boolean Param: - pjList: A State object List which contains data from the given file - lexi: boolean that returns true when option 2 is used last Return?: - returns a match ( if not found: Prints error and ends option 4) """ choice = raw_input("\nInsert State Name:") count= 0 print("") if(lexi == False): print("Sequential Search:\n") while(count<len(pjList)): if(State.getName(pjList[count]) == choice): State.__str__(pjList[count],3) break count+=1 if(count == len(pjList)): print("Error: " + choice + " is not found." ) else: print("Binary Search:\n") n = len(pjList)-1 l = 0 stop = 0 while(stop != 5): loop = l+(n-l)/2 if(loop == 49): stop +=1 if(stop == 5): print("Error: " + choice + " is not found.") if(State.getName(pjList[loop]) == choice): State.__str__(pjList[loop],3) break elif(State.getName(pjList[loop]) > choice): n = loop-1 else: l = loop+1 def partition(pjList,low,high): """ Partition Function: - An extention for option 2 quicksort algorithm that organize data based upon the pivot point Param: - pjList: A State object List which contains data from the given file - low : start of the list - high : end of the list Return?: - returns a partition sorted list,which will eventually be repartitioned by option2 function """ count = (low -1) pivot = pjList[high] for x in range(low,high): if (State.__gt__(pjList[x],'<',pivot) == True | State.__gt__(pjList[x],'=',pivot) == True): count += 1 pjList[count],pjList[x] = pjList[x],pjList[count] pjList[count + 1],pjList[high] = pjList[high],pjList[count + 1] return(count + 1) def CSort(pjList,pos): """ CSort Function: - An extention for option 3 radix algorithm that organize data based upon the counting sort algorithm Param: - pjList: A State object List which contains data from the given file - pos : an int used to divide the population variable in order to get a specific digit's modulus 10 ( Ex: 1234/pos(10) = 123 -> 123%10 = 3 ) Return?: - returns a counting sorted list,which will eventually be repeated in increasing pos in order to complete option 3's radix sort. """ pjList2 = [0] * (len(pjList)) temp = [0] * 10 for x in range(len(pjList)): index = (int(State.getPopu(pjList[x]))/pos) temp[ (index)%10 ] += 1 for y in range(1,10): temp[y] += temp[y-1] i = len(pjList) -1 while i >= 0: index =(int(State.getPopu(pjList[i]))/pos) pjList2[ temp[(index) %10] - 1 ]= State.getPopu(pjList[i]) temp[index % 10] -= 1 i -= 1 for g in range(len(pjList)): tempo = pjList[g] for h in range(len(pjList)): if int(pjList2[g]) == int(State.getPopu(pjList[h])) : pjList[g] = pjList[h] pjList[h] = tempo break for z in range(len(pjList)): State.setPopu(pjList[z],pjList2[z]) if __name__ == "__main__": main()
# import libraries import urllib2 from bs4 import BeautifulSoup # specify the url quote_page = 'https://projects.fivethirtyeight.com/soccer-predictions/mls/' req = urllib2.Request(quote_page) response = urllib2.urlopen(req) # query the website and return the html to the variable page page = response print page # parse the html using beautiful soup and store in variable `soup` soup = BeautifulSoup(page, 'html.parser') # Take out the <div> of name and get its value name_box = soup.find('h1') name = name_box.text.strip() # strip() is used to remove starting and trailing print name_box # get the index price #name2_box = soup.find('div', attrs={'class': 'logo'}) #print name2_box
# a < b < c # a**2 + b**2 = c**2 # a + b + c = 1000. # a*b*c = ? import traceback for a in range(3,1000): for b in range(a+1, 999-a): c = 1000 - a - b traceback.print_exc() if c**2 == a**2 + b**2: print(a,b,c) print(a*b*c)
import urllib2 ## There's also urllib. response = urllib2.urlopen ('http://api.wunderground.com/api/063bc5d3a98d95bf/conditions/q/DC/Washington.json') ## Note the very end of the URL. It's a query about weather in DC. ## I created a weather underground account and got a key. Did I need it to do the above? import json forecast = json.load (response) ## Response is the parent in a big, nested dictionary that weather underground displays. ## forecast ['current observation'] would return all of the data nested under 'current observation' on the web page. print forecast ['current_observation']['temp_f'] #This returns just one item from the web page: the temp in Fahrenheit.
class Stack: def __init__(self): self.stack=[] def pop(self): return self.stack.pop() def push(self,item): self.stack.append(item) def peek(self): return self.stack[-1] def isEmpty(self): return len(self.stack)==0 def size(self): return len(self.stack) def main(): s=Stack() s.push(1) s.push(5) s.push('dog') print(s.size()) print(s.pop()) print(s.peek()) print(s.size()) print(s.isEmpty()) if __name__=='__main__': main()
def insertionSort(aList): for i in range(1,len(aList)): currentvalue=aList[i] position=i while currentvalue<aList[position-1] and position>0: aList[position]=aList[position-1] position-=1 aList[position]=currentvalue return aList alist = [54,26,93,17,77,31,44,55,20] insertionSort(alist) print(alist)
# Assignment Number...: 1 # Student Name........: 오승환 # File Name...........: hw1_오승환 # Program Description.: 기본적인 자료형과 input 함수를 활용하는 법을 익히는 과제입니다. season = input("What is your favorite season? ") #input 함수를 사용하여 값을 입력받아 변수에 할당한다. print(season) #print 함수를 사용하여 변수 season에 할당된 값을 출력한다. date = input("Which date were you born? ") print(type(date)) print(type(float(date))) #float 함수를 사용하여 변수 date의 자료형을 float 타입으로 변경한다. print("My favorite season is", season + ".", "I was born on the", date + "th.") #print 함수를 사용하여 좋아하는 계절과 태어난 날짜를 한 문장으로 결합한다. #"My favorite season is" 문자열과 변수 season을 결합할 때는 띄어써야 하므로 comma를 사용하였다. #변수 season과 마침표를 결합할 때는 결합시 띄어쓰기를 하지 않는 '+' 기호를 사용하였다. #마침표와 뒤의 문자열과 결합할 때는 띄어쓰기를 위해 comma를 사용하였다. #"I was born on the" 문자열과 변수 date를 결합할 때는 띄어써야 하므로 comma를 사용하였다. #변수 date와 뒤의 문자열 "th."를 결합할 때는 결합시 띄어쓰기를 하지 않는 '+' 기호를 사용하였다.
# Computes approximate solutions to differential equations of the form dy/dx = f(y) using Euler's method # (also known as autonomous or time-invariant systems) import matplotlib.pyplot as plt import numpy as np def calculate_next_point(last_point, delta, derivative_function): '''Calculates the next point given the last point, a delta and the derivative function''' return [last_point[0] + delta, last_point[1] + derivative_function(last_point[1]) * delta] def compute_approximate_solution(initial_point, delta, derivative_function, end_x): '''Computes an approximate solution to the given differential equation''' solution = [initial_point] while solution[-1][0] < end_x: solution.append(calculate_next_point(solution[-1], delta, derivative_function)) return solution # User input ------------------------------------------------------------ # The f(y) in our equation (the function that gives the derivative) user_function_string = input('Enter an expression for f(y) in the equation dy/dx = f(y): ') user_function = compile('x = ' + user_function_string, 'user', 'single') def f(i): ns = {'y': i} exec(user_function, ns) print(ns['x']) return ns['x'] # The initial value of the function initial_point = input('Initial point of the form <x,y> for the approximation [enter for <0,3>]').split(',') if initial_point == ['']: initial_point = [0, 3] else: initial_point = [float(x) for x in initial_point] # The various 'delta x's to use in Euler's method deltas = input('List of deltas of the form <x,y,z> [press enter for <2,1,0.1>]: ').split(',') if deltas == ['']: deltas = [2, 1, 0.1] else: deltas = sorted([float(x) for x in deltas], reverse=True) # The last x value we want to compute (the length of the approximation) end_x = float(input('Greatest x value for the approximation: ')) # Compute the approximations with different deltas solutions = [compute_approximate_solution(initial_point, d, f, end_x) for d in deltas] # Isolate x and y xs = [[n[0] for n in s] for s in solutions] ys = [[n[1] for n in s] for s in solutions] # Plot result ------------------------------------------------------------ plt.rcParams['font.family'] = 'serif' plt.rcParams['font.serif'] = 'Helvetica Neue' plt.rcParams['font.size'] = 10 plt.style.use('fivethirtyeight') for i in range(len(solutions)): plt.plot(xs[i], ys[i], label='delta = ' + str(deltas[i])) plt.xlabel('x') plt.ylabel('y(x)') plt.title('Approximations to y(x)') plt.legend() plt.show()
import datetime import time start_time = time.time() # options date res = [] def next_weekday(d, weekday): days_ahead = weekday - d.weekday() if days_ahead <= 0: # Target day already happened this week days_ahead += 7 return d + datetime.timedelta(days_ahead) for i in range(0,28,7): x = next_weekday(datetime.date.today() + datetime.timedelta(i), 3) day = x.strftime("%d") month = x.strftime("%b") year = x.strftime("%Y") # print(day+'-'+month+'-'+year) res.append(day+'-'+month+'-'+year) import calendar from datetime import date, datetime for i in range(4): if i == 3: month = calendar.monthcalendar(datetime.today().year, 12) else: month = calendar.monthcalendar(datetime.today().year, datetime.today().month+1+i) thrusday = max(month[-1][calendar.THURSDAY], month[-2][calendar.THURSDAY]) day = str(thrusday) if i == 3: currentmonth = datetime.strptime(str(12), "%m").strftime("%b") else: currentmonth = datetime.strptime(str(datetime.today().month+1+i), "%m").strftime("%b") year = str(datetime.today().year) res.append(day+'-'+currentmonth+'-'+year) print(res) # futures date from datetime import datetime res1 = [] temp = 0 i = 0 # for i in range(3): while i < 3: month = calendar.monthcalendar(datetime.today().year, datetime.today().month+temp+i) thrusday = max(month[-1][calendar.THURSDAY], month[-2][calendar.THURSDAY]) # print(type(date.today().strftime("%d"))) # if thrusday < int(date.today().strftime("%d")): # temp = 1 # i-=1 # continue present = datetime.now() # print(present) day = str(thrusday) # currentmonth = datetime.strptime(str(datetime.today().month+temp+i), "%m").strftime("%b") currentmonth = str(datetime.strptime(str(datetime.today().month+temp+i), "%m").strftime("%m")) year = str(datetime.today().year) # print(datetime(int(year), int(datetime.strptime(str(datetime.today().month+temp+i), "%m").strftime("%m")), int(day))) # print(datetime(int(year), int(datetime.strptime(str(datetime.today().month+temp+i), "%m").strftime("%m")), int(day)) < present) # print(datetime(int(year), int(datetime.strptime(str(datetime.today().month+temp+i), "%m").strftime("%m")), int(day), 23, 59, 0)) if datetime(int(year), int(datetime.strptime(str(datetime.today().month+temp+i), "%m").strftime("%m")), int(day), 23, 59, 0) < present: temp = 1 i-=1 else: # res1.append(day+'-'+currentmonth+'-'+year) res1.append(year+'-'+currentmonth+'-'+day) i+=1 print(res1) # API import gspread from oauth2client.service_account import ServiceAccountCredentials from pprint import pprint # Authorize the API scope = [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file' ] file_name = 'client_key.json' creds = ServiceAccountCredentials.from_json_keyfile_name(file_name,scope) client = gspread.authorize(creds) # Fetch data from sheet print("start") for i in range(1,9): sheet1 = client.open('ISB shareable-'+str(i)).worksheet('ISB OPTION CHAIN - NIFTY') print("Opened sheet", i, "NIFTY") sheet1.update_cell(2, 2, res[i-1]) print("Updated sheet", i, "NIFTY") sheet2 = client.open('ISB shareable-'+str(i)).worksheet('ISB OPTION CHAIN - BANK NIFTY') print("Opened sheet", i, "BANKNIFTY") sheet2.update_cell(2, 2, res[i-1]) print("Updated sheet", i, "BANKNIFTY") sheet = client.open('ISB shareable-1').worksheet('ISB FUTURES') print("Opened sheet FUTURES") print(res1[0]) sheet.update_cell(1, 1, ('=IMPORTXML("https://www.moneycontrol.com/india/indexfutures/nifty/9/'+res1[0]+'/", "//*[contains(@class, \'r_28\')]")')) sheet.update_cell(2, 1, ('=IMPORTXML("https://www.moneycontrol.com/india/indexfutures/nifty/9/'+res1[1]+'/", "//*[contains(@class, \'r_28\')]")')) sheet.update_cell(3, 1, ('=IMPORTXML("https://www.moneycontrol.com/india/indexfutures/nifty/9/'+res1[2]+'/", "//*[contains(@class, \'r_28\')]")')) sheet.update_cell(1, 2, ('=IMPORTXML("https://www.moneycontrol.com/india/indexfutures/banknifty/23/'+res1[0]+'/", "//*[contains(@class, \'r_28\')]")')) sheet.update_cell(2, 2, ('=IMPORTXML("https://www.moneycontrol.com/india/indexfutures/banknifty/23/'+res1[1]+'/", "//*[contains(@class, \'r_28\')]")')) sheet.update_cell(3, 2, ('=IMPORTXML("https://www.moneycontrol.com/india/indexfutures/banknifty/23/'+res1[2]+'/", "//*[contains(@class, \'r_28\')]")')) print("Updated sheet FUTURES") print("done") print("--- %s seconds ---" % (time.time() - start_time))
__author__ = 'elpython3' import pygame # The module to make games. import sys # To close the game without error output. from pygame.font import SysFont # Initialize Pygame pygame.init() # This game is open-sourced. If you wish to mod this and make it public, please reference me. # If you are using this file and want to mod it, get an IDLE, such as Visual Studio Code. # To compile this game to an executable, please install Pyinstaller using pip. The command to install for Windows: pip install pyinstaller # To compile this game to an executable, please install Pyinstaller using pip. The command to install for linux: pip3 install pyinstaller # To turn the .py file into an executable, the command is: pyinstaller (type in the name of this file) --onefile # Get the colors all set up and initialized. Each color is in RGB code (search up on the web for more info). RED = (255, 0, 0) ORANGE = (255, 150, 0) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) BLUE = (0, 0, 255) MIDNIGHT_BLUE = (25, 25, 125) PURPLE = (50, 0, 50) PINK = (255, 0, 255) SILVER = (192, 192, 192) BLACK = (0, 0, 0) WHITE = (255, 255, 255) def makeFromASCII(ascii, fgColor=(255,255,255), fgColor2=(0,0,0), fgColor3=(0,0,0), fgColor4=(0, 0, 0)): """Returns a new pygame.Surface object that has the image drawn on it as specified by the ascii parameter. The first and last line in ascii are ignored. Otherwise, any X in ascii marks a pixel with the foreground color and any other letter marks a pixel of the background color. The Surface object has a width of the widest line in the ascii string, and is always rectangular.""" """ This function will be inherited into every sprite that will inherit this function, according to the laws of Object-Orientated Programming. """ ascii = ascii.split('\n')[1:-1] width = max([len(x) for x in ascii]) height = len(ascii) surf = pygame.Surface((width, height), pygame.SRCALPHA, 32) # surf.fill(bgColor) surf = surf.convert_alpha() pArr = pygame.PixelArray(surf) for y in range(height): for x in range(len(ascii[y])): if ascii[y][x] == 'X': pArr[x][y] = fgColor if ascii[y][x] == 'P': pArr[x][y] = fgColor2 if ascii[y][x] == '#': pArr[x][y] = fgColor3 if ascii[y][x] == 'E': pArr[x][y] = fgColor4 return surf spaceship = """ X XXXXX XXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX PPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPP PPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPP PPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPP PPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPP PPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPP PPPPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPPPP PPPPPPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPPP XXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXX PPPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPP XXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXX PPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPP XXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXX PPPPPPPPPPPPPPPP PPPPPPPPPPPPPPP XXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXX PPPPPPPPPPPPPPP PPPPPPPPPPPPPP XXXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXXX PPPPPPPPPPPPPP PPPPPPPPPPPPP XXXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXXXX PPPPPPPPPPPPP PPPPPPPPPPPP XXXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXX PPPPPPPPPPPP PPPPPPPPPPP XXXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXXX PPPPPPPPPPP PPPPPPPPPP XXXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXXX PPPPPPPPPP PPPPPPPPP XXXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXXX PPPPPPPPP PPPPPPPP XXXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXXX PPPPPPPP PPPPPPP XXXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXXX PPPPPPP PPPPPP XXXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXXX PPPPPP PPPPP XXXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXXX PPPPP PPPP XXXXXXXXXXXXPPPPPPPPXXXXXXXXXXXX PPPP PPP XXXXXXXXXXXPPPPPPPPXXXXXXXXXXX PPP PP XXXXXXXXXXPPPPPPPPXXXXXXXXXX PP PP XXXXXXXXXPPPPPPPPXXXXXXXXX PP PP PPPPPPPP PP P PPPPPPPP P """ bullet = """ X XXX XXXXX XXXXXXX XXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX """ missle = """ XXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXX XXXXXXX XXXXX XXX X """ alien = """ XXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXX XXXXXXX XXXXX XXX X """ boss = """ PP PP PPP PPP PPPP PPPP PPPPP XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX PPPPP PPPPPP XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX PPPPPP PPPPPPP XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX PPPPPPP PPPPPPPP XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX PPPPPPPP PPPPPPPPP XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX PPPPPPPPP PPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPPP PPPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPPP PPPPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPPP PPPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPPP PPPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPPP PPPPPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPPPPP PPPPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPPPP PPPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPPP PPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPP PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXP XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXX XXXXXXX XXXXX XXX X """ class SpriteTemplate(pygame.sprite.Sprite): # Make some optional parameters, as some sprites do not use these parameters def __init__(self, image, speed, color1=(0, 0, 0), color2=(0, 0, 0), color3=(0, 0, 0), color4=(0, 0, 0), armor=0): # Put this line so some sprites are allowed to be put into Group, a list-like object from pygame super().__init__() # Make our image self.image = makeFromASCII(image, color1, color2, color3, color4) self.rect = self.image.get_rect() self.mask = pygame.mask.from_surface(self.image) self.speed = speed self.armor = armor self.vel = 0 self.kill_this_sprite = False def update(self): # If the sprite needs to dissapear, kill the sprite if self.kill_this_sprite == True: self.kill() def blitme(self): TMRC.screen.blit(self.image, self.rect) class Player(SpriteTemplate): """ Create our player, the spaceship """ def __init__(self): SpriteTemplate.__init__(self, spaceship, 5, SILVER, RED, BLUE, ORANGE) self.rect.midbottom = TMRC.screen_rect.midbottom self.move_right = False self.move_left = False self.vel = float(self.rect.x) def update(self): SpriteTemplate.update(self) if self.move_left and self.rect.left > TMRC.screen_rect.left: self.vel -= self.speed if self.move_right and self.rect.right < TMRC.screen_rect.right: self.vel += self.speed self.rect.x = self.vel def blitme(self): SpriteTemplate.blitme(self) class Bullet(SpriteTemplate): """ Create the bullet that the player will shoot. These bullets will dissapear when they reach the top of the screen. """ def __init__(self): SpriteTemplate.__init__(self, bullet, 10, ORANGE) self.rect.center = TMRC.player.rect.midtop self.vel = float(self.rect.y) def update(self): SpriteTemplate.update(self) self.vel -= self.speed self.rect.y = self.vel if self.rect.bottom < TMRC.screen_rect.top: # Less than because the coordinates (0, 0) would mean the topleft of the screen. self.kill_this_sprite = True def blitme(self): SpriteTemplate.blitme(self) class Alien(pygame.sprite.Sprite): """ Our enemy. We need to shoot each one of them, or else they will make it to their target and destroy the galaxy we live in. """ def __init__(self): super().__init__() # Make our image self.image = makeFromASCII(alien, GREEN) self.rect = self.image.get_rect() self.mask = pygame.mask.from_surface(self.image) self.speed = 3 self.armor = 0 self.vel = 0 self.kill_this_sprite = False self.x = float(self.rect.x) def update(self): self.x += (self.speed * TMRC.direction) # self.x += self.speed self.rect.x = self.x def check_edges(self): screen_rect = TMRC.screen.get_rect() if self.rect.right >= screen_rect.right or self.rect.left <= screen_rect.left: return True def blitme(self): TMRC.screen.blit(self.image, self.rect) class Missle(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = makeFromASCII(missle, RED) self.rect = self.image.get_rect() self.rect.center = TMRC.bossSprite.rect.center self.speed = 3 self.steer_speed = 5 self.xvel = float(self.rect.x) self.yvel = float(self.rect.y) def update(self): self.yvel += self.speed self.rect.y = self.yvel if TMRC.player.rect.right + 10 < self.rect.left: self.xvel -= self.steer_speed if TMRC.player.rect.left - 10 > self.rect.right: self.xvel += self.steer_speed self.rect.x = self.xvel def blitme(self): TMRC.screen.blit(self.image, self.rect) class Boss(SpriteTemplate): def __init__(self): SpriteTemplate.__init__(self, boss, 0, SILVER, GREEN, armor=3) self.rect.midtop = TMRC.screen_rect.midtop self.timer_ticks = pygame.time.get_ticks() def update(self): SpriteTemplate.update(self) if ((pygame.time.get_ticks()-self.timer_ticks)/1000) >= 3: newMissle = Missle() TMRC.missle_list.add(newMissle) self.timer_ticks = pygame.time.get_ticks() if self.armor == 0: TMRC.boss_destroyed = True TMRC.boss = False class Button(pygame.sprite.Sprite): def __init__(self, word='', fontcolor=(0,0,0), backgroundcolor=(0,0,0)): super().__init__() self.color = fontcolor self.backgroundcolor = backgroundcolor self.word = word self.font = SysFont('Ubuntu', 50, False, False) def prep_button(self): self.image = self.font.render(self.word, True, self.color, self.backgroundcolor) self.rect = self.image.get_rect() self.rect.center = TMRC.screen_rect.center def blitme(self): TMRC.screen.blit(self.image, self.rect) class ScoreBoard(pygame.sprite.Sprite): def __init__(self): self.color = WHITE self.font = SysFont('Ubuntu', 50, False, False) def prep_scoreboard(self): self.scoreimage = self.font.render("Score: " + str(TMRC.score), True, self.color) self.levelimage = self.font.render("Level: " + str(TMRC.level), True, self.color) self.score_rect = self.scoreimage.get_rect() self.level_rect = self.levelimage.get_rect() self.score_rect.topleft = TMRC.screen_rect.topleft self.level_rect.x = self.score_rect.x self.level_rect.y = self.score_rect.y + 50 def blitme(self): TMRC.screen.blit(self.scoreimage, self.score_rect) TMRC.screen.blit(self.levelimage, self.level_rect) class TheMainRunningClass(): def __init__(self): # Our function to initialize # Make our screen dimensions self.WIDTH = 1200 self.HEIGHT = 800 self.WINDOW_SIZE = [self.WIDTH, self.HEIGHT] self.WINDOW_FLAGS = pygame.DOUBLEBUF self.screen = pygame.display.set_mode(self.WINDOW_SIZE, self.WINDOW_FLAGS) self.screen_rect = self.screen.get_rect() # Set our caption for the window. pygame.display.set_caption("Super Space Defense") self.level = 1 self.score = 0 self.boss = False self.boss_destroyed = False self.set_game_active = False self.clock = pygame.time.Clock() def mainFunc(self): # Our main game loop # Set up number variables self.direction = 1 # Define our sprites; These sprites will reset their stats everytime a new level happens. Also define our groups. self.startButton = Button('PLAY', BLACK, RED) self.startButton.prep_button() self.scoreboard = ScoreBoard() self.scoreboard.prep_scoreboard() self.player = Player() self.bullet_list = pygame.sprite.Group() self.enemy_alien_list = pygame.sprite.Group() self.missle_list = pygame.sprite.Group() self.make_alien_fleet() while True: # Bug checker (will be deleted when put on github) # print(str(self.screen_rect.left) + ", " + str(self.player.rect.left)) # Check for events for event in pygame.event.get(): if event.type == pygame.QUIT: # If we clicked on the red X sys.exit() if event.type == pygame.KEYDOWN: # Our check if we are pressing on the keyboard. if event.key == pygame.K_LEFT: self.player.move_left = True if event.key == pygame.K_RIGHT: self.player.move_right = True if event.key == pygame.K_SPACE: if self.set_game_active == True: self.fire_bullet() if event.type == pygame.KEYUP: # Our check if we are letting go of the keyboard. if event.key == pygame.K_LEFT: self.player.move_left = False if event.key == pygame.K_RIGHT: self.player.move_right = False if event.type == pygame.MOUSEBUTTONDOWN: # If we clicked on the mouse... mouse_pos = pygame.mouse.get_pos() if event.button == 1: # To be precise, if we left-clicked on the mouse... clicked = self.startButton.rect.collidepoint(mouse_pos) if clicked: self.set_game_active = True self.boss_destroyed = False # Update our sprites self.update() # Blit our sprites to our screen self.blit_everything_onto_screen() # Call the function to destroy the aliens self.check_bullet_alien_collision() # Call the function to make the aliens change dir self._check_fleet_edges() # Set our fps to 60 self.clock.tick(60) # Let us see what we have drawn. pygame.display.flip() # Just to be safe, kill the program if the game is closed. sys.exit() def update(self): if self.set_game_active == True: for bullet in self.bullet_list: bullet.update() self.player.update() for alien in self.enemy_alien_list: alien.update() if self.boss == True: self.bossSprite.update() self.bossisdestroyed() for missle in self.missle_list: missle.update() self._check_collision_on_bottom() self.scoreboard.prep_scoreboard() def blit_everything_onto_screen(self): # Draw everything onto the screen. Order matters. # Fill the background a specific color, say midnight blue self.screen.fill(MIDNIGHT_BLUE) # Draw the bullets. These will go below the player (makes more sense) for bullet in self.bullet_list: bullet.blitme() # Draw our infamous player, the spaceship self.player.blitme() # Draw our enemy aliens for alien in self.enemy_alien_list: alien.blitme() for missle in self.missle_list: missle.blitme() if self.boss == True: self.bossSprite.blitme() self.scoreboard.blitme() if self.set_game_active == False: self.startButton.blitme() # Make special functions def fire_bullet(self): # If our amount of ammo shot is less than five, then fire a bullet. Else, lets reload. if len(self.bullet_list) <= 5: newBullet = Bullet() self.bullet_list.add(newBullet) def make_alien_fleet(self): alien = Alien() alien_width, alien_height = alien.rect.size avaliable_space_x = self.WIDTH - (2 * alien_width) number_aliens_x = avaliable_space_x // (2 * alien_width) ship_height = self.player.rect.height avaliable_space_y = (self.HEIGHT - (3 * alien_height) - ship_height) # number_rows = avaliable_space_y // (2 * alien_height) number_rows = 4 for row_number in range(number_rows): for alien_number in range(number_aliens_x): self._create_alien(alien_number, row_number) def _create_alien(self, alien_number, row_number): alien = Alien() alien_width, alien_height = alien.rect.size alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number self.enemy_alien_list.add(alien) def check_bullet_alien_collision(self): # Detects if we destroyed something self.collide = pygame.sprite.groupcollide(self.bullet_list, self.enemy_alien_list, True, True) self.collide2 = pygame.sprite.groupcollide(self.bullet_list, self.missle_list, True, True) if self.level == 5: self.collide3 = pygame.sprite.spritecollide(self.bossSprite, self.bullet_list, True) # Add to our score if self.collide: self.score += 10 if self.collide2: self.score += 20 if self.level == 5: if self.collide3: self.bossSprite.armor -= 1 self.score += 20 # Now detect if there are no aliens if not self.enemy_alien_list and not self.boss: self.bullet_list.empty() self.enemy_alien_list.empty() self.level += 1 if self.level < 5: self.make_alien_fleet() elif self.level >= 5: if self.boss_destroyed == False: self.boss = True self.bossSprite = Boss() def _check_fleet_edges(self): for alien in self.enemy_alien_list.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): for alien in self.enemy_alien_list.sprites(): alien.rect.y += 10 self.direction *= -1 def _check_collision_on_bottom(self): for alien in self.enemy_alien_list.sprites(): if alien.rect.bottom >= self.screen_rect.bottom: self.player_hit() if pygame.sprite.spritecollide(self.player, self.enemy_alien_list, True): self.player_hit() for missle in self.missle_list.sprites(): if missle.rect.bottom >= self.screen_rect.bottom: self.player_hit() if pygame.sprite.spritecollide(self.player, self.missle_list, True): self.player_hit() def bossisdestroyed(self): if self.bossSprite.armor == 0: self.missle_list.empty() self.enemy_alien_list.empty() self.level = 1 self.score = 0 self.make_alien_fleet() self.set_game_active = False def player_hit(self): self.bullet_list.empty() self.enemy_alien_list.empty() self.missle_list.empty() self.make_alien_fleet() self.level = 1 self.score = 0 self.player.rect.midbottom = self.screen_rect.midbottom self.set_game_active = False TMRC = TheMainRunningClass() TMRC.mainFunc()
from flask import Flask,render_template,session,url_for,request,redirect from datetime import timedelta ''' tutorial on sessions''' app = Flask(__name__) app.permanent_session_lifetime = timedelta(minutes=5) app.secret_key = "jana" @app.route('/home') def home(): return render_template('child.html') @app.route('/login',methods=["POST","GET"]) @app.route('/',methods=["POST","GET"]) def login(): if request.method == "POST": session.permanent = True username = request.form["name"] session["uname"] = username return redirect(url_for("user")) else: if "uname" in session: return redirect(url_for("user")) return render_template('login.html') '''doubt on 17th & 18th statements. why we do that?''' ''' from session dictionary, the "uname" keyword is accessed and is copied to 'un' variable''' @app.route('/user') def user(): if "uname" in session: un = session["uname"] return f"<h4>Hello {un}! welcome to our website !</h4>" else: return redirect(url_for("login")) '''deleting an session manually''' '''similar syntax of deleting an element in a dictionary (using pop)''' @app.route('/logout') def logout(): session.pop("uname",None) return redirect(url_for("login")) if __name__== "__main__": app.run(debug=True)
#数字列から■で構成された文字に変換する def numprint(numlist): numchars =[ """ ■■■■■■■■ ■ ■ ■ ■ ■ ■ ■■■■■■■■ """, """ ■ ■ ■ ■ ■ """, """ ■■■■■■■■ ■ ■■■■■■■■ ■ ■■■■■■■■ """, """ ■■■■■■■■ ■ ■■■■■■■■ ■ ■■■■■■■■ """, """ ■ ■ ■ ■ ■■■■■■■■ ■ ■ """, """ ■■■■■■■■ ■ ■■■■■■■■ ■ ■■■■■■■■ """, """ ■■■■■■■■ ■ ■■■■■■■■ ■ ■ ■■■■■■■■ """, """ ■■■■■■■■ ■ ■ ■ ■ ■ ■ """, """ ■■■■■■■■ ■ ■ ■■■■■■■■ ■ ■ ■■■■■■■■ """, """ ■■■■■■■■ ■ ■ ■■■■■■■■ ■ ■■■■■■■■ """, """ ■ ■ """ ] #配列セットアップ for i in range(len(numchars)): #ヘッダーとフッターを削除して改行ごとに配列化 numchars[i] = numchars[i].split('\n')[1:6] tex = "" for i in range(5): for j in numlist: tex += str(numchars[j][i])+' ' tex +='\n' return tex import time,datetime import os today = datetime.datetime.fromtimestamp(time.time()) #print(today.strftime('%Y %m %d %I:%M:%S %p')) t = list(time.strftime('%I')) t.append('10') t += list(time.strftime('%M')) t = [int(i) for i in t] t =[0,0,10,0,0] count = 14*60+30#時間 dec = 10 for i in range(count)[::-1]: min = int(i/60) if min >9: t[0] = int(min /dec) t[1] = int(min%dec) else: t[0] = 0 t[1] = min sec = int(i%60) if sec >9: t[3] = int(sec / dec) t[4] = int(sec % dec) else: t[3] = 0 t[4] = sec os.system('cls') print(numprint(t)) time.sleep(1) else: os.system('cls') print(numprint(t).replace('■','□'))
# # Global Centering # # Global Centering: Calculating and subtracting the mean pixel value across color channels. # Local Centering: Calculating and subtracting the mean pixel value per color channel. from PIL import Image from numpy.core._asarray import asarray image = Image.open('sydney_bridge.jpeg') pixels = asarray(image) print('Data Type: %s' % pixels.dtype) print('Min: %.3f, Max: %.3f' % (pixels.min(), pixels.max())) pixels = pixels.astype('float32') print('Data Type: %s' % pixels.dtype) print('Min: %.3f, Max: %.3f' % (pixels.min(), pixels.max())) mean = pixels.mean() print('Mean %.3f' % mean) print('Min: %.3f, Max: %.3f' % (pixels.min(), pixels.max())) pixels = pixels - mean mean = pixels.mean() print('Mean %.3f' % mean) print('Min: %.3f, Max: %.3f' % (pixels.min(), pixels.max())) # image2 = Image.fromarray(pixels) # image2.show()
def man(): d_1 = "\n Enter 1 - to see list of all workers\n" d_2 = "Enter 2 - to see 'to-do list'\n" d_3 = "Enter 3 - list of instructions to employees\n" d_4 = "Enter 4 - show a list of all coverage for specific areas\n" d_5 = "Enter 5 - show the amount for real estate, for sale, for rent\n" d_6 = "Enter 6 - calculate% by category of real estate\n" print(d_1,d_2,d_3,d_4,d_5,d_6) m=int(input("Please dial the menu number to work with the program,\n If you're done, dial 7:")) return m
def quick_sort(arr): n=len(arr) if n<=1: return arr else: pivot = arr.pop(0) # creating 2 empty lists to segregate greater than pivot elements and less than pivot elements lesser_than_pivot = [] greater_than_pivot = [] for item in arr: if item<pivot: lesser_than_pivot.append(item) else: greater_than_pivot.append(item) return quick_sort(lesser_than_pivot) + [pivot] + quick_sort(greater_than_pivot) arr = [5, 1, 7, 2, 9, 4, 3] print(quick_sort(arr))
import abc from typing import Dict from .const import SecurityType from .date import Date, RDate from . import cashflow as cf class Index: """ This represents price of equity and FX or value of rates To be differentiated with asset, which is traded on the market and thus holds market value directly. For example the value of rates (an index) is a derived quantity from market value of bonds and swaps (assets) """ def __init__(self, index_type, name): self.index_type = index_type self.name = name class Schedule: def __init__(self, end_date, rdate: RDate): self.end_date = end_date self.rdate = rdate def set_pricing_date(self, pricing_date: Date): pass class Security(abc.ABC): def __init__(self, security_type, cashflows: Dict[Date, cf.Cashflow]): self.security_type = security_type # schedule is the dates of event that are known as of today # to be differentiate with event_dates which can be added by the pricer to improve accuracy self.cashflows = cashflows self.schedule = sorted(self.cashflows.keys()) @abc.abstractmethod def set_pricing_date(self, pricing_date: Date): pass def __str__(self): text = '' text += f'{self.security_type.name}\n' for date, cashflow in zip(self.schedule, self.cashflows): text += f'{date}: {cashflow}' return text def __repr__(self): return self.security_type.name class EuropeanOption(Security): def __init__(self, asset: str, expiry: Date, strike: float): self.asset = asset self.expiry = expiry self.strike = strike cashflows = {expiry: cf.Max(cf.Equity(asset) - strike, 0)} super(EuropeanOption, self).__init__(SecurityType.EuropeanOption, cashflows=cashflows) class BarrierOption(Security): def __init__(self, asset: str, expiry: Date, strike: float, do: float): alive = cf.Constant(1) cashflow = { } super(BarrierOption, self).__init__(SecurityType.BarrierOption)
class Machine: ingredient = ["water", "milk", "coffee beans", "disposable cups", "money"] metrics = ["ml", "ml", "grams ", "pieces"] in_machine_info = [400, 540, 120, 9, 550] menu_names = ['espresso', 'latte', 'cappuccino'] menu = [[250, 0, 16, 1, -4], [350, 75, 20, 1, -7], [200, 100, 12, 1, -6]] def enough_for_order(self, order): for n in range(len(self.ingredient)): if self.in_machine_info[n] < order[n]: return self.ingredient[n] return '' def info(self): print(f"\nThe coffee machine has:") for i in range(len(self.ingredient)): print(str(self.in_machine_info[i]) + " of " + self.ingredient[i]) def action(self): while True: print("\nWrite action (buy, fill, take, remaining, exit):") action = input() if action == "buy": self.buy() elif action == "fill": self.fill() elif action == "take": self.take() elif action == "remaining": self.info() elif action == "exit": break def buy(self): s = "\nWhat do you want to buy? " + ("%s, " * len(self.menu_names)) + "back - to main menu:" print(s % tuple([(str(n) + " - " + self.menu_names[n - 1]) for n in range(1, len(self.menu_names) + 1)])) client_input = input() if client_input == "back": return order = int(client_input) - 1 check_result = self.enough_for_order(self.menu[order]) if (len(self.menu) > order >= 0) and len(check_result) < 2: print("I have enough resources, making you a coffee!") for d in range(len(self.in_machine_info)): self.in_machine_info[d] -= self.menu[order][d] else: print(f"Sorry, not enough {check_result}!") def fill(self): for i in range(len(self.in_machine_info) - 1): print(f"Write how many {self.metrics[i]} of {self.ingredient[i]} do you want to add:") self.in_machine_info[i] += int(input()) def take(self): print(f"I gave you ${self.in_machine_info[4]}") self.in_machine_info[4] = 0 m = Machine() m.action()
# Convolutional Neural Network # Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git # Installing Tensorflow # pip install tensorflow # Installing Keras # pip install --upgrade keras # Have distinct data structure for training and test set # Part 1 - Building the CNN # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Conv2D # Speech is 1D, Image is 2D & Video are 3D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense # Initialising the CNN classifier = Sequential() # Step 1 - Convolution # Stride =1 # We start with 32 feature detectors, slowly move to 64 and 128, etc # Input shape is the image dimension/format, 3 represents the three channels- R, B & G # The dimension of the training images are > 256x256. We can use higher dim when working on GPU # Now we restrict the dimension to 64*64 # Argument order in theano is different from tf. Here we use tf backend # Activation function is to remove any linearity present by removing negative pixels in convolved image classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) # Step 2 - Pooling # Image translational invariance (or retain the spatial relationship), reduce dimension yet keep the information # We will also reduce the nodes in the flatten layer and reduce the computational intensive # Highly recomended to use 2x2 classifier.add(MaxPooling2D(pool_size = (2, 2))) # Adding a second convolutional layer classifier.add(Conv2D(32, (3, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2)))# You can control strides here as well # Step 3 - Flattening classifier.add(Flatten()) # Step 4 - Full connection classifier.add(Dense(units = 128, activation = 'relu')) classifier.add(Dense(units = 1, activation = 'sigmoid')) # Compiling the CNN # Multiple categories- softmax & categorical_cross entropy classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Part 2 - Fitting the CNN to the images from keras.preprocessing.image import ImageDataGenerator # Image Augmentation # Image/Data Augmentation avoids overfitting by generalizing the spatial relationships # Image transformation increasing the data by rotating, shearing, zoom, etc train_datagen = ImageDataGenerator(rescale = 1./255, # This is compulsory step and is like scaling of the num variables to nullify the effect of units/scale of measurement # Rescale is a value by which we will multiply the data before any other processing. Our original images consist in RGB coefficients in the 0-255, but such values would be too high for our model to process (given a typical learning rate), so we target values between 0 and 1 instead by scaling with a 1/255 shear_range = 0.2, # random shearing zoom_range = 0.2, # random zoom horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory('dataset/training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory('dataset/test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') classifier.fit_generator(training_set, steps_per_epoch = 800, epochs = 25, validation_data = test_set, validation_steps = 200) # Part 3 - Making new predictions import numpy as np from keras.preprocessing import image test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) result = classifier.predict(test_image) training_set.class_indices if result[0][0] == 1: prediction = 'dog' else: prediction = 'cat' # How can you improve the model? '1. batch normalization' '2. data augmentation' '3. pre-trained models/weights such as VGG, InceptionV3, etc.'
'''Python Mad Libs''' print "Mad Libs Start!" name = raw_input("Please input your name: ") print "We need 3 adjectives for the game." adj1 = raw_input("Please input the 1st adjective: ") adj2 = raw_input("Please input the 2nd adjective: ") adj3 = raw_input("Please input the 3rd adjective: ") print "We need 3 verbs for the game." verb1 = raw_input("Please input the 1st verb: ") verb2 = raw_input("Please input the 2nd verb: ") verb3 = raw_input("Please input the 3rd verb: ") print "We need 4 nouns for the game." noun1 = raw_input("Please input the 1st noun: ") noun2 = raw_input("Please input the 2nd noun: ") noun3 = raw_input("Please input the 3rd noun: ") noun4 = raw_input("Please input the 4th noun: ") animal = raw_input("Please input an animal: ") food = raw_input("Please input a food: ") fruit = raw_input("Please input a friut: ") number = raw_input("Please input a number: ") superhero = raw_input("Please input a superhero name: ") country = raw_input("Please input a country: ") dessert = raw_input("Please input a dessert: ") year = raw_input("Please input an year: ") print "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to %s to the rythym of the %s, which made all of the %ss very %s. %s tried to %s into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping %s into a puddle of %s. %s then fell asleep and woke up in the year %s, in a world where %ss ruled the world." %(adj1, name, verb1, adj2, noun1, noun2, animal, food, verb2, noun3, fruit, adj3, name, verb3, number, name, superhero, superhero, name, country, name, dessert, name, year, noun4)
Question 1 Which Python keyword indicates the start of a function definition? help rad break def Answer: def Question 2 In Python, how do you indicate the end of the block of code that makes up the function? You put a # character at the end of the last line of the function You de-indent a line of code to the same indent level as the def keyword You add a line that has at least 10 dashes You put the colon character (:) in the first column of a line Answer: You de-indent a line of code to the same indent level as the def keyword Question 3 In Python what is the raw_input() feature best described as? A conditional statement A data structure that can hold multiple values using strings as keys A built-in function A reserved word Answer:A built-in function What does the following code print out? def thing(): print 'Hello' print 'There' thing Hello There There Hello def thing Answer: There Question 5 In the following Python code, which of the following is an "argument" to a function? x = 'banana' y = max(x) print y print x y x print max Answer: x What will the following Python code print out? def func(x) : print x func(10) func(20) 10 20 x 10 x 20 x x func func Answer: 10 20 Question 7 Which line of the following Python program is useless? def stuff(): print 'Hello' return print 'World' stuff() print 'Hello' def stuff(): stuff() print 'World' return Answer: print "World" Question 8 What will the following Python program print out? def greet(lang): if lang == 'es': return 'Hola' elif lang == 'fr': return 'Bonjour' else: return 'Hello' print greet('fr'),'Michael' Bonjour Michael Hello Michael def Michael Hola Bonjour Hello Michael Answer: Bonjour Michaels Question 9 What does the following Python code print out? (Note that this is a bit of a trick question and the code has what many would consider to be a flaw/bug - so read carefully). def addtwo(a, b): added = a + b return a x = addtwo(2, 7) print x addtwo 2 9 Traceback Answer: 2 Question 10 What is the most important benefit of writing your own functions? To avoid having more than 10 lines of sequential code without an indent or de-indent Following the rule that whenever a program is more than 10 lines you must use a function Following the rule that no function can have more than 10 statements in it Avoiding writing the same non-trivial code more than once in your program Answer: Avoiding writing the same non-trivial code more than once in your program
# class Solution: # def __init__(self): # self.dp = {} # def tribonacci(self, n): # if n == 0: # return 0 # if n == 1 or n == 2: # return 1 # try: # return self.dp[n] # except: # self.dp[n] = self.tribonacci(n-1) + self.tribonacci(n-2) + self.tribonacci(n-3) # return self.dp[n] ans = {0:0, 1:1, 2:1} class Solution(object): def tribonacci(self, n): """ :type n: int :rtype: int """ if n in ans: return ans[n] else: ans[n] = self.tribonacci(n-1) + self.tribonacci(n-2) + self.tribonacci(n-3) return ans[n]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # 方法更快 class Solution(object): # 类函数 def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ paths = [] # 普通函数 def getPath(root, path): # 如果根节点不为空 首先把根节点加到返回的string上 更新path if root: path += str(root.val) # 如果根节点的左右子树都是空 就把当前path的值append到list 并返回 if not root.left and not root.right: paths.append(path) # 如果根节点的左右子树不都为空 就把"->"加到path后面 递归左右子树 else: path += "->" getPath(root.left, path) getPath(root.right, path) # 调用函数 getPath(root, "") return paths class Solution(object): # 类函数 def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ # 定义全局变量self.paths self.paths = [] # 调用函数 self.getPath(root, "") return self.paths # 类函数 def getPath(self, root, path): # 如果根节点不为空 首先把根节点加到返回的string上 更新path if root: path += str(root.val) # 如果根节点的左右子树都是空 就把当前path的值append到list 并返回 if not root.left and not root.right: self.paths.append(path) # 如果根节点的左右子树不都为空 就把"->"加到path后面 递归左右子树 else: path += "->" self.getPath(root.left, path) self.getPath(root.right, path)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head = ListNode(0) dummy = head total = 0 while l1 or l2 : if l1: total += l1.val l1 = l1.next if l2: total += l2.val l2 = l2.next num = total % 10 total = total / 10 tmp = ListNode(num) dummy.next = tmp dummy = tmp if total == 1: dummy.next = ListNode(1) return head.next
class Solution(object): def reformatDate(self, date): """ :type date: str :rtype: str """ day, mon, year = date.split(" ") month_map = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"} mon = month_map[mon] day = day[:-2] # return "%s-%s-%02d" % (year, mon, int(day) return "%s-%s-%02d" % (year, mon, int(day))
class Solution(object): # 回溯算法 和46题思路一样 # 不同地方是消除重复 写下两个例子就能明白了 def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # 先排序 nums.sort() n = len(nums) res = [] def helper(li, tmp_li, cnt): if cnt == n: res.append(tmp_li) for i in range(len(li)): # 判断重复数字 if i > 0 and li[i] == li[i-1]: continue helper(li[:i] + li[i+1:], tmp_li + [li[i]], cnt + 1) helper(nums, [], 0) return res # 效率很低 def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] n = len(nums) def helper(nums, temp_list, length): # 判断重复数字 if length == n and temp_list not in res: res.append(temp_list) for i in range(len(nums)): helper(nums[:i] + nums[i + 1:], temp_list + [nums[i]], length + 1) helper(nums, [], 0) return res
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def nextLargerNodes(self, head): """ :type head: ListNode :rtype: List[int] """ # 栈中存放未找到更大值的节点,以及该节点的下标 curr = head res = [] stack = [] i = 0 while curr: res.append(0) # 如果栈不空 栈顶元素小于当前curr.val 就把栈顶元素相应的res里面值换成curr.val # 并pop栈顶元素 while stack and stack[-1][0] < curr.val: res[stack[-1][1]] = curr.val stack.pop() stack.append((curr.val, i)) i += 1 curr = curr.next return res
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead. """ f = {} def find(p): # 如果p不在dict里 那么p的value设置为p f.setdefault(p, p) if f[p] != p: f[p] = find(f[p]) return f[p] def union(p, q): f[find(p)] = find(q) if not board or not board[0]: return row = len(board) col = len(board[0]) dummy = row * col # 第一次遍历整个矩阵 进行连接 for i in range(row): for j in range(col): if board[i][j] == "O": # 如果四边上出现"O" 把当前位置和dummy连接 if i == 0 or i == row - 1 or j == 0 or j == col - 1: # print i * col + j, dummy union(i * col + j, dummy) # print f # 如果"O"不在四边上 else: # 检查四个方向的值 for p, q in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # 如果任意一个方向出现"O" 就把当前位置和出现"O"的位置连接 if board[i + p][j + q] == "O": # print i * col + j, (i + p) * col + (j + q) union(i * col + j, (i + p) * col + (j + q)) # print f # 第二次遍历整个矩阵 for i in range(row): for j in range(col): if find(i * col + j) == find(dummy): board[i][j] = "O" else: board[i][j] = "X" # [["X","X","X","X"], # ["X","O","O","X"], # ["X","X","O","X"], # ["X","O","X","X"]] # 5 6 # {5: 6, 6: 6} # 6 10 # {10: 10, 5: 6, 6: 10} # 6 5 # {10: 10, 5: 10, 6: 10} # 10 6 # {10: 10, 5: 10, 6: 10} # 13 16 # {16: 16, 10: 10, 5: 10, 6: 10, 13: 16}
class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if nums == []: return [-1,-1] # 第一次二分查找需要找到最左边的target left = 0 right = len(nums)-1 while left < right: middle = (left+right)/2 if nums[middle] >= target: right = middle else: left = middle+1 if nums[right] != target: return[-1,-1] start = right # 第二次二分查找需要找到最右边的target left = 0 right = len(nums)-1 while left < right: # 向右取中位数! middle = (left+right+1)/2 if nums[middle] > target: right = middle-1 else: left = middle if nums[right] != target: return[-1,-1] end = right return [start,end] # 第一次复习写的答案 class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) == 0: return[-1,-1] # 第一次二分查找,找最左边target left = 0 right = len(nums)-1 ret = [] while left < right: mid = (left+right)/2 if nums[mid] < target: left = mid + 1 else: right = mid # 如果没找到直接返回,如果找到的话继续第二次二分查找,找最右边的target if nums[right] != target: return [-1,-1] else: # 这次的查找范围应该是在[left,right]之间,而不是[0,right],可以缩小范围 ret.append(left) right = len(nums)-1 while left < right: mid = (left+right+1)/2 if nums[mid] < target: left = mid + 1 elif nums[mid] > target: right = mid - 1 elif nums[mid] == target: left = mid ret.append(right) return ret
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ min_val = 10000 res = self.getNodes(root) # 每次比较相邻两个元素 找到小的那个 更新min for i in range(len(res) - 1): min_val = min(res[i + 1] - res[i], min_val) return min_val # 中序遍历得到节点 已排好序 def getNodes(self, root): if root == None: return [] return self.getNodes(root.left) + [root.val] + self.getNodes(root.right)
# class Solution(object): # def searchMatrix(self, matrix, target): # """ # :type matrix: List[List[int]] # :type target: int # :rtype: bool # """ # if len(matrix) == 0 or len(matrix[0]) == 0: # return False # 考虑左下角或者右上角的两个点 # 左下角 # x = len(matrix)-1 # y = 0 # while True: # if matrix[x][y] == target: # return True # elif matrix[x][y] < target: # y = y + 1 # elif matrix[x][y] > target: # x = x - 1 # if x < 0 or y >= len(matrix[0]): # return False # 第一遍复习写出答案 class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if len(matrix) == 0 or len(matrix[0]) == 0: return False m = len(matrix) n = len(matrix[0]) i = m-1 j = 0 while i >= 0 and j < n: if matrix[i][j] == target: return True elif matrix[i][j] < target: j += 1 else: i -= 1 return False
""" # Definition for a Node. class Node(object): def __init__(self, val=None, children=None): self.val = val self.children = children """ # 递归1 class Solution(object): def preorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: return [] # 先把根节点入栈 再依次访问每一个子节点 res = [root.val] for node in root.children: res.extend(self.preorder(node)) return res # 递归2 class Solution(object): def preorder(self, root): """ :type root: Node :rtype: List[int] """ def pre(root): if not root: return # 先把根节点入栈 再依次访问每一个子节点 res.append(root.val) for child in root.children: pre(child) res = [] pre(root) return res # 迭代 class Solution(object): def preorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: return None res = [] stack = [root] while stack: cur = stack.pop() # 根节点入栈 res.append(cur.val) # 从头最右边孩子开始遍历 for child in cur.children[::-1]: stack.append(child) return res
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def findDuplicateSubtrees(self, root): """ :type root: TreeNode :rtype: List[TreeNode] """ # 用一个字典存储每一个子树 包括叶子节点 出现的频率 d = collections.defaultdict(list) def dfs(root): if not root: return '' # 用"#"连接 根节点 左孩子 右孩子 s = '#'.join((str(root.val), dfs(root.left), dfs(root.right))) # 遍历出来的每一个子树都要append到d[s]对应的list后面 # dict = {"4##":[Tree1, Tree2]} d[s].append(root) # dict = {"4##":[Tree1, Tree2, root]} root被append到里面 return s dfs(root) # 对字典里每一个value,也就是相同子树的集合,如果这个value的长度大于1,也就说明相同子树至少有两个,那么返回这个树 return [l[0] for l in d.values() if len(l) > 1]
from random import choice class RandomizedSet(): def __init__(self): """ Initialize your data structure here. """ self.dic = {} self.li = [] def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. """ if val in self.dic: return False self.dic[val] = len(self.li) self.li.append(val) print self.dic, self.li return True def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. """ if val in self.dic: # move the last element to the place idx of the element to delete last_element, idx = self.li[-1], self.dic[val] self.li[idx], self.dic[last_element] = last_element, idx # delete the last element self.li.pop() del self.dic[val] return True return False def getRandom(self): """ Get a random element from the set. """ return choice(self.li) # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
class Solution(object): # 自己解法超时 def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ if len(A) < 3: return False for i in range(1, len(A)-1): if all(A[m] > A[m-1] for m in range(1, i+1)) and all(A[n] > A[n+1] for n in range(i, len(A)-1)): return True return False # 改进 def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ if len(A) < 3: return False if A[-1] > A[-2] or A[0] > A[1]: return False flag = "grt" for i in range(0, len(A)-1): if A[i] > A[i+1]: flag = "sml" if A[i] >= A[i+1] and flag == "grt" or A[i] <= A[i+1] and flag == "sml": return False return True # 官方解法 def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ N = len(A) i = 0 # walk up while i < N-1 and A[i] < A[i+1]: i += 1 # peak can't be first or last if i == 0 or i == N-1: return False # walk down while i < N-1 and A[i] > A[i+1]: i += 1 return i == N-1
class Solution(object): # 参考网上答案 单调栈 def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ stack = [] cnt = collections.Counter(s) for char in s: if char not in stack: while stack and stack[-1] > char and cnt[stack[-1]] > 0: stack.pop() stack.append(char) cnt[char] -= 1 return "".join(stack) # 解法一样 多加一个set存储数据 def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ stack = [] seen = set() remain_counter = collections.Counter(s) for char in s: if char not in seen: while stack and char < stack[-1] and remain_counter[stack[-1]] > 0: seen.discard(stack.pop()) seen.add(char) stack.append(char) remain_counter[char] -= 1 # print seen, stack return ''.join(stack)
class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ i = 0 n = len(A) while i < n: if A[i] % 2 == 0: i += 1 else: temp = A.pop(i) A.append(temp) n = n - 1 return A def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ A.sort(key = lambda x: x % 2) return A def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ return ([x for x in A if x % 2 == 0] + [x for x in A if x % 2 == 1]) def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ i, j = 0, len(A) - 1 while i < j: if A[i] % 2 > A[j] % 2: A[i], A[j] = A[j], A[i] if A[i] % 2 == 0: i += 1 if A[j] % 2 == 1: j -= 1 return A
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # dict储存节点和节点个数 class Solution(object): def pseudoPalindromicPaths (self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 def travel(node, counter): counter[node.val] += 1 # 如果是叶节点的话,判断是否是伪回文 if node.left == None and node.right == None: # 取出所有计数伪奇数的数值 odds = [k for k,v in counter.items() if v%2==1] if len(odds) < 2: self.ans += 1 else: # 如果有左节点 递归 并更新counter的值 if node.left: travel(node.left, counter) # 这个步骤很关键 counter[node.left.val] -= 1 # 如果有右节点 递归 并更新counter的值 if node.right: travel(node.right, counter) # 这个步骤很关键 counter[node.right.val] -= 1 # 用到collections.defaultdict(int)这个方法 travel(root, collections.defaultdict(int)) return self.ans # dict储存节点和节点个数 class Solution(object): def pseudoPalindromicPaths (self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 def travel(node, counter): if node.val in counter: counter[node.val] += 1 else: counter[node.val] = 1 # 如果是叶节点的话,判断是否是伪回文 if node.left == None and node.right == None: # 取出所有计数伪奇数的数值 odds = [k for k,v in counter.items() if v%2==1] if len(odds) < 2: self.ans += 1 else: # 如果有左节点 递归 并更新counter的值 if node.left: travel(node.left, counter) # 这个步骤很关键 counter[node.left.val] -= 1 # 如果有右节点 递归 并更新counter的值 if node.right: travel(node.right, counter) # 这个步骤很关键 counter[node.right.val] -= 1 # 用到collections.defaultdict(int)这个方法 travel(root, {}) return self.ans # 二进制 # 利用二进制前缀和快速验证是否是回文串。 # 验证思路:因为数据范围是0-9,位数很固定。故用一个最长10位的2进制数字保存累计状态。 # 每次遍历到新节点数据时,对相应位数数字进行异或操作。如果该位数是1,说明累计奇数个,是0说明累计偶数个。 # 遍历到叶子节点后,看累计状态是否最多只有一个1,如果是就说明该路径是回文路径。 class Solution: def pseudoPalindromicPaths (self, root): self.ans = 0 def travel(node, mask): mask = mask ^ (1 << node.val) print mask if not (node.left or node.right): if (mask & (mask-1) == 0 or mask == 0): self.ans += 1 else: if node.left: travel(node.left, mask) if node.right: travel(node.right, mask) travel(root, 0) return self.ans
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): # 东哥解法 def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ def isValid(root, smallest, biggest): if root == None: return True if smallest != None and root.val <= smallest.val: return False if biggest != None and root.val >= biggest.val: return False print smallest, biggest # 左子树最大值应该是root的值 # 右子树最小值应该是root的值 return isValid(root.left, smallest, root) and isValid(root.right, root, biggest) return isValid(root, None, None)
# cspmodel.py # Author: Sébastien Combéfis # Version: April 12, 2020 from abc import ABC, abstractmethod class Variable: '''Class representing a named variable with its associated domain.''' def __init__(self, name, domain): self.name = name self.domain = domain self.value = None def is_assigned(self): return self.value is not None def __eq__(self, other): if not isinstance(other, Variable): return NotImplemented return self.name == other.name def __repr__(self): return '{} {}'.format(self.name, self.domain) class Constraint(ABC): '''Class representing a constraint on a set of variables.''' def __init__(self, variables): self.variables = variables @abstractmethod def is_satisfied(self): pass class Problem(): '''Class representing a CSP with a set of variables and a set of constraints.''' def __init__(self, name, variables, constraints): self.name = name self.variables = variables self.constraints = constraints def is_solved(self): return all(v.is_assigned() for v in self.variables) and all(c.is_satisfied() for c in self.constraints) def solve(self): raise NotImplementedError def __repr__(self): v = '\n'.join([' * {}'.format(v) for v in self.variables]) c = '\n'.join([' * {}'.format(c) for c in self.constraints]) return '==={}===\n\nVariables:\n\n{}\n\nConstraints:\n\n{}\n'.format(self.name, v, c)
import functools import time def timer(func): """Print the runtime of the decoreted function Arguments: func {[object]} -- The function to be decorated """ @functools.wraps(func) def wrapper_timer(*arg, **kwargs): start_time = time.perf_counter() print(f"Function {func.__name__!r}: Started execution") value = func(*arg, **kwargs) end_time = time.perf_counter() run_time = end_time - start_time print(f"Function {func.__name__!r}: Finished execution") print(f"Time elapsed {run_time:.4f} secs") return value return wrapper_timer
#TUNG, DONIA #SoftDev2 pd7 #K15 -- Do You Even List? #2018-04-25 UC_LETTERS = "ABCDEFGHIJKLNOPQRSTUVWXYZ" NUMS = "1234567890" NONALPHNUM = ".?!&#,;:-_*" def threshold(password): return checkNumbers(password) & checkLetters(password) def checkNumbers(password): word = [1 if x in NUMS else 0 for x in password] num = word[0] for each in word: if(num != each): return True return False def checkLetters(password): letters = [1 if x in UC_LETTERS else 0 for x in password] num = letters[0] for each in letters: if (num != each): return True return False def checkAlph(password): word = [1 if x in NONALPHNUM else 0 for x in password] num = word[0] for each in word: if (num != each): return True return False def rating(password): rating=0 if (checkNumbers(password)): rating += 3 if (checkLetters(password)): rating += 3 if (checkAlph(password)): rating += 3 return rating print threshold("helLo1") #True print threshold("sapghe") #False print threshold(";agoeE1oubawu") #True print threshold("owingeE")#False print threshold("woigen2")#False print rating("a;lnoeb2345") print rating("Drag0n123")
def fun(): str1 = input("Enter string 1: ") str2 = input("Enter string 2: ") s1 = len(str1) s2 = len(str2) if s1>s2: print(str1) elif s2>s1: print(str2) elif s1==s2: print(str1) print(str2) fun()
counter = 1 while counter <= 5: number = int(input("Guess the " + str(counter) + ". number ")) if number != 5: print("Try again.") counter = counter +1 elif number ==5: print("Good guess!") break counter = counter +1 else: print ("Sorry but that was not very successful.")
def unique(list1): list_set = set(list1) unique_list = (list(list_set)) for x in unique_list: print(x) list1 = [10, 20, 10, 30, 40, 40] print("the unique values from 1st list is") unique(list1)
def showNumber(limit): for i in range(0,limit+1): if i%2 == 0: x = print(i,'EVEN') else: x = print(i,'ODD') return x showNumber(5)
print 'Welcome to a crease/section of folded paper calculator!' print 'Input the number of creases before the number of folds that you want to find out.' print 'However, it does round down to the nearest non-float.' preCrease = float(raw_input('> ')) nowCrease = int(preCrease * 2 + 1) nowSect = int(nowCrease + 1) print 'You folded again, and now you have ' + str(nowCrease) + ' creases, and ' + str(nowSect) + ' sections.'
#!usr/bin/env python def my_range(stop): i = 0 lista = [] while i < stop: lista.append(i) i += 1 return lista def my_range2(stop, start = 0, krok = 1): i = 0 lista = [] while i < stop: lista.append(i) i += krok return lista def my_range3(*arg): if len(arg) > 3 or len(arg) < 0: print("Too many arguments passed to te function my_range3. {} was given, 3 is max.".format(len(arg))) return 0 elif len(arg) < 0: print("You should give at least one argument to the function my_range3") elif len(arg) == 1: i = 0 stop = arg[0] lista = [] while i < stop: lista.append(i) i += 1 return lista elif len(arg) == 2: start = arg[0] stop = arg[1] lista = [] while start < stop: lista.append(start) start += 1 return lista else: start = arg[0] stop = arg[1] krok = arg[2] lista = [] while start < stop: lista.append(start) start += krok return lista def proper_range(*args, **kwargs): if len(args) < 0 or len(args) > 3: print("Podano złą ilość argumentów.") return 0 elif len(args) == 1: return my_range(args[0]) elif len(args) == 2: return my_range2(args[1], args[0]) elif len(args) == 3: return my_range2(args[1], args[0], args[2]) else: return my_range2(**kwargs) import pierwsze print(pierwsze.pierwsze(7))
def trianglemath(num): return num ** num num = int(input("Please input a number: ")) print(trianglemath(num))
def romanToInt(s): mapping = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, } min_ = None total = 0 for c in s: val = mapping[c] print(min_, "Min at start") if min_ and val > min_: print(val, "Executed if") print(min_) print(total, "Total on if") total = total - min_ * 2 print(total, " Total Number after calculation") else: print(val, "ELSE") min_ = val print(min_, " MIN is val") total += val print(total, "After IF") return total print(romanToInt("MMIV"))
def filter_list(l): nlist = [] for filter in l: #print(filter) if isinstance(filter, int) == True: if filter > 0: nlist.append(filter) return nlist l = [1, 'a', 'b', 0, 15] print(filter_list(l))
# abre um novo arquivo file = open("compras.txt", "w") # adiciona itens ao arquivo file.write('Agua\n') file.write('Arroz\n') file.write('Detergente\n') # fecha arquivo file.close() # abre arquivo novamente file = open("compras.txt", "r") # ler arquivo print(file.read()) # ler primeira linha print(file.readline()) # ler todas as linhas, retorna quebras de linhas tbm print(file.readlines()) # fecha arquivo file.close() # abre arquivo novamente file = open("compras.txt", "a") # adiciona itens ao arquivo, sem apagar os ja existentes (a = append) file.write('Bolacha\n') file.write('Peixe\n') file.write('Ovos\n') # fecha arquivo file.close()
# lacos de repeticao # while contador = 0 # while contador != 100: # nome = input('Digite um nome: ') # contador = contador + 1 # while com else while contador < 3: print("Dentro do loop") contador = contador + 1 else: print('Dentro do else') # for capitais = ['Recife','Maceio','Salvador','Aracaju'] # usando o for for x in capitais: # a variavel de controle pode ter qualquer nome, nesse caso ("x") print(x) # usando loop while para iterar lista para o mesmo comando do for index = 0 tamanho_lista = len(capitais) while index < tamanho_lista: print(capitais[index]) index = index + 1 # usando o else junto com o for for cidade in capitais: print(cidade) else: print('Nao ha mais cidades.') # necessario sempre avaliar se o tipo de laco corresponde ao tipo de problema # resolvendo um problema com while secreto = 10 tentativa = '' contador = 0 while tentativa != secreto: tentativa = int(input("Digite um numero: ")) contador += 1 # resolvendo um problema com for for number in range(0, 11): print(3 * number) # break # exemplo 1 for letra in 'Recife': # executa por letra ate o i, e no i, ele para a execucao if letra == 'i': break print('Letra:', letra) # exemplo 2 numero = 1 while numero > 0: print('Valor:', numero) numero += 1 # executa ate o numero 4, e no 5, ele para a execucao if numero == 5: break # continue # exemplo 1 for letra in 'Recife': # executa por letra ate o i, e no i, ele salta para proxima execucao if letra == 'i': continue print('Letra:', letra) # exemplo 2 numero = 5 while numero > 0: print('Valor: ', numero) numero -= 1 if numero == 5: continue # pass # utilizado para futuras implementacoes # interpretado como nulo for letra in 'Recife': pass # iteracao usando loops # iterando sobre listas, usando for e while linguagens = ['Python', 'C++', 'Java', 'Swift', 'Dart'] # ler lista usando o for for l in linguagens: print(l) # ler lista usando o while x = 0 while x < len(linguagens): print(linguagens[x]) x += 1 # iterando sobre tuplas frutas = ('banana', 'maca', 'pera', 'laranja') # retornando o index e o valor na tupla for var in frutas: # detalhe na palavra index aqui print(frutas.index(var), var) # iterando sobre dicionarios # usando chaves supermercado = {'banana': 1.90, 'arroz': 4.5, 'óleo': 6.45} print(supermercado.keys()) for key in supermercado.keys(): # busca pelas chaves do dicionario print(key) # usando valores supermercado = {'banana': 1.90, 'arroz': 4.5, 'óleo': 6.45} print(supermercado.values()) for value in supermercado.values(): # busca pelos valores do dicionario print(value) # usando itens supermercado = {'banana': 1.90, 'arroz': 4.5, 'óleo': 6.45} print(supermercado.items()) for item in supermercado.items(): # busca pelos itens do dicionario print(item) # exemplo 1 total = 0 compras = { "camisa": 79.99, "sapato": 299.99, "cinto": 50.00, "hamburguer": 22.80, "cinema": 35.50, "pipoca": 10.00, "estacionamento": 10.00 } # itera sobre valores dos items for item in compras.values(): total = total + item print("Total gasto R$ %.2f" % total) # exemplo 2 lista1 = [5, 20, 15, 20, 25, 50, 20] # remove o item 20 da lista for num in lista1: if num == 20: lista1.remove(num) print(lista1)
#!/usr/bin/env python def std(): std_dict = {('Valid', 'Unknown'): 0, ('Valid', 'Invalid'): 0, ('Unknown', 'Valid'): 0, ('Unknown', 'Invalid'): 0, ('Invalid', 'Valid'): 0, ('Invalid', 'Unknown'): 0} with open('result.txt', 'r') as rfile: lines = rfile.readlines() for line in lines: content = line.strip() sep = content.split('|') left = sep[0].strip() lsep = left.split(',') lstatus = lsep[-1] right = sep[1].strip() rsep = right.split(',') rstatus = rsep[-1] std_dict[(lstatus, rstatus)] += 1 return std_dict if __name__ == '__main__': result = std() print result
from MyTwoThreeNode import MyTwoThreeNode class MyTwoThreeTree: def __init__(self): self.root = None def insert(self, new_data): if self.root is None: self.root = MyTwoThreeNode(new_data) else: current_node = self.root found_empty_spot = False while not found_empty_spot: if new_data > max(current_node.data_values): if current_node.right is None: current_node.right = MyTwoThreeNode(new_data) found_empty_spot = True # Case 1 elif len(current_node.right.data_values) == 1: current_node.right.data_values.append(new_data) found_empty_spot = True # Case 2,3 elif len(current_node.right.data_values) == 2: if new_data > current_node.right.data_values[1]: current_node.right.data_values.insert(2, new_data) elif new_data < current_node.right.data_values[0]: current_node.right.data_values.insert(0, new_data) else: current_node.right.data_values.insert(1, new_data) # Case 2 if len(current_node.data_values) == 1: current_node.data_values.append(current_node.right.data_values.pop(1)) current_node.middle.data_values.append(current_node.right.data_values.pop(0)) # Case 3 elif len(current_node.data_values) == 2: if new_data > current_node.data_values[1]: current_node.data_values.insert(2, new_data) elif new_data < current_node.data_values[0]: current_node.data_values.insert(0, new_data) else: current_node.data_values.insert(1, new_data) new_max_node = MyTwoThreeNode(current_node.data_values.pop()) new_min_node = MyTwoThreeNode(current_node.data_values.pop(0)) new_max_node.right = current_node.right new_max_node.left = current_node.right.data_values.pop(0) new_min_node.left = current_node.left new_min_node.right = current_node.middle current_node.right = new_max_node current_node.left = new_min_node current_node.middle = None found_empty_spot = True else: current_node = current_node.right elif new_data < min(current_node.data_values): if current_node.left is None: current_node.left = MyTwoThreeNode(new_data) found_empty_spot = True # Case 1 elif len(current_node.left.data_values) == 1: current_node.left.data_values.append(new_data) found_empty_spot = True # Case 2,3 elif len(current_node.left.data_values) == 2: if new_data > current_node.left.data_values[1]: current_node.left.data_values.insert(2, new_data) elif new_data < current_node.left.data_values[0]: current_node.left.data_values.insert(0, new_data) else: current_node.left.data_values.insert(1, new_data) # Case 2 if len(current_node.data_values) == 1: current_node.data_values.append(current_node.left.data_values.pop(1)) current_node.middle = MyTwoThreeNode(current_node.left.data_values.pop(1)) # Case 3 elif len(current_node.data_values) == 2: if new_data > current_node.data_values[1]: current_node.data_values.insert(2, new_data) elif new_data < current_node.data_values[0]: current_node.data_values.insert(0, new_data) else: current_node.data_values.insert(1, new_data) new_max_node = MyTwoThreeNode(current_node.data_values.pop()) new_min_node = MyTwoThreeNode(current_node.data_values.pop(0)) new_max_node.right = current_node.right new_max_node.left = current_node.middle new_min_node.left = current_node.left new_min_node.right = current_node.left.data_values.pop() current_node.right = new_max_node current_node.left = new_min_node current_node.middle = None found_empty_spot = True else: if current_node.middle is None: current_node.middle = MyTwoThreeNode(new_data) found_empty_spot = True # Case 1 elif len(current_node.middle.data_values) == 1: current_node.middle.data_values.append(new_data) found_empty_spot = True # Case 3 elif len(current_node.middle.data_values) == 2: if new_data > current_node.middle.data_values[1]: current_node.middle.data_values.insert(2, new_data) elif new_data < current_node.middle.data_values[0]: current_node.middle.data_values.insert(0, new_data) else: current_node.middle.data_values.insert(1, new_data) if new_data > current_node.data_values[1]: current_node.data_values.insert(2, new_data) elif new_data < current_node.data_values[0]: current_node.data_values.insert(0, new_data) else: current_node.data_values.insert(1, new_data) new_max_node = MyTwoThreeNode(current_node.data_values.pop()) new_min_node = MyTwoThreeNode(current_node.data_values.pop(0)) new_max_node.right = current_node.right new_max_node.left = current_node.middle.data_values.pop() new_min_node.left = current_node.middle.data_values.pop() new_min_node.right = current_node.left.data_values.pop() current_node.right = new_max_node current_node.left = new_min_node current_node.middle = None found_empty_spot = True def print_tree(self): pre_order_print(self.root) def delete(self, key): recursive_delete(self.root, key) def search(self, key): return pre_order_search(self.root, key) def get_min(self, node=None): if node is None: node = self.root return get_min_in_sub_tree(node) def get_max(self): current_node = self.root while current_node.right is not None: current_node = current_node.right return current_node.data_value def pre_order_print(current_node): if current_node is not None: print current_node.data_values, if current_node.left is not None: pre_order_print(current_node.left) if current_node.middle is not None: pre_order_print(current_node.middle) if current_node.right is not None: pre_order_print(current_node.right) def recursive_delete(current_node, key): if current_node is None: return current_node if key < min(current_node.data_values): current_node.left = recursive_delete(current_node.left, key) elif key > max(current_node.data_values): current_node.right = recursive_delete(current_node.right, key) else: current_node.middle = recursive_delete(current_node.middle, key) if key in current_node.data_values: if len(current_node.data_values) == 1: if current_node.left is None: return current_node.right elif current_node.right is None: return current_node.left current_node.data_values = get_min_in_sub_tree(current_node.right) current_node.right = recursive_delete(current_node.right, current_node.data_values[0]) if len(current_node.data_values) == 2: if current_node.data_values[0] == key: key_index = 0 else: key_index = 1 if current_node.middle is None: current_node.data_values.pop(key_index) else: current_node.data_values[key_index] = current_node.middle.data_values.pop(0) if len(current_node.middle.data_values) == 0: current_node.middle = None return current_node def get_min_in_sub_tree(current_node): while current_node.left is not None: current_node = current_node.left return current_node.data_value def pre_order_search(current_node, key): if current_node is None: return False else: if key in current_node.data_values: return True elif min(current_node.data_values) > key: return pre_order_search(current_node.left, key) elif max(current_node.data_values) < key: return pre_order_search(current_node.right, key) else: return pre_order_search(current_node.middle, key)
from MyTreeNode import MyTreeNode class MyAVLTree: def __init__(self): self.root = None def print_tree(self): pre_order_print(self.root) def insert(self, new_data): self.root = self.insert_and_fix_tree(self.root, new_data) def insert_and_fix_tree(self, node, new_data): if node is None: return MyTreeNode(new_data) elif new_data < node.data_value: node.left = self.insert_and_fix_tree(node.left, new_data) else: node.right = self.insert_and_fix_tree(node.right, new_data) node.height = 1 + max(get_height(node.right), get_height(node.left)) balance_factor = get_balance_factor(node) # Left Left if balance_factor > 1 and new_data < node.left.data_value: return right_rotate(node) # Left Right if balance_factor > 1 and new_data > node.left.data_value: node.left = left_rotate(node.left) return right_rotate(node) # Right Right if balance_factor < -1 and new_data > node.right.data_value: return left_rotate(node) # Right Left if balance_factor < -1 and new_data < node.right.data_value: node.right = right_rotate(node.right) return left_rotate(node) return node def delete(self, key): self.root = self.delete_and_fix_tree(self.root, key) def delete_and_fix_tree(self, node, key): if not node: return node elif key < node.data_value: node.left = self.delete_and_fix_tree(node.left, key) elif key > node.data_value: node.right = self.delete_and_fix_tree(node.right, key) else: if node.left is None: return node.right elif node.right is None: return node.left node.data_value = get_min_in_sub_tree(node.right) node.right = self.delete_and_fix_tree(node.right, node.data_value) if node is None: return node node.height = 1 + max(get_height(node.left), get_height(node.right)) # Step 3 - Get the balance factor balance = get_balance_factor(node) # Left Left if balance > 1 and get_balance_factor(node.left) >= 0: return right_rotate(node) # Left Right if balance > 1 and get_balance_factor(node.left) < 0: node.left = left_rotate(node.left) return right_rotate(node) # Right Right if balance < -1 and get_balance_factor(node.right) <= 0: return left_rotate(node) # Right Left if balance < -1 and get_balance_factor(node.right) > 0: node.right = right_rotate(node.right) return left_rotate(node) return node def search(self, key): return pre_order_search(self.root, key) def get_min(self, node=None): if node is None: node = self.root return get_min_in_sub_tree(node) def get_max(self): current_node = self.root while current_node.right is not None: current_node = current_node.right return current_node.data_value def get_height(node): if node is None: return 0 return node.height def left_rotate(current_node): right_child = current_node.right left_child_of_right_child = right_child.left right_child.left = current_node current_node.right = left_child_of_right_child current_node.height = 1 + max(get_height(current_node.left), get_height(current_node.right)) right_child.height = 1 + max(get_height(right_child.left), get_height(right_child.right)) return right_child def right_rotate(current_node): left_child = current_node.left right_child_of_left_child = left_child.right left_child.right = current_node current_node.left = right_child_of_left_child current_node.height = 1 + max(get_height(current_node.left), get_height(current_node.right)) left_child.height = 1 + max(get_height(left_child.left), get_height(left_child.right)) return left_child def get_balance_factor(node): if node is None: return 0 return get_height(node.left) - get_height(node.right) def pre_order_print(current_node): if current_node is not None: print current_node.data_value, if current_node.left is not None: pre_order_print(current_node.left) if current_node.right is not None: pre_order_print(current_node.right) def get_min_in_sub_tree(current_node): while current_node.left is not None: current_node = current_node.left return current_node.data_value def pre_order_search(current_node, key): if current_node is None: return False else: if current_node.data_value == key: return True if current_node.data_value > key: return pre_order_search(current_node.left, key) return pre_order_search(current_node.right, key)
##Author: Michael Shiferaw ##Date: 8/5/2017 - 8/5/2017 ##Program Description: Maximize Profits for Raw Material Provider ##Key Components: List competitive pricing. Allow users to update price/amount. Be user friendly. Return results quickly. import company def main(): company_dictionary = read_and_store() ##display menu## print_menu() ##Grab user input and validate## menu_choice = get_menu_choice() while menu_choice != 3: ##logic to update a prospective companies asking price if menu_choice == 1: select_company = input('''Which company would you like to update the price for?''') update_price = float(input('''What would you like to update the price to?''')) company_dictionary[select_company].set_asking_price(update_price) print("ACTION COMPLETE") print("=======================================================") print('') print_menu() menu_choice = get_menu_choice() ##logic to update a prospective companies asking amount elif menu_choice == 2: select_company = input('''Which company would you like to update the amount for?''') update_amount = float(input('''What would you like to update the amount to?''')) company_dictionary[select_company].set_desired_amount(update_amount) print("ACTION COMPLETE") print("=======================================================") print('') print_menu() menu_choice = get_menu_choice() ##logic to build a dictionary for price ratios (key = company name, value = ratio) price_ratio_dict = build_ratio_dict(company_dictionary) sorted_ratio_list = build_ratio_list(price_ratio_dict) ##prompt user to enter in the amount of material x available for sale available_material = int(input('''How much material do you have available for sale?''')) total_profit = 0 ##list contain who to purchase from purchase_from_list = [] ##Begin logic for data processing while available_material != 0: ##use ratio list to avoid dictionary length edits during iterations for ratio in sorted_ratio_list: company_name = compare_ratio(company_dictionary, ratio) company_amount = int(company_dictionary[company_name].get_desired_amount()) company_price = int(company_dictionary[company_name].get_asking_price()) if available_material >= company_amount: available_material = available_material - company_amount current_profit = company_price purchase_from_list.append("Buy " + str(company_amount) + " from " + company_name) ##occurs only during last iteration else: purchase_from_list.append("Buy " + str(available_material) + " from " + company_name) current_profit = (company_price/company_amount) * available_material available_material = available_material - available_material total_profit = current_profit + total_profit sorted_ratio_list.remove(ratio) print(purchase_from_list) print("Total Profit: $" + str(format(total_profit, '.2f'))) ##search ratio dict for matching ratio and return the key def compare_ratio(comp_dict, ratio_search): for item in comp_dict: compare_ratio = comp_dict[item].calc_value() if compare_ratio == ratio_search: company_letter = item return company_letter ##builds the list of ratios and sorts them greatest to least def build_ratio_list(ratio_info_dict): ratio_list = [] for item in ratio_info_dict: ratio_list.append(ratio_info_dict[item]) ratio_list.sort() ratio_list.reverse() return ratio_list ##grabs menu number choice from user, validates that its within range def get_menu_choice(): print('') menu_select = int(input("Please select a menu option number from the list above.")) while menu_select <= 0 or menu_select > 3: menu_select = int(input(" Invalid Value: Please enter either 1, 2, or 3.")) return menu_select ##displays menu def print_menu(): print('''1. Update a company's price.''') print('''2. Update a company's amount.''') print('''3. Begin data processing .''') ##read sample data file and create objects for each line. Store the data in a dictionary def read_and_store(): company_data_input = open('CompanyData.txt', 'r') company_dict = {} for line in company_data_input: seperated_info = line.split(':') company_name = seperated_info[0] quoted_amount = seperated_info[1] quoted_price = seperated_info[2] my_company_object = company.Company(company_name, quoted_price, quoted_amount) company_dict[company_name] = my_company_object return company_dict ##builds ratio dictionary containing the company name as the key def build_ratio_dict(info_dict): ratio_dict = {} for line in info_dict: price_ratio = info_dict[line].calc_value() ratio_dict[line] = price_ratio return ratio_dict main()
# FUNCIONES DE MANIPULACION DE CADENA 1: msg="EL FIN DEL MUNDO SE ACERCA" # Mostrar el nro de ocurrencias de la palabra FIN print("FIN",msg.count("FIN")) print("A ->", msg.count("A")) # FUNCIONES DE MANIPULACION DE CADENA 2: cadena1="LOS VENGADORES FIN DE LA GUERRA" # Transformar el texto en minusculas mensaje=cadena1.lower() print(mensaje) # FUNCIONES DE MANIPULACION DE CADENA 3: cadena2="para los niños existe papa noel" # Transformar en mayusculas mensaje=cadena2.upper() print(mensaje) # FUNCIONES DE MANIPULACION DE CADENA 4: cadena3="LA CAPITAL DE PErU ES LIMA" # transformar en minusculas mensaje=cadena3.lower() print(mensaje) # FUNCIONES DE MANIPULACION 5: cadena4="BAJO EL ARBOL ENCONTRE UNA MANZANA" # Mostrar el nro de ocurrencias de la palabra MANZANA print("MANZANA", cadena4.count("MANZANA")) print("N ->", cadena4.count("N")) # FUNCIONES DE MANIPULACION DE CADENA 6: cadena5="los gatos no nadan" # transformar en maysuculas mensaje=cadena5.upper() print(mensaje) # FUNCIONES DE MANIPULACION DE CADENA 7: cadena6="SUMMIT LA SUPERCOMPUTADORA MAS PODEROSA DEL MUNDO" # Mostrar el nro de ocurrencias de la palabra SUPERCOMPUTADORA print("SUPERCOMPUTADORA", cadena6.count("SUPERCOMPUTADORA")) print("E ->", cadena6.count("E")) # FUNCIONES DE MANIPULACION DE CADENA 8: cadena7="LOS GATOS ODIAN A LOS PERROS" # transformar en minusculas mensaje=cadena7.lower() print(mensaje) # FUNCIONES DE MANIPULACION DE CADENA 9: cadena8="los ricos tambien lloran" # transformar en mayusculas mensaje=cadena8.upper() print(mensaje) # FUNCIONES DE MANIPULACION DE CADENA 10: cadena10="TODO FLUYE, NADA PERMANECE" # transformar en minusculas mensaje=cadena10.lower() print(mensaje) # FUNCIONES DE MANIPULACION DE CADENA 11: cadena11="Si no esperas lo inesperado no lo reconocerás cuando llegue" # transformar en mayusculas mensaje=cadena11.upper() print(mensaje) # FUNCIONES DE MANIPULACION DE CADENA 12: cadena12="Los asnos prefieren la paja al oro" # transformar en mayusculas mensaje=cadena12.upper() print(mensaje) # FUNCIONES DE MANIPULACION DE CADENA 13: cadena13=" Todas las leyes humanas se alimentan de la ley divina" # transformar en mayusculas mensaje=cadena13.upper() print(mensaje) # FUNCIONES DE MANIPULACION DE CADENA 14: cadena14=" Muerte es todo lo que vemos despiertos; sueño lo que vemos dormidos" # Mostrar el nro de ocurrencias de la palabbra dormidos print("dormidos", cadena14.count("dormidos")) print("o ->", cadena14.count("o")) # FUNCIONES DE MANIPULACION DE CADENA 15: cadena15="LOS PERROS SOLO LADRAN A QUIENES NO CONOCEN" # transformar en minusculas mensaje=cadena15.lower() print(mensaje)
#MANIPULACION DE TEXTOS # 10 # 01234567890123456789 cadena="HOY TE IRÁ MUY BIEN" #manipulador de texto nro 1 print(cadena[5],cadena[6],cadena[12]) #me imprime los caracteres "E I" que ocupa los indice 5 6 12 #manipulador de texto nro 2 print(cadena[2],cadena[9]) #me imprime los caracteres "Y Á " que ocupa los indices 2 9 #manipulador de texto nro 3 print(cadena[4]) #me imprime el caracter "T" que ocupa el indice 4 que ocupa el indice 2 #manipulador de texto nro 4 print(cadena[1],cadena[6]) #me imprime el caracteres "O " que ocupa los indices 1 6 #manipulador de texto nro 5 print(cadena[0],cadena[5],cadena[8],cadena[15])#me imprime los caracter "H E R B" que ocupa los indice 0 5 8 15 #manipulador de texto nro 6 print(cadena[9],cadena[17],cadena[11]) #me imprime los caracter "A E M" que ocupa los indices 9 17 11 #manipulador de texto nro 7 print(cadena[11]) #me imprime el caracter "M " que ocupa el indice 11 #manipulador de texto nro 8 print(cadena[10]) #me imprime el caracter " " que ocupa el indice 10 #manipulador de texto nro 9 print(cadena[18],cadena,[7],cadena[0]) #me imprime el caracter "N I O" que ocupa los indice 18 7 0 #manipulador de texto nro 10 print(cadena[16,cadena[11]]) #me imprime el caracter "I M" que ocupa los indice 16 11 #manipulador de texto nro 11 print(cadena[7],cadena[5],cadena,[15]) #me imprime los caracteres "I E B" que ocupa los indice 7 5 15 #manipulador de texto nro 12 print(cadena[8]) #me imprime el caracter "R" que ocupa el indice 8 #manipulador de texto nro 13 print(cadena[17],cadena[5]) #me imprime los caracteres "E E" que ocupa los indices 17 5 #manipulador de texto nro 14 print(cadena[14]) #me imprime el caracter " " que ocupa el indice 14 #manipulador de texto nro 15 print(cadena[13],cadena[8],cadena[9]) #me imprime los caracteres "Y R A" que ocupa los indices 13
""" // Time Complexity : o(m*n) // Space Complexity : o(m*n) // Did this code successfully run on Leetcode : not on leetcode // Any problem you faced while coding this : no """ class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 r = len(matrix) c = len(matrix[0]) dp = [[0 for i in range(c + 1)]for j in range(r + 1)] #print(dp) m = 0 for i in range(1,r + 1): for j in range(1,c + 1): if matrix[i-1][j-1] == '1': dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) #stores one dimension of the maximum square that can be formed at that point m = max(m, dp[i][j]) #maximum dimension return m*m
a = {'john', 'josh', 'joe', 'james'} b = {'joe', 'george', 'james', 'jack'} print(a.intersection(b))
# this program will rename photos to the following file-name format # example: IMG_2015015_233016.jpg import os import pyexiv2 import datetime i = 0 # remove spaces from file names old_list = os.listdir(os.getcwd()) for old_name in old_list: file_name = old_name.replace(' ', '_') file_name = old_name.replace('-', '_') os.rename(old_name, file_name) # identify file names to change file_list = os.listdir(os.getcwd()) change_list = [] for file_name in file_list: file_ext = os.path.splitext(file_name)[1] # thumbnail files should not be renamed if "Thumbs" in file_name: print ("ignored - thumbnail: "+ file_name) # double underscored files should not be renamed elif "__" in file_name: print ("ignored - underscored: "+ file_name) # dotted files should not be renamed elif file_name.startswith("."): print ("ignored - dotted: "+ file_name) # non-image files should not be renamed elif not (file_ext == ".jpg" or file_ext == ".png" or file_ext == ".JPG" or file_ext == ".jpeg"): print ("ignored - not image: "+ file_name) # already renamed files should not be renamed elif "IMG_" in file_name: print ("ignored - already changed: "+ file_name) # add qualifying files to change_list else: change_list.append(file_name) # define the new file name for file_name in change_list: print ("defining: "+ file_name) meta_name = os.path.splitext(file_name)[0] file_ext = os.path.splitext(file_name)[1] metadata = pyexiv2.ImageMetadata(file_name) metadata.read() if "Exif.Photo.DateTimeOriginal" in metadata.exif_keys: tag = metadata['Exif.Photo.DateTimeOriginal'] meta_name = tag.value.strftime('%Y%m%d_%H%M%S') elif "Exif.Image.DateTime" in metadata.exif_keys: tag = metadata['Exif.Image.DateTime'] meta_name = tag.value.strftime('%Y%m%d_%H%M%S') else: print ("no meta-data: "+ file_name) new_name = "IMG_" + meta_name + file_ext # check for duplicates while new_name in file_list: i = i + 1 print ("found - duplicate file: "+ new_name) new_name = "IMG_" + meta_name + "-" + str(i) + file_ext # rename the file os.rename(file_name, new_name) file_list = os.listdir(os.getcwd()) print ("changed "+ file_name +" to "+ new_name) i = 0 print "DONE!"
# Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) count=0 num=0 total=0 for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue count=count+1 num = float(line[21:]) total=num+total avg=total/count print("Average spam confidence:",avg)
import pickle import string from collections import Counter from .utils import parse_into_words class WordFrequency: def __init__(self): self._dictionary = Counter() self._total_words = 0 self._unique_words = 0 self._letters = set() self._longest_word_length = 0 self._tokenizer = parse_into_words def __contains__(self, key): """ Check if dictionary contains key """ key = key.lower() return key in self._dictionary def __getitem__(self, key): """ Get frequency """ key = key.lower() return self._dictionary[key] def __iter__(self): """ iter support """ for word in self._dictionary: yield word def pop(self, key, default=None): """ Delete the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present """ key = key.lower() return self._dictionary.pop(key, default) @property def dictionary(self): """ Counter: A counting dictionary of all words in the corpus and the \ number of times each has been seen Note: Not settable """ return self._dictionary @property def total_words(self): """ int: The sum of all word occurrences in the word frequency \ dictionary Note: Not settable """ return self._total_words @property def unique_words(self): """ int: The total number of unique words in the word frequency list Note: Not settable """ return self._unique_words @property def letters(self): """ str: The listing of all letters found within the corpus Note: Not settable """ return self._letters @property def longest_word_length(self): """ int: The longest word length in the dictionary Note: Not settable """ return self._longest_word_length def keys(self): """ Iterator over the key of the dictionary Yields: str: The next key in the dictionary""" for key in self._dictionary.keys(): yield key def words(self): """ Iterator over the words in the dictionary Yields: str: The next word in the dictionary """ for word in self._dictionary.keys(): yield word def items(self): """ Iterator over the words in the dictionary Yields: str: The next word in the dictionary int: The number of instances in the dictionary Note: This is the same as `dict.items()` """ for word in self._dictionary.keys(): yield word, self._dictionary[word] def load_dictionary(self, filename): """ Load in a pre-built word frequency list Args: filename (str): The filepath to the json (optionally gzipped) \ file to be loaded """ self._dictionary.update(pickle.load(open(filename, 'rb'))) self._update_dictionary() def remove_by_threshold(self, threshold=5): """ Remove all words at, or below, the provided threshold Args: threshold (int): The threshold at which a word is to be removed """ keys = [x for x in self._dictionary.keys()] for key in keys: if self._dictionary[key] <= threshold: self._dictionary.pop(key) self._update_dictionary() def _update_dictionary(self): """ Update the word frequency object """ self._longest_word_length = 0 self._total_words = sum(self._dictionary.values()) self._unique_words = len(self._dictionary.keys()) self._letters = set() for key in self._dictionary: if len(key[0]) > self._longest_word_length: self._longest_word_length = len(key[0]) self._longest_word = key[0] self._letters.update(string.ascii_lowercase)
class Bike(object): """docstring for Bike.""" def __init__(self, price, max_speed, miles = 0): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print self.price, self.max_speed, self.miles def ride(self): print "Riding" self.miles += 10 return self def reverse(self): if not self.miles - 5 < 0: print "Reversing" self.miles -= 5 else: print "Can't Reverse!" return self bike1 = Bike(200,"25mph") bike2 = Bike(250,"35mph") bike3 = Bike(100,"15mph") bike1.displayInfo() bike1.ride().ride().reverse().displayInfo() bike2.ride().ride().reverse().reverse().displayInfo() bike3.reverse().reverse().reverse().displayInfo()
print("") print("This prints out a list of all the divisors of the number you input.") print("") print("Enter a number:") num = int(input("--> ")) list_of_num = [] list_range = list(range(1,num+1)) for elem in list_range: if num % elem == 0: list_of_num.append(elem) print(list_of_num)
import unittest import os import testLib class TestNilUser(testLib.RestTestCase): """Test adding user with empty Username""" def assertResponse(self, respData, errCode = testLib.RestTestCase.ERR_BAD_USERNAME): """ Check that the response data dictionary matches the expected values """ expected = { 'errCode' : errCode } self.assertDictEqual(expected, respData) def testAdd1(self): respData = self.makeRequest("/users/add", method="POST", data = { 'user': '', 'password': 'hehe'} ) self.assertResponse(respData) class TestMaxUser(testLib.RestTestCase): """Test adding user with too long Username""" def assertResponse(self, respData, errCode = testLib.RestTestCase.ERR_BAD_USERNAME): """ Check that the response data dictionary matches the expected values """ expected = { 'errCode' : errCode } self.assertDictEqual(expected, respData) def testAdd1(self): a = "a"*129 respData = self.makeRequest("/users/add", method="POST", data = { 'user': a, 'password': 'hehe'} ) self.assertResponse(respData) class TestMaxPassword(testLib.RestTestCase): """Test adding user with too long Username""" def assertResponse(self, respData, errCode = testLib.RestTestCase.ERR_BAD_PASSWORD): """ Check that the response data dictionary matches the expected values """ expected = { 'errCode' : errCode } self.assertDictEqual(expected, respData) def testAdd1(self): b = "b"*129 respData = self.makeRequest("/users/add", method="POST", data = { 'user': 'hehe', 'password': b} ) self.assertResponse(respData) class TestDupUser(testLib.RestTestCase): """Test Duplicate Users Added to Database""" def assertResponse(self, respData, errCode = testLib.RestTestCase.ERR_USER_EXISTS): """ Check that the response data dictionary matches the expected values """ expected = { 'errCode' : errCode } self.assertDictEqual(expected, respData) def testAdd1(self): self.makeRequest("/users/add", method="POST", data = { 'user' : 'me', 'password' : 'you'} ) respData = self.makeRequest("/users/add", method="POST", data = { 'user' : 'me', 'password' : 'you'} ) self.assertResponse(respData) class TestLoginUser(testLib.RestTestCase): """Test login functionality""" def assertResponse(self, respData, count = 2, errCode = testLib.RestTestCase.SUCCESS): """ Check that the response data dictionary matches the expected values """ expected = { 'errCode' : errCode } if count is not None: expected['count'] = count self.assertDictEqual(expected, respData) def testAdd1(self): self.makeRequest("/users/add", method="POST", data = { 'user' : 'zack', 'password' : 'wack'} ) respData = self.makeRequest("/users/login", method="POST", data = { 'user' : 'zack', 'password' : 'wack'} ) self.assertResponse(respData, count = 2) class TestLoginNoUser(testLib.RestTestCase): """Test Logging in user that has not been created""" def assertResponse(self, respData, errCode = testLib.RestTestCase.ERR_BAD_CREDENTIALS): """ Check that the response data dictionary matches the expected values """ expected = { 'errCode' : errCode } self.assertDictEqual(expected, respData) def testAdd1(self): respData = self.makeRequest("/users/login", method="POST", data = { 'user' : 'nothere', 'password' : 'lsls'} ) self.assertResponse(respData) class TestLoginBadPassword(testLib.RestTestCase): """Test Logging in user with a bad password""" def assertResponse(self, respData, errCode = testLib.RestTestCase.ERR_BAD_CREDENTIALS): """ Check that the response data dictionary matches the expected values """ expected = { 'errCode' : errCode } self.assertDictEqual(expected, respData) def testAdd1(self): respData = self.makeRequest("/users/login", method="POST", data = { 'user' : 'user1', 'password' : 'uhoh'} ) self.assertResponse(respData) class TestDbReset(testLib.RestTestCase): """Test Logging in user that has not been created""" def assertResponse(self, respData, errCode = testLib.RestTestCase.SUCCESS): """ Check that the response data dictionary matches the expected values """ expected = { 'errCode' : errCode } self.assertDictEqual(expected, respData) def testAdd1(self): respData = self.makeRequest("/TESTAPI/resetFixture", method="POST", data = {}) ###not sure about empty dict self.assertResponse(respData)
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) arr.sort(reverse=True) max_num = arr[0] runner = 0 for num in arr: if num != max_num: runner = num break print(runner)
# This file assumes a reference input for z (named x in the lectures) variable # and plots the z reference and z, as well as, the theta value over time. # It should not need to be changed by the students import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np plt.ion() # enable interactive drawing class plotData: ''' This class plots the time histories for the pendulum data. ''' def __init__(self): #Number of subplots = num_of_rows*num_of_cols self.num_rows = 2 # Number of subplot rows self.num_cols = 1 # Number of subplot columns #Create figure and axes handles self.fig, self.ax = plt.subplots(self.num_rows, self.num_cols, sharex=True) #Instantiate lists to hold the time and data histories self.time_history = [] # time self.zref_history = [] # reference position z_r self.z_history = [] # position z self.theta_history = [] # angle theta #create subplots self.ax[0].set(xlabel='time(s)', ylabel='z(m)', title='Performance') self.ax[1].set(xlabel='time(s)', ylabel='theta(deg)') def Plot(self, t, reference, states): ''' Add to the time and data histories, and update the plots. ''' #the time history of all plot variables self.time_history = t # time self.zref_history = reference[:,0] # reference base position self.z_history = states[:,0] # base position self.theta_history = 180.0/np.pi*states[:,2] # pendulum angle (converted to degrees) #the plots with associated histories line1, = self.ax[0].plot(self.time_history, self.zref_history, label='Z-Reference') line2, = self.ax[0].plot(self.time_history, self.z_history, label='Z') line3, = self.ax[1].plot(self.time_history, self.theta_history, ) plt.show()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'lyl' # 使用元类 # 可以使用type()函数创建新的类型 def fn(self, name = 'world'): print('Hello, %s' % name) Hello = type('Hello', (object, ), dict(hello = fn)) # 创建Hello class h = Hello() print('Hello类型是:', type(Hello)) print('类的实例对象类型是:', type(h))
# Gets the Conversation (based on the is reply to Key of the libraries timeline) of each tweet and returns the conversation as a LoD with following keys: # # u'hours_to_answer', u'is_follower', u'follower_local', u'original_is_question', u'original_screen_name', # u'original_status_id', u'original_text', u'original_time', u'original_user_id', # u'orphan', u'reply_is_answer', u'reply_status_id', u'reply_text', u'reply_time' # # # Saves a file as csv with the following keys: # u'hours_to_answer', u'is_follower', u'original_is_question', u'original_time', # u'orphan', u'reply_is_answer', u'reply_time', u'follower_local' # # 1. Function Definitions # # 1. Authenticating @ Twitter # All functions from MTSW 2 Ed. # # (added another error handler (# 403) in function make_twitter_request # import time import twitter def oauth_login(): # XXX: Go to http://twitter.com/apps/new to create an app and get values # for these credentials that you'll need to provide in place of these # empty string values that are defined as placeholders. # See https://dev.twitter.com/docs/auth/oauth for more information # on Twitter's OAuth implementation. CONSUMER_KEY = CONSUMER_SECRET = OAUTH_TOKEN = OAUTH_TOKEN_SECRET = auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET) twitter_api = twitter.Twitter(auth=auth) return twitter_api # Sample usage twitter_api = oauth_login() import sys from urllib2 import URLError from httplib import BadStatusLine def make_twitter_request(twitter_api_func, max_errors=10, *args, **kw): # A nested helper function that handles common HTTPErrors. Return an updated # value for wait_period if the problem is a 500 level error. Block until the # rate limit is reset if it's a rate limiting issue (429 error). Returns None # for 401 and 404 errors, which requires special handling by the caller. def handle_twitter_http_error(e, wait_period=2, sleep_when_rate_limited=True): if wait_period > 3600: # Seconds print >> sys.stderr, 'Too many retries. Quitting.' raise e # See https://dev.twitter.com/docs/error-codes-responses for common codes if e.e.code == 401: print >> sys.stderr, 'Encountered 401 Error (Not Authorized)' return None if e.e.code == 403: # added error handler for 403 (TG) print >> sys.stderr, 'Encountered 403 Error (Not Authorized)' return None elif e.e.code == 404: print >> sys.stderr, 'Encountered 404 Error (Not Found)' return None elif e.e.code == 429: print >> sys.stderr, 'Encountered 429 Error (Rate Limit Exceeded)' if sleep_when_rate_limited: print >> sys.stderr, "Retrying in 15 minutes...ZzZ..." sys.stderr.flush() time.sleep(60*15 + 5) print >> sys.stderr, '...ZzZ...Awake now and trying again.' return 2 else: raise e # Caller must handle the rate limiting issue elif e.e.code in (500, 502, 503, 504): print >> sys.stderr, 'Encountered %i Error. Retrying in %i seconds' % \ (e.e.code, wait_period) time.sleep(wait_period) wait_period *= 1.5 return wait_period else: raise e # End of nested helper function wait_period = 2 error_count = 0 while True: try: return twitter_api_func(*args, **kw) except twitter.api.TwitterHTTPError, e: error_count = 0 wait_period = handle_twitter_http_error(e, wait_period) if wait_period is None: return except URLError, e: error_count += 1 time.sleep(wait_period) wait_period *= 1.5 print >> sys.stderr, "URLError encountered. Continuing." if error_count > max_errors: print >> sys.stderr, "Too many consecutive errors...bailing out." raise except BadStatusLine, e: error_count += 1 time.sleep(wait_period) wait_period *= 1.5 print >> sys.stderr, "BadStatusLine encountered. Continuing." if error_count > max_errors: print >> sys.stderr, "Too many consecutive errors...bailing out." raise # 2. Helper Functions import csv def impCSV(input_file): ''' input_file = csv with keys: "URL", "Twitter" output = list of dictionaries ''' f = open(input_file, 'r') d = csv.DictReader(f) LoD = [] # list of dictionaries for row in d: LoD.append(row) f.close() return LoD def exp2CSV(listOfDict, screen_name): ''' arguments = list of dictionaries, filename output = saves file to cwd (current working directory) ''' #creating the filename of the csv with current datestamp import datetime datestamp = datetime.datetime.now().strftime('%Y-%m-%d') outputfile = screen_name + '_ReplyStats_' + datestamp + '.csv' keyz = listOfDict[0].keys() f = open(outputfile,'w') dict_writer = csv.DictWriter(f,keyz) dict_writer.writer.writerow(keyz) dict_writer.writerows(listOfDict) f.close() print 'Conversation statistics was saved as ' + outputfile + '.' def readJSON(filename): import json with open(filename) as f: data = json.load(f) return data def saveConversationAsJSON(timeline, user_name): import io, json, datetime datestamp = datetime.datetime.now().strftime('%Y-%m-%d') filename = user_name + '_Conversation_' + datestamp + '.json' with io.open(filename, 'w', encoding='utf-8') as f: f.write(unicode(json.dumps(timeline, ensure_ascii=False))) print 'Conversation archive was saved as ' + filename + '.' def sortLoD(listname, key): from operator import itemgetter listname.sort(key=itemgetter(key)) # sorting the list over the given key of the dictionary return listname # Helper function to search for value in a LoD (bisection search) def bisectInLoD(listname, key, value): ''' input: listname of sorted LoD (sortLoD-Function!), key and value return index of key-value pair will be returned ''' i_min = 0 i_max = len(listname) -1 i_mid = i_min + (i_max-i_min)/2 if str(value) == str(listname[i_min][key]): return i_min elif str(value) == str(listname[i_max][key]): return i_max #elif str(value) == str(listname[i_mid][key]): # return i_mid else: while str(value) != str(listname[i_mid][key]): # print 'i_min', i_min, 'i_mid', i_mid,'i_max', i_max # T E S T if i_mid == i_max or i_mid == i_min: # print 'Some error occured!' # T E S T return None elif str(value) > str(listname[i_mid][key]): i_min = i_mid i_mid = i_min + (i_max-i_min)/2 elif str(value) < str(listname[i_mid][key]): i_max = i_mid i_mid = i_min + (i_max-i_min)/2 return i_mid # 3. Conversation Functions def repliedToTweetList(screen_name, timestamp_Timeline, timestamp_Followers): ''' input: screen_name of lib account and timestamps of the libs timeline & Followers output: LoD ''' # 1. def getReplies(timeline): listOfReplies = [] for e in timeline: d = {} if e['in_reply_to_user_id_str'] != None: # filter out tweets from deleted users accounts s = 'via @' + str(e['in_reply_to_screen_name']).lower() #filter out "via @XXX" retweets if s not in e['text'].lower(): # which are generated via the reply function d['original_user_id'] = e['in_reply_to_user_id_str'] d['original_screen_name'] = e['in_reply_to_screen_name'] d['original_status_id'] = e['in_reply_to_status_id_str'] d['reply_status_id'] = e['id_str'] d['reply_time'] = e['created_at'] d['reply_text'] = e['text'] if d['original_status_id'] != None: d['orphan'] = 0 else: d['orphan'] = 1 listOfReplies.append(d) return listOfReplies # 2. def separateListOfReplies(listOfReplies): replies = listOfReplies repl = replies[:] # make a copy of replies LoNone = [] # replies with NoneType-Elements LoIDs = [] for e in repl: if e['orphan'] == 0: LoIDs.append(e['original_status_id']) else: LoNone.append(e) # replies with NoneType-Elements replies.remove(e) # remove the NoneType-Elements from the list repl = replies[:] # re-identify both lists: repl = replies without Nonetypes return LoIDs, repl, LoNone # 3. def getOriginalTweets(LoIDs): LoOriginalTweets = [] for e in LoIDs: tw = make_twitter_request(twitter_api.statuses.show, _id=e) # this twitter api request has a rate limit of 180! LoOriginalTweets.append(tw) # #print 'Length of LoOriginalTweets is:', len(LoOriginalTweets) return LoOriginalTweets # 4. def newDict(LoOriginalTweets): # try to get original text and time of tweet, if tweet ID is not valid, pass LoDic = [] for i in LoOriginalTweets: d = {} try: # try to get original text and time of tweet, if tweet ID is not valid, pass d['original_text'] = i['text'] #.encode('utf-8') d['original_time'] = i['created_at'] d['original_status_id'] = i['id'] LoDic.append(d) except: print 'Trouble with this tweet (It is not included in further examination!):', i pass #print len(LoDic) # T e s t #print LoDic[0].keys() # T e s t return LoDic # 5. def clusterValid(LoDic, repl): import time repl = sortLoD(repl, 'original_status_id') # sort repl #print 'len repl', len(repl) # T e s t for n in LoDic: i = bisectInLoD(repl, 'original_status_id', n['original_status_id']) # search for id in repl n.update(repl[i]) repl.pop(i) # remove item from list after it's appended to LoDic if screen_name in n['original_text']: # test if reply is answer n['reply_is_answer'] = 1 else: n['reply_is_answer'] = 0 if '?' in n['original_text']: # check if original tweet was a question (included an '?') n['original_is_question'] = 1 else: n['original_is_question'] = 0 # calculate reaction time to reply #calculating Tweets per day and year t0 = time.mktime(time.strptime(n['original_time'], "%a %b %d %H:%M:%S +0000 %Y"))#returns date in seconds (from 1970-01-01) t1 = time.mktime(time.strptime(n['reply_time'], "%a %b %d %H:%M:%S +0000 %Y")) diff = round(float((t1 - t0))/3600,1) #calculates the difference in hours (3600 sec per hour) n['hours_to_answer'] = diff #print len(n.keys()) # T e s t #print n.keys() # T e s t return LoDic, repl # 6. def clusterNoneTypes(repl): for n in repl: n['original_text'] = '-' n['original_time'] = '-' n['reply_is_answer'] = '-' n['hours_to_answer'] = '-' n['original_is_question'] = '-' n['orphan'] = 1 return repl # 7. def isFollower(repl): filenameFLW = screen_name + '_Followers_' + timestamp_Followers + '.csv' flw = impCSV(filenameFLW) flw = sortLoD(flw, 'followers_user_id') cluster = ['librarian', 'Bib', 'publisher'] for n in repl: i = bisectInLoD(flw, 'followers_user_id', n['original_user_id']) if type(i) == int: if flw[i]['cluster'] in cluster: n['is_follower'] = 'professional' else: n['is_follower'] = 'nonprof' if 'local' in flw[i]['followers_location']: n['follower_local'] = 1 else: n['follower_local'] = 0 else: n['is_follower'] = 0 n['follower_local'] = 0 return repl filenameTL = screen_name + '_timeline_' + timestamp_Timeline + '.json' tl = readJSON(filenameTL) # 0. get timeline listOfReplies = getReplies(tl) # 1.0 get the replies from TL if len(listOfReplies) > 0: # 1.1 if there are replies at all LoIDs, repl, LoNone = separateListOfReplies(listOfReplies) # 2. get list of valid status IDs of original tweets LoOriginalTweets = getOriginalTweets(LoIDs) # 3. make Twitter API request to get original Tweets # only 180 Tweets per 15 min!! LoDic = newDict(LoOriginalTweets) # 4. try to get original text and time of tweet LoDic, repl = clusterValid(LoDic, repl) # 5. cluster the valid tweets repl += LoNone # 6.0 concatenate both NoneType lists repl = clusterNoneTypes(repl) # 6.1 cluster the NoneType tweets repl += LoDic # 7.0 concatenate Valid & NoneType lists repl = isFollower(repl) # 7.1 check if replied to are followers saveConversationAsJSON(repl, screen_name) # 8. save as json-file else: # 9. create LoD for non replying libs edl = ['hours_to_answer', 'is_follower', 'original_time', 'original_is_question', 'orphan', 'reply_is_answer', 'reply_time', 'follower_local', 'reply_status_id'] repl = [] ed = {} for e in edl: ed[e] = '-' repl.append(ed) return repl # 10. return the LoD def saveReplyStats(repl,screen_name): lod = [] for e in repl: d = {} d['hours_to_answer'] = e['hours_to_answer'] d['is_follower'] = e['is_follower'] d['follower_local'] = e['follower_local'] d['original_is_question'] = e['original_is_question'] d['original_time'] = e['original_time'] d['orphan'] = e['orphan'] d['reply_is_answer'] = e['reply_is_answer'] d['reply_time'] = e['reply_time'] d['reply_status_id'] = e['reply_status_id'] lod.append(d) exp2CSV(lod, screen_name) # 4. Reporting Functions def reportFollower(rep): p = 0 n = 0 nf = 0 l = 0 for e in rep: if e['is_follower'] == 'professional': p += 1 elif e['is_follower'] == 'nonprof': n += 1 elif e['is_follower'] == 0: nf += 1 else: print 'Take a closer look at', e print if e['follower_local'] == 1: l += 1 print 'From the total of ' + str(len(rep)) + ', the replied to accounts belonged to following groups:' print p, 'professionals' print n, 'non professionals' print nf, 'non followers' print l, 'of these are locals.' def reactionReport(rep): antime = 0 orph = 0 quest = 0 ans = 0 for e in rep: # calculate mean of time to answer if e['orphan'] == 1: orph += 1 else: if type(e['hours_to_answer']) == float: antime += e['hours_to_answer'] # calculate answers to questions if e['original_is_question'] == 1: quest += 1 if e['reply_is_answer'] == 1: ans += 1 print 'It took about', round(antime/(len(rep) - orph),1), ' hours in average to reply to a tweet.' print orph, "of the original tweets were no longer accessible (were deleted)" print " - and thus couldn't be evaluated." print "Of these tweets,", quest, "were questions (i.e. a ratio of ", round(float(quest)/(len(rep) - orph),2), "),", print ans, "were answers to questions." # # 2. Wrap Up Function # def getConversations(Twitterfile, timestamp_Timeline, timestamp_Followers): ''' input: Twitterfile, timestamp_Timeline, timestamp_Followers output: returns LoD as a csv with keys u'hours_to_answer', u'is_follower', u'original_is_question', u'original_time',u'orphan', u'reply_is_answer', u'reply_time', u'follower_local' ''' f = impCSV(Twitterfile) listOfScreenNames = [] for e in f: listOfScreenNames.append(e['Twitter']) # get Twitter handel of the library for sn in listOfScreenNames: convers = repliedToTweetList(sn, timestamp_Timeline, timestamp_Followers) saveReplyStats(convers, sn)
# # Creating the Twitter CSV files # # Write new csv files with all the libraries with Twitter handles # # - 1 file for the National libraries (3 libraries) # - 1 file for university libraries (27 libraries) # - 1 file for public libraries (21 libraries) import csv import json #import & export CSV def impCSV(input_file): ''' input_file = csv with keys: "URL", "Twitter" output = list of dictionaries ''' f = open(input_file, 'r') d = csv.DictReader(f) LoD = [] # list of dictionaries for row in d: LoD.append(row) f.close() return LoD def exp2CSV(listOfDict, filename): ''' arguments = list of dictionaries, filename output = saves file to cwd (current working directory) ''' outputfile = filename keyz = listOfDict[0].keys() f = open(outputfile,'w') dict_writer = csv.DictWriter(f,keyz) dict_writer.writer.writerow(keyz) dict_writer.writerows(listOfDict) f.close() # extracting the tweeting libraries form the files def twiLibCSV(listname, newFilename): ''' input: the name of the list and a Filename output: saves a new LoD with only the tweeting libraries and prints out a status update ''' LoD_2 = [] for i in listname: LoD = impCSV(i) for i in LoD: if i['Twitter'] != '@_@': i['Twitter'] = i['Twitter'].lower() # the Twitter names given on the websites LoD_2.append(i) # and the screen_names in the Twitter accounts # vary sometimes regarding to upper- and lower case! exp2CSV(LoD_2, newFilename) print 'The new csv file was saved as', newFilename, 'to your current working directory!' print print 'In this file are', len(LoD_2), 'libraries:' print print json.dumps(LoD_2, indent=1) #return LoD_2
import time class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ x_str = str(abs(x)) #先取絕對值 reversed_x = x_str[::-1] if x >= 0: ans_int = int(reversed_x) else: ans_int = int(reversed_x) * (-1) #注意沒有sign可以放到2**32,如果有sign的話只能到+/-2**31 if ans_int>int(2**31) or ans_int<int(-2**31): ans_int = 0 else: pass print(ans_int) return ans_int start = time.time() test = int(-15741222222) S=Solution() S.reverse(test) end = time.time() print(end-start)
import sqlite3 conn = sqlite3.connect('Database.db') c = conn.cursor() def createTables(c): c.execute('''CREATE TABLE USERS ([uid] INTEGER PRIMARY KEY, [username] VARCHAR(30) NOT NULL UNIQUE, [password] VARBINARY(100) NOT NULL, [role] VARCHAR(20)) ''') conn.commit() def populateTables(c): c.execute('''INSERT INTO USERS VALUES (1, 'threefish', 01010101, 'fish')''') conn.commit() createTables(c) c.execute("SELECT * FROM USERS") print(c.fetchall()) conn.close()
hungry = input("Are you hungry?") if hungry == "yes": print("Eat pasta.") else: print("Go to your work")
# You are given a string.Your task is to print only the consonants present in the string without affecting the sentence spacings if present. If no consonants are present print -1 # Input Description: # You are given a string ‘s’. # Output Description: # Print only consonants. # Sample Input : # I am shrey # Sample Output : # m shry s=input() vowel=["a","e","i","o","u","A","E","I","O","U"] b=[] for i in s: if i not in vowel: b.append(i) if b: print("".join(b)) else: print("-1")
### Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. n=input() print(n) print(len(n)) b="ing" j=len(n)-1 print(j) if(n.endswith("ing")): print(n+"ly") else: print(n+"ing")
##real armstrong no n1=int(input()) sum=0 temp=n1 while(temp>0): digit=temp%10 sum+=digit**3 temp//=10 if(sum==n1): print("armstrong") else: print("not armstrong")
###Write a Python program to swap comma and dot in a string. Go to the editor ###Sample string: "32.054,23" ###Expected Output: "32,054.23" S = input() k = "" for i in S: if i == ",": k = k + "." continue if i == ".": k = k + "," continue else: k = k + i print(k)
### Write a Python program to count repeated characters in a string. Go to the editor ##Sample string: 'thequickbrownfoxjumpsoverthelazydog' ##Expected output : ##o 4 ##e 3 ##u 2 ##h 2 ###r 2 ##t 2### s=(input()) print(s) dic={} for i in s: if(not dic.get(i)): dic[i]=1 else: dic[i]+=1 print(dic) for j in dic.keys(): if dic[j]>1: print(j,end=" ") print(dic[j])
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> ##decimal to binary >>> import math num=int(input()) print(num%2) rem="" while num>=1: rem+=str(num%2) num=math.floor(num/2) binary="" for i in range(len(rem)-1,-1,-1): binary = binary + rem[i] print(binary)
##Write a Python program to find the first non-repeating character in given string. ##input:ammartamizh ##output:['a', 'm', 'm', 'a', 'r', 't', 'a', 'm', 'i', 'z', 'h'] ##{'a': 3, 'm': 3, 'r': 1, 't': 1, 'i': 1, 'z': 1, 'h': 1} ##r s=list(input()) print(s) dic={} for i in s: if(not dic.get(i)): dic[i]=1 else: dic[i]+=1 print(dic) for j in dic.keys(): if dic[j]==1: print(j) break
class FileParser(object): """This class reads the file input and returns appropriate data to caller""" def __init__(self, path_to_file): self.path_to_file = path_to_file def read_file(self): """Read file contents and return a list""" # ipdb.set_trace(context=1) list_allocations = [] contents = [line.rstrip('\n') for line in open(self.path_to_file, 'r')] for line in contents: words = line.split(" ") person_name = words[0].replace( "'", "") + " " + words[1].replace("'", "") person_type = words[2] residing = "N" if len(words) == 4: residing = "Y" list_allocations.append([person_name, person_type, residing]) return list_allocations
""" Author: Pruthvi Suryadevara Email: pruthvi.suryadevara@tifr.res.in Code to plot Mass as a function of radius """ import numpy as np import scipy.integrate as area import matplotlib.pyplot as plt ### Using Cartesian cootdinates def fz(y,x,r): return(area.quad(lambda z:1,-np.sqrt(r**2 -x**2 -y**2),np.sqrt(r**2 -x**2 -y**2))[0]) def fy(x,r): return(area.quad(fz,-np.sqrt(r**2 -x**2),np.sqrt(r**2 -x**2),args=(x,r,))[0]) def vol(r): volu=area.quad(fy,-r,r,args=(r,))[0] return volu ### Using Sperical coordinates def ar(r,p): return(r**2 * np.sin(p)) def fr(R,tet,p): return(area.quad(ar,0,R,args=(pi,))[0]) def fpi(R,tet): return(area.quad(fr,0,0.5 * np.pi,args=(R,tet,))[0]) def vol2(R): return(area.quad(fpi,0,2*np.pi,args=(R,))[0]) p=10 rs=np.linspace(0,10,100) volu=[(lambda x:p*vol(x))(x) for x in rs] plt.plot(rs,volu) plt.xlabel("Radius") plt.ylabel("Mass") plt.title("Mass vs Radius") plt.show()
str1 = str(input()) str2 = str(input()) if(str1==str2): print(-1) else: print(max(len(str1),len(str2)))
import torch import torch.functional as F from torch.autograd import Variable import numpy as np #created multiple layers for a neural network using a logistic optimizer xy = np.loadtxt('/Users/elliottchoi/Desktop/Code_Repository/data-03-diabetes.csv', delimiter=',', dtype=np.float32) x_data=Variable(torch.from_numpy(xy[:,0:-1])) y_data=Variable(torch.from_numpy(xy[:,[-1]])) #prints the dimensions of the data print(x_data.data.shape) print(y_data.data.shape) class Model(torch.nn.Module): #use of sigmoid def __init__(self): super(Model,self).__init__() #4 layers of back neural network self.layerOne=torch. nn.Linear(8,6) self.layerTwo =torch.nn.Linear(6, 4) self.layerThree = torch.nn.Linear(4, 2) self.layerFour = torch.nn.Linear(2, 1) #in the end of the data, we connecate 8 vars to 1 output #output is 0 or 1, so the appropriate use of a sigmoid self.sigmoid=torch.nn.Sigmoid() def forward(self,x): out1=self.sigmoid(self.layerOne(x)) out2 = self.sigmoid(self.layerTwo(out1)) out3 = self.sigmoid(self.layerThree(out2)) y_predict = self.sigmoid(self.layerFour(out3)) return y_predict #model object model=Model() #Use of Sigmoid means we want to use BCE loss criterion=torch.nn.BCELoss(size_average=True) optimizer=torch.optim.SGD(model.parameters(),lr=0.01) for epoch in range (1000): y_predict=model(x_data) loss=criterion(y_predict,y_data) print(epoch,loss.data[0]) optimizer.zero_grad() loss.backward() optimizer.step()
from socket import * s = socket(AF_INET,SOCK_STREAM) server = input('Server u want to Connect :-') def pscan(port): try: s.connect((server,port)) return True except: return False for x in range(1,25): if pscan(x): print('Port {0} is open!!!!!!!!!!!!!!!'.format(x)) else: print('Port {0} is closed'.format(x))
from graphics import * class Computer(object): def __init__(self, x, y, color, win): self.x = x self.y = y self.color = color self.drawComp(x, y, color, win) # place points and color here def drawComp(self, x, y, color, win): comp = Rectangle(Point(self.x, self.y), Point(self.x+100, self.y+200)) comp.setFill(self.color) comp.draw(win) class Desktop(Computer): def __init__(self, x, y, color, win): super(Desktop, self).__init__(x, y, color, win) self.monitor = Monitor(x, y, win) #place points here def drawKeyBoard(self, color, win): rec = Rectangle(Point(self.x+50, self.y+100), Point(self.x+50, self.y+100) ) rec.setFill(self.color) rec.draw(win) class Laptop(Computer): def __init__(self, x, y, color, win): super(Laptop, self).__init__(x, y, color, win) self.monitor = Monitor(x, y, win) #place points and color self.drawBottom(color, win) #place color def drawBottom(self, color, win): bottom = Rectangle(Point(self.x, self.y+100), Point(self.x, self.y+100)) bottom.setFill(self.color) bottom.draw(win) class Monitor(object): def __init__(self, x, y, win): self.x = x self.y = y self.drawMonitor(x, y, win) #place points def drawMonitor(self, x, y, win): monitor = Rectangle(Point(self.x, self.y), Point(self.x+200, self.y+100)) monitor.draw(win)
# http://judge.mipt.ru/mipt_cs_on_python3_2016/labs/lab5.html # Упражнение №2. Задачи посложнее # ================================= # Переставьте соседние элементы в списке. Задача решается в три строки. s = "1 2" s = "1" s = "1 2 3 4 5 6 7" s = "" s = "1 2 3 4 5 6" L = s.split() last = len(L) - 1 if len(L) % 2 else len(L) L[:last:2], L[1:last:2] = L[1:last:2], L[:last:2] print(*L) # Выполните циклический сдвиг элементов списка вправо. s = "1 2 3 4 5" L = s.split() print(*(L[-1:] + L[:-1])) # Выведите элементы, которые встречаются в списке только один раз. # Элементы нужно выводить в том порядке, в котором они встречаются в списке. s = "1 2 2 3 3 3 5 6 6" L = s.split() print(*[el for el in L if L.count(el) == 1]) # Определите, какое число в этом списке встречается чаще всего. Если таких # чисел несколько, выведите любое из них. s = "1 2 2 3 3 4 4 5 6 6 3 4" L = s.split() print(max([L.count(el) for el in L]))
# http://judge.mipt.ru/mipt_cs_on_python3_2016/labs/lab5.html#o9 # Упражнение № 9 # =============== hours = int(input()) data = list(map(int, input().split())) k = int(input()) maximum = max([sum(data[i:i + k]) for i in range(hours - k + 1)]) print(maximum)
# http://judge.mipt.ru/mipt_cs_on_python3/labs/lab1.html#o5 # http://cs.mipt.ru/python/lessons/lab2.html#o5 # Упражнение №5: больше квадратов import turtle import turtle_helper def paint_square(turtle, side, x = 0, y = 0, angle = 0): turtle_helper.move(turtle, x, y) turtle.left(angle) for i in range(4): turtle.forward(side) turtle.left(90) def main(): wn = turtle_helper.make_window("lightgreen", "More squares") t = turtle_helper.make_turtle("red", 2, -50, -100) SQUARES_QTY = 10 side = 40 side_shift = 15 x, y = -100, -50 for i in range(SQUARES_QTY): paint_square(t, side, x, y) side += 2 * side_shift x -= side_shift y -= side_shift wn.mainloop() if __name__ == '__main__': main()
import unittest from A import find_two_equal class FindTwoEqual(unittest.TestCase): def test_find_two_equal(self): self.assertEqual(find_two_equal([8, 3, 5, 4, 5, 1]), 5) self.assertEqual(find_two_equal([5, 5, 1, 4, 2, 3]), 5) self.assertEqual(find_two_equal([1, 4, 2, 3, 5, 5]), 5) self.assertEqual(find_two_equal([5, 5]), 5) self.assertEqual(find_two_equal([5, 1, 2, 3, 4, 5]), 5) unittest.main()
""" http://judge.mipt.ru/mipt_cs_on_python3_2015/labs/lab6.html#a Задача A ========= В массиве ровно два элемента равны. Найдите эти элементы. Программа получает на вход число N, в следующей строке заданы N элементов списка через пробел. Выведите значение совпадающих элементов. """ def find_two_equal(array): array_copy = array[:] array_copy.sort() for i in range(1, len(array_copy)): if array_copy[i] == array_copy[i - 1]: return array_copy[i] def main(): _ = int(input()) array = list(map(int, input().split())) print(find_two_equal(array)) if __name__ == '__main__': main()
# http://judge.mipt.ru/mipt_cs_on_python3/labs/lab1.html#o10 # http://cs.mipt.ru/python/lessons/lab2.html#o10 # Упражнение № 10: "цветок" (версия № 2) import turtle import turtle_helper def main(): wn = turtle_helper.make_window("lightgreen", "Flower") t = turtle_helper.make_turtle("red", 2) radius = 100 # Используем собственную функцию draw_circle for angle in range(0, 360, 45): turtle_helper.draw_circle(t, radius, angle) wn.mainloop() if __name__ == '__main__': main()
#K-邻近算法,KNN,当k=1时称为最近临近算法 import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors,datasets,model_selection def load_classfication_data(): digits = datasets.load_digits() X_train = digits.data y_train = digits.target return model_selection.train_test_split(X_train,y_train,test_size = 0.25,stratify = y_train) def create_regression_data(n): X = np.random.rand(n,1) y = np.sin(X).ravel() y[::5] += (0.5 - np.random.rand(n/5)) return model_selection.train_test_split(X,y) def test_KneighborsClassifier(*data): X_train,X_test,y_train,y_test = data clf = neighbors.KNeighborsClassifier() clf.fit(X_train, y_train) clf.kneighbors_graph(X_train,n_neighbors,mode) print('Training Score : %f' %clf.score(X_train,y_train)) print('Test Score : %f' %clf.score(X_test,y_test)) X_train,X_test,y_train,y_test = load_classfication_data() test_KneighborsClassifier(X_train,X_test,y_train,y_test) #t同时考察K值以及投票规则对预测性能的影响 def test_KneighborsClassifier_k_w(*data): X_train,X_test,y_train,y_test = data ks = np.linspace(1,y_train.size,num = 100,endpoint=False,dtype='int') weights = ['uniform','distance'] fig = plt.figure() ax = fig.add_subplot(1,1,1) for weight in weights: training_scores = [] testing_scores = [] for k in ks: clf = neighbors.KNeighborsClassifier(weights = weight,n_neighbors = k,n_jobs=-1) clf.fit(X_train, y_train) training_scores.append(clf.score(X_train, y_train)) testing_scores.append(clf.score(X_test,y_test)) ax.plot(ks,training_scores,label = 'training_scores : weight = %s' %weight) ax.plot(ks,testing_scores,label = 'testing_scores : weight = %s' %weight) ax.legend() ax.set_xlabel('K') ax.set_ylabel('score') ax.set_title('KneighborsClassifier') ax.set_ylim(0,1.05) X_train,X_test,y_train,y_test = load_classfication_data() test_KneighborsClassifier_k_w(X_train,X_test,y_train,y_test) def test_KneighborsClassifier_k_p(*data): X_train,X_test,y_train,y_test = data ks = np.linspace(1,y_train.size,num = 100,endpoint=False,dtype='int') ps = [1,2,10] fig = plt.figure() ax = fig.add_subplot(1,1,1) for p in ps: training_scores = [] testing_scores = [] for k in ks: clf = neighbors.KNeighborsClassifier(p = p,n_neighbors = k,n_jobs=-1) clf.fit(X_train, y_train) training_scores.append(clf.score(X_train, y_train)) testing_scores.append(clf.score(X_test,y_test)) ax.plot(ks,training_scores,label = 'training_scores : p = %s' %p) ax.plot(ks,testing_scores,label = 'testing_scores : p = %s' %p) ax.legend() ax.set_xlabel('K') ax.set_ylabel('score') ax.set_title('KneighborsClassifier') ax.set_ylim(0,1.05) X_train,X_test,y_train,y_test = load_classfication_data() test_KneighborsClassifier_k_p(X_train,X_test,y_train,y_test) #KNN回归同KNN决策相似,KNeighborsRegressor
def add(no): sum=int(0) for i in str(no): sum=sum+int(i); return sum def main(): no=int(input("Enter no : ")); print("Sum is: ",add(no)) if __name__=="__main__": main();