blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
87f3692eb4df2e6e113a4c71f00a09712d29b89c
MrWater/XPyTest
/Python/GUI/test_listbox.py
1,019
3.546875
4
import tkinter root = tkinter.Tk() # selectmode: single multiple browse(移动鼠标进行选中,而不是单击选中) EXTENDED支持shift和ctrl listbox = tkinter.Listbox(root, selectmode=tkinter.MULTIPLE) listbox.pack() for i in range(19): listbox.insert(tkinter.END, i) listbox = tkinter.Listbox(root, selectmode=tkinter.BROWSE) listbox.pack() for i in range(19): listbox.insert(tkinter.END, i) listbox = tkinter.Listbox(root, selectmode=tkinter.EXTENDED) listbox.pack() for i in range(19): listbox.insert(tkinter.END, i) # selection_set 两个参数索引表示范围,一个则选中一个 # selection_clear 取消选中 # curselection() 当前选中项,而不是索引 # selection_includes(index) 判断某个索引是否被选中 # listvariable 绑定变量 # listbox不支持command设置毁掉函数,必须使用bind来指定 print(listbox.size()) print(listbox.get(3)) print(listbox.get(3,9)) listbox.bind('<Double-Button-1>', lambda event: print(listbox.curselection())) root.mainloop()
1d1a37c8933d54fe5f697a5718b13d09233dda7c
MrWater/XPyTest
/cv/test.py
121
3.546875
4
#-*-coding:utf8-*- import numpy as np arr = np.random.random((2, 2, 2, 3)) print(arr) np.random.shuffle(arr) print(arr)
1e629e6a649ca028d7eef107d2e51f98a96c0f46
D4N-W4TS0N/Python-Lockdown
/while_loops.py
75
3.671875
4
i = 1 while i <= 10: print(i * "this is a while loop") i = i + 1
4d4c2670577d87081d1404c1414ecda037d8f769
psk264/rock-paper-scissors
/game.py
3,680
4.15625
4
# game.py # Rock-Paper-Scissors program executed from command line #import modules to use additional third party packages import random import os import dotenv #Input command variation, using print and input # print("Enter your name: ") # player_name = input() #Above statements can be reduced to single line of code #Option 1: # print("Fetching player name from command line") # player_name = input("Enter your name: ") #Option 2: Fetching player name from command line using command: PLAYER_NAME="Guest" if env is missing (package needed: os) # PLAYER_NAME = os.getenv("PLAYER_NAME") # player_name = PLAYER_NAME # print("Fetching player name from command line using command \'PLAYER_NAME=\"Guest\" python game.py\'") #Option 3:Fetching player name from environment variable (package needed: dotenv) dotenv.load_dotenv() player_name = os.getenv("PLAYER_NAME") print("Fetching player name from env file") #User Choice: if(player_name and player_name.strip()): print("Welcome, ", player_name, "! Get ready to play Rock-Paper-Scissors.") else: print("OOPS! player name is empty. No problem, we got your back!") player_name = input("Please enter the player name: ") user_choice = input("Please choose one of 'rock', 'paper', 'scissors': ") print(player_name+"'s choice:", user_choice) #Computer Choice: # one way to write the choice statement is to enter the list in the argument # computer_choice = random.choice(["rock","paper","scissors"]) #another way to write choice statement using list valid_options = ["rock","paper","scissors"] computer_choice = random.choice(valid_options) # print("Computer's choice:", computer_choice) #******************************************************************** #Game Logic Approach 1 #This can be improved by removing duplicate checks and improved readability #******************************************************************** # if(user_choice in valid_options): # if(user_choice == computer_choice): # print("Its a tie!") # elif(user_choice == "rock"): # if(computer_choice == "scissors"): # print(player_name, "won!") # elif(computer_choice == "paper"): # print("Oh, the computer won. It's ok.") # elif(user_choice == "paper"): # if(computer_choice == "rock"): # print(player_name, "won!") # elif(computer_choice == "scissors"): # print("Oh, the computer won. It's ok.") # elif(user_choice == "scissors"): # if(computer_choice == "paper"): # print(player_name, "won!") # elif(computer_choice == "rock"): # print("Oh, the computer won. It's ok.") # print("Thanks for playing. Please play again!") #******************************************************************** #Game Logic Approach 2 #******************************************************************** if(user_choice in valid_options): print("Computer's choice:", computer_choice) if(user_choice == computer_choice): print("Its a tie!") elif(user_choice == "rock" and computer_choice == "scissors") or (user_choice == "paper" and computer_choice == "rock") or (user_choice == "scissors" and computer_choice == "paper"): print(f"{player_name} won! {user_choice} beats {computer_choice}") else: print(f"Oh, the computer won! {computer_choice} beats {user_choice}") print("It's ok") print("Thanks for playing. Please play again!") else: print("Oops, invalid input. Accepted values: 'rock', 'paper', 'scissors'. You entered '" + user_choice + "'") print("THIS IS THE END OF OUR GAME. PLEASE TRY AGAIN.") exit()
ecbd94b636438891fa11ed64943fa66eef961d00
ezeutno/All_Comp_Math_Assignment
/Exam Simulation/Data.py
2,014
3.84375
4
from sympy import * import numpy as np import math as m import matplotlib.pyplot as plt #Latihan Exam BiMay #Number 1 def fact(num): res = 1 for i in range(1,num+1): res *= i return res def Maclaurin(x,n): res = 0 if type(n) is np.ndarray: data = [] for a in np.nditer(n): for k in range(a): res += ((-1)**k/fact(2*k+1))*(x**(2*k+1)) data.append(res) res = 0 return np.array(data) else: for k in range(n): res += ((-1)**k/fact(2*k+1))*(x**(2*k+1)) return res print("Number 1") maclaurinRes = Maclaurin(np.pi/3,100) exactValueSIN = 0.5*m.sqrt(3) print("SIN 60 : ",maclaurinRes,"|",exactValueSIN) print("Margin of Error : ", (abs(exactValueSIN - maclaurinRes)/exactValueSIN)*100,"%") #Number 2 print("Number 2") n = np.array([5,10,20,50,100]) multiMacRes = abs(np.ones(5)*exactValueSIN - Maclaurin(np.pi/3,n)) plt.plot(n,multiMacRes,label = "ERROR") plt.legend() plt.show() #Number 3 print("Number 3") x = symbols('x') expression = sin(x)/(1+x**2) resInter = integrate(expression,(x,0,pi/2)).evalf() print("Result : ",resInter) #Number 4 print("Number 4") f = lambda x: np.sin(x)/(1+x**2) def simpIntegrat(n, fx=f, a=0, b=np.pi/2): if type(n) is np.ndarray: data = [] for h in np.nditer(n): x = np.linspace(a,b,h+1) w = np.ones(h+1) w[1:-1:2] = 4 w[2:-2:2] = 2 data.append(sum(w*fx(x))*abs(x[0]-x[1])/3) return np.array(data) else: x = np.linspace(a,b,n+1) w = np.ones(n+1) w[1:-1:2] = 4 w[2:-2:2] = 2 return sum(w*fx(x))*abs(x[0]-x[1])/3 n = np.array([2,5,10,50,100,200,1000,10000,20000,30000,35000]) res = simpIntegrat(n) print("n".ljust(5),"estimassion".ljust(23),"error%") print("="*50) for i in range(len(n)): print(repr(n[i]).ljust(5),repr(res[i]).ljust(23),(abs(res[i]-resInter)/resInter)*100) print("="*50)
caded9115b67830a704ea736272a43d4923b7a90
Jeduroid/intermediate-python-course
/dice_roller.py
537
3.953125
4
import random def main(): dice_rolls = int(input('\nHow many dice you want to roll : ')) dice_size = int(input('\nHow many sides a dice have : ')) dice_sum = 0 for i in range(0,dice_rolls): roll = random.randint(1,dice_size) dice_sum += roll if roll == 1: print(f'You rolled a {roll} ! Critical Failure !') elif roll ==dice_size: print(f'You rolled a {roll} ! Criticial Success !') else: print(f'You rolled a {roll}') print(f'Dice sum = {dice_sum}') if __name__== "__main__": main()
f0b385abec60ac9edaa7d68ea9cceb83c52062e1
ktheylin/ProgrammingForEveryone
/Python-GettingStarted/assg4-6.py
278
3.828125
4
def computepay(hrs, rate): if hrs <= 40: gross_pay = hrs * rate else: gross_pay = 40 * rate + ( (hrs - 40) * (rate * 1.5) ) return(gross_pay) hrs = float(raw_input("Enter Hours: ")) rate = float(raw_input("Enter Rate per Hour: ")) print computepay(hrs,rate)
3abb8b828e114b048fd19d232e858e0f204f2901
ktheylin/ProgrammingForEveryone
/Python-WebAccessData/week4-followLinks.py
733
3.5
4
# Note - this code must run in Python 2.x and you must download # http://www.pythonlearn.com/code/BeautifulSoup.py # Into the same folder as this program import urllib from BeautifulSoup import * tag_index = 17 loop = 7 count = 0 #url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html' url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Asiya.html' # Continue to read the next URL until loop counter has been met while count < loop: html = urllib.urlopen(url).read() soup = BeautifulSoup(html) tags = soup('a') # Get the index number of the tag tag = tags[tag_index] # print tag url = tag.get('href', None) print 'Retrieving:', url count = count + 1
36f889bbd9010c826012a2e0b12600aba9ab9ee3
Leo-Simpson/c-lasso
/classo/stability_selection.py
5,674
3.59375
4
import numpy as np import numpy.random as rd from .compact_func import Classo, pathlasso """ Here is the function that does stability selection. It returns the distribution as an d-array. There is three different stability selection methods implemented here : 'first' ; 'max' ; 'lam' - 'first' will compute the whole path until q parameters pop. It will then look at those paremeters, and repeat it for each subset of sample. It this case it will also return distr_path wich is an n_lam x d - array . It is usefull to have it is one want to plot it. - 'max' will do the same but it will stop at a certain lamin that is set at 1e-2 * lambdamax here, then will look at the q parameters for which the max_lam (|beta_i(lam)|) is the highest. - 'lam' will, for each subset of sample, compute the classo solution at a fixed lambda. That it will look at the q highest value of |beta_i(lam)|. """ def stability( matrix, StabSelmethod="first", numerical_method="Path-Alg", Nlam=100, lamin=1e-2, lam=0.1, q=10, B=50, percent_nS=0.5, formulation="R1", seed=1, rho=1.345, rho_classification=-1.0, true_lam=False, e=1.0, w=None, intercept=False, ): rd.seed(seed) n, d = len(matrix[2]), len(matrix[0][0]) if intercept: d += 1 nS = int(percent_nS * n) distribution = np.zeros(d) lambdas = np.linspace(1.0, lamin, Nlam) if StabSelmethod == "first": distr_path = np.zeros((Nlam, d)) distribution = np.zeros(d) for i in range(B): subset = build_subset(n, nS) submatrix = build_submatrix(matrix, subset) # compute the path until n_active = q. BETA = np.array( pathlasso( submatrix, lambdas=lambdas, n_active=q + 1, lamin=0, typ=formulation, meth=numerical_method, rho=rho, rho_classification=rho_classification, e=e * percent_nS, w=w, intercept=intercept, )[0] ) distr_path = distr_path + (abs(BETA) >= 1e-5) pop = biggest_indexes(BETA[-1], q) distribution[pop] += 1.0 # to do : output, instead of lambdas, the average aciv """ distr_path(lambda)_i = 1/B number of time where i is (among the q-first & activated before lambda) """ # distribution = distr_path[-1] return (distribution * 1.0 / B, distr_path * 1.0 / B, lambdas) elif StabSelmethod == "lam": for i in range(B): subset = build_subset(n, nS) submatrix = build_submatrix(matrix, subset) regress = Classo( submatrix, lam, typ=formulation, meth=numerical_method, rho=rho, rho_classification=rho_classification, e=e * percent_nS, true_lam=true_lam, w=w, intercept=intercept, ) if type(regress) == tuple: beta = regress[0] else: beta = regress qbiggest = biggest_indexes(abs(beta), q) for i in qbiggest: distribution[i] += 1 elif StabSelmethod == "max": for i in range(B): subset = build_subset(n, nS) submatrix = build_submatrix(matrix, subset) # compute the path until n_active = q, and only take the last Beta BETA = pathlasso( submatrix, n_active=0, lambdas=lambdas, typ=formulation, meth=numerical_method, rho=rho, rho_classification=rho_classification, e=e * percent_nS, w=w, intercept=intercept, )[0] betamax = np.amax(abs(np.array(BETA)), axis=0) qmax = biggest_indexes(betamax, q) for i in qmax: distribution[i] += 1 return distribution * 1.0 / B """ Auxilaries functions that are used in the main function which is stability """ # returns the list of the q highest componants of an array, using the fact that it is probably sparse. def biggest_indexes(array, q): array = abs(array) qbiggest = [] nonnul = np.nonzero(array)[0] reduc_array = array[nonnul] for i1 in range(q): if not np.any(nonnul): break reduc_index = np.argmax(reduc_array) index = nonnul[reduc_index] if reduc_array[reduc_index] == 0.0: break reduc_array[reduc_index] = 0.0 qbiggest.append(index) return qbiggest # for a certain threshold, it returns the features that should be selected def selected_param(distribution, threshold, threshold_label): selected, to_label = [False] * len(distribution), [False] * len(distribution) for i in range(len(distribution)): if distribution[i] > threshold: selected[i] = True if distribution[i] > threshold_label: to_label[i] = True return (np.array(selected), np.array(to_label)) # submatrices associated to this subset def build_submatrix(matrix, subset): (A, C, y) = matrix subA, suby = A[subset], y[subset] return (subA, C, suby) # random subset of [1,n] of size nS def build_subset(n, nS): return rd.permutation(n)[:nS]
bb18f87d4e9fe1d0489fe3f833200955d9d80e80
ysabhi1993/Python-Practice
/Queue_imp.py
1,305
3.953125
4
class Node: def __init__(self, data): self.data = data self.nextnode = None class Queue: def __init__(self): self.head = None self.size = 0 def IsEmpty(self): return self.head == None def enqueue(self, data): currentnode = None newnode = Node(data) if self.head is not None: currentnode = self.head else: self.head = newnode currentnode = self.head while currentnode.nextnode is not None: currentnode = currentnode.nextnode currentnode.nextnode = newnode newnode.nextnode = None def dequeue(self): currentnode = self.head self.head = currentnode.nextnode return currentnode.data def peek(self): return self.head.data def print_queue(self): currentnode = self.head while currentnode is not None: print(currentnode.data) currentnode = currentnode.nextnode def size_queue(self): self.size = 0 currentnode = self.head while currentnode is not None: self.size += 1 currentnode = currentnode.nextnode return self.size
c4c527c574ca40c828dacc7da03a6216a946f53c
ysabhi1993/Python-Practice
/useful_functions.py
7,609
3.984375
4
#Checks if a number is even or odd def checkOE(): num = int(input("Enter a number:")) if num%2 == 1: print('The number you entered is odd') elif num%4 == 0: print('The number you entered is divisible by 4') else: print('The number is even') #prints out a string that says if a number is divisible by another def check_div(num,check): if num%check == 0: print('The number is divisible by {}' .format(check)) else: print('The number is not divisible by {}'.format(check)) #prints out a list of all integers < a user specified input def under_ten(a): b = int(input("Enter a number:")) c = [i for i in a if i < b] print(c) #prints out a list of all the factors def factors(a): b = [] for i in range(1,a+1): if (a%i) == 0: b.append(i) print(b) #compares and prints the common objects in a list to a new list without repetation def common_list(a,b): c = [] for i in a: if i in b: if i not in c: c.append(i) print(c) def common_list1(a,b): return (a&b) #read a string and verify if its a palindrome def palindrome(a): b = list(a) #it is not necessary to convert the string into a list, but if we need to change in-place, it will help. b.reverse() c = list(a) if c == b: print('its a palindrome') else: print('not a palindrome') def palindrome_trivial(a): #b = list(a) count = 0 for i in range(int(len(a)/2)+1): if a[i] == a[ len(a) -i - 1]: count +=1 else: count+=0 if count >= int(len(a)/2): print('its a palindrome') else: print('not a palindrome') #make a new list of all even numbers from a given list in one line def even_list(a): b=[i for i in a if i%2 == 0] return b #guess a random number def guess_num(): import random str_input = '' count = 0 while str_input is not 'exit': b = random.randint(1,9) count += 1 i_input = input("enter a number:") if i_input == 'exit': str_input = 'exit' elif int(i_input) == b: print('correct') elif int(i_input) > b: print(b) print('too high') else: print(b) print('too low') print("number of attempts:{}".format(count - 1)) #prime or not def primality(a): c = [] for i in range(1, a+1): if a%i == 0: c.append(i) if c == [1,a]: print('the number is prime') else: print('the number is not prime. These are its factors: {}'.format(c)) #fibonacci series def fibonacci_seq(n): a = [0,1] for i in range(1,n+1): a.append( a[i] + a[i-1]) print(a) #list remove duplicates def rem_dup_list(a): a = list(a) b = [] for i in a: if i not in b: b.append(i) return b def rem_dup_set(a): a = list(a) b = list(set(a)) return b #reverse word order def rev_word(): a = input("enter a string:") b = a.split(" ") c = [] for i in range(len(b)): c.append(b[len(b) - i - 1]) b.reverse() print(" ".join(b)) return c #find the median of sorted arrays def findMedianSortedArrays(nums1, nums2): nums3 = nums1 + nums2 nums3.sort() if len(nums3) == 0: return 0 elif len(nums3) == 1: return nums3[0] elif len(nums3) % 2 == 1: return nums3[int(len(nums3)/2)] else: a = float((nums3[int(len(nums3)/2) -1] + nums3[int(len(nums3)/2)])) return a/2 #sum of two numbers in an array equals target def twoSum(nums, target): a = [] if len(nums) <= 1: return False else: for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i] + nums[j] == target: a.append(i) a.append(j) return a def twoSum1(nums, target): if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i+1] else: buff_dict[target - nums[i]] = i+1 #finding hamming distance def hammingDistance(x, y): count = 0 z = x^y z = list(bin(z)[2:]) for i in z: if i == '1': count += 1 return count #find the sum of all digits def addDigits(num): #d = [int(i) for i in list(str(num))] #num = sum(d) while num>9: d = [int(i) for i in list(str(num))] num = sum(d) addDigits(num) else: return num def findContentChildren(g, s): count = 0 a = [] s = list(set(s)) print(s) for i in s: if i in g: count += 1 g.remove(i) a.append(i) print(count) g.sort() for i in a: s.remove(i) for i in s: for j in g: if i > j: count += 1 g.remove(j) break #Ransom Note def canConstruct(ransomNote, magazine): return not collections.Counter(ransomNote) - collections.Counter(magazine) def canConstruct(ransomNote, magazine): count = 0 ransomNote = list(ransomNote) magazine = list(magazine) if ransomNote == [] and magazine == []: return True else: for i in ransomNote: if i in magazine: magazine.remove(i) count += 1 if count == len(ransomNote): return True else: return False #intersection of two arrays def intersection(nums1, nums2): return list(set(nums1)&set(nums2)) #sum if squares of n integers def sum_of_squares(n): count = 0 for i in range(n+1): count += i**2 return count #check if integer repeats def int_rep(a): import collections b = list(dict(collections.Counter(a)).values()) if 2 in b: print('repetitions yes') else: print('no repetitions') #p-norm def norm(v,p=2): a = [i**p for i in v] b = sum(a)**(1/p) print(b) #int to binary def converti_b(a): c = 0 while a>0: b = a%2 a = int(a/2) c += 1 return c def firstUniqChar(s): count = [0]*len(s) for i in range(len(s)): for j in range(len(s)): if s[i] == s[j]: count[i] += 1 print(count) if s == '': return -1 else: if 1 in count: for i in range(len(count)): if count[i] == 1: return i break else: return -1 #find integer value of excel column def titleToNumber(s): count = 0 a = len(s) for i in range(a): count+= (26**(a-i-1))*(ord(s[i])-64) return count
47358be77fec8fc5229dfb73736cb8a92f74e406
nan0314/RRTstar
/RRTstar.py
12,203
3.640625
4
import pygame import random as r import pylineclip as lc ############################################ ## Constants ############################################ # Define colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0,0,255) YELLOW = (255,255,0) PURPLE = (128,0,128) # This sets the wdith of the screen WIDTH = 800 WINDOW_SIZE = [WIDTH, WIDTH] # RRT Constants NODE_RADIUS = 4 # The radius of a node as it is drawn on the pygame screen RRT_RADIUS = 20 # The radius used to place new nodes SEARCH_RADIUS = 30 # The radius searched when considering reconnecting nodes END_RADIUS = 20 # The allowable distance from the end node needed to end the algorithm NODES = 20 # The number of new nodes created in a single step of the algorithm ############################################ ## Classes ############################################ class obstacle(): ''' This class represents an obstacle in the grid ans stores the positional data associated with a given obstacle ''' def __init__(self,x1,y1,x2,y2): self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 class node(): ''' This class represents an RRT node and stores the necessary information associated with that node. ''' def __init__(self,x,y): # Positional Data self.x = x self.y = y # Node cost (distance of path to this point) self.cost = 0 # Start/end or path self.start = False self.end = False self.path = None ############################################ ## Functions ############################################ def between(sample,b1,b2): ''' This function takes a sample integer and checks to see if that integer is between to outher boundary integers b1 and b2 ''' if b1 <= sample and sample <= b2: return True elif b2 <= sample and sample <= b1: return True else: return False def euclidean(x1,y1,x2,y2): ''' This function calculates the Euclidean distance between two points. Note that the arguments are the individual x and y values of the two points, not two pairs of points. ''' ans = ((x1-x2)**2 + (y1-y2)**2)**.5 return ans def updatePOS(closest,pos): ''' This function is part of the RRT* algorithm that is used to set the location of a new node. To do this, a random point is generated anywhere on the map and the node closest to that is found. This function takes those two as inputs and calculates a new position by taking the nearest node and moving a constant distance (RRT_RADIUS) in the direction of the random point closest - nearest node to random point pos - random point coordinates [x,y] ''' # Vector from closest to pos vector = [pos[0]-closest.x,pos[1]-closest.y] # Adjust vector to RRT radius length magnitude = (vector[0]**2 + vector[1]**2)**.5 normed_vector = [x / magnitude * RRT_RADIUS for x in vector] # Calculate the position of the new node new_pos = [int(closest.x+normed_vector[0]),int(closest.y+normed_vector[1])] return new_pos def drawBoard(obstacles, nodes): # Set the screen background screen.fill(WHITE) # Draw obstacles for i in obstacles: w = i.x2-i.x1 h = i.y2-i.y1 rectangle = pygame.rect.Rect(i.x1,i.y1,w,h) pygame.draw.rect(screen, BLACK, rectangle) # Draw nodes if nodes != []: for i in nodes: if i.start or i.end: continue pygame.draw.circle(screen,RED,(i.x,i.y),NODE_RADIUS) # Draws node pygame.draw.line(screen,RED,(i.x,i.y),(i.path.x,i.path.y)) # Draws links between nodes pygame.draw.circle(screen,BLUE,(start.x,start.y),NODE_RADIUS) # Draws start node pygame.draw.circle(screen,YELLOW,(end.x,end.y),END_RADIUS) # Draws end circle around end node. pygame.draw.circle(screen,PURPLE,(end.x,end.y),NODE_RADIUS) # Draws end node def endGame(end_node): ''' This function is called at the end of the RRT* algorithm when a path to the end node has been found. It takes the end_node and redraws the complete path using purple instead of the standard red. ''' # Draw the path in purple starting from the end node current = end_node while current.path is not None: pygame.draw.circle(screen,PURPLE,(current.x,current.y),NODE_RADIUS) # Draw nodes in the path pygame.draw.line(screen,PURPLE,(current.x,current.y),(current.path.x,current.path.y)) # Draw links between nodes current = current.path # Move back to the prior node in the path. # Update the screen pygame.display.flip() ############################################ ## Visualization ############################################ # Initialize pygame pygame.init() # Set the size of the screen screen = pygame.display.set_mode(WINDOW_SIZE) # Set the screen background screen.fill(WHITE) # Set title of screen pygame.display.set_caption("RRT* Pathfinding Algorithm") # Used to manage how fast the screen updates clock = pygame.time.Clock() # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Shape variables x1 = x2 = y1 = y2 = 0 # RRT variables obstacles = [] # List to hold the obstacle objects nodes = [] # List to hold the node objects placed = False # Has the user finished placing objects? Started = False # Has the user started the algorithm? start = None # start node end = None # end node found = False # Has a path been found from start to stop drawing = False # Is user currently drawing an obstacle (used to show obstacles as user is drawing with click-drag) ############################################ ## Main Loop ############################################ done = False while not done: # Board setup for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop # If user presses the spacebar, switch from placing obstacles to placing start and end or the algorithm starts. if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: if placed: Started = True else: placed = True # Skip setup commands if algorithm has started if Started: continue # Create obstacle # User clicks and the position is svaed elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and not placed: x1, y1 = event.pos drawing = True # Draw obstacle as user is dragging cursor on screen elif event.type == pygame.MOUSEMOTION and drawing == True: x2, y2 = event.pos w = x2-x1 h = y2-y1 drawBoard(obstacles,nodes) rectangle = pygame.rect.Rect(x1,y1,w,h) pygame.draw.rect(screen, BLACK, rectangle) # Draw and save obstacle when user releases mouse elif event.type == pygame.MOUSEBUTTONUP and event.button == 1 and not placed: x2, y2 = event.pos w = x2-x1 h = y2-y1 rectangle = pygame.rect.Rect(x1,y1,w,h) pygame.draw.rect(screen, BLACK, rectangle) obstacles.append(obstacle(x1,y1,x2,y2)) drawing = False # Create start node elif pygame.mouse.get_pressed()[0] and placed and start is None: # User clicks the mouse. Get the position pos = pygame.mouse.get_pos() start = node(pos[0],pos[1]) start.start = True nodes.append(start) pygame.draw.circle(screen,BLUE,(start.x,start.y),NODE_RADIUS) # Create end node elif pygame.mouse.get_pressed()[2] and placed and end is None: # User clicks the mouse. Get the position pos = pygame.mouse.get_pos() end = node(pos[0],pos[1]) end.end = True pygame.draw.circle(screen,YELLOW,(end.x,end.y),END_RADIUS) pygame.draw.circle(screen,PURPLE,(end.x,end.y),NODE_RADIUS) # RRT* Algorithm if Started: # Set up algorithm invalid = False # True if node placement is invalid num = 0 # Number of valid nodes succesfully placed # Add NODES amount of nodes while num<=NODES: # Generate random position pos = [r.randint(0,WIDTH-1),r.randint(0,WIDTH-1)] # Find the closest node to that position closest = start for i in nodes: distance = euclidean(i.x,i.y,pos[0],pos[1]) if euclidean(closest.x,closest.y,pos[0],pos[1]) > euclidean(i.x,i.y,pos[0],pos[1]): closest = i if distance == 0: invalid = True # If the node is on top of another node, try again if invalid: invalid = False continue # Update the position to be RRT_RADIUS away from the closest node in the direction of the original position pos = updatePOS(closest,pos) # Check to see if the node is in an obstacle and if so try again for i in obstacles: if between(pos[0],i.x1,i.x2) and between(pos[1],i.y1,i.y2): invalid = True break if invalid: invalid = False continue # Find the cheapest node in RRT_RADIUS cheapest = closest for i in nodes: if euclidean(i.x,i.y,pos[0],pos[1]) <= SEARCH_RADIUS and i.cost < cheapest.cost: cheapest = i # If line between cheapest and new node intersects obstacle, try again for i in obstacles: xlist = [i.x1,i.x2] ylist = [i.y1,i.y2] x3,y3,x4,y4 = lc.cohensutherland(min(xlist), max(ylist), max(xlist), min(ylist), cheapest.x, cheapest.y, pos[0], pos[1]) if x3 is not None or y3 is not None or x4 is not None or y4 is not None: invalid = True break if invalid: invalid = False continue # If completely successful, create new node connected to cheapest near node newNode = node(pos[0],pos[1]) newNode.cost = cheapest.cost + euclidean(newNode.x,newNode.y,cheapest.x,cheapest.y) newNode.path = cheapest # Stores the node that the newNode is linked to # Record and store the new node nodes.append(newNode) num+=1 # Rewire nearby nodes if cheaper to do so for i in nodes: tempCost = newNode.cost + euclidean(newNode.x,newNode.y,i.x,i.y) if tempCost < i.cost and euclidean(newNode.x,newNode.y,i.x,i.y)< SEARCH_RADIUS: i.path = newNode i.cost = tempCost # Check if end has been found if euclidean(newNode.x,newNode.y,end.x,end.y) <= END_RADIUS: end.path = newNode found = True # Draw new nodes to board drawBoard(obstacles,nodes) # End node has been found if found: # Draw the path to the end node endGame(end) go = False # Allow the user to continue algorithm to add more nodes and optimize path while not go: for event in pygame.event.get(): if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: go = True if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop go = True pygame.display.flip() # End the pygame instance pygame.quit()
4f32d0b2293ff8535a870cd9730528ecf4874190
comedxd/Artificial_Intelligence
/2_DoublyLinkedList.py
1,266
4.21875
4
class LinkedListNode: def __init__(self,value,prevnode=None,nextnode=None): self.prevnode=prevnode self.value=value self.nextnode=nextnode def TraverseListForward(self): current_node = self while True: print(current_node.value, "-", end=" ") if (current_node.nextnode is None): print("None") break current_node = current_node.nextnode def TraverseListBackward(self): current_node = self while True: print(current_node.value, "-", end=" ") if (current_node.prevnode is None): print("None") break current_node = current_node.prevnode # driver code if __name__=="__main__": node1=LinkedListNode("Hello ") node2=LinkedListNode("Dear ") node3=LinkedListNode(" AI ") node4=LinkedListNode("Student") head=node1 tail=node4 # forward linking node1.nextnode=node2 node2.nextnode=node3 node3.nextnode=node4 # backward linking node4.prevnode=node3 node3.prevnode=node2 node2.prevnode=node1 head.TraverseListForward() tail.TraverseListBackward()
85f7053fa27c235f58c6042f625a691c47f622c0
comedxd/Artificial_Intelligence
/0-13-Nested_Function_NON_Local_variables.py
297
3.578125
4
# Defining the nested function only def print_msg(msg): def printer(): print(msg) #nested function is accessing the non-local variable 'msg' printer() print("i am outer function") printer() # calling the nested function # driver code print_msg("this is message")
b45abb8df2533c41170f40dcbd293c6c58ab29fc
comedxd/Artificial_Intelligence
/0-5-dataprotection.py
403
3.890625
4
class Square: def __init__(self): self._height = 2 self._width = 2 def set_side(self,new_side): self._height = new_side # variables having name starting with _ are called protected variables self._width = new_side # protected variable can be accessed outside class square = Square() square._height = 3 # not a square anymore print(square._height,square._width)
76348acf643b1cd9764e1184949478b3b888b014
jdipendra/asssignments
/multiplication table 1-.py
491
4.15625
4
import sys looping ='y' while(looping =='y' or looping == 'Y'): number = int(input("\neneter number whose multiplication table you want to print\n")) for i in range(1,11): print(number, "x", i, "=", number*i) else: looping = input("\nDo you want to print another table?\npress Y/y for yes and press any key to exit program.\n") if looping =='y' or looping == 'Y': looping = looping else: sys.exit("program exiting.......")
e6e94d3d50a56f104d1ad9993d78f8c44394b753
jdipendra/asssignments
/check square or not.py
1,203
4.25
4
first_side = input("Enter the first side of the quadrilateral:\n") second_side = input("Enter the second side of the quadrilateral:\n") third_side = input("Enter the third side of the quadrilateral:\n") forth_side = input("Enter the forth side of the quadrilateral:\n") if float(first_side) != float(second_side) and float(first_side) != float(third_side) and float(first_side) != float(forth_side): print("The Geometric figure is an irregular shaped Quadrilateral.") elif float(first_side) == float(third_side) and float(second_side) == float(forth_side) and float(first_side) != float(second_side): digonal1 = input("Enter first digonal:\n") digonal2 = input("Enter second digonal:\n") if float(digonal1) == float(digonal2): print("The Geometric figure is a rectangle.") else: print("The Geometric figure is a parallelogram.") elif float(first_side) == float(second_side) == float(third_side) == float(forth_side): digonal1 = input("Enter first digonal:\n") digonal2 = input("Enter second digonal:\n") if float(digonal1) == float(digonal2): print("The Geometric figure is a square.") else: print("The Geometric figure is a rhombus.")
a7b9b32d1a9e5ee6c7cf1a3b1556a5140a0c98d9
jdipendra/asssignments
/mine calculator.py
4,012
4.46875
4
import sys menu = True def calculator(): print("You can do the following mathematical operations with BRILLIANT-CALCLATOR APP") print("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Square Root\n6.Square\n7.Exponential\n8.nth Root") choice = int(input("Enter Your choice")) condition = 'Y' while condition == 'Y': if choice == 1: print("You choose an Addition.\nNow enter the entries which you want to add together:") elif choice == 2: print("You choose a Subtraction.\nNow enter the entries which you want to subtract:") elif choice == 3: print("You choose a Multiplication.\nNow enter the entries which your want to multiply together:") elif choice == 4: decision = 1 while decision == 1: divident = input("enter Divident:\n\t") divisor = input("Enter Divisor:\n\t") result = int(divident) / int(divisor) reminder = int(divident) % int(divisor) print("\nResult of the division operation:\n\tquotent :", int(result), "\n\treminder :", reminder) print("Do you want to divide another number?\n") decision = input("What you want to do?\n\t1.Menu\n\t2.Division\n\t3.Exit program\n") if decision == 1: calculator() elif decision == 2: decision = decision elif decision == 3: decision = 0 sys.exit("---------Program Exiting after division operation!!!---------") elif choice == 5: print("You choose to calculate the Square Root.\nEnter the number whose Square Root you want to calculate:") number = input("enter the number whose square root is to be calculated:\n") result = print("nth root:", float(number) ** (1 / float(2))) elif choice == 6: print("You choose to calculate Square of a number.\nEnter a number whose Square you want to calculate:") number = input("enter the number whose nth root is to be calculated:\n") result = print("nth root:", float(number) ** (float(2))) elif choice == 7: print("You choose to calculate exponential value.\nEnter base and exponent:") base = (input("Enter base")) exponent = (input("Enter exponent of base")) result = print("The base ", base, "and exponent", exponent, "returned the value", float(base) ** float(exponent)) elif choice == 8: print("You choose to calculate nth root of the number.\nEnter the nht value of root and a number:") elif choice == 9: print( "You choose to calculate average value of the number.\nEnter numbers whose average you want to calculate:") list = [] i = 0 n = int(input("Enter number of elements whose Average you want to calculate:")) while (i < n): print("enter another item of the list") element = float(input()) list.append(element) i += 1 print(list) sum = 0 for item in range(0, len(list)): sum = sum + list[item] print("The average of the numbers is:", sum / n) sys.exit("Program Exiting") elif choice == 10: print("You choose to calculate nth root of the number:") number = input("enter the number whose nth root is to be calculated:\n") nth_root = input("enter the nth root value") result = print("nth root:", float(number) ** (1 / float(nth_root))) else: print("Invalid input!!!") condition = 'f' sys.exit("\nThank you for using BRILLIANT-CALCULATOR APP\nprogram exiting.....") calculator()
a45c34fe97086442b252db0c6f9fd373d5cb6100
potroshit/Data_science_basic_1
/home_work_1/home_work_1_Avdeev.py
644
3.859375
4
# задание 1 arr = [1, 2, 3, 4, 5, 6, 7, 8] for i in arr: if i % 2 == 0: a1 = i a2 = [i] * i print(a1, a2) # задание 2 x = int(input()) y = int(input()) if -1 <= x <= 1 and -1 <= y <= 1: print("принадлежит") else: print("нет") # задание 3 A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] B = [] for i in A: if i % 2 == 0: B.append(i) print(B) # задание 4 name = input() print(f'Привет, {name}!') # задание 5 num = int(input()) print(f"The next number for the number {num} is {num + 1}. The previous number for the number {num} is {num - 1}.")
bacbbfa0ee5a53bbf8d572568d0555d2696e0514
potroshit/Data_science_basic_1
/home_work_1/Клачев_Максим_10И2.py
760
3.609375
4
#a = input('Ввести имя: ') #a = list(a) #a = a[1:-1] #b = input('Ввести класс: ') #a.append(b) #c = input('Ввести фамилию: ') #a+=c #print(a) #1 j = [1, 2, 3, 4, 5, 6, 7] u = [[i]*i for i in j if i % 2 == 0] print(j[i], u) #2 x = int(input()) y = int(input()) if -1<= x <= 1 and -1 <= y <= 1: print('Принадлежит') else: print('Не принадлежит') #3 a = input() a.split() a = list(a) b = [] for i in a: if i%2==0: b.append(i) print(b) #4 n = input() print('Привет', n, '!') #5 a k= int(input()) print('The next number for the number', str(k), 'is', str(k+1)+'.', 'The previous number for the number', str(k), 'is', str(k-1)+'.')
2675e7a9424696fc2a057cca1ff8d093a6139c2f
potroshit/Data_science_basic_1
/class_work1/classwork1_Мезенцева.py
257
3.984375
4
name = [ "k", "s", "e", "n", "i", "a", 16] print(name) #проверка print(name[1:-1]) #задание 1 name.append("10п") print(name) #задание 2 surname = "Mezenceva" surname = list(surname) name = name + surname print(name) #задание 3
398472bec52a37a71af162adce1b17ec71fb388a
MouseOnTheKeys/small_projects
/recursion_palindrom.py
853
3.765625
4
# -*- coding: utf-8 -*- """ Created on Mon May 19:30:57 2020 @author: Nenad Bubalo 1060/19 Domaci zadatak 13: 1. U programskom jeziku Python, napisati funkciju koja rekurzivno proveravada li je dati string palindrom. String je palindrom ako se s desna na levo i s leva na desno isto čita """ # Funkcija koja rekurzivno proverava string def palindrom(x): if len(x) < 2: return True else: if x[0] == x[-1]: return palindrom(x[1:-1]) else: return False if __name__ == "__main__": # Unos trazenog stringa niska = str(input('Uneti zeljeni "string":')) if palindrom(niska) == True: print('Provera "stringa" !!! \nTrazeni string je Palindrom.\n') else: print('Provera "stringa" !!! \nTrazena string NIJE Palindrom.\n')
c6d950474777fdc034c6b0d086478eb3f9de12c1
skynette/30-days-code-challenge-day-1
/day1.py
219
3.546875
4
def twofer(name="you"): # Enter your code here. Read input from STDIN. Print output to STDOUT if name: return("One for {}, one for me.".format(name)) else: return("One for you, one for me.")
95bf80fc821ee37718c25869f217b5da8a3e83f6
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex33.py
195
3.703125
4
""" Leia o tamanho do lado de um quadrado e imprima como resultado sua área. """ tam = float(input("Lado do quadrado: ")) area = tam * tam print("Resultado de sua área = {:.2f}".format(area))
e103f7dc1bdb8ddfeaccba17c2661cf1692aae2c
jocelinoFG017/IntroducaoAoPython
/02-Livros/IntroduçãoAProgramaçãoComPython/CapituloII/Exercicio2.1.py
252
3.875
4
""" Exercicio 2.1 Converta as seguintes expressões matemáticas para que possam ser calculadas usando o interpretador python. 10 + 20 x 30 4² ÷ 30 (9⁴ + 2) x 6-1 """ # Resposta print(10+20*30) print(4**2/30) print((9**4 +2)* 6-1)
24b16e3a48c7688365a31738ad2e12f2f41bc5dc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex03.py
247
4.1875
4
""" .3. Faça um algoritmo utilizando o comando while que mostra uma contagem regres- siva na tela, iniciando em 10 e terminando em 0. Mostrar uma mensagem 'FIM!' após a contagem. """ i = 10 while i >= 0: print(i) i = i - 1 print('FIM')
12b0ad3a799b83888c413ba1499b78b3cbe05170
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex08.py
725
4.15625
4
""" Faça um programa que leia 2 notas de um aluno, verifique se as notas são válidas e exiba na tela a média destas notas. Uma nota válida deve ser, obrigatoriamente, um valor entre 0.0 e 10.0, onde caso a nota possua um valor válido, este fato deve ser informado ao usuário e o programa termina. """ nota1 = float(input("Informe a nota1: ")) nota2 = float(input("Informe a nota2: ")) media = (nota1+nota2)/2 if (nota1 >= 0.0) and (nota1 <= 10.0) and (nota2 >= 0.0) and (nota2 <= 10.0): print(f"Nota1 válida = {nota1}") print(f"Nota2 válida = {nota2}") print("Média = {:.2f}".format(media)) else: print("Uma das notas é inválida") print("Tente outra vez com valores válidos de 0.0 a 10.0")
6e253a61bbec738313c6751af19db42204402edf
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex27.py
287
3.578125
4
""" Leia um valor de área em hectares e apresente-o em metros quadrados m². A fórmula de conversão é: M = H * 10.000, sendo M a área em m² e H a área em hectares. """ area = float(input("Valor da hectares: ")) convert = area * 10.000 print("Em m² fica: {:.4f}".format(convert))
677274c5c2e5ef86e3090e5501182c28e1d7acf3
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex21.py
1,216
4.15625
4
""" Escreva o menu de opções abaixo. Leia a opção do usuário e execute a operação escolhida. Escreva uma mensagem de erro se a opção for inválida. Escolha a opção: 1 - Soma de 2 números. 2 - Diferença entre 2 números. (maior pelo menor). 3 - Produto entre 2 números. 4 - Divisão entre 2 números (o denominador não pode ser zero). opção = """ print(" ---- Informe sua escolha abaixo ---- ") print("1 - Soma ") print("2 - Diferença (M-m)") print("3 - Produto ") print("4 - Divisão ") op = int(input("Escolha de opção: ")) if (op > 0) and (op < 5): n1 = int(input("1º Número: ")) n2 = int(input("2º Número: ")) if op == 1: print("{} + {} = {}".format(n1, n2, n1+n2)) elif op == 2: if n1 > n2: print("{} - {} = {}".format(n1, n2, n1 - n2)) else: print("{} - {} = {}".format(n1, n2, n2 - n1)) elif op == 3: print("{} * {} = {}".format(n1, n2, n1 * n2)) else: # numerador = n1 denominador = n2 if denominador == 0: print("O denominador(n2) não pode ser zero") else: print("{} / {} = {:.2f}".format(n1, n2, n1 / n2)) else: print("Opção inválida.")
6bdaa9fca5f74779af13721837fc1bf30625af36
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_22_ao_41/S05_Ex28.py
1,237
4.15625
4
""" .28. Faça um programa que leia três números inteiros positivos e efetue o cálculo de uma das seguintes médias de acordo com um valor númerico digitado pelo usuário. - (a) Geométrica : raiz³(x * y * z) - (b) Ponderada : (x + (2 * y) + (3 * z)) / 6 - (c) Harmônica : 1 / (( 1 / x) + (1 / y) + (1 / z)) - (d) Aritmética: (x + y + z)/3 """ x = int(input("Informe o valor de X: ")) y = int(input("Informe o valor de Y: ")) z = int(input("Informe o valor de Z: ")) print("A - Geométrica") print("B - Ponderada") print("C - Harmônica") print("D - Aritmética") op = input("Escolha uma média acima: ") geometrica = (x * y * z) ** (1/3) ponderada = (x + (2 * y) + (3 * z)) / 6 harmonica = 1 / (( 1 / x) + (1 / y) + (1 / z)) aritmetica = (x + y + z)/3 if op == "A" or op == "a": print("A - Geométrica escolhida \n") print("Média = {:.2f}".format(geometrica)) elif op == "B" or op == "b": print("B - Ponderada escolhida \n") print("Média = {:.2f}".format(ponderada)) elif op == "C" or op == "c": print("C - Harmônica escolhida \n") print("Média = {:.2f}".format(harmonica)) elif op == "D" or op == "d": print("D - Aritmética escolhida \n") print("Média = {:.2f}".format(aritmetica))
a3922a8d8afbea816fa87015c6fd318ef1eb4efc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_1_ao_21/S04_Ex18.py
307
3.875
4
""" Leia um valor de volume em metros cúbicos m³ e apresente-o convertido em litros. A formula de conversão é: L = 1000*M, sendo L o volume em litros e M o volume em metros cúbicos. """ volume = float(input("Valor Volume(m³): ")) convert = volume*1000 print("Em Litros fica: {:.2f}".format(convert))
031f74a6547ec84a7815735874badd864e191acf
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_22_ao_41/S06_Ex29.py
309
3.609375
4
""" .29. Faça um programa para calcular o valor da série, para 5 termos. - S = 0 + 1/2! + 1/4! + 1/6 +... """ from math import factorial soma = 0 termos = 5 for i in range(1, termos + 1): if i % 2 == 0: # Condição para encontrar valores pares soma = soma + 1/factorial(i) print(soma)
cf90f34f7fac4c7ec15afdb130ccc715ca5b9598
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex06.py
412
3.984375
4
""" Escreva um programa que, dado dois números inteiros, mostre na tela o maior deles, assim como a diferença existente entre ambos. """ n1 = int(input("Informe um número: ")) n2 = int(input("Informe outro número: ")) dif = 0 if n1 > n2: print(f"O maior: {n1}") dif = n1 - n2 print(f"A diferença: : {dif}") else: print(f"O maior: {n2}") dif = n2 - n1 print(f"A diferença: {dif} ")
28473894237479028f7090828351d147a1f439b5
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_22_ao_41/S06_Ex24.py
345
4
4
""" .24. Escreva um programa que leia um número inteiro e calcule a soma de todos os divisores desse numero, com exceção dele próprio. EX: a soma dos divisores do número 66 é 1 + 2 + 3 + 6 + 11 + 22 + 33 = 78 """ n = int(input('Informe um numero: ')) soma = 0 for i in range(1, n): if n % i == 0: soma = soma + i print(soma)
ab98f9c6ff4f60984dba33b33038588020bae6bc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex13.py
645
4.21875
4
""" Faça um algoritmo que calcule a média ponderada das notas de 3 provas. A primeira e a segunda prova tem peso 1 e a terceira tem peso 2. Ao final, mostrar a média do aluno e indicar se o aluno foi aprovado ou reprovado. A nota para aprovação deve ser igual ou superior a 60 pontos. """ nota1 = float(input("nota1: ")) nota2 = float(input("nota2: ")) nota3 = float(input("nota3: ")) divisor = ((nota1 * 1) + (nota2 * 1) + (nota3 * 2)) dividendo = 1 + 1 + 2 media = divisor/dividendo if media >= 6.0: print("Aprovado") print("Media = {:.2f}".format(media)) else: print("Reprovado") print("Media = {:.2f}".format(media))
47d4adf6d6e33bc0578eaf576cb5d81821261d60
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex04.py
354
4.09375
4
""" Faça um programa que leia um número e, caso ele seja positivo, calcule e mostre: - O número digitado ao quadrado - A raiz quadrada do número digitado """ n = float(input("Informe um número: ")) rq = pow(n, 1/2) if n >= 0: print("{} ao quadrado é = {:.2f}: ".format(n, n ** 2)) print("Raiz Quadrada de {} é = {:.2f}: ".format(n, rq))
51f0f4a8aecd6bdff88482d13c6813501689f2b4
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex17.py
602
3.921875
4
""" Faça um programa que calcule e mostre a área de um trapézio. Sabe-se que: - A = ((baseMaior + baseMenor)*altura)/2 Lembre-se a base MAIOR e a base menor devem ser números maiores que zero. """ baseMaior = float(input("BaseMaior: ")) baseMenor = float(input("BaseMenor: ")) altura = float(input("Altura: ")) if baseMaior > 0: if baseMenor > 0: area = ((baseMaior + baseMenor) * altura) / 2 print("A área do trapézio é = {:.2f}".format(area)) else: print("A baseMenor deve ser maior que zero(0)") else: print("A baseMaior deve ser maior que zero(0)")
efef90bd4f05f5d84f10e44e9422e3329e1d3e98
jocelinoFG017/IntroducaoAoPython
/02-Livros/IntroduçãoAProgramaçãoComPython/CapituloV/Exercicio5.2.py
182
4.40625
4
""" # O programa do livro x =1 while x <= 3: print(x) x = x +1 #Modifique o programa para exibir os números de 1 a 100 """ x = 50 while x <= 100: print(x) x = x +1
bb84e63b12ca692da1a1277fa62b6400bfe278a2
jocelinoFG017/IntroducaoAoPython
/02-Livros/IntroduçãoAProgramaçãoComPython/CapituloIV/Exercicio4.3.py
754
3.9375
4
""" Escreva um programa que leia três números e que imprima o maior e o menor """ n1 = int(input()) n2 = int(input()) n3 = int(input()) if (n1>n2) and (n1>n3): # n1 > n2 and n3 if (n2>n3): #n1>n2>n3 print("maior:",n1) print("menor:",n3) if (n3>n2): # n1>n3>n2 print("maior:", n1) print("menor:", n2) if (n2>n1) and (n2 > n3):# n2> n1 and n3 if (n1>n3): #n2>n1>n3 print("maior:",n2) print("menor:",n3) if (n3>n1): # n2>n3>n1 print("maior:", n2) print("menor:", n1) if (n3>n1) and (n3 > n2): # n3 > n1 and n2 if (n1>n2): #n3>n1>n2 print("maior:",n3) print("menor:",n2) if (n2>n1): # n3>n2>n1 print("maior:", n3) print("menor:", n1)
d80274fec662b690fff77f8900d4c6b5c25bb132
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção10-Expressões_Lambdas_e_Funções_Integradas/MinAndMax.py
1,784
4.28125
4
""" Min() e Max() max() -> retorna o maior valor ou o maior de dois ou mais elementos # Exemplos lista = [1, 2, 8, 4, 23, 123] print(max(lista)) tupla = (1, 2, 8, 4, 23, 123) print(max(tupla)) conjunto = {1, 2, 8, 4, 23, 123} print(max(conjunto)) dicionario = {'a': 1, 'b': 2, 'c': 8, 'd': 4, 'e': 23, 'f': 123} print(max(dicionario.values())) # Faça um programa que receba dois valores e retorna o maior valor vlr1 = int(input("VALOR 1: ")) vlr2 = int(input("VALOR 2: ")) print(max(vlr1, vlr2)) print(max(1, 34, 15, 65, 12)) print(max('a', 'abc', 'ab')) print(max('a', 'b','c', 'g')) min() -> Contrário do max() # outros exemplos nomes = ['Arya', 'Joel', 'Dora', 'Tim', 'Ollivander'] print(max(nomes)) print(min(nomes)) print(max(nomes, key=lambda nome: len(nome))) print(min(nomes, key=lambda nome: len(nome))) """ musicas = [ {"titulo": "Thunderstruck", "tocou": 3}, {"titulo": "Dead Skin Mask", "tocou": 2}, {"titulo": "Back in Black", "tocou": 4}, ] print(max(musicas, key=lambda musica: musica['tocou'])) print(min(musicas, key=lambda musica: musica['tocou'])) # DESAFIO! imprimir o titulo da musica mais e menos tocada print('desafio') print(max(musicas, key=lambda musica: musica['tocou'])['titulo']) print(min(musicas, key=lambda musica: musica['tocou'])['titulo']) # DESAFIO! imprimir o titulo da musica mais e menos tocada sem usar o min(), max() e lambda print('desafio 2') max = 0 for musica in musicas: if musica['tocou'] > max: max = musica['tocou'] for musica in musicas: if musica['tocou'] == max: print(musica['titulo']) min = 99999 for musica in musicas: if musica['tocou'] < min: min = musica['tocou'] for musica in musicas: if musica['tocou'] == min: print(musica['titulo'])
a7b48d30123753ea5c87b79acff9e6ef0c1e0fba
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex15.py
239
3.921875
4
""" .15.Faça um programa que leia um número inteiro positivo impar N e imprima todos os números impares de 0 até N em ordem crescente. """ n = int(input('Informe um numero: ')) for i in range(0, n): if i % 2 == 1: print(i)
0d330f98177358d5bf90bae0b6b73d6c73668a4a
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex08.py
333
3.875
4
""" .8. Escreva um programa que leia 10 números e escreva o menor valor lido e o maior valor lido. """ maior = 0 menor = 999999 for i in range(0, 5): num = int(input(f'Informe o valor {i+1}: ')) if num > maior: maior = num if num < menor: menor = num print(f'maior = {maior}') print(f'menor = {menor}')
0f387b4432f970d10a67347d58f4e1aa6983b75d
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex48.py
289
3.765625
4
""" Leia um valor inteiro em segundos, e imprima-o em horas, minutos e segundos. """ x = int(input()) hora = x // 3600 resto = x % 3600 minutos = resto // 60 resto= resto % 60 seg = resto // 1 print("{}h:{}m:{}s".format(hora, minutos, seg)) # print("{} horas : {} min: {} seg".format())
d57e86a7d82801e5c0485ffa94211f0025e08acf
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_1_ao_21/S04_Ex16.py
336
3.890625
4
""" Leia um valor de comprimento em polegadas e apresente-o convertido em centimetros. a formula de conversão é: C = P*2.54, sendo C o comprimento de centimetros e P o comprimento em polegadas. """ comprimento = float(input("Valor Comprimento(pol): ")) convert = comprimento * 2.54 print("Em centimetros fica: {:.2f}".format(convert))
79b58db5b932f19b7f71f09c37c3942554507803
RjPatil27/Python-Codes
/Sock_Merchant.py
840
4.1875
4
''' John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n = 7 socks with colors arr = [1,2,1,2,3,2,1] . There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2 . Write code for this problem. ''' from __future__ import print_function def main(): n = int(input().strip()) c = list(map(int, input().strip().split(' '))) pairs = 0 c.sort() c.append('-1') i = 0 while i < n: if c[i] == c[i + 1]: pairs = pairs + 1 i += 2 else: i += 1 print(pairs) if __name__ == '__main__': main()
bbc6900a6123bd2cfe9c1bb832bee170e7c025d8
RjPatil27/Python-Codes
/PrimeNo.py
419
4.0625
4
# Python Program - Check Prime Number or Not print("Enter 'x' for exit.") num = input("Enter any number: ") if num == 'x': exit(); try: number = int(num) except ValueError: print("Please, enter a number...exiting...") else: for i in range(2, number): if number%i == 0: print(number, "is not a prime number.") break; else: print(number, "is a prime number.") break;
6fc26692c43e63efbce1678792fff2845a3953a5
VIKGO123/Using-Pandas-library-in-python
/csvshow.py
374
3.53125
4
import matplotlib.pyplot as plt import csv x=[] y=[] with open('test.csv','r') as csvfile: plots=csv.reader(csvfile)#reads file for row in plots: #accessing row by row x.append((row[0])) #accessing first element of row y.append((row[1])) #accessing 2nd element of row plt.plot(x,y,label='File') plt.xlabel('x') plt.ylabel('y') plt.show()
05432b48af09dc9b89fded6fb53181df2645ee53
Mat4wrk/Working-with-Dates-and-Times-in-Python-Datacamp
/1.Dates and Calendars/Putting a list of dates in order.py
569
4.375
4
"""Print the first and last dates in dates_scrambled."" # Print the first and last scrambled dates print(dates_scrambled[0]) print(dates_scrambled[-1]) """Sort dates_scrambled using Python's built-in sorted() method, and save the results to dates_ordered.""" """Print the first and last dates in dates_ordered.""" # Print the first and last scrambled dates print(dates_scrambled[0]) print(dates_scrambled[-1]) # Put the dates in order dates_ordered = sorted(dates_scrambled) # Print the first and last ordered dates print(dates_ordered[0]) print(dates_ordered[-1])
df540eae1ad91815ed2a578cc9fbf175b0fcb7e9
vytran0710/CS106.K21.KHCL
/TH/TH1/Bai 3/Bai3_IDS.py
1,117
3.609375
4
from collections import defaultdict class Graph: def __init__(self,vertices): self.V = vertices self.graph = defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) def DLS(self,src,target,maxDepth): if src == target : return True if maxDepth <= 0 : return False for i in self.graph[src]: if(self.DLS(i,target,maxDepth-1)): return True return False def IDDFS(self,src, target, maxDepth): for i in range(maxDepth): if (self.DLS(src, target, i)): return True return False g = Graph (10); g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 3) g.addEdge(1, 4) g.addEdge(2, 5) g.addEdge(2, 6) g.addEdge(3, 7) g.addEdge(4, 8) g.addEdge(5, 9) target = 0; maxDepth = 1; src = 0 if g.IDDFS(src, target, maxDepth) == True: print ("Found target within max depth") else : print ("Not Found target within max depth") #Tham khao: https://www.geeksforgeeks.org/iterative-deepening-searchids-iterative-deepening-depth-first-searchiddfs/
dbd92d328c883c792554926aae4de04d22ccb149
changzheng1993/map
/recommend.py
8,834
3.59375
4
# CS 61A Spring 2015 # Name: Zheng Chang # Login: cs61a-aep """A Yelp-powered Restaurant Recommendation Program""" from abstractions import * from utils import distance, mean, zip, enumerate, sample from visualize import draw_map from data import RESTAURANTS, CATEGORIES, USER_FILES, load_user_file from ucb import main, trace, interact def find_closest(location, centroids): """Return the item in CENTROIDS that is closest to LOCATION. If two centroids are equally close, return the first one. >>> find_closest([3, 4], [[0, 0], [2, 3], [4, 3], [5, 5]]) [2, 3] """ "*** YOUR CODE HERE ***" return min(centroids, key=lambda x: distance(location, x)) def group_by_first(pairs): """Return a list of pairs that relates each unique key in [key, value] pairs to a list of all values that appear paired with that key. Arguments: pairs -- a sequence of pairs >>> example = [ [1, 2], [3, 2], [2, 4], [1, 3], [3, 1], [1, 2] ] >>> group_by_first(example) [[2, 3, 2], [4], [2, 1]] """ # Optional: This implementation is slow because it traverses the list of # pairs one time for each key. Can you improve it? keys = [] for key, _ in pairs: if key not in keys: keys.append(key) return [[y for x, y in pairs if x == key] for key in keys] def group_by_centroid(restaurants, centroids): """Return a list of lists, where each list contains all restaurants nearest to some item in CENTROIDS. Each item in RESTAURANTS should appear once in the result, along with the other restaurants nearest to the same centroid. No empty lists should appear in the result. """ "*** YOUR CODE HERE ***" pairs = [] # list of pair of centroid and restraurant for restaurant in restaurants: location = restaurant_location(restaurant) # find the closest centroid by location of the restaurant centroid = find_closest(location, centroids) if centroid is not None: pairs.append([centroid, restaurant]) return group_by_first(pairs) # group restaurants by centroid def find_centroid(restaurants): """Return the centroid of the locations of RESTAURANTS.""" "*** YOUR CODE HERE ***" # list of locations of restaurants locations = [restaurant_location(restaurant) for restaurant in restaurants ] latitudes = [location[0] for location in locations] # list of latitude of location list longitudes = [location[1] for location in locations] # list of longitude of locations return [mean(latitudes), mean(longitudes) ] # mean of latitude list and longitude list def k_means(restaurants, k, max_updates=100): """Use k-means to group RESTAURANTS by location into K clusters.""" assert len(restaurants) >= k, 'Not enough restaurants to cluster' old_centroids, n = [], 0 # Select initial centroids randomly by choosing K different restaurants centroids = [restaurant_location(r) for r in sample(restaurants, k)] while old_centroids != centroids and n < max_updates: old_centroids = centroids "*** YOUR CODE HERE ***" # group restaurants by the closest centroid centroid_restaurants = group_by_centroid(restaurants, centroids) # get the centroid of the each grouped restaurants centroids = [find_centroid(x) for x in centroid_restaurants] n += 1 return centroids def find_predictor(user, restaurants, feature_fn): """Return a rating predictor (a function from restaurants to ratings), for USER by performing least-squares linear regression using FEATURE_FN on the items in RESTAURANTS. Also, return the R^2 value of this model. Arguments: user -- A user restaurants -- A sequence of restaurants feature_fn -- A function that takes a restaurant and returns a number """ reviews_by_user = {review_restaurant_name(review): review_rating(review) for review in user_reviews(user).values()} xs = [feature_fn(r) for r in restaurants] ys = [reviews_by_user[restaurant_name(r)] for r in restaurants] "*** YOUR CODE HERE ***" mean_x = mean(xs) mean_y = mean(ys) lst = zip(xs, ys) Sxx, Syy, Sxy = 0, 0, 0 for each in lst: x = each[0] y = each[1] Sxx += (x-mean_x)*(x-mean_x) Syy += (y-mean_y)*(y-mean_y) Sxy += (x-mean_x)*(y-mean_y) b = Sxy / Sxx a = mean_y - b*mean_x r_squared = (Sxy*Sxy) /(Sxx*Syy) def predictor(restaurant): return b * feature_fn(restaurant) + a return predictor, r_squared def best_predictor(user, restaurants, feature_fns): """Find the feature within FEATURE_FNS that gives the highest R^2 value for predicting ratings by the user; return a predictor using that feature. Arguments: user -- A user restaurants -- A dictionary from restaurant names to restaurants feature_fns -- A sequence of functions that each takes a restaurant """ reviewed = list(user_reviewed_restaurants(user, restaurants).values()) "*** YOUR CODE HERE ***" # find the predictor of max r_squared max_predictor = max([find_predictor(user, reviewed, feature_fn) for feature_fn in feature_fns], key=lambda x: x[1] ) # return the predictor function return max_predictor[0] def rate_all(user, restaurants, feature_functions): """Return the predicted ratings of RESTAURANTS by USER using the best predictor based a function from FEATURE_FUNCTIONS. Arguments: user -- A user restaurants -- A dictionary from restaurant names to restaurants """ # Use the best predictor for the user, learned from *all* restaurants # (Note: the name RESTAURANTS is bound to a dictionary of all restaurants) predictor = best_predictor(user, RESTAURANTS, feature_functions) "*** YOUR CODE HERE ***" all_ratings = {} reviewed = list(user_reviewed_restaurants(user, restaurants).keys()) rating = 0 for each in restaurants.keys(): # if the restaurant is reviewed, use the rating reviewed by the user if each in reviewed: rating = user_rating(user, each) # use the best predictor to predict the rating for the non-reviewed restaurant else: rating= predictor(restaurants[each]) all_ratings[each] =rating return all_ratings def search(query, restaurants): """Return each restaurant in RESTAURANTS that has QUERY as a category. Arguments: query -- A string restaurants -- A sequence of restaurants """ "*** YOUR CODE HERE ***" return [x for x in restaurants if query in restaurant_categories(x)] def feature_set(): """Return a sequence of feature functions.""" return [restaurant_mean_rating, restaurant_price, restaurant_num_ratings, lambda r: restaurant_location(r)[0], lambda r: restaurant_location(r)[1]] @main def main(*args): import argparse parser = argparse.ArgumentParser( description='Run Recommendations', formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument('-u', '--user', type=str, choices=USER_FILES, default='test_user', metavar='USER', help='user file, e.g.\n' + '{{{}}}'.format(','.join(sample(USER_FILES, 3)))) parser.add_argument('-k', '--k', type=int, help='for k-means') parser.add_argument('-q', '--query', choices=CATEGORIES, metavar='QUERY', help='search for restaurants by category e.g.\n' '{{{}}}'.format(','.join(sample(CATEGORIES, 3)))) parser.add_argument('-p', '--predict', action='store_true', help='predict ratings for all restaurants') args = parser.parse_args() # Select restaurants using a category query if args.query: results = search(args.query, RESTAURANTS.values()) restaurants = {restaurant_name(r): r for r in results} else: restaurants = RESTAURANTS # Load a user assert args.user, 'A --user is required to draw a map' user = load_user_file('{}.dat'.format(args.user)) # Collect ratings if args.predict: ratings = rate_all(user, restaurants, feature_set()) else: restaurants = user_reviewed_restaurants(user, restaurants) ratings = {name: user_rating(user, name) for name in restaurants} # Draw the visualization restaurant_list = list(restaurants.values()) if args.k: centroids = k_means(restaurant_list, min(args.k, len(restaurant_list))) else: centroids = [restaurant_location(r) for r in restaurant_list] draw_map(centroids, restaurant_list, ratings)
619f65ba890f6fa2e891f197581b739f02baae40
Jmwas/Pythagorean-Triangle
/Pythagorean Triangle Checker.py
826
4.46875
4
# A program that allows the user to input the sides of any triangle, and then # return whether the triangle is a Pythagorean Triple or not while True: question = input("Do you want to continue? Y/N: ") if question.upper() != 'Y' and question.upper() != 'N': print("Please type Y or N") elif question.upper() == 'Y': a = input("Please enter the opposite value: ") print("you entered " + a) b = input("Please enter the adjacent value: ") print("you entered " + b) c = input("Please enter the hypotenuse value: ") print("you entered " + c) if int(a) ** 2 + int(b) ** 2 == int(c) ** 2: print("The triangle is a pythagorean triangle") else: print("The triangle is not a pythagorean triangle") else: break
6273ea18be6a76f5d37c690837830f34f7c516e4
cahill377979485/myPy
/正则表达式/命名组.py
1,351
4.46875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Python 2.7的手册中的解释: (?P<name>...) Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named id in the example below can also be referenced as the numbered group 1. For example, if the pattern is (?P<id>[a-zA-Z_]\w*), the group can be referenced by its name in arguments to methods of match objects, such as m.group('id') or m.end('id'), and also by name in the regular expression itself (using (?P=id)) and replacement text given to .sub() (using \g<id>). """ import re # 将匹配的数字乘以 2 def double(matched): value = int(matched.group('value')) return str(value * 2) def double2(matched): value = int(matched.group(1)) return str(value * 2) s = 'A23G4HFD567' # 用命名group的方式 print(re.sub('(?P<value>\\d+)', double, s)) # ?P<value>的意思就是命名一个名字为value的group,匹配规则符合后面的/d+,具体文档看上面的注释 # 用默认的group带数字的方式 print(re.sub('(\\d+)', double2, s))
bf359f264311bd83105764a70207a67360835493
valerie-bernstein/Moon-and-Magnetotail
/x_rotation_matrix.py
300
3.703125
4
import numpy as np def x_rotation_matrix(theta): #rotation by the angle theta (in radians) about the x-axis #returns matrix of shape (3,3) rotation_matrix = np.array([[1, 0, 0], [0, np.cos(theta), np.sin(theta)], [0, -np.sin(theta), np.cos(theta)]]) return rotation_matrix
6b1aa9476e1deb167321b3c37c88e8c517b13e8a
sivaprasad0/AssignmentsDaily
/Aug11/palindrome.py
237
3.859375
4
name=input("enter a palindrme: ") l= len(name) i=0 count=0 for i in range(0,(l+1)//2): if name[i]==name[l-1-i]: pass else: count=count+1 break if count==0: print(name," is palindrome") else: print(name,"is not a palindrome")
0c6fcfa855bc02ebc378e1f5d0c1e5bc5014d5b1
HeloiseKatharine/Bioinformatica
/Atividade 1/3.py
821
4.125
4
''' Crie um programa em python que receba do usuário uma sequência de DNA e retorne a quantidade de possíveis substrings de tamanho 4 (sem repetições). Ex.: Entrada: actgactgggggaaa Após a varredura de toda a sequência achamos as substrings actg, ctga, tgac, gact, ctgg, tggg, gggg, ggga, ggaa, gaaa, logo a saída do programa deve ser: Saída: 10 ''' seq = input('Digite a sequência de DNA: ')#recebe a sequência de DNA tam_seq = len(seq) #tamanho da string seq tam_sub = 4 #declarando o tamanho da substring dic_sub = dict() for i in range(tam_seq - tam_sub + 1): #percorre toda a string sub = seq[i:i+tam_sub] #percorre a sequência de acordo com o tamanho da substring if(sub in dic_sub): dic_sub[sub] += 1 else: dic_sub[sub] = 1 quant = len(dic_sub.keys()) print (quant)
7a3f6276f0a8346e840ab8069e1802370a2abcf5
JimmyBowden/IT780
/C4.py
1,484
3.546875
4
#Jimmy Bowden #IT780 #C4 import csv #-----------------Var #-----------------Functions def readNameCSV(): myList = [] fName = 'People.csv' with open(fName, 'r') as inFile: line = inFile.readline() while line != "": nameList = line.split(",") myList.append(nameList[0]) line = inFile.readline() #print(myList) return myList def readRatingCSV(nameList): myRatingDict = {} myFinalDict = {} for item in nameList: myFinalDict[item] = {} #print(myFinalDict) fName = 'Ratings.csv' with open(fName, 'r') as inFile: line = inFile.readline() count = 0 while line != "": ratingList = line.split(",") val = ratingList[2].strip() myFinalDict[ratingList[1]][ratingList[0]] = float(val) #myFinalDict[ratingList[1]] ({ratingList[0] : float(val)}) #print(ratingList[0], ratingList[2]) #myList.append(nameList[0]) line = inFile.readline() count = count + 1 #print(count) return myFinalDict def orderDictionary(myDict): myDictList = [] for key in myDict: temp = () temp = [myDict[key], key[0]] myDictList.append(temp) sortedDictList = sorted(myDictList, reverse=True) return sortedDictList #-----------------Main dictList = readNameCSV() myDict = readRatingCSV(dictList) #sortedDictList = orderDictionary(myDict) #print(myDict)
0d43af9ffd13bc33c8691eba0cb4a01ec2f2efae
JimmyBowden/IT780
/C8.py
4,778
3.734375
4
#Jimmy Bowden #C8.py from math import sqrt import C4 class myRecommender: def __init__(self): from math import sqrt def manhattan(self, rating1, rating2): """Computes the Manhattan distance. Both rating1 and rating2 are dictionaries """ distance = 0 commonRatings = False for key in rating1: if key in rating2: distance += abs(rating1[key] - rating2[key]) commonRatings = True if commonRatings: return distance else: return -1 #Indicates no ratings in common def minkowski(self, rating1, rating2, r): distance = 0 commonRatings = False for key in rating1: if key in rating2: distance += pow((abs(float(rating1[key]) - float(rating2[key]))), r) commonRatings = True if commonRatings: distance = pow(distance,(1/r)) return distance else: return -1 #Indicates no ratings in common def euclidean(self, rating1, rating2): distance = 0 commonRatings = False for key in rating1: if key in rating2: distance += (rating1[key] - rating2[key]) ** 2 commonRatings = True if commonRatings: distance = sqrt(distance) return distance else: return -1 #Indicates no ratings in common def computeNearestNeighbor(self, username, users, r, Pearson = False): """creates a sorted list of users based on their distance to username""" distances = [] for user in users: if user != username: if Pearson == True: #print(user) distance = self.pearson(users[user], users[username]) else: distance = self.minkowski(users[user], users[username], r) distances.append((distance, user)) # sort based on distance -- closest first distances.sort(reverse=Pearson) return distances def recommend(self, username, users, r, Pearson = False): """Give list of recommendations""" # first find nearest neighbor if Pearson == True: nearest = self.computeNearestNeighbor(username, users, r, True)[0][1] else: nearest = self.computeNearestNeighbor(username, users, r)[0][1] recommendations = [] # now find bands neighbor rated that user didn't neighborRatings = users[nearest] userRatings = users[username] for artist in neighborRatings: if not artist in userRatings: recommendations.append((artist, neighborRatings[artist])) #print(recommendations) # using the fn sorted for variety - sort is more efficient return sorted(recommendations, key=lambda artistTuple: artistTuple[1], reverse = True) def pearson(self, rating1, rating2): sum_xy = 0 sum_x = 0 sum_y = 0 sum_x2 = 0 sum_y2 = 0 n = 0 for key in rating1: if key in rating2: n += 1 x = rating1[key] y = rating2[key] sum_xy += x * y sum_x += x sum_y += y sum_x2 += pow(x, 2) sum_y2 += pow(y, 2) if n == 0: return 0 # now compute denominator denominator = (sqrt(sum_x2 - pow(sum_x, 2) / n) * sqrt(sum_y2 - pow(sum_y, 2) / n)) if denominator == 0: return 0 else: return (sum_xy - (sum_x * sum_y) / n) / denominator def mainRun(self): dictList = C4.readNameCSV() myDict = C4.readRatingCSV(dictList) myInput = input("Enter a name: ").capitalize() manTest1 = computeNearestNeighbor(myInput, myDict, 1) manTest2 = recommend(myInput, myDict, 1) print("Manhattan:") print("Nearest Neighhbors: ", manTest1) print("Recommendations: ", manTest2) print("") euTest1 = computeNearestNeighbor(myInput, myDict, 2) euTest2 = recommend(myInput, myDict, 2) print("Eucledian:") print("Nearest Neighhbors: ", euTest1) print("Recommendations: ", euTest2) print("") pearTest1 = computeNearestNeighbor(myInput, myDict, 1, True) pearTest2 = recommend(myInput, myDict, 1, True) print("Pearson:") print("Nearest Neighhbors: ", pearTest1) print("Recommendations: ", pearTest2) print("") #-----------------------------Main--------------------------------- #mainRun()
068596b0d357250adba6202530cd94d150e71532
dpdi-unifor/juicer
/juicer/scikit_learn/util.py
1,439
4
4
import numpy as np def get_X_train_data(df, features): """ Method to convert some Pandas's columns to the Sklearn input format. :param df: Pandas DataFrame; :param features: a list of columns; :return: a DataFrame's subset as a list of list. """ column_list = [] for feature in features: # Validating OneHotEncode data existence if isinstance(df[feature].iloc[0], list): column_list.append(feature) columns = [col for col in features if col not in column_list] tmp1 = df[columns].to_numpy() if (len(column_list) > 0): tmp2 = df[column_list].sum(axis=1).to_numpy().tolist() output = np.concatenate((tmp1, tmp2), axis=1) elif len(features) == 1: output = tmp1.flatten() else: output = tmp1 return output.tolist() def get_label_data(df, label): """ Method to check and convert a Panda's column as a Python built-in list. :param df: Pandas DataFrame; :param labels: a list of columns; :return: A column as a Python list. """ # Validating multiple columns on label if len(label) > 1: raise ValueError(_('Label must be a single column of dataset')) # Validating OneHotEncode data existence if isinstance(df[label[0]].iloc[0], list): raise ValueError(_('Label must be primitive type data')) y = df[label].to_numpy().tolist() return np.reshape(y, len(y))
ce47e80b7965d38045d0c2a6aac967fca7435217
sophiezeng1215/Algorithms
/Algorithm/Binary Tree Preorder Traversal.py
766
3.9375
4
#Time O(n), space O(n) #append node.val, use a stack to store node.right(only), and then move node to the left, and # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == []: return stack = [] vals = [] node = root while stack or node: if node: vals.append(node.val) stack.append(node.right) node = node.left else: node = stack.pop() return vals
eea37504d1e1776291a20d3517bb601bc31e1970
sophiezeng1215/Algorithms
/Algorithm/Reverse Linked List.py
536
3.859375
4
#Use "prev" and 'temp' = node.next; return prev #Time O(n), space O(1) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ node = head prev = None while node: temp = node.next node.next = prev prev = node node = temp return prev
c78396501abd25be740492c42842b70d60532af0
yugalsherchan1991/python-project
/funcitons.py
2,133
4
4
#%% def evalQuadratic(a, b, c, x): ''' a, b, c: numerical values for the coefficients of a quadratic equation x: numerical value at which to evaluate the quadratic. ''' return (a * x*x) + (b * x) + c evalQuadratic (1,2,3,4) # %% def f(x,y): x = x + y print ("In f(x,y) : x and y: ",x ,y) return x x = 2 y = 2 f(x,y) # %% def a(x): return x + 1 a(a(a(6))) # %% def a(x, y, z): if x: return y else: return z a(3>2,a,b) # %% def b(q, r): return a(q>r, q, r) b(2,3) # %% x = 12 def g(x): x = x + 1 def h(y): return x + y return h(6) g(x) # %% str1 = "exterminate!" #str1.count('e') #str1.upper #str1.upper() str1 = str1.replace('e','*') str1 # %% str2 = "number one - the larch" #str2 = str2.capitalize() #str2.swapcase() str2.find('') #str2.replace("one", "seven") #str2.find('!') # %% str = "basically that is not that hard" str.replace('that', 'which') # %% #Recursive method for iteration def multi(base,exp): if exp <= 0: return 1 else: return base * multi(base, exp-1) multi(-1.99,0) # %% """ Write an iterative function iterPower(base, exp) that calculates the exponential base,exp by simply using successive multiplication. For example, iterPower(base, exp) should compute base,exp by multiplying base times itself exp times. Write such a function below. """ def iterPower(base,exp): result = 1 while exp > 0: result *= base exp -= 1 return result iterPower(4,5) # %% def gcd(a,b): ''' a and b is positive integer value returns: a positive interger the greated common divisor of a and b. ''' testvalue = min(a, b) while a % testvalue != 0 or b % testvalue != 0: testvalue -= 1 return testvalue gcd(9,12) # %% #This is the recursive solution to find the GCD between two integers a and b def gcdRecur(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if b == 0: return a else: return gcdRecur(b,a%b) gcdRecur(9,12) # %%
dfaf1ef03730da91c867e734c4c33efb86310c06
mbernste/bio-sequence-tools
/bio_sequence/rand_seq.py
800
3.796875
4
#!/usr/bin/python import sys import random from sequence import Sequence import fasta NUCLEOTIDES = ['A', 'C', 'T', 'G'] def randNucleotide(): i = random.randint(0, 3) return NUCLEOTIDES[i] def randNucleotideExlude(excludedNucleotides): pickFrom = [nucl for nucl in NUCLEOTIDES if nucl not in excludedNucleotides] i = random.randint(0, len(pickFrom)-1) return pickFrom[i] def genSequence(length): seq = "" for i in range(0, length): seq += randNucleotide() return seq def randomSequence(name, length): seq = genSequence(length) return Sequence(name, seq) def main(): name = sys.argv[1] length = int(sys.argv[2]) seq = randomSequence(name, length) print fasta.formatSequenceToFasta(seq) if __name__ == "__main__": main()
498986037d33c74ded5f9aba97d7448979aca830
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 32/remove nth node.py
545
3.53125
4
# username: shantanugupta1118 # Day 32 of 100 Days # 19. Remove Nth Node From End of List # https://leetcode.com/problems/remove-nth-node-from-end-of-list/ class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: start, curr = [], head while curr: start.append(curr) curr = curr.next for i in range(n-1): start.pop() if len(start) == 1: return start[0].next start[-2].next = start[-1].next return head
52f97e7f4eccf88f0eb1930ee8a8527b6420eaa7
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 8/xor-equality.py
316
3.546875
4
MOD = 10**9+7 def equality(n, x=2): res = 1 x %= MOD if x==0: return 0 while n>0: if n&1 != 0: res = (res*x)%MOD n = n>>1 x = (x*x)%MOD return res def main(): for _ in range(int(input())): n = int(input()) print(equality(n-1)) main()
3e5f2ef814933ff40deb61305404d9c6c1e055b6
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 27/106. Construct Binary Tree from Inorder and Postorder Traversal.py
2,749
3.90625
4
# Github: Shantanugupta1118 # DAY 27 of DAY 100 # 106. Construct Binary Tree from Inorder and Postorder Traversal # https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ # Solution 2-- class TreeNode: def __init__(self, val): self.val = val self.left = None self.right= None class Solution: def search(self, inorder, val, n): i = 0 while i<n: if inorder[i] == val: return i i += 1 return i def buildTree(self, inorder, postorder): def constructTree(inorder): nonlocal postIdx if postIdx<0: return None if inorder==[]: return None val = postorder[postIdx] postIdx -= 1 inorder_Idx = self.search(inorder, val, len(inorder)) left_ele = inorder[:inorder_Idx] right_ele = inorder[inorder_Idx+1:] root = TreeNode(val) root.right = constructTree(right_ele) root.left = constructTree(left_ele) return root postIdx = len(postorder)-1 return constructTree(inorder) inorder = [9, 3, 15, 20, 7] postorder = [9, 15, 7, 20, 3] print(Solution().buildTree(inorder, postorder)) # Solution 2--- """ class Node: def __init__(self, val): self.val = val self.left = None self.right = None class Solution: postIdx = 0 s = [] def search(self, inorder, val, n): i = 0 while i < n: if inorder[i] == val: return i i += 1 return i def buildTree(self, inorder, postorder, start, end, n): if start > end: return val = postorder[self.postIdx] inoIdx = self.search(inorder, val, n) self.postIdx -= 1 self.buildTree(inorder, postorder, inoIdx+1, end, n) self.buildTree(inorder, postorder, start, inoIdx-1, n) self.s.append(val) def constructTree(self, preorder, start, end): if start > end: return None node = Node(preorder[start]) i = start while i <= end: if preorder[i] > node.val: break i += 1 node.left = self.constructTree(preorder, start+1, i-1) node.right = self.constructTree(preorder, i, end) return node def preOrder(self, inorder, postorder): n = len(postorder) self.postIdx = n-1 self.buildTree(inorder, postorder, 0, n-1, n) return self.constructTree(self.s, 0, len(self.s)-1) inorder = [9, 3, 15, 20, 7] postorder = [9, 15, 7, 20, 3] print(Solution().preOrder(inorder, postorder)) """
f7da868b7a723c2ff02967a213fd6bc11cbddc04
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 20/215. Kth Largest Element in an Array.py
607
3.71875
4
# Contribution By: Shantanu Gupta # Github: Shantanugupta1118 # DAY 20 of DAY 100 # 215. Kth Largest Element in an Array - Leetcode # https://leetcode.com/problems/kth-largest-element-in-an-array/ from heapq import * ''' First Approach without inbuilt fnc ''' ''' def k_largest(arr, k): heap = [] for i in arr: heappush(heap, -i) for i in range(k): a = heappop(heap) return a*-1 ''' ''' Second Approach using built in fnc''' def k_largest(arr, k): heapify(arr) return nlargest(k, arr)[-1] arr = list(map(int, input().split())) k = int(input()) print(k_largest(arr, k))
e3ac99530b606e0675d1f5cef956d063808e26b7
alphapk/Python_learnings
/Add_two_nums.py
291
4.09375
4
__author__ = 'Praveen Kumar Anbalagan' #Program to add two numbers #get input from the user num1 = input('Enter the 1st number: ') num2 = input('Enter the 2nd number: ') #add two numbers sum = float(num1)+float(num2) #print the sum print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))
e6779f734aa8b8ca02d9b43933825ca90f5c6bdb
ItamarMu/university-stuff
/Introduction to CS - Python/HW1/s1.py
247
3.78125
4
import time num = eval(input("Please enter a positive integer: ")) m = num cnt = 0 t0 = time.clock() while m>0: if m%10 == 0: cnt+=1 m = m//10 t1 = time.clock() print(num, "has", cnt, "zeros") print("Running time: ", t1-t0, "sec")
8058a5f3841dc1d7147b0cdfbd3b5f43cd95b1ac
ItamarMu/university-stuff
/Introduction to CS - Python/HW4/elp.py
318
3.828125
4
import time def elapsed(expression,number=1): ''' computes elapsed time for executing code number of times (default is 1 time). expression should be a string representing a Python expression. ''' t1=time.clock() for i in range(number): eval(expression) t2=time.clock() return t2-t1
87302ce1cb35e41aa75795d92b9568222deeb3bc
valeeero/Hillel_HW
/Home_work_7/Home_work_7.py
3,667
3.6875
4
# 1 from collections import OrderedDict user_info = OrderedDict({'Имя': 'Валерий', 'Фамилия': 'Лысенко', 'Рост': 184, 'Вес': 81, 'Пол': 'Мужской'}) print(user_info, id(user_info)) first_user_info = list(user_info.items())[0] last_user_info = list(user_info.items())[-1] user_info.move_to_end(key=first_user_info[0]) user_info.move_to_end(key=last_user_info[0], last=False) second_user_info = list(user_info.items())[1] del user_info[second_user_info[0]] user_info['new_key'] = 'new_value' print(user_info, id(user_info)) # 2 student = {"name": "Emma", "class": 9, "marks": 75} info_marks = student.get("marks") print("key_marks: ", info_marks) # 3 p = {"name": "Mike", "salary": 8000} print(p.get("age")) # 4 sample = {"1": ["a", "b"], "2": ["c", "d"]} print(sample.get("2")[1]) # 5 list_1 = ["Украина-Киев", "Россия-Сочи", "Беларусь-Минск", "Япония-Токио", "Германия-Мюнхен"] list_2 = ["Киев", "Токио", "Минск"] countryes = [] cityes = [] for item_country in list_1: country = item_country for item_city in list_2: city = item_city if country.find(city) != -1: countryes.append(country.split("-")[0]) cityes.append(city) else: continue dict_ = dict(zip(countryes, cityes)) print(dict_) # 6 if __name__ == '__main__': value = [] de_value = [] txt = input("Введите текст для шифровки: ") keys = {'а': 574, 'б': 242, 'в': 334, 'г': 394, 'д': 324, 'е': 584, 'ж': 264, 'з': 344, 'и': 284, 'й': 404, 'к': 414, 'л': 484, 'м': 374, 'н': 564, 'о': 594, 'п': 504, 'р': 364, 'с': 384, 'т': 494, 'у': 444, 'ф': 572, 'х': 242, 'ц': 332, 'ч': 392, 'ш': 322, 'щ': 582, 'ь': 262, 'ы': 342, 'э': 282, 'ю': 402, 'я': 412, 'А': 482, 'Б': 372, 'В': 562, 'Г': 592, 'Д': 502, 'Е': 362, 'Ж': 382, 'З': 492, 'И': 442, 'Й': 578, 'К': 248, 'Л': 338, 'М': 398, 'Н': 328, 'О': 588, 'П': 268, 'Р': 348, 'С': 288, 'Т': 408, 'У': 418, 'Ф': 488, 'Х': 378, 'Ц': 568, 'Ч': 598, 'Ш': 508, 'Щ': 368, 'Ь': 388, 'Ы': 498, 'Э': 448, 'Ю': 575, 'Я': 245, 'a': 335, 'b': 395, 'c': 325, 'd': 585, 'e': 265, 'f': 345, 'g': 285, 'h': 405, 'i': 415, 'j': 485, 'k': 375, 'l': 565, 'm': 595, 'n': 505, 'o': 365, 'p': 385, 'q': 495, 'r': 445, 's': 577, 't': 247, 'u': 337, 'v': 397, 'w': 327, 'x': 587, 'y': 267, 'z': 347, 'A': 287, 'B': 407, 'C': 417, 'D': 487, 'E': 377, 'F': 567, 'G': 597, 'H': 507, 'I': 367, 'J': 387, 'K': 497, 'L': 447, 'M': 573, 'N': 243, 'O': 333, 'P': 393, 'Q': 323, 'R': 583, 'S': 263, 'T': 343, 'U': 283, 'V': 403, 'W': 413, 'X': 483, 'Y': 373, 'Z': 563, ' ': 593, '.': 503, ',': 363, '!': 383, '?': 493, '0': 571, '1': 241, '2': 331, '3': 391, '4': 321, '5': 581, '6': 261, '7': 341, '8': 281, '9': 401, '+': 411, '-': 481, '<': 371, '>': 561, '@': 591, '#': 501, '$': 361, '%': 381, '^': 491, '&': 441, '*': 579, '(': 249, ')': 339, '_': 399, '=': 329, '~': 589, '`': 269, '"': 349, ':': 289, ';': 409, '[': 419, ']': 489, '{': 379, '}': 569} txt = list(txt) for item in txt: for key in keys: if key == item: value.append(keys[key]) de_value.append(key) decrypted_value = "".join(de_value) print(value) print(decrypted_value) # 7 dict_vlaue = {i : i ** 3 for i in range(1, 11)} print(dict_vlaue) # 8 text = str(input("Введите текст: ")) my_dict = {i: text.count(i) for i in text} print(my_dict)
908ca14a8df570182f00437af6406410e2340953
CrazyDi/Python2
/Week2/screensaver_my.py
10,990
3.875
4
import math import random import pygame class Vec2d: """ Класс вектора """ def __init__(self, x, y): self._vector = (x, y) def __get__(self, instance, owner): # получение значения вектора return self._vector def __getitem__(self, index): # получение координаты вектора по индексу return self._vector[index] def __str__(self): # переопеределение печати экземпляра класса return str(self._vector) def __add__(self, other): # сумма двух векторов return Vec2d(self[0] + other[0], self[1] + other[1]) def __sub__(self, other): # разность двух векторов return Vec2d(self[0] - other[0], self[1] - other[1]) def __mul__(self, other): # умножение вектора на число и скалярное умножение векторов if isinstance(other, Vec2d): return Vec2d(self[0] * other[0], self[1] * other[1]) else: return Vec2d(self[0] * other, self[1] * other) def __len__(self): # длина вектора return int(math.sqrt(self[0]**2 + self[1]**2)) def int_pair(self): # получение пары (x, y) return self._vector class Polyline: """ Класс замкнутых линий """ def __init__(self, speed=2): self._points = [] self._speeds = [] self._screen = (800, 600) self._speed = speed def __len__(self): return len(self._points) def __get__(self, instance, owner): return self._points def __getitem__(self, index): return self._points[index] speed = property() # свойство количество точек сглаживания @speed.setter def speed(self, value): self._speed = value if value > 0 else 1 @speed.getter def speed(self): return self._speed def add_point(self, point, speed): # добавление в ломаную точки и ее скорости self._points.append(point) self._speeds.append(speed) def delete_point(self, index=None): # удаление точки по индексу if index is None: index = len(self._points) - 1 del self._points[index] del self._speeds[index] def set_points(self): # пересчет координат точек на скорость for i in range(len(self._points)): self._points[i] = self._points[i] + self._speeds[i] * self._speed if self._points[i][0] > self._screen[0] or self._points[i][0] < 0: self._speeds[i] = Vec2d(- self._speeds[i][0], self._speeds[i][1]) if self._points[i][1] > self._screen[1] or self._points[i][1] < 0: self._speeds[i] = Vec2d(self._speeds[i][0], - self._speeds[i][1]) def draw_points(self, display, style="points", width=3, color=(255, 255, 255)): # рисование точек и линий if style == "line": for i in range(-1, len(self._points) - 1): pygame.draw.line(display, color, (int(self._points[i][0]), int(self._points[i][1])), (int(self._points[i + 1][0]), int(self._points[i + 1][1])), width) elif style == "points": for i in self._points: pygame.draw.circle(display, color, (int(i[0]), int(i[1])), width) class Knot(Polyline): """ Класс кривой """ def __init__(self, count): super().__init__() self._count = count self._points_knot = [] count = property() # свойство количество точек сглаживания @count.setter def count(self, value): self._count = value if value > 0 else 1 @count.getter def count(self): return self._count # сглаживание кривой def _get_point(self, points, alpha, deg=None): if deg is None: deg = len(points) - 1 if deg == 0: return points[0] return points[deg] * alpha + self._get_point(points, alpha, deg - 1) * (1 - alpha) def _get_points(self, base_points): alpha = 1 / self._count res = [] for i in range(self._count): res.append(self._get_point(base_points, i * alpha)) return res def _get_knot(self): self._points_knot = [] if len(self) >= 3: for i in range(-2, len(self) - 2): ptn = [(self[i] + self[i + 1]) * 0.5, self[i + 1], (self[i + 1] + self[i + 2]) * 0.5] self._points_knot.extend(self._get_points(ptn)) def add_point(self, point, speed): # добавление в ломаную точки и ее скорости (переопределенная) super().add_point(point, speed) self._get_knot() def delete_point(self, index=None): # удаление точки по индексу (переопределенная) super().delete_point(index) self._get_knot() def set_points(self): # пересчет координат точек на скорость (переопределенная) super().set_points() self._get_knot() # рисование точек и линий (переопределенная) def draw_points(self, display, style="points", width=3, color=(255, 255, 255)): # self._get_knot() if style == "line": for i in range(-1, len(self._points_knot) - 1): pygame.draw.line(display, color, (int(self._points_knot[i][0]), int(self._points_knot[i][1])), (int(self._points_knot[i + 1][0]), int(self._points_knot[i + 1][1])), width) elif style == "points": for i in self: pygame.draw.circle(display, color, (int(i[0]), int(i[1])), width) # Отрисовка справки def draw_help(): gameDisplay.fill((50, 50, 50)) font1 = pygame.font.SysFont("courier", 24) font2 = pygame.font.SysFont("serif", 24) data = [["F1", "Show Help"], ["R", "Restart"], ["P", "Pause/Play"], ["Num+", "More points"], ["Num-", "Less points"], ["Backspace", "Delete last point"], ["Num*", "More speed"], ["Num/", "Less speed"], ["", ""], [str(poly.count), "Current points"], [str(poly.speed), "Current speed"]] pygame.draw.lines(gameDisplay, (255, 50, 50, 255), True, [ (0, 0), (800, 0), (800, 600), (0, 600)], 5) for i, text in enumerate(data): gameDisplay.blit(font1.render( text[0], True, (128, 128, 255)), (100, 100 + 30 * i)) gameDisplay.blit(font2.render( text[1], True, (128, 128, 255)), (200, 100 + 30 * i)) # Основная программа if __name__ == "__main__": # инициализация окна pygame.init() gameDisplay = pygame.display.set_mode((800, 600)) pygame.display.set_caption("MyScreenSaver") working = True # маркер работы poly = Knot(35) show_help = False # маркер отображения помощи pause = True # маркер паузы hue = 0 # оттенок color_line = pygame.Color(0) # цвет # цикл работы программы while working: # отлавливаем событие с клавиатуры и мышки for event in pygame.event.get(): # если нажат крестик закрытия окна, меняем маркер работы программы if event.type == pygame.QUIT: working = False # отлавливаем событие с клавиатуры if event.type == pygame.KEYDOWN: # Esc - меняем маркер работы программы if event.key == pygame.K_ESCAPE: working = False # R - обнуляем данные if event.key == pygame.K_r: poly = Knot(35) # P - меняем маркер движения if event.key == pygame.K_p: pause = not pause # Num+ - увеличиваем количество точек сглаживания if event.key == pygame.K_KP_PLUS: poly.count += 1 # F1 - открытие/закрытие окна помощи if event.key == pygame.K_F1: show_help = not show_help # Num- - уменьшаем количество точек сглаживания if event.key == pygame.K_KP_MINUS: poly.count -= 1 # Backspace - удаление последней добавленной точки if event.key == pygame.K_BACKSPACE: poly.delete_point() # Num* - увеличиваем скорость движения кривой if event.key == pygame.K_KP_MULTIPLY: poly.speed += 1 # Num / - уменьшаем скорость движения кривой if event.key == pygame.K_KP_DIVIDE: poly.speed -= 1 # отлавливаем событие с мыши - клик любой кнопкой - добавляем точку в # полилайн и генерируем скорость для этой точки if event.type == pygame.MOUSEBUTTONDOWN: point_event = Vec2d(event.pos[0], event.pos[1]) speed_event = Vec2d(random.random(), random.random()) poly.add_point(point_event, speed_event) # отрисовка окна gameDisplay.fill((0, 0, 0)) # заполняем окно черным цветом hue = (hue + 1) % 360 # меняем оттенок линии color_line.hsla = (hue, 100, 50, 100) # формируем новый цвет с учетом нового оттенка poly.draw_points(gameDisplay) # рисуем точки poly.draw_points(gameDisplay, "line", 3, color_line) # рисуем линию # draw_points(get_knot(points, steps), "line", 3, color) # если стоит маркер движения - сдвигаем точки на скорость if not pause: poly.set_points() # если стоит маркер окна помощи - показываем окно помощи if show_help: draw_help() pygame.display.flip() # перерисовка окна # выход из программы pygame.display.quit() pygame.quit() exit(0)
b98ec4d5a55d11ad62cbf8fc725774719669a7e7
junbaih/OthelloGame
/model.py
7,831
3.703125
4
## global constant , with value of 1 and -1 easy to switch around EMPTY = 0 BLACK = 1 WHITE = -1 ##exception class GameOverError(Exception): pass class InvalidMoveError(Exception): pass #### Class part with methods make a move if it is valid and flip accessble discs #### get the number of certain color disc and so on class game_board: def __init__(self,row,col,first_turn,start_disc,win_rule): self.board = self._start_board(row,col,start_disc) self.num_of_row = len(self.board) self.num_of_col = len(self.board[1]) self.turn = first_turn self.rule = win_rule def count_disc(self,color:'BLACK/WHITE')->int: '''count the disc with specified color''' self.count = 0 for row in self.board: self.count+=row.count(color) return self.count def board_row(self)->int: '''return the dimension of the game board''' return self.num_of_row def board_column(self)->int: '''as the same as board_row method''' return self.num_of_col def turn_swift(self)->None: '''swift a turn''' self.turn = -self.turn def current_turn(self)->int: '''show current turn ''' return self.turn def move_and_flip(self,row,col)->None: '''drop a disc and flip all plausible discs''' if self.check_game_over(): raise GameOverError if (row,col) in self._get_valid_list(self.turn): self._flip(row,col,0,1,self.turn) self._flip(row,col,0,-1,self.turn) self._flip(row,col,1,1,self.turn) self._flip(row,col,1,-1,self.turn) self._flip(row,col,-1,0,self.turn) self._flip(row,col,1,0,self.turn) self._flip(row,col,-1,1,self.turn) self._flip(row,col,-1,-1,self.turn) self.board[row-1][col-1] = self.turn else: raise InvalidMoveError def check_game_over(self)->bool: '''return if a game is over''' return self._get_valid_list(WHITE)==[] \ and self._get_valid_list(BLACK)==[] def no_move_swift(self)->None: '''if there is not valid move for another players in next turn, no turn swift is made, otherwise, turn changes into another player ''' if self._get_valid_list(-self.turn)==[]: self.turn = self.turn else: self.turn_swift() def winner(self)->int: '''print the winner for the game''' if self.check_game_over(): if self.rule == '>': if self.count_disc(BLACK)>self.count_disc(WHITE): return BLACK elif self.count_disc(BLACK)<self.count_disc(WHITE): return WHITE elif self.count_disc(BLACK)==self.count_disc(WHITE): return elif self.rule == '<': if self.count_disc(BLACK)>self.count_disc(WHITE): return WHITE elif self.count_disc(BLACK)<self.count_disc(WHITE): return BLACK elif self.count_disc(BLACK)==self.count_disc(WHITE): return ## private functions, including create initial board, which will be an ## attribute when creating the class; check if a disc call be flip ## check if a move is valid; create a valid move list and check if a ## place is on board def _create_empty_board(self,num_of_rows:int,num_of_cols:int)->None: ''' create a board with all empty cells ''' self.board = [] for row in range(num_of_rows): self.board.append([]) for column in range(num_of_cols): self.board[row].append(0) def _start_board(self,num_of_rows:int, num_of_cols:int,start_disc:'BLACK or WHITE')->'board': ''' create a initial board, with specified color disc in top left and bottom right ''' self._create_empty_board(num_of_rows,num_of_cols) top_left_center = bottom_right_center = start_disc top_right_center = bottom_left_center = -start_disc self.board[int(num_of_rows/2-1)][int(num_of_cols/2-1)] = top_left_center self.board[int(num_of_rows/2)][int(num_of_cols/2)] = bottom_right_center self.board[int(num_of_rows/2-1)][int(num_of_cols/2)] = top_right_center self.board[int(num_of_rows/2)][int(num_of_cols/2-1)] = bottom_left_center return self.board def _flip(self,row,col,rowdelta,coldelta,turn)->None: ''' check if discs in one giving direction can be flipped ''' if self._valid_check(row,col,rowdelta,coldelta,turn): next_row =row+rowdelta next_col = col+coldelta while self._check_on_board(next_row,next_col)== True: if self.board[next_row-1][next_col-1] !=turn: self.board[next_row-1][next_col-1] = turn next_row+=rowdelta next_col+=coldelta else: break else: pass def _get_valid_list(self,turn)->list: ''' get a valid move list by scan the board and check each cell ''' valid_list = [] for row in range(len(self.board)): for col in range(len(self.board[1])): if self._check_valid_move(row+1,col+1,turn): valid_list.append((row+1,col+1)) return valid_list def _check_valid_move(self,row,col,turn)->bool: ''' check a certain cell in all 8 directions to see if it could be a valid move ''' if self._valid_check(row,col,0,1,turn) \ or self._valid_check(row,col,0,-1,turn) \ or self._valid_check(row,col,1,0,turn) \ or self._valid_check(row,col,-1,0,turn) \ or self._valid_check(row,col,1,-1,turn) \ or self._valid_check(row,col,1,1,turn) \ or self._valid_check(row,col,-1,-1,turn) \ or self._valid_check(row,col,0-1,1,turn): return True return False def _valid_check(self,row:int,col:int,rowdelta:int,coldelta:int,turn)->bool: '''check a cell in one direction to see if it is movable in that direction ''' if not self._check_on_board(row,col): raise InvalidMoveError drow_position = self.board[row-1][col-1] cell_count = 0 if drow_position != 0: return False while True: row+=rowdelta col+=coldelta cell_count+=1 if self._check_on_board(row,col) and self.board[row-1][col-1]==-turn: pass if self._check_on_board(row,col) and self.board[row-1][col-1]==0: return False if self._check_on_board(row,col) and self.board[row-1][col-1]== turn: if cell_count == 1: return False return True if not self._check_on_board(row,col): break def _check_on_board(self,row,col)->bool: '''check if the specifie position is on board''' return 0<row<=len(self.board) and 0<col<=len(self.board[1])
9174bbd6390284af1d29bca9e5b6d783367b5302
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__011.py
332
3.71875
4
# pintando parede larg = float(input('Qual é a largura da parede que você deseja pintar?')) alt = float(input('E qual é a altura desta mesma parede?')) area = float((larg*alt)) tinta = float((area/2)) print('Você precisará pintar {} m² de área de parede\nE para isso precisará usar {} L de tinta'.format(area, tinta))
c3912498bdd7197cd60c10943fefc448909f27f5
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__037.py
628
4.125
4
# conversor de bases numéricas n = int(input('Digite um número inteiro: ')) print('''Escolha umda das bases para a conversão:' [ 1 ] converter para BINÁRIO [ 2 ] converter para OCTAL [ 3 ] converter para HEXADECIMAL''') opção = int(input('Sua opção: ')) if opção == 1: print('{} convertido para BINÁRIO é igual a {}'.format(n, bin(n)[2:])) elif opção == 2: print('{} convertido para OCTAL é igual a {}'.format(n, oct(n)[2:])) elif opção == 3: print('{} convertido para HEXADECIMAL é igual a {}'.format(n, hex(n)[2:])) else: print('Você precisa digitar uma das opções acima!')
b27eb11a268eb165af970993edad89d4f4c7694a
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__059.py
1,526
4.15625
4
# criando um menu de opções from time import sleep n1 = float(input('Digite um número qualquer: ')) n2 = float(input('Digite mais um número: ')) print(' [ 1 ] somar\n' ' [ 2 ] multiplicar\n' ' [ 3 ] maior\n' ' [ 4 ] novos números\n' ' [ 5 ] sair do programa') opção = int(input('>>>>> Qual é a sua opção? ')) while opção !=5: if opção > 5 or opção == 0: print('Opção inválida. Tente novamente!') if opção == 1: soma = n1+n2 print('A soma de {:.2f} com {:.2f} resulta em {:.2f}.'.format(n1, n2, soma)) elif opção == 2: multi = n1*n2 print('A multiplicação de {:.2f} com {:.2f} resulta em {:.2f}.'.format(n1, n2, multi)) elif opção == 3: if n1 > n2: maior = n1 else: maior = n2 print('O maior número entre {:.2f} e {:.2f} é {:.2f}.'.format(n1, n2, maior)) elif opção == 4: print('Informe os números novamente:') n1 = float(input('Primeiro valor: ')) n2 = float(input('Segundo valor: ')) sleep(1) print('-==-'*8) print(' [ 1 ] somar\n' ' [ 2 ] multiplicar\n' ' [ 3 ] maior\n' ' [ 4 ] novos números\n' ' [ 5 ] sair do programa') opção = int(input('>>>>> Qual é a sua opção? ')) if opção == 5: print('Finalizando...') sleep(1) print('-==-'*8) print('Fim do programa. Volte sempre!')
4e42cfc44d1e1a84c11fb66682b1d7760e262b25
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__018.py
357
4.03125
4
# seno, cosseno e tangente import math a = float(input('Digite o ângulo que você deseja:')) print('O SENO do ângulo de {} vale {:.2f}'.format(a, math.sin(math.radians(a)))) print('O COSSENO do ângulo de {} vale {:.2f}'.format(a, math.cos(math.radians(a)))) print('A TANGENTE do ângulo de {} vale {:.2f}'.format(a, math.tan(math.radians(a))))
044b28a4f77671479e15a7620c9b0b6feb37ece6
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__085.py
487
3.671875
4
lista = list() pares = list() impares = list() for c in range(1, 8): n = int(input(f'Digite o {c}º valor: ')) lista.append(n) print('--' * 50) print(f'Você digitou os valores: {lista}') for v in range(0, len(lista)): if lista[v] % 2 == 0: pares.append(lista[v]) else: impares.append(lista[v]) print(f'Os valores pares digitados foram: {sorted(pares)}') print(f'Os valores ímpares digitados foram: {sorted(impares)}') print('--' * 50)
54d1c9b14fecd247df7d3230fa4a3125e40e3ab0
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__005.py
191
4.09375
4
# sucessor e antecessor num = int(input('Digite um número qualquer:')) n1 = num-1 n2 = num+1 print('Analisando seu número, o antecessor é {} e o sucessor é {}'.format(n1, n2))
6b2d874c613182e7e45222686b4824aa40e2521f
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__031.py
267
3.578125
4
# custo da viagem d = float(input('Qual é a distância da sua viagem em km? ')) p1 = d*0.5 p2 = d*0.45 if d<= 200: print('O preço da sua passagem será de R${:.2f}'. format(p1)) else: print('O preço da sua passagem será de R${:.2f}'.format(p2))
2cdc4ee9ce0f59cf33147284a9d7b165a599284d
EstephanoBartenski/Aprendendo_Python
/Teoria/teoria__Classes_4.py
1,093
4.0625
4
# atributos class Pessoa: num_de_pessoas = 0 @classmethod def num_de_pessoas_(cls): return cls.num_de_pessoas @classmethod def add_pessoa(cls): cls.num_de_pessoas += 1 def __init__(self, nome): self.nome = nome Pessoa.add_pessoa() p1 = Pessoa('João') p2 = Pessoa('Zuleide') p3 = Pessoa('Orimberto') # print(Pessoa.num_de_pessoas) print(Pessoa.num_de_pessoas_()) # Pessoa.num_de_pessoas = 55 # print(Pessoa.num_de_pessoas) # print(p1.num_de_pessoas) # print(p1.num_de_pessoas) # aquele num de pessoas que eu deixei lá em cima, fora/antes no init # vale pra galera toda!! não vai mudar de pessoa pra pessoa # então posso chamar aquilo pra qualquer pessoa # e mudar a qualquer tempo, fazendo a classe+aquilo recebe tal # aí posso fazer contagem hehe # mas a ideia de constante é a mais útil mesmo, tipo gravidade sl # algo que é sempre -9.8 m/s² # class methods # a ideia é que fazem referência à classe inteira (método da classe), # e não algum outor método dessa classe
0eed0a6a10c8b1a522b927c0afd10d5dcf34a5b1
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__047.py
387
4.0625
4
# contando pares for contagem in range(2,52,2): print(contagem, end=' ') # outra forma de fazer for contagem in range(1,51): if (contagem%2) == 0: print(contagem, end=' ') # neste segundo método, a interação é feita de 1 em 1, mesmo que o resultado não seja mostrado. No primeiro método, só # foi feito metade do serviço (isso ocupa menos processador)
2517c1c7c6ada14bb1bdef025828624a676573cd
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__051.py
527
3.796875
4
# progressão artimética print('='*30) print(' 10 TERMOS DE UMA PA ') print('='*30) a1 = int(input('Digite o primeiro termo: ')) r = int(input('Razão: ')) for c in range(0, 10): c = a1 + c * r print(c, end=' ') print('->', end=' ') print('ACABOU') # refazendo # an = a1 + (n - 1) * r a1 = int(input('Primeiro termo: ')) r = int(input('Razão da PA: ')) n = 0 for n in range(1, 11): an = a1 + (n - 1) * r n += 1 print('{} --> '.format(an), end='') print('FIM', end='')
5dd2a28ae62cf46d8a3d296ddbbc8df758527596
EstephanoBartenski/Aprendendo_Python
/Teoria/teoria__lista_5.py
801
3.875
4
'''pessoal = [['Joana', 33], ['Marcelo', 45], ['Otávio', 50], ['Jorge', 12], ['Bárbara', 14]] print(pessoal[1]) print(pessoal[1][1]) print(pessoal[1][0]) print() turma = list() turma.append(pessoal[:]) print(turma) print(turma[0]) print(turma[0][4]) print(turma[0][4][1])''''' galera = list() dado = list() for c in range(0, 3): dado.append(str(input('Nome: '))) dado.append(int(input('Idade: '))) galera.append(dado[:]) dado.clear() print(galera) print() totmaior = totmenor = 0 for p in galera: if p[1] >= 18: print(f'{p[0]} é maior de idade.') totmaior += 1 else: print(f'{p[0]} é menor de idade.') totmenor +=1 print(f'Há {totmaior} pessoas maiores de idade e {totmenor} pessoas menores de idade.')
73a76de770942df37edb4958c3bb3267b4335dd6
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__060.py
423
4.09375
4
# calculando um fatorial num = int(input('Digite um número para calcular seu fatorial: ')) c = num f = 1 # pra começar uma multiplicação limpa, assim como usamos 0 pra começar uma soma limpa print('Calculando {}! = '.format(num), end='') while c > 0: print('{}'.format(c), end='') print(' x ' if c > 1 else ' = ', end='') f *= c c -= 1 print(f) # lembrando que no math tem um factorial
7473b81569f4aa4ff56d53372a670e3816876131
natrajitpoint/python
/classmethod.py
590
3.78125
4
class employee: def setdata(self,eno, ename, esal): self.eno = eno self.ename = ename self.esal = esal def getdata(self): print("\n*** Employee Info ***\nEmployee Id : {}\n\ Employee Name : {}\nEmployee Salary : {}"\ .format(self.eno,self.ename,self.esal)) #main e1 = employee() e2 = employee() e1.setdata(1001, 'Srinivas',35000) x = int(input("Enter employee Id : ")) y = input("Enter employee name : ") z = float(input("Enter employee salary : ")) e2.setdata(x,y,z) e1.getdata() e2.getdata() e3 = employee() e3.getdata()#error
3cdb31a1ce22e86265fd5ad8e5e4b4c9fe08e6ea
natrajitpoint/python
/insertexecute.py
804
3.5
4
import pymysql # Open database connection conn = pymysql.connect(host="localhost", user="root", passwd="itpoint", db="DB5to6") # Create a Cursor object to execute queries. cur = conn.cursor() # Insert records into Books table insertquery = "Insert into books values(%s,%s,%s,%s)" #Accept Data from user bid = int(input("Enter Book Id : ")) name = input("Enter Book Name : ") author = input("Enter Author Name : ") price = float(input("Enter Book Price : ")) try: # Execute Query ret = cur.execute(insertquery, [bid, name, author,price]) conn.commit() print("%s rows inserted successfully...." %ret) except Exception as ex: conn.rollback() print(ex) finally: # disconnect from server conn.close()
b9908917407ec89e662b804ced360417491bcc98
mmalek06/amazon-interview
/AmazonInterviewPy/sum_of_two.py
275
4
4
find_sum_of_two([2, 1, 8, 4, 7, 3],3) def find_sum_of_two(A, val): pairs = dict() for cnt in range(0, len(A)): if (A[cnt] in pairs): return True the_other_number = val - A[cnt] pairs[the_other_number] = A[cnt] return False
e8d204ed131a1baa1f694ece35d9984700901ed2
averni/Simplify_with_Topology
/trianglecalculator.py
1,111
3.828125
4
#! /usr/bin/env python # encoding: utf-8 __author__ = 'asimmons' class TriangleCalculator(object): """ TriangleCalculator() - Calculates the area of a triangle using the cross-product. """ def __init__(self, point, index): # Save instance variables self.point = point self.ringIndex = index self.prevTriangle = None self.nextTriangle = None # enables the instantiation of 'TriangleCalculator' to be compared # by the calcArea(). def __cmp__(self, other): return cmp(self.calcArea(), other.calcArea()) ## calculate the effective area of a triangle given ## its vertices -- using the cross product def calcArea(self): # Add validation if not self.prevTriangle or not self.nextTriangle: print "ERROR:" p1 = self.point p2 = self.prevTriangle.point p3 = self.nextTriangle.point area = abs(p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1])) / 2.0 #print "area = " + str(area) + ", point = " + str(self.point) return area
790cdcb6e2eb5f734c6ccc27bc58596685a1a2a2
vijay092/Optimal-Control-RL
/minecraftControl/uquat.py
2,517
3.59375
4
""" A collection of operations on unit quaternions """ import numpy as np def normalize(q): norm = np.sqrt(np.dot(q,q)) return q/norm def vec_to_uquat(v): dt = np.array(v).dtype if dt == np.int or dt == np.float: dt = float else: dt = object input_array = np.zeros(4,dtype=dt) input_array[1:] = v return input_array def cast_as_uquat(q): if len(q) == 4: return q elif len(q) == 3: return vec_to_uquat(q) def mult(q,p): qQuat = cast_as_uquat(q) pQuat = cast_as_uquat(p) if qQuat.dtype == np.object or pQuat.dtype == np.object: dt = object else: dt = float rQuat = np.zeros(4,dtype=dt) r1 = qQuat[0] v1 = qQuat[1:] r2 = pQuat[0] v2 = pQuat[1:] rQuat[0] = r1*r2 - np.dot(v1,v2) rQuat[1:] = r1*v2 + r2*v1 + np.cross(v1,v2) return rQuat def inv(q): """ This simply conjugates the quaternion. In contrast with a standard quaterionion, you would also need to normalize. """ if q.dtype == np.object: dt = object else: dt = float qinv = np.zeros(4,dtype=dt) # Here is the main difference between a unit quaternion # and a standard quaternion. qinv[0] = q[0] qinv[1:] = -q[1:] return qinv def rot(q,v): """ This performs a rotation with a unit quaternion """ qinv = inv(q) res = mult(q,mult(v,qinv)) return np.array(res[1:]) def expq(v): """ This computes the quaternion exponentiation of a vector, v Input v: a vector in R^3 Output q: a unit quaternion corresponding to e^((0,v)) """ norm = np.sqrt(np.dot(v,v)) qr = np.cos(norm) qv = v * np.sinc(norm/np.pi) # Want v * sin(norm) / norm. As is, you'll get problems in the limit # of norm near 0. Thus, use the sinc function, which is # sinc(x) = sin(pi*x) / (pi*x) q = np.array([qr,qv[0],qv[1],qv[2]]) return q def cross_mat(v): """ Extract the skew symmetric matrix corresponding to a 3-vector """ dt = v.dtype M = np.zeros((3,3),dtype=dt) M[0,1] = -v[2] M[0,2] = v[1] M[1,2] = -v[0] M = M - M.T return M def mat(q): """ return the rotation matrix corresponding to unit quaternion """ dt = q.dtype r = q[0] v = q[1:] M = cross_mat(v) Msq = np.dot(M,M) R = r*r * np.eye(3) + np.outer(v,v) + 2 * r * M + Msq return R
5acdea7afe5a64f6aee54842b3800d8966f13686
gauravaror/programming
/reOrderList.py
1,274
3.734375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ fp = head headcopy = head sp = head while fp: #print(fp.val, sp.val) if fp.next: fp = fp.next.next sp = sp.next else: fp = fp.next # Reverse from slow pointer #print(sp.val) #return sp prev = None while sp: #print(sp.val) save = sp.next sp.next = prev prev = sp #print(save, sp.val) if save: sp = save else: break #sp = prev #print(sp.val, sp.next.val, sp.next.next) while headcopy and sp: save = headcopy.next headcopy.next = sp spsave = sp.next sp.next = save headcopy = save sp = spsave if headcopy: headcopy.next = None #print("jjhgg ",headcopy, sp) return head
089443a83c95a5caf8f211a18559963edbef9b8b
gauravaror/programming
/linked_list_in_binary_tree.py
1,956
3.859375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def tree_height(self, root): if root == None: return 0 left_height = self.tree_height(root.left) right_height = self.tree_height(root.right) return max(left_height, right_height) + 1 def list_leng(self, he): if he == None: return 0 return 1 + self.list_leng(he.next) def isSubPath(self, head: ListNode, root: TreeNode) -> bool: if self.list_leng(head) > self.tree_height(root): return False return self.isSubPath1(head, root) def justMatchPath(self, head: ListNode, root: TreeNode) -> bool: if head == None: return True if root == None: return False if head.val == root.val: if self.justMatchPath(head.next, root.left): return True if self.justMatchPath(head.next, root.right): return True return False def isSubPath1(self, head: ListNode, root: TreeNode) -> bool: if head == None: return True if root == None: return False if root.val == head.val: left_mpath = self.justMatchPath(head.next, root.left) if left_mpath: return True right_mpath = self.justMatchPath(head.next, root.right) if right_mpath: return True left_path = self.isSubPath1(head, root.left) if left_path: return True right_path = self.isSubPath1(head, root.right) if right_path: return True return left_path or right_path
4268f60fc2cfdff90d1da67a16d88544fbe7693f
gauravaror/programming
/myCalender1.py
1,340
3.65625
4
class MyCalendar: def __init__(self): self.starts = [] self.ends = [] def bs(self, array, target): start = 0 end = len(array) while start < end: mid = start + (end-start)//2 if array[mid] > target: end = mid else: start = mid + 1 return start def book(self, start: int, end: int) -> bool: if len(self.starts) == 0: self.starts.append(start) self.ends.append(end) return True starting_index = self.bs(self.starts, start) ending_index = self.bs(self.ends, end) new_meeting_index = self.bs(self.ends, start) #print(self.starts, self.ends, starting_index, ending_index, new_meeting_index) if new_meeting_index != starting_index: return False if starting_index != ending_index: return False if starting_index < len(self.starts) and self.starts[starting_index] > start and self.starts[ending_index] < end: return False self.starts.insert(starting_index, start) self.ends.insert(ending_index, end) return True # Your MyCalendar object will be instantiated and called as such: # obj = MyCalendar() # param_1 = obj.book(start,end)
1c741e95677effe1805363a8ac8a4b7ebce2c91b
gauravaror/programming
/binary-tree-level-order-traversal_2.py
882
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: answer = [] stack = [] current_level = 0 if not root: return [] stack.append((root,1)) while len(stack) > 0: #print(stack) elem = stack.pop(0) level = elem[1] node = elem[0] if node.left: stack.append((node.left, level+1)) if node.right: stack.append((node.right, level+1)) if current_level != level: answer.append([]) current_level = level answer[-1].append(node.val) answer.reverse() return answer
916ca7c13f04b1d9f401941a6cdba3a21e20f500
gauravaror/programming
/lrucache_double_linked_list_solution.py
2,048
3.5625
4
class Node: def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.hh = {} self.head = Node(0,0) self.tail = Node(0,0) self.capacity = capacity self.limit = 0 def arrange_access(self, key: int) -> int: accessednode = self.hh[key] if self.tail != accessednode: prevn = accessednode.prev nextn = accessednode.next if prevn: prevn.next = nextn if nextn: nextn.prev = prevn if accessednode == self.head and nextn != None: self.head = nextn self.tail.next = accessednode accessednode.prev = self.tail self.tail = accessednode return accessednode.val def get(self, key: int) -> int: #print("get", key, self.head, self.tail, self.hh) if key in self.hh: return self.arrange_access(key) else: return -1 def put(self, key: int, value: int) -> None: #print("put", key,value, self.head, self.tail, self.hh) if key in self.hh: self.hh[key].val = value self.arrange_access(key) else: while self.limit >= self.capacity: remove_n = self.head del self.hh[remove_n.key] self.head = self.head.next self.limit -= 1 newnode = Node(key, value) oldtail = self.tail oldtail.next = newnode newnode.prev = oldtail self.tail = newnode self.hh[key] = newnode if self.limit == 0: self.head = newnode self.limit += 1 # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
15f3a8fbce221a05aff3f14531cb122b80f816cd
gauravaror/programming
/reconstructQueue_SORT_sol.py
287
3.53125
4
class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: people.sort(key=lambda h: (-h[0],h[1])) print(people) queue = [] for p in people: #print(queue) queue.insert(p[1], p) return queue
9527fc836db1dfa78746035db321aa262d9d6da9
gauravaror/programming
/tweet_count_per_frequency.py
1,385
3.515625
4
from collections import Counter class TweetCounts: def __init__(self): self.hours = Counter() self.days = Counter() self.minutes = Counter() def recordTweet(self, tweetName: str, time: int) -> None: minute = time//60 hour = time//3600 self.hours[tweetName+str(hour)] += 1 self.minutes[tweetName+str(minute)] += 1 self.days[tweetName+str(time)] += 1 def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]: start = startTime end = endTime use_counter = self.days if freq == 'hour': start = start //3600 end = end//3600 use_counter = self.hours elif freq == 'minute': start = start // 60 end = end //60 use_counter = self.minutes answer = [] for i in range(start, end+1): key = tweetName + str(i) print(use_counter, i , key) if key in use_counter: answer.append(use_counter[key]) #else: #answer.append(0) return answer # Your TweetCounts object will be instantiated and called as such: # obj = TweetCounts() # obj.recordTweet(tweetName,time) # param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)
ec08f2a7bd1c0a73cdd7a032d962b74b31e73549
gauravaror/programming
/avgwaittime.py
373
3.59375
4
class Solution: def averageWaitingTime(self, customers: List[List[int]]) -> float: currtime = 1 wait = 0 for arrival, prep in customers: if currtime < arrival: currtime = arrival currtime += prep wait += (currtime-arrival) return wait/len(customers)
66ba54e0e35f8db59e76f5df17dc5f4e392c47ba
gauravaror/programming
/reverseBits.py
317
3.578125
4
class Solution: def reverseBits(self, n: int) -> int: st = 1 num = 32 output = 0 while num >= 0: num -= 1 bit = n&st if bit: output += pow(2,num) st = st << 1 #print(st, num, output) return output
16ac1e3175ed3d36d0203505f5573c4223a7446e
gauravaror/programming
/maximum-product-of-splitted-binary-tree.py
1,416
3.5
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def dfs(self, node): left_tree = 0 right_tree = 0 if node.left: left_tree = self.dfs(node.left) if node.right: right_tree = self.dfs(node.right) left_prod = (self.total_sum-left_tree) left_prod *= left_tree right_prod = (self.total_sum-right_tree) right_prod = right_prod*right_tree if (left_prod) > self.maximum: self.maximum = left_prod if right_prod > self.maximum: self.maximum = right_prod return (node.val + left_tree + right_tree) def maxProduct(self, root: TreeNode) -> int: stack = [] total_sum = 0 stack.append(root) self.modulo = 1e9 + 7 while len(stack) > 0: elem = stack[0] stack.pop(0) total_sum = total_sum + (elem.val) if elem.left: stack.append(elem.left) if elem.right: stack.append(elem.right) self.maximum = 0 self.total_sum = total_sum self.dfs(root) print(total_sum, self.maximum) return int(self.maximum % self.modulo)
2454e54711aa57ac5fd43599a85ab5ab1584f44b
gauravaror/programming
/streamChecker.py
1,042
3.609375
4
class Trie: def __init__(self): self.chars = {} self.finishing = False #self.wrd = word def add(self, word): if len(word) == 0: self.finishing = True return if word[0] not in self.chars: self.chars[word[0]] = Trie() self.chars[word[0]].add(word[1:]) from collections import deque class StreamChecker: def __init__(self, words: List[str]): self.root = Trie() for word in words: self.root.add(word[::-1]) self.deque = deque() def query(self, letter: str) -> bool: self.deque.appendleft(letter) node = self.root for i in self.deque: if i in node.chars: node = node.chars[i] if node.finishing: return True else: return False # Your StreamChecker object will be instantiated and called as such: # obj = StreamChecker(words) # param_1 = obj.query(letter)