blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
6de317a5ce24e098ff9cbefe0c53995cc5debbd7
yeukhon/meme-lang
/lexer.py
1,240
3.515625
4
import re from collections import namedtuple Token = namedtuple('Token', ['type', 'value', 'lineno', 'columno']) def tokens(source, definitions, ignore_case=True): """Yield a token if part of the source matched one of the token definitions.""" re_definitions = [ (re.compile(t_def[0], re.I), t_def[1]) for t_def in definitions ] # Break sources into lines lines = source.split("\n") for lineno, line in enumerate(lines): columno = 0 while columno < len(line): match = None for t_def, t_type in re_definitions: match = t_def.match(line, columno) if match: yield Token(type=t_type, value=match.group(0), lineno=lineno, columno=columno) columno = match.end() break if not match: yield Token(type="UNKNOWN_TOKEN", value=line[columno], lineno=lineno, columno=columno) columno += 1 #definitions = [ # (r'hello', 'HELLO'), # (r'\d+', 'NUMBER'), # (r'\w+', 'WORD') #] #for x in tokens("123 hello what? \nhello123 hello what", definitions): # print x
f27fe6dd57b6229b26d776caceacddf0ef0adb2f
beyondasce/Algorithm
/fingerOffer/9_stack_to_list.py
800
3.578125
4
class my_list: def __init__(self): self.l1 = [] #入 self.l2 = [] #出 def put(self,value): self.l1.append(value) def pop(self): if self.l2: return self.l2.pop(-1) while self.l1: self.l2.append(self.l1.pop(-1)) if self.l2: return self.l2.pop(-1) else: raise Exception(".......") if __name__ == "__main__": a = my_stack() a.put(1) a.put(2) a.put(3) a.put(4) a.put(5) a.put(6) print(a.pop()) a.put(6) a.put(6) print(a.pop()) print(a.pop()) a.put(6) print(a.pop()) a.put(7) print(a.pop()) print(a.pop()) print(a.pop()) print(a.pop()) print(a.pop()) print(a.pop()) print(a.pop())
ca198d683a35f1ad256577de6e23b7ff2d49d698
beyondasce/Algorithm
/fingerOffer/8_find_next.py
418
3.71875
4
class Node(): def __init__(self,value): self.value = value self.parent = None self.left = None self.right = None def get_next(node): p_next = None if node.right: p = node.right while p: p = p.left p_next = p else: while p.parent and p.parent.right ==p : p = p.parent p_next = p.parent return p_next
04d5ccd877271991befdfd3dfea137e9b290c1f1
beyondasce/Algorithm
/fingerOffer/6_list.py
803
3.625
4
import random class My_list(): def __init__(self,value): self.value = value self.next = None def get_list(li): p = None p1 = p for i in li: n1 = My_list(i) if not p: p = n1 p1 = p else: p1.next = n1 p1 = p1.next return p def digui_list(li): if not li: return digui_list(li.next) print(li.value) def show_num(p_list): l1 = [] p = p_list while p: l1.append(p.value) p = p.next l2 = [] while l1: l2.append(l1.pop(-1)) return l2 if __name__ == "__main__": l1 = [ random.randint(0,12) for i in range(12) ] print(l1) p_list = get_list(l1) l2 = show_num(p_list) print(l2) digui_list(p_list)
e045549ac7c8471b37e10b5e20802f25e60ff9e5
saranya1999/sara
/103.py
169
3.578125
4
jak=int(input()) jak=str(jak) fa=0 for i in range(0,len(jak)): if(jak[i]=='0' or jak[i]=='1'): fa=1 else: fa=0 break if(fa==1): print('yes') else: print('no')
4a9fe514fc9c291f2e2981a4722bae220157226c
saranya1999/sara
/10e.py
107
3.71875
4
nu=[int(i) for i in input().split()] nu1=nu[0]*nu[1] if nu1 % 2 == 0: print("even") else: print("odd")
ec99b836876d4584369b6a98e9118a74a4f7e35c
pavel-malin/practice
/vectors_matrices_arrays/finding_max_min_values.py
341
4.09375
4
import numpy as np # Create matrix matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # max elements (9) print(np.max(matrix)) # min elements (0) print(np.min(matrix)) # find max elements column (array([7, 8, 9])) print(np.max(matrix, axis=0)) # find max elements stock (array([3, 6, 9])) print(np.max(matrix, axis=1))
e2951526d6bcc35fa05d4022ab9a55796e14c1a0
Caustic/Project-Euler
/python/factor.py
533
3.953125
4
#! /usr/bin/python2 #simple factorization problem from listprime import listprimes from math import sqrt #simple factorization algoritm that uses a prime # seive to test all factors recursively up to # sqrt of the number def factor(number): factors = list([]) for i in listprimes(sqrt(number)+1): #print(number) if (number % i == 0): factors.append(i) factors.extend(factor(number/i)) return factors if number != 1: factors.append(number) return factors
8b50de912f85197a510f302e06d6ee7d110c4935
cyrilnavessamuel/StrategyGames
/nimble.py
3,750
4
4
import random class nimble: # Initialisation methods def __init__(self): self.board = []; self.pawn = 0; # Define a new board with n square of board # P maximum no of pawns def newBoard(self, n, p): self.pawn = p; for i in range(0, n): self.board.insert(i, 0); for j in range(1, p + 1): ran = random.randint(0, n - 1); if (self.board[ran] != 0): self.board[ran] = self.board[ran] + 1; else: self.board.insert(ran, 1); return self.board; # Display the board square with the pawns def displayBoard(self, board, n, ): output = ""; scndoutput = ""; for square in range(0, len(board)): output += str(board[square]) + " | "; print(output); dashoutput = "" for l in range(len(output)): dashoutput += "-"; print(dashoutput); for square in range(0, len(board)): scndoutput += str(square) + " | "; print(scndoutput); # Possible Squares for a board with def possibleSquare(self, board, n, i): if (board[i] != 0): return True; else: return False; # Select a square to move def selectSquare(self, board, n): squareinstance = 0; possquare=True; while(possquare): squareinstance = int(input("Enter the square you want to select")) if (self.possibleSquare(board, n, squareinstance)): possquare=False; posdestination = True; while(posdestination): destinationsquare = self.selectDestination(board, n, squareinstance); if (self.possibleDestination(board, n, squareinstance, destinationsquare)): posdestination=False; self.move(board, n, squareinstance, destinationsquare); self.displayBoard(board, n); print("next move"); # Select a possible destination and check to move the pawn to def possibleDestination(self, board, n, i, j): possiblesquare = []; leng = len(board); while (i >= 0): i = i - 1; possiblesquare.append(i); if (j in possiblesquare): return True; else: return False; # Select the destination of the pawn def selectDestination(self, board, n, i): square = int(input("Enter the square you want to move to")); return square; # Move the pawn to destination def move(self, board, n, i, j): board[i] = board[i] - 1; board[j] = board[j] + 1; # Check if possible move exists for a player/ no move present in board def lose(self, board, n): if (board[0] == self.pawn): return True; else: return False; def nimbleplay(self, n, p): playerno = 0; boardinstance = self.newBoard(n, p); self.displayBoard(boardinstance, n); while (not (self.lose(boardinstance, n))): if (playerno == 2): playerno -= 1; else: playerno += 1; print("Player" + str(playerno)); self.selectSquare(boardinstance, n) print("Game Finished Winner:Player " + str(playerno)); def main(self): n = int(input("Enter the no of square of the board")); print(n); p = int(input("Enter the no of pawns")); print(p); self.nimbleplay(n, p); if __name__ == '__main__': nimbleinstance = nimble(); nimbleinstance.main();
fae21a63bd70a0c2d2f33b8263490e6b5e2fcca1
Andyt-Nguyen/python-basics
/file.py
493
3.671875
4
# Write Read Create files fo = open('text.txt', 'w') # File Information print('Name',fo.name) print('Is closed?', fo.closed) print('Opening mode', fo.mode) # Write into a file fo.write('I love python') fo.write(', javascript') fo.close() # Add to file.txt fo = open('text.txt', 'a') fo.write(' and I guess php') fo.close() # Create File fo = open('text2.txt', 'w+') fo.write('This is a new file') fo.close() # Read File fo = open('text.txt', 'r+') text = fo.read() print(text) fo.close()
156d92310a219f1ab56d7774a4dc3376566ef40b
ViktorWase/Frank-the-Science-Bot
/nonparametricDistribution.py
784
3.53125
4
from scienceFunctions import georand from random import randint from random import random def linCombRand(database): """ Takes a random number of points from the database and returns a vector that is a randomly weighted linear combination of the points. """ numPoints = georand(0.8) out = [0.0]*database.numAttributes for i in range(numPoints): rand1 = randint(0,database.numElements-1) rand2 = randint(0,database.numElements-1) w = random() for j in range(database.numAttributes): out[j] = out[j] + database.datapoints[rand1].attributes[j]*w + database.datapoints[rand1].attributes[j] * (1-w) for i in range(database.numAttributes): out[i] = out[i]/numPoints return out
7932cb303be6e4adb70c7c07bd1daebf422ae38b
ViktorWase/Frank-the-Science-Bot
/Templates/functionTemplate.py
1,784
3.5
4
""" This is a the template for the functions. So far we only have Artificial Neural Networks and Radial Basis Functions. All function classes need the methods described below. """ from tautology import * import random class radialBasisFunctionParameters: def __init__(self, chosenAttributes, ... ): """ It doesn't matter much how the constructor looks like. But it probably needs the array chosenAttributes to tell if which attributes are used in the hypothesis. Make sure that it is called correctly from the hypothesis constructor. """ def randomHypothesis(self, database): """ This resets the parameters of the hypothesis to a bunch of random values. """ def addRandomJump(self): """ This adds a small mutation to the parameters of the hypothesis. """ def functionName(x): """ This method can be called whatever (But make sure it's called correctly from the function method in hypothesis.py) This should return a single value from the vector input x. This is the function that the object is representing. """ def returnCopy(self): """ This returns a copy of the object. Make sure to copy all vectors by value, and not by reference. """ def getNeig_copy( self, database ): """ This returns a copy of the object. (Make sure to copy all vectors by value, and not by reference.) It then adds a small random jump to the copied object. """
64f15cdd74fd3e022ba4bec6c437ac8d414e47b0
ThomasB123/Tutoring
/02.py
5,027
3.671875
4
# 1. inFile = open('airports.txt','r') airports = [] for line in inFile: airports.append(line.split('\n')[0].split(',')) inFile.close() intAirports = [] for i in range(len(airports)): intAirports.append(airports[i][0]) ukAirports = ['LPL','BOH'] aircraft = [['Medium narrow body',8,2650,180,8],['Large narrow body',7,5600,220,10],['Medium wide body',5,4050,406,14]] valid1 = False valid2 = False valid3 = False # 2. while True: choice = input(''' Select an option: 1. Enter airport details 2. Enter flight details 3. Enter price plan and calculate profit 4. Clear data 5. Quit Your Choice > ''') # user input here if choice == '1': # 4. ukCode = input('Enter the 3-letter code for the UK airport > ') # user input here if ukCode in ukAirports: intCode = input('Enter the 3-letter code for the overseas airport > ') # user input here if intCode in intAirports: print(airports[intAirports.index(intCode)][1]) # program output here valid1 = True else: print('Invalid overseas airport code') # program output here valid1 = False else: print('Invalid UK airport code') # program output here valid1 = False if choice == '2': # 5. airType = input('Enter the type of aircraft > ') # user input here types = ['Medium narrow body','Large narrow body','Medium wide body'] if airType in types: x = types.index(airType) print(''' Type: {} Running cost per seat per 100km: £{} Maximum flight range: {}km Capacity if all standard-class: {} Minimum number of first-class seats (if any): {} '''.format(aircraft[x][0],aircraft[x][1],aircraft[x][2],aircraft[x][3],aircraft[x][4])) # program output here valid2 = True first = int(input('Enter the number of first-class seats > ')) # user input here if first != 0: if first < aircraft[x][4]: print('Number of first-class seats must be at least {}'.format(aircraft[x][4])) # program output here valid3 = False elif first > aircraft[x][3] /2: print('Number of first-class seats must be no more than {}'.format(aircraft[x][3] // 2)) # program output here valid3 = False else: standard = aircraft[x][3] - first * 2 print('Number of standard-class seats: {}'.format(standard)) # program output here valid3 = True else: standard = aircraft[x][3] print('Number of standard-class seats: {}'.format(standard)) # program output here valid3 = True else: print('Invalid aircraft type') # program output here valid2 = False if choice == '3': # 6. if valid1: if valid2: if valid3: planeRange = aircraft[x][2] distance = int(airports[intAirports.index(intCode)][ukAirports.index(ukCode)+2]) if planeRange >= distance: standardPrice = int(input('Enter price of standard-class seat > ')) # user input here firstPrice = int(input('Enter price of first-class seat > ')) # user input here perSeat = aircraft[x][1] * distance / 100 cost = perSeat * (first + standard) income = first * firstPrice + standard * standardPrice profit = income - cost print(''' Flight cost per seat: £{} Flight cost: £{} Flight income: £{} Flight profit: £{} '''.format(perSeat,cost,income,profit)) # program output here else: print('The aircraft range is {}km but the distance between the airports is {}km'.format(planeRange,distance)) # program output here else: print('You must first enter number of first-class seats') # program output here else: print('You must first enter the aircraft details') # program output here else: print('You must first enter the airport details') # program output here if choice == '4': # 7. ukCode = None intCode = None airType = None first = None standardPrice = None firstPrice = None valid1 = False valid2 = False valid3 = False print('Data cleared') # program output here if choice == '5': # 3. print('You have chosen to quit') # program output here quit() # close the program
b1e90944c9f45ddd1499ede657d1a18e6f951afc
starmon00/161HW
/MatrixMultiplication.py
1,044
3.8125
4
def matrixMultiplication(matrixA, matrixB): if type(matrixA) == int and type(matrixB) == int: return matrixA * matrixB elif type(matrixA) == int and type(matrixB) == list: solution = [] for row in matrixB: solutionRow = [] for col in row: solutionRow.append(col * matrixA) solution.append(solutionRow) return solution elif type(matrixB) == int and type(matrixA) == list: solution = [] for row in matrixA: solutionRow = [] for col in row: solutionRow.append(col * matrixB) solution.append(solutionRow) return solution elif type(matrixA) == list and type(matrixB) == list: solution = [] addthis = [] mul_index = 0 for row in matrixA: mul_index += 1 matrixB_row = 0 for col in row: addthis.append(col * matrixB[matrixB_row][mul_index]) matrixB_row += 1 print(matrixMultiplication(1,2)) print(matrixMultiplication(2,[[1,2,3],[4,5,6],[7,8,9]])) print(matrixMultiplication([[1,2,3],[4,5,6],[7,8,9]],2)) print(matrixMultiplication([[1,2,3],[4,5,6]],[[7,8],[9,10],[11,12]]))
0b142414e09fb32cac27af863fa8c7287b43a010
amohamud23/Python
/trees.py
531
4.0625
4
class Node(object): def __init__(self): self.left = None self.right = None self.data = None root = Node() n1 = Node() n2 = Node() n3 = Node() n4 = Node() n5 = Node() n6 = Node() root.data = "root" root.left = n1 root.right = n2 n1.data = 1 n2.data = 2 n1.left = n3 n1.right = n4 n3.data = 3 n4.data = 4 n2.left = n5 n2.right = n6 n5.data = 5 n6.data = 6 def traverse(root): if root != None: print(root.data) traverse(root.left) traverse(root.right) traverse(root)
e1d3b4fe36c9b98180365a16034b33e17e59324d
Mahmoud-Elbattah/Top500_Viz_2005-2017
/PythonCode/Counter.py
999
3.6875
4
import pandas countryCoordinates = {} def countryCounts(data,year): counts = {} for (i,country) in enumerate(data["Country"]): if country in counts: counts[country] += 1 else: counts[country] = 1 countryCoordinates[country] = (data.loc[i,"Lat"],data.loc[i,"Lng"]) outputFile = open("countryCounts_"+str(year)+".csv", "a") outputFile.write("Name,Count,Lat,Lng") for (key, value) in sorted(counts.items(),key=lambda item: (item[1], item[0]), reverse=True): Lat= str(countryCoordinates[str(key)][0]) Lng = str(countryCoordinates[str(key)][1]) outputFile.write("\n"+str(key)+","+str(value)+","+Lat+","+Lng) def main(): print("***Finding Country Counts***") for year in range(2005, 2018): print("Current Year:",year) data = pandas.read_csv("Top500_" + str(year) + ".csv", encoding="ISO-8859-1") countryCounts(data, year) main() print("Done.")
61d57d7debbc312a6abcbfd2598f5aab134a4fe2
eirikhoe/advent-of-code
/2022/02/sol.py
976
3.59375
4
from pathlib import Path data_folder = Path(".").resolve() symb_to_num = {"A": 1, "B": 2, "C": 3, "X": 1, "Y": 2, "Z": 3} def parse_data(data): games = [[symb_to_num[symb] for symb in game.split()] for game in data.split("\n")] return games def score(game, new_interpretation): if new_interpretation: offset = (game[1] - 2) % 3 played = (((game[0] - 1) + offset) % 3) + 1 score = played + 3 * (game[1] - 1) else: win_factor = (1 + (game[1] - game[0]) % 3) % 3 score = game[1] + 3 * win_factor return score def main(): data = data_folder.joinpath("input.txt").read_text() games = parse_data(data) print("Part 1") scores = [score(game, False) for game in games] print(f"The total score is {sum(scores)}") print() print("Part 2") scores = [score(game, True) for game in games] print(f"The total score is {sum(scores)}") print() if __name__ == "__main__": main()
c4f3ef7cc86733f3c6749d19442fcb39860f6494
eirikhoe/advent-of-code
/2018/11/sol.py
922
3.796875
4
from pathlib import Path import numpy as np def main(): serial = 8141 print(find_best_square(serial,3)) print(find_best_square(serial)) def find_best_square(serial,square_size=None): size = 300 gen = np.arange(size)+1 X = np.tile(gen,(size,1)) Y = np.copy(X.T) p = X+10 p *= Y p += serial p *= (X+10) p = (p % 1000)//100 p -= 5 max_power = -1000 if square_size is None: square_sizes = range(1,size+1) else: square_sizes = [square_size] for square_size in square_sizes: for y in range(size-square_size): for x in range(size-square_size): total_power = np.sum(p[y:y+square_size,x:x+square_size]) if total_power > max_power: best_square = (x+1,y+1,square_size) max_power = total_power return best_square if __name__ == "__main__": main()
204df96c8acb2a833bad5d9dbcfca10a25479dc8
eirikhoe/advent-of-code
/2021/12/sol.py
1,595
3.5625
4
from pathlib import Path from collections import defaultdict data_folder = Path(".").resolve() def parse_data(data): cave_connections = [line.split("-") for line in data.split("\n")] connected_to = defaultdict(list) for line in cave_connections: connected_to[line[0]].append(line[1]) connected_to[line[1]].append(line[0]) return connected_to def find_cave_paths(connected_to, visited, lower_twice_allowed, lower_twice_already): if visited[-1] == "end": return 1 n_paths = 0 for candidate in connected_to[visited[-1]]: lower_twice = lower_twice_already if candidate == "start": continue if (candidate == candidate.lower()) and (candidate in visited): if (not lower_twice_allowed) or lower_twice: continue else: lower_twice = True new_visited = visited + [candidate] n_paths += find_cave_paths(connected_to, new_visited, lower_twice_allowed, lower_twice) return n_paths def main(): data = data_folder.joinpath("input.txt").read_text() connected_to = parse_data(data) print("Part 1") n_paths = find_cave_paths(connected_to, ["start"], False, False) print(f"There are {n_paths} paths through this cave system that visit small caves at most once.") print() print("Part 2") n_paths = find_cave_paths(connected_to, ["start"], True, False) print(f"There are {n_paths} paths through this cave system that visit at most one small cave twice.") print() if __name__ == "__main__": main()
492503ce1d085ca365be4934606c8746e41c9d3e
rodrikmenezes/ProjetoEuler
/4 LargestPalindromeProduct2.py
1,041
4.1875
4
# ============================================================================= # A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. # ============================================================================= import numpy as np def palindromos(): ''' Retorna uma lista de números palíndromos formados pela multiplicação entre outros dois números de dois dígitos''' palindromos = [] for i in range(1, 1000): for j in range(1, 1000): p = i * j s = str(p) l = len(s) cont = 0 n = int(np.floor(l/2)) for w in range(0, n): ww = (w+1) * (-1) if s[w] == s[ww]: cont += 1 if cont == n: palindromos.append(p) return list(sorted(set(palindromos))) # Resposta print(max(palindromos()))
bff174c4bf0b2d4375deb8679c4b59c7cf1211b4
rajasekhar-varikuti/basic_algorithms
/basic_algorithms/sorting_algorithms_helpers.py
1,954
4.0625
4
#helping methods for sorting algorithms def merge_list(array, start, mid, end): left = array[start:mid] right = array[mid:end] k = start i = 0 j = 0 while (start + i < mid and mid + j < end): if (left[i] <= right[j]): array[k] = left[i] i = i + 1 else: array[k] = right[j] j = j + 1 k = k + 1 if start + i < mid: while k < end: array[k] = left[i] i = i + 1 k = k + 1 else: while k < end: array[k] = right[j] j = j + 1 k = k + 1 def merge_sort(array, start, end): '''Sorts the list from indexes start to end - 1 inclusive.''' if end - start > 1: mid = (start + end)//2 merge_sort(array, start, mid) merge_sort(array, mid, end) merge_list(array, start, mid, end) return array def partition(arr,low,high): i = low-1 # index of smaller element pivot = arr[high] # pivot for j in range(low , high): if arr[j] <= pivot: i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return ( i+1 ) def quick_sort(arr,first_index,last_index): if first_index < last_index: partition_index = partition(arr,first_index,last_index) quick_sort(arr, first_index, partition_index-1) quick_sort(arr, partition_index+1, last_index) return arr def heapify(arr, n, i): largest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[i] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r if largest != i: arr[i],arr[largest] = arr[largest],arr[i] heapify(arr, n, largest)
37377c07e6f8f2153e3e723d8ede0a7aca395c37
bharathkumarna/Python-Deep-Learning-Lab-Assignments
/Lab-1/Source/Task-2.py
548
4.0625
4
import string #create set with lowercased string alphabets = set(string.ascii_lowercase) #input strings inp = ['How quickly daft jumping zebras vex','How quickly daft jumping zebras'] inp_nospace =[None]*inp.__len__() for i in range(len(inp)): #replace space character (' ') with ('') inp_nospace[i] = inp[i].replace(' ', '') #check if every letter in the set alphabets is in the set created from input text output = ("is not a pangram","is a pangram")[set(inp_nospace[i].lower()) >= alphabets] print(inp[i]+' --> '+output)
655545225361f6c5bcae9e1188b442b7f258d114
amdel2020/Algorithms
/mergesortedarray.py
1,019
3.6875
4
from queue import PriorityQueue class Node: def __init__(self, index, list_num): self.index = index self.listNum = list_num def merge(sorted_arrays): pq = PriorityQueue(0) res = [] for idx, item in enumerate(sorted_arrays): pq.put((item[0], Node(0, idx))) while not pq.empty(): min_node = pq.get() res.append(min_node[0]) next_index = min_node[1].index + 1 if next_index < len(sorted_arrays[min_node[1].listNum]): n = Node(next_index, min_node[1].listNum) new_item = sorted_arrays[min_node[1].listNum][next_index] pq.put((new_item, n)) return res maxRange = 1000001 arr1 = [] for i in range(2, maxRange): if i % 10 == 0: arr1.append(i) arr2 = [] for i in range(2, maxRange): if i % 15 == 0: arr2.append(i) arr3 = [] for i in range(2, maxRange): if i % 21 == 0: arr3.append(i) arr = [] arr.append(arr1) arr.append(arr2) arr.append(arr3) sortedarray = merge(arr) #print(sortedarray)
530436f9fe184e0134cb2ac03fe90663bf8adce5
amdel2020/Algorithms
/GradingStudents.py
587
3.78125
4
def gradingStudents(grades): result = [] for grade in grades: if grade < 38: result.append(grade) else: if grade % 5 == 0: result.append(grade) else: count = 0 temp = grade while temp % 5 != 0: temp += 1 count += 1 if count < 3: result.append(temp) else: result.append(grade) return result grades = [73, 67, 38, 33] print(gradingStudents(grades))
fcdae72bb66288329640b052012d5e4f2f60ee15
amdel2020/Algorithms
/13.01.eopi.py
158
3.609375
4
from collections import Counter def check_palindrome(s): return sum( ch % 2 for ch in Counter(s).values()) <= 1 print(check_palindrome("dokilolokido"))
de79189d4622cb8b63b451c92e2d3b59762b4899
amdel2020/Algorithms
/8.7.py
395
3.59375
4
def solve(string): arr = list(string) p = [arr[0:2], arr[1::-1]] for i in range(2, len(arr)): temp1 = [[]] for s in p: for j in range(len(s)): temp2 = s[:] temp2.insert(j, arr[i]) temp1.append(temp2) temp1.pop(0) p = temp1 print(p) if __name__ == '__main__': solve('abcdef')
6afa5b0c4dcad188de0dcf2ba6c492d99e68ce89
petrakri/INF5860-petteakr
/inf5860_oblig1/inf5860/classifiers/softmax.py
4,151
3.828125
4
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. - reg: (float) regularization strength Returns a tuple of: - loss as single float - gradient with respect to weights W; an array of same shape as W """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # TODO: Compute the softmax loss and its gradient using explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# [D, C] = W.shape [N, D]= X.shape # denum = p matrisen i gradienten # lambda -> reg theta -> W # m -> N y(i) -> y[i] # k -> C theta_j -> W[:,j] # l -> C x(i) = X[i,:] for i in range(N): denum = 0 for l in range(C): denum += np.exp(np.dot(W[:,l],X[i,:])) for j in range(C): q = np.exp(np.dot(W[:,j],X[i,:]))/denum loss += (y[i] == j) * np.log(q) dW[:,j] += X[i,:]*((y[i] == j) - q) # summe regulariseringen til slutt etter alle løkker R += W[i,j]**2 == np.sum(W**2) loss = -(loss/N) + (reg/2)*np.sum(W**2) dW = -(dW/N) + reg*W pass ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW def softmax_loss_vectorized(W, X, y, reg): """ softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive. """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # TODO: Compute the softmax loss and its gradient using no explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# [D, C] = W.shape [N, D]= X.shape # denum = p matrisen i gradienten # lambda -> reg theta -> W # m -> N y(i) -> y[i] # k -> C theta_j -> W[:,j] # l -> C x(i) = X[i,:] # Calculate scores, dot product of X and W scores = np.dot(X,W) # Create a p for the true distribution, where is y the correct class p = np.zeros_like(scores) p[np.arange(N), y] = 1 # shifting, highest value is 0, avoiding numeric stability scores -= np.max(scores) # Softmax function q = np.exp(scores) / np.sum(np.exp(scores),axis=1).reshape(N,1) # q for log(q) # Loss function loss = -np.sum(p*np.log(q)) dW = np.dot(X.T,(p - q)) # Skalerer og legger til generalisering loss = loss/N + (reg/2)*np.sum(W**2) dW = -(dW/N) + reg*W ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW
5a91c22b5ee87704cc8991bd6dab3eb2b2684d8b
ivanvi22/repository_name
/HelloWorld.py
323
4.1875
4
# программа для вывода "Hello World" car_color = 'wite' car_type = 'masda' car_count = 2 print("Укажите цвет машины:") car_color = input() print("Укажите тип машины:") car_type = input() print("You have " + str(car_count) + ' ' + car_color + ' ' + car_type) print(2 ** 3)
7dcdb9f9d1ee10795021f722200cc9324744ee29
ctemelkuran/py4e
/ex8.5.py
565
4.03125
4
#From [email protected] Sat Jan 5 09:14:16 2008 #You will parse the From line using split() and # print out the second word in the line(i.e. the entire address of the person). #Then print out a count at the end. fname = input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" fh = open(fname) count = 0 for line in fh: line = line.rstrip() if not line.startswith('From:'): continue pieces = line.split() count = count + 1 print(pieces[1]) print("There were", count, "lines in the file with From as the first word")
9198e83e1836573e6ddd826ccf850ffe5e12db26
JGUO-2/MLwork
/Fibonacci/Fib_recursion.py
743
3.90625
4
# -*- coding: utf-8 -*- """ 实现斐波那契数列 方法五:递归 """ def Fib_list(n) : if n == 1 or n == 2 : #n为项数,若为1、2时,结果返回为1 return 1 else : m = Fib_list(n - 1) + Fib_list(n - 2) #其他情况下,结果返回前两项之和 return m if __name__ == '__main__': while 1: print("**********请输入要打印的斐波拉契数列项数n的值***********") n = input("enter:") if not n.isdigit(): print("请输入一个正整数!") continue n = int(n) list2 = [0] tmp = 1 while (tmp <= n): list2.append(Fib_list(tmp)) tmp += 1 print(list2)
8aa62e157ceb4c3c7760359cca19152bd9c64c69
JGUO-2/MLwork
/Fibonacci/Fib_generator.py
794
3.90625
4
# -*- coding: utf-8 -*- """ 实现斐波那契数列 方法一:生成器 """ def Fib_yield_while(max): a, b = 0, 1 #设置初始值 while max > 0: a, b = b, a + b max -= 1 yield a #执行yield函数 def Fib_yield_for(n): a, b = 0, 1 for _ in range(n): #循环遍历n次 a, b = b, a + b yield a if __name__ == "__main__": while 1: print("**********请输入要打印的斐波拉契数列项数n的值***********") n = input("enter:") #输入要计算的项数n if not n.isdigit(): #判断输入值是否为数字 print("请输入一个正整数!") continue n = int(n) for i in Fib_yield_for(n): print(i)
dd87bfe17b74e88e1b019726695aacc81dfa937c
vsiddhu/qinfpy
/src/qinfpy/basic/zerOutMd.py
876
3.671875
4
#zerOut(mt) : Removes small entries in array import copy import numpy as np __all__ = ['zerOut'] def zerOut(array, tol = 1e-15): r"""Takes as input an array and tolerance, copies it, in this copy, nulls out real and complex part of each entry smaller than the tolerance, returns the copy. Parameters ---------- array : numpy.ndarray tol : float Optional, 1e-15 by default Returns ---------- arr : numpy.ndarray Identical to input array, except each entry smaller than tol is set to zero """ arr = copy.deepcopy(array) for index, val in np.ndenumerate(arr): if (np.abs(val.real) < tol): arr[index] = (arr[index] - arr[index].conj())/2. if (np.abs(val.imag) < tol): arr[index] = (arr[index] + arr[index].conj())/2. return arr
1a5f6a490a8aa05fff89a73ac2a015e4f94ca80b
lbvf50mobile/til
/20230808_Tuesday/20230808.py
1,060
3.84375
4
# Leetcode: 33. Search in Rotated Sorted Array. # https://leetcode.com/problems/search-in-rotated-sorted-array/ class Solution: # Copied from: # https://leetcode.com/problems/search-in-rotated-sorted-array/solution/ def search(self, nums: List[int], target: int) -> int: n = len(nums) left, right = 0, n - 1 while left <= right: mid = left + (right - left) // 2 # Case 1: find target if nums[mid] == target: return mid # Case 2: subarray on mid's left is sorted elif nums[mid] >= nums[left]: if target >= nums[left] and target < nums[mid]: right = mid - 1 else: left = mid + 1 # Case 3: subarray on mid's right is sorted. else: if target <= nums[right] and target > nums[mid]: left = mid + 1 else: right = mid - 1 return -1
a93434543dfa574acdd4a0093c33ef1d7dad99e5
lbvf50mobile/til
/20230810_Thursday/20230810.py
654
3.625
4
# https://leetcode.com/problems/search-in-rotated-sorted-array-ii/discuss/1891315/Python-or-binary-search class Solution: def search(self, nums: List[int], target: int) -> bool: l = 0 r = len(nums)-1 while l<=r: m=(r+l)//2 if target in [nums[m], nums[r], nums[l]]: return True elif nums[m]==nums[l] or nums[m]==nums[r]: r-=1 l+=1 elif nums[l]<=nums[m]: if nums[l]<target<nums[m]: r=m-1 else: l=m+1 else: if nums[m]<target<nums[r]: l=m+1 else: r=m-1 return False
b4a39da185af20c91ac6358a36f427eb84d42830
lbvf50mobile/til
/20230723_Sunday/20230723.py
930
3.734375
4
# Leetcode: 894. All Possible Full Binary Trees. # https://leetcode.com/problems/all-possible-full-binary-trees/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # Leetcode's solution. # https://leetcode.com/problems/all-possible-full-binary-trees/solution/ def allPossibleFBT(self, n: int) -> List[TreeNode]: if n % 2 == 0: return [] dp = [[] for _ in range(n + 1)] dp[1].append(TreeNode(0)) for count in range(3, n + 1, 2): for i in range(1, count - 1, 2): j = count - 1 - i for left in dp[i]: for right in dp[j]: root = TreeNode(0, left, right) dp[count].append(root) return dp[n]
fd3c0a63cf36c2fd364cc1fc6c513d1db4c16f74
lbvf50mobile/til
/20230701_Saturday/20230701.py
1,707
3.515625
4
# Leetcode: 2305. Fair Distribution of Cookies. # https://leetcode.com/problems/fair-distribution-of-cookies/ # = = = = = = = = = = = = = = # Accepted. # Thanks God, Jesus Christ! # = = = = = = = = = = = = = = # Runtime: 1594 ms, faster than 36.20% of Python3 online submissions for Fair # Distribution of Cookies. # Memory Usage: 16.5 MB, less than 10.82% of Python3 online submissions for Fair # Distribution of Cookies. # 2023.07.01 Daily Challenge. class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: # Copied from: # https://leetcode.com/problems/fair-distribution-of-cookies/solution/ cur = [0] * k n = len(cookies) def dfs(i, zero_count): # If there are not enough cookies remaining, return `float('inf')` # as it leads to an invalid distribution. if n - i < zero_count: return float('inf') # After distributing all cookies, return the unfairness of this # distribution. if i == n: return max(cur) # Try to distribute the i-th cookie to each child, and update answer # as the minimum unfairness in these distributions. answer = float('inf') for j in range(k): zero_count -= int(cur[j] == 0) cur[j] += cookies[i] # Recursively distribute the next cookie. answer = min(answer, dfs(i + 1, zero_count)) cur[j] -= cookies[i] zero_count += int(cur[j] == 0) return answer return dfs(0, k)
9af08911cc64efd457bf9616256368a48334dc98
lbvf50mobile/til
/20230722_Saturday/20230722.py
1,608
3.765625
4
# Leetcode: 688. Knight Probability in Chessboard. # https://leetcode.com/problems/knight-probability-in-chessboard/ class Solution: # Based on: # https://leetcode.com/problems/knight-probability-in-chessboard/solution/ def knightProbability(self, n: int, k: int, row: int, column: int) -> float: # Define possible directions for the knight's moves directions = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)] # Initialize the dynamic programming table dp = [[[0] * n for _ in range(n)] for _ in range(k + 1)] dp[0][row][column] = 1 # Iterate over the number of moves for moves in range(1, k + 1): # Iterate over the cells on the chessboard for i in range(n): for j in range(n): # Iterate over possible directions for direction in directions: prev_i, prev_j = i - direction[0], j - direction[1] # Check if the previous cell is within the chessboard if 0 <= prev_i < n and 0 <= prev_j < n: # Add the previous probability dp[moves][i][j] += dp[moves - 1][prev_i][prev_j] # Divide by 8 dp[moves][i][j] /= 8 # Calculate total probability by summing probabilities for all cells total_probability = sum( dp[k][i][j] for i in range(n) for j in range(n) ) return total_probability
a09d4162a16191968c5ae16762a63facf71abafd
lbvf50mobile/til
/20230819_Saturday/20230819.py
3,264
3.84375
4
# Leetcode: 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree. # https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/ # = = = = = = = = = = = = = = # Accepted. # Thanks God, Jesus Christ! # = = = = = = = = = = = = = = # Runtime: 1114 ms, faster than 65.38% of Python3 online submissions for Find # Critical and Pseudo-Critical Edges in Minimum Spanning Tree. # Memory Usage: 16.6 MB, less than 40.66% of Python3 online submissions for Find # Critical and Pseudo-Critical Edges in Minimum Spanning Tree. # 2023.08.19 Daily Challenge. class Solution: # Copied from: # https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/solution/ class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.max_size = 1 def find(self, x): # Finds the root of x if x != self.parent[x]: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): # Connects x and y root_x = self.find(x) root_y = self.find(y) if root_x != root_y: if self.size[root_x] < self.size[root_y]: root_x, root_y = root_y, root_x self.parent[root_y] = root_x self.size[root_x] += self.size[root_y] self.max_size = max(self.max_size, self.size[root_x]) return True return False def findCriticalAndPseudoCriticalEdges(self, n, edges): new_edges = [edge.copy() for edge in edges] # Add index to edges for tracking for i, edge in enumerate(new_edges): edge.append(i) # Sort edges based on weight new_edges.sort(key=lambda x: x[2]) # Find MST weight using union-find uf_std = self.UnionFind(n) std_weight = 0 for u, v, w, _ in new_edges: if uf_std.union(u, v): std_weight += w # Check each edge for critical and pseudo-critical critical = [] pseudo_critical = [] for (u, v, w, i) in new_edges: # Ignore this edge and calculate MST weight uf_ignore = self.UnionFind(n) ignore_weight = 0 for (x, y, w_ignore, j) in new_edges: if i != j and uf_ignore.union(x, y): ignore_weight += w_ignore # If the graph is disconnected or the total weight is greater, # the edge is critical if uf_ignore.max_size < n or ignore_weight > std_weight: critical.append(i) continue # Force this edge and calculate MST weight uf_force = self.UnionFind(n) force_weight = w uf_force.union(u, v) for (x, y, w_force, j) in new_edges: if i != j and uf_force.union(x, y): force_weight += w_force # If total weight is the same, the edge is pseudo-critical if force_weight == std_weight: pseudo_critical.append(i) return [critical, pseudo_critical]
d919df4732a94c3619d678b00e26dad0188684c0
gustavoSaboia97/gamelibapi
/src/game/models/model/Game.py
541
3.578125
4
class Game: def __init__(self, game_dict: dict): self.__name = game_dict["name"] self.__category = game_dict["category"] self.__year = game_dict["year"] @property def name(self): return self.__name @property def category(self): return self.__category @property def year(self): return self.__year def to_dict(self) -> dict: return { "name": self.__name, "category": self.__category, "year": self.__year }
98212cc7172cd5103a5631b0fd325bbe0ea120a5
Soonki/drone_contest
/src/scheduler.py
1,295
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time, threading class Scheduler(): def __init__(self,function,step_time): self.stop_event = threading.Event() #停止させるかのフラグ self.inc_event = threading.Event() #刻み幅を増やすかのフラグ self.step_time=step_time self.function=function self.count=0 self.state=0 #スレッドの作成 self.thread = threading.Thread(target = self.run) def run(self): self.count+=1 self.function() if not self.stop_event.is_set(): self.thread=threading.Timer(self.step_time,self.run) self.thread.start() def start(self): self.state=1 self.thread.start() def stop(self): """スレッドを停止させる""" self.stop_event.set() self.thread.join() #スレッドが停止するのを待つ self.state=0 def inc(self): self.inc_event.set() if __name__ == '__main__': def hello(): print("hello") def bab(): print("Babu") h = Scheduler(hello,0.5) #スレッドの開始 b = Scheduler(bab,2) time.sleep(6) h.stop() #スレッドの停止 b.stop() print "finish"
74ef4502adf08b826bc5b21b3bf427d10ced9f88
wniedziolka/Programowanie-I-R
/speed.py
478
3.5625
4
import time a = float(input("Podaj pierwszą liczbę: ")) b = float(input("Podaj drugą liczbę: ")) c = 0 add_start = time.perf_counter_ns() c = a + b add_stop = time.perf_counter_ns() mul_start = time.perf_counter_ns() c = a * b mul_stop = time.perf_counter_ns() print("czas dodawania to: {0}".format(add_stop-add_start)) print("czas mnożenia to: {0}".format(mul_stop-mul_start)) print("różnica tych czasów to {0}".format((mul_stop-mul_start) - (add_stop-add_start)))
cc187912acdbe277fb2de0ed7b4c636e6c0a2012
jake-albert/py-algs
/c17/c17p19.py
20,828
3.90625
4
from operator import xor, add, mul from functools import reduce from math import sqrt, factorial, log2 from random import shuffle # c17p19 # Missing Two: You are given an array with all the numbers from 1 to N # appearing exactly once, except for one number that is missing. How can you # find the missing number in O(N) time and O(1) space? What if there were two # numbers missing? ############################################################################## # When one number is missing, the approach is straightforward. We know that # the numbers from 1 to N sum to (N)(N+1)/2, so all we can just sum the values # in the list and subtract to find its difference with the expected sum. # Are memory requirements here actually O(1), though? It is true that we use # only one int object to store the sum, but of course the space required for # this int gets larger as the sum increases, since Python ints have no # limiting bit length. Pedantically, then, O(log(N^2)) memory is required to # store the sum, which simplifies to O(logN) since the constant power inside a # log is the same as multiplying by a constant factor. # If, on the other hand, we assume we are storing the sum value using unsigned # 32-bit integers, the highest value we can hold is around 4.3 billion, so we # can handle only inputs with N such that (N)(N+1)/2 is less than this value. # If we can assume that N is always within this range (or any range, for that # matter), then it would be fair to argue that the algorithm uses O(1) space. def f1(lst): """Returns the missing integer in a list. Args: lst: A list of ints 1 through some number N, with one number in that range missing. Returns: An int. """ n = len(lst) + 1 return (n)*(n+1)//2 - sum(lst) # Another approach that works with one number missing is to use the bitwise # XOR function for all of the values rather than the sum. We know that if we # repeatedly XOR values together, and then we take a number with a 0 bit at # some position out from that agglomeration, then there is no change at that # position. If it is a 1 bit, then the bit flips. # If we XOR all of the values 1 to N that we EXPECT to be in the list (x1) and # XOR all of the values actually in the list (x2), then (x1 XOR x2) results in # a number that has a 0 any time when bits match up between x1 and x2 (that is, # where there was no change from x1 to x2) and a 1 any time the bit flipped. # This number is the missing value. # The below function requires twice as many calculations as the above since it # is repeatedly calling XOR over O(N) values twice as opposed to finding a # single value for the expected sum above, but XOR should be a faster # operation than addition so the function might be faster. Might revisit to # test later. # Provided we use an iterator like range() that does not actually use O(N) # memory to generate all of the numbers from 1 to N, then the only space that # is needed is the O(logN) for the bits that must hold the highest value of N. # Again, though, if we have some realistic expectation of a highest possible # value for N, we can argue that this is in O(1) space. def f2(lst): """See f1 docstring.""" # N is equal to len(lst)+1, so we call range with upper limit N+1. return reduce(xor,range(1,len(lst)+2)) ^ reduce(xor,lst) # The REASON that both of these functions work is not because there is # something special to the XOR operator, or to addition, but that both of # these agglomeration functions produce a single value from the input values # that, when combined in some other way with the agglomeration of all expected # values from 1 to N, produce a UNIQUE value that we can use to determine the # missing value. To get a solution when there are TWO missing values, then we # will need to find some other function, for every TWO distinct values from 1 # to N that could be missing, produce different results. # Clearly, we cannot use addition alone as we did above. If we find, as above, # the sum S of expected values (N)(N+1)/2, then there are possibly many unique # pairs of integers <= N that sum to S. For instance, [1,2,3,4,6,7,9,10] is # missing 5 and 8, which sum to 13, and (10)(11)/2 = 55 minus the sum in the # list does correctly give us 13 as well, but there are several valid pairs of # integers: (3,10), (4,9), and (5,8). # Another way to express this is that for some pair of integers X,Y such that # X < Y and X+Y = S, there are infinite integers A such that (X-A)+(Y+A) = S, # because X-A+Y+A = X+Y is tautologically true no matter WHAT value A takes. # And when there are numbers 1 through N to deal with, there are O(N) possible # A values that could yield pairs X and Y within range. # We can try using multiplication to disambiguate. Say we have a pair of # integers X and Y that add to S, and another pair of integers X-A and Y+A # that also add to S. Is it possible for X*Y to equal (X-A)*(Y+A)? What must # A be for this to be true? Solving for A in the equation X*Y = (X-A)*(Y+A), # I found that A equals X-Y, but the integers X-(X-Y) and Y+(X-Y) are simply # the same pair of integers, Y and X. This implies that the pair of integers # X and Y are the only pairs that both sum to S and have some product P. # In the below function we find the sum and product of the missing numbers and # algebraically solve for the missing numbers. To find the product of the # missing numbers, we first find the factorial of N, which gets large quite # quickly. The number of bits to store N! is in O(log(N!)) which is in # O(Nlog(N)). Like above, if N is limited to some value, this is technically # O(1) space, but given that a 32-bit unsigned integer can hold only up to # 12!, this solution does not seem to meet the spirit of the problem when it # asked for O(1) space. def f3(lst): """Returns the missing two integers in a list. Args: lst: A list of ints 1 through some number N, with two numbers in that range missing. Returns: A tuple of ints. """ n = len(lst) + 2 # There is actually way to do these calculations that is less # memory intensive over many inputs. Start with the identities of 0 # for addition and 1 for multiplication, and then for each number X # from 1 to N, add/multiply by that number X and sub/divide away # the Xth number in the list (when X is in range of the list). # Worst-case memory performance is still the same, and it would be # important to handle division with floats or the Fractions library # properly, but on input lists such as [1,2,3,4...23,24,27,28] the # running product never exceeds 1000, as opposed to 28! which is # larger than 10^29. S = (n)*(n+1)//2 - reduce(add,lst) P = factorial(n) // reduce(mul,lst) disc = sqrt(S*S-4*P) # Discriminant of the quadratic equation. return int((S-disc)/2), int((S+disc)/2) # It is possible to avoid using such big numbers above by summing the base-2 # logs of all of the numbers rather than multiplying them. Since log(X) + # log(Y) is equal to log(X*Y), if we exponentiate by 2 at the end we will end # up with the same product without ever dealing with factorials. # Just because we avoid using large numbers does not automatically mean that # we have negligible memory constraints, though. Using logs requires that we # store floats, and these floats must have enough bits to store sufficiently # precise numbers that we get correct results after rounding. # With the standard Python float, which is accurate to 53 bits or about 16 # decimal places, the below function fails on inputs where N is as low as # 71,431 or so. More rigorous testing would be needed to find out on exactly # what kinds of inputs this is secure, or alternatively what level of # float precision is required to have f4 be secure over a given N for inputs. def f4(lst): """See f3 docstring.""" n = len(lst) + 2 S = (n)*(n+1)//2 - reduce(add,lst) P = round(2 ** (reduce(add,logs(range(1,n+1))) - reduce(add,logs(lst)))) disc = sqrt(S*S-4*P) # Discriminant of the quadratic equation. return int((S-disc)/2), int((S+disc)/2) def logs(it): """Yields logs of iterator items 1-by-1 rather than O(N) list.""" for item in it: yield log2(item) # Is there another way that we can aggregate numbers using both addition and # XOR, given that both of these operations were useful when one number was # missing? We are able to in O(N) time and O(1) space find what the missing # two numbers sum to, as well as what they XOR to. Perhaps we can take # advantage of the fact that bitwise addition is very similar to XOR? # Say that X+Y is 17, or [1,0,0,0,1], and A^B is 9, or [1,0,0,1]. We can # deduce that the 0th bit of X and Y must XOR to 1, and since the carry from # the first addition must be 0, that the 1st bits of X and Y are both 0. It # is possible to deduce altogether that X and Y are 4-bit numbers of the form # X = [a4,1,0,a0] and Y = [b4,1,0,b0], where a4^b4 and a0^b0 both XOR to 1. # But there are TWO pairs of numbers that fits these criteria, 13 and 4 as # well as 12 and 5, so we cannot determine the correct missing numbers from # this information. # More generally, this approach gives us information for each bit in the pair # of missing numbers whether A) they are both 0, B) they are both 1, or C) # they differ from each other. Up to log(N) of the bits can differ from each # other, so O(2**log(N)), or O(N), possible pairs of numbers, would need to # be tested. But we cannot do this without either using more than O(1) space # or taking O(N) time to check each pair, which violates our constraints. # If we are permitted to modify the array, then there is another approach that # works by performing a sort of in-place radix sort on the input. Every number # in the list "belongs" at an index equal to that number's value minus 1. At # most two of these indices are currently out of range of the list, so we # append two "empty" indices to the list. # [ 2 , 3 , 1 , 4 , 5 , 9 , 10 , 7 ] # [ 2 , 3 , 1 , 4 , 5 , 9 , 10 , 7 , X , X ] # Every number that we encounter in the list either A) is already at the # correct index (ex. 4 and 5 above), B) belongs in one of the new indices that # resulted from the append (ex. 9 and 10), C) belongs where one of the numbers # in case B) was originally (ex. 7), or D) is part of a closed loop with other # numbers that can be shifted around circularly (ex. 1,2,3). # We can perform these shifts in O(N) time by progressing through the list and # never moving a number to a different index more than once. Once the sort is # complete, the two "empty" indices that remain are the locations of the # missing numbers, and one more scan of the list will help find them. # [ 1 , 2 , 3 , 4 , 5 , X , 7 , X , 9 , 10 ] # This approach is generalizable to any problem with list 1 through N that has # any number R of missing numbers, and requires O(R) additional space for the # extra appended slots. For this problem R is a constant, 2, so space is O(1). def f5(lst): """See f3 docstring. Unlike f3, modifies input list.""" return find_r_missing_numbers(lst,2) def find_r_missing_numbers(lst,R): """Returns the R missing numbers in a list. Sorts the list in place after appending R empty slots to the list. Args: lst: A list of ints 1 through some number N, with R numbers in that range missing. Returns: A tuple of R ints. """ NO_NUM = -1 for _ in range(R): lst.append(NO_NUM) for i in range(len(lst)): # Empty slots and case A. if lst[i] == NO_NUM or lst[i] == i+1: continue # Cases B, C and D. Move a number from its current slot, # leaving an empty slot behind, to its proper slot, and then # move whatever displaced number was there, until there is an # empty slot rather than a number to displace. curr_val = lst[i] lst[i] = NO_NUM while curr_val != NO_NUM: next_val = lst[curr_val-1] lst[curr_val-1] = curr_val curr_val = next_val return tuple([i+1 for i in range(len(lst)) if lst[i] == NO_NUM]) # If we are not allowed to modify the list, I thought of a probabilistic # approach with average O(N) performance. Though we cannot tell what the two # missing numbers are by knowing only the sum, we DO get more information if # we calculate TWO sums: one of the upper half of numbers in the list, and one # of the lower half of numbers. Regardless of the order of numbers in the list, # we are able to determine which half any number belongs to since 1 through N # are supposed to be there. # If we find that one number is missing from the lower sum, and one from the # upper sum, then we can immediately deduce those missing numbers in the same # way we did in f1. Otherwise, we can go through the list again, this time # narrowing the range of numbers that we sum to those in the half where we # know both missing numbers are. # Since the list is unordered, we must scan the entire list each time we sum # to hit all of the numbers we want, no matter how small the range is. BUT the # average number of times we must scan is constant. We start with 1 sweep # regardless of which numbers are missing. Say that the first missing number # is in some of the numbers 1 through N (either the lower or upper half). # The second missing number is in the same half roughly half the time, and # in the opposite half the other half of the time. So for roughly half of # inputs we make another scan. Following this logic recursively, we see that # the full call requires 1 + 1/2 + 1/4 + ... scans, which approaches 2, a # constant, as N approaches infinity. # So this approach runs in O(N) time, but in the AVERAGE case over UNIFORMLY # RANDOMLY DISTRIBUTED inputs. The worst case is when the missing numbers are # certain pairs of adjacent integers, such as 1 and 2 when N is 1000. In this # case, the full number of O(log(N)) scans is required, making performance # O(NlogN). # This behavior makes the approach similar to, unsurprisingly, another # algorithm that relies on random splits over the input: Quicksort, which has # average performance of O(NlogN) but worst case O(N^2) runtime over certain # inputs, like already sorted lists. We tend to be comfortable describing # Quicksort as an "O(NlogN) sort", so by that standard I am okay with calling # the below function an O(N) algorithm, but it would be important to remember # that the average performance in "real" contexts where the inputs could skew # towards suboptimal cases might be worse. # I wrote the function iteratively, not recursively, so as to avoid storing # instances of execution on a call stack, which would lead to O(logN) space # requirements in the worst case. def f6(lst,timetest=False): """See f3 docstring. When timetest is True, returns the number of scans of that were required during the call for testing purposes. """ n = len(lst) + 2 lo, hi = 1, n passes = 0 while hi - lo > 1: # When False, only two numbers remain. passes += 1 # The split is the INCLUSIVE upper bound of the lower half. spl = (lo + hi) // 2 els, ehs = expected_sums(lo,spl,hi) als, ahs = actual_sums(lst,lo,spl,hi) # If a number is missing from BOTH halves, then we have found # both numbers. Otherwise, we decrease the range of candidates. if als < els and ahs < ehs: return passes if timetest else (els-als, ehs-ahs) else: lo,hi = (lo,spl) if ahs == ehs else (spl+1,hi) return passes if timetest else (lo, hi) def expected_sums(lo,spl,hi): """Returns the expected lower sum and expected higher sum. Given positive integers lo, spl, and hi, returns the sum of all integers from lo to spl inclusive, and from spl+1 to hi inclusive. For example, if lo is 4, spl is 6, and hi is 9, returns 4+5+6 = 15 and 7+8+9 = 24. Applies simple algebra in O(1) time. """ spl_item = (spl)*(spl+1) # Saved to avoid redundant calculations. return (spl_item-(lo)*(lo-1))//2, ((hi)*(hi+1)-spl_item)//2 def actual_sums(lst,lo,spl,hi): """Returns the actual lower sum and actual higher sum. Given a list and positive integers lo, spl, and hi, returns the sum of all elements in the list from lo to spl inclusive, and from spl+1 to hi inclusive. Runs in O(n) time. """ lo_sum, hi_sum = 0,0 for num in lst: if lo <= num and num <= spl: lo_sum += num elif spl < num and num <= hi: hi_sum += num return lo_sum, hi_sum # The below "speed test" checks how many scans of the list are required and # verifies that the behavior predicted above is occurring. # For example, with n=50, we see: # 1225 total trials. = 50*49/2 unique input pairs # min: 1 ~ Half of inputs require only one pass. # max: 5 Worst case: floor(log(50)) passes. # avg: 1.876734693877551 # And with n=1000: # 499500 total trials. = 1000*999/2 unique input pairs # min: 1 ~ Half of inputs require only one pass. # max: 9 Worst case: floor(log(1000)) passes. # avg: 1.989149149149149 AVG # of passes approaches 2. def speed_test(n): """Tests runtime of f6. Given an integer N, tests f6's performance over an input list for all unique pairs of missing integers X and Y such that X < Y < =N. Records the number of scans over the list that were required to determine the output, and aggregates and prints statistics of these. """ all_counts = [] for lo in range(1,n+1): print(f"Testing missing pairs with {lo} as lo...") for hi in range(lo+1,n+1): bob = [x for x in range(1,n+1) if (x!=lo and x!=hi)] all_counts.append(f6(bob,True)) all_counts.sort() min,max = all_counts[0],all_counts[-1] avg = sum(all_counts) / len(all_counts) print(f"{len(all_counts)} total trials") print(f" min: {min}") print(f" max: {max}") print(f" avg: {avg}") # Interestingly, the book suggested a different "equation-based" approach that # calculates the sum, and then sum of squares of inputs. This approach does # not fail on larger inputs the way f4 did, does not calculate factorials # which quickly overflow the way f3 did, so it is the superior equation-based # function. Like my informal proof above with X-A and Y+A, it can be shown by # solving quadratic equations that only unique pairs of integers have both the # same sum and same sum of squares. def f7(lst): """See f3 docstring.""" n = len(lst) + 2 S1 = (n)*(n+1)//2 - reduce(add,lst) S2 = reduce(add,squares(range(1,n+1))) - reduce(add,squares(lst)) disc = sqrt(2*S2-S1*S1) # Discriminant of the quadratic equation. return int((S1-disc)/2), int((S1+disc)/2) def squares(it): """Yields squares of iterator items 1-by-1 instead of O(N) list.""" for item in it: yield item**2 # We confirm accuracy of f5, f6, and f7 below. (On small inputs, f3 and f4 # could also be tested, but I am reserving the tests only for the "best" of # each of the three types of approaches I worked with for this problem.) def accuracy_test(n,trials): """Tests correctness of the best equation-based approach, f7, the probabilistic approach, f6, and the sort-based approach, f5. Given an integer N, tests correctness over an input list for all unique pairs of missing integers X and Y such that X < Y <= N. For each pair, a new input list is created and shuffled trials times, as f5 has different behavior based on the order of items in the input. Raises: AssertionError: At least one among f5, f6 and f7 is incorrect. """ for lo in range(1,n+1): print(f"Testing missing pairs with {lo} as lo...") for hi in range(lo+1,n+1): for _ in range(trials): lst = [x for x in range(1,n+1) if (x!=lo and x!=hi)] shuffle(lst) assert (lo,hi) == f7(lst) assert (lo,hi) == f6(lst) assert (lo,hi) == f5(lst) # Modifies input so do last.
201eb517d7b66b5bb4c7bdd2ef7ebe37b5c1e5bd
jake-albert/py-algs
/c17/c17p11.py
9,202
4.03125
4
from random import randint # c17p11 # Word Distance: You have a large text file containing words. Given any two # words, find the shortest distance (in terms of number of words) between them # in the file. If the operation will be repeated many times for the same file # (but different pairs of words), can you optimize your solution? ############################################################################## # I assume that I have access to an NLP tokenizer like from the NLTK library # in Python that handles punctuation, hyphenation etc. consistently when # parsing files. So I abstract the text file as a list of ints. # I assume for this question that the distance between two word instances in # the file is the absolute value of the difference between the two indices of # the words. This means that A) it does not matter if a greater index comes # before a lesser index; distance is always POSTIVE, and B) there is no # "wrapping around" from the end of a file to the start. The first and last # words of the file/list are the two words with the greatest distance. # My first thought on how to solve this problem was that storing info on word # connectedness in a graph would be helpful. Say we create a new node for # each unique word in the document and add edges between words that somewhere # in the document are adjacent. Then, couldn't we simply call bidirectional # search over this graph to find the shortest path between two words? # It turns out that this give a different kind of "shortest distance" between # words than what we are interested in, because allowing one node to # represent every instance of a word in the text allows us to "jump" between # instances of a word without adding any distance cost when we should not. # Ex. "MY DOG IS THE BEST DOG IN THE WORLD BETTER THAN THE BLUE DOG." # # Shortest path in the above graph from "MY" to "BLUE" is just 2; # from "MY" to "DOG", then a "jump" from that "DOG" to the last # "DOG" that costs nothing, then from that "DOG" to "BLUE". The # correct shortest distance is 12. # Another idea involves storing indices to words in some way that lets us # calculate word distances easily. My solution below begins by reading the # text (list) once in O(N) time, where N is the word length of the text, and # storing in a dictionary the indices of all occurrences of each word. # The trick is that because we read and store indices in increasing order, # the problem reduces to taking two sorted lists of integers and finding the # smallest absolute value difference between any two integers from each list, # which can be done in O(L1+L2). L1 and L2 being lengths of the lists, which # here correspond to the number of instances of each word in the document. # This approach allows us to find the shortest distance between any two words # quite quickly, but for very long documents the most common words might # occur so often in a document that it would be helpful to calculate the # shortest distance between them and other words overnight so they may be # returned in O(1) time. This would require an extra O(M^2) storage, where M # is the number of words among which we want to store distances ahead of time, # or O(M*N) time if we want to for some M words store their distances from # every other word for O(1) time lookup. # Whether we would want to actually do this, though, depends on specific time # and memory costs related to the type of document we are storing and what # words we expect to be looked up most often. # I first implement the O(L1+L2) algorithm and test it against an O(L1*L2) # brute-force algorithm for correctness: def smallest_difference(lst_a,lst_b): """Given two lists of integers sorted in increasing order, returns the smallest absolute value difference between any two integers from each list. Args: lst_a, lst_b: Lists of ints. Returns: An int. """ # I define difference as undefined when at least one list is empty. if len(lst_a) == 0 or len(lst_b) == 0: return None mindiff = float("inf") index_a, index_b = 0, 0 while index_a < len(lst_a) and index_b < len(lst_b): if lst_a[index_a] == lst_b[index_b]: # Best possible diff. return 0 mindiff = min(mindiff,abs(lst_a[index_a]-lst_b[index_b])) # Since the lists are sorted, only advancing further into the # list with the smaller element has a chance of resulting in a # DECREASED difference between the elements. if lst_a[index_a] < lst_b[index_b]: index_a += 1 else: index_b += 1 # Once one list has been fully traversed, we know that every yet # unseen value in the other list is greater than or equal to the # greatest value in the finished list. So diff cannot decrease. return mindiff def sd_brute(lst_a,lst_b): """O(L1*L2) version of above function.""" if len(lst_a) == 0 or len(lst_b) == 0: return None mindiff = float("inf") for index_a in range(len(lst_a)): for index_b in range(len(lst_b)): mindiff = min(mindiff,abs(lst_a[index_a]-lst_b[index_b])) return mindiff def test(trials,L1,L2): """Tests smallest_difference against sd_brute on random inputs. Args: trials: An int. Number of inputs to make and test. L1,L2: Ints >= 0. Lengths of input lists to test. Raises: AssertionError: The functions' output is different. """ MAXVAL = max(L1,L2)**4 for trial in range(trials): lst_a = sorted([randint(0,MAXVAL) for _ in range(L1)]) lst_b = sorted([randint(0,MAXVAL) for _ in range(L2)]) assert smallest_difference(lst_a,lst_b) == sd_brute(lst_a,lst_b) # With that work done (arguably, the "real work" part of the problem), I wrote # a word dictionary that supports finding shortest distances between words # that actually works on text files. I wrote a rudimentary word "parser" that # defines "words" as longest possible sequences of consecutive, non-whitespace # characters. (I guess I could also just install NLTK.) def words_from_text(filepath): """Generator that yields words one by one from a file. Treats whitespace characters as word boundaries, and greedily treats as many non-whitespace characters as possible as one word. All words are converted to lower-case before being yielded. Args: filepath: A string. Yields: Strings of non-whitespace characters. Raises: FileNotFoundError: filepath does not lead to a file. """ try: with open(filepath,"r") as f: for line in f: read = 0 while read < len(line): while read < len(line) and line[read].isspace(): read += 1 start_char = read while read < len(line) and not line[read].isspace(): read += 1 if read > start_char: yield line[start_char:read].lower() except FileNotFoundError as e: print(e) class FileDict: """Stores documents in a way to support word distance queries. Attributes: lookup: A dictionary from strings to indices of occurrences of those strings in the document. """ def __init__(self,filepath): """Inits a FileDict in O(N) time (N: word count). Args: filepath: A string path to the document. """ self.lookup = self._load_dict(filepath) def _load_dict(self,filepath): """Loads each word occurrence into lookup.""" lookup = {} index = 0 for word in words_from_text(filepath): if word not in lookup: lookup[word] = [index] else: lookup[word].append(index) index += 1 return lookup def word_distance(self,w1,w2): """Returns the shortest distance between any occurrences of two words in a document, or None if at least one word does is not in the document. Args: w1,w2: Strings. Returns: An int, or None. """ if w1 not in self.lookup or w2 not in self.lookup: return None return smallest_difference(self.lookup[w1],self.lookup[w2]) def toy_test(): """Tests a toy example.""" fd = FileDict("c17p11.txt") triples = [("this","is",1), ("purposes","bananas",4), ("parts","test",56), ("test","parts",56), ("this","the",2), ("missing_word","bananas",None)] for w1,w2,d in triples: assert fd.word_distance(w1,w2) == d
d95a3e695cf3726436afe59d60e5284555c3b2e1
jake-albert/py-algs
/c16/c16p06.py
3,878
3.71875
4
# c16p06 # Smallest Difference: Given two arrays of integers, compute the pair of # values (one value in each array) with the smallest (non-negative) # difference. Return the difference. # EXAMPLE # Input: {1, 3, 15, 11, 2}, {23, 127, 235, 19, 8} # Output: 3. That is, the pair (11, 8). ############################################################################## # The most straightforward way is to compare each of the M vals in the first # array against each of the N vals in the second, returning the min difference # we find. This can be done in O(MN) time. # One improvement that we can make to this is sort the two lists, and then # upon reading all values from lowest to highest, record a difference only # when switching from one list to another. On the example input: # [1,3,15,11,2] and [23,127,235,19,8] # We sort each getting # [1,2,3,11,15] and [8,19,23,127,235] # Then, place read heads at both 1 and 8. We see that the min is 1, and then 2, # and then 3, all in the same list. Next is 8, and only then do we change to # read from a different list. So we record 8-3 which is 5. Next smallest value # is 11, and we record 11-8 to find a better difference of 3. # Important is to remember the case where all values in one list are less than # all values in a second list. [1,2,3,4] and [7,8,9,10] has a min diff of 3. # Sorts takes O(MlogM + NlogN) time, and reading heads O(M+N) time, so overall # the function needs O(MlogM + NlogN) time and requires O(1) space assuming # the sorts are implemented in place, such as with quicksort. We assume that # the input is correctly formed (no non-integer objects in the lists). def f1(A,B): """Returns the difference between the pair of values with the smallest non-negative difference, one from each input array. Args: A: A list of integers. B: A list of integers. Returns: An integer difference, or None if at least one of A or B is empty. """ if len(A) < 1 or len(B) < 1: return # We sort the lists in place, but if it is required that the # original input not be modified, then copying is required. A.sort() B.sort() min_diff = float("inf") read_a, read_b = 0, 0 # Heads are indices. prev_lst = None # Previous list with minimum val. # We can halt when we have reached the end of one list. while read_a < len(A) and read_b < len(B): if A[read_a] < B[read_b]: cur_lst = A cur_val = A[read_a] next_a, next_b = read_a+1, read_b elif B[read_b] < A[read_a]: cur_lst = B cur_val = B[read_b] next_a, next_b = read_a, read_b+1 else: # If the two values are equal, return immediately. return 0 # Check for a min difference only when read head switches. if prev_lst is not None and cur_lst is not prev_lst: diff = cur_val - prev_val if diff < min_diff: min_diff = diff read_a, read_b = next_a, next_b prev_lst = cur_lst prev_val = cur_val # One last check is required after exiting the loop. Find the # "last value" to check, which is the value at whichever read head # has not yet traversed all of its list, and find the difference # between this last value and the previous value seen. Return the # minimum of this difference and the minimum difference seen so far. last_val = A[read_a] if read_b >= len(B) else B[read_b] diff = last_val - prev_val return min(diff,min_diff) def test(): """Tests some example inputs. """ assert f1([1,3,15,11,2],[23,127,235,19,8]) == 3 assert f1([5,6,77,35,78,1,45,98],[245,676,111,344,766,800]) == 13
5db74f2976c19b396a624c8518aab5f7de051164
jake-albert/py-algs
/other_practice/p02_grid.py
7,335
4.15625
4
# The class below simulates a valid grid for p02 as it is produced and has # methods that make writing the recursive algorithm in p02.py very easy. # It could be redesigned to handle square grids of any dimension with some # effort, so long as the rules for valid rows and columns are clarified. (Ex. # What values are allowed in each square? What kinds of "straights" are # permitted? What kinds of special combinations like "248" are permitted?). # But because these rules are not defined, the class is "hard-coded" to handle # only a dimension of 3, and only 1-9 as permitted values in each square. It # thus does NOT define attributes like "DIM", "MINVAL", and "MAXVAL", which is # generally good practice but here could give the impression that the class is # easily modifiable to other cases. class Grid: """Simulates a grid in progress of being filled in with digits according to the rules described above. Attributes: BLANK: An integer representing a blank square. Here, -1. sqs: A list of length 9 representing the squares of the grid, top left to bottom right. """ BLANK = -1 def __init__(self): """Inits Grid to be entirely blank.""" self.sqs = [self.BLANK] * 9 def is_blank(self,i): """Returns True if ith square is blank, False otherwise.""" return self.sqs[i] == self.BLANK def set_square(self,i,dig): """Sets the ith square of the grid to hold a digit.""" if dig < 1 or dig > 9: raise ValueError("Invalid input: Digit must be integer 1 to 9.") self.sqs[i] = dig def clear_square(self,i): """Sets the ith square back to a BLANK value.""" self.sqs[i] = self.BLANK def display(self): """Pretty prints the grid.""" print(" _____") for i in range(len(self.sqs)): if i%3 == 0: print("|",end="") if i%3 == 2: print(self.sqs[i],end="") print("|",end="\n") else: print(self.sqs[i],end=" ") print(" ¯¯¯¯¯") def all_valid_digits(self,i): """Returns an iterable containing each of the digits 1-9 that may be placed at the ith square without violating any row or column rules. Assumes that the ith square is blank. """ # The other digits in the ith square's row and column set # constraints on which digits are valid. If no constraints, # then all digits are valid. If only one of the row and column # constrains to a set of digits, then those digits are returned # immediately. Otherwise, the sets' intersection is returned. rds, cds = self._row_digits(i), self._column_digits(i) if rds is None and cds is None: return range(1,10) elif rds is None: return self._valid_digits(cds) elif cds is None: return self._valid_digits(rds) else: rvds, cvds = self._valid_digits(rds), self._valid_digits(cds) return rvds.intersection(cvds) def _row_digits(self,i): """Returns the digits in the same row as the ith square, or None if no such digits exist. Assumes that the ith square is blank. """ i0 = i//3*3 # ex. "3" for 3,4,5. digs = [self.sqs[j] for j in range(i0,i0+3) if not self.is_blank(j)] return self._format_digs(digs) def _column_digits(self,i): """Returns the digits in the same column as the ith square, or None if no such digits exist. Assumes that the ith square is blank. """ i0 = i%3 # ex. "2" for 2,5,8. digs = [self.sqs[j] for j in range(i0,i0+7,3) if not self.is_blank(j)] return self._format_digs(digs) def _format_digs(self,digs): """Ensures that the digits are returned as a list in increasing order, or the None object if there are no digits. When called by functions like row_digits and column_digits, the input digs list is guaranteed to hold at most 2 digits. """ if len(digs) == 0: return None elif len(digs) == 1: return digs else: return [min(digs[0],digs[1]), max(digs[0],digs[1])] def _valid_digits(self,ds): """Given a list of either one or two digits from the same group (a row or column), returns a set of valid digits that can join this group. """ if len(ds) == 1: return self._valid_digits_one(ds[0]) else: return self._valid_digits_two(ds) def _valid_digits_one(self,d): """Given a single digit, returns the set of valid digits that could be added to a group with that digit. For example, if d is 1, returns {1,2,3,4,5,7}. 6,8,9 cannot exist in the same group as 1 so they are left out. """ # Digits can form a 0-straight, 1-straight, 2-straight, or # 3-straight of values (order not mattering). This means that # if a group contains a single number d, any digit that is # within plus-or-minus 0,1,2,3,4, or 6 may join that group. # (So long as it is within range of 1-9 inclusive.) # The special case of group [2,4,8] is already handled here, as # each of the values of this group are within 2,4, or 6 of one # another. diffs = [x for x in range(-4,5)] diffs.append(-6) diffs.append(6) return {d+diff for diff in diffs if 0<d+diff<10} def _valid_digits_two(self,ds): """Given a list of two digit, returns the set of valid digits that could be added to complete a group with those digits. For example, if d is [5,7], returns {3,6,9}. Other digits cannot be added. Assumes that the list ds is sorted in increasing order. """ output = set() # One possibility to complete a group would be to be an # "external" addition to a straight that extends the pattern. # These include going up ([2,4] and then 6) and going down # ([8,9],and then 7.). 0-straights are also handled the same. diff = ds[1] - ds[0] if 0 <= diff <= 3: candidate1 = ds[1] + diff candidate2 = ds[0] - diff if candidate1 < 10: output.add(candidate1) if candidate2 > 0: output.add(candidate2) # Another possibility to complete a group would be to be an # "internal" addition ([2,8] with 5 in the middle). This case # occurs only when the two digits' average is an integer. sum = (ds[0]+ds[1]) if sum % 2 == 0: output.add(sum//2) # Valid digits from the special "248" case handled separately. if ds == [2,4]: output.add(8) elif ds == [4,8]: output.add(2) elif ds == [2,8]: output.add(4) return output
4bebbaa17b0ec98c097929740b8bfa9faba7cd84
jake-albert/py-algs
/data_structs/queue.py
2,454
4.03125
4
from .doubly import Doubly from collections import deque class LinkedListQueue: """Queue implemented with my doubly linked list class. Attributes: queue: A Doubly instance that simulates the queue. """ def __init__(self,loads=None): """Inits an empty LinkedListQueueQueue by default. If loads is not None and non-empty, loads items into queue such that the first item in loads is the first that will be removed.""" if loads is not None: self.queue = Doubly(loads) else: self.queue = Doubly() def __len__(self): return self.queue.size def add(self, item): """Adds an item in O(1) time.""" self.queue.insert_head(item) def remove(self): """Removes and returns the least-recently added item in O(1) time. Returns None if queue is empty.""" if not self.is_empty(): return self.queue.remove_tail() def peek(self): """Returns the least-recently added item in O(1) time. Returns None if queue is empty.""" if not self.is_empty(): return self.queue.tail.val def is_empty(self): """Returns a Boolean.""" return self.queue.size == 0 class DequeQueue: """Queue implemented with the Python deque object. Attributes: queue: A deque object.""" def __init__(self,loads=None): """Inits an empty DequeQueue. If loads is not None and non-empty, loads items into queue such that the first item in loads is the first that will be removed.""" self.queue = deque() if loads is not None: for load in loads: self.add(load) def __len__(self): return len(self.queue) def add(self,item): """Adds an item in O(1) time.""" self.queue.appendleft(item) def remove(self): """Removes and returns least-recently added item in O(1) time. Raises: IndexError: queue is empty. """ return self.queue.pop() def peek(self): """Returns least-recently added item in O(1) time. Raises: IndexError: queue is empty. """ return self.queue[-1] def is_empty(self): """Returns a Boolean.""" return len(self.queue) == 0
987837642c25fe151af6d7f60ba30e3125585ff7
jake-albert/py-algs
/c16/c16p26.py
8,444
3.90625
4
from operator import add, sub, mul, truediv from random import randint # c16p25 # Calculator: Given an arithmetic expression consisting of positive integers, # +, -, * and / (no parentheses), compute the result. # # EXAMPLE # Input: 2*3+5/6*3+15 # Output: 23.5 ############################################################################## # The text does not seem to give any indication of the format of the input. It # seems most plausible that this would be a string of characters such as "5" # or "6+87/23". # If we are not so concerned with minimizing memory, then we could parse the # full input string in order to populate some data structure such as a list # (for example, ["2","*","13","+","55","/","6","*","3"]), a linked list, or # stacks that would (perhaps) make implementing the calculator simpler. With # the linked list, for example, we could make one "scan" from left to right # that, for each "*" and "/" operator it encounters in a node, replaces the # previous node, current operator node, and following node with the result # of that computation, and then moves on, and then repeat this process with # "+" and "-" until only one node remains. This data structure would, of # course, require O(N) space. # On the other hand, if we are concerned about optimizing memory usage (which # admittedly might not be a high priority in most use cases for this problem, # but could plausibly become a priority if inputs ever increase to having tens # of thousands of integers), we can also compute the result using O(1) extra # space by carefully reading integers and operator symbols from the string and # aggregating them in the correct order. I implement that function. # (Pedantically speaking, since there is no limit to the size of integers in # the input, it is possible that the input string consists of only one integer # that must be read and stored by the function before returning, so in reality # we can cap memory requirements only at O(logN), where N is the character # length of the input, even though the number of distinct integers and # operations that we allocate memory for is in O(1).) # My function raises a ValueError when the input is invalid; that is, when it # cannot match the regex a(ba)*, where a is the string representation of some # positive integer, and b is one of "+", "-", "*", or "/". # ALSO, an important note about associativity. We obviously must be careful to # get correct the order of operations in an expression like "3+2*2" and thus # cannot blindly calculate operations from left to right. But because we are # working with the true division operator and float results, the order that we # compute results even within a sequence of "mutually associative" operations # makes a difference as well: # >>> 69*31/59 # 36.25423728813559 # >>> (69*31)/59 # 36.25423728813559 # >>> 69*(31/59) # 36.2542372881356 # In order to truly replicate the behavior of the Python interpreter, it is # important that we greedily compute operations from left to right whenever # possible, rather than perform these operations in a different order, even # though the fractional value of the result would not change (above, 2139/59). # Alternatively, we could store a running tab of the result to return using # Python's Fraction class, and then only at the end output a decimal form. In # that case, the relative order of multiplications and divisions would not # make a difference. (This approach might also be faster, as we would avoid # floating-point arithmetic until the end? I would have to look more into how # the Fraction class implements its operations.) def f1(exp): """Given a string representing an arithmetic expression of positive integers, computes and prints the result. Args: exp: A string. Should match the regex a(ba)*, where a is some number of digits representing a positive integer, and b is one of "+", "-", "*", or "/". Returns: An float if the division operator is in the input, and an integer otherwise. Raises: ValueError: exp is empty or is improperly formed. ZeroDivisionError: exp calls for dividing by zero. """ if len(exp) == 0: raise ValueError("Empty expression, undefined result.") output, i = get_next_int(exp,0) if i == len(exp): return output # At all times, we keep track of a running value for the expression # as it is calculated from left to right, the operator and integer # (the "argument") that follow, and the next operator after that # (or None if no such operator exists). # out op arg nop # 55 + 3 * 6 ... op, i = get_next_op(exp,i) arg, i = get_next_int(exp,i) nop, i = get_next_op(exp,i) while nop is not None: # We aim to calculate (out op arg) as soon as we possibly can. # When op is * or /, we can do this immediately and "shift" op, # arg, and nop to the right. But when op is + -, we must first # compute ALL consecutive * or / operations from nop to the # right, which might include the final operation in the string. if (op is add) or (op is sub): while (nop is not add) and (nop is not sub): narg, i = get_next_int(exp,i) arg = nop(arg,narg) nop, i = get_next_op(exp,i) if nop is None: return op(output,arg) output = op(output,arg) op = nop arg, i = get_next_int(exp,i) nop, i = get_next_op(exp,i) return op(output,arg) def get_next_int(exp,i): """Returns the integer beginning at the ith index in a string. Args: exp: A string. i: An int index where a positive integer is expected to begin. Returns: The integer value, and a new index 1 to the right of where the integer ends in the string. Raises: ValueError: There is no positive integer at index i. IndexError: i is out of range. """ if i == len(exp): raise ValueError(f"Integer expected at index {i}.") if not exp[i].isnumeric(): raise ValueError(f"Non-numeric char found at index {i}.") val = 0 while i < len(exp) and exp[i].isnumeric(): val = val*10 + int(exp[i]) i += 1 return val, i def get_next_op(exp,i): """Returns the operator represented at the ith index of a string, or None if i is at the end of the string. Args: exp: A string. i: An int index where an operator symbol is expected. Returns: An function object or None, and min(i+1,len(exp)). Raises: ValueError: There is an unexpected character at index i. """ if i == len(exp): return None, i if exp[i] == "+": return add, i+1 elif exp[i] == "-": return sub, i+1 elif exp[i] == "*": return mul, i+1 elif exp[i] == "/": return truediv, i+1 else: raise ValueError(f"Failed to find valid operator at index {i}.") def test(max_ops,trials,max_int): """Tests f1 against the Python interpreter's performance on randomly generated input strings of increasing lengths. Args: max_ops: An int. Number of operations in longest test input. trials: An int. Number of strings to test per op count. max_int: An int. Highest value that may be part of a string. Returns: None. Prints any input with discrepancies between f1 and interpreter. """ for n_ops in range(max_ops+1): for _ in range(trials): str = generate_input(n_ops+1,max_int) if f2(str) != eval(str): print("f2 issue:",str) def generate_input(c,max_int): """Returns a string representing an arithmetic expression with c random integers from 1 to max_int (inclusive), and c-1 operations randomly selected from plus, minus, multiply, and divide. """ ops = ["+", "-", "*", "/"] builder = [] for _ in range(c-1): builder.append(str(randint(1,max_int))) builder.append(ops[randint(0,len(ops)-1)]) builder.append(str(randint(1,max_int))) return "".join(builder)
a4185becd747eea6db3e191612d83b9daf9eea53
jake-albert/py-algs
/c17/c17p02.py
3,613
4.125
4
from random import randint from math import factorial from statistics import median, stdev # c17p02 # Shuffle: Write a method to shuffle a deck of cards. It must be a perfect # shuffle-in other words, each of the 52! permutations of the deck has to be # equally likely. Assume that you are given a random number generator which is # perfect. ############################################################################## # I assume that the perfect random number generator outputs random integers in # any specified range. I use Python's randint() function to simulate the RNG, # and abstract a deck of cards as a list of length 52. (In fact, this solution # works to shuffle Python lists of any length.) # First, we must pick with equal probability some card out of the 52 to occupy # the "top" of the deck, or the 0th-indexed position in the list. Having done # this, we need to pick one of the the remaining 51 cards with equal # probability to occupy the second position, and so on. We can do this in # place on the list by swapping values. # Assuming that each call to randint() returns in O(1) time, this shuffle # algorithm runs in linear time to length of the input. Since it is written # iteratively rather than recursively, it requires O(1) memory. def f1(lst): """Shuffles a list of length N so that all N! permutations are equally likely. The list is shuffled in place. Args: lst: A list of objects. """ for i in range(len(lst)-1): # No need to swap the final value. selection = randint(i,len(lst)-1) lst[i], lst[selection] = lst[selection], lst[i] def test(N,trials): """Tests the shuffle function and prints some rudimentary results. Args: N: An int. The length of the list to shuffle. trials: An int. The number of shuffles to perform. """ occurrences = {} for t in range(trials): if trials > 10 and t % (trials//10) == 0: print(f"Trial:{t:10} ({100*t/trials:2.0f}%)") lst = list(range(N)) f1(lst) key = tuple(lst) # Hashable version of the shuffle. if key not in occurrences: occurrences[key] = 1 occurrences[key] += 1 print("\nRESULTS:\n") fact = factorial(N) print(f"Expected distinct shuffles: {fact}") print(f"Actual distinct shuffles : {len(occurrences.items())}\n") print(f"Expected hits per shuffle : ~{trials//fact:8}") lo_q, med, hi_q = get_qs(occurrences.values()) print(f"Lower quartile of shuffle hits : {lo_q:8}") print(f"Median : {med:8}") print(f"Upper quartile : {hi_q:8}\n") print(f"Expected probability of each shuffle: {100/fact:.4f}%") sigma = stdev([100*occ/trials for occ in occurrences.values()]) print(f"StdDev of probabilities : {sigma:.4f}%") if N <= 5: # Do not print all shuffles when N! is too large. print("") print("Shuffle: Hits (Percentage)") for k,v in sorted(occurrences.items()): print(f"{k}: {v:6} ({100*v/trials:7.4f}%)") # I use the rudimentary function below rather than use a more sophisticated # library like numpy or pandas to get quartile information. def get_qs(lst): """Returns (rough) Q1, Q2, and Q3 values of a list.""" sorted_lst = sorted(lst) mid = len(sorted_lst) // 2 lo_q = int(median(sorted_lst[:mid])) med = int(median(lst)) hi_q = int(median(sorted_lst[mid:])) return lo_q, med, hi_q
cbffb60b5392afe5b4198d7cd342002ca5847345
bastih/banana
/examples/calculator/scenarios/rules.py
613
3.71875
4
from banana import matches from calculator import Calculator @matches(r'^Given the user opens the calculator$') def calculusInit(t): t.calculator = Calculator() @matches(r'^When entering (\d+) and (\d+)$') def calcAddNums(t, num1, num2): t.calculator.num1 = int(num1) t.calculator.num2 = int(num2) @matches(r'^When entering (\d+\s,?)+$') def calcGroupedAdd(t, *args, **kwargs): print args, kwargs @matches(r'^Expect a result of (\d+)$') def expectedResult(t, result): assert t.calculator.sum() == int(result), "Correct result should be %s but is %s" % (int(result), t.calculator.sum())
f9d2ca5e97c35550587983c9ef35770a83cecc2e
tjvonbr/interview_prep
/interview_prop_python/goodrich_practice/minmax.py
208
4
4
def minmax(arr): min = arr[0] max = arr[0] for i in arr: if i < min: min = i elif i > max: max = i else: continue print((min, max)) print(minmax([1, 9, 0, -1, 15]))
ef40d6026aee4d666ef8a15c7b2b5083e69a85cb
pl80tech/CarND-PID-Control-Project
/log/data_visualize.py
1,813
3.546875
4
# Script to visualize multiple log in a figure & save to image for easy comparison # # How to use: # $ python data_visualize.py arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 # arg1 --> log file 1 # arg2 --> log file 2 # arg3 --> log file 3 # arg4 --> title of the figure # arg5 --> x label of the figure # arg6 --> y label of the figure # arg7 --> legend for log 1 # arg8 --> legend for log 2 # arg9 --> legend for log 3 # arg10 --> save file # Import the required packages import random import numpy as np import matplotlib.pyplot as plt import sys # Get the data from log and set x, y coordinate def getLogData(logfile): logline = open(logfile, "r").readlines() cte = [0] * len(logline) x = [0] * len(logline) for i in range(len(logline)): cte[i] = float(logline[i].strip('\n')) x[i] = i return x, cte # Set x, y coordinate for center line def getCenterLine(len): x = [0] * len y = [0] * len for i in range(len): x[i] = i return x, y # Get x, y coordiante from the log files (passed from command line) x1, cte1 = getLogData(sys.argv[1]) x2, cte2 = getLogData(sys.argv[2]) x3, cte3 = getLogData(sys.argv[3]) # Number of iterations to be visualized n_iteration = min(len(x1), len(x2), len(x3)) # Get x, y coordinate for center line center_x, center_y = getCenterLine(n_iteration) # Plot multiple data in a same figure plt.plot(x1[0:n_iteration-1], cte1[0:n_iteration-1]) plt.plot(x2[0:n_iteration-1], cte2[0:n_iteration-1]) plt.plot(x3[0:n_iteration-1], cte3[0:n_iteration-1]) plt.plot(center_x, center_y) # Add title, label and legend plt.title(sys.argv[4]) plt.xlabel(sys.argv[5]) plt.ylabel(sys.argv[6]) plt.legend([sys.argv[7], sys.argv[8], sys.argv[9]]) # Save visualized data to image file savefile = sys.argv[10] plt.savefig(savefile) # Show on screen plt.show()
6490618fda77e8b9c88590f5b9a2af5a597c04db
daverave1212/Ppender
/config.py
922
3.578125
4
def parse_config_file(): with open('config.cfg', 'r') as f: # Parse the config file text = f.read() lines = text.split('\n') pairs = [line.split('=') for line in lines if (not line.isspace() and not len(line) == 0)] config = {} for pair in pairs: config[pair[0].strip()] = pair[1].strip() setup_config(config) return config def setup_config(config): print(config) if config['TEXT'] == 'None': print('Type in the phrase you want to paste with F3:') config['TEXT'] = input() print('Ok: ' + config['TEXT']) config['RENAME_PRESS_F2'] = to_bool(config['RENAME_PRESS_F2']) config['RENAME_PRESS_ENTER'] = to_bool(config['RENAME_PRESS_ENTER']) config['CUT_INSTEAD_OF_COPY'] = to_bool(config['CUT_INSTEAD_OF_COPY']) def to_bool(string): return True if string in ['True', 'true', 'yes', '1'] else False
a1ed74f09083aa09de21700ccf76cd27b4e56365
SotirisKavv/AdventOfCode2020
/day1/product.py
972
3.515625
4
def readFile(filename): f = open(filename) words = f.read().splitlines() words = [int(i) for i in words] f.close() return words def candidate2Product(arr, val): i = 0 j = len(arr) - 1 arr.sort() while i < j: a = int(arr[i]) b = int(arr[j]) if a + b < val: i=i+1 elif a + b > val: j=j-1 elif a + b == val: return a*b return 0 def candidate3Product(arr, val): arr.sort() for i in range(0, len(arr)): j = i + 1 k = len(arr) - 1 a = int(arr[i]) while j < k: b = int(arr[j]) c = int(arr[k]) if a + b + c < val: j=j+1 elif a + b + c > val: k=k-1 elif a + b + c == val: return a*b*c return 0 entries = readFile('input1') print(candidate2Product(entries, 2020)) print(candidate3Product(entries, 2020))
886dc39d2bb61f93ac6d8769b059f38cb7cf34ae
andrewghaly/KMeans-1
/pa6-calendar-student-1/plotK.py
7,180
3.796875
4
import matplotlib.pyplot as plt import numpy as np from math import sqrt import random colors = list('cmyk') class Centroid: def __init__(self, color, position): self.color = color self.position = position self.coordinateList = list() def euclid(self, b): """ Euclidean Distance Algorithm for two points sqrt((x1-x2)^2 + (y1-x2)^2)) """ x, y = self.position input_x, input_y = b.position return sqrt((x - input_x) ** 2 + (y - input_y) ** 2) def manhattan(self, b): """ Manhattan Distance Algorithm for two points abs(x1-x2) + abs(y1y2) """ x,y = self.position input_x, input_y = b.position return abs(x-input_x) + abs(y-input_y) def plot(self): """Adds point to the current plot""" x, y = self.position plt.scatter(x, y, s=250, marker=u'^', color=self.color, zorder=5) def computePosition(self): """Computes the mean of all points in self.coordinateList()""" if self.coordinateList: x_value_list = list() y_value_list = list() for i in self.coordinateList: x, y = i.position x_value_list.append(x) y_value_list.append(y) self.position = (np.mean(x_value_list), np.mean(y_value_list)) def equals(self, input_position): """Checks if two Centroids are in the same position""" if input_position[0] == self.position[0] and input_position[1] == self.position[1]: return True else: return False def __str__(self): stringRep = str( "Centroid ({0}, {1}), has {2} points".format(round(self.position[0], 2), round(self.position[1], 2), len(self.coordinateList)) ) return stringRep class Coordinate: def __init__(self, position, color): self.position = position self.color = color def plot(self): """Adds point to the current plot""" x, y = self.position plt.scatter(x, y, marker="o", color=self.color, alpha=.35, s=75) def plotCoordinates(coordinateList, centroidList): """ Plots the individual points on the map Find the closest centroid to a given coordinate Add that point to the centroidList and plot it on the map """ # Reset the coordinateList for each Centroid for current_centroid in centroidList: current_centroid.coordinateList = list() # Calculate the nearest Centroid # Append it to the Centroid's coordinate list # Color the coordinate the same as the Centroid for coordinate in coordinateList: # Get a list of all the distances to the Centroids distanceList = list() for centroid in centroidList: distanceList.append(centroid.euclid(coordinate)) # Gets the lowest numerical distance to a centroid minDistance = min(distanceList) # Find the index of the closest distance # Use that index to get the closest Centroid # Apply all the properties to the Coordinate for i in range(len(centroidList)): temp_distance = distanceList[i] if temp_distance == minDistance: closestCentroid = centroidList[i] closestCentroid.coordinateList.append(coordinate) coordinate.color = closestCentroid.color coordinate.plot() def plotCentroids(centroidList): """ Plots centroids on to graph""" for centroid in centroidList: centroid.plot() def plotGraph(inCentroidList, inCoordinateList): """ Plot the centroid and Coordinates Apply the axis to the graph window """ plotCentroids(inCentroidList) plotCoordinates(inCoordinateList, inCentroidList) plt.xlabel('# of tests passed', fontsize=16, style='italic') plt.ylabel('# of tests passed (weighted) ', fontsize=16, style='italic') for centroid in inCentroidList: print centroid print "\n" plt.show() def generateUniqueCentroids(k, dataList): """ Generates a list of centroids used in the k-Means graph Selects k-unique coordinates that exist within the data Returns the set of coordinates """ uniqueCoordinateList = list() # Find all unique coordinates in the list for coordinate in dataList: # Check that it's not already in the set if coordinate not in uniqueCoordinateList: uniqueCoordinateList.append(coordinate) # Generate k-number of random coordinates centroidList = list() while len(centroidList) != k and uniqueCoordinateList: centroid = random.choice(uniqueCoordinateList) uniqueCoordinateList.remove(centroid) if centroid not in centroidList: centroidList.append(centroid) return centroidList def generateRandomCentroids(k, dataList): """ Generates a list of centroids used in the k-Means graph Uses the max x and y values for the upper bounds of the generated coordinates Randomly generate k-coordinates within the the bounds Returns the list of the coordinates """ # Compute the max x and y values maxY = max([yCoordinate[1] for yCoordinate in dataList]) maxX = max([xCoordinate[0] for xCoordinate in dataList]) # Selects k-number of unique x and y values # Using the bounds from maxX and maxY coordinateY = maxY * np.random.random((k, 1)) coordinateX = maxX * np.random.random((k, 1)) # Iterates through combining the values as coordinates into a list centroidList = [(coordinateX[i], coordinateY[i]) for i in range(k)] return centroidList def main(dataList, k): # Lambda function to generate a random color r = lambda: random.randint(0, 255) # Convert the coordinates into Coordinate objects # Fill it into a list plottedCoordinateList = list() for position in dataList: plottedCoordinateList.append(Coordinate(position, None)) # <-----Algorithms to generate Centroid positions-----> # This will generate k-unique coordinates from x randomCentroidList = generateUniqueCentroids(k, dataList) # Generate k-random coordinates within the data set # randomCentroidList = generateRandomCentroids(k, dataList) # <-----End Centroid Generation Algorithms-----> # Creates the list of Centroid objects plottedCentroidList = list() for centroid_position in randomCentroidList: plottedCentroidList.append(Centroid('#%02X%02X%02X' % (r(), r(), r()), centroid_position)) # Initial Centroid plotGraph(plottedCentroidList, plottedCoordinateList) # Keep plotting new graph # until positions do not change completed = 0 while completed != len(plottedCentroidList): completed = 0 for centroid in plottedCentroidList: oldPosition = centroid.position centroid.computePosition() if centroid.equals(oldPosition): completed += 1 plotGraph(plottedCentroidList, plottedCoordinateList)
3beb50957df5443a45e4547846d35f563a71f64a
rickeranderson/LinkedList_Python
/LinkedList.py
2,719
3.890625
4
#project: LinkedList #author: Rick Anderson from ListNode import ListNode class LinkedList: def __init__(self): self.head = None self.tail = None self.count = 0 def insert(self, x): self.insertAtRear(x) def insertAtRear(self, x): if (self.head == None): self.head = ListNode(x, None, None) self.tail = self.head else: tmp = ListNode(x, None, None) self.tail.next = tmp tmp.prev = self.tail self.tail = tmp self.count += 1 def insertAtFront(self, x): if(self.head == None): self.insertAtRear(x) else: tmp = ListNode(x, None, None) self.head.prev = tmp tmp.next = self.head self.head = tmp self.count += 1 def size(self): return self.count def find(self, x): current = self.head while(current != None): if(current.data == x): return current current = current.next return None def remove(self, x): current = self.find(x) if(current == None): print('Node does not exist') return if(current.prev != None): current.prev.next = current.next else: self.head = current.next if(current.next != None): current.next.prev = current.prev else: self.tail = current.prev self.count -= 1 def removeFront(self): self.head.next.prev = None self.head = self.head.next self.count -= 1 def removeRear(self): self.tail.prev.next = None self.tail = self.tail.prev self.count -= 1 def enqueue(self, x): self.insertAtRear(x) def dequeue(self): tmp = self.head self.removeFront() return tmp.data def push(self, x): self.insertAtRear(x) def pop(self): tmp = self.tail self.removeRear() return tmp def get(self, index): if index > self.count or index < 0: print('index is out of bounds') return None current = self.head for i in range(0,index): current = current.next return current.data def indexOf(self,x): current = self.head count = 0 while (current != None): if (current.data == x): return count current = current.next count += 1 return -1 def printList(self): current = self.head while(current != None): print(current.data) current = current.next
5bbce3aaa6c5a5d38b2a2848ce856322107a8c91
mirsadm82/pyneng-examples-exercises-en
/exercises/06_control_structures/answer_task_6_2a.py
1,788
4.34375
4
# -*- coding: utf-8 -*- """ Task 6.2a Make a copy of the code from the task 6.2. Add verification of the entered IP address. An IP address is considered correct if it: - consists of 4 numbers (not letters or other symbols) - numbers are separated by a dot - every number in the range from 0 to 255 If the IP address is incorrect, print the message: 'Invalid IP address' The message "Invalid IP address" should be printed only once, even if several points above are not met. Restriction: All tasks must be done using the topics covered in this and previous chapters. """ ip_address = input("Enter ip address: ") octets = ip_address.split(".") correct_ip = True if len(octets) != 4: correct_ip = False else: for octet in octets: if not (octet.isdigit() and int(octet) in range(256)): correct_ip = False break if not correct_ip: print("Invalid IP address") else: octets_num = [int(i) for i in octets] if octets_num[0] in range(1, 224): print("unicast") elif octets_num[0] in range(224, 240): print("multicast") elif ip_address == "255.255.255.255": print("local broadcast") elif ip_address == "0.0.0.0": print("unassigned") else: print("unused") # second version ip = input("Enter IP address") octets = ip.split(".") valid_ip = len(octets) == 4 for i in octets: valid_ip = i.isdigit() and 0 <= int(i) <= 255 and valid_ip if valid_ip: if 1 <= int(octets[0]) <= 223: print("unicast") elif 224 <= int(octets[0]) <= 239: print("multicast") elif ip == "255.255.255.255": print("local broadcast") elif ip == "0.0.0.0": print("unassigned") else: print("unused") else: print("Invalid IP address")
86fc4bc0e652ee494db883f657e918b2b056cf3e
mirsadm82/pyneng-examples-exercises-en
/exercises/04_data_structures/task_4_8.py
1,107
4.125
4
# -*- coding: utf-8 -*- """ Task 4.8 Convert the IP address in the ip variable to binary and print output in columns to stdout: - the first line must be decimal values - the second line is binary values The output should be ordered in the same way as in the example output below: - in columns - column width 10 characters (in binary you need to add two spaces between columns to separate octets among themselves) Example output for address 10.1.1.1: 10 1 1 1 00001010 00000001 00000001 00000001 Restriction: All tasks must be done using the topics covered in this and previous chapters. Warning: in section 4, the tests can be easily "tricked" into making the correct output without getting results from initial data using Python. This does not mean that the task was done correctly, it is just that at this stage it is difficult otherwise test the result. """ ip = "192.168.3.1" octets = ip.split(".") output = """ {0:<10}{1:<10}{2:<10}{3:<10} {0:08b} {1:08b} {2:08b} {3:08b}""" print(output.format(int(octets[0]), int(octets[1]), int(octets[2]), int(octets[3])))
192f825f65d935555adb5d1e746a6bcec9d29bdb
aoineza/tic_tac_toe
/t_mechanics.py
1,332
3.796875
4
'Tic-Tac-Toe Mechanics' import copy class game_board(): def __init__(self): self.board = [['','',''],['','',''],['','','']] def add_element(self,element,row,column): if self.board[row][column] != '': return False self.board[row][column] = element return True def hor_match(self): for i,row in enumerate(self.board,0): if row == ['X','X','X'] or row == ['O','O','O']: return (True,i) return (False,0) def transpose(self): t_board = [['','',''],['','',''],['','','']] for i in range(3): for j in range(3): t_board[i][j] = self.board[j][i] return t_board def vert_match(self): t_board = self.transpose() record = copy.copy(self.board) self.board = t_board res = self.hor_match() self.board = record return res def diag_match(self): if self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2] and self.board[0][0] != '': return (True,'left') elif self.board[0][2] == self.board[1][1] and self.board[2][0] == self.board[1][1] and self.board[0][2] != '': return (True,'right') else: return (False,0)
246036fb9bcfa3b61110f060c4018c8fdb3d7f90
FernandoSSilvaM/Tarea_07
/Tarea.py
2,031
4.03125
4
#Fernando Sebastian Silva M #Da un menu de finciones que puedes utilizar. Tambien te permite salir manuelmente del programa. def probarDivisiones(): #Realiza divisiones con restas. print("Bienvenido al programa para dividir") x = int(input("Dame el Divisor: ")) y = int(input("Dame el Dividendo: ")) residuo = x - y c = 1 if y == 0: return ("%i / %i = ERROR , sobra ERROR" % (x, y)) if residuo < 0: c = 0 residuo = x elif residuo == 0: c = 1 else: while residuo > 0: residuo -= y if residuo < 0: residuo += y break c += 1 return("%i / %i = %i, sobra %i" %(x, y, c, residuo)) def encontrarMayor(): #De una lista de datos, busca el numero más alto print("Bienvenido al programa de Encontrar mayores") x = int(input("Teclea un numero [teclea -1 para terminar]: ")) y = x if x == -1: return("No hay numeros mayores") while x != -1: if x > y: y = x x = int(input("Teclea un numero [teclea -1 para terminar]: ")) else: return "El numero mayor es "+str(y) def main(): x = int(input( "Tarea 07. Ciclos While\nAutor: Fernando S. Silva\n1. Imprimir divisiones\n2.Encontrar el mayor\n3.Salir\nTeclea tu opcion: ")) while x != 3: if x ==1: print(probarDivisiones()) x = int(input( "Tarea 07. Ciclos While\nAutor: Fernando S. Silva\n1. Imprimir divisiones\n2.Encontrar el mayor\n3.Salir\nTeclea tu opcion: ")) elif x == 2: print(encontrarMayor()) x = int(input( "Tarea 07. Ciclos While\nAutor: Fernando S. Silva\n1. Imprimir divisiones\n2.Encontrar el mayor\n3.Salir\nTeclea tu opcion: ")) else: print("Error, Teclea 1, 2 ó 3") x = int(input( "Tarea 07. Ciclos While\nAutor: Fernando S. Silva\n1. Imprimir divisiones\n2.Encontrar el mayor\n3.Salir\nTeclea tu opcion: ")) print("Gracias por usar el programa, vuelva pronto") main()
cd31fe810e8c006639692ec3985193de75aaf7dc
sneha1sneha/pgms
/pROGRAMS/assessment/Rrotation.py
292
3.921875
4
#list=[1,2,3,4] #list=[1,2,3,4,5,6,7,8,9] #o/p=[3,4,1,2] a=int(input("enter the position from " "which rotation to be performed")) i=a-1 n=len(list) listt=[] for num in range(i,n): listt.append(list[num]) j=0 for num in range(j,i): listt.append(list[num]) print(listt)
270537d5cf5e7ed55853e5b25e258d7b1a549291
sneha1sneha/pgms
/regularexpression/regphnumber.py
248
3.90625
4
from re import * #num=input("enter the number") #rule="(91)?[0-9]{10}" #\d{10} f=open("phonenumber","r") for num in f: rule="(91)?[0-9]{10}" matcher=fullmatch(rule,num) if matcher==None: print("invalid entry") else: print("valid entry")
7fc31cd478cadafacb5712d92d3327d59efca882
yuxuanwu17/leetcode
/lengthOfLIS.py
754
3.515625
4
from typing import List class Solution: def lengthOfLIS(self, nums: List[int]) -> int: memo = {} def recursion(nums: [int], i: int) -> int: if i in memo: return memo[i] # base case if i == len(nums) - 1: return 1 maxSubLength = 1 for j in range(i + 1, len(nums)): if nums[i] < nums[j]: maxSubLength = max(maxSubLength, recursion(nums, j) + 1) memo[i] = maxSubLength return maxSubLength return max(recursion(nums, i) for i in range(len(nums))) if __name__ == '__main__': sol = Solution nums = [7, 7, 7, 7, 7, 7, 7] print(sol.lengthOfLIS(sol, nums))
b3cfe1ba6b28715f0f2bccff2599412d406fd342
n001ce/python-control-flow-lab
/exercise-5.py
670
4.40625
4
# exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. # 2. Print each term and number as follows: # term: 0 / number: 0 # term: 1 / number: 1 # term: 2 / number: 1 # term: 3 / number: 2 # term: 4 / number: 3 # term: 5 / number: 5 # etc. # Hint: The next number is found by adding the two numbers before it # Program to display the Fibonacci sequence up to n-th term n1, n2 = 0, 1 count = 0 print("Fibonacci sequence:") while count < 50: print(f"term: {count} / number: {n1}") nth = n1 + n2 n1 = n2 n2 = nth count += 1
763979679c5737080f54ebfbd9e673d20de79c15
KingBing/SigmaGO_GuideDog
/ult_lib.py
1,732
3.5625
4
# Import required Python libraries # ----------------------- import time import RPi.GPIO as GPIO # ----------------------- # Define some functions # ----------------------- class ult(): def __init__(self): GPIO.setmode(GPIO.BOARD) self.GPIO_TRIGGER = 36 self.GPIO_ECHO = 37 GPIO.setup(self.GPIO_TRIGGER,GPIO.OUT) GPIO.setup(self.GPIO_ECHO,GPIO.IN) GPIO.output(self.GPIO_TRIGGER,False) def measure(self): # This function measures a distance #GPIO.setmode(GPIO.BOARD) try: GPIO.output(self.GPIO_TRIGGER, GPIO.HIGH) time.sleep(0.00001) GPIO.output(self.GPIO_TRIGGER, GPIO.LOW) start = time.time() while GPIO.input(self.GPIO_ECHO)==0: start = time.time() #print(0) while GPIO.input(self.GPIO_ECHO)==1: stop = time.time() #print(1) elapsed = stop - start distance = (elapsed * 34300)/2 #print(distance) return distance except (KeyboardInterrupt, SystemExit): self.quit() def measure_average(self): # This function takes 3 measurements and # returns the average. try: distance1=self.measure() time.sleep(0.025) distance2=self.measure() time.sleep(0.025) distance3=self.measure() distance = distance1 + distance2 + distance3 distance = distance / 3 #print(distance) return distance except( KeyboardInterrupt, SystemExit): self.quit() def quit(self): GPIO.cleanup()
75fd4c2cc5721d569a8664dd3eab55469055fb6c
LoveAndHappinesss/Learning-How-to-Use-Git
/TicTacToe.py
6,553
3.9375
4
def display_board(choice, turn, board_position): if turn == 'X': board_position[choice] = 'X' else: board_position[choice] = 'O' print('\n') print(' '+board_position[0]+' | '+board_position[1]+' | '+board_position[2]+' ') print(' ------------') print(' '+board_position[3]+' | '+board_position[4]+' | '+board_position[5]+' ') print(' ------------') print(' '+board_position[6]+' | '+board_position[7]+' | '+board_position[8]+' ') print('\n') return board_position def win_check(player1, player2, game_turn): winner = False if player1 == 'X': if (board_position[0] == "X" and board_position[1] == 'X' and board_position[2] == 'X' or board_position[3] == "X" and board_position[4] == 'X' and board_position[5] == 'X' or board_position[6] == "X" and board_position[7] == 'X' and board_position[8] == 'X' or board_position[0] == "X" and board_position[3] == 'X' and board_position[6] == 'X' or board_position[1] == "X" and board_position[4] == 'X' and board_position[7] == 'X' or board_position[2] == "X" and board_position[5] == 'X' and board_position[8] == 'X' or board_position[0] == "X" and board_position[4] == 'X' and board_position[8] == 'X' or board_position[2] == "X" and board_position[4] == 'X' and board_position[6] == 'X'): winner = True print("Congratulations! Player 1 has won the game!") if (board_position[0] == "O" and board_position[1] == 'O' and board_position[2] == 'O' or board_position[3] == "O" and board_position[4] == 'O' and board_position[5] == 'O' or board_position[6] == "O" and board_position[7] == 'O' and board_position[8] == 'O' or board_position[0] == "O" and board_position[3] == 'O' and board_position[6] == 'O' or board_position[1] == "O" and board_position[4] == 'O' and board_position[7] == 'O' or board_position[2] == "O" and board_position[5] == 'O' and board_position[8] == 'O' or board_position[0] == "O" and board_position[4] == 'O' and board_position[8] == 'O' or board_position[2] == "O" and board_position[4] == 'O' and board_position[6] == 'O'): winner = True print("Congratulations! Player 2 has won the game!") elif player1 == 'O': if (board_position[0] == "X" and board_position[1] == 'X' and board_position[2] == 'X' or board_position[3] == "X" and board_position[4] == 'X' and board_position[5] == 'X' or board_position[6] == "X" and board_position[7] == 'X' and board_position[8] == 'X' or board_position[0] == "X" and board_position[3] == 'X' and board_position[6] == 'X' or board_position[1] == "X" and board_position[4] == 'X' and board_position[7] == 'X' or board_position[2] == "X" and board_position[5] == 'X' and board_position[8] == 'X' or board_position[0] == "X" and board_position[4] == 'X' and board_position[8] == 'X' or board_position[2] == "X" and board_position[4] == 'X' and board_position[6] == 'X'): winner = True print("Congratulations! Player 2 has won the game!") if (board_position[0] == "O" and board_position[1] == 'O' and board_position[2] == 'O' or board_position[3] == "O" and board_position[4] == 'O' and board_position[5] == 'O' or board_position[6] == "O" and board_position[7] == 'O' and board_position[8] == 'O' or board_position[0] == "O" and board_position[3] == 'O' and board_position[6] == 'O' or board_position[1] == "O" and board_position[4] == 'O' and board_position[7] == 'O' or board_position[2] == "O" and board_position[5] == 'O' and board_position[8] == 'O' or board_position[0] == "O" and board_position[4] == 'O' and board_position[8] == 'O' or board_position[2] == "O" and board_position[4] == 'O' and board_position[6] == 'O'): winner = True print("Congratulations! Player 1 has won the game!") elif game_turn == 9: winner = True print("The game is a draw") return winner def p1_what_side(): isvalid = False choice = '' while isvalid is False: choice = input("Player 1, would you like to be X or O: ").upper() if choice == 'X': isvalid = True print("Player 1 controls the Xs") return 'X' if choice == 'O': isvalid = True print("Player 1 controls the Os") return 'O' else: print("This is an invalid input. Please try again.") def p2_what_side(x): if x == 'O': return 'X' else: return 'O' def user_choice(turn): isvalid = False while isvalid is False: if turn == 'X': choice = int(input('Where would you like to place your X?: ')) else: choice = int(input('Where would you like to place your O?: ')) if choice not in occupied_spots and 0 < choice < 10: occupied_spots.append(choice) return (choice - 1) else: print("This is not a valid input. Please try again.") def play_again(): isvalid = False choice = '' while isvalid is False: choice = input('Would you like to play again (Y or N): ').upper() if choice == 'N': isvalid = True print("Thanks for playing!") return False if choice == 'Y': isvalid = True return True else: print("This is an invalid input. Please try again.") play_game = True while play_game is True: player1 = p1_what_side() player2 = p2_what_side(player1) turn = player1 win = False game_turn = 0 board_position = ['', '', '', '', '', '', '', '', ''] occupied_spots = [] while win is False: choice = user_choice(turn) display_board(choice, turn, board_position) win = win_check(player1, player2, game_turn) game_turn += 1 if turn == player1: turn = player2 else: turn = player1 play_game = play_again()
e9a72caac8d953e5f30e7268668e6d2ab5b47eb3
teganbroderick/Python-Projects
/Tic Tac Toe/TicTacToe.py
4,730
4.3125
4
#!/usr/bin/env python3 #Tic Tac Toe game #Tegan Broderick, 20190815 #Combined exercises from practicepython.org #Game runs in the terminal using python 3 def game(gameboard, positionlist, running_position_list, turnlist): """Function calculates what turn the game is up to, assigns a player (1 or 2) to that turn, asks for userinput, analyzes whether the input move is valid, converts the player input into a valid list position, and appends the move to the nested gameboard list. The function also calls the 'checkwinner' function to see if anyone has won the game""" #calculates what turn the game is up to, and therefore what player is making a move if turnlist[-1] % 2 == 0: player = "Player 2" #O else: player = "Player 1" #X turn = turnlist[-1] + 1 turnlist.append(turn) #player input player_input = input(player + ", where would you like to place your piece? ") #Conditional, repeats if player chooses a position that's already taken or invalid while (player_input not in positionlist) or (player_input in running_position_list): print("That's not a valid position.") player_input = input(player + ", where would you like to place your piece? ") #convert userinput to correct format for python lists (starting at zero) running_position_list.append(player_input)#append input position to running position list, refer to in subsequent moves player_input = player_input.split(",") #split string into a list player_position = [] #list for player position in python list format for i in player_input: tempnumber = int(i) - 1 #minus one from each value to get correct nested list location player_position.append(tempnumber) #'place piece' into nested list x = player_position[0] y = player_position[1] if player == "Player 1": gameboard[x][y] = "X" else: gameboard[x][y] = "O" #print gameboard print() print("Gameboard:") print(" " + (" ---" * 3)) for i in range (0,3): for j in range(0,3): print(" | ", end='') print(gameboard[i][j], end='') print(" |") print(" " + (" ---" * 3)) print() checkforwinner(gameboard) def checkforwinner(nestedlist): """Function analyses nestedlist (gameboard) to see if anyone has won the game.""" winner = " " #space " " will be analyed as the winner with an empty or near empty board #horizontal win options if nestedlist[0][0] == nestedlist[0][1] == nestedlist[0][2]: winner = nestedlist[0][0] elif nestedlist[1][0] == nestedlist[1][1] == nestedlist[1][2]: winner = nestedlist[1][0] elif nestedlist[2][0] == nestedlist[2][1] == nestedlist[2][2]: winner = nestedlist[2][0] #vertical win options elif nestedlist[0][0] == nestedlist[1][0] == nestedlist[2][0]: winner = nestedlist[0][0] elif nestedlist[0][1] == nestedlist[1][1] == nestedlist[2][1]: winner = nestedlist[0][1] elif nestedlist[0][2] == nestedlist[1][2] == nestedlist[2][2]: winner = nestedlist[0][2] #diagonal win options elif nestedlist[0][0] == nestedlist[1][1] == nestedlist[2][2]: winner = nestedlist[0][0] elif nestedlist[2][0] == nestedlist[1][1] == nestedlist[0][2]: winner = nestedlist[2][0] #tie - game is out of spaces and there is no winner elif " " not in nestedlist[0] and " " not in nestedlist[1] and " " not in nestedlist[2]: print("You are out of spaces. The game is a tie.") return True else: print() #results if winner == "X": print("Player 1 wins!") return True elif winner == "O": print("Player 2 wins!") return True else: return False #introduction print("Welcome to Tic Tac Toe. Player one is 'X', and player two is 'O'. To play, specify your desired position using the format 'row, column'.") print() print("Here is an example board showing positions: ") dottedline = (" " + (" ---" * 3)) print(dottedline) print(" |1,1|1,2|1,3|") print(dottedline) print(" |2,1|2,2|2,3|") print(dottedline) print(" |3,1|3,2|3,3|") print(dottedline) #Play game repeat = "yes" while repeat == "yes": #setup gameboard = [[" "," "," "], [" "," "," "], [" "," "," "]] positionlist = ["1,1", "1,2", "1,3", "2,1", "2,2", "2,3", "3,1", "3,2", "3,3" ] #every possible position, used to verify user input running_position_list = [] #to store positions as they are chosen by the users, and reference to see if the requested position is already taken turnlist = [1] #used for calcuating which player is making a move print() print("Gameboard:") print(" " + (" ---" * 3)) for i in range (0,3): for j in range(0,3): print(" | ", end='') print(gameboard[i][j], end='') print(" |") print(" " + (" ---" * 3)) print() while checkforwinner(gameboard) == False: game(gameboard, positionlist, running_position_list, turnlist) print("-" * 60) repeat = input("Would you like to play again? yes or no: ")
22b51de6575b2bae03e07d9498d1ba16e083b688
c0ntradicti0n/CorpusCookApp
/logtest.py
575
3.734375
4
import logging, sys class LogFile(object): """File-like object to log text using the `logging` module.""" def __init__(self, name=None): self.logger = logging.getLogger(name) def write(self, msg, level=logging.INFO): self.logger.log(level, msg) def flush(self): for handler in self.logger.handlers: handler.flush() logging.basicConfig(level=logging.DEBUG, filename='mylog.log') # Redirect stdout and stderr sys.stdout = LogFile('stdout') sys.stderr = LogFile('stderr') print ('this should to write to the log file')
4540b64352cbbc636337cd0a1061494dc04c76dd
alopezja/Phyton
/UPB/Ejercicios/jun8.py
618
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 8 18:35:30 2021 @author: exlonk """ print("Ingrese el valor de compra e ingrese un valor de cero para finalizar") contador = 0 monto = None numero_compra = 1 while monto != 0: monto= float(input("Valor compra {0}: ".format(numero_compra))) if monto > 0 : contador += monto numero_compra +=1 elif monto < 0: print("Ingrese el valor correcto") else: break if contador > 1000: contador = contador - contador*0.10 print("Total compra:",contador) else: print("Total compra:",contador)
63547b9b5fda15e875f1dbc359f09da689305ab4
alopezja/Phyton
/UPB/Ejercicios/ejercicio3.py
401
3.859375
4
### Parque de diversiones edad = int(input("Digite su edad:\n >>> ")) if 0<edad<18: print("Solo puede entrar a las atracciones de menores de edad") else: if 18<=edad<60: print("Puede utilizar todas las atracciones del parque") else: if edad>=60: print("Solo puede utilizar unas cuantas atracciones") else: print("Digite una edad válida")
44ffa186670d787e5aafa5b380e669e7763d9e5d
alopezja/Phyton
/UPB/Ejercicios/jun11.py
764
3.84375
4
from os import system system("clear") #Delimitadores para cambiar un string con un separador #para agregar cada argumento por separado a un elemento en una lista s = "Alex-David-Lopez" delimiter = "-" print(s.split(delimiter)) lista = ["Programar","es","lo","mejor"] delimiter = " " print(delimiter.join(lista)) a = "casa" b = "casa" print(a is b) #Apuntan al mismo objeto c = ["a","b","c"] d = ["a","b","c"] print(c is d) #Apuntan al diferente objeto num = [1,2,3] num2 = num num2[0] = 0 print(num is num2) print(num) print("\n") t1 = [1,2] t2 = t1.append(3) print(t1) print(t2) print("\n") t1 = [1,2] t3 = t1 + [3] print(t1) print(t3) t2 is t3 print("\n") a = [1,2] a.insert(0,3) print(a) print(a.count(1)) a = [1,2,3,4,5,6,7,8,9] print(a.index(3,0,8))
6c6ca1405b0b0a73e610f148962c9eea2f4fe62b
rykroon/mongoendjin
/mongoendjin/utils/text.py
268
4.0625
4
import re re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))') def camel_case_to_spaces(value): """ Split CamelCase and convert to lowercase. Strip surrounding whitespace. """ return re_camel_case.sub(r' \1', value).strip().lower()
061aa64d7b81d640feac402dd1840ec8e80b1c7c
advancer-debug/Daily-learning-records
/数据结构与算法记录/习题解答记录/链表/offero6_test.py
2,482
4.125
4
# -*- coding = utf-8 -*- # /usr/bin/env python # @Time : 20-11-28 下午2:02 # @File : offero6_test.py # @Software: PyCharm # 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 # 方法一递归法 # 利用递归: 先走至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出。 # python算法流程 # 递推阶段: 每次传入 head.next ,以 head == None(即走过链表尾部节点)为递归终止条件,此时返回空列表 [] 。 # 回溯阶段: 利用 Python 语言特性,递归回溯时每次返回 当前 list + 当前节点值 [head.val] , # 即可实现节点的倒序输出。 # 复杂度分析: # # 时间复杂度 O(N): 遍历链表,递归 N 次。 # 空间复杂度 O(N): 系统递归需要使用 O(N) 的栈空间。 # Definition for singly-linked list. # 1. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseprint(self, head: ListNode)->List[int]: return self.reverseprint(head.next)+[head.val] if head else [] # 2. class Solution: def reverseprint(self, head: ListNode)->List[int]: p, rev = head, None while p: rev, rev.next, p = p, rev, p.next result = [] while rev: result.append(rev.val) rev = rev.next return result # 辅助栈法 # 解题思路: # 链表特点: 只能从前至后访问每个节点。 # 题目要求: 倒序输出节点值。 # 这种 先入后出 的需求可以借助 栈 来实现。 # 算法流程: # 入栈: 遍历链表,将各节点值 push 入栈。(Python​ 使用 append() 方法,​Java​借助 LinkedList 的addLast()方法)。 # 出栈: 将各节点值 pop 出栈,存储于数组并返回。(Python​ 直接返回 stack 的倒序列表,Java ​新建一个数组,通过 popLast() 方法将各元素存入数组,实现倒序输出)。 # 复杂度分析: # 时间复杂度O(N):入栈和出栈共使用O(N)时间。 # 空间复杂度O(N):辅助栈stack和数组res共使用 O(N)的额外空间。 class Solution: def reversePrint(self, head: ListNode) -> List[int]: stack = [] while head: stack.append(head.val) head = head.next return stack[::-1] # stack.reverse() return stack
1045bc8666f46dea921581ff515f2d4d5908d729
advancer-debug/Daily-learning-records
/python的魔法使用/test.py
684
3.8125
4
# -*- coding = utf-8 -*- # /usr/bin/env python # @Time : 20-11-18 下午8:25 # @File : test.py # @Software: PyCharm # try/except/else while/else break continue # while True: # reply = input('Enter txt:') # if reply == 'stop': # break # try: # num = int(reply) # except: # print('Bad!' * 8) # else: # print(int(reply)**2) # # print('Bye') while True: reply = input('Enter txt:') if reply == 'stop': break elif not reply.isdigit(): print('Bad!'*8) else: num = int(reply) if num < 20: print('low'*4) else: print(num**2) print('Bye'*3)
8d980ed029b0dc74e4dc6aa0e7785d6af0f95fa7
NiharikaSinghRazdan/PracticeGit_Python
/Code_Practice/list_exercise.py
512
4.21875
4
# Convert string into list mystring="This is the new change" mylist = [] for letter in mystring: mylist.append(letter) print(mylist) # Change string into list with different convert format and in one line mystring1="Hi There" mylist1 =[letter for letter in mystring1] print(mylist1) # Check other usage of this new one liner format to convert string into list #Check the odd no in list mylist2=[num for num in range(0,11) if num%2==0] print(mylist2) mylist2=[num**2 for num in range(0, 11)] print(mylist2)
e0a8fb7f830eb8d4faa7cb14ca39d0f9ae33e621
NiharikaSinghRazdan/PracticeGit_Python
/Code_Practice/tuples.py
181
4.09375
4
tuples1=(1,2,3,"age") print(type(tuples1)) print(tuples1[0]) print(len(tuples1)) print(tuples1[-1]) #tuples1[1]="Name", tuple object does not support item assignment. print(tuples1)
bc76d2ae44f894254a3e24c0b53c61db5039f4ff
NiharikaSinghRazdan/PracticeGit_Python
/Code_Practice/arbitary_list.py
1,556
4.1875
4
#retrun the list where the passed arguments are even def myfunc(*args): mylist=[] for item in args: if item%2==0: mylist.append(item) else: continue print(mylist) print(myfunc(-2,4,3,5,7,8,10)) # return a string where every even letter is in uppercase and every odd letter is in lowercase def myfunct(*args): mylist1=[] for item in args: # find the index of the items index=args.index(item) if (item==item.upper() and index%2==0) or (item==item.lower() and index%2!=0): mylist1.append(item) print(mylist1) print(myfunct('A','B','C','D','e',"f")) # check the index of the list and verify that even is in uppercase and odd index is in lower case def myfunc1(*args): mystring=' ' mystring_t=args[0] print(len(mystring_t)) for item in range(len(mystring_t)): if (item%2==0): mystring=mystring+mystring_t[item].upper() else: mystring=mystring+mystring_t[item].lower() print(mystring) print(myfunc1("supercalifragilisticexpialidocious")) # print the argument in upper and lowercase alternate def myfunc2(*args): mystring_total=args[0] c_string=' ' for item in mystring_total: index1=mystring_total.index(item) if (index1%2==0): item=item.upper() c_string=c_string+item else: item=item.lower() c_string=c_string+item print(mystring_total) print(c_string) print(myfunc2("AbcdEFGHijKL"))
37b1dce3bcbe2da05065e677491797983588c285
dankolbman/NumericalAnalysis
/Homeworks/HW1/Problem1.py
520
4.21875
4
import math a = 25.0 print("Squaring a square-root:") while ( math.sqrt(a)**2 == a ): print('sqrt(a)^2 = ' + str(a) + ' = ' + str(math.sqrt(a)**2)) a *= 10 # There was a rounding error print('sqrt(a)^2 = ' + str(a) + ' != ' + str(math.sqrt(a)**2)) # Determine the exponent of the float expo = math.floor(math.log10(a))-1.0 # Reduce to only significant digits b = a/(10**expo) print("Ajusting decimal placement before taking the square-root:") print('sqrt(a)^2 = ' + str(a) + ' = ' + str((math.sqrt(b)**2)*10**expo))
3ecc8e12c963520b723804c9ca6beebb2544b01f
bravacoreana/python
/files/12.py
245
4
4
a = [1,2,3,4,5,6,7] for element in a: print(element) numbers = [1,2,3,4,5,6,7,8,9,10] for number in numbers: if number % 2 == 0 : print("even number: {}".format(number)) else: print("odd number: {}".format(number))
33d08154e946264256f7810254cd09f236622718
bravacoreana/python
/files/08.py
409
4.34375
4
# if <condition> : # when condition is true if True: print("it's true") if False: print("it's false") number = input("input a number >>> ") number = int(number) if number % 2 == 0: print("even") if number % 2 != 0: print("odd") if number < 10: print("less than 10") elif number < 20: print("less than 20") elif number < 30: print("less than 30") else: print("hahaha")
c9eb65921d784d054c7dd2d2eac5605ab2b462d2
young508/pythonLearn
/main/oop/抽象类.py
526
3.765625
4
import abc # 抽象类必须声明一个类并且指定当前类的元类 class Human(metaclass=abc.ABCMeta): # 抽象方法 @abc.abstractmethod def smoking(self): pass # 定义类的抽象方法 @abc.abstractclassmethod def drink(cls): pass # 定义静态抽象方法 @abc.abstractstaticmethod def play(): pass class Man(Human): def smoking(self): print("smoking") def drink(cls): print("drink") def play(): print("play")
bfc1710b45ac38465e6f545968f2e00cd535d2dc
Tarun-Rao00/Python-CodeWithHarry
/Chapter 4/03_list_methods.py
522
4.21875
4
l1 = [1, 8, 7, 2, 21, 15] print(l1) l1.sort() # sorts the list print("Sorted: ", l1) l1.reverse() #reverses the list print("Reversed: ",l1) l1.reverse() print("Reversed 2: ",l1) l1.append(45) # adds to the end of the list print ("Append", l1) l2 = [1,5, 4, 10] l1.append(l2) # l2 (list) will be added print("Append 2", l1) l1.insert(0, 100) # Inserts 100 at 0-(position) print("Inserted", l1) l1.pop(2) # removes item from position 2 print("Popped", l1) l1.remove(7) # removes 7 from the list print("Removed", l1)
fdd7aede3f987bfdbe75d46712b141bffae2ef9c
Tarun-Rao00/Python-CodeWithHarry
/Chapter 8/11_pr-07.py
221
3.828125
4
def remov(strg): word = input("Enter the word you want to remove: ") newStrng = strg.replace(word, "") newStrng1 = newStrng.strip() return newStrng1 strg = input("Enter your text: ") print(remov(strg))
64dfa1b97046bb32385d14a3a17890efdc290cd1
Tarun-Rao00/Python-CodeWithHarry
/Chapter 6/05_pr_01.py
265
3.984375
4
a = int(input("Enter number one: ")) b = int(input("Enter number two: ")) c = int(input("Enter number three: ")) d = int(input("Enter number four: ")) if(a>b and a>b and a>d): print(a) elif(b>c and b>d): print(b) elif(c>d): print(c) else: print(d )
d3116722a51caab7ade845d108d90214533b1b93
Tarun-Rao00/Python-CodeWithHarry
/Chapter 4/05_tuple_methods.py
158
3.796875
4
t = (1, 2, 3, 4, 5, 1, 1) print("Count", t.count(1)) # Returns the number of occurence value print("Index", t.index(5)) # returns the first index of value
0ab24f03f7919f96e74301d06dd9af5a377ff987
Tarun-Rao00/Python-CodeWithHarry
/Chapter 2/02_operators.py
548
4.125
4
a = 34 b = 4 # Arithimatic Operator print("the value of 3+4 is ", 3+4) print("the value of 3-4 is ", 3-4) print("the value of 3*4 is ", 3*4) print("the value of 3/4 is ", 3/4) # Assignment Operators a = 34 a += 2 print(a) # Comparision Operators b = (7>14) c = (7<14) d = (7==14) e = (7>=14) print(b) print(c) print(d) print(e) # Logical Operators boo1 = True bool2 = False print("The value of bool1 and bool2 is", (boo1 and bool2)) print("The value of bool1 and bool2 is", (boo1 or bool2)) print("The value of bool1 and bool2 is", (not bool2))
062cb2773c796daeae0581cad63b05da9e771744
Tarun-Rao00/Python-CodeWithHarry
/Chapter 5/06_pr_01.py
332
4.0625
4
myDict = { "Pankha" : "Fan", "Darwaja" : "Door", "Hawa" : "Air", "Badal": "Clouds", "Aasmaan" : "Sky" } print("options are ", myDict.keys()) a = input("Enter the hindi word\n") # Below line will not throw an error if the key is not present the Dictionary print("The meaning of your word is:\n", myDict.get[a])
d31f727127690b2a4584755c941cd19c7452d9e4
Tarun-Rao00/Python-CodeWithHarry
/Chapter 6/11_pr_06.py
221
4.15625
4
text = input("Enter your text: ") text1 = text.capitalize() num1 = text1.find("Harry") num2 = text1.find("harry") if (num1==-1 and num2==-1): print("Not talking about Harry") else: print("Talking about Harry")
03e0dbdd4929f5992182830a995642a75805704b
Tarun-Rao00/Python-CodeWithHarry
/Chapter 10/05_instance_class_attribute.py
231
3.921875
4
class Employee: company = "Google" salary = 100 harry = Employee() rajni = Employee() # Creating instance attribute salry for both the objects harry.salary = 300 rajni.salary = 400 print(harry.salary) print(rajni.salary)
8a2be0cbdc3ca978a888670067c440c2806a0b81
saratiedt/python-exercises
/semana 2/buscaString.py
217
3.953125
4
palavra = input("Digite uma palavra: ") letra = input("Digite uma letra para ser buscada na palavra: ") if letra in palavra: print(f'Existe {letra} na {palavra}') else: print(f'Não existe {letra} na {palavra}')
f6f79e3ec31c1dac8443d6588028008b02691339
saratiedt/python-exercises
/semana 3/contadorCaracteres.py
177
3.703125
4
nome = input("Digite seu nome: ") sobrenome = input("Digite seu sobrenome: ") tamanhoNome = len(nome) + len(sobrenome) print(f'O nome tem {tamanhoNome} caracteres no total.')
c6564a35f4ac868cb5ebd5898316c8b5f42691ec
jitendrasinghiitg/sonar-python-coverage
/python/calc.py
373
3.734375
4
""" calc.py """ def add(x, y): """ :param x: :param y: :return: sum of x and y """ return x + y def difference(x, y): """ :param x: :param y: :return: returns difference of x and y """ return x - y def multiply(x, y): """ :param x: :param y: :return: returns product of x and y """ return x * y
0a9cf183231f226cdde9a5e8fc829516f534a56e
willmclaughlin13/CS415
/greedy.py
3,379
3.984375
4
from collections import namedtuple # This is our heap class class maxHeap: def __init__(self, array=None): self._heap = [] if array is not None: # The constructor, builds the heap from a list for i in array: self.insert(i) # Insert takes value to insert as input, appends it to the array, then # calls sift up to find it's place in the heap def insert(self, value): self._heap.append(value) _sift_up(self._heap, len(self) - 1) # Pop removes and returns the maximum value at the root def pop(self): _swap(self._heap, len(self) - 1, 0) i = self._heap.pop() _siftDown(self._heap, 0) return i def __len__(self): return len(self._heap) # Swap the two values in the list def _swap(L, i, j): L[i], L[j] = L[j], L[i] # Find the new value's place in the heap def _sift_up(heap, idx): parent_idx = (idx - 1) // 2 # Hit the root if parent_idx < 0: return # Check for swap if heap[idx].ratio > heap[parent_idx].ratio: _swap(heap, idx, parent_idx) _sift_up(heap, parent_idx) # After removing the root, find a new one and sift up def _siftDown(heap, idx): child_idx = 2 * idx + 1 if child_idx >= len(heap): return # Hit the root if child_idx + 1 < len(heap) and heap[child_idx].ratio < heap[child_idx + 1].ratio: child_idx += 1 # Check for swap if heap[child_idx].ratio > heap[idx].ratio: _swap(heap, child_idx, idx) _siftDown(heap, child_idx) # takes an array as input, turns it into a heap, # and returns the sorted values as a list. def heap_sort(array): heap = maxHeap(array) sorted_arr = [] while len(heap) > 0: sorted_arr.append(heap.pop()) return sorted_arr # Knapsack algorithm using the built-in list def greedySort(cap, weight, values): ratios = [] subset = [] for i in range(len(values)): ratios.append(values[i]/weight[i]) subset.append(i+1) ratios, values, weight, subset = (list(t) for t in zip(*sorted(zip(ratios, values, weight, subset), reverse=True))) finalSubset = [] totalWeight = 0 totalValue = 0 for i in range(len(values)): if totalWeight + weight[i] >= cap: finalSubset.sort() return finalSubset, totalValue else: finalSubset.append(subset[i]) totalWeight += weight[i] totalValue += values[i] # Knapsack algorithm using our heap class def greedyHeap(cap, weight, values): myHeap = namedtuple("myHeap", "weight value idx ratio") items = [] ratios = [] for i in range(len(values)): ratios.append(values[i]/weight[i]) for i in range(len(values)): m = myHeap(weight=weight[i], value=values[i], idx=i+1, ratio=ratios[i]) items.append(m) items = heap_sort(items) finalSubset = [] totalWeight = 0 totalValue = 0 for i in items: if totalWeight + i.weight >= cap: finalSubset.sort() return finalSubset, totalValue else: finalSubset.append(i.idx) totalWeight += i.weight totalValue += i.value
562874a65da4ea0f2119953a021689b201013800
Nanorneirbo/self_driving_car-project
/Lanes/lanes_video.py
3,191
3.5625
4
import cv2 import numpy as np import matplotlib.pyplot as plt # function to run the canny def canny(image): # in - a new image # out - greyscael, smoothed, canny image. #greyscale the image gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) #blur the image blur = cv2.GaussianBlur(gray, (5,5),0) # canny - detect big changes in gradients using derivatives canny = cv2.Canny(blur, 50, 150) return canny def regionofinterest(image): # in - the image # out - a filled mask showing the lane we want # height of image = rows in the array height = image.shape[0] # actually just one but fillpoly dont like that polygons = np.array([ [(200,height), (1100, height), (550,250)] ]) # create an array of zeros same shape as image mask = np.zeros_like(image) # fill the region of interest with white only cv2.fillPoly(mask, polygons, 255) #use bitwise and to clear out uninteresting stuff masked_image = cv2.bitwise_and(image,mask) return masked_image def display_lines(image,lines): line_image = np.zeros_like(image) if lines is not None: for line in lines: x1,y1,x2,y2 = line.reshape(4) # draw line blue and ten thick cv2.line(line_image, (x1,y1), (x2,y2),(255,0,0), 10) return line_image def make_coordinates(image, line_parameters): slope, intercept = line_parameters print (image.shape) # y's start at bottom x's use slope and intercet. y1 = image.shape[0] # 3/5 is an estimate y2 = int(y1 * 3/5) x1 = int((y1 - intercept)/slope) x2 = int((y2 - intercept)/slope) return np.array([x1, y1, x2, y2]) def average_slope_intercept(image,lines): # in - the original image and the lines image left_fit =[] right_fit =[] for line in lines: x1, y1, x2, y2 = line.reshape(4) # get the slope using a polynomial. parameters = np.polyfit((x1, x2), (y1,y2), 1) slope = parameters[0] intercept = parameters[1] # negative = for slope left hand side, positive is on right if slope < 0 : left_fit.append((slope, intercept)) else : right_fit.append((slope,intercept)) # test the lines - print(left_fit) #print(right_fit) # average the sides and make sure to do along the right access(0) left_fit_average = np.average(left_fit, axis = 0) right_fit_average = np.average(right_fit, axis = 0) #print(left_fit_average, 'left') #print(right_fit_average, 'right') # need to get the coordinates - created a function above left_line = make_coordinates(image, left_fit_average) right_line = make_coordinates(image, right_fit_average) # return the lines return np.array([left_line, right_line]) # take in the video cap = cv2.VideoCapture("test2.mp4") while(cap.isOpened()): _, frame = cap.read() canny_image = canny(frame) cropped_image = regionofinterest(canny_image) lines = cv2.HoughLinesP(cropped_image, 2,np.pi/180, 100, np.array([]), minLineLength = 40, maxLineGap = 5) averaged_lines = average_slope_intercept(frame,lines) line_image = display_lines(frame, averaged_lines) combo_image = cv2.addWeighted(frame, 0.8, line_image, 1,1) cv2.imshow('result', combo_image) #cv2.waitKey(1) # allow us to close the video - q if cv2.waitKey(1) == ord('q'): break cap.release() cv2.destroyAllWindows()
4362c2094c0a0a944a0a74940c77a615f1cb1fbd
okccc/python
/basic/10_线程.py
3,305
3.53125
4
# coding=utf-8 import threading import time def test01(): for i in range(5): print("---test01---%d" % i) time.sleep(0.5) def test02(): for i in range(10): print("---test02---%d" % i) time.sleep(0.5) def main01(): # 多线程实现多任务 # Thread()方法只是创建实例对象,一个实例对象只能创建一个线程且该线程只能开启一次 RuntimeError: threads can only be started once t1 = threading.Thread(target=test01) t2 = threading.Thread(target=test02) # setDaemon(True)将线程设置为守护线程,当主线程结束时守护线程也结束 t1.setDaemon(True) t2.setDaemon(True) # 调用start()方法创建线程并启动线程;该线程会运行target函数,函数运行结束时该子线程结束 t1.start() t2.start() # join()方法表示堵塞模式,等待当前已经启动的线程执行完再继续往下执行 # t1.join() # t2.join() while True: # 统计当前正在运行的线程 print(threading.enumerate()) # 当子线程都结束只剩下主线程时中断程序 if len(threading.enumerate()) == 1: break # 线程执行没有顺序,主线程和子线程都在抢资源往下运行,可以通过sleep()控制线程执行顺序 time.sleep(0.5) print("主线程over!") g_num = 0 g_list = [11, 22] def test03(): # 如果修改全局变量内存地址发生变化(重新赋值)要加global关键字 global g_num g_num += 100 print("---in test03---g_num=%d" % g_num) # 内存地址不变不用加global g_list.append(33) print("---in test03---g_list=%s" % g_list) def test04(): print("---in test04---g_num=%d" % g_num) print("---in test04---g_list=%s" % g_list) def main02(): # 多线程之间是共享全局变量的 t3 = threading.Thread(target=test03) t4 = threading.Thread(target=test04) t3.start() # 等待t3子线程先执行完 time.sleep(1) t4.start() print("---in main thread---g_num=%d" % g_num) print("---in main thread---g_num=%s" % g_list) def test05(count): global g_num for i in range(count): # 上锁:如果之前没上锁则上锁成功,如果已经上锁会堵塞直到锁释放;为了避免堵塞太久上锁代码越少越好,只给存在资源竞争的代码上锁即可 lock.acquire() g_num += 1 # 解锁:操作完共享数据就释放锁等待下一次获取锁再继续操作 lock.release() print("---in test07---num is %d" % g_num) def test06(count): global g_num for i in range(count): lock.acquire() g_num += 1 lock.release() print("---in test08---num is %d" % g_num) # 创建互斥锁 lock = threading.Lock() def main03(): # 当循环次数足够大时,多线程操作全局变量的资源竞争冲突就体现出来了,需要用锁将两个线程同步起来 t7 = threading.Thread(target=test05, args=(1000000,)) t8 = threading.Thread(target=test06, args=(1000000,)) t7.start() t8.start() # 主线程睡眠3秒等待子线程全部执行完 time.sleep(3) print("---in main thread---num is %d" % g_num) if __name__ == "__main__": # main01() # main02() main03()
efe618ae87f00a3f691905cd6987b72809c878f6
okccc/python
/other/cardmanager/card_tools.py
4,373
3.640625
4
# coding=utf-8 """ card_tools: 工具类,包含主程序要用的所有函数 """ # 定义一个空列表存储数据,放在第一行,这样所有函数都能使用该数据 card_list = [] # 显示功能列表 def show_menu(): print("*" * 50) print("欢迎使用【名片管理系统】 V 1.0") print("1.新增名片") print("2.显示全部") print("3.搜索名片") print("0.退出系统") print("*" * 50) # 新增名片 def new_card(): print("新增名片") print("-" * 50) # 1、提示用户输入名片信息 name_str = input("请输入姓名:") phone_str = input("请输入电话:") email_str = input("请输入邮箱:") # 2、用字典封装这些数据 card_dict = { "name": name_str, "phone": phone_str, "email": email_str } # 3、将字典添加到存储数据的列表 card_list.append(card_dict) print(card_list) # 4、提示用户添加成功 print("新增名片 %s 成功!" % name_str) # 显示全部 def show_all(): print("显示全部") print("-" * 50) # 1、先判断是否有数据,没有数据就不打印表头了 if len(card_list) == 0: print("当前没有任何名片,请先添加新名片!") # return关键字可以返回函数的结果,也可以用来终止程序,返回到函数调用入口,return下方的语句不会被执行到 return # 2、打印表头 for name in ["姓名", "电话", "邮箱"]: print(name, end="\t\t") print("") # 3、打印分割线 print("=" * 30) # 4、遍历循环列表 for card_dict in card_list: print("%s\t\t%s\t\t%s" % ( card_dict["name"], card_dict["phone"], card_dict["email"] )) # 搜索名片 def search_card(): print("搜索名片") print("-" * 50) # 1、提示输入信息 find_name = input("请输入要搜索的名字:") # 2、遍历循环列表 for card_dict in card_list: # 3、搜索到了就输出详细信息 if card_dict["name"] == find_name: print("找到 %s 啦!" % find_name) print("姓名\t\t电话\t\t邮箱") print("=" * 30) print("%s\t\t%s\t\t%s" % ( card_dict["name"], card_dict["phone"], card_dict["email"] )) # 4、搜索到之后进行的后续操作(尽量不要把所有代码放在一个代码块,可以调用其他函数) card_deal(card_dict) # 5、终止循环 break # 没搜索到也提示一下 else: print("很抱歉,没有找到 %s 同学。。。" % find_name) # 处理搜索到的名片 def card_deal(find_dict): """ :param find_dict: 搜索到的名片信息 """ # 输入提示 action_str = input("请选择要继续执行的操作,[1] 修改 [2] 删除 [0] 返回上级:") if action_str == "1": # 修改名片(这里有个地方要改进,如果某个key不需要修改的话,就不用输入内容,所以这里要对用户是否输入内容做判断) # find_dict["name"] = input("姓名:") # 用键盘输入重新给字典的key赋值 # find_dict["phone"] = input("电话:") # find_dict["email"] = input("邮箱:") find_dict["name"] = input_new(find_dict["name"], "姓名:") find_dict["phone"] = input_new(find_dict["phone"], "电话:") find_dict["email"] = input_new(find_dict["email"], "邮箱:") print("修改名片 %s 成功!" % find_dict["name"]) elif action_str == "2": # 删除名片 card_list.remove(find_dict) print("删除名片 %s 成功!" % find_dict["name"]) elif action_str == "0": show_menu() else: print("error input!") # 改造input函数 def input_new(old_value, new_value): """ :param old_value: 原有字典value值 :param new_value: 用户键盘输入的新的value值 :return: 返回结果值 """ # 1、提示用户输入内容 result = input(new_value) # 2、判断用户是否输入了内容 if len(result) > 0: # 3、如果输入内容就返回新输入的值 return result else: # 4、如果直接回车就返回原有值 return old_value
14a80976e094faffcab44a4e0ae049b68b921b5e
jkeller51/ECE448_MP4
/gen_training_data.py
2,057
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 28 12:36:57 2018 @author: jkell """ import numpy as np resolution = 10 import random def intersect_line(x1,y1,x2,y2,linex): """ Determine where the line drawn through (x1,y1) and (x2,y2) will intersect the line x=linex """ if (x2 == x1): return 0 return ((y2-y1)/(x2-x1))*abs(linex-x1)+y1 #ball_x = np.asarray(range(0,resolution))/(resolution) #ball_y = ball_x.copy() # #ball_vx = np.asarray(range(0,resolution))/resolution * 0.06 - 0.03 #ball_vy = ball_vx.copy() # #paddle_y = np.asarray(range(0,resolution))/(resolution) # #data = [] # #for bx in ball_x: # for by in ball_y: # for vx in ball_vx: # for vy in ball_vy: # for py in paddle_y: ## if (vx < 0): # ball moving away # if (by < py-0.01): # yy = 0 # # elif (by > py+0.01): # yy = 2 # # else: # yy = 1 ## else: ## y_int = intersect_line(bx,by,vx,vy,1) ## if (y_int < py+0.1): ## yy = 0 ## elif (y_int == py+0.1): ## yy = 1 ## elif (y_int > py+0.1): ## yy = 2 # data.append([bx, by, vx, vy, py, yy]) data = [] for _ in range(100000): bx = random.random() by = random.random() vx = random.random() * 0.06 - 0.03 vy = random.random() * 0.06 - 0.03 py = random.random() if (by+vy < py): yy = 0 elif (by+vy > py+0.2): yy = 2 else: yy = 1 data.append([bx, by, vx, vy, py, yy]) f = open('./data/test_policy_easy.txt', 'w') for d in data: f.write(str(d[0]) + " " + str(d[1]) + " " + str(d[2]) + " " + str(d[3]) + " " + str(d[4]) + " " + str(d[5]) + "\n") f.close()
b53765f11a2ab8b9ecda7607eaa1e6be6849c4e8
varunnair735/Neural-Net
/activation_functions.py
744
3.65625
4
""" Author: Varun Nair Date: 6/25/19 """ import numpy as np def sig(x): """Defines sigmoid activation function""" return (1 / (1+ np.exp(-x))) def sig_prime(x): """Defines the derivative of the sigmoid function used in backprop""" return sig(x)*(1-sig(x)) def RELU(x): """Defines ReLU activation function""" return x*(x>0) def RELU_prime(x): """Derivative is 0 when <0 and 1 when >0""" return 1*(x>0) def softmax(x): """Computes softmax score for each class so probabilities add to 1. This is adjusted by the max value to avoid overflows""" a = np.exp(x - np.max(x)) return a / (np.sum(a, axis=1)) def softmax_prime(x): """Derivative of softmax function for use in backprop""" pass
406ad197c1a6b2ee7529aaa7c6ea5a86e10114de
carrenolg/python-code
/Chapter12/optimize/main.py
896
4.25
4
from time import time, sleep from timeit import timeit, repeat # main def main(): """ # measure timing # example 1 t1 = time() num = 5 num *= 2 print(time() - t1) # example 2 t1 = time() sleep(1.0) print(time() - t1) # using timeit print(timeit('num = 5; num *= 2', number=1)) print(repeat('num = 5; num *= 2', number=1, repeat=3)) """ # Algorithms and Data Structures # build a list in different ways def make_list_1(): result = [] for value in range(1000): result.append(value) return result def make_list_2(): result = [value for value in range(1000)] return result print('make_list_1 takes', timeit(make_list_1, number=1000), 'seconds') print('make_list_2 takes', timeit(make_list_2, number=1000), 'seconds') if __name__ == '__main__': main()
9bbc0b6c797397a5fd72079b649b115fe117879e
carrenolg/python-code
/chapter6/chapter6.py
4,636
4.1875
4
# Chapter6 - Oh Oh: Objects and Classes class Person(): def __init__(self, name): self.name = name soccer_player = Person('Juan Roman') print(soccer_player) # Inheritance class Car(): def exclaim(self): print("I'm a Car!") class Yugo(Car): def exclaim(self): print("I'm a Yugo!") def need_a_push(self): print("A little help here?") pass obj_car = Car() obj_yugo = Yugo() obj_car.exclaim() obj_yugo.exclaim() class MDPerson(Person): def __init__(self, name): self.name = "Doctor " + name class JDPerson(Person): def __init__(self, name): self.name = name + ", Esquire" person = Person('Fudd') doctor = MDPerson('Fudd') lawyer = JDPerson('Fudd') print(person.name, doctor.name, lawyer.name) obj_yugo.need_a_push() class EmailPerson(Person): def __init__(self, name, email): super().__init__(name) self.email = email bob = EmailPerson('Bob Frapples', '[email protected]') class Duck(): def __init__(self, input_name): self.hidden_name = input_name def get_name(self): print('inside the getter') return self.hidden_name def set_name(self, input_name): print('inside the setter') self.hidden_name = input_name name = property(get_name, set_name) fowl = Duck('Howard') print(fowl.name) fowl.name = 'Daffy' print(fowl.name) class DDuck(): def __init__(self, input_name): self.hidden_name = input_name @property def name(self): print('>>> inside the getter') return self.hidden_name @name.setter def name(self, input_name): print('>>> inside the setter') self.hidden_name = input_name dfowl = DDuck('Gio10') print(dfowl.name) dfowl.name = 'carrenolg10' print(dfowl.name) class Circle(): def __init__(self, radius): self.radius = radius @property def diameter(self): return 2 * self.radius c = Circle(5) print(c.radius, c.diameter) c.radius = 7 print(c.radius, c.diameter) # Name Mangling for Privacy class Duck(): def __init__(self, input_name): self.__name = input_name def get_name(self): print('inside the getter') return self.__name def set_name(self, input_name): print('inside the setter') self.__name = input_name name = property(get_name, set_name) fowl = Duck('Howard') print(fowl.name) fowl.name = 'Donald' print(fowl.name) # print(fowl.__name) # can't access print(fowl._Duck__name) # Method Types # class method class A(): count = 0 def __init__(self): A.count += 1 def exclaim(self): print("I'm an A! ") @classmethod def kids(cls): print('A has', cls.count, 'little objects') esay_a = A() beezy_a = A() whezzy_a = A() A.kids() # static method class CoyoteWeapon(): @staticmethod def commercial(): print('This CoyoteWeapon has been brought to you by Acme') # call method CoyoteWeapon.commercial() # Duty typing class Quote(): def __init__(self, person, words): self.person = person self.words = words def who(self): return self.person def says(self): return self.words + '.' class QuestionQuote(Quote): def says(self): return self.words + '?' class ExclamationQuote(Quote): def says(self): return self.words + '!' hunter = Quote('Elmer Fudd', "I'm hunting wabbits") print(hunter.who(), 'says:', hunter.says()) hunted1 = QuestionQuote('Bugs Bunny', "What's up, doc") print(hunted1.who(), 'says:', hunted1.says()) hunted2 = ExclamationQuote('Daffy Duck', "It's rabbit season") print(hunted2.who(), 'says:', hunted2.says()) # Special Methods class Word(): def __init__(self, text): self.text = text def __eq__(self, word2): return self.text.lower() == word2.text.lower() def __str__(self): return self.text def __repr__(self): return 'Word("' + self.text + '")' a = Word('ha') b = Word('HA') c = Word('eh') print(a.__eq__(b)) print(a.__eq__(c)) print(a == b) print(a == c) print(c) # Aggregation and Composition class Bill(): def __init__(self, description): self.description = description class Tail(): def __init__(self, length): self.length = length class Duck(): def __init__(self, bill, tail): self.bill = bill self.tail = tail def about(self): print('This duck has a (', self.bill.description, ') bill and a (', self.tail.length, ') tail') a_tail = Tail('long') a_bill = Bill('wide orange') duck = Duck(a_bill, a_tail)
cfbc5acf0f0493b58b9b86540824bd0fa61bd4f3
carrenolg/python-code
/Chapter12/debugging/main.py
1,320
3.890625
4
"""Chapter 12 - Be a pythonista""" # vars def dump(func): """Print input arguments and output value(s)""" def wrapped(*args, **kwargs): print("Function name: %s" % func.__name__) print("Input arguments: %s" % ' '.join(map(str, args))) print("Input keyword arguments: %s" % kwargs.items()) output = func(*args, **kwargs) print("Output:", output) return output return wrapped @dump def double(*args, **kwargs): """Double every argument""" output_list = [2 * arg for arg in args] output_dict = {k: 2*v for k, v in kwargs.items()} return output_list, output_dict # pdb def process_cities(filename): with open(filename, 'rt') as file: for line in file: line = line.strip() if 'quit' == line.lower(): return country, city = line.split(',') city = city.strip() country = country.strip() print(city.title(), country.title(), sep=',') def func(*arg, **kwargs): print('vars:', vars()) def main(): """ # working with vars() function func(1, 2, 3) func(['a', 'b', 'argh']) double(3, 5, first=100, next=98.6, last=-40) """ # working with pdb process_cities("cities.csv") if __name__ == '__main__': main()