blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
c5b0e574459bcf1b31c18d69970cd6acfb9502bd
Gitthuma/simple-signup-and-loggin-system
/app.py
781
4.1875
4
# Create welcome message that asks to create account and takes user input print("Welcome! Please create an account:") userName = input("Please enter username: ") passWord = input("Please enter password: ") # Print a congratulations message and ask user to log in print("Congratulations! You have created a new account.") print("Please log in:") # Ask for user input and check if it matches the login credentials, if yes print a scucces message if not print a invalid credential message userNameInput = input("Please enter your user name: ") passWordInput = input("Plese enter your password: ") if userNameInput == userName and passWordInput == passWord: print("Welcome! You have successifully logged in.") else: print("Sorry! You have entered invalid credentials.")
77b53140a0c3ddab5056ebf1bd5e35724cef7dc4
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/1316.py
1,010
3.71875
4
#!/usr/bin/env python2 import logging logging.basicConfig(filename='debug.log',level=logging.DEBUG) #logging.basicConfig(level=logging.DEBUG) log = logging.getLogger("default") def tidyness(num): index = 0 length = len(num) tidy = "" prev_digit = 0 for current_char in num[::-1]: current_digit = int(current_char) if index > 0: if current_digit > prev_digit: current_digit -= 1 # replace what we wrote so far with 9's tidy = "9"*index else: tidy += str(prev_digit) prev_digit = current_digit index += 1 if prev_digit > 0: tidy += str(prev_digit) return tidy[::-1] n = int(raw_input()) # cases log.debug("Test cases: %d" % n) for i in xrange(1, n + 1): log.debug("Starting test case: %d" % i) num = raw_input() tidy = tidyness(num) log.debug("Input: %s, output: %s" % (num, tidy)) print("Case #{}: {}".format(i, tidy))
734a6ed81b7eb63eb19f3a980777c0f5054196f6
sahildua2305/Pythonic-Algorithm-Implementations
/Abstract Data Types/Lists/Ordered Lists/Implementation.py
2,073
4.21875
4
#For creating a single node class Node: def __init__(self,initdata): self.data = initdata self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self,newdata): self.data = newdata def setNext(self,newnext): self.next = newnext #Now, we create the ordered list class class OrderedList: def __init__(self): self.head = None def search(self, item): current = self.head found = False stop = False while current != None and not found and not stop: if current.getData() == item: found = True else: if current.getData() > item: stop = True else: current = current.getNext() return found #Traverses theough the list and adds in the item. def add(self, item): current = self.head previous = None stop = False #The traversal going on. Previous is used, because we want to follow one position behind the current node #in order to add. Ex: 31, 45, 56. We want to add 36. So, we traverse through the list and reach till 45. #So, now we want to add the current number behind 45. while current != None and not stop: if current.getData() > item: stop = True else: previous = current current = current.getNext() #If there is no previous, it means that the node is the head. Else, we need to insert the number and assign #previous and next accordingly to the neighbouring elements. temp = Node(item) if previous == None: temp.setNext(self.head) self.head = temp else: temp.setNext(current) previous.setNext(temp) def isEmpty(self): return self.head == True def size(self): current = self.head count = 0 while current != None: count += 1 current = current.getNext() return count #Examples for testing. Please uncomment, for usage. # mylist = OrderedList() # mylist.add(31) # mylist.add(77) # mylist.add(17) # mylist.add(93) # mylist.add(26) # mylist.add(54) # print(mylist.size()) # print(mylist.search(93)) # print(mylist.search(100))
223d2925c759a6c3a4450f43d7fb439346015323
hakaorson/CodePractise
/String/regular-expression-matching.py
2,346
3.71875
4
''' Leetcode 10 给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符 '*' 匹配零个或多个前面的那一个元素 所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。 ''' class Solution_dynamic(): def isMatch(self, s, p): s, p = '%#'+s, '%#'+p matrix = [[False for j in range(len(p))]for i in range(len(s))] matrix[0][0] = True for i in range(1, len(s)): for j in range(1, len(p)): if s[i] == p[j] or p[j] == '.': matrix[i][j] = matrix[i-1][j-1] elif p[j] == '*': if s[i] == p[j-1] or p[j-1] == '.': # 关键要注意时刻保持选择的权力 matrix[i][j] = matrix[i-1][j] or matrix[i][j-2] else: matrix[i][j] = matrix[i][j-2] else: matrix[i][j] = False return matrix[-1][-1] class Solution_recursive(): def isMatch(self, s, p): if s == '' and p == '': return True elif p == '': return False else: if len(p) >= 2 and p[1] == '*': # 主要考虑*的情况 if s and (s[0] == p[0] or p[0] == '.'): return self.isMatch(s[1:], p) or self.isMatch(s, p[2:]) ''' 一种情况是考虑现在匹配一个,其他什么都不变 还尊一种情况是考虑现在匹配了零个,其他什么都不变 ''' else: return self.isMatch(s, p[2:]) # 这种情况只能匹配零个 else: if s and (s[0] == p[0] or p[0] == '.'): return self.isMatch(s[1:], p[1:]) else: return False s = 'ab' p = '.*' ''' solu_recursive = Solution_recursive() result_recursive = solu_recursive.isMatch(s, p) print(result_recursive) ''' solu_dynamic = Solution_dynamic() result_dynamic = solu_dynamic.isMatch(s, p) print(result_dynamic)
c38c7b167df9b3fb4d7cf4004fa4f3033b2a5029
Artties/HUAWEI_Machine_Test
/Random_number_remove_duplicates.py
1,539
4
4
#明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作(同一个测试用例里可能会有多组数据,希望大家能正确处理)。 #注:测试用例保证输入参数的正确性,答题者无需验证。测试用例不止一组。 #当没有新的输入时,说明输入结束。 #输入描述: #注意:输入可能有多组数据。每组数据都包括多行,第一行先输入随机整数的个数N,接下来的N行再输入相应个数的整数。具体格式请看下面的"示例"。 #输出描述: #返回多行,处理后的结果注:测试用例保证输入参数的正确性,答题者无需验证。测试用例不止一组。 #当没有新的输入时,说明输入结束。 #输入描述: #注意:输入可能有多组数据。每组数据都包括多行,第一行先输入随机整数的个数N,接下来的N行再输入相应个数的整数。具体格式请看下面的"示例"。 #输出描述: #返回多行,处理后的结果 while True: try: a,res=int(input(),set()) for i in range(a):res.add(int(input())) for i in sorted(res):print(i) except: break
6cac5988b2612ca4ebe4c5f7d470d0e24945fd46
sprash98/Tests
/Workout/workout.py
10,120
3.765625
4
import pickle import re from collections import OrderedDict def validate_numeric_params(type,*max): if re.match("Age",type,re.I) : units = "yrs" elif re.match("Duration",type,re.I) : units = "minutes" elif re.match("Weight",type,re.I) : units = "Kgs/Lbs" else : units = "levels" while True: try: value = input("Please enter your %s in %s : " %(type,units)) value = int(value) if value <= 0 : raise ValueError if max: if value > max[0] : raise ValueError except (TypeError, ValueError) : if max : print("Please enter a positive non-zero integer value for %s " "lesser than or equal to %d %s" % (type,max[0],units)) else : print("Please enter a positive non-zero integer value for %s" %type) else : break return value class Workout(): """ Class containing the workout details Identifiers: title - Name of the workout duration - duration of workout, in minutes intervals - Total number of workout intervals settinga - An ordered dictionary where the keys are the timestamps corresponding to the intervals, and the value is a dictionary where the keys are Intensity, Workout level and Incline """ # Set bounds for numeric values max_duration = 120 max_level = 10 max_intensity = 10 max_incline = 12 def __init__(self): """ Add a workout to the list of user workouts :return: 1 """ # Add workout information self.title = input("Enter a name for the workout: ") self.duration = validate_numeric_params("duration",Workout.max_duration) self.intervals = validate_numeric_params("intervals") self.settings = OrderedDict() # If workout is on a treadmill, toggle the is_treadmill flag while True : self.is_treadmill = input("Is this a treadmill workout? (Y/N)?") if not re.search("Y|N",self.is_treadmill,re.I) : print("Please enter a Y or a N for the answer") else : if re.search("Y",self.is_treadmill,re.I) : self.is_treadmill = 1 else : self.is_treadmill = 0 break # Obtain the list of timestamps as an array times = self.process_intervals(self.duration,self.intervals) # Create the settings for each timestamp as an ordered dictionary # where the keys are the timestamps and the values are a dictionary # containing the level, intensity and incline values for time in times : print("Interval at time %d seconds" %time) intensity = validate_numeric_params("intensity",Workout.max_intensity) level = validate_numeric_params("level",self.max_level) if self.is_treadmill : incline = validate_numeric_params("incline",Workout.max_incline) else: incline = 0 self.settings[time] = {"Intensity": intensity, "WorkoutLevel": level, "Incline":incline} def process_intervals(self,duration,intervals): """ :param duration: Total time duration of workout :param intervals: Total number of time intervals :return: A list containing the timestamps corresponding to the time duration and intervals """ time_per_interval = self.duration*60//self.intervals spillover = self.duration*60%self.intervals dur = self.duration timestamps = [] current_time = 0 while intervals >0 : timestamps.append(current_time) current_time += time_per_interval intervals -= 1 return timestamps class User() : """ Class containing user information Fieklds : name - Name of user gender: Gender of user weight: Weight of the user unitweight: 1 for Kgs, 2 for Lbs max_count: Maximum no of workouts per user workouts: List of Workout objects """ workout_count = 0 workouts = [] max_count = 10 max_age = 110 def __init__(self): """ Supply user information :return: """ self.name = input("Please enter your name: ") self.age = validate_numeric_params("age",User.max_age) while True: self.gender = input("Please enter your gender (M/F): ") if re.search("M|F",self.gender,re.I) : break else: print("Please enter one of 'M' or 'F' for gender") self.weight = validate_numeric_params("weight") while True : try: self.unitWeight = input("Please select the unit for weight (1 for KGs/2 for Lbs) :") self.unitWeight = int(self.unitWeight) except ValueError: print("Please select 1 for Kg or 2 for Lb") else: if self.unitWeight == 1 or self.unitWeight == 2 : break def update_user_workouts(self,workout): """ If there are max no of workouts, it deletes the first workout and adds a new one as the last entry in the list :return: 1 """ # Pop the first/oldest entry in the list print("Deleting the first workout...") self.workouts.pop(0) self.workout_count -+ 1 # Adding the new workout to the end of the list print("Adding new workout...") self.workouts.append(workout) self.workout_count += 1 return 1 def delete_user_workout(self,key): """ :param selfself: :param key: Number or title of workout :return: 1, for successful deletion 0, if operation is unsuccessful """ # If key is specified as a number, pop that element from the list # else if key is specified as a title, remove the element matching # the tilte name. is_deleted = 0 workout = self.get_user_workout(key) if workout == None : print("Unable to delete workout. Workout specified not found. Aborting...") else : self.workouts.remove(workout) self.workout_count -=1 print("Workout deleted!") is_deleted += 1 return is_deleted def add_user_workout(self): """ Add a workout to the list of user workouts :return: Workout object, if object is successfully added None, otherwise """ is_added = 0 workout = Workout() # If the number of workouts is less than max, append the workout to the list if self.workout_count < self.max_count : self.workouts.append(workout) self.workout_count +=1 is_added +=1 else : # If the list of workouts is full, prompt before appending new workout while True: overwrite = input("All records are full. Would you like to delete" "the oldest workout and add the new one? (Y/N)") choice = re.compile("Y|N",re.I) if not choice.search(overwrite) : print("Please enter a Y or a N for the answer") else : if re.search('y',overwrite,re.I) : self.update_user_workouts(workout) is_added +=1 else : print("Workout %s not added to workout list" %workout.title) break if is_added : return workout else : return None def print_user_workout(self,key): """ Print the details of a user workout :param selfself: :param key: :return:1 """ workout = self.get_user_workout(key) if workout == None : print("Workout %s not found for printing." %key) else : for time in workout.settings.keys() : print("Intensity at time %d seconds is %d" %(time,workout.settings[time]["Intensity"])) print("Workout level at time %d seconds is %d" %(time,workout.settings[time]["WorkoutLevel"])) if workout.is_treadmill : print("Incline at time %d seconds is %d" %(time,workout.settings[time]["Incline"])) return 1 def get_user_workout(self,key): """ Return workout with specified title/index :param key: Title of workout to be returned :return: Workout object, if successful None, if failure """ is_found = 0 # Check if supplied key is the index to the list of workouts try : key = int(key) if key <1 or key > len(self.workouts): print("Invalid key specified for printing workout.") else : workout = self.workouts[key-1] is_found +=1 # If supplied key is a string, compare it to the titles of the saved workouts except ValueError: pattern = re.compile(key,re.I) for workout in self.workouts : if pattern.search(workout.title) : is_found += 1 break # If workout is found, return the object else return None if not is_found: workout = None return workout def check_user_workout(self,title): """ Verify that a workout of the specified title is present :param selfself: :param key: :return: 1, if successful 0, if unsuccessful """ if not self.get_user_workout(title) : return 0 else : return 1
618fb72bdf38974b157f55bee8eb86f8bae31e93
sulemanmahmoodsparta/Data24Repo
/Databall/a_Players.py
1,514
3.859375
4
import random # for player generation from abc import ABC, abstractmethod # An Abstract class that cannot be initialised class Players(ABC): @abstractmethod def __init__(self, fname, lname, value, position, score): self.__first_name = fname self.__last_name = lname self.__value = value self.__position = position self.__score = score @property def name(self): return f"{self.__first_name} {self.__last_name}" @property def value(self): return self.__value @property def cost(self): return self.__value @property def position(self): return self.__position @property def score(self): return self.__score class Goalkeeper(Players): # Overriding base class abstract initialiser def __init__(self, fname, lname, value, score): super().__init__(fname, lname, value, "Goalkeeper", score) class Defender(Players): # Overriding base class abstract initialiser def __init__(self, fname, lname, value, score): super().__init__(fname, lname, value, "Defender", score) class Midfielder(Players): # Overriding base class abstract initialiser def __init__(self, fname, lname, value, score): super().__init__(fname, lname, value, "Midfielder", score) class Striker(Players): # Overriding base class abstract initialiser def __init__(self, fname, lname, value, score): super().__init__(fname, lname, value, "Striker", score)
13048e126a14d55b869152a39e925dce5d57d7a5
sevencd/learnpython
/lamba.py
643
3.796875
4
square = lambda x: x ** 2 print(square(3)) print([(lambda x: x * x)(x) for x in range(10)]) l = [(1, 20), (3, 0), (9, 10), (2, -1)] l.sort(key=lambda x: x[1]) print(l) """ from tkinter import Button, mainloop button = Button( text='This is a button', command=lambda: print('being pressed')) # 点击时调⽤lambda函数 button.pack() mainloop() """ # 函数式编程 squared = map(lambda x: x ** 2, [1, 2, 3, 4, 5]) l = [1, 2, 3, 4, 5] new_list = filter(lambda x: x % 2 == 0, l) # [2, 4] print(new_list) lreduce = [1, 2, 3, 4, 5] # product = reduce(lambda x, y: x * y, lreduce) # 1*2*3*4*5 = 120 # print(product)
5c4153f0fb05f1253183b3ba554101473926ced9
IronDrago/Tic-Tac-Toe
/tic-tac-toe.py
2,348
3.703125
4
import random def create_field(): board = [['.', '.', '.'], ['.', '.', '.'], ['.', '.', '.']] return board def draw_field(board): for x in board: print(x[0], x[1], x[2]) def player_move(token, board): while True: print('Ходит ', token) line = input('Введите строку: ') column = input('Введите столбец; ') try: line = int(line) column = int(column) except: print('Вводите только цифры') continue if not(1 <= line <= 3) or not(1 <= column <= 3): print('Нельзя выбрать эту клетку. Вводите числа от 1 до 3') continue if board[line - 1][column - 1] == '.': board[line - 1][column - 1] = token return board else: print('Эта клетка уже занята') continue def is_win(board): win = [[board[0][0], board[0][1], board[0][2]], [board[1][0], board[1][1], board[1][2]], [board[2][0], board[2][1], board[2][2]], [board[0][0], board[1][0], board[2][0]], [board[0][1], board[1][1], board[2][1]], [board[0][2], board[1][2], board[2][2]], [board[0][0], board[1][1], board[2][2]], [board[0][2], board[1][1], board[2][0]]] for each in win: if (each[0] != '.') and (each[0] == each[1] == each[2]): return each[0] return False def main(board): i = random.randrange(0, 2) if i == 0: sym = 'O' else: sym = 'X' draw_field(board) count = 0 while True: player_move(sym, board) draw_field(board) count += 1 if count > 4: victory = is_win(board) if victory: print(victory + ' победил!') break if count == 9: print('Ничья!') break if sym == 'O': sym = 'X' else: sym = 'O' while True: string = input('Чтобы начать игру нажмите Enter') if not string: field = create_field() main(field) else: break
5d1e128a577c7785d7549551f8f6a14cc4dc95a1
linshaoyong/leetcode
/python/design/0232_implement_queue_using_stacks.py
1,062
4.34375
4
class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ self.data = [] def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: None """ stack = [x] tmp = [] while self.data: tmp.append(self.data.pop()) while tmp: stack.append(tmp.pop()) self.data = stack def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ return self.data.pop() def peek(self): """ Get the front element. :rtype: int """ return self.data[-1] def empty(self): """ Returns whether the queue is empty. :rtype: bool """ return len(self.data) == 0 def test_myqueue(): q = MyQueue() q.push(1) q.push(2) q.push(3) assert 1 == q.peek() assert 1 == q.pop() assert q.empty() is False
d0cff9eaed9ae3d7bebf95d19ed4425a974c0443
Elyteaa/P5
/Sandbox/AstarTemplate
3,571
3.9375
4
#!/usr/bin/python #source for the tutorial: https://www.youtube.com/watch?v=ob4faIum4kQ from Queue import PriorityQueue class State(object): #this class stores all the results of Astar algorithm functions writte below def __init__(self, value, parent, start = 0, goal = 0, solver = 0); self.children = [] self.parent = parent self.value = value self.dist = 0 if parent: self.path = parent.path[:] #[:] makes a copy of a list of parents and stores it in self.path self.path.append(value) self.start = parent.start self.goal = parent.goal self.solver = parent.solver else: self.path = [value] self.start = start self.goal = goal self.solver = solver def GetDist(self): pass def CreateChildren(self): pass class State_String(State): #this is the class defining the state (I think so) def __init__(self, value, parent, start = 0, goal = 0): super(State_String, self).__init__(value, parent, start, goal)#constructor self.dist = self.GetDist() def GetDist(self) if self.value == self.goal: #if the goal location is the same as start location return 0 dist = 0 for i in range(len(self.goal)): #in this example the function goes through the each letter of the goal pos = self.goal[i] dist += abs(i - self.value.index(pos)) #index of the position; in this case it's an index of a letter, we need an index of waypoint return dist def CreateChildren(self): # the function goes through all the possible combinations of the waypoints if not self.children: #precaution so no children are created twice for i in xrange(len(self.goal)-1): val = self.value #the value is stored val = val[:i] + val[i+1] + val[i] + val[i+2:] #this is where switcheru between letters in the word works in this example: 1st switched with 2nd and 2nd with 3rd, etc <-- this is where we need a grid with waypoints child = State_String(val, self) self.children.append(child) #adding the child to the children list class Astar_Solver: def __init__(self, start, goal): self.path = [] #this stores the solution from start state to goal state self.visitQueue = [] #this keeps track of all the children that have been visited, so we don't end up in forever loop self.PriorityQueue = PriorityQueue() self.start = start self.goal = goal def Solve(self) startState = State_String(self.start, 0, self.start, self.goal) count = 0 #this creates an id for each of the children self.PriorityQueue.put((0, count, startState)) while (not self.path and self.PriorityQueue.qzise()): #while path is empty and while priorityqueue has a size closestChild = self.PriorityQueue.get()[2] #[2] is the array, where "2" corresponds to the startState closestChild.CreateChildren() self.visitQueue.append(closestChild.value) #keeps track on which children has been visited for child in closestChild.children: if child.value not in self.visitQueue: count += 1 if not child.dist self.path = child.path break # this breaks inner for loop and program goes back into while loop self.PriorityQueue.put((child.dist, count, child)) if not self.path: print "Goal of " + self.goal "is not possible" return self.path ### main if __name__ == "__main__": start1 = "qwerty" goal1 = "wtreqy" print 'kurwa' a = Astar_Solver (start1, goal1) #initialize the solver a.Solve() #call solve function for i in xrange(len(a.path)): #get the result print "%d)" %i + a.path[i] ##### the task now is to change the logic from rearranging the letters to selecting waypoints.
efdf58aa771b30a2db40c5814ad1f2c1f13c968c
Ivernys-clone/maths-quiz1
/user details/user_details_v1.py
166
4.28125
4
#The following code is wrtitten to ask for user information name = input("What is your name") #The print fuction will display the results print("Hello",name)
1c4ee480cf8cd2612ddabda861fae32e62c2c2a7
webscienceuniform/uniform
/assignment7/uniform_assignment7_3.py
4,377
3.734375
4
import random import numpy as np import matplotlib.pyplot as plt import collections #function to rolling two diece simultaneously and returns the sum of results def rollDiceGetSum(): return random.randint(1, 6) + random.randint(1, 6) #functions to calculate CDF def calculateCDF(result): frequencyNum = collections.Counter(result).most_common() total = sum([frequency for (key, frequency) in frequencyNum]) probabilityForEachNumDict = {} for (key, frequency) in frequencyNum: probabilityForEachNumDict[key] = frequency / \ total arrayForCDFCalc = list(probabilityForEachNumDict.values()) a = np.array(arrayForCDFCalc) # Gets us CDF cdfEvalDict = np.cumsum(a) return (list(probabilityForEachNumDict.keys()), cdfEvalDict) # function to draw the histogram of sum of results def drawHistogram(sumResult): plt.hist(sumResult, bins=[2,3,4,5,6,7,8,9,10,11,12]) plt.title('Histogram with frequencies of dice sum outcomes from the simulation', y=1.06) plt.ylabel('Frequencies') plt.xlabel('Different Sum Results') plt.xticks(np.arange(2, 13, 1)) plt.grid('on') plt.show() #functions to draw CDF and shows the median and prob. of sum less or equal to 9 def drawSingleCDF(sumResult, median, probLessNnine): (xval, cdfval) = calculateCDF(sumResult) plt.title("CDF PLOT for 100 times rolling two dice(sum of two dice)") plt.xlabel("Different Sum Results") plt.ylabel("Cumulative frequency in percentage") plt.grid('on') plt.xticks(np.arange(2, 13, 1)) plt.yticks(np.arange(0, 1.1, 0.1)) plt.plot(xval, cdfval, drawstyle='steps-post', label='CDF') plt.plot((2, 13), (.5, .5)) plt.plot((median, median), (0, .5)) plt.annotate('Median: %d' % median, (median, .5), xytext=(0.7, 0.7), arrowprops=dict(arrowstyle='->')) plt.plot((2, 13), (probLessNnine, probLessNnine)) plt.annotate('Probability (<=9): %s' % probLessNnine, (9, probLessNnine), xytext=(1, 0.9), arrowprops=dict(arrowstyle='->')) plt.legend(loc=0) plt.show() #functions to draw two CDF according to random number n def drawDoubleCDF(result1, result2, n): (xval1, cdfval1) = calculateCDF(result1) (xval2, cdfval2) = calculateCDF(result2) maxDist = getMaxDistance(cdfval1, cdfval2) print(" The maximum pointwise distance between two CDFs for n= " + str(n)+ ", is =" + str(maxDist)) plt.title("CDF PLOT for " + str(n) + " times rolling two dice(sum of two dice)") plt.xlabel("Different Sum Results of rolling of two diece") plt.ylabel("Cumulative frequency in percentage") plt.xticks(np.arange(2, 13, 1)) plt.yticks(np.arange(0, 1.1, 0.1)) plt.plot(xval1, cdfval1, drawstyle='steps-post', label='CDF for first time') plt.plot(xval2, cdfval2, drawstyle='steps-post', label='CDF for second time') plt.grid('on') plt.legend(loc=0) plt.show() #functions to roll two dice uniformly upto n times. def rollDice(n): sumResult = [] for _ in range(n): result = rollDiceGetSum() sumResult.append(result) sumResult = np.sort(sumResult) return sumResult #functions to calculate median from the give array def getMedian(sumResult): a = np.array(sumResult) print("Median val: ", np.median(a)) return np.median(a) #functions to calculate probability of given value in a array def getProbByVal(arr, val): gen = [x for x in arr if x<= val] return (len(gen)/len(arr)) #functions to calculate maximum pointwise distance def getMaxDistance(result1, result2): diffResult = [abs(x - y) for x, y in zip(result1, result2)] return max(diffResult) #main function to do random sampling according to question def main(): sumResult = rollDice(100) # Draw histogram drawHistogram(sumResult) median = getMedian(sumResult) val = getProbByVal(sumResult, 9) # Draw CDF drawSingleCDF(sumResult, median, val) sumResult1 = rollDice(100) # Draw CDF for n = 100 drawDoubleCDF(sumResult, sumResult1, 100) # Draw CDF for n= 1000 result1 = rollDice(1000) result2 = rollDice(1000) drawDoubleCDF(result1, result2, 1000) if __name__ == '__main__': main()
1a473383f61ee12090dba6828fd563380fac401c
Chairmichael/ProjectEuler
/Python/Complete/0012a - Highly divisible triangular number.py
2,299
3.828125
4
''' The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? ''' primes_under_100 = [2,3,5,7,11,13,17,19,23,29,31,37,41, 43,47,53,59,61,67,71,73,79,83,89,97] def is_prime(n): if n == 2 or n == 3: return True if n < 2 or not n%2: return False if n < 9: return True if not n%3: return False r = int(n**0.5) f = 5 while f <= r: if not n%f: return False if not n%(f+2): return False f +=6 return True def primes_upto(n, start=3, calc=False): if calc: if n > 2: yield 2 for x in range(start, n, 2): if is_prime(x): yield x else: if n < 100: for p in primes_under_100: if p < n: yield p else: if n > 2: yield 2 for x in range(start, n, 2): if is_prime(x): yield x def triangle_numbers(ceiling, start=1): x = 0 if start == 1: yield 1 for i in range(1, ceiling+1): x+=i if start < i: yield x def prime_factors(n): # primes = primes_upto(n//2) factors = [ ] for d in primes_under_100: if not n%d: #divisable n //= d factors.append(d) while not n%d: n //= d factors.append(d) return factors def number_of_divisors(n): factors = prime_factors(n) num = 1 for i in list(set(factors)): num *= factors.count(i) + 1 return num def main(): largest = 0 for i, x in enumerate(triangle_numbers(100000), start=1): n = number_of_divisors(x) # print(f'\ti{i}\tx{x}\tn{n}') if largest < n: largest = n print(i, largest) if n > 500: print(f'OVER 500: num={x}, divs={n}, i={i}') break if __name__ == '__main__': main()
b0a81e258dff8966d08dd1f228fb5ac20aa6f740
Metbaron/Pong
/Pong1.py
4,053
3.9375
4
import turtle import os wn = turtle.Screen() # create window wn.title("Pong") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) # stops automatic updating # Score score_a = 0 score_b = 0 # Paddle A paddle_a = turtle.Turtle() # Turtle object paddle_a.speed(0) # speed of animation to max paddle_a.shape("square") # built in shapes paddle_a.color("white") paddle_a.shapesize(stretch_wid=5, stretch_len=1) # change size of rectangle paddle_a.penup() # something with lines paddle_a.goto(-350, 0) # Navigator # Paddle B paddle_b = turtle.Turtle() # Turtle object paddle_b.speed(0) # speed of animation to max paddle_b.shape("square") # built in shapes paddle_b.color("white") paddle_b.shapesize(stretch_wid=5, stretch_len=1) # change size of rectangle paddle_b.penup() # something with lines paddle_b.goto(350, 0) # Navigator # Ball ball = turtle.Turtle() # Turtle object ball.speed(0) # speed of animation to max ball.shape("square") # built in shapes ball.color("white") ball.penup() # something with lines ball.goto(0, 0) # Navigator ball.dx = 0.5 # x-axis movement of ball, new attribute ball.dy = 0.5 # y-axis movement of ball # Pen for keeping score pen = turtle.Turtle() pen.speed(0) pen.color("white") pen.penup() # no drawing line when pen moves pen.hideturtle() pen.goto(0, 260) pen.write("Player A: 0 Player B: 0", align="center", font=("Courier", 24, "normal")) # Game functions def paddle_a_up(): # consider taking paddle as input # get y coordinate and change it to new value y = paddle_a.ycor() # get y coordinates y += 20 paddle_a.sety(y) def paddle_a_down(): # Todo consider taking paddle as input # Todo way to stop going over top/bottom # get y coordinate and change it to new value y = paddle_a.ycor() # get y coordinates y -= 20 paddle_a.sety(y) def paddle_b_up(): y = paddle_b.ycor() y += 20 paddle_b.sety(y) def paddle_b_down(): y = paddle_b.ycor() y -= 20 paddle_b.sety(y) # Keyboard binding wn.listen() # listen for input wn.onkey(paddle_a_up, "w") # move up on pressing w wn.onkey(paddle_a_down, "s") wn.onkey(paddle_b_up, "Up") wn.onkey(paddle_b_down, "Down") # Main game loop, required for every game, runs constantly while True: wn.update() # Move the ball ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) # Border checking if ball.ycor() > 290: # account for ball size ball.sety(290) # reset position ball.dy *= -1 # reverse direction os.system("aplay bounce.wav&") # & stops delay after playing sound if ball.ycor() < -290: ball.sety(-290) ball.dy *= -1 os.system("aplay bounce.wav&") # Todo make it so that ball starts from pedal # Todo create scoring function to update on hit if ball.xcor() > 390: ball.goto(0, 0) # reset ball ball.dx *= -1 # reverse direction score_a += 1 # score keeping pen.clear() # delete previous score pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center", font=("Courier", 24, "normal")) if ball.xcor() < -390: ball.goto(0, 0) ball.dx *= -1 score_b += 1 pen.clear() pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center", font=("Courier", 24, "normal")) # Paddle ball collision # Collision when ball hits certain x coord and y coord of paddle if (ball.xcor() > 340 and ball.xcor() < 350) and \ (ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40): ball.setx(340) # set ball to correct position ball.dx *= -1 os.system("aplay bounce.wav&") if (ball.xcor() < -340 and ball.xcor() > -350) and \ (ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40): ball.setx(-340) # set ball to correct position ball.dx *= -1 os.system("aplay bounce.wav&") # Todo fixed update speed
0534aec84e9bd75e34af0dfec07f5fd179e0fc42
Uttam1982/PythonTutorial
/02-Python-Flow-Control/01-If-else.py
2,654
4.375
4
# What is if...else statement in Python? # Decision making is required when we want to execute a code only # if a certain condition is satisfied. # The if…elif…else statement is used in Python for decision making. # ****************************************************************************** # Python if Statement Syntax # ****************************************************************************** # Will execute statement(s) only if the test expression is True. # If the test expression is False, the statement(s) is not executed. # Example: Python if Statement num = 5 if num > 0: print(num, "is a postive number") print("This will always be printed") num = -1 if num > 0: print(num, "is a postive number") print("This will always be printed") # ****************************************************************************** # Python if...else Statement # ****************************************************************************** # If the condition is False, the body of else is executed. # Indentation is used to separate the blocks. # Example of if...else #num = 5 #num = -1 num = 0 if num >= 0: print("Positive or zero") else: print("Negative number") # ****************************************************************************** # Python if...elif...else Statement # ****************************************************************************** # The elif is short for else if. It allows us to check for multiple expressions. # If the condition for if is False, it checks the condition of the next elif block and so on. # If all the conditions are False, the body of else is executed. # The if block can have only one else block. But it can have multiple elif blocks. # Example of if...elif...else '''In this program, we check if the number is positive or negative or zero and display an appropriate message''' num = 5 # num = 0 # num = -1 if num > 0: print("positive number") elif num == 0: print("Zero") else: print("Negaive number") # ****************************************************************************** # Python Nested if statements # ****************************************************************************** # We can have a if...elif...else statement inside another if...elif...else statement. # This is called nesting in computer programming. '''In this program, we input a number check if the number is positive or negative or zero and display an appropriate message This time we use nested if statement''' num = float(input("Enter a number : ")) if num >= 0: if num == 0: print("zero") else: print("Positive number") else: print("Negative number")
ed135c2dd4b6ce99268194d97e9117bc43abafc4
jmdibble/python-exercises
/ex6.py
164
4.03125
4
word = str(input("Type your favourite word: ")) word = word.lower() new_word = word[::-1] if new_word == word: print("Yay!") else: print("Nope")
8e9ceeff6c9927830455a17d3b6fcdb9813888fc
biyoner/-offer_python_code
/50第一个只出现一次的字符_02.py
1,187
3.671875
4
#coding= utf-8 #author:Biyoner import collections class CharStatistics(object): def __init__(self): self.occurrrence = collections.OrderedDict() def Insert(self,ch): if self.occurrrence.has_key(ch): if self.occurrrence[ch] >0: self.occurrrence[ch] = -2 else: self.occurrrence[ch] = 1 def FirstAppearingOnce(self): val = "" for key in self.occurrrence.keys(): if self.occurrrence[key] >0: val = key break return val def Test(name, ch,expectedValue): if ch.FirstAppearingOnce() == expectedValue: print name + " is passed !" else: print name + " is failed !" if __name__ == "__main__": chars = CharStatistics() Test("Test1", chars, "") chars.Insert("g") Test("Test2", chars, 'g') chars.Insert('o') Test("Test3", chars, 'g') chars.Insert('o') Test("Test4", chars, 'g') chars.Insert('g') Test("Test5", chars, "") chars.Insert('l') Test("Test6", chars, 'l') chars.Insert('e') Test("Test7", chars, 'l')
675c46c9b05e7fa7f74a9113a2b15f50d6bbdf21
mastermind2001/Problem-Solving-Python-
/snail's_journey.py
1,349
4.3125
4
# Date : 23-06-2018 # A Snail's Journey # Each day snail climbs up A meters on a tree with H meters in height. # At night it goes down B meters. # Program which takes 3 inputs: H, A, B, and calculates how many days it will take # for the snail to get to the top of the tree. # Input format : # 15 # For H # 1 # For A # 0.5 # For B # # where H > A > B import math def snail_journey(height_of_tree, climbs_up, climbs_down): """ :param height_of_tree: Height of tree :param climbs_up: snail climbs up A meters each day on a tree :param climbs_down: snail climbs down B meters each night from a tree :return: number of days it takes to climb tree """ days = (height_of_tree - climbs_down) / (climbs_up - climbs_down) return 'Snail will take ' + str(math.ceil(days)) + ' days to climb the tree.' # input positive integer values H = input() A = input() B = input() # error handling for wrong input try: if float(H) and float(A) and float(B): H = float(H) A = float(A) B = float(B) if H > A > B: # calling function snail_journey print(snail_journey(H, A, B)) else: raise ValueError except ValueError: print("""Invalid input. You can enter only positive numbers.\n Input format :\n 15 # For H 1 # For A 0.5 # For B where H > A > B.""")
e1402f9b16225913799870056215b643a961bcd2
zuowanbushiwo/Speechprocess_t
/readwritewav.py
1,312
3.53125
4
# !usr/bin/env python # coding=utf-8 import wave import matplotlib.pyplot as plt import numpy as np def read_wave_data(file_path): # open a wave file, and return a Wave_read object f = wave.open(file_path, "rb") # read the wave's format infomation,and return a tuple params = f.getparams() # get the info # 读取格式信息 # (声道数、量化位数、采样频率、采样点数、压缩类型、压缩类型的描述) # (nchannels, sampwidth, framerate, nframes, comptype, compname) nchannels, sampwidth, framerate, nframes = params[:4] # Reads and returns nframes of audio, as a string of bytes. str_data = f.readframes(nframes) # close the stream f.close() # turn the wave's data to array wave_data = np.fromstring(str_data, dtype=np.short) # for the data is stereo,and format is LRLRLR... # shape the array to n*2(-1 means fit the y coordinate) wave_data.shape = -1, 2 # transpose the data wave_data = wave_data.T # calculate the time bar time = np.arange(0, nframes) * (1.0 / framerate) return wave_data, time def main(): wave_data, time = read_wave_data("C:\Users\CJP\Desktop\miss_you.wav") # draw the wave plt.plot(time, wave_data[0]) plt.show() if __name__ == "__main__": main()
e9c7ada1853ad4429fe42d6549263fefdcb34280
Da-Yuan/LeetCode-Python
/LeetCode-217.py
445
3.640625
4
# 给定一个整数数组,判断是否存在重复元素。 # 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。 def Solution1(nums): # 超出时间限制 if len(nums)==1: return False for i in range(len(nums)): for j in range(len(nums)-i-1): if nums[i]==nums[-j-1]: return True return False a1=[1,2,3,1] a2=[1,2,3,4] a3=[3,1] print(Solution(a3))
abdc2fb4e7be0a91d0602d1c8fc1f9affc5b0a98
bjan94/Interview-Questions
/strings/NextClosestTime.py
1,501
4.15625
4
from itertools import product """ Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused. You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid. Example 1: Input: "19:34" Output: "19:39" Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later. Example 2: Input: "23:59" Output: "22:22" Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day's time since it is smaller than the input time numerically. """ def next_closest_time(time): start = ans = int(time[:2]) * 60 + int(time[3:]) min_elapsed = minutes_in_day = 24 * 60 allowed = {int(x) for x in time if x != ':'} for h0, h1, m0, m1 in product(allowed, repeat=4): hour = h0 * 10 + h1 minute = m0 * 10 + m1 if hour < 24 and minute < 60: cur_mins = hour * 60 + minute cur_elapsed = (cur_mins - start) % minutes_in_day if 0 < cur_elapsed < min_elapsed: ans = cur_mins min_elapsed = cur_elapsed return "{:02d}:{:02d}".format(*divmod(ans, 60)) def main(): print(next_closest_time("19:34")) if __name__ == "__main__": main()
43cfe1e24f52f44424c88854dfc86830448c996a
DRTooley/AlgorithmsReview
/UCSD/Week1-SuffixTree/suffix_tree/suffix_tree.py
1,019
3.953125
4
# python3 import sys class Edge: def __init__(self, begin, end): self.begin = begin self.end = end class Node: def __init__(self, value, edges=None): self.value = value if edges is None: self.edges = set() else: self.edges = edges def build_suffix_tree(text): """ Build a suffix tree of the string text and return a list with all of the labels of its edges (the corresponding substrings of the text) in any order. """ root = Node(0) end = Node(len(text)-1) e = Edge(root, end) for i in range(1, len(text), 1): n = root current_index = i while n: for e in n.edges: if text[current_index] == text[n.value] result = [] # Implement this function yourself return result if __name__ == '__main__': text = sys.stdin.readline().strip() result = build_suffix_tree(text) print("\n".join(result))
04964f9c07d41cb53a0ce02e68c57f579aa0fb11
dgallab/exercises_in_python
/python_f/data structures/LinkedList.py
1,463
4.125
4
class Node(): def __init__(self, dataval): self.dataval = dataval self.nextval = None #this will be another node class LinkedList(): def __init__(self): self.headval = None #this will be a node, not a datavalue def add_node(self,node): if self.headval is None: self.headval = node else: x=self.headval while x.nextval is not None: x=x.nextval x.nextval = node def remove_node(self, val): x=self.headval if (x is not None) and (x.dataval == val): self.headval = x.nextval x=None else: y=x.nextval while (x is not None): if y.dataval == val: x = y y = y.nextval break if x == None: return x.nextval=y.nextval x=None def print_LL(self): cn = self.headval while cn is not None: print(cn.dataval) cn=cn.nextval def main(): a=Node("a") b=Node("b") c=Node("z") LL = LinkedList() LL.add_node(a) LL.add_node(b) LL.add_node(c) LL.print_LL() print('\n') LL.remove_node("z") LL.print_LL() main()
6dc7cb539824494aaa748ed1893403740a6192bd
Lavekernis/Problemy
/Problemy/Problem114_2.py
1,735
3.640625
4
#Wcześniejsza próba implementacji za pomocą rekurecji z zapisywaniem '''from memorised.decorators import memorise @memorise() def possib(n): if n < 3: return 1 else: sum = 1 for i in range(0,n-3): sum += possib(i) return possib(n-1)+sum''' #Iteracyjna wersja SIZE = 50 combinations = [0] #Tworzymy tabelę do zapisu poprzednich sytuacji for i in range(SIZE): combinations.append([0]) #Uzupełniamy powoli tabelę for n in range(len(combinations)): #Dla sytuacji w której mamy n mniejsze niż 3 możliwe miejsca mamy jedną mozliwość i jest nią brak czerwonych kratek if n < 3: combinations[n] = 1 else: #Sytuację można rozważyć tak jak problem wieży Hanoi, tylko w tym przyadku zrobimy to "iterując rekurencyjnie" #dla danego n możemy mieć sytuację w której: # - mamy wypełnione wszystkie bloczki czyli 1 # - mamy na ostatnim miejscu jeden pusty bloczek, a wiec sytuacja tak naprawdę sprowadza się dla planszy n-1 # sytuacja gdy na końcu będą 2, 3, 4, 5, ... wolnych miejsc jest juz zawarta wyżej # - dojdziemy do stuacji, gdy n-3-1, to w wolne miejsce po prawej możemy wpisać bloczek (ponieważ są 3 wolne miejsca z odstępem), # a więc należy to odpowiednio uwaględnić. Robimy to poprzez warunek sum(combinations[ : n - 3]), który jest zapisany odwrotnie, ponieważ bierze pod uwagę, że nasze # rozumowanie prowadzimy od końca, natomiast liczymy od początku combinations[n] = combinations[n - 1] + sum(combinations[ : n - 3]) + 1 print(combinations[-1])
214b4ec7a5aef78faa152d56b253692eb3f9c8c2
taolin1996/Algorithm
/Chapter1/insert_sort.py
464
3.5
4
import random import time def insert_sort(A,n): j = 0 for i in range(0,n-1): j = i key = A[j+1] #print("key =",key) while((key < A[j]) & (j >= 0)): A[j+1] = A[j] j -= 1 A[j+1] = key test = [random.randint(1,800000) for i in range(10000)] #print(test) start = time.time() insert_sort(test, len(test)) print("Time used:", time.time()-start) #print(test)
6c86520234d5bbeeecc1296d16185c60e4eac6c3
chr0m3/boj-codes
/0/1/1260/1260.py
1,873
3.609375
4
import collections import sys import time input = sys.stdin.readline def find_next(n: int, v: int, graph: list, visited: list): for i in range(1, n + 1): if graph[v][i] is True and visited[i] is False: # Connected and not visited. return i return None def dfs(n: int, v: int, graph: list) -> list: visited = [False for _ in range(n + 1)] order = list() path = list() current = v while True: if visited[current] is False: order.append(current) visited[current] = True # Find and move to next vertex. next = find_next(n, current, graph, visited) if next is not None: path.append(current) current = next continue # DFS finished. if len(path) == 0: break # Backtrack. current = path.pop() return order def bfs(n: int, v: int, graph: list) -> list: visited = [False for _ in range(n + 1)] order = list() queue = collections.deque() current = v while True: if visited[current] is True: # BFS finished. if len(queue) == 0: break # Move to next vertex. current = queue.popleft() continue visited[current] = True order.append(current) # Find next vertexes. for i in range(1, n + 1): if graph[current][i] is True: queue.append(i) return order if __name__ == '__main__': n, m, v = map(int, input().split()) graph = [[False for _ in range(n + 1)] for _ in range(n + 1)] for _ in range(m): a, b = map(int, input().split()) graph[a][b] = True graph[b][a] = True print(' '.join(map(str, dfs(n, v, graph)))) print(' '.join(map(str, bfs(n, v, graph))))
79265dee5a7f6e7683e2b73b54d9baf9f1033a64
gsudarshan1990/Training_Projects
/Classes/class_example6.py
470
4.15625
4
"""This is an example of class which initializes twice""" class Person: """This class describes about the person""" def __init__(self): """This is used to intialize the values""" self.firstname = "Johny" self.lastname = "Depp" self.eyecolor = "grey" self.age = 42 person1 = Person() person2 = Person() person1.name = "David" person2.name = "James" print("Person 1 name",person1.name) print("Person 2 name",person2.name)
499b2d8b89769ce4bc332b665a7ee149ea1158f0
borko81/python_fundamental_solvess
/Final Exam Preparation - 24 July 2019/03. The Isle of Man TT Race.py
2,010
3.546875
4
import re FOUND = False pattern = re.compile(r'^([\#, \$, \%, \*, \&])(\w+)(\1)=(\d+)!!(\S+)') while not FOUND: notes = input() length = len(notes) temp = pattern.match(notes) if temp and int(temp.group(4)) == len(temp.group(5)): increase_with = int(temp.group(4)) hash_code = "".join([chr(ord(i) + increase_with) for i in temp.group(5)]) print(f"Coordinates found! {temp.group(2)} -> {hash_code}") FOUND = True else: print('Nothing found!') ''' Write a program that decrypts messages. You’re going to receive a few notes that contain the following information: • Name of racer ◦ Consists only of letters. It is surrounded from the both sides by any of the following symbols – "#, $, %, *, &". Both symbols – in the beginning and at the end of the name should match. • Length of geohashcode ◦ Begins after the "=" sign and it is consisted only of numbers. • Encrypted geohash code ◦ Begins after these symbols - “!!”. It may contain anything and the message always ends with it. Examples for valid input: #SteveHislop#=16!!tv5dekdz8x11ddkc Examples of invalid input: %GiacomoAgostini$=7!!tv58ycb – The length is the same, but the name is not surrounded by matching signs. $GeoffDuke$=6!!tuvz26n35dhe4w4 – The length doesn't match the lengh of the code. &JoeyDunlop&!!tvndjef67t=14 – The length should be before the code. The information must be in the given order, otherwise it is considered invalid. The geohash code you are looking for is with length exactly as much as the given length in the message. To decrypt the code you need to increase the value of each symbol from the geohashcode with the given length. If you find a match, you have to print the following message: "Coordinates found! {nameOfRacer} -> {geohashcode}" and stop the program. Otherwise, after every invalid message print: "Nothing found!" Input / Constraints'''
0a73fa0abb613fe52c35ae0e4a59b0861fecce96
kucherskyi/train
/lesson07/task06.py
482
3.8125
4
#!/usr/bin/env python """ Write a generator that consumes lines of a text and prints them to standard output. Use this generator and a flatten function from the previous task to print contents of two different files to a screen pseudo-simultaneously. """ from task05 import flatten def line_writer(): yield while True: print (yield) generate = line_writer() generate.next() for line in flatten(open('alice.txt'), open('alice01.txt')): generate.send(line)
602453edd8ae15a89bfab021a4427fc6d4b15c5e
KhangNLY/Py4E
/Assignment/Course 1 - Programming for Everybody (Getting Started with Python)/Week 6/4.6.py
238
3.828125
4
def computepay(h, r): if h > 40: return 40 * r + (h - 40) * (r * 1.5) else: return h * r hrs = input("Enter Hours:") rate = input("Enter Rate:") p = computepay(float(hrs), float(rate)) print("Pay", p)
d68124c47ce8939dc69bf08b6d38758b8c09dc3b
Teresa90/demo
/assisngment2.py
805
4.09375
4
import math def introduction_message(): print("This program computers the roots") print("of a second order equation:") print() print(" ax^2+bx+c=0 ") print() def input_and_solve(): a = eval(input ("please enter a: ")) b = eval(input ("please enter b: ")) c = eval(input ("please enter c: ")) delta = (b*b) - (4*a*c) xl = -b + math.sqrt(delta) x2 = -b - math.sqrt(delta) print() print("The roots are : ") print("xl = ", xl) print("x2 = ", x2) def final_message(): print() print(" Thank you for using this program") print("=================================") print("*** All rights reserved ***") print("=================================") print() introduction_message() input_and_solve() final_message()
f6ec074233d94acb8658090f547968fcbf2b34de
elabzina/python-washu-2014
/hw4/classes.py
4,380
4.03125
4
class Node(): def __init__(self, _value=None, _next=None): self.value=_value self.next=_next def __str__(self): return str(self.value) class LinkedList(): #pointers to the first and last nodes of the link are stored, also len stores the number of nodes. #in case of the cycles len stops making sense; overall def __init__(self,value=None): if (not isinstance(value,int)): self.last=self.start=Node(None) self.len=0 else: self.last=self.start=Node(value) self.len=1 @staticmethod def intCheck(value): if (not isinstance((value),int)): print "The number you entered is not an interger!" return False return True #Computation complexity is 1, since the node is just added to the end, while the end is stored as self.last No way to make it more efficient. def addNode(self,new_value): if (not LinkedList.intCheck(new_value)): return self.last.next=Node(new_value) self.last=self.last.next self.len+=1 #Without checking whether this code is in this list, the complexity is 1, hence it's know where exactly to add it. Including the check, the complexity is proportional to the length of the list, #and since this is not a sorted list or something similar, there's no way to improve it def addNodeAfter(self,new_value,after_node): if (not LinkedList.intCheck(new_value)): return search=self.start while (search.next!=after_node and search!=None): search=search.next if (search==None): print "No such node!" return tail = after_node.next after_node.next = Node(new_value) after_node.next.next=tail self.len+=1 #Exactly the same situation as in the previous case. def addNodeBefore(self,new_value,before_node): if (not LinkedList.intCheck(new_value)): return search=self.start while (search.next!=before_node and search!=None): search=search.next if (search==None): print "No such node!" return search.next = Node(new_value) search.next.next=before_node self.len+=1 #Exactly the same situation as in the previous case. def removeNode(self,node_to_remove): search=self.start while (search.next!=node_to_remove and search!=None): search=search.next if (search==None): print "No such node!" return tail=node_to_remove.next search.next=tail node_to_remove=None self.len-=1 #All nodes are looked at it one by one. The complexity equals to the number of the nodes. Because of the structure of the data, no way exists to decrease this number. def removeNodeByValue(self,value): if (not LinkedList.intCheck(value)): return search=self.start while (search!=None): if (search.value==value): aux=search search=search.next self.removeNode(aux) else: search=search.next def __str__(self): if (self.isCycle()): return "The list contains cycles and can't be displayed properly" tail=self.start out="" while (tail!=None): out+=str(tail)+" -> " tail=tail.next out+="NULL" return out def length(self): s = "Length: "+str(self.len) return s def reverse(self): tail=self.last=self.start self.start=None while (tail!=None): aux=tail tail=tail.next aux.next=self.start self.start=aux #function to understand whether the list has a cycle #the idea is to move the lookup pointer node by node in the list checking whether the link of the pointer is linked #to a node behind the lookup pointer def isCycle(self): if (self.start==None): return False if (self.start.next==self.start):return True search = self.start lookup=self.start.next while (lookup.next!=None): while (search.next!=lookup): if (lookup.next==search): return True search=search.next lookup=lookup.next search=self.start return False
3b7247bd24ffd07cbd139217f35f20f2311d7e54
TheAlgorithms/Python
/ciphers/decrypt_caesar_with_chi_squared.py
9,452
4.5625
5
#!/usr/bin/env python3 from __future__ import annotations def decrypt_caesar_with_chi_squared( ciphertext: str, cipher_alphabet: list[str] | None = None, frequencies_dict: dict[str, float] | None = None, case_sensitive: bool = False, ) -> tuple[int, float, str]: """ Basic Usage =========== Arguments: * ciphertext (str): the text to decode (encoded with the caesar cipher) Optional Arguments: * cipher_alphabet (list): the alphabet used for the cipher (each letter is a string separated by commas) * frequencies_dict (dict): a dictionary of word frequencies where keys are the letters and values are a percentage representation of the frequency as a decimal/float * case_sensitive (bool): a boolean value: True if the case matters during decryption, False if it doesn't Returns: * A tuple in the form of: ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher ) where... - most_likely_cipher is an integer representing the shift of the smallest chi-squared statistic (most likely key) - most_likely_cipher_chi_squared_value is a float representing the chi-squared statistic of the most likely shift - decoded_most_likely_cipher is a string with the decoded cipher (decoded by the most_likely_cipher key) The Chi-squared test ==================== The caesar cipher ----------------- The caesar cipher is a very insecure encryption algorithm, however it has been used since Julius Caesar. The cipher is a simple substitution cipher where each character in the plain text is replaced by a character in the alphabet a certain number of characters after the original character. The number of characters away is called the shift or key. For example: Plain text: hello Key: 1 Cipher text: ifmmp (each letter in hello has been shifted one to the right in the eng. alphabet) As you can imagine, this doesn't provide lots of security. In fact decrypting ciphertext by brute-force is extremely easy even by hand. However one way to do that is the chi-squared test. The chi-squared test ------------------- Each letter in the english alphabet has a frequency, or the amount of times it shows up compared to other letters (usually expressed as a decimal representing the percentage likelihood). The most common letter in the english language is "e" with a frequency of 0.11162 or 11.162%. The test is completed in the following fashion. 1. The ciphertext is decoded in a brute force way (every combination of the 26 possible combinations) 2. For every combination, for each letter in the combination, the average amount of times the letter should appear the message is calculated by multiplying the total number of characters by the frequency of the letter For example: In a message of 100 characters, e should appear around 11.162 times. 3. Then, to calculate the margin of error (the amount of times the letter SHOULD appear with the amount of times the letter DOES appear), we use the chi-squared test. The following formula is used: Let: - n be the number of times the letter actually appears - p be the predicted value of the number of times the letter should appear (see #2) - let v be the chi-squared test result (referred to here as chi-squared value/statistic) (n - p)^2 --------- = v p 4. Each chi squared value for each letter is then added up to the total. The total is the chi-squared statistic for that encryption key. 5. The encryption key with the lowest chi-squared value is the most likely to be the decoded answer. Further Reading ================ * http://practicalcryptography.com/cryptanalysis/text-characterisation/chi-squared- statistic/ * https://en.wikipedia.org/wiki/Letter_frequency * https://en.wikipedia.org/wiki/Chi-squared_test * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> decrypt_caesar_with_chi_squared( ... 'dof pz aol jhlzhy jpwoly zv wvwbshy? pa pz avv lhzf av jyhjr!' ... ) # doctest: +NORMALIZE_WHITESPACE (7, 3129.228005747531, 'why is the caesar cipher so popular? it is too easy to crack!') >>> decrypt_caesar_with_chi_squared('crybd cdbsxq') (10, 233.35343938980898, 'short string') >>> decrypt_caesar_with_chi_squared('Crybd Cdbsxq', case_sensitive=True) (10, 233.35343938980898, 'Short String') >>> decrypt_caesar_with_chi_squared(12) Traceback (most recent call last): AttributeError: 'int' object has no attribute 'lower' """ alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) frequencies = { "a": 0.08497, "b": 0.01492, "c": 0.02202, "d": 0.04253, "e": 0.11162, "f": 0.02228, "g": 0.02015, "h": 0.06094, "i": 0.07546, "j": 0.00153, "k": 0.01292, "l": 0.04025, "m": 0.02406, "n": 0.06749, "o": 0.07507, "p": 0.01929, "q": 0.00095, "r": 0.07587, "s": 0.06327, "t": 0.09356, "u": 0.02758, "v": 0.00978, "w": 0.02560, "x": 0.00150, "y": 0.01994, "z": 0.00077, } else: # Custom frequencies dictionary frequencies = frequencies_dict if not case_sensitive: ciphertext = ciphertext.lower() # Chi squared statistic values chi_squared_statistic_values: dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(alphabet_letters)): decrypted_with_shift = "" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet new_key = (alphabet_letters.index(letter.lower()) - shift) % len( alphabet_letters ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter chi_squared_statistic = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: letter = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.lower().count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary chi_squared_statistic_values[shift] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(key: int) -> tuple[float, str]: return chi_squared_statistic_values[key] most_likely_cipher: int = min( chi_squared_statistic_values, key=chi_squared_statistic_values_sorting_key, ) # Get all the data from the most likely cipher (key, decoded message) ( most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, ) = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
4aa73fe746ce789c8c6bfe9ff4d070e739831d01
bbdavidbb/A_Star-Search-Algorithm
/puzzle.py
4,019
3.765625
4
import random from copy import deepcopy from itertools import chain def gen_puzzle_n(n): """ Generate a puzzle of size nxn @param n(int) The len of row and col @return puzzle(2d list) An nxn 2d list """ size = n * n temp = list(range(size)) temp = sorted(temp, key=lambda x: random.random()) puzzle = [temp[i:i + n] for i in range(0, len(temp), n)] return puzzle def move(puzzle, direction): """ Swap a tile with the empty tile if possible @param puzzle A 2d list in which the tile is swapped @param direction The direction the tile is moved @return A copy of the puzzle with the tile swapped with the empty tile or none if the empty tile is not in that direction """ x, y = coord_of_tile(puzzle, 0) x2, y2 = x + direction[0], y + direction[1] if x2 not in range(len(puzzle)) or y2 not in range(len(puzzle[0])): return None nPuzzle = deepcopy(puzzle) nPuzzle[x][y], nPuzzle[x2][y2] = nPuzzle[x2][y2], nPuzzle[x][y] return nPuzzle def coord_of_tile(puzzle, tile_to_find): """ Find the 2D coordinates of a tile give a puzzle @param puzzle A 2d list @param tile_to_find An int within the constraints of the puzzle """ for x, column in enumerate(puzzle): for y, tile in enumerate(column): if tile == tile_to_find: return x, y def up(puzzle): """ Swap a tile with the empty tile in the up direction @param puzzle a 2d list @return the puzzle with the tile swapped or None otherwise """ return move(puzzle, [1, 0]) def down(puzzle): """ Swap a tile with the empty tile in the down direction @param puzzle a 2d list @return the puzzle with the tile swapped or None otherwise """ return move(puzzle, [-1, 0]) def left(puzzle): """ Swap a tile with the empty tile in the left direction @param puzzle a 2d list @return the puzzle with the tile swapped or None otherwise """ return move(puzzle, [0, 1]) def right(puzzle): """ Swap a tile with the empty tile in the right direction @param puzzle a 2d list @return the puzzle with the tile swapped or None otherwise """ return move(puzzle, [0, -1]) def printPuzzle(puzzle): """ Print a puzzle in the standard grid format @param puzzle a 2d list """ for i in range(len(puzzle)): for j in range(len(puzzle[i])): print(puzzle[i][j], end=' ') print() def is_solvable(puzzle, final_state, n): """ Determine if a given puzzle is solvable with the given final solution @param puzzle a 2d list @param final_state The solved state of the puzzle @param n the len of the puzzle's row/col @return True if the puzzle is solvable False othewise """ flatten_puzzle = list(chain.from_iterable(puzzle)) # flatten the list inversions = inv_count(flatten_puzzle, final_state, n) puzzle_zero_row, puzzle_zero_column = coord_of_tile(puzzle, 0) puzzle_zero_row = puzzle_zero_row // n puzzle_zero_column = puzzle_zero_column % n final_zero_row, final_zero_column = coord_of_tile(final_state, 0) final_zero_column = final_zero_column % n manhattan = abs(puzzle_zero_row - final_zero_row) + abs(puzzle_zero_column - final_zero_column) if manhattan % 2 == 0 and inversions % 2 == 0: return True if manhattan % 2 == 1 and inversions % 2 == 1: return True return False def inv_count(puzzle, final_state, n): """ Count the number of inversions in a puzzle @param puzzle a 2d list @param final_state The solved state of the puzzle @param n the len of the puzzle's row/col @return An int that is the number of inversions """ inversions = 0 n_2 = n * n for i, tile in [(i, tile) for i, tile in enumerate(puzzle) if tile != len(puzzle)]: for j in range(i+1, n_2): if puzzle[j] < tile: inversions += 1 return inversions
4ff35b87bbc3bb3d996aebc45e5c8a1c17a1bf1b
upat0003/Data-Structure-Algorithms
/MIPS and Logical sequences/task1b.py
375
4.3125
4
year=int(input("Enter the year:")) #asking to enter the year to compare if(year<1582): print("Enter number greater than 1581") #if the condion meets, it will print the following statement else: if((year%4==0 and year%100!=0) or (year%400==0)): print("Is leap year") else: print("Is not a leap year")
e2f65a57ea2e9aa3860b1663bed20710832c4477
Ovidiu2004/Instruc-iunea-FOR
/5for.py
119
3.859375
4
nr=int(input("numarul este")) s=0 for a in range(1,nr+1): if a%3==0 or a%5==0: s=s+a print("suma =",s)
bab7c7342d0cfddb3b9349e9ae9173b1123efd0a
berkercaner/pythonTraining
/Chap08/sets.py
445
3.953125
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ """ It's a collection type. contains unordered collection of unique and immutable objects """ def main(): a = set("We're gonna need a bigger boat.") b = set("I'm sorry, Levy. I'm afraid I can't do that.") print_set(a) print_set(b) def print_set(o): print('{', end = '') for x in o: print(x, end = '') print('}') if __name__ == '__main__': main()
dfcfb04ad15486e26f33af3cd260d7622712ecd7
webjoaoneto/spotify-playlist-downloader-gui
/actions/youtube.py
1,929
3.515625
4
#!/usr/bin/python # This sample executes a search request for the specified search term. # Sample usage: # python search.py --q=surfing --max-results=10 # NOTE: To use the sample, you must provide a developer key obtained # in the Google APIs Console. Search for "REPLACE_ME" in this code # to find the correct place to provide that key.. import argparse from googleapiclient.discovery import build from googleapiclient.errors import HttpError # Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps # tab of # https://cloud.google.com/console # Please ensure that you have enabled the YouTube Data API for your project. # Ok, i know that is a mistake to put my credentials here # but I'd rather believe in humanity PINDAMONHANGABA = 'AIzaSyBkwliFIrRV5uDZJksrXdRkdNlbnR0sBxQ' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' def youtube_search( q, max_results ): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=PINDAMONHANGABA) # Call the search.list method to retrieve results matching the specified # query term. search_response = youtube.search().list( q= q, part='id,snippet', maxResults= max_results ).execute() videos = [] channels = [] playlists = [] # Add each result to the appropriate list, and then display the lists of # matching videos, channels, and playlists. for search_result in search_response.get('items', []): if search_result['id']['kind'] == 'youtube#video': return search_result['id']['videoId'] elif search_result['id']['kind'] == 'youtube#channel': channels.append('%s (%s)' % (search_result['snippet']['title'], search_result['id']['channelId'])) elif search_result['id']['kind'] == 'youtube#playlist': playlists.append('%s (%s)' % (search_result['snippet']['title'], search_result['id']['playlistId']))
e38bd5619fbe6bcf5e779d02b6c5b33d308fadfc
behrouzmadahian/python
/GANS/01-DCGAN.py
10,994
3.734375
4
import numpy as np import tensorflow as tf import os, time, itertools, imageio, pickle from matplotlib import pyplot as plt from tensorflow.examples.tutorials.mnist import input_data ''' we resize the images into (1,64,64,1). Think about convolution, getting a p*p image (1, 64, 64, 1) and after several convolutions, reshapes its input to (1,1,1,1). now transpose convolution layers of generator get the (1,1,1,100) noise and turn in into (1, 64,64,1), For the SAME padding, the output height and width are computed as: out_height = ceil(float(in_height) / float(strides[1])) out_width = ceil(float(in_width) / float(strides[2])) And For the VALID padding, the output height and width are computed as: out_height = ceil(float(in_height - filter_height) / float(strides[1])) +1 out_width = ceil(float(in_width - filter_width) / float(strides[2])) + 1 ''' # dataset normalization: range -1 -> 1: (pixelVal -0.5)/0.5 # training parameters: batchSize = 100 lr = 0.0002 training_epoch = 20 optimizer = tf.train.AdamOptimizer dropout = 0.3 def lrelu(x, th =0.2): return tf.maximum(th*x, x) #Generator: G(z): def generator(x, isTrain = True, reuse =False): # x is some sort of a noise.. with tf.variable_scope('generator', reuse =reuse): # 1st hidden layer conv1 = tf.layers.conv2d_transpose(x, 1024, [4, 4], strides=(1, 1), padding='valid') lrelu1 = lrelu(tf.layers.batch_normalization(conv1, training=isTrain), 0.2) # 2nd hidden layer: conv2 = tf.layers.conv2d_transpose(lrelu1, 512, [4, 4], strides=(2, 2), padding='same') lrelu2 = lrelu(tf.layers.batch_normalization(conv2, training=isTrain), 0.2) # 3rd hidden layer: conv3 = tf.layers.conv2d_transpose(lrelu2, 256, [4, 4], strides=(2, 2), padding='same') lrelu3 = lrelu(tf.layers.batch_normalization(conv3, training=isTrain), 0.2) # 4th conv layer: conv4 = tf.layers.conv2d_transpose(lrelu3, 128, [4, 4], strides=(2, 2), padding='same') lrelu4 = lrelu(tf.layers.batch_normalization(conv4, training=isTrain), 0.2) # output layer: conv5 = tf.layers.conv2d_transpose(lrelu4, 1, [4, 4], strides=(2, 2), padding='same') o = tf.nn.tanh(conv5) print('Generator: Shape of output of each transpose convolution layer:') print(x.get_shape(),conv1.get_shape(), conv2.get_shape(), conv3.get_shape(), conv4.get_shape(), conv5.get_shape()) return o def discriminator(x, isTrain =True, reuse =False): with tf.variable_scope('discriminator', reuse=reuse): # 1st hidden layer conv1 = tf.layers.conv2d(x, 128, [4, 4], strides=(2, 2), padding='same') lrelu1 = lrelu(conv1, 0.2) # 2nd hidden layer conv2 = tf.layers.conv2d(lrelu1, 256, [4, 4], strides=(2, 2), padding='same') lrelu2 = lrelu(tf.layers.batch_normalization(conv2, training=isTrain), 0.2) # 3rd hidden layer conv3 = tf.layers.conv2d(lrelu2, 512, [4, 4], strides=(2, 2), padding='same') lrelu3 = lrelu(tf.layers.batch_normalization(conv3, training=isTrain), 0.2) # 4th hidden layer conv4 = tf.layers.conv2d(lrelu3, 1024, [4, 4], strides=(2, 2), padding='same') lrelu4 = lrelu(tf.layers.batch_normalization(conv4, training=isTrain), 0.2) # output layer conv5 = tf.layers.conv2d(lrelu4, 1, [4, 4], strides=(1, 1), padding='valid') o = tf.nn.sigmoid(conv5) print('Discriminator: Shape of output of each convolution layers:') print(x.get_shape(),conv1.get_shape(), conv2.get_shape(), conv3.get_shape(), conv4.get_shape(), conv5.get_shape()) return o, conv5 fixed_Z = np.random.normal(0, 1, (25, 1, 1, 100)) x = tf.placeholder(tf.float32, shape = (None, 64,64,1)) z = tf.placeholder(tf.float32, shape = (None, 1, 1, 100)) isTrain = tf.placeholder(dtype=tf.bool) #networks: generator: G_z = generator(z, isTrain=isTrain) print('Shape of output of Generator:', G_z.get_shape()) # discriminator network: d_real, d_real_logits = discriminator(x, isTrain) d_fake, d_fake_logits = discriminator(G_z, isTrain, reuse =True) ## # Measures the probability error in discrete classification tasks # in which each class is independent and not mutually exclusive. d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_real_logits, labels= tf.ones([batchSize, 1, 1, 1]))) D_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_fake_logits, labels=tf.zeros([batchSize, 1, 1, 1]))) D_loss = d_loss_real + D_loss_fake G_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_fake_logits, labels=tf.ones([batchSize, 1, 1, 1]))) # trainable variables for each network T_vars = tf.trainable_variables() D_vars = [var for var in T_vars if var.name.startswith('discriminator')] G_vars = [var for var in T_vars if var.name.startswith('generator')] # optimizer for each network # BATCH NORMALIZATION HAS EXTRA parameters that wee need to trigger extra_update_ops # to do so we use control dependeincies on the optimizers as follows: with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): D_optim = tf.train.AdamOptimizer(lr, beta1=0.5).minimize(D_loss, var_list=D_vars) G_optim = tf.train.AdamOptimizer(lr, beta1=0.5).minimize(G_loss, var_list=G_vars) def show_result(sess, num_epoch, show = False, path = 'results.png', isFix = False): z_ = np.random.normal(0, 1, (25,1,1, 100)) if isFix: test_images = sess.run(G_z, feed_dict = {z: fixed_Z, isTrain :False}) else: test_images = sess.run(G_z, feed_dict = {z: z_, isTrain: False}) size_figure_grid = 5 fig, ax = plt.subplots(size_figure_grid, size_figure_grid, figsize = (5,5)) for i,j in itertools.product(range(size_figure_grid), range(size_figure_grid)): ax[i, j].get_xaxis().set_visible(False) ax[i,j].get_yaxis().set_visible(False) for k in range(size_figure_grid*size_figure_grid): i = k // size_figure_grid j = k % size_figure_grid ax[i,j].cla() #clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched. ax[i,j].imshow(np.reshape(test_images[k], (64, 64)), cmap ='gray') label = 'Epoch {0}'.format(num_epoch) fig.text(0.5, 0.04, label, ha = 'center') plt.savefig(path) if show: plt.show() else: plt.close() def show_train_hist(hist, show = False, save =False, path = 'Train_hist.png'): x = range(len(hist['D_losses'])) y1 = hist['D_losses'] y2 = hist['G_losses'] plt.plot(x, y1, label ='D_losses') plt.plot(x, y2, label ='G_losses') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend(loc=4) plt.grid(True) plt.tight_layout() if save: plt.savefig(path) if show: plt.show() else: plt.close() # load mnist: mnist = input_data.read_data_sets('MNIST_data/', one_hot=True, reshape =[]) # reshape=[]: returns (N, 28, 28, 1) print('Shape of image data before resizing:', mnist.train.images[0].shape) # loss for each network: init = tf.global_variables_initializer() # results save folder # results save folder root = 'MNIST_DCGAN_results/' model = 'MNIST_DCGAN_' if not os.path.isdir(root): os.mkdir(root) if not os.path.isdir(root + 'Fixed_results'): os.mkdir(root + 'Fixed_results') if not os.path.isdir(root+ 'Random_results'): os.mkdir(root+'Random_results') train_hist = {} train_hist['D_losses'] = [] train_hist['G_losses'] = [] train_hist['per_epoch_ptimes'] = [] train_hist['total_ptime'] = [] with tf.Session() as sess: sess.run(init) # MNIST resize and normalization train_set = tf.image.resize_images(mnist.train.images, [64, 64]).eval() train_set = (train_set - 0.5) / 0.5 np.random.seed(int(time.time())) start_time = time.time() for epoch in range(training_epoch): p = root + 'random_Results/' + model + str(epoch) + '.png' fixed_p = root + 'Fixed_results/' + model + str(epoch) + '.png' show_result(sess, (epoch + 1), show=False, path=p, isFix=False) show_result(sess, (epoch + 1), show=False, path=fixed_p, isFix=True) G_losses = [] D_losses = [] epoch_start_time = time.time() # update discriminator 3 times more often! kk = 1 for iter in range(train_set.shape[0]//batchSize): # update discriminator: x_ = train_set[iter*batchSize:(iter+1)*batchSize] print(x_.shape) z_ = np.random.normal(0, 1, (batchSize,1,1, 100)) loss_d_, _ = sess.run([D_loss, D_optim], feed_dict={x:x_, z:z_, isTrain:True}) D_losses.append(loss_d_) # update generator if epoch < 10: if kk % 2 == 0: z_ = np.random.normal(0, 1, (batchSize,1,1, 100)) loss_g_, _ = sess.run([G_loss, G_optim], feed_dict={z: z_,x:x_, isTrain:True}) G_losses.append(loss_g_) kk += 1 else: z_ = np.random.normal(0, 1, (batchSize,1,1, 100)) loss_g_, _ = sess.run([G_loss, G_optim], feed_dict={z: z_, x:x_, isTrain:True}) G_losses.append(loss_g_) epoch_end_time = time.time() per_epoch_ptime = epoch_end_time - epoch_start_time print('[%d/%d] - ptime: %.2f loss_d: %.3f, loss_g: %.3f' % ((epoch + 1), training_epoch, per_epoch_ptime, np.mean(D_losses), np.mean(G_losses))) train_hist['D_losses'].append(np.mean(D_losses)) train_hist['G_losses'].append(np.mean(G_losses)) train_hist['per_epoch_ptimes'].append(per_epoch_ptime) end_time = time.time() total_ptime = end_time - start_time train_hist['total_ptime'].append(total_ptime) print('Avg per epoch ptime: %.2f, total %d epochs ptime: %.2f' % (np.mean(train_hist['per_epoch_ptimes']), training_epoch, total_ptime)) print("Training finish!... save training results") with open(root + model + 'train_hist.pkl', 'wb') as f: pickle.dump(train_hist, f) show_train_hist(train_hist, save=True, path=root + model + 'train_hist.png') images = [] for e in range(training_epoch): img_name = root + model +'Fixed_results/'+model+ str(e + 1) + '.png' images.append(imageio.imread(img_name)) imageio.mimsave(root + model +'generation_animation.gif', images, fps=5) sess.close()
0c6ef09a8f561f197ea995a8cbf28617ee7b1292
JuanGinesRamisV/python
/practica 5/p5e2.py
383
3.96875
4
#juan gines ramis vivancos p5e2 #Escribe un programa que pida dos números y escriba qué números entre ese #par de números son pares y cuáles impares print('Escribe un número') numero1 = int(input()) print('Escribe un numero mayor que' ,numero1,) numero2 = int(input()) for i in range(numero1,numero2+1): if ((i%2) == 0): print(i, 'es par') else: print(i, 'es inpar')
db0d4790cf2dd9f4d8590906dede80c86c385032
keerthidl/Python-Assignment-re-work-
/area.py
984
4.3125
4
#Implement a program with functions, for finding the area of circle, triangle, square. import math class Area: def circle(radius): pi = 3.1415 return (pi * (radius * radius)) def triangle(height, base): return ((height * base)/2) def square(side): return (side * side) from area import Area def main(): print("\n1 - Area of Circle\n") print("2 - Area of Triangle\n") print("3 - Area of Square\n") choice = int(input("\nEnter your choice:\t")) if choice == 1: radius = float(input("\nEnter radius of the Circle:\t")) print("\nArea is : " + str(Area.circle(radius))) if choice == 2: base = float(input("\nEnter base of the Triangle:\t")) height = float(input("\nEnter height of the Triangle:\t")) print("\nArea is : " + str(Area.triangle(height, base))) if choice == 3: side = float(input("\nEnter a side of the Square:\t")) print("\nArea is : " + str(Area.square(side))) if __name__=="__main__": main()
cfea0e7dc9f6ebd266dbb33317ee6a7dfa1f20a1
cheyra90/CodeKatas
/count_sheep.py
580
4
4
''' given [True, True, True, False, True, True, True, True , True, False, True, False, True, False, False, True , True, True, True, True , False, False, True, True] count the amount of Trues ''' arr = [True, True, True, False, True, True, True, True , True, False, True, False, True, False, False, True , True, True, True, True , False, False, True, True] def count_sheep(arr): return arr.count(True) #Shorter implementation #return sum(1 for x in arr if x == True) # Longer implementation x = count_sheep(arr) print(x)
cc26f2f374bc0be8b052417421006a6c362a3018
Adarsh-Liju/Python-Course
/Fibonacci Series.py
392
4.03125
4
#Program 1 a) f1=0#assigning the values f2=1 s=0 n=int(input("Enter the number of terms"))#inputing the value if(n==1): print(f1) elif(n==2): print(f1,end=" ") print(f2,end=" ") elif(n>2): print(f1,end=" ") print(f2,end=" ") for i in range(n-2):#adding the two variables s=f1+f2 print(s,end=" ") f1=f2 f2=s
77112434b7fec16bc976f58678aa6b99c6b56275
JagadeeshMandala/python-programs
/set4/print pascal triangle.py
121
3.609375
4
n=int(input("enter the number")) for i in range(n): print(" "*(n-i),end=" ") print(" ".join(map(str,str(11**i))))
c38c9be51ae23e97ef7febf0de42e62a0a60eb73
Linkin-1995/test_code1
/day17/exercise03(生成器应用).py
754
3.96875
4
""" 练习: list01 = [3,434,35,6,7] 定义函数,将全局变量list01中所有奇数返回. 1. 使用传统思想: 创建新列表存储所有结果,再返回列表 2. 使用生成器思想: 使用yield返回奇数 """ list01 = [3, 434, 35, 6, 7] def find01(): list_result = [] for number in list01: if number % 2: list_result.append(number) return list_result # 立即 积极 result = find01() for item in result: print(item) # .................................. def find02(): for number in list01: if number % 2: yield number # 推算数据 # 延迟(惰性)操作 result = find02() for item in result: print(item)
fb88499a2a09fcef279dda837c9d1923d69f4742
kamisaberi/python-toturial
/7.extra_operators.py
169
3.921875
4
x = 5 y = 5 print(x == y) print(x is y) y = 6 print(x is y) students = ["ali", "reza", "ahmad"] print("Ali" in students) print (x is not y) print("ali" not in students)
5ffc0ae09229cbf802db7ee3940fba9989936e64
PaulLiang1/CC150
/linklist/link_list_cycle_ii_extra_space.py
621
3.765625
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of the linked list. @return: The node where the cycle begins. if there is no cycle, return null """ def detectCycle(self, head): seen = dict() ptr = head i = 0 while ptr is not None: if ptr not in seen: seen[ptr] = i else: return ptr ptr = ptr.next i += 0 return None
ac7cf28285f53c5341e77f47a8942dbbebd870a1
zhucebuliaolongchuan/my-leetcode
/DataStructureDesign/LC170_TwoSum3.py
1,258
4
4
""" 170. TwoSum 3 - Data Structure Design Design and implement a TwoSum class. It should support the following operations: add and find. add - Add the number to an internal data structure. find - Find if there exists any pair of numbers which sum is equal to the value. For example, add(1); add(3); add(5); find(4) -> true find(7) -> false """ class TwoSum(object): def __init__(self): """ initialize your data structure here """ self.num = [] def add(self, number): """ Add the number to an internal data structure. :rtype: nothing """ self.num.append(number) def find(self, value): """ Find if there exists any pair of numbers which sum is equal to the value. :type value: int :rtype: bool """ d = {} for i in range(len(self.num)): target = value - self.num[i] if target not in d: d[target] = i for i in range(len(self.num)): if self.num[i] in d and d[self.num[i]] != i: return True return False # Your TwoSum object will be instantiated and called as such: # twoSum = TwoSum() # twoSum.add(number) # twoSum.find(value)
9bb50692bd5040c9e54cc807d08fe5959086300d
MjrMatt/PythonProjects
/ABSWP_myProjects/mclip.py
551
3.796875
4
#! python3 # mclip.py - A multi-clipboard program. TEXT = {'agree': """Yes, I agree. That sounds fine to me.""", 'busy': """Sorry, can we do this later this week or next month?""", 'upsell': """Would you consider making this a monthly donation?"""} import sys, pyperclip if len(sys.argv) < 2: print('Usage: mclip.py [keyphrase] - copy phrase text') sys.exit() keyphrase = sys.argv[1] if keyphrase in TEXT: pyperclip.copy(TEXT[keyphrase]) print('Text for '+keyphrase+' copied to clipboard.') else: print('There is no text for '+ keyphrase)
cb7b8c9c38399cf5925a8b1772ff510d8ec402a2
ZvenZ2/vardata
/datafiler/find_num.py
497
3.84375
4
def find_num(setning, min, max): hours_ahead = input(str(setning)) if hours_ahead == "": return hours_ahead try: num = int(hours_ahead) if (num >= int(min)) and (num <= int(max)): num = int(num) else: print(f"Gi ett tall mellom {min} og {max}") num = find_num(setning, min, max) except: print(f"Gi ett tall mellom {min} og {max}") num = find_num(setning, min, max) finally: return num
1fa2422dd0247da931b38f6d8b4e460e0a59b216
lmssr/python
/euler/problem2/test_problem2.py
656
3.515625
4
"""Unit tests for p2.py.""" import unittest from problem2 import sum_of_even_fibo_nums class TestSumOfFibo(unittest.TestCase): def test_sum_of_even_fibo_nums(self): self.assertEqual(sum_of_even_fibo_nums(1), 0) self.assertEqual(sum_of_even_fibo_nums(2), 2) self.assertEqual(sum_of_even_fibo_nums(3), 2) self.assertEqual(sum_of_even_fibo_nums(4), 2) self.assertEqual(sum_of_even_fibo_nums(5), 2) self.assertEqual(sum_of_even_fibo_nums(6), 2) self.assertEqual(sum_of_even_fibo_nums(7), 2) self.assertEqual(sum_of_even_fibo_nums(8), 10) if __name__ == '__main__': unittest.main()
315a665ee7572887d43eaa014e8d00f5d374a685
HediaTnani/Python-for-Bioinformatics
/remove_seq.py
2,520
3.671875
4
# Removing all sequences(contigs) less than a particular length from a fasta file derived from metagenomic data # Here the length of the sequences to be removed is taken as 300 bp # Type "python remove_seq.py -i Path/of/your/fasta/file -l Cut off length of the sequences to be removed # - o Output file name with extension" for running the code # Example: python remove_seq.py -i C:\Users\dell\PycharmProject\fb_page\metagenomic.fasta -l 300 # -o metagenomic_out.fasta # Type "python remove_seq.py -h" for help/usage description # Output: Fasta file with only those sequences which are greater than or equal to the specified length(e.g. 300) # Sample input file: metagenomic.fasta # Sample output file: metagenomic_out.fasta import argparse from pathlib import Path from Bio import SeqIO parser = argparse.ArgumentParser(description="Removing all sequences(contigs) less than a particular length from a fasta file", usage= "remove_seq.py -i path/to/fasta/file -l Cut off length of the sequences to be removed -o Output filename with extension") parser.add_argument("-i", help="ENTER FULL PATH OF THE FASTA FILE") parser.add_argument("-l", help="ENTER CUT OFF LENGTH OF THE SEQUENCES TO BE REMOVED", type=int) parser.add_argument("-o", help="ENTER OUTPUT FILE NAME WITH EXTENSION") args = parser.parse_args() fasta_path = Path(args.i) cut_off_length = args.l # generating out file path using the fasta path out_filepath = fasta_path.parent/args.o # parsing all the fasta sequences as seq records in the variable 'fasta_records' fasta_records = SeqIO.parse(fasta_path,"fasta") # an empty list to store the names of all the removed sequences removed_seq = [] with open(out_filepath, "w") as fw: # looping over each fasta record stored inside 'fasta_records' for record in fasta_records: print(len(record.seq)) # checking for length of each fasta sequence if len(record.seq) >= cut_off_length: # writing the required fasta sequences to output file SeqIO.write(record, fw, format="fasta") fw.write("\n") else: removed_seq.append(record.description) print("The following sequences have been removed: ") for seq_name in removed_seq: print(seq_name) print(f"Output file successfully created at {out_filepath}") ## please contact us if you face any issues while using the code ## your personal queries are also invited
c4a95e364a723c6db4a9cd961f31e2a5d42c1dcf
maxschipper1/Exercise
/number_to3.py
101
3.71875
4
import time x = 0 while True: print(x) x += 1 if x > 3: x = 0 time.sleep(1)
1d6b9e561e9cd5302e967e47c87b4d2f0be62e0e
choidslab/IntroducingPython
/ch6/namedtuple.py
337
4.09375
4
from collections import namedtuple Bird = namedtuple('Bird', 'bill tail') duck = Bird('wide orange', 'long') print(duck) print(duck.bill) print(duck.tail) #parts 딕셔너리에서 key, value 값을 각각 추출하여 Duck클래스에 인자로 전달 parts = {'bill': 'wide orange', 'tail': 'long'} duck2 = Bird(**parts) print(duck2)
bcfd2b97f062ede5979a9739aa482df9460810b9
Sahilmallick/Python-Batch-38
/day1/operators.py
347
3.96875
4
""" + - * /=>float division // => integer division %=modulor & == ->comparioson operator ** -> power """ """ a=int(input("enter a no.:")) b=int(input("enter another no.:")) print(a/b) print(a//b) """ """ a=int(input("enter a no.:")) b=int(input("enter another no.:")) print(a+b) print(a-b) print(a*b) print(a//b) print(a/b) """ #print(85.25%3.21)
7a908763ee75b87a794c44a5b6e40985b0872734
devkant/competitive_programming
/pm4.py
292
3.75
4
a=str(input()) z=len(a) flag=0 count=0 for i in range(0,z): if a[i]=="a" or a[i]=="i" or a[i]=="0" or a[i]=="u" or a[i]=="e": flag+=1 if a[i]!="a" or a[i]!="i" or a[i]!="0" or a[i]!="u" or a[i]!="e": if flag>count: count=flag flag=0 print(count)
1e71ebff8ced9cf24e9487c44ce63d0363f1540d
Rudrarka/planning-poker-server
/backend/game_service/player.py
538
3.546875
4
class Player: """ Holds information about the Player """ def __init__(self, id, name, is_admin, vote=None, sid=None) -> None: self.id = id self.name = name self.is_admin = is_admin self.vote = vote self.sid = sid def toJSON(self): """ Helper function to return json object """ return { 'id':self.id, 'name': self.name, 'is_admin': self.is_admin, 'vote': self.vote }
06e267e0f74160e4564c975f36e01e4e93f5fca4
reversedArrow/cmput291
/lab exam2/lab_exam.py
5,367
3.6875
4
# Name: Xianhang Li # CCID: 1465904 import sys import sqlite3 import time from random import randint import datetime # connection = None cursor = None connection = sqlite3.connect('lab_exam_2.db') # Your functions go here # ====================== def add_flight(): unique = True while unique: flight_id = str(randint(11,100)) if check_unique_id(flight_id): break flight_id = str(randint(11,100)) source = input("Please enter source: ") destination = input("Please enter destination: ") departure_date = input("Please enter departure date: ") airline_name = input("Please enter airline name: ") capacity = input("Please enter capacity: ") try: c = connection.cursor() c.execute('''INSERT INTO flight VALUES (?, ?, ?, ?, ?, ?)''',(flight_id, source, destination, departure_date, airline_name, capacity,)) connection.commit() print("Add successfull") except sqlite3.Error as e: print ("Error: " + e.message) return def check_unique_id(flight_id): c = connection.cursor() c.execute('''SELECT * FROM flight WHERE flight_id = ?''', (flight_id,) ) row = c.fetchall() if not row: return True def search_flight(): destination = input("Please enter destination: ") c = connection.cursor() c.execute('''SELECT * FROM flight WHERE destination = ?''', (destination,) ) rows = c.fetchall() for row in rows: print(row[0],row[1],row[2],row[3],row[4],row[5]) return def book_flight(): c = connection.cursor() date = datetime.date.today() c.connection.cursor() c.execute('''SELECT flight_id FROM flight''') rows = c.fetchall() for row in rows: print(row) passenger_id = input("Please enter your passenger id: ") flight_id = input("Please enter the flight id you want to book: ") flight_class = input("Please select your class(ECO,BUS,FIR): ") if check_avaliable_seat(flight_id): c.execute('''INSERT OR IGNORE INTO reserve VALUES (?, ?, ?, ?)''', (passenger_id, flight_id, flight_class, date)) connection.commit() print("You have successfull booked your flight!") update_avaliable_seat(flight_id) else: return def check_avaliable_seat(flight_id): c = connection.cursor() c.connection.cursor() c.execute('''select f.current_capacity from flight f where f.flight_id = ?''',(flight_id,)) rows = c.fetchall() if rows: if rows[0][0] == 0: return False else: return True def update_avaliable_seat(flight_id): c = connection.cursor() c.connection.cursor() c.execute('''SELECT current_capacity FROM flight WHERE flight_id = ?''', (flight_id,)) row = c.fetchall() capacity = row[0][-1] capacity -= 1 c.execute('''UPDATE flight set current_capacity = ? where flight_id = ?''',(capacity,flight_id)) connection.commit() print("Book successfull") return def cancel_flight(): c = connection.cursor() c.connection.cursor() c.execute('''select fl_id from reserve''') rows = c.fetchall() for row in rows: print(row) ps_id = input("Please enter your passenger id: ") fl_id = input("which flight do you want to cancell: ") c.execute('''DELETE FROM reserve WHERE ps_id = ? and fl_id = ?''',(ps_id,fl_id)) connection.commit() update_avaliable_seat2(fl_id) return def update_avaliable_seat2(fl_id): c = connection.cursor() c.connection.cursor() c.execute('''SELECT current_capacity FROM flight WHERE flight_id = ?''', (fl_id,)) row = c.fetchall() capacity = row[0][-1] capacity += 1 c.execute('''UPDATE flight set current_capacity = ? where flight_id = ?''',(capacity,fl_id) ) connection.commit() print("Cancell successfull") return def printMenu(): date = datetime.date.today() while(True): print("\nPlease select an option:") print("1 - Add a new flight") print("2 - Search flights by destination") print("3 - Book a flight") print("4 - Cancel a flight") print("5 - Exit") selectedOption = input("you want to do option ") selectedOption = int(selectedOption) try: selectedOption = int(selectedOption) if selectedOption > 0 and selectedOption < 6: return selectedOption print ("Invalid option") except: print ("Invalid option") return def connect(path): global connection, cursor connection = sqlite3.connect(path) connection.row_factory = sqlite3.Row cursor = connection.cursor() cursor.execute(' PRAGMA forteign_keys=ON; ') initScript = open('init.sql', 'r').read() cursor.executescript(initScript) connection.commit() return def main(): global connection, cursor path = "./lab_exam_2.db" pathInitFile = "./init.sql" date = datetime.date.today() connect(path) # your call to the function that initializes the global variables # your call to the funtion that creates and populates the tables using init.sql while (True): userOption = printMenu() if userOption == 1: add_flight() if userOption == 2: search_flight() if userOption == 3: book_flight() if userOption == 4: cancel_flight() if userOption == 5: sys.exit() # Your code for handling the different options; it must be based on calling # the functions that you are required to write accoring to the lab exam specifications. return if __name__ == "__main__": main()
8249f303ff1558fca3a88b54832a382d3e449dba
TNMR-m/NLP100knock
/09.py
1,422
3.609375
4
def kansu09(str_x): str_x = str_x.split() # 文を単語ごとに分解する a = 0 from random import shuffle # シャッフルをインポート for i in str_x: str1 = str_x[a] # 現在扱っている単語をstr1とする mojisu = len(str_x[a]) # 現在扱っている単語の文字数 if mojisu > 4: # ! 単語の文字数が4文字より多い時、最初と最後以外の文字をシャッフル nakami1 = str1[1:-1] # 単語の2~最後から一つ手前の文字までを取り出す nakami2 = list(nakami1) # ↑ を一文字ずつに区切ってリストにする shuffle(nakami2) # 中身をシャッフル nakami1 = ''.join(nakami2) # 中身を文字列に戻す b = str1[:1] + nakami1 + str1[-1:] # 最初&最後の文字とくっつける str_x[a] = b # 元のリストの単語を生成した文字列で置き換える a += 1 # ループを一つ進める str_y = ' '.join(str_x) # リストを文字列に戻す return str_y str2 = kansu09("I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .") print(str2)
89fb5a097037e27734a242090654b4bda73e1dd8
Douglasdai/CQU_Holiday_Improvment
/code-improve/DSC/day_1.py
1,145
3.78125
4
print("hello world") str='Runoob' print(str) # 输出字符串 print(str[0:-1]) # 输出第一个到倒数第二个的所有字符 print(str[0]) # 输出字符串第一个字符 print(str[2:5]) # 输出从第三个开始到第五个的字符 print(str[2:]) # 输出从第三个开始后的所有字符 print(str * 2) # 输出字符串两次 print(str + '你好') # 连接字符串 print('------------------------------') print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符 print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义 import sys; x = 'runoob'; sys.stdout.write(x + '\n') x="a" y="b" # 换行输出 print( x ) print( y ) print('---------') # 不换行输出 print( x, end=" " ) print( y, end=" " ) print() from sys import argv,path # 导入特定的成员 print('================python from import===================================') print('path:',path) # 因为已经导入path成员,所以此处引用时不需要加sys.path
c6253f50e7f1a37f99bc285a3bbe5aa010bb03f8
abulyomon/exercises
/locations.py
5,205
4.0625
4
"""Coding exercise You have a list of Cartesian coordinates of locations: List[ (Double, Double) ]. You have a second list of approximate locations, of the same type. For example: List 1: [ (2.5, 2.1), (0.9, 1.8), (-2.5, 2.1), …] List 2: [ (0.0, 0.0), (0.2, -0.1), (2.4, 2.2), (1.0, 2.0), …]  The coordinates represent distance in kilometres North and East of London.  Both lists are large but can fit in the memory of a single computer. You want to match each item in the second list to the closest location in the first list. You do not know the error on the estimated location in the second list. As the lists are large, you need the search to be efficient. """ import numpy import timeit debug = False verbose = True experiment_size = 10 float_precision = 2 dimensions = 2 # Assumption: London is 40x40 KMs # Known locations list list1 = list(zip(numpy.round(numpy.random.uniform(-20, 20, experiment_size), float_precision), numpy.round(numpy.random.uniform(-20, 20, experiment_size), float_precision))) # Approximate locations list list2 = list(zip(numpy.round(numpy.random.uniform(-20, 20, experiment_size // 2), float_precision), numpy.round(numpy.random.uniform(-20, 20, experiment_size // 2), float_precision))) """ A few ways to approach the ask. First, the bullish way: for each point in list2 calculate the distance from each point in list1 and pick the smallest, in loops! Just helps get a feel of things. """ # We need a function that calculates the Euclidean distance between two 2d coordinates def dist(a, b): x1 = a[0] x2 = a[1] y1 = b[0] y2 = b[1] # Good old Pythagoras! return ((y2 - x2) ** 2 + (y1 - x1) ** 2) ** .5 def find_nearest_v1(p, known_list): # Assume it's the first point as a starting comparison reference nearest_point = known_list[0] nearest_distance = dist(p, nearest_point) # Now loop through the rest of the points for q in known_list[1:]: d = dist(p, q) if d < nearest_distance: nearest_distance = d nearest_point = q return nearest_point # Here goes the matching -- complexity is quadratic matched_list = {} def method1(): for point in list2: matched_list[point] = find_nearest_v1(point, list1) pass print('Method 1') method1() if verbose: print(matched_list) """ Let's move on to something slightly more efficient. One way could be to stray from lists and traditional functions/loops to array manipulation """ # Switch from lists to arrays def find_nearest_v2(p, known_list): knwon_array = numpy.asarray(known_list) # Distance calculation from point to each known location distance = numpy.sum(((knwon_array - p) ** 2), axis=1) # Return the point with smallest distance return known_list[distance.argmin()] # Let's calculate again for all approximate locations matched_list = {} def method2(): for point in list2: matched_list[point] = find_nearest_v2(point, list1) pass print('Method 2') method2() if verbose: print(matched_list) """ We could push this further. Instead of a function call for each individual approximate point let's try a method where we drop the remaining loop and have one that works directly on both lists (arrays) """ def find_nearest_v3(approximate_list, known_list): # Lists to arrays for quick manipulation approximate_array = numpy.asarray(approximate_list) known_array = numpy.asarray(known_list) # Duplicate the known location points array as many times as there are approximate points to search for known_array_dup = numpy.tile(known_array, len(approximate_list)) # Flatten approximate locations array for broadcasting to work approximate_array_flat = approximate_array.reshape(1, approximate_array.size) # Calculate the distance: subtracting, squaring and then summing along the tiled matrix two columns at a time distance = numpy.add.reduceat((known_array_dup - approximate_array_flat) ** 2, range(0, approximate_array.size, dimensions), axis=1) # Pick the smallest distance and return a result array as index of matched location return distance.argmin(axis=0) # Let's match! def method3(): return find_nearest_v3(list2, list1) print('Method 3') matched_list = dict(zip(list2, [list1[key] for key in method3()])) if verbose: print(matched_list) # Who did best?! """ This causes the approximation code to rerun -- If you play with experiment size it will be evident that as n->∞ method3 becomes the most efficient Tested on my laptop (pushed it): For experiment size 50000 Method 1 execution time: 0.02309236899964162 Method 2 execution time: 0.02571395000040866 Method 3 execution time: 0.018711035999785963 """ if debug: print("For experiment size {}".format(experiment_size)) print("Method 1 execution time: {}".format(timeit.timeit('method1', globals=globals()))) print("Method 2 execution time: {}".format(timeit.timeit('method2', globals=globals()))) print("Method 3 execution time: {}".format(timeit.timeit('method3', globals=globals())))
3bcf01364b6cbe7682ad109c4427eaae510a373e
nakulgoel55/skylight
/venv/thoughts_manager.py
3,884
3.78125
4
from edit_text_files import * from other import * from encryption_decryption import * from data import textfile_array, month_to_days from datetime import date import datetime from variables import * def record_thoughts(): # Prints person's name print(str(random_greeting()) + " " + str(read_file('name.txt')) + ", ") print("Let's record your thoughts") # If use has never set a password, ask for password if len(list_file_data('password.txt')) == 0: password = input("Enter your password: ") # Encrypt password and write it to a file element = encryption(password) write_file('password.txt', element) # Ask user to record thoughts only if user has never recorded thoughts if len(list_file_data('thoughts.txt')) == 0: lines = [] # When user types 'done', loop breaks print("Write 'done' in a new line when you are done recording your thoughts") # Keep asking for input unless user types 'done' while True: line = input() if line != 'done': # Encrypt input and append to list encrypted_text = encryption(line) lines.append(encrypted_text) # break out of loop when user types done else: break # Join all input text = '\n'.join(lines) # Write to files write_file('thoughts.txt', encryption(str(today_date))) write_file('regularity_thoughts.txt', str(today_date)) append_file('thoughts.txt', text) # If user has previously recorded thoughts else: # Same as above lines = [] print("Write 'done' in a new line when you are done recording your thoughts") while True: line = input() if line != 'done': line = encryption(line) lines.append(line) else: break text = '\n'.join(lines) append_file('thoughts.txt', encryption(str(today_date))) append_file('regularity_thoughts.txt', str(today_date)) append_file('thoughts.txt', text) # Print encryption text print("Here's the super secret encrypted text because it's really cool to look at. \n\n") for each in list_file_data('thoughts.txt')[-(len(lines))-1:]: print(str(each)) # Leave a line print('\n') # Thoughts manager def thoughts(): # To avoid showing thoughts menu on loop thought_counter = int(read_file('counter_thoughts.txt')) # Change counter value write_file('counter_thoughts.txt', str(int(thought_counter) + 1)) # Set person's name to variable named person person = read_file('name.txt') # If thought_counter/ 2 is an integer or thought_counter is 0, show menu if thought_counter / 2 in range(1,100) or int(thought_counter) == 0: user_input = input("Hey, " + person + ''' what would you like me to do? Record Thoughts: rt Show All Thoughts: st Main Menu: m ''') # Else is necessary to make it work else: user_input = input("What do you want to do next?") if user_input == 'rt': record_thoughts() # Show a person's thoughts elif user_input == 'st': show_thoughts() # Go back to menu, returning false breaks the while loop elif user_input == 'm': return_to_menu() # If input was not expected else: print("Try again. ") # Leave a lne print('\n') return True
4d9ba6fce3e837aced0294b7c8492ac112b379fc
isolde18/Class
/returnvalues3.py
196
3.84375
4
def number(): num1=int(input("Please enter number ")) num2=int(input("Please enter number2 ")) return num1,num2 number1 , number2=number() print(number1) print(number2)
2737b91d62344bc16ff0532269d955a92c1c46c0
BryanMorfe/ptdb
/tests/modify_db.py
1,705
4
4
from ptdb import parse def change_password(email, current_password, new_password): # This function will return True if we change the password in an entry or false if we couldn't. # Before anything, we make sure that the current_password and the new_password are different and have a value. if current_password == new_password or not current_password or not new_password: return False # Now, we parse our data my_db = parse('database') # Now we check if the email is in the database if my_db.isItemInColumn('email', email.lower()): # Now we make sure that the currentPassword matches the one for that email db_password = my_db.getColumnItem('password', my_db.getRowIndex('email', email.lower())) if db_password == current_password: # If it entered here, then we can change the password. my_db.modifyEntry('password', my_db.getRowIndex('email', email.lower()), new_password) # The above method is saying; Replace the column 'Password' with 'new_password', where the column 'Email', is 'email.lower()' and saves the file return True else: return False # Gabriella feels like her password is not secure enough, and she asked me to write this code for her. # She's my friend, so I said of course! # We first need Gaby's information gabys_email = '[email protected]' gabys_password = 'password2' gabys_new_password = 'P@s5w0rd' if change_password(gabys_email, gabys_password, gabys_new_password): print('Password has been changed successfully.') else: print('There was an error changing your password.') # Prints 'Password has been changed successfully.' and the database is saved.
9ca1cdfba64bdb0d656bc9a1722450dca83dc99f
TrellixVulnTeam/Demo_933I
/Demo/xiaoxiangkecheng/52week.py
199
3.625
4
week = 52 money = 10 money_total = 0 for i in range(week): money_total += money print(f'第{i}周,存入{money}元,总计{money_total}元') money += 10 print(money_total)
54ed4339bf7ffbba7755fc612bba620e63788af8
SimOgaard/MdhCases
/MdhCases/attgöralista.py
2,545
3.765625
4
#att göra lista import pickle import os import json längd = 60 linje = ("_"*längd) thisdict = {} menu = ["List | List todo","Add | Add todo","Check | check todo","Delete | delete todo",linje,"Save | Save todo to files", "Load | Load todo from files", linje] metod = ["list", "add", "check", "delete", "save", "load"] def meny(): print(linje) titel= "Todify" print(titel.center(längd)) print(linje) for i in menu: print(i) def funktioner(ska): if ska == "add": #Lägger till objekt try: key=input("Todo description: ") thisdict[str(key)] = "[ ]" except: print("Something went wrong") elif ska == "list": # Skriver ut alla objekt och deras värden for x, i in thisdict.items(): print(i,x) elif ska == "check": #Markerar i listan for x, i in thisdict.items(): print(i,x) check = input("What do you want to check or uncheck? ") for x in thisdict: if x == str(check): if thisdict[str(x)] == "[ ]": thisdict[str(x)] = "[✓]" break elif thisdict[str(x)] == "[✓]": thisdict[str(x)] = "[ ]" break else: print("Error", check,"was not in the list") elif ska =="delete": # Tar bort objekt i listan for x, i in thisdict.items(): print(i,x) delete = input("What do you want to delete? ") if str(delete) in thisdict: del thisdict[str(delete)] elif ska == "save": #Sparar filen som binär i datorn try: save = input("Name the file ") with open(save+".txt", 'w') as outfile: json.dump(thisdict, outfile) # save2 = save+".dat" # print(save,"was saved on you computer") # pickle.dump(thisdict, open(save2, "wb")) except: print("404 error with") elif ska == "load": #Ladar in data från datorn try: load = input("Name the file ") load2 = load+".dat" test = open(str(load2),"rb") ut = pickle.load(test) thisdict.update(ut) except: FileNotFoundError print("error") input("Press enter to continue") while True: meny() y = input("Choose method ") if y.lower() in metod: funktioner(y) os.system("cls")
731acb4236916b26e4ddbf91cf802d0d82560446
WhiteRobe/ShuaTi
/leetcode/_test_/tree/test_删除子文件夹5231.py
930
3.703125
4
import unittest from leetcode.tree import 删除子文件夹5231 as tT class MyTestCase(unittest.TestCase): def test_case_1(self): s = tT.Solution() self.assertEqual(["/a", "/c/d", "/c/f"], s.removeSubfolders(folder=["/a", "/a/b", "/c/d", "/c/d/e", "/c/f"])) def test_case_2(self): s = tT.Solution() self.assertEqual(["/a"], s.removeSubfolders(folder=["/a", "/a/b/c", "/a/b/d"])) def test_case_3(self): s = tT.Solution() self.assertEqual(["/a/b/c", "/a/b/d", "/a/b/ca"], s.removeSubfolders(folder=["/a/b/c", "/a/b/d", "/a/b/ca"])) def test_case_4(self): s = tT.Solution() self.assertEqual(["/ah/al"], s.removeSubfolders(folder=["/ah/al/am", "/ah/al"])) def test_case_5(self): s = tT.Solution() self.assertEqual(["/ah/al"], s.removeSubfolders(folder=["/ah/al", "/ah/al/am"])) if __name__ == '__main__': unittest.main()
b15acda680593474fa1ded5ce60f5875d1cb7294
daniel-reich/turbo-robot
/437h8sNsWAPCcMRSg_23.py
784
4.1875
4
""" Write a function that returns `True` if the given number `num` is a product of any two prime numbers. ### Examples product_of_primes(2059) ➞ True # 29*71=2059 product_of_primes(10) ➞ True # 2*5=10 product_of_primes(25) ➞ True # 5*5=25 product_of_primes(999) ➞ False # There are no prime numbers. ### Notes * `num` is always greater than 0. * `0` and `1` aren't prime numbers. """ def product_of_primes(num): import math primes = [] n = num while n % 2 == 0: primes.append(2) n = n / 2 for i in range(3, num, 2): while n%i==0: primes.append(i) n = n/i for idx,i in enumerate(primes): for j in range(idx): if i * primes[j] == num: return True return False
1df5d570d004803df7766618e76c4c2a60d18aef
mischelay2001/WTCSC121
/CSC121Lab01_Lab08_Misc/CSC121Lab2Problem4_PizzaSoda.py
915
4.21875
4
__author__ = 'Michele Johnson' # Program Requirements # A group of high school students are selling pizza and soda during a basketball game to raise fund for a field trip. # Pizza is $3.50 per slice and soda is $1.25 per cup. Design a program to do the following. # Ask the user to enter number of cups of soda and number of slices of pizza ordered by the customer. # The program will calculate and display the total amount due from the customer. # Get input from user Num_Cups = int(input('Enter the number of cups of drink ordered: ')) Num_Slice = int(input('Enter the number of slices of ordered: ')) # Calculations Soda_Prc = Num_Cups * 1.25 Pizza_Prc = Num_Slice * 3.50 Tot_Amt = Soda_Prc + Pizza_Prc # Output print('\nDrink total:\t\t$' + (format(Soda_Prc, ',.2f'))) print('Pizza slices total:\t$' + (format(Pizza_Prc, ',.2f'))) print('\nOrder total:\t\t$' + (format(Tot_Amt, ',.2f')))
457427a8dca45cfdf072cfe56ed9d1dcc156b1b7
yongxuUSTC/challenges
/binary-tree-traversal-post-order.py
2,433
4.0625
4
'''Binary Tree Class and its methods''' class BinaryTree: def __init__(self, data): self.data = data # root node self.left = None # left child self.right = None # right child # set data def setData(self, data): self.data = data # get data def getData(self): return self.data # get left child of a node def getLeft(self): return self.left # get right child of a node def getRight(self): return self.right # get left child of a node def setLeft(self, left): self.left = left # get right child of a node def setRight(self, right): self.right = right def insertLeft(self, newNode): if self.left == None: self.left = BinaryTree(newNode) else: temp = BinaryTree(newNode) temp.left = self.left self.left = temp def insertRight(self, newNode): if self.right == None: self.right = BinaryTree(newNode) else: temp = BinaryTree(newNode) temp.right = self.right self.right = temp # Post-order recursive traversal. The nodes' values are appended to the result list in traversal order def postorderRecursive(root, result): if not root: return postorderRecursive(root.left, result) postorderRecursive(root.right, result) result.append(root.data) # Post-order iterative traversal. The nodes' values are appended to the result list in traversal order def postorderIterative(root,result): visited = set() mystack = [] #IMPORTANT: append None , trigger for end mystack.append(None) node = root while node: if node.left and node.left not in visited: mystack.append(node) node = node.left elif node.right and node.right not in visited: mystack.append(node) node = node.right else: #left and right nodes have beeen processed result.append(node.data) visited.add(node) node = mystack.pop() ''' 1 / \ 2 3 / \ / \ 4 5 6 7 post order traversal = 4,5,2,6,7,3,1 ''' #Initialize Binary Tree root = BinaryTree(1) root.insertLeft(2) root.insertRight(3) root.getLeft().insertLeft(4) root.getLeft().insertRight(5) root.getRight().insertLeft(6) root.getRight().insertRight(7) #Traverse result = [] #postorderRecursive(root, result) #print("PostOrder traversal (recursive): %s" % (result)) #del result[::] postorderIterative(root, result) print("PostOrder traversal (Iterative): %s" % (result))
392a4b26ca0a981f128dfee66c7c976157d59b7a
nvlinh/Python
/PythonCrashCourse2nd/Chap_4_WorkingWithLists/list.py
3,277
4.375
4
# 1. Looping through an entire list foods = ['fish', 'meat', 'egg'] for food in foods: print(food) # 2. Avoid indentation error print('2. Avoid indentation error') # 2.1 Forgetting to ident magicians = ['alice', 'david', 'carolina'] for magician in magicians: # if print(magician) don't have indent in the left => IndentationError print(magician) # 2.2 Forgetting to indent additional lines print('Forgetting to indent additional lines\n') magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(f"{magician.title()}, that was a great trick!") print(f"I can't wait to see your next trick, {magician.title()}.\n") # code don't error but ony run second print one time. # 2.3 Indenting unnecessarily message = "Hi" # print(message) => IndentationError: unexpected indent # 2.4 Indenting unnecessarily after the loop print('\n 2.4 Indenting unnecessarily after the loop \n') magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(f"{magician.title()}, that was a great trick!") print(f"I can't wait to see your next trick, {magician.title()}.\n") print("Thank you everyone, that was a great magic show!") # in for loop because have indent in the left # 2.5 Forgetting the colon # for magician in magicians # 3. Making number lists print('\n 3. Making number lists \n') # 3.1 Using the range() function for value in range(1, 6): print(value) # print 1,2,3,4,5 for value in range(6): print(value) # print 0,1,2,3,4,5 # 3.2 Using range() to making a list of number print('\n 3.2 Using range() to making a list of number \n') numbers = list(range(1, 11)) print(numbers) numbers = list(range(1, 11, 2)) print(numbers) # 3.3 Simple statistics with a list of numbers print('\n 3.3 Simple statistics with a list of numbers\n') digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(max(digits)) print(min(digits)) print(sum(digits)) # 3.4 List comprehensions print('\n3.4 List comprehensions\n') squares = [value ** 2 for value in range(1, 11)] print(squares) # 4 Working with part of a list print('\n4 Working with part of a list:\n') # 4.1 Slicing a List numbers = ['One', 'Two', 'Three', 'Four', 'Five', 'Six'] print(numbers[0:3]) print(numbers[1:4]) print(numbers[:4]) print(numbers[2:]) print(numbers[-3:]) print(numbers[:-3]) # 4.2 Looping through a slice print('4.2 Looping through a slice:\n') players = ['linh', 'tam', 'tinh', 'tien'] print('Here are the first three player on my team') for player in players[:3]: print(player) # 4.3 Copying a List print(' 4.3 Copying a List:\n') my_foods = ['rice', 'fish', 'meat', 'egg'] my_wife_foods = my_foods[:] my_foods.append('coffee') my_wife_foods.append('pizza') print(f'My foods : {my_foods}') print(f'My wife foods {my_wife_foods}') # 5 Tuples print('5. Tuples\n') # An immutable list is called tuple # 5.1 Defining a Tuple print('5.1 Defining a Tuple\n') firstTuple = (1, 2, 3) print(firstTuple[0]) # firstTuple[1] =2 #TypeError: 'tuple' object does not support item assignment # defining one element secondTuple = (4,) for item in secondTuple: print(item) # Writing over a Tuple firstTuple = (4, 5, 6, 7) # 6. Styling your code # A bit about PEP8 : indentation, line length, blank line # https://www.python.org/dev/peps/pep-0008/
776883c023ee7d2a0fcbf7b8ce5c4f9c669e388f
daltonleshan/Just4Fun
/quicksort.py
550
3.859375
4
def partition(numbers, l, r): pivot = numbers[r] i = 0 for j in range(r): if numbers[j] <= pivot: numbers[j], numbers[i] = numbers[i], numbers[j] i += 1 numbers[i], numbers[r] = numbers[r], numbers[i] return i def quicksort(numbers, l, r): if l < r: pi = partition(numbers, l, r) quicksort(numbers, l, pi - 1) quicksort(numbers, pi + 1, r) return numbers a = [3,1,4,9,6] b = [6,9,1,3,4] print(quicksort(a, 0, len(a) - 1)) print(quicksort(b, 0, len(b) - 1))
e94f939d29ce6d949c4a425e6299b2e33870a694
AdityaMisra/find_path_in_maze
/find_path.py
1,309
3.625
4
def is_cell_in_constraints(maze, x, y, n, m): if n > x >= 0 and m > y >= 0 and maze[x][y] == 1: return True return False def find_path(maze, x, y, cells_travelled, n, m): if x == n - 1 and y == m - 1: cells_travelled.append((x, y)) return True if is_cell_in_constraints(maze, x, y, n, m): if not (x, y) in cells_travelled: cells_travelled.append((x, y)) else: return False if find_path(maze, x + 1, y, cells_travelled, n, m): return True if find_path(maze, x, y + 1, cells_travelled, n, m): return True if find_path(maze, x - 1, y, cells_travelled, n, m): return True if find_path(maze, x, y - 1, cells_travelled, n, m): return True cells_travelled.remove((x, y)) return False def find_path_in_maze(maze, n, m): cells_travelled = [] if not find_path(maze, 0, 0, cells_travelled, n, m): print("No path found!") return False for each_cell in cells_travelled: print(each_cell) if __name__ == "__main__": _maze = [[1, 1, 0, 0, 0], [0, 1, 1, 1, 1], [0, 1, 1, 0, 1], [0, 0, 0, 0, 1]] _n = 4 _m = 5 find_path_in_maze(_maze, _n, _m)
6cd500bc83b4cbc2feaa76e3e399cb5daba6bd85
nRookie/python
/effectivePython/37Item.py
5,847
3.890625
4
''' Item 37: Use Threads for Blocking I/O , Avoid for Parallelism The standard implementation of Python is called CPython. CPython runs a Python program in two steps. First, it parses and complies the source text into bytecode. Then, it runs the bytecode using a stack-based interpreter. The bytecode interpreter has state that must be maintained and coherent while the Python program executes. Python enforces coherence with a mechanism called the global interpreter lock (GIL). Essentially, the GIL is a mutual-exclusion lock(mutex) that prevents CPython from being affected by preemptive multithreading,where one thread takes control of a program by interrupting another thread. thread. Such an interruption could corrupt the interpreter state if it comes at an unexpected time. The GIL prevents these interruptions and ensures that every bytecode instruction works correctly with the CPython implementation and its C-extension modules. The GIL has an important negative side effect. With programs written in languages like C++ or Java, having multiple threads of execution means your program could utilize multiple CPU cores at the same time. Although Python supports multiple threads of execution, the GIL causes only one of them to make forward progress at a time. This means that when you reach for threads to do parallel computation and speed up your Python programs, you will be sorely disappointed. For example, say you want to do something computationally intensive with Python. I'll use a naive number factorization algorithm as a proxy. ''' from time import time def factorize(number): for i in range(1, number + 1): if number % i == 0: yield i ''' Factoring a set of numbers in serial takes quite a long time''' numbers = [42139079, 1214759, 1516637, 1852285] start = time() for number in numbers: list(factorize(number)) end = time() print('Took %.3f seconds ' % (end - start)) ''' Using multiple threads to do this computation would make sense in other languages because you could take advantage of all of the CPU cores of your computer. Let me try that in Python. Here, I define a Python thread for doing the same computation as before: ''' from threading import Thread class FactorizeThread(Thread): def __init__(self, number): super().__init__() self.number = number def run(self): self.factors = list(factorize(self.number)) ''' Then, I start a thread for factorizing each number in parallel. ''' start1 = time() threads = [] for number in numbers: thread = FactorizeThread(number) thread.start() threads.append(thread) for thread in threads: thread.join() end1 = time() print('Took %.3f seconds ' % (end1 - start1)) ''' What's surprising is that this takes even longer than running factorize in serial. With one thread per number, you may expect less than a 4x speedup in other languages due to the overhead of creating threads and coordinating with them. You may expect only a 2X speedup on the dual-core machine I used to run this code. But you would never expect the performance of these threads to be worse when you have multiple CPUs to utilize. This demonstrates the effect of the GIL on programs running in the standard CPython interpreter. There are ways to get CPython to utilize multiple cores, but it doesn't work with the standard Thread class (see Item 41:"Consider concurrent.futures for True Parallelism) and it can require substantial effort. Knowing these limitations you may wonder, why does Python support threads at all ? There are two good reasons. First, multiple threads make it easy for your program to seem like it's doing multiple things at the same time. Managing the juggling act of simultaneous tasks is difficult to implement yourself(see Item 40: Consider coroutines to run many functions concurrently for an example). With threads, you can leave it to Python to run your functions seemingly in parallel. This works because CPython ensures a level of fairness between Python threads of execution, even though only one of them makes forward progress at a time due to the GIL. The second reason Python supports threads is to deal with blocking I/O, which happens when Python does certain types of system calls. System calls are how your Python program asks your computer's operating system to interact with the external environment on your behalf. Blocking I/O includes things like reading and writing files, interacting with networks, communicating with devices like displays, etc.Threads help you handle blocking I/O by insulating your program from the time it takes for the operating system to respond to your request. For example, say you want to send a signal to a remote-controlled helicopter through a serial port. I'll use a slow system call (select) as a proxy for this activity. This function asks the operating system to block for 0.1 second and then return control to my program, similar to what would happen when using a synchronous serial port. ''' import select def slow_systemcall(): select.select([], [], [], 0.1) ''' running this system call in serial requires a linearly increasing amount of time ''' start = time() for _ in range(5): slow_systemcall() end = time() print('Took %.3f seconds ' % (end - start)) ''' Python threads can't run bytecode in parallel on multiple CPU cores because of the global interpreter lock(GIL). - Python threads are still useful despite the GIL because they provide an easy way to do multiple thigns at seemingly the same time. - Use Python threads to make multiple system calls in parallel. This allows you to do blocking I/O at the same time as computation.
4ef41ed184a271b3e355a90fdfd42b71dd461b02
abiewardani/robotorial_scrapping
/asset.py
964
3.5625
4
from utils import cleansingValue def assetCalculation(data, historyYear, quartal, index): assetNow = 0 assetLastQuartal = 0 assetNowRaw = 0 assetLastQuartalRaw = 0 for i, row in enumerate(data[index]): if quartal > 3: if i == 1: assetNowRaw = row assetNow = cleansingValue(row) else: if i == 2: assetNowRaw = row assetNow = cleansingValue(row) if i == 3: assetLastQuartalRaw = row assetLastQuartal = cleansingValue(row) marginAsset = ((assetNow - assetLastQuartal)/assetNow) * 100 if assetNow > assetLastQuartal: print('Total asset sd kuartal ' + str(quartal) + ' tahun ini adalah '+assetNowRaw+'. Terjadi peningkatan asset sebesar ' + str(round(marginAsset, 2))+' persen daripada kuartal ' + str(quartal) + ' tahun kemarin sebesar ' + assetLastQuartalRaw)
cad0ab9170353bd352f477ae39e4f3ec9e5ea157
gwiily/Python-Crash-Course-Practice
/chapter10/10-10.py
243
3.734375
4
filename = 'alice.txt' try: with open(filename) as f: contents = f.read() except FileNotFoundError: print("Can't find " + filename) else: times = contents.lower().count('the') print("Word 'the' has been found " + str(times) + " times.")
4fa0acd0d82c856015bad85d65dc685c3d6e8d8b
apophis981/programming_solutions
/lists/lists.py
1,967
4.21875
4
#!/usr/bin/python listint = [1,4,3,5,6,7,8,2] listchar = ['c','a','r','a','t','h'] # Index # c print(listchar[0]) # Negative indexing # h print(listchar[-1]) #prints t print(listchar[-2]) # Slices # 3rd to 5th element ['r', 'a', 't'] print(listchar[2:5]) # beginning to 3rd last character ['c', 'a', 'r'] print(listchar[:-3]) # 3rd from beginning to end print(listchar[3:] # Chaning arrays # change single element listchar[0] = 'f' # change slice listchar[0:2] = ['f', 'a'] # Append adds single item to the end of the list listint.append(3) # Extend adds list to end of list listint.extend([1,2,3]) # Insert into list, now listint[1] is 4 listint[1:1] = 4 # prepend list a = [1,2,3] b = [4,5,6] a[:0] = b a # output [4, 5, 6, 1, 2, 3] # You can 'insert' another list at any position, just address the empty slice at that location: a = [1,2,3] b = [4,5,6] a[1:1] = b a # output [1, 4, 5, 6, 2, 3] # Removing elements list.remove() removes one matching element from the list a.remove(2) print(a) # finding index of an element, list.index() returns the smallest index matching print(a.index(3)) # Concatenating lists #https://www.programiz.com/python-programming/list odd = [1, 3, 5] # Output: [1, 3, 5, 9, 7, 5] print(odd + [9, 7, 5]) # * operator repeats a list a given number of times #Output: ["re", "re", "re"] print(["re"] * 3) # Count recurrences of an item test = [1, 2, 1, 3, 1] print(test.count(1)) # Remove and return item at index with pop item = test.pop(3) print(item) print(test) # Map def calculateSquare(n): return n*n numbers = (1, 2, 3, 4) result = map(calculateSquare, numbers) print(result) # converting map object to set numbersSquare = set(result) print(numbersSquare) # Sort, sorted test.sort() # Or test = sorted(test) print(test) # Max print(max(test)) # Min print(min(test)) # Max and min can be passed multiple variables or an iterable print(max(test[1], test[2]) # Sum of all itmss in list print(sum(test))
d76534596519a60d3c9f402635149485c1dfdbdc
King-liangbaikai/python-turtle
/捂脸哭表情包.py
3,669
4.03125
4
import turtle # 画指定的任意圆弧 def arc(sa, ea, x, y, r): # start angle,end angle,circle center,radius turtle.penup() turtle.goto(x, y) turtle.setheading(0) turtle.left(sa) turtle.fd(r) turtle.pendown() turtle.left(90) turtle.circle(r, (ea - sa)) return turtle.position() turtle.hideturtle() # 画脸 turtle.speed(5) turtle.setup(900, 600, 200, 200) turtle.pensize(5) turtle.right(90) turtle.penup() turtle.fd(100) turtle.left(90) turtle.pendown() turtle.begin_fill() turtle.pencolor("#B26A0F") # head side color turtle.circle(150) turtle.fillcolor("#F9E549") # face color turtle.end_fill() # 画嘴 turtle.penup() turtle.goto(77, 20) turtle.pencolor("#744702") turtle.goto(0, 50) turtle.right(30) turtle.fd(110) turtle.right(90) turtle.pendown() turtle.begin_fill() turtle.fillcolor("#925902") # mouth color turtle.circle(-97, 160) turtle.goto(92, -3) turtle.end_fill() turtle.penup() turtle.goto(77, -25) # 画牙齿 turtle.pencolor("white") turtle.begin_fill() turtle.fillcolor("white") turtle.goto(77, -24) turtle.goto(-81, 29) turtle.goto(-70, 43) turtle.goto(77, -8) turtle.end_fill() turtle.penup() turtle.goto(0, -100) turtle.setheading(0) turtle.pendown() # 画左边眼泪 turtle.left(90) turtle.penup() turtle.fd(150) turtle.right(60) turtle.fd(-150) turtle.pendown() turtle.left(20) turtle.pencolor("#155F84") # tear side color turtle.fd(150) turtle.right(180) position1 = turtle.position() turtle.begin_fill() turtle.fillcolor("#7EB0C8") # tear color turtle.fd(150) turtle.right(20) turtle.left(270) turtle.circle(-150, 18) turtle.right(52) turtle.fd(110) position2 = turtle.position() turtle.goto(-33, 90) turtle.end_fill() # 画右边眼泪 turtle.penup() turtle.goto(0, 0) turtle.setheading(0) turtle.left(90) turtle.fd(50) turtle.right(150) turtle.fd(150) turtle.left(150) turtle.fd(100) turtle.pendown() turtle.begin_fill() turtle.fd(-100) turtle.fillcolor("#7EB0C8") # tear color turtle.right(60) turtle.circle(150, 15) turtle.left(45) turtle.fd(66) turtle.goto(77, 20) turtle.end_fill() # 画眼睛 turtle.penup() turtle.pencolor("#6C4E00") # eye color turtle.goto(-65, 75) turtle.setheading(0) turtle.left(27) turtle.fd(38) turtle.pendown() turtle.begin_fill() turtle.fillcolor("#6C4E00") # eye color turtle.left(90) turtle.circle(38, 86) turtle.goto(position2[0], position2[1]) turtle.goto(position1[0], position1[1]) turtle.end_fill() # 画手 turtle.pencolor("#D57E18") # hand side color turtle.begin_fill() turtle.fillcolor("#EFBD3D") # hand color # 第一个手指 arc(-110, 10, 110, -40, 30) turtle.circle(300, 35) turtle.circle(13, 120) turtle.setheading(-50) turtle.fd(20) turtle.setheading(130) # 第二个手指 turtle.circle(200, 15) turtle.circle(12, 180) turtle.fd(40) turtle.setheading(137) # 第三个手指 turtle.circle(200, 16) turtle.circle(12, 160) turtle.setheading(-35) turtle.fd(45) turtle.setheading(140) # 第四个手指 turtle.circle(200, 13) turtle.circle(11, 160) turtle.setheading(-35) turtle.fd(40) turtle.setheading(145) # 第五个手指 turtle.circle(200, 9) turtle.circle(10, 180) turtle.setheading(-31) turtle.fd(50) # 画最后手腕的部分 turtle.setheading(-45) turtle.pensize(7) turtle.right(5) turtle.circle(180, 35) turtle.end_fill() turtle.begin_fill() turtle.setheading(-77) turtle.pensize(5) turtle.fd(50) turtle.left(-270) turtle.fd(7) turtle.pencolor("#EFBD3D") turtle.circle(30, 180) turtle.end_fill() # 测试 # res=arc(70,220,90,50,300) # print(res[0],res[1]) turtle.done()
ff72998a7fc32c14441a108d6b6d50abc2006f0d
ivanji/csps
/fibonacci/fibMemo.py
254
3.71875
4
from typing import Dict memo: Dict[int, int] = {0: 0, 1:1} # Base case def fib(n: int) -> int: if n not in memo: memo[n] = fib(n - 1) + fib(n-2) #memoization return memo[n] if __name__ == "__main__": print(fib(5)) print(fib(70))
5f33886568adc815303ab40d42b7cd1f666edde2
landonsanders/python-dive
/linked-list.py
509
3.703125
4
class Node(): def __init__(self, cargo=0, nextNode=None): self.cargo = cargo self.nextNode = nextNode def __str__(self): return str(self.cargo) node0 = Node(0) node1 = Node(1) node2 = Node(2) node0.nextNode = node1 node1.nextNode = node2 node = node0 while node: print node node = node.nextNode def print_b(items): if items == None: return head = items tail = items.nextNode print_b(tail) print head print_b(node0)
fc17fee3406098eb1e1de341ee47b489cb5e0ba9
grovesr/foo_bar
/foo_bar/carrotland.py
23,766
4.03125
4
''' Created on Jan 30, 2016 @author: grovesr google foo.bar challenge 4.1 Carrotland ========== The rabbits are free at last, free from that horrible zombie science experiment. They need a happy, safe home, where they can recover. You have a dream, a dream of carrots, lots of carrots, planted in neat rows and columns! But first, you need some land. And the only person who's selling land is Farmer Frida. Unfortunately, not only does she have only one plot of land, she also doesn't know how big it is - only that it is a triangle. However, she can tell you the location of the three vertices, which lie on the 2-D plane and have integer coordinates. Of course, you want to plant as many carrots as you can. But you also want to follow these guidelines: The carrots may only be planted at points with integer coordinates on the 2-D plane. They must lie within the plot of land and not on the boundaries. For example, if the vertices were (-1,-1), (1,0) and (0,1), then you can plant only one carrot at (0,0). Write a function answer(vertices), which, when given a list of three vertices, returns the maximum number of carrots you can plant. The vertices list will contain exactly three elements, and each element will be a list of two integers representing the x and y coordinates of a vertex. All coordinates will have absolute value no greater than 1000000000. The three vertices will not be collinear. Languages ========= To provide a Python solution, edit solution.py To provide a Java solution, edit solution.java Test cases ========== Inputs: (int) vertices = [[2, 3], [6, 9], [10, 160]] Output: (int) 289 Inputs: (int) vertices = [[91207, 89566], [-88690, -83026], [67100, 47194]] Output: (int) 1730960165 ''' from math import sqrt from fractions import Fraction from decimal import Decimal class IntegerPoint(): ''' IntegerPoint object ''' def __init__(self, x = None, y = None): if x is not None and y is not None: self._x = int(x) self._y = int(y) else: self._x = 0 self._y = 0 def __repr__(self): return '(%d, %d)' % (self._x, self._y) def __sub__(self, other): return IntegerPoint(self._x - other._x, self._y - other._y) def __add__(self, other): return IntegerPoint(self._x + other._x, self._y + other._y) def __eq__(self, other): if not isinstance(other, self.__class__): return False return self._x == other._x and self._y == other._y def __ne__(self, other): if not isinstance(other, self.__class__): return False return self._x != other._x or self._y != other._y def touches_edge(self, edge): intercept = edge._p1._y - edge.slope() * edge._p1._x return edge.slope() * self._x + intercept == self._y def relation_to_line(self, line): ''' check to see if this point is greater than the line. equation of line y - mx - b = result if result == 0 then point is on this line when stretched to infinity. Sign of result indicates location of point on one side or other of this line. ''' b = line._p1._y - line.slope() * line._p1._x m = line.slope() if m == float('inf'): result = self._x - line._p1._x else: result = self._y - m * self._x - b if result == 0: return 0 return result / abs(result) def tuple(self): return (self._x, self._y) class IntegerSegment(): ''' IntegerSegment object consists of two IntegerPoints ''' def __init__(self, p1 = None, p2 = None): if (isinstance(p1, tuple) and isinstance(p2,tuple) and len(p1) == 2 and len(p2) == 2): self._p1 = IntegerPoint(p1[0], p1[1]) self._p2 = IntegerPoint(p2[0], p2[1]) elif p1 is not None and p2 is not None: self._p1 = p1 self._p2 = p2 else: self._p1 = IntegerPoint(0, 0) self._p2 = IntegerPoint(0, 0) def __repr__(self): return '%s->%s' % (str(self._p1), str(self._p2)) def slope(self): delta = self._p2 - self._p1 try: m = Fraction(delta._y, delta._x) except ZeroDivisionError: m = float('inf') return m def length(self): delta = self._p2 - self._p1 return sqrt(delta._y**2 + delta._x**2) def ortho(self): return self.slope() == 0 or self.slope() == float('inf') def vertices(self): return (self._p1, self._p2) def other_end_point(self, point): return [endPoint for endPoint in self.vertices() if endPoint != point][0] def contains_point(self, point): return self._p1 == point or self._p2 == point def intersects_triangle(self, triangle): ''' This edge crosses the interior space of a triangle. If all triangle vertices have same relationship to self and are non-zero, the line doesn't cross the triangle. From http://stackoverflow.com/a/3590421 If the triangle has a vertex interior to the circumscribing rectangle, then the line stretched to infinity may cross the triangle, but the line segment may still not enter the triangle interior. Check to see if the line SEGMENT has points on either side of the triangle long edge. If it does, the line crosses the triangle. ''' signs = set() interiorPoint = triangle.pt_inside_circumscribing_rectangle() if interiorPoint: # Checking for cases where the triangle contains a # vertex inside the circumscribing rectangle. # Check if this line segment has points on both sides of the # triangle long edge. If it dies, this line crosses the triangle longEdge = triangle.long_edge() signs = set() for point in self.vertices(): signs.add(point.relation_to_line(longEdge)) else: for point in triangle.vertices(): signs.add(point.relation_to_line(self)) return -1 in signs and 1 in signs def tuple(self): return(self._p1.tuple(), self._p2.tuple()) def like(self, other): commonPoints = [point for point in self.vertices() if point in other.vertices()] return len(commonPoints) == 2 def __eq__(self, other): if not isinstance(other, self.__class__): return False return self.vertices() == other.vertices() def __ne__(self, other): if not isinstance(other, self.__class__): return False return self.vertices() != other.vertices() def containing_pt_ct(self): ''' containing_pt_ct returns number of points on a 2-D, integer cartesian plane that touch the IntegerSegment lying in that plane. ''' if self.length() == 0: pointCount = 1 if self.slope() == float('inf'): pointCount = abs((self._p2 - self._p1)._y) + 1 elif self.slope() == 0: pointCount = abs((self._p2 - self._p1)._x) + 1 else: delta = self._p2 - self._p1 pointCount = abs(delta._x / self.slope().denominator) + 1 return pointCount class IntegerTriangleError(): pass class IntegerTriangle(object): ''' IntegerTriangle object consists of three IntegerPoints ''' def __init__(self, p1 = None, p2 = None, p3 = None): if (isinstance(p1, tuple) and isinstance(p2,tuple) and isinstance(p3,tuple) and len(p1) == 2 and len(p2) == 2 and len(p3) == 2): self._p1 = IntegerPoint(p1[0], p1[1]) self._p2 = IntegerPoint(p2[0], p2[1]) self._p3 = IntegerPoint(p3[0], p3[1]) elif p1 is not None and p2 is not None and p3 is not None: self._p1 = p1 self._p2 = p2 self._p3 = p3 else: self._p1 = IntegerPoint(0, 0) self._p2 = IntegerPoint(0, 0) self._p3 = IntegerPoint(0, 0) self._a = IntegerSegment(self._p1, self._p2) self._b = IntegerSegment(self._p2, self._p3) self._c = IntegerSegment(self._p3, self._p1) def __repr__(self): return '%s->%s->%s' % (str(self._p1), str(self._p2), str(self._p3)) def vertices(self): return (self._p1, self._p2, self._p3) def sides(self): return (self._a, self._b, self._c) def vertex_tuple(self): return (self._p1.tuple(), self._p2.tuple(), self._p3.tuple()) def side_tuple(self): return (self._a.tuple(), self._b.tuple(), self._c.tuple()) def is_ortho(self): return self._a.ortho() or self._b.ortho() or self._c.ortho() def is_ortho_right(self): return ((self._a.ortho() and self._b.ortho()) or (self._a.ortho() and self._c.ortho()) or (self._b.ortho() and self._c.ortho())) def minx(self): return min([p._x for p in self.vertices()]) def miny(self): return min([p._y for p in self.vertices()]) def maxx(self): return max([p._x for p in self.vertices()]) def maxy(self): return max([p._y for p in self.vertices()]) def like(self, other): return len([point for point in self.vertices() if point in other.vertices()]) == 3 def long_edge(self): longEdge = self.sides()[0] for edge in self.sides(): if edge.length() > longEdge.length(): longEdge = edge return longEdge def interior_edges_tuple(self): ''' return edge tuples not coincident with an edge of the circumscribed rectangle ''' interiorEdges = set() circumscribedRectangle = self.circumscribed_rectangle() for triSide in self.sides(): found = False for rectSide in circumscribedRectangle.sides(): if triSide.like(rectSide): found = True break if not found: interiorEdges.add(triSide.tuple()) return list(interiorEdges) def interior_edges(self): return [IntegerSegment(edgeTuple[0], edgeTuple[1]) for edgeTuple in self.interior_edges_tuple()] def pt_inside_circumscribing_rectangle(self): pts = [point for point in self.vertices() if point._x > self.minx() and point._x < self.maxx() and point._y > self.miny() and point._y < self.maxy()] if pts: return pts[0] return None def circumscribed_rectangle(self): return IntegerOrthoRectangle(IntegerPoint(self.minx(), self.miny()), IntegerPoint(self.maxx(), self.maxy())) def squaring_triangles(self): squaringTriangles = [] interiorEdges = self.interior_edges() interiorPoint = self.pt_inside_circumscribing_rectangle() # return the surrounding triangles to rectangularize the triangle for interiorEdge in interiorEdges: touchingPoints = self.circumscribed_rectangle().points_touching(interiorEdge) if len(touchingPoints) == 1: # try to create an ortho right triangle from the end of the interior # edge that doesn't touch a vertex of the circumscribing rectangle. # Make sure you create the triangle that doesn't cross self otherEndPoint = touchingPoints[0] firstEndPoint =interiorEdge.other_end_point(touchingPoints[0]) elif len(touchingPoints) == 1: # this is the special case of the interior edge running # between diagonal corners of the circumscribing rectangle otherEndPoint = touchingPoints[1] firstEndPoint = touchingPoints[0] else: # no touching points firstEndPoint = interiorEdge._p1 otherEndPoint = interiorEdge._p2 popt = IntegerPoint(firstEndPoint._x, otherEndPoint._y) newEdge = IntegerSegment(firstEndPoint, popt) pointValid = not newEdge.intersects_triangle(self) if interiorPoint and len(touchingPoints) == 2: # check to see if popt lies on the opposite side of the # diagonal interior edge as the interiorPoint. If it doesn't # don't create this triangle, otherwise it will overlap self pointValid = (popt.relation_to_line(interiorEdge) != interiorPoint.relation_to_line(interiorEdge)) newTriangle = IntegerOrthoRightTriangle(otherEndPoint, firstEndPoint, popt) if not pointValid or newTriangle.like(self): # try the other direction popt = IntegerPoint(otherEndPoint._x, firstEndPoint._y) newTriangle = IntegerOrthoRightTriangle(otherEndPoint, firstEndPoint, popt) squaringTriangles.append(newTriangle) return squaringTriangles def squaring_shapes(self): ''' Set of shapes that are added to the exterior of the triangle to fill up the circumscribed rectangle. Will be three right triangles and possibly a rectangle. ''' squaringShapes = self.squaring_triangles() interiorPoint = self.pt_inside_circumscribing_rectangle() if interiorPoint: # we have to include a surrounding rectangle to the three triangles # to rectangularize the triangle longEdge = self.long_edge() nonTouchingPoints = self.circumscribed_rectangle().points_not_touching(longEdge) for point in nonTouchingPoints: if (point.relation_to_line(longEdge) == interiorPoint.relation_to_line(longEdge)): # create the squaring rectangle if the point is on the # same side of the diagonal edge as interiorPoint squaringShapes.append(IntegerOrthoRectangle(point, interiorPoint)) break return squaringShapes def interior_pt_ct(self): ''' interior_pt_ct returns number of points on a 2-D, integer cartesian plane that are interior to the IntegerTriangle lying in that plane. We find the containing circumscribing rectangle, then locate the orthogonal right triangles and possibly an orthogonal rectangle needed to rectangularize the triangle. We can calculate the containing points for rectangles and right triangles easily. Once we have calculated those, we just subtract them from the points inside the circumscribing rectangle to get the points completely interior to this triangle. ''' exteriorPoints=0 squaringShapes = self.squaring_shapes() multiCountPoints = 0 edgePoints = 0 uniquePoints = [] uniqueSides = [] for shape in squaringShapes: for point in shape.vertices(): if point in uniquePoints: multiCountPoints += 1 else: uniquePoints.append(point) for side in shape.sides(): if len([sd for sd in uniqueSides if sd.like(side)]) > 0: multiCountPoints += (side.containing_pt_ct() - 2) else: uniqueSides.append(side) for shape in squaringShapes: exteriorPoints += shape.containing_pt_ct() exteriorPoints -= multiCountPoints circumscribedRectangle = self.circumscribed_rectangle() for triSide in self.sides(): for rectSide in circumscribedRectangle.sides(): if triSide.like(rectSide): edgePoints += (triSide.containing_pt_ct() - 2) if self.is_ortho_right(): # a common edge point needs to be removed edgePoints += 1 return int(self.circumscribed_rectangle().containing_pt_ct() - exteriorPoints - edgePoints) class IntegerOrthoRightTriangleInvalidError(IntegerTriangleError): pass class IntegerOrthoRightTriangle(IntegerTriangle): ''' IntegerOrthoRightTriangle object consists of three IntegerPoints representing the corners of a right triangle that has two sides parallel to the horizontal and vertical axes in a 2D cartesian plane. We can easily calculate the containing point count. ''' def __init__(self, *args, **kwargs): super(IntegerOrthoRightTriangle,self).__init__(*args, **kwargs) if not self.is_ortho_right(): raise IntegerOrthoRightTriangleInvalidError def containing_pt_ct(self): ''' containing_pt_ct returns number of points on a 2-D, integer cartesian plane that are covered by the IntegerOrthoTriangle lying in that plane. ''' hyp = self.interior_edges()[0] return (Fraction(self.circumscribed_rectangle().containing_pt_ct(), 2) + Fraction(hyp.containing_pt_ct(), 2)) class IntegerOrthoRectangle(): ''' IntegerOrthoRectangle object consists of two IntegerPoints representing the diagonally opposed corners of a rectangle that has sides parallel to the horizontal and vertical axes in a 2D cartesian plane We can easily calculate the containing point count. ''' def __init__(self, p1 = None, p3 = None): if p1 == None: self._p1 = IntegerPoint(0, 0) if p3 == None: self._p3 = IntegerPoint(0, 0) if (isinstance(p1, tuple) and isinstance(p3,tuple) and len(p1) == 2 and len(p3) == 2): self._p1 = IntegerPoint(p1[0], p1[1]) self._p3 = IntegerPoint(p3[0], p3[1]) elif p1 is not None and p3 is not None: self._p1 = p1 self._p3 = p3 if self._p1 is not None and self._p3 is not None: self._a = IntegerSegment(self._p1, IntegerPoint(self._p3._x, self._p1._y)) self._b = IntegerSegment(IntegerPoint(self._p3._x, self._p1._y), self._p3) self._c = IntegerSegment(self._p3, IntegerPoint(self._p1._x, self._p3._y)) self._d = IntegerSegment(IntegerPoint(self._p1._x, self._p3._y), self._p1) def __repr__(self): return '%s->%s->%s->%s' % self.vertices() def vertices(self): p2 = IntegerPoint(self._p3._x, self._p1._y) p4 = IntegerPoint(self._p1._x, self._p3._y) return (self._p1, p2, self._p3, p4) def sides(self): return (self._a, self._b, self._c, self._d) def vertex_tuple(self): return (self._p1.tuple(), self._p3.tuple()) def like(self, other): return len([point for point in self.vertices() if point in other.vertices()]) == 4 def points_touching(self, edge): return [point for point in self.vertices() if edge.contains_point(point)] def points_not_touching(self, edge): return [point for point in self.vertices() if not edge.contains_point(point)] def containing_pt_ct(self): ''' containing_pt_ct returns number of points on a 2-D, integer cartesian plane that are covered by the IntegerOrthoRectangle lying in that plane. ''' return self._a.containing_pt_ct() * self._b.containing_pt_ct() def answer(vertices): ''' Calculate the number of integer grid points contained completely inside of an arbitrary triangle with vertices placed on integer grid points. I know! I know! Pick's theorem! I got started down the road of completing the circumscribing rectangle by adding orthogonal right triangles and rectangles from which we can easily calculate containing point counts. Then all we have to do is subtract these "squaring" shape's containing point counts from the circumscribing rectangle containing point count to get the interior point count of the triangle. Sure Pick's theorem is MUCH shorter and more efficient, but I like my solution as well! once I finally figured out that my approach was getting much too involved, I started Googling and found Pick's theorem on Wikipedia. I went ahead and finished the "squaring" solution and then implemented Pick's theorem too. It made dealing with the large number float math concerns with Pick's theorem easy, since I had a working solution for arbitrary triangles with my "squaring" solution that I could use to compare. If your in love with Pick's theorem, just use answer_picks(vertices). I won't hold it against you :-) ''' p1=IntegerPoint(vertices[0][0], vertices[0][1]) p2=IntegerPoint(vertices[1][0], vertices[1][1]) p3=IntegerPoint(vertices[2][0], vertices[2][1]) triangle = IntegerTriangle(p1, p2, p3) return triangle.interior_pt_ct() # Pick's theorem approach starts here def slope(p0, p1): try: m = Fraction(p1[1] - p0[1], p1[0] - p0[0]) except ZeroDivisionError: m = float('inf') return m def edge_points(p0, p1): m = slope(p0, p1) if m == float('inf'): n = abs(p1[1] - p0[1]) + 1 elif m == 0: n = abs(p1[0] - p0[0]) + 1 else: n = abs((p1[0] - p0[0]) / m.denominator) + 1 return int(n) def triangle_area(p0, p1, p2): lena = Decimal(Decimal(p1[0] - p0[0]) ** 2 + Decimal(p1[1] - p0[1]) ** 2) ** Decimal(0.5) lenb = Decimal(Decimal(p2[0] - p1[0]) ** 2 + Decimal(p2[1] - p1[1]) ** 2) ** Decimal(0.5) lenc = Decimal(Decimal(p0[0] - p2[0]) ** 2 + Decimal(p0[1] - p2[1]) ** 2) ** Decimal(0.5) # 1/2 perimeter s = Decimal(0.5) * (lena + lenb + lenc) # area (from CRC standard mathematical tables 29th edition) k = Decimal(s * (s - lena) * (s - lenb) * (s - lenc)) ** Decimal(0.5) return k def answer_picks(vertices): # OK, now that we've done it wrong, let's try using Pick's theorem # https://en.wikipedia.org/wiki/Pick's_theorem # A = i + b/2 - 1 # where i is the number of interior points # b = the number of edge points # call vertices 0, 1, 2 # call edges a, b, c where: # a = 0 -> 1 # b = 1 -> 2 # c = 2 -> 0 na = edge_points(vertices[0], vertices[1]) nb = edge_points(vertices[1], vertices[2]) nc = edge_points(vertices[2], vertices[0]) b = na + nb + nc - 3 A = triangle_area(vertices[0], vertices[1], vertices[2]) i = A - b / 2 + 1 return int(round(i,1)) if __name__ == '__main__': vertices = [[2, 3], [6, 9], [10, 160]] vertices = [[0, 0], [7, 2], [2, 6]] vertices = [[0, 0], [7, 0], [7, 7]] vertices = [[0, 0], [9,2], [2, 5]] # vertices = [[0, 0], [2, 0], [2, 1]] # vertices = [[91207, 89566], [-88690, -83026], [67100, 47194]] print answer_picks(vertices) # cProfile.run('answer(vertices)')
cf324e1d42d6498a2bcd908316c8eca46a60d4ed
nikc22/text_adventure
/backpack.py
1,426
3.9375
4
class Backpack(): def __init__(self, capacity): """Creates a Backpack, setting the max capacity""" self.items = {} self.weight = 0 self.max_weight = capacity def get_inventory(self): """Prints the inventory in the backpack""" if len(self.items) == 0: print('There is nothing in your backpack') else: for ind in self.items: item = self.items[ind] print(item.get_name() + ' (' + str(item.get_weight()) + ')') print('Your backpack weighs ' + str(self.weight)) print('The capcity of your backpack is ' + str(self.max_weight)) def add_item(self, item): """Adds an Item to the backpack, if there is capacity""" if self.get_weight() + item.get_weight() <= self.max_weight: self.items[item.get_name()] = item self.weight += item.get_weight() return True else: return False def drop_item(self, item): """Removes an item fromt the Backapack""" ind = self.items[item] del self.items[item] self.weight -= ind.get_weight() return ind def get_weight(self): """Returns the weight of items in the backpack""" return self.weight def get_items(self): """Returns the items, allowing for searching int he list of items""" return self.items
8a7ad5ceaa1413a23a256a7af6ac6e821da324bc
wnyoung/Sensor
/gpio/gpio_led/sample2.py
564
3.78125
4
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) led_pin1 = 14 led_pin2 = 15 GPIO.setup(led_pin1, GPIO.OUT) GPIO.setup(led_pin2, GPIO.OUT) def Blink(numTimes,speed): for i in range(0,numTimes): print ("Iteration " + str(i+1)) GPIO.output(14,True) time.sleep(speed) GPIO.output(14,False) time.sleep(speed) print("Done") iterations = input("Enter total number of times to blink: ") speed = input("Enter lingth of each blink(seconds): ") Blink(int(iterations),float(speed))
4645583949d89b2ab6ace0294d1de277d90e9120
nullconfig/wsgi-calculator
/calculator.py
5,559
4.15625
4
""" For your homework this week, you'll be creating a wsgi application of your own. You'll create an online calculator that can perform several operations. You'll need to support: * Addition * Subtractions * Multiplication * Division Your users should be able to send appropriate requests and get back proper responses. For example, if I open a browser to your wsgi application at `http://localhost:8080/multiple/3/5' then the response body in my browser should be `15`. Consider the following URL/Response body pairs as tests: ``` http://localhost:8080/multiply/3/5 => 15 http://localhost:8080/add/23/42 => 65 http://localhost:8080/subtract/23/42 => -19 http://localhost:8080/divide/22/11 => 2 http://localhost:8080/ => <html>Here's how to use this page...</html> ``` To submit your homework: * Fork this repository (Session03). * Edit this file to meet the homework requirements. * Your script should be runnable using `$ python calculator.py` * When the script is running, I should be able to view your application in my browser. * I should also be able to see a home page (http://localhost:8080/) that explains how to perform calculations. * Commit and push your changes to your fork. * Submit a link to your Session03 fork repository! """ import traceback from functools import reduce def home(*args): page = ''' <h1>WSGI Calculator</h1> <head> <style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 5px; } th { text-align: left; } </style> </head> <table style="float:left"> <tr> <th>Calulator tutorial</th> </tr> <tr> <th>The calculator takes three paths. <br> One declaring the intended action and two representing the operands.<br> It can perform one of four actions depending on the path provided.<br><br> The four paths for the calculation actions are: <ul> <li>add</li> <li>subtract</li> <li>multiply</li> <li>divide</li> </ul> </th> </tr> <tr> <th>Syntax</th> <td>http://127.0.0.1:8080/path/operand/operand</td> </tr> <tr> <th>Examples</th> </tr> <tr> <th>Addition</th> <td>http://127.0.0.1:8080/add/2/2</td> </tr> <tr> <th>Subtraction</th> <td>http://127.0.0.1:8080/subtract/4/2</td> </tr> <tr> <th>Multiplication</th> <td>http://127.0.0.1:8080/multiply/3/24</td> </tr> <tr> <th>Divison</th> <td>http://127.0.0.1:8080/divide/8/4</td> </tr> </table>''' return page def add(*args): """ Returns a STRING with the sum of the arguments """ body = ['<h1>Addition Calculator</h1>'] _sum = sum(map(int, args)) body.append(f'Total equals: {_sum}') return '\n'.join(body) def subtract(*args): """ Returns a STRING with the difference of the arguments """ body = ['<h1>Subtraction Calculator</h1>'] diff = reduce(lambda x,y: x - y, map(int,args)) body.append(f'Total equals: {diff}') return '\n'.join(body) def multiply(*args): """ Returns a STRING with the product of the arguments """ body = ['<h1>Multiplication Calculator</h1>'] product = reduce(lambda x,y: x * y, map(int,args)) body.append(f'Total equals: {product}') return '\n'.join(body) def divide(*args): """ Returns a STRING with the quotient of the arguments """ body = ['<h1>Divison Calculator</h1>'] try: quotient = reduce(lambda x,y: x / y, map(int,args)) body.append(f'Total equals: {quotient}') except ZeroDivisionError: raise ZeroDivisionError return '\n'.join(body) def resolve_path(path): """ Should return two values: a callable and an iterable of arguments. """ # TODO: Provide correct values for func and args. The # examples provide the correct *syntax*, but you should # determine the actual values of func and args using the # path. funcs = { '': home, 'add': add, 'subtract': subtract, 'multiply': multiply, 'divide': divide } path = path.strip('/').split('/') func_name = path[0] args = path[1:] try: func = funcs[func_name] except KeyError: raise NameError return func, args def application(environ, start_response): # TODO: Your application code from the book database # work here as well! Remember that your application must # invoke start_response(status, headers) and also return # the body of the response in BYTE encoding. headers = [('Content-type', 'text/html')] try: path = environ.get('PATH_INFO', None) if path is None: raise NameError func, args = resolve_path(path) body = func(*args) status = "200 OK" except NameError: status = "404 Not Found" body = "<h1>Not Found</h1>" except ZeroDivisionError: status = "405 Not Allowed" body = f'<h2>Cannot Divide by zero</h2><a href="/">Return home</a>' except Exception: status = "500 Internal Server Error" body = "<h1>Internal Server Error</h1>" print(traceback.format_exc()) finally: headers.append(('Content-length', str(len(body)))) start_response(status, headers) return [body.encode('utf8')] return [body.encode('utf8')] if __name__ == '__main__': # TODO: Insert the same boilerplate wsgiref simple # server creation that you used in the book database. from wsgiref.simple_server import make_server srv = make_server('localhost', 8080, application) srv.serve_forever()
e1786a1f18640979af624aea10e07470fbbed09e
khalsakuldeep77/Competitive-programming
/valid parentheses.py
507
3.65625
4
class Solution: def isValid(self, s: str) -> bool: Dict={'[':']','{':'}','(':')'} stack=[] openn=['(','{','['] for i in s: if(i in openn): stack.append(i) elif i not in openn: if(len(stack)==0): return 0 else: close=stack.pop() if(Dict[close]!=i): return 0 if(len(stack)>0): return 0 return 1
0420e3b5d17252060553d2394fb973997c08816f
vivekjha1213/Algorithms-practice.py
/data structure using python.py/array_question/tower_hunoi.py
294
3.875
4
def TowerOfHanoi(n , start, mid, end): if n == 1: print("Move disk 1 from rod",start,"to rod",mid) return TowerOfHanoi(n-1, start, end, mid) print("Move disk",n,"from rod",start,"to rod",mid) TowerOfHanoi(n-1, end, mid, start) # Driver code n = 3 TowerOfHanoi(n, 'A', 'C', 'B')
dd8dbc43f9035fa227dce8325043fb14d7e08605
capac/python-exercises
/edx-cs50/caesar.py
937
4.09375
4
from sys import argv def rotate_char(char): if char.isalpha(): if char.islower(): return chr(ord('a') + (ord(char) - ord('a') + int(argv[1])) % 26) else: return chr(ord('A') + (ord(char) - ord('A') + int(argv[1])) % 26) return char def main(): if len(argv) == 2: string = input("plaintext: ") cipher_text = [] for char in string: cipher_text.append(rotate_char(char)) print("ciphertext: ", ''.join(cipher_text)) else: print("Only one argument!") if __name__ == "__main__": main() ''' :) encrypts "a" as "b" using 1 as key :) encrypts "barfoo" as "yxocll" using 23 as key :) encrypts "BARFOO" as "EDUIRR" using 3 as key :) encrypts "BaRFoo" as "FeVJss" using 4 as key :) encrypts "barfoo" as "onesbb" using 65 as key :) encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key :) handles lack of argv[1] '''
0406a1538909b5889a4a7f99878f83f0802ab91b
jurueta/exercism-python
/anagram/anagram.py
472
3.75
4
def find_anagrams(word, candidates): resultado = list() for letra in candidates: if(letra.lower() != word.lower()) and (len(letra) == len(word)): cant = 0 new_word = word for i in letra.lower(): if i in new_word.lower(): cant += 1 new_word = new_word.replace(i, "", 1) if cant == len(word): resultado.append(letra) return resultado
ca9ca4ca58adc46dd508af202413bdba59d1fd77
Voron07137/Portfolio_experience
/07.2017/labyr_oop.py
5,610
3.515625
4
class Labyrinth: def __init__(self, mat, begin, end): self.matrix = mat self.action(begin, end) def init_walls(self): for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): if self.matrix[i][j] == 1: self.matrix[i][j] = -1 def check_border_down(self, index): if index + 1 >= len(self.matrix): return False else: return True def check_border_right(self, index, j_index): if j_index + 1 >= len(self.matrix[index]): return False else: return True def check_border_up_left(self, index): if index - 1 < 0: return False else: return True def action(self, begin, end): self.init_walls() i = begin[0] j = begin[1] if begin[0] == end[0] and begin[1] == end[1]: print("0") else: count = 1 self.matrix[i][j] = -2 if self.check_border_down(i): if self.matrix[i + 1][j] == 0: self.matrix[i + 1][j] = count if self.check_border_right(i, j): if self.matrix[i][j + 1] == 0: self.matrix[i][j + 1] = count if self.check_border_up_left(i): if self.matrix[i - 1][j] == 0: self.matrix[i - 1][j] = count if self.check_border_up_left(j): if self.matrix[i][j - 1] == 0: self.matrix[i][j - 1] = count while self.matrix[end[0]][end[1]] == 0: for i in range(0, len(self.matrix)): for j in range(0, len(self.matrix[i])): next_count = count + 1 if self.matrix[i][j] == count: if self.check_border_down(i): if self.matrix[i + 1][j] == 0: self.matrix[i + 1][j] = next_count if self.check_border_right(i, j): if self.matrix[i][j + 1] == 0: self.matrix[i][j + 1] = next_count if self.check_border_up_left(i): if self.matrix[i - 1][j] == 0: self.matrix[i - 1][j] = next_count if self.check_border_up_left(j): if self.matrix[i][j - 1] == 0: self.matrix[i][j - 1] = next_count count += 1 self.matrix[begin[0]][begin[1]] = 0 res = [count] route_reverse = '' i = end[0] j = end[1] while count != 0: prev_count = count - 1 if self.check_border_down(i): if self.matrix[i + 1][j] == prev_count: route_reverse += 'N' i += 1 if self.check_border_right(i, j): if self.matrix[i][j + 1] == prev_count: route_reverse += 'W' j += 1 if self.check_border_up_left(i): if self.matrix[i - 1][j] == prev_count: route_reverse += 'S' i -= 1 if self.check_border_up_left(j): if self.matrix[i][j - 1] == prev_count: route_reverse += 'E' j -= 1 count -= 1 directions = list(route_reverse) route = ''.join(directions[::-1]) res.append(route) print(str(res)) matrix1 = Labyrinth([ [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0] ], [0, 0], [11, 11]) # [62, 'ESSSSSSSSSSEENNNNNNNNNEESSSSSSSSSEENNNNNNNNNEEESSWSSESSWSSESES'] matrix2 = Labyrinth([ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1], [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1], [1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1], [1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1], [1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], [1, 1], [10, 10]) # [18, 'SSSSSEESEEESEEEESS'] matrix3 = Labyrinth([ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], ], [1, 1], [12, 11]) # [21, 'EEEEEEEEESSSSSSSSSSES']
129e37095c66b73e4f0bc75cadf25ba7db39f640
tahmed5/Basics-Of-NN
/linearregression.py
2,065
3.71875
4
import numpy import time def get_coordinates(): global x_coord global y_coord x_coord = [] y_coord = [] entering_coordinates = True print('Enter Your x and y Coordinates in the format x,y') print("Type 'done' when you are finished") while entering_coordinates == True: data = input() if data == 'done': if len(x_coord) < 2 or len(y_coord) < 2: print('not enough data inputted') exit() entering_coordinates = False break data = data.split(',') if len(data) != 2: print("Invalid Format: E.G x,y --> 5,3") continue if data[0] == '' or data[1] == '': print('Incomplete coorindates') continue try: data[0] = int(data[0]) data[1] = int(data[1]) except: print('String Detected') continue x_coord.append(data[0]) y_coord.append(data[1]) def partial_derivative_m(m,c): sum_gradient_m = 0 for x in range(len(x_coord)): sum_gradient_m += (2 * x_coord[x]) * (m * x_coord[x] + c - y_coord[x]) return 1/len(x_coord) * sum_gradient_m def partial_derivative_c(m,c): sum_gradient_c = 0 for x in range(len(x_coord)): sum_gradient_c += 2 * (m * x_coord[x] + c - y_coord[x]) return 1/len(x_coord) * sum_gradient_c def main(): get_coordinates() c = 1 m = 1 c_finished = False m_finished = False while c_finished != True and m_finished != True: m_u = m c_u = c m = m - 0.0001 * partial_derivative_m(m,c) c = c - 0.0001 * partial_derivative_c(m,c) if round(m_u,10) == round(m,10): m_finished = True if round(c_u,10) == round(c,10): c_finished = True print('M:', round(m,2)) print('C:', round(c,2)) main()
daa9e0b1763f827a0e4ac37e06bf3b950e66a4e7
TuxMan20/CS50-2017
/pset6/mario.py
485
3.9375
4
## Infinite loop to get an Int from the user, breaks when it is accepted while True: try: h = int(input("Height: ")) except ValueError: continue else: if h >= 0 and h < 20: break else: continue hashes = 1 spaces = h-1 for i in range(h): for j in range(spaces): print(" ", end="") for k in range(hashes): print("#", end="") print("") spaces = spaces - 1 hashes = hashes + 1
c37cfa1798753fcd44b4b5174477a54fb3b798d8
kevalrathod/Python-Learning-Practice
/other_Exmple/FileInput_Output.py
371
3.796875
4
#reading file and output file f=open('myfile.txt','r') print(f.name()) print(f.mode()) f.close() #2nd method with open('myfile.txt','r') as f: size=4 fop=f.read(size) while len(fop)>0: print(fop,end='*') fop=f.read(size) #copy one file to another with open('myfile.txt','r') as f: with open('mynewtext.txt','w') as w: for line in f: w.write(line)
a357db0a866dfe5567c67cb1bd2f1a3a75d3fc70
deepsinghsodhi/python-OOPS-assignments
/Programs using Functions/01) Telephon_bill.py
1,591
4.03125
4
''' 1) Write a program that prompts the user to input number of calls and calculate the monthly telephone bills as per the following rule: Minimum Rs. 200 for up to 100 calls. Plus Rs. 0.60 per call for next 50 calls. Plus Rs. 0.50 per call for next 50 calls. Plus Rs. 0.40 per call for any call beyond 200 calls. ''' # ===================================================================================================================== class TeleBillCalc: def getCall(self): #Method to get input as number of calls from user. self.calls = int(input("Please Enter Number of calls:")) self.CalcBill() def CalcBill(self): # Method to calculate the monthly bills according to question. if self.calls <= 100: # If Number of calls are 100 or below. print("Your Monthly bill is:", 200) elif self.calls > 100 and self.calls <= 150: # If Number of calls are between 101 - 150. self.bill = 100 + (self.calls * 0.60) print("Your Monthly bill is (101-150 calls):", self.bill) elif self.calls > 150 and self.calls <= 200: # If Number of calls are between 151 - 200. self.bill = 100 + (self.calls * 0.60) + (self.calls * 0.50) print("Your Monthly bill is (151-200 calls):", self.bill) else: # If calls are more then 200. self.bill = 100 + (self.calls * 0.60) + (self.calls * 0.50) + (self.calls * 0.40) print("Your Monthly bill is (above 200 calls):", self.bill) t = TeleBillCalc() t.getCall()
00adb4416fb05217b477a32eb7bc713e98403bae
zhanggq96/AnimeStride
/Recommender/RC/RecommenderC.py
6,126
3.71875
4
## Based off of python implementation of Coursera ML 1 Course. ## https://github.com/mstampfer/Coursera-Stanford-ML-Python ## from matplotlib import use, cm use('TkAgg') import numpy as np from scipy.optimize import minimize # from show import show ## =============== Part 1: Loading movie ratings dataset ================ # You will start by loading the movie ratings dataset to understand the # structure of the data. # from .cofiCostFunc import cofiCostFunc # from loadMovieList import loadMovieList from .normalizeRatings import normalizeRatings def recommend(user_ratings, num_shows, ratings_matrix, shows, users, verbose = False, num_users = 100, num_recommendations = 5): # num_users = 100 # num_shows, ratings_matrix, shows, users = cdf.create_ratings_matrix(user_list_db = user_list_db, # show_list_db = show_list_db, verbose = verbose, max_users = num_users) # Notes: X - num_movies x num_features matrix of movie features # Theta - num_users x num_features matrix of user features # ratings_matrix - num_movies x num_users matrix of user ratings of movies # user_rated - num_movies x num_users matrix, where R[i, j] = 1 if the # i-th movie was rated by the j-th user # user_ratings: dict of 'show_name' : rating num_ratings = 0 # for show, rating in user_ratings.items(): # print('Show: ' + str(show) + ', Rating: ' + str(rating)) # print(len(users)) # print(users) show_map = {index: show for show, index in shows.items()} user_map = {index: user for user, index in users.items()} # for i in range(2000): # if i in show_map: # print('Index: ' + str(i) + ', Show: ' + show_map[i]) # for i in range(500): # print(show_map[i+1]) # print(ratings_matrix) # print(user_rated) # print(show_map) my_ratings = np.zeros(num_shows) # for i in range(50,100): # my_ratings[i] = (i+3) % 10 + 1 # print(show_map[i+3]) for show, rating in user_ratings.items(): try: my_ratings[shows[show]] = rating if int(rating) > 0: num_ratings = num_ratings + 1 except KeyError as ke: if verbose: print('Show ' + str(ke) + ' not in anime db.') except TypeError: if verbose: print('Type error in recommender c.') ratings_matrix_ = np.column_stack((my_ratings, ratings_matrix)) R = np.greater(ratings_matrix_, np.zeros(ratings_matrix_.shape)) # print(R[0:]) # print(user_rated) # print(ratings_matrix.shape) ratings_norm, ratings_mean = normalizeRatings(ratings_matrix_, R) # print(ratings_norm) # print(ratings_mean) num_users = ratings_matrix_.shape[1] # for row in ratings_matrix: # print(row) # for row in R: # print(row) num_features = 10 X = np.random.rand(num_shows, num_features) Theta = np.random.rand(num_users, num_features) initial_parameters = np.hstack((X.T.flatten(), Theta.T.flatten())) # Set Regularization Lambda = 10 if verbose: print(num_users, num_shows, num_features) costFunc = lambda p: cofiCostFunc(p, ratings_norm, R, num_users, num_shows, num_features, Lambda)[0] gradFunc = lambda p: cofiCostFunc(p, ratings_norm, R, num_users, num_shows, num_features, Lambda)[1] result = minimize(costFunc, initial_parameters, method='CG', jac=gradFunc, options={'disp': verbose, 'maxiter': 60.0}) theta = result.x cost = result.fun if verbose: print('Cost: ' + str(cost/num_shows)) # 0.9060709961732336 X = theta[:num_shows * num_features].reshape(num_shows, num_features) Theta = theta[num_shows * num_features:].reshape(num_users, num_features) if verbose: print('Recommender system learning completed.') # input("Program paused. Press Enter to continue...") p = X.dot(Theta.T) my_predictions = p[:, 0] + ratings_mean # print('Ratings Matrix: ') # for i in range(20): # print(ratings_matrix_[i]) # print('My predictions: ') # print(my_predictions) # print('Ratings Mean: ') # print(ratings_mean) pre=np.array([[idx, p] for idx, p in enumerate(my_predictions)]) post = pre[pre[:,1].argsort()[::-1]] r = post[:,1] ix = post[:,0] prediction = [] # print('\nTop recommendations for you:') # # for i in range(num_recommendations): # j = int(ix[i]) # if show_map[j] in user_ratings and user_ratings[show_map[j]] != 0: # prediction.append([my_predictions[j], show_map[j]]) i = 0 while len(prediction) < 5 and i < 1999: j = int(ix[i]) # print(j) i = i + 1 # Right now this is a mess... # If show_key in show_map and show_map[show_key] in user ratings and rating is not zero # if show_map[j] in user_ratings and user_ratings[show_map[j]] == 0: # if show_map[j] not in user_ratings or user_ratings[show_map[j]] == 0: prediction.append([my_predictions[j], show_map[j]]) # print('Predicting rating %.1f for show %s\n' % (my_predictions[j], show_map[j])) # print(i) return prediction # print('\nOriginal ratings provided:') # for i in range(len(my_ratings)): # if my_ratings[i] > 0: # print('Rated %d for %s\n' % (my_ratings[i], show_map[i])) # movieList = loadMovieList() # # # sort predictions descending # pre = np.array([[idx, p] for idx, p in enumerate(my_predictions)]) # post = pre[pre[:, 1].argsort()[::-1]] # r = post[:, 1] # ix = post[:, 0] # # print('\nTop recommendations for you:') # # for i in range(10): # j = int(ix[i]) # print('Predicting rating %.1f for movie %s\n' % (my_predictions[j], movieList[j])) # # print('\nOriginal ratings provided:') # for i in range(len(my_ratings)): # if my_ratings[i] > 0: # print('Rated %d for %s\n' % (my_ratings[i], movieList[i]))
b7f45c8336d421fcecb4be56503ee2ccf23516fd
yinghe616/NEKCEM
/bin/mapdegrees
1,770
3.6875
4
#! /usr/bin/env python import sys def establish_connectivity(elements): result = [] def connected(a, b): result.append((a,b)) el_point_count = len(elements[0])-1 if el_point_count == 4: for quad in elements: connected(quad[1], quad[2]) connected(quad[2], quad[4]) connected(quad[4], quad[3]) connected(quad[1], quad[3]) elif el_point_count == 8: for hex in elements: connected(hex[1], hex[2]) connected(hex[2], hex[4]) connected(hex[4], hex[3]) connected(hex[1], hex[3]) connected(hex[2], hex[6]) connected(hex[4], hex[8]) connected(hex[1], hex[5]) connected(hex[3], hex[7]) connected(hex[1+4], hex[2+4]) connected(hex[2+4], hex[4+4]) connected(hex[4+4], hex[3+4]) connected(hex[1+4], hex[3+4]) else: print "Don't know what element to use for point count", el_point_count import sys sys.exit(1) return result def main(): import sets map = file(sys.argv[1], "r").readlines()[1:] elements = [ [-1] + [int(number) for number in line.split()] [1:] for line in map] node_cnx = {} def connect_one_way(a,b): if a in node_cnx: node_cnx[a].add(b) else: node_cnx[a] = sets.Set([b]) for (a,b) in establish_connectivity(elements): connect_one_way(a,b) connect_one_way(b,a) #for node, cn in node_cnx.iteritems(): #print node, cn cnx_hist = {} for node in node_cnx.keys(): degree = len(node_cnx[node]) if degree in cnx_hist: cnx_hist[degree] += 1 else: cnx_hist[degree] = 1 for degree in cnx_hist.keys(): print "%d nodes of degree %d" % (cnx_hist[degree], degree) if __name__ == "__main__": main()
7626d591317ba624a890c66ef3da9533d0283b52
nd9dy/Algorithmic-Toolbox
/Algorithm Toolbox/Week 2 Code/Fibonacci Partial Last Digit Sum.py
865
3.671875
4
# Uses python3 import sys them = [0,1,1] i = 3 while True: if them[i - 1] == 1 and them[i - 2] == 0: break new = (them[i - 1] % 10) + (them[i - 2] % 10) real = new % 10 them.append(real) i += 1 def fibonacci_sum_naive(n,m): global them if n == m: if n < 2: return n else: yam = them length = len(yam) - 2 if yam[n % length] == -1: return 9 else: return yam[n % length] else: raw = them length = len(raw) - 2 maybe = raw[(m+2) % length] - 1 compare = raw[(n + 1) % length] - 1 if maybe < compare: return (maybe + 10) - compare else: return maybe - compare store = input() n , m = map(int, store.split()) print(fibonacci_sum_naive(n, m))
2b2d0fa76ada5baa16f4d41d4b6cd64465d9f0db
wjddp0220/wjddp0000
/파이썬/210723ox.py
253
3.828125
4
num = input("o 와 x를 배열하시오 : ") score = [] for n in range(0, len(num)): if(num[n] == "o"): score += 1 elif(num[n] == "x"): score += 0 elif(num[n] == num[n-1] == "o"): score += score.append
a3a73030b3ccae8a84cb0fe8d0f4ce82a1e813c2
jvasilakes/Search_Algorithms
/dfs.py
691
3.984375
4
#! /usr/bin/python2 # A depth-first search of graph for end graph = { '1': ['2', '3', '4'], '2': ['5', '6'], '5': ['9', '10'], '4': ['7', '8'], '7': ['8', '11', '12'], '11': ['13', '14', '15'], '12': ['16'] } graph2 = { '1': ['2', '3', '4'], '2': ['5'], '4': ['6'], '5': ['6', '7'], '6': ['7', '8'] } def dfs(graph, start=None, end=None, visited=None): if not visited: visited = list() visited.append(start) for adj in graph.get(start, []): visited = dfs(graph, adj, end, visited) if visited and visited[-1] == end: return visited else: visited.pop() return visited if __name__ == '__main__': print dfs(graph2, start='1', end='8')
1d8008e8d24ae3135cf971a910716b3c4f04bf1d
Sukhrobjon/leetcode
/easy/783_minimum_ difference_between_bst_nodes.py
1,482
4.0625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None """ Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree. 1. Naive solution: traverse the tree, get in order traversal. Then find all possible difference between pairs, which takes O(n^2) 2. For each node find the closest number to it, which takes O(nlogn), because we search for closer number in logn time for each n nodes. 3. Do in order traversal and Compare the adjacents, keep track of min difference """ class Solution(object): # smallest number possible prev = -float('inf') # the biggest possible difference difference = float('inf') def minDiffInBST(self, root): """ :type root: TreeNode :rtype: int """ self.in_order(root) return self.difference def in_order(self, node, prev=None, difference=None): if node is None: return # if prev is None and difference is None: # prev = -float('inf') # difference = float('inf') self.in_order(node.left) self.difference = min(node.val-self.prev, self.difference) # update the prev value to current node's val self.prev = node.val # move to the right side of node self.in_order(node.right)