text
stringlengths
37
1.41M
#Useful Binary Search template that can solve most problem. def template(searchArray): #base case: if not searchArray: return None #Condition requirement: these are varies depends on the problem and it is up to the user to find the pattern def condition(searchArray): #add code here: pass left = 0 right = len(searchArray) - 1 while left < right: mid = left + (right - left) // 2 if condition(searchSpace): right = mid else: left = mid + 1 return left searchSpace = [] template(searchSpace)
if __name__ == '__main__': a = int(input()) b = int(input()) if (a > 0 and b > 0): print(a + b) print(a - b) print(a * b)
""" Created by Daniel Susman (dansusman) Date: 10/03/2020 This module holds the InsertionSort class, which holds all of the functionality required to display the sorting of a given array using the Insertion Sort algorithm. """ from algorithms import Algo class InsertionSort(Algo): """ Represents the Insertion Sort algorithm, which is an O(n^2) best case, worst case, and average case algorithm.""" # initialize by assigning insertion sort a name in Algo class def __init__(self): super().__init__("Insertion Sort") def sort_by_algo(self): """ Sorts the given array using the insertion sort algorithm.""" for i in range (1, len(self.arr)): value_at_marker = self.arr[i] j = i - 1 # until we find an item whose value is larger than the value at marker, swap # elements to the right and decrement j to examine leftward (compare with # everything to the left until find one that is smaller than marker value) while (j >= 0) and value_at_marker < self.arr[j]: self.arr[j + 1] = self.arr[j] j -= 1 self.arr[j + 1] = value_at_marker self.update_view(self.arr[j], self.arr[i])
#Carlos Ochoa #Calcula el total a pagar por unos asientos determinando el tipo de asiento #Calcula el pago total de los asientos def calcularPago(asientosA, asientosB, asientosC): pagoA=asientosA*870 pagoB=asientosB*650 pagoC=asientosC*235 totalPago=pagoA+pagoB+pagoC return totalPago def main(): numBA=int(input("cuantos boletos a se vendieron: ")) numBB=int(input("cuantos boletos b se vendieron: ")) numBC=int(input("cuantos boletos c se vendieron: ")) pagoT=calcularPago(numBA, numBC, numBC ) print ("total a pagar: %.2f" % pagoT) main()
"""Word Finder: finds random words from a dictionary.""" import random class WordFinder: ... def __init__(self, path): self.words = open(path, "r") print(f"{self.words_read()} words read") def words_read(self): count = 0 for line in self.words: count +=1 return count def random(self): word_list = [] self.words.seek(0) for line in self.words: word_list.append(line) return random.choice(word_list).strip('\n') class SpecialWordfinder(WordFinder): def __init__(self, path): super().__init__(path) def random(self): word_list = [] self.words.seek(0) for line in self.words: if "#" not in line and len(line) > 2 : word_list.append(line) return random.choice(word_list).strip('\n')
def weight_on_planets(): weightEarth = int(input("What do you weigh on earth? ")) weightMars = weightEarth * 0.38 weightJupiter = weightEarth * 2.34 print("\nOn Mars you would weigh", weightMars, "pounds.") print("On Jupiter you would weigh", weightJupiter, "pounds.") return if __name__ == '__main__': weight_on_planets()
class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.root = { 'isEnd': True, 'neighbors': {} } def addWord(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ ptr = self.root for ch in word: if ch in ptr['neighbors']: ptr = ptr['neighbors'][ch] else: ptr['neighbors'][ch] = { 'isEnd': False, 'neighbors': {} } ptr = ptr['neighbors'][ch] ptr['isEnd'] = True return def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ return self.subSearch(word, self.root) def subSearch(self, word, ptr): res = False for (i, ch) in enumerate(word): if ch != '.': if ch not in ptr['neighbors']: return False else: ptr = ptr['neighbors'][ch] else: for t in ptr['neighbors']: if self.subSearch(word[i+1:], ptr['neighbors'][t]): return True return False return ptr['isEnd'] obj = WordDictionary() word = 'helloworld' search = 'h...world' obj.addWord('a') obj.addWord('a') param_2 = obj.search('.a') print param_2
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ self.preorder = preorder self.inorder = inorder return self.subBuild(0, 0, len(inorder)-1) def subBuild(self, preStart, inStart, inEnd): if preStart > len(self.preorder) - 1 or inStart > inEnd: return None node = TreeNode(self.preorder[preStart]) index = self.inorder.index(self.preorder[preStart]) node.left = self.subBuild(preStart+1, inStart, index-1) node.right = self.subBuild(preStart+index-inStart+1, index+1, inEnd) return node def buildTreeLooply(self, preorder, inorder): stack_tree = [] stack_val = [] i = j = 0 flag = False if len(preorder) == 0: return None node = TreeNode(preorder[0]) root = node stack_tree.append(node) stack_val.append(preorder[0]) i += 1 while i < len(preorder): if len(stack_tree) > 0 and inorder[j] == stack_tree[-1].val: flag = True node = stack_tree[-1] stack_tree.pop() stack_val.pop() j += 1 else: if flag is False: stack_val.append(preorder[i]) node.left = TreeNode(preorder[i]) node = node.left stack_tree.append(node) else: flag = False stack_val.append(preorder[i]) node.right = TreeNode(preorder[i]) node = node.right stack_tree.append(node) i += 1 return root obj = Solution() obj.buildTreeLooply([1,2], [2,1])
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if len(p) == 0: return len(s) == 0 if p[1] == '*': return (self.isMatch(s, p[2:]) or len(s) != 0 and (s[0] == p[0] or '.' == p[0]) and self.isMatch(s[1:], p)); else: return len(s) != 0 and (s[0] == p[0] or '.' == p[0]) and self.isMatch(s[1:], p[1:]) def isMatchByDP(self, s, p): m = len(s) n = len(p) f = [[False for i in range(n + 1)] for i in range(m + 1)] f[0][0] = True i = 1 while i <= m: f[i][0] = False i += 1 j = 1 while j <= n: f[0][j] = j > 1 and '*' == p[j-1] and f[0][j-2] j += 1 i = 1 while i <= m: j = 1 while j <= n: if p[j-1] != '*': f[i][j] = f[i-1][j-1] and (s[i-1] == p[j-1] or '.' == p[j-1]) else: f[i][j] = f[i][j-2] or ((s[i-1] == p[j-2] or '.' == p[j-2]) and f[i-1][j]) j += 1 i += 1 return f[m][n] obj = Solution() print obj.isMatch('abc', 'ab.*') print obj.isMatchByDP('abc', 'ab.*')
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ left_h = left_t = right_h = right_t = None while head: if head.val < x: if left_h is None: left_h = head else: left_t.next = head left_t = head else: if right_h is None: right_h = head else: right_t.next = head right_t = head head = head.next if left_h is not None: left_t.next = right_h if right_h is not None: right_t.next = None return left_h else: if right_h is not None: right_t.next = None return right_h
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i = j = 0 for k in range(len(nums)): v = nums[k] nums[k] = 2 if v < 2: nums[j] = 1 j += 1 if v == 0: nums[i] = 0 i += 1 print nums def sortColorsH(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i = 0 j = len(nums) - 1 while True: while nums[i] < 1: i += 1 while nums[j] > 1: j -= 1 if i >= j: break nums[i], nums[j] = nums[j], nums[i] nums[j], nums[0] = nums[0], nums[j] print nums obj = Solution() obj.sortColorsH([2,0,2,1,0,1])
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ self.inorder = inorder self.postorder = postorder return self.subBuildTree(len(postorder) - 1, 0, len(inorder) - 1) def subBuildTree(self, postorder_i, inorder_left, inorder_right): if postorder_i < 0 or inorder_left > inorder_right: return None node = TreeNode(self.postorder[postorder_i]) middle_pos = self.inorder.index(self.postorder[postorder_i]) node.left = self.subBuildTree(postorder_i - (inorder_right - middle_pos) - 1, inorder_left, middle_pos - 1) node.right = self.subBuildTree(postorder_i - 1, middle_pos + 1, inorder_right) return node def buildTreeLooply(self, inorder, postorder): if len(inorder) == 0: return None stn = [] root = TreeNode(postorder[-1]) stn.append(root) postorder.pop() while True: if inorder[-1] == stn[-1].val: p = stn[-1] stn.pop() inorder.pop() if len(inorder) == 0: break if len(stn) != 0 and inorder[-1] == stn[-1].val: continue p.left = TreeNode(postorder[-1]) postorder.pop() stn.append(p.left) else: p = TreeNode(postorder[-1]) postorder.pop() stn[-1].right = p stn.append(p) return root def traverse(self, root): if root is None: return print root.val self.traverse(root.left) self.traverse(root.right) obj = Solution() #r = obj.buildTree([4,2,5,1,6,3,7], [4,5,2,6,7,3,1]) r = obj.buildTreeLooply([3,2,1], [3,2,1]) obj.traverse(r)
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ self.zeroDict = {} rows = len(board) if rows > 0: cols = len(board[0]) else: return # From first row left to right for j in range(cols): if board[0][j] == 'O': self.expand(board, rows, cols, 0, j) # From first column top to down for i in range(1, rows): if board[i][0] == 'O': self.expand(board, rows, cols, i, 0) # From last row left to right for j in range(1, cols): if board[rows - 1][j] == 'O': self.expand(board, rows, cols, rows - 1, j) # From last column top to down for i in range(1, rows - 1): if board[i][cols - 1] == 'O': self.expand(board, rows, cols, i, cols - 1) for i in range(rows): for j in range(cols): key = str(i) + '-' + str(j) if key not in self.zeroDict: board[i][j] = 'X' print board def expand(self, board, rows, cols, i, j): if i < 0 or j < 0 or i >= rows or j >= cols or board[i][j] != 'O': return key = str(i) + '-' + str(j) if key in self.zeroDict: return self.zeroDict[key] = 1 self.expand(board, rows, cols, i - 1, j) self.expand(board, rows, cols, i + 1, j) self.expand(board, rows, cols, i, j - 1) self.expand(board, rows, cols, i, j + 1) obj = Solution() #obj.solve([['X', 'X', 'X', 'X'], ['X', 'O', 'O', 'X'], ['X', 'X', 'O', 'X'], ['X', 'O', 'X', 'X']]) #obj.solve([['X', 'O', 'X', 'X']]) #obj.solve([["X","O","X"],["X","O","X"],["X","O","X"]]) obj.solve([["O","X","X","O","X"],["X","O","O","X","O"],["X","O","X","O","X"],["O","X","O","O","O"],["X","X","O","X","O"]])
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def countNodes(self, root): """ :type root: TreeNode :rtype: int """ lh = self.height(root) if lh < 0: return 0 if self.height(root.right) == lh - 1: return (1 << lh) + self.countNodes(root.right) else: return (1 << (lh - 1)) + self.countNodes(root.left) def height(self, root): if root is None: return -1 else: return 1 + self.height(root.left) def myCountNodes(self, root): """ :type root: TreeNode :rtype: int """ ptr = root self.llevel = 0 while ptr is not None: self.llevel += 1 ptr = ptr.left self.canExit = False self.lost = 0 self.traverse(root, 0) return 2 ** self.llevel - self.lost - 1 def traverse(self, root, level): if self.canExit: return if root is None: if level == self.llevel: self.canExit = True return else: self.lost += 1 return self.traverse(root.right, level + 1) self.traverse(root.left, level + 1) a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) d = TreeNode(4) e = TreeNode(5) a.left = b a.right = c b.left = d b.right = e obj = Solution() print obj.countNodes(a)
# Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e def __str__(self): return '[' + str(self.start) + ',' + str(self.end) + ']' class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ intervals = sorted(intervals, lambda a,b:a.start-b.start) i = 0 length = len(intervals) if length <= 1: return intervals result = [] while i < length - 1: if intervals[i].end >= intervals[i+1].start: tmp = Interval(intervals[i].start, intervals[i].end) # find to last can be merged while i < length - 1: if tmp.end < intervals[i+1].start: break # this is important if tmp.end < intervals[i+1].end: tmp.end = intervals[i+1].end i += 1 if tmp.end < intervals[i].end: tmp.end = intervals[i].end result.append(tmp) else: result.append(intervals[i]) i += 1 if intervals[length-1].end > result[-1].end and intervals[length-1].end != result[-1].end: result.append(intervals[-1]) return result obj = Solution() #rtn = obj.merge([Interval(2,3),Interval(4,5),Interval(6,7),Interval(8,9),Interval(1,10)]) #rtn = obj.merge([Interval(1,4), Interval(2,3)]) rtn = obj.merge([Interval(1,3),Interval(2,6),Interval(8,10),Interval(9,18)]) for item in rtn: print item
import unicodedata class NormalizedStr: ''' By default, Python's str type stores any valid unicode string. This can result in unintuitive behavior. For example: >>> 'César' in 'César Chávez' True >>> 'César' in 'César Chávez' False The two strings to the right of the in keyword above are equal *semantically*, but not equal *representationally*. In particular, the first is in NFC form, and the second is in NFD form. The purpose of this class is to automatically normalize our strings for us, making foreign languages "just work" a little bit easier. ''' def __init__(self, text, normal_form='NFC'): self.norm = normal_form self.text = unicodedata.normalize(self.norm, text) self.i = -1 self.n = len(self.text) def __repr__(self): ''' The string returned by the __repr__ function should be valid python code that can be substituted directly into the python interpreter to reproduce an equivalent object. ''' return "NormalizedStr(\'{}\', \'{}\')".format(self.text, self.norm) def __str__(self): ''' This functions converts the NormalizedStr into a regular string object. The output is similar, but not exactly the same, as the __repr__ function. ''' normalized = unicodedata.normalize(self.norm, self.text) return normalized def __len__(self): ''' Returns the length of the string. The expression `len(a)` desugars to a.__len__(). ''' return len(self.text) def __contains__(self, substr): ''' Returns true if the `substr` variable is contained within `self`. The expression `a in b` desugars to `b.__contains__(a)`. HINT: You should normalize the `substr` variable to ensure that the comparison is done semantically and not syntactically. ''' normalized = unicodedata.normalize(self.norm, substr) return str(self.text).__contains__(str(normalized)) def __getitem__(self, index): ''' Returns the character at position `index`. The expression `a[b]` desugars to `a.__getitem__(b)`. ''' return self.text.__getitem__(index) def lower(self): ''' Returns a copy in the same normalized form, but lower case. ''' return self.text.lower() def upper(self): ''' Returns a copy in the same normalized form, but upper case. ''' return self.text.upper() def __add__(self, b): ''' Returns a copy of `self` with `b` appended to the end. The expression `a + b` gets desugared into `a.__add__(b)`. HINT: The addition of two normalized strings is not guaranteed to stay normalized. Therefore, you must renormalize the strings after adding them together. ''' temp = self.text + unicodedata.normalize(self.norm, str(b)) copy = unicodedata.normalize(self.norm, temp) return NormalizedStr(copy, self.norm) def __iter__(self): ''' HINT: Recall that the __iter__ method returns a class, which is the iterator object. You'll need to define your own iterator class with the appropriate magic methods, and return an instance of that class here. ''' return NormalizedStr2(self.text, self.n) class NormalizedStr2: def __init__(self, text, n): self.text = text self.i = 0 self.n = n def __next__(self): while self.i < self.n: self.i += 1 return self.text[self.i - 1] raise StopIteration
# -*- coding: utf-8 -*- ''' Universidade Federal de Pernambuco (UFPE) (http://www.ufpe.br) Centro de Informática (CIn) (http://www.cin.ufpe.br) Graduando em Sistemas de Informação IF969 - Algoritmos e estrutura de dados Autor: Emerson Victor Ferreira da Luz (evfl) Email: [email protected] Data: 2017-10-22 Copyright(c) 2017 Emerson Victor ''' def countSums(array): #Conta a quantidade de triplas que somadas resultam em zero mergeSort(array) size = len(array) total = 0 for i in range(size): for j in range(i+1, size): if binarySearch(-array[i]-array[j], array) > j: total += 1 return total def binarySearch(number, array): #Realiza uma bunca binária em um vetor, retornando a posição caso encontre ou -1 caso não encontre start = 0 end = len(array) - 1 while start <= end: position = (start + end) // 2 if array[position] > number: end = position - 1 elif array[position] < number: start = position + 1 else: return position return -1 def mergeSort(array): # Ordenação por meio do merge sort global aux aux = list(array) mergeSortAux(array, 0, len(array) - 1) del aux def mergeSortAux(array, left, right): if left >= right: return middle = (left + right) // 2 mergeSortAux(array, left, middle) mergeSortAux(array, middle + 1, right) merge(array, left, middle, right) def merge(array, left, middle, right): i = left j = middle + 1 for k in range(left,right + 1): aux[k] = array[k] for k in range(left, right + 1): if i > middle: array[k] = aux[j] j+=1 elif j > right: array[k] = aux[i] i+=1 elif aux[i] > aux[j]: array[k] = aux[j] j+=1 else: array[k] = aux[i] i+=1
# insert an image into the database. import sqlite3 # connect to the already existing database db = sqlite3.connect('images.sqlite') db.execute('DROP TABLE image_store') db.commit() db.execute('CREATE TABLE image_store (i INTEGER PRIMARY KEY, image BLOB, filetype TEXT, imgName TEXT, imgDesc TEXT)') db.commit() # configure to allow binary insertions db.text_factory = bytes # grab whatever it is you want to put in the database #r = open('dice.png', 'rb').read() #vars = (r, "png") print '....inserting.....' # insert! #db.execute('INSERT INTO image_store (image) VALUES (?)', (r,)) #db.execute('INSERT INTO image_store(image, filetype) VALUES(?,?)', vars) #db.commit() #db.execute('UPDATE image_store SET filetype="png" WHERE i=1') #db.commit()
def min_max(minmax, num): if minmax[0] is None: minmax[0] = num minmax[1] = num else: if num > minmax[1]: minmax[1] = num if num < minmax[0]: minmax[0] = num return minmax def main(): string = input() num1 = "" num2 = "" item = 0 minmax = [None, None] # first - minimum of numbers, second - maximum of numbers while item < len(string): if string[item].isdigit(): num1 += string[item] else: if string[item] == "+": # if adding operation item += 1 while item < len(string) and string[item].isdigit(): num2 += string[item] item += 1 if num1 and num2: print(int(num1) + int(num2)) minmax = min_max(minmax, int(num1) + int(num2)) num1 = "" num2 = "" elif num2: print(int(num2)) minmax = min_max(minmax, int(num2)) num2 = "" elif string[item] == "-": # if subs operation item += 1 while item < len(string) and string[item].isdigit(): num2 += string[item] item += 1 if num1 and num2: print(int(num1) - int(num2)) minmax = min_max(minmax, int(num1) - int(num2)) num1 = "" num2 = "" elif num2: print(int(num2)) minmax = min_max(minmax, int(num2)) num2 = "" elif string[item] == "*": # if multiply operation item += 1 while item < len(string) and string[item].isdigit(): num2 += string[item] item += 1 if num1 and num2: print(int(num1) * int(num2)) minmax = min_max(minmax, int(num1) * int(num2)) num1 = "" num2 = "" elif num2: print(int(num2)) minmax = min_max(minmax, int(num2)) num2 = "" elif string[item] == "/": # if dividion operation item += 1 while item < len(string) and string[item].isdigit(): num2 += string[item] item += 1 if num1 and num2: print(int(num1) // int(num2)) minmax = min_max(minmax, int(num1) // int(num2)) num1 = "" num2 = "" elif num2: print(int(num2)) minmax = min_max(minmax, int(num2)) num2 = "" else: if num1: print(int(num1)) minmax = min_max(minmax, int(num1)) num1 = "" item += 1 if num1: # print last digits in string print(int(num1)) minmax = min_max(minmax, int(num1)) print("Max: ", minmax[1]) print("Min: ", minmax[0]) main()
def is_prime(n, range_div): count = 0 if (n > 10) and (n % 10 == 5): count = 1 else: i = 0 while range_div and n >= range_div[i] * range_div[i]: if n % range_div[i] == 0: count = 1 break i += 1 return False if count else True def primes(): rez = 1 pozition = 0 list_primes = [] while True: rez += 1 if is_prime(rez, list_primes): pozition += 1 list_primes.append(rez) yield rez, pozition def primeof(gen, number): rez = next(gen) while not rez[1] == number: rez = next(gen) return rez[0] def main(): n = int(input().strip()) numbers_prime = input().strip().split() g = primes() for item in range(n): rez = primeof(g, int(numbers_prime[item])) print(rez, end=" ") # start program main()
def main(): x = float(input()) y = float(input()) print("NO") if x > 1 or x < -1 or y > 1 or y < -1 else print("YES") # start program main()
#!/usr/bin/env python __author__ = 'Alex Chung' __email__ = '[email protected]' __python_version__="2.7" """ Game Rules: In the game of Ghost, two players take turns building up an English word from left to right. Each player adds one letter per turn. The goal is to not complete the spelling of a word: if you add a letter that completes a word (of 4+ letters), or if you add a letter that produces a string that cannot be extended into a word, you lose. (Bluffing plays and "challenges" may be ignored for the purpose of this puzzle.) Program Description: Write a program that allows a user to play Ghost against the computer. The computer should play optimally given the following dictionary: WORD.LST (1.66 MB). Allow the human to play first. If the computer thinks it will win, it should play randomly among all its winning moves; if the computer thinks it will lose, it should play so as to extend the game as long as possible (choosing randomly among choices that force the maximal game length). Notes: 1) String length ONLY increments 2) English word ONLY [a-z] 3) Case insensitive (all lower) 4) It's okay to form a word that has less than 4 letters 5) Does the computer evaluate its chance after every human move or just the first one? 6) I'm assuming that the description means: if there is a tie of multiple moves that extend the game at the same maximal length, the computer will choose among them. 7) B-Tree. Each letter will be a single node 8) remember that the CPU next moves will skip turns 9) If the computer is uncertain of winning or losing, it will choose the letter that has a higher chance of leading to a win """ import os import re #Regular Expression import random #Random number from collections import deque #Queue #STEP 1: Define B-Tree that will hold the words list #Assume the words list contains only English words and there are no #other characters besides a-z class BTree(object): def __init__(self, name='', value=-1, children=None, isWord=False): self.name = name #Hold the letter value self.value = value #Hold the level within the tree self.isWord = isWord #Mark if this node is the end of a word if children: for c in children: self.addChild(c) else: self.children = list() def addChild(self, child): self.children.append(child) def findSubTree(self, name): if self is None: return False if not self.children: return False for c in self.children: if c.name == name: return c return False def dfawsHelper(self, foundWords): if self is None: return False if self.isWord and self.value > 3: foundWords.append(self) else: for c in self.children: c.dfawsHelper(foundWords) def depthFirstAllWordsSearch(self): foundWords = list() if self is None: return False if self.isWord and self.value > 3: foundWords.append(self) else: for c in self.children: c.dfawsHelper(foundWords) if foundWords: return foundWords else: return False #STEP 2: Get WordList File then Parse Words List #Assume data file in same directory as the python source file #this is an easy way to get the right path name for the data file def getLocalPathFromThisSourceFile(fname): curpath = os.path.abspath(fname) words_file = os.path.dirname(curpath) words_file = os.path.join(words_file, fname) return words_file #Load and parse a words list def parseInputFile(fname): words = list() try: input_file = getLocalPathFromThisSourceFile(fname) #Read in the words list fin = open(input_file, 'r') for line in fin: line = line.strip() #turn all strings to lowercase characters line.lower() words.append(line) fin.close() return words except Exception as ex: print ("error opening file %s", ex) return #STEP 3: Build a tree from the words list def buildABTree(words): root = BTree("root", 0) if words: for word in words: #print word currentNode = root for i, char in enumerate(word): foundNode = currentNode.findSubTree(char) if foundNode: #there is an existing node, reuse currentNode = foundNode else: #create new node newNode = BTree(char, i + 1) currentNode.addChild(newNode) #the new node is now the current node currentNode = newNode #mark current character as the end of a read word currentNode.isWord = True return root else: return singleLetterPattern = re.compile('^[a-z]$') #STEP4: Define the Ghost Game Logic class GhostGame(object): winner = None finalWord = None currString = '' def __init__(self, id=None, numHumanPlayers=None, currentNode=None): self.numHumanPlayers = numHumanPlayers self.currentNode = currentNode def promptHumanInput(self, i): #Error Checking on human inputs validInput = False user_input = None while (not validInput): user_input = raw_input('Player' + str(i) + '\'s turn: Please enter an English letter (a-z):') user_input = user_input.strip().lower() if len(user_input) > 1: print "Please enter only a single letter. Try again." continue elif not re.match(singleLetterPattern, user_input): print "Please enter a letter from a -z only. Try again." continue else: validInput = True return user_input def WordExtensionCheck(self): if self.currentNode.children: return True else: return False def ComputerMoveDecision(self): #Find all the nodes that are end of words but with more than 3 letters #Find a node that leads to all paths with an even number of remaining rounds from the current round #Choose path base on the following rules: #1. hasEven = True and hasOdd = False => certain win #2. hasEven = True and hasOdd = True => 50/50 #3. hasEven = False and hasOdd = True => certain lose, pick the path with the highest remaining round winningMoves = list() neutralMoves = list() losingMoves = list() lastMove = None nextMove = None #Peak at all the letter choices for c in self.currentNode.children: #Find the word stops from each of the possible letter choice allFoundWords = c.depthFirstAllWordsSearch() hasEvenRemainRound = 0 hasOddRemainRound = 0 #Calculate the number of rounds between the computer move and the next closest word stops #Computer is looking for even number of rounds so that it will not make the last move try: if allFoundWords: for w in allFoundWords: remainRound = w.value - c.value + 1 if remainRound % (self.numHumanPlayers + 1) == 0: #consider the total num of players + comp hasEvenRemainRound += 1 else: hasOddRemainRound += 1 if hasEvenRemainRound > 0 and hasOddRemainRound == 0: #certain win winningMoves.append(c) elif hasEvenRemainRound > 0 and hasOddRemainRound > 0: #50/50. Uncertain #Pick one path with the highest number of even remaning rounds #If there is a tie, randomly pick one neutralMoves.append((c, hasEvenRemainRound, hasOddRemainRound)) elif hasEvenRemainRound == 0 and hasOddRemainRound > 0: #certain lose losingMoves.append(c) else: #no more move with this choice lastMove = c else: pass except: pass if len(winningMoves) > 0: nextMove = random.choice(winningMoves) #print "winning move: " + nextMove.name elif len(neutralMoves) > 0: maxChanceMove = None maxChancePercent = None for p in neutralMoves: #Calculate the percent of even number paths out of total pPercentOfEvenNum = float(p[1])/float(p[1] + p[2]) if maxChanceMove is None: maxChanceMove = p maxChancePercent = pPercentOfEvenNum elif maxChancePercent < pPercentOfEvenNum: #Compare the percentage of even number paths out of total maxChanceMove = p maxChancePercent = pPercentOfEvenNum nextMove = maxChanceMove[0] elif len(losingMoves) > 0: maxExtensionMove = None for c in losingMoves: if maxExtensionMove is None: maxExtensionMove = c elif maxExtensionMove.value < c.value: #Compare and look for the longest word maxExtensionMove = c nextMove = maxExtensionMove else: nextMove = lastMove return nextMove def GameCheck(self, user_input, playerName): self.currString += user_input #update the current displayed string treeNode = self.currentNode.findSubTree(user_input) #Find the node based the new user_input if treeNode: self.currentNode = treeNode #Check if the player has created a word if treeNode.isWord and len(self.currString) > 3: #word has to have 4 or more letters #Yes self.finalWord = self.currString self.winner = playerName print playerName + " loses. A Word has been completed: " + self.finalWord + '.' return True else: #No pass #Check if the word can be extend if self.WordExtensionCheck(): #Yes pass else: #No print "Oops. " + playerName + " have entered a string that cannot be extended." self.finalWord = self.currString self.winner = playerName return True return False else: #not found. User has entered an invalid word print "Sorry " + playerName + ". You have entered an invalid string that cannot be extended to a word." self.finalWord = self.currString self.winner = playerName return True def playGame(self): #Display Game Instroduction print "WELCOME TO PLAY THE GAME OF GHOST" print "" print "Game Rules:" print "In the game of Ghost, two players take turns building up an English word from left to right." print "Each player adds one letter per turn. The goal is to not complete the spelling of a word:" print "if you add a letter that completes a word (of 4+ letters)," print "or if you add a letter that produces a string that cannot be extended into a word, you lose." print "" currString = '' while (self.finalWord is None and self.winner is None): if len(self.currString) > 0: print "Game progress: " + self.currString #what has been entered so far #Human Players for i in range(1, self.numHumanPlayers + 1): #support multiple human players if self.winner is None: user_input = self.promptHumanInput(i) if self.GameCheck(user_input, 'Player' + str(i)): break #Computer Player if self.winner is None: #Calculate the next move nextMove = self.ComputerMoveDecision() if nextMove is None: #There is no next move for the computer. Thus the human player loses print "Oops. You have entered a string that cannot be extended." self.finalWord = self.currString self.winner = 'Computer' break else: print 'Computer' + '\'s turn: ' + nextMove.name if self.GameCheck(nextMove.name, 'Computer'): break #STEP5: Execute Program def main(): #Load the words list into memory words = parseInputFile('WORD.LST') root = buildABTree(words) #Start A Game Instance game = GhostGame(1, 1, root) game.playGame() if __name__ == '__main__': main() ################################ #Sample Outputs: # # ################################ """ WELCOME TO PLAY THE GAME OF GHOST Game Rules: In the game of Ghost, two players take turns building up an English word from left to right. Each player adds one letter per turn. The goal is to not complete the spelling of a word: if you add a letter that completes a word (of 4+ letters), or if you add a letter that produces a string that cannot be extended into a word, you lose. Player1's turn: Please enter an English letter (a-z):b Computer's turn: w Game progress: bw Player1's turn: Please enter an English letter (a-z):a Computer's turn: n Game progress: bwan Player1's turn: Please enter an English letter (a-z):e Sorry Player1. You have entered an invalid string that cannot be extended to a word. """
from tkinter import * app=Tk() text=Text(app,undo=True,autoseparator=False) text.pack() text.insert(1.0,'I trust fishc.com') '待注释' def callback(event): text.edit_separator() text.bind('<Key>',callback) '定义撤销方法,添加撤销按钮' def show(): text.edit_undo() Button(app,text='撤销',command=show).pack() mainloop()
print() ''' 属性:姓名(默认姓名为’小甲鱼‘) 方法:打印姓名 方法中对属性的引用形式需要加上self.如:self.name ''' class Person: name='小甲鱼' def printName(self): print('我的名字叫:%s'%self.name) person=Person() person.printName()
''' 1 定义一个单词(word)类继承自字符串,重写比较操作符的,当两个word类对象进行比较时, 根据单词的长度来进行比较大小。 加分要求:实例化如果传入的是带空格的字符串,则取第一个空格前的单词作为参数 ''' class Word(int): def __new__(cls, args): if isinstance(args,str): if ' 'in args: length=args.find(' ') else: length = len(args) args=length return int.__new__(cls,args) a=Word('a') b=Word('a 123') print(a<=b)
import random class Turtle: moveStep=random.randint(1,2) movedirection=0 min_x=0 max_x=10 min_y=0 max_y=10 position=[0,0] hp=1005 #随机生成乌龟的移动方向 def getDirection(self): self.movedirection=random.randint(-1,1) if self.movedirection==-1: print('乌龟决定往回游,移动的步数为:%d'%self.moveStep) else: print('乌龟决定向前游,移动的步数为:%d' % self.moveStep) while self.movedirection==0: self.movedirection = random.randint(-1, 1) return self.movedirection def getRandomStep(self): self.moveStep=random.randint(1,2) #当乌龟达到场景边缘,会自动反方向移动 def autoReturn(self): while self.position[0]==self.min_x and self.position[1]==self.max_y: self.position[0]+=self.moveStep self.position[1]+=self.moveStep print("到达边界,开始反方向移动,现在乌龟的位置为:%s" % self.position) while self.position[0] == self.max_x and self.position[1] == self.max_y: self.position[0]-=self.moveStep self.position[1] -= self.moveStep print("到达边界,开始反方向移动,现在乌龟的位置为:%s" % self.position) # while self.position==self.min_y: # self.position[1]+=self.moveStep # print("到达边界,开始反方向移动,现在乌龟的位置为:%s" % self.position) # while self.position==self.max_y: # self.position[1]-=self.moveStep # print("到达边界,开始反方向移动,现在乌龟的位置为:%s" % self.position) #乌龟的移动控制,假如一次性的移动数值超出边界,要将乌龟的定位返回到场景范围内 def move(self): while self.movedirection == -1: tmp_x = self.position[0] tmp_y = self.position[1] tmp_x -= self.moveStep tmp_y -= self.moveStep if tmp_x < self.min_x and tmp_y < self.min_y: self.position[0] = self.min_x - tmp_x self.position[1] = self.min_y - tmp_y else: self.position[0] = tmp_x self.position[1] = tmp_y return self.position while self.movedirection == 1: tmp2_x = self.position[0] tmp2_y = self.position[1] tmp2_x += self.moveStep tmp2_y += self.moveStep if tmp2_x > self.max_x and tmp2_y > self.max_y: self.position[0] = tmp2_x - (tmp2_x - self.max_x) self.position[1] = tmp2_y - (tmp2_y - self.max_y) else: self.position[0] = tmp2_x self.position[1] = tmp2_y return self.position #计算乌龟的HP def countHp(self): # if self.move(): # self.hp-=1 return self.hp class Fish: moveStep = 1 movedirection = 0 min_x = 0 max_x = 10 min_y = 0 max_y = 10 position = [0, 0] num=10 # 随机生成鱼的移动方向 def getDirection(self): self.movedirection=random.randint(-1,1) while self.movedirection==0: self.movedirection = random.randint(-1, 1) return self.movedirection # 当鱼达到场景边缘,会自动反方向移动 def autoReturn(self): while self.position==self.min_x: self.position[0]+=self.moveStep print("到达边界,自动返回,现在鱼的位置为:%s"%self.position) while self.position==self.max_x: self.position[0]-=self.moveStep print("到达边界,自动返回,现在鱼的位置为:%s" % self.position) while self.position==self.min_y: self.position[1]+=self.moveStep print("到达边界,自动返回,现在鱼的位置为:%s" % self.position) while self.position==self.max_y: self.position[1]-=self.moveStep print("到达边界,自动返回,现在鱼的位置为:%s" % self.position) turtle=Turtle() fish=Fish() print('乌龟的起始坐标为:%s'%turtle.position) print('鱼的起始坐标为:%s'%fis5h.position) while 1: turtle.getDirection() turtle.moveStep turtle.move() turtle.autoReturn() print('乌龟的移动到新坐标:%s'%turtle.position) # break
class Celsius: def __init__(self,value=26.0): self.value=float(value) def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value=value class Fahrenheit: def __get__(self, instance, owner): return instance.cel*1.8+32 def __set__(self, instance, value): instance.cel=(float(value)-32)/1.8 class Temperature: cel=Celsius() fah=Fahrenheit()
import math class Point: def __init__(self,x,y): self.x=x self.y=y class Line: def getlen(self,Point,Point2): result=math.sqrt((Point.x-Point2.x)**2+(Point.y-Point2.y)**2) return result pointA=Point(1,0) pointB=Point(2,0) line=Line() print(line.getlen(pointA,pointB))
print() ''' 1 写一个函数get_digits(n),将参数n分解出每个位的数字并按顺序存放在列表中。 如:get_digits(12345)——[1,2,3,4,5] ''' result = [] def get_digits(n): if n > 0: result.insert(0, n % 10) get_digits(n // 10) '这里只是控制了执行的次数而已,每次的结果直接放在了外面的全局变量' '假如放在里面的话会重复的初始化,导致拿不到完整的列表' get_digits(12345) print(result) '普通版本' def get_digit2(n): result=[] '普通版本是先走完循环再出来的,不会重复初始化result,所以可以放在里面' while n>0: result.insert(0,n%10) n=n//10 return result print(get_digit2(12345))
def compare(file1,file2): file_content1=open(file1) file_content2=open(file2) count=0 differ = [] for i in file_content1: j=file_content2.readline() count+=1 if i!=j: differ.append(count) file_content1.close() file_content2.close() return differ file1=input('请输入文件1:') file2=input('请输入文件2:') differ=compare(file1,file2) length=len(differ) if length==0: print('两个文件完全一样') else: for i in differ: print('第%d行不一样'%i)
tmp=input("请输入你的成绩:") while not tmp.isdigit(): tmp=input('你的输入有误!请重新输入:') score=int(tmp) if 60<=score<80: print("C") elif 60<=score<70: print("D") elif 0<=score<60: print("F") elif 80<=score<90: print("B") elif 90<=score<=100: print("A") else: print('非法成绩')
'过滤字符串对于求和的影响' def sum(x): result=0 for i in x: if type(i)==float or type(i)==int: result=result+i else: continue return result print(sum([1,2,4,5,6,3.15,7.25,'sdfdsf',10*10]))
#for循环方法 a=1 for i in range(0,101): if i%2!=0: print(i,end=' ') #换行打印 print('') while a<=100: if a % 2!=0: print(a,end=' ') a+=1
def huiwenlian(): '''回文联是指顺着读跟倒着读文字显示的内容是一样的''' content=input('请输入一句话:') tmp=[] new='' for i in content: tmp.insert(0,i) for i in tmp: new+=i if content==new: return '这是一个回文联' else: return '这不是一个回文联' print(huiwenlian())
import datetime import os """ 一 编写with操作类Fileinfo(),定义__enter__和__exit__方法。完成功能: 1.1 在__enter__方法里打开Fileinfo(filename),并且返回filename对应的内容。如果文件不存在等情况,需要捕获异常。 1.2 在__enter__方法里记录文件打开的当前日期和文件名。并且把记录的信息保持为log.txt。内容格式:"2014-4-5 xxx.txt" """"" class Fileinfo(object): def __init__(self,fileName): self.fileName=fileName self.f=open(self.fileName) def __enter__(self): now=datetime.date.today().isoformat() with open("fileLog.txt",'w')as f: f.write(str(now)+' '+self.fileName) try: self.f=open(self.fileName) return self.f.read() except IOError: return "文件参数传入错误,打开失败" def __exit__(self, exc_type, exc_val, exc_tb): self.f.close() # # with Fileinfo("123")as f: # print('正在执行') """ 二:用异常方法,处理下面需求: info = ['http://xxx.com','http:///xxx.com','http://xxxx.cm'....]任意多的网址 2.1 定义一个方法get_page(listindex) listindex为下标的索引,类型为整数。 函数调用:任意输入一个整数,返回列表下标对应URL的内容,用try except 分别捕获列表下标越界和url 404 not found 的情况。 2.2 用logging模块把404的url,记录到当前目录下的urlog.txt。urlog.txt的格式为:2013-04-05 15:50:03,625 ERROR http://wwwx.com 404 not foud、 """ """ 三:定义一个方法get_urlcontent(url)。返回url对应内容。 要求: 1自己定义一个异常类,捕获URL格式不正确的情况,并且用logging模块记录错误信息。 2 用内置的异常对象捕获url 404 not found的情况。并且print 'url is not found' """
def power(x,y): if y: return x*power(x,y-1) else: return 1 print(power(5,0))
# https://www.hackerrank.com/challenges/capitalize/problem def solve(s): return " ".join(word.capitalize() for word in s.split(" "))
def swap_case(s): return "".join([char.lower() if char.isupper() else char.upper() for char in s])
# -*- coding: utf-8 -*- message="This is regarding getting confirmation from you to have your time. Are you available now ?" #edit with your message here title="Message from administrator" #edit with your title here import Tkinter as tk import tkMessageBox as messagebox root = tk.Tk().withdraw() value=messagebox.askquestion(title, message) if value == 'yes' : print "User clicked Yes Option" print 'The following message is sent to the user.\n%s'%message else: print "User clicked No Option"
"""You are in a room with a circle of 100 chairs. The chairs are numbered sequentially from 1 to 100. At some point in time, the person in chair #1 will be asked to leave. The person in chair #2 will be skipped, and the person in chair #3 will be asked to leave. This pattern of skipping one person and asking the next to leave will keep going around the circle until there is one person left the survivor. Write a program to determine which chair the survivor is sitting in.""" #### RECURSIVE WAY ### ppl_in_chairs = [] for i in range(1,101): ppl_in_chairs.append(i) def ask_ppl_to_leave(list_name): if len(list_name) == 1: print list_name[0] else: remaining_ppl = [] for i in range(len(list_name)): if i % 2 == 1: remaining_ppl.append(list_name[i]) ask_ppl_to_leave(remaining_ppl) # ask_ppl_to_leave(ppl_in_chairs) ##### LINKED LIST WAY ### from creating_linked_lists import LinkedList ppl_in_chairs = LinkedList() for i in range(1,101): ppl_in_chairs.AddNode(i) # ppl_in_chairs.PrintList() def ask_ppl_to_leave_ll(ll_name): next_elem = ll_name.head.next while next_elem != None: ll_name.head = next_elem print ll_name.head.data while next_elem != None: print next_elem.data next_elem.next = next_elem.next.next next_elem = next_elem.next print next_elem.next.data print ll_name.head.data ask_ppl_to_leave_ll(ppl_in_chairs)
# stolen from the interwebz class Node: def __init__(self,value,next): self.value = value self.next = next def prnt(n): next = n.next print n.value if(next is not None): prnt(next) #Iterative def reverse(n): previous = None current = n while current is not None: next = current.next current.next = previous previous = current current = next return previous #Recursive def recurse(n,previous): if n is None: return previous next = n.next n.next = previous return recurse(next, n) nD = Node(4,None) nC = Node(3,nD) nB = Node(2,nC) nA = Node(1,nB) #l = reverse(n3) prnt(nA) result = recurse(nA, None) prnt(result)
def count(lst): even=0 odd=0 for i in lst: if i %2==0: even+=1 else: odd+=1 return even,odd lst=[1,2,3,44,5] even,odd= count(lst) print(even,odd)
# class variables and instance variables or namespaces # class method and instance method(accesor andd mutator) and static method class student: # class variable school="myworld" def __init__(self,m1,m2): self.m1=m1 self.m2=m2 def sum(self): return (self.m1+self.m2) # accesor or instance method def get_marks(self): return self.m1 # mutator or instance method def set_marks(self,value): self.m1=value print(self.m1) # class method @classmethod def info(cls): student.school="telusko" return student.school # static method @staticmethod def stat_inform(): print("Iam here") c1 =student(30,40) print(c1.sum()) print(c1.get_marks()) c1.set_marks(20) print(student.info()) student.stat_inform()
def selectionsort(list): for i in range(0,len(list)): p=i for j in range(i,(len(list))): if list[p]>list[j]: p=j t=list[i] list[i]=list[p] list[p]=t list=[8,9,2,4,7] selectionsort(list) print(list)
x=["name","movies","python"] print(x[1]) print("i like"+ x[1])
from typing import Iterable from AuxiliaryMethods import * import random """ Lecture 5 Sorting """ # Selection Sort # O(n^2) def selectionSort(A: Iterable[int], lo: int, hi: int) -> None: """ Implementation of selection sort requires 0 <= lo and lo <= hi and hi <= len(A) ensures isSorted(A, lo, hi) """ for i in range(hi): assert lo <= i and i <= hi assert isSorted(A, lo, i) assert leSegs(A, lo, i, A, i, hi) min = findMin(A, i, hi) swap(A, i, min) A = [1,5,6,7,3,4] print(A) selectionSort(A, 0, len(A)) print(A) # Best & Average: O(nlogn) Worst: O(n^2) def partition(A: Iterable[int], lo: int, pi: int, hi: int) -> int: """ requires 0 <= lo and lo <= pi and pi < hi and hi <= len(A) ensures lo <= result and result < hi ensures geSeg(A[result], A, lo, result) ensures leSeg(A[result], A, result, hi) """ pivot = A[pi] swap(A, lo, pi) left = lo + 1 right = hi while (left<right): assert lo+1 <= left and left <= right and right <= hi assert geSeg(pivot, A, lo+1, left) assert leSeg(pivot, A, right, hi) if (A[left] <= pivot): left += 1 else: assert A[left] > pivot swap(A, left, right-1) right -= 1 swap(A, lo, left-1) return left-1 # Quick Sort # Best & Average: O(nlogn) Worst: O(n^2) def quickSort(A: Iterable[int], lo: int, hi: int) -> None: """ Implementation of Quick Sort requires 0 <= lo and lo <= hi and hi <= len(A) ensures isSorted(A, lo, hi) """ if (hi-lo <= 1): return pi = random.randint(lo, hi-1) #random index of the array mid = partition(A, lo, pi, hi) quickSort(A, lo, mid) quickSort(A, mid+1, hi) return A = [1,5,6,7,3,4] print(A) quickSort(A, 0, len(A)) print(A) def merge(A: Iterable[int], lo: int, mid: int, hi: int) -> None: """ requires 0 <= lo and lo <= mid and mid <= hi and hi <= len(A) requires isSorted(A, lo, mid) and isSorted(A, mid, hi) ensures isSorted(A, lo, hi) """ B = [0] * len(A) i, j, k = lo, mid, 0 # Compare i and j, put the lower element into the sorted array while (i < mid and j < hi): assert lo <= i and i <= mid assert mid <= j and j <= hi assert k == (i - lo) + (j - mid) if (A[i] <= A[j]): B[k] = A[i] i += 1 else: assert A[i] > A[j] B[k] = A[j] j += 1 k += 1 assert i == mid or j == hi # Put any remaining elements into the sorted array while (i < mid): B[k] = A[i] i += 1 k += 1 while (j < hi): B[k] = A[j] j += 1 k += 1 # Put back the sorted array into the original array for i in range(hi-lo): A[lo+i] = B[i] # Merge Sort # O(nlogn) def mergeSort(A: Iterable[int], lo: int, hi: int) -> None: """ Implementation of Merge Sort requires 0 <= lo and lo <= hi and hi <= len(A) ensures isSorted(A, lo, hi) """ if (hi-lo <= 1): return mid = lo + (hi-lo)//2 mergeSort(A, lo, mid) mergeSort(A, mid, hi) merge(A, lo, mid, hi) return A = [1,5,6,7,3,4] print(A) mergeSort(A, 0, len(A)) print(A)
start_num = 1 logest_chain = 0 big_num_long_chain = 0 while start_num < 1000000: # I start from 2 start_num = start_num + 1 # The chain length starts from 1, the starting number is counted in the chain chain_length = 1 chain_number = start_num # Repeat the process until the number isn't 1 while chain_number != 1: # Check if the number is even if chain_number%2 == 0: chain_number = chain_number / 2 chain_length = chain_length + 1 # Otherwise is odd else: chain_number = (3 * chain_number) + 1 chain_length = chain_length + 1 if logest_chain < chain_length: logest_chain = chain_length big_num_long_chain = start_num #print("Start num: "+str(start_num)+" | Length: "+str(chain_length)) print("Solution is: "+str(big_num_long_chain))
from tkinter import * from tkinter import ttk from tkinter.scrolledtext import * # from demopanels import msgpanel, seedismisspanel TXT = """ This window is a scrolled text widget. It displays one or more lines of text and allows you to edit the text. Here is a summary of the things you can do to a text widget: 1. Scrolling. Use the scrollbar to adjust the view in the text window. 2. Scanning. Press the left mouse button in the text window and drag up or down. This will drag the text at high speed to allow you to scan its contents. 3. Insert text. Press the left mouse button to set the insertion cursor, then type text. What you type will be added to the widget. 4. Select. Press mouse button 1 and drag to select a range of characters. Once you've released the button, you can adjust the selection by pressing button 1 with the shift key down. This will reset the end of the selection nearest the mouse cursor and you can drag that end of the selection by dragging the mouse before releasing the mouse button. You can double-click to select whole words or triple-click to select whole lines. 5. Delete and replace. To delete text, select the characters you'd like to delete and type Backspace or Delete. Alternatively, you can type new text, in which case it will replace the selected text. 6. Copy the selection. To copy the selection into this window, select what you want to copy (either here or in another application), then click button 2 to copy the selection to the point of the mouse cursor. 7. Edit. Text widgets support the standard Motif editing characters plus many Emacs editing characters. Backspace and Control-h erase the character to the left of the insertion cursor. Delete and Control-d erase the character to the right of the insertion cursor. Meta-backspace deletes the word to the left of the insertion cursor, and Meta-d deletes the word to the right of the insertion cursor. Control-k deletes from the insertion cursor to the end of the line, or it deletes the newline character if that is the only thing left on the line. Control-o opens a new line by inserting a newline character to the right of the insertion cursor. Control-t transposes the two characters on either side of the insertion cursor. Control-z undoes the last editing action performed, and, Control-Shift-z (or Control-y) redoes undone edits. 8. Resize the window. This widget has been configured with the "setGrid" option on, so that if you resize the window it will always resize to an even number of characters high and wide. Also, if you make the window narrow you can see that long lines automatically wrap around onto additional lines so that all the information is always visible.""" class ScrolledTextDemo(ttk.Frame): # sames as Basic Text demo but uses tkinter.scrolledtext # rather than creating text and scrollbars separately def __init__(self, isapp=True, name='scrolledtextdemo'): ttk.Frame.__init__(self, name=name) self.pack(expand=Y, fill=BOTH) self.master.title('Scrolled Text Demo') self.isapp = isapp self._create_widgets() def _create_widgets(self): if self.isapp: pass # don't need message panel # SeeDismissPanel(self) self._create_demo_panel() def _create_demo_panel(self): # create demo panel demoPanel = ttk.Frame(self) demoPanel.pack(side=TOP, fill=BOTH, expand=Y) # create scrolled text widget text = ScrolledText(height=30, wrap=WORD, undo=True, setgrid=True, pady=2, padx=3) text.pack(in_=demoPanel, fill=BOTH, expand=Y) # add text to scrolled text widget text.insert(END, TXT) if __name__ == '__main__': ScrolledTextDemo().mainloop()
class GridWorld: # 4 x 4 그리드 월드 x = 0 y = 0 def step(self, a): if a == 0: self.move_right() elif a == 1: self.move_left() elif a == 2: self.move_up() else: self.move_down() # 보상은 언제나 -1 reward = -1 done = self.is_done() return (self.x, self.y), reward, done def move_right(self): # 오른쪽으로 이동하니까 y좌표 +1 self.y += 1 if self.y > 3: # 가장 오른쪽 칸을 벗어나려고 하면 가장 오른쪽 칸으로 돌아온다 self.y = 3 def move_left(self): # 왼쪽으로 이동하니까 x좌표 -1 self.y -= 1 if self.y < 0: # 가장 왼쪽 칸을 벗어나려고 하면 가장 왼쪽 칸으로 돌아온다 self.y = 0 def move_up(self): # 위로 움직이니까 x좌표 -1 self.x -= 1 if self.x < 0: # 맨 위를 뚫으려고하면 맨 위로 다시 돌아온다 self.x = 0 def move_down(self): # 아래로 움직이니까 x좌표 +1 self.x += 1 if self.x > 3: # 맨 아래를 뚫으려고하면 맨 아래로 다시 돌아온다 self.x = 3 def is_done(self): # x,y 가 3,3 이 되면 에피소드 종료 if self.x == 3 and self.y == 3: return True else: return False def get_state(self): return (self.x, self.y) def reset(self): # 에피소드가 끝나면 0,0 위치로 다시 돌아감 self.x = 0 self.y = 0 return (self.x, self.y)
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] print(L[0:3]) #['Michael', 'Sarah', 'Tracy'] print(L[:3]) #['Michael', 'Sarah', 'Tracy'] print(L[1:3]) #['Sarah', 'Tracy'] print(L[1:]) #[ 'Sarah', 'Tracy', 'Bob', 'Jack'] print(L[-1]) #['Jack'] print(L[-2:]) #'Bob', 'Jack' print(L[-2:-1]) #Bob', 'Jack' L2 = list(range(100)) print(L2[:10:2]) #0246 #所有数,每5个取一个: print(L2[::5]) #051015 print((0, 1, 2, 3, 4, 5)[:3]) #012 print('ABCDEFG'[:3]) #ABC
from urllib import request from urllib import parse base_url ='http://www.baidu.com/s?' wd = input("输入搜索关键字") qs = { 'wd':wd } print(qs) #{'wd': 'aaa'} qs = parse.urlencode(qs) #转换url编码 print(qs) #wd=aaa #拼接url fullurl = base_url + qs response = request.urlopen(fullurl) html = response.read().decode('utf-8') print(html) with open("E:\DXP\爬虫练习\dnf.html",'w',encoding="utf-8") as fp: fp.write(html)
#area of circle pi=3.14 r=2 area=pi*r*r print(area)
#!/bin/python3 # -*- coding: utf-8 -*- # ship.py # @author 刘秋 # @email [email protected] # @description 飞船的类 # @created 2019-08-16T11:21:33.165Z+08:00 # @last-modified 2019-08-23T10:41:30.305Z+08:00 import pygame from pygame.sprite import Sprite class Ship(Sprite): """飞船类""" def __init__(self, ai_settings, screen, ): """初始化飞船 并设置其初始位置""" super().__init__() self.screen = screen self.ai_settings = ai_settings # 加载飞船图像并获取其外形矩形 self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() # 将每艘新飞船放在屏幕底部中央 self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom # 移动标志 self.moving_right = False self.moving_left = False self.moving_up = False self.moving_down = False def update(self): """根据移动标识调整飞船位置-计算""" center = float(self.rect.centerx) botto = float(self.rect.bottom) if self.moving_right: center += self.ai_settings.ship_speed_factor if self.moving_left: center -= self.ai_settings.ship_speed_factor if self.moving_down: botto += self.ai_settings.ship_speed_factor if self.moving_up: botto -= self.ai_settings.ship_speed_factor # 判断和更改坐标 self.__get_update(botto, center) def __get_update(self, botto, center): """ 修改位置条件""" if center > self.ai_settings.screen_width: center = 1 if center < 0: center = self.ai_settings.screen_width - 1 if botto > self.ai_settings.screen_height: botto = 1 if botto < 0: botto = self.ai_settings.screen_height - 1 self.rect.bottom = botto self.rect.centerx = center def blitme(self): """在指定位置位置飞船""" self.screen.blit(self.image, self.rect) def center_ship(self): """让飞船在屏幕中央""" self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom
import os import Conversao import SomaBinario import SubtracaoBinario import MultiplicacaoBinario import DivisaoBinario def menu_principal(): while(True): print("BEM VINDO A CALCULADORA BINÁRIA\n") print("===== MENU INTERATIVO =====") print("O QUE DESEJA FAZER?\n") print("[1]Converter um número decimal para binário") print("[2]Soma") print("[3]Subtração") print("[4]Multiplicação") print("[5]Divisão") print("Se quiser encerrar o programa digite 'sair'") opcao = input("OPÇÃO: ") os.system('cls') if opcao.lower() == 'sair': print("\nFim do Programa!") exit(0) elif opcao == '1': #CONVERSÃO DE DECIMAIS Conversao.conversao_decimais() elif opcao == '2': #SOMA DE BINÁRIOS SomaBinario.soma() elif opcao == '3': #SUBTRAÇÃO DE BINÁRIOS SubtracaoBinario.subtracao() elif opcao == '4': #MULTIPLICAÇÃO DE BINÁRIOS MultiplicacaoBinario.multiplicacao() elif opcao == '5': #DIVISÃO DE BINÁRIOS DivisaoBinario.divisão() else: #QUALQUER OUTRA OPÇÃO DIGITADA SERÁ INVÁLIDADA PARA O BOM USO DO CÓDIGO print("Opção inválida, tente novamente\n") os.system('pause') os.system('cls') continue
''' Created on 04.07.2014 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. ''' def count_amicable_numbers(): numbers_and_divisor_sums = dict((x, get_divisors(x)) for x in range(0, 10001)) print(sum([number for number, divisor_sum in numbers_and_divisor_sums.iteritems() if (number == numbers_and_divisor_sums.get(divisor_sum) and number != numbers_and_divisor_sums.get(number))])) def get_divisors(number): limit = number / 2 + 1 return sum([div_Test for div_Test in range(1,limit) if (number % div_Test) == 0]) if __name__ == '__main__': count_amicable_numbers()
num = int(input("Enter a number: ")) m = num % 2 if m > 0: print(" an odd.") else: print("an even .")
class Tris: def __init__(self): self.l = [" ", " ", " ", " ", " ", " ", " ", " ", " "] def pieno(self, x, y): return self.l[(x - 1) * 3 + y - 1] != " " def inserisci_la_giocata(self, x, y, g): self.l[(x - 1) * 3 + y - 1] = g def stampa_il_campo(self): print(self.l[0] + "|" + self.l[1] + "|" + self.l[2]) print(self.l[3] + "|" + self.l[4] + "|" + self.l[5]) print(self.l[6] + "|" + self.l[7] + "|" + self.l[8]) def vittoria(self): if ((self.l[0] == self.l[1] and self.l[1] == self.l[2] and self.l[1] != " ") or (self.l[3] == self.l[4] and self.l[4] == self.l[5] and self.l[3] != " ") or (self.l[6] == self.l[7] and self.l[7] == self.l[8] and self.l[6] != " ") or (self.l[0] == self.l[3] and self.l[6] == self.l[3] and self.l[3] != " ") or (self.l[1] == self.l[4] and self.l[4] == self.l[7] and self.l[1] != " ") or (self.l[2] == self.l[5] and self.l[5] == self.l[8] and self.l[2] != " ") or (self.l[0] == self.l[4] and self.l[4] == self.l[8] and self.l[0] != " ") or (self.l[2] == self.l[4] and self.l[4] == self.l[6] and self.l[2] != " ")): return True else: return False tris = Tris() for i in range(9): if i % 2 == 0: giocatore = "X" else: giocatore = "O" #il giocatore sceglie la giocata mossa = input("Dove vuoi mettere la "+ giocatore +" (riga-colonna):") riga = int(mossa[0]) colonna = int(mossa[1]) while True: #controllo se è piena la casella if tris.pieno(riga, colonna) == True: print("posizione non disponibile!") mossa = input("Dove vuoi mettere la "+ giocatore +" (riga-colonna):") riga = int(mossa[0]) colonna = int(mossa[1]) else: break tris.inserisci_la_giocata(riga, colonna, giocatore) tris.stampa_il_campo() #controllo vittoria tris.vittoria() if tris.vittoria() == True: print("Bravo ha vinto " + giocatore + " !") exit() print("Bel pareggio!!!")
def power(n): while (n % 2 == 0): n /= 2; return n == 1; n=int(input()) if power(n): print("yes") else: print("no")
from binary_search_tree import BinarySearchTree import time start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() binary_tree = BinarySearchTree(names_1[0]) duplicates = [] for i in range(1, len(names_1)): # Populate binary tree binary_tree.insert(names_1[i]) for j in range(1, len(names_2)): # Using BST "contains" in names_2 to find duplicates if binary_tree.contains(names_2[j]): duplicates.append(names_2[j]) # for name_1 in names_1: # for name_2 in names_2: # if name_1 == name_2: # duplicates.append(name_1) end_time = time.time() print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n") print(f"runtime: {end_time - start_time} seconds") # ---------- Stretch Goal ----------- # Python has built-in tools that allow for a very efficient approach to this problem # What's the best time you can accomplish with no restrictions on techniques or data # structures?
''' Created on Apr 11, 2018 @author: riccga ''' from random import randint sbank = 60 bank = sbank point = 'off' bet = 5 odds = 0 def roll_dice(): dice = randint(1,6) return dice bank = bank - bet print bank print "Bet is $" + str(bet) dicea = roll_dice() diceb = roll_dice() total = dicea + diceb print "Dice A = " + str(dicea) print "Dice B = " + str(diceb) print "Total = " + str(total) if point =='off': if total == 7: print 'WIN' bank = bank + bet*2 print bank elif total == 2 or total == 12: print 'LOSE' else: point = "on" point_num = total print "Point is on " + str(total) print "How much odds would you like to put on it?" odds = float(raw_input()) bank = bank - odds*bet while point != 'off': dicea = roll_dice() diceb = roll_dice() total = dicea + diceb print "Dice A = " + str(dicea) print "Dice B = " + str(diceb) print "Total = " + str(total) if total == point_num: point = 'off' bank = float(bank) + float(bet)*2 + float(bet)*odds*2.5 break elif total == 7: point = 'off' break print 'You have made ' + str(float(bank-sbank)) + 'Dollars ' + ' or a ' + str(float((bank-sbank)/sbank*100)) + str(' percent!')
import typing import numpy as np from data import SecretaryInstance def secretary_algorithm(all_candidates, max_colors) -> SecretaryInstance: """This method runs the first baseline: the Secretary Algorithm Args: all_candidates ([SecretaryInstance]): List of all candidates max_colors ([string]): List of names of all groups Returns: SecretaryInstance: The selected candidate """ stop_rule = round(len(all_candidates) / np.e) max_value = np.max([item.score for item in all_candidates[:stop_rule]]) try: best_candidate = next(x for x in all_candidates[stop_rule:] if x.score > max_value) best_candidate.ismax = best_candidate.score == max_colors[best_candidate.color] except StopIteration: best_candidate = SecretaryInstance(-1, -1, None) return best_candidate def one_color_secretary_algorithm(candidates, max_colors, *args) -> SecretaryInstance: """This method runs the second baseline: the One Color Secretary Algorithm Args: all_candidates ([SecretaryInstance]): List of all candidates max_colors ([string]): List of names of all groups args (tuple): Necessary arguments, namely the list of colors, probabilities and size of groups Returns: SecretaryInstance: The selected candidate """ colors, probabilities = args[0], args[1] rand_balanced = np.random.rand() for i in range(len(probabilities)): if rand_balanced <= probabilities[i]: winning_group = [x for x in candidates if x.color == colors[i]] break rand_balanced -= probabilities[i] best_candidate = secretary_algorithm(winning_group, max_colors) try: best_candidate.ismax = best_candidate.score == max_colors[best_candidate.color] except KeyError: best_candidate.ismax = False return best_candidate def multiple_color_secretary_algorithm(candidates, max_colors, *args) -> SecretaryInstance: """This method runs the fair opt algorithm: the Multiple Color Secretary Algorithm Args: all_candidates ([SecretaryInstance]): List of all candidates max_colors ([string]): List of names of all groups args (tuple): Necessary arguments, namely the list of colors, probabilities and size of groups Returns: SecretaryInstance: The selected candidate """ colors, thresholds = args[0], args[1] max_until_threshold = [0] * len(colors) for i in range(len(candidates)): color_index = colors.index(candidates[i].color) if i < thresholds[color_index]: max_until_threshold[color_index] = max(max_until_threshold[color_index], candidates[i].score) if i >= thresholds[color_index] and candidates[i].score >= max_until_threshold[color_index]: candidates[i].ismax = candidates[i].score == max_colors[candidates[i].color] return candidates[i] return SecretaryInstance(-1, -1, None) def multiple_color_thresholds(p) -> typing.List[float]: """Helper function for the fair opt algorithm. Receives probabilities and converts them to threshold Args: p ([float]): The groups probability of being selected Returns: t ([float]): A percentage threshold to be used in the main algorithm """ t = [0.0] * len(p) k = len(p) t[k-1] = np.power((1 - (k - 1) * p[k - 1]), (1 / (k - 1))) for j in range(k-2, 0, -1): sum = np.sum([p[r] for r in range(0, j+1)]) sum /= j t[j] = t[j+1] * np.power((sum - p[j]) / (sum - p[j+1]), 1 / j) t[0] = t[1] * np.exp(p[1] / p[0] - 1) return t
def parse_fasta(fasta_file): sequence = '' with open(fasta_file) as f: for line in f: if not line.startswith(">"): sequence += line.strip() return sequence
""" This class represents a cell in a maze, or a state. Each cell stores not only its own cost, but the cost of the path up to it, and the path leading toward it. """ class Cell: def __init__(self, row, col, loc, value, cost, path_cost, path): self.parent = None self.row = row self.col = col self.loc = loc self.value = value if value == '*': self.interpreted_value = value self.cost = cost self.path_cost = path_cost self.path = path def update_interpreted_value(self, new_interpreted_value): if self.value != '*': raise ValueError self.interpreted_value = new_interpreted_value def __str__(self): return "<" + str(self.loc) + "," + str(self.value) + ">"
import math def is_prime(num): for i in range(2, math.ceil(math.sqrt(num))): if not num % i: return False return True def field_in(): field = int(input("input the size of field Z: ")) if not is_prime(field): print("this is not a field") return field def polynomial_in(): polynomial = input("Enter polynomial F[x,y]: ") polynomial = polynomial.replace(' ', "") polynomial = polynomial.replace('-', "+-") polynomial = polynomial.split('+') result = [] for term in polynomial: if len(term) == 0: continue temp = {'num': 0, 'x': 0, 'y': 0} prev = 0 # 0 for num, 1 x, 2 y number = "" x = "0" y = "0" for character in term: if character == '^': if prev == 1: x = "" else: y = "" continue if character == '-': continue if prev == 0: if character != 'x' and character != 'y': number += character else: if character == 'x': prev = 1 x = "1" elif character == 'y': prev = 2 y = "1" elif prev == 1: if character != 'y': x += character else: prev = 2 y = "1" elif prev == 2: if character != 'x': y += character else: prev = 1 x = "1" try: temp['num'] = int(number) if term[0] == '-': temp['num'] *= -1 except ValueError: temp['num'] = 1 if term[0] != '-' else -1 temp['x'] = int(x) temp['y'] = int(y) result.append(temp) return result def calculate(poly, x, y, field): result = 0 for term in poly: result += term['num'] * x**term['x'] * y**term['y'] return result % field def display(polynomial, field): for row in range(field - 1, -1, -1): print("{0:2}".format(row)+'|', end="") for column in range(field): value = calculate(polynomial, column, row, field) if value == 0: print(u"\u2588\u2588", end="") else: print(' ', end="") print() print('-' * (2*(field+3))) print(' |', end="") for i in range(field): print(str(i)[0]+(" "), end="") print('\n ', end="") for i in range(field): if i > 9: print(i % 10, end=" ") else: print(' ', end="") print() def ui_loop(): field = field_in() polynomial = polynomial_in() while True: display(polynomial, field) option = input("Q quit, F new field, P new polynomial, A new everything: ") if option.upper() == 'Q': break if option.upper() == 'F': field = field_in() if option.upper() == 'P': polynomial = polynomial_in() if option.upper() == 'A': field = field_in() polynomial = polynomial_in() if __name__ == '__main__': ui_loop()
def prime(no): cnt=1 for i in range(2,no): if no%i==0: cnt=0 break if cnt == 1: print("Number is prime") else: print("Number is not prime") print("Enter the number") no=int(input()) prime(no)
class FilterTest: __doc__ = ''' 和map()类似,filter()也接收一个函数和一个序列。 和map()不同的是,filter()把传入的函数依次作用于每个元素, 然后根据返回值是True还是False决定保留还是丢弃该元素。 ''' def __init__(self): self.seq = None pass def oddnums_iter(self): n = 1 while True: n = n + 2 yield n def filtered_nums(self): yield 2 self.seq = self.oddnums_iter() while True: n = next(self.seq) yield n self.seq = filter(self._not_divisible(n), self.seq) def _not_divisible(self, n): return lambda x: x % n > 0 def do_test(self): n = 0 for i in self.filtered_nums(): if i > 1000: break else: print(i) n += 1 print(">>>", n, "个") if __name__ == '__main__': filter_test = FilterTest() filter_test.do_test()
''' TO DO: abstract into class. add decks. ''' from sys import argv from random import choice import pickle class ArdenDeck: def __init__(self, deckType): self.deck = {} def setDeck(self, deck): self.deck = deck def initCards(self): self.deck = {} self.deck['type'] = "standard" self.deck['cards'] = [] for number in range(0,52): deck['cards'].append( {} ) deck['cards'][number]['name'] = numToCardName(number) deck['cards'][number]['hp'] = 100 return deck def numToCardName(self, num): values = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king'] suits = ['spades','clubs','hearts','diamonds'] if num < 52: valIndex = num % len(values) suitIndex = int(num / len(values) - 1) return "%s of %s" % ( values[valIndex], suits[suitIndex] ) else: return "joker" def bridgeShuffle(self): ''' fold a deck onto itself ''' final_pile = [] #halve the deck, poorly splitpoint = len(self.deck['cards']) / 2 + choice(range(-7, 7)) subdeck_a = self.deck['cards'][0:splitpoint] subdeck_b = self.deck['cards'][splitpoint:] #drop cards from subdecks into a pile, close to one at a time while len(final_pile) != len(self.deck['cards']): maxcards_a = choice(range(1,3)) for num in range(1,maxcards_a): if ( len(subdeck_a) >= num ): final_pile.append(subdeck_a.pop(-1)) maxcards_b = choice(range(1,3)) for num in range(1,maxcards_b): if ( len(subdeck_b) >= num ): final_pile.append(subdeck_b.pop(-1)) #massage data newdeck = self.deck.copy() newdeck['cards'] = final_pile self.deck = newdeck def drawTopCard(self): card = self.deck['cards'].pop(0) card['hp'] -= 0.1 return card def putCardIntoDeck(self, card, location="mid"): if location == "top": self.deck['cards'].insert(0, card) elif location == "bot": self.deck['cards'].insert(-1, card) elif location == "mid": maxrange = int( len(self.deck['cards']) / 8 ) offby = choice( range( -maxrange, maxrange ) ) location = len(deck['cards']) / 2 + offby self.deck['cards'].insert(location, card) else: #location is an index self.deck['cards'].insert(location, card)
#builtin modules-random module import random#importing module for i in range(3): print(random.random())#returns value btw 0 and 1 for i in range(3): print(random.randint(10,20))#returns arbitrary value btw 10 and 20(included) #if u want to randomly choose something members=['Cel','galdin','sheena','joy'] leader=random.choice(members) print(leader)
#pb prev='stop' inst=input('<').lower() while inst!='quit': if inst=='help': print('start-to start the car') print('stop-to stop the car') print('quit-to exit') elif inst=='start': if prev==inst: print('hey, the car has already started') else: print('car started ...ready to go!') elif inst=='stop': if prev==inst: print('hey the car has already stopped') else: print('car stopped.') else: print("i don't understand this") prev=inst inst=input('<').lower()
#nexted loop;print all 2D coordinates possible with 0<=x<=3 and 0<=y<=2 for i in range(4): for j in range(3): print(f'({i},{j})')
class hashtable: def __init__(self): self.max=100 self.arr=[None for i in range(self.max)] def get_hash(self,key):#our hash fn is sum of ascii values of key modulus 100 sum=0 for char in key: sum+=ord(char)#returns ascii value of character return sum%self.max #def add(self,key,value): # h=self.get_hash(key) # self.arr[h]=value #or u can use below fn def __setitem__(self,key,value):#to set the value of arr at index key to value h=self.get_hash(key) #here u can use like arr[key]=value to call self.arr[h]=value def __getitem__(self,key): h=self.get_hash(key) #here u can use arr[key] while calling instead p1.some_fn(key) return self.arr[h] def __delitem__(self,key):#standard operators in python h=self.get_hash(key) self.arr[h]=None t=hashtable() t['march 6']=130 t['march 1']=20 t['dec 17']=27 print(t['march 6']) del t['march 1'] print(t['march 1'])
#!/usr/bin/env python2.7 import sys import random greetings = ("hi", "hello", "how are you,") responses = ["well hello there", "hey", "wassup?"] input = raw_input("Please enter a message: ") def respond_to_greeting(input): for word in input.split(): if word.lower() in greetings: return random.choice(responses) return "*smiles and nods*" output = respond_to_greeting(input) print output
from math import pi def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def division(num1, num2): return num1 / num2 def remainder(num1, num2): return num1 % num2 def squared(num, indices): return num ** indices def quotient(num1, num2): return num1 // num2 myString = """Life is to short, You need python""" upper_string = "HI ALL" under_string = "hi all" greeting = " Hi " odd = [1, 3, 5, 7, 9] even = [2, 4, 6, 8, 10] strings = [1, 2, 3, ['self', 'b', 'c', 'd', 'e']] set_a = set([1, 2, 3, 4, 5]) set_b = set([4, 5, 6, 7, 8, 9, 10]) finalList = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) is_day = False is_light_on = not is_day if __name__ == '__main__': print("타입 확인 시작".center(20, '#')) integer = 1 print(type(integer), integer) a = 1.2 print(type(a), a) print(type(myString), myString) data = { '시스템유틸리티제작': True , 'GUI 프로그래밍': True , 'C/C++와의결합': True , '웹 프로그래밍': True , '수치연산프로그래밍': True , '데이터베이스프로그래밍': True , '데이터분석_IoT': True , '시스템프로그래밍': False , '모바일프로그래밍': False } print(type(data), data) myList = range(0, 10) print(type(myList), myList) myList2 = [] for i in myList: myList2.insert(i, i) print(type(myList2), myList2) print(type(set_a), set_a) print(type(finalList), finalList) print(type(is_day), is_day) print(type(is_light_on), is_light_on) print("타입 확인 끝".center(20, '#')) print("숫자 사칙연산시작".center(20, '#')) print(f"""더하기: 1+1 = {add(1, 1)}""") print(f"""빼기: 15-12 = {subtract(15, 12)}""") print(f"""곱하기: 3*7 = {multiply(3, 7)}""") print(f"""나누기: 3/4 = {division(3, 4)}""") print(f"""몫: 3/4 = {quotient(3, 4)}""") print(f"""나머지: 3/4 = {remainder(3, 4)}""") print(f"""제곱: 2**3 = {squared(2, 3)}""") print("숫자사칙연산시작끝".center(20, '#')) print("문제풀이 시작".center(20, '#')) print("숫자 14를 3으로 나누었을 때 몫과 나머지") print(f"""몫: 14/3 = {quotient(14, 3)}""") print(f"""나머지: 14/3 = {remainder(14, 3)}""") print("문제풀이 끝".center(20, '#')) print("문자열 연산".center(20, '#')) head = "Python" tail = " is fun" print("문자열 더하기:", add(head, tail)) print("문자열 곱하기:", multiply(head, 3)) print("문자열 길이:", len(myString.split(',')[0].strip())) print("문자열 연산끝".center(20, '#')) print("문제풀이 시작".center(20, '#')) print("You need python 문장을 문자열로 만들고 길이를 구해 보자") print(myString.split(',')[1].strip() + " 길이:", len(myString.split(',')[1].strip())) print("문제풀이 끝".center(20, '#')) print("문자열슬라이싱".center(20, '#')) print("myString[0:4]:", myString[0:4]) print("myString[0:4:2]:", myString[0:4:2]) print("myString[:8]:", myString[:8]) print("myString[8:]:", myString[8:]) print("문자열슬라이싱끝".center(20, '#')) print("문자열인덱싱".center(20, '#')) print("myString[3]:", myString[3]) print("myString[-3]:", myString[-3]) print("문자열인덱싱끝".center(20, '#')) print("문자열치환".center(20, '#')) print("python -> Python", myString.replace("python", "Python")) print("문자열치환끝".center(20, '#')) print("문자열 포맷팅".center(20, '#')) number = 10 day = "삼" print("저는 사과 %d개를 먹었습니다. 그래서 저는 %s일동안 아팠습니다." % (number, day)) print(f"""시스템유틸리티제작: {data['시스템유틸리티제작']}""") print("정렬과 공백:", "%10smy crews" % upper_string) print("정렬과 공백:", "%-10smy crews" % upper_string) print("소수점 표현하기", "%0.4f" % pi) print("문자열 포맷팅 끝".center(20, '#')) print("문제풀이".center(20, '#')) print("""format 함수 또는 f문자열 포매팅을 사용해 '!!!python!!!'문자열을 출력해보자""") print(f"""{'python':!^12}""") print("문제풀이 끝".center(20, '#')) print("문자열 관련 함수".center(20, '#')) words = myString.split(" ") print("문자 개수 세기(myString): ", myString.count('i')) print("문자위치 알려주기(find):", myString.find('You')) print("문자위치 알려주기(index):", myString.index('o')) a = 'abcd' print("','.join('abcd') =>", ','.join(a)) print("소문자를 대문자로 바꾸기", under_string.upper()) print("대문자를 소문자로 바꾸기", upper_string.lower()) print("왼쪽공백 지우기", greeting.lstrip()) print("오른쪽공백 지우기", greeting.rstrip()) print("양쪽공백 지우기", greeting.strip()) print("문자열 치환", myString.replace("Life", "Your reg")) print("문자열나누기", myString.split(" ")) print("문자열 관련 함수 끝".center(20, '#')) print("리스트".center(20, '#')) print("리스트 인덱싱:", odd[2]) print("리스트 내 값 더하기", add(odd[0], odd[1])) print("리스트 even 내 마지막 요소", even[-1]) print("리스트 strings에 포함된 'self' 값을 인덱싱을 사용해 출력", strings[-1][0]) print("리스트 슬라이싱 odd[0:2]:", odd[0:2]) A = list(range(1, 6)) print(f"""A={A} 리스트에서 슬라이싱 기법을 사용하여 리스트 [2,3]을 만들어보자""") print("정답:", A[1:3]) print("리스트더하기: ", odd + even) print("리스트반복하기: ", odd * 3) print("리스트길이구하기", len(odd)) print("리스트 값 수정, A[4] =", A[4]) A[4] = 7 print("리스트 값 수정, A[4] =", A[4]) A = list(range(1, 6)) print("del 함수 사용해 리스트 요소 삭제, 원래는", A) del A[2] print("삭제후", A) A = list(range(1, 6)) del A[2:] print("슬라이싱으로 한꺼번에 삭제", A[:2]) A.append(3) A.append(4) A.append(5) print("리스트 요소 추가", A) A.append([6, 7]) print("리스트 요소 추가", A) C = odd + even print("C=", C) C.sort() print("리스트 정렬", C) C.reverse() print("리스트 뒤집기", C) C.insert(0, 11) print("리스트요소삽입 ", C) C.remove(3) print("리스트 요소 삭제", C) print("리스트 요소 끄집어내기", C.pop()) print("리스트 요소 끄집어내기", C.pop(1)) print("끄집어낸 요소는 삭제됨", C) print("리스트 요소 갯수 세기", C.count(7)) C.extend([1, 0]) print("리스트확장", C) print("리스트 끝".center(20, '#')) print("튜플".center(20, '#')) print("리스트는 저장된 항목의 변경이 가능하지만, 튜플은 불가능하다.") print("튜플 슬라이싱", finalList[:3]) t2 = (11, 12) print("튜플더하기", finalList + t2) print("튜플 곱하기", multiply(finalList, 3)) print("튜플 길이구하기", len(finalList)) print("튜플 끝".center(20, '#')) print("딕셔너리".center(20, '#')) print("딕셔너리", data) print("딕셔너리 Key만 출력", data.keys()) keys = data.keys() print("딕셔너리 내용 출력") for name in keys: print(name + ":", data.get(name)) data2 = data print(data.items()) print("데이터2 확인", data2) data2.clear() print("데이터2 clear", data2) print("딕셔너리 끝".center(20, '#')) print("집합 자료형".center(20, '#')) print("집합 자료형", set_a) str_set = set("Hello") print("문자 집합", str_set) print("집합 self=", set_a, "집합 b=", set_b, "교집합=", set_a & set_b) print("집합 self=", set_a, "집합 b=", set_b, "교집합=", set_a.intersection(set_b)) print("집합 self=", set_a, "집합 b=", set_b, "합집합=", set_a.union(set_b)) print("집합 self=", set_a, "집합 b=", set_b, "차집합=", set_a.difference(set_b)) set_c = set([1, 2, 3]) set_c.add(4) print("집합 c에 4를 추가", set_c) set_c.update([5, 6]) print("집합 c에 5,6를 추가", set_c) print("집합 자료형 끝".center(20, '#'))
# Задача - 1 # Опишите несколько классов TownCar, SportCar, WorkCar, PoliceCar # У каждого класса должны быть следующие аттрибуты: # speed, color, name, is_police - Булево значение. # А так же несколько методов: go, stop, turn(direction) - которые должны сообщать, # о том что машина поехала, остановилась, повернула(куда) class TownCar: def __init__(self, speed, color, name, is_police=False): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): return 'поехала' def stop(self): return 'остановилась' def turn(self, direction): return 'повернула ' + direction class SportCar: def __init__(self, speed, color, name, is_police=False): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): return 'поехала' def stop(self): return 'остановилась' def turn(self, direction): return 'повернула ' + direction class WorkCar: def __init__(self, speed, color, name, is_police=False): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): return 'поехала' def stop(self): return 'остановилась' def turn(self, direction): return 'повернула ' + direction class PoliceCar: def __init__(self, speed, color, name, is_police=True): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): return 'поехала' def stop(self): return 'остановилась' def turn(self, direction): return 'повернула ' + direction town_car = TownCar('100', 'Серебристый', 'Honda Fit') print('{} {}'.format(town_car.name, town_car.go())) print(town_car.is_police) # Задача - 2 # Посмотрите на задачу-1 подумайте как выделить общие признаки классов # в родительский и остальные просто наследовать от него. class Car: def __init__(self, speed, color, name, is_police=False): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): return 'поехала' def stop(self): return 'остановилась' def turn(self, direction): return 'повернула ' + direction class TownCar(Car): pass class SportCar(Car): pass class WorkCar(Car): pass class PoliceCar(Car): def __init__(Car, speed, color, name): super().__init__(speed, color, name, is_police=True) police_car = PoliceCar('120', 'темный', 'FORD ') print('{} {}'.format(police_car.name, police_car.turn('на лево'))) print(police_car.is_police)
def how_many_trees(tree_map, x_slope, y_slope): x = 0 y = 0 trees = 0 while y <= len(tree_map) - 1: if tree_map[y][x % len(tree_map[y])] == "#": trees += 1 y += y_slope x += x_slope return trees def get_input(): with open("input.txt") as f: return [line.strip() for line in f.readlines()] if __name__ == "__main__": # part 1 input_map = get_input() trees = how_many_trees(input_map, 3, 1) print(f"Ran into {trees} trees with a 3/1 slope") print("-" * 20) # part 2 slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] # (x, y) trees_encountered = [] for slope in slopes: trees_encountered.append(how_many_trees(input_map, slope[0], slope[1])) product = 1 for tree_count in trees_encountered: product *= tree_count print(f"Product of trees encountered across all slopes is {product}")
def make_seat_map(): return [[0, 0, 0, 0, 0, 0, 0, 0] for y in range(128)] def populate_seat_map(boarding_passes, seat_map): for boarding_pass in boarding_passes: y = [i for i in range(128)] x = [i for i in range(8)] for index, instruction in enumerate(boarding_pass): if instruction == "F": y = y[: len(y) // 2] elif instruction == "B": y = y[len(y) // 2 :] elif instruction == "L": x = x[: len(x) // 2] elif instruction == "R": x = x[len(x) // 2 :] if index == len(boarding_pass) - 1: seat_map[y[0]][x[0]] = 1 def seat_ids(seat_map, return_max=False): max_id = 0 all_ids = {} for row, _ in enumerate(seat_map): for column, _ in enumerate(seat_map[row]): if seat_map[row][column] != 1: continue current_id = (row * 8) + column all_ids[current_id] = None if current_id > max_id: max_id = current_id if return_max: return max_id return all_ids def find_seat(seat_map, all_seat_ids): for row, _ in enumerate(seat_map): for column, _ in enumerate(seat_map[row]): if seat_map[row][column] == 1: continue current_id = (row * 8) + column if current_id + 1 in all_seat_ids and current_id - 1 in all_seat_ids: return current_id def get_input(): with open("input.txt") as f: return [line.strip() for line in f.readlines()] if __name__ == "__main__": # part 1 inputs = get_input() seat_map = make_seat_map() populate_seat_map(inputs, seat_map) max_id = seat_ids(seat_map, True) print(f"Max seat id is {max_id}") print("-" * 20) # part 2 all_seat_ids = seat_ids(seat_map) santa_seat_id = find_seat(seat_map, all_seat_ids) print(f"Santa's seat ID is {santa_seat_id}")
''' Car Price Prediction ''' import pandas as pd import seaborn as sns df=pd.read_csv("D:/Studies/Course Material/car_price_prediction_project/car data.csv") df.head() df.dtypes df.columns col=[col for col in df.columns if df[col].dtypes=='object'] col.pop(0) # to find the unique categories for the categorical variables for i in col: print(str(i)+" - " + str(df[i].unique())) # to find the count of unique categories for the categorical variables for i in col: print(df[i].value_counts()) df['Owner'].value_counts() df.isnull().sum() df.describe() # dropping the car_name feature df.drop(['Car_Name'],axis=1,inplace=True) ''' We will create a new feature called number of years to find the age of the car ''' df['Current_Year']=2021 df['Age_Car']=df['Current_Year'] - df['Year'] # dropping the year and current_year feature df.drop(['Year','Current_Year'],axis=1,inplace=True) dummy=pd.get_dummies(df[col]) df=pd.concat([df,dummy],axis=1) df.drop(col,axis=1,inplace=True) df.corr() sns.pairplot(df) # creating a heatmap corrmat = df.corr() sns.heatmap(corrmat,annot=True,cmap='RdYlGn') x=df.iloc[:,1:] y=df['Selling_Price'] # feature importance from sklearn.ensemble import ExtraTreesRegressor imp = ExtraTreesRegressor() imp.fit(x,y) imp_features=pd.Series(imp.feature_importances_) imp_features.index=x.columns imp_features.sort_values(ascending=False) imp_features.nlargest(15).plot(kind='bar') from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42) ''' building different models to check which model works the best ''' # RandomForest Regressor from sklearn.ensemble import RandomForestRegressor rf=RandomForestRegressor() # XGBoost Regressor import xgboost xgb=xgboost.XGBRegressor() # Linear Regression from sklearn.linear_model import LinearRegression lr=LinearRegression() # Ridge Regression from sklearn.linear_model import Ridge ridge=Ridge() # Lasso Regression from sklearn.linear_model import Lasso lasso=Lasso() models=[rf,xgb,lr,ridge,lasso] def accuracy(i): # function to check the accuracy score acc=i.min()/i.max() return acc*100 acc_scores=[] def acc_mod(list_model,acc): for i in list_model: m=i.fit(x_train,y_train) p=pd.Series(m.predict(x_test)) df=pd.DataFrame(columns=['a','b']) df['a']=y_test df['b']=p acc_scores.append((df.apply(acc,axis=1)).mean()) acc_mod(models,accuracy) accuracy_scores=pd.DataFrame(columns=['Model Name','Accuracy Score']) accuracy_scores['Model Name']=pd.Series(['RandomForest Regression','XGB Regression','Linear Regression' ,'Ridge Regression','Lasso Regression']) accuracy_scores['Accuracy Score']=pd.Series(acc_scores) '''lasso regression has the highest accuracy score so we'll consider it for further steps''' ''' creating a pickel file of the model ''' import os import pickle os.getcwd() file = open('lasso_regressor.pkl','wb') # creating and opening a file named "lasso_regressor.pkl" in "wb(write byte") mode # dumping our model and it's parameters into the file opened above pickle.dump(lasso,file) file.close() # closing the file
import sys print("Command line arguments have been passed: ") i = 0 for arg in sys.argv: if i == 0: print("This one doesn't count " + str(sys.argv[i])) else: print(sys.argv[i]) i += 1
import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from scipy import signal from PIL import Image # -- Read an image -- # Attribution - Bikesgray.jpg By Davidwkennedy (http://en.wikipedia.org/wiki/File:Bikesgray.jpg) [CC BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons img1 = Image.open('Bikesgray.jpg') # -- Display original image -- img1.show() # -- X gradient - Sobel Operator -- f1 = np.asarray([[1, 0, -1], [2, 0, -2], [1, 0, -1]]) # -- Convolve image with kernel f1 -> This highlights the vertical edges in the image -- vertical_sobel = signal.convolve2d(img1, f1, mode='full') # -- Display the image -- # Write code here to display the image 'vertical_sobel' (hint: use plt.imshow with a color may of gray) plt.imshow(vertical_sobel, cmap="gray") mpimg.imsave("Vertical_Edges.jpg", arr=vertical_sobel, cmap="gray") plt.figure() # -- Y gradient - Sobel Operator -- f2 = np.asarray([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) # -- Convolve image with kernel f2 -> This should highlight the horizontal edges in the image -- horz_sobel = signal.convolve2d(img1, f2, mode='full') # -- Display the image -- # Write code here to display the image 'horz_sobel' (hint: use plt.imshow with a color may of gray) plt.imshow(horz_sobel, cmap="gray") mpimg.imsave("Horizontal_Edges.jpg", arr=horz_sobel, cmap="gray") plt.show()
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ def main(): # animals = { # "kitten": "meow", # "puppy": "ruff!", # "lion": "grrr", # "giraffe": "I am a giraffe!", # "dragon": "rawr", # } animals = dict( kitten="meow", puppy="ruff!", lion="grrr", giraffe="I am a giraffe!", dragon="rawr", ) # Prints all keys in the dictionary # for k in animals.keys(): # print(k) # Prints all values in the dictionary # for v in animals.values(): # print(v) # Prints the value of the key "lion" # print(animals["lion"]) # Assigns a new value to the key "lion" # animals["lion"] = "I am a lion" # Prints "True" since the dictionary contains a key called "lion" # print("lion" in animals) # Prints "found!" since the dictionary contains a key called "lion" # print("found!" if "lion" in animals else "nope!") # Prints "nope!" since the dictionary does not contains a key called "godzilla" # print("found!" if "godzilla" in animals else "nope!") # Causes a KeyError exception since the key doesn't exist # print(animals["godzilla"]) # Returns "None" since the key doesn't exist # print(animals.get("godzilla")) print_dict(animals) def print_dict(o): # for x in o: # print(f"{x}: {o[x]}") for k, v in o.items(): print(f"{k}: {v}") if __name__ == "__main__": main()
def sup21(nombre): if nombre >= 21: return True return False test_ = sup21(1) def pairs(liste): liste_paires = [liste[i] for i in range(len(liste)) if liste[i] % 2 == 0] return liste_paires le = [1, 2, 4] print(pairs(le)) def ajout4(liste): nouv = liste.copy() nouv.append(4) return nouv a = ajout4([]) def to_strings(dico): li = [] for k, v in dico.items(): cote = "" cote += str(k) + ":" + str(v) li.append(cote) # parcours des clés et valeurs return li print(to_strings({1: 2, 3: 4})) def extremites(liste): f = [] f += liste[:2] + liste[-2:] return f print(extremites(["a", "b", "c", "d", "e"])) def extremites(liste): if len(liste) > 4: res = [] res += liste[:2] + liste[-2:] return res else: assert len(liste) == None return liste class Mot: def __init__(self, mot): self.mot = mot def comptelettre(self, lettre): return self.mot.upper().count(lettre.upper()) mot = Mot("Bonjour") def tri_et_inverse(li): # liste_triee=sorted(li) li.sort(reverse=True) return li maliste = [4, 7, 6] tri_et_inverse(maliste) ville_nom_pays = { "Paris": "France", " Berlin": "Allemagne", "Madrid": "Espagne", "Moscou": "Russie", }
from abc import ABCMeta, abstractmethod class ProgressBarBase(metaclass=ABCMeta): @abstractmethod def set_title(self, title): """ Sets informative text about what the progress bar is indicating the progress of """ pass @abstractmethod def set_position(self, position): """ Sets the current thing the progress bar is on """ pass @abstractmethod def set_end(self, end): """ Sets the total number of things for the progress bar to count to """ pass
import os BOARD_TOP = [''' |/ \|/ \| |/ |/ | |/ | \| \|/ \| |/ \|/ \|\|/ |/ | | | | | | | | | ^^^^^^^^^^^^^^^^^^^| |^^^^^^^^^^^^^^^^^^^'''] BOARD_LEVELS = ['''~~~~~~~~~~~~~~~~~~~|____________________|~~~~~~~~~~~~~~~~~~~'''] TOP_BAR = ['GOLD: ', 'GPS: ', 'ITERATION: '] class Gameboard(object): """Contains all properties needed to draw the game board. """ state = None current_board = [] platform = '' def __init__(self, platform, state): self.state = state self.platform = platform self.current_board = [BOARD_TOP[0]] for i in range(10): self.current_board.append(BOARD_LEVELS[0]) def print_board(self): self.clear() self.print_top_bar() for i in range(len(self.current_board)): print(self.current_board[i]) def print_top_bar(self): to_print = str(TOP_BAR[0]) + str(self.state.total_gold) + '\t' + \ str(TOP_BAR[1]) + str(self.state.gps) + '\t' + \ 'Platform: ' + str(self.platform) + '\t' + \ str(TOP_BAR[2]) + str(self.state.iteration) print(to_print) def clear(self): if self.platform is 'Windows': os.system('cls') else: os.system('clear')
#Strings e bytes não são diretamente intercambiáveis #Strings contém unicode, bytes são valores de 8 bits def main(): #Definindo valores iniciais b = bytes([0x41, 0x42, 0x43, 0x44]) print(b) s = "Isso é uma string" print(s) #Tentando juntar os dois. #print(s + b) #Bytes e strings precisam ser encoded e decoded print(s + b.decode(('utf-8'))) #Fazendo encode da string como UTF-32 print(s.encode('utf-32') + b) if __name__ == "__main__": main()
# Usando métodos mágicos para comparar objetos entre si class Pessoa: def __init__(self, nome, sobrenome, nivel, anos_trabalhados): self.nome = nome self.sobrenome = sobrenome self.nivel = nivel self.senioridade = anos_trabalhados # TODO: Implemente as comparações usando o nível de cada pessoa def __ge__(self, other): if self.nivel == other.nivel: return self.senioridade >= other.senioridade return self.nivel >= other.nivel def __gt__(self, other): if self.nivel == other.nivel: return self.senioridade > other.senioridade return self.nivel > other.nivel def __lt__(self, other): if self.nivel == other.nivel: return self.senioridade < other.senioridade return self.nivel < other.nivel def __le__(self, other): if self.nivel == other.nivel: return self.senioridade <= other.senioridade return self.nivel <= other.nivel def main(): # Definindo pessoas dpto = [] dpto.append(Pessoa("Túlio", "Toledo", 5, 9)) dpto.append(Pessoa("João", "Junior", 4, 12)) dpto.append(Pessoa("Jessica", "Temporal", 6, 6)) dpto.append(Pessoa("Rebeca", "Robinson", 5, 11)) dpto.append(Pessoa("Thiago", "Tavares", 5, 12)) # TODO: Descobrindo quem é mais sênior print(dpto[0] > dpto[2]) print(dpto[4] < dpto[3]) # TODO: Organizando as pessoas por senioridade pessoas = sorted(dpto) for pessoa in pessoas: print(pessoa.nome) main()
#Demonstração de algumas funções built-in úteis. def main(): # Usando any() e all() para testar valores boleanos lista = [1, 2, 3, 4, 5, 6] # Retorna true caso qualquer valor da lista seja verdade print(any(lista)) # Retorna True se todos os valores da lista forem verdade print(all(lista)) # Usando as funções min e max para retornar os valores mínimo e máximo print(min(lista)) print(max(lista)) # Usando sum() para somar os valores da lista print(sum(lista)) if __name__ == "__main__": main()
#Define a global empty dictionary. Iterate from 1 till 10 and fill the dictionary # with the key as the number and value as the square of that number. #reference from google d={} def add_values(x,y): d[x]=y a=1 while(a<10): # prints uptil 10 items x=eval(input("Enter key {}:".format(a))) y=eval(input("ENter values corr. to key : ")) add_values(x,y) a+=1 for x,y in d.items(): print("Key is <",x,"> and value is <",y,">")
#Using the above dictionary, print the following output. #Aex #class : V #rolld_id : 2 #Puja #class : V #roll_id : 3 students = { 'Aex':{'class':'V', 'rolld_id':2}, 'Puja':{'class':'V', 'roll_id':3 } } for a in students: print(a) for b in students[a]: print (b,':',students[a][b])
#Sort this dictionary ascending and descending. import operator d = {7: 2, 9: 4, 4: 3, 2: 1, 0: 0} print('Original dictionary : ',d) sorted_d = dict (sorted(d.items(), key=operator.itemgetter(1))) #sort in ascending print('Dictionary in ascending order by value : ',sorted_d) sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))#sort in descending print('Dictionary in descending order by value : ',sorted_d)
#Write a Python program to count the number of strings in a list # where the string length is 2 or more # and the first and last character are the same from a given list of strings. list1 = ["himani","maheta","aba"] def match_words(list1): ctr = 0 for word in list1: if len(word) > 1 and word[0] == word[-1]: # check the string length and the first and last char is same ctr += 1 return ctr print(match_words(list1))
while True: var = input("suuuuup?").lower() print("you chose: " + var) import random choice = random.choice(["rock","paper", "scissors"]) if var == "rock" or var == "paper" or var == "scissors": print("we pick: " + choice) if var == choice: print("draw") elif var =="rock" and choice =="scissors": print("you win") elif var == "paper" and choice =="rock": print("you win") elif var == "scissors" and choice == "paper": print("you win") else: print("you loooooooseee") else: print("f you")
#!/usr/bin/env python # this is a python 2.x file due to dpkt dependency # # pcap_analyser.py # # Copyright 2014 Tim auf der Landwehr <[email protected]> # # This script provides a pcap data analyser. # It is able to count all packets in a pcap file, # find IP packets and distinguish TCP and UDP packets. # In addition it can show the http communication for a # given source ip address. # import sys import getopt import dpkt import socket # pcap analyser class class PCAPAnalyser: # init def __init__(self, filename): self.filename = filename pcap_file = open(filename) self.pcap = dpkt.pcap.Reader(pcap_file) # count all packages def count_packages(self): packages = 0 for x,y in self.pcap: packages += 1 print("The file %s contains %i packets."%(self.filename, packages)) return packages # count ip, udp and tcp packets def count_package_types(self): ip = tcp = udp = other = nonip = 0 for (ts, buf) in self.pcap: try: eth = dpkt.ethernet.Ethernet(buf) if eth.type == dpkt.ethernet.ETH_TYPE_IP: ip += 1 if eth.data.p == dpkt.ip.IP_PROTO_TCP: tcp += 1 elif eth.data.p == dpkt.ip.IP_PROTO_UDP: udp += 1 else: other += 1 else: nonip += 1 except: pass print("The file %s contains:"%(self.filename)) print("%i IP packets"%ip) print(" >%i TCP packets"%tcp) print(" >%i UDP packets"%udp) print(" >%i other IP packets"%other) print("%i non-IP packets"%nonip) # show all communication for the given ip range def show_communication(self, ip_range): for (ts, buf) in self.pcap: try: eth = dpkt.ethernet.Ethernet(buf) # only analyse TCP packets if eth.type == dpkt.ethernet.ETH_TYPE_IP \ and eth.data.p == dpkt.ip.IP_PROTO_TCP: # find source ip = eth.data src = socket.inet_ntoa(ip.src) # check if in requested range if src.startswith(ip_range): tcp = ip.data http = dpkt.http.Request(tcp.data) print("------------------------------------------------------") print(http.headers['user-agent']) print(http.headers['host']) print(src) except: pass # usage def usage(): print("\n pdf_to_text.py by Tim auf der Landwehr") print('') print(' Usage: pcap_analyser.py') print(' > Analyse .pcap files') print('') print(' --file [filename]') print(' \t.pcap-file to be analysed') print(' --ip [ip]') print(' \t.IP range to be shown, default: [192.168.179.x]') print(' \t.Specify without x ') print(' -h --help') print(' \tShow this information') # main def main(): try: opts, args = getopt.gnu_getopt(sys.argv[1:],"ho:v",["help", "file=", "ip="]) except (getopt.GetoptError, NameError): usage() sys.exit() # defaults filename = '' ip_range = '192.168.179.' # get parameters for o,v in opts: if o in ['--file']: filename = v elif o in ['-h','--help']: usage() sys.exit(1) else: print('unknown parameter %s'%o) sys.exit(1) # make sure that a file is specified if filename == '': print('Please specify an input file.') sys.exit(1) # create analyser analyser = PCAPAnalyser(filename) # count packets analyser.count_packages() # count ip, udp and tcp packets analyser.count_package_types() # show all communication for the given ip range analyser.show_communication(ip_range) if __name__ == "__main__": main()
while True: number = int(raw_input("Enter a number:")) check = int(raw_input("Give me another number to divide by:")) if number % 2 == 0: print ("{0} is an Even Number").format(number) elif number % 4 == 0: print ("{0} is a multiple of 4").format(number) else: print("{0} is odd").format(number or number2) if number % check == 0: print("{0} divides evenly by {1}").format(number, check) else: print(number, "does not divide evenly by", check)
import time import random class Engine: def __init__(self, wordlist, kelime_sayaci): self.wordlist = wordlist self.kelime_sayaci = kelime_sayaci self.zaman = time.perf_counter() self.counter = 0 self.output = "" self.wrong_counter = 0 def get_sentences(self): with open(self.wordlist, "r+", encoding = "utf-8") as f: x = f.readlines() sentence = random.choice(x) self.output = sentence.replace("\n", "") # Cleaning each word. return self.output def check(self): if (self.counter < self.kelime_sayaci): self.counter += 1 self.get_sentences() # For using method from inside of Class. else: print(self.kelime_sayaci, "Adet kelime sayısına ulaşıldı") # 'Reached to max words' return 0 def start(self): self.check() # Using check method. while True: giris = input(f"{self.output} -> ") if (giris == "q"): print(self.counter-1, "Adet doğru kelime girdiniz.") # -1 for discarding the 'q' value. print(self.wrong_counter, "Adet yanlış giriş yapıldı.") break if giris != self.output: self.wrong_counter += 1 continue if eng.check() == 0: print(self.wrong_counter, "Adet yanlış giriş yapıldı.") break if __name__ == "__main__": print("\n\n\n\n\n\n\n\n\n\n\n\n\n") while True: # Checking if input is integer or not try: inp = int(input("Kaç adet kelime yazmak istersiniz?: ")) #How many words would you like to write? except: print("Lütfen bir tam sayı giriniz.") #input must be an integer continue # Checking if input is below or equal than zero or not if (inp <= 0): print("Kelime sayısı 0'dan küçük olamaz") #Word count can't be equal or lower than 0 continue else: ch = input("Hangi dilde alıştırma yapmak istersiniz?(english | turkish): ") if (ch == "turkish" or ch == "Turkish"): eng = Engine("turkish.txt", inp) # Kelimeler -> Words eng.start() elif (ch == "english" or ch == "English"): eng = Engine("english.txt", inp) eng.start() else: print("HATALI GİRİŞ YAPILDI.") # Wrong/unknown input print("Türkçe ile devam ediliyor...") # Auto-choosing Turkish if all inputs are False. eng = Engine("turkish.txt", inp) eng.start() break
def parse(line): return line.strip() with open("input.txt") as f: lines = f.readlines() input = [parse(line) for line in lines] def analyze(numbers): zeroes = [0 for _ in numbers[0]] ones = [0 for _ in numbers[0]] for l in numbers: for i, c in enumerate(l): if c == '0': zeroes[i] += 1 else: ones[i] += 1 return zeroes, ones zeroes, ones = analyze(input) gamma = 0 epsilon = 0 for i in range(len(zeroes)): gamma *= 2 epsilon *= 2 if zeroes[i] > ones[i]: gamma += 1 else: epsilon += 1 print(gamma, epsilon, gamma * epsilon) # part 2 def filter_to(ch, idx, l): return list(filter(lambda n: n[idx] == ch, l)) oxy = list(input) co2 = list(input) for i in range(len(input[0])): zeroes, ones = analyze(oxy) if zeroes[i] > ones[i]: oxy = filter_to('0', i, oxy) else: oxy = filter_to('1', i, oxy) if len(co2) == 1: continue zeroes, ones = analyze(co2) if zeroes[i] > ones[i]: co2 = filter_to('1', i, co2) else: co2 = filter_to('0', i, co2) print(oxy, co2) print(int(oxy[0], 2) * int(co2[0], 2))
def print_expr(expr, pos): print(" " * pos + "v") print(expr) moves = {"W": (-1, 0), "E": (1, 0), "N": (0, -1), "S": (0, 1)} def parse(expr, pos, distances, start_x, start_y): x, y, length = start_x, start_y, distances[(start_x, start_y)] while expr[pos] != "$" and expr[pos] != ")": print_expr(expr, pos) print(x, y, length) move = expr[pos] if move == "(": pos = parse(expr, pos+1, distances, x, y) # can ignore displacement caused by subexpressions elif move == "|": x, y, length = start_x, start_y, distances[(start_x, start_y)] else: dx, dy = moves[move] x += dx y += dy if (x, y) in distances: length = distances[(x, y)] else: length += 1 distances[(x, y)] = length pos += 1 print_expr(expr, pos) return pos with open("day20test5.txt") as file: expr = file.readline().strip() start_x, start_y = 200, 200 distances = {(start_x, start_y): 0} pos = parse(expr, 1, distances, start_x, start_y) if pos != len(expr) - 1: print("didn't reach end", pos, len(expr)) print(max(distances.values())) print(sum(1 for range in distances.values() if range >= 1000))
# test # puzzle_input = "389125467" # real import typing puzzle_input = "135468729" class Node: def __init__(self, val, prev=None, next=None): if prev is None: prev = self if next is None: next = self self.val = val self.prev = prev self.next = next class Circle: def __init__(self, vals: typing.Sequence[int]): self.size = len(vals) self.nodes:typing.List[typing.Optional[Node]] = [None] * (self.size + 1) self.root = Node(vals[0]) self.nodes[self.root.val] = self.root for val in vals[1:]: self.root = self.insert(val) self.root = self.root.next def insert(self, val, where=None): if where is None: where = self.root if not self.nodes[val]: self.nodes[val] = Node(val) self.nodes[val].prev = where self.nodes[val].next = where.next where.next = self.nodes[val] self.nodes[val].next.prev = self.nodes[val] return self.nodes[val] def pop(self): result = self.root.val self.root.prev.next = self.root.next self.root.next.prev = self.root.prev self.root = self.root.next return result def one_turn(self): current_val = self.root.val self.root = self.root.next removed = [self.pop(), self.pop(), self.pop()] target_val = (current_val - 2) % self.size + 1 while target_val in removed: target_val = (target_val - 2) % self.size + 1 # go find target target = self.nodes[target_val] for val in removed: target = self.insert(val, target) def __str__(self): vals = [self.root.val] walker = self.root.next while walker != self.root: vals.append(walker.val) walker = walker.next return str(vals) circle = Circle([int(val) for val in puzzle_input]) ROUNDS = 100 for i in range(ROUNDS): print(i+1, circle) circle.one_turn() print(101, circle) CIRCLE_SIZE = 1_000_000 circle_nums = list(range(1, CIRCLE_SIZE+1)) circle_nums[:len(puzzle_input)] = [int(val) for val in puzzle_input] circle = Circle(circle_nums) ROUNDS = 10_000_000 for i in range(ROUNDS): if i % 100_000 == 0: print(i) circle.one_turn() one = circle.nodes[1] print(one.next.val, one.next.next.val, one.next.val * one.next.next.val)
FILE = "input.txt" with open(FILE) as f: seats = [list(line.strip()) for line in f] FLOOR = '.' EMPTY = 'L' OCCUPIED = '#' def nearby(row, col, seats): top = max(row-1, 0) bottom = min(row+2, len(seats)) left = max(col-1, 0) right = min(col+2, len(seats[0])) return sum(1 for row in seats[top:bottom] for seat in row[left:right] if seat == OCCUPIED) # given rules: # empty seat becomes occupied if it has 0 occupied neighbors # occupied seat becomes empty if it has at least 4 occupied neighbors # equivalent formation (including a seat as "nearby" itself): # any seat becomes occupied if it has 0 occupied seats nearby # any seat becomes empty if it has at least threshold occupied seats nearby # otherwise it doesn't change def step(row, col, seats, threshold, counter=nearby): current = seats[row][col] if current == FLOOR: return FLOOR count = counter(row, col, seats) if count == 0: return OCCUPIED if count >= threshold: return EMPTY return current changes = True while changes: new_seats = [[step(row, col, seats, 5) for col in range(len(seat_row))] for row, seat_row in enumerate(seats)] changes = 0 != sum(1 for row in range(len(seats)) for col in range(len(seats[0])) if seats[row][col] != new_seats[row][col]) seats = new_seats print(sum(1 for row in seats for seat in row if seat == OCCUPIED)) # part 2 with open(FILE) as f: seats = [list(line.strip()) for line in f] def visible_one(row, col, dr, dc, seats): # starting location doesn't count now row += dr col += dc while row >= 0 and row < len(seats) and col >= 0 and col < len(seats[row]): if seats[row][col] != FLOOR: return seats[row][col] row += dr col += dc return FLOOR DIRS = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)] def visible(row, col, seats): return sum(1 for dr, dc in DIRS if visible_one(row, col, dr, dc, seats) == OCCUPIED) def print_seats(seats): for row in seats: print("".join(row)) print() #print_seats(seats) changes = True while changes: new_seats = [[step(row, col, seats, 5, visible) for col in range(len(seat_row)) ] for row, seat_row in enumerate(seats)] changes = 0 != sum(1 for row in range(len(seats)) for col in range(len(seats[0])) if seats[row][col] != new_seats[row][col]) seats = new_seats #print_seats(seats) print(sum(1 for row in seats for seat in row if seat == OCCUPIED))
from breadth_first import breadth_first with open("input.txt") as f: map = [line.strip() for line in f] allkeys = set() start_x, start_y = 0, 0 for y, row in enumerate(map): for x, cell in enumerate(row): if cell == '@': start_x, start_y = x, y elif cell in 'qwertyuiopasdfghjklzxcvbnm': allkeys.add(cell) def neighbors(state): x, y, keys = state for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: newx, newy = x + dx, y + dy if newx < 0 or newx >= len(map[0]): continue if newy < 0 or newy >= len(map): continue cell = map[newy][newx] if cell == '#': continue if cell in 'QWERTYUIOPASDFGHJKLZXCVBNM' and cell.lower() not in keys: continue if cell in 'qwertyuiopasdfghjklzxcvbnm': yield 1, (newx, newy, keys | set(cell)) else: yield 1, (newx, newy, keys) def done(dist, state): x, y, keys = state if keys == allkeys: return dist else: return None # dist = breadth_first((start_x, start_y, frozenset()), neighbors, done) # print(dist) with open("input_altered.txt") as f: map = [line.strip() for line in f] allkeys = set() starts = tuple() for y, row in enumerate(map): for x, cell in enumerate(row): if cell == '@': starts = starts + ((x, y),) elif cell in 'qwertyuiopasdfghjklzxcvbnm': allkeys.add(cell) def multineighbors(state): locs, keys = state def explore(c): x, y = c for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: newx, newy = x + dx, y + dy if newx < 0 or newx >= len(map[0]): continue if newy < 0 or newy >= len(map): continue cell = map[newy][newx] if cell == '#': continue if cell in 'QWERTYUIOPASDFGHJKLZXCVBNM' and cell.lower() not in keys: continue yield 1, (newx, newy) for i, (bot_x, bot_y) in enumerate(locs): found_keys = dict() def findkey(dist, c): x, y = c cell = map[y][x] if cell in 'qwertyuiopasdfghjklzxcvbnm' and cell not in keys and (x, y) not in found_keys: found_keys[x, y] = dist # get keys breadth_first((bot_x, bot_y), explore, findkey) for (newx, newy), dist in found_keys.items(): yield dist, (tuple(locs[:i] + ((newx, newy),) + locs[i+1:]), keys | set(map[newy][newx])) def multidone(dist, state): locs, keys = state if keys == allkeys: return dist else: return None dist = breadth_first((starts, frozenset()), multineighbors, multidone, status=True) print(dist)
SNAFU_DIGITS = { '=': -2, '-': -1, '0': 0, '1': 1, '2': 2, } DIGITS_SNAFU = {v: k for (k, v) in SNAFU_DIGITS.items()} def unSNAFU(snafu): answer = 0 for c in snafu: answer *= 5 answer += SNAFU_DIGITS[c] return answer def parse(line): return unSNAFU(line) with open("input.txt") as file: lines = [parse(line.rstrip()) for line in file] final_answer = sum(lines) print(final_answer) def snafu(val): answer = [] while val != 0: digit = (val + 2) % 5 - 2 answer.append(DIGITS_SNAFU[digit]) val = (val + 2) // 5 return "".join(reversed(answer)) print(snafu(final_answer))