text
stringlengths
37
1.41M
__author__ = 'GaryGoh' def squeeze(filename): file = open(filename, "r") line_num = 0 preLine = "" while True: line = file.readline() # To break dead loop if line == "": break line_num = line_num + 1 # Compare with previous line if same as current line if line != preLine: print("%3d - %s" % (line_num, line)) # To store the previous line because it is hard to get the previous line after pointer moving to next preLine = line return print(squeeze("test2File.txt"))
__author__ = 'GaryGoh' def peaks(s): # Empty list if not s: return [] # Not emtpy list # initialized ascList in order to avoid list index out of range ascList = [s[0]] # Similar as insertion sort, but no need to walk though the new list again # Only compare the current element from original list to the latest element from new list # This way can have O(n) = n time consuming for i in s: if i > ascList[-1]: ascList.append(i) return ascList rawList = input() lists = list(map(int, rawList.split())) print(peaks(lists))
__author__ = 'GaryGoh' def print_dictionary(d): # abstract keys of d and sort them # I suppose left-justified columns of width 10 is that # each column has 10 width from left to right. for k in sorted(d.keys()): print("%-10s : %-10s" % (k, d[k])) return d = {'sun': 'grian', 'tree': 'crann', 'horse': 'capall', 'water': 'uisce'} print_dictionary(d)
from tkinter import* from tkinter import ttk #ttk are actually separate files in tkinter, this updates the original with improved widgets. import random class Application(Frame): #Frame is a previously defined class/widget designed to be a container for other widgets. Example of Class inheritance def __init__ (self,master): # 'master' is just the augment, in this example it will be root eg: Application(root) which is basically Tk() Frame.__init__(self,master) # This line of code is needed to keep the inheritance of the parent's __init__() function otherwise it will be overrided by the child's __init() function self.grid() # Inheritance allows us to define a class that inherits all the methods and properties from another class. self.create_widgets() self.gold=0 self.exp=0 self.lexp=0 self.level=0 self.area=["Forest of the Chaos Harlequins ","Forgotten Graveyard of Endal","Castle of the Blackest Knight","Haunted Farm of Yondor","Deathtrap Dungeon of Borgon"," Mysterious Swampland of Kuluth", "Swamp of the Slimy Hobbits", "Darkest Dungeons", "Ruins of the Fallen Gods", "Forlorn Islands of Lost Souls","Hidden Hideout of Ninedeadeyes", "Wildlands of Lady L Moore"," Woods of Ypres","Heart of Darkness", "Doomville", "The Red Jester's Torture Chamber","The Goblins Fortress of Snikrik,"," Temple of Apshai"," Dungeons of Doom", "Mountains of the Wild Berserker","Stronghold of Daggerfall","Walking Hills of Cthulhu" ] self.monster=["orcs","goblins","dragons","demons","kobolds","blobs","hobbits","zombies","gnomes","vampires","beholders","trolls","hill giants","ettins","mimics", "succubuses","bone devils","clay golems","drows","gnolls","swamp hags"," night goblins","half-ogres","hobgoblins","bog imps","owlbears","ponies","winter wolves","harlequin","abomination"] self.description=["stupid","horny","heart broken","deranged","morbid","tiny","suicidal","sexy","skinny","racist","peaceful","silly","drunk","sadistic","young", "shy","talkative", "lovestruck","sarcastic","homophobic","forelorn","happy","friendly","psychopathic","optimistic","mysterious","beautiful","malnourish","zealous","hot-headed"] self.power_ranking=("The Village Punchbag (It's a job, i guess )") def create_widgets(self): self.bttn= Button(self) self.bttn["text"]="Explore" self.bttn["command"]= self.adventure self.bttn.grid(row=0,column=0,columnspan=1,sticky=W) self.stat_lbl=Label(self,text="Gold:0 EXP:0 LEVEL:0") self.stat_lbl.grid(row=0,column=1,columnspan=2,sticky=E) self.story_txt=Text(self,width=45, height=5,wrap=WORD) self.story_txt.grid(row=3, column=0, columnspan=3, sticky = W) self.stat_lb2=Label(self,text="Power ranking: Ready to begin your quest from zero to hero ? ") self.stat_lb2.grid(row=5,column=0,columnspan=2,sticky=W) def adventure(self): adventure=random.choice(self.area) adventure1=str(adventure) encounter=random.choice(self.monster) descript=random.choice(self.description) descript1=str(descript) encounter1=str(encounter) number=random.randrange(2,5) number1=str(number) reward=random.randrange(1,10) reward1=str(reward) exp=random.randrange(1,20) exp1=str(exp) self.gold+=reward self.exp+=exp self.lexp+=exp if self.lexp >123+(self.level*10): self.level+=1 self.lexp=0 if self.level >2 and self.level <4: self.power_ranking="The Cannon Fodder (Ready to die ? ) " if self.level >4 and self.level <6: self.power_ranking="The Weakling Avenger (At least your tried )" if self.level >6 and self.level <8: self.power_ranking="The Nice Guy (This is no compliment )" if self.level >8 and self.level <10: self.power_ranking="The Beta Warrior (At least you won't die first )" if self.level >10 and self.level <12: self.power_ranking="The Mighty Beta Warrior (Some nerds respect you )" if self.level >12 and self.level <14: self.power_ranking="The Average Chump (Nothing to see here ) " if self.level >14 and self.level <16: self.power_ranking="The Man with a Stick (Fear my wood ) " if self.level >16 and self.level <18: self.power_ranking="The Man with a Big Stick (MORE WOOD )" if self.level >18 and self.level <20: self.power_ranking="The Town's Guard (Obey my authority ) " if self.level >20 and self.level <24: self.power_ranking="The Try-Hard Hero (You win some, you lose more )" if self.level >24 and self.level <26: self.power_ranking="The Goblin Slayer (Your reputation grows )" if self.level >26 and self.level <28: self.power_ranking="The Orc Breaker (Orcs cower in your presence )" if self.level >28 and self.level <30: self.power_ranking=" The Average Hero (Good but not great,keep fighting )" if self.level >30 and self.level <32: self.power_ranking=" The Demon Demolisher (Guts will be proud of you )" if self.level >32 and self.level <34: self.power_ranking=" The Master Killer (A black belt in DEATH )" if self.level >34 and self.level <40: self.power_ranking=" The Champion of Man (The best a man can be )" if self.level >40 and self.level <70: self.power_ranking=" Legendary Hero (Well done. You can retire now )" if self.level >70 and self.level <90: self.power_ranking=" Old Warrior (Why are you still playing ? )" if self.level >90 and self.level <90: self.power_ranking="It's Over 9000 !! ( Seriously, quit it )" if self.level >100 : self.power_ranking="God (We bow down to your greatness )" story ="You explore the " story += adventure1 story +="." story += " You encounter " story +=number1 story +=" " story+=descript1 story +=" " story += encounter1 story +="." story += " You slay the " story += encounter1 story +="." story += " You gain " story += reward1 story += " gold and " story += exp1 story += " exp" story +="." rank= "Power ranking: " rank+= self.power_ranking stat="Gold:" stat+=str(self.gold) stat+=" " stat+="EXP" stat+=str(self.exp) stat+=" " stat+="LEVEL:" stat+=str(self.level) self.story_txt.delete(0.0,END) self.story_txt.insert(0.0,story) self.stat_lbl["text"]=stat self.stat_lb2["text"]=rank root = Tk() root.title(" One Click RPG ") root.geometry("380x150") app=Application(root) root.mainloop() # This is a method on the main window which we execute when we want to run our application. #This method will loop forever, waiting for events from the user, until the user exits the program #https://github.com/Ninedeadeyes/15-mini-python-games-
# -*- coding: utf-8 -*- """ Created on Mon Apr 27 2020 @author: Daniel Hryniewski Collatz Conjecture - Start with a number n > 1. Find the number of steps it takes to reach one using the following process: If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. """ def choice(): i = 0 while True: try: while i < 1: number = int(input('Enter a number: ')) if number > 0: i += 1 else: print("Enter a positive integer.") except: print("Enter a positive integer.") else: break return number def calcul(n): listCollatz = [] listCollatz.append(n) while n > 1: if n == 1: break elif n % 2 == 0: n = n / 2 listCollatz.append(round(n)) else : n = n * 3 + 1 listCollatz.append(round(n)) return listCollatz def main(): n = choice() result = calcul(n) list_str = [str(result) for result in result] print(f"Starting with {n}, one gets the sequence:", ", ".join(list_str)) print("Number of steps: ", len(list_str) - 1) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Created on Tue May 5 2020 @author: Daniel Hryniewski Binary to Decimal and Back Converter - Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent. """ def bintodec(num): result = bin(num) return result[2:] def dectobin(num): result = int(str(num), 2) return result def choice(): while True: try: a = int(input('>>> ')) if a == int(a): break except: print('ERROR - print a numbers') return a def convert(): print('1 - Convert Binary to Decimal\n2 - Convert Decimal to Binary') while True: c = choice() if c == 1 or c == 2: break else: print('ERROR - Choice 1 or 2') print('Print your number:') while True: num = choice() if c == 1: result = bintodec(num) break else: try: result = dectobin(num) break except: print('ERROR - Your number is not binary!') print(result) convert()
# -*- coding: utf-8 -*- """ Created on Tue May 6 2020 @author: Daniel Hryniewski Sorting - Implement two types of sorting algorithms: Merge sort and bubble sort. """ from random import randint def randomlist(): r = randint(5,30) randlist = [] for i in range(1, r+1): n = randint(1,100) randlist.append(n) return randlist def fusion(l1, l2): l0 = [] while l1 != [] and l2 != []: if l1 != None and l2 != None: if l1[0] > l2[0]: l0.append(l2[0]) l2.pop(0) else: l0.append(l1[0]) l1.pop(0) elif l1 == None: l0.append(l2[0]) l2.pop(0) elif l2 == None: l0.append(l1[0]) l1.pop(0) if l1 != None: l0 = l0 + l1 if l2 != None: l0 = l0 + l2 return l0 def mergesort(l): n = len(l) if n <= 1: return l left = l[:(round(n/2))] right = l[(round(n/2)):] lsorted = mergesort(left) rsorted = mergesort(right) return fusion(lsorted, rsorted) def bubblesort(l): s = True while s == True: s = False for i in range(0, len(l)-1): if l[i] > l[i+1]: l[i], l[i+1] = l[i+1], l[i] s = True return l def main(): mylist = randomlist() print('My random list:') print(mylist) print('\nBubble sort:') print(bubblesort(mylist)) print('\nMerge sort:') print(mergesort(mylist)) if __name__ == '__main__': main()
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ #for i in range(nums1): # if nums1[i] == 0: # nums[i] = None iA = m-1 iB = n-1 iM = m+n-1 while iB >= 0: if iA >= 0 and nums1[iA] > nums2[iB]: nums1[iM] = nums1[iA] iA-=1 else: nums1[iM] = nums2[iB] iB-=1 iM-=1
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ p1, p2 = 0, len(nums) - 1 p = 0 while p <= p2: if nums[p] < 1: nums[p], nums[p1] = nums[p1], nums[p] p1 += 1 p += 1 elif nums[p] > 1: nums[p], nums[p2] = nums[p2], nums[p] p2 -= 1 else: p += 1
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: a=collections.defaultdict(list) def t(node,depth): if node: a[depth].append(node.val) t(node.left,depth+1) t(node.right,depth+1) else: a[depth].append(-1) t(root,0) print(a) for i in a.keys(): if a[i] != a[i][::-1]: return False return True
def sortByBits(self, arr: List[int]) -> List[int]: '''import collections def count(n): count = 0 while n != 0: if n & 1 == 1: count += 1 n >>= 1 return count d = collections.defaultdict(list) res = [] for num in arr: d[count(num)].append(num) for i in sorted(d): for n in sorted(d[i]): res.append(n) return res ''' arr.sort(key=lambda x: [bin(x).count('1'), x]) return arr
class Solution: def rotateString(self, A: str, B: str) -> bool: n = len(A) if n == len(B): b = A+A return B in b return False
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ a=collections.defaultdict(list) def tr(node, depth): if node: a[depth].append(node.val) if node.left: tr(node.left, depth+1) if node.right: tr(node.right, depth+1) tr(root,0) return a.values()
#10) Mostrar los números pares entre 1 al 100. # Solucion 1: for x in range(1,101): if(x%2==0): print(x) # Solucion 2: for i in range(2,101,2): print(i)
#12) Crea una lista vacía (pongamos 10 posiciones), pide sus valores y devuelve la suma y la media de los números. lista=[] suma=0 media=0 for i in range(1,11): n=int(input("Digite un numero: ")) lista.append(n) suma+=n media=suma/len(lista) print(lista) print("la suma de los valores es:",suma) print("la media de los valores es:",media)
#5) Crea una variable numérica y si esta entre 0 y 10, mostrar un mensaje indicándolo. # Solucion 1 x=int(input("digite un numero: ")) if(0<=x<=10): print(x,"está entre 0 y 10") else: print(x,"no está entre 0 y 10") # Solucion 2: if(x>=1 and x<=10): print("Esta entre 0 y 10") else: print("No esta en ese rango")
#4) De dos números, saber cual es el mayor. x=int(input("digite un numero: ")) y=int(input("digite otro numero: ")) if(x>y): print(x,"es el mayor") elif (x<y): print(y,"es el mayor") else: print("los numeros son iguales")
#9) Crea una tupla con números e indica el numero con mayor valor y el que menor tenga. tupla=(1,2,5,1,1,6,0,2,2,0,2,1) print("El numero mayor es:",max(tupla)) print("El numero menor es:",min(tupla))
from copy import deepcopy class Nod: def __init__(self, e): self.e = e self.urm = None class Lista: def __init__(self): self.prim = None def creareLista(): lista = Lista() lista.prim = creareLista_rec() return lista def creareLista_rec(): x = int(input("x=")) if x == 0: return None else: nod = Nod(x) nod.urm = creareLista_rec() return nod def tipar(lista): tipar_rec(lista.prim) def tipar_rec(nod): if nod != None: print (nod.e) tipar_rec(nod.urm) def removeElement(list): newList = deepcopy(list) if newList.prim is not None: newList.prim = newList.prim.urm return newList def addElement(list, e): newList = deepcopy(list) newNode = Nod(e) newNode.urm = newList.prim newList.prim = newNode return newList def substituteElement(lista, i, v): if lista.prim is None: return Lista() elif i == 1: return addElement(removeElement(lista), v) else: return addElement(substituteElement(removeElement(lista), i-1, v),lista.prim.e) def belongs(lista, element): if lista.prim is None: return False elif lista.prim.e == element: return True return belongs(removeElement(lista), element) def difference(list1, list2): if list1.prim is None: return Lista() elif belongs(list2, list1.prim.e): return difference(removeElement(list1), list2) else: return addElement(difference(removeElement(list1), list2), list1.prim.e) def testSubstitute(): list = creareLista() i = int(input("enter substitution index:")) v = int(input("enter substitute value:")) tipar(substituteElement(list, i, v)) print("END!") def testDifference(): list1 = creareLista() list2 = creareLista() tipar(difference(list1, list2)) print('END!') def main(): testSubstitute() testDifference() main()
# 1. A client sends to the server an array of numbers. Server returns the sum of the numbers. import socket import struct import sys def tcp_client_init(ip_address, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip_address, port)) return sock def tcp_send_int(sock, number): print('Sending {} to {}'.format(number, sock)) number = struct.pack('!i', number) sock.send(number) def tcp_recv_int(sock): number = struct.unpack('!i', sock.recv(4))[0] print("Received number {}".format(number)) return number def tcp_send_array(sock, array): print('Sending {} to {}'.format(array, sock)) print('Sending array length = {}'.format(len(array))) tcp_send_int(sock, len(array)) for e in array: print('Sending element {}'.format(e)) tcp_send_int(sock, e) ip_address = '0.0.0.0' port = 1234 sock = tcp_client_init(ip_address, port) if __name__ == '__main__': array = [] while True: cmd = input('Enter element, e to exit\n') if cmd == 'e': break try: cmd = int(cmd) array.append(cmd) except ValueError: print('enter a valid choice!') pass tcp_send_array(sock, array) print('sum of elements is {}'.format(tcp_recv_int(sock))) sock.close()
#เกรด 0,1,2,3,4 #ข้อมูลนำเข้า คือ คะแนนสอบ #ประมวลผลว่าอยู่ในเกรดไหน #พิมพ์ว่าได้เกรดไหน score = int(input("Input your score : ")) if score >= 0 and score <= 100: if score >= 80: print("เกรด 4") elif score >= 70 : print("เกรด 3") elif score >= 60 : print("เกรด 2") elif score >= 50 : print("เกรด 1") else : print("เกรด 0") else : print("ใส่เลขผิด")
#แปลง พศ เป็น คศ number = int(input("ป้อน พ.ศ. ")) number2 = number-543 print("ค.ศ. = ", number2) # print("ค.ศ. = ", number-543)
# if boolean expression : # statement #age = 15 - 20 วัยรุ่น # 21 - 29 ผู้ใหญ่ # 30 - 39 วัยทำงาน #and or not age = int(input("age : ")) name = input("name : ") if age >= 15 and age <= 20: print("วัยรุ่น") if age >= 21 and age <= 29 : print("ผู้ใหญ่") if age >= 30 and age <= 39: print("วัยทำงาน") if not (age == 15) : print("age != 15") print(age == 15) if name == "aew" : print("aew") else: print("nick")
#การเพิ่มข้อมูลเข้าไปใน list number = [1,2,3,4,5,6] #สมาชิิกคือ 1-6 fruit = ["มะม่วง","มะนาว","มะยม"] print("ก่อนเพิ่ม == > ", fruit) #append() นำสมาชิกใหม่ ไปต่อท้ายเพื่อน fruit.append("มะปราง") fruit.append("แตงโม") print("หลังเพิ่ม == > ", fruit) #insert (index , สมาชิกใหม่) การแทรก fruit.insert(1,"ทุเรียน") print("หลังแทรก == > ", fruit)
age = int(input("ใส่อายุของคุณ : ")) if age <= 15: if age == 15: print("ม 3") elif age == 14 : print(" ม 2") elif age == 13 : print("ม 1") else : print("ประถมศึกษา") else : print("ม ปลาย")
# -*- coding: utf-8 -*- """ Created on Wed Nov 6 17:14:38 2019 @author: Diogo """ import numpy as np import matplotlib.pyplot as plt import scipy.stats as ss #2.1. Load the numpy files for data1 which have already been split into training #data (variables xtrain and ytrain) and test data (variables xtest and ytest). xtest = np.load('data1_xtest.npy') xtrain = np.load('data1_xtrain.npy') ytest = np.load('data1_ytest.npy') ytrain = np.load('data1_ytrain.npy') #2.2. Obtain a scatter plot of the training and test data, using different colors, or symbols, #for the different classes. Don’t forget to use equal scales for both axes, so that the #scatter plot is not distorted. #colors for each class c1 = 'orange' c2 = 'green' c3 = 'blue' plt.figure() plt.axis('equal') #same scale for both axis #train arrays to separate the data into each class xtrain_class1 = np.empty((0,2)) xtrain_class2 = np.empty((0,2)) xtrain_class3 = np.empty((0,2)) label1 = 'Class 1' label2 = 'Class 2' label3 = 'Class 3' size = 10 #plot/build arrays for training set for i in range(ytrain.size): if ytrain[i] == 1: plt.scatter(xtrain[i][0],xtrain[i][1], c=c1, s = size, label=label1) #plot for class 1 xtrain_class1 = np.vstack((xtrain_class1, xtrain[i])) #build array for class 1 label1 = '' if ytrain[i] == 2: plt.scatter(xtrain[i][0],xtrain[i][1], c=c2, s = size, label=label2) xtrain_class2 = np.vstack((xtrain_class2, xtrain[i])) label2 = '' if ytrain[i] == 3: plt.scatter(xtrain[i][0],xtrain[i][1], c=c3, s = size, label=label3) xtrain_class3 = np.vstack((xtrain_class3, xtrain[i])) label3 = '' #plot test dataset for i in range(ytest.size): if ytest[i] == 1: plt.scatter(xtest[i][0],xtest[i][1], s = size, c=c1) if ytest[i] == 2: plt.scatter(xtest[i][0],xtest[i][1], s = size, c=c2) if ytest[i] == 3: plt.scatter(xtest[i][0],xtest[i][1], s = size, c=c3) plt.legend() plt.title('Scatter plot of training and test data') plt.xlabel('x1') plt.ylabel('x2') plt.show() #2.3. Make a script that creates a naive Bayes classifier based on the training data, and that #finds the classifications that that classifier gives to the test data. The script should plot #the classifications of the test data as a function of the test pattern index, and should #print the percentage of errors that the classifier makes on the test data. #calculate mean and var of x for each class xtrain_mean_class1 = np.mean(xtrain_class1, axis = 0) xtrain_var_class1 = np.var(xtrain_class1, axis = 0, ddof = 0) #ddof = 0 -> divide by N and not N-1 xtrain_mean_class2 = np.mean(xtrain_class2, axis = 0) xtrain_var_class2 = np.var(xtrain_class2, axis = 0, ddof = 0) xtrain_mean_class3 = np.mean(xtrain_class3, axis = 0) xtrain_var_class3 = np.var(xtrain_class3, axis = 0, ddof = 0) #calculate covar matrix (we assume it is a diagonal matrix) xtrain_covar_class1 = np.identity(2) * xtrain_var_class1 xtrain_covar_class2 = np.identity(2) * xtrain_var_class2 xtrain_covar_class3 = np.identity(2) * xtrain_var_class3 #calculate the "probability" of each point in the test setbelonging to each of the 3 classes p_class1 = ss.multivariate_normal.pdf(xtest, xtrain_mean_class1, xtrain_covar_class1) p_class2 = ss.multivariate_normal.pdf(xtest, xtrain_mean_class2, xtrain_covar_class2) p_class3 = ss.multivariate_normal.pdf(xtest, xtrain_mean_class3, xtrain_covar_class3) #the predicted class will be the one in which the probability is bigger y_predict = np.transpose(np.asmatrix(np.argmax(np.array([p_class1, p_class2, p_class3]), axis = 0) + 1)) # the +1 is for converting index to class (0,1,2 -> 1,2,3) #2.4. Plot the classifications of the test data as a function of the test pattern index. plt.figure() for i in range(ytest.size): plt.scatter(i,ytest[i], c='blue', s= 50, label='y_test' if i == 0 else '') for i in range(y_predict.size): plt.scatter(i, float(y_predict[i]), c='orange', s = 10, label='y_predict' if i == 0 else '') plt.legend() plt.title('Classifications of the test data as a function of the test pattern index') plt.ylabel('Class') plt.xlabel('Index') #2.5. Indicate the percentage of errors that you obtained in the test set. errors = 0 for i in range(ytest.size): if y_predict[i] != ytest[i]: errors = errors + 1 percentage_errors = errors/ytest.size print("Percentage of errors: ", percentage_errors*100, "%")
# LAB11.py class Node: def __init__(self, value): self.value = value self.next = None def getValue(self): return self.value def getNext(self): return self.next def setValue(self, new_value): self.value = new_value def setNext(self, new_next): self.next = new_next def __str__(self): return "{}".format(self.value) __repr__ = __str__ class Queue: def __init__(self): self.count = 0 self.head = None self.tail = None def isEmpty(self): if self.count == 0: return True else: return False def size(self): return self.count def enqueue(self, item): newNode = Node(item) if self.count == 0: self.head = newNode self.tail = self.head elif self.count == 1: self.tail = newNode self.head.next = self.tail else: current = self.head for i in range(self.count - 1): current = current.next current.next = newNode self.tail = newNode self.count += 1 def dequeue(self): if self.count == 0: return "Queue is empty" elif self.count == 1: self.count -= 1 removed = self.head.value self.head = None return removed elif self.count == 2: self.count -= 1 removed = self.head.value self.head, self.tail = self.tail, None return removed else: self.count -= 1 removed = self.head.value newHead = self.head.next del self.head self.head = newHead return removed def printQueue(self): temp = self.head while temp: print(temp.value, end=' ') temp = temp.next print() # Collaboration Statement: # I worked on the homework(lab) assignment alone, using only previous and current course materials.
import time from selenium import webdriver vegetables = ['Onion - 1 Kg', 'Musk Melon - 1 Kg', 'Water Melon - 1 Kg', 'Almonds - 1/4 Kg'] veggies = [] driver = webdriver.Chrome(executable_path="C:\\browser\chromedriver.exe") driver.maximize_window() driver.get("https://rahulshettyacademy.com/seleniumPractise/#/") driver.find_element_by_css_selector("input[type='search']").send_keys("on") time.sleep(3) vegs = driver.find_elements_by_css_selector("h4[class='product-name']") for veg in vegs: veggies.append(veg.text) print(veggies) assert veggies == vegetables
from math import sqrt num = int(input('enter how many terms you want\n'.title())) no_of_terms_found = 1 record = 1 current_no = 2 anti_primes = [1] divisors_of_anti_primes = [[1]] def get_divisors(n): divisors = [] for i in range(1,int(sqrt(n)) + 1): if n%i == 0: if i*i == n: divisors.append(i) else: divisors.append(i) divisors.append(int(n/i)) return(divisors) while (num > no_of_terms_found): current_divisors = get_divisors(current_no) if len(current_divisors) > record: record = len(current_divisors) anti_primes.append(current_no) divisors_of_anti_primes.append(sorted(current_divisors)) no_of_terms_found += 1 current_no += 2 for i in range(num): print(anti_primes[i],divisors_of_anti_primes[i])
#!/usr/bin/env python # Simple translation model and language model data structures import sys from collections import namedtuple # A translation model is a dictionary where keys are tuples of French words # and values are lists of (english, logprob) named tuples. For instance, # the French phrase "que se est" has two translations, represented like so: # tm[('que', 'se', 'est')] = [ # phrase(english='what has', logprob=-0.301030009985), # phrase(english='what has been', logprob=-0.301030009985)] # k is a pruning parameter: only the top k translations are kept for each f. phrase = namedtuple("phrase", "english, logprob") def TM(filename, k): sys.stderr.write("Reading translation model from %s...\n" % (filename,)) tm = {} for line in open(filename).readlines(): (f, e, logprob) = line.strip().split(" ||| ") tm.setdefault(tuple(f.split()), []).append(phrase(e, float(logprob))) for f in tm: # prune all but top k translations tm[f].sort(key=lambda x: -x.logprob) del tm[f][k:] return tm # # A language model scores sequences of English words, and must account # # for both beginning and end of each sequence. Example API usage: # lm = models.LM(filename) # sentence = "This is a test ." # lm_state = lm.begin() # initial state is always <s> # logprob = 0.0 # for word in sentence.split(): # (lm_state, word_logprob) = lm.score(lm_state, word) # logprob += word_logprob # logprob += lm.end(lm_state) # transition to </s>, can also use lm.score(lm_state, "</s>")[1] ngram_stats = namedtuple("ngram_stats", "logprob, backoff") class LM: def __init__(self, filename): sys.stderr.write("Reading language model from %s...\n" % (filename,)) self.table = {} for line in open(filename): entry = line.strip().split("\t") if len(entry) > 1 and entry[0] != "ngram": (logprob, ngram, backoff) = (float(entry[0]), tuple(entry[1].split()), float(entry[2] if len(entry)==3 else 0.0)) self.table[ngram] = ngram_stats(logprob, backoff) def begin(self): return ("<s>",) def score(self, state, word): ngram = state + (word,) score = 0.0 while len(ngram)> 0: if ngram in self.table: return (ngram[-2:], score + self.table[ngram].logprob) else: #backoff score += self.table[ngram[:-1]].backoff if len(ngram) > 1 else 0.0 ngram = ngram[1:] return ((), score + self.table[("<unk>",)].logprob) def end(self, state): return self.score(state, "</s>")[1]
import re VALID_EMAIL_RE = re.compile(r"^[a-z0-9._+-]+[@][a-z0-9-]+(\.[a-z0-9-]+)+$") def validate_clean_email_string(string): return VALID_EMAIL_RE.match(string) is not None def clean_email_string(string): return string.lower().strip() # For DB models def validate_email_field_in_db(self, key, value): clean_value = clean_email_string(value) if not validate_clean_email_string(clean_value): raise AssertionError("Invalid email address") return clean_value
def contar(dato,objetivo): n = 0 for item in dato: if item == objetivo: #Encuentra coincidencia n+=1 return n lista =["a","a","b","c","a","d"] cuenta = contar(lista,"a") print(cuenta)
__author__ = 'Ashton' def a_decorator_passing_arbitrary_arguments(function_to_decorate): # Данная "обёртка" принимает любые аргументы def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs): print("Передали ли мне что-нибудь?:") print(args) print(kwargs) # Теперь мы распакуем *args и **kwargs # Если вы не слишком хорошо знакомы с распаковкой, можете прочесть следующую статью: # http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ function_to_decorate(*args, **kwargs) return a_wrapper_accepting_arbitrary_arguments class Mary(object): def __init__(self): self.age = 31 @a_decorator_passing_arbitrary_arguments def sayYourAge(self, lie=-3): # Теперь мы можем указать значение по умолчанию print("Мне %s, а ты бы сколько дал?" % (self.age + lie)) m = Mary() m.sayYourAge()
import pylev def distance(var1, var2): print("Doing levenstien distance for ", var1 , var2) print("Distance should be ", pylev.levenshtein(var1, var2)) var3 = 0 var4 = 0 var5 = 0 if var1[0] == var2[0]: var3 = var3 + 0 else: var3 = var3 + 1 if var1[1] == var2[1]: var4 = var4 + 0 else: var4 = var4 + 1 if var1[2] == var2[2]: var5 = var5 + 0 else: var5 = var5 + 1 x = len(var1) y = len(var2) z = abs(x-y) # assert(pylev.levenshtein(var1, var2), (var3+var4+var5)) print("Result is:", var3 + var4 + var5 + z) distance('dog', 'cat') distance('bat', 'cat') #distance('', 'bob') distance(None, 3) distance('asdasd', '12321asd1') # come up with test cases that break the function above # What data structure would be better to "compare" characters? ... How does the computer store characters
from openpyxl import load_workbook def worksheet_dict_reader(worksheet): """ A generator for the rows in a given worksheet. It maps columns on the first row of the spreadsheet to each of the following lines returning a dict like { "header_column_name_1": "value_column_1", "header_column_name_1": "value_column_2" } :param worksheet: a worksheet object :type worksheet: `openpyxl.worksheet.ReadOnlyWorksheet` """ rows = worksheet.iter_rows(values_only=True) # pylint: disable=stop-iteration-return header = list(filter(None, next(rows))) for row in rows: if not any(row): return yield dict(zip(header, row)) def get_spreadsheet_data(filename) -> dict: """ Uses `openpyxl.load_workbook` to process the specified file. Returns a dict of the spreadsheet data grouped by worksheet. """ workbook = load_workbook(filename=filename, read_only=True, data_only=True) dados_empresa = worksheet_dict_reader(workbook["Empresa"]) dados_funcionarios = worksheet_dict_reader(workbook["Funcionários"]) dados_pagamentos = worksheet_dict_reader(workbook["Pagamentos"]) return { "Empresa": list(dados_empresa)[0], "Funcionários": list(dados_funcionarios), "Pagamentos": list(dados_pagamentos), }
"""Parser with declaration, expression and statements. Typical usage example: new_parser = Parser(cio_instance, scn_instance) new_parser.compilation() """ from typing import Set import chario import scanner import token ADD_OP_SET: Set[str] = {"plus", "minus"} MUL_OP_SET: Set[str] = {"mul", "div", "mod"} REL_OP_SET: Set[str] = {"eq", "ne", "lt", "le", "gt", "ge"} DEC_OP_SET: Set[str] = {"type", "proc", "id"} STATEMENT_OP_SET: Set[str] = {"loop", "while", "exit", "if", "null", "id"} class Parser(object): """Parse soruce program and analyze the syntax through recursive descent approach. Attributes: chario: A Chario object to read source program and deliver errors. scanner: A Scanner object to receive source program tokens. token: A Token object to be evaluated. """ def __init__(self, new_cio: chario.Chario, new_scn: scanner.Scanner): """Init with Chario and Scanner instances.""" self.chario: chario.Chario = new_cio self.scanner: scanner.Scanner = new_scn self.token: token.Token = self.scanner.next_token() def __next_token(self) -> None: """Update token attribute with next token from scanner.""" self.token = self.scanner.next_token() def __test_token(self, expected: str, err_msg: str) -> None: """Test if the current token matches the expected token. Args: expected: A string representing expected token id. err_msg: Error message to be printed if the two tokens do not match. """ if self.token.tok_id != expected: self.__raise_error(err_msg) self.__next_token() def __raise_error(self, err_msg: str) -> None: """Raise exception with custom error message. Args: err_msg: Error message to be printed. """ self.chario.put_error(err_msg) raise Exception(err_msg) # Starting from below are methods implementing TinyAda EBNF. def compilation(self) -> None: """Run compilation.""" if self.chario.src: self.__subprogram_body() self.__test_token("eof", "Unexpected file termination") self.chario.report_errors() def __subprogram_body(self) -> None: self.__subprogram_spec() self.__test_token("is", "'is' expected") self.__declarative_part() self.__test_token("begin", "'begin' expected") self.__seq_of_statements() self.__test_token("end", "'end' expected") if self.token.tok_id == "id": self.__next_token() self.__test_token("semi", "';' expected") def __declarative_part(self) -> None: while self.token.tok_id in DEC_OP_SET: self.__basic_declaration() def __basic_declaration(self) -> None: if self.token.tok_id == "type": self.__type_declaration() elif self.token.tok_id == "proc": self.__subprogram_body() elif self.token.tok_id == "id": self.__obj_num_declaration() else: self.__raise_error("error for [basic_declaration]") def __obj_num_declaration(self) -> None: self.__identifier_list() self.__test_token("colon", "':' expected") if self.token.tok_id == "const": # numberDeclaration self.__next_token() self.__test_token("assign", "':=' expected") self.__expression() else: # objectDeclaration self.__type_definition() self.__test_token("semi", "';' expected") def __identifier_list(self) -> None: self.__test_token("id", "identifier expected") while self.token.tok_id == "comma": self.__next_token() self.__test_token("id", "identifier expected") def __type_declaration(self) -> None: self.__test_token("type", "'type' expected") self.__test_token("id", "identifier expected") self.__test_token("is", "'is' expected") self.__type_definition() self.__test_token("semi", "';' expected") def __type_definition(self) -> None: if self.token.tok_id == "l_par": self.__enum_type_definition() elif self.token.tok_id == "array": self.__array_type_definition() elif self.token.tok_id == "range": self.__range() elif self.token.tok_id == "id": self.__name() else: self.__raise_error("error for [type_definition]") def __range(self) -> None: self.__test_token("range", "'range' expected") self.__simple_expression() self.__test_token("to", "'..' expected") self.__simple_expression() def __index(self) -> None: if self.token.tok_id == "range": self.__range() elif self.token.tok_id == "id": self.__name() else: self.__raise_error("error for [index]") def __enum_type_definition(self) -> None: self.__test_token("l_par", "'(' expected") self.__identifier_list() self.__test_token("r_par", "')' expected") def __array_type_definition(self) -> None: self.__test_token("array", "'array' expected") self.__test_token("l_par", "'(' expected") self.__index() while self.token.tok_id == "comma": self.__next_token() self.__index() self.__test_token("r_par", "')' expected") self.__test_token("of", "'of' expected") self.__name() def __subprogram_spec(self) -> None: self.__test_token("proc", "'procedure' expected") self.__test_token("id", "identifier expected") if self.token.tok_id == "l_par": self.__formal_part() def __formal_part(self) -> None: self.__test_token("l_par", "'(' expected") self.__parameter_specification() while self.token.tok_id == "semi": self.__next_token() self.__parameter_specification() self.__test_token("r_par", "')' expected") def __parameter_specification(self) -> None: self.__identifier_list() self.__test_token("colon", "':' expected") self.__mode() self.__name() def __mode(self) -> None: if self.token.tok_id == "in": self.__next_token() if self.token.tok_id == "out": self.__next_token() elif self.token.tok_id == "out": self.__next_token() def __condition(self) -> None: self.__expression() def __expression(self) -> None: self.__relation() if self.token.tok_id == "and": while self.token.tok_id == "and": self.__next_token() self.__relation() elif self.token.tok_id == "or": while self.token.tok_id == "or": self.__next_token() self.__relation() def __relation(self) -> None: self.__simple_expression() if self.token.tok_id in REL_OP_SET: self.__next_token() self.__simple_expression() def __simple_expression(self) -> None: if self.token.tok_id in ADD_OP_SET: self.__next_token() self.__term() while self.token.tok_id in ADD_OP_SET: self.__next_token() self.__term() def __term(self) -> None: self.__factor() while self.token.tok_id in MUL_OP_SET: self.__next_token() self.__factor() def __factor(self) -> None: if self.token.tok_id == "not": self.__next_token() self.__primary() else: self.__primary() if self.token.tok_id == "exp": self.__next_token() self.__primary() def __primary(self) -> None: if self.token.tok_id == "int": self.__next_token() elif self.token.tok_id == "l_par": self.__next_token() self.__expression() self.__test_token("r_par", "')' expected") elif self.token.tok_id == "id": self.__name() else: self.__raise_error("error for [primary]") def __name(self) -> None: self.__test_token("id", "identifer expected") if self.token.tok_id == "l_par": self.__indexed_component() def __indexed_component(self) -> None: self.__test_token("l_par", "'(' expected") self.__expression() while self.token.tok_id == "comma": self.__next_token() self.__expression() self.__test_token("r_par", "')' expected") def __seq_of_statements(self) -> None: self.__statement() while self.token.tok_id in STATEMENT_OP_SET: self.__statement() def __statement(self) -> None: if self.token.tok_id == "id": self.__assign_call_statement() elif self.token.tok_id == "exit": self.__exit_statement() elif self.token.tok_id == "if": self.__if_statement() elif self.token.tok_id == "null": self.__null_statement() elif self.token.tok_id in ("while", "loop"): self.__loop_statement() else: self.__raise_error("error for [statement]") def __null_statement(self) -> None: self.__test_token("null", "'null' expected") self.__test_token("semi", "';' expected") def __loop_statement(self) -> None: if self.token.tok_id == "while": self.__test_token("while", "'while' expected") self.__condition() self.__test_token("loop", "'loop' expected") self.__seq_of_statements() self.__test_token("end", "'end' expected") self.__test_token("loop", "'loop' expected") self.__test_token("semi", "';' expected") def __if_statement(self) -> None: self.__test_token("if", "'if' expected") self.__condition() self.__test_token("then", "'then' expected") self.__seq_of_statements() while self.token.tok_id == "elsif": self.__test_token("elsif", "'elsif' expected") self.__condition() self.__test_token("then", "'then' expected") self.__seq_of_statements() if self.token.tok_id == "else": self.__test_token("else", "'else' expected") self.__seq_of_statements() self.__test_token("end", "'end' expected") self.__test_token("if", "'if' expected") self.__test_token("semi", "';' expected") def __exit_statement(self) -> None: self.__test_token("exit", "'exit' expected") if self.token.tok_id == "when": self.__test_token("when", "'when' expected") self.__condition() self.__test_token("semi", "';' expected") def __assign_call_statement(self) -> None: self.__name() if self.token.tok_id == "assign": self.__next_token() self.__expression() elif self.token.tok_id == "l_par": self.__indexed_component() self.__test_token("semi", "';' expected")
""" Created on 4/25/2020 @author: erosales Description of file: """ from clear_log import clear from player import Player total_players = dict() first_spins = [] def create_player(player_number): player_name = input("\nPlayer %s, what is your name: " % player_number) clear() _spin(player_name) def _spin(player_name): print("\n%s, please spin to determine the order of players." % player_name) spin = input("\nType in \"SPIN\" and press ENTER: ") clear() if spin == 'SPIN': temp_player = Player(name=player_name) turn = temp_player.spin() print("\n%s, you spun a %s." % (player_name, turn)) if turn not in total_players.keys(): temp_player.turn = turn total_players[turn] = temp_player first_spins.append(int(turn)) else: temp = turn while temp in total_players.keys(): turn = int(turn) - 1 if turn not in total_players.keys(): total_players[turn] = Player(name=player_name, turn=str(turn)) first_spins.append(int(turn)) break else: print("\nWhoops! you typed in \"%s\"." % spin) _spin(player_name)
i=1 while i<=100: if i%3==0 or i%5==0: i+=1 continue; else: print(i) i+=1
num=int(input("Enter the number to find factorial:")) f=1 for i in range(num,0,-1): f=f*i print("The factorial of given number:"+str(f))
# Python program to demonstrate that copy # created using set copy is shallow first = {'g', 'e', 'e', 'k', 's'} second = first.copy() # before adding print ('before adding: ') print ('first: ',first) print ('second: ', second ) # Adding element to second, first does not # change. second.add('f') # after adding print ('after adding: ') print( 'first: ', first) print ('second: ', second )
a=2 print(id(a)) print(id(2)) a=a+1 print(id(3)) print(id(a)) b=2 print(id(2)) print(id(b)) def printhello(): print("hello") a=printhello() print(a)
from array import * a=array('i',[1,23,45,67]) pos=int(input("Enter the element position which you want to display:")) for i in range(pos-1,3): a[i]=a[i+1] for i in range(3): print(a[i])
name='''vanshika sikarwar is not a good girl but she tries to be a good girl''' age="""Her age is very small than understanding""" print(name) print(age) print("Hello,\ with \ world") print(\ "Hello,\ world") print(1+2\ +3+4) print(r"vanshika sikarwar""\\")
n =input() if isinstance(n, int): print("This input is of type integer") elif isinstance(n, float): print("This input is of type float") elif isinstance(n, str): print("This input is of type string") else: print("This is something else")
t=int(input()) while t!=0: string=input() print(string.replace('a',"xxx"))
#create a function to find if a number is prime or not. def is_prime(num): if num == 1: return False for i in range(2, num): if num % i == 0: return False return True #create a function to find median of two sorted lists in O(logn) time. def find_median(list1, list2): if len(list1) > len(list2): list1, list2 = list2, list1 x = len(list1) y = len(list2) low = 0 high = x while low <= high: partitionX = (low + high) // 2 partitionY = (x + y + 1) // 2 - partitionX maxLeftX = list1[partitionX - 1] if partitionX != 0 else float('-inf') minRightX = list1[partitionX] if partitionX != x else float('inf') maxLeftY = list2[partitionY - 1] if partitionY != 0 else float('-inf') minRightY = list2[partitionY] if partitionY != y else float('inf') if maxLeftX <= minRightY and maxLeftY <= minRightX: if (x + y) % 2 == 0: return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY)) / 2 else: return max(maxLeftX, maxLeftY) elif maxLeftX > minRightY: high = partitionX - 1 else: low = partitionX + 1
# Python program to remove duplicate elements in list lst = [1,2,3,4,4,5,6,6,6,7,8,9,9,9,9,10] new_lst = [] for i in lst: if i not in new_lst: new_lst.append(i) print(" Original list --> ",lst) print(" List after removing duplicate elements -->",new_lst)
size = int(input("Enter the size of queue : ")) Queue = [] def insert(): if len(Queue) < size: element1 = input("Enter the element to insert:") Queue.append(element1) print("Queue : ", Queue) else: print("Queue is full!!") def delete(): if len(Queue) <= 0: print("Queue is empty!!") else: Queue.remove(Queue[0]) print("Queue : ", Queue) while True: option = int(input("Enter the Queue operation: \n 1.Insert 2.Delete :")) if option == 1: insert() elif option == 2: delete()
class Vehicle: def car(self, company, color): self.company = company self.color = color print("Car details : ", self.company, self.color) def bike(self): print() ve = Vehicle() ve.car('BMW', ", Black") #ve.bike()
salary = float(input("Enter your salary:")) service = float(input("Enter the total years of service:")) bonus = float((5/100)*salary) if(service>=5): print("your net bonus amount is ",salary+bonus) else: print("Bonus not applicable!!")
num1 = int(input("Enter num 1: ")) num2 = int(input("Enter num 2: ")) print(num1, "*", num2, "=", num1*num2)
# person child parent student # child and parent inherit person # student class inherit child class Person: def per(self, name, age, gender): self.name = name self.age = age self.gender = gender print(self.name, self.age, self.gender) class Parent(Person): def par(self, job, place, salary): self.job = job self.place = place self.salary = salary print(self.job, self.place, self.salary) class Child(Person): def chi(self, school): self.school = school print(self.school) class Student(Child): def std(self, rollno): self.rollno = rollno print(self.rollno) obj1 = Parent() obj1.per('Joel', 23, 'Male') obj1.par('Developer', 'EKM', 50000) obj2 = Child() obj2.chi('KPMHSS') obj3 = Student() obj3.std(10)
# remove special characters string="H,el;l,o W::or?ld" s_char=",<.>/?;:" n_string="" # for i in string: # if i in s_char: # continue # else: # n_string+=i for i in string: if i not in s_char: n_string+=i print(n_string)
# Write a Python program that matches a string that has an 'a' followed by anything, ending in 'b import re n = input("Enter string : ") x = '(^a[\w\W]*b)$' match = re.fullmatch(x,n) if match : print("Valid") else: print("Invalid")
# starting with a and ending with b import re n = input("Enter string : ") x = '(^a[\w\W]*b)$' match = re.fullmatch(x,n) if match is not None: print("Valid") else: print("Invalid")
# LAMBDA # Addition using lambda add = lambda num1,num2:num1+num2 print("Addition: ",add(1,2)) sub = lambda num1,num2:num1-num2 print("Subtraction: ",sub(10,2.3)) mul = lambda num1,num2:num1*num1 print("Multiplication:", mul(5,4)) div = lambda num1,num2:num1/num2 print("Division: ",div(5,2))
lst = [1,"Joel",2,'j',3,4,5,6,7,8,9,10] search = (input("Enter an element to search : ")) if search in lst: print("Element found !!") else: print("Element not found!!")
EMPLOYEE = {'ID': "1001", "Name": 'Joel', "Designation": "Dev", "Salary": 20000} # Print emp name print("EMP Name : ", EMPLOYEE['Name']) # company : name if 'COMP' not in EMPLOYEE: EMPLOYEE['COMP'] = 'Google' print(EMPLOYEE) # Salary + 5000 EMPLOYEE['Salary'] += 5000 # Print for i in EMPLOYEE: print(i, ":", EMPLOYEE[i])
# whileloop # syntax: # initialization # while(condition) # statement # inc or decr i=1 while(i<=10): print("Hi") i+=1
# single inheritance class Person: # parent class / base class / super class def details(self, name, age, gender): self.name = name self.age = age self.gender = gender def print(self): print(self.name, self.age, self.gender) class Student(Person): # child class / sub class / derived class def det(self, r_no, school): self.r_no = r_no self.school = school def print_s(self): print(self.r_no, self.school) per = Person() per.details('Joel', 23, "M") per.print() st = Student() st.det(10, 'LMPS') st.print_s() st.details('Johny', 23, 'M') st.print()
# List slicing # lst[upper limit:lowerlimit] # from upper limit to lower limit-1 lst = [0,1,2,3,4,5,6] print(len(lst)) # print(lst[:]) # print(lst[1:]) # print(lst[:9]) print(lst[3:-4])
import pygame import math import random import sys #colours to be used in game Green = (50,205 ,50) Ivory = (255,255,240) Blue = (0,0,255) Red = (255,0,0) Purple = (255,0,255) Grey = (190,190,190) Black = (0,0,0) White = (255, 255, 255) Yellow = (255, 255, 0) Orange = (255, 165, 0) #screen width and height WIDTH = 540 HEIGHT = 720 # Drwaing the healtbar for the player. Its attributes are the surface(the screen) its colour which is green, # its x and y coordinates which are in the top left corner of the screen and a player_health value so it can #decwhich can decrease. def draw_health(screen, color, x, y, health): #widht and height local constant variables that never change. The player_health can change BAR_HEIGHT = 20 # Bar is a variable for a rectangle with x and y 1and then a widht of the amount filled calculated above # and height of the constant Bar height. Bar changes colour when player health reaches certain point # bar = pygame.Rect(x,y, amount_filled, BAR_HEIGHT) if health > 75: color = Green elif health > 30: color = Yellow else: color = Red if health < 0: health = 0 pygame.draw.rect(screen,color,[x,y,health,BAR_HEIGHT],0) # Draw the text on screen function. It has text, the string for what will be said. The # size of the font, the colour of the text and the x and y cooridnates. The font obects is then # defined to draw text. Text Surface renders the pixels of the text onto the screen. # The true means whther the text will be anit-aliased or not. Anit-aliased gets rid of rough #edges on corners of letters and makes the writing look smoother. Text rect will create # a text box where the text will go in. The x and y of the actual text will go directly in the #centre of the box. def message_display(surface,text, size, color, x, y): font = pygame.font.SysFont('OCR A extended', size) titleFont = pygame.font.SysFont('OCR A extended', size) TextSurface = font.render(text, True, color) TextRect = TextSurface.get_rect() TextRect.center = (x, y) screen.blit(TextSurface, TextRect) class Player(pygame.sprite.Sprite): def __init__(self, platforms_group, enemy_group, powerups_group, all_sprites_list): super().__init__() #set height and width as local variables, fill the colour of the image. width = 50 height = 50 self.image = pygame.image.load("img/bluie.png").convert_alpha() self.rect = self.image.get_rect() #speed of the player. Change in its x direction or change # in its y direction self.change_x = 0 self.change_y = 0 # gains the platform as an attribute so it can gain the platforms attributes and methods self.platforms_group = platforms_group self.enemy_group = enemy_group self.powerups_group = powerups_group self.all_sprites_list = all_sprites_list self.health= 100 self.score = 0 #The initialisation of a timer that will count from zero and time that amount of time that passes once an enemy #player collides with enemy and begins losing health self.time_since_last_hit = 0 # A counter that will spawn enemies based on the screen scrolling upwards initially set at zero self.next_enemy_scroll_counter = 0 # A counter that will spawn powwrups also based on the screen scrolling upwards self.next_powerup_scroll_counter = 100 self.time_since_last_shot = 0 def update(self): #Gravity, defined below self.gravity() #To move left or right self.rect.x += self.change_x #To move up or down self.rect.y += self.change_y #Return the amount of seconds or milleiseconds that have passed since the timer began self.time_since_last_hit += clock.get_time() self.time_since_last_shot += clock.get_time() #Check to see if player collides with something #Resets player position based on the top or bottom of the object if self.change_y > 0: collides= pygame.sprite.spritecollide(self, self.platforms_group, False) #If player hits something take the players y coordinate and set it to the top # of the object it has collided with #set y velocity to 0 so the player stops moving if collides: if self.rect.y < collides[0].rect.bottom: self.rect.bottom = collides[0].rect.top self.change_y = 0 # Enemy collision with player: Every half a second the timer checks for collisions between the player and enemy #If there is a collision, ilast for half a second, reduces health by -20 and the timer resets to zero if self.time_since_last_hit > 1000: enemycollision = pygame.sprite.spritecollide(self, self.enemy_group, False) if enemycollision: self.health = self.health - 20 self.time_since_last_hit = 0 # collision for when player collides with powerup. If so then the powerup disappears and player should fly upwards at faster velocity powerupcollision = pygame.sprite.spritecollide(self, self.powerups_group, True) if powerupcollision: self.change_y = -25 #wraps around the top and bottom of screen if self.rect.x > WIDTH: self.rect.x= 0 if self.rect.x < 0: self.rect.x = WIDTH #When the top of the player reaches the top third of the screen, everthing should move down. #Take the players y postion and move it upwards, use the absolute value since player velocity is #negative moving upwards. Take the y position of the platforms and add the y velocity of the #player. For each platform, it moves down at the speed of the player if self.rect.top <= HEIGHT / 3: self.rect.y += abs(self.change_y) for platforms in self.platforms_group: platforms.rect.y += abs(self.change_y) if platforms.rect.top >= HEIGHT: self.score += 10 platforms.kill() for enemies in self.enemy_group: enemies.rect.y += abs(self.change_y) if enemies.rect.top >= HEIGHT: enemies.kill() for powerups in self.powerups_group: powerups.rect.y += abs(self.change_y) if powerups.rect.top >= HEIGHT: powerups.kill() self.next_enemy_scroll_counter -= abs(self.change_y) self.next_powerup_scroll_counter -= abs(self.change_y) #player goes off the screen it dies # When there are 5 platforms on screen, spawn a random platform as defined below. while len(self.platforms_group) == 5: platform = Platform(random.randrange(0, WIDTH -100), random.randrange(-45,-40), random.randrange(60,100), 25) self.platforms_group.add(platform) self.all_sprites_list.add(platform) # To spawn random enemies, if there are less than 3 and the timer is zero.. if len(self.enemy_group) < 3 and self.next_enemy_scroll_counter <= 0: #One line if statement that chooses one of two random x coordinates to spawn an enemy newenemyx = 0 if random.randint(0, 1) == 0 else WIDTH - 30 #Random y cooridnate just above the screen newenemyy = random.randrange(-60, -30) enemy = Enemy(newenemyx, newenemyy, 30, 30) self.all_sprites_list.add(enemy) self.enemy_group.add(enemy) # spawn the enemy at the y cooridnate specified + a number of pixels to space it out self.next_enemy_scroll_counter = (newenemyy) + 200 #if the counter is at zero, spawn a powerup and spawn it every 1200 to 2000 pixels if self.next_powerup_scroll_counter <= 0: newpowerupx = random.randint(0, WIDTH - 40) newpowerupy = -30 powerup = Powerup(newpowerupx, newpowerupy, 25, 25) self.powerups_group.add(powerup) self.all_sprites_list.add(powerup) self.next_powerup_scroll_counter = random.randint(1500, 2000) def gravity(self): #Effects of gravity if self.change_y == 0: self.change_y = 1 else: self.change_y += 0.5 def jump(self): #check below to see if there is anything to jump from then shift back up self.rect.y +=2 collides= pygame.sprite.spritecollide(self, self.platforms_group, False) self.rect.y -=2 #Set the speed upwards if its ok to jump if collides: self.change_y = -12 def dead(self): return self.rect.top > HEIGHT or self.health <= 0 #Player controlled movement def move_left(self): self.change_x = -7 def move_right(self): self.change_x = 7 def stop(self): self.change_x = 0 # for player to shoot, variable called fireball spawns fireball that comes from the center of the player # and comes out from the top def shoot(self): if self.time_since_last_shot > 2000: fireball = Fireball(self, self.enemy_group, self.rect.x,self.rect.y) self.all_sprites_list.add(fireball) self.time_since_last_shot = 0 class Platform(pygame.sprite.Sprite): def __init__(self,x,y,width,height): super().__init__() self.image = pygame.image.load("img/platform.png").convert_alpha() self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y class Fireball(pygame.sprite.Sprite): def __init__(self,player,enemy_group,x,y): super().__init__() self.image = pygame.image.load("img/fireball.png").convert_alpha() self.rect = self.image.get_rect() self.player = player self.enemy_group = enemy_group self.rect.x = self.player.rect.centerx self.rect.y = self.player.rect.y self.change_y = -8 self.player.score = player.score def update(self): self.rect.y += self.change_y if self.rect.bottom < 0: self.kill() fireball_hits = pygame.sprite.spritecollide(self, self.enemy_group, True) if fireball_hits: self.player.score +=5 class Enemy(pygame.sprite.Sprite): def __init__(self,x,y,width,height): super().__init__() self.image = pygame.image.load("img/crabby.png").convert_alpha() self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.change_x = 0 self.change_y = 0 def update(self): self.rect.x += self.change_x self.rect.y += self.change_y if self.rect.x == 0: self.change_x = 6 if self.rect.x == WIDTH -30: self.change_x = -6 class Powerup(pygame.sprite.Sprite): def __init__(self, x, y, width, height): super().__init__() self.image = pygame.image.load("img/ufo.png").convert_alpha() self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.vel_y = 3 def update(self): self.rect.y += self.vel_y #initilaise pygame pygame.init() #manage how fast the screen updates clock = pygame.time.Clock() size = [WIDTH, HEIGHT] screen = pygame.display.set_mode(size) #set title of the window pygame.display.set_caption('Space Hopper') # this is the introduction function. it will load when the game runs. It will be filled def intro(): screen.fill(Blue) message_display(screen, "Space Hopper", 48, Green, WIDTH/2, HEIGHT- 600) message_display(screen, "Left key to move left", 24, Yellow, WIDTH/2, HEIGHT- 400) message_display(screen, "Right key to move Right", 24, Yellow, WIDTH / 2, HEIGHT - 350) message_display(screen, "Space Bar to jump", 24, Yellow, WIDTH/2, HEIGHT- 300) message_display(screen, "Up arrow to shoot", 24, Yellow, WIDTH/2, HEIGHT- 250) message_display(screen, "Press any key to play!", 24, Yellow, WIDTH/2, HEIGHT- 100) pygame.display.flip() key_pressed = False while not key_pressed: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: key_pressed = True def outro(score, highscore, new_highscore): screen.fill(Blue) message_display(screen, "Game Over!", 48, Red, WIDTH/2, HEIGHT- 600) message_display(screen, "Score: " + str(score), 24, Yellow, WIDTH / 2, HEIGHT - 400) if new_highscore: highscore_text = "NEW HIGH SCORE ACHIEVED: " else: highscore_text = "Highscore: " message_display(screen, highscore_text + str(highscore), 24, Yellow, WIDTH / 2, HEIGHT - 350) message_display(screen, "Press Enter to play again ", 24, Yellow, WIDTH / 2, HEIGHT - 200) pygame.display.flip() key_pressed = False while not key_pressed: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: key_pressed = True def game(): #list to hold the spritrs all_sprites_list = pygame.sprite.Group() #create the sprites #platform = Platform() platforms_group = pygame.sprite.Group() newplatform = Platform(300, HEIGHT - 100, 120, 25) all_sprites_list.add(newplatform) platforms_group.add(newplatform) newplatform = Platform(180, HEIGHT - 220, 120, 25) all_sprites_list.add(newplatform) platforms_group.add(newplatform) newplatform = Platform(380, HEIGHT - 350, 120, 25) all_sprites_list.add(newplatform) platforms_group.add(newplatform) newplatform= Platform(200, HEIGHT - 450, 120, 25) all_sprites_list.add(newplatform) platforms_group.add(newplatform) newplatform = Platform(330, HEIGHT - 600, 120, 25) all_sprites_list.add(newplatform) platforms_group.add(newplatform) platform = Platform(random.randrange(0, WIDTH -100), random.randrange(-50, -30), random.randrange(60,100) , 25) platforms_group.add(platform) all_sprites_list.add(platform) enemy_group = pygame.sprite.Group() newenemy = Enemy(0, HEIGHT - 380, 30, 30) all_sprites_list.add(newenemy) enemy_group.add(newenemy) newenemy = Enemy(WIDTH - 30, HEIGHT - 530, 30, 30) all_sprites_list.add(newenemy) enemy_group.add(newenemy) powerups_group = pygame.sprite.Group() #sets the player postion x and y cooridnates and adds it to sprite list player = Player(platforms_group, enemy_group, powerups_group, all_sprites_list) player.rect.x = 300 player.rect.y = HEIGHT - 100 all_sprites_list.add(player) #-------MAIN PROGRAM LOOP--------# while not player.dead(): #limit to 60 frames per second of screen update clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # When holding down a key keys = pygame.key.get_pressed() if keys [pygame.K_LEFT]: player.move_left() if keys [pygame.K_RIGHT]: player.move_right() if keys [pygame.K_SPACE]: player.jump() if keys[pygame.K_UP]: player.shoot() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT and player.change_x < 0: player.stop() if event.key == pygame.K_RIGHT and player .change_x >0: player.stop() #Update the player all_sprites_list.update() #DRAW TEXT CODE screen.fill(Blue) all_sprites_list.draw(screen) draw_health(screen, Green,10, 10, player.health) message_display(screen, "Score:" + str(player.score), 22, Yellow, WIDTH/2, 15) # screen blit allows the player image to be on top of everything else so when it passes somwthing # it doesnt disappear behind it. screen.blit(player.image, player.rect) #updates the screen with any changes pygame.display.flip() return player.score intro() highscore = 0 while True: score = game() new_highscore = False if score > highscore: new_highscore = True highscore = score outro(score, highscore,new_highscore) pygame.quit()
# names = ["sahil","shripad","Dudwadkar","mr.dude"] # for item in names: # print(item) # [syntax] --- For loop # for i in range(10): # print(f"Hello World {i}") #sum from 1 to 10 # total = 0 # for i in range(1,11): # total = total + i # print(total) # user input num = int(input("Enter a number :")) total = 0 for i in range(1,num+1): total = total + i print(total)
# Print string last character with function # def last_char(name): # return name[-2] # print(last_char("sahil")) # ------------------------------------------------------------------------ # Even or odd # def odd_even(num): # if num%2==0: # return "even" # return "odd" # num = int(input("Enter a number :")) # print(odd_even(num)) # ---------------------------------------------------------------------------------- # Even or odd & return Boolean Value # def ifs_even(num): # if num%2==0: # return True # else: # return False # num = int(input("Enter a number for entered number is even or not :")) # print(ifs_even(num)) # ----------------------------------------------------------------------------------- # Grater Num function # def Greater_num(a,b): # if a>b: # return a # return b # num1 = int(input("Enter num1 :")) # num2 = int(input("Enter num2 :")) # print(Greater_num(num1,num2)) # given string is palindrom or not def is_palindrom(name): reverse_name = name[::-1] if name == reverse_name: return "Name is palindrome" return "Name is not palindrome" name = input("Enter a name for check name is palindrome or not :") print(is_palindrom(name))
# def fibo(num): # a=0 # b=1 # if num == 1: # print(a) # elif num == 2: # print(b) # else: # # print(a,b , end = " ") # for i in range(num-2): # c=a+b # a=b # b=c # print(b,end = " ") # fibo(10) # -------------------------------------------------------------------------------------- # fibonacci series with user input def fibo(num): a=0 b=1 if num == 1: print(a) elif num == 2: print(b) else: for i in range(num): c = a+b a = b b = c print(b,end=" ") num = int(input("Enter a number for fibonacci series")) print(fibo(num))
# set1 = {11,12,13,14} # print(set1) # Print set with for loop # for i in set1: # print(i) # print null set # set1 = set({}) # print(set1) # add method for adding elements in set # set1 = {11,12,13,14} # print(set1) # set1.add(66) # print(set1) # update() method -- for adding one more value in set # set1 = {11,12,13,14} # print(set1) # set1.update({55,66}) # print(set1) # discard() method for removing elements from set # set1 = {11,12,13,14} # print(set1) # set1.discard(12) # print(set1) # remove() method for removing elements from set # set1 = {11,12,13,14} # print(set1) # set1.remove(12) # print(set1) # pop() method for remove random element from set # set1 = {11,12,13,14} # print(set1) # set1.pop() # print(set1) # clear() method for removing total set element from set # set1 = {11,12,13,14} # print(set1) # set1.clear() # print(set1) # Union - Intersection - Difference A = {0,2,4,6,8,10} B = {1,2,3,4,5,6} print("Union Result is :" + str(A | B)) print("Intersection Result is :" + str(A & B)) print("Difference Result is :" + str(A - B)) # print("Union Result is :" + str(A | B)) -----------------// Merge or combine two sets # print("Intersection Result is :" + str(A & B)) ---------------------// Return commom values between two sets # print("Difference Result is :" + str(A - B)) -----------------------// Return diffrent values from two sets
number_one = float(input("Enter first number")) number_two = float(input("Enter second number")) total = number_one + number_two print(total) # num1 = str(4) # num2 = float("20") # num3 = int("50") # print(num2 + num3)
# 73_factorial_using_while.py n = 5 factorial = 1 i = n while(i > 0): factorial = factorial * i i = i - 1 print(f"{n}! = {factorial}")
# 24_conditional_operators.py ''' == Equal to != Not equal to < less than <=less than or equal to > greater than >= greater than or equal to ''' print('10 == 10', 10 == 10) print('10 == 11', 10 == 11) print('15 != 15', 15 != 15) print('15 != 25', 15 != 25) print('20 < 30', 20 < 30) print('20 < 10', 20 < 10)
# 109_max_number_in_a_list.py import math my_list = [ 34, 5, 77, 87, 556, 99, 98, 347, 33, 232 ] max = -math.inf for num in my_list: if(num > max): max = num print('Max = ', max)
# 52_range_with_steps.py n = 10 print("Starting at 0\nStep: 2") for i in range(0, n, 2): print(i) print("Starting at 1\nStep: 2") for i in range(1, n, 2): print(i) print("Starting at 5\nStep: 2") for i in range(5, n, 2): print(i) """[output] Starting at 0 Step: 2 0 2 4 6 8 Starting at 1 Step: 2 1 3 5 7 9 Starting at 5 Step: 2 5 7 9 """
# 28_max_of_three_numbers.py print("---- Max of three numbers ----") a = int(input("Enter first number : ")) b = int(input("Enter second number: ")) c = int(input("Enter third number : ")) if(a > b): # a is max if(a > c): print("Max: ", a) else: print("Max: ", c) else: # b is max if(b > c): print("Max: ", b) else: print("Max: ", c)
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import copy import itertools def get_maximums(numbers): max_liste = [] for liste in numbers: max_liste.append(max(liste)) return max_liste def join_integers(numbers): return int(''.join([str(elem) for elem in numbers])) def generate_prime_numbers(limit): prime = [] numbers = list(range(2,(limit+1))) while len(numbers) != 0: prime.append(numbers[0]) numbers = [values for values in numbers if values % numbers[0] != 0] return prime def combine_strings_and_numbers(strings, num_combinations, excluded_multiples): combined = [] numbers = list(range(1,num_combinations + 1)) if excluded_multiples != None: numbers = [values for values in numbers if values % excluded_multiples != 0] for values in numbers: for elem in strings: combined.append(elem + str(values)) return combined if __name__ == "__main__": print(get_maximums([[1,2,3], [6,5,4], [10,11,12], [8,9,7]])) print("") print(join_integers([111, 222, 333])) print(join_integers([69, 420])) print("") print(generate_prime_numbers(17)) print("") print(combine_strings_and_numbers(["A", "B"], 2, None)) print(combine_strings_and_numbers(["A", "B"], 5, 2))
import pickle from course import Course from student import Student from edge import Edge # the purpose of this script is to create the edges for the graph # using data from the .pickle file of students data = open('./data/students.pickle', 'rb') students = pickle.load(data) data.close() data = open('./data/students.pickle', 'wb') pickle.dump(students, data) data.close() data = open('./data/edges.pickle', 'rb') edgesToLoad = pickle.load(data) data.close() text = open('edgeHash.txt', 'w') edges = {} for s in students: courses = students[s].courses for c in courses: for d in courses: if c is not d: e = Edge(c,d) text.write(str(e.__hash__()) + ": " + e.toString() + "\n") edges[e.__hash__()] = e text.close() data = open('./data/edges.pickle', 'wb') pickle.dump(edges, data) data.close()
num1=input("Enter first Numb: ") num2=input("Enter Second Numb: ") num3=input("Enter Third Numb: ") #num=(int(num1)+int(num2)+int(num3))/3 print(f"Average of given numbers: {(int(num1)+int(num2)+int(num3))/3}") name="Sandeep" print(name[0:])
# Some functions of Strings hello = "my name is Hardik" standard = "I am in eleventh standard." print(hello + standard) # 1. Len print(len(hello)) # 2. endswith print(hello.endswith('Hardik')) # 3. capitalize print(hello.capitalize()) # 4. count print(hello.count('a')) # 5. replace print(hello.replace('name', 'hardik')) # 6. find print(hello.find('hardik'))
""" Iterators and generators """ MAX_SEQ = 42 def fibonacci_generator(): index = 2 first = 0 second = 1 if MAX_SEQ == 1: yield first elif MAX_SEQ == 2: yield second else: while index < MAX_SEQ: third = first + second first = second second = third index += 1 yield third if __name__ == '__main__': fibonacci_iterator = fibonacci_generator() while True: try: the_number = next(fibonacci_iterator) #print(the_number) except StopIteration: print("I'm done!") break print('The {} Fibonacci number is:'.format(MAX_SEQ)) print(the_number)
# original autor: maksim32 # Rewrite to Python 3: Code0N # Original date: 2017-09-10 # Rewrite date: 02.04.2021 import sys g_alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюяABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ,." def Trisemus(key, strval, action): keyword, (height, width) = key isEncode = True if action == "encode" else False isDecode = True if action == "decode" else False # building table pos = 0 table = [['.' for x in range(width)] for y in range(height)] hchars = {} for i in keyword + g_alphabet: if hchars.get(i) == None: hchars[i] = pos table[int(pos / width)][pos % width] = i pos += 1 if pos >= width * height: break print("Debug table\n") #print('\n'.join(' '.join(j for j in table[i]) for i in range(len(table)))) # debug: output table result = "" for i in strval: pos = hchars.get(i) if pos != None: x = pos % width if isEncode: y = (int(pos / width) + 1) % height elif isDecode: y = (int(pos / width) - 1 + height) % height else: y = int(pos / width) % height # do nothing result += table[y][x] else: # then you need to select one of the actions with symbols that are not in the table : result += i # leave unchanged #result += "" # delete #result += table[height - 1][width - 1] # replace to last in table return result keyword = input("Please, enter keyword: ") tablesize = (11, 11) key = (keyword, tablesize) print("key = " + str(key)) inputstr = input("Text to encode: ") print("Given string: '{}'\n".format(inputstr)) s = Trisemus(key, inputstr, "encode") print("Encoded text '{}'\n".format(s)) s = Trisemus(key, s, "decode") print("Decoded text '{}'\n".format(s))
'__author__'=='deepak Singh Mehta(learning graphs)) ' #problem :- https://www.hackerrank.com/challenges/journey-to-the-moon #theory:- Set-Disjoint if __name__=='__main__': n, m = map(int, input().split()) lis_of_sets = [] for i in range(m): a,b = map(int, input().split()) indices = [] new_set = set() set_len = len(lis_of_sets) s = 0 while s < set_len: if a in lis_of_sets[s] or b in lis_of_sets[s]: indices.append(s) new_set = new_set.union(lis_of_sets[s]) del lis_of_sets[s] set_len -= 1 else: s += 1 new_set = new_set.union([a, b]) lis_of_sets.append(new_set) ans = n*(n-1)//2 for i in lis_of_sets: ans -= len(i)*(len(i)-1)//2 print(ans)
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from collections import Counter from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import random '''' Handle Data: Open the dataset from CSV and split into test/train datasets. Similarity: Calculate the distance between two data instances. Neighbors: Locate k most similar data instances. Accuracy: Summarize the accuracy of predictions. Main: Tie it all together.''' number = int(input("number: ")) names = ['url_length', 'dots', 'url_numbers', 'dashes', 'class'] name = names[number] ''''Handle Data: Open the dataset from CSV and split into test/train datasets. The first thing we need to do is load our data file. The data is in CSV format without a header line or any quotes. We can open the file with the open function and read the data lines using the reader function in the csv module.''' df = pd.read_csv("malicious_vectors4.csv", header=1, names=names, error_bad_lines=False) df.head() print("Dataset Lenght:: ", len(df)) print("Dataset Shape:: ", df.shape) X1 = np.array(df.ix[:,0]) X2 = np.array(df.ix[:,number]) Y = np.array(df['class']) colors=[] for y in Y: if y == 'bad': colors.append('red') else: colors.append('green') plt.scatter(X1,X2,color=colors,marker='o', alpha=0.1) plt.xlabel('URL lenght') plt.ylabel(name) plt.savefig(name+'.png') plt.show()
a=input'Enter the number to check' while (a=<1000): def reverse(s): return s[::-1] def isPalindrome(s): rev = reverse(s) if (s == rev): return yes return no
s1 = input("Please enter a word:") s2 = input("Please enter another word:") for i in range(0, len(s1), 1): if i in range (0, len(s2), 1): print("its anagram")
# 1051 a = float(input()) if a>=0.00 and a<=2000: print("Isento") elif a>=2000.01 and a<= 3000: tax = (a-2000)*0.08 print("R$ %.2f"%tax) elif a>=3000.01 and a<=4500: tax=(1000*0.08)+((a-3000)*.18) print("R$ %.2f"%tax) elif a>=4500.01: tax=(1000*0.08)+(1500*.18)+((a-4500)*.28) print("R$ %.2f"%tax)
# 1040 value=input().split(" ") n1,n2,n3,n4 = value avg = ((2*float(n1)) + (3*float(n2)) + (4*float(n3)) + (1*float(n4))) / (2+3+4+1) print("Media: %.1f"%avg) if avg>=7: print("Aluno aprovado.") elif avg<5: print("Aluno reprovado.") else: print("Aluno em exame.") exam=float(input()) print("Nota do exame: %.1f"%exam) avg2 = (exam+avg)/2 if avg2>=5: print("Aluno aprovado.") else: print("Aluno reprovado.") print("Media final: %.1f"%avg2)
# 1044 value = input().split(" ") a,b = value if int(b)%int(a) == 0: print("Sao Multiplos") else: print("Nao sao Multiplos")
# 1035 value=input().split(" ") A,B,C,D = value if int(B)>int(C) and int(D)>int(A): if (int(C)+int(D))>(int(A)+int(B)): if int(C)>0 and int(D)>0: if int(A)%2==0: print("Valores aceitos") else: print("Valores nao aceitos") else: print("Valores nao aceitos") else: print("Valores nao aceitos") else: print("Valores nao aceitos")
# 1036 value = input().split(" ") a,b,c = value if float(a)!=0: if (float(b)**2 - (4*float(a)*float(c)))>=0: R1 = (-float(b)+(float(b)**2 - (4*float(a)*float(c)))**0.5)/(2*float(a)) R2 = (-float(b)-(float(b)**2 - (4*float(a)*float(c)))**0.5)/(2*float(a)) print("R1 = %.5f"%R1) print("R2 = %.5f"%R2) else: print("Impossivel calcular") else: print("Impossivel calcular")
# 1098 (5% wrong on i = 2) i = float(0) j = float(1) while i<=2: print(i,j) if i.is_integer() or j.is_integer(): print("I={:.0f} J={:.0f}".format(i,j)) print("I={:.0f} J={:.0f}".format(i,j+1)) print("I={:.0f} J={:.0f}".format(i,j+2)) else: print("I={} J={}".format(round(i,1),round(j,1))) print("I={} J={}".format(round(i,1),round(j+1,1))) print("I={} J={}".format(round(i,1),round(j+2,1))) i+=round(0.2,1) j+=round(0.2,1)
largest = None smallest = None while True: try: num = raw_input("Enter a number: ") if num == "done": break #print (num) num = int(num) if largest is None or largest < num: largest = num elif smallest is None or smallest > num: smallest = num except ValueError: print("Invalid input") print ("Maximum is", largest) print ("Minimum is", smallest) #Enter 7,2,bob,10,4 u will get desired output
#1-1 for i in range(5,0,-1): print('☆'*i) #1-2 for i in range(1,6): print(' '*(6-i)+'*'*(2*i-1)) #2 num=int(input('숫자 입력 : ')) while True: if num == 7 : print('{0} 입력! 종료!'.format(num)) break else : num=int(input('다시 입력 :')) #3 money=10000 charge=2000 song=0 while True: if money < 2000: break song += 1 money=money-charge print('노래 {0}곡 불렀습니다.'.format(song)) print('현재 {0}원 남았습니다.'.format(money)) print('잔액이 없습니다. 종료합니다.')
# append mode를 사용하여 파일끝에 추가 f = open('test2.txt','a',encoding='utf-8') data = '\n\nPython programming' f.write(data) f.close() # 읽기모드로 파일을 열어서 내용 출력(파일 수정 + 읽기) f = open('test2.txt','a',encoding='utf-8') data = '\nR programming\n' f.write(data) f = open('test2.txt','r',encoding='utf-8') print(f.read()) f.close()
# 클래스 상속 실습 # 슈퍼클래스: 사람 클래스 person <- 서브클래스 : 학생클래스 student class Person: def __init__(self,age,sex,name): self.age=age self.name=name self.sex=sex def greeting(self): print('안녕하세요') class Student(Person): # 학교, 학과, 학번, 공부하다(), 시험보다() def __init__(self,age,sex,name,school,grade,number): super().__init__(age,sex,name) self.school=school self.grade=grade self.number=number def study(self, name, grade): print("%s가 %s를 공부하고 있습니다." %(self.name, self.grade)) def test(self, name, grade): print("%s가 %s 과목을 시험치고 있습니다." %(self.name, self.grade)) person1 = Person(1,'F','이기쁨') student1=Student(20,'M','이기리','S','DS','123') person1.greeting()
#문자열의 기본 형식과 이해 crawling='Data crawling is fun.' parsing = 'Data parsing is also fun' print(type(crawling)) print(type(parsing)) ''' PI = 3.1414 r=10 result = ('반지름 ' + str(PI) + '인 원의 넓이는'+str(PI*r*r)) print(result) print('hello ' * 3) ''' #slicing : 문자의 일부분을 추출 print(crawling[0]) print(crawling[-1]) print(crawling[1:5]) print(crawling[:-1]) print(crawling[-1:]) print(crawling[:]) print(crawling[0:10])
#1~100까지의 정수중 3의배수 ''' n=1 sum=0 while n <= 100: if n%3 == 0: sum+=n n+=1 print('1부터 100까지의 합은 {0}'.format(sum)) ''' n=0 sum=0 while n <= 100: sum += n n+=3 print('1부터 100까지의 합은 {0}'.format(sum))
#생성된 file.txt파일은 빈 파일 # f=open('file1.txt','w') # f.close() # 경로 수정 : 디렉토리가 존재하지 않은 경로 # f=open('c:/python/file1.txt','w') # f.close() #f=open('file1.txt','w') #FileNotFoundError: [Errno 2] No such file or directory: 'c:/python/file1.txt' #상대경로 표현 f=open('../file.txt','w') f.close() #/python study/pythonstudy/16_fileI0/01_file_기본.py" 상위폴더에 저장
#리스트의 요소를 제거 : remove() pop() #remove(삭제하려는값) : 가장 첫번째 만나는 값을 삭제 n=[1,2,3,4,5,3,4,-1,-5,10] n.remove(3) print(n) cnt=n.count(3) print(cnt) #pop() : 맨 마지막 값을 삭제하지만 pop(index) : index위치의 값을 삭제후 반환 data=n.pop(4) print(n) print(data)
class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): ar = self.length * self.width print(ar) def perimeter(self): peri = 2 * (self.length + self.width) print(peri) class Square(Rectangle): def __init__(self, width): self.width = width self.length = width rect = Rectangle(2, 4) rect.area() #8 square = Square(8) square.area() #64 square.perimeter() #32
import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * # Subclass QMainWindow to customise your application's main buttons class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowTitle("My second try on PyQt5") label = QLabel("This is a PyQt5 buttons!") # The 'Qt' name space has a lot of attributes to customise # widgets. See: http://doc.qt.io/qt-5/qt.html label.setAlignment(Qt.AlignCenter) # Set the central widget of the buttons. Widget will expand # to take up all the space in the buttons by default self.setCentralWidget(label) toolbar = QToolBar("My main toolbar") self.addToolBar(toolbar) button_action = QAction("your buttom", self) button_action.setStatusTip("This is your button") button_action.triggered.connect(self.onMyToolBarButtonClick) toolbar.addAction(button_action) self.setStatusBar(QStatusBar(self)) def onMyToolBarButtonClick(self, s): print("click", s) dlg = QDialog(self) dlg.setWindowTitle("hello") dlg.exec_() app = QApplication(sys.argv) window = MainWindow() window.show() app.exec()
from validate_email import validate_email def validate_list_with_searchString(listitem, searchString): print("Length of list search: " + str(listitem.count(searchString))) print("Length of List: " + str(len(listitem))) if listitem.count(searchString) == len(listitem): print("list length is equal") return True else: print("Not equal") return False def check_validate_email(email): is_valid = validate_email(email) return is_valid
# add dic a = {1: 'a'} print("\na dictionary: {0}".format(a)) a[2] = 'b' print("add a[2] = b: {0}".format(a)) a['name'] = 'pooh' print("add a['name'] = 'pooh': {0}".format(a)) a[3] = [1, 2, 3] print("add a[3] = [1, 2, 3]: {0}".format(a)) # delete dictionary del a[1] print("\ndelete dictionary a[1]: {0}".format(a)) # keys a = {'name': 'pooh', 'phone':'01093829472', 'birth': '1125'} print("\nlist a: {0}".format(a)) print("key list of dictionary a: {0}".format(a.keys())) print("value list of dictionary a: {0}".format(a.values())) for k in a.keys(): print(k) # items of dictionary print("\nget items of dic a: \n{0}".format(a.items())) # get value of dictionary print("\nget value of name of dic_a: {0}".format(a.get('name'))) # delete all items of dictioniary a.clear() print("\ndelete all items: {0}".format(a))