text
stringlengths
37
1.41M
__author__ = 'mingluma' import os class Splitter(object): def __init__(self, path, worker_num): self.path = path self.worker_num = worker_num def split(self): """ Split files into splits, each split has multiple chunks. :return: An array of split information, i.e., (file, start, end) """ overall_chunks = [] for filename in self.get_all_files(): file_chunks = self.split_single_file(filename) overall_chunks.extend(file_chunks) return overall_chunks def get_all_files(self): if os.path.isdir(self.path): return os.listdir(self.path) else: return [self.path] def split_single_file(self, filename): """ Split a single file into parts in chunk size :return: An array of split position of the chunks, i.e., (file, start, end). """ file_size = os.path.getsize(filename) chunk_size = (file_size + self.worker_num - 1) / self.worker_num file_handler = open(filename, "r") chunks = [] pos = 0 while pos < file_size: next_pos = min(pos + chunk_size, file_size) if pos == 0: chunks.append((filename, pos, self.find_next_newline(file_handler, next_pos))) else: chunks.append((filename, self.find_next_newline(file_handler, pos), self.find_next_newline(file_handler, next_pos))) pos = next_pos file_handler.close() return chunks def find_next_newline(self, file_handler, pos): file_handler.seek(pos) line = file_handler.readline() return pos + len(line) if __name__ == "__main__": splitter = Splitter("input", 4) print splitter.split()
# -*- coding:utf-8 -*- """ 代码主要作用: """ class Condition(object): def __init__(self, rank): self._rank = rank def __ge__(self, other): """Used for comparisons.""" return self._rank >= other._rank def __str__(self): if self._rank == 1: return "critical" elif self._rank == 2: return "serious" else: return "fair" class Patient(object): def __init__(self, name, condition): self._name = name self._condition = condition def __ge__(self, other): """Used for comparisons.""" return self._condition >= other._condition def __str__(self): return self._name + ' / ' + str(self._condition)
# -*- coding:utf-8 from ExampleCode.chapter4.node import Node from ExampleCode.arrays import Array from abstractset import AbstractSet class HashSet(AbstractCollection, AbstractSet): """A hashing implementation of a set.""" DEFAULT_CAPACITY = 3 def __init__(self, sourceCollection=None, capacity=None): if capacity is None: self._capacity = HashSet.DEFAULT_CAPACITY else: self._capacity = capacity self._items = Array(self._capacity) self._foundNode = self._priorNode = None self._index = -1 AbstractCollection.__init__(self, sourceCollection) # Accessor methods def __contains__(self, item): """Returns True if item is in the set or False otherwise.""" self._index = abs(hash(item)) % len(self._items) self._priorNode = Node self._foundNode = self._items[self._index] while self._foundNode != None: if self._foundNode.data == item: return True else: self._priorNode = self._foundNode self._foundNode = self._foundNode.next return False def __iter__(self): """Supports iteration over a view of self.""" cursor = 0 while cursor < len(self): yield self._items[cursor] cursor += 1 def __str__(self): """Returns the string representation of self.""" pass # Mutator methods def clear(self): """Makes self become empty.""" self._size = 0 self._array = Array(HashSet.DEFAULT_CAPACITY) def add(self, item): """Adds item to the set if it is not in the set.""" if not item in self: newNode = Node(item, self._items[self._index]) self._items[self._index] = newNode self._size += 1 def remove(self, item): """Precondition: item is in self. Raises: KeyError if item is not in self. PostCondition: item is removed from self.""" if not item in self: raise KeyError('Missing: ' + str(item)) self._items.pop(item)
# -*- coding:utf-8 -*- """ File: countfib.py Prints the number of calls of a recursive Fibonacci function with problem sizes that double. """ from ExampleCode.chapter1.counter import Counter def fib(n, counter): """Count the number of calls of the Fibonacci function.""" counter.increment() if n < 3: return 1 else: return fib(n-1, counter) + fib(n-2, counter) def liner_fib(n, counter): """Count the number of iterations in the Fibonacci function.""" sum = 1 first = 1 second = 1 count = 3 while count <= n: counter.increment() sum = first + second first = second second = sum count += 1 problemSize = 2 print("%12s%15s%15s" % ("Problem Size", "fib_Calls", "fib2_Calls")) for count in range(5): counter = Counter() counter2 = Counter() # The start of the algorithm liner_fib(problemSize, counter) fib(problemSize, counter2) # The end of the algorithm print("%12d%15s%15s" % (problemSize, counter, counter2)) problemSize *= 2
# -*- coding:utf-8 -*- """ 代码主要作用: """ class ArrayListIterator(object): """Represents the list iterator for an array list.""" def __init__(self, backingStore): """Set the initial state of the list iterator.""" self._backingStore = backingStore self._modCount = backingStore.getModCount() self.first() def first(self): """Resets the cursor to the beginning of the backing store.""" self._cursor = 0 self._lastItemPos = -1 def hasNext(self): """Returns True if the iterator has a next item or False otherwise.""" return self._cursor < len(self._backingStore) def next(self): """Preconditions: hasNext returns True. The list has not been modified except by this iterator's mutators. Returns the current item and advances the cursor to the next item.""" if not self.hasNext(): raise ValueError('No next item in list iterator') if self._modCount != self._backingStore.getModCount(): raise AttributeError('Illegal modification of backing store') self._lastItemPos = self._cursor self._cursor += 1 return self._backingStore[self._lastItemPos] def last(self): """Moves the cursor to the end of the backing store.""" self._cursor = len(self._backingStore) self._lastItemPos = -1 def hasPrevious(self): """Returns True if the iterator has a previous item or False otherwise.""" return self._cursor > 0 def previous(self): """Preconditions: hasPrevious returns True. The list has not been modified except by this iterator's mutators. Returns the current item ans moves the cursor to the previous item.""" if not self.hasPrevious(): raise ValueError('No previous item in list iterator') if self._modCount != self._backingStore.getModCount(): raise AttributeError('Illegal modification of backing store') self._cursor -= 1 self._lastItemPos = self._cursor return self._backingStore[self._lastItemPos] def replace(self, item): """Preconditions: the current position is defined. The list has not been modified except by this iterator's mutators.""" if self._lastItemPos == -1: raise AttributeError('The current position is undefined.') if self._modCount != self._backingStore.getModCount(): raise AttributeError('List has been modified illegally.') self._backingStore[self._lastItemPos] = item self._lastItemPos = -1 def insert(self, item): """Preconditions: The list has not been modified except by this iterator's mutators.""" if self._modCount != self._backingStore.getModCount(): raise AttributeError('List has been modified illegally.') if self._lastItemPos == -1: # Cursor nto defined, so add item to end of list self._backingStore.add(item) else: self._backingStore.insert(self._lastItemPos, item) self._lastItemPos = -1 self._modCount += 1 def remove(self): """Preconditions: the current position is defined. The list has not been modified except by this iterator's mutators.""" if self._lastItemPos == -1: raise AttributeError('The current position is undefined.') if self._modCount != self._backingStore.getModCount(): raise AttributeError('List has been modified illegally.') item = self._backingStore.pop(self._lastItemPos) # If the item removed was obtained via next, move cursor back if self._lastItemPos < self._cursor: self._cursor -= 1 self._modCount += 1 self._lastItemPos = -1
# -*- coding:utf-8 -*- """ 代码主要作用: """ from hashtable import HashTable class Profiler(object): """Represents a profiler for hash tables.""" def __init__(self): self._table = None self._collisions = 0 self._probeCount = 0 def test(self, table, data): """Inserts the data into table and gathers statistics.""" self._table = table self._collisions = 0 self._probeCount = 0 self._result = ('Load Factor Item Inserted ' 'Home Index Actual Index Probes\n') for item in data: loadFactor = table.loadFactor() table.insert(item) homeIndex = table.homeIndex() actualIndex = table.actualIndex() probes = table.probeCount() self._probeCount += probes if probes > 0: self._collisions += 1 line = '%8.3f%14d%12d%12d%14d' % (loadFactor, item, homeIndex, actualIndex, probes) self._result += line + '\n' self._result += ('Total collisions: ' + str(self._collisions) + '\nTotal probes: ' + str(self._probeCount) + '\nAverage probes per collision: ' + str(self._probeCount / self._collisions)) def __str__(self): if self._table is None: return 'No test has been run yet.' else: return self._result
# -*- coding:utf-8 -*- def main(): iteration_time = int(input("input a iteration time: ")) flag = -1 div4_result = 0 denominator = 1 while iteration_time > 0: div4_result -= 1 / denominator * flag iteration_time -= 1 flag *= -1 denominator += 2 print('the result is %6.8f' % (div4_result * 4)) if __name__ == "__main__": main()
# -*- coding:utf-8 -*- from project_09 import Book, Patron class Library: book_list = [] reader_list = [] # def __init__(cls): # cls.book_list = [] # cls.reader_list = [] @classmethod def add_book(cls, title, author, reader=None): """添加一本书""" book = Book(title, author, reader) cls.book_list.append(book) print('书本 %s 添加成功!' % book) @classmethod def del_book(cls, title, author): """删除一本书""" target_book = None for book in cls.book_list: if book.title == title and book.author == author: target_book = book break if target_book: cls.book_list.remove(target_book) print('书本 %s 删除成功!' % title) else: print('书本 %s 不存在!' % title) @classmethod def find_book(cls, title, author=None): """根据书名查找一本书 如果不存在则返回 -1,存在则返回 1""" titles = [b.title for b in cls.book_list] if title in titles: print('书本:%s 已找到!' % title) return 1 else: print('书本:%s 找不到!' % title) return -1 @classmethod def add_reader(cls, name): """添加一个读者""" reader = Patron(name) cls.reader_list.append(reader) print('读者 %s 添加成功!' % reader) @classmethod def del_reader(cls, name): """删除一个读者""" target_reader = None for reader in cls.reader_list: if reader.name == name: target_reader = reader break if target_reader: cls.reader_list.remove(target_reader) print('读者 %s 删除成功!' % target_reader) else: print('该读者不存在!') @classmethod def find_reader(cls, name): """根据读者名称查找一个读者 如果找到则返回 1,找不到则返回 -1""" names = [r.name for r in cls.reader_list] if name in names: print('读者:%s 已找到!' % name) return 1 else: print('读者:%s 找不到!' % name) return -1 if __name__ == '__main__': lib = Library() lib.add_book('python数据结构', '李军译', 'Cavin') lib.add_book('Spring实战第4版', 'MANNING', 'Cavin') lib.add_book('机器学习实战', 'Peter Harrington', 'Cavin') lib.find_book('机器学习实战') lib.del_book('Spring实战第4版', 'MANNING') print() lib.add_reader('柴剑波') lib.add_reader('Peter Harrington') lib.add_reader('John Smith') lib.add_reader('钟无艳') lib.find_reader('John Smith') lib.del_reader('钟无艳')
import matplotlib.pyplot as plt x_values = list(range(1, 1001)) y_values = [x**2 for x in x_values] # s表示点大小 # edgecolor表示轮廓颜色 # c表示点颜色 # p1t.scatter(x_values, y_values, s=40, edgecolor='none', c='red') # cmap设置颜色映射,数据从小到大,则颜色由浅变深 # 这里要设置点颜色c=y_values plt.scatter(x_values, y_values, s=40, edgecolor='none', c=y_values, cmap=plt.cm.Blues) # 设置图表标题并给坐标轴加上标签 plt.title("Square Numbers", fontsize=24) plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) # 设置刻度标记的大小 plt.tick_params(axis="both", which="major", labelsize=8) # 设置每个坐标轴的取值范围 plt.axis([0, 1100, 0, 1100000]) plt.show()
""" 输入学生考试成绩计算平均分 """ def main(): number = int(input("请输入学生人数:")) names = [None] * number scores = [None] * number for index in range(len(names)): names[index] = input("请输入第【%d】个学生的姓名:" % (index + 1)) scores[index] = float(input("请输入第【%d】个学生的成绩:" % (index + 1))) totalScore = 0 for index in range(len(names)): print("%s: %.1f 分" % ( names[index], scores[index])) totalScore += scores[index] print("平均分为: %.1f" % (totalScore / number)) if __name__ == "__main__": main()
import math radius = float(input('请输入圆的半径:')) peremeter = 2 * math.pi * radius area = math.pi * radius * radius print('圆的半径长%.2f,周长%.2f,面积%.2f' %(radius, peremeter, area))
name = input('請輸入名字: ') #遇到input 程式會等到使用者輸入才結束 print('嗨', name) #問完問題想要把回答儲存 取變數 把右邊的輸入東西存進name #先印出嗨這個單獨的字串 再印出name這個變數 這裡是印出兩個東西 一個字串和一個變數
class BinaryTree(): def __init__(self, val): self.value = val self.left = None self.right = None self.parent = None def set_left(self,node): self.left = node self.left.parent = self def set_right(self,node): self.right = node self.right.parent = self def inorder(self): left_vals = self.left.inorder() if self.left is not None else [] right_vals = self.right.inorder() if self.right is not None else [] return left_vals + [self.value] + right_vals if __name__ == '__main__': tree = BinaryTree(4) left = BinaryTree(3) left.set_left(BinaryTree(1)) left.set_right(BinaryTree(20)) right = BinaryTree(7) right.set_left(BinaryTree(6)) right.set_right(BinaryTree(30)) tree.set_left(left) tree.set_right(right) print tree.inorder()
# craps.py # # This program simulates the dice game craps. The user starts with $100 and is allowed to bet on the roll of two # six-sided dice: # # - A roll of 7 or 11 on the opening throw results in a win # - A roll of 2, 3, or 12 on the opening throw results in a loss # - A roll of anything else means the user has to re-roll the dice until that same number is rolled (a win) or a 7 is # rolled (a loss) # # A win pays whatever amount was bet. A loss takes the amount bet. The user can continue to play until he/she is out of # money. # # by Mr. Ciccolo import random cash = 0 bet = 0 def main(): global cash cash = 100 display_welcome() play_again = True # Boolean- Something that is either true and false while play_again: place_bet() total = roll_dice() if total == 7 or total == 11: print("You win!") print("You have $", cash, sep="") elif total == 2 or total == 3 or total == 12: print("You lose!") cash = bet - cash print("You have $", cash, sep="") else: re_roll(total) print() # Blank line for spacing if cash <= 5: play_again = False print("You lost! You have no money left! Feel free to vist www.gamblersanonymous.org") else: play_again = (input("Enter 'N' to quit! ") == '') clear_screen() def clear_screen(): for i in range(20): print() def display_welcome(): print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$") print("$ $") print("$ Welcome to the Computer Science Craps Table! $") print("$ $") print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$") print() #how to play? def roll_dice(): input("\nPress Enter to roll the dice...") # We don't do anything with the input, we're just using it to pause the game die1 = random.randrange(1, 7) die2 = random.randrange(1, 7) total = die1 + die2 print() print(" +---+ +---+") print(" |", die1, "| + |", die2, "| =", total) print(" +---+ +---+") print() return total def re_roll(point): global cash global bet print("You have to keep rolling until you get another", point) print() # Blank line for spacing total = roll_dice() while total != point and total != 7: total = roll_dice() if total == point: print("You win!") cash = cash + bet else: print("You lose!") cash = cash - bet print("You have $", cash, sep="") def place_bet(): global cash, bet raw_bet = input("You can bet $5-$" + str(cash) + ". How much do you want to bet?: ") while raw_bet == "": raw_bet = input("You can bet $5-$" + str(cash) + ". How much do you want to bet?: ") bet= eval(raw_bet) if bet < 5: print("\nHey, the minimum bet is $5. I'll let you off with warning and make it $5 this game") bet = 5 elif bet > cash: print("\nHey, you only have ", cash,", you can't bet ", bet,"!\nDon't play tricks on me! \nI see you feel lucky today, so I'll put down all you have", sep="") bet = cash main()
''' #acceptint user input x=int(input("Enter the value of x")) print(x) y=5 print(y) #multiplication a = 10 b = 20 c = a * b print(c) #mnemonic multiplication hrs=10 rate=5 pay=hrs*rate print(pay) #assignment operator g=0.5 print(g) g=3.9*g*(1-g) print ("This is new value of g :",g) #numeric expression xx=56 yy=25 zz=xx%yy print("It should dispaly the remainder:",zz) #type conversion #done in python shell #r=52 #t=25 #u=r+t #print(u) #>>> sval='123' #>>> type(sval) #<class 'str'> #>>> ival=int(sval) #>>> type(ival) #<class 'int'> #>>> print(sval+1) #Traceback (most recent call last): # File "<stdin>", line 1, in <module> #TypeError: can only concatenate str (not "int") to str #>>> print(ival+1) #124 #>>> r=53 #>>> t=25 #>>> u=r+t #>>> print(u) #78 #>>> type(u) #<class 'int'> #>>> r=53.5 #>> u=r+t #>>> print(u) #78.5 #>>>''' print(" end")
import math def loc_angle(c, a, b): numerator = math.pow(c, 2) - math.pow(a, 2) - math.pow(b, 2) denominator = -2*a*b frac = numerator / denominator result = math.acos(frac) return math.degrees(result) print(loc_angle(5, 4, 3))
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param intervals, a list of Intervals # @return a list of Interval def merge(self, intervals): i=0 #moveahead=0 while(i+1<len(intervals)): a=intervals[i].start b=intervals[i].end c=intervals[i+1].start d=intervals[i+1].end if (a==max(a,c) and b==max(b,d)): intervals[i].start=c intervals[i].end=d intervals[i+1].start=a intervals[i+1].end=b if not(max(a,c) > min(b,d)): intervals[i].start=min(a,c) intervals[i].end=max(b,d) del intervals[i+1] i=0 else: i+=1 #moveahead=1 #for i in intervals: # print(i.start,i.end) return intervals ''' class Solution: # @param intervals, a list of Intervals # @return a list of Interval def merge(self, I): res = [] I.sort(key=lambda i: i.start) for i in I: if not res or res[-1].end < i.start: res.append(i) else: res[-1].end = max(res[-1].end, i.end) return res #working '''
# To find where the target element should be inserted in the sorted list. #lightest class Solution: def searchInsert(self, nums: List[int], target: int) -> int: l = 0 r = len(nums) - 1 while l<=r: m = l + int((r-l) / 2) if nums[m] < target: l = m + 1 else: r = m - 1 return l #fastest 28 ms class Solution: def searchInsert(self, nums: List[int], target: int) -> int: lo, hi = 0, len(nums) - 1 while lo < hi: mid = (lo + hi) // 2 if nums[mid] == target: return mid elif nums[mid] < target: lo = mid + 1 else: hi = mid if lo == len(nums) - 1 and target > nums[-1]: return len(nums) return lo #32 ms class Solution: def searchInsert(self, nums: List[int], target: int) -> int: l, h = 0, len(nums)-1 while l <= h: m = l + (h-l) // 2 if nums[m] == target: return m if nums[m] < target: l = m+1 else: h = m-1 return l
class Solution: # @param A : list of list of integers # @return a list of list of integers def diagonal(self, A): m=len(A) n=len(A[0]) listy=[] for i in range(m+n-1): ni=[] for j in range(i+1): if(j>=m or i-j>=n): continue; k=i-j; ni.append(A[j][k]) listy.append(ni) return listy ''' Input: 1 2 3 4 5 6 7 8 9 Return the following : [ [1], [2, 4], [3, 5, 7], [6, 8], [9] ] '''
#using heapq class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: # graph g = defaultdict(lambda:[]) #heapq q= ["JFK":["ATL","SFO"]] for u,v in tickets: # to maintain sort heap heapq.heappush(g[u],v) ans = [] def go(s): # check if any airport need to travel from cur airport while g[s]: a = heapq.heappop(g[s]) # lets fly to a new airport go(a) # current journey has no next flight anymore ans.append(s) # Starting the journey go("JFK") # return with reversing the visited ans return ans[::-1] #fastest class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: #### By Euler path using DFS self.graph = collections.defaultdict(list) for frm,to in tickets: self.graph[frm].append(to) for k,v in self.graph.items(): v.sort() self.ans = [] self.DFS("JFK") return self.ans[::-1] def DFS(self,src): dest = self.graph[src] while dest: nextD = dest.pop(0) self.DFS(nextD) self.ans.append(src)
from stack_and_queue.node import Node class Queue: def __init__(self): self.front=None self.rear=None def enqueue(self, value): node=Node(value) if not self.rear: self.front=node self.rear=node else: self.rear.next=node self.rear=node def dequeue(self): pass def peek(self): pass def is_empty(self): return not self.front
from typing import List, Optional, Union, Dict import numpy as np import pandas as pd from feature_engine.base_transformers import BaseNumericalTransformer from feature_engine.variable_manipulation import _check_input_parameter_variables class CyclicalTransformer(BaseNumericalTransformer): """ The CyclicalTransformer() applies a cyclical transformation to numerical variables. There are some features that are cyclic by nature. Examples of this are the hours of a day or the months of a year. In both cases, the higher values of a set of data are closer to the lower values of that set. For example, December (12) is closer to January (1) than to June (6). The CyclicalTransformer() works only with numerical variables. Missing data should be imputed before applying this transformer. A list of variables can be passed as an argument. Alternatively, the transformer will automatically select and transform all numerical variables. Parameters ---------- variables : list, default=None The list of numerical variables that will be transformed. If None, the transformer will automatically find and select all numerical variables. max_values: dict, default=None A dictionary that maps the natural maximum or a variable. Useful when the maximum value is not present in the dataset. drop_original: bool, default=False Use this if you want to drop the original variables from the output. Attributes ---------- max_values_ : The maximum value of the cylcical feature that will be used for the transformation. Methods ------- fit: Learns the maximum values of the cyclical features. transform: Applies the cyclical transformation, creates 2 new features. fit_transform: Fit to data, then transform it. References ---------- http://blog.davidkaleko.com/feature-engineering-cyclical-features.html """ def __init__( self, variables: Union[None, int, str, List[Union[str, int]]] = None, max_values: Optional[Dict[str, Union[int, float]]] = None, drop_original: Optional[bool] = False ) -> None: if max_values: if not isinstance(max_values, dict) or not all( isinstance(var, (int, float)) for var in list(max_values.values())): raise TypeError( 'max_values takes a dictionary of strings as keys, ' 'and numbers as items to be used as the reference for' 'the max value of each column.' ) if not isinstance(drop_original, bool): raise TypeError( 'drop_original takes only boolean values True and False.' ) self.variables = _check_input_parameter_variables(variables) self.max_values = max_values self.drop_original = drop_original def fit(self, X: pd.DataFrame, y: Optional[pd.Series] = None): """ Learns the maximmum value of each of the cyclical variables. Parameters ---------- X : pandas dataframe of shape = [n_samples, n_features] The training input samples. Can be the entire dataframe, not just the variables to transform. y : pandas Series, default=None It is not needed in this transformer. You can pass y or None. Raises ------ TypeError If the input is not a Pandas DataFrame. ValueError: - If some of the columns contains NaNs. - If some of the mapping keys are not present in variables. Returns ------- self """ # check input dataframe X = super().fit(X) if self.max_values is None: self.max_values_ = X[self.variables].max().to_dict() else: for key in list(self.max_values.keys()): if key not in self.variables: raise ValueError(f'The mapping key {key} is not present' f' in variables.') self.max_values_ = self.max_values self.input_shape_ = X.shape return self def transform(self, X: pd.DataFrame): """ Creates new features using the cyiclical transformation. Parameters ---------- X : Pandas DataFrame of shame = [n_samples, n_features] The data to be transformed. Raises ------ TypeError If the input is not Pandas DataFrame. Returns ------- X : Pandas dataframe. The dataframe with the original variables plus the new variables if drop_originals was False, alternatively, the original variables are removed from the dataset. """ X = super().transform(X) for variable in self.variables: max_value = self.max_values_[variable] X[f'{variable}_sin'] = np.sin(X[variable] * (2. * np.pi / max_value)) X[f'{variable}_cos'] = np.cos(X[variable] * (2. * np.pi / max_value)) if self.drop_original: X.drop(columns=self.variables, inplace=True) return X
def validate_brackets(string): stack = [] for char in string: # If its opening bracket, so push it in the stack if char == '{' or char == '(' or char == '[': stack.append(char) # Else if its closing bracket then check if the stack is empty then return false or # Pop the top most element from the stack and compare it elif char == '}' or char == ')' or char == ']': if len(stack) == 0: return False top_bracket = stack.pop() # Compare whether two brackets are corresponding to each other if not compare(top_bracket, char): return False # Check if the stack is empty or not if len(stack) != 0: return False return True def compare(opening, closing): if opening == '(' and closing == ')': return True if opening == '[' and closing == ']': return True if opening == '{' and closing == '}': return True return False
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next class Queue: def __init__(self, node=None): self.front = node self.rear = node def enqueue(self, value): node = Node(value) if self.front is None: self.front = node self.rear = node return self self.rear.next = node self.rear = node return self def dequeue(self): if self.front is None: raise Exception("Queue is empty") temp = self.front.value self.front = self.front.next return temp def peek(self): if self.front is None: raise Exception("Queue is empty") return self.front.value def isEmpty(self): return self.front == None # if __name__ == "__main__": # pass
""" Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ import time def divisores(n): return [i for i in range(1, n // 2 + 1) if n % i == 0] # Menos pythonico, igual de eficiente, no mejora def divisores_2(n): suma = 0 for i in range(1, n // 2 + 1): if n % i == 0: suma += i return suma # Fuerza bruta O(N^2). No sirve para mas de 500 aprox def amigos_bruta(n): suma = 0 for i in range(4, n): sum_n1 = sum(divisores(i)) for j in range(max(i + 1, sum_n1), n): sum_n2 = sum(divisores(j)) if (sum_n1 == j and sum_n2 == i and sum_n1 > 0): print(i, j) suma += i + j return suma start = time.time() # A lo bruto pero menos. Calculo d(num) = suma para cada i # veo si d(suma) = num # Mucho mas rapido que el anterior, que es estupido. # Util, los saca, hay que comprobar que la suma no se sale # del rango, y para no repetir calculo llevo control de los # anteriores. Con un vector caracteristico sobra para con- # trolarlo, gastanto solo 2xn bytes def amigos_bruta_bis(n): suma = 0 numeros = [False] * (n + 1) for i in range(4, n): s = sum(divisores(i)) if not numeros[i] and s < n: numeros[s] = True if (i == sum(divisores(s)) and i != s): print(i, s) suma += i + s return suma print(amigos_bruta_bis(10000)) print("Tiempo es {:.5f} seg".format(time.time() - start)) start = time.time() # Funcion en C# con prog func. Buenas ideas # Func<int,int> divs = n => Enumerable.Range(1, n).Where(i => n % i == 0). # sum(); # Func<int,int,bool> areFriends = (a,b) => a!=b && divs(a) == divs(b); n = 1000 div = filter(lambda i, n: n % i == 0, range(1, n // 2 + 1)) amigos = lambda x, y: x != y and sum( divisores(x)) == y and sum(divisores(y)) == x #print(sum(divisores(220))) #print(sum(divisores(284))) # suma_div = lambda x, y: # amigos = [i for i in list(div) if ] # print(list(div(100))) print(amigos(220, 284)) print("Tiempo es {:.5f} seg".format(time.time() - start))
# The arithmetic sequence, 1487, 4817, 8147, in which each of the # terms increases by 3330, is unusual in two ways: # (i) each of the three terms are prime, and, # (ii) each of the 4-digit numbers are permutations # of one another. # # There are no arithmetic sequences made up of three 1-, 2-, # or 3-digit primes, exhibiting this property, but there is one # other 4-digit increasing sequence. # # What 12-digit number do you form by concatenating the three # terms in this sequence? from math import sqrt from itertools import permutations from timeit import timeit def problema049(): """ Metodo largo, pero facil y claro """ def is_prime(x): return all(x % i != 0 for i in range(2, int(sqrt(x) + 1))) dic = {} for i in range(1000, 9999): aux = [] todas_permutaciones = [] if is_prime(i): array = [i for i in str(i)] # creamos array con todos los valores que se pueden # formar a partir del numero, ordenados, sin repetir for j in permutations(array): tmp = int(''.join(j)) if tmp > 1000 and tmp not in todas_permutaciones: todas_permutaciones.append(tmp) todas_permutaciones.sort() # Para cada serie, vemos cuantos primos hay y los # anyadimos. # Con esta list comprehension extra es mas rapido # (si la hago con un loop extra tambien) que si anyado # directamente a aux en el loop anterior. Cosas # de python. aux = [j for j in todas_permutaciones if is_prime(j)] # Recorremos cada serie, y si algunas restas son # iguales, esa es j = 2 while j < len(aux): a = aux[j] - aux[j - 1] b = aux[j - 1] - aux[j - 2] if a == b: return aux j += 1 dic[i] = aux return -1 if __name__ == '__main__': # print(problema049()) # Medimos tiempos def wrapper(problema049, *args, **kwargs): def wrapped(): return problema049(*args, **kwargs) return wrapped wrapped = wrapper(problema049) veces = 100 print("{:.5f} seg por loop".format(timeit(wrapped, number=veces) / veces)) print("resultado: {}".format(problema049())) # con pypy bastante mejor que con cpython, aprox mitad de tiempo (algo mejor)
''' It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5) 24 cm: (6,8,10) 30 cm: (5,12,13) 36 cm: (9,12,15) 40 cm: (8,15,17) 48 cm: (12,16,20) In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles. 120 cm: (30,40,50), (20,48,52), (24,45,51) Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed? ''' from time import time from math import sqrt def find_sides(l): o = c = h = 0 hay_resultado = False for i in range(l//2 - 1, l//3, -1): h = i hs = i ** 2 limit = (l - h) // 2 for j in range(i - 1, limit, -1): o = j os = j ** 2 c = l - h - o cs = c ** 2 if cs + os == hs: if hay_resultado: return False hay_resultado = True if hay_resultado: return 1 return 0 def pytagoric_triplet(l): a = b = c = 0 n = int(sqrt(l)) + 1 m = 2*n / 3 for i in range(1, m): for j in range(i+1, n): if a + b + c != l: a = j*j - i*i b = 2*j*i c = j*j + i*i else: return 1 return 0 if __name__ == "__main__": start = time() res = 0 N = 150000 pytagoric_triplet(36) for i in range(2, N+1): res += pytagoric_triplet(i) print res, 'ternas primitivas' # for i in range(2, N+1, 2): # res += find_sides(i) # print res print 'total time =', (time() - start), 's'
def divisors(num): try: if num<0: raise ValueError("Tiene que ser numero positivo") divisors = [] for i in range(1,num + 1): if num % i == 0: divisors.append(i) return divisors except ValueError as ve: print(ve) return False def run(): try: num= int(input('Ingresa un numero: ')) print(divisors(num)) print('termino el programa') except ValueError: print("Debes ingresar un numero") if __name__=='__main__': run()
#Convert Decimal number to Binary Number dec_n=int(input("Enter number")) bin_n=0 k=1 while dec_n!=0: r=int(dec_n%2) bin_n=bin_n+(r*k) dec_n=dec_n/2 k=k*10 print(bin_n) '''output: Enter number10 1010'''
print ( "mengubah Huruf Kecil menjadi Kapital") print( "silahkan masukan huruf yang ingin diubah") a=input () #perintah input() untuk memasukkan string print("menjadi =", a.upper()) print("========================")
kısakenar = input("kısa kenarı giriniz") uzunkenar = input("uzun kenarı giriniz") cevre = (int(kısakenar) + int(uzunkenar)) alan = int(kısakenar) * int(uzunkenar) print("\nDikdörtgenin Çevresi : {0}".format(cevre)) print("\nDikdörtgenin Alanı : {0}".format(alan))
#!/usr/bin/python __author__ = 'Mayank' # Although normally set in a setter method, instance attribute values can be set anywhere # Encapsulation in python is a voluntary restriction # Python does not implement data hiding, as does java class MyClass(object): def set_val(self, val): self.val = val def get_val(self): return self.val a = MyClass() b = MyClass() a.set_val(9) b.set_val(65) a.val = "Breaking Encapsulation" print a.val print b.val
#!/usr/bin/python __author__ = 'Mayank' class MyInteger(object): def set_val(self, val): try: val = int(val) except ValueError: return self.val = val def get_val(self): return self.val def increment_val(self): self.val = self.val + 1 myint = MyInteger() myint.set_val(23) print myint.get_val() myint.increment_val() print myint.get_val() myint.set_val("hi") # Exception encountered, return gracefully without doing anything print myint.get_val() # value not set to hi myint.val = "hi" # Breaking Encapsulation print myint.get_val() print myint.increment_val() # Throws exception
#!/usr/bin/python __author__ = 'Mayank' import random class Animal(object): def __init__(self, name): self.name = name class Dog(Animal): def __init__(self, name): super(Dog, self).__init__(name) self.breed = random.choice(['Lebrador', 'German Shepherd', 'Bulldog', 'Golden Retriever']) for dog in (Dog('Spot'), Dog('Scooby'), Dog('Tom'), Dog('Timothy')): print '{0} belongs to {1} breed.'.format(dog.name, dog.breed)
# coding=utf-8 while 1 : words = input("谁是这个世界上最美的女生?") if words == "林嘉婷" : print("真聪明~") while 1: answer = input("你喜欢她吗?") if answer== "喜欢": print("她说她也喜欢你哦~") break else: print("我再问你一遍!") continue break else: continue
''' Class for drawing a Circuit in matplotlib or other output matplotlib output is generated by the PlotQCircuit library: https://github.com/rpmuller/PlotQCircuit Multi-bit gates will be displayed on the last bit with the others drawn as control bits. Example: ``` from circuit import QuantumCircuit from gate import * from util import pi from drawCircuit import DrawableCircuit circuit = QuantumCircuit() reg = circuit.newRegister(3, name='a') x, = circuit.borrowAncilla(1) H(reg) Rz(-3*pi/32)(reg[1]) P(pi/2)(reg) SWAP(reg[1], x) CX(reg[0], x) CRz(pi/3)(reg[1], reg[2]) drawable = DrawableCircuit(circuit, showArgs=True) drawable.plot(showLabels=True, scale=0.7) ``` ''' from circuit import QuantumCircuit from displayUtil import angleToLatex class DrawableCircuit: plotNameMap = {'CX':'CNOT', 'CCX':'TOFFOLI'} plotSpecial = {'M', 'CNOT', 'TOFFOLI', 'NOP', 'SWAP', 'CPHASE'} def __init__(self, circuit, showArgs=False): self.showArgs = showArgs self._buildFromCircuit(circuit) def _buildFromCircuit(self, circuit): self.history = list(circuit.history) # Make a copy #self.labels = ['q{}'.format(i) for i in range(circuit.n)] self.labels = [None] * circuit.n for regName, bits in circuit.regNames.items(): if regName == 'ancilla': for i, b in enumerate(bits): self.labels[b] = '0' elif len(bits) == 1: self.labels[bits[0]] = regName else: for i, b in enumerate(bits): self.labels[b] = '{}_{}'.format(regName, i) def _argToStr(self, arg): return angleToLatex(arg) def _gateNameStr(self, gate, nameMap={}, special=set()): name = nameMap.get(gate.name, gate.name) if self.showArgs and gate.args: return '${}({})$'.format(name, ','.join( map(self._argToStr,gate.args))) elif name in special: return name else: return '${}$'.format(name) def plot(self, showLabels=True, scale=0.75): import PlotQCircuit.plot_quantum_circuit as pqc plotList = [] for gate in self.history: name = self._gateNameStr(gate, self.plotNameMap, self.plotSpecial) if len(gate.bits) <= 0: bits = (0,) else: bits = gate.bits[::-1] entry = (name, *bits) plotList.append(entry) ids = range(len(self.labels)) inits = {i:self.labels[i] for i in ids} pqc.plot_quantum_circuit(plotList, inits=inits, labels=ids, plot_labels=showLabels, scale=scale)
from help import insertion_sort, test_k def quicksort(arr, k = 0, start = 0, end = None): if end is None: end = len(arr) - 1 if end <= start: return if len(arr) <= k: insertion_sort(arr) return div_ind = (start + end) // 2 divider = arr[div_ind] i, j = start, end while i <= j: while arr[i] < divider: i += 1 while arr[j] > divider: j -= 1 if i <= j: arr[i], arr[j] = arr[j], arr[i] i += 1 j -= 1 quicksort(arr, k, start, j) quicksort(arr, k, i, end) return arr if __name__ == "__main__": test_k(quicksort)
import random class HashTable: def __init__(self, M, C=None): if M == 0: raise Exception("M must be greater than 0") self.M = M self.C = C or 0.61 self.values = [None] * M @staticmethod def h1(number, M, C): return int(M * ((C * number) % 1)) @staticmethod def h2(number, M, C): return number % (M - 1) + 1 def __repr__(self): return "hash_table\n " + '\n '.join( [str(i) + ": " + str(x) for i, x in enumerate(self.values) if x is not None]) def add(self, value): x = HashTable.h1(value, self.M, self.C) y = HashTable.h2(value, self.M, self.C) for i in range(self.M): if self.values[x] == None or self.values[x] == value: self.values[x] = value return x = (x + y) % self.M raise Exception("no available space") def find(self, value): x = HashTable.h1(value, self.M, self.C) y = HashTable.h2(value, self.M, self.C) for i in range(self.M): if self.values[x] is not None: if self.values[x] == value: return x else: return None x = (x + y) % self.M return -1 def delete(self, value): key = self.find(value) if key == -1: raise Exception(f"no such a value {value}") else: self.values[key] = None if __name__ == "__main__": h = HashTable(1024) random.seed(1) for i in range(0, 800): h.add(random.randint(1, 10000)) print(h)
# -*- coding:utf-8 -*- ''' log api example: log('output is: ' + str(output)) ''' import numpy as np from log_api import log class Solution(): def solve(self, A): return np.poly1d(A) * np.poly1d(np.array([2.0, 0.0, -1.0, 1.0])) ''' 在Numpy中,多项式函数的系数可以用一维数组表示,例如对于f(x)=2x^3-x+1可表示为f=np.array([2.0,0.0,-1.0,1.0]),而np.poly1d()方法可以将多项式转换为poly1d(一元多项式)对象,返回多项式函数的值,请利用poly1d()方法计算多项式g(x)(例如g(x)=x^2+2x+1)和f(x)的乘积并将结果返回 Input / Output Input Example np.array([1.0, 2.0, 1.0]) Input Description 多项式g(x)的一维数组表示 Output Example np.poly1d([2.0,4.0,1.0,-1.0,1.0,1.0]) Output Description f(x)*g(x)的poly1d对象 ''' log(Solution().solve(np.array([1.0, 2.0, 1.0])))
# -*- coding:utf-8 -*- ''' log api example: log('output is: ' + str(output)) ''' from scipy.stats import chi2 from log_api import log class Solution(): def solve(self): data = ((154, 132), (180, 126), (104, 131)) total_x = (286, 306, 235) total_y = (438, 389) total = 827 c2 = 0 for i in range(0, 3): for j in range(0, 2): t = total_x[i] * total_y[j] * 1.0 / total c2 += (data[i][j] - t) ** 2 / t d = chi2.ppf(0.95, 2) return [2, round(c2, 2), c2 < d] ''' The table below summaries a data set that examines the response of a random sample of college graduates and non-graduate on the topic of oil drilling. Complete a chi-square test for test data to check whether there is a statistically significant difference in responses from college graduates and non-graduates. College Grad? Yes No Total Support 154 132 286 Oppose 180 126 306 Do not know 104 131 235 Total 438 389 827 Output Description [degree-of-freedom-of-distribution, statistical values, conclusion],'degree-of-freedom-of-distribution' and 'statistical values' are accurate to the second decimal place, 'conclusion' is True, which means the H0 is accepted, or False ''' log(Solution().solve())
import random def pickDices(): diceList = ['d4','d6','d6', 'd8','d8','d8','d8','d10','d10','d12','d20','d20','d20'] firstThreeDices = random.sample(diceList, 3) print("First three dices are: ", firstThreeDices) for dice in firstThreeDices: diceList.remove(dice) print("Remaining Dices to pick from: ", diceList) return random.sample(diceList, 2) def rollDice(diceType): diceRange = int(diceType[1:]) numRolled = random.randint(1,diceRange) print("The dice and number rolled are: ", diceType, numRolled) return numRolled def getSumOfDices(): dicePicked = pickDices() print("The two dices picked are: ", dicePicked) sum = 0 for dice in dicePicked: sum += rollDice(dice) print("The sum of number rolled in two dices is: ", sum) getSumOfDices()
import csv import copy """ This is a very useful class for Chris, and others who might work with CSV data often. The key data structure to know about is that each row is naturally stored as a dictionary where column names are keys as opposed to a list. Here are the assumptions made: If a row has missing elements, fill in with '' If a row has extra elements, ignore them All value types are strings! If you get a datum, you may modify it but the csv cols will not be impacted """ MISSING_VALUE = '' class SimpleCsv: def __init__(self, file_name = None): if not file_name: self.col_names = [] self.rows = [] return reader = csv.reader(open(file_name)) self.col_names = next(reader) self.rows = [] for row in reader: datum = self._make_datum(row) self.rows.append(datum) def __str__(self): result_str = '' result_str += self._header_str() + '\n' for row in self.rows: result_str += self._row_str(row) + '\n' return result_str.rstrip() def __iter__(self): self._iter_index = 0 return self def __next__(self): if self._iter_index >= len(self.rows): raise StopIteration next_row = self.rows[self._iter_index] self._iter_index += 1 return next_row def __len__(self): return len(self.rows) ################################################ # Candidates! # ################################################ def save(self, file_path): writer = csv.writer(open(file_path, 'w')) writer.writerow(self.col_names) for datum in self.rows: out_row = self._row_list(datum) writer.writerow(out_row) def to_dict(self, key_col_name): result = {} for datum in self: key = datum[key_col_name] result[key] = datum return result def get_col_names(self): return copy.deepcopy(self.col_names) def set_col_names(self, col_names): self.col_names = col_names def add_col_name(self, new_name): self.col_names.append(new_name) def add_row(self, row_dictionary): self.rows.append(row_dictionary) ################################################ # Helpers # ################################################ def _make_datum(self, row_list): datum = {} for i in range(len(self.col_names)): col_name = self.col_names[i] value = MISSING_VALUE if i < len(row_list): value = row_list[i] datum[col_name] = value return datum def _row_list(self, datum): result_list = [] for col_name in self.col_names: value = MISSING_VALUE if col_name in datum: value = datum[col_name] result_list.append(value) return result_list def _row_str(self, datum): result_str = '' for col_name in self.col_names: value = MISSING_VALUE if col_name in datum: value = datum[col_name] result_str += value + '\t' return result_str.rstrip() def _header_str(self): result_str = '' for value in self.col_names: result_str += value + '\t' return result_str.rstrip()
from room1 import Room from player1 import Player # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons."), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."""), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air."""), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.""") } # Link rooms together room['outside'].n_to = room['foyer'] room['foyer'].s_to = room['outside'] room['foyer'].n_to = room['overlook'] room['foyer'].e_to = room['narrow'] room['overlook'].s_to = room['foyer'] room['narrow'].w_to = room['foyer'] room['narrow'].n_to = room['treasure'] room['treasure'].s_to = room['narrow'] player = Player('outside') # Write a loop that: # # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. # # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. user = input("\n Options for travel are: \n\n [n] - north \n [s] - south \n [e] - east \n [w] - west \n [q] - quit \n\n In what direction would you like to travel: " ) while not user == "q": if user in ["n", "s", "e", "w"]: player.move_room(user) user = input("\n Options for travel are: \n\n [n] - north \n [s] - south \n [e] - east \n [w] - west \n [q] - quit \n\n In what direction would you like to travel: " ) print("Game Ended thank you for playing") # from player1 import Player # class Room: # def __init__(self, name, description, n_to = False, s_to = False, e_to = False, w_to = False): # self.name = name # self.description = description # self.n_to = n_to # self.s_to = s_to # self.e_to = e_to # self.w_to = w_to # def __repr__(self): # return "{self.name}, {self.description}".format(self=self) # room = { # 'outside': Room("Outside Cave Entrance", # "North of you, the cave mount beckons"), # 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty # passages run north and east."""), # 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling # into the darkness. Ahead to the north, a light flickers in # the distance, but there is no way across the chasm."""), # 'narrow': Room("Narrow Passage", """The narrow passage bends here from west # to north. The smell of gold permeates the air."""), # 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure # chamber! Sadly, it has already been completely emptied by # earlier adventurers. The only exit is to the south."""), # } # room['outside'].n_to = room['foyer'] # room['foyer'].s_to = room['outside'] # room['foyer'].n_to = room['overlook'] # room['foyer'].e_to = room['narrow'] # room['overlook'].s_to = room['foyer'] # room['narrow'].w_to = room['foyer'] # room['narrow'].n_to = room['treasure'] # room['treasure'].s_to = room['narrow'] # player = Player(room['outside']) # user = input("\n Options for travel are: \n\n [n] - north \n [s] - south \n [e] - east \n [w] - west \n [q] - quit \n\n In what direction would you like to travel: " ) # print(f"you find yourself in the {player.current_room.name} {player.current_room.description} ") # while not user == "q": # print(f"you find yourself in the {player.current_room.name} {player.current_room.description} ") # if user in ["n", "s", "e", "w"]: # direction = user # player.move(direction) # else: # print("incorrect input") # user = input("\n Options for travel are: \n\n [n] - north \n [s] - south \n [e] - east \n [w] - west \n [q] - quit \n\n In what direction would you like to travel: " ) # print("Game Ended thank you for playing")
answer = input("Would you like to play? (yes/no) ") if answer.lower().strip() == "yes": answer = input("you reach a crossroads, would you like to go left or right").lower().strip() if answer == "left": answer = input("you encounter a monster, would you like to run or attack.") if answer == "attack": print("You lost that was really stupid why would u fight a monster") else: print("Good choice dont fight monsters") answer = input("would you say you enjoyed this game? (yes/no)") if answer == "yes": print("aww thank you ;-;") else: print("go away then") elif answer == "right": print("you walk aimlessly to the right and fall on a patch of ice. You injure your leg and cannot continue. Game over!") else: print("go away")
''' Joseph Erwin Internship Game Project ''' from hero import Hero from os import path, chdir def selectHero(heroList, prompt): # Ask the user to provide input based on the prompt heroNum = int(input(prompt)) # Return the hero at the input index return heroList[heroNum] def heroCombat(heroes): # List all heroes and their indices print("Here are the heroes and their indices:") for i in range(len(heroes)): print("{}: {}".format(i,heroes[i].getName())) # Prompt the user for a selection of the heroes print("-"*50) # Ensure input is valid while True: try: hero1 = selectHero(heroes, "Select your first hero: ") hero2 = selectHero(heroes, "Select your second hero: ") break except: continue print("-" * 50) # Fight while at least one of the heroes has greater than 0 health while hero1.getHealth() > 0 and hero2.getHealth() > 0: # Print the health for each hero print("{} has {} health".format(hero1.getName(), hero1.getHealth())) print("{} has {} health".format(hero2.getName(), hero2.getHealth())) # Generate random powers for each hero h1Power = hero1.useRandomPower() h2Power = hero2.useRandomPower() # Determine winner of fight outcome = h1Power.fight(h2Power) # Depending upon outcome, inflict damage on heroes if outcome == 1: hero2.takeDamage() elif outcome == -1: hero1.takeDamage() else: hero1.takeDamage() hero2.takeDamage() print("-"*50) # Print out the result of the round if hero1.getHealth() > hero2.getHealth(): print(hero1.getName() + " WINS!") else: print(hero2.getName() + " WINS!") def main(): heroes = [] print("Welcome to the hero fighter!") print("-"*50) while True: print() printMenu() # Ask user for a selection choice = input("> ") # Ensure selection is an integer try: choice = int(choice) except: return # Load file if choice is 1 heroes = loadHeroes("heroes.txt") # Print roster of all heroes if choice is 2 if choice == 1: # Print roster of all loaded heroes printRoster(heroes) # Print a message to built excitement in the user's heart elif choice == 2: heroCombat(heroes) else: print("Quitting...") break def loadHeroes(fileName): # List to store lines of input file heroes = [] while True: # Ensure file name is valid; if not, request a valid one try: # Open file with open(fileName,"r") as file: # Iterate through file and append each line to the list for line in file: hero = Hero(line.strip()) heroes.append(hero) break except: fileDirec = input("Please input the correct path for the heroes.txt file: ") chdir(fileDirec) continue # return the hero list return heroes def printRoster(heroes): # tell the user how many heroes are loaded print("The following {} heroes are loaded...".format(str(len(heroes)))) # Print all heroes for i in heroes: print("*" * 50) print(i) print("*" * 50) def printMenu(): # Show options to user print("Choose an option:\n1. Print Hero Roster\n2. Hero Fight!\n3. Quit") main()
SIZE = 100 Q = [0] * SIZE front, rear = -1, -1 def isFull(): if rear == len(Q): return True else: return False def isEmpty(): if front == rear: return True else: return False def enQueue(item): global rear rear += 1 Q[rear] = item def deQueue(): global front front += 1 return Q[front] def Qpeek(): return Q[front+1] enQueue(1) enQueue(2) enQueue(3) print(Qpeek()) print(deQueue()) print(deQueue()) print(deQueue()) print(Q)
answer = [] oneBlock_dy = [1, -1, 0, 0] oneBlock_dx = [0, 0, 1, -1] diagonal_dy = [1, 1, -1, -1] diagonal_dx = [1, -1, 1, -1] def check_oneBlock(place, y, x): for i in range(4): if place[y][x] == 'P': Y = y + oneBlock_dy[i] X = x + oneBlock_dx[i] if 0 <= Y < 5 and 0 <= X < 5 and place[Y][X] == 'P': return False return True def check_twoBlock(place, y, x): for i in range(4): if place[y][x] == 'P': Y = y + (oneBlock_dy[i] * 2) X = x + (oneBlock_dx[i] * 2) if 0 <= Y < 5 and 0 <= X < 5 and place[Y][X] == 'P': if place[y + oneBlock_dy[i]][x + oneBlock_dx[i]] != 'X': return False return True def check_diagonal(place, y, x): for i in range(4): if place[y][x] == 'P': Y = y + diagonal_dy[i] X = x + diagonal_dx[i] if 0 <= Y < 5 and 0 <= X < 5 and place[Y][X] == 'P': if place[y][x+diagonal_dx[i]] != 'X' or place[y+diagonal_dy[i]][x] != 'X': return False return True def checkPlace(place): for y in range(5): for x in range(5): if place[y][x] == 'P': if not check_oneBlock(place, y, x): answer.append(0) return if not check_twoBlock(place, y, x): answer.append(0) return if not check_diagonal(place, y, x): answer.append(0) return answer.append(1) return def solution(places): for place in places: checkPlace(place) return answer print(solution([["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]]))
words = input() def my_strrev(words): long = int(len(words) // 2) re_words = list(words) for i in range(long): re_words[i], re_words[-i-1] = words[-i-1], words[i] return ''.join(re_words) print(my_strrev(words)) #-------------------------------- s = "Reverse this strings" s = s[::-1] print(s)
str1 = "abc 1, 2 ABC" print(str1) str1 = str1.replace("1, 2", "one, two") print(str1)
# 비트마스크 ############################################## # 공집합 zero = 0 print(bin(zero)) # '0b0' ############################################## # 꽉 찬 집합 ( 20 bit ) full = (1 << 20) - 1 print(bin(full)) # '0b11111111111111111111' # '0b100000000000000000000'(21bit) 에서 1을 뺀 2진수 20bit 전체가 1인 2진수 ############################################## # 원소의 포함 여부 확인 # python 은 2진수가 str 형으로 표현됨 a = 1 << 19 # '0b10000000000000000000' b = 1 << 5 # '0b100000' if(a & b): print('YES') else: print('No') # No ############################################## # 원소의 삭제 a = int('0b11111', 2) b = int('0b00100', 2) c = a & ~b print(bin(c)) # '0b11011' # b 의 원소 삭제 ############################################## # 원소의 토글 a = int('0b11011', 2) b = int('0b00100', 2) a ^= b print(bin(a)) # a = '0b11111' a ^= b print(bin(a)) # a = '0b11011' ############################################## # 최소 원소 지우기 a = int('0b100100100', 2) b = a - 1 print(bin(b)) # a = '0b100100100' # b = '0b100100011' # b 는 켜져있는 최 하위 bit 를 끄고 그 밑의 bit 를 전부 켠 것 c = a & b print(bin(c)) # c = '0b100100000' ############################################## # 모든 부분집합 순회하기 origin = int('0b1101', 2) subset = origin while True: subset = (subset - 1) & origin if subset == 0: break print(bin(subset)) # 0b1100 -> 1100 # 0b1001 -> 1001 # 0b1000 -> 1000 # 0b101 -> 0101 # 0b100 -> 0100 # 0b1 -> 0001
from generallibrary.functions import Operators import time from datetime import datetime import pytz from dateutil import parser from dateutil.tz import gettz import timeit class Timer: """ Callable class to easily time things and print. """ def __init__(self, start_time=None): """ Returns a started Timer instance. :param float start_time: Defaults to time in seconds since epoch (time.time()) """ self.start_time = self.reset(start_time=start_time) def reset(self, start_time=None): """ Reset and start timer. """ if start_time is None: start_time = time.time() self.start_time = start_time return start_time def seconds(self): """ Get seconds passed since timer started or was reset. """ return time.time() - self.start_time def print(self, reset=False): """ Print seconds passed. """ print(f"Seconds passed: {self.seconds()}") if reset: self.reset() @classmethod def deco(cls, iterations=1): def _deco(func): def _wrapper(*args, **kwargs): timer = timeit.default_timer() for _ in range(iterations): result = func(*args, **kwargs) print(f"Seconds for {iterations} iterations of '{func.__name__}': {timeit.default_timer() - timer}") return result return _wrapper return _deco def sleep(seconds): """ Normal sleep function from time package. :param float seconds: Time in seconds to sleep. """ time.sleep(seconds) @Operators.deco_define_comparisons(lambda date: date.datetime) class Date: """ Simplify datetime, truncating seconds and microseonds for now. """ timezone = "Europe/Paris" format = "%Y-%m-%d %H:%M %Z" def __init__(self, date): if isinstance(date, Date): datetime = date.datetime else: if isinstance(date, str): datetime = parser.parse(date, tzinfos={"CET": gettz("CET"), "CEST": gettz("CEST")}) else: datetime = date if str(datetime.tzinfo) != self.timezone: datetime = self.get_timezone_obj().localize(datetime.replace(tzinfo=None)) datetime = datetime.replace(second=0, microsecond=0) self.datetime = datetime @classmethod def get_timezone_obj(cls): return pytz.timezone(cls.timezone) @classmethod def now(cls): return Date(datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(cls.get_timezone_obj())) def __sub__(self, other): difference = self.datetime - Date(other).datetime return difference.total_seconds() def __str__(self): return self.datetime.strftime(self.format) def __repr__(self): return str(self) # return repr(self.datetime)
import sys if sys.argv[1] == "-": linia = raw_input() znak = "" while linia != znak: if linia.find(sys.argv[2])>-1: print (linia) linia = raw_input() linia = "" else: with open(sys.argv[1],"r") as plik: if linia.find(sys.argv[2])>-1: print linia
""" This class is responsible for the lecturer announcements feature so students can see the latest announcements from LiC """ from database.DataBaseManager import DataBaseManager class AnnouncementsGetter: def __init__(self, database_manager=DataBaseManager()): """Instantiate with a database instance which will be used to perform lookups. :param database_manager: Database instance :type: DataBaseManager """ self.database_manager = database_manager def delete_announcement(self, cid): """Delete an announcement :param cid: course id of the course that has the announcement you want to delete :type: str :return: database operation result :rtype: str """ cid = cid.upper() query = "DELETE FROM announcement WHERE cid = %s" inputs = (cid, ) return self.database_manager.execute_query(query, inputs) def add_announcement(self, cid, c_name, content, date): """Update the announcement of a course for a student in the databse :param cid: course code :type: str :param content: anncouncement :type: str :param date: the date of published anncouncement :type: var :return: database operation result :rtype: str """ query = "INSERT INTO announcement(cid, c_name, content, date) VALUES (%s, %s, %s, %s)" inputs = (cid, c_name, content, date, ) return self.database_manager.execute_query(query, inputs) def get_announcement(self, cid): """Perform the search for announcement of a given course :param cid: course id of the course to search :type: str :return: Announcement for a course :rtype: str """ cid = cid.upper() query = "SELECT * from announcement where cid = %s" inputs = (cid, ) result = self.database_manager.execute_query(query, inputs) if result: announcement = "Announcement for {} ({}): {}".format(result[0][0], result[0][3], result[0][2]) else: announcement = "No announcement for this {}".format(cid) return announcement
""" This file contains the Authenticator class which is responsible for checking if a credential entered is correct or not and also give authority level to the user logging in. """ from database.DataBaseManager import DataBaseManager from conf.Logger import Logger """ Logger setup """ logger = Logger(__name__).log class Authenticator: def __init__(self, database_manager=DataBaseManager()): """Initialise the Authenticator using the provided database instance :param database_manager: Database instance :type: DatabaseManager """ self.database_manager = database_manager def check_is_admin(self, username, password): """Check if user is an admin or not by using an SQL query against the database with the given credentials :param username: username :type: str :param password: password :type: str :return: if user is admin or not :rtype: bool """ query = "SELECT type FROM users WHERE username = %s AND password = %s" inputs = (username, password, ) result = self.database_manager.execute_query(query, inputs) return True if len(result) == 1 and result[0][0] == 'admin' else False def check_is_student(self, username, password): """Check if user is an student or not by using an SQL query against the database with the given credentials :param username: username :type: str :param password: password :type: str :return: if user is student or not :rtype: bool """ query = "SELECT type FROM users WHERE username = %s AND password = %s" inputs = (username, password, ) result = self.database_manager.execute_query(query, inputs) return True if len(result) == 1 and result[0][0] == 'student' else False
""" Algorytm 18 1) Stwórz listę 'f' wypełnioną 1 i listę 'F' wypełnioną 2 (1...n). 2) Zdefiniuj zmienną boolowską 'koniec' i przypisz jej False. 3) Dopóki 'koniec' nie jest True, to wypisuj tablicę 'f'. 4) Przypisz 'j' wartośc 'n', jeśli f[j] jest równe F[j] to zmniejszaj 'j' o 1. 5) Gdy wartość 'j' jest większa od 1 to wartość elementu f[j] zostaje zwiększona o 1, a wszystkie elementy leżące na prawo przypisujemy 1, uaktualniając jednocześnie tablice F. 6) Uaktualnienie to polega na tym, że jeżeli nowa wartość f[j] daje f[j] == F[j], to wszystkie elementy tablicy F leżące na prawo przyjmują wartość F[j] + 1, a w przeciwnym razie przyjmują one wartość F[j]. 7) Proces (3-6) kończymy gdy koniec = True ('j' jest mniejsze lub równe 1). """ def generuj_rgf(n): f = [1 for _ in range(n)] F = [2 for _ in range(n)] koniec = False while not koniec: print (f) j = n while True: j = j - 1 if f[j] != F[j]: break if j > 0: f[j] = f[j] + 1 for i in range(j + 1, n): f[i] = 1 if f[j] == F[j]: F[i] = F[j] + 1 else: F[i] = F[j] else: koniec = True generuj_rgf(4) # [1, 1, 1, 1] # [1, 1, 1, 2] # [1, 1, 2, 1] # [1, 1, 2, 2] # [1, 1, 2, 3] # [1, 2, 1, 1] # [1, 2, 1, 2] # [1, 2, 1, 3] # [1, 2, 2, 1] # [1, 2, 2, 2] # [1, 2, 2, 3] # [1, 2, 3, 1] # [1, 2, 3, 2] # [1, 2, 3, 3] # [1, 2, 3, 4] """ 1) Idea algorytmu polega na znalezieniu pierwszej pozycji z prawej strony tablicy f, dla której f[j] != F[j]. """
# Find the best response to any tic-tac-toe board configuration. # taking a memoized approach. # This could be used as a starting point for a full game with the ability # to play tic-tac-toe against an intelligent computer. # It also serves as an example for how to find brute-force solutions for # more complex games where straightforward logic would not be possible. # This version does not take advantage of the symmetries of the board. # Xan Vongsathorn # 7/7/2014 import itertools from time import clock class TicTacToe(): """Implements the basic components of a tic-tac-toe solver. best_responses is a dictionary where: * each key represents a board, e.g. key = (-1, 0, 0, 1, 1, 0, 0, 0, 0), where key[0:3] is the first row, and so forth. 1, -1, and 0 represent an X, an O, and unfilled square respectively. * each value is a tuple, (move, value), where: * move: an int in range(9) indicating where the player should move, or None if there is nowhere left to go. * value: the value of that move to the player who makes it. value = +1/-1/0 for a win/loss/draw, respectively. Note: given a board, the corresponding (move, value) is from the perspective of the player whose turn it is to go next. It is assumed without loss that X always goes first; thus, because X's and O's alternate, we can always tell whose turn it is given the board configuration. """ def __init__(self, WIDTH=3): self.WIDTH = WIDTH self.SIZE = WIDTH ** 2 self.NUM_DIAGS = 2 self.best_responses = {} def build_best_responses(self, board=None, player=None): """Recursively compute best responses for all subgames of current board. Call with no arguments to build the entire best_responses dict. This adds a key to best_responses for each possible board configuration that could follow from board. player = 1 for X, -1 for O. This is the current player, i.e. the one who goes next given the current board. """ # Initialize if board is None: board = (0,) * self.SIZE player = 1 if board in self.best_responses: return win = self.check_win(board, player) # If win/loss/draw has been determined, the game is over. if win is not None: self.best_responses[board] = (None, win) # None => no move needed return # If we don't know the best response yet, compute it. best_value = -2 for i, val in enumerate(board): if val == 0: # create new tuple with player's move in ith slot board2 = board[:i] + (player,) + board[i+1:] # If board2 is already in best_responses, this does nothing. # Otherwise, it ensures board2 is added to best_responses. self.build_best_responses(board2, -1 * player) # The player's value given board2 is the reverse of the next # player's value value = -1 * self.best_responses[board2][1] if value > best_value: best_value, best_move = value, i self.best_responses[board] = (best_move, best_value) def check_win(self, board, player): """Evaluate the current board to determine if there is a winner. Returns 1 if player wins, 0 if draw, -1 if loses, and None if no winner is yet determined. """ lines = ([self.get_row(board, i) for i in range(self.WIDTH)] + [self.get_col(board, i) for i in range(self.WIDTH)] + [self.get_diag(board, i) for i in range(self.NUM_DIAGS)] ) # First check for win/loss, i.e. row/col/diag with three 1's or three -1's. for t in lines: winner = sum(t) if winner == self.WIDTH or winner == -self.WIDTH: # 3 in a row, X's or O's. winner /= self.WIDTH # Transform winner to be +-1 from player's perspective, not X's: return winner * (player == 1) - winner * (player == -1) if board.count(0) == 0: return 0 # draw else: return None # game not over yet def get_row(self, board, i): "Return row i of board as a list." return board[i*self.WIDTH:(i+1)*self.WIDTH] def get_col(self, board, j): "Return column j of board as a list." return [board[i*self.WIDTH + j] for i in range(self.WIDTH)] def get_diag(self, board, i): "Return main diagonal if i = 0, other diagonal if i = 1" if i == 0: return [board[(self.WIDTH+1) * i] for i in range(self.WIDTH)] else: return [board[(self.WIDTH-1) + (self.WIDTH-1)*i] for i in range(self.WIDTH)] # Some sample tests, not very high coverage. class TestTicTacToe(): def test(self): print "\n---RUNNING TESTS---\n" self.test_check_win() self.test_build_best_responses() print "\n---ALL TESTS PASS---\n" def test_check_win(self): game = TicTacToe() assert game.check_win((0,0,0, 0,0,0, 0,0,0), -1) is None assert game.check_win((1,1,-1, 0,0,0, 0,0,0), -1) is None assert game.check_win((1,-1,-1, 0,1,0, 0,0,1), -1) == -1 assert game.check_win((1,1,1, 0,0,0, -1,-1,0), -1) == -1 assert game.check_win((1,1,-1, 1,0,-1, 0,0,-1), 1) == -1 assert game.check_win((1,1,1, -1,0,-1, 0,0,-1), 1) == 1 assert game.check_win((1,1,-1, -1,-1,1, 1,1,-1), 1) == 0 print 'test_check_win passes' def test_build_best_responses(self): game = TicTacToe() game.build_best_responses() assert game.best_responses[(1,1,0, 0,-1,-1, 0,0,0)] == (2, 1) # Since the solver has no preference for winning sooner rather than # later, it won't necessarily choose the move that ends the game # when it could do another move that also leads to an eventual win. # assert best_responses[(1,0,0, 1,-1,-1, 0,0,0)] == (6,1) # actually == (1,1) # But at least we can check that it DOES expect to win given such a board. assert game.best_responses[(1,0,0, 1,-1,-1, 0,0,0)][1] == 1 print 'test_build_best_responses passes' def funtime(fun, *args): "Time the execution of function fun" t0 = clock() fun(*args) t1 = clock() print "Runtime: ", t1-t0 if __name__ == '__main__': tests = TestTicTacToe() tests.test() print "Timing for WIDTH = 3..." tictactoe = TicTacToe(3) funtime(tictactoe.build_best_responses) print "Size of best_responses:", len(tictactoe.best_responses)
numeros = [0] * 6 # Ler os valores for i in range(6): numeros[i] = int(input('Valor: ')) # Verificar se são distintos distintos = True for i in range(6): # Verificar se o números da vez (i) é igual algum valor que # está após ele (j) na coleção. for j in range(i + 1, 6): # Se forem iguais, podemos concluir que a coleção não é distinta if (numeros[i] == numeros[j]): distintos = False break # pode parar de verificar if (distintos == False): break if (distintos == True): print("Números distintos") else: print("Números não distintos")
''' Para ler 4 números. Calcule e informe a soma dos números lidos! ''' soma = 0 qtde_pos = 0 qtde = int(input('Quantidade de iterações: ')) for i in range(qtde): num = int(input('Informe o {} valor: '.format(i + 1))) soma = soma + num if (num > 0): qtde_pos += 1 # soma += num print(soma)
while(True): abriu_i = False abriu_b = False try: texto = input() texto_out = '' for s in texto: if (s == '_'): if (not abriu_i): texto_out += '<i>' abriu_i = True else: texto_out += '</i>' abriu_i = False elif (s == '*'): if (not abriu_b): texto_out += '<b>' abriu_b = True else: texto_out += '</b>' abriu_b = False else: texto_out += s print(texto_out) except EOFError: break
lista1 = [1,2,3,4] lista2 = [5,6,7,8] lista3 = lista1 + lista2 lista4 = lista3[4:len(lista3)] print(lista1, len(lista1)) print(lista2, len(lista2)) print(lista3, len(lista3)) print(lista4, len(lista4))
# Converter em maiúsculo # minúsculo: [97 - 122] palavra = input('Palavra: ') nova_palavra = '' for i in range(len(palavra)): #if (ord(palavra[i]) >= 97) and (ord(palavra[i]) <= 122): if (palavra[i] >= 'a') and (palavra[i] <= 'z'): nova_palavra += chr(ord(palavra[i]) - 32) else: nova_palavra += palavra[i] print(palavra) print(nova_palavra)
numeros = [0] * 10 # Ler os 10 valores for i in range(10): numeros[i] = int(input('Número: ')) # Exibir os números ímpares digitados for i in range(10): if (numeros[i] % 2 == 1): print(numeros[i])
# select only one element from each list, apply square data = [[1, 2, 3, 4], [5, 6, 7, 8], [8, 9, 10]] def getCartezianProduct(N): # storing 1st row elements as lists in product product = [[x] for x in N[0]] rest_rows = N[1:] for i in range(0, len(rest_rows)): # tmp will store cartezian products tmp = [] # iterate through rest rows for n in rest_rows[i]: # print(n) # iterating through list items in product for j in product: # fetching elements from list items of products element = [x for x in j] # appending current elemnt of input data element.append(n) # storing cartezian product in tmp for each elemnts of current row tmp.append(element) # print(tmp) # replacing product with product till ith or current row product = tmp return product product = getCartezianProduct(data) print(product)
# -*- coding: utf-8 -*- """ Created on Fri Jul 24 10:11:43 2020 @author: DAVID CAIZALUISA """ import numpy as np from random import randint print("Ingrese la cantidad de filas que desea: ") fis=int(input()) print("Ingrese la cantidad de columnas que desea: ") colu=int(input()) print("\n"*0) matrix=np.zeros([fis,colu]) m=fis b=fis fy=-1 clu=-1 for q in range(0,fis): for n in range(0,colu): matrix[q][n]=int(randint(0,99)) print(" La matriz ejecutada es de",fis,"x",colu,) print("\n"*0) print(matrix) print("\n"*0) print('El valor de la diagonal principal de la matriz es: ') print("\n"*0) for r in range(0,fis): if fy<fis: fy+=1 m-=1 print(' | 0 |'*fy,"|",int(matrix[r][fy])," |",'| 0 | '*m) print('El valor de la diagonal secundaria de la matriz es: ') print("\n"*0) for t in range(0,fis): if clu<fis: clu+=1 b-=1 print(' | 0 |'*b,"|",int(matrix[t][b]),"|",'| 0 | '*clu)
#Question 1 list=[] n=int(input("Enter how much integers you want in list\n")) print("Enter elements") for i in range(n): a=int(input()) list.append(a) print(list) #Question 2 list2=['google','apple','facebook','microsoft','tesla'] list.extend(list2) print(list) #Question 3 list3=[1,1,2,3,4,3,4,5,3,2,3,3] print(list3.count(3)) #Question 4 list4=[20,11,13,7,8,100,45,23] list4.sort() print(list4) #Question 5 l1=[1,10,2,6,8] print("list 1 is: ",l1) l2=[31,24,3,5,21,32] print("list 2 is: ",l2) l1.sort() l2.sort() print("sorted list1 is: ",l1) print("sorted list2 is: ",l2) l1.extend(l2) print("merged is: ",l1) l1.sort() print("sorted merged list is: ",l1) #Question 6 countEve=0 countOdd=0 for i in l1: if(i%2==0): countEve+=1 else: countOdd+=1 print("Odd count: " , countOdd) print("Even count: ",countEve)
class FormattedWord: def __init__(self, word, capitalize=False) -> None: self.word = word self.capitalize = capitalize class Sentence(list): def __init__(self, plain_text): for word in plain_text.split(' '): self.append(FormattedWord(word)) def __str__(self) -> str: return ' '.join([ formatted.word.upper() if formatted.capitalize else formatted.word for formatted in self ]) if __name__ == '__main__': sentence = Sentence('hello world') sentence[1].capitalize = True print(sentence)
from copy import deepcopy class Address: def __init__(self, street, suite, city) -> None: self.street = street self.suite = suite self.city = city def __str__(self) -> str: return f'{self.street}, Suite #{self.suite}, {self.city}' class Employee: def __init__(self, name, address) -> None: self.name = name self.address = address def __str__(self) -> str: return f'{self.name} works at {self.address}' class EmployeeFactory: main_office_employee = Employee('', Address('123 East Dr', 0, 'London')) aux_office_employee = Employee('', Address('123B East Dr', 0, 'London')) @staticmethod def __new_employee(proto, name, suite): result = deepcopy(proto) result.name = name result.address.suite = suite return result @staticmethod def new_main_office_employee(name, suite): return EmployeeFactory.__new_employee( EmployeeFactory.main_office_employee, name, suite ) @staticmethod def new_aux_office_employee(name, suite): return EmployeeFactory.__new_employee( EmployeeFactory.aux_office_employee, name, suite ) if __name__ == '__main__': john = EmployeeFactory.new_main_office_employee('John', 101) jane = EmployeeFactory.new_aux_office_employee('Jane', 500) print(john) print(jane)
#Create board, an array of arrays board=[['BR','BKn','BB','BQ','BK','BB','BKn','BR'],['BP','BP','BP','BP','BP','BP','BP','BP'],['','','','','','','',''],['','','','','','','',''],['','','','','','','',''],['','','','','','','',''],['WP','WP','WP','WP','WP','WP','WP','WP'],['WR','WKn','WB','WQ','WK','WB','WKn','WR']] record=['p1name','p2name'] #The record is a history of an individual game. The first two rows should contain the #names of the players, to be created when we have a 'tournament' program. #The following elements in the record array will be the moves, which is an array itself. def updaterecord(move): global record record.append(move) return record def updateboard(move): global board [p,x1,y1,x2,y2]=move; board[x2][y2]=board[x1][y1] board[x1][y1]='' return board #Sample move. This would be passed to master from the players move=[1,6,0,4,0] #first number identifies player number, e.g. 1 = white print checklegal(board,move) if checklegal(board,move)==1: updaterecord(move) updateboard(move) print record print board
def conversacion(mensaje): print('Hola') print('Como estás') print(mensaje) print('Adios') opcion = int(input('Elige una opcion: (1, 2, 3): ')) if opcion == 1: conversacion('Elegiste la opcion 1') elif opcion == 2: conversacion('Elegiste la opcion 2') elif opcion == 3: conversacion('Elegiste la opcion 3') else: print('Elige una opcion correcta') # def sumar(a, b): # print('Se sumarán 2 números: ') # suma = a + b # return suma # resultado = sumar(4, 5) # print(resultado)
import datetime # imports the datetime fields needed for the game print('---------------------------------') print(' BIRTHDAY APP') # gives name of the game print('---------------------------------') print() year= int(input('what year were you born in [YYYY]:')) # asking for year of birth month = int(input('what month were you born in [MM]: ') )# asking for month of birth day = int(input('what day were you born in [DD]: ') )# asking for the day of birth date_birth=datetime.date(year,month,day) # makes the date of birth date_today_orig=datetime.date.today() # gets todays date date_today=datetime.date(date_birth.year,date_today_orig.month,date_today_orig.day) # normalizes today's date to the # year the person is born so years will not be counted in the days num_days_between=date_birth-date_today # takes the difference in days if num_days_between.days > 0: # checks for days left until birthday print('There are %i days left until your birthday' %num_days_between.days) # outputs the number of days left # until the person's birthday print('I hope you are looking forward to your birthday') elif num_days_between.days < 0: # checks for how many days passed after birthday occured print('your birthday was %i days ago'%abs(num_days_between.days))# outputs the number of days since the persons # birthday print('I hope you enjoyed your birthday') else: # checks if the date is the person's birthday print('Today is your birthday. Happy birthday.')
print('-------------------------------------') print(' SEARCHING APP ') print('-------------------------------------') # imports all required libraries import os import time arb=None # main function def main(): filename = None while filename is None: # asks for the name and directory of the file filename = str(input("What is the /path/to/the/file? ")) # Check if the filename exists. # checks if the directory exists if not os.path.exists(filename): print("That file could not be found. Try again.") filename = None while arb is None: # asks for the word desired to be searched from suer string_search=str(input("Type in the words that are desired to be searched within the file")) if len(string_search)==0: print("You cannot search without criteria or words to searhc for") continue if string_search!=0: break # lists all directories filenames_list=os.listdir(filename) print(filenames_list) # prints directories col=0 while col <len(filenames_list): # runs as many times as files found in directory files=os.path.join(filename,filenames_list[col]) [line,lines_num]=word_searcher(files,string_search) if len(line)==0: # prints out the line with the word within the file print("found nothing within the file: %s" %(filenames_list[col])) else: print("found %i mathes in the file: %s"%(len(line),str(filenames_list[col]))) x=1 while x<=len(line): time.sleep(1) # time stop 1 sec for delay so you can read the line print("found %s in line %s with the line containing the string: %s" %(string_search,lines_num[x-1],str(line[x-1]))) x+=1 col+=1 print("Thanks for searching") def word_searcher(files,string_search): lines=[] lines_num_arr=[] line_num: int=1 #print(files) with open(files,mode='r') as handle: # opens the file as a read file to see matching words for liner in handle: liner=str(handle.readline()) #print(liner) # opens and reads teh file and finds matching word within that file if liner.find(string_search)>=0: lines.append(liner) lines_num_arr.append(line_num) line_num+=1 return [lines,lines_num_arr] # returns line and the line number if __name__ == '__main__': main()
""" Example of Decision Tree Algorithms usage. This Example uses the Play tennis Dataset from Kaggle: https://www.kaggle.com/datasets/fredericobreno/play-tennis """ import pandas as pd from mlkit.classification.decision_tree import DecisionTree def example_tennis_categorical(): target = 'target' df = pd.read_csv('examples/datasets/play_tennis_continuous.csv') model = DecisionTree() model.fit(df.drop(target, axis=1), df[target]) x_test = pd.DataFrame({'Outlook': ['Sunny'], 'Temperature': ['Hot'], 'Humidity': ['Normal'], 'Wind': ['Weak']}) print(model.predict(x_test)) if __name__ == '__main__': example_tennis_categorical()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 5 14:02:34 2017 @author: janusboandersen """ #inputfile = "dna.txt" #f = open(inputfile, "r") #seq = f.read() inputfile = "dna.txt" def read_seq(inputfile, cds_start=0, cds_stop=0, mod_crop=1): """ Reads and returns the input sequence with special characters removed. Arguments: cds_start=integer: the CDS range starting position cds_stop=integer: the CDS range stopping position mod_crop=integer: crops the length of the sequence to fit codons as multiples of the specified length. Cropping occurs before extraction of CDS sequence. """ with open(inputfile, "r") as f: seq = f.read() #remove newline (n) and carriage return (r) seq = seq.replace("\n", "") seq = seq.replace("\r", "") #Remove any last hanging characters crop = len(seq) % mod_crop seq = seq[0:len(seq)-crop] #Extract the CDS sequence if cds_start > 0 and cds_stop > cds_start: #convert to 0-indexed cds_start -= 1 #cds_stop stays the same -1 for zero-index, +1 to ensure the last char is included. #extract the sequence seq = seq[cds_start:cds_stop] #Return the sequence return seq; def translate(seq): """ Translate a string containing a nucleotide sequence into a string containing the corresponding sequence of amino acids . Nucleotides are translated in triplets using the table dictionary; each amino acid 4 is encoded with a string of length 1. """ #translation table of codons to amino acids # _ underscores are nature's stop codons. table = { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W', } #The protein is a sequence of amino acids protein = "" # Check that the length of the string is divisible by 3 if len(seq) % 3 == 0: # Valid sequence - proceed # Loop over the sequence for i in range(0, len(seq), 3): # Extract a single codon (3-letter string) codon = seq[i:i+3] # Look up each codon (3-letter string) and store the result # Concatenating to generate an amino acid sequence protein += table[codon] else: pass return protein; #### end of function translate #### NM207618_2 = read_seq(inputfile, cds_start=21, cds_stop=938) translated_protein = translate(NM207618_2) #remove the stop codon if translated_protein[-1] == "_": NM207618_2 = NM207618_2[0:len(NM207618_2)-3] translated_protein = translate(NM207618_2) #load comparison protein prt = read_seq("protein.txt") print("Comparison of translated sequence and downloaded sequence: ", translated_protein == prt)
# Maxwell Lin 46268364 class gamestate: def __init__(self,list_2d,turn): self._board = list_2d self._turn = turn def print_board(self): for rows in self._board: row = [] for cols in rows: row.append(cols) print(' '.join(row)) def print_turn(self): print ('TURN: '+self._turn) def switch_turn(self): if self._turn == 'B': self._turn = 'W' else: self._turn = 'B' def give_gamestate(self): return [self._board, self._turn] def give_board(self): return self._board def give_turn(self): return self._turn def change_board(self,list_2d): self._board = list_2d
# -*- coding: utf-8 -*- ''' 字符串连续出现的字符压缩成一个字符并在后面加上该字符的次数 eg: s = 'aaabdd' output: r = 'a3b1d2' ''' s = 'aaabddd' r = [] last = s[0] count = 1 for e in s[1:]: if last != e: r.append(last) r.append(str(count)) last = e count = 1 else: count += 1 else: r.append(last) r.append(str(count)) if len(r) > len(s): r = s print('r is', ''.join(r))
# -*- coding: utf-8 -*- ''' 请实现一个算法,翻转一个给定的字符串. eg: "This is nowcoder!" output: !redocwon si sihT ''' def reversestr(s): low = 0 high = len(s) - 1 s2 = [e for e in s] while low < high: s2[low], s2[high] = s2[high], s2[low] low += 1 high -= 1 return ''.join(s2) s = "This is nowcoder!" r = reversestr(s) print('r is', r)
# -*- coding: utf-8 -*- ''' 题目描述 输入一组勾股数a,b,c(a≠b≠c),用分数格式输出其较小锐角的正弦值。(要求约分。) 输入格式 一行,包含三个数,即勾股数a,b,c(无大小顺序)。 输出格式 一行,包含一个数,即较小锐角的正弦值 ''' nums_str = input().split() nums = [int(e) for e in nums_str] # 做排序的操作 nums.sort() a, _, c = nums def gcd(a, b): if b == 0: return a return gcd(b, a % b) mod = gcd(a, c) print('{}/{}'.format(a // mod, c // mod)) # print('gcd(3, 4)', gcd(a, c))
# -*- coding: utf-8 -*- ''' 题目描述 Given two integers A and B, A modulo B is the remainder when dividing A by B. For example, the numbers 7, 14, 27 and 38 become 1, 2, 0 and 2, modulo 3. Write a program that accepts 10 numbers as input and outputs the number of distinct numbers in the input, if the numbers are considered modulo 42. 输入格式 The input will contain 10 non-negative integers, each smaller than 1000, one per line. 输出格式 Output the number of distinct values when considered modulo 42 on a single line. ''' # 其实要考虑的是桶排序的思路!!! res = set() for _ in range(10): r = input() res.add(int(r) % 42) print(len(res))
# -*- coding: utf-8 -*- from collections import namedtuple # 二叉树的创建 ''' 补空法,是指如果左子树或右子树为空时,则用特殊字符补空,如'#'.然后先按照先序遍历 的顺序,得到先序遍历序列,根据该序列递归创建二叉树 ''' class Node: def __init__(self, val): self.val = val self.left = self.right = None def __str__(self): return self.val def preorder(self) -> str: res = [] def dfs(root): if root is None: res.append('#') return res.append(root.val) dfs(root.left) dfs(root.right) dfs(self) return ''.join(res) def recer_create_tree(str, d={}) -> Node: index = d['index'] d['index'] = index + 1 if index == len(str): return None v = str[index] if v == '#': pass else: n = Node(v) left = recer_create_tree(str, d) right = recer_create_tree(str, d) n.left = left n.right = right return n # def create_treel(root, s): # # # # # root为当前的父节点 # # # # if not s: # # # # pass # # # # else: # # # # n = Node(s[0]) rootA = Node('A') rootB = Node('B') rootC = Node('C') rootD = Node('D') rootE = Node('E') rootF = Node('F') rootG = Node('G') rootA.left = rootB rootA.right = rootC rootB.left = rootD rootB.right = rootE rootC.left = rootF rootF.right = rootG r = rootA.preorder() print('r is', r) # # print(rootA.right) d = { 'index': 0, } n = recer_create_tree(r, d) print('n is', n.preorder())
# -*- coding: utf-8 -*- # 切蛋糕递归算法 def sum2(arr, index): if index == len(arr): return 0 return arr[index] + sum2(arr, index + 1) a = list(range(101)) print('a is', sum2(a, 0)) # 翻转字符串 a = 'abcd' r = [] def revse(s, index): if index == -1: return # print(s[index]) r.append(str(s[index])) revse(s, index - 1) revse(a, len(a) - 1) # r = revse(a, len(a) - 1) print('revse a is', ''.join(r))
# -*- coding: utf-8 -*- import threading from threading import Lock import time from queue import Queue from typing import Callable def printFirst(): print('first') def printSecond(): print('second') def printThird(): print('third') class Foo: def __init__(self): self.qub = Queue() self.quc = Queue() def first(self, printirst: 'Callable[[], None]') -> None: # printFirst() outputs "first". Do not change or remove this line. printFirst() self.qub.put(0) def second(self, printSecond: 'Callable[[], None]') -> None: # printSecond() outputs "second". Do not change or remove this line. self.qub.get() printSecond() self.quc.put(0) def third(self, printThird: 'Callable[[], None]') -> None: # printThird() outputs "third". Do not change or remove this line. self.quc.get() printThird() # foo = Foo() # # t1 = threading.Thread(target=foo.first, args=([],)) # t2 = threading.Thread(target=foo.second,args=([],)) # t3 = threading.Thread(target=foo.third, args=([],)) # # t1.start() # t2.start() # t3.start() qu = Queue() def ff(): v = qu.get() print('v is', v) # t = threading.Thread(target=ff) # t.start() # # time.sleep(3) # # qu.put(30) lock = Lock() # lock.release() # lock.release() # lock.acquire() # lock.acquire() with lock: print('kk') with lock: print('kk') # print(lock)
# -*- coding: utf-8 -*- ''' 判断一个字符串是否为 回文字符串。 ''' s = 'abccba' reverse_s = ''.join(reversed(s)) print('s is', s) print('reverse of s is', reverse_s) res = s == reverse_s print('res is', res)
# -*- coding: utf-8 -*- # 通过python的list来进行顺序存储的逻辑 # 而且我们通过索引1的位置开始存储 # 如上所示0代表我们不存储任何值 # 小顶堆的下沉的操作 def sink(nums, k, n): while k * 2 <= n: m = le = k * 2 # 替换到下一个节点 ri = le + 1 if ri <= n and nums[ri] > nums[le]: m += 1 if nums[k] < nums[m]: nums[k], nums[m] = nums[m], nums[k] k = m def buildHeap(nums): n = len(nums) - 1 k = n // 2 while k > 0: sink(nums, k, n) k -= 1 def sort_heap(nums): n = len(nums) - 1 k = n while k > 0: nums[1], nums[k] = nums[k], nums[1] sink(nums, 1, k - 1) # print('kkk', nums) k -= 1 nums = [None, 30, 28, 20, 16, 18, 2, 17, 6, 10, 12] nums_bak = nums[:] print('before nums', nums) # step 1 build max_heap buildHeap(nums) print('builed nums is', nums) # sort heap sort_heap(nums) print('sorted nums is', nums) print('sorted nums == sort heapsort', sorted(nums_bak[1:]) == nums[1:])
# -*- coding: utf-8 -*- ''' 编写某个方法,返回集合的所有的子集 给定 ''' import copy # 递归模式 def getsubsetscore(s, index): if index == len(s): return [set()] # # if index == len(s) - 1: # return [set(), {s[index]}] c = s[index] old_set = getsubsetscore(s, index + 1) new_set = [] for o_set in old_set: # 对于每个子集,cur这个元素可以加进去,也可以不加进去 new_set.append(o_set) clone_set = copy.deepcopy(o_set) # clone_set = o_set clone_set |= {c} new_set.append(clone_set) return new_set s = 'ABCDEFGHIMNK' r = getsubsetscore(s, 0) print('r is', r) print('len of r is', len(r)) def getsubsets(a): s2 = sorted(a) return getsubsetscore(s2, 0) # 迭代的模式
# -*- coding: utf-8 -*- # 算法思路,所需要找的最小值一定是在无序的那段区间之中 a = list(range(4, 20)) a = a + [0, 1, 2, 3] # a = [5, 6, 1, 2, 3] print('a is', a) def findMin(nums, low, high): # if low == high: # return nums[low] if low + 1 == high: return min(nums[low], nums[high]) mid = (low + high) // 2 if nums[low] < nums[mid]: return findMin(nums, mid, high) else: return findMin(nums, low, mid) r = findMin(a, 0, len(a) - 1) print('r is', r)
# -*- coding: utf-8 -*- a = list(range(10 ** 3, -1, -1)) print('希尔排序前 a is ', a) interval = len(a) // 2 while interval > 0: i = 0 while i < interval: for j in range(i + interval, len(a), interval): ii = j tmp = a[j] # 边界条件确实需要斟酌!!! while ii > i and a[ii - interval] > tmp: a[ii] = a[ii - interval] ii -= interval a[ii] = tmp i += 1 interval //= 2 print('希尔排序后 a is ', a)
# -*- coding: utf-8 -*- # def pow0(a: int, n: int) -> int: # if n == 0: # return 1 # # return a * pow0(a, n - 1) # # r = pow0(2, 3) # print('r is ', r) ''' 高效的模式的确很高效的策略 ''' def pow2(a: int, n: int) -> int: if n == 0: return 1 res = a ex = 1 while ex << 1 <= n: res *= res ex <<= 1 return res * pow2(a, n - ex) r2 = pow2(10, 3) print('r2 is ', r2)
# -*- coding: utf-8 -*- nums = list(range(9, -1, -1)) print('nums is ', nums) # 分区的逻辑的确很重要的特性!!! def partition(nums, low, high) -> int: ''' 一遍单向扫描法,定主元的情况 该分区算法的逻辑是把第一个当做最大值来进行考虑,然后从中把最大的值放入到 临界的那个位置中去 :param nums: :param low: :param high: :return: 返回的值则是主元素所对应的索引值 ''' # 不应该使用该返回值的条件 # if low + 1 == high: # return low pivot = nums[low] index = low + 1 while index <= high: # 最终的边界条件为 high 指向到了倒出第一个小于pivot的数据,而index则是指向第一个大小pivot的数据 if nums[index] <= pivot: index += 1 else: nums[index], nums[high] = nums[high], nums[index] high -= 1 print('low, high is', low, high) nums[low], nums[high] = nums[high], nums[low] return high def partition2(nums, low, high) -> int: ''' 一遍双向扫描,同时从左边和右边一起扫描 :param nums: :param low: :param high: :return: 返回的值则是主元素所对应的索引值 ''' # 不该使用该返回值的条件 # if low + 1 == high: # return low p = nums[low] left = low + 1 right = high while left <= right: # left 不停的往右走,直到遇到大于主元的元素 while left <= right and nums[left] <= p: left += 1 # right 一定是指向最后一个小于主元 while left <= right and nums[right] > p: right -= 1 # left == right 不需要进行元素的交换的逻辑 if left < right: nums[left], nums[right] = nums[right], nums[left] # while 退出时,两者交错,且right指向的是最后一个小于等于主元的位置, nums[low], nums[right] = nums[right], nums[low] return right ''' 快速排序 1: 先对数组以第一个元素进行分区的操作,然后对分别的各个子区域进行相关的递归排序的过程 ''' def quickSort(nums, low, high): if low >= high: return mid = partition2(nums, low, high) # mid = partition(nums, low, high) # print('mid is', mid) quickSort(nums, low, mid - 1) quickSort(nums, mid + 1, high) # quickSort(nums, 0, len(nums) - 1) print('soted nums is', nums) # b = partition(nums, 0, len(nums) - 1) # # print('nums is ', nums) b = [1, 2, 3, 4] print('b is', b) i = partition2(b, 0, len(b) - 1) print('b is ', b) print('i is ', i)
# -*- coding: utf-8 -*- k = 5 glo_d = { 'k': k, 'heap': [0] * k, 'size': 0, } print('heap is', glo_d['heap']) # 目前我们使用数组来代表堆的使用 def minHeap(nums): for i in range(len(nums) // 2 - 1, -1, -1): minheapfixdown(nums, i, len(nums)) def minheapfixdown(nums, i, n): # 找到左右孩子 le_index = i * 2 + 1 ri_index = i * 2 + 2 # 如果nums[i]比两个孩子都要小,不用做调整 # if le_index >= len(nums): # return if le_index >= n: return min_v = le_index # if ri_index >= len(nums): if ri_index >= n: pass else: if nums[ri_index] < nums[le_index]: min_v = ri_index if nums[i] <= nums[min_v]: return # 否则找到两个孩子中较小的,和i交换 nums[i], nums[min_v] = nums[min_v], nums[i] # 小孩子那个位置的值发生了变化,i变更为小孩子那个位置,递归调整 minheapfixdown(nums, min_v, n) def deal(x): size = glo_d['size'] k = glo_d['k'] heap = glo_d['heap'] if size < k: heap[size] = x size += 1 glo_d['size'] = size # x和堆顶元素进行比较(最小堆) elif size == k: # 代码进行相关堆化 minHeap(heap) size += 1 glo_d['size'] = size # 由于是最小堆顶,所以比堆顶小的元素我们不需要去关注 # x和堆顶进行比较,如果x大于堆顶,x将堆顶挤掉并向下调整 size = glo_d['size'] if size > k and heap[0] < x: heap[0] = x minheapfixdown(heap, 0, k) print('heap is ', heap) for i in range(1, 10): deal(i)
"""Contains the TrieNode class, that represents a node of the Prefix Trie. Use list_completions to retrieve the list of completions of a given word. """ __all__ = ['TrieNode', 'list_completions'] class TrieNode(object): """Node of the Trie. Contains value and children nodes""" def __init__(self): self.children = dict() self.value = None def insert(self, string, value): """Inserts string into Trie. Value is attached to the terminal node.""" node = self index_last_char = None for index_char,char in enumerate(string): if char in node.children: node = node.children[char] else: index_last_char = index_char break if index_last_char is not None: for char in string[index_last_char:]: node.children[char] = TrieNode() node = node.children[char] node.value = value def find_completions_node(node, key): """Returns node corresponding to matched prefix.""" for char in key: if char in node.children: node = node.children[char] else: return None return node def list_completions(node, key): """Returns list of strings of the matched prefix completions.""" completions = [] def get_terminal(node): if node.value is not None: completions.append(node.value) for key in node.children: get_terminal(node.children[key]) last_node = find_completions_node(node, key) if last_node is not None: get_terminal(last_node) return completions
import shutil columns = shutil.get_terminal_size().columns def Merge(array, copy, low, mid, high): k,i = low,low j = mid+1 while i<=mid and j<=high: if array[i]<=array[j]: copy[k] = array[i] i += 1 k += 1 else: copy[k]=array[j] j += 1 k += 1 #filling the remaining while i<=mid: copy[k] = array[i] i += 1 k += 1 for i in range(low, high+1): array[i] = copy[i] def MergeSort(array, copy, low, high): if low == high: return mid = (low + ((high-low) >>1)) #left MergeSort(array, copy, low, mid) #right MergeSort(array, copy, mid+1, high) #time to merge! Merge(array, copy, low, mid, high) def IsSorted(array): prev = array[0] for i in range(1,n): if prev > array[i]: print("Merge Fails!!") return False prev = array[i] return True if __name__=="__main__": print("MERGE SORT".center(columns)) while True: array = input("\nInput the numbers separated by commas: ").split(",") array = [int(x) for x in array] n = len(array) copy = array.copy() MergeSort(array,copy, 0, n-1) if IsSorted(array): print(array) ask = input("\nWanna Continue? [y/n]: ").lower() if ask == "y": continue elif ask == "n": exit()
class Stack: def __init__(self): self._data = [] def push(self, e): self._data.append(e) def pop(self): return self._data.pop() def len(self): return len(self._data) def is_empty(self): return not self._data def top(self): if self.is_empty(): return False return self._data[-1] def Binary(n): s = Stack() n = int(input()) while n != 0: if(n % 2 == 0): s.push(0) else: s.push(1) n = n // 2 v = '' while s.len() != 0: a = s.pop() v = v + str(a) print(v)
import numpy as np from copy import deepcopy ''' Experiment 5: - A population of input excitatory neurons. - A population of output excitatory neurons. - A single, very strong, IIN. We're trying to understand the connection between the inhibitory threshold size and the number of winners (among output neurons), where we define a winner to be any neuron that fired at least once. We expect that if we average over many trials, when the inhibitory and excitatory threshold are equal, exactly half of the neurons will become winners- since the characteristics of excitatory input to all the neurons is equal, and a winner is exactly the neurons that charges faster than the IIN. Result: Our prediction is incorrect: when we set the thresholds to be equal, a bit more than half of the neurons were winners. To get exactly half, we had to set the inhibitory threshold a bit smaller than the excitatory threshold (in_th =~ 0.381, ex_th = 0.4). The reason: the inhibitory threshold is not exactly dividable by the average input into the IIN. If, for example, in_th=0.4 and the average input is 0.03, the IIN will actually fire when it's accumulated input will be 0.42 (since 0.42 is dividable by 0.03)- after 14 time steps, on average. So all excitatory neurons that have average input 0.029 will become winners- since they will also fire after 14 time steps (since 0.029*14=0.406 is larger than 0.4), and this is more than half of the neurons. ''' # General parameters input_num = 8 output_num = 8 iin_num = 1 unit_num = input_num + output_num + iin_num # Competition parameters T = 10000 class ModelClass: default_configuration = { # Neuron parameters 'excitatory_threshold' : 0.4, 'inhibitory_threshold' : 0.4, 'sensory_input_strength' : 0.13333, # Normalization parameter 'Z_ex_ex_th_ratio' : 0.5, 'Z_iin_ex_th_ratio' : 1, 'Z_inp_Z_ex_ratio' : 0.5, } def __init__(self, configuration, load_from_file, quiet): self.conf = {key : configuration[key] if key in configuration else ModelClass.default_configuration[key] for key in ModelClass.default_configuration.keys()} self.quiet = quiet self.init_normalization_parameters() self.init_data_structures(load_from_file) def my_print(self, my_str): if not self.quiet: print(my_str) def save_synapse_strength(self): # Save the synapse strength matrix to a file. trained_strength = [self.synapse_strength] file_name = "synapse_strength" file_name += "_" + str(unit_num) + "_neurons" np.save(file_name, trained_strength) def init_data_structures(self, load_from_file): ''' Initialize the data structures. load_from_file- if different from 'None', holds the suffix of the file to be loaded. ''' if not load_from_file: # Initialize random synapse strength self.synapse_strength = np.random.rand(unit_num, unit_num) self.synapse_strength[:, unit_num - iin_num:] = (-1) * self.synapse_strength[:, unit_num - iin_num:] else: file_name = "synapse_strength" file_name += "_" + str(unit_num) + "_neurons" file_name += ".npy" trained_strength = np.load(file_name) self.synapse_strength = trained_strength[0] self.prev_act = np.zeros((unit_num, 1)) self.prev_input_to_neurons = np.zeros((unit_num, 1)) self.fix_synapse_strength() def init_normalization_parameters(self): # Initialize normalization parameters self.conf['Z_ex'] = self.conf['Z_ex_ex_th_ratio'] * self.conf['excitatory_threshold'] self.conf['Z_iin'] = self.conf['Z_iin_ex_th_ratio'] * self.conf['excitatory_threshold'] self.conf['Z_inp'] = self.conf['Z_inp_Z_ex_ratio'] * self.conf['Z_ex'] self.conf['Z_out'] = self.conf['Z_ex'] - self.conf['Z_inp'] def fix_synapse_strength(self): # Normalize the synapses strength, and enforce the invariants. excitatory_unit_num = unit_num - iin_num # Make sure excitatory weights in are all excitatory self.synapse_strength[:, :excitatory_unit_num][self.synapse_strength[:, :excitatory_unit_num] < 0] = 0 # Normalize incoming excitatory weights to each unit input_begin = 0 output_begin = input_begin + input_num input_to_input_row_sum = (self.synapse_strength[input_begin:input_begin + input_num, input_begin:input_begin + input_num].sum(axis=1).reshape(input_num, 1).repeat(input_num, axis=1)) / self.conf['Z_inp'] output_to_input_row_sum = (self.synapse_strength[input_begin:input_begin + input_num, output_begin:output_begin + output_num].sum(axis=1).reshape(input_num, 1).repeat(output_num, axis=1)) / self.conf['Z_out'] input_row_sum = np.concatenate((input_to_input_row_sum, output_to_input_row_sum), axis=1) input_to_output_row_sum = (self.synapse_strength[output_begin:output_begin + output_num, input_begin:input_begin + input_num].sum(axis=1).reshape(output_num, 1).repeat(input_num, axis=1)) / self.conf['Z_inp'] output_to_output_row_sum = (self.synapse_strength[output_begin:output_begin + output_num, output_begin:output_begin + output_num].sum(axis=1).reshape(output_num, 1).repeat(output_num, axis=1)) / self.conf['Z_out'] output_row_sum = np.concatenate((input_to_output_row_sum, output_to_output_row_sum), axis=1) input_to_iin_row_sum = (self.synapse_strength[-iin_num:, input_begin:input_begin + input_num].sum(axis=1).reshape(iin_num, 1).repeat(input_num, axis=1)) / self.conf['Z_inp'] output_to_iin_row_sum = (self.synapse_strength[-iin_num:, output_begin:output_begin + output_num].sum(axis=1).reshape(iin_num, 1).repeat(output_num, axis=1)) / self.conf['Z_out'] iin_from_ex_row_sum = np.concatenate((input_to_iin_row_sum, output_to_iin_row_sum), axis=1) excitatory_row_sums = np.concatenate((input_row_sum, output_row_sum, iin_from_ex_row_sum), axis=0) # Make sure inhibitory weights are all inhibitory self.synapse_strength[:, excitatory_unit_num:][self.synapse_strength[:, excitatory_unit_num:] > 0] = 0 # Normalize incoming inhibitory weights to each unit inhibitory_row_sums = (-1) * ((self.synapse_strength[:, excitatory_unit_num:].sum(axis=1).reshape(unit_num, 1).repeat(iin_num, axis=1)) / self.conf['Z_iin']) row_sums = np.concatenate((excitatory_row_sums, inhibitory_row_sums), axis=1) row_sums[row_sums == 0] = 1 self.synapse_strength = self.synapse_strength / row_sums def simulate_dynamics(self, input_vec): # Given an input, simulate the dynamics of the system, for iter_num time steps fire_history = [] for _ in range(unit_num): fire_history.append([]) for t in range(T): if t % 1000 == 0: self.my_print('t=' + str(t)) # Propagate external input self.prop_external_input(input_vec) # Document fire history for unit_ind in range(unit_num): if self.prev_act[unit_ind, 0] == 1: fire_history[unit_ind].append(t) self.my_print('firing count: ' + str([len(a) for a in fire_history[input_num:]])) return fire_history def prop_external_input(self, sensory_input_vec): # Simulate the dynamics of the system for a single time step cur_input = np.zeros((unit_num, 1)) input_from_prev_layer = np.pad(sensory_input_vec, ((0, unit_num - input_num), (0, 0)), 'constant') cur_input = np.add(cur_input, input_from_prev_layer) input_from_pre_layer = np.matmul(self.synapse_strength, self.prev_act) cur_input = np.add(cur_input, input_from_pre_layer) ''' Accumulating input and refractory period: If a neuron fired in the last time step, we subtract its previous input from its current input. Otherwise- we add its previous input to its current input. ''' prev_input_factor = (1 - 2 * self.prev_act) cur_input = np.add(cur_input, prev_input_factor * self.prev_input_to_neurons) # Make sure the input is non-negative cur_input = np.where(cur_input >= 0, cur_input, 0) cur_act = np.concatenate((self.excitatory_activation_function(cur_input[:unit_num - iin_num, [0]]), self.inhibitory_activation_function(cur_input[unit_num - iin_num:, [0]])), axis=0) self.prev_act = deepcopy(cur_act) self.prev_input_to_neurons = deepcopy(cur_input) def excitatory_activation_function(self, x): # Linear activation function for excitatory neurons return 0 + (x >= self.conf['excitatory_threshold']) def inhibitory_activation_function(self, x): # Linear activation function for inhibitory neurons return 0 + (x >= self.conf['inhibitory_threshold']) def generate_random_external_input(self): strength_factor = np.random.rand() first_active_unit = np.random.randint(input_num - 1) precentage_of_first_unit = np.random.rand() sensory_vec = np.zeros((input_num, 1)) sensory_vec[first_active_unit, 0] = strength_factor * precentage_of_first_unit * self.conf['sensory_input_strength'] sensory_vec[first_active_unit + 1, 0] = strength_factor * (1 - precentage_of_first_unit) * self.conf['sensory_input_strength'] return sensory_vec iter_num = 1000 winner_num_sum = 0 for cur_iter in range(iter_num): if cur_iter % 100 == 0: print('cur_iter=' + str(cur_iter)) model = ModelClass({}, False, True) input_vec = model.generate_random_external_input() fire_history = model.simulate_dynamics(input_vec) fire_count = [len(a) for a in fire_history] winner_num = len([x for x in fire_count[input_num:input_num + output_num] if x > 0]) winner_num_sum += winner_num winner_num_average = winner_num_sum / iter_num print('Winner num average: ' + str(winner_num_average))
#1 - Define a dictionary call story1, it should have the following keys: # 'start', 'middle' and 'end' story1 = { "start": "Villain destroying earth", "middle": "Hero fights with villain", "end": "Hero saves earth from the villain" } #2 - Print the entire dictionary print(story1) #3 - Print the type of your dictionary print(type(story1)) #4 - Print only the keys print(story1.keys()) #5 - print only the values print(story1.values()) #6 - print the individual values using the keys (individually, lots of print commands) print(story1.get("start")) print(story1.get("middle")) print(story1.get("end")) #7 - Now let's add a new key:value pair. # 'hero': yourSuperHero story1.update({"hero": "yourSuperHero"}) print(story1.values())
# EJERCICIO 12 # Participante: # Jose Luis Hernandez Meza # Import of modules import argparse import time import os import DetectEs # Start argparse parser = argparse.ArgumentParser( description = "Cesar Encryption Tool" ) # We add the required arguments parser.add_argument( "-mode", nargs = "?", default = "e", type = str, help = "Type the working mode: 'e' for encrypt, 'd' for decrypt or 'c' for crack message.") parser.add_argument( "-message", nargs = "?", default = "Soy LSTI y me gusta programar", type = str, help = "Type the message to use") parser.add_argument( "-key", nargs = "?", default = "clave del dia", type = str, help = "Type the message to use") args = parser.parse_args() # We make the arguments simpler mod = args.mode message = args.message key = len(args.key) print("==============================") print("-------STARTING PROGRAM-------") print("==============================") time.sleep(2) # We define our dictionary dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?." # Create the function that encrypts all messages def Encrypt(message, key): translated = '' # We have an empty dictionary for symbol in message: if symbol in dict: symbolIndex = dict.find(symbol) translatedIndex = symbolIndex + key if translatedIndex >= len(dict): translatedIndex = translatedIndex - len(dict) elif translatedIndex < 0: translatedIndex = translatedIndex + len(dict) translated = translated + dict[translatedIndex] else: translated = translated + symbol print(translated) # Create the function that will decrypt all messages def Decrypt(message, key): translated = '' # We have an empty dictionary for symbol in message: if symbol in dict: symbolIndex = dict.find(symbol) translatedIndex = symbolIndex - key if translatedIndex >= len(dict): translatedIndex = translatedIndex - len(dict) elif translatedIndex < 0: translatedIndex = translatedIndex + len(dict) translated = translated + dict[translatedIndex] else: translated = translated + symbol print(translated) # We create the function that will crack all messages using brute force def Crack(message, key): for key in range(len(dict)): translated = '' # We have an empty dictionary for symbol in message: if symbol in dict: symbolIndex = dict.find(symbol) translatedIndex = symbolIndex - key if translatedIndex < 0: translatedIndex = translatedIndex + len(dict) translated = translated + dict[translatedIndex] else: translated = translated + symbol print('Key #%s: %s' % (key, translated)) if __name__ == "__main__": # Verify the selected mode if mod == "e": print("You have selected the message encryption option") message = message.upper() print("Your encrypted message is:") Fraenc = Encrypt(message, key) # Print encrypted message elif mod == "d": print("You have selected the message decryption option.") message = message.upper() print("our decrypted message is:") Frades = Decrypt(message, key) # Prints the decrypted message elif mod == "c": print("You have selected the message cracking option") message = message.upper() print("The cracked message is:") Fracrack = Crack(message, key) # Print cracked message
import random # Define the players and their bets players = { 'Lou': 100, 'David': 200, 'Dan': 500 } # Calculate the total amount of money collected total_money = sum(players.values()) # Calculate the value of each square square_value = total_money / 100 # Create an empty 10x10 grid to store the assigned squares grid = [[0 for j in range(10)] for i in range(10)] # Assign squares to each player based on their bet amount for player, bet_amount in players.items(): num_squares = int(bet_amount / square_value) for i in range(num_squares): # Randomly choose an unassigned square and assign it to the player while True: row = random.randint(0, 9) col = random.randint(0, 9) if grid[row][col] == 0: grid[row][col] = player break # Print the grid to show the assigned squares for row in grid: print(row) f
# Rename the key size to amount for any dictionary of the same style recipe = { 'ingredients': [ {'id': 1, 'ingredient': 'flour', 'size': 200, 'measurement': 'mg'}, {'id': 2, 'ingredient': 'eggs', 'size': 2, 'measurement': 'egg'}, {'id': 3, 'ingredient': 'milk', 'size': 3, 'measurement': 'mL'} ] } # How do we get to the measurement value? print(recipe['ingredients'][1]['measurement']) # How do we reassign a value # recipe['ingredients'][1]['amount'] = recipe['ingredients'][1].pop('size') print(recipe['ingredients'][1]) # How do we get the length of the list? print(len(recipe['ingredients'])) # How do we reassign the values for all of them in this dictionary? # length = len(recipe['ingredients']) # for val in range(length): # recipe['ingredients'][val]['amount'] = recipe['ingredients'][val].pop('size') # print(recipe['ingredients']) # How can we make this work for any type? def rewrite(recipe): length = len(recipe['ingredients']) for val in range(length): recipe['ingredients'][val]['amount'] = recipe['ingredients'][val].pop('size') print(recipe['ingredients']) rewrite(recipe)
def solution(nums): answer = 0 if len(set(nums)) > len(nums)//2: answer = len(nums)//2 else: answer = len(set(nums)) return answer print(solution([3,1,2,3])) print(solution([3,3,3,2,2,4])) print(solution([3,3,3,2,2,2]))
# -*- coding: utf-8 -*- # class for places class Ort: def __init__(self, name, beschreibung): self.name = name self.beschreibung = beschreibung self.nach = {} richtungen = ("norden", "süden", "osten", "westen", "oben", "unten") bar = Ort( "Die Bar", "Du nichtnütziges Stück Schafscheiße sitzt mal wieder seit Stunden in der Bar und kippst dir billigen Fusel hinter die Binde. Du kannst hier entweder weiter rumsitzen und saufen oder du verlässt die Bar nach Süden und erlebst vielleicht noch mal irgendwas.") strasse = Ort( "Die Straße vor der Bar", "Du stehst (wankst) auf dem Bürgersteig vor der Bar.") bar.nach["süden"] = strasse strasse.nach["norden"] = bar aktuellerOrt = bar # geklaute druck-Funktion, die print ersetzt def druck(s="", width=80): column = 0 for word in str(s).split(): column += len(word) + 1 if column > width: column = len(word) + 1 print() print (word, end=" ") print() def ortBeschreiben(ort): druck() druck(ort.name) druck() druck(ort.beschreibung) druck() def ortBetreten(ort): global aktuellerOrt aktuellerOrt = ort ortBeschreiben(ort) # geklaute Eingabe-Funktion def anweisung(): return [word.lower() for word in input("? ").rstrip(".?!").split()] # SPIELEN! def spiel(): ortBetreten(bar) # todo spiel()
""" The approach to this problem is to maintain a dp array, which stores T or F based on if the wordDict contains the sub-string till the current index, if so we can consider the sub-string till the current index and at any given point if the other part of the main string i.e is the remaing part which has not been stored in the dp array is found in the wordDict then we make the dp array of the currrent index to True, in this way we check the entire string if it is present in the wordDict, if the last index of the dp array is True then we can conclude that we found all the sub-strings in the wordDict. Leetcode - Running Time Complexity - O(N) Space complexity - O(N) """ def wordBreak(self, s, wordDict): dp = [False] *(len(s)+1) dp[0] = True for i in range(len(s)): for j in range(i,len(s)): if dp[i] and s[i:j+1] in wordDict: dp[j+1] = True return dp[-1]