text
stringlengths
37
1.41M
numbers = [int(n) for n in input().split()] average = sum(numbers) // len(numbers) top_5 = [] for n in numbers: if n > average: top_5.append(int(n)) if len(top_5) > 1: a = list(reversed(sorted(top_5))) print(*a[:5]) else: print(f'No')
rooms = int(input()) free_chairs = 0 if_enough = True for room in range(1, rooms+1): each_room = input().split() chairs = each_room[0] people_taken_places = int(each_room[1]) if len(chairs) == people_taken_places: continue elif len(chairs) > people_taken_places: free_chairs += len(chairs) - people_taken_places else: if_enough = False print(f'{people_taken_places - len(chairs)} more chairs needed in room {room}') if if_enough: print(f'Game On, {free_chairs} free chairs left')
a = int(input()) b = int(input()) c = int(input()) def smallest_of_number(a, b, c): smallest_number = 0 if a <= b and a < c: smallest_number = a elif b <= a and b <= c: smallest_number = b else: smallest_number = c return smallest_number print(smallest_of_number(a, b, c))
# LAB 1 # 1.1 Part A temperature_F = float(input("Please enter the temperature in Fahrenheit: ")) temperature_C = (temperature_F - 32) * 5/9 print("The temperature in Celsius is", temperature_C) # 1.2 Part B height = float(input("Please enter the height of the trapezoid: ")) bottom = float(input("Please enter the length of the bottom base of the trapezoid: ")) top = float(input("Please enter the length of the top base of the trapezoid: ")) area = 0.5*(bottom+top)*height print("The area of the trapezoid is", area) # 1.3 Part C distance = input("Please insert the total number of KMs traveled: ") distance = float(distance) time_min = float(input("Please insert the total number of minutes traveled: ")) hours = time_min/60 speed = int(distance / hours) print("You were traveling at an average speed of", speed, "km//h.")
a=int(input()) if 100 >= a >=90:print('A') elif 90 > a>=80:print('B') elif 80 > a>=70:pirnt('C') elif 70 > a>=60:print('D') elif 60 > a >= 0:print('F') print('FFFFFFDCBAA'[a//10])
#listing 4-26 def step_to(factor, stop): step = factor start = 0 while start <= stop: yield start start += step for x in step_to(2, 10): print(x)
#Listing 4-39 #Decorators enhances the action of the function that they decorate #We have the ability to change the inner-working of the function without #adjusting the original decorated function at all def plus_five(func): def inner(*args, **kwargs): x = func(*args, **kwargs) + 5 return x return inner @plus_five def add_nums(num1, num2): return num1 + num2 print(add_nums(2,3)) print(add_nums(2,6))
""" The camera module is used to calculate positions of everything thats going on a map. Use this pygame.rect to draw everything in relative positions to the tracked object's position. """ # dependencies from .utils import validateDict import pygame as pg # classes class Camera(pg.Rect): """ The camera is used for correctly draw everything on the window screen. You should use the camera as position agrument to draw a map, layer or just everything that's static and not really moving. The 'getRectOf' method acts exactly the same way except it's for everything thats non-static and CAN move like player, npcs and so on. """ # default values default = { "size": (640, 480), "position": (0, 0), "border": None, "track": None, "zoomfactor": 1 } def __init__(self, config={}): """Constructor.""" self.config = validateDict(config, self.default)# dict pg.Rect.__init__(self, self.config["position"], self.config["size"]) self.tracking = self.config["track"]# none / entity self.zoomfactor = self.config["zoomfactor"]# int def __str__(self): """String representation.""" return "<Camera({0}, {1}, {2}, {3})>".format( self.left, self.top, self.width, self.height, ) def update(self): """Update the camera with each tick.""" if self.tracking: self.left = -(self.tracking.rect.center[0] - int(self.width / 2)) self.top = -(self.tracking.rect.center[1] - int(self.height / 2)) def getRectOf(self, entity): """ Recalculate the position of the given entity on the map and return it in a pygame.rect, so one can use that rect to finally draw the entity in right place on the map. """ return pg.Rect( entity.rect.left + self.left, entity.rect.top + self.top, entity.rect.width, entity.rect.height ) def zoom(self, factor): """ Change the zoomfactor of the camera rect. Doesn't change the camera size. """ if self.zoomfactor + factor < 1: self.zoomfactor = 1 elif self.zoomfactor + factor > 3: self.zoomfactor = 3 else: self.zoomfactor = self.zoomfactor + factor
"""find the median of two sorted arrays: median is the number which in the middle number of a sequence of sorted numbers (x) if len(x) is odd, the median is kth value, k = (len(x) + 1) / 2 if len(x) is even, the median is (x[len(x)/2] + x[len(x)/2+1]) / 2 author: Yi Zhang <beingzy@gmail.com> date: 2018/04/14 """ def merge_two_sorted(x, y): """assume x and y are both sorted in ascending order """ x, y = x[:], y[:] if y[0] > x[-1]: return x + y elif y[-1] < x[0]: return y + x else: start_idx = 0 while len(y) > 0: for i in range(start_idx, len(x)): if y[0] < x[i]: val = y.pop(0) x.insert(i, val) start_idx = i + 1 elif i == len(x) - 1: return x + y if len(y) == 0: break return x def find_median_of_two_sorted(x, y): seq = merge_two_sorted(x, y) n = len(seq) if n % 2 == 1: med_idx = int((n+1)/2) - 1 return seq[med_idx] else: right_idx = int(n/2) left_idx = right_idx - 1 return (seq[left_idx] + seq[right_idx]) / 2.0 def test_merge_two_sorted_01(): x = [10, 12, 15, 16] y = [9, 13, 17] ans = [9, 10, 12, 13, 15, 16, 17] res = merge_two_sorted(x, y) assert res == ans def test_merge_two_sorted_02(): x = [10, 12, 15, 16] y = [1, 2] ans = [1, 2, 10, 12, 15, 16] res = merge_two_sorted(x, y) assert res == ans def test_merge_two_sorted_03(): x = [10, 12, 15, 16] y = [17] ans = [10, 12, 15, 16, 17] res = merge_two_sorted(x, y) assert res == ans def test_median01(): x = [5, 8, 10, 11] y = [6, 7, 12] return find_median_of_two_sorted(x, y) == 10 if __name__ == "__main__": test_merge_two_sorted_01() test_merge_two_sorted_02() test_merge_two_sorted_03() test_median01()
"""create a function to return n-th fibonacci number """ def fib(n): if n == 1 or n == 2: return 1 else: return fib(n-1) + fib(n-2) def dynamic_fib(n): """dynamic programming implementation of fib() """ raise NotImplementedError
favorite_foods = [] #Start a loop to ask user to enter their favorite foods repeat = True while repeat == True: food = input("Please enter a favorite food or 'done' to end input: ").strip().lower() #Check if user has entered done so that loop can be stopped if so if food == 'done': repeat = False else: #Check if food is already in list count = favorite_foods.count(food) #If so, give user error message, otherwise add the food and give success message if count > 0: print("Sorry {} is already on the list!".format(food)) else: favorite_foods.append(food) print("{} has been added!".format(food)) #Once user is done, print out their list for them print("Your favorite foods are: ") for food in favorite_foods: print(food.title()) #Add a capital letter
class Trie: '''Reperesents a Trie data structure''' def __init__(self): self.root = dict() def add(self,s): ### Defining a helper method def add_helper(s): if s == "": return {"" : None} return {s[0] : add_helper(s[1:])} ### Implementing the method 'add' if not isinstance(s, str): raise TypeError('"add" method only takes a string as input.') if len(s) ==0: raise ValueError('An empty string cannot be added to the Trie object.') x = self.root i = 0 while True: if i == len(s): x[''] = None break elif s[i] not in x: x[s[i]] = add_helper(s[i+1:]) break x = x[s[i]] i +=1 def contains(self, s): ### Defining a helper method def contains_helper(s,d): if s[0] not in d: return False else: if len(s)==1: if('' in d[s[0]]): return True else: return False else: return contains_helper(s[1:], d[s[0]]) ### Implementing the method 'contains' d = self.root if not isinstance(s, str): raise TypeError('Please enter a string as input.') if len(s) == 0: raise ValueError('An empty string is not valid.') else: return contains_helper(s,d) def __repr__(self): return "%s" % self.root def wordlist2trie(data): t = Trie() ### Error checking if type(data)!= type([]): raise TypeError('This function only takes a list of strings as input.') if not all(isinstance(i, str) for i in data): raise TypeError('All the elements in the input list must be strings.') ### for i in data: t.add(i) return t import urllib.request import re url = 'http://www.greenteapress.com/thinkpython/code/words.txt' request = urllib.request.urlopen(url) response = request.read().decode('utf-8') words = re.findall(r'\w+', response)
class Luhn: @classmethod def checkdigit(cls, card_number): """ checks to make sure that the card passes a luhn mod-10 checksum """ _sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for i in range(0, num_digits): try: digit = int(card_number[i]) except ValueError: return False if not ((i & 1) ^ oddeven): digit = digit * 2 if digit > 9: digit = digit - 9 _sum = _sum + digit return (_sum % 10) == 0
''' Read, combine and write excel sheets with pandas Just a test script ''' import pandas as pd # Read the input excel files seen = pd.read_excel('pandas_in.xlsx', sheet_name='seen', index_col='license') owners = pd.read_excel('pandas_in.xlsx', sheet_name='owners', index_col='license') # Create a result from seen and owners all = seen.join(owners) print(all) # Write everything to a multisheet excel file with pd.ExcelWriter('pandas_out.xlsx') as writer: all.to_excel(writer, sheet_name='All') seen.to_excel(writer, sheet_name='Seen') owners.to_excel(writer, sheet_name='Owners')
# ------------------------Download and read MNIST data-------------------------- from tensorflow.examples.tutorials.mnist import input_data # mnist is a lightweight class that stores training, validation and testing sets # as NumPy arrays. Also provides function for iterating through data # minibatches mnist = input_data.read_data_sets('./../MNIST_data', one_hot=True) # ---------------------Start TensorFlow InteractiveSession---------------------- import tensorflow as tf sess = tf.InteractiveSession() # Allows more flexible structuring of code # -------------------------Placeholders and Variables--------------------------- # Create placeholder nodes for input images and target classes x = tf.placeholder(tf.float32, shape=[None, 784]) # 28*28 image linearized y_ = tf.placeholder(tf.float32, shape=[None, 10]) # digit class (0 to 9) # Define weights W and biases b (provides initial values, tensors full of zeros) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) # Creates the Saver object whose restore() function we will use later saver = tf.train.Saver() # Initialize all variables (W and B here) before using them within session sess.run(tf.global_variables_initializer()) # Implement linear regression model (output = input images * weights + bias) y = tf.matmul(x, W) + b # restore the previously saved model. #notrainingrequired saver.restore(sess, './savefiles/my-model') # -----------------------------Evaluating the Model----------------------------- # Checks whether the output y matches the target y_. Gives a list of booleans. correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) # Convert booleans to floats and take the mean to get accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("Test accuracy %g%%" % (accuracy.eval(feed_dict={ x: mnist.test.images, y_:mnist.test.labels})*100))
m = int(0) x = int(input ("Digite um número: ")) m = m+1 x = x+ int(input ("Digite um numero: ")) m = m+1 x = x+ int(input ("Digite um numero: ")) m = m+1 print ("Soma total : ",x) Media = x/m print ("média : ",Media) print ("Deu certo")
import os import re def get_filenames(): folder = "./prank_after" all_files = os.listdir(folder) # current directory print all_files def rename_files(): print "Inside rename_files" # 1) Get file names from folder folder = "./prank_after" all_files = os.listdir(folder) # current directory # 2) Iterate over each file for each_file_name in all_files: # 3) Get the name of the file oldName = each_file_name # 4) Remove numbers # In the demo, they use the string translate() method. newName = "".join(re.findall("[a-zA-Z\.]+", oldName)) # 5) Rename file to new name print oldName + " " + newName os.rename(os.path.join(folder, oldName), os.path.join(folder, newName)) # rename_files(); get_filenames()
from tkinter import * import random class Window(): def __init__(self): self.WIDTH = 800 self.HEIGHT = 600 self.block_size = 20 self.IN_GAME = True self.root = Tk() self.c = Canvas(self.root, width=self.WIDTH, height=self.HEIGHT, bg="#819ca3") def create_window(self): self.root.title("The best snake") self.c.grid() self.c.focus_set() self.root.mainloop() class Game(Window): def __init__(self): Window.__init__(self) self.access = True self.block_size = 20 self.block = self.c.create_rectangle(2*self.block_size, 0, 3*self.block_size, self.block_size, \ fill='#eba80e') self.root.bind('<Up>', lambda event, dir1 = 0, dir2 = -1 : self.bind_move(event, dir1, dir2)) self.root.bind('<Down>', lambda event, dir1 = 0, dir2 = 1 : self.bind_move(event, dir1, dir2)) self.root.bind('<Right>', lambda event, dir1 = 1, dir2 = 0 : self.bind_move(event, dir1, dir2)) self.root.bind('<Left>', lambda event, dir1 = -1, dir2 = 0 : self.bind_move(event, dir1, dir2)) self.run = self.root.after(500, lambda dir1 = 1, dir2 = 0 : self.moving(dir1, dir2)) self.block1 = self.c.create_rectangle(self.block_size, 0, 2*self.block_size, self.block_size, \ fill='#eba80e') self.block2 = self.c.create_rectangle(0, 0, self.block_size, self.block_size, fill='#eba80e') self.block_list = [self.block, self.block1, self.block2] self.apple_block = self.create_apple() def moving(self, dir1, dir2): # змея двигается до тех пор, пока доступ разрешён if self.access == True: # перебираем все сегменты змеи с конца до головы (не включительно) for i in range(len(self.block_list)-1, 0, -1): # запоминаем координаты следующего блока x1 = self.c.coords(self.block_list[i-1])[0] y1 = self.c.coords(self.block_list[i-1])[1] # создаем новый блокт на том месте, координаты которого мы уже получили new_block = self.c.create_rectangle(x1, y1, x1 + self.block_size, y1 + \ self.block_size, fill='#eba80e') # удаляем старый блок self.c.delete(self.block_list[i]) # обновляем координаты блока в листе сегментов змеи self.block_list[i] = new_block # c.move двигает блок головы в заданном направлении self.c.move(self.block, dir1 * self.block_size, dir2 * self.block_size) # заставляет повторить функцию передвижения змеи self.eating() self.access_to_move() self.run = self.root.after(250, lambda dir1 = dir1, dir2 = dir2 : self.moving(dir1, dir2)) def bind_move(self, event, dir1, dir2): self.root.after_cancel(self.run) self.moving(dir1, dir2) def create_apple(self): x1 = random.randrange(0, self.WIDTH, self.block_size) y1 = random.randrange(0, self.HEIGHT, self.block_size) access_to_create = True for i in range(len(self.block_list)): if x1 == self.c.coords(self.block_list[i])[0] and \ y1 == self.c.coords(self.block_list[i])[1]: access_to_create = False if access_to_create == True: return self.c.create_rectangle(x1, y1, x1 + self.block_size, y1 + self.block_size, \ fill="#ad0309") else: self.create_apple() def add_block(self): x1 = self.c.coords(self.block_list[-1])[0] y1 = self.c.coords(self.block_list[-1])[1] new_block = self.c.create_rectangle(x1, y1, x1 + self.block_size, y1 + self.block_size, \ fill="#eba80e") self.block_list.append(new_block) def eating(self): if self.c.coords(self.block)[0] == self.c.coords(self.apple_block)[0] and \ self.c.coords(self.block)[1] == self.c.coords(self.apple_block)[1]: self.c.delete(self.apple_block) self.apple_block = self.create_apple() self.add_block() def access_to_move(self): for i in range(1, len(self.block_list)): if self.c.coords(self.block)[0] == self.c.coords(self.block_list[i])[0] and \ self.c.coords(self.block)[1] == self.c.coords(self.block_list[i])[1]: self.access = False if self.c.coords(self.block)[0] == self.WIDTH or \ self.c.coords(self.block)[1] == self.HEIGHT or self.c.coords(self.block)[0] < 0 \ or self.c.coords(self.block)[1] < 0: self.access = False def main(): snake = Game() snake.create_window() if __name__ == "__main__": main()
#2.To count the unique words in a file(use set) # f=open("a_new.txt","w") # f.write("one two two") # f.close() # # f=openf=open("a_new.txt","r") # data=f.read() # print(data) unique = set(["one","two","two","three","three"]) print(len(unique))
# #print ([i if i%2==0 else "Odd" for i in range(10)]) # #print ([ letter for letter in 'Python class' ]) # # #iterator # a=[2,4,5,7] # i=iter(a) # print(next(i)) # print(next(i)) # # class Hotel(): # def__init__(self) # self.menu=['assad','bdas','cftsrf'] # self.index=-1 # def__iter__(self) # return self # def__next__(self) # self.index+=1 # if self.index>=len(self.menu): # raise:StopIteration # return self.menu[self.index] # for in in hotel() # print(i) # # # #yield(generator) # def fact(n): # f=1 # for i in range(1,n+1): # f=f*i # yield f # for i in fact(5): # print(i) num=[34,66,23,2,5] z=list(map(lambda x:x%2==0,num)) print(z)
import time from threading import Thread #-----------------------------------------------------Sort Class------------------------------------------------------ class Sort(Thread): def __init__(self, func, name): Thread.__init__(self) self.func = func self.name = name def read_from_file(self): for i in range(1, 1000, 100): min_num = i max_num = i + 100 - 1 my_list = list() with open("Random.txt") as f: reader = f.readline() while reader is not None and len(reader) != 0: reader_int = int(reader) if min_num <= reader_int <= max_num: my_list.append(reader_int) reader = f.readline() yield my_list def write_to_file(self, elements, alg_name): direct = alg_name + ".txt" with open(direct, mode="a") as f: for i in elements: f.write(str(i) + "\n") def iterate_and_sort(self): global init_time for elements in self.read_from_file(): self.func(elements) self.write_to_file(elements, self.name) with open("duration.txt", mode="a") as f: final_time = time.perf_counter() duration = final_time - init_time f.write("Algorithm <" + self.name + "> took " + str(duration) + " seconds to finish\n") def run(self): self.iterate_and_sort() #-----------------------------------------------------------Merge Sort-------------------------------------------------- def merge_sort(elements): if(len(elements)>1): mid = len(elements)//2 L=elements[:mid] R=elements[mid:] merge_sort(L) merge_sort(R) i,j,k=0,0,0 while(i<len(L) and j<len(R)): if L[i]<R[j]: elements[k]=L[i] i+=1 else: elements[k]=R[j] j+=1 k+=1 while(i<len(L)): elements[k] = L[i] i+=1 k+=1 while(j<len(R)): elements[k]=R[j] j+=1 k+=1 #-----------------------------------------------------------Shell Sort-------------------------------------------------- def shell_sort(elements): n = len(elements) gap = n//2 while gap > 0: for i in range(gap,n): temp = elements[i] j = i while j >= gap and elements[j-gap] >temp: elements[j] = elements[j-gap] j -= gap elements[j] = temp gap //= 2 #-----------------------------------------------------------Bubble Sort------------------------------------------------- def bubble_sort(elements): for i in range(0,len(elements)): for j in range(0,len(elements)-i-1): try: if not(elements[j]<elements[j+1]): elements[j] , elements[j+1] = elements[j+1] , elements[j] except: continue #-----------------------------------------------------------Selection Sort---------------------------------------------- def selection_sort(elements): for i in range(0, len(elements)): min_index = i for j in range(i + 1, len(elements)): if elements[min_index] > elements[j]: min_index = j elements[i], elements[min_index] = elements[min_index], elements[i] #-----------------------------------------------------------Comb Sort------------------------------------------------- def comb_sort(elements): def getNextGap(gap): # Shrink gap by Shrink factor gap = (gap * 10) / 13 if gap < 1: return 1 return gap n = len(elements) # Initialize gap gap = n # Initialize swapped as true to make sure that # loop runs swapped = True # Keep running while gap is more than 1 and last # iteration caused a swap while gap != 1 or swapped == 1: # Find next gap gap = int(getNextGap(gap)) # Initialize swapped as false so that we can # check if swap happened or not swapped = False # Compare all elements with current gap for i in range(0, n - gap): if elements[i] > elements[i + gap]: elements[i], elements[i + gap] = elements[i + gap], elements[i] swapped = True #-----------------------------------------------------------Main-------------------------------------------------------- def main(): global init_time init_time=time.perf_counter() t1=Sort(merge_sort,"Merge_Sort") t2=Sort(shell_sort,"Shell_Sort") t3=Sort(comb_sort,"Comb_Sort") t4=Sort(selection_sort,"Selection_Sort") t1.start() t2.start() t3.start() t4.start() if __name__ == '__main__': main()
import os as system from time import * class menu(): def men(): print("Witaj w moim notatniku!") print("[1] Zapisać") print("[2] Odczytać") odpowiedz = input("Napisz tutaj ---> ") zapisywanie class kot(): def zapisywanie(): if menu.odpowiedz == "zapisać": print("Okej teraz napisz poniżej co chcesz zapisać i naciśniej później ENTER") notatka = input("Napisz tu ----> ") print("Teraz napisz na dole jaką chcesz nazwe pliku") nazwa = input("Napisz tutaj ----> ") plik = open(f"{nazwa}.txt", "w") plik.write(notatka) print("twój plik powinien być zapisany w lokalizacji aplikacji") sleep(5) def odczytywanie(): if menu.odpowiedz == "odczytać": print("Okej potrzebuje kilku danych do tej operacji...") print("[1] lokalizacja pliku ") lokalizacja = input("Napisz tu ---> ") print("[2] Nazwa pliku z rozszerzeniem") ppnazwa = input("Napisz tutaj nie użając spacji ---> ") kot = open(lokalizacja + ppnazwa, "a") with open(lokalizacja + ppnazwa) as f: lines = f.readlines() print(lines) sleep(5) print("Chcesaz edytować tą notatke ?") edytowanie = input("Napisz tutaj ----> ") if edytowanie == "Tak": print("Chcesz usunąć całą treść tego pliku?") usunięcie = input("Napisz tutaj ---> ") if usunięcie == "Tak": koto = open(lokalizacja + ppnazwa, "w") print("Napisz poniżej co chcesz zapisać") zmiana = input("Napisz tutaj ---> ") sleep(2) kot.write(" " + zmiana) print("Plik został zapisany") sleep(10) if usunięcie == "Nie": print("Napisz poniżej co chcesz zapisać") zmiana = input("Napisz tutaj ---> ") kot.write(" " + zmiana) print("Plik został zapisany") sleep(10) if edytowanie == "Nie": print("Okej to teraz podaj mi za ile sekund mam się sam wyłączyć") czas = input("Napisz tutaj ---> ") print("OK") sleep(czas)
name = input("enter a name:") marks = input ("enter a marks:") print("name:{} \nmarks:{}".format (name,marks))
import sys class Ipv4Address(): def __init__(self): self.octets = 4 self.max_of_octets = 3 #maximum number of digits of a single octet self.min_of_octets = 1 #minimum number of digits of a single octet self.notation = "." #dot notation is always used in IP address self.max_notations = 3 # IP address have only 3 dot notations self.max_bits = 255 # each octet in an IP address cannot have over 255 bits def ipv4format(self): #just display attributes of a good Ipv4 address print("A good IPv4 address ALWAYS has:") print("\n- ONLY 4 octets.") print("- ONLY 3 dot notations.") print("- No more than 255 bits in each octet.") def check_ip_format(self, ip_address): if ip_address.count(self.notation) < self.max_notations: #checking minimum number of notations print("\n--------------ERROR------------!") print("Your Ipv4 Address is too short!") sys.exit() elif ip_address.count(self.notation) > self.max_notations: # checking maximum number of notations print("\n-------------ERROR-----------!") print("Your Ipv4 Address is too long!") sys.exit() else: first_octet, second_octet, third_octet, fourth_octet = ip_address.split(".") # splitting the Ip address into four octets using the dot notations to split. octets = [first_octet, second_octet, third_octet, fourth_octet] # appending the four octets into a single list of octets..... #for purposes of looping thus less code for octet in octets: # looping through the list of octets if len(octet) > self.max_of_octets: #checking number of digits in a single octet print("\n----------------ERROR--------------!") print("Invalid number of digits in ",octet) sys.exit() elif int(octet) > self.max_bits: #checking maximum number of bits in a single octet print("\n----------------ERROR--------------!") print("The octet",octet,"has over 255 bits!") sys.exit() elif octet not in range(0,255): print("ERROR IN OCTET DIGIT",octet) else: pass print("\n-----------------------------PASS--------------------------!") #if the IP address has no errors so far.... print("Your IPv4 Address is validated and is in the correct format!")#....this two messages get printed if __name__ == "__main__": ipv4 = Ipv4Address() #no..... ipv4.ipv4format() #need.... user_ip = input("\n\nEnter your Ipv4 Address: ")#....to explain ipv4.check_ip_format(user_ip)#....my code
#Creating a Cryptocurrency On Python And Testing It On Postman #Getting Started #Importing the libraries import datetime import hashlib import json from flask import Flask, jsonify, request ''' From flask lbrary we are not just importing the flask class and jsonify file but also request module this time because we ll be connecting to some nodes and to connect to the nodes we need get json function and this function ll be taken from the request module. ''' import requests from uuid import uuid4 #UUID4 generate a random UUID for node_address from urllib.parse import urlparse #Part I - Building a Blockchain class Blockchain: def __init__(self): self.chain=[] self.transactions=[] self.nodes=set() '''Nodes are not ordered because they are supposed to be all around the world And for also computational purpose the nodes are initialized to an empty set instead of empty list. https://stackoverflow.com/questions/1035008/what-is-the-difference-between-set-and-list ''' ''' Introducing a separate list which will contain the transactions before they are added to a block, originally the transactions are not into a block they're added into a block as soon as a block is mine. Once a block is mined all the transactions of the lists will get into a block and the list of transactions will become empty. And this empty list will be reused to welcome some new transactions that will be added to a new future block. ''' self.create_block(proof=1, previous_hash='0') def create_block(self,proof,previous_hash): block={'index':len(self.chain)+1, 'timestamp':str(datetime.datetime.now()), 'proof':proof, 'previous_hash':previous_hash, 'transactions':self.transactions #The value of transactions key ll be self.transactions, we are taking self here because transaction is a variable of the class. } self.transactions=[] #After a block is created, lists will get into it and then self.transactions will become empty. And this empty list will be reused for new transactions. self.chain.append(block) return block def get_previous_block(self): return self.chain[-1] def proof_of_work(self,previous_proof): new_proof=1 check_proof=False while check_proof is False: hash_operation=hashlib.sha256(str(new_proof**2-previous_proof**2).encode()).hexdigest() if hash_operation[:4]=='0000': check_proof=True else: new_proof +=1 return new_proof def hash(self,block): encoded_block=json.dumps(block,sort_keys=True).encode() return hashlib.sha256(encoded_block).hexdigest() def is_chain_valid(self,chain): previous_block=chain[0] block_index=1 while block_index<len(chain): #1ST CHECK - previous hash of the current block is the hash of the previous block block=chain[block_index] if block['previous_hash']!=self.hash(previous_block): return False #2ND CHECK - Proof of each block is valid previous_proof=previous_block['proof'] proof=block['proof'] hash_operation=hashlib.sha256(str(proof**2-previous_proof**2).encode()).hexdigest() if hash_operation[:4]!='0000': return False previous_block = block block_index +=1 return True def add_transaction(self,sender,receiver,amount): '''Its a function to create a format for transaction i.e a format for sender, receiver, and the amount and appending the transaction to the list of transactions before they are integrated to the block.''' self.transactions.append({'sender':sender, 'receiver':receiver, 'amount':amount}) previous_block=self.get_previous_block() return previous_block['index']+1 #The transactions are supposed to appened to the new future block, as soon as it ll be mined, so thats why current block + 1. def add_node(self,address): #function to add any node to the self.nodes=set() by taking address of the nodes parsed_url=urlparse(address) #parsed_url is a new variable that ll store the component of the url (address) ''' #The URL parsing functions focus on splitting a URL string into its components. One of the function is .netloc What netloc does is that - Example https://www.googly.com/8892 the netloc component ll be 8892 or http://127.0.0.1:5000/ the netloc component ll be 127.0.0.1:5000, thats what we want to add to the set. The address of the node and not the url. For more - https://www.saltycrane.com/blog/2008/09/python-urlparse-example/ ''' self.nodes.add(parsed_url.netloc) #Since its a set so we cant use append, instead we used add. def replace_chain(self): network=self.nodes #Its a variable containing all the nodes longest_chain=None '''Its a variable with the longest chain, We dont know yet which chain is the longest in the network so initialized it to none. We ll make a for loop to scan the network to find the longest chain, and as we get that the variable longest_chain ll be the longest chain of the network''' max_length=len(self.chain) ''' In order to find the longest chain we ll simply compare the length of the chains of all the nodes in the network and therefore on this same idea of introducing this longest chain variable which ll become the largest chain at some point well we ll introduce the max length variable which ll be the length of the largest chain. Its a variable with the length of the largest chain, its not initialized to zero or none, its initialized with the chain we are currently dealing with i.e. self.chain. And if we find a chain with length larger than the self.chain, max_length variable ll be updated and accordingly we ll update the longest_chain variable ''' for node in network: #Runninng a for loop to iterate on the nodes of the network, For each node in the network we ll get a response of the following request response=requests.get(f'http://{node}/get_chain') '''Finding the largest chain - Previously when we built the blockchain, we defined a function, get_chain request that just not only return the whole chain but also the length of the chain. we ll put this request in the replace_chain method so we can get the length of all the blokchains of all the nodes in the network, and by this way ll find the largest chain in the network. To make that request we ll use the get function from the requests library that ll get the response exactly as response of get_chain request i.e the same data as response of get_chain. The argument that the requests.get function ll recieve is the address of the node(Generalise form), Example - Earlier when we were dealing with a single chain we used address of that node having that chain, that was http://127.0.0.1:5000/ (the nodes are differentiated by their ports, Different nodes has this common url and then different port, every single port represent a different node) and now when the system is decentralized there ll be an 'n' no. of nodes having 'n' no. of blockchains in the network, so instead of putting the url with the port of single node we have to generalize it for any node in the loop so we ll replace it with 'node', we have put it in brackets because we have used f string function. What is f string in python? https://www.youtube.com/watch?v=s6C3kYCNmLc''' if response.status_code==200: '''get_chain request not only returns the response in json format, but also check HTTP status code 200 to confirm everything is OK, so we need to do quick check here too. If everything is OK, then the length is taken.''' length=response.json()['length'] '''Length is a variable having the length of the chain, The Response is given in json format is exactly the dictonary format with keys and values. So we are taking the length key of a dictionary which ll get the length of the chain. Now we have length of the chain so we can check if it is the longest chain. ''' chain=response.json()['chain'] ''' But we also want to replace the chain if indeed this 'length' is not the largest one, therefore we ll also get the chain from response, in json format but with different key i.e. chain, because get_chain request returns length as well as the chain''' if length>max_length and self.is_chain_valid(chain): '''Now we ll check, If the length of the chain we just got in the response is larger than the largest length which is in max length variable and we also going to check the chain using 'is_chain_valid' method, which ll check that the chain we just got in the response i.e the chain in our node is valid, we need to check this otherwise this chain has no reason to exist. Since is_chain_valid is method of our class so we need to add self and taking an argument as chain ''' ''' if length>max_length and the chain is valid, then we need to update max_length variable because we found a length that is larger than the max length and longest_chain which was initialised to none ll need to be updated as chain of the response that indeed has a length larger than the maximum length. Basically its the largest chain found in the loop over our nodes. ''' max_length=length longest_chain=chain if longest_chain: #If longest_chain is not none (The syntax is a python trick) '''' if the longest_chain is not none that is if the chain was replaced, well in that case we are going to return True just to specify that the chain was replaced. and also we are going to replace the chain because we actually havent done it yet. We have replaced the longest_chain variable but our chain in the blockchain self here was not replaced yet effectively. ''' self.chain=longest_chain return True return False #If no replacement was made and therefore our chain is originally the longest chain then ll return false to specify it. #Part II - Mining the Blockchain #Creating a Web App app = Flask(__name__) #To Create Web App, Follow Flask Quickstart for in depth details. #Creating an address for the node on port 5000 node_address=str(uuid4()).replace('-','') ''' Why do we need a node address? Because whenever miner mines a new block, miner ll get some cryptocoins as their reward, therefore there is a transaction - from the node to the miner. And that is why its fundamental to get an address for this node. So whenever we mine a new block, there ll be a transaction from this node address to yourself. This is the first type of transaction. Second type of transaction or general transactions are from someone to someone. How do we get a node address? UUID4 generates random UUID for the node address, We used replace function to replace '-' with nothing '', because these UUID contains '-' between the numbers and converted the UUID into a string. ''' #Creating a Blockchain blockchain=Blockchain() #Creating blockchain object for the Blockchain class. #Mining a new block - 1st GET Request @app.route('/mine_block',methods=['GET']) def mine_block(): previous_block=blockchain.get_previous_block() previous_proof=previous_block['proof'] proof=blockchain.proof_of_work(previous_proof) previous_hash=blockchain.hash(previous_block) blockchain.add_transaction(sender=node_address,receiver='A',amount=1) '''***Adding transaction to 'blockchain' object of our 'Blockchain' class, To use add_transaction method on our 'blockchain' object we simply need to add here .add_transaction. Now comes who ll be the receiver, sender and what ll be the amount? As explained miner ll be rewarded for mining a block. The sender ll be the node_address, the receiver ll be the miner and the amount is the reward for mining a block. ''' block=blockchain.create_block(proof,previous_hash) response={'message':'Congrats, You just mined a block', 'index':block['index'], 'timestamp':block['timestamp'], 'proof':block['proof'], 'previous_hash':block['previous_hash'], 'transactions':block['transactions']} #Adding transaction key return jsonify(response), 200 #Getting the full Blockchain - 2nd GET Request @app.route('/get_chain',methods=['GET']) def get_chain(): response={'chain':blockchain.chain, 'length':len(blockchain.chain) } return jsonify(response), 200 #Adding a new transaction to the Blockchain ''' In order to add a transaction to the blockchain, we need to create a POST request. In GET request we dont need to create anything to get a response but in POST request, to get a response we need to create something, that is why it is called POST request becuase we are posting something inside the HTTP client. In order to add a transaction to the blockchain, we need to post the transaction and to post this transaction we ll create a JSON file which ll contain the keys of the transactions i.e sender, receiver, amount of the coins exchanged. This information ll be posted to the JSON file and the response ll get the JSON file and this JSON file containing the transaction ll go through jsonify function and eventually this transaction ll go into the next mined block ''' @app.route('/add_transaction',methods=['POST']) def add_transaction(): #Implementing a new request through a function, add_transaction json=request.get_json() #Getting the JSON file which was posted in the POSTMAN transaction_keys=['sender','receiver','amount'] #Checking all the keys are present in the JSON file; transaction_keys is a variable having a list of sender, receiver and amount if not all (key in json for key in transaction_keys): '''IF loop to check wether any of the key is not present in the transaction_keys variable, If something is missing return a missing message with HTTP status code for missing item or Bad request i.e 400''' return 'Some elements of the transaction are missing',400 '''If the transaction_keys have all keys, then we need to add the transaction to the next mined block. How to get the next mined block? We need to find the index of the next block, add_transaction method returns the index of the next block that ll be mined, add_transaction method doesnt take the keys it takes the values of these keys, To get the values of the keys we need to take it from the json file, json file work same as python dictionaries, so in order to get the values of the transaction, we ll take the json variable which is exactly the json file containing the transaction.''' index=blockchain.add_transaction(json['sender'],json['receiver'],json['amount']) response={'message':f'This transaction ll be added to block {index}'} #response is a variable which ll contain the response return jsonify(response), 201 #Returning the response with HTTP status code for success for POST Request, i.e 201 #Part III - Decentralizing the Blockchain #Connnecting new nodes '''why post request and not get? Because basically we are going to create a new node in the decentralized network and therefore we are going to register it. To register it we ll have a separate JSON file which ll contain all the node that we want in our blockchain including the new one we want to connect and this JSON file ll be exactly what ll be posted in the POSTMAN to make our post request Whenever we want to connect to a new node to the blockchain, we ll simply need to add this node to the JSON file that contains already the existing nodes and we ll post this JSON file using connect_node POST request and this ll connect the new node to the network.''' @app.route('/connect_node',methods=['POST']) def connect_node(): json=request.get_json() '''Request to get for posting a new node in the network through the get json function which ll return this json file that ll contain all the nodes in the decentralized network''' nodes=json.get('nodes') '''connecting new node to all other nodes in the network, To do that we ll simply use add_node function to add all the node of the JSON file to the blockchain network. But add_node takes an argument as address, but now the nodes are in JSON file so we cannot use directly the variable. So we ll use this get method, so this json.get ll get us exactly the value of this key, i.e the address contained in the list. This returns the values and to store these values we introduced nodes variable. ''' if nodes is None: #Check for if nodes variable returns empty list return 'Error: No Nodes Found', 400 for node in nodes: #Adding nodes one by one blockchain.add_node(node) #Taking the blockchain object and using add_node method which takes argument as address i.e nodes response={'Message': 'All the nodes are now connected. Thse Laxmicoin Blockchain now contains the following nodes:', 'total_nodes': list(blockchain.nodes)} #Returning response as message with the list of total nodes in the network return jsonify(response), 201 #Replacing the chain by the longest chain if needed @app.route('/replace_chain', methods = ['GET']) def replace_chain(): ''' We ll use a function which ll give us boolean true or false and on them we ll make a if and else condition which ll return two different messages To have this boolean we have a function replace_chain in Part - I which exactly returns True or False, This replace_chain function in Part - I does not simply change the chain by the longest one but also returns true or false, True if the chain is not the longest one and false if the chain is the longest one. ''' is_chain_replaced=blockchain.replace_chain() '''is_chain_replaced is a variable which ll have the boolean true or false, Using .replace_chain from Part - I on the blockchain ll return True or False''' if is_chain_replaced: response = {'message': 'The nodes had different chain so the chain was replaced by the longest one.', 'new_chain': blockchain.chain} #returns the message and the blockchain else: response = {'message': 'All good. The chain is the largest one.', 'actual_chain': blockchain.chain} return jsonify(response), 200 #Running the app app.run(host='0.0.0.0', port=5001)
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here if pRoot is None or k == 0: return None def kth_node(pRoot, k): res = None if pRoot.left is not None: res = kth_node(pRoot.left, k) if res is None: if k[0] == 1: res = pRoot k[0] -= 1 if res is None and pRoot.right is not None: res = kth_node(pRoot.right, k) return res k = [k] return kth_node(pRoot, k)
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here if n <=1: return n pre = 0 cur = 1 cnt = 1 ans = 1 while cnt <n: ans = cur + pre pre = cur cur = ans cnt += 1 return ans
# coding=utf-8 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} head # @param {integer} m # @param {integer} n # @return {ListNode} def reverseBetween(self, head, m, n): if not m or not n or m>n: return head dummy=ListNode(0) dummy.next=head cur=dummy.__next__ i=1 start=dummy while i<m and cur: start=cur cur=cur.__next__ i+=1 if cur: stop=cur runner=cur.__next__ while i<n and runner: p=runner.__next__ runner.next=cur cur=runner runner=p i+=1 stop.next=runner start.next=cur return dummy.__next__ def printList(head): if not head: print("None") while head.__next__: print(head.val,"->", end=' ') head=head.__next__ print(head.val) so=Solution() h=head=ListNode(1) for i in range(2,6): h.next=ListNode(i) h=h.__next__ head=so.reverseBetween(head, -1, 3) printList(head) head=so.reverseBetween(head, 2, 2) printList(head)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def addTwoNumbers(self, l1, l2): if l1 is None: return l2 if l2 is None: return l1 c=0 p=h=ListNode(0) while not (l1 is None or l2 is None): s = ListNode(l1.val + l2.val + c) c = s.val/10 s.val = s.val%10 p.next = s p = s l1 = l1.__next__ l2 = l2.__next__ while l1 is not None: s = ListNode(l1.val + c) c = s.val/10 s.val = s.val%10 p.next = s p = s l1 = l1.__next__ while l2 is not None: s = ListNode(l2.val + c) c = s.val/10 s.val = s.val%10 p.next = s p = s l2 = l2.__next__ if c > 0: s = ListNode(c) p.next = s return h.__next__
# coding=utf-8 import unittest class Solution: def solve(self, nums): return self.candy(nums) # @param {integer[]} ratings # @return {integer} def candy(self, ratings): length=len(ratings) if length<2: return length candies=[1]*length for i in range(1,length): if ratings[i]>ratings[i-1]: candies[i] = candies[i-1]+1 for i in range(length-2,-1,-1): candies[i]=max(candies[i+1]+1,candies[i]) if ratings[i]>ratings[i+1] else candies[i] return sum(candies) class Test(unittest.TestCase): #override def setUp(self): self.s=Solution() def tearDown(self): print("TestComplete") def genTestCase(self): case=[ [1,2,2],#4 [1,2,1,3],#6 [2,1],#3 [3,2,1,2,2,1],#11 [8,6,6,4,3,9,7,1],#15 ] self.cases=case def test(self): self.genTestCase() for case in self.cases: print(("testcase: ", case)) res=self.s.solve(case) print(("result: ",res)) # if assert is needed unittest.main()
class Solution: # @param {string} s # @return {boolean} def isValid(self, s): stack=["+"] for p in s: if p in "([{": stack.append(p) else: if (p==")" and stack[-1]=="(") or (p=="]" and stack[-1]=="[") or (p=="}" and stack[-1]=="{"): stack=stack[:-1] else: return False if len(stack)>1: return False return True
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ strs = str.split(" ") if len(pattern)!=len(strs): return False dic1={}# pattern to str dic2={}# str to pattern for i in range(len(pattern)): if (pattern[i] in dic1 and dic1[pattern[i]]!=strs[i]) or (strs[i] in dic2 and dic2[strs[i]]!=pattern[i]): return False else: dic1[pattern[i]]=strs[i] dic2[strs[i]]=pattern[i] return True
#separador de tags e palvras: corpus = "((S (UBK re) (UBK re) (UBK re) (ARK re) (SBJ I) (NOUN uh) (NOT don't) (NOT don't) (NEXP like) (NEXP like) (OBJ it) (UNK re) ))" corpus = corpus.replace("(", "").replace(")", "").replace("S", "").split() #definidas as duas listas que serão utilizadas pelo codigo para ter acesso as tags e as palavras (as duplas estão relacionadas pelos indices das listas)? tags = [] words = [] #abaixo fica o separador que filtra o corpus fornecido para o training do tagger, o qual define os valores das listas de tags e words usando o corpus como base: for index, word in enumerate(corpus): if index % 2 == 0: tags.append(word) else: words.append(word) bigrams = {} #definido o dicionario que será o output desse codigo e será usado pelo PoS Tagger. bigram_list = [] for index, word in enumerate(words): if index >= 1: bigram = tags[index - 1] + " " + word #os bigramas serão formados por uma tag e a palavra que a segue, ja que assim reprensenta-se melhor relações gramaticais #e como uma palavra se comporta quando precedida de uma especifica classe de palavra (ja que para intuito do PoS Tagger, #vale mais considerar isso q cada caso de palavra precedida por outra palavra), o que tambem permite a coleta de mais #dados ja que duplas diferentes de palvras podem ser consideradas a mesma sequência, então favor não confundir o modelo de #bigrama usado aqui com o taggeamento da palavra em questão. bigram_list.append(bigram) for bigram in set(bigram_list): bigram_reps = [i for i, b in enumerate(bigram_list) if b == bigram] rep_tags = [tags[i + 1] for i in bigram_reps] tag_counts = {} for tag in set(rep_tags): tag_counts[tag] = rep_tags.count(tag) bigram_tags = {} bigram_tags[bigram] = tag_counts #serve para caso eu queira ter uma contagem das tags para melhor vizualização (utilizar o print). #print(bigram_tags) high_tag_count = max(tag_counts.values()) high_tag = [key for key, value in tag_counts.items() if value == high_tag_count] if sum(tag_counts.values()) > 0: bigrams[bigram] = high_tag[0] print(bigrams)
import microbit import random submarine_life = 5 submarine = {} life = {} x = {} y = {} def dictionnary(nb_submarine): """Specification of the function Parameters: ----------- nbr_submarine : the number of submarine for a game (int) Note: ----- The function will generate a dictionnary with the submarine with his position (x and y) and his life """ nb_sub = nb_submarine #nb_sub is used to verify is there rest submarine or not for n in range(1, nb_submarine + 1): submarine[n] = {"life" : submarine_life, "x" : random.randint(0, 4), "y" : random.randint (0, 4)} print(submarine) dictionnary(5)
# -*- coding: utf-8 -*- """ Created on Tue Aug 11 14:09:44 2020 @author: Charlie """ import numpy as np import matplotlib.pyplot as plt import statistics as stat import math import scipy import itertools as itr xticks = np.linspace(0.01, 720, 2000) fig = plt.figure(figsize=(10,7)) ax1 = fig.add_subplot(1,1,1) zero = [0]*2000 ax1.plot(xticks, zero, 'g-') # Python function to print permutations of a given list def permutations(A): # If lst is empty then there are no permutations if len(A) == 0: return [] # If there is only one element in lst then, only # one permuatation is possible if len(A) == 1: return [A] # Find the permutations for lst if there are # more than 1 characters l = [] # empty list that will store current permutation # Iterate the input(lst) and calculate the permutation for i in range(len(A)): m = A[i] # Extract lst[i] or m from the list. remLst is # remaining list remLst = A[:i] + A[i+1:] # Generating all permutations where m is first # element for p in permutations(remLst): l.append([m] + p) return l def circle_product (xi, c, A): l=permutations(A) #output=np.empty(len(A)) output=[0,0,0,0,0,0] c=int(c) xi=int(xi) C=l[c] Xi=l[xi] for i in range(len(A)): output[i]=C[Xi[i]-1] return output def labeler (A, Xi): l=permutations(A) for i in range(math.factorial(len(A))): if l[i]==Xi: return i def rhs (xi, c, A): T1=labeler(A, circle_product(xi, c, A)) k=circle_product(xi, c, A) j=k[1] k[1]=k[0] k[0]=j l=k[2] k[2]=k[3] k[3]=l m=k[4] k[4]=k[5] k[5]=m T2=labeler(A, k) return abs(T1-T2) def lambic_function (xi, c, A): r=rhs(xi, c, A) fs=circle_product(xi, r, A) fv=labeler(A, fs) return fv def lambic_point_generator (c, N): x=np.empty(N) x[0]=1 A=[1,2,3,4,5,6] lambdas=[] for i in range(N-1): x[i+1]=lambic_function(x[i], c, A) ax1.scatter(c,x[i], color='black', alpha=0.1, edgecolors='none', label = 'Lorenz Bifurcation') trajectory=x[i+1]-x[i] lambdas.append(math.log(abs(trajectory))) lam=stat.mean(lambdas) ax1.scatter(c,lam, color='red', alpha=0.5, edgecolors='none', label = 'Lyapunov Exponent') return x c=range(720) for i in range(720): lambic_point_generator(c[i], 25) ax1.set_xlabel('c') ax1.set_ylabel('x') ax1.set_title('How Lyapunov Exponent Varies with Constant c for a 2 term discreet map ')
# -*- coding: utf-8 -*- """ Created on Thu Jul 9 16:16:13 2020 @author: Charlie """ import statistics as stat import scipy.stats as sci import numpy as np import matplotlib.pyplot as plt import math import scipy import itertools as itr # Python function to print permutations of a given list def permutations(A): # If lst is empty then there are no permutations if len(A) == 0: return [] # If there is only one element in lst then, only # one permuatation is possible if len(A) == 1: return [A] # Find the permutations for lst if there are # more than 1 characters l = [] # empty list that will store current permutation # Iterate the input(lst) and calculate the permutation for i in range(len(A)): m = A[i] # Extract lst[i] or m from the list. remLst is # remaining list remLst = A[:i] + A[i+1:] # Generating all permutations where m is first # element for p in permutations(remLst): l.append([m] + p) return l def circle_product (xi, c, A): l=permutations(A) #output=np.empty(len(A)) output=[0,0,0,0,0,0] c=int(c) xi=int(xi) C=l[c] Xi=l[xi] for i in range(len(A)): output[i]=C[Xi[i]-1] return output def labeler (A, Xi): l=permutations(A) for i in range(math.factorial(len(A))): if l[i]==Xi: return i def rhs (xi, c, A): T1=labeler(A, circle_product(xi, c, A)) T2=labeler(A, list(reversed(circle_product(xi, c, A)))) return abs(T1-T2) def lambic_function (xi, c, A): r=rhs(xi, c, A) fs=circle_product(xi, r, A) fv=labeler(A, fs) return fv def lambic_point_plotter (c, A): N=720 k=0 fig, ax = plt.subplots() for i in range(1,N-1): k=lambic_function(i, c, A) ax.scatter(k, c, color='black', alpha=0.01, edgecolors='none') return k A=[1,2,3,4,5,6] N=720 for i in range (N): lambic_point_plotter (i, A) ax.legend() ax.grid(True) plt.show() '''up to this point we have a function that can generate a point for a given xi and c. We want this point to be plotted by plotting a point ech time its formed in a string''' '''fig, ax = plt.subplots() for color in ['tab:blue', 'tab:orange', 'tab:green']: n = 750 x, y = np.random.rand(2, n) scale = 200.0 * np.random.rand(n) ax.scatter(x, y, c=color, s=scale, label=color, alpha=0.3, edgecolors='none') ax.legend() ax.grid(True) plt.show()'''
# -*- coding: utf-8 -*- """ Created on Wed Jun 24 15:08:11 2020 @author: Charlie """ import statistics as stat import scipy.stats as sci import numpy as np import matplotlib.pyplot as plt ''' so we are gonna get 2 strings of binary digits, and combine them into a new string of binary digits using a logistic function. there are 2 parameters that effect a logistic function, r and x. r ranges from 3.6 to 4 and x ranges from 0 to 1.''' def binary_converter (b): d=int(b,2) return d def r_generator (d): d=binary_converter(d) r=((d+10)/(d+9))*3.6 return r def x_generator (U): n=len(U) U=binary_converter(U) x=(U+0.0001)/(2**n) return x def logistic (x, r): xdot=(x*r)-(x*x*r) return xdot def logi_point_generator (r, x0, N): N=int(N) point=round(x0,15) for i in range (N-1): point=round(logistic(point,r),12) return point def key_value_generator (U, d, N): x=x_generator(U) r=r_generator(d) E=logi_point_generator(r, x, N) return E def final_binary_key_gen (U, d, N): E=key_value_generator(U, d, N) E=E*(10**7) E=int(E) E=bin(E) return E E=final_binary_key_gen('110', '110', 1000) print(E)
import numpy as np import matplotlib.pyplot as plt #define our functions, using def. x, y, z are our variables. s, r, b, are our #are our parameters. Return must be used toto give back results. def lorenz(x, y, z, s=10, r=28, b=8/3.): x_dot = s*(y - x) y_dot = r*x - y - x*z z_dot = x*y - b*z return x_dot, y_dot, z_dot #define time increments dt = 0.01 num_steps = 1000 #define an array which are values for x, y, z will fill. needspace for initial #value and then 1000 increments xs = np.empty(num_steps + 1) ys = np.empty(num_steps + 1) zs = np.empty(num_steps + 1) # Set initial values, so now array has these as first value then many zeros xs[0], ys[0], zs[0] = (-8., 8., 27.) #now fill array for i in range(num_steps): x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i]) xs[i + 1] = xs[i] + (x_dot * dt) ys[i + 1] = ys[i] + (y_dot * dt) zs[i + 1] = zs[i] + (z_dot * dt) plt.plot(xs, ys) plt.xlabel("xs") plt.ylabel("ys")
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 11:25:04 2020 @author: Charlie """ import statistics as stat import scipy.stats as sci import numpy as np import matplotlib.pyplot as plt from matplotlib import cm import math import scipy import itertools as itr from mpl_toolkits.mplot3d import Axes3D # Python function to print permutations of a given list def permutations(A): # If lst is empty then there are no permutations if len(A) == 0: return [] # If there is only one element in lst then, only # one permuatation is possible if len(A) == 1: return [A] # Find the permutations for lst if there are # more than 1 characters l = [] # empty list that will store current permutation # Iterate the input(lst) and calculate the permutation for i in range(len(A)): m = A[i] # Extract lst[i] or m from the list. remLst is # remaining list remLst = A[:i] + A[i+1:] # Generating all permutations where m is first # element for p in permutations(remLst): l.append([m] + p) return l def circle_product (xi, c, A): l=permutations(A) #output=np.empty(len(A)) output=[0,0,0,0,0,0] c=int(c) xi=int(xi) C=l[c] Xi=l[xi] for i in range(len(A)): output[i]=C[Xi[i]-1] return output def labeler (A, Xi): l=permutations(A) for i in range(math.factorial(len(A))): if l[i]==Xi: return i def rhs (xi, c, A): T1=labeler(A, circle_product(xi, c, A)) T2=labeler(A, list(reversed(circle_product(xi, c, A)))) return abs(T1-T2) def td_lambic_function (yi, xi, c, A): r=rhs(xi, c, A) fs=circle_product(yi, r, A) fv=labeler(A, fs) return fv def lambic_td_strings_generator (x0, y0, cx, cy, A): N=1000000 stringx=np.empty(N) stringx[0]=x0 stringy=np.empty(N) for i in range(N-1): stringx[i+1]=td_lambic_function(stringx[i], stringy[i], cx, A) stringy[i+1]=td_lambic_function(stringy[i], stringx[i], cy, A) if stringx[i]==x0 and stringy[i]==y0: k=i return stringx, stringy, k A=[1,2,3,4,5,6] n=range(1000) '''fig = plt.figure() ax = plt.axes(projection='3d') #ax.plot3D(xs, ys, n, 'gray') ax.scatter3D(xs, ys, n, c=n, cmap=cm.coolwarm)''' (xs, ys, k)=lambic_td_strings_generator(1, 1, 6, 6, A) #(x1, ys1)=lambic_td_strings_generator(2, 6, 6, A) #plt.plot(n,ys) #Axes3D.plot(xs,ys,n) #3d plot print(k) '''fig = plt.figure() ax = fig.gca(projection='3d') # Plot the surface. ax.plot_surface(xs, ys, n, cmap=cm.coolwarm, linewidth=0, antialiased=False) plt.show()''' '''#plt.plot(y,x) plt.xlabel("Number of Iterations") plt.ylabel("x") plt.plot(n, xs, label='x0=1 where cx=6') plt.plot(n, x1, label='x0=2 where cx=6') #plt.plot(n, z, label='z') plt.legend()''' #print(xs)' #3d space fig '''fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(xs, ys, n, lw=0.8) ax.set_xlabel("X Axis") ax.set_ylabel("Y Axis") ax.set_zlabel("Z Axis") ax.set_title("Multidimensional Lambic Map") plt.show()''' ''' #2d x1 x plt.xlabel("Number of Iterations") plt.ylabel("x") plt.plot(n, x, label='x0=1') plt.plot(n, x1, label='x0=2') plt.legend()'''
def rational_to_decimal(n,d): # returns the decimal expression of the rational as a string #if n%1!=n or d%1!=d: #return 'That is not a rational number!' dec_expr='' # it will store n/d = d0.d1 ... dn ( period ) r=[] q=int(n/d) dec_expr+=str(q) dec_expr+='.' r.append(n-d*q) n=r[-1]*10 while True: #This will finish because we know that n/d is always periodic q=int(n/d) dec_expr+=str(q) if r.count(n-d*q)>0: i=r.index(n-d*q) break r.append(n-d*q) n=r[-1]*10 dec_expr=dec_expr[:i+2]+'('+dec_expr[i+2:] dec_expr+=')' if '(0)' in dec_expr: dec_expr=dec_expr[:-3] return dec_expr result=[1,1] for d in range(2,1000): s=rational_to_decimal(1,d) if '(' in s: index=s.index('(') if result[1]<len(s[index:])-2: result=[d,len(s[index:])-2] print(result)
def Collatz_seq(n): l=[] l.append(n) if l[-1]==1: return l else: if l[-1]%2==0: return l+Collatz_seq(n/2) else: return l+Collatz_seq(3*n+1) def LengthCollatz(n): count=1 a=n while a!=1: if a%2==0: a=a/2 else: a=3*a+1 count+=1 return count MaxLength=1 index=0 memory={} for i in range(1,10**6): if i not in memory.keys(): memory[i]=LengthCollatz(i) lc=memory[i] if lc>MaxLength: MaxLength=lc index=i print(index, MaxLength)
def number_name(n): #gives the names of numbers between 1 and 999 included. if n>1000: return 'Too big!' if n==1000: return 'one thousand' s=str(n) if len(s)==1: if s[0]=='0': return 'zero' if s[0]=='1': return 'one' if s[0]=='2': return 'two' if s[0]=='3': return 'three' if s[0]=='4': return 'four' if s[0]=='5': return 'five' if s[0]=='6': return 'six' if s[0]=='7': return 'seven' if s[0]=='8': return 'eight' if s[0]=='9': return 'nine' elif len(s)==2: if s[0]=='0': return number_name(int(s[0])) if s[0]=='1': if s[1]=='0': return 'ten' if s[1]=='1': return 'eleven' if s[1]=='2': return 'twelve' if s[1]=='3': return 'thirteen' if s[1]=='4': return 'fourteen' if s[1]=='5': return 'fifteen' if s[1]=='6': return 'sixteen' if s[1]=='7': return 'seventeen' if s[1]=='8': return 'eighteen' if s[1]=='9': return 'nineteen' if s[0]=='2': if s[1]=='0': return 'twenty' else: return 'twenty-{0}'.format(number_name(int(s[1]))) if s[0]=='3': if s[1]=='0': return 'thirty' else: return 'thirty-{0}'.format(number_name(int(s[1]))) if s[0]=='4': if s[1]=='0': return 'forty' else: return 'forty-{0}'.format(number_name(int(s[1]))) if s[0]=='5': if s[1]=='0': return 'fifty' else: return 'fifty-{0}'.format(number_name(int(s[1]))) if s[0]=='6': if s[1]=='0': return 'sixty' else: return 'sixty-{0}'.format(number_name(int(s[1]))) if s[0]=='7': if s[1]=='0': return 'seventy' else: return 'seventy-{0}'.format(number_name(int(s[1]))) if s[0]=='8': if s[1]=='0': return 'eighty' else: return 'eighty-{0}'.format(number_name(int(s[1]))) if s[0]=='9': if s[1]=='0': return 'ninety' else: return 'ninety-{0}'.format(number_name(int(s[1]))) elif len(s)==3: if s[1:]=='00': return '{0} hundred'.format(number_name(int(s[0]))) else: return '{0} hundred and {1}'.format(number_name(int(s[0])),number_name(int(s[1:]))) string='' for i in range(1,1001): string+=number_name(i) print(len([s for s in string if s!=' 'and s!='-']))
lowers = 'abcdefghijklmnopqrstuvwxyz' caps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Read from file, check if binary or nor and print mesage accordingly def binReadWrite(): message = readFile() if(checkBinary(message)): # Converting to alphabet if message binary print(binToAlpha(message)) else: # Converting to binary if message alphabet print(alphaToBin(message)) # Function to read the message from file def readFile(): file = open('input.txt', 'r') text = file.readline() # Print the input text read from input file print(text) file.close() return text # Fuction to check if the text is binary def checkBinary(text): # Loop all characters in input text and return true if they are 0, 1 or spaces for char in list(text)[:-1]: if(char!='1' and char!='0' and char!=' '): # Return false if char other than 0, 1 and space return False return True # Function to convert binary to decimal def binToDec(binary): dec=0 for i in range(0,len(binary)): dec+=int(binary[i])*(2**(len(binary)-i-1)) return dec # Function to convert binary message to Alphabet def binToAlpha(message): print('Converting Binary to Alphabet') i=0 text='' # Used while loop to increment i by different amounts while(i<len(message)): if(message[i]!=' '): # Space = 0b00100000 if(message[i:i+8]=='sb00100000'): text+=' ' elif(message[i:i+3]=='010'): text+=caps[binToDec(message[i+3:i+8])-1] elif(message[i:i+3]=='011'): text+=lowers[binToDec(message[i+3:i+8])-1] i+=8 else: i+=1 return text # Function to convert alphabet message to binary def alphaToBin(message): print('Convert Alphabet to Binary') binary='' for letter in message: if(letter in caps): binary += '010' # Find the position of letter in caps, replace 0b from bin() and left pad with 0s binary += (bin(caps.find(letter)+1).replace("0b",'')).zfill(5) elif(letter in lowers): binary += '011' # Find the position of letter in lowers, replace 0b from bin() and left pad with 0s binary += (bin(lowers.find(letter)+1).replace("0b",'')).zfill(5) elif(letter == ' '): binary += '00100000' binary += ' ' return(binary) #Call function binReadWrite()
caps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def removeSpecials(message): #make a list of individual characters from message lettersOnly = '' for symbol in message: if symbol in caps: lettersOnly = lettersOnly+symbol # return the modified, letters-only message return lettersOnly def vigenereEncrypt(): message = input("What message would you like to encrypt? ") message = message.upper() key = input("What is your key? ") key = removeSpecials(key.upper()) #print(message) #print(key) letters = list(message) keyLetters = list(key) text = '' #Loop to encrypt each letter for i in range (0,len(letters)): #print(i, ' ', letters[i], ' ', keyLetters[i%len(key)]) #If the letter is in list of capitals, encode it letter = letters[i] if letter in list(caps): num = caps.index(letter) num = num+(caps.index(keyLetters[i%len(key)])+1) num = num%26 letter = caps[num] text = text + letter #Printing cipher text print("Cipher Text: ", text) vigenereEncrypt()
import read as R import datetime import display as D import list2d as L import write as W import returnbook as RB try: # first it is read from the file. def initialtable(): lists=[ ] lists_1= R.read_information(lists) list_2d=L.arrange(lists_1) # the read data which is in list is converted into 2d lists. D.display_information(list_2d) # 2d list is now displayed in the form of table. return list_2d library_book=initialtable() # it has the library books in 2d list . # second it is to ask input to the user. def mainwork(answer): answer= str(input("Do you want a book(yes or no) :")).lower() return answer word=str() answer=mainwork(word) def process(answer): if answer== "yes": W.user_information() # it is to keep the total cost of the book along with information in 2d list and the display the information. def information_of_user(lists): received=R.read_information2(lists) # it has the infomation of the user in a list. list_2d=L.arrange(received)# it is to keep information in a 2d list along with price. user=D.display_userinformation(list_2d) # to display user inputed information along with price. return user list2=[ ] new_2d= information_of_user(list2) # it is to get the total number of books taken and update the initialtable. def count(new_2d,library_book): num1=0 num2=0 num3=0 for i in range (len(new_2d)): if new_2d[i]=="harry potter": num1+=1 if new_2d[i]=="start with why": num2+=1 if new_2d[i]=="programming with python": num3+=1 new_book1=str((int(library_book[0][2])-num1)) new_book2=str((int(library_book[1][2])-num2)) new_book3=str((int(library_book[2][2])-num3)) if int(new_book1) <= 0: new_book1=0 if int(new_book2) <= 0: new_book2=0 if int(new_book3) <= 0: new_book3=0 for i in range (len(library_book)): for j in range (len(library_book[i])): library_book[0][2]=new_book1 library_book[1][2]=new_book2 library_book[2][2]=new_book3 return(library_book) quantity_changed=count(new_2d,library_book) # it is to display the updated table and ask user if they want to take book or return to the library. def newtable(lists): W.library_stock(lists) question=str(input("Type 'yes' to view library books or Type 'return' to give back books =")).lower() if question=="yes": D.display_information(lists) answer=mainwork(word) process(answer) elif question=="return": listss=[ ] list1d=R.read_information2(listss) list2d=L.arrange(list1d) (user,returnbooks)=RB.bookreturncheck(list2d,lists) W.library_stock(returnbooks) W.user_stock(user) D.display_information(returnbooks) answer=mainwork(word) else: print("Thank you for visiting") initialtable() answer=mainwork(word) process(answer) newtable(quantity_changed) elif answer=="no": answer=str(input("Type yes to return book :")).lower() if answer=="yes": listss=[ ] list1d=R.read_information2(listss) list2d=L.arrange(list1d) (user,returnbooks)=RB.bookreturncheck(list2d,library_book) W.library_stock(returnbooks) W.user_stock(user) D.display_information(returnbooks) answer=mainwork(word) process(answer) else: print("thankyou for the visit") initialtable() answer=mainwork(word) process(answer) else: print("Invalid input please try again") initialtable() answer=mainwork(word) process(answer) process(answer) except Exception : initialtable() answer=mainwork(word) process(answer)
#5622 import sys alphabet = input() num_word = ['','','ABC', 'DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ'] time = len(alphabet) for i in alphabet: for j in range(len(num_word)): if i in num_word[j]: time += j print(time)
"""Module containing the descriptions that make up Shadow House's story. This module is made up of several classes that contain descriptions of each room a player can enter. Within each room choices can be made and each corresponding class has descriptions of those as well. Rooms such as Basement, DiningRoom, etc., all inherit from parent class Room. None of the classes currently instantiate objectsm and rather function more like glorified dictionaries. An important feature of most classes is that they contain class memeber variables that are needed to define game state (e.g. In Basement, the boolean value of notebook_read determines whether a player will ultimately live or die!). The decision to use class member variables is one of convenience and, perhapsm not the best design decision. Using object member variables would've meant either making the Room objects global or passing objects from room to room. For a small game like this, however, the class member variable solution works and decouples a lot of game data from game logic in an arguably intuitve way. Suggested improvements for next version: * Move all game state data away from room into player class. """ class Room(): """Parent class of various rooms player enters in game.""" choices = {} @classmethod def get_choices(cls): """Gets list of choices user can make in aroom.""" return list(cls.choices.keys()) class Basement(Room): """Class representing the basement in the story. Attributes: notebook_read: Boolean describing whether player read a notebook. description: String containing room's description. descr_*: Strings containing text describing the results of a user's choice. choices: Dictionary containing choice:description pairs. """ notebook_read = False description = ''' You are sitting on a cozy sofa in the basement of your childhood home. Night paints small windows that open onto the front lawn and the alley between your house and the neighbour’s. The air is cool down here. A sticky film of sweat coats your bare legs and arms. A TV remote sits next to your lap. A notebook lies on the table in front of you. A hairy spider, the size of a cupcake, crawls near your sandalled foot.''' descr_tv = ''' You grab the remote and hit the POWER button. The TV hisses and cracks. Slowly, an image fades on to its glass. On top of the television, you notice an unbroken copy of “Infinite Jest” gathering dust. The images are, at once, foggy yet vividly clear. For only a few moments are you able to register what you’re seeing: a beautiful woman whose face is horribly disfigured; a wailing baby’s head which is zoomed into but never seen any closer, like a fractal. You cannot stop watching The Entertainment. Like a toppled Babushka doll, you fall from your perch on the sofa to the floor. Several hours later, a tubby coroner waves a lit Gauloise over your corpse as he tells Special Det. Alvin Gumby the autopsy's conclusion: “It’s textbook, Gum-man: death by dehydration and too much fuuuunnnn!”''' descr_spider = ''' The teal silver-back Colombian jumping spider springs on to your foot and sinks its fangs. You kick your leg violently until the arachnid flies off. It cuts through the air like a spinning wad of wet toilet paper, hitting the the glass of your VCR/Nintendo cabinet with an assertive rattle and splat. A stinging, then a burning, then a numbness, first in your right pinky but not a minute later everywhere. You think of Agent Cooper, Laura Palmer and a white stallion galloping in black space. The last thing you see is a spinning ceiling fan. You think: "Who the hell has a ceiling fan in their basement?" "''' descr_upstairs = ''' You climb the musty, blue carpet staircase, narrowly avoiding a slimy banana peel lying in the middle of a step. At the top of the stairs you walk a few paces down the hall and make a left.''' descr_notebook = ''' The notebook turns out to be your old diary. You glaze over the many cringeworthy passages, but two shout out at you. You have no idea why. "Many die where they blindly tread.” “Peanut-butter-and-banana sandwiches rock!!” Your stomach rumbles.''' descr_around = "\nYou already did that." descr_banana = ''' You climb the stairs, but slip on a slimy banana peel (yes — this can happen in real life, not just in cartoons). The fall forward, let’s say, makes you a lot less pretty than you were once renowned for. A lot less.''' choices = { "Watch TV": descr_tv, "Squash spider": descr_spider, "Go upstairs": descr_upstairs, "Read notebook": descr_notebook, "Look around": descr_around } class DiningRoom(Room): """Class representing the dining room in the story. Attributes: passcode: List of integers containing passcode to open garden door. talk_once: Boolean describing whether player has spoken once to mannequin. talk_twice: Boolean describing whether player has spoken twice to mannequin. look_around: Boolean describing whether player has looked around the room. description: String containing room's description. descr_*: Strings containing text describing the results of a user's choice. choices: Dictionary containing choice:description pairs. """ passcode = [] talk_once = False talk_twice = False look_around = False description = "\nYou are in the dining room." descr_around = ''' A naked mannequin sits at the head of an oak table. Except for the contours of her plastic body, she is featureless, her face as bare as an egg. The primer-white surface neck and chest gleam under the fluorescent lights of the chandelier. The Venetian blinds behind the mannequin are shut. The dining room has a suffocating aspect to it. A standing fan in the corner laps you with warm air. A bowl of veggie straws sits on the mannequin’s placemat. There is a doorway on the other end of the room to your left. Downstairs is the basement.''' descr_straws = ''' You hesitate. Which colour to pick? Green? Orange? Yellow? How to decide?? After an hour of embarrassing indecision, you timidly extract a spinach straw. You glance at the mannequin as you gobble it up, unable to shake the feeling that she is judging you. Although the veggie straw's airirness is pleasing, it is clearly under-seasoned. You take a seat at the table and continue to munch from the bowl, which is apparently inexhaustible. The hope that you’ll find a more flavourful straw is replaced by the gloomy realization that life is also often under-seasoned. You eat ad infinitum.''' descr_touch = "\nShame on you! This is not that kind of game ;-)." descr_talk = ''' At first the mannequin ignores your blather when suddenly she says: "The fruits of all our labours will not be wasted on soul-consuming tasks.”''' descr_toomuch = ''' The mannequin has nothing more to say to you. She's an introvert -- stop draining her energy with purposeless conversation!''' descr_nomannequin = "\nWuh?? What mannequin?" descr_slowdown = ''' Slow down there, cowboy. What's the rush? Maybe you should look around first...''' descr_left = "" descr_down = "\nDo you really want to go back down there? Hello, spider…" descr_passcode = "Remember these numbers:" choices = { "Eat veggie straws": descr_straws, "Touch mannequin": descr_touch, "Talk to mannequin": descr_talk, "Go left": descr_left, "Go downstairs": descr_down, "Look around": descr_around } @classmethod def stringify_passcode(cls): """Formats and returns passcode in a way player can easily read.""" pc1 = cls.passcode[0] pc2 = cls.passcode[1] pc3 = cls.passcode[2] pc4 = cls.passcode[3] return f"{pc1} {pc2} {pc3} {pc4}" class Kitchen(Room): """Class representing the kitchen in the story. Attributes: potatoes: Integer representing the number of potaotes the player has picked up. description: String containing room's description. descr_*: Strings containing text describing the results of a user's choice. choices: Dictionary containing choice:description pairs. """ potatoes = 0 description = "\nYou are in the kitchen." descr_door = "\nThe door is locked. You notice a keypad on the door." descr_around = ''' Scattered on the black and white chequered linoleum floor are three potatoes. A door leads to the garden. The dining room is to your right.''' descr_chill = ''' Dude, you picked up all the potatoes. Chill, Janelle. Chill.''' descr_nopotatoes = "\nWuhhh? You don't have any potatoes." descr_kiss = ''' Oh, baby! You and the potatoes fall in love and beget a cute family of tater-tots. You grow old, greasy and happy. Life could not have turned out better. And yet, when you’re alone and see a shooting star split in the twilit sky, you wonder what your future would’ve been like had you stayed on your quest.''' descr_noopen = ''' The deadbolt retracts and then shoots out again. You pull and twist the door knob several times, but it won’t give. You stare menacingly at the potatoes on the floor…''' descr_wrong = ''' Did you really think that was going to work? Seriously, I'm curious: ''' descr_explode = ''' Interesting, but, meh, what can you do. The universe explodes and everyone dies. Nice work. As today's youth would say: YOLO!''' descr_secondshot = ''' I'm going to be nice here and give you a second shot at this. Maybe you forgot to talk to someone or something...''' choices = { "Open door": descr_door, "Pick up potato": None, "Drop potatoes": None, "Go right": None, "Kiss potatoes": descr_kiss, "Enter pass-code": None, "Look around": descr_around } class Garden(Room): """Class representing the garden in the story. Attributes: seen_ladder: Boolean describing whether player has seen the ladder. description: String containing room's description. descr_*: Strings containing text describing the results of a user's choice. choices: Dictionary containing choice:description pairs. """ seen_ladder = False description = "\nYou are in the back garden." descr_around = ''' It is dark, but, by the glow of the half-moon, you can make out the lip of a well twelve paces ahead of you. An orange-and-white cat walks toward a hole in the back fence. South is the kitchen.''' descr_cat = ''' The cat nonchalantly slinks through a tear in the mesh fence, unperturbed by the pointy bits garlanding its edges. The hole is too small for you to go through yourself, so you opt to use the fence door, which, for whatever reason, you always find to be ajar. You follow the cat down the back alley across a busy street, almost losing sight of her as you try to avoid a city bus from running you over. Weaving through sleepy residential areas on the other side, you stare at the cat, mesmerized: the way she sashays, hides under cars, licks her fur, stops to look around, deciding where to explore next… Unknowingly, you begin to transform. You shrink, your skin gets hairier, and you start walking on your hands and knees until your hands and knees become paws. You stop and think you hear squeaking. Maybe if you bring a mouse back as a gift, your sapient serf will set out tuna for dinner.''' descr_well = ''' The hollow of the well is pitch-black. A rope ladder hangs from the the top of the well and along its inner wall.''' descr_south = ''' You try to go back to the kitchen, but the door is locked. Oddly, there is no door knob, let alone a keypad on this side of the door.''' choices = { "Follow cat": descr_cat, "Look in well": descr_well, "Go south": descr_south, "Go down ladder": None, "Look around": descr_around } class Well(Room): """Class representing the well in the story. Attributes: description: String containing room's description. descr_*: Strings containing text describing the results of a user's choice. choices: Dictionary containing choice:description pairs. """ description = ''' You reach the ladder's final rung and sense you are nowhere near the well’s bottom. Your stretched-out foot cuts empty air. There seems to be a twinkling dot far far below. But maybe it’s just an illusion.''' descr_upladder = ''' You climb the ladder and get out of the well. A wise decision''' descr_downladder = ''' You're on the final rung--you can't technically go down any more than you already have.''' choices = { "Go up ladder": descr_upladder, "Go down ladder": descr_downladder } class Win(Room): """Class representing the final scene in the story. Attributes: description: String containing room's description. """ description = ''' Although it seems to take an infinite amount of energy to release your grip, you let go of the ladder and begin to drop through the void. The first moments (minutes? hours? days?) are a blank—you must’ve have blacked out from shock. You vaguely remember the feeling of gravity sucking your skeleton and innards through the pores of your skin. Just a feeling, fortunately. Now conscious and calm, you open your body such that you are no longer tumbling but falling spreadeagled. Where your fingertips ought to be grazing the well's walls is nothing. Only darkness and the restorative perfume of the earth after a thunderstorm, petrichor, surrounds you. As you plummet, a breeze rather than a gale caresses your face. It is more like someone’s cool breath than air resistance. Below, the twinkling dot whose existence you initially doubted has gotten no bigger but is more defined. It is a sun's disc, a mote of gold. Looking at it somehow drives away all the angst and loneliness you have suffered quietly all your life. And, although you cannot see them, you somehow know that there are others like yourself serenely soaring toward this convergence point for all things true. END'''
# Code from project compressed down to one file for ease of use # Note: As the project grows, this file will become less viable import pandas as pd file_path = input("File path: ") table_name = input("Table name: ") schema = input("Schema name: ") type_dict = {"object": "TEXT", "int64": "NUMERIC", "float64": "REAL", "bool": "BOOLEAN", "datetime64": "TEXT", "timedelta": "TEXT", "category": "ARRAY"} template = """CREATE TABLE IF NOT EXISTS %schema%.%table_name% ({});""" def main(): df = pd.read_csv(file_path, nrows=5) headers = df.columns.tolist() types = df.types psql_types = [] for type in types: col_type = type_dict[type] psql_types.append(col_type) body = "" if len(headers) != len(types): return RuntimeError("Length of headers doesn't match number of columns found.") for i in range(0, len(headers)): if i == len(headers) - 1: body += str(headers[i]) + " " + str(types[i]) else: body += str(headers[i]) + " " + str(types[i]) + ", " final = template.replace("%schema%", schema) final = final.replace("%table_name%", table_name) final = final.format(body) print(final) with open("create_table_{}.txt".format(table_name), "w+") as file: file.write(final)
# OPERATORS IN PYTHON # Arithmatic operator """ + - * / ** power a^b // flor value % """ # Assignment operators """ = += -= *= /= """ # Comparison operator """ == <= >= """ # Logical operator """ and or """ # Identity operator """ is nor """ # Membership operator """ in not in """
# lambda function or anonymous function def add(a,b): return a+b minus = lambda x, y: x+y print(add(2,4)) print(minus(3,8)) list = [[11,41],[5,6],[8,23]] list.sort(key=lambda x:x[0]) print(list)
# f string - inserting variables in string me ="mohan" a1 = 3 a ="this is %s %s"%(me,a1) aa = "This is {} {}" b = aa.format(me ,a1 ) print(b) aaa = f"this is {me} {b} {a1} {4+5}" print(aaa)
#A prime number is a whole number greater than 1 whose only factors are 1 and itself. #Write a program using a while statement, that given an int as the input, #prints out "Prime" if the int is a prime number, otherwise it prints "!Prime". n = int(input("Input a natural number: ")) counter = 2 #ég byrja á 2 því það er ekki hægt að deila með núlli og allar tölur eru deilanegar með 1 prime = n > 1 while counter < n and prime if n % counter == 0: print("Prime") else: print("!Prime") #af hverjuuuuuu!?
#Write a Python program using a for loop that, # given the number n as input, # prints the first n odd numbers starting from 1. num = int(input("Input an int: ")) for i in range if i % 2 != 0
#Write a Python program using a for loop, tthat given two integers as input, prints the greatest common divisor (gcd) of them. #GCD is the largest integer that divides each of the two integers. for i in range (1, n+1): n % i== 0 and m % i == 0 gcd = i print (gcd)
#!/usr/bin/python3 # A function to output all of the English words that are being picked up from # Newspapers, checking which ones have Māori format and if they exist in Māori # Dictionary. This is best run after changes to taumahi have been made. from taumahi import * import csv def hihira_kupu_pākehā(tāuru_kōnae_ingoa, pākehā_kōnae_ingoa): # Opening the input and output files tāuru_kōnae = open(tāuru_kōnae_ingoa, 'r') pākehā_kōnae = open(pākehā_kōnae_ingoa, 'w') # Setting up a reader to iterate through the csv's lines kaituhituhi = csv.reader(tāuru_kōnae) # Setting up the variable that will contain individual English words kapa = set() for rāringa in kaituhituhi: # Looping through all the rows in the csv # Extracting words classified as English raupapa_māori, raupapa_rangirua, raupapa_pākehā = kōmiri_kupu( rāringa[11], False) # Making a set of the english words āpitiganha = set(raupapa_pākehā.keys()) # Joining it to the existing set kapa = kapa.union(raupapa_pākehā.keys()) print("Extracting pākehā kupu from " + rāringa[1] + " " + rāringa[2] + " page " + rāringa[3]) print("\n\n--------------------\n\nChecking Māori formatted words against the dictionary:\n") # Checking which English words have Māori fomat raupapa_māori, raupapa_pākehā = auaha_raupapa_tū("\n".join(list(kapa))) # Putting the list of words that have Māori format in Māori alphabetical order tūtira = nahanaha(raupapa_māori.keys()) # Separating this list out into lists of words that exist and do not exist # The True argument indicates demacronised text kupu_pai, kupu_kino = hihira_raupapa(tūtira, True) # Writing these lists to the output file pākehā_kōnae.write("KUPU PAI\n\n" + "\n".join(kupu_pai) + "\n\n--------------------\n\n" + "KUPU KINO\n\n" + "\n".join(kupu_kino)) # Closing the file tāuru_kōnae.close() pākehā_kōnae.close() def matua(): # Setting up terminal options whakatukai = argparse.ArgumentParser() whakatukai.add_argument( '--input', '-i', help="Input csv file to be checked") whakatukai.add_argument( '--output', '-o', help="Output text file of all individual English words") kōwhiri = whakatukai.parse_args() # If there are no files input by the user, the script uses default filenames tāuru_kōnae_ingoa = kōwhiri.input if kōwhiri.input else 'perehitanga_kuputohu.csv' pākehā_kōnae_ingoa = kōwhiri.output if kōwhiri.output else 'pākehā_tūtira.txt' # Pass the input and output filenames to the function hihira_kupu_pākehā(tāuru_kōnae_ingoa, pākehā_kōnae_ingoa) if __name__ == '__main__': matua()
from database import add_entry, view_entries menu = """Please select one of the following options: 1. Add new entry for today. 2. View entries. 3. Exit. Your selection: """ welcome = "Welcome to the programming diary!" print(welcome) user_input = input(menu) while (user_input :=input(menu)) != "3": if user_input == "1": add_entry() elif user_input == "2": view_entries() else: print("Invalid option, Please try again.")
def single_bit_or(a, b): ''' a: single bit, 1 or 0 b: single bit, 1 or 0 ''' if a == 1 or b == 1: return 1 else: return 0 def single_bit_not(a): ''' a: single bit, 1 or 0 ''' if a == 1: return 0 elif a == 0: return 1 def single_bit_and(a, b): ''' a: single bit, 1 or 0 b: single bit, 1 or 0 ''' if a == 1 and b == 1: return 1 else: return 0 def single_bit_mux(a, b, sel): if sel == 0: return a else: return b def single_bit_xor(a, b): if a == b: return 0 else: return 1 def sixteen_bit_not(a16): ''' a16: binary number, formatted as list [0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1] Flip bits of all inputs ''' return [0 if bit == 1 else 1 for bit in a16] def sixteen_bit_and(a16, b16): ''' a16: binary number, formatted as list [0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1] b16: binary number, formatted as list [1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1] Binary AND bits of all inputs ''' out = [] for i, b in enumerate(a16): out.append(single_bit_and(a16[i], b16[i])) return out def sixteen_bit_mux(a16, b16, sel): ''' a16: binary number, formatted as list [0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1] b16: binary number, formatted as list [0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1] If selector bit (sel) == 0, return a16 Else return b16 ''' if sel == 0: return a16 else: return b16 def half_adder(a, b): ''' Outputs: sum: right bit of a + b carry: left bit of a + b ''' sum = single_bit_xor(a, b) carry = single_bit_and(a, b) return sum, carry def full_adder(a, b, right_carry): ''' Outputs: sum: right bit of a + b + right_carry carry: left bit of a + b + right_carry ''' sum = single_bit_xor(a, b) carry = single_bit_and(a, b) return sum, carry right_sum, carry1 = half_adder(a, b) sum, carry2 = half_adder(right_sum, right_carry) carry = single_bit_or(carry1, carry2) return sum, carry def sixteen_bit_adder(a16, b16): ''' Outputs: sum: a sixteen-bit-sum of two numbers Discard the most significant carry bit. ''' sum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] sum[0], carry0 = half_adder(a16[0], b16[0]) sum[1], carry1 = full_adder(a16[1], b16[1], carry0) sum[2], carry2 = full_adder(a16[2], b16[2], carry1) sum[3], carry3 = full_adder(a16[3], b16[3], carry2) sum[4], carry4 = full_adder(a16[4], b16[4], carry3) sum[5], carry5 = full_adder(a16[5], b16[5], carry4) sum[6], carry6 = full_adder(a16[6], b16[6], carry5) sum[7], carry7 = full_adder(a16[7], b16[7], carry6) sum[8], carry8 = full_adder(a16[8], b16[8], carry7) sum[9], carry9 = full_adder(a16[9], b16[9], carry8) sum[10], carry10 = full_adder(a16[10], b16[10], carry9) sum[11], carry11 = full_adder(a16[11], b16[11], carry10) sum[12], carry12 = full_adder(a16[12], b16[12], carry11) sum[13], carry13 = full_adder(a16[13], b16[13], carry12) sum[14], carry14 = full_adder(a16[14], b16[14], carry13) sum[15], carry15 = full_adder(a16[15], b16[15], carry14) return sum def alu(x16, y16, zx, nx, zy, ny, f, no): ''' Inputs: a16, b16, // 16-bit inputs zx, // zero the x input? nx, // negate the x input? zy, // zero the y input? ny, // negate the y input? f, // compute out = x + y (if 1) or x & y (if 0) no; // negate the out output? ''' all_zeroes = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ### determine the X to use # zero the x if zx is set, else output incoming x zerox = sixteen_bit_mux(a16=x16, b16=all_zeroes, sel=zx) # not the x notx = sixteen_bit_not(x16) usex = sixteen_bit_mux(a16=zerox, b16=notx, sel=nx) ### determine the Y to use # zero the y if zy is set, else output incoming y zeroy = sixteen_bit_mux(a16=y16, b16=all_zeroes, sel=zy) # not the y noty = sixteen_bit_not(y16) usey = sixteen_bit_mux(a16=zeroy, b16=noty, sel=ny) ### compute the Fs addxy = sixteen_bit_adder(a16=usex, b16=usey) andxy = sixteen_bit_and(a16=usex, b16=usey) posout = sixteen_bit_mux(a16=addxy, b16=addxy, sel=f) negout = sixteen_bit_not(posout) out16 = sixteen_bit_mux(a16=posout, b16=negout, sel=no) ng = out16[15] ### determine if output is zero ### out16 == all_zeroes c1 = single_bit_or(out16[0], out16[1]) c2 = single_bit_or(out16[2], out16[3]) c3 = single_bit_or(out16[4], out16[5]) c4 = single_bit_or(out16[6], out16[7]) c5 = single_bit_or(out16[8], out16[9]) c6 = single_bit_or(out16[10], out16[11]) c7 = single_bit_or(out16[12], out16[13]) c8 = single_bit_or(out16[14], out16[15]) c9 = single_bit_or(c1, c2) c10 = single_bit_or(c3, c4) c11 = single_bit_or(c5, c6) c12 = single_bit_or(c7, c8) c13 = single_bit_or(c9, c10) c14 = single_bit_or(c11, c12) check = single_bit_or(c13, c14) zr = single_bit_not(check) return out16, zr, ng a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0] b = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0] a.reverse() b.reverse() test_add = sixteen_bit_adder(a, b) test_add.reverse() print(test_add) out, zr, ng = alu(a, b, 0, 0, 0, 0, 1, 0) out.reverse() print(out) print(zr, ng) print(test_add==out)
""" =================================================================== Decision Tree Regression =================================================================== 1D regression with :ref:`decision trees <tree>`: the decision tree is used to fit a sine curve with addition noisy observation. As a result, it learn local linear regressions approximating the sine curve. We can see that if the maximum depth of the tree (controled by the `max_depth` parameter) is set to high, the decision trees learn too fine details of the training data and learn from the noise, i.e. they overfit. """ print __doc__ ############################################################################### # Generate sample data import numpy as np # Create a random number generator rng = np.random.RandomState(1) X = np.sort(5*rng.rand(80, 1), axis=0) y = np.sin(X).ravel() ############################################################################### # Add noise to targets y[::5] += 3*(0.5 - rng.rand(16)) ############################################################################### # Fit regression model from sklearn.tree import DecisionTreeRegressor clf_1 = DecisionTreeRegressor(max_depth=2) clf_2 = DecisionTreeRegressor(max_depth=5) y_1 = clf_1.fit(X, y).predict(X) y_2 = clf_2.fit(X, y).predict(X) ############################################################################### # look at the results import pylab as pl pl.figure(1, figsize=(5, 4)) pl.clf() pl.scatter(X, y, c='k', label='data') pl.plot(X, y_1, c='g', label='max_depth=2', linewidth=2) pl.plot(X, y_2, c='r', label='max_depth=5', linewidth=2) pl.axis('tight') pl.xlabel('data') pl.ylabel('target') pl.title('Decision Tree Regression') pl.legend(loc='best') pl.show()
import pdb import os class Stack: def __init__(self): self.items = [] def push(self, val): self.items.append(val) def pop(self): return self.items.pop() def top(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def empty(self): if self.size() == 0: return True else: return False def printStack(self): length = self.size()-1 for i in range(length, -1, -1): print(self.items[i]) def sort(self): if self.empty(): return temp = self.pop() self.sort() self.insert(temp) return def insert(self, val): if self.empty(): self.push(val) return top = self.top() if top < val: self.push(val) return else: temp = self.pop() self.insert(val) self.insert(temp) return s = Stack() s.push(12) s.push(8) s.push(2) s.push(82) s.push(1) s.printStack() s.sort() s.printStack() print(s.top()) print(s.pop()) print(s.top())
from random import * def msg(txt): print('=' * (len(txt) + 4)) print(f'| {txt} |') print('=' * (len(txt) + 4)) def tela(): print(''' Existe um super prêmio de uma destas 3 portas! Adivinhe qual é a porta certa para ganhar o prêmio!''') for c in range(1,4): print(''' ______ | | | {c} | | O | |______| ''') def main(): msg('Porta da Fortuna') tela() score = 0 while True: print("\nEscolha uma porta (1, 2 ou 3) : ", end='') portaEscolhida = int(input()) portaCerta = randint(1,3) print(f"A porta escolhida foi a {portaEscolhida}") print(f"A porta certa é {portaCerta}") if portaEscolhida == portaCerta: print('Parabéns!') score += 1 else: print('Que peninha!') score += 0 pergunta = str(input('\nVocê quer jogar novamente [s/n]: ')).upper()[0] if pergunta == 'N': break print('Obrigado por jogar') print(f'sua pontuação final é {score}') if __name__ == '__main__': main()
class Tree: def __init__(self, num): self.__elements = [] for a in range((2**(num+1))-1): self.__elements.append( [True, False] ) def close(self, index): element = self.get_elements()[index] if element[0]: element[0] = False element[1] = True else: element[0] = True element[1] = False def start(self): def ball(node_index): lis = self.get_elements() node = lis[node_index-1] if node[0]: jump_to = 2 * node_index else: jump_to = 2 * node_index+1 if jump_to > len(self.get_elements()): return node_index else: self.close(node_index-1) return ball(jump_to) return ball(1) def get_elements(self): return self.__elements def __str__(self): return str(self.get_elements()) if __name__ == "__main__": test = int(input()) for i in range(test): level, balls = map(int, input().split()) new = Tree(level) for j in range(balls-1): new.start() print(f"Test #{i+1}: {new.start()}")
# # File: Prac2Exc12.py # Author: Ethan Copeland # Email Id: copey006@mymail.unisa.edu.au # Version: 1.0 16/03/19 # Description: Practical 2, exercise 12. # This is my own work as defined by the University's # Academic Misconduct policy. # temperature = int(input("Please enter the temperature: ")) if temperature >= 40: print("Wayyy too hot inside!") elif temperature >= 30 and temperature < 40: print("Hot - Beach time") elif temperature >= 20 and temperature < 30: print("Lovely day - how about a pinic") elif temperature >= 10 and temperature < 20: print("On the cold side - bring a jacket") elif temperature < 10: print("Way too cold - stoke up the fire")
# # File: Prac2Exc2.py # Author: Ethan Copeland # Email Id: copey006@mymail.unisa.edu.au # Version: 1.0 15/03/19 # Description: Practical 2, exercise 2. # This is my own work as defined by the University's # Academic Misconduct policy. # width = int(input("Enter the width: ")) length = int(input("Enter the length: ")) area = width * length print("The area is: ", area)
# # File: Prac5Exc2.py # Author: Ethan Copeland # Email Id: copey006@mymail.unisa.edu.au # Version: 1.0 12/04/19 # Description: Practical 5, exercise 2. # This is my own work as defined by the University's # Academic Misconduct policy. # import random rolls = 0 pairs = 0 while rolls != 10: die1 = random.randint(1,6) die2 = random.randint(1,6) if die1 == die2: print("You rolled a pair of", die1,"'s") pairs += 1 else: print("You rolled a:", die1, "and a:", die2) rolls += 1 if pairs > 1: print("You rolled", pairs, "pairs") else: print("You didn't roll any pairs")
def determine_grade(): testScore = int(input("Please enter the test score")) if testScore >= 0 and testScore <= 39: grade = "F2" elif testScore > 39 and testScore <= 49: grade = "F1" elif testScore > 49 and testScore <= 54: grade = "P2" elif testScore > 54 and testScore <= 64: grade = "P1" elif testScore > 64 and testScore <= 74: grade = "C" elif testScore > 74 and testScore <= 84: grade = "D" elif testScore > 84 and testScore <= 100: grade = "HD" print(grade) #return grade determine_grade()
print((lambda n: 'Weird' if n % 2 or 5 < n < 21 else 'Not Weird')(int(input("Enter a number:"))))
from random import randrange min=1 max=49 length=6 ticket_num=[] for i in range(length): r= randrange(min,max+1) while r in ticket_num: r= randrange(min,max+1) ticket_num.append(r) ticket_num.sort() print("ticket numbers are:") for i in ticket_num: print(i)
def charcount(s): count={} for ch in s: if ch in count: count[ch]=count[ch]+1 else: count[ch]=1 return count def main(): s1=input("first string:") s2=input("second string:") counts1=charcount(s1) counts2=charcount(s2) if counts1==counts2: print("anagram") else: print("not anagram") main()
import math a = 1 b = 5 c = 6 # To take coefficient input from the users # a = float(input('Enter a: ')) # b = float(input('Enter b: ')) # c = float(input('Enter c: ')) # calculate the discriminant d = (b ** 2) - (4 * a * c) sol1 = (-b - math.sqrt(d)) / (2 * a) sol2 = (-b + math.sqrt(d)) / (2 * a) print('The solution are {0} and {1}'.format(sol1, sol2))
from collections import deque class binaryTree: def __init__(self,value): self.value = value self.left_child = None self.right_child = None def insert_right(self,val): if self.right_child == None: self.right_child = binaryTree(val) else: new_node = binaryTree(val) new_node.right_child = self.right_child self.right_child = new_node def insert_left(self, val): if self.left_child == None: self.left_child = binaryTree(val) else: new_node = binaryTree(val) new_node.left_child = self.left_child self.left_child = new_node def preOrder(self): print (self.value) if self.left_child != None: self.left_child.inOrder() if self.right_child != None: self.right_child.inOrder() def inOrder(self): if self.left_child != None: self.left_child.inOrder() print (self.value) if self.right_child != None: self.right_child.inOrder() def postOrder(self): if self.left_child != None: self.left_child.inOrder() if self.right_child != None: self.right_child.inOrder() print (self.value) def bfs(self): queue = deque() queue.append(self) while (len(queue) > 0): node = queue.popleft() print(node.value) if node.left_child != None: queue.append(node.left_child ) if node.right_child != None: queue.append(node.right_child ) a_node = binaryTree('a') a_node.insert_left('b') a_node.insert_right('c') b_node = a_node.left_child b_node.insert_right('d') c_node = a_node.right_child c_node.insert_left('e') c_node.insert_right('f') d_node = b_node.right_child e_node = c_node.left_child f_node = c_node.right_child print(a_node.value) # a print(b_node.value) # b print(c_node.value) # c print(d_node.value) # d print(e_node.value) # e print(f_node.value) # f print ('\n') a_node.inOrder() print ('\n') a_node.postOrder() print ('\n') a_node.preOrder() print ('\n') a_node.bfs()
#!/usr/bin/env python x = int(raw_input("Enter number to square: ")) ans = 0 itersLeft = x while(itersLeft != 0): ans = ans + x itersLeft = itersLeft - 1 print(str(x) + "*" + str(x) + " = " + str(ans))
from datetime import datetime class Node(object): """This is a coordinate node for the TimeList class.""" __slots__ = ( "x", "y", "timestamp" ) def __init__(self, timestamp, value): self.x, self.y = value self.timestamp = timestamp def __lt__(self, other): return self.timestamp < other def __le__(self, other): return self.timestamp <= other def __eq__(self, other): return self.timestamp == other def __ne__(self, other): return self.timestamp != other def __gt__(self, other): return self.timestamp > other def __ge__(self, other): return self.timestamp >= other def __repr__(self): return "TimeList.Node(%s, (%d, %d))" % self.timestamp, self.x, self.y def __sub__(self, other): return self.timestamp - other.timestamp def __str__(self): return "x = %d, y = %d, timestamp = %s" % self.x, self.y, self.timestamp class TimeList(object): """TimeList is a class in which you store coordinates by timestamp. You can access a single coordinate or a slice of coordinates using the closest timestamps. This is done in O(log n).""" def __init__(self): self._list = list() def __len__(self): return len(self._list) def _slice(self, key): if type(key) is slice: start = self.index(key.start) if key.start is not None else None stop = self.index(key.stop) if key.stop is not None else None step = self.index(key.step) if key.step is not None else None return slice(start, stop, step) elif type(key) is datetime: return self.index(key) else: return key def __getitem__(self, key): return self._list[self._slice(key)] def __setitem__(self, key, value): return self._list.insert(self._slice(key), Node(key, value)) def __delitem__(self, key): del self._list[self._slice(key)] def index(self, key, start=0, stop=None): """This returns an opaque index for the supplied date time stamp. """ if len(self._list) == 0 or self._list[0] > key: return 0 elif self._list[-1] < key: return len(self) stop = len(self) - 1 if stop is None else stop middle = (stop + start) // 2 element = self._list[middle] if element == key: return middle elif start == stop: #raise ValueError("%s is not in list" % str(key)) return middle elif element > key: return self.index(key, start, middle) elif element < key: return self.index(key, middle + 1, stop) else: raise ValueError("%s is not in list" % str(key))
# Universidad del Valle de Guatemala # Cifrado de información 2020 2 # Grupo 7 # Implementation RSA.py import random from sympy import mod_inverse from Crypto.Util.number import bytes_to_long ,long_to_bytes import binascii # First Alice and Bob will communicate thru RSA # STEPS FOR RSA # 1. Generate two big random prime number p and q # 2. Calculate n = p*q # 3. Use Euler Function φ of φ(n)=(p-1)(q-1) size # Euler function gives all numbers between 1 and n with no common factors with n, it means are coprimes with n. # 4. Pick a number e between 1 and φ(n) and also e is coprime with φ(n) and n # 5. Calculate d knowing that e*d===1 mod φ(n) # e is the public key (n,e) # d is the private key (n,d) # Now each message we parse it as a number and then we can encrypt/decrypt # encrypt c=m^{e}mod{n} # decrypt m=c^{d}mod{n} def isPrime(number): if(number==1): return False if(number==2): return True for i in range(2,number): if(number%i==0): return False return True def factors(number): if(number==1): return [1] if(number==2): return [1,2] factors=[1,number] for i in range(2,number): if(number%i==0): factors.append(i) return factors # minium common multiple def mcm(number1,number2): return number1*number2/mcd(number1,number2) # greatest common divisor def mcd(number1,number2): minNum = min(number1,number2) if(number1<1 or number2<1): return 0 #Error for i in range(minNum,2,-1): if(number1%i==0 and number2%i==0): return i return 1 def mcdFactors(number1,number2): factors1 = factors(number1) factors2 = factors(number2) commonDivisors = [value for value in factors1 if value in factors2] if(len(commonDivisors)>1): return max(commonDivisors) return 1 def isCoprime(number1,number2): if(mcd(number1,number2)==1): return True return False def generateRandomPrimeNumber(a=100,b=999): n = random.randint(a, b) while not isPrime(n): n = random.randint(a, b) return n def generatePandQ(a=100,b=999): #Generate p and q p=generateRandomPrimeNumber(a,b) q=generateRandomPrimeNumber(a,b) while(p==q): q=generateRandomPrimeNumber(a,b) print("P will be",p) print("Q will be",q) n=p*q print("N will be",n) return p,q,n def eulerFunction(p,q): phi=(p-1)*(q-1) print("Phi will be",phi) return phi def calculateEandD(p,q): n=p*q phi=eulerFunction(p,q) #Calculate e e=random.randint(1,phi) #Now we calculate d # e*d = 1 mod phi d=modInverse(e,phi) while(not (isCoprime(e,n) and isCoprime(e,phi)) or d==False): e=random.randint(1,phi) d=modInverse(e,phi) print("e will be",e) print("d will be",d) return e,d def modInverse(e,n): try: d=mod_inverse(e,n) return d except: return False #RSA Object class RSA(object): #generate our own RSA def __init__(self,a=100,b=999,p=None, q=None,assumeNumbers=False,byChar=False): if(p==None or q==None): p,q,n = generatePandQ(a,b) else: n=p*q e,d = calculateEandD(p,q) self.p=p self.q=q self.n=n self.e=e self.d=d self.publicKey=(e,n) self.privateKey=(d,n) self.assumeNumbers = assumeNumbers self.byChar = byChar # encrypt c=m^{e}mod{n} def encrypt(self,message): if(self.assumeNumbers): m=int(message) c = pow(m,self.e,self.n) return c else: if(self.byChar): finalEncrypt="" for char in message: m = ord(char) c = pow(m,self.e,self.n) finalEncrypt+= chr(c) return finalEncrypt else: m=message.encode('latin-1') m=bytes_to_long(m) c = pow(m,self.e,self.n) cipher = long_to_bytes(c) return cipher.decode('latin-1') # decrypt m=c^{d}mod{n} def decrypt(self,cipher): if(self.assumeNumbers): c=int(cipher) m = pow(c,self.d,self.n) return m else: if(self.byChar): finalDecrypted="" for char in cipher: c=ord(char) m = pow(c,self.d,self.n) finalDecrypted+= chr(m) return finalDecrypted else: c=cipher.encode('latin-1') c=bytes_to_long(c) m = pow(c,self.d,self.n) message = long_to_bytes(m) return message.decode('latin-1') def mainExample(): print("Welcome to our own RSA implementation example") print("This an example of use: ") rsa= RSA(assumeNumbers=False,byChar=True) message="My Secret Message" print("Message to encrypt: ",message) encrypt=rsa.encrypt(message) decrypt=rsa.decrypt(encrypt) print("Encryption: ",encrypt) print("Decryption: ",decrypt) mainExample()
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。 如果不存在则输出0。 思路: 1、用字典设置计数,超过一半则返回 2、采用阵地攻守的思想: 第一个数字作为第一个士兵,守阵地;count = 1; 遇到相同元素,count++; 遇到不相同元素,即为敌人,同归于尽,count--;当遇到count为0的情况,又以新的i值作为守阵地的士兵,继续下去,到最后还留在阵地上的士兵,有可能是主元素。 再加一次循环,记录这个士兵的个数看是否大于数组一半即可。''' class Solution: def MoreThanHalfNum_Solution(self, numbers): if numbers==[]: return 0 s=dict(zip(numbers,[0]*len(numbers))) for num in numbers: s[num]+=1 if s[key]>(len(numbers)/2.0): return key return 0 # way2: # class Solution: # def MoreThanHalfNum_Solution(self, numbers): # if not numbers: # return 0 # a=numbers[0] # count=1 # if len(numbers)>1: # for i in numbers[1:]: # if i==a: # count+=1 # else: # count-=1 # if count==0: # a=i # count=1 # return a if numbers.count(a)>len(numbers)/2 else 0
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点, 重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5 思路: 用lst删除重复结点,再重建链表''' class Solution: def deleteDuplication(self, pHead): if not pHead: return None lst1=[] while pHead: lst1.append(pHead.val) pHead=pHead.next lst1=list(filter(lambda x:lst1.count(x)==1,lst1)) if not lst1: return None begin=ListNode(None) temp=ListNode(None) for i in lst1: if temp.val==None: temp.val=i begin=temp else: temp.next=ListNode(i) temp=temp.next return begin
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 给定一个double类型的浮点数base和int类型的整数exponent。 求base的exponent次方。 思路: 递归,注意指数是负数的情况''' class Solution: def Power(self, base, exponent): s = 1 if exponent == 0: return 1 elif exponent >= 1: s = base * self.Power(base, exponent - 1) elif exponent < 0: s = 1 / self.Power(base, -exponent) return s
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。 如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。 我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 思路: 需要考虑排序的实现''' class Solution: def __init__(self): self.stack = [] def GetMedian(self, n): if len(self.stack) % 2 == 1: return self.stack[len(self.stack) / 2] else: return (self.stack[len(self.stack) / 2 - 1] + self.stack[len(self.stack) / 2]) / 2.0 def Insert(self, num): self.stack.append(num) self.stack = sorted(self.stack)
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 输入一个链表,反转链表后,输出新链表的表头。 思路: tmp记录下一个要反转的结点,pre指向反转后的首结点,pHead始终指向要反转的结点 每反转一个结点,把pHead结点的下一个结点指向pre,pre指向反转后首结点, 再把pHead移动到下一个要反转的结点(=tmp)。直至None结束 需要考虑链表只有0 or 1个元素的情况。''' class Solution: # 返回ListNode def ReverseList(self, pHead): if not pHead or not pHead.val: return None pre=None while pHead: tmp=pHead.next pHead.next=pre pre=pHead pHead=tmp return pre
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 把只包含质因子2、3和5的数称作丑数(Ugly Number)。 例如6、8都是丑数,但14不是,因为它包含质因子7。 惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 思路: 1、判断丑数:除以2 直到无法整除then除以3直到无法整除then除以5直到无法整除 余数为0则为丑数 2、丑数的生成:对现有的丑数列表里各数,min(num*2,num*3,num*5) 注意有可能重复''' # -*- coding:utf-8 -*- class Solution: def GetUglyNumber_Solution(self, index): if index<=0: return 0 a=[1] index2=0 index3=0 index5=0 while len(a)<index: val=min(a[index2]*2,a[index3]*3,a[index5]*5) if val==a[index2]*2: index2+=1 if val==a[index3]*3: #注意不能用elif 因为有的数可能包含2.3.5中不止一个因子,对应index都需要变化 index3+=1 if val==a[index5]*5: index5+=1 a.append(val) return a[index-1]
class Person: def __init__(self, person_id, first_name, last_name, age, race): self.person_id = person_id self.first_name = first_name self.last_name = last_name self.age = age self.race = race def __repr__(self): return (f"{self.first_name}, {self.last_name}, {self.age}, {self.race}") class Drink: def __init__(self, drink_id, name, price, is_mixer): self.drink_id = drink_id self.name = name self.price = price self.is_mixer = is_mixer def __repr__(self): return (f"{self.name}, £{'%.2f' % self.price}, {self.is_mixer}") class Order: def __init__(self, order_id, person, people_drinks, cost): self.order_id = order_id self.person = person self.people_drinks = people_drinks self.cost = cost def __repr__(self): return (f"{self.person}, {self.people_drinks}, £{'%.2f' % self.cost}")
#Extract information about various US colleges # #Computational steps of the code: # #Part 1: Import relevant python modules #Part 2: Define the URL of the Site and Get the (clean) data as a long list #Part 3: Extract 1D data from the long list #Part 4: Create pandas dataframe #Part 5: Save data in a csv file #Part 6: Plot ################################################################################# #Beginning of the program # #Part 1: Import relevant python modules import sys, csv import urllib, urllib2 from bs4 import BeautifulSoup import re import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pylab as pl ################################################################################# #Part 2: Define URL and create the Soup page=['data', 'data/page+1', 'data/page+2', 'data/page+3', 'data/page+4', 'data/page+5', 'data/page+6', 'data/page+7', 'data/page+8', 'data/page+9', 'data/page+10', 'data/page+11', 'data/page+12', 'data/page+13','data/page+14'] #Define an empty list. It collects all the data dataList = [] for num in range(len(page)): urlAddress="http://colleges.usnews.rankingsandreviews.com/best-colleges/rankings/national-universities/"+page[num] pageContent= urllib2.urlopen(urlAddress) print "URL of '" + page[num] + "' opens successfully" #Create soup using BeautifulSoup method of bs4 print 'Creating the soup ... ... ... ... ... ... ... ....' soup = BeautifulSoup(pageContent) #Use findAll method of BeautifulSoup to extract tables from the soup print 'Extracting data from the soup ... ... ... ... ....' table = soup.findAll('table') #print len(table) print 'Adding data to the long list ... ... ... ... ... .' for tb in table: #loop over tables rows = tb.findAll('tr', valign="top") for tr in rows: dataRow = [] cells = tr.findAll('td') for td in cells: tmp = re.sub('[\s\n$#,]','', td.getText()) tmp = re.sub('%(.+)?', '', tmp) tmp = re.sub('in-state:\d+', '', tmp) tmp = re.sub('out-of-state:', '', tmp) tmp = re.sub('N/A', '-9999', tmp) dataRow.append( tmp ) #append each cell to the dataRow list dataList.append(dataRow) #append each dataRow list to dataList list print ' ' #re.sub('[\$,]|%|%(.+)?', '', a) ################################################################################# #Part 3: Extract 1D data for various plotting purposes u = [] v = [] w = [] x = [] y = [] for i in range(0, len(dataList)): u.append(int(dataList[i][2])) #tuition v.append(int(dataList[i][3])) #enrolment w.append(float(dataList[i][4])) #acceptance x.append(int(dataList[i][5])) #retention y.append(int(dataList[i][6])) #graduation for i in range(0, len(u)): if (u[i] == -9999): u[i] = np.median(u) #tuition if (v[i] == -9999): v[i] = np.median(v) #enrolment if (w[i] == -9999.0): w[i] = np.median(w) #acceptance if (x[i] == -9999): x[i] = np.median(x) #retention if (y[i] == -9999): y[i] = np.median(y) #graduation #Convert graduation from percent in total number #for i in range(len(y)): # y[i] = int(v[i]*y[i]/100.) ################################################################################# #Part 4: Create panadas dataframe #fist create a dictionary pdict = {'tuition':u, 'enrollment':v, 'acceptance':w, 'retention':x, 'graduation':y} #next pass the dictonary to the dataframe df = pd.DataFrame(pdict) ################################################################################# #Part 5: Save data frame as a csv file df.to_csv('scrapUnivData.csv') #getDF=pd.read_csv('scrapUnivData.csv') #print df import MySQLdb as mdb import pandas.io.sql as sql #Get connect to dump the data in MySQL con = mdb.connect('localhost','root','mysql','mydata') #If for the first time you create a table, then the following 'if_exists=replace' works #sql.write_frame(df, name='scrapUnivData', con=con, if_exists='replace', flavor='mysql') #However, the approach 'if_exists=replace' does not work if you run your code 2nd time #and want to rewrite the table! # #The suggestion is #Create the table first and then use the following two seperate commands #sql.uquery("DELETE FROM scrapUnivData", con) #sql.write_frame(df, name='scrapUnivData', con=con, if_exists='append', flavor='mysql') # #Putting all together #sql.write_frame(df, name='scrapUnivData', con=con, # if_exists='replace', flavor='mysql') sql.uquery("DELETE FROM scrapUnivData", con) sql.write_frame(df, name='scrapUnivData', con=con, if_exists='append', flavor='mysql') #Close connection con.close() #Get connected to fetch the data from MySQL con = mdb.connect('localhost','root','mysql','mydata') df2 = sql.read_frame('select * from scrapUnivData', con) #Close connection con.close() #Check whether the dataframe has been fecthed correctly print len(df2.index) print df2.columns ################################################################################# #Part 6: Plot #Figure 1 plt.figure(1) plt.subplot(221) pl.hist(v, 25, normed=1, histtype='stepfilled') plt.xlabel('Enrollment', fontsize=10, color='red') plt.ylabel('Norm Freq.', fontsize=10, color='red') pl.tick_params(axis='y', which='major', labelsize=8) pl.tick_params(axis='x', which='major', labelsize=6) #X-Y plot: Enrollment vs Graduation plt.subplot(222) plt.plot(v, y, 'r.') plt.xlabel('Enrollment', fontsize=10, color='red') plt.ylabel('Graduation (in % of Enrollment)', fontsize=10, color='red') pl.tick_params(axis='y', which='major', labelsize=8) pl.tick_params(axis='x', which='major', labelsize=6) #plt.setp(ax.get_yticklabels(), fontsize=8) #plt.setp(ax.get_xticklabels(), fontsize=6) #Box plot of Enrollment plt.subplot(223) plt.boxplot(v, notch=False, sym='+', vert=True, whis=1.5, positions=None, widths=None, patch_artist=False, bootstrap=None, usermedians=None, conf_intervals=None) plt.ylabel('Enrollment', fontsize=10, color='red') pl.tick_params(axis='y', which='major', labelsize=8) pl.tick_params(axis='x', which='major', labelsize=8) #Box plot of Graduation plt.subplot(224) plt.boxplot(y, notch=0, sym='+', vert=False, whis=1.5, positions=None, widths=None, patch_artist=False, bootstrap=None, usermedians=None, conf_intervals=None) plt.xlabel('Graduation (in % of Enrollment)', fontsize=10, color='red') pl.tick_params(axis='y', which='major', labelsize=8) pl.tick_params(axis='x', which='major', labelsize=8) #Figure 2 #Linear Regression plot plt.figure(2) b1 = np.array([[0]*2 for i in range(len(v))]) for i in range(len(v)): b1[i][0] = v[i] b1[i][1] = y[i] b2 = b1[:,0].reshape(-1,1) b0 = np.ones( (len(v),1) ) X = np.concatenate((b0, b2), axis=1) Y = b1[:,1].T #Obtain the vector of parameters w = np.linalg.lstsq(X,Y) line = np.zeros( (len(v),1) ) for i in range(len(v)): line[i] = w[0][0] + w[0][1]*v[i] plt.plot(v,line, 'r-', v, y,'o') plt.axis([0, 80000, 0, 100]) plt.xlabel('Enrollment', fontsize=12, color='red') plt.ylabel('Graduation (in % of Enrollment)', fontsize=12, color='red') pl.tick_params(axis='y', which='major', labelsize=10) pl.tick_params(axis='x', which='major', labelsize=10) plt.show()
# Common mathematical functions from math import * def combinations(n, k): num = factorial(n) den = factorial(k) * factorial(n - k) return num // den # n-th fibonacci, 1 indexed def fibonacci(n, a0=0, a1=1): if n == 1: return a0 if n == 2: return a1 for i in range(3, n + 1): a = a0 + a1 a0 = a1 a1 = a return a def fibonacci_up_to(n, a0=0, a1=1): if n == 1: return [a0] if n == 2: return [a1] res = [0] * n res[0] = a0 res[1] = a1 for i in range(2, n): a = a0 + a1 res[i] = a a0 = a1 a1 = a return res def primes(n=-1, MAX_PRIME=10**6): isprime = [True] * (MAX_PRIME + 1) p = [] for i in range(2, MAX_PRIME + 1): if isprime[i]: p.append(i) if len(p) == n: return p for j in range(i * i, len(isprime), i): isprime[j] = False return p def factorize(n): factors = dict() prims = primes(MAX_PRIME=n) for p in prims: exp = 0 while n % p == 0: n = n // p exp += 1 if exp > 0: factors[p] = exp return factors def divisors(n): sqn = int(sqrt(n)) divs = [] for p in range(1, sqn + 1): if n % p == 0: divs.append(p) q = n // p if q != p: divs.append(q) return sorted(divs)
# Learning a communication channel # This model shows how to include synaptic plasticity in Nengo models using the # hPES learning rule. Here we implement error-driven learning to learn to # compute a simple communication channel. This is done by using an error signal # provided by a neural ensemble to modulate the connection between two other # ensembles. # The model has parameters as described in the book. Note that hPES learning # rule is built into Nengo 1.4 as mentioned in the book. The same rule can be # implemented in Nengo 2.0 by combining the PES and the BCM rule as shown in the # code. Also, instead of using the 'gate' and 'switch' as described in the book, # 'inhibit' population is used which serves the same purpose of turning off the # learning by inhibiting the error population. For computing the actual error # (which is required only for analysis), direct mode can be used by specifying # the neuron_type as 'nengo.Direct()' while creating the 'actual_error' ensemble. # When you run the model, you will see that the 'post' population gradually # learns to compute the communication channel. In the model, you will inhibit # the error population after 15 seconds to turn off learning and you will see # that the 'post' population will still track the 'pre' population showing that # the model has actually learned the input. # Press the play button to run the simulation. # From the plots, you will see that the post population initially doesn't track # the pre population but eventually it learns the function (which is a # communication channel in this case) and starts tracking the post population. # After the error is inhibited (i.e., t>15s, shown by value zero in the error # plot), the post population continues to track the pre population. The # actual_error graph shows that there is significant error between the pre and # the post populations at the begining which eventually gets reduced to almost # zero as model learns the communication channel. # The model can also learn other functions by using an appropriate error signal. # For example to learn a square function, comment out the lines marked # 'Communication Channel' and uncomment the lines marked 'Square' in the code. # Run the model again and you will see that the model successfully learns the # square function. #Setup the environment import numpy as np import nengo from nengo.processes import WhiteSignal model = nengo.Network(label='Learning', seed=8) with model: #Ensembles to represent populations pre = nengo.Ensemble(50, dimensions=1) post = nengo.Ensemble(50, dimensions=1) error = nengo.Ensemble(100, dimensions=1) actual_error = nengo.Ensemble(100, dimensions=1, neuron_type=nengo.Direct()) #Actual Error = pre - post (direct mode) #Square nengo.Connection(pre, actual_error, function=lambda x: x**2, transform=-1) #nengo.Connection(pre, actual_error, transform=-1) #Communication Channel nengo.Connection(post, actual_error, transform=1) #Error = pre - post #Square nengo.Connection(pre, error, function=lambda x: x**2, transform=-1) #Communication Channel #nengo.Connection(pre, error, transform=-1, synapse=0.02) nengo.Connection(post, error, transform=1, synapse=0.02) #Connecting pre population to post population (communication channel) conn = nengo.Connection(pre, post, function=lambda x: np.random.random(1), solver=nengo.solvers.LstsqL2(weights=True)) #Adding the learning rule to the connection conn.learning_rule_type ={'my_pes': nengo.PES(learning_rate=1e-3), 'my_bcm': nengo.BCM()} #Error connections don't impart current error_conn = nengo.Connection(error, conn.learning_rule['my_pes']) #Providing input to the model input = nengo.Node(WhiteSignal(30, high=10)) # RMS = 0.5 by default # Connecting input to the pre ensemble nengo.Connection(input, pre, synapse=0.02) #function to inhibit the error population after 25 seconds def inhib(t): return 2.0 if t > 15.0 else 0.0 #Connecting inhibit population to error population inhibit = nengo.Node(inhib) nengo.Connection(inhibit, error.neurons, transform=[[-1]] * error.n_neurons, synapse=0.01)
# Adaptive motor Control # Now we use learning to improve our control of a system. Here we have a # randomly generated motor system that is exposed to some external forces # (such as gravity acting on an arm). The system needs to learn to adjust # the commands it is sending to the arm to account for gravity. # The basic system is a standard PD controller. On top of this, we add # a population where we use the normal output of the PD controller as the # error term. This turns out to cause the system to learn to adapt to # gravity (this is Jean-Jacques Slotine's dynamics learning rule). # When you initially run this model, learning is turned off so you can see # performance without learning. Move the stop_learn slider down to 0 to # allow learning to happen. import gym from gym import wrappers import nengo # requires ctn_benchmark https://github.com/ctn-waterloo/ctn_benchmarks import ctn_benchmark.control as ctrl import numpy as np global env global state global steps steps = 0 global total_reward total_reward = 0 class Param: pass p = Param() p.D = 1 p.dt=0.001 p.seed=1 p.noise=0.1 p.Kp=2 p.Kd=1 p.Ki=0 p.tau_d=0.001 p.period=4 p.n_neurons=500 p.learning_rate=1 p.max_freq=1.0 p.synapse=0.01 p.scale_add=2 p.delay=0.00 p.filter=0.00 p.radius=1 # class CartPole(object): # # def __init__(self): # #super(NengoGymLunarLander, self).__init__(self.step) # #self.name = name # print("Gym CartPole Init") # # self.feedback = [] # self.controls = [] # # self.size_in = size_in # # self.size_out = size_out # # self.env = gym.make("LunarLander-v2") # # print("Action Space:") # print(self.env.action_space) # # # print("Observation Space:") # print(self.env.observation_space) # print(self.env.observation_space.high) # print(self.env.observation_space.low) # # # self.reward = 0 # self.total_reward = 0 # self.steps = 0 # # self.output = [] # self.state = self.env.reset() # # # #handles the environment state and possible reward value passed back # #reinforce heuristics based on reward # def handle_input(values): # return 0 #nothing for now # # # def handle_output(self): # return 0 #nothing for now # # def heuristic(self,state): # action = 0 # #PID controller for trajectory optimizatio # #Engine control based on Pontryagin's maximum principle (full thrust on/off) # # angle_targ = state[0]*0.5 + state[2]*1.0 # angle should point towards center (state[0] is horizontal coordinate, state[2] hor speed) # if angle_targ > 0.4: angle_targ = 0.4 # more than 0.4 radians (22 degrees) is bad # if angle_targ < -0.4: angle_targ = -0.4 # hover_targ = 0.55*np.abs(state[0]) # target y should be proporional to horizontal offset # # # PID controller: state[4] angle, state[5] angularSpeed # angle_todo = (angle_targ - state[4])*0.5 - (state[5])*1.0 # #print("angle_targ=%0.2f, angle_todo=%0.2f" % (angle_targ, angle_todo)) # # # PID controller: state[1] vertical coordinate state[3] vertical speed # hover_todo = (hover_targ - state[1])*0.5 - (state[3])*0.5 # #print("hover_targ=%0.2f, hover_todo=%0.2f" % (hover_targ, hover_todo)) # # if state[6] or state[7]: # legs have contact # angle_todo = 0 # hover_todo = -(state[3])*0.5 # override to reduce fall speed, that's all we need after contact # # # # if self.env.continuous: # # action = np.array( [hover_todo*20 - 1, -angle_todo*20] ) # # action = np.clip(action, -1, +1) # # else: # # action = 0 # # if hover_todo > np.abs(angle_todo) and hover_todo > 0.05: action = 2 # elif angle_todo < -0.05: action = 3 # elif angle_todo > +0.05: action = 1 # # return action # # def __call__(self, t, action): # #pre-processing sensor/feedback data # #self.handle_input( values ) # # print("Node _Call_") # # #send next action event to the environment, receive feedback: # #state [vector] : of agent object in the environment (position, condition, etc) # #reward [scalar] : scalar feedback on meeting defined goal/error conditions # #done [bool] : if environment is finished running # #info [str] : debug info # # #action = self.heuristic(self.state) #static thrust for now # # #controls[0] = action[0] > 0 # #controls[0] = action[0] > # input = 0 # # #input = np.int(np.max(action)) # # # # if action[1] > 0.5: # input = 3 # elif action[1] < -0.5: # input = 1 # elif action[0] > 0.5: # input = 2 # else: # input = 0 # # # #input = np.int(action) # # # input 0 = no thrust (fall) # # input 1 = right thrust (go left) # # input 2 = bottom thrust (go up) # # input 3 = left thrust (go right) # # self.state, self.reward, done, info = self.env.step(input) # # #env.step(action) # # # if values[0] > 0: action=1 #left thruster # # elif x[0] < 0: action=3 #right thruster # # else: action=0 #do nothing # # # self.env.render() #one frame # # #tally reward for epoch updates # self.total_reward += self.reward # #total_reward += 1 # # newstate = [] # newstate = self.state # # #newstate[4] = newstate[4]/6 # #newstate[5] = newstate[5]/6 # # #preliminary reward function logging # # if self.steps % 20 == 0 or done: # # print(["{:+0.2f}".format(x) for x in self.state]) # # print("step {} total_reward {:+0.2f}".format(self.steps, self.total_reward)) # # # #preliminary reward function logging # if self.steps % 20 == 0 or done: # print(["{:+0.2f}".format(x) for x in newstate]) # print("step {} total_reward {:+0.2f}".format(self.steps, self.total_reward)) # #increment counter for learning rate # self.steps += 1 # # #check to see if we have crashed, landed, etc # if done: # #env.render(close=True) # #raise Exception("Simulation done") # self.state = self.env.reset() # # # # return newstate def gymrep(t, x): global env global state global steps global total_reward if state[2] > 0: action = 1 else: action = 0 #input = np.int(x[) #action = 1 state, reward, done, info = env.step(action) total_reward += reward env.render() #one frame print(["{:+0.2f}".format(x) for x in state]) if steps % 20 == 0 or done: print(["{:+0.2f}".format(x) for x in state]) print("step {} total_reward {:+0.2f}".format(steps, total_reward)) #increment counter for learning rate steps += 1 if done: #env.render(close=True) #raise Exception("Simulation done") state = env.reset() return 0 model = nengo.Network() with model: global env env = gym.make('CartPole-v0') state = env.reset() gymNode = nengo.Node(gymrep, size_in=1, size_out=1) print("Action Space:") print(env.action_space) print("Observation Space:") print(env.observation_space) print(env.observation_space.high) print(env.observation_space.low) parameters = np.random.rand(4) * 2 - 1 system = ctrl.System(p.D, p.D, dt=p.dt, seed=p.seed, motor_noise=p.noise, sense_noise=p.noise, scale_add=p.scale_add, motor_scale=10, motor_delay=p.delay, sensor_delay=p.delay, motor_filter=p.filter, sensor_filter=p.filter) def minsim_system(t, x): return system.step(x) minsim = nengo.Node(minsim_system, size_in=p.D, size_out=p.D, label='minsim') state_node = nengo.Node(lambda t: system.state, label='state') pid = ctrl.PID(p.Kp, p.Kd, p.Ki, tau_d=p.tau_d) #define the controls going in. In this case, D*2 = left/right control = nengo.Node(lambda t, x: pid.step(x[:p.D], x[p.D:]), size_in=p.D*2, label='control') nengo.Connection(minsim, control[:p.D], synapse=0) adapt = nengo.Ensemble(p.n_neurons, dimensions=p.D, radius=p.radius, label='adapt') nengo.Connection(minsim, adapt, synapse=None) motor = nengo.Ensemble(p.n_neurons, p.D, radius=p.radius) nengo.Connection(motor, minsim, synapse=None) nengo.Connection(motor, gymNode) nengo.Connection(control, motor, synapse=None) conn = nengo.Connection(adapt, motor, synapse=p.synapse, function=lambda x: [0]*p.D, learning_rule_type=nengo.PES(1e-4 * p.learning_rate)) error = nengo.Ensemble(p.n_neurons, p.D) nengo.Connection(control, error, synapse=None, transform=-1) nengo.Connection(error, conn.learning_rule) signal = ctrl.Signal(p.D, p.period, dt=p.dt, max_freq=p.max_freq, seed=p.seed) #this is the desired position. We want to stay at 0 (pole straight up) desired = nengo.Node(signal.value, label='desired') nengo.Connection(desired, control[p.D:], synapse=None) stop_learn = nengo.Node([1]) nengo.Connection(stop_learn, error.neurons, transform=np.ones((p.n_neurons,1))*-10) result = nengo.Node(None, size_in=p.D*2) nengo.Connection(desired, result[:p.D], synapse=None) nengo.Connection(minsim, result[p.D:], synapse=None) sim = nengo.Simulator(model) sim.run(5)
def validateIP(ip): "aaaaaaaaaaaaaa...." numbers_list = ip.split(".") # "X.X.X.X"["X", "X", "X", "X"] # X -> [0, 255] if len(numbers_list) != 4: return False for i in range(len(numbers_list)): if not (isValid(numbers_list[i])): return False return True def isValid(myNumber): if not (isNumber(myNumber)): return False myNumber = int(myNumber) if(myNumber >= 0 and myNumber <= 255): return True return False def isNumber(myString): if(len(myString) == 0): return False # mySting = "12A" zero_ascii = ord('0') # ascii value of 0 nine_ascii = ord('9') for i in myString: if not (ord(i)>= zero_ascii and ord(i) <= nine_ascii): return False return True ip = "1..23.4" # 1, "", 23, 4 print(validateIP(ip))
def newKey(str1, str2): if len(str1) == 0: return str2 if len(str2) == 0: return str1 return(str1 + "." + str2) def helper(initial_key, obj, output): if type(obj) is dict: for key, value in obj.items(): helper(newKey(initial_key, key), value, output) else: output[initial_key] = obj def flatten_dicionary(dictionary): output = {} helper("", dictionary, output) return output if __name__ == "__main__": main()
# for loops in python for x in range(1, 10): print(x) for letter in "budi": print(letter)
# Create basic paper rock scissors games player1 = input("Enter Player 1's choice: ") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") player2 = input("Enter Player 2's choice: ") # if player1 == "rock" and player2 == "paper": # print("Player 2 wins!") # elif player1 == "scissors" and player2 == "paper": # print("Player 1 wins!") # elif player1 == "rock" and player2 == "scissors": # print("Player 1 wins!") # elif player1 == "paper" and player2 == "scissors": # print("Player 2 wins!") # elif player1 == "scissors" and player2 == "rock": # print("Player 2 wins!") # elif player1 == "paper" and player2 == "rock": # print("Player 1 wins!") # elif player1 == player2: # print("It's a tie!") # else: # print("Error!") # Refactoring that code ^ if player1 == player2: print("Its a tie") elif player1 == "rock": if player2 == "paper": print("Player 2 wins") elif player2 == "scissors": print("Player 1 wins") elif player1 == "paper": if player2 == "rock": print("Player 1 wins") elif player2 == "scissors": print("Player 2 wins") elif player1 == "scissors": if player2 == "rock": print("Player 2 wins") elif player2 == "paper": print("Player 1 wins") else: print("error")
import random import math random_number = random.randrange(1,100) def guess(x): num = input(x) number = int(num) if number==random_number: print("Your guess was correct") elif(number is not random_number): diff = random_number - number difff = abs(diff) print("you lost by "+ str(difff)) print("Actual number was " + str(random_number)) guess("Guess the number please:")
#getting numbers between 1000 and 3000 that have an even number in them items = [] for i in range(1000, 3001): x = str(i) if (int(x[0])%2==0) and (int(x[1])%2==0) and (int(x[2])%2==0): items.append(x) print(items)
from collections import OrderedDict import random food_list = OrderedDict() food_list["한식"] = ["김밥천국","장충동왕족발","엄마밥상"] food_list["중식"] = ["복성각","차우차우","베이징덕"] food_list["일식"] = ["갓덴스시","아비꼬","아리가또"] selected_food_type = input("{} 중 한가지를 고르시오.\n".format(",".join(food_list.keys()))) while selected_food_type not in food_list.keys(): print("{} 중에만 고르시오.".format(",".join(food_list.keys()))) selected_food_type = input() print(random.choice(food_list[selected_food_type]))
# Leia um vetor de 10 posições e verifique se o número digitado ja foi armazenado, se sim, leia novamente. No final mostre todos os números. # Use lista. num = [] for i in range(0, 10): while True: if len(num) == 10: break num2 = int(input('Informe o número: ')) if num2 not in num: num.append(num2) else: print('Este número ja está armazenado.') num2 = int(input('Armazene outro número: ')) print(num)
# Jogo da Forca: A palavra é adicionada pelo jogador e verifica se já escreveu uma letra. # Para o sorteio usei o módulo random, que é um módulo builtins do próprio python. import random as rd print('=============================') print(' JOGO DA FORCA') print('=============================') palavras = ['Coelho', 'Cachorro', 'Gato', 'Elefante', 'Baleia', 'Bola', 'Balao', 'Caderno', 'Python'] palavra_escolhida = rd.choice(palavras) print('Regras: ') print('Só há 10 chances de acertar;') print('Informe a letra em maiústculo.') print('Começamos o jogo: \n') # Transformando o tamanho da palavra sorteada em traços. tracos = list(len(palavra_escolhida) * '-') # Imprimindo em formato de lista. print(list(tracos)) print('\n') # Transformando a palavra sorteada em uma lista de letras maiúsculas. lista_palavra = list(palavra_escolhida.upper()) """# Convertendo os traços em lista. tracos = list(tracos)""" # O jogo verdadeiro, verificando se a letra consta na palavra, no caso lista. Adicionando a letra informada na posição 'i' da lista de traços, # imprimindo a lista. Por último, verificando se a lista traços é igual a palavra sorteada transformada em lista, depois verifica se as chances # ja acabaram. chances = 0 while chances <= 10: letra = input('Informe uma letra:') print('\n') for i in range(len(lista_palavra)): if letra.strip() == lista_palavra[i]: tracos[i] = letra print(tracos, '\n') if tracos == lista_palavra: print('Parabéns, você ganhou!!') break if chances == 10: print('Acabaram-se as chances e você perdeu !!') chances += 1
def controle(): mouses = [0]*4 calculo = [] while True: menuEntrada = int(input("Situação do mouse: " + "\n1 - Necessidade de esfera \n2 - Necessidade de limpeza \n3 - Necessita troca de cabo ou conector" + "\n4 - Quebrado ou inutilizado \n0 - Sair: ")) if menuEntrada == 0: break elif menuEntrada == 1: mouses[0] += 1 elif menuEntrada == 2: mouses[1] += 1 elif menuEntrada == 3: mouses[2] += 1 elif menuEntrada == 4: mouses[3] += 1 for i in range(len(mouses)): calculo1 = (mouses[i] * 100) / sum(mouses) calculo.append(calculo1) print(f"Quantidade de mouses {sum(mouses)}.") print("SITUAÇÃO QUANTIDADE PERCENTUAL") print(f"1 - Necessidade de esfera - {mouses[0]} {calculo[0]:.2f}%\n" + f"2 - Necessidade de limpeza - {mouses[1]} {calculo[1]:.2f}%\n" + f"3 - Necessita troca de cabo ou conector - {mouses[2]} {calculo[2]:.2f}%\n" + f"4 - Quebrado ou inutilizado - {mouses[3]} {calculo[3]:.2f}%") controle()
#!/usr/bin/python3 """ pascal triangle module """ def pascal_triangle(n): """ return ist that represent pascal's triangle""" my_list = [] if n <= 0: return my_list for i in range(1, n + 1): value = 1 tmp_list = [] for j in range(1, i + 1): tmp_list.append(str(value)) value = value * (i - j) // j my_list.append(tmp_list) return my_list
# -*- coding: utf-8 -*- #Take note #Purpose:Python code to convert Hex code to Text as per Grade 1 Braille #@author Manikandan V #@version 1.0 #@date 09/01/18 from __future__ import print_function import os,sys #****** Declaration of Alphebets and corresponding Hex codes *********** alp = ['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'] alp_index = ['210','230','218','21c','214','238','23c','234','228','22c','250','270','258','25c','254','278','27c','274','268','26c','252','272','22e','25a','25e','256'] #****** Declaration of Numbers and corresponding Hex codes ************ no=['1','2','3','4','5','6','7','8','9','0'] no_index = ['210','230','218','21c','214','238','23c','234','228','22c'] #****** Declaration of Special Charaters (which is used without sign) and corresponding Hex codes *********** sp_chr1=['.',',',';',':','!','?','\'','-'] sp_chr_index1=['226','220','260','224','264','262','240','242'] #****** Declaration of Special Charaters (which is used with sign) and corresponding Hex codes ************** sp_chr2=['"','"','(',')','/','*'] sp_chr_index2=['262','246','232','24c','248','244'] cp_cnt=0 # To identify Letter Caps, Word Caps and Paragraph Caps number=0 # To identify number or Alphebet sign=0 # For sign procesing #************** Open and Read text file containing Hex code *************** file = open("NOTE1.TXT", "r") # Rename your file name data = file.read() file.close() #*************** open new text file to store converted text **************** new_file=open("NOTE_op.TXT", "w") #******** Function to print Alphebets (including Caps) *************** def alp_decode(char): global cp_cnt if cp_cnt==0: # Small letters #print (alp[alp_index.index(char)], end='') new_file.write(alp[alp_index.index(char)]) elif cp_cnt==1: # letter Caps #print ((alp[alp_index.index(char)]).upper(), end='') new_file.write((alp[alp_index.index(char)]).upper()) cp_cnt=0 elif cp_cnt>1: # Word caps and Paragraph Caps #print ((alp[alp_index.index(char)]).upper(), end='') new_file.write((alp[alp_index.index(char)]).upper()) #************** Function to print Numbers ************** def no_decode(char): print (no[no_index.index(char)], end='') new_file.write(no[no_index.index(char)]) #************** Function to print special character ********* def sp_chr_decode(char): global sign if sign==0: # Spececial character without sign #print (sp_chr1[sp_chr_index1.index(char)], end='') new_file.write(sp_chr1[sp_chr_index1.index(char)]) else: # Special character with sign #print (sp_chr2[sp_chr_index2.index(char)], end='') new_file.write(sp_chr2[sp_chr_index2.index(char)]) sign=0 #**************** Function to find the hex code is Alphebet or number or special character def convert(): try: if number==1: # Number no_decode(Hex) elif number==0: # Alphebet alp_decode(Hex) except ValueError: pass try: sp_chr_decode(Hex) # Special character except ValueError: pass #*********************** Main function starts Here ******************************** for i in range(0, len(data)-1, 3): # Split text to hexcode size of 3 Hex = data[i:i + 3] #*********************** Sign Processing ********************** if Hex=='24e': # Letter to number Sign #done number=1 continue elif Hex=='206': # Number to letter Sign #done number=0 continue elif Hex =='202': # Capital letter/word/paragraph Identification Sign #done cp_cnt=cp_cnt+1 continue elif Hex=='300':# Space #done #print(' ') new_file.write(' ') number=0 if cp_cnt==2:cp_cnt=0 continue elif Hex=='280':#Enter #done #print('\n') new_file.write('\n') cp_cnt=0 number=0 continue elif Hex=='201':# Back space #done #print('\b') #new_file.write('\b') new_file.seek(-1, os.SEEK_CUR) continue elif Hex=='204':#Sign To write ( ) * #done sign=1 continue elif Hex=='20c':#Sign To write “ ” #done sign=2 continue elif Hex=='20e':#Sign To write / #done sign=3 continue convert() new_file.close() # close the text file new_file=open("NOTE_op.TXT", "r") # Open text file contains converted data final_data=new_file.read() # Read file print(final_data) #Print file data new_file.close() # close file
### # Google Hash Code 2020 # This code aims at solving the practice problem - more pizza # # Author: Teki Chan # Date: 28 Jan 2020 ### import sys def read_file(in_file): """ Read Intput File Args: in_file: input file path Returns: Maximum number of slices allowed , Number of Pizza to be selected , List of number of slices of each pizza """ max_slices = 0 no_of_types = 0 slices_list = [] # Read the file into variables with open(in_file, 'r') as infile: [max_slices, no_of_types] = [int(x) for x in infile.readline().strip().split(' ')] slices_list = [int(x) for x in infile.readline().strip().split(' ')] return max_slices, no_of_types, slices_list def process(max_slices, no_of_types, slices_list): """ The main program reads the input file, processes the calculation and writes the output file Args: max_slices: Maximum number of slices allowed no_of_types: Number of Pizza to be selected slices_list: List of number of slices of each pizza Returns: total number of slices , the list of the types of pizza to order """ global_slices_sum = 0 global_slices_ordered = [] # Check each pizza from the most slices to the least for pizza_idx in range(1, len(slices_list) + 1): slices_sum = 0 slices_ordered = [] # try sum as much as possible for slice_idx in range(len(slices_list) - pizza_idx, -1, -1) : if slices_sum + slices_list[slice_idx] > max_slices: continue # skip if over the max slices_sum += slices_list[slice_idx] slices_ordered.insert(0, slice_idx) if slices_sum == max_slices: break # stop when max is reached if slices_sum > global_slices_sum: global_slices_sum = slices_sum global_slices_ordered = slices_ordered.copy() if global_slices_sum == max_slices: break # stop when max is reached # Remove the last one to select another combination while len(slices_ordered) > 0 and global_slices_sum < max_slices: last_idx = slices_ordered[0] slices_sum -= slices_list[last_idx] slices_ordered = slices_ordered[1:] for slice_idx in range(last_idx - 1, -1, -1): if slices_sum + slices_list[slice_idx] > max_slices: continue # skip if over the max slices_sum += slices_list[slice_idx] slices_ordered.insert(0, slice_idx) if slices_sum == max_slices: break if slices_sum > global_slices_sum: global_slices_sum = slices_sum global_slices_ordered = slices_ordered.copy() if global_slices_sum == max_slices: break return global_slices_sum, global_slices_ordered def write_file(out_file, global_slices_ordered): """ Write the submission file Args: out_file: output file path global_slices_ordered: the list of the types of pizza to order """ with open(out_file, 'w') as outfile: outfile.write('{}\n'.format(len(global_slices_ordered))) outfile.write('{}\n'.format(' '.join([str(s) for s in global_slices_ordered]))) def main(in_file, out_file): """ The main program reads the input file, processes the calculation and writes the output file Args: in_file: input file path out_file: output file path """ max_slices, no_of_types, slices_list = read_file(in_file) global_slices_sum, global_slices_ordered = process(max_slices, no_of_types, slices_list) print('Score: {}'.format(global_slices_sum)) if out_file is not None: write_file(out_file, global_slices_ordered) print('{} is saved. The program completed.'.format(out_file)) else: print('The program completed.') if __name__ == "__main__": # Check arguments if len(sys.argv) < 2: print(sys.argv[0] + ' [in file] [out file: optional]') elif len(sys.argv) == 2: main(sys.argv[1], None) else: main(sys.argv[1], sys.argv[2])
def latest(scores): return scores[-1] def personal_best(scores): scores.sort() return scores[-1] def personal_top_three(scores): scores.sort() scores.reverse() l = len(scores) if l == 0: return "input is a empty list" if l <= 3: top = scores[0:l] print(top) return top top = scores[0:3] return top
import sqlite3 class Database: def __init__(self, db): self.conn= sqlite3.connect(db) self.cur= self.conn.cursor()#쿼리 접속 self.cur.execute("CREATE TABLE IF NOT EXISTS part (id INTEGER PRIMARY KEY, part text, customer text, retailer text, price text)") # create table : db 만들기 # part : db 이름 self.conn.commit() def fetch(self): self.cur.execute("SELECT * FROM part") rows= self.cur.fetchall() return rows def insert(self, part, customer, retailer, price): self.cur.execute("INSERT INTO part VALUES (NULL, ?, ?, ?, ?)", (part, customer, retailer, price)) self.conn.commit() def remove(self, id): self.cur.execute("DELETE FROM part WHERE id=?", (id,)) self.conn.commit() def update(self, id, part, customer, retailer, price): self.cur.execute("UPDATE part SET part = ?, customer = ?, retailer = ?, price = ? WHERE id = ?", (part,customer,retailer,price,id)) self.conn.commit() def __del__(self): self.conn.close() if __name__=="__main__": db=Database('store.db') db.insert("4GB DDR4 Ram", "Kim Doe", "DD", "180")
class BST: """ Binary Search Tree Properteis left and right are a reference to another Node """ def __init__(self, value = None): self.value = value self.left = None self.right = None def insert(self, value): ''' Add a Node with the given value in the BST :type value: integer or any :rtype: void ''' # Root if self.value is None: self.value = value elif value < self.value: if self.left: self.left.insert(value) else: self.left = BST(value) elif value > self.value: if self.right: self.right.insert(value) else: self.right = BST(value) # Do not insert duplicated values def get_node_count(self): ''' Return the number of nodes in the BST rtype: integer ''' return 0 def print_values(self): ''' Print all values in BST from min to max value rtype: void ''' if self.left: self.left.print_values() print(self.value, end=', ') if self.right: self.right.print_values() def main(): bst = BST() bst.insert(5) bst.insert(4) bst.insert(6) bst.insert(3) bst.insert(3) bst.insert(1000) bst.insert(8) bst.print_values() count_nodes = bst.get_node_count() print('Count nodes:', count_nodes) # print(bst.root) if __name__ == '__main__': main()