text
stringlengths
37
1.41M
import tkinter as tk def button_clicked(): my_label.config(text=user_input.get()) print(user_input.get()) window = tk.Tk() window.title("My First GUI Program") window.minsize(width=500, height=300) window.config(padx=20, pady=20) # how to add padding my_label = tk.Label(text="I am a label", font=("Arial", 24, "bold")) # my_label.pack() # positions the elements centered in the window if no args # must position an element in the window for it to show up # is not enough to merely create it # my_label.place(x=100, y=200) my_label.grid(column=0, row=0) # how to update things my_label["text"] = "new text" my_label.config(text="New Text", padx=50, pady=50) # button button = tk.Button(text="Click Me", command=button_clicked) # button.pack() button.grid(column=1, row=1) new_button = tk.Button(text="New Button") new_button.grid(column=2, row=0) # Entry user_input = tk.Entry(width=15) # user_input.insert(tk.END, "some text to begin with") # print(user_input.get()) # user_input.pack() user_input.grid(column=3, row=2) # # text # text = tk.Text(height=5, width=30) # # puts cursor in textbox # text.focus() # text.insert(tk.END, "Example of multi-line text entry.") # # gets current value in textbox at line 1 character 0 # print(text.get("1.0", tk.END)) # text.pack() # # # Spinbox # # # def spinbox_used(): # #gets the current value in spinbox. # print(spinbox.get()) # # # spinbox = tk.Spinbox(from_=0, to=10, width=5, command=spinbox_used) # spinbox.pack() # # # Scale # # # def scale_used(value): # print(value) # # # scale = tk.Scale(from_=0, to=100, command=scale_used) # scale.pack() # # # Checkbutton # # # def checkbutton_used(): # print(checked_state.get()) # # # checked_state = tk.IntVar() # checkbutton = tk.Checkbutton(text="Is it on?", variable=checked_state, command=checkbutton_used) # checked_state.get() # checkbutton.pack() # # # Radiobutton # # # def radio_used(): # print(radio_state.get()) # # # # Variable to hold on to which radio button value is checked. # radio_state = tk.IntVar() # radiobutton1 = tk.Radiobutton(text="Option1", value=1, variable=radio_state, command=radio_used) # radiobutton2 = tk.Radiobutton(text="Option2", value=2, variable=radio_state, command=radio_used) # radiobutton1.pack() # radiobutton2.pack() # # # Listbox # # # def listbox_used(event): # # Gets current selection from listbox # print(listbox.get(listbox.curselection())) # # # listbox = tk.Listbox(height=4) # fruits = ["Apple", "Pear", "Orange", "Banana"] # for item in fruits: # listbox.insert(fruits.index(item), item) # listbox.bind("<<ListboxSelect>>", listbox_used) # listbox.pack() window.mainloop() # needed to keep the window open while the user interacts
# -*- coding: utf-8 -*- # создаём первый супер-класс class mainClass: arg1 = 'This is argument 1 from class mainClass;' arg2 = 'This is argument 2 from class mainClass;' def ext_1(self): return 'This if method ext_1 from class mainClass.' # создаём объект суперкласса main_class = mainClass() # создаём сабкласс # который наследует атрибуты суперкласса mainClass class firstInherit(mainClass): arg3 = 'This is argument 3 from class firstInherit;' arg4 = 'This is argument 4 from class firstInherit;' def ext_2(self): return 'This if method ext_2 from class firstInherit.' first_inherit = firstInherit() # создаём второй сабкласс # который наследует атрибуты классов mainClass и firstInherit class secondInherit(mainClass, firstInherit): arg5 = 'This is argument 5 from class firstInherit;' arg6 = 'This is argument 6 from class firstInherit;' def ext_3(self): return 'This if method ext_3 from class secondInherit.' second_inherit = secondInherit()
#Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. #Start the program #Get number number = input("Enter a number: ") mod = number % 2 #Validate the type of number if is odd and even if mod > 0: print("You insert an odd number") else: print("You insert an even number")
#------------------------------------------------------------------------------------------------------------------------------------- # Program Objective: Create an automobile class that will be used by a dealership as a vehicle inventory program. # The following attributes are the automobile class: # -private string make # -private string model # -private string color # -private int year # -private int mileage # This program have appropriate methods such as: # -constructor # -add a new vehicle # -remove a vehicle # -update vehicle attributes # At the end of your program, it will allow the user to output all vehicle inventory to a text #file. #-------------------------------------------------------------------------------------------------------------------------------------- class Automobile: def __init__(self): self.car_make = '' self.car_model = '' self.car_color = '' self.car_year = 0 self.car_mileage = 0 def addVehicle(self): try: self.car_make = input('Enter make: ') self.car_model = input('Enter model: ') self.car_color = input('Enter color: ') self.car_year = int(input('Enter year: ')) self.car_mileage = int(input('Enter mileage: ')) return True except ValueError: print('Please try again. Please use only whole numbers for mileage and year.\n*Do not use commas to speart the numbers.') return False def __str__(self): return '\t'.join(str(x) for x in [self.car_make, self.car_model, self.car_color, self.car_year, self.car_mileage]) class Inventory: def __init__(self): self.vehicles = [] def addVehicle(self): vehicle = Automobile() if vehicle.addVehicle() == True: self.vehicles.append(vehicle) print () print('Vehicle added, Thank you') def viewInventory(self): print('\t'.join(['','Make','Model', 'Color', 'Year', 'Mileage'])) for idx, vehicle in enumerate(self.vehicles) : print(idx + 1, end='\t') print(vehicle) automotive_inventory = Inventory() while True: print (''' Automative Inventory Command Center 1.Add a Vehicle 2.Delete a Vehicle 3.View Inventory 4.Update Existing Inventory 5.Export Inventory 6.Quit ''') userInput=input('Please choose one of the above options: ') #add a vehicle to the inventory if userInput=="1": automotive_inventory.addVehicle() # delete a vehicle from the inventory elif userInput=='2': if len(automotive_inventory.vehicles) < 1: print('Sorry there are no vehicles in inventory') continue automotive_inventory.viewInventory() item = int(input('Enter the number associated with the vehicle to remove: ')) if item - 1 > len(automotive_inventory.vehicles): print('Invalid number') else: automotive_inventory.vehicles.remove(automotive_inventory.vehicles[item - 1]) print () print('Vehicle has been removed') # view the list of all the vehicles elif userInput == '3': if len(automotive_inventory.vehicles) < 1: print('Sorry there are no vehicles in inventory') continue automotive_inventory.viewInventory() # edit a vehicle from the inventory elif userInput == '4': if len(automotive_inventory.vehicles) < 1: print('Sorry there are no vehicles in inventory') continue automotive_inventory.viewInventory() item = int(input('Enter the number associated with the vehicle to update: ')) if item - 1 > len(automotive_inventory.vehicles): print('Invalid number') else: automobile = Automobile() if automobile.addVehicle() == True : automotive_inventory.vehicles.remove(automotive_inventory.vehicles[item - 1]) automotive_inventory.vehicles.insert(item - 1, automobile) print () print('Vehicle has been updated') # export the list of the inventory to a text file elif userInput == '5': if len(automotive_inventory.vehicles) < 1: print('Sorry there are no vehicles in inventory') continue i = open('VihicleInventory.txt', 'w') i.write('\t'.join(['Make','', 'Model','','Year','', 'Color','', 'Mileage'])) i.write('\n') for vechicle in automotive_inventory.vehicles: i.write('%s\n' %vechicle) i.close() print('Vehicle inventory has been exported to file named VihicleInventory.txt') elif userInput == '6': # exit the loop print('Good Bye. Have a great day!') break else: #invalid user input print('Invalid input, please try again')
class HashTableNode: def __init__(self, word ,vector, next): self.word = word self.vector = vector self.next = next class HashTable: def __init__(self, table_size, alpha_value): self.table = [None] * table_size self.alpha_value = alpha_value def insert(self,k,vector, funcselect): loc = self.hash_function_switcher( funcselect,k) self.table[loc] = HashTableNode(k, vector, self.table[loc]) def search(self, k, funcselect): loc = self.hash_function_switcher( funcselect,k) temp = self.table[loc] count = 0 while temp is not None: count+=1 if temp.word == k: return temp,count temp=temp.next def loadfactor(self): return self.total_elements*.75 def hash_function1(self, k): """the hash function uses only the value of the first a-z, 1-26 respectivly making 26 buckets""" return self.alpha_value[k[0]] % len(self.table) def hash_function2(self, k): """Sums the value of each letter represented alphabetically as 1-26 respectivly, Symbols have a value of 0""" b25word = 0 for i in range(len(k)-1,0,-1): if k[i] not in self.alpha_value: b25word +=0 else: b25word += self.alpha_value[k[i]] return (b25word*len(k)) % len(self.table) def hash_function3(self, k): """converts word to numbers by summing the vales of each letter as if it was part a of a base 25 number then multiplying by the length of the word, values of symbols count as 0""" b25word = 0 for i in range(len(k)-1,0,-1): if k[i] not in self.alpha_value: b25word +=0 else: b25word += self.alpha_value[k[i]]*(i**25) return (b25word*len(k)) % len(self.table) def hash_function_switcher(self,selection, k): """Using a dictionary to switch functions for hashing""" switcher = { 1:self.hash_function1, 2:self.hash_function2, 3:self.hash_function3 } func = switcher.get(int(selection) ) return func(k)
n = int(input("Nhap vao so n:")) S = 0 for number in range(n+1): S += number print(S)
def sort_cards(stuff): """Sorts a list of cards by ascending values.""" cards = { 'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13 } return sorted(stuff, key=cards.get)
# -*- coding: utf-8 -*- """ Created on Tue May 26 19:30:26 2020 @author: User """ import random while True: guess = int(input('guess(1~20):')) count = 0 a = random.randint(1,20) if guess==a: print('bingo!') break else: print('wrong!') if guess > a: print('大一點') count + 1 if guess < a: print('小一點') count + 1 else: count == 5 print('失敗')
'''Sprint Challenge Unit 3 Sprint 1 - Part 4 Class report''' from random import randint, sample, uniform from acme import Product ADJECTIVES = ['Classic', 'Shiny', 'Explosive', 'New', 'Improved'] NOUNS = ['Anvil', 'Catapult', 'Tunnel', 'Dynomite', 'TNT'] def generate_products(num_products=30): """Make random products""" products = [] for _ in range(num_products): name = sample(ADJECTIVES, 1)[0] + ' ' + sample(NOUNS, 1)[0] price = randint(5, 100) weight = randint(5, 100) flammability = uniform(0.0, 2.5) products.append(Product(name, price=price, weight=weight, flammability=flammability)) return products def inventory_report(products): """Takes the list of products, and prints a report.""" # We'll use a set to track unique names, and total others to average names = set() total_price = 0 total_weight = 0 total_flammability = 0.0 for product in products: names.add(product.name) total_price += product.price total_weight += product.weight total_flammability += product.flammability print("ACME CORPORATION OFFICIAL INVENTORY REPORT") print("Unique product names: {}".format(len(names))) print("Average price: {}".format(total_price / len(products))) print("Average weight: {}".format(total_weight / len(products))) print("Average flammability: {}".format( total_flammability / len(products))) if __name__ == '__main__': inventory_report(generate_products())
prices = [0, *map(int, input().split())] trucks = [tuple(map(int, input().split())) for _ in range(3)] starts = [t[0] for t in trucks] ends = [t[1] for t in trucks] price = 0 curr_trucks = 0 for time in range(1, max(ends) + 1): curr_trucks += starts.count(time) curr_trucks -= ends.count(time) price += prices[curr_trucks] * curr_trucks print(price)
CONFUSING_TRANS = str.maketrans("BGIOQSUYZ", "8C1005VV2") def translate(s): return s.translate(CONFUSING_TRANS) def char_val(c): return "0123456789ACDEFHJKLMNPRTVWX".index(c) def dec_to_char(d): return "0123456789ACDEFHJKLMNPRTVWX"[d] def check_digit(s): coeff = (2, 4, 5, 7, 8, 10, 11, 13) check = 0 for i in range(8): check += coeff[i] * char_val(s[i]) return check % 27 def get_decimal(dig): check = check_digit(dig) if dig[-1] != dec_to_char(check): return "Invalid" val = 0 for c in dig[:8]: val = (val * 27) + char_val(c) return val def main(): P = int(input()) for _ in range(P): K, digit = input().split() print(K, get_decimal(digit)) if __name__ == '__main__': main()
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not len(matrix) or not len(matrix[0]): return False for row in matrix: if row[-1] < target: continue for r in row: if r == target: return True elif r > target: return False return False return False
def does_react(a, b): return a != b and a.lower() == b.lower() def react(l): changes = True while changes: nl = [] changes = False i = 0 while i < len(l): if i < len(l) - 1 and does_react(l[i], l[i + 1]): i += 2 changes = True else: nl.append(l[i]) i += 1 l = nl return l def main(): poly = raw_input() l = react(list(poly)) print len(l) if __name__ == '__main__': main()
from itertools import permutations n = int(input()) smallest = None for p in permutations(str(n)): p = int(''.join(p)) if p > n: if smallest is None: smallest = p smallest = min(smallest, p) print(smallest if smallest is not None else 0)
def gen_digits(): digits = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"] digits += ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] for t in ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]: for i in xrange(10): digits.append(t + digits[i]) for h in ["onehundred", "twohundred", "threehundred", "fourhundred", "fivehundred", "sixhundred", "sevenhundred", "eighthundred", "ninehundred"]: for i in xrange(100): digits.append(h + digits[i]) return digits def main(): digits = gen_digits() len_to_word = {} for i in xrange(len(digits) - 1, 0, -1): len_to_word[i - len(digits[i])] = digits[i] N = int(raw_input()) words = [raw_input() for _ in xrange(N)] chars = sum(map(len, words)) - 1 sentence = ' '.join(words) print sentence.replace('$', len_to_word[chars]) if __name__ == '__main__': main()
s = input() i = 1 while s != "END": mids = s.split('*')[1:-1] if len(set(mids)) <= 1: print(i, "EVEN") else: print(i, "NOT EVEN") i += 1 s = input()
from collections import deque class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ stack = deque() open_to_close = {'{': '}', '[': ']', '(': ')'} for b in s: if b in open_to_close: stack.append(open_to_close[b]) elif not stack or stack.pop() != b: return False return not bool(stack)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2, carry=0): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if l1 is None and l2 is None: if carry: return ListNode(carry) return None n = ListNode(0) v = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry n.val = v % 10 n.next = self.addTwoNumbers((l1.next if l1 else None), (l2.next if l2 else None), v / 10) return n
def dist(p1, p2): return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5 def main(): order = [None] * 9 for i in range(3): for j, n in enumerate(map(int, input().split())): order[n - 1] = (i, j) print(sum(dist(a, b) for a, b in zip(order, order[1:]))) if __name__ == '__main__': main()
class Category: def __init__(self, reqs, contains): self.reqs = int(reqs) self.contains = set(contains) def main(): f = input() while f != '0': ncourse, cats = map(int, f.split()) categories = [] courses = set(input().split()) for _ in range(cats): _, req, *contains = input().split() categories.append(Category(req, contains)) for c in categories: if len(c.contains & courses) < c.reqs: print("no") break else: print("yes") f = input() if __name__ == '__main__': main()
N = int(input()) while N: first = [int(input()) for _ in range(N)] second = [int(input()) for _ in range(N)] second_to_first_pairs = {s: f for s, f in zip(sorted(second), sorted(first))} redone_second = [None]*N for s in second: f_equiv = second_to_first_pairs[s] f_ind = first.index(f_equiv) redone_second[f_ind] = s for s in redone_second: print(s) N = int(input()) if N: print()
from math import pi, sin, cos T = int(input()) for _ in range(T): M = int(input()) ang, x, y = pi/2, 0, 0 for _ in range(M): angle, dist = map(float, input().split()) ang += angle * pi/180 x += cos(ang) * dist y += sin(ang) * dist print(x, y)
class Node: def __init__(self, name): self.name = name self.connected = [] self.color = None def main(): N = int(input()) items = [input() for _ in range(N)] nodes = {name: Node(name) for name in items} M = int(input()) for _ in range(M): a, b = input().split() nodes[a].connected.append(nodes[b]) nodes[b].connected.append(nodes[a]) walt, jessie = [], [] stack = [] seen = set() for name in items: if name in seen: continue nodes[name].color = True stack.append(nodes[name]) while stack: n = stack.pop() if n.name in seen: continue seen.add(n.name) if n.color: walt.append(n.name) else: jessie.append(n.name) for nbr in n.connected: if nbr.color is None: nbr.color = not n.color stack.append(nbr) elif nbr.color == n.color: print("impossible") return print(' '.join(walt)) print(' '.join(jessie)) if __name__ == '__main__': main()
def main(): x, y = int(input()), int(input()) print(get_quad(x, y)) def get_quad(x, y): if y > 0: if x > 0: return 1 else: return 2 else: if x < 0: return 3 else: return 4 if __name__ == '__main__': main()
from math import cos, sin, radians, hypot def walk(point, direction, steps): return point + (direction * steps), direction def turn(point, direction, degrees): return point, direction * complex(cos(radians(degrees)), sin(radians(degrees))) COMMANDS = { 'walk': walk, 'turn': turn, 'start': turn, } def get_end_point(start_x, start_y, instrs): point = complex(start_x, start_y) direction = 1 + 0j for cmd, val in instrs: point, direction = COMMANDS[cmd](point, direction, val) return point def complex_dist(a, b): c = a - b return hypot(c.real, c.imag) def main(): N = int(input()) while N: ends = [] for _ in range(N): start_x, start_y, *cmds = input().split() ends.append(get_end_point( float(start_x), float(start_y), zip(cmds[::2], map(float, cmds[1::2])))) average = sum(ends) / len(ends) furthest = max(complex_dist(average, x) for x in ends) print(average.real, average.imag, furthest) N = int(input()) if __name__ == '__main__': main()
from math import pi, acos def strand_length(r, h): return 2 * (h ** 2 - r ** 2) ** 0.5 def circle_ratio(r, h): return 1 - (acos(r / h) / pi) def string_length(r, h, s): strand = strand_length(r, h) circle_len = circle_ratio(r, h) * 2 * pi * r return (circle_len + strand) * (1 + s/100) def main(): r, h, s = [int(x) for x in input().split()] while r or h or s: print("{:.2f}".format(string_length(r, h, s))) r, h, s = [int(x) for x in input().split()] if __name__ == '__main__': main()
from src.ingredient import Ingredient ''' Inventory: a class used to store inventory. ''' ### add minimum amount to sell class Inventory(object): def __init__(self): self._ingredients = {} # dict<Ingredient> # add new ingredients to the inventory # ingredients to be created first (aggregation relationship) def add_new_ingredients(self, *argv: Ingredient): for ingredient in argv: self._ingredients[ingredient.name] = ingredient # add or substract amount of an ingredient def update_stock(self, ingredient_name: str, amount: float): self._ingredients[ingredient_name].change(amount) # check an ingredient whether available (with an amount) def is_available(self, ingredient_name: str, amount: float =None): available_amount = self._ingredients[ingredient_name].amount/self._ingredients[ingredient_name].multiplier if amount or (amount == 0): return True if available_amount >= amount else False else: return self._ingredients[ingredient_name].is_soldout # display all the unavailable ingredients in the inventory def display_unavailable_ingredients(self): unavailable_ingredients = [] for ingredient in self._ingredients.values(): if ingredient.is_soldout: unavailable_ingredients.append(ingredient.name) elif not self.is_available(ingredient.name, ingredient.minimum): unavailable_ingredients.append(ingredient.name) return unavailable_ingredients # get ingredient details def get_ingredient(self, name: str) -> Ingredient: return self._ingredients[name] def get_ingredients(self): return [ingredient for ingredient in self._ingredients.values()] def __str__(self): l = [f"{ingredient.name}: {ingredient.amount}" for ingredient in self._ingredients.values()] return str(l) if __name__ == "__main__": butter = Ingredient("butter") tomato = Ingredient("tomato", 10) inventory = Inventory() inventory.add_new_ingredients(butter, tomato) print(inventory._ingredients)
typeword = eval(input("word to translate into pig latin? ")) firstletter = typeword[0] restofword = typeword[1:] piglatinword = restofword + firstletter + "ay" print (piglatinword)
i = 7 while i > 2: if i == 5: first = 10 i -= 1 print(first)
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #Pull data from minis mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) # Create tensor x as value input, 28x28 = 784 pixel -> varible x is vector of 784 input feature, we set none because we don't know length of data,number of row items X= tf.placeholder(tf.float32,shape=[None,784]) # Create tensor y as predict probability of each digit 0 - 9 ex: [0.5 0 0.7 0 0.9 0 0 0 0 0] Y = tf.placeholder(tf.float32,[None,10]) # Create inital weights and bias W=tf.Variable(tf.zeros([784,10])) b=tf.Variable(tf.zeros([10])) # Create hypothesis function hypo = tf.matmul(X,W)+b # activate function - use softmax hypo_softmax = tf.nn.softmax(hypo) # define cost function use cost entropy cost_entropy= tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y,logits=hypo_softmax)) # define optimizer train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cost_entropy) #================ # Train Model - iterate minimize cost #initialize varible model init = tf.global_variables_initializer() session=tf.Session() session.run(init) #perfom in 100 steps for i in range(1000): batch_x,batch_y=mnist.train.next_batch(100) # get 100 random data x:image y is labels [0-9] session.run(train_step,feed_dict={X:batch_x,Y:batch_y}) # Evaluate Model - compare highest propability and actual digit correct_predict = tf.equal(tf.argmax(Y,1),tf.argmax(hypo_softmax,1)) accuracy = tf.reduce_mean(tf.cast(correct_predict,tf.float32)) test_accuracy = session.run(accuracy,feed_dict= {X:mnist.test.images,Y:mnist.test.labels}) print("Test Accuray {0}%".format(test_accuracy*100)) session.close()
# Defining class inbuilt listnode class ListNode: def __init__(self, data, next=None): self.data = data self.next = next class LinkedList: def __init__(self):# Constructor self.head = None def getSize(self): curr = self.head s = 1 while curr.next is not None: curr = curr.next s = s + 1 print(str(s)) # If head is not null we are parsing till end and then adding the new node. def addNode(self,data): newNode = ListNode(data) if self.head is None: self.head = newNode else: curr = self.head while curr.next is not None: curr = curr.next curr.next = newNode # Assume three nodes a, b, c. # Then if we want to delete we putting prev to a, curr to b. # Now, we give b.next as null and putting curr to b and prev.next to c. def delete(self,value): curr = self.head prev = self.head while curr is not None: if curr.data is value: if curr.data == prev.data: curr = curr.next prev.next = None self.head = curr else: curr = curr.next prev.next = curr else: prev = curr curr = curr.next def printNode(self): curr = self.head while curr is not None: print(str(curr.data)) curr = curr.next # Main function starts here. myList = LinkedList() value = 1 value_2 = 1; while value>0: print("Press the number regarding what you want to do!\n 1 for adding the element\n 2 for printing the list\n 3 for getting the link size \n 4 for deleting the following node") value_1 = input() # Switch case in python. def switch(arg) : switcher = { 1 : 1, 2 : 2, 3 : 3, 4 : 4, } return switcher.get(arg,"invalid argument") number = switch(value_1) if(number == 1): print("Enter the total number of numbers you want to add") total_number = input() for x in range(0,total_number): string = str(x+1) print "Enter the {} number".format(string) number = input() myList.addNode(number) value+=1 elif(number == 2): myList.printNode() elif(number == 3): myList.getSize() elif(number == 4): print("Enter the number you want to delete") value = input() myList.delete(value)
## # date:20170324 # Use : count the face numbers # Input: rectroiall.txt ## import os,sys def get_count_face(filename): no_face_count = 0 face_count = 0 f = open(filename) filelines = f.readlines() for line in filelines: imginfo = line.strip().split() #print line facenum = int(imginfo[1]) if facenum == 0: no_face_count = no_face_count + 1 else: face_count = face_count+facenum # for i in range(2,len(imginfo),5): # pos_label=int(imginfo[i]) # print 'pos_label: ',pos_label # if pos_label == 0 : # right_face_count = right_face_count + 1 # if pos_label == 2 : # left_face_count = left_face_count + 1 # else : # normal_face_count = normal_face_count + 1 f.close() return no_face_count,face_count if __name__=="__main__": filename1 = sys.argv[1] # file1 no_face_count,face_count = get_count_face(filename1) print 'f1_no_face_count: ',no_face_count print 'f1_face_count: ',face_count
# This program searches Google Drive and DropBox to find files matching the hashes provided # Author: Eric Scherfling # Version: 1.0 import googledrive_seacher import dropbox_searcher import argparse import os import hashlib import json def main(): parser = argparse.ArgumentParser() search = parser.add_argument_group("Parse Parameters") searchhash = search.add_mutually_exclusive_group() searchhash.add_argument("-hf", "--HashFile", dest="hashfile", type=str, help="Path to the file of hashes to search", required=False) searchhash.add_argument("-hp", "--HashPath", dest="hashpath", type=str, help="Path to the folder of hashes to search", required=False) search.add_argument("-ho", "--HashOutput", dest="hashoutput", type=str, help="Path to where to save the hashes of the folder", required=False) search.add_argument("-o", "--Output", dest="output", type=str, help="Path of the directory to save the output", default=None, required=False) search.add_argument("-gt", "--GoogleToken", dest="googletoken", type=str,required=False, help="Path to the file of Google credentials", default=None) search.add_argument("-dt", "--DropboxToken", dest="dropboxtoken", type=str, required=False, help="Path to the file of DropBox credentials", default=None) setup = parser.add_mutually_exclusive_group() setup.add_argument("-gs", "--GoogleSetup", dest="newgoogletoken", type=str, required=False, help="Run set up for a Google Drive token, path for where to store credentials", default=None) setup.add_argument("-ds", "--DropboxSetup", dest="newdropboxtoken", type=str, required=False, help="Run set up for a DropBox token, path for where to store credentials", default=None) args = parser.parse_args() if args.newgoogletoken: # Check if a google token has to be set up print(args.newgoogletoken) googledrive_seacher.createGoogleAuth(args.newgoogletoken) elif args.newdropboxtoken: # Check if a dropbox token has to be set up print(args.newdropboxtoken) dropbox_searcher.createDropBoxAuth(args.newdropboxtoken) else: # Start searching through drive and dropbox results = dict() hashfile = args.hashfile hashpath = args.hashpath # If no source of hashes were provided, exit if not hashfile and not hashpath: print("No source of hashes provided") parser.print_help() return googletoken = args.googletoken dropboxtoken = args.dropboxtoken hashoutput = args.hashoutput # If a folder was supplied, but no output source was supplied, # or if no token to search was supplied, then exit. if (hashpath and not (googletoken or dropboxtoken) and not hashoutput): print("No credentials provided / No output path for hashing files") parser.print_help() return # The difference between the check above and below is this behavior: # There's no need to parse a file if no token is supplied, # but if there's a folder supplied, you may want to save the hashes without searching. # There's no need to copy a file you already have by parsing it and then writing it again. # If the hashfile was supplied, but no token to search was supplied, # then exit. if (hashfile and not (googletoken or dropboxtoken)): print("No credentials provided with hash file") parser.print_help() return # Parse the hashes either by file or calculating it in real time hashes = {} if hashfile: hashes = parseFile(hashfile) elif hashpath: hashes = parseFolder(hashpath) # check hashes actually exist if len(hashes) == 0: print("Hashes not found") return # If the hashes should be saved, first do a check to make sure you aren't reading # from a file, only write if you computed them in real time if hashoutput and not hashfile: with open(hashoutput, 'w') as hashoutputfile: hashoutputfile.write(json.dumps(hashes)) # If we are only calculating then saving our hashes, we can exit now if not (googletoken or dropboxtoken): return # Search Google if googletoken and "md5" in hashes: googleresults = googledrive_seacher.checkGoogleHashes(hashes["md5"], googletoken) # If there were any results from the google search, don't return any if googleresults and len(googleresults) > 0: results["Google Drive"] = googleresults #Search DropBox if dropboxtoken and "sha256" in hashes: dropboxresults = dropbox_searcher.checkDropBoxHashes(hashes["sha256"], dropboxtoken) # If there were any results from the dropbox search, don't return any if dropboxresults and len(dropboxresults) > 0: results["DropBox"] = dropboxresults output = args.output # If the user wants to store the final result, write it to the file supplied if output: with open(output,'w') as outputf: jsonobj = json.dumps(results) outputf.write(jsonobj) # Otherwise, just print out the results else: if "DropBox" in results: print("DropBox results:") for dbresult in results["DropBox"]: for tag in dbresult: #print tag by tag print("{0}: {1}".format(tag, dbresult[tag])) # print an extra line at the end of each file, to make it easier to read print() if "Google Drive" in results: print("Google Drive results:") for dbresult in results["Google Drive"]: for tag in dbresult: #print tag by tag print("{0}: {1}".format(tag, dbresult[tag])) # print an extra line at the end of each file, to make it easier to read print() def parseFile(filepath): hashes = {} # Use JSON to parse the file, if there's an error, send back an empty dictionary # The JSON files are keyed by hash name, (sha256, md5) and the value is a list of hashes try: with open(filepath, 'rb') as hashFile: hashes = json.loads(hashFile.read()) if not ("md5" in hashes and "sha256" in hashes): return {} return hashes except: return hashes def parseFolder(folderPath): md5hashes = [] sha256hashes = [] # Traverse all files in a directory for dirName, _, fileList in os.walk(folderPath): for fname in fileList: fullpath = os.path.join(dirName, fname) # Each file's hash is then calculated in md5 and sha256 md5hashes.append(computemd5Hash(fullpath)) # DropBox uses it's own method of computing the sha256 hash # based solely on metadata, so we have to use their hashing # method. sha256hashes.append(compute_dropbox_hash(fullpath)) if len(sha256hashes) == 0 and len(md5hashes) == 0: # if there were files to hash in that directory, send an empty dictionary return {} return {"md5": md5hashes, "sha256": sha256hashes} def computesha256Hash(filename): sha256_hash = hashlib.sha256() with open(filename, "rb") as f: # Read and update hash string value in blocks of 4K for byte_block in iter(lambda: f.read(4096), b""): sha256_hash.update(byte_block) return sha256_hash.hexdigest() def computemd5Hash(filename): md5_hash = hashlib.md5() with open(filename, "rb") as f: # Read and update hash string value in blocks of 4K for byte_block in iter(lambda: f.read(4096), b""): md5_hash.update(byte_block) return md5_hash.hexdigest() def compute_dropbox_hash(filename): with open(filename, 'rb') as f: block_hashes = b'' while True: chunk = f.read(4*1024*1024) if not chunk: break block_hashes += hashlib.sha256(chunk).digest() return hashlib.sha256(block_hashes).hexdigest() if(__name__ == "__main__"): main()
#!/usr/bin/env python # coding: utf-8 # In[ ]: def ridge_regression(y, tx, lambda_): #Ridge regression using normal equations # y: vector of outputs (dimension N) # tx: matrix of data (dimension N x D), such that tx[:, 0] = 1 #lambda_: regularization parameter N,D = tx.shape A = np.dot(tx.T, tx) + lambda_ * np.ones(D) B = np.linalg.inv(A) w = np.dot(np.dot(B,tx.T), y) # Calculating loss r = y - np.dot(tx,w) loss = (np.dot(r,r)+ lambda_ * np.dot(w,w)) / (2*N) return w, loss def least_squares_GD(y, tx, initial_w,max_iters, gamma): """ Linear regression using gradient descent and least squares """ N, D = tx.shape # Iterations of gradient descent w = initial_w for _ in range(max_iters): grad = -np.dot(tx.T, (y - np.dot(tx,w))) / (N) w = w - gamma * grad # Calculating the loss r = y - np.dot(tx,w) loss = np.dot(r,r) / (2*N) return w, loss #Linear regression using stochastic gradient descent def least_squares_SGD(y, tx, initial_w,max_iters, gamma, frequency=0): """Linear regression using stochastic gradient descent and least squares""" N, D = tx.shape # Iterations of stochastic gradient descent w = initial_w for i in range(max_iters): k = np.random.randint(0,N-1) grad = -(y[k]-np.dot(tx[k,:], w))*tx[k,:] w = w - gamma * grad r = y - np.dot(tx,w) loss = np.dot(r,r) / (2*N) return w, loss #Least squares regression using normal equations def least_squares(y, tx): N, _ = tx.shape # Calculating w w = (np.linalg.inv((tx.T).dot(tx)).dot(tx.T)).dot(y) #Calculating loss r = y - tx.dot(w) loss = np.dot(r,r)/(2*N) return w, loss def logistic_regression(y, tx, initial_w,max_iters, gamma): """ #Logistic regression using SGD # y: vector of outputs (dimension N) # tx: matrix of data (dimension N x D) # initial_w: vector (dimension D) # max_iters: scalar # gamma: scalar respresenting step size # return parameters w for the regression and loss """ return reg_logistic_regression(y, tx, 0, initial_w,max_iters, gamma) def reg_logistic_regression(y, tx, lambda_ ,initial_w, max_iters, gamma): """ #Regularized logistic regression using SGD # y: vector of outputs (dimension N) # tx: matrix of data (dimension N x D), such that tx[:, 0] = 1 # lambda: scalar representing regularization parameter # initial_w: vector (dimension D) # max_iters: scalar # gamma: scalar respresenting step size # return parameters w for the regression and loss """ N, _ = tx.shape w = initial_w for i in range(max_iters): k = np.random.randint(0,N-1) tmp = np.dot(tx[k,:],w) grad = -y[k]*tx[k,:]+sigmoid(tmp)*tx[k,:]+lambda_*w w = np.squeeze(np.asarray(w - gamma*grad)) tmp = np.squeeze(np.asarray(np.dot(tx,w))) loss = - np.dot(tmp, y.T) loss += np.sum(np.log(1+np.exp(tmp))) loss /= (2*N) return w, loss
import sys line = ''.join(sys.stdin.readlines()) stop = ['.', '?', '!'] prev = '.' a = ord('a') z = ord('z') A = ord('A') Z = ord('Z') def isletter(ch): return a <= ord(ch) <= z or A <= ord(ch) <= Z def issmall(ch): return a <= ord(ch) <= z count = 0 first = None for i in range(len(line)): ch = line[i] if isletter(ch): if first == None: first = ch if issmall(ch): count += 1 if not issmall(ch): if isletter(prev): count += 1 elif ch in stop: first = None prev = ch print count
# Julius Caesar Act 4, Scene 3, 218–224 brutus_speech = "There is a tide in the affairs of men \nWhich, taken at the flood, leads on to fortune; \nOmitted, all the voyage of their life \nIs bound in shallows and in miseries. \nOn such a full sea are we now afloat, \nAnd we must take the current when it serves, \nOr lose our ventures." # print out the text of this speech print(brutus_speech) list_of_words = brutus_speech.split(" ") list_of_formatted_words = [] for word in list_of_words: word = word.replace(",", "") word = word.replace(".", "") word = word.replace(";", "") word = word.replace("\n", "") word = word.lower() list_of_formatted_words.append(word) print(f'Number of words = {len(list_of_formatted_words)}\n') for num in range(29): number_words = len([x for x in list_of_formatted_words if len(x) == num]) if number_words: print(f'{num}-letter words = {number_words}')
import re def find_vowel_names(input_list): """ Given an iterable, return number of lines that match "name,gender,count", where name starts and ends with a vowel. """ vowels = re.compile(r"^[aeiouAEIOU][a-zA-Z]*[aeiouAEIOU],[FM],\d+$") vowel_names = [] for line in input_list: line = line.strip() result = vowels.search(line) if result: vowel_names.append(line) return len(vowel_names)
import csv from sys import argv, exit import cs50 # Connecting the db file to our python code db = cs50.SQL("sqlite:///students.db") # Prompting the user for enough command line arguments if len(argv) != 2: print("misssing command line arguments") exit(1) # Opening the csv file for reading with open(argv[1], "r") as csv_file: reader = csv.DictReader(csv_file) # Looping in the csv file rows and inserting the data to the db file for row in reader: row["name"] = row["name"].split() if len(row["name"]) == 3: db.execute("INSERT INTO students (first,middle,last,house,birth) VALUES (?,?,?,?,?)", row["name"][0], row["name"][1], row["name"][2], row["house"], row["birth"]) else: db.execute("INSERT INTO students (first,last,house,birth) VALUES (?,?,?,?)", row["name"][0], row["name"][1], row["house"], row["birth"])
''' Create a class Employee that will take a full name as argument, as well as a set of none, one or more keywords. Each instance should have a name and a lastname attributes plus one more attribute for each of the keywords, if any. ''' class Employee: def __init__(self, full_name, *args, **kwargs): self.__dict__.update(kwargs) self.full_name = full_name arguments = {'salary': 0, 'height': 0, 'nationality': 0} arguments.update(kwargs) self.attributes = arguments self.salary = arguments['salary'] self.height = arguments['height'] self.natioanality = arguments['nationality'] self.name = full_name.split(' ')[0] self.lastname = full_name.split(' ')[1] def initialize_attr(self): return self.name john = Employee('John Doe') print(john.lastname) mary = Employee("Mary Major", salary=120000) print(mary.salary) richard = Employee("Richard Roe", salary=110000, height=178) print(richard.salary) print(richard.height) giancarlo = Employee("Giancarlo Rossi", salary=115000, height=182, nationality="Italian") print(giancarlo.name) print(giancarlo.natioanality) peng = Employee('Peng Zhu', salary=500000, height=185, nationality='Chinese', subordinates=[i.lastname for i in (john, mary, richard, giancarlo)]) print(peng.subordinates) kwang = Employee('Jiang Jing', salary=20000, height=169, nationality='Chinese', lst=[ i.natioanality for i in (john, mary, richard, giancarlo)]) print(kwang.lst)
# -*- coding: utf-8 -*- ''' 一次元の特徴量に対して、EM法(Expectation–Maximization Algorithm)を用いて、混合ガウス分布を当てはめる Usage: $ python modling.py modeling.main(data,N) ・対数尤度あってるのか? ・BICの実装 ''' import math import csv import random import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab import pylab from sklearn import mixture def main(data, N): EMs = [] ## dataを分割する for i in range(data.shape[1]): EM = expectation_maximization(data[:,i], N) EMs.append(EM) return EMs def expectation_maximization(data, N): ''' 混合ガウス分布を用いてdataをモデリングする args : data -> モデリングしたいデータ N -> いくつのガウス分布の線形重ね合わせで表現するか dst : score -> 対数尤度(log likelihood) param: N -> いくつのガウシアン分布を用いるか EM.weights_ -> 混合係数, 足したら1になる EM.covars_ -> それぞれのガウス分布の分散 EM.means_ -> ガウス分布の平均(頂点の座標になる)、2変量ガウス分布だから2次元 EM.converged_ -> 収束してればTrue ''' # dataの形状を整える data = data.reshape((data.shape[0], 1)) data = np.hstack((data,np.zeros_like(data))) # fitting EM = mixture.GMM(n_components=N, covariance_type='full',n_iter=100,verbose=0) EM.fit(data) return EM def display_contour(X,Y,Z): ''' 等高線を表示 ''' XX = np.array([X.ravel(), Y.ravel()]).T Z = EM.score_samples(XX)[0] Z = Z.reshape(X.shape) CS = plt.contour(X, Y, Z) CB = plt.colorbar(CS) def calc_log_likelihood(xs, ms, vs, p): s = 0 for x in xs: g0 = gaussian(x, ms[0], vs[0]) g1 = gaussian(x, ms[1], vs[1]) # g2 = gaussian(x, ms[2], vs[2]) # g3 = gaussian(x, ms[3], vs[3]) # g4 = gaussian(x, ms[4], vs[4]) # s += math.log(p[0] * g0 + p[1] * g1 + p[2] * g2 + p[3] * g3 + p[4] * g4) s += math.log(p[0] * g0 + p[1] * g1) return s def gaussian(x, m, v): ''' ガウシアン分布にパラメータを代入したg(x,m,v)を返す。 dst : p -> float ''' p = math.exp(- pow(x - m, 2) / (2 * v)) / math.sqrt(2 * math.pi * v) return p def get_data(): ''' csvファイルから配列を生成して返す ''' sam = open('../../../data/statistical data/old_faithful.csv', 'r') reader = csv.reader(sam, delimiter=' ') data = [] for raw in reader: data.append([float(raw[0]), float(raw[1])]) sam.close() data = np.array(data) return data def display_result(): fig = plt.figure(figsize = (12,9)) num = 100 * data.shape[1] + 10*1 + 1*1 for i, EM in enumerate(EMs): ax = fig.add_subplot(num + i) x = np.linspace(start=min(data[:,i]), stop=max(data[:,i]), num=1000) y = 0 ps = range(N) p = 0 for k in range(N): # それぞれのガウス分布を描画 ps[k] = EM.weights_[k] * mlab.normpdf(x, EM.means_[k,0], math.sqrt(EM.covars_[k][0][0])) p += ps[k] plt.plot(x, ps[k], color='orange') if EM.converged_ == True: # 収束してたら描画 plt.plot(x,p,color='red',linewidth=3) plt.hist(data[:,i], bins = 30, color='dodgerblue', normed=True) else: # 収束しなかった場合 print '!!!Cannot converge!!!' # score = EM.score(data).sum() def histgram_3D(data): ''' 入力された二次元配列を3Dhistgramとして表示する ''' from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = data[:,0] y = data[:,1] hist, xedges, yedges = np.histogram2d(x, y, bins=30) X, Y = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25) # bar3dでは行にする X = X.flatten() Y = Y.flatten() Z = np.zeros(len(X)) # 表示するバーの太さ dx = (xedges[1] - xedges[0]) * np.ones_like(Z) dy = (yedges[1] - yedges[0]) * np.ones_like(Z) dz = hist.flatten() # これはそのままでok # 描画 ax.bar3d(X, Y, Z, dx, dy, dz, color='b', zsort='average') def display_3D(X,Y,Z): ''' 入力画像を3Dで表示する args: X,Y,Z dst : None ''' # データの準備 from mpl_toolkits.mplot3d import Axes3D # plot fig = plt.figure() ax = Axes3D(fig) # 設定 ax.set_xlabel('pixel') ax.set_ylabel('pixel') ax.set_zlabel('intensity') # ax.set_zlim(0, 300) ax.set_title('Image') ax.plot_surface(X, Y, Z, rstride=10, cstride=10, cmap = 'jet',linewidth=0) # ax.plot_wireframe(X,Y,Z, cmap = 'Greys', rstride=30, cstride=30) # plt.pause(-1) # これだけでok if __name__ == '__main__': data = get_data() score = main(data=data, N=10) print 'log likelihood = {}'.format(score)
''' Тут будет тело программы ''' class Enigma(): def encrypt_by_number(self,text,key): ''' Зашифровывает текст методом Цезаря ''' text = list(text) new_text = [] for i in text: i=ord(i) i+= int(key) if i>= 65536: i -= 65536 i=chr(i) new_text.append(i) new_text = ''.join(new_text) return new_text def encript_by_key_name(self, text, key): ''' Зашифровывает текст методом Вернама ''' text = list(text) key = list(key) key_count = 0 new_text = [] for i in text: try: j = key[(key_count%len(key))] except ZeroDivisionError: key = list(input('Ключ не введен. Введите ключ: ')) j = key[(key_count%len(key))] #print('Введите ключ') i = ord(i) i += ord(j) i = chr(i) key_count += 1 new_text.append(i) new_text = ''.join(new_text) return new_text #text = 'Я текст. Сегодня меня будут зашифровывать и расшифровывать.' #text = '' #a = Enigma() #a.encript_by_key_name(text, '') #a.encrypt_by_number(text, 1)
def main(): print nested_sum([[1,2,3],[4,5,6,[7,8,9]]) def nested_sum(t): x = 0 for val in t: if type(val) == int: x += val else: x += nested_sum(val) return x def remove_duplicates(t): res = [] for i in range(len(t)): if t[i] not in res: res.append(t[i]) return res if __name__ == '__main__': #Only run main if called from command line main()
from collections import Counter def mkwrdlst(inputfile): """ Makes a list of all words from text file inputfile: plain text file output: list of strings """ fin = open(inputfile) words = [] for line in fin: w = line.strip() words.append(w) return words def eightletterwords(inputfile): """ Makes a list of all 8 letter words from text file inputfile: plain text file output: list of strings """ fin = open(inputfile) words = [] for line in fin: w = line.strip() if len(w) == 8: words.append(w) return words def alphabetize(word): """ Alphabetizes a given string word: string output: string """ return ''.join(sorted(word)) def allanagrams(): """ Finds all groups of words which are anagrams of each other output: list of lists of strings """ words = mkwrdlst('words.txt') anagrams = dict() for word in words: alph = alphabetize(word) if alph not in anagrams: anagrams[alph] = [word] else: anagrams[alph] = anagrams[alph] + [word] temp = sorted(anagrams.values(), key = len, reverse = True) return [i for i in temp if len(i) != 1] def bingo(): """ Finds the largest group of 8 letters words which are anagrams of eachother output: list of strings """ words = eightletterwords('words.txt') anagrams = dict() for word in words: alph = alphabetize(word) if alph not in anagrams: anagrams[alph] = [word] else: anagrams[alph] = anagrams[alph] + [word] temp = sorted(anagrams.values(), key = len, reverse = True) return temp[0] if __name__ == '__main__': temp = allanagrams() for i in range(len(temp)): print temp[i] print bingo()
"""Created as a solution to an excersize in thinkpython by Allen Downey Written by Brooks Draws a Koch curve of given length """ from swampy.TurtleWorld import * world = TurtleWorld() bob = Turtle() bob.delay = 0.01 def draw(t, length, n): if n == 0: return angle = 50 fd(t, length*n) lt(t, angle) draw(t, length, n-1) rt(t, 2*angle) draw(t, length, n-1) lt(t, angle) bk(t, length*n) def koch(t, x): """Draws a Koch curve of length x x: Integer, total length of Koch curve """ if x < 3: fd(t, x) return koch(t, x/3) lt(t, 60) koch(t, x/3) rt(t, 120) koch(t, x/3) lt(t, 60) koch(t, x/3) def snowflake(t, x): """Draws a snowflake comprised of three koch curves x: Integer, length of each component Koch curve """ for i in range(3): koch(t,x) rt(t,120) #koch(bob, 200) length = 200 bob.x = -length/2 bob.y = .3*length snowflake(bob,length) wait_for_user()
student_heights = input("Input a list of student heights ").split() for n in range(0, len(student_heights)): student_heights[n] = int(student_heights[n]) total_height = 0 number_of_students = 0 for height in student_heights: number_of_students += 1 total_height += height avarage_height = round(total_height / number_of_students) print(avarage_height)
""" CSV: Name,Alter,Geschlecht Susanne, 42, w Kurt, 27, m Susanne ist 42 Jahre alt und weiblich Kurt ist 27 Jahre alt und männlich ... <file>.readlines() <string>.split() """ with open("mitglieder.csv", "r") as member_file: members = member_file.readlines() for x in range(1, len(members)): # anstelle von member in members: (Hier dann erst ab 1. Spalte weil grds Beginn mit 0) member = members[x].strip() # entfernt str Zeichen und Leerzeichen (Schönheitskorrektur zB für /n) parts = member.split(',') # Angabe an welcher Stelle der Datensatz geteilt werden soll (Zeichenkette --> Liste) print("{0} ist {1} Jahre alt und {2}".format(*parts)) # {} --> statt print(parts[0] + ' ist' + parts[1] + ' Jahre alt und' + parts[2])
def check_upc(string): rev = string[::-1] sum_odd = 0 sum_even = 0 for i in range(len(rev)): if i % 2 == 0: sum_even += rev[i] if i % 2 == 1: sum_odd += rev[i] * 3 total = sum_even + sum_odd # if total % 10 == 0: # return True # else: # return False return total % 10 == 0
# Create a list. elements = [] # Append empty lists in first two indexes. elements.append([]) elements.append([]) # Add elements to empty lists. elements[0].append([1, 2]) elements[0].append(2) elements[1].append(3) print elements[0] elements[1].append(4) # Display top-left element. print(elements[0][0][0]) # Display entire list. print(elements) x=0 y=1 z=2 if z>=y and x: print "hello"
import numpy as np def f(x): s=x**2+x+1 return s def F(x): s=x**3/3+x**2/2+x return s x=[0,1] quad=(1/2)*(f(x[0])+f(x[1])) print('approximation with Trapezontial rule :', quad) print('real solution of integration : ', F(1)-F(0))
def has_redundant(s): stack = [0] for c in s: if c == '(': stack.append(0) elif c == ')': if stack.pop() == 0: return True else: # print stack[-1] stack[-1] += 1 # Treat (expr) as redundant return stack.pop() == 0 def had_red(s): stack = [0] for c in s: if c == '(': stack.append(0) elif c == ')': if stack.pop() == 0: return True else: stack[-1] += 1 return stack.pop() == 0 assert had_red("((()))") assert has_redundant("()") assert has_redundant("(a+b)") assert not has_redundant("(a+b)+c") assert has_redundant("((a+b))+c")
''' https://www.journaldev.com/15911/python-super ''' import socket import random class NetConnect: def __init__(self,hostname,port): self.hostname = hostname self.port = port def set_hostname(self,hostname): self.hostname = hostname def set_port(self,port): self.port = port def set_message(self,message): self.message = bytes(message, encoding="utf-8") def get_hostname(self): return self.hostname def get_port(self): return self.port def get_message(self): if self.message: return self.message else: return class NetClient(NetConnect): def __init__(self,hostname,port): super().__init__(hostname,port) def send_packet(self): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((self.hostname,int(self.port))) print("Get ready to ride the bull!") while True: guess = input("Enter number: ") s.send(guess.encode()) data = s.recv(80).decode() print(data) if data == "found the secret": break print("Received:",repr(data)) print("Connection closed.") s.close() class NetServer(NetConnect): def __init__(self,hostname,port): super().__init__(hostname, port) def secret(self): secret_num = random.randint(1,10) print(f"The secret number is {secret_num}") return secret_num def connect(self): num = self.secret() s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #Find difference of bind and connect s.bind((self.hostname,int(self.port))) #What does the 1 stand for? s.listen(1) socket_,address = s.accept() #print(socket_) print(f"Connection establisghed from {address}") while True: print('Dealer waits for a guess') guess = socket_.recv(80).decode() print(f"Dealer received {guess}") if int(guess) < num: reply = 'too low' elif int(guess) > num: reply = 'too high' else: reply = 'found the secret' socket_.send(reply.encode()) if reply == 'found the secret': break s.close() def main(): print("Please choose from the following:\n" "1) Player\n" "2) Dealer") user = input("Response: ") user = input_validation(user) if user == 1: pkt = packet_build() client = NetClient(pkt.get_hostname(),pkt.get_port()) client.send_packet() elif user == 2: pkt = packet_build() server = NetServer(pkt.get_hostname(),pkt.get_port()) server.connect() def packet_build(): hostname = input("Enter hostname: ") port = input("Enter port: ") nc = NetConnect(hostname,port) return nc def input_validation(num): while str.isnumeric(num) == False: num = input("ERROR! Enter a number: ") return int(num) main()
''' 1) Write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below: Here are two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment. Sample data: http://py4e-data.dr-chuck.net/comments_42.json (Sum=2553) Actual data: http://py4e-data.dr-chuck.net/comments_57128.json (Sum ends with 10) You do not need to save these files to your folder since your program will read the data directly from the URL. ''' #Imported modules to run the code successfully from urllib import request #Used in function to verify url exists from urllib import error #Error message if url doesn't exist ex: https://www.python.ogr import requests #Used to pull the json file #Main function that runs the code def main(): sum_count() #Engine to count the sum of the count def sum_count(): url = input("Enter URL: ") url = url_verify(url) if url != None: r = requests.get(url) #req = r.content[0:-1] This variable is purely for trouble shooting #print(req) This print statement is purely for trouble shooting response = r.json() sum = 0 for i in range(len(response['comments'])): sum += response['comments'][i]['count'] print(sum) else: return #Basic verification of url we learned in class def url_verify(url): try: request.urlopen(url) return url except error.URLError as e: print(f"ERROR: {e.reason}") return None main()
""" SimpleSymbols(str) Input:"+d+=3=+s+" Output:true Input:"f++d+" Output:false """ import re import random def SimpleSymbols(str): alpha_str = "abcdefghijklmnopqrstuvwxyz" if len(str) < 3: return False if (str[0] in alpha_str) or (str[-1] in alpha_str): return False for letter in range(1, len(str)-1): if str[letter] in alpha_str: if not (str[letter-1] == "+" and str[letter+1] == "+"): return False return True # print(SimpleSymbols("=d+=3=+s+")) """ Have the function LetterCapitalize(str) take the str parameter being passed and capitalize the first letter of each word. Words will be separated by only one space. Sample Test Cases Input:"hello world" Output:Hello World Input:"i ran there" Output:I Ran There """ def LetterCapitalize(str1): new_str = str1.split(" ") capitalized_str = [] for word in new_str: capitalized_str.append(word.capitalize()) return " ".join(capitalized_str) # print(LetterCapitalize("hello world")) """ Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots. """ def reverse_string(str2): new_strng = str2.split(".") i = 0 j = len(new_strng) -1 while i < j: new_strng[i], new_strng[j] = new_strng[j], new_strng[i] i += 1 j -= 1 return ".".join(new_strng) #print(reverse_string("this.is.sahana's.mom.my.name.is.asha")) """ Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string. Sample Test Cases Input:"hello*3" Output:Ifmmp*3 Input:"fun times!" Output:gvO Ujnft! """ def LetterChanges(str): alphabets = "abcdefghijklmnopqrstuvwxyz" vowels = "aeiou" output_list = [] final_list = [] for letter in str: if letter in alphabets: new_letter = chr(ord(letter)+1) output_list.append(new_letter) else: output_list.append(letter) new_strng = "".join(output_list) for letter in new_strng: if letter in vowels: final_list.append(letter.upper()) else: final_list.append(letter) return "".join(final_list) #print(LetterChanges("hello*3 world!31")) """ Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24. For the test cases, the range will be between 1 and 18 and the input will always be an integer. Sample Test Cases Input:4 Output:24 Input:8 Output:40320 """ def FirstFactorial(num): factorial = 1 for i in range(1, num+1): factorial *= i return factorial #print(FirstFactorial(18)) """ Have the function TimeConvert(num) take the num parameter being passed and return the number of hours and minutes the parameter converts to (ie. if num = 63 then the output should be 1:3). Separate the number of hours and minutes with a colon. Sample Test Cases Input:126 Output:2:6 Input:45 Output:0:45 """ def TimeConvert(num): minutes = num % 60 hours = int(num / 60) return f'{hours}:{minutes}' # print(type(TimeConvert(100))) """ Longest word in the string along with removing the special characters """ def long_word(strng): word_list = re.sub("[^\w' ]", "", strng).split() longest_word = '' longest_size = 0 for word in word_list: if len(word) > longest_size: longest_word = word longest_size = len(word) return longest_word """ Coin flip and return the number of times Heads and Tails appear """ def flip_coin(num): flip_list, heads, tails = [], 0, 0 for i in range(20): flip = random.randint(0, 1) if flip == 0: heads += 1 flip_list.append("Heads") else: tails += 1 flip_list.append("Tails") print("Heads appeared:" f'{heads}' "times") print("Tails appeared:" f'{tails}' "times") return flip_list """ String Palindrome """ def palindrome(str1): rev_str2 = str1[::-1] if str1 == rev_str2: print("string is a palindrome") else: print("string is not a palindrome") # palindrome("hello") """ Fibonacci Sequence """ def fibonacci_seq(num): a, b = 0, 1 for i in range(num): print(a) a, b = b, a + b return # fibonacci_seq(10) """ Prime Factor for a number """ def prime_factor(num): i = 2 list_primefactor = [] while num > 1: if num % i == 0: list_primefactor.append(i) num /= i i -= 1 i += 1 return list_primefactor # print(prime_factor(100))
''' Unit test suite for following functions 1. SimpleSymbols 2. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string. 3. Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots. 4. For this challenge you will be determining the largest word in a string. 5. return the number of hours and minutes the parameter converts to (ie. if num = 63 then the output should be 1:3). Separate the number of hours and minutes with a colon. ''' import unittest import HtmlTestRunner import code_bytes class Testcoderbytes(unittest.TestCase): def test_SimpleSymbols(self): self.assertEqual(code_bytes.SimpleSymbols("+d+=3=+s+"), True) def test_LetterChanges(self): self.assertEqual(code_bytes.LetterChanges("hello*3"), "Ifmmp*3") self.assertEqual(code_bytes.LetterChanges("fun times!"), "gvO Ujnft!") def test_reverse_string(self): self.assertEqual(code_bytes.reverse_string("my.name.is.asha"), 'asha.is.name.my') def test_long_word(self): self.assertEqual(code_bytes.long_word("My name is Asha, my daughter is Sahana and my mom is Veena"), "daughter") self.assertEqual(code_bytes.long_word("Sahana is very beautiful and smart*&%$$####"), "beautiful") # def test_TimeConvert(self): # self.assertEqual((code_bytes.TimeConvert(63), "1:3")) if __name__ == '__main__': unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner())
from operator import itemgetter def sort_skills(skills, skill_count): """ Given a list of skills, sort them by their confidence level in descending order. Cleans up irrelevant skills :param skills: list of skill objects, each with a confidence value :return: sorted list of skills, with irrelevant fields removed """ skill_count = [n + 1 for n in skill_count] # Fix divide by zero errors new_skills = [{'id': skill['id'], 'skill': skill['skill'], 'confidence': skill['confidence'] / skill_count[skill['id']]} for skill in skills] return sorted(new_skills, key=itemgetter('confidence'), reverse=True) def get_top_skills(skills, n): """ Given a sorted list of skills sorted in descending order, return the top n :param skills: sorted list of skills in descending order :param n: some integer :return: top n skills """ if n < 0: return [] elif n > len(skills): return skills else: return skills[:n] def filter_skills(skills): pass
""" Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. For example,"egg" and "add" are isomorphic, "foo" and "bar" are not. """ # My thought process: # (0) Check that strings are the same length. Else False # (1) walk down the strings together, # (2) If char1 not in the map yet, add the mapping from char1 to char2 # (3) If char1 already in the map, it needs to match char2, else False from unittest import TestCase def are_isomorphic(string_1, string_2): if len(string_1) != len(string_2): return False char_map = {} for char_1, char_2 in zip(string_1, string_2): expected_char = char_map.get(char_1, None) if expected_char is None: char_map[char_1] = char_2 else: if char_2 != expected_char: return False return True class TestIso(TestCase): def test_iso(self): self.assertTrue(are_isomorphic("egg", "add")) self.assertFalse(are_isomorphic("foo", "bar")) self.assertFalse(are_isomorphic("foof", "baad")) self.assertTrue(are_isomorphic("eeggyff", "aaddyqq"))
""" Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. """ # Questions I would have had: # (1) am I get the number of elements? # Thoughts: # (1) Use a Red-black tree? # (2) Do insert, followed by a tree rotation? # (3) Track length when I insert, then rotate as needed.. # CAn keep track of # of elements in the tree, Keep rotating left until root is correct? # Track ideal root # rotate left on parent of ideal root while it is not ideal rool. # Keep track of longest path. If root in correct spot, rotate GGP left? # I was attempting a solution which was too difficult (in-place construction) # A simpler strategy I looke dup was to get the number of nodes, and to use recursion. # Because you can divide and conquer off of the root node. # So I am coding that up. import math class Element(object): def __init__(self, key, next_elem=None): self.key = key self.next_elem = next_elem class Node(object): def __init__(self, key, parent=None, left=None, right=None): self.key = key self.parent = parent self.left = left self.right = right def linked_to_bst(list_head): pointer_array = [list_head] element = list_head # Traverse the linked list, construct an array of pointers, and get the length. while element.next_elem is not None: pointer_array.append(element.next_elem) # Basically python version of pointer.. element = element.next_elem # Call a recursive function which takes the n/2the element as the root, # and recursively constructs the left and right subtrees bst_root = construct_bst(pointer_array) return bst_root def construct_bst(pointer_array): n_nodes = len(pointer_array) root_idx = math.floor(n_nodes/2) # Termination conditions: Empty array, size 1 array if n_nodes == 0: return None # Construct root node root_node = Node(pointer_array[root_idx].key) if n_nodes == 1: return root_node # Construct left subtree left_root = construct_bst(pointer_array[:root_idx]) # Construct right subtree right_root = construct_bst(pointer_array[(root_idx+1):]) root_node.left = left_root if left_root is not None: left_root.parent = root_node root_node.right = right_root if right_root is not None: right_root.parent = root_node return root_node def test_bst_constuct(): print("Unit Testing Linked List to BST Constructor...") # Create the linked list elements = [Element(i+1) for i in range(7)] for i,e in enumerate(elements): if i != len(elements)-1: e.next_elem = elements[i+1] bst = linked_to_bst(elements[0]) assert bst.key == 4, "Root is incorrect!" assert bst.left.key == 2, "Root Left Child is incorrect!" assert bst.right.key == 6, "Root Right Child is incorrect!" assert bst.left.parent.key == 4, "Root Left Child Parent is incorrect!" assert bst.right.parent.key == 4, "Root Right Child Parent is incorrect!" assert bst.left.left.key == 1, "Leaf node is incorrect!" assert bst.left.right.key == 3, "Leaf node is incorrect!" assert bst.right.left.key == 5, "Leaf node is incorrect!" assert bst.right.right.key == 7, "Leaf node is incorrect!" new_elem = Element(8) elements[-1].next_elem = new_elem elements.append(new_elem) bst = linked_to_bst(elements[0]) assert bst.key == 5, "Inbalanced Root is incorrect" assert bst.left.left.left is not None, "Inbalanced leaf incorrect" assert bst.left.left.left.key == 1, "Inbalanced leaf incorrect" print("All Passed!") if __name__ == "__main__": test_bst_constuct()
# Часть 1 - присваивание и вывод переменных a = 10 b = 20 c = 100 d = 'Часть 1 - присваивание и вывод переменных' print(d) print('Переменная a =', a, ';', 'Переменная b =', b, ';', 'Переменная b =', c) # Часть 2 - запрос переменных у пользователя e = 'Часть 2 - запрос переменных у пользователя' print(e) name = input('Введите ваше имя ') age = int(input('Введите ваш возраст в числовой форме ')) print('Ваше имя = ', name, ';', 'Ваш возраст = ', age)
class A: def __init__(self, a): self.a = a def __str__(self): return "A:"+str(self.a) class B: def __init__(self, a): self.a = a def __str__(self): return "B:"+str(self.a) class C(A,B): def __init__(self, a, b, c): A.__init__(self,a) B.__init__(self,b) self.c = c def __str__(self): return "{}, {}, C: {}".format(A.__str__(self), B.__str__(self), self.c) if __name__ == '__main__': print(C(1,2,3))
class Person: def __init__(self, id, name): self.id = id self.name = name def __str__(self): return "ID: {}, Name: {}".format(self.id, self.name) class Employee(Person): def __init__(self, id, name, dept, job): super().__init__(id, name) #usage of super self.dept = dept self.job = job def __str__(self): return "{}, Dept: {}, Job: {}".format(Person.__str__(self), self.dept, self.job) #useage of superclass name class SalariedEmployee(Employee): def __init__(self, id, name, dept, job, sal, bonus): super().__init__(id, name, dept, job) self.bonus = bonus self.sal = sal def __str__(self): return "{}, Salary: {}, Bonus: {}, NetSal: {}".format(Employee.__str__(self), self.sal, self.bonus, self.netSal()) def netSal(self): return self.sal + (.1*self.sal) + (.15*self.sal) + (.08*self.sal) + self.bonus #sal+ha+hra+pf+bonus class ContractEmployee(Employee): def __init__(self, id, name, dept, job, hrs, rate): super().__init__(id, name, dept, job) self.hrs = hrs self.rate = rate def __str__(self): return "{}, Hours: {}, Rate: {}, NetSal: {}".format(Employee.__str__(self), self.hrs, self.rate, self.netSal()) def netSal(self): return self.hrs * self.rate if __name__ == '__main__': print(Employee(1,"name","dept","job")) print(SalariedEmployee(1,"name","dept","job",1236,65)) print(ContractEmployee(1,"name","dept","job",1236,65))
class Point: def __init__(self, x=0,y=0): self.x = x self.y = y def __str__(self): return "x:{}, y:{}".format(self.x,self.y) def __add__(self,other): if isinstance(other,Point): return Point(self.x + other.x, self.y + other.y) return Point(self.x + other, self.y + other) def __radd__(self,other): return Point(self.x + other, self.y + other) def __mul__(self,other): if isinstance(other,Point): return Point(self.x * other.x, self.y * other.y) return Point(self.x * other, self.y * other) def __rmul__(self,other): return Point(self.x * other, self.y * other) def __sub__(self,other): if isinstance(other,Point): return Point(self.x - other.x, self.y - other.y) return Point(self.x - other, self.y - other) def __rsub__(self,other): return Point(self.x - other, self.y - other) def __truediv__(self,other): if isinstance(other,Point): return Point(self.x / other.x, self.y / other.y) return Point(self.x / other, self.y / other) def __rtruediv__(self,other): return Point(self.x / other, self.y / other) if __name__ == '__main__': p1 = Point(5,2) p2 = Point(10,40) print("add:",p2+p1) print("radd:",p2+10) print("mul:",p2*p1) print("rmul:",p2*10) print("sub:",p2-p1) print("rsub:",p2-10) print("div:",p2/p1) print("rdiv:",p2/10)
import collections import numpy as np import util import svm import csv from ps2.ps2.ps2.src.spam.svm import train_and_predict_svm def get_words(message): """Get the normalized list of words from a message string. This function should split a message into words, normalize them, and return the resulting list. For splitting, you should split on spaces. For normalization, you should convert everything to lowercase. Args: message: A string containing an SMS message Returns: The list of normalized words from the message. """ # *** START CODE HERE *** # this is how the get_words function works: # it gets a single message and returns the lower case and each word in a list lower_case = message.lower() splitted = lower_case.split() return splitted # *** END CODE HERE *** def create_dictionary(messages): """Create a dictionary mapping words to integer indices. This function should create a dictionary of word to indices using the provided training messages. Use get_words to process each message. Rare words are often not useful for modeling. Please only add words to the dictionary if they occur in at least five messages. Args: messages: A list of strings containing SMS messages Returns: A python dict mapping words to integers. """ # *** START CODE HERE *** # make a list of all the words word_list = [] dict = {} c = 0 for row in messages: seperated = get_words(row) for i in seperated: word_list.append(i) for words in word_list: tobe = words in dict.values() if tobe == False: if word_list.count(words) > 4: dict[c] = words c += 1 return dict # *** END CODE HERE *** def transform_text(messages, word_dictionary): """Transform a list of text messages into a numpy array for further processing. This function should create a numpy array that contains the number of times each word of the vocabulary appears in each message. Each row in the resulting array should correspond to each message and each column should correspond to a word of the vocabulary. Use the provided word dictionary to map words to column indices. Ignore words that are not present in the dictionary. Use get_words to get the words for a message. Args: messages: A list of strings where each string is an SMS message. word_dictionary: A python dict mapping words to integers. Returns: A numpy array marking the words present in each message. Where the component (i,j) is the number of occurrences of the j-th vocabulary word in the i-th message. """ # *** START CODE HERE *** Array = np.zeros([len(messages),len(word_dictionary)]) keys = list(word_dictionary.keys()) values = list(word_dictionary.values()) for i in range(len(messages)): for words in get_words(messages[i]): condition = words in values if condition == True: n = get_words(messages[i]).count(words) j = keys[values.index(words)] Array[i,j] = n return Array # *** END CODE HERE *** def fit_naive_bayes_model(matrix, labels): """Fit a naive bayes model. This function should fit a Naive Bayes model given a training matrix and labels. The function should return the state of that model. Feel free to use whatever datatype you wish for the state of the model. Args: matrix: A numpy array containing word counts for the training data labels: The binary (0 or 1) labels for that training data Returns: The trained model """ # *** START CODE HERE *** n_words = np.shape(matrix)[1] n_label = np.shape(matrix)[0] phi_spam = np.zeros((1,n_words)) phi_nonspam = np.zeros((1,n_words)) zeros = 0 ones = 0 # count the number of spam(1) and not-spam(0) emails for i in labels: if i == 0: zeros += 1 else: ones += 1 phi_y = (1 + ones)/(n_words + n_label) #P(y=1) for i in range(n_label): if labels[i] == 0: for j in range(n_words): if matrix[i,j] != 0: phi_nonspam[0,j] += 1/(2+zeros) if labels[i] == 1: for j in range(n_words): if matrix[i,j] != 0: phi_spam[0,j] += 1/(2+ones) for j in range(n_words): phi_spam[0, j] += 1 / (2 + ones) phi_nonspam[0, j] += 1 / (2 + zeros) return phi_y, phi_spam, phi_nonspam # *** END CODE HERE *** def predict_from_naive_bayes_model(phi_y, phi_spam, phi_nonspam, matrix): """Use a Naive Bayes model to compute predictions for a target matrix. This function should be able to predict on the models that fit_naive_bayes_model outputs. Args: model: A trained model from fit_naive_bayes_model matrix: A numpy array containing word counts Returns: A numpy array containg the predictions from the model """ # *** START CODE HERE *** #zeros, ones, phi_spam, phi_nonspam = model n_words = np.shape(matrix)[1] n_label = np.shape(matrix)[0] phi = np.zeros((1,n_label)) prob_log = np.zeros((1, n_label)) pred = np.zeros((1, n_label)) for i in range(n_label): mul1 = 1 # y=1 mul2 = 1 # y=0 summation = 0 for j in range(n_words): if matrix[i,j] != 0: mul1 = mul1*phi_spam[0,j] mul2 = mul2*phi_nonspam[0,j] #summation += np.log(phi_spam[0,j]) summation += np.log(phi_nonspam[0, j]) #print(phi_y*mul1 + mul2*(1-phi_y)) #prob_log[0,i] = summation + np.log(phi_y) - np.log(phi_y*mul1 + mul2*(1-phi_y)) # probability that it is not spam prob_log[0, i] = summation + np.log(1-phi_y) - np.log(phi_y * mul1 + mul2 * (1 - phi_y)) pred[0,i] = np.exp(prob_log[0,i]) for i in range(n_label): if pred[0,i] < 0.5: pred[0,i] = 1 else: pred[0,i] = 0 return pred # *** END CODE HERE *** def get_top_five_naive_bayes_words(phi_y, phi_spam, phi_nonspam, dictionary): """Compute the top five words that are most indicative of the spam (i.e positive) class. Ues the metric given in part-c as a measure of how indicative a word is. Return the words in sorted form, with the most indicative word first. Args: model: The Naive Bayes model returned from fit_naive_bayes_model dictionary: A mapping of word to integer ids Returns: A list of the top five most indicative words in sorted order with the most indicative first """ # *** START CODE HERE *** N = len(dictionary) ratio = np.zeros((1,N)) for j in range(N): ratio[0,j] = np.log(phi_spam[0,j]/phi_nonspam[0,j]) sorted_ind = np.argsort(ratio) sorted_list = sorted_ind[0].tolist() word = [] for i in sorted_list: word.append(dictionary[i]) n = len(word) last_five = [word[n-1],word[n-2],word[n-3],word[n-4],word[n-5]] return last_five # *** END CODE HERE *** def compute_best_svm_radius(train_matrix, train_labels, val_matrix, val_labels, radius_to_consider): """Compute the optimal SVM radius using the provided training and evaluation datasets. You should only consider radius values within the radius_to_consider list. You should use accuracy as a metric for comparing the different radius values. Args: train_matrix: The word counts for the training data train_labels: The spma or not spam labels for the training data val_matrix: The word counts for the validation data val_labels: The spam or not spam labels for the validation data radius_to_consider: The radius values to consider Returns: The best radius which maximizes SVM accuracy. """ # *** START CODE HERE *** naive_bayes_accuracy = [] for j in radius_to_consider: y = svm.train_and_predict_svm(train_matrix, train_labels, val_matrix, j) naive_bayes_accuracy.append(np.mean(y == val_labels)) # *** END CODE HERE *** return radius_to_consider[np.argmax(naive_bayes_accuracy)] def main(): train_messages, train_labels = util.load_spam_dataset('spam_train.tsv') val_messages, val_labels = util.load_spam_dataset('spam_val.tsv') test_messages, test_labels = util.load_spam_dataset('spam_test.tsv') """" # Checking the code portions seperately dict = create_dictionary(train_messages) Arrray1 = transform_text(train_messages, dict) phi_y, phi_spam, phi_nonspam = fit_naive_bayes_model(Arrray1, train_labels) Arrray = transform_text(test_messages, dict) word = get_top_five_naive_bayes_words(phi_y, phi_spam, phi_nonspam, dict) #print(word) """ dictionary = create_dictionary(train_messages) print('Size of dictionary: ', len(dictionary)) util.write_json('spam_dictionary', dictionary) train_matrix = transform_text(train_messages, dictionary) np.savetxt('spam_sample_train_matrix', train_matrix[:100,:]) val_matrix = transform_text(val_messages, dictionary) test_matrix = transform_text(test_messages, dictionary) phi_y, phi_spam, phi_nonspam = fit_naive_bayes_model(train_matrix, train_labels) naive_bayes_predictions = predict_from_naive_bayes_model(phi_y, phi_spam, phi_nonspam, test_matrix) #np.savetxt('spam_naive_bayes_predictions', naive_bayes_predictions) naive_bayes_accuracy = np.mean(naive_bayes_predictions == test_labels) print('Naive Bayes had an accuracy of {} on the testing set'.format(naive_bayes_accuracy)) top_5_words = get_top_five_naive_bayes_words(phi_y, phi_spam, phi_nonspam, dictionary) print('The top 5 indicative words for Naive Bayes are: ', top_5_words) util.write_json('spam_top_indicative_words', top_5_words) optimal_radius = compute_best_svm_radius(train_matrix, train_labels, val_matrix, val_labels, [0.01, 0.1, 1, 10]) util.write_json('spam_optimal_radius', optimal_radius) print('The optimal SVM radius was {}'.format(optimal_radius)) svm_predictions = svm.train_and_predict_svm(train_matrix, train_labels, test_matrix, optimal_radius) svm_accuracy = np.mean(svm_predictions == test_labels) print('The SVM model had an accuracy of {} on the testing set'.format(svm_accuracy, optimal_radius)) if __name__ == "__main__": main()
# 1부터 n까지 나머지 없이 딱 떨어지는 수를 더하면 되는데 반이 넘어가면 계산 안하고 걍 자기자신 더해주면 됨 def solution(num): return num + sum([i for i in range(1, (num // 2)+1) if num % i == 0]) def test_solution(): assert solution(12) == 28 assert solution(5) == 6
# Python Program illustrating # working of argmax() import numpy as geek # Working on 2D array #array = geek.arange(12).reshape(3, 4) array = geek.random.randint(0,100,(4,3)) print("INPUT ARRAY : \n", array) # No axis mentioned, so works on entire array print("\nMax element : ", geek.argmax(array)) # returning Indices of the max element # as per the indices print("\nIndices of Max element : ", geek.argmax(array, axis=0)) print("\nIndices of Max element : ", geek.argmax(array, axis=1))
#!/usr/bin/python print ("Hello gd34639\nPrzykład klasy pozycja w Pythonie class Pozycja\n") class Pozycja: """Klasa przechowująca pozycję figury""" x = 0 y = 0 def __init__(self, pole): self.ustaw(pole) def ustaw(self, pole): self.x = ord(pole[0]) - ord('A') + 1 self.y = int(pole[1])
import numpy as np import math from pytope.polytope import Polytope from scipy.optimize import linprog class SupportFcn(): ''' Support Function Class Support Functions are a method of describing convex sets. They are defined by S(P; l) = sup {l^{T} x | x \in P } for some convex set P. They are used for the efficiency in representing Minkowski addition and linear mapping operations. See Boyd and Vandenberghe, "Convex Optimization". ''' # TODO: Add documentation # TODO: Additional unit testing # TODO: Add support for Minkowski differences between Polytopes and Support # functions # TODO: Implement support vectors # Turn off numpy ufunc __array_ufunc__ = None def __init__(self, n, callback=None): self._callback = callback self._n = n @property def n(self): return self._n def __call__(self, l): if self.is_empty: return np.array([], dtype=float) else: return self._callback(l) def __add__(self, b): if isinstance(b, SupportFcn): if self.n != b.n: raise ValueError('Cannot add support functions of different ' 'dimensions: {} + {}'.format(self.n, b.n)) if self.is_empty: if b.is_empty: return SupportFcn(self.n) else: return SupportFcn(b.n, callback=lambda l: b(l)) else: if b.is_empty: return SupportFcn(self.n, callback=lambda l: self(l)) else: return SupportFcn(self.n, callback=lambda l: self(l) + b(l)) elif isinstance(b, np.ndarray): if len(b.shape) > 1: raise ValueError('Cannot add support function and a matrix') else: if b.shape[0] != self.n: raise ValueError('Cannot perform addition: support ' 'function and vector are not of compatible dimension: ' '{} + {}'.format(self.n, b.shape[0])) return SupportFcn(self.n, callback=lambda l: self(l) + (l @ b)) elif isinstance(b, float): if self.n > 1: raise ValueError('Cannot perform addition: support function ' 'dimension mismatch: {} + {}'.format(self.n, 1)) return SupportFcn(self.n, callback=lambda l: self(l) + l * b) else: return NotImplemented def __rmul__(self, A): if self.is_empty: return SupportFcn(self.n) if isinstance(A, np.ndarray) or isinstance(A, float): if isinstance(A, float): return SupportFcn(self.n, callback=lambda l: self(A * l)) else: if len(A.shape) != 2: if len(A.shape) == 1 and A.shape[0] == 1: # Passed a scalar in the form of a numpy array return A[0] * self else: raise ValueError('Can only perform multiplication by ' 'a scalar or a matrix') else: if self.n != A.shape[1]: raise ValueError('Dimension mismatch between matrix ' 'multiplier and dimension of the support function ' 'space') return SupportFcn(A.shape[0], callback=lambda l: self(A.T @ l)) else: return NotImplemented def to_polytope(self, A): A = np.array(A, dtype=float) if len(A.shape) > 1: b = np.empty(A.shape[0]) for i, a in enumerate(A): b[i] = self(a) else: b = self(A) return Polytope(A, b) @property def is_empty(self): return self._callback is None @classmethod def forNdSphere(self, xc, rad): xc = np.array(xc, dtype=float) if len(xc.shape) > 1: raise ValueError('Center point must be a vector') n = xc.shape[0] return SupportFcn(n, lambda l: sup_ndsphere_callback(xc, rad, l)[0]) @classmethod def forPolytope(self, poly): if not isinstance(poly, Polytope): raise ValueError('Unexpected input type. Expected ' 'pytope.Polytope; received {}'.format(type(poly))) if poly.in_V_rep: if len(poly.V.shape) > 1: n = poly.V.shape[1] else: n = poly.V.shape[0] return SupportFcn(n, callback=lambda l: sup_vpoly_callback(poly, l)[0]) else: if len(poly.A.shape) > 1: n = poly.A.shape[1] else: n = poly.A.shape[0] return SupportFcn(n, callback=lambda l: sup_hpoly_callback(poly, l))[0] def sup_vpoly_callback(poly, l): y = poly.V @ l i = np.argmax(y) return y.max(), poly.V[i] def sup_hpoly_callback(poly, l): res = linprog(-l, poly.A, poly.b, bounds=(-np.inf, np.inf)) if not res.success: raise RuntimeError('Polytope support function lp failed with the ' 'message: {}'.format(res.message)) return -res.fun, res.x def sup_ndsphere_callback(xc, r, l): if np.linalg.norm(l) == 0: return 0 else: sv = xc + r * l / np.linalg.norm(l) return l @ sv, sv class SupportVector(): ''' Support Vector Class Support Vectors are a method of describing convex sets. They are defined by S(P; l) = argsup {l^{T} x | x \in P } for some convex set P. They are used for the efficiency in representing Minkowski addition and linear mapping operations. See Boyd and Vandenberghe, "Convex Optimization". ''' # TODO: Add documentation # TODO: Additional unit testing # TODO: Add support for Minkowski differences between Polytopes and Support # functions # TODO: Implement support vectors # Turn off numpy ufunc __array_ufunc__ = None def __init__(self, n, callback=None): self._callback = callback self._n = n @property def n(self): return self._n def __call__(self, l): if self.is_empty: return np.array([], dtype=float) else: return self._callback(l) def __add__(self, b): if isinstance(b, SupportVector): if self.n != b.n: raise ValueError('Cannot add support functions of different ' 'dimensions: {} + {}'.format(self.n, b.n)) if self.is_empty: if b.is_empty: return SupportVector(self.n) else: return SupportVector(b.n, callback=lambda l: b(l)) else: if b.is_empty: return SupportVector(self.n, callback=lambda l: self(l)) else: return SupportVector(self.n, callback=lambda l: self(l) + b(l)) elif isinstance(b, np.ndarray): if len(b.shape) > 1: raise ValueError('Cannot add support function and a matrix') else: if b.shape[0] != self.n: raise ValueError('Cannot perform addition: support ' 'function and vector are not of compatible dimension: ' '{} + {}'.format(self.n, b.shape[0])) return SupportVector(self.n, callback=lambda l: self(l) + b) elif isinstance(b, float): if self.n > 1: raise ValueError('Cannot perform addition: support function ' 'dimension mismatch: {} + {}'.format(self.n, 1)) return SupportVector(self.n, callback=lambda l: self(l) + b) else: return NotImplemented def __rmul__(self, A): if self.is_empty: return SupportFcn(self.n) if isinstance(A, np.ndarray) or isinstance(A, float): if isinstance(A, float): return SupportVector(self.n, callback=lambda l: A * self(A * l)) else: if len(A.shape) != 2: if len(A.shape) == 1 and A.shape[0] == 1: # Passed a scalar in the form of a numpy array return A[0] * self else: raise ValueError('Can only perform multiplication by ' 'a scalar or a matrix') else: if self.n != A.shape[1]: raise ValueError('Dimension mismatch between matrix ' 'multiplier and dimension of the support vector ' 'space') return SupportVector(A.shape[0], callback=lambda l: A @ self(A.T @ l)) else: return NotImplemented def to_polytope(self, A): A = np.array(A, dtype=float) if len(A.shape) > 1: b = np.empty(A.shape[0]) for i, a in enumerate(A): b[i] = self(a) else: b = self(A) return Polytope(A, b) @property def is_empty(self): return self._callback is None @classmethod def forPolytope(self, poly): if not isinstance(poly, Polytope): raise ValueError('Unexpected input type. Expected ' 'pytope.Polytope; received {}'.format(type(poly))) if poly.in_V_rep: if len(poly.V.shape) > 1: n = poly.V.shape[1] else: n = poly.V.shape[0] return SupportFcn(n, callback=lambda l: sup_vpoly_callback(poly, l)[1]) else: if len(poly.A.shape) > 1: n = poly.A.shape[1] else: n = poly.A.shape[0] return SupportFcn(n, callback=lambda l: sup_hpoly_callback(poly, l))[1] @classmethod def forNdSphere(self, xc, rad): xc = np.array(xc, dtype=float) if len(xc.shape) > 1: raise ValueError('Center point must be a vector') n = xc.shape[0] return SupportVector(n, lambda l: sup_ndsphere_callback(xc, rad, l)[1])
import datetime # Instructions: # Practice: Companies and Employees # Instructions # Create an Employee type that contains information about employees of a company. Each employee must have a name, job title, and employment start date. # Create a Company type that employees can work for. A company should have a business name, address, and industry type. # Create two companies, and 5 people who want to work for them. # Assign 2 people to be employees of the first company. # Assign 3 people to be employees of the second company. # Output a report to the terminal the displays a business name, and its employees. # For example: # Acme Explosives is in the chemical industry and has the following employees # * Michael Chang # * Martina Navritilova # Jetways is in the transportation industry and has the following employees # * Serena Williams # * Roger Federer # * Pete Sampras class Employee: def __init__(self, emp_name,title, start): self.emp_name = emp_name self.job_title = title self.start_date = start class Company: def __init__(self, buss_name, industry): self.buss_name = buss_name self.address = "" self.industry_type = industry self.employees = list() life_way = Company("LifeWay", "Publishing") home_depot = Company("HomeDepot", "Building Materials") mimi = Employee("Mimi Chu", "Sales Manager", datetime.datetime.now()) jay = Employee("Jay Galleg", "Engineer", datetime.datetime.now()) tedy = Employee("Teddy Anders", "Admin", datetime.datetime.now()) vince = Employee("Vince Smith", "Finance Analyst", datetime.datetime.now()) peter = Employee("Peter McDonald", "Farmer", datetime.datetime.now()) life_way.employees.append(mimi) life_way.employees.append(jay) home_depot.employees.append(tedy) home_depot.employees.append(vince) home_depot.employees.append(peter) # companies = [] # companies.append(life_way) # companies.append(home_depot) print(f'{life_way.buss_name} is a {life_way.industry_type} industry and has the following employees:') for employee in life_way.employees: print(f"* {employee.emp_name}") print(f'{home_depot.buss_name} is a {home_depot.industry_type} industry and has the following employees:') for employee in home_depot.employees: print(f"* {employee.emp_name}")
#!/usr/bin/env python """ exemplify grayscale color histogram Parameters Usage Example $ python <scriptname>.py --image ../img/<filename>.png ## Explain """ import matplotlib.pyplot as plt import argparse import cv2 def main(): ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("Original", image) hist = cv2.calcHist([image], [0], None, [256], [0, 256]) M = [image, hist] fig, ax = plt.subplots(1, 2, figsize=(10,4)) for(i, img) in enumerate(M): if i == 0: ax[i].imshow(img, cmap="gray") else: ax[i].plot(img, c="k") ax[i].set_title("Grayscale Histogram") ax[i].set_xlabel("Bins") ax[i].set_ylabel("# of Pixels") ax[i].set_xlim([0, 256]) plt.savefig("../fig/grayscale_histogram.png") cv2.waitKey(0) if __name__=="__main__": main()
#!/usr/bin/env python """ Exemplify thresholding, binarization of an grayscale image to either 0 or 255 --> select pixel value $p$ as threshold Applications: - preprocessing, focus on objects or areas of particular interest in an image - segment foreground and background Parameters Usage Example $ python <scriptname>.py --image ../img/<filename>.png ## Explain """ import numpy as np import argparse import cv2 def main(): ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # remove high frequency edges with a blur kernel blurred = cv2.GaussianBlur(image, (5, 5), 0) cv2.imshow("Image", image) # threshold (T, thres) = cv2.threshold(blurred, 155, 255, cv2.THRESH_BINARY) cv2.imshow("Threshold Binary", thres) (T, thresInv) = cv2.threshold(blurred, 155, 255, cv2.THRESH_BINARY_INV) cv2.imshow("Threshold Binary Inverse", thresInv) cv2.imshow("Coins", cv2.bitwise_and(image, image, mask = thresInv)) cv2.waitKey(0) if __name__=="__main__": main()
#Nested_Lists d = {} for _ in range(int(input())): s = input() n = float(input()) d[s] = n v = d.values() l = sorted(list(set(v)))[1] k = [] for key,value in d.items(): if value == l: k.append(key) k.sort() for i in k: print(i)
#Chef_and_the_Wildcard_Matching for _ in range(int(input())): s=input() t=input() c=1 for i in range(len(s)): if(s[i]==t[i]): continue elif(s[i]=='?'): continue elif(t[i]=='?'): continue else: c=0 break if(c==0): print("No") else: print("Yes")
#boy_or_girl s=input() a=set(s) if(len(a)%2!=0): print("IGNORE HIM!") else: print("CHAT WITH HER!")
#Zoos s = input() o = s.count('o') z = s.count('z') if o % 2 == 0 and o >= 2 * z: print("Yes") else: print("No")
#Lift_queries la = 0 lb = 7 for _ in range(int(input())): n = int(input()) if n - la <= lb - n: print("A") la = n else: print("B") lb = n
#Anagrams from collections import Counter for _ in range(int(input())): a = input() b = input() A = Counter(a) B = Counter(b) e = A & B d = e.values() g = sum(d) print(len(a)+len(b)-2*(g))
#Author - Roshan ghimire #Amusing_Joke from collections import Counter s=input() #SANTACLAUS t=input() #DEDMOROZ m=input()#SANTAMOROZDEDCLAUS if(Counter(s)+Counter(t)==Counter(m)): print("YES") else: print("NO")
#HOW_MANY_DIGITS_DO_I_HAVE n=input() if(len(n)<=3): print(len(n)) else: print("More than 3 digits")
#word_capitalization s=input() print(s[0].upper()+s[1:len(s)+1])
#Chef_and_Interactive_Contests n , r = map(int,input().split()) for i in range(n): a = int(input()) if a >= r: print("Good boi") else: print("Bad boi")
#Teddy_and_Tweety n = int(input()) a = n // 3 if a + a + a == n: print("YES") else: print("NO")
def islower(letter): return letter.islower() def generate(maxLen, word = "S"): if len("".join(filter(islower, word))) > maxLen: return if word == "": solution.add("#") elif word.islower() and len(word) <= maxLen: solution.add(word) else: for (index, letter) in enumerate(word): if letter.isupper(): for production in productions[letter]: generate(maxLen, word[:index] + production + word[index+1:]) with open("grammar.txt") as file: productions = {} for line in file.readlines(): if line == "\n": break left, right = line[:-1].split("-") if right == "#": right = "" if left not in productions: productions[left] = [] productions[left].append(right) n = int(input("n=")) solution = set() generate(n) print("Solutie:", ", ".join(sorted(solution)))
# import time # import os # import pandas # while True: # if os.path.exists("files/temps_today.csv"): # data = pandas.read_csv("files/temps_today.csv") # print(data.mean()["st1"]) # else: # print("File does not exist.") # #time.sleep(10) import json import difflib from difflib import get_close_matches def word_def(word): data = json.load(open("teaching/data.json")) word = word.lower() if word in data: return data[word] elif len(get_close_matches(word, data.keys())) > 0: print("Did you mean %s instead? Press Y if yes, and N if no." %get_close_matches(word, data.keys())[0]) if input() == "Y": return data[get_close_matches(word, data.keys())[0]] else: return "We didn't find word. Please double check it." else: return "We didn't find word. Please double check it." output = word_def(input("Enter the word: ")) if type(output) == list: for i in output: print(i) else: print(output)
word = input() index =0 list=[] flagAB=False flagBA=False while index<len(word)-1: if word[index].lower()+word[index+1].lower() =="ab": flagAB=True index+=2 elif word[index].lower()+word[index+1].lower()=="ba": flagBA=True index+=2 else: index+=1 if flagAB and flagBA: print("YES") else: print("NO")
value = 0 age = 0 while value != -1: value = int( input()) if value>=10 and value<=90: if value >= age: age = value print(age)
x=int(input()) if x>0 and x<6: print('khordsal') elif x>=6 and x<10: print('koodak') elif x>=10 and x<14: print('nojavan') elif x>=14 and x<24: print('javan') elif x>=24 and x<40: print('bozorgsal') elif x>=40: print('miansal')
def find_recurring_char(inp_string): hash_table = {} for x in inp_string: if x in hash_table: return(x) else: hash_table[x] = 1 return("Nothing Found!") print(find_recurring_char("abca"))
# import packages from qiskit import * import numpy as np import random as rand def qAlice_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return 0 elif(inp == 1): return np.pi/2 else: print("INVALID choice") return 100 def qBob_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return np.pi/4 elif(inp == 1): return -np.pi/4 else: print("INVALID choice") return 100 # Alice's strategy qA_st = int(input('select the quantum strategy for Alice, input 1,2 or 3 to pick one of the strategies listed above: ')) # Bob's strategy qB_st = int(input('select the quantum strategy for Bob, input 1,2 or 3 to pick one of the strategies listed above: ')) # set parameters of the quantum run of the game shots = 1 # set how many times the circuit is run, accumulating statistics about the measurement outcomes backend = 'local_qasm_simulator' # set the machine where the quantum circuit is to be run #fixes the numbers of games to be played N=100 # initializes counters used to keep track of the numbers of games won and played by Alice an Bob cont_win = 0 # counts games won cont_tot = 0 # counts games played #play N games for i in range(N): #creates quantum program, which allows to specify the details of the circuit like the register and the gates used Q_program = QuantumProgram() # creates registers for qubits and bits q = Q_program.create_quantum_register('q', 2) # creates a quantum register, it specifies the qubits which are going to be used for the program c = Q_program.create_classical_register('c', 2) # creates a classical register, the results of the measurement of the qubits are stored here # creates quantum circuit, to write a quantum algorithm we will add gates to the circuit game = Q_program.create_circuit('game', [q], [c]) # These gates prepare the entangled Bell pair to be shared by Alice and Bob as part of their quantum strategy # Alice will have qubit 0 and Bob will have qubit 1 game.h(q[0]) # Hadamard gate on qubit 0 game.cx(q[0],q[1]) # CNOT gate on qubit 1 controlled by qubit 0 # generates two random input from the refree, x and y, to be given to Alice and Bob random_num1 = rand.random() # first random number random_num2 = rand.random() # second random number if(random_num1 >= 1/2): # converts the first random number to 0 or 1 x = 0 else: x = 1 if(random_num2 >= 1/2): # converts the second random number to 0 or 1 y = 0 else: y = 1 # The main part of Alice and Bob quantum strategy is to fix different rotation angles for their qubit according to the input x,y theta = qAlice_output(qA_st, x) # fixes Alice's rotation for her qubit phi = qBob_output(qB_st, y) # fixes Bob's rotation for his qubit # The following gates rotate Alice's qubit and Bob's qubit game.ry(theta,q[0]) #rotates Alice's qubit of an angle theta game.ry(phi,q[1]) ##rotates Bob's qubit of an angle phi # These gates are used to measure the value of the qubits game.measure(q[0], c[0]) # measure Alice's qubit and stores the result in a classical bit game.measure(q[1], c[1]) # measure Bob's qubit and stores the result in a classical bit # Assemble the gates in the circuit circuits = ['game'] # assemble circuit # executes circuit and store the output of the measurements #result = Q_program.execute(circuits, backend=backend, shots=shots, wait=10, timeout=240) result = Q_program.execute(circuits, backend=backend, shots=shots, timeout=240) data = result.get_counts('game') # extract the outcomes and their statistics from the result of the execution # reads the result of the measurements of the quantum system for outcomes in data.keys(): out = outcomes # converts the result of the measurements contained in the classical register as string '00', '01', '10', '11', # which are the answers of Alice(a) and Bob (b), from a 'string' type to 'integer' type if(out == '00'): a = 0 b = 0 if(out == '01'): a = 1 b = 0 if(out == '10'): a = 0 b = 1 if(out == '11'): a = 1 b = 1 # check if the condition for winning the game is met if(x*y == a^b): cont_win += 1 # increase thes won games' counter if the condition to win the game is met cont_tot += 1 # increases the played games' counter qProb_win = cont_win/cont_tot print('Alice and Bob won the game with probability: ', qProb_win*100, '%')
import numpy import math import random import collections import matplotlib.pylab as plt from collections import defaultdict def dot(v, w): return sum(v_i * w_i for v_i, w_i in zip(v,w)) def sum_of_squares(v): return dot(v,v) def mean(x): return sum(x) / len(x) def de_mean(x): x_bar = mean(x) return [x_i - x_bar for x_i in x] def variance(x): n = len(x) deviations = de_mean(x) return sum_of_squares(deviations) / n def expected_value(p, x): return sum([pi * xi for pi, xi in zip(p,x)]) def square(list): return [i ** 2 for i in list] sim = int(input("How many simulations to run? ")) if sim <= 0: sim = 100 counts = defaultdict(int) a = 0 b = 0 aa = 0 bb = 0 for s in range(sim): a = random.randint(-1,1) b = random.randint(-1,1) aa = random.randint(-1,1) bb = random.randint(-1,1) f = abs(a*(b-bb) + aa*(b+bb)) #f = a*(b-bb) + aa*(b+bb) counts[f] += 1 #calculate the average, variance, expected value av = sum(counts.keys()) / len(counts.keys()) events = list(counts.values()) total_events = sim probs = [ev / total_events for ev in events] vals = list(counts.keys()) vals_squared = square(list(counts.keys())) print("Average: {0}".format(av)) print("Variance: {0}".format(variance(vals))) print("Expected Value: +-{0}".format(expected_value(probs, vals))) plt.bar(counts.keys(), counts.values()) plt.show()
class Link: """A linked list. >>> s = Link(1) >>> s.first 1 >>> s.rest is Link.empty True >>> s = Link(2, Link(3, Link(4))) >>> s.first = 5 >>> s.rest.first = 6 >>> s.rest.rest = Link.empty >>> s # Displays the contents of repr(s) Link(5, Link(6)) >>> s.rest = Link(7, Link(Link(8, Link(9)))) >>> s Link(5, Link(7, Link(Link(8, Link(9))))) >>> print(s) # Prints str(s) <5 7 <8 9>> """ empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest def __repr__(self): if self.rest is not Link.empty: rest_repr = ', ' + repr(self.rest) else: rest_repr = '' return 'Link(' + repr(self.first) + rest_repr + ')' def __str__(self): string = '<' while self.rest is not Link.empty: string += str(self.first) + ' ' self = self.rest return string + str(self.first) + '>' # 1.1 def multiply_lnks(lst_of_lnks): """ >>> a = Link(2, Link(3, Link(5))) >>> b = Link(6, Link(4, Link(2))) >>> c = Link(4, Link(1, Link(0, Link(2)))) >>> p = multiply_lnks([a, b, c]) >>> p.first 48 >>> p.rest.first 12 >>> p.rest.rest.rest is Link.empty True """ # recursive solution: first = 1 for i in range(len(lst_of_lnks)): if lst_of_lnks[i] is Link.empty: return Link.empty else: first *= lst_of_lnks[i].first lst_of_lnks[i] = lst_of_lnks[i].rest link = Link(first, multiply_lnks(lst_of_lnks)) return link # Iterative solution: # import operator # from functools import reduce # def prod(factors): # return reduce(operator.mul, factors, 1) # # head = Link.empty # tail = head # while Link.empty not in lst_of_lnks: # all_prod = prod(_.first for _ in lst_of_lnks) # if head is Link.empty: # head = Link(all_prod) # tail = head # else: # tail.rest = Link(all_prod) # tail = tail.rest # lst_of_lnks = [_.rest for _ in lst_of_lnks] # return head # 1.2 def remove_duplicates(lnk): """ >>> lnk = Link(1, Link(1, Link(1, Link(1, Link(5))))) >>> remove_duplicates(lnk) >>> lnk Link(1, Link(5)) """ # recursive solution: # if lnk is Link.empty or lnk.rest is Link.empty: # return # elif lnk.first == lnk.rest.first: # lnk.rest = lnk.rest.rest # remove_duplicates(lnk) # else: # remove_duplicates(lnk.rest) # !!!!sorted linked list # Iterative solution: while lnk is not Link.empty and lnk.rest is not Link.empty: if lnk.first == lnk.rest.first: lnk.rest = lnk.rest.rest else: lnk = lnk.rest # 3.1 def even_weighted(lst): """ >>> x = [1, 2, 3, 4, 5, 6] >>> even_weighted(x) [0, 6, 20] """ return [i * lst[i] for i in range(len(lst)) if i % 2 == 0] # 3.2 def quicksort_list(lst): """ >>> quicksort_list([3, 1, 4]) [1, 3, 4] """ if len(lst) == 1: return lst pivot = lst[0] less = [i for i in lst if i < pivot] greater = [i for i in lst if i > pivot] return quicksort_list(less) + [pivot] + quicksort_list(greater) # 3.3 def max_product(lst): """Return the maximum product that can be formed using lst without using any consecutive numbers >>> max_product([10,3,1,9,2]) # 10 * 9 90 >>> max_product([5,10,5,10,5]) # 5 * 5 * 5 125 >>> max_product([]) 1 """ if len(lst)==0: return 1 elif len(lst)==1: return lst[0] else: return max(max_product(lst[1:]),lst[0]*max_product(lst[2:])) # 3.4 def redundant_map(t, f): """ >>> double = lambda x: x*2 >>> tree = Tree(1, [Tree(1), Tree(2, [Tree(1, [Tree(1)])])]) >>> redundant_map(tree, double) >>> print_levels(tree) [2] # 1 * 2 ˆ (1) ; Apply double one time [4, 8] # 1 * 2 ˆ (2), 2 * 2 ˆ (2) ; Apply double two times [16] # 1 * 2 ˆ (2 ˆ 2) ; Apply double four times [256] # 1 * 2 ˆ (2 ˆ 3) ; Apply double eight times """ t.label = f(t.label) new_f = lambda x: f(f(x)) for branch in t.branches: return redundant_map(branch,new_f)
# Constructor def tree(label, branches=[]): for branch in branches: assert is_tree(branch) return [label] + list(branches) # Selectors def label(tree): return tree[0] def branches(tree): return tree[1:] def is_tree(tree): if type(tree) != list or len(tree) < 1: return False for branch in branches(tree): if not is_tree(branch): return False return True # For convenience def is_leaf(tree): return not branches(tree) # fall 2015,midterm 2,#3a def complete(t, d, k): """Return whether t is d-k-complete. A tree is d-k-complete if every node at a depth less than d has exactly k branches and every node at depth d is a leaf. >>> complete(tree(1),0,5) True >>> u=tree(1,[tree(1),tree(1),tree(1)]) >>> complete(tree(1,[u,u,u]),2,3) True >>> complete(u,1,3) True >>> complete(tree(1,[u,u]),2,3) False """ if not branches(t): # is_leaf(t) return d == 0 bs = [complete(branch, d - 1, k) for branch in branches(t)] return len(branches(t)) == k and all(bs) # Spring 2018,Exam-Prep 03,#1 x, y, z = 1, 2, 3 y = [x, [y, [z, []]]] x = [y[1][0], y, [y[1][1][1]]] z = len([]) class Tree: def __init__(self, root, branches=[]): self.root = root for branch in branches: assert isinstance(branch, Tree) self.branches = list(branch) def is_leaf(self): return not self.branches class Tree(object): def __init__(self, entry, left=None, right=None): self.entry = entry self.left = left self.right = right # Spring 2015,Midterm 2,#3c def closest(t): """ Return the smallest difference between an entry and the sum of the entries of its branches . >>> t = Tree (8 , [ Tree (4) , Tree (3)]) >>> closest (t) # |8 - (4 + 3)| = 1 1 >>> closest ( Tree (5 , [t])) # Same minimum as t 1 >>> closest ( Tree (10 , [ Tree (2) , t])) # |10 - (2 + 8)| = 0 0 >>> closest ( Tree (3)) # |3 - 0| = 3 3 >>> closest ( Tree (8 , [ Tree (3 , [ Tree (1 , [ Tree (5)])])])) # |3 - 1| = 2 2 >>> sum ([]) 0 """ diff = abs(t.entry - sum([b.entry for b in t.branches])) return min([diff], [closest(b) for b in t.branches]) # Custom Question def is_path(t, path): """Return whether a given path exists in a tree, beginning at the root. >>> t = tree(1, [tree(2, [tree(4), tree(5)]), tree(3, [tree(6), tree(7)])]) >>> is_path(t, [1, 2]) True >>> is_path(t, [1, 2, 4]) True >>> is_path(t, [2, 4]) False """ if label(t) != path[0]: return False if not branches(t): return True return any([is_path(b, path[1:]) for b in branches(t)]) #Spring 2015,Midterm 2,#4b def scramble(egg): return [egg,over(egg)] def over(easy): easy[1]=[[easy],2] return list(easy[1]) egg = scramble([12,24])
#Add a legend title and axis labels to this plot to plot from lab 8.8.py import numpy as np import matplotlib.pyplot as plt minSalary = 20000 maxSalary = 80000 minAges = 21 maxAges = 65 numberOfEntries = 100 # this is so that the "random" numbers are the same each time to make it easier to debug. np.random.seed(1) salaries = np.random.randint(minSalary, maxSalary, numberOfEntries) ages = np.random.randint(minAges,maxAges,numberOfEntries) plt.scatter(ages, salaries, label="salaries") #plt.show() # if you do this the proram will halt here until the plot is closed add x squared xpoints = np.array(range(1, 101)) ypoints = xpoints * xpoints # multiply each entry by itself plt.plot(xpoints, ypoints, color='r', label = "x squared") plt.title("random plt") plt.xlabel("Salaries") plt.ylabel("age") plt.legend() plt.show()
#This program taken in a float from the user and outputs the absolute value of that float # Author: Ciaran Moran number = float(input("Enter a number:")) absoluteValue = abs(number) print('The absolute value of {} is {}'.format(number, absoluteValue))
# nameAndAge.py # This program reads in Users name and age, then prints it out # Author: Ciaran Moran name = input("What is your name?:") age = input("What is your age?:") print('Hello {},\t your age is {}.'.format(name,age))
# es.py # This program reads in a text file from an arguement on the command line. # It outputs the number of "e" characters in the file. # Author: Ciaran Moran import os import sys filename = sys.argv[1] # accept the 2nd arguement from the command line def readFile(filename): with open(filename,'r') as f: # open file in read only mode, use of alias means no need to close file data = f.read() # call the read function on the alias return data def eCharacterCount(data): eCount = data.count("e") # use of .count method to count occurances of a character in a file ECount = data.count("E") eTotal = eCount + ECount print("There are {} lowercase 'e' characters in this text file".format(eCount)) print("There are {} uppercase 'E' characters in this text file".format(ECount)) print("There are {} total 'e' characters in this text file (case independant)".format(eTotal)) data = readFile(filename) eCharacterCount(data) # main reference list is in pands-problem-sheet reposotory README file #Refernces used: # 1.Docs.python.org, 2021, 7.2. Reading and Writing Files — Python 3.9.2 Documentation, viewed 05 March 2021, https://docs.python.org/3/tutorial/inputoutput.html # 3.GeeksforGeeks, 2019, How to use sys.argv in Python, viewed 12 March 2021, https://www.geeksforgeeks.org/how-to-use-sys-argv-in-python/ # 3.GeeksforGeeks, 2019, With statement in Python, viewed 05 March 2021, https://www.geeksforgeeks.org/with-statement-in-python. # 4.Gutenberg.org, 2000, Moby Dick, viewed 05 March 2021, https://www.gutenberg.org/files/2701/old/moby10b.txt # 5.Zíka, H, 2018, Counting specific characters in a file (Python), viewed 12 Mar 2021, https://stackoverflow.com/questions/48885930/counting-specific-characters-in-a-file-python.
#This program takes a user input as a float as this datatype will accept decimal places (9.44 dollars mentioned in question) #Next converts the float to an abso1ute value (to remove and negative signs) #Next converts the absolute value to cent and rounds result to the nearest integer (zero decimal places) #Author: Ciaran Moran moneyAmount = float(input("Enter the amount of money in dollars: ")) absoluteValue = abs(moneyAmount) dollarToCent = round(absoluteValue* 100,0) print(dollarToCent)
str="space remove" ans="" cnt=0; for i in str: if i==' ': cnt+=1; continue; ans=ans+i; for i in range(0,cnt): ans='_'+ans; print("\n"); print("after moving space to front (_ represented as space) ",ans); print("\n");
import copy class Input: data = None concrete = False def __init__(self): pass def __len__(self): return len(self.data) def copy(self): #print "data:",self.data return copy.copy(self) def isSymbolic(self): return not self.concrete def isConcrete(self): return self.concrete def SetSymbolic(self): self.concrete = False def SetConcrete(self): self.concrete = True class Arg(Input): def __init__(self, i, data): self.i = i self.data = str(data) if ("\0" in data): self.data = self.data.split("\0")[0] self.size = len(self.data) def __str__(self): return "Arg("+str(self.i)+") = "+repr(self.data) def GetData(self): return str(self.data) def GetSize(self): return len(self.data) def PrepareData(self): return self.GetData() def IsValid(self): return self.size > 0 def __cmp__(self, arg): return cmp(self.i, arg.i) # def copy(self): # return Arg(self.i, self.data) def GetName(self): if self.concrete: return "cargv_"+str(self.i) else: return "argv_"+str(self.i) def GetType(self): return "arg" class File(Input): def __init__(self, filename, data): self.filename = str(filename) self.data = str(data) self.size = len(data) def __str__(self): return "file("+str(self.filename)+") = "+repr(self.data) def GetData(self): return str(self.data) def GetSize(self): return len(self.data) def PrepareData(self): if self.filename == "/dev/stdin": with open("Stdin", 'w') as f: f.write(self.data) return "< Stdin" else: with open(self.filename, 'w') as f: f.write(self.data) return None def IsValid(self): return True def GetName(self): return "file_"+self.filename.replace("/", "__") def GetType(self): return "file"
import os import getpass import random print(" ------------------------\n| Piggy's Trolling Tools: |\n| :-: Folder Creator :-: |\n ------------------------\n") where = input("Input directory where folders should be created: ") name = input("Enter folder name: ") total = int(input("Enter amount of Folders: ")) os.chdir(where) os.system("cls") getpass.getpass(prompt=f"\nPress enter to create {total} folders\n") for i in range(total): try: randomnum = random.randrange(100) os.mkdir(f"{name} #{randomnum}") print(f"Created: \"{name} #{randomnum}\" |") except Exception as error: print(error) pass print("\nFinished.\n")
""" Simple graph implementation compatible with BokehGraph class. """ import random class Vertex: def __init__(self, vertex_id, x=None, y=None): self.id = vertex_id self.edges = set() if x is None: self.x = random.random() * 10 - 5 else: self.x = x if y is None: self.y = random.random() * 10 - 5 else: self.y = y def __repr__(self): return f"{self.edges}" class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): """ Create an empty graph """ self.vertices = {} def add_vertex(self, vertex_id): """ Add an vertex to the graph """ self.vertices[vertex_id] = Vertex(vertex_id) def add_edge(self, v1, v2): """ Add an undirected edge to the graph """ if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].edges.add(v2) self.vertices[v2].edges.add(v1) else: raise IndexError("That vertex does not exist!") def add_directed_edge(self, v1, v2): """ Add a directed edge to the graph """ if v1 in self.vertices: self.vertices[v1].edges.add(v2) else: raise IndexError("That vertex does not exist!")
import socket import sys import zipfile import os host = '127.0.0.1' port = 1337 k = int(sys.argv[1]) zip_name = 'main.zip' s = socket.socket() print('[+] Client socket is created.') s.connect((host, port)) print('[+] Socket is connected to {}'.format(host)) with zipfile.ZipFile(zip_name, 'w') as file: for j in range(1, (k+1)): file.write('{}.jpg'.format(j)) print('[+] {}.jpg is sent'.format(j)) s.send(zip_name.encode()) f = open(zip_name, 'rb') l = f.read() s.sendall(l) os.remove(zip_name) f.close() s.close()