blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
aaf02763d3b8ef0952f681de941f98a57a8bf35a
jailukanna/100daysofcodechallenge
/day16_Hacker_rank challenge.py
641
4.25
4
# https://www.hackerrank.com/challenges/word-order/problem # Problem Statement:You are given words. Some words may repeat. For each word, output its number of occurrences. # The output order should correspond with the input order of appearance of the word. ''' Sample Input 4 bcdef abcdefg bcde bcdef Sample Output 3 2 1 1 ''' from collections import OrderedDict occurances = OrderedDict() for _ in range(int(input())): # _ in for loop is used when you do not want to use the iterator values word = input() occurances[word] = occurances.get(word, 0) + 1 # print(occurances) print(len(occurances)) print(*occurances.values())
ce42c743dd7fb273d979517afba641754ddaf48a
corifeo/challenges
/reverse_vowels.py
654
4.28125
4
""" Write a function that takes a string as input and reverse only the vowels of a string. """ VOWELS = set('aeiou') def reverse_vowels(input_string): string = list(input_string) vowels = [] indexes = [] # loop through string to find vowels for x, y in enumerate(string): if y in VOWELS: vowels.append(y) indexes.append(x) # loop through tuple and replace characters for i, j in zip(indexes, reversed(vowels)): string[i] = j return ''.join(string) print(reverse_vowels('hello')) # holle print(reverse_vowels('lEetcode')) # leotcedE print(reverse_vowels('anAconda')) # anocAnda
77bc0334264181a3e05ccefa0b198423d1df9bf5
kikiyoung/425-Machine-Learning
/HW3/homework3.xinyuan.py
10,671
3.65625
4
#!/usr/bin/env python # coding: utf-8 # # Homework Assignment 3 # Xinyuan Yang # # UID:305255240 # ## Problem I. Logistic Regression # In[45]: import numpy as np import matplotlib.pyplot as plt from getDataset import getDataSet from sklearn.linear_model import LogisticRegression # Starting codes # Fill in the codes between "%PLACEHOLDER#start" and "PLACEHOLDER#end" # step 1: generate dataset that includes both positive and negative samples, # where each sample is described with two features. # 250 samples in total. [X, y] = getDataSet() # note that y contains only 1s and 0s, # create figure for all charts to be placed on so can be viewed together fig = plt.figure() def func_DisplayData(dataSamplesX, dataSamplesY, chartNum, titleMessage): idx1 = (dataSamplesY == 0).nonzero() # object indices for the 1st class idx2 = (dataSamplesY == 1).nonzero() ax = fig.add_subplot(1, 3, chartNum) # no more variables are needed plt.plot(dataSamplesX[idx1, 0], dataSamplesX[idx1, 1], 'r*') plt.plot(dataSamplesX[idx2, 0], dataSamplesX[idx2, 1], 'b*') # axis tight ax.set_xlabel('x_1') ax.set_ylabel('x_2') ax.set_title(titleMessage) # plotting all samples func_DisplayData(X, y, 1, 'All samples') # number of training samples nTrain = 120 ######################PLACEHOLDER 1#start######################### # write you own code to randomly pick up nTrain number of samples for training and use the rest for testing. # WARNIN: maxIndex = len(X) RandomTrainingData = np.random.choice(maxIndex, nTrain, replace=False) RandomTestingData = [i for i in range(maxIndex)if i not in RandomTrainingData] trainX = X[RandomTrainingData,:] # training samples trainY = y[RandomTrainingData,:] # labels of training samples nTrain X 1 testX = X[RandomTestingData,:] # testing samples testY = y[RandomTestingData,:] # labels of testing samples nTest X 1 ####################PLACEHOLDER 1#end######################### # plot the samples you have pickup for training, check to confirm that both negative # and positive samples are included. func_DisplayData(trainX, trainY, 2, 'training samples') func_DisplayData(testX, testY, 3, 'testing samples') # show all charts plt.show() # Through step 1, we generate the provided data and split it into training and testing subsets. In this case, we use random 120 samples as training data, and use the left 130 samples as testing data. # # Then, the code will display the splitting results of all samples, traning samples and testing samples. From the plot, we can see that the distributions of features are similiar in the three pictures. # In[50]: # step 2: train logistic regression models ######################PLACEHOLDER2 #start######################### # in this placefolder you will need to train a logistic model using the training data: trainX, and trainY. # please delete these coding lines and use the sample codes provided in the folder "codeLogit" # logReg = LogisticRegression(fit_intercept=True, C=1e15) # create a model # logReg.fit(trainX, trainY)# training # coeffs = logReg.coef_ # coefficients # intercept = logReg.intercept_ # bias # bHat = np.hstack((np.array([intercept]), coeffs))# model parameters clf = LogisticRegression() # utilize the function fit() to train the class samples clf.fit(trainX,trainY) # scores over testing samples # print the fearure distribution plot of data using functions in the library pylab from pylab import scatter, show, legend, xlabel, ylabel positive = np.where(y == 1) negative = np.where(y == 0) scatter(X[positive, 0], X[positive, 1], c='y') scatter(X[negative, 0], X[negative, 1], c='g') xlabel('Feature 1: score 1') ylabel('Feature 2: score 2') legend(['Label: Admitted', 'Label: Not Admitted']) show() theta = [0,0] #initial model parameters alpha = 0.1 # learning rates max_iteration = 1000 # maximal iterations from util import Cost_Function, Gradient_Descent, Cost_Function_Derivative, Cost_Function, Prediction, Sigmoid theta = [0,0] #initial model parameters alpha = 0.1 # learning rates max_iteration = 1000 # maximal iterations m = len(y) # number of samples for x in range(max_iteration): # call the functions for gradient descent method new_theta = Gradient_Descent(X,y,theta,m,alpha) theta = new_theta if x % 200 == 0: # calculate the cost function with the present theta Cost_Function(X,y,theta,m) print('theta is ', theta) print('cost is ', Cost_Function(X,y,theta,m)) score = 0 for i in range(len(testX)): prediction = round(Prediction(testX[i],theta)) answer = testY[i] if prediction == answer: score += 1 gdScore = float(score) / float(len(testX)) print('Coefficients from sklearn:', clf.coef_) print('Coefficients from gradient descent:',theta) print('Score from sklearn: ', clf.score(testX,testY)) print('Score from gradient descent: ', gdScore) ######################PLACEHOLDER2 #end ######################### # The second step is to train a logistic regression model using the 120 training samples. To do so, we use the functions in the folder ‘codeLogit’ and there are two different implementations, that is, sklearn and gradient descent. # # The accurancy in this case is 0.9, so we can conclude that with the used model, the accuancy of the test dataset is considerably high. # # Additionally, we can see that there is a decreasing trend of theta, it even goes from positive to negative, and the output of the cost function decreases as well. # # Lastly, coparing the sklearn model and gradient descent model, the score for sklearn model is 0.9846153846153847 and the score for gradient descent model is 0.823076923076923. The difference here is due to the shorages in Gradient Descent Model, it has a strict rule for learning rate, it is relatively sensitive. # In[34]: # step 3: Use the model to get class labels of testing samples. ######################PLACEHOLDER3 #start######################### # codes for making prediction, # with the learned model, apply the logistic model over testing samples # hatProb is the probability of belonging to the class 1. # y = 1/(1+exp(-Xb)) # yHat = 1./(1+exp( -[ones( size(X,1),1 ), X] * bHat )); )); # WARNING: please DELETE THE FOLLOWING CODEING LINES and write your own codes for making predictions # xHat = np.concatenate((np.ones((testX.shape[0], 1)), testX), axis=1) # add column of 1s to left most -> 130 X 3 # negXHat = np.negative(xHat) # -1 multiplied by matrix -> still 130 X 3 # hatProb = 1.0 / (1.0 + np.exp(negXHat * bHat)) # variant of classification -> 130 X 3 # predict the class labels with a threshold # yHat = (hatProb >= 0.5).astype(int) # convert bool (True/False) to int (1/0) # PLACEHOLDER#end #print('score Scikit learn: ', clf.score(testX,testY)) #this is the prediction using gradient decent yHat = [Prediction(row,theta) for row in testX] yHat = np.array([float(int(val >= .6)) for val in yHat]) #yHat yHatSk = clf.predict(testX) #yHatSk #testY #len(yHatSk) #len(testY) ######################PLACEHOLDER 3 #end ######################### # The third step is to apply the learned model to get the binary classes of testing samples. This step is modified according to the implementation of the second step. # In[54]: # step 4: evaluation # compare predictions yHat and and true labels testy to calculate average error and standard deviation testYDiff = np.abs(yHat - testY) avgErr = np.mean(testYDiff) stdErr = np.std(testYDiff) print('average error of the Gradient decent model: {} ({})'.format(avgErr, stdErr)) score = 0 winner = "" # accuracy for sklearn scikit_score = clf.score(testX,testY) length = len(testX) for i in range(length): prediction = round(Prediction(testX[i],theta)) answer = testY[i] if prediction == answer: score += 1 my_score = float(score) / float(length) if my_score > scikit_score: print('You won!') elif my_score == scikit_score: print('Its a tie!') else: print('Scikit won.') print('Your score: ', my_score) print('Scikits score: ', scikit_score) # The fourth step is to compare the predictions with the ground-truth labels and calculate average errors and standard deviation. # ## Problem II. Confusion matrix # Confusion Matrix: # # Cat Dog Monkey # Cat 1 3 1 # Dog 3 3 2 # Monkey 2 2 3 # # Accuracy: (1+3+3)/20=0.35 # # For Cat: # Precision: 1/(1+3+2)=0.167 # Recall:1/(1+3+1)=0.2 # # For Dog: # Precision:3/(3+3+2)=0.375 # Recall:3/(3+3+2)=0.375 # # For Monkey: # Precision:3/(1+2+3)=0.5 # Recall:3/(3+2+2)0.429 # ## Problem III. Comparative Studies! # In[55]: #this function returns the accuracy and a precision/recall array. #included in each row of the precision recall array is: # 0 - the value # 1 - the precision # 2 - the recall def func_calConfusionMatrix(predY,trueY): print("Confusion Matrix:") for pred1 in np.unique(predY): print(int(pred1), end=" ") for pred2 in np.unique(predY): correctCount = 0 for i in range(len(predY)): if(predY[i] == pred1 and trueY[i] == pred2): correctCount += 1 print(correctCount, end=" ") print() #accuacy correctCount = 0 for index in range(len(trueY)): if(trueY[index] == predY[index]): correctCount += 1 #print(correctCount) accuracy = correctCount / len(trueY) precRec = [] for pred in np.unique(trueY): pred = int(pred) #print(pred) #precision correctCount = 0 for i in range(len(trueY)): if(int(trueY[i]) == int(predY[i]) and int(trueY[i]) == pred): correctCount += 1 #print(correctCount) #print(len(predY[predY == pred])) prec = correctCount / len(predY[predY == pred]) #recall correctCount = 0 for i in range(len(trueY)): if(trueY[i] == predY[i] and int(trueY[i]) == pred): correctCount += 1 rec = correctCount / len(trueY[trueY == pred]) #print(len(trueY[trueY == pred])) #print(rec) precRec.append([pred,prec,rec]) return accuracy, precRec values = func_calConfusionMatrix(yHatSk,testY) print('Accurracy, Precision, and Recall for our SkLearn model:') print(values) print() values = func_calConfusionMatrix(yHat,testY) print('Accurracy, Precision, and Recall for our gradient decent model:') print(values)
483e12218f140a769b22b2ac23dbd6240bef948e
alestrzelec/python
/ldld.py
205
3.625
4
a = [1,2,3] b = [3,4,8] #while len(a) > 0: # a.pop() # print "lala" c = [] for i in range(len(a)): c.append(a[i] + b[i]) print c for i in range(len(a)): a[i] = a[i] + b[i] print a
d7e44a9854e0cc34b7606ac9bc78182537928eca
jake1512/SE04-Nhom29.1
/rotation.py
1,539
3.5
4
import math # 3D rotation # rotate by X axis def rotateX3D(theta, posxy): sinTheta = math.sin(math.radians(theta)) cosTheta = math.cos(math.radians(theta)) newPosXY = [] for node in posxy: tmpz = node[2] tmpy = node[1] z = tmpz * cosTheta + tmpy * sinTheta y = tmpy * cosTheta - tmpz * sinTheta newPosXY.append((node[0], y, z)) return newPosXY # rotate by Y axis def rotateY3D(theta, posxy): sinTheta = math.sin(math.radians(theta)) cosTheta = math.cos(math.radians(theta)) newPosXY = [] for node in posxy: tmpx = node[0] tmpz = node[2] x = tmpx * cosTheta + tmpz * sinTheta z = tmpz * cosTheta - tmpx * sinTheta newPosXY.append((x, node[1], z)) return newPosXY # rotate by Z axis def rotateZ3D(theta, posxy): sinTheta = math.sin(math.radians(theta)) cosTheta = math.cos(math.radians(theta)) newPosXY = [] for node in posxy: tmpx = node[0] tmpy = node[1] x = tmpx * cosTheta - tmpy * sinTheta y = tmpy * cosTheta + tmpx * sinTheta newPosXY.append((x, y, node[2])) return newPosXY def rotate3D(rx, ry, rz, posxy, h): newPosXY = [] for node in posxy: # convert 2D coord to 3D coord newPosXY.append((node[0], node[1], h)) posxy = newPosXY if rx != 0: posxy = rotateX3D(rx, posxy) if ry != 0: posxy = rotateY3D(ry, posxy) if rz != 0: posxy = rotateZ3D(rz, posxy) return posxy
ee0f6e3f3598f5478d3cac3c224b5576ceae38f2
daniel-amaral/temp-trabalho-ad
/entidades/evento.py
868
3.5625
4
class Evento(): def __init__(self, tipo_de_evento, func_gera_amostra): self.__tipo_de_evento = tipo_de_evento self.__func_gera_amostra = func_gera_amostra self.__instante = None @property def tipo_de_evento(self): return self.__tipo_de_evento def instante(self): """ Retorna o instante atual e já calcula o tempo do evento seguinte """ if self.__instante is not None: ret = self.__instante self.__instante += self.__func_gera_amostra() return ret instante_atual = self.__func_gera_amostra() self.__instante = instante_atual + self.__func_gera_amostra() return instante_atual def set_instante(self, instante): self.__instante = instante def __lt__(self, other): return self.instante < other.instante
2534535d0f1d7f205565c9c152f986274e0f71cc
lukeFalsina/StudyPlanGeneratorPolimi
/GenerateStudyPlan.py
2,655
3.703125
4
# GenerateStudyPlan.py # This small Python script takes as an input the solution provided # by AMPL on the study_plan.mod and saves in an outfile file # the corresponding study plan table using courses information # stored in the auxiliary file "course_info.txt" # # Author: Luca Falsina # from tabulate import tabulate from operator import itemgetter import sys def main(argv): if (len(sys.argv) != 1): sys.exit('Usage: GenerateStudyPlan.py') # Initialize dictionaries. isInEnglish = {} credits = {} semester = {} group = {} name = {} # Collect all courses info from an auxiliary file # and store them into proper dictionaries. with open('course_info.txt') as courseFile: for line in courseFile: course_info_list = list(line.split('#')) # First attribute is the unique code for the course.. course_code = int(course_info_list[0]) # Then it follows the language used to teach it.. if int(course_info_list[1]) == 1: isInEnglish[course_code] = "English" else: isInEnglish[course_code] = "Italian" # Then its number of credits.. credits[course_code] = int(course_info_list[2]) # Then the semester in which it's held.. semester[course_code] = int(course_info_list[3]) # Then its group.. group[course_code] = course_info_list[4].replace(" ","") # And finally the full course name name[course_code] = course_info_list[5].strip() # Initialize study plan table with first row used for the headers studyPlanTable = [] with open('temp.txt') as studyPlanFile: # Skip first three lines since they are headers for _ in xrange(3): next(studyPlanFile) for line in studyPlanFile: if len(line) > 6: # Remove multiple blank spaces purgedLine = " ".join(line.split()) counter = 0 currCourseCode = 0 for value in purgedLine.split(): if counter % 2 == 0: # This value should be a course code.. currCourseCode = int(value) else: # This value tells if the previous course # should be added to the study plan.. if int(value) == 1: # The tuple of this course is added.. studyPlanTable.append([currCourseCode, name[currCourseCode], group[currCourseCode], isInEnglish[currCourseCode], semester[currCourseCode], credits[currCourseCode]]) counter = counter + 1 # Sort elements in the table by their name studyPlanTable = sorted(studyPlanTable, key=itemgetter(1)) # Define headers for the table headers_tuple = ["Code", "Course Name", "Group", "Teaching Language", "Semester", "Credits (CFU)"] print tabulate(studyPlanTable, headers = headers_tuple, tablefmt="grid") if __name__ == "__main__": main(sys.argv[1:])
313b1311d3ebeaec945301ce2cbbf4f70ec61c46
jeffseif/projectEuler
/src/p043.py
656
3.625
4
#! /usr/bin/python3 # The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. # Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: # d2d3d4=406 is divisible by 2 # d3d4d5=063 is divisible by 3 # d4d5d6=635 is divisible by 5 # d5d6d7=357 is divisible by 7 # d6d7d8=572 is divisible by 11 # d7d8d9=728 is divisible by 13 # d8d9d10=289 is divisible by 17 # Find the sum of all 0 to 9 pandigital numbers with this property. from euler import * if __name__ == '__main__': pass
a8b7588ed349fd0cc87a9653ef7c6c22af7e741f
dhankhar313/Coursera-Courses
/An-Introduction-to-Programming-the-Internet-of-Things-(IOT)-Specialization/4. The Raspberry Pi Platform and Python Programming for the Raspberry Pi/Week 3/assignment.py
95
4
4
temp = [] for i in range(3): temp.append(int(input('Enter number:'))) print(sorted(temp))
a27e67abea3a173a443e8e8a8b06bdf1eb3c6ad0
Yaswanthbobbu/IQuestions_Python
/Questions/9. swap any element.py
223
3.859375
4
list =[1,2,3,4] #approach list[0],list[2]=list[2],list[0] print(list) #tuple get=(list[0],list[2]) list[2],list[0]=get print(list) #pop pos1=list.pop(1) pos2=list.pop(2) list.insert(1,pos2) list.insert(3,pos1) print(list)
b69d85df1e94e594b26c9019b77ea5fb53eb369a
hasanIqbalAnik/math-prog
/find_group_generator.py
530
3.53125
4
from collections import defaultdict # we find the generators of a cyclic group formed by F*_p where p is any prime number. def generate_group_elements(prime): return [x%prime for x in range(1, prime)] def find_all_group_gen(group_elems, prime): d = {k: True for k in group_elems} res = [] for elem in group_elems: d_check = defaultdict(int) for i in range(1, prime): v = (elem**i)%prime if v in d_check: break else: d_check[v] = True if len(d_check) == prime - 1: res.append(elem) return res
1d0442cb0b294d47c33f6a9c2c8831338e604ce3
developeryuldashev/python-core
/python core/Lesson_10/Class_work1/methods.py
491
3.53125
4
# coding=utf-8 def Print(x): for i in x: for j in i: print(j, end=' ') print() def Input(m,n): x = [] for i in range(m): b = [] for j in range(n): b.append(int(input('x[{}][{}]='.format(i,j)))) print('--------------') x.append(b) return x def makeMatrix(m): a = [] for i in range(m): b = [] for j in range(m): b.append((i+1)*10+j+1) a.append(b) return a
1e2354a47691c33d42ae92a8dfa5c3e9dd1e2def
Life-of-pi/python_bootcamp
/sets.py
178
3.625
4
mylist=[4,6,4,6,4,4,67,6] print(set(mylist)) my_dict= { 'siva':[45,6,4,6,4,5], 'sanjay':{'c':[45,3,67,34,6],'java':[45,4,3,6,8]}} print(my_dict) print(my_dict.keys())
a568e24e944303c95fd0528c19a686d5fbfa9c6e
shengqianfeng/deeplearning
/pystudy/io/file_rw.py
3,602
4.34375
4
""" 读文件: 要以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符 """ # f = open('D://text.txt', 'r') # 标示符'r'表示读,这样,我们就成功地打开了一个文件 # 如果文件不存在,open()函数就会抛出一个IOError的错误,并且给出错误码和详细的信息告诉你文件不存在 # FileNotFoundError: [Errno 2] No such file or directory: 'D://test.txt' # 如果文件打开成功,接下来,调用read()方法可以一次读取文件的全部内容,Python把内容读到内存,用一个str对象表示 # print(f.read()) # hello,world """ 最后一步是调用close()方法关闭文件。文件使用完毕后必须关闭, 因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的 """ # f.close() """ 由于文件读写时都有可能产生IOError,一旦出错,后面的f.close()就不会调用。 所以,为了保证无论是否出错都能正确地关闭文件,我们可以使用try ... finally来实现 """ # try: # f = open('D://text.txt', 'r') # print(f.read()) # finally: # if f: # f.close() # 但是每次都这么写实在太繁琐,所以,Python引入了with语句来自动帮我们调用close()方法 # 这和前面的try ... finally是一样的,但是代码更佳简洁,并且不必调用f.close()方法 # with open('D://text.txt', 'r') as f: # print(f.read()) """ 调用read()会一次性读取文件的全部内容,如果文件有10G,内存就爆了,所以,要保险起见,可以反复调用read(size)方法, 每次最多读取size个字节的内容。另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。 因此,要根据需要决定怎么调用。 """ # for line in f.readlines(): # print(line.strip()) # 把末尾的'\n'删掉 """ 二进制文件读取 前面讲的默认都是读取文本文件,并且是UTF-8编码的文本文件。要读取二进制文件,比如图片、视频等等,用'rb'模式打开文件即可 """ f = open('c://Users//ubt//Pictures//whoareyou.jpg', 'rb') print(f.read()) """ 字符编码 要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件 open()函数还接收一个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略 """ f = open('D://text.txt', 'r', encoding='gbk', errors='ignore') print(f.read()) """ 写文件: 写文件和读文件是一样的,唯一区别是调用open()函数时,传入标识符'w'或者'wb'表示写文本文件或写二进制文件 """ f = open('D://text.txt', 'w') f.write('Hello, py!') """ 注意: 你可以反复调用write()来写入文件,但是务必要调用f.close()来关闭文件。 当我们写文件时,操作系统往往不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。 只有调用close()方法时,操作系统才保证把没有写入的数据全部写入磁盘。 忘记调用close()的后果是数据可能只写了一部分到磁盘,剩下的丢失了。所以,还是用with语句来得保险 """ with open('D://text.txt', 'a') as f: f.write('Hello, world!') """ 以'w'模式写入文件时,如果文件已存在,会直接覆盖(相当于删掉后新写入一个文件)。 如果我们希望追加到文件末尾怎么办?可以传入'a'以追加(append)模式写入 """
3bcb4c28f6c4c149a686896e8cae08ea8fd61f74
Mcilie/TaliffExer
/p06 r12 ilie michael CODE 57.py
150
4.1875
4
year = int(input("Enter year: ")) if year %4 ==0 and year %400 ==0 and year %100 != 0: print("Leap year") else: print("year is not Leap")
3ffaf93b3a7f8baa7f499784cfee01687c5f04dc
jaysimon/leetcode
/junior/02-linker/03-reverseList.py
1,187
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 ShenZhen Hian Speech S&T Co.,Ltd. All rights reserved. # FileName : reverseList.py # Author : Hou Wei # Version : V1.0 # Date: 2019-02-21 # Description: # History: class ListNode: def __init__(self, x): self.val = x self.next = None def reverseList(head: ListNode) -> ListNode: if (not head): return None nCurrent = head nHead = ListNode(0) nHead.next = nCurrent while (nCurrent.next): # print(nCurrent.val, nCurrent.next.val) nNext = nCurrent.next nCurrent.next = nNext.next nNext.next = nHead.next nHead.next = nNext # new_node = nHead # while (new_node != None): # print(new_node.val) # new_node = new_node.next # print("\n") return nHead.next if __name__ == "__main__": node = ListNode(1) node.next = ListNode(2) node.next.next = ListNode(3) node.next.next.next = ListNode(4) node.next.next.next.next = ListNode(5) new_node = node new_node = reverseList(node) while (new_node != None): print(new_node.val) new_node = new_node.next
7b36083d01865d8bf91f881a9bdce25f897f5885
sathya-sai/Python
/DataStructure/BalancedParanthisis/paranthisis.py
546
3.71875
4
from DataStructure.utility import Stack def parChecker(symbolString): s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol == "(": # if ( push the element s.push(symbol) elif symbol == ")": # if ) pop the element s.pop() index = index + 1 if balanced and s.isEmpty(): return True else: return False z = str(input("enter the arithmetic expressions\n")) print(parChecker(z))
7e69b56f88d81488abc816174d0bca993ff279f1
MoisesSantosC/cursoPythonDSA
/Cap02/Projeto/calculadora.py
952
4.34375
4
# Cabeçalho print(f'{19*"*"} Python Calculator {19*"*"}') print('\nSelecione o número de opção desejada:\n') print('1 - Soma\n2 - Subtração\n3 - Multiplicação\n4 - Divisão') # Variáveis de entradas do usuário op = input('\nDigite a sua opção (1/2/3/4): ') num1 = int(input('\nDigite o primeiro número: ')) num2 = int(input('\nDigite o segundo número: ')) # Expressões Lambdas soma = lambda num1, num2: num1 + num2 subtracao = lambda num1, num2: num1 - num2 multiplicacao = lambda num1, num2: num1 * num2 divisao = lambda num1, num2: num1 / num2 # Condicionais if op == '1': print(f'\nResultado: {num1} + {num2} = {soma(num1, num2)}') elif op == '2': print(f'\nResultado:{num1} - {num2} = {subtracao(num1, num2)}') elif op == '3': print(f'\nResultado:{num1} * {num2} = {multiplicacao(num1, num2)}') elif op == '4': print(f'\nResultado:{num1} / {num2} = {divisao(num1, num2)}') else: print('\nOpção Inválida!')
fae611e30af9637784648551481042cbae120235
eduardogomezvidela/Summer-Intro
/4 Turtles/Exercises/13.py
525
4.46875
4
#A sprite is a simple spider shaped thing with n legs coming out from a center point. The angle between each leg is 360 / n degrees. #Write a program to draw a sprite where the number of legs is provided by the user. import turtle screen=turtle.Screen() screen.bgcolor("black") alex=turtle.Turtle() alex.color("white") alex.pensize(15) alex.dot() alex.pensize(2) legs=input("How many legs?") legs=int(legs) for i in range(legs): alex.forward(100) alex.forward(-100) alex.right(360/legs) screen.exitonclick()
acbeb43bb40d31fa2440b0402f3582f9dcd40d15
captainsafia/advent-of-code-2018
/day-1/solution.py
839
3.515625
4
# Iteration 1 with open("frequencies.txt") as frequencies: result = 0 numbers = frequencies.read().splitlines() for number in numbers: if number.startswith("-"): number_as_int = int(number[1:]) result -= number_as_int elif number.startswith("+"): number_as_int = int(number[1:]) result += number_as_int else: raise Exception("{} is not in the valid format.".format(number)) print(result) # Iteration 2 with open("frequencies.txt") as frequencies: result = 0 numbers = frequencies.read().splitlines() for number in numbers: result += int(number) print(result) # Iteration 3 with open("frequencies.txt") as frequencies: result = sum([int(number) for number in frequencies.read().splitlines()]) print(result)
2888747acd6b8a883e31b72ad4ce7b0b993f4eb4
cmcfaul/teaching
/quadratic_cancellation_errors.py
1,063
4.21875
4
#!/usr/bin/python """ The Quadratic Equation ax^2 + bx + c = has two solutions. the solutiosn can be written as either: x1,2 = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} x'1,2 = \frac{-2c}{-b \pm \sqrt{b^2 - 4ac}} """ VERSION = '$Id: $' from cmath import sqrt def quadratic_traditional(a,b,c): """ Provides the two solutions in the normal form, x1,2 = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} Inputs: a, b, and c are reals; they are the coefficients of the equation. Outputs: x1 and x2 are the two solutions. They are complex numbers. """ x1 = (-b + sqrt(b**2 - 4*a*c))/(2*a) x2 = (-b - sqrt(b**2 - 4*a*c))/(2*a) return x1, x2 def quadratic_inverted(a,b,c): """ Provides the two solutions in the inverted form, x1,2 = \frac{-2c}{-b \pm \sqrt{b^2 - 4ac}} Inputs: a, b, and c are reals; they are the coefficients of the equation. Outputs: x1 and x2 are the two solutions. They are complex numbers. """ x1 = (-2*c)/(-b + sqrt(b**2 - 4*a*c)) x2 = (-2*c)/(-b - sqrt(b**2 - 4*a*c)) return x1, x2
b3144c6e663e4a19bd039206323310edbb7ba216
mario-sanz/Connect4-AI
/connect4-AI.py
12,492
3.640625
4
import numpy as np import pygame import sys import math import random ROW_COUNT = 6 COLUMN_COUNT = 7 BLUE = (0,0,255) # blue color for the screen BLACK = (0,0,0) # black color for the screen RED = (255,0,0) # red color for the tiles of player 1 YELLOW = (255,255,0) # yellow color for the tiles of player 2 PLAYER = 0 AI = 1 EMPTY = 0 PLAYER_PIECE = 1 AI_PIECE = 2 WINDOW_LENGTH = 4 def create_board(): board = np.zeros((ROW_COUNT,COLUMN_COUNT)) # create a 6x7 matrix full of 0's return board; def drop_piece(board, row, col, piece): board[row][col] = piece def is_valid_location(board, col): return board[ROW_COUNT-1][col] == 0 # is the column empty? def get_next_open_row(board, col): for r in range(ROW_COUNT): if board[r][col] == 0: return r # the function returns the first row that is empty def print_board(board): print(np.flip(board, 0)) # flips the board from axix 0 def winning_move(board, piece): # Check HORIZONTAL possibilities for c in range(COLUMN_COUNT-3): for r in range(ROW_COUNT): if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece: return True # Check VERTICAL possibilities for c in range(COLUMN_COUNT): for r in range(ROW_COUNT-3): if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece: return True # Check DIAGONALS WITH POSITIVE SLOPE possibilities for c in range(COLUMN_COUNT-3): for r in range(ROW_COUNT-3): if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece: return True # Check DIAGONALS WITH NEGATIVE SLOPE possibilities for c in range(COLUMN_COUNT-3): for r in range(3, ROW_COUNT): if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece: return True def evaluate_window(window, piece): score = 0 opp_piece = PLAYER_PIECE if piece == PLAYER_PIECE: opp_piece == AI_PIECE if window.count(piece) == 4: score += 100 elif window.count(piece) == 3 and window.count(EMPTY) == 1: score += 5 elif window.count(piece) == 2 and window.count(EMPTY) == 2: score += 2 if window.count(opp_piece) == 3 and window.count(EMPTY) == 1: score -= 4 # it counts more that we have 3 in a row to win that that the opponent has 3 in a row return score def score_position(board, piece): score = 0 # CENTER SCORE center_array = [int(i) for i in list(board[:, COLUMN_COUNT//2])] center_count = center_array.count(piece) score += center_count * 3 # HORIZONTAL SCORE for r in range(ROW_COUNT): row_array = [int(i) for i in list(board[r,:])] # store row t into an array for c in range(COLUMN_COUNT-3): window = row_array[c:c+WINDOW_LENGTH] score += evaluate_window(window, piece) # VERTICAL SCORE for c in range(COLUMN_COUNT): col_array = [int(i) for i in list(board[:,c])] # store column c into an array for r in range(ROW_COUNT-3): window = col_array[r:r+WINDOW_LENGTH] score += evaluate_window(window, piece) # DIAGONALS WITH POSITIVE SLOPE SCORE for r in range(ROW_COUNT-3): for c in range(COLUMN_COUNT-3): window = [board[r+i][c+i] for i in range(WINDOW_LENGTH)] score += evaluate_window(window, piece) # DIAGONALS WITH NEGATIVE SLOPE SCORE for r in range(ROW_COUNT-3): for c in range(COLUMN_COUNT-3): window = [board[r+3-i][c+i] for i in range(WINDOW_LENGTH)] score += evaluate_window(window, piece) return score def is_terminal_node(board): return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_valid_locations(board)) == 0 # returns True if the player wins, if the AI wins, or if there are no more positions in the board """ THIS IS THE ORIGINAL MINIMAX VERSION, BELLOW THIS FUNCITION IS "ALPHA-BETA PRUNING", THAT IS AN IMPROVED VERSION OF MINIMAX WHICH ELIMINATES BRANCHES THAT ARE NOT WORKING SO THAT THE ALGORITHM IS MORE EFFICIENT def minimax(board, depth, maximizingPlayer): valid_locations = get_valid_locations(board) is_terminal = is_terminal_node(board) if depth == 0 or is_terminal: if is_terminal: if winning_move(board, AI_PIECE): return (None, 100000000) elif winning_move(board, PLAYER_PIECE): return (None, -100000000) else: # game over, no more valid movements return (None, 0) else: # depth = 0 return (None, score_position(board, AI_PIECE)) if maximizingPlayer: value = -math.inf column = random.choice(valid_locations) for col in valid_locations: row = get_next_open_row(board, col) b_copy = board.copy() drop_piece(b_copy, row, col, AI_PIECE) new_score = minimax(b_copy, depth-1, False)[1] if new_score > value: value = new_score column = col return column, value else: # minimizing player value = math.inf column = random.choice(valid_locations) for col in valid_locations: row = get_next_open_row(board, col) b_copy = board.copy() drop_piece(b_copy, row, col, PLAYER_PIECE) new_score = minimax(b_copy, depth-1, True)[1] # change to maximizing player if new_score < value: value = new_score column = col return column, value """ def minimax(board, depth, alpha, beta, maximizingPlayer): # ALPHA-BETA PRUNING valid_locations = get_valid_locations(board) is_terminal = is_terminal_node(board) if depth == 0 or is_terminal: if is_terminal: if winning_move(board, AI_PIECE): return (None, 100000000000000) elif winning_move(board, PLAYER_PIECE): return (None, -10000000000000) else: # game over, no more valid movements return (None, 0) else: # depth = 0 return (None, score_position(board, AI_PIECE)) if maximizingPlayer: value = -math.inf column = random.choice(valid_locations) for col in valid_locations: row = get_next_open_row(board, col) b_copy = board.copy() drop_piece(b_copy, row, col, AI_PIECE) new_score = minimax(b_copy, depth-1, alpha, beta, False)[1] if new_score > value: value = new_score column = col alpha = max(alpha, value) if alpha >= beta: break return column, value else: # minimizing player value = math.inf column = random.choice(valid_locations) for col in valid_locations: row = get_next_open_row(board, col) b_copy = board.copy() drop_piece(b_copy, row, col, PLAYER_PIECE) new_score = minimax(b_copy, depth-1, alpha, beta, True)[1] # changes to maximizing player if new_score < value: value = new_score column = col beta = min(beta, value) if alpha >= beta: break return column, value def get_valid_locations(board): valid_locations = [] for col in range(COLUMN_COUNT): if is_valid_location(board, col): valid_locations.append(col) return valid_locations def pick_best_move(board, piece): valid_locations = get_valid_locations(board) best_score = -10000 best_col = random.choice(valid_locations) for col in valid_locations: row = get_next_open_row(board, col) temp_board = board.copy() drop_piece(temp_board, row, col, piece) score = score_position(temp_board, piece) if score > best_score: best_score = score best_col = col return best_col def draw_board(board): # draw of the board and empty spaces for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): pygame.draw.rect(screen, BLUE, (c*SQUARESIZE, r*SQUARESIZE+SQUARESIZE, SQUARESIZE, SQUARESIZE)) pygame.draw.circle(screen, BLACK, (int(c*SQUARESIZE+SQUARESIZE/2), int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/2)), RADIUS) for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): if board[r][c] == PLAYER_PIECE: # draw tiles 1 (red) pygame.draw.circle(screen, RED, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS) elif board[r][c] == AI_PIECE: # draw tiles 2 (yellow) pygame.draw.circle(screen, YELLOW, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS) pygame.display.update() board = create_board() print_board(board) game_over = False # GRAPHICAL INTERFACE pygame.init() SQUARESIZE = 100 width = COLUMN_COUNT * SQUARESIZE height = (ROW_COUNT+1) * SQUARESIZE size = (width, height) RADIUS = int(SQUARESIZE/2 - 5) screen = pygame.display.set_mode(size) # creates the window draw_board(board) pygame.display.update() myfont = pygame.font.SysFont("monospace", 75) turn = random.randint(PLAYER, AI) # player or IA start at random while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # draw the tile moving in the upper part of the board before falling if event.type == pygame.MOUSEMOTION: pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE)) # constantly erase the previous moving tile posx = event.pos[0] if turn == PLAYER: # player 1 pygame.draw.circle(screen, RED, (posx, int(SQUARESIZE/2)), RADIUS) pygame.display.update() if event.type == pygame.MOUSEBUTTONDOWN: pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE)) # erase the previous moving tile #print(event.pos) # this tells us on the console the coordinates of the window on which we press # Input of FIRST player if turn == PLAYER: posx = event.pos[0] # pos[0] is the x axis of the coordinates col = int(math.floor(posx/SQUARESIZE)) # this gives us the column number on which we press if is_valid_location(board, col): row = get_next_open_row(board,col) drop_piece(board, row, col, PLAYER_PIECE) # tiles of player 1 are always 1 if winning_move(board, PLAYER_PIECE): label = myfont.render("JUGADOR 1 GANA", 1, RED) screen.blit(label, (40,10)) game_over = True # TURN ALTERNANCE turn += 1 turn = turn % 2 # turn is going to altern between 0 and 1 # BOARD print_board(board) draw_board(board) # Input of SECOND player if turn == AI and not game_over: # col = random.randint(0, COLUMN_COUNT-1) # col = pick_best_move(board, AI_PIECE) col, minimax_score = minimax(board, 5, -math.inf, math.inf, True) if is_valid_location(board, col): #pygame.time.wait(500) row = get_next_open_row(board,col) drop_piece(board, row, col, AI_PIECE) # tiles of player 2 are always 2 if winning_move(board, AI_PIECE): label = myfont.render("ORDENADOR GANA", 1, YELLOW) screen.blit(label, (40,10)) game_over = True # BOARD print_board(board) draw_board(board) # TURN ALTERNANCE turn += 1 turn = turn % 2 # turn is going to altern between 0 and 1 if game_over: pygame.time.wait(3000) # wait 3 seconds before closing the window
022f4c829f0cb234d522d70d2ef561f710320d49
TNY-NeXT/python-
/线程的简单示例2.py
523
3.6875
4
import time import threading begin = time.time() def foo(n): print('foo %s' % n) time.sleep(1) print('end the foo') return def bar(n): print('bar %s' % n) time.sleep(3) print('end the bar') return #串行执行花费4秒多 # foo(2) # bar(3) #并行执行3秒多 t1 = threading.Thread(target=foo, args=(2,)) t2 = threading.Thread(target=bar, args=(2,)) t1.start() t2.start() print('...the main function....') t1.join() t2.join() end = time.time() print(end-begin)
a592c5b797a7606e9e60a888c7bcaae9a82c8a02
Aasthaengg/IBMdataset
/Python_codes/p02819/s078970240.py
328
3.71875
4
import math X = int(input()) def is_prime(x): a = int(math.sqrt(X)) + 1#ある数が素数かどうかはO(√A)で判定できる for i in range(2,a): if x % i == 0: return False return True#xは素数 for j in range(X,10**5+4): if is_prime(j): ans = j break print(ans)
34091697afe304a8dad01e2899f1ff82d11cb726
Arjahck/Cipher
/programme_DE.py
8,266
3.5
4
from math import sqrt ''' linear cryptography ''' def diviseurs(n): D,racine=[1],int(sqrt(n)) fin=racine+1 for d in range(2,fin): if n%d==0 : D.extend([d,n//d]) D=sorted(set(D)) return D def phi(n): D=diviseurs(n) Phi,somme=[1],"1" for i,div in enumerate(D): if div!=1: D_i,q=[d for d in D if div%d==0 and d<div],0 for d in D_i: q+=Phi[D.index(d)] p=div-q Phi.append(p) somme+="+"+str(p) return n-sum(Phi) def bezout(n1, n2): if (n1 < n2): n1 = n1 + n2 n2 = n1 - n2 n1 = n1 - n2 tableau = [] tableau.append([n1, 1, 0]) tableau.append([n2, 0, 1]) quotient = int(tableau[0][0] / tableau[1][0]) reste = tableau[0][0] % tableau[1][0] tableau.append([reste, tableau[0][1] - (quotient * tableau[1][1]) , tableau[0][2] - (quotient * tableau[1][2])]) while (tableau[2][0] > 1): tableau[0] = tableau[1] tableau[1] = tableau[2] quotient = int(tableau[0][0] / tableau[1][0]) reste = tableau[0][0] % tableau[1][0] tableau[2] = [reste, tableau[0][1] - (quotient * tableau[1][1]) , tableau[0][2] - (quotient * tableau[1][2])] if(tableau[2][0] == 1): dico = {"pgcd" : 1, str(n1) : tableau[2][1], str(n2) : tableau[2][2]} else: dico = {"pgcd" : tableau[1][0], str(n1) : tableau[1][1], str(n2) : tableau[1][2]} return dico def affiche_tab(tab): for x in tab: '''for y in x: print(y)''' print(str(x)) def RestesChinois(nb, resultat, modulo): bez = bezout(nb, modulo) pgcd = bez["pgcd"] if (pgcd == 1): inverse = bez [str(nb)] x = (inverse*resultat)%modulo print(x) elif (resultat%nb == 0): i = 0 while (i < 5): x = ((resultat + modulo*i)/nb) print(x) i = i +1 else: print("Pas de solution") def expo_modu(nmbr, pui, mod): return (nmbr**pui)%mod def determinant(x): return (x[0][0] * x[1][1]) - (x[0][1] * x[1][0]) def multipli_matr(a, x): result = [] result.append( (a[0][0] * x[0]) + (a[0][1] * x[1]) ) result.append( (a[1][0] * x[0]) + (a[1][1] * x[1]) ) return result def decomposition_nbpremiers(n): nbPremiers=[] i=2 while n>1: while n%i==0: nbPremiers.append(i) n=n/i i=i+1 return nbPremiers def theoremeRSA_verif(nbPremiers): prems = nbPremiers[0] i = 1 for i in nbPremiers: if i == prems: boolean = 0 else: prems = i boolean = 1 if (boolean == 0): return False else: return True class crypto_affine(object): """docstring for crypto_affine""" def __init__(self): super(crypto_affine, self).__init__() self.a = 0 self.b = 0 self.modulo = 0 def chiffr(self, x): return((self.a * x + self.b)%self.modulo) def dechiffr(self, y): inv_a = bezout(self.a, self.modulo)[str(self.a)] return ( ( (inv_a * y) - (inv_a * self.b) ) % self.modulo) def is_dechiffr(self): if (bezout(self.a, self.modulo)["pgcd"] == 1): return True else: return False class crypto_affine_dia(object): """docstring for crypto_affine""" def __init__(self): self.a = 0 self.b = 0 self.modulo = 0 def is_bij(self): if (bezout(determinant(self.a)%self.modulo, self.modulo)["pgcd"] == 1): return True else: return False def chiffr(self, x): mult = multipli_matr(self.a, x) mult[0] = (mult[0] + self.b[0]) % self.modulo mult[1] = (mult[1] + self.b[1]) % self.modulo return mult def inv_a(self): det = determinant(self.a)%self.modulo inv_det = bezout(det, self.modulo)[str(det)] inverse_a = self.a temp = self.a[0][0] inverse_a[0][0] = (inv_det * self.a[1][1]) % self.modulo inverse_a[0][1] = (inv_det * (self.a[0][1]*-1)) % self.modulo inverse_a[1][0] = (inv_det * (self.a[1][0]*-1)) % self.modulo inverse_a[1][1] = (inv_det * temp) % self.modulo return inverse_a def dechiffr(self, y): inverse_a = self.inv_a() x = multipli_matr(inverse_a, y) y = multipli_matr(inverse_a, self.b) x[0] = (x[0] - y[0])%self.modulo x[1] = (x[1] - y[1])%self.modulo return x class crypto_rsa(object): """docstring for crypto_rsa""" def __init__(self): self.nA = 0 self.eA = 0 self.dA = 0 self.sA = 0 self.nB = 0 self.eB = 0 self.dB = 0 self.sB = 0 def completeA(self): phin= phi(self.nA) x=bezout(self.dA,phin) if(x[str(self.dA)])<0: x[str(self.dA)]=x[str(self.dA)]+phi(self.nA) return x[str(self.dA)] def completdA(self): phin= phi(self.nA) x=bezout(self.eA,phin) if(x[str(self.eA)])<0: x[str(self.eA)]=x[str(self.eA)]+phi(self.nA) return x[str(self.eA)] def completeB(self): phin= phi(self.nB) x=bezout(self.dB,phin) if(x[str(self.dB)])<0: x[str(self.dB)]=x[str(self.dB)]+phi(self.nB) return x[str(self.dB)] def completdB(self): phin= phi(self.nB) x=bezout(self.eB,phin) if(x[str(self.eB)])<0: x[str(self.eB)]=x[str(self.eB)]+phi(self.nB) return x[str(self.eB)] """def find_d(self,who): if (who == "A"): phin= phi(self.nA) x=bezout(self.eA,phin) if(x[str(self.eA)])<0: x[str(self.eA)]=x[str(self.eA)]+phi(self.nA) print(x[str(self.eA)]) else: phin= phi(self.nB) x=bezout(self.eB,phin) if(x[str(self.eB)])<0: x[str(self.eB)]=x[str(self.eB)]+phi(self.nB) print(x[str(self.eB)]) def find_e(self,who): if (who == "A"): phin= phi(self.nA) x=bezout(self.dA,phin) if(x[str(self.dA)])<0: x[str(self.dA)]=x[str(self.dA)]+phi(self.nA) print(x[str(self.dA)]) else: phin= phi(self.nB) x=bezout(self.dB,phin) if(x[str(self.dB)])<0: x[str(self.dB)]=x[str(self.dB)]+phi(self.nB) print(x[str(self.dB)])""" def chiffr(self, x, who): if (who == "A"): return (x**self.eB)%self.nB elif (who == "B"): return (x**self.eA)%self.nA def dechiffr(self, y, who): if (who == "A"): return (y**self.dA)%self.nA elif (who == "B"): return (y**self.dB)%self.nB def signature(self, who): if (who == "A"): if (self.nA <= self.nB): sign = (((self.sA ** self.dA)%self.nA) ** self.eB)%self.nB else: sign = (((self.sA ** self.eB)%self.nB) ** self.dA)%self.nA elif (who == "B"): if (self.nA <= self.nB): sign = (((self.sB ** self.eA)%self.nA) ** self.dB)%self.nB else: sign = (((self.sB ** self.dB)%self.nB) ** self.eA)%self.nA return sign def signature_verif(self, sign, who): if (who == "A"): if (self.nA > self.nB): result = (((sign ** self.dA)%self.nA) ** self.eB)%self.nB else: result = (((sign ** self.eB)%self.nB) ** self.dA)%self.nA elif (who == "B"): if (self.nA > self.nB): result = (((sign ** self.eA)%self.nA) ** self.dB)%self.nB else: result = (((sign ** self.dB)%self.nB) ** self.eA)%self.nA return result class crypto_elgamal(object): """docstring for crypto_elgamal""" def __init__(self): self.g = 0 self.modulo = 0 self.eA = 0 self.dA = 0 self.eB = 0 self.dB = 0 def chiffr(self, x, k, who): r = (self.g ** k)%self.modulo if (who == "A"): y = (x * (self.eB**k))%self.modulo elif (who == "B"): y = (x * (self.eA**k))%self.modulo return {"r": r, "y" : y} def dechiffr(self, r, y, who): if (who == "A"): temp = r**self.dA x = y * bezout(temp, self.modulo)[str(temp)] elif (who == "B"): temp = r**self.dB x = y * bezout(temp, self.modulo)[str(temp)] return x%self.modulo def find_dA(self): x = 1 while ( ((self.g**x)%self.modulo) != self.eA): x += 1 return x def find_dB(self): x = 1 while ( ((self.g**x)%self.modulo) != self.eB): x += 1 return x def find_eA(self): return ( (self.g**self.dA)%self.modulo ) def find_eB(self): return ( (self.g**self.dB)%self.modulo ) pass """crypt = crypto_elgamal() crypt.g = 2 crypt.modulo = 19 crypt.eA = 14 crypt.dA = 7 crypt.eB = 17 crypt.dB = 1 print(crypt.dechiffr(8, 10, "A"))""" crypt = crypto_rsa() crypt.nA = 77 crypt.eA = 29 crypt.dA = 29 crypt.sA = 8 crypt.nB = 65 crypt.eB = 35 crypt.dB = 11 crypt.sB = 12 print(crypt.signature("A"))
37633f85fe0abbdd5b60b3d9110be497b103b868
Heisenberg66/ORAL1
/10 Exemples illustrant l’utilisation de différentes méthodes de résolution de problèmes algorithmiques/euclide.py
219
3.53125
4
def euclide_iter(a,b): while a%b!=0: a,b=b,a%b return b def euclide_rec(a,b): if a%b!=0: return euclide_rec(b,a%b) return b print(euclide_iter(96,76)) print(euclide_rec(96,76))
7f80f286089a6ee8e03577172a7364b258baf86c
mikephys8/The_Fundamentals_pythonBasic
/ex2-1.py
857
4.03125
4
__author__ = 'Administrator' def get_capital(country): countries = {'Canada': 'Ottawa', 'Greece': 'Athens', 'France': 'Paris', 'Germany': 'Berlin', 'Japan': 'Tokyo', 'Spain': 'Madrid', 'Norway': 'Oslo'} for item in countries: if country == item: return countries[item] print(get_capital('Spain')) print('------------------//----------------') def longer(country1, country2): if len(country1) > len(country2): return country1 elif len(country1) < len(country2): return country2 else: print('They are equal') print(longer('hello man', 'hello man')) print('------------------//----------------') print('The longer string comparing the ' + get_capital('Japan') + ' and ' + get_capital('Greece')+ ' is ' + longer(get_capital('Japan'), get_capital('Greece')))
6de89fef9facbd1163a8bad5b6ac107cd9b8f196
Yta-ux/python_algorithms
/basic_algorithms/aumento_mútiplos.py
281
3.703125
4
s1=float(input('Digite seu salário:')) maior= s1 +(s1 * (10/100)) menor= s1+(s1 * (15/100)) if(s1<= 1.250): print('Seu salário era de R${:.3f}, passou a ser R${:.3}'.format(s1,menor)) else: print('Seu salário era de R${:.3f}, passou a ser R${:.3f}'.format(s1,maior))
2fa39686be88bc5184bcaefc397e6538c4c4059b
Prateek478/ds_algo_problem_solving_python-
/15_smaller_difference_pair.py
1,639
4.09375
4
''' Smallest Difference pair of values between two unsorted Arrays Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference. Examples : Input : A[] = {l, 3, 15, 11, 2} B[] = {23, 127, 235, 19, 8} Output : 3 That is, the pair (11, 8) Input : A[] = {l0, 5, 40} B[] = {50, 90, 80} Output : 10 That is, the pair (40, 50) ''' def smallest_diff(A, B): diff = float("inf") A.sort() B.sort() a=b=0 while (a < len(A) and b < len(B)): if abs(A[a] - B[b]) < diff: diff = abs(A[a] - B[b]) # Move Smaller Value if A[a] < B[b]: a += 1 else: b += 1 # return final sma result return diff def smallest_diff(A, B): diff = float("inf") A.sort() B.sort() a=b=0 while (a < len(A) and b < len(B)): if abs(A[a] - B[b]) < diff: diff = abs(A[a] - B[b]) # Move Smaller Value if A[a] < B[b]: a += 1 else: b += 1 # return final sma result return diff # ord(n2) complexity def smallest_diff_1(A, B): A.sort() B.sort() diff = {} for i in range(len(A)): for j in range(len(B)): if abs(A[i]-B[j]) not in diff: diff[abs(A[i]-B[j])] = ((A[i],B[j])) # return final sma result return min(diff.keys()) #return diff if __name__ == "__main__": A = [1, 3, 15, 11, 2] B = [23, 127, 235, 19, 8] print(smallest_diff(A, B)) print(smallest_diff_1(A, B))
bb8c57cbb13e79dca311f2f43044a5dd0e0cf6c0
vcaptainv/Painting
/turtle_interpreter.py
3,211
4.125
4
#Yusheng Hu #turtle interpreter #VERSION 2 import turtle import random class TurtleInterpreter: def __init__(self, dx = 800, dy = 800): turtle.setup(width=dx, height=dy) turtle.tracer(False) def drawString(self, dstring, distance, angle): #create two lists which can include information of turtle position and turtle color stack =[] color=[] # for each character in the dstirng for c in str(dstring): if c == 'F': # python would go forward turtle.forward(distance) elif c == '+': #turtle would turn left turtle.left(angle) elif c == '-': #turtle would turn right turtle.right(angle) elif c == '[': #turtle would record the position and heading angle stack.append(turtle.position()) stack.append(turtle.heading()) elif c == ']': #turtle would return to the position and heading angle recorded before turtle.up() turtle.setheading(stack.pop()) turtle.setposition(stack.pop()) turtle.down() elif c == 'L': #turtle would draw a green leave h = turtle.heading() p = turtle.position() turtle.color('limegreen') turtle.fill(True) turtle.circle(distance/3, 180) turtle.fill(False) turtle.color('black') turtle.up() turtle.goto(p) turtle.down() turtle.setheading(h) elif c == 'o': # turtle would draw a berry turtle.color(random.random(), random.random(), random.random()) turtle.fill(True) turtle.circle(distance/5, 360) turtle.fill(False) turtle.color("black") elif c=='<': #turtle would record the color value color.append(turtle.color()[0]) elif c=='>': #turtle would return to the color value recorded before turtle.color(color.pop()) elif c=='g': #turtle would turn to green color turtle.color(0.15,0.5,0.2) elif c=='y': #turtle would turn to yellow color turtle.color(0.8,0.8,0.3) elif c=='r': #turtle would turn to red color turtle.color(0.7,0.2,0.3) elif c == 'b': #turtle would change color to brown turtle.color('saddlebrown') elif c == '%': #turtle would change color to chocolate turtle.color('chocolate') elif c == '!': #turtle would change color to black turtle.color('black') elif c == 'w': #turtle would change the width to 2(make the line seems thicker) turtle.width(2) elif c == 'c': #turtle would return to default value of width turtle.width(1) turtle.update() def hold(self): # have the turtle listen for events turtle.listen() # hide the turtle and update the screen turtle.ht() turtle.update() # have the turtle listen for 'q' turtle.onkey( turtle.bye, 'q' ) # have the turtle listen for a click turtle.onscreenclick( lambda x,y: turtle.bye() ) # start the main loop until an event happens, then exit turtle.mainloop() exit() def place(self, xpos,ypos,angle=None): turtle.up() turtle.goto(xpos,ypos) if angle !=None: turtle.setheading(angle) turtle.down() def orient(self,angle): turtle.setheading(angle) def goto(self,xpos,ypos): turtle.up() turtle.goto(xpos,ypos) turtle.down() def color(self,c): turtle.color(c) def width(self,w): turtle.width(w)
c3faeb46497f6b620c545302a636b958516f3801
SushantKrMishra/Basic-School-administration-Tool
/FirstProject.py
1,542
3.984375
4
#project1: Basic School administrationTool import csv def write_into_csv(info_list): with open('student_info.csv' , 'a', newline= '') as csv_file: writer = csv.writer(csv_file) if csv_file.tell() == 0: writer.writerow(["Name","Age","Contact Number","Email Id"]) writer.writerow(info_list) if __name__ == '__main__': condition = True student_num = 1 while condition: student_info = input("Enter some Student Information for Student {} in the following format(Name,Age,Contact No,Email Id) : ".format(student_num)) Student_info_list = student_info.split(',') print("\nThe Entered information is - \nName: {}\nAge: {}\nContact Number: {}\nEmail Id: {}".format(Student_info_list[0],Student_info_list[1],Student_info_list[2],Student_info_list[3])) choice_check = input("Is the Entered information is Correct?") choice_check=choice_check.casefold() if choice_check == "yes": write_into_csv(Student_info_list) student_num = student_num + 1 condition_check = input("Enter Yes or No if you want to Enter a Information of a Student: ") condition_check=condition_check.casefold() if condition_check == "no": condition = False elif condition_check == "yes": condition = True elif choice_check == "no": print("Please re-enter the Information")
37efaebfc1da15f21a019b77254c84169d515470
jwasher/fakepandas
/fakepandas.py
6,532
3.984375
4
import operator def num_rows(d): ''' Get number of data rows. Raise ValueError if not all columns have the same number of rows. ''' if len(d) == 0: return 0 def gen_columns(): for v in d.values(): yield v columns = gen_columns() length = len(next(columns)) for index, column in enumerate(columns, 1): if len(column) != length: raise ValueError(index) return length # The operator module does not provide functions for the logical "and" # and "or" operators, only the bitwise "&" and "|". So we make our own # functions for the logicals. def logical_and(a, b): return a and b def logical_or(a, b): return a or b class GeneralComparison: ''' A generic representation of a comparison. Used when comparing two columns to each other (i.e., two LabelReferences). ''' def __init__(self, lookup, value, operate): self.lookup = lookup self.value = value self.operate = operate def apply(self, data, row_number): other_value = self.lookup(data, row_number) return self.operate(other_value, self.value) # __and__ is actually bitwise and ("a & b"), not logical and ("a # and b"). Unfortunately, no current version of Python provides a # magic method for logical and. Thus, we have little choice but # to fake it using bitwise and. def __and__(self, other): return Conjunction(self, other, logical_and) # The situation with __or__ is exactly analogous. def __or__(self, other): return Conjunction(self, other, logical_or) class Comparison(GeneralComparison): ''' Simplified form of comparison. Used when comparing a column (LabelReference) to a constant value. ''' def __init__(self, label: str, value, operate): def lookup(data, row_number): return data[label][row_number] super().__init__(lookup, value, operate) class Conjunction: ''' Represents a logical "and" or "or" relationship between two expressions. combine will generally be set to either logical_and or logical_or. ''' def __init__(self, left: GeneralComparison, right: GeneralComparison, combine: 'func'): self.left = left self.right = right self.combine = combine def apply(self, data: dict, row_number: int): return self.combine(self.left.apply(data, row_number), self.right.apply(data, row_number)) class LabelReference: ''' Represents a labeled column in a Dataset. ''' def __init__(self, label: str): self.label = label def compare(self, value, operate): return Comparison(self.label, value, operate) def __lt__(self, value): return self.compare(value, operator.lt) def __gt__(self, value): return self.compare(value, operator.gt) def __ge__(self, value): return self.compare(value, operator.ge) def __le__(self, value): return self.compare(value, operator.le) def __eq__(self, value): return self.compare(value, operator.eq) def __add__(self, other): return PairedLabelReference(self, other, operator.add) def __sub__(self, other): return PairedLabelReference(self, other, operator.sub) def __mod__(self, other): return PairedLabelReference(self, other, operator.mod) class PairedLabelReference(LabelReference): ''' Represents two separate columns in some comparision relation to each other. ''' def __init__(self, first: LabelReference, second: LabelReference, operate: 'func'): self.first = first self.second = second self.operate = operate def lookup(self, data: dict, row_number: int): first_value = data[self.first.label][row_number] if isinstance(self.second, LabelReference): second_value = data[self.second.label][row_number] else: second_value = self.second return self.operate(first_value, second_value) def compare(self, value, operate: 'func'): return GeneralComparison(self.lookup, value, operate) class Dataset: ''' Core class representing a set of data. Filter rows with obj[expression]. ''' def __init__(self, data: dict): self.data = data self.length = num_rows(data) self.labels = sorted(data.keys()) def __getattr__(self, label: str): if label not in self.data: raise AttributeError("'{}' object has no attribute '{}'".format(self.__class__.__name__, label)) return LabelReference(label) def __getitem__(self, comparison: GeneralComparison): filtered_data = dict((label, []) for label in self.labels) def append_row(row_number): for label in self.labels: filtered_data[label].append(self.data[label][row_number]) for row_number in range(self.length): if comparison.apply(self.data, row_number): append_row(row_number) return Dataset(filtered_data) # presentation/rendering methods def __str__(self): def row(row_number): return '\t'.join([ str(self.data[label][row_number]) for label in self.labels]) header = '\t'.join(self.labels) + '\n' return header + '\n'.join([ row(row_number) for row_number in range(self.length)]) def pprint(self): print(self.pprint_str()) def pprint_str(self): # helpers def width_of(label): width = max(len(str(value)) for value in self.data[label]) width = max([width, len(str(label))]) return width def format(value, label): return '{value:>{width}}'.format(value=str(value), width=field_widths[label]) # precompute field_widths = {label: width_of(label) for label in self.labels} table_width = sum(width for width in field_widths.values()) + 3 * (len(self.labels)-1) + 4 HR = '-' * table_width # render lines labels_line = '| ' + ' | '.join(format(label, label) for label in self.labels) + ' |' lines = [ HR, labels_line, HR, ] for row_number in range(self.length): formatted_values = (format(self.data[label][row_number], label) for label in self.labels) lines.append('| ' + ' | '.join(formatted_values) + ' |') lines.append(HR) return '\n'.join(lines)
d17abcd718bf3f8d3bdb48edfaadd38dc3b80cf2
Joedmo15/Continental
/main.py
5,778
3.546875
4
import random from random import shuffle def straight_check(list, run_count=1): list.sort() if len(list) == 1: if run_count == 4: return True else: return False elif run_count == 4: return True elif list[0] + 1 == list[1]: return straight_check(list[1:], run_count + 1) else: return straight_check(list[1:], 1) def countz(list, value): x = 0 for yeet in list: if yeet == value: x += 1 return int(x) class player: def __init__(self): self.hand = [] self.ask_name = input("What is your name?") self.name = self.ask_name def deal(self, core): random.shuffle(core.deck) x = 0 while x <= core.deal_numbers[core.round_num] - 1: card = core.deck[x] card = card[0] self.hand.append(card) x += 1 print("Your hand is:") print(self.hand) print("") def turn(self, core): random.shuffle(core.deck) print("The card showing is " + core.card_showing) choice = input("What would you like to do? (draw or pick)") if choice == "draw": self.hand.append(core.deck[0][0]) print("You picked up "+str(core.deck[0])) else: self.hand.append(core.card_showing) print("You picked up "+core.card_showing) print(self.hand) print("") discard = input("What would you like to discard? (which number of card)") discard = self.hand[int(discard)-1] core.card_showing = discard self.hand.remove(discard) print("You discarded "+ str(discard)) print(self.hand) print("") random.shuffle(core.deck) def buy(self, core): if not core.card_showing == "''": buy = input("The card showing is " + core.card_showing + ". Would you like to buy it? (yes or no)") if buy == "yes": self.hand.append(core.card_showing) core.card_showing = "" self.hand.append(core.deck[0][0]) self.hand.append(core.deck[1][0]) print("You also picked up " + str(core.deck[0][0]) + " and " + str(core.deck[1][0])) print("") print("Your current hand is") print(self.hand) def winning_check(self, core): roundz = list(core.rounds[core.round_num]) card_values = [] check = [] for element in self.hand: element = element.split() value = element[0] if value == "Jack": value = 11 if value == "Queen": value = 12 if value == "King": value = 13 if value == "Ace": value = 14 value = int(value) card_values.append(value) card_values.sort() for value in roundz: if value == "3": for element in card_values: count = card_values.count(element) if count == 3: card_values.remove(element) check.append("yes") elif count > 3: difference = count - 3 card_values.remove(element) x = 0 while x < difference: card_values.append(element) x += 1 check.append("yes") else: check.append("no") if value == "4": check_duplicates = card_values[:] for element in check_duplicates: z = int(check_duplicates.count(element)) if z > 1: check_duplicates.remove(element) check_duplicates.append(element) check_duplicates.sort() run_check = straight_check(check_duplicates, 1) if run_check: check.append("yes") else: check.append("no") if check.count("yes") == 2: print("Yippee") core.win = True else: core.win = False class game: def __init__(self): self.values = ['2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace'] self.suites = ['Hearts', 'Clubs', 'Diamonds', 'Spades'] self.deck = [[v + ' of ' + s] for s in self.suites for v in self.values] #self.number = input("How many players?") self.rounds = ["33","34","44","333","334","344","444"] self.deal_numbers = [6,7,8,9,10,11,12] self.hand = [] self.round_num = 1 self.round = self.rounds[self.round_num] self.card_showing = "" self.win = False def main(): core = game() number = int(input("How many players?")) players = [] x = 0 while x < number: players.append(player()) x += 1 for element in players: element.deal(core) while not core.win: turn = 0 while turn <= number: players[turn].turn(core) players[turn].winning_check(core) next_player = turn + 1 if next_player > number: next_player = 0 players[next_player].buy(core) for thing in players: thing.buy(core) turn += 1 main()
93540707ca6bc8d6e2515228b90513490300b12c
cristobalgh/python
/dellibro/rolldie.py
713
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 17 15:07:08 2018 @author: cristobal.galleguill """ import random def rolldie(): return random.choice([1,2,3,4,5,6]) def rollcoin(): return random.choice([0,1]) def rollN(n, fun): result = '' for i in range(n): result = result + str(fun()) print(result) def flip(numFlips): heads = 0.0 for i in range(numFlips): if random.random() < 0.5: heads +=1 return heads/numFlips def flipsim(NumFlipsPerTrial, numTrials): fracHeads = [] for i in range(numTrials): fracHeads.append(flip(NumFlipsPerTrial)) mean = sum(fracHeads)/len(fracHeads) return mean
8aba9c68a5fb936fa275bcba14e16a775ac37cb7
DurgaMahesh31/Python
/source/datatypebasics.py
1,512
4.03125
4
""" This module is to practise data types""" # to comment out the code select the line of code and ctrl + / name = "Python" print(name) print(name[0]) print(name[-1]) a = 20 print(a) # 20 print(type(a)) # <class 'int' > b = a print(b) # 20 print(type(b)) # < class 'int' > print(id(a), id(b)) # 111 111 print(a is b) # True print("====== Changing the object for b ======") b = "python" print(a) # 20 print(b) # python print(type(b)) # < class 'str'> print(id(a), id(b)) # 111 222 print(a is b) # False # ================== Sequential data type ==================== # name = "python2example" print(name) # python2example print(name[1]) # y print(name[2]) # t print(name[1], name[-5]) # y, y print(name[4], name[-2]) # o, o print("emptyCharacter:%s" % name[6]) print("empty") print(name[7]) # ===================Immutable Modification and deletion data not supported ============= # print("deletion not supported" ) name[1] = 'e' del name[0] #del name print(name) # ======================= Mutable Modification and deletion data in Object ============ # list_of_accounts = [ "Mahesh", "Suresh", "Naresh" ] print(list_of_accounts[0]) list_of_accounts[0] = 23456 print(list_of_accounts[0]) del list_of_accounts[2] print(list_of_accounts) # ==================== Unordered data =============================== # score_data = {"Mahesh": 199, "Suresh": 99, "Naresh": 49} print(score_data) print(score_data["Mahesh"]) del score_data["Naresh"] print(score_data)
2d41ffaea069e6de022f6c4cc06b0fd9bb118db8
karockai/Yongorithm
/자료구조/스택큐/주식가격.py
561
3.578125
4
# https://programmers.co.kr/learn/courses/30/lessons/42584 prices = [1, 2, 3, 2, 3] def solution(prices): from collections import deque answer = deque([0]) time = 0 stack = [[prices[-1], 0]] for i in range(len(prices)-2, -1, -1): time += 1 while (stack and prices[i] <= stack[-1][0]): stack.pop() if (stack): answer.appendleft(time - stack[-1][1]) else: answer.appendleft(time) stack.append([prices[i],time]) return list(answer) print(solution(prices))
2877537b6df22debf3273d02f8534c90019de37e
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/1318.py
586
3.5
4
def fix_one_inversion(n): num_digits = len(n) for i in range(num_digits - 1): if (int(n[i]) > int(n[i + 1])): if (i == 0 and n[i] == '1'): return ['9'] * (num_digits - 1) n[i] = str(int(n[i]) - 1) return n[: i + 1] + ['9'] * (num_digits - i - 1) return n t = int(input()) for case in range(1, t + 1): n = list(input()) num_digits = len(n) for i in range(num_digits - 1): new_n = fix_one_inversion(n) if (''.join(new_n) == ''.join(n)): n = new_n[:] break n = new_n[:] print("Case #" + str(case) + ":", ''.join(n))
866f0e29e617f5ea8cd011fcbd351d96ec507270
dsiegler2000/Coeus
/src/evaluation.py
33,207
3.734375
4
""" All code related to evaluating a board state """ import json import logging import os from typing import Union, List, Optional, Tuple import chess import utils from movegeneration import SearchBoard, PieceList from utils import count_bin_ones logger = logging.getLogger(os.path.basename(__file__)) class BoardEvaluation: """ Basic data class to store board evaluations. A positive evaluation means `self.side_to_move` is ahead. """ def __init__(self, white_evaluation: float, black_evaluation: float, side_to_move: chess.Color, white_endgame: bool, black_endgame: bool, num_men: int): self.white_evaluation = white_evaluation self.black_evaluation = black_evaluation self.side_to_move = side_to_move self.white_endgame = white_endgame self.black_endgame = black_endgame self.num_men = num_men self.board_evaluation = self.black_evaluation - self.white_evaluation self.board_evaluation *= -1 if self.side_to_move == chess.WHITE else 1 # Mate information self.mate = False self.mate_in = -1 def set_mate(self, mate_in: int, mate_val: int = 1_000_000): """ Sets it so that this evaluation is for a checkmate position in `mate_in` moves. :param mate_in: Number of moves until mate. :param mate_val: Dummy value to use as the mate value. :return: None """ self.mate = True self.mate_in = mate_in self.board_evaluation = -mate_val + mate_in self.white_evaluation = None self.black_evaluation = None def __str__(self): to_move = "w" if self.side_to_move == chess.WHITE else "b" if self.mate: return f"mate in {self.mate_in: <3}, evaluation: {self.board_evaluation: <3}, {to_move} to move" return f"evaluation: {self.board_evaluation: <3} (white: {self.white_evaluation: <3}, " \ f"black: {self.black_evaluation: <3}, {to_move} to move)" class BoardHeatmap: """ Data class to store heatmap information on a chess board, including the white and black versions of the heatmap. Heatmap refers to an array of ints that gives a weighting to each square on the board for a given piece. """ def __init__(self, heatmap: Union[str, List[List[int]], List[int]], piece_type: chess.PieceType, color=chess.WHITE): """ Parses a board heatmap (such as a piece square table) in either string or array form. :param heatmap: The heatmap to parse. The heatmap must be either a 2D array of values or a string where the ranks are separated by newlines and the values separated by commas :param piece_type: The piece type that this map relates to :param color: The color that the input is assumed to be for ("w" for white, "b" for black) """ self.piece_type = piece_type if isinstance(heatmap, str): heatmap_list = [] for rank in heatmap.split("\n"): heatmap_list.append([int(v) for v in rank.split(",") if len(v) > 0]) heatmap = heatmap_list if isinstance(heatmap, list): if isinstance(heatmap[0], int): # "Flattened" heatmap_list = [] for i in range(0, 64, 8): heatmap_list.append(heatmap[i:i + 8]) heatmap = heatmap_list else: if len(heatmap) != 8 or sum(len(rank) for rank in heatmap) != 64: raise ValueError("the provided heatmap has an invalid format or size!") # Generate the horizontally flipped heatmap to have both white and black versions heatmap_flipped = [heatmap[len(heatmap) - i - 1] for i in range(len(heatmap))] # Note that this is actually flipped from what is expected because of how chess reports pieces, and also we # only need the "white" oriented version because pieces are always reported relative to white in the bitmask white_heatmap_2d = heatmap_flipped if color is chess.WHITE else heatmap black_heatmap_2d = heatmap if color is chess.WHITE else heatmap_flipped # Finally flatten the arrays self._white_heatmap = [v for r in white_heatmap_2d for v in r] self._black_heatmap = [v for r in black_heatmap_2d for v in r] # Save a copy for printing/display self._printing_heatmap = white_heatmap_2d if color is chess.WHITE else heatmap_flipped def apply_heatmap(self, color: chess.Color, piece_list: PieceList): """ Applies a heatmap to the given piece list :param color: :param piece_list: :return: """ heatmap = self._white_heatmap if color == chess.WHITE else self._black_heatmap return sum(heatmap[sq] for sq in piece_list.square_list(self.piece_type, color)) def apply_heatmap_dynamic(self, board: SearchBoard, color: chess.Color) -> int: """ Applies a heatmap to a given board. This implementation dynamically locates pieces and thus it is slower than `apply_heatmap`, which should be used if possible. :param board: The board to apply the heatmap to :param color: The color to apply the heatmap to :return: The sum of the heatmap times 1 if a piece of the given color and `self.piece_type` """ piece_mask = board.pieces_mask(self.piece_type, color) heatmap = self._white_heatmap if color == chess.WHITE else self._black_heatmap return sum(v * (1 if piece_mask & (1 << i) else 0) for i, v in enumerate(heatmap)) def __str__(self): files = "".join([f"{chr(i): <5}" for i in range(ord('a'), ord('h') + 1)]) header = " " * 5 + files footer = "(w) " + files board_lines = [str(8 - i) + " " + "".join([f"{str(s)[:4]: >5}" for s in r]) for i, r in enumerate(self._printing_heatmap)] board_lines.insert(0, header) board_lines.append("") board_lines.append(footer) return "\n".join(board_lines) + "\n" class BaseEvaluator: """ Base interface for all board evaluators, including some helper methods that are useful to all evaluators. """ def __init__(self, config_filepath: str): """ The initializer simply reads in the config file given the filepath. This config file should contain all relevant information on the parameters of the evaluator. All evaluators must contain a name, version, and description. :param config_filepath: Filepath to the config json """ self.config_filepath = config_filepath with open(self.config_filepath, "r+") as config_f: self.config = json.load(config_f) self._parse_base_config() self._parse_config() def _parse_base_config(self): """ Internal method to parse the fields that are required for all evaluators. :return: None """ try: self.name = self.config["name"] self.description = self.config["description"] self.version = self.config["version"] self.type = self.config["type"] except KeyError as e: logger.warning(e) def _parse_config(self): """ Abstract method that all child classes must implement to parse the relevant fields in their configurations. :return: None (sets fields) """ raise NotImplementedError("_parse_config must be implemented by all evaluators!") def _parse_board_heatmap(self, heatmap_key: str, piece_type: chess.PieceType, color_key: str = "piece_square_table_color") -> BoardHeatmap: """ Parses a board heatmap (such as a piece square table) from the config and returns the heatmap object. :param heatmap_key: The key into the config file for this heatmap. The value must be either a 2D array of values or a string where the ranks are separated by newlines. '/'s can be included in the key to index into sub-dictionaries. This is all relative to the JSON root :param piece_type: The piece type for this heatmap :param color_key: The key into the config file for the color that the input is assumed to be for ("w" for white, "b" for black). :return: The BoardHeatmap for the given heatmap """ key_split = heatmap_key.split("/") heatmap = self.config[key_split[0]] for s in key_split[1:]: heatmap = heatmap[s] color = chess.WHITE if self.config[color_key][0].lower() == "w" else chess.BLACK return BoardHeatmap(heatmap, piece_type, color=color) def _parse_piece_value_table(self, key) -> List[Optional[int]]: """ Helper method to parse piece value tables from the config into dictionary form. :param key: The key in the config for the piece value dictionary :return: The piece value dictionary """ piece_values = [None for _ in range(max(chess.PIECE_TYPES) + 1)] for piece_symbol, value in self.config[key].items(): piece_values[chess.Piece.from_symbol(piece_symbol).piece_type] = value return piece_values def _log_base_config(self): """ Logs the base configuration of name, description, and version to debug :return: None """ logger.debug(f"\tname={self.name}") logger.debug(f"\tdescription={self.description}") logger.debug(f"\tversion={self.version}") def evaluate_board(self, board: SearchBoard) -> BoardEvaluation: """ Evaluates a board position, generating a score for white and black. :param board: The board to evaluate :return: A BoardEvaluation object with the evaluations for both white and black and `board_evaluation` set to positive if the move to side to move is white and white is winning, also positive if side to move is black and black is winning, etc. """ raise NotImplementedError("evaluate_board must be implemented by all evaluators!") @staticmethod def _count_piece_type(board: SearchBoard, piece_type: chess.PieceType) -> Tuple[int, int]: """ Counts how many occurrences of the given piece type are on the board. :param board: Board to consider :param piece_type: Piece type to count :return: The piece count for white, black """ return (count_bin_ones(board.pieces_mask(piece_type, chess.WHITE)), count_bin_ones(board.pieces_mask(piece_type, chess.BLACK))) @staticmethod def _compute_materials_dynamic(value_map: List[int], board: SearchBoard) -> Tuple[int, int, int]: """ Counts up piece values on each side using the provided mapping of pieces to values, returning the piece values on each side. Dynamically counts pieces, which is much slower than the preferred _sum_materials method. :param value_map: A list of values for each piece :param board: Board to consider :return: Tuple of white piece values, left piece values, number of total pieces """ white_materials, black_materials, num_men = 0, 0, 0 for piece_type in chess.PIECE_TYPES: white_count, black_count = BaseEvaluator._count_piece_type(board, piece_type) white_materials += value_map[piece_type] * white_count black_materials += value_map[piece_type] * black_count num_men += white_count + black_count return white_materials, black_materials, num_men @staticmethod def _compute_materials(value_map: List[int], piece_list: PieceList) -> Tuple[int, int, int]: """ Counts up piece values on each side using the provided mapping of pieces to values, returning the piece values on each side. Uses a piece list and therefore is much faster. :param value_map: A list of values for each piece :param piece_list: Piece list :return: Tuple of white piece values, left piece values, number of total pieces """ white_materials, black_materials, num_men = 0, 0, 0 for piece_type in chess.PIECE_TYPES: wn = len(piece_list.square_list(piece_type, chess.WHITE)) bn = len(piece_list.square_list(piece_type, chess.BLACK)) white_materials += value_map[piece_type] * wn black_materials += value_map[piece_type] * bn num_men += wn + bn return white_materials, black_materials, num_men class SimplifiedEvaluator(BaseEvaluator): """ Evaluator based on https://www.chessprogramming.org/Simplified_Evaluation_Function. The config file must contain the piece value dictionary, appropriate piece square tables (pawn, knight, bishop, rook, queen, king middle game, king end game, with the proper names/nesting and color), the endgame criteria, and the position weighting (material values are assumed to be a weight of 1). The endgame criteria is either "queens" or "queens+pieces" representing the following respective criteria: Both sides have no queens ("queens") Every side which has a queen has additionally no other pieces or one minorpiece maximum ("queens+pieces") """ def __init__(self, config_filepath): """ All SimplifiedEvaluators must contain a piece_values dict. :param config_filepath: Filepath to config file """ super().__init__(config_filepath) logger.debug(f"Created a SimplifiedEvaluator: config_filepath={config_filepath}") self._log_base_config() def _parse_config(self): """ Currently parses and sets piece values and heatmaps. :return: None """ # Piece values self.piece_values = self._parse_piece_value_table("piece_values") # Piece square tables self.pawn_pst = self._parse_board_heatmap("piece_square_tables/pawn", chess.PAWN) self.knight_pst = self._parse_board_heatmap("piece_square_tables/knight", chess.KNIGHT) self.bishop_pst = self._parse_board_heatmap("piece_square_tables/bishop", chess.BISHOP) self.rook_pst = self._parse_board_heatmap("piece_square_tables/rook", chess.ROOK) self.queen_pst = self._parse_board_heatmap("piece_square_tables/queen", chess.QUEEN) self.king_middle_game_pst = self._parse_board_heatmap("piece_square_tables/king/middle_game", chess.KING) self.king_end_game_pst = self._parse_board_heatmap("piece_square_tables/king/end_game", chess.KING) # Endgame criteria self.endgame_criteria = self.config["endgame_criteria"].lower() if "queen" in self.endgame_criteria and "pieces" in self.endgame_criteria: self.endgame_criteria = "queen+pieces" elif "queen" in self.endgame_criteria: self.endgame_criteria = "queen" else: raise ValueError("endgame_criteria in config must be either 'queen' or 'queen+pieces'!") def _compute_positions(self, board: SearchBoard, color: chess.Color, endgame: bool) -> int: """ Computes the position score for a given board, color, and whether it is endgame using the PSTs. :param board: The board to consider :param color: The color to consider :param endgame: Whether it is currently endgame or not (precomputed) :return: The position score for the given color, board, and endgame """ return sum([ self.pawn_pst.apply_heatmap_dynamic(board, color), self.knight_pst.apply_heatmap_dynamic(board, color), self.bishop_pst.apply_heatmap_dynamic(board, color), self.rook_pst.apply_heatmap_dynamic(board, color), self.queen_pst.apply_heatmap_dynamic(board, color), self.king_end_game_pst.apply_heatmap_dynamic(board, color) if endgame else self.king_middle_game_pst.apply_heatmap_dynamic(board, color), ]) def evaluate_board(self, board: SearchBoard) -> BoardEvaluation: """ Evaluates the board position using https://www.chessprogramming.org/Simplified_Evaluation_Function. :param board: Board to evaluate :return: A `BoardEvaluation` object """ # Materials white_materials, black_materials, num_men = self._compute_materials_dynamic(self.piece_values, board) # Positions endgame = self._is_endgame(board, white_materials, black_materials) white_positions, black_positions = (self._compute_positions(board, chess.WHITE, endgame), self._compute_positions(board, chess.BLACK, endgame)) return BoardEvaluation(white_materials + white_positions, black_materials + black_positions, board.turn, endgame, endgame, num_men) def _is_endgame(self, board: SearchBoard, white_materials: int, black_materials: int) -> bool: """ Detects the endgame using the appropriate criteria :return: True if in the endgame, False otherwise """ white_queens, black_queens = self._count_piece_type(board, chess.QUEEN) if self.endgame_criteria == "queen": return white_queens == black_queens == 0 elif self.endgame_criteria == "queen+pieces": # If the side has a queen then they have 1 other minorpiece maximum return not ((white_queens > 0 and white_materials > self.piece_values[chess.BISHOP]) or (black_queens > 0 and black_materials > self.piece_values[chess.BISHOP])) else: return False class ViceEvaluator(BaseEvaluator): """ Evaluator based off the vice engine (https://www.youtube.com/playlist?list=PLZ1QII7yudbc-Ky058TEaOstZHVbT-2hg). Implements the following features: - position square tables - passed pawns - isolated pawns - open and semi-open squares for rooks and queens - bishop pairs - uses piece lists for efficiency """ def __init__(self, config_filepath: str): super().__init__(config_filepath) logger.debug(f"Created a ViceEvaluatorV2: config_filepath={config_filepath}") self._log_base_config() self._generate_bitmasks() def _generate_bitmasks(self): """ Generates the needed bitmasks for this evaluator (rank, file, passed, and isolated) :return: """ # Rank and file bitmasks (note that rank 1 is 0th index and file A is 0th index) self._rank_bbs = chess.BB_RANKS self._file_bbs = chess.BB_FILES # Passed pawns, & opposite side pieces BB with the square in question # True means the pawn is NOT passed, False means that it is passed self._white_passed_pawns_bbs = [0 for _ in chess.SQUARES] self._black_passed_pawns_bbs = [0 for _ in chess.SQUARES] for rank in range(8): for file in range(8): # White board = [[0 for i in range(8)] for j in range(8)] for rank_offset in range(1, 8): for file_offset in range(-1, 2): target_rank = rank + rank_offset target_file = file + file_offset if 0 <= target_rank <= 7 and 0 <= target_file <= 7: board[7 - target_rank][target_file] = 1 self._white_passed_pawns_bbs[8 * rank + file] = utils.array_to_bitboard(board) # Black board = [[0 for i in range(8)] for j in range(8)] for rank_offset in range(-1, -8, -1): # Simply go in reverse here for file_offset in range(-1, 2): target_rank = rank + rank_offset target_file = file + file_offset if 0 <= target_rank <= 7 and 0 <= target_file <= 7: board[7 - target_rank][target_file] = 1 self._black_passed_pawns_bbs[8 * rank + file] = utils.array_to_bitboard(board) # Isolated pawns, again & with same side pawns and True means the pawn is NOT isolated, False means it is self._isolated_pawns_bbs = [0 for _ in chess.SQUARES] for rank in range(8): for file in range(8): board = [[0 for i in range(8)] for j in range(8)] for rank_offset in range(-7, 8): for file_offset in [-1, 1]: target_rank = rank + rank_offset target_file = file + file_offset if 0 <= target_rank <= 7 and 0 <= target_file <= 7: board[7 - target_rank][target_file] = 1 self._isolated_pawns_bbs[8 * rank + file] = utils.array_to_bitboard(board) def _parse_config(self): self.piece_values = self._parse_piece_value_table("piece_values") self.pawn_pst = self._parse_board_heatmap("piece_square_tables/pawn", chess.PAWN) self.knight_pst = self._parse_board_heatmap("piece_square_tables/knight", chess.KNIGHT) self.bishop_pst = self._parse_board_heatmap("piece_square_tables/bishop", chess.BISHOP) self.rook_pst = self._parse_board_heatmap("piece_square_tables/rook", chess.ROOK) self.king_opening_game_pst = self._parse_board_heatmap("piece_square_tables/king/opening_game", chess.KING) self.king_end_game_pst = self._parse_board_heatmap("piece_square_tables/king/end_game", chess.KING) # Bishop pairs self.bishop_pair = self.config["bishop_pair"] # Endgame material value cutoff self.endgame_materials_cutoff = sum(v * self.piece_values[chess.Piece.from_symbol(p).piece_type] for p, v in self.config["endgame_cutoff_material"].items()) # Pawn positioning self.pawn_isolated: int = self.config["pawn_isolated"] self.pawn_passed: List[int] = self.config["pawn_passed"] # Rook positioning self.rook_open_file = self.config["rook_open_file"] self.rook_semiopen_file = self.config["rook_semiopen_file"] # Queen positioning self.queen_open_file = self.config["queen_open_file"] self.queen_semiopen_file = self.config["queen_semiopen_file"] def _compute_positions(self, color: chess.Color, piece_list: PieceList, white_materials: int, black_materials: int) -> int: """ Computes position score for the given color. :param color: Color :param piece_list: Piece list :param white_materials: White material values :param black_materials: Black material values :return: Position score """ king_pst = self.king_end_game_pst if self._is_endgame(color, white_materials, black_materials) \ else self.king_opening_game_pst return sum([ self.pawn_pst.apply_heatmap(color, piece_list), self.knight_pst.apply_heatmap(color, piece_list), self.bishop_pst.apply_heatmap(color, piece_list), self.rook_pst.apply_heatmap(color, piece_list), king_pst.apply_heatmap(color, piece_list) ]) def _compute_passed_isolated_pawns(self, board: SearchBoard, piece_list: PieceList) -> Tuple[int, int, int, int]: """ Computes the score for white and black passed and isolated pawns. :param board: Board to compute on :param piece_list: Piece list :return: white passed pawn score, black, white isolated pawn score, black """ white_pawns = board.pieces(chess.PAWN, chess.WHITE).mask black_pawns = board.pieces(chess.PAWN, chess.BLACK).mask white_passed, black_passed = 0, 0 white_isolated, black_isolated = 0, 0 for sq in piece_list.square_list(chess.PAWN, chess.WHITE): # Pawn present and it is passed (note that pawn is guaranteed to be here) if not self._white_passed_pawns_bbs[sq] & black_pawns: white_passed += self.pawn_passed[sq // 8] # Pawn present and is isolated if not self._isolated_pawns_bbs[sq] & white_pawns: white_isolated += self.pawn_isolated for sq in piece_list.square_list(chess.PAWN, chess.BLACK): if not self._black_passed_pawns_bbs[sq] & white_pawns: black_passed += self.pawn_passed[7 - (sq // 8)] if not self._isolated_pawns_bbs[sq] & black_pawns: black_isolated += self.pawn_isolated return white_passed, black_passed, white_isolated, black_isolated def _compute_open_files(self, board: SearchBoard, piece_list: PieceList) -> Tuple[int, int]: """ Computes the score for occupying open files (for rooks and queens) :param board: Board to consider :param piece_list: Piece list of the board :return: White open file score, black open file score """ white_pawns = board.pieces(chess.PAWN, chess.WHITE).mask black_pawns = board.pieces(chess.PAWN, chess.BLACK).mask pawns = white_pawns | black_pawns open_file = lambda s: not (pawns & self._file_bbs[s % 8]) white_semiopen_file = lambda s: not (white_pawns & self._file_bbs[s % 8]) black_semiopen_file = lambda s: not (black_pawns & self._file_bbs[s % 8]) white, black = 0, 0 for sq in piece_list.square_list(chess.ROOK, chess.WHITE): if open_file(sq): white += self.rook_open_file elif white_semiopen_file(sq): white += self.rook_semiopen_file for sq in piece_list.square_list(chess.ROOK, chess.BLACK): if open_file(sq): black += self.rook_open_file elif black_semiopen_file(sq): black += self.rook_semiopen_file # Queens for sq in piece_list.square_list(chess.QUEEN, chess.WHITE): if open_file(sq): white += self.queen_open_file elif white_semiopen_file(sq): white += self.queen_semiopen_file for sq in piece_list.square_list(chess.QUEEN, chess.BLACK): if open_file(sq): black += self.queen_open_file elif black_semiopen_file(sq): black += self.queen_semiopen_file return white, black def _is_endgame(self, color: chess.Color, white_materials: int, black_materials: int) -> bool: """ Returns True if the given color is in the end game. :param color: Color to check :param white_materials: White materials :param black_materials: White materials :return: True if in end game, False otherwise """ materials = black_materials if color == chess.WHITE else white_materials materials_minus_king = materials - self.piece_values[chess.KING] return materials_minus_king <= self.endgame_materials_cutoff def _is_material_draw(self, piece_list: PieceList) -> bool: """ Determines if the board is a material draw (minus pawns) using a heuristic from sjeng 11.2 and https://www.youtube.com/watch?v=4ozHuSRDyfE&list=PLZ1QII7yudbc-Ky058TEaOstZHVbT-2hg&index=82. Note that pawns must also be checked to truly determine if the board is a material draw. :param piece_list: Piece list :return: True if material draw, otherwise False """ if len(piece_list.square_list(chess.ROOK, chess.WHITE)) == 0 and \ len(piece_list.square_list(chess.ROOK, chess.BLACK)) == 0 and \ len(piece_list.square_list(chess.QUEEN, chess.WHITE)) == 0 and \ len(piece_list.square_list(chess.QUEEN, chess.BLACK)) == 0: if len(piece_list.square_list(chess.BISHOP, chess.WHITE)) == 0 and \ len(piece_list.square_list(chess.BISHOP, chess.BLACK)) == 0: return len(piece_list.square_list(chess.KNIGHT, chess.WHITE)) < 3 and \ len(piece_list.square_list(chess.KNIGHT, chess.BLACK)) < 3 elif len(piece_list.square_list(chess.KNIGHT, chess.WHITE)) == 0 and \ len(piece_list.square_list(chess.KNIGHT, chess.BLACK)) == 0: return abs(len(piece_list.square_list(chess.BISHOP, chess.WHITE)) - len(piece_list.square_list(chess.BISHOP, chess.BLACK))) < 2 elif (len(piece_list.square_list(chess.KNIGHT, chess.WHITE)) < 3 and len(piece_list.square_list(chess.BISHOP, chess.WHITE)) == 0) or \ (len(piece_list.square_list(chess.BISHOP, chess.WHITE)) == 1 and len(piece_list.square_list(chess.KNIGHT, chess.WHITE)) == 0): return (len(piece_list.square_list(chess.KNIGHT, chess.BLACK)) < 3 and len(piece_list.square_list(chess.BISHOP, chess.BLACK)) == 0) or \ (len(piece_list.square_list(chess.BISHOP, chess.BLACK)) == 1 and len(piece_list.square_list(chess.KNIGHT, chess.BLACK)) == 0) elif len(piece_list.square_list(chess.QUEEN, chess.WHITE)) == 0 and \ len(piece_list.square_list(chess.QUEEN, chess.BLACK)) == 0: if len(piece_list.square_list(chess.ROOK, chess.WHITE)) == 1 and \ len(piece_list.square_list(chess.ROOK, chess.BLACK)) == 1: return len(piece_list.square_list(chess.KNIGHT, chess.WHITE)) + \ len(piece_list.square_list(chess.KNIGHT, chess.WHITE)) < 2 and \ len(piece_list.square_list(chess.KNIGHT, chess.BLACK)) + \ len(piece_list.square_list(chess.KNIGHT, chess.BLACK)) < 2 elif len(piece_list.square_list(chess.ROOK, chess.WHITE)) == 1 and \ len(piece_list.square_list(chess.ROOK, chess.BLACK)) == 0: return len(piece_list.square_list(chess.KNIGHT, chess.WHITE)) + \ len(piece_list.square_list(chess.BISHOP, chess.WHITE)) == 0 and \ 1 <= len(piece_list.square_list(chess.KNIGHT, chess.BLACK)) + \ len(piece_list.square_list(chess.BISHOP, chess.BLACK)) <= 2 elif len(piece_list.square_list(chess.ROOK, chess.BLACK)) == 1 and \ len(piece_list.square_list(chess.ROOK, chess.WHITE)) == 0: return len(piece_list.square_list(chess.KNIGHT, chess.BLACK)) + \ len(piece_list.square_list(chess.BISHOP, chess.BLACK)) == 0 and \ 1 <= len(piece_list.square_list(chess.KNIGHT, chess.WHITE)) + \ len(piece_list.square_list(chess.BISHOP, chess.WHITE)) <= 2 return False def evaluate_board(self, board: SearchBoard) -> BoardEvaluation: piece_list = board.generate_piece_list() # Pawns must also be checked if len(piece_list.square_list(chess.PAWN, chess.WHITE)) == 0 and \ len(piece_list.square_list(chess.PAWN, chess.BLACK)) == 0 and \ self._is_material_draw(piece_list): return BoardEvaluation(0, 0, board.turn, True, True, 0) # Compute all values (all in centipawns) white_materials, black_materials, num_men = self._compute_materials(self.piece_values, piece_list) white_positions = self._compute_positions(chess.WHITE, piece_list, white_materials, black_materials) black_positions = self._compute_positions(chess.BLACK, piece_list, white_materials, black_materials) passed_isolated = self._compute_passed_isolated_pawns(board, piece_list) white_passed, black_passed, white_isolated, black_isolated = passed_isolated white_open_files, black_open_files = self._compute_open_files(board, piece_list) white_bishop_pair = self.bishop_pair if len(piece_list.square_list(chess.BISHOP, chess.WHITE)) >= 2 else 0 black_bishop_pair = self.bishop_pair if len(piece_list.square_list(chess.BISHOP, chess.BLACK)) >= 2 else 0 # Sum it all up white = white_materials + white_positions + white_passed + white_isolated + white_open_files + white_bishop_pair black = black_materials + black_positions + black_passed + black_isolated + black_open_files + black_bishop_pair return BoardEvaluation(white, black, board.turn, self._is_endgame(chess.WHITE, white_materials, black_materials), self._is_endgame(chess.BLACK, white_materials, black_materials), num_men) def evaluator_from_config(config_filepath: str) -> BaseEvaluator: with open(config_filepath, "r+") as config_f: config = json.load(config_f) eval_type = config["type"] if eval_type == "SimpleEvaluator": return SimplifiedEvaluator(config_filepath) elif eval_type == "ViceEvaluator": return ViceEvaluator(config_filepath) raise ValueError("the given config does not contain a valid type key!")
4edd924a4bc2ae69e4aad8b38457d64b3de17079
spinon187/practice
/treepaths.py
487
3.734375
4
class Solution: def binaryTreePaths(self, root): results = [] self.dfs(root, '', results) return results def dfs(self, node, string, arr): if not node: return if node.left or node.right: string += (str(node.val) + '->') self.dfs(node.left, string, arr) self.dfs(node.right, string, arr) else: string += str(node.val) arr.append(string)
5f631cfcc81db77a83ac3f2cc89b95d657d3a3b6
Bot-Zavod/botchallenge
/board/_pathfinding.py
5,422
4.03125
4
""" Pathfinding methods of the board """ from typing import Tuple, List, Set class Node: """A node class for A* Pathfinding""" def __init__(self, parent=None, position=None): self.parent = parent self.position = position self.g = 0 self.h = 0 self.f = 0 def __eq__(self, other): return self.position == other.position def __str__(self): return str(self.position) def __repr__(self): return str(self.position) class Mixin: def bfs_nearest( self, start: Tuple[int, int], end_points: List[Tuple[int, int]] ) -> Tuple[int, int]: """ return the nearest point to the start """ end_points = set(end_points) visited = set() queue = [start] while queue: node = queue.pop() visited.add(node) neighbors = self._get_neighbors(node) for neighbor in neighbors: if neighbor not in visited: if neighbor in end_points: return neighbor queue.append(neighbor) return () def astar( self, start: Tuple[int, int], end: Tuple[int, int] ) -> List[Tuple[int, int]]: """ Returns a list of tuples as a path from the given start to the given end in the given maze """ # Create start and end node start_node = Node(None, start) start_node.g = start_node.h = start_node.f = 0 end_node = Node(None, end) end_node.g = end_node.h = end_node.f = 0 # Initialize both open and closed list open_list = [] closed_list = [] # Add the start node open_list.append(start_node) # Loop until you find the end while len(open_list) > 0: # print() # print("open_list: ", open_list) # print("closed_list: ", closed_list) # Get the current node current_node = open_list[0] current_index = 0 for index, item in enumerate(open_list): if item.f < current_node.f: current_node = item current_index = index # print("current_node: ", current_node.position) # Pop current off open list, add to closed list open_list.pop(current_index) closed_list.append(current_node) # Found the goal if current_node == end_node: path = [] current = current_node while current is not None: path.append(current.position) current = current.parent return path[::-1] # Return reversed path neighbors = self._get_neighbors(current_node.position) # Generate children children = [] for neighbor in neighbors: new_node = Node(current_node, neighbor) # Create new node children.append(new_node) # Append # Loop through children for child in children: stop_itaration = False # Child is on the closed list for closed_child in closed_list: if child == closed_child: stop_itaration = True break if stop_itaration: continue # Create the f, g, and h values child.g = current_node.g + 1 if (abs((current_node.position[0] - child.position[0]) + (current_node.position[1] - child.position[1])) > 1): child.g += 1 child.h = self._mht_dist(child.position, end_node.position) child.f = child.g + child.h # Child is already in the open list for open_node in open_list: if child == open_node and child.g > open_node.g: stop_itaration = True break if stop_itaration: continue # Add the child to the open list open_list.append(child) def _get_neighbors(self, start: Tuple[int, int]) -> List[Tuple[int, int]]: """ return 4 Adjacent squares """ non_barrier = self._non_barrier jump_over = self._jump_over directions = self.directions[:-1] neighbors = [] for new_position in directions: # Adjacent squares # Get node position node_position = (start[0] + new_position[0], start[1] + new_position[1]) # where to jump if it is box or hole if node_position in jump_over: node_position = ( start[0] + new_position[0] * 2, start[1] + new_position[1] * 2, ) # Make sure walkable terrain if node_position not in non_barrier: continue # Make sure no object on second layer if node_position in jump_over: continue neighbors.append(node_position) return neighbors def _mht_dist(self, start: Tuple[int, int], end: Tuple[int, int]): return ((end[0] - start[0]) ** 2) + ((end[1] - start[1]) ** 2)
6158b346fb994583de0e54ac4a3f98f47c3bd422
ToddZenger/PHYS19a
/tutorial/lesson01/numpy_tutorial.py
2,937
4.3125
4
""" Author: Todd Zenger, Brandeis University The purpose of this program is to tie in between lists and Numpy arrays and to introduce some concepts of Numpy """ import numpy as np """ Anytime we want to use Numpy, we must write this on top of our script """ # First, let's look at lists once again x = [4, 9, 12, 13] y = [2, 4, 8, 15] # First task, let's increase all elements by 2 for i in range(len(x)): x[i] = x[i]+2 y[i] = y[i]+2 # Now, let's print out the results print("List x increased by 2 is: {}".format(x)) print("List y increased by 2 is: {}".format(y)) # Second task, let's add x and y together into a new list z z = [] for i in range(len(x)): z.append(x[i]+y[i]) # Remember, that we are using the increased by 2 x and y lists print("List z is: {}".format(z)) """ Moral of the story: anytime we want to do something will all or most of the elements of a list, we need to create a for loop to help us solve this. Is there a better way? Yes! Numpy arrays! Let's solve the previous two tasks with Numpy arrays """ print() xn = np.array([4, 9, 12, 13]) yn = np.array([2, 4, 8, 15]) xn = xn + 2 yn = yn + 2 print("Array x increased by 2 is: {}".format(xn)) print("Array y incraesed by 2 is: {}".format(yn)) # Now let's add them together zn = xn + yn print("Array z is: {}".format(zn)) """ Now, let's get a bit more practical utilizing Numpy's power The problem: we are given three sets of data and each item in the array represents a measurement at a certain time. Calculate mean and std at each time. """ print() data1 = np.array([1, 3, 5, 9]) data2 = np.array([1.4, 2.8, 7, 8.2]) data3 = np.array([0.4, 2.9, 7.6, 7]) mu = (data1 + data2 + data3)/3 print("The mean of this data is: {}".format(mu)) sigma = np.sqrt(((data1-mu)**2+(data2-mu)**2+(data3-mu)**2)/(3-1)) print("The standard deviation is: {}".format(sigma)) """ Now, some other mathematical things we can do: """ print() # First, we can create arrays in some ascending order nums = np.arange(10) print(nums) # Or, we can sepcify how it counts with (start, stop, steps) vals = np.arange(0, 3, 0.5) print(vals) # There are math functions we can use sinvals = np.sin(vals) print(sinvals) # What use is there for this? It helps us model the expected values """ Next, we can go two dimenional. How? We have the array hold arrays! """ d = np.array([[1,2],[3,4]]) print() print("My 2d array d is:") print(d) # How do we access items? We can index using [row, column] print("row 0 column 0: {}".format(d[0,0])) print("row 0 column 1: {}".format(d[0,1])) print("row 1 column 0: {}".format(d[1,0])) print("row 1 column 1: {}".format(d[1,1])) # If we want all of a certain row or column, we can use slicing print("The first row is: {}".format(d[0,:])) print("The second row is: {}".format(d[1,:])) # Notice, that these columns come out as a 1D array print("The first column is: {}".format(d[:,0])) print("The second column is: {}".format(d[:,1]))
e8d5f3b501d1acebe6f6e2f435a39d40df9f7ed2
Zahidsqldba07/practice-python-2
/08_rock_paper_scissors.py
1,265
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game) """ player1 = str(input("Who is player 1?")) player2 = str(input("Who is player 2?")) def move(): player1_move = str(input(player1 + ", what do you choose -- rock, paper or scissors?")) player2_move = str(input(player2 + ", and you? Rock, paper or scissors?")) if player1_move == player2_move: print("Equal game!") elif player1_move == "rock": if player2_move == "paper": print(player2 + ", you win!") else: print(player1 + ", you win!") elif player1_move == "scissors": if player2_move == "rock": print(player2 + ", you win!") else: print(player1 + ", you win!") elif player1_move == "paper": if player2_move == "scissors": print(player2 + ", you win!") else: print(player1 + ", you win!") another_game = input("Want to play again? Yes or no?") if another_game == "yes": move() else: print("That was all, folks!") move()
cabe516536213d890ba5efa4e3f674396b99d36b
xiangge/xiangge_repo
/programing/learn_python/test05.py
1,331
3.578125
4
#encoding:UTF-8 # https://leetcode.com/problems/next-permutation/description/ def nextPermutation(nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 """ if len(nums) >1: # get start place temp = len(nums)-1 for i in range(len(nums)-1, -1, -1): if i == 0: for m in range(0, len(nums)-1): for n in range(m+1 ,len(nums)): if nums[m] > nums[n]: nums[m], nums[n] = nums[n], nums[m] return if i != 0 and nums[i] > nums[i-1]: temp = i break print temp for i in range(len(nums)-1, temp-1, -1): if nums[i] > nums[temp-1]: nums[i], nums[temp-1] = nums[temp-1], nums[i] print "-----" break print temp for m in range(temp, len(nums)): for n in range(m+1 ,len(nums)): if nums[m] > nums[n]: nums[m], nums[n] = nums[n], nums[m] print nums #nextPermutation([4,2,0,2,3,2,0]) nextPermutation([2,3,0,2,4,1]) #nextPermutation([3,2,1]) # nextPermutation([1,2,3]) nextPermutation([1,3,2])
e7856c335ad7acde5c072c0db212eae9a098e870
amanjaiswalofficial/100-Days-Code-Challenge
/code/python/day-24/Dictionary.py
309
3.71875
4
import math dictn={} name='' n=int(input()) for x in range(n): name=str(input()) phy=float(input()) chem=float(input()) maths=float(input()) totalavg=float(phy+chem+maths)/3 dictn[name]=totalavg uinput=str(input()) for x in dictn: if(x==uinput): print(float(dictn[x]))
a5d1c6f6a3f39e6f76b68dd43f029dac37ee8ea3
Victorkme/PythonProjects
/pythonscripts/mineSweeper.py
3,456
3.65625
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 22 11:22:12 2019 @author: User1 """ matrix = [[True,False,False],[False,True,False],[False,False,False]] def minesweeper(matrix): if not matrix: return [[0]] rows = len(matrix) columns = len(matrix[0]) result = [[0 for col in range(columns)] for mrow in range(rows)] for row in range(rows): for column in reversed(range(columns)): value = matrix[row][column] #print(result) #print("column: " + str(column) + " value: " + str(value)) if row == 0: if column == len(matrix[row])-1: if value: result[row][column-1] += 1 result[row+1][column-1] += 1 result[row+1][column] += 1 elif column == 0: if value: result[row][column+1] += 1 #print(result) result[row+1][column+1] += 1 #print(result) result[row+1][column] += 1 #print(result) else: if value: result[row][column-1] += 1 result[row][column+1] += 1 result[row+1][column-1] += 1 result[row+1][column+1] += 1 result[row+1][column] += 1 elif row == rows-1: if column == len(matrix[row])-1: if value: result[row][column-1] += 1 result[row-1][column-1] += 1 result[row-1][column] += 1 elif column == 0: if value: result[row][column+1] += 1 result[row-1][column+1] += 1 result[row-1][column] += 1 else: if value: result[row][column-1] += 1 result[row][column+1] += 1 result[row-1][column-1] += 1 result[row-1][column+1] += 1 result[row-1][column] += 1 else: if column == len(matrix[row])-1: if value: result[row][column-1] += 1 result[row-1][column-1] += 1 result[row-1][column] += 1 result[row+1][column-1] += 1 result[row+1][column] += 1 elif column == 0: if value: result[row][column+1] += 1 result[row-1][column+1] += 1 result[row-1][column] += 1 result[row+1][column+1] += 1 result[row+1][column] += 1 else: if value: result[row][column-1] += 1 result[row][column+1] += 1 result[row-1][column-1] += 1 result[row-1][column+1] += 1 result[row-1][column] += 1 result[row+1][column-1] += 1 result[row+1][column+1] += 1 result[row+1][column] += 1 return result print(minesweeper(matrix))
8f542901b827e6a5a6939872b7dfa9bc83625cf8
Viiic98/holbertonschool-machine_learning
/supervised_learning/0x0D-RNNs/8-bi_rnn.py
1,390
4.375
4
#!/usr/bin/env python3 """ Bidirectional RNN """ import numpy as np def bi_rnn(bi_cell, X, h_0, h_t): """ performs forward propagation for a bidirectional RNN - bi_cell is an instance of BidirectionalCell that will be used for the forward propagation - X is the data to be used, given as a numpy.ndarray of shape (t, m, i) - t is the maximum number of time steps - m is the batch size - i is the dimensionality of the data - h_0 is the initial hidden state in the forward direction, given as a numpy.ndarray of shape (m, h) - h is the dimensionality of the hidden state - h_t is the initial hidden state in the backward direction, given as a numpy.ndarray of shape (m, h) Returns: H, Y - H is a numpy.ndarray containing all of the concatenated hidden states - Y is a numpy.ndarray containing all of the outputs """ T, m, i = X.shape _, h = h_0.shape H_f = np.zeros((T + 1, m, h)) H_b = np.zeros((T + 1, m, h)) H_f[0] = h_0 H_b[-1] = h_t for f, b in zip(range(T), range(T - 1, -1, -1)): H_f[f + 1] = bi_cell.forward(H_f[f], X[f]) H_b[b] = bi_cell.backward(H_b[b + 1], X[b]) H = np.concatenate((H_f[1:], H_b[0:-1]), axis=-1) Y = bi_cell.output(H) return H, Y
571790eba0c2bce61b187353f19fc766cd7cbc05
SidStraw/leet-codes
/2021-08/2021-08-02 (day15)/CXPhoenix/solution1.py
891
3.90625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1 and not l2: return None if not l1: return l2 if not l2: return l1 c1 = l1 c2 = l2 merged = ListNode(None) m1 = merged while c1 or c2: if not c1: m1.next = c2 break if not c2: m1.next = c1 break if c1.val <= c2.val: m1.next=c1 c1 = c1.next else: m1.next=c2 c2 = c2.next m1 = m1.next return merged.next
18fffccc83edc59159b2e08ea72ac91f04fb855b
q1003722295/WeonLeetcode
/_44-WildcardMatching/WildcardMatching1.py
2,526
3.53125
4
''' 给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。 '?' 可以匹配任何单个字符。 '*' 可以匹配任意字符串(包括空字符串)。 两个字符串完全匹配才算匹配成功。 说明: s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。 示例 1: 输入: s = "aa" p = "a" 输出: false 解释: "a" 无法匹配 "aa" 整个字符串。 示例 2: 输入: s = "aa" p = "*" 输出: true 解释: '*' 可以匹配任意字符串。 示例 3: 输入: s = "cb" p = "?a" 输出: false 解释: '?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。 示例 4: 输入: s = "adceb" p = "*a*b" 输出: true 解释: 第一个 '*' 可以匹配空字符串, 第二个 '*' 可以匹配字符串 "dce". 示例 5: 输入: s = "acdcb" p = "a*c?b" 输入: false ''' ''' 暴力递归回溯法 超时 ''' class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ def _isMatch(s, p, s_i, p_i): if s_i == len(s) and p_i == len(p): return True elif s_i != len(s) and p_i == len(p): return False elif s_i == len(s) and p_i != len(p): for i in range(p_i, len(p)): if p[i] != '*': return False return True i = s_i j = p_i while i<len(s) and j < len(p): if p[j] == '*': while j+1<len(p) and p[j+1] =='*': j+=1 for skip in range(0, len(s) - i + 1 ): if _isMatch(s, p, i + skip, j + 1): return True return False else: if not (s[i] == p[j] or p[j] == '?'): return False i += 1 j += 1 if i == len(s) and j == len(p): return True elif i != len(s) and j == len(p): return False elif i == len(s) and j != len(p): for k in range(j, len(p)): if p[k] != '*': return False return True return _isMatch(s, p, 0, 0) s = Solution() print(s.isMatch("babbaabbaaabbaabbbaaa", "*****aab"))
98c36e38b891c3afeef4d5de8729ed32d73e68bf
zhio/python_notebook
/常见编程语言语法比较/example.py
1,442
3.640625
4
# array = [] # array.append(2) # array.append(3) # array.append(1) # array.append(0) # array.append(2) # #链表 # class ListNode: # def __init__(self, x): # self.val = x # 节点值 # self.next = None # 后继节点引用 # n1 = ListNode(4) # n2 = ListNode(5) # n3 = ListNode(1) # n1.next = n2 # n2.next = n3 # # 栈 # stack = [] # stack.append(1) # stack.append(2) # stack.pop() # stack.pop() # # 队列 # from collections import deque # queue = deque() # queue.append(1) # queue.append(2) # queue.popleft() # queue.popleft() # # 树 # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # n1 = TreeNode(3) # n2 = TreeNode(4) # n3 = TreeNode(5) # n4 = TreeNode(1) # n5 = TreeNode(2) # n1.left = n2 # n2.right = n3 # n2.left = n4 # n2.right = n5 # # 堆 # from heapq import heappush, heappop # # 初始化小顶堆 # heap = [] # # 元素入堆 # heappush(heap, 1) # heappush(heap, 4) # heappush(heap, 2) # heappush(heap, 6) # heappush(heap, 8) # # 元素出堆(从小到大) # heappop(heap) # -> 1 # heappop(heap) # -> 2 # heappop(heap) # -> 4 # heappop(heap) # -> 6 # heappop(heap) # -> 8 import requests url = "https://bfabaicup.oss-cn-beijing.aliyuncs.com/headimg/5e8791b2efb066822fdc5c7bbd356644.jpeg" response = requests.get(url) img = response.content with open("./a.jpg",'wb') as f: f.write(img)
f20f1b21fb8964b8f5b1bd62226ed18e61c12ac8
hamseul/ch03-2
/input_multiply.py
131
3.78125
4
num1=int(input("첫 번째 수를 입력하세요. : ")) num2=int(input("두 번째 수를 입력하세요. : ")) print(num1*num2)
702f52d934e24fc003f1cee734fcc5498e5897f4
AlbertoPeon/project-euler
/40/40.py
564
3.578125
4
#! /usr/bin/env python3 # https://projecteuler.net/problem=40 from functools import reduce from itertools import count from operator import mul important_digits = [1, 10, 100, 1000, 10000, 100000, 1000000] length = 0 result = [] for number in count(start=1): str_number = str(number) if length < important_digits[0] and length + len(str_number) >= important_digits[0]: result.append(int(str_number[important_digits.pop(0) - length - 1])) if not important_digits: break length += len(str_number) print(reduce(mul, result, 1))
f29edad0513c504ff865a683746fe446c3558f8b
JaehoonYi/Python-GCSE-2019-2021
/python/LESSON ACTIVITIES FOR YEAR 1, TERM 1/week 5/activity 5.2.4.py
141
3.765625
4
answer = input("Is it snowing? ") if answer == ("yes"): print ("You’d better take a sledge.") else: print("Have a good day.")
f98890dd1b38df1a49b1bfe0f447719307bdc2fb
dkssyd07/OlympicLOGO
/LOGO.py
308
3.671875
4
#Olympic Logo import turtle as p def drawCircle(x,y,c = 'red'): p.pu() p.goto(x,y) p.pd() p.color(c) p.circle(30,360) p.pensize(7) drawCircle(0,0,'blue') drawCircle(60,0, 'black') drawCircle(120,0,'red') drawCircle(90,-30,'green') drawCircle(30,-30,'yellow') p.done()
4f659fd65b0643f5a4b9d496792e2e683202168e
iamnaf/Meedya
/seriesdownloader.py
2,858
3.515625
4
import os import bs4 from selenium import webdriver import urllib2 from bs4 import BeautifulSoup """ download bs4 by using pip install bs4 on the command line download selenium by using pip install selenium on the command line """ """ This is a damn crude code i just wrote, but it sure downloads something """ class Downloader: def __init__(self, url, title): self.url = url self.title = title def openPage(self): newpage = urllib2.urlopen(self.url).read() return newpage def getTitle(self): firstletter = self.title[0].lower() print firstletter return firstletter def getSeriesPage(self): page = self.openPage() firsttitle = '' if self.getTitle() in "a,b,c".split(','): firsttitle = 'a' elif self.getTitle() in "d,e,f".split(','): firsttitle = 'd' elif self.getTitle() in "g,h,i".split(','): firsttitle = 'g' elif self.getTitle() in "j,k,l".split(','): firsttitle = 'j' elif self.getTitle() in "m,n,o".split(','): firsttitle = 'm' elif self.getTitle() in "p,q,r".split(','): firsttitle = 'p' elif self.getTitle() in "s,t,u".split(','): firsttitle = 's' elif self.getTitle() in "v,w,x".split(','): firsttitle = 'v' elif self.getTitle() in "y,z,0,1,2,3,4,5,6,7,8,9,#".split(','): firsttitle = 'y' #print firsttitle return firsttitle def openSeriesPage(self): seriesPage = "{}/{}".format(self.url, self.getSeriesPage()) newpage = urllib2.urlopen(seriesPage).read() newsoup = BeautifulSoup(newpage, 'html.parser') links = newsoup.find_all('a') for tags in links: link = tags.get('href', None) if link is not None: pass return seriesPage def downloadSeries(self): browser = webdriver.Firefox() browser.get(self.openSeriesPage()) serieslink = browser.find_element_by_link_text("Game of Thrones") serieslink.click() selectSeason = browser.find_element_by_link_text("Season 06") selectSeason.click() selectEpisode = browser.find_element_by_link_text("Episode 01") selectEpisode.click() selectVideo = browser.find_element_by_link_text("Game of Thrones - S06E01 (TvShows4Mobile.Com).mp4") selectVideo.click() url = "http://o2tvseries.com" title = "Game of Thrones" newDownloader = Downloader(url, title) #newDownloader.getTitle() newDownloader.openSeriesPage() newDownloader.downloadSeries()
c4430f27d22bd62b083c77325b9d408e5af1ce80
oscar-liu/unittest.io
/fn.py
177
3.5
4
#待测试的方法函数 #加 def add(a, b): return a+b #减 def minus(a, b): return a-b #乘 def multi(a, b): return a*b #除 def divide(a, b): return a/b
efe7c337cce5459b6c1a24b10701af7244db5c06
kt3a/GWCPython
/ClassDemo.py
849
4.15625
4
import tkinter from tkinter import Button #define the quit function def set_quit(): top.destroy() #to show text def show_text(): message.insert(0,e.get()) #Layout top = tkinter.Tk() top.geometry("300x300") #label label = tkinter.Label(top, text = "Hello World!") top.title("First GUI") label.pack() #Entry Widget e = tkinter.Entry(top) e.pack() #string_input = e.get() text = tkinter.Label(top, text = "Answer:").pack() #make a box to display the message message = tkinter.Entry(top) message.pack() #make a button that will display the message when pushed ans = tkinter.Button(top, text = "Show Message", command = show_text) ans.pack() #button qbutton = tkinter.Button(top, text = "Quit", command = set_quit) qbutton.pack() #cButton = tkinter.Button(self.window,text = "Change",command=self.change_paint) top.mainloop()
ee12cd1e29a65a784de1e44a9134f19b3ce7877a
MannazX/mannaz
/Learning Python/Fibbonacci sequence.py
1,646
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 20 10:39:07 2019 @author: magge """ import numpy as np import matplotlib.pyplot as plt import math as m """ The following script is about the Fibonacci sequence and the Golden ratio, the first part of the script approximates the golden ratio to 15 decimal places (40 iterations). The second part of the script computes the Fibonacci sequence and appends the numbers in a list (39 terms). The last part of the script plots the Fibonacci numbers, their square values, the approximation of the Golden ratio, and the error decrease. """ al = [] fl = [] el = [] a0 = 0 a1 = 1 al.append(a1) phi = (1+np.sqrt(5))/2 for i in range(2,40): a = a0 + a1 al.append(a) f = a/a1 err = abs(f-phi) fl.append(f) el.append(err) print("{:.15f} {:15.15f}".format(f,err)) a0 = a1 a1 = a print(48*'-') print(al) print(48*'-') al2 = [i**2 for i in al] x1 = [i for i in range(len(al))] x2 = [j for j in range(len(fl))] x3 = [k for k in range(len(el))] def plot(): plot = str(input("Choose one of the plots (1, 2, 3, or 4):")) if plot == "1": plt.plot(x1,al,'g.') plt.title("Fibbonacci Numbers Generated") elif plot == "2": plt.plot(x1,al2,'m.') plt.title("Squares of Fibbonacci Numbers") elif plot == "3": plt.plot(x2,fl,'k.') plt.title("Approksimation of the Golden Ratio") elif plot == "4": plt.plot(x3,el,'b.') plt.title("Erorr of the Golden Ratio Approksimation") else: print(plot, "is not one of the plot options, there are four, please choose one of them.") plot()
e123157dad83fddac5e778c8485e75d281fea483
Lindisfarne-RB/GUI-L3-tutorial
/Lesson52OOPS.py
1,433
4.1875
4
'''Docstrings for documenting classes We already know about writing comments to document our code. With classes, we usually write docstrings to say what the purpose of the class is. You might remember these from looking at functions in level 2. A docstring is a description written on the first line of a class (or function) in triple double quotes: """ class MyClass: """Here is a description of what this class does""" If you call help() on a class you will see the docstring e.g. print(help(MyClass))''' '''create On line 3, add a docstring to the account class with the following text: The Account class stores the details of each account and has methods to deposit, withdraw and calculate progress towards the savings goal Underneath the printed attributes from the 3 account objects we created, call the help() function on the Account class and print the result.''' # Create the Account class class Account: """The Account class stores the details of each account and has methods to deposit, withdraw and calculate progress towards the savings goal""" def __init__(self, name, balance, goal): self.name = name self.balance = balance self.goal = goal # Create instances of the class savings = Account("Savings", 0, 1000) phone = Account("Phone", 0, 800) holiday = Account("Holiday", 0, 7000) # Print out some attributes print(savings.name) print(phone.balance) print(holiday.goal) print(help(Account))
c73d58c4838b4250069c2f3c242c9bc2feb96014
MinWooPark-dotcom/learn-pandas
/Part1/1.15_transpose.py
1,842
3.546875
4
import pandas as pd exam_data = {'이름': ['서준', '우현', '인아'], '수학': [90, 80, 70], '영어': [98, 89, 95], '음악': [85, 95, 100], '체육': [100, 90, 90]} df = pd.DataFrame(exam_data) print(df) print('\n') # 이름 수학 영어 음악 체육 # 0 서준 90 98 85 100 # 1 우현 80 89 95 90 # 2 인아 70 95 100 90 # 데이터프레임 df를 전치하기 (메서드 활용) df = df.transpose() print(df) print('\n') # 0 1 2 # 이름 서준 우현 인아 # 수학 90 80 70 # 영어 98 89 95 # 음악 85 95 100 # 체육 100 90 90 # 데이터프레임 df를 다시 전치하기 (클래스 속성 활용) df = df.T print(df) # 이름 수학 영어 음악 체육 # 0 서준 90 98 85 100 # 1 우현 80 89 95 90 # 2 인아 70 95 100 90 # ! my exam_data = {'이름': ['김코딩', '박해커', '최고수'], '언어': ['JS', 'Python', 'C'], '경력': ['1년', '2년', '3년'], '취미': ['걷기', '독서', '등산'], '특기': ['양궁', '축구', '노래']} df = pd.DataFrame(exam_data) print(df) print('\n') df.transpose() print(df) print('\n') df.T print(df) print('\n') # 이름 언어 경력 취미 특기 # 0 김코딩 JS 1년 걷기 양궁 # 1 박해커 Python 2년 독서 축구 # 2 최고수 C 3년 등산 노래 # 이름 언어 경력 취미 특기 # 0 김코딩 JS 1년 걷기 양궁 # 1 박해커 Python 2년 독서 축구 # 2 최고수 C 3년 등산 노래 # 이름 언어 경력 취미 특기 # 0 김코딩 JS 1년 걷기 양궁 # 1 박해커 Python 2년 독서 축구 # 2 최고수 C 3년 등산 노래
bd24828a4d9cb8e602cd8e75e5c0221a8dd05837
969452199/pythonproject
/day02/day02_class09.py
1,132
3.9375
4
'''集合''' l1 = set([1,2])#{1, 2} print(l1) l2 = {1,(1,2,3)} print(l2)#{1, (1, 2, 3)} l3 = {2,3,4,2,3,5}#集合互异 print(l3)#{2, 3, 4, 5} print(type(l3))#<class 'set'> l4 = {3,2,4,5} print(l3 == l4)#无序性#True print([1,2,3] == [2,1,3])#False #列表不能作为集合的元素 #a = {1,2,[3,4]} #创建可变集合用set(),不可变用frozonset() a = [1,2,3,4,5,5,6] print(a)#[1, 2, 3, 4, 5, 5, 6] b = set(a) print(b)#{1, 2, 3, 4, 5, 6} b.add(7) print(b)#{1, 2, 3, 4, 5, 6, 7} b.update(set([8,'hello']))#增加需要集合形式,故需要加set print(b)#{1, 2, 3, 4, 5, 6, 7, 8, 'hello'} b.pop()#删除,从前面开始删除 print(b)#{2, 3, 4, 5, 6, 7, 8, 'hello'} b.pop() print(b)#{3, 4, 5, 6, 7, 8, 'hello'} b.remove(8)#删除,指定删除,当不存在时报错 print(b)#{3, 4, 5, 6, 7, 'hello'} #b.remove(8) #print(b) b.discard(4)#删除,指定删除,当不存在时不报错 print(b)#{3, 5, 6, 7, 'hello'} b.discard(8) print(b)#{3, 5, 6, 7, 'hello'} #b.clear() #print(b) print(5 in b)#判断元素是否在集合中用in print(8 in b) #lst = set(1,2,[1,2]) #print(lst) #lst = set(1,2,(2,3)) #print(lst)
6c7a51ebed92033b6fac38a4585f51d499cedc53
yanshuyu/learn-python
/buildinFuction/map.py
408
4.15625
4
def pow2(x): return x**2 def add(x,y): return x+y if __name__ == "__main__": numbers = [1, 2.2, 5, 7, 9] mapnumbers = map(pow2, numbers) print('numbers before map: ', numbers) print('map numbers: ', mapnumbers, [e for e in mapnumbers]) print('numbers after map: ', numbers) arr1 = [1,2,3] arr2 = [4,5,6] print('arr1 + arr2: ', [e for e in map(add, arr1, arr2)])
bfef1a8c0c8f1e60d07d1c55e73deaf68d4b3878
nowmaciej/python
/unittests/circle_area.py
206
3.96875
4
from math import pi def circle_area(r): if type(r) not in [float,int]: raise TypeError("value mus be number > 0") if r < 0: raise ValueError("value must be > 0") return pi*(r**2)
d141a088dc89774f913f10eb08b7cd216bf90081
gabits/training
/python/project_euler/002-fibonacci_evens_sum_under_4million.py
942
3.828125
4
"""Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ def fibonacci_to_four_million(): sequency = [1, 1] # it starts with two ones for the first sum while sum(fibonacci) <= 4000000: for number in fibonacci: n = sequency[number - 1] + sequency[number] n.append(sequency) return fibonacci def sum_evens: sequency = fibonacci_to_four_million() for number in sequency: if number % 2 == 0: number.append() sum(evens) # def fib_test(): # fibonacci = [1, 2] # for n in range(40): # if n == sum(fibonacci[-1], fibonacci[-2]): # fibonacci.append(n) # return fibonacci
bb50aa7e68ecddaeefd7d65e29fbef5d46f3e310
0911012580/ccc
/lesson 02.py
130
3.515625
4
var = 2005 print(var) real = 1 print(real) name = 'bình minh' place = 'bắc ninh' print( name + ' lives in ' + str(place))
d64417548e1a5eef149ea81f3efaa0bfd61c3d6b
Dutta-SD/CC_Codes
/Competitions/Atcoder/ABC_200/C.py
322
3.53125
4
from itertools import combinations n = int(input()) c = combinations (range(n), 3) candidates = [tuple(map(int, input().split())) for _ in range(n)] teamPower = -1 for item in c: power = min([max([i, j, k]) for i, j, k in zip(*[candidates[p] for p in item])]) teamPower = max(power, teamPower) print(teamPower)
198351a7649298d2d75f6e9b7d1e643aeea89d38
nazaninsbr/Introduction-to-Selection
/Intro-to-Numpy/reshape.py
132
3.796875
4
import numpy as np a = np.array([[1, 2], [3, 4], [5, 6]]) print(a.shape) a= a.reshape(2,3) print(a) a=a.reshape(6, 1) print(a)
970e0dddffd4ecd28345cc1c384412736dc5dbfe
sudhansom/python_sda
/python_fundamentals/00-python-HomePractice/w3resource/conditions-statements-loops/problem2.py
916
4
4
""" Write a Python program to convert temperatures to and from celsius, fahrenheit. [ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ] Expected Output : 60°C is 140 in Fahrenheit 45°F is 7 in Celsius """ print("choose the option : \na. Celcius to Fahrenheit. \nb. Fahrenheit to Celcius.") while True: option_ = input("Enter the option a or b : ").strip().lower() result = 0 if option_ == 'a': c = int(input("Enter the temperature in celcius : ").strip()) result = c * 1.8 + 32 print(f"{c} degree celcius is {result:.1f} in Fahrenheit") break elif option_ == 'b': f = int(input("Enter the temperature in fahrenheit : ").strip()) result = (f - 32) / 1.8 print(f"{f} degree fahrenheit is {result: .1f} in celcius.") break else: print(f'Sorry {option_} is not in the option')
617eef0a8d130abb7e6c2d0ea01b5a4707d02ac5
qirh/tic_tac_toe
/main.py
9,534
3.640625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys import copy from random import randint, shuffle class IllegalMove(Exception): pass class Player(): def __init__(self, char, name): self.char = char self.name = name def __repr__(self): return f'({self.char})' def __eq__(self, other): if isinstance(other, self.__class__): return self.__str__() == other.__str__() return False class Board: class Cell: def __init__(self, index): self.index = index self.player = None self.is_free = True def __repr__(self): if self.is_free: return f'({self.index})' else: return f'{self.player}' def __eq__(self, other): if isinstance(other, self.__class__): return self.__str__() == other.__str__() return False def __init__(self, size=3, difficulty=1): self._size = size self._board = [self.Cell(i) for i in range(size*size)] self.difficulty = difficulty self.list_of_random_moves = [i for i in range(size*size)] self.free_cells = len(self.list_of_random_moves) shuffle(self.list_of_random_moves) def __repr__(self): printed_board = '' printed_board += ' ' + '—'*self._size*6 + '\n' for row in range(self._size): printed_board += '| ' for col in range(self._size): printed_board += self._board[col+row*self._size].__str__() + ' | ' printed_board += '\n' printed_board += ' ' + '—'*self._size*6 return printed_board def make_move(self, move, player, test_board=None): free_cells = self.free_cells if test_board: board = test_board else: board = self._board if not self._is_move_legal(move, board): raise IllegalMove(f'move {move} is not allowed') board[move].is_free = False board[move].player = player free_cells -= 1 if not test_board: self.free_cells = free_cells return { 'move': move, **self.is_game_over(move, player, board), } def is_game_over(self, move, player, board): # 1. win # 1(a). row & col win for i in range(self._size): if move >= i*self._size and move < (i+1)*self._size: # check row victory row = [board[j] for j in range(i*self._size, (i+1)*self._size)] if all(cell==row[0] for cell in row): return { 'game_over': True, 'win': True, 'player': player, 'win_condition': 'row', 'index': i, } # check col victory first_row = move while first_row >= self._size: first_row -= self._size col = [board[k] for k in range(first_row, (self._size**2), self._size)] if all(cell==col[0] for cell in col): return { 'game_over': True, 'win': True, 'player': player, 'win_condition': 'col', 'index': first_row, } # 1(b). diagonal win if self._size%2 != 0: # only odd sized boards center = (self._size//2)*self._size + (self._size//2) if not board[center].is_free and board[center].player == player: # center # 2 cases: neg_slope = True pos_slope = True # a. negative slope up_left = center - self._size - 1 while up_left >= 0: if board[up_left].player != player: neg_slope = False break up_left -= self._size - 1 down_right = (center + self._size + 1) while neg_slope and down_right < (self._size**2): if board[down_right].player != player: neg_slope = False break down_right += self._size + 1 # b. positive slope up_right = center - self._size + 1 while up_right >= self._size-1: if board[up_right].player != player: pos_slope = False break up_right -= self._size + 1 down_left = (center + self._size - 1) while pos_slope and down_left < (self._size**2 - 1): if board[down_left].player != player: pos_slope = False break down_left += self._size - 1 if neg_slope or pos_slope: return { 'game_over': True, 'win': True, 'index': center, 'player': player, 'win_condition': 'center', } return { 'game_over': False, } # 2. not win, no more moves (tie) if self.free_cells <= 0: return { 'game_over': True, 'tie': True } # 3. no win, there are still moves (continue) return { 'game_over': False, } def _is_move_legal(self, move, board): try: return board[move].is_free except Exception as e: return False def test_win_move(self, move, player): test_board = [copy.deepcopy(cell) for cell in self._board] # deep copy return self.make_move(move, player, test_board) def computer_pick_move(self): if self.difficulty == 1: # easy for index, move in enumerate(self.list_of_random_moves[:]): try: result = self.make_move(move, COMPUTER) self.list_of_random_moves = self.list_of_random_moves[index:] result['move'] = move return result except IllegalMove: pass else: # https://mblogscode.wordpress.com/2016/06/03/python-naughts-crossestic-tac-toe-coding-unbeatable-ai/ # check computer win moves for move in range(self._size**2): if self._board[move].is_free and self.test_win_move(move, COMPUTER).get('win'): result = self.make_move(move, COMPUTER) result['move'] = move return result # check player win moves for move in range(self._size**2): if self._board[move].is_free and self.test_win_move(move, HUMAN).get('win'): result = self.make_move(move, COMPUTER) result['move'] = move return result # play a corner for move in [0, self._size-1, (self._size**2)-self._size, (self._size**2)-1]: if self._board[move].is_free: result = self.make_move(move, COMPUTER) result['move'] = move return result # play center if self._board[(self._size//2)*self._size + (self._size//2)].is_free: move = (self._size//2)*self._size + (self._size//2) result = self.make_move(move, COMPUTER) result['move'] = move return result # play side (only for size 3). boards with size>3 , play first free cell for move in range(len(board)): if self._board[move].is_free: result = self.make_move(move, COMPUTER) result['move'] = move return result HUMAN = Player('O', 'human') COMPUTER = Player('X', 'computer') PLAYERS = [HUMAN, COMPUTER] board = Board() def pick_char(): AASCII_LOWER_BOUND = 65 AASCII_LOWER_BOUND = 126 print(f'accepted chars are ascii[{AASCII_LOWER_BOUND}, {AASCII_LOWER_BOUND}]') for player in PLAYERS: human_input = input(f'the {player.name}\'s char is ({player.char}) enter a new char to change it or press enter to skip\n') if len(human_input) == 0: pass elif len(human_input) > 1 or ord(human_input) < AASCII_LOWER_BOUND or ord(human_input) > AASCII_LOWER_BOUND: print('invalid input, keeping default value') else: player.char = human_input def who_plays_first(players): random_pick = randint(0, len(players) - 1) print(f'{PLAYERS[random_pick].name} picked randomly to play first') return random_pick def welcome(): os.system('clear') print('welcome, to tic_tac_toe\n') print('please choose a difficulty') while True: print('1. Regular (default)') print('2. Unmöglich!\n') difficulty_parsed = 1 difficulty_input = input('>> ') if difficulty_input == '': break else: try: difficulty_parsed = int(difficulty_input) if difficulty_parsed not in [1, 2]: print(f'invalid entry ({difficulty_parsed}) should be either 1 or 2 or press enter to skip') else: print() break except ValueError: print(f'invalid entry ({difficulty_input}) is not an int') if sys.argv[1:] and '-skip_char' not in sys.argv[1:]: pick_char() chars = 'players will play with the following chars\n' for player in PLAYERS: chars += f'\t- {player.name} ({player.char})\n' print(chars) board.difficulty = difficulty_parsed play() def play(): turn_index = who_plays_first(PLAYERS) turn = PLAYERS[turn_index] while True: print(f'<<<{turn.name}\'s turn>>>') if turn.name == 'human': print(board) player_input = input('>> ') try: move = int(player_input) try: result = board.make_move(move, HUMAN) except IllegalMove: print('illegal move\n') continue except ValueError: print('invalid move\n') continue else: result = board.computer_pick_move() if result['game_over']: print(board) print('Game Over.', end=' ') if result.get('win'): print(f'{turn.name} has won. Winning {result["win_condition"]} @index #{result["index"]}') elif result.get('tie'): print('!tie!') break else: print(f'{turn.name} played at index {result["move"]}\n') turn_index = (turn_index + 1) % 2 turn = PLAYERS[turn_index] welcome()
b849934f1bdcc1e6394affa37c5b98b6dca2ba93
Tetsuya3850/DSA-Primitives
/ArraysStrings/shortest_sequentially_covering.py
1,189
3.640625
4
def smallest_sequentially_covering(paragraph, keywords): # Time O(N), Space O(M), where N is the length of the paragraph and M is the length of keywords keyword_to_idx = {k: i for i, k in enumerate(keywords)} latest_occurrence = [-1] * len(keywords) shortest_subarray_length = [float("inf")] * len(keywords) shortest_dist = float('inf') result = (-1, -1) for i, p in enumerate(paragraph): if p in keyword_to_idx: keyword_idx = keyword_to_idx[p] if keyword_idx == 0: shortest_subarray_length[keyword_idx] = 1 elif shortest_subarray_length[keyword_idx-1] != float('inf'): distance_to_previous_keyword = ( i - latest_occurrence[keyword_idx - 1]) shortest_subarray_length[keyword_idx] = distance_to_previous_keyword + \ shortest_subarray_length[keyword_idx-1] latest_occurrence[keyword_idx] = i if keyword_idx == len(keywords) - 1 and shortest_subarray_length[-1] < shortest_dist: shortest_dist = shortest_subarray_length[-1] result = (i-shortest_dist+1, i) return result
3b49b8fe287935488da4d2f3369f644011b851cc
poulomikhaiitm/Shinichi-Kudo
/minutes & seconds.py
221
3.6875
4
# -*- coding: utf-8 -*- """ Created on Fri May 17 13:54:03 2019 @author: shinichikudo """ N = int(input('Enter the value of Minutes = ')) P = int(input('Enter the value of seconds = ')) S = (N*60) + P print(S)
edd13442611e8bae82f91cc3805d68a503873f6a
Phys767-Spring17/Azmain_fizzbuzz
/fizzbuzz/fizzbuzz.py
397
4.15625
4
#def fizzbuzz(number): # <code here operates on number> # return <something> def fizzbuzz(number): if number % 3 == 0 and number % 5 == 0: return 'fizzbuzz' elif number % 3 == 0: # % means remainder after dividing by the following number return 'fizz' elif number % 5 == 0: # remainder from number/5 is zero return 'buzz' else: return number
1d25a17421d9fd3092579a5d38ef0376b7195232
XiangyuDing/Beginning-Python
/Beginning/python3_cookbook/ch02/06-ignorecase.py
601
4.53125
5
# 2.6 字符串忽略大小写的搜索替换 import re text = 'UPPER PYTHON, lower python, Mixed Python' print(re.findall('python', text, flags=re.IGNORECASE)) print(re.sub('python','snake',text, flags=re.IGNORECASE)) def matchcase(word): def replace(m): text = m.group() if text.isupper(): return word.upper() elif text.islower(): return word.lower() elif text[0].isupper(): return word.capitalize() else: return word return replace print(re.sub('python',matchcase('snake'),text,flags=re.IGNORECASE))
d28a2496e71fe7f63b5ed6e58b28b1b3747cf671
votus777/AI_study
/ML/m17_pipeline_iris_keras.py
2,415
3.578125
4
# iris를 케라스 파이프라인 구성 # 당연히 RandomizedSearchCV 구성 import numpy as np from keras.utils import np_utils from keras.models import Model from keras.layers import Input, Conv2D, Dropout, Flatten, Dense, MaxPool2D from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris from sklearn.pipeline import Pipeline, make_pipeline from sklearn.preprocessing import MinMaxScaler, StandardScaler # RandomizedSearchCV # 데이터 iris = load_iris() x = iris.data y = iris.target print(x.shape) # (150, 4) print(y.shape) # (150,) x_train, x_test, y_train, y_test = train_test_split(x,y, test_size = 0.2, shuffle=True, random_state = 58) y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) print(y_train.shape) # (60000, 10) print(y_train[0]) # [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] y_train = y_train[ :, 1:] y_test = y_test[ :, 1:] # 모델 def bulid_model(drop=0.5, optimizer = 'adam') : inputs = Input(shape=(150), name= 'inputs') # (786,) x = Dense(512, activation='relu', name= 'hidden1')(inputs) x = Dropout(drop)(x) x = Dense(256, activation='relu', name = 'hidden2')(x) x = Dropout(drop)(x) x = Dense(128, activation='relu', name = 'hidden3')(x) x = Dropout(drop)(x) outputs = Dense(4, activation='softmax', name= 'outputs')(x) model = Model(inputs = inputs, outputs = outputs) model.compile(optimizer=optimizer, metrics=['acc'], loss = 'categorical_crossentropy') return model def create_hyperparameters() : batches = [ 30, 40, 50] optimizers = ['rmsprop'] dropout = [0.1, 0.3,0.5 ] return{"models__batch_size" : batches, "models__optimizer": optimizers, "models__drop" : dropout } from keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor model = KerasClassifier(build_fn=bulid_model, verbose=1) pipe = Pipeline([("scaler", MinMaxScaler()), ("models", model)]) hyperparameters =create_hyperparameters() from sklearn.model_selection import GridSearchCV, RandomizedSearchCV search = RandomizedSearchCV(model, hyperparameters, cv=3 ) search.fit(x_train,y_train) from sklearn.model_selection import cross_val_score val_scores = cross_val_score(model,x_test,y_test, cv=3) acc = search.score(x_test,y_test) print(search.best_estimator_) print("val_scores : " ,val_scores) print( "acc : ", acc)
5610a4c02ec95d79e5c7b77ec7aa25e3fb355c5c
preethikarthi99/mysql
/mysql_crud.py
3,419
3.75
4
''' Created on Apr 20, 2017 @author: Preethi source: https://www.w3schools.com/python/python_mysql_insert.asp ''' #!/usr/bin/python import base64 import sys import codecs import MySQLdb def get_db(): db = MySQLdb.connect(host="localhost", # your host, usually localhost user="root", # your username passwd="Password1234", # your password db="preethi") # name of the data base return db def get_db_cursor(): db = MySQLdb.connect(host="localhost", # your host, usually localhost user="root", # your username passwd="Password1234", # your password db="preethi") # name of the data base # you must create a Cursor object. It will let # you execute all the queries you need return db.cursor() ''' Add customers ''' def add_customers(db, name, address): # you must create a Cursor object. It will let # you execute all the queries you need cur = db.cursor() # sql = "INSERT INTO customers (NAME, ADDRESS) VALUES (%s, %s)" values = (name, address) # Use all the SQL you like cur.execute(sql, values) db.commit() print('Done : '+str(cur.rowcount)+" inserted") ''' Update customers ''' def update_customers(db, name, address, id): # you must create a Cursor object. It will let # you execute all the queries you need cur = db.cursor() # sql = "UPDATE customers SET NAME = %s, ADDRESS = %s WHERE ID = %s" values = (name, address, id) # Use all the SQL you like cur.execute(sql, values) db.commit() print('Done : '+str(cur.rowcount)+" updated") read_customers(db) ''' Delete customers ''' def delete_customers(db, id): # you must create a Cursor object. It will let # you execute all the queries you need cur = db.cursor() # sql = "DELETE FROM customers WHERE ID = %s" values = (id, ) # Use all the SQL you like cur.execute(sql, values) db.commit() if(cur.rowcount == 0): raise Exception("Item Not Available to Delete") if(cur.rowcount > 1): raise Exception("More than one item deleted") print('Done : '+str(cur.rowcount)+" deleted") read_customers(db) ''' Read customers ''' def read_customers(db): cur = db.cursor() # Use all the SQL you like cur.execute("SELECT * FROM customers") # print all the first cell of all the rows counter = 0; for row in cur.fetchall(): try: counter = counter + 1 pid = str(row[0]) name = str(row[1]) address = str(row[2]) print(pid + " - " + name + " - " +address) except ValueError as error: print('Error', format(error)) def main(): db = get_db() # C - add customers add_customers(db, "Yuvi", "Perungalathur") # R - read customers read_customers(db) # U - update customers update_customers(db, "Swathi", "Tambaram", 6) # D - delete customers try: delete_customers(db, 7) except Exception as er: print("Error : ", format(er)) # close DB db.close() if __name__ == '__main__': main()
3926fe01aed39ab36596362396f2790bea6a1038
manpreet7688/LearningProjects
/map_filter_lambda.py
689
3.984375
4
def sequare(n): return n**2 my_list = [1,2,3,4] print(map(sequare, my_list)) def filter_ex(n): if n%2==0: return n my_list_filter = [1,2,3,4,5,6,7,8,9] print(filter(filter_ex, my_list_filter)) # Filter another example def splicer(name): if len(name)%2==0: return 'Even' else: return name[0] string_list = ["andy","liela", "rupalia"] for n in map(splicer, string_list): print(n) '''So while using lambda we do not need to use below mentioon function def check_num(num): if num%2==0: return "Even"''' '''Instaed write limbda directly''' my_integer_list = [1,2,3,4,5,6,7] print(filter(lambda num:num%2==0,my_integer_list))
b5a4e4e2a514e5273bf50aa5d4326555d8764b9f
sunnysong1204/61a-sp14-website
/slides/23.py
6,720
4.25
4
class Tree: """A Tree consists of a label and a sequence of 0 or more Trees, called its children.""" def __init__(self, label, *children): """A Tree with given label and children.""" self._label = label self._children = list(children) @property def is_leaf(self): return self.arity == 0 @property def label(self): return self._label @property def arity(self): """The number of my children.""" return len(self._children) def __iter__(self): """An iterator over my children.""" return iter(self._children) def __getitem__(self, k): """My kth child.""" return self._children[k] def set_child(self, k, val): """Set my Kth child to VAL, which should be a tree.""" self._children[k] = val def __str__(self): """My printed string representation (leaves print only their labels). >>> str(Tree(3, Tree(2), Tree(3), Tree(4, Tree(5), Tree(6)))) '(3 2 3 (4 5 6))' """ if self.is_leaf: return str(self.label) return "(" + str(self.label) + " " + \ " ".join(map(str, self)) + ")" def __repr__(self): """My string representation for the interpreter, etc. >>> Tree(3, Tree(2), Tree(3), Tree(4, Tree(5), Tree(6))) Tree:(3 2 3 (4 5 6))""" return "Tree:" + str(self) class BinTree(Tree): def __init__(self, label, left=None, right=None): Tree.__init__(self, label, left or BinTree.empty_tree, right or BinTree.empty_tree) # or super().__init__(label, left or ...) @property def is_empty(self): """This tree contains no labels or children.""" return self is BinTree.empty_tree @property def left(self): return self[0] @property def right(self): return self[1] def set_left(self, newval): """Assuming NEWVAL is a BinTree, sets SELF.left to NEWVAL.""" self.set_child(0, newval) def set_right(self, newval): """Assuming NEWVAL is a BinTree, sets SELF.right to NEWVAL.""" self.set_child(1, newval) # The empty binary tree. This definition is a placeholder, the # real definition is just below. (We can't call BinTree while its # still being defined.) empty_tree = None def preorder_values(self): """My labels, delivered in preorder (node label first, then labels of left child in preorder, then labels of right child in preorder. >>> T = BinTree(10, BinTree(5, BinTree(2), BinTree(6)), BinTree(15)) >>> for v in T.preorder_values(): ... print(v, end=" ") 10 5 2 6 15 >>> list(T.preorder_values()) [10, 5, 2, 6, 15]""" return tree_iter(self) def inorder_values(self): """An iterator over my labels in order. >>> T = BinTree(10, BinTree(5, BinTree(2), BinTree(6)), BinTree(15)) >>> for v in T.inorder_values(): ... print(v, end=" ") 2 5 6 10 15 """ return inorder_tree_iter(self) def __repr__(self): """A string representing me (used by the interpreter). >>> T = BinTree(10, BinTree(5, BinTree(2), BinTree(6)), BinTree(15)) >>> T {2, 5, 6, 10, 15}""" return "{" + ', '.join(map(repr, self.inorder_values())) + "}" # Or, the long way: # result = "{" # for v in self.inorder_values(): # if result != "{": # result += ", " # result += repr(v) # return result + "}" def __str__(self): return self.repr() # Make BinTree.empty_tree be an arbitrary node with no children BinTree.empty_tree = BinTree(None) class tree_iter: def __init__(self, the_tree): self._work_queue = [ the_tree ] def __next__(self): while len(self._work_queue) > 0: subtree = self._work_queue.pop(0) # Get first item if subtree.is_empty: pass else: self._work_queue[0:0] = subtree.left, subtree.right return subtree.label raise StopIteration def __iter__(self): return self # Alternative implementation, adding and removing from the end of the # work queue instead of the beginning: class tree_iter: def __init__(self, the_tree): self._work_queue = [ the_tree ] def __next__(self): while len(self._work_queue) > 0: subtree = self._work_queue.pop() if subtree.is_empty: pass else: self._work_queue += subtree.right, subtree.left # Reversed! return subtree.label raise StopIteration def __iter__(self): return self class inorder_tree_iter: def __init__(self, the_tree): # As suggested previously, we'll keep work_queue in the # reverse of the order it needs to be processed for speed. self._work_queue = [ the_tree ] def __next__(self): # What goes here? raise StopIteration def __iter__(self): return self def dtree_add(T, x): """Assuming T is a binary search tree, a binary search tree that contains all previous values in T, plus X (if not previously present). May destroy the initial contents of T.""" if T.is_empty: return BinTree(x) elif x == T.label: return T elif x < T.label: T.set_left(dtree_add(T.left, x)) return T else: T.set_right(dtree_add(T.right, x)) return T def intersection(s1, s2): """A binary search tree containing the values that are in both search trees S1 and S2. >>> T1 = BinTree(9, BinTree(3, BinTree(0), BinTree(6)), ... BinTree(15, BinTree(12), BinTree(18))) >>> T2 = BinTree(10, BinTree(6, BinTree(4, BinTree(2)), ... BinTree(8)), ... BinTree(14, BinTree(12), BinTree(18, BinTree(16)))) >>> T1 {0, 3, 6, 9, 12, 15, 18} >>> T2 {2, 4, 6, 8, 10, 12, 14, 16, 18} >>> intersection(T1, T2) {6, 12, 18} """ it1, it2 = s1.inorder_values(), s2.inorder_values() v1, v2 = next(it1, None), next(it2, None) result = BinTree.empty_tree while v1 is not None and v2 is not None: if v1 == v2: result = dtree_add(result, v1) v1, v2 = next(it1, None), next(it2, None) elif v1 < v2: v1 = next(it1, None) else: v2 = next(it2, None) return result
fddb068475712fd6d2f1fcfd78f5e2ef3ec365af
shubham-debug/Python-Programs
/WinningStrategy.py
657
3.578125
4
#winning strategy def solve(arr): p1=0 p2=0 arr.sort(reverse=True) p1=arr[0] if(len(arr)>=3): p2=arr[1]+arr[2] elif(len(arr)==2): p2=arr[1] count=3 while(count<len(arr)): p1+=arr[count] count+=2 count=4 while(count<len(arr)): p2+=arr[count] count+=2 if(p1>p2): return 'first' elif(p2>p1): return 'second' return 'draw' if __name__=="__main__": t=int(input()) for test in range(t): n=int(input()) arr=[int(i) for i in input().split()] print(solve(arr))
dbdeb5ef53af84fd9bc0d8d01765b04d6935a1f8
richakbee/Back-Order-Prediction
/Data_preprocessing_prediction/preprocessing.py
14,785
3.515625
4
import csv import pickle from datetime import datetime import os import numpy import pandas import sklearn from sklearn.impute import _knn class preprocessing: """ This class shall be used to clean and transform the data before training. Written By: richabudhraja8@gmail.com Version: 1.0 Revisions: None """ def __init__(self, logger_object, file_object): self.file_obj = file_object self.log_writer = logger_object def remove_columns(self, data, column_list): """ Method Name: remove_columns Description: TThis method removed the the columns in the column list from the data. Output: Returns A pandas data frame. On Failure: Raise Exception Written By: richabudhraja8@gmail.com Version: 1.0 Revisions: None """ self.log_writer.log(self.file_obj, "Entered remove_columns of preprocessing class!!") try: new_data = data.drop(columns=column_list, axis=1) self.log_writer.log(self.file_obj, "Column removal Successful.Exited the remove_columns method of the Preprocessor class!!") return new_data except Exception as e: self.log_writer.log(self.file_obj, 'Exception occurred in remove_columns method of the Preprocessor class!! Exception message:' + str( e)) self.log_writer.log(self.file_obj, 'removing columns from data failed.Error in remove_columns method of the Preprocessor class!!') raise e def is_null_present(self, X): """ Method Name: is_null_present Description: This method takes input as dataframe . and tells if there are nulls in any column Output: Returns boolean yes or no .if yes then a csv will be stored will count of null for each column at location "preprocessing_data/null_values.csv". Also returns a list of column names with null values On Failure: Raise Exception Written By: richabudhraja8@gmail.com Version: 1.0 Revisions: None """ null_df_loc = "preprocessing_data/" self.log_writer.log(self.file_obj, "Entered is_null_present in class preprocessing. Checking for null values in training data") bool_value = False columns_with_null = [] now = datetime.now() date = now.date() time = now.strftime("%H%M%S") try: count_null = X.isnull().sum() for count_ in count_null: if count_ > 0: bool_value = True break if bool_value: null_df = pandas.DataFrame(count_null).reset_index().rename( columns={'index': 'col_name', 0: 'no_of_nulls'}) file_name = 'null_values_prediction' + str(date) + "_" + str(time) + '.csv' dest = os.path.join(null_df_loc, file_name) if not os.path.isdir(dest): null_df.to_csv(dest, index=False, header=True) # list of columns that has null values columns_with_null = list(null_df[null_df['no_of_nulls'] > 0]['col_name'].values) self.log_writer.log(self.file_obj, "Finding missing values is a success.Data written to the null values file at {}. Exited the is_null_present method of the Preprocessor class".format( null_df_loc)) return bool_value, columns_with_null except Exception as e: self.log_writer.log(self.file_obj, 'Exception occurred in is_null_present method of the Preprocessor class. Exception message: ' + str( e)) self.log_writer.log(self.file_obj, 'Finding missing values failed. Exited the is_null_present method of the Preprocessor class') raise e def get_col_with_zero_std_deviation(self, X): """ Method Name: get_col_with_zero_std_deviation Description: TThis method finds out the columns which have a standard deviation of zero. Output: Returns A list of all coulmns which have a standard deviation of zero. On Failure: Raise Exception Written By: richabudhraja8@gmail.com Version: 1.0 Revisions: None """ self.log_writer.log(self.file_obj, "Entered get_col_with_zero_std_deviation of preprocessing class!!") try: # get the standard deviation of all columns as data frame , where index is column name . std_columns = pandas.DataFrame(X.describe().loc['std']) col_list = std_columns[std_columns['std'] == 0].index.to_list() self.log_writer.log(self.file_obj, "Column search for Standard Deviation of Zero Successful. Exited the get_columns_with_zero_std_deviation method of the Preprocessor class!!") return col_list except Exception as e: self.log_writer.log(self.file_obj, 'Exception occurred in get_col_with_zero_std_deviation method of the Preprocessor class!! Exception message:' + str( e)) self.log_writer.log(self.file_obj, 'fetching column list with standard deviation of zero failed. get_col_with_zero_std_deviation method of the Preprocessor class!!') raise e def encode_categorical_columns_from_mapping_file(self, data, categorical_columns): """ Method Name: ensure_categorical_data_type Description: TThis method uses list of the columns which have categorical value & the data and encodes the categorical columns using mapping file encoded during training . Output: Returns data with categorical columns encoded . Save the dictionary used for mapping On Failure: Raise Exception Written By: richabudhraja8@gmail.com Version: 1.0 Revisions: None """ dict_mapping_file_loc = 'preprocessing_data/encoding_mapping_csv_file.csv' self.log_writer.log(self.file_obj, "Entered encode_categorical_columns of preprocessing class!!") try: # reading the dictionary encoding_dic = {} with open(dict_mapping_file_loc) as f: reader = csv.DictReader(f) for row in reader: encoding_dic = row # using the dictionary to encode the data in data frame for col in categorical_columns: val_dic = eval(encoding_dic[col]) # value was dictionary within a string . removing the string type data[col] = data[col].apply(lambda x: int(val_dic[ x])) # by default it takes as float. will create an issue in Ml algorithms if target columns/label is float not integer self.log_writer.log(self.file_obj, "Encoding successful. Exited encode_categorical_columns of preprocessing class!!") return data except Exception as e: self.log_writer.log(self.file_obj, 'Exception occurred in encode_categorical_columns method of the Preprocessor class!! Exception message:' + str( e)) self.log_writer.log(self.file_obj, 'Encoding categorical features failed. Exited encode_categorical_columns method of the Preprocessor class!!') raise e def scale_numerical_columns_from_training_Scaler(self, data, categorical_columns): """ Method Name: scale_numerical_columns Description: This method get a data frame,& list of categorical columns in the daat & finds the numerical columns and scale them using standard scaler() of preprocessing from sklearn, that was saved during training from location "preprocessing_data/standardScaler.pkl" (ENSURE THE DTYPE OF SUCH COLUMNS TO BE CATEGORICAL ELSE RESULTS IN UNEXPECTED BEHAVIOUR.) Output: Returns data with numerical columns scaled while categorical columns as is. On Failure: Raise Exception Written By: richabudhraja8@gmail.com Version: 1.0 Revisions: None """ scaler_path = 'preprocessing_data/StandardScaler.pkl' self.log_writer.log(self.file_obj, "Entered scale_numerical_columns of preprocessing class!!") try: # find the numerical columns numerical_col_list = list(numpy.setdiff1d(list(data.columns), categorical_columns)) # get data frames for tarin & test df_ = data[numerical_col_list] # define standard scaler object scaler = pickle.load(open(scaler_path, 'rb')) # fitting the scaler on train set scaled_data = scaler.transform(df_) # scaled data is a array convert back to data frame scaled_df_ = pandas.DataFrame(scaled_data, columns=df_.columns, index=df_.index) self.log_writer.log(self.file_obj, "Scaling numerical columns successful.Exited scale_numerical_columns of preprocessing class!!") return scaled_df_ except Exception as e: self.log_writer.log(self.file_obj, 'Exception occurred in scale_numerical_columns method of the Preprocessor class!! Exception message:' + str( e)) self.log_writer.log(self.file_obj, 'Scaling numerical columns failed. Exited scale_numerical_columns method of the Preprocessor class!!') raise e def impute_Categorical_values(self, data, columns_with_null): """ Method Name: impute_Categorical_values Description: TThis method get list of the columns which have categorical value & has nulls cin the columns. it imputes the null with mode of the column Output: Returns data with imputed value inplace of nulls On Failure: Raise Exception Written By: richabudhraja8@gmail.com Version: 1.0 Revisions: None """ self.log_writer.log(self.file_obj, "Entered impute_Categorical_values of preprocessing class!!") try: for col in columns_with_null: # only for category columns in list of columns that has null values , fill them with mode if ((data[col].dtypes) == 'object') or ((data[col].dtypes) == 'category'): data[col].fillna(data[col].mode().values[0], inplace=True) self.log_writer.log(self.file_obj, "imputing null value in categorical features successful. Exited the impute_Categorical_values method of the Preprocessor class!!") return data except Exception as e: self.log_writer.log(self.file_obj, 'Exception occurred in impute_Categorical_values method of the Preprocessor class!! Exception message:' + str( e)) self.log_writer.log(self.file_obj, 'imputing null value in categorical features failed. impute_Categorical_values method of the Preprocessor class!!') raise e def one_hot_encode_cagtegorical_col(self, data, categorical_features): df_cat = data[categorical_features].copy() #temporary fix to issue , needs sophisticated fix for col in categorical_features: unique_val = len(list(df_cat[col].unique())) if unique_val > 1: df_cat = pandas.get_dummies(df_cat, columns=[col], prefix=[col], drop_first=True) else: df_cat.rename(columns={str(col): str(col) + '_' + str(unique_val)}, inplace=True) return df_cat def pcaTransformation(self, X_num_scaled): """ Method Name: scale_numerical_columns Description: this method is used to perform pca transformation Output: Returns data with pca columns. On Failure: Raise Exception Written By: richabudhraja8@gmail.com Version: 1.0 Revisions: None """ pca_obj_loc = 'preprocessing_data/pca.pkl' self.log_writer.log(self.file_obj, "Entered pcaTransformation of preprocessing class!!") try: # define standard scaler object pca = pickle.load(open(pca_obj_loc , 'rb')) # fitting the scaler on train set pca_data = pca.transform(X_num_scaled) # scaled data is a array convert back to data frame pca_num_components = pca.n_components_ column_names = ['PC-' + str(i + 1) for i in range(pca_num_components)] X_num_pca = pandas.DataFrame(pca_data, columns=column_names, index=X_num_scaled.index) self.log_writer.log(self.file_obj, "pcaTransformation successful.Exited pcaTransformation of preprocessing class!!") return X_num_pca except Exception as e: self.log_writer.log(self.file_obj, 'Exception occurred in pcaTransformation method of the Preprocessor class!! Exception message:' + str( e)) self.log_writer.log(self.file_obj, 'pcaTransformation failed. Exited spcaTransformation method of the Preprocessor class!!') raise e pass
668d2562096b9cefabab411ec5922a4219b2712a
Koozzi/Algorithms
/SAMSUNG/SWEA/PROBLEM/1949_등산로조정_20210419.py
1,820
3.546875
4
from collections import deque def get_highest(): highest = 0 for i in range(N): for j in range(N): highest = max(highest, board[i][j]) return highest def get_start_index(highest): start_index = [] for i in range(N): for j in range(N): if board[i][j] == highest: start_index.append([i, j]) return start_index def dijkstra(start_i, start_j): depth = [[0 for _ in range(N)] for _ in range(N)] depth[start_i][start_j] = 1 q = deque([[start_i, start_j]]) max_depth = 1 while q: current_i, current_j = q.popleft() for di, dj in [[0, 1], [0, -1], [1, 0], [-1, 0]]: next_i = current_i + di next_j = current_j + dj if 0 <= next_i < N and 0 <= next_j < N: if board[next_i][next_j] < board[current_i][current_j]: if depth[next_i][next_j] < depth[current_i][current_j] + 1: depth[next_i][next_j] = depth[current_i][current_j] + 1 q.append([next_i, next_j]) max_depth = max(max_depth, depth[next_i][next_j]) return max_depth T = int(input()) for t in range(1, T+1): N, K = map(int, input().split()) board = [list(map(int, input().split())) for _ in range(N)] highest = get_highest() start_index = get_start_index(highest) answer = 0 for k in range(K + 1): for i in range(N): for j in range(N): board[i][j] -= k for si, sj in start_index: answer = max(answer, dijkstra(si, sj)) board[i][j] += k print("#{} {}".format(t, answer)) """ 2 5 1 9 3 2 3 2 6 3 1 7 5 3 4 8 9 9 2 3 7 7 7 7 6 5 5 8 3 2 1 2 1 2 1 2 1 2 1 """
f6a1a274dfc0fa0f79992316e690d5129351badf
jasonfreak/arena
/1025/250/main.py
1,381
3.640625
4
class PeacefulLine(object): def __init__(self): object.__init__(self) def check(self, y): last = y[0] for student in y[1:]: if student == last: return 'impossible' last = student return 'possible' def makeLine(self, x): cntOfStudent = len(x) heights = {} for student in x: heights[student] = heights.get(student, 0) + 1 sortedHeights = sorted(heights.keys(), key=lambda x: heights[x], reverse=True) # print 'debug[20]', heights, sortedHeights y = [None] * cntOfStudent index = range(cntOfStudent) for height in sortedHeights: cntOfIndex = len(index) step = (cntOfIndex + 1) / heights[height] # print 'debug[27]', step for i in range(cntOfIndex): if i % step == 0: y[index[i]] = height index[i] = -1 index = filter(lambda x: x >= 0, index) # print 'debug[32]', y return self.check(y) def main(): obj = PeacefulLine() print obj.makeLine((1, 2, 3, 4)) print obj.makeLine((1, 1, 1, 2)) print obj.makeLine((1,1,2,2,3,3,4,4)) print obj.makeLine((3,3,3,3,13,13,13,13,3)) if __name__ == '__main__': main()
2d67e53e3d6230ea087082e57cd3babf22c11517
hwillmott/csfundamentals
/leetcode/257_binarytreepaths.py
789
3.6875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {string[]} def binaryTreePaths(self, root): def getPath(root, stringsofar, result): if root.left is None and root.right is None: result.append(stringsofar + str(root.val)) return if root.left is not None: getPath(root.left, stringsofar + str(root.val) + "->", result) if root.right is not None: getPath(root.right, stringsofar + str(root.val) + "->", result) result = [] if root is not None: getPath(root, "", result) return result
832c5102ccc2b4ea516737d5c0d5d8cceefda0b9
fjguaita/codesignal
/Arcade/Intro/47_isMAC48Address.py
646
3.703125
4
import re def isMAC48Address(s): if len(s)!=17: return False for i in s.split('-'): if "".join(re.findall('[0-9A-F]',i))!=i: return False return True if len(s.split('-'))==6 else False def isMAC48Address(s): return bool(re.match(('^' + '[\dA-F]{2}-' * 6)[:-1] + '$', s)) def isMAC48Address(inputString): return re.match("^([0-9A-F]{2}-){5}[0-9A-F]{2}$", inputString) is not None def isMAC48Address(inputString): return bool(re.match('^([0-9A-F]{2}-){5}([\dA-F]{2})$', inputString)) s="00-1B-63-84-45-E6" s1="Z1-1B-63-84-45-E6" s2="not a MAC-48 address"
87a0492db1130a7e9fe89e5d21f40d7d498ea71a
bramvanulden/programming
/Les6/pe6_4.py
697
3.6875
4
i = False def new_password(x, y): if x not in y: if len(y) >= 6: for c in y: if c in "0123456789": i = True if i == True: print("Uw wachtwoord is succesvol veranderd.") else: print("Uw wachtwoord moet minimaal 1 cijfer bevatten.") else: print("Uw nieuwe wachtwoord moet minimaal 6 tekens bevatten.") else: print("Uw nieuwe wachtwoord mag niet hetzelfde zijn als uw oude wachtwoord.") oldpassword = input("Uw oude wachtwoord: ") newpassword = input("Uw nieuwe wachtwoord: ") new_password(oldpassword, newpassword)
435c7edab2f4dba0e99c01480e6edeb43df906dd
rafaelperazzo/programacao-web
/moodledata/vpl_data/415/usersdata/296/86505/submittedfiles/exe11.py
222
3.65625
4
# -*- coding: utf-8 -*- n = int(input("Digite um número: ")) soma = 0 while (n > 0): if 10000000 <= n <= 99999999: resto = n%10 n = (n-resto)/10 soma = soma + resto print(soma)
87d3d3720a69fab9dea3045810a52cd2ca87e800
l0uvre/CS50-2017
/pset6/caesar.py
640
3.78125
4
import sys def main(): if len(sys.argv) != 2: print("Usage: ./caesar k\n") exit(1) else: pText = input("plaintext: ") print("ciphertext: ", end = "") key = int(sys.argv[1]) for char in pText: if char.isalpha(): if char.islower(): print("{}".format(chr((ord(char) + key - 97) % 26 + 97)), end = "") else: print("{}".format(chr((ord(char) + key - 65) % 26 + 65)), end = "") else: print(char, end = "") print() exit(0) if __name__ == '__main__': main()
ac798dc7ff51c3c60079a7674b4d4aff2314a815
Bill-Portugues/Proyect-Euler---Python
/28 - Number spiral diagonals.py
309
3.546875
4
def SpiralWaves(number): layers=int((number+1)/2) OriginalNum=1 sum=1 step=2 for x in range(1,layers,1): for y in range(1,5,1): sum += OriginalNum + step*y OriginalNum += step*4 step+=2 print (sum) SpiralWaves(1001)
44c1c5287f51ce880dcf328e17f2652ecdc6512f
rohit18259/Rummy
/rummy/rummy.py
16,049
3.921875
4
import pygame import random import time import itertools ### This is an indian rummy game. # we will have 1 pure sequence of 4 cards, 1 sequence of 3 cards, and 2 sets of 3 cards each. # you have to arrange the cards in the following sequences and sets in the order as given by the marking on the game screen. # you have to arrange your cards in the above criteria and in each frame, the program will automatically parse your given card pattern and see if it is in the desired format to win. # if you do so , you will win , given that you finish your steps within 10 minutes of the starting of the game. # if you dont finish it within 10 minutes, you will lose and PC will win. # the rules of a sequence and set is givem in the readme.txt file. v1=(32,580) v2=(144,580) v3=(256,580) v4=(368,580) v5=(480,580) v6=(592,580) v7=(702,580) v8=(816,580) v9=(928,580) v10=(1040,580) v11=(1152,580) v12=(1264,580) v13=(1376,580) decv=(550,200) disv=(870,200) def funcsuit(x): return x.suit def differentsuit(l): z=sorted(l,key=funcsuit) for i in range(len(l)-1): if z[i].suit==z[i+1].suit: return False else: return True def funcvalue(x): return x.value def differentvalue(l): z=sorted(l,key=funcvalue) for i in range(len(l)-1): if z[i].value==z[i+1].value: return False else: return True def ordervalue(x): if x.value=="ace": return 1 elif x.value=="jack": return 11 elif x.value=="queen": return 12 elif x.value=="king": return 13 elif x.value=="red": return -1 elif x.value=="black": return -1 elif x.value=="deck": return -1 else: return int(x.value) class card: def __init__(self,name,x=0,y=0,index=0): self.name=name self.x=x self.y=y self.index=index if '_' in name: self.value=name[:name.index('_')] self.suit=name[name.rindex('_')+1:] else: self.value="deck" self.suit="deck" def show(self,win): img=pygame.image.load(r"newcards/"+self.name+".png") s=pygame.Surface((80,122)) s.fill((255,255,255)) s.blit(img,(0,0)) win.blit(s,(self.x,self.y)) def showback(self,win): img=pygame.image.load(r"newcards/deck.png") s=pygame.Surface((80,122)) s.fill((255,255,255)) s.blit(img,(0,0)) win.blit(s,(self.x,self.y)) background=pygame.image.load(r"background.png") _2_clubs=card("2_of_clubs") _2_diamonds=card("2_of_diamonds") _2_hearts=card("2_of_hearts") _2_spades=card("2_of_spades") _3_clubs=card("3_of_clubs") _3_diamonds=card("3_of_diamonds") _3_hearts=card("3_of_hearts") _3_spades=card("3_of_spades") _4_clubs=card("4_of_clubs") _4_diamonds=card("4_of_diamonds") _4_hearts=card("4_of_hearts") _4_spades=card("4_of_spades") _5_clubs=card("5_of_clubs") _5_diamonds=card("5_of_diamonds") _5_hearts=card("5_of_hearts") _5_spades=card("5_of_spades") _6_clubs=card("6_of_clubs") _6_diamonds=card("6_of_diamonds") _6_hearts=card("6_of_hearts") _6_spades=card("6_of_spades") _7_clubs=card("7_of_clubs") _7_diamonds=card("7_of_diamonds") _7_hearts=card("7_of_hearts") _7_spades=card("7_of_spades") _8_clubs=card("8_of_clubs") _8_diamonds=card("8_of_diamonds") _8_hearts=card("8_of_hearts") _8_spades=card("8_of_spades") _9_clubs=card("9_of_clubs") _9_diamonds=card("9_of_diamonds") _9_hearts=card("9_of_hearts") _9_spades=card("9_of_spades") _10_clubs=card("10_of_clubs") _10_diamonds=card("10_of_diamonds") _10_hearts=card("10_of_hearts") _10_spades=card("10_of_spades") ace_clubs=card("ace_of_clubs") ace_diamonds=card("ace_of_diamonds") ace_hearts=card("ace_of_hearts") ace_spades=card("ace_of_spades") jack_clubs=card("jack_of_clubs") jack_diamonds=card("jack_of_diamonds") jack_hearts=card("jack_of_hearts") jack_spades=card("jack_of_spades") king_clubs=card("king_of_clubs") king_diamonds=card("king_of_diamonds") king_hearts=card("king_of_hearts") king_spades=card("king_of_spades") queen_clubs=card("queen_of_clubs") queen_diamonds=card("queen_of_diamonds") queen_hearts=card("queen_of_hearts") queen_spades=card("queen_of_spades") black_joker=card("black_joker") red_joker=card("red_joker") deck_=card("deck") lv=[v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13] dv=[decv,disv] cv=lv+dv cardlist=[_2_clubs,_2_diamonds,_2_hearts,_2_spades,_3_clubs,_3_diamonds,_3_hearts,_3_spades,_4_clubs,_4_diamonds,_4_hearts,_4_spades,_5_clubs,_5_diamonds,_5_hearts,_5_spades,_6_clubs,_6_diamonds,_6_hearts,_6_spades,_7_clubs,_7_diamonds,_7_hearts,_7_spades,_8_clubs,_8_diamonds,_8_hearts,_8_spades,_9_clubs,_9_diamonds,_9_hearts,_9_spades,_10_clubs,_10_diamonds,_10_hearts,_10_spades,ace_clubs,ace_diamonds,ace_hearts,ace_spades,jack_clubs,jack_diamonds,jack_hearts,jack_spades,king_clubs,king_diamonds,king_hearts,king_spades,queen_clubs,queen_diamonds,queen_hearts,queen_spades,black_joker,red_joker] print(len(cardlist)) def shuffle(l): z=list(l) n=len(z) for i in range(n): j=random.randint(0,n-1) z[i],z[j]=z[j],z[i] return z final=shuffle(cardlist) cardlist=final[:13] cpcardlist=final[13:26] deck=final[26:-1] discard=[final[-1]] discard[0].x=870 discard[0].y=200 discard[0].index=15 print(len(deck)) for i in range(13): cls=cardlist[i] cls.x=lv[i][0] cls.y=lv[i][1] cls.index=i+1 for i in deck: cls=i cls.x=550 cls.y=200 cls.index=14 def transprect(x,y,width,length): s=pygame.Surface((width,length)) s.set_alpha(50) s.fill((255,255,0)) win.blit(s,(x,y)) def oncardtrue(posx,posy): for i in cv: if i[0]<=posx<=i[0]+80 and i[1]<=posy<=i[1]+122: return True else: return False def inplaying_discard(posx,posy): for i in lv+[disv]: if i[0]<=posx<=i[0]+80 and i[1]<=posy<=i[1]+122: return True else: return False def fetchcard(posx,posy): global num_deck,num_discard if decv[0]<=posx<=decv[0]+80 and decv[1]<=posy<=decv[1]+122: if num_deck>=1: c=deck[-1] # deck.pop() num_deck=len(deck) print(num_deck) return c else: return False elif disv[0]<=posx<=disv[0]+80 and disv[1]<=posy<=disv[1]+122: c=discard[-1] return c else: for i in lv: if i[0]<=posx<=i[0]+80 and i[1]<=posy<=i[1]+122: c=cardlist[lv.index(i)] return c def reshuffle(deck,discard): green=(0,255,0) blue=(0,0,255) a=time.time() pygame.font.init() font=pygame.font.Font('freesansbold.ttf',32) text=font.render('reshuffling',True,green,blue) textrect=text.get_rect() textrect.center=(750,400) while time.time()-a<=4: win.blit(text,textrect) pygame.display.update() def drawtext(string,x,y,colort,colorb): pygame.font.init() font=pygame.font.Font('freesansbold.ttf',32) text=font.render(string,True,colort,colorb) textrect=text.get_rect() textrect.x,textrect.y=x,y win.blit(text,textrect) def validflife(l): winn=1 flife=l if flife[0].suit==flife[1].suit==flife[2].suit==flife[3].suit: winn=winn else: winn=0 a1,b1,c1,d1=flife[0],flife[1],flife[2],flife[3] z1=[ordervalue(a1),ordervalue(b1),ordervalue(c1),ordervalue(d1)] if z1[0]==-1 or z1[1]==-1 or z1[2]==-1 or z1[3]==-1: winn=0 else: winn=winn if z1[0]-z1[1]==-1 and z1[1]-z1[2]==-1 and z1[2]-z1[3]==-1: winn=winn else: winn=0 if winn==1: return True else: return False def validllife(l): winn=1 llife=l for i in llife: if ordervalue(i)==-1: llife.remove(i) if len(llife)<=1: winn=winn else: for i in range(len(llife)-1): if llife[i].suit==llife[i+1].suit: winn=winn else: winn=0 z2=[ordervalue(i) for i in llife] for i in range(len(z2)-1): if z2[i+1]-z2[i]==1: winn=winn else: winn=0 if winn==1: return True else: return False def validset1(l): winn=1 set1=l a3,b3,c3=set1[0],set1[1],set1[2] if differentsuit([a3,b3,c3]): winn=winn else: winn=0 z3=[ordervalue(a3),ordervalue(b3),ordervalue(c3)] for i in z3: if i==-1: z3.remove(i) if len(set(z3))==1: winn=winn else: winn=0 if winn==1: return True else: return False def validset2(l): winn=1 set2=l a4,b4,c4=set2[0],set2[1],set2[2] if differentsuit([a4,b4,c4]): winn=winn else: winn=0 z4=[ordervalue(a4),ordervalue(b4),ordervalue(c4)] for i in z4: if i==-1: z4.remove(i) if len(set(z4))==1: winn=winn else: winn=0 if winn==1: return True else: return False def cparrangecard(l): global cpcardlist var=False n=len(l) if not validflife(l[0:4]): z=itertools.permutations(l,4) for i in z: i=list(i) i1=i.copy() if validflife(i1): l.remove(i[0]) l.remove(i[1]) l.remove(i[2]) l.remove(i[3]) if len(l)==10: newc=l.pop() newc.x,newc.y=disv[0],disv[1] newc.index=15 discard.append(newc) l=i+l cpcardlist=l var=True return var elif not validllife(l[4:7]): z=itertools.permutations(l[4:],3) for i in z: i=list(i) i1=i.copy() if validllife(i1): l.remove(i[0]) l.remove(i[1]) l.remove(i[2]) if len(l)==11: newc=l.pop() newc.x,newc.y=disv[0],disv[1] newc.index=15 discard.append(newc) l=l[0:4]+i+l[7:] cpcardlist=l var=True return var elif not validset1(l[7:10]): z=itertools.permutations(l[7:],3) for i in z: i=list(i) i1=i.copy() if validset1(i1): l.remove(i[0]) l.remove(i[1]) l.remove(i[2]) if len(l)==11: newc=l.pop() newc.x,newc.y=disv[0],disv[1] newc.index=15 discard.append(newc) l=l[0:7]+i+l[10:] cpcardlist=l var=True return var elif not validset2(l[10:13]): z=itertools.permutations(l[10:],3) for i in z: i=list(i) i1=i.copy() if validset2(i1): l.remove(i[0]) l.remove(i[1]) l.remove(i[2]) if len(l)==11: newc=l.pop() newc.x,newc.y=disv[0],disv[1] newc.index=15 discard.append(newc) l=l[0:10]+i+l[13] cpcardlist=l var=True return var if len(l)==14: l.pop() cpcardlist=l return var def playerwin(cardlist): winn=1 flife=cardlist[0:4] if flife[0].suit==flife[1].suit==flife[2].suit==flife[3].suit: winn=winn else: winn=0 a1,b1,c1,d1=flife[0],flife[1],flife[2],flife[3] z1=[ordervalue(a1),ordervalue(b1),ordervalue(c1),ordervalue(d1)] if z1[0]==-1 or z1[1]==-1 or z1[2]==-1 or z1[3]==-1: winn=0 else: winn=winn if z1[0]-z1[1]==-1 and z1[1]-z1[2]==-1 and z1[2]-z1[3]==-1: winn=winn else: winn=0 if winn==1: print("flife sequence true") llife=cardlist[4:7] for i in llife: if ordervalue(i)==-1: llife.remove(i) if len(llife)<=1: winn=winn else: for i in range(len(llife)-1): if llife[i].suit==llife[i+1].suit: winn=winn else: winn=0 z2=[ordervalue(i) for i in llife] for i in range(len(z2)-1): if z2[i+1]-z2[i]==1: winn=winn else: winn=0 if winn==1: print("llife sequence true") set1=cardlist[7:10] a3,b3,c3=set1[0],set1[1],set1[2] if differentsuit([a3,b3,c3]): winn=winn else: winn=0 z3=[ordervalue(a3),ordervalue(b3),ordervalue(c3)] for i in z3: if i==-1: z3.remove(i) if len(set(z3))==1: winn=winn else: winn=0 if winn==1: print("set1 true") set2=cardlist[10:13] a4,b4,c4=set2[0],set2[1],set2[2] if differentsuit([a4,b4,c4]): winn=winn else: winn=0 z4=[ordervalue(a4),ordervalue(b4),ordervalue(c4)] for i in z4: if i==-1: z4.remove(i) if len(set(z4))==1: winn=winn else: winn=0 if winn==1: print("set2 true") if winn==1: return True else: return False def cpwin(cpcardlist): return playerwin(cpcardlist) def cpplay(cpcardlist): if cparrangecard(cpcardlist+[discard[-1]])==True: return else: cparrangecard(cpcardlist+[deck[-1]]) def displayplayerwin(): red=(255,0,0) yellow=(255,255,0) a=time.time() pygame.font.init() font=pygame.font.Font('freesansbold.ttf',32) text=font.render('PLAYER WINS!! :)',True,red,yellow) textrect=text.get_rect() textrect.center=(750,400) while time.time()-a<=4: win.blit(text,textrect) pygame.display.update() def displaycpwin(): red=(255,0,0) yellow=(255,255,0) a=time.time() pygame.font.init() font=pygame.font.Font('freesansbold.ttf',32) text=font.render('COMPUTER WINS!',True,red,yellow) textrect=text.get_rect() textrect.center=(750,400) while time.time()-a<=4: win.blit(text,textrect) pygame.display.update() start=time.time() re=0 deck_.x=550 deck_.y=200 deck_.index=14 # deck pile index = 14 # discard pile index = 15 num_deck=27 num_discard=1 up=True Down=False count=0 fetch=False win=pygame.display.set_mode((1500,800)) pygame.display.set_caption("Rummy Game") run=True while run: pygame.time.delay(20) for event in pygame.event.get(): if event.type==pygame.QUIT: run=False pos=pygame.mouse.get_pos() posx,posy=pos[0],pos[1] if fetch==True and c!=False: c.x=posx c.y=posy if event.type==pygame.MOUSEBUTTONDOWN: if oncardtrue(posx,posy) and count%2==0: c=fetchcard(posx,posy) fetch=True count=1 elif fetch==True: count=0 fetch=False if not oncardtrue(posx,posy): ind=c.index if ind>13: c.x,c.y=dv[ind-14][0],dv[ind-14][1] else: c.x,c.y=lv[ind-1][0],lv[ind-1][1] else: if inplaying_discard(posx,posy): other=fetchcard(posx,posy) if c.index<=13 and other.index==15: c.x,c.y=lv[c.index-1][0],lv[c.index-1][1] elif c.index==15 and other.index==15: c.x,c.y=dv[1][0],dv[1][1] elif c.index!=14: cind=c.index othindex=other.index c.index,other.index=othindex,cind #c.x,c.y,other.x,other.y=other.x,other.y,c.x,c.y if c in discard: c.x,c.y,other.x,other.y=other.x,other.y,dv[1][0],dv[1][1] cardlist[othindex-1],discard[-1]=c,other else: c.x,c.y,other.x,other.y=other.x,other.y,lv[cind-1][0],lv[cind-1][1] cardlist[cind-1],cardlist[othindex-1]=other,c elif c.index==14: if other.index<=13: cind=c.index othindex=other.index c.index,other.index=othindex,15 c.x,c.y,other.x,other.y=other.x,other.y,dv[1][0],dv[1][1] cardlist[othindex-1]=c discard.append(other) deck.pop() elif other.index==15: c.x,c.y=dv[0][0],dv[0][1] else: other=fetchcard(posx,posy) if c.index<=13: c.x,c.y=lv[c.index-1][0],lv[c.index-1][1] elif c.index==15: c.x,c.y=dv[1][0],dv[1][1] elif c.index==14: c.x,c.y=dv[0][0],dv[0][1] if deck==[]: re=1 for i in range(27): cls=discard[0] cls.index=14 cls.x,cls.y=dv[0][0],dv[0][1] discard.pop(0) deck.append(cls) win.fill((0,0,0)) win.blit(background,(0,0)) transprect(550,200,80,122) transprect(870,200,80,122) pygame.draw.line(win,(255,0,0),(32,540),(448,540),1) pygame.draw.line(win,(0,255,0),(480,540),(782,540),1) pygame.draw.line(win,(0,0,255),(816,540),(1120,540),1) pygame.draw.line(win,(0,255,255),(1152,540),(1456,540),1) drawtext("4 card pure sequence",32,480,(255,255,255),(0,0,0)) drawtext("3 card sequence",480,480,(255,255,255),(0,0,0)) drawtext("3 card set",816,480,(255,255,255),(0,0,0)) drawtext("3 card set",1152,480,(255,255,255),(0,0,0)) for i in lv: transprect(i[0],i[1],80,122) for cls in cardlist: cls.show(win) for cls in discard[-2:]: if cls: cls.show(win) for cls in deck[-2:]: if cls: cls.showback(win) pwins=playerwin(cardlist) if pwins==True: displayplayerwin() break if re==1: reshuffle(deck,discard) re=0 #cpplay(cpcardlist) #cpwins=cpwin(cpcardlist) #if cpwins==True: # displaycpwin() # break if time.time()-start>=600: displaycpwin() break pygame.display.update() pygame.quit()
02ba7b4bbc251b7fed0e4db91a93484b507f2aa8
setu-parekh/Object-Oriented-Programming-in-Python
/private_protected_public.py
1,834
4.15625
4
# Public - making members (attributes and methods) of the class accessible to that particular class, derived class and also outside the derived class. # Protected - making members (attributes and methods) of the class accessible to that particular class and its derived members. # Private - making members (attributes and methods) of the class only accessible to that class only. It is not even accessible to its derived class. # define parent class Company class Company: # constructor def __init__(self, name, proj, ceo): self.name = name # name(name of company) is public self._proj = proj # proj(current project) is protected self.__ceo = ceo # ceo is private def who_is_ceo(self): print("CEO is {}".format(self.__ceo)) # define child class Emp class Emp(Company): # constructor def __init__(self, eName, sal, cName, proj, ceo): # calling parent class constructor Company.__init__(self, cName, proj, ceo) self.name = eName # public member variable self.__sal = sal # private member variable # public function to show salary details def show_sal(self): print("The salary of {} is {} ".format(self.name, self.__sal,)) def show_ceo_and_proj(self): print("CEO: {} || Project: {}".format(self.__ceo, self._proj)) import ipdb; ipdb.set_trace() # creating instance of Company class comp = Company("Stark Industries", "Mark 4", "Mr. CEO") # print(comp.__ceo) - This will not work. Because __ceo is private attribute. # creating instance of Employee class empl = Emp("Steve", 9999999, comp.name, comp._proj, 'Ms. New CEO') print("Welcome to ", comp.name) print("Here",empl.name,"is working on",empl._proj) # to show the value of __sal we have created a public function show_sal() empl.show_sal()
73c96652f91062342de74789e7b72f95fb576a5c
coldspeed5566/coldspeed
/2019_python/01.io/loop.py
1,226
3.75
4
def prNum(n): for i in range(0, n+1): print(i, end = ' ') print("") #prNum(5) def pr_Range(a, b): for i in range(a, b): print(i, end = ' ') print() #pr_Range(10, 20) def pr_odd1(n): x = 1 for i in range(n): print(x, end = " ") x += 2 print() #pr_odd1(5) def pr_odd2(n): for i in range(n): print(i*2+1, end=' ') print() #pr_odd2(5) def rect_for( m, n, ch): for i in range(m): for i in range(n): print(ch, end = ' ') print() #rect_for(3, 5, '$') def rect_while( m, n, ch): j = 0 while j < n: print(ch) while j < n: print(ch, end = " ") j += 1 print() i += 1 #rect_while(3, 5, '$') def frame(m, n, ch= "*") for i in range(n): print(ch, end=' ') print() print(ch, end=" ") for i in range(n-2): print(' ', end=' ') print(ch) frame(5, 6, '#') frame(7, 15, '@') def square_number(n): i = 1 while i > n: print(i, end= ' ') i += 1 print() square_number(25) def pr_digits(n): while n > 100: print(n % 10) n = n / 10 pr_digits(5764) pr_digits(123456) def rect_str(m, n, ch): for i in range(m): print((ch+' ') * n) #rest_str(3, 5 ,'$')
88eff2ee04f6569af42783238339ab1191e6b809
Amortized/Algorithms-and-Data-Structures
/Binomial_Fibonacci_Heaps/BinomialHeaps.py
5,474
3.734375
4
""" Author : Rahul Binomial Heaps Implementation Insert ele, Merge Heaps,Del ele, Find Min ele, Decrease Key ele,Del Min Ele all in O(log n) """ def test(): data = [500,20,30,400,580,60,700,80,90] H = BinomialHeap() tempNode = None for d in data: n = HeapNode(d) if d == max(data): tempNode = n insert(H, n) print_heap(H.head, 'o', '->') decreaseKey(H, tempNode, 1) print_heap(H.head, 'o', '->') for i in xrange(len(data)/2): n = removeMin(H) d = n.key print "Min Element (%2d) ---"%(d) print_heap(H.head, 'o', '->') n = removeMin(H) d = n.key print "-Min Now (%2d) ---"%(d) print_heap(H.head, 'o', '->') """ Test Ends""" class HeapNode: def __init__(self,key): self.key = key self.parent = None self.child = None self.sibling = None self.degree = 0 class BinomialHeap: def __init__(self): self.head = None def linkNodes(x,y): """ Links Binomial Tree rooted at x to y """ x.sibling = y.child x.parent = y y.child = x y.degree = y.degree + 1 def findMin(H): x = H.head y = x if x != None: minKey = x.key x = x.sibling while x!= None: if x.key < minKey: y = x minKey = x.key x = x.sibling return y def merge(Hx,Hy): """ Orders the nodes of two heaps in increasing order of degrees""" x = Hx.head y = Hy.head class SiblingGen: sibling = None """Head of New List""" h = SiblingGen() """Set the tail to head""" t = h while x!=None and y!=None: if(x.degree <= y.degree): t.sibling = x t = x x = x.sibling else : t.sibling = y t = y y = y.sibling if x!=None: t.sibling = x else : t.sibling = y return h.sibling def union(Hx,Hy): """Make a New Heap""" Hz = BinomialHeap() Hz.head = merge(Hx,Hy) """If both heaps are empty""" if Hz.head == None: return Hz prev = None x = Hz.head while x.sibling != None: if (x.degree != x.sibling.degree) or (x.sibling.sibling != None and x.sibling.sibling.degree == x.degree): """ If the roots have different order or nodes siblings siblings has same deg as node its safe to move ahead""" prev = x x = x.sibling else : if x.key <= x.sibling.key: """x will be the root. x.sibling will be linked into it. x does not move head here""" y = x.sibling x.sibling = x.sibling.sibling linkNodes(y,x) else : """ x.sibling will be the root""" y = x.sibling """Set the previous pointer""" if prev != None: prev.sibling = y else : Hz.head = y linkNodes(x,y) x = y #Change x for next stage return Hz def insert(H,newNode): """Make a New Heap""" H1 = BinomialHeap() H1.head = newNode T = union(H,H1) """Change the Old head""" H.head = T.head def decreaseKey(H,node,newKey): assert(newKey <= node.key) if node.key == newKey: return node.key = newKey """Now Swap with parent till tree is adjusted""" y = node z = y.parent while z!=None and z.key > y.key: """Go up""" """Swap the keys""" temp = y.key y.key = z.key z.key = temp """Swap the pointers""" y = z z = y.parent def removeMin(H): if H.head == None: return None """Find the Tree which has the min node and remove it""" minNode = H.head prev = None cur = minNode x = minNode.sibling while x!=None: if x.key < minNode.key: prev = cur minNode = x cur = x x = x.sibling if prev == None: H.head = minNode.sibling else : prev.sibling = minNode.sibling """Now prepare a heap from Min Nodes children in increasing order of degrees""" newHeap = BinomialHeap() x = minNode.child while x!=None: x.parent = None y = x.sibling #Next Child x.sibling = newHeap.head #Reverse Order. Changed Here newHeap.head = x x = y """Now take the Union of two heaps""" T = union(H,newHeap) H.head = T.head """Free the Minnode""" minNode.sibling = None minNode.child = None minNode.degree = 0 minNode.parent = None """Return the Min Node""" return minNode def deleteEle(H,node): """Get the Min""" minNode = findMin(H) """Decrease the key of the node to less than min""" decreaseKey(H,node,minNode.key - 1) """That Tree has been adjusted by decreaseKey by [putting this at the root of the tree,Now adjust the Heap""" #Heap Extracts this min removeMin(H) def print_heap(x, indent='#', char='#'): while x != None: print "%s %d [%d]" %(indent, x.key, x.degree) if x.child != None: print_heap(x.child, indent+char, char) x = x.sibling if __name__ == '__main__': test()
5fc93e11624f1bb89d5935e459be83f0051304aa
seema1711/My100DaysOfCode
/Day 4/removeItemLL.py
1,440
4.03125
4
''' We can remove an existing node using the key for that node. We will locate the previous node of the node which is to be deleted. Then point to the next pointer of this node to the next node to be deleted. ''' class Node: def __init__(self,data=None): self.data = data self.next = None class SLinkedList: def __init__(self): self.head = None def AtBeginning(self,data_in): NewNode = Node(data_in) NewNode.next = self.head self.head = NewNode # Function to remove node def RemoveNode(self, Removekey): HeadVal = self.head if (HeadVal is not None): if (HeadVal.data == Removekey): self.head = HeadVal.next HeadVal = None return while (HeadVal is not None): if HeadVal.data == Removekey: break previous = HeadVal HeadVal = HeadVal.next if (HeadVal == None): return previous.next = HeadVal.next HeadVal = None def listprint(self): printval = self.head while (printval): print(printval.data) printval = printval.next list = SLinkedList() list.AtBeginning('Seema') list.AtBeginning('Kareena') list.AtBeginning('Salman') list.AtBeginning('Akshay') list.AtBeginning('Preeti') list.RemoveNode('Preeti') print("After removing the node") list.listprint()
5fc3d93dcdc8b3ded7313b709526b21ae515137b
ClemenceLVR/Terminator
/Terminator/fonctionTerminator.py
5,907
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 29 14:27:12 2018 @author: skaering """ import re def findRegex(source): # search numerical values in the text using a regex pattern=re.compile(r""" (([[]?[0-9]+([.,]\d+)?-[0-9]+([.,]\d+)?[]]?)# interval | #or ([0-9]+([.,]\d+)?)) #a simple numerical value ([ ]*(µg|cm|g|mg|µm|mm|cg|m))? #with an unity or not """, re.VERBOSE) result = pattern.finditer(source) listofresult={} #record the result in a dictionnary for m in result: print(m.group()) listofresult.append(m.group()); return listofresult def intelligentOrgansResearch(source,sourcelist): listOfFoundedOrgans=[] source1= source sourceSplited= list(source1.split()); i=0 while (i < len(sourceSplited)): if sourceSplited[i] in sourcelist: pos, x=i+1,sourceSplited[i] while ((pos< len(sourceSplited)) and (x+" "+sourceSplited[pos] in sourcelist)): x=x + ' ' + sourceSplited[pos] print(x) pos+=1 listOfFoundedOrgans.append(x) i=pos else: i+=1 return listOfFoundedOrgans def intelligentSplit (source, organs): source1=source.lower(); sourceSplited=list(source1.split()) i=0 while(i<len(sourceSplited)): if sourceSplited[i] in organs: sourceSplited[i]="@" i+=1 str="".join(sourceSplited) return (str.split("@")) def createDict(organs): d = {} for i in organs: d[i]=[] return d def findOccurences(source, d): oc=[] oc1={} for i in d.keys(): for j in list(re.finditer(i, source)): oc1 = {'name': i, 'start':j.start(), 'end':j.end(),'av':True} if "start" in oc1: oc.append(oc1) oc1={} return oc def findWordsInSource(oc,d): for w in d.keys(): if oc.get(w) != None: d[w]=oc.get(w) return d def deduction_Prop_implicite(source,dico_Organ_Prop,dico_Prop_Value): org = [] #list organs, valeurs, prop val = [] prop = [] c = "" n = "" chint = "" u = 0 Sentences_list = source.lower().split(".") #je coupe en phrase grâce au point et je majuscule->minuscule for i, sentence in enumerate(Sentences_list): #pour chaque phrases word_sent = Sentences_list[i].split(" ") #je coupe en mots for j, word in enumerate(word_sent): #pour chaque mot -> 2 tests u = len(word_sent) #Je reléve l'indice du dernier item de la liste word_sent (enfin ça me renvoie le dernier +1 je sais pas pourqoui) if j != u-1: # Si j n'est pas le dernier mot (item) de la liste alors chint = word + " " + word_sent[j+1] #la chaine intermediaire prends le mot plus celui après "lip" + "region" for o, key_organ in enumerate(dico_Organ_Prop.keys()): #test : est-ce un organe répertorié if chint == key_organ: #est ce que l'organe est un organe à deux mot "lip region" org.append(key_organ) #si oui ajout à la liste c = dico_Organ_Prop.get(key_organ) #Je stock la valeur de cette clé chint = "" #la chaine doit être vidé elif word == key_organ: #sinon est ce que le mot est un organe répertorié org.append(word) #si oui ajout à la liste c = dico_Organ_Prop.get(key_organ) #Je stock la valeur de cette clé for key, value in dico_Prop_Value.items():#test : est-ce une valeur répertoriée if word == value: val.append(value) #si oui ajout à la liste n = key #Je stock la clé de cette valeur if c == n and c != '' or n != '': #Test final: est ce que la valeur de dicoOrg,Prop (donc prop) prop.append(c) # est égale à la clé de dicoProp,Val (la clé est aussi prop) c = "" #reset des bouches trous n = "" for i, o, j in zip(org, val, prop): print("Organe : ", i, " sa valeur est : ", o, " Propriété associé : ", j) ## fonction permettant de rechercher une proprieté relative exlicite et les organes qui lui sont associé def recherchePropRelative (source,listeRelativeProp,organs): ListFoundedProp= intelligentOrgansResearch(source,listeRelativeProp); #on recherche si on a des proprietés explicites print(ListFoundedProp); final=[] #création de la liste finale if len(ListFoundedProp) != 0:#si on a des prop relatives # ListFoundedOrgan = inteligentResearch(organs); source1= intelligentSplit(source,ListFoundedProp);#on split par les prop trouvés # l= [];#creation d'une liste tampon couple=[];# creation de la liste contenant les couples for i in len(source1): #pour chaque élément de la liste splité: l= intelligentOrgansResearch(source1[i],organs); #on regarde si on a des organes dedans et on les met dans l if len(l)>0: couple.append(l[0]);#couple prend le premier et le derniers element de l if len(l)>1: #si il y a plus d'un element couple prend le dernier de la liste l couple.append(l[len(l)]); couple.remove(1); # on suprime le premier de couple qui fausse le resultat for j in len(ListFoundedProp): # pour chaque prop trouvé : final recoit le premier couple puis la prop puis le second couple tampon={couple[0],ListFoundedProp[i],couple[1]} ##print(tampon); final.append(tampon) couple.remove(0); # ensuite supression des couples ajoutés couple.remove(1); return final;
83a09a56d522ef36d53b55566a287086803c2bcb
gmumar/Optimization_problems
/warehouse/solver_working.py
5,674
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- def cheapestWarehouse_dist(wlist,n): # Selects the nth cheapest warehouse by least avg distance cost whose capacity is greater than 0 global avgDistanceToWarehouse n = n - 1 return avgDistanceToWarehouse[n][1] def cheapestWarehouse_fixed(wlist,n): # Selects the nth cheapest warehouse by fixed cost whose capacity is greater than 0 global capacityRemaining lmin = float("inf") index = float("inf") seen = [] for k in range(n): for i in xrange(len(wlist)): if(wlist[i][1]<lmin and capacityRemaining[i]>0 and i not in seen): lmin = wlist[i][1] index = i seen.append(index) lmin = float("inf") return index def nearestCustomer(index): # Returns the nearest customer to a particular warehouse whose capacity is less then the remaining space at the warehouse global customerCount global capacityRemaining global solution lmin = float("inf") index_r = float("inf") for i in xrange(customerCount): if(customerCosts[i][index] < lmin and customerSizes[i] <= capacityRemaining[index] and i not in connected): lmin = customerCosts[i][index] index_r = i return index_r def solveIt(inputData): # Modify this code to run your optimization algorithm # parse the input lines = inputData.split('\n') parts = lines[0].split() global customerCount global warehouseCount warehouseCount = int(parts[0]) customerCount = int(parts[1]) global warehouses warehouses = [] for i in range(1, warehouseCount+1): line = lines[i] parts = line.split() warehouses.append((int(parts[0]), float(parts[1]))) # warehouse capacity, warehouse fixed cost global customerSizes global customerCosts customerSizes = [] customerCosts = [] lineIndex = warehouseCount+1 for i in range(0, customerCount): customerSize = int(lines[lineIndex+2*i]) customerCost = map(float, lines[lineIndex+2*i+1].split()) customerSizes.append(customerSize) customerCosts.append(customerCost) # demand in customerSizes, transportation cost to n warehouse in customerCosts # customerSizes[n] returns demand of nth customer # customerCosts[n] returns a list of distances to mth warehouse global solution solution = [-1] * customerCount # initialization for the solution array global capacityRemaining capacityRemaining = [w[0] for w in warehouses] # Shows the capacity remaining at n warehouse global connected connected = [] #shows all the customers connected to warehouses global avgDistanceToWarehouse avgDistanceToWarehouse = [0]*warehouseCount # Shows the avg distance to nth warehouse for i in range(customerCount): for k in range(warehouseCount): avgDistanceToWarehouse[k] = customerCosts[i][k] + avgDistanceToWarehouse[k] for k in range(warehouseCount): avgDistanceToWarehouse[k] = (avgDistanceToWarehouse[k] * warehouses[k][1]) / warehouseCount for k in range(warehouseCount): avgDistanceToWarehouse[k] = (avgDistanceToWarehouse[k],k) avgDistanceToWarehouse.sort() valid = [] for k in range(20): valid.append(avgDistanceToWarehouse[k][1]) #------------------------INIT---------------------- print(warehouseCount,customerCount) print valid #print(avgDistanceToWarehouse) #print("warehouses",warehouses) #print("customer Costs",customerCosts) #print("customer Sizes",customerSizes) #print ("cap remaining",capacityRemaining) count = 1 while (-1 in solution): warehouseIndex = cheapestWarehouse_dist(warehouses,count) #print("Cheapest warehouse",warehouseIndex) while(capacityRemaining[warehouseIndex] > 0 and -1 in solution): customerIndex = nearestCustomer(warehouseIndex) #print("closest customer", customerIndex) if(customerIndex == float("inf")): count = count + 1 if(count > warehouseCount): count = 1 break capacityRemaining[warehouseIndex] = capacityRemaining[warehouseIndex] - customerSizes[customerIndex] solution[customerIndex] = warehouseIndex connected.append(customerIndex) #print (solution) #print(capacityRemaining,solution) # calculate the cost of the solution used = [0]*warehouseCount for wa in solution: used[wa] = 1 obj = sum([warehouses[x][1]*used[x] for x in range(0,warehouseCount)]) for c in range(0, customerCount): obj += customerCosts[c][solution[c]] # prepare the solution in the specified output format outputData = str(obj) + ' ' + str(0) + '\n' outputData += ' '.join(map(str, solution)) return outputData import sys if __name__ == '__main__': if len(sys.argv) > 1: fileLocation = sys.argv[1].strip() inputDataFile = open(fileLocation, 'r') inputData = ''.join(inputDataFile.readlines()) inputDataFile.close() print 'Solving:', fileLocation print solveIt(inputData) else: print 'This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/wl_16_1)'
c1776cc19ff56b0e98342dbcbeff905d09432b6e
indiee27/IPMI-Portfolio
/Python/Week02/utils2.py
9,052
3.5625
4
""" utility functions for use in the image registration exercises 2 for module MPHY0025 (IPMI) Jamie McClelland UCL """ import numpy as np import matplotlib.pyplot as plt plt.style.use('default') import scipy.interpolate as scii def dispImage(img, int_lims = [], ax = None): """ function to display a grey-scale image that is stored in 'standard orientation' with y-axis on the 2nd dimension and 0 at the bottom INPUTS: img: image to be displayed int_lims: the intensity limits to use when displaying the image, int_lims(1) = min intensity to display, int_lims(2) = max intensity to display [default min and max intensity of image] ax: if displaying an image on a subplot grid or on top of a second image, optionally supply the axis on which to display the image. OUTPUTS: ax_im: the AxesImage object returned by imshow """ #check if intensity limits have been provided, and if not set to min and #max of image if not int_lims: int_lims = [np.nanmin(img), np.nanmax(img)] #check if min and max are same (i.e. all values in img are equal) if int_lims[0] == int_lims[1]: #add one to int_lims(2) and subtract one from int_lims(1), so that #int_lims(2) is larger than int_lims(1) as required by imagesc #function int_lims[0] -= 1 int_lims[1] += 1 # take transpose of image to switch x and y dimensions and display with # first pixel having coordinates 0,0 img = img.T if not ax: plt.gca().clear() ax_im = plt.imshow(img, cmap = 'gray', vmin = int_lims[0], vmax = int_lims[1], origin='lower') else: ax.clear() ax_im = ax.imshow(img, cmap = 'gray', vmin = int_lims[0], vmax = int_lims[1], origin='lower') #set axis to be scaled equally (assumes isotropic pixel dimensions), tight #around the image plt.axis('image') plt.tight_layout() return ax_im def defFieldFromAffineMatrix(aff_mat, num_pix_x, num_pix_y): """ function to create a 2D deformation field from an affine matrix INPUTS: aff_mat: a 3 x 3 numpy matrix representing the 2D affine transformation in homogeneous coordinates num_pix_x: number of pixels in the deformation field along the x dimension num_pix_y: number of pixels in the deformation field along the y dimension OUTPUTS: def_field: the 2D deformation field """ # form 2D matrices containing all the pixel coordinates [X,Y] = np.mgrid[0:num_pix_x, 0:num_pix_y] # reshape and combine coordinate matrices into a 3 x N matrix, where N is # the total number of pixels (num_pix_x x num_pix_y) # the 1st row contains the x coordinates, the 2nd the y coordinates, and the # 3rd row is all set to 1 (i.e. using homogenous coordinates) total_pix = num_pix_x * num_pix_y pix_coords = np.array([np.reshape(X, -1), np.reshape(Y, -1), np.ones(total_pix)]) # apply transformation to pixel coordinates trans_coords = aff_mat * pix_coords #reshape into deformation field by first creating an empty deformation field def_field = np.zeros((num_pix_x, num_pix_y, 2)) def_field[:,:,0] = np.reshape(trans_coords[0,:], (num_pix_x, num_pix_y)) def_field[:,:,1] = np.reshape(trans_coords[1,:], (num_pix_x, num_pix_y)) return def_field def resampImageWithDefField(source_img, def_field, interp_method = 'linear', pad_value=np.NaN): """ function to resample a 2D image with a 2D deformation field INPUTS: source_img: the source image to be resampled, as a 2D matrix def_field: the deformation field, as a 3D matrix inter_method: any of the interpolation methods accepted by interpn function [default = 'linear'] - 'linear', 'nearest' and 'splinef2d' pad_value: the value to assign to pixels that are outside the source image [default = NaN] OUTPUTS: resamp_img: the resampled image NOTES: the deformation field should be a 3D numpy array, where the size of the first two dimensions is the size of the resampled image, and the size of the 3rd dimension is 2. def_field[:,:,0] contains the x coordinates of the transformed pixels, def_field[:,:,1] contains the y coordinates of the transformed pixels. the origin of the source image is assumed to be the bottom left pixel """ x_coords = np.arange(source_img.shape[0], dtype = 'float') y_coords = np.arange(source_img.shape[1], dtype = 'float') # resample image using interpn function return scii.interpn((x_coords, y_coords), source_img, def_field, bounds_error=False, fill_value=pad_value, method=interp_method) def affineMatrixForRotationAboutPoint(theta, p_coords): """ function to calculate the affine matrix corresponding to an anticlockwise rotation about a point INPUTS: theta: the angle of the rotation, specified in degrees p_coords: the 2D coordinates of the point that is the centre of rotation. p_coords[0] is the x coordinate, p_coords[1] is the y coordinate OUTPUTS: aff_mat: a 3 x 3 affine matrix """ #convert theta to radians theta = np.pi * theta / 180 #form matrices for translation and rotation T1 = np.matrix([[1, 0, -p_coords[0]], [0, 1, -p_coords[1]], [0,0,1]]) T2 = np.matrix([[1, 0, p_coords[0]], [0, 1, p_coords[1]], [0,0,1]]) R = np.matrix([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]]) #compose matrices aff_mat = T2 * R * T1 return aff_mat def calcSSD(A,B): """ function to calculate the sum of squared differences between two images INPUTS: A: an image stored as a 2D matrix B: an image stored as a 2D matrix. B must be the same size as A OUTPUTS: SSD: the value of the squared differences NOTE: if either of the images contain NaN values, these pixels should be ignored when calculating the SSD. """ # use nansum function to find sum of squared differences ignoring NaNs return np.nansum((A-B)*(A-B)) def calcMSD(A,B): """ function to calculate the sum of squared differences between two images INPUTS: A: an image stored as a 2D matrix B: an image stored as a 2D matrix. B must be the same size as A OUTPUTS: SSD: the value of the squared differences NOTE: if either of the images contain NaN values, these pixels should be ignored when calculating the MSD. """ # use nansum function to find sum of squared differences ignoring NaNs return np.nanmean((A-B)*(A-B)) def calcNCC(A,B): """ function to calculate the normalised cross correlation between two images INPUTS: A: an image stored as a 2D matrix B: an image stored as a 2D matrix. B must the the same size as A OUTPUTS: NCC: the value of the normalised cross correlation NOTE: if either of the images contain NaN values these pixels should be ignored when calculating the NCC. """ # use nanmean and nanstd functions to calculate mean and std dev of each # image mu_A = np.nanmean(A) mu_B = np.nanmean(B) sig_A = np.nanstd(A) sig_B = np.nanstd(B) # calculate NCC using nansum to ignore nan values when summing over pixels return np.nansum((A-mu_A)*(B-mu_B))/(A.size * sig_A * sig_B) def calcEntropies(A, B, num_bins = [32,32]): """ function to calculate the joint and marginal entropies for two images INPUTS: A: an image stored as a 2D matrix B: an image stored as a 2D matrix. B must the the same size as A num_bins: a 2 element vector specifying the number of bins to in the joint histogram for each image [default = 32, 32] OUTPUTS: H_AB: the joint entropy between A and B H_A: the marginal entropy in A H_B the marginal entropy in B NOTE: if either of the images contain NaN values these pixels should be ignored when calculating the entropies. """ #first remove NaNs and flatten nan_inds = np.logical_or(np.isnan(A), np.isnan(B)) A = A[np.logical_not(nan_inds)] B = B[np.logical_not(nan_inds)] #use histogram2d function to generate joint histogram, an convert to #probabilities joint_hist,_,_ = np.histogram2d(A, B, bins = num_bins) probs_AB = joint_hist / np.sum(joint_hist) #calculate marginal probability distributions for A and B probs_A = np.sum(probs_AB, axis=1) probs_B = np.sum(probs_AB, axis=0) #calculate joint entropy and marginal entropies #note, when taking sums must check for nan values as #0 * log(0) = nan H_AB = -np.nansum(probs_AB * np.log(probs_AB)) H_A = -np.nansum(probs_A * np.log(probs_A)) H_B = -np.nansum(probs_B * np.log(probs_B)) return H_AB, H_A, H_B
f5a64cd6875ca4a40b22edf4ba6efbbe5e3b1156
Levi-Huynh/Sprint-Challenge--Graphs
/util.py
1,070
3.71875
4
# Note: This Queue class is sub-optimal. Why? # b/c self.que is using array # time complexity to pop off first index in array is O(n) (shifts all over 1 at time ) # LL or DEQ maybe be tter class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) def __str__(self): return str(self.queue) class Stack(): def __init__(self): self.stack = [] # can get around resizing if know size of stack/create size of stack def push(self, value): self.stack.append(value) # resizing may occur every now & then O(n)? def pop(self): if self.size() > 0: return self.stack.pop() # not espensive rt, to pop off end of -array else: return None def size(self): return len(self.stack) def __str__(self): return str(self.stack)
953713d0322304704a707a57dfa244cba7d705b4
nicholaswuu/Year9DesignPythonNW
/Data Analysis/DataAnalysis1.py
1,159
3.859375
4
data = open("dataAnalysis1.txt","r"); dataString = data.read() dataList = dataString.split("\n") for i in range(0, len(dataList), 1): dataList[i] = dataList[i].replace(",","") dataList[i] = float(dataList[i]) minimum = min(dataList) print(minimum) maximum = max(dataList) print(maximum) diff = maximum - minimum print(diff) smallest = dataList[0] for i in range (0, len(dataList), 1): if smallest > dataList[i]: smallest = dataList[i] print("MIN IS: " + str(smallest)) largest = dataList[0] for i in range (0, len(dataList), 1): if largest < dataList[i]: largest = dataList[i] print("MAX IS: " + str(largest)) maxvalue = input("What number do you want to set as upper limit: ") maxvalue = float(maxvalue) biggest = dataList[0] minvalue = input("What number do you want to set as lower limit: ") minvalue = float(minvalue) smallest1 = dataList[0] for i in range (0, len(dataList), 1): if maxvalue > dataList[i] and dataList[i] > biggest: biggest = dataList[i] print("MAX IS: " + str(biggest)) for i in range (0, len(dataList), 1): if minvalue < dataList[i] < smallest1: smallest1 = dataList[i] print("MIN IS: " + str(smallest1))
3a88cf59365c1bd57650f4ef6c369dc028820587
AliceSkilsara/python
/tasks/task25.py
441
4.4375
4
month = input("Input your month:").lower() if month == "january" or month == 'february' or month == 'december': print("It's winter") elif month == 'march' or month == 'april' or month == 'may': print("It's spring") elif month == 'june' or month == 'july' or month == 'august': print("It's summer") elif month == 'september' or month == 'october' or month == 'november': print("It's autumn") else: print("Unknown month")
fc48c0acdfeb79d89f3ad19b26adb67cc9e1b943
Rayanthere/91883-884-Gk-Quiz
/Python assesment/V1(User Details)/user _details_v2.py
594
4.03125
4
#the following code is to ask rhe user their user details print("*********************Welcome to the General knowledge Quiz**********************") print("This quiz is been developed by Rayan") while True: name = input("What is your name : ") if name.isalpha(): break print("Please enter your name in letters only") while True: age = input("What is your age : ") if age.isnumeric(): break print("Please enter your age in numbers only")
15b490d28617d1da9ef888402045f84c25015c40
pravalikavis/Python-Mrnd-Exercises
/unit6_assignment_03.py
3,723
3.984375
4
__author__ = 'Kalyan' notes = ''' This problem will require you to put together many things you have learnt in earlier units to solve a problem. In particular you will use functions, nested functions, file i/o, functions, lists, dicts, iterators, generators, comprehensions, sorting etc. Read the constraints carefully and account for all of them. This is slightly bigger than problems you have seen so far, so decompose it to smaller problems and solve and test them independently and finally put them together. Write subroutines which solve specific subproblems and test them independently instead of writing one big mammoth function. Do not modify the input file, the same constraints for processing input hold as for unit6_assignment_02 ''' problem = ''' Given an input file of words (mixed case). Group those words into anagram groups and write them into the destination file so that words in larger anagram groups come before words in smaller anagram sets. With in an anagram group, order them in case insensitive ascending sorting order. If 2 anagram groups have same count, then set with smaller starting word comes first. For e.g. if source contains (ant, Tan, cat, TAC, Act, bat, Tab), the anagram groups are (ant, Tan), (bat, Tab) and (Act, cat, TAC) and destination should contain Act, cat, TAC, ant, Tan, bat, Tab (one word in each line). the (ant, Tan) set comes before (bat, Tab) as ant < bat. At first sight, this looks like a big problem, but you can decompose into smaller problems and crack each one. source - file containing words, one word per line, some words may be capitalized, some may not be. - read words from the source file. - group them into anagrams. how? - sort each group in a case insensitive manner - sort these groups by length (desc) and in case of tie, the first word of each group - write out these groups into destination ''' import unit6utils import string def est1(li): r=[] for a in range(len(li)): s=[] for b in range(a+1,len(li)): if li[b]!="": if len(li[a])==len(li[b]): x=[z.lower() for z in li[a]] y=[z.lower() for z in li[b]] x.sort() y.sort() if x==y: s.append(li[b]) li[b]="" if s!=[]: s.append(li[a]) li[a]="" s.sort(key=lambda x:len(x)) r.append(s) return r def anagram_sort(source, destination): f = open(source, "r") l = [x if '#' not in x else x[:x.index('#')].strip() for x in f.readlines() if x[0] != '#' and x != '\n'] l = [x if x[-1] != '\n' else x[:-1] for x in l if x != ''] l1=est1(l) l1 = [sorted(x, key=lambda x: x.lower()) for x in l1] l1.sort(key=lambda x: (x[0].lower(), len(x)), reverse=True) l1.reverse() l.sort(key=lambda x: (x.lower(), len(x))) with open(destination,"w") as f1: for a in l1: for b in a: f1.write(b) f1.write('\n') for a in l: if a!='': f1.write(a) f1.write('\n') f.close() f1.close() def test_anagram_sort(): source = unit6utils.get_input_file("unit6_testinput_03.txt") expected = unit6utils.get_input_file("unit6_expectedoutput_03.txt") destination = unit6utils.get_temp_file("unit6_output_03.txt") anagram_sort(source, destination) result = [word.strip() for word in open(destination)] expected = [word.strip() for word in open(expected)] assert expected == result
e4602357f874d1f0dabbffdf6d3f8811f25297ce
andrew-rietz/FiftySeven_Coding_Challenges
/challenges/c49_FlickrPhotos/49_FlickrPhotoSearch.py
2,992
3.71875
4
""" Some services provide search features and give you a lot of control over the results you get back. All you have to do is construct the right kind of request. Create a program with a graphical interface that takes in a search string and displays photographs that match that search string. Use Flickr's public photo feed as your service. (https://www.flickr.com/services/feeds/docs/photos_public/) ___________________ Example Output ___________________ Your program should display the photographs like this: Photos about "<<search term>>" --------- --------- --------- | | | | | | | | | | | | | | | | | | | | | | | | --------- --------- --------- ___________________ Constraints ___________________ Because this is a graphical program, you'll need to display the pictures from the API. If you're using Javascript, do this with HTML and the DOM. Don't use jQuery or any external frameworks. If you're using Java, try building a desktop application with Swing or an Android application. If you're using a language with a rich GUI toolkit, create an HTML page and open it with the local browser. """ def getInputs(): searchTerm = input( "What kind of pictures would you like? " ) return (searchTerm) def writeHTML(searchTerm, pictures): import math pageHTML =( """ <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Flickr Photos</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <style> .img-thumbnail{ height: 200px; width: 200px; object-fit: cover; } </style> </head> <body> <div class="container"> """ ) pageHTML += f'\ <h2>Photos about "{searchTerm}"</h2>' pageHTML += (''' <div class="row">''' ) for picture in pictures: pageHTML += ( f""" <div class="px-0"> <img src="{picture}" alt="Picture Not Found" class="img-thumbnail"> </div> """ ) pageHTML += "</div>" pageHTML += ( """ </div> </body> </html> """ ) with open("./49_FlickrPhotos/49_html.html", "w") as writer: writer.write(pageHTML) return "File created" def main(): import requests import json (searchTerm) = getInputs() apiRequest = ( f"https://api.flickr.com/services/feeds/photos_public.gne?" + f"tags={searchTerm}&format=json" ) apiResponse = requests.get(apiRequest) jsonResponse = json.loads(apiResponse.text[15:len(apiResponse.text)-1]) imgLinks = [dict["media"]["m"] for dict in jsonResponse["items"]] print(writeHTML(searchTerm, imgLinks)) main()