text
stringlengths
37
1.41M
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here pReversedHead = None pNode = pHead pPrev = None while(pNode != None): pNext = pNode.next if(pNext == None): pReversedHead = pNode pNode.next = pPrev pPrev = pNode pNode = pNext return pReversedHead node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 s = Solution() print(s.ReverseList(node1).val)
# -*- coding:utf-8 -*- class Solution: def VerifySquenceOfBST(self, sequence): # write code here if not sequence: return False root = sequence[-1] left = [] right = [] # 在二叉搜索树中左子树节点的值小于根节点的值 for i in range(len(sequence)): if sequence[i] < root: left.append(sequence[i]) else: break # 在二叉搜索树中右子树节点的值大于根节点的值 for j in range(i, len(sequence)-1): if sequence[j] < root: return False else: right.append(sequence[j]) # 判断左子树是不是二叉搜索树 left_flag = True if i > 0: left_flag = self.VerifySquenceOfBST(left) # 判断右子树是不是二叉搜索树 right_flag = True if i < len(sequence)-1: right_flag = self.VerifySquenceOfBST(right) return left_flag and right_flag s = Solution() # print(s.VerifySquenceOfBST([5,7,6,9,11,10,8])) # print(s.VerifySquenceOfBST([4,8,6,12,16,14,10])) print(s.VerifySquenceOfBST([7,4,6,5]))
import speech_recognition as sr from gtts import gTTS import os import playsound import requests import time import random import wikipedia import webbrowser def hearing(): r = sr.Recognizer() voice_data = " " with sr.Microphone() as source: print("Listening: ") audio = r.listen(source) try: voice_data = r.recognize_google(audio) # converting speech to text print(voice_data) except Exception as e: print(e) return voice_data.lower() def speak(voice_data): audio = gTTS(text = voice_data, lang = "en") # converting text to audio random_num = random.randrange(9999999) audio_file = "audio" + str(random_num) + ".mp3" # saving audio file audio.save(audio_file) playsound.playsound(audio_file) # playing audio file os.remove(audio_file) # deleting audio file def respond(voice_data): speak(voice_data) print(voice_data) def main(): respond("Hey, what's up?") # greeting voice_data = hearing() if voice_data == "who are you" or voice_data == "what is your name" or voice_data == "what's your name": respond("I'm Athena.") # gives introduction if voice_data == "what time is it" or voice_data == "what is the time" or voice_data == "tell me the time": local_time = time.asctime() local_time = local_time[11:19] time_words = f"{local_time[:2]} hours and {local_time[3:5]} minutes and {local_time[6:]} seconds." respond(time_words) # tells you time if "search google for" in voice_data: # google search query = voice_data.split() query = query[3:] respond("Opening browser.") webbrowser.open("https://www.google.com/search?q=" + "%20".join(query)) if "search wikipedia for" in voice_data: # searches wikipedia voice_data = voice_data.split() results = wikipedia.search(voice_data[3:]) respond(f"Here is what I found for {voice_data[3:]}.") for i in range(len(results)): print(f"{i+1}. {results[i]}") respond("What do you want to search in particular? Enter index of the result") choice = int(input("Enter index: ")) print(wikipedia.summary(results[choice-1]) + "\n----") page_url = wikipedia.page(results[choice-1]).url print(f"Page url: {page_url}") respond("Would you like me to open the page?") choice_2 = input("Enter (y/n): ") if choice_2 == "y": webbrowser.open(page_url) else: respond("Ok!") if voice_data == "rock paper scissors": # plays rock paper scissors speak("How many rounds you want to play?") rounds = int(input("How many rounds you want to play? ")) computer, user = 0, 0 for i in range(rounds): comp_turn = random.choice(["rock", "paper", "scissors"]) print("Your turn!") user_turn = hearing() if comp_turn == "rock" and user_turn == "scissors": computer += 1 elif comp_turn == "paper" and user_turn == "rock": computer += 1 elif comp_turn == "scissors" and user_turn == "paper": computer += 1 elif user_turn == "rock" and comp_turn == "scissors": user += 1 elif user_turn == "paper" and comp_turn == "rock": user += 1 elif user_turn == "scissors" and comp_turn == "paper": user += 1 else: computer += 0 user += 0 if computer == user: respond("Draw!") elif computer > user: respond("You lose!") else: respond("You won!") if voice_data == "chuck norris": # gets random chuck norris joke response = requests.get("https://api.chucknorris.io/jokes/random") data = response.json() respond(data["value"]) if voice_data == "advice" or voice_data == "give me an advice": response = requests.get("https://api.adviceslip.com/advice") data = response.json() respond(data["slip"]["advice"]) # gives random advice if voice_data == "goodbye" or voice_data == "bye" or voice_data == "quit": respond("See ya later!") # quits the program exit() main()
#By Prathyusha Theerdhala import random from time import sleep choice=["Charmander","Bulbasaur","Squirtle"] cpu=random.choices(choice) player=False while player ==False: print("Welcome to the Pokémon Battleground!") print("\nAre you ready to choose your Pokémon?") player=str(input("Which Pokémon do you want to choose?\nCharmander\nSquirtle \nBulbasur \nStop")) print("The computer chose its Pokémon") if player==cpu: print("\nPlease wait...You will be able to see your result in a few seconds...") sleep(2) print("Tie!") elif player=="Charmander": if cpu=="Squirtle": print("\nPlease wait...You will be able to see your result in a few seconds...") sleep(2) print("Sorry!You lost!") else: print("\nPlease wait...You will be able to see your result in a few seconds...") sleep(2) print("You win!") elif player=="Squirtle": if cpu=="Bulbasur": print("\nPlease wait...You will be able to see your result in a few seconds...") sleep(2) print("Sorry!You lost!") else: print("\nPlease wait...You will be able to see your result in a few seconds...") sleep(2) print("You win!") elif player=="Bulbasur": if cpu=="Charmander": print("\nPlease wait...You will be able to see your result in a few seconds...") sleep(2) print("Sorry!You lost!") else: print("\nPlease wait...You will be able to see your result in a few seconds...") sleep(2) print("You win!") elif player =="Stop": print("Thank you for playing!") break else: print("That's not a valid play!") player=False
class Botilleria: def __init__(self,marca,litros,precio): self.marca = marca self.litros = litros self.precio = precio def __str__(self): return "{} de {} litro, tiene un precio de {} pesos.".format(self.marca,self.litros,self.precio) class Cerveza(Botilleria): tipo = "" def __str__(self): return "{} {} de {} litro, tiene un precio de {} pesos.".format(self.tipo,self.marca,self.litros,self.precio) class Vino(Botilleria): tipo = "" def __str__(self): return "{} ,{} de {} litro, tiene un precio de {} pesos.".format(self.tipo,self.marca,self.litros,self.precio) class Aguas(Botilleria): tipo = "" def __str__(self): return "{} {} de {} litro, tiene un precio de {} pesos.".format(self.tipo,self.marca,self.litros,self.precio)
str=input("Enter word") c=0 n=input("enter letter to be count") for item in str: if item!=n: continue else: c=c+1 print(c)
from abc import ABC,abstractmethod class shape(ABC): @abstractmethod def area(self): return 0 class rectange(): def __init__(self,l,b): self.l=l self.b=b def area(self): return self.l*self.b class square(): def __init__(self,s): self.s=s def area(self): return self.s*self.s rec=rectange(2,3) square=square(2) print(rec.area(),"and",square.area())
list = [2, 4, 6, 8, 10] for item in list: if item > 4: print("grater then 2") list2 = ['Elton', 'Souza'] for name in list2: if not name == "Elton": print(name)
""" 4. Given dictionary representing a student name as a key and corresponding value is a grade which he obtained in different subjects. WAP update each dict value with average score obtained by each student respectively. scores = {Student1: [65, 68, 59, 52, 69, 65, 55, 59], Student2: [60, 64, 60, 60, 88, 64, 68, 75], Student3: [59, 72, 64, 62, 66, 68, 72, 73], Student4: [82, 62, 61, 54, 71, 89, 75, 73] } """ scores = {"Student1": [65, 68, 59, 52, 69, 65, 55, 59], "Student2": [60, 64, 60, 60, 88, 64, 68, 75], "Student3": [59, 72, 64, 62, 66, 68, 72, 73], "Student4": [82, 62, 61, 54, 71, 89, 75, 73] } for ch in scores: num = 0.0 length = len(scores[ch]) for val in scores[ch]: num = num + val Average = num/length scores[ch] = Average print scores
""" 13. Given a string of even length and print the output as string contains last half added with first half of the given string """ Input_str = raw_input("Enter a given length string: ") length = len(Input_str) print length num = 0 first = ' ' last = ' ' for ch in Input_str: if ((length/2)-1) > num: first = first + ch else: last = last + ch num = num + 1 Output_str = last + first print Input_str print Output_str
#!/usr/bin/env python import json,sys json_file = open(sys.argv[1], "r+") doc = json.load(json_file) keys = sys.argv[2].split('.') def search(d, keys): if len(keys) == 1: return d[keys[0]] else: return search(d[keys[0]], keys[1:]) print search(doc, keys)
# Given a matrix representation of plot of land, # find the sizes of all the ponds in the matrix # 0 indicates water. Pond is the region of water connected vertically, horizontally, or diagonaly def pond_region(grid, x, y): print(x,y) if x < 0 or y < 0 or x >= len(grid) or y >= len(grid[0]): return 0 # no water if grid[x][y] != 0: return 0 # this x,y has been checked so mark as visited grid[x][y] = -1 print(x, y) print(grid) size = 1 for row in range(x-1, x+2): for col in range(y-1, y+2): if x != row or y != col: size += pond_region(grid, row, col) print(size) return size def find_ponds(grid): result = [] for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: result.append(pond_region(grid, i, j)) return result if __name__=="__main__": grid = [[0, 2, 1, 0], [0, 1, 0, 1], [1, 1, 0, 1], [0, 1, 0, 1]] pond_sizes = find_ponds(grid) print ', '.join(map(str, pond_sizes))
''' find the k smallest integers froma given array''' ''' Solution 1: Sort the array and return the first k elements Solution 2: Use a BST and do in order traversal to find first k elements Solution 3: Selection rank algorithm Selection Rank 1. Pickarandomelementinthearrayanduseitasa"pivot:'Partitionelementsaroundthepivot,keeping track of the number of elements on the left side of the partition. 2. Ifthereareexactlyielementsontheleft,thenyoujustreturnthebiggestelementontheleft. 3. Ifthele sideisbiggerthani,repeatthealgorithmonjustthele partofthearray. 4. Iftheleftsideissmallerthani,repeatthealgorithmontheright,butlookfortheelementwithrank i - leftSize. ''' import os import random def smallestK(array, k): if k <= 0 or k > len(array): return None # get an item with rank k-1 threshold = rank(array, k-1) # copy elements smaller than the threshold smallest = [] count = 0 for a in array: # copy elements that are only smaller than threshold # prevents filling up smallest with duplicates if a < threshold and count < k: smallest.append(a) count += 1 return smallest # find a value in array with rank k def rank(array, k): if k >= len(array): return -1 return rankHelper(array, k, 0, len(array)-1) def randomNum(lower, higher): return random.randint(lower, higher) def partition(array, start, end, pivot): left = start right = end middle = start while (middle <= right): if (array[middle] < pivot): # middle is smaller than pivot # left is either small or equal to pivot # so swap middle and left swap(array, middle, left) middle += 1 left += 1 elif (array[middle] > pivot): # swap middle with right swap(array, middle, right) right -= 1 elif array[middle] == pivot: # middle is equal to pivot move to next middle middle += 1 # return sizes of left and middle return (left-start, right-left+1) def swap(array, left, right): temp = array[left] array[left] = array[right] array[right] = temp # Find value with rank k in sub array between start and end. def rankHelper(array, k, start, end): # partition array around a pivot randnum = randomNum(start, end) pivot = array[randnum] # partition the array leftSize, middleSize = partition(array, start, end, pivot) if (k < leftSize): # rank k is on left half return rankHelper(array, k, start, start+leftSize-1) elif (k < leftSize+middleSize): # rank k is in the middle return pivot # middle is all pivot values else: # rank k is on the right return rankHelper(array, k-leftSize-middleSize, start+leftSize+middleSize, end)
# given two sorted arrays find the median of these two sorted arrays (combined) ''' solution: Median is the middle element 1. divide the arrays as left part and right part 2. criteria for the left part and right part (includes both A and B's left part) a. len(left_part) = len(right_part) b. max(left_part) <= min(right_part) 3. the median will be (max(left_part) + min(right_part)) / 2 NOTE: array A is split at i th position and array B is split at j th position i + j = m - i + n - j (or m-i+n-j+1) m = size(A) n = size(B) if n >= m, i = 0 to m and j = (m+n+1)/2 - i and B[j-1] <= A[i] and A[i-1] <= B[j] ''' # Time Complexity: O(log(min(m,n))) import os def median(A, B): m = len(A) n = len(B) if m > n: # switch them A, B, m, n = B, A, n, m if n == 0: raise ValueError imin = 0 imax = m half_len = (m + n + 1) / 2 while (imin <= imax): i = (imin + imax) / 2 j = half_len - i if i < m and B[j-1] > A[i]: # i is too small, increase it imin = i + 1 elif i > 0 and A[i-1] > B[j]: # i is too big, must decrease it imax = i - 1 else: # i is perfect if i == 0: max_of_left = B[j-1] elif j == 0: max_of_left = A[i-1] else: max_of_left = max(A[i-1], B[j-1]) if (m+n)%2 == 1: return max_of_left if i == m: min_of_right = B[j] elif j == n: min_of_right = A[i] else: min_of_right = min(A[i], B[j]) return (max_of_left + min_of_right)/2.0
# implement multiply, subtract and divide operations for integers # use only the add operator import os def negate(num): neg = 0 if num < 0: newsign = 1 else: newsign = -1 while (num != 0): neg += newsign num += newsign return neg def subtract(a, b): return a + negate(b) def multiply(a, b): if a < b: return(multiply(b, a)) sum = 0 runner = b while (runner > 0): sum = sum + a runner = subtract(runner, 1) if b < 0: sum = negate(sum) return sum def absolute(num): if num < 0: return negate(num) else: return num def division(a, b): if (b == 0): return -1 # or throw an exception absa = abs(a) absb = abs(b) product = 0 numerator = 0 while (product + absb <= absa): product += absb numerator += 1 if ((a < 0 and b < 0) or (a > 0 and b > 0)): return numerator else: return negate(numerator)
### peaks and valleys # sort an input array into an alternating sequence of peaks and valleys import os import sys def swap(arr, left, right): temp = arr[left] arr[left] = arr[right] arr[right] = temp # Approach One: # Sort the array and swap every element with its right neighbor starting index 1 and increment 2 def peaksAndValleys(arr): arr.sort() for i in range(1, len(arr), 2): swap(arr, i-1, i) # Approach two: # No sorting required. # Place the peaks in their appropriate place so that valleys are automatically in their place def sortValleyPeak(arr): for i in range(1, len(arr), 2): biggestIndex = maxIndex(arr, i-1, i, i+1) if i != biggestIndex: swap(arr, i, biggestIndex) def maxIndex(arr, a, b, c): l = len(arr) aValue = -1 * sys.maxint bValue = -1 * sys.maxint cValue = -1 * sys.maxint if a >= 0 and a < l: aValue = arr[a] if b >= 0 and b < l: bValue = arr[b] if c >= 0 and c < l: cValue = arr[c] maxValue = max(aValue, max(bValue, cValue)) if maxValue == aValue: return a elif maxValue == bValue: return b else: return c if __name__=="__main__": arr = [9, 1, 0, 4, 8, 7] peaksAndValleys(arr) print(arr) sortValleyPeak(arr) print(arr)
''' given an array of number and a value, find all subsequences that add up to that value ''' # NP complete problem Subset sum # Dynamic programming can also be used import os import numpy as np def isSubsetSumDP(array, sum): n = len(array) # The value of subset[i][j] will be true if there is a subset of array[0..j-1] with sum equal to i subset = np.zeros((sum+1, n+1), dtype=bool) # if sum is 0, then answer is true subset[0][i] = True for i in range(n+1) # if sum is not 0, and array is empty, then answer is false subset[i][0] = False for i in range(1, sum+1) # fill the subset table in bottom up manner for i in range(1, sum+1): for j in range(1, n+1): subset[i][j] = subset[i][j-1] if i >= array[j-1]: subset[i][j] = subset[i][j] or subset[j-1][j-1] return subset[sum][n] # recursive solution def isSubsetSumRecursive(array, sums): n = len(array) if sums == 0: return True if len(array) == 0 and sums != 0) return False # if last element is greater than sum, then ignore it if (array[n-1] > sums): return isSubsetSumRecursive(array[0:n-2], sums) # else check if sum can be obtained by any of the following # 1. including the last element # 2. excluding the last element return isSubsetSumRecursive(array[0:n-2], sums) or isSubsetSumRecursive(array[0:n-2], sums-array[n-1])
# you are given an array of integers (both +ve and -ve). Find the contiguous sequence with the largest sum # idea is to sum up subsequences of positive and negative numbers # example: (2, 3, -8, -1, 2, 4, -2, 3)'s sum array is (5, -9, 6, -2, 3) # now examine this array from first element # 1. take 5 as maxSum and sum. # 2. now add -9 to sum. If sum > maxSum then set maxSum to sum, else reset sum import os def getMaxSum(arr): maxSum = 0 sums = 0 for i in range(0, len(arr)): sums = sums + arr[i] if (maxSum < sums): maxSum = sums elif (sums < 0): sums = 0 return maxSum if __name__=="__main__": arr = [2, 3, -8, -1, 2, 4, -2, 3] print(getMaxSum(arr))
# a=[3,34,1,55,23,49] # print(34 in a) # a =(True and False) # b =(True and True) # c =(False or True) # c1 =(True or False) # print(a,b,c1,c) list1=[] list2=[] list3=list1 if(list1==list2): print(True) else: print(False) if(list1 is list2): print(True) else: print(False) if(list1 is list3): print(True) else: print(False)
a = 50 b = 100 avg =(a+b)/2 avg = (int(avg)) c = ("the average between a and b is:") print (c,avg) print (type(c),type(avg))
sent=('ahsan','omer','king') a = (input("Enter a word you want to find:\n")) if(a.lower in sent): print("it is in the list") else: print("it is not in the list")
letter='''Dear NAME DATE From "Dear Omar Ahsan Khan, from abc house we are promoting you for your performance this year our regards have a good day. Thank you,from bill''' Name = input('your name') Date = input('date') From = input('From') letter =letter.replace('NAME',Name) letter =letter.replace('DATE',Date) letter =letter.replace('From',From) print (letter)
# use python3 import sys import threading import queue sys.setrecursionlimit(10**7) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size class Tree: def __init__(self, index, depth=None): self.val = index self.child = [] self.depth = depth def add_child(self, child): self.child.append(child) def cal_height(tree): node = None for x in tree: if x.depth == 0: # Breadth-first travel root = x fifo_queue = queue.Queue() fifo_queue.put(root) while not fifo_queue.empty(): node = fifo_queue.get() if not node.child == []: for i in node.child: i.depth = node.depth + 1 fifo_queue.put(i) print(node.depth + 1) def main(): n = int(sys.stdin.readline()) parent = list(map(int, sys.stdin.readline().split())) node = n * [0] # CREAT TREE for index, dad in enumerate(parent): if node[index] == 0 and dad != -1: node[index] = Tree(index) if dad == -1: node[index] = Tree(index, depth=0) continue if node[dad] == 0: node[dad] = Tree(dad) node[dad].add_child(node[index]) # CREATE TREE cal_height(node) threading.Thread(target=main).start()
import matplotlib #绘制一个plot折线图,取别名plt import matplotlib.pyplot as plt # %matplotlib inline #绘制y = x^2 (x,1,2,3,4...)/列表自身具有索引【0....】/数据为列表 squares = [x**2 for x in range(1,10)] #绘图/ # plt.plot(squares) # plt.show() #改变线条的样式,线条的粗细linewidth plt.plot(squares,linewidth=2) plt.show() #给图标题标题大小 fontsize,图中写中文:方法属性 fontproperties="Sim_" plt.title('我',fontproperties="SimHei") plt.show() #在图中有中文2:统一指定字体 plt.rcParams['font.sans-serif']=['SimHei']#统一指定 plt.rcParams['axes.unicode_minus']=False #显示负号 #x轴,y轴 写法: plt.xlabel('数字',fontsize=12) plt.ylabel('平方',fontsize=12) plt.show()
#Embedded file name: eve/common/script/planet\surfacePoint.py """ Surface point """ import math MATH_2PI = math.pi * 2 class SurfacePoint: """ Represents a point on the surface of a sphere, both in cartesian and spherical coordiantes. A surface point can be created by specifying the cartesian coordinates: - sp = planet.SurfacePoint(x=1.0, y=2.0, z=3.0) ... or by specifying the spherical coordinates - sp = planet.SurfacePoint(radius=100.0, theta=math.pi, phi=math.pi/4) In spherical coordinates, theta should be in the range [0,PI] - THETA [0, 2*PI] indicates the angle from the positive X-axis on the XZ plane - PHI [0, PI] indicates the angle from the positive Y-axis """ __guid__ = 'planet.SurfacePoint' def __init__(self, x = 0.0, y = 0.0, z = 0.0, radius = 1.0, theta = None, phi = None): if theta is not None and phi is not None: self.SetRadThPhi(radius, theta, phi) else: self.SetXYZ(x, y, z) def SetXYZ(self, x, y, z): self.x = x self.y = y self.z = z self._CalcRadThPhi() def Copy(self, surfacePoint): self.x = surfacePoint.x self.y = surfacePoint.y self.z = surfacePoint.z self.radius = surfacePoint.radius self.theta = surfacePoint.theta self.phi = surfacePoint.phi def SetRadThPhi(self, radius, theta, phi): self.radius = radius self.theta = theta self.phi = phi self._CalcXYZ() def _CalcRadThPhi(self): self.radius = math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) if self.radius == 0.0: self.theta = self.phi = 0.0 return self.phi = math.acos(self.y / self.radius) self.theta = math.atan2(self.z, self.x) self._CheckTheta() def _CheckTheta(self): """This will normalize theta to a range of [0..2*Pi)""" while self.theta >= MATH_2PI: self.theta -= MATH_2PI while self.theta < 0.0: self.theta += MATH_2PI def _CalcXYZ(self): """ x = r * sin(phi) * cos(theta) y = r * sin(phi) * cos(theta) z = r * cos(phi) """ radSinPhi = self.radius * math.sin(self.phi) self.x = radSinPhi * math.cos(self.theta) self.z = radSinPhi * math.sin(self.theta) self.y = self.radius * math.cos(self.phi) def SetX(self, x): self.x = x self._CalcRadThPhi() def SetY(self, y): self.y = y self._CalcRadThPhi() def SetZ(self, z): self.z = z self._CalcRadThPhi() def SetRadius(self, radius): self.radius = radius self._CalcXYZ() def SetTheta(self, theta): self.theta = theta self._CheckTheta() self._CalcXYZ() def SetPhi(self, phi): self.phi = phi self._CalcXYZ() def GetAsXYZTuple(self): return (self.x, self.y, self.z) def GetAsRadThPhiTuple(self): return (self.radius, self.theta, self.phi) def GetAsXYZString(self): return '(%6.2f, %6.2f, %6.2f) = (x,y,z)' % self.GetAsXYZTuple() def GetAsRadThPhiString(self): return '(%6.2f, %6.2f, %6.2f) = (rad,theta,phi)' % self.GetAsRadThPhiTuple() def GetAngleBetween(self, other): dotProduct = (self.x * other.x + self.y * other.y + self.z * other.z) / self.radius / other.radius if dotProduct > 1.0: dotProduct = 1.0 return math.acos(dotProduct) def GetDistanceToOther(self, other): return self.radius * self.GetAngleBetween(other) __exports__ = {'planet.SurfacePoint': SurfacePoint}
import unittest from ..node import Node class NodeTest(unittest.TestCase): def test_ctor(self): """Test some variants of the Node __init__ method""" node = Node("name", "data") self.assertEqual("name", node.name) self.assertEqual("data", node.data) node = Node("name", attr1="value1", attr2="value2") self.assertEqual(dict(attr1="value1", attr2="value2"), node.attributes) def test_toxml(self): """Test if serializing to XML works""" node = Node("name") self.assertEqual("<name></name>", node.toxml()) node = Node("name", "data") self.assertEqual("<name>data</name>", node.toxml()) node = Node("name", children=[Node("child1"), Node("child2")]) xml = ("<name>\n" + " <child1></child1>\n" + " <child2></child2>\n" + "</name>") self.assertEqual(xml, node.toxml()) def test_dict(self): """Test some of the dictionary interface""" node = Node("name") node["attr1"] = "value1" self.assertTrue("attr1" in node.attributes) self.assertTrue("attr1" in node) self.assertEqual(1, len(node)) for key in node: # Test iterator self.assertEqual("attr1", key)
import pandas as pd from topics import * from clean import stats def calc_age_stats(df): ''' Take in cleaned and processed data, remove cities with less than 50 data points Calculate statistics per city - display top 5 - % that advertise IG - % that advertise SC - % that mention Coivd - % ''' reduced = df.groupby('age').filter(lambda x: x["name"].count() > 2000) citydf = pd.DataFrame(reduced.groupby('age').size(),columns=["DPs"]) citydf['college'] = reduced.groupby('age').apply(lambda x: round(100*x['college'].count()/x['name'].count(),1)) citydf['job'] = reduced.groupby('age').apply(lambda x: round(100*x['job'].count()/x['name'].count(),1)) citydf['anthem'] = reduced.groupby('age').apply(lambda x: round(100*x['anthem'].count()/x['name'].count(),2)) citydf['city'] = reduced.groupby('age').apply(lambda x: round(100*x['city'].count()/x['name'].count(),2)) # citydf['age_dist'] = reduced.groupby('age').apply(lambda x: x['age'].to_list()) for each in topics: citydf[each] = reduced.groupby('age').apply(lambda x: round(100*x[each].sum()/x['name'].count(),2)) return citydf def top_5(citydf): print("---------------------------------------------") print("-----------HERE ARE YOUR TOP 8---------------") print("-----TOP 8 CITIES WITH MOST DATA ENTRIES-----") print(citydf.DPs.sort_values(ascending=False).head(8)) print("-----TOP 8 CITIES WITH MOST CITIES-----") print(citydf.city.sort_values(ascending=False).head(8)) print("-----TOP 8 CITIES WITH HIGHEST COLLEGE %-----") print(citydf.college.sort_values(ascending=False).head(8)) print("-------TOP 8 CITIES WITH HIGHEST JOB %-------") print(citydf.job.sort_values(ascending=False).head(8)) print("------TOP 8 CITIES WITH HIGHEST ANTHEM %-----") print(citydf.anthem.sort_values(ascending=False).head(8)) print("--------TOP 8 CITIES WITH HIGHEST IG %-------") print(citydf.instagram.sort_values(ascending=False).head(8)) print("-------TOP 8 CITIES WITH HIGHEST SNAP %------") print(citydf.snapchat.sort_values(ascending=False).head(8)) print("-------TOP 8 CITIES WITH HIGHEST COVID %-----") print(citydf.covid19.sort_values(ascending=False).head(8)) print("-------TOP 8 CITIES WITH HIGHEST WEED %-----") print(citydf.cannabis.sort_values(ascending=False).head(8)) print("-------TOP 8 CITIES WITH HIGHEST ALCOHOL %-----") print(citydf.alcohol.sort_values(ascending=False).head(8)) print("-------TOP 8 CITIES WITH HIGHEST TV %-----") print(citydf.tv.sort_values(ascending=False).head(8)) print("-------TOP 8 CITIES WITH HIGHEST Premium Snap %-----") print(citydf.premium.sort_values(ascending=False).head(8)) print("-------TOP 8 CITIES WITH HIGHEST OFFICE %-----") print(citydf.office.sort_values(ascending=False).head(8)) print("---------------------------------------------") print(citydf.head()) df = pd.read_csv("data/processed/cleaned_data.csv") new = calc_age_stats(df) top_5(new)
from flask import Flask import json import os app = Flask(__name__) @app.route("/") def reverse_slicing(s): return s[::-1] input_str = 'ABç∂EF' if __name__ == "__main__": print('Reverse String using slicing =', reverse_slicing(input_str))
''' DEFAULT -- interpretter -- when there is no other constructor in a class No-arg -- user has defined a constructor without parameter paramaterized --user has defined a constructor with parameter max -- there will one contstructor in class -- last one ''' class Person : def method1(self,**a): sum = 0 if a.__len__()>10 : for item in a: sum = sum + item else : for item in a: sum = sum * item p = Person() d = p.method1(10,40) print(d)
# This is created by sugan😎😍😀 '''First enter your equations and press run''' print("this program is created by sugan under MIT lisence 2.0") def find(a): num1 = a[0] # instead use x1 ,1 num2 = a[1] # y1 ,1 num3 = a[2] # c2 ,5 num4 = a[3] # x2 ,2 num5 = a[4] # y2 ,2 num6 = a[5] # c2 ,4 if num1 == num4: if num2 == num5: """ if num2 == num5 and num3 == num6 print("Invalid1") return else: print("Invalid2") next just use an if """ if num3 == num6: print("Invalid1") else: print("Invalid2") elif num2 != num5: if num3 != num6: print('y = ', (num3 - num6) / (num2 - num5), 'x = ', (num3 - (num2*((num3 - num6) / (num2 - num5))))/num1)#very confusing use two line or store the value in a variable like y = (num3 - num6) / (num2 - num5) # so in second eqn x = (num3 - num2 * y)/num1 much more readble return " " elif num3 == num6: print('y = 0 and x = ', b[2]) # whh is b whf is it's third value it must be num3 or num6 i hope return " " else: print("Invalid3") else: print("Invalid4") elif num1 != num4: # if it is not equal then it must be not equal so you didn't need elif simple else is enough if num2 == num5: if num3 == num6: print("x = 0 and y = ", b[2]) # again wtf num3 or num6 return " " elif num3 != num6: # you didn't need elif # x = (num6 - num3) / (num4 - num1) # y = (num3 - num1* x )/num2 y is wrong in your calculation print("x =", (num6 - num3) / (num4 - num1), 'y = ', (num3 - num1)/(num2)) return " " else: # this else simply waste print("Invalid5") elif num2 != num5: # else is enough mullist1 = [i * num4 for i in a[:3]] mullist2 = [i * num1 for i in a[3:]] # use variable name for mullist1[1] and mullist2[2] # and wtf is mullist1 # because u are using it again and again if mullist1[1] > mullist2[1] or mullist1[1] == mullist2[1]: #wtf is w,a,s,d w = mullist1[1] - mullist2[1] a = mullist1[2] - mullist2[2] s = a / w # atleat name is y d = (num3 - num2 * s) / num1 print("x = ", d, "y = ", s) return " " else: # u are doing the same thing as above waste of space w = mullist1[1] - mullist2[1] a = mullist1[2] - mullist2[2] s = a / w d = (num3 - num2 * s) / num1 print("x = ", d, "y = ", s) return " " else: # waste else print("invalid6") else:#waste else print("invalid7") while True: first_equ = str(input().replace(' ', '')) #input itself is a string you don't need str() second_equ = str(input().replace(' ', '')) try: listconv1 = first_equ.split('=')# x + y = 5 ['x+y' , '5'] listconv2 = second_equ.split("=")# 2x + 2y = 4 ['x+2y' , '4'] """ bad variable names wtf is w c s d """ w = listconv1[0].split("x")# 'x+y' ['','+y'] c = w[1].split('y') # '+y' ['+',''] c.remove('') # ['+'] w += c # ['','+y','+'] s = listconv2[0].split("x") # '2x+2y' ['2','+2y'] c = s[1].split('y') # ['+2',''] c.remove('') # ['+2y'] s += c # ['2','+2y','+2'] d = [[w[0], w[2], listconv1[1]], [s[0], s[2], listconv2[1]]] # [['','+',5],['2','+2','4']] a = [] for x in d: for i in range(len(x)): # instead use "for idx,val in enumerate(x):" if x[i] == '' or x[i] == '+': x[i] = 1 elif x[i] == '-': x[i] = -1 else: x[i] = int(x[i]) a += x # use extend function to be more explict that you are using list it may confused with a number print(a) #[1,1,5,2,2,4] print(find(a)) except: print('error') break
""" File: asteroids.py Original Author: Br. Burton Designed to be completed by others This program implements the asteroids game. """ import arcade import math import random from abc import ABC, abstractmethod import pyglet # These are Global constants to use throughout the game SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 600 BULLET_LENGTH = 35 BULLET_WIDTH = 25 BULLET_SPEED = 10 BULLET_LIFE = 60 POWER_UP_BULLET_LENGTH = 65 POWER_UP_BULLET_WIDTH = 20 ENEMY_BULLET_LENGTH = 65 ENEMY_BULLET_WIDTH = 20 SHIP_TURN_AMOUNT = 3 SHIP_TURN_MULTIPLIER = 2 SHIP_THRUST_AMOUNT = 0.25 SHIP_RADIUS = 65 PLAYER_TWO_RADIUS = 45 SHIP_BASE_HEALTH = 100 ENEMY_SHIP_RADIUS = 35 ENEMY_SHIP_HEALTH = 100 ENEMY_SHIP_SPAWN_TIMER = 500 ENEMY_SHIP_SPEED = 2 ENEMY_FREIGHTER_RADIUS = 55 ENEMY_FREIGHTER_HEALTH = 200 ENEMY_FREIGHTER_SPAWN_TIMER = 2000 POWER_UP_WIDTH = 40 POWER_UP_RADIUS = 50 INITIAL_ROCK_COUNT = 5 BIG_ROCK_SPIN = 1 BIG_ROCK_SPEED = 1.5 BIG_ROCK_RADIUS = 30 BIG_ROCK_DAMAGE = 10 MEDIUM_ROCK_SPIN = -2 MEDIUM_ROCK_RADIUS = 20 MEDIUM_ROCK_DAMAGE = 5 SMALL_ROCK_SPIN = 5 SMALL_ROCK_RADIUS = 10 SMALL_ROCK_DAMAGE = 2 ASTEROID_SPAWN_TIMER = 300 DEFAULT_SHOOT_TIMER = 3 POWER_UP_TIMER = 750 POWER_UP_ALIVE_TIMER = 150 INSTRUCTIONS = 0 GAME_RUNNING = 1 TRANSITION = 2 GAME_OVER = 3 QUIT = 4 MAX_SPEED = 15 SPAWN_DISTANCE = 200 def set_new_asteroid(new, old, dx, dy): """ This function receives the old and the new asteroid as input, and also receives another dx and dy value to be added to the old asteroid's dx and dy. This function essentially sets up the new asteroid. :param new: Asteroid being created :param old: Asteroid that was destroyed :param dx: dx that will be added to old dx for new asteroid :param dy: dy that will be added to old dy for new asteroid :return: new asteroid (modified) """ new.center.x = old.center.x new.center.y = old.center.y new.velocity.dx = old.velocity.dx + dx new.velocity.dy = old.velocity.dy + dy return new class Point: """ Creates a class that will store a location in the xy plane. """ def __init__(self): self.x = 0 self.y = 0 def new_location(self, ship_1, ship_2): self.x = random.uniform(1, SCREEN_WIDTH - 1) self.y = random.uniform(1, SCREEN_HEIGHT - 1) while (abs(ship_1.center.x - self.x) < SPAWN_DISTANCE or abs(ship_1.center.y - self.y) < SPAWN_DISTANCE) and \ (abs(ship_2.center.x - self.x) < SPAWN_DISTANCE or abs(ship_2.center.y - self.y) < SPAWN_DISTANCE): self.x = random.uniform(1, SCREEN_WIDTH - 1) self.y = random.uniform(1, SCREEN_HEIGHT - 1) class Velocity: """ Creates a class that will store velocity values. """ def __init__(self): self.dx = 0 self.dy = 0 class FlyingObject: """ Creates class for Flying Objects. This is a base class for other flying objects classes that will be created. Contains methods: advance draw check_off_screen """ def __init__(self): """ Creates and sets class variables. """ self.center = Point() self.velocity = Velocity() self.radius = 0 self.alive = True self.angle = 0 self.velocity.dx = 0 self.velocity.dy = 0 self.image = "Files/Millennium_Falcon.png" self.alpha = 1 def advance(self): """ Changes the position of a flying object """ self.center.x += self.velocity.dx self.center.y += self.velocity.dy def draw(self): """ Draws a flying object """ texture = arcade.load_texture(self.image) arcade.draw_texture_rectangle(self.center.x, self.center.y, self.radius * 2, self.radius * 2, texture, self.angle, self.alpha) def check_off_screen(self): """ Checks to see whether a flying object is off the screen. Relocates it on the other side. """ if self.center.x <= 0: self.center.x = SCREEN_WIDTH - 1 elif self.center.x >= SCREEN_WIDTH: self.center.x = 1 elif self.center.y <= 0: self.center.y = SCREEN_HEIGHT - 1 elif self.center.y >= SCREEN_HEIGHT: self.center.y = 1 class Asteroid(FlyingObject, ABC): """ Asteroid class inherits from the Flying Object class. This class will be used to model other classes for different types of asteroids. """ def __init__(self): super().__init__() self.image = "Files/meteorGrey_big1.png" self.radius = BIG_ROCK_RADIUS self.spin = BIG_ROCK_SPIN self.velocity_angle = random.uniform(0, 359) self.speed = BIG_ROCK_SPEED self.velocity.dx = math.cos(math.radians(self.velocity_angle)) * self.speed self.velocity.dy = math.sin(math.radians(self.velocity_angle)) * self.speed self.type = 1 def rotate(self): """ Changes angle of asteroid depending on self.spin value. """ self.angle += self.spin def advance(self): self.rotate() super().advance() @abstractmethod def split(self, asteroids): """ Will be responsible for splitting up an asteroid after getting hit. :param asteroids: list containing all asteroids in game class. """ pass @abstractmethod def hit(self, power): pass @abstractmethod def damage(self, power): pass @abstractmethod def hit_ship(self, power): pass class LargeAsteroid(Asteroid): """ Large Asteroid class. Inherits from the Asteroid class. """ def __init__(self): super().__init__() def split(self, asteroids): """ Splits up large asteroid into smaller asteroids. :param asteroids: list containing all asteroids from game. :return: asteroids """ med_1 = MediumAsteroid() med_1 = set_new_asteroid(med_1, self, 0, 2) med_2 = MediumAsteroid() med_2 = set_new_asteroid(med_2, self, 0, -2) small_1 = SmallAsteroid() small_1 = set_new_asteroid(small_1, self, 5, 0) asteroids.extend([med_1, med_2, small_1]) self.alive = False return asteroids def hit(self, power): if power: return 20 else: return 10 def damage(self, power): if not power: return 5 else: return 0 def hit_ship(self, power): if not power: return BIG_ROCK_DAMAGE else: return 0 class MediumAsteroid(Asteroid): """ Medium Asteroid class. Inherits from the Asteroid class. """ def __init__(self): super().__init__() self.image = "Files/meteorGrey_med1.png" self.radius = MEDIUM_ROCK_RADIUS self.spin = MEDIUM_ROCK_SPIN self.type = 2 def split(self, asteroids): """ Splits up medium asteroid into smaller asteroids. :param asteroids: list containing all asteroids from game. :return: asteroids """ small_1 = SmallAsteroid() small_1 = set_new_asteroid(small_1, self, 1.5, 1.5) small_2 = SmallAsteroid() small_2 = set_new_asteroid(small_2, self, -1.5, -1.5) asteroids.extend([small_1, small_2]) self.alive = False return asteroids def hit(self, power): if power: return 10 else: return 5 def damage(self, power): if not power: return 3 else: return 0 def hit_ship(self, power): if not power: return MEDIUM_ROCK_DAMAGE else: return 0 class SmallAsteroid(Asteroid): """ Small Asteroid class. Inherits from the Asteroid class. """ def __init__(self): super().__init__() self.image = "Files/meteorGrey_small1.png" self.radius = SMALL_ROCK_RADIUS self.spin = SMALL_ROCK_SPIN self.type = 3 def split(self, asteroids): """ Sets alive to false, returns asteroids. :param asteroids: list containing all asteroids from game. :return: asteroids """ self.alive = False return asteroids def hit(self, power): if power: return 5 else: return 2 def damage(self, power): if not power: return 1 else: return 0 def hit_ship(self, power): if not power: return SMALL_ROCK_DAMAGE else: return 0 class Laser(FlyingObject): """ Laser class, inherits from Flying Object class. """ def __init__(self): super().__init__() self.image = "Files/REDLASER.png" self.center.x = 0 self.center.y = 0 self.radius = 25 self.life = BULLET_LIFE self.speed = BULLET_SPEED self.type = 1 self.length = 35 self.width = 25 def advance(self): if self.life > 0: super().advance() self.life -= 1 else: self.alive = False def draw(self): """ Changes draw to use length and width. """ texture = arcade.load_texture(self.image) arcade.draw_texture_rectangle(self.center.x, self.center.y, self.length, self.width, texture, self.angle, self.alpha) def fire(self, ship): """ Fires bullet at an angle and a speed. :param ship: ship from game """ self.velocity.dx = ship.velocity.dx + (math.cos(math.radians(ship.angle)) * self.speed) self.velocity.dy = ship.velocity.dy + (math.sin(math.radians(ship.angle)) * self.speed) class EnemyLaser(Laser): """ Enemy laser class, inherits from Laser class. """ def __init__(self): super().__init__() self.image = "Files/Green_Laser.png" self.type = 2 self.length = ENEMY_BULLET_LENGTH self.width = ENEMY_BULLET_WIDTH class PowerUp(FlyingObject): """ Power up class, inherits from Flying Object class. Will cause a power up for user that comes into contact with it. """ def __init__(self): super().__init__() self.image = "Files/REBEL.png" self.radius = POWER_UP_RADIUS self.timer = POWER_UP_ALIVE_TIMER class ShipBase(FlyingObject): def __init__(self): super().__init__() self.radius = SHIP_RADIUS self.health = SHIP_BASE_HEALTH self.type = 0 self.thrust = SHIP_THRUST_AMOUNT self.turn = SHIP_TURN_AMOUNT self.center.x = SCREEN_WIDTH/2 self.center.y = (5 * SCREEN_HEIGHT)/8 class Ship(ShipBase): """ Ship class, inherits from Flying Object class. This is the ship that the user will control in the game class. """ def __init__(self): super().__init__() def accelerate(self): """ Increases speed when triggered. """ if abs(self.velocity.dx) < MAX_SPEED: self.velocity.dx += math.cos(math.radians(self.angle)) * self.thrust if abs(self.velocity.dy) < MAX_SPEED: self.velocity.dy += math.sin(math.radians(self.angle)) * self.thrust def decelerate(self): """ Decreases speed when triggered. """ self.velocity.dx /= 2 self.velocity.dy /= 2 def turn_left(self, m=1): """ Changes angle of ship (rotates left) :param m: multiplier """ self.angle += self.turn * m def turn_right(self, m=1): """ Changes angle of ship (rotates right) :param m: multiplier """ self.angle -= self.turn * m @property def speed(self): """ Returns speed of ship (rounded to nearest .25) :return: """ speed = math.sqrt((self.velocity.dx ** 2) + (self.velocity.dy ** 2)) speed = round(speed*4)/4 return speed class PlayerTwoShip(Ship): """ Player Two Ship class, inherits from ship class. This is the ship used by player two in the game class. """ def __init__(self): super().__init__() self.image = "Files/X-Wing.png" self.type = 2 self.center.x = SCREEN_WIDTH/2 self.center.y = (3 * SCREEN_HEIGHT)/8 class LaserTwo(Laser): """ Laser shot by player two. """ def __init__(self): super().__init__() self.type = 3 class AggressiveEnemyShip(ShipBase): """ Class for Aggressive enemy ship, inherits from ship class. This ship will attack the player(s). """ def __init__(self): super().__init__() self.image = "Files/Tiefighter.png" self.radius = ENEMY_SHIP_RADIUS self.health = ENEMY_SHIP_HEALTH self.enemy_speed = ENEMY_SHIP_SPEED self.type = 1 self.outside_ship = None self.multiplier = random.uniform(.5, 1) def set_target(self, ship): """ Sets target as ship that is closest. :param ship: """ self.outside_ship = ship def set_speed(self, actual_dist): """ Sets speed of enemies. :param actual_dist: distance from target """ self.enemy_speed = (actual_dist / 100) * self.multiplier def advance(self): """ Enemy advances according to proximity to target. """ dist_x = self.center.x - self.outside_ship.center.x dist_y = self.center.y - self.outside_ship.center.y actual_dist = math.sqrt((dist_x ** 2) + (dist_y ** 2)) self.set_speed(actual_dist) if actual_dist > SPAWN_DISTANCE: self.velocity.dx = math.cos(math.radians(self.angle)) * self.enemy_speed self.velocity.dy = math.sin(math.radians(self.angle)) * self.enemy_speed elif abs(dist_x) < SPAWN_DISTANCE: self.velocity.dx = 0 elif abs(dist_y) < SPAWN_DISTANCE: self.velocity.dy = 0 super().advance() class EnemyFreighter(ShipBase): """ Large enemy ship, inherits from ship class. This ship is large and has lots of health. When the user destroys it, a power up will appear. """ def __init__(self): super().__init__() self.image = "Files/Imperial_Star_Destroyer.png" self.radius = ENEMY_FREIGHTER_RADIUS self.health = ENEMY_FREIGHTER_HEALTH self.type = 2 self.velocity.dx = random.uniform(-1, 1) self.velocity.dy = random.uniform(-1, 1) self.length = 200 self.width = 75 def draw(self): """ Changes draw to use length and width. """ texture = arcade.load_texture(self.image) arcade.draw_texture_rectangle(self.center.x, self.center.y, self.length, self.width, texture, self.angle, self.alpha) class Game(arcade.Window): """ This class handles all the game callbacks and interaction This class will then call the appropriate functions of each of the above classes. You are welcome to modify anything in this class. """ def __init__(self, width, height): """ Sets up the initial conditions of the game :param width: Screen width :param height: Screen height """ super().__init__(width, height) self.media_player = pyglet.media.Player() self.game_over_sound = arcade.load_sound("Files/GAME_OVER.wav") self.sound = pyglet.media.load("Files/Star_Wars.wav") self.play_sound = True self.play_game_over = False self.game_over_player = pyglet.media.Player() self.game_over_player.queue(self.game_over_sound) self.looper = pyglet.media.SourceGroup(self.sound.audio_format, None) self.looper.loop = True self.looper.queue(self.sound) self.enemy_blast = arcade.load_sound("Files/Tie_fighter_blast.wav") self.p_2_blast = arcade.load_sound("Files/X-Wing_blast.wav") self.ship_blast = arcade.load_sound("Files/Millennium_Falcon_Blast.wav") self.pause_sound = arcade.load_sound("Files/PAUSE.wav") self.background = arcade.load_texture("Files/Background.jpg") self.media_player.queue(self.looper) self.mute = False self.quit = False self.held_keys = set() # I made all of these variables... self.ship = Ship() self.player_two = PlayerTwoShip() self.asteroids = [] self.bullets = [] self.initial_rocks = INITIAL_ROCK_COUNT self.enemies = [] self.score = 0 self.score_2 = 0 self.current_state = INSTRUCTIONS self.final_scores = [] self.power_ups = [] self.final_score = 0 self.final_score_2 = 0 self.play_count = 0 self.high_score = 0 self.game_over = False self.power_up = False self.power_up_2 = False self.power_up_timer = POWER_UP_TIMER self.power_up_timer_2 = POWER_UP_TIMER self.shoot_timer = DEFAULT_SHOOT_TIMER self.shoot_timer_2 = DEFAULT_SHOOT_TIMER self.pause = False def on_draw(self): """ Called automatically by the arcade framework. Handles the responsibility of drawing all elements. """ # clear the screen to begin drawing arcade.start_render() if self.current_state == 4: pyglet.app.exit() arcade.close_window() elif self.quit: self.draw_quit() self.game_over_player.pause() else: if self.current_state == INSTRUCTIONS: self.draw_instructions() if self.current_state == GAME_RUNNING: arcade.draw_texture_rectangle(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, SCREEN_WIDTH, SCREEN_HEIGHT, self.background) if self.play_sound: self.game_over_player.pause() self.media_player.seek(0) self.media_player.play() self.play_sound = False self.draw_score() self.draw_health() if self.ship.alive: self.ship.draw() if self.player_two.alive: self.player_two.draw() self.draw_speed() for bullet in self.bullets: bullet.draw() for asteroid in self.asteroids: asteroid.draw() for enemy in self.enemies: enemy.draw() for power in self.power_ups: power.draw() if self.pause: self.media_player.pause() self.draw_pause() elif self.current_state == TRANSITION: self.final_scores.append(self.score) self.final_scores.append(self.score_2) self.get_final_value() self.play_game_over = True elif self.current_state == GAME_OVER: if self.play_game_over: self.game_over_player.seek(0) self.media_player.pause() self.game_over_player.play() self.play_game_over = False self.draw_final() if self.mute: self.draw_mute() def get_final_value(self): """ Gets final value, stores into list, changes current state to game over. """ self.final_score = self.final_scores[int(self.play_count*2)] self.final_score_2 = self.final_scores[int(self.play_count*2 + 1)] self.current_state = GAME_OVER def get_high_score(self): """ Calculates high score. Sets self.high_score to this value. """ high_score = -1000 for score in self.final_scores: if score > high_score: high_score = score self.high_score = high_score def draw_final(self): """ Displays game over screen, including final score(s), high score, and times played. """ arcade.set_background_color(arcade.color.BLACK) self.get_high_score() score_text = "Final Score P1: {} Final Score P2: {}".format(self.final_score, self.final_score_2) high_text = "High Score: {}".format(self.high_score) other_text = "Total times played: {}".format(self.play_count + 1) start_x = 10 start_y = SCREEN_HEIGHT - 20 arcade.draw_text(score_text, start_x=start_x, start_y=start_y, font_size=12, color=arcade.color.WHITE) arcade.draw_text("GAME OVER!", start_x=SCREEN_WIDTH / 5 + 47, start_y=(SCREEN_HEIGHT / 2), font_size=72, color=arcade.color.WHITE) arcade.draw_text(high_text, start_x=(SCREEN_WIDTH - 150), start_y=start_y, font_size=12, color=arcade.color.WHITE) arcade.draw_text("Press Enter to continue", start_x=(SCREEN_WIDTH/2 - 155), start_y=(SCREEN_HEIGHT / 2) - 35, font_size=24, color=arcade.color.WHITE) arcade.draw_text("Press 'Q' to quit", start_x=(SCREEN_WIDTH / 2 - 110), start_y=(SCREEN_HEIGHT / 2) - 70, font_size=24, color=arcade.color.WHITE) arcade.draw_text(other_text, start_x=10, start_y=12, font_size=12, color=arcade.color.WHITE) if self.pause: arcade.draw_text("Music Paused", start_x=SCREEN_WIDTH - 110, start_y=12, font_size=12, color=arcade.color.WHITE) def draw_speed(self): """ Puts the current speed on the screen """ text_1 = "P1 Speed: {}".format(self.ship.speed) text_2 = "P2 Speed: {}".format(self.player_two.speed) start_x_1 = SCREEN_WIDTH / 2 - 190 start_x_2 = SCREEN_WIDTH / 2 - 70 start_y = SCREEN_HEIGHT - 20 arcade.draw_text(text_1, start_x=start_x_1, start_y=start_y, font_size=12, color=arcade.color.WHITE) arcade.draw_text(text_2, start_x=start_x_2, start_y=start_y, font_size=12, color=arcade.color.WHITE) def draw_score(self): """ Puts the current score on the screen """ score_text = "Score P1: {} Score P2: {}".format(self.score, self.score_2) start_x = 10 start_y = SCREEN_HEIGHT - 20 arcade.draw_text(score_text, start_x=start_x, start_y=start_y, font_size=12, color=arcade.color.WHITE) def draw_health(self): """ Puts health left on screen. """ health = "Health P1: {}% Health P2: {}%".format(self.ship.health, self.player_two.health) start_x = SCREEN_WIDTH - 270 start_y = SCREEN_HEIGHT - 20 arcade.draw_text(health, start_x=start_x, start_y=start_y, font_size=12, color=arcade.color.WHITE) def draw_pause(self): """ Draws pause. """ text = "PAUSE" start_x = SCREEN_WIDTH/2 - 140 start_y = SCREEN_HEIGHT/2 arcade.draw_text(text, start_x=start_x, start_y=start_y, font_size=76, color=arcade.color.WHITE) restart = "Press 'R' to restart" x = SCREEN_WIDTH/2 - 134 y = SCREEN_HEIGHT/2 - 40 arcade.draw_text(restart, start_x=x, start_y=y, font_size=26, color=arcade.color.WHITE) quit_game = "Press 'Q' to quit" y_quit = SCREEN_HEIGHT/2 - 80 arcade.draw_text(quit_game, start_x=x+19, start_y=y_quit, font_size=26, color=arcade.color.WHITE) def draw_instructions(self): arcade.draw_text("INSTRUCTIONS:", start_x=15, start_y=SCREEN_HEIGHT - 60, font_size=50, color=arcade.color.WHITE) text_0 = "- The objective is to get as many points as possible. This is done by trying" text_1 = " not to get hit, and destroying as many enemies as possible." text_2 = "- To move the Millennium Falcon, use UP, DOWN, LEFT, and RIGHT. Use SPACE to shoot." text_3 = "- To move the X-Wing, use W, A, S, and D. Use the GRAVE key to shoot (`~)." text_4 = "- Health, speed and current score for both players are displayed at the top of the screen." text_5 = "- When you destroy an large enemy, you can get a powerup. These will make you" text_6 = " invulnerable for a short time, and you will shoot a constant stream of bullets." text_7 = "- Press 'P' to pause or 'M' to mute. When paused, push 'R' to reset or 'Q' to quit." text_8 = "- Try to destroy as many enemies and asteroids as you can without getting hit!" text_9 = "Press ENTER to continue" arcade.draw_text(text_0, 15, SCREEN_HEIGHT - 100, font_size=19, color=arcade.color.WHITE) arcade.draw_text(text_1, 15, SCREEN_HEIGHT - 140, font_size=19, color=arcade.color.WHITE) arcade.draw_text(text_2, 15, SCREEN_HEIGHT - 180, font_size=19, color=arcade.color.WHITE) arcade.draw_text(text_3, 15, SCREEN_HEIGHT - 220, font_size=19, color=arcade.color.WHITE) arcade.draw_text(text_4, 15, SCREEN_HEIGHT - 260, font_size=19, color=arcade.color.WHITE) arcade.draw_text(text_5, 15, SCREEN_HEIGHT - 300, font_size=19, color=arcade.color.WHITE) arcade.draw_text(text_6, 15, SCREEN_HEIGHT - 340, font_size=19, color=arcade.color.WHITE) arcade.draw_text(text_7, 15, SCREEN_HEIGHT - 380, font_size=19, color=arcade.color.WHITE) arcade.draw_text(text_8, 15, SCREEN_HEIGHT - 420, font_size=19, color=arcade.color.WHITE) arcade.draw_text(text_9, 90, 65, font_size=60, color=arcade.color.WHITE) def draw_mute(self): """ Draws mute. """ text = "Audio Muted" start_x = SCREEN_WIDTH / 2 - 30 start_y = 12 arcade.draw_text(text, start_x=start_x, start_y=start_y, font_size=12, color=arcade.color.WHITE) def draw_quit(self): text = "Are you sure you want to quit?" start_x = 10 start_y = SCREEN_HEIGHT / 2 arcade.draw_text(text, start_x=start_x, start_y=start_y, font_size=58, color=arcade.color.WHITE) response = "'Y' for yes, 'N' for no" x = SCREEN_WIDTH / 2 - 130 y = SCREEN_HEIGHT / 2 - 40 arcade.draw_text(response, start_x=x, start_y=y, font_size=24, color=arcade.color.WHITE) def update(self, delta_time): """ Update each object in the game. :param delta_time: tells us how much time has actually elapsed """ if not self.pause and self.current_state == GAME_RUNNING: self.check_keys() self.check_collisions() self.check_off_screen() self.ship.advance() self.player_two.advance() self.create_asteroids() self.check_death() if random.randint(1, ENEMY_SHIP_SPAWN_TIMER) == 1: enemy = AggressiveEnemyShip() enemy.center.new_location(self.ship, self.player_two) self.enemies.append(enemy) if random.randint(1, ENEMY_FREIGHTER_SPAWN_TIMER) == 1: enemy = EnemyFreighter() enemy.center.new_location(self.ship, self.player_two) self.enemies.append(enemy) for asteroid in self.asteroids: asteroid.advance() for bullet in self.bullets: bullet.advance() # Power ups will disappear after a while for power in self.power_ups: if power.timer > 0: power.timer -= 1 power.advance() else: power.alive = False for enemy in self.enemies: if enemy.health > 0: if enemy.type == 1: self.enemy_attack(enemy) enemy.advance() else: enemy.alive = False if self.ship.health > SHIP_BASE_HEALTH: self.ship.health = SHIP_BASE_HEALTH if self.player_two.health > SHIP_BASE_HEALTH: self.player_two.health = SHIP_BASE_HEALTH if self.power_up: if self.power_up_timer > 1: self.shoot(self.ship) self.power_up_timer -= 1 else: self.power_up = False self.power_up_timer = POWER_UP_TIMER if self.power_up_2: if self.power_up_timer_2 > 1: self.shoot(self.player_two) self.power_up_timer_2 -= 1 else: self.power_up_2 = False self.power_up_timer_2 = POWER_UP_TIMER def enemy_attack(self, enemy): """ Determines which player the enemy should shoot at, and shoots at the player. :param enemy: """ x_diff_s = enemy.center.x - self.ship.center.x y_diff_s = enemy.center.y - self.ship.center.y x_diff_2 = enemy.center.x - self.player_two.center.x y_diff_2 = enemy.center.y - self.player_two.center.y ship_distance = math.sqrt((x_diff_s ** 2) + (y_diff_s ** 2)) p2_distance = math.sqrt((x_diff_2 ** 2) + (y_diff_2 ** 2)) angle = 0 target = self.ship if ship_distance > p2_distance: if self.player_two.alive: angle = math.atan2(y_diff_2, x_diff_2) target = self.player_two else: angle = math.atan2(y_diff_s, x_diff_s) elif ship_distance < p2_distance: if self.ship.alive: angle = math.atan2(y_diff_s, x_diff_s) else: angle = math.atan2(y_diff_2, x_diff_2) target = self.player_two enemy.angle = math.degrees(angle) - 180 enemy.set_target(target) if random.randint(1, 20) == 1 and (self.ship.alive or self.player_two.alive): self.shoot(enemy) def check_death(self): """ Checks to see whether a ship or both ships have died, and performs the appropriate actions. """ if self.ship.health <= 0: self.ship.health = 0 self.ship.alive = False self.ship.velocity.dx = 0 self.ship.velocity.dy = 0 if self.player_two.health <= 0: self.player_two.health = 0 self.player_two.alive = False if not self.game_over: self.current_state = TRANSITION self.game_over = True elif self.player_two.health <= 0: self.player_two.health = 0 self.player_two.alive = False self.player_two.velocity.dx = 0 self.player_two.velocity.dy = 0 if self.ship.health <= 0: self.ship.health = 0 self.ship.alive = False if not self.game_over: self.current_state = TRANSITION self.game_over = True def create_asteroids(self): """ Creates new asteroids. """ if self.initial_rocks > 0: asteroid = LargeAsteroid() asteroid.center.new_location(self.ship, self.player_two) self.asteroids.append(asteroid) self.initial_rocks -= 1 else: rand = random.randint(1, ASTEROID_SPAWN_TIMER) if rand == 1: asteroid = LargeAsteroid() asteroid.center.new_location(self.ship, self.player_two) self.asteroids.append(asteroid) else: pass def check_collisions(self): """ Checks to see if bullets have hit asteroids, and checks other collisions as well. Updates scores and removes dead items. """ for bullet in self.bullets: for asteroid in self.asteroids: if self.is_collision(bullet, asteroid): bullet.alive = False if bullet.type == 1: self.score += asteroid.hit(self.power_up) elif bullet.type == 3: self.score_2 += asteroid.hit(self.power_up_2) self.asteroids = asteroid.split(self.asteroids) for asteroid in self.asteroids: if self.is_collision(asteroid, self.ship): self.ship.health -= asteroid.hit_ship(self.power_up) self.score -= asteroid.damage(self.power_up) self.asteroids = asteroid.split(self.asteroids) if self.is_collision(asteroid, self.player_two): self.player_two.health -= asteroid.hit_ship(self.power_up_2) self.score_2 -= asteroid.damage(self.power_up_2) self.asteroids = asteroid.split(self.asteroids) for enemy in self.enemies: if self.is_collision(enemy, self.ship): if not self.power_up: self.ship.health -= 5 enemy.health -= 10 if self.is_collision(enemy, self.player_two): if not self.power_up_2: self.player_two.health -= 5 enemy.health -= 10 for bullet in self.bullets: for enemy in self.enemies: if self.is_collision(bullet, enemy): if bullet.type == 1: if self.ship.alive: if enemy.health <= 0: if enemy.type == 1: self.ship.health += 10 self.score += 20 else: self.score += 50 enemy.alive = False elif bullet.type == 3: if self.player_two.alive: if enemy.health <= 0: if enemy.type == 1: self.player_two.health += 10 self.score_2 += 20 else: self.score_2 += 50 enemy.alive = False bullet.alive = False enemy.health -= 15 for bullet in self.bullets: for power in self.power_ups: if self.is_collision(bullet, power): if bullet.type == 1: power.alive = False self.ship.alive = True self.power_up = True self.power_up_timer = POWER_UP_TIMER self.ship.health = SHIP_BASE_HEALTH elif bullet.type == 3: power.alive = False self.player_two.alive = True self.power_up_2 = True self.power_up_timer_2 = POWER_UP_TIMER self.player_two.health = SHIP_BASE_HEALTH bullet.alive = False for power in self.power_ups: if self.is_collision(power, self.player_two): power.alive = False self.player_two.alive = True self.power_up_2 = True self.power_up_timer_2 = POWER_UP_TIMER self.player_two.health = SHIP_BASE_HEALTH if self.is_collision(power, self.ship): power.alive = False self.ship.alive = True self.power_up = True self.power_up_timer = POWER_UP_TIMER self.ship.health = SHIP_BASE_HEALTH for bullet in self.bullets: if bullet.type == 2: if self.is_collision(bullet, self.ship): if not self.power_up: bullet.alive = False self.ship.health -= 5 else: bullet.alive = False if self.is_collision(bullet, self.player_two): if not self.power_up_2: bullet.alive = False self.player_two.health -= 3 else: bullet.alive = False for bullet1 in self.bullets: for bullet2 in self.bullets: if bullet1.type != bullet2.type: if self.is_collision(bullet1, bullet2): bullet1.alive = False bullet2.alive = False self.cleanup_zombies() def is_collision(self, object_1, object_2): """ Checks to see whether a collision occurred. :param object_1: :param object_2: :return: """ if object_1.alive and object_2.alive: too_close = object_1.radius + object_2.radius if (abs(object_1.center.x - object_2.center.x) < too_close and abs(object_1.center.y - object_2.center.y) < too_close): return True else: return False def cleanup_zombies(self): """ Removes any dead bullets, asteroids, enemies, etc. from the list. """ for bullet in self.bullets: if not bullet.alive: self.bullets.remove(bullet) for asteroid in self.asteroids: if not asteroid.alive: self.asteroids.remove(asteroid) for enemy in self.enemies: if not enemy.alive: if enemy.type == 2: self.create_power_up(enemy) self.enemies.remove(enemy) for power in self.power_ups: if not power.alive: self.power_ups.remove(power) def create_power_up(self, enemy): """ Creates a new Power up. :param enemy: Imports an enemy """ power = PowerUp() power.center.x = enemy.center.x power.center.y = enemy.center.y power.velocity.dx = enemy.velocity.dx + 2 power.velocity.dy = enemy.velocity.dy self.power_ups.append(power) def check_off_screen(self): """ Checks to see if bullets or asteroids have left the screen and if so, removes them from their lists. """ self.ship.check_off_screen() self.player_two.check_off_screen() for bullet in self.bullets: bullet.check_off_screen() for asteroid in self.asteroids: asteroid.check_off_screen() for enemy in self.enemies: enemy.check_off_screen() for power in self.power_ups: power.check_off_screen() def set_alpha(self, alpha): """ Sets Alpha for all objects on screen. :param alpha: """ for asteroid in self.asteroids: asteroid.alpha = alpha for bullet in self.bullets: bullet.alpha = alpha for enemy in self.enemies: enemy.alpha = alpha self.ship.alpha = alpha self.player_two.alpha = alpha def check_keys(self): """ This function checks for keys that are being held down. You will need to put your own method calls in here. """ if arcade.key.LEFT in self.held_keys: m = 1 if arcade.key.DOWN in self.held_keys: m = 2 self.ship.turn_left(m) if arcade.key.RIGHT in self.held_keys: m = 1 if arcade.key.DOWN in self.held_keys: m = 2 self.ship.turn_right(m) if arcade.key.UP in self.held_keys: self.ship.accelerate() if arcade.key.DOWN in self.held_keys: self.ship.decelerate() if arcade.key.A in self.held_keys: m = 1 if arcade.key.S in self.held_keys: m = 2 self.player_two.turn_left(m) if arcade.key.D in self.held_keys: m = 1 if arcade.key.S in self.held_keys: m = 2 self.player_two.turn_right(m) if arcade.key.W in self.held_keys: self.player_two.accelerate() if arcade.key.S in self.held_keys: self.player_two.decelerate() # Machine gun mode... if self.ship.alive: if arcade.key.SPACE in self.held_keys: if self.shoot_timer == DEFAULT_SHOOT_TIMER and not self.mute: arcade.play_sound(self.ship_blast) if self.shoot_timer >= 0: self.shoot(self.ship) self.shoot_timer -= 1 else: if self.shoot_timer <= -(DEFAULT_SHOOT_TIMER * 3): self.shoot_timer = DEFAULT_SHOOT_TIMER else: self.shoot_timer -= 1 if self.player_two.alive: if arcade.key.GRAVE in self.held_keys: if self.shoot_timer_2 == DEFAULT_SHOOT_TIMER and not self.mute: arcade.play_sound(self.p_2_blast) if self.shoot_timer_2 >= 0: self.shoot(self.player_two) self.shoot_timer_2 -= 1 else: if self.shoot_timer_2 <= -(DEFAULT_SHOOT_TIMER * 3): self.shoot_timer_2 = DEFAULT_SHOOT_TIMER else: self.shoot_timer_2 -= 1 def shoot(self, ship): """ Fires bullets from a ship. :param ship: """ if not self.pause: bullet = "" distance = 80 if ship.type == 0: bullet = Laser() elif ship.type == 1: bullet = EnemyLaser() if not self.mute: arcade.play_sound(self.enemy_blast) distance = 50 elif ship.type == 2: bullet = LaserTwo() if (ship.type == 0 and self.power_up) or (ship.type == 2 and self.power_up_2): bullet.image = "Files/PURPLE_LASER.png" bullet.length = POWER_UP_BULLET_LENGTH bullet.width = POWER_UP_BULLET_WIDTH distance = 100 bullet.center.x = ship.center.x + math.cos(math.radians(ship.angle)) * distance bullet.center.y = ship.center.y + math.sin(math.radians(ship.angle)) * distance bullet.angle = ship.angle bullet.fire(ship) self.bullets.append(bullet) def reset(self): """ Resets values to previous state for a new game. """ self.held_keys = set() self.ship = Ship() self.player_two = PlayerTwoShip() self.asteroids = [] self.bullets = [] self.initial_rocks = INITIAL_ROCK_COUNT self.enemies = [] self.power_ups = [] self.score = 0 self.score_2 = 0 self.final_score = 0 self.final_score_2 = 0 self.power_up = False self.power_up_2 = False self.power_up_timer = POWER_UP_TIMER self.power_up_timer_2 = POWER_UP_TIMER self.shoot_timer = DEFAULT_SHOOT_TIMER self.shoot_timer_2 = DEFAULT_SHOOT_TIMER if self.game_over: self.play_count += 1 self.play_sound = True self.game_over = False def on_key_press(self, key: int, modifiers: int): """ Puts the current key in the set of keys that are being held. You will need to add things here to handle firing the bullet. """ if not self.game_over and self.pause: if key == arcade.key.R: self.reset() self.pause = False if self.ship.alive: self.held_keys.add(key) if key == arcade.key.SPACE: self.shoot(self.ship) if self.player_two.alive: self.held_keys.add(key) if key == arcade.key.GRAVE: self.shoot(self.player_two) if self.current_state == INSTRUCTIONS: if key == arcade.key.ENTER: self.current_state = GAME_RUNNING if self.current_state == GAME_OVER: if key == arcade.key.ENTER: self.reset() self.current_state = GAME_RUNNING if key == arcade.key.P: if not self.pause: self.pause = True if not self.mute: arcade.play_sound(self.pause_sound) if not self.game_over: self.set_alpha(.5) else: self.game_over_player.pause() else: self.pause = False if not self.game_over: self.media_player.play() self.set_alpha(1) else: self.game_over_player.play() if key == arcade.key.Q: if self.pause: self.quit = True if self.game_over: self.quit = True if self.quit: if key == arcade.key.Y: self.current_state = 4 if key == arcade.key.N: self.quit = False if not self.pause: self.game_over_player.play() if key == arcade.key.M: if not self.mute: self.media_player.volume = 0 self.game_over_player.volume = 0 self.mute = True else: self.media_player.volume = 1 self.game_over_player.volume = 1 self.mute = False def on_key_release(self, key: int, modifiers: int): """ Removes the current key from the set of held keys. """ if key in self.held_keys: self.held_keys.remove(key) def main(): """ Creates the game and starts it going """ Game(SCREEN_WIDTH, SCREEN_HEIGHT) try: pyglet.app.run() arcade.run() except AttributeError: print("Thanks for playing!") if __name__ == "__main__": main()
""" File: ta10-solution.py Author: Br. Burton This file demonstrates the merge sort algorithm. There are efficiencies that could be added, but this approach is made to demonstrate clarity. """ from random import randint MAX_NUM = 100 def merge(left, right): left_i = 0 right_i = 0 result = [] while left_i < len(left) and right_i < len(right): if left[left_i] < right[right_i]: result.append(left[left_i]) left_i += 1 else: result.append(right[right_i]) right_i += 1 result += left[left_i:] result += right[right_i:] return result def merge_sort(items): """ Sorts the items in the list :param items: The list to sort """ if len(items) == 1: return items half = len(items)//2 left = merge_sort(items[:half]) right = merge_sort(items[half:]) return merge(left, right) def generate_list(size): """ Generates a list of random numbers. """ items = [randint(0, MAX_NUM) for i in range(size)] return items def display_list(items): """ Displays a list """ for item in items: print(item) def main(): """ Tests the merge sort """ size = int(input("Enter size: ")) items = generate_list(size) items = merge_sort(items) print("\nThe Sorted list is:") display_list(items) if __name__ == "__main__": main()
count = {} with open("census.csv", "r") as f: for line in f: words = line.split(',') key = words[3] if key not in count: count[key] = 1 else: count[key] += 1 for key in count: print(count[key], "--", key)
import arcade SCREEN_WIDTH = 1080 SCREEN_HEIGHT = 600 class Point: def __init__(self): self.x = 0 self.y = 0 class Velocity: def __init__(self): self.dx = 0 self.dy = 0 class FlyingObjects: """ Creates class for Flying Objects. This is a base class for other flying objects classes that will be created. Contains methods: advance draw is_off_screen fire hit """ def __init__(self, radius=10, color=arcade.color.CARROT_ORANGE): """ Creates and sets class variables. :param radius: Default radius size :param color: Color default """ self.center = Point() self.center.x = 50 self.center.y = 50 self.velocity = Velocity() self.velocity.dx = 4 self.velocity.dy = 4 def advance(self, multiplier=1): """ Changes the position of a flying object :param multiplier: Value can be changed to increase speed of flying object """ self.center.x += self.velocity.dx * multiplier self.center.y += self.velocity.dy * multiplier def bounce_horizontal(self): """ Causes the ball to bounce horizontally """ self.velocity.dx = self.velocity.dx * (-1) def bounce_vertical(self): """ Causes the ball to bounce vertically """ self.velocity.dy = self.velocity.dy * (-1) class Doge(FlyingObjects): def __init__(self): super().__init__() def draw(self): img = "Doge.png" texture = arcade.load_texture(img) width = texture.width / 2.5 height = texture.height / 2.5 alpha = 1 # For transparency, 1 means not transparent x = self.center.x y = self.center.y arcade.draw_texture_rectangle(x, y, width, height, texture, alpha) class Game(arcade.Window): def __init__(self, width, height): """ Sets up the initial conditions of the game :param width: Screen width :param height: Screen height """ super().__init__(width, height) self.doge = Doge() arcade.set_background_color(arcade.color.WHITE) def on_draw(self): """ Called automatically by the arcade framework. Handles the responsibility of drawing all elements. """ # clear the screen to begin drawing arcade.start_render() # TODO: Set game states self.doge.draw() arcade.draw_text("wow",400,400, color=arcade.color.ORANGE, font_size=35) arcade.draw_text("such bounce", 200, 200, color=arcade.color.BLUE, font_size=30) arcade.draw_text("many cool", 700, 300, color=arcade.color.RED, font_size=25) arcade.draw_text("much python", 600, 150, color=arcade.color.GREEN, font_size=30) arcade.draw_text("very computer", 350, 500, color=arcade.color.BLACK, font_size=25) def update(self, delta_time): """ Update each object in the game. :param delta_time: tells us how much time has actually elapsed """ self.check_bounce() self.doge.advance() def check_bounce(self): if self.doge.center.x < 0 or self.doge.center.x > SCREEN_WIDTH: self.doge.bounce_horizontal() elif self.doge.center.y < 0 or self.doge.center.y > SCREEN_HEIGHT: self.doge.bounce_vertical() # Creates the game and starts it going def main(): window = Game(SCREEN_WIDTH, SCREEN_HEIGHT) arcade.run() if __name__ == "__main__": main()
print('What type of Dungeons and Dragons character are you? Answer this short personality test to find out.') birthday = str(input('Please enter your astrology sign, Ex. aquarius, sagittarius, et.,: ')) print() name_birth = ('Cupcake', 'Krusk', 'Gimble', 'Hennet', 'Tordek', 'Ragnara', 'Sandharrow', 'Eulad', 'Xerxes', 'Avery', 'Quinn', 'Riley', 'Kingsley',) name = 'a' if birthday == ('aquarius'): name = name_birth[0] elif birthday == ('pisces'): name = name_birth[1] elif birthday == ('capricorn'): name = name_birth[2] elif birthday == ('sagittarius'): name = name_birth[3] elif birthday == ('scorpio'): name = name_birth[4] elif birthday == ('libra'): name = name_birth[5] elif birthday == ('virgo'): name = name_birth[6] elif birthday == ('leo'): name = name_birth[7] elif birthday == ('cancer'): name = name_birth[8] elif birthday == ('gemini'): name = name_birth[9] elif birthday == ('taurus'): name = name_birth[10] elif birthday == ('aries'): name = name_birth[11] else: print(str(input('Sorry, check your spelling and only use lowercase. Enter your astrology sign, Ex. aquarius, sagitarius, et.,: '))) color = str(input('What is your favorite color? ')) print() evil_adj = ('0', 'fine and dandy', 'gentle', 'unpleasant', 'sniveling', 'destructive', 'revolting', 'wicked', 'hateful', 'depraved', 'heinous') clean_location = ('0', 'Buggers Swamp', 'Ratstool lagoon', 'Curmudgeon Cave', 'Fort solitude', 'Mediocre Village', 'Hillside Hamlet', 'Michaels Mansion', 'Crystal Castle', 'the Golden Temple of Ka', 'Anti-microbial Vaccum Chamber Palace') char_race = ('0', 'zombie', 'troll', 'curmudgeon', 'gnome', 'dwarf', 'human', 'elf', 'pixie', 'leprechaun', 'wood sprite') theft_noun = ('0', 'cupcake', 'bleeding heart', 'social butterfly', 'destroyer', 'usurper', 'nimrod', 'cretin', 'devil', 'simpleton', 'slavedriver') courage_weapon = ('0', 'large blunt object', 'branch from a willow tree', 'obtuse finger', 'unusually large thumb', 'flaming sword','death glare', '10,000 exploding fingers of fury manuever', '+3 utility knife', 'callous handshake', 'uncomfortable stare' ) role = ('fighter', 'ranger', 'cleric', 'paladin', 'wizard', 'magic-user', 'thief', 'ninja', 'archer', 'jester', 'shaman') clr = 'a' if color == ('white'): clr = role[0] elif color == ('black'): clr = role[1] elif color == ('pink'): clr = role[2] elif color == ('blue'): clr = role[3] elif color == ('yellow'): clr = role[4] elif color == ('red'): clr = role[5] elif color == ('green'): clr = role[6] elif color == ('orange'): clr = role[7] elif color == ('purple'): clr = role[8] elif color == ('brown'): clr = role[9] elif color == ('maroon'): clr = role[10] else: color = (str(input('Sorry, try a different color. What is your favorite color? '))) charisma = int(input('On a scale from 1-10, ten being the highest, how often do you spend time for recreation? ')) print() if charisma > 10: print(int(input('Sorry, please enter numbers 1-10 only. How often do you spend time for recreation? '))) elif charisma <= 0: print(int(input('Sorry, please enter numbers 1-10 only. How often do you spend time for recreation? '))) else: print(' ') theft = int(input('On a scale from 1-10, ten being the highest, How often do you steal small items at work, in a hotel, or from your classmates? ')) print() if theft > 10: print(int(input('Sorry, please enter numbers 1-10 only. How often do you steal small items at work, in a hotel, or from your classmates? '))) elif charisma <= 0: print(int(input('Sorry, please enter numbers 1-10 only. How often do you steal small items at work, in a hotel, or from your classmates? '))) else: print(' ') clean = int(input('On a scale from 1-10, ten being the highest, how clean do you require your surroundings to be? ')) print() if clean > 10: print(int(input('Sorry, please enter numbers 1-10 only. How clean do you require your surroundings to be? '))) elif clean <= 0: print(int(input('Sorry, please enter numbers 1-10 only. How clean do you require your surroundings to be?'))) else: print(' ') evil = int(input('On a scale from 1-10, ten being the highest, how much empathy do you have for seeing innocent people suffer while you benefit from their misfortune? ')) print() if evil > 10: print(int(input('Sorry, please enter numbers 1-10 only. How much empathy do you have for seeing innocent people suffer while you benefit from their misfortune?'))) elif evil <= 0: print(int(input('Sorry, please enter numbers 1-10 only. How much empathy do you have for seeing innocent people suffer while you benefit from their misfortune?'))) else: print(' ') courage = int(input('On a scale from 1-10, ten being the highest, how much courage do you have in killing spiders? ')) print() import textwrap print('Congratulations! You are %s the %s %s of %s!' % (name, evil_adj[evil], theft_noun[theft], clean_location[clean])) print('You are a %s %s and your weapon of choice is your %s.' % (char_race[charisma], clr, courage_weapon[courage])) beginning = (str(input('Do you wish to continue? Y/N' + '\n'))) if beginning == ('n'): print('So sorry to hear that! Quitting is the cowards way out. Have fun pecking around the yard for feed and laying eggs. Good-bye!') elif beginning ==('y'): strs = 'Excellent!!!! Now our adventure can begin! Imagine you find yourself in a strange building on Highline campus you have never seen before.' \ ' You walk cautiously down the hallway and come to a T intersection. You are facing a very large bookshelf. Half lazily looking at it while pondering your next move you ' \ 'slowly realize that all of the redbacked books on the shelf stand out and spell the word, KANG. Just then a large booming voice comes over the speakers. Who dares enter' \ ' the building of Professor Kang! Imediately a swarm of bats come flying out from an opening in the ceiling.' print(textwrap.fill(strs, 75)) user_input = (str(input('%s the %s %s dives to the floor: ' 'Make a dexterity roll by randomly choosing any lowercase alphabet key to continue....' % (name, evil_adj[evil], theft_noun[theft])))) print() def dexterity(): for (str) in user_input: if ('a' <= (str) <= 'g'): print('%s the %s %s just barely misses. -0 pts.\n' % (name, evil_adj[evil], theft_noun[theft])) elif ('h' <= (str) <= 's'): print('%s the %s %s cannot get out of the way in time. -5 pts.\n' % (name, evil_adj[evil], theft_noun[theft])) elif ('t' <= (str) <= 'z'): print('%s the %s %s fails utterly and completely. -10 pts.\n' % (name, evil_adj[evil], theft_noun[theft])) dexterity() strs = 'You get up, dust yourself off and notice a clue. A pair of size 12 footprints go left down the corrider. That must be Professor Kang! ' \ 'You walk down the corrider keeping an eye out for bats. The corrider leads to an open room full of cobwebs. You can see a light at the far end ' \ 'and move towards it. The cobwebs are getting thicker now, so thick you begin to wonder if they are even spiderwebs at all. As you get closer to the ' \ 'light you catch movement out of the corner of your eyes. About that time you trip and fall on something big and heavy. ' \ 'That is when you realize you are surrounded by large spiders that were feeding on the mummified corpse of a student intern. And now they are coming towards you!' + '\n' print(textwrap.fill(strs, 75)) user_input = (str(input('You raise your %s high as %s the %s prepares for battle: ' 'Make a strength roll and randomly choose any lowercase alphabet key to continue....\n' % (courage_weapon[courage], name, theft_noun[theft])))) print() def strength(): for (str) in user_input: if ('a' <= (str) <= 'g'): print('The %s is swung violently against the floor and bounces back in your face. -10 pts.\n' % (courage_weapon[courage])) elif ('h' <= (str) <= 's'): print('You cannot wield the %s effectively because your %s is wet -gross. +0 pts.\n' % (courage_weapon[courage], courage_weapon[courage])) elif ('t' <= (str) <= 'z'): print('Nothing can withstand the might of your %s. +10 pts.\n' % (courage_weapon[courage])) strength() strs = 'You head towards the light and discover it is the light to an open elevator door. You get inside ' \ 'and decide Professor Kang is most likely on the top floor. Only the best for Professor Kang, you grimace.' \ ' You try the button. Nothing happens. You try again, nothing. Two minutes later of kicking and cursing a ' \ 'ceiling panel falls down and hits you on the head. $@$*?$! and then you notice it leads to the elevator shaft. ' \ 'OK you think to yourself. I have been through bats and spiders so far so what is a little climb compared to that? You ' \ 'climb up to the cable and give it all you got. As you near the top you are surprised at how much energy you still have. ' \ 'Finally all of those trips to the gym paid off! With all that left over energy you easily swing yourself onto the floor in ' \ 'one heroic leap. And as you land you realize the shiny floor is shiny because it is all slippery and slick like black ice. No!!!!!' + '\n' print(textwrap.fill(strs, 75)) user_input = (str(input('%s the %s %s is approaching the floor at break neck speed: ' 'Make a dexterity roll by randomly choosing any lowercase alphabet key to continue....' % (name, evil_adj[evil], theft_noun[theft])))) print() def dexterity(): for (str) in user_input: if ('a' <= (str) <= 'g'): print('%s the %s %s just barely misses. -0 pts.\n' % (name, evil_adj[evil], theft_noun[theft])) elif ('h' <= (str) <= 's'): print('%s the %s %s cannot get out of the way in time. -5 pts.\n' % (name, evil_adj[evil], theft_noun[theft])) elif ('t' <= (str) <= 'z'): print('%s the %s %s fails utterly and completely. -10 pts.\n' % (name, evil_adj[evil], theft_noun[theft])) dexterity() strs = 'After you gather your bearings you realize the floors were freshly waxed. ' \ 'Nothing but the best for Professor Kang, you lament. Is that so?, a voice from behind you says. ' \ 'You whirl around and see yourself face to face with the Professor Kang! Or rather, face to ' \ 'belt buckle because Professor Kang is huge! However, despite his size he does look just ' \ 'like his canvas highline picture. He opens his mouth and breathes fire, his eyes glow red and as ' \ 'he tilts his head back a laser beam shoots out from under his nose!' + '\n' print(textwrap.fill(strs, 75)) user_input = (str(input('You raise your %s high as %s the %s prepares for battle: ' 'Make a strength roll and randomly choose any lowercase alphabet key to continue....\n' % (courage_weapon[courage], name, theft_noun[theft])))) print() def strength(): for (str) in user_input: if ('a' <= (str) <= 'g'): print('The %s is swung violently against the floor and bounces back in your face. -10 pts.\n' % (courage_weapon[courage])) elif ('h' <= (str) <= 's'): print('You cannot wield the %s effectively because your %s is wet -gross. +0 pts.\n' % (courage_weapon[courage], courage_weapon[courage])) elif ('t' <= (str) <= 'z'): print('Nothing can withstand the might of your %s. +10 pts.\n' % (courage_weapon[courage])) strength() strs = 'The great Professor Kang suddenly lurches backwards, then forwards, then backwards again before ' \ 'crashing to the floor! You gingerly walk over to the behemoth giant and notice something printed ' \ 'on the side of his neck. Made in China it says. What?! This was not Professor Kang at all but a robot. ' \ 'At about that time a very handsome, distinguished, refined, gentleman steps out from behind a curtain. ' \ 'I see you defeated my robot. Well I guess it can not be helped. I will just build another one with my godlike ' \ 'knowledge of python and the secrets of the universe. You see, for me building that robot is no more difficult ' \ 'than it is for an imbecile to wipe his nose with the back of his hand. But I digress, clearly you had a good ' \ 'reason to spend so much trouble to seek my audience. And now you have it. So, as the laymen say, what can I do you for? ' \ 'You look upon the greatness that is Professor Kang and you suddenly blurt out, My grades! In python class! ' \ 'How did I do?! To the embaressment of both of you. Professor Kang replies, Ah yes, your grades. Let us see, in my ' \ 'infinite wisdom I constructed the obstacles within this building as a test. If you want to know how you did in ' \ 'class, simply look at the results of your time in this obstacle course. Shall I show you? It is the least I can do.' + '\n' print(textwrap.fill(strs, 75)) ending = (str(input('Do you wish to know your final grade on the obstacle course? Y/N' + '\n'))) print() if ending == ('n'): print('As you give your answer you are shocked to see he is already on his way out. Grades are posted on canvas! Next time take my advice and trust me when I say canvas is the best way to reach me!') elif ending ==('y'): strs = 'Here is how you did:' cont = (str(input('Play again? Y/N' + '\n')))
''' Society is an econmicics game/simulator in which the player can control meny aspects of life within a "society" of one hundered people. Consequences of a player's actions will be as real as possible. Title: Society Arthor: third-meow Date: ''' # ## # ''' Goals include tax low wage cut off include math for find living costs include "cash on hand" vairable for finding money after living costs and tax karma stat homeless stat city wide crime? city wide "activitys" buildings could include bank lawers roads police stations (combats crime levels and karma?) truck depot state houseing buildings could unlock other buildings infrastuctor random events! earthquakes fires sudden lack of money changes of federal law requirements criminal activity in town state lawsuits people in society demanding/requesting stuff enviromentalists commuters anti-tax avoiders sick people homeless people end objectives prove to govenment you are stable by not dying for X days/years ''' print('\n') import time from math import floor from random import uniform import instruct #chance variables unhealthy_chance = 10.0 #the higher this is(out of 100) the more people will be unhealthy. unemployment_chance = 10.0 #the higher this is(out of 100) the more unemployed Society will be. get_sick_chance = 1.0 #the higher this is the more likely a person will get sick. get_better_chance = 1.0 #the higher this is the more likely a sick person will get better. new_job_chance = 1.0 #the higher this is the more likely a unemployed person will get a job. lose_job_chance = 1.0 #the higher this is the more likely a person is to lose their job. pay_rise_chance = 1.0 #the higher this is the more likely a person will get a pay rise pay_cut_chance = 1.0 #the higher this is the more likely a person will get a pay cut class Society: def __init__(self): self.people = 100 #number of people is society self.population = [] #holds instances of class "person" self.health = 0 #number of healthy people is society self.employment = 0 #number of employed people is society self.avr_salary = 0 #average salary of the people in society self.avr_savings = 0 #average savings of the people in society self.available_buildings = [] #list of buildings player could build self.available_buildings.append({'name':'Clinic','cost':1000,'cost/day':1.2,'health impact':+13,'employment impact':+15}) #available_buildings becomes a list of dictionarys with stats about the avalible buildings self.available_buildings.append({'name':'School','cost':300,'cost/day':2.1,'health impact':+2,'employment impact':+15}) self.available_buildings.append({'name':'Library','cost':50,'cost/day':1.0,'health impact':0,'employment impact':+1}) self.available_buildings.append({'name':'Park','cost':50,'cost/day':0.05,'health impact':+5,'employment impact':+1}) self.available_buildings.append({'name':'Dairy','cost':25,'cost/day':0.5,'health impact':0,'employment impact':+5}) self.buildings = [] #list of built buildings self.employment_offset = 0 self.health_offset = 0 self.salary_offset = 0 self.income_tax = 10 #income_tax is how much of each citizen's salary they pay for tax per year self.gov_funds = 20 #the govenments savings self.gov_costs = 0.5 #dayliy cost of govenment self.days = 0 #days so far self.years = 0 #years so far self.rst = False #allows game to be reset self.ext = False #allows game to exit for p in range(self.people): if uniform(0,100) < unhealthy_chance: temp_health = False else: temp_health = True if uniform(0,100) < unemployment_chance: temp_employed = False else: temp_employed = True temp_salary = uniform(10,200) #create instances of class "person" with random health status, employment status & random salary self.population.append(Person(temp_health,temp_employed,temp_salary)) print(''.join(instruct.instructions)) #print instructions from instruct.py self.update_stats() self.days = 0 #begin gameplay with day 0 def reset(self): #allows for self.rst to be "seen" outside self return self.rst def exit(self): #allows for self.ext to be "seen" outside self return self.ext def update_stats(self): self.days+=1 #every recalculate() is one day passing if self.days == 365: # if 365 days have past, 1 year has past and so we: self.years+=1 # update the year count +1 self.days = -1 # & set days to negitive 1 because the next day should be 1 year 0 days self.health = 0 self.employment = 0 self.avr_salary = 0 #set all statistics about society to 0 (we are about to update them) total_salary = 0 self.avr_savings = 0 total_savings = 0 for p in self.population: #for loop where p represents a instance of person from our list total_savings += p.savings #total savings is used to calculate average savings if p.health == True: self.health += 1 #this will keep track of how meny healthy people there are in our population if p.employed == True: self.employment += 1 #this will keep track of how meny employed people there are in our population total_salary += p.salary #total salary is used to calculate average salary self.gov_funds = (self.gov_funds + ((p.salary/100)*(self.income_tax/365))) #add each person's income tax to govement funds p.savings = p.savings + (p.salary - ((p.salary/100)*(self.income_tax/365)))/365 #add remaining money to person's savings self.avr_salary = total_salary/self.employment #calculate average salary self.avr_savings = total_savings/self.people #calculate average savings self.gov_funds -= self.gov_costs #take govement costs off govement funds def calibrate_chances(self,debug=False): #to be run in self.recalculate() after self.update_stats() but before if statments try: self.calibrated_get_sick_chance = get_sick_chance/self.health except ZeroDivisionError: self.calibrated_get_sick_chance = 100 try: self.calibrated_get_better_chance = get_better_chance/(self.people-self.health) except ZeroDivisionError: self.calibrated_get_better_chance = 100 try: self.calibrated_lose_job_chance = lose_job_chance/self.employment except ZeroDivisionError: self.calibrated_lose_job_chance = 100 try: self.calibrated_new_job_chance = new_job_chance/(self.people-self.employment) except ZeroDivisionError: self.calibrated_new_job_chance = 100 if debug: print('self.calibrated_get_sick_chance') print(self.calibrated_get_sick_chance) print('self.calibrated_get_better_chance') print(self.calibrated_get_better_chance) print('self.calibrated_lose_job_chance') print(self.calibrated_lose_job_chance) print('self.calibrated_new_job_chance') print(self.calibrated_new_job_chance) print('back to non-calibrated values') print('getsick') print(self.calibrated_get_sick_chance*self.health) print('getbetter') print(self.calibrated_get_better_chance*(self.people-self.health)) print('losejob') print(self.calibrated_lose_job_chance*self.employment) print('newjob') print(self.calibrated_new_job_chance*(self.people-self.employment)) def recalculate(self, printout=False): self.update_stats() self.calibrate_chances() for p in self.population: if p.health == True: if uniform(0,100) < (self.calibrated_get_sick_chance + (self.health_offset/self.people)): p.health = False else: if uniform(0,100) < (self.calibrated_get_better_chance - (self.health_offset/self.people)): p.health = True if p.employed == True: if uniform(0,100) < (self.calibrated_lose_job_chance + (self.employment_offset/self.people)): p.employed = False else: if uniform(0,100) < (self.calibrated_new_job_chance - (self.employment_offset/self.people)): p.employed = True if p.employed == True: if uniform(0,100) > pay_rise_chance: p.salary = p.salary/0.95 if uniform(0,100) > pay_cut_chance: p.salary = p.salary*0.95 if printout: self.dashboard() def dashboard(self): dash_labels=[] dash_values=[] dash_labels.append('Days') dash_labels.append((6-len('Days')) * ' ') dash_labels.append('Years') dash_labels.append((8-len('Years')) *' ') dash_labels.append('Health') dash_labels.append((9-len('Health')) * ' ') dash_labels.append('Employment') dash_labels.append((13-len('Employment')) * ' ') dash_labels.append('Average Salary') dash_labels.append((17-len('Average Salary')) * ' ') dash_labels.append('Income Tax(%)') dash_labels.append((16-len('Income Tax(%)')) * ' ') dash_labels.append('Gov Funds') dash_labels.append((12-len('Gov Funds')) * ' ') dash_labels.append('Average Savings') dash_values.append(str(self.days)) dash_values.append((6-len(str(self.days))) * ' ') dash_values.append(str(self.years)) dash_values.append((8-len(str(self.years))) * ' ') dash_values.append(str(self.health)) dash_values.append((9-len(str(self.health))) * ' ') dash_values.append(str(self.employment)) dash_values.append((13-len(str(self.employment))) * ' ') dash_values.append(str(floor(self.avr_salary))) dash_values.append((17-len(str(floor(self.avr_salary)))) * ' ') dash_values.append(str(self.income_tax)) dash_values.append((16-len(str(self.income_tax))) * ' ') dash_values.append(str(floor(self.gov_funds))) dash_values.append((12-len(str(floor(self.gov_funds)))) * ' ') dash_values.append(str(floor(self.avr_savings*100)/100)) dash_values.append('\n') print(''.join(dash_labels)) print(''.join(dash_values)) def action(self): while True: self.dashboard() usr_sig = input('Action> ') if usr_sig == 'n' or usr_sig == 'N': # n = next day break elif usr_sig == 'x' or usr_sig == 'X': # x = reset/exit usr_reset_sig = input('Do you want to reset(r), exit(x) or continue(c)>') if usr_reset_sig == 'r' or usr_reset_sig =='R': self.rst = True break elif usr_reset_sig == 'x' or usr_reset_sig == 'X': self.ext = True break elif usr_reset_sig == 'c' or usr_reset_sig == 'C': pass else: pass elif usr_sig == 't' or usr_sig == 'T': # t = tax change self.income_tax = int(input('Income tax(%)> ')) elif usr_sig == 'e' or usr_sig == 'E': # e = employ self.build() elif usr_sig == 'w' or usr_sig == 'W': # w = wait wait_for = int(input('Days>')) for i in range (wait_for): self.recalculate() elif usr_sig == 'DEV': command = input('COMMAND>') exec(command) else: break def build(self): print('Built Buildings') print( #print the column titles 'Index' #index number for selcting building +(14-len('Index'))*' ' #spacer +'Building' #building name +(18-len('Building'))*' ' #spacer +'Cost/day' #cost per day +(18-len('Cost/day'))*' ' #spacer ) for i in range(len(self.buildings)): print( #print details of available buildings str(i) #index number +(14-len(str(i)))*' ' #spacer +self.buildings[i]['name'] #building name +(18-len(self.buildings[i]['name']))*' ' #spacer +str(self.buildings[i]['cost/day']) #cost per day ) print('\n') print('Available Buildings') print( #print the column titles 'Index' #index number for selcting building +(14-len('Index'))*' ' #spacer +'Building' #building name +(18-len('Building'))*' ' #spacer +'Cost' #cost of building +(8-len('Cost'))*' ' #spacer +'Cost/day' #cost per day +(18-len('Cost/day'))*' ' #spacer +'Effect(heath/employment)' #effect of building on health and employment ) for i in range(len(self.available_buildings)): print( #print details of available buildings str(i) #index number +(14-len(str(i)))*' ' #spacer +self.available_buildings[i]['name'] #building name +(18-len(self.available_buildings[i]['name']))*' ' #spacer +str(self.available_buildings[i]['cost']) #cost +(8-len(str(self.available_buildings[i]['cost'])))*' ' #spacer +str(self.available_buildings[i]['cost/day']) #cost per day +(18-len(str(self.available_buildings[i]['cost/day'])))*' ' #spacer +'[' #open bracket for "effects" +str(self.available_buildings[i]['health impact']) #health effect +'/' #slash to separate effects +str(self.available_buildings[i]['employment impact']) #emplyment effects +']' ) print('\n') usr_sig = input('Build(b) or exit(x)>') if usr_sig == 'b' or usr_sig == 'B': usr_build_sig = int(input('Build(index number)>')) if self.gov_funds > self.available_buildings[usr_build_sig]['cost']: #if you have enough money self.gov_funds -= self.available_buildings[usr_build_sig]['cost'] #take money from gov_funds self.gov_costs += self.available_buildings[usr_build_sig]['cost/day'] #add the amount building costs per day to gov_costs self.health_offset += self.available_buildings[usr_build_sig]['health impact'] #add building's health impact to self's health_offset self.employment_offset += self.available_buildings[usr_build_sig]['employment impact'] #add building's health impact to self's employment_offset self.buildings.append(self.available_buildings[int(usr_build_sig)]) #add building to self.buildings else: #if you dont have enough money print('Not enough funds \n') #print "not enough funds" time.sleep(1) #wait 1 seconds else: pass class Person: def __init__(self,health,employed,salary): self.health = health self.employed = employed self.salary = salary #can be from 10K to 200K self.savings = 0 while True: mySociety = Society() while mySociety.reset() == False: mySociety.recalculate() mySociety.action() if mySociety.exit(): quit()
print('Hello world') def main(): pass #łańcuch znaków imie = "Adam" print (imie) print(type(imie)) print(type(5)) print(type(5.7)) print(type(True)) print(type(None)) # <class 'str'> # <class 'int'> # <class 'float'> # <class 'bool'> # <class 'NoneType'> print(imie[2]) imie ="Damam" imie = imie.lower() print(imie) wiek = 3000 # print(imie + " ma" +wiek + "lat.") print(imie + " ma " + wiek.__str__() + " lat.") print(imie + " ma " + str(wiek) + " lat.") print("{} ma {} lat.".format(imie, wiek)) print("{0} ma {1} lat.".format(imie, wiek)) # f-string print(f"{imie} ma {wiek} lat.") #pyformat.info liczba = 6.21376969 print(f"{liczba:.2f}") # typ liczbowy liczba = 5 liczbaf = 5.6 print(1 + 2) print(1 - 2) print(1 * 2) print(1 / 2) print(1 // 2) # dzielenie bez reszty print(1 ** 2) # potęgowanie print(1 % 2) # modulo tekst = "2137" liczba_z_tekstu = int(tekst, 16) print(liczba_z_tekstu) import math pi = 3.15 from math import * from math import pow , sqrt , pi import math as m # m.pow(2, 2) print(m.pi) # listy lista = [] # pusta lista lista2 = list() # pusta lista lista3 = [1, 2, 3] lista3 = [1, "Ala", True, None, [1, 2]] lista3[1] = "Zosia" macierz = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(macierz[1][1]) print(0.1 + 0.2 == 0.3) # Decimal print(f"{0.1:.20f}") lista = lista + lista3 lista += lista3 # słowniki słownik = {} słownik = dict() słownik3 = {"Klucz": "Wartość"} słownik3 ['Klucz'] słownik3 ['Klucz'] = 100 słownik3[0] = 999 print(słownik3) słownik3.keys() słownik3.values() print(słownik3.items()) # dict_items([('Klucz', 100), (0,999)])
#!/usr/bin/env python import numpy as np import math as m def angle_between_vectors(va = 'vector1' , vb = 'vector2'): ''' Finds the angle between two vectors in degrees (Internal Function) Args: va: first vector numpy array [x, y, z] vb: second vector numpy array [x, y, z] Returns: Angle: angle between vector_a and vector_b in degrees ''' RAD2DEG = 180/m.pi mag_va = np.linalg.norm(va) # sum(abs(v)**2)**(1./2) mag_vb = np.linalg.norm(vb) angle = m.acos(np.dot(va,vb)/mag_va/mag_vb)*RAD2DEG return angle
#!/usr/bin/env python def inverse_parabola(alpha, theta): ''' Applies Inverse Parabola Scalling Returns a number between 1 and 0.5 ''' return 1 - (2.0*alpha*alpha)/(theta*theta)
"""String""" import pprint def nicely_print(dictionary,print=True): """Prints the nicely formatted dictionary - shaonutil.strings.nicely_print(object)""" if print: pprint.pprint(dictionary) # Sets 'pretty_dict_str' to return pprint.pformat(dictionary) def change_dic_key(dic,old_key,new_key): """Change dictionary key with new key""" dic[new_key] = dic.pop(old_key) return dic def sort_dic_by_value(dic): return {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}
from random import randint from datetime import * import time def end_buble(buble): def wrap(b): print(f"{buble(b)}\n array is sorted by buble sort") return wrap def end_stupid(stupid): def wrap(data): print(f"""{stupid(data)}\narray is sorted by stupid sort""") return wrap def timer_fun(func): """Декоратор для вычесления времени работы функции""" def wrap(a): print(a) start = datetime.now() func(a) finish = datetime.now() time_d = (finish - start).total_seconds() * 1000 print("Time running", time_d) return wrap @timer_fun @end_buble def buble(a): N = len(a) for i in range(N - 1): for j in range(N - i - 1): if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] return a @timer_fun @end_stupid def stupid(data): i, size = 1, len(data) while i < size: if data[i - 1] > data[i]: data[i - 1], data[i] = data[i], data[i - 1] i = 1 else: i += 1 return data five_hundred = [randint(1,1000) for i in range(500)] thousend = [randint(1,1000) for i in range(1000)] hundred = [randint(1,1000) for i in range(100)] buble(hundred) buble(five_hundred) buble(thousend) five_hundred = [randint(1,1000) for i in range(500)] thousend = [randint(1,1000) for i in range(1000)] hundred = [randint(1,1000) for i in range(100)] stupid(hundred) stupid(five_hundred) stupid(thousend)
from sqlite3 import * #объект коонекта conn = connect("Exercise_DB.db") #Создание / Подключение к базе данных с указанным названием #Создание объекта курсора (уникальный указатель на данные) cursor = conn.cursor() #Создание таблици """ CREATE TABLE name_table (name_column_1, surname_column_2, age_column_3) """ #cursor.execute("""CREATE TABLE Person # (name, surname, age)""") #Типы данных #TEXT - обычная строка #INTEGER - целый тип данных #FLOAT - вещественный тип данных #BLOB - большие бинарные файлы #BIT - 0 / 1 логический тип данных #MONEY - тип данных для хранениея денежных едениц #NVARCHAR - хранит данные в unicode #cursor.execute("""CREATE TABLE Table_2 # (userName NVARCHAR(20), email NVARCHAR(30), phone NVARCHAR(20), age INTEGER)""") #Запрос на удаление таблицы #cursor.execute("""DROP TABLE Person""") # Переименование таблицы #cursor.execute("""ALTER TABLE Table_2 RENAME TO Account """) #Типы ограничений #Настройка главного ключа #cursor.execute("""CREATE TABLE Table_2 # (id INT PRIMARY KEY, # userName NVARCHAR(20), # email NVARCHAR(30), # phone NVARCHAR(20), #age INTEGER)""") #Настройка точки отсчета для поля #cursor.execute("""CREATE TABLE Table_3 # (id INTEGER PRIMARY KEY AUTOINCREMENT, # userName NVARCHAR(20) NULL, # email NVARCHAR(30) NOT NULL, # phone NVARCHAR(20), #age INTEGER)""") #НАстройка уникальности данных #cursor.execute("""CREATE TABLE Table_5 # (id INTEGER PRIMARY KEY AUTOINCREMENT, # userName NVARCHAR(20) NULL, # email NVARCHAR(30) NOT NULL, # phone NVARCHAR(20) UNIQUE, #age INTEGER)""") #Настройка значения по умолчанию #cursor.execute("""CREATE TABLE Table_6 # (id INTEGER PRIMARY KEY AUTOINCREMENT, # userName NVARCHAR(20) DEFAULT Taras777, # email NVARCHAR(30) NOT NULL, # phone NVARCHAR(20) UNIQUE, #age INTEGER)""") # ДОюовление данных в таблицу #cursor.execute("""INSERT INTO Account #VALUES('Ivan1997', '[email protected]', '+3800994354321', 33)""") #cursor.execute("""INSERT INTO Table_2 #VALUES(1, '[email protected]', '+3800994354321', '33',0)""") #cursor.execute("""INSERT INTO Table_3 #VALUES(1,'', NULL, '+3800994354321', 33)""") #add dannie list_1 = ["dfsdf","sdf.sd","1323413"] cursor.execute(f"""INSERT INTO Table_2 VALUES(4, ?, ?, ?,4)""", list_1) #Подтверждение изменений conn.commit() #Закрыть подключение conn.close()
"""код_договора код_клиента код_кредита дата_выдачи сумма 1 ItSorce 23 04.10.2018 1000000 2 —odewars 3 17.01.2019 20000 3 ItCraft 17 31.12.2017 340000 4 SoftVerse 1 25.07.2020 900000 5 ItLand 44 06.06.2016 3000000 6 22 11.08.2011 440000 7 PostCode 22 830000 8 CraftSource 13 31.12.2017 340000 9 SoftVerse 1 25.07.2020 900000 10 ItCraft 17 31.12.2017 340000 """ from copy import deepcopy from sqlite3 import * n = input() conn = connect(n) #Создание / Подключение к базе данных с указанным названием #Создание объекта курсора (уникальный указатель на данные) cursor = conn.cursor() with open("part_data_1.txt", "r", encoding="utf-8") as file: h = file.readline().split() table_1 = [] for line in file.readlines(): a = line.split() #print(a) if len(a) < 5: if a[0].isdigit() == False: a.insert(0,'') if a[1].isdigit() == True: a.insert(1, '') if a[2].isdigit() == False: a.insert(2, '') if a[3].isdigit() == True: a.insert(3, '') if a[4].isdigit() == False: a.insert(4, '') table_1.append(a) cursor.execute(f"""CREATE TABLE table_1 ({str(h[0])}, {str(h[1])}, {str(h[2])}, {str(h[3])}, {str(h[4])})""") table_2 = deepcopy(table_1) for i in table_1: cursor.execute("""INSERT INTO table_1 VALUES(?,?,?,?,?)""",i) #second table cursor.execute(f"""CREATE TABLE table_2 ({str(h[0])}, {str(h[1])} UNIQUE, {str(h[2])}, {str(h[3])}, {str(h[4])})""") j=1 for i in table_1: #print(table_1_help) try: cursor.execute("""INSERT INTO table_2 VALUES(?,?,?,?,?)""",i) except IntegrityError: i[1] = 'hillel'+str(j) j+=1 cursor.execute("""INSERT INTO table_2 VALUES(?,?,?,?,?)""", i) #third table cursor.execute(f"""CREATE TABLE table_3 ({str(h[0])}, {str(h[1])}, {str(h[2])} , {str(h[3])} NOT NULL, {str(h[4])})""") for i in table_2: #print(table_1_help) if i[3] == '': print("You write some incoret inputs") continue cursor.execute("""INSERT INTO table_3 VALUES(?,?,?,?,?)""",i) conn.commit() # Закрыть подключение conn.close()
def me(x,y): if x==y: print("Yup!!") else: print("nope!!") use_input = input("enter your favourite number:".upper()) user_input = input("enter your brother's favourite number:".upper()) me(use_input,user_input)
# Use gradient descent to build linear regression model for predicting # height, age, weight # output alpha, num_iters, bias, b_age, b_weight import pandas as pd import sys import numpy as np import csv from pandas import DataFrame learning_rates = [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10] # add vector column for the intercept at the front of the matrix # get mean for each feature column def get_mean(x): #return sum(x)/len(x) return np.mean(x, axis = 0) # get standard deviation for each feature column def get_sd(x): return np.std(x, axis =0) # return np.std(x, axis = 0) # scale each feature (height and weight) by its standard deviation def scale_feature(f): return (f - get_mean(f))/get_sd(f) # run this method with each alpha 100 times # pick a 10th learning rate def gradient_descent(num_iter, feat_data, Y, output_file): # 3 dimensions, 1 intercept at the front, 2 features beta = np.zeros(feat_data.shape[1]) output = [] for alpha in learning_rates: count = 0 # f(xi) - yi for i in range(num_iter): count +=1 error = np.dot(feat_data, beta) - Y #R = np.sum(error ** 2) # now we are calculaing gradient descent rule for x in range(feat_data.shape[1]): beta[x] -= (alpha * (1/len(Y))) * np.sum(error * feat_data[:, x]) result = beta[0], beta[1], beta[2] row = [alpha] row.append(count) row.extend(result) output.append(row) with open(output_file, 'w') as f: write = csv.writer(f, delimiter = ',') write.writerows(output) #return alpha, num_iter, beta[0], beta[1], beta[2] def gradient_descent_add(new_alpha, new_iter, feat_data, Y, output_file): beta = np.zeros(feat_data.shape[1]) count = 0 output = [] for i in range(new_iter): count +=1 error = np.dot(feat_data, beta) - Y for x in range(feat_data.shape[1]): beta[x] -= (new_alpha * (1/len(Y))) * np.sum(error * feat_data[:, x]) result = beta[0], beta[1], beta[2] row = [new_alpha] row.append(count) row.extend(result) output.append(row) with open(output_file, 'a') as f: write = csv.writer(f, delimiter = ',') write.writerows(output) # https://stackoverflow.com/questions/29287224/pandas-read-in-table-without-headers if __name__ == "__main__": input_file = sys.argv[1] data = pd.read_csv('input2.csv', header=None) # type is numpy data = data.as_matrix() # get number of rows or dimension dim = data.shape[1] # add intercept at the beginning data = np.insert(data, obj = 0, values =1, axis = 1) # age and weight are features intercept = data[:, 0] age = data[:, 1] weight = data[:, 2] height = data[:, 3] # this would be the middle 2 columns feature_data = data[:,1:3] #print(feature_data) output_csv = sys.argv[2] scaled_age = scale_feature(age) scaled_weight = scale_feature(weight) normalized_feature_data = np.column_stack((intercept, scaled_age, scaled_weight)) #print(normalized_feature_data) num_iter = 100 #out_file = open(output_csv, 'w') """for alpha in learning_rates: i = 0 for each in range(num_iter): i = i + 1 result = gradient_descent(alpha, i, normalized_feature_data, height) print(result) """ gradient_descent(num_iter, normalized_feature_data, height, output_csv) gradient_descent_add(0.8, 70, normalized_feature_data, height, output_csv) # To graph the data #output_data = pd.read_csv('output2.csv', header= None) """alpha = output_data[:, 0] print(alpha) num_iter = output_data[:, 1] b_0 = output_data[:, 2] b_age = output_data[:, 3] b_weight = output_data[:, -1] lin_reg_weights = output_data[:,2:5] print(lin_reg_weights) """ # plot each feature on xy plane # plot regressionn equation as plane in xyz space
#Text of challenge: "Have the function LetterCapitalize(str) take the #str parameter being passed and capitalize the first letter of each #word. Words will be separated by only one space." def LetterCapitalize(str): return str.title() print LetterCapitalize(raw_input())
#Using Python language, have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it def FirstFactorial(num): factorial = 1 for i in range(1,num+1): factorial=factorial*i return factorial print FirstFactorial(raw_input())
import sys import datetime Feb = 2 TwentyNine = 29 def dayOfDate(date): days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] dayNumber = date.weekday() return days[dayNumber] def checkLeapYear(year): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False def findNearestLeapYears(year): years = [] if year % 4 == 0: years.append(year-4) years.append(year+4) elif year % 4 == 2: if (checkLeapYear(year+2)): years.append(year+2) else: years.append(year+6) if(checkLeapYear(year-2)): years.append(year-2) else: years.append(year-6) elif year % 4 == 1: if(checkLeapYear(year-1)): years.append(year-1) else: years.append(year+3) else: if(checkLeapYear(year+1)): years.append(year+1) else: years.append(year-3) return years def yearFunction(year): if((len(year) == 4) and (int(year[0]) > 0)): year = int(year) print("input :") print(year) # Check Leap Year isLeapYear = checkLeapYear(year) if isLeapYear: extraDay = datetime.date(year, Feb, TwentyNine) print("Output :") print("Its a leap year") print("Day : "+dayOfDate(extraDay)) else: nearestLeapYears = findNearestLeapYears(year) print("Output :") print("This is not a leap year") print("Nearest leap years :") for y in nearestLeapYears: extraDay = datetime.date(y, Feb, TwentyNine) print("Year : "+str (y)) print("Day : "+dayOfDate(extraDay)) else: print("Invalid Year Input") if __name__ == "__main__": y = (sys.argv[1]) if(y): yearFunction(y) else: print("Invalid Year Input")
import math import sys import random def distance(city1, city2): return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) def read_input(filename): with open(filename) as f: cities = [] for line in f.readlines()[1:]: # Ignore the first line. xy = line.split(',') cities.append((float(xy[0]), float(xy[1]))) return cities if __name__ == "__main__": param = sys.argv cities = read_input (param[1]) n = len(cities) route = [0] * n sum_distance = 0 route[1] = random.randint(1, n-1) x = route[1] for a in range(2, n): if (a + x) == n : route[a] = x + 1; elif (a + x) > n: route[a] = a + x -n; else : route[a] = a + x; #print route for i in range(0, n-1): sum_distance += distance(cities[route[i]], cities[route[i+1]]) sum_distance += distance(cities[route[n-1]], cities[route[0]]) d_best = sum_distance route_best = [0] * n sum1 = 0 y = 0 for b in range(1, n): for a in range(b, n): sum1 = 0 y = route[1] route[1] = route[a] route[a] = y for i in range(0, n): c0 = route[i] if i < n - 1: c1 = route[i+1] else: c1 = route[0] sum1 += distance(cities[c0], cities[c1]) if sum1 < d_best : d_best = sum1 for i in range(0, n) : route_best[i] = route[i] print route_best print d_best
# -*- coding: utf-8 -*- def error(S,w): ''' renvoie l'erreur quadratique commis par le perceptron, avec le vecteur de pondération w, l'échantillon S. ''' err = 0 for i in range(len(S)): err += 0.5 * (S[i][1] - output_perceptron(S[i][0],w))**2 return err def errorDerivative(S,w,j): ''' renvoie la derivee de l'erreur par rapport à la pondération n°j. ''' derivative = 0 for i in range(len(S)): derivative += (S[i][1] - output_perceptron(S[i][0],w)) * (-int(S[i][0][j])) return derivative def output_perceptron(s,w): ''' renvoie le resultat du percetron (1 ou 0), avec les ponderations du vecteur w, et le vecteur x en input (string). ''' res = 0 for i in range(len(s)): res += int(s[i])*int(w[i]) return ( res > 0 ) #Algorithme d'apprentissage par erreur : def learn_linear(S,w,eps): while(error(S,w)) : for i in S: err = i[1] - output_perceptron(i[0],w) for j in range(8): w[j] = w[j] + err * int(i[0][j]) * eps return w #Algorithme d'apprentissage par minimisation de l'erreur quadratique : #Méthode du gradient : def learn_errorMinimisationGradientMethod(S,w,eps,iteration): while (iteration > 0): derivative = [] for j in range(8): derivative.append(errorDerivative(S,w,j)) for j in range(8): w[j] = w[j] - derivative[j] * eps iteration -= 1 return w # ***************** # TEST # ***************** S=[("1111110",0),("0110000",1),("1101101",0),("1111001",1),("0110011",0),("1011011",1),("0011111",0),("1110000",1),("1111111",0),("1111011",1)] # ajout d'une entrée toujours active pour le bias : for i in range( len(S) ): S[i] = ("1"+ S[i][0] , S[i][1]) w=[] for i in range(8): w.append(1)
is_male = False is_tall = False if is_male and is_tall: print("You are a male and tall or both") elif is_male and not(is_tall): print("Your are a male but not tall") elif not(is_male) and is_tall: print("Your are not a male but you are tall") else: print("You neither male or tall") # comparator> !=, ==, >=, <= def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 print(max_num(3, 100, 5))
def check(x): try: num2=int(x) #an to num den einai int den einai oyte to num2 ara epistrefei false calc(num2) return True except: return False def calc(y): a=2 #dinei mia timh diaforh toy 1 sth metavlhth a gia na ksekinhsei h diadikasia while a!=1: #oso o telikos arithmos einai monopshfios epanalave num3 = y*3 + 1 array = [int(i) for i in str(num3)] #vazei se lista kathe pshfio ths num3 print('Τα ψηφία του τελικού αριθμού είναι: ' + str(array)) s=sum(array) print('Το άθροισμα των ψηφίων είναι: ' + str(s)) a=len(str(s)) if a==1: print('Ο τελικός αριθμός έχει 1 ψηφίo, οπότε ολοκληρώνετε η διαδικασία') break #an a=1 h diadikasia teleiwnei kai h synarthsh check epistrefei true print('Ο τελικός αριθμός έχει '+str(a)+' ψηφία, οπότε επαναλαμβάνετε η διαδικασία με το '+str(s)+'\n') num3 = s #kane pali thn diadikasia me arxikh metavlhth thn s y = s num='b' #dinei esfalmenh timh sth metavlhth num gia na zhththei arithmos while not check(num): #oso h synarthsh check epistrefei False (otan dhladh o xrhsths dinei string) zhta ksana arithmo num = input("Δώσε έναν φυσικό αριθμό:")
# https://www.hackerrank.com/contests/world-codesprint-8/challenges/prime-digit-sums import math import time primes = [] nav_map = {} # connect graph for groups of five soln_cache = [] # solution cache limit = 10 ** 9 + 7 # as per requirements def primesieve(n): primes = [] limit = int(n ** 0.5 + 1) sieve = [True] * limit for i in range(2, limit): if not sieve[i]: continue for j in range(i * i, limit, i): sieve[j] = False primes.append(i) return primes def is_prime(n): for p in primes: if p >= n: break elif n % p == 0: return False return n > 1 def sum_digits(s): """ Sum digits of string :param s: string with only digits """ return sum(map(int, s)) def is_special(n): l = int(math.log10(n) + 1) # number of digits d = str(n) for i in range(l - 2): if not is_prime(sum_digits(d[i : i + 5])): return False if not is_prime(sum_digits(d[i : i + 4])): return False if not is_prime(sum_digits(d[i : i + 3])): return False return True # vacuous truth # build map and function cache def build_map(k, v): if len(k) != 5: return if k not in nav_map: nav_map[k] = set() nav_map[k].add(k[-4:] + str(v)) # build list of numbers satisifying prime requirement # possible optimisation only track last and first 5 digits def specials(s=3, t=6): l = list(filter(is_special, range(10 ** (s - 1), 10 ** s))) for i in range(s, t): ns = [] for n in l: d = str(n) if is_prime(sum_digits(d[-2:] + "0")): ns.append(n * 10) build_map(d, 0) if is_prime(sum_digits("0" + d[:2])): build_map("0" + d[:-1], d[-1]) if is_prime(sum_digits("00" + d[:1])): build_map("00" + d[:-1], d[-1]) for j in range(1, 10): before = str(j) + d first3 = sum_digits(before[:3]) first4 = 2 if i < 3 else first3 + int(before[3]) first5 = 2 if i < 4 else first4 + int(before[4]) if is_prime(first3) and is_prime(first4) and is_prime(first5): ns.append(int(before)) build_map(before[:i], before[-1]) after = d + str(j) last3 = sum_digits(after[-3:]) last4 = 2 if i < 3 else last3 + int(after[-4]) last5 = 2 if i < 4 else last4 + int(after[-5]) if is_prime(last3) and is_prime(last4) and is_prime(last5): ns.append(int(after)) build_map(d, j) if i == t - 1: break else: l = set(ns) return t - 1, l def count(t, n=0): """ Count number of paths of given length """ if t < 0: raise ValueError("negative length not allowed") elif t < 5: return [0, 9, 90, 303, 280][t] else: i = t - n st = len(soln_cache) - 1 if i > st: for i0 in range(st, i): c_map = {} for k, v in soln_cache[-1].items(): if k not in nav_map: continue for ns in nav_map[k]: if ns not in c_map: c_map[ns] = 0 c_map[ns] += v c_map[ns] %= limit soln_cache.append(c_map) return sum(soln_cache[i].values()) % limit ## main solution s_t = time.time() q = int(input().strip()) # q = 2 * 10**4 # get prime factors st = time.time() primes = primesieve(45) et = time.time() print("sieving:", round(et - st, 3), primes) # num special 5 digit numbers st = time.time() t, sps = specials() et = time.time() print("specials:", round(et - st, 3), len(sps)) # initialise solution cache soln_cache.append({}) for s in sps: soln_cache[0][str(s)] = 1 for i in range(q): n = int(input().strip()) # n = 4 * 10**5 st = time.time() c = count(n, t) et = time.time() print("counting:", round(et - st, 3), c) e_t = time.time() print("time:", round(e_t - s_t, 3))
x=input('enter x') z= input('enter z') sum=x+z print(sum)
# Enter your code here. Read input from STDIN. Print output to STDOUT n = input() arr = [int(i) for i in raw_input().strip().split()] mean = float (sum(arr)) / n print mean def calc_median(input_list): sorted_list = sorted(input_list) l = len(sorted_list) if(l%2 == 0): med = float (sorted_list[l/2] + sorted_list[(l/2)-1])/2 return med else: med = sorted_list[l/2] return med median = calc_median(arr) print median def mode(inp_list): sort_list = sorted(inp_list) dict1 = {} for i in sort_list: count = sort_list.count(i) if i not in dict1.keys(): dict1[i] = count maximum = 0 #no. of occurences max_key = -1 #element having the most occurences for key in dict1: if(dict1[key]>maximum): maximum = dict1[key] max_key = key elif(dict1[key]==maximum): if(key<max_key): maximum = dict1[key] max_key = key return max_key print mode(arr) def std_deviation(arr,mean): sum_sqr_distances = 0 float(sum_sqr_distances) for i in arr: sum_sqr_distances += (i-mean)**2 std_dev = 0.0 float(std_dev) std_dev = (sum_sqr_distances/n)**0.5 return round(std_dev,1) std_dev = std_deviation(arr,mean) print std_dev """ 95% confidence interval ------------------------ Lower limit = M - Z.95 M Upper limit = M + Z.95 M where, M = mean Z.95 = 1.96 M = standard error of mean = / (n^0.5) where = std. deviation """ def calc_confidence_interval(arr,mean,std_dev): std_error = float(std_dev/(len(arr)**0.5)) lower = 0.0 upper = 0.0 lower = mean - (1.96 * std_error) upper = mean + (1.96 * std_error) print str(lower) + " " + str(upper) return 1 calc_confidence_interval(arr,mean,std_dev)
import turtle turtle.width(8) turtle.color("green") for i in range(18): turtle.penup() turtle.goto(0,0) turtle.seth(i*20) turtle.pendown() for j in range(5): turtle.circle(40,80) turtle.circle(-40,80)
n1 = 34 n2 = 34.4 n3 = 100 s1 = 'Hello' s2 = 'World' total_n = n1 + n2 + n3 print(total_n) n1 = n1 + 1 print(n1 + 1) n2 = n2 + 10 print(n2) n3 = n3 - 50 print(n3) n3 = n3 * 50 print(n3) n3 = n3 / 50 n1 += n1 + 1 print(n1) n2 += 10 print(n2) n3 *= 50 print(n3) n3 /= 50 print(n3) concat_string = s1 + s2 print(concat_string) s1 = s1 + "Yoohoo" print(s1) s2 = s2 + "Yippee" print(s2) new_s1 = s1 print(new_s1) s1 = "Some other values" print(s1) some_n = n3 print(some_n) n3 *= 1000 print(n3)
from arrays import Array def mergeSort(lyst): # lyst list being sorted for i in xrange(1, 10) # copyBuffer temporary space needed during merge copyBuffer = Array(len(lyst)) mergeSortHelper(lyst, copyBuffer, 0, len(lyst) - 1) def mergeSortHelper(lyst, copyBuffer, low, high): # lyst list being sorted # copyBuffer temporary space needed during merge # low, high bounds of sublist # middle midpoint of sublist if low < high: low = lyst[0] high = lyst[len(lyst) - 1] middle = (low + high) / 2 mergeSortHelper(lyst, copyBuffer, low, middle) mergeSortHelper(lyst, copyBuffer, middle + 1, high) merge(lyst, copyBuffer, low, middle, high) def merge(lyst, copyBuffer, low, middle, high): # lyst list being sorted # copyBuffer temporary space needed during merge # low, high bounds of sublist # middle midpoint of sublist # middle + 1 beginning of the second sorted sublist # high end of second sorted sublist # Initialize i1 and i2 to the first items in each sublist i1 = low i2 = middle + 1 # Interleave items from the esublists into the # copyBuffer in such a way that order is maintained. for i in xrange(low, high + 1): if i1 > middle: copyBuffer[i] = lyst[i2] i2 += 1 elif i2 > high: copyBuffer[i] = lyst[i1] i1 += 1 elif lyst[i1] > lyst[i2]: copyBuffer[i] = lyst[i1] i1 += 1 else: copyBuffer[i] = lyst[i2] i2 += 1 for i in xrange(low, high + 1): lyst[i] = copyBuffer[i]
#Convolution applied on images #Edge Detection #download standard image #wget --quiet https://ibm.box.com/shared/static/cn7yt7z10j8rx6um1v9seagpgmzzxnlz.jpg --output-document bird.jpg #already downloaded #1. load image (.jpg format) #2. convert image to grayscale #3. convolve image with edge detector kernel, store result in new matrix; display matrix in image format #4. normalize the matrix; update pixel values #5. store it as new matrix; display the result #importing import numpy as np from scipy import signal from scipy import misc import matplotlib.pyplot as plt from PIL import Image #default file name: bird.jpg (enter in command line) print("Enter name of the file (default: bird.jpg") raw = raw_input() im = Image.open(raw) #converting image to greyscale (using Luma transform) image_gr = im.convert("L") print("\nOriginal type: %r \n\n" % image_gr) ###convert image to a matrix with values from 0 to 255 (uint8) arr = np.asarray(image_gr) print("After conversion to numerical representation: \n\n %r" % arr) #activate matplotlib for ipython #%matplotlib inline #not needed #plot image (using matplotlib.pyplot) imgplot = plt.imshow(arr) imgplot.set_cmap('gray') #other maps: gray, winter, autumn print("\n Input image converted to gray scale: \n") plt.show(imgplot) #edge detector kernel kernel = np.array([[0, 1, 0],[1, -4, 1],[0, 1, 0]]) #gradient (new) after edge detector kernel slide over arr grad = signal.convolve2d(arr, kernel, mode='same', boundary='symm') print('GRADIENT MAGNITUDE - Feature Map') fig, aux = plt.subplots(figsize=(10, 10)) #display image from the matrix edgeplot = aux.imshow(np.absolute(grad), cmap='gray') #saving op in a variable to display print("\n Grayscale image converted to edge detection \n") plt.show(edgeplot) #when dealing with real applications, convert pixel values to range from 0 to 1 -> called "normalization" type(grad) #new matrix grad_biases with updated pixel values grad_biases = np.absolute(grad) + 100 #adding 100 to each pixel value grad_biases[grad_biases > 255] = 255 #maximizing upto 255 print('GRADIENT_BIASES MAGNITUDE - Feature Map') fig, aux = plt.subplots(figsize=(10, 10)) grad_biases_edgeplot = aux.imshow(np.absolute(grad_biases), cmap='gray') plt.show(grad_biases_edgeplot)
def authenticate(pwd1,pwd2): if (pwd1 != pwd2): return False else: return True def getName(): name = raw_input("Please Enter Your Name:\n") return name def getPassword(): pwd2 = raw_input("Please Enter Your Password:\n") return pwd2 if __name__=="__main__": usr=getName() pwd2=getPassword() num_attempts=3 pwd1 = "Mike1" for x in range(num_attempts): authenticate(pwd1, pwd2) if authenticate(pwd1,pwd2): print "My name is " + usr + " and password is " + pwd1 break else: print "" + str(num_attempts - x) + " attempts left. Please try again" usr = getName() pwd2 = getPassword()
import sys import csv str_max = [] def main(): # checks to validate usage argv = sys.argv argc = len(sys.argv) if argc != 3: print("Usage: dna.py input/File.csv input/File.txt") exit(1) # opens data file and saves the headers and number of headers with open(argv[1], "r") as df: d_read = csv.DictReader(df) headers = d_read.fieldnames num_head = len(headers) df.close() # initialize a list to store the length of each header, then loop through to find length of each header head_len = [] for i in range(num_head): head_len.append(len(headers[i])) # open sequence file and save as a string sf = open(argv[2], "r") sequence = sf.read() sf.close() # variable that is number of chars in string sequence s_len = len(sequence) # initialize lists for number of STRs in a given set of repititions and the max number of STR repetitions in the string str_count = [] str_max = [] # loop through number of headers, append to STR count and STR max for i in range(num_head): str_count.append(0) str_max.append(0) s = 0 # loops through sequence string to find STRs while (s < s_len): # enters if the string at that point in the string is equal to the header name it is checking for, then increments by the length of that header if sequence[s:(s + head_len[i])] == headers[i]: str_count[i] = str_count[i] + 1 s = s + head_len[i] if (str_count[i] > str_max[i]): str_max[i] = str_count[i] # enters in all other conditions, increments by 1 else: # checks if the most recent string of STRs is greater than the previous highest string, resets STR count and replaces max if most recent STR count is higher than previous max str_count[i] = 0 s = s + 1 # re-open datafile with open(argv[1], "r") as df: d_read = csv.DictReader(df) # loops through each row in list of dicts, resets i and max to 0 prior to looping through each value in the row for row in d_read: i = 0 match = 0 # loop through each value in the current dict for k, v in row.items(): # skips first column, still iterates 1 so that str_max[0] is not compared if k == 'name': i += 1 continue # enters if value of a given row equals the number of STRs counted in the sequence, increments match by 1 if int(v) == str_max[i]: match += 1 # enters if all values in a given dict are equal to the STR maximums found in the sequence and exits if match == num_head - 1: print(row['name']) return i += 1 # prints No match if most recent if statments is not entered print("No Match") main()
lado=input("Ingrese el lado del cuadrado:") lado=int(lado) superficie= lado*lado print("La superficie el cuadrado es: ") print(superficie)
class Stack: def __init__(self): self.values = [] def isEmpty(self): Empty = False if self.values == []: Empty = True return Empty def push(self, value): self.values.append(value) def pop(self): return self.values.pop() def peek(self): return self.values[len(self.values)-1] def size(self): return len(self.values) class NodeTree: def __init__(self, value): self.left = None self.right = None self.value = value def insert(self,value): if self.value: if value < self.value: if self.left is None: self.left = NodeTree(value) else: self.left.insert(value) elif value > self.value: if self.right is None: self.right = NodeTree(value) else: self.right.insert(value) else: self.value = value def findval(self, value): if value < self.value: if self.left is None: return False return self.left.findval(value) elif value > self.value: if self.right is None: return False return self.right.findval(value) else: return True def displayTree(self): if self.left: self.left.displayTree() return self.value, if self.right: self.right.displayTree()
def add(tree, value): if tree == None: newNode = {"data":value, "left":None, "right":None} return newNode elif tree["data"] == value: return tree elif value < tree["data"]: tree["left"] = add(tree["left"], value) return tree elif value > tree["data"]: tree["right"] = add(tree["right"], value) return tree def height(tree): if tree == None: return 0 leftHeight = height(tree["left"]) rightHeight = height(tree["right"]) tallestChildHeight = max(leftHeight, rightHeight) return 1+ tallestChildHeight def search(tree, value): if tree == None: return False elif tree["data"] == value: return True elif value < tree['data']: return search(tree['left'],value) elif value > tree['data']: return search(tree['right'],value) def toList(tree): if tree == None: return [] else: leftList = toList(tree['left']) rightList = toList(tree['right']) return leftList + [tree['data']] + rightList def display(tree, indent = 0): if tree == None: return else: display(tree['right'], indezt +4) print(' '*indent + str(tree['data'])) display(tree['left'], indezt +4) def delete(tree, value): if tree == None: return elif value < tree['data']: tree['left'] = delete(tree['left'], value) return tree elif value > tree['data']: tree['right'] = delete(tree['right'], value) return tree else: ### no subtrees - root is only noode in the tree if tree['left'] == None and tree['right'] == None: return None ### root has a right subtree, but no left subtree elif tree['left'] == None: return tree['right'] ### root has a left subtree, but no right subtree elif tree['right'] == None: return tree['left'] ### else: newRoot = maxValue(tree['left']) tree['data'] = newRoot tree['left'] = delete[tree['left'], newRoot) return tree def maxValue(tree): if tree['right'] == None: return tree['data'] else: return maxValue(tree['right']
############################################### Linked list functions with recursion def createTestList(): lastNode = {"data":"C", "next":None} secondNode = {"data":"B","next":lastNode} firstNode = {"data":"A", "next":secondNode} return firstNode def linkedListToString(LL): stringResult = "|" if(LL == None): return "" stringResult += str(LL["data"]) if(LL["next"] != None) : stringResult += ", " return stringResult + linkedListToString(LL["next"]) else: return stringResult def getNodeAtIndex(LL, index): currentNode = LL currentIndex = 0 if (index < 0) or (LL == None): return None elif(index == 0): return LL return getNodeAtIndex(LL["next"], index - 1) def insertValue(LL, index, value): if (index < 0): print("error") return LL if (index == 0) : newNode = {"data": value, "next": LL} return newNode if (LL == None): print("Error") return LL tail = LL["next"] LL["next"] = insertValue(LL["next"], index - 1, value) return LL def deleteValue(LL, index): if (index < 0): print("error") return LL elif (LL == None): print("error") return LL elif (index == 0) : return LL["next"] else: LL["next"] = deleteValue(LL["next"], index - 1) return LL def setValue(LL, index, value): if(index < 0) or (LL == None) : print("error") elif(index == 0) : LL["data"] = value else: setValue(LL["next"], index - 1, value) def getLength(LL): if(LL == None): return 0 return 1 + getLength(LL["next"]) ##################################################### Towers of Hanoi def hanoi(numDisks, startPeg = 1, destPeg = 3, tempPeg = 2): if (numDisks == 1) : print("Move disk from peg", startPeg, "to peg", destPeg) else: hanoi(numDisks - 1, startPeg, tempPeg, destPeg) print("Move disk from peg", startPeg, "to peg", destPeg) hanoi(numDisks - 1, tempPeg, destPeg, startPeg) def hanoi2(numDisks, startPeg = 1, destPeg = 3, tempPeg = 2): if (numDisks == 0) : return else: hanoi2(numDisks - 1, startPeg, tempPeg, destPeg) print("Move disk from peg", startPeg, "to peg", destPeg) hanoi2(numDisks - 1, tempPeg, destPeg, startPeg) #################################################### Maze def findPath(maze, row=0, col=0): ### Assume the maze is square ### Maze is a 2D list size = len(maze) ### Error handling if(row < 0) or ( row >= size) or (col < 0) or (col >= size): return False elif maze[row][col] != " ": return False maze[row][col] = "." ### Base case, we're done if (row ==(size -1)) and (col == (size - 1)): return Truw ### Recursion, not yet in bottem left corner if findPath(maze, row, col - 1): #Left return True elif findPath(maze, row, col +1 ): #Right return True elif findPath(maze, row - 1, col): #Up return True elif findPath(maze, row + 1, col): #Down return True maze[row][col] = " " return False ##################################################### Expressions def evaluate(expr): if isinstance(expr, dict): leftVal = evaluate(expr['left']) rightVal = evaluate(expr['right']) if expr['operator'] == '+': return leftVal + rightVal elif expr['operator'] == '-': return leftVal - rightVal elif expr['operator'] == '*': return leftVal * rightVal elif expr['operator'] == '/': return float(leftVal / rightVal) else: print("error: unknown operator") else: return expr def exprString(expr): if isinstance(expr, dict): opPrecedence = precedence(expr) leftPrecedence = precedence(expr['left']) rightPrecendece = precedence(expr['right']) leftString = exprString(expr['left']) rightString = exprString(expr['right']) if leftPrecedence < opPrecedence: leftString = '(' + leftString + ')' if rightPrecedence < opPrecedence: rightString = '(' + rightString + ')' return leftString + expr["operator"] + rightString else: return str(expr) def printExpr(expr): print(exprString(expr)) def precedence(expr): if isinstance(expr, dict): if expr['operator'] in "*/": return 2 else: return 1 else: return 3
import pandas as pd import numpy as np import time from .neighborhoods import solution_generator, aux_neighborhoods, LS_neighborhoods from .auxiliaries import calculatecosts def VND(df, costs, n = 2, n1 = 10, n2 = 10, alpha = 0.3, nsol = 20): """ VND algorithm. Args: df: Dataframe that specifies which subset cover which elements costs: costs of choosing each subset neigh: number that indicates which neighborhood to head n: n condition for second neighborhood n1: n condition for third neighborhood n2: n condition for fourth neighborhood alpha: percentage of the top half subsets that will be considered. nsol: number of times that it will run Output: subsets: newly chosen subsets cost: cost function """ # Start time start_time = time.perf_counter() # Generate First Solution and calculate cost initial_subsets = solution_generator(df, costs) initial_cost = calculatecosts(initial_subsets, costs) print('Initial Solution: %s' % initial_cost) # Aux neigh = 1 cost_before = initial_cost subsets_before = initial_subsets # Start neighborhood search while neigh <= 4: print(neigh) # Find solution that belongs to the j neighborhood new_subsets = aux_neighborhoods(df, costs, subsets_before, neigh, n, n1, n2, alpha, nsol) new_cost = calculatecosts(new_subsets, costs) print('New Solution: %s' % new_cost) if new_cost < cost_before: neigh = 1 # Update values cost_before = new_cost subsets_before = new_subsets print('NEW IMPROVEMENT') else: neigh += 1 # Time counter time_now = time.perf_counter() - start_time if time_now > 300: print('BREAK') done = True break print('Final Solution: %s' % cost_before) subsets_before = [subset + 1 for subset in subsets_before] return cost_before, subsets_before def VNS(df, costs, n = 2, n1 = 10, n2 = 10, alpha = 0.3, nsol = 20): """ VNS algorithm. Args: df: Dataframe that specifies which subset cover which elements costs: costs of choosing each subset neigh: number that indicates which neighborhood to head n: n condition for second neighborhood n1: n condition for third neighborhood n2: n condition for fourth neighborhood alpha: percentage of the top half subsets that will be considered. nsol: number of times that it will run Output: subsets: newly chosen subsets cost: cost function """ # Generate First Solution and calculate cost initial_subsets = solution_generator(df, costs) initial_cost = calculatecosts(initial_subsets, costs) print('Initial Solution: %s' % initial_cost) # Aux neigh = 1 cost_before = initial_cost subsets_before = initial_subsets # Start neighborhood search while neigh <= 4: # Find solution that belongs to the j neighborhood new_subsets = aux_neighborhoods(df, costs, subsets_before, neigh, n, n1, n2, alpha, nsol) new_cost = calculatecosts(new_subsets, costs) print('New Solution: %s' % new_cost) # More Auxiliaries new_cost_before = new_cost new_subsets_before = new_subsets local_optimum = False # Check if it is a local optimum while not local_optimum: newsub = aux_neighborhoods(df, costs, new_subsets_before, neigh, n, n1, n2, alpha, nsol) newc = calculatecosts(newsub, costs) print('New Solution: %s' % newc) if newc < new_cost_before: new_cost_before = newc new_subsets_before = newsub print('NEW IMPROVEMENT') else: local_optimum = True print('LOCAL OPTIMUM') if new_cost_before < cost_before: cost_before = new_cost_before subsets_before = new_subsets_before neigh = 1 else: neigh += 1 print('Final Solution: %s' % cost_before) subsets_before = [subset + 1 for subset in subsets_before] return cost_before, subsets_before def SA(df, costs, T0, Tf, L, r, neigh = 3, n = 2, n1 = 10, n2 = 10, alpha = 0.3, nsol = 20): """ Simulated Anealing algorithm. Args: df: Dataframe that specifies which subset cover which elements costs: costs of choosing each subset subsests: chosen subsets neigh: number that indicates which neighborhood to head n: n condition for second neighborhood n1: n condition for third neighborhood n2: n condition for fourth neighborhood alpha: percentage of the top half subsets that will be considered. nsol: number of times that it will run Output: subsets: newly chosen subsets cost: cost function """ # Start time start_time = time.perf_counter() # Generate First Solution and calculate cost initial_subsets = solution_generator(df, costs) initial_cost = calculatecosts(initial_subsets, costs) print('Initial Solution: %s' % initial_cost) # Initialize T T = T0 # Aux cost_before = initial_cost subsets_before = initial_subsets best_cost = 300000000000 best_subsets = [] done = False # Start Loop while T > Tf: l = 0 # Start second Loop while l < L: l += 1 new_cost = 0 new_subsets = [] # Find solution that belongs to the j neighborhood new_subsets = aux_neighborhoods(df, costs, subsets_before, neigh, n, n1, n2, alpha, nsol) new_cost = calculatecosts(new_subsets, costs) print('New Solution: %s' % new_cost) d = new_cost - cost_before if d < 0: # Update solution cost_before = new_cost subsets_before = new_subsets print('NEW IMPROVEMENT') # Store best results if best_cost > cost_before: best_cost = cost_before best_subsets = subsets_before # Time counter time_now = time.perf_counter() - start_time if time_now > 300: print('BREAK') done = True break else: rand = np.random.uniform(0,1) if rand < np.exp(-d/T): # Update solution cost_before = new_cost subsets_before = new_subsets print('SET BACK') # Time counter time_now = time.perf_counter() - start_time if time_now > 300: print('BREAK') done = True break T = r*T if done: break print('Final Solution: %s' % best_cost) best_subsets = [subset + 1 for subset in best_subsets] return best_cost, best_subsets def LS(df, costs, neigh, n = 2, n1 = 10, n2 = 10, alpha = 0.3, nsol = 20): """ Initialize nsol local search and chooses the one with the best results. Args: df: Dataframe that specifies which subset cover which elements costs: costs of choosing each subset neigh: number that indicates which neighborhood to head n: n condition for second neighborhood n1: n condition for third neighborhood n2: n condition for fourth neighborhood alpha: percentage of the top half subsets that will be considered nsol: number of iterations to run Output: subsets: newly chosen subsets """ # Start time start_time = time.perf_counter() # Generate First Solution and calculate cost initial_subsets = solution_generator(df, costs) initial_cost = calculatecosts(initial_subsets, costs) print('Initial Solution: %s' % initial_cost) # To store results zs = [] subset_options = [] for i in range(nsol): print('Iteration Number %s' % i) subsets_option = LS_neighborhoods(df, costs, initial_subsets, neigh, n, n1, n2, alpha) cost_option = calculatecosts(subsets_option, costs) zs.append(cost_option) subset_options.append(subsets_option) # Time counter time_now = time.perf_counter() - start_time if time_now > 300: print('BREAK') done = True break # Select minimum, if multiple, pick randomly zs = pd.Series(zs) min_zs = zs.min() mins = zs[zs == min_zs] rand_min = mins.sample(1).index[0] subsets = subset_options[rand_min] print('Final Solution: %s' % min_zs) subsets = [subset + 1 for subset in subsets] return min_zs, subsets
import random import itertools values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs'] deck = list(itertools.product(values, suits)) def shuffle_deck(deck): count = 0 while count < len(deck): current = deck[random.randint(0, len(deck)-1)] if current in deck: deck.remove(current) deck.insert(0, current) count += 1 return deck print(shuffle_deck(deck))
int_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for num in int_list: num = num + 1 print(num)
age = input('Enter your age: ') def define_age(age): age = int(age) if 3 <= age < 7: return 'Kindergarten' elif 7 <= age <= 18: return 'School' elif 18 < age <= 23: return 'College' else: return 'Some job' res = define_age(age) print(res)
# encoding-UTF-8 # AUTOR: José Antonio Vázquez Gabián # Este programa imprime tu indice de masa corporal #Calcula tu peso y estatura def calcularIMC (peso,estatura): x = (peso)/(estatura**2) return x def saberEstado(imc): if imc<18.5: p= ("Bajo Peso") if imc>=18.5 and imc<=25: p= ("Peso Normal") if imc>25: p= ("Sobrepeso") return p def main(): #se evalua tu rango de estado llamando a la funcion anterior Kg=float(input("Teclea tu peso en kilogramos: ")) M=float(input("Teclea tu estatura en metros: ")) imc=calcularIMC(Kg,M) print("Tu IMC es de: %.2f " % imc) rango=saberEstado(imc) print("Tu estado es de: " ,rango) main()
################################################################################## # Step 1: Create tables in our database to hold trip info, pickups and dropoffs # # DEPRECATED: Initially wrote this to setup the backend. However, quickly found out that # Heroku uses Postgresql so used this to play with data using the SQLite browser. # ################################################################################### import os import csv import sqlite3 from datetime import datetime conn = sqlite3.connect('rides.db') c = conn.cursor() # Create table c.execute('CREATE TABLE trips (TIMESTAMP datetime, MONTH integer, DAY integer, HOUR integer, MINUTE integer, PICKUP_LAT real, PICKUP_LNG real, DROPOFF_LAT real, DROPOFF_LNG real, PICKUP_LOCATION varchar(25), DROPOFF_LOCATION varchar(25))') c.execute('CREATE TABLE pickups (TIMESTAMP datetime, MONTH integer, DAY integer, HOUR integer, MINUTE integer, PICKUP_LAT real, PICKUP_LNG real, PICKUP_LOCATION varchar(25), TOTAL_PICKUPS integer, PRIMARY KEY (PICKUP_LAT, PICKUP_LNG))') c.execute('CREATE TABLE dropoffs (TIMESTAMP datetime, MONTH integer, DAY integer, HOUR integer, MINUTE integer, DROPOFF_LAT real, DROPOFF_LNG real, DROPOFF_LOCATION varchar(25), TOTAL_PICKUPS integer, PRIMARY KEY (DROPOFF_LAT, DROPOFF_LNG))') conn.commit() # Insert Trip details into Table trips for a given file. def insert_trips(file_name, conn): c = conn.cursor() line_num = 0 pick_up = True with open(file_name, 'r') as csv_file: reader = csv.reader(csv_file, delimiter=',') for row in reader: line_num += 1 # Skip header if line_num == 1: print("Header row, skipping") continue if pick_up: pick_up = False date_object = datetime.strptime(row[0], '%m/%d/%Y %H:%M:%S') pickup_lat = float(row[1]) pickup_lng = float(row[2]) pickup_location = str(pickup_lat) + ',' + str(pickup_lng) else: pick_up = True drop_off_lat = float(row[1]) drop_off_lng = float(row[2]) drop_off_location = str(drop_off_lat) + ',' + str(drop_off_lng) trip_tuple = [date_object, date_object.month, date_object.day, date_object.hour, date_object.minute, pickup_lat, pickup_lng, drop_off_lat, drop_off_lng, pickup_location, drop_off_location] # This statement will actually insert a single row into the table called trips c.execute("INSERT INTO trips VALUES (?,?,?,?,?,?,?,?,?,?,?)", trip_tuple) conn.commit() print("Done iterating over file contents - the file has been closed now!") # Iterate through all the csv files in the directory and insert that data into our database localExtractFilePath = "./RawData/" for file in os.listdir(localExtractFilePath): if file.endswith(".csv"): # For each CSV file, call the function insertTrips to store its data to the table trips. insert_trips(localExtractFilePath + file, conn) c = conn.cursor() cursor = c.execute('INSERT INTO pickups SELECT timestamp, month, day, hour, minute, pickup_lat, pickup_lng, pickup_location, COUNT(pickup_location) as total_pickups FROM Trips GROUP BY pickup_location ORDER BY COUNT(pickup_location) DESC') cursor = c.execute('INSERT INTO dropoffs SELECT timestamp, month, day, hour, minute, dropoff_lat, dropoff_lng, dropoff_location, COUNT(dropoff_location) as total_dropoffs FROM Trips GROUP BY dropoff_location ORDER BY COUNT(dropoff_location) DESC') conn.commit()
# # When creating a camera you need to specify the map's width and height and the # screen's width and height. # # When you want to calculate the offset of everything call calculate_position() # with the player/character's x and y coordinates and it returns the camera's # coordinates. To use those the best idea (probably) is to subtract them from # whatever coordinates you already have. Kinda like this: # # cam = Camera( map_width, map_height, screen_width, screen_height ) # camera_x, camera_y = cam.calculate_position( player_x, player_y ) # screen.blit( tile_x - camera_x, tile_y - camera_y ) # # TODOs: # # - When the map is smaller than the screen, the map gets drawn on the # top-left corner without any nice padding. I'm thinking of positioning the # camera on the center of the map in this case. # class Camera( ): def __init__( self, map_width, map_height, screen_width, screen_height, tile_size = 32 ): self.mw, self.mh = map_width, map_height self.sw, self.sh = screen_width, screen_height self.ts = tile_size def calculate_position( self, player_x, player_y ): # center camera on player x, y = player_x - self.sw / 2, player_y - self.sh / 2 if x < 0: # lock left side x = 0 elif x > ( self.mw * self.ts ) - ( self.sw ): # lock right side x = ( self.mw * self.ts ) - ( self.sw ) if y < 0: # lock top y = 0 elif x > ( self.mh * self.ts ) - ( self.sh ): # lock bottom y = ( self.mh * self.ts ) - ( self.sh ) return( x, y )
''' @author: whuan @contact: @file: lesson2.py @time: 2018/10/20 19:47 @desc:控制语句,文件操作 ''' # 条件语句 import math import time num = 5 if num == 3: print("3") elif num == 5: print("5") else: print("no") # 循环 a = 1 while (a <= 10): print(a) a += 1 else: print("结束") for letter in "Ilovepython": print(letter) else: print("over") fruits = ['banana', 'apple', 'mango'] for fruit in fruits: print(fruit) for index in range(len(fruits)): print("当前水果", fruits[index]) else: print("没有水果了") print(math.e) print(math.pi) print(time.time()) print(time.asctime(time.localtime(time.time()))) def printInfo(name="小花", age=10, *vartuple): print("名字:", name, ",年龄:", age) for var in vartuple: print("朋友是:", var) return printInfo("小明", 10, '小黑', '小绿') # 使用了不定长函数后不能再指定参数顺序 # printInfo(age=18,name="小红","小黑","小路") printInfo() ''' lambda匿名函数 ''' sum = lambda a, b: a + b sum(1, 8) print(sum(1, 10)) ''' open文件 读文件 #r表示是文本文件,rb是二进制文件 写文件 #w表示是文本文件,wb是二进制文件 'r':读 'w':写 'a':追加 'r+' == r+w(可读可写,文件若不存在就报错(IOError)) 'w+' == w+r(可读可写,文件若不存在就创建) 'a+' ==a+r(可追加可写,文件若不存在就创建) ''' try: file = open("foo.txt", "r") str = file.read() print(str) print("文件名:", file.name) except ValueError: print("文件操作错误",IOError) else: print("文件操作成功") finally: print("结束了") file.close() try: file = open("foo.txt", "a") str = file.write("\npython is very intersting") print(str) print("文件名:", file.name) except ValueError: print("文件操作错误",IOError) else: print("文件操作成功") finally: print("结束了") # aa="these are words my written" # file.write(aa) # file.write("these are words my written".decode('utf8')) # file.write(aa.split(','.encode(encoding="utf-8"))) file.close()
# -*- coding: utf-8 -*- """ Created on Sat Aug 20 15:09:52 2016 @author: Kazuma Wittick """ maxMode = 0 array = [12, 3, 4, 5, 6, 7, 8, 9, 1, 4,4, 6, 2,1, 5, 76, 6, 6, 6 ] for i in array: getMode = array.count(i) if getMode > maxMode: maxMode = getMode modeNumber = i print modeNumber
exam_st_date = (11, 12, 2014) (day,month,year) = exam_st_date #it's tuple unpacking exercise :) how fun :) needed to refresh how to do it print("The examination will start from : ",day,"/",month,"/",year)
import os import sys from csv import reader class CompanyInfo(object): """ The company info is stored in it """ def __init__(self, company_name): """called when object isntance is created""" self.__company_price__list = [] self.__company_time_list = [] self.__name = company_name def add_info(self, year, month, price): """ add the company info to each list""" self.__company_time_list.append(year + ' ' + month) self.__company_price__list.append(price) def find_peak_share_time(self): """find the peak time when the share was at the highest peak position """ indices = [i for i, x in enumerate(self.__company_price__list) if x == max(self.__company_price__list)] time_string = '' for index in indices: time_string += self.__company_time_list[index] + ' ' # appending all the time strings when the rate was at peak position return time_string, self.__company_price__list[indices[0]] def share_info(self): """ return a formatted form of the final output""" return self.__name + ' ---> the peak time is %s and Share at that time is %s '% self.find_peak_share_time() class MainHandler(object): """ Triggers the main process """ def __init__(self): self.company_list = [] def final_info(self): for company in self.company_list: print company.share_info() # printing the final output def add_company(self, company): self.company_list.append(company) def process_row(self,row): """ Process each row of the csv file and write it to dictornary """ year = row[0] month = row[1] share_prices = row[2:] for x in range(0, len(self.company_list)): self.company_list[x].add_info(year, month, share_prices[x]) # populating the company info (year month and share_price) def read_from_file(self,filename): """ Read the given csv file """ with open(filename, 'rb') as file_object: csv_reader = reader(file_object) companies_name = next(csv_reader) # fetching the header first for company_name in companies_name[2:]: self.add_company(CompanyInfo(company_name)) # making companyinfo object for each company try : while(True): self.process_row(next(csv_reader)) # processing the data except: pass # stoping the iteration file_object.close() if __name__ == "__main__": # check whether the filename is given or not if len(sys.argv) != 2 : print 'Please enter the filename' sys.exit() # check whether the file exists or not if os.path.exists(sys.argv[1]): my_main_handler = MainHandler() # making an instance of Mainhandler my_main_handler.read_from_file(sys.argv[1]) # calling the readfile function my_main_handler.final_info() # printing the final info to the console else : print 'Please check the file is present or not'
# python3 import sys def compute_min_refills(distance, tank, stops): start = 0 noOfStops = 0 stops.append(distance) for i in range(len(stops)): if (start + tank) >= distance: return noOfStops for j in range(i, len(stops)): if (start + tank) < stops[j]: initialstop = start start = stops[j-1] noOfStops += 1 finalstop = start if initialstop == finalstop: return -1 break if __name__ == '__main__': d = int(input()) m = int(input()) numberOfStops = int(input()) stops = input() stops = list(map(int, stops.split())) print(compute_min_refills(d, m, stops))
from random import randint spock= int(1) lagarto= int(2) pedra= int(3) papel= int(4) tesoura= int(5) jogador_contagem=0 computador_contagem=0 jogador=0 computador=0 while computador_contagem<3 and jogador_contagem<3: computador= randint(1,5) jogador= int(input("Vamos jogar! Para isso, é necessário que você escolha algum número. 1: spock 2: lagarto, 3: pedra, 4: papel e 5: tesoura:")) #jogador sendo spock if jogador==1: if computador==1: print("Houve um empate!") elif computador==2: print("Você perdeu") computador_contagem=computador_contagem+1 elif computador==3: print("Voce ganhou") jogador_contagem=jogador_contagem+1 elif computador==4: print("Voce perdeu") computador_contagem=computador_contagem+1 elif computador==5: print("voce ganhou") jogador_contagem=jogador_contagem+1 #jogador sendo lagarto if jogador==2: print(computador) if computador==2: print("Houve um empate") elif computador==1: print("Voce ganhou") jogador_contagem=jogador_contagem+1 elif computador==3: print("Voce perdeu") computador_contagem=computador_contagem+1 elif computador==4: print("Voce perdeu") computador_contagem=computador_contagem+1 elif computador==5: print("voce ganhou") jogador_contagem=jogador_contagem+1 #jogador sendo pedra if jogador==3: if computador==3: print("Houve um empate") elif computador==1: print("Voce perdeu") computador_contagem=computador_contagem+1 elif computador==2: print("Voce ganhou") jogador_contagem=jogador_contagem+1 elif computador==4: print("Voce perdeu") computador_contagem=computador_contagem+1 elif computador==5: print("voce ganhou") jogador_contagem=jogador_contagem+1 #jogador sendo papel if jogador==4: if computador==4: print("Houve um empate") elif computador==1: print("Voce ganhou") jogador_contagem=jogador_contagem+1 elif computador==2: print("Voce perdeu") computador_contagem=computador_contagem+1 elif computador==3: print("Voce ganhou") jogador_contagem=jogador_contagem+1 elif computador==5: print("voce perdeu") computador_contagem=computador_contagem+1 #jogador sendo tesoura if jogador==5: if computador==5: print("Houve um empate") elif computador==1: print("Voce perdeu") computador_contagem=computador_contagem+1 elif computador==2: print("Voce ganhou") jogador_contagem=jogador_contagem+1 elif computador==3: print("Voce perdeu") computador_contagem=computador_contagem+1 elif computador==4: print("voce ganhou") jogador_contagem=jogador_contagem+1 computador_contagem=0 if jogador_contagem==(3): print("voce ganhou o jogo, parabéns mestre") elif computador_contagem==3: print("infelizmente voce perdeu o jogo, e uma pena. Tente novamente") else: print("deu erro")
from tkinter import * import wikipedia def search_me(): entery_value=e.get() text.delete(1.0,END) try: answer_value=wikipedia.summary(entery_value) text.insert(INSERT,answer_value) except: text.insert(INSERT,'please check your input or internet connection') scr=Tk() scr.title('wikipedia summary applicaton') scr.config(bg='blue') frametop=Frame(scr,bg="blue") e=Entry(frametop,bg='yellow') e.pack() b=Button(frametop,text='search',command=search_me,bg='red',font=('times',10,'bold')) b.pack() frametop.pack(side=TOP) framebottom=Frame(scr) scroll=Scrollbar(framebottom) scroll.pack(side=RIGHT,fill=Y) text=Text(framebottom,height=20,width=40,wrap='word',yscrollcommand=scroll.set,bg='yellow') text.pack() scroll.config(command=text.yview) framebottom.pack() scr.mainloop()
import numpy as np from query import * from config import * def add_quotes(str): """Adds quotes on the end and returns the output""" return f'\'{str}\'' def csv_reader(address, list_size, quotes): """ Address is the csv file location, list_size is the size of the row in the table to be inserted, quotes is a one hot vector which represents which position need to be surrounded by "" """ df = np.loadtxt(address, dtype=np.str, delimiter=",") rows = [] """Splitting the csv file into rows""" for i in range(0, len(df), list_size): rows.append(list(df[i: i + list_size])) """Cleaning the entries by inserting quotes""" for row in rows: for index in range(0, len(row)): row[index] = strip_space(row[index]) if(quotes[index] == 1): row[index] = add_quotes(row[index]) """ Converting numbers to int or float""" for row in rows: for index in range(0, len(row)): if quotes[index] == 0: """Skipping dates""" if row[index].find('-') != -1: continue elif row[index].find('.') != -1: row[index] = float(row[index]) else: row[index] = int(row[index]) return rows def Insert_csv(address, table_name): index = table_names.index(table_name) quotes = all_quotes[index] rows = csv_reader(address, len(quotes), quotes) for row in rows: insert_row(table_name, row) for table in table_names: Insert_csv(f"../data/{table}.csv", table) # table_names = ["players", # "tournament_type", # "matches", # "participating_teams", # "heroes", # "base_stats", # "abilities", # "player_characters", # "match_description", # "match_performance", # "teams", # "teams_teams", # "roles", # "teams_player"] # table = "player_characters" # Insert_csv(f"../data/{table}.csv", table) # select * from teams_player;
# Littel Machine Learning Test # # Using the popular Iris flower data set and sklearn along with Python # http://scikit-learn.org/stable/ # https://en.wikipedia.org/wiki/Iris_flower_data_set # The iris flower dataset is like the "hello world" program of datasets. # It's not meant to be used in practical applications, but it's good for testing machine learning techniques. from sklearn.datasets import load_iris iris = load_iris() print(list(iris.target_names)) # ['setosa', 'versicolor', 'virginica'] from sklearn import tree classifier = tree.DecisionTreeClassifier() classifier = classifier.fit(iris.data, iris.target) # this is clearly a setosa, all the features do match up print(classifier.predict([[5.1,3.5,1.4,0.2]])) # = [0] # this is ambiguous, as the last feature does not "fit" clearly print(classifier.predict([[5.1,3.5,1.4,1.5]])) # = [0] or [1] # The decision tree classifier randomly chooses a feature # that it thinks will make the best comparison which results in probabilistic behavior.
def main(): num = int(input("Enter a number: ")) if num % 2 == 0: print(f"{num} is even") else: print(f"{num} is odd") if __name__ == '__main__': main()
array = [] count = 0 try: n = int(input('Введите количество элементов в массиве: ')) for i in range(n): array.append(int(input('Введите элемент массива: '))) delta = int(input('Введите DELTA: ')) except ValueError: print('Ошибка, введите целое число') else: for j in range(len(array) - 1): for l in range(len(array) - j - 1): if array[l] > array[l + 1]: array[l], array[l + 1] = array[l + 1], array[l] for k in range(len(array)): if array[k] - array[0] == delta: count += 1 print('Количество чисел, отличающихся от наименьшего элемента на DELTA - ', count)
import turtle import datetime import time def draw_hour(t, hour): t.color("blue") t.width(3) t.right((360/12) * hour) t.forward(150) t.forward(-150) t.setheading(90) def draw_min(t, min): t.color("lightblue") t.width(3) t.right((360/60) * min) t.forward(150) t.forward(-150) t.setheading(90) def draw_sec(t, sec): t.color("black") t.width(1) t.right((360/60) * sec) t.forward(150) t.forward(-150) t.setheading(90) def up_time(): for i in range(1000): global t t.reset() t.speed(0) now = datetime.datetime.time(datetime.datetime.now()) h = now.hour m = now.minute s = now.second draw_hour(t,h) draw_min(t,m) draw_sec(t,s) time.sleep(1) def main(): win = turtle.Screen() win.listen() win.onkey(up_time, "a") win.mainloop() t = turtle.Turtle() main()
def is_sorted(string): """Returns True if string is sorted from least to greatest False otherwise.""" largest = 0 for char in string.lower(): if ord(char) > largest: largest = ord(char) else: return False return True print(is_sorted("abed")) def funny(asdf): print(asdf) myFunc = funny("first") print(myFunc)
''' Write a function that will return the number of digits in an integer. ''' def len_of_int(number): ''' returns the number of digits in an integer ''' return len(str(number)) def remove_first_occurrence(substring, original_string): ''' returns string ''' return original_string.replace(substring, '', 1) def reverse(text): ''' returns ''' return text[::-1] def is_palindrome(text): ''' Test a string to see if it is a palindrome ''' return reverse(text.lower().replace(' ','')) == text.replace(' ','') def mirror(text): ''' mirrors the given string ''' return text + reverse(text) def encript(original_string, mapping): ''' a crummy cypher ''' temp_string = '' for char in original_string.lower(): temp_string += mapping[ord(char)- 97] if not char == ' ' else ' ' return temp_string def main(): ''' main entry point ''' print("len_of_int(): " + str(len_of_int(7684))) print(remove_first_occurrence("an", "banana")) print(reverse("Jason")) print(is_palindrome("I am a cat")) print(is_palindrome("race car")) print(mirror("Jason")) print(encript("jason was here", "bcdefghijklmnopqrstuvwxyza")) if __name__ == "__main__": main()
from random import randint while True: s = int(input('Отгадай число:')) a = randint(0, 11) # обращай внимание на предупреждения PEP8 # между значениями и операторами должен быть пробел # между именем функции и оператором вызова пробела нет if s > 10: print('Я загадываю числа от 1 до 10') elif s == a: print('Победил') break # elif - лишний, потому что условие проверять необязательно # если s == a не выполнился, то s != a и так всегда будет верно # поэтому логичнее использовать просто else else: print('Проиграл') # continue здесь лишний, потому что это и так последняя инструкция в блоке # хотя для читаемости оставить можно, но тогда непонятно, почему в блоке if s > 10 его нет :)
## helper functiont o find nearest neightbor respect to extracted target phrase tokenized_lists = [nltk.pos_tag(word_tokenize(i)) for i in dataset['statement']] ## helper function to find nearest adjective respect to target phrase def search_adj(word_list, target, text_tag): """ Search for a part of speech (POS) nearest a target phrase of interest. Parameters ---------- word_list: list Sentence that's already been tokenized/POS-tagged target: str Target phrase of interest text_tag: str Nearby POS """ # Find the locations of your target phrase in the sentence target_index = [index for index, word in enumerate(word_list) if word[0] == target] if len(target_index) == 0: return None else: target_index = target_index[0] for i, entry in enumerate(word_list): try: ahead = target_index + 1 + i behind = target_index + 1 - i if (word_list[ahead][1]) == text_tag: return word_list[ahead][0] elif (word_list[behind][1]) == text_tag: return word_list[behind][0] else: continue except IndexError: pass for sentence in tokenized_lists: print(search_adj(sentence, 'the', 'JJ'))
import datetime def gettime(): return datetime.datetime.now() def take(k): if k==1: a=int(input("Enter 1 for Food and 2 for Exercise")) if b==1: value=input("Type here...") with open("Harry Food.txt","a") as op: op.write(str([str(gettime())])+":" +value+"\n") print("Written Successfully") elif b==2: value=input("Type here...") with open ("Harry Exercise.txt","a") as op: op.write(str([str(gettime())])+":"+value+"\n") print("Written Successfully...") elif k==2: a=int(input("Enter 1 for Food and 2 for Exercise")) if b==1: value=input("Type here...") with open("satyansh food.txt","a") as op: op.write(str([str(gettime())])+":"+value+"\n") print("Written Successfully...") elif(b==2): value=input("Type here...") with open("satyansh excrcise.txt" ,"a") as op: op.write(str([str(gettime())])+":"+value+"\n") print("Written Successfully...") else: print("Please Valid enter [harry,satyansh]") def retrive(k): int(input("Enter 1 for excrcise and 2 for Food")) if k==1: if b==1: with open("Harry Food.txt") as op: for i in op: print(i,end="") elif b==2: with open("Harry Exercise.txt","a") as op: for i in op: print(i,end="") elif k==2: if b==1: with open("satyansh food.txt") as op: for i in op: print(i,end="") elif b==2: with open("satyansh exercise.txt","a") as op: for i in op: print(i,end="") else: print("Please enter valid value:---->") print("Heth Management System") a=int(input(" Enter 1 for log value and press 2 for retrive value...")) if a==1: b=int(input(" Press 1 for Harry and 2 for satyansh")) take(b) else: b=int(input(" Press 1 for Harry and 2 for satyansh")) retrive(b) input()
import numpy as np ''' x + 2*y + z = 2 3*x + 8y + z = 12 4*y + z = 2 ''' A = np.matrix([[1,2,1], [3,8,1], [0,4,1]]) b = np.array([2,12,2]) # level 1: substract 2 * row1 from row2: E_2_1 = np.matrix([[1,0,0], [-3,1,0], [0,0,1]]) print('level1: E_1_1 * A:') u_2_1 = np.matmul(E_2_1, A) print(u_2_1) # level 2: substract 2 * row2 from row3: E_3_2 = np.matrix([[1,0,0], [0,1,0], [0,-2,1]]) print('level2: E_3_2 * u_2_1') u_3_2 = np.matmul(E_3_2, u_2_1) print(u_3_2)
import unittest from mock import Mock from machine import Machine from ..node import Node from address import Address class AddressTest(unittest.TestCase): def setUp(self): self.m = Machine('foo') self.n = Node('TestNode') def test_make_machine_address(self): ''' An address item has a make function ''' pass # self.assertTrue( hasattr(a, '_make')) def test_make_machine_address(self): ''' make an address based on machine ''' m2 = Machine('bar') m3 = Machine('baz') a = Address()._make(machine=self.m) self.assertEqual(str(a), 'machine.foo') a = Address()._make(machines=[self.m]) self.assertEqual(str(a), 'machine.foo') a = Address()._make(machines=[self.m, m2]) self.assertEqual(str(a), 'machine.foo+bar') a = Address()._make(machine=self.m, machines=[m2, m3]) self.assertEqual(str(a), 'machine.foo+bar+baz') def test_make_node_address(self): ''' _make method with nodes ''' n2 = Node('FooNode') n3 = Node('GabeNode') a = Address()._make(node=self.n) self.assertEqual(str(a), 'node.TestNode') a = Address()._make(nodes=[self.n]) self.assertEqual(str(a), 'node.TestNode') a = Address()._make(nodes=[self.n, n2]) self.assertEqual(str(a), 'node.TestNode+FooNode') a = Address()._make(node=self.n, nodes=[n2, n3]) self.assertEqual(str(a), 'node.FooNode+GabeNode+TestNode') def test_make_machine_node_address(self): ''' Node on machine specific message ''' m2 = Machine('bar') m3 = Machine('baz') n2 = Node('FooNode') n3 = Node('GabeNode') # machine and node a = Address()._make(machine=m2, node=n2) self.assertEqual(str(a), 'node.bar.FooNode') # machines and node a = Address()._make(machines=[m2,m3], node=n2) self.assertEqual(str(a), 'node.bar+baz.FooNode') # machine and nodes a = Address()._make(machine=m2, nodes=[n2, n3]) self.assertEqual(str(a), 'node.bar.FooNode+GabeNode') # machines and nodes a = Address()._make(machines=[m2,m3], nodes=[n2, n3]) self.assertEqual(str(a), 'node.bar+baz.FooNode+GabeNode') # machine, machines, node and nodes a = Address()._make(machine=self.m, machines=[m2,m3], nodes=[n2, n3]) self.assertEqual(str(a), 'node.foo+bar+baz.FooNode+GabeNode') # node.foo+bar+baz.FooNode+GabeNode+TestNode kw = { 'machine': self.m, 'machines': [m2,m3], 'node': self.n, 'nodes': [n2, n3], } a = Address()._make(**kw) self.assertEqual(str(a), 'node.foo+bar+baz.FooNode+GabeNode+TestNode') def test_change_seperator(self): ''' Alter string mapping seperator ''' m2 = Machine('bar') m3 = Machine('baz') n2 = Node('FooNode') n3 = Node('GabeNode') # machine and node a = Address() a.seperator = ':' a._make(machine=m2, node=n2) self.assertEqual(str(a), 'node:bar:FooNode') a.seperator = '>' self.assertEqual(str(a), 'node>bar>FooNode') a.seperator = None self.assertEqual(str(a), 'nodebarFooNode') a.seperator = Address.SEP self.assertEqual(str(a), 'node.bar.FooNode') def tool_items(self): ''' Alter string mapping seperator ''' m2 = Machine('bar') m3 = Machine('baz') n2 = Node('FooNode') n3 = Node('GabeNode') return (m2, m3, n2,n3) def test_node_string_prefix(self): ''' A node only name will be prefixed through address. ''' # machine a node a = Address('TestNode') self.assertEqual(str(a), 'node.TestNode') def test_node_node_spelling(self): ''' An address can handle a node called 'node' ''' a = Address('node.node') self.assertEqual(str(a), 'node.node') a = Address('node') self.assertEqual(str(a), 'node.node') def test_node_prefixed_prior(self): ''' An address will not re-prefix an address ''' a = Address('node.TestNode') self.assertEqual(str(a), 'node.TestNode') def test_node_name_nodes_list(self): ''' An address can accept a name and a list of nodes. Named node is last. ''' m2,m3,n2,n3 = self.tool_items() a = Address('TestNode', nodes=[n2]) self.assertEqual(str(a), 'node.FooNode+TestNode') # Can be done with prefix a = Address('node.TestNode', nodes=[n2]) self.assertEqual(str(a), 'node.FooNode+TestNode') def test_node_name_nodes_list_node(self): ''' An address can handle name, node and nodes list Named is last. ''' m2,m3,n2,n3 = self.tool_items() a = Address('TestNode', nodes=[n2], machines=[m2]) self.assertEqual(str(a), 'node.bar.FooNode+TestNode') # same with prefix a = Address('node.TestNode', node=n3, nodes=[n2]) self.assertEqual(str(a), 'node.FooNode+TestNode+GabeNode') def test_node_name_list_with_machine(self): ''' An address can accept a name, nodes, machine and machine. named node is last. ''' m2,m3,n2,n3 = self.tool_items() a = Address('TestNode', nodes=[n2], machine='baz', machines=[m2]) self.assertEqual(str(a), 'node.baz+bar.FooNode+TestNode')
""" Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ def check_binary_search_tree_(root): return is_BST(root.left, -1, root.data) and is_BST(root.right, root.data, 10001) def is_BST(current_node, min_data, max_data): if current_node == None: return True if current_node.data >= max_data or current_node.data <= min_data: return False return is_BST(current_node.left, min_data, current_node.data) and is_BST(current_node.right, current_node.data, max_data)
import numpy as np from sklearn.metrics import mean_squared_error from sklearn.neural_network.multilayer_perceptron import MLPRegressor import matplotlib.pyplot as plt from nn_regression_plot import plot_mse_vs_neurons, plot_mse_vs_iterations, plot_learned_function, \ plot_mse_vs_alpha, plot_bars_early_stopping_mse_comparison import random """ Computational Intelligence TU - Graz Assignment 2: Neural networks Part 1: Regression with neural networks This file contains functions to train and test the neural networks corresponding the the questions in the assignment, as mentioned in comments in the functions. Fill in all the sections containing TODO! """ __author__ = 'bellec,subramoney' def calculate_mse(nn, x, y): """ Calculate the mean squared error on the training and test data given the NN model used. :param nn: An instance of MLPRegressor or MLPClassifier that has already been trained using fit :param x: The data :param y: The targets :return: Training MSE, Testing MSE """ ## TODO #mse = 0 mse = mean_squared_error(y, nn.predict(x)) return mse def ex_1_1_a(x_train, x_test, y_train, y_test): """ Solution for exercise 1.1 a) Remember to set alpha to 0 when initializing the model :param x_train: The training dataset :param x_test: The testing dataset :param y_train: The training targets :param y_test: The testing targets :return: """ ## TODO #pass n_hidden = 5 # 2, 5, 50 reg = MLPRegressor(hidden_layer_sizes=(n_hidden,8), activation='logistic', solver='lbfgs', alpha=0) reg.fit(x_train, y_train) y_pred_test = reg.predict(x_test) y_pred_train = reg.predict(x_train) plot_learned_function(n_hidden, x_train, y_train, y_pred_train, x_test, y_test, y_pred_test) def ex_1_1_b(x_train, x_test, y_train, y_test): """ Solution for exercise 1.1 b) Remember to set alpha to 0 when initializing the model :param x_train: The training dataset :param x_test: The testing dataset :param y_train: The training targets :param y_test: The testing targets :return: """ ## TODO #pass MSE_TEST = np.zeros(10, dtype=float) MSE_TRAIN = np.zeros(10, dtype=float) n_hidden = 5 for j in range(10): reg = MLPRegressor(hidden_layer_sizes=(n_hidden,8), activation='logistic', solver='lbfgs', alpha=0,random_state=random.randint(0, 1000)) reg.fit(x_train, y_train) mse = calculate_mse(reg, x_test, y_test) MSE_TEST[j] = mse mse = calculate_mse(reg, x_train, y_train) MSE_TRAIN[j] = mse mse_test_max = max(MSE_TEST) mse_test_min = min(MSE_TEST) mse_test_mean = np.mean(MSE_TEST) mse_test_std = np.std(MSE_TEST) print(mse_test_max, "/", mse_test_min, "/", mse_test_mean, "/", mse_test_std) mse_train_max = max(MSE_TRAIN) mse_train_min = min(MSE_TRAIN) mse_train_mean = np.mean(MSE_TRAIN) mse_train_std = np.std(MSE_TRAIN) print(mse_train_max, "/", mse_train_min, "/", mse_train_mean, "/", mse_train_std) def ex_1_1_c(x_train, x_test, y_train, y_test): """ Solution for exercise 1.1 c) Remember to set alpha to 0 when initializing the model :param x_train: The training dataset :param x_test: The testing dataset :param y_train: The training targets :param y_test: The testing targets :return: """ ## TODO #pass N = 10 n_hidden = [1,2,3,4,6,8,12,20,40] mse_train = np.zeros([np.size(n_hidden), N]) mse_test = np.zeros([np.size(n_hidden), N]) for j in range(np.size(n_hidden)): reg = MLPRegressor(hidden_layer_sizes=(1,n_hidden[j]), activation='logistic', solver='lbfgs', alpha=0,random_state=random.randint(0, 1000)) for r in range(N): reg.fit(x_train, y_train) mse_train[j, r] = calculate_mse(reg, x_train, y_train) mse_test[j, r] = calculate_mse(reg, x_test, y_test) # PLOT plot_mse_vs_neurons(mse_train, mse_test, n_hidden) """ mse_test_mean = np.mean(mse_test, axis=1) ind = np.argmin(mse_test_mean) """ ind = np.unravel_index(np.argmin(mse_test), mse_test.shape) reg = MLPRegressor(hidden_layer_sizes=(n_hidden[ind[0]],), activation='logistic', solver='lbfgs', alpha=0, random_state=random.randint(0, 1000)) reg.fit(x_train, y_train) y_pred_test = reg.predict(x_test) y_pred_train = reg.predict(x_train) plot_learned_function(n_hidden[ind[0]], x_train, y_train, y_pred_train, x_test, y_test, y_pred_test) def ex_1_1_d(x_train, x_test, y_train, y_test): """ Solution for exercise 1.1 b) Remember to set alpha to 0 when initializing the model :param x_train: The training dataset :param x_test: The testing dataset :param y_train: The training targets :param y_test: The testing targets :return: """ ## TODO #pass N = 500 n_hidden = [2,5,50] mse_train = np.zeros([np.size(n_hidden), N]) mse_test = np.zeros([np.size(n_hidden), N]) for j in range(np.size(n_hidden)): reg = MLPRegressor(hidden_layer_sizes=(n_hidden[j],), activation='logistic', solver='lbfgs', alpha=0,random_state=0, warm_start=True, max_iter=1) for r in range(N): reg.fit(x_train, y_train) mse_train[j, r] = calculate_mse(reg, x_train, y_train) mse_test[j, r] = calculate_mse(reg, x_test, y_test) # PLOT plot_mse_vs_neurons(mse_train, mse_test, n_hidden) #mse_test_mean = np.mean(mse_test, axis=1) #ind = np.argmin(mse_test_mean) ind = np.unravel_index(np.argmin(mse_test), mse_test.shape) # geht es auch ohne den MLPRegressor nochmal zu initialisieren? Keine Ahnung obs anders besser geht reg = MLPRegressor(hidden_layer_sizes=(n_hidden[j],), activation='logistic', solver='lbfgs', alpha=0, random_state=random.randint(0, 1000), max_iter=500) reg.fit(x_train, y_train) y_pred_test = reg.predict(x_test) y_pred_train = reg.predict(x_train) plot_learned_function(n_hidden[ind[0]], x_train, y_train, y_pred_train, x_test, y_test, y_pred_test) def ex_1_2_a(x_train, x_test, y_train, y_test): """ Solution for exercise 1.2 a) :param x_train: The training dataset :param x_test: The testing dataset :param y_train: The training targets :param y_test: The testing targets :return: """ ## TODO #pass N = 5000 n_hidden = 50 alpha_ = np.power(10, np.linspace(-8, 2, 11)) mse_train = np.zeros([np.size(alpha_), N]) mse_test = np.zeros([np.size(alpha_), N]) for j in range(np.size(alpha_)): reg = MLPRegressor(hidden_layer_sizes=(n_hidden,), activation='logistic', solver='lbfgs', alpha=alpha_[j], random_state=0, warm_start=True, max_iter=1) for r in range(N): reg.fit(x_train, y_train) mse_train[j, r] = calculate_mse(reg, x_train, y_train) mse_test[j, r] = calculate_mse(reg, x_test, y_test) plot_mse_vs_alpha(mse_train, mse_test, alpha_) def ex_1_2_b(x_train, x_test, y_train, y_test): """ Solution for exercise 1.2 b) :param x_train: The training dataset :param x_test: The testing dataset :param y_train: The training targets :param y_test: The testing targets :return: """ ## TODO #pass Iterations = 100 N = 10 n_hidden = 50 sequence = np.random.permutation(np.arange(0, np.size(y_train), 1)) x_train = x_train[sequence] y_train = y_train[sequence] SIZE = int(np.ceil(np.size(y_train) / 3)) x_val = x_train[:SIZE] y_val = y_train[:SIZE] x_train = x_train[SIZE:] y_train = y_train[SIZE:] mse_train = np.zeros(N) mse_test = np.zeros(N) for r in range(N): reg = MLPRegressor(hidden_layer_sizes=(n_hidden,), activation='logistic', solver='lbfgs', alpha=0,random_state=0, warm_start=True, max_iter=1) for iter in range(Iterations): reg.fit(x_train, y_train) mse_train[r] = calculate_mse(reg, x_train, y_train) mse_test[r] = calculate_mse(reg, x_test, y_test) if np.mod(r, 20) == 0: print('Troll') #plot_bars_early_stopping_mse_comparison(test_mse_end, test_mse_early_stopping, test_mse_ideal) def ex_1_2_c(x_train, x_test, y_train, y_test): """ Solution for exercise 1.2 c) :param x_train: :param x_test: :param y_train: :param y_test: :return: """ ## TODO pass
#In this program we are trying to answer question 2. which mainly involve creating a exponential distrubition then #"messing" it up by adding to it a number of uniform disturbition numbers. We will test when the exponential fit will no #longer be a valid approximation with the chi sqaure function. from ROOT import gROOT,TCanvas,TH1F #The follwing modules are form ROOT (a program developed by cern) import numpy as np from scipy import integrate def qauntile(lammda=0.5,x=0): #the qauntelie as was developed in class return (-1/lammda)*np.log((1-x)) def exp_dist(x=0,l=0.5): #the pdf of an exponetial distubtion return l*np.exp(-1*l*x) def draw(n=100,l=0.5): #In here we are to recreate the process of picking a number from exp distubtion. and puting it in an array vec_num_probexp=[] for i in range(n): x=np.random.uniform(0, 1, size=None) #selecting a random number from a uniform distubtion num=qauntile(l,x) #The unifrom random is placed in the qauntile function vec_num_probexp.append(num) return vec_num_probexp def pk(min_range,max_range,l=0.5): #The integral over an exp distrubtion over the range from min_range to max_range return np.exp(-1*l*min_range)-np.exp(-1*l*max_range) def create_hist_root_exp(sample_size,l,bin_num,v): #A function that involve creating the histogram in ROOT (by cern) min_range=0; max_range=1 h=TH1F ('Data','Histogram of numbers drawen from exponential distrubition lammda=0.5',bin_num,min_range,max_range) for i in range(sample_size): h.Fill(v[i]) return h def chi_sq(v=[],E=[],bin_num=0): #The chi sqaured (for a single bin) function with v as the number #of sample observables and E as the expected value sum=0 for i in range(bin_num): sum+=((v[i]-E[i])**2/E[i]) return sum def create_experimental(bin_num,sample_size,l): #the summation over the different bins to obtain chi-sq E=[] for i in range(bin_num): min_range = float(i) / float(bin_num); max_range = float(i + 1) / float(bin_num) E.append(sample_size * pk(min_range, max_range, l)) return E def add_two_uniform_num(org_sample=[]): #adding a two uniform distubtion numbers to our sample vector two_rand = np.random.uniform(0, 1, size=2) return org_sample.extend(two_rand) def add_n_more(c,org_sample=[],runs=1,bin_num=10,l=0.5,): #Adding a number of 2 uniform distributed numbers to our sample vector for i in range(runs): add_two_uniform_num(org_sample) E=create_experimental(bin_num, np.size(org_sample), l) h=create_hist_root_exp(np.size(org_sample), l, bin_num, org_sample) return (h,chi_sq(org_sample, E, bin_num)) #The start of the program sample_size=100; l=0.5; bin_num=50 v=draw(sample_size,l) E=create_experimental(bin_num,sample_size,l) chi_sum=chi_sq(v,E,bin_num) #some function to run ROOT ploting tools gROOT.Reset() c=TCanvas('c1','Exp distubition question') c.Divide(3) h=create_hist_root_exp(sample_size,l,bin_num,v) c.cd(1) h.Draw() h.GetXaxis().SetTitle("Number") h.GetYaxis().SetTitle("Counts of times the number was drawn") h.SetTitle("A histogram of numbers drawen from exponential distrubition chi_sqr=%d" %chi_sum) print(chi_sum) #Above the end of the ploting using root and below test our sample vector runs=1 hist_two=add_n_more(c,v,runs,bin_num,l) c.cd(2) hist_two[0].Draw() hist_two[0].GetXaxis().SetTitle("Number") hist_two[0].GetYaxis().SetTitle("Counts of times the number was drawn") hist_two[0].SetTitle("A histogram of numbers drawen from exponential distrubition and two form uniform chi_sqr=%d" %hist_two[1]) runs=30 hist_alot=add_n_more(c,v,runs,bin_num,l) print(hist_two[1]) c.cd(3) hist_alot[0].Draw() hist_alot[0].GetXaxis().SetTitle("Number") hist_alot[0].GetYaxis().SetTitle("Counts of times the number was drawn") hist_alot[0].SetTitle("A histogram of numbers drawen from exponential distrubition and a lot more form uniform chi_sqr=%d" %hist_alot[1]) print(hist_alot[1]) print(chi_sum)
r1 = int(input ("введи r1 ")) r2 = int(input ("введи r2 ")) r3 = int(input ("введи r3 ")) s1 = int(input ("введи s1 ")) s2 = int(input ("введи s2 ")) s3 = int(input ("введи s3 ")) x1 = r1/s1 x2 = r2/s2 x3 = r3/s3 if (x1>x2) and (x1>x3): print ('1') if (x2>x1) and (x2>x3): print ('2') if (x3>x1) and (x3>x1): print ('3')
n = int(raw_input("Please enter a number: ")) builder = "*" line = '' for amount in range(0, n): line = line + builder for x in range(0, n): print line def square(n): for i in xrange(0, n): print '*' * n n = int(raw_input("Enter a number: ")) square(n)
# 这个模块显示了类的继承顺序。 class A: def __init__(self): self.n = 2 def add(self, m): print('self is {0} @A.add'.format(self)) self.n += m class B(A): def __init__(self): self.n = 3 def add(self, m): print('self is {0} @B.add'.format(self)) super().add(m) self.n += 3 class C(A): def __init__(self): self.n = 4 def add(self, m): print('self is {0} @C.add'.format(self)) super().add(m) self.n += 4 class D(B, C): def __init__(self): self.n = 5 def add(self, m): print('self is {0} @D.add'.format(self)) super().add(m) self.n += 5 #下列代码输出什么结果呢 d = D() d.add(2) print(d.n) # 1.调用D,print('self is {0} @D.add'.format(self)) # 2.执行到super,调用B,执行print('self is {0} @B.add'.format(self)) # 执行到super,调用C # 3.执行print('self is {0} @C.add'.format(self)) # 执行到super,调用A # print('self is {0} @A.add'.format(self)) # self.n+=2,now self.n=7 # 4.回到C,self.n+=4,now self.n=11 # 5.回到B,self.n+=3,now self.n=14 # 6.回到D,self.n+=5,now self.n=19
from double_queue import DoubleQueue class Node(object): """定义树的节点""" def __init__(self, item=None): self.item = item self.lchild = None self.rchild = None class Tree(object): def __init__(self): node = Node() self.root = node self.q = DoubleQueue() def breadth_add(self, item): """广度优先插入数据""" node = Node(item) if self.root.item is None: self.root = node return self.root else: q = [self.root] while True: target = q.pop(0) if target.lchild is None: target.lchild = node return elif target.rchild is None: target.rchild = node return else: q.append(target.lchild) q.append(target.rchild) def breadth_travel(self): """广度优先遍历树""" if self.root is None: return else: q = [self.root] while q: cursor = q.pop(0) if cursor is None: print(" ") return else: print(cursor.item, "-> ", end="") q.append(cursor.lchild) q.append(cursor.rchild) def pre_order(self, root): """先序遍历""" if root is None: return else: print(root.item, "-> ", end="") self.pre_order(root.lchild) self.pre_order(root.rchild) return def mid_order(self, root): """中序遍历""" if root is None: return else: self.mid_order(root.lchild) print(root.item, "-> ", end="") self.mid_order(root.rchild) return def post_order(self, root): """后序遍历""" if root is None: return else: self.mid_order(root.lchild) self.mid_order(root.rchild) print(root.item, "-> ", end="") return def is_post_order(self, list, start, end): """判断一个数组是否是二元查找树后序遍历的序列""" root = list[end] if list[start:end] == [] or len(list[start:end+1]) < 3: return True for i in list[start:end]: if i > root: split = list.index(i) break self.is_post_order(list, start, split-1) self.is_post_order(list, split, end-1) if min(list[split: end]) >= root: return True else: # print("False") return False if __name__ == '__main__': tree = Tree() tree.breadth_add('A') tree.breadth_add('B') tree.breadth_add('C') tree.breadth_add('D') tree.breadth_add('E') tree.breadth_add('F') tree.breadth_travel() tree.pre_order(tree.root) print("") tree.mid_order(tree.root) print("") tree.post_order(tree.root) print("") print(tree.is_post_order([1, 3, 2, 5, 7, 6, 4], 0, 6))
# This Program finds the smallest positive number # that is evenly divisible by all of the numbers from 1 to 20 from math import log, floor, sqrt def lcm(n, primes): limit = sqrt(n) # square root of n a = {} # exponents check = True i = 0 result = 1 while primes[i] <= n: a[i] = 1 if check: if primes[i] <= limit: a[i] = floor(log(n) / log(primes[i])) else: check = False result = result * (primes[i] ** a[i]) i += 1 return result primes = [2, 3, 5, 7, 11, 13, 17, 19, 23] print(lcm(20, primes))
#!/usr/bin/env python # coding: utf-8 # ### References: # https://machinelearningmastery.com/how-to-perform-face-recognition-with-vggface2-convolutional-neural-network-in-keras/ # # https://github.com/rcmalli/keras-vggface/ # In[1]: import matplotlib.pyplot as plt import numpy as np import dlib import cv2 from scipy.spatial.distance import cosine from keras_vggface.vggface import VGGFace from keras_vggface.utils import preprocess_input # In[2]: # Get face with dlib hog path_image = "Michael Scofield.png" detector = dlib.get_frontal_face_detector() image = cv2.imread(path_image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) rects = detector(gray, 1) top, right, bottom, left = rects[0].top(),rects[0].right(),rects[0].bottom(),rects[0].left() face = image[top:bottom,left:right] face = cv2.resize(face,(224,224)) cv2.imwrite("face.jpg",face) plt.imshow(face) plt.show() # In[3]: # create a vggface model model = VGGFace(model='resnet50', include_top=False, input_shape=(224, 224, 3), pooling='avg') # In[4]: # extract faces and calculate face embeddings for a list of photo files def get_embeddings(faces): # resize faces faces = [cv2.resize(cv2.imread(f),(224,224)) for f in faces] # convert into an array of samples samples = np.asarray(faces, 'float32') # prepare the face for the model, e.g. center pixels samples = preprocess_input(samples, version=2) # perform prediction yhat = model.predict(samples) return yhat # In[5]: # determine if a candidate face is a match for a known face def is_match(known_embedding, candidate_embedding, thresh=0.5): # calculate distance between embeddings score = cosine(known_embedding, candidate_embedding) if score <= thresh: print('>face is a Match (%.3f <= %.3f)' % (score, thresh)) return True else: print('>face is NOT a Match (%.3f > %.3f)' % (score, thresh)) return False # In[6]: get_ipython().run_line_magic('time', 'embeddings = get_embeddings(["face.jpg"])') feature_ms = embeddings[0] # In[7]: # initialize dlib's face detector (HOG-based) detector = dlib.get_frontal_face_detector() # create a videoCapture object with a video file or a capture device cap = cv2.VideoCapture('./prison_break.mp4') # check if we will successfully open the file if not cap.isOpened(): print("Error opening the file.") assert(False) # # Default resolutions of the frame are obtained.The default resolutions are system dependent. # frame_width = int(cap.get(3)) # frame_height = int(cap.get(4)) # # Define the codec and create VideoWriter object.The output is stored in 'output.mp4' file. # out = cv2.VideoWriter('output.mp4',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height)) # read until the end of the video frame by frame while cap.isOpened(): # cap.read (): decodes and returns the next video frame # variable ret: will get the return value by retrieving the camera frame, true or false (via "cap") # variable frame: will get the next image of the video (via "cap") ret, frame = cap.read() if ret: frame = cv2.resize(frame, (1000,600)) # detect faces in the grayscale frame gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) rects = detector(gray, 0) for rect in rects: top, right, bottom, left = abs(rect.top()),abs(rect.right()),abs(rect.bottom()),abs(rect.left()) face = frame[top:bottom,left:right] face = cv2.resize(face,(224,224)) # convert into an array of samples samples = np.asarray([face], 'float32') # prepare the face for the model, e.g. center pixels samples = preprocess_input(samples, version=2) # perform prediction yhat = model.predict(samples) font = cv2.FONT_HERSHEY_SIMPLEX cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2) if is_match(feature_ms, yhat[0]) == True: cv2.putText(frame, "Michael Scofield", (left-5,top-5), font, 1, (0,255,255), 2) else: cv2.putText(frame, "unknown", (left-5,top-5), font, 1, (0,255,255), 2) # to display the frame cv2.imshow("Output", frame) # Write the frame into the file 'output.avi' # out.write(frame) # waitKey (0): put the screen in pause because it will wait infinitely that key # waitKey (n): will wait for keyPress for only n milliseconds and continue to refresh and read the video frame using cap.read () # ord (character): returns an integer representing the Unicode code point of the given Unicode character. if cv2.waitKey(1) == ord('e'): break else: break # to release software and hardware resources cap.release() # out.release() # to close all windows in imshow () cv2.destroyAllWindows()