text
stringlengths
37
1.41M
class Wine: """ This class represents a Wine. """ def __init__(self, appellation, name, vintage, price, global_score, color): self.appellation = appellation self.name = name self.vintage = vintage self.price = price self.global_score = global_score self.color = color def get_appellation(self): return self.appellation def get_name(self): return self.name def get_vintage(self): return self.vintage def get_price(self): return self.price def get_global_score(self): return self.global_score def get_color(self): return self.color def __str__(self): return ("Wine(" "appellation: '{0}'," " name: '{1}'," " vintage: {2}," ")" ).format( self.appellation, self.name, str(self.vintage) )
# This is a comment print ('Hello world') # this prints hello world '''Assigning variables''' location = "lung'aho" name = 'Venus' age = 21 height = 163 print('My name is',name,'My height is ',height) print('My age is' , age) print ('My location is ', location) my_list = ['Venus','Mike','Inno','Trinna',7,8.9] my_turple =('Venus','Mike') my_dict = {'country' : 'Kenya', 'region' : 'Africa', 'Zip Code' : 254} print(my_dict)
#!/usr/bin/python # coding: latin-1 import math class Vector2(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __str__(self): return "(%s, %s)"%(self.x, self.y) def _get_length(self): x, y = self.x, self.y return sqrt(x*x + y*y) def _set_length(self, length): try: x, y = self.x, self.y l = length / sqrt(x*x +y*y) except ZeroDivisionError: v[0] = 0.0 v[1] = 0.0 return self v[0] *= l v[1] *= l length = property(_get_length, _set_length, None, "Length of the vector") @staticmethod def from_points(P1, P2): return Vector2(P2[0] - P1[0], P2[1] - P1[1]) def get_magnitude(self): return math.sqrt( self.x**2 + self.y**2 ) def normalize(self): magnitude = self.get_magnitude() try: self.x /= magnitude self.y /= magnitude except ZeroDivisionError: self.x = 0 self.y = 0 # rhs stands for Right Hand Side def __add__(self, rhs): return Vector2(self.x + rhs.x, self.y + rhs.y) def __sub__(self, rhs): return Vector2(self.x - rhs.x, self.y - rhs.y) def __neg__(self): return Vector2(-self.x , -self.y) def __mul__(self, scalar): return Vector2(self.x * scalar, self.y * scalar) def __div__(self, scalar): return Vector2(self.x / scalar, self.y / scalar)
def is_even(preset_num, ttl_even, ttl_not_even): if preset_num == 0: print(f'A number {preset_num} is made up of {ttl_even + ttl_not_even} ' f'numbers and has {ttl_even} even and {ttl_not_even} odd numbers.') else: tmp = preset_num % 10 if tmp % 2 == 0: ttl_even += 1 else: ttl_not_even += 1 tmp_num = tmp_num // 10 return is_even(tmp_num, ttl_even, ttl_not_even) is_even((input('Enter the number: ')), 0, 0)
try: user_data = int(input('Please enter the year in YYYY format: ')) if user_data % 4 == 0: if user_data % 100 == 0: if user_data % 400 == 0: print('Leap year.') else: print('Not leap year.') else: print('Leap year.') else: print('Not leap year.') except TypeError: print('Unsupported data type. Please, input year. For example: "1984".') except ValueError: print('Incorrect value. Please, input year. For example: "1984".')
""" Не понял ремарку задания "объясните результат", Прикладываю псевдотаблицы с логическими операциями. +-and-+ +--or--+ +-xor-+ |--+--| |--+---| |--+--| |00| 0| |00| 0 | |00| 0| |01| 0| |01| 1 | |01| 1| |10| 0| |10| 1 | |10| 1| |11| 1| |11| 1 | |11| 0| +-----+ +------+ +-----+ 5 и 6 по битам 0101 и 0110 соотвественно. Сдвиг вправо удаляет n бит. Сдвиг влево дописывает n нулей. """ number_a = 5 number_b = 6 or_bit = number_a | number_b xor_bit = number_a ^ number_b and_bit = number_a & number_b print(f'Logical bitwise "AND" result: {bin(and_bit)}') print(f'Logical bitwise "OR" result: {bin(or_bit)}') print(f'Logical bitwise "XOR" result: {bin(xor_bit)}') tmp = number_a << 2 tmp_2 = number_a >> 2 print(tmp, tmp_2)
""" Address: https://leetcode-cn.com/problems/add-two-numbers/ Thinking: 1.链表形式表达没想明白。 猜测本题的关键点可能在满10进1上。涉及到链表的操作(访问和修改) remark.看完题目解析,明白ListNode即是结点,通过next 访问下一结点。重要的是,我们一开始并不需要知道所有元素,只要头结点就可以代表整条链表,同时双链表相加要考虑链表长度问题。 想到递归生成,有两种方式,一种是已经想到的,ListNode(,ListNode) 构造结构时候,这个用while,同时要反序输出,借助cur。 另一种是 addTowNumbers 递归 Test: Review: 链表: 单链表,双链表,循环链表,指针,头结点 ,头插,尾插 """ # Definition for singly-linked list. import math class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: carry = 0 cur = ListNode() head = cur while l1 or l2 or carry: n1, n2 = 0, 0 if l1: n1 = l1.val l1 = l1.next if l2: n2 = l2.val l2 = l2.next cur.next = ListNode((n1 + n2 + carry) % 10) cur = cur.next carry = math.floor((n1 + n2 + carry) / 10) print(n1 + n2 + carry) return head.next class Solution2: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None and l2 is None: return None if l1 is None: l1 = ListNode(0, None) if l2 is None: l2 = ListNode(0, None) if l1.val + l2.val > 9: node = l1.next if l1.next else l2.next if node: node.val = node.val + 1 else: l1.next = ListNode(1, None) return ListNode((l1.val + l2.val) % 10, self.addTwoNumbers(l1.next, l2.next)) s = Solution() nums = [3, 3] target = 6 # print(s.addTwoNumbers(nums, target))
a = [1, 2, 3, 4, 5, 6] b = a[1:3:2] print(b) lenguajes = [ " Python " , " Java " , " Kotlin " , " Python2 " , " Python3 " , " python -dev " , " Ruby " , " C " , " python " , " php " , "Perl " " PyThoN " , " pytHON " , " pYTHON " , " Pyth@n " ] resultado = filter ( lambda x : x . upper () . startswith ( " PYTHON " ) , lenguajes ) for i in resultado : print ( i )
class Stack(object): def __init__(self): self.data = [] def isEmpty(self): return self.data ==[] def push(self,newElem): self.data.append(newElem) def pop(self): if self.isEmpty(): raise Exception("Your Stack is Empty!") else: return self.data.pop() def peek(self): if self.isEmpty(): raise Exception("Your Stack is Empty!") else: return self.data[-1] def size(self): return len(self.data) class MyQueue(object): def __init__(self): self.pushStack = Stack() self.popStack = Stack() def isEmpty(self): if self.pushStack.isEmpty() and self.popStack.isEmpty(): return True else: return False def push(self,newElem): self.pushStack.push(newElem) def pop(self): while(self.pushStack.isEmpty() != True): self.popStack.push(self.pushStack.pop()) return self.popStack.pop() def peek(self): if self.isEmpty(): raise Exception("Your Queue is Empty!") else: while (self.pushStack.isEmpty() != True): self.popStack.push(self.pushStack.pop()) return self.popStack.peek() if __name__ == "__main__": mq = MyQueue() mq.push(1) mq.push(2) mq.push(3) mq.push(4) print(mq.pop()) print(mq.peek())
import sys # 최고값을 구하는 함수작성 : my_max() def my_max(number): max = sys.float_info.min for value in number: if max < value : max = value return max number =[ ] while True: n = int(input('숫자를 입력하세요:')) if n ==0: break number.append(n) print("최대값 : {0} ".format(my_max(number)))
# Print binary reps # def binary(num): #O(log n) # val = '' # while num: # val = str(num&1)+ val # num = num>>1 # print(val) # def binary(num): # print(bin(13)) # binary(13) #--------Check even/odd------------# # def checkEvenOdd(num): # if num & 1: # print('Odd') # else: # print('Even') # return # checkEvenOdd(178) # Counting set bits # def countSetBits(num): #O(log n) # count = 0 # while num: # if num&1: # count+=1 # num= num>>1 # print(count) #------------------Brian Kernighan' Algo-------------# # subtracting 1 from a number flips all the bits after the rightmost set bit (including it) # eg. # 10 ==> 1010 # 9 ==> 1001 # 8 ==> 1000 # 7 ==> 0111 # Get the last set bits (rightmost) # lastsetbit = n & ~(n-1) # lastsetbit = n&-n (~(n-1) == -(n-1)-1) # Get the first set bit (leftmost) (Most Significant bit) # mask = int(log2(n)) # ans = 1<<mask # def countSetBits(num): #O(log n) # count = 0 # while num: # count+=1 # num = num&num-1 # print(count) # countSetBits(6) #-------Missing number in an array of (1-n)-----------# # def missingNum(arr, n): # val = 0 # for v in arr: # val = val^v # for i in range(1, n+1): # val = val^i # return val #--------------check number is power of 8----------# # from math import log2 # def check(num): # if log2(num)%3==0: # print('Yes {} is power of 8'.format(num)) # else: # print('No {} is not a power of 8'.format(num)) # check(64) # Similary we can do for power of 2, 4, 16, 32 # ---------------Check if number if power of 2-------------------# # If a number if power of 2 then its binary representation there will only be one set bit. # so if (x & x-1)==0 that means number is power of 2. #--------------check number is multiple of 3-------------# # Every pow(2, x) can be represent by multiple of 3k+1 or 3k-1. # 3k+1 for even places and 3k-1 for odd places. # so, abs(evensetbits - oddsetbits)%3 decide number is divisible by 3 or not. # def check(num): # evensetbits = 0 # oddsetbits = 0 # bn = bin(num) # bn = bn.split('b')[1] # for i in range(len(bn)): # if i%2==0 and bn[i]=='1': # evensetbits+=1 # if i%2!=0 and bn[i]=='1': # oddsetbits+=1 # if abs(evensetbits-oddsetbits)%3==0: # return True # else: # return False
# https://www.youtube.com/watch?v=IEEhzQoKtQU&pbjreload=10 # Threading is different from multi-processing. Threading can speed up our script when it's IO bound, while # multiprocessing can speed up when its CPU bound. Even threading can slow down our processing speed because it has # an extra overhead of creating and destroying the thread. So one should know when to use one or another. # Using threading module. import threading t1 = threading.Thread(target = some_function, args = []) t1.start() # to start t1 thread concurrently with our main thread. t1.join() # wait our main thread to complete t1 thread and join it back to main thread. from threading import Event e = Event() e.wait() # It will wait our current thread to wait till the event e is not set. e.set() # It will set the event e. e.clear() # It will unset the event e. #---------------------------------------------------------------------------------------------------------# # Using thread pool executors (concurrent.futures) # We dont have to join our threads as this executor automatically waits for our thread to complete. import concurrent.futures with concurrent.futures.ThreadPoolExecutor() as executor: # It Will wait till all threads complete execution. f1 = executor.submit(some_function, arg1, arg2, ...) # It will return a future object. print(f1.result()) # return value of some_function. fobjects = [executor.submit(some_function) for _ in range(10)] for f in concurrent.futures.as_completed(fobjects): print(f.result()) print('Done') # It will print after all the threads gets completed.
# To fix imbalance we perform rotations. # T1, T2 and T3 are subtrees of the tree rooted with y # (on left side) or x (on right side) # y x # / \ Right Rotation / \ # x T3 – – – – – – – > T1 y # / \ < - - - - - - - / \ # T1 T2 Left Rotation T2 T3 class Node: from random import randint def __init__(self, key): self.key = key self.left = None self.right = None self.p = randint(0, 100) class Treap: def __init__(self): self.root = None def leftRotate(self, x): y = x.right t2 = y.left y.left = x x.right = t2 return y def rightRotate(self, y): x = y.left t2 = x.right x.right = y y.left = t2 return x def _insert(self, root, key): if not root: return Node(key) if key<=root.key: root.left = self._insert(root.left, key) if root.left.p > root.p: root = self.rightRotate(root) else: root.right = self._insert(root.right, key) if root.right.p>root.p: root = self.leftRotate(root) return root def _delete(self, root, key): if root==None: return root if key<root.key: root.left = self._delete(root.left, key) elif key>root.key: root.right = self._delete(root.right, key) elif root.left == None: temp = root.right del root root = temp elif root.right == None: temp = root.left del root root = temp elif root.left.p<root.right.p: root = self.leftRotate(root) root.left = self._delete(root.left, key) else: root = self.rightRotate(root) root.right = self._delete(root.right, key) return root def insert(self, key): self.root = self._insert(self.root, key) def delete(self, key): self.root = self._delete(self.root, key) treap = Treap() treap.insert(1) treap.insert(2) treap.insert(4) treap.insert(3) treap.insert(9) treap.insert(6) treap.delete(4)
__author__ = 'noomatik' from datetime import datetime YEAR = datetime.now().year name = input("What is your name? ") birth = input("What is your year of birth? ") age = YEAR - int(birth) print("Hello %s! You are about %s years old." % (name, str(age)))
''' Graphs module: 1. Graph calculator 2. By : Sina Honarvar ''' from collections import deque from matrix import Matrix #_________________________________________________ ''' def is_simple_graph(adj_matrix): 'Returns True if the given matrix can be adjacency matrix of a simple graph' mat = adj_matrix.matrix for i in range(len(mat)): if mat[i][i] == 1: return False for j in range(i+1,len(mat)): if mat[i][j] not in {0,1} or mat[i][j] != mat[j][i]: return False return True ''' #_________________________________________________ def havel(series): 'returns degree list of vertices after perofrming Havel alghorithm' delta = series.pop(0) for i in range(delta): series[i] -= 1 return series #_________________________________________________ class Graph: ''' simple tool for graph theory calculations ''' #_________________________________________________ def __init__(self, graph): ''' Base constructor for Graph class We assume that given matrix belongs to a simple graph ''' assert len(graph.matrix) == len(graph.matrix[0]), (print("Input data is not a square matrix")) if not isinstance(graph, Matrix) and isinstance(graph , list): graph = Matrix (graph) self.graph = graph elif isinstance(graph, Matrix): self.graph = graph else: assert 0 , print("input data is not list or matrix") self.max_deg = max(self.series()) self.min_deg = min(self.series()) self.q = sum(self.series())//2 #_________________________________________________ def series(self): 'Retruns the series of vertices degree in a descending sort' return [(self.graph * self.graph)[i][i] for i in range(len(self.graph.matrix))] #_________________________________________________ def distance(self, v, t): 'Returns distance between two vertices' q = deque([v]) d = [-1] * len(self.graph.matrix) d[v] = 0 while q: u = q.popleft() for i in range(len(self.graph.matrix)): if self.graph.matrix[u][i] and d[i] == -1: d[i] = d[u] + 1 q.append(i) return d[t] #_________________________________________________
#integer n1=5 print(str(n1) + " is type of " + str(type(n1))) #float n2=5.5 print(str(n2) + " is type of " + str(type(n2))) #lists mixed=[] print(type(mixed)) mixed=[2,5.5,'a','b',"uber"] print(type(mixed)) print(mixed) print(mixed[0]) print("length of list is" + str(len(mixed))) #tuple nochange=() print(type(nochange)) nochange=(2,2.5,'a','b',"asd") print(nochange) print(nochange[0]) #below stmt is illegal for tuple #nochange[0]=4 #strings location="chennai" multiline= ''' "hello" +" how "+ "are " +"you" ''' print("location:"+ str(type(location))) print(len(location)) print(location[0]) print(multiline) #sets noorder={25,35,45,65} print(type(noorder)) print(noorder) #print(noorder[0]) #dictionary keyvalue={} print(type(keyvalue)) keyvalue={ 1:"kalyani","tech":"python", 4:8,9:"ML"} print(keyvalue[1]) print(keyvalue["tech"]) print(keyvalue[4]) print(keyvalue[9]) #type conversion n2=5 print(type(n2)) n3=float(n2) print(type(n3)) n4=str(n3) print(type(n4)) #input score1=input("Input Score 1:") score2=input("Input Score 2:") print("Score is :" +score1+score2) print("########################") score1=int(input("Input Score 1:")) score2=int(input("Input Score 2:")) print("Score is : " +str(score1+score2)) print("Score is ",score1)
#lists mixed=[2,4,8,"kalyani",88.88,1,43,"venky",'l'] print(mixed[4]) print(id(mixed)) #:operator print(mixed[3:8]) #Sclice from 3rd index position to (8-1)th position newslice=mixed[3:8] print(type(newslice)) #slice from negative direction backslice=mixed[-4:-1] print(backslice) backslice1=mixed[-5:] backslice2=mixed[-5::1] print(backslice1) print(backslice2) #iterating through the list! for item in mixed: print(item) providers={"uber","ola","zoom","ridzer","didi"} firstproviders=[provider[0] for provider in providers] print(firstproviders) lengthofEachItem=[len(provider) for provider in providers] print(lengthofEachItem) print("uber" in providers) print('l' in "kalyani") # add items to list getx=[x+y for x in 'abc' for y in 'def'] print(getx) #creating 2 dimensional list print("abc" * 4) clone=[4]*3 print(clone) ''' [4,4,4], [4,4,4], [4,4,4] ''' clone2=[[4]*3]*3 print(clone2) #list additions friends1=["oma","oka","chia"] friends2=["pic","Din","aaa"] friends3=friends1+friends2 print(friends3) print(mixed) print(mixed[0: 7: 3]) mixed.insert(0,55) print(mixed) check=mixed.pop(0) print(str(check) + " popped of " + str(mixed)) print(mixed) print(mixed.pop()) #delete last element #create 2 dimensional list using for ''' [4]*3 ->range(0,2) ''' twodimension=[[4]*3 for a in range(0,3)] print(twodimension) twodimension1=[[a]*3 for a in range(0,3)] print(twodimension1) twodimension2=[[a*a]*3 for a in range(0,3)] print(twodimension2) twodimension2=[[a**(a+1)]*3 for a in range(0,3)] print(twodimension2)
'''for loops''' vowel="aeiou" for v in vowel: print(v) numbers=[1,2,3,4,5,6,7,8,9,0] total=0 for n in numbers: #total =total+n print("sum of all list from 1 to 10 ", total) #using from loop with range for n in range(1,5): print(n,end=" ") print() for n in range(1,10,2): print(n, end=" ") #in below case else will not execute as loop is breaking in between for n in numbers: print(n**n) if(n==7): break else: print("Exponent for all numbers is done")
""" This module is used to read the configurations from the various configurations files and generates the flat dictionaries for the same """ from Modules.file_type_mappings import FILE_TYPE_MAPPINGS class ReadModule: def read_file(self,file_name): """ Used to read the configuration file params : file_name : Name of the file : str Returns flattened dictionary """ fp = open(file_name,'r') file_content = fp.readlines() file_content.reverse() file_type = file_name.split('.')[-1] return self.get_config_file(file_content,file_type) def get_config_file(self,file_content,file_type): """ Used to read the configurations and creates a dictionary for the same Params: file_content : List of configurations from the config files : list file_type : Type of the file(yaml/conf/cfg) : str Returns Configuration Dictionary """ config_dict = {} sub_dict = {} list_of_values = [] for line in file_content: if not (line.startswith('#') or line.startswith('\n') or line.startswith('---') or line.startswith('...')): configuration = line.replace('\n','').split(FILE_TYPE_MAPPINGS[file_type]) if len(configuration) > 1: if configuration[0] in sub_dict: sub_dict[configuration[0]].append(configuration[1]) else: sub_dict[configuration[0]] = configuration[1] elif len(configuration) == 1: if configuration[0].startswith(' - '): list_of_values.append(configuration[0].replace(' - ','').strip()) elif list_of_values != []: sub_dict[configuration[0]] = list_of_values list_of_values = [] else: configuration = configuration[0].replace('[','').replace(']','').strip() config_dict[configuration] = sub_dict sub_dict = {} else: pass if sub_dict != {}: config_dict.update(sub_dict) print(config_dict) return config_dict
import random # importing random to generate random numbers later ques = {} # a dictionary to hold questions (key: an integer, value: question) ans = {} # a dictionary to hold answers (key: an integer, value: answer) def loadQuiz(): """ This function loads the quiz's data (i.e, questions and answers) from a file and then puts to dictionaries with key as a serial numbers ( integers) and the question as value and same key as answer's keys and value as the answers. :return: updates the dictionaries """ print("Loading from file") filename = "quizData1.txt" file = open(filename) mainKey = 0 # initializing key integer next(file) # skipping first line for line in file: # going through each line and updating dictionaries line.strip() lineList = line.split() anEmpty = "" if lineList[0] is not "-": mainKey += 1 # updating key (integer) ques[mainKey] = anEmpty # first item in the list is ignored, example: "1." for i in range(1, len(lineList)): ques[mainKey] = ques[mainKey] + lineList[i] + " " else: ans[mainKey] = anEmpty # first item in the list is ignored, which is "-" if len(lineList) > 2: # if answer is more than one word for i in range(1, len(lineList)): ans[mainKey] += lineList[i] + " " else: # if answer is just one word ans[mainKey] = lineList[1] def check(user_answer, qu, count, correct): """ Checks if the given answer matches with the correct one. Recursive if wrong answer is given. After 3 wrong answers, the correct answer is revealed. :param user_answer: user's input answer :param qu: key or question number :param count: count of how many times a user inputs an answer :return: count of correct answers """ correct_answer = ans[qu].strip().lower() count += 1 if len(user_answer) is len(correct_answer) and user_answer in \ correct_answer: correct += 1 print("Correct answer\n") else: if (count is 3): # correct answer revealed after 3 wrong answers print("Thanks for trying, correct answer is " + correct_answer + "\n") return user_answer = input("Wrong answer, try again: ") while len(user_answer) is 0: # making sure user gives an answer not just an empty lin (an ENTER) user_answer = input("Enter answer: ") check(user_answer, qu, count, correct) return correct def doTheQuiz(totalQuestions, num_questions): """ The function that does the quiz taking in: :param totalQuestions: the total questions number :param num_questions: the number of questions user wants :return: number (count) of correct answers """ #making sure user gives a number greater than 0 and less than total questions while (num_questions > totalQuestions or num_questions <= 0): num_questions = int(input("Enter how many questions? ")) # a list holding randomly generated numbers num_random = random.sample(range(1, totalQuestions+1), num_questions) correct = 0 #print(num_random) for qu in num_random: # doing action as per the generated random numbers user_answer = input(ques[qu] + "\nAnswer: ") while len(user_answer) is 0: # making sure user gives an answer not just an empty lin (an ENTER) user_answer = input("Enter answer: ") tryCount = 0 correct = check(user_answer, qu, tryCount, correct) return correct def assignGrade(percent): """ Assigning grade as per the percent scored for correct answers. :param percent: percentage of correct answers out of total asked questions :return: a grade (string) """ if percent >= 90: return "A" elif percent >= 80: return "B" elif percent >= 70: return "C" elif percent >= 60: return "D" else: return "F" def main(): """ Main function that shows user the question according to the randomly generated keys (integers) and takes user's inputs and checks the answers. :return: """ print ("Let's play Quiz!!") loadQuiz() #loading quiz totalQuestions = len(ques) num_questions = int(input("How many questions? (less than " + str( totalQuestions) + "): ")) correct = doTheQuiz(totalQuestions, num_questions) # calculating score percentage percent = correct/num_questions * 100 # printing the result print("You scored: " + str(percent) + " with grade: " + assignGrade( percent)) if __name__ == '__main__': main() print("Done!")
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # 这是原始Python代码,看不懂js版本的可以参考 import tkinter as tk # 导入 Tkinter 库 import math import random class Pair(): # 数据组 def __init__(self, x, y): self.x = x self.y = y def __lt__(self, b): if isinstance(b, Pair): return self.x < b.x else: return NotImplemented class Group(Pair): # 浮点数据组类 def __init__(self, x, y): super().__init__(x, y) self.x = float(self.x) self.y = float(self.y) def __add__(self, b): if isinstance(b, Group): return type(self)(self.x + b.x, self.y + b.y) else: return NotImplemented def __sub__(self, b): if isinstance(b, Group): return type(self)(self.x - b.x, self.y - b.y) else: return NotImplemented def mod(self): return math.sqrt(self.x*self.x+self.y*self.y) def __lt__(self, b): if isinstance(b, Group): return self.x < b.x else: return NotImplemented class Vect(Group): # 向量 子类 def __init__(self, x, y): super().__init__(x, y) def __mul__(self, b): if isinstance(b, Group): return self.x*b.x+self.y*b.y else: return type(self)(self.x * b, self.y * b) def __rmul__(self, a): return type(self)(self.x * a, self.y * a) class Pos(Group): # 坐标 子类 def __init__(self, x, y): super().__init__(x, y) class Vel(Vect): # 速度 子类 def __init__(self, x, y): super().__init__(x, y) class Ball(): def __init__(self, ID, pos, r=10, v = Vel(0,0), m = 50000, fill = "", locked = False): self.ID=ID self.pos=pos self.r=r self.v=v self.m=m self.fill = fill self.locked=locked def moveto(self, pos): self.pos=pos def move(self): self.pos += self.v class Timer(): # 计时器 def __init__(self, root, func, time, enabled): self.rt = root self.func = func self.t=int(time) self.enabled=enabled if enabled: self.enable() def timeup(self): self.func() self.ti = self.rt.after(self.t, self.timeup) def enable(self): self.enabled = True self.timeup() def unable(self): self.enabled = False self.rt.after_cancel(self.ti) def reset_time(self, t): self.unable() self.t=int(t) self.enable() class ID_Pool(): # ID池 def __init__(self): self.pool=[] self.topid=0 def getid(self): if len(self.pool) == 0: self.topid+=1 return self.topid else: return self.pool.pop() def back(self, p): self.pool.append(p) Balls = [] id_pool = ID_Pool() FPS = 60 DeadTime = 1e9 CountNum = 0 def draw_ball(ball): if ball.fill != "": cv.create_oval(ball.pos.x - ball.r, ball.pos.y - ball.r, ball.pos.x + ball.r, ball.pos.y + ball.r, fill = ball.fill) else: cv.create_oval(ball.pos.x - ball.r, ball.pos.y - ball.r, ball.pos.x + ball.r, ball.pos.y + ball.r) def creat_ball(p, r=3, v=Vel(0,0), m=500, fill = "", locked = False): ball_t = Ball(id_pool.getid(), p, r, v, m, fill, locked) Balls.append(ball_t) draw_ball(ball_t) def del_ball(ball): Balls.remove(ball) def update(cv): #更新整个画布 cv.delete("all") for ball in Balls: draw_ball(ball) def solvefunc(a, b, c): delta = math.sqrt(b*b-4*a*c) return [(-b+delta)/(2*a), (-b-delta)/(2*a)] def force(b1, b2): plus = -1 x = b1.pos.x - b2.pos.x y = b1.pos.y - b2.pos.y dis = x*x + y*y if dis == 0: return if math.sqrt(dis) < b1.r + b2.r : plus = (b1.r + b2.r) / math.sqrt(dis) dis = (b1.r + b2.r) ** 2 f = 0.05 * b1.m * b2.m / dis fx = f / math.sqrt(dis) * x fy = f / math.sqrt(dis) * y return Vect(fx * plus, fy * plus) def hit(b1, b2): # 碰撞计算 global CountNum CountNum += 100 dv = b1.v-b2.v if dv.mod()==0: return if hited(b1,b2) == False: return dp = b2.pos-b1.pos dt=0 if dp.mod() < b1.r+b2.r: #print("dis = ", dp.mod(), "dv=", dv.x,",",dv.y) a = dv.x**2 + dv.y**2 b = -2 * (dv.x * dp.x + dv.y * dp.y) c = dp.x**2 + dp.y**2 - (b1.r+b2.r) **2 dt = solvefunc(a, b, c)[1] b1.pos += dt * b1.v b2.pos += dt * b2.v #print("dt=", dt) # 球恢复到“碰撞瞬间” b1.v-=b2.v dp = b2.pos-b1.pos alpha = 0 #print("now dis = ", dp.mod(), "dv=", dv.x,",",dv.y) if dp.x == 0: if dp.y > 0: alpha = math.asin(1) else: alpha = math.asin(-1) else: alpha = math.atan(dp.y/dp.x) v0 = b1.v * Vel(math.cos(alpha), math.sin(alpha)) v0c = b1.v - (v0 * Vel(math.cos(alpha), math.sin(alpha))) #print("v0=" , v0, "vel=", Vel(math.cos(alpha), math.sin(alpha)).x, Vel(math.cos(alpha), math.sin(alpha)).y) b1.v=b2.v b2.v += float((2*b1.m)/(b1.m+b2.m)) * (v0 * Vel(math.cos(alpha), math.sin(alpha))) b1.v += float((b1.m-b2.m)/(b1.m+b2.m)) * (v0 * Vel(math.cos(alpha), math.sin(alpha))) + v0c # 球弹开 dt = -dt b1.pos += dt * b1.v b2.pos += dt * b2.v #弹性系数 #b1.v=b1.v*0.9 #b2.v=b2.v*0.9 def hited(b1, b2): # 是否碰撞 return (b1.v-b2.v).mod() != 0 and dis(b1.pos, b2.pos) <= b1.r + b2.r - 0.00001 def count_hit(): global CountNum stp = len(Balls) hits = [] for i in range(0, stp - 1): for j in range(i + 1, stp): CountNum += 2 if hited(Balls[i], Balls[j]): hits.append(Pair(Balls[i].r + Balls[j].r - dis(Balls[i].pos, Balls[j].pos), [Balls[i], Balls[j]])) hits.sort() #if len(hits): # print(str(len(hits))) return hits def dis(p1, p2): return (p1-p2).mod() def move(): # 初次计算 energy=0 for ball in Balls: energy+=ball.v*ball.v*ball.m global CountNum CountNum += 1 # ball.v.y+=1 ball.move() if ball.pos.x <= 0: ball.v.x *= -1 ball.pos.x = 1 if ball.pos.x >= WIDTH: ball.v.x *= -1 ball.pos.x = WIDTH - 1 if ball.pos.y <= 0: ball.v.y *= -1 ball.pos.y = 1 if ball.pos.y >= HEIGHT: ball.v.y *= -1 ball.pos.y = HEIGHT - 1 #print(energy) def main_loop(): # 主循环 global CountNum CountNum = 0 move() while CountNum < DeadTime: hitlist = count_hit() if len(hitlist) == 0: break for hits in hitlist: hit((hits.y)[0], (hits.y)[1]) for ball in Balls: for oth in Balls: if ball.ID != oth.ID: ball.v += 1/ball.m * force(ball, oth) update(cv) def mouse_press(event): global mouseball mouseball = creat_ball(Pos(event.x,event.y), 20, Vel(0,0), 50000, fill = "yellow") def mouse_up(event): global mouseball del_ball(mouseball) def cmd_click(): if timer.enabled: timer.unable() else: timer.enable() WIDTH = 500 HEIGHT = 500 root = tk.Tk() root.title("Test") root.geometry('630x520') timer = Timer(root, main_loop, 1000/FPS, False) cv = tk.Canvas(root, bg='skyblue', height=HEIGHT, width=WIDTH) cmd = tk.Button(root, text="Start move!", width=int(100/7), height=int(20/17), command=cmd_click) #tst = tk.Button(root, text="Kill Velocity", width=15, height=2, command=stopall) #for i in [60*x for x in range(1,2)]: # for j in [60*x for x in range(int(i/60),9)]: # creat_ball(Pos(i,j), 20, Vel(0,0), fill = "red") # creat_ball(Pos(200,230), 20, Vel(0,6), 500000, fill = "blue") # creat_ball(Pos(300,270), 20, Vel(0,-6), 5000, fill = "red") cv.bind("<ButtonRelease-1>", mouse_press) cv.bind("<Double-Button-1>", mouse_up) cv.place(x=5, y=5) cmd.place(x=505 + 10, y=5) #tst.place(x=505 + 10, y=55) root.mainloop()
def column_to_list(df, col_name): return [x[col_name] for x in df.select(col_name).collect()] def two_columns_to_dictionary(df, key_col_name, value_col_name): k, v = key_col_name, value_col_name return {x[k]: x[v] for x in df.select(k, v).collect()} def to_list_of_dictionaries(df): return list(map(lambda r: r.asDict(), df.collect()))
import numpy as np def find_closest_centroids(X, centroids): """ Computes the centroid memberships for every example. Parameters ---------- X : ndarray, shape (n_samples, n_features) Samples, where n_samples is the number of samples and n_features is the number of features. centroids : ndarray, shape (K, n_features) The current centroids, where K is the number of centroids. Returns ------- idx : ndarray, shape (n_samples, 1) Centroid assignments. idx[i] contains the index of the centroid closest to sample i. """ m = X.shape[0] idx = np.zeros(m) for i in range(m): dist = np.sum(np.square(centroids - X[i, :]), axis=1) idx[i] = np.argmin(dist) return idx
import numpy as np def select_threshold(y_val, p_val): """ Find the best threshold (epsilon) to use for selecting outliers. Parameters ---------- y_val : ndarray, shape (n_samples,) Labels from validation set, where n_samples is the number of samples and n_features is the number of features. p_val : ndarray, shape (n_samples,) The probability density from validation set. Returns ------- best_epsilon : numpy.float64 The best threshold for selecting outliers. best_F1 : numpy.float64 The best F1 score. """ step_size = (np.max(p_val) - np.min(p_val)) / 1000 best_epsilon = 0.0 best_F1 = 0.0 for epsilon in np.arange(min(p_val), max(p_val), step_size): predictions = p_val < epsilon tp = np.sum(predictions[np.nonzero(y_val == True)]) fp = np.sum(predictions[np.nonzero(y_val == False)]) fn = np.sum(y_val[np.nonzero(predictions == False)] == True) if tp != 0: prec = 1.0 * tp / (tp + fp) rec = 1.0 * tp / (tp + fn) F1 = 2.0 * prec * rec / (prec + rec) if F1 > best_F1: best_F1 = F1 best_epsilon = epsilon return best_epsilon, best_F1
import numpy as np def feature_normalize(X): """ Normalizes the features in X. Parameters ---------- X : ndarray, shape (n_samples, n_features) Samples, where n_samples is the number of samples and n_features is the number of features. Returns ------- X_norm : ndarray, shape (n_samples, n_features) Normalized training vectors. mu : ndarray, shape (n_feature, ) Mean value of each feature. sigma : ndarray, shape (n_feature, ) Standard deviation of each feature. """ mu = np.mean(X, axis=0) sigma = np.std(X, axis=0, ddof=1) X_norm = (X - mu) / sigma return X_norm, mu, sigma
import numpy as np import matplotlib.pyplot as plt from poly_features import poly_features from feature_normalize import feature_normalize def plot_fit(min_x, max_x, mu, sigma, theta, p): """ Plots a learned polynomial regression fit over an existing figure. Parameters ---------- min_x : float Minimum value of features. max_x : float Maximum value of features. mu : ndarray, shape (n_features - 1,) Mean value of features, without the intercept term. sigma : ndarray, shape (n_features - 1,) Standard deviation of features, without the intercept term. theta : ndarray, shape (n_features,) Linear regression parameter. p : int Power of polynomial fit. """ x = np.arange(min_x - 15, max_x + 25, 0.05) X_poly = poly_features(x, p) X_poly, dummy_mu, dummy_sigma = feature_normalize(X_poly, mu, sigma) X_poly = np.hstack((np.ones((X_poly.shape[0], 1)), X_poly)) plt.plot(x, X_poly.dot(theta), linestyle='--', marker='', color='b')
import matplotlib.pyplot as plt from plot_data_points import plot_data_points from draw_line import draw_line def plot_progress_k_means(X, history_centroids, idx, K, i): """ Helper function that displays the progress of k-Means as it is running. It is intended for use only with 2D data. Parameters ---------- X : ndarray, shape (n_samples, n_features) Samples, where n_samples is the number of samples and n_features is the number of features. history_centroids : ndarray, shape (n_max_iters, K, n_features) The history of centroids assignment. idx : ndarray, shape (n_samples, 1) Centroid assignments. K : int The number of centroids. i : int Current iteration count. """ plot_data_points(X, idx, K) plt.plot(history_centroids[0:i+1, :, 0], history_centroids[0:i+1, :, 1], linestyle='', marker='x', markersize=10, linewidth=3, color='k') plt.title('Iteration number {}'.format(i + 1)) for centroid_idx in range(history_centroids.shape[1]): for iter_idx in range(i): draw_line(history_centroids[iter_idx, centroid_idx, :], history_centroids[iter_idx + 1, centroid_idx, :])
import numpy as np def pca(X): """ Run principal component analysis on the dataset X. Parameters ---------- X : ndarray, shape (n_samples, n_features) Samples, where n_samples is the number of samples and n_features is the number of features. Returns ------- U : ndarray, shape (n_features, n_features) Unitary matrices. S : ndarray, shape (n_features,) The singular values for every matrix. V : ndarray, shape (n_features, n_features) Unitary matrices. """ m, n = X.shape sigma = X.T.dot(X) / m U, S, V = np.linalg.svd(sigma) return U, S, V
#!/usr/bin/env python3 imie = input("Podaj imie ") nazwisko = input("Podaj nazwisko? ") wiek = input("Podaj wiek? ") print("Imie "+imie) print("Nazwisko "+nazwisko) print("wiek " + wiek)
#! /usr/bin/env python ''' A program which takes in an input file of json log entries and counts the number of unique occurances of each extension type. By: Robin Verleun ''' import sys import argparse import json import re from collections import defaultdict from validator import Validator def get_cli_input(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('input', help='path to the input file', metavar='INPUT_FILE') parser.add_argument('-v', '--verbose', dest='verbose', help='output line errors', action='store_true') args = parser.parse_args() return args def print_result(extensions): ''' Takes in a dictionary and print the key with the size of the corresponding set. ''' for key, value in extensions.items(): print('{0}: {1}'.format(key, len(value))) def main(): args = get_cli_input() # try:except block to catch file open errors. try: with open(args.input, 'r') as file: extension_set = defaultdict(set) line_validator = Validator(args.verbose) # loop over the values, attempting to validate. for linenum, line in enumerate(file, start=1): try: json_file = json.loads(line) result = line_validator(json.loads(line), linenum) if result is None: continue extension_set[result.ext].add(result.name) except Exception as e: print('Issue loading line {0}: {1}'.format(linenum, e)) print_result(extension_set) except Exception as e: print('Error', e) # Execute main function if __name__ == "__main__": main()
import collections # 从序列中随机抽取一个元素 from random import choice # namedtuple是继承自tuple的子类。 # namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性。 # 这对象更像带有数据属性的类,不过数据属性是只读的 # 创建card类型,带属性rank,suit Card = collections.namedtuple('Card', ['rank', 'suit']) class FrenchDeck: ranks = [str(n) for n in range(2, 11)] + list('JQKA') #print(ranks) suits = 'spades diamonds clubs hearts'.split() def __init__(self): self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks] def __len__(self): return len(self._cards) def __getitem__(self, position): return self._cards[position] beer_card = Card('7', 'diamonds') deck = FrenchDeck() print(len(deck)) print(beer_card) print(deck[0],deck[-1]) print(choice(deck)) print(deck[0:3]) # 先找到索引是12的位置,然后每隔13取一张 print(deck[12::13]) for card in deck: print(card) # 反向迭代 for card in reversed(deck): print(card) print(Card('Q', 'hearts') in deck) # sort suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0) def spades_high(card): # card.rank返回2,3...A,rank_value返回索引值0-12 rank_value = FrenchDeck.ranks.index(card.rank) #print(len(suit_values)) #len(suit_values)返回列表长度4, #card.suit返回spades,hearts,diamonds,clubs # suit_values[card.suit]返回,对应的数值,3,2,1,0 return rank_value * len(suit_values) + suit_values[card.suit] # sorted(a. b)函数,输入a, 以b排序 for card in sorted(deck, key=spades_high): print(card)
""" Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you. Take this opportunity to practice using functions, described below. """ from math import sqrt def check_prime(num): a = int(sqrt(num)) if num != 1: for i in range(2,a+1): if num%i == 0: return 1 else: return 0 else: return 1 num_in = int(input("Enter a number: ")) prime_fl = check_prime(num_in) if prime_fl == 1: print("Not Prime") else: print("It is Prime") """ List Comprehension if sum([ True if a%factor == 0 else False for factor in ( [2] + list(range(3,int(math.sqrt(a)),2) )) ]): print("Number is composite") else: print("Number is prime") """
""" Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. Extras: 1. Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. 2. Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button) """ from datetime import datetime name = input("Your name: ") age = int(input("Your age: ")) c_month = datetime.now().strftime('%B') q_str = "Did you born in or before " + c_month + "? (Y/N) " birthday_fl = input(q_str) c_yr = datetime.now().year year2 = abs(c_yr + 100 - age) n = int(input("Enter a num: ")) for i in range(0,n): if birthday_fl.lower() == 'y' and year2 > c_yr: print("You will turn 100 in year:", year2) elif birthday_fl.lower() == 'n' and year2-1 > c_yr: print("You will turn 100 in year:", year2-1) elif age >= 100: print("You already turned 100 in year: ", year2)
import vector import boid import numpy as np import matplotlib.pyplot as plt # This is the main program for running a flocking simulation in python # It uses two objects: a 3D Cartesian vector, and a boid (a birdlike object) # Look inside boid.py and vector.py to see the objects and their methods # Boids follow several simple rules: # ----- # Move towards the centre of mass of the system of boids # Match velocities with the centre of mass of the system # Try not to hit other boids - move away from boids if they come within a certain distance # First, let's define a simple function to get x,y data from our boids def get_coords(boidlist): '''This function strips out x and y data from a list of boid objects for plotting''' x=[] y=[] for i in range(len(boidlist)): x.append(boidlist[i].r.x) y.append(boidlist[i].r.y) return x,y # Now let's get on with the script nboid = int(input("how many boids? ")) tmax=500 # Maximum time for the simulation to run comstrength=0.05 # relative importance of approaching COM vcomstrength = 0.1 # relative importance of matching velocities avoidstrength = 1.0 # relative importance of avoidance avoidrange = 5.0 # Sphere of avoidance radius for boids popn = [] # This list will hold all the boid objects boxsize = 10.0 # This boxsize will determine where the boids are initially placed screensize = 100.0 # This will determine the size of the plotting window dx = boxsize/(nboid) dt = 0.5 flocktwo = vector.Vector3D(20.0, 0.0, 0.0) for j in range(nboid): # set up random positions and velocities r = vector.Vector3D(np.random.rand()*boxsize,np.random.rand()*boxsize,np.random.rand()*boxsize) # Place boids at random in a box v = vector.Vector3D(-2.0 + 4.0*np.random.rand(),-1.0+ 2.0*np.random.rand(),-1.0+2.0*np.random.rand()) # Give them random velocities # create new boid object and add to list d = boid.Boid(j,r,v,v,1.0) popn.append(d) # Extract x and y coords for plotting xplot,yplot = get_coords(popn) fig1 = plt.figure() # This is the figure object ax = fig1.add_subplot(111) # This is the axes of our figure (we can add several to make multiple plots) ax.set_xlim(-screensize, screensize) # x and y limits of the screen ax.set_ylim(-screensize, screensize) scat = ax.scatter(xplot,yplot) # This plots a series of disconnected points (i.e. our boids) plt.show() # Now begin simulation t = 0 obstacle = vector.Vector3D(0.0,-10.0,0.0) flockcounter = 0 while t<tmax: flockcounter+=1 # Calculate centre of mass and COM velocity com = vector.Vector3D(0.0,0.0,0.0) vcom = vector.Vector3D(0.0,0.0,0.0) for j in range(nboid): com = com.add(popn[j].r) vcom = vcom.add(popn[j].v) # Normalise by number of boids com = com.scalarmult(1.0/nboid) vcom = vcom.scalarmult(1.0/nboid) origin = vector.Vector3D(0.0,0.0,0.0) # Apply flocking rules for j in range(nboid): # Constrain boids to approach centre of mass popn[j].approach_COM(com,comstrength) # Boids should attempt to match COM velocity popn[j].match_velocities(vcom,vcomstrength) # Keep boids on screen by attracting them to the origin - this is optional, stops them flying off #popn[j].approach_COM(origin,comstrength) # If neighbours are in avoidance range, boids steer away for k in range(nboid): if j != k: sep=popn[j].r.subtract(popn[k].r) # calculate distance between boids if sep.mag() < avoidrange: # if distance too small, begin avoidance procedure popn[j].avoid_collisions(popn[k].r,0.1) # Avoid VERY SCARY obstacle at (0,5,0) - optional #popn[j].avoid_collisions(obstacle,1.0) # Now move all the boids popn[j].move(dt) # Get coordinates for new population xplot,yplot = get_coords(popn) # plot and save to file ax.clear() # clear previous plot ax.set_xlim(-screensize,screensize) # reset plot limits ax.set_ylim(-screensize,screensize) scat = ax.scatter(xplot,yplot) # Make another scatter plot outputfile='flock_'+str(flockcounter).zfill(4)+'.png' fig1.savefig(outputfile) print outputfile, 'written' # advance time t = t+ dt print "Simulation Ended"
def number(): n = int(input()) sum="" for i in range(1,n+1): sum=sum+str(i) print(int(sum))
# small program to create a simple enigma machine #by Riya Philip alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' class Rotor(): #when all the variables are set to starting position position = 'A' def __init__(self, configuration): self.initial_config = configuration self.connections = configuration self.config1 = dict(zip(alphabet, configuration)) self.config2 = dict(zip(configuration, alphabet)) self.position = 0 self.revolutions = 0 # initial position = self.position def initial_position(self, position): self.position = position def nextStep(self): return True if self.nextStep_position == self.position else False def indent(self): nextStep = self.nextStep() self.position = alphabet[(alphabet.index(self.position) + 1) % 26] if turnover: return True else: return False def rotate(self, steps): self.connections = self.connections[steps:] + self.connections[:steps] self.config1 = dict(zip(alphabet, self.connections)) self.config2 = dict(zip(self.connections, alphabet)) self.position += steps if self.position >= 26: self.revolutions = self.position / 26 #variable self.position = self.position % 26 def reset_rotor(self): self.connections = self.initial_config self.config1 = dict(zip(alphabet, self.initial_config)) self.config2 = dict(zip(self.initial_config, alphabet)) position = 0 revolutions = 0 def encrypt(self, character): return self.config1[character] def decrypt(self, character): return self.config2[character] class Reflector(): def __init__(self, configuration): self.config = dict(zip(alphabet, configuration)) def reflect(self, character): return self.config[character] class Machine(): def __init__(self, rotors=None, reflector=None):#, plug_board=None): self.rotors = rotors self.reflector = reflector #for pair in plug_board: #self.plug_board[pair[0]], self.plug_board[pair[1]] = pair[1], pair[0] def set_rotors(self, positions): if len(positions) != len(self.rotors): print 'Error: rotor settings do not match with number of rotors' else: return def reset(self): for rotor in self.rotors: rotor.reset_rotor() def encipher(self, string): answer = "" for x in string: if x in alphabet: #spaces self.rotors[0].rotate(1) self.rotors[1].rotate(rotors[0].revolutions) #rotate rotor 2 depending on rotation of rotor 1 self.rotors[0].revolutions = 0 self.rotors[2].rotate(rotors[1].revolutions) #rotate rotor 3 depending on rotation of rotor 2 self.rotors[1].revolutions = 0 x = self.rotors[0].encrypt(x) x = self.rotors[1].encrypt(x) x = self.rotors[2].encrypt(x) x = self.reflector.reflect(x) x = self.rotors[2].decrypt(x) x = self.rotors[1].decrypt(x) x = self.rotors[0].decrypt(x) answer += x return answer rotor1 = Rotor('ESOVPZJAYQUIRHXLNFTGKDCMWB') #print rotor1.encrypt("A") #E #rotor1.rotate(3) #print rotor1.encrypt("A") #V #rotor1.rotate(3) #print rotor1.encrypt("B") #A rotor2 = Rotor('AJDKSIRUXBLHWTMCQGZNPYFVOE') rotor3 = Rotor('VZBRGITYUPSDNHLXAWMJQOFECK') rotors=[rotor1, rotor2, rotor3] #'J', 'G'), #'E', 'M'),#'Z', 'Y')] reflector = Reflector('YRUHQSLDPXNGOKMIEBFZCWVJAT') plug_board = [('D', 'N'), ('G', 'R'), ('I', 'S'), ('K', 'C'), ('Q', 'X'), ('T', 'M'), ('P', 'V'), ('H', 'Y'), ('F', 'W'), ('B', 'J')] machine = Machine(rotors, reflector)#, plug_board) print machine.rotors[0].encrypt("A") print machine.encipher("IBOUGHTFLOWERSFROMTHEFLOWERSHOP") print machine.rotors[0].encrypt("A") machine.reset() print machine.rotors[0].encrypt("A") print machine.encipher("YAFBUWZWMBQRXTMQEXHPPSPLLPMJOQA")
from fractions import Fraction x1 = Fraction(150,42) print(x1) print(type(x1), x1.numerator, x1.denominator) x2 = Fraction(264, 64) print(x1+x2)
from pip.backwardcompat import raw_input __author__ = 'Fotty' """ Write a program that prompts a user for their name (first name and family name separately) and then welcomes them. This time, the program should always welcome so that both the first name and the last name begin with a capital letter and the rest of the letters are small, regardless of how the name was entered (only in small letters, in large or mixed). Program should compute initials from entered full name and display them. Also a program should find and print out the number of vowels (letters A, E, I, O, U) in the name (in both, first and family, names). Enter first name: mAriNa Enter family name: lePp Hello Marina Lepp Your initials are M L The number of vowels in your name is 4 """ first_name = str(raw_input("Enter you name: ")) last_name = str(raw_input("Enter your last name: ")) rearrange_words = first_name.lower().capitalize() + " " + last_name.lower().capitalize() initials = first_name[0].upper() + last_name[0].upper() vowels = "aeiouAEIUO" summ = 0 for v in vowels: v = rearrange_words.count(v) summ += v print("Hello {0}\nYour initials are {1}\nThe number of vowels in your name is {2}".format(rearrange_words, initials, str(summ))) """ Every University of Tartu user (student or member of staff), which has username for Study Information System, has home directory and can create webpage using university server. The url for his/her webpage would be www.ut.ee/~username/ (for example, www.ut.ee/~vilo/). Write a program that prompts a user for university url, finds and prints out the username. Here is an example of program output. Please enter url: http://www.ut.ee/~koit/KT/index_eng.html Username is koit """ address = raw_input("Please enter url: ") fpos = address.find("~") lpos = address.find("/", fpos) username = address[fpos + 1:lpos] print("Username is", username)
def budget(number_of_people): room = 100 food = 15 min_budget = room + food * (number_of_people - not_sure_if_attending_guests) max_budget = room + (number_of_people * food) return "Minimum budget is: " + str(min_budget) + " EUR" + "\n" + "Maximum budget is: " + str(max_budget) + " EUR" attending_guests = 0 not_sure_if_attending_guests = 0 try: guestsFile = open('guests.txt') for line in guestsFile: guest = line.strip() if "+" in guest: attending_guests += 1 print(guest[2:] + " is attending ") elif "?" in guest: not_sure_if_attending_guests += 1 print(guest[2:] + " doesn't know yet ") print("Number of people attending: " + str(attending_guests)) print("Number of people who don't know yet: " + str(not_sure_if_attending_guests)) num_of_ppl = attending_guests + not_sure_if_attending_guests total = budget(num_of_ppl) print(total) except: print("File doesn't exist")
''' Created on Jun 25, 2018 Author: @G_Sansigolo ''' from statistics import mean import numpy as np import matplotlib.pyplot as plt xs = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64) ys = np.array([5, 4, 6, 5, 6, 7], dtype=np.float64) def best_fit_slope(xs,ys): m = ( ((mean(xs) * mean(ys)) - mean(xs*ys)) / ((mean(xs) *mean(xs)) - mean(xs*xs)) ) return m m = best_fit_slope(xs,ys) print(m)
tw = pd.read_csv('../data/topwords_test.csv', index_col=0) tw.columns = ['word','freq_rej','freq_app'] def minFreq(df,myMin): return df[(df['freq_rej']>myMin) & (df['freq_app']>myMin)] tw = minFreq(tw,0) def distinctiveWords(df,myMin): df2 = minFreq(df,myMin) df2['ratio_rej'] = df2.freq_rej/df2.freq_app df2['ratio_app'] = df2.freq_app/df2.freq_rej df2 = df2.sort(columns='ratio_rej',ascending=False) print "Rejected Words" print df2[:10] print "" print "Approved Words" df2 = df2.sort(columns='ratio_app',ascending=False) print df2[:10] distinctiveWords(tw,100) distinctiveWords(tw,300) distinctiveWords(tw,10)
#!/usr/bin/env python from Tkinter import Frame, Label, OptionMenu, Button, Entry, SUNKEN, LEFT, RIGHT, StringVar, N, W, E, END from ListPane import ListPane from SpellingDatabase import SpellingDatabase import random class CreateView(Frame): """A class describing the list creation page of the UI""" def __init__(self, parent, height, width, border_style, border_width, background_colour): Frame.__init__(self, parent, height=height, width=width) #Connect to the word/list database self.db = SpellingDatabase() self.parent = parent #Create a frame containing a menu for choosing word category categorymenu_frame = Frame(self, width=340, height=30, relief=SUNKEN, bd=1) categorymenu_frame.pack_propagate(0) categorymenu_label = Label(categorymenu_frame, text="Category:") wordlist_title = Label(categorymenu_frame, text="Select Words") #Menu options: one for each category of word optionList = ("Child", "ESOL", "Spelling Bee", "Custom") self.category_v = StringVar() self.category_v.set(optionList[0]) #Command causes word browser to be populated with words from chosen category self.category_menu = OptionMenu(categorymenu_frame, self.category_v, *optionList, command=self.update_category) self.category_menu.config(width=10) self.category_menu.pack(side=RIGHT) categorymenu_label.pack(side=RIGHT) wordlist_title.pack(side=LEFT) #Create frame for the title of the user list panel userlist_title_frame = Frame(self, width=340, height=30) userlist_title_frame.pack_propagate(0) userlist_title = Label(userlist_title_frame, text="Your New List") userlist_title_frame.grid(column=2, row=0) userlist_title.pack(side=LEFT) #Create frame for middle bar containing transfer buttons middlebar_frame = Frame(self, width = 70, height=400) middlebar_frame.grid_propagate(0) #Buttons transfer words from one list to the other transfer_right_button = Button(middlebar_frame, text="->", command=self.transfer_right) transfer_left_button = Button(middlebar_frame, text="<-", command=self.transfer_left) #Press this button to generate a random list from the current category random_list_button = Button(middlebar_frame, text="Create", command=self.random_list) random_list_label = Label(middlebar_frame, text="Random\nList") self.random_list_entry = Entry(middlebar_frame, width=3, justify=RIGHT) self.random_list_entry.insert(0, 15) transfer_left_button.grid(column=0, row=1, padx=15, pady=50) transfer_right_button.grid(column=0, row=0, padx=15, pady=50) random_list_label.grid(column=0, row=2, pady=3) self.random_list_entry.grid(column=0, row=3, pady=3) random_list_button.grid(column=0, row=4, pady=3) middlebar_frame.grid(column=1, row=1) #random_list_button.grid(column=0, row=2) #Create frame for "Add New Word" menu addword_frame = Frame(self, width=340, height=150, bd=2, relief=SUNKEN) addword_frame.grid_propagate(0) addword_label = Label(addword_frame, text = "Add a new word:") word_label = Label(addword_frame, text="Word:") def_label = Label(addword_frame, text="Definition:") use_label = Label(addword_frame, text="Example of Use:") difficulty_label = Label(addword_frame, text="Difficulty:") #Entry boxes and an option menu allowing the user to enter attributes of the new word self.addword_entry = Entry(addword_frame, width = 28) self.adddefinition_entry = Entry(addword_frame, width=28) self.adduse_entry = Entry(addword_frame, width=28) self.difficulty_v = StringVar() self.difficulty_v.set("1") difficulty_list = range(1,9) self.difficulty_menu = OptionMenu(addword_frame, self.difficulty_v, *difficulty_list) #Pressing this button adds the new word to the database addword_button = Button(addword_frame, text = "Add", command = self.add_word) addword_label.grid(row=0, column=0, sticky=W) addword_button.grid(row=0, column=1, pady=2, sticky=E) word_label.grid(row=1, column=0, sticky=W) def_label.grid(row=2, column=0, sticky=W) use_label.grid(row=3, column=0, sticky=W) difficulty_label.grid(row=4, column=0, sticky=W) self.addword_entry.grid(row=1, column=1, pady=2, sticky=E) self.adddefinition_entry.grid(row=2, column=1, pady=2, sticky=E) self.adduse_entry.grid(row=3, column=1, pady=2, sticky=E) self.difficulty_menu.grid(row=4, column=1, pady=2, sticky=E) addword_frame.grid(column=0, row=2) #Frame for menu allowing users to save their new lists savelist_frame = Frame(self, width=340, height=30, bd=2, relief=SUNKEN) savelist_frame.pack_propagate(0) savelist_label = Label(savelist_frame, text="List Name:") #User enters the name of the new list here self.savelist_entry = Entry(savelist_frame, width=25) #Pressing this button adds the new list to the database savelist_button = Button(savelist_frame, text="Save", command = self.save_list) savelist_label.pack(side=LEFT) savelist_button.pack(side=RIGHT) self.savelist_entry.pack(side=RIGHT, padx=5) savelist_frame.grid(column=2, row=2, sticky=N, pady=5) #Create list panel for browsing the words stored in database self.wordbrowse_frame = ListPane(self, height=25) categorymenu_frame.grid(column=0, row=0) self.wordbrowse_frame.grid(column=0, row=1, sticky=N) #Populate the list with words from database self.update_category() #Double-clicking a word has same effect as transfer button self.wordbrowse_frame.doubleClickFunc = self.transfer_right #Create list panel for holding/displaying the list being built self.userlist_frame = ListPane(self, height=25) self.userlist_frame.grid(column=2, row=1, sticky=N) #Double-clicking a word has same effect as transfer button self.userlist_frame.doubleClickFunc = self.transfer_left def transfer_right(self, index=None): """Moves a word from word browser to user list""" if index == None: index = self.wordbrowse_frame.listbox.curselection() if self.wordbrowse_frame.get()!=None: #Add selection to user list self.userlist_frame.insert(self.wordbrowse_frame.get()) #Remove selection from word browser word_list = list(self.wordbrowse_frame.getDisplayed()) word_list.remove(self.wordbrowse_frame.get()) self.wordbrowse_frame.display(word_list) #Ensure current list contents stay visible and select the next word self.wordbrowse_frame.listbox.see(index) self.wordbrowse_frame.listbox.selection_set(index) def transfer_left(self, index=None): """Moves a word from user list back to word browser""" if index == None: index = self.userlist_frame.listbox.curselection() if self.userlist_frame.get()!=None: word_list = list(self.wordbrowse_frame.getDisplayed()) word_list.append(self.userlist_frame.get()) word_list.sort(key=str.lower) self.wordbrowse_frame.display(word_list) word_list = list(self.userlist_frame.getDisplayed()) word_list.remove(self.userlist_frame.get()) self.userlist_frame.display(word_list) self.userlist_frame.listbox.see(index) self.userlist_frame.listbox.select_set(index) def random_list(self): source_list = self.wordbrowse_frame.getDisplayed() list_size = int(self.random_list_entry.get()) if list_size > len(source_list): list_size = len(source_list) self.random_list_entry.delete(0, END) self.random_list_entry.insert(0, list_size) generated_list = random.sample(source_list, list_size) self.userlist_frame.display(generated_list) def update_category(self, event=None): """Populates the word browser with words from the selected category""" category = self.category_v.get() if category == "Child": category = "CL" elif category == "ESOL": category = "AL" elif category == "Spelling Bee": category = "SB" else: category = "UL" word_records = self.db.sql("SELECT word FROM words WHERE difficulty LIKE '%s%s'"%(category, "%")) word_list = [] for word in word_records: word_list.append(str(word[0])) word_list.sort(key=str.lower) self.wordbrowse_frame.display(word_list) def add_word(self): """Adds a new word to the database with the attributes entered by the user""" if self.addword_entry.get() == "": return self.db.sql("INSERT INTO words (word, definition, usage, difficulty) VALUES ('%s', '%s', '%s', 'UL%s')"%(self.addword_entry.get(), self.adddefinition_entry.get(), self.adduse_entry.get(), self.difficulty_v.get())) self.addword_entry.delete(0, END) self.adddefinition_entry.delete(0, END) self.adduse_entry.delete(0, END) #User words are added to a 'Custom' category self.category_v.set("Custom") self.update_category(None) self.db.commit() def save_list(self): """Adds the list contained in the user list panel to the database""" word_list = self.userlist_frame.getDisplayed() self.db.createList(word_list, self.savelist_entry.get()) self.savelist_entry.delete(0, END) self.db.commit() self.parent.parent.update_lists()
def makeParen(k=0, left=0, right=0, str=""): if left + right == k: print str return else: if left < k/2: makeParen(k, left + 1, right, str + "(") if right < left: makeParen(k, left, right + 1, str + ")") def paren(value): return makeParen(value*2, 0, 0, "") print paren(2)
# move 0s to end of array, either in place or out of place def moveZeros(a): indx = 0 for i in xrange(len(a)): if a[i] != 0: a[indx] = a[i] indx += 1 while indx < len(a): a[indx] = 0 indx += 1 return a a = [5, 0, 3, 1, 0, 0, 3, 4, 5, 6] print moveZeros(a)
# 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 addHelper(self, root, v, d, curr_d): if root == None: return if curr_d == d - 1: print root.val node_t_l = TreeNode(v) node_t_l.left = root.left node_t_r = TreeNode(v) node_t_r.right = root.right root.left = node_t_l root.right = node_t_r return self.addHelper(root.left, v, d, curr_d + 1) self.addHelper(root.right, v, d, curr_d + 1) def addOneRow(self, root, v, d): """ :type root: TreeNode :type v: int :type d: int :rtype: TreeNode """ if d == 1: node_t = TreeNode(v) node_t.left = root return node_t self.addHelper(root, v, d, 1) return root
# Hackerrank Language Proficiency Module: Python # Title: Shape and Reshape # Directory: Python > Numpy > Shape and Reshape import math import os import random import re import sys import numpy as np if __name__ == "__main__": arr = np.array(list(map(int, input().split()))) arr.shape = (3, 3) print(arr) arr2 = np.array(list(map(int, input().split()))) print(np.reshape(arr2, (3, 3)))
# Hackerrank Language Proficiency Module: Python # Title: Finding the percentage # Directory: Python > Basic Data Types > Finding the percentage import math import os import random import re import sys if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() avg_scr = 0 score = student_marks.get(query_name) if score is not None: for i in range(0, len(score)): avg_scr += score[i] avg_scr = avg_scr / len(score) print("%.2f" % avg_scr) else: print("Query name does not exist")
__version__ = '1.0' if __name__ == '__main__': while 1: user_number = input("Choose a number: \n") if user_number.isdigit(): user_number = int(user_number) break else: print("{} is not a valid number".format(user_number)) if user_number > 100: print(user_number**2) else: print(user_number**user_number)
# Hackerrank Language Proficiency Module: Python # Title: Print Function # Directory: Python > Introduction > Print Function import math import os import random import re import sys if __name__ == '__main__': n = int(input()) answer_string = '' for i in range(1, n+1): answer_string += str(i) print(answer_string)
# -*- coding: utf-8 -*- """ Created on Sat Sep 18 18:04:30 2021 @author: Gabe Butler """ import random, turtle turtle.colormode(255) # setting up the panel panel = turtle.Screen() w = 1200 h = 400 panel.setup(width=w, height=h) sky = ((random.randint(100,135)), random.randint(180,206), random.randint(200,255)) # sky color panel.bgcolor(sky) # set background color to sky # create turtle that will draw rainbow rainbow = turtle.Turtle() rainbow.speed(0) rainbow.up() ROYGBIV = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] # list that will hold RGB values of ROYGBIV rings = 250 # radius of circles that will create rainbow y = -420 # y position of where rainbow will be drawn x = 280 # x position of where rainbow will be drawn count = 0 # needed to keep track of colors in for loop # create a list of random rainbow colors (most common R, G, and B values that put the color into the correct family) ROYGBIV[0] = random.randint(210,255) # red R ROYGBIV[1] = random.randint(0,100) # red G ROYGBIV[2] = random.randint(0,100) # red B ROYGBIV[3] = 255 # orange R ROYGBIV[4] = random.randint(70,200) # orange G ROYGBIV[5] = random.randint(0,30) # orange B ROYGBIV[6] = random.randint(200,255) # yellow R ROYGBIV[7] = random.randint(200,240) # yellow G ROYGBIV[8] = random.randint(0,100) # yellow B ROYGBIV[9] = random.randint(0,160) # green R ROYGBIV[10] = random.randint(100,255) # green G ROYGBIV[11] = random.randint(0,140) # green B ROYGBIV[12] = random.randint(50,160) # blue R ROYGBIV[13] = random.randint(150,240) # blue G ROYGBIV[14] = random.randint(220,255) # blue B ROYGBIV[15] = random.randint(0,70) # indigo R ROYGBIV[16] = random.randint(0,100) # indigo G ROYGBIV[17] = random.randint(140,255) # indigo B ROYGBIV[18] = random.randint(100,150) # violet R ROYGBIV[19] = random.randint(0,100) # violet G ROYGBIV[20] = random.randint(200,255) # violet B # draw rainbow for colors in range(7): rainbow.color(ROYGBIV[count], ROYGBIV[count+1], ROYGBIV[count+2]) rainbow.up() rainbow.goto(x,y) rainbow.down() rainbow.begin_fill() rainbow.circle(rings) rainbow.end_fill() rings = rings - 20 y = y + 20 count = count + 3 # draw sky colored circle to make rainbow look like a rainbow rainbow.color(sky) rainbow.up() rainbow.goto(x,y) rainbow.down() rainbow.begin_fill() rainbow.circle(rings) rainbow.end_fill() # create turtle that will draw cloud cloud = turtle.Turtle() cloud.color("white") cloud.speed(0) cloud.up() cloud.hideturtle() numberOfClouds = random.randint(0,6) # select random amount of clouds that will appear # draw clouds for clouds in range(0,numberOfClouds): cloud.goto(random.randint(-600,30), random.randint(-150,200)) radius = random.randint(20,50) cloud.down() bump = random.randint(4,7) for bumps in range(0,bump): cloud.begin_fill() cloud.circle(radius) cloud.end_fill() cloud.up() cloud.right(360/bump) cloud.forward(10) cloud.down() cloud.right(90) cloud.forward(40) cloud.left(90) cloud.begin_fill() cloud.circle(25) cloud.end_fill() cloud.up() turtle.done()
#!/usr/bin/env python """Example using transition system dynamics. This example illustrates the use of TuLiP to synthesize a reactive controller for system whose dynamics are described by a discrete transition system. """ # RMM, 20 Jul 2013 # # Note: This code is commented to allow components to be extracted into # the tutorial that is part of the users manual. Comments containing # strings of the form @label@ are used for this purpose. # @import_section@ # Import the packages that we need from __future__ import print_function import logging from tulip import transys, spec, synth, dumpsmach # @import_section_end@ logging.basicConfig(level=logging.WARNING) logging.getLogger('tulip.spec.lexyacc').setLevel(logging.WARNING) logging.getLogger('tulip.synth').setLevel(logging.WARNING) logging.getLogger('tulip.interfaces.omega').setLevel(logging.WARNING) # # System dynamics # # The system is modeled as a discrete transition system in which the # robot can be located anyplace on a 2x3 grid of cells. Transitions # between adjacent cells are allowed, which we model as a transition # system in this example (it would also be possible to do this via a # formula) # # We label the states using the following picture # # +----+----+----+ # | X3 | X4 | X5 | # +----+----+----+ # | X0 | X1 | X2 | # +----+----+----+ # # @system_dynamics_section@ # Create a finite transition system sys_water = transys.FTS() sys_water_vars = set() # Define the states of the system sys_water.states.add_from(['Water100','Water60', 'Water20','Water0']) sys_water.states.initial.add('Water100') # start in state X0 #sys_water.states.initial.add('Water60') #sys_water.states.initial.add('Water20') #sys_water.states.initial.add('Water0') # Define the allowable transitions sys_water.transitions.add_comb({'Water100'}, {'Water60','Water100'}) sys_water.transitions.add_comb({'Water60'}, {'Water100', 'Water20','Water60'}) sys_water.transitions.add_comb({'Water20'}, {'Water100', 'Water0','Water20'}) sys_water.transitions.add_comb({'Water0'}, {'Water100', 'Water0'}) # @system_dynamics_section_end@ # # @environ_section@ env_vars = {'Base','GoalPos','Goal'} env_init = set() # empty set env_prog = {'Base','GoalPos','Goal','!Base','!GoalPos','!Goal'} env_safe = {'Base->!GoalPos','GoalPos->!Base'} # empty set # @environ_section_end@ #sys_vars = #{'X0reach'} # infer the rest from TS sys_init = set()#{'X0reach'} sys_prog = set()#{'home'} # []<>home #sys_safe = {'(X (X0reach) <-> lot) || (X0reach && !park)'} #sys_prog |= {'X0reach'} sys_water_safe = set() # Water control requirements WaterDownSpec = ('((!(loc = "Water0")) && (X(Goal) && X(GoalPos)))&&(!(X(Base)))->(' + '(!(X(loc = "Water100")))&&(X(loc = "Water60")<->(loc = "Water100"))&&(X(loc = "Water20")<->(loc = "Water60"))' + '&&(X(loc = "Water0")<->(loc = "Water20")))') Home_spec = ('(X(Base))->((!(X(loc = "Water0")))&&((X(loc = "Water100")))'+ '&&(!(X(loc = "Water60")))&&(!(X(loc = "Water20"))))') WaterKeepSpec = ('(!(X(Goal) && X(GoalPos)))&&(!(X(Base)))->' + '((X(loc = "Water0")<->(loc = "Water0"))&&' +'(X(loc = "Water100")<->(loc = "Water100"))&&(X(loc = "Water60")<->(loc = "Water60"))&&(X(loc = "Water20")<->(loc = "Water20")))') WaterKeepSpec2 = ('(((loc = "Water0") && (X(Goal) && X(GoalPos)))&&(!(X(Base))))->' + '((X(loc = "Water0")<->(loc = "Water0"))&&' +'(X(loc = "Water100")<->(loc = "Water100"))&&(X(loc = "Water60")<->(loc = "Water60"))&&(X(loc = "Water20")<->(loc = "Water20")))') sys_water_safe |= {WaterDownSpec,Home_spec,WaterKeepSpec,WaterKeepSpec2} # @specs_create_section@ # Create the specification specs = spec.GRSpec(env_vars, sys_water_vars, env_init, sys_init, env_safe, sys_water_safe, env_prog, sys_prog) # @specs_create_section_end@ # # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. # # @synthesize@ # Moore machines # controller reads `env_vars, sys_vars`, but not next `env_vars` values specs.moore = False # synthesizer should find initial system values that satisfy # `env_init /\ sys_init` and work, for every environment variable # initial values that satisfy `env_init`. specs.qinit = '\E \A' ctrl = synth.synthesize(specs, sys=sys_water) assert ctrl is not None, 'unrealizable' # @synthesize_end@ # # Generate a graphical representation of the controller for viewing, # or a textual representation if pydot is missing. # # @plot_print@ if not ctrl.save('discrete.png'): print(ctrl) # @plot_print_end@ Filename = 'WaterControl_controller.py' dumpsmach.write_python_case(Filename,ctrl)
# school类 import pickle import os from . import Course from . import Group from . import Student from . import Teacher class School(object): def __init__(self): self.sname = '' self.saddress = '' self.teacherlist = [] self.courselist = [] self.grouplist = [] self.studentlist = [] return def store(self): fddir = os.path.dirname(os.path.dirname(__file__)) with open('%s\dumpfile\school\%s' % (fddir, self.sname), 'wb') as fd: pickle.dump(self, fd) return def setschool(self): name = input("学校名字:") address = input("学校地址:") self.sname = name self.saddress = address self.store() return self def getteacher(self): print("本校有以下老师:") for t in self.teacherlist: print(t.tname) return def getcourse(self): print("本校开设以下课程:") for c in self.courselist: print(c.cname) return def getgroup(self): print("本校开设以下班级:") for g in self.grouplist: print(g.gname) return def getstudent(self): print("本校有以下学员:") for s in self.studentlist: print(s.sname) return def addteacher(self): print("招募讲师......") name = input("老师姓名:") newteacher = Teacher.Teacher(name) self.teacherlist.append(newteacher) print("%s 老师到岗。" % newteacher.tname) newteacher.store() self.store() return def addcourse(self): print("开设课程......") name = input("课程名称:") price = input("课程价格:") newcourse = Course.Course(name, price) self.courselist.append(newcourse) print("%s 课程开设完毕。" % newcourse.cname) newcourse.store() self.store() return def addgroup(self): print("开设班级......") csname = input("课程名字:") name = input("班级名字:") maxnum = input("班级最多人数:") teachername = input("带班老师:") fddir = os.path.dirname(os.path.dirname(__file__)) with open('%s\dumpfile\\teacher\%s' % (fddir, teachername), 'rb') as fd: teacherobj = pickle.load(fd) cnamelist = [] for c in self.courselist: cnamelist.append(c.cname) if csname in cnamelist: tnamelist = [] for t in self.teacherlist: tnamelist.append(t.tname) if teachername in tnamelist: newgroup = Group.Group(name, maxnum, teachername) self.grouplist.append(newgroup) newgroup.store() teacherobj.grouplist.append(newgroup) teacherobj.store() else: print("没有你要的带班老师,班级开设失败。") else: print("本校没有你输入的课程,班级开设失败") self.store() return
import random print ("Hello warrior. Enter your name and face death standing proud") name = input(str) secretNumber= random.randint(1,99) print ("HAHAHA," + name + ", i am hiding somewhere between 1 and 99! TRY AND FIND ME BEFORE I KILL YOUR ENTIRE VILAGE") for guessesTaken in range(1, 20): print ("Roll the D20 until you hit that fatal 1") guess = int(input()) if guess < secretNumber: print ("YOU SWUNG TOO LOW!") print ("I SHALL ATTACK YOUR TZONE!") elif guess > secretNumber: print ("YOU SWING TOO HIGH!") print ("YOUR LEGS ARE MINE, " + name) else: break #unless the answer is divisible by zero!! if guess == secretNumber: print ("GAH! I AM SLAIN! FOUL HERO I SHALL RISE AGAIN!") else: print ("FOOL I HAVE WON!") print ("DARE YOU CHALLENGE ME AGAIN IN THE NEXT LIFE?")
import tkinter as tk from tkinter import N, S, E, W, END, Button class EditView(tk.Toplevel): def __init__(self, master): tk.Toplevel.__init__(self, master) self.master = master self.protocol('WM_DELETE_WINDOW', self.withdraw) self.title('Input data') self.__text_area = tk.Text(self, height=10, width=30) self.__text_area.focus_set() self.__text_area.grid(columnspan=2, sticky=N + S + E + W) self.ok_btn = Button(self, text='OK') self.cancel_btn = Button(self, text='Cancel') self.ok_btn.grid(column=0, row=1, sticky=N + S + E + W) self.cancel_btn.grid(column=1, row=1, sticky=N + S + E + W) # Properly expand whole grid col_size, row_size = self.grid_size() self.columnconfigure(tuple(range(col_size)), weight=1) self.rowconfigure(tuple(range(row_size)), weight=1) def set_text(self, new_text): # '1.0' means BEGIN of text area like arr[0] self.__text_area.delete('1.0', END) self.__text_area.insert('1.0', new_text) def get_text(self): # '1.0' means BEGIN of text area like arr[0] return self.__text_area.get('1.0', END)
# In this challenge, you are tasked with creating a Python script for analysing # the financial records of your company. You will give a set of financial data called # budget_data.csv. The dataset is composed of two columns: Date and Profit/Losses. # (Thankfully, your company has rather lax standards for accounting so the records are simple.) # Your task is to create a Python script that analyses the records to calculate each of the following: # 1-The total number of months included in the dataset # 2-The net total amount of "Profit/Losses" over the entire period # 3-The average of the changes in "Profit/Losses" over the entire period # 4-The greatest increase in profits (date and amount) over the entire period # 5-The greatest decrease in losses (date and amount) over the entire period # import library import os import csv budget_data_csv = os.path.join("Resources", "budget_data.csv") # declare variables Totalmonths = 0 NetTot_revenue = 0 profit_previous_month = 0 Total_change_profit = 0 date = [] monthly_change = [] # read the file with open(budget_data_csv, "r") as csv_file: csv_reader = csv.reader(csv_file, delimiter=",") next (csv_reader) # 1-The total number of months included in the dataset for row in csv_reader: Totalmonths += 1 # 2-The net total amount of "Profit/Losses" over the entire period NetTot_revenue += int(row[1]) print("Total number of months: ", Totalmonths) print("Net total amount of Profit/Losses:" + str(NetTot_revenue)) # 3-The average of the changes in "Profit/Losses" over the entire period monthly_profit = int(row[1]) monthly_change_profits = monthly_profit - profit_previous_month monthly_change.append(monthly_change_profits) Total_change_profit = Total_change_profit + monthly_change_profits profit_previous_month = monthly_change average_change_profits = (Total_change_profit/Totalmonths) print("Average_change_profits:" + "$" + str(round(average_change_profits))) # 4-The greatest increase in profits (date and amount) over the entire period greatest_increase = max(monthly_change) #5-The greatest decrease in losses (date and amount) over the entire period greatest_decrease = min(monthly_change) print (greatest_increase) print (greatest_decrease) output_file = os.path.join(".", "analysis", "results.txt") with open(output_file, "w",) as textfile: textfile.write("Financial Analysis\n") textfile.write("-----------------------------\n") textfile.write("Total months:" + str(Totalmonths) + "\n") textfile.write("Total:" + "$" + str(NetTot_revenue) + "\n") # textfile.write("Average_change_profits:" + "$" + str(round(average_change_profits)) + "\n") # textfile.write("Greatest_increase in profits:", str(greatest_increase) + "\n") # textfile.write("Greatest_decrease in profits:", str(greatest_increase) + "\n")
#!/usr/bin/python3 import unittest def factor(number): fac = number // 8 rem = number % 8 print (number," = 8 *",fac, " + ", rem) return fac class Test2(unittest.TestCase): def test_factor1(self): self.assertEquals(factor(1), 0) def test_factor2(self): self.assertEquals(factor(12), 3) self.assertEquals(1,0) def test_factor3(self): self.assertEquals(factor(23), 2) def test_factor4(self): self.assertEquals(factor(1024), 31)
def french_rap(csv): try: list_read = {} f = open(csv, 'r') str = f.read() arr = str.splitlines() for x in arr: divide = x.index(',') list_read.setdefault(x[divide + 1:], []).append(x[:divide]) f.close() return list_read except FileNotFoundError: raise FileNotFoundError('File does not exist')
__author__ = 'Scott' #pyChallenge 6 #url: http://www.pythonchallenge.com/pc/def/channel.html #HINT: now there are pairs #HINT: zip # pants.html #HINT: amazing. zoom in #url: http://www.pythonchallenge.com/pc/def/channel.zip -> downloads a zip file #IN ZIP #welcome to my zipped list. #hint1: start from 90052 #hint2: answer is inside the zip import re from zipfile import ZipFile global nothing, comments nextNothing = "" comments = "" zf = ZipFile("channel.zip") def getComment(info): global comments comments = comments + info.comment with open('channel/90052.txt', 'r') as f: getComment(zf.getinfo("90052.txt")) for line in f: nothing = re.findall(r'[0-9]+', line) nextNothing = nextNothing + str(nothing[0]) while True: with open("channel/%s.txt" % nextNothing, "r") as file: getComment(zf.getinfo("%s.txt" % nextNothing)) nextNothing = "" for line in file: nothing = re.findall(r'[0-9]+', line) nextNothing = nextNothing + str(nothing[0]) #GIVES: Collect the comments. print comments #**************************************************************** #**************************************************************** #** ** #** OO OO XX YYYY GG GG EEEEEE NN NN ** #** OO OO XXXXXX YYYYYY GG GG EEEEEE NN NN ** #** OO OO XXX XXX YYY YY GG GG EE NN NN ** #** OOOOOOOO XX XX YY GGG EEEEE NNNN ** #** OOOOOOOO XX XX YY GGG EEEEE NN ** #** OO OO XXX XXX YYY YY GG GG EE NN ** #** OO OO XXXXXX YYYYYY GG GG EEEEEE NN ** #** OO OO XX YYYY GG GG EEEEEE NN ** #** ** #***************************************** #**************************************************************** #url http://www.pythonchallenge.com/pc/def/oxygen.html
""" <Program Name> upper_dot_lower.py <Started> March, 2017 <Author> Lukas Puehringer <[email protected]> <Purpose> Provides functions to encode and decode to and from dot-lower encoding. Dot-lower encoding replaces all upper case letters in a string with a dot followed by the lower case representation of that letter. Additionally, the encoding prepends an underscore. This module can be used to generate RepyV2 conformant non-hidden filenames from base64 encoded strings. Note: The module can be used as Python or RepyV2 module. <Example> >>> base64_enc = "c3lzdGVtanMvYWNlL3JlbmFtLnNo" >>> dot_lower_enc = encode_dot_lower(base64_enc) >>> dot_lower_enc '_c3lzd.g.vtan.mv.y.w.nl.l3.jlbm.ft.ln.no' >>> dot_lower_dec = decode_dot_lower(dot_lower_enc) >>> base64_enc == dot_lower_dec True """ def encode_dot_lower(string): """ <Purpose> Dot-lower encodes a passed string by replacing all upper case letters with a dot (.) and the lower case representation of that string. Additionally the encoder prepends an underscore (_). <Arguments> string A string to dot-lower encode <Returns> A dot lower encoded version of the passed string """ string_enc = "_" for char in string: if char.isupper(): char_enc = "." + char.lower() else: char_enc = char string_enc += char_enc return string_enc def decode_dot_lower(string_enc): """ <Purpose> Decodes a passed dot-lower encoded string by replacing all all dots (.) and the succeeding lower case letter with the upper case representation of that letter. The first letter is ignored, because it should be an underscore (_). <Arguments> sting_enc A string to dot-lower decode <Returns> The dot lower decoded version of the passed string """ string_dec = "" length = len(string_enc) # Start at 1 to ignore the leading underscore i = 1 while i < length: if (string_enc[i] == "." and i + 1 < length and string_enc[i + 1].isalpha()): string_dec += string_enc[i + 1].upper() i += 2 else: string_dec += string_enc[i] i += 1 return string_dec
file = open('month.txt', 'r') list = [] for line in file: list.append(line.strip()) list.sort() for line in list: print(line) outFile = open('sorted_month.txt','w') for line in list: outFile.write(line + '\n') file.close() outFile.close()
# -*- coding: utf-8 -*- """ Created on Sun Sep 18 08:25:23 2016 @author: Meng Wang """ #question 1 def is_palindrome(string): ''' This function is a palindrome recogniser that read a string and return TRUE if it's a palindrome or FLASE if else. Parameter: A string Returns: True if palindrome False if not palindrome ''' string = string.lower() #lower case of each letter puncspace="`~!@#$%^&*()_-=+[]{}\|;:,<.>/? " for k in string: if k in puncspace: string=string.replace(k,'')#no spaces and punctuations in string if not string.isalpha(): return False # return false if there is non-character in it if string[::-1] == string: # if the reverse is the same as itself return True else: return False def palindrome_file(file): ''' This function palindrome_file() reads a file and apply palindrome function to all lines then return lines that are palindrome Parameter: A file Return: Lines that are palindrome ''' file1 = open(file) # open a file for line in file1.read().split('\n'): # read file by lines if is_palindrome(line): print(line) # print the line if it is a palindrome return None #e.g. palindrome_file('name1.txt')#name1.txt is a local file #question 2 def semord(file): ''' This function works as a semordnilap recogniser that accepts a file name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilaps to the screen. Parameter: A file Returns A list containing paired words ''' list1=list(open(file).read().split())#convert a text file into a list puncspace="`~!@#$%^&*()_-=+[]{}\|;:,<.>/?" for k in list1: k=k.lower()#lower case of every character if k in puncspace: list1=list1.replace(k,'')#no punctuations in string new=[]#creat an empty list for i in list1: if i[::-1] in list1 and len(i)>1: #if the length of word is not 1 #and the backward word in the list new.append(i+' '+i[::-1])#word+space+backward word return new #e.g. semord('name1.txt')#'name1.txt' is a local file #question 3 def char_freq_table(file): ''' This function accepts a file name from the user, builds a frequency listing of the characters contained in the file, and prints a sorted and nicely formatted character frequency table to the screen. Parameter: A file Returns: Dictionary(Table) showing frequency of characters ''' string=open(file).read()#open a file and read lines dic= {'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0, 'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,'r':0,'s':0,'t':0, 'u':0,'v':0,'w':0,'x':0,'y':0,'z':0}#formated dictionary string=string.lower()#lower case of each letter string=string.replace('\n','') for i in string: if i in dic: dic[i]+=1#check frequency import operator sorted_dic = sorted(dic.items(), key=operator.itemgetter(0))#convert into a #list and sort return sorted_dic #e.g. char_freq_table('name1.txt')#'name1.txt' is a local file #question4 def speak_ICAO(string,ICAOpause=1,wordpause=3): ''' This function translate string into ICAO words and speak the out. Apart from the text to be spoken, the procedure also needs to accept two additional parameters: a float indicating the length of the pause between each spoken ICAO word, and a float indicating the length of the pause between each word spoken. Parameter: A string Returns: Speak ICAO words ''' import os import time ICAO = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot', 'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima', 'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo', 's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey', 'x':'x-ray', 'y':'yankee', 'z':'zulu'} # define dictionary dic for k in string.split():#split a string into words for i in k:#i represents each character if i not in "`~!@#$%^&*()_-=+[]{}\|;:,<.>/?0123456789": #only letter os.system('say '+ICAO[i.lower()])#speak time.sleep(ICAOpause)#pasue between ICAO words time.sleep(wordpause)#pause between words #e.g. speak_ICAO('When I met your mother',1,3) #question 5 def hapax(file): ''' Define a function that gives the file name of a text will return all its hapaxes. Capitalization and punctuations are ignored. Parameter: A file Returns: A list containing all hapaxes ''' string=open(file).read()#read each line in the file string=string.lower()#lower case of each letter puncspace="`~!@#$%^&*()_-=+[]{}\|;:,<.>/?" for k in string: if k in puncspace: string=string.replace(k,'')#no punctuations in string hapaxes=[]#empty list for i in string.split(): if string.count(i)==1:#if the word shows up only once hapaxes.append(i)#add it into the list return hapaxes #e.g. hapax('name1.txt') #'name1.txt' is a local file #question 6 def numberfile(file): ''' This function gives a text file will create a new text file in which all the lines from the original file are numbered from 1 to n. Parameter: A file Returns: A new file with numbered lines ''' file1=open(file).readlines()#file1 is a list file2=open('New.txt','w')#new empty file for i in range(len(file1)): file2.write('line'+str(i+1)+': '+file1[i])#add 'line#: ' to the #begining of each line, put them together into line2 file2.close()#save and close #e.g. numberfile('name1.txt')#'name1.txt' is a local text file #question 7 def ave(file): ''' This function calculates the average word length of a text stored in a file Parameter: A file Returns: A number(the sum of all the lengths of the word tokens in the text, divided by the number of word tokens) ''' string=open(file).read()#open and read file puncspace="`~!@#$%^&*()_-=+[]{}\|;:,<.>/? " string=string.replace('\n',' ')# no'\n' in string wordnumber=len(string.split())#caculate the number of words for k in string: if k in puncspace: string=string.replace(k,'')#no spaces and punctuations in string charnumber=len(string)#caculate the number of characters return charnumber/wordnumber #e.g. ave('name1.txt')#'name1.txt' is a local text file #question 8 ''' This is a program able to play the "Guess the number" game. Parameter: Name and a number Returns: Strings and how many times taken ''' name=input('What is your name? ')#input name chance=1 import random b=random.randint(0,20) while True: number=int(input(name+', I am thinking of a number between 1 and 20. Take a guess. '))#input a number if number==18: print('Good job, {}! You guessed my number in {} guesses!'.format(name,chance))# break#stop the program when guess the number elif number<18: print('Your guess is too low. Take a guess.') chance+=1#times taken+1 else: print('Your guess is too high. Take a guess.') chance+=1#times taken+1 #e.g #This program need to be saved and imported so it can run #question 10 def lingo(answer): ''' lingo game: The object of the game is to find this word by guessing, and in return receive two kinds of clues: 1) the characters that are fully correct, with respect to identity as well as to position, and 2) the characters that are indeed present in the word, but which are placed in the wrong position. Write a program with which one can play Lingo. Use square brackets to mark characters correct in the sense of 1), and ordinary parentheses to mark characters correct in the sense of 2) Parameter: a word as answer Returns: word after proceed ''' while True: new='' guess=input('take a guess(only 5 characters!): ')#guess a word for i in range(len(guess)): if guess[i]==answer[i]:#if identity and and position are both correct new+='['+guess[i]+']'#add '[]' to the character elif guess[i] in answer:#if only identity is correct new+='('+guess[i]+')'#add '()' to the character else: new+=guess[i]#if neither is correct, just add character if guess==answer: print('Clue: '+new) print('You are right! Good job!') break#stop the program else: print('Clue: '+new) #e.g. lingo('catch') #question 11 punc='?!' lower='abcdefghijklmnopqrstuvwxyz' cap='ABCDEFGHIJKLMNOPQRSTUVWXYZ' num='0123456789' title=['Mr','Mrs','Dr'] punctuation="`~!@#$%^&*()_-=+[]{}\|;:,<.>/?" def splitter(file): ''' This function opens a txt file and works as a sentence splitter to write its sentences with each sentences on a separate line. Sentence boundaries occur at one of "." (periods), "?" or "!", except that a. Periods followed by whitespace followed by a lower case letter are not sentence boundaries. b. Periods followed by a digit with no intervening whitespace are not sentence boundaries. c. Periods followed by whitespace and then an upper case letter, but preceded by any of a short list of titles are not sentence boundaries. Sample titles include Mr., Mrs., Dr., and so on. d. Periods internal to a sequence of letters with no adjacent whitespace are not sentence boundaries (for example, www.aptex.com, or e.g). e. Periods followed by certain kinds of punctuation (notably comma and more periods) are probably not sentence boundaries. Parameter: A text file (the input file will be overwritten by the function!) Returns: A text file (the input file will be overwritten by the function!) ''' string=open(file,'r').read()#open file for read for i in range(1,len(string)-2): if string[i]=='.':#period if string[i+1]==' 'and string[i+2] in lower: string=string #Periods followed by whitespace followed by a lower case letter are not sentence boundaries. elif string[i+1] in num: string=string #Periods followed by a digit with no intervening whitespace are not sentence boundaries. elif (string[i-2:i] or string[i-3:i]) in title and string[i+1]==' ' and string[i+2] in cap: string=string #Periods followed by whitespace and then an upper case letter, but preceded by any of a short list of titles are not sentence boundaries elif string[i-1]!=' ' and string[i+1]!=' ': string=string #Periods internal to a sequence of letters with no adjacent whitespace are not sentence boundaries elif string[i+1] in punctuation: string=string #Periods followed by certain kinds of punctuation else: string=string[:i+1]+'\n'+string[i+2:] #else, add '\n' after period (new line) elif string[i] in punc: string=string[:i+1]+'\n'+string[i+2:]#for sentences end with '?' and '!', seperate new line file1=open(file,'w')#open for write, warning: this function will overwrite your file file1.write(string)#write string into it file1.close()#save and close #e.g splitter('name1.txt') #'name1.txt' is a local file
""" An implementation of a Binary Tree based on the description given in Computer Science by Bob Reeves (Hodder Eduction, 2015). This is not a terribly good implementation as it doesn't take advantage of OOP to create node objects to build the tree. Instead it uses three arrays (lists), node[], left[] and right[] to keep track of which nodes are to the left and right of each other node. For a better implementation, see bTree.py in this project. """ class BinaryTree: __node = [] __left = [] __right = [] __currentNode = None def getLeft(self, index): return self.__node[self.__left[index]] def getRight(self, index): return self.__node[self.__right[index]] def getData(self, index): return self.__node[index] def addData(self, data): if len(self.__node) == 0: # node array is empty print("Node array is empty") self.__node.append(data) self.__left.append(None) self.__right.append(None) print("Added as tree root: %s" % data) return self.__node.append(data) self.__left.append(None) self.__right.append(None) newIndex = len(self.__node) - 1 # index of newly added node presentNode = 0 # Start at the root of the tree while presentNode < newIndex: # Branch left or right? if data < self.__node[presentNode]: if self.__left[presentNode] == None: self.__left[presentNode] = newIndex # Place the index of the new node in the appropriate place in the left[] array presentNode = self.__left[presentNode] else: if self.__right[presentNode] == None: self.__right[presentNode] = newIndex presentNode = self.__right[presentNode] print("Added: %s" % self.__node[presentNode]) def showTree(self): print("Tree structure:") print("---------------") for n in range(0,len(self.__node)): print("Node {0}: {1} \t\tLeft node:{2}\t\tRight node:{3}".format(n, self.__node[n], self.__left[n], self.__right[n])) def inOrderTraverse(self): if len(self.__node)== 0: print("Tree is empty!") return bt = BinaryTree() """ bt.addData("Jim") bt.addData("Kevin") bt.addData("Alice") bt.addData("Bruce") bt.addData("Alex") bt.addData("Carl") bt.showTree() """ bt.inOrderTraverse()
def show_list_contents(l): if len(l) > 0: # Spacing and row headings output = [""] * 5 output[0] = " " output[1] = " Index: " output[2] = " " output[3] = "Contents: " output[4] = " " # For each item in the list, print out the index number and contents for i in range(0, len(l)): output[0] += "+" + "-" * 8 output[1] += "|{0:^8}".format(i) output[2] += "+" + "-" * 8 output[3] += "|{0:^8}".format(l[i]) output[4] += "+" + "-" * 8 # Put endings on the rows output[0] += "+" output[1] += "|" output[2] += "|" output[3] += "|" output[4] += "+" for row in output: print(row) else: print(" +------------+") print(" | EMPTY |") print(" +------------+") print()
class TuringMachine: def __init__(self): self.__tape = [] self.__head_pos = 0 self.__start_state = self.__s1 self.__current_state = "" self.__halt_reached = False def load(self, s): self.__tape = list(s) def show(self): print("CURRENT STATE: " + self.__current_state) HORIZONTAL_BORDER = "+-" * len(self.__tape) + "+" print(HORIZONTAL_BORDER) for element in self.__tape: print("|" + element, end='') print("|") print(HORIZONTAL_BORDER) print(" " * (self.__head_pos - 1) + " ^") print() def __set_head(self, x): self.__head_pos = x def __move_head(self, x): self.__head_pos += x def __read(self): return self.__tape[self.__head_pos - 1] def __write(self, x): self.__tape[self.__head_pos -1] = str(x) def run(self, start_head_pos): self.__move_head(start_head_pos) self.__start_state(self.__read()) def __s1(self, i): self.__current_state = "S1" self.show() if i == "0": self.__write("0") self.__move_head(1) return self.__s1(self.__read()) elif i == "1": self.__write("1") self.__move_head(1) return self.__s2(self.__read()) elif i == ".": self.__write("e") self.__move_head(1) return self.__s3(self.__read()) def __s2(self, i): self.__current_state = "S2" self.show() if i == "0": self.__write(0) self.__move_head(1) return self.__s2(self.__read()) elif i == "1": self.__write(1) self.__move_head(1) return self.__s1(self.__read()) elif i == ".": self.__write("o") self.__move_head(1) return self.__s3(self.__read()) def __s3(self, i): self.__current_state = "S3" self.show() print("HALT STATE REACHED") return self.__tape tm = TuringMachine() tm.load("...01100..") tm.run(4)
class btNode: __data = None __left = None __right = None def __init__(self, d): self.__data = d def getData(self): return self.__data def getLeft(self): return self.__left def getRight(self): return self.__right def addChild(self, d): if d < self.__data: if self.__left is None: self.__left = btNode(d) print("Added {0} to left of {1}".format(d, self.__data)) else: self.__left.addChild(d) else: if self.__right is None: self.__right = btNode(d) print("Added {0} to right of {1}".format(d, self.__data)) else: self.__right.addChild(d) class bTree: __root = None def __init__(self, d): self.__root = btNode(d) def add(self, d): self.__root.addChild(d) def postOrder(self): visited = [] def traverse(currentNode:btNode): if currentNode.getLeft() is not None: traverse(currentNode.getLeft()) if currentNode.getRight() is not None: traverse(currentNode.getRight()) visited.append(currentNode.getData()) traverse(self.__root) return visited # Build the tree used in the example on Page 97 bt = bTree("Colin") bt.add("Bert") bt.add("Alison") bt.add("Cedric") print(bt.postOrder())
class HashTable: __table = [] def __init__(self, size = 10): self.__table = [None] * size def getHashValue(self,key): hashValue = 0 for digit in key: hashValue = hashValue + ord(digit) hashValue = hashValue % len(self.__table) return hashValue def insert(self, data): h = self.getHashValue(data) if self.__table[h] == None: self.__table[h] = data else: tmp = self.__table[h] self.__table[h] = [tmp] self.__table[h].append(data) def search(self,key): h = self.getHashValue(key) if self.__table[h] != None: if type(self.__table[h]) == type([]): for item in self.__table[h]: if item == key: return True else: if self.__table[h] == key: return True else: return False def showTable(self): print(self.__table) ht = HashTable(20) ht.insert("1234") ht.insert("6488836") ht.insert("2342") ht.insert("2341") ht.insert("Bob") ht.showTable() print(ht.search("1234")) print(ht.search("2349")) print(ht.search("Bob"))
text_to_compress = input("Enter some text to compress: ") text_to_compress += " " previous_character = "" same_character_count = 1 output = "" # Look at each letter for letter in text_to_compress: # If the letter is the same and the previous letter if letter == previous_character: # Count consecutive letters same_character_count += 1 else: if previous_character != "": output = output + previous_character + " " + str(same_character_count) + " " previous_character = letter same_character_count = 1 #output = output + previous_character + " " + str(same_character_count) + " " print(output)
__author__ = 'Kyle Rouse' def d(data1, data2): value = 0 for i in range(len(data1)): value += (data1[i] - data2[i])**2 return value**.5 def traversal_first_traversal(data, k): point = data[0] centers = [] centers.append(point) data.remove(point) while len(centers) < k: dataSets = [] for i in range(0, len(data)): min_distance = min_dist(data[i], centers) dataSets.append((min_distance, data[i])) center = max([i for i in dataSets], key=lambda x:x[0][0]) centers.append(center[1]) dataSets.remove(center) data.remove(center[1]) return centers def min_dist(point, centers): tmp = [] dist = 0 list_order = [] for i in centers: if i != point: dist += d(point, i) list_order.append((d(point,i),i)) tmp.append((i, dist)) return min(list_order,key=lambda x:x[0]) def main(text): lines = open(text).read().split("\n") splitLine = lines[0].split(" ") k = float(splitLine[0]) data = lines[1:] data = [map(float,i.split(" ")) for i in data] answer = traversal_first_traversal(data, k) for i in answer: for j in i: print j, print if __name__ == '__main__': main("rosalind_ba8a.txt")
__author__ = 'kyle' <<<<<<< HEAD def longest_path_setup(text): file_in = open(text) lines_list = file_in.read().split("\n") dimensions = lines_list[0].split(" ") m1, m2 = get_matrices(lines_list[1:len(lines_list)]) n = int(dimensions[0]) m = int(dimensions[1]) return longest_path(n, m, m1, m2) def longest_path(n, m, down, right): zero_matrix = [[0]*(m+1) for i in range(n+1)] for i in range(1, n+1): zero_matrix[i][0] = zero_matrix[i-1][0] + down[i-1][0] for i in range(1, m+1): zero_matrix[0][i] = zero_matrix[0][i-1] + right[0][i-1] for i in range(1, n+1): for j in range(1, m+1): zero_matrix[i][j] = max(zero_matrix[i-1][j]+down[i-1][j], zero_matrix[i][j-1] + right[i][j-1]) return zero_matrix[n][m] def get_matrices(matrix_list): matrix = list() matrix_container = list() for i in range(0, len(matrix_list)): weights = matrix_list[i].split(" ") node = list() if matrix_list[i] != "-": for j in range(0, len(weights)): node.append(int(weights[j])) matrix.append(node) else: matrix_container.append(matrix) matrix = list() matrix_container.append(matrix) return matrix_container[0], matrix_container[1] print longest_path_setup("input") ======= def longest_path(text): file_in = open(text) lines_list = file_in.read().split("\n") dimensions = lines_list[0].split(" ") x = dimensions[0] y = dimensions[1] x_dim = int(x)-1 y_dim = int(y)-1 nodes_matrix = Nodes(0, list(), len(lines_list[1]), 0) matrix_container = list() matrix = nodes_matrix.matrix dim_y = 0 max = 0 for i in range(1, len(lines_list)): weights_list = lines_list[i].split(" ") tmp_path = "" tmp_max = 0 if lines_list[i] != "-": length = len(weights_list) matrix.append(list()*length) y = nodes_matrix.get_y() node = matrix[y] for j in range(0, length): weight = int(weights_list[j]) if y == 0: if j == 0: tmp_max = weight node.append(Node(weight,weight,weight)) else: tmp_max = weight+node[j-1].get_max() node.append(Node(weight,weight,weight+node[j-1].get_max())) else: if j == 0: tmp_max = weight+matrix[y-1][j].get_max() node.append(Node(weight,tmp_max,weight)) else: left_weight = weight+node[j-1].get_max() top_weight = weight+ matrix[y-1][j].get_max() node.append(Node(weight,left_weight,top_weight)) tmp_max = node[j].get_max() tmp_path += str(weight)+"," print "TMP MAX:",tmp_max if tmp_max > nodes_matrix.max_weight: nodes_matrix.max_weight = tmp_max nodes_matrix.set_max_weight(tmp_max) nodes_matrix.set_y(nodes_matrix.get_y()+1) else: if nodes_matrix.matrix[x_dim][y_dim].get_max() > max: max = nodes_matrix.matrix[x_dim][y_dim].get_max() nodes_matrix.print_matrix() matrix_container.append(nodes_matrix) nodes_matrix.set_y(0) nodes_matrix = Nodes(0, list(), len(lines_list[1]), 0) matrix = nodes_matrix.matrix matrix_container.append(nodes_matrix) return max class Nodes: def __init__(self, weight, matrix, x, y): #self.nodes = nodes self.max_weight = weight self.matrix = matrix self.x = x self.y = y self.target = weight def set_target(self,in_weight): if self.target < in_weight: self.target = in_weight def get_target(self): return self.target def get_x(self): return self.x def print_matrix(self): for i in range(0,len(self.matrix)): row = "" for j in range(0, len(self.matrix[i])): row += str(self.matrix[i][j].get_max())+" " print row def get_y(self): return self.y def set_x(self, x): self.x = x def set_y(self, y): self.y = y def get_max_weight(self): return self.max_weight def set_max_weight(self,weight): self.max_weight = weight def add_row(self, row): self.y += 1 self.matrix.append(row) def add_node(self,node): self.nodes.append(node) class Node: def __init__(self, weight, top_weight, left_weight): self.weight = weight if top_weight > left_weight: self.total_weight_max = top_weight else: self.total_weight_max = left_weight self.total_weight_top = top_weight self.total_weight_left = left_weight def top_total(self): return self.total_weight_top def set_top_total(self, weight): if weight > self.total_weight_max: self.total_weight_max = int(weight) self.total_weight_top = int(weight) def set_left_total(self,weight): if weight > self.total_weight_max: self.total_weight_max = int(weight) self.total_weight_top = int(weight) def left_total(self): return self.total_weight_left def get_max(self): return self.total_weight_max def set_max(self, weight): self.total_weight_max = int(weight) print longest_path("input.txt") >>>>>>> 9c227b03a489a7a06dfc5e5b7dd8d3a192553c9b
__author__ = 'kyle' <<<<<<< HEAD def coins(text): in_file = open(text) lines = in_file.read().split("\n") total = int(lines[0]) tmp = lines[1].split(",") coins_available = list() for i in tmp: coins_available.append(int(i)) coins_available.sort() coin_bag = list() for i in range(0, len(coins_available)): coin_bag.insert(i, Coin(int(coins_available[i]),total/int(coins_available[i]))) return starting_sum(coin_bag, total) def starting_sum(coins, total): number_of_coins = len(coins)-1 count = 0 path = "" check=total while 0 <= number_of_coins: coin = coins[number_of_coins].value path += str(coin)+" " while total >= coin: print total/(coin+(coin - coins[number_of_coins-1].value)),"<", coins[number_of_coins-1].value print (total/coins[number_of_coins-1].value), "<=", coins[0].value if total %coins[number_of_coins-1].value == 0: coins[number_of_coins-1].min_div = total/coins[number_of_coins-1].value print "Total:",total print "Count:",count divs = total/coins[number_of_coins-1].value print "total/21:",total /divs print "divs",divs tmp_count = count+total/coins[number_of_coins-1].value print tmp_count,count if tmp_count < check: check = tmp_count if tmp_count < check: count = check if total < 1: return count if divs < coins[number_of_coins-1].value: number_of_coins -= 1 if total/(coin+(coin - coins[number_of_coins-1].value)) < coins[number_of_coins-1].value: print total%21 print total, coins[number_of_coins-1].value**2 total -= coin count += 1 if check < count: count = check if total < 1: return count path += str(coin)+" + "+str(total)+" " number_of_coins -= 1 tmp_val = coins[get_largest_divisible(coins, total)].value number_of_coins = check_mod(coins, tmp_val, total, number_of_coins) print "CHECK:",check if tmp_count < check: return check return count def check_mod(coins, val, total, index): while 0 <= index: if coins[index] <= total and coins[index].value%val==0: return index index -= 1 def get_largest_divisible(coin, total): count = len(coin)-1 while 0 <= count: if coin[count].is_divisible(total): return count count -= 1 return class Coin: def __init__(self, value,min_div): self.min_div = min_div self.value = value def is_divisible(self, total): return 0 == total%self.value def get_remaining(self, total): ======= def coins(text): in_file = open(text) lines = in_file.read().split("\n") total = lines[0] coins_available = lines[1].split(",") coin_bag = list() print "hi" for i in range(0, len(coins_available)): coin_bag.insert(i,Coin(coins_available[i])) print coin_bag[i].value print get_remaining(total) class Coin: def __init__(self, value): self.value = valu def is_divisible(self,total): return 0 == total%self.value def get_remaining(self,total): >>>>>>> 9c227b03a489a7a06dfc5e5b7dd8d3a192553c9b return total%self.value def get_lower_count(self, value2, total): if total/self.value < total/value2: return total/self.value else: return total/value2 def remove_n_minus_one(self,total): count = 0 <<<<<<< HEAD while count+self.value < total-self.value: count += self.value return count/self.value, total-count print coins("rosalind_ba5a.txt") # Driver program to test above function ======= while count+self.value < total: count += self.value return count/self.value, total-count coins("input.txt") >>>>>>> 9c227b03a489a7a06dfc5e5b7dd8d3a192553c9b
def palindromesubsequence(x,y): m = len(x) n = len(y) L = [[0]* (n+1)]*(m+1) for i in range(n+1): for j in range(n+1): if (i==0 or j==0): L[i][j]=0; elif (x[i-1] == y[j-1]): L[i][j] = L [i-1][j-1]+1; else: pass return L[0] [n-1] def longestpalindromesubsequence(ABCCBDDCE): return (string)
def addition(l1): for i in l1: sum1=sum(l1) return sum1 def multiplication(l1): mull=1 for i in l1: mull = mull*i return mull
class Level: def __init__(self, current_level=1, current_xp=0, level_up_base=200, level_up_factor=150): self.current_level = current_level self.current_xp = current_xp self.level_up_base = level_up_base self.level_up_factor = level_up_factor # Calcula a experiencia necessaria no proximo nivel com base em factor e nivel atual @property # Define como uma 'variavel' read-only def experience_to_next_level(self): return self.level_up_base + self.current_level * self.level_up_factor def add_xp(self, xp): self.current_xp += xp # Checa se personagem ultrapassou o nivel if self.current_xp > self.experience_to_next_level: self.current_xp -= self.experience_to_next_level return True else: return False
roomies=[] print('Enter the name of all the roomies:') while True: name=input() if name=='': break roomies=roomies+[name] print('The name of the roomies are') for i in roomies: print(' '+ i)
import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset=pd.read_csv("logistic.csv") x=dataset.iloc[:,:-1].values y=dataset.iloc[:,-1].values from sklearn.preprocessing import * #en=LabelEncoder() #x[:,1]=en.fit_transform(x[:,1]) m=MinMaxScaler() x=m.fit_transform(x) def sigmoid(theta,x): return 1.0/(1+np.exp(-np.dot(x,theta.T))) def calc_val(theta,x,y): val=sigmoid(theta,x) first=val-y.reshape(len(y),1) second=np.dot(first.T,x) return second def cost_func(theta,x,y): log_func_v = sigmoid(theta, x) y = np.squeeze(y) y=y.reshape(len(y),1) step1 = y*np.log(log_func_v) step2 = (1 - y) * np.log(1 - log_func_v) final = -step1 - step2 return np.mean(final) def grad(theta,x,y): change_cost=1 cost=cost_func(theta,x,y) learning_rate=0.01 i=1 while(change_cost>0.00001 ): old_cost=cost val=calc_val(theta,x,y) theta=theta-(learning_rate*val) cost=cost_func(theta,x,y) change_cost=old_cost-cost i+=1 return theta,i X=np.append(np.ones((x.shape[0],1)),x,axis=1) from sklearn.model_selection import * train_x,test_x,train_y,test_y=train_test_split(X,y,test_size=0.3,random_state=0) theta=np.random.rand(1,X.shape[1]) theta,num=grad(theta,train_x,train_y) # get_val=np.dot(test_x,theta.T) y_pred=np.where(get_val>=0.5,1,0) x0=test_x[np.where(test_y==0)] x1=test_x[np.where(test_y==1)] plt.scatter([x1[:,1]],[x1[:,2]],color="G") plt.scatter([x0[:,1]],[x0[:,2]],color="B") x1 = np.arange(0, 1, 0.1) x2 = -(theta[0,0] + theta[0,1]*x1)/theta[0,2] plt.plot(x1, x2, c='k', label='reg line') plt.xlabel('input values') plt.ylabel('predicted values') plt.title('classification using logistic regression') plt.show() accuracy=np.sum(test_y.reshape(-1,1)==y_pred)/len(y_pred)*100 print('Accuracy: ',accuracy,' %')
from collections import Counter import pandas as pd import seaborn as sns from matplotlib.colors import ListedColormap from palettable.colorbrewer import diverging, qualitative, sequential def is_data_homogenous(data_container): """ Checks that all of the data in the container are of the same Python data type. This function is called in every other function below, and as such need not necessarily be called. :param data_container: A generic container of data points. :type data_container: `iterable` """ data_types = set([type(i) for i in data_container]) return len(data_types) == 1 def infer_data_type(data_container): """ For a given container of data, infer the type of data as one of continuous, categorical, or ordinal. For now, it is a one-to-one mapping as such: - str: categorical - int: ordinal - float: continuous There may be better ways that are not currently implemented below. For example, with a list of numbers, we can check whether the number of unique entries is less than or equal to 12, but has over 10000+ entries. This would be a good candidate for floats being categorical. :param data_container: A generic container of data points. :type data_container: `iterable` """ # Defensive programming checks. # 0. Ensure that we are dealing with lists or tuples, and nothing else. assert isinstance(data_container, list) or isinstance( data_container, tuple ), "data_container should be a list or tuple." # 1. Don't want to deal with only single values. assert ( len(set(data_container)) > 1 ), "There should be more than one value in the data container." # 2. Don't want to deal with mixed data. assert is_data_homogenous( data_container ), "Data are not of a homogenous type!" # Once we check that the data type of the container is homogenous, we only # need to check the first element in the data container for its type. datum = data_container[0] # Return statements below # treat binomial data as categorical # TODO: make tests for this. if len(set(data_container)) == 2: return "categorical" elif isinstance(datum, str): return "categorical" elif isinstance(datum, int): return "ordinal" elif isinstance(datum, float): return "continuous" else: raise ValueError("Not possible to tell what the data type is.") def is_data_diverging(data_container): """ We want to use this to check whether the data are diverging or not. This is a simple check, can be made much more sophisticated. :param data_container: A generic container of data points. :type data_container: `iterable` """ assert infer_data_type(data_container) in [ "ordinal", "continuous", ], "Data type should be ordinal or continuous" # Check whether the data contains negative and positive values. has_negative = False has_positive = False for i in data_container: if i < 0: has_negative = True elif i > 0: has_positive = True if has_negative and has_positive: return True else: return False def is_groupable(data_container): """ Returns whether the data container is a "groupable" container or not. By "groupable", we mean it is a 'categorical' or 'ordinal' variable. :param data_container: A generic container of data points. :type data_container: `iterable` """ is_groupable = False if infer_data_type(data_container) in ["categorical", "ordinal"]: is_groupable = True return is_groupable def num_discrete_groups(data_container): """ Returns the number of discrete groups present in a data container. :param data_container: A generic container of data points. :type data_container: `iterable` """ return len(set(data_container)) def items_in_groups(data_container): """ Returns discrete groups present in a data container and the number items per group. :param data_container: A generic container of data points. :type data_container: `iterable` """ return Counter(data_container) def n_group_colorpallet(n): """If more then 8 categorical groups of nodes or edges this function creats the matching color_palette """ cmap = ListedColormap(sns.color_palette("hls", n)) return cmap cmaps = { "Accent_2": qualitative.Accent_3, "Accent_3": qualitative.Accent_3, "Accent_4": qualitative.Accent_4, "Accent_5": qualitative.Accent_5, "Accent_6": qualitative.Accent_6, "Accent_7": qualitative.Accent_7, "Accent_8": qualitative.Accent_8, "continuous": sequential.YlGnBu_9, "diverging": diverging.RdBu_11, "weights": sns.cubehelix_palette( 50, hue=0.05, rot=0, light=0.9, dark=0, as_cmap=True ), } def to_pandas_nodes(G): # noqa: N803 """ Convert nodes in the graph into a pandas DataFrame. """ data = [] for n, meta in G.nodes(data=True): d = dict() d["node"] = n d.update(meta) data.append(d) return pd.DataFrame(data) def to_pandas_edges(G, x_kw, y_kw, **kwargs): # noqa: N803 """ Convert Graph edges to pandas DataFrame that's readable to Altair. """ # Get all attributes in nodes attributes = ["source", "target", "x", "y", "edge", "pair"] for e in G.edges(): attributes += list(G.edges[e].keys()) attributes = list(set(attributes)) # Build a dataframe for all edges and their attributes df = pd.DataFrame(index=range(G.size() * 2), columns=attributes) # Add node data to dataframe. for i, (n1, n2, d) in enumerate(G.edges(data=True)): idx = i * 2 x = G.node[n1][x_kw] y = G.node[n1][y_kw] data1 = dict( edge=i, source=n1, target=n2, pair=(n1, n2), x=x, y=y, **d ) data2 = dict( edge=i, source=n1, target=n2, pair=(n1, n2), x=x, y=y, **d ) df.loc[idx] = data1 df.loc[idx + 1] = data2 return df
#!/usr/bin/python import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as anim def plot_cont(fun,xmax): y = [] fig = plt.figure() ax = fig.add_subplot(1,1,1) def update(i): yi = fun() y.append(yi) x = range(len(y)) ax.clear() ax.plot(x,y) a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False) plt.show() def main(): def func(): x = np.random.randint(-10,10,1) return x[0] plot_cont(func,10) if __name__ == '__main__': main()
from collections import deque data = {} data['a'] = 1 data['b'] = 2 data['c'] = 3 def print_test(data): for i in data: print(i, data[i]) #print_test(data) class Node: # Creates single double facing nodes def __init__(self, val, prev=None, nxt=None): self.val = val self.prev = prev self.nxt = nxt class LinkedList: # Doubly linked list def __init__(self, start, end=None): self.start = start self.end = end or start def add_left(self, curr_node): self.start.prev = curr_node curr_node.nxt = self.start self.start = curr_node def pop_left(self): popped_node = self.start self.start = popped_node.nxt # Clean start node self.start.prev = None # Clean up popped node popped_node.nxt = None return popped_node.val def add_right(self, curr_node): self.end.nxt = curr_node curr_node.prev = self.end self.end = curr_node def pop_right(self): popped_node = self.end self.end = popped_node.prev # clean end node self.end.nxt = None # clean pooped node popped_node.prev = None return popped_node.val n1 = Node(1) n2 = Node(4) n3 = Node(3) n4 = Node(8) llist = LinkedList(n1) llist.add_right(n2) llist.add_left(n3) llist.add_right(n4) print('start: ', llist.start.val) print('end: ', llist.end.val) print('popped: ', llist.pop_right()) print('end: ', llist.end.val) def queue(): q = deque() q.append('a') q.append('b') q.append('c') temp = q.popleft() print(q) # queue() class que(object): def __init__(self, que = []): self.que = que x = que() x.que.append('a') x.que.append('b') x.que.append('c') # print(x.que)
#!/usr/bin/env python3 def main(): with open('input.txt', "r") as f: number = int(f.readline()) for i in range(2,int(number**0.5)+1): if number/i == int(number/i): print('false') break else: print('true') if __name__ == '__main__': main()
#!/usr/bin/python3 ################################################################# # Simple Python3 script to generate random passwords # # Made for educational purposes, feel free to use if you'd like # # Created by Kris Rostkowski # ################################################################# # Import Module # Random is needed to radomize the characters for the generated passwords import random # Variables with Input requesting password length, converting to integer, and possible password characters Passlength = input("How long would you like your password to be?") Length = int(Passlength) chars = """abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&' ()*+,-./:;<=>?@[]^_`{|}~""" # Variable to hold the newly generate password # For loop that will create and randomized the password, then prints out to the screen Pass = "" for c in range(Length): Pass += random.choice(chars) print(Pass)
current_wickipidia = int(input("current_wickipidia count")) if current_wickipidia >= 1000: print("buy10") elif current_wickipidia <= 1000: print("holding")
#!/usr/bin/env python3 # -*- coding: utf8 -*- #------------------------------------------------------------------------------- # created on: 11-12-2018 # filename: makewordplot.py # author: brendan # last modified: 12-11-2018 21:26 #------------------------------------------------------------------------------- """ Parse the rank file to make a plot of the rank of a particular word """ import tarfile import numpy as np import datetime as dt import dateutil.relativedelta as rdelta import matplotlib.pyplot as plt import matplotlib.dates as dts import pickle import argparse def calc_prev_median(date, data, k=1.5): """ Calculate the median for a certain date from the data of the previous six months of data. """ earliest_date = date - rdelta.relativedelta(months=6) # keep only the data in this range my_data = [] for check_date, rank in data: if check_date >= earliest_date and check_date <= date: my_data.append(rank) median = np.median(my_data) first_quart = np.percentile(my_data, 25) third_quart = np.percentile(my_data, 75) IQR = third_quart - first_quart lower_bound = first_quart - k * IQR # make sure the lower bound doesn't go below 1 lower_bound = lower_bound if lower_bound > 1 else 1 upper_bound = third_quart + k * IQR return (date, median, lower_bound, upper_bound) def main(WORD, LOG, YEAR, CUTOFF=100001): """ Run the program with the 3 global varables taken from the arg parsing """ try: with open('data/{}-{}-full-data.pkl'.format(WORD, YEAR), 'rb') as f: full_data = pickle.load(f, encoding='bytes') except: full_data = [] with tarfile.open(TARFILE, mode='r:gz') as f: for member in f: if member.isfile(): # parse the date from the file name date_str = member.name.split('.')[0][-10:] try: date = dt.datetime.strptime(date_str, '%Y-%m-%d') except ValueError: print(member.name.split('.')) if date.year == YEAR or date.year == YEAR - 1: # flag to record if the word was found in the file found = False for line in f.extractfile(member): if WORD in line.decode(): rank = int(line.decode().split()[-1]) full_data.append((date, rank)) found = True break # if the word isn't found give it the max rank if not found: rank = CUTOFF full_data.append((date, rank)) full_data = sorted(full_data) with open('data/{}-{}-full-data.pkl'.format(WORD, YEAR), 'wb') as f: pickle.dump(full_data, f) fig, ax = plt.subplots() loc = dts.MonthLocator() myFmt = dts.DateFormatter('%m') median_plot = [] for date, _ in full_data: if date.year == YEAR: median_plot.append(calc_prev_median(date, full_data)) # make the plots only for 2018 plot_data = full_data plot_data = [(date, rank) for date, rank in full_data if date.year == YEAR] rdate, rank = zip(*plot_data) mdate, median, upper_bound, lower_bound = zip(*median_plot) # calculate the standard deviation, to note points that rise much higher # the typical values of the plot filename = 'plots/{}-{}-baseline-comparison'.format(WORD, YEAR) ylabel = 'Rank' if LOG: rank = np.log10(rank) median = np.log10(median) upper_bound = np.log10(upper_bound) lower_bound = np.log10(lower_bound) ylabel = 'Log Rank' filename = '{}-LOG'.format(filename) ax.plot(rdate, rank, 'k-') ax.plot(mdate, median, 'r--') ax.fill_between(mdate, upper_bound, lower_bound, color='r', alpha=0.3, linewidth=0) # ax[1].axhspan(first_quart - k * IQR, third_quart + k * IQR, color='r', # alpha=0.25, lw=0) ax.set_xlabel('Month') ax.set_ylabel(ylabel) ax.invert_yaxis() ax.xaxis.set_major_formatter(myFmt) ax.set_title('Rank plot for {} in {}'.format(WORD, YEAR)) fig.savefig('{}.jpg'.format(filename)) plt.close(fig) if __name__ == '__main__': """ put the relevant code in the if statement, so I can import calc_prev_median without running the full script, and passing in command line arguments """ parser = argparse.ArgumentParser( description="Make a word plot with shifting median for a given year") parser.add_argument('word', help='the word for plotting') parser.add_argument('log', nargs='?', default=False, help='boolean flag to produce a log plot') parser.add_argument('year', nargs='?', default=2018, help='the year of concern for the plot') args = parser.parse_args() home_directory = 'top_daily_words_uni' TARFILE = '{}.tar_.gz'.format(home_directory) WORD = args.word print(WORD) LOG = bool(args.log) print(LOG) YEAR = args.year print(YEAR) # the number to multiply the IQR by to indicate extreme values vs. outliers main(WORD, LOG, YEAR)
#1 import datetime import calendar Name=input("Give me your Name") DOB =input("Give me your DOB") Date=datetime.datetime.strptime(DB,'%d %m %Y') Day=D.replace(year = Date.year+100) print("Hello " +Name+ ", You will turn 100 years old in the year" ,Day.year) N=Day.weekday() Day_Name= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday'] print("Day of your 100th Birthday is ",Day_Name[N]) #2 Number=(int)(input("Enter Number: ")) for x in range(1,Number+1): if(Number%x==0): print(x) #3 List1= [1, 2, 3, 4, 5,6,11] List2= [5, 6, 7, 8, 9,10] a=set(List1) b=set(List2) if len(a.intersection(b)) > 0: print(a.intersection(b)) else: print("no common elements") #4 string = input("Please enter the String : ") if(string == string[:: - 1]): print("This word is a palindrome") else: print("This word is not a palindrome") #5 import math class circle(): def __init__(self, radius): self.radius = radius def area(self): return math.pi * (self.radius ** 2) def perimeter(self): return 2 * math.pi * self.radius Radius = int(input("Enter radius of circle: ")) obj = circle(Radius) print("Area of circle:", round(obj.area(), 2)) print("Perimeter of circle:", round(obj.perimeter(), 2))
# Big-O # 1. Constant----------------- O(1) # 2. Logarithmic-------------- O(Log N) # log (base) N = exponent # log 8 = 3 # linear---------------------- 0(N) animals = ['duck', 'cat', 'dog', 'bear'] def print_animals(animal_list): for i in range(len(animal_list)): print(animal_list[i]) counter = 0 for n in range(10000): counter += 1 print_animals(animals) # O(100000*n) ----> O(N) # linearithmic/log-linear----- O(N * Log N) # polynomial ----------------- O(N^c) # exponential ---------------- O(c^N) #
# this program issues a serach for youtube videos , given a particular search import json import urllib.parse import urllib.request GOOGLE_API_KEY = "AIzaSyAdpz4y7NlVi6diJnNUm61FxgV7qTxPFY0" BASE_YOUTUBE_URL = 'https://www.googleapis.com/youtube/v3' def build_search_url(search_query:str, max_results: int) ->str: query_parameters = [ ('key', GOOGLE_API_KEY),('part','snippet'), ('type', 'video'),('maxResults',str(max_results)), ('q',search_query) ] return BASE_YOUTUBE_URL + '/search?' + urllib.parse.urlencode(query_parameters) def get_result(url:str)->'json': response = None try: response = urllib.request.urlopen(url) json_text = response.read().decode(encoding = 'utf-8') return json.loads(json_text) finally: if response != None: response.close() def print_title_and_description(json_result: 'json') ->None: for item in json_result['items']: print(item['snippet']['title']) print(item['snippet']['description']) print() if __name__ == '__main__': search_query = input('Query: ') result = get_result(build_search_url(search_query, 10)) print_title_and_description(result) #print(result)
#gridlayout from tkinter import * root = Tk() label1 = Label(root, text = "Label 1 ") label2 = Label(root, text = "Label 2 ") label3 = Label(root, text = "Label 3 ") label1.grid(row = 0 , column = 0 ) label2.grid(row = 0, column = 1) label3.grid(row = 1 , column = 0) root.mainloop()
from tkinter import * import Othello import math class OthelloApplication: def __init__(self, gameState: Othello.Othello, winner :str): # creates a game board self._state = gameState self._state._new_game_board() self._root_window =Tk() self._root_window.configure(bg = 'black') self._root_window.title("WELCOME TO OTHELLO") self._score_frame = Frame(master=self._root_window) self._white_text = StringVar() self._white_text.set('White:{}'.format(self._state.countPieces('W'))) self._black_text = StringVar() self._black_text.set('Black:{}'.format(self._state.countPieces('B'))) self._turn_text = StringVar() self._turn_text.set('Turn:{}'.format(self._state._turn)) self._score_frame.grid(row=0,column=0,padx=10,pady=10,sticky= S + N) self._black=Label(master=self._score_frame,textvariable=self._black_text,font=('Helvetica',16)) self._black.grid(row=0,column=0,padx=10,pady=10,sticky= W) self._turn=Label(master=self._score_frame,textvariable=self._turn_text,font=('Helvetica',16)) self._turn.grid(row=0,column=1,padx=10,pady=10,) self._white=Label(master=self._score_frame,textvariable=self._white_text,font=('Helvetica',16)) self._white.grid(row=0,column=2,padx=10,pady=10,) self._canvas = Canvas( master = self._root_window, width = 600, height = 600, background = "green") self._counter = 0 self._tiles = [] self._winner = winner self._canvas.grid( row = 1, column = 0, padx = 10, pady = 10, sticky = N + S + E + W) self._row=self._state._row self._col=self._state._col self._board=self._state._board self._canvas.bind('<Configure>', self._on_canvas_resized) self._canvas.bind('<Button-1>', self._on_canvas_clicked) self._score_frame.rowconfigure(0, weight = 1) self._score_frame.columnconfigure(0, weight = 0) self._score_frame.columnconfigure(1, weight = 0) self._score_frame.columnconfigure(2, weight = 0) self._root_window.rowconfigure(1,weight=1) self._root_window.columnconfigure(0, weight = 1) def start(self) -> None: self._root_window.mainloop() def _on_canvas_resized(self, event:Event) ->None: self._redraw_all_spots() def createBoard(self,row,col): # creates the new game board b width = self._canvas.winfo_width() height = self._canvas.winfo_height() spaceX=math.ceil(width/row) spaceY=math.ceil(height/col) for x in range((spaceX),width+spaceX,(spaceX)): self._canvas.create_line(x,0,x,height) # neeed to change the code later for y in range((spaceY),height+spaceY,(spaceY)): self._canvas.create_line(0,y,width,y) def _on_canvas_clicked(self, event: Event) -> None: ''' When the canvas is clicked, I get the event x and y location. Then from there, I keep andding or subtracting 1 until the The Spacing of X modded by the event x is = to 0. Same goes for the y. Once this happens, I know the coordinates of the top left and bottom right of the cell and am able to the create a move by converting the coordinates to a coordinate plane pixel and passing that into my game logic. O nce the game logic runs,if it is a valid move, ill update my gui board, switch the score and check 2 future moves to see if there is a potential game over. I then append the tile to my self varialbe tiles to keep track of which locations have a tile. ''' width = self._canvas.winfo_width() height = self._canvas.winfo_height() spaceX=math.ceil(width/self._row) spaceY=math.ceil(height/self._col) y=int(event.x/spaceX) x=int(event.y/spaceY) y1=y+1 x1=x+1 move=self._state.place_piece(y,x) if(move!=False): self._redraw_all_spots() self._black_text.set('Black:{}'.format(self._state.countPieces('B'))) self._white_text.set('White:{}'.format(self._state.countPieces('W'))) self._turn_text.set('Turn:{}'.format(self._state._turn)) self._counter=0 if(self._state.getValidMoves()==[]): self._state._turn=self._state._opposite_turn() self._turn_text.set('Turn:{}'.format(self._state._turn)) if(self._state.getValidMoves()==[]): self.getWinner() def getWinner(self): ''' gets the winner of the game and disables mouse clicks on the board. The text label on the top is updated to the final score of the game ''' self._black_text.set("") self._white_text.set("") if(self._winner=='More'): self._turn_text.set(self._state.determineWinner()) self._canvas.bind('<Button-1>', None) else: self._turn_text.set(self._state.determineWinnerLeast()) self._canvas.bind('<Button-1>', None) def _redraw_all_spots(self) -> None: ''' Redraws all of the spots on the grid. ''' self._canvas.delete(ALL) canvas_width = self._canvas.winfo_width() canvas_height = self._canvas.winfo_height() self.createBoard(self._row,self._col) for x in range(len(self._state._board)): for y in range(len(self._state._board[0])): if(self._state._board[x][y]!=" "): self._canvas.create_oval(x*(canvas_width/self._row),y*(canvas_height/self._col),(x+1)*(canvas_width/self._row),(y+1)*(canvas_height/self._col),fill=self.fillColor(self._state._board[x][y])) def fillColor(self,color:str): if color == 'W': return 'White' else: return 'black' ############################## Optioions Menu ################################### class inputs: def __init__(self): self._optionPane = Tk() self._optionPane.title("Settings of the game ") ## self._optionPane.resizable(width=False,height=False) ## ## rows_label=Label(master=self._optionPane,text='How Many Rows?',font=('Helvetica',12)) ## rows_label.grid(row=1,column=0,padx = 10, pady = 10, ## sticky = W) ## cols_label=Label(master=self._optionPane,text='How Many Cols?',font=('Helvetica',12)) ## cols_label.grid(row=2,column=0,padx = 10, pady = 10, ## sticky = W) ## turn_label=Label(master=self._optionPane,text='Who Goes First?',font=('Helvetica',12)) ## turn_label.grid(row=3,column=0,padx = 10, pady = 10, ## sticky = W) ## corner_label=Label(master=self._optionPane,text='Which pieces starts in the top left?',font=('Helvetica',12)) ## corner_label.grid(row=4,column=0,padx = 10, pady = 10, ## sticky = W) ## winning_label=Label(master=self._optionPane,text='More pieces win,or less pieces win?',font=('Helvetica',12)) ## winning_label.grid(row=5,column=0,padx = 10, pady = 10, ## sticky = W) ## ## ## number=(4,6,8,10,12,16) turns=('B','W') winners=('More','Less') self._row=StringVar(self._optionPane) self._row.set(4) row_drop=OptionMenu(self._optionPane,self._row,*number) row_drop.pack() self._col=StringVar(self._optionPane) self._col.set(4) col_drop=OptionMenu(self._optionPane,self._row,*number) col_drop.pack() self._turn=StringVar(self._optionPane) self._turn.set("who goes first (Default B)") turn_drop=OptionMenu(self._optionPane,self._turn,*turns) turn_drop.pack() self._corner=StringVar(self._optionPane) self._corner.set("Which player will be on the top (default B)") corner_drop=OptionMenu(self._optionPane,self._corner,*turns) corner_drop.pack() self._winner=StringVar(self._optionPane) self._winner.set("Which winner wins (with more pieces / or with less )") winner_drop=OptionMenu(self._optionPane,self._winner,*winners) winner_drop.pack() self.doneButton = Button(self._optionPane , text='Lets play', command = self.settings) self.doneButton.pack() self._optionPane.grid() self._optionPane.mainloop() def settings(self): self._row=(self._row.get()) self._col=(self._col.get()) self._turn=self._turn.get() self._corner=self._corner.get() self._winner=self._winner.get() self._optionPane.destroy() if __name__ == '__main__': while True: temp=inputs() if not (temp._row=="" or temp._col=="" or temp._turn=="" or temp._corner==""): break OthelloApplication(Othello.Othello(int(temp._col),int(temp._row),temp._turn,temp._corner,[]),temp._winner).start()
''' Project 5 Othello GUI ''' import tkinter import Othello import math ##class OthelloGame: ## ## def __init__(self, game: Othello.Othello, winner :str): ## ''' ## ## Initializes the game board, and prepares the menu to the user ## , update the score of the board ## ## ''' ## ## self._state = game ## self._state._game_board() # creates a new game board size ## root_window = tkinter.Tk() root_window.title("GAME OF OTHELLO") root_window.configure(bg = 'black') # score_frame begins here score_frame = tkinter.Frame(master = root_window, bg = "orange") white_text = tkinter.StringVar() white_text.set('WHITE : 500 ') black_text = tkinter.StringVar() black_text.set('BLACK : 263') turn_frame = tkinter.Frame(master = root_window) turn_text = tkinter.StringVar() turn_text.set("TURN : PLAYER HARRIS T.") score_frame.grid(row = 0, column = 0, padx = 15, pady = 15, sticky = tkinter.S + tkinter.N, ) black = tkinter.Label(master = score_frame, textvariable = black_text, bg = "magenta", font = ('Helvetica', 18)) black.grid(row = 1, column = 0,padx = 15, pady = 15, sticky = tkinter.W) white = tkinter.Label(master = score_frame, textvariable = white_text, bg = "green",font = ('Helvetica', 18)) white.grid(row = 2, column = 0 ,padx = 15, pady = 15, sticky = tkinter.W) turn = tkinter.Label(master = score_frame, textvariable = turn_text, bg = "red", font = ('Helvetica', 18)) turn.grid(row = 1, column = 5, rowspan = 3,columnspan = 3, padx = 15, pady = 15) # score_board ends # canvas begins here canvas = tkinter.Canvas( master = root_window, width = 600, height = 600, bg = "yellow") canvas.grid( row = 1, column = 0, padx = 10, pady = 10, sticky = tkinter.N + tkinter.S + tkinter.E + tkinter.W) score_frame.rowconfigure(0, weight = 1) score_frame.columnconfigure(0, weight = 0) score_frame.columnconfigure(1, weight = 0) score_frame.columnconfigure(2, weight = 0) root_window.rowconfigure(1,weight=1) root_window.columnconfigure(0, weight = 1) def _on_canvas_sized(): print("Canvas Resized") def _on_canvas_clicked(): print("mouse button was clicked") # Draw board row = 8 col = 8 width = canvas.winfo_width() height = canvas.winfo_height() spaceX=math.ceil(width/row) spaceY=math.ceil(height/col) for x in range((spaceX),width+spaceX,(spaceX)): canvas.create_line(x,0,x,height, fill = "black") for y in range((spaceY),height+spaceY,(spaceY)): canvas.create_line(0,y,width,y, fill= "black") # canvas ends here root_window.mainloop()
# bhaskar directions=[[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1]] def print_board(temp_board): for i in range(0,len(temp_board)): for j in range(0,len(temp_board[0])): print(temp_board[i][j], end=' ') print("") def get_opposite_of(color): if color == "B": return "W" else: return "B" def get_count(board, color): count = 0 for i in range(0,len(board)): for j in range(0,len(board[i])): if board[i][j] == color: count += 1 return count def is_valid_rows_or_column(real_value, entered_value): if (entered_value >= 4 and entered_value <= real_value): return True else : return False def in_bound(board,i,j): if((i >=0 and i < len(board)) and (j >=0 and j < len(board[0]))): return True else: return False def is_move_valid(board,i,j,color): valid_boxes = [] for a,b in directions: x,y = i,j x += a y += b if(in_bound(board,x,y) and board[x][y] == get_opposite_of(color)): x += a y += b while (in_bound(board,x,y) and (board[x][y] == get_opposite_of(color))): x+=a y+=b if (in_bound(board,x,y) and board[x][y] == color): while True: x -= a y -= b valid_boxes.append([x,y]) if x==i and y==j: break return valid_boxes def get_winner(board,winning_criteria): if(winning_criteria == ">"): if (get_count(board,"B") > get_count(board,"W")): return "B" elif (get_count(board,"B") == get_count(board,"W")): return "NONE" else: return "W" else: if (get_count(board,"B") < get_count(board,"W")): return "B" elif (get_count(board,"B") == get_count(board,"W")): return "NONE" else: return "W" def is_empty(board): for x in range(0,len(board)): for y in range(0,len(board[0])): if board[x][y] == ".": return True continue return False while True: rows = int(input()) if ((rows >= 4) and (rows <= 16) and (rows%2==0)): break else: print("INVALID") while True: columns = int(input()) if ((columns >= 4) and (columns <= 16) and (columns%2==0)): break else: print("INVALID") while True: first_mover = input() if (first_mover == "B" or first_mover == "W"): break else: print("INVALID") while True: top_left_corner = input() if (top_left_corner == "B" or top_left_corner == "W"): break else: print("INVALID") while True: winning_criteria = input() if (winning_criteria == ">" or winning_criteria == "<"): break else: print("INVALID") turn = first_mover board = [] count = 0 for i in range(0,rows): board.append([]) for j in range(0,columns): board[i].append(".") board[int(rows/2)-1][int(columns/2)-1] = top_left_corner board[int(rows/2)][int(columns/2)] = top_left_corner board[int(rows/2)-1][int(columns/2)] = get_opposite_of(top_left_corner) board[int(rows/2)][int(columns/2)-1] = get_opposite_of(top_left_corner) while True: print("B: %d W: %d" %(get_count(board, "B"),get_count(board,"W"))) print_board(board) boxes = [] for i in range(0,len(board)): for j in range(0,len(board[0])): if(is_move_valid(board,i,j,turn)): boxes.append([i+1,j+1]) if not is_empty(board): print("WINNER:", get_winner(board,winning_criteria)) break if (boxes == []): count += 1 if count==2: print("WINNER:", get_winner(board,winning_criteria)) break turn = get_opposite_of(turn) continue print("TURN: ", turn) while True: str = input() str = str.split() x = int(str[0]) y = int(str[1]) if([x,y] in boxes): moves = is_move_valid(board,x-1,y-1,turn) print("VALID") for p,q in moves: board[p][q] = turn turn = get_opposite_of(turn) count = 0 break else: print("INVALID")
from collections import namedtuple Bedroom = namedtuple('Bedroom', 'room_num ') Reservation = namedtuple('Reservation', 'room_num checkinDate checkoutDate lastName firstName') def stage3(): list_of_bedrooms = [] list_of_reservations = [] reservation_dict = {} bb = open ('stage3.txt', 'r') lines = bb.readlines() #outfile = write('s', 'w') ? for line in lines: x = line.split() #print(x) if x[0].upper() == 'PL': print(line[3:]) elif x[0].upper() == 'NB': list_of_bedrooms.append(x[1]) elif x[0].upper() == 'RR': if int(x[1]) in reservation_dict: reservation_dict.pop(int(x[1])) #list_of_reservations.remove(reservation_dict[x[1]]) else: print("Sorry, can't cancel reservation; no confirmation number" ,x[1]) elif x[0].upper() == 'NR': if x[1] in list_of_bedrooms: r = Reservation(x[1], x[2], x[3], x[4], x[5]) list_of_reservations.append(r) confirmation_num = 1 for i in list_of_reservations: reservation_dict[confirmation_num] = i confirmation_num += 1 print("Reserving room", x[1], "for", x[4], x[5], "-- Confirmation #", confirmation_num - 1) print("\t(arriving", x[2], ", departing", x[3], ")") else: print("Sorry; can't reserve room", x[1],"; room not in service") elif x[0].upper() == 'LR': print ('Number of reservations:', len(list_of_reservations)) print('No. Rm. Arrive Depart Guest') print('------------------------------------------------') confirmation = 0 for k,v in reservation_dict.items(): #print("Reserving ", v.room_num, "arriving from ", v.checkinDate,"departing ", v.checkoutDate, "in the name of ", v.lastName, v.firstName, "confirmation #", k) print("{:3d} {:3s} {:10s} {:10s} {:15s}".format(k,v.room_num,v.checkinDate, v.checkoutDate, v.lastName +" " + v.firstName)) stage3()
# Shambhu Thapa 10677794 #Project 3: Ride Across The River import mymap import generator def user_interface(): ''' interact betweeen different modules and produce the output ''' try: locations = get_locations() data = mymap.get_result(mymap.build_search_url(locations)) instructions = user_command() if len(locations) >= 2 and len(instructions) <=5 : handle_output(data, instructions) else: print("You must specify at least two locations and maximum 5 outputs. Please try again later\n") except: print("MAPQUEST ERROR") finally: print() print(" Directions Courtesy of MapQuest; Map Data Copyright OpenStreetMap Contributors") def get_locations()->list: ''' gets an input for locations from the user ''' result = list() num_of_locations = int(input()) for item in range(num_of_locations): location = input() result.append(location) return result def user_command()->list: ''' when the user wants to see the result they want to , this function ask the user the number of results that like to see ''' num_of_results = int(input()) result = list() for items in range(num_of_results): user_result = input() result.append(user_result) return result def handle_output(data :'json', instruction:list): for item in instruction: if item == 'STEPS': generator.Steps(data).control() if item == 'TOTALDISTANCE': generator.Distance(data).control() if item == 'TOTALTIME': generator.Time(data).control() if item == 'LATLONG': generator.Latlong(data).control() if item == 'ELEVATION': generator.Elevation(data).control() if __name__ == "__main__": ''' handle the main interface of the map ''' user_interface()
### If you want to run the code, you should comment out the problems you haven't ### done yet so you can't see the answers for them. ### Hints for each problem are at the bottom of this file ## ### 1. What's the output of the following code? ##try: ## try: ## a = 5 ## b = 7 ## c = "five" ## d = "seven" ## print(a*c) ## print(c+d) ## except: ## print(b*c) ## else: ## print(c*d) ## finally: ## print("first finally") ##except: ## print("second except") ##else: ## print("second else") ##finally: ## print("second finally") ## ####ANSWERS ####fiveseven ## ## 2. Imagine you have 3 modules as seen below ##"first.py" ##import second ##print("1") ##if __name__ == '__main__': ## print("first main") ## ##"second.py" ##import third ##print("2") ##if __name__ == '__main__': ## import first ## print("second main") ## ##"third.py" ##print("3") ##if __name__ == '__main__': ## import second ## print("third main") ## ## What is the output if ## a) first.py is run, ## b) second.py is run, and ## c) third.py is run? ## ## ## 3. What's wrong with the following class? Just try to fix the class, ## don't fix anything in the if name = main block ##class Person: ## def __init__(self, name): ## self.name = name ## self.age = 0 ## def grow_up(self): ## self.age += 1 ## ##if __name__ == '__main__': ## a = Person("Alex") ## a.grow_up() # 4. Write a function that takes a nested list of integers and returns the # minimum. Below is a function definition but you need to fill in the body. # Remember that a nested list of integers means that every element in the list # is either an int or a nested list of ints. ##def find_min(l: list) -> int: ## num_list = [] ## ## for num in l: ## if type(num) == list: ## num_list.append(find_min(num)) ## else: ## num_list.append(num) ## ## return min(num_list) # 5. What does the underscore before a function mean? '''It means that it is a privaate code only for the programmer to use''' # 6. What does the if __name__ == '__main__' statement mean? '''If you want your program to run automatically without importing, use this. or the code under this will ctreate whatever it has as a module''' ## Read all his code examples for review. If you understand everything he ## wrote in his code examples, as well as what you did in projects, ## you should be fine. ## Things to look over that I didn't go in depth about: ## the sockets, protocol, and classes code examples. ## Make sure you're able to write your own classes! ## On Wednesday I'll be going over any questions you might have, so make sure ## to bring them! ## Hints ## 1. Remember what each word means. When do you do the except and else ## blocks? When in doubt, always do finally! ## ## 2. If a module is loaded once through import, it doesn't load again, even if ## the same import is called again. Python is smart enough to remember what ## modules have been loaded already ## ## 3. Remember what we went over in class about classes. What always has to be ## inside a class? There's 2 problems only, but they might be found in multiple ## places ## ## 4. With recursion, always start small. How do you find the minimum of a simple ## list of integers? After you get that, seperate it into the differnt possible ## cases and deal with each seperately.
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1+class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) # Code ends here # -------------- # Code starts here courses = {'Math':65,'English':70,'History':80,'French':70,'Science':60} print(courses) total = courses['Math']+courses['English']+courses['French']+courses['Science']+courses['History'] print(total) percentage = (total/500)*100 print(percentage) # Code ends here # -------------- # Code starts here mathematics = {'Geoffrey Hinton':78,'Andrew Ng':95,'Sebastian Raschka':65,'Yoshua Benjio':50,'Hilary Mason':70,'Corinna Cortes':66,'Peter Warden':75} marks = mathematics.values() highest_marks = max(marks) for name,marks in mathematics.items(): if marks == highest_marks: topper = name print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here names = topper.split() first_name = names[0] last_name = names[1] full_name = last_name+" "+first_name certificate_name = full_name.upper() print(certificate_name) # Code ends here
def main(): out = "" while True: try: string = input().strip() except EOFError: break; out = out + string print(out, end='') main()
# -*- coding: utf-8 -*- """ Data Incubator milestone project: stock chart """ from datetime import datetime, timedelta #from pandas import DataFrame import yfinance as yf from math import pi from calendar import monthrange import streamlit as st from pandas_datareader import data as pdr import plotly.graph_objects as go yf.pdr_override() st.title("Shahar's milestone project") with st.form("form"): symbol = st.text_input("Ticker?") date = st.date_input('Click month/year to scroll; select any day on require month') adjusted = st.checkbox("Display adjusted prices") month = date.month year = date.year submitted = st.form_submit_button("Submit") if submitted: start = datetime(year, month, 1) end = datetime(year, month, monthrange(year, month)[1]) data = pdr.get_data_yahoo(symbol, start=start, end=end) if adjusted: close = data['Adj Close'] else: close = data['Close'] title = symbol.upper() + " share prices " + str(month)+"/"+str(year) candlestick = go.Candlestick(x=data.index, open=data.Open, high=data.High, low=data.Low, close=close) fig = go.Figure(data=[candlestick]) fig.update_layout(title=title, yaxis_title='Price [US$]', xaxis_rangeslider_visible=False) st.plotly_chart(fig)
""" This little program shows the use of the enumerate() - operator """ def enuming(): t = [6, 7, 8, 19, 42] for p in enumerate(t) print(p) def enuming2(): x = [192, 135, 643, 346] for i, v in enumerate(x): print("i = {}, v = {}".format(i,v)) """ range() isn't used widely in python!: >>> list(range(0,10,2)) >>> [0, 2, 4, 6, 8] """
''' Exercise 3 Note: This exercise should be done using only the statements and other features we have learned so far. Write a function that draws a grid like the following: + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + Hint: to print more than one value on a line, you can print a comma-separated sequence of values: print('+', '-') By default, print advances to the next line, but you can override that behavior and put a space at the end, like this: print('+', end=' ') print('-') The output of these statements is '+ -' on the same line. The output from the next print statement would begin on the next line. Write a function that draws a similar grid with four rows and four columns. ''' plus = '+'; bar = '-'; side = '|'; space = ' ' header = plus + (bar *4) + plus + (bar*4) + plus sides = side + (space*4) + side + (space*4) + side def two_by_four(): print(header + "\n"+((sides+"\n")*4) + header + "\n"+((sides+"\n")*4) + header) def four_by_four(): top = '+----+----+----+----+' + '\n'; sides = '| | | | |' + '\n' print(((top + sides*4)*2) + top + (sides*4 + top)+ (sides*4 + top)) ''' In [55]: two_by_four() +----+----+ | | | | | | | | | | | | +----+----+ | | | | | | | | | | | | +----+----+ In [56]: four_by_four() +----+----+----+----+ | | | | | | | | | | | | | | | | | | | | +----+----+----+----+ | | | | | | | | | | | | | | | | | | | | +----+----+----+----+ | | | | | | | | | | | | | | | | | | | | +----+----+----+----+ | | | | | | | | | | | | | | | | | | | | +----+----+----+----+ In [57]: '''
def knapsack(items, i, size): """items: sequence of weights, i: item you're considering; i==len(items)->done size: size of knapsack""" memo = {0: [0]} for i in range(len(items)): memo[i+1] = [] for weights in memo[i]: memo[i+1].append(weights) if weights + items[i] <= size: memo[i+1].append(weights + items[i]) # see the max size of len(items) return max(memo[len(items)]) def knapsack_v2(sizes, values, knapsack_size): """sizes: array of sizes of items values: array of values of items sizes[i] corresponds to weight of item at values[i] knapsack_size: how much your knapsack can carry""" #memo[item you're considering][total weight of items so far] memo = {} #Base case memo[len(sizes)] = [0 for s in range(knapsack_size+1)] #In topologically sorted order for i in reversed(range(len(sizes))): memo[i] = [0 for s in range(knapsack_size+1)] for s in range(knapsack_size+1): if s >= sizes[i]: memo[i][s] = max(memo[i+1][s], memo[i+1][s-sizes[i]] + values[i]) else: memo[i][s] = memo[i+1][s] return max(memo[0]) items = [4, 2, 3] values = [10, 4, 7] size = 5 print(knapsack(items, 0, size)) print() print(knapsack_v2(items, values, size))
class Node: # node for linked list def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def push(self, key): # push to the front of the linked list new_head = Node(key) new_head.next = self.head self.head = new_head def pop(self): # pop the first element of the linked list val = self.head.value self.head = self.head.next return val def search(self, key): # go through the linked list of tuples and try to find the key # if key is found, return val, else return None current = self.head while (current): if current.value[0] == key: return current.value[1] current = current.next return None def delete(self, key): ''' go through the linked list, delete the node with given key and return value associated w/ the key, else return None ''' current = self.head prev = None while current: if current.value[0] == key: if not prev: self.head = self.head.next return current.value[1] else: val = current.value[1] prev.next = current.next return val prev = current current = current.next return None def __str__(self): ''' list string representation''' s = '[' current = self.head while current: s += str(current.value) if current.next: s += ', ' current = current.next s += ']' return s class HashTable: # make sure our hash table doesn't get smaller than this symbolic constant BASE_SIZE = 8 def __init__(self): self.array = [] self.size = self.BASE_SIZE self.elements = 0 for i in range(self.size): self.array.append(LinkedList()) def hash(self, key, size): ''' basic hash function for strings ''' h = 0 for c in key: h *= 256 h += ord(c) h %= size return h def resized_array(self, size): # create a new array of linked lists of size array = [] for i in range(size): array.append(LinkedList()) return array def rehash(self, new_array, new_size): # rehash the elements in size.array with new hash function # put those elements in new_array # iterate through all of the linked lists for i in range(self.size): llist = self.array[i] # iterate through all of the elements in the linked lists current = llist.head while current: # rehash h = self.hash(current.value[0], new_size) # put the (key,value) onto the linked list at new[h] (new_array[h]).push(current.value) current = current.next def resize(self): ''' If self.elements / self.size >= 1 (load factor), then you want to double the size of it if load factor == 0.25, then shrink it by half in both cases, rehash all of the elements''' load_factor = float(self.elements) / self.size if load_factor >= 1: new_array = self.resized_array(2 * self.size) self.rehash(new_array, 2 * self.size) self.array = new_array self.size *= 2 elif load_factor <= 0.25: new_array = self.resized_array(self.size // 2) self.rehash(new_array, self.size // 2) self.array = new_array self.size = self.size // 2 def insert(self, key, value): ''' insert key, val pair into our chained hash table ''' if value == None: raise Exception('value cannot be None') ind = self.hash(key, self.size) (self.array[ind]).push((key, value)) self.elements += 1 self.resize() def search(self, key): ''' search for the key, returns val if found, None if not found ''' ind = self.hash(key, self.size) return (self.array[ind]).search(key) def delete(self, key): ''' deletes key and returns value if it exists, else returns None and doesn't do anything ''' ind = self.hash(key, self.size) val = (self.array[ind]).delete(key) if val: self.elements -= 1 return val def __str__(self): s = "{" for i, llist in enumerate(self.array): s += str(llist) if i != len(self.array) - 1: s += ', ' s += '}' return s ''' s = LinkedList() for i in range(10): s.push(i) print(s) ''' ht = HashTable() strs = ["hello", "world", "space", "cats", "dogs", "life", "chaos", "suffering", \ "patience", "sucking", "overcome", "why", "first time"] for i, string in enumerate(strs): ht.insert(string, i) print(ht) print('chaos', ht.search('chaos')) print('space', ht.search('space')) print('meaning', ht.search('meaning')) print(ht.delete('chaos')) print(ht.delete('hello')) print(ht)
import time # cheap way to do squares squares = dict([(c, int(c)**2) for c in "0123456789"]) # list of numbers in the never-ending sequence bad_nums = sorted([4, 16, 37, 58, 89, 145, 42, 20]) def midpoint(low, high): ''' gets the midpoint of two ints. If the ints sum to an odd number, we round using Python's integer division. low: int; lower int high: int; higher int returns: int; the midpoint (low + high)/2 ''' # calculate to avoid overflow return (low + ((high - low)/2)) def bin_search(target, lst, low, high): ''' binary search a list for a number (either a float or int) between indices low and high (inclusive) target: int or float; number to search for lst: list of ints or floats; list to search in low: int; lower bound on index to search for high: int; upper bound on index to search for returns: bool; True if the target was found, False otherwise ''' if low == high: return(lst[low] == target) while low <= high: mid = midpoint(low, high) elt = lst[mid] if elt == target: return True elif elt < target: low = mid + 1 elif elt > target: high = mid - 1 return False def is_happy(n): ''' determine if a number is happy or not n: int; the number in question returns: bool; True if the number is happy, False otherwise ''' num = n # testing three conditions #while (num > 1) and (not bin_search(num, bad_nums, 0, 7)): #while (num > 1) and (num != 4): while (num > 1) and (not (num in bad_nums)): num = sum(squares[digit] for digit in str(num)) return (num == 1) def main(): # measure real and CPU time real_time = time.time() cpu_time = time.clock() for n in xrange(1,10000+1): print("%d\t%s" %(n, is_happy(n))) real_time = time.time() - real_time cpu_time = time.clock() - cpu_time print("\n\n") print("Real time: %f" %real_time) print("CPU time: %f" %cpu_time) if __name__ == '__main__': main()