blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
aec3412a5cdf280635bae837c4133227c21f7507
joshuaDclark/US-Timezone-Converter
/converter.py
765
3.765625
4
from datetime import datetime from us_timezones import us_time import pytz fmt = '%Y-%m-%d %H:%M:%S %Z%z' while True: date_input = input("Enter date here: (set date as shown --> MM/DD/YYYY HH:MM format)") try: local_date = datetime.strptime(date_input, '%m/%d/%Y %H:%M') except ValueError: print("{} doesn't seem to be a valid date & time.".format(date_input)) else: # Enter Your Local Timezone Below local_date = pytz.timezone('US/Eastern').localize(local_date) utc_date = local_date.astimezone(pytz.utc) output = [] for timezone in us_time: output.append(utc_date.astimezone(timezone)) for date_time in output: print(date_time.strftime(fmt)) break
7657ac3c9edfab3e5d8122c940304d068f348630
leandro-jr/Tetris
/task/tetris/game.py
19,719
3.671875
4
import numpy as np from collections import deque class Piece: """Piece object and related functionality""" def __init__(self, dimensions, stored_pieces): """The initializer for the class. Arguments: shape -- string with piece shape I, S, Z, L, J, O, T. dimensions -- list with int M and N grid dimensions """ # m width n height self.m = dimensions[0] self.n = dimensions[1] # grid is a matrix array. M "row" arrays with N "columns" filled with '-' self.grid = np.array([['-'] * self.m] * self.n) # rotation to be used on initial_position arrays on subclasses self.rotation = 0 self.stored_pieces = stored_pieces def print_grid(self): """Print the MxN grid. """ # for each row, prints each column. self.m - 1 is used because the array index starts at 0 for row in self.grid: for index, column in enumerate(row): # if it is the end of the row, don't add blank space after the {column} and go to next line if index == self.m - 1: print(f"{column}") # else remains in line and add blank space to {column} content else: print(f"{column} ", end="") # this print is necessary to pass the question test print() def write_position(self, np_positions): """Recreate the original grid with '-' and replace '-' for '0' where the piece is placed at the moment. Arguments: np_positions - - numpy array with the current position of the piece on the grid.E.g[4 14 24 34] """ self.grid = np.array([['-'] * self.m] * self.n) # write grid with saved pieces if self.stored_pieces: for position in self.stored_pieces: row = position // 10 column = position % 10 try: self.grid[row][column] = 0 except IndexError: print(self.stored_pieces) print(f"row: {row}, column: {column}") # write grid with np_positions if len(np_positions) != 0: for position in np_positions: row = (position // 10) % self.n column = position % 10 self.grid[row][column] = 0 self.print_grid() def move(self, np_positions, move=0): """Add +1/-1/0 to positions numpy array, making it moves 'right'/'left'/'down'. Limit movement within grid walls. Then, add +10 making it moves 'down'. Arguments: np_positions -- numpy array with the current position of the piece on the grid. E.g [4 14 24 34] move -- int with +1 to right, -1 to left and 0 to down Return the np_positions updated """ # update np_positions with the command move. Saves it as new_np_positions new_np_positions = (np_positions + move) # if go_horizontal is True, move is allowed go_horizontal = True # if go_vertical is True, piece movement down is allowed go_vertical = True # if any position in new_np_positions changes row after the move was added to np_positions, flag go_horizontal # is set to False and new_np_positions is ignored for index in range(len(np_positions)): if new_np_positions[index] // 10 != np_positions[index] // 10: go_horizontal = False # if any position in new_np_positions matches a position in piece.stored_pieces, flag go_horizontal and # go_vertical are set to False and new_np_positions is ignored if self.stored_pieces: for position in self.stored_pieces: if position in new_np_positions + 10: go_horizontal = False go_vertical = False if go_horizontal and go_vertical: np_positions = (new_np_positions + 10) elif not go_horizontal and go_vertical: np_positions = (np_positions + 10) # update the grid after the movement self.write_position(np_positions) return np_positions, go_vertical def rotate(self, positions, movements): """Movements has all piece movements made in the game. Using it as a queue, remake all the piece movements (+1/-1/0) or 'right'/'left'/'down' to the rotated piece. Then, add +10 making it moves 'down' for each movement. Arguments: positions -- list with initial position of the rotated piece on the grid. E.g [4, 14, 24, 34] movements -- deque with ints: +1 to right, -1 to left and 0 to down Return the np_positions updated """ np_positions = np.array(positions) for movement in movements: np_positions = (np_positions + movement) np_positions = (np_positions + 10) # update the grid after the movement self.write_position(np_positions) return np_positions def floor(self, np_positions): """Verify if piece achieved the floor of the grid. Arguments: np_positions -- numpy array with the current position of the piece on the grid. E.g [4 14 24 34] Return boolean True if piece touched the floor. False otherwise """ hit_floor = False if (np_positions // 10 == self.n - 1).any(): hit_floor = True self.stored_pieces = self.stored_pieces + deque(np_positions.tolist()) return hit_floor def erase_row(self): """Verify if row must be erased and update grid accordingly. Return boolean True if row was erased. False otherwise. """ test_width_sorted = deque(sorted(self.stored_pieces.copy())) count_col = 0 last_row = self.n - 1 row_erased = False while len(test_width_sorted) > 0: i = test_width_sorted.pop() if i // 10 == last_row: count_col += 1 if count_col == self.m: np_test_width_sorted = np.array(test_width_sorted) + 10 test_width_sorted = deque(np_test_width_sorted.tolist()) count_col = 0 row_erased = True else: break if row_erased: self.stored_pieces = deque(np_test_width_sorted.tolist()) return row_erased def game_over(self, np_positions): """Verify if a column of the grid was completely filled. If yes, it's game over. Arguments: np_positions -- numpy array with the current position of the piece on the grid. E.g [4 14 24 34] Return boolean True if it's game over. False otherwise. """ test_height = self.stored_pieces.copy() for position in np_positions: test_height.append(position) test_height_sorted = deque(sorted(test_height)) while True: i = test_height_sorted.popleft() increment = 10 count_row = 1 if i // 10 == 0: while i + increment in test_height_sorted and count_row < self.n: increment += 10 count_row += 1 if count_row == self.n: return True else: break return False # There is no need to create one class for each piece shape at this moment of the project. I used that to pratice inheritance class I(Piece): """I object and related functionality. It is a child class from Piece class""" def __init__(self, dimensions, stored_pieces): """The initializer for the class. Inherits the methods of Piece class and creates others. Arguments: dimensions -- list with int M and N grid dimensions """ super().__init__(dimensions, stored_pieces) self.shape = "I" # possible initial positions of the piece for each rotation on the grid self.initial_positions = [[4, 14, 24, 34], [3, 4, 5, 6]] # chooses an initial position based on the rotation. Index 0 is been used. self.positions = self.initial_positions[self.rotation] self.np_positions = np.array(self.positions) # update the grid after the piece is created self.write_position(self.np_positions) def __repr__(self): """Print of the piece""" return f"Shape: {self.shape}; Initial positions: {self.initial_positions}; Rotation: {self.rotation}; np_positions: {self.np_positions}" class S(Piece): """S object and related functionality. It is a child class from Piece class""" def __init__(self, dimensions, stored_pieces): """The initializer for the class. Inherits the methods of Piece class and creates others. Arguments: dimensions -- list with int M and N grid dimensions """ super().__init__(dimensions, stored_pieces) self.shape = "S" # possible initial positions of the piece for each rotation on the grid self.initial_positions = [[5, 4, 14, 13], [4, 14, 15, 25]] # chooses an initial position based on the rotation. Index 0 is been used. self.positions = self.initial_positions[self.rotation] self.np_positions = np.array(self.positions) # update the grid after the piece is created self.write_position(self.np_positions) def __repr__(self): """Print of the piece""" return f"Shape: {self.shape}; Initial positions: {self.initial_positions}; Rotation: {self.rotation}; np_positions: {self.np_positions}" class Z(Piece): """Z object and related functionality. It is a child class from Piece class""" def __init__(self, dimensions, stored_pieces): """The initializer for the class. Inherits the methods of Piece class and creates others. Arguments: dimensions -- list with int M and N grid dimensions """ super().__init__(dimensions, stored_pieces) self.shape = "Z" # possible initial positions of the piece for each rotation on the grid self.initial_positions = [[4, 5, 15, 16], [5, 15, 14, 24]] # chooses an initial position based on the rotation. Index 0 is been used. self.positions = self.initial_positions[self.rotation] self.np_positions = np.array(self.positions) # update the grid after the piece is created self.write_position(self.np_positions) def __repr__(self): """Print of the piece""" return f"Shape: {self.shape}; Initial positions: {self.initial_positions}; Rotation: {self.rotation}; np_positions: {self.np_positions}" class L(Piece): """L object and related functionality. It is a child class from Piece class""" def __init__(self, dimensions, stored_pieces): """The initializer for the class. Inherits the methods of Piece class and creates others. Arguments: dimensions -- list with int M and N grid dimensions """ super().__init__(dimensions, stored_pieces) self.shape = "L" # possible initial positions of the piece for each rotation on the grid self.initial_positions = [[4, 14, 24, 25], [5, 15, 14, 13], [4, 5, 15, 25], [6, 5, 4, 14]] # chooses an initial position based on the rotation. Index 0 is been used. self.positions = self.initial_positions[self.rotation] self.np_positions = np.array(self.positions) # update the grid after the piece is created self.write_position(self.np_positions) def __repr__(self): """Print of the piece""" return f"Shape: {self.shape}; Initial positions: {self.initial_positions}; Rotation: {self.rotation}; np_positions: {self.np_positions}" class J(Piece): """J object and related functionality. It is a child class from Piece class""" def __init__(self, dimensions, stored_pieces): """The initializer for the class. Inherits the methods of Piece class and creates others. Arguments: dimensions -- list with int M and N grid dimensions """ super().__init__(dimensions, stored_pieces) self.shape = "J" # possible initial positions of the piece for each rotation on the grid self.initial_positions = [[5, 15, 25, 24], [15, 5, 4, 3], [5, 4, 14, 24], [4, 14, 15, 16]] # chooses an initial position based on the rotation. Index 0 is been used. self.positions = self.initial_positions[self.rotation] self.np_positions = np.array(self.positions) # update the grid after the piece is created self.write_position(self.np_positions) def __repr__(self): """Print of the piece""" return f"Shape: {self.shape}; Initial positions: {self.initial_positions}; Rotation: {self.rotation}; np_positions: {self.np_positions}" class O(Piece): """O object and related functionality. It is a child class from Piece class""" def __init__(self, dimensions, stored_pieces): """The initializer for the class. Inherits the methods of Piece class and creates others. Arguments: dimensions -- list with int M and N grid dimensions """ super().__init__(dimensions, stored_pieces) self.shape = "O" # possible initial positions of the piece for each rotation on the grid self.initial_positions = [[4, 14, 15, 5]] # chooses an initial position based on the rotation. Index 0 is been used. self.positions = self.initial_positions[self.rotation] self.np_positions = np.array(self.positions) # update the grid after the piece is created self.write_position(self.np_positions) def __repr__(self): """Print of the piece""" return f"Shape: {self.shape}; Initial positions: {self.initial_positions}; Rotation: {self.rotation}; np_positions: {self.np_positions}" class T(Piece): """T object and related functionality. It is a child class from Piece class""" def __init__(self, dimensions, stored_pieces): """The initializer for the class. Inherits the methods of Piece class and creates others. Arguments: dimensions -- list with int M and N grid dimensions """ super().__init__(dimensions, stored_pieces) self.shape = "T" # possible initial positions of the piece for each rotation on the grid self.initial_positions = [[4, 14, 24, 15], [4, 13, 14, 15], [5, 15, 25, 14], [4, 5, 6, 15]] # chooses an initial position based on the rotation. Index 0 is been used. self.positions = self.initial_positions[self.rotation] self.np_positions = np.array(self.positions) # update the grid after the piece is created self.write_position(self.np_positions) def __repr__(self): """Print of the piece""" return f"Shape: {self.shape}; Initial positions: {self.initial_positions}; Rotation: {self.rotation}; np_positions: {self.np_positions}" def main(): """Input grid dimensions, piece shape and piece movements. First input is the Tetris grid dimension MxN. Where M is the number of columns and N the number of rows. After the input is provided, a blank grid with MxN dimension is displayed. After that, user input 'piece' followed by the Tetris piece shape. Shapes can be I, S, Z, L, J, O, T. Next inputs are the movements of the piece. Options are: right, left, down, rotate(to rotate the piece). After each movement input the piece moves down on the grid as well. The grid is displayed after each movement input. If an entire row is occupied by pieces, the row disappears. If an entire column is occupied by pieces, it's game over. Input 'break' to stop and 'exit' to finish the game. Example: 10 10 piece T right down break """ # MxN grid dimensions dimensions = [int(x) for x in input().split()] # stored_pieces will save pieces that hit the floor or that touched other pieces stored_pieces = deque() # display empty grid empty_grid = Piece(dimensions, stored_pieces) empty_grid.print_grid() # calls the class method based on the movement while True: command = input() if command == "exit": break elif command == "break": piece.write_position([]) elif command == "piece": shape = input() # create the movements deque where the player movements will be stored for a given piece movements = deque() # based on shape creates the class instance. The variable with the instance is "piece" if shape == 'I': piece = I(dimensions, stored_pieces) elif shape == 'S': piece = S(dimensions, stored_pieces) elif shape == 'Z': piece = Z(dimensions, stored_pieces) elif shape == 'L': piece = L(dimensions, stored_pieces) elif shape == 'J': piece = J(dimensions, stored_pieces) elif shape == 'O': piece = O(dimensions, stored_pieces) elif shape == 'T': piece = T(dimensions, stored_pieces) # verify if game over condition was reached elif piece.game_over(piece.np_positions): piece.write_position(piece.np_positions) print("Game Over!") break # verify if piece achieved the floor. If yes, saves the piece position, ignore command, print the grid and # verifies if row must be erased elif piece.floor(piece.np_positions): stored_pieces = piece.stored_pieces.copy() piece.write_position(piece.np_positions) if piece.erase_row(): stored_pieces = piece.stored_pieces.copy() # for "right", move method is called. +1 is sent to move and added to movements # go_vertical is a flag that if false means that a piece touched another and need to be saved elif command == "right": piece.np_positions, go_vertical = piece.move(piece.np_positions, 1) movements.append(1) if not go_vertical: piece.stored_pieces = piece.stored_pieces + deque(piece.np_positions.tolist()) stored_pieces = piece.stored_pieces.copy() # for "left", move method is called. -1 is sent to move and added to movements elif command == "left": piece.np_positions, go_vertical = piece.move(piece.np_positions, -1) movements.append(-1) if not go_vertical: piece.stored_pieces = piece.stored_pieces + deque(piece.np_positions.tolist()) stored_pieces = piece.stored_pieces.copy() # for "down", move method is called. 0 is added to movements elif command == "down": piece.np_positions, go_vertical = piece.move(piece.np_positions) movements.append(0) if not go_vertical: piece.stored_pieces = piece.stored_pieces + deque(piece.np_positions.tolist()) stored_pieces = piece.stored_pieces.copy() # for "rotate", rotate method is called. 0 is added to movements elif command == "rotate": # shifts the initial_positions array when user wants to rotate the piece piece.rotation = (piece.rotation + 1) % len(piece.initial_positions) movements.append(0) piece.np_positions = piece.rotate(piece.initial_positions[piece.rotation], movements) if __name__ == '__main__': main()
8f39700657d4539a77829962a3d609240de2a247
M-de-Mateus/Python
/ex102 - Função para Fatorial.py
489
3.796875
4
def fatorial(n, show = False): ''' :param n: Número qual será calculado o fatorial :param show: Mostra a conta feita para calcular o fatorial :return: retorna o valor do fatorial ''' f = 1 for c in range(n, 0, -1): if show: print(c, end='') if c > 1: print(' x ', end='') else: print(' = ', end='') f *= c return f print(fatorial(5, show=False))
4b207de719748221408cbb507030233f1b3e213c
Peng-Zhanjie/The-CP1404-Project
/Week8/taxi.py
986
3.75
4
from car import Car class Taxi(Car): """Specialised version of a Car that includes fare costs.""" price_per_km = 1.23 def __init__(self, name="",fuel=100, ): self.fuel = fuel self.name = name super().__init__( name,fuel) self.price = self.price_per_km self.current_fare_distance = 0 def get_fare(self): fare = round(self.current_fare_distance * self.price, 1) return fare def drive(self, distance): """Drive like parent Car but calculate fare distance as well.""" distance_driven = super().drive(int(distance)) self.current_fare_distance += distance_driven return distance_driven def start_fare(self): self.current_fare_distance = 0 def __str__(self): return super().__str__() + ",{}km on current fare, ${:.2f}/km".format(self.current_fare_distance, self.price_per_km)
b14deeadae29d942ccc6c6f330b6f4375c23bd3a
yuandaxing/leetcode
/python/LongestCommonPrefix.py
609
3.5625
4
class Solution: # @return a string def longestCommonPrefix(self, strs): if len(strs) == 0 : return '' commonPrefix = strs[0] for i in range(1, len(strs)) : commonIdx = 0 while commonIdx < min(len(commonPrefix), \ len(strs[i])) : if commonPrefix[commonIdx] != strs[i][commonIdx]: break commonIdx += 1 commonPrefix = commonPrefix[0:commonIdx] return commonPrefix sol = Solution() tests = ['abcd', 'abc'] print sol.longestCommonPrefix(tests)
6ec3cf56307e5bb71611816bbc39698934190812
nishamnisha/python-programming
/pro86.py
194
3.71875
4
def isogram(): s=input() l1=list(s) r1=[] for i in l1: if not i in r1: r1.append(i) if len(l1)==len(r1): print('yes') else : print('no') try: isogram() except: print('invalid')
55d330b9e410c283ee1fab8116d69fa0c08aeb4b
alexmsmith/Cipher-Attacks
/Parta/parta.py
3,318
3.921875
4
#cipher.py e/d key.txt plaintext.txt/ ciphertext.txt # HOW TO USE # 1) Enter: 'parta.py ciphertext.txt' # 2) Wait Until The Brute-Force Attack Is Complete # 3) This Will Print The Plaintext And Key Along With The Time It Took To Finish The Attack import time #Used to calculate how long it would take for the program to finish import re #RegularExpression functionality for plaintext detection keyList = [] #This array will store all possible keys that are found within the keyspace startLoop = 97 #Decimal value for 'a' endLoop = 123 #Decimal value for 'z' start_time = time.time() #Execute start time def KSA(key): keylength = len(key) S = list(range(256)) j = 0 for i in range(256): j = (j + S[i] + key[i % keylength]) % 256 S[i], S[j] = S[j], S[i] return S def PRGA(S): i = 0 j = 0 while True: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] K = S[(S[i] + S[j]) % 256] yield K #Each key in the keyList array will be passed into the streamcipher function def streamcipher(key): S = KSA(key) return PRGA(S) if __name__ == '__main__': import sys cipherFile = open(sys.argv[1], 'r') #Open the cipherFile that is read from the console ciphertext = cipherFile.read() #Read this file and store in ciphertext cipherFile.close() #This file is no longer needed, and it can be close #Each loop represents each character within the keysize, total of 6 #To increase/decrease the size of the key, we can uncomment/comment related code for c1 in range(startLoop, endLoop): for c2 in range(startLoop, endLoop): for c3 in range(startLoop, endLoop): for c4 in range(startLoop, endLoop): #for c5 in range(startLoop, endLoop): #for c6 in range(startLoop, endLoop): initialList = [c1, c2, c3, c4] #c5, #c6] #Convert each decimal to a character char1 = chr(c1) char2 = chr(c2) char3 = chr(c3) char4 = chr(c4) #char5 = chr(c5) #char6 = chr(c6) #Create new array and append the characters charList = [char1, char2, char3, char4] #char5, #char6] #The charList array is then converted to a string (key) key = ''.join(str(e) for e in charList) #strList #We then append the key to the keyList array keyList.append(key) #c6 = c6 + 1 #c5 = c5 + 1 c4 = c4 + 1 c3 = c3 + 1 c2 = c2 + 1 #The convert function will separate each key into individual characters def convert(s): return [ord(c) for c in s] for key in keyList: key = convert(key) keystream = streamcipher(key) #The key processed through the keystream n = 0 sString = "" while n < len(ciphertext): x = int(ciphertext[n:n+2], 16) character = chr(x ^ next(keystream)) #XOR the first bits of both ciphertext and keystream string = ''.join(character) sString+=str(string) n += 2 if re.match("^[A-Za-z0-9 -]*$", sString): #If anything but unspecified symbols are found.. #Print the key and also the plaintext message KEY="" for k in key: keyC = chr(k) KEY+=str(keyC) print("Key: "+KEY) print("String: "+sString) break #break loop print("---%s seconds ---" % (time.time() - start_time)) #Print total execution time to console
c43bb86edb8dd2c2f068fc1a9406ad151e85a2e5
SnehankaDhamale/Python-Assg-WFH-
/Assignment6/ex25.py
299
4.15625
4
#Write a Python program to print all Prime numbers between 1 to n. n=int(input("Enter the no:")) print("Prime nos:") for i in range(1,n+1): count=0 for j in range(2,(i//2+1)): if i%j ==0: count=count+1 break if count==0 and i!=1: print(i,end=' ')
a8afae80b05a815ae516d64581a001980c1953a7
KoeusIss/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/rectangle.py
4,246
3.65625
4
#!/usr/bin/python3 """Rectangle module""" from models.base import Base class Rectangle(Base): """Rectangle class Attributes: width (int): rectangle's width height (int): rectangle's height x (int): rectangle's abscissa y (int): rectangle's orders id (int): the rectangle id """ def __init__(self, width, height, x=0, y=0, id=None): """Initializer""" Base.__init__(self, id) self.width = width self.height = height self.x = x self.y = y @property def width(self): """Width getter""" return self.__width @width.setter def width(self, value): """width setter Args: value (int): given setting value Raises: TypeError: if width not an integer ValueError: if width a null or negative integer """ if type(value) is not int: raise TypeError("width must be an integer") if value <= 0: raise ValueError("width must be > 0") self.__width = value @property def height(self): """height getter""" return self.__height @height.setter def height(self, value): """height setter Args: value (int): given setting value Raises: TypeError: if height not an integer ValueError: if height a null or negative integer """ if type(value) is not int: raise TypeError("height must be an integer") if value <= 0: raise ValueError("height must be > 0") self.__height = value @property def x(self): """x getter""" return self.__x @x.setter def x(self, value): """x setter Args: value (int): given stting value Raises: TypeError: if x not an integer ValueError: if x non positive integer """ if type(value) is not int: raise TypeError("x must be an integer") if value < 0: raise ValueError("x must be >= 0") self.__x = value @property def y(self): """y getter""" return self.__y @y.setter def y(self, value): """y setter Args: value (int): given setting value Raises: TypeError: if y not integer ValueError: if y non positive integer """ if type(value) is not int: raise TypeError("y must be an integer") if value < 0: raise ValueError("y must be >= 0") self.__y = value def area(self): """return rectangle area""" return self.width * self.height def display(self): """displays a rectangle with #""" print("{}".format("\n"*self.y), end="") for i in range(self.height): print("{}{}".format(" "*self.x, "#"*self.width)) def __str__(self): """Returns humain readable rectangle form""" return "[Rectangle] ({}) {}/{} - {}/{}".format( self.id, self.x, self.y, self.width, self.height ) def update(self, *args, **kwargs): """updates rectangle attributes Args: args (tuple): tuple of a designated attributes """ for idx, item in enumerate(args): if idx == 0: self.id = item if idx == 1: self.width = item if idx == 2: self.height = item if idx == 3: self.x = item if idx == 4: self.y = item for k, v in kwargs.items(): if k == "id": self.id = v if k == "width": self.width = v if k == "height": self.height = v if k == "x": self.x = v if k == "y": self.y = v def to_dictionary(self): """Returns the dictionary representation of the rectangle""" return {"id": self.id, "width": self.width, "height": self.height, "x": self.x, "y": self.y}
cc4242612ebb0b83b98050ae69a41c5b7388b4e1
yiranzhimo/Python-Practice
/Day-10_32.py
139
3.65625
4
def test(): dic = dict() for i in range(1,21): dic[i]=i*i return dic.keys() print(test()) #此时不需要定义参数
41b8e3cfb40460adcf3deeaece819e051237c1e4
aguilarjose11/ML-Playground
/ml-by-scratch/linear_algebra.py
3,899
4.0625
4
''' Linear Algebra used for machine learning. ''' import math from typing import List, Tuple, Callable import sympy #---------------- # Vector Algebra | #---------------- # Vectors store a single row of a matrix. Vector = List[float] # Vectorial Addition. def add(v: Vector, w: Vector) -> Vector: ''' with: v = (v_1, v_2, ..., v_x) w = (w_1, w_2, ..., w_x) v + w = (v_1 + w_1, v_2 + w_2, ..., v_x + w_x) as: add(v, w) ''' assert len(v) == len(w), f"Dimension of vectors do not match: dim(v)={len(v)} != dim(w)={len(w)}." return [v_x + w_x for v_x, w_x in zip(v, w)] # Vectorial Subtraction. def subtract(v: Vector, w: Vector) -> Vector: ''' with: v = (v_1, v_2, ..., v_x) w = (w_1, w_2, ..., w_x) v - w = (v_1 - w_1, v_2 - w_2, ..., v_x - w_x) as: subtract(v, w) ''' assert len(v) == len(w), f"Dimension of vectors do not match: |v|={len(v)} != |w|={len(w)}." return [v_x - w_x for v_x, w_x in zip(v, w)] # Multiple vector addition. def vector_sum(vectors: List[Vector]) -> Vector: ''' for every vector v_x having same dimensions: v_1 + v_2 + ... + v_x = (v_1x + v_2x + ... v_xx, v_1y + v_2y + ... v_xy, v_1z + v_2z + ... v_xz) ''' assert vectors, "No vectors provided!" n_vector_dim = len(vectors[0]) assert all(len(v) == n_vector_dim for v in vectors), "dimensions do not match!" return [sum(vector[x] for vector in vectors) for x in range(n_vector_dim)] # Scalar Product. def scalar_multiply(c: float, v: Vector) -> Vector: return [c * v_n for v_n in v] # Component-Wise vectorial mean. def vector_mean(vectors: List[Vector]) -> Vector: assert vectors, "No vectors provided!" n_vector_dim = len(vectors[0]) assert all(len(v) == n_vector_dim for v in vectors), "dimensions do not match!" return scalar_multiply(1/len(vectors), vector_sum(vectors)) # dot product. def dot(v: Vector, w: Vector) -> float: assert len(v) == len(w), "vector sizes are different!" return sum(v_n * w_n for v_n, w_n in zip(v, w)) # Summation of squares. def sum_of_squares(v: Vector) -> float: return dot(v, v) # Vectorial Magnitude. def magnitude(v: Vector) -> float: return math.sqrt(sum_of_squares(v)) # Vectorial distance. def distance(v: Vector, w: Vector) -> float: return magnitude(subtract(v, w)) # unit vector def unit_vector(v: Vector) -> Vector: return [v[v_i]/magnitude(v) for v_i in range(len(v))] # ---------------- # Matrix Algebra | # ---------------- # Note: Matrix = List[Vector] Matrix = List[List[float]] # Matrix shape def shape(A: Matrix) -> Tuple[int, int]: return len(A), len(A[0]) # Matrix row extraction def get_row(A: Matrix, i: int) -> Vector: return A[i] # Matrix column extraction def get_column(A: Matrix, j: int) -> Vector: return [column[j] for column in A] # Matrix generation with specified dimensions def make_matrix(num_rows: int, num_cols: int, entry_fn: Callable[[int, int], float]) -> Matrix: return [[entry_fn(row, col) for col in range(num_cols)] for row in range(num_rows)] # Identity Matrix generator. def identity_matrix(n: int) -> Matrix: def identity_matrix_base_func(row, col): if row == col: return 1 else: return 0 return make_matrix(n, n, identity_matrix_base_func) # Matrix scalar product def matrix_scalar_multiply(c: float, A: Matrix) -> Matrix: return [scalar_multiply(c, row) for row in A] def transpose(A: Matrix) -> Matrix: return [[row[col] for row in A] for col in range(len(A[0]))] # Matrix cross-product def matrix_dot(A: Matrix, B: Matrix) -> Matrix: assert shape(A)[1] == shape(B)[0], "Inner dimensions of matrices do not match!" return [[dot(row, column) for column in transpose(B)] for row in A]
1836defd90ef907237efaf483d10daee20f96d7a
rhjain100/Data-Structures_And_Algorithms
/Assignment-1/Method3.py
905
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 27 20:41:25 2019 @author: rishabhjain """ def PowerofG(n): G=[[0,1],[1,1]] if n==1: return G else: if n%2==0: H=PowerofG(n/2) return matmult(H,H) else: H=PowerofG((n-1)/2) return matmult(matmult(H,H),G) def matmult(X,Y): result = [[0,0], [0,0]] for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] return result def f3(n): temp = PowerofG(n) return (temp[1][0]) nums=[] fil1 = open("input3.txt","r") fil2 = open("output3.txt","w") for i in fil1: x="" for j in range(len(i)): if i[j]=="\n": break x+=i[j] a=str(f3(int(x))) a=a+"\n" fil2.write(a) fil1.close() fil2.close()
ea6087b49b2f372d8589ad45c47b12f08ba35729
Aasthaengg/IBMdataset
/Python_codes/p03997/s940143591.py
109
3.609375
4
# -*- coding: utf-8 -*- a = int(input()) b = int(input()) h = int(input()) S = 0 S = (a+b)*h/2 print(int(S))
d615db1e224493b0c142dcf80978866ac2cfe4ff
Emrys-Hong/SUTD-deep-learning-homework
/computer-vision/Lab2/week6/libs/layers.py
36,066
3.578125
4
from builtins import range import numpy as np ####x # def affine_forward(x, w, b): # """ # Computes the forward pass for an affine (fully-connected) layer. # The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N # examples, where each example x[i] has shape (d_1, ..., d_k). We will # reshape each input into a vector of dimension D = d_1 * ... * d_k, and # then transform it to an output vector of dimension M. # Inputs: # - x: A numpy array containing input data, of shape (N, d_1, ..., d_k) # - w: A numpy array of weights, of shape (D, M) # - b: A numpy array of biases, of shape (M,) # Returns a tuple of: # - out: output, of shape (N, M) # - cache: (x, w, b) # """ # out = None # ########################################################################### # # TODO: Implement the affine forward pass. Store the result in out. You # # # will need to reshape the input into rows. # # ########################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # N = x.shape[0] # D, M = w.shape # out = x.reshape(N, D) @ w + b # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ########################################################################### # # END OF YOUR CODE # # ########################################################################### # cache = (x, w, b) # return out, cache # ####x # def affine_backward(dout, cache): # """ # Computes the backward pass for an affine layer. # Inputs: # - dout: Upstream derivative, of shape (N, M) # - cache: Tuple of: # - x: Input data, of shape (N, d_1, ... d_k) # - w: Weights, of shape (D, M) # - b: Biases, of shape (M,) # Returns a tuple of: # - dx: Gradient with respect to x, of shape (N, d1, ..., d_k) # - dw: Gradient with respect to w, of shape (D, M) # - db: Gradient with respect to b, of shape (M,) # """ # x, w, b = cache # dx, dw, db = None, None, None # ########################################################################### # # TODO: Implement the affine backward pass. # # ########################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # D,M = w.shape # N = x.shape[0] # db = np.sum(dout,axis = 0) # X_ravel = x.reshape((N,D)) # dw = X_ravel.T.dot(dout) # dX_ravel = dout.dot(w.T) # dx = dX_ravel.reshape(x.shape) # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ########################################################################### # # END OF YOUR CODE # # ########################################################################### # return dx, dw, db # ####x # def relu_forward(x): # """ # Computes the forward pass for a layer of rectified linear units (ReLUs). # Input: # - x: Inputs, of any shape # Returns a tuple of: # - out: Output, of the same shape as x # - cache: x # """ # out = None # ########################################################################### # # TODO: Implement the ReLU forward pass. # # ########################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # out = x # out[out<0] = 0 # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ########################################################################### # # END OF YOUR CODE # # ########################################################################### # cache = x # return out, cache # ####x # def relu_backward(dout, cache): # """ # Computes the backward pass for a layer of rectified linear units (ReLUs). # Input: # - dout: Upstream derivatives, of any shape # - cache: Input x, of same shape as dout # Returns: # - dx: Gradient with respect to x # """ # dx, x = None, cache # ########################################################################### # # TODO: Implement the ReLU backward pass. # # ########################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # dx = np.ones(x.shape) # dx = dx*dout # dx[x<=0] = 0 # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ########################################################################### # # END OF YOUR CODE # # ########################################################################### # return dx # ###x # def dropout_forward(x, dropout_param): # """ # Performs the forward pass for (inverted) dropout. # Inputs: # - x: Input data, of any shape # - dropout_param: A dictionary with the following keys: # - p: Dropout parameter. We keep each neuron output with probability p. # - mode: 'test' or 'train'. If the mode is train, then perform dropout; # if the mode is test, then just return the input. # - seed: Seed for the random number generator. Passing seed makes this # function deterministic, which is needed for gradient checking but not # in real networks. # Outputs: # - out: Array of the same shape as x. # - cache: tuple (dropout_param, mask). In training mode, mask is the dropout # mask that was used to multiply the input; in test mode, mask is None. # NOTE: Please implement **inverted** dropout, not the vanilla version of dropout. # See http://cs231n.github.io/neural-networks-2/#reg for more details. # NOTE 2: Keep in mind that p is the probability of **keep** a neuron # output; this might be contrary to some sources, where it is referred to # as the probability of dropping a neuron output. # """ # p, mode = dropout_param['p'], dropout_param['mode'] # if 'seed' in dropout_param: # np.random.seed(dropout_param['seed']) # mask = None # out = None # if mode == 'train': # ####################################################################### # # TODO: Implement training phase forward pass for inverted dropout. # # # Store the dropout mask in the mask variable. # # ####################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # p = dropout_param['p'] # mask = (np.random.rand(*x.shape) < p) / p # out = x*mask # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ####################################################################### # # END OF YOUR CODE # # ####################################################################### # elif mode == 'test': # ####################################################################### # # TODO: Implement the test phase forward pass for inverted dropout. # # ####################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # out = x # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ####################################################################### # # END OF YOUR CODE # # ####################################################################### # cache = (dropout_param, mask) # out = out.astype(x.dtype, copy=False) # return out, cache # ###x # def dropout_backward(dout, cache): # """ # Perform the backward pass for (inverted) dropout. # Inputs: # - dout: Upstream derivatives, of any shape # - cache: (dropout_param, mask) from dropout_forward. # """ # dropout_param, mask = cache # mode = dropout_param['mode'] # dx = None # if mode == 'train': # ####################################################################### # # TODO: Implement training phase backward pass for inverted dropout # # ####################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # dx = dout * mask # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ####################################################################### # # END OF YOUR CODE # # ####################################################################### # elif mode == 'test': # dx = dout # return dx # ###x # def conv_forward_naive(x, w, b, conv_param): # """ # A naive implementation of the forward pass for a convolutional layer. # The input consists of N data points, each with C channels, height H and # width W. We convolve each input with F different filters, where each filter # spans all C channels and has height HH and width WW. # Input: # - x: Input data of shape (N, C, H, W) # - w: Filter weights of shape (F, C, HH, WW) # - b: Biases, of shape (F,) # - conv_param: A dictionary with the following keys: # - 'stride': The number of pixels between adjacent receptive fields in the # horizontal and vertical directions. # - 'pad': The number of pixels that will be used to zero-pad the input. # During padding, 'pad' zeros should be placed symmetrically (i.e equally on both sides) # along the height and width axes of the input. Be careful not to modfiy the original # input x directly. # Returns a tuple of: # - out: Output data, of shape (N, F, H', W') where H' and W' are given by # H' = 1 + (H + 2 * pad - HH) / stride # W' = 1 + (W + 2 * pad - WW) / stride # - cache: (x, w, b, conv_param) # """ # out = None # ########################################################################### # # TODO: Implement the convolutional forward pass. # # # Hint: you can use the function np.pad for padding. # # ########################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # st, p = conv_param['stride'], conv_param['pad'] # N, C, H, W = x.shape # F, C, HH, WW = w.shape # H_out = 1 + (H+2*p-HH) // st # W_out = 1 + (W+2*p-WW) // st # X_pad = np.pad(x, [[0,0], [0,0], [p,p], [p,p]], 'constant', constant_values=0) # out = np.zeros((N, F, H_out, W_out)) # for i in range(N): # for h in range(H_out): # for wi in range(W_out): # for f in range(F): # x_small = X_pad[i, :, h*st:h*st+HH, wi*st:wi*st+WW] # w_small = w[f, :,:,:] # out[i,f,h,wi] = (x_small * w_small).sum() + b[f] # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ########################################################################### # # END OF YOUR CODE # # ########################################################################### # cache = (x, w, b, conv_param) # return out, cache # ###x # def conv_backward_naive(dout, cache): # """ # A naive implementation of the backward pass for a convolutional layer. # Inputs: # - dout: Upstream derivatives. # - cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive # Returns a tuple of: # - dx: Gradient with respect to x # - dw: Gradient with respect to w # - db: Gradient with respect to b # """ # dx, dw, db = None, None, None # ########################################################################### # # TODO: Implement the convolutional backward pass. # # ########################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # x, w, b, conv_param = cache # N, C, H, W = x.shape # F, C, HH, WW = w.shape # st = conv_param['stride'] # p = conv_param['pad'] # x_pad = np.pad(x, ((0, 0), (0, 0), (p, p), (p,p)), 'constant', constant_values=0) # H_n = 1 + (H + 2 * p - HH) // st # W_n = 1 + (W + 2 * p - WW) // st # dx_pad = np.zeros_like(x_pad) # dx = np.zeros_like(x) # dw = np.zeros_like(w) # db = np.zeros_like(b) # for n in range(N): # for f in range(F): # db[f] += dout[n,f].sum() # for hi in range(H_n): # for wi in range(W_n): # dw[f] += x_pad[n, :, hi*st:hi*st+HH, wi*st:wi*st+WW] * dout[n,f,hi,wi] # dx_pad[n, :, hi*st:hi*st+HH, wi*st:wi*st+WW] += w[f] * dout[n,f,hi,wi] # dx = dx_pad[...,p:p+H, p:p+W] # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ########################################################################### # # END OF YOUR CODE # # ########################################################################### # return dx, dw, db # ###x # def max_pool_forward_naive(x, pool_param): # """ # A naive implementation of the forward pass for a max-pooling layer. # Inputs: # - x: Input data, of shape (N, C, H, W) # - pool_param: dictionary with the following keys: # - 'pool_height': The height of each pooling region # - 'pool_width': The width of each pooling region # - 'stride': The distance between adjacent pooling regions # No padding is necessary here. Output size is given by # Returns a tuple of: # - out: Output data, of shape (N, C, H', W') where H' and W' are given by # H' = 1 + (H - pool_height) / stride # W' = 1 + (W - pool_width) / stride # - cache: (x, pool_param) # """ # out = None # ########################################################################### # # TODO: Implement the max-pooling forward pass # # ########################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # N, C, H, W = x.shape # ph, pw, st = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride'] # H_n = int(1 + (H - ph) / st) # W_n = int(1 + (W - pw) / st) # out = np.zeros((N,C,H_n,W_n)) # for i in range(N): # for hi in range(H_n): # for wi in range(W_n): # for l in range(C): # out[i,l,hi,wi] = np.max(x[i,l, hi*st:hi*st+ph, wi*st:wi*st+pw]) # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ########################################################################### # # END OF YOUR CODE # # ########################################################################### # cache = (x, pool_param) # return out, cache # ###x # def max_pool_backward_naive(dout, cache): # """ # A naive implementation of the backward pass for a max-pooling layer. # Inputs: # - dout: Upstream derivatives # - cache: A tuple of (x, pool_param) as in the forward pass. # Returns: # - dx: Gradient with respect to x # """ # dx = None # ########################################################################### # # TODO: Implement the max-pooling backward pass # # ########################################################################### # # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # x, pool_param = cache # N, C, H, W = x.shape # ph, pw, st = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride'] # H_n = int(1 + (H - ph) / st) # W_n = int(1 + (W - pw) / st) # dx = np.zeros_like(x) # for i in range(N): # for hi in range(H_n): # for wi in range(W_n): # for l in range(C): # index = np.argmax(x[i,l,st*hi:st*hi+ph,st*wi:st*wi+pw]) # ind1,ind2 = np.unravel_index(index,(ph, pw)) # dx[i,l,hi*st:hi*st+ph, wi*st:wi*st+pw][ind1, ind2] += dout[i,l,hi,wi] # # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # ########################################################################### # # END OF YOUR CODE # # ########################################################################### # return dx # ###x # def softmax_loss(x, y): # """ # Computes the loss and gradient for softmax classification. # Inputs: # - x: Input data, of shape (N, C) where x[i, j] is the score for the jth # class for the ith input. # - y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and # 0 <= y[i] < C # Returns a tuple of: # - loss: Scalar giving the loss # - dx: Gradient of the loss with respect to x # """ # shifted_logits = x - np.max(x, axis=1, keepdims=True) # Z = np.sum(np.exp(shifted_logits), axis=1, keepdims=True) # log_probs = shifted_logits - np.log(Z) # probs = np.exp(log_probs) # N = x.shape[0] # loss = -np.sum(log_probs[np.arange(N), y]) / N # dx = probs.copy() # dx[np.arange(N), y] -= 1 # dx /= N # return loss, dx from builtins import range import numpy as np ####x def affine_forward(x, w, b): """ Computes the forward pass for an affine (fully-connected) layer. The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N examples, where each example x[i] has shape (d_1, ..., d_k). We will reshape each input into a vector of dimension D = d_1 * ... * d_k, and then transform it to an output vector of dimension M. Inputs: - x: A numpy array containing input data, of shape (N, d_1, ..., d_k) - w: A numpy array of weights, of shape (D, M) - b: A numpy array of biases, of shape (M,) Returns a tuple of: - out: output, of shape (N, M) - cache: (x, w, b) """ out = None ########################################################################### # TODO: Implement the affine forward pass. Store the result in out. You # # will need to reshape the input into rows. # ########################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** N = x.shape[0] D = w.shape[0] M = w.shape[1] out = x.reshape(N,D).dot(w) + b pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ########################################################################### # END OF YOUR CODE # ########################################################################### cache = (x, w, b) return out, cache ####x def affine_backward(dout, cache): """ Computes the backward pass for an affine layer. Inputs: - dout: Upstream derivative, of shape (N, M) - cache: Tuple of: - x: Input data, of shape (N, d_1, ... d_k) - w: Weights, of shape (D, M) - b: Biases, of shape (M,) Returns a tuple of: - dx: Gradient with respect to x, of shape (N, d1, ..., d_k) - dw: Gradient with respect to w, of shape (D, M) - db: Gradient with respect to b, of shape (M,) """ x, w, b = cache dx, dw, db = None, None, None ########################################################################### # TODO: Implement the affine backward pass. # ########################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** D,M = w.shape N = x.shape[0] db = np.sum(dout,axis = 0) X_ravel = x.reshape((N,D)) dw = X_ravel.T.dot(dout) dX_ravel = dout.dot(w.T) dx = dX_ravel.reshape(x.shape) pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ########################################################################### # END OF YOUR CODE # ########################################################################### return dx, dw, db ####x def relu_forward(x): """ Computes the forward pass for a layer of rectified linear units (ReLUs). Input: - x: Inputs, of any shape Returns a tuple of: - out: Output, of the same shape as x - cache: x """ out = None ########################################################################### # TODO: Implement the ReLU forward pass. # ########################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** out = x out[out<0] = 0 pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ########################################################################### # END OF YOUR CODE # ########################################################################### cache = x return out, cache ####x def relu_backward(dout, cache): """ Computes the backward pass for a layer of rectified linear units (ReLUs). Input: - dout: Upstream derivatives, of any shape - cache: Input x, of same shape as dout Returns: - dx: Gradient with respect to x """ dx, x = None, cache ########################################################################### # TODO: Implement the ReLU backward pass. # ########################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** dx = np.ones(x.shape) dx[x<=0] = 0 dx = dx*dout pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ########################################################################### # END OF YOUR CODE # ########################################################################### return dx ###x def dropout_forward(x, dropout_param): """ Performs the forward pass for (inverted) dropout. Inputs: - x: Input data, of any shape - dropout_param: A dictionary with the following keys: - p: Dropout parameter. We keep each neuron output with probability p. - mode: 'test' or 'train'. If the mode is train, then perform dropout; if the mode is test, then just return the input. - seed: Seed for the random number generator. Passing seed makes this function deterministic, which is needed for gradient checking but not in real networks. Outputs: - out: Array of the same shape as x. - cache: tuple (dropout_param, mask). In training mode, mask is the dropout mask that was used to multiply the input; in test mode, mask is None. NOTE: Please implement **inverted** dropout, not the vanilla version of dropout. See http://cs231n.github.io/neural-networks-2/#reg for more details. NOTE 2: Keep in mind that p is the probability of **keep** a neuron output; this might be contrary to some sources, where it is referred to as the probability of dropping a neuron output. """ p, mode = dropout_param['p'], dropout_param['mode'] if 'seed' in dropout_param: np.random.seed(dropout_param['seed']) mask = None out = None if mode == 'train': ####################################################################### # TODO: Implement training phase forward pass for inverted dropout. # # Store the dropout mask in the mask variable. # ####################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** p = dropout_param['p'] mask = (np.random.rand(*x.shape) < p) / p out = x*mask pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ####################################################################### # END OF YOUR CODE # ####################################################################### elif mode == 'test': ####################################################################### # TODO: Implement the test phase forward pass for inverted dropout. # ####################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** out = x pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ####################################################################### # END OF YOUR CODE # ####################################################################### cache = (dropout_param, mask) out = out.astype(x.dtype, copy=False) return out, cache ###x def dropout_backward(dout, cache): """ Perform the backward pass for (inverted) dropout. Inputs: - dout: Upstream derivatives, of any shape - cache: (dropout_param, mask) from dropout_forward. """ dropout_param, mask = cache mode = dropout_param['mode'] dx = None if mode == 'train': ####################################################################### # TODO: Implement training phase backward pass for inverted dropout # ####################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** dx = dout*mask pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ####################################################################### # END OF YOUR CODE # ####################################################################### elif mode == 'test': dx = dout return dx ###x def conv_forward_naive(x, w, b, conv_param): """ A naive implementation of the forward pass for a convolutional layer. The input consists of N data points, each with C channels, height H and width W. We convolve each input with F different filters, where each filter spans all C channels and has height HH and width WW. Input: - x: Input data of shape (N, C, H, W) - w: Filter weights of shape (F, C, HH, WW) - b: Biases, of shape (F,) - conv_param: A dictionary with the following keys: - 'stride': The number of pixels between adjacent receptive fields in the horizontal and vertical directions. - 'pad': The number of pixels that will be used to zero-pad the input. During padding, 'pad' zeros should be placed symmetrically (i.e equally on both sides) along the height and width axes of the input. Be careful not to modfiy the original input x directly. Returns a tuple of: - out: Output data, of shape (N, F, H', W') where H' and W' are given by H' = 1 + (H + 2 * pad - HH) / stride W' = 1 + (W + 2 * pad - WW) / stride - cache: (x, w, b, conv_param) """ out = None ########################################################################### # TODO: Implement the convolutional forward pass. # # Hint: you can use the function np.pad for padding. # ########################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** stride = conv_param['stride'] pad = conv_param['pad'] N, C, H, W = x.shape Out, C, HH, WW = w.shape H_new = int(1 + (H + 2 * pad - HH) / stride) W_new = int(1 + (W + 2 * pad - WW) / stride) X_padded = np.pad(x,((0,0),(0,0),(pad,pad),(pad,pad)),'constant', constant_values=0) out = np.zeros((N,Out,H_new,W_new)) for i in range(N): for j in range(H_new): for k in range(W_new): for o in range(Out): X_i = X_padded[i] inp_conv = X_i[:,j*stride:j*stride+HH,k*stride:k*stride+WW] out_conv = (inp_conv*w[o,:,:,:]).sum() + b[o] out[i,o,j,k] = out_conv # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ########################################################################### # END OF YOUR CODE # ########################################################################### cache = (x, w, b, conv_param) return out, cache ###x def conv_backward_naive(dout, cache): """ A naive implementation of the backward pass for a convolutional layer. Inputs: - dout: Upstream derivatives. - cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive Returns a tuple of: - dx: Gradient with respect to x - dw: Gradient with respect to w - db: Gradient with respect to b """ dx, dw, db = None, None, None ########################################################################### # TODO: Implement the convolutional backward pass. # ########################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** x, w, b, conv_param = cache N, C, H, W = x.shape F, C, HH, WW = w.shape stride = conv_param['stride'] pad = conv_param['pad'] x_pad = np.pad(x, ((0, 0), (0, 0), (pad, pad), (pad, pad)), 'constant', constant_values=0) H_n = 1 + (H + 2 * pad - HH) // stride W_n = 1 + (W + 2 * pad - WW) // stride dx_pad = np.zeros_like(x_pad) dx = np.zeros_like(x) dw = np.zeros_like(w) db = np.zeros_like(b) for n in range(N): for f in range(F): db[f] += dout[n, f].sum() for j in range(0, H_n): for i in range(0, W_n): dw[f] += x_pad[n,:,j*stride:j*stride+HH,i*stride:i*stride+WW]*dout[n,f,j,i] dx_pad[n,:,j*stride:j*stride+HH,i*stride:i*stride+WW] += w[f]*dout[n, f, j, i] dx = dx_pad[:,:,pad:pad+H,pad:pad+W] pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ########################################################################### # END OF YOUR CODE # ########################################################################### return dx, dw, db ###x def max_pool_forward_naive(x, pool_param): """ A naive implementation of the forward pass for a max-pooling layer. Inputs: - x: Input data, of shape (N, C, H, W) - pool_param: dictionary with the following keys: - 'pool_height': The height of each pooling region - 'pool_width': The width of each pooling region - 'stride': The distance between adjacent pooling regions No padding is necessary here. Output size is given by Returns a tuple of: - out: Output data, of shape (N, C, H', W') where H' and W' are given by H' = 1 + (H - pool_height) / stride W' = 1 + (W - pool_width) / stride - cache: (x, pool_param) """ out = None ########################################################################### # TODO: Implement the max-pooling forward pass # ########################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** N, C, H, W = x.shape pool_height = pool_param['pool_height'] pool_width = pool_param['pool_width'] stride = pool_param['stride'] H_n = int(1 + (H - pool_height) / stride) W_n = int(1 + (W - pool_width) / stride) out = np.zeros((N,C,H_n,W_n)) for i in range(N): for j in range(H_n): for k in range(W_n): for l in range(C): x_max = x[i,l,stride*j:stride*j+pool_height,stride*k:stride*k+pool_width] out[i,l,j,k] = np.amax(x_max) pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ########################################################################### # END OF YOUR CODE # ########################################################################### cache = (x, pool_param) return out, cache ###x def max_pool_backward_naive(dout, cache): """ A naive implementation of the backward pass for a max-pooling layer. Inputs: - dout: Upstream derivatives - cache: A tuple of (x, pool_param) as in the forward pass. Returns: - dx: Gradient with respect to x """ dx = None ########################################################################### # TODO: Implement the max-pooling backward pass # ########################################################################### # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** x,pool_param = cache N, C, H, W = x.shape pool_height = pool_param['pool_height'] pool_width = pool_param['pool_width'] stride = pool_param['stride'] H_n = int(1 + (H - pool_height) / stride) W_n = int(1 + (W - pool_width) / stride) dx = np.zeros_like(x) for i in range(N): for j in range(H_n): for k in range(W_n): for l in range(C): index = np.argmax(x[i,l,stride*j:stride*j+pool_height,stride*k:stride*k+pool_width]) ind1,ind2 = np.unravel_index(index,(pool_height, pool_width)) dx[i,l,stride*j:stride*j+pool_height,stride*k:stride*k+pool_width][ind1,ind2] = dout[i,l,j,k] pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ########################################################################### # END OF YOUR CODE # ########################################################################### return dx ###x def softmax_loss(x, y): """ Computes the loss and gradient for softmax classification. Inputs: - x: Input data, of shape (N, C) where x[i, j] is the score for the jth class for the ith input. - y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and 0 <= y[i] < C Returns a tuple of: - loss: Scalar giving the loss - dx: Gradient of the loss with respect to x """ shifted_logits = x - np.max(x, axis=1, keepdims=True) Z = np.sum(np.exp(shifted_logits), axis=1, keepdims=True) log_probs = shifted_logits - np.log(Z) probs = np.exp(log_probs) N = x.shape[0] loss = -np.sum(log_probs[np.arange(N), y]) / N dx = probs.copy() dx[np.arange(N), y] -= 1 dx /= N return loss, dx
ed7ca7f12e8f15e98fd9ece8ef1068a935534bf6
Dwyanepeng/leetcode
/minMoves2_462.py
1,057
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # File :minMoves2_462.py # Author: PengLei # Date : 2019/7/13 '''给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数,其中每次移动可将选定的一个元素加1或减1。 您可以假设数组的长度最多为10000。 例如: 输入: [1,2,3] 输出: 2 说明: 只有两个动作是必要的(记得每一步仅可使其中一个元素加1或减1): [1,2,3] => [2,2,3] => [2,2,2]''' #相遇问题, 不用考虑奇偶数了 class Solution: def minMoves2(self, nums): nums = sorted(nums) length = len(nums) times = 0 center_num = nums[length//2] # print('center_num', center_num) for i in range(0,length//2): times += center_num - nums[i] for j in range(length//2+1,length): times += nums[j] - center_num # for i in range(le ngth): # times += abs(center_num - nums[i]) return times s = Solution() print(s.minMoves2([6,5,4,3,2,1]))
8a2b22ec15509b97e08a10fd63b9a998f292e221
guojia60180/algorithm
/算法题目/算法题目/搜索算法/backtracking回溯法/LeetCode79在矩阵中找字符串.py
795
3.578125
4
#Author guo class Solution: def exist(self, board, word): #一笔画一个字符串 for y in range(len(board)): for x in range(len(board[0])): if self.exit(board,word,x,y,0): return True return False def exit(self,board,word,x,y,i): if i==len(word): return True if x<0 or x>=len(board[0]) or y<0 or y>=len(board): return False if board[y][x]!=word[i]: return False board[y][x]=board[y][x].swapcase() isexit=self.exit(board,word,x+1,y,i+1) or self.exit(board, word, x, y + 1, i + 1) or self.exit(board, word, x - 1, y, i + 1) or self.exit(board, word, x, y - 1, i + 1) board[y][x]=board[y][x].swapcase() return isexit
5c5d2e7d4e846689daed09818cddde1e2e818f1c
zeastion/hardway
/test16.py
623
3.984375
4
people = int(raw_input("How many people?")) cats = int(raw_input("How many cats?")) dogs = int(raw_input("How many dogs?")) if people < cats: print "There are: \n %d people\n %d cats\n------" % (people, cats) print "Too many cats! The world is doomed!" if people > cats: print "There are: \n %d people\n %d cats\n------" % (people, cats) print "Not many cats! The world is saved!" if people < dogs: print "There are: \n %d people\n %d dogs\n------" % (people, dogs) print "The world is drooled on!" if people > dogs: print "There are: \n %d people\n %d dogs\n------" % (people, dogs) print "The world is dry!"
85f6076607b4f2ef0e7cf3f356a277f85147341e
jay-1307/OCR_Project
/sameer_fibonacci.py
114
3.71875
4
x = input("Enter the number: ") i = 1 n = 0 while i <= x : print(i) j = i i = i + n n = j
387dfb60a229d040e9a2cc56e8e2fd4f5de5001e
scarletfrost/python-challenge
/PyBank/main.py
2,771
3.734375
4
import os import csv # cvs file path csvpath = os.path.join('Resources', 'budget_data.csv') #creating empty lists total_months = [] total_profit = [] monthly_profit_change = [] # read csv file with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') # to skip the header row csv_header = next(csvreader) csvreader = list(csvreader) #loop for total number of months and profit for i in csvreader: # adding all the months in a list total_months.append(i[0]) count_months = len(total_months) # adding all the profits/losses in a list total_profit.append(int(i[1])) sum_profits = sum(total_profit) # loop to find the change between months for i in range(0, (len(csvreader)-1)): old_rev = int(csvreader[i][1]) new_rev = int(csvreader[i+1][1]) change = new_rev - old_rev # adding the monthly change in a list monthly_profit_change.append(change) avg_change = round(sum(monthly_profit_change)/len(monthly_profit_change), 2) # calculating greatest increase and decrease g_inc = max(monthly_profit_change) g_dec = min(monthly_profit_change) # finding the months for greatest increase and decrease g_inc_monthindex = monthly_profit_change.index(g_inc) + 1 g_dec_monthindex = monthly_profit_change.index(g_dec) + 1 g_inc_month = csvreader[g_inc_monthindex][0] g_dec_month = csvreader[g_dec_monthindex][0] # printing the analysis to the terminal print("Financial Analysis") print("--------------------------------------------------------") print(f"Total Months: {count_months}") print(f"Total: $ {sum_profits}") print(f"Average Change: ${avg_change}") print(f"Greatest Increase in Profits: {g_inc_month} (${g_inc})") print(f"Greatest Decrease in Profits: {g_dec_month} (${g_dec})") # exporting the analysis to a text file output_path = os.path.join("FinancialAnalysis.txt") # Open the file using "write" mode with open(output_path, 'w', newline='') as txtfile: txtfile.write("Financial Analysis") txtfile.write('\n' + "---------------------------------------------------------") txtfile.write('\n' + f"Total Months: {count_months}") txtfile.write('\n' + f"Total: ${sum_profits}") txtfile.write('\n' + f"Average Change: ${avg_change}") txtfile.write('\n' + f"Greatest Increase in Profits: {g_inc_month} (${g_inc})") txtfile.write('\n' + f"Greatest Decrease in Profits: {g_dec_month} (${g_dec})")
5ce3fec0cae69bab7aaea8ff8befe4504fa12830
libus1204/bigdata2019
/01. Jump to python/chap06/prac5.py
1,841
3.71875
4
class InputError1(Exception): pass class InputError2(Exception): pass class InputError3(Exception): pass class prac4_sum: def __init__(self, num1, num2): try: if num1.isdigit() == False: raise InputError1("죄송합니다. 첫 번째 입력이 [%s] 입니다. 숫자를 입력하세요." % num1) except Exception as e: print(e) try: if num2.isdigit() == False: raise InputError2("죄송합니다. 두 번째 입력이 [%s] 입니다. 숫자를 입력하세요." % num2) except Exception as e: print(e) self.num1 = int(num1) self.num2 = int(num2) def safe_sum(self): result = self.num1 + self.num2 print("두 수의 덧셈은 : ", result) def safe_min(self): result = self.num1 - self.num2 print("두 수의 뺄셈은 : ", result) def safe_mul(self): result = self.num1 * self.num2 print("두 수의 곱셈은 : ", result) def safe_div(self): try: if num2 == '0': raise InputError3("죄송합니다. 두 번째 입력에서 0을 입력하셨습니다. 분모는 0이 되어선 안됩니다.") except Exception as e: print(e) else: result = self.num1 / self.num2 print("두 수의 나눗셈은 : ", result) while True: try: user_input = input("두 수를 입력하세요 : ").split() if user_input[0] =="종료" : print("프로그램을 종료합니다.") exit() num1 = user_input[0] num2 = user_input[1] my_cal = prac4_sum(num1, num2) my_cal.safe_sum() my_cal.safe_min() my_cal.safe_mul() my_cal.safe_div() except Exception as e: pass
bbf263a1fcc9dec184d54309f9aa6db1ba35a070
chinmay29hub/hangman-game
/hangman.py
1,965
4.21875
4
import random name = input("What is your name ? --->> ") print("\n") print("It's time to play Hangman "+name) print("Good Luck\n") words = ['program', 'trees', 'computer', 'python', 'java', 'syntax', # Insert n number of words here 'house', 'linux', 'system', 'science', 'code', 'network', 'planet'] word = random.choice(words) # we will you use while loop for the condition till the turns are 0 def game(): print("-------------------------------START----------------------------\n") print("Start guessing the characters\n") noofguesses = '' turns = 13 #these are the no of chances the player will get, you can add yours while turns > 0: guess = input("Guess a character ---> ") print("\n") noofguesses += guess failed = 0 for char in word: if char in noofguesses: print(char) else: print("_") failed += 1 if failed == 0: print("You have won the game ") print("The Word Is -----> ", word) exit() if guess not in word : turns -= 1 print("Wrong Guess :( ") print("\n") print("You have ",+turns,"chances left") print("\n") if turns == 0: print("You have lost") print("The correct word was ----> ",word) game()
577fde3e18556eb3a7ff1f88abaed04fdea0b13d
eshu-bade/Comprinno-Questions
/Question4.py
1,624
4.03125
4
# Question link: https://drive.google.com/file/d/1YyMzLed3RZEWcYIjSQ5Ze1hJqFWyWmYt/view?usp=sharing def MilkCookies(): validities = [] # Taking a list to see if all the strings follow the pattern for each_case in full_list: """Iterating over the complete input section """ if (len(each_case) ==1 or each_case[-1] =='cookie') and 'cookie' in each_case: # Prints NO if a single input or the last parameter of the input and cookie in the list print("NO") # Prints YES if a single input or the if just milk in the input elif ('milk'in each_case or len(each_case) ==1) and 'cookie' not in each_case: print("YES") elif len(each_case)>1: for i in range(len(each_case)): # eat = ['c', 'm', 'm', 'c', 'm', 'c', 'm'] if each_case[i] == 'cookie': if each_case[i+1] == 'milk': validity = 'True' validities.append(validity) else: validity = 'False' validities.append(validity) if 'False' in validities: print("NO") else: print("YES") validities.clear() # Input section of the code testCases = int(input("testCases are: ")) full_list = [] for i in range(testCases): integers = int(input("number of values: ")) inputStrings = list(map(str,input("Enter either milk or cookie by separating with space : ").strip().split(' ')))[:integers] full_list.append(inputStrings) # Calling the function MilkCookies()
aa687afb7cd22e41d05d0488ca64254caecedc25
mauricioZelaya/QETraining_BDT_python
/DanielaTicona‎/practice 4.py
1,559
3.765625
4
print "_+_+_+_+_+_+_ Exercise 1+_+_+_+_+_+_+_+_+_+_" x= "esto es una pruebaddfgfdg https://docs.google.com/document21 testsfdsf" #x="sfdsfe4 dsgfsdg fsdf " n= x.find ("http") key=0 #print (n) url="" if (n>0): while (key==0 ): if (x[n]!=" "): #print (x[n]) url=url+x[n] n=n+1 else: key=1 #print ("nehhh") print ("La direccion url es:",url) else: print ("no hay Url") print "+_+_+_+_+_+_+_+_+_+_+_+_+Exercise 2+_+_+_+_+_+_+_+_+_+_+_+_" z="Papafrita miau aba" old="a" new="5" def replace(z, old, new): n=len(z) count=0 newstr="" while (count<n): if z[count]==old: #print "secambia" , z[count] newstr=newstr+new else: #print "no pasa nada" newstr=newstr+z[count] count=count+1 return (newstr) phrase=replace(z,old,new) print "La frase original es:", z print "su reemplazo es:", phrase print "+_+_+_+_+_+_+_+_+_+_+_+_+ Exercise 3 +_+_+_+_+_+_+_+_+_+_+_+_" alpha ={'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0,' ':0} r="A mi me GustA LA SAlchipApaAA" y= r.lower() print y for i in range (len(y)): if alpha.has_key(y[i]): word=y[i] alpha[word]= alpha[word]+1 #print "esta el valor", word, "y este es el valor", alpha[word] else: print "nuu hay" print "the String is:", y print alpha # test #mmg print alpha.keys(), alpha.values()
592a1d91006f81c81d72caa06f2d45ab2dec0c80
jpatra78/General-Assembly
/1_python_practice/Project1-4b.py
836
4
4
#Project1 - Problem 4 #Jeff Patra import numpy as np # Provided for loop for i and numbers: for i in range(5, 15, 2): numbers = [x if not x % i == 0 else 0 for x in range(101)] #Function that calculates summary stats for distribution def summary_stats(i,numbers): #num = range(1,number,2) diff = len(numbers) - (len(numbers) - i) print 'The input number i is the %sth number in the range' % (diff) #Not working properly if len(numbers) % 2 == 1: median = numbers[(len(numbers)+1)/2-1] else: lower = numbers[len(numbers)/2-1] upper = numbers[len(numbers)/2] median = numbers[len(numbers)/2] print 'The median is: %s' % (median) mean = sum(numbers)/len(numbers) print 'The mean is: %s' % (mean) # Call your function here using i and numbers: print summary_stats(25,numbers)
48ee4addea3564582dee51d09d28a14b07114d8b
santhosh-kumar/AlgorithmsAndDataStructures
/python/test/unit/problems/dynamic_programming/test_longest_increasing_subsequence.py
757
3.9375
4
""" Unit Test for longest_increasing_subsequence """ from unittest import TestCase from problems.dynamic_programming.longest_increasing_subsequence import LongestIncreasingSubsequence class TestLongestIncreasingSubsequence(TestCase): """ Unit test for LongestIncreasingSubsequence """ def test_solve(self): """Test solve Args: self: TestLongestIncreasingSubsequence Returns: None Raises: None """ # Given input_list = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] lis_problem = LongestIncreasingSubsequence(input_list) # When result = lis_problem.solve() # Then self.assertEqual(result, 6)
aa824f3b0bd2d772662ecf38fb2cf7dffa2a1653
abraaojs/bigdata
/model_build.py
1,759
3.546875
4
# -*- coding: utf-8 -*- """ created by Abraão Silva @uthor abraaosilva """ import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import MinMaxScaler from sklearn.pipeline import Pipeline from sklearn.externals import joblib def read_input_attributes(filename="attributes.txt"): """Função de leitura do arquivo com os nomes dos atributos""" with open(filename, 'r') as file_attr: return [attr.replace('\n', '') for attr in file_attr.readlines()] def test_model(data, model): """Função que treina e testa um modelo de machine learning""" input_attributes = read_input_attributes() input_data = data[input_attributes].values output_data = data['class'] train_x, test_x, train_y, test_y = train_test_split(input_data, output_data, test_size=.3) model.fit(train_x, train_y) print("Acurácia do modelo = %.3f"%model.score(test_x, test_y)) def create_model(data, model): """Função que treina e salva um modelo de machine learning""" input_attributes = read_input_attributes() input_data = data[input_attributes].values output_data = data['class'] model.fit(input_data, output_data) model_filename = "model.pkl" joblib.dump(model, model_filename) data = pd.read_csv("bolsa.data") model = Pipeline([("norm", MinMaxScaler()), ("classifier", LogisticRegression())]) # Selecione o que deseja fazer: treinar/testar e/ou gerar um modelo # (des)comentando as funções abaixo test_model(data, model) #create_model(data, model)
aae590fdb481a2b083bfeebc563d165acaf27d29
Joshuayeo95/Osusume
/mal_scrapers.py
4,453
3.578125
4
''' Functions for scraping data from MyAnimeList Author : Joshua Yeo Last Updated : 11 September 2020 ''' from selenium import webdriver from bs4 import BeautifulSoup import requests import random import pickle import time def mal_user_profiles_scraper(mal_user_profiles ,num_loops=10, time_between_loops=30, verbose=True): ''' Function that scrapes MyAnimeList for Users and the respective links to their profiles. Arguments: mal_user_profiles : dict Dictionary with MAL Username as key and respective profile links as values. num_loops : int Number of times to loop the scraper. time_between_loops : int Time in seconds to wait between 'refreshing' the website. Webpage we are scraping from displays recent users, therefore to get new users \ we need to wait a short period before requesting from the same webpage. verbose : bool Displays number of new users added to the dictionary for each loop. Returns: mal_users_profiles : dict Updated list of Usernames and profile links. ''' initial_number_of_users = len(mal_user_profiles) loop_counter = 0 while loop_counter < num_loops: initial_users = len(mal_user_profiles) source = requests.get('https://myanimelist.net/users.php').text soup = BeautifulSoup(source, 'lxml') for user_entry in soup.find_all('td', class_='borderClass'): user_name = user_entry.div.a.text user_profile_url = 'https://myanimelist.net/profile/' + user_name user_animelist_url = 'https://myanimelist.net/animelist/' + user_name + '?status=2' mal_user_profiles[user_name] = [user_profile_url, user_animelist_url] loop_counter += 1 new_users_added = len(mal_user_profiles) - initial_users if verbose: print(f'Number of new user profiles added : {new_users_added}') time.sleep(time_between_loops) total_new_users_added = len(mal_user_profiles) - initial_number_of_users print() print('Beep Boop. Scraping Finished.') print(f'Total number of new users added : {total_new_users_added}') return mal_user_profiles def user_completed_animelist_scraper(mal_user_profiles, user_anime_ratings, chrome_driver_path, browser_loading_buffer=10): ''' Function that scrapes the completed animes watched by the user and their respective scores. Arguments: mal_user_profiles : dict Dictionary of usernames and their respective profiles links. user_anime_ratings : dict Dictionary of users and their the given ratings of their completed anime. {username : {anime : rating}} chrome_driver_path : str Path to chromedriver. browser_loading_buffer : int Time in seconds to wait for the webpage to finish loading. Returns: user_anime_ratings : dict Updated dictionary of users and their respective anime and ratings. ''' users_updated = 0 new_users_added = 0 for user, profile_links in mal_user_profiles.items(): animelist_url = profile_links[1] # completed anime list browser = webdriver.Chrome(executable_path=chrome_driver_path) browser.get(animelist_url) time.sleep(browser_loading_buffer) soup = BeautifulSoup(browser.page_source, 'lxml') anime_names = [] anime_ratings = [] for anime_cells in soup.find_all('td', class_='data title clearfix'): anime_names.append(anime_cells.a.text) # Saving anime ratings, which are in String format as there anime without ratings ('-') for anime_rating_cells in soup.find_all('td', class_='data score'): anime_ratings.append((anime_rating_cells.a.span.text.strip())) user_ratings = dict(zip(anime_names, anime_ratings)) if user_anime_ratings.get(user): users_updated += 1 else: new_users_added += 1 user_anime_ratings[user] = user_ratings browser.close() print() print('Beep Boop. Anime Ratings for Users have been updated.') print(f'Records updated : {users_updated}') print(f'New records added : {new_users_added}') print(f'Total number of users : {len(user_anime_ratings)}') print() return user_anime_ratings
1d65b4f9b10b8d70ba0e362b1ba437ad84ba7e80
ankitk2109/LeetCode
/22. MergeTwoBinaryTrees-Iterative.py
1,607
4.21875
4
#PS: https://leetcode.com/problems/merge-two-binary-trees # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1 and not t2: return if not t1: return t2 if not t2: return t1 else: stack = [] stack.append((t1,t2)) while(stack): n1,n2 = stack.pop() n1.val += n2.val #If n1.left is None we simply point to n2.left (Even if n2.left is None that would suffice our condition) if(n1.left == None): n1.left = n2.left #if above condition is false that means n1.left is not none hence we check wether n2.left is none or not. If it's not none then append it to stack. elif(n2.left != None): stack.append((n1.left, n2.left)) #If n1.right is None we simply point to n2.right (Even if n2.right is None that would suffice our condition) if(n1.right == None): n1.right = n2.right #if above condition is false that means n1.right is not None hence we check wether n2.right is None or not. If it's not None then append it to stack. elif(n2.right != None): stack.append((n1.right, n2.right)) return t1
1bfbf05ef647c552dafb3965a985c89b3f941ba8
didemertens/udemy_python
/advanced_sets.py
744
3.890625
4
s = set() s.add(1) s.add(2) #sets don't take duplicate items s.clear() s = {1,2,3} sc = s.copy() s.add(4) s.difference(sc) # shows the difference between s and sc s1 = {1,2,3} s2 = {1,4,5} s1.difference_update(s2) # returns the first set without the element that isn't in set2 # if it isn't in the set, does nothing otherwise removes it s1.discard(12) s1 = {1,2,3} s2 = {1,2,4} s1.intersection(s2) # common in both of the sets s1.intersection_update(s2) # first set with just the common elements s1 = {1,2} s2 = {1,2,4} s3 = {5} s1.isdisjoint(s2) # they do have something in common so it's False s1.isdisjoint(s3) # is true, have a null intersection s1.issubset(s2) # is it a part of set2 and other way around: s2.issuperset(s1)
86f6fe1cd4c94962c7987a5dfe54feaac3eee1a7
OxingchenO/Python_Lib
/code/dict_default.py
391
3.890625
4
# -*- coding: utf-8 -*- from collections import defaultdict, Counter if __name__ == '__main__': default_list = defaultdict(list) default_list["a"].append(1) default_list["a"].append(2) default_list["a"].append(3) print(default_list) default_zero = Counter() default_zero["b"] += 1 default_zero["b"] += 2 default_zero["b"] += 3 print(default_zero)
d2790846aeb0005cc6d9621cfec12c16afca0a86
medifle/python_6.00.1x
/Quiz/Problem4_defMyLog.py
237
3.984375
4
def myLog(x, b): ''' x: a positive integer b: a positive integer; b >= 2 returns: log_b(x), or, the logarithm of x relative to a base b. ''' if x < b: return 0 else: return 1 + myLog(x / b, b)
3549d61ab303840961e898cc56f4bc4216f2b44f
marcoAureliosm/Listas-de-atividades-06-de-python
/questão 01.py
262
3.875
4
def trueandfalso(num): if num %2 ==0: return True else: return False valor =int(input("DIGITE O NUMERO")) trueandfalso(valor) if trueandfalso(valor)==True: print("NUMERO PAR: ",valor) else:print("NUMERO IMPAR: ",valor)
563ce4212016aa39becb932c22341db180a623a9
gyula/hackerrank
/src/python/balanced-brackets.py
501
3.53125
4
#!/bin/python import sys lefts = '{[(' rights = '}])' brackets = { a:b for a,b in zip(rights,lefts)} def isBalanced(s): br_stack = [] for c in s: if c in lefts: br_stack.append(c) elif c in rights: if not br_stack or br_stack.pop() != brackets[c]: return False return not br_stack t = int(raw_input().strip()) for a0 in xrange(t): s = raw_input().strip() if isBalanced(s): print 'YES' else: print 'NO'
d9a9d80a3d4129521c5b10a7762e499565d16754
goatber/dice_py
/main.py
1,342
4.1875
4
""" Dice Rolling Simulator by Justin Berry Python v3.9 """ import random class Die: """ Creates new die with methods: roll """ def __init__(self, sides: int): self.sides = sides def roll(self) -> int: """ Rolls die, returns random number based on probability """ result = random.randint(1, self.sides) return result def main(): """ Runs simulator """ choosing_sides = True print("----------\n" "Type 'stop' to end program at any time" ) while choosing_sides: print("----------") inp = input("How many sides should the die have? (4, 6, 8, 12, etc):\n") if inp.isalpha(): if inp == "stop": raise SystemExit() if inp.isdigit(): inp = int(inp) if inp > 0: if inp < 1000: die = Die(inp) print("You rolled a:", die.roll()) else: print("Die must have less than 1000 sides.") else: print("Die must have more than 0 sides.") else: print("Input must be numeric (including '-').") # Run game on compile: if __name__ == "__main__": main()
65733a52483816d3a797469c67c036e49399c45b
lucaseduardo101/MetodosII
/Trapezio/trapezio.py
493
3.859375
4
#metodos para trapezio sem repeticao f=[] def h_simples(xm,x0): return(xm-x0) def trapezioSimples(h,fx0,fx1): return ((h/2)*(fx0+fx1)) def erro(integral,it): return (integral-it) #metodos para trapezio com repeticao def h_repetido(b,a,m): aux=(float)(b-a) h2=aux/m return h2 def trapezioRepetido(h,fx0,fx1,somatorio): return ((h/2)*(fx0+(2*somatorio)+fx1)) def somatorio(f,m): s=0 #Realiza o somatorio for i in range(1,m): print "f[ ",i,"] =", f[i] s = s + f[i] return s
81c7eb9d4f7eef15bd60a5eb25b2e20c84cc18b7
calincan2000/CVND-Facial-Keypoint-Detection
/models-Copy1.py
3,610
3.671875
4
## TODO: define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TODO: Define all the layers of this CNN, the only requirements are: ## 1. This network takes in a square (same width and height), grayscale image as input ## 2. It ends with a linear layer that represents the keypoints ## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs # As an example, you've been given a convolutional layer, which you may (but don't have to) change: # 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel self.conv1 = nn.Conv2d(1,32,5) # (32,92,92) output tensor # (W-F)/S + 1 = (96-5)/1 + 1 = 92 # the output Tensor for one image, will have the dimensions: (10, 110, 110) # after one pool layer, this becomes (10, 55, 55) # maxpool layer # pool with kernel_size=2, stride=2 self.pool = nn.MaxPool2d(2, 2) #this becomes (10, 55, 55) # second conv layer: 10 inputs, 20 outputs, 3x3 conv ## output size = (W-F)/S +1 = (55-3)/1+1 = 26 # the output tensor will have dimensions: (20, 26, 26) # after another pool layer this becomes (20, 13, 13); self.conv2 = nn.Conv2d(32,64,5) # (64,44,44) output tensor # (W-F)/S + 1 = (46-5)/1 + 1 = 42 # third conv layer: 20 inputs, 40 outputs, 3x3 conv ## output size = (W-F)/S +1 = (13-3)/1+1 = 5 # the output tensor will have dimensions: (40, 5, 5) # after another pool layer this becomes (40, 2, 2); # self.conv3 = nn.Conv2d(20, 40, 3) self.fc1 = nn.Linear(64*21*21, 1000) self.fc1 = nn.Linear(1000, 500) self.fc1 = nn.Linear(500, 136) # dropout with p=0.4 self.drop1 = nn.Dropout(p=0.4) # finally, create 10 output channels (for the 10 classes) # self.fc2 = nn.Linear(422, 136) ## Note that among the layers to add, consider including: # maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting def forward(self, x): ## TODO: Define the feedforward behavior of this model ## x is the input image and, as an example, here you may choose to include a pool/conv step: ## x = self.pool(F.relu(self.conv1(x))) # x.view(x.size(0), -1) # x = self.pool(F.relu(self.conv1(x))) # x = self.pool(F.relu(self.conv2(x))) # Flatten and continue with dense layers # x = x.view(x.size(0), -1) # x = F.relu(self.fc1(x)) # x = self.fc1_drop(x) # x = F.relu(self.fc2(x)) x = F.relu(self.conv1(x)) x = self.pool(x) x = F.relu(self.conv2(x)) x = self.pool(x) x = self.drop1(x) # Flatten and continue with dense layers x = x.view(x.size(0), -1) x = F.selu(self.fc1(x)) x = self.drop1(x) x = F.selu(self.fc2(x)) x = self.drop1(x) x = self.fc3(x) #x = self.fc1_drop(x) # a modified x, having gone through all the layers of your model, should be returned return x
dbd22ccfa6c2b6c316c147b2146283816bafcd7d
devinitpy/devinitpy.github.io
/mid/methods.py
610
4.0625
4
list = ['larry', 'curly', 'molly','molly'] list.append('shemp') ## append elem at end list.insert(0, 'xxx') ## insert elem at index 0 list.extend(['yyy', 'zzz']) ## add list of elems at end print list ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz'] print list.index('curly') ## 2 m=list.remove('curly') ## search and remove that element print(m) n=list.pop(1) print n ## removes and returns 'larry' print list ## ['xxx', 'moedhhh', 'shemp', 'yyy', 'zzz'] x=list.count('molly') print x #string methods s=list[1] res=s[1:3] print res # s.replace ("rry" ,"m") # print s
7dbed04d7ca3dce2cb206aacdaadd059fe9c3a29
HankerZheng/LeetCode-Problems
/python/292_Nim_Game.py
807
3.734375
4
""" If there is 0 stones left, I lost. If there is 1 - 3 stones left, I win. dp[i] - if there is i stones on the table, would the first picker be the winner? dp[i] = any([not dp[i-1], not dp[i-2], not dp[i-3]]) """ class Solution(object): def canWinNim_On(self, n): """ :type n: int :rtype: bool """ if n == 0: return False if 1 <= n <=3: return True dp = [False] * 3 dp[1] = dp[2] = True for numStone in xrange(3, n + 1): # not a || not b || not c = not( a and b and c) dp[numStone % 3] = not all(dp) return dp[n % 3] def canWinNim_O1(self, n): return bool(n & 3) if __name__ == '__main__': sol = Solution() for i in xrange(40): print i, sol.canWinNim_On(i)
5093739e24471c4a2d0d64606f55d1d59237cf36
kwoneyng/TIL
/Solving_Problem/daily_222/1207/요기요 3번.py
295
3.53125
4
def solution(S): ls = list(S) wdset = [] vis = [] for i in range(len(ls)): if ls[i] not in vis: vis.append(ls[i]) else: wdset.append(vis) vis = [ls[i]] wdset.append(vis) return(len(wdset)) S = input() print(solution(S))
759d496e73b1b5be08503fd3687b95e18e00430e
Unintented/Python-basis
/function_2.py
526
3.90625
4
# 返回字典 def build_person(first_name, last_name, age=""): person = {'first': first_name.title(), 'last': last_name.title()} if age: person['age'] = age return person if __name__ == '__main__': musician = build_person('kevin', 'chan', age=27) print(musician) # 传递列表 def greet_users(names): for name in names: msg = "Hello," + name.title() print(msg) if __name__ == '__main__': usernames = ['kevin', 'lily', 'tom'] greet_users(usernames)
50c77699fa17b9d6bac2f0e5b6312bfe51fb9ed0
Elyseum/python-crash-course
/ch3/guests.py
1,817
3.890625
4
""" Dinner guests exercise """ GUESTS = ['bill', 'linus', 'steve'] print("Invitations take 1:") print("Hi " + GUESTS[0].title() + ", would you like to come to my dinner?") print("Hi " + GUESTS[1].title() + ", would you like to come to my dinner?") print("Hi " + GUESTS[2].title() + ", would you like to come to my dinner?") print("Oops, turns out " + GUESTS[2].title() + " can't make it") GUESTS[2] = 'Satya' print("\nInvitations take 2:") print("Hi " + GUESTS[0].title() + ", would you like to come to my dinner?") print("Hi " + GUESTS[1].title() + ", would you like to come to my dinner?") print("Hi " + GUESTS[2].title() + ", would you like to come to my dinner?") GUESTS.insert(0, "new guest 1") GUESTS.insert(2, "new guest 2") GUESTS.append("new guest 3") print("\nInvitations take 3:") print("Hi " + GUESTS[0].title() + ", would you like to come to my dinner?") print("Hi " + GUESTS[1].title() + ", would you like to come to my dinner?") print("Hi " + GUESTS[2].title() + ", would you like to come to my dinner?") print("Hi " + GUESTS[3].title() + ", would you like to come to my dinner?") print("Hi " + GUESTS[4].title() + ", would you like to come to my dinner?") print("Hi " + GUESTS[5].title() + ", would you like to come to my dinner?") print("\nCancellations:") print("Sorry " + GUESTS.pop().title() + ", I have to cancel your invitation") print("Sorry " + GUESTS.pop().title() + ", I have to cancel your invitation") print("Sorry " + GUESTS.pop().title() + ", I have to cancel your invitation") print("Sorry " + GUESTS.pop().title() + ", I have to cancel your invitation") print("Don't worry " + GUESTS[0].title() + ", you're still invited") print("Don't worry " + GUESTS[1].title() + ", you're still invited") del GUESTS[0] del GUESTS[0] # Don't use 1 ^^ print("\nEmpty list:") print(GUESTS)
248fc887715887849aed9f0cae485e6de8a30ae3
civcomunb/Downloads
/eq2deg_solver.py
603
4.09375
4
from math import sqrt print('This software solves 2nd degree equations like ax^2 + bx + c = 0\n') a = float(input('Type the value of a: ')) b = float(input('Type the value of b: ')) c = float(input('Type the value of c: ')) delta = b*b - 4*a*c try: sdelta = sqrt(delta) r1 = (-b + sdelta)/(2*a) r2 = (-b - sdelta)/(2*a) print('Your equation: %fx^2 + %fx + %f = 0\n' % (a, b, c)) print('Solution: \nr1 = %f\nr2 = %f' % (r1, r2)) input('Press <Return> to exit...') except ValueError: print('\nDelta is negative. Result is complex.') input('Press <Return> to exit...')
78a7a2f07bd4b2c803f2f1012a3878dd815ddabd
aratik711/grokking-the-coding-interview
/sliding-window/words-concat/words-concat.py
1,810
4.25
4
""" Given a string and a list of words, find all the starting indices of substrings in the given string that are a concatenation of all the given words exactly once without any overlapping of words. It is given that all words are of the same length. Example 1: Input: String="catfoxcat", Words=["cat", "fox"] Output: [0, 3] Explanation: The two substring containing both the words are "catfox" & "foxcat". Example 2: Input: String="catcatfoxfox", Words=["cat", "fox"] Output: [3] Explanation: The only substring containing both the words is "catfox". time complexity: O(N∗M∗Len) where ‘N’ is the number of characters in the given string, ‘M’ is the total number of words, and ‘Len’ is the length of a word. Space complexity: O(M+N) """ def find_word_concatenation(str1, words): if len(words) == 0 or len(words[0]) == 0: return [] word_freq = {} for word in words: if word not in word_freq: word_freq[word] = 0 word_freq[word] += 1 result_indices = [] words_count = len(words) word_length = len(words[0]) for i in range((len(str1) - (words_count * word_length)) + 1): words_seen = {} for j in range(words_count): next_word_index = i+j * word_length word = str1[next_word_index:next_word_index+word_length] if word not in word_freq: break if word not in words_seen: words_seen[word] = 0 words_seen[word] += 1 if words_seen[word] > word_freq.get(word, 0): break if j+1 == words_count: result_indices.append(i) return result_indices print(find_word_concatenation("catfoxcat", ["cat", "fox"])) print(find_word_concatenation("catcatfoxfox", ["cat", "fox"]))
54488222c54e9107dbd48dd5e29fe68ccd4bbe23
AryanshuArindam08/Simple-Quiz-Game-In-Python
/Quiz_game.py
899
3.953125
4
# Simple-Quiz-Game-In-Python print('Welcome to Aryanshu Quiz') answer=input('Are you ready to play the Quiz ? (yes/no) :') score=0 total_questions=3 if answer.lower()=='yes': answer=input('Question 1: what is the easiest programming language?') if answer.lower()=='python': score += 1 print('correct') else: print('Wrong Answer :(') answer=input('Question 2: who is the world richest person ? ') if answer.lower()=='Elon Musk': score += 1 print('correct') else: print('Wrong Answer :(') answer=input('Question 3: Birthday of Elon Musk?') if answer.lower()=='28 June': score += 1 print('correct') else: print('Wrong Answer :(') print('Than kyou for Playing',score,"questions correctly!") mark=(score/total_questions)*100 print('Marks obtained:',mark) print('BYE!') print('Made by ARYANSHU')
a5a98534d5d422cc3ec249a5cc8c31834c40539e
Emirichu/Python-labs
/Woostagram2.0.py
811
3.984375
4
username = input("Enter Username:") password = input("Enter Password:") if (username not in ("HexBeetle75","JavaMan27","PetPet")): print("That Username" ,username ,"does not exsit") if (username == "HexBeetle75" and password != "invasivespecies"): print("Sorry, wrong password!") elif (username == "HexBeetle75" and password == "invasivespecies"): print("Welcome ", username , "!") if (username == "JavaMan27" and password != "coder"): print("Sorry, wrong password!") elif (username == "JavaMan27" and password == "coder"): print("Welcome ", username , "!") if (username == "PetPet" and password != "particardi"): print("Sorry, wrong password!") elif (username == "PetPet" and password == "particardi"): print("Welcome ", username , "!") #By Ayush Kadigari
7b4e501de7a97048058e7a58914699fd5ce8bee6
ElseVladimir/21_python_game
/game.py
1,403
3.515625
4
# --------- BLACK JACK ---------- # # --------- ver. 1.0 alpha -------# # import json import random import os.path # --- configuration JSON --- # filename = "black_jack/settings.txt" # check_settings = os.path.exists('setting.txt') # my_file = open(filename, 'w') # --- --- connect = True check = True while connect == True: deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] total_cards = random.sample(deck, 2) sum_cards = sum(total_cards) print("Вы вытянули из колоды : " + str(total_cards) + " Сумма карт: " + str(sum_cards)) while check == True: if sum_cards < 21: choice = input("Взять карту? (y/n): ") if choice == "y": sum_cards = sum_cards + random.choice(deck) print("Сумма карт: " + str(sum_cards)) elif choice == "n": exit("Game over") elif sum_cards == 21: choice = input("Поздравляем, вы сорвали банк! Продолжить? (y/n)") if choice == "y": break elif choice == "n": exit("Game over") elif sum_cards > 21: choice = input("Вы проиграли банк! Продолжить? (y/n)") if choice == "y": break elif choice == "n": exit("Game over")
10cb9b758bde1c808d847bd7bda6a6b1919be903
lidongze6/leetcode-
/1003. 检查替换后的词是否有效-3.py
100
3.625
4
def isValid(S): while S != "" and "abc" in S: S=S.replace("abc","") return S==""
9598a249b4c3c087e4ce6bd549e880652bf2a112
Supermaxman/PiRegister
/PiRegister/Item.py
709
3.5625
4
from decimal import * class Item(object): #Object for individual item data def __init__(self, id, name, price): self.id = id self.name = name self.price = price @property def id(self): return self.__id @id.setter def id(self, value): self.__id = int(value) @property def name(self): return self.__name @name.setter def name(self, value): self.__name = str(value) @property def price(self): return self.__price @price.setter def price(self, value): self.__price = Decimal(value) def __str__(self): return "{0}:{1}:{2}:{3}".format(self.id, self.name, self.price)
09f367131da317cd466526668c06e53ab9226e89
acmcx/travis-try
/tests.py
420
3.53125
4
import unittest from hello import hello, goodbye, me_need_test class TestHello(unittest.TestCase): def test_hello(self): h = hello() self.assertEqual(h, "Hello, World!") def test_goodbye(self): g = goodbye() self.assertEqual(g, 11) def test_me_need_test(self): i = me_need_test() self.assertEqual(i, 1) if __name__ == "__main__": unittest.main()
339138f755afbc2ce2293144beaf3464b25b23d4
akotadi/Competitive-Programming
/Contest/Club Ranking/2019 ⁄ 2/1/A.py
183
3.5
4
def gcd(x,y): while(y): x, y = y, x % y return x s = raw_input() n = int(s.split()[0]) k = int(s.split()[1]) aux = gcd(n,k) print(k*aux*(n/aux-1) + (aux-1)*(k-1))
9821dd074bb434205be73a65407ec4cc7a8bb3a4
lucasebs/EstruturaDeDados2017.1
/circleList.py
2,653
4
4
''' Node Object ''' class Node: def __init__(self, data): self.next = None self.data = data ''' Circle List Object ''' class CircleList: def __init__(self): self.reference = None ''' Find Last Element ''' def find_last_node(self): if(self.reference == None): return None temp = self.reference while(temp.next != self.reference): temp = temp.next return temp ''' List Size ''' def listSize(self): if(self.reference == None): return 0 if(first_node == first_node.next): return 1 temp = self.reference count = 0 while(temp.next != self.reference): temp = temp.next count = 0 return count ''' Add Element at Begin ''' def add_begin_circle(self, data): new_node = Node(data) if(self.reference == None): self.reference = new_node new_node.next = self.reference return last_node = self.find_last_node() last_node.next = new_node new_node.next = self.reference self.reference = new_node ''' Add Element at End ''' def add_end_circle(self, data): new_node = Node(data) if(self.reference == None): self.reference = new_node new_node.next = self.reference return last_node = self.find_last_node() last_node.next = new_node new_node.next = self.reference ''' Add Element at Position pos ''' def add_pos_circle(self, data, pos): new_node = Node(data) if(self.reference == None): self.reference = new_node new_node.next = self.reference return if(pos > self.listSize()): raise ListSize('Position out of the list') count = 0 temp_a = self.reference temp_b = temp_a.next while(pos < count): temp_a = temp_b temp_b = temp_a.next temp_a.next = new_node new_node.new_node = temp_b ''' Remove Element at Begin ''' def remove_begin_circle(self): if(self.reference == None): raise ListEmpty('List Empty') first_node = self.reference if(first_node == first_node.next): self.reference = None last_node = self.find_last_node() self.reference = first_node.next last_node.next = self.reference ''' Remove Element at End ''' def remove_end_circle(self): if(self.reference == None): raise ListEmpty('List Empty') last_node = self.reference ''' Remove Element at End ''' def remove_pos_circle(self, pos): if(self.reference == None): raise ListEmpty('List Empty') if(pos > self.listSize()): raise ListSize('Position out of the list') if(first_node == first_node.next and pos == 0): self.reference = None count = 0 temp_a = self.reference temp_b = temp_a.next while(pos < count): temp_a = temp_b temp_b = temp_a.next temp_a.next = temp_b.next
9656d8137ad87241b7748e66209c8d41fb43061f
RicardoAriel09/Exercicios-em-python
/Curso em Video/Exercício 69.py
508
3.65625
4
p = 0 h = 0 m20 = 0 while True: print("===" * 20) n1 = int(input("\033[0;31mDigite a sua idade: ")) n2 = str(input("Qual é o seu sexo? [M/F] ")).upper() n3 = str(input("Quer continuar? [S/N] \033[m")).upper() if n1 > 18: p += 1 if n2 == "M": h += 1 if n1 < 20 and n2 == "F": m20 += 1 if n3 == "N": break print(f"Há {p} pessoa(s) com mais de 18 anos.") print(f"Foram cadastrados {h}, homens.") print(f"Há {m20} mulher com menos de 20 anos.")
0d16dcf6747a47c99b5143915690eb3223e9f211
ricartty/Curso_Python_Zumbis
/Resolvidos Lista I/Exercicio_1.9.py
447
3.78125
4
#Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado pelo usurio, assim como a quantidade de dias pelos quais o carro foi alugado. Calcule o preo a pagar, sabendo que o carro custa R$ 60,00 por dia e R$ 0,15 por km roda kmp = float(input("Quantidade de km percorridos: ")) dias = float(input ("Quantos dias de aluguel: ")) preco = 60*dias + 0.15*kmp print ("O valor final do aluguel de %.2f" %preco)
94354acc5d5f4d4614d4054be4706f7a10d31a02
melany202/programaci-n-2020
/talleres/taller3.py
1,199
3.984375
4
#ejercicio 1 print("---ejercicio1 for---") suma = 0 for i in range(101): suma += i print(suma) #ejercicio 2 print("---ejercicio2 for---") preguntaNumero ="Ingrese un numero entero : " numero1= int(input(preguntaNumero)) factorial = 1 for i in range(numero1): factorial=factorial * (i+1) print(factorial) #ejercicio 3 print("---ejercicio3 for---") sumaPositivo=0 cantidadPositivos=0 sumaNegativos=0 preguntaNumero="ingrese un numero entero" for i in range(6): numero=int(input(preguntaNumero)) if (numero>0): sumaPositivo=sumaPositivo+numero cantidadPositivos=cantidadPositivos+1 else: sumaNegativos=sumaNegativos+numero print("suma de los negativos:",sumaNegativos) if (cantidadPositivos!=0): print("promedio de los positivos :",sumaPositivo/cantidadPositivos) else: print("No se ingresaron numeros negativos") #ejercicio 4 print("---ejercicio4 for---") listaCanciones=["relacion","hawai","caramelo","linda","mojaita"] sizeList =len (listaCanciones) for i in range(sizeList): print(listaCanciones[i]) import random cancionAleatoria = random.randint(0,4) print(f"se escogio esta cancion: {listaCanciones[cancionAleatoria]}")
2963c783f928e38349ddb886c76af12a3fa56955
DimitrijeKojic/IU7
/semester 1/Python Labs/lab-11/lab-11 — копия.py
10,629
3.6875
4
#Лабораторная работа № 11 #Имитировать работу базы данных, используя бинарный файл. #Запись содержит 3-4 поля. Например, запись "книга" содержит поля "автор", "наименование", "год издания". #Необходимо сделать меню: #1. Создание БД. #2. Добавление записи в БД. #3. Вывод всей БД. #4. Поиск записи по одному полю. #5. Поиск записи по двум полям. #Для работы с текущей записью используется словарь. import pickle as p choice = None database = {} print('__________МЕНЮ____________') print('1 - Создание БД.') print('2 - Добавления записи в БД.') print('3 - Вывод всей БД.') print('4 - Поиск записи по одному полю.') print('5 - Поиск записи по двум полям.') print('0 - Выход') while choice != '0': choice = input('Выбор: ') #----------------------------------------------- if choice == '1': k = 0 nameOfDatabase = input('Введите название БД: ') try: fileOfDatabase = open(nameOfDatabase + '.bin','rb') except FileNotFoundError: fileOfDatabase = open(nameOfDatabase + '.bin','wb') arrOfFileds = [] numberOfFields = int(input('Введите количество полей в записи: ')) for i in range(numberOfFields): print('Введите название', i+1, '-го поля: ', end='') nameOfField = input() arrOfFileds.append(nameOfField) print('БД "', nameOfDatabase, '" была создана.') k = 1 if k == 0: while True: answer = input('Перезаписать БД да/нет? ') if answer == 'да' or answer == 'y': fileOfDatabase = open(nameOfDatabase + '.bin','wb') database.clear() arrOfFileds = [] numberOfFields = int(input('Введите количество полей в записи: ')) for i in range(numberOfFields): print('Введите название', i+1, '-го поля: ', end='') nameOfField = input() arrOfFileds.append(nameOfField) print('БД "', nameOfDatabase, '" была пересоздана.') break elif answer == 'нет' or answer == 'n': break fileOfDatabase.close() #----------------------------------------------- elif choice == '2': try: fileOfDatabase = open (nameOfDatabase + '.bin','rb') except NameError: nameOfDatabase = input('Введите название БД: ') try: fileOfDatabase = open (nameOfDatabase + '.bin','rb') try: database = p.load(fileOfDatabase) except: database = {} except FileNotFoundError: print('БД с именем', nameOfDatabase, 'нет!') if fileOfDatabase != 0: fileOfDatabase.close() fileOfDatabase = open (nameOfDatabase + '.bin','wb') database_i = {} nameOfNotice = input('Введите название записи БД: ') while True: try: k = 0 except ValueError: k = 1 print('Ошибка ввода!') if k == 0: break for i in range(numberOfFields): print('Введите название', i+1, '-го поля: ', end='') nameOfField = input() print('Введите данные в поле "', nameOfField, '": ', end='') dataOfField = input() data = {nameOfField:dataOfField} database_i.update(data) database_i = {nameOfNotice:database_i} database.update(database_i) p.dump(database, fileOfDatabase) fileOfDatabase.close() #----------------------------------------------- elif choice == '3': k = 0 try: fileOfDatabase = open (nameOfDatabase + '.bin','rb') except NameError: nameOfDatabase = input('Введите название БД: ') except FileNotFoundError: nameOfDatabase = input('Введите название БД: ') try: fileOfDatabase = open (nameOfDatabase + '.bin','rb') try: database = p.load(fileOfDatabase) except: database = {} except FileNotFoundError: print('БД с именем', nameOfDatabase, 'нет!') k = 1 if database == {} and k == 0: print('БД пуста!') elif k == 0: print('---------------------------') for notice in database.keys(): print('Запись -', notice) data = database.setdefault(notice) for field in data.keys(): dataOfNotice = field + ': ' + data.setdefault(field) print(dataOfNotice) print('---------------------------') fileOfDatabase.close() else: k = 1 #----------------------------------------------- elif choice == '4': k = 0 try: fileOfDatabase = open (nameOfDatabase + '.bin','rb') except NameError: nameOfDatabase = input('Введите название БД: ') except FileNotFoundError: nameOfDatabase = input('Введите название БД: ') try: fileOfDatabase = open (nameOfDatabase + '.bin','rb') try: database = p.load(fileOfDatabase) except: database = {} except FileNotFoundError: print('БД с именем', nameOfDatabase, 'нет!') k = 1 if database == {} and k == 0: print('БД пуста!') elif k == 0: field_1 = input('Введите название искомого поля в записи: ') arrOfNotice = [] for notice in database.keys(): data = database.setdefault(notice) for field in data.keys(): if field == field_1: arrOfNotice.append(notice) if arrOfNotice == []: print('Записей с полем', field_1, ' нет.') else: b = 0 print('---------------------------') for notice in database.keys(): if notice == arrOfNotice [b]: if b < len(arrOfNotice) - 1: b += 1 data = database.setdefault(notice) print('Запись -', notice) for field in data.keys(): dataOfNotice = field + ': ' + data.setdefault(field) print(dataOfNotice) print('---------------------------') fileOfDatabase.close() #----------------------------------------------- elif choice == '5': k = 0 try: fileOfDatabase = open (nameOfDatabase + '.bin','rb') except NameError: nameOfDatabase = input('Введите название БД: ') except FileNotFoundError: nameOfDatabase = input('Введите название БД: ') try: fileOfDatabase = open (nameOfDatabase + '.bin','rb') try: database = p.load(fileOfDatabase) except: database = {} except FileNotFoundError: print('БД с именем', nameOfDatabase, 'нет!') k = 1 if database == {} and k == 0: print('БД пуста!') elif k == 0: while True: field_1 = input('Введите название искомого поля 1 в записи: ') field_2 = input('Введите название искомого поля 2 в записи: ') if field_1 != field_2: break else: print('Введено одно и тоже название поля!') arrOfNotice = [] for notice in database.keys(): data = database.setdefault(notice) for field in data.keys(): if field_1 in data.keys() and field_2 in data.keys(): arrOfNotice.append(notice) if arrOfNotice == []: print('Записей с полем', field_1, ' нет.') print('Записей с полем', field_2, ' нет.') else: b = 0 print('---------------------------') for notice in database.keys(): if notice == arrOfNotice [b]: if b < len(arrOfNotice) - 1: b += 1 data = database.setdefault(notice) print('Запись -', notice) for field in data.keys(): dataOfNotice = field + ': ' + data.setdefault(field) print(dataOfNotice) print('---------------------------') #----------------------------------------------- elif choice == '0': print('До свидания.') else: print('Команду', choice, 'нет !!!') print()
f802917eddced59013ef5cc73f8dac1bfd8fcfa8
ahmedabdulwhhab/SDN-RYU-Redundancy-STP
/custom_topo.py
1,446
3.703125
4
"""Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. sudo mn --custom custom_topo_00.py --topo mytopo --controller remote,ip=127.0.0.1 --switch ovsk,protocols=OpenFlow13 --mac --ipbase=192.168.1.0/24 """ from mininet.topo import Topo class MyTopo( Topo ): "Simple topology example." def build( self ): "Create custom topo." # Add hosts and switches h1 = self.addHost( 'h1',ip='192.168.1.21/24' ) h2 = self.addHost( 'h2',ip='192.168.1.22/24' ) s1 = self.addSwitch( 's1' ) s2 = self.addSwitch( 's2' ) # Add links self.addLink( h1, s1 ) self.addLink( h2, s1 ) self.addLink( h1, s2 ) self.addLink( h2, s2 ) #self.addLink( s1, s2 ) """ write these commands inside mininet manually h1 ip link set h1-eth1 down h1 ip link set h1-eth1 address 00:00:00:00:00:11 h1 ip addr add 10.1.0.2/24 dev h1-eth1 h1 ip link set h1-eth1 up h2 ip link set h2-eth1 down h2 ip link set h2-eth1 address 00:00:00:00:00:21 h2 ip addr add 10.1.0.3/24 dev h2-eth1 h2 ip link set h2-eth1 up """ topos = { 'mytopo': ( lambda: MyTopo() ) }
02609d6a1381d7416a720f739f87c66ce8e8c2ca
anoubhav/LeetCode-Solutions
/top_interview_questions/rotate_array.py
2,842
3.734375
4
def rotateArray(nums, k): n = len(nums) arr = [0]*n for i in range(n): arr[i] = nums[(i - k)%n] return arr def rotateArrayInPlaceBubbleSort(nums, k): # Used same logic as bubble sort. O(N^2) time complexity. TLE n = len(nums) period = k%n if period == 0: return nums count = 0 for i in range(n-period, n): for j in range(i, count, -1): nums[j], nums[j-1] = nums[j-1], nums[j] count += 1 return nums def gcd(a, b): if b == 0: return a return gcd(b, a%b) # faster than 100% python solution def rotateArrayInPlaceCyclicRotation(nums, k): # move elem i --> (i + k)%n. move elem at (i + k)%n to (i + 2k)% n and so on. Stop when you reach i again. Time complexity: O(N). First for loop is executed gcd(N, k) times. Second while loop processes N/(gcd(N, k)) elements and breaks. Thus each element is only processed once. n = len(nums) period = k%n if period == 0: return nums # if we did range(n) instead, it would shift to the right place midway..and shift it again back to normal location. We need to iterate only till the order we want is obtained. # if we have n elements and period k. e.g., n = 6 k= 2; # a b c d e f ---> (after 1st for loop) ---> x b x d x f ----> (after 2nd for loop iteration) x x x x x x. We should stop here, if we continue we will go from x, back to numbers. for i in range(gcd(n, period)): prev = nums[i] ind = i while True: nxtind = (ind + period) % n nums[nxtind], prev = prev, nums[nxtind] ind = nxtind if ind == i: # each iteration of the while loop, N/gcd(N, k) elements are shifted. So we repeat the outer loop gcd(N, k) times. break return nums def reverse(arr, start, end): while start<end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 return arr def rotateArrayInPlaceReverse(nums, k): # This approach is based on the fact that when we rotate the array k times, k elements from the back end of the array come to the front and the rest of the elements from the front shift backwards. # In this approach, we firstly reverse all the elements of the array. Then, reversing the first k elements followed by reversing the rest n−k elements gives us the required result. n = len(nums) k%=n if k == 0:return reverse(nums, 0, n-1) reverse(nums, 0, k-1) reverse(nums, k, n-1) return nums k = 3 arr = [1, 2, 3, 4, 5, 6, 7] print(rotateArray(arr.copy(), k)) print(rotateArrayInPlaceBubbleSort(arr.copy(), k)) print(rotateArrayInPlaceCyclicRotation(arr.copy(), k)) print(rotateArrayInPlaceReverse(arr.copy(), k))
46f8f3fd4b6a728a34a4deeac71d71972ae2d689
elminster19/python-
/线性结构/有效括号的另一种匹配思路.py
1,089
4.0625
4
''' 题目内容: 给定一个只包括 '(',')','{','}','[',']'的字符串,判断字符串是否有效。 有效字符串需满足: (1)左括号必须用相同类型的右括号闭合。 (2)左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 输入格式:一行字符串 输出格式:True或False,表示该输入是否为合法括号串 输入样例1:([]) 输出样例1:True ''' #使用字典的键值进行匹配检测 class Stack(list): def push(self,item): self.append(item) def peek(self): return self[-1] def isEmpty(self): return self == [] def size(self): return len(self) st = Stack() d = {"(": ")", "[": "]", "{": "}"} s = input() for a in s: if a in d.keys(): st.push(a) elif st.isEmpty() or not a == d[st.pop()]: # 右括号多出来或不匹配 print("False") break else: if st.isEmpty(): print("True") # 正好匹配 else: print("False") # 左括号多出来
7abe0132ed4e3b5486bb3bf04833f86e1db7d656
hoangminhhuyen/Python-buoi-2
/kiểm tra anagram.py
326
3.671875
4
def kiểm_tra(str1, str2): if sorted(str1)==sorted(str2): print('2 chuỗi này là anagram của nhau') else: print('2 chuỗi này không phải là anagram của nhau') kiểm_tra('Hello', 'eHlol') kiểm_tra('Mello', 'eHlol') kiểm_tra('Hello', 'eHcol') kiểm_tra('Hello', 'fHlol')
4e7c7b0b7070f6f1c2eaa416ea2633d5230fe2ba
Tiagoksio/estudandoPython
/exercicios002/descontosEAumentos.py
1,017
3.875
4
opcao = int(input('Informe a operação desejada:\n1 - Descobrir o percentual acrescentado ou deduzido de um certo valor\n2 - Acrescentar ou deduzir um percentual de um certo valor\n3 - Descobrir o valor total a partir de um valor parcial e seu percentual equivalente\n')) if opcao == 1: n1 = float(input('Informe o valor inicial: ')) n2 = float(input('Informe o valor com os acrescimos ou deduções: ')) print('A diferença percentual entre {} e {} é de {}%'.format(n1, n2, (n2-n1) / n1 * 100)) elif opcao == 2: n1 = float(input('Informe o valor inicial: ')) n2 = float(input('Informe o percentual sem o "%", que deseja aplicar: ')) print('O número {} com uma alteração de {}%, fica {}'.format(n1, n2, n2 / 100 * n1 + n1)) elif opcao == 3: n1 = float(input('Informe o valor parcial: ')) n2 = float(input('Informe o percentual do total que esse valor equivale: ')) print('O número {} equivale à {}%, de {}'.format(n1, n2, n2 * 100 / n1)) else: print('Opção inválida')
ee1b03284347f55b1f5cc919bb3713f88628280c
nhattieu/python-tutorial
/main.py
4,331
3.53125
4
from collections import OrderedDict # print('hello world') # day1 = ('monday', 'tuesday', 'wednesday') # day2 = ('thursday', 'friday', 'saturday' , 'sunday') # day3 = ('thursday', 'friday', 'saturday' , 'sunday', day1) # day = day1 + day2 # print('Day: ', end="") # print(day) # print(day3) # print(day3[1][0][0]) # a = 7 // 4.0 # print(type(a)) # from decimal import Decimal # print(Decimal(0.1 + 0.2)) # print(Decimal(0.3)) # myString = 'abcdefgh' # print(len(myString)) # print(myString[1:]) # print(myString[1:-1]) # print(myString[:]) # print(myString.split('h')) # my_list = ['g', 'i','a', 'h','b', 'e', 'c', 'd', 'e', 'f'] # print(my_list) # my_list.sort() # my_sorted_list = my_list # print(my_sorted_list) # print(my_list) # my_dict = {} # my_dict['key6'] = 600 # my_dict['key1'] = 100 # my_dict['key7'] = 700 # my_dict['key9'] = 900 # my_dict['key5'] = 500 # my_dict['key2'] = 200 # my_dict['key8'] = 800 # my_dict['key3'] = 300 # my_dict['key4'] = 400 # print(my_dict) # print(my_dict.items()) # print(my_dict.keys()) # print(my_dict.values()) # my_dict['key8'] = 800 # print(my_dict) # my_dict['key1'] = 1000 # print(my_dict) # for key, value in my_dict.items(): # print(key, value) # print("This is a Dict:\n") # d = {} # d['a'] = 1 # d['b'] = 2 # d['c'] = 3 # d['d'] = 4 # for key, value in d.items(): # print(key, value) # print("\nThis is an Ordered Dict:\n") # od = OrderedDict() # od['a'] = 1 # od['b'] = 2 # od['c'] = 3 # od['d'] = 4 # for key, value in od.items(): # print(key, value) # my_od = OrderedDict() # my_od['a'] = 100 # my_od['e'] = 500 # my_od['c'] = 300 # my_od['d'] = 400 # my_od['b'] = 200 # for key, value in my_od.items(): # print(key, value) # print("\nAfter:\n") # my_od['e'] = 5000 # for key, value in my_od.items(): # print(key, value) # print(my_od) # BOOLEAN # print(1 > 2) # print(0.1 == 0.1) # print((0.4 - 0.3) == 0.1) # b = None # print(None == b) # print(type(b)) # print(-False) # print(-True) # lap lai 3 ki tu trong chuoi def front3(str): front_end = 3 if len(str) < front_end: front = str * 3 return front else: front = str[0:front_end] return front * 3 # print(front3('as')) # dao 2 ki tu dau tien va cuoi cung def front_back(str): if len(str) < 2: return str else: firstChar = str[0] lastChar = str[-1] middleText = str[1:-1] result = lastChar + middleText + firstChar return result # print(front_back('asdasdasdasdqwettt')) # week is false or vacation is true thi return true, unless return false def sleep_in(week, vacation): if not week or vacation: return True else: return False # print(sleep_in(True, True)) # print(sleep_in(True, False)) # print(sleep_in(False, False)) # print(sleep_in(False, True)) # Co 2 con khi, cung cuoi hoac cung ko cuoi thi tra ve true, con ko thi tra ve false def monkey_trouble(a_smile, b_smile): if a_smile and b_smile: return True elif not a_smile and not b_smile: return True else: return False # print(monkey_trouble(True, True)) # print(monkey_trouble(True, False)) # print(monkey_trouble(False, False)) # print(monkey_trouble(False, True)) # cho 2 so nguyen, tinh tong cua chung, neu 2 so do giong y chang nhau thi tra ve x2 lan tong cua no def sum_double(a, b): result = 0 if a == b: result = (a + b) * 2 return result else: result = a + b return result # print(sum_double(5, 10)) # print(sum_double(100, 100)) # nhan zo 1 so nguyen n, tinh khoang cach tuyet doi giua n va so 21, neu n > 21 thi ra ve gap doi def diff21(n): result = 0 if n > 21: result = (n - 21) * 2 return result else: result = 21 - n return result # print(diff21(1)) # print(diff21(19)) # print(diff21(21)) # print(diff21(121)) # print(diff21(-1)) # co 1 con vet, tra ve true neu con vet dang noi va thoi gian no noi o khoang truoc 7h va sau 20h def parrot_trouble(talking, hour): if talking and (hour < 7 or hour > 20): return True else: return False print(parrot_trouble(True, 5)) print(parrot_trouble(False, 15)) print(parrot_trouble(True, 15)) print(parrot_trouble(False, 21)) print(parrot_trouble(True, 20))
6655b632cbfb0a1db97cc09e2666b9395c2155c5
saikatsahoo160523/python
/Ass9.py
305
4.34375
4
# 9. Define a function max_of_three() that takes three numbers as arguments and returns the largest of them. def max_of_three(a,b,c): imax=a if(b>imax) and (b>c): imax=b elif(c>imax): imax=c return imax print(max_of_three(4,5,6)) ''' OUTPUT : [root@python PythonPrograms]# python Ass9.py 6 '''
a5e80f3872deceac5c0f022f4b61f8ea8d2b9eca
acharist/python-mipt
/turtle/butterfly.py
644
4.21875
4
from turtle import Screen, Turtle import math screen = Screen() turtle = Turtle() turtle.shape('turtle') turtle.speed(10) def draw_circle(radius, dir): i = 0 angle = 10 length = 2 * math.pi * radius step = (length / 360) * angle while(i < 360): turtle.forward(step) turtle.right(angle) if dir == 0 else turtle.left(angle) i += angle def butterfly(n): radius = 50 i = 0 turtle.right(90) while(i < n): if((i + 1) % 3 == 0): radius += 10 n += 1 else: draw_circle(radius, i % 2) i += 1 butterfly(20) screen.mainloop()
b492cf9ef30249426121f0ee27a1c62fa01a9489
dheena18/python
/day8ex1and2.py
713
3.953125
4
first = float(input("first number:")) second = float(input("Second number:")) print("1.add 2.sub 3.multiply 4.division") try: operator=int(input("Option:")) if operator==1: print(first+second) elif operator==2: print(first-second) elif operator == 3: print(first*second) elif operator == 4: print(first/second) else: print("Enter a valid integer") except NameError: print("Please use number only") except SyntaxError: print("Please use number only") except TypeError: print("Please use number only") except AttributeError: print("Please use number only") except ValueError: print("Please use number only")
ec420be79d24d5140f9a3e4d78ff2e62e9bc0b65
shrader/algorithm-practice
/disemvowel.py
240
4.09375
4
def disemvowel(string): vowels = ['a','e','i','o','u','A','E','I','O','U'] string2 = [] for letter in string: if letter not in vowels: string2.append(letter) string2 = "".join(string2) return string2
5128494bcab6bd4c2a7240deec2ecc6239bec922
August1s/LeetCode
/Linked List/No206反转链表.py
644
4.125
4
# 迭代法 # 使用pre记录前一个节点,使用cur记录当前节点 def reverseList(self, head: ListNode) -> ListNode: pre, cur = None, head while cur: next = cur.next cur.next = pre pre = cur cur = next return pre # 利用栈 def reverseList(self, head: ListNode) -> ListNode: if not head or not head.next: return head L = [] while head: L.append(head) head = head.next newhead = L.pop() p = newhead p.next = None while L: temp = L.pop() p.next = temp temp.next = None p = temp return newhead
00c0436e9275bd53369665e9b13d0d027b94453a
saheb222/ds
/instertion_sort.py
238
3.6875
4
def selecttion_sort(a): for i in range(len(a)): point = i for j in range(i-1,-1,-1): if a[point]<a[j]: (a[point],a[j]) = (a[j],a[point]) point = j return a print (selecttion_sort([200,100,23,14,1,6,7,18,9,0,-5,-8,-100]))
62afe72ff02bd73cad852deb58dad5ba5d2a57e0
jringenbach/Pendu
/game.py
4,282
3.8125
4
# -*- coding: utf-8 -*- from word import Word from options import Options class Game: """Class that contains information of the different games that have been played.""" def __init__(self): #We initialize the attributes of Game class self.player = "" self.win = False self.endGame = False self._wordChosen = "" self.errorAllowed = 6 self._options = Options() # ----------------------------------------------------------------------- # GETTERS AND SETTERS # ----------------------------------------------------------------------- def _get_word_chosen(self): """ Getters for the word that has been chosen randomly""" return self._wordChosen def _set_word_chosen(self, wordChosen): """Setters for the word that has been chosen randomly""" self._wordChosen = wordChosen def _get_options(self): """Getters for the options of the game """ return self._options def _set_options(self, options): """Setters for the options of the game """ self._options = options options = property(_get_options, _set_options) wordChosen = property(_get_word_chosen, _set_word_chosen) # ----------------------------------------------------------------------- # FUNCTIONS # ----------------------------------------------------------------------- def checkEndGame(self): """We check if the player has won or not""" if self.errorAllowed == 0: endGame = True def checkLose(self): """ We check if the player has lost by checking if the number of errors allowed left is equal to 0""" playerLose = False if self.errorAllowed == 0: playerLose = True return playerLose def checkWin(self): """We check every argument in letter discovered. If each of them is set to true, then it means the player has won""" letterDiscovered = self._get_word_chosen()._get_letter_discovered() playerWins = True for statusLetter in letterDiscovered: if statusLetter == False: playerWins = False return playerWins def endGameMessage(self): """Display the endgame message depending if the player has won or not """ if self.win == True: print("Vous avez gagné!") else: print("Vous avez perdu!") def play(self): """function where the game is happening """ letterFound = False self._get_word_chosen().displayWord() letterChosen = self.player.choseALetter() letterFound = self._get_word_chosen().checkLetterInWord(letterChosen) if letterFound == False: self.errorAllowed = self.errorAllowed - 1 print("Il vous reste "+str(self.errorAllowed)+" essais") #We check if the player has won or lost the game if self.checkWin() == False: if self.checkLose() == True: self.endGame = True else: self.win = True self.endGame = True def replay(self, optionSelected): """Select the right action depending on what the player has selected in the replay options at the endgame""" if optionSelected == "1": self._get_options()._set_pseudo_options(False) self._get_options()._set_difficulty_options(False) self._get_options()._set_play_again(True) elif optionSelected == "2": self._get_options()._set_pseudo_options(True) self._get_options()._set_difficulty_options(True) self._get_options()._set_play_again(True) elif optionSelected == "3": self._get_options()._set_pseudo_options(False) self._get_options()._set_difficulty_options(True) self._get_options()._set_play_again(True) else: self._get_options()._set_play_again(False) def resetGame(self): """Reset the attributes of the game """ self.win = False self.endGame = False self.errorAllowed = 6
49f22133741c23bdec6d6500fffcb868f113fa09
MdNoorr/python-projects
/password-scanner.py
583
3.6875
4
import random add = "@2019", "123.", ".234", "@abc", "_2018", "()2000", "+0000", "@new", "<bd>", ":001", "read;" s = "@", "_", ":", ";", "()", "{}", "[]", "-", "^", "#", "/", "%", "?", ".""=", "!", ",", "$", "&", "¡" char = str(input("Enter Your Password : ")) print("=" * 38, '\n', "The input :", char) count = 0 sp = 0 for i in char: count = count + 1 for j in s: if j == i: sp = sp + 1 if count > 7 or sp > 0: print("The password is strong.") else: print("The password is weak.") print("Suggested password :") print(char + (random.choice(add)))
f382e05c11fd5d430a7abdc60847748a5bceb840
namntran/2021_python_principles
/13_line.py
122
3.90625
4
# line.py # Print a line of hashes n = int(input("Enter a number: ")) for i in range(n): print("#", end = "") print()
a661ed1dcfd84987631d2afb12df0958aac60a9d
danrasband/coding-experiment-reviews
/responses/9SNKCW-X7G/1_count_of_largest_integer.py
403
3.59375
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python if len(A) == 0: return 0 max_int = A[0] max_cnt = 1 for i in range(1, len(A)): if A[i] > max_int: max_int = A[i] max_cnt = 1 elif A[i] == max_int: max_cnt += 1 return max_cnt
e6ce24caea6c3300a503caeae4a2ed587061307c
Kalibanizm/Learn_python_otus
/homework_02/base.py
838
3.671875
4
from abc import ABC from homework_02 import exceptions class Vehicle(ABC): weight = 2500 started = False fuel = 100 fuel_consumption = 1 def __init__(self, weight, fuel, fuel_consumption): self.weight = weight self.fuel = fuel self.fuel_consumption = fuel_consumption def start(self): if self.started is False and (self.fuel > 0): self.started = True return self.started elif self.started is True and (self.fuel > 0): return self.started else: raise exceptions.LowFuelError def move(self, journey): need_fuel = self.fuel_consumption * journey if self.fuel >= need_fuel: self.fuel -= need_fuel return self.fuel else: raise exceptions.NotEnoughFuel
459b4b134a0fef15e335512d031e13d76c4c6597
koshimitzuWen/HWSET1
/hw1_3.py
136
4.0625
4
number = int(input("Please input an integer: ")) x = 0 sum = 0 for n in range(0, number + 1): sum = sum + x x = x + 1 print(sum)
07ee4fa09f93724df9cafe689ddf071c6170a68d
ys0823/python-100examples
/100 examples/67.py
1,183
4.09375
4
#----------------------------------------------------- #题目:一个商城在搞抽奖的活动,需要在搞活动的宣传单上印刷优惠卷的验证码, # 验证码规定20位,生成100个 #2018-8-24 #----------------------------------------------------- import random import string forSelect = string.ascii_letters + string.digits #string用法 def generate_code(count, length): ra = '' for x in range(count): Re = '' for y in range(length): Re = random.choice(forSelect) #随机选取一个字符 #print('Re is:%s'%Re) ra += Re #print('rais:%s'%ra) return ra if __name__ =='__main__': for i in range(100): count = generate_code(20,20) print(count) ''' import random import string forSelect = string.ascii_letters + string.digits def generate_code(length): ra = '' for y in range(length): #re = '' Re = random.choice(forSelect) #随机选取一个字符 #print('Re is:%s'%Re) #print('rais:%s'%ra) ra += Re return ra if __name__ =='__main__': for i in range(100): count = generate_code(20) print(count) '''
4f8bf56053b0032f435374ee3817850bba6024d8
KornSiwat/final-com-pro-1
/paruj/final_obj_template.py
2,071
4.375
4
import datetime class Person: def __init__(self, name): """Create a person""" name = name.split(' ') self.__name = name[0] if len(name) == 3: self.__midname = name[1] self.__lastname = name[2] else: self.__midname = '' self.__lastname = name[1] self.__birthdate = '' def getName(self): """Returns self's full name""" if self.__midname != '': return f'{self.__name} {self.__midname} {self.__lastname}' else: return f'{self.__name} {self.__lastname}' def getLastName(self): """Returns self's last name""" return self.__lastname def setBirthday(self, birthdate): """Assumes birthdate is of type datetime.date Sets self's birthday to birthdate""" self.__birthdate = birthdate def getBirthday(self): """Assumes birthdate is of type datetime.date Sets self's birthday to birthdate""" return f'{self.__birthdate.year}-{self.__birthdate.month:02}-{self.__birthdate.day:02}' def getAge(self): """Returns self's current age in years""" today_date = datetime.date.today() year_now = today_date.year return year_now - self.__birthdate.year def __str__(self): """Returns self's name and birthday""" return f'{self.__name} {self.__lastname} {self.getBirthday()}' today_date = datetime.date.today() print(today_date) print(today_date.day, today_date.month, today_date.year) me = Person('Frederick Brooks') him = Person('Barack Hussein Obama') her = Person('Barbara Jane Liskov') me.setBirthday(datetime.date(1931, 4, 19)) him.setBirthday(datetime.date(1961, 8, 4)) her.setBirthday(datetime.date(1939, 11, 7)) print(me) print(him) print(her) print(me.getLastName()) print(him.getLastName()) print(her.getLastName()) print(me.getName(), 'is', me.getAge(), 'years old') print(him.getName(), 'is', him.getAge(), 'years old') print(her.getName(), 'is', her.getAge(), 'years old')
3b2180bc1bbeec35e25d9fecace029cc0418954a
Tagliacollo/lagrangeplus
/lagrange/decimalarray.py
722
3.65625
4
from decimal import * class DecimalArray (list): def __init__(self, listOfNumbers): junk = map( self.append, map(Decimal, listOfNumbers) ) def __add__(self, b): ret = DecimalArray(self) for i, a in enumerate(self): ret[i] = a + b[i] return ret #def __mul__(self, b): #ret = DecimalArray(self) #for i, a in enumerate(self): #ret[i] = a * b[i] #return ret def __mul__(self,b): ret = list() for i,a in enumerate(self): ret.append( a * b[i] ) return ret if __name__ == "__main__": a = DecimalArray([1,2,3]) b = a + a print b c = b * b print c print sum(c)
78d66434a019185859557b775bbbcdf088bd598e
nicooris98/modelos-y-simulacion-tp2
/p4.py
341
3.515625
4
def gen_congruencial(a, m, x0, c=0):# En multiplicativo c=0 #mostrara 20 numeros if c==0: print("Generador Multiplicativo") else: print("Generador Mixto") for i in range(1,21): x=(a*x0+c)%m print("Num"+str(i)+": "+str(x)) x0=x gen_congruencial(5, 8, 4, 7) gen_congruencial(3, 100, 51)
146d434ea541c336e38f73e589fe94b60e5fe45e
combobulate/180DA-WarmUp
/week0/test.py
526
3.921875
4
import random as r if __name__ == '__main__': #x = "ECE_180_DA_DB" #if x == "ECE_180_DA_DB": # print("You are living in 2017") #else: # # this is a comment # x = x + " - Best class ever" # print(x) val = int(input("Enter the number of random letters to generate: ")) out = "" for i in range(val): out = out + chr(r.randrange(97,122)) print("The new word we've created for you is: " + out) print("Use it in a sentence to impress all of your friends!")
2096d4cfa6f6891d1dd5ab2819253fa6d238a213
mhaidarhanif/crypto-text
/encode.py
623
3.765625
4
#!/usr/bin/env python from lib.encrypt import * def main(): filename = raw_input("[?] Enter text file name: ") output = raw_input("[?] Enter output text file name: ") key = input("[?] Enter the key number (0-9): ") file = open(str(filename), 'r') text = file.read() file.close() encrypted = scytale_encrypt(text, key) encrypted = jefferson_encrypt(encrypted) print "[i] Text: \n %s \n" % (text) print "[i] Encrypted: \n %s \n" % (encrypted) file = open(str(output), 'w') file.write(encrypted) file.close() if __name__ == '__main__': main()
a915016d3cd3f3459abc9113830ba6f915c1fc23
magicpieh28/leetcode
/125_isPalindrome.py
388
3.78125
4
class Solution: def isPalindrome(self, s): self.s = s s = [i.lower() for i in s if i.isalnum()] bools = [] if not s: return True else: for (i, j) in zip(s, s[::-1]): if i == j: bools.append(True) else: return False if bools: return True is_pal = "A man, a plan, a canal: Panama" not_pal = "race a car" sol = Solution() sol.isPalindrome(not_pal)
84c1ef9c0787d527e839d749a6912f6fc80b78f2
sourav9064/coding-practice
/coding_18.py
3,256
3.796875
4
##A City Bus is a Ring Route Bus which runs in circular fashion.That is, Bus once starts at the Source Bus Stop, halts at each Bus Stop in its Route and at the end it reaches the Source Bus Stop again. ##If there are n number of Stops and if the bus starts at Bus Stop 1, then after nth Bus Stop, the next stop in the Route will be Bus Stop number 1 always. ##If there are n stops, there will be n paths.One path connects two stops. Distances (in meters) for all paths in Ring Route is given in array Path[] as given below: ##Path = [800, 600, 750, 900, 1400, 1200, 1100, 1500] ##Fare is determined based on the distance covered from source to destination stop as Distance between Input Source and Destination Stops can be measured by looking at values in array Path[] and fare can be calculated as per following criteria: ## ##If d =1000 metres, then fare=5 INR ##(When calculating fare for others, the calculated fare containing any fraction value should be ceiled. For example, for distance 900n when fare initially calculated is 4.5 which must be ceiled to 5) ##Path is circular in function. Value at each index indicates distance till current stop from the previous one. And each index position can be mapped with values at same index in BusStops [] array, which is a string array holding abbreviation of names for all stops as- ##“THANERAILWAYSTN” = ”TH”, “GAONDEVI” = “GA”, “ICEFACTROY” = “IC”, “HARINIWASCIRCLE” = “HA”, “TEENHATHNAKA” = “TE”, “LUISWADI” = “LU”, “NITINCOMPANYJUNCTION” = “NI”, “CADBURRYJUNCTION” = “CA” ## ##Given, n=8, where n is number of total BusStops. ##BusStops = [ “TH”, ”GA”, ”IC”, ”HA”, ”TE”, ”LU”, ”NI”,”CA” ] ## ##Write a code with function getFare(String Source, String Destination) which take Input as source and destination stops(in the format containing first two characters of the Name of the Bus Stop) and calculate and return travel fare. ## ##Example 1: ##Input Values ##ca ##Ca ## ##Output Values ##INVALID OUTPUT ## ##Example 2: ##Input Values ##NI ##HA ##Output Values ##23.0 INR ## ##Note: Input and Output should be in format given in example. ##Input should not be case sensitive and output should be in the format INR import math def getFare(source,destination): route=[[ "TH", "GA", "IC", "HA", "TE", "LU", "NI","CA" ],[800, 600, 750, 900, 1400, 1200, 1100, 1500]] fare = 0.0 if not (source in route[0] and destination in route[0]): print("INVALID INPUT") exit() if route[0].index(source) < route[0].index(destination): for i in range(route[0].index(source),route[0].index(destination)+1): fare += route[1][i] elif route[0].index(destination) < route[0].index(source): for i in range(route[0].index(source)+1,len(route[0])): fare += route[1][i] for i in range(0, route[0].index(destination)+1): fare += route[1][i] return float(math.ceil(fare*.005)) source = input() destination = input() fare = getFare(source,destination) if fare == 0: print("INVALID INPUT") exit() else: print(fare)
75b1df679909578fd64bf9b48727fc68024f58ef
eroicaleo/LearningPython
/interview/leet/56_Merge_Intervals.py
718
3.625
4
#!/usr/bin/env python class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: def merge(self, intervals): ret = [] sorted_intervals = sorted(intervals, key=lambda iv: iv.start) for iv in sorted_intervals: if not ret or ret[-1].end < iv.start: ret.append(iv) else: ret[-1].end = max(ret[-1].end, iv.end) return ret intervals = [[1,4],[4,5]] intervals = [[1,3],[2,6],[8,10],[15,18]] intervals = [[8,10],[2,6],[1,3],[15,18]] # [[1,6],[8,10],[15,18]] sol = Solution() print([[iv.start, iv.end] for iv in sol.merge([Interval(iv[0], iv[1]) for iv in intervals])]) # [[1,5]]
16a048fd1bb1536b3ca63dfe895f69bc5af6a16b
chenrb/python-data-structure
/5_sort/冒泡排序.py
1,256
4.0625
4
# -*- coding:utf-8 -*- __author__ = 'John 2017/11/17 9:57' """ 冒泡排序需要多次遍历列表。它比较相邻的项并交换那些无序的项。每次遍历列表将下一个 最大的值放在其正确的位置。实质上,每个项“冒泡”到它所属的位置。 """ def short_bubble_sort1(alist): """ for循环 :param alist: :return: """ passnum = len(alist) for i in range(passnum): exchanges = False for j in range(passnum-1-i): if alist[j] > alist[j+1]: alist[j], alist[j+1] = alist[j+1], alist[j] exchanges = True if not exchanges: return alist return alist def short_bubble_sort2(alist): """ while循环 :param alist: :return: """ exchanges = True passnum = len(alist)-1 while passnum > 0 and exchanges: exchanges = False for i in range(passnum): if alist[i] > alist[i+1]: alist[i], alist[i+1] = alist[i+1], alist[i] exchanges = True passnum -= 1 alist1=[20,30,40,90,50,60,70,80,100,110] alist2=[20,30,40,90,50,60,70,80,100,110] short_bubble_sort1(alist1) short_bubble_sort2(alist2) print(alist1) print(alist2)
c4a1f527a0afb00b05b3766cc7a6ef6381cd7ada
priyankaramachandra/python_programs
/28.py
362
4.1875
4
# Implement a progam to convert the input string to inverse case(upper->lower, lower->upper) ( without using standard library) str=input("enter a string\n") res='' res1='' for char in str: if ord(char)>=97 and ord(char)<=122: result=ord(char) - 32 res1=chr(result) res=res+res1 else: result=ord(char) + 32 res1=chr(result) res=res+res1 print(res)
6a506fce179af5e54c580f95f48689a44d7ab0e6
towerjoo/CS-notes
/gae/lib/django/tests/modeltests/get_or_create/models.py
1,554
4.15625
4
""" 33. get_or_create() get_or_create() does what it says: it tries to look up an object with the given parameters. If an object isn't found, it creates one with the given parameters. """ from django.db import models class Person(models.Model): first_name = models.CharField(maxlength=100) last_name = models.CharField(maxlength=100) birthday = models.DateField() def __str__(self): return '%s %s' % (self.first_name, self.last_name) __test__ = {'API_TESTS':""" # Acting as a divine being, create an Person. >>> from datetime import date >>> p = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)) >>> p.save() # Only one Person is in the database at this point. >>> Person.objects.count() 1 # get_or_create() a person with similar first names. >>> p, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)}) # get_or_create() didn't have to create an object. >>> created False # There's still only one Person in the database. >>> Person.objects.count() 1 # get_or_create() a Person with a different name. >>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)}) >>> created True >>> Person.objects.count() 2 # If we execute the exact same statement, it won't create a Person. >>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)}) >>> created False >>> Person.objects.count() 2 """}
1d0f2b65ee17dd769587db631fb3a3eb84aaf696
Marc2540/Small-scripts-and-code-snippets
/Pig Latin Translator.py
545
3.859375
4
#Created in python 3.3.0 #Created by Marc2540, guide from codeacademy.com pyg = 'ay' original = input('Enter a word:') if len(original) > 0 and original.isalpha(): #print original #debugging word = original.lower() first = word[0] if word[0] in ['a','e','i','o','u']: #print ('vowel') #debugging new_word=original + pyg print (new_word) else: #print ('consonant') #debugging new_word=word[1:]+word[0]+pyg print (new_word) else: print ('Try again, you wrote something invalid.')
efbedc2c47e31edfcd763399cca856587d540984
Raihan-Muzzammil/QR---Code-and-Decode
/Decode.py
519
3.65625
4
import cv2 # OpenCV is a library with a vast number of built in function that are yet to be explored. # Today I will be sticking with the theme of QRCodes and make a QRCode Decoder. # We Assign a function to a new variable. Decode = cv2.QRCodeDetector() # We create a new variable to display the result of the QR Code. # Here the underscores are used to avoid unwanted outputs. Decoded, _, _ = Decode.detectAndDecode(cv2.imread("textQR.jpg")) # We print the Code. print("Decoded Text is : ", Decoded)
8d759670234bfa76982a36446204b2e09985c948
SmischenkoB/campus_2018_python
/Ruslan_Neshta/4/MapGenerator.py
1,456
4.21875
4
from random import randint def fill_the_map(world, size, amount_of_items, item): """ Fills map with given amount of items :param world: map to fill :param size: maps size :param amount_of_items: amount of items to spawn :param item: item to spawn :return: nothing :rtype: None """ i = 0 while i < amount_of_items: x = randint(0, size - 1) y = randint(0, size - 1) if world[x][y] == item: continue else: world[x][y] = item i += 1 def generate(size, empty=' ', trap='#', treasure='@'): """ Generates map: size per size squares with size*size / 10 traps and size*size / 20 treasures :param size: number of squares :param empty: string that defines empty field :param trap: string that defines trap :param treasure: string that defines treasure :return: map with traps and treasures :rtype: list """ world = [[empty for i in range(size)] for i in range(size)] amount_of_traps = size * size / 10 amount_of_treasures = size * size / 20 fill_the_map(world, size, amount_of_traps, trap) fill_the_map(world, size, amount_of_treasures, treasure) return world if __name__ == "__main__": game_map = generate(3) print(game_map) game_map = generate(5) print(game_map) game_map = generate(10) print(game_map) game_map = generate(15) print(game_map)
f16bea6e993ce96f6eaf2426046b383363c08a78
nir20ane/Python
/leetcode/LinkedLists/SplitLinkedListinParts.py
2,979
3.875
4
"""** Split Linked List in Parts * Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts". * The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. * This may lead to some parts being null. * The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later. * Return a List of ListNode's representing the linked list parts that are formed. * Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ] * * Example 1: Input: root = [1, 2, 3], k = 5 Output: [[1],[2],[3],[],[]] * Explanation: * The input and each element of the output are ListNodes, not arrays. * For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null. * The first element output[0] has output[0].val = 1, output[0].next = null. * The last element output[4] is null, but it's string representation as a ListNode is []. * * Example 2: Input: root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3 Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] * Explanation: * The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. * Note: * The length of root will be in the range [0, 1000]. * Each value of a node in the input will be an integer in the range [0, 999]. * k will be an integer in the range [1, 50]. * Time complexity = O(N+k) * Space complexity = O(k) *""" class SplitLinkedListinParts(object): def __init__(self): self.head = None def split(self, root, k): curr = root length = 0 while curr: length += 1 curr = curr.next # calculate length curr = root width = length//k remain = length % k # calc width and remaining splits = [] for i in range(k): head = curr if i < remain: val = width + 1 - 1 # calculate val based on width else: val = width + 0 - 1 for j in range(val): if curr is not None: curr = curr.next # iterate curr if curr is not None: prev = curr # make prev point to curr, increment curr curr = curr.next # This is needed as head will now point to prev and the nodes following it prev.next = None splits.append(head) # incremented curr will become new head in next i iteration return splits class Node(object): def __init__(self, data=None): self.data = data self.next = None list1 = SplitLinkedListinParts() list1.head = Node(0) e2 = Node(1) e3 = Node(2) e4 = Node(3) list1.head.next = e2 e2.next = e3 e4.next = None split = list1.split(list1.head, 2) for s in split: print(s.data)
63ce624bda5219eaf9c9c54f6f4295e478350a59
weak-head/leetcode
/leetcode/p0121_best_time_to_buy_and_sell_stock.py
2,214
4.3125
4
from typing import List def maxProfit(prices: List[int]) -> int: """ Kadane's algorithm https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane's_algorithm Time: O(n) Space: O(1) """ min_price = float("inf") max_profit = 0 for price in prices: min_price = min(min_price, price) max_profit = max(max_profit, price - min_price) return max_profit def maxProfit_dp(prices: List[int]) -> int: """ Dynamic Programming Each day has the two possible states: - we hold stock - we don't hold the stock If we hold the stock, it means that we either had it yesterday, or we bought it today. If we dont hold the stock, we either didn't have it yesterday, or we sold it today. Time: O(n) Space: O(n) """ n = len(prices) dp = [None] * (n + 1) dp[0] = (0, float("-inf")) # (don't have stock, have stock) # days are shifted related to prices # so we refer 'prices[day - 1]' for day in range(1, n + 1): # today we dont hold the stock if we had no stock yesterday, # of we have sold the stock today dont_hold = max(dp[day - 1][0], dp[day - 1][1] + prices[day - 1]) # today we hold the stock if we had stock yesterday, # of we have bought the stock today hold = max(dp[day - 1][1], -prices[day - 1]) dp[day] = (dont_hold, hold) return dp[n][0] def maxProfit_dp_optimized(prices: List[int]) -> int: """ Dynamic Programming Similar to the previous solution, but optimized for memory. And with this optimization it looks exactly like Kadene's algorithm. Time: O(n) Space: O(1) """ n = len(prices) prev_dont, prev_do = 0, float("-inf") for day in range(n): # today we dont hold the stock if we had no stock yesterday, # of we have sold the stock today dont_hold_today = max(prev_dont, prev_do + prices[day]) # today we hold the stock if we had stock yesterday, # of we have bought the stock today hold_today = max(prev_do, -prices[day]) prev_dont, prev_do = dont_hold_today, hold_today return prev_dont
1d284b90fe24f20fc5d2cb7b4263cab4a4fee6ff
guojoanna/Maptimize
/Code/histogram.py
617
3.640625
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 9 20:31:52 2017 @author: dariu """ import matplotlib.pyplot as plt from conversion_list import convert_list population = convert_list('histogram',1) population = [float(x) for x in population] transit_time = convert_list('histogram',0) transit_time = [float(y) for y in transit_time] plt.bar(transit_time,population,align='center', alpha=0.5,width=50) plt.xlabel('Transit Time (sec)') plt.ylabel('Population (people)') plt.title('Transit times to nearest health centers for people without vehicles') plt.show() plt.savefig('histogram.png')
0a143ba8616e10aeed18338e88393dc9eccdfdae
paulinho-16/MIEIC-FPRO
/REs/RE03/LadosEstrela/start.py
389
4.03125
4
import turtle campo=turtle.Screen() campo.bgcolor('blue') tartaruga=turtle.Turtle() tartaruga.color('white') tartaruga.shape('circle') tartaruga.pensize(3) lados=int(input('Introduza o número de lados da estrela: ')) angulo=float(360/lados) for n in range(lados): tartaruga.forward(150) tartaruga.stamp() tartaruga.backward(150) tartaruga.right(angulo) campo.exitonclick()
928a3f2c941bb3f5ee596511961ffe1929bc0b07
dmf24/cra
/mining/get_longest_and_shortest.py
1,743
3.78125
4
import sys # Get longest sequence and put into displayable string def get_longest(stream): stream.seek(0, 0) lstring = 'Longest Sequence: \n' line = stream.readline() maximum = 0 # FIND MAXIMUM while line: if line[0] == '>' and maximum < int(line[line.rfind("length=") + 7:-1]): maximum = int(line[line.rfind("length=") + 7:-1]) line = stream.readline() # SEEK BEGINNING stream.seek(0, 0) # GET MORE INFO ON IT line = stream.readline() while line: if line[0] == '>' and int(line[line.rfind("length=") + 7:-1]) == maximum: lstring += line break line = stream.readline() return lstring # Get shortest sequence and put into displayable string def get_shortest(stream): stream.seek(0, 0) sstring = 'Shortest Sequence: \n' line = stream.readline() minimum = sys.maxint # FIND MINIMUM while line: if line[0] == '>' and minimum > int(line[line.rfind("length=") + 7:-1]): minimum = int(line[line.rfind("length=") + 7:-1]) line = stream.readline() # SEEK BEGGINING stream.seek(0, 0) # GET MORE INFO ON IT line = stream.readline() while line: if line[0] == '>' and int(line[line.rfind("length=") + 7:-1]) == minimum: sstring += line break line = stream.readline() return sstring input_file = sys.argv[1] output_file = sys.argv[2] longest = '' shortest = '' # INPUT with open(input_file, "r") as stream_in: longest = get_longest(stream_in) shortest = get_shortest(stream_in) # OUTPUT with open(output_file, "w") as stream_out: stream_out.write(longest) stream_out.write(shortest)
1734369039e62b1d949b46ff61e7fbe85c74f599
AMunkyCoder/pylenin_course
/daily_py/day_10/q1.py
125
3.859375
4
# Write a Python program to check if a set contains one or more items that are False. x = {1, 0, True, False} print(any(x))
3ed06b4beb8274e9ed43cfa059ab5529ab990b5e
pushkarparanjpe/practical-rl
/MountainCar/base/expt.py
7,794
3.796875
4
import gym import numpy as np from collections import deque from matplotlib import pyplot as plt class BaseExperiment(object): """ Experiment to train a reinforcement-learning agent that learns using a table of Q-values. Agent is a car. Goal is to climb the mountain and reach the flag. Following is the set of actions: action = 0 # PUSH LEFT action = 1 # DO NOTHING action = 2 # PUSH RIGHT Ref.: https://pythonprogramming.net/q-learning-reinforcement-learning-python-tutorial/ """ # Settings : # ---------- # Settings for discret-ising (binning) the observed continuous state values OBS_BIN_COUNTS = [20, 20] # State is 2-dimensional (position, velocity) # Settings for Q-Learning LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 10_000 # Settings for exploration # In initial episodes, epsilon has a high value --> low probability greedy-action-selection # But in later episodes, epsilon will have a low value --> high probability of greedy-action-selection epsilon = 1 START_EPSILON_DECAYING = 1 END_EPSILON_DECAYING = EPISODES // 2 # Settings for rendering, stats SHOW_EVERY = 1000 STATS_EVERY = 100 def __init__(self): # Create the gym environment for the "MountainCar" task self.env = gym.make("MountainCar-v0") print("HIGH", self.env.observation_space.high) print("LOW", self.env.observation_space.low) print("n actions", self.env.action_space.n) self.OBS_BIN_WIDTHS = (self.env.observation_space.high - self.env.observation_space.low) / self.OBS_BIN_COUNTS print("OBS BUCKETS BIN WIDTHS", self.OBS_BIN_WIDTHS) # Randomly init the Q-table self.q_table = np.random.uniform( low=-2, high=0, size=(*self.OBS_BIN_COUNTS, self.env.action_space.n) ) print("Q Table shape: ", self.q_table.shape) # Settings for exploration self.EPSILON_DECAY_VALUE = self.epsilon / (self.END_EPSILON_DECAYING - self.START_EPSILON_DECAYING) # Accessories for stats self.achieved_rewards = deque(maxlen=self.STATS_EVERY) self.stats = {'ep': [], 'min': [], 'avg': [], 'max': []} # Helper function that discreti-ses continuous state values to discrete values def get_discrete_state(self, state): discrete_state = (state - self.env.observation_space.low) / self.OBS_BIN_WIDTHS return tuple(discrete_state.astype(np.int32)) def init_episode_state(self): # Default Init : places the agent in the env # at a random position and having random velocity discrete_state = self.get_discrete_state(self.env.reset()) return discrete_state def choose_action(self, discrete_state): # Scheduled epsilon-greedy strategy if np.random.random() > self.epsilon: # [EXPLOIT] # Choose the best action for # this particular discrete state action = np.argmax(self.q_table[discrete_state]) else: # [EXPLORE] # Choose a random action action = np.random.randint(0, self.env.action_space.n) return action def do_scheduled_epsilon_update(self, episode): # Decay the epsilon according to the schedule if self.START_EPSILON_DECAYING <= episode <= self.END_EPSILON_DECAYING: self.epsilon -= self.EPSILON_DECAY_VALUE def do_scheduled_learning_rate_update(self, episode): # TODO : impl update to learning_rate pass def play_episode(self, episode): # Acquire the initial state for this episode discrete_state = self.init_episode_state() # Variable to indicate: Has the episode completed ? done = False # Init the episode reward to 0 episode_reward = 0 # Render SHOW_EVERY'th episode only render = True if (episode % self.SHOW_EVERY == 0) else False # Loop over all steps of this episode while not done: # Choose an action action = self.choose_action(discrete_state) # Step the env new_state, reward, done, _ = self.env.step(action) # Discret-ise the new state new_discrete_state = self.get_discrete_state(new_state) # Update the Q-value for (current state, chosen action) # ----------------------------------------------------------------- # Unpack the new_state pos, vel = new_state if pos < self.env.goal_position: # MountainCar did not reach the goal flag # Current Q value for this particular (state, taken action) current_q = self.q_table[discrete_state + (action,)] # Max possible Q value by actioning from the future state max_future_q = np.max(self.q_table[new_discrete_state]) # Calculate the new Q value for this particular (state, taken action) # Ref.: https://pythonprogramming.net/static/images/reinforcement-learning/new-q-value-formula.png new_q = (1 - self.LEARNING_RATE) * current_q \ + self.LEARNING_RATE * (reward + self.DISCOUNT * max_future_q) else: # MountainCar made it to / past the goal flag ! # We got the max possible reward (at any step) i.e. 0 new_q = 0 # Update the q_table self.q_table[discrete_state + (action,)] = new_q # ----------------------------------------------------------------- # Accumulate reward for stats episode_reward += reward # Did this episode complete ? if done: # Collect total reward for this episode for stats self.achieved_rewards.append(episode_reward) # Set new discrete state as the current discrete state discrete_state = new_discrete_state # Render if it is the SHOW_EVERY'th episode if render: self.env.render() def agg_stats(self, episode): if episode % self.STATS_EVERY == 0: self.stats['ep'].append(episode) min_ = np.min(self.achieved_rewards) max_ = np.max(self.achieved_rewards) avg_ = np.mean(self.achieved_rewards) self.stats['min'].append(min_) self.stats['max'].append(max_) self.stats['avg'].append(avg_) print(f"Stats: ep {episode} , min {min_} , max {max_} , avg {avg_}") def train(self): # Loop over all episodes for episode in range(self.EPISODES): # Update epsilon self.do_scheduled_epsilon_update(episode) # Update learning rate self.do_scheduled_learning_rate_update(episode) # Run the intra-episode loop self.play_episode(episode) # Agg stats self.agg_stats(episode) # Close the gym env self.env.close() def viz_stats(self): # Viz stats plt.style.use('ggplot') plt.plot(self.stats['ep'], self.stats['min'], label='min rewards') plt.plot(self.stats['ep'], self.stats['max'], label='max rewards') plt.plot(self.stats['ep'], self.stats['avg'], label='avg rewards') plt.ylabel("agg rewards") plt.xlabel("episodes") plt.title(self.__class__.__name__) plt.legend(loc=0) plt.savefig(f"charts/stats_{self.__class__.__name__}", dpi=90) plt.show() def run(self): self.train() self.viz_stats() if __name__ == '__main__': expt = BaseExperiment() expt.run()
6ee9c7a8bb82b07df85a9487a6bb6f44afa06a34
narc0tiq/scratch
/heapsort.py
978
3.859375
4
a = [12, 3, 44, 98, 4, 59, 85] def heapify(a): count = len(a) start = (count - 2) / 2 while start >= 0: sift_down(a, start, count-1) start -= 1 def sift_down(a, start, end): root = start while 2*root + 1 <= end: child = 2*root + 1 swap = root if a[swap] < a[child]: swap = child if child+1 <= end and a[swap] < a[child+1]: swap = child + 1 if swap is not root: do_swap(a, root, swap, 'heapify') root = swap else: return def heapsort(a): print "%r initial condition" % a heapify(a) end = len(a) - 1 while end > 0: do_swap(a, 0, end, 'put the maximum at the end') end -= 1 sift_down(a, 0, end) def do_swap(a, left, right, note=''): a[left], a[right] = a[right], a[left] print "%r after swap(%d, %d): %s" % (a, left, right, note) if __name__ == '__main__': heapsort(a)
b76c43aa7524b536d3fc14a3e16d25b2594253eb
Aliubit/ADM-HW-1-2020-
/scripts/Problem2/Insertion_Sort_Part2.py
402
3.78125
4
# Insertion Sort - Part 2 import math import os import random import re import sys def insertionSort(ar): for q in range(1,len(ar)): for i in range(q): if(ar[q] < ar[i]): temp=ar[q] ar[q]=ar[i] ar[i]=temp print(' '.join(str(x) for x in ar)) m = input() ar = [int(i) for i in input().strip().split()] insertionSort(ar)
c5902cb3040615563c849719386846f01ff158c5
sicle1043/python_codes
/example2_crash/dictionary_learn.py
311
3.515625
4
vocabularies = { 'set': 'different list', 'dictionary': 'key and value', 'tuple': 'unchange', 'list': 'just a list', } for value, key in vocabularies.items(): print(value.title() + ':' + key) print('*****************') for vocabulary in sorted(vocabularies.keys()): print(vocabulary)
8e5289717c39acfa8227981cb97f669ba0bc3a32
akb46mayu/Data-Structures-and-Algorithms
/LintcodePartII/li581_longestReaptingSubsequence.py
2,014
3.65625
4
""" Given a string, find length of the longest repeating subsequence such that the two subsequence don’t have same string character at same position, i.e., any ith character in the two subsequences shouldn’t have the same index in the original string. Have you met this question in a real interview? Yes Example str = abc, return 0, There is no repeating subsequence str = aab, return 1, The two subsequence are a(first) and a(second). Note that b cannot be considered as part of subsequence as it would be at same index in both. str = aabb, return 2 """ class Solution: # SLE problem for current code, TLE for array %2 # @param {string} str a string # @return {int} the length of the longest repeating subsequence def longestRepeatingSubsequence(self, str): # Write your code here if not str: return 0 n = len(str) dp = [[0]*(n+1) for _ in range(n+1)] for i in range(1, n+1): for j in range(1, n+1): if i!=j and str[i-1] == str[j-1]: dp[i][j] = dp[i-1][j-1] + 1 else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) return dp[n][n] # java solution: public class Solution { /** * @param str a string * @return the length of the longest repeating subsequence */ public int longestRepeatingSubsequence(String str) { // Write your code here int n = str.length(); int[][] dp = new int[n + 1][n + 1]; for (int i = 0;i <= n; i++){ for (int j = 0; j <= n; j++){ dp[i][j] = 0; } } for (int i = 1; i <= n; i++){ for (int j = 1; j <= n; j++){ if (i != j && str.charAt(i-1) == str.charAt(j-1)){ dp[i][j] = dp[i-1][j-1] + 1; }else{ dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); } } } return dp[n][n]; } }
444958d4c72cdf2fc2ae0ab1711d789ec912c2d4
bigeast/ProjectEuler
/(#193)SquareFreeNumbers.py
790
3.59375
4
def Primes(a): sieve=[True]*(a+1) sieve[:2]=[False, False] sqrt=int(a**.5)+1 for x in range(2, sqrt): if sieve[x]: sieve[2*x::x]=[False]*(a/x-1) return sieve def main(a): print Primes(a) primes = [x for x in range(len(Primes(a))) if Primes(a)[x]] #print primes nums = [True] * (a+1) for p in primes: for x in range(p**2, a, p**2): nums[x] = False print nums.count(True)-1, len(primes), primes def main2(a): pr = Primes(a) primes = [x for x in range(len(pr)) if pr[x]] sq = int(a**.5)+2 nums = [True] * (sq) total = 0 for x in primes: s = x**2 for y in range(s,sq,s): nums[y] = False for y in range(1,sq): if y main2(2**4)