blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
f32c2b197598ac6dc6f0a20c70d29980358a4521
Janet-ctrl/python
/Chapter4/try116412.py
336
4.0625
4
pizzas =['pikkant', 'meaty treat', 'three cheese', 'chicken', 'sweet chilli'] friend_pizzas = pizzas[:] pizzas.append('vegi') friend_pizzas.append('hawain') print('My favorite pizzas are:') for pizza in pizzas: print(pizza.title()) print('\nMy Friend\'s favorite pizzas are:') for pizza in friend_pizzas: print(pizza.title())
b26882901a152805d40a5ba3baab3faa2ce6711d
sheilla13/Korelasi-Jenis-Presensi-Terhadap-Minat-Kehadiran-Mahasiswa
/NaiveBayes.py
968
3.8125
4
# coding: utf-8 # In[1]: #import libraries import random # to randomize the training dataset import math # self-explanatory import pprint # to pretty print our initial non-panda dataset import pandas as pd # to list and do vector manipulation # In[2]: df = pd.read_csv("DataTraining.csv") print df # In[3]: df # In[4]: from sklearn import preprocessing le = preprocessing.LabelEncoder() # In[5]: smt = le.fit_transform(df['Semester']) print smt # In[6]: gender = le.fit_transform(df['Gender']) print gender # In[7]: jp = le.fit_transform(df['JenisPresensi']) print jp # In[8]: label = le.fit_transform(df['Minat']) print label # In[9]: fs = zip(smt, gender, jp) print fs # In[10]: from sklearn.naive_bayes import GaussianNB # In[18]: #Create a Gaussian Classifier model = GaussianNB() # Train the model using the training sets model.fit(fs, label) #Predict Output predicted = model.predict([[0,1,2],[0,1,1],[3,1,2]]) predicted
ec6d27a25b48a88cf1c90f3949f3d88d3f954454
NukeWolf/Advent-Of-Code-2020-Nukewolf
/18/order of operations.py
2,411
3.640625
4
import re with open('input.txt','r') as f: lines = f.readlines() lines = [x.strip().replace(" ","") for x in lines] #print(lines) #Part 1 def findEndParen(string): current = 1 for ind,val in enumerate(string): if(val == "("): current +=1 elif(val == ")"): current -=1 if(current == 0): return ind def findFirstParen(string): current = 1 for ind,val in enumerate(string[::-1]): if(val == ")"): current +=1 elif(val == "("): current -=1 if(current == 0): return len(string) - ind - 1 def solveExpression(string): result = 0 skip = -1 operation = "+" for ind,val in enumerate(string): if(ind <= skip): continue if(val.isnumeric()): if(operation == "+"): result += int(val) else: result *= int(val) elif(val == "+" or val == "*"): operation = val elif(val == "("): start = ind end = start + 1 + findEndParen(string[start+1:]) skip = end if(operation == "+"): result += solveExpression(string[start+1:end]) else: result *= solveExpression(string[start+1:end]) return result count = 0 for line in lines: res = solveExpression(line) count+= res print(count) def insert_str(string, str_to_insert, index): return string[:index] + str_to_insert + string[index:] #Part 2 newLines = [] for line in lines: index = 0 while (index < len(line)): if (line[index] == "+"): #Check what is before if(line[index+1].isnumeric()): line = insert_str(line,")",index+2) if(line[index+1]=="("): end = index + 3 + findEndParen(line[index+2:]) line = insert_str(line,")",end) if(line[index-1].isnumeric()): line = insert_str(line,"(",index-1) if(line[index-1]==")"): beginning = findFirstParen(line[:index-1]) line = insert_str(line,"(",beginning) index+=1 index+=1 #print(line) #input() newLines.append(line) count = 0 for line in newLines: res = solveExpression(line) print(res) count+= res print(count)
7dd06e09fcd98cbc31e8bde1d16fb7b41bec9266
NukeWolf/Advent-Of-Code-2020-Nukewolf
/21/Allergens.py
1,857
3.640625
4
with open('input.txt','r') as f: lines = f.read().strip().split('\n') allergenList = [] for food in lines: foods = {} split = food.split(' (contains ') foods['ingredients'] = split[0].split(' ') allergy = split[1][:-1].split(', ') foods['allergens'] = allergy allergenList.append(foods) allergies = [] for food in allergenList: for allergen in food['allergens']: allergies.append(allergen) allergies = list(set(allergies)) print(allergies) initialList = {} for allergy in allergies: possibleIngredients = None for food in allergenList: if (allergy in food['allergens']): if(possibleIngredients == None): possibleIngredients = food['ingredients'] continue newPossibleList = [] for ingredient in possibleIngredients: if ingredient in food['ingredients']: newPossibleList.append(ingredient) possibleIngredients = newPossibleList initialList[allergy] = possibleIngredients print(initialList) for x in range(30): for allergen in initialList: if (len(initialList[allergen]) == 1): remove = initialList[allergen][0] for allergen in initialList: if (len(initialList[allergen]) != 1): try: initialList[allergen].remove(remove) except: pass combinedAllergens = [initialList[allergen][0] for allergen in initialList] print(combinedAllergens) count = 0 for food in allergenList: for ingredient in food['ingredients']: if (not ingredient in combinedAllergens): count+=1 print(count) sortedAllergensByEnglishName = [initialList[allergen][0] for allergen in sorted(initialList)] print(','.join(sortedAllergensByEnglishName))
b2b652acf6f4c5dbd568b6d7ce7cda4286371d59
Resolt/ML_Bootcamp
/LinearRegression/LinearRegressionProject.py
2,334
3.5625
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression as LR from sklearn.model_selection import train_test_split from sklearn import metrics plt.style.use('ggplot') # plt.tight_layout() dir = 'Bootcamp/LinearRegression/' df = pd.read_csv(dir+'Ecommerce Customers') print(df.head()) print(df.info()) print(df.describe()) # PLOTTING sns.jointplot(x='Time on Website',y='Yearly Amount Spent',data=df) sns.jointplot(x='Time on App',y='Yearly Amount Spent',data=df) sns.jointplot(x='Time on App',y='Length of Membership',data=df,kind='hex') sns.pairplot(df) # LENGTH OF MEMBERSHIP LOOKS LIKE THE MOST CORRELATED FEATURE sns.lmplot(x='Length of Membership',y='Yearly Amount Spent', data=df) plt.show() # LINEAR REGRESSION cols = ['Avg. Session Length','Time on App','Time on Website','Length of Membership'] X = df[cols] y = df['Yearly Amount Spent'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101) lm = LR(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False) lm.fit(X_train, y_train) # PRINT THE COEFFICIENTS NICELY IN A DATAFRAME print("Coefficients of fitted model:\n{}\n".format( pd.DataFrame(lm.coef_,X.columns,columns=['Coeff']) )) # PUT THE TARGETS AND PREDICTIONS ON DATAFRAME AND PRINT CORRELATIONS pred = pd.DataFrame({'A':y_test,'B':lm.predict(X_test)}) print("Correlation: {}\n".format(pred.corr())) # SCATTER PLOT THE TARGETS AND THE PREDICTIONS sns.scatterplot(x='A',y='B',data=pred) plt.show() # EVALUATE MODEL PERFORMANCE WITH THESE METRICS (LOWER IS BETTER) print("MAE: {}\n".format(metrics.mean_absolute_error(pred['A'], pred['B']))) print("MSE: {}\n".format(metrics.mean_squared_error(pred['A'], pred['B']))) print("RMSE: {}\n".format(np.sqrt(metrics.mean_squared_error(pred['A'], pred['B'])))) # PLOT THE RESIDUALS (TARGET MINUS PREDICTION - DISTANCE TO TARGETS) sns.distplot((pred['A']-pred['B'])) plt.show() # THE REQUESTED DATA FRAME WAS CREATED EARLIER # CONCLUSIONS # A - Time on website has next to no influence on yearly amount spent # B - Length of membership has most influence, so keeping people around appears to be the most important factor (loyalty plan?) # C - Spending more time on mobile affects the spending as well, UXD should be of high concern
499d425b3c3e8a3e3f3381f2f50230f6a76dc8cc
Grissie/Python
/1-Sintaxis/02-tipos-datos.py
560
3.640625
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 12 19:00:17 2020 @author: Gris """ def main(): x=None y=5*2+4-3*8 z=5/2.0 w="Esto es una cadena" d='Esta es un dicho "Más vale pájaro en mano, que cientos volando"' a="""Esto también es una cadena""" entrada=input("Ingrese su nombre: ") print("Tipo de dato de x: ",type(x)) print("El resultado de y: ",y) print("El resultado de z: ",z) print('\n') print(w) print(d) print(a) print(w+' '+a) print(w*4) print("Hola %s"%entrada) main()
32c15b7519c1bdf963fab88891dc2f9dc29cb6e4
Grissie/Python
/1-Sintaxis/22-funciones-valor-referencia.py
1,022
3.84375
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 14 20:06:42 2020 @author: Gris """ #Referencia -> Listas def doblarValores(numeros): for i in range(0,len(numeros)-1): numeros[i] *= 2 ns=[2,4,8,10,12,14] print("Lista inicial") print(ns) doblarValores(ns) print("Lista duplicada") print(ns) #Valor def numero(a): a=5 print("Valor de 'a' dentro de la funcion: %d"%(a)) a=15 print("Valor de 'a' antes de la funcion: %d"%(a)) numero(a) #Paso por referencia #Se manda la variable(direccion de memoria) #y sus datos ya son modificados en la función #Siempre para tipos de datos compuestos #Listas, diccionarios, conjuntos.... c1 =[1,2,3] def duplicar(c): for i,n in enumerate(c): c[i]= c[i]*2 print(c[i]) print("Lista c1") print(c1) print("Lista c1 duplicada") print(duplicar(c1)) #Simular dato simple como referencia n=10 def duplicar(n): n = n*2 return n print(n) n = duplicar(n) print(n) #simular dato compuesto pase como valor duplicar(c2[:]) #llamada a la funcion mandando la copia de la variable
08687482497f528b16fbd3d6a7d7270021cf08b9
Grissie/Python
/2-Algoritmos de ordenamiento/4-heapSort.py
1,637
3.765625
4
def heapify(l,i): #Si el nodo tiene dos hijos if 2*i+2<=len(l)-1: #El hijo izquierdo es menor al hijo derecho if l[2*i+1]<= l[2*i+2]: min=2*i+1 #El hijo derecho es el menor else: min=2*i+2 #Comparar el valor del menor de los hijos con el padre, preguntamos #El padre es mayor al menor del hijo if l[i]>l[min]: #Intercambio aux=l[i] l[i]=l[min] l[min]=aux #Recursividad heapify(l,min) #Si tiene un hijo elif 2*i+1<=len(l)-1: #Hijo menor que el padre ? if l[i]>l[2*i+1]: aux=l[i] l[i]=l[2*i+1] l[2*i+1]=aux return l def heapSort(l): #Lista final l2=[] #Iterar sobre lista desde la longitud de la lista//2-1 #hasta -1, decremento de -1 for i in range(len(l)//2-1,-1,-1): #Recibe una lista a ordenar y el valor i l=heapify(l,i) #Iterar en el rango de 0 hasta la longitud de la lista menos uno for i in range(0,len(l)): #Intercambio aux=l[0] #Primer elemento de la lista igual al ultimo elmento l[0]=l[len(l)-1] #Ultimo elemento de la lista igual al primero l[len(l)-1]=aux #Agregar ultimo elemento de la lista l2.append(aux) #Eliminar el ultimo elemento de la lista l=l[:len(l)-1] #Recursividad con la lista y el nodo cero l=heapify(l,0) return l2 lista=[12,78,90,2,12,0,32,65] print("Lista original \n",lista) print("Lista ordenada \n",heapSort(lista))
9a4720d070f056e06b8c73bcee97ca49c7d76049
Grissie/Python
/1-Sintaxis/29-expresiones-regulares.py
1,116
3.625
4
#-*- coding: utf-8 -*- """ Created on Thu Sep 24 21:54:24 2020 @author: Gris """ #Libreria para hacer uso de expresiones regulares import re buscar='no' texto='Este es un texto de ejemplo, el cual no dice nada en concreto. Además sirve para probar el modulo regex de python.' texto2='Nosotros no somos animales, somos humanos.' #Buscamos alguna coincidencia en cualquier posicion match = re.search(buscar,texto) print(match) #Regresa la posicion/indice donde encuentra la coincidencia inicio=match.start() fin=match.end() print(inicio);print(fin) print('Buscar: "{}" en \n"{}"\nIndices donde se encontro: \nDe {} a {} ("{}")' .format(match.re.pattern, match.string,inicio, fin, texto[inicio:fin])) #Compilar para buscar el patron # Precompile the patterns regexes = [ re.compile(p) for p in ['this', 'that'] ] text = 'Does this text match the pattern?' print('Text: {!r}\n'.format(text)) for regex in regexes: print('Seeking "{}" ->'.format(regex.pattern), end=' ') if regex.search(text): print('match!') else: print('no match')
149dd9a37bd79adbc7a909bf6cd63a151a669d8f
bluivy/personal-assistant
/PatriciaParker2.py
1,437
3.546875
4
import speech_recognition as sr from time import ctime import time import os from gtts import gTTS def say(audiostring): print(audiostring) tts=gTTS(text=audiostring,lang='en-uk') tts.save("pcvoice.mp3") os.system("start pcvoice.mp3") def recordaudio(): r=sr.Recognizer() with sr.Microphone() as source: print("say something") audio=r.listen(source) data="" try: data=r.recognize_google(audio) print("you said"+data) except sr.UnknownValueError: print("I didnt quite get what you said") except sr.RequestError as e: print("There are some glitches I guess;{0}".format(e)) return data def Nova(data): if "how are you" in data: say("I am fine Nivya,Thanks for the concern") elif "what time is it" in data: say(ctime()) elif "what is your name" in data: say("I am first generation personal assistant,My name is PatriciaParker") elif "what can you do" in data: say("As of now I can tell time for you") say("do you wanna know what time is it?") say(ctime()) elif "tell a joke in data" in data: say("I am sorry im not programmed to do that") time.sleep(2) say("This is PatriciaParker,I am glad to be of help") while 1: data=recordaudio() Nova(data)
5aeeda32fa924d2cd845a4936b71d98c6dc28885
linuxacademy/content-gui-programming-with-python
/messages.py
1,464
3.640625
4
import tkinter as tk import sys from tkinter import messagebox root = tk.Tk() root.minsize(width=200, height=250) root.resizable(width=False, height=False) def display_message(func_name, **kwargs): def display(): answer = getattr(sys.modules[messagebox.__name__], func_name)(**kwargs) if answer == True: print("You clicked something that returned True") elif answer == False: print("You clicked something that returned False") elif answer == "yes": print("You clicked something that returned 'yes'") elif answer == "no": print("You clicked something that returned 'no'") elif answer == None: print("You clicked something that returned None") return display functions = [ ("askokcancel", messagebox.QUESTION), ("askquestion", messagebox.QUESTION), ("askretrycancel", messagebox.QUESTION), ("askyesno", messagebox.QUESTION), ("askyesnocancel", messagebox.QUESTION), ("showerror", messagebox.ERROR), ("showinfo", messagebox.INFO), ("showwarning", messagebox.WARNING), ] for func, icon in functions: button = tk.Button( root, text=f"Display {func}", command=display_message( func, title=f"Rendered {func}", message="Message goes here", icon=icon, detail="Details go here", ), ) button.pack() root.mainloop()
efffd3b52497bf990f8a02ea00af6f8f360f0270
musatoktas/Numerical_Analysis
/Python/Non-Linear Equations Roots/step_decreasing.py
387
4.125
4
x = float(input("Enter X value:")) h = float(input("Enter H value:")) a = float(input("Enter a value:")) eps = float(input("Enter Epsilon value:")) def my_func(k): import math j = math.sin(k) l = 2*pow(k,3) m = l-j-5 return m while (h>eps): y = my_func(x) z = my_func(x+h) if (y*z>0): x = x + h else: h = h / a print('root is: %f'%x)
2c969e27e178cb286b98b7e320b5bbdcaee3b8f7
ProximaDas/HW06
/HW06_ex09_04.py
1,579
4.53125
5
#!/usr/bin/env python # HW06_ex09_04.py # (1) # Write a function named uses_only that takes a word and a string of letters, # and that returns True if the word contains only letters in the list. # - write uses_only # (2) # Can you make a sentence using only the letters acefhlo? Other than "Hoe # alfalfa?" # - write function to assist you # - type favorite sentence(s) here: # 1: reproachful coalfishes # 2: coalfishes reproachfully # 3: coalfishes reproachfulnesses ############################################################################## # Imports import itertools # Body def uses_only(word,letters): flag = False for letter in word.lower(): if letter in letters.lower(): flag = True else: flag = False break return flag def make_sentence(): letters = "acefhlo" flag = False word_list = [] with open("words.txt","r") as handler: words = handler.read().split() for word in words: for letter in letters: if letter in word: flag = True else: flag = False break if flag == True: word_list.append(word) print ' '.join(word_list) # def combination(): # list_ = list('acefhlo') # new = itertools.chain.from_iterable(itertools.combinations(list_,i) for i in range(len(list_)+1)) # # print list(new) # while True: # try: # print ''.join(new.next()) # except: # break ############################################################################## def main(): print uses_only("banana","aBn") make_sentence() combination() if __name__ == '__main__': main()
6c4ecc2e39a5a1a0c59199b506255d7fa8694605
PuffyShoggoth/Competitive
/Fun Math/Prime Factorization.py
207
3.765625
4
import math n=int(input()) for i in range(n): f=int(input()) for k in range(2, int(math.sqrt(f))+2): while f%k==0: print(k, end=" ") f=f//k if f!=1: print(f) else: print()
87c381b53a57865e44be48395d1e7298273d5096
PuffyShoggoth/Competitive
/CCC/CCC '04 J4 - Simple Encryption.py
496
3.8125
4
keyword=input() withsymbols=input() tocode='' for i in range(0, len(withsymbols)): if withsymbols[i].isalpha(): tocode=tocode+withsymbols[i] c={} def lettershift(x, y): if ord(x)+ord(y)-ord('A')>ord('Z'): return chr((ord(x)+ord(y))-ord('Z')-1) else: return chr(ord(x)+ord(y)-ord('A')) for i in range(0, len(keyword)): for q in range(i, len(tocode), len(keyword)): c[q]=lettershift(tocode[q], keyword[i]) coded='' for i in range(0, len(c)): coded=coded+c[i] print(coded)
6c44aa1cb893940e31bd557dea89581b8cd90fd2
PuffyShoggoth/Competitive
/Seasonal/Rabbit Girls.py
140
3.703125
4
girls=int(input()) groups=int(input()) h=girls%groups if h==0: print(0) elif girls<groups: print(groups-girls) else: print(min(groups-h, h))
90721da9b3098ef0418361996ed0cbc0757ff048
PuffyShoggoth/Competitive
/Uncategorized/Boolean.py
122
3.8125
4
h=input().split() i=h.count('not') if i%2==0: print(h[len(h)-1]) elif h[len(h)-1]=='False': print(True) else: print(False)
cb78d8ee4206130172f0f32307cec5db7bbea3bc
PuffyShoggoth/Competitive
/CCC/CCC '02 S1 - The Students' Council Breakfast.py
582
3.78125
4
pink=int(input()) green=int(input()) red=int(input()) orange=int(input()) prof=int(input()) combos=0 mintic=prof for a in range(0, prof+1): for b in range(0, prof+1): for c in range(0, prof+1): for d in range(0, prof+1): if a*pink+b*green+c*red+d*orange==prof: print('# of PINK is', a, '# of GREEN is', b, '# of RED is', c, '# of ORANGE is', d) combos=combos+1 if a+b+c+d<mintic: mintic=a+b+c+d print('Total combinations is', str(combos)+'.') print('Minimum number of tickets to print is', str(mintic)+'.')
14141a05debe15e7b2e343affc461cb94fc93768
PuffyShoggoth/Competitive
/CCC/CCC '02 S2 - Fraction Action.py
336
3.671875
4
noom=int(input()) denom=int(input()) num=noom//denom fra=noom%denom for i in range(1, denom//2+1): if fra%i==0 and denom%i==0: fra=fra/i denom=denom/i if num==0 and fra==0: print('0') elif num==0: print(str(int(fra))+'/'+str(int(denom))) elif fra==0:print(int(num)) else: print(int(num),str(int(fra))+'/'+str(int(denom)))
583535a0c18294a5c8996a07e658bc9b0c0331f4
PuffyShoggoth/Competitive
/CCC/CCC '15 J2 - Happy or Sad.py
278
3.640625
4
stg=str(input()) happy=0 sad=0 for i in range(0, len(stg)): if stg[i:i+3]==':-)': happy=happy+1 if stg[i:i+3]==':-(': sad=sad+1 if sad==0 and happy==0: print('none') elif sad==happy: print('unsure') elif sad>happy: print('sad') else: print('happy')
aac914aab179e655a9af2cbb9bf3a5f3b01d79fe
PuffyShoggoth/Competitive
/GFSSOC/OR-deal.py
65
3.609375
4
n=int(input()) while(n>1): print(1, end="") n=n//2 print(1)
fcdddc65c38a3fef5cd2ea1e24e601a4db05db11
jerrypirkle/Scrapers
/pysrt.py
921
3.84375
4
#!/usr/bin/env python3 """ Creates a list of planets and sorts alphabetically """ __author__ = "jerry pirkle" __version__ = "0.1.0" __license__ = "MIT" def main(): """ Input: Sector text file with items delimited with % Output: Sorted list of planets """ # Should be taken as a command line argument if this is used multiple times fileName = "ErtuSector.txt" sectorFile = open(fileName, 'r').readlines() count = 0 lineList = "" result = [] for line in sectorFile: lineList += line if line == "%\n": count +=1 result.append(lineList) lineList = "" sorted_list = sorted(result) f = open("outputFile.txt", "a") for i in sorted_list: # print(i) f.write(i.replace("%", "")) f.close() if __name__ == "__main__": """ This is executed when run from the command line """ sectorFile = "" main()
5a4b1df79339104f72a3ee9e9b3041116cbbc219
zxczhkzxc/image-etl
/object_detection_etl/utils/get_color_code.py
2,496
3.546875
4
from sklearn.cluster import KMeans from sklearn import metrics import cv2 # By Adrian Rosebrock import numpy as np import cv2 # Load the image # image = cv2.imread("red.png") image = cv2.imread("blue.jpg") image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Resize it h, w, _ = image.shape w_new = int(100 * w / max(w, h) ) h_new = int(100 * h / max(w, h) ) image = cv2.resize(image, (w_new, h_new)); # Reshape the image to be a list of pixels image_array = image.reshape((image.shape[0] * image.shape[1], 3)) print image_array # Clusters the pixels clt = KMeans(n_clusters = 3) clt.fit(image_array) def centroid_histogram(clt): # grab the number of different clusters and create a histogram # based on the number of pixels assigned to each cluster numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) (hist, _) = np.histogram(clt.labels_, bins = numLabels) # normalize the histogram, such that it sums to one hist = hist.astype("float") hist /= hist.sum() # return the histogram return hist # Finds how many pixels are in each cluster hist = centroid_histogram(clt) # Sort the clusters according to how many pixel they have zipped = zip (hist, clt.cluster_centers_) zipped.sort(reverse=True, key=lambda x : x[0]) hist, clt.cluster_centers = zip(*zipped) # By Adrian Rosebrock import numpy as np import cv2 bestSilhouette = -1 bestClusters = 0; for clusters in range(2, 10): # Cluster colours clt = KMeans(n_clusters = clusters) clt.fit(image_array) # Validate clustering result silhouette = metrics.silhouette_score(image_array, clt.labels_, metric='euclidean') # Find the best one if silhouette > bestSilhouette: bestSilhouette = silhouette; bestClusters = clusters; print(bestSilhouette) print(bestClusters) def plot_colors(hist, centroids): # initialize the bar chart representing the relative frequency # of each of the colors bar = np.zeros((50, 300, 3), dtype="uint8") startX = 0 # loop over the percentage of each cluster and the color of # each cluster for (percent, color) in zip(hist, centroids): # plot the relative percentage of each cluster endX = startX + (percent * 300) cv2.rectangle(bar, (int(startX), 0), (int(endX), 50), color.astype("uint8").tolist(), -1) startX = endX # return the bar chart return bar bar = plot_colors(hist, clt.cluster_centers_) import matplotlib.pyplot as plt # show our color bart plt.figure() plt.axis("off") plt.imshow(bar) plt.show()
6f434bc4ee40877cec79f70bb58400f90ccbc529
bramvanderzee/advent2019
/day04/4b.py
675
3.6875
4
lower = 353096 upper = 843213 def check(num, lower, upper): numList = sorted([int(x) for x in str(num)]) for i, x in enumerate(numList): if int(num[i]) != int(x): return False foundAdjacent = False for i, x in enumerate(num): if i == 5: break if int(num[i+1]) == int(x) and num.count(x) == 2: foundAdjacent = True break if not foundAdjacent: return False if int(num) < lower or int(num) > upper: return False return True passwords = [] for i in range(lower, upper+1): if check(str(i), lower, upper): passwords.append(i) print(len(passwords))
9f20edffd433138aae3ecb014c25b55790e122fc
bramvanderzee/advent2019
/day03/3b.py
1,611
3.671875
4
fn = 'input.txt' class Coord: def __init__(self, x, y): self.x = x self.y = y def pathToCoords(path): pointer = Coord(0,0) coords = [] for instruction in path: direction = instruction[0] dist = int(instruction[1:]) if direction == 'R': coords.extend([(x, pointer.y) for x in range(pointer.x, pointer.x+dist)]) pointer = Coord(pointer.x+dist, pointer.y) elif direction == 'L': coords.extend([(x, pointer.y) for x in range(pointer.x, pointer.x-dist, -1)]) pointer = Coord(pointer.x-dist, pointer.y) elif direction == 'U': coords.extend([(pointer.x, y) for y in range(pointer.y, pointer.y+dist)]) pointer = Coord(pointer.x, pointer.y+dist) elif direction == 'D': coords.extend([(pointer.x, y) for y in range(pointer.y, pointer.y-dist, -1)]) pointer = Coord(pointer.x, pointer.y-dist) return coords lin = [] with open(fn) as f: lin = f.readlines() path1 = lin[0].split(',') path2 = lin[1].split(',') intersects = [] coords1 = pathToCoords(path1) coords2 = pathToCoords(path2) print('Path to coords done') print(len(coords1),len(coords2)) for i in range(len(coords1)): for o in range(len(coords2)): x1, y1 = coords1[i] x2, y2 = coords2[o] if x1 == x2 and y1 == y2: intersects.append([x1, y1, i, o]) print(x1, y1, i + o) print('Found intersections') dists = [] origin = (0,0) for data in intersects: dists.append(int(data[2]) + int(data[3])) dists.sort() print(dists)
08e4640b17d9b466862ff168e76ef4bb7f39bb36
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio068.py
1,799
3.875
4
# Desafio068 programa que jogue par ou impar. finaliza quando jogador perder, mostrando total de vitorias consecutivas. # importanto a função rondom e a funçãi sleep. from random import randint import time numeropc = randint(0,10) resultadoFinal = str() resultadoFinalN = int() imparParPc = int falaPc = str() contador = -1 while resultadoFinalN != imparParPc: # escolha do jogador jogadorPouI = str(input('escolha PAR ou IMPAR ')).strip().lower() imparParjogador = int() # Escolha do Pc # convertemos a string em inteiro if jogadorPouI == 'par': imparParjogador = 0 imparParPc = 1 falaPc = 'IMPAR' print(' Você é \033[2;32m PAR \033[m e eu sou \033[2;32m IMPAR \033[m ') if jogadorPouI == 'impar': imparParjogador = 1 imparParPc = 0 falaPc = 'PAR' print(' Você é \033[2;32m IMPAR \033[m e eu sou \033[2;32m PAR \033[m ') else: print('Esse é um jogo de par ou impar, entao digite algo valido, como Par ou Impar') print('Estou pensando em um numero...') time.sleep(2) print('....') time.sleep(1) print('....... ') time.sleep(1) print('pronto ja pensei...') myescolha = int(input('Sua vez escolha quantos dedos. \nSó valem os das mãos, ou seja, escola de 1 a 10 ')) contador += 1 soma = numeropc + myescolha if soma %2 == 0: resultadoFinal = 'PAR' resultadoFinalN = 0 if soma %2 != 0: resultadoFinalN = 1 resultadoFinal = 'IMPAR' if resultadoFinalN == imparParjogador: print(f'Eu escolhi {numeropc}, ja voce escolheu {myescolha}, o total é {soma} que é um numero {resultadoFinal}, entao você Ganhou. vamos outra') print(f'Voce perdeu, mas ganhou {contador} vezes antes de perder.')
351efcfee569a265f41fd78b55fbaa4c04f823c3
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio019b.py
200
3.578125
4
#Desafio019b segunda tentativa de criar( aplicação randomica para determinar que aluno vai no quadro. import random al01 = str('joao') al02 = str('paula') al = (al01,al02) print(random.choice(al))
9883f8a50e17c28d9ebfbb9b12b31464910ed2f9
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio049.py
258
3.90625
4
# Desafio049: fazer a tabuada num01 = int(input('insira um numero para saber a tabuada dele ')) ate = int(input('insira até onde quer a tabuada ')) for c in range(0,ate): number = c+1 num00 = number*num01 print(f'{num01} X {number} = {num00}')
a1ba04ea990b1b978940e7bc6ba5ba513a2bf683
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio017.py
248
4.0625
4
# descobre o valor da hypotenuse ( hipotenusa) from math import sqrt n1 = float(input('digite o comprimento do cateto oposto ')) n2 = float(input('digite o comprimento do cateto adjacente ')) print(f'O valor da hipotenusa é {sqrt(n1*n1+n2*n2)}')
369f7919463d3e478996444a97dad645cc9fbf9b
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo3/Desafio084b.py
962
3.90625
4
# Desafio084 ESSE PROGRAMA lê o nome e peso de varias pessoas. no final mostra quantas pessoas foram cadastradas listaTemp = [] namePeso = [] maior = 0 nmaior = '' menor = 0 nmenor = '' print('para sair do programa digite sair no campo nome') while True: listaTemp.append(str(input('Nome: '))) if 'sair' in listaTemp: listaTemp.clear() break listaTemp.append(int(input('Peso: '))) if len(namePeso) == 0: maior = menor = listaTemp[1] nmaior = nmenor = listaTemp[0] else: if listaTemp[1] > maior: maior = listaTemp[1] nmaior = listaTemp[0] if listaTemp[1] < menor: menor = listaTemp[1] nmenor = listaTemp[0] namePeso.append(listaTemp[:]) listaTemp.clear() print(namePeso) print(f'Foram cadastrado {len(namePeso)} Pessoas. ') print(f'Quem tem o maior Peso é {maior}') print(f'O menor peso é de {menor}') print(f'{nmaior} e {nmaior}')
a2269827a7ec319057a12375b004b0118e6ea809
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/aula010.py
227
4.03125
4
# documentação bla bla bla, trabalahndo com if e else name = str(input('Qual o seu nome seu nome?')) if name == 'marco': print('Que nome de um cara fodelão!!!') else: print('que nome bosta') print(f'seja bem vindo {name}')
8d2569ca35b4e74a34839f736fbd7c47b174f580
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio058c.py
744
4
4
# Desafio058c descobrir numero com quente ou frio from random import randint numeroPc = randint(0,100) print(numeroPc) numeroUser = int() numerotemp = int() numerotemp2 = int() tentativas = int() while not numeroUser == numeroPc: numeroUser = int(input('Advinhe o numero de 0 a 100 que eu estou pensando!')) tentativas += 1 if numeroUser > numeroPc: numerotemp = numeroUser - numeroPc if numeroUser < numeroPc: numerotemp = numeroPc - numeroUser print(numerotemp) if numerotemp2 < numerotemp: print(' ta esfriando') if numerotemp2 > numerotemp: print(' ta esquentando') numerotemp2 = numerotemp print(f'parabéns voce acertou o numero que eu pensei em {tentativas} tentativas.')
aa1403aeaa7c51aa6031bd5361a55cb8a796bc78
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo3/Desafio086b.py
423
4.125
4
# Desafio086b criar uma matriz 3*3 e preencher ela com dados. alista = [[0,0,0],[0,0,0],[0,0,0]] for l in range(0,3): for c in range(0,3): alista[l][c] = int(input(f'Insira o numero da posição {l},{c}')) for c in range (0,3): for d in range(0,3): print(f'{alista[c][d]:^5}',end='') print() # print(f'{alista[0]:^5}\n{alista[1]}\n{alista[2]}') # essa é outra posssiblidade de fazer o print
c826d42f8b5564ced62fef3934aac2eb763030ac
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo3/Desafio104.py
430
4
4
# Desqafio104 o programa possui uma função que verifica se o input é um numero int def leiaInt (num): while True: if num.isnumeric(): return num #print(f'Você digitou {num}') #break else: print(f' {num} Não é um numero, digite um numero') print() num = input('Digite um numero') novo_numero = leiaInt('k') print(novo_numero)
e9b0a04c85342e1b0c613a50fc9b78afea5fb2b3
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio051.py
458
3.859375
4
# Desafio051 fazer um sistema de P.A Progressao arentimetrica nInicial = int(input('Qual o valor inicial? ')) nRazao = int(input('Qual a Razão ? ')) nSquencia =int(input('Qual o tamanha da P.A? ')) sequen = nInicial-nRazao fim = int(0) while fim != nSquencia: sequen = + nRazao + sequen fim += 1 print(f'fim:{fim}') print(sequen) '''numero inicial razao quantos numeros na sequencia quantas vezes numero inicial + razao'''
86d68ee779c54c96654a40b6731b56af8f7a61fc
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio033.py
439
3.984375
4
#A aplicação recebe 3 idades e diz quem é mais velho a = int(input('digite a idade da primeira pessoa')) b = int(input('digite a idade da segunda pessoa')) c = int(input('digite a idade da terceira pessoa')) menor = (a) maior = (a) if b<a and b<c: menor = b elif c<a and c < b: menor = c print(f'o menor valor é {menor}') if b > a and b > c: maior = b elif c > a and c > b: maior = c print(f'o maior valor é {maior}')
f8a8333d1f190af23e527f2e695f44d08a2ba184
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio039.py
581
3.78125
4
import datetime datenasc = int(input(f'insert you date of bit ')) atualdate = str(datetime.date.today())[0:4] datestr = int(atualdate) datefinal = datestr - datenasc print(datefinal) if datefinal < 18: print(f'voce esta com {datefinal}Faltam {18-datefinal} pra você se alistar ao exercito hahahah' ) elif datefinal == 18: print(f'Você completa 18 anos agora em {atualdate}' f'Chegou a hora ser servir seu país como bucha de canhão otario.\nPegue seus documentos ') else: print(f'Você escapou sabichão, ja esta com {datefinal}, se livrou né safadenho')
61561fd6a7d4af7158635d8b6a14ef10ff300038
bettalazza99/PCS2-Homework-4
/revp.py
570
3.53125
4
def reverse_complement(s): complements = {'A':'T', 'T':'A', 'G':'C', 'C':'G'} return ''.join([complements[a] for a in reversed(s)]) with open("C:\\Users\\Elisabetta\\Desktop\\rosalind_revp.txt")as dna: dna_str = dna.readlines() seq = "" for line in dna_str: line = line.strip() if line[0] != ">": seq += line for i in range(len(seq)): for n in range(4,13): if seq[i:i+n] == reverse_complement(seq[i:i+n]): if i + n <= len(seq): print (i+1, n)
fc8eb527c2948b443be22f8d8da3d6da81e4ca83
KetchupOnWaffles/sudokuGenerator
/show.py
872
3.65625
4
out = open("out.txt", 'w+') def show(line): li = "" for i in line: for j in i: li += str(j) + " " li += "\n" out.write(li) out.write("\n") showline = " _ _ _ _ _ _ _ _ _\n" showline += " _ _ _ _ _ _ _ _ _\n" showline += "| " counter = 0 counter2 =0 for i in line: for j in i: showline+= str(j) showline+= " " if counter == 2: showline += "| " counter = 0 else: counter+=1 showline+="\n" if counter2 == 2: showline += " _ _ _ _ _ _ _ _ _\n" counter2 = 0 else: counter2 +=1 showline += "| " showline+="\n" showline += " _ _ _ _ _ _ _ _ _\n" showline += " _ _ _ _ _ _ _ _ _\n" print(showline)
944e2a71557eb18ecf11191d81df48d7272485b7
nileshsingal/aws-practise
/python/Addition/addition.py
126
3.9375
4
a = int(input("Enter First Number: ")) b = int(input("Enter Second Number: ")) addition = a + b print("Sum Is :",addition)
22d26ae10374b19e6fb6718d6fdf57c73ed386e8
jasonxiaohan/DataStructure
/Map/Solution-349.py
804
3.8125
4
#!/usr/bin/env python # encoding: utf-8 """ @author: daixiaohan @license: (C) Copyright 2018, Node Supply Chain Manager Corporation Limited. @contact: jasonxiaohan198@qq.com @file: Solution-349.py @time: 2018/7/22 11:49 @desc: """ from DataStructure.Set.BSTSet import BSTSet class Solution: def intersection(self, nums1, nums2): """ :param nums1: :param nums2: :return: """ list = [] sets = set() for num1 in nums1: sets.add(num1) for num2 in nums2: if(num2 in sets): list.append(num2) sets.remove(num2) return list if __name__ == '__main__': num1 = [1, 2, 2, 1] nums2 = [2, 2] solution = Solution() list = solution.intersection(num1, nums2) print(list)
87cd59806c49e612324817a83a76c87cdcea4e9e
keshavkant0409/pythonSDET
/array_example4.py
988
4.0625
4
from numpy import * arr=array([4,6,7,8,9]) print(arr) arr=arr+5 print(arr) arr1=array([14,16,17,1,19]) arr3=arr+arr1 print(arr3) print(sin(arr3)) print(cos(arr3)) print(log(arr3)) print(sqrt(arr3)) print(sum(arr3)) print(min(arr3)) print(max(arr3)) print(sort(arr3)) arr4=concatenate([arr1,arr3]) print(arr4,'+++++++++') print(unique(arr4)) 'copy an array' arr5=arr4 print(arr4) print(arr5) print(id(arr4),id(arr5),'++++++++++++++') 'copy array using view(it is a function to copy array at different location and also it is shallow copy i.e if we change value of one array it will change value of other array)' arr6=arr4.view() print(arr4,arr6) print(id(arr4),id(arr6)) arr4[3]=100 print(arr4,arr6,'+++++++++++++') 'copy array using copy(it is a function to copy array at different location and also it is deep copy i.e if we change value of one array it will not change value of other array)' arr7=arr4.copy() print(arr4,arr7) print(id(arr4),id(arr7)) arr4[5]=2100 print(arr4,arr7)
6b490f58bb97d4d2528c479fc9de5c98f3c22c4e
keshavkant0409/pythonSDET
/function_example1.py
233
3.78125
4
def summation(a,b): add=a+b print(add) summation(4,5) def summation1(a,b): add=a+b return add c=summation1(6,7) print(c) def sum_sub(a,b): add=a+b sub=a-b return sub,add c1,d=sum_sub(9,5) print(c1,d)
aea37d348ee18b8ad849540bd2ee511372c481ca
Fleshwork/100-Days-of-Python
/100 Days of Python/Day Two/Tip Calculator v1.py
437
4.09375
4
priceTotal = float(input("What was the total price of your bill? ")) tipPercent = int(input("How much tip? 10, 12 or 15%? ")) numberOfDiners = int(input("How many people are paying? ")) #pre calc maxTotal = tipPercent /100 * priceTotal + priceTotal #calculation pricePerPerson = maxTotal / numberOfDiners result = "{:.2f}".format(pricePerPerson) #print message = f"Each person should pay ${result}" print(message)
fd5053556cb49b6580f6319b3b4bdbf416224d6e
KeerthanaPriya-B/ProgramS
/Comparing Strings.py
368
3.5
4
s1 = input() s2 = input() flag,first,second=0,'','' if len(s1)<len(s2): first=s1 second=s2 else: first=s2 second=s1 for j in first: for k in second: if(j==k): print('YES') flag=1 if flag==1: break if flag==1: break if flag==0 : print('NO')
dd0ff2cd46ecbb046d3c9b341526b87e371f5eb1
KeerthanaPriya-B/ProgramS
/Print the missing alphabets.py
124
3.78125
4
s=input() alpha='abcdefghijklmnopqrstuvwxyz' missing="" for i in alpha: if i not in s: missing+=i print(missing)
78861ffe43fdcf67fdea185ff9efe32bc63b1d64
ehdqoddl6/coding-test
/backjoon/queue/2164.py
193
3.59375
4
from collections import deque n = int(input()) queue = deque(i+1 for i in range(n)) while(len(queue) > 1): queue.popleft() b = queue.popleft() queue.append(b) print(queue[0])
c44353f5a52823e55df8a6d68415b92207973b0b
ehdqoddl6/coding-test
/backjoon/sort/2751.py
360
3.546875
4
import sys input = sys.stdin.readline n = int(input()) num = [] for i in range(n): num.append(int(input())) import heapq def solution(array): h = [] for x in array: heapq.heappush(h, x) result = [] while(h): result.append(heapq.heappop(h)) return result num = solution(num) for x in num: print(x)
79889a9fd5ef477fdd78c41afe6d530025f2dcb5
ehdqoddl6/coding-test
/backjoon/basicMath/2775.py
607
3.53125
4
#num = int(input()) def solve(k, n): n_list = [i for i in range(1, 15)] last_list = [] for i in range(k): ho_sum = [] sum = 0 if(i == 0): for j in range(n): sum = sum + n_list[j] ho_sum.append(sum) else: for j in range(n): sum = sum + last_list[j] ho_sum.append(sum) last_list = ho_sum print(last_list[n-1]) """ for i in range(num): k = int(input()) n = int(input()) solve(k, n) """ solve(2, 3)
35a03d4c5ebb51b272ce284076da59dddd3525ba
hgarciaospina/PythonArrays
/ejerc_2_40.py
3,415
3.875
4
''' 40. El dueño de una cadena de almacenes de artículos deportivos desea controlar sus ventas por medio de una computadora. Los datos de entrada son: a) El número del almacén (1 a 50) b) Un número que indica el deporte del artículo (1 a 20) Hacer un programa que escriba al final del día lo siguiente: 1. Las ventas totales en el día para cada almacén. 2. Las ventas totales para cada uno de los deportes. 3. Las ventas totales de todos los almacenes ''' #!/usr/bin/python import random #Definición de variables #cadena_almacenes[i][j]- para i=0..49 - para j=0..19 # i = número almacen, j = numero artículo cadena_almacenes = [] ventas_totales_diarias_x_almacen = [] ventas_totales_x_deporte = [] numero_de_almacenes = 50 numero_deporte_articulo = 20 numero_almacen = 0 numero_articulo = 0 venta_articulo_almacen = 0 ventas_articulos_deportes = 0 total_general_almacenes = 0 total_general_deportes = 0 #Asignación de ceros a toda la matriz de 50 x 20 for i in range(numero_de_almacenes): cadena_almacenes.append([0] * numero_deporte_articulo) #Asignación de ceros ventas totales diarias por almacen for i in range(numero_de_almacenes): ventas_totales_diarias_x_almacen.append(0) #Asignación de ceros ventas totales diarias por deporte for i in range(numero_deporte_articulo): ventas_totales_x_deporte.append(0) #Asignación ventas por artículo en cada almacen for numero_almacen in range(numero_de_almacenes): for numero_articulo in range(numero_deporte_articulo): venta_articulo_almacen = random.randint(1, 10) cadena_almacenes[numero_almacen][numero_articulo] = venta_articulo_almacen print("almacen",numero_almacen,"numero artículo", numero_articulo, "venta:", cadena_almacenes[numero_almacen][numero_articulo]) #Proceso de ventas totales diarias por almacen for numero_almacen in range(numero_de_almacenes): for numero_articulo in range(numero_deporte_articulo): ventas_totales_diarias_x_almacen[numero_almacen] = ventas_totales_diarias_x_almacen[numero_almacen] + cadena_almacenes[numero_almacen][numero_articulo] total_general_almacenes = total_general_almacenes + ventas_totales_diarias_x_almacen[numero_almacen] for numero_almacen in range(numero_de_almacenes): for numero_articulo in range(numero_deporte_articulo): print("Almacen : ",numero_almacen, "articulo", numero_articulo, "venta articulo", cadena_almacenes[numero_almacen][numero_articulo]) print("\n") print("--------------------------------------------------------") for numero_almacen in range(numero_de_almacenes): print("Almacen : ",numero_almacen, "venta total diaria almacen", ventas_totales_diarias_x_almacen[numero_almacen]) print('\n') print("Total venta general de los 50 almacenes ", total_general_almacenes) #Proceso de ventas totales por deporte for numero_articulo in range(numero_deporte_articulo): for numero_almacen in range(numero_de_almacenes): ventas_totales_x_deporte[numero_articulo] = ventas_totales_x_deporte[numero_articulo] + cadena_almacenes[numero_almacen][numero_articulo] total_general_deportes = total_general_deportes + ventas_totales_x_deporte[numero_articulo] for numero_articulo in range(numero_deporte_articulo): print("Deporte : ",numero_articulo, "venta total por deporte", ventas_totales_x_deporte[numero_articulo]) print('\n') print("Total venta general de los 20 deportes x cada uno de los 50 almacenes ", total_general_almacenes)
220fbfe3f19fa9c5a1446af79e821919c0095696
hgarciaospina/PythonArrays
/ejerc_2_1.py
868
3.6875
4
''' 1. Calcular el promedio de 10 valores almacenados en un vector. Determinar además cuantos son mayores que el promedio, imprimir el promedio, el número de datos mayores que el promedio y un listado de los valores que resultaron ser mayores al promedio. ''' vector = [25, 100, 30, 95, 80, 45, 87, 63, 11, 29] mayores_promedio = [] promedio = 0 suma = 0 cuenta_mayores_promedio = 0 i = 0 j = 0 for i in range(0,10): suma = suma + vector[i] promedio = suma / 10 for i in range(0,10): if (vector[i] > promedio): mayores_promedio.append(vector[i]) j += 1 cuenta_mayores_promedio = len(mayores_promedio) print("El promedio de los 10 números es: " + str(promedio)) print("Hay " + str(cuenta_mayores_promedio) + " números mayores al promedio") for i in range(0, cuenta_mayores_promedio): print("Número mayor al promedio: " + str(mayores_promedio[i]))
8e8c0d8c6437ef40b0359ab97572b166a4631443
SahishnuTiwari88/OpenCVPython
/chapter3.py
498
3.59375
4
# Resizing & croping import cv2 img = cv2.imread("C:/Users/Sahishnu/Pictures/Screenshots/ada.png") print(img.shape) # it gives height,width and no. for your channels i.e. BGR i.e. colors imgResize = cv2.resize(img,(300,250)) # used to resize the image into desired height and width (width,height) imgCrop = img[0:350,350:750] # first range of height followed by range of width cv2.imshow("image",img) cv2.imshow("Resize image",imgResize) cv2.imshow("Crop Image",imgCrop) cv2.waitKey(0)
308a96b56534d587575e0be55f037bdcbeb5c06e
subbul/python_book
/lists.py
2,387
4.53125
5
simple_list = [1,2,3] print "Simple List",simple_list hetero_list = [1,"Helo",[100,200,300]]# can containheterogenous values print "Original List",hetero_list print "Type of object hetero_list",type(hetero_list) # type of object, shows its fundamental data type, for e.g., here it is LIST print "Item at index 0 ",hetero_list[0] #first index print "Item at index -1",hetero_list[-1] #negative index start from end so here the last elemtn in LIST print "Length -->", len(hetero_list) print "#############################################" big_list = [1,2,3,4,5,6,7,8,9] print " big List", big_list print "lets slice from index [2:]",big_list[2:] # start, end index, includes start, ends before end-index print " slice till [:4]", big_list[:4] # stops before index 4 , 0-1-2-3 new_list = big_list[:] #from beginning to end print "New list is a copy of big list", new_list print "##############################################" big_list = [1,2,3,4,5,6,7,8,9] big_list[2]="x" print " Index 2 is modified to x-->" print big_list big_list[len(big_list):] = [11,12,13] # adding at the end appending print "Appended list", big_list print " Append vs Extend list" list_a = [1,2,3] list_b = ['a','b','c'] print "list a", list_a print "list b", list_b list_a.append(list_b) print "Append b to a", list_a list_a = [1,2,3] list_a.extend(list_b) print "Extend b to a", list_a list_a = [1,2,3] print "Original list", list_a list_a.insert(1,"x") print " x insert before index 1",list_a list_a = [1,2,3] list_a.reverse() print "reverse list", list_a print "1 in list_a", (1 in list_a) print "10 in list_a", (10 in list_a) print "###################################################" def custom_sort(string1): return len(string1) list_a = ["I am","good","World","Very big statement"] list_a.sort() print "Sorted naturally alphabetical", list_a list_a = ["I am","good","World","Very big statement"] list_a.sort(key=custom_sort) print "Sorted using custom key", list_a list_a = [10] * 4 print "list with initialization using *", list_a list_a = [1,11] * 4 print "list with initialization using *", list_a list_a = [10,20,30,40,50,60] print "List -->", list_a print "Index of 40-->", list_a.index(40) list_a = [20,2,442,3,2,67,3] print "List -->", list_a print "Count occurance of 3 in list ==",list_a.count(3)
a860e94cbf066f0b8490329ce4c2bc4d4ec0a3d7
subbul/python_book
/dictionary.py
1,843
4.03125
4
list = [] dictionary = {} # list[0]='hello'// not allowed dictionary[0]='hello' #allowed dictionary["two"]= 2 dictionary["pi"]= 3.14 # literal use of python dictionary english_to_french = {} english_to_french['red'] = 'rouge' english_to_french['blue'] = 'bleu' english_to_french = {'red':'rouge','blue':'bleu','green','vert'} # another representation of name value pairs print "Length of dictionary english_to_french", len(english_to_french) print "Keys of dictionary", english_to_french.keys() print "Values of dictionary", english_to_french.values() print " Items of dictionary, name:value pairs", english_to_french.items() del english_to_french['green'] print " Items after del green", list(english_to_french.items()) # converting from view to list otherwise #iterations will be difficult print "Is Red in Dictionary?-->", "red" in english_to_french print "Is yellow in Dictionary? -->", "yellow" in english_to_french # dictionary.get (search, string_if_search_string_not_found) print "Result of query if red is available?",english_to_french.get("red","red not available") print "Result of query if yello is available?",english_to_french.get("yellow","yellow not available") english_to_french.setdefault('yellow','defaultyellow') #check if yellow has value, if not set defaultyellow #update z = {1:'One',2:'Two'} x = {0:'Zero',1:'one'} print " Z is -->",z.items() print " X is -->",x.items() x.update(z) print " Updated X",x.items() #word counting sample_string = "to be or not to be" occurence = {} for word in sample_string.split(): occurence[word] = occurence.get(word,0)+1 for word in occurence: print ("The word is occuring ",occuring[word],"times") #sparse matrix contain only non-zero items matrix = { (0,0):3, (0,2):-2,(0,3):11,(1,1):9,(2,1): 7 ,(3,3):-5} matrix.get((rownum,colnum),0) #dictionary for caching
84abdd28ee4e617cb1c0ffff2fedf7c0e9b1a543
krylov-as/python-project-lvl1
/brain_games/scripts/brain_prime.py
534
3.6875
4
#!/usr/bin/env python3 """Start game brain-prime.""" import brain_games.cli as cli import brain_games.is_prime as is_prime def main(): """Ask name user. Start Brain Games - brain-prime.""" print('Welcome to the Brain Games!') name = cli.welcome_user() print('Answer "yes" if the number is prime. Otherwise answer "no".') check = is_prime.game() if check: print('Congratulations, {}!'.format(name)) else: print("Let's try again, {}!".format(name)) if __name__ == '__main__': main()
e2214418b67873b50836766a94f3c3fb2108e683
krylov-as/python-project-lvl1
/brain_games/scripts/brain_calc.py
498
3.546875
4
#!/usr/bin/env python3 """Start game brain-calc.""" import brain_games.cli as cli import brain_games.calc as calc def main(): """Ask name user. Start Brain Games - brain-calc.""" print('Welcome to the Brain Games!') name = cli.welcome_user() print('What is the result of the expression?') check = calc.game() if check: print('Congratulations, {}!'.format(name)) else: print("Let's try again, {}!".format(name)) if __name__ == '__main__': main()
6ee270b6763c17cce3b67a00e2e5c3f72fd28da8
rkumar2468/AI
/Project-05/ClickStream/Tree.py
1,426
3.625
4
__author__ = 'sri' class Node: #This class represents the tree data structure def __init__(self, val): self.value = val self.children = [] self.distribution = 0 self.parent = None def addDist(self, dist): self.distribution = dist def addChildren(self, childNode): if self.children: self.children.append(childNode) else: self.children = [childNode] childNode.parent = self def getChildren(self): return self.children def getDistribution(self): return self.distribution def getParent(self): return self.parent def getValue(self): return self.value class TreeTraversals: def __init__(self, node): self.root = node def getParentList(self): #Function to get the parents of a given node temp = self.root list = [] while temp.getParent() != None: temp = temp.getParent() list.append(temp.value) return list def dfs(self): if self.root: self.dfsUtil(self.root) def dfsUtil(self, node): print node.getValue(), ' -> ', for i in node.getChildren(): self.dfsUtil(i) print ',' print " //"
626bcc62f786c5cfb15559748a7cd7005d3e4a01
Josh-Cruz/python-strings-and-list-prac
/PYthon_Dict_basics.py
335
3.796875
4
josh_C = { "name": "Josh", "age": 30, "country": "Murica", "fav_lan": "Python" } def print_info(dict): print "My name is", dict["name"] print "My age is", dict["age"] print "My country of origin is", dict["country"] print "My favorite language to code in is", dict["fav_lan"] print(print_info(josh_C))
5f717d310289edd62d65b001a0f4feb7bd110738
Soumithroy/Internwork
/Soumith.py
1,999
4
4
import time from datetime import datetime, date, time, timedelta import ast def MissingDates(thisdict): #creating list of keys and values keylist = list() valuelist=list() #creating updated list of missing keys and values upkey=list() upvalue=list() #converting keys to date and storing in the keylist for i in thisdict.keys(): keylist.append(datetime.strptime(i, '%Y-%m-%d')) #storing the values from dictionary into value list valuelist.append(thisdict[i]) #accessing adjacent keys to find the missing days for i in range(len(keylist)-1): diff=keylist[i+1]-keylist[i]; #checking if there are any missing days if (diff.days)>1: firstday=keylist[i]; firstvalue=int(valuelist[i]); #calculating the average avg=(int(valuelist[i+1])-int(valuelist[i]))/(diff.days); #adding missing dates for j in range(1,diff.days): #adding missing date key to upkey list firstday+=timedelta(days=1) upkey.insert(j,str(firstday)); #adding missing value to upvalue list firstvalue=firstvalue+avg; upvalue.insert(j,int(firstvalue)); #adding missing key-value from lists to dictionary for key in upkey: for value in upvalue: thisdict[key] = value upvalue.remove(value) break #sorting on basis of keyss for i in sorted (thisdict.keys()): print((i, thisdict[i]), end =" ") class_list = dict() # initializing string and taking input from user test_string = input('Enter date(yyyy-mm-dd) & value in dictionary format i.e {"key":value}:-') # using ast.literal_eval() test_string to dictionary class_list = ast.literal_eval(test_string) MissingDates(class_list);
dcf9e902db1b5960e4a839f65b6d7679845a9b04
pedrohenrique-hash/Astropython
/Astro.py
366
3.8125
4
x = [2, 6, 8, 9, 10, 11, 12, 13, 14, 15] def median(v): n = len(v) sorted_v = sorted(v) midpoint = n // 2 if n % 2 == 1: return sorted_v[midpoint] else: lo = midpoint - 1 hi = midpoint return (sorted_v[lo] + sorted_v[hi]) / 2 #5 inicio das execuções print(median(x)) print(sum(x) / len(x))
4ec3c682ef42afd9867983fe58b30c7a2eba70b1
NicolasGomez97/Cientifico-Datos-ISPC
/Programacion-I/13vaSemana/ejercicio9.py
359
3.734375
4
def dicMaterias(): d = {} while True: m = str(input("Ingrese Materia: ")) n = float(input("Ingrese Nota que sacaste: ")) d[m]=n i = str(input('Quiere Seguir ingresando Materias y Notas: \n')) if i == 'no': break for i,y in list(d.items()): if y >= 6.0: d.pop(i) print(d)
46d71236db28466463bff4f17f6845d862351cbc
jakiiii/Cryptography-with-Python
/CryptographyUsingPython/CeaserCipher/brute_force.py
483
3.6875
4
#!/usr/bin/env python3 message = 'ABCH HKHEL KHJNK DFGAS OFSX' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' for key in range(len(LETTERS)): translated = '' for symbol in message: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print("#{key}, {translated}".format(key=key, translated=translated))
0ca12599d692b0f7a46966c6603f5b78334df63f
XxTyaftioNxX/LyricalBot
/graph.py
1,684
3.5625
4
#Markov Chain Representation import random #define the graph in terms of vertices class Vertex: def __init__(self, value): self.value = value self.adjacent = {} #nodes that have edge to this vertex self.neighbours = [] self.neighbour_weights = [] def add_edge_to(self, vertex, weight=0): self.adjacent[vertex] = weight def increment_edge(self, vetex): #incrementing the weight of the vertex self.adjacent[vetex] = self.adjacent.get(vetex, 0) + 1 def get_probability_map(self): for(vertex, weight) in self.adjacent.items(): self.neighbours.append(vertex) self.neighbour_weights.append(weight) def next_word(self): #select next word based on weights as list and returns the first return random.choices(self.neighbours, weights = self.neighbour_weights)[0] #making graph out of the vertices class Graph: def __init__(self): self.vertices = {} def get_vertex_values(self): #it returns all the posssible words (values of the all vertex) return set(self.vertices.keys()) def add_vertex(self, value): #creating new vertex self.vertices[value] = Vertex(value) def get_vertex(self, value): if value not in self.vertices: self.add_vertex(value) #returns the vertex object return self.vertices[value] def get_next_word(self, current_vertex): return self.vertices[current_vertex.value].next_word() def generate_probability_mappings(self): for vertex in self.vertices.values(): vertex.get_probability_map()
b1cf4a3e46754ba2a54f0a24699766d18cb7ed35
PedroExt/Mis-Proyectos-Con-Python
/WeekOneHomeWork/Exercise5.py
319
3.59375
4
C=float(input('Ingrese valor de compra:')) n=float(input('Ingrese el nro de cuotas: ')) i=float(input('Ingrese la tasa de interes: ')) VC= C*(i*((1+i)**n)/((1+i)**n-1)) montoTotalIntereses=VC*n-C print('El valor de la cuota es : %.2f'%VC,'soles.') print('Monto total de intereses es: %.2f'%montoTotalIntereses,'soles.')
71c37a7257ee0cdcc82fa4bf62370f89ab5a1a48
nitayke/Rubiks-Cube
/hungary_client.py
5,745
3.5625
4
import socket import copy UP, LEFT, FRONT, RIGHT, BACK, DOWN = range(6) dic = {'U': UP, 'D':DOWN, 'L':LEFT, 'F':FRONT, 'R':RIGHT, 'B':BACK} class Cube: def __init__(self, cube): self.cube = [] if isinstance(cube, list): self.cube = copy.deepcopy(cube) else: for i in range(6): self.cube.append([list(cube[i*9:i*9+9])[x:x+3] for x in range(0, 9, 3)]) def is_solved(self): for i in self.cube: if i[0] != i[1] or i[1] != i[2]: return False for j in i: if j.count(j[0]) != 3: return False return True def rotate_one_side(self, side): new_list = [] for i in range(3): new_list.append([self.cube[side][2-j][i] for j in range(3)]) self.cube[side] = new_list def rotate_first_line(self, side): if side == UP: self.cube[FRONT][0], self.cube[LEFT][0], self.cube[BACK][0], self.cube[RIGHT][0] = self.cube[RIGHT][0], self.cube[FRONT][0], self.cube[LEFT][0], self.cube[BACK][0] elif side == LEFT: sides = list() for i in (UP, FRONT, DOWN): sides.append([self.cube[i][j][0] for j in range(3)]) sides.append([self.cube[BACK][2-i][2] for i in range(3)]) for i in range(3): self.cube[FRONT][i][0] = sides[0][i] for i in range(3): self.cube[DOWN][i][0] = sides[1][i] for i in range(3): self.cube[BACK][2-i][2] = sides[2][i] for i in range(3): self.cube[UP][i][0] = sides[3][i] elif side == FRONT: sides = list() sides.append(self.cube[UP][2]) sides.append([self.cube[RIGHT][i][0] for i in range(3)]) sides.append(self.cube[DOWN][0]) sides.append([self.cube[LEFT][i][2] for i in range(3)]) for i in range(3): self.cube[RIGHT][i][0] = sides[0][i] self.cube[DOWN][0] = sides[1][::-1] for i in range(3): self.cube[LEFT][i][2] = sides[2][i] self.cube[UP][2] = sides[3][::-1] elif side == RIGHT: sides = list() sides.append([self.cube[UP][2-i][2] for i in range(3)]) sides.append([self.cube[BACK][i][0] for i in range(3)]) sides.append([self.cube[DOWN][i][2] for i in range(3)]) sides.append([self.cube[FRONT][i][2] for i in range(3)]) for i in range(3): self.cube[BACK][i][0] = sides[0][i] for i in range(3): self.cube[DOWN][2-i][2] = sides[1][i] for i in range(3): self.cube[FRONT][i][2] = sides[2][i] for i in range(3): self.cube[UP][i][2] = sides[3][i] elif side == BACK: sides = list() sides.append(self.cube[UP][0]) sides.append([self.cube[LEFT][i][0] for i in range(3)]) sides.append(self.cube[DOWN][2][::-1]) sides.append([self.cube[RIGHT][i][2] for i in range(3)]) for i in range(3): self.cube[LEFT][2-i][0] = sides[0][i] self.cube[DOWN][2] = sides[1] for i in range(3): self.cube[RIGHT][i][2] = sides[2][i] self.cube[UP][0] = sides[3] else: self.cube[FRONT][2], self.cube[RIGHT][2], self.cube[BACK][2], self.cube[LEFT][2] = self.cube[LEFT][2], self.cube[FRONT][2], self.cube[RIGHT][2], self.cube[BACK][2] def print(self): for i in range(3): print(' ' * 15, self.cube[BACK][2-i][::-1]) print() for i in range(3): print([self.cube[LEFT][2-j][i] for j in range(3)], [self.cube[UP][i][j] for j in range(3)], [self.cube[RIGHT][j][2-i] for j in range(3)]) print() for i in range(3): print(' ' * 15, self.cube[FRONT][i]) print() for i in range(3): print(' ' * 15, self.cube[DOWN][i]) print('\n\n\n') def rotate(self, side): self.rotate_one_side(side) self.rotate_first_line(side) def solve(self, moves): curr = '' for j in moves: if j == "'": self.rotate(dic[curr]) self.rotate(dic[curr]) else: self.rotate(dic[j]) curr = j CONNECTION_INFO = ('challenges.cyber.org.il', 10505) def get_startup_info(server_socket): data = '' while 'Send the correct line:' not in data: data += server_socket.recv(1024).decode() return data def main(): answer = '' server_socket = socket.socket() server_socket.connect(CONNECTION_INFO) while 'Wrong!' not in answer and 'MUCH' not in answer: data = get_startup_info(server_socket) cube = Cube(data[data.index('Shuf')+10:data.index('Option')-1]) #cube.print() tmp_cube = Cube(cube.cube) data = data[data.index('Options') + 9 : data.index('Send the correct line') - 2] data_list = [i[i.index(' ')+1:] for i in data.split('\n')] line_number = 0 curr = '' for i in data_list: tmp_cube.solve(i) if tmp_cube.is_solved(): line_number = str(data_list.index(i) + 1).encode() tmp_cube = Cube(cube.cube) if line_number == 0: return 1 server_socket.send(line_number) answer = server_socket.recv(100).decode() print(answer) if __name__ == '__main__': while True: try: main() except: continue else: exit(0)
cba688a4c6ad9f743c93ccf4b40c14fec169f08d
aesdeef/advent-of-code-2020
/day_16/day_16_ticket_translation.py
3,376
3.796875
4
import re from math import prod def parse_input(): """ Parses the input and returns a dict of rules and a list of tickets, starting with your ticket """ rules = {} tickets = [] with open("input_16.txt") as f: for line in f: rule_pattern = r"^([a-z ]+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)" match = re.match(rule_pattern, line) if match: name, *numbers = match.groups() numbers = [int(number) for number in numbers] rules[name] = ((numbers[0], numbers[1]), (numbers[2], numbers[3])) elif "," in line: tickets.append([int(number) for number in line.split(",")]) return rules, tickets def satisfies(number, rule): """ Checks if the number satisfies the rule """ for range_ in rule: min_, max_ = range_ if min_ <= number <= max_: return True return False def scan_ticket(rules, ticket): """ Scans the ticket and returns whether the ticket is valid and the scanning error for that ticket """ valid_ticket = True scanning_error = 0 for number in ticket: valid_number = False for rule in rules.values(): if satisfies(number, rule): valid_number = True break if not valid_number: valid_ticket = False scanning_error += number return valid_ticket, scanning_error def scan_all_tickets(rules, tickets): """ Scans all tickets and returns a list of valid tickets and the scanning error rate """ valid_tickets = [] scanning_error_rate = 0 for ticket in tickets: is_valid, scanning_error = scan_ticket(rules, ticket) if is_valid: valid_tickets.append(ticket) else: scanning_error_rate += scanning_error return valid_tickets, scanning_error_rate def deduce_field_order(rules, valid_tickets): """ Deduces the order of the fields """ possible_fields = [] for numbers in zip(*valid_tickets): possibilities = set() for name, rule in rules.items(): if all(satisfies(number, rule) for number in numbers): possibilities.add(name) possible_fields.append(possibilities) fixed = [False for options in possible_fields] while not all(fixed): newly_fixed = set() for i, options in enumerate(possible_fields): if not fixed[i] and len(options) == 1: newly_fixed |= options fixed[i] = True for i in range(len(possible_fields)): if not fixed[i]: possible_fields[i] -= newly_fixed return [options.pop() for options in possible_fields] def part_2(fields, my_ticket): """ Calculates the answer to Part 2 """ return prod( number for name, number in zip(fields, my_ticket) if name.startswith("departure") ) if __name__ == "__main__": rules, tickets = parse_input() my_ticket = tickets.pop(0) valid_tickets, scanning_error_rate = scan_all_tickets(rules, tickets) # The scanning error rate is the solution to Part 1 print(scanning_error_rate) fields = deduce_field_order(rules, valid_tickets) print(part_2(fields, my_ticket))
bf156e7b213f6983b47792c94c842dd9bcd7c7ee
aesdeef/advent-of-code-2020
/day_17/part_1.py
1,315
4.03125
4
from functools import lru_cache def parse_input(): """ Parses the input and returns a set of cubes """ cubes = set() with open("input_17.txt") as f: for y, line in enumerate(f): for x, char in enumerate(line): if char == "#": cubes.add((x, y, 0)) return cubes @lru_cache def nearby(cube): """ Returns a set of all cubes around the given cube """ x, y, z = cube nearby_cubes = set() for dx in (-1, 0, 1): for dy in (-1, 0, 1): for dz in (-1, 0, 1): if any((dx, dy, dz)): nearby_cubes.add((x + dx, y + dy, z + dz)) return nearby_cubes def iterate(cubes): """ Performs one cycle on the given set of cubes and returns a new set of cubes """ remaining = {cube for cube in cubes if len(nearby(cube) & cubes) in (2, 3)} potential_cubes = set.union(*(nearby(cube) for cube in cubes)) - cubes created = {cube for cube in potential_cubes if len(nearby(cube) & cubes) == 3} return remaining | created def part_1(): """ Returns the solution for part 1 """ cubes = parse_input() for _ in range(6): cubes = iterate(cubes) return len(cubes) if __name__ == "__main__": print(part_1())
a7b576bf5c4fca869c2d238dccce509abd244e69
aesdeef/advent-of-code-2020
/day_12/ship_part_1.py
2,539
4.0625
4
class Ship: def __init__(self): self.x = 0 # east self.y = 0 # north self.direction = "E" self.operations = { "N": self.north, "S": self.south, "E": self.east, "W": self.west, "L": self.turn_left, "R": self.turn_right, } def parse_input(self): """ Parses the input and performs the operations """ with open("input_12.txt") as f: for line in f: operation = line[0] argument = int(line[1:]) self.go(operation, argument) def go(self, operation, argument): """ Performs the operation assigned to the given symbol. If that symbol is F, then it performs the operation assigned to the characters that marks the direction the ship is currently facing """ if operation == "F": operation = self.direction self.operations[operation](argument) def north(self, argument): """ Moves the ship north by the specified number of units """ self.y += argument def south(self, argument): """ Moves the ship south by the specified number of units """ self.y -= argument def east(self, argument): """ Moves the ship east by the specified number of units """ self.x += argument def west(self, argument): """ Moves the ship west by the specified number of units """ self.x -= argument def turn_left(self, argument): """ Rotates the ship counterclockwise the specified number of degrees """ def _turn(): """ Rotates the ship counterclockwise 90 degrees """ self.direction = { "N": "W", "W": "S", "S": "E", "E": "N", }[self.direction] for _ in range((argument // 90) % 4): _turn() def turn_right(self, argument): """ Rotates the ship clockwise the specified number of degrees """ def _turn(): """ Rotates the ship clockwise 90 degrees """ self.direction = { "N": "E", "E": "S", "S": "W", "W": "N", }[self.direction] for _ in range((argument // 90) % 4): _turn()
9774dd4f758bd0b7a97c40acc61cba5a98991d5d
aesdeef/advent-of-code-2020
/day_14/part_2.py
1,029
3.640625
4
def write_to_mem(target, number, mask, mem): """ Writes the given value to all applicable memory addresses """ target = f"{target:036b}" addresses = [""] for t, m in zip(target, mask): if m == "0": addresses = [address + t for address in addresses] elif m == "1": addresses = [address + "1" for address in addresses] else: addresses = [address + "0" for address in addresses] + [ address + "1" for address in addresses ] for address in addresses: mem[int(address)] = number def part_2(): """ Returns the solution for part 2 """ with open("input_14.txt") as f: mask = "" mem = {} for line in f: target, value = line.split(" = ") if target == "mask": mask = value else: target = int(target.strip("mem[]")) write_to_mem(target, int(value), mask, mem) return sum(mem.values())
f3bcc1f64a92fa0b2886f77bee03df5996ee9fdd
Edceebee/Python_stuff
/utils.py
280
4.0625
4
def add(digit1: int, digit2: int) -> int: """ a function that adds two numbers""" digit3 = digit1 + digit2 return digit3 def multiply(digit1: int, digit2: int) -> int: """a function that can multiply two numbers""" digit3 = digit1 * digit2 return digit3
4a74e71bc3869350e6e7802404a120fae1ecc304
ryazadd/Algorithms
/сортировка слиянием.py
1,015
4.03125
4
def merge(array, left_index, middle, right_index ): left_copy = array[left_index:middle] right_copy = array[middle:right_index] l = 0 r = 0 k = left_index while l < len(left_copy) and r < len(right_copy): if left_copy[l] <= right_copy[r]: array[k] = left_copy[l] l += 1 k += 1 else: array[k] = right_copy[r] r += 1 k += 1 while l < len(left_copy): array[k] = left_copy[l] l += 1 k += 1 while r < len(right_copy): array[k] = right_copy[r] r += 1 k += 1 return array def merge_sort(array, left_index, right_index): if (right_index-left_index)>1: middle = (left_index + right_index) // 2 merge_sort(array, left_index, middle) merge_sort(array, middle, right_index) merge(array, left_index, middle, right_index) # array = [0,4,2,0,4,4,4,42,2,2,23,4,4,21,1] # merge_sort(array, 0, 3) # print(array)
830ac9b40a729f587080b407c1069d7356a9598d
ryazadd/Algorithms
/working_sort_Mihail.py
844
3.890625
4
def merge(arr: list, left: int, mid: int, right: int) -> list: L, R = arr[left:mid], arr[mid:right] N, M = len(L), len(R) i = j = 0 k = left while i < N and j < M: if L[i] <= R[j]: arr[k] = L[i] i += 1 k += 1 else: arr[k] = R[j] j += 1 k += 1 while i < N: arr[k] = L[i] i += 1 k += 1 while j < M: arr[k] = R[j] j += 1 k += 1 return arr def merge_sort(arr: list, left: int, right: int) -> None: if (right - left) > 1: mid = left + (right - left) // 2 merge_sort(arr, left, mid) merge_sort(arr, mid, right) merge(arr, left, mid, right) array = [0,4,2,0,4,4,4,42,2,2,23,4,4,21,1] merge_sort(array, 0, len(array)) print(array)
1d14b8695c938bed324dc13fee35b1e13d5d334b
chelberserker/mipt_cs_on_python
/lab 7/exA.py
181
3.703125
4
import numpy as np import matplotlib.pyplot as plt def f(x): return x*x-6-x x=np.arange(-10,10,0.01) plt.plot(x, f(x)) for i in x: if -0.01 <= f(i) <= 0.01: print(i) plt.show()
26b569140d5da48f061577958fe48a553741d8ca
evelynnenguyen/HackerrankSolutions
/interview-preparation-kit/dictionaries-and-hashmaps/count-triplets.py
533
3.59375
4
#!/bin/python3 import math import os import random import re import sys # Complete the countTriplets function below. def countTriplets(arr, r, n): t = 0 r = float(r) return t if __name__ == '__main__': k = int(input()) for i in range(k): nr = input().rstrip().split() n = int(nr[0]) # print('n', n) r = int(nr[1]) # print('r', r) arr = list(map(int, input().rstrip().split())) print('arr', arr) ans = countTriplets(arr, r, n) print(ans)
9d05234b70c705950a9ff2a5640107b9dde9e092
yangxi5501630/pythonProject
/study/study/re/3_re扩展.py
2,486
3.78125
4
import re #字符串切割 str = "abc123efg456xyz" print(str.split("123")) #不支持正则 str1 = "abc123efg456xyz" print(re.split("\d+",str1)) #可以随意切割 str2 = "hello world zhangsan" print(re.split('\s+', str2)) print(re.split('\s+', str2, 1)) ''' re.finditer函数 原型:finditer(pattern, string, flags=0) 参数: patter: 匹配的正则表达式 string: 要匹配的字符串 flags:标志位,用于控制正则表达式的匹配方式 功能:与findall类似,扫描整个字符串,返回的是一个迭代器 ''' str3 = "hello 1234 world! hello 55555 world!" d = re.finditer(r"(hello)", str3) while True: try: l = next(d) print(d) print(l.span()) except StopIteration as e: break ''' 字符串的替换和修改 sub(pattern, repl, string, count=0) subn(pattern, repl, string, count=0) pattern: 正则表达式(规则) repl: 指定的用来替换的字符串 string: 目标字符串 count: 最多替换次数 功能:在目标字符串中以正则表达式的规则匹配字符串,再把他们替换成指定的字符串。可以指定替换的次数,如果不指定,替换所有的匹配字符串 区别:前者返回一个被替换的字符串,后者返回一个元组,第一个元素被替换的字符串,第二个元素表示被替换的次数 ''' str5 = "hello world world world tarena" print(re.sub(r"hello", "china", str5)) print(type(re.sub(r"(world)", "china", str5))) print(re.subn(r"(world)", "张三", str5)) print(type(re.subn(r"(good)", "张三", str5))) ''' 编译:当我们使用正则表达式时,re模块会干两件事 1、编译正则表达式,如果正则表达式本身不合法,会报错 2、用编译后的正则表达式去匹配对象 compile(pattern, flags=0) pattern:要编译的正则表达式 ''' pat = r"^1([3578])\d{9}$" print(re.match(pat, "13612345678")) #编译成正则对象 re_telephon = re.compile(pat) print(re_telephon.match("13612345678")) ''' group 除了简单地判断是否匹配之外,正则表达式还有提取子串的强大功能。 用()表示的就是要提取的分组(Group)。 比如:^(\d{3})-(\d{3,8})$分别定义了两个组, 可以直接从匹配的字符串中提取出区号和本地号码 ''' str6 = "010-66677788" m = re.match(r'^(\d{3})-(\d{3,8})$', str6) print(m.group(0)) #永远是源字符串 print(m.group(1)) #第一个字符串 print(m.group(2)) #第二个字符串 print(m.groups()) #打印所有字符元组
3a7fad6b82f2dc1f6065587d1745f67c64b79597
yangxi5501630/pythonProject
/study/study/16_字典.py
1,386
4
4
''' 字典使用:key:value进行数据存储,查找速度极快 注意:字典是无序的,也就是元素位置顺序不固定,用{}扩起来 key特点: 1.字典中的key必须是唯一的 2.key必须是不可变对象,字符串,整数等都是不可变的,可以作为key 3.列表list是可变,不能作为key #和list比较 #1、查找和插入的速度极快,不会随着key-value的增加而变慢 #2、需要占用大量的内存,内存浪费多 #list #1、查找和插入的速度随着数据量的增多而减慢 #2、占用空间小,浪费内存少 ''' #字典描述人的名字和年龄 dict1 = {"zhangsan":22, "lisi":23, "wanger":21} print(dict1) #元素访问:字典名[key名] print(dict1["zhangsan"]) print(dict1["lisi"]) print(dict1["wanger"]) print(dict1.get("zhangsan")) print(dict1.get("youcw")) ret = dict1.get("youcw") if ret == None: print("没有") else: print("有") #添加元素 dict1["youcw"] = 20 print(dict1) #修改 dict1["youcw"] = 18 print(dict1) #删除 dict1.pop("lisi") print(dict1) #遍历 for key in dict1: print(key, dict1[key]) print(dict1.values()) #列表 for value in dict1.values(): print(value) print(dict1.items()) for key, value in dict1.items(): print(key, value) #获取下标index,当然是无意义的,因为字典是无序的 for index, key in enumerate(dict1): print(index, key, dict1[key])
1bb058c929eb776f52deab7486bcb65c71148d58
yangxi5501630/pythonProject
/study/study/15_元组.py
1,470
4.1875
4
''' tuple下元组本质就是一个有序集合 格式:元组名 = (元组元素1, 元组元素2, ……, 元组元素n) 特点: 1.与列表类似 2.用() 3.一旦初始化就不能修改,这个和字符串一样 ''' #创建空元组 tuple1 = () print(tuple1) #创建带元素的元组 tuple2 = (1,2,"tarena", True) print(tuple2) #定义只有一个元素的元组,记得后面带分割符, tuple3 = (1,) print(tuple3) print(type(tuple3)) #访问元组成员 tuple4 = (1,2,3,4) index = 0 for member in tuple4: print("tuple[%d] = %d" %(index, tuple4[index])) index += 1 tuple4 = (1,2,3,4) index = -4 for member in tuple4: print("tuple[%d] = %d" %(index, tuple4[index])) index += 1 #修改元组的成员 tuple5 = (1,2,3,4,[5,6,7]) #tuple5[2] = 250 #不可修改 tuple5[4][1] = 250 #修改成员列表,没毛病 print(tuple5) #删除元组 del tuple5 #print(tuple5) #元组合体 tuple6 = (1,2,3) tuple7 = (4,5,6) print(tuple6 + tuple7) #元组的重复 print(tuple6 * 3) #判断 print(2 in tuple6) print(2 in tuple7) #元组截取 tuple8 = (1,2,3,4,5,6,7,8) print(tuple8[:3]) print(tuple8[3:]) print(tuple8[3:6]) #二维元组 tuple9 = ((1,2,3),(4,5,6)) print(tuple9[1][1]) #元组的方法 #len() 返回元组中元素的个数 tuple10 = (1,2,3,4,5) print(len(tuple10)) #max() 返回元组中的最大值 #min() print(max((5,6,7,8,9))) print(min((5,6,7,8,9))) #列表转元组 list = [1,2,3,4] tuple11 = tuple(list) print(tuple11)
17ac35fbdba7dcf0c9d5438b469c9510c46e6b55
yangxi5501630/pythonProject
/study/study/线程/8_线程通信.py
450
3.5
4
import threading, time #事件对象 event = threading.Event() def run(): for i in range(5): # 等待事件出发 print("子进程 start: %d" % (i)) event.wait() # 重置 event.clear() print("子进程 end: %d" % (i)) t = threading.Thread(target=run) t.start() print("主线程开始.") for i in range(5): time.sleep(2) #触发事件 event.set() t.join() print("主线程结束.")
6a8aa8ce16427dab54ddc650747a5fcb306b86ba
twilliams9397/eng89_python_oop
/python_functions.py
897
4.375
4
# creating a function # syntax def name_of_function(inputs) is used to declare a function # def greeting(): # print("Welcome on board, enjoy your trip!") # # pass can be used to skip without any errors # # greeting() # function must be called to give output # # def greeting(): # return "Welcome on board, enjoy your trip!" # # print(greeting()) # def greeting(name): # return "Welcome on board " + name # # print(greeting("Tom")) # def greeting(name): # return "Welcome on board " + name + "!" # # print(greeting(input("What is your name? ").capitalize())) # functions can have multiple arguments and data types # def add(num1, num2): # return num1 + num2 # # print(add(2, 3)) def multiply(num1, num2): return num1 * num2 print("this is the required outcome of two numbers") # this line will not execute as it is after return statement print(multiply(3, 5))
7d5593eb3b395dd9b27f75137a1d2c2cd3e56ea7
kvalv/nonogram_solver
/a_star.py
5,795
3.8125
4
import time from abc import ABC, abstractmethod from node import Node class A_Star(ABC): def __init__(self, heuristic_fun, window=None, as_dfs=False): """ heuristic_fun: Node -> float, a function that estimates the remaining length until reaching goal node. as_dfs: Boolean, if True use a LIFO-queue instead of a sorted queue. """ self.solution = None self.known_nodes = [] self.closed_queue = [] self.open_queue = [] self.window = window self.as_dfs = as_dfs self.heuristic_fun = heuristic_fun @abstractmethod def cost_fun(self, parent, child): """returns the exact cost of going from `parent` to `child`""" pass @abstractmethod def goal_fun(self, node): """ Returns True if `node` has reached the goal. Otherwise returns False """ pass @abstractmethod def generate_children(self, parent): """ parent: a Node-instance generates children for each parent by applying all possible operators on parent. Returns an iterator that yields new children for parent. Each child should be called self._attach_and_eval(child, parent) in this function to properly set `parent` as its parent. """ pass def _attach_and_eval(self, child, parent): """ attach `child` to its `parent` and evaluates the f, g, h values of child in the following manner: child.h = self.heuristic_fun(child) child.g = parent.g + self.cost_fun(parent, child) child.f = child.g + child.h returns: child - the modified Node instance """ child.parent = parent child.g = parent.g + self.cost_fun(parent, child) child.h = self.heuristic_fun(child) child.f = child.g + child.h return child def _propagate_path_improvements(self, parent): """ from parent, propagate new path improvements (if any) on its children. Also causes changes, so the heuristic function h is needed. input: parent: a node instance heuristic_fun: a function heuristic_fun(node) -> float returns: None """ for child in parent.children: candidate_g = parent.g + self.cost_fun(parent, child) if candidate_g < child.g: child.parent = parent child.g = candidate_g child.f = child.g + self.heuristic_fun(child) def _make_initial_node(self, initial_state): """ For initial state, creates a Node instance with that state with node.g = 0, node.h = self.heuristic_fun(node). returns the Node-instance """ node = Node(initial_state) node.info = 0 node.g = 0 node.h = self.heuristic_fun(node) node.f = node.g + node.h return node def _step(self, node): """ Executes a single step of the a* algorithm. node: the node popped from `self.open_queue` to be processed. returns None, but might alter nodes in the graph. """ def state_exists_and_assign(node): """ Sets `node` as the previous existing node if in self.known_nodes and returns True, otherwise returns False. """ if any([node == each for each in self.known_nodes]): idx = [each.state for each in self.known_nodes].index(node.state) visited_node = self.known_nodes[idx] node = visited_node import pdb; pdb.set_trace() return True else: return False for each in self.generate_children(node): has_changed = state_exists_and_assign(each) if not has_changed: # that means it is new self.known_nodes.append(each) if each not in self.closed_queue and each not in self.open_queue: self._attach_and_eval(each, node) if self.as_dfs: self.open_queue = [each] + self.open_queue # prepend else: self.open_queue.append(each) if node.g + self.cost_fun(node, each) < each.g: self._attach_and_eval(each, node) if each in self.closed_queue: self._propagate_path_improvements(each) def solve(self, initial_state, visual=False): initial_node = self._make_initial_node(initial_state) self.open_queue.append(initial_node) self.known_nodes = [initial_node] i = 0 while self.open_queue: node = self.open_queue.pop(0) if self.window: node.visualize_state(self.window) self.closed_queue.append(node) if not self.as_dfs: # sort if it's not dfs self.open_queue.sort(key=lambda N: N.f, reverse=False) print(f'step{i}\t\tqueue size {len(self.open_queue)}\t\th={node.h}') i += 1 if self.goal_fun(node): self.solution = node return node self._step(node) raise Exception('No solution is found') def print_summary(self): n_moves = len(self.solution.get_ancestors()) - 1 # initial is not a move n_expand = len(self.closed_queue) n_created = n_expand + len(self.open_queue) print('\n\n---------------------') print(' summary') print('---------------------') print(f'path length: {n_moves}\nnodes created: {n_created}\nnodes visited: {n_expand}') return None
77643962496f439389d3d55c41df0797d3ed65f3
SimonIyamu/2d-Convex-Hull
/src/incremental/incremental.py
3,781
3.71875
4
''' Find the convex hull of random points using an incremental algorithm ''' import matplotlib.pyplot as plt import numpy as np # import Point.py class from Point import Point # Returns true if point p is left of the line ab def isLeftOf(p,a,b): return (np.sign((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)) >= 0 ) # Returns true if point p is right of the line ab def isRightOf(p,a,b): return (np.sign((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)) <= 0 ) # Returns true if the point p is upper tangent of point p. # q1 is the previous point of p and q2 is the next point, when moving CCW in a polygon def isUpperTangent(p, q, q1, q2): return isLeftOf(p,q,q2) and isRightOf(p,q1,q) def isLowerTangent(p, q, q1, q2): return isRightOf(p,q,q2) and isLeftOf(p,q1,q) allPoints = list() ''' allPoints.append(Point(3,9)) allPoints.append(Point(3.5,6)) allPoints.append(Point(6,1)) allPoints.append(Point(9,0)) ''' for i in range(20): allPoints.append(Point(100*np.random.rand(),100*np.random.rand())) # Sort points by their x-coordinate allPoints = sorted(allPoints) print(allPoints) # Start with a trivial hull(a triangle of the first points) hullPoints = allPoints[:3] # Store edges in CCW (counter-clock wise) order hullEdge = {} if (isRightOf(hullPoints[0], hullPoints[1], hullPoints[2])): hullEdge= { hullPoints[0]: {'prev': hullPoints[1], 'next': hullPoints[2]}, hullPoints[1]: {'prev': hullPoints[2], 'next': hullPoints[0]}, hullPoints[2]: {'prev': hullPoints[0], 'next': hullPoints[1]} } else: hullEdge= { hullPoints[0]: {'prev': hullPoints[2], 'next': hullPoints[1]}, hullPoints[2]: {'prev': hullPoints[1], 'next': hullPoints[0]}, hullPoints[1]: {'prev': hullPoints[0], 'next': hullPoints[2]} } n = len(allPoints) # One by one add the remaining vertices to the convex hull # and remove vertices that are inside it for i in range(3,n): pi = allPoints[i] print('Adding point pi=%s'%(pi)) # Let j be the rightmost index of the convex hull j = len(hullPoints) - 1 # Look for upper tangent point u = j upperTangent = hullPoints[u] while(not isUpperTangent(pi, upperTangent, hullEdge[upperTangent]['prev'], hullEdge[upperTangent]['next'])): #print('- its not %s'%(upperTangent)) u -= 1 upperTangent = hullPoints[u] print(' Upper tangent point: %s' %(upperTangent)) # Look for lower tangent point by iterating over the vertices that are # previous of upperTangent, one by one until it is found lowerTangent = hullEdge[upperTangent]['prev'] while(not isLowerTangent(pi, lowerTangent, hullEdge[lowerTangent]['prev'], hullEdge[lowerTangent]['next'])): print(' Removing %s' %(lowerTangent)) temp = lowerTangent lowerTangent = hullEdge[lowerTangent]['prev'] hullEdge.pop(temp,None) hullPoints.remove(temp) print(' Lower tangent point: %s' %(lowerTangent)) # Update convex hull by adding the new point hullPoints.append(pi) # Update edges hullEdge[pi] = {'prev': lowerTangent, 'next': upperTangent} hullEdge[lowerTangent]['next'] = pi hullEdge[upperTangent]['prev'] = pi print('') print('Generating plot...') # Convert points and edges into a np.arrays in order to plot them pointsArray = list() for point in allPoints: pointsArray.append([point.x, point.y]) pointsArray = np.array(pointsArray) hullEdge[pi] = {'prev': lowerTangent, 'next': upperTangent} hullArray = list() point = hullPoints[0] for i in range(len(hullPoints)): hullArray.append([point.x, point.y]) point = hullEdge[point]['next'] hullArray.append(hullArray[0]) hullArray = np.array(hullArray) plt.plot(pointsArray[:,0], pointsArray[:,1], 'o') plt.plot(hullArray[:,0], hullArray[:,1], 'r--') plt.show() print('Plot was generated')
5dfec88ae06aee495998076d0e80777c1e9b408b
Carr1996/Python_file
/Related_exercises/三级菜单.py
2,055
3.703125
4
menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{}, }, '上地':{ '百度':{}, }, }, '昌平':{ '沙河':{ '老男孩':{}, '北航':{}, }, '天通苑':{}, '回龙观':{}, }, '朝阳':{}, '东城':{}, }, '上海':{ '闵行':{ '人民广场':{ '炸鸡店':{}, }, }, '闸北':{ '火车站':{ '携程':{} } }, '浦东':{}, }, '山东':{}, } while True: for i in menu: print(i) choice=input(">:").strip() if not choice: continue if choice in menu: while True: #进入第二层 for i in menu[choice]: print(i) choice2=input(">>:").strip() if not choice2:continue if choice2 in menu[choice]: while True: #进入第三层 for i in menu[choice][choice2]: print(i) choice3=input(">>>:") if not choice3:continue if choice3 in menu[choice][choice2]: print("go to : ",menu[choice][choice2][choice3]) elif choice3=='b': break elif choice3=='q': exit('bye') else: print('节点不存在') elif choice2=='b': break elif choice2=='q': exit('bye') else: print('节点不存在') elif choice=='q': exit('bye') else: print('节点不存在')
7ccc7606168c9156ef0a2590792e8114cc3d7af1
daviddahl/altcoin-autosell
/exchange_api.py
1,537
3.609375
4
# An exception that any methods in exchange may raise. class ExchangeException(Exception): def __init__(self, exception): message = '[%s] %s' % (type(exception).__name__, exception) Exception.__init__(self, message) # An available market. class Market(object): source_currency_id = None target_currency_id = None market_id = None trade_minimum = 0.00000001 def __init__(self, source_currency_id, target_currency_id, market_id, trade_minimum=0.0000001): self.source_currency_id = source_currency_id self.target_currency_id = target_currency_id self.market_id = market_id self.trade_minimum = trade_minimum # A base class for Exchanges. class Exchange(object): # The name of the exchange. name = '' # Returns a dict of currency_id to currency_name, e.g. # { # 1: 'BTC', # 2: 'LTC', # 12: 'DOGE', # 15: '42', # } def GetCurrencies(self): raise NotImplementedError # Returns a dict of currency_id to balance, e.g. # { # 12: 173.23, # 13: 19,347, # } def GetBalances(self): raise NotImplementedError # Returns an array of Markets. def GetMarkets(self): raise NotImplementedError # Creates an order (market order if price is 0). # If 'bid' is True, this is a bid/buy order, otherwise an ask/sell order. # Returns an order_id. def CreateOrder(self, market_id, amount, bid=True, price=0): raise NotImplementedError
2dc4e9e0b197084b6c76ebffea23fa75de884849
JonBanes/Happy-Save-The-Bunny-Game
/random_walk.py
619
3.671875
4
import random def random_walk(step, moveset): """ Returns tuple in random 'step' direction of moveset list (square grid clockwise 0 == stay still) """ directions = [(0,0), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0), (-1,-1)] walk_direction = random.randrange(len(moveset)) return (directions[moveset[walk_direction]][0] * step, directions[moveset[walk_direction]][1] * step) print(int(1178.908349057 // 30) - 1)
23b5ab72527d9f6b9469c34865d8e3ed6541e7bd
bnathasingh/recursion
/lab07.py
7,075
4.0625
4
""" A module with several recursive functions YOUR NAME AND NETID HERE THE DATE COMPLETED HERE """ # IMPLEMENT ALL OF THESE FUNCTIONS def sum_list(thelist): """ Returns the sum of the integers in list l. Example: sum_list([34]) is 34 Example: sum_list([7,34,1,2,2]) is 46 Parameter thelist: the list to sum Precondition: thelist is a list of ints """ #if len(thelist)==0: # return thelist[0] #else: # return thelist[0]+sum_list(thelist[1:]) return sum(thelist) # Stub return. Replace this. def numberof(thelist, v): """ Returns the number of times v occurs in thelist. Parameter thelist: The list to count from Precondition: thelist is a list of ints Parameter v: The value to count Precondition: v is an int """ # HINT: Divide and conquer only applies to one of the arguments, not both if thelist==[]: return 0 if thelist[0] == v: return 1 + numberof(thelist[1:], v) else: return 0 + numberof(thelist[1:], v) # Stub return. Replace this. def replace(thelist,a,b): """ Returns a COPY of thelist but with all occurrences of a replaced by b. Example: replace([1,2,3,1], 1, 4) = [4,2,3,4]. Parameter thelist: The list to count from Precondition: thelist is a list of ints Parameter a: The value to replace Precondition: a is an int Parameter b: The value to replace with Precondition: b is an int """ sampleFile <- "/shared_data/RNAseq/exercise3/fission_sample.csv" #if len(thelist) == 0: # return [] # elif len(thelist)==1: # return [b] if thelist[:1] == a else thelist[:1] # left=replace(thelist[:1], a, b) # right = replace(thelist[1:], a, b) # return left + right # HINT: Divide and conquer only applies to one of the arguments, not all three #if len(thelist)==0: def remove_dups(thelist): """ Returns a COPY of thelist with adjacent duplicates removed. Example: for thelist = [1,2,2,3,3,3,4,5,1,1,1] the answer is [1,2,3,4,5,1] Parameter thelist: The list to modify Precondition: thelist is a list of ints """ # HINT: You can still do this with divide-and-conquer # The tricky part is combining the answers if len(thelist)<2: return thelist else: if thelist[0]== thelist[1]: return remove_dups(thelist[1:]) else: return [thelist[0]]+remove_dups(thelist[1:]) # Stub return. Replace this. # OPTIONAL EXERCISES def number_not(thelist, v): """ Returns the number of elements in seq that are NOT v. Parameter thelist: the list to search Precondition: thelist is a list of ints Parameter v: the value to search for Precondition: v is an int """ return 0 # Stub return. Replace this. def remove_first(thelist, v): """ Returns a COPY of thelist but with the FIRST occurrence of v removed (if present). Note: This can be done easily using index. Don't do that. Do it recursively. Parameter thelist: the list to search Precondition: thelist is a list of ints Parameter v: the value to search for Precondition: v is an int """ return [] # Stub return. Replace this. def oddsevens(thelist): """ Returns a COPY of the list with odds at front, evens in the back. Odd numbers are in the same order as thelist. Evens are reversed. Example: oddsevens([3,4,5,6]) returns [3,5,6,4]. oddsevens([2,3,4,5,6]) returns [3,5,6,4,2]. oddsevens([1,2,3,4,5,6]) returns [1,3,5,6,4,2]. Parameter thelist: The list to modify Precondition: thelist is a list of ints (may be empty) """ # HINT: How you break up the list is important. A bad division will # make it almost impossible to combine the answer together. # However, if you look at all three examples in the specification you # will see a pattern that should help you define the recursion. return [] # Stub return. Replace this. def flatten(thelist): """ Returns a COPY of thelist flattened to remove all nested lists Flattening takes any nested list and recursively dumps its contents into the parent list. Examples: flatten([[1,2],[3,4]]) is [1,2,3,4] flatten([[1,[2,3]],[[4],[5,[6,7]]]]) is [1,2,3,4,5,6,7] flatten([1,2,3]) is [1,2,3] Parameter thelist: the list to flatten Precondition: thelist is a list of either ints or lists which satisfy the precondition """ return [] # Stub return. Replace this ### Numeric Examples ### def sum_to(n): """ Returns the sum of numbers 1 to n. Example: sum_to(3) = 1+2+3 = 6, Example: sum_to(5) = 1+2+3+4+5 = 15 Parameter n: the number of ints to sum Precondition: n >= 1 is an int. """ return 0 # Stub return. Replace this. def num_digits(n): """ Returns the number of the digits in the decimal representation of n. Example: num_digits(0) = 1 Example: num_digits(3) = 1 Example: num_digits(34) = 2 Example: num_digits(1356) = 4 Parameter n: the number to analyze Precondition: n >= 0 is an int """ return 0 # Stub return. Replace this. def sum_digits(n): """ Returns the sum of the digits in the decimal representation of n. Example: sum_digits(0) = 0 Example: sum_digits(3) = 3 Example: sum_digits(34) = 7 Example: sum_digits(345) = 12 Parameter n: the number to analyze Precondition: n >= 0 is an int. """ return 0 # Stub return. Replace this. def number2(n): """ Returns the number of 2's in the decimal representation of n. Example: number2(0) = 0 Example: number2(2) = 1 Example: number2(234252) = 3 Parameter n: the number to analyze Precondition: n >= 0 is an int. """ return 0 # Stub return. Replace this. def into(n, c): """ Returns the number of times that c divides n, Example: into(5,3) = 0 because 3 does not divide 5. Example: into(3*3*3*3*7,3) = 4. Parameter n: the number to analyze Precondition: n >= 1 is an int Parameter c: the number to divide by Precondition: c > 1 are ints. """ return 0 # Stub return. Replace this. # IF YOU REALLY WANT A CHALLENGE def related(p,q): """ Returns True if Persons p and q are related; False otherwise. We say that two people are related if they have a common person in their family tree (including themselves). A recursive way of saying this is that they are related if (1) they are the same person, or (2) one is related to an ancestor (parent, grandparent, etc.) of another If either p or q is None, this function returns False. Parameter p: a person to compare Precondition: p is a Person object OR None Parameter q: a person to compare Precondition: q is a Person object OR None """ return False # Stub return. Replace this.
df1b44df37c7360d4c68579b6076f984cb8a9acb
theexiled1/sscrypt
/sscrypt.py
4,192
3.578125
4
#!/usr/bin/env python "Instagram: @SSploit\nTwitter: @SecuritySploit\nYouTube: Blackhole Security\nGithub: BlackholeSec\n\nSSCrypt (SecSploit Encryption)\nThis Encryption uses custom mathematical algoritms to ensure the privacy of your data whether it be clandestine or merely for privacy" import random import os import sys import binascii class desolation_error(Exception): pass def __encode_data(data): enc_str = "" for char in data: enc_str = enc_str + binascii.hexlify(char) + " " end_val = "" for val in enc_str.split(' '): end_val = end_val + binascii.hexlify(val) + " " return end_val def __decode_data(data): dec_str = "" for char in data.split(" "): dec_str = dec_str + binascii.unhexlify(char) dec_str = binascii.unhexlify(dec_str) return dec_str def __gen_key(key): key_val = str(__encode_data(key)) key_value = "" for c in key_val.split(" "): key_value = key_value + c key_value = int(key_value) calc = key_value ** (len(key) % key_value) / (len(str(key_value)) % key_value) calc = calc / (2 + (16 % len(key))) // (8 + (len(str(key_value)) / 32 + (len(str(calc)) ** 2))) calc = calc - 82 + len(str(calc)) * (key_value / 32) ^ 256 >> 6 calc = calc | 32 / (len(str(key_value)) % 512) << 2 * (512 * len(str(key_value)[:2])) + 1024 / len(str(calc)) calc = (calc + calc) % len(str(calc)) / len(str(key_value)) << len(key) ^ (16 ** len(str(key_val))) calc = (calc ** 32) % len(str(key_value)) + 16 ** len(str(key_val)) + 1024 ^ len(str(key_val)) calc = calc ** len(str(key_value)) + 128 >> len(str(key_val)) + (len(str(key_value)) + 16) / 1024 calc = calc / len(str(key_val)) - len(str(key_val)) + 2 return calc def __encrypt_data(key_calc,data): enc_msg = "" for val in str(data.strip()).split(" "): enc_msg = enc_msg + str(int(val) * key_calc) + ":" return enc_msg def __decrypt_data(key_calc,data): dec_msg = "" for val in str(data).strip().split(":"): try: dec_msg = dec_msg + str(int(str(val)) / key_calc) except: pass dec_msg = __decode_data(dec_msg) return dec_msg def encrypt(data,key): "Use this function for encrypting clandestine data\nUsage encrypt('message','password')" enc_data = __encrypt_data(__gen_key(key),__encode_data(data)) return enc_data def decrypt(data,key): "Use this function for decrypting encrypted data\nUsage decrypt('encrypted message','password')" dec_data = __decrypt_data(__gen_key(key),data) return dec_data def encrypt_file(file,key): "Use this function for encrypting clandestine files\nUsage encrypt_file('filename.ext','password')" try: with open(file, 'r') as fhandler: data = fhandler.read() if(len(str(data).strip()) == 0): raise desolation_error("File is empty, there is nothing to encrypt.") exit(1) fhandler.close() except Exception as e: sys.stdout.write(str(e)) sys.stdout.flush() exit(1) try: for i in range(80): with open(file, 'w+') as fhandler: fhandler.truncate() fhandler.write(str(random.SystemRandom().getrandbits(1024))) fhandler.close() lname = file for i in range(80): nname = str('0' * int(random.SystemRandom().randint(1,15))) os.rename(lname,nname) lname = nname os.remove(lname) except: raise try: with open(file,'w+') as fhandler: fhandler.write(encrypt(data,key)) fhandler.close() except: raise def decrypt_file(file,key): "Use this function for decrypting encrypted files\nUsage decrypt_file('filename.ext','password')" try: with open(file, 'r') as fhandler: data = fhandler.read() if(len(str(data).strip()) == 0): raise desolation_error("File is empty, there is nothing to decrypt.") exit(1) fhandler.close() except Exception as e: sys.stdout.write(str(e)) sys.stdout.flush() exit(1) try: for i in range(80): with open(file, 'w+') as fhandler: fhandler.truncate() fhandler.write(str(random.SystemRandom().getrandbits(1024))) fhandler.close() lname = file for i in range(80): nname = str('0' * int(random.SystemRandom().randint(1,15))) os.rename(lname,nname) lname = nname os.remove(lname) except: raise try: with open(file,'w+') as fhandler: fhandler.write(decrypt(data,key)) fhandler.close() except: raise
81eb6bed5384060113082f3368ef063c99d8120a
oshkuk22/repo_2_lesson
/1.py
622
3.875
4
# 1. Создать список и заполнить его элементами различных типов данных. # Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. # Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. my_list = [1, 'stroka', 3.6, [5,6],(1,2),{3,4},{'name':'Sergey'}, True] for i in my_list: print(f'Тип эдемента списка: {type(i)}')
afe3b5d0575470ec875ac55769a7944a92e682be
stockholm44/python_study_2018
/edwith/Chapter 7/1_linear_regression/linear_regression.py
4,956
3.84375
4
# Linear regression with one variable, implemented by numpy. # 1. pyplot, pandas, numpy 로드 import matplotlib.pyplot as plt import pandas as pd import numpy as np # 2. %matplotlib inline ?? 입력 %matplotlib inline # 1) LOAD DATASET # 3. xls 데이터 불려들어오기. C:/study_2018/python_study_2018/edwith/Chapter 7/1_linear_regression/slr06.xls df = pd.read_excel("C:/study_2018/python_study_2018/edwith/Chapter 7/1_linear_regression/slr06.xls") # 4. head데이터 로드 df.head() # 5. raw_X에 X컬럼을 1개짜리 컬럼으로에서 array로써 변수할당. raw_X = df["X"].values.reshape(-1, 1) # 6. Y 컬럼을 y에 할당 y = df["Y"].values # 한번 plot해보자. # 7. figsize 10,5로 figure만들기 plt.figure(figsize=(10,5)) # 8. raw_X와 y로 plot, o모양, 투명도 0.5(alpha써라.) plt.plot(raw_X,y, 'o', alpha=0.5) # 9. raw_X와 y 5행까지 로드 raw_X[:5], y[:5] # 10. raw_X의 길이 * 1만큼 one행렬만들어주기. 하되 3줄까지만 출력.(W0의 계산을 위함.) np.ones((len(raw_X),1))[:3] # 11. raw_X행렬의 0 컬럼에 위의 10.에서 만든 one 행렬 붙여주되 열로(열방향) 붙이고 X이름으로 변수로 저장. X = np.concatenate( (np.ones((len(raw_X),1)), raw_X), axis=1 ) # 12. X의 5줄까지 출력 X[:5] # 첫 W벡터를 normal(가우시안) distribution범위로 2와 1을 랜덤숫자로 만들기.(W0, W1) # Draw random samples from a normal (Gaussian) distribution. # numpy.random.normal(loc=0.0, scale=1.0, size=None) # 13. W벡터를 가우시안 dist로 2*1로 만들기. 14. 출력 w = np.random.normal((2,1)) w # 15. 10*5로 plot을 하기전 figure만들기 plt.figure(figsize=(10, 5)) # 16. X와 w를 dot product 해서 y_predict에 할당 y_predict = np.dot(X, w) # 17. raw_X, y로 plot하되 o모양으로 투명도 0.5 plt.plot(raw_X, y, "o", alpha=0.5) # 18. raw_X와 y_predict로 plot plt.plot(raw_X, y_predict) # 2) HYPOTHESIS AND COST FUNCTION # 19 hypothesis_function 함수 만들기. 2개 array받아서 dot product하는 . def hypothesis_function(X, theta): return X.dot(theta) # 20. cost_function 함수만들기. return 값은 (1/2*갯수) * 시그마(h-y)^2 def cost_function(h, y): return (1/(2*len(y))) * np.sum((h-y)**2) # 21. h에 hypothesis_function 할당. h = hypothesis_function(X,w) # 22. cost_function 실행하되 위에서 만든 h와 y로 해보자. cost_function(h,y) w # 3) GRADIENT DESCENT # 23. gradient_descent 함수 만들기. 변수 X, y, w, alpha, iterations # return 값은 theta (최종값), theta_list, cost_list,-->list 두개는 10번째 반복시마다 리스트에 append하게. def gradient_descent(X, y, w, alpha, iterations): theta = w m = len(y) theta_list = [theta.tolist()] cost = cost_function(hypothesis_function(X, theta), y) cost_list = [cost] for i in range(iterations): t0 = theta[0] - (alpha/m) * np.sum(np.dot(X, theta) - y) t1 = theta[1] - (alpha/m) * np.sum((np.dot(X, theta) - y) * X[:,1]) theta = np.array([t0, t1]) if i % 10 == 0: theta_list.append(theta.tolist()) cost = cost_function(hypothesis_function(X, theta), y) cost_list.append(cost) return theta, theta_list, cost_list w # DO Linear regression with GD # 24. iterations 10000, alpha 0.001로 지정. iterations = 10000 alpha = 0.001 # 25 theta, theta_list, cost_list를 gradient_descent로 받기.변수는 변수들그대로, theta, theta_list, cost_list = gradient_descent(X, y, w, alpha, iterations) theta # 26. cost에 cost_function으로 만든걸로 값넣기. cost = cost_function(hypothesis_function(X, w), y) # 27. theta와 cost 프린트하기. print("theta", theta) print("cost: ", cost_function(hypothesis_function(X, theta), y)) # 28. theta_list 5줄 출력 theta_list[:5] # 29. theta_list 어레이화하고 30. 모양보기. 31. X의 모양은? theta_list = np.array(theta_list) theta_list.shape X.shape cost_list[:5] # 30. figure 만들기. 사이즈는 10*5 plt.figure(figsize=(10,5)) # 31. 이건 왜있는지 모르겠다.. X와 theta_list를 dot-product해서 y_predict_step = np.dot(X, theta_list.transpose()) # 32. y_predict_step 출력. y_predict_step y_predict_step.shape # 아. 쉐입을 출력해보니 이해가능. # 1001번반복한 결과들이 한번 하면 행당 1001개 생성. # 63은? 기존 x_data들에 대한 예측치가 어떻게 변했는지를 보여주는 것. # 33. plot 하자. 기존X데이터와 y로 o모양ㅇ로 투명도 0.5 plt.plot(raw_X, y, "o", alpha=0.5) for i in range(0, len(cost_list), 100): plt.plot(raw_X, y_predict_step[:,i], label='Line %d' % i) # 34. 범례넣기.33이랑 같이 아래 반복문으로 fitting한 그래프들을 한번에 그리기. plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0) # 35. cost_list를 이용해서 cost가 어떻게 줄어드는지 graph를 그리기. plt.plot(range(len(cost_list)), cost_list)
b1c7b85d81a6a9e6840454854296ed88ee3cb97f
stockholm44/python_study_2018
/Effective_Python_Code/29.py
2,303
3.5
4
class OldResistor(object): def __init__(self,ohms): self._ohms = ohms def get_ohms(self): return self._ohms def set_ohms(self, ohms): self._ohms = ohms r0 = OldResistor(50e3) print('Before: %5r' % r0.get_ohms()) r0.set_ohms(10e3) print('After: %5r' % r0.get_ohms()) r0.set_ohms(r0.get_ohms() + 5e3) print('Finally: %5r', r0.get_ohms()) # 일반속성으로 구현시 class Resistor(object): def __init__(self, ohms): self.ohms = ohms self.voltage = 0 self.current = 0 r1 = Resistor(50e3) print(r1.ohms) r1.ohms = 10e3 print(r1.ohms) # 속성설정시 특별한 동작이 일어나야하면 @property 데코레이터사용 class VoltageResistance(Resistor): def __init__(self, ohms): super().__init__(ohms) self._voltage = 0 @property def voltage(self): return self._voltage @voltage.setter def voltage(self, voltage): self._voltage = voltage self.current = self._voltage / self.ohms r2 = VoltageResistance(1e3) print('Before : %5r amps' % r2.current) r2.voltage = 10 print('After : %5r amps' % r2.current) # 프로퍼티에 setter 설정시 타입체크하고 값검증가능. class BoundedResistance(Resistor): def __init__(self, ohms): super().__init__(ohms) @property def ohms(self): return self._ohms @ohms.setter def ohms(self, ohms): if ohms <= 0: raise ValueError('%f ohms must be >0' % ohms) self._ohms = ohms r3 = BoundedResistance(1e3) # r3.ohms = 0 # BoundedResistance(-5) # 부모클래스의 속성을 불변으로 만드든데도 @property 사용가능 class FixedResistance(Resistor): @property def ohms(self): return self._ohms @ohms.setter def ohms(self, ohms): if hasattr(self, '_ohms'): raise AttributeError("Can't set attribute") self._ohms = ohms r4 = FixedResistance(1e3) print(r4.ohms) # r4.ohms = 2e3 print(r4.ohms) class MysteriousResistor(Resistor): @property def ohms(self): self.voltage = self._ohms * self.current return self._ohms r7 = MysteriousResistor(10) print(r7.ohms, r7.voltage, r7.current) r7.current = 0.01 print('Before: %5r' % r7.voltage) r7.ohms print('After: %5r' % r7.voltage)
013b2ac2244f256970950dc1cc7cdcae25f5371d
stockholm44/python_study_2018
/wikidocs/06-2.py
737
4.15625
4
# 06-2 3의 배수와 5의 배수를 1-1000사이에 더해주는거. 아니다. 그냥 class로 n을 받자. class Times: def __init__(self, n): self.n = n def three_five_times(self): sum = 0 # return sum = sum + i for i in range(1, self.n) if i % 3 ==0 or i % 5 == 0] # how can i make functional sum of for loop. for i in range(1, self.n): if i % 3 == 0 or i % 5 == 0: sum += i return sum a = Times(1000) print(a.three_five_times()) #새로운답 """ class Sum: def __init__(self, n): self.n = n def Sum_Times(self): return sum([x for x in range(1, self.n) if x % 3 ==0 or x % 5 == 0]) a = Sum(1000) print(a.Sum_Times()) """
1e0667bd5203e872f1d64f6273d4a124e0617a5e
stockholm44/python_study_2018
/wikidocs/05-1_클래스.py
1,824
3.90625
4
# wikidocs #1 class Calculator: def __init__(self): self.value = 0 def add(self, val): # --> self 넣어야함. self.value += val cal = Calculator() cal.add(3) cal.add(4) print(cal.value) #2 class Calculator: def __init__(self, init_value): self.value = init_value def add(self, val): self.value += val cal = Calculator(0) # --> init value 설정 cal.add(3) cal.add(4) print(cal.value) #3 class Calculator: def __init__(self): self.value = 0 def add(self, val): self.value += val class UpgradeCalculator(Calculator): def minus(self, val): self.value -= val cal = UpgradeCalculator() cal.add(10) print(cal.value) cal.minus(7) print(cal.value) # 10에서 7을 뺀 3을 출력 #4 class Calculator: def __init__(self): self.value = 0 def add(self, val): self.value += val class MaxLimitCalculator(Calculator): def add(self, val): self.value += val # if self.value > 100: # self.value = 100 self.value = self.value if self.value < 100 else 100 cal = MaxLimitCalculator() cal.add(50) # 50 더하기 print(cal.value) cal.add(60) # 60 더하기 print(cal.value) #5 class Calculator: def __init__(self, list): self.list = list def sum(self): self.sum = 0 for i in self.list: self.sum += i return self.sum def avg(self): # self.sum = 0 # for i in self.list: # self.sum += i return self.sum/len(self.list) cal1 = Calculator([1,2,3,4,5]) print(cal1.sum()) # 15 출력 print(cal1.avg()) # 3.0 출력 cal2 = Calculator([6,7,8,9,10]) print(cal2.sum()) # 40 출력 print(cal2.avg()) # 8.0 출력
73ec6e73f0d84cd6265a02419283a76c05491c59
Cattleman/Feedforward
/nn.py
7,259
3.96875
4
"""Functions and classes for training feedforward neural networks.""" import math import random import numpy as np import scipy.optimize as optim class FeedforwardNN: """A simple feedforward neural network class.""" def __init__(self, sizes, seed=0): self.sizes = list(sizes) self.w, self.b = _random_layers(self.sizes, seed=seed) def __repr__(self): sizes = '[{}]'.format(', '.join([str(s) for s in self.sizes])) return 'FeedforwardNN({})'.format(sizes) @property def num_layers(self): return len(self.w) + 1 def predict(self, x): """Apply the network to an input. Parameters ---------- x : The input. Returns ------- The predicted value at x. """ activ = self.forward(x) return activ[-1].squeeze() def forward(self, x): """Collect activations of hidden units. Parameters ---------- x : The input. Returns ------- A list containing the input and the activations at layer. """ activ = [np.atleast_1d(x)] for w, b in zip(self.w, self.b): a = sigmoid(w @ activ[-1] + b) activ.append(a) return activ def backprop(self, x, y): """Compute the gradient of the loss using backpropagation. Parameters ---------- x : Input data. y : Target data. Returns ------- Partial derivatives with respect to parameters in each layer. """ activ = self.forward(x) yhat = activ[-1].squeeze() delta = [] # Special case for last layer. z = self.w[-1] @ activ[-2] + self.b[-1] delta.append(-(y - yhat) * sigmoid_jac(z)) # All remaining layers (except the first). for k in range(2, self.num_layers): z = self.w[-k] @ activ[-(k + 1)] + self.b[-k] d = (delta[-1] @ self.w[-(k - 1)]) * sigmoid_jac(z) delta.append(d) delta.reverse() # Compute gradients dw = [] db = [] for k in range(1, self.num_layers): a = activ[k - 1] d = delta[k - 1] dw.append(_colv(d) * a) db.append(d) return dw, db def update(self, dw, db, rate): """Update model parameters using gradients. Parameters ---------- dw : Weight gradients. db : Bias gradients. rate : Learning rate. Returns ------- Nothing, just updates the parameters. """ for k in range(self.num_layers - 1): self.w[k] -= rate * dw[k] self.b[k] -= rate * db[k] def loss(self, dataset): """Compute the average loss on a dataset. Parameters ---------- dataset : List of x, y pairs. Returns ------- A single number. """ losses = [0.5 * np.sum((y - self.predict(x))**2) for x, y in dataset] return np.mean(losses) def learn(model, train, rate, batch_size, epochs): """Run stochastic gradient descent to learn model weights. Parameters ---------- model : Neural network. train : Training instances. rate : Learning rate to use. batch_size : Number of samples in each batch. epochs : Number of epochs (passes through the data). Returns ------- Updated model. """ train = list(train) num_train = len(train) num_batches = math.ceil(num_train / batch_size) for i in range(epochs): random.shuffle(train) for j in range(num_batches): first = j * batch_size last = (j + 1) * batch_size batch = train[first:last] dw = [0.0] * (model.num_layers - 1) db = [0.0] * (model.num_layers - 1) for x, y in batch: w, b = model.backprop(x, y) for k in range(len(dw)): dw[k] += w[k] / len(batch) db[k] += b[k] / len(batch) model.update(dw, db, rate) if (i + 1) % 10 == 0: print(model.loss(train)) return model def _random_layers(sizes, scale=0.1, seed=0): """Randomly initialize layer weights and biases. Parameters ---------- sizes : A list of layer sizes. scale : The standard deviation of the initialization distribution. seed : Random number generator seed. Returns ------- A list of weights corresponding to the layers mapping between hidden units. """ rng = np.random.RandomState(seed) weights = [] biases = [] for n_in, n_out in zip(sizes, sizes[1:]): w = rng.normal(scale=scale, size=(n_out, n_in)) b = rng.normal(scale=scale, size=n_out) weights.append(w) biases.append(b) return weights, biases def learn_neuron(x, y): """Learn the weights of a single neuron. Parameters ---------- x : Example inputs. y : Example outputs. Returns ------- A vector of weights parameterizing a neuron. """ x = np.asarray(x) y = np.asarray(y) def loss(w): yhat = np.array([neuron(w, x) for x in x]) return 0.5 * np.mean((y - yhat)**2) def loss_jac(w): yhat = np.array([neuron(w, x) for x in x]) dw = (yhat - y)[:, None] * np.array([neuron_jac(w, x) for x in x]) return np.mean(dw, axis=0) w = np.random.normal(scale=0.01, size=len(x[0])) solution = optim.minimize(loss, w, jac=loss_jac, method='CG') return solution['x'] def neuron(w, x): """A single neuron activation. Parameters ---------- w : The weight vector. x : The input vector. Returns ------- The neuron activation value. """ return sigmoid(w @ x) def neuron_jac(w, x): """The jacobian of the neuron with respect to w. Parameters ---------- w : The weight vector. x : The input vector. Returns ------- The jacobian of the neuron. """ return sigmoid_jac(w @ x) * x def sigmoid(x): """The sigmoid function. Parameters ---------- x : A scalar or ndarray. Returns ------- The sigmoid evaluated at x (or its elements if it is an ndarray). """ return 1.0 / (1.0 + np.exp(-x)) def sigmoid_jac(x): """The derivative of the sigmoid function. Parameters ---------- x : A scalar or ndarray. Returns ------- The derivative with respect to x (or each of its elements). """ y = sigmoid(x) return y * (1.0 - y) def add_bias(x): """Add a bias (intercept) to the inputs.""" b = np.ones((len(x), 1)) return np.hstack((b, x)) def rescale(x, low, high): """Rescale values to lie between 0 and 1. Parameters ---------- x : Array of values. low : The unscaled lower bound. high : The unscaled upper bound. Returns ------- An array with rescaled values. """ return (x - low) / (high - low) def _rowv(x): """View array as a row vector.""" return x[None, :] def _colv(x): """View array as a column vector.""" return _rowv(x).T
c5910f1116ccfb97578f5c4d0f3f65023e3be1ad
leocjj/0123
/Machine Learning/0_Copilot/test02.py
342
4.21875
4
def calculate_fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return calculate_fibonacci(n-1) + calculate_fibonacci(n-2) def main(): n = int(input("Enter the number of terms: ")) for i in range(n): print(calculate_fibonacci(i), end=" ") if __name__ == "__main__": main()
071bbc12b2d818a217e5eb364da33d022b1166a7
leocjj/0123
/Machine Learning/ZZ_Census/backup/25-one_hot_decode.py
983
3.6875
4
#!/usr/bin/env python3 """ 0x01. Classification """ import numpy as np def one_hot_decode(one_hot): """ Function that converts a one-hot matrix into a vector of labels. :param one_hot: is a one-hot encoded numpy.ndarray with shape (classes, m) classes is the maximum number of classes m is the number of examples :return: a numpy.ndarray with shape (m, ) containing the numeric labels for each example, or None on failure """ if not isinstance(one_hot, np.ndarray) \ or not one_hot.ndim == 2 \ or not one_hot.shape[0] > 0 \ or not one_hot.shape[1] > 0 \ or not np.all(0 <= one_hot)\ or not np.all(one_hot <= 1): return None result = np.array([]) for i in range(one_hot.shape[1]): temp = np.where(one_hot[:, i] == 1) if len(temp[0]) != 1: return None result = np.append(result, temp[0][0]).astype(int) return result
2b32d798a175be4fbc682ca9b737c5d1231ff989
leocjj/0123
/Python/python_dsa-master/stack/postfix_eval.py
730
4.1875
4
#!/usr/bin/python3 """ Evaluate a postfix string """ from stack import Stack def postfix_eval(string): # Evaluate a postfix string operands = Stack() tokens = string.split() for token in tokens: if token.isdigit(): operands.push(int(token)) else: op2 = operands.pop() op1 = operands.pop() operands.push(do_math(token, op1, op2)) return operands.pop() def do_math(op, op1, op2): # Perform an operation if op == '*': return op1 * op2 elif op == '/': return op1 / op2 elif op == '+': return op1 + op2 else: return op1 - op2 if __name__ == '__main__': print(postfix_eval('7 8 + 3 2 + /'))
27c6ec9e71d1d1cdd87ae03180937f2d798db4b2
leocjj/0123
/Python/python_dsa-master/recursion/int_to_string.py
393
4.125
4
#!/usr/bin/python3 """ Convert an integer to a string """ def int_to_string(n, base): # Convert an integer to a string convert_string = '0123456789ABCDEF' if n < base: return convert_string[n] else: return int_to_string(n // base, base) + convert_string[n % base] if __name__ == '__main__': print(int_to_string(1453, 16)) print(int_to_string(10, 2))
059bfba1640d2d348a08d6764c41c0fc6951fa64
leocjj/0123
/Python/python_dsa-master/search/selection.py
528
4
4
#!/usr/bin/python3 # Implement selection sort # O(n^2) def selection_sort(my_list): # Implement selection sort for passes in range(len(my_list) - 1, 0, -1): pos_max = 0 for i in range(1, passes + 1): if my_list[i] > my_list[pos_max]: pos_max = i my_list[passes], my_list[pos_max] = my_list[pos_max], my_list[passes] print(my_list) if __name__ == '__main__': my_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print(my_list) selection_sort(my_list)
35eb4eddbc01e1c926e84c1a7d5f5467f4365746
leocjj/0123
/Python/python_dsa-master/recursion/palindrome.py
737
4.21875
4
#!/usr/bin/python3 """ Check if a string is a palindrome """ def remove_white(s): # Remove characters that are not letters new = '' for ch in s: if ord(ch) >= ord('a') and ord(ch) <= ord('z'): new += ch return new def palindrome(s): # Check if a string is a palindrome if len(s) <= 1: return True elif s[0] != s[len(s) - 1]: return False else: return palindrome(s[1:-1]) if __name__ == '__main__': print(palindrome(remove_white('lsdkjfskf'))) print(palindrome(remove_white('radar'))) print(palindrome(remove_white('a man, a plan, a canal, panama'))) print(palindrome(remove_white(''))) print(palindrome(remove_white("madam i'm adam")))
30119f22b0adfe7d39baff1ecae0a1fe9a8ffea7
leocjj/0123
/Machine Learning/ZZ_Census/backup/24-one_hot_encode.py
820
3.65625
4
#!/usr/bin/env python3 """ 0x01. Classification """ import numpy as np def one_hot_encode(Y, classes): """ Function that converts a numeric label vector into a one-hot matrix. :param Y: is a np.ndarray with shape (m,) containing numeric class labels. :param classes: is the maximum number of classes found in Y :return: a one-hot encoding of Y with shape (classes, m) or None on failure """ if not isinstance(classes, int) or classes < 1: return None if not isinstance(Y, np.ndarray)\ or not Y.ndim == 1\ or not np.issubdtype(Y.dtype, np.integer)\ or not np.all(0 <= Y)\ or not np.all(Y < classes): return None A = np.zeros((classes, Y.shape[0])) for i in range(Y.shape[0]): A[Y[i]][i] = 1 return A
e81c76e31dd827790d6b98e739763201cfc618ab
tlepage/Academic
/Python/longest_repetition.py
1,121
4.21875
4
__author__ = 'tomlepage' # Define a procedure, longest_repetition, that takes as input a # list, and returns the element in the list that has the most # consecutive repetitions. If there are multiple elements that # have the same number of longest repetitions, the result should # be the one that appears first. If the input list is empty, # it should return None. def longest_repetition(i): count = 0 largest_count = 0 curr = None largest = None for e in i: if curr == None: curr = e largest = e count = 1 else: if e == curr: count += 1 if count > largest_count: largest_count = count largest = curr else: curr = e count = 1 return largest #For example, print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1]) # 3 print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd']) # b print longest_repetition([1,2,3,4,5]) # 1 print longest_repetition([]) # None print longest_repetition([2, 2, 3, 3, 3])