blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
a6c0324efd7588288b83d3e541bce695aa8fafa2
easternpillar/AlgorithmTraining
/Programmers Level 1&2 완전 정복/신고 결과 받기.py
781
3.546875
4
# 링크: https://programmers.co.kr/learn/courses/30/lessons/92334?language=python3 # 문제 접근 # 1. 딕셔너리에 나를 신고한 사람의 이름을 담음 # 2. 딕셔너리 길이가 기준을 넘으면 딕셔너리 values에게 메일이 전송 # 3. 딕셔너리 value값은 중복되면 안되므로 set from collections import defaultdict def solution(id_list, report, k): answer = [] report_dict = defaultdict(set) cnt_dict = defaultdict(int) for re in report: a, b = re.split(" ") report_dict[b].add(a) for key in report_dict: if len(report_dict[key]) >= k: for value in report_dict[key]: cnt_dict[value] += 1 for id in id_list: answer.append(cnt_dict[id]) return answer
7961117c272b5935e03c6d61ae78c99632d9258d
jnguyen1991/Rosalind
/sset.py
658
3.625
4
# -*- coding: utf-8 -*- """ Created on Thu May 24 09:48:11 2018 @author: jnguyen3 """ def sset(n, output): for i in n: temp = n.copy() temp.remove(i) if temp not in output: output.append(temp) output.append(sset(temp, output)) def main(n): ''' Recursive solution, doesn't work well for large numbers ''' largest = set(range(1,n+1)) output = [] output.append(largest) output.append(sset(largest, output)) return len([x for x in output if x != None]) #print sset(lst) x = 827 #print main(x) print 2**x % 1000000 #or pow(2,x,1000000) for better efficiency
40d4aa7bfab318dac684558ad18adbe095f206ef
JohanGro/CSE
/DictionaryNotes.py
2,283
3.546875
4
states = { "CA": "California", "VA": "Virginia", "MD": "Maryland", "RI": "Rhode Island", "NV": "Nevada" } ''' print(states["CA"]) print(states["NV"]) ''' nested_dictionary = { "CA": { "NAME": "California", "POPULATION": 39557045 # 39,557,045 }, "VA": { "NAME": "Virginia", "POPULATION": 8517685 # 8,517,685 }, "MD": { "NAME": "Maryland", "POPULATION": 6042718 # 6,042,718 }, "RI": { "NAME": "Rhode Island", "POPULATION": 1057315 # 1,057,315 }, "NV": { "NAME": "Nevada", "POPULATION": 3034392 # 3,034,392 } } print(nested_dictionary["NV"]["POPULATION"]) print(nested_dictionary["RI"]["NAME"]) complex_dictionary = { "CA": { "NAME": "California", "POPULATION": 39557045, # 39,557,045 "CITIES": [ "Fresno", "San Fransisco", "Los Angeles" ] }, "VA": { "NAME": "Virginia", "POPULATION": 8517685, # 8,517,685 "CITIES": [ "Richmond", "Norfolk", "Alexandria" ] }, "MD": { "NAME": "Maryland", "POPULATION": 6042718, # 6,042,718 "CITIES": [ "Bethesda", "Annapolis", "Baltimore" ] }, "RI": { "NAME": "Rhode Island", "POPULATION": 1057315, # 1,057,315 "CITIES": [ "Providence", "Newport", "Warwick" ] }, "NV": { "NAME": "Nevada", "POPULATION": 3034392, # 3,034,392 "CITIES": [ "Carson City", "Las Vegas", "Reno" ] } } print(complex_dictionary["RI"]["CITIES"][2]) print(complex_dictionary["VA"]["NAME"]) print(complex_dictionary["MD"]["CITIES"][0]) print(complex_dictionary.keys()) print(nested_dictionary.items()) print() for key, value in complex_dictionary.items(): print(key) print(value) print("-" * 20) # were going to make it look great... for state, facts in complex_dictionary.items(): for attr, value in facts.items(): print(attr) print(value) print("-" * 20) print("=" * 20) states["AL"] = "Alabama"
7f362996aa4bd6fdd02d571c21ee41037c40bd78
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/web-dev-notes-resource-site/2-content/ciriculumn/week-17/python/my-intro-BG/2/Module3PersonalizedStorySolution.py
1,316
4.40625
4
# initialize the variables girldescription = " " boydescription = " " walkdescription = " " girlname = " " boyname = " " animal = " " gift = " " answer = " " # Ask the user to specify values for the variables girlname = input("Enter a girl's name: ") boyname = input("Enter a boy's name: ") animal = input("Name a type of animal: ") gift = input("Name something you find in the bathroom: ") girldescription = input("Enter a description of a flower: ") boydescription = input("Enter a description of a car: ") walkdescription = input("Enter a description of how you might dance: ") answer = input("What would you say to someone who gave you a cow: ") # Display the story # Don't forget to format the strings when they are displayed print("Once upon a time,") print("there was a girl named " + girlname.capitalize() + ".") print( "One day, " + girlname.capitalize() + " was walking " + walkdescription.lower() + " down the street." ) print( "Then she met a " + boydescription.lower() + " boy named " + boyname.capitalize() + "." ) print("He said, 'You are really " + girldescription.lower() + "!'") print("She said '" + answer.capitalize() + ", " + boyname.capitalize() + ".'") print( "Then they both rode away on a " + animal.lower() + " and lived happily ever after." )
edfba19244397e3c444e910b9650de1a855633b3
Allaye/Data-Structure-and-Algorithms
/Stacks/balancedParen.py
2,399
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from Stack import Stack # personal implementation of stack using python list # In[12]: def check_balance(string, opening='('): ''' a function to check if parenthesis used in a statement is balanced this solution used a custom implementation of a stack using python list. the below steps was used: a: check if the length of the string to be checked is even, if yes: c: loop through the string, if the any item there is == to the opening variable: d: push then into the stack, else: e: check if the length is not zero, if it is not pop the stack, else: f: return false: g: if we reach the end of the loop, return True if the size of the stack is zero else return False b: ''' s = Stack() if len(string) % 2 == 0: for w in string: if w == opening: s.push(w) else: if s.size() > 0: s.pop() else: return False return s.size() == 0 else: return False # In[2]: def double_balance(string, openings=['[', '{', '(']): ''' a function to check if the 3 types of parenthesis used in a statement is balanced this solution used a custom implementation of a stack using python list. the below steps was used: a: check if the length of the string to be checked is even, if yes: c: loop through the string, if the item matches openings: d: push then into the stack, else: e: check if the top element in the stack and item matches any tuple in our matches and pop the stack else: f: return false: g: if we reach the end of the loop, return True if the size of the stack is zero else return False b: return False since the parenthesis can only be balance if the have a corresponding closing one ''' s = Stack() matches = [('{', '}'), ('(', ')'), ('[', ']')] if len(string) % 2 == 0: for w in string: if w in openings: s.push(w) else: if (s.peek(), w) in matches: s.pop() else: return False return s.size() == 0 else: <<<<<<< HEAD return False ======= return False >>>>>>> 34dd19a4c05ecb4cd984fb078a578c1934859c39
9841e35ff7828069dd6e31617549104603a1cb8b
marcuschiriboga/RPS-se-q3-oct-2021-class
/RPS.py
400
4.09375
4
# https://realpython.com/python-rock-paper-scissors/ import random # pictures user_action = input("enter a choice (rock, paper, scissors): ") if user_action not in ["rock", "paper", "scissors"]: print("you chose poorly") quit() possible_actions = ["rock", "paper", "scissors"] computer_action = random.choice(possible_actions) print(f"\n human: {user_action} | computer: {computer_action}")
92984714b31d0371d71ecf1b5199079e4954a089
saetar/pyEuler
/not_done/py_not_started/euler_618.py
768
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # ~ Jesse Rubin ~ project Euler ~ """ Numbers with a given prime factor sum http://projecteuler.net/problem=618 Consider the numbers 15, 16 and 18: 15=3× 5 and 3+5=8. 16 = 2× 2× 2× 2 and 2+2+2+2=8. 18 = 2× 3× 3 and 2+3+3=8. 15, 16 and 18 are the only numbers that have 8 as sum of the prime factors (counted with multiplicity). We define S(k) to be the sum of all numbers n where the sum of the prime factors (with multiplicity) of n is k. Hence S(8) = 15+16+18 = 49. Other examples: S(1) = 0, S(2) = 2, S(3) = 3, S(5) = 5 + 6 = 11. The Fibonacci sequence is F_1 = 1, F_2 = 1, F_3 = 2, F_4 = 3, F_5 = 5, .... Find the last nine digits of ∑_k=2^24S(F_k). """ def p618(): pass if __name__ == '__main__': p618()
105ae8f9f679e7152364420c391995e6cd32d9a1
minus9d/python_exercise
/parallel_and_concurrent/multiprocessing_pool.py
208
3.59375
4
#!/usr/bin/python3 import multiprocessing def pow2(n): return n * n before = list(range(100000000)) with multiprocessing.Pool(4) as p: after = p.map(pow2, before) print(before[:5]) print(after[:5])
f46a1a47e165d5b894de0b9877fb046f42017f1a
selenazhen/planetParasite
/movingSprites.py
13,420
4.0625
4
TESTING CODE FOR FEATURES, IGNORE FILE # """ # Sample Python/Pygame Programs # Simpson College Computer Science # http://programarcadegames.com/ # http://simpson.edu/computer-science/ # # Explanation video: http://youtu.be/qbEEcQXw8aw # """ # # import pygame # import random # # # Define some colors # BLACK = (0, 0, 0) # WHITE = (255, 255, 255) # GREEN = (0, 255, 0) # RED = (255, 0, 0) # # # class Block(pygame.sprite.Sprite): # """ # This class represents the ball # It derives from the "Sprite" class in Pygame # """ # def __init__(self, color, width, height): # """ Constructor. Pass in the color of the block, # and its x and y position. """ # # Call the parent class (Sprite) constructor # super().__init__() # # # Create an image of the block, and fill it with a color. # # This could also be an image loaded from the disk. # self.image = pygame.Surface([width, height]) # self.image.fill(color) # # # Fetch the rectangle object that has the dimensions of the image # # image. # # Update the position of this object by setting the values # # of rect.x and rect.y # self.rect = self.image.get_rect() # # def reset_pos(self): # """ Reset position to the top of the screen, at a random x location. # Called by update() or the main program loop if there is a collision. # """ # self.rect.y = random.randrange(-300, -20) # self.rect.x = random.randrange(0, screen_width) # # def update(self): # """ Called each frame. """ # # # Move block down one pixel # self.rect.y += 1 # # # If block is too far down, reset to top of screen. # if self.rect.y > 410: # self.reset_pos() # # # class Player(Block): # """ The player class derives from Block, but overrides the 'update' # functionality with new a movement function that will move the block # with the mouse. """ # def update(self): # # Get the current mouse position. This returns the position # # as a list of two numbers. # pos = pygame.mouse.get_pos() # # # Fetch the x and y out of the list, # # just like we'd fetch letters out of a string. # # Set the player object to the mouse location # self.rect.x = pos[0] # self.rect.y = pos[1] # # # Initialize Pygame # pygame.init() # # # Set the height and width of the screen # screen_width = 700 # screen_height = 400 # screen = pygame.display.set_mode([screen_width, screen_height]) # # # This is a list of 'sprites.' Each block in the program is # # added to this list. The list is managed by a class called 'Group.' # block_list = pygame.sprite.Group() # # # This is a list of every sprite. All blocks and the player block as well. # all_sprites_list = pygame.sprite.Group() # # for i in range(50): # # This represents a block # block = Block(BLACK, 20, 15) # # # Set a random location for the block # block.rect.x = random.randrange(screen_width) # block.rect.y = random.randrange(screen_height) # # # Add the block to the list of objects # block_list.add(block) # all_sprites_list.add(block) # # # Create a red player block # player = Player(RED, 20, 15) # all_sprites_list.add(player) # # # Loop until the user clicks the close button. # done = False # # # Used to manage how fast the screen updates # clock = pygame.time.Clock() # # score = 0 # # # -------- Main Program Loop ----------- # while not done: # for event in pygame.event.get(): # if event.type == pygame.QUIT: # done = True # # # Clear the screen # screen.fill(WHITE) # # # Calls update() method on every sprite in the list # all_sprites_list.update() # # # See if the player block has collided with anything. # blocks_hit_list = pygame.sprite.spritecollide(player, block_list, False) # # # Check the list of collisions. # for block in blocks_hit_list: # score += 1 # print(score) # # # Reset block to the top of the screen to fall again. # block.reset_pos() # # # Draw all the spites # all_sprites_list.draw(screen) # # # Limit to 20 frames per second # clock.tick(20) # # # Go ahead and update the screen with what we've drawn. # pygame.display.flip() # # pygame.quit() #! /usr/bin/env python ############################################################################ # File name : detectSpriteCollsion.py # Purpose : Demostarting The Killing of Sprite On Collision # Usages : Logic can be used in real time games # Start date : 04/01/2012 # End date : 04/01/2012 # Author : Ankur Aggarwal # License : GNU GPL v3 http://www.gnu.org/licenses/gpl.html # How To Run: python detectSpriteCollision.py ############################################################################ # import pygame # from pygame.locals import * # import random # # screen=pygame.display.set_mode((640,480),0,32) # pygame.display.set_caption("Collision Detection") # # # #creating the boxes # class Boxes(pygame.sprite.Sprite): # def __init__(self): # pygame.sprite.Sprite.__init__(self) # self.image=pygame.Surface((50,50)) # self.rect=self.image.get_rect() # self.image.fill((255,255,255)) # pygame.draw.circle(self.image,(0,0,0),(25,25),25,0) # # self.rect.center=(100,100) # # #creating circle # class Circle(pygame.sprite.Sprite): # def __init__(self): # pygame.sprite.Sprite.__init__(self) # self.image=pygame.Surface((50,50)) # self.image.fill((0,255,0)) # pygame.draw.circle(self.image,(255,0,0),(25,25),25,0) # self.rect=self.image.get_rect() # def update(self): # self.rect.center=pygame.mouse.get_pos() # # # def main(): # background=pygame.Surface(screen.get_size()) # background=background.convert() # background.fill((255,255,255)) # screen.blit(background,(0,0)) # # boxes=[] # for i in range(0,10): # boxes.append(Boxes()) # # circle=Circle() # allSprites=pygame.sprite.Group(boxes) # circleSprite=pygame.sprite.Group(circle) # while 1: # for i in pygame.event.get(): # if i.type==QUIT: # exit() # # # #checking the collision.check 'pydoc pygame.sprite.spritecollide' for mode details. True is used for sprite killing. It doesn't kill the sprite in actual.It is still present in the computer memory though.It has just removed it from the group so that no further display of that sprite is possible. # if pygame.sprite.spritecollide(circle,allSprites,True): # print ("collision") # # #following the CUD method # allSprites.clear(screen,background) # circleSprite.clear(screen,background) # allSprites.update() # circleSprite.update() # allSprites.draw(screen) # circleSprite.draw(screen) # pygame.display.flip() # # # if __name__=='__main__': # main() # # """You can also check the collision about the rect attributes. There are many ways to do that.Example: # 1.circle.rect.colliderect(box1) will check the collision between the circle and box1 collision # 2. pygame.sprite.collide_rect(sprite1,sprite2) willl also do the same """ # #### # import pygame # import sys # from pygame.locals import * # # class StickMan(pygame.sprite.Sprite): # # # We’ll just accept the x-position here # def __init__(self, xPosition, yPosition): # # pygame.sprite.Sprite.__init__(self) # self.old = (0, 0, 0, 0) # self.image = pygame.image.load('img/planet1.png').convert_alpha() # self.rect = self.image.get_rect() # self.rect.x = xPosition # self.rect.y = yPosition # # # The x-position remains the same # def update(self, xPosition): # # self.old = self.rect # self.rect = self.rect.move([xPosition - self.rect.x, 0]) # # # Define a function to erase old sprite positions # # This will be used later # def eraseSprite(screen, rect): # screen.blit(blank, rect) # # pygame.init() # screen = pygame.display.set_mode((256, 256)) # # pygame.display.set_caption(‘Sprite Groups’) # screen.fill((255, 255, 255)) # # # Create the three stick men # stick1 = StickMan(0,25) # stick2 = StickMan(0,75) # stick3 = StickMan(0,125) # # # Create a group and add the sprites # stickGroup = pygame.sprite.Group() # stickGroup.add((stick1, stick2, stick3)) # # # Add a variable for the direction, y-position and height of the # # sprite we are dealing with # stickGroup.direction = 'up' # stickGroup.y = screen.get_rect().centery # stickGroup.x = screen.get_rect().centerx # stickGroup.height = stick1.rect.height # # # Create a blank piece of background # blank = pygame.Surface((stick1.rect.width, stick1.rect.height)) # blank.fill((255, 255, 255)) # # pygame.display.update() # # # Create an event that will appear ever 100 milliseconds # # This will be used to update the screen # pygame.time.set_timer(pygame.USEREVENT + 1, 100) # # while True: # # for event in pygame.event.get(): # if event.type == pygame.QUIT: # sys.exit() # if (event.type == pygame.KEYDOWN) and (event.key == K_UP): # print ('left') # # stickGroup.rect.x = stickGroup.rect.x - 10 # stickGroup.y = stickGroup.y + 10 # # # Check for our update event # if event.type == pygame.USEREVENT + 1: # # # Update the y-position # if stickGroup.direction == 'up': # stickGroup.y = stickGroup.y - 10 # else: # stickGroup.y = stickGroup.y + 10 # # # Check if we have gone off the screen # # If we have, fix it # if stickGroup.direction == 'up' and stickGroup.y <= 0: # stickGroup.direction = 'down' # elif stickGroup.direction == 'down' and stickGroup.y >= (screen.get_rect().height - stickGroup.height): # stickGroup.direction = 'up' # stickGroup.y = screen.get_rect().height - stickGroup.height # # # Clear the old sprites # # Notice that we pass our eraseSprite function # # This will be called, and the screen and old position will be passed # stickGroup.clear(screen, eraseSprite) # # # Update the sprites # stickGroup.update(stickGroup.y) # # # Blit the sprites # stickGroup.draw(screen) # # # Create a list to store the updated rectangles # updateRects = [] # # # Get the updated rectangles # for man in stickGroup: # updateRects.append(man.old) # updateRects.append(man.rect) # pygame.display.update(updateRects) ##### WORKING: MOVING PLANETS WITH ARROW KEYS BELOW # ''' pygame_sprite_keys1.py # move a sprite rect with the arrow keys # see also ... # http://www.pygame.org/docs/ref/sprite.html # http://www.pygame.org/docs/ref/time.html # ''' # # import pygame as pygame # import sys # from pygame.locals import * # import random # # speed = 5 # # pygame.init() # width = 640 # height = 480 # screen = pygame.display.set_mode((width, height)) # pygame.display.set_caption("move with arrow keys (escape key to exit)") # # # color (r, g, b) tuple, values 0 to 255 # white = (255, 255, 255) # background = pygame.Surface(screen.get_size()) # background.fill(white) # # class Planet(pygame.sprite.Sprite): # # def __init__(self, xPosition, yPosition): # pygame.sprite.Sprite.__init__(self) # self.image = pygame.image.load('img/planet1.png').convert_alpha() # self.rect = self.image.get_rect() # self.rect.centerx = xPosition # self.rect.centery = yPosition # def move(self, xMove,yMove): # self.rect.centerx = self.rect.centerx + xMove # self.rect.centery = self.rect.centery + yMove # # planet1 = Planet(random.randrange(0,width),random.randrange(0,height)) # planet2 = Planet(random.randrange(0,width),random.randrange(0,height)) # planetGroup = pygame.sprite.Group() # planetGroup.add((planet1, planet2)) # # clock = pygame.time.Clock() # while 1: # # limit runtime speed to 30 frames/second # clock.tick(30) # keyinput = pygame.key.get_pressed() # for event in pygame.event.get(): # if event.type == pygame.QUIT: # pygame.quit() # raise SystemExit # if (event.type == pygame.KEYDOWN) and (event.key == K_LEFT): # for planet in planetGroup: # planet.move(-speed,0) # if (event.type == pygame.KEYDOWN) and (event.key == K_RIGHT): # for planet in planetGroup: # planet.move(speed,0) # if (event.type == pygame.KEYDOWN) and (event.key == K_UP): # for planet in planetGroup: # planet.move(0,-speed) # if (event.type == pygame.KEYDOWN) and (event.key == K_DOWN): # for planet in planetGroup: # planet.move(0,speed) # if (event.type == pygame.KEYDOWN) and (event.key == K_ESCAPE): # playing = False # screen.blit(background, (0, 0)) # planetGroup.draw(screen) # # update display # pygame.display.flip()
a3f5f074f54b27b21a1d257ab3688165a303beff
its-me-debk007/Simple-GUI-Calculator
/GUI_Calculator.py
5,269
3.875
4
from tkinter import * from math import * window=Tk() window.title("Calculator") window.configure(bg="black") e = Entry(window, borderwidth=10, width=14, fg="white", bg="black", font=("Arial",20)) e.grid(row=0, column=0, columnspan=4, pady = 1) flag=0 def click(n): global flag if flag: e.delete(0,END) flag=0 txt=e.get() if n=="c": if txt!="": txt=txt[:-1] else: txt=e.get()+str(n) e.delete(0,END) e.insert(0,txt) def power(): global first_num first_num = e.get() + "P" e.delete(0,END) def add(): global first_num first_num = e.get()+"A" e.delete(0,END) def sub(): global first_num first_num = e.get()+"S" e.delete(0,END) def mult(): global first_num first_num = e.get()+"M" e.delete(0,END) def div(): global first_num first_num = e.get()+"D" e.delete(0,END) def root(): num=float(e.get()) e.delete(0,END) if num < 0: e.insert(0,"Error") else: ans = sqrt(num) if(ans - int(ans) == 0): ans = int(ans) e.insert(0, ans) global flag flag=1 def absolute(): num = float(e.get()) e.delete(0,END) if num<0: num = abs(num) else: num = -num if not num - int(num): num = int(num) e.insert(0, num) def equal(): second_num = float(e.get()) e.delete(0,END) num=float(first_num[:-1]) if first_num[-1]=="A": ans = num + second_num elif first_num[-1]=="S": ans = num - second_num elif first_num[-1]=="M": ans = num * second_num elif first_num[-1]=="D": if num%second_num ==0: ans=int(num/second_num) else: ans=num/second_num elif first_num[-1] == "P": ans = pow(num, second_num) if(ans - int(ans) == 0): ans = int(ans) e.insert(0,ans) global flag flag=1 bt7=Button(window,text="7",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(7)) bt7.grid(row=2,column=0) window.bind("7", lambda event: click(7)) bt8=Button(window,text="8",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(8)) bt8.grid(row=2,column=1) window.bind("8", lambda event: click(8)) bt9=Button(window,text="9",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(9)) bt9.grid(row=2,column=2) window.bind("9", lambda event: click(9)) bt4=Button(window,text="4",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(4)) bt4.grid(row=3,column=0) window.bind("4", lambda event: click(4)) bt5=Button(window,text="5",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(5)) bt5.grid(row=3,column=1) window.bind("5", lambda event: click(5)) bt6=Button(window,text="6",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(6)) bt6.grid(row=3,column=2) window.bind("6", lambda event: click(6)) bt1=Button(window,text="1",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(1)) bt1.grid(row=4,column=0) window.bind("1", lambda event: click(1)) bt2=Button(window,text="2",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(2)) bt2.grid(row=4,column=1) window.bind("2", lambda event: click(2)) bt3=Button(window,text="3",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(3)) bt3.grid(row=4,column=2) window.bind("3", lambda event: click(3)) bt0=Button(window,text="0",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(0)) bt0.grid(row=5,column=1) window.bind("0", lambda event: click(0)) btadd=Button(window,text="+",font=("Arial",20),fg="white",bg="black",width=3,command=add) btadd.grid(row=4,column=3) window.bind("+", lambda event: add()) btsub=Button(window,text="-",font=("Arial",20),fg="white",bg="black",width=3,command=sub) btsub.grid(row=3,column=3) window.bind("-", lambda event: sub()) btmult=Button(window,text="*",font=("Arial",20),fg="white",bg="black",width=3,command=mult) btmult.grid(row=2,column=3) window.bind("*", lambda event: mult()) btdiv=Button(window,text="/",font=("Arial",20),fg="white",bg="black",width=3,command=div) btdiv.grid(row=1,column=3) window.bind("/", lambda event: div()) btdot=Button(window,text=".",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click(".")) btdot.grid(row=5,column=0) window.bind(".", lambda event: click(".")) btroot = Button(window, text="√", font=("Arial",20),command=root,fg="white",bg="black",width=3).grid(row=1,column=0) btcut=Button(window,text="c",font=("Arial",20),fg="white",bg="black",width=3,command=lambda:click("c") ) btcut.grid(row=1,column=2) window.bind("<BackSpace>", lambda event: click("c")) btpow = Button(window, text = "^", font = ("Arial",20), fg = "white", bg = "black",width = 3, command = power) btpow.grid(row = 1, column = 1) window.bind("^", lambda event: power()) bteq=Button(window,text="=",font=(" Arial",20),fg="white",bg="black",width=3,command=equal) window.bind("<Return>", lambda event: equal()) bteq.grid(row=5,column=3) btabs = Button(window, text = "+/-", fg = "white", bg = "black", font = ("Arial",20), command = absolute, width = 3).grid(row = 5, column = 2) window.mainloop()
6bcb7aad9b7a23689eeed75a78fe1a1f154e0c00
sharadsharmam/DataStructures-in-Python
/Queues.py
2,116
3.859375
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 12 15:07:21 2019 @author: sharad sharma """ class Queue: def __init__(self, queueLimit): self.head = None self.tail = None self.limit = queueLimit def isEmpty(self): if self.head == None: return True else: return False def isFull(self): if self.isEmpty(): return False currNode = self.head count=0 while(currNode != None): count += 1 currNode = currNode.next if count<self.limit: return False else: return True def enqueue(self, data): if self.isFull(): print("QueueOverFlow") return tempNode = queueNode(data) if self.isEmpty(): self.tail = tempNode else: tempNode.next = self.head self.head.prev = tempNode self.head = tempNode def dequeue(self): if self.isEmpty(): print("Queue is Empty") return temp = self.tail.val if self.head == self.tail: self.head = None self.tail = None else: self.tail = self.tail.prev self.tail.next = None return temp def printQueue(self): if self.isEmpty(): print("Queue is Empty") return currNode = self.head while(currNode!=None): print("<--",currNode.val, end=" ") currNode = currNode.next print("\n") def changeLimit(self, newLimit): self.limit = newLimit class queueNode: def __init__(self, data): self.val = data self.next = None self.prev = None ''' qu = Queue(5) qu.enqueue(1) qu.printQueue() qu.enqueue(2) qu.printQueue() qu.enqueue(3) qu.printQueue() qu.enqueue(4) qu.printQueue() print(qu.dequeue()) qu.printQueue() qu.enqueue(5) qu.printQueue() '''
701b95d2a47ca261293e41a70a90a4641c7bacb7
olopez15401/Python_Exercises
/favorite_number.py
1,032
4.25
4
""" Simple program that prompts a user's favorite number, stores it, and prints it out. Author: Oscar Lopez Date: Jan 11, 2019 """ import json class favorite_number(): def __init__(self): self.number = 0 self.prompt_user() self.save_number() print("Your favorite number is : " + self.read_number()) def prompt_user(self): while True: try: self.number = int(input("What is your favorite number?\n")) break except ValueError: print("ERROR: Please enter a valid number!") def save_number(self, filename = 'favorite_number.json'): with open(filename,'w') as f_obj: json.dump(str(self.number),f_obj) def read_number(self,filename = 'favorite_number.json'): try: with open(filename) as f_obj: return json.load(f_obj) except FileNotFoundError: print("ERROR! File " + filename + " cannot be read!") favorite_number()
210037f1cb8e3cb64d8aabcf69258238307bb519
aestriplet1279/cs109-osp
/hw3_with_hint_ArmaniEstriplet.py
2,689
4.5
4
############################### # Print Range # # Giving the following variables: # start (number): The lower bound of the range. # end (number): The upper bound of the range. # stride (number): The amount to increment when counting. # # # Print all numbers between `start` and `end` at # intervals of `stride` # # Example: # if start = 0, end = 5, stride = 1, then print # 0 # 1 # 2 # 3 # 4 # 5 # # Example: # if start = 2, end = 3.2, stride = 0.5, then print # 2 # 2.5 # 3.0 start = 2 end = 3.2 stride = 0.5 ### Your code here ### start = 0 end = 20 stride = .2 while stride < int(end): print(start + stride) stride += .2 ############################### # Wheel of Fortune # # WARNING: This exersise is significantly harder than what # we have done up until this point. You should attempt it, # but if you cannot complete it that is fine. # # Giving the following variables: # word (string): The secret word to guess # # Write a program that shows a string of underscores ("_") of # the same length as `word`. We will refer to this sting as the # board. Using a loop, take a single character input from the # user. If the input character exists in the secret word, # replace the underscores on the board in the same positions # as character in the secret word with the character. # # Once all characters in the secret word have been input, # the board should be equal to the secret word. # # Basically we are trying to recreate a simple version of # the "Wheel of Fortune" or "hangman". # https://www.coolmath-games.com/0-hangman # # EXAMPLE: Using the word "lollipop" the output should look # something like this: # # ________ | Enter a letter: l # l_ll____ | Enter a letter: p # l_ll_p_p | Enter a letter: i # l_llip_p | Enter a letter: o # lollipop Correct! word = "lollipop" ### Your code here ### # Here we loop through every board position and # replace all of the "_" with "l" in positions # where there is an "l" in the secret word. guess = input("letters") board = "_____p_p" new_board = "" counter = 0 i ="l_llip_p" o = "lollipop" while counter < len(board): # Here we assume "l" is our guess. if word[counter] == "l": # Add the guess to the new_board at the position counter. new_board = new_board + "l" else: # Keep what already exists on the board at the position. new_board = new_board + board[counter] counter = counter + 1 board = new_board print(board) if i in word: print("l_llip_p") if o in word: print("lollipop")
43bb7546c2030ed60cb3cec80e5649f582b20c7b
VictorRielly/bhk
/neuralnet.py
67,060
3.53125
4
# This python script will be used to implement a neural network. # The neural network will be nested in a class so it may integrated # more easily with other code later on. import sklearn.metrics from sklearn import svm import numpy as np import csv import pandas as pd import copy import time import math np.random.seed() import gc class Neuralnet: # The network will be set up to allow any number of # layers and any number of nodes per layer. The only # parameter passed into the constructor is an array # holding the number of nodes per layer starting with # the input layer and continuing to the output layer def __init__(*arg): # by default, we will make a 785 by 25 by 10 # neural network. self = arg[0] self.eta = 0.01 self.alpha = 0 self.netl = [785,26,10] self.numl = 3 self.netw = [np.zeros((25,785)),np.zeros((10,26))] self.netwd = [np.zeros((25,785)),np.zeros((10,26))] self.netx = [np.ones(785),np.ones(26),np.ones(10)] self.netd = [np.ones(785),np.ones(26),np.ones(10)] # sets default values for self.train and self.test self.train = './mnist_train.csv' self.test = './mnist_test.csv' # creates a matrix target vector matrix self.target = np.ones((10,10)) self.target = self.target*.1 temp = np.eye(10) temp = temp*.8 self.target = self.target + temp numi = 0 for i in arg: if numi == 1: self.numl = np.size(i) self.netl = i self.netw = [0,]*(self.numl - 1) self.netwd = [0,]*(self.numl - 1) self.netx = [1,]*(self.numl) self.netd = [1,]*(self.numl) for k in range(0,self.numl): self.netx[k]=np.ones(self.netl[k]) self.netd[k]=np.ones(self.netl[k]) for j in range(0,self.numl-2): self.netw[j] = np.zeros((self.netl[j+1]-1,self.netl[j])) self.netwd[j] = np.zeros((self.netl[j+1]-1,self.netl[j])) self.netw[self.numl-2] = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) self.netwd[self.numl-2] = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) # creates a matrix target vector matrix self.target = np.ones((i[self.numl-1],i[self.numl-1])) self.target = self.target*.1 temp = np.eye(i[self.numl-1])*.8 self.target = self.target + temp if numi == 2: self.train = i if numi == 3: self.test = i if numi == 4: self.eta = i if numi == 5: self.alpha = i numi = numi +1 # Initializes the weights to be random self.rand_weights() # reads training and test data into self.train and # self.test respectively self.traind = (pd.read_csv(self.train,sep=',',header=None)).values self.testd = (pd.read_csv(self.test,sep=',',header=None)).values self.traindata = np.ones((np.shape(self.traind)[0],np.shape(self.traind)[1]+1)) self.testdata = np.ones((np.shape(self.testd)[0],np.shape(self.testd)[1]+1)) self.testdata[:,:-1] = self.testd self.traindata[:,:-1] = self.traind self.testdata[:,1:-1] = self.testdata[:,1:-1]/255.0 self.traindata[:,1:-1] = self.traindata[:,1:-1]/255.0 # Randomizes the weights def rand_weights(self): for i in range(0,self.numl-1): self.netw[i] = (np.random.rand(np.shape(self.netw[i])[0],np.shape(self.netw[i])[1])-.5)*.1 # apply sigmoid function to the num'th vector of self.netx def sigmoid(self,num): if num < self.numl-1: self.netx[num][:-1] = 1.0/(1+np.exp(-self.netx[num][:-1])) else : self.netx[num] = 1.0/(1+np.exp(-self.netx[num])) # apply the sgn function to the num'th vector of self.netx def sgn(self,num): if num < self.numl-1: for i in range(0,self.netl[num]-1): if self.netx[num][i] > 0: self.netx[num][i] = 1 else : self.netx[num][i] = 0 else : for i in range(0,self.netl[num]): if self.netx[num][i] > 0: self.netx[num][i] = 1 else : self.netx[num][i] = 0 # propagates the first vector of self.netx through all of the vectors in self.netx def propagate_sigmoid(self): for i in range(0,self.numl-2): self.netx[i+1][:-1] = np.dot(self.netw[i],self.netx[i]) self.sigmoid(i+1) self.netx[self.numl-1] = np.dot(self.netw[self.numl-2],self.netx[self.numl-2]) self.sigmoid(self.numl-1) # propagates the first vector of self.netx through all of the vectors in self.netx def propagate_sgn(self): for i in range(0,self.numl-2): self.netx[i+1][:-1] = np.dot(self.netw[i],self.netx[i]) self.sgn(i+1) self.netx[self.numl-2] = np.dot(self.netw[self.numl-2],self.netx[self.numl-2]) # shuffles the training data def shuffle(self): np.random.shuffle(self.traindata) # This function calculates the accuracy of the network on # the train data def train_accuracy_sigmoid(self): total = 0 for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() if (np.argmax(self.netx[self.numl-1]) == i[0]): total = total + 1 self.train_accuracy = (0.0+total)/(np.shape(self.traindata)[0]) # This function calculates the accuracy of the network on # the test data def test_accuracy_sigmoid(self): total = 0 for i in self.testdata: self.netx[0] = i[1:] self.propagate_sigmoid() if (np.argmax(self.netx[self.numl-1]) == i[0]): total = total + 1 self.test_accuracy = (0.0+total)/(np.shape(self.testdata)[0]) # This function calculates the accuracy of the network on # the train data using the covarience weight matrix for the last layer def train_accuracy_sigmoid_conv(self): total = 0 for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() self.netx[self.numl-1] = np.dot(self.covw,self.netx[self.numl-2]) if (np.argmax(self.netx[self.numl-1]) == i[0]): total = total + 1 self.train_accuracy = (0.0+total)/(np.shape(self.traindata)[0]) # This function calculates the accuracy of the network on # the test data using the covarience weight matrix for the last layer def test_accuracy_sigmoid_conv(self): total = 0 for i in self.testdata: self.netx[0] = i[1:] self.propagate_sigmoid() self.netx[self.numl-1] = np.dot(self.covw,self.netx[self.numl-2]) if (np.argmax(self.netx[self.numl-1]) == i[0]): total = total + 1 self.test_accuracy = (0.0+total)/(np.shape(self.testdata)[0]) # This function calculates the accuracy of the network on # the train data this uses the sgn function in place of the sigmoid def train_accuracy_sgn(self): total = 0 for i in self.traindata: self.netx[0] = i[1:] self.propagate_sgn() if (np.argmax(self.netx[self.numl-1]) == i[0]): total = total + 1 self.train_accuracy = (0.0+total)/(np.shape(self.traindata)[0]) # This function calculates the accuracy of the network on # the test data using the sgn function def test_accuracy_sgn(self): total = 0 for i in self.testdata: self.netx[0] = i[1:] self.propagate_sgn() if (np.argmax(self.netx[self.numl-1]) == i[0]): total = total + 1 self.test_accuracy = (0.0+total)/(np.shape(self.testdata)[0]) #This function prepares target vectors for neural network stock # market applications. Prepares training vector def stochastic_stock_prep(self): self.traintarget = np.zeros((np.shape(self.traindata)[0],123)); for i in range(0,np.shape(self.traindata)[0]-1): rowsum = 0; for j in range(0,123): if self.traindata[i+1][-123+j:] > 0: self.traintarget[i][j] = self.traindata[i+1][-123+j:]; rowsum = rowsum + self.traindata[i+1][-123+j:]; self.traintarget[k][:] = self.traintarget[k][:]/rowsum; #This function prepares target vectors for neural network stock # market applications prepares the test vector def stochastic_stock_prep_test(self): self.testtarget = np.zeros((np.shape(self.testdata)[0],123)); k = 0; l = 0; for i in self.testdata: rowsum = 0; for j in i: if j > 0: self.testtarget[k][l] = j; rowsum = rowsum + j; l = l + 1; k = k + 1; l = 0; # This function trains using stochastic gradient descent # for 1 epoch with target vectors [.1 .1 .9 .1 ...] def stochastic_stocks(self): self.stochastic_stock_prep(); currentc = 0; for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() # calculates the delta for the last layer self.netd[-1] = self.netx[-1]*(1-self.netx[-1])*(self.traintarget[currentc]-self.netx[-1]) # calculates the delta for all other layers self.netd[-2] = self.netx[-2]*(1-self.netx[-2])*(np.dot(self.netw[-1].T,self.netd[-1])) for j in range(0,self.numl-2): self.netd[-j-3] = self.netx[-j-3]*(1-self.netx[-j-3])*(np.dot(self.netw[-j-2].T,self.netd[-j-2][:-1])) # Now we update all of the weights based on the deltas, etas, and alphas for j in range(0,self.numl-2): # computes the momentum including delta w self.netwd[j] = self.eta*np.outer(self.netd[j+1][:-1],self.netx[j]) + self.alpha*self.netwd[j] # updates the weights self.netw[j] = self.netw[j] + self.netwd[j] # computes the momentum including delta w self.netwd[-1] = self.eta*np.outer(self.netd[-1],self.netx[-2]) + self.alpha*self.netwd[-1] # updates the weights self.netw[-1] = self.netw[-1] + self.netwd[-1] currentc = currentc + 1; # This function trains using stochastic gradient descent # for 1 epoch with target vectors [.1 .1 .9 .1 ...] def stochastic_gradient_sigmoid(self): for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() # calculates the delta for the last layer self.netd[-1] = self.netx[-1]*(1-self.netx[-1])*(self.target[int(i[0])]-self.netx[-1]) # calculates the delta for all other layers self.netd[-2] = self.netx[-2]*(1-self.netx[-2])*(np.dot(self.netw[-1].T,self.netd[-1])) for j in range(0,self.numl-2): self.netd[-j-3] = self.netx[-j-3]*(1-self.netx[-j-3])*(np.dot(self.netw[-j-2].T,self.netd[-j-2][:-1])) # Now we update all of the weights based on the deltas, etas, and alphas for j in range(0,self.numl-2): # computes the momentum including delta w self.netwd[j] = self.eta*np.outer(self.netd[j+1][:-1],self.netx[j]) + self.alpha*self.netwd[j] # updates the weights self.netw[j] = self.netw[j] + self.netwd[j] # computes the momentum including delta w self.netwd[-1] = self.eta*np.outer(self.netd[-1],self.netx[-2]) + self.alpha*self.netwd[-1] # updates the weights self.netw[-1] = self.netw[-1] + self.netwd[-1] # This function trains just one layer at a time def stochastic_gradient_sigmoid_2(self,layer): for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() # calculates the delta for the last layer self.netd[-1] = (self.target[int(i[0])]-self.netx[-1])*self.netx[-1]*(1-self.netx[-1]) # calculates the delta for all other layers self.netd[-2] = self.netx[-2]*(1-self.netx[-2])*(np.dot(self.netw[-1].T,self.netd[-1])) for j in range(0,self.numl-2): self.netd[-j-3] = self.netx[-j-3]*(1-self.netx[-j-3])*(np.dot(self.netw[-j-2].T,self.netd[-j-2][:-1])) # Now we update all of the weights based on the deltas, etas, and alphas for j in range(0,self.numl-2): # computes the momentum including delta w self.netwd[j] = self.eta*np.outer(self.netd[j+1][:-1],self.netx[j]) + self.alpha*self.netwd[j] # updates the weights if j == layer: self.netw[j] = self.netw[j] + self.netwd[j] # computes the momentum including delta w self.netwd[-1] = self.eta*np.outer(self.netd[-1],self.netx[-2]) + self.alpha*self.netwd[-1] if layer == self.numl-2: # updates the weights self.netw[-1] = self.netw[-1] + self.netwd[-1] # This function trains using stochastic gradient descent # for 1 epoch with target vectors [0 0 1 0 0 0 0 ...] def stochastic_gradient_sigmoid_1(self): temp = np.eye(self.netl[self.numl-1]) for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() # calculates the delta for the last layer self.netd[-1] = self.netx[-1]*(1-self.netx[-1]) self.netd[-1] = self.netd[-1]*(temp[int(i[0])]-self.netx[-1]) # calculates the delta for all other layers self.netd[-2] = self.netx[-2]*(1-self.netx[-2]) self.netd[-2] = self.netd[-2]*(np.dot(self.netw[-1].T,self.netd[-1])) for j in range(0,self.numl-2): self.netd[-j-3] = self.netx[-j-3]*(1-self.netx[-j-3]) self.netd[-j-3] = self.netd[-j-3]*(np.dot(self.netw[-j-2].T,self.netd[-j-2][:-1])) # Now we update all of the weights based on the deltas, etas, and alphas for j in range(0,self.numl-2): # computes the momentum including delta w self.netwd[j] = self.eta*np.outer(self.netd[j+1][:-1],self.netx[j]) + self.alpha*self.netwd[j] # updates the weights self.netw[j] = self.netw[j] + self.netwd[j] # computes the momentum including delta w self.netwd[-1] = self.eta*np.outer(self.netd[-1],self.netx[-2]) + self.alpha*self.netwd[-1] # updates the weights self.netw[-1] = self.netw[-1] + self.netwd[-1] # This function calculates and stores the confusion matrix with sigmoid function def conf_train_sigmoid(self): self.conf_train = np.zeros((self.netl[self.numl-1],self.netl[self.numl-1])) for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() temp = np.argmax(self.netx[self.numl-1]) self.conf_train[int(i[0])][temp] += 1 # This function calculates and stores the confusion matrix with sigmoid function def conf_test(self): self.conf_test = np.zeros((self.netl[self.numl-1],self.netl[self.numl-1])) for i in self.testdata: self.netx[0] = i[1:] self.propagate_sigmoid() temp = np.argmax(self.netx[self.numl-1]) self.conf_test[int(i[0])][temp] += 1 # This function uses inverse covariance matrix to calculate the weights for the # last layer of the neural network, using training data def calc_last_layer3(self): self.covariancep = np.zeros((self.netl[self.numl-2],self.netl[self.numl-2],self.netl[self.numl-1])) self.covariancen = np.zeros((self.netl[self.numl-2],self.netl[self.numl-2],self.netl[self.numl-1])) self.meanp = np.zeros((self.netl[self.numl-2],self.netl[self.numl-1])) self.meann = np.zeros((self.netl[self.numl-2],self.netl[self.numl-1])) self.mean = np.zeros((self.netl[self.numl-2],self.netl[self.numl-1])) self.c = np.zeros((self.netl[self.numl-2],self.netl[self.numl-2],self.netl[self.numl-1])) self.cinv = np.zeros((self.netl[self.numl-2],self.netl[self.numl-2],self.netl[self.numl-1])) self.ptot = np.zeros(self.netl[self.numl-1]) self.ntot = np.zeros(self.netl[self.numl-1]) for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() for k in range(0,self.netl[self.numl-1]): if i[0] == k: self.ptot[k] += 1 self.covariancep[:,:,k] += np.outer(self.netx[self.numl-2],self.netx[self.numl-2]) self.meanp[:,k] += self.netx[self.numl-2] else : self.ntot[k] += 1 self.covariancen[:,:,k] += np.outer(self.netx[self.numl-2],self.netx[self.numl-2]) self.meann[:,k] += self.netx[self.numl-2] for k in range(0,self.netl[self.numl-1]): self.covariancep[:,:,k] = self.covariancep[:,:,k]/(self.ptot[k]) - np.outer(self.meanp[:,k],self.meanp[:,k])/((self.ptot[k])*(self.ptot[k])) self.covariancen[:,:,k] = self.covariancen[:,:,k]/(self.ntot[k]) - np.outer(self.meann[:,k],self.meann[:,k])/((self.ntot[k])*(self.ntot[k])) self.mean[:,k] = self.meanp[:,k]/(self.ptot[k]) - self.meann[:,k]/(self.ntot[k]) self.c = self.covariancep+self.covariancen # we begin by splitting the training data into 10 classes one # for each digit self.numnums = np.zeros(self.netl[-1]) for i in self.traindata: self.numnums[int(i[0])] += 1 # Creates an array for each of the classes self.classes = [0,]*self.netl[-1] for i in range(0,self.netl[-1]): self.classes[i] = np.zeros((int(self.numnums[i]),np.shape(self.traindata)[1])) temp = np.zeros(self.netl[-1]) for i in self.traindata: self.classes[int(i[0])][int(temp[int(i[0])])] = i temp[int(i[0])] += 1 # We will start with the zero weight vector self.covw = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) for epoch in range(0,epochs): self.covw += self.covw + (self.c*self.covw - self.mean) #for k in range(0,self.netl[self.numl-1]): # self.cinv[:,:,k] = np.linalg.inv(self.c[:,:,k]) # #self.covw = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) #for k in range(0,self.netl[self.numl-1]): # self.covw[k,:] = np.dot(self.cinv[:,:,k],self.mean[:,k]) # This function computes the weight matrix for the last layer using # gradient descent so as to maximize the area under the roc_auc curve # using W^{t+1} = W^{t} - gamma_t(C^{hat}W^{t}-mu^{hat}) # where C^{hat}= 1/(n-1)(sum(Z*Z^T)-1/n^2sum(Z)sum(Z)^T) def calc_last_layer_gradient(self,batchs,epochs): # we begin by splitting the training data into 10 classes one # for each digit self.numnums = np.zeros(self.netl[-1]) for i in self.traindata: self.numnums[int(i[0])] += 1 # Creates an array for each of the classes self.classes = [0,]*self.netl[-1] for i in range(0,self.netl[-1]): self.classes[i] = np.zeros((int(self.numnums[i]),np.shape(self.traindata)[1])) temp = np.zeros(self.netl[-1]) for i in self.traindata: self.classes[int(i[0])][int(temp[int(i[0])])] = i temp[int(i[0])] += 1 # We will start with the zero weight vector self.covw = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) z = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) c = np.zeros(self.netl[self.numl-1]) cov = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) mean = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) # We attempt to scale all the output weight vectors so the mean # of the positive class is sent to -1 and the mean of the negative # input vector is sent to +1. This way, the outputs should be more # comparable self.meanpt = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) self.meannt = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) self.b = np.ones(self.netl[self.numl-1]) for epoch in range(0,epochs): for i in range(0,int(np.floor(self.numnums[0]/batchs))): for j in range(0,batchs): for k in range(0,self.netl[-1]): randomc = np.random.randint(self.netl[-1]-1) randomc = (k + randomc)%(self.netl[-1]) self.netx[0] = self.classes[k][i,1:] self.propagate_sigmoid() xp = copy.copy(self.netx[self.numl-2]) self.meanpt[k] += xp self.netx[0] = self.classes[randomc][i,1:] self.propagate_sigmoid() xn = self.netx[self.numl-2] self.meannt[k] += xn z[k,:] = xp - xn c[k] = np.dot(z[k,:],self.covw[k,:]) cov += z*c[:,None] mean += z for k in range(0,self.netl[-1]): mean[k,:] = (batchs/(batchs-1.0)*1.0/(batchs*batchs)*np.dot(mean[k,:],self.covw[k,:]) + self.b[k]*1.0/batchs)*mean[k,:] cov = 1.0/(batchs-1)*cov self.covw = self.covw - 1.0/(i+1+epoch*np.floor(self.numnums[0]/batchs))*(cov - mean) # zero the mean and cov cov = 0*cov mean = 0*mean # scales the view vectors by their magnitudes for k in range(0,self.netl[-1]): blittle = (1./abs(np.linalg.norm(self.covw[k,:]))) self.covw[k,:] = self.covw[k,:]*blittle self.b[k] = self.b[k]*blittle for i in range(0,self.netl[-1]): np.random.shuffle(self.classes[i]) # This function computes the weight matrix for the last layer using # gradient descent so as to maximize the area under the roc_auc curve # using W^{t+1} = W^{t} - gamma_t(C^{hat}W^{t}-mu^{hat}) # where C^{hat}= 1/(n-1)(sum(Z*Z^T)-1/n^2sum(Z)sum(Z)^T) def calc_last_layer_gradient2(self,batchs,epochs): # we begin by splitting the training data into 10 classes one # for each digit self.numnums = np.zeros(self.netl[-1]) for i in self.traindata: self.numnums[int(i[0])] += 1 # Creates an array for each of the classes self.classes = [0,]*self.netl[-1] for i in range(0,self.netl[-1]): self.classes[i] = np.zeros((int(self.numnums[i]),np.shape(self.traindata)[1])) temp = np.zeros(self.netl[-1]) for i in self.traindata: self.classes[int(i[0])][int(temp[int(i[0])])] = i temp[int(i[0])] += 1 # We will start with the zero weight vector self.covw = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) zp = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) zn = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) cp = np.zeros(self.netl[self.numl-1]) cn = np.zeros(self.netl[self.numl-1]) cov = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) mean = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) # sums of positives and negatives self.meanpt = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) self.meannt = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) # unit conversion constant self.b = np.ones(self.netl[self.numl-1]) for epoch in range(0,epochs): for i in range(0,int(np.floor(self.numnums[0]/batchs))): for j in range(0,batchs): for k in range(0,self.netl[-1]): randomc = np.random.randint(self.netl[-1]-1) randomc = (k + randomc)%(self.netl[-1]) self.netx[0] = self.classes[k][i,1:] self.propagate_sigmoid() xp = copy.copy(self.netx[self.numl-2]) self.meanpt[k] += xp self.netx[0] = self.classes[randomc][i,1:] self.propagate_sigmoid() xn = self.netx[self.numl-2] self.meannt[k] += xn zp[k,:] = xp zn[k,:] = xn cp[k] = np.dot(zp[k,:],self.covw[k,:]) cn[k] = np.dot(zn[k,:],self.covw[k,:]) cov += zp*cp[:,None] + zn*cn[:,None] mean += zp - zn for k in range(0,self.netl[-1]): #mean[k,:] = (batchs/(batchs-1.0)*1.0/(batchs*batchs)*np.dot(mean[k,:],self.covw[k,:]) + self.b[k]*1.0/batchs)*mean[k,:] mean[k,:] = self.b[k]*1.0/batchs*mean[k,:] cov[k,:] = cov[k,:]-1.0/batchs*(self.meanpt[k,:]*np.dot(self.meanpt[k,:],self.covw[k,:])+self.meannt[k,:]*np.dot(self.meannt[k,:],self.covw[k,:])) cov = 1.0/(batchs-1)*cov self.covw = self.covw - 1.0/(i+1+epoch*np.floor(self.numnums[0]/batchs))*(cov - mean) # zero the mean and cov cov = 0*cov mean = 0*mean self.meanpt = 0*self.meanpt self.meannt = 0*self.meannt # scales the view vectors by their magnitudes for k in range(0,self.netl[-1]): blittle = (1./abs(np.linalg.norm(self.covw[k,:]))) self.covw[k,:] = self.covw[k,:]*blittle self.b[k] = self.b[k]*blittle for i in range(0,self.netl[-1]): np.random.shuffle(self.classes[i]) # This function uses svm to calculate the weight vectors. This needs to be improved to # work for second to last layer so it can live at the end of a neuralnet def calc_last_layer_svm(self): temp = 0 self.train_target = np.zeros((self.netl[-1],np.shape(self.traindata)[0])) for i in range(0,self.netl[-1]): self.train_target[i][0:int(self.numnums[i])] = 1 #self.trainsvmdata = np.zeros((self.netl[-1],np.shape(self.traindata)[0],np.shape(self.traindata)[1])) self.trainsvmdata = np.zeros((np.shape(self.traindata)[0],np.shape(self.traindata)[1]-1)) self.svmw = np.zeros((self.netl[-1],self.netl[-2])) self.svm = svm.SVC(kernel='linear') for i in range(0,self.netl[-1]): self.trainsvmdata[0:int(self.numnums[i])] = self.classes[i][:,0:-1] temp = int(self.numnums[i]) for j in range(0,self.netl[-1]): if j != i: self.trainsvmdata[temp:temp+int(self.numnums[j])] = self.classes[j][:,0:-1] temp += int(self.numnums[j]) self.svm.fit(self.trainsvmdata,self.train_target[i]) self.svmw[i] = copy.copy(self.svm.coef_) print i def sigmoid2(self,mat): mat[:,:-1] = 1.0/(1+np.exp(-mat[:,:-1])) return mat def sigmoid3(self,mat): mat = 1.0/(1+np.exp(-mat)) return mat # apply sigmoid function to the num'th vector of self.netx def sigmoid(self,num): if num < self.numl-1: self.netx[num][:-1] = 1.0/(1+np.exp(-self.netx[num][:-1])) else : self.netx[num] = 1.0/(1+np.exp(-self.netx[num])) # This function will use gradient descent but increase the presence of # negatively classified instances in the training set. def stochastic_gradient_sigmoid_e(self,epochs): self.temp = self.traindata[:] self.shuffle() self.stochastic_gradient_sigmoid() for j in range(0,epochs): self.traindata = self.temp[:] self.train_accuracy_nice() print self.train_accuracy numerrors = np.sum(self.errors) self.newdata = np.zeros((int(np.sum(self.errors)),np.shape(self.traindata)[1])) countolaf = 0 for i in range(0,np.shape(self.traindata)[0]): if self.errors[i] == 1: self.newdata[countolaf] = self.traindata[i] np.vstack((self.traindata,self.newdata)) self.shuffle() self.traindata = self.traindata[:int(-numerrors)] print np.shape(self.traindata) self.traindata = self.temp[:] def train_accuracy_nice(self): self.tempx1 = np.dot(self.traindata[:,1:],self.netw[0].T) self.errors = np.zeros(np.shape(self.traindata)[0]) for i in range(1,self.numl-1): print np.shape(self.tempx1) self.tempx1 = np.concatenate((self.tempx1,np.ones((np.shape(self.traindata)[0],1))),axis=1) print np.shape(self.tempx1) self.tempx1 = self.sigmoid2(self.tempx1) print np.shape(self.tempx1) self.tempx1 = np.dot(self.tempx1,self.netw[i].T) self.sigmoid3(self.tempx1) count = 0 for i in range(0,np.shape(self.tempx1)[0]): if np.argmax(self.tempx1[i,:]) != self.traindata[i,0]: self.errors[i] = 1 else : count += 1 self.train_accuracy = (count+0.0)/(np.shape(self.traindata)[0]) def test_accuracy_nice(self): self.tempx1 = np.dot(self.testdata[:,1:],self.netw[0].T) self.errors = np.zeros(np.shape(self.testdata)[0]) for i in range(1,self.numl-1): print np.shape(self.tempx1) self.tempx1 = np.concatenate((self.tempx1,np.ones((np.shape(self.testdata)[0],1))),axis=1) print np.shape(self.tempx1) self.tempx1 = self.sigmoid2(self.tempx1) print np.shape(self.tempx1) self.tempx1 = np.dot(self.tempx1,self.netw[i].T) self.sigmoid3(self.tempx1) count = 0 for i in range(0,np.shape(self.tempx1)[0]): if np.argmax(self.tempx1[i,:]) != self.testdata[i,0]: self.errors[i] = 1 else : count += 1 self.test_accuracy = (count+0.0)/(np.shape(self.testdata)[0]) # This function uses inverse covariance matrix to calculate the weights for the # last layer of the neural network, using training data def calc_last_layer(self): self.covariancep = np.zeros((self.netl[self.numl-2],self.netl[self.numl-2],self.netl[self.numl-1])) self.covariancen = np.zeros((self.netl[self.numl-2],self.netl[self.numl-2],self.netl[self.numl-1])) self.meanp = np.zeros((self.netl[self.numl-2],self.netl[self.numl-1])) self.meann = np.zeros((self.netl[self.numl-2],self.netl[self.numl-1])) self.mean = np.zeros((self.netl[self.numl-2],self.netl[self.numl-1])) self.c = np.zeros((self.netl[self.numl-2],self.netl[self.numl-2],self.netl[self.numl-1])) self.cinv = np.zeros((self.netl[self.numl-2],self.netl[self.numl-2],self.netl[self.numl-1])) self.ptot = np.zeros(self.netl[self.numl-1]) self.ntot = np.zeros(self.netl[self.numl-1]) for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() for k in range(0,self.netl[self.numl-1]): if i[0] == k: self.ptot[k] += 1 self.covariancep[:,:,k] += np.outer(self.netx[self.numl-2],self.netx[self.numl-2]) self.meanp[:,k] += self.netx[self.numl-2] else : self.ntot[k] += 1 self.covariancen[:,:,k] += np.outer(self.netx[self.numl-2],self.netx[self.numl-2]) self.meann[:,k] += self.netx[self.numl-2] for k in range(0,self.netl[self.numl-1]): self.covariancep[:,:,k] = self.covariancep[:,:,k]/(self.ptot[k]) - np.outer(self.meanp[:,k],self.meanp[:,k])/((self.ptot[k])*(self.ptot[k])) self.covariancen[:,:,k] = self.covariancen[:,:,k]/(self.ntot[k]) - np.outer(self.meann[:,k],self.meann[:,k])/((self.ntot[k])*(self.ntot[k])) self.mean[:,k] = self.meanp[:,k]/(self.ptot[k]) - self.meann[:,k]/(self.ntot[k]) self.c = self.covariancep+self.covariancen for k in range(0,self.netl[self.numl-1]): self.cinv[:,:,k] = np.linalg.inv(self.c[:,:,k]) self.covw = np.zeros((self.netl[self.numl-1],self.netl[self.numl-2])) for k in range(0,self.netl[self.numl-1]): self.covw[k,:] = np.dot(self.cinv[:,:,k],self.mean[:,k]) # This function computes the roc_auc_cov over the training set for the output node specified by the # parameter def roc_auc_train_cov(self,vals): x = np.zeros((np.shape(self.traindata)[0],np.size(vals))) y = np.zeros((np.shape(self.traindata)[0],np.size(vals))) j = 0 for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() self.netx[self.numl - 1] = np.dot(self.covw,self.netx[self.numl - 2]) for k in range(0,np.size(vals)): if i[0] == vals[k]: x[j][k] = 1 y[j][k] = self.netx[self.numl-1][vals[k]] j = j + 1 self.train_auc = np.zeros(np.size(vals)) for k in range(0,np.size(vals)): self.train_auc[k] = sklearn.metrics.roc_auc_score(x[:,k],y[:,k]) # This function computes the roc_auc over the training set for the output node specified by the # parameter def roc_auc_test_cov(self,vals): x = np.zeros((np.shape(self.testdata)[0],np.size(vals))) y = np.zeros((np.shape(self.testdata)[0],np.size(vals))) j = 0 for i in self.testdata: self.netx[0] = i[1:] self.propagate_sigmoid() self.netx[self.numl - 1] = np.dot(self.covw,self.netx[self.numl - 2]) for k in range(0,np.size(vals)): if i[0] == vals[k]: x[j][k] = 1 y[j][k] = self.netx[self.numl-1][vals[k]] j = j + 1 self.test_auc = np.zeros(np.size(vals)) for k in range(0,np.size(vals)): self.test_auc[k] = sklearn.metrics.roc_auc_score(x[:,k],y[:,k]) # This function computes the roc_auc over the training set for the output node specified by the # parameter def roc_auc_train(self,vals): x = np.zeros((np.shape(self.traindata)[0],np.size(vals))) y = np.zeros((np.shape(self.traindata)[0],np.size(vals))) j = 0 for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() for k in range(0,np.size(vals)): if i[0] == vals[k]: x[j][k] = 1 y[j][k] = self.netx[self.numl-1][vals[k]] j = j + 1 self.train_auc = np.zeros(np.size(vals)) for k in range(0,np.size(vals)): self.train_auc[k] = sklearn.metrics.roc_auc_score(x[:,k],y[:,k]) # This function computes the roc_auc over the training set for the output node specified by the # parameter def roc_auc_test(self,vals): x = np.zeros((np.shape(self.testdata)[0],np.size(vals))) y = np.zeros((np.shape(self.testdata)[0],np.size(vals))) j = 0 for i in self.testdata: self.netx[0] = i[1:] self.propagate_sigmoid() for k in range(0,np.size(vals)): if i[0] == vals[k]: x[j][k] = 1 y[j][k] = self.netx[self.numl-1][vals[k]] j = j + 1 self.test_auc = np.zeros(np.size(vals)) for k in range(0,np.size(vals)): self.test_auc[k] = sklearn.metrics.roc_auc_score(x[:,k],y[:,k]) # This function computes the roc_auc_cov over the training set for the output node specified by the # parameter def roc_auc_train_svm(self,vals): x = np.zeros((np.shape(self.traindata)[0],np.size(vals))) y = np.zeros((np.shape(self.traindata)[0],np.size(vals))) j = 0 for i in self.traindata: self.netx[0] = i[1:] self.propagate_sigmoid() self.netx[self.numl - 1] = np.dot(self.svmw,self.netx[self.numl - 2]) for k in range(0,np.size(vals)): if i[0] == vals[k]: x[j][k] = 1 y[j][k] = self.netx[self.numl-1][vals[k]] j = j + 1 self.train_auc = np.zeros(np.size(vals)) for k in range(0,np.size(vals)): self.train_auc[k] = sklearn.metrics.roc_auc_score(x[:,k],y[:,k]) # This function computes the roc_auc over the training set for the output node specified by the # parameter def roc_auc_test_svm(self,vals): x = np.zeros((np.shape(self.testdata)[0],np.size(vals))) y = np.zeros((np.shape(self.testdata)[0],np.size(vals))) j = 0 for i in self.testdata: self.netx[0] = i[1:] self.propagate_sigmoid() self.netx[self.numl - 1] = np.dot(self.svmw,self.netx[self.numl - 2]) for k in range(0,np.size(vals)): if i[0] == vals[k]: x[j][k] = 1 y[j][k] = self.netx[self.numl-1][vals[k]] j = j + 1 self.test_auc = np.zeros(np.size(vals)) for k in range(0,np.size(vals)): self.test_auc[k] = sklearn.metrics.roc_auc_score(x[:,k],y[:,k]) ############################################################################################### # The stuff in the neuralnet class that follows this comment will be used to implement the # kernalized version of the binary classifier that optimizes the area under the roc curve. # the hypothesis h(x) given the sample x, and training vectors {x_i} is computed with: # h(x) = sum_{i=1}^{n}alpha_{i}K(x_i,x). Notice, to compute the hypothesis, we need to do the # computational equivalent of n dot products of d dimensional vectors where n is the number of # training points and d is the dimension of the training points. We will assume the user wants # the input vectors to these to be the first layer of the neuralnetwork, if the user # wants the input to be a hidden layer of the neuralnetwork, then the user must copy the hidden # layer to the first layer. To do all computations we need, at a bare minimum, the K_{i} # vectors and the K_{+} and K_{-} vectors. We may do the computations without using a lot of # memory, at the expense of computational compexity, or we may save on computational complexity # by n^2 storage (for the mnist data, for instance, this amounts to about 10Gb). In either case # we need to compute K_{-} and K_{+}. ############################################################################################### # Computes the polynomial kernel of the vector stored in self.vec1 and self.vec2 and stores the # answer into self.a1 def linear_kernel_vec(self,n,c): self.a1 = (np.dot(self.vec1,self.vec1)+c)**n # Computes the linear kernel of the vector stored in self.vec1 with every vector stored in # self.mt1 and stores the resulting vector into self.veca1 def linear_kernel_mt1(self,n,c): self.veca1 = (np.dot(self.mt1,self.vec1)+c)**n # Computes the linear kernel of every vector stored in self.mt2 with every vector stored in # self.mt1 and stores the resulting matrix into self.mta1 def linear_kernel_mt2(self,n,c): self.mta1 = (np.dot(self.mt1,self.mt2)+c)**n # Computes the polynomial kernel of the vector stored in self.vec1 and self.vec2 and stores the # answer into self.a1 def tanh_kernel_vec(self,n,c): self.a1 = np.tanh((1.0/n)*np.dot(self.vec1,self.vec1)+c) # Computes the linear kernel of the vector stored in self.vec1 with every vector stored in # self.mt1 and stores the resulting vector into self.veca1 def tanh_kernel_mt1(self,n,c): self.veca1 = np.tanh((1.0/n)*np.dot(self.mt1,self.vec1)+c) # Computes the linear kernel of every vector stored in self.mt2 with every vector stored in # self.mt1 and stores the resulting matrix into self.mta1 def tanh_kernel_mt2(self,n,c): self.mta1 = np.tanh((1.0/n)*np.dot(self.mt1,self.mt2)+c) # Computes kplus and kminus 5/6 of the training data will be used to create the alphas and # 1/6th of the data will be used to find lambda. def compute_K_plus_minus(self,n,c): # we want it to concatenate self.n = (5*np.shape(self.traindata)[0])/6; self.traintrain = self.traindata[:self.n,1:] self.mt1 = self.traintrain self.traintest = self.traindata[self.n:,1:] self.kplus = np.zeros(self.n) self.kminus = np.zeros(self.n) # we can optimize the following comptation # by using a matrix matrix multiplication to compute # all the kernals, however, that would require storing # an n by n matrix where n is the number of training # points. So instead we will have a loop of matrix vector # multiplications self.posnum = 0 self.negnum = 0 for i in range(0,self.n): # place the vector in the appropriate register self.vec1 = self.traintrain[i] # replace this operation with the desired kernal function self.linear_kernel_mt1(n,c) # if in the negative class if self.traindata[i][0] == 0: self.negnum += 1 self.kminus += self.veca1 else : self.kplus += self.veca1 self.posnum += 1 self.kminus *= 1.0/self.negnum self.kplus *= 1.0/self.posnum # Computes kplus and kminus 5/6 of the training data will be used to create the alphas and # 1/6th of the data will be used to find lambda. def compute_all_tanh(self,n,c): # we want it to concatenate self.n = (5*np.shape(self.traindata)[0])/6; self.traintrain = self.traindata[:self.n,1:] self.mt1 = self.traintrain self.traintest = self.traindata[self.n:,1:] self.mt2 = self.traintrain.T self.tanh_kernel_mt2(n,c) print np.shape(self.mta1) self.k = self.mta1 # we can optimize the following comptation # by using a matrix matrix multiplication to compute # all the kernals, however, that would require storing # an n by n matrix where n is the number of training # points. So instead we will have a loop of matrix vector # multiplications self.posnum = int(np.sum(self.traindata[:self.n,0])) self.negnum = self.n - self.posnum print self.posnum self.traintemp = np.zeros(np.shape(self.k)) self.posind = 0 self.negind = self.posnum for i in range(0,self.n): if self.traindata[i][0] == 1: self.traintemp[self.posind]=self.k[i] self.posind += 1 else : self.traintemp[self.negind] = self.k[i] self.negind += 1 print self.posind print self.negind self.kplus = (1.0/self.posnum)*(self.traintemp[:self.posnum][:]).sum(axis = 0) self.kminus = (1.0/self.negnum)*(self.traintemp[self.posnum:][:]).sum(axis = 0) print np.shape(self.kplus) self.gp = np.dot((self.traintemp[:self.posnum,:]-self.kplus).T,(self.traintemp[:self.posnum,:]-self.kplus)) self.gp = (1.0/self.posnum)*self.gp self.gm= np.dot((self.traintemp[self.posnum:,:]-self.kminus).T,(self.traintemp[self.posnum:,:]-self.kminus)) self.gm = (1.0/self.negnum)*self.gm self.g = self.gp + self.gm # Computes kplus and kminus 5/6 of the training data will be used to create the alphas and # 1/6th of the data will be used to find lambda. def compute_all(self,n,c): # we want it to concatenate self.n = (5*np.shape(self.traindata)[0])/6; self.traintrain = self.traindata[:self.n,1:] self.mt1 = self.traintrain self.traintest = self.traindata[self.n:,1:] self.mt2 = self.traintrain.T self.linear_kernel_mt2(n,c) print np.shape(self.mta1) self.k = self.mta1 # we can optimize the following comptation # by using a matrix matrix multiplication to compute # all the kernals, however, that would require storing # an n by n matrix where n is the number of training # points. So instead we will have a loop of matrix vector # multiplications self.posnum = int(np.sum(self.traindata[:self.n,0])) self.negnum = self.n - self.posnum print self.posnum self.traintemp = np.zeros(np.shape(self.k)) self.posind = 0 self.negind = self.posnum for i in range(0,self.n): if self.traindata[i][0] == 1: self.traintemp[self.posind]=self.k[i] self.posind += 1 else : self.traintemp[self.negind] = self.k[i] self.negind += 1 self.k = 0 gc.collect() print self.posind print self.negind self.kplus = (1.0/self.posnum)*(self.traintemp[:self.posnum][:]).sum(axis = 0) self.kminus = (1.0/self.negnum)*(self.traintemp[self.posnum:][:]).sum(axis = 0) print np.shape(self.kplus) self.g = (1.0/self.posnum)*np.dot((self.traintemp[:self.posnum,:]-self.kplus).T,(self.traintemp[:self.posnum,:]-self.kplus)) self.g += (1.0/self.negnum)*np.dot((self.traintemp[self.posnum:,:]-self.kminus).T,(self.traintemp[self.posnum:,:]-self.kminus)) def evaluate_alpha(self,n,c): self.mt1 = self.traintrain self.mt2 = self.traintest.T self.linear_kernel_mt2(n,c) self.h = np.dot(self.alpha,self.mta1) return sklearn.metrics.roc_auc_score(self.traindata[self.n:,0],self.h) def evaluate_alpha_tanh(self,n,c): self.mt1 = self.traintrain self.mt2 = self.traintest.T self.tanh_kernel_mt2(n,c) self.h = np.dot(self.alpha,self.mta1) return sklearn.metrics.roc_auc_score(self.traindata[self.n:,0],self.h) def compute_alpha2(self,n,c): self.roc_auc = -1 self.alpha = np.zeros(self.n) self.falpha = np.zeros(self.n) self.new_roc_auc = self.evaluate_alpha(n,c) while self.new_roc_auc >= self.roc_auc: self.falpha = self.alpha[:] self.roc_auc = self.new_roc_auc self.alpha = self.alpha - self.eta*(np.dot(self.g,self.alpha) - (self.kplus - self.kminus)) self.new_roc_auc = self.evaluate_alpha(n,c) print self.new_roc_auc def compute_alpha3(self,n,c,l): self.roc_auc = -1 self.alpha = np.dot(np.linalg.inv(.5*self.g+self.traintemp*l),(self.kplus - self.kminus)) self.new_roc_auc = self.evaluate_alpha(n,c) print self.new_roc_auc def compute_alpha(self,n,c): self.roc_auc = -1 self.alpha = np.zeros(self.n) self.new_roc_auc = self.evaluate_alpha(n,c) while self.new_roc_auc >= self.roc_auc: self.roc_auc = self.new_roc_auc self.Gpalpha = np.zeros(self.n) self.Gmalpha = np.zeros(self.n) for i in range(0,self.n): self.vec1 = self.traintrain[i] self.linear_kernel_mt1(n,c) if self.traindata[i][0] == 0: self.zp = self.veca1 - self.kplus self.Gpalpha += self.zp*np.dot(self.zp,self.alpha) elif self.traindata[i][0] == 1: self.zm = self.veca1 - self.kminus self.Gmalpha += self.zm*np.dot(self.zm,self.alpha) self.Gpalpha *= (1.0)/(self.posnum*self.posnum) self.Gmalpha *= (1.0)/(self.negnum*self.negnum) self.alpha -= self.eta*(self.Gpalpha + self.Gmalpha - self.kplus + self.kminus) self.new_roc_auc = self.evaluate_alpha(n,c) print self.new_roc_auc # This part of the code will be to try to test the idea of using neural networks # to come up with numbers of hamming distance close to an inputs smallest factor def doPrimeStuff(): from Crypto.Util import number target = open('primes.csv','w') target2 = open('primetest.csv','w') for i in range(0,6000): num1 = number.getPrime(500) num2 = number.getPrime(500) if num1 > num2: num3 = num1 num1 = num2 num2 = num3 num3 = num2*num1 target.write(str(num1)+','+str(num3)+','+str(num2)+"\n") for i in range(0,1000): num1 = number.getPrime(500) num2 = number.getPrime(500) if num1 > num2: num3 = num1 num1 = num2 num2 = num3 num3 = num2*num1 target2.write(str(num1)+','+str(num3)+','+str(num2)+"\n") target.close() target2.close() s = Neuralnet([1000,500,500],'primes.csv','primetest.csv') target = open('primes.csv','r') index = 0 s.traindata = [] s.testdata = [] for i in target: s.traindata.append(i.split(",")) index += 1 target.close() target = open('primetest.csv') index = 0 for i in target: s.testdata.append(i.split(",")) target.close() count = 0 secount = 0 for i in s.traindata: for j in i: s.traindata[count][secount] = [] s.traindata[count][secount] = np.array([int(x) for x in bin(long(j))[2:]]) secount += 1 count += 1 secount = 0 count = 0 secount = 0 for i in s.testdata: for j in i: s.testdata[count][secount] = [] s.testdata[count][secount] = np.array([int(x) for x in bin(long(j))[2:]]) secount += 1 count += 1 secount = 0 s.target = np.zeros((7000,500)) for i in range(0,6000): s.target[i,500-np.size(s.traindata[i][0]):] = s.traindata[i][0] for i in range(0,1000): s.target[i+6,500-np.size(s.testdata[i][0]):] = s.testdata[i][0] s.target2 = np.zeros((7000,500)) for i in range(0,6000): s.target2[i,500-np.size(s.traindata[i][2]):] = s.traindata[i][2] for i in range(0,1000): s.target2[i+6,500-np.size(s.testdata[i][2]):] = s.testdata[i][2] s.traindata2 = np.zeros((6000,1000)) for i in range(0,6000): s.traindata2[i,1000-np.size(s.traindata[i][1]):] = s.traindata[i][1] s.testdata2 = np.zeros((1000,1000)) for i in range(0,1000): s.testdata2[i,1000-np.size(s.testdata[i][1]):] = s.testdata[i][1] s.traindata = s.traindata2 s.testdata = s.testdata2 return s # Removes NANs and stores percent differences def prepnan(): data = (pd.read_csv('MV1E0081c.csv',',',header=None)).values; i = np.shape(data)[0]-1; for j in range(1,i): for k in range(0,np.shape(data)[1]): if math.isnan(float(data[i-1][k])): data[i-1][k] = data[i][k]; if ((float(data[i-1][k]) <= .0001) and (float(data[i-1][k]) >= -.0001)): print "here"; data[i-1][k] = data[i][k]; i = i - 1; print np.argmin(data[1:][:].astype(float)); for j in range(1,np.shape(data)[0]-1): data[j][:] = 100*255*np.divide((data[j+1][:].astype(float) - data[j][:].astype(float)),data[j][:].astype(float)); np.savetxt('prepreped.csv',data,delimiter=',',fmt='%s'); # more preprocessing def prep(): data = (pd.read_csv('prepreped.csv',',',header=None)).values; output = np.zeros((np.shape(data)[0]-10,np.shape(data)[1]*10+1)); i = 1; for row in output: for j in range(0,10): output[i-1][1+j*(np.shape(data)[1]):1+(j+1)*(np.shape(data)[1])]=data[:][i+j]; i = i + 1; for i in range(0,np.shape(output)[0]-1): output[i][0] = np.nanargmax(output[i+1][-122:]); np.savetxt('training.csv',output[0:3000][:],delimiter=',',fmt='%f'); np.savetxt('testing.csv',output[3001:][:],delimiter=',',fmt='%f'); # more preprocessing def prep2(): data = (pd.read_csv('prepreped.csv',',',header=None)).values; output = np.zeros((np.shape(data)[0]-10,np.shape(data)[1]*10+1)); i = 1; for row in output: for j in range(0,10): output[i-1][1+j*(np.shape(data)[1]):1+(j+1)*(np.shape(data)[1])]=data[:][i+j]; i = i + 1; for i in range(0,np.shape(output)[0]-1): output[i][0] = i; np.savetxt('training.csv',output[0:3000][:],delimiter=',',fmt='%f'); np.savetxt('testing.csv',output[3001:][:],delimiter=',',fmt='%f'); # assumes there are no skipped months def preprocesstr(): monthAr1 = [30]*12; monthAr1[0] = 31; monthAr1[1] = 28; monthAr1[2] = 31; monthAr1[4] = 31; monthAr1[6] = 31; monthAr1[7] = 31; monthAr1[9] = 31; monthAr1[11] = 31; monthAr2 = monthAr1[:]; monthAr2[1] = 29; print(monthAr1); print(monthAr2); data = pd.read_csv('MV1E0081.csv',',',header=None); increment = 0; last = data[0][1]; output = np.zeros(np.size(data[0][1:])); for row in data[0][1:]: if (increment == 0): output[increment] = 0; else: if (int(row[9:11]) == int(last[9:11])) and (int(row[0:4]) == int(last[0:4])): tempdate = data[0][increment+1]; output[increment] = output[increment-1] + int(row[16:18]) - int(last[16:18]); last = tempdate; elif (int(row[0:4])%4 != 0): tempdate = data[0][increment+1]; output[increment] = output[increment-1] + monthAr1[int(last[9:11])-1] - int(last[16:18]) + int(row[16:18]); last = tempdate; elif (int(row[0:4])%4 == 0) : tempdate = data[0][increment+1]; output[increment] = output[increment-1] + monthAr2[int(last[9:11])-1] - int(last[16:18]) + int(row[16:18]); last = tempdate; increment = increment + 1; output = output.astype(int); np.savetxt('output.csv',output,delimiter=',',fmt='%d'); def stockStuff(): import copy stocks = Neuralnet([1231,200,123],'training.csv','testing.csv'); stocks.testdatacopy = copy.copy(stocks.testdata); stocks.traindatacopy = copy.copy(stocks.traindata); for i in range(0,1): stocks.shuffle(); stocks.stochastic_gradient_sigmoid(); stocks.total = 1; i = 0; for j in stocks.testdatacopy: stocks.netx[0] = j[1:]; stocks.propagate_sigmoid(); ## calculates the delta for the last layer #stocks.netd[-1] = stocks.netx[-1]*(1-stocks.netx[-1])*(stocks.target[int(j[0])]-stocks.netx[-1]) ## calculates the delta for all other layers #stocks.netd[-2] = stocks.netx[-2]*(1-stocks.netx[-2])*(np.dot(stocks.netw[-1].T,stocks.netd[-1])) #for j in range(0,stocks.numl-2): # stocks.netd[-j-3] = stocks.netx[-j-3]*(1-stocks.netx[-j-3])*(np.dot(stocks.netw[-j-2].T,stocks.netd[-j-2][:-1])) # # Now we update all of the weights based on the deltas, etas, and alphas #for j in range(0,stocks.numl-2): # # computes the momentum including delta w # stocks.netwd[j] = stocks.eta*np.outer(stocks.netd[j+1][:-1],stocks.netx[j]) + stocks.alpha*stocks.netwd[j] # # updates the weights # stocks.netw[j] = stocks.netw[j] + stocks.netwd[j] ## computes the momentum including delta w #stocks.netwd[-1] = stocks.eta*np.outer(stocks.netd[-1],stocks.netx[-2]) + stocks.alpha*stocks.netwd[-1] ## updates the weights #stocks.netw[-1] = stocks.netw[-1] + stocks.netwd[-1] temp = stocks.netx[2].argsort()[-4:]; print temp; const = 0; for k in temp: const = const + stocks.netx[2][k]; ans = 0; for k in temp: ans = ans + (stocks.netx[2][int(k)]*stocks.testdatacopy[i+10][int(k)+2]/const)/100; if (ans < .5) and (ans > -.5): stocks.total = stocks.total*(1+ans); print stocks.testdatacopy[i][0]; print ans; i = i + 1; if (i > np.shape(stocks.testdatacopy)[0] -20): return stocks; return stocks; def stockStuff_2p(): import copy stocks = Neuralnet([1231,200,123],'training.csv','testing.csv'); stocks.testdatacopy = copy.copy(stocks.testdata); stocks.traindatacopy = copy.copy(stocks.traindata); # creates the target matrix and destroys the last testing datapoint stocks.target = np.ones((np.shape(stocks.traindata)[0]+np.shape(stocks.testdata)[0]-1,123))*.1; for i in range(0,np.shape(stocks.target)[0]): if (i < np.shape(stocks.traindata)[0] - 2): for j in range(0,123): if (stocks.traindata[i+1][-123+j] > 1): stocks.target[i][j] = .9; if (i >= np.shape(stocks.traindata)[0] - 2): for j in range(0,123): if (stocks.testdata[i - np.shape(stocks.traindata)[0]][-123+j] > 1): stocks.target[i][j] = .9; for i in range(0,10): stocks.shuffle(); stocks.stochastic_gradient_sigmoid(); stocks.total = 1; i = 0; for j in stocks.testdatacopy: stocks.netx[0] = j[1:]; stocks.propagate_sigmoid(); temp = stocks.netx[2].argsort()[-4:]; print temp; const = 0; for k in temp: const = const + stocks.netx[2][k]; ans = 0; for k in temp: ans = ans + (stocks.netx[2][int(k)]*stocks.testdatacopy[i+10][int(k)+2]/const)/100; if (ans < .5) and (ans > -.5): stocks.total = stocks.total*(1+ans); print ans; print stocks.total; i = i + 1; if (i > np.shape(stocks.testdatacopy)[0] -20): return stocks; return stocks; def stockStuff_3p(): import copy stocks = Neuralnet([1231,200,123],'training.csv','testing.csv'); stocks.testdatacopy = copy.copy(stocks.testdata); stocks.traindatacopy = copy.copy(stocks.traindata); # creates the target matrix and destroys the last testing datapoint stocks.target = np.zeros((np.shape(stocks.traindata)[0]+np.shape(stocks.testdata)[0]-1,123)); for i in range(0,np.shape(stocks.target)[0]): if (i < np.shape(stocks.traindata)[0] - 1): for j in range(0,123): if (stocks.traindata[i+1][-123+j] > 2): stocks.target[i][j] = 1; if (i >= np.shape(stocks.traindata)[0] - 1): for j in range(0,123): if (stocks.testdata[i - np.shape(stocks.traindata)[0]][-123+j] > 2): stocks.target[i][j] = 1; for i in range(0,20): stocks.shuffle(); stocks.stochastic_gradient_sigmoid(); stocks.total = 1; i = 0; for j in stocks.testdatacopy: if (i % 20 == 0) and (i != 0): stocks.traindata = copy.copy(stocks.traindatacopy); stocks.traindata[0:i] = copy.copy(stocks.testdata[0:i]); stocks.rand_weights(); for zk in range(0,20): stocks.shuffle(); stocks.stochastic_gradient_sigmoid(); stocks.netx[0] = j[1:]; stocks.propagate_sigmoid(); temp = stocks.netx[2].argsort()[-4:]; print temp; const = 0; for k in temp: const = const + stocks.netx[2][k]; ans = 0; for k in temp: ans = ans + (stocks.netx[2][int(k)]*stocks.testdatacopy[i+10][int(k)+2]/const)/100; if (ans < .5) and (ans > -.5): stocks.total = stocks.total*(1+ans); print ans; print stocks.total; i = i + 1; if (i > np.shape(stocks.testdatacopy)[0] -20): return stocks; return stocks; def stockStuff_5(): import copy stocks = Neuralnet([1231,200,123],'training.csv','testing.csv'); stocks.testdatacopy = copy.copy(stocks.testdata); stocks.traindatacopy = copy.copy(stocks.traindata); stocks2 = Neuralnet([1231,200,123],'training.csv','testing.csv'); stocks2.testdatacopy = copy.copy(stocks2.testdata); stocks2.traindatacopy = copy.copy(stocks2.traindata); # creates the target matrix and destroys the last testing datapoint stocks.target = np.ones((np.shape(stocks.traindata)[0]+np.shape(stocks.testdata)[0]-1,123))*.1; for i in range(0,np.shape(stocks.target)[0]): if (i < np.shape(stocks.traindata)[0] - 2): for j in range(0,123): if (stocks.traindata[i+1][-123+j] > 2): stocks.target[i][j] = 1; if (i >= np.shape(stocks.traindata)[0] - 2): for j in range(0,123): if (stocks.testdata[i - np.shape(stocks.traindata)[0]][-123+j] > 2): stocks.target[i][j] = 1; stocks2.target = np.ones((np.shape(stocks2.traindata)[0]+np.shape(stocks2.testdata)[0]-1,123))*.1; for i in range(0,np.shape(stocks2.target)[0]): if (i < np.shape(stocks2.traindata)[0] - 2): for j in range(0,123): if (stocks2.traindata[i+1][-123+j] < -1): stocks2.target[i][j] = 1; if (i >= np.shape(stocks2.traindata)[0] - 2): for j in range(0,123): if (stocks2.testdata[i - np.shape(stocks2.traindata)[0]][-123+j] < -1): stocks2.target[i][j] = 1; for i in range(0,10): stocks.shuffle(); stocks.stochastic_gradient_sigmoid(); for i in range(0,10): stocks2.shuffle(); stocks2.stochastic_gradient_sigmoid(); stocks.total = 1; i = 0; for j in stocks.testdatacopy: stocks.netx[0] = j[1:]; stocks2.netx[0] = j[1:]; stocks.propagate_sigmoid(); stocks2.propagate_sigmoid(); temp = (stocks.netx[2] - stocks2.netx[2]).argsort()[-4:]; print temp; const = 0; for k in temp: const = const + (stocks.netx[2][k] - stocks2.netx[2][k]); ans = 0; for k in temp: ans = ans + ((stocks.netx[2][int(k)] - stocks2.netx[2][k])*stocks.testdatacopy[i+10][int(k)+2]/const)/100; if (ans < .5) and (ans > -.5): stocks.total = stocks.total*(1+ans); print ans; print stocks.total; i = i + 1; if (i > np.shape(stocks.testdatacopy)[0] -20): return stocks; return stocks; def stockStuff_6(): import copy stocks = Neuralnet([1231,200,123],'training.csv','testing.csv'); stocks.testdatacopy = copy.copy(stocks.testdata); stocks.traindatacopy = copy.copy(stocks.traindata); # creates the target matrix and destroys the last testing datapoint stocks.target = np.ones((np.shape(stocks.traindata)[0]+np.shape(stocks.testdata)[0]-1,123))*.1; for i in range(0,np.shape(stocks.target)[0]): if (i < np.shape(stocks.traindata)[0] - 2): for j in range(0,123): if ((stocks.traindata[i+1][-123+j] > 2) and (stocks.traindata[i+1][-123+j] < 20)): stocks.target[i][j] = 1; if (i >= np.shape(stocks.traindata)[0] - 2): for j in range(0,123): if ((stocks.testdata[i - np.shape(stocks.traindata)[0]][-123+j] > 2) and stocks.testdata[i-np.shape(stocks.traindata)[0]][-123+j] < 20): stocks.target[i][j] = 1; for i in range(0,10): stocks.shuffle(); stocks.stochastic_gradient_sigmoid(); stocks.total = 1; i = 0; temptotal = stocks.total; tempweights = copy.copy(stocks.netw); for k in range(0,10): stocks.netx[0] = stocks.testdatacopy[k][1:]; stocks.propagate_sigmoid(); temp = stocks.netx[2].argsort()[-4:]; print temp; const = 0; for k in temp: const = const + stocks.netx[2][k]; ans = 0; for k in temp: ans = ans + (stocks.netx[2][int(k)]*stocks.testdatacopy[i+10][int(k)+2]/const)/100; if (ans < .5) and (ans > -.5): stocks.total = stocks.total*(1+ans); print ans; print stocks.total; i = i + 1; print "test1"; while (stocks.total < 1.10): if stocks.total < temptotal: stocks.netw = copy.copy(tempweights); stocks.total = temptotal; else : tempweights = copy.copy(stocks.netw); temptotal = stocks.total; for i in range(0,1): stocks.shuffle(); stocks.stochastic_gradient_sigmoid(); stocks.total = 1; i = 0; for k in range(0,10): stocks.netx[0] = stocks.testdatacopy[k][1:]; stocks.propagate_sigmoid(); temp = stocks.netx[2].argsort()[-4:]; print temp; const = 0; for k in temp: const = const + stocks.netx[2][k]; ans = 0; for k in temp: ans = ans + (stocks.netx[2][int(k)]*stocks.testdatacopy[i+10][int(k)+2]/const)/100; if (ans < .5) and (ans > -.5): stocks.total = stocks.total*(1+ans); print ans; print stocks.total; print "test"; i = i + 1; print "out of test"; stocks.total = 1; i = 0; for j in stocks.testdatacopy: if (i % 20 == 19): print "month"; stocks.netx[0] = j[1:]; stocks.propagate_sigmoid(); temp = stocks.netx[2].argsort()[-4:]; print temp; const = 0; for k in temp: const = const + stocks.netx[2][k]; ans = 0; for k in temp: ans = ans + (stocks.netx[2][int(k)]*stocks.testdatacopy[i+10][int(k)+2]/const)/100; if (ans < .5) and (ans > -.5): stocks.total = stocks.total*(1+ans); print ans; print stocks.total; i = i + 1; if (i > np.shape(stocks.testdatacopy)[0] -20): return stocks; return stocks; def stockStuff_7(): import copy stocks = Neuralnet([1231,200,123],'training.csv','testing.csv'); stocks.testdatacopy = copy.copy(stocks.testdata); stocks.traindatacopy = copy.copy(stocks.traindata); # creates the target matrix and destroys the last testing datapoint stocks.target = np.ones((np.shape(stocks.traindata)[0]+np.shape(stocks.testdata)[0]-1,123))*.1; for i in range(0,np.shape(stocks.target)[0]): if (i < np.shape(stocks.traindata)[0] - 2): for j in range(0,123): if ((stocks.traindata[i+1][-123+j] > 2) and (stocks.traindata[i+1][-123+j] < 20)): stocks.target[i][j] = 1; if (i >= np.shape(stocks.traindata)[0] - 2): for j in range(0,123): if ((stocks.testdata[i - np.shape(stocks.traindata)[0]][-123+j] > 2) and stocks.testdata[i-np.shape(stocks.traindata)[0]][-123+j] < 20): stocks.target[i][j] = 1; closest = np.zeros((20,2)); prediction = np.zeros(123); i = 0; stocks.total = 1; for j in stocks.testdata: for k in stocks.traindata: temp = np.inner(j[1:],k[1:])/(np.linalg.norm(j[1:])*np.linalg.norm(k[1:])); if temp > closest[-1][0]: for l in range(0,20): if temp > closest[i][0]: for t in range(-2,i-20): closest[t+1] = closest[t]; closest[l][0] = temp; closest[l][1] = k[0]; break; for q in closest: prediction += stocks.target[int(q[1])]; temp = prediction.argsort()[-4:]; print temp; const = 0; for q in temp: const = const + stocks.netx[2][q]; ans = 0; for q in temp: ans = ans + (prediction[int(q)]*stocks.testdatacopy[i+10][int(q)+2]/const)/100; if (ans < .5) and (ans > -.5): stocks.total = stocks.total*(1+ans); print ans; print stocks.total; i = i + 1; if (i > np.shape(stocks.testdatacopy)[0] -20): return stocks; def tempstuff(): import matplotlib.pyplot as plt data = (pd.read_csv('prepreped.csv',',',header=None)).values; ourdata = data[1:,1].astype('float'); length = np.size(ourdata); convolution = np.zeros((length,length)); for i in range(0,length): for j in range(0,length): convolution[i][j] = ourdata[i]*ourdata[j]; stdard = np.std(convolution); print stdard; for i in range(0,length): for j in range(0,length): if np.abs(convolution[i][j]) > stdard: if convolution[i][j] > 0: convolution[i][j] = stdard; else: convolution[i][j] = -stdard; plt.imshow(convolution, cmap='hot',interpolation='nearest') plt.show() return convolution; # Creates a csv file called mnist_train_#.csv where # is num # that is exactly the same as mnist_train.csv except the expected # value of each row is one if the row is num, and zero otherwise. def create_mnist_binary_train(num): with open('../mnist_train.csv') as csvfile: trainreader = csv.reader(csvfile, delimiter=',', quotechar='|') csvwrite = open('../mnist_train_'+str(num)+'.csv','w'); csvwriter = csv.writer(csvwrite,delimiter=',',quotechar="|",quoting=csv.QUOTE_MINIMAL) for row in trainreader: if int(row[0]) == num: row[0] = '1' else : row[0] = '0' csvwriter.writerow(row) csvwrite.close(); # Creates a csv file called mnist_train_#.csv where # is num # that is exactly the same as mnist_train.csv except the expected # value of each row is one if the row is num, and zero otherwise. def create_mnist_binary_minitrain(num): with open('../mnist_train.csv') as csvfile: trainreader = csv.reader(csvfile, delimiter=',', quotechar='|') csvwrite = open('../mnist_minitrain_'+str(num)+'.csv','w'); csvwriter = csv.writer(csvwrite,delimiter=',',quotechar="|",quoting=csv.QUOTE_MINIMAL) num = 6000; for row in trainreader: if int(row[0]) == num: row[0] = '1' else : row[0] = '0' csvwriter.writerow(row) num -= 1 if num == 0: break csvwrite.close(); # Creates a csv file called mnist_test_#.csv where # is num # that is exactly the same as mnist_test.csv except the expected # value of each row is one if the row is num, and zero otherwise. def create_mnist_binary_test(num): with open('../mnist_test.csv') as csvfile: trainreader = csv.reader(csvfile, delimiter=',', quotechar='|') csvwrite = open('../mnist_test_'+str(num)+'.csv','w'); csvwriter = csv.writer(csvwrite,delimiter=',',quotechar="|",quoting=csv.QUOTE_MINIMAL) for row in trainreader: if int(row[0]) == num: row[0] = '1' else : row[0] = '0' csvwriter.writerow(row) csvwrite.close(); # small binary classifier test def small_test(): output = open("mnist_09_1_11_0_10_test.csv","w") for i in range(0,10): mn = Neuralnet([785,1],"mnist_train_"+str(i)+".csv","mnist_test_"+str(i)+".csv") mn.traindata = mn.traindata[:12000][:] for j in range(1,11): for k in range(0,10): mn.compute_all(j,k) s = str(i)+","+str(j)+","+str(k)+","+str(mn.compute_alpha3(j,k,0)) mn.mt2 = (mn.testdata[:,1:]).T mn.linear_kernel_mt2(j,k) mn.h = np.dot(mn.alpha,mn.mta1) s += str(sklearn.metrics.roc_auc_score(mn.testdata[:,0],mn.h)) print s output.write(s) output.close()
c7b7e889a0be44893d49b0aff09711340d7af055
clevelandhighschoolcs/p4mawpup-DexterCarpenter
/Versions/WebScraper8.py
4,232
3.53125
4
# # Web Scraper # Version: 8 """ cd C:\Users\Dexter Carpenter\Documents\GitHub\WebScraper\environment c:\Python27\Scripts\virtualenv.exe -p C:\Python27\python.exe .lpvenv .lpvenv\Scripts\activate # on at home computer: cd C:\Users\dexte\Documents\GitHub\WebScraper\environment """ # import libraries import sys import urllib2 try: from bs4 import BeautifulSoup except Exception as e: print "Are you sure you have BeautifulSoup installed?" print "Type 'pip install BeautifulSoup4' in the terminal to install it." sys.exit() import time from twilio.rest import Client #variables global tagcountnow global tagcountold global scrape_interval global Twillo_null #a variable that will determine the functionality of Twillo in this program Twillo_null = False global account_sid global auth_token global twilio_phone_number global my_phone_number print '' print "Press 'Ctrl + C' to exit the Scraper" # specify the url print 'Enter what website you want to scrape:' quote_page = raw_input() try: webUrl = urllib2.urlopen(quote_page) if(webUrl.getcode() == 200): quote_page = '%s' %quote_page else: code = webUrl.getcode() except Exception: quote_page = raw_input('Enter a valid website: ') print '' print 'How often do you want to scrape the webpage? (seconds)' scrape_interval = raw_input() print '' #These next 20 lines have to do with Twillo and allowing that to work print ' ' print "Would you like me to send you a text message when I find a change(y/n)? (You will need to gave a twillo number for this to work.)" txtmessage = raw_input() if txtmessage == "y": print ' ' print 'Enter your account SID (all of the following can be obtained on your Twillo dashboard)' account_sid = raw_input() print ' ' print 'Enter your authentification token' auth_token = raw_input() print ' ' print 'Enter your Twillo phone number' twilio_phone_number = raw_input() if (twilio_phone_number[:2] != "+1"): #this ensures a "+1" is given at the beginning of the phone number twilio_phone_number = "+1" + twilio_phone_number print ' ' print "Enter your own phone number" my_phone_number = raw_input() if (my_phone_number[:2] != "+1"): #this ensures a "+1" is given at the beginning of the phone number my_phone_number = "+1" + my_phone_number #This makes sure that the info inputted is valid, if not, it skips this part. if (len(account_sid) != 34) or (len(auth_token) != 32) or (len(twilio_phone_number) != 12) or (len(my_phone_number) != 12) or (twilio_phone_number[:2] != "+1") or (my_phone_number[:2] != "+1"): Twillo_null = True #if this is triggered, the program will refrain from doing anything with the information given above else: Twillo_null = True print 'The Scraper will check the number of tags in the webpage.' print 'The Scraper will display "Change!" if the number of tags has changed from the previous scan.' print '' print 'Scraping...' #get the initial count for tags def initial(): global tagcountnow global tagcountold # query the website and return the html to the variable page page = urllib2.urlopen(quote_page) # parse the html using beautiful soup and store in variable 'soup' soup = BeautifulSoup(page, 'html.parser') #find number of tags tagcountold = len(soup.find_all()) if __name__ == "__main__": initial() def scraper(): global tagcountnow global tagcountold global Twillo_null global account_sid global auth_token global twilio_phone_number global my_phone_number # query the website and return the html to the variable page page = urllib2.urlopen(quote_page) # parse the html using beautiful soup and store in variable 'soup' soup = BeautifulSoup(page, 'html.parser') #find number of tagss tagcountnow = len(soup.find_all()) if tagcountnow == tagcountold: print 'No Change' body = 'No Change' elif tagcountnow != tagcountold: print 'Change!' body = 'Change!' tagcountold = tagcountnow #This sends the message to your phone if Twillo_null == False: client = Client(account_sid, auth_token) client.messages.create( body=body, to=my_phone_number, from_=twilio_phone_number ) while True: if __name__ == "__main__": scraper() time.sleep(float(scrape_interval))
9fe11203587e6965eef579ea703cb422698b8c42
Jhangsy/ta_eval
/func.py
501
3.59375
4
# -*- coding: utf-8 -*- character_dict = "E:/ta_eval/character_dict.txt" kungfu_dict = "E:/ta_eval/kungfu_dict.txt" def split_name(character_name,kungfu_name): character = open(character_dict).read() kungfu = open(kungfu_dict).read() with open("name_dic.txt","wb") as outfile: outfile.write(kungfu) outfile.write(character.replace("、","\n").replace(")","").replace("(","\n") .replace(":","\n")) print outfile split_name(character_dict, kungfu_dict)
7cf3636502de6a1c38dab9a7dd890cdff3f35e1a
montlebalm/euler
/python/problems/problem4.py
819
4.0625
4
""" Question: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. Answer: 906609 """ from helpers.timer import print_timing def is_palindrome(num): digits = str(num) return digits == digits[::-1] @print_timing def problem4(digits): highest_val = int("9" * digits) lowest_val = 10 ** (digits - 1) p1 = p2 = highest_val largest_palindrome = 0 while p1 >= lowest_val and p2 >= lowest_val: p1 -= 1 product = p1 * p2 if product > largest_palindrome and is_palindrome(product): largest_palindrome = product # Reset if p1 == lowest_val: p2 -= 1 p1 = 999 return largest_palindrome if __name__ == "__main__": print(problem4(3))
3fd212cf4b006b196aa8d5ff387b1d6295f491d2
JaiminBhagat5021/CyberstormGriffin
/Binary.py
1,367
3.953125
4
########################################################################################### # Name: Jaimin Bhagat # Date: 3/23/2020 # Description: Binary Decoder for Bits evenly divisible by 7 and 8(Done in Python 2.7.17) ########################################################################################### from sys import stdin #standard input library def decode(binary, n): #takes binary and some number of bits as parameters text = "" i = 0 while(i < len(binary)): byte = binary[i:i+n] #Isolate a byte with n number of bits byte = int(byte, 2) #convert each byte of 1's and 0's to int in base 2 if(byte == 8): #if character is a backspace text = text[:-1] #remove last character of the string stored in text else: text += chr(byte) #convert each ASCII value to its character version i += n return text #read input and get rid of the new line and store it in a variable binary = stdin.read().rstrip("\n") if(len(binary) %7 == 0): #length of binary is evenly divisible by 7 text = decode(binary, 7) #get the result of decode function and store it in text print "7-bit:" print text if(len(binary) %8 == 0): #length of binary is evenly divisible by 8 text = decode(binary, 8) #get the result of deocde function and store it in text print "8-bit:" print text
d922663c4e172e8bd321644ea934378a76541303
navdeepbeniwal16/Daily-Coding-Problem
/Python Solutions/day2.py
1,145
3.984375
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Uber. Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. Follow-up: what if you can't use division? """ def findProduct(arr): arrLen = len(arr) if arrLen == 0: return 0 leftArr = [None] * arrLen rightArr = [None] * arrLen resultArr = [None] * arrLen leftArr[0] = 1 rightArr[-1] = 1 # Forward pass for left products for i in range(1, arrLen): leftArr[i] = leftArr[i-1] * arr[i-1] # Backward pass for right products for i in range(len(array)-2, -1, -1): rightArr[i] = rightArr[i+1] * arr[i+1] for i in range(arrLen): resultArr[i] = leftArr[i] * rightArr[i] return resultArr array = [1, 2, 3, 4, 5] resultArray = findProduct(array) print(resultArray)
11c1b46b320c8c0ca2337654870c759456591a46
liqima/Machine_Learning_books
/kaggle竞赛之路/classification/decisontree.py
1,170
3.5
4
# obtain the dataset import pandas as pd titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt') #titanic.info() #print(titanic.head()) # preprocessing x = titanic[['pclass', 'age', 'sex']] y = titanic['survived'] x['age'].fillna(x['age'].mean(), inplace = True) # add data for age feature #x.info() # split from sklearn.cross_validation import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=33) # feature extraction from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer(sparse = False) x_train = vec.fit_transform(x_train.to_dict(orient = 'record')) #print(vec.feature_names_) x_test = vec.transform(x_test.to_dict(orient = 'record')) # import decision tree model from sklearn.tree import DecisionTreeClassifier dtc = DecisionTreeClassifier() dtc.fit(x_train, y_train) y_predict = dtc.predict(x_test) # report from sklearn.metrics import classification_report print('the accuracy is ', dtc.score(x_test, y_test)) print(classification_report(y_predict, y_test, target_names = ['died', 'survived']))
570bf9388c854f5084b9d9c783314be0117433ee
deepikasr03/python-basic-examples
/hello.py
295
3.65625
4
#defining a function called say_hello .This function takes no parameters.and hence there are no variable #declared in the parenthesis. def say_hello(): print("hello world") #calling the function twice.This means there is no neccesity to write the same code twice. say_hello() say_hello()
9160bbad83029a80b5d5ee2e66c0ba3ab72d5cc1
radomirbrkovic/algorithms
/matrices/row-wise-sorting-2d-array.py
411
4.15625
4
# Row wise sorting in 2D array https://www.geeksforgeeks.org/row-wise-sorting-2d-array/ def sortRowWise(matrix): for i in range(len(matrix)): matrix[i].sort() for i in range(len(matrix)): for j in range(len(matrix[i])): print(matrix[i][j], end=" ") print() sortRowWise([ [9, 8, 7, 1 ], [7, 3, 0, 2], [9, 5, 3, 2], [ 6, 3, 1, 2 ] ])
046002906d814aa4229f3185b8fc9e5c666591b6
veratsurkis/enjoy_sleeping
/ex1_2.py
149
3.671875
4
import turtle as tr from random import * tr.shape('turtle') for i in range(100): tr.forward(randint(10,100)) tr.right(randint(0,360))
8822bd05b3c007f28646074bcb20e8abe4eafe17
Mehulagrawal710/learnings
/python/algorithms/merge_set_of_ranges.py
341
3.84375
4
def merge(l): l.sort() merged = [l[0]] for x in l: a = merged[-1][0] b = merged[-1][1] c = x[0] d = x[1] ########################### if d>b: if c>b: merged.append(x) else: merged[-1][1] = d ########################### return merged print(merge([[2, 4], [1, 2], [3, 5]])) print(merge([[2,3],[1,3],[5,8],[4,6],[5,7]]))
5506cb76e56bfcdcabe675561b41ff755e3736b3
Lolita88/GenomeSequencing
/k_universal_circular_string_problem.py
4,030
3.59375
4
# Function finds a universal circular string in binary numbers # example uses eight binary 3-mers (000, 001, 011, 111, 110, 101, 010, and 100) exactly once # output is 00011101 from copy import deepcopy from random import randint import random, sys import itertools def k_universal_circular_string_problem(k): # get length of a binary (k)mer # if k == 3, then length is 8, 8 binary 3-mers possible # if k == 4, then there would be 16 # The only thing we need to do is solve the k-Universal Circular String Problem # is to find an Eulerian cycle in DeBruijn(BinaryStringsk). Note that the nodes # of this graph represent all possible binary (k - 1)-mers. A directed edge # connects (k - 1)-mer Pattern to (k - 1)-mer Pattern' in this graph if there # exists a k-mer whose prefix is Pattern and whose suffix is Pattern'. # turn k into binary version of kmers # itertools.product - cartesian product of input iterables., equivalent to a nested for-loop # product(range(2), repeat=3) or can use product([0,1], ...) lst = [list(i) for i in itertools.product([0, 1], repeat=k)] binary_list = [] for each in lst: binary_list.append(''.join(map(str, each))) de_bruijn = de_bruijn_graph_from_kmers(binary_list) eulerian = find_eulerian_cycle(de_bruijn) genome = genome_path_from_eulerian_path(eulerian) return genome def de_bruijn_graph_from_kmers(kmers): adjacency_list = {} kmers.sort() for i in range(len(kmers)): pre = kmers[i][0:-1] suf = kmers[i][1:] if(pre[1:] == suf[:-1]): #add to dict for output if pre in adjacency_list.keys(): # if already there, append adjacency_list[pre] += ("," + suf) else: # write anew adjacency_list[pre] = pre + " -> " + suf return adjacency_list.values() def find_eulerian_cycle(my_list): #create adj my_list - key/value pairs # keys are the pre, values are the sufs they can point to adj_list, circuit_max = create_adjacency_my_list(my_list) #reduced adj my_list to keep track of traveled edges red_adj_list = {} red_adj_list = deepcopy(adj_list) #exact copy of dict #arbitrary starting point (if graph is directed/balanced) start = random.choice(list(my_list)) start = start.split(" ") start = start[0] curr_vert = start stack = [] circuit = [] while len(circuit) != circuit_max: if red_adj_list[curr_vert] != []: #if neighbor nodes exist stack.append(curr_vert) pick = randint(0,len(red_adj_list[curr_vert])-1) #what is pick? temp = deepcopy(curr_vert) #why use deepcopy curr_vert = red_adj_list[temp][pick] red_adj_list[temp].remove(curr_vert) else: circuit.append(curr_vert) curr_vert = stack[len(stack)-1] stack.pop() #formatting path = start + '->' path = "" for vert in circuit[::-1]: path += (vert + '->') return path def create_adjacency_my_list(my_list): adj_list = {} circuit_max = 0 for line in my_list: node = line.strip('\n') node = node.replace(' -> ', ' ') node = node.split(' ') adj_list.setdefault(node[0],[]) #adj my_list gets the start of the node pair(ie. first num) for num in node[1].split(','): #num gets assigned the end node of the pair. Split on comma needed when multiple end nodes adj_list[node[0]].append(num) circuit_max += 1 return adj_list, circuit_max def genome_path_from_eulerian_path(eulerian_path): # takes in something like this GGC->GCT->CTT->TTA->TAC->ACC->CCA # returns a genome sequence like this GGCTTACCA kmers = eulerian_path.split("->") genome = "" for i in range(len(kmers)): genome = genome[:i] + kmers[i] return genome #k = 4 k = sys.stdin print(k_universal_circular_string_problem(k)) # sample output for binary 4mer: 0000110010111101
960225f77054ce48a9a52a3a2a550c91391dcfae
MPankajArun/Python-Proctice-Examples
/Day 4/RegexDemo-findall.py
603
3.609375
4
import re patt =r"PSL" s1 = "PSLaaa welcome to Pune. PSL PErsistyent ..." s2 = "Welcome to PSL ... Good Morning PSL" m = re.findall(patt,s1) #print "m = ",m if m != None: #match start search begining of line from first character print patt ,"Occures " ,len(m) ,"time" print "Match found as = ",m else: print "Match not found" print "---------------------------------------------------------------" print re.findall("car","car") print re.findall("car","scary") print re.findall("car","carry the tarcardi to the car") print "---------------------------------------------------------------"
fa9c0a49375e63526af795222ccd459e9c3bc3bd
AR123456/python-deep-dive
/work-from-100-days/Intermediate days 15-100/Day-32/Birthday-wisher-v2-datetime-module/main.py
214
3.515625
4
import datetime as dt now = dt.datetime.now() year = now.year month = now.month day_of_week = now.weekday() print(day_of_week) date_of_birth = dt.datetime(year=1995, month=12, day=15, hour=4) print(date_of_birth)
1fec54c7c2a05270e2656c481bf1b0c248219cea
cstrahan/python_practice
/coding_bat/warmup_1/pos_neg.py
959
3.53125
4
import pytest # Given 2 int values, return True if one is negative and one is positive. # Except if the parameter "negative" is True, then return True only if both are # negative. def pos_neg(a, b, negative): pass @pytest.mark.parametrize( "a,b,negative,expected", [ (1, -1, False, True), (-1, 1, False, True), (-4, -5, True, True), (-4, -5, False, False), (-4, 5, False, True), (-4, 5, True, False), (1, 1, False, False), (-1, -1, False, False), (1, -1, True, False), (-1, 1, True, False), (1, 1, True, False), (-1, -1, True, True), (5, -5, False, True), (-6, 6, False, True), (-5, -6, False, False), (-2, -1, False, False), (1, 2, False, False), (-5, 6, True, False), (-5, -5, True, True), ], ) def test_pos_neg(a, b, negative, expected): assert pos_neg(a, b, negative) == expected
ddac4756f16e2c042f78e1ed6dcf4abe20a3c8e7
dolomaniuk/FirstStepsInPython
/solution.py
2,538
3.859375
4
import math y1 = int(input()) x1 = int(input()) y2 = int(input()) x2 = int(input()) res = 'y' distance = y2 - y1 # макс разброс по X isEvenY1 = y1 % 2 # четность Y1 isEvenY2 = y2 % 2 # четность Y2 minX = int(math.fabs(x1 - distance)) # миним значение X if minX < 1: if isEvenY2 == 0: minX = 2 else: minX = 1 maxX = (x1 + distance) # макс значение X if maxX > 8: if isEvenY2 == 0: maxX = 8 else: maxX = 7 def isClrBlack(n, m): # опр. цвет клетки res = 'y' if n % 2 == 0: if m % 2 != 0: res = 'n' else: if m % 2 == 0: res = 'n' return res if distance > 0 and isClrBlack(y1, x1) == 'y' and isClrBlack(y2, x2) == 'y': if isEvenY1 != 0: # нечетные строки if isEvenY2 == 0: if maxX - minX > 2: # больше 2х значений if (x2 >= minX) and (x2 <= maxX): res = 'y' else: res = 'n' else: # меншье двух значений if x2 == minX or x2 == maxX: res = 'y' else: res = 'n' else: if maxX - minX > 2: # больше 2х значений if (x2 >= minX) and (x2 <= maxX) or x2 == x1: res = 'y' else: res = 'n' else: if x2 == minX or x2 == maxX: res = 'y' else: res = 'n' else: # нечетные строки if isEvenY2 == 0: if maxX - minX > 2: # больше 2х значений if (x2 >= minX) and (x2 <= maxX) or x2 == x1: res = 'y' else: res = 'n' else: if x2 == minX or x2 == maxX: res = 'y' else: res = 'n' else: if maxX - minX > 2: # больше 2х значений if (x2 >= minX) and (x2 <= maxX): res = 'y' else: res = 'n' else: if x2 == minX or x2 == maxX: res = 'y' else: res = 'n' else: res = 'n' if res == 'y': print('YES') else: print('NO')
5a54812f2362e01abf23750d533eb8ced2727ae2
spisheh/Udacity-ML-projects
/outliers/outlier_cleaner.py
634
3.734375
4
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ cleaned_data = [] ### your code goes here for i in range(len(ages)): cleaned_data.append((ages[i], net_worths[i], predictions[i]-net_worths[i])) cleaned_data = sorted(cleaned_data, key = lambda x : abs(x[2])) return cleaned_data[:81]
e294cbebf9fb8a1a0d2e0eaf0799620e6d7d1ea3
FrederikLehn/modpy
/modpy/plot/_tornado.py
6,305
3.515625
4
import numpy as np from matplotlib import pyplot as plt # ############################################################################### # # The data (change all of this to your actual data, this is just a mockup) # variables = [ # 'apple', # 'juice', # 'orange', # 'peach', # 'gum', # 'stones', # 'bags', # 'lamps', # ] # # base = 3000 # # lows = np.array([ # base - 246 / 2, # base - 1633 / 2, # base - 500 / 2, # base - 150 / 2, # base - 35 / 2, # base - 36 / 2, # base - 43 / 2, # base - 37 / 2, # ]) # # values = np.array([ # 246, # 1633, # 500, # 150, # 35, # 36, # 43, # 37, # ]) # # ############################################################################### # # The actual drawing part # # # The y position for each variable # ys = range(len(values))[::-1] # top to bottom # # # Plot the bars, one by one # for y, low, value in zip(ys, lows, values): # # The width of the 'low' and 'high' pieces # low_width = base - low # high_width = low + value - base # # # Each bar is a "broken" horizontal bar chart # plt.broken_barh( # [(low, low_width), (base, high_width)], # (y - 0.4, 0.8), # facecolors=['white', 'white'], # Try different colors if you like # edgecolors=['black', 'black'], # linewidth=1, # ) # # # Display the value as text. It should be positioned in the center of # # the 'high' bar, except if there isn't any room there, then it should be # # next to bar instead. # x = base + high_width / 2 # if x <= base + 50: # x = base + high_width + 50 # plt.text(x, y, str(value), va='center', ha='center') # # # Draw a vertical line down the middle # plt.axvline(base, color='black') # # # Position the x-axis on the top, hide all the other spines (=axis lines) # axes = plt.gca() # (gca = get current axes) # axes.spines['left'].set_visible(False) # axes.spines['right'].set_visible(False) # axes.spines['bottom'].set_visible(False) # axes.xaxis.set_ticks_position('top') # # # Make the y-axis display the variables # plt.yticks(ys, variables) # # # Set the portion of the x- and y-axes to show # plt.xlim(base - 1000, base + 1000) # plt.ylim(-1, len(variables)) # # plt.show() col_low = np.array([253., 191., 111.]) / 255. col_high = np.array([32., 120., 180.]) / 255. def tornado(ax, low, high, base=0., labels=(), facecolors=(col_low, col_high)): """ Draws a tornado chart. Originally based on: https://stackoverflow.com/questions/32132773/a-tornado-chart-and-p10-p90-in-python-matplotlib Parameters ---------- ax : matplotlib.Axes Axes on which to draw tornado chart. low : array_like, shape (n,) Values of low case results. high : array_like, shae (n,) Values of high case results. base : float Base case value. labels : tuple Labels for the y-axis. facecolors : tuple Tuple of (color_low, color_high). """ # ensure consistent input ------------------------------------------------------------------------------------------ low = np.array(low) high = np.array(high) n = low.size if high.size != n: raise ValueError('`low` ({}) and `high` ({}) must have the same length.'.format(n, high.size)) if not labels: labels = [str(i) for i in range(1, n + 1)] if len(labels) != n: raise ValueError('`labels` ({}) must have the same length as `low` and `high` ({}).'.format(len(labels), n)) if np.any(low > base): raise ValueError('All values of `low` must be less than or equal to `base`.') if np.any(high < base): raise ValueError('All values of `high` must be greater than or equal to `base`.') # sort according to largest difference ----------------------------------------------------------------------------- diff = high - low idx = np.argsort(diff)[::-1] low = low[idx] high = high[idx] labels = [labels[i] for i in idx] # for labeling min_dist = np.amax(diff) * 0.05 # draw chart ------------------------------------------------------------------------------------------------------- # The y position for each variable ys = range(n)[::-1] # top to bottom # Plot the bars, one by one for y, l, h in zip(ys, low, high): # The width of the 'low' and 'high' pieces low_width = base - l high_width = h - base # Each bar is a "broken" horizontal bar chart ax.broken_barh( [(l, low_width), (base, high_width)], (y - 0.4, 0.8), facecolors=facecolors, edgecolors=['black', 'black'], linewidth=1, ) # display text for negative increments xl = base - low_width / 2. if xl >= base - min_dist: xl = base - low_width - min_dist ha = 'right' else: ha = 'center' low_width = int(low_width) if low_width >= 10. else low_width ax.text(xl, y, str(low_width), va='center', ha=ha) # display text for positive increments xh = base + high_width / 2. if xh <= base + min_dist: xh = base + high_width + min_dist ha = 'left' else: ha = 'center' high_width = int(high_width) if high_width >= 10 else high_width ax.text(xh, y, str(high_width), va='center', ha=ha) # Draw a vertical line down the middle ax.axvline(base, color='black') # Position the x-axis on the top, hide all the other spines (=axis lines) #ax.spines['left'].set_visible(False) #ax.spines['right'].set_visible(False) #ax.spines['bottom'].set_visible(False) ax.xaxis.set_ticks_position('top') # Make the y-axis display the variables ax.set_yticks(ys) ax.set_yticklabels(labels) ax.tick_params(axis='y', which='both', length=0) # set grid ax.grid(True) ax.set_axisbelow(True) # Set the portion of the x- and y-axes to show ax.set_ylim([-1, n])
e08e58d929f62044eb5e95bc43e69d9209de1a2b
Kai-log-93/python_modules_for_work
/pandas/filter.py
1,335
3.609375
4
import pandas as pd from openpyxl.workbook import Workbook df_csv = pd.read_csv('Names.csv', header=None) # specify header for CSV df_csv.columns = ['First', 'Last', 'Address', 'City', 'State', 'Area Code', 'Income'] # get City == 'Riverside' print(df_csv.loc[df_csv['City'] == 'Riverside']) print('-------------------------------------------') # get City == 'Riverside' and First == 'John' print(df_csv.loc[(df_csv['City'] == 'Riverside') & (df_csv['First'] == 'John')]) print('-------------------------------------------') # Lamda funtion base on income get the tax rate df_csv['Tax %'] = df_csv['Income'].apply(lambda x: .15 if 10000 < x < 40000 else .2 if 40000 < x < 80000 else .25) print(df_csv) print('-------------------------------------------') # get Taxes df_csv['Texes Owed'] = df_csv['Income'] * df_csv['Tax %'] print(df_csv['Texes Owed']) print(df_csv) print('-------------------------------------------') # drop collums to_drop = ['Area Code', 'First', 'Address'] df_csv.drop(columns = to_drop, inplace = True) print(df_csv) print('-------------------------------------------') # boolean df_csv['Test col'] = False df_csv.loc[df_csv['Income'] < 60000, 'Test Col'] = True print(df_csv) print('-------------------------------------------') # group by print(df_csv.groupby(['Test Col']).mean().sort_values('Income'))
da5a0302e4459f0246d2d500bdea981542387f02
vesso8/Functions
/07. Chairs.py
513
3.703125
4
# from itertools import combinations # # result = list(combinations(input().split(", "), int(input()))) # for x , y in result: # print(x, y , sep= ", ") def combination(name, count, current_names=[]): if len(current_names) == count: print(', '.join(current_names)) return for i in range(len(name)): current_names.append(name[i]) combination(name[i+1:], count,current_names) current_names.pop() names = input().split(", ") n = int(input()) combination(names,n)
c18e99603c2be1080538050092c07bf74c930a2e
anubhavsrivastava10/Python-ML
/DAY 20/prostate_cancer.py
3,172
3.5625
4
import pandas as pd dataset = pd.read_csv("http://www.stat.cmu.edu/~ryantibs/statcomp/data/pros.dat", delimiter =' ') features = dataset.iloc[:,:-1] labels = dataset.iloc[:,-1] #performing train test and spliy from sklearn.model_selection import train_test_split features_train, features_test, labels_train, labels_test = train_test_split(features,labels,test_size = 0.2, random_state=0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() features_train = sc.fit_transform(features_train) features_test = sc.transform(features_test) # Fitting Logistic Regression to the Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features_train, labels_train) # Predicting the Test set results labels_pred = regressor.predict(features_test) import numpy as np labels_test = np.array(labels_test) #yes we can predict lspa df = pd.DataFrame(labels_test,labels_pred) df #(1) Train the unregularized model (linear regressor) and calculate the mean squared error. from sklearn import metrics print ("Simple Regression Mean Square Error (MSE) for TEST data is") print (np.round (metrics .mean_squared_error(labels_test, labels_pred),2) ) #(2) Apply a regularized model now - Ridge regression and lasso as well and check the mean squared error. from sklearn.linear_model import Lasso from sklearn.linear_model import Ridge lm_lasso = Lasso() lm_ridge = Ridge() lm_lasso.fit(features_train, labels_train) lm_ridge.fit(features_train, labels_train) predict_test_lasso = lm_lasso.predict (features_test) predict_test_ridge = lm_ridge.predict (features_test) print ("RSquare Value for Lasso Regresssion TEST data is-") print (np.round (metrics.mean_squared_error(predict_test_lasso,labels_test)*100,2)) print ("RSquare Value for Ridge Regresssion TEST data is-") print (np.round (metrics.mean_squared_error(predict_test_ridge,labels_test)*100,2)) #(b) Can we predict whether lpsa is high or low, from other variables? mean_val = dataset['lpsa'].mean() labels = labels.to_frame() labels['lpsa'] = labels['lpsa'].map(lambda x : 1 if x > mean_val else 0) #performing train test and spliy from sklearn.model_selection import train_test_split features_train1, features_test1, labels_train1, labels_test1 = train_test_split(features,labels,test_size = 0.2, random_state=0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() features_train1 = sc.fit_transform(features_train1) features_test1 = sc.transform(features_test1) # Fitting Logistic Regression to the Training set from sklearn.linear_model import LogisticRegression classifier = LogisticRegression() classifier.fit(features_train1, labels_train1) # Predicting the Test set results labels_pred = classifier.predict(features_test1) import numpy as np labels_test = np.array(labels_test1) #yes we can predict lspa df2 = pd.DataFrame(labels_test1,labels_pred) df2 #making confusion matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(labels_test1,labels_pred) cm
2a6d9bdaae27a64cec7d6487ac55c370f3c343fd
bingyihua/bing
/help/py/jicheng_duo.py
325
3.765625
4
class Parent2(): print('我是第二个爹') class Parent(): print('我是第一个爹') class SubClass(Parent, Parent2): print('我是子类') # # 结果:我是第二个爹 # 我是第一个爹 # 我是子类 #注意:类在定义的时候就执行类体代码,执行顺序是从上到下
4d9b5a16da2436ee293b1e88806c37ffd272c024
nadiaguedess/SistemasDistribuidosEstruturaSequencialPython
/ListaSequencial/atividade_8.py
232
3.875
4
salarioHora = float(input("Digite quantos você ganha por hora:")) horasTrabalhadas = int(input("Digite quantas horas você trabalhou no mês:")) salarioFinal = salarioHora * horasTrabalhadas print("Seu salário é:", salarioFinal)
6c3042b4dc5760ff78adaa38f1addc54968d8d36
ianlai/Two-Circle-Intersection-Area
/two-circle-intersection-area.py
3,026
3.828125
4
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- import math import numpy as np import sys PI = 3.14159265359 ### Default Setting x1 = 2.1 y1 = 1.8 r1 = 1.9 x2 = 5.3 y2 = 2.5 r2 = 3.2 numerical = False def p(x): return pow(x,2) def s(x): return pow(x,0.5) def sin(x): return math.sin(x) def cos(x): return math.cos(x) def acos(x): return math.acos(x) class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "("+str(self.x)+","+str(self.y)+")" class Circle: def __init__(self, r, p): self.r = r self.c = p def __str__(self): mystring = "radius=" + str(self.r) + ", center=" + str(self.c) return mystring def area(self): return str(PI*p(self.r)) def distance(p1,p2): return s(p(p1.x-p2.x)+p(p1.y-p2.y)) #target angle is between a and b def cosine_rule(a,b,c): angle=acos((p(a)+p(b)-p(c))/(2*a*b)) return angle #theta is between a and b def triangle_area(a,b,theta): return 0.5*a*b*sin(theta) def cone_area(r,theta): return p(r)*PI*theta/(2*PI) if "-x1" in sys.argv: x1 = float(sys.argv[sys.argv.index("-x1")+1]) if "-y1" in sys.argv: y1 = float(sys.argv[sys.argv.index("-y1")+1]) if "-r1" in sys.argv: r1 = float(sys.argv[sys.argv.index("-r1")+1]) if "-x2" in sys.argv: x2 = float(sys.argv[sys.argv.index("-x2")+1]) if "-y2" in sys.argv: y2 = float(sys.argv[sys.argv.index("-y2")+1]) if "-r2" in sys.argv: r2 = float(sys.argv[sys.argv.index("-r2")+1]) if "-n" in sys.argv: numerical = True if "--numerical" in sys.argv: numerical = True p1 = Point(x1,y1) p2 = Point(x2,y2) c1 = Circle(r1,p1) c2 = Circle(r2,p2) if not numerical: print("=================================================================") print("Circle-1: " + str(c1) + " | Area=" + c1.area()) print("Circle-2: " + str(c2) + " | Area=" + c2.area()) print("=================================================================") d = distance(c1.c, c2.c) external_distance_bound = c1.r + c2.r internal_distance_bound = math.fabs(c1.r - c2.r) if d >= external_distance_bound: if not numerical: print("Two circles have no overlap.") else: print(0) elif d <= internal_distance_bound: if not numerical: if r1 <= r2: print("Circle 1 is totally inside Circle 2.") else: print("Circle 2 is totally inside Circle 1.") else: if r1 <= r2: print(r1*r1*PI) else: print(r2*r2*PI) else: theta1 = 2 * cosine_rule(c1.r, d, c2.r) theta2 = 2 * cosine_rule(c2.r, d, c1.r) t_area1 = triangle_area(c1.r, c1.r, theta1) c_area1 = cone_area(c1.r,theta1) t_area2 = triangle_area(c2.r,c2.r,theta2) c_area2 = cone_area(c2.r,theta2) two_circle_overlap_area = c_area1 + c_area2 - t_area1 - t_area2 if not numerical: print("Overlap Area: " + str(two_circle_overlap_area)) else: print(two_circle_overlap_area)
eecdf56616975b28768a8c7b689ae28796cb5cda
SantaPoro/IT-Chalmers
/Contains.py
1,252
4.4375
4
#!/bin/python def contains(list, e): """ determines whether e is contained in the list """ for elem in list: if elem == e: return True return False integer_list = [0, 1, 2, 3] print("") print("Does the list contain 3?: %r" % contains(integer_list, 3)) print("Does the list contain 5?: %d" % contains(integer_list, 5)) print("") list1 = [1, 2, 3, 4] list2 = [1, 2, 3, 4, 5, 6, 7] list3 = [1, 2, 3, 5] # Create a function which determines whether a list is contained in another list. # Some tips: # - use the contains function defined above in your function. # - you want to check if each element in the sublist is contained in the list # - you can use boolean arithmetics, short example in boolean_arithmetic.py # 4. def sublist_contains(real_list, sublist): for elem in real_list: if not contains(sublist,elem): return False return True print ("Are the list the same?: %r" % sublist_contains(list1,list2)) print("") print("Expected True, Actual %r" % sublist_contains(list2, list1)) print("Expected False, Actual %r" % sublist_contains(list3, list1)) print("Expected True, Actual %r" % sublist_contains(list1, list1)) print("")
3ead2197c78a6414100389b2b2cde2f9df8e1760
LizinczykKarolina/Python
/Practice Python/ListEx3.py
312
3.875
4
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] z=[] for i in a: if i <= 5: print "Adding element %d to the list" % i z.append(i) print z print "Please enter the number: " num = int(raw_input("> ")) x = [i for i in a if i < num] c = [] for y in x: c.append(y) print c
be47d91f72e229c20353485ff009d2fd02a7d22a
praveen5658/cspp1
/cspp1_practise/cspp1-assignments/m8/GCD using Recursion/gcd_recr.py
501
3.75
4
''' Author : Praveen Date : 07-08-2018 ''' def gcd_recur(input_a, input_b): ''' This function returns GCD of two numbers using Recursion ''' if input_a < input_b: input_a, input_b = input_b, input_a if input_a % input_b == 0: return input_b return gcd_recur(input_b, input_a % input_b) def main(): '''This is main function''' data = input() data = data.split() print(gcd_recur(int(data[0]), int(data[1]))) if __name__ == "__main__": main()
182d1b0c993b77213bbc353e0cae94e23754341f
abhilashmaddineni/Terraform_Abhi
/Challenge#3/Scenario1.py
602
4.3125
4
#Scenario 1: If some undefined variable is given in the dictionary which is not present, below code will skip the undefined Varibale and check for next variable. #taking the dictionary into cont variable cont = {"x":{"y":{"z":"a"}}} #Validating with key key = "john/x" #using split function to separate the keys and using it for further iterations new_key = key.split("/") #looping the separated key with the dictionary for item in new_key: #checking if the given key present in the dictionary if item in cont: cont = cont[item] #printing the dictionary based on the key check. print cont
2e71e66d31a1cf9aa3f0d31dfff101c35395d08a
AdrianM20/Hangman---PracticalExam
/src/hangman/ui/console.py
3,105
3.5
4
""" console Module Created on 30.01.2017 @author adiM """ from hangman.domain.validators import HangmanException class Console(object): def __init__(self, sentence_controller, game_controller): self.__sentence_controller = sentence_controller self.__game_controller = game_controller def run_app(self): """ Program starting point """ options = {1: self.__add_sentences, 2: self.__play_game, 3: self.__print_available_sentences} while True: self.__print_menu() option = input("Enter option: ") if option == "x": break try: option = int(option) options[option]() except ValueError as ve: print("Invalid input: ", ve) print("Try again!") except KeyError as ke: print("Option not available. Try again!") except HangmanException as he: print("An error occurred: ", he) print("Try again!") def __print_menu(self): print() print("What would you like to do?") print("\t1 - Add sentences to game") print("\t2 - Play Hangman") print("\tx - Exit app") def __add_sentences(self): print("Enter a sentence: ") sentence = input() self.__sentence_controller.add_sentence(sentence) self.__sentence_controller.save_to_file() def __print_available_sentences(self): sentences = self.__sentence_controller.get_all() for s in sentences: print(s) def __print(self, sentence, tries): hang = ["h", "a", "n", "g", "m", "a", "n"] if tries >= 0: print(sentence + ' - "{0}"'.format(''.join(hang[:tries + 1]))) else: print(sentence + ' - ""') def __play_game(self): tries = -1 self.__game_controller.start_game() self.__print(self.__game_controller.print_sentence(), tries) while True: if tries >= 6: print("YOU LOST! Good luck next time!") break letter = input("Enter a letter: ") if letter.isalpha(): if self.__game_controller.is_letter(letter): if self.__game_controller.is_available(letter): self.__game_controller.fill_letter(letter) if self.__game_controller.game_end(): print(self.__game_controller.print_sentence() + "\tYOU WON!!!\nPlay again?") break self.__print(self.__game_controller.print_sentence(), tries) else: tries += 1 self.__print(self.__game_controller.print_sentence(), tries) else: tries += 1 self.__print(self.__game_controller.print_sentence(), tries) else: print("Incorrect input. Not a letter.")
7a3535e82cf7a851995070fefc6304def69b9537
shebac22/remote
/check_number.py
90
3.859375
4
# check whether 4 is even num = 4 if (num % 2) == 0: print("{0} is Even".format(num))
f0c17fbe451f63d334ed57a1179095ea69c9faf2
xavi-/random
/Euler/problem27.py
649
3.703125
4
def isPrime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False i = 3 while(n / i >= i): if(n % i == 0): return False i += 2 return True def testExpression(a, b): for n in range(1, 900): if not isPrime(n*n + a*n + b): return (n, a, b) return (89, a, b) maxSeq = (0, 0, 0) primes = [i for i in range(2, 1000) if isPrime(i)] for b in primes: for a in range(-999, 1000, 2): seq = testExpression(a, b); if seq[0] > maxSeq[0]: maxSeq = seq print("on b: %s" % b) print("maxSeq: %s", maxSeq)
2948a131295b9fecf0bcb71841e0d91cf3feb844
joseangel-sc/CodeFights
/Arcade/BookMarket/ProperNounCorrection.py
621
4.1875
4
#Proper nouns always begin with a capital letter, followed by small letters. #Correct a given proper noun so that it fits this statement. #Example #For noun = "pARiS", the output should be #properNounCorrection(noun) = "Paris"; #For noun = "John", the output should be #properNounCorrection(noun) = "John". #Input/Output #[time limit] 4000ms (py) #[input] string noun #A string representing a proper noun with a mix of capital and small Latin letters. #Constraints: #1 ≤ noun.length ≤ 10. #[output] string #Corrected (if needed) noun. def properNounCorrection(noun): return noun[0].upper()+noun[1:].lower()
f737a16017cb5f7eec8c58d5ba1b633eb482977f
renyi1314/Source-code
/basis/data/card.py
2,697
3.984375
4
''' 需求:1,显示用户菜单 ''' card_list = [] tmp_card = {} # 临时保存查找到的数据 tmp_name = "" # 临时保存查找的名字 tmp_index = int() # 临时保存查找到数据的索引,用于更新数据 def main(): print("欢迎进入名片管理系统") print("请选择操作: ") print("1.新增名片") print("2.显示全部") print("3.查找名片") print("0.退出系统") choice = input("请输入选择的操作") if choice == "1": insert_card() elif choice == "2": display_all_card() elif choice == "3": search_card_by_name() elif choice == "0": print("退出操作") else: print("请选择正确的操作") main() def insert_card(): name = input("请输入名字: ") phone = input("请输入电话: ") QQ = input("请输入QQ号: ") email = input("请输入邮箱: ") card_list.append({"name": name, "phone": phone, "QQ": QQ, "email": email}) print("新建成功") main() def display_all_card(): print("名字\t\t电话\t\tQQ\t\t邮箱") for card in card_list: # 遍历列表,获取所有字典 print("{name}\t{phone}\t{QQ}\t{email}".format(**card)) # 打印字典所有值 # for value in card.values(): # print(value, end="\t") print() main() def search_card_by_name(): tmp_name = input("请输入要查询的名字: ") for card in card_list: tmp_card = card tmp_index = card_list.index(tmp_card) if tmp_name == card["name"]: print(tmp_index) print("名字\t\t电话\t\tQQ\t\t邮箱") print("{name}\t{phone}\t{QQ}\t{email}".format(**card)) # for value in card.values(): # print(value, end="\t") print() choice = input("请选择要执⾏的操作 [1] 修改 [2] 删除 [0] 返回上级菜单") if choice == "1": update_search_card() elif choice == "2": delete_search_card() elif choice == "0": main() else: print("没有找到相应的名字") main() def update_search_card(): name = input("请输入名字: ") phone = input("请输入电话: ") QQ = input("请输入QQ号: ") email = input("请输入邮箱: ") tmp_card["name"] = name tmp_card["phone"] = phone tmp_card["QQ"] = QQ tmp_card["email"] = email card_list[tmp_index] = tmp_card print("数据修改成功") print(tmp_index) main() def delete_search_card(): del card_list[tmp_index] print("数据删除成功") main() main()
1dfc76b312eebcde9d3612b05eaad4af1d56b4c1
vikky12343/python_basic-programs
/lab_6/lab6.9.py
304
3.90625
4
class power: def __init__(self,a,b): self.x=a self.n=b self.p=1 def pow(self): while(self.n>0): self.p=self.p*self.x self.n=self.n-1 def display(self): print self.p a,b=input() ob=power(a,b) ob.pow() ob.display()
c42cee88d2157af6428e11c11a5be8aa2fba83ca
noisebridge/PythonClass
/guest-talks/20171204-profiling/001-string-concat.py
540
4.3125
4
def lowercase(string): return string.lower() # Concatenate using a loop def concat_loop(strings): result = '' for string in strings: result += ',' result += lowercase(string) # ! return result # Concatenate using string.join def concat_join(strings): return ','.join([lowercase(string) for string in strings]) # ! # Read in the system dictionary and produce a comma-separated # list of lowercase words strings = open('/usr/share/dict/words').readlines() concat_loop(strings) concat_join(strings)
67c1d8262a87b233dfccbe0425be12b3b3f55f73
Botany-Downs-Secondary-College/password_manager-joshua-saunders
/password_manager.py
2,499
4.21875
4
#password_manager.py #Joshua Saunders 25/02/2021 #Lists password_list = ["Pass1234"] username_list = ["BDSC2021"] #Functions def line(): print(" ") def age(): while True: try: age = int(float(input("What is you age: "))) if age < 13: print("Sorry you are not old enough") break elif age >= 13: print("Hello {}".format(name)) menu() break except ValueError: print("Enter an integer not a word please") def menu(): while True: try: options = int(input("1: New User | 2: Existing User | 3: View Username List | 4: View Passwords List | 5: Exit: ")) if options == 1: line() add_user() elif options == 2: log_in() elif options == 3: print(username_list) menu() elif options == 4: print(password_list) menu() elif options == 5: break else: print("Please enter a number from the ones shown") except ValueError: print("Enter a number shown from the options given") def add_user(): while True: add_username = input(("Enter a username to create a user for a new account: ")) x = len(add_username) if x >= 10: print("Username is created") username_list.append(add_username) password() else: print("Username is too short, it must contain 5 or more letters") def password(): while True: add_password = input("Please enter a password, must be 8 letters or more: ") y = len(add_password) if y >= 8: print("Password length is sufficent") password_list.append(add_password) menu() else: print("Password is too short please enter one with 8 letters or more") def log_in(): while True: user = input("Are you an existing user? Yes/No: ").lower() if user == "yes": username = input("Username: ") elif user == "no": menu() if username in username_list: password = input("Password: ") if username not in username_list: print("Username not found, we have returned you back to the menu") menu() if password in password_list: add_extra = input("Welcome, Press 1 To View Your Lists, And Press 2 To Add More Passwords: ") if add_extra == 1: print(username_list) print(password_list) break if add_extra == 2: add_user() password() else: print("User was not found please try again") name = input("What is you name: ") age()
56d954ec2ab4773adb186ce9f240117e792507c7
My-Students/Turtle_UDP_Server
/Turtle_Giavelli/Server.py
1,105
3.640625
4
import socket import turtle #TURTLE_KING=turtle.Turtle() #TURTLE_KING.hideturtle() MOVE=10 server_ip="127.0.0.1" server_port=10000 s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind((server_ip,server_port)) port_table=[] turtle_dict={} def turtle_create(address,movement): turtle_dict[address[1]]=turtle.Turtle() #turtle_dict[address[1]]=TURTLE_KING.clone() #turtle_dict[address[1]].showturtle() move(address,movement) def move(address,movement): if movement=="w": turtle_dict[address[1]].forward(MOVE) elif movement=="s": turtle_dict[address[1]].backward(MOVE) elif movement=="a": turtle_dict[address[1]].left(MOVE) elif movement=="d": turtle_dict[address[1]].right(MOVE) while True: command,address = s.recvfrom(4096) movement=command.decode() if address[1] in port_table: print(address[1]) move(address,movement) else: port_table.append(address[1]) turtle_create(address,movement) print(address[1])
0c8b1fcc3b7d63371bd24a06c2d66b63fb4920f3
hdantas/prog-puzzles
/codewars/python/5kyu/processes.py
1,041
3.5625
4
# http://www.codewars.com/kata/542ea700734f7daff80007fc def processes(start, end, original_processes, solution_candidate=[]): # uses recursion to greedily explore trees, then returns the shortest tree of those with the correct start and end node if (start == end): return solution_candidate # found a possible solution tmp_result = [] matched_processes = [] # nodes traversed non_matched_processes = [] # nodes to traverse in the recursion for p in original_processes: if p[1] == start: matched_processes += [p] else: non_matched_processes += [p] for m in matched_processes: tmp_result += [processes(m[2], end, non_matched_processes, solution_candidate + [m[0]])] clean_tmp_result = [item for item in tmp_result if len(item) > 0] # remove empty solution candidates if clean_tmp_result == []: result = [] else: result = min(clean_tmp_result, key=len) # off the possible solutions pick the one with the smallest length return result
408babae6f2e8b73ff56eaab659d421628c46cab
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/6 Problems on characters/2_CheckCapital/Demo.py
408
4.15625
4
''' Accept Character from user and check whether it is capital or not (A-Z). Input : F Output : TRUE Input : d Output : FALSE ''' def CheckCapital(ch): if((ch >= 'A') and (ch <= 'Z')): return True; else: return False; def main(): ch = input("Enter character:"); result = False; result = CheckCapital(ch); print(result); if __name__ == "__main__": main();
99541d9078f385475dfd6f0ccd5a1fac274b034a
justinta89/Work
/PythonProgramming/Chapter 8/Exercises/fibonacci.py
487
4.28125
4
# fibonacci.py # Calculates the nth number in fibonacci sequence. def fibonacci(n): if n > 0: if n == 1: fn = 1 elif n == 0: fn = 0 else: fn = (n - 1) + (n - 2) if n < 0: if n == -1: fn = 1 else: fn = ((-1) ** (n + 1)) * n return fn def main(): num = int(input("Enter a number >> ")) print(fibonacci(num)) if __name__ in ['__console__', '__main__']: main()
e9c3ed5154d1bf0b35ed01a70634ad2eb1cbb290
scolphew/leetcode_python
/leetcode/_043_MultiplyStrings.py
877
3.59375
4
class Solution(object): def multiply(self, num1, num2): """ string乘法 :type num1: str :type num2: str :rtype: str """ len_1 = len(num1) len_2 = len(num2) result = [0 for _ in range(len_1 + len_2)] print(result) for i in range(len_1 - 1, -1, -1): for j in range(len_2 - 1, -1, -1): num = int(num1[i]) * int(num2[j]) p1 = i + j p2 = p1 + 1 sum_num = num + result[p2] result[p1] += sum_num // 10 result[p2] = sum_num % 10 r = [] for i in result: if r or i != 0: r.append(str(i)) result = ''.join(r) return result if result else '0' if __name__ == '__main__': s = Solution() print(s.multiply("00", "009"))
06a0ea2f01878451b4abf17d2e930a62585d9f86
IM-MC/LCsol
/49.py
572
3.765625
4
def groupAnagrams(strs): """ :type strs: List[str] :rtype: List[List[str]] """ dic = dict() res = [] for i in range(len(strs)): checker = [0]*26 for char in strs[i]: value = ord(char) - ord('a') checker[value] += 1 key = tuple(checker) if key not in dic.keys(): dic[key] = [strs[i]] else: dic[key].append(strs[i]) for key in dic.keys(): res.append(dic[key]) return res print(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
27432145ccb7d6656fabe18b41b3eb0124355d6b
ngchitrungkien/nguyenchitrungkien-fundamental-c4e20
/Session01/homework01/Turtle exercise session01/turtle_equilateraltriangle.py
243
3.625
4
from turtle import * speed(1) shape("classic") color("green") pencolor("green") fillcolor("yellow") begin_fill() for i in range (3): forward(300) left(120) color("yellow") end_fill() pencolor("green") fillcolor("yellow") mainloop()
be59f6e67e8ce78560b107c50280e38bbc976fab
SouzaCadu/guppe
/Secao_19_Manipulando_data_hora/19_138_Metodos_data_hora.py
3,575
4
4
""" Metodos import datetime from textblob import TextBlob # aceita parâmetro de fuso horário (timezone) agora = datetime.datetime.now() print(type(agora), repr(agora), agora) hoje = datetime.datetime.today() print(type(hoje), repr(hoje), hoje) # Mudanças acontecendo a meia noite manutencao = datetime.datetime.combine(datetime.datetime.now() + datetime.timedelta(days=3), datetime.time()) print(type(manutencao), repr(manutencao), manutencao) # 0 - Monday # 1 - Tuesday # 2 - Wednesday # 3 - Thursday # 4 - Friday # 5 - Saturday # 6 - Sunday print(manutencao.weekday()) nascimento = input("Informe sua data de nascimento no formato dd/mm/yyyy: ") nascimento = nascimento.split("/") aniversario = datetime.datetime(int(nascimento[2]), int(nascimento[1]), int(nascimento[0])) if aniversario.weekday() == 0: print('Você nasceu em uma segunda-feira') elif aniversario.weekday() == 1: print('Você nasceu em uma terça-feira') elif aniversario.weekday() == 2: print('Você nasceu em uma quarta-feira') elif aniversario.weekday() == 3: print('Você nasceu em uma quinta-feira') elif aniversario.weekday() == 4: print('Você nasceu em uma sexta-feira') elif aniversario.weekday() == 5: print('Você nasceu em um sábado') elif aniversario.weekday() == 6: print('Você nasceu em um domingo') # formatando datas/horas com str(time) string format time hoje = datetime.datetime.today() hoje_formatado = hoje.strftime("%d/%m/%y") print(hoje_formatado) def formata_data(data): if data.month == 1: return f'{data.day} de Janeiro de {data.year}' elif data.month == 2: return f'{data.day} de Fevereiro de {data.year}' elif data.month == 3: return f'{data.day} de Março de {data.year}' elif data.month == 4: return f'{data.day} de Abril de {data.year}' elif data.month == 5: return f'{data.day} de Maio de {data.year}' elif data.month == 6: return f'{data.day} de Junho de {data.year}' elif data.month == 7: return f'{data.day} de Julho de {data.year}' elif data.month == 8: return f'{data.day} de Agosto de {data.year}' elif data.month == 9: return f'{data.day} de Setembro de {data.year}' elif data.month == 10: return f'{data.day} de Outubro de {data.year}' elif data.month == 11: return f'{data.day} de Novembro de {data.year}' elif data.month == 12: return f'{data.day} de Dezembro de {data.year}' print(formata_data(hoje)) # Refatorando def formata_data(data): return f"{data.day} de {TextBlob(data.strftime('%B')).translate(to='pt-br')} de {data.year}" hoje = datetime.datetime.today() print(formata_data(hoje)) # utilizando o método strptime nascimento = input("Informe sua data de nascimento no formato dd/mm/yyyy: ") aniversario = datetime.datetime.strptime(nascimento, "%d/%m/%Y") print(nascimento) # horários almoco = datetime.time(13, 10, 00) print(almoco) # Avaliando o tempo de processamento do código import timeit, functools # marcando o tempo de processamento de códigos # Loop tempo = timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) print(tempo) # List Comprehension tempo = timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) print(tempo) # Map tempo = timeit.timeit('"-".join(map(str, range(100)))', number=10000) print(tempo) def teste(n): soma = 0 for num in range(n * 200): soma = soma + num ** num + 4 return soma print(timeit.timeit(functools.partial(teste, 2), number=10000)) """
0de34e7f84a0aff75af827cb56f12e3d3e6075f8
astral-sh/ruff
/crates/ruff/resources/test/fixtures/tryceratops/TRY400.py
1,283
3.703125
4
""" Violation: Use '.exception' over '.error' inside except blocks """ import logging import sys logger = logging.getLogger(__name__) def bad(): try: a = 1 except Exception: logging.error("Context message here") if True: logging.error("Context message here") def bad(): try: a = 1 except Exception: logger.error("Context message here") if True: logger.error("Context message here") def bad(): try: a = 1 except Exception: log.error("Context message here") if True: log.error("Context message here") def bad(): try: a = 1 except Exception: self.logger.error("Context message here") if True: self.logger.error("Context message here") def good(): try: a = 1 except Exception: logger.exception("Context message here") def good(): try: a = 1 except Exception: foo.exception("Context message here") def fine(): try: a = 1 except Exception: logger.error("Context message here", exc_info=True) def fine(): try: a = 1 except Exception: logger.error("Context message here", exc_info=sys.exc_info())
a7a9ec4067ff45625b0429831e01a175fc86a8a2
southzyzy/FILAttack
/main_ui.py
3,963
3.546875
4
""" Python Version 3.8 Singapore Institute of Technology (SIT) Information and Communications Technology (Information Security), BEng (Hons) ICT-2203 Network Security Assignment 1 Author: @ Tan Zhao Yea / 1802992 Chin Clement / 1802951 Gerald Peh Wei Xiang / 1802959 Academic Year: 2020/2021 Lecturer: Woo Wing Keong Submission Date: 25th October 2020 This script holds the code to perform various attacks in our Assignment. - Telnet Bruteforce, DHCP Staravation, Rogue DHCP Server, DNS Poisoning """ import os import subprocess import cowsay from pyfiglet import Figlet, figlet_format # Log File Configurations DHCP_STARVE_LOG = os.path.abspath("logs/dhcp_starve.txt") DNS_POISON_LOG = os.path.abspath("logs/dns_poison.txt") # Error Message Dictionary ERRMSG = { 1: "Value Error! The option input is not provided in the function" } # Rogue DHCP Abs Path META_DHCP_SERVER_DIR = os.path.abspath("scripts/meta_dhcp_setup.rc") # Function to display the main menu def display_ui(): """ Display the Banner Message """ print(figlet_format("Welcome To ICT-2203-F17 Attack Script")) cowsay.cow("Do anything you want, just don't get caught :)") cowsay.cow("Moooo") def options_ui(): """ Diplay the Options """ print("") print("-=-=-=-=-=-=-=-=-=-=-= OPTIONS -=-=-=-=-=-=-=-=-=-=-=-=") print("1. Host Discovery.") print("2. Telnet Bruteforce Attack.") print("3. DHCP Starvation Attack.") print("4. Run Rogue DHCP Server.") print("5. DNS Poisoning.") print("6. Exit.") print("0. Clear Screen (Enter 0 to clear screen)") print("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=") def exit_ui(): """Exit UI """ cowsay.cow("Goodbye, Mooo, Mooo, Mooo :)") def main(): """ Main Function """ display_ui() # Infinite Loop while True: try: options_ui() print("[*] Which attack would you like to perform?") choice = int(input("[>]: ")) except ValueError: print(ERRMSG.get(1)) continue except KeyboardInterrupt: exit_ui() break else: if choice < 0 or choice > 6: print(ERRMSG.get(1)) continue # Clear the Screen if choice == 0: os.system("clear") # Host Discovery elif choice == 1: print("\t[+] Enter Network IP Address/Subnet") network_cidr = input("\t[>]: ") print("\n[*] Running Host Discovery") subprocess.run(["python3","scripts/host_discovery.py",network_cidr]) # Telnet Bruteforce Attack elif choice == 2: print("\t[+] Enter Target IP Address") target_ip = input("\t[>]: ") print("\t[+] Enter Dictionary File") password_file = input("\t[>]:") print("\n[*] Running Telnet Bruteforce Attack") try: subprocess.run(["python3","scripts/telnet_bruteforce.py",target_ip,password_file]) except EOFError: print("[ERR] Telnet Connection Closed") input("Press Enter to return to main menu...") continue # DHCP Starvation Attack elif choice == 3: print("\n[*] Running DHCP Starvation Attack") subprocess.Popen(["python3","scripts/dhcp_starvation.py"], close_fds=True) print(f"[*] Please refer to {DHCP_STARVE_LOG} for runtime information ...") input("Press Enter to return to main menu...") continue # Rogue DHCP Server elif choice == 4: print("\n[*] Setting up Rogue DHCP Server") print("\n[*] Please open a new terminal and run the following commands:") print(f"\t[+] sudo msfconsole -q -r '{META_DHCP_SERVER_DIR}'") input("Press Enter to return to main menu...") continue # DNS Attack elif choice == 5: print("\n[*] Running DNS Poisoning Attack") subprocess.Popen(["python3","scripts/dns_poison.py"], close_fds=True) print(f"[*] Please refer to {DNS_POISON_LOG} for runtime information ...") input("Press Enter to return to main menu...") continue # Exit Program elif choice == 6: exit_ui() break if __name__ == '__main__': # Make log directory folder if it does not exist if not os.path.exists('logs/'): os.makedirs('logs/') main()
d4b17b8ee5a1a13e75bf1ea9f3100fdb31b83317
dinhhuyminh03/C4T21
/session3/turtle_intro.py
342
3.859375
4
from turtle import * shape ("turtle") speed(-1) # forward(100) # left(90) # forward(100) # left(90) # forward(100) # left(90) # forward(100) # left(30) # forward(100) # left(90) # forward(100) # left(90) # forward(100) # left(90) # forward(100) # left(30) for i in range (10,200,5): forward(10 + i) left(90) for r in range mainloop ()
cba3ef8acfa0a67b9d9718f968ecf2df4f3ff17c
DanielRrr/Algorithms-Studies
/gcd3.py
184
3.84375
4
def gcd3(a, b): assert a >= 0 and b >= 0 if a == 0 or b == 0: return max(a, b) elif a >= b: return gcd3(a % b, b) else: return gcd3(a, b % a)
8663b54614d6361def4d1b4605bad4a9d3c04a2c
Barbariansyah/pyjudge
/test/loop_2.py
139
3.546875
4
def loop_2(in1,in2): if in1 > in2: i = 0 while i < in1: i = i+1 return i else: return 0
e9bf3e88f740d9d2f8f092d494b44a852fc4f5e0
rochejohn/ATBS
/Projects/Character_Picture_Grid.py
1,072
4.0625
4
#! /usr/bin/env python3 ''' Chapter 4 Character Picture Grid Basically take this grid below and print it so the image is shifted 90 degrees to the right You will need to use a loop in a loop in order to print grid[0][0], then grid[1][0], then grid[2][0], and so on, up to grid[8][0]. This will finish the first row, so then print a newline. Then your program should print grid[0][1], then grid[1][1], then grid[2][1], and so on. The last thing your program will print is grid[8][5]. ''' from time import sleep grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] for x in range(len(grid[0])): print() for y in range(len(grid)-1,-1,-1): print(grid[y][x],end=' ') sleep(0.2) #added sleep to display the image being drawn print() print()
b531b455550925271b011e4dd5ab1dc51bcee440
rishikeshpuri/python-codes
/assignment-2 one complex number from user and display the greater number between real part and imaginary part.py
281
4.4375
4
#To accept one complex number from user and display the greater number between real part and imaginary part. x=int(input("Enter one real number")) y=complex(input("Enter one imaginary number")) if x>y: print("%d is greater number"%x) else: print("%d is greatest number"%y)
bf96ba839c7df2c0e5be37a3cebfa6fb3b83acf7
shreya1sharma/Coding
/programming-puzzles/jump_game.py
808
3.84375
4
''' Method 1: recursion pseudo-code 1. read the first element 2. initialize a canJump variable to False 3. Check all possible jumps starting from maximum to 0 (reverse order) 4. For each jump repeat steps 1-3 5. if the jump leads to the end of the array (len(arr)=1): Update canJump to True, else do not update 6. If while jumping the arr length is exceeded: reduce the jump size and repeat steps 1-5 7. return canJump ''' def jumps(arr): first_element = arr[0] canJump = False if len(arr)==1: return True for i in range( first_element, 0, -1): if len(arr[i:])!=0: canJump = jumps(arr[i:]) if canJump == True: break return canJump ''' Method 2: dynamic programming pseudo-code ''' #%%
8692211470383feed28dae0e008aa2a20194a513
FrankJonasmoelle/Matrix-Library
/matrix/test_unittest.py
423
3.546875
4
import unittest from matrix import * class TestMatrix(unittest.TestCase): def setUp(self): self.m1 = Matrix([[1,2,3],[4,5,6]]) self.m2 = Matrix([[1,1,1],[1,1,1]]) self.m3 = Matrix([[1,2],[3,4],[5,6]]) def test_add(self): out = self.m1 + self.m2 expected = Matrix([[2,3,4], [5,6,7]]) self.assertEqual(out, expected) if __name__ == "__main__": unittest.main()
86912d6585057f5618747f0ff5e43c36b0d35a8a
dan1el5/cs50-lectures
/lecture2/square.py
187
3.8125
4
from functions import square # could also use import functions num = int(input("number: ")) print("The square is" , square(num)) # and then change square(num) to functions.square(num)
ee11cd3dba463874062b05e9d15b89031fff7f5d
deep141997/web-scraping
/web scraping3
1,260
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 13 02:05:15 2018 @author: deepak """ import requests from bs4 import BeautifulSoup # when we run request.get it return a response object page=requests.get("http://dataquestio.github.io/web-scraping-pages/simple.html") print(page.status_code) #response oject has a property status code and status_code=200 page succesfully downloaded #print(page.content) # read data in html format soup=BeautifulSoup(page.content,"html.parser") #print(soup.prettify) #print(soup.title) # to fetch the data of paragraph paragraph=soup.find('p') print(paragraph.text) for i,pg in enumerate(soup.find_all('p')): print(i,pg.text) # all tags are nested we can select all the elements at the first level # we have to use children method of soup it will generate list so we have to use list #print(soup.children) list type for item in list(soup.children): print(type(item)) #<class 'bs4.element.Doctype'> #<class 'bs4.element.NavigableString'> #<class 'bs4.element.Tag'> tags=list(soup.children)[2] print(tags) print(type(tags)) tags_html=list(tags.children) print(tags_html) print(type(tags_html)) for tag in tags_html: print(tag.get_text())
f61cedd2d260d3c74d9e1766d5b6508cbd0f5b71
trevornagaba/Agile-project
/logic.py
706
3.75
4
user_name = raw_input('Please enter your username: ') user_type = raw_input('Hello {}, what type of user are you? :'.format(user_name)) if user_type == user_type.lower('user'): comment = raw_input('Enter new comment here: ') add_comment() edt_comment = raw_input('If you want to edit a comment, please the comment id here: ') edit_comment() elif user_type == user_type.lower('moderator'): comment = raw_input('Enter new comment here: ') add_comment() del_comment = raw_input('If you want to delete a comment, enter the comment id here: ') delete_comment() edt_comment = raw_input('If you want to edit a comment, please the comment id here: ') edit_comment()
d4c5aba6f9e1ef97458bf3c50342b596a54a6e1e
meagles/advent-of-code-2020
/app.py
12,419
3.609375
4
import re #regex def open_puzzle_input(day): with open('./Day{}/input.txt'.format(day), 'r') as file: data = file.read() splitData = data.splitlines() return splitData if __name__ == "__main__": day = 10 puzzle = 2 input = open_puzzle_input(day) if day == 10: int_input = [] for val in input: int_input.append(int(val)) prev_joltage = 0 differences_1 = 0 differences_3 = 0 for joltage in sorted(int_input): if joltage == prev_joltage + 1: differences_1 = differences_1 + 1 elif joltage == prev_joltage + 3: differences_3 = differences_3 + 1 prev_joltage = joltage print(differences_1) print(differences_3) elif day == 9: if puzzle == 1: previous_nums = [] preamble_length = 25 for line_num in range(len(input)): if line_num < preamble_length: print("Still in preamble") else: value = input[line_num] previous_nums = input[(line_num-preamble_length):(line_num)] for preceding_pos in range(line_num-preamble_length, line_num): if (str(int(value) - int(input[preceding_pos]))) in previous_nums: # print("Found sum for "+str(value)+": "+str(input[preceding_pos])+" and "+str(int(value) - int(input[preceding_pos]))) break elif preceding_pos == line_num-1: print("Could not find "+str(value)) elif puzzle == 2: desired_sum = 1639024365 for line_num in range(len(input)): ongoing_sum = 0 nums = [] sum_line_num = int(line_num) while ongoing_sum < desired_sum: nums.append(int(input[sum_line_num])) ongoing_sum = ongoing_sum + int(input[sum_line_num]) sum_line_num = sum_line_num + 1 if ongoing_sum == desired_sum: print("Row "+str(line_num)+" to "+str(sum_line_num-1)) print(sorted(nums)) elif day == 8: if puzzle == 2: # we're gonna try this with slightly modified inputs until we get an answer for index_to_modify in range(len(input)): if input[index_to_modify][0:3] != "acc": # print("Trying with changed row "+str(index_to_modify+1)) this_input = input.copy() line_to_modify = this_input[index_to_modify] if line_to_modify[:3] == "jmp": modified_line = "nop"+line_to_modify[3:len(line_to_modify)] elif line_to_modify[:3] == "nop": modified_line = "jmp"+line_to_modify[3:len(line_to_modify)] this_input[index_to_modify] = modified_line keep_running = True accumulator = 0 current_row = 0 executed_rows = [] while keep_running: if current_row > len(this_input) or current_row in executed_rows: # print("+ infinite loop or out of bounds.") break elif current_row == len(this_input): print("Found infinite loop fix! Changed row "+str(index_to_modify+1)) keep_running = False break else: executed_rows.append(current_row) line = this_input[current_row] # print("Running row "+str(current_row)+": "+line) line_parts = line.split(" ") if line_parts[0] == "acc": accumulator = accumulator + int(line_parts[1]) current_row = current_row + 1 elif line_parts[0] == "jmp": current_row = current_row + int(line_parts[1]) elif line_parts[0] == "nop": current_row = current_row + 1 continue if not keep_running: print("++++++Accumulator is at "+str(accumulator)) elif puzzle == 1: print('aoeu') keep_running = True accumulator = 0 current_row = 0 executed_rows = [] while keep_running: line = input[current_row] print("Running row "+str(current_row)+" (accumulator at "+str(accumulator)+"): "+line) if current_row in executed_rows: break else: executed_rows.append(current_row) line_parts = line.split(" ") if line_parts[0] == "acc": accumulator = accumulator + int(line_parts[1]) current_row = current_row + 1 elif line_parts[0] == "jmp": current_row = current_row + int(line_parts[1]) elif line_parts[0] == "nop": current_row = current_row + 1 continue print("Accumulator is at "+str(accumulator)) elif day == 7: # create rules dictionary rules = {} for line in input: line_parts = line.split(" bags contain ") outer_color = line_parts[0] inner_colors = line_parts[1].split(', ') rules[outer_color] = {} for this_bag in inner_colors: num_color = this_bag[0:(this_bag.find(' bag'))] inner_color = num_color.lstrip('1234567890 ') inner_number = num_color.split(" ")[0] if inner_number == 'no': inner_number = 0 rules[outer_color][inner_color] = int(inner_number) # create def check_bag_contains(rules, outer_color, desired_color, seen_colors=[]): contents_dict = rules[outer_color] for this_color in contents_dict: if this_color == "no other": return False elif this_color == desired_color: return True elif this_color not in seen_colors: # not the color we are looking for, but could it contain that color? if check_bag_contains(rules, this_color, desired_color, seen_colors): return True else: seen_colors.append(this_color) return False def count_bag_contents(rules, this_bag_color): num_bags = 1 # we have this bag at least contents_dict = rules[this_bag_color] for color in contents_dict: if color == "no other": return num_bags else: num_outer_bags = contents_dict[color] num_inner_bags = count_bag_contents(rules, color) num_bags = num_bags + (num_outer_bags * num_inner_bags) return num_bags if puzzle == 1: # look for shiny gold in each bag num_valid = 0 for bag_color in rules: if check_bag_contains(rules, bag_color, 'shiny gold'): num_valid = num_valid + 1 print(bag_color+" is valid") print("Total valid: "+str(num_valid)) elif puzzle == 2: gold_bag_contents = count_bag_contents(rules, 'shiny gold') - 1 # don't count the gold bag print("Gold bag contains "+str(gold_bag_contents)+" bags") elif day == 6: group_yeses = '' answer_sum = 0 new_group = True for line in input: if len(line) == 0: answer_sum = answer_sum + len(group_yeses) group_yeses = '' new_group = True continue if puzzle == 1: group_yeses = ''.join(set(group_yeses+line)) elif puzzle == 2: if new_group: new_group = False group_yeses = line # at this point everyone has said yes continue else: personset = set(line) new_group_yeses = '' for char in group_yeses: if char in personset: new_group_yeses = new_group_yeses + char group_yeses = new_group_yeses answer_sum = answer_sum + len(group_yeses) # last set print("Sum: "+str(answer_sum)) elif day == 5: highest_seat_id = 0 all_seat_ids = [] for line in input: front_back_info = line[0:7] left_right_info = line[7:10] front_back_binary = "" left_right_binary = "" for pos in range(7): if front_back_info[pos] == "F": front_back_binary += "0" elif front_back_info[pos] == "B": front_back_binary += "1" for pos in range(3): if left_right_info[pos] == "L": left_right_binary += "0" elif left_right_info[pos] == "R": left_right_binary += "1" row = int(front_back_binary,2) column = int(left_right_binary,2) seat_id = row * 8 + column all_seat_ids.append(seat_id) if seat_id > highest_seat_id: highest_seat_id = seat_id print("Highest seat id is: "+str(highest_seat_id)) prev_seat_id = None for this_seat_id in sorted(all_seat_ids): if prev_seat_id is not None and this_seat_id != prev_seat_id + 1: print("We have seats "+str(this_seat_id)+" and "+str(prev_seat_id)+" with a seat between them") prev_seat_id = this_seat_id elif day == 4: def validate_passport(puzzle, passport_fields, passport_data): required_fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"] missing_fields = [field for field in required_fields if field not in passport_fields] if len(missing_fields) == 0 or missing_fields == ["cid"]: if puzzle == 1: return True else: for index in range(len(passport_fields)): this_data = str(passport_data[index]) this_field = passport_fields[index] if this_field == 'byr' and (len(this_data) != 4 or int(this_data) < 1920 or int(this_data) > 2002): print('byr') return False elif this_field == 'iyr' and (len(this_data) != 4 or int(this_data) < 2010 or int(this_data) > 2020): print('iyr') return False elif this_field == 'eyr' and (len(this_data) != 4 or int(this_data) < 2020 or int(this_data) > 2030): print('eyr') return False elif this_field == 'hgt': print('hgt') if not re.search("^([0-9]+(cm|in))", this_data): return False if this_data.find('cm') != -1: # dealin' with metric number_centimeters = int(this_data[0:this_data.find('cm')]) if number_centimeters < 150 or number_centimeters > 193: return False else: # dealin' with imperialism number_inches = int(this_data[0:this_data.find('in')]) if number_inches < 59 or number_inches > 76: return False elif this_field == 'hcl' and not re.search("^#([a-f0-9]{6})", this_data): print('hcl') return False elif this_field == 'ecl' and this_data not in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']: print('ecl') return False elif this_field == 'pid' and (len(this_data) != 9 or not int(this_data)): print('pid') return False return True else: return False valid_passports = 0 passport_fields = [] passport_data = [] for row_num in range(0, len(input)+1): if row_num >= len(input): # we need an empty line at the end lol line = "" else: line = input[row_num] if len(line) > 0: # line with data line_parts = line.split(' ') for pair in line_parts: key_value = pair.split(':') passport_fields.append(key_value[0]) passport_data.append(key_value[1]) else: # blank line, check old user, go to new user if validate_passport(puzzle, passport_fields, passport_data): valid_passports = valid_passports + 1 passport_fields = [] passport_data = [] print(str(valid_passports)+" valid passports found") elif day == 3: if puzzle == 1: velocities = [[3,1]] elif puzzle == 2: velocities = [[1,1],[3,1],[5,1],[7,1],[1,2]] mult_product = 1 for velocity in velocities: x_pos = 0 y_pos = 0 x_vel = velocity[0] y_vel = velocity[1] print("Doing velocity: "+str(x_vel)+","+str(y_vel)) trees_encountered = 0 for row_num in range(0, len(input), y_vel): line = input[row_num] if x_pos >= len(line): x_pos = x_pos - len(line) if line[x_pos] == "#": trees_encountered = trees_encountered + 1 x_pos = x_pos + x_vel if puzzle == 2: mult_product = mult_product * trees_encountered print(str(trees_encountered)+" trees encountered") if puzzle == 2: print("Multiplied product: "+str(mult_product)) elif day == 2: valid_passwords = 0 for line in input: line_parts = line.split(' ') pw_policy_parts = line_parts[0].split('-') # array of 2 values char = line_parts[1][0] password = line_parts[2] if puzzle == 1: char_count = password.count(char) min_char_count = int(pw_policy_parts[0]) max_char_count = int(pw_policy_parts[1]) if (char_count >= min_char_count and char_count <= max_char_count): valid_passwords = valid_passwords + 1 elif puzzle == 2: position_1 = int(pw_policy_parts[0]) - 1 # they aren't 0-indexed, so policy char x is at python index x-1 position_2 = int(pw_policy_parts[1]) - 1 if (len(password) >= position_2): # check it's even long enough if ((password[position_1] == char and password[position_2] != char) or (password[position_2] == char and password[position_1] != char)): valid_passwords = valid_passwords + 1 print(str(valid_passwords)+" passwords are valid") elif day == 1: if puzzle == 1: for line in input: for line2 in input: if (int(line)+int(line2))==2020: print("Result is "+str(int(line) * int(line2))) if puzzle == 2: for line in input: for line2 in input: for line3 in input: if (int(line)+int(line2)+int(line3))==2020: print("Result is "+str(int(line) * int(line2) * int(line3)))
a7b2aec62b5b7f1a8ebb4b5e3facfeaf3cea2aa9
saitoshin45/AnimalTetris-
/tetris.py
917
3.65625
4
#saitoshin45 tetris game import tkinter #variables for the positions mouseX = 0 mouseY = 0 mouseC = 0 cursorX = 0 cursorY = 0 #function to get the mouse's positions def mouse_move(e): global mouseX, mouseY mouseX = e.x mouseY = e.y def mouse_press(e): global mouseC mouseC = 1 def mouse_release(e): global mouseC mouseC = 0 def game_main(): fnt =("Times New Roman", 30) txt = "mouse({},{}){}".format(mouseX, mouseY, mouseC) cvs.delete("test") cvs.create_text(456, 384, text=txt, fill="black",font=fnt,tag="test") root.after(100, game_main) root = tkinter.Tk() root.title("mouse input") root.resizable(False, False) root.bind("<Motion>", mouse_move) root.bind("<ButtonPress>",mouse_press) root.bind("<ButtonRelease>",mouse_release) cvs = tkinter.Canvas(root, width=912, height = 768) cvs.pack() game_main() root.mainloop()
2e85ac86faf369f94a100a6efdadc8cbb53500d1
AndreiBratkovski/CodeFights-Solutions
/Interview Practice/Arrays/firstNotRepeatingCharacter.py
818
4.25
4
""" Note: Write a solution that only iterates over the string once and uses O(1) additional memory, since this is what you would be asked to do during a real interview. Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'. Example For s = "abacabad", the output should be firstNotRepeatingCharacter(s) = 'c'. There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first. For s = "abacabaabacaba", the output should be firstNotRepeatingCharacter(s) = '_'. There are no characters in this string that do not repeat. """ def firstNotRepeatingCharacter(s): for i in range(len(s)): if i == s.index(s[i]) and s.count(s[i]) == 1: return s[i] return '_'
dcfeb2cdbb6613c8be2925b9b61a08b696c17b15
adamorhenner/Fundamentos-programacao
/vp2/objeto2.py
460
3.8125
4
class Pessoa: def __init__(self, nome, cpf, email): self.nome = nome self.cpf = cpf self.email = email p1 = Pessoa("adamor","065054343", "[email protected]") p2 = Pessoa("adamo","06505434", "[email protected]") p3 = Pessoa("adam","0650543", "[email protected]") p4 = Pessoa("ada","065054", "[email protected]") print(p1.nome, p1.cpf, p1.email) p = [] p.append(p1) p.append(p2) p.append(p3) p.append(p4) for pessoa in p: print(pessoa.nome, pessoa.cpf, pessoa.email)
fd7a9eab46b710503c991c10717b215617e08471
sgrade/pytest
/leetcode/convert_sorted_array_to_binary_search_tree.py
1,933
4.03125
4
# https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ """ Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example: Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: @staticmethod def sorted_array_to_bst(nums): """ :type nums: List[int] :rtype: TreeNode """ def inner_function(arr): # corner cases arr_length = len(arr) if arr_length == 0: return mid = int(arr_length / 2) # print('mid', mid) root = TreeNode(arr[mid]) # print('root', root.val) try: # print('\ntrying LEFT with array:', arr[:mid]) root.left = inner_function(arr[:mid]) except: return try: # print('\ntrying RIGHT with array:', arr[mid+1:]) root.right = inner_function(arr[mid+1:]) except: return return root return inner_function(nums) # ++++++++++++++ # Helper function # Utility function to print BST traversal def bst_traversal_print(node): if not node: return print(node.val) bst_traversal_print(node.left) bst_traversal_print(node.right) sol = Solution() # inp = [1, 2, 3, 4, 5] inp = [-10, -3, 0, 5, 9] x = sol.sorted_array_to_bst(inp) bst_traversal_print(x)
c19baa97e81bd46c5a9f662e3eb2cec86c621c3b
ICCV/coding
/others/of52.py
466
3.578125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ L1,L2 = headA,headB while L1!=L2: L1 = headB if L1==None else L1.next L2 = headA if L2== None else L2.next return L1
2841a3be0a2107c129223ca26d3d7954ffc79d48
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/NatalieRodriguez/Lesson08/test_Circle.py
1,835
3.59375
4
from Circle import * import pytest from math import * a = Circle(10) b = Circle(5) c = Circle(2) d = Circle(1) def getter_test(): assert a.radius == 10 assert b.radius == 5 assert c.radius == 2 assert d.radius == 1 assert a.diameter == 20 assert b.diameter == 10 assert c.diameter == 4 assert d.diameter == 2 def setter_test(): a.diameter = 10 assert a.diameter == 10 assert a.radius == 5 a.radius = 5 assert a.diameter == 10 assert a.radius == 5 def area_test(): assert a.area == pi*100 assert b.area == pi*25 assert c.area == pi*4 def init_diameter_test(): aa = Circle.from_diameter(8) ab = Circle.from_diameter(7) ac = Circle.from_diameter(6) assert aa.radius == 4 assert ab.radius == 3.5 assert ac.radius == 3 assert aa.diameter == 8 assert ab.diameter == 7 assert ac.diameter == 6 def str_repr_test(): assert str(a) == "Circle with radius: " + str(a.radius) assert str(b) == "Circle with radius: " + str(b.radius) assert repr(a) == 'Circle(12)' assert repr(b) == 'Circle(1)' def add_multiple_test(): assert repr(a + b) == "Circle(15)" assert repr(a * 3) == "Circle(30)" assert repr(3 * a) == "Circle(30)" assert a * 3 == 3 * a def compare_test(): assert a > b assert b < a assert a == Circle(10) assert b == b assert a != b assert a >= b assert b <= a def len_circumference_test(): assert len(a) == round(2 * pi * 10) assert a.circumference == 2 * pi * 10 assert len(a) == round(a.circumference) assert len(b) == round(2 * pi) assert b.circumference == 2 * pi def aug_operators_test(): ba = Circle(16) bb = Circle(20) ba += bb bb *= 2 assert ba == Circle(42) assert bb == Circle(40) assert bb/2 == Circle(20)
72c91389167bd08dd363dd1fe132e3c919aad4ea
xhimanshuz/time-pass
/Python/fileio_ui.py
454
3.640625
4
#Input Data by user in file from sys import argv from os.path import exists source, filename = argv print("Enter Data in %r" %filename) print("Currently in %r \n" %filename) ofile = open(filename, "r+w+") print(ofile.read()) line1 = raw_input("Enter Text to Line 1: ") line2 = raw_input("Enter Text to Line 2: ") ofile.write(line1) ofile.write(line2) ofile = open(filename, "r") print("Printing %r Text: \n " %filename) print(ofile.read()) ofile.close()
37b9acd8596877fb6d4ee7252ff124a5db16a09d
mstrzelczyk4/Exercism---python-track
/wordy/wordy.py
983
3.796875
4
import re def answer(question): operators = ["plus", "minus", "multiplied", "divided"] tab = [word for word in question[:-1].split() if re.search("[0-9]+", word) or word in operators] if len(tab) % 2 == 0 or not re.search("[0-9]+", question[-2]): raise ValueError("Invalid question!") for x in range(len(tab)): if x % 2 == 0: try: tab[x] = int(tab[x]) except ValueError: raise ValueError("Invalid question!") elif tab[x] not in operators: raise ValueError("Invalid question!") if len(tab) == 1: return tab[0] result = tab[0] i = 1 while i < len(tab): if tab[i] == "plus": result += tab[i + 1] elif tab[i] == "minus": result -= tab[i + 1] elif tab[i] == "multiplied": result *= tab[i + 1] elif tab[i] == "divided": result /= tab[i + 1] i += 2 return result
e75ca20199a09434371b6a9f6c5e797a5807a7a2
SebastianAthul/pythonprog
/OOP/INHERITANCE/person_child.py
735
4
4
#MULTIPLE INHERITANCE class Person: def set(self,name,age,address): self.name=name self.age=age self.address=address print("Name=",self.name) print("AGE=",self.age) class Child: def setvalue(self,school,std): self.school=school self.std=std print("school=",self.school) print("std=",self.std) class Student(Person,Child): #multiple inheritance, inheriting proprty of both Person and child classes def printvalue(self,rollno,marks): self.rollno=rollno self.marks=marks print("Roll=",self.rollno) print("marks=",self.marks) obj=Student() obj.set("ATHUL",23,"kurisingal") obj.setvalue("LUMINAR",12) obj.printvalue(18,45)
dc9ae09a62ac884572a56bbd649c9c40e31da970
karolinanikolova/SoftUni-Software-Engineering
/2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/06-Objects-and-Classes/02_Exercises/02-Weapon.py
1,069
4.0625
4
# 2. Weapon # Create a class Weapon. The __init__ method should receive an amount of bullets (integer). Create an attribute called bullets, to store them. # The class should also have the following methods: # • shoot() - if there are bullets in the weapon, reduce them by 1 and return a message "shooting…". # If there are no bullets left, return: "no bullets left" # You should also override the toString method, so that the following code: print(weapon) should work. # To do that define a __repr__ method that returns "Remaining bullets: {amount_of_bullets}". # You can read more about the __repr__ method here: link class Weapon: def __init__(self, bullets): self.bullets = bullets def shoot(self): if self.bullets > 0: self.bullets -= 1 return "shooting..." return "no bullets left" def __repr__(self): return f"Remaining bullets: {self.bullets}" # weapon = Weapon(5) # weapon.shoot() # weapon.shoot() # weapon.shoot() # weapon.shoot() # weapon.shoot() # weapon.shoot() # print(weapon)
0eb02469796ba91bad5473c6f3f6c73f3b8be1db
praba230890/Simultaneity
/queue_threading.py
558
3.53125
4
import threading, queue import time q = queue.Queue() def task(i): d = 0 for v in range(100000): d += 1 q.put(d) print("Thread: %s" % (i)) time.sleep(1) if __name__ == "__main__": tasks = [] for i in range(100): add_task = threading.Thread(target=task, args=(i,)) add_task.start() tasks.append(add_task) for task in tasks: task.join() out = 0 while not q.empty(): out += q.get() q.task_done() print("Final result of 100 times 100000: %s" % out)
23ed86aa27ee01da36c29b9f43575a81c7e296ea
Kushbak/python-tasks
/Neobis/Logic/#biggestDigit.py
473
3.71875
4
hundred = [] def setDig(n): i = 0 while n > i: i += 1 anyNum = int(input(str(i) + ' число: ')) hundred.append(anyNum) showArr() def showArr(): maxNum = max(hundred) indexOfMax = hundred.index(maxNum) print('Самое большое число: ' + str(maxNum)) print('Его индекс: ' + str(indexOfMax + 1)) nums = int(input('Количество чисел, которые вы хотите ввести: ')) setDig(nums)
e9e85d18792bf3175a691fdb3cff116435a645ef
JinzhuoYang/hogwarts
/class_pritice/class_pritice1.py
682
3.65625
4
class person: def __init__(self,name,age,gender): self.name = name self.age = age self.gender = gender def set_att(self,value): self.value = value def eat(self): print(f" name : {self.name}, age : {self.age}, gender : {self.gender} i'm eat") def drink(self): print(f" name : {self.name}, age : {self.age}, gender : {self.gender} i'm drink") def run(self): print(f" name : {self.name}, age : {self.age}, gender : {self.gender} i'm run") goulin = person("goulin" , 25 ,"femail") yangjinzhuo = person("yangjinzhuo" , 24 , "mail") print(goulin.name) goulin.run() goulin.set_att("fat") print(goulin.value)
56c2e62daffd1d133cbda5a484ddcf60f20c2d26
dimitar-daskalov/SoftUni-Courses
/python_advanced/labs_and_homeworks/01_lists_as_stacks_and_queues_exercise/02_maximum_and_minimum_element.py
623
3.5
4
manipulation_stack = [] commands_number = int(input()) for _ in range(commands_number): command = input() if command.startswith("1"): element = int(command.split()[1]) manipulation_stack.append(element) elif command == "2": if manipulation_stack: manipulation_stack.pop() elif command == "3": if manipulation_stack: print(max(manipulation_stack)) elif command == "4": if manipulation_stack: print(min(manipulation_stack)) manipulation_stack = [str(el) for el in manipulation_stack][::-1] print(", ".join(manipulation_stack))
a8f4d0a132e0fb22a367e067692ac81540537b7b
rafaelperazzo/programacao-web
/moodledata/vpl_data/380/usersdata/315/95895/submittedfiles/principal.py
162
3.671875
4
# -*- coding: utf-8 -*- from minha_bib import * #COMECE AQUI ABAIXO for x in range(-10,10,1): a = ((x**2)-(2*x)+1) if a ==0: print(i)
bdac19986e18ad413e11500c344aaf3df0b68ea6
doPggy/py-try
/3-str.py
1,562
4.21875
4
# 单引双引号都可以创建字符串 s = "hello world" print(s) s = 'hello, world' print(s) # 简单操作 ## 加法 s = 'h' + 'w' print(s) ## 与数字相乘 print("echo" * 3) # 字符串方法 ## 分割 line = "1 2 3 \t 4 5" print(line.split()) line = '1, 2, 3, 4, 5' print(line.split(',')) ## 连接 s = ',' '''以 s 为连接符连接成一个字符串''' ss = s.join(['1', '2', '3']) # char list print(ss) ## 替换 s = "hello world" '''s.replace(p1, p2), 将 s 的 p1 部分换成 p2。''' ss = s.replace('world', '111') print(ss) ## 大小写转化 print('hello'.upper()) print('HELLO'.lower()) ## 去除多余空白字符 s = " he\t\n " print(s.strip()) print(s.lstrip()) print(s.rstrip()) ## 查看更多成员方法 print(dir(s)) # 使用 \ 来换行 """最后一行不用加 '\'""" a = "hellll" \ "1111" \ "my name" print(a) # 强制转化为 str print(str(1.1 + 2.2)) print(repr(1.1 + 2.2)) # 整数 -> 不同进制 str '''to 16 进制''' print(hex(255)) '''to 8 进制''' print(oct(255)) '''to 2 进制''' print(bin(255)) # str -> int print(int('23')) '''指定进制''' print(int('FF', 16)) print(int('377', 8)) print(int('11111111111', 2)) # str -> float print(float('4.55')) # 格式化字符串 print('{} {} {}'.format('a', 'b', 'c')) ## 指定参数位置 print('{2} {1} {0}'.format('a', 'b', 'c')) ## 指定参数名称 print('{color} {0} {x} {1}'.format(10, 'foo', x = 1.5, color = 'blue')) ## 占位符 '''类似 c 的 printf''' print('{color:10} {0:10d} {x} {1}'.format(10, 'foo', x = 1.5, color = 'blue'))
2018849a56da6195fd7b6734a90e5a7ef5830f43
sjogleka/General_codes
/criticalRouters.py
3,197
3.84375
4
import collections ''' def FindCriticalNodes(numEdges, numNodes, edges): # Get all the node nodes = [] for i in range(numEdges): # Get nodes if edges[i][0] not in nodes: nodes.append(edges[i][0]) if edges[i][1] not in nodes: nodes.append(edges[i][1]) # Get all the neighbours neighbours = {node: [] for node in nodes} for i in range(numEdges): # Get neighbours neighbours[edges[i][0]].append(edges[i][1]) neighbours[edges[i][1]].append(edges[i][0]) def dfs(parent, seen): nonlocal neighbours # print("Visiting node {}".format(parent)) # Mark the parent as explored seen[parent] = 1 # Get all the neighbours from parent neig = neighbours[parent] # Iterate all the neighbours for i in range(len(neig)): # return if this node was exlored if seen[neig[i]] == 1: continue # DFS dfs(neig[i], seen) # Loop over all the nodes output = [] for i in range(numNodes): explored = {node: 0 for node in nodes} # Mark the cutting point as explored as we # don't wanna explore this point explored[nodes[i]] = 1 # DFS # Traverse from 0 every time total_visited = 1 dfs(nodes[0], explored) print("Node {}: Explores {} nodes.".format(nodes[i], sum(explored.values()))) # If all nodes are explored, it means it's not articulate point if (sum(explored.values()) < numNodes): output.append(nodes[i]) print(neighbours, nodes) print(output) if __name__ == "__main__": numNodes, numEdges = 7, 7 #edges = [[0, 1], [0, 2], [1, 3], [2, 3], [2, 5], [5, 6], [3, 4]] edges = [[1, 2], [1, 3], [2, 4], [3, 4], [3, 6], [6, 7], [4, 5]] FindCriticalNodes(numNodes, numEdges, edges) ''' # Input: # numNodes = 7, # numEdges = 7, # edges = [[0, 1], [0, 2], [1, 3], [2, 3], [2, 5], [5, 6], [3, 4]] # Output: # [2, 3, 5] def findcriticalnodes(n, edges): g = collections.defaultdict(list) for conn in edges: g[conn[0]].append(conn[1]) g[conn[1]].append(conn[0]) visited = [0] * n isarticulationpoints = [0] * n order = [0] * n low = [0] * n seq = 0 def dfs(u, p): nonlocal seq visited[u] = 1 order[u] = low[u] = seq seq = seq + 1 children = 0 for to in g[u]: if to == p: continue if visited[to]: low[u] = min(low[u], low[to]) else: dfs(to, u) low[u] = min(low[u], low[to]) if order[u] <= low[to] and p != -1: isarticulationpoints[u] = 1 children += 1 if p == -1 and children > 1: isarticulationpoints[u] = 1 dfs(0, -1) ans = [] for i in range(len(isarticulationpoints)): if isarticulationpoints[i]: ans.append(i) return ans if __name__ == "__main__": a = [[1, 2], [1, 3], [2, 4], [3, 4], [3, 6], [6, 7], [4, 5]] print(findcriticalnodes(7, a))
9bfa12055dc14833cc06613977ae83e784953612
BarisAkkus/Main
/Sezon1/Ders10-Formatting.py
571
4.25
4
for i in range(1, 13): print("No.{0:2} squared is {1:3} and cube is {2:4}".format(i,i**2,i**3)) print() for i in range(1, 13): print("No.{0:2} squared is {1:<3} and cube is {2:<4}".format(i,i**2,i**3)) #sola dayalı print() print("Pi is approximately {0:<12}".format(22 / 7 )) print("Pi is approximately {0:<12f}".format(22 / 7 )) print("Pi is approximately {0:<12.50f}".format(22 / 7 )) print("Pi is approximately {0:<52.50f}".format(22 / 7 )) print("Pi is approximately {0:<62.50f}".format(22 / 7 )) print("Pi is approximately {0:<72.50f}".format(22 / 7 ))
6c0188ab2a17ddb968f9476865101313531a5a98
ErvinHRivasM/Python
/basicPython/conversor_mejorado_v_alfa.py
990
4.09375
4
""" Bienvenido al conversor de monedas 1 - Pesos Colombianos 2 - Pesos Argentinos 3 - Pesos Mexicanos Elige una opción: """ opcion = input("¿Cuanto pesos colombiano tienes?") if opcion == 1: pesos = input("¿Cuanto pesos colombiano tienes?") pesos = float(pesos) valor_dolar = 3846.40 dolares = pesos / valor_dolar dolares = round(dolares,2) dolares = str(dolares) print("Tienes $"+dolares+" dolares") elif opcion == 2: pesos = input("¿Cuanto pesos Argentinos tienes?") pesos = float(pesos) valor_dolar = 98.10 dolares = pesos / valor_dolar dolares = round(dolares,2) dolares = str(dolares) print("Tienes $"+dolares+" dolares") elif opcion == 3: pesos = input("¿Cuanto pesos Mexicanos tienes?") pesos = float(pesos) valor_dolar = 19.87 dolares = pesos / valor_dolar dolares = round(dolares,2) dolares = str(dolares) print("Tienes $"+dolares+" dolares") else: print("Elige una opción valida")
a39e0196f034b1ea086a3d321beb605126acc78d
RobertaLara/BankAccount
/Bank.py
2,931
4.0625
4
# Consulta ao saldo na conta corrente e liberação do valor somente se for dentro do valor disponível na conta # Programadora Roberta Lara import os def clear(): # Função para limpar console os.system('clear') clear() print("\n\n\tBANCO 24 HORAS - Não aceite ajuda de estranhos\n") auxiliar = 0 # Declarei um auxiliar para encerrar o while quando o usuário desejar encerrar a operação saldo = 500.00 # Saldo do usuário é inicialmente fixo while (auxiliar == 0): # Somente vai sair do while quando o auxiliar for diferente de 0 operacao = input("\nQual a operação desejada?\n\n" # Instrução para o usuário digitar qual operação ele deseja "Para consultar saldo, digite 1\n" "Para saque, digite 2\n" "Para finalizar a operação, digite 3\n") while (operacao != '1') and (operacao != '2') and (operacao != '3'): # Caso usuário digite um número diferente operacao = input(" OPÇÃO INVÁLIDA! DIGITE OPERAÇÃO NOVAMENTE.\n") clear() if (operacao == '3'): # Caso usuário solicite finalizar a operação, uma mensagem é exibida e o progama é encerrado print("\n\n\tOBRIGADO POR USAR O BANCO 24 HORAS!\n\n") auxiliar = 1 # Alteração do valor do auxiliar para encerrar o while macro if (operacao == '1'): # Caso o usuário solicite ver o saldo, o mesmo será exibido na tela print("\n\n\tSALDO DISPONÍVEL PARA SAQUE: ",round(float(saldo),2),"\n\n") elif (operacao == '2'): # Caso usuário solicite sacar valor valorSaque = input("\n\nDigite valor que deseja sacar: ") # Instrução para o usuário digitar valor do saque while (float(valorSaque) > saldo) or (float(valorSaque) < 0 or (int(float(valorSaque)) != float(valorSaque))): # Valor do saque não pode ser maior que o saldo, negativo ou conter casas decimais (não trabalhamos com moedas) valorSaque = input("\n\tSALDO INSUFICIENTE OU VALOR INVÁLIDO! DIGITE OUTRO VALOR.\n\n") clear() print("\n\n\tVALOR SACADO: ",round(float(valorSaque),2),"\n\n") # Informa valor sacado saldo = saldo - float(valorSaque) # Subtrai o valor sacado do saldo, gerando um saldo atualizado if (auxiliar == 0): simNao = input("Dejesa fazer mais alguma operação?\n\n" # Opção do usuário continuar com outra operação ou não "Sim, digite 1\n" # Se usuário quiser continuar, todo o processo é repetido "Não, digite qualquer outro valor\n") if (simNao != '1'): # Caso ele não queira continuar, uma mensagem é exibida e o progama é encerrado clear() print("\n\n\tOBRIGADO POR USAR O BANCO 24 HORAS!\n\n") auxiliar = 1 # Alteração do valor do auxiliar para encerrar o while macro
5db87bbf83793956f96325a6baf8b13ff8f530aa
grand-mother/h5py-examples
/examples/units.py
3,566
3.78125
4
#! /usr/bin/env python3 # The following example illustrates how numerical data can be wrapped with # units using the Pint package. # # Note that while using Physical units can prevent some type of bugs it can # also create new ones. In particular when wrapping data with units one must # take care if a copy or a reference of the data is returned. Performance wise # references are better for large data sets however they can lead to unexpected # results, i.e. bugs. import h5py import numpy # First we create a new unit registry and define some shortcuts. Note that this # would actually be imported from a dedicated package, e.g. as: # `from grand import Quantity, units` import pint units = pint.UnitRegistry() Quantity = units.Quantity # The unit registry starts populated with standard units. Extra / custom units # can be added using a definition file or programmatically, e.g. as: units.define('bigfoot = 3 * meter = Bf') # See: https://pint.readthedocs.io/en/0.10.1/defining.html#defining for more # examples # Let us use dummy positions data for this illustration. The Quantity # constructor allows to wrap data with a unit. Note that the new Quantity holds # a reference to the initial data, i.e. the data are NOT copied data = numpy.eye(3, dtype='f8') positions = Quantity(data, units.m) # If a copy is desired one can use the multiplication operator instead, as: positions_copy = data * units.m # Changing the units inplace is done with the `ito` method. positions.ito(units.cm) # <== This changes the unit inplace to cm. Note # that the data are also converted accordingly, # i.e. the initial data array IS modified print(data[0,0]) # <== Now data[0,0] is 100, no more 1! # If a copy is desired then the `to` method can be used instead, e.g. as: positions_cm = positions.to(units.cm) # Note however that IF the initial Quantity already has the desired unit then # a REFERENCE is returned instead of a copy! Therefore the following code would # be better if a copy is desired in all cases: if positions.units == units.cm: positions_cm = positions.copy() else: positions_cm = positions.to(units.cm) data[0, 0] = 0 print(positions[0,0]) # <== This is 0 because it refers to data. The print(positions_copy[0,0]) # copies below are not modified as expected print(positions_cm[0,0]) positions[0, 0] = 100 * units.cm # Let write and read back the Quantity to and HDF5 file. Pint is not natively # supported by H5Py. Therefore we use an attribute (units) in order to store # the units information with h5py.File('example.hdf5', 'w') as f: dataset = f.create_dataset('positions', data=positions.magnitude) # <== Those are the # numerical values dataset.attrs['units'] = str(positions.units) # <== A string representation # of the unit is written # to the HDF5 file with h5py.File('example.hdf5', 'r') as f: dataset = f['positions'] # <== This is only a handle. It does not read # the data from file positions = Quantity(dataset[:], # <== Build the Quantity from dataset.attrs['units']) # numerical data and the # unit string print(positions) print(type(positions.magnitude)) print(numpy.all(positions == positions_copy))
a986f208e42103ac976ee17b213e0711ac31745b
CNZedChou/python-web-crawl-learning
/spider/codes/37_variable_thread.py
788
3.546875
4
# !/usr/bin/python3 # -*- coding: utf-8 -*- """ @Author : Zed @Version : V1.0.0 ------------------------------------ @File : 37_variable_thread.py @Description : @CreateTime : 2020-5-8 14:21 ------------------------------------ @ModifyTime : """ from threading import Thread import time import random g_num = 100#104--GIL#100 def work1(): global g_num for i in range(3): g_num += 1 time.sleep(random.random()) print('in work1,gum=%d' % g_num) def work2(): global g_num for i in range(3): g_num += 1 time.sleep(random.random()) print('in work2,gum=%d' % g_num) if __name__ == '__main__': t1 = Thread(target=work1) t2 = Thread(target=work2) t1.start() t2.start()
93b728a28fe8f3ffcf2926837ab97bdfe992d23e
Long0Amateur/Self-learnPython
/Chapter 6 Strings/Problem/16. A program asks user their name and generates offer.py
428
3.640625
4
# s = input('Enter name:') s1 = s.split()[0] print('Dear',s+',\n') print('I am pleased to offer you our new Platinum Plus Reward card at a special',end=' ') print('introductory APR of 47.99%.',s1+',','an offer like this does not come along',end=' ') print('every day, so I urge you to call now toll-free at 1-800-314-1592.', end=' ') print('We cannot offer such a low rate for long,',s1+',','so call right away.')
edd0fa92f5ee53fb114cb39361c00a0882cc12e6
ARTIC-TTS-experiments/2021-ICASSP
/lib/densenet.py
2,121
3.515625
4
from keras.layers import BatchNormalization, Dropout, Flatten, Dense, Activation import numpy as np # Function for creating a dense layer(s) def dense_block(layer, n_neurons, flatten=True, inner_activation='relu', last_activation='sigmoid', batch_norm=True, batch_norm_after_activation=True, dropout=None, name='dense'): # Check input assert isinstance(n_neurons, (tuple, list)) and len(n_neurons) > 0, 'Input dense layers must be tuple or list of ' \ 'at least 1 elements, typically (n, 1) or (1)' # Check input dropout if dropout is None: dropout = list(np.zeros(len(n_neurons)-1)) assert isinstance(dropout, (tuple, list)) and len(dropout) == len(n_neurons)-1, \ 'Input dense layers must be tuple or list of the same length as n_neurons-1' if flatten: layer = Flatten()(layer) # Add inner layers if batch_norm: for i, (n, d) in enumerate(zip(n_neurons[:-1], dropout)): layer = Dense(n, name='{}{}'.format(name, i+1))(layer) if batch_norm_after_activation: layer = Activation(inner_activation)(layer) if d > 0: layer = Dropout(d, name='{}_dropout{}_{}'.format(name, i+1, d))(layer) layer = BatchNormalization(name='{}_bn{}'.format(name, i+1))(layer) else: layer = BatchNormalization(name='{}_bn{}'.format(name, i+1))(layer) layer = Activation(inner_activation)(layer) if d > 0: layer = Dropout(d, name='{}_dropout{}_{}'.format(name, i+1, d))(layer) else: for i, (n, d) in enumerate(zip(n_neurons[:-1], dropout)): layer = Dense(n, activation=inner_activation, name='{}{}'.format(name, i + 1))(layer) if d > 0: layer = Dropout(d, name='{}_dropout{}_{}'.format(name, i+1, d))(layer) # Add the last dense layer - the prediction layer layer = Dense(n_neurons[-1], activation=last_activation, name='predictions')(layer) return layer
c5cc900c47e979eb91f96b4a206834925577f311
jasoncsonic/CS313E
/Intervals.py
3,703
4.40625
4
# File: Intervals.py # Description: A program that scans a list of tupples and sees if they are overlapping with one another. Whichever tuples are no #longer overlapping with one another are sent to another list that will tell the user which tuples are no longer overapping. # Student's Name: Peyton Breech # Student's UT EID: pb23489 # Course Name: CS 313E # Unique Number: 50205 # Date Created: 9/9/2019 # Date Last Modified: 9/9/2019 #These are the two lists that will be needed to track the entire list of the data file for the intervals, the list that keeps track of #the tuples that do not intersect, and the variable that opens the file. tupleList = [] nonOverLapList = [] f = open("D:\CS313E\intervals.txt", "r") #This function is used to strip each line of the file and store it as a tupple within the list. It turns them into strings initially #but then they are converted into integers so that they can be sorted ascending based on the [x][0] value of the tuple. It then #sends the list to another functioned to be filtered. def main(): #Loop made to go through each line within the file. for line in f: line = line.strip() interval = line.split(" ") num1 = int(interval[0]) num2 = int(interval[1]) tupleList.append((num1, num2)) #Closes the txt file we have open to gather our tuples. f.close() #Sorts the list that we create of the tuples. tupleList.sort() checkLapping(tupleList, nonOverLapList, f) #This function is used to check the lists to see if tuple n and tuple n+1 are overlapping. If they are, it will combine both tuples #making it tuple n. Once tuple n and tuple n+1 are no longer overlapping, it will send that tuple to the list that is designated for the #non overlapping tuples which will be printed in the next function. def checkLapping (tupleList, nonOverLapList, f): #Used to identify which tuple we are currently on y = 1 #keeps track of the current low value and high value within the current tupple. currentLowNum = 0 currentHighNum = 0 #keeps track of the lowest value we have within our given overlapping tuples, and highest number we have within our given #overlapping tuples. lowestNum = tupleList[0][0] highestNum = tupleList[0][1] #loop that is used to filter through the tuples and see which ones are overlapping. while y < len(tupleList): currentLowNum = tupleList[y][0] currentHighNum = tupleList[y][1] #If the highest value of the tuple we are given/created is higher than the n+1 tuple's lower value and lower than the #high number of the n+1 tuple, then we will know the tuples are overlapping. if highestNum > currentLowNum and highestNum < currentHighNum: highestNum = currentHighNum #If the if statement above is false, then the tuples are no longer overlapping and the current tuple we are on will be sent #to the list of the non-overlapping tuples. else: nonOverLapList.append((lowestNum, highestNum)) highestNum = currentHighNum lowestNum = currentLowNum y = y+1 printList(tupleList, nonOverLapList, f) #This function is made to print the non intersecting intervals within our given data. def printList (tupleList, nonOverLapList, f): print("Non-intersecting Intervals:") #Value used to loop the while loop so that we can print out all of the non-overlapping intervals. wrong = 0 while wrong < len(nonOverLapList): print(nonOverLapList[wrong]) wrong = wrong + 1 main()
3dd9201b0b228fecabb349efb0bd1903fc6bf09b
szabgab/slides
/python/examples/basics/calculator_argv.py
454
3.5625
4
import sys def main(): if len(sys.argv) < 4: exit("Usage: " + sys.argv[0] + " OPERAND OPERATOR OPERAND") a = float(sys.argv[1]) b = float(sys.argv[3]) op = sys.argv[2] if op == '+': res = a + b elif op == '-': res = a - b elif op == '*': res = a * b elif op == '/': res = a / b else: print("Invalid operator: '{}'".format(op)) exit() print(res) main()
39d70e9babb3ef7ee258054893d5afc872b70e40
wbshobhit1/Python3.7
/finally_else.py
251
3.703125
4
f1 = open("eyes.txt") try: f = open("water.txt") except Exception as e: print(e) else: print("This will run only if except is not running") finally: print("Run this anyway...") f.close() f1.close() print("Important to run")
07607c9b673d9a5145848e9cd607a1cd1111ea73
sheng1993/coding-problems
/interview/04_tree_and_graphs/12_paths_with_sum.py
1,236
3.546875
4
# Paths with Sum: You are given a binary tree in which each node contains an integer value (which # might be positive or negative). Design an algorithm to count the number of paths that sum to a # given value. The path does not need to start or end at the root or a leaf, but it must go downwards # (traveling only from parent nodes to child nodes). from utils.models.trees import Node from collections import defaultdict def count_paths_with_sum(node:Node, target: int): return count_paths_with_sum(node, target, 0, defaultdict(lambda: 0)) def count_paths_with_sum(node :Node, target: int, running: int, table:defaultdict): if not node: return 0 running += node.val sum = running - target total_paths = table[sum] if running == target: total_paths += 1 increment_hash_table(table, running, 1) total_paths += count_paths_with_sum(node.left, target, running, table) total_paths += count_paths_with_sum(node.right, target, running, table) increment_hash_table(table, running, -1) return total_paths def increment_hash_table(table: defaultdict, key, delta): new_count = table[key] + delta if new_count == 0: del table[key] else: table[key] = new_count
3536d39f0c2ea49e6888a96ede54aa1be165896a
maygrey/RimeIce
/Codeeval/primepalindrome.py
936
3.90625
4
''' Codeeval challenge 3 Created on 02/06/2014 @author: maygrey ''' import sys def search_primes(n): """Search all the primes from 2 to n""" num = [2] i = 3 while i < n: for j in num[:]: if i % j == 0: i = i + 1 break else: num.append(i) i = i + 1 return num def iden_palindrome(num): """Identifies all the palindromes in list 'num' """ tmp = [] for i in range(len(num)): tmp.append(str(num[i])) for i in range(len(tmp)): for j in range(len(tmp[i])): if tmp[i][j] != tmp[i][len(tmp[i])-j-1]: break else: result =tmp[i] print(result), if __name__ == '__main__': """I search all the primes till 1000 and identify the palindromes""" primes = search_primes(1000) iden_palindrome(primes) sys.exit(0)
3f01872b9ddb442b7f94b29ee9d026ee82e77735
super3/PyDev
/Old Projects/ident/Helper.py
615
3.65625
4
# Name: Helper.py # Author: Super3(super3.org) import random def FiletoArray(filename): """Converts a .txt file to list""" try: tmp = [] file = open(filename) except: print("Error Reading File:",filename) else: for line in file: line = line.strip() line = line.lower() tmp.append(line) file.close() return tmp def ArraytoFile(array, filename): """Converts a list to a .txt file""" file = open(filename+'.txt', 'w') for line in array: file.write(line+"\n") file.close() def getRandVal(aList): """Returns a random value from a list""" return aList[random.randrange(len(aList))]