text
stringlengths
37
1.41M
#how many fibonacci numbers to generate? fibo =int(input("how many fibonacci numbers to generate? ")) def fib(n): a,b=0,1 for i in range(0,fibo): print(a) a,b=b,b+a fib(fibo)
#!/usr/bin/python3 from operator import add, sub def a_plus_abs_b(a, b): # Return a+abs(b), but without calling abs. if b < 0: f = sub else: f = add return f(a,b) def two_of_three(a, b, c): """Return x*x + y*y, where x and y are the two largest members of the positive numbers a, b, and c. >>> two_of_three(1, 2, 3) 13 >>> two_of_three(5, 3, 1) 34 >>> two_of_three(10, 2, 8) 164 >>> two_of_three(5, 5, 5) 50 """ return a*a + b*b + c*c - min(a,b,c) **2 ############################################################# # with_if_statement() returns the number 1, but with_if_function() does not (it can do anything else): def if_function(condition, true_result, false_result): """Return true_result if condition is a true value, and false_result otherwise. >>> if_function(True, 2, 3) 2 >>> if_function(False, 2, 3) 3 >>> if_function(3==2, 3+2, 3-2) 1 >>> if_function(3>2, 3+2, 3-2) 5 """ if condition: return true_result else: return false_result def with_if_statement(): """ >>> with_if_statement() 1 """ if c(): return t() else: return f() def with_if_function(): return if_function(c(), t(), f()) def c(): if "x" not in globals(): global x x = 0 return False def t(): global x x = x * 100 return x def f(): global x x = x + 1 return x # The trick is t() called regardless in with_if_function(). t() is never called in with_if_statement() ################################################################### def hailstone(n): """Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ steps = 0 while n > 1: print(n) steps += 1 if n % 2 == 1: n = n*3+1 else: n = n//2 print(n) steps += 1 return steps if __name__ == "__main__": # Q1 print("\nQ1") print(a_plus_abs_b(2, 3)) print(a_plus_abs_b(2, -3)) #Q2 print("\nQ2") print(two_of_three(1, 2, 3)) print(two_of_three(5, 3, 1)) print(two_of_three(10, 2, 8)) print(two_of_three(5, 5, 5)) #Q3 print("\nQ3") print(with_if_statement()) print(with_if_function()) #Q4 print("\nQ4:Hailstone") a = hailstone(10) print("hailstone(10) steps =", a) a = hailstone(1) print("hailstone(1) steps =", a) #TODO: Challenge question
""" A board for Connect Four. Currently does not work for diagonal wins (e.g. 5 in a row along a diagonal). """ import numpy as np import random, time class Board(): # The idea is that you place your pieces at the top, and they # drop down to populate the first empty square closest to the bottom. def __init__(self, rows=6, cols=7): self.board = np.zeros((rows, cols)) self.nrows = rows self.ncols = cols """ For playing pieces """ def __playPiece(self, piece_color, col): # Private method. 0-indexed # Place a piece (denoted by 1) at a given column. color = 1 if piece_color == "red" else 2 # Iterate bottom up until hit a 0; otherwise invalid move! for sx in xrange(self.nrows-1, -2, -1): if sx == -1: # if hit top of board without empty square raise Exception("No more moves in that column!") if self.board[sx, col] == 0: self.board[sx, col] = color break # Return winner information (1 = RED, 2 = BLACK, -1 = neither yet) return self.isSolved() def playRed(self, col): # Place a RED piece (denoted by 1) at a given column. # Return status of game. return self.__playPiece("red", col) def playBlack(self, col): # Place a BLACK piece (denoted by 2) at a given column. # Return status of game. return self.__playPiece("black", col) """ For checking whether the board is solved """ def __hasFourInRow(self, vector): # Given a vector, see if it has a winner (4 of same piece in row). # Could be improved and made more concise with NumPy # Handle 0's. Note that if >2 spaces are still empty (== 0), you # can't have a winner. num_zeros = sum([1 if i == 0 else 0 for i in vector]) if num_zeros > 2: return -1 # Simple linear algorithm to check if there is a 5-in-a-row, # and if so return 1 (RED) or 2 (BLACK). Else, return -1. this_col = vector slow = fast = 0 while True: if this_col[slow] == this_col[fast]: fast += 1 else: if abs(fast - slow) >= 4: if this_col[slow] == 1: return 1 return 2 slow = fast fast += 1 if fast > len(this_col) - 1: if this_col[slow] == this_col[fast - 1]: if abs(fast - slow) >= 4: if this_col[slow] == 1: return 1 return 2 break return -1 def isSolved(self): # Return 1 if RED has won, 2 if BLACK has, and -1 if neither # has won yet. # Check if any of the columns have winners. for i in range(self.ncols): result = self.__hasFourInRow(self.board[:,i]) if result > 0: return result # Check if any of the rows have winners. for j in range(self.nrows): result = self.__hasFourInRow(self.board[j,:]) if result > 0: return result return -1 def availCols(self): # Return whichever columns are available for more moves. return [i for i in xrange(self.ncols) if self.board[0,i] == 0] """ Other utilities """ def flattenScaleCurr(self): # Get a flattened representation of the current board (numpy array) # state for input to a neural network. # Scale into range (0, 1) for neural net. Note can just multiply by # 1/2 since only values are 0, 1, 2 return np.asarray(self.board.reshape(-1, 1)) * - 1.0 def getCol(self, col): return self.board[:, col] def getRow(self, row): return self.board[row, :] def getNumCols(self): return self.ncols def getNumRows(self): return self.nrows def removePiece(self, col): # Remove the top piece in a column. curr_col = self.getCol(col) for px, piece in enumerate(curr_col): if piece > 0: # set back to 0 self.board[px, col] = 0 return return def randomize(self): # Randomize the board with 0's, 1's, and 2's, still noting # the effects of gravity (pieces fall to bottom). Does not # check if the board is solved. # Reset board, then generate # of pieces to play. self.board = np.zeros((self.nrows, self.ncols)) num_pieces = random.choice(xrange(self.nrows * self.ncols)) pieces = iter([random.randint(1,2) for i in xrange(num_pieces)]) # Reset board. For each piece, check which cols are available to play, # and then play whoever's turn it is next. for px, piece in enumerate(pieces): avail_cols = [i for i in xrange(self.ncols) if self.board[0,i] == 0] rand_col = random.choice(avail_cols) if px % 2 == 0: # whoever goes first self.playRed(rand_col) else: self.playBlack(rand_col) def show(self): # Pretty print the board print "--------- BOARD ----------" for j in xrange(self.nrows): for i in xrange(self.ncols): print "%d " % self.board[j,i], print print "--------------------------" from controller import * if __name__=="__main__": """ Run a sample game with the controller module. """ nrows, ncols = 6, 7 board = Board(rows=nrows, cols=ncols) red_player = MLPPlayer(1, board) black_player = MLPPlayer(2, board) for i in xrange(64): if i % 2 == 0: # red goes print "RED moves next:" red_move = red_player.play(board) # move is a column to play if red_move == -1: # in case you'd like RED to not move print "RED yields. " break game_status = board.playRed(red_move) else: print "BLACK moves next: " black_move = black_player.play(board) if black_move == -1: # in case you'd like BLACK to not move print "BLACK yields. " break game_status = board.playBlack(black_move) board.show() print time.sleep(1) if game_status > 0: break if game_status > 0: print "%s wins!\n" % ("RED" if game_status == 1 else "BLACK") else: print "Stalemate!" """ Run a sample game w/o controller module. Both sides just play randomly. """ # nrows, ncols = 6, 7 # board = Board(rows=nrows, cols=ncols) # for i in xrange(64): # print "Next: move %d. %s\'s turn!" % (i, # ("RED" if i % 2 == 0 else "BLACK")) # # Get a random available column # avail_cols = board.availCols() # if len(avail_cols) == 0: # print "NEITHER RED OR BLACK WIN\n" # break # rand_col = random.choice(avail_cols) # if i % 2 == 0: # game_status = board.playRed(rand_col) # else: # game_status = board.playBlack(rand_col) # board.show() # print # if game_status > 0: # print "%s wins!\n" % ("RED" if game_status == 1 else "BLACK") # break
# A program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. # The results should be printed to the screen. import pyinputplus as pyip from pathlib import Path import os from posix import read import re def regexSearch(): # Ask user for his expression expression = pyip.inputRegexStr("You want to search for: ") # Set counter for number of occurances expressionCounter = 0 # Store all .txt files in a list directory = Path.cwd() allFiles = (list(directory.glob("*.txt"))) for file in allFiles: # Open all .txt files in the folder currentFile = open(file, "r") content = currentFile.read() currentFile.close() # Search user expression in the file for match in re.finditer(expression, content): expressionCounter += 1 print("The expression occured " + str(expressionCounter) + " times") if __name__ == "__main__": regexSearch()
from random import randint # 作业一 while True: a = randint(0, 100) if a == 66: print('找到66了') break else: print(a)
# 当前时间: 2021-09-06 12:28 # 会把整个模块的内容导入进来 import random print(random.randint(0,100)) # 导入某个方法 from random import randint,random print(randint(0,100)) import math print(math.sqrt(9)) print(math.sqrt(16)) import time time.sleep(2) print('hi') from time import sleep as s # 改名s s(2) print('python')
#!/usr/bin/env python3 import argparse import secrets def generate_password( total_passwords, total_characters, uppercase_threshold, number_threshold, punctuation_threshold): total_thresholds = ( uppercase_threshold + punctuation_threshold + number_threshold) passwords = [] assert total_characters >= total_thresholds for i in range(total_passwords): password = [] random = secrets.SystemRandom() uppers = False numbers = False punctuations = False thresholds = False total_lowercase = 0 total_uppercase = 0 total_numbers = 0 total_punctuations = 0 while not thresholds or not uppers or not numbers or not punctuations: generate = random.random() * 10 if generate < 4: total_accepted_lower = (total_characters - total_thresholds) if total_lowercase < total_accepted_lower: total_lowercase += 1 password.append(chr(random.randint(97, 122))) else: thresholds = True continue elif generate < 6: if total_numbers < number_threshold: total_numbers += 1 password.append(chr(random.randint(48, 57))) else: numbers = True continue elif generate < 8: if total_uppercase < uppercase_threshold: total_uppercase += 1 password.append(chr(random.randint(65, 90))) else: uppers = True continue else: if total_punctuations < punctuation_threshold: total_punctuations += 1 password.append(random.sample('?@$!+-', 1)[0]) else: punctuations = True continue passwords.append(''.join(password)) return passwords def run(): parser = argparse.ArgumentParser(description='Generate password') parser.add_argument( '--total-passwords', default=5, type=int, help='How many passwords you want to generate') parser.add_argument( '--total-characters', default=8, type=int, help='How many characters to your passwords',) parser.add_argument( '--total-uppercase', default=2, type=int, help='How many uppercase to your passwords',) parser.add_argument( '--total-numbers', default=2, type=int, help='How many numbers to your passwords',) parser.add_argument( '--total-punctuations', default=2, type=int, help='How many numbers to your passwords',) args = parser.parse_args() for password in generate_password( args.total_passwords, args.total_characters, args.total_uppercase, args.total_numbers, args.total_punctuations): print(password)
#Bastien Anfray 8INF802 – Simulation de systèmes #Partie 3 - Utilisation du générateur import randomGen import pygame import time import sys import math import matplotlib.pyplot as plt #variables initialization steps = [] distArray = [] width = 700 height = 700 environment = [] arraytemp = [] userChoice = 0 userChoice2 = 0 i = 0 j = 0 first_i =0 first_j = 0 old_i = 0 old_j = 0 nbStep = 0 screen = 0 rect = 0 font = 0 pixel_size = 7 wait_time = 0.05 text = "Hello World" test_number = 10000 array1 = [] array2 = [] array3 = [] #Just a random walk, the character go in a random direction at each step def randomWalk(): #variable initialization global i global j global old_i global old_j global nbStep global array1 arraytemp = [] # print("randomWalk") #for each number generated, we go on one of the four directions for step in steps: old_i = i old_j = j if step == 1:#North i = i-1 elif step == 2:#East j = j+1 elif step == 3:#South i = i+1 elif step == 4:#West j = j-1 #we increase the number of step nbStep += 1 #we draw the new step we made if userChoice != 4: drawPixel(j,i) else: calculate_Distance(i,j, first_i, first_j, arraytemp) if arraytemp is not None: array1.append(arraytemp) #Same as the random walk but the character can not come back on his last step def nonReversingWalk(): #variables initialization global i global j global old_i global old_j global nbStep global steps global environment global screen global array2 global arraytemp oldStep = 0 step_cancelled = 0 environment[i][j] = 1 # print("nonReversingWalk") #for each number generated, we go on one of the four directions. We verify that we do not come from this position for step in steps: #we put a 2 on the position of the step before now. It represents the position we can not go on environment[old_i][old_j] = 2 if userChoice != 4: pygame.draw.rect(screen,(0,0,0),(old_j*pixel_size,old_i*pixel_size,pixel_size,pixel_size),1) if step == 1 and i-1 > -1 and environment[i-1][j] != 2:#North environment[old_i][old_j] = 1 old_i = i old_j = j i = i-1 environment[i][j] = 1 calculate_Distance(i,j, first_i, first_j, arraytemp) elif step == 2 and j+1 < width/pixel_size and environment[i][j+1] != 2:#East environment[old_i][old_j] = 1 old_i = i old_j = j j = j+1 environment[i][j] = 1 calculate_Distance(i,j, first_i, first_j, arraytemp) elif step == 3 and i+1 < height/pixel_size and environment[i+1][j] != 2:#South environment[old_i][old_j] = 1 old_i = i old_j = j i = i+1 environment[i][j] = 1 calculate_Distance(i,j, first_i, first_j, arraytemp) elif step == 4 and j-1 > -1 and environment[i][j-1] != 2:#West environment[old_i][old_j] = 1 old_i = i old_j = j j = j-1 environment[i][j] = 1 calculate_Distance(i,j, first_i, first_j, arraytemp) else: #if we come from this position (or we are in the limit of the array), we cancel the step and increase the number of cancelled steps step_cancelled += 1 nbStep -= 1 #we increase the number of step nbStep += 1 #we draw the new step we made if userChoice != 4: drawPixel(j,i) if arraytemp is not None and nbStep == userChoice2: arr = [] for a in range(0, len(arraytemp)): arr.append(arraytemp[a]) array2.append(arr) #we regenerate random numbers because of the steps cancelled, we do not want to lose steps. Then we call the function nonReversingWalk again if step_cancelled > 0: steps = randomGen.generateSequence(1, 4, step_cancelled) nonReversingWalk() #Same as the random walk but the character can not go somewhere he has been before def selfAvoidingWalk(): #variables initialization global i global j global old_i global old_j global nbStep global steps global environment global screen global array3 global arraytemp oldStep = 0 step_cancelled = 0 environment[i][j] = 1 blocked = 0 # print("selfAvoidingWalk") #for each number generated, we go on one of the four directions. We verify that we have never been on one of the positions for step in steps: if step == 1 and i-1 > -1 and environment[i-1][j] != 1:#North old_i = i old_j = j i = i-1 environment[i][j] = 1 calculate_Distance(i,j, first_i, first_j, arraytemp) elif step == 2 and j+1 < width/pixel_size and environment[i][j+1] != 1:#East old_i = i old_j = j j = j+1 environment[i][j] = 1 calculate_Distance(i,j, first_i, first_j, arraytemp) elif step == 3 and i+1 < height/pixel_size and environment[i+1][j] != 1:#South old_i = i old_j = j i = i+1 environment[i][j] = 1 calculate_Distance(i,j, first_i, first_j, arraytemp) elif step == 4 and j-1 > -1 and environment[i][j-1] != 1:#West old_i = i old_j = j j = j-1 environment[i][j] = 1 calculate_Distance(i,j, first_i, first_j, arraytemp) #if we have ever been on the four directions, we are blocked and we stop the simulation elif(i-1 == -1 or i+1 == height/pixel_size or j-1 == -1 or j+1 == width/pixel_size): if userChoice != 4: print("BLOCKED at ", nbStep) elif userChoice == 4: if arraytemp is not None and nbStep < userChoice2: arr = [] for a in range(0, len(arraytemp)): arr.append(arraytemp[a]) array3.append(arr) blocked = 1 break elif (environment[i-1][j] == 1) and (environment[i+1][j] == 1) and (environment[i][j-1] == 1) and (environment[i][j+1] == 1): if userChoice != 4: print("BLOCKED at ", nbStep) elif userChoice == 4: if arraytemp is not None and nbStep < userChoice2: arr = [] for a in range(0, len(arraytemp)): arr.append(arraytemp[a]) array3.append(arr) blocked = 1 break else: #if we have ever been on the direction of the step (or we are in the limit of the array), we cancel the step and increase the number of cancelled steps step_cancelled += 1 nbStep -= 1 #we increase the number of step nbStep += 1 #we draw the new step we made if userChoice != 4: drawPixel(j,i) if arraytemp is not None and nbStep == userChoice2 and blocked != 1: arr = [] for a in range(0, len(arraytemp)): arr.append(arraytemp[a]) array3.append(arr) #we regenerate random numbers because of the steps cancelled, we do not want to lose steps. Then we call the function selfAvoidingWalk again if step_cancelled > 0 and blocked != 1: steps = randomGen.generateSequence(1, 4, step_cancelled) selfAvoidingWalk() #Choice selection function def choiceSelection(): #variables initialization global environment global steps global i global j global first_i global first_j global userChoice global userChoice2 #Mode choosing. We can only choose 1, 2 or 3 while userChoice not in [1, 2, 3, 4]: print("Welcome in the random Walk Program, please make your choice :\n1 - Random Walk\n2 - Non Reversing Walk\n3 - Self Avoiding Walk\n4 - All + see graph") userInput = input("Choose your walk : ") try: userChoice = int(userInput) except ValueError: print("That's not an int!") #Step number choosing (positive number only) while True: userInput2 = input("Put the number of steps you want (positive number) : ") try: userChoice2 = int(userInput2) if(userChoice2 > 0): break except ValueError: print("That's not an int!") #Generation of the steps (1 to 4 are directions North, East, South, West). steps = randomGen.generateSequence(1, 4, userChoice2) #the environment is an array of 0. His size is the height and width divided by the ratio of the 2D graphics (pixel_size) environment = [[0 for i in range(int(height/pixel_size))] for j in range(int(width/pixel_size))] #we start at the middle of the environment i = int(len(environment)/2) j = int(len(environment)/2) first_i = i first_j = j old_i = i old_j = j if userChoice != 4: pygameInit() #initialization of the pygame environment #the user choice call one of the 3 functions if userChoice == 1: randomWalk() elif userChoice == 2: nonReversingWalk() elif userChoice == 3: selfAvoidingWalk() elif userChoice == 4: runAll() def calculate_Distance(x,y,xx,yy, array): dist = math.dist([x,y],[xx,yy]) array.append(dist) #initialization of the 2D environment def pygameInit(): #variables initialization global screen global text global nbStep global font global rect pygame.init() #we set the window size and fill it with white screen = pygame.display.set_mode((width, height)) screen.fill((255,255,255)) #we display the number of steps in the up left corner font = pygame.font.SysFont(None, 20) img = font.render(str(nbStep), True, (0,0,0)) rect = img.get_rect() rect.topleft = (20, 20) pygame.display.update() #this function draw on the 2d environment def drawPixel(x, y): #variables initialization global old_i global old_j global rect global userChoice #we update the display of the environment and think about quitting the simulation for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pygame.display.update() #we create a pixel and fill it with blue pixel = pygame.Surface((pixel_size, pixel_size)) pixel.fill((0,0,255)) #we draw the pixel on the screen screen.blit(pixel,(x*pixel_size,y*pixel_size)) #We draw a red rectangle on the current pixel pygame.draw.rect(screen,(255,0,0),(x*pixel_size,y*pixel_size,pixel_size,pixel_size),1) #if we are on a non reversing walk, we draw a green rectangle on the pixel of the step before now if userChoice == 2: pygame.draw.rect(screen,(0,255,0),(old_j*pixel_size,old_i*pixel_size,pixel_size,pixel_size),1) #else we draw a black rectangle on it else: pygame.draw.rect(screen,(0,0,0),(old_j*pixel_size,old_i*pixel_size,pixel_size,pixel_size),1) #displaying the number of steps text = nbStep img = font.render(str(nbStep), True, (0,0,0)) rect = img.get_rect() rect.topleft = (20, 20) #we clear the old text with a rectangle pygame.draw.rect(screen, (255,255,255),rect,0) #we draw the text on the rectangle screen.blit(img, rect) #we update the display pygame.display.update() #we wait to have the time to see the simulation time.sleep(wait_time) def calculateMean(array): arraymean = [0 for a in range(userChoice2)] mean = 0 val = 0 nb_val = [0 for a in range(userChoice2)] for a in range(0, len(array)): for step_number in range(1, userChoice2): if len(array[a]) >= step_number: val = array[a][step_number-1] arraymean[step_number-1] += val nb_val[step_number - 1] += 1 for a in range(0, len(arraymean)): if nb_val[a] != 0: arraymean[a] = pow(arraymean[a]/nb_val[a],2) if arraymean[a] == 0 and a > 0 : arraymean[a] = arraymean[a-1] return arraymean def runAll(): global wait_time wait_time = 0 for a in range(0,test_number): reset() randomWalk() reset() nonReversingWalk() reset() selfAvoidingWalk() drawAllPlots() def drawAllPlots(): print(len(array1)) print(len(array2)) print(len(array3)) array1mean = calculateMean(array1) array2mean = calculateMean(array2) array3mean = calculateMean(array3) l1 = plt.plot(array1mean, label = 'randomWalk') l2 = plt.plot(array2mean, label = 'nonReversingWalk') l3 = plt.plot(array3mean, label = 'selfAvoidingWalk') plt.legend() plt.ylabel("Distance de l'origine") plt.xlabel("Nombre de pas") plt.show() def reset(): global nbStep global i global j global old_i global old_j global steps global environment environment = [[0 for i in range(int(height/pixel_size))] for j in range(int(width/pixel_size))] nbStep = 0 i = int(len(environment)/2) j = int(len(environment)/2) old_i = i old_j = j steps = randomGen.generateSequence(1, 4, userChoice2) arraytemp.clear() #Main choiceSelection() #choice selection, environment creation and generation of the steps if userChoice != 4: while(True): #we wait for an event to happen event = pygame.event.wait() #we think about quitting the simulation if event.type == pygame.QUIT: pygame.quit() sys.exit()
"""Core Common: Functions for use throughout the application""" # Python imports import re # Django imports from django.conf import settings # 3rd party apps # Local app imports # * Dictionary file location file_path = "%s/dictionary.txt" % (settings.STATIC_ROOT) def init_data(path) -> list: try: file = open(path, "r") words = file.readlines() file.close() return words except: raise Exception("Unable to open file") def init_hash_table(data) -> dict: table = {} for item in data: table[item.strip()] = True return table def init_dictionary(data) -> list: return [word.strip() for word in data] def hash_table_checker(table, word) -> bool: word_lower = word.lower() status = table.get(word_lower) if status is not None: return status else: return False def dictionary_checker(dict, word) -> list: suggestions = [] word_lower = word.lower() for dict_word in dict: if word_lower[: len(word_lower)] in dict_word[: len(word_lower)]: suggestions.append(dict_word) return suggestions def rule_checker(word) -> bool: """Check if letter in word repeats consecutively 3 or more times""" if len(re.findall(r"([a-zA-Z])\1{2,}", word, re.I)) != 0: raise Exception("Multiple characters present") """check if islower/upper is true, return true""" if word.isupper() or word.islower(): return True # * Mixed cased word will still be checked, missing vowels will be treated as misspelled word return False def get_word(word) -> dict: dictionary = init_dictionary(init_data(file_path)) hash_table = init_hash_table(dictionary) rule_checker_status = rule_checker(word) hash_status = hash_table_checker(hash_table, word) if rule_checker_status: # * Rules passed if hash_status: return {"correct": hash_status, "suggestions": []} # * return words similar to passed word elif hash_status == False and len(dictionary_checker(dictionary, word)) != 0: return { "correct": hash_status, "suggestions": dictionary_checker(dictionary, word), } # * No word or words of similarity present raise Exception("Word not in dictionary") else: # * A rule failed # * No words of similarity present if len(dictionary_checker(dictionary, word)) == 0: raise Exception("Word not in dictionary") # * return words similar to passed word return { "correct": rule_checker_status, "suggestions": dictionary_checker(dictionary, word), }
from decimal import * class Order: """Orders represent the core piece of the exchange. Every bid/ask is an Order. Orders are doubly linked and have helper functions (next_order, prev_order) to help the exchange fulfill orders with quantities larger than a single existing Order. """ def __init__(self, quote, order_list): self.timestamp = int(quote['timestamp']) # Integer Unix timestamp self.quantity = Decimal(quote['quantity']) # Quantity can be partial amounts self.price = Decimal(quote['price']) self.order_id = quote['order_id'] self.trade_id = quote['trade_id'] self.next_order = None self.previous_order = None self.order_list = order_list def next_order(self): return self.next_order def previous_order(self): return self.previous_order def update_quantity(self, new_quantity, new_timestamp): """Updates the quantity of shares outstanding to be bought/sold.""" if new_quantity > self.quantity and self.order_list.tail != self: # Check to see that the order is not the last order in list and the quantity is more self.order_list.move_to_tail(self) # move to the end self.order_list.volume -= self.quantity - new_quantity self.timestamp = new_timestamp self.quantity = new_quantity
# Exercise: # * Create a login application, that can store and handle multiple users. # * The user should be asked if he wants to log in or create a login. # * If 'create': The users credentials should be written to a file # * If 'login': The users information should be checked agains the content of the file. # * The user should be granted or denied acces. # # Go for the simplest, easiest, fastest approach! # # Most of what you need we already have covered, the rest is easy. # You get 15 min. # Then we do it together import abc list_of_logins = [] command = input('Type "create" or "login"\n') + '' if command == 'create': username = input('Type username: \n') + '' password = input('Type password: \n') + '' with open("logins.txt", 'w') as file_object: file_object.write(username + "&" + password) if command == 'login': username = input('Type username: \n') + '' password = input('Type password: \n') + '' file_object = open("logins.txt") for line in file_object: list_of_logins.append(line) for item in list_of_logins: if item == username + '&' + password: print("You're logged in, woohoo!") exit() print("I'm sorry, you couldn't login!")
class Cyclinder: def __init__(self,height,radius): self.height = height self.radius = radius def getHeight(self): return self.height def setHeight(self,height): if height > 0: self.height = height def getRadius(self): return self.radius def setRadius(self,radius): if radius > 0: self.radius = radius def area(self): pi = 3.14 area_cal = 2*(pi*(self.radius)**2) + 2*pi*self.radius*self.height return area_cal def volume(self): pi = 3.14 volume_cal = (pi*(self.radius)**2)*self.height return volume_cal cylinder1 = Cyclinder(5,3) print(cylinder1.area()) print(cylinder1.volume())
def binary_to_dec(binary): sum = 0 valueOfdigit = len(binary) for i in binary: if i == "1" : sum += 2**(valueOfdigit-1) valueOfdigit -= 1 elif i == "0": valueOfdigit -= 1 return sum print(binary_to_dec("10010")) def dec_to_binary(decimal): binary = "" while decimal != 0 : if decimal%2 == 1: binary += "1" elif decimal%2 == 0: binary += "0" decimal = decimal//2 return binary[::-1] print(dec_to_binary(8))
number = int(input("up to what number I check: ")) for i in range(2, number) : for divisor in range(2,i) : if i % divisor == 0 : break else: print(i)
#Write a Python program that asks the user how many Fibonacci numbers to generate and then displays them. howmanyFibo = int(input("How many Fibonacci do u want? ")) listOffibo = [1,1] if howmanyFibo == 1 : print(1) elif howmanyFibo == 0 : print("nothingg") elif howmanyFibo >=2 : for i in range(1, howmanyFibo-1) : lastnumber1 = listOffibo[len(listOffibo)-1] lastnumber2 = listOffibo[len(listOffibo)-2] newnumber = lastnumber1 + lastnumber2 listOffibo.append(newnumber) print(listOffibo)
x = int(input("Birinci Sayı:")) y = int(input("Ikinci Sayı:")) z = x + y print("Sayilarin Toplami:", z)
#● Write a Python program that determines and #prints whether a password is valid or not. #● A valid password is at least 8 characters long #and contains at least one uppercase letter #(A-Z), at least one lowercase letter (a-z), #and at least one number (0-9). password = str(input("enter the password: ")) upper = 0 lower = 0 digit = 0 for i in password : if len(password) >=8 : if i.isdigit() : digit += 1 if i.isupper() : upper += 1 if i.islower() : lower += 1 if len(password) < 8 or upper == 0 or lower == 0 or digit == 0: print("not valid !") else : print("ok. its valid.")
import unittest class MyUnitTest(unittest.TestCase): def test_splurthian(self): tests = [ ("Spenglerium", "Ee", True), ("Zeddemorium", "Zr", True), ("Venkmine", "Kn", True), ("Stantzon", "Zt", False), ("Melintzum", "Nn", False), ("Tullium", "Ty", False) ] for t in tests: self.assertEqual(valid_splurthian(t[0], t[1]), t[2]) def valid_splurthian(element, short): # rule 1: length of symbol must be two letters if len(short) != 2: return False element = element.lower() short = short.lower() # rule 2: both letters in short must appear in element name if not all([_ in element for _ in short]): return False # rule 3: if the short is two of the same letters, it must appear twice. otherwise, check rule 4 if short[0] == short[1]: if element.count(short[0]) < 2: return False # rule 4: one instance of first letter in short must appear in element before second letter -- or reversed! else: if short[1] not in element[element.index(short[0]):]: return False return True if __name__ == '__main__': unittest.main()
from random import randrange from re import match def insert_or_append(dictionary, key, value): if key not in dictionary: dictionary[key] = [value] else: dictionary[key].append(value) class Twister(object): def __init__(self, data_source="data.txt"): self.latin_to_gibberish = {} with open(data_source) as handle: for line in handle: if match("\|\[\[..\|..\s..\]\]\|\|\w\s.*", line): upper, lower, latin = line[6], line[9], line[15] if latin == upper: continue insert_or_append(self.latin_to_gibberish, latin, upper) insert_or_append(self.latin_to_gibberish, latin.lower(), lower) def twist_up_letter(self, letter): if letter in self.latin_to_gibberish: index = randrange(0, len(self.latin_to_gibberish[letter])) return self.latin_to_gibberish[letter][index] return letter def twist_up(self, word): ret = "" for letter in word: ret += self.twist_up_letter(letter) return ret if __name__ == '__main__': tw = Twister() print(tw.twist_up("Hello, world")) print(tw.twist_up(""" For, after all, how do we know that two and two make four? Or that the force of gravity works? Or that the past is unchangeable? If both the past and the external world exist only in the mind, and if the mind itself is controllable – what then? """))
import folium import pandas as pd # we require only these three fields from the dataset fields=['name_of_city','population_total','location'] data_frame=pd.read_csv("indian cities.csv",usecols=fields) #location column of data_frame consist of both latitude and longitude seperated by a ','. #seperate them into two columns. new = data_frame["location"].str.split(",", n = 1, expand = True) data_frame["Latitude"]= new[0] data_frame["Longitude"]= new[1] #deleting location column as it's no more required data_frame.drop(['location'],axis=1) #creating a background map of india map_india=folium.Map(location=[22.778,80.434],zoom_start=5) #iterating the whole data_frame for index,i in data_frame.iterrows(): #marking the cities on map having population greater than 500000 if(i['population_total']>500000): folium.Marker(location=[float(i['Latitude']),float(i['Longitude'])], tooltip=i['name_of_city']).add_to(map_india) #saving the map as an html file map_india.save('india_map.html')
''' Challenge #5. Your challenge for today is to create a program which is password protected, and wont open unless the correct user and password is given. For extra credit, have the user and password in a seperate .txt file. for even more extra credit, break into your own program :) ''' import hashlib import os def check_authorisation(username, password): user_pw_file = open('/home/associat/h/hauk/bots/DailyProgrammer/tmp/users.txt', 'r') for i in user_pw_file.readlines(): if( len(i.split()) > 1): user_details = i.split() if(user_details[0] == username and user_details[1] == password): user_pw_file.close() return True user_pw_file.close() return False def sys_login(): print("Welcome to the magical system! Please login to continue.") user = input("Enter your username: ") password = input("Enter your password: ") print("Verifying login...") pwhash = hashlib.sha1(password.encode('utf-8')) if(check_authorisation(user, pwhash.hexdigest()) == True): print("You are now verified... Loading secret modules...") else: print("You are TOTES unauthorised. GTFO.") def add_user(): user = input("Enter a new username: ") password = input("Please enter a new password: ") confirm_pw = input("Please confirm your new password: ") if(password == confirm_pw): pwhash = hashlib.sha1(password.encode('utf-8')) user_store = open('/home/associat/h/hauk/bots/DailyProgrammer/tmp/users.txt', 'at', encoding='utf-8') user_store.write(user + " " + (pwhash.hexdigest()) + '\n') user_store.close() #add_user() check_authorisation("eoghan", "blah") sys_login()
# quy = ["nam", 77, "Vinh", 21, ["Anime", "Manga"]] # dictionary # CRUD #key : value person = { "name": "Quý", "age": 20, "university": "hust", "ex": 2, "favs": ["Anime", "Manga"], } key = "age" if key in person: print(person[key]) else: print("Not found") # for key in person.keys(): # print(key, end="\t") # for key, value in person.items(): # print(key, value) # for value in person.values(): # print(value) # update # person["ex"] = 20 # person["gender"] = "male" # # delete # del person["age"] # print(person)
from random import * string = ["CHAMPION", "HERO", "SCHOOL", "SHOOT"] string = choice(string) work = list(string) updated_work = [] loop = True while loop: rand_work = choice(work) updated_work.append(rand_work) work.remove(rand_work) if len(work) == 0: loop = False print(*updated_work) ans = input("Guess work:").upper() if ans == string: print("Correct") else: print("Wrong")
# 1. Sử dụng hàm type() # 2. Đặt tên biến sau đây thì lỗi # - Minh Quang (có dấu cách) # - 1quang (tên có số ở đầu) # - print (tên trùng hàm có sẵn) # Rad = int(input("Radius?")) # area = 3.14 * Rad # print("Area = ",area) from turtle import * shape("turtle") color("blue","yellow") speed(-1) begin_fill() #A square # for i in range(4): # forward(100) # left(90) #An equilateral triangle # for i in range(3): # forward(150) # left(120) #A circle # circle(100) end_fill() #Multi-circles for i in range(15): circle(100) left(30) mainloop()
Cel = int(input("Enter the temperature in celsius?")) Fah = Cel * 1.8 + 32 print(Cel, "=", Fah)
# load pandas for data preprocessing import pandas as pd # a class for Loading and preprocessing data class LoadData(object): def __init__(self, file_loc): self.file_loc = file_loc def __load_seperate_data(self): # load data using pd dataframe data = pd.read_csv(self.file_loc) features = data[data.columns[:-1]] # seperate features labels = data[data.columns[-1]] # seperate labels return features, labels def load_processed_data(self): # seperate_data into features and labels features, labels = self.__load_seperate_data() # one hot encode features features_with_dummies = pd.get_dummies(features) # onehot encode labels labels_with_dummies = pd.get_dummies(labels, prefix="", prefix_sep="") # list the root_labels root_labels = labels_with_dummies.columns # return set of labels return { "features": features_with_dummies, "labels": labels_with_dummies, "root_labels": root_labels, }
class Node(): """ [Class] Node A class to represent the Open Street Map Node. Properties: - osmId : Open Street Map ID. - lat : Latitude of this cell. - lon : Longitude of this cell. - isRoad : Boolean to mark whether this Node is a part of a road. - connection : List of all connected node. - ways : A dictionary of Open Street Map Ways. - tags : dictionary of the Map Feature of this object (check Open Street Map - Map Features). """ def __init__(self): """ [Constructor] Initialize an empty node. """ self.osmId = "" self.lat = 0.0 self.lon = 0.0 self.isRoad = False self.connections = [] self.ways = {} self.tags = {} def fill(self, osmNode): """ [Method]fill Fill up several property of this object, such as: - osmId - lat - lon - isRoad - tags Parameter: - osmNode = osmium library node. """ self.osmId = f"{osmNode.id}" self.lat = osmNode.location.lat self.lon = osmNode.location.lon for tag in osmNode.tags: self.tags[tag.k] = tag.v if 'highway' in self.tags.keys(): isRoad = True def addWay(self,way): """ [Method] addWay Add an Open Street Map Way into the ways property. Parameter: - way = Namazu Way (not osmium "Way", osmium "Way" is deleted after the loop). """ self.ways[way.osmId] = way def addConnection(self,connection): """ [Method] addConnection Add a node that is connected to this node. Parameter: - connection = Namazu Node. """ self.connections.append(connection) def __str__(self): """ [Method] __str__ Generate the summarized node information string and return it. Return: [string] String of summarized map Information. """ tempstring = f"id: {self.osmId}\nlat = {self.lat} lon = {self.lon} \nnumber of ways : {self.ways.__len__()}\nnumber of connections : {self.connections.__len__()}\nTags : \n" for key in self.tags.keys(): tempstring = tempstring + f"\t{key} : {self.tags[key]}\n" tempstring = tempstring + "\n" return tempstring def getPosition(self): """ [Method] getPosition generate a tuple of longitude and lat in that order. Return = (lon,lat) """ return (self.lat,self.lon)
import re import copy # ##################### 定制插件(HTMl) ##################### class TextInput(object): """ 定制前端页面的标签: :return: <input type='text' class="c1" ID='I1' ..../>" """ def __init__(self,attrs=None): """ 标签自定制属性功能 :param attrs: {'class':'c1', .....} """ if attrs: self.attrs = attrs else: self.attrs = {} def __str__(self): data_list = [] for k,v in self.attrs.items(): tmp = "{0}='{1}'".format(k,v) data_list.append(tmp) tpl = "<input type='text' {0}>".format(" ".join(data_list)) return tpl class EmailInput(object): def __init__(self, attrs=None): if attrs: self.attrs = attrs else: self.attrs = {} def __str__(self): data_list = [] for k, v in self.attrs.items(): tmp = "{0}='{1}'".format(k, v) data_list.append(tmp) tpl = "<input type='email' {0} />".format(" ".join(data_list)) return tpl class PasswordInput(object): def __init__(self, attrs=None): if attrs: self.attrs = attrs else: self.attrs = {} def __str__(self): data_list = [] for k, v in self.attrs.items(): tmp = "{0}='{1}'".format(k, v) data_list.append(tmp) tpl = "<input type='password' {0} />".format(" ".join(data_list)) return tpl # ##################### 定制字段(正则) ##################### class Field(object): def __str__(self): """ 保存用户输入的值,当用户调用过is_valid,则self.value有值, 在插件中增加属性 value = 用户提交过来的值 :return: 插件的str值,验证过则新增value = 输入值的属性 """ if self.value: self.widget.attrs['value'] = self.value return str(self.widget) class CharField(Field): default_widget = TextInput regex = "\w+" def __init__(self,widget=None): """ 初始化的时候,设置对应的插件,如果传入widget,则使用widget传入的插件对象, 如果未传入则使用默认的插件对象。 :param widget: 插件对象,TextInput()、EmailInput().... """ self.value = None self.widget = widget if widget else self.default_widget() def valid_field(self,value): self.value = value if re.match(self.regex,value): return True else: return False class EmailField(Field): default_widget = EmailInput regex = "\w+@\w+" def __init__(self,widget=None): self.value = None self.widget = widget if widget else self.default_widget() def valid_field(self,value): self.value = value if re.match(self.regex,value): return True else: return False # ##################### 定制Form ##################### class BaseForm(object): def __init__(self,data): """ 获取在类中生成的所有插件,设置到对象中,并添加到self.fields字典中, 供is_valid方法对所有注册的插件进行数据验证。 :param data: """ self.fields = {} self.data = data #用户form表单提交值 {"user":'Mitsui','email':'Mitsui@live.com'} #需要使用Form表单时,会继承BaseForm类,实例化生成对象时,self即需要在前端展示的form对象 #通过type(self)找到Form类,Form类__dict__中包含所有的类的静态字段,即使用form时创建的插件, #user = CharField() 插件都是继承自Field类,由此获取所有的插件 for name,field in type(self).__dict__.items(): #name:user, field:CharField() if isinstance(field,Field): #由于是静态字段,所以使用的是同一个对象,如果对其进行修改,会影响其它的form对象, #所以这里通过深拷贝防止对其进行修改 new_field = copy.deepcopy(field) #将类的这些静态字段设置到对象中,方便调用 setattr(self,name,new_field) self.fields[name] = new_field def is_valid(self): """ 将form组件设置的所有字段循环,交给每一个Field字段验证,如果有一个错误 返回False,否则返回True :return: """ flag = True for name,field in self.fields.items(): # name:user, field:CharField() user_input_val = self.data.get(name) result = field.valid_field(user_input_val) if not result: flag = False return flag # ##################### 使用Form ##################### class LoginForm(BaseForm): user = CharField() email = EmailField(widget=EmailInput()) #Django: # if request == "GET": # form = LoginForm() # return render('login.html',{'form':form}) # else: # form = LoginForm(request.POST) # if form.is_valid(): # pass # else: # pass l # Tornado: # def get(self, *args, **kwargs): # form = LoginForm() # self.render("login.html",form=form) # # def post(self, *args, **kwargs): # post_data = {} # for key in self.request.arguments: # if key == '_xsrf': continue # post_data[key] = self.get_arguments(key)[0] # form = LoginForm(post_data) # if form.is_valid(): # pass # else: # self.render('login.html',form=form)
debug = False with open("input.txt") as file: input = [line.strip() for line in file.readlines()] orbits = {} for connection in input: around, orbit = connection.split(")") orbits[orbit] = around count = 0 for orbit, around in orbits.items(): count += 1 # direct next = orbits.get(around) while next: count += 1 # indirect next = orbits.get(next) print("Part1 :", count) def findChildren(parent): children = [] for orbit, around in orbits.items(): if around == parent: children.append(orbit) return children def findParent(current): return orbits.get(current) found = False start = orbits.get("YOU") end = orbits.get("SAN") def walk(start, end, hops=0): debug and print("start", start) children = findChildren(start) debug and print("children", children) for child in children: debug and print("visit", child, hops) if child == end: debug and print("found", child, end, hops) return hops else: hops += 1 result = walk(child, end, hops) if result: return result return None parent_hops = 0 current = start while current and not found: child_hops = walk(current, end) if not child_hops: current = findParent(current) debug and print("new current", current) if current: parent_hops += 1 debug and print("parent hops", parent_hops) if current == end: found = True else: found = True if found: print("Part 2:", parent_hops + child_hops)
# https://www.hackerrank.com/contests/university-codesprint-2/challenges/breaking-best-and-worst-records n = int(input()) s = input().split() highest = int(s[0]) hcount = 0 least = int(s[0]) lcount = 0 s= s[1:] for i in s: if int(i) >highest: highest = int(i) hcount += 1 elif int(i) < least: least = int(i) lcount += 1 print(str(hcount), str(lcount), sep = " ")
##!/bin/python3 #https://www.hackerrank.com/contests/womens-codesprint-3/challenges/hackathon-shirts #https://www.hackerrank.com/contests/womens-codesprint-3/challenges/choosing-recipes import math import sys #sys.stdin = open("in","r") def hackathon_shirts(): t = int(input()) for case in range(t): n = int(input()) guests = map(int, input().split()) guests = sorted(guests) m = int(input()) ranges = [] for i in range(m): b,e = map(int, input().split()) ranges.append((b,1)) ranges.append((e,2)) ranges = sorted(ranges) ans = 0 j = 0 start = 0 start_point = 0 for cr in ranges: if cr[1]==1: if start==0: start_point = cr[0] start=start+1 if cr[1]==2: start=start-1 if start==0: #a group of overlapped ranges ended end_point = cr[0] while j<n and guests[j]<=end_point: if guests[j]>=start_point: ans = ans + 1 j = j + 1 print(ans) def choosing_recipes(): q = int(input().strip()) for a0 in range(q): r,p,n,m = input().strip().split(' ') r,p,n,m = [int(r),int(p),int(n),int(m)] pantry = list(map(int, input().strip().split(' '))) cost = list(map(int, input().strip().split(' '))) recipe = [] for recipe_i in range(r): recipe_t = [int(recipe_temp) for recipe_temp in input().strip().split(' ')] recipe.append(recipe_t) rec = [] for a1 in recipe: count = 0 for i in range(len(a1)): if i not in pantry: count+=a1[i]*cost[i] rec.append(count) print(rec) choosing_recipes()
limit = 150000000 result = 0 def IsProbablePrime(num): for i in range(2, int(num/2)): remain = num % i if remain == 0: return False return True for i in range (10, limit, 10): squared = i * i; if squared % 3 != 1: continue if squared % 7 != 2 & squared % 7 != 3: continue if (squared % 9 == 0 & squared % 13 == 0 & squared % 27 == 0): continue print (i) if IsProbablePrime(squared + 1) and IsProbablePrime(squared + 3) and IsProbablePrime(squared + 7) and IsProbablePrime(squared + 9) and IsProbablePrime(squared + 13) and IsProbablePrime(squared + 27) and not IsProbablePrime(squared + 19) and not IsProbablePrime(squared + 21): result += i print (result)
import time def timing(f, n, a): print f.__name__, r = range(n) t1 = time.clock() for i in r: f(a); f(a); f(a); f(a); f(a); f(a); f(a); f(a); f(a); f(a) t2 = time.clock() print round(t2-t1, 3)
# Python program to print prime factors import math def primeFactors(n): # Print the number of two's that divide n dic = {} while n % 2 == 0: if 2 in dic: dic[2] += 1 else: dic[2] = 1 n = n / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3,int(math.sqrt(n))+1,2): # while i divides n , print i ad divide n while n % i== 0: if i in dic: dic[i] += 1 else: dic[i] = 1 n = n / i # Condition if n is a prime # number greater than 2 if n > 2: if n in dic: dic[n] += 1 else: dic[n] = 1 return dic n = int(input()) arr = primeFactors(n) arr2 = [] for key in arr: arr2.append(arr[key]) length = len(arr2) ans = 0 #print("ura") while True: sqrt = True if len(arr2) == 0: break for i in arr2: if i%2 == 1: sqrt = False break if sqrt: ans += 1 for i in range(length): arr2[i] = arr2[i]/2 else: break p = 0 start = 1 if len(arr2) ==0: a = 1 else: a = max(arr2) for i in range(1000): if start<a: start *= 2 p += 1 else: break plus1 = False for i in range(length): if arr2[i] <start: plus1 = True break if plus1: ans += p + 1 else: ans += p ans0 = 1 for i in arr: ans0 *= i print(int(ans0),ans)
#https://www.hackerrank.com/challenges/pacman-bfs bfs #https://www.hackerrank.com/challenges/pacman-astar a* search #https://www.hackerrank.com/challenges/n-puzzle a* search def neighbors(edges, x,y): result = [] if x !=0: result.append((x-1,y)) if y != 0: result.append((x, y-1)) if y+1 < len(edges[0]): result.append((x,y+1)) if x+1< len(edges): result.append((x+1,y)) return result def f(): x,y = [int(i) for i in input().split()] fx,fy = [int(i) for i in input().split()] r,c = [int(i) for i in input().split()] matrix = [] for i in range(r): a = input() matrix.append(a) queue = [(x,y)] discovered = [] count = 0 trace = [[0]*c for i in range(r)] trace[x][y] = (x,y) while len(queue) != 0: item = queue.pop(0) if item not in discovered: if matrix[item[0]][item[1]] == "-" or matrix[item[0]][item[1]] == "P": count+= 1 for i in neighbors(matrix, item[0], item[1]): queue.append(i) trace[i[0]][i[1]] = item discovered.append(item) if matrix[item[0]][item[1]] == ".": count+=1 discovered.append(item) break print(count) for i in discovered: print(i[0],i[1]) tracearray = [] traceback = (fx,fy) print(fx,fy) counter =0 print(trace[5][2]) print(trace[5][3]) while traceback != (x,y): counter+=1 tracearray.append(traceback) traceback = trace[traceback[0]][traceback[1]] if counter == 3: print(traceback) break print(len(tracearray)) tracearray.append((x,y)) for i in reversed(tracearray): print(i[0],i[1]) f()
#https://www.hackerrank.com/contests/w29/challenges/day-of-the-programmer y = int(input().strip()) if y == 1918: print( "26.09.1918") elif y<1918: if y %4 == 0: print( "12.09."+str(y)) else: print( "13.09."+str(y)) else: if (y %400==0) or (y%4==0 and y%100!=0): print( "12.09."+str(y)) else: print( "13.09."+str(y))
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data """ MNIST is the machine learning "hello world" MNIST:Mixed National Institute of Standards and Technology database 数据库,存储各个国家地区,不同标准手写数字 """ """ MNIST data split three parts: 1.mnist.train:55000 data points of train 2.mnist.test :10000 points of test 3.mnist.validation: 5000 points fo validation data MNIST data points two parts: 1.an image of a handwritten digit 2.a corresponding label the train set and test set contain images and their corresponding labels """ mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#!/usr/bin/env python from time import sleep, time # Allows us to call the sleep function to slow down our loop import RPi.GPIO as GPIO # Allows us to call our GPIO pins and names it just GPIO GPIO.setmode(GPIO.BCM) # Set's GPIO pins to BCM GPIO numbering SW_PIN = 4 TX_PIN = 17 RX_PIN = 27 # rx 2 - 17 # tx 3 - 4 # sw 5 - 27 GPIO.setup(SW_PIN, GPIO.OUT) GPIO.output(SW_PIN, 0) GPIO.setup(TX_PIN, GPIO.OUT) GPIO.setup(RX_PIN, GPIO.IN) reading = False # Start a loop that never ends while True: if (GPIO.input(RX_PIN) == True): # Physically read the pin now active = True st = time() while active: print(str(bool(GPIO.input(RX_PIN))))
def add(a, b): return a + b def greeting(name, times): greeting_str = "" for _ in range(times): greeting_str += "Hi " + name + "\n" return greeting_str def return_values(a, b): return a * 2, b * 3, a * b def main(): x = add(2, 3) print(x) ret_str = greeting("Jonas", 3) print(ret_str, end="") ret_str = greeting("Anna", 5) print(ret_str, end="") y = return_values(4, 5) print(y) a,b,c = return_values(4, 5) print(a) print(b) print(c) if __name__ == '__main__': main()
def my_func(*args): print("my_func with", len(args), "args") for value in args: print(value) def my_func_2(**kwargs): print("my_func_2 with", len(kwargs), "kwargs") print(type(kwargs)) print(kwargs) for k, v in kwargs.items(): print(k, "=", v) def my_func_3(*args, **kwargs): print("my_func_3 with", len(args), "args, and", len(kwargs), "kwargs") print("args:", args) print("kwargs:", kwargs) def main(): my_func(1, 3) my_func(2, 4, 6, 8) my_func(9) my_func() my_func_2(name="Jonas", age=28) my_func_2(city="London", country="UK", value=34) my_func_3(1, 2, 3, name="Jonas", age=28) my_func_3() my_func_3(animal="Dog") my_func_3(2, 3) if __name__ == '__main__': main()
''' Created on Feb 1, 2018 @author: catad ''' from board.board import * ''' board = Board() b = board.setBoard() print(b) move = Square(1, 2, 1) s = Strategy(board) validator = Validate(board) game = Play(board, 0, s) control = MoveControl(game, validator) play = Play(board, 1, s) print(play.moveChaos(move)) print(play.moveOrder) ''' class UI: def __init__(self): self._play = Play(strategy) def StartUI(self): print(str(self._play._board)) turn = 2 if self._play._board.checkWin() == True: print("Computer wins!") if self._play._board.checkFull() == True: print("User wins.") while (not self._play._board.checkWin() and not self._play._board.checkFull()): if turn%2 == 0: self._play.moveOrder() else: row = int(input("row: ")) column = int(input("column: ")) value = str(input("symbol(X or O): ")) if value == 'X': symbol = 1 elif value == 'O': symbol = -1 else: symbol = -2 move = Square(row, column, symbol) self._play.moveChaos(move) turn += 1 print(str(self._play._board)) board = Board() strategy = Strategy(board) play = UI() play.StartUI()
from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() class Game(db.Model): """Board game.""" __tablename__ = "games" game_id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(20), nullable=False, unique=True) description = db.Column(db.String(100)) def connect_to_db(app, db_uri="postgresql:///games"): app.config['SQLALCHEMY_DATABASE_URI'] = db_uri db.app = app db.init_app(app) def example_data(): """Create example data for the test database.""" #FIXME: write a function that creates a game and adds it to the database. twister = Game(name="Twister", description="Twist your body") charades = Game(name="Charades", description="Act things out") dominoes = Game(name="Dominoes", description="Match numbers and build a train") jenga = Game(name="Jenga", description="Stack blocks without knocking over the tower") db.session.add_all([twister, charades, dominoes, jenga]) db.session.commit() if __name__ == '__main__': from server import app connect_to_db(app) print "Connected to DB."
""" If we calculate a2 mod 6 for 0 ≤ a ≤ 5 we get: 0,1,4,3,4,1. The largest value of a such that a2 ≡ a mod 6 is 4. Let's call M(n) the largest value of a &lt; n such that a2 ≡ a (mod n). So M(6) = 4. Find ∑M(n) for 1 ≤ n ≤ 107. """ import sympy def M(n): if sympy.isprime(n): return 1 for a in range(n, 1, -1): if pow(a, 2, n) == a: return a return 0 print(sum(M(n) for n in range(1, 10**7)))
""" Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20  7  8  9 10 19  6  1  2 11 18  5  4  3 1217 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? """ tot = 1 end = 1 N = 1001 for i in range(3, N + 1, 2): tot += 10 * (i - 1) + 4 * end end = i**2 print(tot)
""" It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5)24 cm: (6,8,10)30 cm: (5,12,13)36 cm: (9,12,15)40 cm: (8,15,17)48 cm: (12,16,20) In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles. 120 cm: (30,40,50), (20,48,52), (24,45,51) Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed? """ from math import sqrt, ceil import numba import numpy as np from time import time N = 1500000 @numba.jit(nopython=True, cache=True) def gcd(a: int, b: int) -> int: if b: return gcd(b, a % b) else: return a @numba.jit(numba.int32[:, :](numba.int32), nopython=True, cache=True) def pythagorean_triples(max_perimeter): max_m = int(sqrt(max_perimeter / 2)) triples = np.zeros((10 * max_m ** 2, 3), dtype=np.int32) count = 0 for m in range(2, max_m): for n in range(1, m): if ((n + m) % 2 == 1) and (gcd(n, m) == 1): a = m**2 - n**2 b = 2 * m * n c = m**2 + n**2 for k in range(1, int(ceil(max_perimeter / (a + b + c)))): if (k*a + k*b + k*c) <= max_perimeter: triples[count] = np.array((k*a, k*b, k*c)) count += 1 triples = triples[:count] return triples t = time() trips = pythagorean_triples(N) unique, counts = np.unique(np.sum(trips, axis=1), return_counts=True) answer = np.sum(counts == 1) t = time() - t print("Answer {} computed in {} seconds.".format(answer, t))
""" Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n &gt; 1? """ digits = set(range(1, 10)) def concat_prod(integer, n): return ''.join(str(integer * i) for i in range(1, n + 1)) def is_pandigital(n): n = str(n) return len(n) == 9 and set(int(i) for i in n) == digits vals = {} for i in range(10**4): # max digits is 4 since will have > 1 pieces ndigits = len(str(i)) max_n = 9 // ndigits for n in range(2, ndigits + 1): c = concat_prod(i, n) if is_pandigital(c): vals[(i, n)] = int(c) max_k = max(vals, key=lambda x: vals[x]) print(max_k, vals[max_k])
#python 3.7.2 """ Alternate Name: Annual Savings *compute annual dollar amount on savings invested at 10% over i_Years years variables: **i_Years = duration of investment **f_interest = interest ragte **f_iniInvest= initial investment output savings in last year (i_Years) """ import numpy as np #define variables i_Years = 30 f_interest = 0.1 f_iniInvest = 1e4 #Computation def annual_return(f_iniInvest,f_interest,i_Years): currInvest=f_iniInvest for i in range(i_Years): fGrowth=currInvest*f_interest #print('Year',i+1,'savings',round(currInvest,2)) currInvest += fGrowth return currInvest print(annual_return(f_iniInvest,f_interest,i_Years))
palindrom_lst = [] for i in range(101, 999): print('i =',i) for j in range(i, 999): multi_IJ = str(i * j) # palindrom = multi_IJ[::-1]# print(i, '*', j, '=', str(i * j)) #print(palindrom) if palindrom == multi_IJ: palindrom=int(palindrom) print(palindrom) palindrom_lst.append(palindrom) print(palindrom_lst) #количество таких чисел print() # print(max(palindrom_lst))
import matplotlib.pyplot as plt import numpy as np x = np.arange(0,2*np.pi,0.1) # start,stop,step y = np.sin(x) z = np.cos(x) plt.plot(x,y,x,z) tan_y = np.tan(x) plt.plot(x, tan_y) plt.legend(['sin(x)', 'cos(x)', 'tan(x)']) plt.title("Sin, Cosine, and Tangent One Period") plt.show()
age = int(input("Сколько тебе лет?\n")) if (age < 18 ): print("Тебе нет 18!") else: print("Проходи")
# Leader (Theory from Codility) # Uses python3 def slowLeader(A): # O(n^2) n = len(A) leader = -1 for k in range(n): candidate = A[k] count = 0 for i in range(n): if A[i] == candidate: count +=1 if count > n//2: leader = candidate return leader def fastLeader(A): # (n logn) n = len(A) candidate = A[n//2] A.sort() # O (nlogn) leader = -1 count = 0 for i in range(n): if A[i] == candidate: count += 1 if count > n//2: leader = candidate return leader def goldenLeader(A): # O(n) leader = -1 candidate = -1 lst = [] n = len(A) size = 0 count = 0 for elem in A: if size == 0: lst.append(A) value = elem size +=1 else: if elem != value: size -= 1 else: size += 1 if size > 0: candidate = value for elem in A: if elem == candidate: count += 1 if count > n//2: leader = candidate return leader # Example of usage if __name__ == "__main__": A =[6,8,4,6,8,6,6] print(slowLeader(A)) print(fastLeader(A)) print(goldenLeader(A))
# Fibonacci # Uses python3 def fibonacci(n): if n < 3: return 1; else: return(fibonacci(n-1) + fibonacci (n-2)) # Example of usage if __name__ == "__main__": number = int(input("Enter fibonacci number: ")) result = list() for i in range(1,number+1): result.append(fibonacci(i)) print(result)
import random print("SIMPLE GAME OF SNAP!") print("===================="); #set loop condition to false snap = False #create array of cards deckOfCards = ["1","2","3","4","5","6","7","8","9","10","jack","queen","king"] lengthOfArray = len(deckOfCards) while snap==False: #get element from the array using the randrange and len to determine the array size card1 = deckOfCards[random.randrange(0, lengthOfArray)] #get element from the array using the randrange and len to determine the array size card2 = deckOfCards[random.randrange(0, lengthOfArray)] #check if snap if card1==card2: print("**********") print("** SNAP **") print("**********") print("Cards were " + card1 + " and " + card2) snap = True else: print("Unlucky :( Cards were " + card1 + " and " + card2)
import math def length(x, y, a, b): return math.sqrt(pow(x - a, 2) + pow(y - b, 2)) class Thing: def __init__(self, x, y, keys): self.x = x self.y = y self.keys = keys def use(self, key, map): map.use_key(key) self.x = map.thing[0] self.y = map.thing[1] def conclude(self, key, init_x, init_y, map): if (init_x, init_y) == (self.x, self.y): key.value = -1 else: if (length(init_x, init_y, self.x, self.y)) > length(init_x, init_y, self.x, self.y): key.value = 2 else: key.value = 1
class BST: # to initialize a BST, construct a node to be the root def __init__(self): self.root = None return # to create a new key-value pair # or to update a existed key-value pair def put(self, key, value): self.root = self.__putNode(self.root, key, value) return def __iter__(self): queue = list() self.__inorder(self.root, queue) return iter(queue) def __inorder(self, node, queue): if node is None: return self.__inorder(node.left, queue) queue.append(node.key) self.__inorder(node.right, queue) # put a node in order def __putNode(self, node, key, value): # if there is not a node, then create a new one if node == None: return self.__node(key, value) compare = self.__compateTo(key, node.key) # if the new key is smaller than current node, shift to the left if compare < 0: node.left = self.__putNode(node.left, key, value) # if the new key is larger than current node, shift to the left elif compare > 0: node.right = self.__putNode(node.right, key, value) # if the new key is equal to current node, update the value else: node.value = value # update the node # count of nodes in this tree is the sum of 2 subtree's size and itself node.count = 1 + self.__sizeNode(node.left) + self.__sizeNode(node.right) return node # to get the value of given key def get(self, key): node = self.root while node is not None: compare = self.__compateTo(key, node.key) if compare < 0: node = node.left elif compare > 0: node = node.right else: return node.value return None # return the number of nodes in the tree def size(self): return self.__sizeNode(self.root) # return the number of nodes in the subtree with the root of this node @staticmethod def __sizeNode(node): if node is None: return 0 else: return node.count # return how many keys are smaller than a specific key def rank(self, key): return self.__rankNode(self.root, key) # return how many keys are smaller than a specific key in the subtree with the root of this node def __rankNode(self, node, key): if node is None: return 0 compare = self.__compateTo(key, node.key) # if the specific key is smaller than the node's key, shift to the left subtree. if compare < 0: return self.__rankNode(node.left, key) # if the specific key is larger than the node's key, add the node itself and all the nodes in the left subtree. # than shift to the right subtree elif compare > 0: return 1 + self.__sizeNode(node.left) + self.__rankNode(node.right, key) else: return self.__sizeNode(node.left) # every node has 5 fields: key, value, reference to left subtree, reference to right subtree, count of nodes in subtrees class __node: def __init__(self, key = None, value = None): self.key = key self.value = value self.left = None self.right = None self.count = 1 return @staticmethod def __compateTo(a, b): if a > b: return 1 elif a < b: return -1 else: return 0 BST = BST() BST.put('d', 20) BST.put('a', 15) BST.put('d', 12) BST.put('f', 22) BST.put('c', 18) print(BST.get('d')) print(BST.size()) print(BST.rank('e')) for key in BST: print(key, end = ' ') print('\n')
def feq(str): s_list = str.split() unique_words = set(s_list) for words in unique_words: print('Frequency of ', words, 'is :',s_list.count(words)) str = 'I am a good boy and i am good in gaming and also in coding' freq(str)
from collections import defaultdict direction_deltas = { "<": (-1, 0), ">": (1, 0), "^": (0, 1), "v": (0, -1) } def take_turn(current_position, delivery_map, direction): current_position = tuple([sum(x) for x in zip(current_position, direction_deltas[direction])]) delivery_map[current_position] += 1 return current_position, delivery_map def got_at_least_one_present(directions): """ >>> got_at_least_one_present(">") 2 >>> got_at_least_one_present("^>v<") 4 >>> got_at_least_one_present("^v^v^v^v^v") 2 """ current_position = (0, 0) delivery_map = defaultdict(int, {(0, 0): 0}) for direction in directions: current_position, delivery_map = take_turn(current_position, delivery_map, direction) return len(delivery_map) def with_robo_santa(directions): """ >>> with_robo_santa("^v") 3 >>> with_robo_santa("^>v<") 3 >>> with_robo_santa("^v^v^v^v^v") 11 """ positions = [(0, 0), (0, 0)] delivery_map = defaultdict(int, {(0, 0): 2}) for x in range(len(directions)): positions[x % 2], delivery_map = take_turn(positions[x % 2], delivery_map, directions[x]) return len(delivery_map) if __name__ == "__main__": import doctest doctest.testmod()
# fact = int(input("enter the nop. ")) # def fact(fact): # for i in range(1,fact): # fact = i*(i+1) # return fact # print(fact) # fact(8) def factorial(n): fac = 1 for i in range(n): fac = fac * (i +1) return fac num = int(input("enter the no. ")) print(factorial(num))
list = [6, 9, 70, 7, 44, ] for item in list: if item>6: print(item)
import random lst = ["snake", "water", "gun"] choice = random.choice(lst) print(" welcome t6o snake water gun game") inpt = str(input("choose between snake, gun and water: ")) if inpt=="snake" and choice == "water": print("opponent is water \n snake drunk the water") elif inpt == "snake" and choice == "gun": print("opponent is gun \nsnake died") elif inpt == "water" and choice== "gun": print("opponent is gun\ngun damaged") elif inpt == "water" and choice== "snake": print("opponent is snake \nwater is drunk") elif inpt == "gun" and choice== "water": print("opponent is water \n your gun damaged") elif inpt == "gun" and choice== "snake": print("opponent is snake \nyou killed the snake") elif inpt == choice: print("both choose the same")
cgpa={} cgpa ["rafay"]=3.5 cgpa ["ali"]=2 cgpa ["khan"]=3.5 for k in cgpa.keys(): if(cgpa[k]<2.5 ): print("no degree's",k) else: print("degree awaded",k)
weather=int(input("enter your month ")) if weather<3 : print("winter") elif weather<6 : print("spring") elif weather<12 : print("summer")
#Q1 def number(): a=int(input("Enter 1st Number ")) b=int(input("Enter 2nd Number ")) print("Addition of two numbers is ",a+b) print("Subtraction of two numbers is ",a-b) print("Division of two numbers is ",a/b) print("Multiplication of two numbers is ",a*b) number() #Q2 print() def covid(p_name,temp=98): print("pateint name : ",p_name) print("Body temperature : ",temp) print() covid('John') covid('Peter',102)
import sys if __name__ == "__main__": print("number args", len(sys.argv)) print("arguments", str(sys.argv)) user_input = [] is_input = False if len(sys.argv) == 7: is_input = True user_input= '[' for i in range(1,6): user_input += sys.argv[i] user_input += ', ' user_input += '1]' print(user_input) else: print("bad input, will not be displayed") with open("output.txt", "r") as f: data = f.read() data = data.split('Proof:\n')[1].split('\ngenerate-proof successful: true\n')[0] data = data.split('\n') res = "" result_list = [] for line in data: if len(line) > 0: ls = line.split('(')[-1].split(')')[0] if ls[0] == '0': ls = ls.split(', ') res = '["' + ls[0] + '", "' + ls[1] + '"]' else: res = ls res = res.replace('[', '') res = res.replace(']', '') res = res.replace(',', '') res = res.split(' ') res = '[["' + res[0] + '", "' + res[1] + '"], ["' + res[2] + '", "' + res[3] + '"]]' result_list.append(res) if is_input: result_list.append(user_input) print("### LIST ###") print(result_list) one_line = ','.join(result_list) print("### ONE LINE ###") print(one_line)
# /usr/env/python # encoding:utf-8 import os import time from GameOfLife import GameOfLife clear = lambda: os.system('clear') def main(): clear() print("Game of Life") rows, cols = int(input("How many Rows:")), int(input("How many Columns:")) game = GameOfLife(rows, cols) while True: clear() print(game) game.iterate() time.sleep(0.5) if __name__ == '__main__': main()
import webbrowser #open browsers import time #control time, like sleep import random #random ranges or numbers while True: randomSite=random.choice(['google.com','yahoo.com','bing.com','reddit.com']) #a list of sites that are going to be selected randomly and used as a value (string) only visit = "http://{}".format(randomSite)# change the style of text, and format it to url webbrowser.open(visit) #execute webbrowser to open the formatted url seconds=random.randrange(5,20) #set a random amount of seconds to open the site, or wait to open the new one time.sleep(seconds) # put loop to sleep this amount of time, before opening another website
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def binaryTreePaths(self, root): """ Given a binary tree, return all root-to-leaf paths. 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] :type root: TreeNode :rtype: List[str] """ if root: paths = self.binaryTreePaths(root.left) + self.binaryTreePaths(root.right) if len(paths) == 0: return [str(root.val)] else: return [str(root.val) + '->'+ path for path in paths] else: return []
print("****************read****************") f3 = open("user.txt", "r") x= f3.read()# returns the string that contains file data print(type(x)) #print all print(x) f3.close()
# take size as input and perform the sum for the entered numbers s = 0 while (s < 100): num = int(input("enter num")) if (num > 0): s = num + s print("sum of num=", s) s = 0 while (s < 100): num = int(input("enter num")) if (num < 0): continue s = num + s print("sum of num=", s) s = 0 while (s < 100): num = int(input("enter num")) if (num < 0): continue if (num == 999): break s = num + s print("sum of num=", s) # TAKE INT AS INPUTS CONTINUOSLY , AND PERFORM SUM , IF THE SUM >= 50 stop and print sum= 0 while sum <50: i = int(input('enter number')) sum= sum+i; print("current sum =",sum) print(sum) # TAKE INT AS INPUTS CONTINUOSLY , AND PERFORM SUM , IF THE SUM >= 50 stop and print , if negative num --> dont sum sum= 0 while sum <50: i = int(input('enter number')) if i<0 : continue # take you to next iternation by stopping curren iteration sum= sum+i; print("current sum =",sum) print(sum) # TAKE INT AS INPUTS CONTINUOSLY , AND PERFORM SUM , IF THE SUM >= 50 stop and print , if negative num --> stop algorithm , and display current sum sum= 0 while sum <50: i = int(input('enter number')) if i<0 : break # stop all iterations and come out of the loop sum= sum+i; print("current sum =",sum) print(sum) # we can write the else block for a while loop sum= 0 while sum <50: i = int(input('enter number')) if i<0 : break # stop all iterations and come out of the loop sum= sum+i; print("current sum =",sum) else : # executes ocne the loop is done print(sum)
""" #how to take the inputs from the console # use input() function #by default input() funtn considers every value as string syntax: x = 90 #[value is provided by dev] x = input("enter num") # value provided from console/command prompt its is the dev responsibility to convert from string to any other data type: how to convert from str to int? use int() function how to convert from str to float? use float() function 1.How to take string as input x= input("enter name") 2.How to take int as input x = int( input("enter num") ) 3.How to take float as input x = float( input("enter decimal") ) """ a = input("enter a num") b = input("enter a float") c = input("enter a string") print(type(a),type(b),type(c) ) a = int(input("enter a number")) b= float(input("enter a float")) c = input("enter a string") print("value of a = ", a, type(a)) print("value of b = ", b,type(b)) print("value of c = ", c,type(c)) # input two string , sum not concactination num1 = "20.32" num2 = "21.45" # convert string, float to float -->float() n1 = float(num1) n2 = float(num2) print(n1+n2) # input two string , sum not concactination num3 = "20.56" num4 = 51 # convert string, int to float -->int() n1 = float(num3) # convert string to float n2 = float(num4) # convert float to float print(n1+n2) # input two string , sum not concactination num1 = "20" num2 = "31" # convert string, float to int -->int() n1 = int(num1) n2 = int(num2) print(n1+n2) # input two string , sum not concactination num3 = "20" num4 = 51.56 # convert string, float to int -->int() n1 = int(num3) # convert string to int n2 = int(num4) # convert float to int print(n1+n2)
import xlwt from xlwt import Workbook wb = Workbook() # add_sheet is used to create sheet. sheet1 = wb.add_sheet('Data') list = [ (10,20), (30,56) ] r=0 for row in list: c=0 for data in row: sheet1.write(r,c, data) c = c+1 r = r+1 wb.save('example2.xls') #This package is for writing data and formatting information to older Excel files (ie: .xls # You’ll learn how to work with packages such as pandas, openpyxl, xlrd, xlutils and pyexcel. # Workbook is created
""" Req: Person has id, name, age as instance variables Employee has id, name, age, pan, pfNo as instance variables create obj and set data for person and employee. w/o inheritence ------------------------------------------ class Person: id=None name=None age=None def showPersonalInfo(self): print(self.id) print(self.name) print(self.age) class Employee : pan= None pfNo=None id=None name=None age=None def printEmp(self): print(self.pan) print(self.pfNo) print(self.id) print(self.name) print(self.age) With Inheritence: -------------------------------------------------- #Person class as parent class Person: id=None name=None age=None def showPersonalInfo(self): print(self.id) print(self.name) print(self.age) class Employee(Person): pan= None pfNo=None def printEmp(self): print(self.pan) print(self.pfNo) """ #Person class as parent class Person: id=None name=None age=None def showPersonalInfo(self): print(self.id) print(self.name) print(self.age) #Employee class as child class Employee(Person): pan= None pfNo=None def printEmp(self): print(self.pan) print(self.pfNo) # emp class is reusing id,name,age and showPersonalInfo() funtn # create obj ; set data and show print("print person info") p = Person() p.id = 2000 p.name = "user1" p.age = 34 p.showPersonalInfo() # shows id,name, age for person print("print employee info") emp = Employee() emp.id = 4000 emp.name = "user2" emp.age = 39 emp.pan = "testpan" emp.pfNo = "testpf" emp.showPersonalInfo() # shows id,name, age for emp emp.printEmp() # show pan, pfNo of emp # emp obj is reusing id,name,age and showPersonalInfo() funtn #showPersonalInfo() can be called by parent obj and child obj
""" Write a function that prints welcome msg and call the function blocks: if if else elif for while function """ #write the function def myFunction(): print("Hello") print("Bye") #call the function myFunction() myFunction() myFunction()
""" Req: Perform div of two nums if the second num is zero then throw exception. and handle the exception """ def div(n1, n2): if n2 == 0: raise ArithmeticError("NUM2 cannot be zero") print(n1 / n2) try: div(6,2) div(6, 0) div(6, 3) except ArithmeticError as ex: print("issue due to ", ex) print("end")
num1 = int(input("Enter num1")) num2 = int(input("Enter num2")) num3 = int(input("Enter num3")) if (num1 > num2): #big is between num1 and num3 if (num1 > num3): print("Big = ", num1) else: print("Big = ", num3) else: # big is between num2 and num3 if (num2 > num3): print("Big = ", num2) else: print("Big = ", num3)
#assignmnets a=b=c=100 print(a,b,c) a,b,c =100,200,300 print(a,b,c) a,b,c = 100, 12.2424, "krishna" print(a,b,c) print("***********print with seperator********************") a,b,c =100,200,300 print(a,b,c, sep ="$")# seperator for every value. default seperator is single space" " #what should be the printed after every value print("***********print with end********************") print(a , end="***") # what should be the printed after the last value , default is "\n" print(b , end="***") print(c , end="***") print("hello", "python",) print("***********print with sep and end********************") print(a ,b, c ,sep="#" ,end="***") print("bye") print("***********print values ************************") """ o/p: a = 100 , b = 200 , c = 300 req: print combining multiple variables and values use the place holder approach. """ a,b,c= 70,90,80 print( "a = " , a , "b = " , b , "c = ", c) print("student 1 mark = {} , student 2 mark= {} , student 3 mark= {} ".format(a,b,c))
""" create a class with id, anme , age as instance variables. create obj , set data and display """ #create a class class Person: id=None age= None name=None def show(self): print("Hello") #create object p1 = Person() # set data p1.id = 90 p1.name="kumar" p1.age = 45 #dispaly print(p1.id) print(p1.name) print(p1.age)
""" write a function that takes 2 nums as input and prints the bigger number. """ #how to write function def big(x,y): if(x>y): print("Big = ", x) else: print("Big = ", y) # x, y , bigger are the local variables #how to call the function big(30,13) n1=56 n2=90 big(n1,n2) n3= int(input("enter num1")) n4= int(input("enter num2")) big(n3,n4) #n1,n2,n3,n4 are global variables. """ write a function that takes 2 nums as input and prints the smaller number. """ """ write a function that takes 3 nums as input and prints the smaller number. """ """ write a function that takes 3 nums as input and prints the bigger number. """
class PersonInfo: def __init__(self, pId, pName, pAge, pPan): self.__id = pId self.__name = pName self.__age = pAge self.pan = pPan #here id, name,age are private and pan is public def show(self): # public method ; can be callsed outside the class print(self.__id) print(self.__name) print(self.__age) print(self.pan) def show1(self): print(self.__id, self.__name, self.__age) def __process(self): #private method ; cannot be called outside the class print("hello im in private") #here PersonInfo is the class #__id , __name , __name are instance varioables #show() is instance method and is public #__process() is instance method and is private #private cannot be accessed outside the class myObj = PersonInfo(12000, "murali", 34, "myTestPan") myObj.show()
""" can we write try with multiple except blocks? Yes at a time only one except block is executed. For IndexError ,ZeroDivisionError ,ValueError we need to write 3 except blocks """ list = [1, 2, 3] x = 50 y = 0 age =None try: print(list[0]) print(list[7]) # trying to access 8th element but list has 4 elements divRes = x / y print("result = ", divRes) age = int(input("enter age") ) print("after concerting age= ",age) except IndexError as ex: print("invalid index please try again") except ZeroDivisionError as ex: print("denominator cannot be zero. Please correct ") except ValueError as ex: print("Please enter only digits for age") else: print("No exception")
# Str is commonly data type # by defualt we have buildin strin operations name= "hi Accumed It technologies bye" # find length of string size = len(name) print("length of str==", size) #upper name="Hi How Are you" upStr = name.upper() # creates a new string #lower lowStr = name.lower() # creates a new string print(upStr) print(lowStr) # string is ending with "bye" name= "hi Accumed technologies bye" flag = name.endswith("bye") if flag: print("string ends with bye") else: print("string doesnt end with bye") # string is starts with "bye" flag = name.startswith("hi") if flag: print("string begins with hi") else: print("string doesnt begins with hi") # word "tech" is substring of name?????? name= "hi Accumed technologies bye" s1="tech" s2 ="hi" s3="xyz" charNo = name.find(s1) # retuns int print(charNo) charNo = name.find(s2) # retuns int print(charNo) charNo = name.find(s3) # retuns int print(charNo) # find method returns int # int value >=0 ===> string is found # int value ==-1 ===> string is not found #find :---->>>> check sub string or find the position no print(name.index("tech")) # index funtion retunrs posi no: if the string is not found it throws exception # string concatenation name1 = "bangalore" name2="india" name3 = name1 + name2 print(name3) #repeater name= "kumar" name2 = name * 5 print(name2) # frequency str ="Hi shyam ! where are you shyam!! im back to work , shyam" # find no of times the word "shyam" is repetaed in string from 0 position countStr = str.count("shyam") print(countStr) # find no of times the word "shyam" is repetaed in string strating from 10th position countStr = str.count("shyam",10) print(countStr) # find no of times the word "shyam" is repetaed in string strating from 0th position #till 15th postion countStr = str.count("shyam",0,15) print(countStr) #split operation data in string seperated by # inputStr ="kumar#23#2334566#bncpk97404" data = inputStr.split("#") # retuns an array print(data[0]) print(data[1]) print(data[2]) print(data[3]) name="userR" print(name.isalpha()) # returns true if all chars are alphabets [a-z] [A-Z] name="1213242" print(name.isdigit()) # returns true if all chars are digits [0-9] name="user134131@" print(name.isalnum()) # returns true if all chars are alphabets + digits[a-z] [A-Z] and [0-9] #Replace word name= " shyam !!! kumar!! harsha!! jaya! shyam" newStr= name.replace("shyam", "shubham") print(newStr) # extract substring str ="hellouser! welcome to python! programmming is fun" print(str[0]) print(str[0:3])# substring from 0 position to 2nd position print(str[:4]) # extract 1st n chars print(str[10:25])# from 10th till 24 print("lasstt") print(str[-1]) # last char n print(str[-3]) # last f print(str[:-3]) # from 0 position till (size-3) position print(str[-3:]) # last three chras #capitalize :-- convert 1st char to capital # center() :-- centre char #islower() - is in lower? #isuuper() - is in upper? #isnumeric() #lstrip() ---> trim the white spaces in the begining #rstrip() ---> trim the white spaces at end #replace() # extract substring str ="Hellouser! welcome to python! programmming is fun" print(str[0]) print(str[0:3])# substring from 0 position to 2nd position print(str[:4]) # extract 1st n chars print(str[10:25])# from 10th till 24 print(str[-1]) # last but one n print(str[-3]) # last but three f print(str[:-3]) # from 0 position till (size-3) position print(str[-3:]) # last three chras print(str[2:-3]) # from 2nd till last but 3 # input : sentence o/p: no of times a word has been repetaed?? # hi kumar shyma kumar varsa shyam ram kumar
""" //take input for id , age , usertype //validate id & age , usertype //if id is positive print valid id , if not print invalid id //if age is greater than 18 print valid age else print invalid age //if usertype is "admin" print valid usertype else print invalid usertype if id is valid then only validate the age [ when age is invalid dont validate further ] if age is valid then only validate the usertype there is a dependency between the conditions solution: if and elif when should we use if and elif? -> there is a dependency between the conditions -> at a time only one block is executed """ #input id = int(input("enter id ")) age = int(input("enter age ")) usertype = input("enter usertype ") if id <0 : print("invalid id") elif (age < 18): print("valid id") print("invalid age") elif (usertype != "admin"): print("valid id") print("valid age") print("invalid usertype") else: print("valid id") print("valid age") print("valid usertype")
from conn import getConn con =getConn() cursor = con.cursor() #fetch only id,name from all persons print("conn success") sql1 = "SELECT ID,NAME FROM person " cursor.execute(sql1) myresult = cursor.fetchall() for row in myresult: print(row) if cursor: cursor.close() if con: con.close()
""" one parent having multiple child classes. RBI is a parent class SBI , HDFC , ICICI are the child classes for RBI RBI: Parent class has - createAccount() - processLoan() SBI is a child of RBI - demat1() HDFC is a child of RBI - demat2() ICICI is a child of RBI - demat3() Create obj for RBI , SBI , HDFC , ICICI and call the methods. """ class RBI: def createAccount(self): print("RBI:: account created") def processLoan(self): print("RBI:: roi 10%") class SBI(RBI): def demat1(self): print("SBI demat") class HDFC(RBI): def demat2(self): print("HDFC demat") class ICICI(RBI): def demat3(self): print("ICICI demat") """ How many methods in SBI? 3 [createAccount() , processLoan(), demat1() ] How many methods in HDFC? 3 [createAccount() , processLoan(), demat2() ] How many methods in ICICI? 3 [createAccount() , processLoan(), demat3() ] """ print("**********RBI**********") rbi = RBI() rbi.createAccount() # LOGIC FROM RBI rbi.processLoan() # LOGIC FROM RBI #crate obj print("**********SBI**********") sbi = SBI() sbi.createAccount() # LOGIC FROM RBI sbi.processLoan() # LOGIC FROM RBI sbi.demat1() # LOGIC FROM SBI print("**********HDFC**********") h = HDFC() h.createAccount()# LOGIC FROM RBI h.processLoan()# LOGIC FROM RBI h.demat2() # LOGIC FROM HDFC print("**********ICICI**********") i = ICICI() i.createAccount() # LOGIC FROM RBI i.processLoan() # LOGIC FROM RBI i.demat3() # LOGIC FROM ICICi
""" while loop - every for loop can be converted to while loop print("***************************Print numbers from 1 for 50 ****************************************") for i in range(1,51): print(i) start with 1 print till< 51 and increment by 1 init is before the while loop condition is part of the while statement increment/decrement is inside the while block """ i=1 while(i<51): print(i) i= i +1
import xlwt from xlwt import Workbook #This package is for writing data and formatting information to older Excel files (ie: .xls # You’ll learn how to work with packages such as pandas, openpyxl, xlrd, xlutils and pyexcel. # Workbook is created wb = Workbook() # add_sheet is used to create sheet. sheet1 = wb.add_sheet('Data') sheet1.write(1, 0, 'data1') sheet1.write(2, 0, 'data2') sheet1.write(3, 0, 'data3') sheet1.write(4, 0, 'data5') sheet1.write(5, 0, 'CLOCK TOWER') sheet1.write(0, 0, 'user1') sheet1.write(0, 1, 'user2') sheet1.write(0, 2, 'user3') sheet1.write(0, 3, 'user4') sheet1.write(0, 4, 'user5') sheet1.write(0, 5, 'user6') wb.save('example.xls') list = [ (10,20), (30,56) ] r=0 for row in list: c=0 for data in row: sheet1.write(r,c, data) c = c+1 r = r+1
# Pass by reference #write a function that takes obj as input arg def display(pObj): print(pObj.id) print(pObj.name) print(pObj.age) #write a function that returns person obj def getObj(id,name,age): pObj = Person() pObj.id = id pObj.name = name pObj.age = age return pObj def change(pObj): #pObj = p1, pObj and p1 are referring to same object pObj.id = 6790 pObj.name = "ramesh" pObj.age = 56 class Person: id=None age= None name=None #create obj + set data p1 = getObj(90,"kumar",45) #print obj print("****************show p1**********************") display(p1) #call the change function by pasisng the object change(p1) # assign p1 to pObj , pObj = p1 print("****************show p1 aftr calling change function **********************") display(p1) """ if you are passing a object to a function (ex:change()) and if the function modifies the object then it will have impact to the caller """
""" function that takes name as input and returns by appending Mr/Mrs """ def greet(name): res = "Mr/Mrs "+ name return res r1 = greet("murali") print(r1) r1 = greet("kumar") print(r1) r1 = greet("shyam") print(r1)
try: age = int ( input("enter age") ) print("after concerting age= ",age) except ValueError as ex: print("conversion not possible") print("end")
""" How to write the private function: --------------------------------------- - a private funtion should be written only inside the class - a private function cannot be accessed outside the class if we write "__" before the funtion name then the funtion will become private. ex: class Data: def show(self): print("show") def __hello(self): # private function print("helo") points: class: Data instance funtions: show() and __hello() public instance funtion : show() private instance funtion : __hello() """ def m1(): # global function print("global function called") class Data: def show(self): # instance function print("welcome to instance function....") def __hello(self): # private function print("helo") """ points: class: Data instance funtions: show() and __hello() public instance funtion : show() private instance funtion : __hello() """ # call global function m1() # call instance function d1 = Data() d1.show() # d1.hello() --> will not work # d1.__hello() --> will not work d2 = Data() d2.show()
# Python code to sort the tuples using second element # of sublist Inplace way to sort using sort() def Sort(sub_li): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used #While sorting via this method the actual content of the tuple is changed, #and just like the previous method, in-place method of sort is performed. sub_li.sort(key = lambda x: x[1]) return sub_li # Driver Code sub_li =[('ram', 10), ('akash', 5), ('raj', 20), ('gaurav', 15)] print(Sort(sub_li)) list1 =[('ram', 10), ('akash', 5), ('raj', 20), ('gaurav', 15)] list1.sort(key = lambda x: x[1]) print(list1) # Python code to sort the tuples using second element # of sublist Function to sort using sorted() #Sorted() sorts a list and always returns a list with the elements in a sorted manner, #without modifying the original sequence. #It takes three parameters from which two are optional, #here we tried to use all of the three: def Sort2(sub_li): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used return(sorted(sub_li, key = lambda x: x[1])) # Driver Code sub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]] print(Sort2(sub_li))
""" Threading: ------------ -> concurrent programming/ parallel programming. -> by default single thread is created by python to run prog. -> test 1000 test cases on chrome , firefox , internet explorer. solution: threading. Threads: ------------------------ -threading is used for parallel programming. [ Parallel programming means Executing multiple programs at the time] Advantage of thread: -response time is improved -utilization of resources Thread: -thread is a single unit created under the process -every thread has its own line of execution -every thread is independent when should we use thread? ----------------------------------- -when the tasks are independent of each other, i.e.the output of one task is not required for the another task - TEST the application in multiple browsers -when the thread is created it would not start immediately, because it is decided by the cpu, then it would run we cannot determine when the thread would start or end. thread states: -------------------------- 1. ready state -- when the developer creates the thread and adds to the cpu job list 2. running -- when cpu gives appointment to the thread 3. possible 3 states after running state a. dead state or completed state b. wait state : we don't know the time c. sleep state : we will know for how long it is going to know sleep adv: ---- -> save time , response time/Turn around time is improved. Process: Requires seperate memory. Thread: - is a single unit/agent under the process. - Thread uses the memory allocated for the Process. - Every thread has its own seprate execution. - We cannot predict when the thread starts or when the thread ends. It depends on CPU. -Every thread has name + priority. When do we need to create thread? A) When the tasks are independent to each other. o/p of one task is not required for the other task. By default python creates the main thread. using the main thread we need to create the additional threads. use module "threading" How to create Thread: ------------------------- 1. Create a Thread Class (ex:MyThread) extending threading.Thread 2. Provide the run() function inside the class. 3.create the Object for MyThread. 4.call the start method using the object. [start method internally calls the run() function] """
x = 90 def process(): y = 89 print("process") class Person: # instance variables id = None name = None age = None # instance funtion # every instance function has self as default arg def show(self): print("hello inside show") """ here x is a global variable y is a local variable process() is a global function show(self): is a instance function """ # Syntax for obj creation p1 = Person() # Set data p1.id = 30000 p1.name = "user1" p1.age = 45 # display data print(p1.id) print(p1.name) print(p1.age) #calling the function p1.show()
# declaration of a set # will not allow duplicates # search by content is fast # insertion order is not maintained. # item #set for nums myset = {1, 45, 3,4,1, 1, 23, 0, -1 } print(myset) # creating a set using a constructor mySet6 = set() print(mySet6) #set for strings myset2 = {'sap', 'java', 'hana', 'sap', 'hadoop', 'angularjs', 'java'} print(myset2) #set with data of multiple data types myset3 = {1, 'kumar', 23, 'kumar', 23, 1} print(myset3) print("***** Add new element ***************") # to add entry into the set myset3.add("mythri") myset3.add("mythri") myset3.add("mythri") print(myset3) print("***** search by content ***************") #search by content use 'in' print('kumar' in myset3) print('ram' in myset3) print("*****length of set ***************") #length print(len(myset3)) print("--------------iterate all-------------------------") #iterate all elements for data in myset3: print(data) print("------------delete kumar----------------") #delete by content myset3.remove("kumar") print(myset3) print(len(myset3)) myset4 = {1, 'raj', 23} myset5 = {'raj', 'banglalore', 'India'} print("***********minus operation***************") #perform minus operation on sets [ what is present in set1 but not in set2] res = myset4- myset5 print(res) res = myset5- myset4 print(res) # Union Opearation , merging both sets by avoiding duplicates, + opeartion is not applicable for sets print("*****************union of sets*********************************") res = myset4 | myset5 print(res) # Common in both the sets print("*******************common in sets**************************") res = myset4 & myset5 print(res) # symmetric diff # MERGE BOTH AND REMOVE COMMONS print("****************symmetric diff******************") res = myset4 ^ myset5 print(res) #how to convert list or tuple to a set #solution : use set() function. # convert list to set , use set() function myList = [1, 2, 3, 4, 1, 4, 1, 7, 8, 9, 1, 3] resSet = set(myList) print("list = ",myList) print("set = ",resSet) # convert a tuple to set, use set() function myTupl = (1, 2, 3, 4, 1, 4, 1, 7, 8, 9, 1, 3) resSet = set(myTupl) print("tuple = ",myTupl) print("set = ",resSet) """ # converst set to frozewn set ; # frozen will no any update/remove operations; used only for read operations f = frozenset(myset) print(type(f)) """
""" files: -------------- for working with files we need os module. create folder rename folder del folder create file del file write to file read from file file obj represents both file and folder. ex: import os """ import os import struct from os import path """ import os from os import path create a folder os.mkdir("<folder name>") how to check if folder exists: os.path.exists("<folder name>") # returs boolean How to remove a folder: os.rmdir("<folder name>") How to rename the folder: os.rename('<old folder name>', '<new folder name>') """ # create a folder import os.path if not os.path.exists("test5"): os.mkdir("test5") # rename a folder import os.path os.rename('test5', 'test56') # remove a folder import os.path os.rmdir("test56") os.chdir("test5") #print(os.listdir())
import os import os.path import struct from os import path #This function gives the name of the operating system dependent module imported. #The following names have currently been registered: �posix�, �nt�, �os2�, �ce�, �java� and �riscos� print(os.name) print(os.getcwd()) # For 32 bit it will return 32 and for 64 bit it will return 64 print(struct.calcsize("P") * 8) #check file exists def main(): print ("file exist:"+str(path.exists('guru99.txt'))) print ("File exists:" + str(path.exists('career.txt'))) print ("directory exists:" + str(path.exists('myDirectory'))) print ("Is it File?" + str(path.isfile('hello.txt'))) print ("Is it File?" + str(path.isfile('myDirectory'))) print ("Is it Directory?" + str(path.isdir('guru99.txt'))) print ("Is it Directory?" + str(path.isdir('myDirectory'))) main() #Python program to get OS name, platform and release information. import platform import os print(os.name) print(platform.system()) print(platform.release())
""" var arg function: a function that takes any umber of arguments. sum of any numbers: """ #WRITE THE FUNCTION def sum(*nums): res =0 for n in nums: res= res + n print(res) #sum funtion can be called by passing any number of values #call the function sum(1,2) sum(1,2,24,2,5,21,36,25,343,7,25,7,25,43,3256,47) sum(10,20,30) sum(1,2,42,1,4,214,14,4)
""" """ #code for returning value from the function def getData(): x = "Hello" return x #x is local varibles #call the function v1 = getData() print(v1) v2 = getData() print(v2)
#input : i/p func obj , return type: f2 obj """ outer functn : i/p: function obj ;; return :inner functn obj inner functn : i/p: NA , o/p: NA inner functn calls the functn using the function obj """ def f1(func): print("f1 is called") def f2(): print("f2 is called") func() return f2 @f1 def f3(): print("My f3 functn") @f1 def f4(): print("F4 function") print("*********************************** call f3 ********************************************************") f3() print("***************************************** call f4 **************************************************") f4()
""" Req: Person: id,name Student : branch User : id,name , branch ,pan create obj for User , set data and display. Solution: -> Create Person class -> Create Student class -> Create User class with Person , Student as parent classes call show() method that should print every thing """ class Person: id=None name=None def printPerson(self): print(self.id, self.name) class Student: branch=None def printStu(self): print(self.branch) # User is child for both Person,Student class User(Person,Student): pan = None def show(self): Person.printPerson(self) Student.printStu(self) print(self.pan) #create obj u = User() #set data u.id=1234 u.name="kumar" u.branch = "csc" u.pan="bncpk" #print data u.show() # prints id,name, branch , pan #call u.show() that should print the user info.