blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7e40acf91acd9dd755ffa1e2e6f819f147cf5779
meltopian/learningtocode
/tasks/task_12hrtime.py
969
3.953125
4
# Create a program that takes user input # and converts a 12h time (e.g. 4:53pm, 6:00am) # into into a 24h time (e.g. 16:53, 06:00) print('please enter an am or pm time, for example 4:00pm, and i will convert it to 24hr time') time = input() split_time = time.split(":") if 'p' in split_time[1]: split_time[0] = int(split_time[0])+12 split_time[1] = split_time[1].replace('pm', '') if 'a' in split_time[1]: split_time[0] = split_time[0] split_time[1] = split_time[1].replace('am', '') #split_time[1].replace('am', '').replace('pm, '') #(commented out as line has been split into above) final_output = str(split_time[0]) + ':' + str(split_time[1]) #[:-2] #(commented out as this was originally how I removed am/pm from the final result) print('input was') print(time) print('output is') print(final_output) # Potential improvements: # Prevent impossible times (e.g. 25:00) # As user if they want to covert 12->24 or 24->12 # Make input uniform
d4ebc370a69806dff8d30456528fb750f2ebde75
Glittering/netEase
/firstbook/firstBook/demos/wordsStatistics/test_word.py
372
3.546875
4
#coding:utf-8 import string path = 'Walden.txt' with open(path,'r') as f: words = [word.strip(string.punctuation).lower() for word in f.read().split()] words_index=set(words) word = {word:words.count(word) for word in words_index} for word_get in sorted(word,key = lambda x: word[x],reverse= True): print ("{}--{} times".format(word_get,word[word_get]))
279049551c0ffa7d50284ceabb533decf38c4830
merediiii/pytcode
/maxProfit.py
364
3.671875
4
# -*- coding: utf-8 -*- from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: r = 0 a = 0x3f3f3f3f for i in range(0,len(prices)): a = min(a,prices[i]) r = max(r, prices[i] - a) return r if __name__ == '__main__': s = Solution() print(s.maxProfit([7,1,5,3,6,4]))
fda80dc78e5dffa95ed33bcb58cae6423ce45d99
br3ndonland/algorithms
/py/algorythms/tutorials/talkpython_async_05_threading.py
1,042
4.3125
4
""" Talk Python Training: Async Techniques and Examples in Python --- Course: https://training.talkpython.fm/ Code: https://github.com/talkpython/async-techniques-python-course Chapter 5: Threading This is a simple demonstration of how background, or "daemon," threads allow other work to continue in the foreground. """ import threading import time def generate_data(name: str, num: int) -> None: """Generate data for thread. Your normal synchronous code goes here.""" for n in range(num): print(f"Hello {name}! This is greeting number {n + 1}.") time.sleep(0.5) def main() -> None: """Run a background thread, do other work, and wait for completion.""" # Create thread thread = threading.Thread(target=generate_data, args=("You", 5), daemon=True) # Start thread thread.start() # Do other work while thread is running print("I'm doing other work!") # Wait for completion thread.join(timeout=5 * 0.5) # Finish up print("Done.") if __name__ == "__main__": main()
faa2a8a164bf348b746c58aab300d2ab4e6f5aed
soniakash1998/Optical-Flow
/PA2_1.py
5,830
3.578125
4
__author__ = 'khushboo_agarwal' #import libraries import math from scipy import signal from PIL import Image import numpy as np from numpy import * from matplotlib import pyplot as plt from pylab import * import cv2 import random ''' 1. Lucas-Kanade method is basically an estimate of the movement of interesting features in successive images of a scene. 2. Lucas-Kanade assumes a) that the intensity of the pixel does not change of a pixel when it moves from frame1(I1) to frame(I2) with displacement (u,v): I1(x,y) = I2(x+u, y+v) b) small motion, i.e (u,v)< 1 pixel expanding I2 in Taylor series, we get I2(x+u, y+v) = I2(x,y) + I2x(u) + I2y(v) + higher_order_terms ~ I2(x,y) + I2x(u) + I2y(v) 3. Lucas-Kanade associate a movement vector (u,v) to every pixel in a scene obtained by comparing the two consecutive images or frames. 4. works by trying to guess in which direction an object has moved so that local changes in intensity can be explained. 5. Optical Flow has a constraint equation to be solved; Ix.u + Iy.v +It = 0 ; (this equation is obtained by substituting 2b in 2a) where, Ix : derivative of I in x-direction Iy : derivative of I in y-direction It : derivative of I w.r.t time Ix and Iy are image gradients, and It is along t axis since now we deal with a third dimension. These can be d) This will only work for small movements 6. Smoothing the image first to attenuate any noise using Gaussian Smoothing as preprocessing 7. Using an averaging/smoothing filter of 2x2 size to find the first derivative of the smoothed image. 8. Finding features to track using goodFeatureToTrack [Ref: http://docs.opencv.org/2.4/modules/imgproc/doc/feature_detection.html] 9. initialize the u and v vector array ''' def LK_OpticalFlow(Image1, # Frame 1 Image2, # Frame 1 ): ''' This function implements the LK optical flow estimation algorithm with two frame data and without the pyramidal approach. ''' I1 = np.array(Image1) I2 = np.array(Image2) S = np.shape(I1) #applying Gaussian filter of size 3x3 to eliminate any noise I1_smooth = cv2.GaussianBlur(I1 #input image ,(3,3) #shape of the kernel ,0 #lambda ) I2_smooth = cv2.GaussianBlur(I2, (3,3), 0) ''' let the filter in x-direction be Gx = 0.25*[[-1,1],[-1,1]] let the filter in y-direction be Gy = 0.25*[[-1,-1],[1,1]] let the filter in xy-direction be Gt = 0.25*[[1,1],[1, 1]] **1/4 = 0.25** for a 2x2 filter ''' # First Derivative in X direction Ix = signal.convolve2d(I1_smooth,[[-0.25,0.25],[-0.25,0.25]],'same') + signal.convolve2d(I2_smooth,[[-0.25,0.25],[-0.25,0.25]],'same') # First Derivative in Y direction Iy = signal.convolve2d(I1_smooth,[[-0.25,-0.25],[0.25,0.25]],'same') + signal.convolve2d(I2_smooth,[[-0.25,-0.25],[0.25,0.25]],'same') # First Derivative in XY direction It = signal.convolve2d(I1_smooth,[[0.25,0.25],[0.25,0.25]],'same') + signal.convolve2d(I2_smooth,[[-0.25,-0.25],[-0.25,-0.25]],'same') # finding the good features features = cv2.goodFeaturesToTrack(I1_smooth # Input image ,10000 # max corners ,0.01 # lambda 1 (quality) ,10 # lambda 2 (quality) ) feature = np.int0(features) plt.subplot(1,3,1) plt.title('Frame 1') plt.imshow(I1_smooth, cmap = cm.gray) plt.subplot(1,3,2) plt.title('Frame 2') plt.imshow(I2_smooth, cmap = cm.gray)#plotting the features in frame1 and plotting over the same for i in feature: x,y = i.ravel() cv2.circle(I1_smooth #input image ,(x,y) #centre ,3 #radius ,0 #color of the circle ,-1 #thickness of the outline ) #creating the u and v vector u = np.nan*np.ones(S) v = np.nan*np.ones(S) # Calculating the u and v arrays for the good features obtained n the previous step. for l in feature: j,i = l.ravel() # calculating the derivatives for the neighbouring pixels # since we are using a 3*3 window, we have 9 elements for each derivative. IX = ([Ix[i-1,j-1],Ix[i,j-1],Ix[i-1,j-1],Ix[i-1,j],Ix[i,j],Ix[i+1,j],Ix[i-1,j+1],Ix[i,j+1],Ix[i+1,j-1]]) #The x-component of the gradient vector IY = ([Iy[i-1,j-1],Iy[i,j-1],Iy[i-1,j-1],Iy[i-1,j],Iy[i,j],Iy[i+1,j],Iy[i-1,j+1],Iy[i,j+1],Iy[i+1,j-1]]) #The Y-component of the gradient vector IT = ([It[i-1,j-1],It[i,j-1],It[i-1,j-1],It[i-1,j],It[i,j],It[i+1,j],It[i-1,j+1],It[i,j+1],It[i+1,j-1]]) #The XY-component of the gradient vector # Using the minimum least squares solution approach LK = (IX, IY) LK = np.matrix(LK) LK_T = np.array(np.matrix(LK)) # transpose of A LK = np.array(np.matrix.transpose(LK)) A1 = np.dot(LK_T,LK) #Psedudo Inverse A2 = np.linalg.pinv(A1) A3 = np.dot(A2,LK_T) u[i,j] = np.dot(A3,IT)[0] # we have the vectors with minimized square error v[i,j] = np.dot(A3,IT)[1] # we have the vectors with minimized square error #======= Pick Random color for vector plot======== colors = "bgrcmykw" color_index = random.randrange(0,8) c=colors[color_index] #======= Plotting the vectors on the image======== plt.subplot(1,3,3) plt.title('Vector plot of Optical Flow of good features') plt.imshow(I1,cmap = cm.gray) for i in range(S[0]): for j in range(S[1]): if abs(u[i,j])>t or abs(v[i,j])>t: # setting the threshold to plot the vectors plt.arrow(j,i,v[i,j],u[i,j],head_width = 5, head_length = 5, color = c) plt.show() t = 0.3 # choose threshold value #import the images Image1 = Image.open('basketball1.png').convert('L') Image2 = Image.open('basketball2.png').convert('L') LK_OpticalFlow(Image1, Image2) Image3 = Image.open('grove1.png').convert('L') Image4 = Image.open('grove2.png').convert('L') LK_OpticalFlow(Image3, Image4) Image5 = Image.open('teddy1.png').convert('L') Image6 = Image.open('teddy2.png').convert('L') LK_OpticalFlow(Image5, Image6)
48c028fbe194d9b88bae60ac1a4a69ee7dae892f
Atadeno/Projet_RO_Groupe_8
/croisement.py
7,625
3.609375
4
import ordonnancement as ord import job import random ### Croisement ### def swap(A, B, i, j): TEMP_B = B[j] B[j] = A[i] A[i] = TEMP_B return A, B # prend deux listes d'entiers entrée # croise ces deux listes d'entiers # retourne les deux listes d'entiers croisées def croiser_liste(L, M): try: len(M) != len(L) except: print("ERREUR: les longueurs des solutions à croiser ne sont pas égales") L1 = L[0: int(len(L) / 3)] L2 = L[int(len(L) / 3): int(2 * len(L) / 3)] L3 = L[int(2 * len(L) / 3): len(L)] M1 = M[0: int(len(M) / 3)] M2 = M[int(len(M) / 3): int(2 * len(M) / 3)] M3 = M[int(2 * len(M) / 3): len(M)] new_L = L1 + M2 + L3 new_M = M1 + L2 + M3 # R : y avait job.num alors que job est un int index_L = [job for job in new_L] #? index_M = [job for job in new_M] #? index_L = new_L index_M = new_M # R : j'ai commenté ceci, l'utilité détecter les doublons qui apparaissent """" for index in new_L: if index_L.count(index) > 1: print() print() for index in new_M: if index_M.count(index) > 1: print(index) print("indexes_L", index_L) print("indexes_M", index_M) """"" return index_L, index_M # R : répare les deux listes de jobs qui ont été croisées, l'entrée c'est le résultat de la méthode dessus # les valeurs des deux listes doivent être exactement dans l'ensemble {1,2,3 ... Nb_job}, jobs compté de 1 # une modification de réparation ne peut se faire que dans la sous-liste éxogène de numéros def repair(list_jobs_L, list_jobs_M) : Nb_job = len(list_jobs_L) index_L = [] index_M = [] # on remplace les jobs par leurs numéros respectifs pour les deux listes de jobs for job in list_jobs_L : index_L.append(job.numero()) for job in list_jobs_M : index_M.append(job.numero()) # visualiser les listes d'entiers """ print("index_L",index_L) print("index_M", index_M) """ # problème du comptage des jobs à partir de 1 ou de 0 résolu par cette condition if 0 in index_L or 0 in index_M : maximum = Nb_job-1 minimum = 0 else : maximum = Nb_job minimum = 1 # Etape 1 : Doublons # ces deux listes contiendront des tuples des élèments doublés (dans la sous-liste exogène) avec leurs positions respectives, les positions doivent être dans # l'intervalle [Nb_job//3,2*Nb_job//3] doubled_elements_L = [] doubled_elements_M = [] for i in range(Nb_job//3,2*Nb_job//3) : # l'intervalle est bien respecté selon la règle dans la fonction de croisement if index_L.count(index_L[i]) > 1 : doubled_elements_L.append((index_L[i],i)) if index_M.count(index_M[i]) > 1 : doubled_elements_M.append((index_M[i],i)) # tester la détection des doublons """ print("Doubles L",doubled_elements_L) print("Doubles M", doubled_elements_M) """ # Etape 2 : Manquants # ces deux listes contiendront des tuples des élèments manquants missing_elements_L = [] missing_elements_M = [] for i in range(minimum, maximum+1): indice_L = False indice_M = False for j in range(0, Nb_job): if i==index_L[j]: indice_L = True if i==index_M[j]: indice_M = True if indice_L == False: missing_elements_L.append(i) if indice_M == False: missing_elements_M.append(i) # tester la détection des manquants """ print("Missing L", missing_elements_L) print("Missing M", missing_elements_M) """ random.shuffle(missing_elements_L) random.shuffle(missing_elements_M) # Etape 3 : Remplacer les doublons par les manquants # on remplace les doublons dans les listes exogènes par les manquants for i in range(0, len(doubled_elements_L)): index_L[doubled_elements_L[i][1]] = missing_elements_L[i] index_M[doubled_elements_M[i][1]] = missing_elements_M[i] # retourne les listes des entiers après croisement # print pour tests """ print(index_L) print(index_M) """ # On revient aux jobs well_formed_kids_L = [ None for i in range(0,Nb_job)] well_formed_kids_M = [ None for i in range(0,Nb_job)] for job in list_jobs_L+list_jobs_M : # prob job potentiel manquant dans les deux listes for i in range(0,Nb_job) : if job.numero() == index_L[i] : well_formed_kids_L[i] = job if job.numero() == index_M[i] : well_formed_kids_M[i] = job # afficher le réparage des jobs """ print("well_formed_kids_L") for job in well_formed_kids_L : job.afficher() print("well_formed_kids_M") for job in well_formed_kids_M : job.afficher() """ return well_formed_kids_L , well_formed_kids_M # prend deux parents # retourne deux enfants croisés def create_two_kids(parent_1, parent_2): liste_jobs_parent_1 = parent_1.sequence() liste_jobs_parent_2 = parent_2.sequence() l1, l2 = croiser_liste(liste_jobs_parent_1, liste_jobs_parent_2) # R : réparage l1, l2 = repair(l1,l2) kid1 = ord.Ordonnancement(parent_1.nb_machines) kid2 = ord.Ordonnancement(parent_1.nb_machines) kid1.ordonnancer_liste_job(l1) kid2.ordonnancer_liste_job(l2) return kid1, kid2 # prend une liste de population de taille N # réalise le croisement deux à deux # retourne une nouvelle population de taille 2*N def croisement_population(population): kids = [] for index in range(int(len(population)/2)): kid1, kid2 = create_two_kids(population[2*index], population[2*index + 1]) kids.append(kid1) kids.append(kid2) return population + kids if __name__ == '__main__': # R : génération des enfants commentée """ number_of_machines = 10 job1 = job.Job(1, [46, 61, 3, 51, 37, 79, 83, 22, 27, 24]) job2 = job.Job(2, [52, 87, 1, 24, 16, 93, 87, 29, 92, 47]) job3 = job.Job(3, [79, 51, 58, 21, 42, 68, 38, 99, 75, 39]) job4 = job.Job(4, [45, 25, 85, 57, 47, 75, 38, 25, 94, 66]) job5 = job.Job(5, [97, 73, 33, 69, 94, 37, 86, 98, 18, 41]) job6 = job.Job(6, [10, 93, 71, 51, 14, 44, 67, 55, 41, 46]) liste1 = [job1, job4, job5, job3, job2, job6] liste2 = [job5, job3, job4, job6, job1, job2] liste3 = [job1, job2, job3, job4, job5, job6] liste4 = [job6, job5, job4, job3, job2, job1] liste5 = [job6, job4, job5, job3, job1, job2] liste6 = [job1, job6, job2, job5, job3, job4] parent_1 = ord.Ordonnancement(10) parent_2 = ord.Ordonnancement(10) parent_3 = ord.Ordonnancement(10) parent_4 = ord.Ordonnancement(10) parent_5 = ord.Ordonnancement(10) parent_6 = ord.Ordonnancement(10) parent_1.ordonnancer_liste_job(liste1) parent_2.ordonnancer_liste_job(liste2) parent_3.ordonnancer_liste_job(liste3) parent_4.ordonnancer_liste_job(liste4) parent_5.ordonnancer_liste_job(liste5) parent_6.ordonnancer_liste_job(liste6) population = [parent_1, parent_2, parent_3, parent_4, parent_5, parent_6] new_population = croisement_population(population) print(len(new_population)) for individu in population: individu.afficher() """ # R : Test de la fonction repair pour deux listes des jobs : #index_L,index_M = croiser_liste(L,M) #le croisement super """ repair(croiser_liste(liste1,liste2)[0],croiser_liste(liste1,liste2)[1]) """
ae82e44d50d0f24b1a20b1cb78c2a911f47240cc
avishek088/py-tictactoe
/TicTacToeGame.py
3,773
3.671875
4
from itertools import cycle from colorama import init, Fore, Style init() def game_board(game_map, player=0, row=0, col=0, just_display=False): try: if(game_map[row][col] != 0): print("This position is occupied ! Please choose another ...") return game_map, False print(" "+" ".join([str(i) for i in range(len(game_map))])) if not just_display: game_map[row][col] = player for count, row in enumerate(game_map): colored_row = "" for item in row: if item == 0: colored_row += " " elif item == 1: colored_row += Fore.GREEN + ' X ' + Style.RESET_ALL elif item == 2: colored_row += Fore.MAGENTA + ' O ' + Style.RESET_ALL print(count, colored_row) return game_map, True except IndexError as e: print("Error! make sure you input row/columns as 0 1 or 2? ", e) return game_map, False except Exception as e: print("Error! something went wrong! ", e) return game_map, False def win(current_game): def all_same(l): if(l.count(l[0]) == len(l) and l[0]) != 0: return True else: return False # Determine horizontal winner for row in current_game: # print(row) if(all_same(row)): print(f"Player {row[0]} is the winner horizontally (-)") return True # Determine vertical winner for col in range(len(current_game)): check = [] for row in current_game: check.append(row[col]) # print(check) if(all_same(check)): print(f"Player {check[0]} is the winner vertically (|)") return True # Determine diagonal winner # Direction "\" diags = [] for idx in range(len(current_game)): diags.append(current_game[idx][idx]) # print(diags) if(all_same(diags)): print(f"Player {diags[0]} is the winner diagonally (\\)") return True # Direction "/" diags = [] # cols = list(reversed(range(len(current_game)))) # rows = list(range(len(current_game))) # print(cols) # print(rows) '''for col, row in zip(cols, rows): diags.append(current_game[col][row]) ''' for col, row in enumerate(reversed(range(len(current_game)))): # print(col, row) diags.append(current_game[row][col]) # print(diags) if(all_same(diags)): print(f"Player {diags[0]} is the winner diagonally (/)") return True return False play = True while play: game_size = int(input("What size of tic tac toe game you want to play? : ")) game = [[0 for i in range(game_size)] for i in range(game_size)] game_won = False player_choice = cycle([1, 2]) game, _ = game_board(game, just_display=True) while not game_won: current_player = next(player_choice) print(f"Current player: {current_player}") played = False while not played: column_choice = int(input("What column do you want to play? (0, 1, 2): ")) row_choice = int(input("What row do you want to play? (0, 1, 2): ")) game, played = game_board(game, current_player, row_choice, column_choice) if win(game): game_won = True again = input("Would you like to play again? (y/n): ") if again.lower() == "y": print("Restarting!") elif again.lower() == "n": print("Byeeeee") play = False else: print("Not a valid choice! See you later... aligator ;) ") play = False
1af07fa51b4b364184fa587778add8fe02586ad9
archu997/codekata
/working.py
231
3.875
4
def workingDay(day): work=['monday','tuesday','wednesay','thursday','friday','saturday'] if day in work: return True else: return False day=raw_input("Enter a day") day=day.lower() print workingDay(day)
6f01bda382ad3bb0fbeec369c65c8a85ac6007ec
arpita-ak/APS-2020
/Hackerrank solutions/Medium- Climbing the Leaderboard.py
987
3.921875
4
""" Climbing the Leaderboard: https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem """ #!/bin/python3 import math import os import random import re import sys # Complete the climbingLeaderboard function below. def climbingLeaderboard(s, scores, a, alice): uniq=[0]*(s+a) j=0 for i in scores: if i not in uniq: uniq[j]=i j+=1 print(uniq) for i in range(a): for k in range(j): if uniq[k]<alice[i]<uniq[k+1]: uniq[k+1]=alice[i] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = int(input()) scores = list(map(int, input().rstrip().split())) a = int(input()) alice = list(map(int, input().rstrip().split())) result = climbingLeaderboard(s, scores, a, alice) fptr.write('\n'.join(map(str, result))) fptr.write('\n') fptr.close()
2ea8ccb0b4969ad8262f04e78d1316703d8aff72
paularodriguez/python-core-and-advance-course
/sec11-lambdas/decorator_strings.py
451
4.3125
4
# The hello function takes a name and it will return Hello under that name and then even create a decorator # function called howareyou that will take the result of the hello function and it will append a string # called "How are you" at the end # Hello (name) # howareyou() def howareyou(fun): def inner(n): return fun(n) + " How are you?" return inner @howareyou def hello(name): return "Hello " + name print(hello("Paula"))
f81c26622f99a75af43fb439ebf150a319f04507
obada320/My-Codes
/Python learning/old.py
456
4.03125
4
name1 = str(input('Enter name ')) age1 = float(input('Enter age ')) name2 = str(input('Enter name ')) age2 = float(input('Enter age ')) name3 = str(input('Enter name ')) age3 = float(input('Enter age ')) if age1 > age2: if age1 > age3: print(name1,' is the oldest') if age2 > age1: if age2 > age3: print(name2, ' is the oldest') if age3 > age1: if age3 > age2: print(name3, ' is the oldest')
151cc645d92a0f59c510e55ffde4157d0fb320d7
kinghoward63/hello-world
/Module 1-Problem 2.py
236
3.90625
4
#Dante Howard #4/23/2019 #Problem 2 this will tell you the numberof day the week you returned on day=int(input("number0-8")) gone=int('How ling were you gone?")) gone%7 ((gone%7)+day) print(((gone%7)+day)%7)
edae72ce9e44e9ab712a4135adf2d877cfc0e3fb
ridersw/Karumanchi---Algorithms
/InsertionSort.py
356
4.15625
4
def insertionSort(elements): for swi in range(1, len(elements)): anchor = elements[swi] swj = swi - 1 while swj >= 0 and elements[swj] > anchor: elements[swj+1] = elements[swj] swj -= 1 elements[swj+1] = anchor if __name__ == "__main__": elements = [11, 9, 29, 7, 2, 15, 28] insertionSort(elements) print(elements)
b3a803ce3de9c52547df7fe5e1093f86d99348db
hal00010001/PythonProjects
/af_semana9.py
4,089
4.125
4
#!/usr/bin/python3 #coding: utf-8 import random # Inicio do exercicio 1 # Faça um algoritmo que solicite ao usuário números e os armazene em uma matriz 6x6. Em seguida, crie um vetor que armazene os elementos da diagonal principal da matriz. def exercicio1(): vetor = [0]*6 matriz = [0]*6 for i in range(6): matriz[i] = [0]*6 for linha in range(6): for coluna in range(6): matriz[linha][coluna] = input('Digite um valor a ser adicionado:\n') print('A matriz e: {}'.format(matriz)) for linha in range(6): for coluna in range(6): if linha == coluna: vetor[linha] = matriz[linha][coluna] print('A matriz impressa de forma tabular e:\n') for j in matriz: for k in j: print(k, end=' ') print('\n') print('A diagonal principal e: {}'.format(vetor)) # Inicio do exercicio 2 # Tendo uma matriz 10x10 preenchida com valores aleatórios entre 10 e 50, mostre a média dos elementos da diagonal secundária. def exercicio2(): matriz = [0]*10 vetor = [0]*10 for i in range(10): matriz[i] = [0]*10 for linha in range(10): for coluna in range(10): matriz[linha][coluna] = random.randint(10,50) for linha in range(10): for coluna in range(10): # O numero 9 corresponde a n+1 que e o numero de colunas da matriz + 1 if linha + coluna == 9: vetor[linha] = matriz[linha][coluna] print('A media da diagonal secundaria da matriz e: {}\n'.format(sum(vetor)/len(vetor))) for j in matriz: for k in j: print(k, end=' ') print('\n') print('A diagonal secundaria e: {}\n'.format(vetor)) # Inicio do exercicio 3 # Tendo uma matriz 10x10 preenchida com valores aleatórios entre 10 e 50, mostre o maior valor existente desconsiderando os elementos da diagonal principal. def exercicio3(): matriz = [0]*10 vetor = [0]*10 for i in range(10): matriz[i] = [0]*10 for linha in range(10): for coluna in range(10): matriz[linha][coluna] = random.randint(10,50) for j in matriz: for k in j: print(k, end=' ') print('\n') valorMaior = matriz[1][0] for linha in range(10): for coluna in range(10): if(linha != coluna): if(matriz[linha][coluna] > valorMaior): valorMaior = matriz[linha][coluna] print ('O maior valor da matriz desconsiderando a diagonal principal e {}\n'.format(valorMaior)) # Inicio do exercicio 4 # Tendo uma matriz 5x5 preenchida com valores aleatórios entre 0 e 99, mostre o segundo maior valor existente. def exercicio4(): matriz = [0]*5 segundoValorMaior = 0 for i in range(5): matriz[i] = [0]*5 valorMaior = matriz[0][0] for linha in range(5): for coluna in range(5): matriz[linha][coluna] = random.randint(0,99) for j in matriz: for k in j: print(k, end=' ') print('\n') for linha in range(5): for coluna in range(5): if(matriz[linha][coluna] > valorMaior): valorMaior = matriz[linha][coluna] print('O maior valor e: {}\n'.format(valorMaior)) for linha in range(5): for coluna in range(5): if(matriz[linha][coluna] > segundoValorMaior and matriz[linha][coluna] != valorMaior): segundoValorMaior = matriz[linha][coluna] print('O segundo valor maior e: {}\n'.format(segundoValorMaior)) # Menu de selecao das funcoes escolha = 0 while escolha != 5: escolha = int(input('Digite qual funcao deseja executar:\n [1] Diagonal principal de uma matriz\n [2] Media da diagonal secundaria da matriz\n [3] Maior valor existente desconsiderando a diagonal principal\n [4] Segundo maior valor existente\n [5] Sair do programa\n')) if(escolha == 1): exercicio1() elif(escolha == 2): exercicio2() elif(escolha == 3): exercicio3() elif(escolha == 4): exercicio4() # Fim do programa
a487f40fe1a1f9fd900c3ff4812850b9219370a2
JamesRoth/Unit3
/betterAdditionGameDemo.py
593
3.9375
4
#James Roth #2/28/18 #betterAdditionGameDemo.py - the name says it all from random import randint numCorrect=0 numIncorrect=0 while numCorrect<5: num1=randint(-10,10) num2=randint(-10,10) print("You've had", numCorrect, "correct answers, and", numIncorrect, "incorrect answers.") answer=int(input("What is the sum of " + str(num1) + " and " + str(num2) + "? ")) if answer==num1+num2: print("Correct!") numCorrect+=1 else: print("Incorrect. The correct answer was ", str(num1+num2) + "." ) numIncorrect+=1 print("You can do 1st grade math!")
3b8ff5aa837b81e2b25175b3f966e91b552aee1c
SmartPracticeschool/llSPS-INT-2749-Garbage-Classification
/Preprocessed and Model/Model.py
980
3.625
4
#Importing The Model Building Libraries from keras.models import Sequential from keras.layers import Dense from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten #Initializing The Model model = Sequential() #Loading The Prepocessed Data from Preprocessed import * #Adding CNN Layers model.add(Convolution2D(32,(3,3),input_shape = (64,64,3),activation = 'relu')) #Configure The Learning Process model.add(MaxPooling2D(pool_size = (2,2))) model.add(Flatten()) #Adding Dense Layers model.add(Dense(output_dim = 128 ,init = 'uniform',activation = 'relu')) model.add(Dense(output_dim = 6,activation = 'softmax',init ='uniform')) #Optimise The Model model.compile(loss = 'categorical_crossentropy',optimizer = "adam",metrics = ["accuracy"]) #Train And Test The Model model.fit_generator(x_train, steps_per_epoch = 126,epochs = 1000,validation_data = x_test,validation_steps = 32) #Saving the model model.save("garbage.h5")
70deb2dc69056571aee0f2a654fa3b77c4ca014f
XenonShawn/Sudoku
/sudoku.py
3,410
3.984375
4
from sys import argv, stderr from time import time def main() -> None: # Get the board board = input_board() print("Input Board:") print_board(board) start = time() if check_board_validity(board): solve(board) print("Result:") print_board(board) else: print("Impossible Board") print("Time Taken", time() - start) def solve(board) -> bool: # We start solving from the cell which has the least number of possible values sorted_possible_values = sorted(get_possible_values(board).items(), key=lambda x: len(x[1])) # No more empty cells, board is solved! if not sorted_possible_values: return True # Extract out the cell with the least number of possible values idx, possible_values = sorted_possible_values[0] for i in possible_values: board[idx] = i # For each possible value of the cell, try further solving it if solve(board): return True # All possible values don't work - reset the cell value back to None board[idx] = None return False def input_board() -> list: board = list() with open(argv[1]) as f: for row in f: board += list(map(lambda x: int(x) if x.isdigit() else None, row[:9].ljust(9, ' '))) return board def print_board(board) -> None: for i in range(9): print('|', end='') for j in range(9): number = board[9 * i + j] print(' ' if number is None else number, end='') print('|', end='') print() def get_possible_values(board) -> dict: # Initialise with a full set of possible values, for each unfilled cell (ie v is None) result = {idx: {1, 2, 3, 4, 5, 6, 7, 8, 9} for idx, v in enumerate(board) if v is None} for idx, possible_values in result.items(): row, col = divmod(idx, 9) # Check row and column for i in range(9): possible_values.discard(board[i * 9 + col]) possible_values.discard(board[row * 9 + i]) # Remove number from 3x3 square squareRow = row - row % 3 squareCol = col - col % 3 for i in range(squareRow, squareRow + 3): for j in range(squareCol, squareCol + 3): possible_values.discard(board[i * 9 + j]) return result def check_board_validity(board) -> bool: """Initially check if the board is valid. Not necessary, but helps speed up "solve" time for impossible boards.""" for idx, cell in enumerate(board): if cell is None: continue row, col = divmod(idx, 9) for i in range(9): # Check row if i != col: if board[row * 9 + i] == cell: return False # Check column if i != row: if board[i * 9 + col] == cell: return False # Check 3x3 square squareRow = row - row % 3 squareCol = col - col % 3 for i in range(squareRow, squareRow + 3): for j in range(squareCol, squareCol + 3): if i != row or j != col: if board[i * 9 + j] == cell: return False return True if __name__ == "__main__": if len(argv) != 2: print(f"Usage: python {argv[0]} sudoku_file", file=stderr) exit(1) main()
c677818a25890aa90139253b963bc0de48db9d3f
excaliware/python
/temperature.py
520
4.03125
4
""" Convert temprature from Celsius to Fahrenheit or vice versa. """ import sys def main(): if len(sys.argv) == 3: mode = str(sys.argv[1]) value = int(sys.argv[2]) else: print_usage() exit(-1) if mode == 'f': print("%.1f" % f2c(value)) elif mode == 'c': print("%.1f" % c2f(value)) else: print_usage() exit(-1) def print_usage(): print("Usage: temperature {f|c} VALUE") def f2c(f): return (f - 32) / 1.8 # 9 / 5 def c2f(c): return c * 1.8 + 32 if __name__ == "__main__": main()
15cc10a850e7a0f9ca1932ee46527e6adef30c5a
ledunn/dev-sprint2
/chap6.py
578
3.9375
4
# Enter your answers for chapter 6 here # Name: Lauren Dunn # Ex. 6.6 def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] print middle('') #middle() doesn't work with two letter, one, or no letter strings. def is_palindrome(word): if len(word)<2: pass elif len(word)==3 and first(middle(word))== last(middle(word)): return True if first(word)== last(word): return is_palindrome(middle(word)) else: return False x=is_palindrome('racecar') print x #Ex 6.8: def gcd(a,b): gcd(a,b)=gcd(b,r) gcd(a,0)=a
dc63d6a556cc465d7e6aadaa281e0c238632f4d4
javierfdz10/shopping_cart
/shopping_cart.py
4,655
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 15 13:12:24 2018 @author: Javier """ #Our e-shop sells the following products: # 1. Guitar: $1000 # 2. Pick box: $5 # 3. Guitar Strings: $10 # Create a function named checkout that takes a list that represents a shopping cart and returns the total cost of it. This function should check that the shopping cart must not be empty. # Create also some tests for the function. Try to think of the corner cases. # Hint: you can represent a product as a dictionary with a name and a price. #%% prices = {"Guitar":1000, "Pick Box":5, "Guitar Strings":10} prices_in_cart = [] def checkout_white(mycart): if mycart == []: return None else: for i in mycart: # print(prices_in_cart) prices_in_cart.append(prices[i]) # print(prices_in_cart) return sum(prices_in_cart) #checkout_white(["Pick Box", "Guitar"]) #%% #You want to give more features to the user, so you decide that you will allow #them to purchase an insurance package on their purchase and also priority mail. #Consider that these two new services can only be purchase once per order. # # 1. Insurance: $5 # 2. Priority mail: $10 # # Modify your checkout function so it handles these cases correctly, # and add more tests that check your functionality. #%% prices = {"Guitar":1000, "Pick Box":5, "Guitar Strings":10, "Insurance":5, "Priority mail":10} prices_in_cart = [] def checkout_blue(mycart): if "Insurance" in mycart: prices_in_cart.append(prices["Insurance"]) for i in mycart: if "Insurance" in mycart: mycart.pop(mycart.index("Insurance")) print(mycart) if "Priority mail" in mycart: prices_in_cart.append(prices["Priority mail"]) for i in mycart: if "Priority mail" in mycart: mycart.pop(mycart.index("Priority mail")) print(mycart) if mycart == []: return None else: for i in mycart: prices_in_cart.append(prices[i]) print(prices_in_cart) return sum(prices_in_cart) #checkout_blue(["Guitar", "Pick Box", "Insurance", "Insurance", "Priority mail", "Priority mail"]) #checkout_blue(["Guitar Strings", "Insurance"]) #checkout_blue(["Insurance", "Insurance", "Guitar", "Insurance", "Insurance"]) #%% # You want to add a new feature to your ecommerce, you want to create three different # tiers of customers: # # - normal: No added benefits # - silver: 2% discount on products from the ecommerce # - gold: 5% discount on everything # # Modify the checkout function to accept another parameter with the tier of the # customer and apply the discounts as needed. # # Implement this feature in the checkout function and add tests that prove that # your implementation is correct. prices = {"Guitar":1000, "Pick Box":5, "Guitar Strings":10, "Insurance":5, "Priority mail":10} tiers = {"Normal": 1, "Silver": 0.98, "Gold": 0.95} prices_in_cart = [] def checkout_black(tier, mycart): silver = tiers["Silver"] gold = tiers["Gold"] normal = tiers["Normal"] if tier == "Normal": silver = 1 gold = 1 elif tier == "Silver": gold = 1 elif tier == "Gold": silver = 1 print(silver , "Silver") print(gold, "Gold") print(normal, "Normal") if "Insurance" in mycart: prices_in_cart.append(prices["Insurance"]) for i in mycart: if "Insurance" in mycart: mycart.pop(mycart.index("Insurance")) print(mycart) if "Priority mail" in mycart: prices_in_cart.append(prices["Priority mail"]) for i in mycart: if "Priority mail" in mycart: mycart.pop(mycart.index("Priority mail")) print(mycart) if mycart == []: return None else: for i in mycart: prices_in_cart.append(prices[i] * silver) print(prices_in_cart) return sum(prices_in_cart) * normal * gold #checkout_black("Silver", ["Insurance","Pick Box", "Guitar", "Insurance", "Insurance", "Priority mail", "Priority mail"]) #checkout_black("Gold", ["Pick Box", "Insurance", "Insurance", "Priority mail", "Priority mail"]) #%%
7224bdeea7e8e55e953dd1be9e0ef932621a7259
Jcoder2022/ConditionalStatementsInPython
/conditionalStmt.py
2,820
4.3125
4
# if it's hot # It's a hot day # Drink plenty of water # otherwise if it's cold # It's a cold day # Wear warm clothes # otherwise # It's a lovely day weather = "cold" is_hot = True is_cold = True if is_hot: print("It's a hot day") print("Drink plenty of water") elif is_cold: print("It's a cold day") print("Wear warm clothes") else: print("It's a lovely day") # o/p will be following # It's a hot day # Drink plenty of water print("---------------------------------------------------------") if weather == "hot": print("It's a hot day") print("Drink plenty of water") elif weather == "cold": print("It's a cold day") print("Wear warm clothes") else: print("It's a lovely day") print("Enjoy your Day") # o/p will be following # It's a cold day # Wear warm clothes # Enjoy your Day print("---------------------------------------------------------") is_hot = False is_cold = False if is_hot: print("It's a hot day") print("Drink plenty of water") elif is_cold: print("It's a cold day") print("Wear warm clothes") else: print("It's a lovely day") # o/p will be following # It's a lovely day # Multiple Conditions # AND, OR, NOT # if applicant has high income AND good credit # Eligible for loan has_high_income = True has_good_credit = True if has_high_income and has_good_credit: print("Eligible for loan") # if applicant has high income OR good credit # Eligible for loan has_high_income = True has_good_credit = False if has_high_income or has_good_credit: print("Eligible for loan") # Not - example # if applicant has good credit AND doesn't have criminal record # Eligible for loan has_good_credit = True has_criminal_record = True if has_good_credit and not has_criminal_record: print ("Eligible for loan") # Comparison Operator # <,<=,>,>=,==,!= # if temperature is greater than 30 # it's a hot day # otherwise if it's less than 10 # it's a cold day # otherwise # it's neither hot nor cold temperature = 10 if temperature > 30: print("it's a hot day") elif temperature<10: print("it's a cold day") else: print("it's neither hot nor cold") # exercise name="Salman" length = len(name) if length < 3: print("name must be atleast 3 char long") elif length > 50: print("name can be a max of 50 characters") else: print("name looks good!") # exercise # Weight: 160 (input) # (L)bs or (K)g: l (input) # You are 72.0 kilos weight = input("Weight: ") measurement_unit = input("(L)bs or (K)g: ") if measurement_unit.lower() == 'l': weight_in_kilos = int(weight) * 0.45359237 print(f"You are {weight_in_kilos} kilos") else: weight_in_pounds = int(weight)/0.45 print(f"You are {weight_in_pounds} pounds")
b61314b7915fac3f3f4e4f0b7423166f262cbd69
NavTheRaj/python_lab
/pickle_veg.py
3,513
4.5625
5
#WAP TO DEMONSTRATE DICTIONAARY OPERATIONS IN PYTHON veg_dict={'Brinjal':10,'Cabbage':20,'Pumpkin':25} print("-------------------\n") #print("1.View list\n2.Add a new vegetable\n3.Change the price of an vegetable\n4.Delete the vegetable\n5.Quit!") choice=0 while choice != 5 : print("1.View list\n2.Add a new vegetable\n3.Change the price of an vegetable\n4.Delete the vegetable\n5.Quit!") print("-------------------\n") choice=int(input("Enter your choice ")) #CHOICE 1 TO SHOW THE ELEMENTS if choice == 1: print("-------------------\n") print(veg_dict) print("-------------------\n") #CHOICE 2 TO ADD THE NEW VEGETABLE SET elif choice == 2: print("-------------------\n") print("Your vegetable list\n") print(veg_dict) print("-------------------\n") veg_name=input("Enter the new vegetable-> ") print("-------------------\n") price=input('Enter price of '+veg_name+'-> ') print("-------------------\n") veg_dict.update({veg_name:price}) print("Your new vegetable list\n") print(veg_dict) print("-------------------\n") #CHOICE 3 TO EDIT THE PRICE OF THE EXISTING VEGETABLE elif choice == 3: print("-------------------\n") print("Your vegetable list\n") print(veg_dict) print("-------------------\n") veg_change="" while veg_change not in veg_dict: veg_change=input("Enter the vegetable whose price you wanna change->") print("-------------------\n") if veg_change in veg_dict: print('Current price of '+veg_change+'-> '+str(veg_dict[veg_change])) price_change=input('Enter your updated price for '+veg_change+'->') print("-------------------\n") veg_dict[veg_change]=price_change print("Your new vegetable list\n") print(veg_dict) print("-------------------\n") break else: print("-------------------\n") print("Vegetable not found..Try again!") print("-------------------\n") #CHOICE 4 TO DELETE THE VEGETABLE FROM THE DICTIONARY elif choice == 4: print("-------------------\n") print("Your vegetable list\n") print(veg_dict) print("-------------------\n") veg_delete="" while veg_delete not in veg_dict: print("-------------------\n") veg_delete=input("Enter the vegetable to delete") if veg_delete in veg_dict: del veg_dict[veg_delete] print("-------------------\n") print("Deleted "+veg_delete+" successfully!") print("-------------------\n") break else: print("-------------------\n") print("Vegetable not found..Try again!") print("-------------------\n") #CHOICE 5 TO SAVE THE UPDATED LIST IN FILE AND EXIT THE PROGRAM elif choice == 5: print("-------------------\n") veg_file=open("veg.txt","w+") veg_file.write(str(veg_dict)) veg_file.close() print("Saving the updated list and exiting..") exit() #CHOICE INVALID TO ITERATE THE WHILE LOOP else: print("-------------------\n") print("Invalid input..Try again!") print("-------------------\n")
3181050086a4ea4b6c1f46f27535633e334b5f74
Rodrigs22/ExerciciosCursoEmvideo
/ex040.py
2,561
3.625
4
#cores cores = {'limpa': '\033[m', 'amarelo': '\033[33m', 'vermelho': '\033[31m', 'verde': '\033[32m', 'ciano': '\033[36m'} #estética print(cores['amarelo']) print('-=' * 22) print(cores['limpa']) print(cores['ciano']) print('CALCULE A MÉDIA DO SEU ALUNO !') print(cores['limpa']) print(cores['amarelo']) print('-=' * 22) print(cores['limpa']) # programa para calcular a média do aluno quantidade = int(input('digite quantas notas serão usadas para avaliar (MIN 2, MAX 4): ')) if quantidade == 2: n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) media = (n1 + n2) / 2 if media >= 7: print('{}Sua nota foi dê {}, você foi APROVADO !{}'.format(cores['verde'], media, cores['limpa'])) elif media >= 5 < 7: print('{}Sua nota foi dê {}, você esta de recuperação{}'.format(cores['amarelo'], media, cores['limpa'])) else: print('{}Sua nota foi dê {}, você foi reprovado !{}'.format(cores['vermelho'], media, cores['limpa'])) print('{}Desejamos um bom dia a todos !{}'.format(cores['ciano'], cores['limpa'])) elif quantidade == 3: n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) n3 = float(input('Digite a terceira nota: ')) media = (n1 + n2 + n3) / 3 if media >= 7: print('{}Sua nota foi dê {}, você foi APROVADO !{}'.format(cores['verde'], media, cores['limpa'])) elif media >= 5 < 7: print('{}Sua nota foi dê {}, você esta de recuperação{}'.format(cores['amarelo'], media, cores['limpa'])) else: print('{}Sua nota foi dê {}, você foi reprovado !{}'.format(cores['vermelho'], media, cores['limpa'])) print('{}Desejamos um bom dia a todos !{}'.format(cores['ciano'], cores['limpa'])) elif quantidade == 4: n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) n3 = float(input('Digite a terceira nota: ')) n4 = float(input('Digite a quarta nota: ')) media = (n1 + n2 + n3 + n4) / 4 if media >= 7: print('{}Sua nota foi dê {}, você foi APROVADO !{}'.format(cores['verde'], media, cores['limpa'])) elif media >= 5 < 7: print('{}Sua nota foi dê {}, você esta de recuperação{}'.format(cores['amarelo'], media, cores['limpa'])) else: print('{}Sua nota foi dê {}, você foi reprovado !{}'.format(cores['vermelho'], media, cores['limpa'])) print('{}Desejamos um bom dia a todos !{}'.format(cores['ciano'], cores['limpa']))
00b40818d5e09b739d65797b096994d9992b9de5
damodardikonda/Python-Basics
/roaster2.py
1,658
3.578125
4
import json import sqlite3 dbname = "roster.sqlite" conn = sqlite3.connect(dbname) cur = conn.cursor() cur.executescript(''' DROP TABLE IF EXISTS User; DROP TABLE IF EXISTS Course; DROP TABLE IF EXISTS Member; CREATE TABLE User ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Course ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE ); CREATE TABLE Member ( user_id INTEGER, course_id INTEGER, role INTEGER, PRIMARY KEY(user_id, course_id) ) ''') filename = input("enter the file nme:") if(len(filename)<1): filename="roaster_data.json" jsondata = open(filename) data = json.load(jsondata) #PART 3: INSERTING DATA for entry in data: user = entry[0] course = entry[1] instructor = entry[2] #Inserting user user_statement = """INSERT OR IGNORE INTO User(name) VALUES( ? )""" SQLparams = (user, ) cur.execute(user_statement, SQLparams) #Inserting course course_statement = """INSERT OR IGNORE INTO Course(title) VALUES( ? )""" SQLparams = (course, ) cur.execute(course_statement, SQLparams) #Getting user and course id courseID_statement = """SELECT id FROM Course WHERE title = ?""" SQLparams = (course, ) cur.execute(courseID_statement, SQLparams) courseID = cur.fetchone()[0] userID_statement = """SELECT id FROM User WHERE name = ?""" SQLparams = (user, ) cur.execute(userID_statement, SQLparams) userID = cur.fetchone()[0] #Inserting the entry member_statement = """INSERT INTO Member(user_id, course_id, role) VALUES(?, ?, ?)""" SQLparams = (userID, courseID, instructor) cur.execute(member_statement, SQLparams) conn.commit()
ac60d2a0aef3355678bc3b29500a052492be65f5
wymen98/Stemmer_vs_WordNet-NLP-
/stemming.py
2,231
3.671875
4
#Stemming #use to find out the stem of the word #PorterStemmer is the most popular Stemmer to be used from nltk.stem import PorterStemmer stemmer = PorterStemmer() print(stemmer.stem('Working')) print(stemmer.stem('Worked')) #------------------------------------------------------ #SnowballStemmer is support 13 type of language #print(SnowballStemmer.languages) #'danish', 'dutch', 'english', 'finnish', 'french', 'german', 'hungarian', 'italian', 'norwegian', 'porter', 'portuguese', 'romanian', 'russian', 'spanish', 'swedish' from nltk.stem import SnowballStemmer french_stemmer = SnowballStemmer('french') print(french_stemmer.stem("French word")) #---------------------------------- #Different between a Stemmer and WordNet stem = PorterStemmer() print(stem.stem('increases')) from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() print(lemmatizer.lemmatize('increases')) #Stemmer would find the stem(real word) #but WordNetLemmatizer would find the synonyms #--------------------------------- #Find the verb, noun, adjective and relative #This could be the best way to cut off #or can be said as minimize the scope of #the script #as you have specify what type of the #word that you want it to be find = WordNetLemmatizer() print(find.lemmatize('playing', pos='v')) print(find.lemmatize('playing', pos='n')) print(find.lemmatize('playing', pos='a')) print(find.lemmatize('playing', pos='r')) #---------------------------------------- #Difference between Stemmer and WordNet #Stemmer is faster but it does not care of the spelling #WordNet would be slower but it is accurate as it is finding #the synonym, but never get spelling wrong stemmer = PorterStemmer() lemmatizer = WordNetLemmatizer() print(stemmer.stem('stones')) print(stemmer.stem('speaking')) print(stemmer.stem('bedroom')) print(stemmer.stem('jokes')) print(stemmer.stem('lisa')) print(stemmer.stem('purple')) print('----------------------') print(lemmatizer.lemmatize('stones')) print(lemmatizer.lemmatize('speaking')) print(lemmatizer.lemmatize('bedroom')) print(lemmatizer.lemmatize('jokes')) print(lemmatizer.lemmatize('lisa')) print(lemmatizer.lemmatize('purple'))
5737255b1c47f67d729375cebea98157bf495f41
KreefS/bX6RzMFSRh
/Python Code/Told you I'd make this.py
832
3.75
4
import turtle def writing(): turtle.penup() turtle.colormode(255) turtle.color(0,255,0) turtle.goto(30,-30) turtle.pendown() turtle.write("Bitcoin be like", False, align="center", font=("Arial", 16, "normal")) turtle.penup() def graph(): turtle.color(0,0,0) turtle.goto(0,0) turtle.pendown() turtle.forward(400) turtle.goto(0,0) turtle.left(90) turtle.forward(400) turtle.goto(0,0) turtle.color(49,233,22) turtle.speed(1) turtle.right(45) turtle.forward(60) turtle.left(20) turtle.forward(400) turtle.right(130) turtle.color(255,0,0) turtle.right(10) turtle.forward(200) turtle.right(15) turtle.speed(5) turtle.forward(700) writing() graph() leave = input("Enter to exit.")
c43356b86addc1386a3dbf146b14199e14550fd3
IanSkapin/AsteroidsPygletTutorial
/game/util.py
180
3.671875
4
import math def distance(a=(0, 0), b=(0, 0)): """Returns the distance between two points""" return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
c2fb2001167731b45df07cb751ef21b1575bc306
TravisLeeWolf/ATBS
/Chapter_1/stringS.py
162
4.09375
4
# String Concatenation print('Alice + Bob') print('Alice' + 'Bob') print('Alice + 5 using str') print('Alice' + str('5')) print('Alice * 5') print('Alice' * 5)
a83ca2f770ff723b1791a35f10d372c9c9c6a7cf
zhangxl97/leetcode
/1_100/Q_11_20.py
12,297
3.703125
4
from typing import List def connect_nodes(nums): if nums != []: head = ListNode() p = head for n in nums: p.next = ListNode(n) p = p.next return head.next else: return None def print_nodes(head): # if head is not None: # print(head.val, end="") while head is not None: print(head.val, end="") head = head.next if head is not None: print("->", end="") print("\n", end="") class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: # 11. Container With Most Water def maxArea(self, height: List[int]) -> int: n = len(height) if n == 2: return min(height) left = 0 right = n - 1 container = 0 while left < right: temp = min(height[left], height[right]) * (right - left) if temp > container: container = temp if height[left] < height[right]: left += 1 else: right -= 1 return container # 12. Integer to Roman def intToRoman(self, num: int) -> str: res = "" while num > 0: if num >= 1000: res += "M" * (num // 1000) num %= 1000 elif 900 <= num < 1000: res += "CM" num -= 900 elif 500 <= num < 900: res += "D" num -= 500 elif 400 <= num < 500: res += "CD" num -= 400 elif 100 <= num < 400: res += "C" * (num // 100) num %= 100 elif 90 <= num < 100: res += "XC" num -= 90 elif 50 <= num < 90: res += "L" num -= 50 elif 40 <= num < 50: res += "XL" num -= 40 elif 10 <= num < 40: res += "X" * (num // 10) num %= 10 elif 9 <= num < 10: res += "IX" num -= 9 elif 5 <= num < 9: res += "V" num -= 5 elif 4 <= num < 5: res += "IV" num -= 4 else: res += "I" * num num = 0 return res # 13. Roman to Integer def romanToInt(self, s: str) -> int: l = len(s) - 1 dic = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} ans = 0 while l > 0: if s[l] == 'I': ans += 1 l -= 1 elif s[l] == 'V': if s[l - 1] == 'I': ans += 4 l -= 2 else: ans += 5 l -= 1 elif s[l] == 'X': if s[l - 1] == 'I': ans += 9 l -= 2 else: ans += 10 l -= 1 elif s[l] == 'L': if s[l - 1] == 'X': ans += 40 l -= 2 else: ans += 50 l -= 1 elif s[l] == 'C': if s[l - 1] == 'X': ans += 90 l -= 2 else: ans += 100 l -= 1 elif s[l] == 'D': if s[l - 1] == 'C': ans += 400 l -= 2 else: ans += 500 l -= 1 elif s[l] == 'M': if s[l - 1] == 'C': ans += 900 l -= 2 else: ans += 1000 l -= 1 if l == 0: ans += dic[s[0]] return ans # 14. def longestCommonPrefix(self, strs: List[str]) -> str: pre = "" try: n_str = len(strs) if n_str == 0: return "" elif n_str == 1: return strs[0] n = len(strs[0]) for pos in range(n): temp = strs[0][pos] for num in range(1, n_str): if strs[num][pos] == temp: continue else: return pre pre += temp except: return pre return pre # 15 3Sum def threeSum(self, nums: List[int]) -> List[List[int]]: # O(n^2) # size = len(nums) # if size < 3 or (size == 3 and sum(nums) != 0): # return [] # target = 0 # nums.sort() # res = [] # i = 0 # while i < size - 2: # t = target - nums[i] # left = i + 1 # right = size - 1 # while left < right: # if nums[left] + nums[right] == t: # res.append([nums[i], nums[left], nums[right]]) # while nums[left] == nums[left + 1] and left < right - 1: # left += 1 # left += 1 # while nums[right] == nums[right - 1] and left < right - 1: # right -= 1 # right -= 1 # elif nums[left] + nums[right] < t: # left += 1 # else: # right -= 1 # while nums[i] == nums[i + 1] and i < size - 3: # i += 1 # i += 1 # return res # O(nlogn) from bisect import bisect_left, bisect_right from collections import Counter size = len(nums) if size < 3: return [] res = [] target = 0 nums.sort() print(nums) count = Counter(nums) print(count) keys = list(count.keys()) keys.sort() if target / 3 in keys and count[target / 3] >= 3: res.append([target // 3] * 3) begin = bisect_left(keys, target - keys[-1] * 2) end = bisect_left(keys, target * 3) for i in range(begin, end): a = keys[i] if count[a] >= 2 and target - 2 * a in count: res.append([a, a, target - 2 * a]) max_b = (target - a) // 2 # target-a is remaining min_b = target - a - keys[-1] # target-a is remaining and c can max be keys[-1] b_begin = max(i + 1, bisect_left(keys, min_b)) b_end = bisect_right(keys, max_b) for j in range(b_begin, b_end): b = keys[j] c = target - a - b if c in count and b <= c: if b < c or count[b] >= 2: res.append([a, b, c]) return res # 16 3sum cloest def threeSumClosest(self, nums: List[int], target: int) -> int: size = len(nums) if size == 3: return sum(nums) bias = float('inf') res = None nums.sort() i = 0 while i < size - 2: left = i + 1 right = size - 1 while left < right: s = nums[i] + nums[left] + nums[right] if s == target: return s elif abs(s - target) < bias: res = s bias = abs(s - target) if s < target: while nums[left] == nums[left + 1] and left < right - 1: left += 1 left += 1 else: while nums[right] == nums[right - 1] and left < right - 1: right -= 1 right -= 1 while nums[i] == nums[i + 1] and i < size - 3: i += 1 i += 1 return res # 17 Letter Combinations of a Phone Number def letterCombinations(self, digits: str) -> List[str]: kv = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} size = len(digits) if size == 0: return [] elif size == 1: return list(kv[digits]) temp = [] for i in range(size): temp.append(kv[digits[i]]) words = [] next_words = self.letterCombinations(digits[1:]) for j in temp[0]: for i in next_words: words.append(j + i) return words # 18 4Sum def fourSum(self, nums: List[int], target: int) -> List[List[int]]: size = len(nums) if size < 4: return [] elif size == 4: if sum(nums) != target: return [] else: return [nums] nums.sort() res = [] i = 0 while i < size - 3: j = i + 1 while j < size - 2: left = j + 1 right = size - 1 while left < right: curr = nums[i] + nums[j] + nums[left] + nums[right] if curr == target: res.append([nums[i], nums[j], nums[left], nums[right]]) while nums[left] == nums[left + 1] and left < right - 1: left += 1 left += 1 while nums[right] == nums[right - 1] and left < right - 1: right -= 1 right -= 1 elif curr < target: while nums[left] == nums[left + 1] and left < right - 1: left += 1 left += 1 else: while nums[right] == nums[right - 1] and left < right - 1: right -= 1 right -= 1 while nums[j] == nums[j + 1] and j < size - 3: j += 1 j += 1 while nums[i] == nums[i + 1] and i < size - 4: i += 1 i += 1 return res # 19 Remove Nth Node From End of List def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: p = head size = 0 while p is not None: size += 1 p = p.next if size == n: return head.next elif size < n: return head p = head for i in range(size - n - 1): p = p.next temp = p.next p.next = temp.next temp.next = None del temp return head # 20 Valid Parentheses def isValid(self, s: str) -> bool: stack = [] for c in s: if c == '(' or c == '[' or c == '{': stack.append(c) elif c == ')': if len(stack) > 0 and stack.pop() == '(': continue else: return False elif c == ']': if len(stack) > 0 and stack.pop() == '[': continue else: return False elif len(stack) > 0 and c == '}': if len(stack) > 0 and stack.pop() == '{': continue else: return False if stack == []: return True else: return False def main(): s = Solution() # 11 # print(s.maxArea([1,100,6,2,100000,100000,8,3,7])) # 12 # print(s.intToRoman(9)) # 13 # print(s.romanToInt("MCMXCIV")) # 14 # print(s.longestCommonPrefix(["dog","racecar","car"])) # 15 # print(s.threeSum([0,0,0])) # 16 # print(s.threeSumClosest([0, 2, 1, -3], 1)) # 17 # print(s.letterCombinations("234")) # 18 # print(s.fourSum([1, 0, -1, 0, -2, 2], 0)) # 19 # head = connect_nodes([1]) # print_nodes(head) # head = s.removeNthFromEnd(head, 1) # print_nodes(head) # 20: print(s.isValid(")")) if __name__ == '__main__': main()
e1799f60ff803a226c7e8976de5d500589332b1c
pigate/py_graph_ex
/graph.py
11,552
4.21875
4
"""Python graph class, demonstrating essential facts and functionalities of graphs """ class Graph(object): def __init__(self, graph_dict={}): """initializes a graph object """ self.__graph_dict = graph_dict def vertices(self): """returns vertices of a graph""" return self.__graph_dict.keys() def edges(self): """returns edges of graph""" return self.__generate_edges() def add_vertex(self, vertex): """If vertex is not in self.__graph_dict, a key "vertex" with empty list added to dictionary. Otherwise do nothing """ if vertex not in self.__graph_dict: self.__graph_dict[vertex] = [] def add_edge(self, edge): """assumes edge is of type set, tuple of list; between 2 vertices can have multiple edges """ vertex_x, vertex_y = tuple(edge) if vertex_x in self.__graph_dict: self.__graph_dict[vertex_x].append(vertex_y) else: self.__graph_dict[vertex_x] = [vertex_y] if vertex_y in self.__graph_dict: self.__graph_dict[vertex_y].append(vertex_x) else: self.__graph_dict[vertex_y] = [vertex_x] def __generate_edges(self): """static method to generate edges of the graph. Edges are represented as sets with one (a loop back to the vertex) or two vertices sets use {} syntax """ edges = [] for vertex in self.__graph_dict: for neighbor in self.__graph_dict[vertex]: if {neighbor, vertex} not in edges: edges.append({vertex, neighbor}) return edges def __str__(self): res = "vertices: " for k in self.__graph_dict: res += str(k) + " " res += "\nedges: " for edge in self.__generate_edges(): res += str(edge) + " " return res def find_path(self, start_vertex, end_vertex, path=[]): """find path from start_vertex to end_vertex in graph """ graph = self.__graph_dict path = path + [start_vertex] if start_vertex == end_vertex: return path if start_vertex not in graph: return None for vertex in graph[start_vertex]: if vertex not in path: extended_path = self.find_path(vertex, end_vertex, path) if extended_path: return extended_path return None def find_all_paths(self, start_vertex, end_vertex, path=[]): """find all paths from start_vertex to end_vertex in graph if start_vertex == end_vertex, returns [start_vertex] if no path, returns [] """ graph = self.__graph_dict path = path + [start_vertex] paths = [] if start_vertex == end_vertex: return [path] if start_vertex not in graph: return [] for vertex in graph[start_vertex]: #check for cycle if vertex not in path: extended_paths = self.find_all_paths(vertex, end_vertex, path) for p in extended_paths: paths.append(p) return paths def find_first_cycle(self, start_vertex, path=[]): """find first cycle in graph""" graph = self.__graph_dict if start_vertex not in graph: return None #update acc if start_vertex in path: return path + [start_vertex] path = path + [start_vertex] for vertex in graph[start_vertex]: extended_path_cycle = self.find_first_cycle(vertex, path) if extended_path_cycle: return extended_path_cycle return None def vertex_degree(self, vertex): #undirected graph, or counts all outward edges #for directed graph, must go through other vertices, check if vertex appears """calculates the degree of a vertex. degree of vertex is number of edges connecting it (number of adjacent vertices). Loops are counted double. i.e. every occurance of vertex in list of adjacent vertices""" degree = 0 adj_vertices = self.__graph_dict[vertex] #count occurances of vertex in its own adj list (as double) # and other vertices degree = len(adj_vertices) + adj_vertices.count(vertex) return degree def find_isolated_vertices(self): """returns list of isolated vertices for undirected graph. """ graph =self.__graph_dict isolated = [] for vertex in graph: #if [] if not graph[vertex]: isolated.append(vertex) return isolated def delta(self): """minimum degree of vertices""" min = 0 #initialize min to degree of first vertice if len(self.__graph_dict.keys()) == 0: return min min = self.vertex_degree(self.__graph_dict.keys()[0]) for vertex in self.__graph_dict: new_min = self.vertex_degree(vertex) if new_min < min: min = new_min return min def Delta(self): """maximum degree of vertices""" max = 0 #initialize max to degree of first vertice if len(self.__graph_dict.keys()) == 0: return max max = self.vertex_degree(self.__graph_dict.keys()[0]) for vertex in self.__graph_dict: new_max = self.vertex_degree(vertex) if new_max > max: max = new_max return max """degree sequence of undirected graph is sequence of its vertex degrees in decreasing order. i.e. [5, 4, 3, 2, 1, 0, 0]""" def degree_sequence(self): """ calculates degree sequences """ seq = [] for vertex in self.__graph_dict: seq.append(self.vertex_degree(vertex)) seq.sort(reverse=True) return seq def density(self): """returns density of graph. Density is ratio of number of edges of a graph and total number of edges the graph can have. Measures how close the graph is to completed graph Every pair of vertice is connected by a unique edge For non empty graph: density = 2 * |E|/(|V|*|V-1|) dense graphs have density close to 1 sparse graphs have density close to 0 """ num_keys = len(self.__graph_dict.keys()) tot_num_edges_possible = 0 if num_keys > 0: tot_num_edges_possible = num_keys*(num_keys - 1)/2 else: return 0 num_edges = len(self.edges()) return num_edges/float(tot_num_edges_possible) def is_connected(self, vertices_encountered, start_vertex=None): """determines if graph is connected. graph is connected if every pair of verices in graph is connected""" #pick start_vertex #record which vertexes start_vertex is connected to #if that collection of vertexes == collection of total vertexes, # that vertex is connected if vertices_encountered is None: vertices_encountered = set() vertices = list(self.__graph_dict.keys()) if len(vertices) == 0: return true if not start_vertex: #choose start_vertex start_vertex = vertices[0] vertices_encountered.add(start_vertex) if len(vertices_encountered) == len(vertices): return True #check through other vertices reachable current_state = False for neighbor in self.__graph_dict[start_vertex]: #avoid checking cycles if neighbor not in vertices_encountered: current_state = current_state or self.is_connected(vertices_encountered, neighbor) return current_state def dist(self, vertex_a, vertex_b): """dist between two vertices in the graph (not counting loops) dist is length of shortest path between the two vertices. returns -1 if no path, 0 if vertex_a == vertex_b """ graph = self.__graph_dict dist = -1 if vertex_a not in graph or vertex_b not in graph: return dist #return shortest distance between the vertexes paths = self.find_all_paths(vertex_a, vertex_b, []) if len(paths) == 0: return dist min_dist = len(paths[0]) for path in paths: if len(path) < min_dist: min_dist = len(path) return min_dist def eccentricity(self, vertex): graph = self.__graph_dict eccentricity = -1 if vertex not in graph: return eccentricity for other_vertex in graph: paths = [] if other_vertex is not vertex: paths = self.find_all_paths(vertex, other_vertex, []) if len(paths) > 0: for path in paths: if len(path) > eccentricity: eccentricity = len(path) return eccentricity def diameter(self): """returns diameter of graph. diameter d of graph is defined as maximum eccentricity of any vertex in graph. eccentricity of a vertex is max distance to any other vertex graph """ max_eccentricity = 0 for node in self.__graph_dict: eccentricity = self.eccentricity(node) if eccentricity > max_eccentricity: max_eccentricity = eccentricity return max_eccentricity if __name__ == "__main__": g = { "a" : ["d"], "b" : ["c"], "c" : ["b", "c", "d", "e"], "d" : ["a", "c"], "e" : ["c"], "f" : [] } graph = Graph(g) print("Vertices of graph: ") print(graph.vertices()) print("Edges of graph: ") print(graph.edges()) print("Add vertex:") graph.add_vertex("z") print("Vertices of graph: ") print(graph.vertices()) print("Add an edge") graph.add_edge({"a", "z"}) print("Vertices of graph: ") print(graph.vertices()) print("Edges of graph: ") print(graph.edges()) print('Adding an edge {"x", "y"} with new vertices:') graph.add_edge({"x", "y"}) print("Vertices of graph: ") print(graph.vertices()) print("Edges of graph: ") print(graph.edges()) path_a_b = graph.find_path("a", "b", []) print "Path from a to b: ", print path_a_b path_a_f = graph.find_path("a", "f", []) print "Path from a to f: ", print path_a_f all_paths_a_b = graph.find_all_paths("a", "b", []) print "All paths from a to b: ", print all_paths_a_b all_paths_a_f = graph.find_all_paths("a", "f", []) print "All paths from a to f: ", print all_paths_a_f cycle_a = graph.find_first_cycle("a", []) print "Cycle from a: ", print cycle_a cycle_b = graph.find_first_cycle("b", []) print "Cycle from b: ", print cycle_b cycle_c = graph.find_first_cycle("c", []) print "Cycle from c: ", print cycle_c cycle_f = graph.find_first_cycle("f", []) print "Cycle from f: ", print cycle_f complete_graph = { "a" : ["b","c"], "b" : ["a","c"], "c" : ["a","b"] } isolated_graph = { "a" : [], "b" : [], "c" : [] } graphs = {} graphs["random"] = graph graphs["complete"] = Graph(complete_graph) graphs["isolated"] = Graph(isolated_graph) for key in graphs: graph = graphs[key] print "\n" + key.upper() + "===========" for vertex in graph.vertices(): print "Degree of " + str(vertex) + ": ", print graph.vertex_degree(vertex) isolated = graph.find_isolated_vertices() print "Isolated: ", print isolated delta = graph.delta() print "delta: ", print delta Delta = graph.Delta() print "Delta: ", print Delta deg_sequence = graph.degree_sequence() print "Degree sequence: ", print deg_sequence print "Density: ", print graph.density() print "Number of edges: ", print len(graph.edges()) print "Is our graph connected? ", print graph.is_connected(None) vertices = graph.vertices() for node_a in vertices: for node_b in vertices: if node_a is not node_b: print "dist(" + str(node_a) + ", " + str(node_b) + "): ", print graph.dist(node_a, node_b) print "eccentricity(" + str(node_a) + ") = ", print graph.eccentricity(node_a) print "diameter: ", print graph.diameter()
9c703fd4b62e8edc365623ee1967131385c092c9
weepwood/CodeBase
/Python/UseCase/字符串的格式化.py
293
3.921875
4
name = "Halo" age = 18 print("Hi, I'm %s. I'm %d" % (name, age)) print("Hi, I'm {}. I'm {}" .format(name, age)) # 括号更换对应索引 print("Hi, I'm {0}. I'm {0}. I'm {1}." .format(name, age)) # 3.6 版本 f-string 括号内可以替换为表达式 print(f"Hi, I'm {name}. I'm {age+1}")
7eaf8fe30cc748b7a787022cee4531dbd25ee320
binchen15/leet-python
/tree/trie/prob677.py
1,814
3.796875
4
# 677 Map Sum pairs using trie class MapSum(object): class Node(object): def __init__(self): self.children = {} self.val = 0 #self.isLeaf = False def __init__(self): """ Initialize your data structure here. """ self.root = self.Node() def insert(self, key, val): """ :type key: str :type val: int :rtype: None """ self._insert(key, val, self.root) def _insert(self, key, val, node): if not node: return if len(key) == 0: node.val = val #node.isLeaf = True return char = key[0] if char not in node.children: node.children[char] = self.Node() self._insert(key[1:], val, node.children[char]) def sum(self, prefix): """ :type prefix: str :rtype: int """ return self._sum(prefix, self.root) def _sum(self, prefix, node): if not node: return 0 if len(prefix) == 0: return self._sum2(node) else: char = prefix[0] if char not in node.children: return 0 else: return self._sum(prefix[1:], node.children[char]) def _sum2(self, node): """collect/sum all node.val starting from given node""" if not node: return 0 tot = node.val for char in node.children: tot += self._sum2(node.children[char]) return tot # Your MapSum object will be instantiated and called as such: # obj = MapSum() # obj.insert(key,val) # param_2 = obj.sum(prefix)
73766357be4db9a68cfedb7f19c76508b922c3e5
seven320/AtCoder
/49/C.py
711
3.546875
4
# encoding:utf-8 import copy import random import bisect #bisect_left これで二部探索の大小検索が行える import fractions #最小公倍数などはこっち import math import sys mod = 10**9+7 sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000 S = str(input()) S = list(S) S.reverse() S = "".join(S) def check(T): if len(S) == 0: return 1 adds = ["maerd","remaerd","esare","resare"] q = copy.deepcopy(adds) while len(q) > 0: t = q.pop() if t == S: return 1 for add in adds: if S[len(t):len(t+add)] == add: q.append(t+add) return 0 if check(""): print("YES") else: print("NO")
e13b6c6053309e260dad25417825735c6bd9e542
ICS3U-Programming-Layla-M/Unit4-03-Python
/power_of_two.py
1,054
4.46875
4
#!/usr/bin/env python3 # Created by: Layla Michel # Created on: May 25, 2021 # This program asks the user to input a number and then # displays the square of all numbers from 0 to that number def main(): # ask the user to input a whole number number_as_string = input("Enter a whole number: ") try: # convert from string to integer number_as_int = int(number_as_string) if (number_as_int < 0): # check if number is negative print("{} is not a whole number.". format(number_as_int)) else: # calculate the square of the numbers in range for counter in range(number_as_int + 1): square = counter ** 2 print("{0}^2 = {1}". format(counter, square)) counter = counter + 1 except ValueError: # error message print("{} is not a whole number.". format(number_as_string)) finally: # end message print("\n") print("Thanks for playing!") if __name__ == "__main__": main()
af6c26ec432482878ef4443dfdfbed6103b08b1c
VeroWrede/CodingDojo
/assignments/python/hw3.py
192
3.609375
4
# for num in range(1000): # if num % 2 == 1: # print(num) # print([num for num in range(1000000) if num%5 == 0]) a = [1, 2, 5, 10, 255, 3] print(sum(list(a))) print(sum(list(a))/len(a))
5bf2db322b4ec416c72b79ac27717c0c1baf6bc0
Rhysoshea/Algos
/Algorithmic_Toolbox/week2_algorithmic_warmup/test.py
98
4.03125
4
#python3 string = 'hydrogen' for index, letter in enumerate(string): print ((letter, index))
7a77be05d0b0a9d073e7650283e38f205115e9cf
Abhijith-1997/pythonprojects
/flow controls/flow12.py
497
4.1875
4
num1=int(input("enter the number")) num2=int(input("enter ur number")) num3=int(input("enter the number")) if(num1>num2)&(num1>num3): if(num2>num3): print("largest number",num2) else: print("largest number",num3) elif(num2>num1)&(num2>num3): if(num1>num3): print("largest number",num1) else: print("largest number",num3) elif(num3>num1)&(num3>num2): if(num1>num2): print("largest number",num1) else: print("largest number",num2)
1d44989e8088c6e8d46ec43fae48cf515b4b5940
gglee89/machine-learning
/HW5-Algorithm/divide_and_conquer.py
734
3.8125
4
def Merge(B, C, A): i = j = k = 0 p = len(B) q = len(C) while i < p and j < q: if B[i] <= C[j]: A[k] = B[i] i = i + 1 else: A[k] = C[j] j = j + 1 k = k + 1 if i == p: A[k:p+q] = C[j:q] else: A[k:p+q] = B[i:p] def FindMaxMin(numbers): lower_half = [] upper_half = [] if len(numbers) > 1: size = len(numbers) lower_half = numbers[0:size/2] upper_half = numbers[size/2:size] FindMaxMin(lower_half) FindMaxMin(upper_half) Merge(lower_half, upper_half, numbers) return numbers test = [4, 6, 2, 3, 4, 1, 8, 6, 9, 20] print(test) print(FindMaxMin(test))
53e70027da58bcc838029e6db73146dedcd78521
mayaragualberto/URIOnlineJudge
/Python/1159.py
296
3.84375
4
while 1: soma=0 X=int(input()) if X==0: break if X%2==0: for i in range(5): soma=soma+X X+=2 print(soma) elif X%2!=0: X+=1 for i in range(5): soma=soma+X X+=2 print(soma)
8f1059fdf4865428abfa315fcee8f0515713b8dc
danielcr10/python2
/pandas9/templatecorredores.py
703
3.5
4
# -*- coding: utf-8 -*- """ DataFrame Corredores """ import pandas as pd import matplotlib.pyplot as plt dfCorredores = pd.read_excel('corredores.xlsx',index_col=0,header =0,decimal ='.') print('\n1- DataFrame dfCorredores') print('\n2-index renomeado para num') print('\n3- Nome do(s) vencedor(es) da corrida e melhor tempo') print('\n4- Nomes dos corredores com melhor desempenho na corrida do que no melhor treino') print('\n5-Dataframe so com os que tiveram desempenho na corrida pior ou igual a media dos treinos') print('\n6-Nome dos corredores que tiveram a maior diferenca entre o seu melhor treino e a corrida') print('(para mais ou para menos)')
0e36f804a926299bd4473740e355acd038b1db4e
SoMuchCode/multizip
/multizip.py
3,122
3.703125
4
#!/usr/bin/env python # # multizip.py # version 0.3 # perform zip operations on multiple files and/or multiple folders. # Python 3.6 # CLM 20170117 # # USAGE: multizip.py /path/to/files/you/want/to/compress/ /optional/output/dir/ # By default output files will be created in directory where multizip is invoked. try: from distutils.archive_util import zipfile import sys, os except ImportError: print('Exception: cannot load module') print('Exiting...') sys.exit(-1) verb = 0 argcount = 0 zipp_path = '' filentmp = '' outputpath = '' win = 0 if os.name == 'nt': win = 1 def make_zipfile(base_name, base_dir): zip_filename = os.path.join(outputpath, base_name) + ".zip" zip_path = os.path.join(base_dir, base_name) # are we doing a file or a dir? if (verb > 0): print('base name:',base_name) print('base dir:',base_dir) print('zip_filename:',zip_filename) print('zip_path:',zip_path) if os.path.isdir(zip_path): # for a dir if (verb > 0): print('dir') zf = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) for folderName, subfolders, filenames in os.walk(zip_path): if verb>0: print('The current folder is ' + folderName) for subfolder in subfolders: if verb>0: print('SUBFOLDER OF ' + folderName + ': ' + subfolder) for filename in filenames: print('Compressing: ' + folderName + ' '+ filename) zipp_path = folderName.split(base_dir) zp = zipp_path[1] filentmp = os.path.join(zp,filename) zp = os.path.join(folderName,filename) zf.write(zp, filentmp) zf.close() else: # for a file if verb>0: print('file') print('Compressing: ' + zip_path) zf = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) zf.write(zip_path, base_name) zf.close() def help(): print('USAGE:') if win == 1: print(sys.argv[0],'C:\\path\\to\\files\\you\\want\\to\\compress\\ \\optional\\output\\dir\\') else: print(sys.argv[0],'/path/to/files/you/want/to/compress/ /optional/output/dir/') exit() # count arguments for arg in sys.argv: argcount += 1 if (arg == '--h' or arg == '-h' or arg == '--help' or arg == '/h' or arg == '/?'): help() if (argcount < 2 or argcount > 3): print('ERROR: You need to supply a path') help() if argcount == 3: outputpath = os.path.abspath(sys.argv[2]) if verb > 0: print(outputpath) if not os.path.isdir(sys.argv[1]): print('ERROR: I need a directory path, not a file path') help() if verb>0: print('Number of arguments:', len(sys.argv), 'arguments.') print('Argument List:', str(sys.argv),'\n') pathname = os.path.abspath(sys.argv[1]) if verb>0: print('path:',pathname) os.listdir(pathname) for ii in os.listdir(pathname): if verb>0: print('file or folder:',ii) make_zipfile(ii,pathname)
a505e862f0fa98d859186a77fce840a55fed9e64
hunthunt2010/compilers
/ToolChainDemo/PLYDemo.py
1,683
3.671875
4
#Basic Grammar for the demo language #START -> S $ #SEN -> PVQ ADJECTIVE NOUN # | PVQ NOUN #PVQ -> PRONOUN VERB QUANTITY #List Of possible tokens tokens = ( 'PRONOUN', 'VERB', 'QUANTITY', 'ADJECTIVE', 'NOUN', ) #RegEx for the tokens t_PRONOUN = r'(I|we|she|he)' t_VERB = r'(ate|made|sold|bought|threw\ away)' t_ADJECTIVE = r'(candy|chocolate|(Rice\ Krispie))' t_NOUN = r'(bars?)' t_ignore = r'[ ]' #Tokens can also be defined as a function def t_QUANTITY(t): r'\d+' t.value = int(t.value) return t # Error handling rule def t_error(t): print("Illegal character :" + str(t.value)) t.lexer.skip(1) #YACC Rules #Error Rule def p_error(t): if t is None: print("Syntax Error") return print("Syntax error at '%s'" % t.value) # GRAMMAR RULES FOR THE PARSER #Start Rule def p_START(t): 'START : SEN' print("Start:" + t[1]) t[0] = "OK" #Rule with alternate productions def p_SEN(t): '''SEN : PVQ ADJECTIVE NOUN | PVQ NOUN''' if len(t) == 4: t[0] = t[1] + t[2] + t[3] else: t[0] = t[1] + t[2] print("SEN:" + t[0]) def p_PVQ(t): 'PVQ : PRONOUN VERB QUANTITY' t[0] = t[1] + t[2] + str(t[3]) print("PVQ:" + t[0]) #Import the lexer and initilize import ply.lex as lex lex.lex() import ply.yacc as yacc parser = yacc.yacc() while True: try: s = input('Validate String > ') except EOFError: break if s == 'quit': break lex.input(s) while True: tok = lex.token() if not tok: break print(tok) print("Result Returned: " + str(parser.parse(s)))
70ef5c43bf3a1dbfe79cf265ee17b1a92ce11a7d
LorenzoVaralo/ExerciciosCursoEmVideo
/Mundo 2/Ex059.py
1,262
4.0625
4
#Crie um programa que leia dois valores e mostre um menu na tela: # [ 1 ] Somar # [ 2 ] Multiplicar # [ 3 ] Maior # [ 4 ] Novos numeros # [ 5 ] Sair do programa #Seu programa deverá realizar a operação solicitada em cada caso. menu = 4 enfeite = '-=' * 20 while menu != 5: if menu == 4: n1 = int(input('Digite um numero: ')) n2 = int(input('Digite outro numero: ')) menu = int(input(''' [ 1 ] Somar [ 2 ] Multiplicar [ 3 ] Maior [ 4 ] Novos numeros [ 5 ] Sair do programa Escolha uma opção: ''')) if menu < 1 or menu > 5: print('Erro! Escolha uma das opções entre 1 e 5.') else: print(enfeite,'\033[1;33m') if menu == 1: print('A soma entre {} e {} é {}.'.format(n1 , n2 , n1+n2)) if menu == 2: print('O produto de {} e {} é {}.'.format(n1 , n2 , n1*n2)) if menu == 3: if n1 > n2: print('O numero maior é o {}.'.format(n1)) elif n1 < n2: print('O numero maior é o {}.'.format(n2)) else: print('Os dois numeros digitados são iguais.') if menu == 5: print('SAINDO DO PROGRAMA...') print('\033[m'+enfeite)
3cdc953ef442ccc3ee2ce7dc410f8e602730ac4a
markku63/mooc-tira-s20
/Viikko_6/subtrees.py
870
4.09375
4
from collections import namedtuple def count(node): if not node: return 0 elif not node.left and not node.right: return 1 else: return 1 + count(node.left) + count(node.right) def diff(node): if not (node and (node.left or node.right)): # Tyhjä solmu tai lehti return 0 else: return max(diff(node.left), diff(node.right), abs(count(node.left) - count(node.right))) if __name__ == "__main__": Node = namedtuple("Node", ["left", "right"]) tree = Node(None,Node(Node(None,None),Node(None,None))) print(diff(tree)) # 3 tree = Node(left=Node(left=Node(left=Node(left=None, right=None), right=None), right=None), right=Node(left=Node(left=Node(left=Node(left=None, right=None), right=None), right=None), right=Node(left=Node(left=None, right=None), right=None))) print(diff(tree)) # 3
94a550e7cba888a65d250ce203c51295f53d3f3d
orionwills/python-exercises
/4.3_control_structures_exercises.py
10,047
4.40625
4
# prompt the user for a day of the week, print out whether the day is Monday or not day_chosen = input('Choose a day of the week: ') if day_chosen == 'Monday': print(day_chosen) # 2. prompt the user for a day of the week, print out whether the day is a weekday or a weekend day_chosen = input('Choose a day of the week: ') if day_chosen == 'Saturday' or day_chosen == 'Sunday': print('This is a weekend.') else: print('This is a weekday.') weekend_days = ['saturday', 'sunday', 'sat', 'sun'] weekday = input('Enter a weekday: ') if weekday.lower() in weekend_days: print('Weekend') else: print('Weekday') # 3. create variables for # # - the number of hour worked in one week # - the hourly rate # - how much the week's paycheck will be # write the python code that calculates the weekly paycheck. You get paid time # and a half if you work more than 40 hours weekly_hours_worked = int(input('How many hours did you work? \n')) hourly_rate = float(input('What is your hourly rate? \n')) if weekly_hours_worked > 40: overtime_hours = weekly_hours_worked - 40 weekly_hours_worked = 40 else: overtime_hours = 0 print(f'Your paycheck should be ${(weekly_hours_worked * hourly_rate) + ((1.5 * hourly_rate) * overtime_hours)}.') # 2. Loop Basics # While # Create an integer variable i with a value of 5. # Create a while loop that runs so long as i is less than or equal to 15 # Each loop iteration, output the current value of i, then increment i by one. # Your output should look like this: # 5 6 7 8 9 10 11 12 13 14 15 i = 5 while i <= 15: print(i) i += 1 # Create a while loop that will count by 2's starting with # 0 and ending at 100. Follow each number with a new line. i = 0 while i <= 100: print(i) i += 2 # Alter your loop to count backwards by 5's from 100 to -10. i = 100 while i >= -10: print(i) i -= 5 #Create a while loop that starts at 2, and displays the number squared # on each line while the number is less than 1,000,000. i = 2 while i < 1_000_000: print(i) i = i * i # Write a loop that uses print to create the output shown below for i in range(100, 0, -5): print(i) # For Loops #Write some code that prompts the user for a number, then shows # a multiplication table up through 10 for that number. user_number = int(input('Enter a number: ')) i = 1 for x in range(i, 11): print(f'{user_number} x {i} = {user_number * x}') i += 1 #Create a for loop that uses print to create the output shown below. # 1 # 22 # 333 # 4444 # 55555 # 666666 # 7777777 # 88888888 # 999999999 i = 1 for x in range(i, 10): print(f'{i}' * i) i+= 1 #break and continue # Prompt the user for an odd number between 1 and 50. Use a loop # and a break statement to continue prompting the user if they # enter invalid input. (Hint: use the isdigit method on strings # to determine this). Use a loop and the continue statement to # output all the odd numbers between 1 and 50, except for the # number the user entered. user_input = input('Please enter an odd number between 1 and 50 \n') for o in user_input: if int(user_input) < 1 or int(user_input) > 50 or int(user_input) % 2 != 0 or not user_input.isdigit(): user_input = input('Not a valid number, try again. Enter an odd number between 1 and 50 \n') else: for p in range(1, 51): print(p) if p % 2 == 0: break else: if p == user_input: break user_input = input('Enter an odd number between 1 and 50: ') while not user_input.isdigit() or int(user_input) > 50 or int(user_input) < 1 or int(user_input) % 2 == 0: user_input = input('Not a valid number, try again. Enter an odd number between 1 and 50 \n') user_input = int(user_input) print(f'Number to skip is: {user_input}\n') for p in range(51): if p == user_input: print(f'Yikes! Skipping number: {p}') continue if p % 2 == 0: continue print(f'Here is an odd number: {p}') # 1. The input function can be used to prompt for input # and use that input in your python code. Prompt the user # to enter a positive number and write a loop that counts # from 0 to that number. (Hints: first make sure that the # value the user entered is a valid number, also note that the # input function returns a string, so you'll need to convert # this to a numeric type.) user_number = int(input('Enter a positive number: ')) if user_number > 0: for n in range(0,user_number): print(n) else: print(f'{user_number} is not a positive number.') # Write a program that prompts the user for a positive integer. # Next write a loop that prints out the numbers from the number # the user entered down to 1. user_number = int(input('Enter a positive number: ')) if user_number > 0: for n in range(user_number,0,-1): print(n) else: print(f'{user_number} is not a positive number.') # Fizzbuzz # One of the most common interview questions for entry-level programmers # is the FizzBuzz test. Developed by Imran Ghory, the test is designed # to test basic looping and conditional logic skills. # Write a program that prints the numbers from 1 to 100. # For multiples of three print "Fizz" instead of the number # For the multiples of five print "Buzz". # For numbers which are multiples of both three and five print "FizzBuzz". for number in range(101): if number % 3 == 0 and number % 5 == 0: print('FizzBuzz') elif number % 3 == 0: print('Fizz') elif number % 5 == 0: print('Buzz') else: print(number) # This is the most versatile version: for n in range(1,101): output = '' if n % 3 == 0: output += 'Fizz' if n % 5 == 0: output += 'Buzz' if n % 7 == 0: output += 'Bang' # # if/else in one line # print(n if output == '' else output) # if output == '': # print(n) # else: # print(output) # SCREW YOU CONDITIONALS def fizzbuzz(n): fizzes = [1, 0, 0] buzzes = [2, 0, 0, 0, 0] words = [None, "Fizz", "Buzz", "FizzBuzz"] for i in range(1, n): words[0] = i print(words[fizzes[i%3] + buzzes[i%5]]) fizzbuzz(100) # Display a table of powers. # Prompt the user to enter an integer. # Display a table of squares and cubes from 1 to the value entered. # Ask if the user wants to continue. # Assume that the user will enter valid data. # Only continue if the user agrees to. user_number = input('What number would you like to go up to? ') int_user_number = int(user_number) user_number_squared = int_user_number * int_user_number user_number_cubed = int_user_number ** int_user_number print('Here are your numbers!\n') print('number | squared | cubed') print('------ | ------- | -----') for i in range(1,int_user_number + 1): print(f'{i:<6} | {i ** 2:<7} | {i ** 3:<5}') # Convert given number grades into letter grades. # Prompt the user for a numerical grade from 0 to 100. # Display the corresponding letter grade. # Prompt the user to continue. # Assume that the user will enter valid integers for the grades. # The application should only continue if the user agrees to. # Grade Ranges: # A : 100 - 88 # B : 87 - 80 # C : 79 - 67 # D : 66 - 60 # F : 59 - 0 # a =[] # for i in range(88,99): # a.append(i) # x = 92 #placeholder; will change to input later # if x in a: # print('yes') # else: # print('no') grade_test = { 'A+': [99,100], 'A': [90,98], 'B+': [88,89], 'B': [80,87], 'C+': [78,79], 'C': [67,77], 'D+': [65,66], 'D': [60,64], 'F': [0,59] } user_grade = int(input('Please enter a numerical grade from 80 to 100: ')) for grade_key in grade_test.keys(): upper_bound = grade_test[grade_key][1] lower_bound = grade_test[grade_key][0] if user_grade >= lower_bound and user_grade <= upper_bound: print('Your grade is:',grade_key) continue_loop = 'yes' while continue_loop == 'yes': user_grade = input('Please enter a numerical grade from 0 to 100: ') ugrade = int(user_grade) if ugrade >= 99: grade_letter = 'A+' elif ugrade >= 88: grade_letter = 'A' elif ugrade >= 86: grade_letter = 'B+' elif ugrade >= 80: grade_letter = 'B' elif ugrade >= 78: grade_letter = 'C+' elif ugrade >= 67: grade_letter = 'C' elif ugrade >= 65: grade_letter = 'D+' elif ugrade >= 60: grade_letter = 'D' else: grade_letter = 'F' print(f'Your grade letter is: {grade_letter}') continue_loop = input('Would you like to check another grade? (yes/no) ') #6. Create a list of dictionaries where each dictionary represents # a book that you have read. Each dictionary in the list should # have the keys title, author, and genre. Loop through the list # and print out information about each book. #Prompt the user to enter a genre, then loop through your books # list and print out the titles of all the books in that genre. books = [ { 'title': '12 Rules for Life', 'author': 'Jordan Peterson', 'genre': 'self-help' }, { 'title': 'Panda Bear Panda Bear', 'author': 'Eric Carle', 'genre': 'children' }, { 'title': 'Jurassic Park', 'author': 'Michael Crichton', 'genre': 'fiction' }, { 'title': 'Test Book', 'author': 'Testy McTesterson', 'genre': 'fiction' } ] g_list = [] for book in books: if book['genre'] in g_list: continue else: g_list.append(book['genre']) user_genre = input(f'Which genre would you like to search for? \n{g_list} ') print('Here are the books with the genre of: ', user_genre) for list in books: if user_genre == list['genre']: print('- title: {}'.format(list['title'])) print('- author: {}'.format(list['author'])) print('- genre: {}'.format(list['genre'])) print('\n')
3249ab22180267b47eef216486990b187e47efda
abhijitsahu/python
/project-02/forms.py
2,166
3.609375
4
""" pip install flask - WTF for WT forms writing Python classes that will be representative of our forms And then they will automatically be converted in the HTML forms within our template """ from flask_wtf import FlaskForm from wtforms import StringField, IntegerField, PasswordField, SubmitField from wtforms.validators import DataRequired, Length, Email, EqualTo """ we wanted to create a registration form then we can create a registration form class. And this will inherit from flask form. Now within our form we're going to have different form fields and these form fields are all going to be imported classes as well. imported from wtf packages not flask packages 'Username' - Label String Field html validators - does vaidation (string cant empty and 2-50 char long string) """ class RegistrationForm(FlaskForm): # few limitations that we want to put in place # So first of all we want to make sure they actually put something for # their username and just don't leave it empty or blank # we wouldn't want a user to be able to create a username 2-20 char long # Validators are also going to be classes that we import so to make sure # a field isn't empty # DataRequired : says can't be empty fields # Length 2-20 char long name_of_student = StringField( 'Name of student', validators=[DataRequired(), Length(min=2, max=20)] ) roll_number = IntegerField( 'Roll Number', validators=[DataRequired(), Length(min=10, max=12)] ) batch_name = StringField( 'Batch Name', validators=[DataRequired(), Length(min=5, max=20)] ) fathers_name = StringField( 'Fathers Name', validators=[DataRequired(), Length(min=2, max=20)] ) email = StringField( 'Email', validators=[DataRequired(), Email()] ) password = PasswordField('Password', validators=[DataRequired()]) confirm_password = PasswordField( 'confirm_password', validators=[DataRequired(), EqualTo('password')] ) submit = SubmitField('Sign up')
390add4ba278696cfa27726885e35104eac56f1a
beentaken/sgt
/misc/puzzles/takecard.py
2,441
3.8125
4
#!/usr/bin/env python # Posted on rec.puzzles early in the morning of 2006-10-08: # # 1000 cards numbered 1 to 1000 are shuffled. # One card at a time is dealt. # You can take or leave each card as it is dealt. # After you have taken your first card, you can only take a card if it is # higher than the last one you took. # The aim is to take as many as you can. # # You are free to note dealt cards, use computers, charts, tables or # chicken entrails to decide on action for each card as it comes. # # How many could you expect to take? from rational import Rational take = {} fn = {0:0} fact = 1 for n in range(1,1001): # We now model the situation in which there are n cards # remaining in the deck _that we can take_. The expected number # of cards we can take with optimal play from this position is # fn[n]. # We completely ignore all the cards we _can't_ take; they are # discarded from the deck as soon as they are dealt and we # don't get to make a choice about them. So there are n # possible _interesting_ cards which could come up next. We # iterate over each of them. expsum = 0 mult = 1 smallesttakek = None for k in range(n-1,-1,-1): # k is the index of the card turned up, counting from 0 at # the top. In other words, if we take this card, there will # be k remaining cards we can take. Therefore, our expected # gain by taking this card will be 1 + fn[k]. takegain = fact + fn[k] * mult mult = mult * k # If we _don't_ take this card, then there will be n-1 # cards we can take, for which our expected gain is fn[n-1]. dropgain = fn[n-1] #print "!", n, k, takegain, dropgain # Whichever of those gives us the bigger expected gain, we # do. if takegain > dropgain: expgain = takegain take[(n,k)] = 1 smallesttakek = k else: expgain = dropgain take[(n,k)] = 0 expsum = expsum + expgain fact = fact * n # Having summed the expected gains from all possible deals, we # now divide by n to find the _average_ expected gain. exp = expsum # And store it in the fn array. fn[n] = exp print n, smallesttakek, 1 + n - smallesttakek, Rational(exp,fact).decrep(20) #print n, fn[n] #tk = take.keys() #tk.sort() #for t in tk: # print t, take[t]
29752f8274d1c7ab48c9c3db01398fb83fe56ee2
aneesh786/Machine-Learning
/Albania suicide analysis - machine learning.py
2,969
3.59375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns #####input file###### df = pd.read_csv('C:\Aneesh\Kaggle\suicide-rates-overview-1985-to-2016\master.csv') #####Input File for Albania Only####### Albania = df[df.country == 'Albania'] ###Remove the column 'HDI for year'#### Albania.drop("HDI for year", axis=1, inplace=True) Albania.groupby('generation').size() Albania.groupby('sex').size() suicide = Albania['suicides_no'] Albania.sex.replace(['male','female'],['1','0'], inplace=True) gdp_capita = Albania['gdp_per_capita ($)'] sns.countplot(df['age']) sns.countplot(Albania['age'],hue=Albania['sex'])##Not much predictions sns.countplot(suicide,hue=Albania['sex']) ##shows suicide is higher in Men compared to Women Albania.info() Albania.drop("country-year", axis=1, inplace=True) x = Albania[['year','age','population','suicides/100k pop','gdp_per_capita ($)']] y = Albania['suicides_no'] x.rename(columns={' gdp_for_year ($) ':'gdp_year'},inplace=True) x.rename(columns={'gdp_per_capita ($)':'gdp_capita'},inplace=True) #########Feature Scaling########### x.population = x.population / 100000 x.gdp_capita = x.gdp_capita / x.gdp_capita.max() x.age.replace(['5-14 years','15-24 years','25-34 years','35-54 years','55-74 years','75+ years'],['0','1','2','3','4','5'],inplace=True) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 45) print(x_train.shape) print(y_train.shape) print(x_test.shape) print(y_test.shape) from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score model = LinearRegression() model.fit(x_train, y_train) y_pred = model.predict(x_test) mse = np.mean((y_test - y_pred)**2) print("MSE :", mse) rmse = np.sqrt(mse) print("RMSE :", rmse) r2 = r2_score(y_test, y_pred) print("r2_score :", r2) from sklearn.ensemble import RandomForestRegressor # creating the model model = RandomForestRegressor() # feeding the training data into the model model.fit(x_train, y_train) # predicting the test set results y_pred = model.predict(x_test) # calculating the mean squared error mse = np.mean((y_test - y_pred)**2) print("MSE :", mse) # calculating the root mean squared error rmse = np.sqrt(mse) print("RMSE :", rmse) #calculating the r2 score r2 = r2_score(y_test, y_pred) print("r2_score :", r2) from sklearn.tree import DecisionTreeRegressor # creating the model model = DecisionTreeRegressor() # feeding the training data into the model model.fit(x_train, y_train) # predicting the test set results y_pred = model.predict(x_test) # calculating the mean squared error mse = np.mean((y_test - y_pred)**2) print("MSE :", mse) # calculating the root mean squared error rmse = np.sqrt(mse) print("RMSE :", rmse) #calculating the r2 score r2 = r2_score(y_test, y_pred) print("r2_score :", r2)
7544394599205d8177e3913faef9e679952f121f
lotabout/leetcode-solutions
/240-search-a-2d-matrix-ii.py
1,323
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://leetcode.com/problems/search-a-2d-matrix-ii/description/ class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix: return False rows = len(matrix) cols = len(matrix[0]) return self.search(matrix, 0, rows-1, 0, cols-1, target) def search(self, matrix, rt, rb, cl, cr, target): if rt > rb or cl > cr: return False rm = (rt + rb) // 2 cm = (cl + cr) // 2 if matrix[rm][cm] == target: return True elif matrix[rm][cm] < target: # right half, bottom left region = [(rt,rb,cm+1,cr), (rm+1,rb,cl,cm)] return any([self.search(matrix, rt, rb, cl, cr, target) for rt, rb, cl, cr in region]) else: # top half, bottom left region = [(rt,rm-1,cl,cr), (rm,rb,cl,cm-1)] return any([self.search(matrix, rt, rb, cl, cr, target) for rt, rb, cl, cr in region]) matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]] solution = Solution() assert solution.searchMatrix(matrix, 5) assert not solution.searchMatrix(matrix, 20)
a1ead97cf9eb5fbf75556d2759bff6f02168e05b
han8909227/data-structures
/src/binheap.py
1,788
4.03125
4
"""Binheap data structure.""" class Binheap(object): """Binheap class for min heap.""" def __init__(self, iterable=None): """Will init a new instance of the min heap.""" self.size = 0 self.list = [None] def push(self, data): """Will push a value into the Binheap class.""" self.list.append(data) self.size += 1 self._perc_up(self.size) def _swap(self, a, b): """Swap function for swapping parent and child(internal use).""" self.list[a], self.list[b] = self.list[b], self.list[a] def _perc_up(self, i): """Bubble up the heap.""" while i // 2 > 0: if self.list[i] < self.list[i // 2]: tmp = self.list[i // 2] self.list[i // 2] = self.list[i] self.list[i] = tmp i = i // 2 def _perc_down(self, i): """Bubble down the heap.""" while (i * 2) <= self.size: min_child = self._min_child(i) if self.list[i] > self.list[min_child]: temp = self.list[i] self.list[i] = self.list[min_child] self.list[min_child] = temp i = min_child def _min_child(self, i): """Find the min child amount all children.""" if i * 2 + 1 > self.size: return i * 2 else: if self.list[i * 2] < self.list[i * 2 + 1]: return i * 2 else: return i * 2 + 1 def pop(self): """Pop from the heap.""" if self.size == 0: raise IndexError root_val = self.list[1] self.list[1] = self.list[self.size] self.size -= 1 self.list.pop() self._perc_down(1) return root_val
e420bf626f0933266134afdff89da5e519f4e096
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/thmjad002/question4.py
662
3.828125
4
"""Assignment 5, Question 4 Jadon Thomson 2014-04-14""" import math def graph_f(): function = input("Enter a function f(x):\n") for y in range (10,-11,-1): for x in range (-10,11): function_value = eval(function) function_value = round(function_value) if function_value == y: print("o",end='') elif x == 0 and y == 0: print("+",end='') elif x == 0: print("|",end='') elif y == 0: print("-",end='') else: print(" ",end='') print(" ") graph_f()
56e9249a8ba83e40fd0277f98b0fba0c3b5d6c95
DudeNr33/zerosegWeatherClock
/src/zerosegWeatherClock.py
3,714
3.5
4
""" 07.11.2016 Andreas Finkler Main module to run the raspiClock. """ # change this later import sys sys.path.append('/home/pi/programming/raspiClock') import threading import time from datetime import datetime import RPi.GPIO as GPIO from src.weather import Weather from src.display import Display DEFAULT_UPDATE_INTERVAL = 0.1 # delay in seconds between view updates DEFAULT_VIEW_DISPLAY_TIME = 5.0 # time to display a view in seconds before it switches back to the default view # Constants defining the views VIEW_TOTAL_NUMBER = 4 # total amount of available views VIEW_INDEX_TIME = 0 VIEW_INDEX_DATE = 1 VIEW_INDEX_TEMPERATURE_FORECAST = 2 VIEW_INDEX_TEMPERATURE_CURRENT = 3 # Constants for GPIO pins SWITCH_1 = 17 SWITCH_2 = 26 class ZerosegWeatherClock(object): def __init__(self): self.timer = None self.viewIndex = 0 # defines which info will be displayed self.weather = Weather() self.display = Display() self._setupButtons() def _setupButtons(self): GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers GPIO.setup(SWITCH_1, GPIO.IN) GPIO.setup(SWITCH_2, GPIO.IN) def _resetViewIndex(self): """ Reset the viewIndex to 0 ( = time and date) and the timer to None. """ self.timer = None self.viewIndex = 0 self.display.clear() self.updateView() # call the updateView method directly so the changes are displayed immediately. def _incrementViewIndex(self): """ Increment the viewIndex to switch to the next view. """ if self.timer is not None: self.timer.cancel() self.viewIndex += 1 self.viewIndex = self.viewIndex % VIEW_TOTAL_NUMBER # overflow self.timer = threading.Timer(DEFAULT_VIEW_DISPLAY_TIME, self._resetViewIndex) self.timer.start() self.display.clear() self.updateView() # call the updateView method directly so the changes are displayed immediately. def _updateDateTime(self): self.display.writeDateAndTime(datetime.now()) def _updateTime(self): self.display.writeTime(dateTimeObject=datetime.now()) def _updateDate(self): self.display.writeDate(dateTimeObject=datetime.now()) def _updateTemperatureForecast(self): temperature = self.weather.getForecastTemperature() self.display.writeTemperatureLowHigh(tempLow=temperature.min, tempHigh=temperature.max) def _updateCurrentTemperature(self): temperature = self.weather.getCurrentTemperature() self.display.writeTemperatureCurrent(temp=temperature.current) def updateView(self): """ Update the current view. """ # check the viewIndex and call the corresponding function if self.viewIndex == VIEW_INDEX_TIME: self._updateTime() elif self.viewIndex == VIEW_INDEX_DATE: self._updateDate() elif self.viewIndex == VIEW_INDEX_TEMPERATURE_FORECAST: self._updateTemperatureForecast() elif self.viewIndex == VIEW_INDEX_TEMPERATURE_CURRENT: self._updateCurrentTemperature() def main(self): while True: try: if not GPIO.input(SWITCH_1) or not GPIO.input(SWITCH_2): self._incrementViewIndex() self.updateView() time.sleep(DEFAULT_UPDATE_INTERVAL) except KeyboardInterrupt: # self._incrementViewIndex() # continue self.display.clear() raise if __name__=='__main__': ZerosegWeatherClock().main()
6f6cf2268bbdf4f1fa542112a910bd2c5d746966
nathancmoore/code-katas
/digital_root/test_root.py
1,026
3.546875
4
"""Test the functionality of digital_root.""" import pytest from root import digital_root def test_basic(): """Basic unit tests provided by codewars.""" assert digital_root(16) == 7 assert digital_root(195) == 6 assert digital_root(992) == 2 assert digital_root(999999999999) == 9 assert digital_root(167346) == 9 assert digital_root(0) == 0 def test_output_exists(): """Test that an output exists.""" assert digital_root(2456) is not None def test_output_type(): """Test that the output is the type expected.""" assert type(digital_root(35)) is int def test_inputs_are_needed(): """Test that the function will throw an error without inputs.""" with pytest.raises(TypeError): digital_root() def test_only_nums_are_valid_inputs(): """Test that only ints are valid inputs.""" bad_inputs = [["boop", "boink"], 99.99, {"one": 2, "three:": 4}] for input in bad_inputs: with pytest.raises(ValueError): digital_root(bad_inputs)
79d283652ae4bc3572785c9b820edd1ff908dab2
i-m-alok/Project1
/Problem1/problem_1.py
6,387
3.796875
4
#used the doubly linked list so the put operation can be easy for us. class Node: def __init__(self, key, value): self.key=key self.value=value self.next=None self.prev=None #doublylinkedlist class I defined only those methods which are needed for LRU_Cache class DoublyLinkedList: def __init__(self): self.head=None self.tail=None self.no_of_ele=0 def insert(self, key, value): if self.head is None: node=Node(key, value) self.head=node self.tail=node self.no_of_ele+=1 return self.head node=Node(key, value)#create the node node.next=self.head #node points the head self.head.prev=node #now head.prev points to node self.head=node #make to node head self.no_of_ele+=1 return self.head #update the value of head node def update(self, value): self.head.value=value def get_tail_key(self): return self.tail.key def delete_tail(self): self.tail=self.tail.prev self.tail.next=None self.no_of_ele-=1 '''This method helps to remove the node which is present in head and tail''' def delete_middle(self, node): ptr=self.head while(ptr!=node): ptr=ptr.next left_ptr=ptr.prev right_ptr=ptr.next left_ptr.next=right_ptr right_ptr.prev=left_ptr self.no_of_ele-=1 #-------------------------------------------------------------------------- class LRU_Cache: def __init__(self, capacity): # Initialize class variables self.capacity=capacity #the capacity of the cache self.cache=DoublyLinkedList() self.lookup_dict=dict() #used dictionary because of faster lookups def get(self, key): # if self.capacity==0: # return "You can't access anything from queue because Capacity of queue is Zero(0)" # The cases where the searched key is not present in the cache, so it returns -1 if not self.lookup_dict.get(key) or self.lookup_dict[key]==-1: return -1 #Get the value corresponding to key and put this node on the first position value=self.lookup_dict[key].value self.put(key,value) return value def put(self, key, value): #edge case if capacity is empty if self.capacity==0: return "You can't add anything to queue because Capacity of queue is Zero(0)" # if the key appeared before and present in the cache if self.lookup_dict.get(key) and self.lookup_dict[key]!=-1: node=self.lookup_dict[key] #if that node is at front the we only need to change its value and doesn't need any extra operation if node==self.cache.head: self.cache.update(value) return #if that node is present at tail so, we only need to detach the last node and #shift the tail left side and insert that node in the front by using insert() function elif node==self.cache.tail: self.cache.delete_tail() self.lookup_dict[key]=self.cache.insert(key,value) return #else the node is somewhere in cache except the head and tail, so we just remove it from the cache #and place it at head using insertFirst() function self.cache.delete_middle(node) self.lookup_dict[key]=self.cache.insert(key,value) #and insert node at first return #if key is newly introduced to cache #if the current length of cache is less the maximum capacity, then follow these steps if self.cache.no_of_ele+1<=self.capacity: node=self.cache.insert(key, value) self.lookup_dict[key]=node #and initialize that key, value pair into lookup_dict return #If the cache is at capacity remove the oldest item. index=self.cache.get_tail_key()#index is the key which is now going to detach from cache self.lookup_dict[index]=-1 # set the value of removed index to -1 so, it is easy to keep track that no node is connected to it self.cache.delete_tail() #detach the tail #now simply add the key, value pair by calling insert() self.lookup_dict[key]=self.cache.insert(key, value) return our_cache = LRU_Cache(5) our_cache.put(1, 1); our_cache.put(2, 2); our_cache.put(3, 3); our_cache.put(4, 4); print(our_cache.get(1)) # returns 1 print(our_cache.get(2)) # returns 2 print(our_cache.get(9)) # returns -1 because 9 is not present in the cache our_cache.put(5, 5) our_cache.put(6, 6) print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry #------------------------------------------------------------------------- #Test case1 our_cache = LRU_Cache(5) our_cache.put(1, 1); our_cache.put(2, 2); our_cache.put(3, 3); our_cache.put(4, 4); print("_________TEST CASE 1_________________") print(our_cache.get(1)) # returns 1 print(our_cache.get(2)) # returns 2 print(our_cache.get(9)) # returns -1 because 9 is not present in the cache our_cache.put(5, 5) our_cache.put(6, 6) print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry # Corner cases 1. #What if the node is already occured once but didn't present in the LRU_cache #and now we need to add it our_cache.put(3,3) #-------------------------------------------------- #Test case 2 print("_________TEST CASE 2_________________") new_cache = LRU_Cache(3) new_cache.put(1, "A") new_cache.put(2, "L") new_cache.put(3, "O") new_cache.put(4, "K") print(new_cache.get(2)) print(new_cache.get("O")) new_cache.put(5, "M") print(new_cache.get(1)) print(new_cache.get(4)) print(new_cache.get(2)) #---------------------------------------------------------- #testcase 3 print("_________TEST CASE 3_________________") fee_queue=LRU_Cache(4) fee_queue.put(1,"ALOK") fee_queue.put(2,"AMAN") fee_queue.put(1,"ANJALI") print(fee_queue.get(1)) fee_queue.put(3,"ABHISHEK") fee_queue.put(4,"ANKITA") fee_queue.put(5,"RASHMI") print(fee_queue.get(2)) print("_________EDGE CASE _________________") zero_capacity=LRU_Cache(0) print(zero_capacity.get(0))
a2d59a496987f1b88679eebdcd77e7a414cb6ad7
AkhtemWays/Algorithms-and-data-structures-coursera-specialization
/Algorithms on graphs/dijkstra.py
2,378
3.90625
4
#Uses python3 # Problem Description: Task: Given an directed graph with positive edge weights and with n vertices and m edges as well as two # vertices u and v, compute the weight of a shortest path between u and v (that is, the minimum total weight of a path from u to v). # Input Format: A graph is given in the standard format. The next line contains two vertices u and v. # Constraints: 1 ≤ n ≤ 10**4, 0 ≤ m ≤ 10**5, u ̸= v, 1 ≤ u,v ≤ n, edge weights are non-negative integers not exceeding 103. # Output Format: Output the minimum weight of a path from u to v, or −1 if there is no path # Memory Limit: 512MB # Sample 1: Input: 4 4 # 1 2 1 # 4 1 2 # 2 3 2 # 1 3 5 # 1 3 # Output: 3 # Sample 2: Input: 5 9 # 1 2 4 # 1 3 2 # 2 3 2 # 3 2 1 # 2 4 2 # 3 5 4 # 5 4 1 # 2 5 3 # 3 4 4 # 1 5 # Output: 6 # The following algorithm uses priority queue data structure and supports 1-based indexing for the nodes given import sys import queue def Relaxation(u, v, w, dist, q): if dist[v] > dist[u] + w: dist[v] = dist[u] + w q.put(v) def Dijkstra(adj, cost, s, t, n): q = queue.PriorityQueue() dist = [float('inf') for _ in range(n+1)] # basically range is n+1 is in order to secure 1-based indexing ignoring 0 index dist[s] = 0 # initialize starting node with 0 q.put(s) while not q.empty(): u = q.get() for v,w in zip(adj[u], cost[u]): # maps the incoming edges from u towards v and the corresponding weights Relaxation(u, v, w, dist, q) # if dist[t] == float('inf'): # if t's node was not reached return -1 return dist[t] if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n, m = data[0:2] data = data[2:] edges = list(zip(zip(data[0:(3 * m):3], data[1:(3 * m):3]), data[2:(3 * m):3])) data = data[3 * m:] adj, cost = {}, {} for i in range(1, n+1): adj[i], cost[i] = [], [] for ((a, b), w) in edges: adj[a].append(b) cost[a].append(w) s, t = data[0], data[1] print(Dijkstra(adj, cost, s, t, n))
a3b26b9bab8f0b7002b47b3188b80a4945673f25
kmarguerite/hello-pluto
/hw10.py
3,651
4.125
4
#!usr/bin/env Python 3 """ Hangman Game! This script will play a game of hangman against the computer! To run this script from the commandline type python hw10.py Assumptions: Everyone loves Harry Potter Requirements: Anaconda Python3 random """ from random import randint # create a hangman class, use set_up and init in order to start the gameplay class Hangman_Game(): #initialize the game, set up a word bank, set up 'game art' #the initialize function outputs def __init__(self): self.words = ["wizard", "potions", "herbology", "wand", "quidditch", "quaffle", "owlry", "accio", "cauldron", "mandrake", "basilisk", "dragon", "charms"] self.art = [" ————\n |\n |\n |\n——————", " ————\n O |\n |\n |\n——————", " ————\n O |\n / |\n |\n——————", " ————\n O |\n / \ |\n |\n——————", " ————\n O |\n /|\ |\n |\n——————", " ————\n O |\n /|\ |\n / |\n——————", " ————\n 0 |\n /|\ |\n / \ |\n——————"] # self.printFile() self.set_up() #create a function to set up including welcome message and counters and variables, printing functions. def set_up(self): print("Hi! Welcome to Harry Potter Hangman!") #randomly select a word from list in init self.selected_word = self.words[randint(0, 13)] self.blank_word = [] for x in self.selected_word: self.blank_word.append("*") #initialize counters and set at 0 self.current_art = 0 self.correct_letters = 0 print(self.art[0]) print(''.join(self.blank_word)) self.get_letter() return(self.selected_word) #create a function for guesses from user input, which are characters. Outputs continue guessing loop, winning, and losing def guess(self, letter): letter_occurrences = self.selected_word.count(letter) if letter_occurrences > 0: previous_occurrence = 0 for occurrence in range(0, letter_occurrences): letter_location = self.selected_word.find(letter, previous_occurrence) self.blank_word[letter_location] = letter previous_occurrence = letter_location + 1 print(self.art[self.current_art]) print(''.join(self.blank_word)) #print message for the winner! self.correct_letters += letter_occurrences if self.correct_letters == len(self.selected_word): print("\nCongratulations, You Win!") else: self.get_letter() #print message if game is lost else: self.current_art += 1 if self.current_art < 7: print(self.art[self.current_art]) if self.current_art == 6: print("Game Over! The correct word was '{}'".format(self.selected_word)) else: print(''.join(self.blank_word)) self.get_letter() # create a function to get letter guesses through user input def get_letter(self): user_input = "" while (len(user_input) != 1): user_input = input("Guess a letter.\n").lower() print(user_input) self.guess(user_input) Hangman_Game() # write hangman word to a file #returns error message that selected_word is not defined f = open("hangman.txt", "w+") f.write("Yout HP Hangman word was {}".format(selected_word)) f.close()
875de887f7d109da692602f3879d5bfbf648c6df
DriveCurrent/hiring-challenge
/db.py
1,933
3.75
4
from datetime import timedelta from random import sample, randint class DataBase(object): """ Object emulating a database of metrics stored by dates_in_range Example ------- >>> from datetime import date >>> db = DataBase() >>> db.get_data('unique_visitors', date(2015, 1, 1), date(2015, 1, 15)) [[date(2015, 1, 1), 5], [date(2015, 1, 6), 5], [date(2015, 1, 9), 25]] >>> db.get_data('invalid', date(2015, 1, 1), date(2015, 1, 15)) Exception: ValueError('Requested invalid column from database') """ valid_metrics = {'unique_visitors', 'page_views', 'visits'} def get_data(self, metric_id, start_date, end_date): """ Returns data for the requested metric between the start and end date Note: Data may not be available for all days Params ------ metric_id: string one of the `valid_metrics` start_date: datetime.date end_date: datetime.date Returns ------- [[datetime.date, int], ...] """ if metric_id not in self.valid_metrics: raise ValueError('Requested invalid column from database') # Get the distance in days between start and end date delta_days = (end_date - start_date).days + 1 # Generate a list of all the dates in between start and end dates_in_range = [ (start_date + timedelta(day)) for day in xrange(delta_days) ] # Make a list by choosing a random number of dates from the list # simulating that the database will not always have data # for certain dates dates_in_range = sample(dates_in_range, randint(0, delta_days)) # Make rows of data for the dates were selected with the data being # a random integer between 0 and 100 data = [[date, randint(0, 100)] for date in dates_in_range] return data
dc623905b96af67acf4ff21e0b324b0415cb10f6
renruoxu/algorithms
/leetcode/trees/226_invert_binary_tree.py
440
3.59375
4
# https://leetcode.com/problems/invert-binary-tree/description/ class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ self.helper(root) return root def helper(self, root): if root == None: return None root.left, root.right = root.right, root.left self.helper(root.left) self.helper(root.right)
93d9af7e28ee95d6c014c07ae689e8e15ca212ef
sersajar/interactive-python-rice
/fullCircle_examples/recipes.py
1,474
3.625
4
# crating a simple database import apsw # Opening/creating database connection = apsw.Connection("cookbook1.db3") cursor = connection.cursor() sql = 'DROP TABLE IF EXISTS Recipes' cursor.execute(sql) sql = 'DROP TABLE IF EXISTS Instructions' cursor.execute(sql) sql = 'DROP TABLE IF EXISTS Ingredients' cursor.execute(sql) # we define a string variable called sql, and assignit the command to create the table sql = 'CREATE TABLE Recipes (pkID INTEGER PRIMARY KEY, name TEXT, serves TEXT, source TEXT)' cursor.execute(sql) # create other tables sql = 'CREATE TABLE Instructions (pkID INTEGER PRIMARY KEY, instructions TEXT, recipeID NUMERIC)' cursor.execute(sql) sql = 'CREATE TABLE Ingredients (pkID INTEGER PRIMARY KEY, ingredients TEXT, recipeID NUMERIC)' cursor.execute(sql) # create first recipe sql = 'INSERT INTO Recipes (name, serves, source) VALUES ("Spanish Rice", 4, "Greg Walters")' cursor.execute(sql) #find out the value that was assigned to the pkID in the recipe table sql = "SELECT last_insert_rowid()" cursor.execute(sql) for x in cursor.execute(sql): lastid = x[0] sql = 'INSERT INTO Instructions (recipeID, instructions)\ VALUES (%s, " Brown hamburger. Stir in all other ingredients. Bring to boil. Stir.\n \ Lower to simmer. Cover and cook dor 20 min or until all liquid is absorved.")' % lastid cursor.execute(sql) sql = 'INSERT INTO Ingredients (recipeID, ingredients) VALUES (%s, " 1 cup parboiled Rice\n lola")' % lastid cursor.execute(sql)
8a15304e4d2cb1ee3998620e92c2a50a23ed5e60
Kasiviswanathan3876/Indian-City-Name-Generator
/citynamespredictor.py
1,826
3.515625
4
from __future__ import print_function, division, absolute_import import tflearn from tflearn.data_utils import * path = "indiancitynames.txt" #Fixing maximum length of city names to be generated maxlen = 20 X, Y, char_idx = \ textfile_to_semi_redundant_sequences(path, seq_maxlen=maxlen, redun_step=3) #LSTM RNN net = tflearn.input_data(shape=[None, maxlen, len(char_idx)]) net = tflearn.lstm(net, 512, return_seq=True, dropout=0.5) net = tflearn.lstm(net, 512, dropout=0.5) net = tflearn.fully_connected(net, len(char_idx), activation='softmax') net = tflearn.regression(g, optimizer='adam', loss='categorical_crossentropy', learning_rate=0.001) #A deep neural network model for generating sequences. model = tflearn.SequenceGenerator(net, dictionary=char_idx, seq_maxlen=maxlen, clip_gradients=5.0, checkpoint_path='model_indian_cities') #training for i in range(40): #Seed helps us start from the same place everytime seed = random_sequence_from_textfile(path, maxlen) #Fitting data to the sequence model.fit(X, Y, validation_set=0.1, batch_size=128, n_epoch=1, run_id='indian_cities') print("\n...TESTING...") print("-- Test with temperature of 1.2 --") """Generate a sequence. Temperature is controlling the novelty of the created sequence, a temperature near 0 will looks like samples used for training, while the higher the temperature, the more novelty.""" print(model.generate(30, temperature=1.2, seq_seed=seed)) print("-- Test with temperature of 1.0 --") print(model.generate(30, temperature=1.0, seq_seed=seed)) print("-- Test with temperature of 0.5 --") print(model.generate(30, temperature=0.5, seq_seed=seed))
f486c90af037d83b199be96403f3e2d969ba392a
obviouslyghosts/dailychallenges
/ProjectEuler/046/pe-046.py
1,131
3.96875
4
""" It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×1**2 15 = 7 + 2×2**2 21 = 3 + 2×3**2 25 = 7 + 2×3**2 27 = 19 + 2×2**2 33 = 31 + 2×1**2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ searching = True lim = 10 def PrimeCheck(n): n = int(n) if n == 1: return False if n == 2: return True ## even check if n%2<1: return False ## only check below square root! l = int(n**0.5)+1 for i in range(3,l,2): if n%i <1: return False return True def ScanPrimes( i ): num = i for i in range(1, i, 1): if PrimeCheck(i): b = (num-i)/2 b = b**0.5 if b.is_integer() and b > 0 and b < num: return i return -1 n = 3 while searching: if not PrimeCheck(n): p = ScanPrimes( n ) if p < 0: print("BROKE") print("%i = %i + 2x%i**2" %(n, p, int(((n-p)/2)**0.5))) searching = False n += 2
2bef6fe4b671d9e71014980418e1e507043adba8
Hariharasudhaan/Python_programs
/commonElements.py
843
4.28125
4
n1=int(input("Enter Size of an array 1:")) #getting Size of an Array 1 a1=[] for i in range(0,n1,1): #Loop for getting Array 1 z1=int(input("Enter the element:")) a1.append(z1) n2=int(input("Enter Size of an array 2:")) #getting Size of an Array 2 a2=[] for i in range(0,n2,1): #Loop for getting Array 2 z2=int(input("Enter the element:")) a2.append(z2) n3=int(input("Enter Size of an array 3:")) #getting Size of an Array 3 a3=[] for i in range(0,n3,1): #Loop for getting Array 3 z3=int(input("Enter the element:")) a3.append(z3) for i in range(0,n1,1): #Loop for Finding Common Elements ia all Three Array's if(a1[i] in a2 and a1[i] in a3): print(a1[i])
8d362931f7633d9194e510bacf4d10f336ffb205
AdamZhouSE/pythonHomework
/Code/CodeRecords/2757/60727/317490.py
202
3.8125
4
a=input() b=input() if a=='5' and b=='1 2': print (6) elif a=='8' and b=='1 2': print(18) elif a=='7' and b=='1 2': print(12) elif a=='10' and b=='1 2': print(36) else: print(3)
7cb461bd557870d81dab5df113db66e74e3ecd1d
Cris-Morales/6.0001-Introduction-to-Computer-Science-and-Programming-in-Python-
/ps0.py
226
4.03125
4
""" Created Saturday March 28, 2020 @author: Cris Morales """ #problem set assignment import math x = int(input("Enter number x: ")) y = int(input("Enter number y: ")) print("x**y = ", x**y) print("log(x) = ", int(math.log2(x)))
7df06dd6db5d7b1049308988cdffe15cf45bc717
cdavis4/CS_325
/HW1/mergeTime.py
1,533
3.90625
4
import time,random """ Function random creates random values in array input # of values desired, low range value and highest in range value outputs array """ n = [100, 250, 500, 1000, 2500, 3000, 5000, 10000, 15000, 20000] def randomArray(size,low,high): randArray = [] i = 0 while i < size: randNum = random.randint(low,high) randArray.append(randNum) i += 1 return randArray def mergeSort(sortedArray): if 1 < len(sortedArray): q = len(sortedArray)//2 left = sortedArray[:q] right = sortedArray[q:] mergeSort(left) mergeSort(right) merge(left,right,sortedArray) def merge(L,R, finalArray): i = 0 # left half index j = 0 # right half index index = 0 #for merged array while i < len(L) and j < len(R): if L[i] <= R[j]: finalArray[index]=L[i] i += 1 else: finalArray[index]=R[j] j += 1 index += 1 while i < len(L): finalArray[index] = L[i] i += 1 index += 1 while j < len(R): finalArray[index] = R[j] j += 1 index += 1 def main(): try: line = 1 for i in n: array = randomArray(i,0,10000) start = time.time() mergeSort(array) end = time.time() print"#", line, ("Array Size: ", i, "Running Time (sec) ", end - start) line +=1 except: print "fail" if __name__ == "__main__": main()
9f9e704cd13e3aad01f816e8348872f04bba7489
codeSmith12/PCAP-Training
/queue2.py
854
3.703125
4
class QueueError(IndexError): # Choose base class for the new exception. def __init__(self): IndexError.__init__(self) class Queue: def __init__(self): self.list = [] def put(self, elem): self.list = str(elem).split() + self.list def get(self): if len(self.list) <=0: raise QueueError val = self.list[-1] del self.list[-1] return val def printQueue(self): for item in self.list: print(item) class SuperQueue(Queue): def __init__(self): Queue.__init__(self) def isEmpty(self): if len(self.list) <= 0: return True return False que = SuperQueue() que.put(1) que.put("dog") que.put(False) for i in range(4): if not que.isEmpty(): print(que.get()) else: print("Queue empty")
bc98dfeaf4bd2ff09119e6e8755a0d46760c1f83
iamrishap/PythonBits
/InterviewBits/dp/word-break-1.py
2,598
3.890625
4
""" Given a string A and a dictionary of words B, determine if A can be segmented into a space-separated sequence of one or more dictionary words. Input Format: The first argument is a string, A. The second argument is an array of strings, B. Output Format: Return 0 / 1 ( 0 for false, 1 for true ) for this problem. Constraints: 1 <= len(A) <= 6500 1 <= len(B) <= 10000 1 <= len(B[i]) <= 20 Examples: Input 1: A = "myinterviewtrainer", B = ["trainer", "my", "interview"] Output 1: 1 Explanation 1: Return 1 ( corresponding to true ) because "myinterviewtrainer" can be segmented as "my interview trainer". Input 2: A = "a" B = ["aaa"] Output 2: 0 Explanation 2: Return 0 ( corresponding to false ) because "a" cannot be segmented as "aaa". """ # Lets again look at the bruteforce solution. # You start exploring every substring from the start of the string, and check if its in the dictionary. If it is, then # you check if it is possible to form rest of the string using the dictionary words. If yes, my answer is true. # If none of the substrings qualify, then our answer is false. # So something like this : # bool wordBreak(int index, string &s, unordered_set<string> &dict) { # // BASE CASES # # bool result = false; # // try to construct all substrings. # for (int i = index; i < s.length(); i++) { # substring = *the substring s[index..i] with i inclusive* # if (dict contains substring) { # result |= wordBreak(i + 1, s, dict); // If this is true, we are done. # } # } # return result; # } # This solution itself is exponential. However, do note that we are doing a lot of repetitive work. # Do note, that index in the wordBreak function call can only take s.length() number of values [0, s.length]. # What if we stored the result of the function somehow and did not process it everytime the function is called ? class Solution: # @param A : string # @param B : list of strings # @return an integer def wordBreak(self, A, B): group = set() for i in B: group.add(i) store = dict([]) for i in range(len(A) - 1, -1, -1): for j in range(i + 1, len(A) + 1): if A[i:j] in group: if j < len(A) and A[j:] in store: store[A[i:]] = 1 break elif j == len(A): store[A[i:]] = 1 if A in store: return 1 else: return 0
d7a390f7940c4568b92c589308f50a59e96b7498
karthikdandavathi/PythonPrograms
/InterviewPractice/FibonacciNumbers.py
266
4.1875
4
"""" Fibonacci numbers are numbers that are 1,1,2,3,5,8 i.e., if f(n) = f(n-1)+f(n-2) for n>2 """ def run_main(): print(F(6)) def F(n): if n == 0: return 0 elif n == 1: return 1 else: return F(n-1)+F(n-2) if __name__ == "__main__": run_main()
80f48475a2442ba8abeb3f4626cfb023f3ea3b76
headlulu888/python_l
/lesson1/hw5.py
215
3.671875
4
first_num = int(input('Введите первое число: \n')) second_num = int(input('Введите второе число: \n')) i = first_num - 1 while i <= second_num: if i % 5 == 0: print(i) i += 1
e670cc67618cdcc82eca812782ee7455b7e782ef
prasadkhajone99/prime
/print_list.py
108
3.59375
4
l=str(input("Enter data...\n")) l2=l.split() l2=l2[::len(l2)-1] print("first-",l2[0]) print("last-",l2[1])
dc8706dbf19d2d83d95f03dd3a495684ccac4cbb
zhiruchen/get_hands_dirty
/ds_application/quick_sort.py
850
3.578125
4
# encoding: utf-8 def quick_sort(alist): do_sort(alist, 0, len(alist)-1) def do_sort(alist, first, last): if first < last: _pos = partition(alist, first, last) do_sort(alist, first, _pos-1) do_sort(alist, _pos+1, last) def partition(alist, first, last): pivot_value = alist[first] left_pos = first + 1 right_pos = last done = False while not done: while left_pos <= right_pos and alist[left_pos] <= pivot_value: left_pos += 1 while right_pos >= left_pos and alist[right_pos] >= pivot_value: right_pos -= 1 if right_pos < left_pos: done = True else: alist[left_pos], alist[right_pos] = alist[right_pos], alist[left_pos] alist[first], alist[right_pos] = alist[right_pos], alist[first] return right_pos
14862f3b6a347cb6ec86328448f4b815fd4a5a99
Calendis/Moderately-Seafaring
/lib/Stat.py
2,196
3.828125
4
#Classes for stats class Stat(object): """docstring for Stat""" def __init__(self): super(Stat, self).__init__() self.name = "Default stat" self.short_name = "STAT" self.value = 0 self.temp_modifier = 0 def get_name(self, short=True): if short: return self.short_name return self.name def get_value(self): return self.value def shift_value(self, offset): self.value += offset def set_value(self, new_value): self.value = new_value class HitPoints(Stat): """When these reach zero, you're done.""" def __init__(self, value): super(HitPoints, self).__init__() self.name = "Hit Points" self.short_name = "HP" self.value = value class ManaPoints(Stat): """Costs these to use magic.""" def __init__(self, value): super(ManaPoints, self).__init__() self.name = "Mana Points" self.short_name = "MP" self.value = 0 class Attack(Stat): """Determines how much non-magical damage you can inflict.""" def __init__(self, value): super(Attack, self).__init__() self.name = "Attack" self.short_name = "ATK" self.value = value class Defence(Stat): """Reduces non-magical damage dealt to you.""" def __init__(self, value): super(Defence, self).__init__() self.name = "Defence" self.short_name = "DEF" self.value = value class MagicalAttack(Stat): """Determines how much magical damage you can inflict.""" def __init__(self, value): super(MagicalAttack, self).__init__() self.name = "Magical Attack" self.short_name = "MAG" self.value = value class MagicalResistance(Stat): """Reduces magical damage done to you.""" def __init__(self, value): super(MagicalResistance, self).__init__() self.name = "Magical Resistance" self.short_name = "RES" self.value = value class Speed(Stat): """Determines who goes first and how easy it is to escape.""" def __init__(self, value): super(Speed, self).__init__() self.name = "Speed" self.short_name = "SPD" self.value = value class Luck(Stat): """Determines crit rate, and acts as attack/defence against status effects.""" def __init__(self, value): super(Luck, self).__init__() self.name = "Luck" self.short_name = "LUK" self.value = value
2d8e8f6abcab03351f087a55caf36e9476215951
amithca/code
/MTech/Sem2/Lab/DSC523/Assignment2/Assignment2_Q1.py
245
3.765625
4
def minor_matrix(m, i, j): # calculate the minor of the matrix (MM) return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])] mtx_A = [[10, 20, 30], [40, 50, 60], [70, 80, 90]] m1 = minor_matrix(mtx_A, 0, 1) print(f'Matrix minor is:{m1}')
ab3810b536cbc9fb28290ef78d8017713331d2da
komalsorte/LeetCode
/Amazon/Array and String/3_LongestSubstringWithoutRepeatingCharacters.py
903
3.8125
4
__author__ = 'Komal Atul Sorte' """ Given a string, find the length of the longest substring without repeating characters. """ class Solution: def longestSubstring(self, s): if s == " ": return 1 ele_list = list() max = 0 res = "" index, start = 0, 0 while start < len(s) and index < len(s): if s[index] in ele_list: start += 1 index = start if max < len(res): max = len(res) res = "" ele_list = list() else: res = res + s[index] ele_list.append(s[index]) index += 1 if max < len(res): max = len(res) return max if __name__ == '__main__': input = "abcabcbb" input = "c" input = "dvdf" print(Solution().longestSubstring(s=input))
6a26efaa39d1c3f4233f293c11c54f83868e01f7
prernakaul22/Airbnb-Price-Analysis
/Project_Part3/PredictAL.py
1,533
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 6 22:15:42 2018 @author: katezeng This module is for Predictive Analysis - Hypothesis Testing - This component contains both the traditional statistical hypothesis testing, and the beginning of machine learning predictive analytics. Here you will write three (3) hypotheses and see whether or not they are supported by your data. You must use all of the methods listed below (at least once) on your data. - You do not need to try all the methods for each hypothesis. For example, you might use ANOVA for one of your hypotheses, and you might use a t-test and linear regression for another, etc. It will be the case, that some of the hypotheses will not be well supported. - When trying methods like a decision tree, you should use cross-validation and show your ROC curve and a confusion matrix. For each method, explain the method in one paragraph. - Explain how and why you will apply your selected method(s) to each hypothesis, and discuss the results. - Therefore, you will have at least three (3) hypothesis tests and will apply all seven (7) of the following methods to one or more of your hypotheses. - Required methods: - t-test or Anova (choose one) - Linear Regression or Logistical Regression (multivariate or multinomial) (choose one) - Decision tree - A Lazy Learner Method (such as kNN) - Naïve Bayes - SVM - Random Forest """
76383345a67e47ec1600cdf200c8dda131817cc3
VisualAcademy/PythonNote
/PythonNote/99_Etc/min_value_python.py
520
3.890625
4
def find_min(data, n): min_value = float('inf') # 최솟값을 무한대로 초기화 for i in range(n): if data[i] < min_value: min_value = data[i] # 작은 데이터로 재 초기화 return min_value def main(): # [1] Init # [2] Input data = [-10, -30, -20, -5, -15] n = len(data) # [3] Process: 최솟값만 구해라!!! min_value = find_min(data, n) # [4] Output print("최솟값:", min_value) # -30 if __name__ == "__main__": main()
2fa6ed04513777a98662ab6b043f6d33406a143c
leehour/ProgramProblem
/剑指offer/重建二叉树.py
1,382
3.609375
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): # write code here if not pre or not tin or len(pre) != len(tin): return None left_index = 0 root = TreeNode(pre[0]) for i in range(len(tin)): if tin[i] == pre[0]: left_index = i break right_index = len(pre) - left_index - 1 if left_index > 0: root.left = self.reConstructBinaryTree(pre[1: left_index + 1], tin[: left_index]) if right_index > 0: root.right = self.reConstructBinaryTree(pre[left_index + 1:], tin[left_index + 1:]) return root if __name__ == '__main__': pre = [1, 2, 4, 7, 3, 5, 6, 8] tin = [4, 7, 2, 1, 5, 3, 8, 6] s = Solution() print(s.reConstructBinaryTree(pre, tin)) # A better solution # class Solution: # def reConstructBinaryTree(self, pre, tin): # if not pre or not tin: # return None # root = TreeNode(pre.pop(0)) # index = tin.index(root.val) # root.left = self.reConstructBinaryTree(pre, tin[:index]) # root.right = self.reConstructBinaryTree(pre, tin[index + 1:]) # return root
7237dcc130d0507a434c42ee3d9ea46c0a13e0fc
pombredanne/scratch-1
/misc/chacha.py
4,730
3.640625
4
""" The ChaCha stream cipher This module exports a single generator function: chacha. Given a key and IV, it returns a generator iterator that produces the keystream a byte at at time. import chacha key = b'It is Arthur King of the Britons' iv = bytes(chacha.IVSIZE) gen = chacha.chacha(key, iv) [next(gen) for _ in range(8)] # => [183, 63, 147, 244, 204, 140, 132, 235] This is free and unencumbered software released into the public domain. """ from array import array as _array from sys import byteorder as _byteorder KEYSIZE = 32 IVSIZE = 8 # Discover the proper array integer type def _basetype(): for c in 'HIL': if _array(c).itemsize == 4: return c raise RuntimeError('no suitable integer type available') _BASETYPE = _basetype() def _rotate(v, n): return (v << n | v >> (32 - n)) & 0xffffffff def _quarterround(x, a, b, c, d): x[a] = (x[a] + x[b]) & 0xffffffff x[d] = _rotate(x[d] ^ x[a], 16) x[c] = (x[c] + x[d]) & 0xffffffff x[b] = _rotate(x[b] ^ x[c], 12) x[a] = (x[a] + x[b]) & 0xffffffff x[d] = _rotate(x[d] ^ x[a], 8) x[c] = (x[c] + x[d]) & 0xffffffff x[b] = _rotate(x[b] ^ x[c], 7) def chacha(key, iv, rounds=20): """Return a generator iterator that produces a keystream byte-by-byte. key (bytes): Must be exactly 32 bytes long. iv (bytes): Initialization vector, must be exactly 8 bytes long. rounds: number of cipher rounds to perform (20, 12, 8) After 2^70 bytes of output the keystream will be exhausted and an OverflowError will be raised. (On conventional hardware, this would take CPython millions of years to reach.) """ if len(key) != KEYSIZE: raise ValueError('key is the wrong length') if len(iv) != IVSIZE: raise ValueError('IV is the wrong length') state = _array(_BASETYPE, [0] * 16) state[ 0] = 0x61707865 # "expand 32-byte k" state[ 1] = 0x3320646e # state[ 2] = 0x79622d32 # state[ 3] = 0x6b206574 # view = _array(_BASETYPE, key) if _byteorder == 'big': view.byteswap() state[ 4] = view[0] state[ 5] = view[1] state[ 6] = view[2] state[ 7] = view[3] state[ 8] = view[4] state[ 9] = view[5] state[10] = view[6] state[11] = view[7] view = _array(_BASETYPE, iv) if _byteorder == 'big': view.byteswap() state[14] = view[0] state[15] = view[1] view = None output = _array(_BASETYPE, [0] * 16) while True: # Compute the next output block for i in range(16): output[i] = state[i] for i in range(rounds // 2): _quarterround(output, 0, 4, 8, 12) _quarterround(output, 1, 5, 9, 13) _quarterround(output, 2, 6, 10, 14) _quarterround(output, 3, 7, 11, 15) _quarterround(output, 0, 5, 10, 15) _quarterround(output, 1, 6, 11, 12) _quarterround(output, 2, 7, 8, 13) _quarterround(output, 3, 4, 9, 14) for i in range(16): output[i] = (output[i] + state[i]) & 0xffffffff # Yield each output byte if _byteorder == 'big': output.byteswap() result = output.tobytes() for byte in result: yield byte # Increment the block counter counter = (state[12] << 32 | state[13]) + 1 state[12] = counter & 0xffffffff state[13] = counter >> 32 def _test(): # Official IETF test vectors for 20 rounds on a zero key and IV expect0 = [ 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, 0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86 ] expect1 = [ 0x9f, 0x07, 0xe7, 0xbe, 0x55, 0x51, 0x38, 0x7a, 0x98, 0xba, 0x97, 0x7c, 0x73, 0x2d, 0x08, 0x0d, 0xcb, 0x0f, 0x29, 0xa0, 0x48, 0xe3, 0x65, 0x69, 0x12, 0xc6, 0x53, 0x3e, 0x32, 0xee, 0x7a, 0xed, 0x29, 0xb7, 0x21, 0x76, 0x9c, 0xe6, 0x4e, 0x43, 0xd5, 0x71, 0x33, 0xb0, 0x74, 0xd8, 0x39, 0xd5, 0x31, 0xed, 0x1f, 0x28, 0x51, 0x0a, 0xfb, 0x45, 0xac, 0xe1, 0x0a, 0x1f, 0x4b, 0x79, 0x4d, 0x6f ] gen = chacha(bytes(KEYSIZE), bytes(IVSIZE)) block0 = [next(gen) for _ in range(64)] block1 = [next(gen) for _ in range(64)] assert block0 == expect0 assert block1 == expect1 if __name__ == '__main__': _test()
df402ade473194711a86d95dbbe43e5aee8584be
anttinevalainen/automating-GIS
/Final assignment/Visualizer.py
14,384
3.5
4
def Visualizer(YKR_ID, travelmode, traveltype, maptype, output_folder): import geopandas as gpd import os from FileFinder import FileFinder from TableJoiner import TableJoiner import mapclassify import matplotlib.pyplot as plt import folium '''Visualizes the travel times of a single YKR_ID or a list of YKR_IDs based on travel times by specified travel mode. The output maps are saved in the specified folder and their filetype depends on the maptype chosen Args: YKR_ID: A (list of) string(s)/integer(s) of YKR cell ID travelmode: (String) Can be one of the following: - car - public transport - walking - biking traveltype: (String) Can be either: - time - distance maptype: (String) Can be either: - static - interactive output_folder: The desired folder the finished product is saved into Returns: None - The function saves the output table into the output folder ''' fp = r'data/MetropAccess_YKR_grid_EurefFIN.shp' grid = gpd.read_file(fp) #########ASSERTION######### #YKR_ID = string, integer or list of strings or integers if type(YKR_ID) == list: for index in YKR_ID: assert (type(index) == str or type(index) == int), 'The variables in a given list need to be string or integer' else: assert (type(YKR_ID) == str or type(YKR_ID) == int), 'The given variable must be a string, integer or list' #travelmode = string AND either 'car', 'public transport', 'walking' or 'biking' assert type(travelmode) == str, ("Travel mode needs to be in string format. " + "Choose: 'car', 'public transport', 'walking' or 'biking'") assert (travelmode.lower() == 'car' or travelmode.lower() == 'public transport' or travelmode.lower() == 'walking' or travelmode.lower() == 'biking'), ("Travel mode needs to be either " + "'car', 'public transport', 'walking' or 'biking'") #traveltype = single string, one of two options assert type(traveltype) == str, ("comparison type variable needs to be a string. " + "Choose either 'time' or 'distance'") assert (traveltype.lower() == 'time' or traveltype.lower() == 'distance'), ("comparison type needs to be either " + "'time' or 'distance'") #maptype needs to be a string and can either be static or interactive assert type(maptype) == str, ('Map type needs to be in string format. ' + 'Choose static of interactive map') assert (maptype.lower() == 'static' or maptype.lower() == 'interactive'), ("Map type needs to be either " + "'static' or 'interactive'") #output folder = string and an existing folder assert type(output_folder) == str, 'output folder needs to be in string format.' assert os.path.isdir(output_folder), 'output_folder does not exits' #grid = geodataframe assert isinstance(grid, gpd.GeoDataFrame), 'grid variable needs to be a geodataframe' #this step can either be done outside the visualizer function or within it. #i chose to add it within the function Filelist = FileFinder(YKR_ID = YKR_ID, foldername = 'data') TableJoiner(Filelist, grid) #if the filelist is empty, no travel time data could be found assert len(Filelist) >= 1, ('Could not find travel time data from the data folder.' + 'Check the input formats and data folder of Filefinder function') ########################### #for each row in the filelist, read the datafile and classify the travel modes in it for index in Filelist: split = Filelist[0].split('_') split = split[2].split('.') filename = 'data/' + split[0] + '.shp' map_data = gpd.read_file(filename) #TIME as the traveltype #5min intervals 0-60 if traveltype == 'time': #create a function to classify. I also created a list for the bins for a neat code bins = [5,10,15,20,25,30,35,40,45,50,55,60] classifier = mapclassify.UserDefined.make(bins=bins) #apply function to both columns and create 2 new columns #at first i had trouble with this but then I noticed to apply the double square brackets map_data['car_r_t_cl'] = map_data[['car_r_t']].apply(classifier) map_data['pt_r_t_cl'] = map_data[['pt_r_t']].apply(classifier) map_data['walk_t_cl'] = map_data[['walk_t']].apply(classifier) #map_data['bike_s_t_cl'] = map_data[['bike_s_t']].apply(classifier) #DISTANCE as the traveltype #first intervals 0,500,3000 and then 3000 rise each step else: #create a function to classify. I also created a list for the bins for a neat code bins = [500,3000,6000,9000,12000,15000,18000,21000,24000,27000,30000,33000] classifier = mapclassify.UserDefined.make(bins=bins) map_data['car_r_d_cl'] = map_data[['car_r_d']].apply(classifier) map_data['pt_r_d_cl'] = map_data[['pt_r_d']].apply(classifier) map_data['walk_d_cl'] = map_data[['walk_d']].apply(classifier) #map_data['bike_s_d_cl'] = map_data[['bike_d_t']].apply(classifier) #STATIC maps if maptype == 'static': #cefine output filename and use it when saving the file: if traveltype == 'time': output_file = (output_folder + '/' + split[0] + '_accessibility_by_' + travelmode.strip() + 'in_minutes.png') else: output_file = (output_folder + '/' + split[0] + '_accessibility_by_' + travelmode.strip() + 'in_meters.png') #create the subplot and define names for the two figures for neat code fig, ax = plt.subplots(figsize=(10,5)) #plot the map if travelmode == 'car': if traveltype == 'time': plot = map_data.plot(column = 'car_r_t_cl', ax=ax, cmap='RdYlBu') else: plot = map_data.plot(column = 'car_r_d_cl', ax=ax, cmap='RdYlBu') if travelmode == 'public transport': if traveltype == 'time': plot = map_data.plot(column = 'pt_r_t_cl', ax=ax, cmap='RdYlBu') else: plot = map_data.plot(column = 'pt_r_d_cl', ax=ax, cmap='RdYlBu') if travelmode == 'walking': if traveltype == 'time': plot = map_data.plot(column = 'walk_t_cl', ax=ax, cmap='RdYlBu') else: plot = map_data.plot(column = 'walk_d_cl', ax=ax, cmap='RdYlBu') #if travelmode == 'biking': #if traveltype = 'time': #plot = map_data.plot(column = 'bike_s_t_cl', ax=ax, cmap='RdYlBu') #else: #plot = map_data.plot(column = 'bike_s_d_cl', ax=ax, cmap='RdYlBu') #apply titles and squeeze the layout ax.title.set_text(split[0] + ' accessibility by ' + travelmode) plt.tight_layout() plt.savefig(output_file) #INTERACTIVE maps if maptype == 'interactive': #define geoid for folium mapping map_data['geoid'] = map_data.index.astype(str) #creating interactive map map = folium.Map(location=[60.11, 24.56], tiles = 'cartodbpositron', zoom_start=10, control_scale=True) if traveltype == 'time': output_file = (output_folder + '/' + split[0] + '_accessibility_by_' + travelmode.strip() + 'in_minutes.html') else: output_file = (output_folder + '/' + split[0] + '_accessibility_by_' + travelmode.strip() + 'in_meters.html') #car if travelmode == 'car': if traveltype == 'time': folium.Choropleth(geo_data = map_data, data = map_data, columns = ['geoid','car_r_t_cl'], key_on = 'feature.id', fill_color = 'RdYlBu', line_color = 'white', line_weight = 0, legend_name = (split[0] + ' accessibility by ' + travelmode + ' in minutes') ).add_to(map) else: folium.Choropleth(geo_data = map_data, data = map_data, columns = ['geoid','car_r_d_cl'], key_on = 'feature.id', fill_color = 'RdYlBu', line_color = 'white', line_weight = 0, legend_name = (split[0] + ' accessibility by ' + travelmode + ' in meters') ).add_to(map) #public transport if travelmode == 'public transport': if traveltype == 'time': folium.Choropleth(geo_data = map_data, data = map_data, columns = ['geoid','pt_r_t_cl'], key_on = 'feature.id', fill_color = 'RdYlBu', line_color = 'white', line_weight = 0, legend_name = (split[0] + ' accessibility by ' + travelmode + ' in minutes') .add_to(map) ) else: folium.Choropleth(geo_data = map_data, data = map_data, columns = ['geoid','pt_r_d_cl'], key_on = 'feature.id', fill_color = 'RdYlBu', line_color = 'white', line_weight = 0, legend_name = (split[0] + ' accessibility by ' + travelmode + ' in meters') ).add_to(map) #walking if travelmode == 'walking': if traveltype == 'time': folium.Choropleth(geo_data = map_data, data = map_data, columns = ['geoid','walk_t_cl'], key_on = 'feature.id', fill_color = 'RdYlBu', line_color = 'white', line_weight = 0, legend_name = (split[0] + ' accessibility by ' + travelmode + ' in minutes') ).add_to(map) else: folium.Choropleth(geo_data = map_data, data = map_data, columns = ['geoid','walk_d_cl'], key_on = 'feature.id', fill_color = 'RdYlBu', line_color = 'white', line_weight = 0, legend_name = (split[0] + ' accessibility by ' + travelmode + ' in meters') ).add_to(map) #biking #if travelmode == 'biking': #if traveltype == 'time': #folium.Choropleth(geo_data = map_data, #data = map_data, #columns = ['geoid','bike_s_t_cl'], #key_on = 'feature.id', #fill_color = 'RdYlBu', #line_color = 'white', #line_weight = 0, #legend_name = (split[0] + ' accessibility by ' + #travelmode + ' in minutes') #).add_to(map) #else: #folium.Choropleth(geo_data = map_data, #data = map_data, #columns = ['geoid','bike_d_cl'], #key_on = 'feature.id', #fill_color = 'RdYlBu', #line_color = 'white', #line_weight = 0, #legend_name = (split[0] + ' accessibility by ' + #travelmode + ' in meters') #).add_to(map) #save the html file map.save(output_file) print('Visualizer done! Thank you for your patience!')
7d8125cc390c30bbe7d3c25e22b3c487991d81f4
tuanmeo/python_toolbox_1
/PYTHON/3_python_data_science_toolbox(1)/chap1_ownfunction.py
5,649
3.734375
4
#%% # create a dictionary of lang and numbers of given langs import pandas as pd df = pd.read_csv('tweets.csv') lang_count = {} col = df['lang'] #iterate over lang column in DataFrame for index in col: #if lang is in lang_count, add 1: if index in lang_count.keys(): lang_count[index] = lang_count[index] + 1 # else add lang to lang_count, set value to 1: else: lang_count[index] = 1 print(lang_count) # %% # create function to return the result and call it tweet_df = pd.read_csv('tweets.csv') def count_entries(df,col_name): lang_count = {} col = df[col_name] #iterate over lang column in DataFrame for entry in col: #if lang is in lang_count, add 1: if entry in lang_count.keys(): lang_count[entry] = lang_count[entry] + 1 # else add lang to lang_count, set value to 1: else: lang_count[entry] = 1 return lang_count result = count_entries(tweet_df, 'lang') print(result) # %% # change value of variable in global team = "teen titans" def change_team(): """Change the value of the global variable team.""" global team team = "justice league" print(team) change_team() print(team) # %% # Nested functions # Not useful for too much variables def mod2plus5(x1, x2, x3): """Returns the remainder plus 5 of three values""" new_x1 = x1 % 2 + 5 new_x2 = x2 % 2 + 5 new_x3 = x3 % 2 + 5 return (new_x1, new_x2, new_x3) print(mod2plus5(3,5,7)) # use nested functions def mod2plus5 (x1, x2, x3): """Returns the remainder plus 5 of three values""" def inner(x): """Returns the remainder plus 5 of a value""" return x % 2 + 5 return (inner(x1), inner(x2), inner(x3)) print (mod2plus5(3,5,7)) # %% # remember the value of function def raise_val(n): """Return the inner function.""" def inner(x): """Raise x to the power of n.""" raised = x ** n return raised return inner square = raise_val(2) print(square(3)) # %% # create function three_shouts() def three_shouts(x1,x2,x3): """Returns a tuple of strings concatenated with '!!!'.""" def inner(x): """Return a string concatenated with '!!!'.""" return x + '!!!' return (inner(x1), inner(x2), inner(x3)) print(three_shouts('a', 'b', 'c')) # %% def echo(n): """Concatenate n copies of word1.""" def inner_echo(word1): echo_word = word1 * n return echo_word return inner_echo # call echo twice twice = echo(2) # call echo thrice thrice = echo(3) print(twice('hello'), thrice('hello')) # %% # Use keyword nonlocal def echo_shout(word): """Change the value of a nonlocal variable.""" # Concatenate word with itself: echo_word echo_word = word * 2 # Print echo_word print(echo_word) # define inner function shout() def shout(): """ Alter a variable in the enclosing scope.""" nonlocal echo_word # Change echo_word to echo_word concatenated with '!!!' echo_word = echo_word + '!!!' # call the function shout shout() # print echo_word print(echo_word) echo_shout('hello') # %% # Add a default argument def power(x, y = 1): value = x ** y return value result1 = power(2,2) result2 = power(2) print(result1) print(result2) # %% # Flexible argurments: *args(1) def add_all(*args): """Sum all values in *args together.""" # initialize sum sum_all = 0 # accumulate the sum for num in args: sum_all += num # sum all the value in tuple return sum_all add_all(1,5) # %% # print out key and value of dictionary use **kwargs def print_all(**kwargs): """Print out key-value pairs in **kwargs.""" # print out the key-value pairs for key, value_1 in kwargs.items(): print("%s = %s" %(key,value_1)) print_all(name = "tuan nguyen", key = "freelance") # %% # Concatenate echo copies of word1 and three !!! # default argument = 1 def shout_echo(word1, echo = 1): """Concatenate echo copies of word1 and !!!.""" echo_word = word1 * echo + "!!!" return echo_word no_echo = shout_echo('Hey') with_echo = shout_echo('Hey', 5) print(no_echo) print(with_echo) # %% def shout_echo(word1, echo = 1, intense = False): """Concatenate echo copies of word1 and !!!.""" echo_word = word1 * echo + "!!!" if intense is True: echo_word = echo_word.upper() else: echo_word = echo_word return echo_word with_big_echo = shout_echo('Hey',5,True) with_no_echo = shout_echo('Hey',intense = True) print(with_big_echo) print(with_no_echo) # %% # Define function 'gibberish()' which can accept a variable number of # string values. Its return value is a single string composed of all # the string arguments concatenated together in the order they were # passed to the function call. def gibberish(*args): """Concatenate strings in *args together.""" # Initialize an empty string: hodgepodge hodgepodge = "" for word in args: hodgepodge += word return hodgepodge text = gibberish("a", "b", "c", "d") print(text) # %% # define a function that accepts a variable number of keyword arguments. def report_status(**kwargs): """Print out the status of a movie character.""" print("\nBEGIN: REPORT\n") # Iterate over the key-value pairs of kwargs for key, value in kwargs.items(): #Print out the keys and values, separated by : print(key + ":" + value) print("\nEND REPORT") #first call report_status(name = 'luke', affiliation = 'jedi', status = 'missing') report_status(name = 'anakin', affiliation = 'sith lord', status = 'deceased') # %%
1229cccc15469f1280791688069834a4e586bb61
jnjnslab/python-sample
/10_file/readlines.py
239
3.5
4
#ファイルをオープンする f = open('hello.txt', 'r', encoding='UTF-8') #1行ごとのリストとして読み込む datalist = f.readlines() for data in datalist: print(data,end='') #ファイルをクローズする f.close()
79fb27bb506698b251535a2ba484723c14067665
li-MacBook-Pro/li
/static/Mac/play/调用/数组中逆序对/nan.py
7,377
3.546875
4
from typing import List class Solution: def reversePairs(self, nums: List[int]) -> int: size = len(nums) if size < 2: return 0 res = 0 for i in range(0, size - 1): for j in range(i + 1, size): if nums[i] > nums[j]: res += 1 return res # 后有序数组中元素出列的时候,计算逆序个数 from typing import List # class Solution: # # def reversePairs(self, nums: List[int]) -> int: # size = len(nums) # if size < 2: # return 0 # # # 用于归并的辅助数组 # temp = [0 for _ in range(size)] # return self.count_reverse_pairs(nums, 0, size - 1, temp) # # def count_reverse_pairs(self, nums, left, right, temp): # # 在数组 nums 的区间 [left, right] 统计逆序对 # if left == right: # return 0 # mid = (left + right) >> 1 # left_pairs = self.count_reverse_pairs(nums, left, mid, temp) # right_pairs = self.count_reverse_pairs(nums, mid + 1, right, temp) # # reverse_pairs = left_pairs + right_pairs # # 代码走到这里的时候,[left, mid] 和 [mid + 1, right] 已经完成了排序并且计算好逆序对 # # if nums[mid] <= nums[mid + 1]: # # 此时不用计算横跨两个区间的逆序对,直接返回 reverse_pairs # return reverse_pairs # # reverse_cross_pairs = self.merge_and_count(nums, left, mid, right, temp) # return reverse_pairs + reverse_cross_pairs # # def merge_and_count(self, nums, left, mid, right, temp): # """ # [left, mid] 有序,[mid + 1, right] 有序 # # 前:[2, 3, 5, 8],后:[4, 6, 7, 12] # 只在后面数组元素出列的时候,数一数前面这个数组还剩下多少个数字, # 由于"前"数组和"后"数组都有序, # 此时"前"数组剩下的元素个数 mid - i + 1 就是与"后"数组元素出列的这个元素构成的逆序对个数 # # """ # for i in range(left, right + 1): # temp[i] = nums[i] # # i = left # j = mid + 1 # res = 0 # for k in range(left, right + 1): # if i > mid: # nums[k] = temp[j] # j += 1 # elif j > right: # nums[k] = temp[i] # i += 1 # elif temp[i] <= temp[j]: # # 此时前数组元素出列,不统计逆序对 # nums[k] = temp[i] # i += 1 # else: # # assert temp[i] > temp[j] # # 此时后数组元素出列,统计逆序对,快就快在这里,一次可以统计出一个区间的个数的逆序对 # nums[k] = temp[j] # j += 1 # # 例:[7, 8, 9][4, 6, 9],4 与 7 以及 7 后面所有的数都构成逆序对 # res += (mid - i + 1) # return res # 前有序数组中元素出列的时候,计算逆序个数 from typing import List # class Solution: # # def reversePairs(self, nums: List[int]) -> int: # size = len(nums) # if size < 2: # return 0 # # temp = [0 for _ in range(size)] # return self.reverse_pairs(nums, 0, size - 1, temp) # # def reverse_pairs(self, nums, left, right, temp): # """ # 在数组 nums 的区间 [l,r] 统计逆序对 # :param nums: # :param left: 待统计数组的左边界,可以取到 # :param right: 待统计数组的右边界,可以取到 # :param temp: # :return: # """ # if left == right: # return 0 # mid = (left + right) >> 1 # left_pairs = self.reverse_pairs(nums, left, mid, temp) # right_pairs = self.reverse_pairs(nums, mid + 1, right, temp) # # reverse_pairs = left_pairs + right_pairs # if nums[mid] <= nums[mid + 1]: # return reverse_pairs # # reverse_cross_pairs = self.merge_and_count(nums, left, mid, right, temp) # return reverse_pairs + reverse_cross_pairs # # def merge_and_count(self, nums, left, mid, right, temp): # """ # [left, mid] 有序,[mid + 1, right] 有序 # # 前:[2, 3, 5, 8],后:[4, 6, 7, 12] # 我们只需要在后面数组元素出列的时候,数一数前面这个数组还剩下多少个数字, # 因为"前"数组和"后"数组都有序, # 因此,"前"数组剩下的元素个数 mid - i + 1 就是与"后"数组元素出列的这个元素构成的逆序对个数 # # """ # for i in range(left, right + 1): # temp[i] = nums[i] # # i = left # j = mid + 1 # # res = 0 # for k in range(left, right + 1): # if i > mid: # nums[k] = temp[j] # j += 1 # elif j > right: # nums[k] = temp[i] # i += 1 # # res += (right - mid) # elif temp[i] <= temp[j]: # nums[k] = temp[i] # i += 1 # # res += (j - mid - 1) # else: # assert temp[i] > temp[j] # nums[k] = temp[j] # j += 1 # return res from typing import List # class Solution: # # def reversePairs(self, nums: List[int]) -> int: # # class FenwickTree: # def __init__(self, n): # self.size = n # self.tree = [0 for _ in range(n + 1)] # # def __lowbit(self, index): # return index & (-index) # # # 单点更新:从下到上,最多到 len,可以取等 # def update(self, index, delta): # while index <= self.size: # self.tree[index] += delta # index += self.__lowbit(index) # # # 区间查询:从上到下,最少到 1,可以取等 # def query(self, index): # res = 0 # while index > 0: # res += self.tree[index] # index -= self.__lowbit(index) # return res # # # 特判 # size = len(nums) # if size < 2: # return 0 # # # 原始数组去除重复以后从小到大排序,这一步叫做离散化 # s = list(set(nums)) # # # 构建最小堆,因为从小到大一个一个拿出来,用堆比较合适 # import heapq # heapq.heapify(s) # # # 由数字查排名 # rank_map = dict() # rank = 1 # # 不重复数字的个数 # rank_map_size = len(s) # for _ in range(rank_map_size): # num = heapq.heappop(s) # rank_map[num] = rank # rank += 1 # # res = 0 # # 树状数组只要不重复数字个数这么多空间就够了 # ft = FenwickTree(rank_map_size) # # # 从后向前看,拿出一个数字来,就更新一下,然后向前查询比它小的个数 # for i in range(size - 1, -1, -1): # rank = rank_map[nums[i]] # ft.update(rank, 1) # res += ft.query(rank - 1) # return res
a9a46f426e46cf080260fba1239b6031d090f23b
teacupwoozy/LPTHW
/ex5.py
704
4
4
name = 'Stacy Em' age = 104 # not a lie height = 99 # inches weight = 407 # lbs eyes = 'Purple' teeth = 'White' hair = 'Brown' height_in_cm = height * 2.54 weight_in_kg = weight * 0.45359237 print(f"Let's talk about {name}.") print(f"She's {height} inches tall.") print(f"She's {weight} pounds heavy.") print("Actually, that's not too heavy") print(f"She's got {eyes} eyes and {hair} hair.") print(f"Her teeth are usually {teeth} depending on the coffee.") # this line is tricky, try to get it exactly right total = age + height + weight print(f"If I add {age}, {height}, and {weight} I get {total}.") # convert to metric print(f"She is {height_in_cm} cm tall.") print(f"She is {weight_in_kg} kilos.")
48cc4217f70024e4cd78893e4879b3991b667716
spectator05/KOSS
/week2/eratos.py
282
3.640625
4
import math n = int(input("숫자를 입력하세요: ")) lst = [i for i in range(n + 1)] lst[0] = 0 lst[1] = 0 for i in range(2, int(math.sqrt(n) + 1)): for j in range(i * 2, n + 1, i): lst[j] = 0 for i in range(len(lst)): if lst[i] != 0: print(lst[i])
41739cac22f1f9a052f4fda3b698a735a919993b
Tekorita/Cursopython
/clases/metodosestaticos.py
606
3.875
4
class Circulo: #los metodos estaticos son aquellas funciones dentro de una clase que no contienen la palabra reservada self #y para que sean estaticos se tienen que decorar #los metodos estaticos son metodos que le pertenecen directamente a la clase y no a la instancia @staticmethod def pi(): return 3.1416 def __init__(self, radio): self.radio = radio def area(self): #metodos de instancia si tiene la palabra self y esta dentro de la clase return self.radio * self.radio * Circulo.pi() circulo_uno = Circulo(4) print(circulo_uno.pi()) print(circulo_uno.area()) print(Circulo.pi())
b3d85a09d974e5e11dd53a783741a53b63d879d9
AlexClowes/advent_of_code
/2019/22/small_shuffle.py
554
3.5625
4
def shuffle(instructions, card, deck_len): for instr in instructions: if instr == "deal into new stack": card = -card - 1 elif instr.split()[0] == "cut": card -= int(instr.split()[-1]) elif instr.split()[0] == "deal": card *= int(instr.split()[-1]) card %= deck_len return card def main(): card = 2019 deck_len = 10007 with open("instructions.txt") as f: print(shuffle((line.strip() for line in f), card, deck_len)) if __name__ == "__main__": main()
276ed1e63d8e5ea6c3db6a27669957331a6ba4d1
ml758392/python_tedu
/python100例/Python100Cases-master/100examples/017.py
330
3.828125
4
string=input("输入字符串:") alp=0 num=0 spa=0 oth=0 for i in range(len(string)): if string[i].isspace(): spa+=1 elif string[i].isdigit(): num+=1 elif string[i].isalpha(): alp+=1 else: oth+=1 print('space: ',spa) print('digit: ',num) print('alpha: ',alp) print('other: ',oth)
28cad05248d1a5375bb37e4caf420889c640a6a9
mbuhot/mbuhot-euler-solutions
/python/problem-023.py
1,673
4.1875
4
#! /usr/bin/env python3 import itertools import factorization description = """ Non-abundant sums Problem 23 A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ def is_abundant(n): return sum(factorization.divisors(n)[:-1]) > n assert(is_abundant(12)) assert(not is_abundant(14)) def abundant_numbers(maxval): return (i for i in range(1, maxval+1) if is_abundant(i)) def abundant_sums(maxval): a = list(abundant_numbers(maxval)) result = {} for x in a: for y in a: n = x + y if n > maxval: break result[x+y] = True return result abundantSums = abundant_sums(28123) nonAbundantSums = [x for x in range(1, 28123 + 1) if not x in abundantSums] print('Sum of numbers which cannot be expressed as sum 2 abundant numbers:', sum(nonAbundantSums))
163c809d1ddc4f55656c82e542730cd5587aec4c
HetDaftary/Competitive-Coding-Solutions
/Hackerrank-Solutions/Hackerrank-30-days-of-code/Day 20: Sorting/test.py
517
4
4
#!/bin/python3 import sys def bubble_sort(n, a): nos = 0 for i in range(n): temp_nos = 0 for j in range(i + 1, n): if a[i] > a[j]: a[i], a[j] = a[j], a[i] temp_nos += 1 nos += temp_nos if (temp_nos == 0): break return nos n = int(input().strip()) a = list(input().strip().split(' ')) nos = bubble_sort(n, a) print("Array is sorted in {} swaps.\nFirst Element: {}\nLast Element: {}".format(nos, a[0], a[n - 1]))
0441b5749eeb62666ea0cc4c2ae82353c97f0920
adonaifariasdev/DevPro
/Práticas/Pr01.py
1,911
3.9375
4
# Faça um Programa para uma loja de tintas. O programa deverá pedir # o tamanho em metros quadrados da área a ser pintada. Considere que # a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que # a tinta é vendida em latas de 18 litros, que custam R$ 80,00 ou em # galões de 3,6 litros, que custam R$ 25,00. # Informe ao usuário as quantidades de tinta a serem compradas e os # respectivos preços em 3 situações: # comprar apenas latas de 18 litros; # comprar apenas galões de 3,6 litros; # misturar latas e galões, de forma que o desperdício de tinta seja menor. # Acrescente 10% de folga e sempre arredonde os valores para cima, isto é, # considere latas cheias. from math import ceil, floor area_a_ser_pintada = int(input('Digite a Área em metros quadrados a ser pintada: ')) area_com_folga = area_a_ser_pintada * 1.1 litros_por_metro = 6 litros_a_serem_usados = area_com_folga / litros_por_metro litros_por_lata = 18 numero_de_latas = ceil(litros_a_serem_usados / litros_por_lata) valor_com_apenas_latas = numero_de_latas * 80 print(f'Você deverá usar {numero_de_latas} latas de 18 litros, no valor de R${valor_com_apenas_latas}') litros_por_galao = 3.6 numero_de_galoes = ceil(litros_a_serem_usados / litros_por_galao) valor_com_apenas_galoes = numero_de_galoes * 25 print(f'Você deverá usar {numero_de_galoes} galões de 3.6 litros, no valor de R${valor_com_apenas_galoes}') # Compra de tinta otimizada por valor numero_de_latas = floor(litros_a_serem_usados / litros_por_lata) valor_de_latas = numero_de_latas * 80 litros_faltantes = litros_a_serem_usados % litros_por_lata numero_de_galoes = ceil(litros_faltantes / litros_por_galao) valor_com_galoes = numero_de_galoes * 25 valor_total = valor_de_latas + valor_com_galoes print(f'Você deverá usar {numero_de_latas} latas de 18 litors mais {numero_de_galoes} galões de 3.6 litros, no valor de R${valor_total}.')
3b296cfada4deb651d91ebe463dbf6cf47e35de7
Aasthaengg/IBMdataset
/Python_codes/p03644/s000813566.py
65
3.5
4
n=int(input()) ans=1 while ans<=n: ans*=2 ans//=2 print(ans)
4ed0ea016bfe406871e93d8ae52cbc81ef77fdd0
TongMingLive/pytest
/study/魔法方法/描述符/Temperature.py
1,203
4.34375
4
# 练习要求: # 1、先定义一个温度类,然后定义两个描述符类用于描述摄氏度和华氏度两个属性 # 2、要求两个属性会自动进行转换,也就是说你可以给摄氏度这个属性赋值,然后打印的华氏度属性是自动转换后的结果 class Celsius: def __init__(self, value=25.0): self.value = float(value) def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value = float(value) class Fahrenheit: def __get__(self, instance, owner): return instance.cel * 1.8 + 32 def __set__(self, instance, value): instance.cel = (float(value) - 32) / 1.8 class Temperature: cel = Celsius() fah = Fahrenheit() class Main: temp = Temperature() print('初始摄氏度为:',temp.cel) print('转换后华氏度为:', temp.fah) print('---------------------------------') temp.cel = 30 print('设置摄氏度为:',30) print('转换后华氏度为:',temp.fah) print('---------------------------------') temp.fah = 75 print('设置华氏度为:', 75) print('转换后摄氏度为:', temp.cel)
b21fa279100b3d822009907f76a253fd5aaebc1c
shivambatsgit/ParkingSystemPython
/system.py
2,162
3.703125
4
""" System module to manage the vehicles coming in and out of an entry-exit point """ from big_car import BigCar from models.entry_exit import EntryExit from models.floor import Floor from data_init import parking_lot_obj as parking_lot from small_car import SmallCar from uuid import uuid4 class System: def __init__(self, floor: Floor, entry_exit: EntryExit): self.floor = floor self.entry_exit = entry_exit def park_vehicle(self, registration_number, size): """ The function parks the vehicle by assigning it a spot from the entry-exit point it has entered from, it also assumes the size of the vehicle to be judged before and is passed as an argument. Once parked, returns a random ticket id which is then used to calculate the fare while exiting the parking lot :param registration_number: Registration number of the vehicle :param size: Size of the vehicle, Can be either BIG or SMALL :return: TicketId Str """ nearest_spot = self.entry_exit.get_nearest_parking() if not nearest_spot: print("No Spot vacant") return self.floor.fill_trigger_other_entry_exit(self.entry_exit, str(nearest_spot)) ticket = uuid4() if size == "BIG": parking_lot.ticket_map[str(ticket)] = BigCar(registration_number, str(nearest_spot)) else: parking_lot.ticket_map[str(ticket)] = SmallCar(registration_number, str(nearest_spot)) print(f"Car with ticket id {ticket} is parked") def exit_vehicle(self, ticket_id): """ Expects a ticketid which is then searched in the parking lot ticket map and returns the fare and Car information :param ticket_id: :return: """ try: car = parking_lot.ticket_map[ticket_id] except KeyError as err: print("Invalid Ticket id") else: fare = car.getFare() print(f"Payment of {fare} is cleared") self.floor.vacant_trigger_other_entry_exit(car.spot) system = System(parking_lot.floors[0], parking_lot.floors[0].entry_exit[0])
e04c66850ec094d41cd3f99110c24ce9fbfad55d
hnnguyen45thinkful/Pirple-Coursework
/Python/loops2.py
1,411
4.5625
5
''' Python Homework Assignment #6 Advanced Loops By: Hieu Nguyen ''' # Details: # Create a function that takes in two parameters: rows, and columns, both of which are integers. The function should then proceed to draw a playing board (as in the examples from the lectures) the same number of rows and columns as specified. After drawing the board, your function should return True. # Extra Credit: # Try to determine the maximum width and height that your terminal and screen can comfortably fit without wrapping. If someone passes a value greater than either maximum, your function should return False. #Create function to display playing board # Start Global rows and columns at 0 because positive numbers. rows = 0 columns = 0 def GridBoard(rows,columns): if rows <=100 and columns <=100: for r in range(1, rows + 1): if r % 2 != 0: for c in range(columns): if c%2 == 0: if c != columns - 1: print(" ",end="") else: print("|",end="") else: print("") else: print("-" * columns) print(True) else: print(False)#Otherwise GridBoard(21,21)#True GridBoard(90,101)#False GridBoard(50,100)#True GridBoard(90,101)#False GridBoard(100,100)#True GridBoard(90,101)#False
2b0f9bb6db1eabaa67ec31922eee69cf4d3b3673
sektor23/AndreyP
/dz_3.1.py
233
3.859375
4
percent = int(input()) if percent == 1: print(percent, 'процент') elif percent > 1 and percent <= 4: print(percent, 'процента') else: percent >= 5 and percent <= 20 print(percent, 'процентов')
e8b537c3b6092efa6870cd240b78dd63c831866f
AntonioCenteno/Miscelanea_002_Python
/Certámenes resueltos/Certamen 1 2014-1/pregunta-2.py
1,618
3.921875
4
#Primero, debemos pedir el ao en curso. anio_actual = int(raw_input("Ingrese anio en curso: ")) #Ahora vamos pidiendo los codigos hasta que el usuario ingrese "fin" cod = raw_input("Ingrese un codigo: ") while cod != "fin": #Desarmamos el codigo anio_ingreso = int(cod[:4]) carrera = int(cod[4:7]) ranking = int(cod[7:10]) origen = int(cod[-2:]) #Ahora vamos con las condiciones. #LLevaremos 2 variables, una para cada posibilidad de descuento. Al final, mantendremos la mas grande. descuento_1 = 0 descuento_2 = 0 #Primera condicion... if (anio_actual - anio_ingreso == 2): #Si lleva 2 aos en la Universidad... descuento_1 += 5 #Es un descuento del 5%. elif (anio_actual - anio_ingreso == 3): #Si lleva 3 aos en la Universidad... descuento_1 += 15 #Es un descuento del 15%. elif (anio_actual - anio_ingreso >= 4): #Si lleva 4 o mas aos en la Universidad... descuento_1 += 25 #Es un descuento del 25%. #Segunda condicion... if (ranking <= 10): #Si ingreso dentro de los 10 primeros de su promocion... descuento_2 += 50 #Obtiene un 50% de descuento. elif (11 <= ranking <= 20): #Si esta entre los lugares 11 a 20... descuento_2 += 30 #es un 30%. elif (21 <= ranking <= 30): #Y si ingreso entre los lugares 21 a 30... descuento_2 += 10 #Es un 10%. descuento = max(descuento_1, descuento_2) #Solo nos interesa el mayor descuento de los dos. print "Al estudiante se le debe descontar un",descuento,"%" #Pedimos el siguiente codigo. cod = raw_input("Ingrese un codigo: ")
0e350cc2d0d43df757bb714368bd6a2e2b9db26a
AlEkramHossainAbir/Python1
/reminder of two numbers.py
172
3.90625
4
#program name: reminder of two numbers #author name: Al- Ekram hossain Abir #a program to find reminder a=int(input()) b=int(input()) c=a%b print("reminder of two number is: ",c)
9d4a1224b4a4d98a822bcf9883243e9a01e6dfee
naoyasu/lrnpython
/test64_1.py
118
3.75
4
# http://tinyurl.com/jcg5qwp a = input("type a number:") b = input("tepe another:") a = int(a) b = int(b) print(a/b)
d471f402cff83bf6c10a2dd2ed8cf0fc770b7359
da-ferreira/algorithms
/Estruturas de Dados/minimo_stack.py
1,464
4
4
""" Implementação de Mínimo Stack autor: David Ferreira de Almeida O objeto do algoritmo é modificar a estrutura de dados stack (pilha) de modo que o menor elemento possa ser acessado em O(1). O elementos são adicionados em pares: o elemento e o menor elemento da pilha. """ class Stack: def __init__(self): self.stack = [] self.size = 0 def min(self): if self.size == 0: return None # caso a lista esteja vazia return self.stack[-1][1] def push(self, element): temp = self.min() if temp is None: temp = element # Adiciona o elemento e o menor entre o novo elemento # e o menor elemento da pilha self.stack.append([element, min(element, temp)]) self.size += 1 def pop(self): if self.size == 0: return None # caso a lista esteja vazia removido = self.stack[-1][0] self.stack.pop() self.size -= 1 return removido def peek(self): if self.size == 0: raise IndexError('list index out of range') return self.stack[-1][0] if __name__ == '__main__': lista = Stack() lista.push(0) lista.push(1) lista.push(15) lista.push(3) lista.push(-2) print(lista.min()) # -> -2 lista.pop() # removendo o -2 print(lista.min()) # -> 0
08fa090859750f430dd97af978e42167760aff0b
AmandaCarvalhoo/BLASTOFF
/00 - Enunciados.py
1,908
3.75
4
"""" Teste de lógica BLASTOFF ------ FOI FEITO TODO EM LINGUAGEM PYTHON OBS: Todas as questões foram respondidas exceto: QUESTÃO 13. Pois ainda não estudei matrizes. Todas os arquivos que terminam com .._C significa que estão completos/resolvidos #(feito)1- Dada as idades I, J, K, X, Y. Faça um algoritmo para calcular a média das idades. #(feito)2- Dada a distância A e o combustível gasto B, faça um algoritmo para calcular o consumo médio. #(feito)3 - Dados três números (a, b, c), faça um algoritmo para mostrar o menor número. #(feito)4 - Faça um algoritmo que converta a temperatura de C para F. Utilize a fórmula C= 5/9 (F + 32)######## #(feito) 5 - Faça um algoritmo para apresentar se dois números são múltiplos. #(feito) 6 - Uma partida de futebol iniciou na hora A e terminou na hora B. Faça um algoritmo que calcule o tempo que durou a partida. #(feito) 7 - Dada uma lista de números A[1,2,3,…], faça um algoritmo que retorne uma lista somente com os números pares. #(feito) 8 - Faça um algoritmo que receba um número e retorne se o número é primo ou não. #(feito) 9 - Faça um algoritmo que receba um número e retorne a tabuada desse número. #(feito) 10 - Faça um algoritmo que receba um número e retorne o Fatorial desse número. #(feito) 11 - Dada duas lista de números A[1,2,3,4] e B[1,2,5,8], faça um algoritmo que retorne a intersecção das listas #(feito) 12 - Dada duas lista de números A[1,2,3,4] e B[1,2,5,8], faça um algoritmo que retorne a concatenação das listas. 13 - Faça um algoritmo que receba uma matriz[i,z] como parâmetro e imprima todos os valores dessa matriz. #(feito) 14 - Faça um algoritmo que recebe uma palavra e retorne se a palavra é palíndromo. (Palavra que se pode ler, indiferentemente, da esquerda para direita ou vice-versa. Ex: osso, Ana e etc) """