text
stringlengths
37
1.41M
from threading import Thread, Lock class WordExtractor: INVALID_CHARACTERS = ["'", ",", ".", "/", "?", ";", ":", "(", ")", "+", "*", "[", "]", "{", "}", "&", "$", "@", "#", "%", "\"", "|", "\\", ">", "<", "!", "=", "(", ")", "`"] NUMBERS = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] HIFEN = "-" ENCODING = "utf-8" MAX_THREADS = 100 def __init__(self): self._word_dict = {} self._lock = Lock() def _treat_word(self, word): word = str(word.encode(WordExtractor.ENCODING)).lstrip("b").strip("'") word = word.replace("\\", "") for character in WordExtractor.INVALID_CHARACTERS: word = word.strip(character).strip(character) if(character in word): return None for character in WordExtractor.NUMBERS: if(character in word): return None word = word.strip(WordExtractor.HIFEN).strip(WordExtractor.HIFEN) if(len(word) <= 3): return None word = word.lower() return word def _add_word_to_dictionary(self, word): with self._lock: number_of_ocurrences = self._word_dict.get(word, 0) + 1 self._word_dict[word] = number_of_ocurrences def _collect_words(self, data): word_list = data.split() for word in word_list: word = self._treat_word(word) if(word is not None): self._add_word_to_dictionary(word) def extract_words(self, data_list): self._word_dict = {} thread_list = [] for data in data_list: thread = Thread(target=self._collect_words, args=([data])) if(len(thread_list) >= WordExtractor.MAX_THREADS): oldest_thread = thread_list[0] oldest_thread.join() del(thread_list[0]) thread_list.append(thread) thread.start() for thread in thread_list: thread.join() treated_word_list = self._word_dict.keys() return treated_word_list
# encoding: utf-8 __author__ = 'liubo' """ @version: @author: 刘博 @license: Apache Licence @contact: [email protected] @software: PyCharm @file: cat_dog_deque.py @time: 2016/6/1 23:39 """ from Queue import Queue def func(): pass class Pet(): def __init__(self, type): self.type = type class Cat(Pet): def __init__(self, type): Pet.__init__(self, type) class Dog(Pet): def __init__(self, type): Pet.__init__(self, type) class PetQueue(): def __init__(self): self.cat_num = 0 self.dog_num = 0 self.cat_deque = Queue() self.dog_deque = Queue() self.dog_type = 'dog' self.cat_type = 'cat' def put_dog(self, dog): self.dog_deque.put(dog) self.dog_num += 1 def put_cat(self, cat): self.cat_deque.put(cat) self.cat_num += 1 def poll_dog(self): if self.dog_num == 0: print 'Empty dog deque' return None else: self.dog_num -= 1 return self.dog_deque.get() def poll_cat(self): if self.cat_num == 0: print 'Empty dog deque' return None else: self.cat_num -= 1 return self.cat_deque.get() def put(self,pet): if pet.type == self.dog_type: self.put_dog(pet) elif pet.type == self.cat_type: self.put_cat(pet) else: print 'error type' if __name__ == '__main__': dog = Dog('dog') cat = Cat('cat') petQueue = PetQueue() petQueue.put_cat(cat) petQueue.put(dog) print petQueue.dog_num print petQueue.cat_num print petQueue.poll_dog()
# encoding: utf-8 __author__ = 'liubo' """ @version: @author: 刘博 @license: Apache Licence @contact: [email protected] @software: PyCharm @file: stack_sort.py @time: 2016/6/9 16:37 """ def stack_sort(stack): ''' :param stack: 需要排序的栈 利用一个辅助栈完成栈的排序 ''' pop_num = 0 stack_tmp = [] while len(stack) > 0: current = stack.pop() if len(stack_tmp) == 0: stack_tmp.append(current) else: while current < stack_tmp[-1]: stack.append(stack_tmp.pop()) pop_num += 1 stack_tmp.append(current) for index in range(pop_num): stack_tmp.append(stack.pop()) pop_num = 0 return stack_tmp if __name__ == '__main__': stack = [1,3,5,7,9,2,4,6,8,0] stack = stack_sort(stack) print stack
# -*- coding:utf-8 -*- __author__='liubo' class Node(object): def __init__(self, value, pre=None, next=None): self.data = value self.next = pre self.prev = next class LinkList(object): def __init__(self): self.head = None self.length = 0 def __getitem__(self, key): # 取第k个元素 if self.is_empty(): print 'linklist is empty.' return elif key < 0 or key > self.getlength(): print 'the given key is error' return else: return self.getitem(key) def __setitem__(self, key, value): if self.is_empty(): print 'linklist is empty.' return elif key < 0 or key > self.getlength(): print 'the given key is error' return else: self.delete(key) return self.insert(key) def initlist(self,data): self.head = Node(data[0]) p = self.head for i in data[1:]: node = Node(i) p.next = node node.prev = p p = p.next def getlength(self): p = self.head length = 0 while p != None: length += 1 p = p.next return length def is_empty(self): if self.getlength() == 0: return True else: return False def clear(self): # 不能这样处理,里面的节点最好也删掉,否则会造成内存泄露 p = self.head while p != None: tmp = p p = p.next del tmp self.head = Node def append(self,item): q = Node(item) if self.head == None: self.head = q else: p = self.head while p.next != None: p = p.next p.next = q q.prev = p def getitem(self, index): if self.is_empty(): print 'Linklist is empty.' return j = 0 p = self.head while p.next != None and j < index: p = p.next j += 1 if j == index: return p.data else: print 'target is not exist!' def insert(self, index, item): # 将item插入到第i个元素的后面 if self.is_empty() or index < 0 or index > self.getlength(): print 'Linklist is empty.' return if index == 0: # 插入到head的后面 if self.head == None:# 当前没有元素 q = Node(item, pre=self.head, next=None) self.head.next = q else: tmp = self.head.next q = Node(item, pre=self.head, next=self.head.next) # 修改原链表中head后节点的pre tmp.prev = q self.head.next = q return p = self.head j = 0 while p.next != None and j < index: p = p.next j += 1 if index == j: pre = p next = pre.next q = Node(item, pre=pre, next=next) pre.next = q next.prev = q def delete(self, index): if self.is_empty() or index < 0 or index > self.getlength(): print 'Linklist is empty.' return if index == 0:# 删除头节点后的第一个元素 tmp = self.head.next self.head.next = tmp.next tmp.next.prev = self.head del tmp return p = self.head post = self.head j = 0 while p.next != None and j < index: post = p p = p.next j += 1 if index == j: if p.next == None: post.next = None else: post.next = p.next p.next.prev = post del p def index(self,value): if self.is_empty(): print 'Linklist is empty.' return p = self.head i = 0 while p.next != None and not p.data == value: p = p.next i += 1 if p.data == value: return i else: return -1 def travel(self): p = self.head print 'travel double list' while p != None: print p.data p = p.next if __name__ == '__main__': l = LinkList() l.initlist([1, 2, 3, 4, 5]) print l.getitem(4) l.append(6) print l.getitem(5) l.insert(4, 40) print l.getitem(3) print l.getitem(4) print l.getitem(5) l.delete(5) l.delete(1) l.delete(0) print l.getitem(5) l.index(5) l.travel()
#!/usr/bin/python # -*- coding: utf-8 -*- height = 1.82 weight = 74.5 bmi = weight/(height*2) print('BMI = %.2f' %bmi) if bmi < 18.5: print('低于18.5:','过轻') elif bmi >= 18.5 and bmi < 25: print('18.5-25:','正常') elif bmi >= 25 and bmi < 28: print('25-28:','过重') elif bmi >= 28 and bmi < 32: print('28-32:','肥胖') else: print('高于32:','严重肥胖')
""" Scientist stores DNA information in the database Each record will be a binary number All binary numbers will have same number of bit sets These numbers can have many digits, but may have relatively few bit sets To save space they are stored using the compression scheme: - instead of storing as binary numbers they are stored as a list of integers matching the indices of the set bits ( 1 bits) - the bits are 0 -indexed, starting from right side (least significant bit) - these indices are given in random order Given a list of numbers represented in this fashion, associate their indices with their values and sort them in descending order by value Return a list of the indices in the order of the sorted array. bitArrays = [[0,2], [2, 3], [2,1]] i binary decimal 0 0101 5 1 1100 12 2 0110 6 Return: [1, 2, 0] The values sorted in descending order are [12, 6, 5]. The indices of those values are [1, 2, 0] Complete the function sortBinaryNumbers in the editor below: sortBinaryNumbers has the following parameter: int bitArrays[n][m]: a 2D array of integers Return int[n]: an array of integers Constraints: 1 <= n, m <= 10^3 0 <= bitArrays[i][j] <= 10^9 All integers in a row are distinct Each row generate a unique binary number """ """" Binary represents numbers using base two. We use the symbols 0 and 1 and 0< 1 12(base 10) = 1100 (base 2) = 1*2^3 + 1*2^2 + 0*2^1 + 0*2^0 = 8(10) + 4(10) + 0 + 0 = 12 (10) """ # # public class Problem2 { # public static void main(String[] args) throws FileNotFoundException { # # List<List<Integer>> main = new ArrayList<>(); # # List<Integer> sub3 = new ArrayList<>(); # sub3.add(0); # main.add(sub3); # # List<Integer> sub4 = new ArrayList<>(); # sub4.add(0); # main.add(sub4); # # List<Integer> answer = new Problem2().solution(main); # # System.out.println("\nAnswer: "); # for (int output : answer) { # System.out.println(output); # } # # } # # private List<Integer> solution(List<List<Integer>> arr) { # LinkedList<Integer> results = new LinkedList<>(); # # for (int i = 0; i < arr.size(); i++) { # arr.get(i).sort((o1, o2) -> o2 - o1); # if (results.isEmpty()) { # results.add(i); # continue; # } # # int size = results.size(); # for (int k = 0; k < size; k++) { # int idx = results.get(k); # if (compareTo(arr.get(idx), arr.get(i)) < 0) { # results.add(k, i); # break; # } # # if (k == size - 1) { # results.addLast(i); # } # } # } # # return results; # } # # private int compareTo(List<Integer> a, List<Integer> b) { # for (int i = 0; i < a.size(); i++) { # if (!a.get(i).equals(b.get(i))) { # return a.get(i) - b.get(i); # } # } # return 0; # } # } # bitArrays = [[0,2], [2, 3], [2,1]] # class Solution: # def sortBinaryNumbers(self, bitArrays): # maxBitNum = 0 # # convert bits to binary # # getting the maximum bit # for bits in bitArrays: # max1 = max(bits) # if maxBitNum < max1: # maxBitNum = max1 # # binArray = {} # # for i in range(len(bitArrays)): # binaryNum = ['0']*(maxBitNum + 1) # for bit in bitArrays[i]: # binaryNum[(maxBitNum)-bit]='1' # binaryNum = ''.join(binaryNum) # binArray[i]= int(binaryNum, 2) # # binArray = sorted(binArray.items(), key=lambda keyVal: keyVal[1], reverse=True) # # result = [] # for tpl in binArray: # result.append(tpl[0]) # return result # # bitArrays = [[0, 1, 2], [3, 1, 0]] # print(Solution().sortBinaryNumbers(bitArrays)) # import math import os import random import re import sys # # Complete the 'sortBinaryNumbers' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts 2D_INTEGER_ARRAY bitArrays as parameter. # # # def compare(index1, index2, bitArrays): # for i in range(len(bitArrays[index1])): # if bitArrays[index1][i] > bitArrays[index2][i]: # return 1 # elif bitArrays[index1][i] < bitArrays[index2][i]: # return -1 # return 0 # # # def compare_to_keys(my_compares, bitArrays): # class A: # def __init__(self, obj, *args): # self.obj = obj # # def __lt__(self, other): # return my_compares(self.obj, other.obj, bitArrays) < 0 # # def __gt__(self, other): # return my_compares(self.obj, other.obj, bitArrays) > 0 # # def __eq__(self, other): # return my_compares(self.obj, other.obj, bitArrays) == 0 # # def __le__(self, other): # return my_compares(self.obj, other.obj, bitArrays) <= 0 # # def __ge__(self, other): # return my_compares(self.obj, other.obj, bitArrays) >= 0 # # def __ne__(self, other): # return my_compares(self.obj, other.obj, bitArrays) != 0 # # return A # # # def sortBinaryNumbers(bitArrays): # for value in bitArrays: # value.sort(reverse=True) # # array = [i for i in range(len(bitArrays))] # array.sort(reverse=True, key=compare_to_keys(compare, bitArrays)) # return array class Solution: def sortBinaryNumbers(self, bitArrays: list[list[int]]): decimals = [] for bitset in bitArrays: num = 0 for bits in bitset: print("bit:", bits, "pow(2,bits): ", pow(2,bits)) num += pow(2,bits) print("num: ", num) decimals.append(num) print(decimals) indexes = [(num, i) for i, num in enumerate(decimals)] indexes = sorted(indexes, key = lambda x: x[0], reverse=True) print(indexes) return [a[1] for a in indexes] bitArrays = [[0,2], [2, 3], [2,1]] print(Solution().sortBinaryNumbers(bitArrays)) bitArrays = [[0, 1, 2], [3, 1, 0]] print(Solution().sortBinaryNumbers(bitArrays))
""" Given a string s containing digits, return a list of all possible valid IP addresses that can be obtained from the string. Note: The order in which IP addresses are placed in the list is not important. A valid IP address is made up of four numbers separated by dots ., for example 255.255.255.123. Each number falls between 0 and 255, and none of them can have leading zeros. Constraints: The input string s consists of digits only. 4 ≤ s.length ≤ 12 """ """ Constraint checking: The intuition behind this concept is that once we’ve placed a dot, we only have three possible positions for the next dot, that is, after one digit, after two digits, or after three digits. This constraint helps reduce the number of combinations that we need to consider. Instead of validating 990 combinations, we only have to check 3×3×3=27 combinations. """ """ We will implement the backtrack function that takes the position of the previously placed dot, prev_pos, and the number of dots, dots, to place them as arguments: Iterate over the three available slots, curr_pos, to place a dot. Check if the current segment from the previous dot to the current one is valid: If yes, place the dot and add the current segment to our segments list. Check if all 3 dots are placed. If yes, concatenate the segments list into a string and add the ip string to the result list. If no, proceed to place next dots backtrack(curr_pos, dots - 1). Remove the last dot to backtrack. """ def valid(segment): segment_length = len(segment) # storing the length of each segment if segment_length > 3: # each segment's length should be less than 3 return False # Check if the current segment is valid # for either one of following conditions: # 1. Check if the current segment is less or equal to 255. # 2. Check if the length of segment is 1. The first character of segment # can be `0` only if the length of segment is 1. return int(segment) <= 255 if segment[0] != '0' else len(segment) == 1 # this function will append the current list of segments to the list of result. def update_segment(s, curr_pos, segments, result): segment = s[curr_pos + 1:len(s)] print(f"The last dot is placed at position {curr_pos}. Validate the remaining part of string as last segment") if valid(segment): # if the segment is acceptable print("Segment is valid so another result is found and appended to results after joining all segments") segments.append(segment) # add it to the list of segments result.append('.'.join(segments)) print("We can now remove last segment") segments.pop() # remove the top segment def backtrack(s, prev_pos, dots, segments, result): # prev_pos : the position of the previously placed dot # dots : number of dots to place size = len(s) # The current dot curr_pos could be placed in # A range from prev_pos + 1 to prev_pos + 4. That is position next to the position of last dot placed and three characters from it # The dot couldn't be placed after the last character in the string. # We place one of the remaining dots at each of the position in this range and check if the segment created is valid for curr_pos in range(prev_pos + 1, min(size - 1, prev_pos + 4)): segment = s[prev_pos + 1:curr_pos + 1] print(f"Looking at segment {segment}") if valid(segment): segments.append(segment) print("This segment is valid") # if all 3 dots are placed add the solution to result if dots - 1 == 0: print("All the dots have been placed and all the segments are valid") update_segment(s, curr_pos, segments, result) else: print("All dots have not been placed so place the next dot and validate the segment") # continue to place dots backtrack(s, curr_pos, dots - 1, segments, result) print("All dots were placed and all segments created were valid. We now remove the last segment") segments.pop() # remove the last placed dot def restore_ip_addresses(s): # creating empty lists for storing valid IP addresses, # and each segment of IP result, segments = [], [] # We start with empty result list and segment list for each string # We haven't placed any dot yet so previous position of dot is set to -1 # All three dots have to be placed backtrack(s, -1, 3, segments, result) return result # driver code def main(): # input streams of IP addresses ip_addresses = ["0000", "25525511135", "12121212", "113242124", "199219239", "121212", "25525511335"] # loop to execute till the lenght of input IP addresses for i in range(len(ip_addresses)): print(i + 1, ".\t Input addresses: '", ip_addresses[i], "'", sep="") print("\t Possible valid IP Addresses are: ", restore_ip_addresses(ip_addresses[i]), sep="") print("-" * 100) if __name__ == '__main__': main()
""" A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). For example, the next permutation of arr = [1,2,3] is [1,3,2]. Similarly, the next permutation of arr = [2,3,1] is [3,1,2]. While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement. Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory. Example 1: Input: nums = [1,2,3] Output: [1,3,2] Example 2: Input: nums = [3,2,1] Output: [1,2,3] Example 3: Input: nums = [1,1,5] Output: [1,5,1] Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 100 """ class Solution: """ Do not return anything, modify nums in-place instead. """ # find longest non-increasing suffix # find the part of the string where the digits are in decreasing order # the digit just before this part becomes the pivot # swap the number at pivot with the first greater than it in the decreasing part of the string # if pivot is zero then above condition won't hold true so reverse the whole string # now in the decreasing part of the string with swapped digits# further swap the left and right end digits and move the pointers closer after swap, # continue until both pointers are at common index or left index is greater than right index def nextPermutation(self, nums: list[int]) -> None: right = len(nums) - 1 # finding the pivot while nums[right-1] >= nums[right] and right - 1 >= 0: right -= 1 if right == 0: return self.reverse(0, len(nums) - 1, nums) pivot = right -1 successor = 0 for i in range(len(nums)-1, pivot, -1): if nums[i] > nums[pivot]: successor = i break nums[pivot], nums[successor] = nums[successor], nums[pivot] return self.reverse(pivot + 1, len(nums) - 1, nums) def reverse(self, left, right, nums): while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 return nums print(Solution().nextPermutation([1,2,3]))
""" The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2] Output: [-1,3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4] Output: [3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. Constraints: 1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 104 All integers in nums1 and nums2 are unique. All the integers of nums1 also appear in nums2. """ class Solution: def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]: greater, stack = {}, [] # for each element in nums2, keep it in a stack # if on next iteration, a number is encountered which is greater than last number placed in stack # then preserve the 'greater than' relation between last number in stack and current number which is greater in a dictionary # also remove that number from stack since a 'greater than' relation was already found for it # for each element in nums1, check if it has an entry in the dictioning preserving 'greater than' relation # if the number is found in the dictionary keys then its values is the greater next element present in nums2 for that number in nums1 for n in nums2: while stack and n > stack[-1]: greater[stack.pop()] = n stack.append(n) return [greater[n] if n in greater else -1 for n in nums1] # [1,3,5,2,4] # [6,5,4,3,2,1,7] # [4,1,2] # [1,3,4,2] # [2,4] # [1,2,3,4]
def add_it_up(n): sum = 0 if n <= 0: return sum else: return sum + n + add_it_up(n-1) print(add_it_up(100 )) # 1,2,3,4,5,6,7,8,9,10
""" Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0. Example 1: Input: nums = [2,1,2] Output: 5 Example 2: Input: nums = [1,2,1] Output: 0 Constraints: 3 <= nums.length <= 104 1 <= nums[i] <= 106 """ class Solution(object): def largestPerimeter(self, A): A.sort() for i in range(len(A) - 3, -1, -1): if A[i] + A[i+1] > A[i+2]: return A[i] + A[i+1] + A[i+2] return 0 class Solution: # Three line segments comprise a triangle if and only if the # greatest length of the three sides is less than the sum of # lengths of the other two sides. (A few sketches or playing # with three sticks should convince you of this fact.) # # Here's the Plan: # • Sort nums in non-increasing order. # # • Iterate though the list and pop off the first element until # nums[0] < nums[1]+nums[2]. The sum of these three nums is the # solution. # # •If no such three numbers exist, then return 0 def largestPerimeter(self, nums: list[int]) -> int: nums.sort(reverse=True) while len(nums) > 2 and nums[0] >= nums[1] + nums[2]: nums.pop(0) return 0 if len(nums) < 3 else sum(nums[:3])
class Solution(object): def sortByBits(self, arr: list[int]) -> list[int]: def count_bit(num): count = 0 while num > 0: num, rem = divmod(num, 2) if rem == 1: count += 1 return count new_list = [(count_bit(num), num) for num in arr] new_list.sort() result = [num for bit, num in new_list] return result arr = [0,1,2,3,4,5,6,7,8] result = Solution().sortByBits(arr) print(result) arr = [1024,512,256,128,64,32,16,8,4,2,1] result = Solution().sortByBits(arr) print(result)
""" Given two sparse vectors, compute their dot product. Implement class SparseVector: SparseVector(nums) Initializes the object with the vector nums dotProduct(vec) Compute the dot product between the instance of SparseVector and vec A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector. Follow up: What if only one of the vectors is sparse? Example 1: Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0] Output: 8 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8 Example 2: Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2] Output: 0 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0 Example 3: Input: nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4] Output: 6 Constraints: n == nums1.length == nums2.length 1 <= n <= 10^5 0 <= nums1[i], nums2[i] <= 100 """ class SparseVector: def __init__(self, nums: list[int]): self.num_vector = {} for i, num in enumerate(nums): if num != 0: self.num_vector[i] = num def dotProduct(self, vec: 'SparseVector') -> int: product = 0 print(self.num_vector.items(), vec.num_vector.items()) for i, num1 in self.num_vector.items(): for j, num2 in vec.num_vector.items(): if i == j: product +=(num1*num2) return product # Your SparseVector object will be instantiated and called as such: nums1 = [0,1,0,0,0] nums2 = [0,0,0,0,2] v1 = SparseVector(nums1) print(v1.num_vector) v2 = SparseVector(nums2) print(v2.num_vector) ans = v1.dotProduct(v2) print(ans) nums1 = [0,1,0,0,2,0,0] nums2 = [1,0,0,0,3,0,4] v1 = SparseVector(nums1) print(v1.num_vector) v2 = SparseVector(nums2) print(v2.num_vector) ans = v1.dotProduct(v2) print(ans) nums1 = [1,0,0,2,3] nums2 = [0,3,0,4,0] v1 = SparseVector(nums1) print(v1.num_vector) v2 = SparseVector(nums2) print(v2.num_vector) ans = v1.dotProduct(v2) print(ans)
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data ''' input data --> wieght --> hidden layer 1 --> weights --> hidden layer 2 (activation funtion) --> weight --> output # Data is passed straight though Feed - Forward compare output to intended --> cost function(cross entropy) optimization function (optimizer) > min. cost (AdamOptimizer) # Going backwards here is Backpropogation feed forward + backpropogation = One Epoch ''' mnist = input_data.read_data_sets('/tmp/data', one_hot=True) n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 n_classes = 10 batch_size = 100 # 100 images at a time x = tf.placeholder('float', [None, 784]) y = tf.placeholder('float') def NeuralNetworkModel(data): hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])), 'biases':tf.Variable(tf.random_normal(n_nodes_hl1))} hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases':tf.Variable(tf.random_normal(n_nodes_hl2))} hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'biases':tf.Variable(tf.random_normal(n_nodes_hl3))} output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes)), 'biases':tf.Variable(tf.random_normal(n_nodes_hl1))}
def quickSort(alist): quickSortHelper(alist, 0, len(alist) - 1) def quickSortHelper(alist, first, last): if first < last: splitPoint = partition(alist, first, last) quickSortHelper(alist, first, splitPoint-1) quickSortHelper(alist,splitPoint+1, last) def swap(alist, x, y): alist[x], alist[y] = alist[y], alist[x] def get_pivot(alist, low, hi): mid = (low+hi)//2 pivot = hi if alist[low] < alist[mid]: if alist[mid] < alist[hi]: pivot = mid elif alist[low] > alist[hi]: pivot = low return pivot def partition(alist, low, hi): print("partition begin: ") pivot = get_pivot(alist, low, hi) pivotValue = alist[pivot] print("pivot value: ", pivotValue) alist[low], alist[pivot] = alist[pivot], alist[low] border = low for compare in range(low+1, hi+1): if alist[compare] < pivotValue: print("swap value: ", alist[compare]) border = border + 1 swap(alist, border, compare) compare = compare + 1 else: compare = compare + 1 print("final border value: ", border) swap(alist, low, border) print("final list for pass:", alist) return border alist = [54,26,93,17,77,31,44,55,20] quickSort(alist) print(alist)
# O(logn) def binary_search(alist, item): start = 0 end = len(alist) - 1 found = False while start <= end and not found: middle = (end + start)//2 if alist[middle] == item: found = True elif alist[middle] < item: start = middle + 1 elif alist[middle] > item: end = middle - 1 else: return found return found testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] print(binary_search(testlist, 3)) print(binary_search(testlist, 13)) print(9//2)
import math class Vector: def __init__(self, x, y): self.x = x self.y = y def setxy(self, x, y): self.x = x self.y = y def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y) def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) # __truediv__ overrides /, ie 5/2 == 2.5 # __floordiv__ overrides //, ie 5//2 == 2 (integer division) def __truediv__(self, divisor): return Vector(self.x / divisor, self.y / divisor) def __mul__(self, multiplier): return Vector(self.x * multiplier, self.y * multiplier) def mag(self): return (self.x ** 2 + self.y ** 2) ** 0.5 def arg(self): """ returns in degrees """ return math.atan(self.y / self.x) * 180 / math.pi def unit_vector(self): return self / self.mag() @staticmethod def createUnitVectorFromAngle(angle): """ angle in degrees """ radians = angle * math.pi / 180 return Vector(math.cos(angle), math.sin(angle)) @staticmethod def createUnitVector(x, y): return (Vector(x, y)).unit_vector()
# from spellchecker import SpellChecker # # spell = SpellChecker() # # # find those words that may be misspelled # misspelled = spell.unknown(['Alberto', 'Jose', 'Debes', 'Selman', '930', 'Spring', 'St', 'NW', 'Apt', 'TI', 'Atlanta,', 'GA', '[email protected]']) # # for word in misspelled: # # Get the one `most likely` answer # print(spell.correction(word)) # # # Get a list of `likely` options # print(spell.candidates(word)) def text_correction(path_to_text): path_to_text_after_correction = path_to_text return path_to_text_after_correction
#http://cs231n.github.io/python-numpy-tutorial/ #%% import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np x = np.linspace(0, 20, 100) plt.plot(x, np.sin(x)) plt.show() #%% def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] print(pivot,arr,left+middle+right) return quicksort(left) + middle + quicksort(right) print(quicksort([3,6,8,10,1,2,1])) #%% import numpy as np # We will add the vector v to each row of the matrix x, # storing the result in the matrix y x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) v = np.array([1, 0,2]) y = x + v # Add v to each row of x using broadcasting print(y) # Prints "[[ 2 2 4] # [ 5 5 7] # [ 8 8 10] # [11 11 13]]" #%% import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) y= x-5 #%% plt.plot(x, y_sin) plt.plot(x, y_cos) plt.plot(x, y) plt.xlabel('x axis label') plt.ylabel('y axis label') plt.title('xx') plt.legend(['Sine','Cosine','Line']) plt.show() #%% plt.subplot(1,2,1) plt.plot(x, y_sin) plt.title('Sine') plt.subplot(1,2,2) plt.plot(x, y_cos) plt.title('Cosine') plt.show
import streamlit as st import os import nltk # nltk.download('punkt') #nlp pakages from textblob import TextBlob import spacy def text_analyzer(my_text): nlp=spacy.load("en") docx=nlp(my_text) all_data=[('"token":{},\n "Lemma":{}'.format(token.text,token.lemma_)) for token in docx ] return all_data def entity_analyser(my_text): nlp=spacy.load("en") docx=nlp(my_text) tokens=[token.text for token in docx] entities = [(entity.text,entity.label_)for entity in docx.ents] allData = ['"Token":{},\n"Entities":{}'.format(tokens,entities)] return allData def main(): """ NLP BASED APP""" #title st.title("NLP WITH STREAMLIT") st.subheader("Natural Language processing ") st.markdown(""" #### Description + This is Natural Language Processing (NLP) Based App Useful for basis nlp tasks like Tokenization, Sentiment Analysis and Summarization """) #Tokenization if st.checkbox("Show Tokens and Lemma"): st.subheader("Tokenize your text") message=st.text_area("Enter Text","Type Here....") if st.button("Analyze"): nlp_result=text_analyzer(message) st.json(nlp_result) if st.checkbox("Show Named Entities"): st.subheader("Analyse your Text") message=st.text_area("enter_text","type Here..") if st.button("Extract"): entity_result=entity_analyser(message) st.json(entity_result) if st.checkbox("Show Sentiment Analysis"): st.subheader("Analyse Your Text") message=st.text_area("Enter_Text","Type Here..") if st.button("Analyse"): blob=TextBlob(message) result_sentiment=blob.sentiment st.success(result_sentiment) if __name__ == "__main__": main()
# 2015-04-04 recursively:85 ms iteratively:53 ms # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): if not root: return True return self.checkSym(root.left, root.right) def checkSym(self, L, R): if not (L or R): return True # both None if not (L and R): return False # one None, one has value if L.val != R.val: return False return self.checkSym(L.left, R.right) and self.checkSym(L.right, R.left) ########################################### class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): # thanks to https://leetcode.com/discuss/26372/python-iterative-way-using-a-queue if not root: return True Q = collections.deque([root.left, root.right]) while Q: node1, node2 = Q.popleft(), Q.popleft() if not (node1 or node2): continue # both None if not (node1 and node2): return False if node1.val != node2.val: return False Q.append(node1.left) Q.append(node2.right) Q.append(node1.right) Q.append(node2.left) return True
# 2015-05-21 # Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] ###########DFS Runtime: 204 ms############## class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if not node: return None self.d = {} # key is original node, value is copy node return self.dfs(node) # @param n, a undirected graph node # @return a its copy def dfs(self, n): if n in self.d: return self.d[n] self.d[n] = UndirectedGraphNode(n.label) for neighbor in n.neighbors: self.d[n].neighbors.append(self.dfs(neighbor)) return self.d[n] ############BFS Runtime: 172 ms############### class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if not node: return None queue = collections.deque([node]) d = {node: UndirectedGraphNode(node.label)} # key is original node, value is its copy while queue: # the poped node must be already in the dictionary d. poped = queue.popleft() for neighbor in poped.neighbors: if neighbor in d: d[poped].neighbors.append(d[neighbor]) else: neighborCopy = UndirectedGraphNode(neighbor.label) d[neighbor] = neighborCopy d[poped].neighbors.append(neighborCopy) # only put new found nodes into queue, otherwise we will get infinite loop, think two-node graph 0 -- 1 queue.append(neighbor) return d[node]
# 2015-06-04 Runtime: 56 ms # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} n # @return {ListNode} def removeNthFromEnd(self, head, n): dummyHead = ListNode(0) dummyHead.next = head p1_pre, p1, p2 = dummyHead, head, head for i in xrange(n): p2 = p2.next while p2: p1_pre, p1, p2 = p1_pre.next, p1.next, p2.next p1_pre.next = p1.next return dummyHead.next
# 2014-01-18 Runtime: 58 ms class Solution: # @param num, a list of integers # @return a string def largestNumber(self, num): num = [str(i) for i in num] # what's this lambda function? for input string x, y # if x + y > y + x, return -1 # if x + y < y + x, return 1 # if x + y == y + x, return 0 num.sort(cmp = lambda x, y: (x + y < y + x) - (x + y > y + x)) # Boolean operators and and or are so-called short-circuit operators # return value of a short-circuit operator is the last evaluated argument return ''.join(num).lstrip('0') or '0'
# 2015-06-26 Runtime: 172 ms # Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): curr = root while curr: nextLevelFirstNode, prev = None, None while curr: if not nextLevelFirstNode: nextLevelFirstNode = curr.left if curr.left else curr.right if curr.left: if prev: prev.next = curr.left prev = curr.left if curr.right: if prev: prev.next = curr.right prev = curr.right curr = curr.next curr = nextLevelFirstNode # go to next level
import numpy as np import matplotlib.pyplot as plt ################################### # Clustering ################################### class kMeans(): def __init__(self, k, random_state = 123): self.k = k self.random_state = random_state self.cluster_centers = None def _update_cluster_assignments(self, X, mu): """ Description: Update cluster assignments, given the data and current cluster means INPUTS: X : (N, D) data matrix; each row is a D-dimensional data point mu : (K, D) matrix of cluster centers (means) OUTPUT: z : (N,) vector of integers indicating current cluster assignment """ N, D = X.shape K, D = mu.shape z = np.zeros((N, K)) for i in range(self.k): dist_x_to_mu_i = np.linalg.norm(X - mu[i], 2, axis = 1) z[:, i] = dist_x_to_mu_i z = z.argmin(axis = 1) for i in range(self.k): if (z == i).sum() == 0: z[np.random.choice(N, 1)] = i return z def _update_cluster_means(self, X, z): """ Description: Update the cluster means, given the data and a current cluster assignment INPUTS: X : (N, D) data matrix; each row is a D-dimensional data point z : (N,) vector of integers indicating current cluster assignment K : integer; target number of clusters OUTPUT: mu : (K, D) matrix of cluster centers (means) """ N, D = X.shape mu = np.zeros((self.k, D)) for i in range(self.k): mu[i, :] = X[z == i].mean(axis = 0) return mu def fit(self, X): """ Description: Using both `update_cluster_means` and `update_cluster_assignments` to implement the K-means algorithm. INPUTS: X : (N, D) data matrix; each row is a D-dimensional data point """ N, D = X.shape rng = np.random.default_rng(self.random_state) random_indices = rng.choice(N, self.k) mu = X[random_indices] # initialise the cluster centers to one of the k data points convergence = False z = np.zeros(N) # a vector of intergers less than k, used to indicate the cluster assignment of the datapoint while not convergence: new_z = self._update_cluster_assignments(X, mu) new_mu = self._update_cluster_means(X, new_z) convergence = (new_z==z).all() z = new_z mu = new_mu ss = 0 for i in range(self.k): ss += ((X[z==i] - mu[i])**2).sum() self.sum_square_dif = ss self.cluster_centers = mu def predict(self, X): assert self.cluster_centers is not None, "Fit the data first!" preds = self._update_cluster_assignments(X, self.cluster_centers) return preds class GaussianMixture(): def __init__(self): pass ################################### # Dimensionality Reduction ################################### class PCA(): def __init__(self, m): """ Description: initialise the PCA algorithm Input: m: determines the number of pca to return """ self.m = m def fit(self, X): """ Description: This function computes the first M prinicpal components of a dataset X. It returns the mean of the data, the projection matrix, and the associated singular values. INPUT: X: (N, D) matrix; each row is a D-dimensional data point """ N, D = X.shape assert self.m <= D, 'the number of principle components must be less than the number of features' self.x_bar = X.mean(axis = 0) X_tilde = X - self.x_bar if X_tilde.shape[0] == X_tilde.shape[1]: hermitian = (X_tilde == X.T) else: hermitian = False u, self.s, W = np.linalg.svd(X_tilde, full_matrices = False, hermitian = hermitian) self.W = W[:self.m].T def transform(self, X): """ Description: Apply the PCA transformation to data (reducing dimensionality). INPUTS: X : (N, D) matrix; each row is a D-dimensional data point OUTPUT: Z : (N, M) matrix of transformed data """ Z = (self.W.T @ (X - self.x_bar).T) return Z.T def inverse_transform(self, Z): """ Description: Apply the PCA inverse transformation, to reconstruct the data from the low-dimensional projection. INPUTS: Z : (N, M) matrix of transformed data OUTPUT: X : (N, D) matrix; each row is a D-dimensional data point """ X_hat = (self.W @ Z.T).T + self.x_bar return X_hat
#CustomNeuralNetwork.py import numpy as np import pandas as pd #Activation function: f(x) = 1/(1+e^(-x)) def sigmoid(x): return 1/(1+np.exp(-x)) #Derivate of sigmoid function def deriv_sigmoid(x): fx = sigmoid(x) return fx * (1 - fx) class Neuron: def __init__(self, weights, bias): self.weights = weights self.bias = bias def feed_forward(self, inputs): total = np.dot(self.weights, inputs) + self.bias return sigmoid(total) class NeuralNetwork: ''' A neural network with: - 2 inputs - a hidden layer with 2 neurons (h1, h2) - an output layer with 1 neuron (o1) Each neuron has the same weights and bias ''' def __init__(self): # Weights self.w1 = np.random.normal() self.w2 = np.random.normal() self.w3 = np.random.normal() self.w4 = np.random.normal() self.w5 = np.random.normal() self.w6 = np.random.normal() # Biases self.b1 = np.random.normal() self.b2 = np.random.normal() self.b3 = np.random.normal() def feedforward(self, x): # x is a numpy array with 2 elements. h1 = sigmoid(self.w1 * x[0] + self.w2 * x[1] + self.b1) h2 = sigmoid(self.w3 * x[0] + self.w4 * x[1] + self.b2) o1 = sigmoid(self.w5 * h1 + self.w6 * h2 + self.b3) return o1 def train(self, data, all_y_trues): ''' - data is a (n x 2) numpy array, n = # of samples in the dataset. - all_y_trues is a numpy array with n elements. Elements in all_y_trues correspond to those in data. ''' learn_rate = 0.1 epochs = 1000 # number of times to loop through the entire dataset for epoch in range(epochs): for x, y_true in zip(data, all_y_trues): # --- Do a feedforward (we'll need these values later) sum_h1 = self.w1 * x[0] + self.w2 * x[1] + self.b1 h1 = sigmoid(sum_h1) sum_h2 = self.w3 * x[0] + self.w4 * x[1] + self.b2 h2 = sigmoid(sum_h2) sum_o1 = self.w5 * h1 + self.w6 * h2 + self.b3 o1 = sigmoid(sum_o1) y_pred = o1 # --- Calculate partial derivatives. # --- Naming: d_L_d_w1 represents "partial L / partial w1" d_L_d_ypred = -2 * (y_true - y_pred) # Neuron o1 d_ypred_d_w5 = h1 * deriv_sigmoid(sum_o1) d_ypred_d_w6 = h2 * deriv_sigmoid(sum_o1) d_ypred_d_b3 = deriv_sigmoid(sum_o1) d_ypred_d_h1 = self.w5 * deriv_sigmoid(sum_o1) d_ypred_d_h2 = self.w6 * deriv_sigmoid(sum_o1) # Neuron h1 d_h1_d_w1 = x[0] * deriv_sigmoid(sum_h1) d_h1_d_w2 = x[1] * deriv_sigmoid(sum_h1) d_h1_d_b1 = deriv_sigmoid(sum_h1) # Neuron h2 d_h2_d_w3 = x[0] * deriv_sigmoid(sum_h2) d_h2_d_w4 = x[1] * deriv_sigmoid(sum_h2) d_h2_d_b2 = deriv_sigmoid(sum_h2) # --- Update weights and biases # Neuron h1 self.w1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w1 self.w2 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w2 self.b1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_b1 # Neuron h2 self.w3 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w3 self.w4 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w4 self.b2 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_b2 # Neuron o1 self.w5 -= learn_rate * d_L_d_ypred * d_ypred_d_w5 self.w6 -= learn_rate * d_L_d_ypred * d_ypred_d_w6 self.b3 -= learn_rate * d_L_d_ypred * d_ypred_d_b3 # --- Calculate total loss at the end of each epoch if epoch % 10 == 0: y_preds = np.apply_along_axis(self.feedforward, 1, data) loss = mse_loss(all_y_trues, y_preds) print("Epoch %d loss: %.3f" % (epoch, loss)) #Mean Squared Error function def mse_loss(y_true, y_pred): return ((y_true - y_pred) ** 2).mean() df = pd.read_csv('data/data.csv') df.Weight = df.Weight-df.Weight.mean().astype(int) df.Height = df.Height-df.Height.mean().astype(int) inputData = df[["Weight", "Height"]] targetData = df[["Gender"]] targetData.loc[targetData["Gender"] == 'F', 'Gender'] = 0 targetData.loc[targetData["Gender"] == 'M', 'Gender'] = 1 inputData = np.array([inputData.Weight, inputData.Height]).transpose() targetData = np.array(targetData.Gender).transpose() # Train the neural network network = NeuralNetwork() network.train(inputData, targetData) # Make some predictions emily = np.array([-7, -3]) # 128 pounds, 63 inches frank = np.array([20, 2]) # 155 pounds, 68 inches print("Emily: %.3f" % network.feedforward(emily)) # 0.951 - F print("Frank: %.3f" % network.feedforward(frank)) # 0.039 - M
# -*- coding: utf-8 -*- import requests import json # GET request # res is a Response object, which contains a server's response to an HTTP request. res = requests.get('https://api.github.com/events') #print(res.text) # get a str object # print(res.content) # get a bytes object #print(res.encoding) # print(res.json()) # json() => to deal with response with JSON data # GET request with params # Passing Parameters In URLs # e.g. httpbin.org/get?key=val # using the params keyword argument payload = {'key1': 'value1', 'key2': 'value2'} payload2 = {'key1': 'value1', 'key2': ['value2', 'value3']} res3 = requests.get('http://httpbin.org/get', params=payload2) #print(res3.url) # More complicated POST requests # 像一張HTML Form的表格 # to do this, simply pass a dictionary to the data argument. payload = {'key1': 'value1', 'key2': 'value2'} res = requests.post("http://httpbin.org/post", data=payload) #print(res.text) # You can also pass a list of tuples to the data argument. payload = (('key1', 'value1'), ('key1', 'value2')) res = requests.post('http://httpbin.org/post', data=payload) #print(res.text) # json.dumps() => return a str object url = 'https://api.github.com/some/endpoint' payload = {'some': 'data'} res = requests.post(url, data=json.dumps(payload)) #print(res.url) # pass it directly using the json parameter res2 = requests.post(url, json=payload) # POST a File # It is strongly recommended that you open files in binary mode. url = 'http://httpbin.org/post' files = {'file': open('favorite-people.txt', 'rb')} res = requests.post(url, files=files) #print(res.text) #print(res.status_code) # If we made a bad request (a 4XX client error or 5XX server error response), we can raise it with #print(res.raise_for_status()) #print(res.headers) # Cookies # deal with cookies from server # Cookies are returned in a RequestsCookieJar, which acts like a dict url = 'http://example.com/some/cookie/setting/url' r = requests.get(url) #print(r.cookies) # To send your own cookies to the server, you can use the cookies parameter: url = 'http://httpbin.org/cookies' cookies = dict(cookies_are='working') #print(cookies) r = requests.get(url, cookies=cookies) #print(r.text) # Cookies are returned in a RequestsCookieJar jar = requests.cookies.RequestsCookieJar() jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies') jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere') #print(jar) url = 'http://httpbin.org/cookies' r = requests.get(url, cookies=jar) #print(r.text) # Redirection and History # The Response.history list contains the Response objects that were created in order to complete the request. r = requests.get('http://github.com') print(r.url) print(r.status_code) print(r.history)
# -*- coding: utf-8 -*- import re line_number = 0 # Regular Expression # \w => Matches Unicode word characters [a-zA-Z0-9_] # [] => to indicate a set # [\w-] => any word char and char '-' # [\w-]+ => any word composed by word chars and '-' custList = [] with open('data/20161121134754-RCHMA-utf8.txt', encoding='utf-8') as a_file: for a_line in a_file: line_number += 1 if "Values" in a_line: rdata = re.split('Values', a_line)[1] custList.append(tuple(re.findall(r"[\w-]+", rdata))) for cust in custList: print(cust)
# -*- coding: utf-8 -*- # import urllib.request from http.client import HTTPConnection from urllib.request import urlopen HTTPConnection.debuglevel = 1 a_url = 'http://www.diveintopython3.net/examples/feed.xml' # urllib.request.urlopen(a_url) => return a file-like object # that you can just read() from to get the full contents of the page # # urllib.request.urlopen(a_url).read() => return a bytes object, not a string # data = urllib.request.urlopen(a_url).read() response = urlopen(a_url).read() print(type(response )) print(response ) print() response2 = urlopen(a_url) print(response2) print() print(response2.headers.as_string()) print() data2 = response2.read() print(len(data2))
class User: def __init__(self, name, login, password, role): self.__name = name self.__login = login self.__password = password self.__role = role self.__is_blocked = False def getName(self): return self.__name def getLogin(self): return self.__login def getPassword(self): return self.__password def getRole(self): return self.__role def getBlock(self): return self.__is_blocked def setName(self, name): self.__name = name def setLogin(self, login): self.__login = login def setPassword(self, password): self.__password = password def setRole(self, role): self.__role = role def block(self): self.__is_blocked = True def unblock(self): self.__is_blocked = False def __str__(self): return 'Name = {}, Login = {}, Password = {}, Role = {}, {}'.format(self.__name,self.__login,self.__password,self.__role,self.__is_blocked) def __eq__(self, other): return self.__name == other.getName()
from abc import ABC, abstractmethod class Car(ABC): """ Стандартный автомобиль со скоростью в километрах. """ @abstractmethod def set_speed(self, speed: float): pass @abstractmethod def get_speed(self) -> float: pass class CarMiles(ABC): """ Нестандартный автомобиль со скоростью в милях. """ @abstractmethod def set_miles_speed(self, miles_speed: float): pass @abstractmethod def get_miles_speed(self) -> float: pass class CarAdapterSpeed(Car, CarMiles): """ Адаптивный класс наследуемый от стандартного интефейса, который работает с клиентским кодом, а также от нестантартного интефеса с которым не работает клиентский код. """ def set_speed(self, speed: float): self.set_miles_speed(speed) self.__speed = round(self.__miles_speed / 1.60934, 2) def get_speed(self) -> float: return self.__speed def set_miles_speed(self, miles_speed: float): self.__miles_speed = miles_speed def get_miles_speed(self) -> float: return self.__miles_speed class EuropeCar(Car): """ Класс наследуемый от стандартного интефейса, который работает с клиентским кодом. """ def set_speed(self, speed: float): self.__speed = speed def get_speed(self): return self.__speed #tests def print_kilometres_speed(car: Car): print(f'Скорость авто {car.get_speed()} км/ч') car1 = EuropeCar() car1.set_speed(180) print_kilometres_speed(car1) car2 = CarAdapterSpeed() car2.set_speed(250) print_kilometres_speed(car2) print(f'Скорость авто {car2.get_miles_speed()} миль/ч')
# creating an empty list people = [] # creating a dictionary to store person details person = { 'first_name': 'ibby', 'last_name': 'blaq', 'age': '20', 'city': 'dsm' } person = { 'first_name': 'icon', 'last_name': 'man', 'age': '22', 'city': 'new city' } people.append(person) person = { 'first_name': 'jack', 'last_name': 'cactus', 'age': '20', 'city': 'bay area' } # add the dictionary into the list of people for person in people: name = f"{person['first_name'].title()} {person['last_name'].title()}" age = person['age'] city = person['city'].title() print(f"{name} age of {age} lives in {city}.")
def make_shirt(size='large',message='I love python'): # summarize the shirt that is gonna be made print(f"\nI'm gonna make a {size} T-shirt.") print(f"Tha's gonna say {message}") # calling the make_shirt function make_shirt() make_shirt(size='medium') make_shirt(message='Python for life baby!', size='extra-large')
# chnaging cases of the string name = 'Ibrahim' print(name.upper()) print(name.title()) print(name.lower()) print() # quotetion print('Albert Einstein once said, “A person who never made a mistake never tried anything new.”') print() ####################### famous_person = 'Albert Einstein' quote = f'{famous_person}once said, “A person who never made a mistake never tried anything new.”' print(quote) print() # stripping witespaces from the string person_name = '\tAlvina' print(person_name) print(person_name.lstrip())
favorite_places = { 'eric': ['bear mountain', 'death valley', 'tierra del fuego'], 'maulin': ['hawaii', 'iceland'], 'john': ['mt. verstovia', 'the playground', 'new hampshire'] } for person, places in favorite_places.items(): print(f'\nMy friend {person.title()} like:') for place in places: print(f'\t- {place.title()}')
numbers = [] for threes in range(3,30,3): numbers.append(threes) print(numbers)
name = 'Ibrahim' # the letter f used to insert variable values to a string message = f'Hello, {name} would you like to learn some python today?' print(message) print()
invited = ['mom','dad','kids'] # print a message for individual print(f"Hey! {invited[0].title()}, I'm having a dinner at my place tonight. You're invited.") print(f"Hey! {invited[1].title()}, I'm having a dinner at my place tonight. You're invited.") print(f"Hey! {invited[2].title()}, I'm having a dinner at my place tonight. You're invited.")
usernames = [] if usernames: for username in usernames: if (username == 'admin'): print('Hello admin, there is a report status.') else: print(f'Hello {username}, thanks for logging in again') else: print("We need some users.")
# list of favourite animals/pets # but i don't real like animals at all. fav_animals = ['dog','cat','lion'] for pet in fav_animals: print(f"I like {pet} 'cause I like it.") print() print("I'm not a fan of pets. goddamnit!")
list=[2,3,4,1,5,6] '''if 4 in list: print("yes") if 10 in list: print("yupp") else: print("no")''' for x in range(len(list)): print(x,end="we") print("") #print(list[x])
class Plant: pass plant = Plant() print(plant) print(isinstance(plant, Plant)) print(isinstance(plant, object)) class BreedingPlant(Plant): pass class WildPlant(Plant): pass breedingPlant = BreedingPlant() wildPlant = WildPlant() print(breedingPlant) print(isinstance(breedingPlant, BreedingPlant)) print(isinstance(breedingPlant, Plant)) print(isinstance(breedingPlant, object)) print(wildPlant) print(isinstance(wildPlant, WildPlant)) print(isinstance(wildPlant, Plant)) print(isinstance(wildPlant, object)) print(isinstance(wildPlant, BreedingPlant)) print(isinstance(breedingPlant, WildPlant)) class Wheat(BreedingPlant): pass class Rye(BreedingPlant): pass wheat = Wheat() rye = Rye() print(wheat) print(isinstance(wheat, Wheat)) print(isinstance(wheat, BreedingPlant)) print(isinstance(wheat, WildPlant)) print(isinstance(wheat, Plant)) print(isinstance(wheat, object)) print(rye) print(isinstance(rye, Rye)) print(isinstance(rye, BreedingPlant)) print(isinstance(rye, WildPlant)) print(isinstance(rye, Plant)) print(isinstance(rye, object)) class BlueBerries(WildPlant): pass class BlackBerries(WildPlant): pass blueBerries = BlueBerries() blackBerries = BlackBerries() print(blueBerries) print(isinstance(blueBerries, BlueBerries)) print(isinstance(blueBerries, BreedingPlant)) print(isinstance(blueBerries, WildPlant)) print(isinstance(blueBerries, Plant)) print(isinstance(blueBerries, object)) print(blackBerries) print(isinstance(blackBerries, BlackBerries)) print(isinstance(blackBerries, BreedingPlant)) print(isinstance(blackBerries, WildPlant)) print(isinstance(blackBerries, Plant)) print(isinstance(blackBerries, object))
""" Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 00000 Output: 1 Example 2: Input: 11000 11000 00100 00011 Output: 3 """ # Time Complexity : O(n^2) # Space Complexity : O(1) class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ islands = 0 for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == '1': self.dfs(grid, row, col) islands += 1 return islands def dfs(self, grid, row, col): if row < 0 or col < 0 or row >= len(grid) or col >= len(grid[0]) or grid[row][col] != '1': return grid[row][col] = '#' self.dfs(grid, row+1, col) self.dfs(grid, row-1, col) self.dfs(grid, row, col+1) self.dfs(grid, row, col-1) return s = Solution() grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]] assert s.numIslands(grid) == 1, "Houston, we have a problem!" print("Success!")
""" Implement int sqrt(int x). Compute and return the square root of x. If x is not a perfect square, return floor(sqrt(x)) Example : Input : 11 Output : 3 DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY """ class Solution: # @param A : integer # @return an integer def sqrt(self, A): if A == 1: return A start = 0 end = A val = A while True: mid = (start + end) / 2 sqr = mid * mid if sqr == val: return mid if sqr > val: end = mid else: higher = (mid + 1) * (mid + 1) if higher > val: return mid start = mid s = Solution() assert s.sqrt(3969) == 63, "Houston, we have a problem!" print "Success!"
""" Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details. Example: Input: 1 2 3 4 5 6 7 8 9 Return the following : [ [1], [2, 4], [3, 5, 7], [6, 8], [9] ] Input : 1 2 3 4 Return the following : [ [1], [2, 3], [4] ] """ class Solution: # @param a : list of list of integers # @return a list of list of integers def diagonal(self, a): l = len(a) result = [[] for x in range(2 * l - 1)] for r in range(l): for c in range(l): result[r + c].append(a[r][c]) return result s = Solution() matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] result_expected = [[1], [2, 4], [3, 5, 7], [6, 8], [9]] assert s.diagonal(matrix) == result_expected, "Houston, we have a problem!" print "Success!"
""" Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5. """ from list_node import ListNode from list_node import createLinkedList class Solution: # @param A : head node of linked list # @param B : integer # @return the head node in the linked list def partition(self, node, partition): beforeStart = None beforeEnd = None afterStart = None afterEnd = None while node != None : nextNode = node.next node.next = None if node.val < partition: if beforeStart == None: beforeStart = node beforeEnd = beforeStart else: beforeEnd.next = node beforeEnd = beforeEnd.next else: if afterStart == None: afterStart = node afterEnd = afterStart else: afterEnd.next = node afterEnd = afterEnd.next node = nextNode if beforeStart == None: return afterStart beforeEnd.next = afterStart return beforeStart s = Solution() list = [1, 4, 3, 2, 5, 2] node = createLinkedList(list) print "Before Partitioning : " print node.returnLinkedListAsList() print "\nAfter Partitioning : " res = s.partition(node, 3) resList = res.returnLinkedListAsList() print resList expected = [1, 2, 2, 4, 3, 5] assert resList == expected, "Houston, we have a problem!" print "\nSuccess!"
# Review the following link for the question prompt: https://www.algoexpert.io/questions/Group%20Anagrams # O(N + N * mlog(m)) time | O(N) space def groupAnagrams(words): memory = {} for anagram in words: sorted_anagram = ''.join(sorted(anagram)) if sorted_anagram in memory: memory[sorted_anagram].append(anagram) else: memory[sorted_anagram] = [anagram] results = [] for value in memory.values(): results.append(value) return results
# Review the following link for the question prompt: https://www.algoexpert.io/questions/Branch%20Sums # Time Complexity: O(N^2 + m) # Space Complexity: O(N + m) def patternMatcher(pattern, string): if len(string) < len(pattern): return [] newPattern = getNewPattern(pattern) didSwitch = pattern[0] == 'y' firstYPos, counts = getCountsAndFirstYPos(newPattern) if counts['y'] != 0: for lenOfX in range(1, len(string)): lenOfY = (len(string) - (lenOfX * counts['x'])) / counts['y'] if lenOfY % 1 != 0: continue lenOfY = int(lenOfY) idxOfY = firstYPos * lenOfX x = string[:lenOfX] y = string[idxOfY: idxOfY + lenOfY] potentialMatch = map(lambda char: x if char == 'x' else y, newPattern) if string == ''.join(potentialMatch): return [x, y] if not didSwitch else [y, x] else: lenOfX = len(string) / counts['x'] if lenOfX % 1 == 0: lenOfX = int(lenOfX) x = string[:lenOfX] y = '' potentialMatch = map(lambda char: x if char == 'x' else y, newPattern) if string == ''.join(potentialMatch): return [x, y] if not didSwitch else [y, x] return [] def getNewPattern(pattern): patternLetters = list(pattern) if patternLetters[0] == 'x': return patternLetters else: return list(map(lambda char: 'x' if char == 'y' else 'y', patternLetters)) def getCountsAndFirstYPos(pattern): counts = {'x':0, 'y':0} firstYPos = None for index, char in enumerate(pattern): if char == 'y' and firstYPos is None: firstYPos = index counts[char] += 1 return firstYPos, counts
# coding=utf-8 """ A robot is located at the top-left corner of an A x B grid (marked ‘Start’ in the diagram below). Path Sum: Example 1 The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below). How many possible unique paths are there? Note: A and B will be such that the resulting answer fits in a 32 bit signed integer. Example : Input : A = 2, B = 2 Output : 2 2 possible routes : (0, 0) -> (0, 1) -> (1, 1) OR : (0, 0) -> (1, 0) -> (1, 1) """ import math class Solution: # @param A : integer # @param B : integer # @return an integer def uniquePaths(self, A, B): return (math.factorial(A + B - 2)) / (math.factorial(B - 1) * math.factorial(A - 1)) s = Solution() assert s.uniquePaths(4, 5) == 35, "Houston, we have a problem." print "Success!"
# Review the following link for the question prompt: https://www.algoexpert.io/questions/Three%20Number%20Sum # Solution 1 - Brute Force # Time Complexity - O(n^3) # Space Complexity - O(1) # Solution 2 - Sort values and iterate # Time Complexity - O(n^2) # Space Complexity - O(n) def threeNumberSum(array, targetSum): # Write your code here. array.sort() results = [] for i in range(len(array) - 2): l = i + 1 r = len(array) - 1 while l < r: total = array[i] + array[l] + array[r] result = [array[i], array[l], array[r]] if total > targetSum: r -= 1 elif total < targetSum: l += 1 else: # total == targetSum results.append(result) l += 1 r -= 1 return results
# Review the following link for the question prompt: https://leetcode.com/problems/validate-binary-search-tree/ # O(N) time | O(d) space # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBSTHelper(self, tree: TreeNode, minVal: float, maxVal: float) -> bool: if tree is None: return True if tree.val <= minVal or tree.val >= maxVal: return False leftIsValid = self.isValidBSTHelper(tree.left, minVal, tree.val) rightIsValid = self.isValidBSTHelper(tree.right, tree.val, maxVal) return leftIsValid and rightIsValid def isValidBST(self, root: TreeNode) -> bool: return self.isValidBSTHelper(root, float('-inf'), float('inf'))
import pygame from pygame.sprite import Sprite class Ship(Sprite): # Clase que gestiona las configuraciones de la nave def __init__(self, ai_settings, screen): super().__init__() self.screen = screen self.ai_settings = ai_settings # Carga la imagen de la nava y obtiene su rectángulo. self.image = pygame.image.load("images/ship.bmp") self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() # Inicia cada nueva nave en la parte inferior central de la pantalla. self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom # Guarda un valor decimal para el centro de la nave. self.center = float(self.rect.centerx) # Banderas de movimiento self.moving_right = False self.moving_left = False def update(self): # Actualiza la posicion de la nave basado en la bandera de movimento. # Actualiza el valor central de la nave, no el rectangulo. if self.moving_right and self.rect.right < self.screen_rect.right: self.center += self.ai_settings.ship_speed_factor if self.moving_left and self.rect.left > 0: self.center -= self.ai_settings.ship_speed_factor # Actualiza el objeto rect desde el self.center. self.rect.centerx = self.center def blitme(self): # Dibuja la nave en su posición actual. self.screen.blit(self.image, self.rect) def center_ship(self): # Centra la nave en la pantalla. self.center = self.screen_rect.centerx
savings = 100 growth_multiplier = 1.1 print("Enter number of years you want to save") numberOfYears = int(input()) i = 1 while i < numberOfYears: yearY = savings*growth_multiplier savings = yearY i += 1 totalSum = yearY print("Din totala summa blir: "); print(totalSum)
maternos= input("Inserte Genes maternos: ") paternos= input("Inserte Genes paternos: ") cadena_adn= input("Inserte cadena ADN: ") mami=0 papi=0 CGA_validacion = "" for letra in cadena_adn: for letraX in maternos: if letraX == letra: mami = mami + 1 for letra in cadena_adn: for letraY in paternos: if letraY == letra: papi = papi + 1 if mami>papi: CGA_validacion = CGA_validacion + "X" elif papi>mami: CGA_validacion = CGA_validacion + "Y" else: CGA_validacion = CGA_validacion + "N" print(CGA_validacion)
""" :Module Name: **log** ======================= This module contains the classes for log handling """ import logging import os import time class LogHandler(logging.FileHandler): """ LogHandler class is for handling logs generation and log file path generation """ def __init__(self, logdirectory, filename, level=logging.DEBUG): """ This is method to initialize the the LogHandler :param logdirectory: ``name of the log directory`` :param filename: ``name of the file`` :param level: ``log level to be set`` :type logdirectory: ``string`` :type filename: ``string`` :type level: ``string`` """ logdirectory = os.path.abspath(logdirectory) if not os.path.exists(logdirectory): os.makedirs(logdirectory) filename = self.generate_filepath(logdirectory, filename) logging.FileHandler.__init__(self, filename) self.setLevel(level) self.setFormatter(FileFormat()) @classmethod def generate_filepath(cls, logdirectory, filename='vc-tools_output.log'): """ This method is for log file path generation :param logdirectory : name of the log directory :param filename : name of the file :type logdirectory: ``string`` :type filename: ``string`` :return: ``log file path name`` :rtype: ``string`` """ return os.path.join(logdirectory, filename) class StdFormatter(logging.Formatter): """ StringFormatter class to set the format of the logs captured """ std_format = '%(asctime)s:[%(name)s] %(levelname)s %(message)s' def __init__(self): """ This is method to initialize the the StdFormatter class """ logging.Formatter.__init__(self, self.std_format) class ColorFormatter(StdFormatter): """ ColorFormatter class is for setting the colour for log level """ std_format = ( '%(bold_cyan)s[%(name)s]%(normal)s %(level_color)s' '%(levelname)s%(normal)s %(message)s' ) def __init__(self, terminal): """ This is method to initialize the colour for log level :param terminal: ``terminal value`` :type terminal: ``string`` :return: None """ self.colors = { 'DEBUG': terminal.magenta, 'INFO': terminal.green, 'WARNING': terminal.red, 'ERROR': terminal.white_on_red, 'CRITICAL': terminal.bold_white_on_red, } self.bold_cyan = terminal.bold_cyan self.normal = terminal.normal StdFormatter.__init__(self) def format(self, record): """ This method is to set the colour for record :param record: ``record`` :type record: ``string`` :return: ``None`` """ record.level_color = self.colors.get(record.levelname) record.bold_cyan = self.bold_cyan record.normal = self.normal return logging.Formatter.format(self, record) class FileFormat(StdFormatter): """ FileFormat class to set the format of the log file """ std_format = '%(asctime)s: [%(name)s] {%(levelname)s} %(message)s' def formatTime(self, record, datefmt=None): """ This method is to set the format of the date and time :param record: ``record`` :param datefmt: ``format of date and time`` :type record: ``string`` :type datefmt: ``string`` :return: ``format of the date and time`` :rtype: ``string`` """ if datefmt: format_time = StdFormatter.formatTime(self, record, datefmt) else: time_struct = self.converter(record.created) # msecs isn't available in time_struct so inject them manually format_time = time.strftime( '%Y-%m-%d %H:%M:%S.{:03.0f} ' '%Z'.format(record.msecs), time_struct, ) return format_time
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): current_node = self.head while(current_node): print(current_node.data) current_node = current_node.next def append(self, data): new_node = Node(data) if(self.head is None): self.head = new_node else: current_node = self.head while(current_node.next): current_node = current_node.next current_node.next = new_node def prepend(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def insert_after_node(self, prev_node, data): if not prev_node: print("previous node is not in the list") else: new_node = Node(data) new_node.next = prev_node.next prev_node.next = new_node llist = LinkedList() llist.append("A") llist.append("B") llist.prepend("C") llist.insert_after_node(llist.head.next, "D") llist.print_list()
# Program to find how many times the sorted array is rotated def find_rotation_count(arr,length): first,last = 0,length-1 while(first<=last): if(arr[first]<=arr[last]): return first #sorted #case:1 mid = (first+last)//2 prev,next = (mid+length-1)%length,(mid+1)%length if(arr[mid]<=arr[prev] and arr[mid] <= arr[next]): return mid # case : 2 elif(arr[mid] <= arr[last]): last = mid-1 # case : 3 elif(arr[mid] >= arr[first]): first = mid+1 # case : 4 return -1 if __name__ == "__main__": arr = [15,22,23,28,31,38,5,6,8,10,12] print("No of rotations of sorted arr is : ",find_rotation_count(arr,len(arr)))
def fibonacci(n): a = 0 b = 1 while (a <= n): yield a a, b = b, a+b for i in fibonacci(99999999999999999999999999): print(i)
#pickandshowRev1_LScroggs.py #this program allows user to pick and display a pre-selected image #10/19/2017 #JES print("Image Select\n") prompt = raw_input("Would you like to select an image? ") prompt = prompt.lower() if prompt == "yes": print("please select") else: sys.exit() def main(): file = get_file() image = make_image(file) show_image(image) def get_file(): file = pickAFile() return file def make_image(file): image = makePicture(file) return image def show_image(image): show(image) main()
class Node: def __init__(self,data): self.__data=data self.__next=None def get_data(self): return self.__data def set_data(self,data): self.__data=data def get_next(self): return self.__next def set_next(self,next_node): self.__next=next_node class LinkedList: def __init__(self): self.__head=None self.__tail=None def get_head(self): return self.__head def get_tail(self): return self.__tail def add(self,data): node1=Node(data) if self.__head == None: self.__head = node1 self.__tail = node1 else: self.__tail.set_next(node1) self.__tail = node1 #Remove pass and write the logic to add an element def display(self): temp = self.__head while temp != None: print(temp.get_data()) temp = temp.get_next() #Remove pass and write the logic to display the elements #You can use the below __str__() to print the elements of the DS object while debugging def __str__(self): temp=self.__head msg=[] while(temp is not None): msg.append(str(temp.get_data())) temp=temp.get_next() msg=" ".join(msg) msg="Linkedlist data(Head to Tail): "+ msg return msg list1=LinkedList() list1.add("Sugar") print("Element added successfully") list1.display() # list3.add("Salt") # list3.display() # list2.add("biscuit") # # list1.display() # list2.display()
#DSA-Assgn-7 #This assignment needs DataStructures.py file in your package, you can get it from resources page from src.DataStructures import LinkedList def remove_duplicates(duplicate_list): list1=[] temp = duplicate_list.get_head() while temp is not None: list1.append(temp.get_data()) temp = temp.get_next() a=set(list1) b=list(a) b.sort() temp=duplicate_list.get_head() while temp is not None: duplicate_list.delete(temp.get_data()) temp=temp.get_next() for i in b: duplicate_list.add(i) #write your logic here return duplicate_list #Add different values to the linked list and test your program duplicate_list=LinkedList() duplicate_list.add(30) duplicate_list.add(40) duplicate_list.add(40) duplicate_list.add(40) duplicate_list.add(40) remove_duplicates(duplicate_list)
#DSA-Assgn-4 class Player: def __init__(self,name,experience): self.__name=name self.__experience=experience def get_name(self): return self.__name def get_experience(self): return self.__experience def __str__(self): return(self.__name+" "+(str)(self.__experience)) class Game: def __init__(self,players_list): self.__players_list = players_list def sort_players_based_on_experience(self): for i in range(len(self.__players_list)): for j in range(len(self.__players_list)): if self.__pslayers_list[i].get_experience() > self.__players_list[j].get_experience(): self.__players_list[i],self.__players_list[j] = self.__players_list[j],self.__players_list[i] def shift_player_to_new_position (self,old_index_position, new_index_position): element=self.__players_list.pop(old_index_position) self.__players_list.insert(new_index_position,element) #temp= self.__players_list[old_index_position] # self.__players_list[old_index_position]= self.__players_list[new_index_position] # self.__players_list[new_index_position]=temp # self.__players_list.insert(new_index_position,self.__players_list[old_index_position]) def display_player_details(self): for i in self.__players_list: print(i.get_name," ",i.get_experience()) #Implement Game class here player1=Player("Dhoni",15) player2=Player("Virat",10) player3=Player("Rohit",12) player4=Player("Raina",11) player5=Player("Jadeja",13) player6=Player("Ishant",9) player7=Player("Shikhar",8) player8=Player("Axar",7.5) player9=Player("Ashwin",6) player10=Player("Stuart",7) player11=Player("Bhuvneshwar",5) #Add different values to the list and test the program players_list=[player1,player2,player3,player4,player5,player6,player7,player8,player9,player10,player11] print(player1) game=Game(players_list) game.sort_players_based_on_experience() game.shift_player_to_new_position(0, 4)
#OOPR-Assgn-18 class Customer: def __init__(self,customer_name): self.__customer_name = customer_name self.__payment_status = None def get_customer_name(self): return self.__customer_name def get_payment_status(self): return self.__payment_status def pays_bill(self,bill): self.__payment_status = "Paid" #print("customer name",self.__customer_name,"bill id",bill.get_bill_id(),"bill amount",bill.get_bill_amount()) class Bill: counter = 1000 def __init__(self): self.__bill_id =None self.__bill_amount =None def get_bill_id(self): return self.__bill_id def get_bill_amount(self): return self.__bill_amount def generate_bill_amount(self,item_quantity,items): Bill.counter +=1 self.__bill_id = "B" + str(Bill.counter) self.__bill_amount = 0 for key,values in item_quantity.items(): for item in items: self.__item_id = item.get_item_id() if self.__item_id.lower() == key.lower(): self.__bill_amount += values * item.get_price_per_quantity() class Item: def __init__(self,item_id,description,price_per_quantity): self.__item_id = item_id self.__description = description self.__price_per_quantity = price_per_quantity def get_item_id(self): return self.__item_id def get_description(self): return self.__description def get_price_per_quantity(self): return self.__price_per_quantity
''' Created on Sep 20, 2018 @author: jatin.pal ''' def encode(message): result = "" oldL = message[0] count = 1 for i in range(1,len(message)): if(message[i] == oldL): count +=1 else: result += str(count) + oldL oldL = message[i] if(i == len(message)-1):result += str(count) + oldL #print(oldL) count =1 return result #Provide different values for message and test your program encoded_message=encode("AABCCA") print(encoded_message)
#task 1 import numpy as np old = np.array([[1, 1, 1], [1, 1, 1]]) new = old new[0, :2] = 0 print(old) #task 2 old = np.array([[1, 1, 1], [1, 1, 1]]) new = old.copy() new[:, 0] = 0 print(old)
''' PROJECT 8 - Graphs Name: Clare Kinery ''' import random def Generate_edges(size, connectedness): """ DO NOT EDIT THIS FUNCTION Generates directed edges between vertices to form a DAG :return: A generator object that returns a tuple of the form (source ID, destination ID) used to construct an edge """ assert connectedness <= 1 random.seed(10) for i in range(size): for j in range(i + 1, size): if random.randrange(0, 100) <= connectedness * 100: yield f'{i} {j}' # Custom Graph error class GraphError(Exception): pass class Vertex: """ Class representing a Vertex in the Graph """ __slots__ = ['ID', 'index', 'visited'] def __init__(self, ID, index): """ Class representing a vertex in the graph :param ID : Unique ID of this vertex :param index : Index of vertex edges in adjacency matrix """ self.ID = ID self.index = index # The index that this vertex is in the matrix self.visited = False def __repr__(self): return f"Vertex: {self.ID}" __str__ = __repr__ def __eq__(self, other): """ DO NOT EDIT THIS METHOD :param other: Vertex to compare :return: Bool, True if same, otherwise False """ return self.ID == other.ID and self.index == other.index def out_degree(self, adj_matrix): """ Returns the number of incoming edges from the given matrix :param adj_matrix: matrix :return: int """ vert_lst = adj_matrix[self.index] count = 0 for i in vert_lst: if i is not None: count += 1 return count def in_degree(self, adj_matrix): """ Returns the number of outgoing edges from the given matrix :param adj_matrix: matrix :return: int """ count = 0 for lst in adj_matrix: if self.ID in lst: count += 1 return count def visit(self): """ Returns whether or not a Vertex has be visited :return: Boolean """ self.visited = True class Graph: """ Graph Class ADT """ def __init__(self, iterable=None): """ DO NOT EDIT THIS METHOD Construct a random Directed Graph :param size: Number of vertices :param: iterable: iterable containing edges to use to construct the graph. """ self.id_map = {} self.size = 0 self.matrix = [] self.iterable = iterable self.construct_graph() if hasattr(iterable, 'close'): iterable.close() def __eq__(self, other): """ DO NOT EDIT THIS METHOD Determines if 2 graphs are Identical :param other: Graph Object :return: Bool, True if Graph objects are equal """ return self.id_map == other.id_map and self.matrix == other.matrix and self.size == other.size def get_vertex(self, ID): """ Returns the vertex based on ID :param ID: Vertex ID :return: Vertex """ return self.id_map[ID] def get_edges(self, ID): """ Returns a set containing all edges of the vertex with given ID :param ID: Vertex ID :return: set of edges """ v= [] v.extend(self.matrix[self.get_vertex(ID).index]) while None in v: v.remove(None) return set(v) def construct_graph(self): """ Iterates through the iterable, constructing a graph :return: None """ if self.iterable is None: raise GraphError for i in self.iterable: s, d = i.split() self.insert_edge(int(s), int(d)) #not sure if those are ints def insert_edge(self, source, destination): """ Creates vertex object if necessary and adds to graph based on IDs given :param source: Vertex ID :param destination: Vertex ID :return: None """ if source not in self.id_map: for lst in self.matrix: lst.append(None) svert = Vertex(source, self.size) self.id_map[source] = svert #add to map self.size += 1 self.matrix.append([None for i in range(self.size)]) #not sure if destination not in self.id_map: for lst in self.matrix: lst.append(None) dvert = Vertex(destination, self.size) self.id_map[destination] = dvert #add to map self.size += 1 self.matrix.append([None for i in range(self.size)]) #not sure sindex = self.id_map[source].index dindex = self.id_map[destination].index self.matrix[sindex][dindex] = destination def bfs(self, start, target, path=None): """ Does a breadth search of graph for target beginning at start and generates a path to return. :param start: Vertex ID :param target: Vertex ID :param path: None :return: set containing the path """ big_lvl = [start] level = [start] self.get_vertex(start).visited = True while len(level) > 0: next_level = [] for u in level: for e in self.get_edges(u): if self.get_vertex(e).visited == False: self.get_vertex(e).visited = True next_level.append(e) big_lvl.append(e) level = next_level if target not in big_lvl: return [] while big_lvl[-1] != target: big_lvl.pop() last = target for i in reversed(big_lvl): if i is last: #skip first iter continue if last not in self.get_edges(i): big_lvl.remove(i) else: last = i return big_lvl def dfs(self, start, target, path=None): """ Does a depth search of graph for target beginning at start and generates a path to return. :param start: Vertex ID :param target: Vertex ID :param path: list :return: set containing the path """ if path is None: path = [start] else: path.append(start) vert_start = self.get_vertex(start) vert_start.visited = True if start is target: return path for i in self.get_edges(start): while path[-1] != start: path.pop() vert = self.get_vertex(i) if vert.visited == False: self.dfs(i, target, path) if target in path: return path if target in path: return path else: return [] def find_k_away(K, iterable, start): """ Creates a graph and eturns Vertex IDs K away from given start as a set :param K: int :param iterable: iterable :param start: Vertex ID :return: set of Vertex IDs """ graph = Graph(iterable) try: graph.get_vertex(start).visited except KeyError: return set() if K == 0: return {start} return get_vert(K, graph, start, start) def get_vert(K, graph, start, beg): """ Recursively finds the Vertex IDs for a given graph K away from the strating Vertex ID :param K: int :param graph: Graph :param start: Vertex ID :param beg: Vertex ID, holds initial :return: set containing Vertex IDs """ lst = [] if K == 0 and start is not beg: graph.get_vertex(start).visited = False return start if graph.get_vertex(start) is None: return set() for i in graph.get_edges(start): if graph.get_vertex(i).visited == False: graph.get_vertex(i).visited = True v = get_vert(K-1, graph, i, beg) if isinstance(v, set): v = list(v) if isinstance(v, list): lst.extend(v) else: lst.append(v) return set(lst)
import re import sys from datetime import datetime class nudb: #method save() to insert entries into the database def __init__(self): self.log_fh = open('logs/log.txt','a') def save(self,object): ''' This method saves the entries into the database use case: 1)If you want to save a single article entry into the article database save method can be used 2)If you would want to save multiple entries into the article database save method can be used examples 1) db.save({'keywords':('android','ios',),'title':'The android related article'}........) 1) db.save([{'keywords':('android','ios',),'title':'The android related article'}........},{'keywords':('hp'),......}]) ''' content_file = "saved_content/content.txt" #saved_entries_list holds all the entries to be written to the file #saved content is to write the content of the corresponding entry into a separare file saved_entries_list =[] saved_content_list =[] start = datetime.now() #if the type of the object passed is a single dictionary if isinstance(object,dict): tuple_returned= self.__create_dict(object , content_file) saved_entries_list.append(tuple_returned[0]) saved_content_list.append(tuple_returned[1]) #if the type of the object is a list elif isinstance(object,list): for each_document in object: tuple_returned =self.__create_dict(each_document,content_file) saved_entries_list.append(tuple_returned[0]) saved_content_list.append(tuple_returned[1]) else: print "Invalid syntax for save method" self.log_fh.writelines("Invalid syntax for save method"+" @ "+str(datetime.now())) sys.exit(1) entries_fh = open('saved_entries/entries.txt','a') for eachEntry in saved_entries_list: entries_fh.writelines(str(eachEntry)) entries_fh.writelines('\n') entries_fh.close() content_fh = open('saved_content/content.txt','a') for eachContent in saved_content_list: content_fh.writelines(str(eachContent)) content_fh.writelines('\n') content_fh.close() end = datetime.now() print "Wrote "+str(len(saved_entries_list))+" entries in: "+str(end-start)+" second" self.log_fh.writelines("Wrote "+str(len(saved_entries_list))+" enrties @ "+str(datetime.now())+"\n") def __create_dict(self , object , content_file): f = open('count.txt','r'); count = int(f.readline()) f.close() id = count + 1 keywords = object['keywords'] likes = object['likes'] comments = object['comments'] category = object['category'] title = object['title'] pub_date = object['pub_date'] text = str(id) + '-' + str(content_file) content = object['text'] description = object['description'] save_entry = {'id':id , 'keywords':keywords , 'likes':likes , 'comments':comments ,'category':category , 'text':text , 'pub_date':pub_date} save_content = {'id':id,'title':title,'description':description , 'content':content} f = open('count.txt','w') f.writelines(str(id)) f.close(); return (save_entry , save_content) def evaluate(self,query): ''' evaluate(query) -> none query => string If the query is a valid query prints the result/results ''' m = self.__validate(query) log_fh = open('logs/log.txt','a') if(m): start = datetime.now() groups = m.groups() selected_entries = [] if(groups[0] != None): #This means that ALL has been specified in the query and all the articles have to be displayed f = open('saved_content/content.txt' ,'r') for eachEntry in f: selected_entries.append(eval(eachEntry)) f.close() self.__writelog(query,len(selected_entries)) return self.__return_articles(selected_entries) elif(groups[0] == None and (groups[5] == None and groups[6] == None and groups[7] == None and groups[8] == None and groups[9] == None)) : #This means that the query is with the a single projection and there is no conjunction selection = groups[1].lower() projection1 = groups[2].lower() operator1 = groups[3].lower() value1 = groups[4].lower() if value1 == "max": value1 =str(max(self.__find_max_min(projection1))) if value1 == "min": value1 =str(min(self.__find_max_min(projection1))) f = open("saved_entries/entries.txt","r") for eachEntry in f: if self.__filter_entries(eval(eachEntry),projection1,operator1,value1): selected_entries.append(eval(eachEntry)) if selection == 'title' or selection == 'articles': f.close() self.__writelog(query,len(selected_entries)) return self.__selection(selected_entries, selection) else: if len(selected_entries) != 0: #This is a list that is used to return the information as JSON json_list = [] for eachEntry in selected_entries: # print '#'*75 # print str(selection).upper()+": " +eachEntry[selection] json_list.append({str(selection):str(eachEntry[selection])}) # print '#'*75 # print '\n' f.close(); self.__writelog(query,len(selected_entries)) return json_list else: json_list = [{"error_code":"502"}] self.log_fh.writelines("Query:"+query+"No matching article"+str(datetime.now())+"\n") return json_list # print "No Matching article" else: #There is a second projection with a conjuction or a disjunction selection = groups[1].lower() projection1 = groups[2].lower() operator1 = groups[3].lower() value1 = groups[4].lower() conjuction_disjunction = groups[6].lower() projection2 = groups[7].lower() operator2 = groups[8].lower() value2 = groups[9].lower() if value1 == "max": value1 =str(max(self.__find_max_min(projection1))) if value1 == "min": value1 =str(min(self.__find_max_min(projection1))) if value2 == "max": value2 =str(max(self.__find_max_min(projection2))) if value2 == "min": value2 =str(min(self.__find_max_min(projection2))) f = open("saved_entries/entries.txt") for eachEntry in f: if self.__filter_entries(eval(eachEntry),projection1,operator1,value1,conjuction_disjunction,projection2,operator2,value2): selected_entries.append(eval(eachEntry)) if selection == 'title' or selection == 'articles': f.close() self.__writelog(query,len(selected_entries)) return self.__selection(selected_entries, selection) else: if len(selected_entries) != 0: for eachEntry in selected_entries: # print '#'*50 # print str(selection).upper()+": " +eachEntry[selection] json_list.append({str(selection):str(eachEntry[selection])}) # print '#'*50 # print '\n' f.close(); self.__writelog(query,len(selected_entries)) return json_list else: json_list = [{"error_code":"502"}] self.log_fh.writelines("Query:"+query+"No matching article"+str(datetime.now())+"\n") return json_list # print "No Matching article" end = datetime.now() print "Fetched "+str(len(selected_entries))+" entries in: "+str(end - start)+' second' self.log_fh.writelines("Query: "+query+" fetched "+str(len(selected_entries))+" entries @ "+str(datetime.now())+"\n") else: #This means this is an invalid query json_list = [] #print "Invalid query" self.log_fh.writelines("Query: "+query+" Invalid query @ "+str(datetime.now())+"\n") json_list.append({'error_code':"500"}) return json_list def __selection(self,entries_list,selection): # This is called only when the selection is articles or titles #This makes sure that the file content.txt has to be really opened selection = selection.lower() id_list = [] for eachEntry in entries_list: id_list.append(int(eachEntry["text"].split("-")[0])) i = 0 len_id_list = len(id_list) if(len_id_list == 0): print "No Matching article" return f = open('saved_content/content.txt','r') json_list = [] for eachEntry in f: each_entry = eval(eachEntry) if i < len_id_list: if each_entry['id'] == id_list[i]: if selection == "title": # print '#'*75 # print str(selection.upper())+": "+each_entry[selection] json_list.append(dict(title=str(each_entry['title']))) i = i +1 # print '#'*75 # print '\n' else: #the selection is articles # print '#'*75 json_list.append(dict(title=str(each_entry['title']),description=str(each_entry['description']),content=str(each_entry['content']))) # print "TITLE: " + each_entry['title'] # print "DESCRIPTION: "+each_entry['description'] # print "CONTENT: "+each_entry['content'] i = i+1 # print '#'*75 # print '\n' else: break return json_list def __filter_entries(self,entry,projection1,operator1,value1,conjunction_disjunction=None,projection2=None,operator2=None,value2=None): if conjunction_disjunction==None: if (isinstance(entry[projection1] , tuple)): #the projection is a tuple return value1 in entry[projection1] else: try: if(operator1 == '='): operator1 = '==' statement = entry[projection1]+operator1+value1 return eval(statement) except NameError: return False else: #Here there is an and/or clause if(isinstance(entry[projection1],tuple) and isinstance(entry[projection2],tuple)): return eval((str(value1 in entry[projection1]) ) +" " +conjunction_disjunction + " "+ (str(value2 in entry[projection2]))) try: if(isinstance(entry[projection1],tuple)) and (isinstance(entry[projection2],str)): if(operator2 == '='): operator2 = '==' return eval((str(value1 in entry[projection1])) + " " +conjunction_disjunction+" "+str(eval(entry[projection2]+operator2+value2))) except NameError: return False try: if(isinstance(entry[projection1],str)) and (isinstance(entry[projection2],tuple)): if(operator1 == '='): operator1 = '==' return eval(str(eval(entry[projection1]+operator1+value1))+" "+conjunction_disjunction+" "+str(value2 in entry[projection2])) except NameError: return False try: if(isinstance(entry[projection1],str)) and (isinstance(entry[projection2],str)): if(operator1 == '='): operator1 = '==' if(operator2 == '='): operator2 = '==' return eval(str(eval(entry[projection1]+operator1+value1))+" "+conjunction_disjunction+" "+str(eval(entry[projection2]+operator2+value2))) except NameError: return False def __validate(self,query): reg1 = "(SELECT ALL)" reg2 = "SELECT (TITLE|PUB_DATE|LIKES|COMMENTS|ARTICLES) WHERE" reg3 = "(CATEGORY|PUB_DATE|LIKES|COMMENTS|KEYWORDS)(=|<|>|<=|>=|!=)(\w+)" regex = reg1 + "|" + reg2+ " " + reg3 + "( (and|or) " + reg3 +")?" m = re.match(regex,query) return m def __return_articles(self,list_): json_list = [] for eachEntry in list_: json_list.append(dict(title=str(eachEntry['title']),description=str(eachEntry['description']),content=str(eachEntry['content']))) return json_list def __find_max_min(self,likes_comments): likes_comments.lower() f = open('saved_entries/entries.txt','r') try: list_ = [ int(eval(eachLine)[likes_comments]) for eachLine in f] except Exception: print "Invalid condition" self.log_fh.writelines("Invalid condition specified for maximum minimum....Maximum and minimum of COMMENTS and LIKES only can be found @ "+str(datetime.now())+"\n") sys.exit(1); finally: f.close() return list_ def __del__(self): self.log_fh.close() def __writelog(self,query,no_of_selected_entries): self.log_fh.writelines("Query: "+query+" fetched "+str(no_of_selected_entries)+" entries @ "+str(datetime.now())+"\n") if __name__ == "__main__": print ''' ######ARTICLE-NGIN####### This is an article query engine.Query the past articles and enjoy reading them THE KEYWORDS THAT ARE INCLUDED IN THE Article-ngin SELECT ALL WHERE MAX MIN TITLE CATEGORY KEYWORDS PUB_DATE COMMENTS LIKES Querying model is as follows "SELECT ALL" selects all the entries in the database and displays them "SELECT TITLE WHERE CATEGORY=android" selects all the articles where the category = android Before the WHERE part is called as SELECTION and after the where part is called as PROJECTION THE SELECTION part may contain the following keywords TITLE,PUB_DATE,LIKES,COMMENTS,ARTICLES THE PROJECTION part may contain the following keywords CATEGORY,PUB_DATE,LIKES,COMMENTS,KEYWORDS SELECT ARTICLES WHERE LIKES=MAX This selects the articles and displays the TITLE DESCRIPTION and TEXT which has the maximum number of likes If there are many articles with the same number of articles then all of them will be displayed The operators supported are > < >= <= != = SELECT ARTICLES WHERE LIKES > 20 selects all the articles having likes greater than 20 CONJUCTION and DISJUNCTION support SELECT TITLE WHERE CATEGORY=android and LIKES=MAX This selects all the android articles having maximum number of likes and displays the title SELECT TITLE WHERE CATEGORY=android or CATEGORY=big-data SELECTS all the articles having cateogry as android or as big data ''' flag = True db = nudb() while flag == True: print"-"*150 print"1.Save data" print"2.Query your favourite article" print"3.Exit" print"-"*150 menu_choice = raw_input("Select the choice(Please enter the menu item number) \n") if(menu_choice == '1'): file_name = raw_input("Enter the file name where the input is present \n") fh = open(file_name,'r') list_ = [] for eachLine in fh: list_.append(eval(eachLine)) db.save(list_) fh.close(); elif menu_choice == '2': query = raw_input('Enter the query: \n') db.evaluate(query) elif menu_choice == '3': flag = False else: print "Invalid choice"
# Import everything from tkiner. from tkinter import * root = Tk() def clik_zero(): greeting = "Hello "+ entry_zero.get() + "!" label_zero = Label(root, text=greeting) label_zero.pack() # Creating of an entery. entry_zero = Entry(root, width=50, borderwidth=10, bg="#dedede", fg="#004f3b") # Pack the entry box. entry_zero.pack() # Placeholder text entry_zero.insert(0, "Enter your name here:") button_zero = Button(root, text="Enter Your Name", padx = 20, pady = 10, fg = "#ffffff", bg="#858585", command=clik_zero) button_zero.pack() root.mainloop()
# coding: utf-8 # author: RaPoSpectre # time: 2016-09-20 # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def system_change(self, l3): pp = l3 while True: if l3.val >= 10: l3.val = l3.val - 10 tm, l3 = l3, l3.next if not l3: tm.next = ListNode(1) else: l3.val += 1 else: l3 = l3.next if not l3: return pp def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ p1 = l1 p2 = l2 p3 = p3h = None while True: if p1 and p2: if p3: p3.next = ListNode(p1.val + p2.val) p3 = p3.next else: p3h = p3 = ListNode(p1.val + p2.val) p1 = p1.next p2 = p2.next if p1 and not p2: p2 = ListNode(0) if p2 and not p1: p1 = ListNode(0) if not (p1 and p2): return self.system_change(p3h)
from abc import abstractmethod import Algorithms from Core import LOGGER logger = LOGGER.attach(__name__) class Player(): @staticmethod def create_player(args): if (args["type"].upper() == "HUMAN"): logger.info("Creating Human " + args["colour"]) return Human(args["colour"]) else: logger.info("Creating Bot " + args["colour"]) algorithm = Algorithms.create_algorithm(args) return Bot(args["colour"], algorithm) num_players = 0 colours = { "RED":((255,0,0)), "GREEN":(0,255,0), "BLUE":(0,0,255), "BLACK":(0,0,0), "WHITE":(255,255,255), "YELLOW":(255,255,0), "AQUA":(0,128,128), "GRAY":(128,128,128), "NAVY":(0,0,128), "ORANGE":(265,165,0) } def set_learning(self, bool): logger.info("Setting learning to " + str(bool) + " for " + self.colour) self.algorithm.set_learning(bool) def __init__(self, colour): Player.num_players += 1 self.algorithm = None if colour.upper() in self.colours: self.colour = colour.upper() else: self.colour = "BLACK" self.number = Player.num_players @abstractmethod def get_choice(self, board): pass def __repr__(self): return self.colour def __str__(self): return self.colour def __int__(self): return self.number def get_rgb(self): return self.colours[self.colour] @abstractmethod def save(self): pass import random class Human(Player): def __init__(self, colour): Player.__init__(self, colour) def get_choice(self, board): actions = board.get_actions() board.print() print("Select from: ", actions , end=": ") user_action = int(input()) return user_action class Bot(Player): def __init__(self, colour, algorithm): Player.__init__(self, colour) self.best_choice = -1 self.algorithm = algorithm self.learning = True def get_choice(self, board): return self.algorithm.get_move(state=board) def clear_memory(self): print(self.colour, ": clearing memory") self.algorithm.clear_memory() def save(self, tag = ""): self.algorithm.save_memory(tag)
# Project : Quiz Game print("Welcome to Computer Quiz Game!") playing = input("Do you want to Play? ") if playing.lower() != "yes": quit() print("Okay! Let's play! \n") score = 0 # Question 1 answer = input("What does CPU stands for? ") if answer.lower() == "central processing unit": print('Correct!') score += 1 else: print('Incorrect!') # Question 2 answer = input("What does GPU stands for? ") if answer.lower() == "graphic processing unit": print('Correct!') score += 1 else: print('Incorrect!') # Question 3 answer = input("What does SPU stands for? ") if answer.lower() == "supply power unit": print('Correct!') score += 1 else: print('Incorrect!') # Question 4 answer = input("What does SU stands for? ") if answer.lower() == "system unit": print('Correct!') score += 1 else: print('Incorrect!') # Percentage percentage = ((score/4)*100) # Output using newer string formatting print(f"You got {score} questions correct!") print(f"You got {percentage}%")
import random d={8:37,38:9,11:2,13:34,40:64,65:46,52:81} p=random.choice([2,8,9,13,40,65,52]) print("You got... ",p) if p in d: if p>d[p]: print("Oops a Snake") else: print("Climb the ladder") print("you can go to",d[p])
# 예제 3. 4변수함수 f(w,x,y,z) = wx + xyz + 3w + zy^2를 미분하여 ## f'(1.0, 2.0, 3.0, 4.0)의 값을 구하여라. import numpy as np def numerical_derivative(f, x) : delta_x = 1e-4 grad = np.zeros_like(x) it = np.nditer(x, flags=["multi_index"],op_flags=["readwrite"]) while not it.finished : idx = it.multi_index tmp_val = x[idx] x[idx] = tmp_val + delta_x fx1 = f(x) x[idx] = tmp_val - delta_x fx2 = f(x) grad[idx] = (fx1 - fx2) / (2 * delta_x) x[idx] = tmp_val it.iternext() return grad def func3(input_obj) : w = input_obj[0,0] x = input_obj[0,1] y = input_obj[1,0] z = input_obj[1,1] return ( w*x + x*y*z + 3*w + z*np.power(y,2) ) input = np.array( [[1.0, 2.0], [3.0, 4.0]]) result = numerical_derivative(func3, input) print (result)
""" # Derivative : 미분 f'(x) = df(x) / dx x가 변할 때, f(x)가 얼마나 변하는 지를 구하는 것 f(x)가 입력 x의 미세한 변화에 얼마나 민감하게 반응하는 지 알 수 있는 식 # 머신러닝 / 딥러닝에서 자주 사용되는 함수의 미분 (1) f(x) = a (a는 상수) / f'(x) = 0 (2) f(x) = ax^n (a는 상수) / f'(x) = nax^n-1 (3) f(x) = e^x / f'(x) = e^x (자기자신) (4) f(x) = ln x / f'(x) = 1 / x (5) f(x) = e^(-x) / f'(x) = -e^(-x) # Partial Derivaive : 편미분 편미분은 입력변수가 하나 이상인 다변수 함수에서, 미분하고자 하는 변수 하나를 제외한 나머지 변수들은 상수로 취급하고, 해당 변수를 미분하는 것 # Chain rule : 연쇄법칙 합성함수란 여러 함수로 구성된 함수로서, 이러한 합성함수를 미분하려면 '합성함수를 구성하는 각 함수의 미분의 곱'으로 나타내는 chain rule(연쇄법칙)이용 (예시1) f(x) = e^(3x^2) / 함수 e^t와 t = 3x^2 조합 (예시2) f(x) = e^(-x) / 함수 e^t와 t=-x 조합 """
def generar_lista_con_saltos(tamanio_listas,salto_entre_elemento,lista): if type(lista) not in [list]: raise TypeError("se espera una lista en el parametro lista para generar una lista con saltos") if type(tamanio_listas) not in [int]: raise TypeError("se espera un entero") if type(salto_entre_elemento) not in [int]: raise TypeError("se espera un entero") if (salto_entre_elemento <= 0) : raise ValueError("el salto debe ser almenos 1(es decir sin saltar elementos") lista_final=[] indice_inicio=0 donde_termina = indice_inicio + salto_entre_elemento*(tamanio_listas-1) while(donde_termina<len(lista)): nueva_lista=[] for i in range(tamanio_listas): nueva_lista.append(lista[(indice_inicio+(salto_entre_elemento*i))]) if(len(nueva_lista)>0): lista_final.append(nueva_lista) indice_inicio=indice_inicio+1 donde_termina = indice_inicio + salto_entre_elemento * (tamanio_listas - 1) return lista_final
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Administrator' #字符统计,统计文本中除空格以外的字符数目 with open("hh.txt", 'r') as f: res = 0 res1 = 0 for line in f: res1 +=1 for word in line.split(): res +=len(word) print res1, res '文件过滤,显示一个文件的所有行,忽略#开头的行' with open('hh.txt','r') as f: for line in f: if line[0] == '#': pass else: print line N = raw_input('Please input the paramter N:') print 1
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 20:18:00 2020 @author: Ercan Karaçelik """ def linear_search(item,my_list): i=0 found=False while i<len(my_list) and found==False: if my_list[i]==item: found=True else: i+=1 return found test=[6,5,8,2,3,70] print(linear_search(87,test)) print(linear_search(70,test))
# -*- coding: utf-8 -*- """ Created on Sat Mar 28 14:04:34 2020 @author: Ercan Karaçelik """ #Dictionaries, Zip Command, Matplotlib lorem_ipsum=""" What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a and type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. """ letter_counts = dict() for i in lorem_ipsum: letter_counts[i] = letter_counts.get(i, 0) + 1 import matplotlib.pyplot as plt x,y= zip(*letter_counts.items()) """ If we want to extract the zip, we have to use the same zip()function. But we have to add an asterisk(*) in front of that list you get from the zipped variable. """ plt.bar(x,y) plt.show() letter_counts_isalpha={} for i in lorem_ipsum: if i.isalpha(): letter_counts_isalpha[i.lower()] = letter_counts_isalpha.get(i.lower(), 0) + 1 print(letter_counts_isalpha) x,y= zip(*letter_counts_isalpha.items()) plt.bar(x,y) plt.show()
# -*- coding: utf-8 -*- """ Created on Wed Apr 1 09:56:49 2020 @author: Ercan Karaçelik """ # CLASS # naming class and function # my_function # MyClass class Patience(object): ''' Class Definition''' status='patience' def __init__(self,name,age): self.var_name=name self.var_age=age self.conditions=[] def get_details(self): print(f'Patience Record:{self.var_name}, {self.var_age}'\ f'Current Informaion: {self.conditions}') def add_info(self,information): self.conditions.append(information) ercan= Patience("Ercion",58) ercan.add_info('he is awesome') print(ercan.get_details())
shoppingList = [] # This item shows how to navigate the app. def show_help(): print("Welcome the shopping app.") print(""" --------------------------------------------- SHOW - Show All Items currently on the list DONE - Finish the list and exit out of the app. HELP - Show this line. UPDATE - Updates an item in the index. DELETE - deletes an item from the list. --------------------------------------------- """) def show_help_other(): print("Welcome the shopping app.") print(""" Instruction ---------------------------------------------- SHOW - Show All Items currently on the list DONE - Finish the list and exit out of the app. HELP - Show this line. ---------------------------------------------- """) # This method adds items to a list. def add_item(item): shoppingList.append(item) print("{} added! You now have {} items.".format(item, len(shoppingList))) # This one simple finish the app and closes. def finish(item): print("Here are your items:") for item in shoppingList: print(item) print("In total, you added {} items".format(len(shoppingList))) # Shows the items the user has inputted so far. def show_item(): if len(shoppingList) == 0: print("You don't have any items yet. Come back when you've added some.") main() else: for item in shoppingList: print(item) # This method allows the user to update an item to the list. def update(): if len(shoppingList) == 0: print("Try added some item and come back again.") else: item = input("Select the item you want to update") while item != "CANCEL" or "SHOW": if item in shoppingList: new_item = input("Select the item you want to replace it with.") for item, new_item, n in shoppingList: if item == shoppingList[n]: shoppingList[n] = new_item print("{} has been replaced with {}".format(item, new_item)) main() else: print("Item does not exist. Returning to the main program.") main() elif item == "SHOW": show_item() continue elif item == "CANCEL": main() else: print("There's no item like that. Try again") continue def delete(): if len(shoppingList) == 0: print("You cannot delete items until you've got some items") main() else: item = input("Select an item on the list that you want to delete\n") if item in shoppingList: shoppingList.remove(item) print("{} has been deleted. It will be free, so be sure to add an item to replace it.") elif item == "CANCEL": print("Going back to the main menu.") main() else: print("Item does not exist. Press the show button to see the item that exists") while item not in shoppingList or item != "CANCEL": item = input("Select an item on the list that you want to delete") def main(): show_help() while True: # Ask for new items item = input("Enter your item\n") if item == "SHOW": show_item() continue elif item == "DONE": break elif item == "HELP": show_help() continue elif item == "UPDATE": update() continue elif item == "DELETE": delete() continue else: add_item(item) # List item main()
''' 1.산술 연산자 + - * / : 두값을 나눈 결과를 반환(실수 값) // : 두 값을 나눈 결과의 몫 반환(정수 값) % : 두 값을 나눈 결과의 나머지 반환 ** : 거듭 제곱의 결과 바환 == : 두 피 연산자 값을 비교하여 동일하면 True, 동일하지 않으면 False 예) 3==3 (True) , 3==4(False) != : 두 피 연산자 값을 비교하여 동일하면 False, 동일하지 않으면 True(연산자 '=='와 반대개념) > : 두 피 연산자 값을 비교하여 왼쪽의 값이 크면 True, 그렇지 않으면 False < : 오른쪽의 값이 크면 True, 그렇지 않으면 False >= : 두 피 연산자 값을 비교하여 왼쪽의 값이 크거나 같으면 True, 그렇지 않으면 False <= : 오른쪽의 값이 크거나 같으면 True, 그렇지 않으면 False * 파이썬에 True == 1 => True * ''' x=input('정수 혹은 문자1 : ') y=input('정수 혹은 문자2 : ') print('x는 {}이고, y는 {}일때.'.format(x,y)) print('x==y는 {}'.format(x==y)) # 같음과 다름은 숫자, 문자끼리 비교가 가능하며 숫자와 문자도 비교 가능하고, type(int,float)과 type(str)도 비교 가능 print('x!=y는 {}'.format(x != y)) print('x<y는 {}'.format(x<y)) print('x>y는 {}'.format(x>y)) print('x<=y는 {}'.format(x<=y)) print('x>=y는 {}'.format(x>=y)) print('{:-^50}'.format('-')) ''' 2.논리 연산자 and : 두 피 연산자가 전부 True인 경우에만 Trud(논리곱) or : 두 피 연산자가 전부 False인 경우에만 False(논리합) not : 오른쪽 피 연산자에 대한 부정 ''' print("x=3,y=5,a='a',b='b'일때") x=3 y=5 a='a' b='b' print('x<y는 {}'.format(x<y)),print('a!=b는 {}'.format(a!=b)) print(' x<y and a!=b는 {}'.format(x<y and a!=b)) print(' x>y and a==b는 {}'.format(x<y and a==b)) print('x>y or a!=b는 {}'.format(x<y and a!=b)) print('not x<y는 {}'.format(x<y)) print('{:-^50}'.format('-')) ''' 3.멤버 연산자 in : 왼쪽 피 연산자 값이 오른쪽 피 연산자 멤버 중 일치하는 값이 존재 하면 not in : 왼쪽 피 연산자 값이 오른쪽 피 연산자 멤버 중 일치하는 값이 존재 하지 않으면 True 4.식별 연산자 is : 두 피 연산자의 식별 값을 비교하였을 때 동일한 객체이면 True is not : 두 피 연산자의 식별 값을 비교하였을 때 동일한 객체이면 False ''' print(1 in (1,2,3,4)) print(2 in (1,3,5,7)) print(1 is type(str)) print(1 is not type(str)) print('{:-^50}'.format('-')) ''' 4.비트 연산자 & : 두 피 연산자의 and 비트 연산을 수행함 0&0 -> 0 0&1 -> 0 1&0 -> 0 1&1 -> 1 | : 두 피 연산자의 or 비트 연산을 수행함 0 | 0 -> 0 0 | 1 -> 1 1 | 0 -> 1 1 | 1 -> 1 ^ : 두 피 연산자의 xor 비트 연산을 수행함 0^0 -> 0 0^1 -> 1 1^0 -> 1 1^1 -> 0 [자석의 N극 S극 개념과 비슷] << : 왼쪽 피 연산자의 비트를 왼쪽으로 2개 비트 이동 비트 2배 증가 >> : 왼쪽 피 연산자의 비트를 오른쪽로 2개비트 이동 비트 2배 감소 ''' print(bin(10)) print(bin(5)) print(10&5) ''' 10=1010 & 5=0101 ---------- 0000 = 0 ''' print(10 | 5) ''' 10=1010 | 5=0101 ----------- 1111 = 15 ''' print(10^5) ''' 10=1010 ^ 5=0101 ------------ 1111 = 15 ''' print(10<<2) ''' 10 = 1010 10<<2 = 101000 = 40 => 1010'00' : 2개 오른쪽으로 이동 ''' print(bin(10<<2)) # 10<<2 를 비트 값으로 출력 print('{:b}'.format(10<<2)) # 10<<2 를 2진수 값으로 출력 print(10>>2) ''' 10 = 1010 10>>2 = 10 = 2 (1010 이 왼쪽으로 2칸 이동하면서 오른쪽 '10'삭제) ''' print(bin(10>>2)) print('{:b}'.format(10>>2))
""" 산술연산자 의미 = 대입 연산자 + 더하기 - 빼기 * 곱하기 / 나누기 // 나누기(몫) ★ % 나머지 구하기★ ** 제곱 """ ''' num1=9;num2=2 print(num1,'+',num2,'=',num1+num2) print(num1,'-',num2,'=',num1-num2) print(num1,'*',num2,'=',num1*num2) print(num1,'/',num2,'=',num1/num2) print(num1,'//',num2,'=',num1//num2) print(num1,'%',num2,'=',num1%num2) print(num1,'**',num2,'=',num1**num2) ''' """ #관계연산자의 모든 자료형은 'bool'임 #모든 기준은 왼쪽에서 오른쪽 관계연산자 의미 a<b a가 b보다 작다 a>b a가 b보다 크다 a<=b a가 b보다 작거나 같다 a>=b a가 b보다 크거나 같다 a == b a와 b가 같으면 (True) a != b a와 b가 다르면 (true) """ ''' S1=3.1;S2=3 print('S1>=S2 : %s'%(S1>=S2)) print('S1<=S2 : %s'%(S1<=S2)) print('S1==S2 : %s'%(S1==S2)) print('S1!=S2 : %s'%(S1!=S2)) print('S1>=S2 : %d'%(S1>=S2)) print('S1<=S2 : %d'%(S1<=S2)) print('S1==S2 : %d'%(S1==S2)) print('S1!=S2 : %d'%(S1!=S2)) print('S1>=S2 : %c'%(S1>=S2)) print('S1<=S2 : %c'%(S1<=S2)) print('S1==S2 : %c'%(S1==S2)) print('S1!=S2 : %c'%(S1!=S2)) print('S1>=S2 : %f'%(S1>=S2)) print('S1<=S2 : %f'%(S1<=S2)) print('S1==S2 : %f'%(S1==S2)) print('S1!=S2 : %f'%(S1!=S2)) ''' """ # a 위치에는 무조건 변수만 가능 / b 에는 변수, 상수 다 가능 #연산해서 좌측에 대입 복합 대입 연산자 의미 a += b a = a + b a -= b a = a - b a *= b a = a * b a /= b a = a / b 기타 다 같게 적용 """ ''' # 6 / 4 / 25 / 1 / 0 S1 = S2 = 5 # 대입연산자는 우측이 최우선, 즉 5가 S2로 대입되고 S2 의 5저장위치가 S1로 대입됨 S1+=1 print('S1 + 1 = ',S1) # 5+1=6 S1-=1 print('S1 - 1 = ',S1) # 6-1=5 S1*=S2 print('S1 * S2 = ',S1) # 5*5=25 S1//=S2 print('S1 // S2 = ',S1) # 25//5=5 S1%=S2 print('S1 % S2 = ',S1) # 5%5=0 '''''' S1=5;S2=3 S1**=S2 print(S1,end= ' ');print(id(S1)) S1-=2 print(S1,end = ' ');print(id(S1)) print('S1 / 4 = ',S1/4) print('S1 // 4 = ',S1//4) print('S1 % 4 = ',S1%4) ''' """ #논리 연산자는 좌측부터 따짐 논리 연산자 사용예 의미 and (a>b)and(a<c) a가 b보다 크고 a가 c보다 작으면 참 [ 참:1,거짓:3] #좌측항이 False면 우측항 무시 or (a>b) or (a<c) a가 b보다 크거나 a가 c보다 작으면 참 [ 참:3,거짓;1] # 좌측항이 True면 우측항 무시 not not(a==b) a 가 b보다 크면 거짓 """ ''' print(0 or 0,':',False or False) print(1 or 0,':',True or False) print(0 or 1,':',False or True) print(1 or 1,':',True or True) print('not : ',not(0 or 0),':',not(False or False)) # not은 반환되는 기본값이 True 와 False이므로 0과1도 False와 True 변환됨 print('not : ',not(1 or 1),':',not(True or True)) '''''' a=20 b=10 print(0 or 0,':',False or (a+b)) # or 앞이 거짓일때는 뒤의 값 반환 (우선순위 때문) print(1 or 0,':',True or (a+b)) # or 앞이 참일때는 뒤 무시 print(0 and 0,':',False and (a+b)) # and 앞이 거짓일때 뒤 값 무시 print(1 and 0,':',True and (a+b)) # and 앞이 값이 참일때 뒤 값 반환 ''' """ 논리 연산자 사용 예 의미 | a | b a와b를 bit로 변환하여 OR 연산 & a&b a와b를 bit로 변환하여 AND 연산 ^ a^b a와b를 bit로 변환하여 XOR 연산(베타적 논리합 : 같은 비트자리에 같은 숫자가 나오면 0, 다르면 1 처리) ~ ~a a를 bit로 변환하여 연산( ~-7 -> 8 , ~8 -> -7) >> a>>2 a를 bit로 변환하여 오른쪽으로 Shift << a<<2 a를 bit로 변환하여 왼쪽으로 Shift """
s = '''import java.util.*; public class BrainyThings { public static void main(String[] args) { Integer[] a = {1, 4, 2, 3, 5}; List<Integer> l = Arrays.asList(a); System.out.println(l); System.out.println(Arrays.toString(a)); l.set(2, 8); System.out.println(l); System.out.println(Arrays.toString(a)); } }''' # f('#a366ff', purple) # f('#ff002b', red) # f('#0099cc', blue) # f('#77b300', green) # f('#ff9900', orange) import re s1 = '' a = re.('[^([A-Za-z][A-Za-z0-9]+)+]', s) print(a)
#!/usr/bin/python3 #This function return integer in [a, b] range def input_int(a, b): print("Please enter the number in [{}, {}] range".format(a,b)) while True: print(">", end=' ') x = input() if x.isdigit(): if(int(x) >= a and int(x) <= b): return x else: print("Only in [{}, {}] range. Try more.".format(a,b)) else: print("Only numbers. Try more.") x = 1 y = 100 number = input_int(x, y) print("Number from our function: {}".format(number))
#!/usr/bin/python3 def find_nonpaired(digits): ''' x, y, flag - 3 variables; for x ... & for y ... - 2 loops res[] - only to return answer from function, so if we rewrite it as one plain function we don't need it ''' res = [] for x in range(0, len(digits)): flag = False for y in range(0, len(digits)): if digits[x] == digits[y] and x != y: print(digits[x], digits[y]) flag = True if not flag: res.append(digits[x]) return res def main(): test = [2, 56, 23, 5, 7, 5, 7, 2] result = [56, 23] if find_nonpaired(test) == result: print("==> OK <==") print("{} nonpaired = {}".format(test, result)) else: print("Something wrong") print("{} nonpaired != {}".format(test, result)) main()
daftar1 = input("Masukan daftar belanja 1 : ") daftar2 = input("Masukan daftar belanja 2 : ") tambah_daftar1 = input("Tambahkan data ke daftar belanja 1 : ") tambah_daftar2 = input("Tambahkan data ke daftar belanja 2 : ") daftar_belanja1 = [daftar1, tambah_daftar1] daftar_belanja2 = [daftar2, tambah_daftar2] print("Daftar belanja 1 adalah", daftar_belanja1[0],",",daftar_belanja1[1]) print("Daftar belanja 2 adalah", daftar_belanja2[0],",",daftar_belanja2[1])
class Stock(object): def __init__(self, stockName, basicHistoricalData, fibonacciNumbers, strategies, links): self.stockName = stockName self.basicHistoricalData = basicHistoricalData self.fibonacciNumbers = fibonacciNumbers self.strategies = strategies self.links = links class Links(object): secondStrategyTest = "" thirdStrategyTest = "" def __init__(self, secondStrategyTestLink, thirdStrategyTestLink): self.secondStrategyTest = secondStrategyTestLink self.thirdStrategyTest = thirdStrategyTestLink class BasicHistoricalData(object): openPrice = 0.0 closePrice = 0.0 prevClose = 0.0 todayDifference = 0.0 percentChange = 0.0 volume = 0.0 tenDayAverageDifference = 0.0 twentyDayAverageDifference = 0.0 thirtyDayChange = 0.0 # The class "constructor" - It's actually an initializer def __init__(self, openPrice, closePrice, prevClose, todayDifference, percentChange, volume, tenDayAverageDifference, twentyDayAverageDifference, thirtyDayChange): self.openPrice = openPrice self.closePrice = closePrice self.prevClose = prevClose self.todayDifference = todayDifference self.percentChange = percentChange self.volume = volume self.tenDayAverageDifference = tenDayAverageDifference self.twentyDayAverageDifference = twentyDayAverageDifference self.thirtyDayChange = thirtyDayChange class FibonacciNumbers(object): closePrice = 0.0 fibHigh = 0.0 fib78 = 0.0 fib62 = 0.0 fib50 = 0.0 fib38 = 0.0 fib24 = 0.0 fibLow = 0.0 def __init__(self, closePrice, fibHigh, fib78, fib62, fib50, fib38, fib24, fibLow): self.closePrice = closePrice self.fibHigh = fibHigh self.fib78 = fib78 self.fib62 = fib62 self.fib50 = fib50 self.fib38 = fib38 self.fib24 = fib24 self.fibLow = fibLow class Strategies(object): firstStrategyBuyOrSellSignal = "" firstStrategyWinPercentageForEntireYear = "" firstStrategyWinPercentageForFiftyDays = "" firstStrategyWinPercentageForFifteenDays = "" secondStrategyBuyOrSellSignal = "" thirdStrategyPredictedDifference = "" thirdStrategyPredictedPercentDifference = "" def __init__(self, firstStrategyBuyOrSellSignal, firstStrategyWinPercentageForEntireYear, firstStrategyWinPercentageForFiftyDays, firstStrategyWinPercentageForFifteenDays, secondStrategyBuyOrSellSignal, thirdStrategyPredictedDifference, thirdStrategyPredictedPercentDifference): self.firstStrategyBuyOrSellSignal = firstStrategyBuyOrSellSignal self.firstStrategyWinPercentageForEntireYear = firstStrategyWinPercentageForEntireYear self.firstStrategyWinPercentageForFifteenDays = firstStrategyWinPercentageForFifteenDays self.firstStrategyWinPercentageForFiftyDays = firstStrategyWinPercentageForFiftyDays self.secondStrategyBuyOrSellSignal = secondStrategyBuyOrSellSignal self.thirdStrategyPredictedDifference = thirdStrategyPredictedDifference self.thirdStrategyPredictedPercentDifference = thirdStrategyPredictedPercentDifference
import string import random wordlist = 'wordlist.txt' #Choosing length of word for game def get_random_word(length_of_word): words = [] with open(wordlist, 'r') as f: for word in f: if '(' in word or ')' in word: continue word = word.strip().lower() if len(word) == length_of_word: words.append(word) return random.choice(words) def num_of_attempts(): while True: num_attempts = input('Please enter the number of attempts you\'d like, must be between ...') try: num_attempts = int(num_attempts) if 1 <= num_attempts <= 25: return num_attempts else: print('Attempts must be in specified range') except ValueError: print('{} is not an integer'.format(num_attempts)) def get_word(): while True: length_of_word = input('Please enter the length of word you\'d like, mist be between... : ') try: length_of_word = int(length_of_word) if 3 <= length_of_word <= 17: return length_of_word else: print('must be between ...') except ValueError: print('{} must be an integer'.format(length_of_word)) word = 'number'
# Script that gets the mood of user on a scale of 1 - 10. # Program runs on startup of computer, therefore this mostly # represents morning mood. Write 'plot' to plot the graph. import matplotlib.pyplot as plt mood = input("Enter your mood on a scale of 1-10: ") if mood == "plot": with open("moods.txt") as read_file: values = [int(x) for x in read_file.read().splitlines()] plt.plot(range(1, len(values)+1), values) plt.xlabel("Days") plt.ylabel("Mood level") plt.title("Mood Levels over the Past "+ str(len(values)) + " Days" + " (Since July 10th, 2019)") plt.show() elif mood.isdigit(): with open("moods.txt", "a") as append_file: append_file.write(mood + "\n") else: print("User gave invalid input")
import random a=int(input('じゃんけんぽん 0=グー、1=チョキ、2=パー')) b=random.randint(0,2) c='グー' if b==1: c='チョキ' if b==2: c='パー' print('CPUの手は',c,'でした') if a==0: if b==0: print('あいこ') elif b==1: print('勝ち!') elif b==2: print('負け……') if a==1: if b==0: print('負け……') elif b==1: print('あいこ') elif b==2: print('勝ち!') if a==2: if b==0: print('勝ち!') elif b==1: print('負け……') elif b==2: print('あいこ')
import os def loadCiphers(): pathToFile = input('Enter path to the .txt file with ciphertexts split per line:') if pathToFile == "": loadCiphers() if os.path.exists(pathToFile) == False: print('File wasn\'t found') loadCiphers() with open(pathToFile, 'rb') as file: texts = [line.rstrip() for line in file] return texts
# insertion sort def insertion_sort(A): for j in range(1, len(A)): key = A[j] # 将A[j]插入到A[0:j]已排序的数组中 i = j - 1 while i >= 0 and A[i] > key: A[i + 1] = A[i] i -= 1 A[i + 1] = key return A A = insertion_sort([5, 2, 4, 6, 1]) print(A)
# 基本栈结构 class stack: def __init__(self): self.data = [0 for _ in range(16)] self.top = -1 def __getitem__(self, key): return self.data[key] def __setitem__(self, key, value): self.data[key] = value def stack_empty(S): if S.top == -1: return True else: return False def push(S, x): S.top += 1 S[S.top] = x def pop(S): if stack_empty(S): raise OverflowError else: S.top -= 1 return S[S.top + 1] if __name__ == '__main__': S = stack() push(S, 2) push(S, 3) push(S, 1) print(pop(S)) print(pop(S)) print(pop(S))
# This script accepts a data file in json form containing pairs of friends in a social network and outputs asymmetric friendship pairs using MapReduce import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): p1 = record[0] p2 = record[1] if p1 > p2: mr.emit_intermediate(p2, p1) else: mr.emit_intermediate(p1, p2) def reducer(key, list_of_values): new_pairs = [] for value in list_of_values: new_pairs.append((key, value)) for value in new_pairs: if new_pairs.count(value) == 1: k, v = value mr.emit((k, v)) mr.emit((v, k)) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
t = int(input()) while t: x = int(input()) y = 1 for i in range(1,x+1): y = y*i print(y) t = t-1
""" r 讀取模式 r+ 讀寫模式 w 寫入模式。如果該檔案不存在,將建立一個新檔案。如果檔案存在,則會被覆蓋。 w+ 讀寫模式。如果該檔案不存在,將建立一個用於讀寫的新檔案。如果檔案存在,則會被覆蓋。 a 追加模式。新資料將寫在檔案末尾。如果該檔案不存在,將建立一個用於寫入的新檔案。 a+ 追加和讀寫模式。新資料將寫在檔案末尾。如果該檔案不存在,將建立一個用於讀寫的新檔案。 #readlines() 會把整個檔案讀出來第i行放在line[i] #readline() 讀出一行(\n)第i個字放在line[i] #readline(3) 讀出三個字第i字放在line[i] """ import os,time MaxLine=100 QuitWord='q' print("create a file.txt ") writeBuff=list() filename=input("press file name=") print("press q to quit") for currenrLine in range(0,MaxLine): temp=input("line%d="%(currenrLine)) if temp ==QuitWord: break writeBuff.append(temp); #print(writeBuff) f=open(filename+'.txt','w+') for i in range(currenrLine): f.write(writeBuff[i]+'\n') f.close print("----------------------%s.txt----------------------"%(filename)) f=open(filename+'.txt','r') line=f.readlines() for i in range(currenrLine): print("%d:"%(i),line[i],end="") f.close() print("-------------------------------------------------------") #os.rename("123.txt","test.txt") #os.remove("test.txt") #os.system("pause");
import csv # csv_file=csv.reader(open('stu_info.csv','r')) # print(csv_file) # # for stu in csv_file: # print(stu) stu=['Marry',28,'ChangSha'] stu1=['XiaoNan',31,'ChengDu'] out=open('stu_info.csv','a',newline='') csv_write=csv.writer(out,dialect='excel') csv_write.writerow(stu) csv_write.writerow(stu1) print('Write file over!') csv_file=csv.reader(open('stu_info.csv','r')) for line in csv_file: print(line)
class Student(): def __init__(self,name,city): self.name=name self.city=city print('My name is %s and come from %s'%(name,city)) def talk(self): print('Hello World!') stu1=Student(input('请输入'),input('请输入城市')) stu1.talk()
#Exercício Python 071: Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: #considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1. print(20*'=') print('{:^20}'.format('BRYANs BANK')) print(20*'=') #Entrada de dados saque = int(input('\nDigite quantos R$ deseja sacar: ')) #Estetica print(20*'=') #Iniciar variaveis resto1 = resto2 = resto3 = n20 = n10 = n1 = 0 #Processamento n50 = saque//50 resto1 = saque%50 #Quantas notas de 50 if (resto1 >= 0): if (n50 > 0): print('Total de {} cedulas de 50'.format(n50)) #Quantas notas de 20 if (resto1 > 0): n20 = resto1//20 resto2 = resto1%20 if (n20 > 0): print('Total de {} cedulas de 20'.format(n20)) #Quantas notas de 10 if (resto2 > 0): n10 = resto2//10 resto3 = resto2%10 if (n10 > 0): print('Total de {} cedulas de 10'.format(n10)) #Quantas notas de 1 if (resto3 > 0): n1 = resto3//1 if (n1 > 0): print('Total de {} moedas de 1 real.'.format(n1)) #Estetica print(20*'=')