text
stringlengths
37
1.41M
days=int(input("Input dys"))*3600*24 hour=int(input("Input hour"))*3600 minute=int(input("Input minutes"))*60 seconds=int(input("seconds")) time=days+hour+minute+second print("the amount of seonds",time)
print("Writen by Oli4.0 Verwoerd\n") # Don't change the imports import csv import os try: with open('export.csv') as check: check.close() except: print("ERROR FILE CAN NOT BE OPENED. check if the file is called export.csv") print("Please note it's csv") input('Press ENTER to continue...') exit() datesSet = set() hours = 0; with open('export.csv') as f: for line in f.readlines(): for s in line[1:11].split(';'): if s[6:8] == "20": datesSet.add(s) for h in line[14:22].split(';'): if h[3:6] == "min": hours += (float(h[0:2]) / 60) if h[2:5] == "uur": hours += (float(h[0:1])) if h[4:7] == "uur": hours += (float(h[0:3])) if h[5:8] == "uur": hours += (float(h[0:4])) print("Total Hours = " + str(round(hours, 2)) + " / 800 = " + str(round((hours / 800 * 100), 2)) + "%") print("Total Days = " + str(len(datesSet)) + " / 100") print("Total Reseve hours = " + str(round(hours, 2) - len(datesSet)*8)) input('Press ENTER to close...') #input('Press ENTER to close')
""" This is code to let humans play Atari games, via the Arcade Learning Environment and the pygame library. This is based on code originally written by Ben Goodrich, who modifed ale_python_test_pygame.py to provide an interactive experience to allow humans to play. I can also display RAM contents, current action, and reward if needed. The keys are: arrow keys -> up/down/left/right, z -> fire button. Right now, the human plays one Atari game for one episode. Some games can take a while so I'll probably just call these as needed. Also, after every game, I can double check if the is enough RAM to store all the screenshots. Store them on my work station! Games tested/verified/understood with notes (see other files for details): 1. Breakout 2. Space Invaders [WIP] """ import os import errno import re import glob import sys import string from ale_python_interface import ALEInterface import pygame import scipy.misc from PIL import Image import time import numpy as np import utilities np.set_printoptions(edgeitems=20) # For now keep this global and intact. It's ugly, but works. key_action_tform_table = ( 0, #00000 none 2, #00001 up 5, #00010 down 2, #00011 up/down (invalid) 4, #00100 left 7, #00101 up/left 9, #00110 down/left 7, #00111 up/down/left (invalid) 3, #01000 right 6, #01001 up/right 8, #01010 down/right 6, #01011 up/down/right (invalid) 3, #01100 left/right (invalid) 6, #01101 left/right/up (invalid) 8, #01110 left/right/down (invalid) 6, #01111 up/down/left/right (invalid) 1, #10000 fire 10, #10001 fire up 13, #10010 fire down 10, #10011 fire up/down (invalid) 12, #10100 fire left 15, #10101 fire up/left 17, #10110 fire down/left 15, #10111 fire up/down/left (invalid) 11, #11000 fire right 14, #11001 fire up/right 16, #11010 fire down/right 14, #11011 fire up/down/right (invalid) 11, #11100 fire left/right (invalid) 14, #11101 fire left/right/up (invalid) 16, #11110 fire left/right/down (invalid) 14 #11111 fire up/down/left/right (invalid) ) class HumanPlayer(object): """ Represents a human playing one Atari game (for one episode). """ def __init__(self, game="breakout.bin", rand_seed=1, output_dir="output/"): self.ale = ALEInterface() self.game = game self.actions = [] self.rewards = [] self.screenshots = [] self.output_dir = output_dir # Set values of any flags (must call loadROM afterwards). self.ale.setInt("random_seed", rand_seed) self.ale.loadROM(self.game) # Other (perhaps interesting) stuff. self.random_seed = self.ale.getInt("random_seed") self.legal_actions = self.ale.getMinimalActionSet() print("Some info:\n-random_seed: {}\n-legal_actions: {}\n".format( self.random_seed, self.legal_actions)) def play_and_save(self): """ The human player now plays! After playing it calls a post-processing step. """ # TODO Figure out how to save checkpoints! # Both screen and game_surface are: <type 'pygame.Surface'>. pygame.init() screen = pygame.display.set_mode((320,420)) game_surface = pygame.Surface(self.ale.getScreenDims()) # (160,210) pygame.display.flip() # Clock and some various statistics. clock = pygame.time.Clock() total_reward = 0.0 time_steps = 0 start_time = time.time() # Iterate through game turns. while not self.ale.game_over(): time_steps += 1 # Get the keys human pressed. keys = 0 pressed = pygame.key.get_pressed() keys |= pressed[pygame.K_UP] keys |= pressed[pygame.K_DOWN] <<1 keys |= pressed[pygame.K_LEFT] <<2 keys |= pressed[pygame.K_RIGHT] <<3 keys |= pressed[pygame.K_z] <<4 action = key_action_tform_table[keys] reward = self.ale.act(action); total_reward += reward # Clear screen and get pixels from atari on the surface via blit. screen.fill((0,0,0)) rgb_image = self.ale.getScreenRGB().transpose(1,0,2) # Transposed! surface = pygame.surfarray.make_surface(rgb_image) screen.blit(pygame.transform.scale2x(surface), (0,0)) pygame.display.flip() # Updates screen. # Process pygame event queue. exit = False for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True break; if pressed[pygame.K_q]: exit = True if exit: break clock.tick(60.) # Higher number means game moves faster. self.rewards.append(reward) self.actions.append(action) self.screenshots.append(rgb_image) # Collect statistics and start post-processing. episode_frame_number = self.ale.getEpisodeFrameNumber() assert episode_frame_number == time_steps, \ "episode_frame_number = {}, time_steps = {}".format(episode_frame_number, time_steps) end_time = time.time() - start_time print("Number of frames: {}".format(episode_frame_number)) print("Game lasted {:.4f} seconds.".format(end_time)) print("Total reward: {}.".format(total_reward)) self.post_process() def post_process(self): """ Now save my game frames, actions, rewards, and checkpoints. This creates three sets of files in self.output_dir/game_name: -> screenshots: contains screenshots (one screenshot per file) -> rewards: contains rewards (one file, one reward per line) -> actions: contains actions (one file, one action per line) -> checkpoints: contains checkpoints (one file, checkpoints) These are nested within self.output_dir/game_name according to the game ID, in files 'game_ID', which we determine here by looking at the numbers that exist. The IDs should be listed in order as I increment them each time. Also, I pad the numbers to make it easier to read later once more games are added. """ # A bit clumsy but it works if I call in correct directory. game_name = (self.game.split("/")[1]).split(".")[0] padding_digits = 4 current_games = glob.glob(self.output_dir+ "/" +game_name+ "/game*") current_games.sort() next_index = 0 if len(current_games) != 0: previous_index = re.findall('\d+', current_games[-1])[0] next_index = int(previous_index)+1 game_id = string.zfill(next_index, padding_digits) head_dir = self.output_dir+ "/" +game_name+ "/game_" +game_id utilities.make_path_check_exists(head_dir) # TODO Check if rewards ever have floats but most are integers, I think. np.savetxt(head_dir+ "/actions.txt", self.actions, fmt="%d") np.savetxt(head_dir+ "/rewards.txt", self.rewards, fmt="%d") # TODO Check if I can extract max value automatically. utilities.make_path_check_exists(head_dir+ "/screenshots/") padding_digits_fr = 6 print("Now saving images ...") for (frame_index, scr) in enumerate(self.screenshots): if frame_index % 1000 == 0: print("Saved {} frames so far.".format(frame_index)) # Be sure to transpose, otherwise it's "sideways." Assumes RGB. im = Image.fromarray(scr.transpose(1,0,2)) pad_frame_num = string.zfill(frame_index, padding_digits_fr) im.save(head_dir+ "/screenshots/frame_" +pad_frame_num+ ".png") print("Done with post processing.")
import os from environments import River, Swamp, Coastline, Grassland, Forest, Mountain def annex_habitat(arboretum): #os.system('cls' if os.name == 'nt' else 'clear') print("1. River") print("2. Swamp") print("3. Coastline") print("4. Grassland") print("5. Forest") print("6. Mountain") biome = input("Choose your habitat > ") name = input("Name > ") if biome == "1": new_biome = River(name) arboretum.add_biome(new_biome) for river in arboretum.rivers: print(river) if biome == "2": new_biome = Swamp(name) arboretum.add_biome(new_biome) if biome == "3": new_biome = Coastline(name) arboretum.add_biome(new_biome) if biome == "4": new_biome = Grassland(name) arboretum.add_biome(new_biome) if biome == "5": new_biome = Forest(name) arboretum.add_biome(new_biome) if biome == "6": new_biome = Mountain(name) arboretum.add_biome(new_biome) print(f"Successfully annexed {name} to the arboretum.")
#!/usr/bin/env python3 # -*- coding:utf-8 -*- def is_odd(n): return n%2 == 1 print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))) def not_empty(s): return s and s.strip() print(list(filter(not_empty,['A','','B',None,'C',' ']))) def main(): # 生成1000以内的素数 for n in primes(): if n < 1000: print(n) else: break #生成一个奇数序列 def _odd_iter(): n = 1 while True: n = n+2 yield n #定义一个筛选函数 def _not_divisiable(n): return lambda x:x%n > 0 #定义一个生成器,不断返回下一个素数 def primes(): yield 2 it = _odd_iter() while True: n = next(it) yield n it = filter(_not_divisiable(n),it) if __name__ == '__main__': main() #生成回数
#函数 import sys sys.setrecursionlimit(10000)#设置递归的最大次数 def fun1(param1,param2): res1 = param1 * 2 res2 = param2 + res1 return res1,res2 result1,result2 = fun1(2,3) print(result1,result2)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from collections import Iterable,Iterator print(isinstance('acv',Iterable)) print(isinstance([1,2,3],Iterable)) def g(): yield 1 yield 2 yield 3 print('Iterable?[1,2,3]:',isinstance([1,2,3],Iterable)) print('Iterable?\'abc\':',isinstance('abc',Iterable)) print('Iterable? 123:',isinstance(123,Iterable)) print('Iterable? g():',isinstance(g(),Iterable)) print('Iterator?[1,2,3]:',isinstance([1,2,3],Iterator)) print('Iterator?iter([1,2,3]):',isinstance(iter([1,2,3]),Iterator)) print('Iterator?\'abc\':',isinstance('abc',Iterator)) print('Iterator? 123:',isinstance(123,Iterator)) print('Iterator? g():',isinstance(g(),Iterator)) for x in [1,2,3,4,5]: print(x) for x in iter([1,2,3,4,5]): print(x) #print(next():) it = iter([1,2,3,4,5]) print(next(it)) print(next(it)) print(next(it)) print(next(it)) print(next(it)) d={'a':1,'b':2,'c':3} for k in d.keys(): print('key:',k) for v in d.values(): print('value:',v) for k,v in d.items(): print('item:',k,v) #使用迭代查找一个list中最小和最大值,并返回一个tuple def findMinAndMax(L): pass r = sorted(L) le = len(r) t = [] for i,v in enumerate(r): if i == 0 : t.append(v) if i == le-1: t.append(v) return t print(findMinAndMax([1,3,5,2,4]))
#encoding=utf-8 sum = lambda a,b:a+b if a > b else a-b def sum(a,b): return a+b sum = sum(1,2) print(sum)
#coding: utf-8 class Student(): name = "" age = 0 gender = "" phone = "" address = "" email = "" def __init__(self,name,age,weight,grade,gender,phone,address,email): self.name = name self.age = age self.gender = gender self.phone = phone self.address = address self.email = email def eat(self): print("eat") def drink(self): print("drink") def play(self): print("play") def sleep(self): print("sleep") student_list = [] Arex = Student("Arex",28,60,19,"male","13166666666","shanghai","[email protected]") Bob = Student("Bob",18,50,9,"male","13588888888","beijing","[email protected]") student_list.append(Arex) student_list.append(Bob) while(1): name = input("please input the student's name:") email = input("please input the student's email:") address = input ("please input the student's address:") for student in student_list: if student.name == name or student.email == email or student.address == address: print(student.__dict__) elif student_list.index(student) == len(student_list) - 1: print("can't find the data. please input the right information.")
# coding: utf-8 ''' 一、编程逻辑 3、给定一个序列,计算任意个连续元素的最大平均值和其中的元素。 示例: 输入:序列list=[1,2,3,3,4,8,5,7],k=2 输出:最大平均值:(8+5)/2=6.5 元素为:[8,5] 输入:序列list=[1,2,3,5,4],k=3 输出:最大平均值:(3+5+4)/3=4 元素为:[3,5,4] 输入:序列list=[1,10,2,5,4],k=2 输出:最大平均值:(10+2)/2=6 元素为:[10,2] ''' ''' 思路: 下标从0开始移动,每个开始下标都遍历至末尾 ''' num_list = eval(input("请输入一个序列list:")) k = int(input("请输入k:")) length = len(num_list) ave_max = 0 total = 0 ele_list = [] for start_num in range(length-k): total = 0 for index in range(start_num, start_num+k): total = total + int(num_list[index]) if ave_max <= total/k: ave_max = total/k ele_list = num_list[start_num:start_num+k] print("最大平均值:%f 元素为:%s"%(ave_max,ele_list))
fruit = 'Banana' fruit[0] = 'b' # This gives an error as you can't change a string new_fruit = fruit.upper() print new_fruit # You can create a new variable
# Import json import json # Create Data: Dictionary # If dictionary, data parsed will be dictionary data = '''{ "name" : "John", "phone" : { "type" : "international", "mobile" : "999" }, "email" : { "hide" : "yes" } }''' # Deserialization from string to internal structure (where you get back a dictionary) info = json.loads(data) # Access native dictionary print 'Name:', info["name"] print 'Hide:', info["email"]["hide"] # Create data list # If list, data parsed will be list input2 = '''[ { "id" : "001", "x" : "2", "name" : "Chuck" }, { "id" : "009", "x" : "7", "name" : "Chuck" } ]''' info2 = json.loads(input2) print 'User count:', len(info2) for item in info2: print 'Name', item['name'] print 'Id', item['id'] print 'Attribute', item['x']
n = 5 while n > 0: print n n -= 1 # n = n - 1 print 'Blastoff!' print n # Results # 5 --> print 5 then subtract 1 = 4 # 4 --> print 4 then subtract 1 = 3 # 3 # 2 # 1 --> print 1 then subtract 1 = 0 # Blastoff # 0 --> result of last subtraction # Loops (repeated steps) have iteration variables, n # Iteration variable changes each time through a loop # Often go through a sequence of numbers
n = 6 while n > 0: n -= 1 # augmented assignment & iteration variable print(n) print('Blastoff!')
"""The class extends the class named Service and it manages the saving for the Amazon S3 service The class accepts a dict with the follow properties: 'force' (list): list of services identifier that they have to be forced for deleting 'timezone' (str): Timezone string name, default is Etc/GMT Here's an example: >>> import aws_saving.s3 as mainClass >>> arguments = {} >>> arguments['force'] = ['i-01234567890'] >>> arguments['timezone'] = ['Europe/Rome'] >>> saving = mainClass.S3(arguments) >>> saving.run(arguments) # license MIT # author Alessandra Bilardi <[email protected]> # see https://github.com/bilardi/aws-saving for details """ import boto3 from .service import Service class S3(Service): s3 = None s3r = None date_tuple = None def __init__(self, event): self.s3 = boto3.client('s3') self.s3r = boto3.resource('s3') Service.__init__(self, event) def get_instances(self): """ gets the s3 details Returns: A dictionary of the s3 instances details """ instances_list = self.s3.list_buckets() instances = [] for instance in instances_list['Buckets']: tag_list = self.s3.get_bucket_tagging(Bucket=instance['Name']) saving = self.get_value(tag_list['TagSet'], 'saving') if saving and saving.lower() == 'enabled': instance['DeletionProtection'] = True instance['Tags'] = tag_list['TagSet'] instances.append(instance) return instances def already_exists(self, name): """ checks if the bucket exists Args: name (string): the bucket name Returns: A boolean True if it exists """ try: if self.s3.head_bucket(Bucket=name): return True except: print('The bucket named ' + str(name) + ' not exists') return False def empty_bucket(self, name): """ empties the bucket before the deleting Args: name (string): the bucket name """ if self.already_exists(name): print('Deleting all objects of ' + name) bucket = self.s3r.Bucket(name) bucket.objects.all().delete() # bucket.delete() # only empty bucket def run(self, event): """ runs the schedulation Args: event (dictionary): aws details 'force' (list): list of services identifier that they have to be forced for deleting """ instances = self.get_instances() for instance in instances: print(instance['Name']) if self.is_time_to_act(instance['Tags'], 'delete'): if self.is_to_be_deleted(event, instance, 'Name', 'DeletionProtection', False): self.empty_bucket(instance['Name']) try: print('Deleting ' + instance['Name']) self.s3.delete_bucket(Bucket=instance['Name']) except: print('Warning: bucket named ' + instance['Name'] + ' is not empty, you have to force for deleting it') def main(event, context): saving = S3(event) saving.run(event) if __name__ == '__main__': main([], None)
""" Here we are calibrating IR sensors by doing some measurements, then finding a function that converts voltage (or, more precisely, the digitized voltage readings) into distance. Some boring math follows. The datasheet for the sensor suggests that distance is linearly related to a biased inverse voltage. In other terms, the following rational function should describe distance and voltage relationship: V = (alpha * d + beta) / (d + gamma) (1) or d = (beta - gamma * V) / (V - alpha) where V - sensor output (digitized voltage) d - distance between object and sensor alpha, beta, gamma - constants Since we have three unknown constants we need to take three measurements of voltage at (different) distances to solve for alpha, beta, gamma. Let V[i] i=0,1,2 be measurements corresponding to d[i] i=0,1,2. I choose d[0] = 3 (inches) d[1] = 6 (inches) d[2] = 12 (inches) Re-arranging eq. 1, we get: alpha * d + beta - gamma * V = d * V and substituting our measurements we get 3 linear equations: alpha * d[i] + beta * 1 - gamma * V[i] = d[i] * V[i], i=0,1,2 again, we are solving for unknown alpha, beta, and gamma. Same equation in matrix form is: M * (alpha, beta, gamma) = f where matrix M is given by: d[0] 1 -V[0] d[1] 1 -V[1] (2) d[2] 1 -V[2] and vector f is: f = (d[0]*V[0], d[1]*V[1], d[2]*V[2]) Solution can be found if we know inverse of M, Mn1: Mn1 * M = I (alpha, beta, gamma) = Mn1 * f Function fit(d, v) below performs all these manipulations to compute vector (alpha, beta, gamma) """ import numpy def fit(d, v): """ Given measurements d[i] and v[i] for i=0,1,2 computes coefficients alpha, beta, gamma such that v = (alpha * d + beta) / (d + gamma) or d = (beta - gamma * v) / (v - alpha) """ m = numpy.matrix([ [d[0], 1., -v[0]], [d[1], 1., -v[1]], [d[2], 1., -v[2]], ]) mn1 = numpy.linalg.inv(m) solution = numpy.dot(mn1, numpy.array([d[0]*v[0], d[1]*v[1], d[2]*v[2]])) return solution[0, 0], solution[0, 1], solution[0, 2] def distance(alpha, beta, gamma, v): """ Computes distance from voltage measurement Note that outside of the "good" voltage region distance formula may behave incorrectly, even reporting small or negative distances for very small voltages. Therefore we postulate that for voltages smaller than V* we just return arbitrarily large distance of 100inches. I will choose V* to be such that distance is 100inches when at the "good" side of the curve (approaching from large v) distance(v) = 100 v = (beta + 100 * alpha) / (100 + gamma) """ if v < (beta + 100 * alpha) / (100 + gamma): return 100 return (beta - gamma * v) / (v - alpha) if __name__ == '__main__': """ To calibrate IR sensors do the following: Put bot in the center of the room (far from obstacles). 1. Find a good "obstacle" (e.g. a book or a case). Use ruler to position this obstacle 3 inches from a sensor. Do the measurement of resulting voltage. 2. Repeat for all 5 sensors 3. Repeat again this time positioning an obstacle 6 inches away 3. And repeat last time, positioning an obstacle 12 inches away. """ ## each of total 5 sensors at 6in: v6 = [898, 862, 769, 989, 719] ## at 12in v12 = [469, 523, 382, 454, 302] ## at 24in v24 = [270, 346, 106, 188, 113] print 'IR_CALIBRATION=[' for sensor in range(5): print '\t', fit([6, 12, 24], [v6[sensor], v12[sensor], v24[sensor]]), ',' print ']' for sensor in range(5): alpha, beta, gamma = fit([6, 12, 24], [v6[sensor], v12[sensor], v24[sensor]]) dd = [] for vv in range(0, 4000): dd.append(distance(alpha, beta, gamma, vv)) import matplotlib.pyplot as plt plt.plot(dd) plt.show()
import os import math n = int(raw_input()) sm = 0 limit = n+1 a = [1 for i in range(0,limit)] a[0] = a[1] = 0 b = [0 for i in range(0,limit)] c = [0 for i in range(0,limit)] def sieve(): for i in range (2,int(math.sqrt(limit))+1): # print "i+"+str(i) for j in range(i*2,limit,i): # print "j+"+str(j) a[j] = 0 def isTruncatablePrime(prime): sp = str(prime) if(len(sp)==1): return False else: if(a[prime]!=1): return False else: #print "checking:"+ sp+":", for i in range(1,len(sp)): #print str(a[int(sp[i:])]) + ":" + str(a[int(sp[:-i])]) if(a[int(sp[i:])]!=1): return False if(a[int(sp[:-i])]!=1): return False #print "yes" return True def FindTruncatablePrimes(): i = 0 global sm for i in range(2,limit): if(isTruncatablePrime(i)): sm += i def sumTruncatablePrimes(): i = 0 c[0]=c[1]=0 for i in range(2,limit): c[i]=c[i-1] if(b[i]!=0): c[i]=c[i-1]+i sieve() FindTruncatablePrimes() # sumTruncatablePrimes() print sm
import os def OneString(num): num = int(num) ones = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine"] print ones[num-1], def TenString(num): num = int(num) tens = ["Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"] print tens[num-1], def OneTenString(num): num = int(num) oneTens = ["Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Ninteen"] print oneTens[num], def printDigits(num): num = int(num) if(num!=0): num = str(num) num = num.zfill(3) #print "num[0:1] is "+num[0:1] + "num is: "+num if(int(num[0:1])!=0): OneString(num[0:1]) print "Hundred", if(int(num[1:2])>=2): TenString(num[1:2]) if(int(num[2:3])!=0): OneString(num[2:3]) elif(int(num[1:2])==1): OneTenString(num[2:3]) else: OneString(num[2:3]) def billion(num): num = int(num) if(num!=0): printDigits(num) print "Billion", def million(num): num = int(num) if(num!=0): printDigits(num) print "Million", pass def thousand(num): num = int(num) if(num!=0): printDigits(num) print "Thousand", pass def hundred(num): num = int(num) if(num!=0): printDigits(num) pass t = int(raw_input()) while(t!=0): t=t-1 n = str(raw_input()) n = n.zfill(12) #print "after zfill:"+n billion(n[0:3]) million(n[3:6]) thousand(n[6:9]) hundred(n[9:12]) print ""
n = input() list = n.split(" ") countU=0 countL=0 for i in list: for j in i: if(j.isalpha()): if j.isupper(): countU+=1 else: countL+=1 print("UPPER CASE %d"%countU) print("LOWER CASE %d"%countL)
#Write a function that calculate factorial based on a positive integer input. 3! is 3 x 2 x 1 = 6. num = int(input("Enter a number for factorial calculation")) fact = 1 for i in range(1, num+1): fact *= i print("The factorial of" + ' ' + "{}".format(num) + ' ' + "is" + ' ' + "{}".format(fact))
# Here we generate the data in the form of linear regression (y = a*x + b) for the demonstration of gradient descent. import numpy as np from matplotlib import pyplot as plt from sklearn.utils import shuffle import pandas as pd # init w = 3 # y = b + wx b = 5 n = 1000 # n: number of data mean = 0 # add normal distribution noise sigma = 2 # creat data x = np.linspace(-5, 5, n) y = a*x + b + np.random.normal(mean, sigma, n) # y = np.array(y) data = np.concatenate((np.transpose([x]), np.transpose([y])), axis=1) # shuffle data data = shuffle(data) # save data df = pd.DataFrame(data) df.to_csv('data.csv')
city=input("enter your city: ") print("You live in " + city ) zip=input("enter your zip code: ") print("Your zip code is " + zip )
import numpy as np # for holding sub-arrays with maximum sum larray = [] larray_temp = [] rarray = [] rarray_temp = [] def max_sum_crossarray(arr, left, right, mid): ''' Function for getting the maximum sum of sub-array crossing the middle arr = find maximum sum and sub-array that produces that sum from this array left = the leftmost index of the arr right = the rightmost index of the arr mid = the middle index of the arr ''' ## the initial left_sum is a big negative value in case of getting a ## negative value as a result of the maximum sum for a sub-array left_sum = -1000000 sum = 0 # clear temporary left sub-array holder if larray_temp: larray_temp.clear() ## go leftward because it is a sub-array that crosses the middle ## elements must be analyzed outward from the middle for i in range(mid, left-1, -1): larray_temp.append(arr[i]) sum = sum + arr[i] if sum > left_sum: larray = larray_temp left_sum = sum ## the initial right_sum is a big negative value in case of getting a ## negative value as a result of the maximum sum for a sub-array right_sum = -1000000 sum = 0 # clear temporary right sub-array holder if rarray_temp: rarray_temp.clear() for i in range(mid+1, right+1): rarray_temp.append(arr[i]) sum = sum + arr[i] if sum > right_sum: rarray = rarray_temp right_sum = sum # return the sum of left and right because it has to be a combination of both return left_sum + right_sum, larray + rarray def max_sum_subarray(arr, left, right): ''' Function that returns the maximum sum and the sub-array that outputs the maximum sub-array. arr = find maximum sum and sub-array that produces that sum from this array left = the leftmost index of the arr right = the rightmost index of the arr ''' # base case: when there is only one element if left == right: base_arr = [] base_arr.append(arr[left]) return arr[left], base_arr middle = (left+right) // 2 # floor division # find the max in the subarray in the left part max_sum_leftarray = max_sum_subarray(arr, left, middle) # find the max in the subarray in the right part max_sum_rightarray = max_sum_subarray(arr, middle+1, right) # find the max in the subarray crossing the midpoint max_sum_middlearray = max_sum_crossarray(arr, left, right, middle) return max(max_sum_leftarray, max_sum_rightarray, max_sum_middlearray) def avg_over_n(n): ''' Function that takes the average maximum sum and the average length of the sub-array that produces the maximum sum over n iterations. Generates an random array of 100 integers in the range (-10,10) each iteration. n = number of iterations ''' tot_val = 0 tot_len = 0 for i in range(n): ar = np.random.random_integers(-10, 10, 100) res = max_sum_subarray(ar, 0, len(ar)-1) tot_val += res[0] tot_len += len(res[1]) avg_val = tot_val / n avg_len = tot_len / n return avg_val, avg_len print("AVG-100") print(avg_over_n(100)) def avg_over_n_with_diff_prob(n): ''' Function that takes the average maximum sum and the average length of the sub-array that produces the maximum sum over n iterations. Generates an random array of 100 integers with different probability distribution in each iteration. n = number of iterations ''' tot_val = 0 tot_len = 0 for i in range(n): final_arr = [] for j in range(n): happy_val = np.random.normal(6, 1, 1) sad_val = np.random.normal(-7, 0.5, 1) happy_sad = [happy_val[0], sad_val[0]] arr_val = np.random.choice(happy_sad, p=[0.5, 0.5]) final_arr.append(arr_val) res = max_sum_subarray(final_arr, 0, len(final_arr)-1) tot_val += res[0] tot_len += len(res[1]) avg_val = tot_val / n avg_len = tot_len / n return avg_val, avg_len print("AVG-100 WITH PROBABILITY DISTRIBUTION") print(avg_over_n_with_diff_prob(100))
# Importando a biblioteca tkinter e todos os seus modulos from tkinter import * # Criando a janela principal da aplicação através de classe Tk() # criando uma instância da classe Tk() janela = Tk() # Criando uma função para quando o 1° botão for clicado, # ele pegue o nome que foi digitado na caixa de texto através do método 'get' # e então substitua essa mensagem no nosso 'label' usando a propriedade 'text' def Muda_nome(): lb2['text'] = caixa_texto.get() # criando uma função para quando o 2° botão for clicado ele voltar # a exibir a primeira menssagem 'Seu nome aqui !' def Voltar(): lb2['text'] = 'Seu nome aqui !' # Label, atribuindo ele a janela principal, definindo a largura como 30px, # definindo o seu texto e definindo a fonte do texto lb = Label(janela, width=30, text='Digite o seu nome', font=('arial', 20, 'bold')) # Gerenciador de layout 'place', nos definimos as coordenadas do nosso label na janela # x: distância da margem esquerda para o centro # y: distância do topo da margem para o centro lb.place(x=-65, y=70) # Entrada de texto com o widget Entry, com largura de 20px caixa_texto = Entry(janela, width=20) caixa_texto.place(x=125, y=140) # criando um botão com o widget Button, atribuindo ele a janela principal, definindo a largura como 30px, # Button(janela, largura, altura, texto_exibido, cor_de_fundo, fonte(fonte, tamanho, estilo) , função_do_botão) btn1 = Button(janela, width=20, height=2, text='Clique aqui', bg='red', font=('arial', 10, 'bold'), command=Muda_nome) btn1.place(x=105, y=180) btn2 = Button(janela, width=20, height=2, text='Voltar', bg='green', font=('arial', 10, 'bold'), command=Voltar) btn2.place(x=105, y=250) lb2 = Label(janela, width=30, text='Seu nome aqui !', font=('arial', 20 , 'bold')) lb2.place(x=-65, y=330) # Definindo tamanho e posição da janela criada janela.geometry('400x400+400+150') # Largura x Altura + Distância da margem esquerda da tela + Distância em releção ao topo da tela # title() : Define o titulo da janela janela.title('Exemplo 1') # Método que faz com que a janela fique sendo exibida na tela janela.mainloop()
class Banco(): def __init__(self, nome, saldo=2000): self.nome = nome self.saldo = saldo def exibir_saldo(self): print(f'Seu Saldo atual: R${self.saldo}') def depositar(self, valor): self.saldo += valor self.exibir_saldo() def sacar(self, valor): self.saldo -= valor self.exibir_saldo() pass # Criar novo atributo conta aberta # criar método para exibir todas informações # implementar lógica da conta aberta/fechada nos outros métodos # Criar no app um programa básico usando poo
# It's prime sieve time! from math import sqrt, floor # the first one is something I wrote without doing research def first_primes(limit): """generates primes up to the given limit""" yield 2 for test_prime in range(3, limit + 1, 2): if is_prime(test_prime): yield test_prime def is_prime(number): """Checks if a number is prime""" if number <= 1: return False elif number < 4: return True elif number % 2 == 0: return False elif number < 9: return True elif number % 3 == 0: return False else: for test_num in range(5, int(floor(sqrt(number))) + 1, 6): if number % test_num == 0: return False if number % (test_num + 2) == 0: return False # return true if we didn't find any divisors return True # this works fairly quickly to get the right answer, # but is definitely not optimized print list(first_primes(1000000))[10000] # note this method would work better with a sieve of eratosthnes or counting # the primes on the way up
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ from math import floor, sqrt number = 13195 number_high = 600851475143 ############## Initial Solution ##################### def get_factors(n): # Returns all the factors of n top = floor(sqrt(n)) return [x for x in range(2, top + 1) if n % x==0] def is_prime(n): if len(get_factors(n)) == 0: return True else: return False def get_prime_factors(n): result = [] for factor in get_factors(n): if is_prime(factor): result.append(factor) return result def largest_prime_factor(n): return max(get_prime_factors(n)) ############# After reading PE solution ################ def reduce_factor(n, factor): # simple function to divide out all instances of a factor while n % factor == 0: n /= factor return n def largest_prime_factor_2(n): # function returns the largest prime factor by # dividing out all smaller factors completely first # First check if two is a factor and then divide out all twos if n % 2 == 0: lastfactor = 2 n = reduce_factor(n, 2) else: lastfactor = 1 # Next check from 3 and count upward by two factor = 3 maxfactor = sqrt(n) # factor can't be higher than the sqrt while n > 1 and factor <= maxfactor: if n % factor == 0: n /= factor lastfactor = factor n = reduce_factor(n, factor) maxfactor = sqrt(n) factor += 2 if n == 1: return lastfactor else: return n if __name__ == '__main__': print(largest_prime_factor_2(number_high))
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ high = 1000 def easy_solution(high): result = 0 for i in range(high): if i%3==0 or i%5==0: result += i return result print(easy_solution(high)) # The solution given py project euler def sum_divible_by(n): p = (high-1) // n return n * p * (p + 1) // 2 print(sum_divible_by(3) + sum_divible_by(5) - sum_divible_by(15))
from overlap import overlaped import random #Test overlaped function with integer random numbers print('Integer overlap test') #Generate a list of integer random numbers numbers = [random.randrange(1, 100, 1) for i in range(4)] #Pass the numbers of the list as parameters to the function overlaped result = overlaped(numbers[0], numbers[1], numbers[2], numbers[3]) #Print the result print('Is Overlaping? ', str(result)) #Test overlaped function with float random numbers print('Float overlap test') #Generate a list of float random numbers numbers = [random.random() for i in range(4)] #Pass the numbers of the list as parameters to the function overlaped result = overlaped(numbers[0], numbers[1], numbers[2], numbers[3]) #Print the result print('Is Overlaping? ', str(result))
""" Purpose of this is to find a target element in an already sorted list L. We use the fact that it is already sorted and get a O(log(n)) search algorithm. Programmed by Aladdin Persson <aladdin.persson at hotmail dot com> # 2019-03-12 Initial programming """ def binarysearch_iterative(L, target): low = 0 high = len(L) - 1 while low <= high: middle = (low + high) // 2 if target == L[middle]: return True, middle elif target < L[middle]: high = middle - 1 else: low = middle + 1 return False, None def binarysearch_recursive(L, target, low, high): middle = (low + high) // 2 if low > high: return False, None elif target == L[middle]: return True, middle elif target < L[middle]: return binarysearch_recursive(L, target, low, middle - 1) else: return binarysearch_recursive(L, target, middle + 1, high) if __name__ == "__main__": target = 1 sorted_array = [1, 1, 1, 1, 1, 1, 1, 1] exists, idx = binarysearch_iterative(sorted_array, target) print(f"The target {target} exists in array: {exists}. The idx of it is: {idx}") exists, idx = binarysearch_recursive(sorted_array, target, 0, len(sorted_array) - 1) print(f"The target {target} exists in array: {exists}. The idx of it is: {idx}")
""" # Purpose of the bisection method is to find an interval where there exists a root # Programmed by Aladdin Persson # 2019-10-07 Initial programming """ def function(x): # return (x**2 - 2) return x ** 2 + 2 * x - 1 def bisection(a0, b0, eps, delta, maxit): # Initialize search bracket s.t a <= b alpha = min(a0, b0) beta = max(a0, b0) a = [] b = [] fa = function(alpha) fb = function(beta) if function(alpha) * function(beta) > 0: print("Needs to have one f(a) > 0 and f(b) < 0") exit() for j in range(maxit): a.append(alpha) b.append(beta) # Carefully compute the midpoint in an effort to avoid numerical roundoff errors midpoint = alpha + (beta - alpha) / 2 fc = function(midpoint) # Check for small residual if abs(fc) <= eps: print("Very small function value -> we're close enough to a root") return alpha, beta # check for small bracket if abs(beta - alpha) <= delta: print("Interval is good enough --> We're close to root") return alpha, beta # Now we know we need to run more iterations if fa * fc < 0: beta = midpoint fb = fc else: alpha = midpoint fa = fc return alpha, beta def main(): a = 0 b = 1 # print(function(a)) # print(function(b)) alpha, beta = bisection(a, b, eps=1e-8, delta=1e-8, maxit=3) print("Bracket is (" + str(alpha) + ", " + str(beta) + ")") main()
""" Purpose is to sort a list. The reason why randomizing is better is that on average, regardless on the input randomized quicksort will have a running time of O(n*logn). This is regardless of the ordering of the inputted list. This is in constrast to first pivot, median pivot, etc Quicksort. Programmed by Aladdin Persson <Aladdin.persson at hotmail dot com> * 2019-03-08 Initial programming """ import random def quicksort_randomized(L): if len(L) <= 1: return L # Randomly choose a pivot idx pivot_idx = random.randint(0, len(L) - 1) pivot = L[pivot_idx] # Swap pivot_idx to the first position L[0], L[pivot_idx] = L[pivot_idx], L[0] i = 0 # range(1, len(L)) because we the pivot element is the first element for j in range(1, len(L)): if L[j] < pivot: L[j], L[i + 1] = L[i + 1], L[j] i += 1 L[0], L[i] = L[i], L[0] left = quicksort_randomized(L[:i]) right = quicksort_randomized(L[i + 1 :]) left.append(L[i]) result = left + right return result if __name__ == "__main__": l = [6, 7, 3, 4, 5, 1, 3, 7, 123] sorted_l = quicksort_randomized(l) print(sorted_l)
def merge_sort(array): total_inversions = 0 if len(array) <= 1: return (array, 0) midpoint = int(len(array) / 2) (left, left_inversions) = merge_sort(array[:midpoint]) (right, right_inversions) = merge_sort(array[midpoint:]) (merged_array, merge_inversions) = merge_and_count(left, right) return (merged_array, left_inversions + right_inversions + merge_inversions) def merge_and_count(left, right): count_inversions = 0 result = [] left_pointer = right_pointer = 0 left_len = len(left) right_len = len(right) while left_pointer < len(left) and right_pointer < len(right): if left[left_pointer] <= right[right_pointer]: result.append(left[left_pointer]) left_pointer += 1 elif right[right_pointer] < left[left_pointer]: count_inversions += left_len - left_pointer result.append(right[right_pointer]) right_pointer += 1 result.extend(left[left_pointer:]) result.extend(right[right_pointer:]) return (result, count_inversions) if __name__ == "__main__": array = [9, 2, 1, 5, 2, 3, 5, 1, 2, 32, 12, 11] print(array) result = merge_sort(array) print(result)
import random class Num_Guess(): attempts = 1 # def __init__(self): def accept_upper(self): upper = int(input('Enter the upper bound to start the game: ')) return upper def randnum_gen(self, upper): randnum = random.randint(1, upper) return randnum def accept_guess(self, upper): self.guess = int(input('Enter a value from 1 to {} including'.format(upper))) # print("guess is {}".format(self.guess)) return self.guess def guess_check(self, randnum, upper): print(self.guess) if self.guess == randnum: print("Perfect Guess and it took {} attempts".format(Num_Guess.attempts)) else: print("Wrong Guess!") Num_Guess.attempts += 1 self.accept_guess(upper) mynumguess = Num_Guess() upper = mynumguess.accept_upper() randnum = mynumguess.randnum_gen(upper) guess = mynumguess.accept_guess(upper) mynumguess.guess_check(randnum,upper)
def cubic(x): result = x * x * x return result def cubic2(x): y = 20 return x * x * x def adder (n1, n2): return n1+n2 def avg_three (n1,n2,n3): temp = n1+n2+n3 return temp/3.0 x = 100 value1 = cubic(3) value2 = cubic2(3) print "x -", x print "Value 1 - ", value1 print "value 2 - ", value2 print "added - ", adder(10,1) print "Avg 18, 23, 19 -", avg_three(18, 23, 19) print "Avg 34, 31, 128 -", avg_three(34, 31, 128)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Utilities function for stuff """ from datetime import datetime, timedelta import numpy as np def all_divisor(num): """ Return all the divisors of a number :param num: The number to find the divisors :return: A list of divisors """ divisor = list() for i in range(1, num+1): if num % i == 0: divisor.append(i) return divisor def normalize_nums(num, minimum, maximum): """ Normalize a positive integer between 0 and 1 :param num: The num to normalize :param minimum: The maximum range :param maximum: The minimum range :return: The normalized number """ nnum = 0 if num == 0: return nnum if num == np.nan: return nnum # if num >= 1 or num <= -1: # nnum = num / maxiumum # else: # nnum = num * (1 / maxiumum) nnum = (num - minimum) / (maximum - minimum) return nnum def normalize_date(date, starting_date, ending_date, date_format): """ Return the position of the date between the starting and ending as a percentage :param date: The date to format :param starting_date: The lower date boundary :param ending_date: The lower date boundary :param date_format: The date format to use :return: A float representing the positions between the date """ num_days = (datetime.strptime(ending_date, date_format) - datetime.strptime(starting_date, date_format)).days day = (datetime.strptime(date, date_format) - datetime.strptime(starting_date, date_format)).days return day / num_days def list_of_dates(starting_date, date_format, iteration): """ Return a list of string formatted date from the start to the end of the iteration :param starting_date: The lower date boundary :param date_format: The date format to use :param iteration: The number of date to count for :return: A list of string date formatted """ lod = [starting_date] sdate = datetime.strptime(starting_date, date_format) for i in range(1, iteration + 1): d = sdate + timedelta(days=i) lod.append(str(d.year) + str(d.month) + str(d.day)) return lod
#ROCK-PAPER-SCISSORS game import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' rps=int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors")) computer=random.randint(0,2) if rps==0 and computer==0: print(rock, end="\n") print("Computer chooses: ,\n"+rock) print("Draw") elif rps==0 and computer==1: print(rock, end="\n") print("Computer chooses: ,\n"+paper) print("You loose!") elif rps==0 and computer==2: print(rock, end="\n") print("Computer chooses: ,\n"+scissors) print("You win!") if rps==1 and computer==0: print(paper, end="\n") print("Computer chooses: ,\n"+rock) print("Win!") elif rps==1 and computer==1: print(paper, end="\n") print("Computer chooses: ,\n"+paper) print("Draw!") elif rps==1 and computer==2: print(paper, end="\n") print("Computer chooses: ,\n"+scissors) print("You lose!") if rps==2 and computer==0: print(scissors, end="\n") print("Computer chooses: ,\n"+rock) print("You lose!") elif rps==2 and computer==1: print(scissors, end="\n") print("Computer chooses: ,\n"+paper) print("You win!") elif rps==2 and computer==2: print(scissors, end="\n") print("Computer chooses: ,\n"+scissors) print("Draw!")
a = float(input("enter a no")) print (a) b = float(input("enter a no")) print (b) c=a*b print("result is"+str(c))
num=int(input("enter the limit")) i=1 sum=0 while(i<=num): sum=sum+i i=i+1 print(sum)
# -*- coding: utf-8 -*- class Accout(): ac_n=0; name=''; deposit=0 type=""; def CreateAccount(self): self.ac_no=int(input("Enter the account number:")) self.name=input("Enter your name:") self.type=input("enter the type of account you are making(C/S):") if(self.type=='C'): while(self.deposit<10000): self.deposit=int(input("Enter the amount you want to deposit(min 5000 for savings and 10000 for current):")) if(self.type=='S'): while(self.deposit<5000): self.deposit=int(input("Enter the amount you want to deposit(min 5000 for savings and 10000 for current):")) print("\n\n\nNew account created") def showaccount(self): print("Account number:",self.ac_no) print("Account Holder Name : ", self.name) print("Type of Account",self.type) print("Balance : ",self.deposit) def modifyaccount(self): print("Account number:",self.ac_no) self.name=input("Modify Account holder's name:") self.type=input("Modify account type:") def depositAmount(self,amount): self.deposit += amount def withdrawAmount(self,amount): self.deposit -= amount def report(self): print(self.ac_no, " ",self.name ," ",self.type," ", self.deposit) def getAccountNo(self): return self.ac_no def getAcccountHolderName(self): return self.name def getAccountType(self): return self.type def getDeposit(self): return self.deposit def intro(): print("\t\t\t\t***************************") print("\t\t\t\t Your favourite Goda bank") print("\t\t\t\t brought to you by Nabajyoti") print("\t\t\t\t***************************") print ("Press enter") input() def writeAccount(): account=Account() account.CreateAccount() writeAccountsFile(account) def displayAll(): with open("Accounts.txt","r") as file: lines=file.readlines() header=lines[0] field_names=header.strip().split(",") print(field_names) for row in lines[1:]: vals=row.strip().split(',') print("{};{};{};{}".format(vals[0],vals[1],vals[2],vals[3])) def displaySp(num): file=open("Accounts.txt","r") lines=file.readlines() found=0 for row in lines[1:]: vals=row.strip().split(',') if (vals[0]==num): found=1 print ("your bank deposit is :",vals[2]) file.close() if (found==0): print("No account exists with this number") ##hashu hashu def depositAndWithdraw(num1,num2): filename='Accounts.txt' tempfile=NamedTemporaryFile(mode='w',delete=False) fields=['Account_number','Name','Deposit','Type'] with open(filename,'r') as csvfile,tempfile: reader = csv.DictReader(csvfile, fieldnames=fields) writer = csv.DictWriter(tempfile, fieldnames=fields) for row in reader: if(row['Account_number']==num1): if(num2==1): amount = int(input("Enter the amount to deposit : ")) row['Deposit']+=amount print("your account has been UPDATED") elif num2==2: amount = int(input("Enter the amount to withdraw : ")) if amount <= row['Deposit'] : row['Deposit']-=amount else: print("ITNA PAISA NHI HAI!") row = {'Account_number': row['Account_number'], 'Name': row['Name'], 'Deposit': row['Deposit'], 'Type': row['Type']} writer.writerow(row) shutil.move(tempfile.name, filename) #start of the program ch='' num=0 intro() while ch!=8: print("\tMAIN MENU") print("\t1. NEW ACCOUNT") print("\t2. DEPOSIT AMOUNT") print("\t3. WITHDRAW AMOUNT") print("\t4. BALANCE ENQUIRY") print("\t5. ALL ACCOUNT HOLDER LIST") print("\t6. CLOSE AN ACCOUNT") print("\t7. MODIFY AN ACCOUNT") print("\t8. EXIT") print("\tSelect Your Option (1-8) ") ch = input() if ch == '1': writeAccount() elif ch =='2': num = int(input("\tEnter The account No. : ")) depositAndWithdraw(num, 1) elif ch == '3': num = int(input("\tEnter The account No. : ")) depositAndWithdraw(num, 2) elif ch == '4': num = int(input("\tEnter The account No. : ")) displaySp(num) elif ch == '5': displayAll(); elif ch == '6': num =int(input("\tEnter The account No. : ")) deleteAccount(num) elif ch == '7': num = int(input("\tEnter The account No. : ")) modifyAccount(num) elif ch == '8': print("\tThanks for using GODA bank") break else : print("Invalid choice") ch = input("Enter your choice : ")
class Game: def __init__(self, w, h): # makes a 2d list for the board self.board = [[True for j in range(w)] for i in range(h)] # remvoes one peg to start self.board[0][0] = False self.w = w self.h = h def __repr__(self): returnStr = "" for i in range(self.h): for j in range(self.w): if self.isOccupied((j, i)): returnStr += "X" else: returnStr += " " returnStr += "\n" return returnStr def go(self, (x, y), dir): # adds direction once for the kill position and twice for the move position killPos = addTuple((x, y), dir) movePos = addTuple(killPos, dir) if self.isOccupied((x, y)): if not self.isOccupied(movePos): if self.isValidPos(movePos): if self.isOccupied(killPos): self.removePeg((x, y)) self.removePeg(killPos) self.addPeg(movePos) def isValidPos(self, (x, y)): return all([x >= 0, y >= 0, x < self.w, y < self.h]) def isOccupied(self, (x, y)): return self.board[y][x] def addPeg(self, (x, y)): self.board[y][x] = True def removePeg(self, (x, y)): self.board[y][x] = False def addTuple((a1, a2), (b1, b2)): return (a1 + b1, a2 + b2) assert(addTuple((1,1),(1,1)) == (2,2)) class Dir: UP = (0,-1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) if __name__ == "__main__": # parameters epsilon = .1 # exploration num_actions = 3 # [move_left, stay, move_right] epoch = 1000 max_memory = 500 hidden_size = 100 batch_size = 50 grid_size = 10 model = Sequential() model.add(Dense(hidden_size, input_shape=(grid_size**2,), activation='relu')) model.add(Dense(hidden_size, activation='relu')) model.add(Dense(num_actions)) model.compile(sgd(lr=.2), "mse") # If you want to continue training from a previous model, just uncomment the line bellow # model.load_weights("model.h5") # Define environment/game env = Catch(grid_size) # Initialize experience replay object exp_replay = ExperienceReplay(max_memory=max_memory) # Train win_cnt = 0 for e in range(epoch): loss = 0. env.reset() game_over = False # get initial input input_t = env.observe() while not game_over: input_tm1 = input_t # get next action if np.random.rand() <= epsilon: action = np.random.randint(0, num_actions, size=1) else: q = model.predict(input_tm1) action = np.argmax(q[0]) # apply action, get rewards and new state input_t, reward, game_over = env.act(action) if reward == 1: win_cnt += 1 # store experience exp_replay.remember([input_tm1, action, reward, input_t], game_over) # adapt model inputs, targets = exp_replay.get_batch(model, batch_size=batch_size) loss += model.train_on_batch(inputs, targets)[0] print("Epoch {:03d}/999 | Loss {:.4f} | Win count {}".format(e, loss, win_cnt)) # Save trained model weights and architecture, this will be used by the visualization code model.save_weights("model.h5", overwrite=True) with open("model.json", "w") as outfile: json.dump(model.to_json(), outfile)
#imports here from game import game #from board import board #from tile import tile #from pieces import pieces #from deck import deck #from dice import dice if __name__ == "__main__": difficulties = ["easy", "medium", "hard"] MAX_PLAYERS = 4 numbers_of_players = [str(player) for player in range(1+1, MAX_PLAYERS+1)] print("_________________________________________________________________________________________________________________________") print("| __ _________ |") print("| / /\\ | /\\ |\\ | |") print("| | / \\ | / \\ | \\ | |") print("| | /____\\ | /____\\ | \\ | |") print("| \\__ / \\ | / \\ | \\| |") print("| |") print("‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾") #draw main screen #player number (fills out with ai) # - 2 to 4 total players # type number and press enter. check input print("What is your number of players?(2-4)") #need to do exception handling players = input() while not players in numbers_of_players: print("You must have made a mistake! Try again.") players = input() #offer difficulty selection # - easy, ai makes decision based on top 5 options, memory buffer of 1 round # - medium, ai makes decision based on top 3 options, memory buffer of 3 rounds # - hard, ai makes decision based on best option, memory buffer is all cards in hands # type selection and press enter. check input print("What is your difficulty?(easy, medium, hard)") #need to do exception handling diff = input().lower() while not diff in difficulties: print("You must have made a mistake! Try again.") diff = input().lower() #credits and tools used #press enter to continue or type rules for rulebook (can use browser to open webpage) #create game object and begin new_game = game(players, diff)
# Hashmap provides Insert and Delete in average constant time, although has problems with GetRandom. # Array List has indexes and could provide Insert and GetRandom in average constant time, though has problems with Delete. # To delete a value at arbitrary index takes linear time. The solution here is to always delete the last value: # * Swap the element to delete with the last one. # * Pop the last element out. from random import choice class RandomizedSet(): def __init__(self): """ Initialize your data structure here. """ self.dict = {} self.list = [] def insert(self, val: int) -> bool: """ Inserts a value to the set. Returns true if the set did not already contain the specified element. """ if val in self.dict: return False self.dict[val] = len(self.list) self.list.append(val) return True def remove(self, val: int) -> bool: """ Removes a value from the set. Returns true if the set contained the specified element. """ if val in self.dict: # move the last element to the place idx of the element to delete last_element, idx = self.list[-1], self.dict[val] self.list[idx], self.dict[last_element] = last_element, idx # delete the last element self.list.pop() del self.dict[val] return True return False def getRandom(self) -> int: """ Get a random element from the set. """ return choice(self.list) # import random # class RandomizedSet: # def __init__(self): # """ # Initialize your data structure here. # """ # self.random_set=[] # def insert(self, val: int) -> bool: # """ # Inserts a value to the set. Returns true if the set did not already contain the specified element. # """ # if val in self.random_set: # return False # else: # self.random_set.append(val) # return True # def remove(self, val: int) -> bool: # """ # Removes a value from the set. Returns true if the set contained the specified element. # """ # if val in self.random_set: # self.random_set.remove(val) # return True # else: # return False # def getRandom(self) -> int: # """ # Get a random element from the set. # """ # #print(self.random_set) # length = len(self.random_set) # #print('length',length) # rand_num = random.randint(0,length-1) # #print('rand_num',rand_num) # new_num = self.random_set[rand_num] # return new_num # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
#Approach 1: Annotate Parent #Intuition #If we know the parent of every node x, we know all nodes that are distance 1 from x. We can then perform a breadth first search from the target node to find the answer. #Algorithm #We first do a depth first search where we annotate every node with information about it's parent. #After, we do a breadth first search to find all nodes a distance K from the target. # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]: def dfs(node,par=None): if node: node.par = par dfs(node.left,node) dfs(node.right,node) dfs(root) q=deque() q.append([target,0]) res=[] seen={target} while q: curnode,level = q.popleft() if level==K: res.append(curnode.val) for nei in (curnode.left,curnode.right,curnode.par): if nei and nei not in seen: seen.add(nei) q.append([nei,level+1]) return res
class Solution: # time:O(log(n!)) # space:O(1) def binarysearch(self,matrix,target,s,v): lo =s hi = len(matrix[0])-1 if v else len(matrix)-1 while lo<=hi: mid = lo+(hi-lo)//2 if v: print('matrix[s][mid]',matrix[s][mid]) if matrix[s][mid] > target: hi = mid-1 elif matrix[s][mid] <target: lo =mid+1 else: return True else: print('matrix[mid][s]',matrix[mid][s]) print('s',s) if matrix[mid][s] > target: hi = mid-1 elif matrix[mid][s] <target: lo =mid+1 else: return True return False def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix: return False for i in range(min(len(matrix),len(matrix[0]))): res1 = self.binarysearch(matrix,target,i,True) res2 = self.binarysearch(matrix,target,i,False) if res1 or res2: return True return False # visit = [[0]*len(matrix[0]) for _ in range(len(matrix))] # def dfs(matrix,i,j,target): # if i<0 or j<0 or i>len(matrix)-1 or j>len(matrix[0])-1: # return False # if visit[i][j]==1: # return False # visit[i][j]=1 # if matrix[i][j]==target: # return True # if matrix[i][j]<target: # if dfs(matrix,i+1,j,target): # return True # if dfs(matrix,i,j+1,target): # return True # return False # return dfs(matrix,0,0,target)
class Solution: def trap(self, height: List[int]) -> int: # // 思考过程: # // brute force: for each bar, how much water the water can be saved above this bar # // Math.min(leftmost larger than cur bar, rightmost larger than current bar) - self height # // time: O(n^2) # // 想想怎么降低时间复杂度, 看哪个部分是重复操作的,浪费了时间?对每个bar,我们都需要反复的往左右看,找比他大的bar # // 如果我们可以记录一下每个bar左右比他大的bar是哪个就好了 # // 所以我们可以用两个array 分别记录左边大的bar,右边大的bar。这样,时间复杂度是O(n),空间复杂度是O(2n)-> O(n) # // 那现在来想想怎样才能降低空间复杂度呢 # // 不用array来记录左边和右边最大的分别是多少,用两个pointer从左从右分别traverse,一边记录当前最大是多少 # // 那我们就需要left, right两个pointer 和leftmax、rightmax两个variable # // 什么时候计算可以储存的水量呢?当leftmax < rightmax的时候,可以计算left上面储存的水量, right 同理 # // 因为 right-1max >= rightmax ====> leftrightmax >= rightmax 而leftmax <= rightmax so leftmax <= leftrightmax # // 我们可以确定储存在cur left上的水量是由leftmax决定的 l,r= 0,len(height)-1 leftmax,rightmax = 0,0 water = 0 while l<r: leftmax = max(leftmax,height[l]) rightmax = max(rightmax,height[r]) print('leftmax',leftmax) print('rightmax',rightmax) if leftmax < rightmax: water +=leftmax-height[l] l+=1 else: water+=rightmax -height[r] r-=1 return water # if len(height)<=1: # return 0 # water=0 # leftmax = [0]*len(height) # rightmax = [0]*len(height) # leftmax[0]=height[0] # rightmax[-1] =height[-1] # for i in range(1,len(height)): # leftmax[i] = max(height[i],leftmax[i-1]) # for i in range(len(height)-2,0,-1): # rightmax[i] = max(height[i],rightmax[i+1]) # for i in range(1,len(height)): # water += min(leftmax[i],rightmax[i])-height[i] # return water
def makeMove(obs, move, color): """ Args: obs (list): 1D array of the board move (int): 1D index that indicates where to place the piece color (int): -1 means black, 1 means white Returns: list: 1D array of the board """ obs = obs.copy() empty = 0 allie = color enemy = -color row, col = move//8, move%8 for horz in [-1, 0, 1]: for vert in [-1, 0, 1]: chk_row, chk_col = row+vert, col+horz flipping_pos = [] while (chk_row >= 0 and chk_col >= 0 and chk_row < 8 and chk_col < 8): chk_pos = 8*chk_row + chk_col if obs[chk_pos] == enemy: flipping_pos.append(chk_pos) elif obs[chk_pos] == allie: if flipping_pos != []: for p in flipping_pos: obs[p] = allie obs[move] = allie break elif obs[chk_pos] == empty: break chk_row += vert chk_col += horz return obs if __name__ == "__main__": test_board = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, -1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] # test_board = [ 0, 0, 1, -1, -1, -1, -1, -1, # -1, 0, 1, -1, -1, 1, 1, -1, # 1, -1, 1, -1, 1, -1, 1, -1, # 1, 1, -1, 1, -1, 1, 1, -1, # 1, 1, 1, -1, 1, -1, 1, -1, # 1, 1, -1, -1, 1, 1, 1, -1, # 1, -1, -1, 1, 1, 1, 1, -1, # 0, 0, 1, 1, 1, 1, 0, 0 ] test = makeMove(test_board, (8*0 + 0), 1) for i in range(8): for j in range(8): print(f"{test[8*i + j]:2}", end=" ") print("")
class Board: def __init__(self): self.gameOver = False self.winner = None self.numMoves = 0 self.currentPlayer = 'X' self.currentMove = "" self.coordinate1 = "" self.coordinate2 = "" self.board = [ [" ", " ", " ",], [" ", " ", " ",], [" ", " ", " " ] ] self.winCombos = ( # Horizontal ((0,0), (0,1), (0,2)), ((1,0), (1,1), (1,2)), ((2,0), (2,1), (2,2)), # Vertical ((0,0), (1,0), (2,0)), ((0,1), (1,1), (2,1)), ((0,2), (1,2), (2,2)), #Diagonal ((0,0), (1,1), (2,2)), ((0,2), (1,1), (2,0)) ) def checkGameOver(self): for combo in self.winCombos: space1 = self.board[combo[0][0]][combo[0][1]] space2 = self.board[combo[1][0]][combo[1][1]] space3 = self.board[combo[2][0]][combo[2][1]] if space1 == space2 == space3 == self.currentPlayer: # Avoid GameOver with 3 blank spaces self.winner = self.currentPlayer self.gameOver = True return if (self.numMoves == 9): # All spaces filled self.gameOver = True return def setCoordinates(self): # coordinates for self.Board self.currentMove.upper() self.coordinate1 = ord(self.currentMove[0])-1 self.coordinate2 = ord(self.currentMove[1])-17 if (self.coordinate1 < 0 or self.coordinate2 < 0): self.coordinate1 = "INVALID" self.coordinate2 = "INVALID" else: self.coordinate1 = int(chr(self.coordinate1)) self.coordinate2 = int(chr(self.coordinate2)) return def isValidMove(self): # checks valid coordinates if ((len(self.currentMove) != 2) or (str(self.coordinate1) not in "012") or (str(self.coordinate2) not in "012") or (self.board[self.coordinate1][self.coordinate2] != " ")): return False return True def switchPlayer(self): if (self.currentPlayer == 'X'): self.currentPlayer = 'O' return self.currentPlayer = 'X' return def placeMove(self): self.board[self.coordinate1][self.coordinate2] = self.currentPlayer self.numMoves += 1 return def drawBoard(self): switch = 1 print (" A B C ") for row in range(0,5): if (switch == 1): boardRow = int(row/2) print (str(boardRow + 1) + " " + self.board[boardRow][0] + "|" + self.board[boardRow][1] + "|" + self.board[boardRow][2] ) else: print (" -----") switch *= -1 return def startGame(self): self.drawBoard() print ("\n To play, enter the row followed by the column of any empty space.") while (not self.gameOver): print (" Current Player: " + self.currentPlayer) self.currentMove = input(" Enter your move: ") self.setCoordinates() if (self.isValidMove()): self.placeMove() self.drawBoard() self.checkGameOver() self.switchPlayer() else: print (" Invalid Move! Try again.") print (" " + self.winner + " wins!") return
(python_by_example)= # An Introductory Example ## Overview We\'re now ready to start learning the Python language itself. In this lecture, we will write and then pick apart small Python programs. The objective is to introduce you to basic Python syntax and data structures. Deeper concepts will be covered in later lectures. You should have read the {ref}`lecture <getting_started>` on getting started with Python before beginning this one. ## The Task: Plotting a White Noise Process Suppose we want to simulate and plot the white noise process $\epsilon_0, \epsilon_1, \ldots, \epsilon_T$, where each draw $\epsilon_t$ is independent standard normal. In other words, we want to generate figures that look something like this: ```{figure} /_static/lecture_specific/python_by_example/test_program_1_updated.png ``` (Here $t$ is on the horizontal axis and $\epsilon_t$ is on the vertical axis.) We\'ll do this in several different ways, each time learning something more about Python. We run the following command first, which helps ensure that plots appear in the notebook if you run it on your own machine. %matplotlib inline ## Version 1 (ourfirstprog)= Here are a few lines of code that perform the task we set import numpy as np import matplotlib.pyplot as plt ϵ_values = np.random.randn(100) plt.plot(ϵ_values) plt.show() Let\'s break this program down and see how it works. (import)= ### Imports The first two lines of the program import functionality from external code libraries. The first line imports NumPy, a favorite Python package for tasks like - working with arrays (vectors and matrices) - common mathematical functions like `cos` and `sqrt` - generating random numbers - linear algebra, etc. After `import numpy as np` we have access to these attributes via the syntax `np.attribute`. Here\'s two more examples np.sqrt(4) np.log(4) We could also use the following syntax: import numpy numpy.sqrt(4) But the former method (using the short name `np`) is convenient and more standard. #### Why So Many Imports? Python programs typically require several import statements. The reason is that the core language is deliberately kept small, so that it\'s easy to learn and maintain. When you want to do something interesting with Python, you almost always need to import additional functionality. #### Packages As stated above, NumPy is a Python *package*. Packages are used by developers to organize code they wish to share. In fact, a package is just a directory containing 1. files with Python code --- called **modules** in Python speak 2. possibly some compiled code that can be accessed by Python (e.g., functions compiled from C or FORTRAN code) 3. a file called `__init__.py` that specifies what will be executed when we type `import package_name` In fact, you can find and explore the directory for NumPy on your computer easily enough if you look around. On this machine, it\'s located in ```{code-block} none anaconda3/lib/python3.7/site-packages/numpy ``` #### Subpackages Consider the line `ϵ_values = np.random.randn(100)`. Here `np` refers to the package NumPy, while `random` is a **subpackage** of NumPy. Subpackages are just packages that are subdirectories of another package. ### Importing Names Directly Recall this code that we saw above import numpy as np np.sqrt(4) Here\'s another way to access NumPy\'s square root function from numpy import sqrt sqrt(4) This is also fine. The advantage is less typing if we use `sqrt` often in our code. The disadvantage is that, in a long program, these two lines might be separated by many other lines. Then it\'s harder for readers to know where `sqrt` came from, should they wish to. ### Random Draws Returning to our program that plots white noise, the remaining three lines after the import statements are ϵ_values = np.random.randn(100) plt.plot(ϵ_values) plt.show() The first line generates 100 (quasi) independent standard normals and stores them in `ϵ_values`. The next two lines genererate the plot. We can and will look at various ways to configure and improve this plot below. ## Alternative Implementations Let\'s try writing some alternative versions of {ref}`our first program <ourfirstprog>`, which plotted IID draws from the normal distribution. The programs below are less efficient than the original one, and hence somewhat artificial. But they do help us illustrate some important Python syntax and semantics in a familiar setting. ### A Version with a For Loop Here\'s a version that illustrates `for` loops and Python lists. (firstloopprog)= ts_length = 100 ϵ_values = [] # empty list for i in range(ts_length): e = np.random.randn() ϵ_values.append(e) plt.plot(ϵ_values) plt.show() In brief, - The first line sets the desired length of the time series. - The next line creates an empty *list* called `ϵ_values` that will store the $\epsilon_t$ values as we generate them. - The statement `# empty list` is a *comment*, and is ignored by Python\'s interpreter. - The next three lines are the `for` loop, which repeatedly draws a new random number $\epsilon_t$ and appends it to the end of the list `ϵ_values`. - The last two lines generate the plot and display it to the user. Let\'s study some parts of this program in more detail. (lists_ref)= ### Lists Consider the statement `ϵ_values = []`, which creates an empty list. Lists are a *native Python data structure* used to group a collection of objects. For example, try x = [10, 'foo', False] type(x) The first element of `x` is an [integer](https://en.wikipedia.org/wiki/Integer_%28computer_science%29), the next is a [string](https://en.wikipedia.org/wiki/String_%28computer_science%29), and the third is a [Boolean value](https://en.wikipedia.org/wiki/Boolean_data_type). When adding a value to a list, we can use the syntax `list_name.append(some_value)` x x.append(2.5) x Here `append()` is what\'s called a *method*, which is a function \"attached to\" an object---in this case, the list `x`. We\'ll learn all about methods later on, but just to give you some idea, - Python objects such as lists, strings, etc. all have methods that are used to manipulate the data contained in the object. - String objects have [string methods](https://docs.python.org/3/library/stdtypes.html#string-methods), list objects have [list methods](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists), etc. Another useful list method is `pop()` x x.pop() x Lists in Python are zero-based (as in C, Java or Go), so the first element is referenced by `x[0]` x[0] # first element of x x[1] # second element of x ### The For Loop Now let\'s consider the `for` loop from {ref}`the program above <firstloopprog>`, which was for i in range(ts_length): e = np.random.randn() ϵ_values.append(e) Python executes the two indented lines `ts_length` times before moving on. These two lines are called a `code block`, since they comprise the \"block\" of code that we are looping over. Unlike most other languages, Python knows the extent of the code block *only from indentation*. In our program, indentation decreases after line `ϵ_values.append(e)`, telling Python that this line marks the lower limit of the code block. More on indentation below---for now, let\'s look at another example of a `for` loop animals = ['dog', 'cat', 'bird'] for animal in animals: print("The plural of " + animal + " is " + animal + "s") This example helps to clarify how the `for` loop works: When we execute a loop of the form ```{code-block} --- class: no-execute --- for variable_name in sequence: <code block> ``` The Python interpreter performs the following: - For each element of the `sequence`, it \"binds\" the name `variable_name` to that element and then executes the code block. The `sequence` object can in fact be a very general object, as we\'ll see soon enough. ### A Comment on Indentation In discussing the `for` loop, we explained that the code blocks being looped over are delimited by indentation. In fact, in Python, **all** code blocks (i.e., those occurring inside loops, if clauses, function definitions, etc.) are delimited by indentation. Thus, unlike most other languages, whitespace in Python code affects the output of the program. Once you get used to it, this is a good thing: It - forces clean, consistent indentation, improving readability - removes clutter, such as the brackets or end statements used in other languages On the other hand, it takes a bit of care to get right, so please remember: - The line before the start of a code block always ends in a colon - `for i in range(10):` - `if x > y:` - `while x < 100:` - etc., etc. - All lines in a code block **must have the same amount of indentation**. - The Python standard is 4 spaces, and that\'s what you should use. ### While Loops The `for` loop is the most common technique for iteration in Python. But, for the purpose of illustration, let\'s modify {ref}`the program above <firstloopprog>` to use a `while` loop instead. (whileloopprog)= ts_length = 100 ϵ_values = [] i = 0 while i < ts_length: e = np.random.randn() ϵ_values.append(e) i = i + 1 plt.plot(ϵ_values) plt.show() Note that - the code block for the `while` loop is again delimited only by indentation - the statement `i = i + 1` can be replaced by `i += 1` ## Another Application Let\'s do one more application before we turn to exercises. In this application, we plot the balance of a bank account over time. There are no withdraws over the time period, the last date of which is denoted by $T$. The initial balance is $b_0$ and the interest rate is $r$. The balance updates from period $t$ to $t+1$ according to ```{math} :label: ilom b_{t+1} = (1 + r) b_t ``` In the code below, we generate and plot the sequence $b_0, b_1, \ldots, b_T$ generated by {eq}`ilom`. Instead of using a Python list to store this sequence, we will use a NumPy array. r = 0.025 # interest rate T = 50 # end date b = np.empty(T+1) # an empty NumPy array, to store all b_t b[0] = 10 # initial balance for t in range(T): b[t+1] = (1 + r) * b[t] plt.plot(b, label='bank balance') plt.legend() plt.show() The statement `b = np.empty(T+1)` allocates storage in memory for `T+1` (floating point) numbers. These numbers are filled in by the `for` loop. Allocating memory at the start is more efficient than using a Python list and `append`, since the latter must repeatedly ask for storage space from the operating system. Notice that we added a legend to the plot --- a feature you will be asked to use in the exercises. ## Exercises Now we turn to exercises. It is important that you complete them before continuing, since they present new concepts we will need. ### Exercise 1 Your first task is to simulate and plot the correlated time series $$ x_{t+1} = \alpha \, x_t + \epsilon_{t+1} \quad \text{where} \quad x_0 = 0 \quad \text{and} \quad t = 0,\ldots,T $$ The sequence of shocks $\{\epsilon_t\}$ is assumed to be IID and standard normal. In your solution, restrict your import statements to import numpy as np import matplotlib.pyplot as plt Set $T=200$ and $\alpha = 0.9$. ### Exercise 2 Starting with your solution to exercise 2, plot three simulated time series, one for each of the cases $\alpha=0$, $\alpha=0.8$ and $\alpha=0.98$. Use a `for` loop to step through the $\alpha$ values. If you can, add a legend, to help distinguish between the three time series. Hints: - If you call the `plot()` function multiple times before calling `show()`, all of the lines you produce will end up on the same figure. - For the legend, noted that the expression `'foo' + str(42)` evaluates to `'foo42'`. ### Exercise 3 Similar to the previous exercises, plot the time series $$ x_{t+1} = \alpha \, |x_t| + \epsilon_{t+1} \quad \text{where} \quad x_0 = 0 \quad \text{and} \quad t = 0,\ldots,T $$ Use $T=200$, $\alpha = 0.9$ and $\{\epsilon_t\}$ as before. Search online for a function that can be used to compute the absolute value $|x_t|$. ### Exercise 4 One important aspect of essentially all programming languages is branching and conditions. In Python, conditions are usually implemented with if--else syntax. Here\'s an example, that prints -1 for each negative number in an array and 1 for each nonnegative number numbers = [-9, 2.3, -11, 0] for x in numbers: if x < 0: print(-1) else: print(1) Now, write a new solution to Exercise 3 that does not use an existing function to compute the absolute value. Replace this existing function with an if--else condition. (pbe_ex3)= ### Exercise 5 Here\'s a harder exercise, that takes some thought and planning. The task is to compute an approximation to $\pi$ using [Monte Carlo](https://en.wikipedia.org/wiki/Monte_Carlo_method). Use no imports besides import numpy as np Your hints are as follows: - If $U$ is a bivariate uniform random variable on the unit square $(0, 1)^2$, then the probability that $U$ lies in a subset $B$ of $(0,1)^2$ is equal to the area of $B$. - If $U_1,\ldots,U_n$ are IID copies of $U$, then, as $n$ gets large, the fraction that falls in $B$, converges to the probability of landing in $B$. - For a circle, $area = \pi * radius^2$. ## Solutions ### Exercise 1 Here\'s one solution. α = 0.9 T = 200 x = np.empty(T+1) x[0] = 0 for t in range(T): x[t+1] = α * x[t] + np.random.randn() plt.plot(x) plt.show() ### Exercise 2 α_values = [0.0, 0.8, 0.98] T = 200 x = np.empty(T+1) for α in α_values: x[0] = 0 for t in range(T): x[t+1] = α * x[t] + np.random.randn() plt.plot(x, label=f'$\\alpha = {α}$') plt.legend() plt.show() ### Exercise 3 Here\'s one solution: α = 0.9 T = 200 x = np.empty(T+1) x[0] = 0 for t in range(T): x[t+1] = α * np.abs(x[t]) + np.random.randn() plt.plot(x) plt.show() ### Exercise 4 Here\'s one way: α = 0.9 T = 200 x = np.empty(T+1) x[0] = 0 for t in range(T): if x[t] < 0: abs_x = - x[t] else: abs_x = x[t] x[t+1] = α * abs_x + np.random.randn() plt.plot(x) plt.show() Here\'s a shorter way to write the same thing: α = 0.9 T = 200 x = np.empty(T+1) x[0] = 0 for t in range(T): abs_x = - x[t] if x[t] < 0 else x[t] x[t+1] = α * abs_x + np.random.randn() plt.plot(x) plt.show() ### Exercise 5 Consider the circle of diameter 1 embedded in the unit square. Let $A$ be its area and let $r=1/2$ be its radius. If we know $\pi$ then we can compute $A$ via $A = \pi r^2$. But here the point is to compute $\pi$, which we can do by $\pi = A / r^2$. Summary: If we can estimate the area of a circle with diameter 1, then dividing by $r^2 = (1/2)^2 = 1/4$ gives an estimate of $\pi$. We estimate the area by sampling bivariate uniforms and looking at the fraction that falls into the circle. n = 100000 count = 0 for i in range(n): u, v = np.random.uniform(), np.random.uniform() d = np.sqrt((u - 0.5)**2 + (v - 0.5)**2) if d < 0.5: count += 1 area_estimate = count / n print(area_estimate * 4) # dividing by radius**2
#! /usr/bin/env python import argparse import re import os parser = argparse.ArgumentParser(description="Text File to Csv File") # I&O file parser.add_argument('--input_file', dest="input_file", type=str, default="./data/data_statistic.txt", help="Data File") args = parser.parse_args() def txt_to_csv(input_file): dir_path = os.path.dirname(os.path.realpath(input_file)) output_path = os.path.join(dir_path, 'data_statistic.csv') data_list = list(open(input_file, 'r', encoding="utf-8").readlines()) f = open(output_path, 'w', encoding="utf-8") for line in data_list: line = line.split('\t') for word in line: f.write(word.strip() + ", ") f.write(+ "\n") def main(): txt_to_csv(args.input_file) if __name__ == '__main__': main()
from random import randint nmb = randint(0, 20000) nmb2 = 0 compteur = 0 while nmb != nmb2: compteur += 1 nmb2 = int(input("Ecrire un nombre")) if nmb2 > nmb: print("Trop Grand") elif nmb2 < nmb: print("Trop Petit") else: print("Gagné avec ", compteur, " coups")
import turtle from random import randint T = turtle.Turtle() for i in range(0,20): randomx = randint(-400,400) randomy = randint(-400,400) randomcircle = randint(0,75) T.penup() T.goto(randomx,randomy) T.pendown() T.circle(randomcircle) T.penup() T.goto(0,0)
def fact(n): f=1 while(n>0): f=f*n n-=1 print(f) x=int(input()) fact(x)
# Binary tree node. class Node: # Constructor for new binary tree Node. def __init__(self,key): self.key = key self.children = [] self.parents = [] def addChild(node,child): node.children.append(child) def addParent(node,parent): node.parents.append(parent) # findPath computes the path from the root to a node. def findPath(root,x,path): path.append(root) if x.key==root.key: return True for i in root.children: if findPath(i,x,path): return True # Remove root from tree if not present in subtree. path.pop() return False # findAncestors computers all the ancestors of a given node. def findAncestors(root,node,ancestors): ancestors.append(node.key) if(node.key==root.key): return for i in node.parents: findAncestors(root,i,ancestors) # findLCADAG is the approach that works for both non-binary trees and DAGs. def findLCADAG(root,node1,node2): if root is None: return False ancestors = [] ancestors2 = [] findAncestors(root,node1,ancestors) findAncestors(root,node2,ancestors2) for i in ancestors: for j in ancestors2: if i== j: return i # findLCA is the approach that works for non-binary trees, but it doesn't work for any graph where a node has more than one parent. def findLCA(root,node1,node2): if root is None: return False path1 = [] path2 = [] findPath(root,node1,path1) findPath(root,node2,path2) lca =0; for i in path1: for j in path2: #print("%d %d:",i.key,j.key) if i.key==j.key: lca = i.key return lca
while (True): str1=input("Enter the age: ") if not str1: break if (int(str1) >0 and int(str1) <=1): print ("Infant") elif (int(str1) >=1 and int(str1) < 18): print("Child") elif (int(str1) >=18 and int(str1) <= 60): print("Adult") else: print ("Senior citizen")
from pathlib import Path from PyPDF2 import PdfFileMerger current_path = Path.cwd() def pdf_pathes(): """ returns list of paths of file taken from input --> list """ file_names_input =input("Enter file names separated with spaces") file_names_list = file_names_input.split() files_paths = [] for name in file_names_list: files_paths.append(str(current_path / name)) return files_paths def merger(file_paths): """ args : paths of pdfs to be merged --> list returns None """ merger = PdfFileMerger() for path in file_paths : merger.append(path) merger.write(str(current_path / 'merged.pdf')) return merger.close() def main(): pdf_paths = pdf_pathes() merger(pdf_paths) print("Done Merging") return main()
# hari = ["senin", "selasa", "rabu" , "kamis", "jumat", "sabtu", "minggu" ] # counter = 0 # for i in hari: # print (i) # print ("=" *50) # while counter <7 : # print (hari[counter]) # counter += 1 # a = 2 # b = 2 # print(hari.index("sabtu")) # print(hari [a + b]) hari1 = ["senin", "selasa", "rabu" , "kamis", "jumat", "sabtu", "minggu" ] hari1.append("sunday") # Hari di tambahkan di paling terakhir print(hari1) hari1.insert(4, "Thursday") print(hari1) hari1[1] = "tuesday" print(hari1) hari1.remove("senin") print(hari1) # hari1.pop(0) # print(hari1) harienglish = list() harienglish.append(hari1[1]) harienglish.append(hari1[4]) harienglish.append(hari1[0]) harienglish.append(hari1) # ['kamis', 'sabtu', 'rabu', ['rabu', 'kamis', 'Thursday', 'jumat', 'sabtu', 'minggu', 'sunday']] = harienglish print(harienglish) print(harienglish[3][0]) harienglish.pop(3) print(harienglish) angka = [ 8, 9, 70, 89, 90, 86, 67, 123, 5] angkaterbesar = max(angka) angkasum = sum(angka) angkalowest = min(angka) urutangka = angka.sort() urutkebalik = angka.sort(reverse=True) print(angkaterbesar) # tupple listtup = 1, 2, 4, 6, 8, 9, 5, 765 print(type(listtup)) setdata = {} print(type(setdata)) #set setdata1 = set() print(type(setdata1)) setdat = [] print(type(setdat)) #Dictionary nilai = { "fabian" : 85, "budi" : 70, "rastra" : 90, } print(nilai["budi"]) print(type(nilai)) nilai.keys() #seluruh keys dictionary nilai.values() #seluruh value nilai.items() #seluruh gabungan nilai.pop("budi") #hapus data nilai["hutagalung"] = 90 # create or update data print(nilai.items()) # Function # def rumus1(contoh): # if contoh%2 == 0: # print("genap") # else: # print("ganjil") # rumus1(2) # return function def rumus1(contoh): if contoh%2 == 0: return "genap" else: return "ganjil" print(rumus1(2)) input = "budi septian" input1 = input.split(" ") print(input1)
import sys # Nomer 1 kata = input("Masukan kalimat yang ingin anda decode/encode (bila kode morse dipisahkan dengan | : ") kata = kata.lower() char = "abcdefghijklmnopqrstuvwxyz" morse = "._" def split(word): return [char for char in word] database = { "a" : ". _", "b" : "_ . . .", "c" : ". . .", "d" : "_ . .", "e" : ".", "f" : ". _ .", "g" : "_ _ .", "h" : ". . . .", "i" : ". .", "j" : "_ . _ .", "k" : "_ . _", "l" : "___", "m" : "_ _", "n" : "_ .", "o" : ". .", "p" : ". . . . .", "q" : ". . _ .", "r" : ". . .", "s" : ". . .", "t" : "_", "u" : ". . _", "v" : ". . . _", "w" : ". _ _", "x" : ". _ . .", "y" : ". . . .", "z" : ". . . .", " " : " " } def morsedecode (inputkata): value1 = list(database.values()) key1 = list(database.keys()) if (any((c in char) for c in inputkata)) and (any((c in morse) for c in inputkata)): print("\nInput yang anda masukan salah hanya bisa kata tau morse tidak bisa di gabung\n") sys.exit() elif (any((c in char) for c in inputkata)) and (any((c in morse) for c in inputkata) == False): pisah = split(inputkata) jumlahkat = len(pisah) print("Hasil decode/encode dari kalimat yang anda masukan adalah:\n") for i in range (0 , jumlahkat): print(database[pisah[i]], end="|") print() elif (any((c in morse) for c in inputkata)): inputkata1 = inputkata.split("|") jumlahkat = len(inputkata1) print("\nHasil decode/encode dari kalimat yang anda masukan adalah:") for i in range (0 , jumlahkat): kata1 = value1.index(inputkata1[i]) print(key1[kata1], end="") print() else: print("\ninput yang ada angka, hanya bisa memasukan kode morse atau kalimat\n") try: morsedecode(kata) except: print("Input yang anda masukan bukan kode morse")
# import sys # def rumus(input1): # a = 7 # hasil = input1 + 2 + a # return(hasil) # print(rumus(2)) # a = 10 # print(a) # print(rumus(a)) # def kuadrat(a): # x = a ** 2 # return x # print("="*50) # bubur = "banteng banget" # x = list() # symbol = "!@$%^&*" # bule = bubur.index("a") # test1 = bubur[0].isalpha() # test2 = bubur[0].isnumeric() # if test1 == False or test2 == False : # print("false") # # sys.exit() # print(bubur) # test2 = len(bubur) # print(test2) # print(bule) # print(type(bule)) # bubur1 = bubur.split(" ") # print(bubur1) # print(bubur1[0]) # my_string = "Where's Waldo?" # my_string.find("Waldo") # print(my_string.find("waldo")) #fungsi Lamda # fungsi yang biasa di pakai sekali # fungsi yg sifat nya khusus # tidak bernama # memiliki ukuran kecil # hanya memiliki 1 fungsi atau 1 ekspresion # tidak ada return value hasil12 = lambda x, y: x * y print(hasil12(4, 5)) print("="*50) hasil5 = lambda x: "angka genap" if x%2==0 else "angka ganjil" print(hasil5(4)) pangkat3 = lambda x: x**3 print("="*50) a = [5, 8, 15, 10] # MAP Function hasilmap = list(map(pangkat3, a)) print(hasilmap) kali = lambda x,y: x * y a1 = [25,15,10] b1 = [10,25,70] c1 = [3, 3, 3] kalian = list(map(kali, a1[0:2], b1[0:2])) print(kalian) triplet = lambda x, y ,z : x * y* z hasil30 = list(map(triplet, a1, b1, c1)) print(hasil30) print("="*50) # FILTER FUNCTION a2 = [1,2,3,4,5,6,7,8,9,10] hasil4 = list(filter(lambda x: x%2 == 0, a2)) print(hasil4) print("="*50) # REDUCE FUNCTION from functools import reduce print("ini nih") f = [1,2,3,4,5,6,7,8,9,10] hasil5 = reduce(lambda a, b: a + b, f) print(hasil5) print("="*50) # Latihan z = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # hasil4 = list(filter(lambda x: x%2 == 0, a2)) # pangkat3 = lambda x: x**3 hasilpangkat3 = list(map(lambda x: x**3, z)) print(hasilpangkat3) hasilatihan = list(filter(lambda x: x >= 1 and x <= 200,filter(lambda x: x%2 == 0, map(lambda x: x**3, z)))) print(hasilatihan)
# https://leetcode.com/problems/solving-questions-with-brainpower/description/ from typing import List class Solution: def mostPoints(self, questions: List[List[int]]) -> int: n = len(questions) dp = [0] * (n+1) for i in range(n-1, -1, -1): point = questions[i][0] jump = questions[i][1] next_question = min(n, i+jump+1) dp[i] = max(dp[i+1], point + dp[next_question]) return dp[0] questions = [[3, 2], [4, 3], [4, 4], [2, 5]] s = Solution() print(s.mostPoints(questions))
# https://leetcode.com/problems/uncrossed-lines/ from typing import List, Tuple class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: m, n = len(nums1), len(nums2) if n > m: return self.maxUncrossedLines(nums2, nums1) dp = [0] * (n + 1) for i in range(m): for j in range(n)[::-1]: if nums1[i] == nums2[j]: dp[j + 1] = dp[j] + 1 for j in range(n): dp[j + 1] = max(dp[j+1], dp[j]) return dp[n] s = Solution() # nums1 = [3, 1, 2, 1, 4, 1, 2, 2, 5, 3, 2, 1, 1, 4, 5, 2, 3, 2, 5, 5] # nums2 = [2, 4, 1, 2, 3, 4, 2, 4, 5, 5, 1, 1, 2, 1, 1, 1, 5, 4, 1, 4, 2, 1, 5, 4, 2, 3, 1, 5, 2, 1] nums1 = [1, 4, 2] nums2 = [1, 2, 4] print(s.maxUncrossedLines(nums1, nums2))
if __name__ == '__main__': for tc in range(1, int(input()) + 1): s = input() stack = [] for letter in s: if stack and letter == stack[-1]: stack.pop() else: stack.append(letter) print('#{} {}'.format(tc, len(stack)))
if __name__ == '__main__': for tc in range(1, int(input()) + 1): s = input() stack = [] brackets_dict = {'}': '{', ')': '('} flag = 1 for letter in s: if letter in brackets_dict.values(): stack.append(letter) if letter in brackets_dict.keys(): if not stack or brackets_dict[letter] != stack[-1]: flag = 0 break else: stack.pop() if stack: flag = 0 print('#{} {}'.format(tc, flag))
#Intro to JSON #Data Modeling in JSON #Objects may have different fields #May have nested Objects #May have nested Arrays #In Python #JSON Objects -> Dictionaries #Arrays -> Lists #JSON Playground #Web service is a database you can access using http requests # formulate queries as url's
import numpy as np def get_values(rosalind_file): """ Function that extracts the necessary data from .txt Rosalind file to convert to the following: n: number of vertical values m: number of horizontal values vert: Matrix of vertical values hori: Matrix of horizontal values """ # Read in file and assign n and m values f = open(rosalind_file, 'r') content = f.readline().split() n = int(content[0]) m = int(content[1]) values = [] for i in f: values.append(i) new_list = [] for i in values: new_list.append(i.strip()) # index of of the '-' that separates matrices dash = new_list.index('-') # Creation of two matrices x = [] y = [] for line in range(len(new_list)): if line < dash: x.append(values[line].split()) elif line > dash: y.append(values[line].split()) #Converting all values to integer data types vert = np.array(x) vert = vert.astype(int) hori = np.array(y) hori = hori.astype(int) return n, m, vert, hori def length_of_longest_path(n, m, vert, hori, arr): """ Takes in 5 parameters: n: number of vertical values m: number of horizontal values vert: Matrix of vertical values hori: Matrix of horizontal values arr: newly created 2D array that must be a n+1 * m+1! Calculates longest path for Manhattan Tourist Problem. To begin with, calculates the first row and column, then calculates the remaining values. """ # Get the values for the first vertical and horizonal lines for i in range(1,n+1): arr[i][0] = arr[i-1][0] + vert[i-1][0] for j in range(1, m+1): arr[0][j] = arr[0][j-1] + hori[0][j-1] # Get values of the remaining rows and columns for i in range(1, n+1): for j in range(1, m+1): if (arr[i-1][j] + vert[i-1][j]) > (arr[i][j-1] + hori[i][j-1]): arr[i][j] = arr[i-1][j] + vert[i-1][j] else: arr[i][j] = arr[i][j-1] + hori[i][j-1] def main(): file = 'manhat_tour.txt' n,m,vert,hori = get_values(file) # Creation of a n+1 * m+1 array using numpy arr = np.zeros((n+1, m+1)) length_of_longest_path(n, m, vert, hori, arr) # convert to int from float print(int(arr[n][m])) if __name__ == "__main__": main()
print("Введите элементы массива") try: array = [int(x) for x in input().split()] delta = int(input("Введите значение delta:")) except: print('Ошибка') else: a = min(array) + delta print ("Количество элементов массиве,отличающихся от минимального на delta = " + str(array.count(a)))
""" CSCI-141: Homework F: Top Baby Names Author: Sean Strout ([email protected]) Author: John Judge This program will find the top baby names for a range of years, based on a state and gender. It will also determine what name in that range occurred the most times in a row. This program, as a collection of modules, requires the rit_object module to be installed in the same location as the other source files. The rit_object module is located at: http://www.cs.rit.edu/~csci141/lib/rit_object_py.txt Language: Python 3 """ from rit_object import * # constants for file format def START_YEAR(): return 1910 def END_YEAR(): return 2013 def MALE(): return 'M' def FEMALE(): return 'F' class Name(rit_object): """ Represents a single top baby name. :slot name (str): The name, e.g. 'Mary' :slot gender (str): The gender, e.g. 'F' :slot year (int): The year, e.g. 1923 :slot state (str): The state, e.g. 'NY' :slot occurrences (int): The number of occurrences, e.g. 2429 """ __slots__ = ('name', 'gender', 'year', 'state', 'occurrences') _types = ( str, str, int, str, int ) def createName(fields): """ Initialize and return a new Name object. :param fields (list of str): A list of strings that represent one line in the file, [state, gender, year, name, occurrences], e.g. ['AK', 'M', '2004', 'Justin', '23'] :return: the new Name object :rtype: Name """ state = fields[0] gender = fields[1] year = int(fields[2]) name = fields[3] occurrences = int(fields[4]) return Name(name, gender, year, state, occurrences) def getTopNames(state, gender, startYear, endYear): """ Get the top names. :param state (str): The state, e.g. 'NY' :param gender (str): The gender, e.g. 'F' :param startYear (int): The starting year, e.g. 1969 :param endYear (int): The ending year, e.g. 2010 :return: The list of top Name objects :rtype: list """ nameObject = [] count = 0 with open(state + '.txt', encoding='utf-8') as infile: for line in infile: lst = line.split(',') if lst[1] == gender: if int(lst[2]) == startYear + count and int(lst[2]) < endYear + 1: count += 1 nameObject.append(createName(lst)) return nameObject def mostConsecutiveYears(names): """ Compute which name occurs the most times consecutively in a list of names. :param names (list of Name): A list of name objects :return: A tuple containing best name (str) and the count (int) :rtype: tuple """ nameList = [] for objects in names: nameList.append(objects.name) count = 0 topCount = 0 topName = nameList[0] Lname = nameList[0] for name in nameList: if name == Lname: count += 1 else: if count > topCount: topName = Lname topCount = count Lname = name count = 1 else: Lname = name count = 1 if count > topCount: topName = Lname topCount = count Lname = name count = 1 return (topName, topCount) def main(): """ The main function. :return None :rtype: None """ # prompt for all information state = input('Enter state: ').upper() gender = input('Enter gender: ').upper() startYear = int(input('Enter start year: ')) endYear = int(input('Enter end year: ')) # sanity check if startYear < START_YEAR(): print('Start year must be greater than or equal to', START_YEAR()) elif endYear > END_YEAR(): print('End year must be less than or equal to', END_YEAR()) elif startYear > endYear: print('Start year must be less than or equal to end year') else: # get/display the top names names = getTopNames(state, gender, startYear, endYear) print('Top', 'male' if gender == MALE() else 'female', 'names for', state, 'between', str(startYear) + '-' + str(endYear) + ': ') for n in names: print('\tIn', n.year, n.name, 'occurred the most at', n.occurrences, 'times') # next, get/display the most consecutively occurring name topName, topCount = mostConsecutiveYears(names) print(topName, 'occurred consecutively the most in this range at', topCount, 'time/s') if __name__ == '__main__': main()
""" Project: Unigrams Task: Letter Frequencies (Part One) This is a test program that students can use to verify that they are able to compute the correct letter frequencies using the unigram file 'very_short.csv'. Author: Sean Strout ([email protected]) Language: Python 3 """ import letterFreq # letterFreq import wordData # readFile, totalOccurrences import string # ascii_lowercase def testVeryShort(): WORD_OCCURRENCES = {'airport' : 348996, 'request' : 2816909, 'wandered' : 451106} LETTER_FREQ = [0.03104758705050717, 0.0, 0.0, 0.03500991824543893, 0.2536276129665047, 0.0, 0.0, 0.0, 0.013542627927787708, 0.0, 0.0, 0.0, 0.0, 0.017504959122719464, 0.013542627927787708, 0.013542627927787708, 0.10930884736053291, 0.15389906233882777, 0.10930884736053291, 0.12285147528832062, 0.10930884736053291, 0.0, 0.017504959122719464, 0.0, 0.0, 0.0] print('Testing with very_short.csv...') words = wordData.readWordFile('very_short.csv') # test totalOccurrences for word in words: print('Total occurrences of', word + ':', 'OK' if wordData.totalOccurrences(word, words) == WORD_OCCURRENCES[word] \ else 'GOT: ' + str(wordData.totalOccurrences(word, words)) + ', EXPECTED: ' + str(WORD_OCCURRENCES[word])) freqList = letterFreq.letterFreq(words) for ch, got, expected in zip(string.ascii_lowercase, freqList, LETTER_FREQ): print('Frequency of', ch + ':', 'OK' if got == expected else 'GOT: ' + str(got) + ', EXPECTED: ' + str(expected)) if __name__ == '__main__': testVeryShort()
#!/usr/local/bin/python3 """ File: testList.py Author: Sean Strout <[email protected]> Contributor: ben k steele <[email protected]> Language: Python 3 Description: A test module for the linked list data structure, MyList. """ # see main() for imports of the module. def testAppendAndToString( module ): print("Testing append and toString...", end=" ") lstA = module.createEmptyList() print( lstA.size == 0, end=' ') print( module.toString(lstA) == '[]', end=' ') module.append(lstA, 'a') print( lstA.size == 1, end=' ') print( module.toString(lstA) == '[a]', end=' ') module.append(lstA, 'b') print( module.toString(lstA) == '[a, b]', end=' ') print( lstA.size == 2, end=' ') module.append(lstA, 'c') print( module.toString(lstA) == '[a, b, c]', end=' ') print() def testClear( module ): print( "Testing clear...", end=" ") lstA = module.createEmptyList() module.clear(lstA) print( lstA.size == 0, end=' ') print( module.toString(lstA) == '[]', end=' ') print() def testInsert( module ): print( "Testing insert...", end=" ") lstA = module.createEmptyList() try: module.insertAt(lstA, -1, 'z') except IndexError: pass module.insertAt(lstA, 0, 'b') print( lstA.size == 1, end=' ') print( module.toString(lstA) == '[b]', end=' ') module.insertAt(lstA, 1, 'd') print( lstA.size == 2, end=' ') print( module.toString(lstA) == '[b, d]', end=' ') module.insertAt(lstA, 1, 'c') print( lstA.size == 3, end=' ') print( module.toString(lstA) == '[b, c, d]', end=' ') module.insertAt(lstA, 0, 'a') print( lstA.size == 4, end=' ') print( module.toString(lstA) == '[a, b, c, d]', end=' ') module.insertAt(lstA, 4, 'e') print( lstA.size == 5, end=' ') print( module.toString(lstA) == '[a, b, c, d, e]', end=' ') try: module.insertAt(lstA, 6, 'z') except IndexError: pass print() def testGet( module ): print( "Testing get...", end=" ") lstA = module.createEmptyList() try: module.get(lstA, 0) except: pass print( lstA.size == 0, end=' ') for ch in ['a','b','c','d']: module.append(lstA, ch) print( module.get(lstA, 0) == 'a', end=' ') print( module.get(lstA, 1) == 'b', end=' ') print( module.get(lstA, 2) == 'c', end=' ') print( module.get(lstA, 3) == 'd', end=' ') print( lstA.size == 4, end=' ') try: module.get(lstA, 4) except: pass print() def testSet( module ): print( "Testing set...", end=" ") lstA = module.createEmptyList() try: module.set(lstA, 0, 'z') except IndexError: pass module.append(lstA, 'a') module.set(lstA, 0, 'z') print( lstA.size == 1, end=' ') print( module.toString(lstA) == '[z]', end=' ') lstA = module.createEmptyList() for ch in ['a','b','c','d','e','f']: module.append(lstA, ch) module.set(lstA, 0, 'x') module.set(lstA, 2, 'y') module.set(lstA, 5, 'z') print( lstA.size == 6, end=' ') print( module.toString(lstA) == '[x, b, y, d, e, z]', end=' ') try: module.set(lstA, 6, 'z') except IndexError: pass print() def testPop( module ): print( "Testing pop...", end=" ") lstA = module.createEmptyList() try: module.pop(lstA, 0) except IndexError: pass module.append(lstA, 'a') print( module.pop(lstA, 0) == 'a', end=' ') print( lstA.size == 0, end=' ') for ch in ['a','b','c','d','e','f']: module.append(lstA, ch) print( module.pop(lstA, 0) == 'a', end=' ') print( lstA.size == 5, end=' ') print( module.toString(lstA) == '[b, c, d, e, f]', end=' ') print( module.pop(lstA, 1) == 'c', end=' ') print( lstA.size == 4, end=' ') print( module.toString(lstA) == '[b, d, e, f]', end=' ') print( module.pop(lstA, 3) == 'f', end=' ') print( lstA.size == 3, end=' ') print( module.toString(lstA) == '[b, d, e]', end=' ') try: module.pop(lstA, 3) except IndexError: pass print() def testIndex( module ): print( "Testing index...", end=" ") lstA = module.createEmptyList() try: module.index(lstA, 0) except: pass module.append(lstA, 'a') print( module.index(lstA, 'a') == 0, end=' ') print( lstA.size == 1, end=' ') for ch in ['b','c','d','a','b']: module.append(lstA, ch) print( module.index(lstA, 'a') == 0, end=' ') print( module.index(lstA, 'b') == 1, end=' ') print( module.index(lstA, 'c') == 2, end=' ') print( module.index(lstA, 'd') == 3, end=' ') print( lstA.size == 6, end=' ') try: module.index(lstA, 6) except: pass print() def testClone( module ): print( "Testing clone...", end=" ") lstA = module.createEmptyList() lstB = None try: lstB = module.clone( lstA ) except AttributeError as exp: print( exp, '\n\tOR\tclone function is not available.' ) return print( lstA.size == 0, end=' ' ) print( lstB.size == 0, end=' ' ) print( module.toString( lstA ) == '[]', end=' ' ) print( module.toString( lstB ) == '[]', end=' ' ) module.append( lstA, 'a' ) lstB = module.clone( lstA ) print( lstA.size == 1, end=' ' ) print( lstB.size == 1, end=' ' ) print( module.toString( lstA ) == '[a]', end=' ' ) print( module.toString( lstB ) == '[a]', end=' ' ) module.append( lstA, 'b' ) print( module.toString( lstA ) == '[a, b]', end=' ' ) print( module.toString( lstB ) == '[a]', end=' ' ) for ch in ['c','d','e','f']: module.append( lstA, ch ) lstB = module.clone( lstA ) print( lstA.size == 6, end=' ' ) print( lstB.size == 6, end=' ' ) print( module.toString( lstA ) == '[a, b, c, d, e, f]', end=' ' ) print( module.toString( lstB ) == '[a, b, c, d, e, f]', end=' ' ) module.remove( lstA, 'd' ) module.remove( lstB, 'f' ) print( module.toString( lstA ) == '[a, b, c, e, f]', end=' ' ) print( module.toString( lstB ) == '[a, b, c, d, e]', end=' ' ) print() def testExtend( module ): print( "Testing extend..." , end=" ") lstA = module.createEmptyList() lstB = module.createEmptyList() try: module.extend( lstA, lstB ) except AttributeError as exp: print( exp, '\n\tOR\textend function is not available.' ) return print( lstA.size == 0, end=' ' ) print( lstB.size == 0, end=' ' ) print( module.toString( lstA ) == '[]', end=' ' ) print( module.toString( lstB ) == '[]', end=' ' ) module.append( lstA, 'a' ) module.extend( lstA, lstB) print( lstA.size == 1, end=' ' ) print( lstB.size == 0, end=' ' ) print( module.toString( lstA ) == '[a]', end=' ' ) print( module.toString( lstB ) == '[]', end=' ' ) lstA = module.createEmptyList() module.append( lstB, 'a' ) module.extend( lstA, lstB) print( lstA.size == 1, end=' ' ) print( lstB.size == 1, end=' ' ) print( module.toString( lstA ) == '[a]', end=' ' ) print( module.toString( lstB ) == '[a]', end=' ' ) lstA = module.createEmptyList() lstB = module.createEmptyList() for ch in ['a','b','c','d']: module.append( lstA, ch) for ch in ['e','f','g']: module.append( lstB, ch) module.extend( lstA, lstB) print( lstA.size == 7, end=' ' ) print( lstB.size == 3, end=' ' ) print( module.toString( lstA ) == '[a, b, c, d, e, f, g]', end=' ' ) print( module.toString( lstB ) == '[e, f, g]', end=' ' ) module.remove( lstA, 'f' ) module.remove( lstB, 'e' ) print( lstA.size == 6, end=' ' ) print( lstB.size == 2, end=' ' ) print( module.toString( lstA ) == '[a, b, c, d, e, g]', end=' ' ) print( module.toString( lstB ) == '[f, g]', end=' ' ) print() def testRemove( module ): print("Testing remove...", end=" ") lstA = module.createEmptyList() try: module.remove(lstA, 'z') except AttributeError as exp: print( exp, '\n\tOR\tremove function is not available.' ) return except ValueError: pass module.append(lstA, 'a') module.remove(lstA, 'a') print(lstA.size == 0, end=' ') print(module.toString(lstA) == '[]', end=' ') module.append(lstA, 'a') module.append(lstA, 'a') module.remove(lstA, 'a') print(lstA.size == 1, end=' ') print(module.toString(lstA) == '[a]', end=' ') module.append(lstA, 'b') module.remove(lstA, 'b') print(lstA.size == 1, end=' ') print(module.toString(lstA) == '[a]', end=' ') for ch in ['a','b','c','d','a','b','c']: module.append(lstA, ch) module.remove(lstA, 'a') module.remove(lstA, 'c') module.remove(lstA, 'd') print(lstA.size == 5, end=' ') print(module.toString(lstA) == '[a, b, a, b, c]', end=' ') try: module.remove(lstA, 'z') except ValueError: pass print() def testCount( module ): print( "Testing count...", end=" ") lstA = module.createEmptyList() try: print( module.count( lstA, 'a' ) == 0, end=' ' ) except AttributeError as exp: print( exp, '\n\tOR\tcount function is not available.' ) return print( lstA.size == 0, end=' ' ) module.append( lstA, 'a' ) print( module.count( lstA, 'a' ) == 1, end=' ' ) print( lstA.size == 1, end=' ' ) module.append( lstA, 'b' ) print( module.count( lstA, 'b' ) == 1, end=' ' ) print( lstA.size == 2, end=' ' ) module.append( lstA, 'a' ) print( module.count( lstA, 'a' ) == 2, end=' ' ) print( lstA.size == 3, end=' ' ) print( module.count( lstA, 'z' ) == 0, end=' ' ) print( lstA.size == 3, end=' ' ) print() def testPyListToMyList( module ): print( "Testing pyListToMyList...", end=" ") try: print( module.toString(module.pyListToMyList([])) == '[]', end=' ') except AttributeError as exp: print( exp, '\n\tOR\tpyListToMyList function is not available.' ) return print( module.toString(module.pyListToMyList(['a'])) == '[a]', end=' ') print( module.toString(module.pyListToMyList(['a','b'])) == '[a, b]', end=' ') print( module.toString(module.pyListToMyList(['a','b','c','d'])) == '[a, b, c, d]', end=' ') print() def testMyListToPyList( module ): print( "Testing myListToPyList...", end=" ") lstA = module.createEmptyList() try: print( module.myListToPyList(lstA) == [], end=' ') except AttributeError as exp: print( exp, '\n\tOR\tmyListToPyList function is not available.' ) return module.append(lstA, 'a') print( module.myListToPyList(lstA) == ['a'], end=' ') module.append(lstA, 'b') print( module.myListToPyList(lstA) == ['a', 'b'], end=' ') for ch in ['c','d','e','f']: module.append(lstA, ch) print( module.myListToPyList(lstA) == ['a', 'b', 'c', 'd', 'e', 'f'], end=' ') print() def testCursor( module ): print( "Testing cursor functions: reset, hasNext, next...", end=" ") lstA = module.createEmptyList() module.reset(lstA) print( module.hasNext(lstA) == False, end=' ') try: module.next(lstA) except IndexError: pass module.append(lstA, 'a') module.reset(lstA) print( module.hasNext(lstA) == True, end=' ') print( module.next(lstA) == 'a', end=' ') print( module.hasNext(lstA) == False, end=' ') try: module.next(lstA) except IndexError: pass module.append(lstA, 'b') module.append(lstA, 'c') module.reset(lstA) module.next(lstA) module.pop(lstA, 1) print( module.hasNext(lstA) == False, end=' ') module.reset(lstA) module.pop(lstA, 0) print( module.hasNext(lstA) == False, end=' ') module.clear(lstA) for ch in ['a','b','c','d']: module.append(lstA, ch) module.reset(lstA) module.set(lstA, 0, 'x') print( module.next(lstA) == 'x', end=' ') print() def main(): """ main asks user to choose between tests using iterative and recursive linked list modules. """ modtype = input( "test iterative (i) or recursive (r) module: " ) if modtype.lower().strip() == "i": import myListIter listmodule = myListIter print( 'iter' ) elif modtype.lower().strip() == "r": import myListRec listmodule = myListRec print( 'rec' ) else: print( "Please enter 'i' or 'r' to test iterative/recursive library." ) return testAppendAndToString( listmodule ) testClear( listmodule ) testInsert( listmodule ) testGet( listmodule ) testSet( listmodule ) testPop( listmodule ) testIndex( listmodule ) testCursor( listmodule ) #testClone( listmodule ) #testExtend( listmodule ) testRemove( listmodule ) testCount( listmodule ) testPyListToMyList( listmodule ) testMyListToPyList( listmodule ) print() # main is the tester. if __name__ == "__main__": main()
#File: tower.py #Name: John J. #Description: This program solves the Tower of Hanoi Puzzle in conjuction with tower_animate.py, rit_object.py, myNode.py, and myStack.py from tower_animate import * def DO_ANIMATION(): return True def solve(stacks, numDisks, original, other, final): """ Solve is a recursive function that solves the Tower of Hanoi puzzle. In this function "stacks" is the pegs in the physical Tower of Hanoi puzzle. The numDisks stands for the number of disks. """ nMoves = 0 if numDisks == 0: pass else: nMoves = solve(stacks, numDisks-1, original, final, other) temp = top(stacks[original]) stacks[final] = push(stacks[final], temp) stacks[original] = pop(stacks[original]) animate_move(stacks, original, final) nMoves += 1 nMoves += solve(stacks, numDisks-1, other, original, final) return nMoves def movePile(stackContents, fromPile, toPile): """ The movePile function is responsible for actauly moving the disks from the three different stacks. This is done by pop() the top disk from each stack and putting it on a new stack. """ if stackContents[fromPile].data > stackContents[toPile].data: stackContents[toPile] = push(stackContents[fromPile].datastackContents[toPile]) stackContents[fromPile] = pop(stackContents[fromPile]) else: raise('Cannot place disk on one that is larger than it.') return stackContents def init_puzzle(disks): """ The init_puzzle function initializes the pegs by first establishing there is now disks on any of the pegs and then it will put however many disks the user prompts the computer to put on the starting peg. """ return_list = [None, None, None] while disks > 0: return_list[0] = push(return_list[0], disks) disks -= 1 return return_list def main(): disks = int(input('How high a tower to start with: ')) if disks < 1: raise ValueError('Disks must be greater than 0') if DO_ANIMATION(): animate_init(disks) towers_list = init_puzzle(disks) moves = solve(towers_list, disks, 0, 1, 2) print('The tower of Hanoi puzzle with ', disks, " disks is solved in ", moves, " moves.") input("Press enter to quit") if DO_ANIMATION(): animate_finish() main()
""" file: heapSort.py version: python3 author: Sean Strout author: John Judge purpose: Implementation of the heapsort algorithm, not in-place, (lst is unmodified and a new sorted one is returned) """ import heapq # mkHeap (for adding/removing from heap) import testSorts # run (for individual test run) def heapSort(lst): """ heapSort(List(Orderable)) -> List(Ordered) performs a heapsort on 'lst' returning a new sorted list Postcondition: the argument lst is not modified """ newlst = [] heap = [] i = 0 # use heapPush to push the item onto heap while (i<len(lst)): heapq.heappush(heap, lst[i]) i += 1 # use heapPop to pop the items off one by one into a new list (which is sorted) i = 0 while i < len(lst): newlst.append(heapq.heappop(heap)) i += 1 return newlst if __name__ == "__main__": testSorts.run('heapSort')
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:茁 # date:2019/5/6 import re string = 'The ghost that says boo haunts the loo.' word = re.findall('[bl]oo', string) print(word)
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:茁 # date:2019/4/24 class Horse: def __init__(self, name, gender, rider): self.name = name self.gender = gender self.rider = rider class Rider: def __init__(self, name): self.name = name person1 = Rider('LvBu') print(person1.name) horse1 = Horse('Red Rabbit', 'male', person1) print(horse1.rider.name)
#Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. #Hint: how does an even / odd number react differently when divided by 2? #Stretch goals: #- If the number is a multiple of 4, print out a different message. #- Ask the user for two numbers: one number to check (call it num) # and one number to divide by (check). If check divides evenly into num, # -tell that to the user. If not, print a different appropriate message. import math userNum = int(input("Please enter a Number dude: ")) if userNum%2 == 0: if userNum%4 == 0: print("It's even and divisible by 4 well done") else: print("At least it's even") else: print("An odd number. Better luck next time") print("\n Another silly number Game then.") num = int(input("\nEnter a new num: ")) check = int(input("\nAnd another: ")) if num%check == 0: print("Well done. You have guessed what this program is checking for." + " The former is divisible but the latter") else: print("Common man it was obviously going to divide the two")
""" HW 02 exercise 8, 9 & 10 """ __author__ = 'tiago' from matplotlib import pyplot as plt import numpy as np # import drawing as dr import random_things as rt # import run_hw02_regression as reg # from sklearn import linear_model class NoisyFunc: """ The function """ noise_prob = 0.10 @staticmethod def eval(x): if len(x.shape) == 1: x1 = x[0] x2 = x[1] else: x1 = x[:, 0] x2 = x[:, 1] _f = np.sign(x1*x1 + x2*x2 - 0.6) flip = np.random.binomial(1, NoisyFunc.noise_prob, len(_f)) _f[flip == True] *= -1 return _f def basic_fit(N=1000, M=10): """ Try to fit a regression line without transform. Fails: Err In Sample ~ 0.5 """ error_in = [] for i in range(M): points, f = rt.random_points(N, func=NoisyFunc) regr = linear_model.LinearRegression() regr.fit(points, f) # ## Error in-sample _g = f * regr.decision_function(points) e_in = len(_g[_g < 0]) error_in.append(e_in) error_in = np.mean(error_in) / N gfit = [regr.coef_[0], regr.coef_[1], regr.decision_function([0, 0])] return error_in, points, f, gfit def transform(points): ## Transform x1x2 = points[:, 0]*points[:, 1] x1x1 = points[:, 0]*points[:, 0] x2x2 = points[:, 1]*points[:, 1] points_t = np.transpose(np.array([points[:, 0], points[:, 1], x1x2, x1x1, x2x2])) return points_t def transform_fit(N=1000, M=10, _p=None): """ Use a non-linear transformation before the fit Transformation: 1, x1, x2, x1*x2, x1**2, x2**2 Results: E_out: 0.126216 Coeficients: -1.41235081e-03 -1.93377357e-03 4.67326156e-03 1.55868881e+00 1.55731603e+00 """ error_in = [] error_out = [] coefs = [] for i in range(M): points, f = rt.random_points(N, func=NoisyFunc) # ## Transform points_t = transform(points) regr = linear_model.LinearRegression() regr.fit(points_t, f) coefs.append(regr.coef_) # ## Error in-sample _g = f * regr.decision_function(points_t) e_in = len(_g[_g < 0]) error_in.append(e_in) # ## Err out-of-sample _out_points, _out_f = rt.random_points(1000, func=NoisyFunc) ## Transform _out_points = transform(_out_points) ## Evaluate _g = _out_f * regr.decision_function(_out_points) _g = _g[_g < 0] error_out.append(len(_g)) error_in = np.mean(error_in) / N error_out = np.mean(error_out) / N return error_in, points, f, coefs, error_out if __name__ == "__main__": N = 1000 M = 1000 # ## Basic fit # error_in, points, f, g_fit = basic_fit(N, M) # dr.draw_points(points, f) # dr.draw_line(g_fit, 'g-') # plt.show() # ## Transform and fit error_in, points, f, coefs, error_out = transform_fit(N, M) print ' Err In ', error_in, M, N print ' Eout: ', error_out coefs = np.mean(coefs, axis=0) print coefs
""" Several methods to generate random things. Shared among several exercises. """ __author__ = 'tiago' from __init__ import BOX_A, BOX_BA import numpy as np import math def random_line(): """ Generate a random line crossing the board. @return: w (vector), and px[], py[] """ px = BOX_BA * np.random .random_sample(2) + BOX_A py = BOX_BA * np.random.random_sample(2) + BOX_A # # Line as A * x + B * y + C = 0 _a = py[0] - py[1] _b = px[1] - px[0] _c = px[0]*py[1] - px[1]*py[0] return [_a, _b, _c], px, py def random_points(number_of_points, line=None, func=None): """ Throw some random points and evaluate whether they are above or below the given line If above RED, else BLUE @Return: points (numpy.array), solution (array) """ points = [] f = [] if line: for i in range(number_of_points): point = BOX_BA * np.random.random_sample(2) + BOX_A if not -1 < point[0] < 1 or not -1 < point[1] < 1: print ' ERROR WITH THE POINTS!!! ', point, BOX_BA, BOX_A points.append(point) _v_line = line[:2] f.append(math.copysign(1, np.dot(_v_line, point) + line[2])) points = np.array(points) elif func: points = BOX_BA * np.random.random_sample((number_of_points, 2)) + BOX_A f = func.eval(points) return points, f
# Define lista que funcionará como memória e suas operações MEMORY_SIZE = 4095 # memory allocation starts in 0 and goes to 65562 memory = [None for i in range(0, MEMORY_SIZE)] def read_byte(address): if(address < 0 or address > MEMORY_SIZE - 1): return "UNABLE TO ACCESS ADRESS" else: return memory[address] def print_byte(address): if(address < 0 or address > MEMORY_SIZE - 1): print("UNABLE TO ACCESS ADRESS") else: print(memory[address]) def write_byte(value, address): if(address < 0 or address > MEMORY_SIZE - 1): print("UNABLE TO ACCESS ADRESS") elif(value > 0xff): print("THE VALUE IS BIGGER THAN A BYTE") else: memory[address] = hex(value) def read_word(address): if(address < 0 or address > MEMORY_SIZE - 2): return "UNABLE TO ACCESS ADRESS" elif(str(memory[address + 1]) == "None"): # Concatena dois bytes, porém o segundo é None return (str(memory[address]) + str(memory[address + 1])) else: # Concatena dois bytes return (str(memory[address]) + str(memory[address + 1])[2:]) def print_word(address): if(address < 0 or address > MEMORY_SIZE - 2): print("UNABLE TO ACCESS ADRESS") elif(str(memory[address + 1]) == "None"): # Concatena dois bytes, porém o segundo é None print(str(memory[address]) + str(memory[address + 1])) else: # Concatena dois bytes print(str(memory[address]) + str(memory[address + 1])[2:]) def write_word(value, address): if(address < 0 or address > MEMORY_SIZE - 2): return "UNABLE TO ACCESS ADDRESS" else: if(value < 0x100): # Se o byte mais significativo é 0x00 memory[address] = hex(0x00) memory[address + 1] = hex(value) elif(value < 0x1000): # Se o byte mais significativo tem primeiro digito hex 0 memory[address] = hex(int("0" + str(hex(value))[2])) memory[address + 1] = hex(int(str(hex(value))[3] + str(hex(value))[4], 16)) elif(value > 0xffff): print("THE VALUE IS BIGGER THAN A WORD") return 0 else: memory[address] = hex( int(str(hex(value))[2] + str(hex(value))[3], 16)) memory[address + 1] = hex(int(str(hex(value))[4] + str(hex(value))[5], 16))
# TO-DO: complete the helpe function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) print(f"merge({arrA}, {arrB})") print("elements", elements) merged_arr = [0] * elements print(f"merged_arr: {merged_arr}") # TO-DO i = 0 j = 0 k = 0 for i in range(i, elements): print(f"arrA: {arrA}, arrB: {arrB}") if j >= len(arrA): # arrA is exhausted merged_arr[i] = arrB[k] k += 1 elif k >= len(arrB): # arrB is exhausted merged_arr[i] = arrA[j] j += 1 elif arrA[j] < arrB[k]: # arrA[j] is smaller merged_arr[i] = arrA[j] j += 1 print(f"j: {j}") elif arrB[k] < arrA[j]: # arrB[k] is smaller merged_arr[i] = arrB[k] print(f"{k}") k += 1 # loop thru elements # compare arrA values to arrB values to find smallest # replace value on merged arr? why not push onto empty arr? # use incremental variables to track array indices # i for merged arr # j and k for arrs # j++ or k++ respectively when value IS smaller return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO # if length is > 1 # split using [mid:] = rhs and [:mid] = lhs # mid = length/2 if len(arr) > 1: mid = int(len(arr)/2) # call recursively to split lhs = merge_sort(arr[:mid]) rhs = merge_sort(arr[mid:]) # call merge(lhs,rhs) arr = merge(lhs, rhs) # else: return arr print(merge_sort([0, 1, 5, 7, 3, 8])) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr
# adapted from SVM from Scratch in Python by Madhu Sanjeevi # https://medium.com/deep-math-machine-learning-ai/chapter-3-1-svm-from-scratch-in-python-86f93f853dc from matplotlib import pyplot as plt from sklearn.datasets.samples_generator import make_blobs import math import numpy as np def SVM_Training(data_dict, max_feature_value, min_feature_value, learning_rate): i = 1 global w global b # { ||w|| : [w, b] } length_Wvector = {} transforms = [[1, 1], [-1, 1], [-1, -1], [1, -1]] b_step_size = 2 b_multiple = 5 w_optimum = max_feature_value * 0.5 for lrate in learning_rate: w = np.array([w_optimum, w_optimum]) optimized = False while not optimized: # b = [-maxvalue to maxvalue] we want to maximize the b values so check for every b value for b in np.arange(-1 * (max_feature_value * b_step_size), max_feature_value * b_step_size, lrate * b_multiple): # transforms = [[1, 1], [-1, 1], [-1, -1], [1, -1]] for transformation in transforms: w_t = w * transformation correctly_classified = True # every data point should be correct for yi in data_dict: for xi in data_dict[yi]: # we want yi * (np.dot(w_t, xi) + b) >= 1 for correct classification if yi * (np.dot(w_t, xi) + b) < 1: correctly_classified = False if correctly_classified: # store w, b for minimum magnitude length_Wvector[np.linalg.norm(w_t)] = [w_t, b] if w[0] < 0: optimized = True else: w = w - lrate norms = sorted([n for n in length_Wvector]) minimum_wlength = length_Wvector[norms[0]] w = minimum_wlength[0] b = minimum_wlength[1] w_optimum = w[0] + lrate * 2 def visualize(data_dict, max_feature_value, min_feature_value, X1, y, ax): # [[ax.scatter(x[0], x[1], s=100, color=colors[i]) for x in data_dict[i]] for i in data_dict] plt.scatter(X1[:,1], X1[:,2], marker='o', c=y) # hyperplane = x . w + b # v = x . w + b # psv = 1 # nsv = -1 # dec = 0 def hyperplane_value(x, w, b, v): return (-w[0] * x - b + v) / w[1] datarange = (min_feature_value * 0.9, max_feature_value * 1.0) hyp_x_min = datarange[0] hyp_x_max = datarange[1] # (w . x + b) = 1 # positive support vector hyperplane psv1 = hyperplane_value(hyp_x_min, w, b, 1) psv2 = hyperplane_value(hyp_x_max, w, b, 1) ax.plot([hyp_x_min, hyp_x_max], [psv1, psv2], 'k') # (w . x + b) = -1 # negative support vector hyperplane nsv1 = hyperplane_value(hyp_x_min, w, b, -1) nsv2 = hyperplane_value(hyp_x_max, w, b, -1) ax.plot([hyp_x_min, hyp_x_max], [nsv1, nsv2], 'k') # (w . x + b) = 0 # positive support vector hyperplane db1 = hyperplane_value(hyp_x_min, w, b, 0) db2 = hyperplane_value(hyp_x_max, w, b, 0) ax.plot([hyp_x_min, hyp_x_max], [db1, db2], 'y--') plt.axis([-5, 10, -12, -1]) plt.show() def predict(features): # sign(x . w + b) dot_result = np.sign(np.dot(np.array(features), w) + b) return dot_result.astype(int) def main(): np.random.seed(1) (X, y) = make_blobs(n_samples=50, n_features=2, centers=2, cluster_std=1.05, random_state=40) # need to add 1 to X values (can say its bias) X1 = np.c_[np.ones((X.shape[0])), X] plt.scatter(X1[:,1], X1[:,2], marker='o', c=y) plt.axis([-5, 10, -12, -1]) plt.show() positiveX = [] negativeX = [] for i, v in enumerate(y): if v == 0: negativeX.append(X[i]) else: positiveX.append(X[i]) # data dictionary data_dict = {-1: np.array(negativeX), 1: np.array(positiveX)} # all the required variables w = [] # weights 2 dimensional vector b = [] # bias max_feature_value = float('-inf') min_feature_value = float('+inf') for yi in data_dict: if np.amax(data_dict[yi]) > max_feature_value: max_feature_value = np.amax(data_dict[yi]) if np.amin(data_dict[yi]) < min_feature_value: min_feature_value = np.amin(data_dict[yi]) learning_rate = [max_feature_value * 0.1, max_feature_value * 0.01, max_feature_value * 0.001] SVM_Training(data_dict, max_feature_value, min_feature_value, learning_rate) colors = {1: 'r', -1: 'b'} fig = plt.figure() ax = fig.add_subplot(1, 1, 1) visualize(data_dict, max_feature_value, min_feature_value, X1, y, ax) for i in X[:5]: print(predict(i)) l = [] for xi in X: l.append(predict(xi[:6])) l = np.array(l).astype(int) print(l) print(X[4]) for i, v in enumerate(y): if v == 0: y[i] = -1 print(y) error = sum((l - y) ** 2) print(error) if __name__ == '__main__': main()
class StackMin: def __init__(self): self.items = [] self.min = [] def push(self, data): if not len(self.min): self.min.append(data) elif data <= self.min[-1]: self.min.append(data) self.items.append(data) def pop(self): if self.items == []: raise Exception('Stack empty') if self.peep() == self.min[-1]: self.min.pop() self.items.pop() def isEmpty(self): return self.items == [] def peep(self): if self.isEmpty(): raise Exception('Stack is empty') return self.items[len(self.items) - 1] def get_min(self): if self.isEmpty(): raise Exception('Stack is empty') return self.min[-1] # trying to implement a stack where I am going to inherit the original stack implementation and extend the way how the stack is treated if __name__ == "__main__": stack = StackMin() stack.push(5) stack.push(6) stack.push(4) stack.push(4) stack.push(5) stack.pop() stack.pop() stack.pop() stack.pop() stack.pop() print(stack.get_min())
from linkedListOwn import Node, LinkedList def partition(ll, x): before_head = before = Node(0) after_head = after = Node(0) itr = ll.head while itr: if itr.data < x: before.next = itr before = before.next else: after.next = itr after = after.next itr = itr.next # chain the 2 linked lists before.next = after_head.next return LinkedList(before_head.next) if __name__ == "__main__": ll = LinkedList() ll.insert_values([1,2,3,2,1,5]) ll.printNodes() partition(ll,2).printNodes()
from linkedListOwn import Node, LinkedList # this is for the case when we have access to every node def delete_middle_node(ll, node): itr = ll.head while itr.next: if itr.next.data == node.data: itr.next = itr.next.next return ll itr = itr.next # the official case when we have access to only the selected node def delete_middle_node_main(node): # we can not delete the last node if node.next == None: return 'last node can not be deleted' node.data = node.next.data node.next = node.next.next if __name__ == "__main__": ll = LinkedList() ll.insert_values(['a','b','c','d', 'e', 'f']) ll.printNodes() input_node = Node('c', 'd') delete_middle_node(ll, input_node).printNodes()
from linkedListOwn import Node, LinkedList def reverseLL(ll): itr = ll.head previous = Node(itr.data, None) if itr.next is None: return {'ll': LinkedList(previous), 'll_len': 1} ll_len = 1 while itr.next: temp = Node(itr.next.data, previous) previous = temp itr = itr.next ll_len += 1 return {'ll': LinkedList(temp), 'll_len': ll_len} def isPalindrome(ll): reversedLL = reverseLL(ll) itr1 = ll.head itr2 = reversedLL["ll"].head for _ in range(ceil(reversedLL["ll_len"]/2)): print(itr1.data, itr2.data) if itr1.data != itr2.data: print('not a palindrome') return itr1 = itr1.next itr2 = itr2.next print('is a palindrome') return if __name__ == "__main__": ll1 = LinkedList() ll1.insert_values(['g','e','g', 'f']) isPalindrome(ll1) print(3/2)
""" Tut by sentdex : https://www.youtube.com/watch?v=sZyAn2TW7GY and {} """ """ RegEx Identifiers: \d - any number \D - anything but a number \s - a space \S - anything But a space \w - any character \w - anything But a character . - any character except a newline \b - the whitespace around words \. - an actual period/dot RegEx Modifiers: {1,3} - a range of 1 to 3 ex \d{1-3} + - match 1 or more ? - match 0 or 1 * - match 0 or more $ - match the end of the str ^ - match the beginning of a str | - either or [] - character set / variance RegEx White Space characters: \n - newline \s - space \e - esacpe (rare) \f form feed \r - return Regexone.com tutorial abc… Letters 123… Digits \d Any Digit \D Any Non-digit character . Any Character - Wildcard -(letter, digit, whitespace, everything) \. Period [abc] Only a, b, or c [^abc] Not a, b, nor c [a-z] Characters a to z [0-9] Numbers 0 to 9 \w Any Alphanumeric character \W Any Non-alphanumeric character {m} m Repetitions {m,n} m to n Repetitions * Zero or more repetitions + One or more repetitions ? Optional character \s Any Whitespace \S Any Non-whitespace character ^…$ Starts and ends (…) Capture Group (a(bc)) Capture Sub-group (.*) Capture all (abc|def) Matches abc or def """ import re # Lets use a regular expression to match a date string. Ignore # the output since we are just testing if the regex matches. regex = r"([a-zA-Z]+) (\d+)" if re.search(regex, "June 24"): # Indeed, the expression "([a-zA-Z]+) (\d+)" matches the date string # If we want, we can use the MatchObject's start() and end() methods # to retrieve where the pattern matches in the input string, and the # group() method to get all the matches and captured groups. match = re.search(regex, "June 24") # This will print [0, 7), since it matches at the beginning and end of the # string print("Match at index %s, %s" % (match.start(), match.end())) # The groups contain the matched values. In particular: # match.group(0) always returns the fully matched string # match.group(1), match.group(2), ... will return the capture # groups in order from left to right in the input string # match.group() is equivalent to match.group(0) # So this will print "June 24" print("Full match: %s" % (match.group(0))) # So this will print "June" print("Month: %s" % (match.group(1))) # So this will print "24" print("Day: %s" % (match.group(2))) else: # If re.search() does not match, then None is returned print("The regex pattern does not match. :(")
# https://stackoverflow.com/questions/3211292/two-processes-reading-writing-to-the-same-file-python from threading import Thread import os import time import itertools def write_every_3_sec(): f = open('2.txt', 'a', os.O_NONBLOCK) abc = itertools.cycle('abcdefghijklmnopqrstuvwxyz') while True: char= abc.__next__() f.write(char) print('Writing:', char) f.flush() time.sleep(3) def read_every_5_sec(): f = open('2.txt', 'r', os.O_NONBLOCK) while True: time.sleep(1) print('reading byte %s :' % f.tell(), f.read(2)) if __name__ == '__main__': Thread(target=write_every_3_sec).start() Thread(target=read_every_5_sec).start()
import numpy as np import tensorflow as tf from tensorflow import keras # Successive layers are defined in Sequence model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer='sgd', loss='mean_squared_error') X = np.array([-1, 0, 1, 2, 3, 4], dtype=np.int32) Y = np.array([-3,-1, 1, 3, 5, 7], dtype=np.int32) # Goes thorough the training loop 500 times model.fit(X, Y, epochs=500) print("for 10 output it " , model.predict([10]))
''' IF statement: ''' a,b=1,2 if a<5 and b>0 : print("yayy") # -> && should not be used anymore . if a==1 or b==1 : print("super") # -> || should not be used anymore if a in range(5) : print("cool") if b not in range(2) : print("not so cool") ''' The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". The else keyword catches anything which isn't caught by the preceding conditions. if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. the else block can be omitted and is not mandatory ''' a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") if a > b: print("a is greater than b") #if only one statement in if loop #Pass statement a = 33 b = 200 if b > a: pass ''' With the break statement we can stop the loop even if the while condition is true: With the continue statement we can stop the current iteration, and continue with the next: break leaves a loop, continue jumps to the next iteration. Note that range(6) is not the values of 0 to 6, but the values 0 to 5. however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6): ''' #continue i = 0 while i < 6: i += 1 if i == 3: continue print(i) #break i = 1 while i < 6: print(i) if i == 3: break i += 1 #range for x in range(2,6): print(x) #2,3,4,5 for x in range(6): print(x) #0,1,2,3,4,5
from matrix import Matrix from vector import Vector def main(): '''a = Matrix(2, 3) a.set_row(0, [1, 2, 3]) a.set_row(1, [3, 2, 1]) print("a: ", a.contents) b = Matrix(3, 2) b.set_col(0, [0, 1, 0]) b.set_col(1, [2, -1, 1]) print("b: ", b.contents) ab = a * b print("ab: ", ab.contents) ba = b * a print("ba: ", ba.contents) at = a.transpose() print("at: ", at.contents) bt = b.transpose() print("bt: ", bt.contents) i = Matrix.identity(3) print("i: ", i.contents) print("symmetric: ", i.symmetric()) print("upper triangular: ", i.upper_triangular()) print("lower triangular: ", i.lower_triangular())''' sys = Matrix(3, 3) sys.set_row(0, [2, 1, -1]) sys.set_row(1, [-3, -1, 2]) sys.set_row(2, [-2, 1, 2]) out = Vector(size=3, contents=[8, -11, -3]) eliminated, pivots = sys.reduce(out) print(eliminated) back_subbed = eliminated.back_sub() print(back_subbed) if __name__ == '__main__': main() # See PyCharm help at https://www.jetbrains.com/help/pycharm/
from main_day_11 import * def test_is_occupied(): # Given grid = [['#', '.'], ['#', '.']] # When Then assert is_occupied(grid, 0, 0) assert not is_occupied(grid, 0, 1) assert not is_occupied(grid, -1, -1) def test_count_adjacent_occupied(): # Given grid = [['#', '.'], ['#', '.']] # When Then assert count_adjacent_occupied(grid, 0, 0) == 1 assert count_adjacent_occupied(grid, 1, 0) == 1 assert count_adjacent_occupied(grid, 0, 1) == 2 assert count_adjacent_occupied(grid, 1, 1) == 2 def test_count_ajacent_occupied_test_input(): # Given grid = read_list_of_list('test_input.txt') grid = seat_all(grid) # When #Then assert count_adjacent_occupied(grid, 0, 0) == 2 assert count_adjacent_occupied(grid, 1, 0) == 3 assert count_adjacent_occupied(grid, 1, 1) == 6 assert count_adjacent_occupied(grid, 0, 1) == 5 assert count_adjacent_occupied(grid, 2, 2) == 6 def test_apply_one_unseat(): # Given grid = read_list_of_list('test_input.txt') # When grid = seat_all(grid) grid = apply_unseat(grid, unseat_first_star(grid)) grid = apply_seat(grid, seat_first_star(grid)) # Then assert True def test_play_first_star(): # Given grid = read_list_of_list('test_input.txt') # When n_seats_occupied = play_first_star(grid) # Then assert n_seats_occupied == 37 def test_count_sight_occupied(): # Given grid = [['#', '.'], ['#', '.']] # When Then assert count_sight_occupied(grid, 0, 1) == 2 assert count_sight_occupied(grid, 1, 1) == 2 def test_second_star_case_1(): # Given grid = read_list_of_list('test_input_2nd_star_1.txt') # When # Then assert count_sight_occupied(grid, 4, 3) == 8 def test_second_star_case_2(): # Give2 grid = read_list_of_list('test_input_2nd_star_2.txt') # When # Then assert count_sight_occupied(grid, 1, 1) == 0 def test_second_star_case_3(): # Give2 grid = read_list_of_list('test_input_2nd_star_3.txt') # When # Then assert count_sight_occupied(grid, 3, 3) == 0 def test_play_second_star(): # Given grid = read_list_of_list('test_input.txt') # When n_seats_occupied = play_second_star(grid) # Then assert n_seats_occupied == 26
while(True): inputStr = raw_input().split() n = int(inputStr[0]) k = int(inputStr[1]) chiken = n coupon = n while coupon >= k: chiken = chiken+1 coupon = coupon-k coupon = coupon+1 print chiken
#!/usr/bin/env python # encoding: utf-8 import itertools #------------------------------------------------------------------------------ # [ chain_iter method ] (iterable items of type contained in multiple list arguments) # Generator that returns iterable for each item in the multiple list arguments in sequence #------------------------------------------------------------------------------ def chain_iter(self, *lists): return itertools.chain(*lists) if __name__ == '__main__': pass
sal=int(input("enter ur salary")) initial=int(input("enter ur joining year")) final=int(input("enter ur current year")) bonus=(5/100)*sal year=final-initial if(year>=5): newsal=bonus+sal print(newsal) else: print("experience less than 5")
#what will be the output of this code? s=[4,5,6,7,8] res=s[-0]+s[-3] print(res)
# my_tuple=('p','e','f','s','o') # print(my_tuple[0]) # print(my_tuple[4]) #using keywords my_tuple=('a','p','p','l','e') print(my_tuple.count('p')) #2 print(my_tuple.index('p')) #3
def linear(): num=int(input("enter the number")) b=[1,5,8,6,9,7,23,4] for i in b: if i==num: #when using integer print("num is in list") linear()
#binary search;split elements with midterm then check less or greater a=[2,4,7,3,56,89,1,79,35,49,78] print(a) def bsearch(): a.sort() print(a) ele=int(input("enter the element")) flag=0 low=0 upp=len(a)-1 print(upp) while low<=upp: mid=(low+upp)//2 if ele>a[mid]: low=mid+1 elif ele<a[mid]: upp=mid-1 elif ele==a[mid]: flag=1 break if flag==1: print("found") else: print("not found") bsearch()
#program to calculate bmi(body mass index) of a person. body mass index is a simple #calculation using a person's height and weight.the formula is BMI=kg/m2 where kg is a #person's weight in kilograms and m2 is their height in meters squared. weight_in_kg=float(input("enter the weight in kg:")) height_in_meter=float(input("enter the height in meters:")) bmi=weight_in_kg/(height_in_meter*height_in_meter) print("BMI is :",bmi)
# arr=[2,3,4,5,6] # def square(num): # return num**2 # #map(function,iterable) # squarelist=list(map(square,arr)) # print(squarelist) arr=[2,3,4,5,6] squarelist=list(map(lambda num:num**2,arr)) print(squarelist) # lst=["ajay","arun","nikil","nivin"] # def to_upper(name): #print names in uppercase letters lst=["ajay","arun","nikil","nivin"] uppername=list(map(lambda name:name.upper(),lst)) print(uppername)
#x='[abc]' either a,b or c #x='[^abc]' except abc #x='[a-z]' a to z #x='[A-Z]' A to Z #x='[a-zA-Z]'both lower and upper case are checked #x='[0-9]' check digits # x='[^a-zA-ZO-9]'special symbols # x='\s' check space # x='\d' check the digits # x='\D' except digit # x='\w' all words except special characters # x='\W' for special characters # # # quantifiers # x='a+' a including group # x='a*' count including zero number of a # x='a?' count a as each including zero no of a # x='a{2}' 2 no of a position # x='a{2,3}' minimum 2 a and maximum 3 a # x='^a' check starting with a # x='a$' check ending with a
#create person class using constructor,use inheritance in constructor class Person: def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender def printval(self): print("name",self.name) print("age",self.age) print("gender",self.gender) class Student(Person): def __init__(self,rollno,mark,name,age,gender): super().__init__(name,age,gender) self.rollno=rollno self.mark=mark def print(self): print(self.rollno) print(self.mark) cr=Student(2,34,"anu",22,"female") cr.printval() cr.print()