text
stringlengths
37
1.41M
# Implement a basic calculator to evaluate a simple expression string. # # The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. # # You may assume that the given expression is always valid. # # Some examples: # "3+2*2" = 7 # " 3/2 " = 1 # " 3+5 / 2 " = 5 # Note: Do not use the eval built-in library function. ### Solution1: split string into nums list and symbols list then process numbers connected with * or /, ### Time O(N) Space O(N) class Solution: def calculate(self, s): """ :type s: str :rtype: int """ ## remove all spaces in string i = 0 num_str = "" num_list = [] symbol_list = [] s = s.replace(" ", "") while i < len(s): if s[i].isdigit(): num_str = num_str + s[i] i += 1 continue num = int(num_str) num_list.append(num) symbol_list.append(s[i]) num_str = '' # print("non_digit is %s , number is %d" % (s[i], num)) i += 1 num = int(num_str) num_list.append(num) i = 0 while i < len(symbol_list): if symbol_list[i] == "*": num_list[i] = num_list[i] * num_list[i + 1] num_list.pop(i + 1) symbol_list.pop(i) elif symbol_list[i] == '/': num_list[i] = num_list[i] // num_list[i + 1] num_list.pop(i + 1) symbol_list.pop(i) else: i += 1 ## Scan symbol_list and num_list1 to get final calculation i = 1 sum = num_list[0] while i < len(num_list): if symbol_list[i - 1] == '+': sum += num_list[i] else: sum -= num_list[i] i += 1 # print("total = %d" % sum) return sum # print(Solution().calculate("30+2*2 - 3/2 + 5")) #38 # print(Solution().calculate("3+2*2")) #7 # print(Solution().calculate("3/2")) #1 # print(Solution().calculate("3 + 5 / 2")) #5 # print("\n") ### Solution2: transform such string into a list with +/-, like [30 + 2 *2 - 3/2 + 5], 30 => +30, 2 * 2 =>4 , -3/2 => -1, +5 => 5 ### One loop is enough ### very fast and clean ### Time O(N) Space O(N) class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ stack = [] num = 0 prev_op = '+' s = s + '+' for n in s: if n.isdigit(): num = num * 10 + ord(n) - ord('0') elif n == ' ': continue else: # "3+2*2" if prev_op == '+': stack.append(num) elif prev_op == '-': stack.append(-num) elif prev_op == '*': stack[-1] = stack[-1] * num else: # in python -3 / 2 == -2, since when dividing Python uses Floor division. stack[-1] = int(stack[-1] * 1.0 / num) num = 0 prev_op = n return sum(stack) print(Solution().calculate("30+2*2 - 3/2 + 5")) #38 print(Solution().calculate("3+2*2")) #7 print(Solution().calculate("3/2")) #1 print(Solution().calculate("3 + 5 / 2")) #5 print("\n")
# Implement the following operations of a queue using stacks. # # push(x) -- Push element x to the back of queue. # pop() -- Removes the element from in front of queue. # peek() -- Get the front element. # empty() -- Return whether the queue is empty. # Notes: # You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. # Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. # You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). ### Solution 1 ### 双栈 O(1) in average in time and O(N) in space class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.stack1 = [] self.stack2 = [] def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: void """ self.stack1.append(x) def stack1tostack2(self): if len(self.stack2) == 0: while self.stack1: self.stack2.append(self.stack1.pop()) def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ self.stack1tostack2() return self.stack2.pop() def peek(self): """ Get the front element. :rtype: int """ self.stack1tostack2() return self.stack2[-1] def empty(self): """ Returns whether the queue is empty. :rtype: bool """ self.stack1tostack2() return len(self.stack2) == 0 # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty() ### Solution 2: from online solution ### 单栈 O(1) in average in time but push use O(N) and O(N) in space class Queue: # initialize your data structure here. def __init__(self): self.stack = [] # @param x, an integer # @return nothing def push(self, x): swap = [] while self.stack: swap.append(self.stack.pop()) swap.append(x) while swap: self.stack.append(swap.pop()) # @return nothing def pop(self): self.stack.pop() # @return an integer def peek(self): return self.stack[-1] # @return an boolean def empty(self): return len(self.stack) == 0 # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
# There are a total of n courses you have to take, labeled from 0 to n - 1. # # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] # # Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? # # For example: # # 2, [[1,0]] # There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. # # 2, [[1,0],[0,1]] # There are a total of 2 courses to take. To take course 1 you should have finished course 0, # and to take course 0 you should also have finished course 1. So it is impossible. ### Solution 1: Time complexity is not good enough => Solution 2 class Solution: """ @param: numCourses: a total of n courses @param: prerequisites: a list of prerequisite pairs @return: true if can finish all courses or false """ def canFinish(self, numCourses, prerequisites): # write your code here ## 异常值判断 if prerequisites is None or len(prerequisites) == 0: return True ## neighbors_dict save key: pre_class value: list of neighbors of pre_class neighbors_dict = {} ## class_indegree dict key: class value: indegree count class_indegree = {} ## pairs_dict to check whether processing duplicate pairs - key: pair value: count pairs_dict = {} ## list including all distinct classes total_classes = [] ## prerequisites pair [class node, pre-class node] for classpair in prerequisites: pre_class = classpair[1] current_class = classpair[0] if (current_class, pre_class) not in pairs_dict: pairs_dict[(current_class, pre_class)] = 1 else: continue if current_class not in class_indegree: class_indegree[current_class] = 1 else: class_indegree[current_class] += 1 ## current_class as neighbor of pre_class if pre_class not in neighbors_dict: neighbors_dict[pre_class] = [current_class] else: neighbors_dict[pre_class].append(current_class) ## save unique class value if pre_class not in total_classes: total_classes.append(pre_class) if current_class not in total_classes: total_classes.append(current_class) ## initialize top_list and BFS queue top_list = [] queue = [] ## loop through list total_courses and save nodes with indegree = 0 for class_node in total_classes: if class_node not in class_indegree: top_list.append(class_node) queue.append(class_node) if class_node not in neighbors_dict: neighbors_dict[class_node] = [] ## scan BFS queue and reduce 1 indegree for those nodes while queue: class_node = queue.pop(0) for neighbor in neighbors_dict[class_node]: print("class_node %d: neighbor: %d" %(class_node, neighbor)) class_indegree[neighbor] -= 1 if class_indegree[neighbor] == 0: queue.append(neighbor) top_list.append(neighbor) ## check topological conditions: return len(total_classes) == len(top_list) ## Solution 2.1: ## 上次那个用dict存储每个node的neighbors 和相应的indegree counts,由于用到了很多hash,如果list量很大,比较耗space ## 这个方法和Solution1 类似,但把neighbors 设成array 组,实际就是adjacent list, 每个index代表每个course的相应neibors [[], [], ...] ## 然后在同一个loop里实现indegree的count class Solution: """ @param: numCourses: a total of n courses @param: prerequisites: a list of prerequisite pairs @return: true if can finish all courses or false """ def canFinish(self, numCourses, prerequisites): # write your code here ## extreme situations exclusion if prerequisites is None or len(prerequisites) == 0: return True ## initialize neighbors list for each class [[], [], ...] class_neighbors = [[] for i in range(numCourses)] ## initialize indegree count for each class [0,0,...] class_indegree = [0] * numCourses for current_class, pre_class in prerequisites: class_neighbors[pre_class].append(current_class) class_indegree[current_class] += 1 ## initialize topological list and BFS queue top_list = [] queue = [] ## get 0 indegree nodes into top_list first for class_num in range(numCourses): if class_indegree[class_num] == 0: top_list.append(class_num) queue.append(class_num) ## loop queue and get its neighbors while queue: class_num = queue.pop(0) for neighbor in class_neighbors[class_num]: class_indegree[neighbor] -= 1 if class_indegree[neighbor] == 0: queue.append(neighbor) top_list.append(neighbor) return len(top_list) == numCourses ## Solution 2.2 ## Solution 2 的进阶版,可以让速度更快,因为少存了一个top_list, top_list也耗space, 如果换成integer 效果一样但省空间 ## 因为现在没让return topological list而是问是不是, 所以可以省去一个list的空间 class Solution: """ @param: numCourses: a total of n courses @param: prerequisites: a list of prerequisite pairs @return: true if can finish all courses or false """ def canFinish(self, numCourses, prerequisites): # write your code here ## extreme situations exclusion if prerequisites is None or len(prerequisites) == 0: return True ## initialize neighbors list for each class [[], [], ...] class_neighbors = [[] for i in range(numCourses)] ## initialize indegree count for each class [0,0,...] class_indegree = [0] * numCourses for current_class, pre_class in prerequisites: class_neighbors[pre_class].append(current_class) class_indegree[current_class] += 1 ## initialize BFS queue and topological sequeunce count queue = [] count = 0 ## get 0 indegree nodes into top_list first for class_num in range(numCourses): if class_indegree[class_num] == 0: # top_list.append(class_num) queue.append(class_num) ## loop queue and get its neighbors while queue: class_num = queue.pop(0) count += 1 for neighbor in class_neighbors[class_num]: class_indegree[neighbor] -= 1 if class_indegree[neighbor] == 0: queue.append(neighbor) # top_list.append(neighbor) return count == numCourses
""" Check if a given linked list has a cycle. Return true if it does, otherwise return false. Assumption: You can assume there is no duplicate value appear in the linked list. """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): """ 解题思路:记得九章以前提过,trick to find if a cycle exists in linkedlist is to check whether fast/slow pointers他们可以 相遇; 如果fast: slow = 2: 1, 那fast肯定最终能追上slow那个如果是cycle linkedlist Time: O(n) Space: O(1) """ def checkCycle(self, head): """ input: ListNode head return: boolean """ # write your solution here """Corner Cases""" if head is None or head.next is None: return False fast, slow = head.next, head while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if fast == slow: return True return False # build linked list with cycle n1 = ListNode(1); n2 = ListNode(2); n3 = ListNode(3); n4 = ListNode(4) # n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n1 n1.next = n2; n2.next = n3; n3.next = n4; n4.next = None # test cases print(Solution().checkCycle(n1))
""" Given an array of integers, sort the elements in the array in ascending order. The selection sort algorithm should be used to solve this problem. Examples {1} is sorted to {1} {1, 2, 3} is sorted to {1, 2, 3} {3, 2, 1} is sorted to {1, 2, 3} {4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6} Corner Cases What if the given array is null? In this case, we do not need to do anything. What if the given array is of length zero? In this case, we do not need to do anything. """ class Solution(object): """ 解题思路: 选择排序就是从unsorted list里面找最小的,放到第一位;然后继续找最小的在剩余的unsorted list里 Time: O(N^2) Space: O(1) """ def solve(self, array): """ input: int[] array return: int[] """ # write your solution here # corner cases if array is None or len(array) == 0 or len(array) == 1: return array for i in range(len(array) - 1): global_min = i for j in range(i + 1, len(array)): if array[j] < array[global_min]: global_min = j if global_min != i: array[i], array[global_min] = array[global_min], array[i] return array print(Solution().solve([3, 2, 1])) print(Solution().solve([4, 2, -3, 6, 1]))
longest = '' current = '' for x in s: if (current == ''): current = x elif (current[-1] <= x): current += x elif (current[-1] > x): if (len(longest) < len(current)): longest = current current = x else: current = x if (len(current) > len(longest)): longest = current print ('Longest substring in alphabetical order is: ' + longest)
def biggest(listToMeasure): current_biggest = 0 current_answer = None for element in listToMeasure: if element > current_biggest: current_biggest = element current_answer = element return current_answer def largest_odd_times(X): """ Assumes X is a non-empty list of ints Returns the largest element of X that occurs an odd number of times in X. If no such element exists, returns None """ checked_elements = [] elements_with_odd_counts = [] for element in X: if X.count(element) % 2 != 0 and element not in checked_elements: checked_elements.append(element) elements_with_odd_counts.append(element) return biggest(elements_with_odd_counts)
""" represents a packet and its header values. This class is used as an abstraction of the physical structure of a packet """ class Message: # attributes: # sequenceNumber: stored as number # acknowledgmentNumber: stored as number # checksumValue: When a message is received, the checksum header is parsed into # this value. Bit can be detected by comparing this value to the result # of calcChecksum(). stored as number. # payload: message payload not including headers, stored as byte array # messageBytes is the bytes of the entire message def __init__(self, seqNum=0, ackNum=0, payload=None, messageBytes=None): if messageBytes is None: # building message from header values and payload self.sequenceNumber = seqNum self.acknowledgmentNumber = ackNum self.payload = payload self.checksumValue = self.calcChecksum() else: # building message from received packet self.sequenceNumber = messageBytes[0] * 256 + messageBytes[1] self.acknowledgmentNumber = messageBytes[2] * 256 + messageBytes[3] self.checksumValue = messageBytes[4] * 256 + messageBytes[5] self.payload = messageBytes[6:] # convert message to bytes def toBytes(self): seqNum = bytearray([self.sequenceNumber // 256, self.sequenceNumber % 256]) ackNum = bytearray([self.acknowledgmentNumber // 256, self.acknowledgmentNumber % 256]) checksumInt = self.calcChecksum() checksumBytes = bytearray([checksumInt // 256, checksumInt % 256]) return seqNum + ackNum + checksumBytes + bytearray(self.payload) # calculate the checksum of the message def calcChecksum(self): sum = self.sequenceNumber + self.acknowledgmentNumber isNewValue = True nextValue = 0 for byte in self.payload: if isNewValue: nextValue += byte * 256 isNewValue = False else: nextValue += byte sum += nextValue isNewValue = False sum %= 65536 return sum # length of payload in bytes def getLength(self): return len(self.payload)
''' This creates a csv file with row 1: Title, rows 2 - 22: Genres, row 23: ImdB Score ''' import csv genres = ["Action","Adventure","Fantasy","Sci-Fi","Thriller","Documentary","Romance","Animation","Comedy","Family","Musical","Mystery","Western","Drama","History","Sport","Crime","Horror","War","Biography","Music"] with open("movie_metadata.csv", newline='') as f: with open("title_genre_ImdbScore.csv", "w", newline='') as f1: reader = csv.reader(f, delimiter=',') writer = csv.writer(f1, delimiter=',') for row in reader: genres_list = row[9].split('|') genres_cols = [] for x in genres: if x in genres_list: val = 'yes' else: val = 'no' genres_cols.append(val) title = row[11].strip() all_cols = [title] + genres_cols + [row[25]] # print(all_cols) writer.writerow(all_cols)
s=[] n=int(input("enter the elements:")) fir i in range(1,n+1): b=int(input("enter the elements:")) s=append(b)a.sort() print("largest elements is :",s[n-1])
num=int(input("enter a number:")) sum=0 temp=num while temp>0: digit=temp%10 sum+= digit**3 temp//=10 if num== sum: print(num,"is an armstrong number") else: print(num,"is not an armstrong number")
char=input("enter a character:) if(char=='A' or char=='a' or char=='E' or char=='e' or char=='I' or char=='i' or char=='O' char=='o' or char=='U' or char=='u'): print(char."is a vowel") else: print(char."is a consonant")
class MoneyBox: def __init__(self, capacity): self.capacity = capacity self.coins = 0 def can_add(self, v): if self.coins + v <= self.capacity: return True else: return False def add(self, v): if self.can_add(v): self.coins = self.coins + v print('{} coin(s) added successfully.'.format(v)) else: print('{} coin(s) cannot be added to MoneyBox \n It exceeds the capacity of {}'.format(v,self.capacity)) moneybox1 = MoneyBox(5) moneybox1.add(3) moneybox1.add(17) print(moneybox1.coins)
class Produto: def __init__(self, nome, preco): self.nome = nome self.preco = preco class Produtos: def __init__(self): self.produtos = [] def addProduto(self, Produto): self.produtos.append(Produto) def listarProdutos(self): print('Produtos:') for produto in self.produtos: print(f'-- Produto: {produto.nome}, Preço: {produto.preco}') def listarProduto(config): config.bd.listarProdutos() def addProduto(config, nome, preco): ProdutoNovo = Produto(nome, preco) config.bd.addProduto(ProdutoNovo) print(f'O produto {nome} foi adicionado com sucesso!')
## 1. The GIL ## import threading import time import statistics def read_data(): with open("Emails.csv") as f: data = f.read() times = [] for i in range(100): start = time.time() read_data() end = time.time() times.append(end - start) threaded_times = [] for i in range(100): start = time.time() t1 = threading.Thread(target=read_data) t2 = threading.Thread(target=read_data) t1.start() t2.start() for thread in [t1, t2]: thread.join() end = time.time() threaded_times.append(end - start) print(statistics.median(times)) print(statistics.median(threaded_times)) ## 4. Clinton Emails ## import pandas import time emails = pandas.read_csv("Emails.csv") capital_letters = [] start = time.time() for email in emails["RawText"]: capital_letters.append(len([letter for letter in email if letter.isupper()])) total = time.time() - start print(total) ## 6. How The GIL Works ## import threading capital_letters1 = [] capital_letters2 = [] start = time.time() def count_capital_letters(email): return len([letter for letter in email if letter.isupper()]) def count_capitals_in_emails(start, finish, capital_letters): for email in emails["RawText"][start:finish]: capital_letters.append(count_capital_letters(email)) t1 = threading.Thread(target=count_capitals_in_emails, args=(0, 3972, capital_letters1)) t2 = threading.Thread(target=count_capitals_in_emails, args=(3972, 7946, capital_letters2)) t1.start() t2.start() for thread in [t1, t2]: thread.join() total = time.time() - start print(total) ## 9. Multiprocessing ## import threading import multiprocessing capital_letters1 = [] capital_letters2 = [] start = time.time() def count_capital_letters(email): return len([letter for letter in email if letter.isupper()]) def count_capitals_in_emails(start, finish, capital_letters): for email in emails["RawText"][start:finish]: capital_letters.append(count_capital_letters(email)) p1 = multiprocessing.Process(target=count_capitals_in_emails, args=(0, 3972, capital_letters1)) p2 = multiprocessing.Process(target=count_capitals_in_emails, args=(3972, 7946, capital_letters2)) p1.start() p2.start() for process in [p1, p2]: process.join() total = time.time() - start print(total) print(capital_letters1) ## 11. Multiple Cores ## import threading import multiprocessing start = time.time() def count_capital_letters(email): return len([letter for letter in email if letter.isupper()]) def count_capitals_in_emails(start, finish): for email in emails["RawText"][start:finish]: count_capital_letters(email) p1 = multiprocessing.Process(target=count_capitals_in_emails, args=(0, 1986,)) p2 = multiprocessing.Process(target=count_capitals_in_emails, args=(1986, 3972,)) p3 = multiprocessing.Process(target=count_capitals_in_emails, args=(3972, 5958,)) p4 = multiprocessing.Process(target=count_capitals_in_emails, args=(5958, 7946,)) p1.start() p2.start() p3.start() p4.start() for process in [p1, p2, p3, p4]: process.join() total = time.time() - start print(total) ## 13. Inter-Process Communication ## import multiprocessing def count_capital_letters(email): return len([letter for letter in email if letter.isupper()]) def count_capitals_in_emails(start, finish): for email in emails["RawText"][start:finish]: capital_letters.append(count_capital_letters(email)) start = time.time() p1 = multiprocessing.Process(target=count_capitals_in_emails, args=(0, 3972)) p2 = multiprocessing.Process(target=count_capitals_in_emails, args=(3972, 7946)) p1.start() p2.start() for process in [p1, p2]: process.join() total = time.time() - start print(total) def count_capitals_in_emails(start, finish, conn): capital_letters = [] for email in emails["RawText"][start:finish]: capital_letters.append(count_capital_letters(email)) conn.send(capital_letters) conn.close() start = time.time() parent_conn1, child_conn1 = multiprocessing.Pipe() parent_conn2, child_conn2 = multiprocessing.Pipe() p1 = multiprocessing.Process(target=count_capitals_in_emails, args=(0, 3972, child_conn1)) p2 = multiprocessing.Process(target=count_capitals_in_emails, args=(3972, 7946, child_conn2)) p1.start() p2.start() capital_letters1 = parent_conn1.recv() capital_letters2 = parent_conn2.recv() for process in [p1, p2]: process.join() total = time.time() - start print(total) ## 15. Worker Pools ## from multiprocessing import Pool import time p = Pool(2) def count_capital_letters(email): return len([letter for letter in email if letter.isupper()]) start = time.time() capital_letters = p.map(count_capital_letters, emails["RawText"]) total = time.time() - start print(total)
''' Changing global variables : Chaning Game Options >>> screen.inch([row,col] ) 'return a character at row,col' ''' import curses, time, random #screen.nodelay(0) #screen.clear() #curses.noecho() #curses.curs_set(0) def menu(): from shift import shift screen = curses.initscr() screen.keypad(1) dims = screen.getmaxyx() height,width = dims[0]-1, dims[1]-1 curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) selection = -1 opt_string = [' Option : {} '.format(i) for i in range(5) ] options = [0] * 5 options[0] = curses.A_REVERSE while True: #selection < 0: screen.clear() screen.refresh() for i in range(len(opt_string)): screen.addstr(height/2-len(opt_string)+i,width/2-len(opt_string), opt_string[i],options[i]) screen.addstr(23,10,'Option : ') screen.addstr(23,10+10, str(options.index(curses.A_REVERSE)),curses.color_pair(1)|curses.A_BOLD) screen.addstr(23,25,'options : ') screen.addstr(23,25+10, str(options), curses.color_pair(2)|curses.A_BOLD) screen.addstr(23,60,'selection : ') screen.addstr(23,60+12, str(selection), curses.color_pair(2)|curses.A_BOLD) action = screen.getch() ''' key input processing ''' if action == ord('k') or action == curses.KEY_UP: shift(options,-1) elif action == ord('j') or action == curses.KEY_DOWN: shift(options,1) elif action == ord('\n') or action == ord(' '): selection = options.index(curses.A_REVERSE) ''' selection processing made by SPACE or ENTER ''' if selection == 0: pass elif selection == 1: pass elif selection == 4: screen.clear() screen.refresh() return menu()
# 8.9 Creating a New Kind of Class or Instance Attribute # Descriptor for a type-checked attribute class Typed(object): def __init__(self,name,expected_type): self.name = name self.expected_type = expected_type def __get__(self,instance,cls): if instance is None: return self return instance.__dict__[self.name] def __set__(self,instance,value): if not isinstance(value, self.expected_type): raise TypeError('Expected '+ str(self.expected_type) ) instance.__dict__[self.name] = value def __delete__(self,instance): del instance.__dict__[self.name] # class decorator that applies it to selected attributes def type_assert(**kwargs): def decorate(cls): for name, expected_type in kwargs.items(): # Attach a Typed descriptor to the class setattr(cls,name, Typed(name,expected_type) ) return cls return decorate # example use if __name__ == '__main__': @type_assert(name=str, share=int,price=float) class Stock(object): def __init__(self,name,shares,price): self.name = name self.shares = shares self.price = price stock = Stock('AAPL',50,10000.0) print stock.name,stock.shares,stock.price stock.name = 'GOOG' stock.price = 4000.0 print stock.name,stock.shares,stock.price
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 016_layers.py pygame sprites with different layers and parallax scrolling url: http://thepythongamebook.com/en:part2:pygame:step016 author: [email protected] licence: gpl, see http://www.gnu.org/licenses/gpl.html change the sprite layer by clicking with left or right mouse button the birdsprites will appear before or behind the blocks point on a sprite and pres "p" to print out more information about that sprite part of www.pythongamebook.com by Horst JENS works with python3.4 and python2.7 """ #the next line is only needed for python2.x and not necessary for python3.x from __future__ import print_function, division def game(): import pygame import os import random pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag pygame.init() screen=pygame.display.set_mode((640,480)) # try out larger values and see what happens ! #winstyle = 0 # |FULLSCREEN # Set the display mode print("pygame version", pygame.ver) BIRDSPEEDMAX = 200 BIRDSPEEDMIN = 10 FRICTION =.999 FORCE_OF_GRAVITY = 9.81 def write(msg="pygame is cool"): """write text into pygame surfaces""" myfont = pygame.font.SysFont("None", 32) mytext = myfont.render(msg, True, (0,0,0)) mytext = mytext.convert_alpha() return mytext class Text(pygame.sprite.Sprite): """ display a text""" def __init__(self, msg ): self.groups = allgroup, textgroup self._layer = 99 pygame.sprite.Sprite.__init__(self, self.groups) self.newmsg(msg) def update(self, time): pass def newmsg(self, msg="i have nothing to say"): self.image = write(msg) self.rect = self.image.get_rect() self.rect.center = (screen.get_width()/2,10) class Mountain(pygame.sprite.Sprite): """generate a mountain sprite for the background, to demonstrate parallax scrolling. Like in the classic 'moonbuggy' game. Mountains slide from right to left""" def __init__(self, atype): self.type = atype if self.type == 1: self._layer = -1 self.dx = -100 self.color = (0,0,255) # blue mountains, close elif self.type == 2: self._layer = -2 self.color = (200,0,255) # pink mountains, middle self.dx = -75 else: self._layer = -3 self.dx = -35 self.color = (255,0,0) # red mountains, far away self.groups = allgroup, mountaingroup pygame.sprite.Sprite.__init__(self, self.groups) # THE Line self.dy = 0 x = 100 * self.type * 1.5 y = screen.get_height() / 2 + 50 * (self.type -1) self.image = pygame.Surface((x,y)) #self.image.fill((0,0,0)) # fill with black self.image.set_colorkey((0,0,0)) # black is transparent pygame.draw.polygon(self.image, self.color, ((0,y), (0,y-10*self.type), (x/2, int(random.random()*y/2)), (x,y-10*self.type), (x,y), (9,y)),0) # width=0 fills the polygon self.image.convert_alpha() self.rect = self.image.get_rect() self.pos = [0.0,0.0] # start right side from visible screen self.pos[0] = screen.get_width()+self.rect.width/2 self.pos[1] = screen.get_height()-self.rect.height/2 self.rect.centerx = round(self.pos[0],0) self.rect.centery = round(self.pos[1],0) self.parent = False def update(self, time): self.pos[0] += self.dx * time self.pos[1] += self.dy * time self.rect.centerx = round(self.pos[0],0) self.rect.centery = round(self.pos[1],0) # kill mountains too far to the left if self.rect.centerx + self.rect.width/2+10 < 0: self.kill() # create new mountains if necessary if not self.parent: if self.rect.centerx < screen.get_width(): self.parent = True Mountain(self.type) # new Mountain coming from the right side class Block(pygame.sprite.Sprite): """a block with a number indicating it's layer. Blocks move horizontal and bounce on screen edges""" def __init__(self, blocknumber=1): self.blocknumber = blocknumber self.color = (random.randint(10,255), random.randint(10,255), random.randint(10,255)) self._layer = self.blocknumber self.groups = allgroup, blockgroup pygame.sprite.Sprite.__init__(self, self.groups) # THE line self.area = screen.get_rect() self.image = pygame.Surface((100,100)) self.image.fill(self.color) self.image.blit(write(str(self.blocknumber)),(40,40)) self.image = self.image.convert() self.rect = self.image.get_rect() self.rect.centery = screen.get_height() / 2 self.rect.centerx = 100 * self.blocknumber + 50 #self.rect.centery = (screen.get_height() / 10.0) * self.blocknumber + self.image.get_height() / 2 self.pos = [0.0,0.0] self.pos[0] = self.rect.centerx self.pos[1] = self.rect.centery self.dy = random.randint(50,100) * random.choice((-1,1)) self.dx = 0 def newspeed(self): self.dy *= -1 def update(self, time): if not self.area.contains(self.rect): # --- compare self.rect and area.rect if self.pos[1] < self.area.top: self.pos[1] = self.area.top self.newspeed() # calculate a new direction elif self.pos[1] > self.area.bottom: self.pos[1] = self.area.bottom self.newspeed() # calculate a new direction self.pos[0] += self.dx * time self.pos[1] += self.dy * time self.rect.centerx = round(self.pos[0],0) self.rect.centery = round(self.pos[1],0) class BirdCatcher(pygame.sprite.Sprite): """circle around the mouse pointer. Left button create new sprite, right button kill sprite""" def __init__(self): self._layer = 9 self.groups = allgroup, stuffgroup pygame.sprite.Sprite.__init__(self, self.groups) self.image = pygame.Surface((100,100)) # created on the fly self.image.set_colorkey((0,0,0)) # black transparent pygame.draw.circle(self.image, (255,0,0), (50,50), 50, 2) # red circle self.image = self.image.convert_alpha() self.rect = self.image.get_rect() self.radius = 50 # for collide check def update(self, seconds): # no need for seconds but the other sprites need it self.rect.center = pygame.mouse.get_pos() class Lifebar(pygame.sprite.Sprite): """shows a bar with the hitpoints of a Bird sprite with a given bossnumber, the Lifebar class can identify the boos (Bird sprite) with this codeline: Bird.birds[bossnumber] """ def __init__(self, bossnumber): self.groups = allgroup, bargroup self.bossnumber = bossnumber self._layer = Bird.birds[self.bossnumber]._layer pygame.sprite.Sprite.__init__(self, self.groups) self.image = pygame.Surface((Bird.birds[self.bossnumber].rect.width,7)) self.image.set_colorkey((0,0,0)) # black transparent pygame.draw.rect(self.image, (0,255,0), (0,0,Bird.birds[self.bossnumber].rect.width,7),1) self.rect = self.image.get_rect() self.oldpercent = 0 def update(self, time): self.percent = Bird.birds[self.bossnumber].hitpoints / Bird.birds[self.bossnumber].hitpointsfull * 1.0 if self.percent != self.oldpercent: pygame.draw.rect(self.image, (0,0,0), (1,1,Bird.birds[self.bossnumber].rect.width-2,5)) # fill black pygame.draw.rect(self.image, (0,255,0), (1,1, int(Bird.birds[self.bossnumber].rect.width * self.percent),5),0) # fill green self.oldpercent = self.percent self.rect.centerx = Bird.birds[self.bossnumber].rect.centerx self.rect.centery = Bird.birds[self.bossnumber].rect.centery - Bird.birds[self.bossnumber].rect.height /2 - 10 #check if boss is still alive if Bird.birds[self.bossnumber].hitpoints < 1: self.kill() # kill the hitbar class Bird(pygame.sprite.Sprite): """a nice little sprite that bounce off walls and other sprites""" image=[] # list of all images birds = {} # a dictionary of all Birds, each Bird has its own number number = 0 waittime = 1.0 # seconds def __init__(self, layer = 4 ): self.groups = birdgroup, allgroup # assign groups self._layer = layer # assign level #self.layer = layer pygame.sprite.Sprite.__init__(self, self.groups ) #call parent class. NEVER FORGET ! #pygame.sprite.Sprite.__init__(self, *args ) #call parent class. NEVER FORGET ! self.pos = [random.randint(50,screen.get_width()-50), random.randint(25,screen.get_height()-25)] self.area = screen.get_rect() self.image = Bird.image[0] self.hitpointsfull = float(100) # maximal hitpoints self.hitpoints = float(100) # actual hitpoints self.rect = self.image.get_rect() self.radius = max(self.rect.width, self.rect.height) / 2.0 self.dx = 0 # wait at the beginning self.dy = 0 self.waittime = Bird.waittime # 1.0 # one second #self.newspeed() self.lifetime = 0.0 self.waiting = True self.rect.center = (-100,-100) # out of visible screen self.cleanstatus() self.catched = False self.crashing = False #--- not necessary: self.number = Bird.number # get my personal Birdnumber Bird.number+= 1 # increase the number for next Bird Bird.birds[self.number] = self # store myself into the Bird dictionary #print "my number %i Bird number %i " % (self.number, Bird.number) Lifebar(self.number) #create a Lifebar for this Bird. # starting implosion of blue fragments for _ in range(8): Fragment(self.pos, True) def newspeed(self): # new birdspeed, but not 0 speedrandom = random.choice([-1,1]) # flip a coin self.dx = random.randint(BIRDSPEEDMIN,BIRDSPEEDMAX) * speedrandom self.dy = random.randint(BIRDSPEEDMIN,BIRDSPEEDMAX) * speedrandom def cleanstatus(self): self.catched = False # set all Bird sprites to not catched self.crashing = False def kill(self): # a shower of red fragments, exploding outward for _ in range(15): Fragment(self.pos) pygame.sprite.Sprite.kill(self) # kill the actual Bird def update(self, seconds): #---make Bird only visible after waiting time self.lifetime += seconds if self.lifetime > (self.waittime) and self.waiting: self.newspeed() self.waiting = False self.rect.centerx = round(self.pos[0],0) self.rect.centery = round(self.pos[1],0) if self.waiting: self.rect.center = (-100,-100) else: # speedcheck # friction make birds slower if abs(self.dx) > BIRDSPEEDMIN and abs(self.dy) > BIRDSPEEDMIN: self.dx *= FRICTION self.dy *= FRICTION # spped limit if abs(self.dx) > BIRDSPEEDMAX: self.dx = BIRDSPEEDMAX * self.dx / self.dx if abs(self.dy) > BIRDSPEEDMAX: self.dy = BIRDSPEEDMAX * self.dy / self.dy # movement self.pos[0] += self.dx * seconds self.pos[1] += self.dy * seconds # -- check if Bird out of screen if not self.area.contains(self.rect): self.crashing = True # change colour later # --- compare self.rect and area.rect if self.pos[0] + self.rect.width/2 > self.area.right: self.pos[0] = self.area.right - self.rect.width/2 if self.pos[0] - self.rect.width/2 < self.area.left: self.pos[0] = self.area.left + self.rect.width/2 if self.pos[1] + self.rect.height/2 > self.area.bottom: self.pos[1] = self.area.bottom - self.rect.height/2 if self.pos[1] - self.rect.height/2 < self.area.top: self.pos[1] = self.area.top + self.rect.height/2 self.newspeed() # calculate a new direction #--- calculate actual image: crasing, catched, both, nothing ? self.image = Bird.image[self.crashing + self.catched*2] #--- calculate new position on screen ----- self.rect.centerx = round(self.pos[0],0) self.rect.centery = round(self.pos[1],0) #--- loose hitpoins if self.crashing: self.hitpoints -=1 #--- check if still alive if self.hitpoints <= 0: self.kill() class Fragment(pygame.sprite.Sprite): """a fragment of an exploding Bird""" gravity = False # fragments fall down ? def __init__(self, pos, bluefrag = False): self._layer = 9 self.groups = allgroup, stuffgroup pygame.sprite.Sprite.__init__(self, self.groups) self.bluefrag = bluefrag self.pos = [0.0,0.0] self.target = pos self.fragmentmaxspeed = BIRDSPEEDMAX * 2 # try out other factors ! if self.bluefrag: # blue frament implodes from screen edge toward Bird self.color = (0,0,random.randint(25,255)) # blue self.side = random.randint(1,4) if self.side == 1: # left side self.pos[0] = 0 self.pos[1] = random.randint(0,screen.get_height()) elif self.side == 2: # top self.pos[0] = random.randint(0,screen.get_width()) self.pos[1] = 0 elif self.side == 3: #right self.pos[0] = screen.get_width() self.pos[1] = random.randint(0,screen.get_height()) else: #bottom self.pos[0] = random.randint(0,screen.get_width()) self.pos[1] = screen.get_height() # calculating flytime for one second.. Bird.waittime should be 1.0 self.dx = (self.target[0] - self.pos[0]) * 1.0 / Bird.waittime self.dy = (self.target[1] - self.pos[1]) * 1.0 / Bird.waittime self.lifetime = Bird.waittime + random.random() * .5 # a bit more livetime after the Bird appears else: # red fragment explodes from the bird toward screen edge self.color = (random.randint(25,255),0,0) # red self.pos[0] = pos[0] self.pos[1] = pos[1] self.dx = random.randint(-self.fragmentmaxspeed,self.fragmentmaxspeed) self.dy = random.randint(-self.fragmentmaxspeed,self.fragmentmaxspeed) self.lifetime = 1 + random.random()*3 # max 3 seconds self.image = pygame.Surface((10,10)) self.image.set_colorkey((0,0,0)) # black transparent pygame.draw.circle(self.image, self.color, (5,5), random.randint(2,5)) self.image = self.image.convert_alpha() self.rect = self.image.get_rect() self.rect.center = self.pos #if you forget this line the sprite sit in the topleft corner self.time = 0.0 def update(self, seconds): self.time += seconds if self.time > self.lifetime: self.kill() self.pos[0] += self.dx * seconds self.pos[1] += self.dy * seconds if Fragment.gravity and not self.bluefrag: self.dy += FORCE_OF_GRAVITY # gravity suck fragments down self.rect.centerx = round(self.pos[0],0) self.rect.centery = round(self.pos[1],0) background = pygame.Surface((screen.get_width(), screen.get_height())) background.fill((255,255,255)) # fill white background.blit(write("press left mouse button to increase Bird's layer"),(50,40)) background.blit(write("press right mouse button to decrease Bird's layer."),(50,65)) background.blit(write("layer of mountains are: -1 (blue), -2 (pink), -3 (red)"),(50,90)) background.blit(write("Press ESC to quit, p to print info at mousepos"), (50,115)) # secret keys: g (gravity), p (print layers) background = background.convert() # jpg can not have transparency screen.blit(background, (0,0)) # blit background on screen (overwriting all) #define sprite groups. Do this before creating sprites blockgroup = pygame.sprite.LayeredUpdates() birdgroup = pygame.sprite.Group() textgroup = pygame.sprite.Group() bargroup = pygame.sprite.Group() stuffgroup = pygame.sprite.Group() mountaingroup = pygame.sprite.Group() # only the allgroup draws the sprite, so i use LayeredUpdates() instead Group() allgroup = pygame.sprite.LayeredUpdates() # more sophisticated, can draw sprites in layers try: # load images into classes (class variable !). if not possible, draw ugly images Bird.image.append(pygame.image.load(os.path.join("data","babytux.png"))) Bird.image.append(pygame.image.load(os.path.join("data","babytux_neg.png"))) except: print("no image files 'babytux.png' and 'babytux_neg.png' in subfolder 'data'") print("therfore drawing ugly sprites instead") image = pygame.Surface((32,36)) image.fill((255,255,255)) pygame.draw.circle(image, (0,0,0), (16,18), 15,2) image.set_colorkey((255,255,255)) Bird.image.append(image) # alternative ugly image image2 = image.copy() pygame.draw.circle(image2, (0,0,255), (16,18), 13,0) Bird.image.append(image2) Bird.image.append(Bird.image[0].copy()) # copy of first image pygame.draw.rect(Bird.image[2], (0,0,255), (0,0,32,36), 1) # blue border Bird.image.append(Bird.image[1].copy()) # copy second image pygame.draw.rect(Bird.image[3], (0,0,255), (0,0,32,36), 1) # blue border Bird.image[0] = Bird.image[0].convert_alpha() Bird.image[1] = Bird.image[1].convert_alpha() Bird.image[2] = Bird.image[2].convert_alpha() Bird.image[3] = Bird.image[3].convert_alpha() try: # ------- load sound ------- cry = pygame.mixer.Sound(os.path.join('data','claws.ogg')) #load sound except: raise(SystemExit, "could not load sound claws.ogg from 'data'") #print"could not load sound file claws.ogg from folder data. no sound, sorry" #create Sprites hunter = BirdCatcher() # display the BirdCatcher and name it "hunter" for x in range(screen.get_width()//100): Block(x) # add more Blocks if you y screen resolution is bigger othergroup = [] # important for good collision detection badcoding = False clock = pygame.time.Clock() # create pygame clock object mainloop = True FPS = 60 # desired max. framerate in frames per second. birdlayer = 4 birdtext = Text("current Bird _layer = %i" % birdlayer) # create Text sprite cooldowntime = 0 #sec # start with some Birds for _ in range(15): Bird(birdlayer) # one single Bird # create the first parallax scrolling mountains Mountain(1) # blue Mountain(2) # pink Mountain(3) # red while mainloop: # ----------------- mainloop ---------------------- milliseconds = clock.tick(FPS) # milliseconds passed since last frame seconds = milliseconds / 1000.0 # seconds passed since last frame for event in pygame.event.get(): if event.type == pygame.QUIT: mainloop = False # pygame window closed by user elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: mainloop = False # user pressed ESC #elif event.key == pygame.K_g: #Fragment.gravity = not Fragment.gravity # toggle gravity class variable elif event.key == pygame.K_p: # get sprites at mouse position, print info print("=========================") print("-----Spritelist---------") spritelist = allgroup.get_sprites_at(pygame.mouse.get_pos()) for sprite in spritelist: print(sprite, "Layer:",allgroup.get_layer_of_sprite(sprite)) print("------------------------") print("toplayer:", allgroup.get_top_layer()) print("bottomlayer:", allgroup.get_bottom_layer()) print("layers;", allgroup.layers()) print("=========================") elif event.key == pygame.K_g: Fragment.gravity = not Fragment.gravity # toggle gravity class variable # change birdlayer on mouseclick if cooldowntime <= 0: # to if pygame.mouse.get_pressed()[0]: if birdlayer < 10: birdlayer += 1 cooldowntime = .5 # seconds cry.play() for bird in birdgroup: allgroup.change_layer(bird, birdlayer) # allgroup draws the sprite for bar in bargroup: allgroup.change_layer(bar, birdlayer) # allgroup draws the sprite for bar in bargroup: allgroup.change_layer(bar, birdlayer) # allgroup draws the sprite if pygame.mouse.get_pressed()[2]: if birdlayer > -4: birdlayer -= 1 cooldowntime = .5 cry.play() for bird in birdgroup: allgroup.change_layer(bird, birdlayer) # allgroup draws the sprite ! for bar in bargroup: allgroup.change_layer(bar, birdlayer) # allgroup draws the sprite else: cooldowntime -= seconds # to avoid speedclicking pygame.display.set_caption("fps: %.2f birds: %i grav: %s" % (clock.get_fps(), len(birdgroup), Fragment.gravity)) birdtext.newmsg("current Bird _layer = %i" % birdlayer) # update text for birdlayer # ------ collision detection for bird in birdgroup: bird.cleanstatus() #pygame.sprite.spritecollide(sprite, group, dokill, collided = None): return Sprite_list crashgroup = pygame.sprite.spritecollide(hunter, birdgroup, False, pygame.sprite.collide_circle) # pygame.sprite.collide_circle works only if one sprite has self.radius # you can do without that argument collided and only the self.rects will be checked for crashbird in crashgroup: crashbird.catched = True # will get a blue border from Bird.update() for bird in birdgroup: # test if a bird collides with another bird # check the Bird.number to make sure the bird is not crashing with himself crashgroup = pygame.sprite.spritecollide(bird, birdgroup, False ) for crashbird in crashgroup: if crashbird.number != bird.number: #different number means different birds bird.crashing = True if not bird.waiting: bird.dx -= crashbird.pos[0] - bird.pos[0] bird.dy -= crashbird.pos[1] - bird.pos[1] # create 10 new Birds if fewer than 11 birds alive if len(birdgroup) < 10: for _ in range(random.randint(1,5)): Bird(birdlayer) # ----------- clear, draw , update, flip ----------------- allgroup.clear(screen, background) allgroup.update(seconds) allgroup.draw(screen) pygame.display.flip() if __name__ == "__main__": game() else: print("i was imported by", __name__)
import pygame, sys from pygame.locals import * # initialize all imported pygame modules pygame.init() # pygame.display.set_mode(resolution=(0,0),flags=0, depth=0) # initialize window surface = pygame.display.set_mode((400,300)) # set title pygame.display.set_caption('Hello World') # run game loop while True: for event in pygame.event.get(): # get events from queue if event.type == quit: pygame.quit(); sys.exit() pygame.display.update() "transparent Colors" # to draw using transparent colors, create a Surface object with convert_alpha()method # anotherSurface = surface.convert_alpha() "pygame.Color object" # pygame.Color(r,g,b,alpha) # pygame.Color(name) e.g. pygame.Color('black') # pygame.color.THECOLORS "rect objects" # x,y,w,h # left,top,width,height # rect = pygame.Rect(x,y,w,h) # rect = pygame.Rect(left,top,width,height) # rect = pygame.Rect((left,top),(width,height)) # right = left + width = x + w # bottom = top + height = y + h # rect.size : (w,h) # rect.topleft : (x,y) # rect.bottomright : (right,bottom)
# 20.8 Adding a Method to a Class Instance at Runtime def add_method_to_objects_class(obj, method, name=None): if name is None: name = method.func_name class NewClass(obj.__class__): pass setattr(NewClass, name, method) obj.__class__ = NewClass import inspect def _rich_str(self): pieces = list() for name,value in inspect.getmembers(self): # do not display specials # if name.startswith('__'): continue # print 'name,value : %s, %s' %(name, value) # do not display the object's own methods # if inspect.ismethod(value) and value.im_self is self: continue pieces.append( name.ljust(15) + '\t' + str(value) +'\n') # pieces.extend( (name.ljust(15),'\t',str(value),'\n')) return ''.join(pieces) def set_rich_str(obj, on=True): def isrich(): attr = getattr(obj.__class__.__str__, 'im_func',None) # print obj.__class__.__str__ print 'attr: ',attr return getattr(obj.__class__.__str__, 'im_func',None) is _rich_str if on: # if not isrich(): add_method_to_objects_class(obj, _rich_str, '__str__') else: if not isrich(): return bases = obj.__class__.__bases__ assert len(bases) == 1 obj.__class__ = bases[0] assert not isrich() if __name__ == '__main__': class Foo(object): def __init__(self,x=23,y=42): self.x,self.y = x,y def show(self): self.total = self.x + self.y print '*'*80 f = Foo(); set_rich_str(f); print f print '*'*80 g = Foo(); set_rich_str(g,False); print g
class Box: def __init__(self,*arg): print arg, type(arg) print arg[0] print len(arg) if type(arg[0]) == tuple: print 'tuple arg:',arg self.x,self.y = arg[0] else: print 'arg:',arg self.x, self.y = arg def __repr__(self): return '(%s,%s)' %(self.x,self.y) if __name__ == '__main__': tu = 2,3 boxt = Box(tu) print boxt box = Box(0,1) print box
def A(func): def wrapper1(*args): print 'A=>{}{}'.format(func,str(args) ) val = func(*args) return val return wrapper1 def B(func): # func = <function wrapper1> def wrapper2(*args): print 'B=>{}{}'.format(func,str(args) ) val = func(*args) return val return wrapper2 @B @A def f(*args): print 'calling original f{}'.format(args) return f(1,2,3) print'-'*40 def g(*args): print 'calling original g{}'.format(args) return g = B(A(g)) g(1,2,3)
''' 004 alphademo.py colorkey and alpha-value ''' import pygame,os white = pygame.Color('white') # image.set_alpha(alpha) # if you have a pygame surface WITHOUT IN-BUILTIN TRANSPARENCY such as an .JPG image # you can set an alpha-value(transparency) for the whole surface with set_alpha def get_alpha_surface(surf,alpha=128,R=128,G=128,B=128,mode=pygame.BLEND_RGBA_MULT): # returns a copy of a surface object with user defined values from R,G,B and Alpha # using this blit mode, you can make an image all blue, red or green by setting # the Per-Pixel-Alpha values for the corresponding color alphasurf = pygame.Surface( surf.get_size(), pygame.SRCALPHA,32 ) alphasurf.fill((R,G,B,alpha)) alphasurf.blit(surf,(0,0),surf.get_rect(),mode) return alphasurf def bounce(value,direction,bouncing=True,valuemin=0,valuemax=255): # boucing a value like alpha or color between valuemin and valuemax # when bouncing, direction(usually -1 or 1) is inverted when reaching valuemin or max value += direction # increase or decrease value by direction if value <= valuemin: value = valuemin if bouncing: direction *= -1 elif value >=valuemax: value = valuemax if bouncing: direction *= -1 return value, direction def write(msg = 'pygame is cool', size=24, color = white): textfont = pygame.font.SysFont('None',size) textsurf = textfont.render(msg,True,color).convert_alpha() return textsurf def alphademo(width=800,height=600): pygame.init() screen = pygame.display.set_mode((width,height)) background = pygame.Surface( screen.get_size() ).convert() #background.fill(white) venus = pygame.image.load(os.path.join("data","800px-La_naissance_de_Venus.jpg")).convert() # transform venus and blit on background in one go pygame.transform.scale(venus,(width,height),background) # -------- png image with convert_alpha() ------------ # .png and .gif graphics can have transparency. pngMonster = pygame.image.load(os.path.join("data", "colormonster.png")).convert_alpha() pngMonster0 = pngMonster.copy() pngMonster3 = pngMonster.copy() # for per-pixel alpha # --------- jpg image --------------------------------- # using .convert() at an .jpg is the same as a .jpg # => no transparency jpgMonster = pygame.image.load(os.path.join("data","colormonster.jpg")).convert() jpgMonster0 = jpgMonster.copy() jpgMonster1 = jpgMonster.copy() # to demonstrate colorkey jpgMonster1.set_colorkey(white) # make white transparent jpgMonster1.convert_alpha() jpgMonster2 = jpgMonster.copy() # for surface alpha jpgMonster3 = jpgMonster.copy() # for per-pixel alpha #--------- text surfaces ------------------------------- png0text = write('png has alpha') png3text = write('png with pixel-alpha') jpg0text = write('jpg no alpha') jpg1text = write('jpg with colorkey') jpg2text = write('jpg with surface alpha') jpg3text = write('jpg with pixel-alpha') # -------- for bitmap-alpha ---------------------------- alpha = 128 direction = 1 # change of alpha # -------- for per-pixel alpha ------------------------- R,G,B,A = 255,255,255,255 modeNr = 7 # index 7, int-value 8, name ='BLEND_RGB_MULT', usage = pygame.BLEND_RGB_MULT paper = pygame.Surface( (400,100) ) # background for instructions # paper.fill(black) paper.set_alpha(128) # half transparent modelist = [ 'BLEND_ADD', 'BLEND_SUB', 'BLEND_MULT', 'BLEND_MIN', 'BLEND_MAX', 'BLEND_RGBA_ADD', 'BLEND_RGBA_SUB', 'BLEND_RGBA_MULT', 'BLEND_RGBA_MIN', 'BLEND_RGBA_MAX' ] # ------ mainloop ------- clock = pygame.time.Clock() mainloop = True effects = False while mainloop: clock.tick(30) screen.blit(background,(0,0)) # draw background every frame pygame.display.set_caption("insert/del=red:%i, home/end=green:%i, pgup/pgdwn=blue:%i, +/-=pixalpha:%i press ESC" % ( R, G, B, A)) # event handler for e in pygame.event.get(): if e.type == pygame.QUIT or \ e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE: mainloop = False if e.type == pygame.KEYDOWN: # press and release key if e.key == pygame.K_RETURN or e.key == pygame.K_KP_ENTER: # modeNr += 1 # if modeNr > 9: modeNr = 0 # cycle throught 0~9 modeNr = ( modeNr + 1) % len(modelist) # by yipyip mode = pygame.constants.__dict__[modelist[modeNr]] # ---------- keyb is pressed ? ------------------- dR,dG,dB,dA = 0,0,0,0 # set changin to 0 for Red,Green,Blue,pixel-Alpha pressedkeys = pygame.key.get_pressed() if pressedkeys[pygame.K_PAGEUP]: dB = +1 # blue Up if pressedkeys[pygame.K_PAGEDOWN]: dB = -1 # blue Down if pressedkeys[pygame.K_HOME]: dG = +1 # Green Up if pressedkeys[pygame.K_END]: dG = -1 # Green Down if pressedkeys[pygame.K_INSERT]: dR = +1 # Red Up if pressedkeys[pygame.K_DELETE]: dR = -1 # Red Down if pressedkeys[pygame.K_KP_PLUS]: dA = +1 # Alpah Up if pressedkeys[pygame.K_KP_MINUS]: dA = -1 # Alpah Down # --------- change color and alpha values ----------- alpha,direction = bounce(alpha, direction) # change alpah R,dR = bounce(R,dR,False) # red for per-pixel G,dG = bounce(G,dG,False) # green for per-pixel B,dB = bounce(B,dB,False) # blue for per-pixel A,dA = bounce(A,dA,False) # alpah for per-pixel # --------- blit jpgMonster0 as it is, no alpha at all ---------- screen.blit(jpgMonster0,(0,300)) screen.blit(jpg0text,(0,550)) # --------- blit jpgMonster1 with the colorkey set to white ------- screen.blit(jpgMonster1,(200,300)) screen.blit(jpg1text,(200,550)) # --------- blit jpgMonster2 with alpha for whole surface --------- jpgMonster2.set_alpha(alpha) # alpha for whole surface screen.blit(jpgMonster2,(400,300)) screen.blit(jpg2text,(400,550)) screen.blit( write('surface-alpha: %i' %alpha), (400,570) ) # --------- blit jpgMonster3 with per-pixel alpha ----------------- tmp = get_alpha_surface( jpgMonster3, A,R,G,B, mode) # get current alpha screen.blit(tmp,(600,300)) screen.blit(jpg3text,(600,550)) # --------- blit pngMonster0 as it is, with transparency from image screen.blit( pngMonster0, (0,0) ) screen.blit( png0text,(0,200)) # -------- blit pngMonster1 with colorkey set to black ----------- # *** png already has alpha, does not need color key *** # ------- blit pngMonster2 with alpha for whole surface ---------- # *** surface-alpha does not work if surface(png) already has alpah *** # ------- blit pngMoster3 with per-pixel alpha -------------------- tmp = get_alpha_surface(pngMonster3, A, R, G, B, mode) # get current alpha screen.blit(tmp, (600,10)) screen.blit(png3text, (600,200)) # ---- instructions ---- screen.blit(paper, (188,150)) # semi-transparent background for instructions screen.blit(write("press [INS] / [DEL] to change red value: %i" % R,24, (255,255,255)),(190,150)) screen.blit(write("press [HOME] / [END] to change green value: %i" % G),(190,170)) screen.blit(write("press [PgUp] / [PgDwn] to chgange blue value: %i"% B), (190, 190)) screen.blit(write("press [Enter] for mode: %i (%s)" % (mode, modelist[modeNr])), (190,230)) screen.blit(write("press [+] / [-] (Keypad) to chgange alpha value: %i"% A), (190, 210)) # ------ next frame -------- pygame.display.flip() # flip the screen 30 times a second if __name__ == "__main__": alphademo()
""" Example using OpenPyXL to create an Excel worksheet """ from openpyxl import Workbook import random # Create an Excel workbook wb = Workbook() # Grab the active worksheet ws = wb.active # Data can be assigned directly to cells ws['A1'] = "This is a test" # Rows can also be appended for i in range(200): ws.append([random.randrange(1000)]) # Save the file wb.save("sample")
# 016 layers.py # pygame sprites with different layers and parallax scrolling # change the sprite layer by clicking with left or right mouse button # the birdsprites will apear before or behind the blocks # POINT ON a sprite and press 'p' to print out more information about that sprite from constants016 import * class Text(pygame.sprite.Sprite): def __init__(self,msg): self.groups = textgroup, allgroup self._layer = 99 pygame.sprite.Sprite.__init__(self, self.groups) self.newMsg(msg) def update(self,time): pass def newMsg(self, msg ='i have nothing to say'): self.image = write(msg) self.rect = self.image.get_rect() self.rect.center = screenwidth/2, 10 class Mountain(pygame.sprite.Sprite): # generate a mountain sprite for the background to demonstrate parallax scrolling # like in the classic 'moonbuggy' game. Mountains slide from right to left # self.centerx, self.centery => self.rect.center def __init__(self,atype): # assign self._layer BEFORE calling pygame.sprite.Sprite.__init__ self.type = atype self.set_layer() self.groups = mountaingroup, allgroup pygame.sprite.Sprite.__init__(self,self.groups) self.dy = 0.0 width = 1.5 * 100 * self.type # 1.5% height = screenheight/2.0 + 50.0*(self.type-1) self.image = pygame.Surface( (width,height)) #self.image.fill(green) self.image.set_colorkey(black) pygame.draw.polygon(self.image, self.color, ( (0,height), (0,height-10*self.type), (width/2, int( random.random() * height/2.0 ) ), (width,height), (9,height) ), 0) self.image.convert_alpha() self.rect = self.image.get_rect() # x,y -> self.image.get_rect().center self.centerx = screenwidth + self.rect.width/2.0 self.centery = screenheight - self.rect.height/2.0 # SET center = self.center = self.centerx,self.centery self.rect.center = self.center self.insideScreen = False def set_layer(self): if self.type == 1: self._layer = -1 # blue Mountain self.dx = -100.0 self.color = blue elif self.type == 2: # pink Mountain self._layer = -2 self.dx = -75.0 self.color = pink else: self._layer = -3 # red Mountain self.dx = -35.0 self.color = red @property def center(self): return self.centerx, self.centery def move(self,time): self.centerx += self.dx * time self.centery += self.dy * time # set center self.rect.center = self.center def isInsideScreen(self): return self.rect.centerx < screenwidth def update(self,time): self.move(time) # kill mountains too far to the left if self.rect.right < 0: # right = self.rect.centerx + self.rect.width/2 self.kill() # create new mountains if necessary if self.insideScreen: return # coming from outside Screen if self.isInsideScreen(): # check if self.rect.centerx is Inside screen Mountain(self.type) # create a new Mountain coming from the right side self.insideScreen = True # no more than one Moutain at a time class BirdCatcher(pygame.sprite.Sprite): # circle around the mouse pointer. # LEFT button create new sprite, RIGHT button kill sprite def __init__(self): self._layer = 9 self.groups = catchergroup, allgroup pygame.sprite.Sprite.__init__(self,self.groups) self.image = pygame.Surface( (100,100) ) self.image.set_colorkey(black) self.rect = self.image.get_rect() self.radius = 50 pygame.draw.circle(self.image,red,(self.radius,self.radius), self.radius, 2) def update(self,seconds): self.rect.center = pygame.mouse.get_pos() #--- define sprite Group before creating sprites #blockgroup = pygame.sprite.LayeredUpdates() textgroup = pygame.sprite.Group() catchergroup = pygame.sprite.Group() mountaingroup = pygame.sprite.Group() # only allgroup draws the sprite, so use LayeredUpdates() instead Group() allgroup = pygame.sprite.LayeredUpdates() # can draw sprites in layers ''' >>> When using 'pygame.sprite.Layeredupdate()' instead of 'pygame.sprite.Group()', >>> you can give each sprite a variable 'self._layer' as well as a variable groups >>> to influence 'the drawing order of the sprite'. The sprite groups must exist (be defined in the mainloop) before you can assign sprites to the groups. >>> Inside the class, you must assign groups and '_layer' >>> BEFORE you call 'pygame.sprite.Sprite.__init__(self, *groups)' ''' def main(): # draw background bgsurf = pygame.Surface( screensize ) bgsurf.fill(white) bgsurf.blit(write("press left mouse button to increase Bird's layer"),(50,40)) bgsurf.blit(write("press right mouse button to decrease Bird's layer."),(50,65)) bgsurf.blit(write("layer of mountains are: -1 (blue), -2 (pink), -3 (red)"),(50,90)) bgsurf.blit(write("Press ESC to quit, p to print info at mousepos"), (50,115)) bgsurf = bgsurf.convert_alpha() screen.blit(bgsurf,(0,0) ) #--- load sound crysound = pygame.mixer.Sound( os.path.join('data','claws.ogg') ) #--------- create Sprites hunter = BirdCatcher() # create the first parallax scrolling mountains Mountain(1) # blue Mountain(2) # pink Mountain(3) # red mainloop = True while mainloop: seconds = clock.tick(fps)/1000.0 for e in pygame.event.get(): if e.type == pygame.QUIT or e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE: mainloop = False if e.type == pygame.KEYDOWN: if e.key == pygame.K_p: printSpriteList() if e.key == pygame.K_g: # toggle gravity pass #printBirds() #Fragment.gravity = not Fragment.gravity # pygame.sprite.spritecollide(sprite,group,dokill,collide=None): return Sprite list # pygame.sprite.collide_circle works ONLY IF sprite has self.radius # -------- clean, draw, update, flip ----------------- allgroup.clear(screen, bgsurf) allgroup.update(seconds) allgroup.draw(screen) pygame.display.flip() def printSpriteList(): print '===========================' print '------- Sprite list -------' spritelist = allgroup.get_sprites_at(pygame.mouse.get_pos()) for sprite in spritelist: print sprite, 'Layer:',allgroup.get_layer_of_sprite(sprite) print '---------------------------' print 'top layer:',allgroup.get_top_layer() print 'bottome layer:', allgroup.get_bottom_layer() print 'layers:',allgroup.layers() print '===========================' if __name__ == '__main__': main()
"""Given a string, find the length of the longest substring in it with no more than K distinct characters. You can assume that K is less than or equal to the length of the given string. Example 1: Input: String="araaci", K=2 Output: 4 Explanation: The longest substring with no more than '2' distinct characters is "araa". Example 2: Input: String="araaci", K=1 Output: 2 Explanation: The longest substring with no more than '1' distinct characters is "aa". Input: String="cbbebi", K=3 Output: 5 Explanation: The longest substrings with no more than '3' distinct characters are "cbbeb" & "bbebi". """ def longest_substring_distinct_characters(input_string=[], K: int = 1): window_chars = {} window_start = 0 max_len = -float("inf") for window_end in range(len(input_string)): cur_char = input_string[window_end] if cur_char not in window_chars: window_chars[cur_char] = 0 window_chars[cur_char] += 1 while len(window_chars) > K: del_char = input_string[window_start] window_chars[del_char] -= 1 if window_chars[del_char] == 0: del window_chars[del_char] window_start += 1 max_len = max(max_len, window_end - window_start + 1) return max_len def main(): print(longest_substring_distinct_characters(input_string="araaci", K=2)) print(longest_substring_distinct_characters(input_string="araaci", K=1)) print(longest_substring_distinct_characters(input_string="cbbebi", K=3)) if __name__ == "__main__": main()
import random; def memoryQuickSort(arr): n = len(arr) if(n <= 1): return arr pivotInd = random.randint(0,n-1) pivot = arr[pivotInd] l = 0 r = n - 1 newArray = [0] * n pivotTimes = 0 for i in range(n): if(arr[i] < pivot): newArray[l] = arr[i] l += 1 elif(arr[i] > pivot): newArray[r] = arr[i] r -= 1 else: pivotTimes += 1 for i in range(pivotTimes): newArray[i + l] = pivot sortedArray = memoryQuickSort(newArray[:l]) + newArray[l:r+1] + memoryQuickSort(newArray[r+1:]) return sortedArray def altQuickSort(arr, l_ref, r_ref): if(r_ref - l_ref <= 1): return arr pivotInd = random.randint(l_ref, r_ref - 1) arr[l_ref], arr[pivotInd] = arr[pivotInd], arr[l_ref] pivot = arr[l_ref] l = l_ref + 1 i = l_ref + 1 r = r_ref - 1 for j in range(l_ref + 1, r_ref): if(arr[i] < pivot): arr[i], arr[l] = arr[l], arr[i] l += 1 i += 1 elif(arr[i] > pivot): arr[i], arr[r] = arr[r], arr[i] r -= 1 else: i += 1 arr[l_ref], arr[l-1] = arr[l-1], arr[l_ref] altQuickSort(arr, l_ref, l-1) altQuickSort(arr, r, r_ref) def quickSort(arr, l_ref, r_ref): if(r_ref - l_ref <= 1): return arr pivotInd = random.randint(l_ref, r_ref - 1) arr[l_ref], arr[pivotInd] = arr[pivotInd], arr[l_ref] pivot = arr[l_ref] l = l_ref + 1 r = l_ref + 1 for j in range(l_ref + 1, r_ref): if(arr[j] < pivot): arr[j], arr[l] = arr[l], arr[j] if(r > l): arr[r], arr[j] = arr[j], arr[r] l += 1 r += 1 elif(arr[j] == pivot): arr[j], arr[r] = arr[r], arr[j] r += 1 arr[l_ref], arr[l-1] = arr[l-1], arr[l_ref] quickSort(arr, l_ref, l-1) quickSort(arr, r, r_ref) arr = [random.randint(1, 20) for _ in range(20)] altQuickSort(arr, 0, len(arr)) print(arr) arr2 = [random.randint(1, 20) for _ in range(20)] quickSort(arr2, 0, len(arr2)) print(arr2) #print(memoryQuickSort(arr)) #print(altQuickSort(arr))
import random def mergeSort(arr): if(len(arr) == 1): return arr arr1 = mergeSort(arr[:len(arr)//2]) arr2 = mergeSort(arr[len(arr)//2:]) ind1 = 0 ind2 = 0 newArray = [] for i in range(len(arr)): if(ind2 >= len(arr2) or (ind1 < len(arr1) and arr1[ind1] < arr2[ind2])): newArray.append(arr1[ind1]) ind1 += 1 else: newArray.append(arr2[ind2]) ind2 += 1 return newArray def choosePivot(arr): c = [] i = 0 auxArr = [] for num in arr: auxArr.append(num) i += 1 if(i == 5): auxArr = mergeSort(auxArr) c.append(auxArr[i//2]) i = 0 auxArr = [] if(i > 0): auxArr = mergeSort(auxArr) c.append(auxArr[i//2]) pivot = DSelection(c, len(c)//2) return pivot def DSelection(arr, pos): n = len(arr) if(pos > n): return -1 if(n == 1): return arr[0] pivot = choosePivot(arr) l = 0 r = 0 for j in range(n): if(arr[j] < pivot): arr[j], arr[l] = arr[l], arr[j] if(r > l): arr[r], arr[j] = arr[j], arr[r] l += 1 r += 1 elif(arr[j] == pivot): arr[j], arr[r] = arr[r], arr[j] r += 1 if(l <= pos - 1 and r > pos - 1): return arr[l] elif(l > pos - 1): return DSelection(arr[:l], pos) else: return DSelection(arr[r:], pos - r) arr = [random.randint(1, 20) for _ in range(20)] pos = random.randint(1, len(arr)) sortedArray = mergeSort(arr) print(sortedArray[pos-1]) print(DSelection(arr, pos))
def gaussian_kernel(size, sigma=1): ''' Calculates and Returns Gaussian kernel. Parameters: size (int): size of kernel. sigma(float): standard deviation of gaussian kernel Returns: gaussian: A 2d array shows gaussian kernel ''' #Writer your code here gaussian = None gaussian = np.zeros((size,size), np.float) ####### your code ######## coe=1/(2*((np.pi)*(sigma**2))) co2_std=2*(sigma**2) for i in range(size): for j in range(size): gaussian[i,j]+=(coe*np.exp((-(i**2+j**2)/co2_std))) return gaussian def sobel_filters(image): ''' finds the magnitude and orientation of the image using Sobel kernels. Parameters: image (numpy.ndarray): The input image. Returns: (magnitude, theta): A tuple consists of magnitude and orientation of the image gradients. ''' #Writer your code here ky = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], np.float) kx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.float) Ix = cv2.filter2D(np.float32(image),-1,np.float32(kx)) Iy = cv2.filter2D(np.float32(image),-1,np.float32(ky)) magnitude = np.hypot(Ix, Iy) #Result is equivalent to Equivalent to sqrt(x1**2 + x2**2), element-wise magnitude = magnitude / magnitude.max() * 255 theta = np.arctan2(Iy, Ix) return magnitude, theta def non_max_suppression(image, theta): ''' Applies Non-Maximum Suppression. Parameters: image (numpy.ndarray): The input image. theta (numpy.ndarray): The orientation of the image gradients. Returns: Z(numpy.ndarray): Output of Non-Maximum Suppression algorithm. ''' #Writer your code here M, N = image.shape Z = np.zeros((M,N), np.float) angle = theta * 180. / np.pi angle[angle < 0] += 180 ## becuse of that -180,180 +180 to become between 0,360 for i in range(1,M-1): for j in range(1,N-1): t1=255 t2 = 255 if (0 <= angle[i,j] < 22.5): t1 = image[i, j+1] t2 = image[i, j-1] elif (157.5 <= angle[i,j] <= 180): t1 = image[i, j+1] t2 = image[i, j-1] elif (22.5 <= angle[i,j] < 67.5): t1 = image[i+1, j-1] t2 = image[i-1, j+1] elif (67.5 <= angle[i,j] < 112.5): t1 = image[i+1, j] t2 = image[i-1, j] elif (112.5 <= angle[i,j] < 157.5): t1 = image[i-1, j-1] t2 = image[i+1, j+1] if (image[i,j] >= t1) and (image[i,j] >= t2): Z[i,j] = image[i,j] else: Z[i,j] = 0 return Z #Non-Max Suppression step will help us mitigate the thick ones. def hysteresis_threshold(image, lowThreshold=38, highThreshold=70): ''' Finds strong, weak, and non-relevant pixels. Parameters: image (numpy.ndarray): The input image. lowThreshold(int): Low Threshold. highThreshold(int): High Threshold. Returns: result(numpy.ndarray): Output of applying hysteresis threshold. ''' #Writer your code here M, N = image.shape result = np.zeros((M,N), dtype=np.int32) weak = np.int32(20) strong = np.int32(255) higher1, higher2 = np.where(image >= highThreshold) middle1, middle2 = np.where((image <= highThreshold) & (image >= lowThreshold)) result[higher1, higher2] = strong result[middle1, middle2] = weak final=result.copy() for i in range(1, M-1): for j in range(1, N-1): if (result[i,j] == weak): if (result[i+1, j-1] == strong): final[i, j] = strong elif (result[i+1, j] == strong): final[i, j] = strong elif (result[i+1, j+1] == strong): final[i, j] = strong elif (result[i, j-1] == strong): final[i, j] = strong elif (result[i, j+1] == strong): final[i, j] = strong elif (result[i-1, j-1] == strong): final[i, j] = strong elif (result[i-1, j] == strong): final[i, j] = strong elif (result[i-1, j+1] == strong): final[i, j] = strong else: final[i, j] = 0 return result,final def canny(image, kernel_size = 3, sigma = 1, lowtreshold = 38, hightreshold =70): ''' Applys Canny edge detector on the input image. Parameters: image (numpy.ndarray): The input image. size (int): size of kernel. sigma(float): standard deviation of gaussian kernel. lowThreshold(int): Low Threshold. highThreshold(int): High Threshold. Returns: img_smoothed(numpy.ndarray): Result of applying the Gaussian kernel on the input image. gradient(numpy.ndarray): The image of the gradients. nonMaxImg(numpy.ndarray): Output of Non-Maximum Suppression algorithm. thresholdImg(numpy.ndarray): Output of applying hysteresis threshold. img_final(numpy.ndarray): Result of canny edge detector. The image of detected edges. ''' kernel=gaussian_kernel(kernel_size,sigma) img_smoothed = cv2.filter2D(np.float32(image),-1,np.float32(kernel)) gradient,theta = sobel_filters(image) nonMaxImg = non_max_suppression(gradient,theta) thresholdImg,img_final = hysteresis_threshold(nonMaxImg,lowtreshold,hightreshold) return img_smoothed, gradient, nonMaxImg, thresholdImg, img_final
def classify_leaf(image): ''' Classifies the input image to only two classes of leaves. Parameters: image (numpy.ndarray): The input image. Returns: int: The class of the image. 1 == apple, 0 == linden ''' leaf_type = 0 #Write your code here img_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) blur = cv2.GaussianBlur(img_gray,(3,3),0) ret, thresh = cv2.threshold(blur, 220, 255, 0) contours, _ = cv2.findContours(thresh,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE ) inx=find_greater_contour(contours) (x,y), (MA,ma), angle = cv2.fitEllipse(contours[inx]) a=ma / 2 b=MA /2 ecc=np.sqrt(a**2 - b**2) / a area = cv2.contourArea(contours[inx]) hull = cv2.convexHull(contours[inx]) hull_area = cv2.contourArea(hull) solidity = float(area)/hull_area x,y,w,h = cv2.boundingRect(contours[inx]) aspect_ratio = float(w)/h area = cv2.contourArea(contours[inx]) x,y,w,h = cv2.boundingRect(contours[inx]) rect_area = w*h extent = float(area)/rect_area if solidity == 1: if aspect_ratio <0.7 and ecc <0.9: if extent > 0.9959: return 0 if ecc <0.5: return 0 else: return 1 return leaf_type
# Copyright (C) 2020 Logan Bier. All rights reserved. # project details # a time-bound distributed currency # that replaces chain exponential energy usage # with a finite energy distributed ledger # made up of a randomly generated set of values # in a range of natural numbers # conceptually, energy is conserved by awarding the # winning guess the Nth "coin" in a stepwise registry # of the vector of secret randomly generated values # with the Unix Time as a standard of linear computation # given a finite cycle time to guess the registry value, # the winning computer is the first one which guesses # correctly in a normalized time range across wallets import random import time class main(): def __init__(self): # 10_25_20 the following is a prototype for a much larger system self.secret_registry = [] self.max_coin_length = 10000000 # ten million self.random_number_max = 10000000 # ten million self.time_amount = 0.001 # 1 millisecond compute slice # ten million * ten million requires ~500 megabytes to store # these values fully express "Ten Million Coin" for x in range(0, self.max_coin_length): self.secret_registry.append(random.randint(1, self.random_number_max)) self.ledger = [] def get_ledger_current_size(input_ledger): return len(self.ledger) # spawn a number of simulated Ten Million Coin "miners" def gen_miner_1(): # take the current length of the distributed ledger # as input on the secret registry to determine the # current target value of the process # get a unique miner ID unique_miner_id = 29304234 var_1 = get_ledger_current_size(self.ledger) guess_this_now = self.secret_registry[var_1] current_guess_var = random.randint(1, self.random_number_max) print('Miner 1 Current Guess: ' + str(current_guess_var)) if current_guess_var == guess_this_now: winning_information = [time.time(), unique_miner_id, var_1, guess_this_now] self.ledger.append(winning_information) file_1 = open('ten_million_ledger.txt', 'w') file_1.write(str(self.ledger)) file_1.close() def gen_miner_2(): # take the current length of the distributed ledger # as input on the secret registry to determine the # current target value of the process # get a unique miner ID unique_miner_id = 12954231 var_1 = get_ledger_current_size(self.ledger) guess_this_now = self.secret_registry[var_1] current_guess_var = random.randint(1, self.random_number_max) print('Miner 2 Current Guess: ' + str(current_guess_var)) if current_guess_var == guess_this_now: winning_information = [time.time(), unique_miner_id, var_1, guess_this_now] self.ledger.append(winning_information) file_1 = open('ten_million_ledger.txt', 'w') file_1.write(str(self.ledger)) file_1.close() while len(self.ledger) < self.max_coin_length: time.sleep(self.time_amount) print(time.time()) gen_miner_1() gen_miner_2() print('Current Length of Ledger: ' + str(len(self.ledger))) print('Current Distributed Ledger: ' + str(self.ledger)) main()
def is_divisable(number): if number%20!=0: return False elif number%19!=0: return False elif number%18!=0: return False elif number%17!=0: return False elif number%16!=0: return False elif number%15!=0: return False elif number%14!=0: return False elif number%13!=0: return False elif number%12!=0: return False elif number%11!=0: return False elif number%10!=0: return False elif number%9!=0: return False elif number%7!=0: return False elif number%6!=0: return False elif number%5!=0: return False elif number%3!=0: return False else: return True for i in range(1,100000000000000000,1): if is_divisable(i): print (i) break
import math print('==== Seno, Cosseno e Tangente ====') angulo = math.radians(int(input('Digte o valor de um ângulo qualquer: '))) print(f'Para o ângulo de {math.degrees(angulo):.1f}°, o seno é {math.sin(angulo):.2f}, cosseno {math.cos(angulo):.2f} e a tangente {math.tan(angulo):.2f}.')
print('\033[32;1m=== Analisando nome ===\033[m') nome = str(input('\033[31mDigite o seu nome completo: ')).strip() print(f'\033[36mO seu nome com letras maiúsculas: \033[34;1m{nome.upper()}\033[m') print(f'\033[36mO seu nome com letras minúsculas: \033[34;1m{nome.lower()}\033[m') print(f'\033[36mTotal de letras: \033[34;1m{len(nome.replace(" ", "" ))}\033[m') PriN = nome.split() print(f'\033[36mTotal de letras no primeiro nome: \033[34;1m{(len(PriN[0]))}\033[m')
print('\033[32;1m==== Conversão de metros em centimetros e milimetros ====\033[m') m = float(input('\033[34mDigite o valor em metros: ')) cent = m*100 mili = m*1000 print(f'\033[35m{m} metros em centimetros é \033[36m{cent}cm') print(f'\033[35m{m} metros em milimetros é \033[36m{mili}mm')
print('\033[32;1m=== Aumento de Salário ===\033[m') Sal = float(input('\033[31mQual o seu salário? ')) if Sal >= 1250.00: Sal = Sal + Sal * (10 / 100) print(f'\033[36mO seu novo salário é de \033[34;1m{Sal}\033[m') else: Sal = Sal + Sal * (15 / 100) print(f'\033[36mO seu novo salário é de \033[34;1m{Sal}\033[m')
from random import randint print('\033[32;1m=== Jogo da adivinhação ===\033[m') n = int(input('\033[31mAdivinhe o número entre 0 e 5 que eu estou pensando: ')) r = randint(0,5) if n == r: print('\033[36mSortudo, você acertou o número que eu estava pensando, PARABÉNS!') else: print(f'\033[36mSinto muito, você errou, o número que eu tava pensando era \033[34;1m{r}')
print('\033[32;1m==== Conversor de Temperatura ====\033[m') C = float(input('\033[31mInforme a temperatura em °C: ')) F = C * 1.8 + 32 print(f'\033[36mA conversão de {C:.1f}°C para Fahrenheit é \033[34;1m{F:.1f}°F')
print('\033[32;1m==== Antecessor e Sucessor de um número ====\033[m') n = float(input('\033[31mDigite um número: \033[m')) print(f'\033[35mO antecessor de \033[34;1m{n}\033[35m é \033[34;1m{n-1}\033[35m e o sucessor é \033[34;1m{n+1}')
# We are given an array containing ‘n’ objects. Each object, when created, was assigned a unique number from 1 to ‘n’ based on their creation sequence. This means that the object with sequence number ‘3’ was created just before the object with sequence number ‘4’. # Write a function to sort the objects in-place on their creation sequence number in O(n)O(n) and without any extra space. For simplicity, let’s assume we are passed an integer array containing only the sequence numbers, though each number is actually an object. # Example 1: # Input: [3, 1, 5, 4, 2] # Output: [1, 2, 3, 4, 5] # Example 2: # Input: [2, 6, 4, 3, 1, 5] # Output: [1, 2, 3, 4, 5, 6] # Example 3: # Input: [1, 5, 6, 4, 3, 2] # Output: [1, 2, 3, 4, 5, 6] def swap(i, j, array): array[i], array[j] = array[j], array[i] def cyclicSort(array): i = 0 while i < (len(array)): if array[i] == i +1: i += 1 else: swap(i, array[i] - 1, array) return array if __name__ == '__main__': array1 = [3, 1, 5, 4, 2] array2 = [2, 6, 4, 3, 1, 5] array3 = [1, 5, 6, 4, 3, 2] out1 = [1, 2, 3, 4, 5] out23 = [1, 2, 3, 4, 5, 6] r1 = cyclicSort(array1) r2 = cyclicSort(array2) r3 = cyclicSort(array3) print(r1, r2, r3) assert out1 == r1 assert out23 == r2 assert out23 == r3
# Minimum Window Sort (medium) # # Given an array, find the length of the smallest subarray in it which when sorted will sort the whole array. # Example 1: # Input: [1, 2, 5, 3, 7, 10, 9, 12] # Output: 5 # Explanation: We need to sort only the subarray [5, 3, 7, 10, 9] to make the whole array sorted # Example 2: # Input: [1, 3, 2, 0, -1, 7, 10] # Output: 5 # Explanation: We need to sort only the subarray [1, 3, 2, 0, -1] to make the whole array sorted # Example 3: # Input: [1, 2, 3] # Output: 0 # Explanation: The array is already sorted # Example 4: # Input: [3, 2, 1] # Output: 3 # Explanation: The whole array needs to be sorted. import math def checkSorted(nums): low = 0 high = len(nums) - 1 for i in range(1, len(nums) - 1): if nums[i] > nums[i - 1]: low += 1 else: break for i in range(len(nums) - 1, 0, -1): if nums[i] > nums[i - 1]: high -= 1 else: # print("Breaking hifgh") break if high == 0: return 0 if low == 0: return len(nums) minSub = math.inf maxSub = -math.inf for i in range(low, high + 1): minSub = min(minSub, nums[i]) maxSub = max(maxSub, nums[i]) for i in range(0, low): if nums[i] > minSub: low = i break for i in range(high, len(nums)): if nums[i] < maxSub: high = i # return low, high, minSub, maxSub return abs(high - low + 1) if __name__ == '__main__': list1 = [1, 2, 5, 3, 7, 10, 9, 12] list2 = [1, 3, 2, 0, -1, 7, 10] list3 = [1, 2, 3] list4 = [3, 2, 1] list5 = [1, 2, 3, 3, 3] print(checkSorted(list1)) print(checkSorted(list2)) print(checkSorted(list3)) print(checkSorted(list4)) print(checkSorted(list5))
# Given an array of sorted numbers and a target sum, find a pair in the array whose sum is equal to the given target. # Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target. # Example 1: # Input: [1, 2, 3, 4, 6], target=6 # Output: [1, 3] # Explanation: The numbers at index 1 and 3 add up to 6: 2+4=6 # Example 2: # Input: [2, 5, 9, 11], target=11 # Output: [0, 2] # Explanation: The numbers at index 0 and 2 add up to 11: 2+9=11 def getTargetSum(nums, target): i = 0 j = len(nums) - 1 while i <j: if (nums[i] + nums[j]) == target: return [i, j] if nums[i] + nums[j] > target: j -= 1 else: i += 1 return [-1, -1] if __name__ == '__main__': nums1 = [1, 2, 3, 4, 6] target1 = 6 x1 = getTargetSum(nums1, target1) assert x1 == [1,3] print(f" {x1}") x2 = getTargetSum([2, 5, 9, 11], 11) assert x2 == [0, 2] print(f" {x2}")
# LIFO Stack DS using Python Lists (Arrays) class StacksArray: def __init__(self): self.stackArray = [] def __len__(self): return len(self.stackArray) def isempty(self): return len(self.stackArray) == 0 def display(self): print(self.stackArray) def top(self): return self.stackArray[-1] def pop(self): if self.isempty(): print("Stack is empty") return None return self.stackArray.pop() def push(self, element): self.stackArray.append(element) if __name__ =='__main__': S = StacksArray() S.push(5) S.push(3) S.display() print(len(S)) print(S.pop()) print(S.isempty()) print(S.pop()) print(S.isempty()) S.push(7) S.push(9) print(S.top()) S.push(4) print(len(S)) print(S.pop()) S.push(6) S.push(8) print(S.pop())
# Given ‘M’ sorted arrays, find the K’th smallest number among all the arrays. # Example 1: # Input: L1=[2, 6, 8], L2=[3, 6, 7], L3=[1, 3, 4], K=5 # Output: 4 # Explanation: The 5th smallest number among all the arrays is 4, this can be verified from the merged # list of all the arrays: [1, 2, 3, 3, 4, 6, 6, 7, 8] # Example 2: # Input: L1=[5, 8, 9], L2=[1, 7], K=3 # Output: 7 # Explanation: The 3rd smallest number among all the arrays is 7. from heapq import * def find_kth_smallest_number(lists, k): minHeap = [] merged = [] for i,j in enumerate(lists): heappush(minHeap, (j[0], i, 0)) print(minHeap) c = 0 while minHeap: r, ln, i = heappop(minHeap) c += 1 if c == k: return r if i + 1 < len(lists[ln]): heappush(minHeap, (lists[ln][i+ 1], ln, i + 1)) return -1 if __name__ == '__main__': rv = find_kth_smallest_number([[2,6,8], [3, 6, 7], [1, 3, 4]], 5) assert rv == 4 print("Kth Smallest numbers is " + str(rv))
# Given an array of points in the a 2D2D plane, find ‘K’ closest points to the origin. # Example 1: # Input: points = [[1,2],[1,3]], K = 1 # Output: [[1,2]] # Explanation: The Euclidean distance between (1, 2) and the origin is sqrt(5). # The Euclidean distance between (1, 3) and the origin is sqrt(10). # Since sqrt(5) < sqrt(10), therefore (1, 2) is closer to the origin. # Example 2: # Input: point = [[1, 3], [3, 4], [2, -1]], K = 2 # Output: [[1, 3], [2, -1]] import math from heapq import * class Points: def __init__(self, x, y): self.x = x self.y = y def print_point(self): print("[" + str(self.x) + "," + str(self.y) + "]" , end="") def find_distance(x,y): return abs(math.sqrt((x*x) + (y*y))) def find_closest_points(points, k): maxHeap = [] j = 0 for i in range(k): d = find_distance(points[i].x, points[i].y) heappush(maxHeap, (-d, points[i]) ) for i in range(k, len(points)): d = find_distance(points[i].x, points[i].y) print(d, maxHeap[0][0]) if d > maxHeap[0][0]: heappop(maxHeap) heappush(maxHeap, (-d, points[i]) ) return maxHeap if __name__ == '__main__': result = find_closest_points([Points(1,3), Points(3,4), Points(2, -1)], 2) print("Here are the k points closest to the origin.", result) for d, point in result: print([point.x, point.y])
# Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects, hence, we can’t count 0s, 1s, and 2s to recreate the array. # The flag of the Netherlands consists of three colors: red, white and blue; and since our input array also consists of three different numbers that is why it is called Dutch National Flag problem. # Example 1: # Input: [1, 0, 2, 1, 0] # Output: [0 0 1 1 2] # Example 2: # Input: [2, 2, 0, 1, 2, 0] # Output: [0 0 1 2 2 2 ] def dutchFlag(array): low = 0 high = len(array) - 1 i = 0 while i <= high : if array[i] == 0: array[i], array[low] = array[low], array[i] i += 1 low += 1 elif array[i] == 1: i += 1 else: array[high], array[i] = array[i], array[high] high -= 1 if __name__ == '__main__': array = [1, 0, 2, 1, 0] print(array) # print(dutchFlag(array)) print(array)
# Given a list of intervals representing the start and end time of ‘N’ meetings, find the minimum number of rooms required to hold all the meetings. # Example 1: # Meetings: [[1,4], [2,5], [7,9]] # Output: 2 # Explanation: Since [1,4] and [2,5] overlap, we need two rooms to hold these two meetings. [7,9] can # occur in any of the two rooms later. # Example 2: # Meetings: [[6,7], [2,4], [8,12]] # Output: 1 # Explanation: None of the meetings overlap, therefore we only need one room to hold all meetings. # Example 3: # Meetings: [[1,4], [2,3], [3,6]] # Output:2 # Explanation: Since [1,4] overlaps with the other two meetings [2,3] and [3,6], we need two rooms to # hold all the meetings. # Example 4: # Meetings: [[4,5], [2,3], [2,4], [3,5]] # Output: 2 # Explanation: We will need one room for [2,3] and [3,5], and another room for [2,4] and [4,5]. class Meetings
# We are given an unsorted array containing ‘n’ numbers taken from the range 1 to ‘n’. The array has some duplicates, find all the duplicate numbers without using any extra space. # Example 1: # Input: [3, 4, 4, 5, 5] # Output: [4, 5] # Example 2: # Input: [5, 4, 7, 2, 3, 5, 3] # Output: [3, 5] def swap(i, j, array): array[i], array[j] = array[j], array[i] def findDuplicates(array): i = 0 n = len(array) duplicates = [] while i < n: if array[i] != i + 1: if array[i] == array[array[i] - 1]: if array[i] not in duplicates: duplicates.append(array[i]) i += 1 continue else: swap(i, array[i] - 1, array) else: i += 1 # sort(duplicae/) return sorted(duplicates) if __name__ == '__main__': array1 = [3, 4, 4, 5, 5] array2 = [5, 4, 7, 2, 3, 5, 3] # array3 = [2, 4, 1, 4, 4] out1 = [4, 5] out2 = [3, 5] # out3 = 4 r1 = findDuplicates(array1) r2 = findDuplicates(array2) # r3 = findMissingNumber(array3) print(r1) print(r2) # print(r3) assert out1 == r1 assert out2 == r2 # assert out3 == r3
# FIFO Queue with Lists/ Array class Queues: def __init__(self): self.QueueList = [] def __len__(self): return len(self.QueueList) def isempty(self): return len(self.QueueList) == 0 def display(self): print(self.QueueList) def enqueue(self, element): self.QueueList.append(element) def dequeue(self): if self.isempty(): print("Queue is empty") return return self.QueueList.pop(0) def peek(self): return self.QueueList[0] if __name__ == '__main__': Q = Queues() Q.enqueue(5) Q.enqueue(15) Q.enqueue(115) Q.display() print("Running Dequeue") Q.dequeue() Q.display() print("Quick peek to Queue->", Q.peek())
# Given an array of ‘K’ sorted LinkedLists, merge them into one sorted list. # Example 1: # Input: L1=[2, 6, 8], L2=[3, 6, 7], L3=[1, 3, 4] # Output: [1, 2, 3, 3, 4, 6, 6, 7, 8] # Example 2: # Input: L1=[5, 8, 9], L2=[1, 7] # Output: [1, 5, 7, 8, 9] from heapq import * class ListNode: def __init__(self, value): self.val = value self.next = None def __lt__(self, other): return self.val < other.val def merge_lists(lists): minHeap = [] resHead = resTail = None merged = [] for i in lists: if i: heappush(minHeap, (i)) while minHeap: r = heappop(minHeap) if resHead == None: resHead = resTail = ListNode(r.val) else: resTail.next = ListNode(r.val) resTail = resTail.next if r.next : heappush(minHeap, (r.next)) return resHead if __name__ == '__main__': l1 = ListNode(2) l1.next = ListNode(6) l1.next.next = ListNode(8) l2 = ListNode(3) l2.next = ListNode(6) l2.next.next = ListNode(7) l3 = ListNode(1) l3.next = ListNode(3) l3.next.next = ListNode(4) result = merge_lists([l1, l2, l3]) print("Here are the elements from the merged lists: ",end= '') while result != None: print(str(result.val) + " ", end='') result = result.next
# Design a class to calculate the median of a number stream. The class should have the following two methods: # insertNum(int num): stores the number in the class # findMedian(): returns the median of all numbers inserted in the class # If the count of numbers inserted in the class is even, the median will be the average of the middle two numbers. # Example 1: # 1. insertNum(3) # 2. insertNum(1) # 3. findMedian() -> output: 2 # 4. insertNum(5) # 5. findMedian() -> output: 3 # 6. insertNum(4) # 7. findMedian() -> output: 3.5 from heapq import * class MedianOfAStream: def __init__(self): self.maxHeap = [] self.minHeap = [] def insert_num(self, num): if not self.maxHeap or num <= -self.maxHeap[0]: heappush(self.maxHeap, -num) else: heappush(self.minHeap, num) # Balance if len(self.minHeap) > len(self.maxHeap): heappush(self.maxHeap, -heappop(self.minHeap)) elif len(self.maxHeap) > len(self.minHeap) + 1: heappush(self.minHeap, -heappop(self.maxHeap)) def find_median(self): if len(self.maxHeap) == len(self.minHeap): return (-self.maxHeap[0] + self.minHeap[0])/2.0 return -self.maxHeap[0]* 1.0 if __name__ == '__main__': medianOfAStream = MedianOfAStream() medianOfAStream.insert_num(3) medianOfAStream.insert_num(1) print("The median is :" + str(medianOfAStream.find_median())) medianOfAStream.insert_num(5) print("The median is :" + str(medianOfAStream.find_median())) medianOfAStream.insert_num(4) print("The median is :" + str(medianOfAStream.find_median()))
# Problem Statement # # Given a string, find if its letters can be rearranged in # such a way that no two same characters come next to each other. # Example 1: # Input: "aappp" # Output: "papap" # Explanation: In "papap", none of the repeating characters come next to each other. # Example 2: # Input: "Programming" # Output: "rgmrgmPiano" or "gmringmrPoa" or "gmrPagimnor", etc. # Explanation: None of the repeating characters come next to each other. # Example 3: # Input: "aapa" # Output: "" # Explanation: In all arrangements of "aapa", atleast two 'a' will come together e.g., "apaa", "paaa". from heapq import * from collections import Counter def rearrange_string(stri): c = Counter(stri) result = "" maxHeap = [] # create a max Heap for k,v in c.items(): heappush(maxHeap, (-v,str(k))) pf, pc = 0, None while maxHeap: print(pc) f, c = heappop(maxHeap) if pc and pf < 0: print("Pushing", pf, pc, maxHeap) heappush(maxHeap, (pf,pc)) result = result + str(c) pc = c pf = f + 1 return result if __name__ == '__main__': print("Rearranged string: " + rearrange_string("aappp")) print("Rearranged string: " + rearrange_string("Programming")) print("Rearranged string: " + rearrange_string("apppb"))
# Given the head of a LinkedList and two positions ‘p’ and ‘q’, reverse the LinkedList from position ‘p’ to ‘q’. class Node: def __init__(self, value, next=None): self.value = value self.next = next def print_list(self): temp = self while temp is not None: print(temp.value, end='->') temp = temp.next def reverse_sublist(head, p, q): current = head prev = None i = 1 if p == q: return head while i < p: prev = current current = current.next i += 1 last_node_of_first_subpart = prev to_be_last_node = current print(i) # exit(1) while current is not None and i <= q: _next = current.next current.next = prev prev = current current = _next i += 1 to_be_last_node.next = current if last_node_of_first_subpart is not None: last_node_of_first_subpart.next = prev else: head = prev return head if __name__ == '__main__': head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) print("Nodes of original LinkedList are : ", head.print_list()) newhead = reverse_sublist(head, 2, 4) print("Nodes of reveresed LinkedList are : ", newhead.print_list())
# 计算0到这个元素的所有的平方和 import time def cpu_bound(number): print(sum(i ** 2 for i in range(0, number))) def calc_sums(numbers): for number in numbers: cpu_bound(number) def main(): start_time = time.perf_counter() numbers = [10000000 + x for x in range(20)] calc_sums(numbers) end_time = time.perf_counter() print('calc_sums takes {} seconds'.format(end_time - start_time)) main()
''' Created on Sep 20, 2018 @author: jgonzales ''' # -*- coding:utf-8 -*- print(sum([x*x for x in range(1,10+1) if x*x % 2 == 0]))
a = int(input("Ingrese un numero: ")) b = int(input("Ingrese otro numero: ")) resultado = a + b print("El resultado es:",resultado)
''' Created on Sep 20, 2018 @author: jgonzales ''' # -*- coding:utf-8 -*- numeros = list(range(1,10+1)) for n in numeros: if n % 2 == 0: print(n) print(sum([x*x for x in numeros if x*x % 2 == 0]))
# i = 0 #this is a while loop kinda like a if statment #so it runs this code until the statment is false # so it coubnts from 1 to 10 while i <= 10: print(i) i = i + 1 # or you can do i += 1 does the same thing print("done with loop")
# print(" ") print("Welcome to this translator") print("this transltor will translate from english to my plop language") def translate(phrase): translation = "" for letter in phrase: if letter.lower() in "aeiou": if letter.isupper(): translation = translation + "W" else: translation = translation + "w" else: translation = translation + letter return translation print(translate(input("enter a phrase: "))) print("this is your phrase in the plop language")
# this is a function you have to have def # say_hi is the name of the function you have to have the this(): # you also have to indent the the thing that is in the function def say_hi(): print("hello user") #this is just showing the flow of the code print("Top") #this is going to excute the function or some people say calling the function say_hi() print("Bottom") print(" ") # the thing in this () is a parameter or 's def hello(name, age): #for numbers that you want to make in to a string or else it will throw a error print("hello " + name + " you are " + str(age)) # for the parameter that you want to fill in like name and age you have to put them in order # like yousuf is is name and 14 is age hello("yousuf", 14) hello("khan", 14)
import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate from scipy.integrate import dblquad from scipy.integrate import tplquad def trapz(func,start,end,Num_steps): """ Trapz takes an equation (func), start and end points, and the number of trapezoids you want to use. Trapz then uses this to calculate the integral (I) from start to end using trapezoids. """ h = (end-start)/Num_steps k = np.arange(1,Num_steps) I = h*(0.5*func(start) + 0.5*func(end) + func(start+k*h).sum()) return I def simps(func,start,end,Num_steps): """ Simps takes an equation (func), start and end points, and the number of quadratic curves you want to use. Simps then uses this to calculate the integral (I) from start to end using quadratic curves as opposed to straight lines. """ h = (end-start)/Num_steps k1 = np.arange(1,Num_steps/2+1) k2 = np.arange(1,Num_steps/2) I = (1./3.)*h*(func(start) + func(end) + 4.*func(start+(2*k1-1)*h).sum() + 2.*func(start+2*k2*h).sum()) return I
#This should be a programm that will be able to encrypt #and decrypt data stored in Caesar Cipher alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] print('Welcome to my Caesar Cipher cryptographer') print(''' _ _ | | | | ___ _ __ _ _ _ __ | |_ ___ __ _ _ __ __ _ _ __ | |__ _ _ / __| '__| | | | '_ \| __/ _ \ / _` | '__/ _` | '_ \| '_ \| | | | | (__| | | |_| | |_) | || (_) | (_| | | | (_| | |_) | | | | |_| | \___|_| \__, | .__/ \__\___/ \__, |_| \__,_| .__/|_| |_|\__, | __/ | | __/ | | | __/ | |___/|_| |___/ |_| |___/ ''') keepgoing = True while keepgoing == True: direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) def caeser(text_par, shift_par, positions_par): end_text = '' if shift_par > (26 * 2): shift_par = shift_par % 26 for i in text: if i in alphabet: position = alphabet.index(i) if positions_par == 'encode': new_position = position + shift_par elif positions_par == 'decode': new_position = position - shift_par new_letter = alphabet[new_position] end_text += new_letter else: end_text += i print(f"The {positions_par}d message is: '{end_text}'") caeser(text, shift, direction) stop = input('Do you wanna go again? (type yes or no)\n') if stop == 'no': keepgoing = False print('Good Bye!')
a = input().upper() s = input().upper() b = s.split() if a in b: k = b.count(a) print(k, end=" ") if s.startswith(a): print(0) elif s.endswith(a) and k==1: print(s.index(" "+a)+1) else: print(s.index(" "+a+" ")+1) else: print(-1)
nums = [1,2,3,4,5,20,30,40,50] def count_pairs_sum_target(nums, target): n = len(nums) nums.sort() l,r = 0,n-1 cnt = 0 while l < r: if nums[l] + nums[r] > target: cnt += r - l r -= 1 else: l += 1 return cnt
def isPrime(n): if n < 2: return False if n == 2: return True if not n & 1: return False for i in range(3, int(n**0.5)+1, 2): if n % i == 0: return False return True N = int(input()) # for i in range(1,N+1): # if isPrime(i): # print(i,end=" ") primes = filter(isPrime,range(1,N+1)) print(" ".join(map(str,primes)))
from functools import lru_cache # @lru_cache(None) # def canMakeSubsequence(str1, str2): # if not str2: # return True # if not str1: # return False # a,b = ord(str1[0]), ord(str2[0]) # if a==b or a+1==b or a-b==25: # return canMakeSubsequence(str1[1:],str2[1:]) # else: # return canMakeSubsequence(str1[1:],str2) def canMakeSubsequence(str1, str2): start = 0 # n = len(str1) # for x in str2: # for i in range(n): # if str1[i]==x or ord(str1[i])+1==ord(x) or (str1[i]=='z' and x=='a'): while str1 and str2: if str1[0]==str2[0] or ord(str1[0])+1==ord(str2[0]) or (str1[0]=='z' and str2[0]=='a'): str1, str2 = str1[1:], str2[1:] else: str1 = str1[1:] if str2: return False else: return True def can_make_sub(str1, str2): str1 = "zc" str2 = "ad" print(canMakeSubsequence(str1,str2))
# list argument must be sorted in ascending order. import bisect a = [2, 4, 6, 8, 10, 12, 14] x = 7 i = bisect.bisect_left(a,x) print(i) a.insert(i, x) print(a) b = [2, 4, 6, 8, 8, 8, 10, 12, 14] x = 8 i = bisect.bisect_left(b,x) print(i) a = [1, 3, 5, 6, 7, 9, 10, 12, 14] x = 8 i = bisect.bisect_left(a, x, lo=2, hi=7) # [5,6,7,9,10] print(i) a = [1, 2, 3, 4, 4, 7, 6] x = 4 i = bisect.bisect_right(a, x) print(i) a = [2, 4, 6, 6, 8, 8, 8, 10, 12, 14] x = 8 bisect.insort_left(a, x) print(a) y = 6 bisect.insort_right(a, y) print(a)
maze = [[0, 0, 1, 1, 1, 1], [1, 0, 0, 0, 1, 1], [0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0]] row = col = 6 def countPath(i,j,count): if i==row-1 and j==col-1: count += 1 else: maze[i][j]=2 if j<col-1 and maze[i][j+1]==0: count = countPath(i,j+1,count) if i<row-1 and maze[i+1][j]==0: count = countPath(i+1,j,count) if j>0 and maze[i][j-1]==0: count = countPath(i,j-1,count) if i>0 and maze[i-1][j]==0: count = countPath(i-1,j,count) maze[i][j]=0 return count print(countPath(0,0,0))
import heapq from collections import Counter # inputText = "this is an example for huffman encoding" # frequencyCounter = Counter(inputText) text = "aaabbcccdddd" frequencyCounter = Counter(text) print(frequencyCounter) def huffman_encode(frequencyCounter): heap = [[freq, [sym, ""]] for sym,freq in frequencyCounter.items()] heapq.heapify(heap) while len(heap)>1: lo = heapq.heappop(heap) hi = heapq.heappop(heap) for pair in lo[1:]: pair[1] = '0' + pair[1] for pair in hi[1:]: pair[1] = '1' + pair[1] heapq.heappush(heap,[lo[0]+hi[0]]+lo[1:]+hi[1:]) return sorted(heapq.heappop(heap)[1:], key=lambda p: (len(p[-1]),p)) print(huffman_encode(frequencyCounter))
class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def preorder(root): # 先序,先root if not root: return [] result = [root.data] result.extend(preorder(root.left)) result.extend(preorder(root.right)) return result def preorder_iterative(root): if not root: return [] stack = [root] result = [] while stack: node = stack.pop() result.append(node.data) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return result def inorder(root): # 中序,中root if not root: return [] result = [] result.extend(inorder(root.left)) result.append(root.data) result.extend(inorder(root.right)) return result def inorder_iterative(root): if not root: return [] stack = [] result = [] node = root while stack or node: if node: stack.append(node) node = node.left else: node = stack.pop() result.append(node.data) node = node.right return result def postorder(root): # 后序,后root if not root: return [] result = [] result.extend(postorder(root.left)) result.extend(postorder(root.right)) result.append(root.data) return result def postorder_iterative(root): if not root: return [] stack = [root] result = [] while stack: node = stack.pop() result.append(node.data) if node.left: stack.append(node.left) if node.right: stack.append(node.right) return result[::-1]
def count_integer_pairs(a, b, c): dp = [[0] * (c+1) for _ in range(c+1)] dp[0][0] = 1 for x in range(c+1): for y in range(c+1): if a*x + b*y <= c: dp[x][y] = 1 for x in range(1, c+1): for y in range(c+1): if y > 0: dp[x][y] += dp[x-1][y-1] dp[x][y] += dp[x-1][y] return dp[c][c] print(count_integer_pairs(10,5,20))
def compute_transition_table(pattern, alphabet): pattern_len = len(pattern) transition_table = [0] * (pattern_len + 1) transition_table[0] = -1 for i in range(pattern_len): transition_table[i + 1] = transition_table[i] + 1 while transition_table[i + 1] > 0 and pattern[i] != pattern[transition_table[i + 1] - 1]: transition_table[i + 1] = transition_table[transition_table[i + 1] - 1] + 1 return transition_table def finite_automata_match(pattern, text): transition_table = compute_transition_table(pattern, set(text)) pattern_len = len(pattern) current_state = 0 matches = [] for i, char in enumerate(text): while current_state > 0 and pattern[current_state] != char: current_state = transition_table[current_state] if pattern[current_state] == char: current_state += 1 if current_state == pattern_len: matches.append(i - pattern_len + 1) return matches # 示例用法 pattern = "abc" text = "abracadabca" matches = finite_automata_match(pattern, text) print(matches) # 输出: [0, 7]
from collections import defaultdict a = input() b = input() a = list(pattern) b = str.split(" ") if len(a)!=len(b): return False l = len(a) d1, d2 = defaultdict(list),defaultdict(list) for i in range(l): if (a[i] not d1 and b[i] not in d2) or (a[i] in d1 and b[i] in d2 and d1[a[i]] == d2[b[i]]): d1[a[i]].append(i) d2[b[i]].append(i) else: return False return True
# At the core of Sorted Containers is the mutable sequence data type SortedList. # The SortedList maintains its values in ascending sort order. # As with built-in list datatype, SortedList supports duplicate elements and fast random-access indexing. from sortedcontainers import SortedList sl = SortedList() # Values may be added to a SortedList using either SortedList.update() or SortedList.add(). sl.update([5,1,3,4,2]) print(sl) sl.add(0) print(sl) # Remove elements by value: SortedList.discard() and SortedList.remove() # Remove elements by index: SortedList.pop() and SortedList.__delitem__() # Remove all: SortedList.clear() sl.remove(0) print(sl) sl.discard(1) print(sl) sl.pop() print(sl) del sl[1] print(sl) sl.clear() print(sl) # Because SortedList is sorted, it supports efficient lookups by value or by index. # Values can be found in logarithmic time. # SortedList.__contains__(), SortedList.count(), SortedList.index(), # SortedList.bisect_left(), SortedList.bisect_right(), SortedList.__getitem__() sl = SortedList('abbcccddddeeeee') print('f' in sl) print(sl.count('e')) print(sl.index('c')) print(sl[3]) print(sl.bisect_left('d')) print(sl.bisect_right('d')) print(sl[6:10]) # Iterate # SortedList.__iter__(), SortedList.__reversed__(), # SortedList.irange(), SortedList.islice() sl = SortedList('acegi') print(list(iter(sl))) print(list(reversed(sl))) print(list(sl.irange('b','h'))) print(list(sl.islice(1,4))) # SortedList.__add__(), SortedList.__mul__() print(sl+sl) print(sl*3) # SortedDict keys are maintained in sorted order. from sortedcontainers import SortedDict sd = SortedDict() # add item # SortedDict.__setitem__(), SortedDict.update(), SortedDict.setdefault() sd['e'] = 5 sd['b'] = 2 print(sd) sd.update({"d":4,"c":3}) print(sd) sd.setdefault('a',1) print(sd) # remove item # SortedDict.__delitem__(), SortedDict.pop(), SortedDict.popitem() del sd['d'] print(sd) print(sd.pop('c')) print(sd.popitem(index=-1)) print(sd) # Look up keys # SortedDict.__getitem__(), SortedDict.__contains__(), SortedDict.get(), SortedDict.peekitem() print(sd['b']) print('c' in sd) print(sd.get('z') is None) print(sd.peekitem(index=-1)) print(sd.bisect_right('b')) print(sd.index('a')) print(list(sd.irange('a','z'))) print(sd.keys(), sd.items(), sd.values()) # SortedSet. from sortedcontainers import SortedSet ss = SortedSet() # SortedSet.__contains__(), SortedSet.add(), SortedSet.update(), SortedSet.discard() ss.add('b') ss.add('c') ss.add('a') ss.add('b') print(ss) print('c' in ss) ss.discard('a') ss.remove('b') what = ss.update('def') print(what) ss.discard('z') # remove('z')会抛异常 print(ss) # SortedSet.__getitem__(), SortedSet.__reversed__(), SortedSet.__delitem__(), SortedSet.pop() print(ss[0]) print(list(reversed(ss))) del ss[0] ss.pop(index=-1) print(ss) # SortedSet.difference(), SortedSet.intersection(), # SortedSet.symmetric_difference(), SortedSet.union() abcd = SortedSet('abcd') cdef = SortedSet('cdef') print(abcd.difference(cdef)) print(abcd.symmetric_difference(cdef)) print(abcd.union(cdef)) print(abcd | cdef) abcd |= cdef print(abcd) # SortedSet.bisect(), SortedSet.index(), SortedSet.irange(), SortedSet.islice() ss = SortedSet('abcdef') print(ss.bisect('d')) print(ss.index('f')) print(list(ss.irange('b','e'))) print(list(ss.islice(-3)))
def find_number_pairs(arr, target): n = len(arr) left = 0 right = n - 1 pairs = [] while left < right: if arr[left] + arr[right] > target: # 找到一个数字对 pairs.append((arr[left], arr[right])) # 继续寻找下一个可能的数字对 right -= 1 else: # 数字对的和小于等于目标值,继续向右移动左指针 left += 1 return pairs # def find_number_pairs(arr, target): # n = len(arr) # pairs = [] # for i in range(n): # left = i + 1 # right = n - 1 # while left <= right: # mid = left + (right - left) // 2 # if arr[mid] > target - arr[i]: # right = mid - 1 # else: # left = mid + 1 # # 将所有大于目标值的数字对添加到结果列表中 # for j in range(i + 1, left): # pairs.append((arr[i], arr[j])) # return pairs arr = [1,2,3,4,5,6, 20,30,40,50] target = 23 print(find_number_pairs(arr,target)) def numberOfPairs(nums,target): i = 0 j = len(nums) - 1 pairs=0 while i<j: if nums[i]+nums[j]>target: pairs += j-i j -= 1 else: i += 1 return pairs print('no of pairs',numberOfPairs([1, 3, 7, 9, 10, 11],7)) #. output:14 print('no of pairs',numberOfPairs([1, 11],7)) #. output: 1 print('no of pairs',numberOfPairs([0,1],7)) #.output: 0 print('no of pairs',numberOfPairs([0,1,2,2],2)) # output:5 print('no of pairs',numberOfPairs(arr,target))
T = int(input()) for i in range(T): C = list(map(int, input().split(" ")))[1] total = sum(list(map(int,input().split(" ")))) if total > C: print("No") else: print("Yes")
#namedtuples #deque #ChainMap #Counter #OrderedDict #defaultdict # dq[1]=z is OK, when dq[1:2] error. # The major advantage of deques over lists is that inserting # items at the beginning of a deque is much faster than inserting # items at the beginning of a list, although inserting items at the # end of a deque is very slightly slower than the equivalent operation # on a list. from collections import deque dq = deque('abc') dq.append('d') dq.appendleft('z') dq.extend('efg') dq.extendleft('yxw') print(dq) # deque(['w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g']) print(dq.pop()) print(dq.popleft()) print(dq) # g # w # deque(['x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f']) dq.rotate(2) print(dq) dq.rotate(-2) print(dq) # deque(['e', 'f', 'x', 'y', 'z', 'a', 'b', 'c', 'd']) # deque(['x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f']) dq = deque({1,2,3,4}) dq.append(5) first = dq.popleft() #ChainMap # The advantage of using ChainMap objects, rather than just a dictionary, # is that we retain previouly set values. from collections import ChainMap dict1 = {'a':1,'b':2,'c':3} dict2 = {'d':4,'e':5} chainmap = ChainMap(dict1,dict2) #linking two dictionaries print(chainmap) print(chainmap.maps) # print(chainmap.values) # ChainMap({'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5}) # [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5}] print(chainmap['b']) print(chainmap['e']) # 2 # 5 dict3 = {'a':10,'f':7} chainmap2 = ChainMap(dict1,dict2,dict3) print(chainmap2.maps) print(chainmap2['a']) print(chainmap2.maps[2]['a']) # [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5}, {'a': 10, 'f': 7}] # 1 # 10 # Counter # We can pass it any sequence object, a dictionary of key:value pairs, or a # tuple of the format (object=value,...) # The most notable difference between counter and dictionaries is that counter # return a zero count for missing items rather than raising a key error. from collections import Counter print(Counter("anysequence")) c2 = Counter({'a':1,'c':2,'e':3}) c3 = Counter(a=1,c=2,e=3) print(c2) print(c3) # Counter({'e': 3, 'n': 2, 'a': 1, 'y': 1, 's': 1, 'q': 1, 'u': 1, 'c': 1}) # Counter({'e': 3, 'c': 2, 'a': 1}) # Counter({'e': 3, 'c': 2, 'a': 1}) c0 = Counter("hello world i am hamilton") print(c0) print(c0.most_common()) # Counter({'l': 4, ' ': 4, 'o': 3, 'h': 2, 'i': 2, 'a': 2, 'm': 2, 'e': 1, 'w': 1, 'r': 1, 'd': 1, 't': 1, 'n': 1}) # [('l', 4), (' ', 4), ('o', 3), ('h', 2), ('i', 2), ('a', 2), ('m', 2), ('e', 1), ('w', 1), ('r', 1), ('d', 1), ('t', 1), ('n', 1)] # OrderedDict, remembers the insertion order # OrderedDict is often used in conjunction with the sorted method to create a sorted dictionary. from collections import OrderedDict od1 = OrderedDict() od1['one'] = 1 od1['two'] = 2 od2 = OrderedDict() od2['two'] = 2 od2['one'] = 1 print(od1) print(od2) print(od1 == od2) # OrderedDict([('one', 1), ('two', 2)]) # OrderedDict([('two', 2), ('one', 1)]) # False kvs = [('three',3),('four',4),('five',5)] od1.update(kvs) print(od1) # OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]) od3 = OrderedDict(sorted(od1.items(), key=lambda t: (4*t[1]-t[1]**2))) print(od3) print(od3.values()) # OrderedDict([('five', 5), ('four', 4), ('one', 1), ('three', 3), ('two', 2)]) # odict_values([5, 4, 1, 3, 2]) # defaultdict, is a subclass of dict, and therefore they share methods and operations. from collections import defaultdict dd = defaultdict(int) words = "red blue green red yellow blue red green green red".split() for word in words: dd[word] += 1 print(dd) print(Counter(words)["green"]) print(dd["green"]) ## namedtuple bob = ('Bob', 30, 'male') print(bob) jane = ('Jane', 29, 'female') print("Field by index:",jane[0]) print("Fields by index:") for p in [bob,jane]: print("{} is a {} year old {}".format(*p)) # ('Bob', 30, 'male') # Field by index: Jane # Fields by index: # Bob is a 30 year old male # Jane is a 29 year old female # This makes tuples convenient containers for simple uses. # In contrast, remembering which index should be used for each value can lead to errors, especially if the tuple has a lot of fields and is constructed far from where it is used. A namedtuple assigns names, as well as the numerical index, to each member. from collections import namedtuple Person = namedtuple('Person','name age') bob = Person(name='bob',age=30) print(bob) jane = Person(name='Jane',age=29) print(jane.name) print("Fields by index:") for p in [bob,jane]: print('{} is {} years old'.format(*p)) # Person(name='bob', age=30) # Jane # Fields by index: # bob is 30 years old # Jane is 29 years old
import bisect def maximumJumps(nums, target): n = len(nums) jump = [(0,0)] # (跳的次数,下标) for i in range(1,n): for p in jump[::-1]: if abs(nums[p[1]]-nums[i]) <= target: # jump.insort((p[0]+1, i)) bisect.insort(jump, (p[0]+1, i)) break for p in jump: if p[1] == n-1: return p[0] return -1 nums = [1,3,6,4,1,2] target = 2 print(maximumJumps(nums,target))
# Given an array, check whether the array is in sorted order with recursion def is_array_sorted(A): if len(A)==1: return True return A[0]<=A[1] and is_array_sorted(A[1:]) A = [127, 220, 246, 277, 321, 454, 534, 565, 933] print(is_array_sorted(A))
# 连续子数组和的绝对值的最大值 # 状态转移方程: f[i] = max(f[i-1]+nums[i], nums[i]) = max(f[i-1],0)+nums[i] def maxabssum(nums): ans = f_max = f_min = 0 for x in nums: f_max = max(f_max, 0) + x f_min = min(f_min, 0) + x ans = max(ans, f_max, -f_min) return ans nums = [1,-3,2,3,-4] print(maxabssum(nums))
grid = [[0, 0, 0, 0, 0, 1], [1, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1], [0, 1, 0, 0, 1, 0], [0, 1, 0, 0, 0, 2]] def search(x,y): if grid[x][y] == 2: print('found at',x,y) return True elif grid[x][y] == 1: print('Wall at',x,y) return False elif grid[x][y] == 3: print('visited at',x,y) return False print('visiting',x,y) grid[x][y] = 3 if x<len(grid)-1 and search(x+1,y) or y<len(grid)-1 and search(x,y+1) or x>0 and search(x-1,y) or y>0 and search(x,y-1) : return True return False search(0,0)
#由于python3浮点数的四舍五入不精确,自己写四舍五入精确一位小数的方法 def myround(x): y = x*10 if y - int(y) < 0.5: res = int(y) else: res = int(y)+1 return res/10 # N = int(input()) # if N<=150: # res = 0.4463 * N # elif 151<=N<=400: # res = 150*0.4463 + (N-150)*0.4663 # else: # res = 150*0.4663 + (400-150)*0.4663 + (N-400)*0.5663 # print("{:.1f}".format(res)) a = [1.25,3.45,10.15,11.15,11.25,11.35,12.35,12.45] for x in a: print(x,round(x,1),myround(x))
nums = [2,5,6,0,0,1,2] # nums = [4,5,6,7,8,9,0,1,2] # nums = [8,9,0,1,2,3,4,5,6] nums = [1,1,1,1,2,1] target = 2 def search_rotated_sorted(nums, target): n = len(nums) left = 0 right = n-1 while left <= right: mid = (left+right)//2 if nums[mid] == target: return True # if nums[left]<=target<nums[mid] or target<nums[mid]<=nums[left] or nums[mid]<=nums[left]<=target: if nums[left]<=target<nums[mid] or target<nums[mid]<=nums[right] or nums[mid]<=nums[left]<=target: right = mid - 1 else: left = mid + 1 return False print(search_rotated_sorted(nums,target)) # 最后,这题不能在O(log(N))内过,O(N) # 那就 return target in nums吧
#일정 시간 간격으로 크롤링 및 기타 반복 작업 가능한 예제 import time import threading def thread_run(): print('=====',time.ctime(),'=====') for i in range(1,51): #개발 하고자 하는 코드 print('Thread running - ', i) threading.Timer(2.5, thread_run).start() thread_run() #threading.Timer(2, thread_run).start() : 메인에서 실행하면 1회 실행
#JSON===CONVERTER import json x = { "name": "ferdi", "age": 28, "city": "l-town" } #Convert into JSON y = json.dumps(x) #JSON CREATED print(y)
# import datetime # x= datetime.datetime.now() # print(x) import datetime x= datetime.datetime(2020, 5, 7) # day # print(x.strftime("%d")) | print(x.strftime("%A")) | print(x.strftime("%a")) # month # print(x.strftime("%B")) | print(x.strftime("%b")) | print(x.strftime("%m")) # # year # print(x.strftime("%Y")) | print(x.strftime("%y")) #microsec # print(x.strftime("%f")) # easiest print(x.strftime("%c"))
# Learning __init__ (initializer) class People: def __init__(self, firstName, age, ): self.firstName = firstName self.age = age def displayPerson(self): print("Hello, my name is " + self.firstName + ", I am " + str(self.age) + " years old.") person1 = People("John", 25) person2 = People("Tim", 24) print("Person 1 name:", person1.firstName) print("Person 2 name:", person2.firstName + "\n") person1.displayPerson() person2.displayPerson() #END
age = 15 if age >= 18: print(True) else: print(False) #? Operador ternario (ternary) is_adult = True if age >= 18 else False #Cualquier condición, pero no se pueden igualar variables dentro del operador ternario print(is_adult) is_adult = 'Es adulto' if age >= 18 else 'No es adulto' print(is_adult) list_a = [1,2,3,4] result = list(map(lambda num: num*2 if num %2==0 else num,list_a)) print(result)
#!/usr/bin/env python3 def popular_words(text: str, words: list) -> dict: result = {} for item in words: count = 0 for word in text.split(' '): if item.lower() == word.lower(): count += 1 print(count) result[item] = count return result if __name__ == '__main__': print(popular_words(''' When I was One I had just begun When I was Two I was nearly new ''', ['i', 'was', 'three', 'near'])) print(popular_words(''' When I was One I had just begun When I was Two I was nearly new ''', ['i', 'was', 'three', 'near'])) if popular_words(''' When I was One I had just begun When I was Two I was nearly new ''', ['i', 'was', 'three', 'near']) == { 'i': 4, 'was': 3, 'three': 0, 'near': 0 }: print("Coding complete? Click 'Check' to earn cool rewards!") else: print('Error') assert popular_words(''' When I was One I had just begun When I was Two I was nearly new ''', ['i', 'was', 'three', 'near']) == { 'i': 4, 'was': 3, 'three': 0, 'near': 0 } print("Coding complete? Click 'Check' to earn cool rewards!")
#!/usr/bin/env python lines=[] while True: s=raw_input() if s: lines.append(s.upper()) else: break; for sentence in lines: print(sentence)
#!/usr/bin/env python3 def checkio(words: str) -> bool: count = 0 for index in words.split(" "): # print(index) if index.isalpha(): count = count + 1 else: count = 0 if count == 3: return True return False if __name__ == '__main__': print(checkio("Hello World hello")) print(checkio("He is 123 man" ))
#!/usr/bin/env python3 def checkio(number: int)-> int: mul = 1 for item in [int(digits) for digits in str(number)]: if item != 0: mul = mul*item return mul if __name__ == '__main__': print(checkio(123405))
#!/usr/bin/env python3 def long_repeat(line): if not line: return 0 else: max_repeat = 0 count = 1 for item in range(1,len(line)): if line[item] == line[item-1] : count += 1 else: count = 1 print(f'{item} : {count}') if max_repeat < count: max_repeat = count return max_repeat if __name__ == '__main__': #print(long_repeat('sdsffffse')) #print(long_repeat('ddvvrwwwrggg')) #print(long_repeat('abababaab')) #print(long_repeat('')) print(long_repeat('abababa'))
#!/usr/bin/env python3 def between_markers(text:str, begin:str, end:str)-> str: if begin in text: begin_index = text.find(begin) + len(begin) else: begin_index = 0 if end in text: end_index = text.find(end) else: end_index = len(text) return text[begin_index:end_index] def between_markers_2(text: str, begin: str, end: str) -> str: m1 = 0 if text.find(begin) < 0 else text.find(begin) + len(begin) m2 = len(text) if text.find(end) < 0 else text.find(end) return text[m1:m2] if __name__ == '__main__': print(between_markers('What is >apple<', '>','<'))
#!/usr/bin/env python3 def find_message(text: str) -> str: result= [] s = "" for letter in text: if letter.isupper() == True: result.append(letter) return s.join(result) def find_message_2(text): return ''.join(i for i in text if i.isupper()) if __name__=='__main__': print(find_message("How are you? Eh, ok. Low or Lower? Ohhh."))
import math import unittest import distance class TestDistance(unittest.TestCase): def test_euclideanBase(self): a = [0, 0] b = [0, 0] self.assertEqual(distance.euclidean(a, b), 0) a = [1, 0] b = [0, 0] self.assertEqual(distance.euclidean(a, b), 1) a = [0, 0] b = [0, 1] self.assertEqual(distance.euclidean(a, b), 1) a = [0, 0] b = [1, 1] self.assertEqual(distance.euclidean(a, b), math.sqrt(2)) def test_levenshteinBase(self): a = 'abc' b = 'abc' self.assertEqual(distance.levenshtein(a, b), 0) a = 'abc' b = 'abd' self.assertEqual(distance.levenshtein(a, b), 1) a = 'abc' b = 'abz' self.assertEqual(distance.levenshtein(a, b), 1) a = 'ab' b = 'abc' self.assertEqual(distance.levenshtein(a, b), 1) a = 'abcd' b = 'abc' self.assertEqual(distance.levenshtein(a, b), 1) a = 'abc' b = 'xyz' self.assertEqual(distance.levenshtein(a, b), 3) if __name__ == '__main__': unittest.main()
import unittest import binarysearchtree class BinarySearchTreeTests(unittest.TestCase): def test_basic(self): t = binarysearchtree.Node(10) assert(t.list() == '(10)') t.add(5) t.add(7) t.add(6) assert(t.list() == '((5((6)7))10)') assert(t.search(7) is not None) assert(t.search(8) is None) t.search(10).remove() assert(t.list() == '((5(6))7)')
a,b=0,1 print(a,b,end=" ") num=int(input("\n\nEnter the number to check if in fib?")) while True: c=a+b print(c,end=" ") if c<=num: if c==num: print("\nYes! It is in the fib series") break else: print("\n NO! It is not in the fibonacci series") break a,b=b,c
print("************************************************") print("Sistema para reconocer que numero es mas grande") print("************************************************\n ") nu = int(input("Por favor, ingrese el primer numero: ")) nd = int(input("Por favor, ingrese el segundo numero: ")) nt = int(input("Por favor, ingrese el tercer numero: ")) if nu > nd and nu > nt: print("El numero ", nu, "es el mas grande. ") elif nd > nt: print("El numero ", nd, "es el mas grande. ") else: print("El numero ", nt, "es el mas grande. ")
def rectangle_area(a, b): if(a>=0 and b>=0): area = a*b print("Pole prostokata wynosi:") print(area) else: print("Blad! Podaj nieujemna wartosc dlugosci boku") return rectangle_area(3.23,1)