text
stringlengths
37
1.41M
def finding_diff_bw_two_sets(*args): a,b=args print(f"finding difference a with b: {a.difference(b)}") print(f"finding difference b with a: {b.difference(a)}") if __name__ == "__main__": a,b = {1,2,3,4,5},{2,3,5,7,8} finding_diff_bw_two_sets(a,b) c,d = {'a',True,(1,2)},{'b',False,True,(1,2)} finding_diff_bw_two_sets(c,d) # not posible with sets of lists cuz list is mutable so not hashable # not posible with sets of dictionaries cuz dict is mutable so not hashable # posible once are numbers(int,float),set,tuple,True,bytes,bytearray e,f={bytes([1,2]),"hello","john"},{'hello','jessy',bytes([1,5])} finding_diff_bw_two_sets(e,f) # not posible # g,h = {1,([1,2],3),'joseph',"rana"},{"rana",({'a':'b'},4,5),6} # finding_diff_bw_two_sets(g,h) # not posible set of lists """because: Sets require their items to be hashable. Out of types predefined by Python only the immutable ones, such as strings, numbers, and tuples, are hashable. Mutable types, such as lists and dicts, are not hashable because a change of their contents would change the hash and break the lookup code. Since you're sorting the list anyway, just place the duplicate removal after the list is already sorted. This is easy to implement, doesn't increase algorithmic complexity of the operation, and doesn't require changing sublists to tuples """ #
from webtask import website def webdata(url): # sending url to website to create file with that website html code website(url) # filename from url dynamically filename = url.split(".")[1]+".html" # reading data from file with open(filename,'r') as filedata: # readline return data into list format to take actual data converting inti str form to split it freadlines=str(filedata.readlines()) # spliting the data fdata=freadlines.split(",") #taking empty set set_=set() # taking each value and appending into set for value in fdata: if value.isdigit(): set_.add(int(value)) # print(set_) list_=list(set_) print(f"before: {set_}\n\n") # print(len(list_)) newlist_=[] tuple_=() for value in list_: if value%2 == 0: # why dont we use discard here when i am using discard it is showing --> # returning RuntimeError: Set changed size during iteration list_.remove(value) if value%3 == 0: list_.pop() if value%4 == 0: newlist_.append(value) print(f"after: {tuple(newlist_)}") # print(len(newlist_)) # print(list_) # print(len(list_)) if __name__ == "__main__": url = "http://www.google.com" webdata(url) url = "http://www.amazon.com" webdata(url) url = "http://www.kfc.com" webdata(url) url = "http://www.colgate.com" webdata(url) url = 'http://www.gmail.com' webdata(url) url = 'http://stackoverflow.com' webdata(url)
"""7. Write a program to find the sum of squares of only the even numbers in the given list. (Hint: Use the methods filter, map, reduce.) Example: Input: list = [1, 2, 3, 4, 5, 6, 7, 8, 9] Output: Sum of squares of even numbers = 120""" from functools import reduce lst = [1,2,3,4,5,6,7,8,9] res = reduce(lambda a,b: a+b,list(filter(lambda x:x % 2 == 0,list(map(lambda x:x*x,lst))))) print(res)
import heapq import sys list1 = [] inputter = int(input("enter the number of elements to be inserted in list: ")) for i in range(inputter): inputter1 = int(input("enter elements: ")) list1.append(inputter1) while(1): z = int(input("1.push\n 2.pop\n 3.pushpop\n 4.replace\n 5.print\n")) if z == 1: g = int(input("enter element: ")) heapq.heappush(list1, g) if z == 2: temp = heapq.heappop(list1) print(str(temp)+" popped!!") if z == 3: h= int(input("enter element: ")) heapq.heapify(list1) temp1 = heapq.heappushpop(list1, h) print(str(temp1) + " popped!!") if z == 4: j = int(input("enter element to be pushed: ")) heapq.heapify(list1) temp2 = heapq.heapreplace(list1, j) print(str(temp2) + " popped!!") if z == 5: heapq.heapify(list1) print(list1)
#Diceware roller import random #choose a number of die number_of_die = int(input("How many die do you wish to roll?: ")) #chose the number of sides number_of_sides = int(input("How many sides should the die have?: ")) def dice(n): print (random.randrange(1,n)) for i in range (0, number_of_die): dice(number_of_sides)
#Reading and writing to file my_file = open('data.txt','r') file_content = my_file.read() my_file.close() print(file_content) username = input('Enter your name: ') my_file_writing = open('data.txt','w') my_file_writing.write(username) my_file_writing.close()
import time from multiprocessing import Process #When you need processes to run at the same time (not for waiting) def ask_user(): start = time.time() user_input = input('Enter your name: ') greet = f'Hello, {user_input}' print(greet) print(f'ask_user, {time.time() - start}') def complex_calc(): start = time.time() print('Started calculating...') [x**2 for x in range(10000000)] print(f'complex_calc, {time.time() - start}') start = time.time() ask_user() complex_calc() #Processes if __name__ == "__main__": process = Process(target=complex_calc()) process2=Process(target=complex_calc()) process.start() process2.start() start = time.time() ask_user() process.join() process2.join() print(f'Single thread total: , {time.time() - start}')
import random # import random is a simple library that implements the random number generator behavior # Please read into the variables below the correct numbers. Use try and except to catch error. # a simple example would be: # hero_hp = int(input("how many hp does the hero have?")) while True: try: hero_hp = input("what is the life of the hero?") hero_hp = int(hero_hp) break except: print("give a proper hero number") while True: try: dragon_hp = input ("what is the life of the dragon?") dragon_hp= int(dragon_hp) break except: print("give a proper dragon number") while True: try: hero_max_dmg = input("what is the hero's max damage?") hero_max_dmg= int(hero_max_dmg) break except: print("give a proper hero number for damage") try: dragon_max_dmg = input("what is the dragon's max damage?") dragon_max_dmg= int(dragon_max_dmg) break except: print("give a proper number for dragon max damage") print("The dragon with", dragon_hp, "hp attacks out hero with", hero_hp, "hp") # add a While for an infinite block while True: # here goes the while: dragon_attack = random.randint(1, dragon_max_dmg) # here you need to update the hero hp, you need to subtract the damage that the dragon did # add code on this line hero_hp=hero_hp-dragon_attack print("The dragon does", dragon_attack, "damage and the hero has", hero_hp, "hp left") # add an if condition to check if the hero was killed by the dragon if hero_hp<1: print("Unfortunately the dragon killed our hero. RIP sir Bravealot") break hero_attack = random.randint(1, hero_max_dmg) # here you need to update the dragon hp, you need to subtract the damage that the hero did # add code on this line dragon_hp = dragon_hp - hero_attack print("The hero does", hero_attack, "damage and the dragon has", dragon_hp, "hp left") # add an if condition to check if the dragon was killed by the hero if dragon_hp<1: print("Our valiant hero has slain the dragon!") break input("Round over. Press any key")
lugares_favoritos = {'Davy': ['Caldas Novas', 'Cinema'], 'Duda': ['Volei', 'Safari'], 'Jose': 'Igreja'} for name, lugar_favorito in lugares_favoritos.items(): print('Os lugares favoritos do ' + name + ' são: {}'.format(lugar_favorito.title()))
prompt = 'Quais sabores o senhor(a) deseja: \n' sabores = '' while sabores != 'quit': print(prompt) sabores = input() print('O sabor ' + sabores.title() + ' foi adicionado com sucesso!!!\n')
from practica3 import * def seleccionador (argument): if argument == 1: while True: try: entrada = input('Introduce una matriz de la forma [[1,2],[2,3]]\n') print(mas_repetido(entrada)) break except: print('Error, se debe ingresar una matriz bidimensional\n') elif argument == 2: while True: try: entrada = input('Introduce una cadena\n') print(condensa(str(entrada))) break except: print('Error, Las cadenas deben estar entre comillas\n') elif argument == 3: entrada = -1 correcto= False while not correcto: try: entrada = int(input('Introduce un numero entero mayor o igual a cero\n')) if entrada >= 0: print(triangulo_pascal(entrada)) correcto = True except: print('Error, se debe ingresar un numero mayor o igual a cero') #print(triangulo_pascal(entrada)) elif argument == 4: while True: try: entrada = input('Introduce una cadena\n') print(subcadenas(str(entrada))) break except: print('Error, Las cadenas deben estar entre comillas\n') elif argument == 0: pass else: print('No es una opcion') def pedirNumeroEntero(): correcto= False num = 0 while not correcto: try: num = int(input("Introduce un numero entero del menu: ")) correcto = True except: print('Error, introduce un numero entero\n') return num def main(): print('Por favor, introduce el valor numerico que desees:\n1.mas_repetido(matriz)\n2.condensa(cadena)\n3.triangulo_pascal(niveles)\n4.subcadenas(cadena)\nIntroduce 0 para salir del programa') seleccionado = -1 while seleccionado != 0: seleccionado = pedirNumeroEntero() seleccionador(seleccionado) print("Adios") if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def indexreshape(n, m): """ separates n indexes in m equal disjoint parts, trims edges equally returns tuple ((1_start_idx, 1_end_idx),...,(m_start_idx, m_end_idx)) """ if n < m: raise ValueError('m must be lower or equal to n') delta = (n % m) // 2 end = n - (n % m) step = end // m r = tuple((i + delta, i + delta + step - 1) for i in range(0, end, step)) return r if __name__ == '__main__': try: length = int(input("enter N = ")) parts = int(input("enter number of parts M = ")) print(indexreshape(length, parts)) except ValueError or TypeError as e: print('Error: incorrect input: %s' % str(e)) exit()
output_list = [] while(True): input_str = input("please input") if(input_str=="0:00"): break split_list = input_str.split(":") single_h = float(360/12)*int(split_list[0]) single_m = 360/60*int(split_list[1]) n1 = abs(single_h-single_m) n2 = 360-single_h+single_m if(n1>n2): print(n2) else: print(n1)
import tkinter as tk from tkinter import * import random import time import numpy as np import keyboard from pynput.mouse import Listener import pyautogui import cv2 #this demo code saves a template which student needs to replicate... #NOTE: here I am only taking a screenshot ONCE, when the program starts, so if the teacher wants to makes any updates to the drawing area, #after opening the option, then you would need to take screenshots again and again after any specified time... #First the teacher would select and 'anchor image; (a fixed part of the screen) so we can have a reference.... #starting dimension of the boxes w= 450 h = 200 x = 500 y = 200 #variables to see the progress of the program... close1 = False close2 = False x1=0 y1 = 0 #two windows variables.. root = None anch = None X = 0 Y = 0 drawing_pt = False image = None posx=0 posy=0 H=0 W=0 #this function creates an anchor window..... with a button... #you can resize this transparent window over any area and then press the (DONE) button on top of it #it will save the underlying area as an anchor iamge.... def create_anchor_window(): global anch1 anch1 = tk.Tk() # root.attributes("-transparentcolor", "white") # root.overrideredirect(1) anch1.title("Anchor image:") anch1.attributes('-alpha', 0.4) anch1.resizable(True, True) anch1.geometry('%dx%d+%d+%d' % (w, h, x, y)) print(anch1.geometry()) button = Button(anch1,text = "DONE",command = close_anchor_window) button.pack() # CANVAS = tk.Canvas(root, width=50, height=50) # CANVAS.pack() # img = PhotoImage(file="rectangle.png") # CANVAS.create_image(25,25, anchor=CENTER, image=img) anch1.call('wm', 'attributes', '.', '-topmost', '1') anch1.mainloop() #this function runs when an anchor image is selected and pressed the button def close_anchor_window(): global X,Y,close1,anch1 #saving the image as anchor.png anch1.update() geometry = anch1.geometry() #X,Y are the cordinates of the anchor image... W = int(geometry.split("x")[0]) H = int((geometry.split("x")[1]).split("+")[0]) X =int( geometry.split("+")[1]) Y = int(geometry.split("+")[2])+35 print("Geo string: ",geometry) print("Geometry of anchor:",X,Y,W,H) anchor = image[Y:Y + H, X:X + W] anch1.destroy() print("X,Y: ",X,Y) cv2.imshow("Anchor: ", anchor) cv2.waitKey(0) cv2.imwrite("match_template\\anchor.png", anchor) close1 = True print("Exiting....") #this function creates the main template selection window... def create_window(): global root root = tk.Tk() # root.attributes("-transparentcolor", "white") # root.overrideredirect(1) root.title("Template area:") root.attributes('-alpha', 0.4) root.resizable(True, True) root.geometry('%dx%d+%d+%d' % (w, h, x, y)) print(root.geometry()) button = Button(root,text = "DONE",command = close_window) button.pack() # CANVAS = tk.Canvas(root, width=50, height=50) # CANVAS.pack() # img = PhotoImage(file="rectangle.png") # CANVAS.create_image(25,25, anchor=CENTER, image=img) root.call('wm', 'attributes', '.', '-topmost', '1') root.mainloop() def close_window(): global posx,posy,close2 #when this is called.... # the template image is shown in a window... file = open("match_template\\match_info.txt", "w+") geometry = root.geometry() W = int(geometry.split("x")[0]) H = int((geometry.split("x")[1]).split("+")[0]) posx =int( geometry.split("+")[1]) posy = int(geometry.split("+")[2])+35 print("Geometry:",posx,posy,W,H) template = image[posy:posy + H, posx:posx + W] root.destroy() cv2.imshow("Template: ", template) cv2.waitKey(0) #template image is saved. cv2.imwrite("match_template\\template.png", template) #coordinates of the template image W.R.T the anchor image's origin.. posx = posx - X posy = posy - Y print("Relative Geometry:", posx, posy, W, H) #written in the file as : Match-box, (X,Y relative to anchor image;s position in the screen), width and height,... file.write("Match-box," + str(posx) + "," + str(posy) + "," + str(W) + "," + str(H) + "\n") file.close() close2 = True print("Exiting....") #maing code.. #waitin for 2 secs to let the user switch to his screen. time.sleep(2) #taking a screen shot... image = pyautogui.screenshot() image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) #asking for anchor image. create_anchor_window() while(1): #once ANCHOr image is done and YOU PRESS 'M' afterwards, # a new window gets launched for setting the template area... if keyboard.is_pressed('m') and close1: # Open match window.. image = pyautogui.screenshot() image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) print('Opening window....') time.sleep(0.5) create_window() if close2: #finishing the program. print("program ended.s") break
from cv2 import * from imutils import * #resizing the image img=imread("sample2.jpg") resizeImg=resize(img, width=200) #resizes the given image imwrite("resizedimage.jpg", resizeImg) #creates the above image in the folder imshow("resizedimage.jpg", resizeImg) #displays the mentioned image on the screen when we run the program #applying GaussianBlur gbimg=GaussianBlur(img,(21,21),0) #function: cv2.GaussianBlur(sourceimage, (kernel), borderType) imwrite("GaussianBlurImage.jpg", gbimg) imshow("GaussianBlurImage.jpg", gbimg) #thresholding: thresholdimg=threshold(gbimg, 200, 255, THRESH_BINARY)[1] #the function returns a tuple of two values and we're choosing the [1] value of the tuple imwrite("thresholdedImage.jpg", thresholdimg) imshow("thresholdedImage.jpg", thresholdimg)
def open_file(file_name): try: return open(file_name, "r") except FileNotFoundError: return None def read_matrix(file_object): matrix = [] for line in file_object: line = line.strip().split() matrix.append([int(element) for element in line]) return matrix def row_sum_same(matrix): established_sum = sum(matrix[0]) total_row_sum = 0 for element in matrix: if sum(element) != established_sum: total_row_sum = 0 break else: total_row_sum = established_sum return total_row_sum def col_sum_same(matrix): established_sum = 0 total_col_sum = 0 for i in range(0,len(matrix)): established_sum += matrix[0][i] for x in range(0, len(matrix)): tmp_sum = 0 for j in range(0, len(matrix)): tmp_sum += matrix[j][x] if tmp_sum != established_sum: total_col_sum = 0 break else: total_col_sum = established_sum return total_col_sum def print_matrix(matrix): for list_element in matrix: for element in list_element: print("{}\t".format(element), end="") print() def determine_if_same(row_sum, col_sum): if row_sum == col_sum: print("Same sums") else: print("Not same sums") def main(): filename = input("File name: ") read_file = open_file(filename) if read_file == None: print("File not found") else: int_matrix = read_matrix(read_file) row_sum = row_sum_same(int_matrix) col_sum = col_sum_same(int_matrix) print_matrix(int_matrix) determine_if_same(row_sum, col_sum) main()
#This program accepts two integers from user input and compares the to see which one is greater int_1 = int(input("Enter the first number: ")) int_2 = int(input("Enter the second number: ")) if int_1 > int_2: print(int_1,"is greater than",int_2) elif int_2 > int_1: print(int_2,"is greater than",int_1) else: print("The numbers are equal")
""" This program allows the user to input a number that represents the length of a list, input that many elements, and then enter one value to determine if it exists within the list """ def populate_list(int_object): new_list = [] while len(new_list) != int_object: list_element = input("Enter an element to put into the list: ") new_list.append(list_element) return new_list def find_element_in_list(list_object, target_string): if target_string in list_object: return True else: return False def main_func(): size_num = int(input("Enter the size of the list: ")) target_string = input("Enter target value to find: ") value_list = populate_list(size_num) is_in_list = find_element_in_list(value_list, target_string) print(value_list) if is_in_list: print("{} is in the list".format(target_string)) else: print("{} is not in the list".format(target_string)) main_func()
def remove_evens(list_object): for element in reversed(list_object): if element % 2 == 0: list_object.remove(element) return list_object def remove_evens2(list_object): new_list = [] for element in list_object: if element % 2 != 0: new_list.append(element) return new_list # Main starts here a_list = [1,2,2,3,4,5] print(a_list) remove_evens(a_list) print(a_list) b_list = [1,2,3,4,4,5,6,7,8,9,10] c_list = remove_evens2(b_list) print(b_list) print(c_list)
#This program takes in two numbers from user input and prints all integers between them lower_int = int(input("Enter the lower number: ")) higher_int = int(input("Enter the higher number: ")) if lower_int >= higher_int: print("The lower number must be lower than the higher one!") else: for i in range(lower_int,higher_int + 1): print(i)
""" This program takes two words from user input and checks if they are anagrams of each other """ def main_func(): words_list = input("Enter two words seperated with a space: ").split() word1 = words_list[0] word2 = words_list[1] word1_sorted = sort_string(word1) word2_sorted = sort_string(word2) anagram_check(word1_sorted,word2_sorted) def sort_string(string_object): return sorted(string_object) def anagram_check(string_1,string_2): if string_1 == string_2: print("The two words are anagrams.") else: print("The two words are not anagrams") main_func()
""" This program reads documents from a file into a list, populates a dictionary with the words from the list of documents as the keys and the set of document numbers as the value for each word. The program then enables the user to search for specific words and find out in which documents they occur, as well as enabling the user to print out the contents of a document associated with a given number. """ import string def read_file(string_object): """Read through a given file""" try: return open(string_object,"r") except FileNotFoundError: return None def get_documents(file_object): """Get documents from a given file stream, returns a list of document strings""" document_list = [] document_string = "" for line in file_object: line = line.strip() if line == "<NEW DOCUMENT>": document_list.append(document_string) document_string = "" else: document_string += (line + " \n") document_list.append(document_string) return document_list def populate_word_list(list_object): """Turns a list of sentances into a cleaned list of words""" word_list = [] for element in list_object: sentance = "".join([char for char in element if char not in string.punctuation]) #Removes punctuation from a sentance in the list word_list.append(sentance.strip().lower().split()) return word_list def populate_word_dictionary(list_object): """Initializes a dictionary with the keys being words from a list of words, and the values being the number of the documents in which that word occurs""" new_dictionary = {} for element in list_object: for word in element: if word not in new_dictionary: new_dictionary[word] = set() else: pass for word in new_dictionary: for i in range(0,len(list_object)): if word in list_object[i]: new_dictionary[word].add(i) return new_dictionary def get_search_results(list_object, dictionary_object): """Searches through a given word dictionary and returns a set which is the intersection of the sets of document numbers belonging to the words being searched for, returns an empty set if a word does not exist in the dictionary""" tmp_doc_list = [] for element in list_object: try: tmp_doc_list.append(dictionary_object[element]) except KeyError: tmp_doc_list.append(set()) intersect_set = tmp_doc_list[0].intersection(*tmp_doc_list) return intersect_set def print_menu(): """Prints the operations menu.""" print("What would you like to do?") print("1. Search Documents") print("2. Print Document") print("3. Quit Program") def menu_loop(list_object, dictionary_object): """Performs the necessary functions of the program and calls other functions to do so. Goes on until the user enters a choice that exits the program""" print_menu() choice_input = input("> ") while choice_input == "1" or choice_input == "2": if choice_input == "1": word_input_list = input("Enter search words: ").lower().split() search_result = get_search_results(word_input_list, dictionary_object) if search_result == set(): print("No match.\n") else: print("Documents that fit search:",*search_result,"\n") elif choice_input == "2": document_number_input = int(input("Enter document number: ")) try: doc_result = list_object[document_number_input] print("Document #{}".format(document_number_input)) print(doc_result) except IndexError: print("No match.\n") print_menu() choice_input = input("> ") else: print("Exiting program.") def main_func(): """Main function""" file_name = input("Document collection: ") open_file = read_file(file_name) if open_file == None: print("Documents not found.") else: print() document_list = get_documents(open_file) word_list = populate_word_list(document_list) word_dictionary = populate_word_dictionary(word_list) menu_loop(document_list, word_dictionary) open_file.close() main_func()
def createPrime(): n = 10**6 sieve = [True] * n for x in range(2, int(n**0.5)+1): if sieve[x]: for y in range(2*x,n,x): sieve[y] = False return sieve def eulerfunction(a,b,prime): n = 1 while True: if not prime[n**2+a*n+b]: return a*b, n n += 1 def test(a,b,prime): n = 1 while True: if not prime[n**2+a*n+b]: return a*b, n n += 1 def main(): large = 0 sumnum = 0 prime = createPrime() for x in range(-999,999): for y in range(-999,999): tmp, tmpsum = eulerfunction(x,y,prime) if tmpsum > sumnum: large = tmp sumnum = tmpsum print large print sumnum prime = createPrime() num, b = test(-79,1601,prime) print num print b main()
import time def main(): start = time.time() n = 2**1000 sum = 0 while n > 0: sum += (n%10) n = n/10 print sum print time.time() - start if __name__ == "__main__": main()
"""Homework 2 for CSE-41273""" # Adam Vickter # Function 1 def combine_lists(one, two): """Take 2 lists as input and return a new list consisting of the elements of the first list followed by the elements of the second list.""" combine_lists = one + two return(combine_lists) # Function 2 def last_n_elements(sequence, n): """Given a sequence and a number n, return the last n elements of the sequence.""" Apple = sequence[-n:] return Apple # Function 3 def last_n_reversed(sequence, n): """Given a sequence and a number n, return the last n elements of the sequence in reversed order.""" return sequence[-n:][::-1] # Function 4 nList = [1,4,7,2,9] def power_list(numbers): """Given a list of numbers, return a new list where each element is the corresponding element of the list to the power of its list index.""" numbers2 = [] for idx, val in enumerate(numbers): number2 = val**idx numbers2.append(number2) return(numbers2) # Function 5 def rotate_list(some_list): """Take a list as input and remove the first item from the list and add it to the end of the list. Return the item moved""" first = some_list.pop(0) some_list.append(first) return first # Function 6 def get_vowel_names(names): """Return a list containing all names given that start with a vowel.""" new_list = [] for name in names: if name[0].lower() in 'aeiou': new_list.append(name) return(new_list)
import argparse import random base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main(): parser = argparse.ArgumentParser() parser.add_argument("mode", help="Either 'encrypt' or 'decrypt' the given fiel") parser.add_argument("text", help="the input file to be encrypted") parser.add_argument("algorithm", help="caesar/vigenere") parser.add_argument("key", help="The key for the corresponded algorithm") args = parser.parse_args() algo_map = { 'caesar': Caesar, 'vigenere': Vigenere, 'wolseley': Wolseley, 'zigzag' : ZigZagTranspositionCipher } cipher = algo_map[args.algorithm]() print(getattr(cipher, args.mode)(args.text, args.key)) class SubstitutionCipher: base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __init__(self): self.permutation = SubstitutionCipher.base def encrypt(self, c): if c in base: return self.permutation[SubstitutionCipher.base.index(c)] else: return c def decrypt(self, c): if c in self.permutation: return SubstitutionCipher.base[self.permutation.index(c)] else: return c def rotateLeft(string, offset): return string[offset:] + string[:offset] def rotateRight(string, offset): return string[len(string) - offset:] + string[:len(string) - offset] class Caesar(SubstitutionCipher): def __init__(self): self.permutation = SubstitutionCipher.rotateLeft(SubstitutionCipher.base, 3) def encrypt(self, text, key): output = "" for c in text: output += SubstitutionCipher.encrypt(self, c) return output def decrypt(self, text, key): output = "" for c in text: output += SubstitutionCipher.decrypt(self, c) return output class Vigenere(SubstitutionCipher): def encrypt(self, text, key): output = "" index = 0 for c in text: rotate_amount = SubstitutionCipher.base.index(key[index]) index = (index + 1) % len(key) self.permutation = SubstitutionCipher.rotateLeft(SubstitutionCipher.base, rotate_amount) output += SubstitutionCipher.encrypt(self, c) return output def decrypt(self, text, key): output = "" index = 0 for c in text: rotate_amount = SubstitutionCipher.base.index(key[index]) index = (index + 1) % len(key) self.permutation = SubstitutionCipher.rotateLeft(SubstitutionCipher.base, rotate_amount) output += SubstitutionCipher.decrypt(self, c) return output class Wolseley(SubstitutionCipher): def setup_permutation(key): grid = [] rest = SubstitutionCipher.base for c in key: grid.append(c) rest = rest.replace(c, "") if c == 'I' or c == 'J': rest = rest.replace("I", "") rest = rest.replace("J", "") grid += rest permutation = "" for alpha in SubstitutionCipher.base: if alpha == "I" or alpha == "J": if "I" in grid: permutation += (grid[24 - grid.index("I")]) else: permutation += (grid[24 - grid.index("J")]) else: permutation += (grid[24 - grid.index(alpha)]) return permutation def encrypt(self, text, key): self.permutation = Wolseley.setup_permutation(key) output = "" for c in text: output += SubstitutionCipher.encrypt(self, c) return output def decrypt(self, text, key): self.permutation = Wolseley.setup_permutation(key) output = "" for c in text: output += SubstitutionCipher.decrypt(self, c) return output class ZigZagTranspositionCipher: def setup_grid(text, length): grid = [text[i:min(i+length, len(text))] for i in range(0, len(text), length)] if len(grid[-1]) != length: for i in range(length - len(grid[-1])): grid[-1] += random.choice(SubstitutionCipher.base) reverse = False for i in range(len(grid)): if reverse: grid[i] = grid[i][::-1] reverse = not reverse return grid def encrypt(self, text, key): length = int(key) grid = ZigZagTranspositionCipher.setup_grid(text, length) index = 0 output = "" for i in range(length): for s in grid: output += s[i] return output def decrypt(self, text, key): length = len(text) // int(key) grid = [text[i:min(i+length, len(text))] for i in range(0, len(text), length)] index = 0 output = "" reverse = False for i in range(length): if reverse: for j in range(len(grid) - 1, -1, -1): output += grid[j][i] else: for j in range(len(grid)): output += grid[j][i] reverse = not reverse return output if __name__ == "__main__": main()
class Node(object): def __init__(self, value): self.left = None self.right = None self.value = value self.height = 1 def getBalance(self): leftHeight = self.left.height if self.left else 0 rightHeight = self.right.height if self.right else 0 return leftHeight - rightHeight def rightRotate(self): left = self.left self.left = left.right left.right = self self.height = self.getHeight() left.height = left.getHeight() return left def leftRotate(self): right = self.right self.right = right.left right.left = self self.height = self.getHeight() right.height = self.getHeight() return right def getHeight(self): return max( self.left.height if self.left else 0, self.right.height if self.right else 0 ) + 1 def rebalance(self): balance = self.getBalance() if balance > 1: childBalance = self.left.getBalance() if childBalance < 0: self.left = self.left.leftRotate() return self.rightRotate() elif balance < -1: childBalance = self.right.getBalance() if childBalance > 0: self.right = self.right.rightRotate() return self.leftRotate() return self def getLeftMost(self): left = self while left.left is not None: left = left.left return left def insert(self, value): if self.value > value: if self.left: self.left = self.left.insert(value) else: self.left = Node(value) self.height = max(self.height, self.left.height + 1) else: if self.right: self.right = self.right.insert(value) else: self.right = Node(value) self.height = max(self.height, self.right.height + 1) return self.rebalance() def delete(self, value): if self.value > value: if self.left: self.left = self.left.delete(value) elif self.value < value: if self.right: self.right = self.right.delete(value) else: if not self.left and self.right: return self.right elif not self.right and self.left: return self.right elif not self.left and not self.right: return None else: leftMost = self.right.getLeftMost() if leftMost: self.value, leftMost.value = leftMost.value, self.value self.right = self.right.delete(value) self.height = self.getHeight() print('before rebalance') self.print() print('----------------') newRoot = self.rebalance() print('after rebalance') newRoot.print() print('-----------------') return newRoot def print(self): print("node level %s: %s" % (self.height, self.value)) if self.left: print("left nodes:") self.left.print() if self.right: print("right nodes:") self.right.print() class BST(object): def __init__(self, values): self.root = None self.insert(values) def insert(self, values): for value in values: if not self.root: self.root = Node(value) else: self.root = self.root.insert(value) def delete(self, values): for value in values: if not self.root: return else: self.root = self.root.delete(value) def print(self): if self.root: self.root.print() if __name__ == "__main__": bst = BST([1,2,3,4,5,6,7,8,9]) bst.print() print('_______delete________') bst.delete([3, 5, 7]) bst.print()
class Node(object): def __init__(self, value, next = None): self.value = value self.next = next def __str__(self): if self.next: return '%s -> %s' % (self.value, self.next) else: return str(self.value) def reverse(head): if head is None or head.next is None: return head next = head.next head.next = None while next: nextNext = next.next next.next = head head = next next = nextNext return head head = Node(1, Node(2, Node(3, Node(4)))) newHead = reverse(head) print(newHead)
def expendStr(arr): alist = ['|', '|'] alist[1:-1] = [item for item in '|'.join(arr)] return alist def manacher(arr): if not arr: return 0 expendArr = expendStr(arr) length = len(expendArr) lps = [0] * length lps[1] = 1 for i in range(2, len(expendArr)): lps[i] = max(0, min(lps[i-1] - 1, lps[i-2])) print("lps at %s: %s" % (i, lps[i])) while i - lps[i] > 0 and i + lps[i] + 1 < length and expendArr[i-lps[i]-1] == expendArr[i+lps[i]+1]: lps[i] += 1 print("lps at %s after expension: %s" % (i, lps[i])) return expendArr, lps if __name__ == "__main__": expendedArr, palindom = manacher("babcbabcbaccba") print(expendedArr) print(palindom)
import math import random import vector ''' this program randomly creates vectors, tells you what the vectors are then shows how simple vector calculations work. The random vectors produced are non integer to ensure the program works for all possible inputs. It also tests the following identities and show if they hold true or not: v1 x v2 = - v2 x v1 v1 ×(v2 + v3) = (v1 x v2) + (v1 × v3) v1 ×(v2 × v3) = (v1 · v3)v2 − (v1 · v2)v3 ''' def identity_1(v1, v2): #v1 x v2 = - v2 x v1 v3 = vector.cross(v1, v2) #lhs v4 = vector.cross(v2, v1) v4 = vector.scalar_mult(v4, -1) #rhs if v3[0]==v4[0] and v3[1]==v4[1] and v3[2]==v4[2]: print('v1 x v2 = - v2 x v1') else: print('v1 x v2 does not equal - v2 x v1') def identity_2(v1, v2, v3): #v1 ×(v2 + v3) = (v1 × v2) + (v1 × v3) v4 = vector.sum(v2, v3) v4 = vector.cross(v1, v4) #lhs v4 = [round(elm, 10) for elm in v4] #elements need to be rounded to be exactly equal v5 = vector.cross(v1,v2) v6 = vector.cross(v1, v3) v7 = vector.sum(v5, v6) v7 = [round(elm, 10) for elm in v7] #rhs if v4[0]==v7[0] and v4[1]==v7[1] and v4[2]==v7[2]: print('v1 ×(v2 + v3) = (v1 x v2) + (v1 × v3)') else: print('v1 ×(v2 + v3) does not equal (v1 × v2) + (v1 × v3)') def identity_3(v1, v2, v3): #v1 ×(v2 × v3) = (v1 · v3)v2 − (v1 · v2)v3 v4 = vector.cross(v2, v3) v4 = vector.cross(v1, v4) #lhs v4 = [round(elm, 10) for elm in v4] #lhs rounded s5 = vector.dot(v1, v3) s6 = vector.dot(v1, v2) s6 = -s6 v5 = vector.scalar_mult(v2, s5) v6 = vector.scalar_mult(v3, s6) v7 = vector.sum(v5, v6) #rhs v7 = [round(elm, 10) for elm in v7] #rhs rounded if v4[0]==v7[0] and v4[1]==v7[1] and v4[2]==v7[2]: print('v1 ×(v2 × v3) = (v1 · v3)v2 − (v1 · v2)v3') else: print('v1 ×(v2 × v3) does not equal (v1 · v3)v2 − (v1 · v2)v3') # Main method: def main(): # Create two random vectors v1 = [random.random(), random.random(), random.random()] v2 = [random.random(), random.random(), random.random()] v3 = [random.random(), random.random(), random.random()] #line break in output screen, clearer to read print() # Print out the vectors to terminal window print("v1 = ", v1) print("v2 = ", v2) print("v3 = ", v3) #line break in output screen, clearer to read print() #print basic vector manipulations #vector sum, scalar product and vector (cross) product print("v1 + v2 =", vector.sum(v1, v2)) print('v1 · v2 =', vector.dot(v1, v2)) print('v1 x v2 =', vector.cross(v1, v2)) #line break in output screen, clearer to read print() #testing if the vector identites hold identity_1(v1, v2) identity_2(v1, v2, v3) identity_3(v1, v2, v3) # Execute main method main()
coins = [200,100,50,20,10,5,2,1] def print_coins(change): if change == 0: print "Nothing" else: for (n, c) in change: if n != 0: print "{}*{} + ".format(n,c), total = sum(map(lambda (n, c): n*c, change)) print " = " + str(total) def make_change(n, usable_coins, coins_used): if len(usable_coins) == 1 : coins_used.append((n, 1)) print_coins(coins_used) return 1 coin = usable_coins.pop(0) possibilities = 0 for number in range(1, n/coin + 1): used = list(coins_used) used.append((number, coin)) possibilities += make_change(n - number*coin, list(usable_coins), used) possibilities += make_change(n, list(usable_coins), coins_used) return possibilities print make_change(200, coins, list([]))
from PIL import Image userInputImage = input("Choose an image to alter .jpg.") im = Image.open(userInputImage) data = list(im.getdata()) #gets the the RGB values of each pixel def addTuples(tuple): return tuple[0] + tuple[1] + tuple[2] red = (140, 35, 24) blue = (94, 140, 106) green = (136, 166, 94) yellow = (242, 196, 98) palette1=[red, blue, green, yellow] dark_red = (61, 0, 12) passion_fruit = (169, 10, 42) sky_blue = (89, 183, 167) off_white = (251, 254, 211) palette2 = [dark_red, passion_fruit, sky_blue, off_white] teal = (1, 9, 76) light_green = (177, 212, 154) yellow = (227, 198, 98) orange = (250, 149, 35) purple = (62, 30, 33) palette3 = [teal, light_green, yellow, orange, purple] newpixels = [] #list of RGB values user_input= input("palette1 or palette2 or palette3") #user chooses palette colors def filter(palette): #what comes up when a certain palette is chosen for i in data: sum = addTuples(i) if sum < 182: #the 182= the intensity of certain part of picture newpixels.append(palette[0]) #if intensity = less than 182 = color number "0" on list elif sum <364: newpixels.append(palette[1]) elif sum <546: newpixels.append(palette[2]) elif sum >= 546: newpixels.append(palette[3]) if user_input == "palette1": filter(palette1) if user_input == "palette2": filter(palette2) if user_input == "palette3": filter(palette3) new_image = Image.new(im.mode, im.size) new_image.putdata(newpixels) new_image.save("output.jpg", "jpeg") #thank you Brad M. for having such a helpful Intro to PIL blog <3 <3
fname = input("Enter file name: ") try: fh = open(fname) except: quit('File does not exist!') lst = list() for line in fh: words = line.rstrip().split() for word in words: if word not in lst: lst.append(word) lst.sort() print(lst)
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # # define GPIO pins with variables a_pin and b_pin # a_pin = 18 # b_pin = 23 # create discharge function for reading capacitor data def discharge(a_pin,b_pin): GPIO.setup(a_pin, GPIO.IN) GPIO.setup(b_pin, GPIO.OUT) GPIO.output(b_pin, False) time.sleep(0.005) # create time function for capturing analog count value def charge_time(a_pin,b_pin): GPIO.setup(b_pin, GPIO.IN) GPIO.setup(a_pin, GPIO.OUT) count = 0 GPIO.output(a_pin, True) while not GPIO.input(b_pin): count = count + 1 return count # create analog read function for reading charging and discharging data def analog_read(pin1,pin2): discharge(pin1,pin2) return charge_time(pin1,pin2) # provide a loop to display analog data count value on the screen # while True: # print(analog_read()) # time.sleep(1)
import psycopg2 as pg choice = int(input("Enter Your choice:\n" "1. Find\n" "2. insert\n" "3. delete\n" "4. Quit\n")) def Conneciton(): connection = "" # use postgres try: connection = pg.connect(user="postgres", password = "sotherny", port="5432", host ="127.0.0.1", database = "DataStructure") # cursor = connection.cursor() # print("connected") return connection except (Exception) as e: print(e) con = Conneciton() cursor = con.cursor() while choice!=0: if choice == 1: choice_find = input("Enter choice you want to find star:\n" "a. by star's id\n" "b. by star's name\n") if choice_find == 'a': id = input("Enter star's id:") cursor.execute(f"select star_name from star where id = '{id}'") con.commit() result = cursor.fetchone() print(result) if choice_find == 'b': name = input("Enter star's name:") cursor.execute(f"select star_name from star where name = '{name}'") con.commit() result = cursor.fetchone() print(result) # continue elif choice==2: id = input("Enter star's id:") star_name = input("Enter star's name:") cursor.execute(f"insert into star values('{id}','{star_name}')") con.commit() print("inserted successfully") elif choice==3: id = input("Enter star's id:") cursor.execute(f"delete from star where id = '{id}'") con.commit() print("deleted successfully") elif choice == 4: if (con): cursor.close() con.close print("connection is closed") break print("____________________________") choice = int(input("Enter Your choice:\n" "1. Find\n" "2. insert\n" "3. delete\n" "4. Quit\n")) # finally: # if(connection): # cursor.close() # connection.close # print("connection is closed") # li = [x for x in range(2)] # print(li)
import collections dic = dict() n = int(input()) for i in range(n): survey = input().split(" ") dic[survey[0]] = survey[1] listOfElems = list(dic.values()) # Create a dictionary of elements & their frequency count dictOfElems = dict(collections.Counter(listOfElems)) # Remove elements from dictionary whose value is 1, i.e. non duplicate items greater = 0 greater_key = "" for key, value in dictOfElems.items(): if value > greater: greater = value greater_key = key if value == greater_key: greater_key = "no most like" print(greater_key) print(listOfElems.count("football"))
class Node(object): def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right def traverse_pre_order_recursive(root, action=print): if root: action(root.data, end=" ") traverse_pre_order_recursive(root.left, action) traverse_pre_order_recursive(root.right, action) def traverse_pre_order_iterative(root, action=print): if root: stack = [root] while stack: node = stack.pop() action(node.data,end=" ") if node.right: stack.append(node.right) if node.left: stack.append(node.left) # root = Node("A") # root.left = Node("B") # root.left.left = Node("C") # root.left.right = Node("D") # root.right = Node("E") # root.right.left = Node("G") # root.right.right = Node("F") root = Node(1) root.right = Node(2) root.right.right = Node(5) root.right.right.left = Node(3) root.right.right.right = Node(6) root.right.right.left.right = Node(4) traverse_pre_order_iterative(root)
import time A= [99,55,4,66,28,31,36,52,38,72] for i in range(len(A)): min_index = i for j in range(i+1, len(A)): if A[min_index] > A[j]: min_index = j A[i], A[min_index] = A[min_index], A[i] print("sorted array") # t = time.time() # print("time complexity",t) for i in range(len(A)): print(A[i])
class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None self.prevval = None class Dlinkedlist: def __init__(self): self.headval=None def push(self, NewVal): if (self.headval is None): self.headval = Node(NewVal) else: hval = self.headval Newnode = Node(NewVal) Newnode.nextval = self.headval self.headval.prevval = Newnode self.headval = Newnode def insertpos(self, Insval , pos): hval = self.headval Insnode = Node(Insval) if (pos == 1): Insnode.nextval = self.headval self.headval.prevval = Insnode self.headval = Insnode else: for i in range(2,pos): if (hval is not None): hval = hval.nextval else: print ("Index out of range") nextnode = hval.nextval Insnode.nextval = nextnode Insnode.prevval = hval hval.nextval = Insnode nextnode.prevval = Insnode def insertkey (self,prev,Insval): hval = self.headval Insnode = Node(Insval) if (hval is None): print ("Emplty list") else: while (hval.dataval != prev): if (hval is not None): hval = hval.nextval else: print ("Node is not in the list") nextnode = hval.nextval Insnode.nextval = nextnode Insnode.prevval = hval hval.nextval = Insnode nextnode.prevval = Insnode def remove (self,remov): hval = self.headval if (hval is None): print ("Emplty list") else: while (hval.dataval != remov): if (hval is not None): hval = hval.nextval else: print ("Node is not in the list") nextnode = hval.nextval hval = hval.prevval nextnode.prevval = hval hval.nextval = nextnode def listprint (self): while(self.headval is not None): print (self.headval.dataval) self.headval = self.headval.nextval list1 = Dlinkedlist() list1.push(1) list1.push(2) list1.push(10) list1.push(13) list1.insertpos(15,1) list1.insertpos(4,4) list1.insertkey(2,20) list1.remove(2) list1.listprint()
from Actividades.Actividad3.Sobre import Sobre from datetime import date, datetime class Caja: # Atributes __id = -1 __date = date __time = datetime __desc = "" __sobres = list() # Constructor def __init__(self, sobres, d): self.__id = self.__id + 2 self.__date = date.today() self.__time = datetime.now() self.__desc = d self.__GenerarSobres(sobres) # Getters/Setters def getId(self): return self.__id def getDate(self): return self.__date def getTime(self): return self.__time def getDescription(self): return self.__desc def getSobres(self): return self.__sobres def SetId(self, Y): self.__id = Y def SetDate(self, Y): self.__date = Y def SetTime(self, Y): self.__time = Y def SetDescription(self, Y): self.__desc = Y # Other methods def __GenerarSobres(self, x): for i in range(x): self.getSobres().append(Sobre("Fallout", "Sobre del juego de mesa del aclamdo videojuego", 5)) def verSobres(self): for i in self.getSobres(): print(i.toString()) def listarCartas(self): for s in self.getSobres(): s.verCartas()
import unittest class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.table = [None for i in range(10)] self.load = 0 def rebuild(self): # print("rebuild") old_table = self.table self.load = 0 self.table = [None for i in range(len(old_table)*2)] for key in old_table: if key is not None: self.add(key) def hash(self, value): h = 7 + value * 31 return h % len(self.table) def add(self, key: int) -> None: h = self.hash(key) if self.table[h] is not None and self.table[h] != key: self.rebuild() self.add(key) else: self.table[h] = key self.load += 1 def remove(self, key: int) -> None: h = self.hash(key) if self.table[h] == key: self.table[h] = None self.load -= 1 def contains(self, key: int) -> bool: """ Returns True if this set contains the specified element """ return self.table[self.hash(key)] == key def get_load(self): return (self.load/len(self.table), self.load, len(self.table)) # Your MyHashSet object will be instantiated and called as such: # obj = MyHashSet() # obj.add(key) # obj.remove(key) # param_3 = obj.contains(key) class Tests(unittest.TestCase): def test_add(self): mhs = MyHashSet() self.assertFalse(mhs.contains(0)) mhs.add(0) self.assertTrue(mhs.contains(0)) def test_remove(self): mhs = MyHashSet() mhs.add(0) self.assertTrue(mhs.contains(0)) mhs.remove(0) self.assertFalse(mhs.contains(0)) def leetcode_format(self, mhs, ops, ins, outs): result = [None] notes = [] for op, inp, out in zip(ops[1:], ins[1:], outs[1:]): inp = inp[0] if op == "contains": r = mhs.contains(inp) result.append(r) if r != out: notes.append(f"Contains {inp} - got {r} expected {out}") if op == "remove": mhs.remove(inp) result.append(None) if op == "add": mhs.add(inp) result.append(None) # print(f"{op} {inp} {mhs.contains(40)}") return result, notes def test_full(self): ops = ["MyHashSet", "contains", "remove", "add", "add", "contains", "remove", "contains", "contains", "add", "add", "add", "add", "remove", "add", "add", "add", "add", "add", "add", "add", "add", "add", "add", "contains", "add", "contains", "add", "add", "contains", "add", "add", "remove", "add", "add", "add", "add", "add", "contains", "add", "add", "add", "remove", "contains", "add", "contains", "add", "add", "add", "add", "add", "contains", "remove", "remove", "add", "remove", "contains", "add", "remove", "add", "add", "add", "add", "contains", "contains", "add", "remove", "remove", "remove", "remove", "add", "add", "contains", "add", "add", "remove", "add", "add", "add", "add", "add", "add", "add", "add", "remove", "add", "remove", "remove", "add", "remove", "add", "remove", "add", "add", "add", "remove", "remove", "remove", "add", "contains", "add"] ins = [[], [72], [91], [48], [41], [96], [87], [48], [49], [84], [82], [24], [7], [56], [87], [81], [55], [19], [40], [68], [23], [80], [53], [76], [93], [95], [95], [67], [31], [80], [62], [73], [97], [33], [28], [62], [81], [57], [40], [11], [89], [28], [97], [86], [20], [5], [77], [52], [57], [88], [ 20], [48], [42], [86], [49], [62], [53], [43], [98], [32], [15], [42], [50], [19], [32], [67], [84], [60], [8], [85], [43], [59], [65], [40], [81], [55], [56], [54], [59], [78], [53], [0], [24], [7], [53], [33], [69], [86], [7], [1], [16], [58], [61], [34], [53], [84], [21], [58], [25], [45], [3]] outs = [None, False, None, None, None, False, None, True, False, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, False, None, True, None, None, True, None, None, None, None, None, None, None, None, True, None, None, None, None, False, None, False, None, None, None, None, None, True, None, None, None, None, True, None, None, None, None, None, None, True, True, None, None, None, None, None, None, None, False, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, False, None] results, notes = self.leetcode_format(MyHashSet(), ops, ins, outs) # print(notes) self.assertEqual(results, outs) def test_full2(self): ops = ["MyHashSet", "add", "contains", "add", "contains", "remove", "add", "contains", "add", "add", "add", "add", "add", "add", "contains", "add", "add", "add", "contains", "remove", "contains", "contains", "add", "remove", "add", "remove", "add", "remove", "add", "contains", "add", "add", "contains", "add", "add", "add", "add", "remove", "contains", "add", "contains", "add", "add", "add", "remove", "remove", "add", "contains", "add", "add", "contains", "remove", "add", "contains", "add", "remove", "remove", "add", "contains", "add", "contains", "contains", "add", "add", "remove", "remove", "add", "remove", "add", "add", "add", "add", "add", "add", "remove", "remove", "add", "remove", "add", "add", "add", "add", "contains", "add", "remove", "remove", "remove", "remove", "add", "add", "add", "add", "contains", "add", "add", "add", "add", "add", "add", "add", "add"] ins = [[], [58], [0], [14], [58], [91], [6], [58], [66], [51], [16], [40], [52], [48], [40], [42], [85], [36], [16], [0], [43], [6], [3], [25], [99], [66], [60], [58], [97], [3], [35], [65], [40], [41], [10], [37], [65], [37], [40], [28], [60], [30], [63], [76], [90], [3], [43], [81], [61], [39], [ 75], [10], [55], [92], [71], [2], [20], [7], [55], [88], [39], [97], [44], [1], [51], [89], [37], [19], [3], [13], [11], [68], [18], [17], [41], [87], [48], [43], [68], [80], [35], [2], [17], [71], [90], [83], [42], [88], [16], [37], [33], [66], [59], [6], [79], [77], [14], [69], [36], [21], [40]] outs = [None, None, False, None, True, None, None, True, None, None, None, None, None, None, True, None, None, None, True, None, False, True, None, None, None, None, None, None, None, True, None, None, True, None, None, None, None, None, True, None, True, None, None, None, None, None, None, False, None, None, False, None, None, False, None, None, None, None, True, None, True, True, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, True, None, None, None, None, None, None, None, None, None, False, None, None, None, None, None, None, None, None] mhs = MyHashSet() results, notes = self.leetcode_format(mhs, ops, ins, outs) print(mhs.get_load()) self.assertEqual(results, outs) def test_full3(self): ops = ["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "add", "add", "remove", "add", "contains", "add", "add", "contains", "add", "add", "add", "add", "add", "remove", "add", "add", "add", "remove", "add", "add", "contains", "remove", "remove", "remove", "add", "add", "remove", "add", "add", "contains", "add", "add", "contains", "add", "add", "remove", "add", "add", "add", "remove", "add", "contains", "add", "add", "contains", "add", "add", "add", "add", "add", "add", "contains", "add", "remove", "add", "remove", "add", "add", "remove", "add", "contains", "add", "remove", "remove", "add", "add", "remove", "add", "remove", "contains", "add", "remove", "add", "add", "contains", "remove", "contains", "add", "contains", "contains", "add", "add", "add", "add", "remove", "add", "add", "contains", "contains", "add", "add", "add", "remove", "remove"] ins = [[], [95], [17], [95], [26], [70], [43], [33], [75], [86], [29], [39], [74], [56], [99], [4], [57], [81], [79], [26], [82], [13], [59], [69], [98], [45], [53], [84], [77], [89], [70], [51], [96], [6], [46], [86], [96], [87], [37], [96], [95], [58], [46], [41], [4], [80], [50], [89], [17], [4], [ 14], [69], [93], [3], [59], [63], [26], [5], [5], [44], [25], [17], [46], [69], [82], [28], [72], [6], [43], [11], [85], [61], [85], [62], [58], [98], [70], [13], [48], [91], [96], [87], [30], [91], [84], [59], [92], [97], [61], [91], [78], [16], [36], [85], [32], [93], [54], [89], [74], [79], [54]] outs = [None, None, None, True, False, None, False, None, None, None, None, False, None, None, False, None, None, None, None, None, None, None, None, None, None, None, None, False, None, None, None, None, None, None, None, None, True, None, None, True, None, None, None, None, None, None, None, None, True, None, None, True, None, None, None, None, None, None, True, None, None, None, None, None, None, None, None, False, None, None, None, None, None, None, None, None, False, None, None, None, None, True, None, True, None, True, False, None, None, None, None, None, None, None, False, True, None, None, None, None, None] mhs = MyHashSet() results, notes = self.leetcode_format(mhs, ops, ins, outs) print(mhs.get_load()) self.assertEqual(results, outs) if __name__ == "__main__": # unittest.main() mhs = MyHashSet() for i in range(1, 10000000): mhs.add(i) print(mhs.get_load())
import string n=input() alphabets=string.ascii_lowercase[:27] if n in alphabets: print('Alphabet') else: print("No")
class A: def truth(self): return 'All numbers are even' class B(A): pass class C(A): def truth(self): return 'Some numbers are even' class D(B,C): def truth(self,num): if num%2 == 0: return A.truth(self) else: return super().truth() d = D() d.truth(6)
import unittest class Hantu: def __init__(self,name,legs): self.name = name self.legs = legs class Jin(Hantu): def __init__(self,name,legs=1,booing='yes'): Hantu.__init__(self,name,legs) self.booing = booing Tomang = Jin('Tomang') #print(Tomang.name) #print(Tomang.legs) #print(Tomang.booing) class Mytest(unittest.TestCase): def test(self): self.assertEqual(Tomang.legs, 0) if __name__ == '__main__': unittest.main()
def perm(arr): result = list([[]]) for i in range(len(arr)): t = list() for y_lst in result: for j in arr: if j not in y_lst: new_lst = list(y_lst) new_lst.append(j) t.append(list(new_lst)) result = t print(result) return result print(perm([1,2,3])) def perm(arr,size): result = list([[]]) for i in range(size): t = list() for y_lst in result: for j in arr: if j not in y_lst: new_lst = list(y_lst) new_lst.append(j) t.append(list(new_lst)) result = t #print(result) return result print(perm([1,2,3,4],3)) lst=list(input("enter number array for permutation")) n=int(input("enter times of combination")) if len(lst)>n: p=[[x for x in range(0)]] for i in range(n): p = [[a] + b for a in lst for b in p if (a not in b)] print(p) else: print("Please enter a combination number lower than list length") x=[1,2,3] n=len(x) def permutate(a, l, r): if l==r: print(x) else: for i in range(l,r+1): a[l], a[i] = a[i], a[l] permutate(a, l+1, r) a[l], a[i] =a[i], a[l] permutate(x, 0, n-1)
from card_game import * from setup import * # Ask for the number of players joining the game n_players = int(input("How many players will join? ")) # Run the function and save it as players_list players_list = ask_names(n_players) # Create a player instances for p in range(n_players): players_list[p] = Player(players_list[p]) # Round 1: Red or Black? print(round1) for p in range(n_players): print(f"\n\n{players_list[p].name}, it is your turn now") prediction = input("Guess: Is the card red or black? ").lower() players_list[p].draw(deck) print("You drew \n") players_list[p].showHand() # Checks if the card is either black or red if prediction in ['black', 'red']: print(win if prediction == players_list[p].hand[0].color else lose) # If the answer is neither black or red... You have to drink else: print(not_valid) # Round 2: Higher or Lower print(round2) for p in range(n_players): print(f"\n\n{players_list[p].name}, it is your turn now") print('Your last card was ') players_list[p].showLastCard() prediction = input("Guess: Is the next card higher or lower? ").lower() players_list[p].draw(deck) print("You drew \n") players_list[p].showHand() if prediction in ['higher', 'lower']: if prediction == 'higher': print(win if players_list[p].hand[1].value > \ players_list[p].hand[0].value else lose) else: print(win if players_list[p].hand[1].value < \ players_list[p].hand[0].value else lose) else: print(not_valid) # Round 3: Inside or outside? print(round3) for p in range(n_players): print(f"\n\n{players_list[p].name}, it is your turn now") print('Your cards are ') players_list[p].showHand() prediction = input("Guess: Is the next card inside or outside? ").lower() players_list[p].draw(deck) print("You drew \n") players_list[p].showHand() if prediction in ['inside', 'outside']: if inside == True and prediction == "inside"\ or outside == True and prediction == "outside": print(win) else: print(lose) else: print(not_valid) # Round 4: Do you already have the suit print(round4) for p in range(n_players): print(f"\n\n{players_list[p].name}, it is your turn now") print('Your cards are ') players_list[p].showHand() prediction = input("Guess: Do you have suit already (yes or no) ").lower() players_list[p].draw(deck) print("You drew \n") players_list[p].showHand() if prediction in ['yes', 'no']: if have_it_already == True and prediction == "yes"\ or have_it_already == False and prediction == "no": print(win) else: print(lose) else: print(not_valid)
def solution(a_list): m1,m2 = float('inf'), float('inf') for x in a_list: if x <= m1: m1, m2 = x, m1 elif x < m2: m2 = x return m2 print solution([1, 2, -8, -2, 0])
my_name = 'Zed .A .Shaw' my_age = 23 my_height = 75 my_weight = 170 my_eyes = 'blue' my_teeth = 'white' my_hair = 'black' print "Let's talk about %s." %my_name print "He is %s lbs in weight." %my_weight print "He is %s inches tall. "%my_height print "He has %s coloured eyes."%my_eyes print "He has %s teeth."%my_teeth print "He has %s Hair."%my_hair print "Tricky line given below" print "If I add %d,%d and %d I get %d." %(my_age , my_height , my_weight , my_age + my_height + my_weight)
#Rohan Rao import random import time name = input("What is your name? ") print("Good Luck ! ", name) # Word bank # Words to guess from words = ['banana','strawberry','mango','blueberry', 'pineapple','apple','raspberry','blackberry','orange','pear', 'grape','peach','kiwi'] #Chooses randomn word word = random.choice(words) print("The Theme is Fruits") guesses = '' turns = 7 while turns > 0: failed = 0 hangman(turns) for char in word: if char in guesses: print(char, end = " ") else: print("_", end = " ") failed += 1 if failed == 0: print("You Win!") print("The word is:", word) break guess = input("guess a character:") guesses += guess # If the letter guessed is not in the word it removes a turn if guess not in word: turns -= 1 print("Wrong") print("You have", + turns, 'more guesses') # When user runs out of turns if turns == 0: print("GAME OVER YOU LOSE! The word was", word) print("Would you like to play again? ")
# Rohan Rao # Help from Dad # This is my final project for Game Design # This game is popular and is known as "Flappy Bird" # It has 3 difficulties (Easy, Medium, and Hard) # which changes the scrolling speed to make it harder # I don't have a leaderboard because # Flappy Bird doesn't usually have a leaderboard # This code ALMOST works fully but the game is still playable # Pseudo code: # import pygame modules # initialize pygame # set dimenisons of pygame window (height, width, caption, etc.) # define fonts (for menu and instructions) # load images (background, menutitle, bird, etc.) # define color # draw buttons for main menu # define game variables (scrolling speed, score, menu and game loops, etc.) # define game functions (frequency for pipes, score, etc.) # run menu loop (background, and buttons) # if click difficulty, run main game loop # after game, 3 buttons (restart with same difficulty, quit, or back to menu) # screen is 846 by 936 pixels # import modules import pygame import time from pygame.locals import * import random #initialize pygame pygame.init() clock = pygame.time.Clock() fps = 60 #set screen dimensions screen_width = 864 screen_height = 936 #set caption of pygame window pygame.display.set_caption('Flappy Bird') #define font font = pygame.font.SysFont('Bauhaus 93', 60) TITLE_FONT = pygame.font.SysFont('comicsans', 70) TITLE_FONT2 = pygame.font.SysFont('comicsans', 70) BUTTON1FONT = pygame.font.SysFont('comicsans', 60) BUTTON2FONT = pygame.font.SysFont('comicsans', 60) BUTTON3FONT = pygame.font.SysFont('comicsans', 60) BUTTON4FONT = pygame.font.SysFont('comicsans', 60) INSTRUCTIONSFONT = pygame.font.SysFont('comicsans', 60) #define colors white = (255, 255, 255) #define game variables screen = pygame.display.set_mode((screen_width, screen_height)) ground_scroll = 0 scroll_speed = 0 flying = False game_over = False pipe_gap = 150 pipe_frequency = 1500 #milliseconds last_pipe = pygame.time.get_ticks() - pipe_frequency score = 0 pass_pipe = False menu = True run = False #drawing main menu buttons # setting dimensions ( x y w h) button1 = pygame.Rect(232,200,400,50) button2 = pygame.Rect(307,275,250,50) button3 = pygame.Rect(307,350,250,50) button4 = pygame.Rect(307,425,250,50) #drawing text on main menu buttons text1 = BUTTON1FONT.render("INSTRUCTIONS [1]", 1, (0,0,0)) text2 = BUTTON2FONT.render("EASY [2]", 1, (0,0,0)) text3 = BUTTON3FONT.render("MEDIUM [3]", 1, (0,0,0)) text4 = BUTTON4FONT.render("HARD [4]", 1, (0,0,0)) #drawing text for instructions Text color text5 = INSTRUCTIONSFONT.render("INSTRUCTIONS:", 1, (0,0,0)) text6 = INSTRUCTIONSFONT.render("THE OBJECTIVE OF FLAPPY BIRD", 1, (0,0,0)) text7 = INSTRUCTIONSFONT.render("IS TO KEEP YOUR BIRD IN BETWEEN", 1, (0,0,0)) text8 = INSTRUCTIONSFONT.render("THE PIPES IN ORDER FOR IT TO FLY", 1, (0,0,0)) text9 = INSTRUCTIONSFONT.render("THROUGH. EVERY TIME YOU GET THE", 1, (0,0,0)) text10 = INSTRUCTIONSFONT.render("BIRD IN BETWEEN THE PIPES, YOU GET", 1, (0,0,0)) text11 = INSTRUCTIONSFONT.render("A POINT. TO MAKE THE BIRD FLY, CLICK", 1, (0,0,0)) text12 = INSTRUCTIONSFONT.render("THE MOUSEPAD. THIS IS AN ENDLESS", 1, (0,0,0)) text13 = INSTRUCTIONSFONT.render("GAMEMODE (IT KEEPS GOING UNTIL YOU", 1, (0,0,0)) text14 = INSTRUCTIONSFONT.render("DIE). THE DIFFICULTY IS BASED ON ", 1, (0,0,0)) text15 = INSTRUCTIONSFONT.render("HOW FAST THE BIRD MOVES.", 1, (0,0,0)) text16 = INSTRUCTIONSFONT.render("Click 1 to go to menu", 1, (0,0,0)) #loading images for game bg = pygame.image.load('bg.png') ground_img = pygame.image.load('ground.png') button_img = pygame.image.load('restart.png') button_2_img = pygame.image.load('exit.png') button_3_img = pygame.image.load('menu.png') MenuTitle = pygame.image.load('FlappyBirdMenuTitle.png') #DEFINING FUNCTIONS #Function for instructions def instructions(): screen.fill(white) #screen_width/2 - text{num}.get_width()/2 is for centering # Text x y screen.blit(text5, (screen_width/2 - text5.get_width()/2, 50)) screen.blit(text6, (screen_width/2 - text6.get_width()/2, 100)) screen.blit(text7, (screen_width/2 - text7.get_width()/2, 150)) screen.blit(text8, (screen_width/2 - text8.get_width()/2, 200)) screen.blit(text9, (screen_width/2 - text9.get_width()/2, 250)) screen.blit(text10, (screen_width/2 - text10.get_width()/2, 300)) screen.blit(text11, (screen_width/2 - text11.get_width()/2, 350)) screen.blit(text12, (screen_width/2 - text12.get_width()/2, 400)) screen.blit(text13, (screen_width/2 - text13.get_width()/2, 450)) screen.blit(text14, (screen_width/2 - text14.get_width()/2, 500)) screen.blit(text15, (screen_width/2 - text15.get_width()/2, 550)) screen.blit(text16, (screen_width/2 - text16.get_width()/2, 750)) keys = pygame.key.get_pressed() # If key 1 is pressed, user returns to menu # (Not working) if keys[pygame.K_1]: menu = True pygame.display.update() pygame.time.delay(10000) #Function for drawing text on the screen def draw_text(text, font, text_col, x, y): img = font.render(text, True, text_col) screen.blit(img, (x, y)) #Function for resetting game after loss def reset_game(): pipe_group.empty() flappy.rect.x = 100 flappy.rect.y = int(screen_height / 2) score = 0 return score class Bird(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.images = [] self.index = 0 self.counter = 0 for num in range (1, 4): img = pygame.image.load(f"bird{num}.png") self.images.append(img) self.image = self.images[self.index] self.rect = self.image.get_rect() self.rect.center = [x, y] self.vel = 0 self.clicked = False def update(self): if flying == True: #apply gravity self.vel += 0.5 if self.vel > 8: self.vel = 8 if self.rect.bottom < 768: self.rect.y += int(self.vel) if game_over == False: #jump if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False: self.clicked = True self.vel = -10 if pygame.mouse.get_pressed()[0] == 0: self.clicked = False #handle the animation flap_cooldown = 5 self.counter += 1 if self.counter > flap_cooldown: self.counter = 0 self.index += 1 if self.index >= len(self.images): self.index = 0 self.image = self.images[self.index] #rotate the bird self.image = pygame.transform.rotate(self.images[self.index], self.vel * -2) else: #point the bird at the ground self.image = pygame.transform.rotate(self.images[self.index], -90) #Class for drawing pipes' sprites class Pipe(pygame.sprite.Sprite): def __init__(self, x, y, position): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("pipe.png") self.rect = self.image.get_rect() #position variable determines if the pipe is coming from the bottom or top #position 1 is from the top, -1 is from the bottom if position == 1: self.image = pygame.transform.flip(self.image, False, True) self.rect.bottomleft = [x, y - int(pipe_gap / 2)] elif position == -1: self.rect.topleft = [x, y + int(pipe_gap / 2)] def update(self): self.rect.x -= scroll_speed if self.rect.right < 0: self.kill() #Class for buttons at end of game class Button(): def __init__(self, x, y, image): self.image = image self.rect = self.image.get_rect() self.rect.topleft = (x, y) def draw(self): action = False #get mouse position pygame.init() pos = pygame.mouse.get_pos() #check mouseover and clicked conditions if self.rect.collidepoint(pos): if pygame.mouse.get_pressed()[0] == 1: action = True #draw button screen.blit(self.image, (self.rect.x, self.rect.y)) return action pipe_group = pygame.sprite.Group() bird_group = pygame.sprite.Group() flappy = Bird(100, int(screen_height / 2)) bird_group.add(flappy) #drawing restart button (after loss) button = Button(screen_width // 2 - 50, screen_height // 2 - 250, button_img) #drawing exit button (after loss) button_2 = Button(screen_width // 2 - 50, screen_height // 2 - 150, button_2_img) #drawing menu button (after loss) button_3 = Button(screen_width // 2 - 50, screen_height // 2 - 200, button_3_img) # MAIN PROGRAM (while loops) # Menu loop while menu: #draw background screen.blit(bg, (0,0)) #draw menu title on background screen.blit(MenuTitle, (175,-100)) #draw main menu buttons pygame.draw.rect(screen,(0,102,0), button1) pygame.draw.rect(screen,(0,102,0), button2) pygame.draw.rect(screen,(0,102,0), button3) pygame.draw.rect(screen,(0,102,0), button4) screen.blit(text1, (screen_width/2 - text1.get_width()/2, 210)) screen.blit(text2, (screen_width/2 - text2.get_width()/2, 285)) screen.blit(text3, (screen_width/2 - text3.get_width()/2, 360)) screen.blit(text4, (screen_width/2 - text4.get_width()/2, 435)) #checking for if a key pressed for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_1: # button to instructions menu = False instructions() if event.key == pygame.K_2: # button to easy difficulty scroll_speed = 4 # Changing scroll speed as difficulty goes up menu = False run = True if event.key == pygame.K_3: # button to medium difficulty scroll_speed = 10 menu = False run = True if event.key == pygame.K_4: # button to hard difficulty scroll_speed = 20 menu = False run = True # updating display to actually display it on the pygame window pygame.display.update() # Main Game Loop while run: #draw background screen.blit(bg, (0,0)) clock.tick(fps) #draw pipes and bird pipe_group.draw(screen) bird_group.draw(screen) bird_group.update() #draw and scroll the ground screen.blit(ground_img, (ground_scroll, 768)) #check the score #check if the bird actually passes through the pipe if len(pipe_group) > 0: if bird_group.sprites()[0].rect.left > pipe_group.sprites()[0].rect.left\ and bird_group.sprites()[0].rect.right < pipe_group.sprites()[0].rect.right\ and pass_pipe == False: pass_pipe = True if pass_pipe == True: if bird_group.sprites()[0].rect.left > pipe_group.sprites()[0].rect.right: score += 1 pass_pipe = False draw_text(str(score), font, white, int(screen_width / 2), 20) #look for collision to pipe #if bird collides, it is game over if pygame.sprite.groupcollide(bird_group, pipe_group, False, False) or flappy.rect.top < 0: game_over = True #once the bird has hit the ground it's game over and no longer flying if flappy.rect.bottom >= 768: game_over = True flying = False #if the bird is flying and it is not game over if flying == True and game_over == False: #it will generate new pipes for the player to pass through time_now = pygame.time.get_ticks() if time_now - last_pipe > pipe_frequency: pipe_height = random.randint(-100, 100) btm_pipe = Pipe(screen_width, int(screen_height / 2) + pipe_height, -1) top_pipe = Pipe(screen_width, int(screen_height / 2) + pipe_height, 1) pipe_group.add(btm_pipe) pipe_group.add(top_pipe) last_pipe = time_now pipe_group.update() ground_scroll -= scroll_speed if abs(ground_scroll) > 35: ground_scroll = 0 #Buttons at the end of the game if game_over == True: if button.draw(): # Restart Button game_over = False score = reset_game() pygame.display.update() if button_2.draw(): # Exit Button pygame.display.quit() if button_3.draw(): # Return to menu Button (not working) menu = True for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN and flying == False and game_over == False: flying = True pygame.display.update() pygame.quit()
#Rohan Rao #This program contains ForLoops Program, Prime Numbers, and the Fibonacci sequence #Forloops for line in range(5): print() for number in range(5-line,0,-1): print(number, end =' ') #Prime Numbers Program start = 25 #First Value of finding prime number end = 50 #Last Value of finding prime number for num in range(start, end + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) #Fibonacci Sequence Program def fib(number_of_terms): a=0 x= 0 y= 1 z= 0 while a <= number_of_terms: print(x) z= x + y x = y y = z a= a + 1 fib(10)
from tkinter import * root = Tk() myLabel = Label(root, text = "hello world!") myLabel.pack() root.mainloop()
from ortools.graph import pywrapgraph import time import random from copy import copy,deepcopy def main(): print("What kind of assignment problem are you trying to solve?\nEnter:") problem = int(input("1: Balanced Minimization\n2: Unbalanced Minimization\n3: Balanced Maximization\n4: Unbalanced Maximization")) if problem==1: cost = balanced_minimization() rows = len(cost) cols = len(cost[0]) elif problem==2: cost = unbalanced_minimization() rows = len(cost) cols = len(cost[0]) elif problem==3: cost,maxim_matrix = balanced_maximization() rows = len(cost) cols = len(cost[0]) elif problem==4: cost,maxim_matrix = unbalanced_maximization() rows = len(cost) cols = len(cost[0]) else: print("Invalid input") exit(0) #linear assignment solver, a specialized solver for the assignment problem #following code creates the solver assignment = pywrapgraph.LinearSumAssignment() #The following code adds the costs to the solver by looping over workers and #tasks. for worker in range(rows): for task in range(cols): #if cost[worker][task]: #creating the bipartite graph that will be used to solve the problem assignment.AddArcWithCost(worker, task, cost[worker][task]) #The following code invokes the solver and displays the solution. solve_status = assignment.Solve() #checks if an optimal solution exists and displays the result accordingly if solve_status == assignment.OPTIMAL: print('Total cost = ', assignment.OptimalCost()) print() maxim_sale=0 if problem ==1 or problem==2: for i in range(0, assignment.NumNodes()): print('Worker %d assigned to task %d. Cost = %d. ' % ( i+1, assignment.RightMate(i)+1, assignment.AssignmentCost(i))) if problem ==3 or problem==4: for i in range(0, assignment.NumNodes()): print('Worker %d assigned to task %d. Cost = %d. Sale is = %d' % ( i+1, assignment.RightMate(i)+1, assignment.AssignmentCost(i), maxim_matrix[i][assignment.RightMate(i)])) maxim_sale += maxim_matrix[i][assignment.RightMate(i)] print("\n\nMaximum Sale is: %d" % (maxim_sale)) #if the solution is infeasible elif solve_status == assignment.INFEASIBLE: print('No assignment is possible.') #if the solution has very large input costs elif solve_status == assignment.POSSIBLE_OVERFLOW: print('Some input costs are too large and may cause an integer overflow.') #creating data for balanced minimization problem def balanced_minimization(): #input in matrix layout format """ a b c d e f g h i """ n = int(input("Enter number of rows: ")) print() cost = [] for i in range(n): cost.append([int(j) for j in input().split()]) return cost #creating data for unbalanced minimization problem def unbalanced_minimization(): rows = int(input("Enter number of rows: ")) cols = int(input("Enter number of columns: ")) if rows > cols: cost = [[random.random() for row in range(rows)] for row in range(rows)] for i in range(rows): for j in range(cols): cost[i][j] = int(input()) while rows > cols: for i in range(rows): cost[i][cols]=0 cols+=1 if cols > rows: cost = [[random.random() for col in range(cols)] for col in range(cols)] for i in range(cols): for j in range(cols): if i<=rows: cost[i][j] = int(input()) while cols > rows: for i in range(cols): cost[rows][i] = 0 rows+=1 return cost #creating data for balanced maximization problem def balanced_maximization(): #input in matrix layout format """ a b c d e f g h i """ n = int(input("Enter number of rows: ")) print() maxim_matrix = [] for i in range(n): maxim_matrix.append([int(j) for j in input().split()]) #converting max matrix to min matrix cost = deepcopy(maxim_matrix) maximum = max(map(max, maxim_matrix)) for i in range(n): for j in range(n): cost[i][j]=maximum-cost[i][j] return cost,maxim_matrix #creating data for unbalanced maximization problem def unbalanced_maximization(): rows = int(input("Enter number of rows: ")) cols = int(input("Enter number of columns: ")) if rows > cols: maxim_matrix = [[random.random() for row in range(rows)] for row in range(rows)] for i in range(rows): for j in range(cols): maxim_matrix[i][j] = int(input()) while rows > cols: for i in range(rows): maxim_matrix[i][cols]=0 cols+=1 if cols > rows: maxim_matrix = [[random.random() for col in range(cols)] for col in range(cols)] for i in range(cols): for j in range(cols): if i<=rows: maxim_matrix[i][j] = int(input()) while cols > rows: for i in range(cols): maxim_matrix[rows][i] = 0 rows+=1 #converting the max matrix to min matrix cost = deepcopy(maxim_matrix) maximum = max(map(max, maxim_matrix)) for i in range(rows): for j in range(cols): cost[i][j]=maximum-cost[i][j] return cost,maxim_matrix #calling the main function if __name__ == "__main__": start_time = time.clock() main() print() print("Time =", time.clock() - start_time, "seconds")
quieres_sabritas_input = input ( "quieres sabrtias de limon? (si/no): ") if quieres_sabritas_input == "si": quieres_sabritas = True elif quieres_sabritas_input == "no": quieres_sabritas = False else: print("tienes que decir que si on no sucio mortal") quieres_sabritas = False tienes_dinero_input = input ("tienes dinero suficiente? (si/no):") sabritas_de_limon_input = input ("hay sabritas de limon? (si/no):") esta_mama_input = input ("estas con mama? (si/no):") quieres_sabritas = quieres_sabritas_input == "si" puedes_comprar = tienes_dinero_input == "si" or esta_mama_input == "si" hay_sabritas_limon = sabritas_de_limon_input == "si" if quieres_sabritas and puedes_comprar and hay_sabritas_limon: print("compra entonces") else: print ("entonces nada")
import re def remove_special_char(text): text = re.sub('[áàãâ]', 'a', text) text = re.sub('[óòõô]', 'o', text) text = re.sub('[éèê]', 'e', text) text = re.sub('[íì]', 'i', text) text = re.sub('[úù]', 'u', text) text = re.sub('ç', 'c', text) return text
class Pizzeria: def __init__(self, pizzas: dict, num_ingredients: int) -> None: self.pizzas = pizzas self.num_ingredients = num_ingredients self._ingredients_reverse_index() def __eq__(self, other): return isinstance(other, Pizzeria) and \ self.pizzas == other.pizzas and \ self.num_ingredients == other.num_ingredients def _ingredients_reverse_index(self): self.ingredients_reverse_index = {} for pizza_key, pizza_value in self.pizzas.items(): for ingredient in pizza_value: ingredient_list = self.ingredients_reverse_index.get(ingredient, []) ingredient_list.append(pizza_key) self.ingredients_reverse_index[ingredient] = ingredient_list
string1 = "Cisco Router" #se puede acceder a los indices de un string, cada caracter representa un indice #el ultimo caracter de puede acceder con -1 #para leer un string del reves se comineza con -1 y va decrenciendo en negativo string1[1] string1[-1] #para saber el lenght de un caracter usar la funcion len len(string1) ####### METODOS ####### a = "Cisco Switch" #Arroja el indice del caracter que se le pasa en el parentesis a.index("i") #1 #Arroja el numero de veces que encuentra la letra i en el string a.count("i") #2 #Arroja el primer indice del macth que hace con los caracteres que se le pasa en el parentesis a.find("sco") #2 #Si no encuentra ningun match arroja -1 a.find("xyz") #-1 #Metodo para pasar todo a minuscula un string a.lower() #'cisco switch' #Metodo para pasar a mayuscula un string, no interfiere con el string original, o sea mantiene su valor a pesar del metodo #Metodo para verificar con letra comienza un string, retorna true o false y es casesensitive a.startswith("c") False a.startswith("C") True #Metodo para verificar con letra termina un string a.endswith("h") True #Metodo para eliminar lo que esta al inicio y al fin de un string, si no se pasa nada en el parentisis elimina los espacios b = " Cisco Switch " b.strip() 'Cisco Switch' c = "$$$Cisco Switch$$$" c.strip("$") 'Cisco Switch' c = "$$$Cisco $$$Switch$$$" c.strip("$") 'Cisco $$$Switch' #Metodo para reemplazar un caracter por otro, se pasa primero el caracter que va a ser reemplazado, luego el nuevo valor b ' Cisco Switch ' b.replace(" ", "") 'CiscoSwitch' #Crea una lista segun el parametro de split definido d = "Cisco,Juniper,HP,Avaya,Nortel" d.split(",") ['Cisco', 'Juniper', 'HP', 'Avaya', 'Nortel'] #Metodo para insertar algo en un string, en este caso inserta entre cada letra un _ a 'Cisco Switch' "_".join(a) 'C_i_s_c_o_ _S_w_i_t_c_h'
''' Implement a function is_prime(x) that returns True if x is prime, False otherwise. (1 Point) >>> is_prime(7) True >>> is_prime(15) False ''' # ... your code ... def is_prime(num): if (num == 1): return False isPrime = True for y in range(2, num - 1): if (isPrime): if (num % y == 0): isPrime = False return isPrime if __name__ == '__main__': print('is_prime') print('Test1', is_prime(1) == False) print('Test2', is_prime(2) == True) print('Test3', is_prime(3) == True) print('Test4', is_prime(4) == False) print('Test5', is_prime(5) == True)
###################################### # Introduction to Python Programming # # WS 2013/2014 # # Iterators & Generators # ###################################### ''' Implement an iterator that iterates over a file by paragraph. By "paragraph" we mean all lines in the file which are not separated by blank lines. For instance, the string """ This is an a sentence. This is another sentence. Followed by yet another one. This is not the last sentence. This one neither. This one is the last one. """ contains four paragraphs. Yor iterator should thus return four strings. (4 Points) Hints: * S.isspace() returns True if all characters in string S are whitespace and there is at least one character in S, False otherwise. Note that if you read in a file line by line, each line usually contains at least one character (the "newline" character \n). * S.rstrip() returns a copy of S with all trailing white space characters removed. * S.join(iterable) returns a string which is the concatenation of the strings in the iterable. The separator between elements is string S. For instance: ' '.join(['Help', 'me', 'please']) returns 'Help me please' (This is often more efficient than concatenating strings using + or +=) ''' class ByParagraph: def __init__(self, file): self.file = file def __iter__(self): """ usually returns the iterator itself :return: """ return self def __next__(self): """ returns the next element or raises StopIteration :return: """ try: temp = self.file.readline() # Check for EOF if temp == '': raise StopIteration else: # Remove any preceding whitespace temp = temp.strip() while temp == '': temp = self.file.readline().strip() # Read until a blank line is reached result = '' while temp != '': if result != '': result = ' '.join([result, temp]) else: result = temp temp = self.file.readline().strip() return result except: raise StopIteration with open("example.txt") as f: for p in ByParagraph(f): print(p) # should print four lines: #This is an a sentence. #This is another sentence. Followed by yet another one. #This is not the last sentence. This one neither. #This one is the last one.
######################################### # Introduction to Python Programming # # Exercise Sheet 13 # # List Comprehensions # ######################################### # Exercise 2 ''' (2 Points) Write function "count" that takes a list of words as argument and returns a list of word-frequency pairs. The function should use a list comprehension. Hint: Lists have a method count that returns the number of occurrences of the argument in the list: [1, 1, 2, 1, 3].count(1) => 3 ''' def count(words): ''' >>> count("Wenn Fliegen hinter fliegen fliegen fliegen Fliegen Fliegen nach".split()) [('Wenn', 1), ('Fliegen', 3), ('hinter', 1), ('fliegen', 3), ('fliegen', 3), ('fliegen', 3), ('Fliegen', 3), ('Fliegen', 3), ('nach', 1)] ''' return [(w, words.count(w)) for w in words] # This automatically tests your code if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
''' 1. POS-Tagged text (3 Points) The file "example.xml" containing POS-tagged text, where words are represented as follows: <W TYPE="part of speech" ...>word</W> Write a function that reads the file and ** returns ** a list of word-POS pairs (see example below). Example: read_file("example.xml") should return: [('FACTSHEET', 'NN1'), ('WHAT', 'DTQ'), ('IS', 'VBZ'), ...] ''' import sys import re def read_file(filename): result = [] with open(filename) as f: for line in f: m = re.search('.*TYPE="(.*)" .*">(.*)</.*', line) if m: result.append((m.group(2), m.group(1))) return result def main(): # for testing pairs = read_file('example.xml') for (word, pos) in pairs: print(word, pos) if __name__ == '__main__': main()
''' Implement a function that recognizes palindromes (2 Points). >>> is_palindrome("level") True >>> is_palindrome("levels") False Hints: string[i] gives you the ith character from left (starting from 0) string[-i] gives you ith character from right (starting from 1) # >>> s = "abcd" # >>> s[0] a # >>> s[-1] d Integer division: >>> 5 // 2 2 ''' # ... your code ... def is_palindrome(str): for i in range(len(str) // 2): if (str[i] != str[-i - 1]): return False return True if __name__ == '__main__': print('is_palindrome') print('Test1', is_palindrome("level") == True) print('Test1', is_palindrome("levels") == False) print('Test1', is_palindrome("abba") == True) print('Test1', is_palindrome("aba") == True) print('Test1', is_palindrome("abab") == False) print('Test1', is_palindrome("") == True)
#create a dictionary for base64 #iterate through each binary value and sum up each 6 bit to the corresponding base64 value def hexToBase64(string): binary = bin(int(string,16)) #convert string -> integer -> binary print(binary) base = 6 mask = '111111' rv = "" while (binary != 0): bit = 1 while (base >= bit): if binary & bit: yield bit bit = bit << 1 print(bit) rv.append(bit) print(rv) return rv #iterate through each hex value and next two binary values and map to corresponding base64 value #def hexToBase64fast(str): # while (str.length() != 0): # for (i = 0; i < 4; i++): # str.substring(0, 1) # apply mask to each iteration until remaining bit string is < 6, then use a tail case to sum the rest. print(hexToBase64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"))
word = input("Give me a word\n") i = 0 l = len(word) while i <= l: print(word[i]) i = i+1
mystr = str(input('Enter a string:')) letter = str(input('What letter do you want to check for?')) mylist = [] for i in mystr: mylist.append(i) if mylist.count(letter)!=0: print('Yes') else: print('No')
# Importation du module <<TURTLE>> import turtle def se_positionner(o,x,y,z=0): ''' OBJECTIF : Cette fonction permet de positionner la tortue, sans tracer, à un point de coordonnees(x et y) connus dans le repère METHODE : utilisation des méthodes "penup()", "goto()" "right()" et "pendown()" BESOIN : "o" comme position actuelle du curseur, "x" comme abcisse du point et "y" comme ordonnee, "z" comme angle départ CONNUS : / ENTREE : o,x,y,z SORTIE : / RESULTAT : / HYPOTHESE : les paramètres sont tous des nombres réels ''' turtle.penup() turtle.goto(o+x,y) turtle.rt(z) turtle.pendown() return [x,y] def se_deplacer(x,y,z=0,o=0): ''' OBJECTIF : Cette fonction permet à la tortue de se déplacer jusqu'à à un point de coordonnees(x et y) connus dans le repère METHODE : utilisation des méthodes "goto()" "right()" BESOIN : "o" comme position actuelle du curseur, "x" comme abcisse du point et "y" comme ordonnee, "z" comme angle départ CONNUS : / ENTREE : o,x,y,z SORTIE : / RESULTAT : / HYPOTHESE : les paramètres sont tous des nombres réels ''' turtle.goto(o+x,y) turtle.rt(z) def cercle(rayon,couleur=""): ''' OBJECTIF : Tracer un cercle dans le repère METHODE : utilisation de la méthode "circle" BESOIN : "rayon" qui représente le rayon du cercle "couleur" CONNUS : / ENTREE : rayon SORTIE : / RESULTAT : / HYPOTHESE : "rayon" est un nombre réel; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() turtle.circle(rayon) turtle.end_fill() def demi_cercle(rayon,couleur=""): ''' OBJECTIF : Tracer un demi cercle METHODE : utilisation de la méthode "circle" en précisant un angle de 180 degrés BESOIN :"rayon" qui represente le rayon du demi cercle "couleur" CONNUS :/ ENTREE :rayon SORTIE : / RESULTAT : / HYPOTHESE : "rayon" est un nombre reel; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() turtle.lt(90) turtle.circle(rayon,180) turtle.setheading(0) turtle.end_fill() def carree(cote,couleur="",i=0): ''' OBJECTIF : tracer un carre METHODE : utilisation de boucle et des methode "forward" et "right" BESOIN : "cote" et "i" "couleur" CONNUS : / ENTREE : cote SORTIE : / RESULTAT : / HYPOTHESE : "cote" est un nombre reel, si i!=0 alors le carrée sera tracé dans le sens inverse; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() if i == 0 : for i in range(4): turtle.fd(cote) turtle.rt(90) else : for i in range(4): turtle.fd(cote) turtle.lt(90) turtle.end_fill() def triangle_equilaterale(cote,couleur=""): ''' OBJECTIF : tracer un triangle equilateral METHODE : utilisation de boucle ainsi les methodes "left"et "forward " BESOIN : "cote" et "i" "couleur" CONNUS : / ENTREE : cote SORTIE : / RESULTAT : / HYPOTHESE : cote est un nombre reel; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() for i in range(3): turtle.fd(cote) turtle.lt(120) turtle.end_fill() def triangle_isocele(base,hauteur,couleur=""): ''' OBJECTIF :tracer un triagle isocele METHODE : utilisation de boucle ainsi les methodes "left" et "forward" BESOIN : "cote" et "i" "couleur" CONNUS : / ENTREE : cote SORTIE : origine RESULTAT : / HYPOTHESE : cote est un nombre reel; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() origine = turtle.pos() turtle.fd(base) turtle.goto(origine[0]+base/2,origine[1]+hauteur) turtle.goto(origine[0],origine[1]) turtle.end_fill() return origine def triangle_rectangle(base,hauteur,F=0,couleur=""): ''' OBJECTIF : tracer un triangle rectangle METHODE : utilisation des methodes "forward" et "goto" BESOIN : "base" , "hauteur" et "F" (qui prend une valeur différente de "0" pour inverser la figure) "couleur" CONNUS : / ENTREE : "base" et "hauteur" SORTIE : origine RESULTAT : / HYPOTHESE : "base" et "hauteur" sont des nombres reels; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() origine = turtle.pos() if F == 0 : turtle.fd(base) turtle.goto(origine[0]+base,origine[1]+hauteur) turtle.goto(origine[0],origine[1]) else: turtle.lt(90) turtle.fd(hauteur) turtle.goto(origine[0]+base,origine[1]) turtle.goto(origine[0],origine[1]) turtle.end_fill() return origine def rectangle(longueur,largeur,couleur=""): ''' OBJECTIF : tracer un rectangle METHODE : utilisation de boucle ainsi les methodes "forward" et "goto" BESOIN : "longueur" et "largeur" "couleur" CONNUS : / ENTREE : longueur et largueur SORTIE : origine RESULTAT : / HYPOTHESE : longueur et largeur sont des nombres reels; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() origine = turtle.pos() turtle.fd(largeur) turtle.goto(origine[0]+largeur,origine[1] - longueur) turtle.goto(origine[0],origine[1] - longueur) turtle.goto(origine[0],origine[1]) turtle.end_fill() return origine def losange(cote,couleur=""): ''' OBJECTIF : tracer un losange METHODE : utisation de boucle ainsi les methodes "forward" et "goto" BESOIN : "cote" "couleur" CONNUS : / ENTREE : cote SORTIE : / RESULTAT : / HYPOTHESE : cote est un nombre reel ; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() turtle.lt(45) for i in range(4): turtle.fd(cote) turtle.rt(90) turtle.end_fill() def trapeze(gbase,pbase,hauteur,couleur=""): ''' OBJECTIF : tracer un trapeze METHODE :utilisation de boucle ainsi les methodes BESOIN : "gbase" "pbase" et "hauteur" "couleur" CONNUS : / ENTREE : "gbase", "pbase", et "hauteur" SORTIE : x coordonnee x du débit de la petite base de la figure RESULTAT : / "gbase" "pbase" et "hauteur" sont des nombres reels HYPOTHESE :tous les paramtères sont des réels sauf couleur qui est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() o = turtle.pos() turtle.fd(gbase) turtle.goto(o[0]+gbase*3/4,o[1]+hauteur) turtle.goto(o[0]+gbase*1/4,o[1]+hauteur) x=turtle.pos() turtle.goto(o[0],o[1]) turtle.heading() turtle.end_fill() return x def parallelogramme(long, hauteur,angle,couleur=""): ''' OBJECTIF :tracer un parrelogramme METHODE : utilisation d'affectations de boucle ainsi que les methodes "forward", "left", "penup", et "position" BESOIN : "long" "hauteur" et "angle" "couleur" CONNUS : / ENTREE : long hauteur et angle SORTIE : x : coordonnees de x en hauteur de la figure RESULTAT : / HYPOTHESE : "long" "hauteur" et "angle" sont des nombres des reels; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() origine = turtle.pos() y=turtle.ycor() turtle.fd(long) turtle.lt(angle) turtle.penup() while (y < origine[1] + hauteur) : turtle.fd(1) y=turtle.ycor() turtle.pendown() x=turtle.xcor() turtle.goto(origine[0]+long,origine[1]) turtle.goto(+x,origine[1]+hauteur) turtle.lt(-angle) turtle.bk(long) turtle.goto(origine[0],origine[1]) turtle.end_fill() return x def polygone(long,nombre_cotes,couleur=""): ''' OBJECTIF : Tracer un polygone à n côtés METHODE : utilisation de boucle et des méthodes "forward" et "left" BESOIN : "long" et"nombre_cotes" "couleur" CONNUS : / ENTREE : "long" et "nombre_cotes" SORTIE : / RESULTAT : / HYPOTHESE : "long" et "nombre_cotes" sont des nombres reels; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() for i in range(nombre_cotes): turtle.fd(long) turtle.lt(360/nombre_cotes) turtle.end_fill() def ellipse(r,couleur="",disposition = 0): ''' OBJECTIF : Tracer une ellipse de METHODE : utilisation de boucle et des méthodes "circle" et "right" BESOIN : "r" et "disposition" (ce dernier est facultatif et indique si la figure est verticale ou horizontale) "couleur" CONNUS : / ENTREE : "r" et "disposition" SORTIE : / RESULTAT : / HYPOTHESE : "r" et "disposition" sont des nombres reels; on obtient une ellipse horizontale si "disposition" = 0 et verticale dans les autres cas; couleur est une chaîne de caractères qui désigne la couleur de remplissage des figures(c'est un paramètre facultatif) ''' turtle.fillcolor(couleur) turtle.begin_fill() if disposition == 0: turtle.right(45) else: turtle.left(45) for i in range(2): turtle.circle(r, 90) turtle.circle(r / 2, 90) turtle.end_fill() def aile_gauche(couleur=""): ''' OBJECTIF : Permet de tracer l'aile gauche de l'avion METHODE : utilisation des méthodes suivantes du modules "turtle": "fd", "rt" et "seteading" BESOINS : / CONNUS : / ENTREES : / SORTIES : / RESULTAT : / HYPOTHESE : ceci est une procedure avec des mesures prédéfinies ''' turtle.fillcolor(couleur) turtle.begin_fill() turtle.rt(25) turtle.fd(300) turtle.rt(45) turtle.fd(25) turtle.rt(120) turtle.fd(285) turtle.setheading(0) turtle.end_fill() def aile_droite(couleur=""): ''' OBJECTIF : Permet de tracer l'aile droites de l'avion METHODE : utilisation des méthodes suivantes du modules "turtle": "fd", "rt" et "seteading" BESOINS : / CONNUS : / ENTREES : / SORTIES : / RESULTAT : / HYPOTHESE : ceci est une procedure avec des mesures prédéfinies ''' turtle.fillcolor(couleur) turtle.begin_fill() turtle.lt(25) turtle.fd(300) turtle.lt(45) turtle.fd(25) turtle.lt(120) turtle.fd(285) turtle.setheading(0) turtle.end_fill() def aileron_gauche(couleur=""): ''' OBJECTIF : Permet de tracer l'aileron(queue) gauche de l'avion METHODE : utilisation des méthodes suivantes du modules "turtle": "fd", "rt" et "seteading" BESOINS : / CONNUS : / ENTREES : / SORTIES : / RESULTAT : / HYPOTHESE : ceci est une procedure avec des mesures prédéfinies ''' turtle.fillcolor(couleur) turtle.begin_fill() turtle.rt(160) turtle.fd(80) turtle.lt(65) turtle.fd(50) turtle.lt(115) turtle.fd(129) turtle.setheading(0) turtle.end_fill() def aileron_droite(couleur=""): ''' OBJECTIF : Permet de tracer l'aileron(queue) droite de l'avion METHODE : utilisation des méthodes suivantes du modules "turtle": "fd", "rt" et "seteading" BESOINS : / CONNUS : / ENTREES : / SORTIES : / RESULTAT : / HYPOTHESE : ceci est une procedure avec des mesures prédéfinies ''' turtle.fillcolor(couleur) turtle.begin_fill() turtle.rt(20) turtle.fd(80) turtle.rt(65) turtle.fd(50) turtle.rt(115) turtle.fd(129) turtle.setheading(0) turtle.end_fill()
def coder(word, key): new_word = [] a = '' alfabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] for each_chr in word: index = (alfabet.index(each_chr) + key) % 26 new_word.append(alfabet[index]) a = a.join(new_word) return a word = input('kalame ra wared konid: ') key = int(input('key ra wared konid: ')) new_word = coder(word, key) print('kalame ramz shode: ', new_word)
from q2.l2_distance import l2_distance from q2.utils import * import matplotlib.pyplot as plt import numpy as np def knn(k, train_data, train_labels, valid_data): """ Uses the supplied training inputs and labels to make predictions for validation data using the K-nearest neighbours algorithm. Note: N_TRAIN is the number of training examples, N_VALID is the number of validation examples, M is the number of features per example. :param k: The number of neighbours to use for classification of a validation example. :param train_data: N_TRAIN x M array of training data. :param train_labels: N_TRAIN x 1 vector of training labels corresponding to the examples in train_data (must be binary). :param valid_data: N_VALID x M array of data to predict classes for validation data. :return: N_VALID x 1 vector of predicted labels for the validation data. """ dist = l2_distance(valid_data.T, train_data.T) nearest = np.argsort(dist, axis=1)[:, :k] train_labels = train_labels.reshape(-1) valid_labels = train_labels[nearest] # Note this only works for binary labels: valid_labels = (np.mean(valid_labels, axis=1) >= 0.5).astype(np.int) valid_labels = valid_labels.reshape(-1, 1) return valid_labels def run_knn(): train_inputs, train_targets = load_train() valid_inputs, valid_targets = load_valid() test_inputs, test_targets = load_test() ##################################################################### # TODO: # # Implement a function that runs kNN for different values of k, # # plots the classification rate on the validation set, and etc. # ##################################################################### k_list = [1,3,5,7,9] classification_rate = [] test_rate = [] for k in k_list: valid_labels = knn(k, train_inputs, train_targets, valid_inputs) classification_rate.append(np.sum(valid_labels == valid_targets)/len(valid_labels)) test_labels = knn(k, train_inputs, train_targets, test_inputs) test_rate.append(np.sum(test_labels == test_targets)/len(test_labels)) plt.scatter(k_list, classification_rate, label="Validation"); plt.scatter(k_list, test_rate, label="Test"); plt.xlabel("Dimension"); plt.ylabel("Accuracy"); plt.title("Dimension VS Accuracy"); plt.legend(); plt.show() ##################################################################### # END OF YOUR CODE # ##################################################################### if __name__ == "__main__": run_knn()
# The super() builtin returns a proxy object # (temporary object of the superclass) that allows us # to access methods of the base class. In Python, super() # has two major use cases: allows us to avoid using # the base class name explicitly and # working with Multiple Inheritance # super is used to call the constructor , methods # and properties of parent class. You may also use the super # keyword in the sub class when you want to invoke a method # from the parent class when you have overridden it in # the subclass import logging from base.selenium_driver import SeleniumDriver from utilities import custom_logger class TestStatus(SeleniumDriver): log = custom_logger.customLogger(logging.INFO) def __init__(self,driver): ''' Inits checkpoint class Result list keeps track of all the results ''' super(TestStatus,self).__init__(driver) self.result_list=[] def set_result(self,result,result_message): try: if result is not None: if result is True: self.result_list.append('PASS') self.log.info("VERIFICATION SUCCESSFUL: "+result_message) else: self.result_list.append('FAIL') self.log.error('VERIFICATION FAILED: '+result_message) else: self.result_list.append("FAIL") self.log.error('EXCEPTION OCCURRED: '+result_message) except: self.result_list.append('FAIL') self.log.error(' ---- EXCEPTION OCCURED! ---- ') def mark(self,result,result_message): ''' Mark the result of the verification point in a test case ''' self.set_result(result,result_message) def mark_final(self,test_name,result,result_message): ''' Mark the final result of the verification point in a test case. Must be called at least once in a test case and should be a final test status of a test case. ''' self.set_result(result,result_message) if 'FAIL' in self.result_list: self.log.error(test_name+' TEST FAILED: ') self.result_list.clear() assert True == False else: self.log.info(test_name+' TEST SUCCESSFUL ') self.result_list.clear() assert True == True
print("Salom. Siz bilan Mad_Lib o'yinini o'ynaymiz.") print("Izohdagi kerakli turdagi so'zlarni kiriting!\n") while True: adj1 = input("adjective: ") noun1 = input("noun: ") pl_noun1 = input("plural noun: ") name = input("woman's name: ") adj2 = input("adjective again: ") noun2 = input("noun again: ") name2 = input("city's name: ") pl_noun2 = input("plural noun: ") adj3 = input("adjective again: ") part_of_body = input("part_of_body: ") l_of_alp = input("letter of Alphabet: ") break print() print(f"""There are many {adj1} ways to choose a {noun1} to read. First, you could ask for recommendations from your friends and {pl_noun1}. Just don't ask Aunt {name} -she only read {adj2} books. If your friends and family are no help, try checking out the {noun2}. Review in The {name2} Times. If the {pl_noun2} featured there too {adj3} for your taste, try something a little more low - {part_of_body}, like {l_of_alp}.""")
#function practice assignment #1 def factorial(n): result=[] import math result=math.factorial(n) return result factorial(5) #2 - prime number is not divisible by anything def is_prime(x): n = 2 if x < n: return 'Is not a prime number' else: while n < x: if x % n == 0: return 'Is not a prime number' break n = n + 1 else: return 'Is a prime number' is_prime(11) #part 2: q=1 def count_words(s): number_words=len(s.split()) return number_words count_words('this is a nice day') #Q=2 def count_delimited_words(s,d): number_words=len(s.split(d)) return number_words count_delimited_words(s='this is a nice day',d=' ') #Q=3 def get_list_len(wordinput,delimeter): wordlist=[] #wordinput=input('enter a string: ') #delimeter=' ' wordlist=(wordinput.split(delimeter)) #len(wordlist) for element in wordlist: print(len(element)) get_list_len(wordinput='Today is a good day',delimeter=' ') #4 def get_prime(n): for num in range(n): prime = True for i in range(2,num): if (num%i==0): prime = False if prime: print (num) get_prime(50)
''' functions used to "deal" cards into the players hand by copying the correct card pictures into a folder (static) from which the browser loads them ''' import os, shutil, re def deal(hand): # deal an entire hand of white cards, takes a list of card indices ''' for pic in os.scandir('static'): #clear the folder of white cards if re.search("card\d",str(pic)): file_path = "static/" + re.search("(card.*?png)",str(pic))[0] os.remove(file_path) ''' for index, num in enumerate(hand): #copy the new cards in shutil.copy("cards\\white\\" + num + ".png", "static\\card" + str(index + 1) + ".png") for i in range(len(hand), 7): #fill the rest of the hand with blank cards shutil.copy("cards\\white\\-1.png", "static\\card" + str(i + 1) + ".png") def deal_black(ID): # deal the new black card into the folder ''' for pic in os.scandir('static'): #clear the folder of black cards if re.search("black_card",str(pic)): file_path = "static/" + re.search("(black_card.png)",str(pic))[0] os.remove(file_path) ''' shutil.copy("cards\\black\\" + ID + ".png", #copy it over "static\\black_card.png") def test(): deal([35, 3, 7, 19, 40, 8, 100]) if __name__ == '__main__': test()
a = dict() a[1] = 1 def calculateCollatzSequenceLength(num): if (int(num) in a): return a[int(num)] if (num%2 ==0): return 1 + calculateCollatzSequenceLength(num/2) return 1 + calculateCollatzSequenceLength(3 * num + 1) maxer = 0 indOfMax = 0 for i in range(2,1000000): col_length = calculateCollatzSequenceLength(i) a[i] = col_length if (col_length > maxer): indOfMax = i maxer = col_length print(str(indOfMax) + " with length of " + str(maxer) + " is the winner")
############################################################################# # Ejemplos extraidos del libro Python 3 Text Processing with NLTK 3 Cookbook. # Referidos al capitulo 7. ############################################################################# from nltk.corpus import movie_reviews from nltk.classify.util import accuracy from nltk.classify import DecisionTreeClassifier from nltk.probability import FreqDist, MLEProbDist, entropy from featx import label_feats_from_corpus, split_label_feats, bag_of_words # featx.py debe estar en el mismo dir. print(movie_reviews.categories()) # ['neg', 'pos'] lfeats = label_feats_from_corpus(movie_reviews) print(lfeats.keys()) # dict_keys(['neg', 'pos']) train_feats, test_feats = split_label_feats(lfeats, split=0.75) print("Training Set: " + str(len(train_feats))) # Training Set: 1500 print("Test Set: " + str(len(test_feats))) # Test Set: 500 dt_classifier = DecisionTreeClassifier.train(train_feats, binary=True, entropy_cutoff=0.8, depth_cutoff=5, support_cutoff=30) print("Accuracy: " + str(accuracy(dt_classifier, test_feats))) # Accuracy: 0.688 fd = FreqDist({'pos': 30, 'neg': 10}) print(entropy(MLEProbDist(fd))) fd['neg'] = 25 print(entropy(MLEProbDist(fd))) fd['neg'] = 30 print(entropy(MLEProbDist(fd))) fd['neg'] = 1 print(entropy(MLEProbDist(fd)))
#Password Generator (Weak or strong) import random n=input('What type of password do you want? Weak or Strong ',) #User Input list1=['grapedwine','downsyndrome', 'celestialbodies','goodwills','badnames','loyalbunnies'] #random names for weak password s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?" #All Chars if n=='Weak'or n=='weak': print('Your password is :', random.choice(list1)) elif n== 'Strong' or n=='strong': print('Your password is :', "".join(random.sample(s,8)))
from abc import ABC, abstractmethod from model import Model class ModelExample(Model): def __init__(self, model_file): super().__init__(model_file) self.reset() relative_path = 'gym_maze/envs/maze_samples/' self._load_model(relative_path + model_file) def _load_model(self, fullpath): print("Load your model here with file:", fullpath) with open(str(fullpath), 'r') as f: print(list(f)) #define any other functions your search solutions need
class PriorityQueue(): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str(i) for i in self.queue]) def is_empty(self): return len(self.queue) == 0 def push(self, data, cost): for i in range(len(self.queue)): if cost <= self.queue[i][1]: self.queue = self.queue[:i] + [(data, cost)] + self.queue[i:] return self.queue = self.queue + [(data, cost)] def pop(self): if(self.is_empty()): return None return self.queue.pop(0) def update(self, data, new_cost): self.remove(data) self.push(data, new_cost) def remove(self, data): if(self.is_empty()): return for i in range(len(self.queue)): if(data == self.queue[i][0]): self.queue = self.queue[:i] + self.queue[i+1:] return def __contains__(self, key): list_of_items = [(x[0]) for x in self.queue] return (key) in list_of_items def getCost(self, key): list_of_items = [] for i in range(len(self.queue)): list_of_items.append(self.queue[i][0]) index = list_of_items.index(key) return self.queue[index][1]
class MergeSort: def mergeSort(self, arr): if len(arr) > 1: middle = len(arr) // 2 left = arr[:middle] right = arr[middle:] # Sort the first half self.mergeSort(left) # Sort the second half self.mergeSort(right) # Merge the two lists left_pointer = 0 right_pointer = 0 for i in range(0, 2 * max(len(left), len(right))): if left_pointer < len(left) and right_pointer < len(right): if left[left_pointer] <= right[right_pointer]: arr[i] = left[left_pointer] left_pointer += 1 else: arr[i] = right[right_pointer] right_pointer += 1 elif left_pointer < len(left): arr[i] = left[left_pointer] left_pointer += 1 elif right_pointer < len(right): arr[i] = right[right_pointer] right_pointer += 1 else: break return arr # Example Use sol = MergeSort() a = [9, -9, -8, 1, 2, 3, 4, 5, -5, -4, -3, -99, 267, 1/2] sorted_list = sol.mergeSort(a)
def victory(): vararray = ['Hello World!', 'Learning how to program.', 'It is always fun.','One step at a time.','This is our song.'] return vararray def initseq(): sequence = [0,1,9,0,2,3,4,0,1,9,0,2,3,4,0,1,9,0,1] #9 is a bookmark for skip a line return sequence def sing_fight_song (): myarray = victory() myseq = initseq() for i in myseq: if i == 9: #this if statement is indicating when to skip a line print('') else: print(myarray[i]) sing_fight_song ()
from random import randint doctors-prueba = dict({423: {'first_name': 'emanuel', 'last_name': 'rolon'}}) def get_keys(): for item in my_dict: print(item, "tiene el valor:", my_dict[item]) def prueba(): return [{doc[0]: {"first_name": doc[1].first_name, "last_name": doc[1].last_name}} for doc in doctors.items()] doctors = dict() read_dbterapistas() def get_doctors(self): """Retrieves list of all doctors.""" print([{doc[0]: {"first_name": doc[1].first_name, "last_name": doc[1].last_name}} for doc in self.doctors.items()]) print(self.doctors.items()) return [{doc[0]: {"first_name": doc[1].first_name, "last_name": doc[1].last_name}} for doc in self.doctors.items()]
#Write a Python program that simulates a handheld calculator. Your program should process input from the Python console # representing buttons that are “pushed,” and then output the contents ofthe screenafter each operation isperformed. # Minimally, your calculator should beable toprocess the basic arithmetic operations and a reset/clear operation. def calculator(): operation = [] while True: operand = input(': ') if operand == '=': break if operand == 'd': operation.pop() print(operation) continue if operand == 'c': operation = [] continue operation.append(operand) result = int(operation[0]) for i in range(0, len(operation)): if operation[i+1] == '+': result += int(operation[i+2]) if operation[i+1] == '-': result -= int(operation[i+2]) if operation[i+1] == '*': result *= int(operation[i+2]) if operation[i+1] == '/': result /= int(operation[i+2]) if i+3 < len(operation): i+=3 else: return result print(calculator())
#Demonstrate how to use Python’s list comprehension syntax to produce the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90]. def progression(): return list(x*(x+1) for x in range(0,10)) print(progression())
#Write a Python program that repeatedly reads lines from standard input until an EOFError is raised, # and then outputs those lines in reverse order (a user can indicate end of input by typing ctrl-D) def line_reader_and_reverser(): lines=[] while True: x= input() if x == '': break lines.append(x) lines = reversed(lines) for line in lines: print(line) line_reader_and_reverser()
# Write a set of Python classes that can simulate an Internet application in which one party, Alice, is periodically # creating a set of packets that she wants to send to Bob. An Internet process is continually checking if Alice has # any packets to send, and if so, it delivers them to Bob’s computer, and Bob is periodically checking if his computer # has a packet from Alice, and, if so, he reads and deletes it from random import randrange import time class NetworkEvent: def __init__(self, type, data ): self.EVENT_TYPES = ['packet_created', 'packet_sent', 'packet_recieved'] if type not in self.EVENT_TYPES: raise TypeError('{} is not a valid type'.format(type)) self._type = type self._data = data def __repr__(self): return 'NetworkEvent->(type:{} | data:{})'.format(self._type, self._data) class Network: def __init__(self): self._events = [] self._clients = [] def add_network_event(self, event): self._events.append(event) def send_packet(self, packet): recipient = packet._recipient recipient._messages.append(packet) # self._events.append(NetworkEvent('packet_sent',packet)) def resolve_packets(self): for i,event in enumerate(self._events): if event._type == 'packet_created': self.send_packet(event._data) self._events.pop(i) class Packet: def __init__(self, data, sender, recipient): self._sender = sender self._recipient = recipient self._data = data def __repr__(self): return 'Packet->(data:{} | sender:{} | recipient:{})'.format(self._data, self._sender, self._recipient) def data(self): return self._data def recipient(self): return self._recipient class Client: def __init__(self, name): self._name = name self._packets = [] self._messages = [] self._network = None def __repr__(self): return 'Client->({})'.format(self._name) def join_network(self, network: Network): self._network = network network._clients.append(self) #methods def create_packet(self, data, recipient): packet = Packet(data, self, recipient) self._packets.append(packet) self._network.add_network_event(NetworkEvent('packet_created',packet)) def periodically_generate_packets(self,period, cycles): data = '' recipient = '' for _ in range(cycles): count = randrange(2,10) for _ in range(count): self.create_packet(data, recipient) print('packet generated') time.sleep(period) @staticmethod def read_message(message): print('oh, I have a message') time.sleep(1) print("I'm done!") def check_messages(self): if len(self._packets) == 0: print('Aww, No Messages. No one cares about me') else: for message in self._messages: self.read_message(message) def server(): alice = Client('Alice') bob = Client('Bob') network = Network() alice.join_network(network) bob.join_network(network) bob.create_packet('wqeqedwvwvwc', alice) alice.create_packet('wqeqedwc', bob) bob.create_packet('wqeqedwvwvwc', alice) alice.create_packet('wqeqedwc', bob) network.resolve_packets() print (network._events) print(alice._messages, bob._messages) print (network._events) server()
#Demonstrate how to use Python’s list comprehension syntax to produce the list [ a , b , c , ..., z ], # but without having to type all 26 such characters literally. print(list(chr(97+a) for a in range(0,26)))
#Write a short Python function that takes a sequence of integer values and determines if there is a distinct pair # of numbers in the sequence whose product is odd. def odd_product_pair(data): data = set(data) for i in data: for j in data: if i == j : continue if i*j % 2 == 1: return True return False print(odd_product_pair([2,4,6,8,9,10]))
""" map built-in function applies a function to items in a sequence and collects all the results in a new list. list(map(abs,[-1,2,0,1,2])) """ if __name__ == '__main__': n = int(input()) input_line = input() integer_list = map(int, input_line.split()) t = tuple(integer_list) print(hash(t))
a = int(input('how many students in the class:')) list_score = [] name = [] for i in range(a): name_input = input('insert your name:') score =int(input('insert test score:')) if score not in list_score: list_score.append(score) name.append(name_input) highest = 0 for score in range(a): if list_score[score] > highest: highest = list_score[score] high_name = name[score] print('highest score',highest,high_name) lowest = 100 for score in range(a): if list_score[score] < lowest: lowest = list_score[score] low_name = name[score] print('lowest score',lowest,low_name) sum_score = sum(list_score) print('class average:',sum_score/a)
# ADD IMPORTS HERE def calculate_distance(x1, x2): """Returns the distance between m-dimensional points x1 and x2. """ # ADD IMPLEMENTATION HERE def find_neighbor_indices(X, query): """Returns 1-dimensional numpy array of shape (m,) where each value is the argsort of the distance. See numpy's argsort(). Parameters: X - numpy array of shape (m, n) where each row represents a data point and each column represents a feature query - numpy array of shape (m, 1) Example: X = np.array([[3, 1], [6, 2], [6, 6]]) query = np.array([8, 10]) find_neighbor_indices(X, query) returns np.array([2, 1, 0]). """ # ADD IMPLEMENTATION HERE
import json # as requested in comment tester = {"one": 1, "two": 2} with open('file.txt', 'w') as file1: file1.write(json.dumps(tester)) # use `json.loads` to do the reverse with open('file.txt', 'r') as file2: test1 = json.loads(file2.readline()) # test1 = json.loads('file.txt') print(test1) print(test1['one'])
a = [['yellow_hat', 'headgear'], ['blue_sunglasses', 'eyewear'], ['green_turban', 'headgear']] # should return 5 b = [['crow_mask', 'face'], ['blue_sunglasses', 'face'], ['smoky_makeup', 'face']] def solution(clothes): total_per_kind = {} # keep track of counts per each kind of clothes for kind in clothes: if kind[1] not in total_per_kind: total_per_kind[kind[1]] = 1 else: total_per_kind[kind[1]] += 1 # since you can either wear a kind of cloth or not wear one # add one to each kind of clothes for i in total_per_kind: total_per_kind[i] += 1 # calculate total possible scenario by multiplying them together answer = 1 for i in total_per_kind: answer *= total_per_kind[i] return answer - 1 # take one scenario off which is not wearing any kind of clothes print(solution(a)) print(solution(b))
''' 14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Note: All given inputs are in lowercase letters a-z. ''' class Solution: def longestCommonPrefix(self, strs): if not strs: return "" if len(strs) == 1: return strs[0] strs.sort() p = '' for i, j in zip(strs[0], strs[-1]): if i == j: p += i else: break return p print(Solution.longestCommonPrefix(Solution,["flow", "foower", "flight"]))
import heapq def solution(scoville, K): answer = 0 # k is target scoville # the goal is to make every scoviile list above K by mixing them # new_scoville = old_scoville(lower one) + (old_scoville(higher one) * 2) heapq.heapify(scoville) while len(scoville) > 1 and scoville[0] < K: a = heapq.heappop(scoville) b = heapq.heappop(scoville) heapq.heappush(scoville, a + (b*2)) answer += 1 if scoville[0] < K: return -1 else: return answer s = [1,2,3,9,10,12] k = 7 print(solution(s,k)) # should return 2
""" An Upper triangular matrix is a square matrix (where the number of rows and columns are equal) where all the elements below the diagonal are zero. For example, the following is an upper triangular matrix with the number of rows and columns equal to 3. 1 2 3 0 5 6 0 0 9 Write a program to convert a square matrix into an upper triangular matrix. Input Format: The first line of the input contains an integer number n which represents the number of rows and the number of columns. From the second line, take n lines input with each line containing n integer elements. Elements are separated by space. Output format: Print the elements of the matrix with each row in a new line and each element separated by a space. Example 1: Input: 3 1 2 3 4 5 6 7 8 9 Output: 1 2 3 0 5 6 0 0 9 Example 2: Input: 4 12 2 5 6 10 11 4 1 32 1 4 10 1 2 10 9 Output: 12 2 5 6 0 11 4 1 0 0 4 10 0 0 0 9 Explanation: In both the examples, elements which are below the diagonal are zero. """ #CODE: n = int(input()) arr = [] while True: try: num = input().split() except EOFError: break arr.append(num) for i in range(n): for j in range(n): if (i > j): arr[i][j]="0" for i in range(n): for j in range(n): if(j < n-1): print(arr[i][j],end=" ") else: print(arr[i][j])
""" Arun is working in an office which is N blocks away from his house. He wants to minimize the time it takes him to go from his house to the office. He can either take the office cab or he can walk to the office. Arun's velocity is V1 m/s when he is walking. The cab moves with velocity V2 m/s but whenever he calls for the cab, it always starts from the office, covers N blocks, collects Arun and goes back to the office. The cab crosses a total distance of N meters when going from office to Arun's house and vice versa, whereas Arun covers a distance of (√2)*N while walking. Help Arun to find whether he should walk or take a cab to minimize the time. Input Format: A single line containing three integer numbers N, V1, and V2 separated by a space. Output Format: Print 'Walk' or 'Cab' accordingly Constraints: 1<=V1, V2 <=100 1<=N<=200 Example-1: Input: 5 10 15 Output: Cab Example-2: Input: 2 10 14 Output: Walk """ #CODE: import math N, V1, V2 = input().split(' ') if int(V1)>=1 and int(V2)<=100 and int(N) <= 200 and int(N) >= 1: T1=(math.sqrt(2)*int(N))/int(V1) T2=int(N)/int(V2) if int(T1)>int(T2): print('Cab') else: print('Walk')
""" In this assignment, you will have to take two numbers as input and print the difference. Input Format: The first line of the input contains two numbers separated by a space. Output Format: Print the difference in single line Example: Input: 4 2 Output: 2 Explanation: Since the difference of numbers 4 and 2 is 2, hence the output is 2. """ #CODE: var1, var2 = input().split(' ') print(int(var1)-int(var2))
# -*- coding: utf-8 -*- """implement a polynomial basis function.""" import numpy as np def build_poly(x, degree): """polynomial basis functions for input data x, for j=0 up to j=degree.""" # *************************************************** expand=np.ones((x.shape[0],1)) for i in range(1,degree+1): expand=np.hstack((expand,x.reshape((-1,1))**i)) # *************************************************** return expand
# # def countBreakpoints(sequence): """ stepik.org/lesson/43282/step/1?unit=21346 rosalind.info/problems/ba6b/# """ length = len(sequence) assert length > 0 pairs = [None] * (length + 1) pairs[0] = (0, sequence[0]) pairs[-1] = (sequence[-1], length + 1) for i in range(length - 1): pairs[i + 1] = (sequence[i], (sequence[i + 1])) # print(pairs) differences = [None] * len(pairs) for i, pair in enumerate(pairs, start=0): differences[i] = pair[1] - pair[0] # print(differences) answer = 0 for diff in differences: if diff != 1: answer += 1 return answer def countBreakpoints2(sequence): """ stepik.org/lesson/43282/step/1?unit=21346 rosalind.info/problems/ba6b/# """ npairs = len(sequence) + 1; assert (npairs) > 1 pairs = [(0, sequence[0])] for i in range(npairs - 2): pairs.append( (sequence[i], (sequence[i + 1])) ) pairs.append((sequence[-1], npairs)) # print(pairs) differences = [pair[1] - pair[0] for pair in pairs] # print(differences) return npairs - differences.count(1) def countBreakpoints3(sequence): """ stepik.org/lesson/43282/step/1?unit=21346 rosalind.info/problems/ba6b/# """ length = len(sequence); assert (length) > 1 answer = 0 if sequence[0] == 1 else 1 for i in range(length - 1): if sequence[i + 1] - sequence[i] != 1: answer += 1 return answer + 1 if sequence[-1] != length else answer def countBreakpoints4(sequence): """ stepik.org/lesson/43282/step/1?unit=21346 rosalind.info/problems/ba6b/# """ return sum(map(lambda x,y: x - y != 1, sequence + [len(sequence) + 1], [0] + sequence)) def main(): dataset = '(+3 +4 +5 -12 -8 -7 -6 +1 +2 +10 +9 -11 +13 +14)' sequence = [int(n) for n in dataset[1:-1].split(' ')] assert sequence == [3, 4, 5, -12, -8, -7, -6, 1, 2, 10, 9, -11, 13, 14] print(countBreakpoints(sequence)) print(countBreakpoints2(sequence)) print(countBreakpoints3(sequence)) print(countBreakpoints4(sequence)) if __name__ == '__main__': main()
import random # Generating numbers for sorting def data_set(count): tab_u = [] # unsorted tab for i in range(count): tab_u.append(random.randint(0, 1000)) return tab_u # Bubble def bubble_sort(tab): for i in range(len(tab) - 1): for j in range(len(tab) - 1): if tab[j] > tab[j + 1]: temp = tab[j] tab[j] = tab[j + 1] tab[j + 1] = temp return tab # TODO Insertion def insertion_sort(tab): for j in range(1, len(tab)): for i in range(j): print("") # Main tab_unsort = data_set(10) print(bubble_sort(tab_unsort))
from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: m = 0 res = -9999999999 for num in nums: m = num + m if res > 0 else num + 0 res = max(res, m, num) if res > 0 >= m: m = num if num > 0 else 0 return res solution = Solution() print(solution.maxSubArray([-2, 3, 1]))