blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
ad6f9f99e1fa329d1790ea6273ad69882829be46
Python
areamluersen/simulacao-discreta
/src/lavacar/numeros_aleatorios/main.py
UTF-8
1,111
2.640625
3
[]
no_license
from entrada import selecaoMetodoDoUsuario, selecaoDeValoresDoUsuario, converteValoresDeEntrada, \ converteSelecaoMetodoDoUsuario, selecaoDeQuantidade, converteSelecaoDeQuantidade from numeros_randomicos import gerarNumerosRandomicos if __name__ == '__main__': metodoDeEntrada = selecaoMetodoDoUsuario() metodoDeEntrada = converteSelecaoMetodoDoUsuario(metodoDeEntrada) selecaoDeQuantidade = selecaoDeQuantidade() selecaoDeQuantidade = converteSelecaoDeQuantidade(selecaoDeQuantidade) valoresDeEntrada = selecaoDeValoresDoUsuario() valoresDeEntrada = converteValoresDeEntrada(valoresDeEntrada) numerosAleatorios = gerarNumerosRandomicos(metodoDeEntrada, selecaoDeQuantidade, **valoresDeEntrada) print('\nResultado:') acc = 0 for i in range(len(numerosAleatorios)): acc += numerosAleatorios[i] print('numero', i + 1, ':', numerosAleatorios[i]) with open('src/numeros_aleatorios/output.dst', 'w') as file: for item in numerosAleatorios: file.write(str(item) + '\n') print('Valor medio : ', acc / len(numerosAleatorios))
true
22e8ff0aa1bf7aafa8e2d863aad24c7ef874d16e
Python
ikale1234/42Work
/pygame1/Game/game1a.py
UTF-8
6,328
2.8125
3
[]
no_license
import pygame import random pygame.init() clock = pygame.time.Clock() win = pygame.display.set_mode((500,480)) pygame.display.set_caption("jump") walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'), pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'), pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')] walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'), pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'), pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')] bg = pygame.image.load('bg.jpg') char = pygame.image.load('standing.png') shoot = False class player(): def __init__(self, x, y, width, height): self.x = x self.y =y self.width = width self.height = height self.vel = 5 self.jump = False self.jcount = 10 self.left = False self.right = False self.wcount = 0 self.alive = True def draw(self,win): if self.alive: if self.wcount + 1 >= 27: self.wcount = 0 if self.left: win.blit(walkLeft[self.wcount//3], (self.x,self.y)) self.wcount += 1 elif self.right: win.blit(walkRight[self.wcount//3], (self.x,self.y)) self.wcount += 1 else: win.blit(char, (self.x,self.y)) class bullet(): def __init__(self): self.x = 0 self.y = 0 self.vel = 30 self.shoot = False def draw(self,win): if self.shoot == True: pygame.draw.rect(win, (0,0,255), (self.x, self.y, 20, 10)) if self.x <-1000 or self.x >2000: self.shoot = False run = True def drawgame(): win.blit(bg, (0,0)) for i in range(len(bs)): bs[i].draw(win) for i in range(len(ds)): ds[i].draw(win) guy.draw(win) dude.draw(win) if l1 != 0: pygame.draw.rect(win, (255,0,0), (guy.x, guy.y, l1, 5)) if l2 != 0: pygame.draw.rect(win, (255,0,255), (dude.x, dude.y, l2, 5)) pygame.display.update() guy = player(300, 410, 64, 64) dude = player(100, 410, 64, 64) bs = [] ds = [] bnum = -1 dnum = -1 bwait= 40 dwait= 40 bcount = 69 dcount = 69 p1score = 0 p2score = 0 p1win = False p2win = False while run: clock.tick(27) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False l1 = 70 - 7*p1score l2 = 70 - 7*p2score key = pygame.key.get_pressed() if key[pygame.K_LEFT] and guy.x > guy.vel: guy.x-=guy.vel guy.left = True guy.right = False elif key[pygame.K_RIGHT] and guy.x< 500-guy.width-guy.vel: guy.x+=guy.vel guy.left = False guy.right = True else: guy.left= False guy.right= False guy.wcount = 0 if guy.jump == False: if key[pygame.K_UP]: guy.jump = True guy.left= False guy.right= False guy.wcount = 0 else: if guy.jcount >= -10: neg = 1 if guy.jcount < 0: neg = -1 guy.y-=(guy.jcount**2)*0.5*neg guy.jcount -=1 else: guy.jump = False guy.jcount =10 if key[pygame.K_a] and dude.x > dude.vel: dude.x-=dude.vel dude.left = True dude.right = False elif key[pygame.K_d] and dude.x< 500-dude.width-guy.vel: dude.x+=dude.vel dude.left = False dude.right = True else: dude.left= False dude.right= False dude.wcount = 0 if dude.jump == False: if key[pygame.K_w]: dude.jump = True dude.left= False dude.right= False dude.wcount = 0 else: if dude.jcount >= -10: neg = 1 if dude.jcount < 0: neg = -1 dude.y-=(dude.jcount**2)*0.5*neg dude.jcount -=1 else: dude.jump = False dude.jcount =10 if l1 == 0: guy.alive = False p2win = True if l2 == 0: dude.alive = False p1win = True dwait+=1 if key[pygame.K_e] and dwait>10: dwait = 0 ds.append(bullet()) dnum+=1 ds[dnum].x= dude.x ds[dnum].y= dude.y+20 ds[dnum].shoot = True dcount = 0 if dcount == 0: if ds[dnum].shoot == True: dcount = 1 if dude.right: mul = 1 elif dude.left: mul = -1 else: mul = random.choice([1,-1]) ds[dnum].vel = ds[dnum].vel*mul for k in range(len(ds)): if ds[k].shoot: ds[k].x+=ds[k].vel if guy.alive: if ds[k].x > guy.x-5 and ds[k].x < guy.x+50: if ds[k].y > guy.y and ds[k].y < guy.y+65: p1score +=1 ds[k].shoot = False bwait+=1 if key[pygame.K_RSHIFT] and bwait>10: bwait = 0 bs.append(bullet()) bnum+=1 bs[bnum].x= guy.x bs[bnum].y= guy.y+20 bs[bnum].shoot = True bcount = 0 if bcount == 0: if bs[bnum].shoot == True: bcount = 1 if guy.right: mul = 1 elif guy.left: mul = -1 else: mul = random.choice([1,-1]) bs[bnum].vel = bs[bnum].vel*mul for k in range(len(bs)): if bs[k].shoot: bs[k].x+=bs[k].vel if dude.alive: if bs[k].x > dude.x-5 and bs[k].x < dude.x+50: if bs[k].y > dude.y and bs[k].y < dude.y+65: p2score +=1 bs[k].shoot = False if p2win: sent = "Pink wins!" if p1win: sent = "Red wins!" if p1win or p2win: font = pygame.font.SysFont("Arial", 30) thing = font.render(sent,True, (255,255,255)) win.blit(thing, (400-thing.get_rect().width/2,100)) drawgame() pygame.quit()
true
2524f5ce0dd56ffe5b0140a187166e485a22e6dd
Python
mishrakeshav/Competitive-Programming
/Code Forces/Problem Set/B/keyboard.py
UTF-8
1,060
2.921875
3
[ "MIT" ]
permissive
if __name__ == '__main__': n, m, x = map(int, input().split()) keyboard = [] for i in range(n): keyboard.append(input()) q = int(input()) text = input() shift_keys = [] cost = dict() for i in range(n): for j in range(m): if keyboard[i][j] == 'S': shift_keys.append((i, j)) else: cost[keyboard[i][j]] = 0 if len(shift_keys) > 0: for i in range(n): for j in range(m): if keyboard[i][j] != 'S': distance = min((i - si)**2 + (j - sj) ** 2 for si, sj in shift_keys) letter = keyboard[i][j].upper() if distance <= x**2: cost[letter] = 0 elif letter not in cost: cost[letter] = 1 result = 0 for letter in text: if letter in cost: result += cost[letter] else: result = -1 break print(result)
true
711e8b0de95dba6c5c0e33f2f2d5c0eac7af8b88
Python
suvam1997/I-stand-with-you-using-Emojis-to-study-Solidarity-in-Crisis-Events
/Project/sentimentAnalysis.py
UTF-8
17,840
2.765625
3
[]
no_license
import sys reload(sys) sys.setdefaultencoding('utf-8') #time for execution import timeit start_time = timeit.default_timer() from nltk.corpus import sentiwordnet as swn import random from sklearn import svm import nltk import re from emoji import UNICODE_EMOJI from nltk.stem.snowball import SnowballStemmer import os import re import math import numpy as np #------------------- files read --------------------------------------- pos = open('positive-words.txt') neg = open('negative-words.txt') unclean_file = open('data/final_tweets.csv') #------------------- nltk variables ----------------------------------- words = list(set(w.lower() for w in nltk.corpus.words.words())) stopWords = list(set(w.lower() for w in nltk.corpus.stopwords.words())) stemmer = SnowballStemmer("english", ignore_stopwords=True) posTweets = [] negTweets = [] posTweetIDs = [] negTweetIDs = [] #------------------- variable declaration ---------------------------------------- posWords = [] negWords = [] finalClustersDict = {1:"", 2:"", 3:"", 4:"", 5:"", 6:""} finalClusters = [] #------------------- file data to lists ------------------------------------------- for line in pos: posWords.append(line.strip('\n').strip()) for line in neg: negWords.append(line.strip('\n').strip()) #-----------------recognize emojis-------------------------------------------------- def is_emoji(s): count = 0 for emoji in UNICODE_EMOJI: count += s.count(emoji) if count > 1: return False return bool(count) # --------- emoji sentiment rank from http://kt.ijs.si/data/Emoji_sentiment_ranking/ --------------------- emoji_SentimentScores = {} #happy, angry, love, sad, playful, confused emoji_SentimentScores["\xF0\x9F\x98\x82"] = 0.221 #0.221*2 emoji_SentimentScores["\xF0\x9F\x98\xA1"] = -0.173 #-0.173 emoji_SentimentScores["\xe2\x9d\xa4"] = 0.746 #0.746*2 emoji_SentimentScores["\xF0\x9F\x98\xAD"] = -0.093 #-0.093*2 emoji_SentimentScores["\xF0\x9F\x98\x9C"] = 0.445 #0.445*2 emoji_SentimentScores["\xf0\x9f\x98\x95"] = -0.397 #0.397*2 #if a positive or negative word is encountered, the sentimentScore will be changed by this value #0.124833 = average of all emoji scores averageChangeInSentiment = sum(emoji_SentimentScores.values())/len(emoji_SentimentScores.values()) #--------- declare targets -------------------------- targetEmoticons = {1: "happy", 2: "love", 3: "playful", 4: "sad", 5: "angry", 6: "confused"} #------------------------------ remove stopwords --------------------------------------------------------------------- tweets = [] #happy, angry, love, sad, playful, confused for row in unclean_file.readlines(): #remove usernames row = ' '.join(re.sub("(@[A-Za-z0-9_]+)", "", row).split()) #remove stopWords wordList = row.split() for word in wordList: if word in stopWords or len(word) == 1: row = row.replace(word, "") #print (word, row) try: tweets.append(row) except: pass #happy, love, playful, sad, angry, confused targets = [0]*len(tweets) for target in range(len(tweets)): if("\xF0\x9F\x98\x82" in tweets[target]): targets[target] = 1 elif("\xF0\x9F\x98\xA1" in tweets[target]): targets[target] = 5 elif("\xe2\x9d\xa4" in tweets[target]): targets[target] = 2 elif("\xF0\x9F\x98\xAD" in tweets[target]): targets[target] = 4 elif("\xF0\x9F\x98\x9C" in tweets[target]): targets[target] = 3 elif("\xf0\x9f\x98\x95" in tweets[target]): targets[target] = 6 ####------------------- uncomment from line 145 to 367 to perform data preprocessing and get sentiment Score ####------------------- else the positive sentiment scores are stored in sentimentPosScore.txt ####------------------- and negative sentiment in sentimentNegScore.txt #------------------ declare vars to store #, emojis, POS tags, sentiment Score for each tweet ------------------------------- hashtags = [""]*len(tweets) emojis = [""]*len(tweets) POStags = [""]*len(tweets) sentimentScore = [0]*len(tweets) sentiWord = [0] * len(tweets) #collector of sentiment Scores #--------------------------- assign #, emojis and store POS tags in POStags[] ------------------------------------ #tweets = tweets[:10] idx = 0 #tweet counter for sentence in tweets: hashtags[idx] = [] emojis[idx] = [] splitSentence = sentence.split() #print (splitSentence, idx) for word in splitSentence: #print (word, "#" in word, is_emoji(word)) if "#" == word[0]: hashtags[idx].append(word[1:]) elif(is_emoji(word)): emojis[idx].append(word) #remove emoji data, usernames to apply POS tweets[idx] = ' '.join(re.sub("(@[A-Za-z0-9_]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweets[idx]).split()) sentence = ' '.join(re.sub("(@[A-Za-z0-9_]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", sentence).split()) txt = nltk.word_tokenize(sentence) try: #txt = txt.decode('cp1252').encode('utf-8') POStags[idx] = nltk.pos_tag(txt) except: pass idx += 1 #------------------------------- get sentimentScore of emojis ------------------------------- # for i in range(len(emojis)): if(len(emojis[i]) == 0): pass else: #match sentiword with hashtag data for j in emojis[i]: if (j in emoji_SentimentScores.keys()): sentimentScore[i] += emoji_SentimentScores[j] #------------------------------- logic to convert hashtags like ThisIsCamelCasing to [This, is, camel, casing] ---------------------- def f1(w,c) : return list(zip(* filter(lambda (x,y): x == c, zip(w, range(len(w))) ))[1]) def getCamelCaseList(j): uppers = list(set([j.index(l) for l in j if l.isupper()])) indices = [] for i in range(len(uppers)): indices.append(f1(j, j[uppers[i]])) indices.append([len(j)]) indices = [item for sublist in indices for item in sublist] flat_list = [] if (indices != []): for k in range(len(indices)-1): #print (j, j[indices[k]:indices[k + 1]]) flat_list.append(str(j[indices[k]:indices[k + 1]]).lower()) return flat_list #-------------------------------- get SentimentScore of hashtags ------------------------------ for i in range(len(hashtags)): val = 0 if (len(hashtags[i]) == 0): pass else: for hashWord in hashtags[i]: newj = getCamelCaseList(hashWord) if(newj != [] or hashWord!=""): if(len(newj)>1): #print (newj) for j in newj: if j in posWords: #print "hash pos many ", hashWord sentimentScore[i] += averageChangeInSentiment*2 elif j in negWords: #print "hash neg many ", hashWord sentimentScore[i] -= averageChangeInSentiment*2 else: #print (hashWord) if hashWord in posWords: #print "hash pos ",hashWord sentimentScore[i] += averageChangeInSentiment*2 elif hashWord in negWords: #print "hash neg ",hashWord sentimentScore[i] -= averageChangeInSentiment*2 #---------------------------------- POS tagging ----------------------------- class Splitter(object): def __init__(self): self.nltk_splitter = nltk.data.load('tokenizers/punkt/english.pickle') self.nltk_tokenizer = nltk.tokenize.TreebankWordTokenizer() def split(self, text): sentences = self.nltk_splitter.tokenize(text) tokenized_sentences = [self.nltk_tokenizer.tokenize(sent) for sent in sentences] return tokenized_sentences class POSTagger(object): def __init__(self): pass def pos_tag(self, sentences): pos = [nltk.pos_tag(sentence) for sentence in sentences] # adapt format pos = [[postag for (word, postag) in sentence] for sentence in pos] #(word, [postag]) return pos for i in range(len(tweets)): splitter = Splitter() postagger = POSTagger() splitted_sentences = splitter.split(tweets[i]) pos_tagged_sentences = postagger.pos_tag(splitted_sentences) for j in range(len(pos_tagged_sentences)): for k in range(len(pos_tagged_sentences[j])): #print pos_tagged_sentences[j][k], pos_tagged_sentences[j][k] in ['NN', 'NNS', 'NNP'], \ # pos_tagged_sentences[j][k] in ['JJ', 'JJR', 'JJS'], \ # pos_tagged_sentences[j][k] in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'], \ # splitted_sentences[j][k], splitted_sentences[j][k] in posWords, splitted_sentences[j][k] in negWords, \ # sentimentScore[i] try: if(pos_tagged_sentences[j][k] in ['NN', 'NNS', 'NNP']): #print "noun ahe" if(splitted_sentences[j][k] in posWords): if(k>0 and pos_tagged_sentences[j][k-1] in ['JJ', 'JJR', 'JJS']): #print "pos k > 0" sentimentScore[i] += averageChangeInSentiment*2 else: #print "fakt noun pos" sentimentScore[i] += averageChangeInSentiment elif(splitted_sentences[j][k] in negWords): if(k>0 and pos_tagged_sentences[j][k-1] in ['JJ', 'JJR', 'JJS']): #print "neg k>0" sentimentScore[i] -= averageChangeInSentiment*2 else: #print "fak noun neg" sentimentScore[i] -= averageChangeInSentiment elif(pos_tagged_sentences[j][k] in ['JJ', 'JJR', 'JJS']): if splitted_sentences[j][k] in posWords: sentimentScore[i] += averageChangeInSentiment*2 elif splitted_sentences[j][k] in negWords: sentimentScore[i] -= averageChangeInSentiment*2 elif(pos_tagged_sentences[j][k] in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']): stemmed_verb = stemmer.stem(splitted_sentences[j][k]) #print " stem verb ",stemmed_verb, stemmed_verb in posWords, stemmed_verb in negWords if stemmed_verb in posWords: sentimentScore[i] += averageChangeInSentiment*2 elif stemmed_verb in negWords: sentimentScore[i] -= averageChangeInSentiment*2 except: pass #------------------ print SentimentScore ---------- # for score in range(len(sentimentScore)): # print (tweets[score], sentimentScore[score], targets[score]) for score in range(len(sentimentScore)): if(sentimentScore[score] > 0): posTweets.append(sentimentScore[score]) posTweetIDs.append(score) elif(sentimentScore[score] < 0): negTweets.append(sentimentScore[score]) negTweetIDs.append(score) print ("--------------tweets-------------") #print (len(sentimentScore)) #out = [x for x in sentimentScore if x>0] #print ("out", len(out), out) sentimentScorePositiveFile = open('sentimentPosScore.txt', 'w') for i in range(len(posTweets)): if(i != len(posTweets)-1): sentimentScorePositiveFile.write(str(posTweetIDs[i])+":"+str(posTweets[i])+",") else: sentimentScorePositiveFile.write(str(posTweetIDs[i])+":"+str(posTweets[i])) sentimentScoreNegativeFile = open('sentimentNegScore.txt', 'w') for i in range(len(negTweets)): if (i != len(negTweets) - 1): sentimentScoreNegativeFile.write(str(negTweetIDs[i])+":"+str(negTweets[i]) + ",") else: sentimentScoreNegativeFile.write(str(negTweetIDs[i])+":"+str(negTweets[i])) #######------------------- files sentimentPosScore.txt & sentimentNegScore.txt contain #######------------------- sentiment scores processed from line 145 to line 367 ###-- comment from line 372 to 389 after uncommenting above lines to get sentiment scores again. # pos_tweets = [] # pos_tweets_id = [] # neg_tweets = [] # neg_tweets_id = [] # pos_tweets_file = open('sentimentPosScore.txt') # neg_tweets_file = open('sentimentNegScore.txt') # read_pos = pos_tweets_file.read().split(",") # for row in read_pos: # pos_tweets_id.append(int(row.split(":")[0])) # pos_tweets.append(float(row.split(":")[1])) # read_neg = neg_tweets_file.read().split(",") # for row in read_neg: # neg_tweets_id.append(int(row.split(":")[0])) # neg_tweets.append(float(row.split(":")[1])) #------------------ fuzzy C Means --------------------- m = 2.0 #membership_constant def getNumerator(arrayOfMemArray, emotweets): mem = [0]*3 for i in range(len(emotweets)): for j in range(3): mem[j] += math.pow(arrayOfMemArray[i][j], m)*emotweets[i] return mem def getDenominator(arrayOfMemArray, emotweets): mem = [0]*3 for i in range(len(emotweets)): for j in range(3): mem[j] += math.pow(arrayOfMemArray[i][j], m) return mem def getMatrixDifference(arrayOfMemArray, emotweets): diff1 = 0; diff2 = 0 for i in range(len(emotweets)): if i == 0: diff1 = math.fabs(arrayOfMemArray[i][0] - arrayOfMemArray[i][1]) diff2 = math.fabs(arrayOfMemArray[i][1] - arrayOfMemArray[i][2]) new_diff1 = math.fabs(arrayOfMemArray[i][0] - arrayOfMemArray[i][1]) new_diff2 = math.fabs(arrayOfMemArray[i][1] - arrayOfMemArray[i][2]) if(new_diff1 < diff1): diff1 = new_diff1 if(new_diff2 < diff2): diff2 = new_diff2 if(diff1 > 0.15 and diff2 > 0.15 and i<len(emotweets)-1): return True return False finalCentroids = [] def fuzzyCMeans(emotweets, emotweetIDs, targets, centroids, finalClustersDictIdx): cluster1 = [] cluster2 = [] cluster3 = [] for i in range(len(emotweets)) : arrayOfMemArray = [] for score in emotweets: score = float(score) membershipArray = [] for centroid_j in centroids: membership = 0 for centroid_k in centroids: membership += math.pow( math.fabs(score-centroid_j) / math.fabs( (score+0.001)-centroid_k), 2/(m-1) ) membership = 1/(membership+0.001) membershipArray.append(membership) arrayOfMemArray.append(membershipArray) numerator = np.array(getNumerator(arrayOfMemArray, emotweets)) denominator = np.array(getDenominator(arrayOfMemArray, emotweets)) centroids = numerator/denominator boolVal = getMatrixDifference(arrayOfMemArray, emotweets) if boolVal == True or i==len(emotweets)-1: for i in range(len(emotweets)): dist1 = math.fabs(centroids[0] - emotweets[i]) dist2 = math.fabs(centroids[1] - emotweets[i]) dist3 = math.fabs(centroids[2] - emotweets[i]) #+ str(emotweetIDs[i])+"," if(dist1 > dist2): if(dist2 > dist3): #cluster3.append(str(emotweets[i])+","+ str(targets[emotweetIDs[i]])) cluster3.append(int(targets[emotweetIDs[i]])) else: cluster2.append(int(targets[emotweetIDs[i]])) else: if(dist1 > dist3): cluster3.append(int(targets[emotweetIDs[i]])) else: cluster1.append(int(targets[emotweetIDs[i]])) finalClusters.append(cluster1) finalClusters.append(cluster2) finalClusters.append(cluster3) for centroid in centroids: finalCentroids.append(centroid) #####---- if you are uncommenting line 145 to 367 and commenting lines 372 to 389, uncomment 502 and 508 #####---- & comment 505 & 511. Currently we are using data from sentimentPosScore and NegScore #####---- so we are using lines 505 and 511 #####---- else use lines 502 and 508 finalClustersDictIdx = 1 fuzzyCMeans(posTweets, posTweetIDs, targets, [0, 1, 3], finalClustersDictIdx) #for test version with senti files # fuzzyCMeans(pos_tweets, pos_tweets_id, targets, [0, 0.5, 1], finalClustersDictIdx) finalClustersDictIdx = 4 fuzzyCMeans(negTweets, negTweetIDs, targets, [0, -1, -3], finalClustersDictIdx) #full version #test # fuzzyCMeans(neg_tweets, neg_tweets_id, targets, [0, -0.25, -0.5], finalClustersDictIdx) print np.array(finalCentroids).flatten() finalClustersDict = {1:"", 2:"", 3:"", 4:"", 5:"", 6:""} finalClustersIdx = [] k = 0 for clusters in finalClusters: finalClustersIdx.append([]) for cluster in clusters: myidx = finalCentroids.index(min(finalCentroids, key=lambda x: abs(x - cluster)))+1 #print cluster, centroids, myidx finalClustersIdx[k].append(myidx) k += 1 indices = [] for cluster in finalClustersIdx: indices.append(max(cluster,key=cluster.count)) #print indices accuracy = [0]*len(finalCentroids) k = 0 for cluster in finalClustersIdx: for row in cluster: if(row == indices[k]): accuracy[k] += 1 k += 1 for row in range(len(accuracy)): #print accuracy[row], len((finalClusters[row])) accuracy[row] = accuracy[row]/float(len(finalClusters[row]))*100 #print "Accuracy for individual emotions", accuracy print "Average accuracy", sum(accuracy)/len(accuracy) elapsed = timeit.default_timer() - start_time print("Time elapsed is ",elapsed)
true
71884c9fc4ee836af4589d5cfe6e87777cfe9321
Python
sranyjstrannik/codeforces
/codeforces386/A.py
UTF-8
140
3.421875
3
[]
no_license
a = int(input()) b = int(input()) c = int(input()) for i in range(a,-1,-1): if 2*i <= b and 4*i <= c: print(7*i) break
true
dedb56d6b874283066589a5e8468a845df49d165
Python
Bubbleskye/2019summer
/leetcode/删除回文子数组.py
UTF-8
1,097
3.171875
3
[]
no_license
def minimumMoves(arr): # 回文子数组即是连续的一段 # dp[i][j]删除arr[i:j+1]这一段所需要进行的操作次数 # if arr[i]==arr[j]: dp[i][j]=dp[i+1][j-1] # 如果头尾相同的话,这两个字符不用单独算一次删除,这两个字符只要跟着中间的随便哪个组合一起删掉就可以 # else: dp[i][j]=min(dp[i][k]+dp[k+1][j]) # 如果头尾不相同的话,分两段逐个找最小 dp = [[float("inf") for _ in range(len(arr))] for _ in range(len(arr))] for j in range(len(arr)): for i in range(j, -1, -1): if i == j: dp[i][j] = 1 elif i + 1 == j and arr[i] == arr[j]: dp[i][j] = 1 elif i + 1 == j and arr[i] != arr[j]: dp[i][j] = 2 else: if arr[i]==arr[j]: dp[i][j] = dp[i + 1][j - 1] else: for k in range(i, j): dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]) return dp[0][-1] arr = [1,3,4,1,5] print(minimumMoves(arr))
true
a7db77bcfcd1270d7fab048d9d860c1a7fef594f
Python
abir-taheer/speed-a-la-mode
/methods/v1_abir.py
UTF-8
1,549
4.53125
5
[]
no_license
def mode(nums: list) -> list: """ Return the most occurring item in a list :param nums: A numerical list :return: The item that appears the most in the list >>> list_mode([1, 2, 3, 1]) [1] >>> list_mode([-1, -4, 9, 2, -4, 9, -4]) [-4] >>> list_mode(["hello", 0, 2, 3, 2, "hello", "hello"]) ['hello'] """ # Initialize two variables # Numbers will hold all unique items that appear in the provided list numbers = [] # Frequency will store how many times each item at the same index of numbers appears in the provided list frequency = [] modes = [] # Check all items in the provided list for x in nums: # Check if it appears in numbers if x not in numbers: # If it does not appear in numbers, add it to numbers and to the frequency lists # They are both added at the same time and their indexes in each list will correspond to each other numbers.append(x) frequency.append(0) # Find the item in the numbers list and increment its counter at the same index of the frequency list frequency[numbers.index(x)] += 1 # Return the item from the numbers list that has the same index as the index of the # highest number in the frequency list max_frequency = max(frequency) for x in range(len(frequency)): if frequency[x] == max_frequency: modes.append(numbers[x]) return modes name = "V1: Two Buckets"
true
b1785e22fea9c3ed82b527d5b771a78b61583f5a
Python
Sohyo/IDS_2017
/Assignment4/script_21.py
UTF-8
1,039
2.828125
3
[]
no_license
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np path = "/Users/danielmlow/Dropbox/lct/data_science/assignment4/lastfm-dataset-1K/" df = pd.read_csv(path+'last_fm_user_band.csv') df = df.iloc[:,1:] pd.set_option('display.float_format', lambda x: '%.4f' % x) uniq = df.iloc[:,1].value_counts(normalize=True) uniq_20 = uniq[:20] uniq_20.plot.bar() plt.xlabel('Bands') plt.ylabel('Probability of being played') plt.title('Highest frequency bands') plt.savefig(path+'../'+'highest_freq_bands.png',bbox_inches='tight') d = {} for index, row in df.iterrows(): user = row['user'] band = row['band'] if user in d: d[user].add(band) else: print(user) d[user] = set([]) d[user].add(band) l = [] for i in d: l.append(len(d[i])) l = l[:-2] arr = np.asarray(l) plt.hist(arr,bins=20,normed=True) plt.ylabel('Normalized frequency of users') plt.xlabel('Amount of bands per user') plt.title('Amount of bands per user') plt.savefig(path+'../'+'bands per user.png',bbox_inches='tight')
true
58ad8d3929ef9177a48681f21451f21bdc472dc4
Python
ineedacookie/SimpleEncodingExercise
/EncodeDecode.py
UTF-8
6,225
2.859375
3
[]
no_license
import numpy as np import random class OTPInvalidInputError(Exception): def __init__(self, provided_obj): super().__init__('OneTimePad require an array of ints. You provided {}: {}'.format(type(provided_obj), provided_obj)) plainTextMessage = "WE ARE DISCOVERED. FLEE AT ONCE" compositeKey = "1422555515" polybius = np.array([['E', '2', 'R', 'F', 'Z', 'M'], ['Y', 'H', '3', '0', 'B', '7'], ['O', 'Q', 'A', 'N', 'U', 'K'], ['P', 'X', 'J', '4', 'V', 'W'], ['D', '1', '8', 'G', 'C', '6'], ['9', 'I', 'S', '5', 'T', 'L']]) def getLocationInSquare(letter): location = np.where(polybius == letter) loc_string = str(location[0][0]) + str(location[1][0]) loc_int = int(loc_string) return loc_int def oneTimePadEncode(plaintext, key): return_value = '' otp_values = plaintext if isinstance(plaintext, str): otp_values = [getLocationInSquare(l) for l in plaintext] elif not isinstance(plaintext, list): raise OTPInvalidInputError(plaintext) for value in otp_values: return_value += '{0:0=2d}'.format(int(value) ^ int(key)) return return_value def oneTimePadDecode(encoded_str, key): return_value = '' if isinstance(encoded_str, str) and encoded_str.isnumeric() and len(encoded_str) % 2 == 0: otp_values = [int(encoded_str[i:i + 2]) for i in range(0, len(encoded_str), 2)] else: raise OTPInvalidInputError(encoded_str) for value in otp_values: xor_result = '{0:0=2d}'.format(value ^ int(key)) return_value += polybius[int(xor_result[0])][int(xor_result[1])] return return_value def getColumnarTranspositionKey(compositeKey): lst = [] start = 0 end = 2 while end < len(compositeKey): lst.append(compositeKey[start:end]) start += 2 end += 2 key = "" for pair in lst: key += polybius[int(pair[0])][int(pair[1])] return key def getPolybiusStr(plainText): cleanedPlainText = "" for char in plainText: if (char.upper() not in (item for sublist in polybius for item in sublist)): continue cleanedPlainText = cleanedPlainText + char return cleanedPlainText def encryptWithColumnarTransposition(plainText, key): innerCounter = 0 outerLst = [] cleanedPlainText = getPolybiusStr(plainText) padAmount = 0 needsPadding = len(cleanedPlainText) % len(key) if (needsPadding != 0): padAmount = 5 for i in range(0, padAmount): cleanedPlainText = cleanedPlainText + str(random.randrange(0, 10, 1)) innerLst = [] for char in cleanedPlainText: innerLst.append(char) innerCounter = innerCounter + 1 if (innerCounter >= len(key)): outerLst.append(innerLst) innerLst = [] innerCounter = 0 sortedKey = "".join(sorted(key)) sortedKeyPairs = [] for i in range(0, len(sortedKey)): sortedKeyPairs.append((sortedKey[i], i, -1)) newSortedKeyPairs = [] for i in range(0, len(key)): for j in range(0, len(sortedKeyPairs)): if key[i] == sortedKeyPairs[j][0]: newSortedKeyPairs.append((sortedKeyPairs[j][0], sortedKeyPairs[j][1], i)) sortedKeyPairs[j] = ("*", sortedKeyPairs[j][1], i) break sortedKeyPairs = newSortedKeyPairs cipherArray = [] for i in range(0, len(key)): cipherArray.append([]) for i in range(0, len(sortedKeyPairs)): text_str = "" newIndex = sortedKeyPairs[i][1] originalIndex = sortedKeyPairs[i][2] for j in range(0, len(outerLst)): text_str += outerLst[j][originalIndex] cipherArray[newIndex] = text_str return ''.join(cipherArray) def createDecodeMatrix(cybertext, key): lenKey = len(key) lenTxt = len(cybertext) sortedKey = sorted(key) try: rowsn = int(lenTxt / lenKey) except Exception as e: print(e) return None matrix = [] positionKey = {} tempKey = [char for char in key] for i in range(lenKey): for j in range(lenKey): if sortedKey[i] == tempKey[j]: tempKey[j] = None positionKey[i] = j break x = 0 for i in range(rowsn): tempArray = [] temp = x for j in range(lenKey): tempArray.append(cybertext[temp]) temp += rowsn x += 1 unsortTempArray = tempArray.copy() for j in range(lenKey): unsortTempArray[positionKey[j]] = tempArray[j] matrix.append(unsortTempArray) return matrix def compressMatrix(matrix): string = '' for i in matrix: for j in i: string += j return string def __main__(): print('Plaintext message: {}'.format(plainTextMessage)) # task 1 key = getColumnarTranspositionKey(compositeKey) first_encode = encryptWithColumnarTransposition(plainTextMessage, key) print("Task 1\n" "Input: \n" " Composite Key: " + compositeKey + "\n" + " Plaintext message: " + plainTextMessage + "\n") print("First encoding: " + first_encode) second_encode = oneTimePadEncode(first_encode, compositeKey[-2:]) print("Output from 2nd encode (OneTimePad encoding): {}".format(second_encode)) # task 2 print("\n===================\n" "Task 2\n" "Input: \n" " Composite Key: " + compositeKey + "\n" + " encoded message: {}\n".format(second_encode)) first_decoding = oneTimePadDecode(second_encode, compositeKey[-2:]) print("First decoding {}".format(first_decoding)) """ Everything after this point is to decrypt the columner transpostion that the first decoding returns """ key = getColumnarTranspositionKey(compositeKey) cybertext = first_decoding sortedKey = sorted(key) matrix = createDecodeMatrix(cybertext, key) decoded = compressMatrix(matrix) print("Second and final Decoding: " + decoded + "\n") print("Output: " + decoded) if __name__ == '__main__': __main__()
true
7added06b54850be5f57ac7af8fb8ce1eb6ab37c
Python
baobaobaobaobao/mypaper
/jarden_center/main_code/divid/NET.py
UTF-8
6,551
2.90625
3
[]
no_license
import networkx as nx import random from Girvan_Newman import GN #引用模块中的函数 #读取文件中边关系,然后成为一个成熟的图 def ContractDict(dir,G): with open(dir, 'r') as f: for line in f: line1=line.strip().split(",") # print (line1) G.add_edge(int(float(line1[0])),int(float(line1[1]))) # print (G.number_of_edges()) return G #生成感染图,我们看看感染图是什么样子。 def Algorithm1(G,basesore,sourceList): SG=nx.Graph() print ("感染列表送入,为啥加不进去",sourceList) for index in range(0,6): for sourceItem in list(sourceList): SG.add_node(sourceItem) for sourceNeightor in list(G.neighbors(sourceItem)): # 将感染点邻接点以一定概率加入到感染节点当中。 # random_number=random.random() # if random_number>0.6: #他们的传染边还要加上特别的属性,比如方向传播属性。 G.add_node(sourceNeightor, Cn=1) SG.add_node(sourceNeightor) SG.add_edge(sourceItem,sourceNeightor) if G.node[sourceNeightor]['Cn']==1: G.node[sourceNeightor]['Scn']+=G.nodes[sourceItem]['Scn'] #对所有n<V(就是分数达到阕值的节点感染)算是谣言的不同之处吧。更新。 for index in range(1,35): if G.node[index]['Scn']>basesore: G.add_node(index, Cn=1) return G,SG #产生head以及tail中的一个随机数。 def randomNum(head,tail): random.random() #遍历这个文件中每一条边,也就是行。然后在被传染或者恢复的边中。选中其中一些边作为 #已经传染,或者已经被传染,这需要g以及对文件的操作。 def Product_infection_Graph(G,dir): GInfetion = nx.Graph() #获取所有关于这个已经感染总图的被感染子图。 infection=[] count=1 for index in range(1,35): if G.nodes[index]['Cn'] == 1: infection.append(index) count+=1 # print ('cont',count) # print ('indexlist',len(infection)) with open(dir, 'r') as f: for line in f: line1=line.strip().split(",") if int(float(line1[0])) in infection and int(float(line1[1])) in infection: GInfetion.add_node(int(float(line1[0]))) GInfetion.add_node(int(float(line1[1]))) GInfetion.add_edge(int(float(line1[0])),int(float(line1[1]))) return GInfetion #定义函数来进行分区后的谣言定位 ''' parameter:多个社区的分区,以及被传播的节点,现在分别计算度以及中心性,进行源头判断。 ''' def cal_source(G,infectList): #按照分区的来进行判断源点。 # print (len(infectList)) # print('感染图,节点总数', G.number_of_nodes()) # print('感染图,边总数', G.number_of_edges()) # print('感染图,边总数', G.edges()) lists = [[] for _ in range(len(infectList))] centrality = nx.betweenness_centrality(G) # print(sorted((v, '{:0.2f}'.format(c)) for v, c in centrality.items())) for v, c in centrality.items(): for i in range(len(infectList)): if v in infectList[i]: lists[i].append([v,c]) #对lists进行排序。 for i in range(len(lists)): secList=sorted(lists[i],key=lambda x:(str(x[1]).lower(),x[0]),reverse = True ) print (secList) # for i in range(len(lists)): # print (lists[i]) # 制造这个图 Ginti = nx.Graph() #初始化图 for index in range(1,35): Ginti.add_node(index) print (index) #构建图 G=ContractDict('karate_[Edges].csv',Ginti) print ('一开始图的顶点个数',G.number_of_nodes()) print ('一开始图的边个数',G.number_of_edges()) ''' 生成若干个感染节点。也就是谣言源点。每个节点有Cn以及Scn属性。 ''' # 先给全体的Cn、Scn的0的赋值。 for index in range(1,35): G.add_node(index, Cn=0,Scn=0) # print (G.nodes[6416]) # 随机产生5个感染点。 sourceList=[] for index in range(1,6): random_RumorSource=0 random_RumorSource=random.randint(1, 34) sourceList.append(random_RumorSource) G.add_node(random_RumorSource,Cn=1) print ('感染点列表',sourceList) # 图形化还差得远。很烦。 # 开始送入我们的算法中,就G和basesore,还有感染源list三个参数 GResult,SGResult=Algorithm1(G,5,sourceList) #打印出所传染的节点个数 Infected_node=[] for i in range(1,35): if G.node[i]['Cn']== 1: Infected_node.append(i) print ('感染点计数,以及他们',len(Infected_node),Infected_node) # #打印出Csn # for i in range(1,35): # if G.node[i]['Cn']== 1: # # print ('print Scn',G.node[i]['Scn']) # # 生成感染图(注意,这里的感染图。是有所有接触过的顶点) ,不包括之前的未感染的边。 GInfection=Product_infection_Graph(G,'karate_[Edges].csv') #我想看看感染图, nx.write_gml(GInfection,'test.gml') #copy防止引用 import copy SGResult_copy=copy.deepcopy(SGResult) print ('感染图,节点总数',SGResult.number_of_nodes()) print ('感染图,边总数',SGResult.number_of_edges()) print ('感染图,点显示',SGResult.nodes()) print ('感染图,边总数',SGResult.edges()) import csv #python2可以用file替代open with open("test.csv","w") as csvfile: writer = csv.writer(csvfile) cout=1 writer.writerow(["source","target","type","Id"]) for u,v in SGResult.edges(): cout+=1 writer.writerow([u,v,"Directed",cout]) #python2可以用file替代open with open("test1.csv","w") as csvfile: writer = csv.writer(csvfile) writer.writerow(["id","label"]) for u in SGResult.nodes(): if u in sourceList: writer.writerow([u,'source']) else: writer.writerow([u]) # 将感染图,进行GN分区。 # algorithm = GN(GInfection) algorithm = GN(SGResult) partition, all_Q, max_Q=algorithm.run() #暂时不需要画图 # algorithm.draw_Q() algorithm.add_group() algorithm.to_gml() # 现在已经知道被感染的节点,那么问题来了,如何在被感染的分区之后的一些节点中找到 #源? #prepare parameter:准备参数,也就是我们的。 cal_source(SGResult_copy,partition)
true
44d890b71390252fe0e11576770615005d0d2de9
Python
atjones90/Jones_DSC510
/IMHOF_DSC510/hello.py
UTF-8
570
3.953125
4
[]
no_license
# Taylor Imhof # Bellevue University | DSC 510 # Date Created: 6.7.2021 # Last Update: 6.10.2021 # Change Log: # 6.8.2021 -- Added functionality to accept user's name from console and display short greeting # 6.10.2021 -- Updated documentation to reflect changes # hello.py # this program first displays the string "Hello, world!" to the console # then, the user is prompted for their name and a short greeting is then display to the console print('Hello, world!\n') name = input('What is your name, stranger?\n') print(f"Well, top of the mornin' to ya, {name}!")
true
02dbe6225a2edac584e5c7eeefe1aa3f12417a08
Python
gitter-badger/dbcollection
/dbcollection/tests/datasets/__test_check_urls.py
UTF-8
2,094
3.109375
3
[ "MIT" ]
permissive
""" Test dataset's urls download status. """ import pytest import signal import requests from dbcollection.core.api import fetch_list_datasets TIMEOUT_SECONDS = 3 def get_list_urls_dataset(): available_datasets = fetch_list_datasets() dataset_urls = [] for name in available_datasets: url_list = [] urls = available_datasets[name]['urls'] for url in urls: if isinstance(url, str): url_list.append(url) elif isinstance(url, dict): try: url_ = url['url'] url_list.append(url_) except KeyError: pass # do nothing else: raise Exception('Unknown format when downloading urls: {}'.format(type(url))) # add list to the out dictionary dataset_urls.append((name, url_list)) return dataset_urls class Timeout(): """Timeout class using ALARM signal.""" class Timeout(Exception): pass def __init__(self, sec): self.sec = sec def __enter__(self): signal.signal(signal.SIGALRM, self.raise_timeout) signal.alarm(self.sec) def __exit__(self, *args): signal.alarm(0) # disable alarm def raise_timeout(self, *args): raise Timeout.Timeout() def check_url_redirect(url): try: with Timeout(TIMEOUT_SECONDS): response = requests.get(url) return response.status_code == 200 except Timeout.Timeout: return True @pytest.mark.parametrize("dataset_name, urls", get_list_urls_dataset()) def test_check_urls_are_valid(dataset_name, urls): for url in urls: response = requests.head(url) # try without redirect enabled if response.status_code == 200: status = True else: if response.status_code == 301: status = check_url_redirect(url) # try with redirect enabled else: status = False assert status, 'Error downloading urls from {}: {}'.format(dataset_name, url)
true
699c2b83108a072ac70fd68cc47e4bd4c036ecb5
Python
ashwin21rao/Sudoku-Solver
/gui.py
UTF-8
7,157
2.984375
3
[]
no_license
import pygame import numpy as np pygame.init() clock = pygame.time.Clock() font_large = pygame.font.Font("extras/OpenSans-Bold.ttf", 25) font_small = pygame.font.Font("extras/OpenSans-Bold.ttf", 20) screen_width = 600 screen_height = 600 side_length = 405 margin = (screen_width - side_length) / 2 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Sudoku") icon = pygame.image.load("extras/icon.png") pygame.display.set_icon(icon) COLOR_BLACK = (0, 0, 0) COLOR_GRAY = (92, 92, 92) COLOR_ACTIVE = (40, 111, 156) COLOR_RED = (255, 0, 0) COLOR_GREEN = (0, 255, 0) COLOR_BLUE = (0, 0, 255) def clear(values, mask): values[np.logical_not(mask)] = 0 def solve(array, i, j, cells, mask, start_time): if j > 8: j = 0 i += 1 if i > 8: return True if array[i, j] != 0: return solve(array, i, j + 1, cells, mask, start_time) active_cell = cells[i][j] for value in range(1, 10): array[i, j] = value drawBoard(cells, array, mask, active_cell, start_time, True) drawButtons() pygame.display.flip() pygame.time.delay(5) if validCell(array, i, j, value): if solve(array, i, j + 1, cells, mask, start_time): return True array[i, j] = 0 return False def validCell(array, i, j, value): return np.count_nonzero(array[i, :] == value) == 1 and \ np.count_nonzero(array[:, j] == value) == 1 and \ np.count_nonzero(array[i // 3 * 3: i // 3 * 3 + 3, j // 3 * 3: j // 3 * 3 + 3] == value) == 1 def sudokuValues(game_number): data = np.loadtxt("games.txt", delimiter=", ", dtype=np.int).reshape((-1, 9, 9)) array = data[game_number] mask = (array != 0) return array, mask def updateTime(start_time): current_time = (pygame.time.get_ticks() - start_time) // 1000 time = "" for i in range(3): if current_time > 0: value = "0" + str(current_time % 60) if (current_time % 60) < 10 else str(current_time % 60) time = ":" + value + time current_time //= 60 else: time = (":00" if i != 2 else "00") + time return time def getCells(): cell_side = side_length / 9 cells = [[pygame.Rect(0, 0, 0, 0) for _ in range(9)] for _ in range(9)] for i in range(9): for j in range(9): cells[i][j] = pygame.Rect(margin + cell_side * j, margin + cell_side * i, cell_side, cell_side) return cells def drawButtons(): new_game_text = font_small.render("New Game", False, (255, 0, 0)) new_game_button = new_game_text.get_rect(bottomleft=(margin, margin)) screen.blit(new_game_text, new_game_button) solve_text = font_small.render("Solve", False, (0, 255, 0)) solve_button = solve_text.get_rect(topleft=(margin, margin + side_length)) screen.blit(solve_text, solve_button) clear_text = font_small.render("Clear", False, (0, 0, 255)) clear_button = clear_text.get_rect(topright=(screen_width - margin, margin + side_length)) screen.blit(clear_text, clear_button) return {"new game": new_game_button, "solve": solve_button, "clear": clear_button} def drawBoard(cells, values, mask, active_cell, start_time, solving=False): screen.fill((255, 255, 255)) for i, row in enumerate(cells): for j, cell in enumerate(row): pygame.draw.rect(screen, (125, 130, 130), cell, 1) if values[i, j] != 0: if mask[i, j]: text = font_large.render(str(values[i, j]), False, COLOR_BLACK) else: text = font_large.render(str(values[i, j]), False, COLOR_GRAY if not solving and validCell(values, i, j, values[i, j]) else COLOR_GREEN if solving and validCell(values, i, j, values[i, j]) else COLOR_RED) center = text.get_rect(center=cell.center) screen.blit(text, center) pygame.draw.rect(screen, COLOR_BLACK, (margin, margin, side_length, side_length), 4) for i in range(1, 3): pygame.draw.line(screen, COLOR_BLACK, (margin, margin + side_length * i / 3), (margin + side_length, margin + side_length * i / 3), 3) pygame.draw.line(screen, COLOR_BLACK, (margin + side_length * i / 3, margin), (margin + side_length * i / 3, margin + side_length), 3) if active_cell: pygame.draw.rect(screen, COLOR_ACTIVE, active_cell, 3) time = updateTime(start_time) time_text = font_large.render(time, False, COLOR_BLACK) pos = time_text.get_rect(bottomright=(screen_width - margin, margin)) screen.blit(time_text, pos) def initializeGame(game_number): values, mask = sudokuValues(game_number) original_array = values.copy() solved_array = values.copy() return values, mask, original_array, solved_array def gameloop(): start_time = pygame.time.get_ticks() game_number = 0 total_games = 5 cells = getCells() active_cell = None active_cell_index = None values, mask, original_array, solved_array = initializeGame(game_number) running = True while running: drawBoard(cells, values, mask, active_cell, start_time) buttons = drawButtons() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False if '1' <= chr(event.key) <= '9' and active_cell: if not mask[active_cell_index]: values[active_cell_index] = chr(event.key) if (event.key == pygame.K_BACKSPACE or event.key == pygame.K_DELETE) and active_cell: if not mask[active_cell_index]: values[active_cell_index] = 0 if event.type == pygame.MOUSEBUTTONDOWN: for i, row in enumerate(cells): for j, cell in enumerate(row): if cell.collidepoint(event.pos[0], event.pos[1]): active_cell = cell active_cell_index = (i, j) if buttons["solve"].collidepoint(event.pos[0], event.pos[1]): solve(solved_array, 0, 0, cells, mask, start_time) values = solved_array.copy() solved_array = original_array.copy() if buttons["clear"].collidepoint(event.pos[0], event.pos[1]): clear(values, mask) if buttons["new game"].collidepoint(event.pos[0], event.pos[1]): start_time = pygame.time.get_ticks() game_number = (game_number + 1) % total_games values, mask, original_array, solved_array = initializeGame(game_number) pygame.display.flip() clock.tick(30) pygame.quit() gameloop()
true
62024bd9b021f59e359647ebfa0c29473d6d91c4
Python
Gholtes/Keras-Deep-Dream
/deepDream.py
UTF-8
5,143
2.828125
3
[ "MIT" ]
permissive
from keras.applications import VGG16 from keras.applications.vgg16 import preprocess_input from keras.layers import Input from keras import backend as K import numpy as np from PIL import Image import scipy ''' Deep dream application based on VGG16 classifier, pretrained on imagenet dataset Written by Grant Holtes, December 2018 www.grantholtes.com ''' def preprocessImage(image): '''preprocess for vgg16''' return preprocess_input(np.expand_dims(image, axis=0)) def postProcessArray(x): '''transform back to RGB to then be exported''' x[..., 0] += 103.939 x[..., 1] += 116.779 x[..., 2] += 123.68 # 'BGR'->'RGB' x = x[..., ::-1] x = np.clip(x, 0, 255) x = x.astype('uint8') return x def saveImage(NPimage, pathForOutput): dream = Image.fromarray(postProcessArray(NPimage[0])) dream.save(pathForOutput) def resizeImage(size, NPimage): '''side = max side length of the output''' shape = NPimage.shape scaleH = size[0] / shape[1] scaleW = size[1] / shape[2] NPimage = scipy.ndimage.zoom(NPimage, (1, scaleH, scaleW, 1), order=1) return NPimage def getFeatureReps(layer_names, Model): '''Get the activations of all layers in the list 'layer_names''' featureMatrices = [] for layer in layer_names: selectedLayer = Model.get_layer(layer) featureMatrices.append(selectedLayer.output) return featureMatrices def loss(layer_names, Model): '''Define how the loss is evaluated''' return - K.sum(getFeatureReps(layer_names, Model)) def gradient(NPimage, layer_names, model): '''Get the gradient of the loss with respect to each input pixel''' gradFunc = K.function([model.input], K.gradients(loss(layer_names, model), [model.input])) return gradFunc([NPimage]) def gradientAccent(NPimage, layer_names, iterations = 5, learningRate = 8): for iter in range(iterations): print("Iteration: {0}".format(iter+1)) gradIter = gradient(NPimage, layer_names, Model) NPimage = np.add(NPimage, -np.multiply(gradIter, learningRate))[0] return NPimage def Main(Model = VGG16(include_top=False, weights='imagenet'), pathToImage = "data.jpg", pathForOutput = "dream.jpg", learningRate = 8, maxSize = "Native", minSize = 100, sizeSteps = 3, iterationsPerSize = 10, layer_names = ['block5_pool']): #Load data original = Image.open(pathToImage) originalSize = original.size original = np.array(original) NPimage = preprocessImage(original) #Save a copy of original: NPoriginal = NPimage.copy() originalUpscaledShrunkImage = NPimage.copy() #Check size of the image if maxSize > max(originalSize): maxSize = max(originalSize) if maxSize < minSize: print("ERROR: maxSize < minSize, quitting") exit() #make sizes sizes = [] for step in range(sizeSteps): Max = round(minSize + step*(maxSize-minSize)/(sizeSteps-1)) if originalSize[0] > originalSize[1]: w = Max h = round(Max*originalSize[1] / originalSize[0]) else: w = round(Max*originalSize[0] / originalSize[1]) h = Max sizes.append([h, w]) previousSize = sizes[0] #Set first size #Main for size in sizes: print("Processing image at size: {0}".format(size)) NPimage = resizeImage(size, NPimage) #shrink original image, compare to unscaled original image to recover lost detail / infomation originalUpscaledShrunkImage = resizeImage(size, originalUpscaledShrunkImage) originalAtSize = resizeImage(size, NPoriginal) #Define lost information lostInformation = originalAtSize - originalUpscaledShrunkImage #Add lost infomation back to both the copy and dream (NPImage) images NPimage += lostInformation originalUpscaledShrunkImage += lostInformation #Perform Gradient Accent NPimage = gradientAccent(NPimage, layer_names, iterationsPerSize, learningRate) #final resize: if maxSize < max(originalSize): #Add remaining lost infomation size = [originalSize[1], originalSize[0]] NPimage = resizeImage(size, NPimage) originalUpscaledShrunkImage = resizeImage(size, originalUpscaledShrunkImage) originalAtSize = resizeImage(size, NPoriginal) lostInformation = originalAtSize - originalUpscaledShrunkImage NPimage += lostInformation #Save the image saveImage(NPimage, pathForOutput) #Load Model tf_session = K.get_session() Model = VGG16(include_top=False, weights='imagenet') print("Model Loaded") #Run Deep Dream - Example of parameters. #Run 'Model.summary()' to view other layer_names #Max size = max side length of the image to be processed in pixels Main(Model = Model, pathToImage = "data.jpg", pathForOutput = "dream.jpg", learningRate = 8, maxSize = 2000, minSize = 100, sizeSteps = 5, iterationsPerSize = 7, layer_names = ['block5_pool'])
true
b6f1a4c5d3d300a0f6d6417d9947deb08143de4a
Python
k0psutin/ohtu-2021
/viikko3/nhl-reader/src/index.py
UTF-8
398
2.71875
3
[]
no_license
from player_stats import PlayerStats from player_reader import PlayerReader def main(): url = "https://nhlstatisticsforohtu.herokuapp.com/players" reader = PlayerReader(url) stats = PlayerStats(reader) players = stats.top_scorer_by_nationality("FIN") print("Suomalaiset pelaajat:") for player in players: print(player) if __name__ == "__main__": main()
true
00bb349abfc734fc9123aeb4227f36c4dacae498
Python
GreatStephen/MyLeetcodeSolutions
/Sum of Subarray Minimums/one stack.py
UTF-8
701
3.078125
3
[]
no_license
class Solution: def sumSubarrayMins(self, A: List[int]) -> int: # 只需要一个Stack,就能找到左右山峰 # stack[i-1]是stac[i]左手边的第一个更小数字的下标 # 当前数字大于stack[-1],压栈。当前数字小于stack[-1],则左山峰下标是stack[-2],右山峰下标是当前i deq = collections.deque() A = [0] + A + [0] ans, MOD = 0, 10**9+7 for i,n in enumerate(A): if len(deq)==0: deq.append(i) continue while A[deq[-1]] > n: t = deq.pop() ans += A[t]*(t-deq[-1])*(i-t) deq.append(i) return ans%MOD
true
e7c23031085f797d07e7dcc623b1c56358d23f83
Python
tkoz0/problems-online-judge
/vol_006/p621.py
UTF-8
248
3.125
3
[]
no_license
n = int(input()) for z in range(n): e = input() if e == '1' or e == '4' or e == '78': print('+') elif e[-2:] == '35': print('-') elif e[0] == '9' and e[-1] == '4': print('*') elif e[:3] == '190': print('?') else: assert 0
true
c3b7182962ceb666b76b404169f5186ec03b25f1
Python
bholaa72429/Higher-Lower
/07_HL_statement_generator.py
UTF-8
725
3.953125
4
[]
no_license
# HL component 7 - Statement Generator def h1_statement(statement, char): print() print(char*len(statement)) print(statement) print(char*len(statement)) print # Main routine too_low = h1_statement("^^ Too low, try a higher number. | " "Guesses Left: 3 ^^", "^") print() too_high = h1_statement("vv Too high, try a lower number. | " "Guesses Left: 2 vv", "v") print() duplicate = h1_statement(" !! You already guessed that # Please try again. | " "Guesses Lefts: 2 !!", "!" ) print() well_done = h1_statement("*** Well done! You got it in 3 guesses ***", "*" ) print() start_round = h1_statement("### Round 1 of 3 ###", "#")
true
26bcbca39eade156c22983821ee9dfdcba4d5022
Python
HarryRicardo1989/airQuality
/carrega_display.py
UTF-8
1,032
2.828125
3
[]
no_license
from lcd_12c import LCD class CarregaDisplay: def __init__(self, i2c_bus=0, address=0x00, mode=LCD.MODE4BITS, lines=LCD.LINES2, dots=LCD.DOTS5X8, numLinhas=2): self.display = LCD(i2c_bus, address, mode, lines, dots, numLinhas) def display_line_0(self, string): self.display.writeLine(str(string), 0) def display_line_1(self, string): self.display.writeLine(str(string), 1) def display_line_2(self, string): self.display.writeLine(str(string), 2) def display_line_3(self, string): self.display.writeLine(str(string), 3) def clear_line_0(self): self.display.writeLine('', 0) def clear_line_1(self): self.display.writeLine('', 1) def clear_line_2(self): self.display.writeLine('', 2) def clear_line_3(self): self.display.writeLine('', 3) def desliga_display(self): self.display.backLight(self.display.BACKLIGHT_OFF) def liga_display(self): self.display.backLight(self.display.BACKLIGHT_ON)
true
1681f69dd865865f89235db74f1ae006457a75c9
Python
FiddeEliasson/Pibot-helpfulai
/exts/ArkhamPlayer.py
UTF-8
17,270
2.671875
3
[]
no_license
# ArkhamPlayer extension for Discord ### PREAMBLE ################################################################## import copy import re import discord import requests import random from discord.ext import commands from unidecode import unidecode class ArkhamPlayer(commands.Cog): """Arkham Horror Player handler""" def __init__(self, bot): self.bot = bot ah_api = [] self.Player1 = [] self.Player2 = [] self.Player3 = [] self.Player4 = [] self.init_api = False def numbers_to_strings(self,argument): switcher = { 0: "Investigator", 1: "Health", 2: "Sanity", 3: "IMG URL", } return switcher.get(argument, "nothing") def refresh_ah_api(self): self.ah_api = sorted([c for c in requests.get('https://arkhamdb.com/api/public/cards?encounter=1').json()], key=lambda card: card['name']) # only player cards self.ah_api_p = [c for c in self.ah_api if "spoiler" not in c] self.init_api = True @commands.command(aliases=['arkhamplayerhelp']) async def aphelp(self, ctx): m_response = "Hi! I'm your discord's arkham player bot. Here's what I can do:\n" m_response += "!apadd1 [Investigator] - Add player 1 investigator \n" m_response += "!apadd2 [Investigator] - Add player 2 investigator \n" m_response += "!apadd3 [Investigator] - Add player 3 investigator \n" m_response += "!apadd4 [Investigator] - Add player 4 investigator \n" m_response += "!aph1 [Number] - Add/Remove health from investigator 1 \n" m_response += "!aph2 [Number] - Add/Remove health from investigator 2 \n" m_response += "!aph3 [Number] - Add/Remove health from investigator 3 \n" m_response += "!aph4 [Number] - Add/Remove health from investigator 4 \n" m_response += "!aps1 [Number] - Add/Remove sanity from investigator 1 \n" m_response += "!aps2 [Number] - Add/Remove sanity from investigator 2 \n" m_response += "!aps3 [Number] - Add/Remove sanity from investigator 3 \n" m_response += "!aps4 [Number] - Add/Remove sanity from investigator 4 \n" await ctx.send(m_response[:2000]) ## PLAYER 1 ## @commands.command(aliases=['addplayer1'], pass_context=True) async def apadd1(self, ctx): """Add player 1""" subexists = False # Auto-link some images instead of other users' names query_redirects = { } if not self.init_api: self.refresh_ah_api() self.Player1.clear() self.Player1.append("None") self.Player1.append(0) self.Player1.append(0) self.Player1.append("") m_query = ' '.join(ctx.message.content.split()[1:]).lower() img = 'imagesrc' if m_query.find("~") >= 0: m_query,m_subquery = m_query.split("~",1) subexists = True m_response = "" if m_query in query_redirects.keys(): m_response = query_redirects[m_query] elif not m_query: # post help text if no query m_response = "!apadd1 [Investigator name] - Add player 1 investigator \n" else: # Otherwise find and handle card names if not self.init_api: self.refresh_ah_api() else: # search player cards m_cards = [c for c in self.ah_api_p if c['name'].lower().__contains__(m_query)] if subexists: m_check = [c for c in m_cards if c['subname'].lower().__contains__(m_subquery)] if m_check: m_cards = m_check for c in m_cards: if m_query == c['name'].lower(): # if exact name match, post only the one card m_cards = [c] break if len(m_cards) == 1: try: self.Player1[0] = m_cards[0]['name'] self.Player1[1] = m_cards[0]['health'] self.Player1[2] = m_cards[0]['sanity'] self.Player1[3] = "http://arkhamdb.com" + m_cards[0][img] m_response += "Player 1 added with investigator: " m_response += self.Player1[0] + ", " m_response += "health: " + str(self.Player1[1]) + ", " m_response += "sanity: " + str(self.Player1[2]) + "." except KeyError as e: if e.args[0] == "imagesrc": # if no image on ArkhamDB m_response = "'{}' has no image on ArkhamDB:\n".format(m_cards[0]['name']) m_response += "https://arkhamdb.com/card/" + m_cards[0]["code"] elif len(m_cards) == 0: m_response += "Sorry, I cannot seem to find any card with these parameters:\n" m_response += "http://arkhamdb.com/find/?q=" + m_query.replace(" ", "+") await ctx.send(m_response[:2000]) @commands.command(aliases=['playerhealth1'], pass_context=True) async def aph1(self, ctx): """Modify player 1 health""" modifier = ' '.join(ctx.message.content.split()[1:]) self.Player1[1] += int(modifier) m_response = "Investigator " + self.Player1[0] + " has " + str(self.Player1[1]) + " health left." await ctx.send(m_response[:2000]) @commands.command(aliases=['playersanity1'], pass_context=True) async def aps1(self, ctx): """Modify player 1 sanity""" modifier = ' '.join(ctx.message.content.split()[1:]) self.Player1[2] += int(modifier) m_response = "Investigator " + self.Player1[0] + " has " + str(self.Player1[2]) + " sanity left." await ctx.send(m_response[:2000]) ## PLAYER 2 ## @commands.command(aliases=['addplayer2'], pass_context=True) async def apadd2(self, ctx): """Add player 2""" subexists = False # Auto-link some images instead of other users' names query_redirects = { } if not self.init_api: self.refresh_ah_api() self.Player2.clear() self.Player2.append("None") self.Player2.append(0) self.Player2.append(0) self.Player2.append("") m_query = ' '.join(ctx.message.content.split()[1:]).lower() img = 'imagesrc' if m_query.find("~") >= 0: m_query,m_subquery = m_query.split("~",1) subexists = True m_response = "" if m_query in query_redirects.keys(): m_response = query_redirects[m_query] elif not m_query: # post help text if no query m_response = "!apadd2 [Investigator name] - Add player 2 investigator \n" else: # Otherwise find and handle card names if not self.init_api: self.refresh_ah_api() else: # search player cards m_cards = [c for c in self.ah_api_p if c['name'].lower().__contains__(m_query)] if subexists: m_check = [c for c in m_cards if c['subname'].lower().__contains__(m_subquery)] if m_check: m_cards = m_check for c in m_cards: if m_query == c['name'].lower(): # if exact name match, post only the one card m_cards = [c] break if len(m_cards) == 1: try: self.Player2[0] = m_cards[0]['name'] self.Player2[1] = m_cards[0]['health'] self.Player2[2] = m_cards[0]['sanity'] self.Player2[3] = "http://arkhamdb.com" + m_cards[0][img] m_response += "Player 2 added with investigator: " m_response += self.Player2[0] + ", " m_response += "health: " + str(self.Player2[1]) + ", " m_response += "sanity: " + str(self.Player2[2]) + "." except KeyError as e: if e.args[0] == "imagesrc": # if no image on ArkhamDB m_response = "'{}' has no image on ArkhamDB:\n".format(m_cards[0]['name']) m_response += "https://arkhamdb.com/card/" + m_cards[0]["code"] elif len(m_cards) == 0: m_response += "Sorry, I cannot seem to find any card with these parameters:\n" m_response += "http://arkhamdb.com/find/?q=" + m_query.replace(" ", "+") await ctx.send(m_response[:2000]) @commands.command(aliases=['playerhealth2'], pass_context=True) async def aph2(self, ctx): """Modify player 2 health""" modifier = ' '.join(ctx.message.content.split()[1:]) self.Player2[1] += int(modifier) m_response = "Investigator " + self.Player2[0] + " has " + str(self.Player2[1]) + " health left." await ctx.send(m_response[:2000]) @commands.command(aliases=['playersanity2'], pass_context=True) async def aps2(self, ctx): """Modify player 2 sanity""" modifier = ' '.join(ctx.message.content.split()[1:]) self.Player2[2] += int(modifier) m_response = "Investigator " + self.Player2[0] + " has " + str(self.Player2[2]) + " sanity left." await ctx.send(m_response[:2000]) ## PLAYER 3 ## @commands.command(aliases=['addplayer3'], pass_context=True) async def apadd3(self, ctx): """Add player 3""" subexists = False # Auto-link some images instead of other users' names query_redirects = { } if not self.init_api: self.refresh_ah_api() self.Player3.clear() self.Player3.append("None") self.Player3.append(0) self.Player3.append(0) self.Player3.append("") m_query = ' '.join(ctx.message.content.split()[1:]).lower() img = 'imagesrc' if m_query.find("~") >= 0: m_query,m_subquery = m_query.split("~",1) subexists = True m_response = "" if m_query in query_redirects.keys(): m_response = query_redirects[m_query] elif not m_query: # post help text if no query m_response = "!apadd3 [Investigator name] - Add player 3 investigator \n" else: # Otherwise find and handle card names if not self.init_api: self.refresh_ah_api() else: # search player cards m_cards = [c for c in self.ah_api_p if c['name'].lower().__contains__(m_query)] if subexists: m_check = [c for c in m_cards if c['subname'].lower().__contains__(m_subquery)] if m_check: m_cards = m_check for c in m_cards: if m_query == c['name'].lower(): # if exact name match, post only the one card m_cards = [c] break if len(m_cards) == 1: try: self.Player3[0] = m_cards[0]['name'] self.Player3[1] = m_cards[0]['health'] self.Player3[2] = m_cards[0]['sanity'] self.Player3[3] = "http://arkhamdb.com" + m_cards[0][img] m_response += "Player 3 added with investigator: " m_response += self.Player3[0] + ", " m_response += "health: " + str(self.Player3[1]) + ", " m_response += "sanity: " + str(self.Player3[2]) + "." except KeyError as e: if e.args[0] == "imagesrc": # if no image on ArkhamDB m_response = "'{}' has no image on ArkhamDB:\n".format(m_cards[0]['name']) m_response += "https://arkhamdb.com/card/" + m_cards[0]["code"] elif len(m_cards) == 0: m_response += "Sorry, I cannot seem to find any card with these parameters:\n" m_response += "http://arkhamdb.com/find/?q=" + m_query.replace(" ", "+") await ctx.send(m_response[:2000]) @commands.command(aliases=['playerhealth3'], pass_context=True) async def aph3(self, ctx): """Modify player 3 health""" modifier = ' '.join(ctx.message.content.split()[1:]) self.Player3[1] += int(modifier) m_response = "Investigator " + self.Player3[0] + " has " + str(self.Player3[1]) + " health left." await ctx.send(m_response[:2000]) @commands.command(aliases=['playersanity3'], pass_context=True) async def aps3(self, ctx): """Modify player 3 sanity""" modifier = ' '.join(ctx.message.content.split()[1:]) self.Player3[2] += int(modifier) m_response = "Investigator " + self.Player3[0] + " has " + str(self.Player3[2]) + " sanity left." await ctx.send(m_response[:2000]) ## PLAYER 4 ## @commands.command(aliases=['addplayer4'], pass_context=True) async def apadd4(self, ctx): """Add player 4""" subexists = False # Auto-link some images instead of other users' names query_redirects = { } if not self.init_api: self.refresh_ah_api() self.Player4.clear() self.Player4.append("None") self.Player4.append(0) self.Player4.append(0) self.Player4.append("") m_query = ' '.join(ctx.message.content.split()[1:]).lower() img = 'imagesrc' if m_query.find("~") >= 0: m_query,m_subquery = m_query.split("~",1) subexists = True m_response = "" if m_query in query_redirects.keys(): m_response = query_redirects[m_query] elif not m_query: # post help text if no query m_response = "!apadd4 [Investigator name] - Add player 1 investigator \n" else: # Otherwise find and handle card names if not self.init_api: self.refresh_ah_api() else: # search player cards m_cards = [c for c in self.ah_api_p if c['name'].lower().__contains__(m_query)] if subexists: m_check = [c for c in m_cards if c['subname'].lower().__contains__(m_subquery)] if m_check: m_cards = m_check for c in m_cards: if m_query == c['name'].lower(): # if exact name match, post only the one card m_cards = [c] break if len(m_cards) == 1: try: self.Player4[0] = m_cards[0]['name'] self.Player4[1] = m_cards[0]['health'] self.Player4[2] = m_cards[0]['sanity'] self.Player4[3] = "http://arkhamdb.com" + m_cards[0][img] m_response += "Player 4 added with investigator: " m_response += self.Player4[0] + ", " m_response += "health: " + str(self.Player4[1]) + ", " m_response += "sanity: " + str(self.Player4[2]) + "." except KeyError as e: if e.args[0] == "imagesrc": # if no image on ArkhamDB m_response = "'{}' has no image on ArkhamDB:\n".format(m_cards[0]['name']) m_response += "https://arkhamdb.com/card/" + m_cards[0]["code"] elif len(m_cards) == 0: m_response += "Sorry, I cannot seem to find any card with these parameters:\n" m_response += "http://arkhamdb.com/find/?q=" + m_query.replace(" ", "+") await ctx.send(m_response[:2000]) @commands.command(aliases=['playerhealth4'], pass_context=True) async def aph4(self, ctx): """Modify player 4 health""" modifier = ' '.join(ctx.message.content.split()[1:]) self.Player4[1] += int(modifier) m_response = "Investigator " + self.Player4[0] + " has " + str(self.Player4[1]) + " health left." await ctx.send(m_response[:2000]) @commands.command(aliases=['playersanity4'], pass_context=True) async def aps1(self, ctx): """Modify player 4 sanity""" modifier = ' '.join(ctx.message.content.split()[1:]) self.Player4[2] += int(modifier) m_response = "Investigator " + self.Player4[0] + " has " + str(self.Player4[2]) + " sanity left." await ctx.send(m_response[:2000]) def setup(bot): bot.add_cog(ArkhamPlayer(bot))
true
d65f9d0e0acf04c4c94a890d6bb9d7017c2f2bf5
Python
Vluuks/AdventOfCode19
/day2.py
UTF-8
2,307
3.75
4
[]
no_license
from copy import deepcopy def parse_intlist(ints): i = 0 # iter over in steps of 4 while True: opcode = ints[i] if opcode == 99: print("termination 99") break print('opcode ' + str(opcode)) val1 = ints[ints[i+1]] val2 = ints[ints[i+2]] print(val1, val2) print("index" + str(ints[i+3])) if opcode == 1: ints[ints[i+3]] = val1 + val2 elif opcode == 2: ints[ints[i+3]] = val1 * val2 else: print("you fucked up") break i += 4 print(ints[i]) print(i) print(ints) def parse_intlist_reverse_engineering(ints): ints_initial = deepcopy(ints) # keep going until the output is the desired value for a in range(0, 100): for b in range(0, 100): print("combo {} {}".format(a, b)) ints[1] = a ints[2] = b print(ints) # PARSE THE LIST i = 0 while True: # get instruction opcode = ints[i] print('opcode ' + str(opcode)) if opcode == 99: print("termination 99") break # get the values to parse val1 = ints[ints[i+1]] val2 = ints[ints[i+2]] print(val1, val2) print("index" + str(ints[i+3])) if opcode == 1: ints[ints[i+3]] = val1 + val2 elif opcode == 2: ints[ints[i+3]] = val1 * val2 # opcode is not 1, 2 or 99 else: print("can never reach end of program") break i += 4 # every time we parsed a list, check if it mees requirement if(ints[0] == 19690720): return (a, b) else: ints = deepcopy(ints_initial) print("SHOULD BE RESET") print(ints) ints = [1,12,2,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,6,19,23,1,23,13,27,2,6,27,31,1,5,31,35,2,10,35,39,1,6,39,43,1,13,43,47,2,47,6,51,1,51,5,55,1,55,6,59,2,59,10,63,1,63,6,67,2,67,10,71,1,71,9,75,2,75,10,79,1,79,5,83,2,10,83,87,1,87,6,91,2,9,91,95,1,95,5,99,1,5,99,103,1,103,10,107,1,9,107,111,1,6,111,115,1,115,5,119,1,10,119,123,2,6,123,127,2,127,6,131,1,131,2,135,1,10,135,0,99,2,0,14,0 ] arr_size = len(ints) print(arr_size) # parse_intlist(ints) success = parse_intlist_reverse_engineering(ints) print("WE ARE DONE FINALLY") print(success)
true
2dd1dcfd5f616f702edc430220567553906d92f6
Python
yzw0917/mypython3
/bs4_理解/lianxi01.py
UTF-8
735
3.046875
3
[]
no_license
import requests from bs4 import BeautifulSoup # 配置请求头 headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36', } # 网站诗词内容下载 url='http://www.shicimingju.com/book/hongloumeng/54.html' #获取标题正文页数据 gethtml = requests.get(url,headers=headers).text soup = BeautifulSoup(gethtml,'html.parser') #解析获得标签 ele = soup.find('div',class_='book-page-nav') #按照参数div取div段,名称是class_指定的 # ele = soup.find('div',class_='chapter_content') # ele = soup.find('div',class_='chapter_content') # print(ele) content = ele.text #获取标签中的数据值 print(content)
true
a39e476077d37813e2ce0bceb8e50447982c1d0e
Python
prabhupanda/LeapFinance-Internship-Tasks
/collegedunia_script.py
UTF-8
4,864
2.6875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Mar 12 12:56:01 2021 @author: prabh Script to Scape collegedunia.com US college-wise data """ import numpy as np import pandas as pd import time from selenium import webdriver from selenium.webdriver.common.keys import Keys #get list of all college names df=pd.read_csv('Colleges_link_final.csv') college_list=df['Colleges'].unique().tolist() #initiate chromedriver browser=webdriver.Chrome('chromedriver.exe') browser.maximize_window() #Instantiating the Dataframe column_name=['College','Course_name','fees_1st_year','duration','course_type'] database=pd.DataFrame(columns=column_name) #lists to store colleges with no_masters no_masters=[] for i in range(len(college_list)): #go to collegedunia.com/USA site c_link=df['Link'][i] browser.get(c_link) #search=browser.find_element_by_id('home-search') #search.clear() #time.sleep(5) #search.send_keys(c) #time.sleep(5) try: #searches=browser.find_element_by_xpath('//div[@class="results_lists"]/ul/li[1]/a') #browser.get(searches.get_attribute('href')) if i==0: #WAIT TIME == 30s added to close the POPUP time.sleep(5) browser.find_element_by_xpath('//button[@class="jsx-1878022974 close bg-white"]').click() time.sleep(35) browser.find_element_by_xpath('//div[@class="jsx-601813733 lead-close-icon pointer"]').click() else: pass prog=browser.find_element_by_xpath('//div[@class="jsx-2373615511 jsx-45449386 position-relative d-flex mx-8 silo-navbar-parent undefined"]/ul/li[2]/a') browser.get(prog.get_attribute('href')) time.sleep(15) try: browser.find_element_by_xpath('//label[@for="Levels-Master"]').click() #sort by fees highest to lowest browser.find_element_by_xpath('//div/span[@class="jsx-3840022005 pointer position-relative sort-link font-weight-bold "][1]').click() #courses_names courses=browser.find_elements_by_xpath('//h3/a[@class="jsx-2254962254 jsx-2349121475"]') course_list=[] for p in courses: course_list.append(p.text) #fees fee_list=[] fee=browser.find_elements_by_xpath('//div/span[@class="jsx-2254962254 jsx-2349121475 fees font-weight-bolder"]') for q in fee: fee_list.append(q.text) #filling blank-data w/ NaN diff=len(course_list)-len(fee_list) for b in range(diff): fee_list.append(np.nan) #duration course_duration=[] dur=browser.find_elements_by_xpath('//div[@class="jsx-2254962254 jsx-2349121475 d-flex justify-content-between align-items-center"]/div[1]/div/p[@class="jsx-2254962254 jsx-2349121475 item-head m-0 pb-1 text-primary text-lg text-uppercase"]') for r in dur: course_duration.append(r.text) #filling blank-data w/ NaN diff_duration=len(course_list)-len(course_duration) for c in range(diff_duration): course_duration.append(np.nan) #course_type course_type=[] c_type=browser.find_elements_by_xpath('//div/span[@class="jsx-2254962254 jsx-2349121475 card-subheading text-md text-uppercase"]') for s in c_type: course_type.append(s.text) #filling blank-data w/ NaN diff_type=len(course_list)-len(course_type) for d in range(diff_type): course_type.append(np.nan) #college_name list(repaeated values of 1 college name) college_name=browser.title college=[] college.extend([college_name for t in range(len(course_list))]) #instantiating a iterative df iter_df=pd.DataFrame({'College':college, 'Course_name':course_list, 'fees_1st_year':fee_list, 'duration':course_duration, 'course_type':course_type}) #adding values to the database dataframe database=database.append(iter_df,ignore_index=True) except: print('{} does not have Masters'.format(college_list[i])) no_masters.append(college_list[i]) except: continue #exporting dataframe into .csv database.to_csv('Main.csv',index=False) no_masters
true
8129a644b468e92088c0997202840979dc2ee42a
Python
AnesuChinoda/rosebotics2
/src/capstone_2_runs_on_robot.py
UTF-8
1,326
3.265625
3
[]
no_license
""" Mini-application: Buttons on a Tkinter GUI tell the robot to: - Go forward at the speed given in an entry box. Also: responds to Beacon button-presses by beeping, speaking. This module runs on the ROBOT. It uses MQTT to RECEIVE information from a program running on the LAPTOP. Authors: David Mutchler, his colleagues, and Alec Polster. """ import rosebotics_new as rb import time import mqtt_remote_method_calls as com import ev3dev.ev3 as ev3 def main(): robot = rb.Snatch3rRobot() rc = RemoteControlEtc(robot) mqtt_client = com.MqttClient(rc) mqtt_client.connect_to_pc() while True: if robot.beacon_button_sensor.is_top_red_button_pressed() is True: ev3.Sound.beep().wait() if robot.beacon_button_sensor.is_top_blue_button_pressed() is True: ev3.Sound.speak('I love you bitch, I aint never gonna stop loving you, bitch').wait() time.sleep(0.01) # For the delegate to do its work class RemoteControlEtc(object): def __init__(self, robot): """ Stores a robot. :type robot: rb.Snatch3rRobot """ self.robot = robot def go_forward(self, speed_string): speed = int(speed_string) print('Robot should start moving') self.robot.drive_system.start_moving(speed, speed) main()
true
935788c507724d8e14f6bf2e24b70cff741f8ffe
Python
GustavHenning/DeepLearning18
/lab4/inits.py
UTF-8
397
2.84375
3
[ "MIT" ]
permissive
import sys import numpy as np class Initializer: def from_shape(self, shape): print("Initializer is an interface.") sys.exit(1) pass class Zeros(Initializer): def from_shape(self, shape): return np.zeros(shape, dtype=float) class Xavier(Initializer): def from_shape(self, shape): return np.random.normal(0, np.sqrt(2 / (sum(shape))), shape)
true
b8a9a5243fb19d0e1dc51a918a1e828733ec36b8
Python
rgliuca/OpenCV
/opencv_hello_world.py
UTF-8
411
2.75
3
[]
no_license
import cv2 image = cv2.imread("images\\trex.png") print("width: %d pixels" % image.shape[1]) print("height: %d pixels" % image.shape[0]) print("channels: %d" % image.shape[2]) cv2.imshow("Trex Image", image) for r in range(image.shape[0]): image[r,150]=(0,0,0) cv2.imshow("Trex with line image", image) cv2.waitKey(0) out_file_name = "trex_with_line.png" cv2.imwrite(out_file_name, image)
true
327a8e70819e2acfa73b2a715c7540de3eecc70d
Python
flareno/ExtraPy
/Scalogram.py
UTF-8
5,118
2.625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Oct 22 10:04:18 2019 @author: Sam Garcia (adapted by Federica Lareno Faccini) """ import numpy as np import scipy.signal from scipy import fftpack def generate_wavelet_fourier(len_wavelet, f_start, f_stop, delta_freq, sampling_rate, f0, normalisation): """ Compute the wavelet coefficients at all scales and makes its Fourier transform. When different signal scalograms are computed with the exact same coefficients, this function can be executed only once and its result passed directly to compute_morlet_scalogram Output: wf : Fourier transform of the wavelet coefficients (after weighting), Fourier frequencies are the first """ # compute final map scales scales = f0/np.arange(f_start,f_stop,delta_freq)*sampling_rate # compute wavelet coeffs at all scales xi=np.arange(-len_wavelet/2.,len_wavelet/2.) xsd = xi[:,np.newaxis] / scales wavelet_coefs=np.exp(complex(1j)*2.*np.pi*f0*xsd)*np.exp(-np.power(xsd,2)/2.) weighting_function = lambda x: x**(-(1.0+normalisation)) wavelet_coefs = wavelet_coefs*weighting_function(scales[np.newaxis,:]) # Transform the wavelet into the Fourier domain #~ wf=fft(wavelet_coefs.conj(),axis=0) <- FALSE wf=fftpack.fft(wavelet_coefs,axis=0) wf=wf.conj() # at this point there was a mistake in the original script return wf def convolve_scalogram(sig, wf): """ Convolve with fft the signal (in time domain) with the wavelet already computed in freq domain. Parameters ---------- sig: numpy.ndarray (1D, float) The signal wf: numpy.array (2D, complex) The wavelet coefficient in fourrier domain. """ n = wf.shape[0] assert sig.shape[0]<=n, 'the sig.size is longer than wf.shape[0] {} {}'.format(sig.shape[0], wf.shape[0]) sigf=fftpack.fft(sig,n) wt_tmp=fftpack.ifft(sigf[:,np.newaxis]*wf,axis=0) wt = fftpack.fftshift(wt_tmp,axes=[0]) return wt def compute_timefreq(sig, sampling_rate, f_start, f_stop, delta_freq=1., nb_freq=None, f0=2.5, normalisation = 0., min_sampling_rate=None, wf=None, t_start=0., zero_pad=True, joblib_memory=None): """ """ #~ print 'compute_timefreq' sampling_rate = float(sampling_rate) if nb_freq is not None: delta_freq = (f_stop-f_start)/nb_freq if min_sampling_rate is None: min_sampling_rate = min(4.* f_stop, sampling_rate) #decimate ratio = int(sampling_rate/min_sampling_rate) #~ print 'ratio', ratio if ratio>1: # sig2 = tools.decimate(sig, ratio) sig2 = scipy.signal.decimate(sig, ratio, n=4, zero_phase=True) else: sig2 = sig ratio=1 tfr_sampling_rate = sampling_rate/ratio #~ print 'tfr_sampling_rate', tfr_sampling_rate n_init = sig2.size if zero_pad: n = int(2 ** np.ceil(np.log(n_init)/np.log(2))) # extension to next power of 2 else: n = n_init #~ print 'n_init', n_init, 'n', n if wf is None: if joblib_memory is None: func = generate_wavelet_fourier else: func = joblib_memory.cache(generate_wavelet_fourier) wf = func(n, f_start, f_stop, delta_freq, tfr_sampling_rate, f0, normalisation) assert wf.shape[0] == n wt = convolve_scalogram(sig2, wf) wt=wt[:n_init,:] freqs = np.arange(f_start,f_stop,delta_freq) times = np.arange(n_init)/tfr_sampling_rate + t_start return wt, times, freqs, tfr_sampling_rate def ridge_map(ampl_map, threshold=70.): max_power = np.max(ampl_map) #Max power observed in frequency spectrum freq_power_threshold = float(threshold) #The threshold range for power detection of the ridge cut_off_power = max_power/100.0*freq_power_threshold #Computes power above trheshold boolean_map = ampl_map >= cut_off_power #For plot value_map = ampl_map for i,j in np.ndenumerate(ampl_map): if j <= cut_off_power: value_map[i] = 0.0 #For computation, all freq < trhesh = 0.0 return boolean_map, value_map def ridge_line(ampl_map, tfr_sampling_rate, delta_freq=0.1, t0=0, t1=None, f0=4, f1=12, rescale=False): freq0 = int(f0/delta_freq) freq1 = int(f1/delta_freq) if t1 is None and t0 is None: theta = ampl_map[:,freq0:freq1] else: time0 = int(tfr_sampling_rate*t0) time1 = int(tfr_sampling_rate*t1) theta = ampl_map[time0:time1,freq0:freq1] ridge = np.empty(len(theta)) ridge[:] = np.nan y = np.empty(len(ridge)) y[:] = np.nan for i in range(theta.shape[0]): ridge[i] = np.max(theta[i,:]) y[i] = (np.where(theta[i,:] == ridge[i]))[0] if rescale: y[:] = y*delta_freq+f0 x = np.arange(0,len(theta),1) return ridge,theta,x,y
true
782a51ea78bf90a34ea65197f0e740ae05ee650c
Python
memuunkie/HBProject_research_library_app
/seed.py
UTF-8
2,265
2.8125
3
[]
no_license
from sqlalchemy import func from model import Book, User, TypeUser from model import connect_to_db, db from server import app from datetime import datetime from csv import reader from datetime import datetime import json def load_books(): """Create library of books""" Book.query.delete() seed_data = reader(open('seed_data/test_data.csv')) for call_num, author, title, edition, pub_info in seed_data: book = Book(call_num=call_num, author=author, title=title, edition=edition, pub_info=pub_info) db.session.add(book) db.session.commit() # total = int(db.session.query(Book.book_id).count()) def load_usertypes(): """Create table of user types""" TypeUser.query.delete() for row in open('seed_data/type_users'): row = row.rstrip() type_name, description = row.split('|') new_type = TypeUser(type_name=type_name, description=description) db.session.add(new_type) db.session.commit() def load_users(): """Create users in database""" User.query.delete() seed_data = json.loads(open('seed_data/MOCK_DATA.json').read()) for row in seed_data: user = User(fname=row['fullname']['fname'], lname=row['fullname']['lname'], email=row['login']['email'], password=row['login']['password'], create_date=datetime.now() ) db.session.add(user) # create one default admin admin = User(fname='The', lname='Librarian', email='bookkeeperchs@gmail.com', password='1234abc', create_date=datetime.now(), type_id=1) db.session.add(admin) db.session.commit() ############################################################################## # Help functions # def count_rows(model_id): # """Prints to console a message that records added successfully""" # total = int(db.session.query(model_id).count()) if __name__ == "__main__": connect_to_db(app) # In case tables haven't been created, create them db.create_all() # Import different types of data load_books() load_usertypes() load_users()
true
1b43b7b31506323bbda99e3dd17f4de628e39305
Python
ishwarjindal/Think-Python
/FuncAsArg.py
UTF-8
245
2.765625
3
[]
no_license
# script to test passing function as argument def print_spam(arg1): print(arg1) def do_twice(f, arg1): f(arg1) f(arg1) def do_four(f, arg1): do_twice(f, arg1) do_twice(f, arg1) do_four(print_spam,"Py for Python")
true
0232d45c10ac50d974432e0ed64b50d53ea8ca79
Python
santhosh-duraipandiyan/corona-hotel
/view.py
UTF-8
496
3.15625
3
[]
no_license
import json from pprint import pprint def viewData(): data = json.load(open('data.json')) print("##########################################") for item in data: if data[item]["name"] == "dummy": return print("\nName: ",data[item]["name"]) print("Email: ",data[item]["email"]) print("Address: ",data[item]["address"]) print("Phone-number: ",data[item]["phone-number"]) print("Date: ",data[item]["date"],"\n") print("##########################################")
true
e16cda56f96e2edca51b53f27a073747622ee628
Python
alexamar0714/Proglab-6
/bbcon2.py
UTF-8
3,565
2.5625
3
[]
no_license
import time class BBCON(): behaviours = [] active_behaviours = [] sensobs = [] motobs = [] arbitrator = None def __init__(self): pass def set_arb(self,arb): self.arbitrator = arb def add_behaviour(self, behaviour): self.behaviours.append(behaviour) def add_sensob(self, sensob): self.sensobs.append(sensob) def add_motobs(self, motob): self.motobs.append(motob) def get_behaviours(self): return self.behaviours def active_behaviour(self, behaviour): if behaviour not in self.active_behaviours: self.active_behaviours.append(behaviour) def deactivate_behaviour(self, behaviour): if behaviour in self.active_behaviours: self.active_behaviours.remove(behaviour) def run_one_timestep(self): self.update_all_sensobs() self.update_all_behaviours() motor_recc, halt_req = self.arbitrator.choose_action(stochastic = False) self.update_motobs(motor_recc, halt_req) print(self.active_behaviours) self.reset_all_sensobs() def update_all_sensobs(self): for sensors in self.sensobs: sensors.update() def update_all_behaviours(self): for behaviour in self.behaviours: behaviour.update() def reset_all_sensobs(self): for sensors in self.sensobs: sensors.reset() def update_motobs(self, motor_recc, halt_req): for tuples in motor_recc: if halt_req: for motobs in self.motobs: print("STOPPING") motobs.stop() elif tuples[0] == "f": print('f-drive:', motor_recc) for motobs in self.motobs: motobs.forward(speed = tuples[1], dur = tuples[2]) elif tuples[0] == "b": print('b-drive:', motor_recc) for motobs in self.motobs: motobs.backward(speed = tuples[1], dur = tuples[2]) old_l_speed = -tuples[1]; old_r_speed = -tuples[1] elif tuples[0] == "r": print('r-drive:', motor_recc) for motobs in self.motobs: motobs.right(speed = tuples[1], dur = tuples[2]) old_l_speed = 0; old_r_speed = tuples[1] elif tuples[0] == "l": print('l-drive:', motor_recc) for motobs in self.motobs: motobs.left(speed = tuples[1], dur = tuples[2]) old_l_speed = tuples[1]; old_r_speed = 0 elif tuples[0] == "inc_r": print('inc_r:', motor_recc) for motobs in self.motobs: motobs.right(speed = old_r_speed + tuples[1], dur = old_dur) motobs.left(speed = old_l_speed, dur = old_dur) old_r_speed = old_r_speed + tuples[1] old_l_speed = old_l_speed elif tuples[0] == "inc_l": print('inc_l:', motor_recc) for motobs in self.motobs: motobs.right(speed = old_r_speed, dur = old_dur) motobs.left(speed = old_l_speed + tuples[1], dur = old_dur) old_r_speed = old_r_speed old_l_speed = old_l_speed + tuples[1] print("sleepend") time.sleep(tuples[2])
true
5302e76b90629c30d3ec355d8f91aba9d32d13ec
Python
jleakakos-cyrus/euler
/python/problem15.py
UTF-8
369
4.125
4
[]
no_license
# Problem 15 # How many routes are there through a 20x20 grid? def factorial(number): mult = 1 for x in range(1, number + 1): mult *= x return mult def binomialCoefficient(m, n): return factorial(m)/(factorial(n) * factorial(m - n)) def problem15(x, y): return binomialCoefficient(x + y, y) if __name__ == '__main__': print problem15(20, 20)
true
2c075a7369d8d30392abcbf09c3ca4022a4c20c1
Python
joeryan/100pythondays2019
/004/program.py
UTF-8
1,332
4.125
4
[ "MIT" ]
permissive
import characters import random def print_header(): print("---------------------") print(" Wizard game") print("---------------------\n") def game_loop(): creatures = [ characters.Creature('bat', 1, 2), characters.Creature('tiger', 4, 6), characters.Creature('beholder', 12, 8), characters.Creature('dragon', 50, 12), characters.Creature('Evil wizard', 1000, 4), ] hero = characters.Wizard('Magilus', 20, 4, ["dagger","Fireball", "Magic Missle"]) exit_game = False while not exit_game: if random.randint(1,50) >= 5: active_creature = random.choice(creatures) print("You see a {} glaring at you".format(active_creature)) else: print("Nothing much is around you right now") choice = input("Do you want to [a]ttack, [l]ook around, [r]un away, or [q]uit the game? ").lower() if choice == 'q': exit_game = True elif choice == 'a': hero.attack_creature() elif choice == 'l': print("taking a look around...") for creature in creatures: print("In the distance you see:") print(creature) elif choice == 'r': hero.run_away() else: print("You really only have those four choices.") print("Thanks for playing!") def main(): print_header() game_loop() if __name__ == '__main__': main()
true
26624611c183882e819f2aa972a7ab49d852638f
Python
NUSTARS/2020-Data-Comm
/React-App/api/parsePacket.py
UTF-8
2,739
2.90625
3
[]
no_license
from struct import unpack, Struct from struct import error as structerror # import struct from binascii import crc32 import time import datetime # import sys """ PACKET FORMAT Byte # 1: Protocol version 2: Flags 3-4: Payload size 5-6: Sequence number 7-10: CRC-32 checksum 11-?: Variable length secion of repeating: --- 2 bytes: Unique ID --- 1 byte: Reserved --- 1 byte: Data type --- ? bytes: Data of length dtype size """ # end = '>' if sys.byteorder=='big' else '<'; # source venv/bin/activate # dict containing TYPE-ID : [TYPE-SIZE, FORMAT-STRING] pairs types = { 0: [1, '>B'], # uint8 1: [2, '>H'], # uint16 2: [4, '>I'], # uint32 3: [8, '>Q'], # uint64 4: [1, '>b'], # int8 5: [2, '>h'], # int16 6: [4, '>i'], # int32 7: [8, '>q'], # int64 8: [4, '>f'], # float32 9: [8, '>d'] # float 64 } # struct class containing format string for unpacking header = Struct('>BBHHI') def unpackHeader(hba): ''' Unpacks the header bytes of the packet. - Input: header bytes (10) - Output: (version, flags, payload-size, sequence-num, checksum) ''' return header.unpack(hba) def unpackPayload(pba, pSize): ''' Unpacks the payload bytes of the packet. - Input: payload bytes, payload size - Output: {uid1: data1, uid2: data2, ...} ''' d = {} i = 0 while (i < pSize): uid = unpack('>H', pba[i:i+2])[0] reserved = unpack('>H', pba[i+2:i+3]) if reserved != 0: return 0 dtype = unpack('>B', pba[i+3:i+4])[0] data = unpack(types[dtype][1], pba[i+4:i+4+dtype])[0] d[uid] = data i += 4+types[dtype][0] return d if i==pSize else 0 # 0 if packet malformed def read_packet(ba): ''' Parses packets read from serial port. - Input: None - Output: Packet object if parse successful, 0 otherwise ''' try: h = unpackHeader(ba[:10]) if h[4] != crc32(ba[10:]): return 0 # checksum failure d = unpackPayload(ba[10:], h[2]) if not d: return 0 # payload unpacking failure obj = { 'version': h[0], 'flags': h[1], 'payloadSize': h[2], 'seqNum': h[3], 'checksum': h[4], 'time': datetime.datetime.now().strftime("%H:%M:%S"), 'data': d } except IndexError as error: print(f'Error: {error}') return 0 except structerror as error: print(f'Error: {error}') return 0 except: return 0 else: return obj
true
ee2b2276c2d16558963277217aae3815b4c02f0c
Python
Hugo-Oh/study_DataStructure
/인프런/섹션 4/10. 역수열/AA2.py
UTF-8
294
2.96875
3
[]
no_license
import sys sys.stdin = open("input.txt", "rt") N = int(input()) arr =list(map(int, input().split())) tot = 0 for i in sorted(arr)[::-1]: cnt = 0 for j in arr: if j > i: cnt += 1 elif j == i: print(cnt, end = " ") break print(cnt)
true
467f1d4ab50bcaa749573268603c50c16a31c6b2
Python
johnmnemonik/aiorest-ws
/aiorest_ws/test/utils.py
UTF-8
4,260
2.84375
3
[ "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- """ Django-like settings functions and classes, which help to modify basic configuration on the fly, while tests performed. """ from functools import wraps from unittest import TestCase from aiorest_ws.conf import settings, UserSettingsHolder __all__ = ('override_settings', ) class BaseContextDecorator(object): """ A base class that can either be used as a context manager during tests or as a test function or unittest.TestCase subclass decorator to perform temporary alterations. `attr_name`: attribute assigned the return value of enable() if used as a class decorator. `kwarg_name`: keyword argument passing the return value of enable() if used as a function decorator. """ def __init__(self, attr_name=None, kwarg_name=None): self.attr_name = attr_name self.kwarg_name = kwarg_name def enable(self): raise NotImplementedError def disable(self): raise NotImplementedError def __enter__(self): return self.enable() def __exit__(self, exc_type, exc_value, traceback): self.disable() def decorate_class(self, cls): if issubclass(cls, TestCase): decorated_setUp = cls.setUp decorated_tearDown = cls.tearDown def setUp(inner_self): context = self.enable() if self.attr_name: setattr(inner_self, self.attr_name, context) decorated_setUp(inner_self) def tearDown(inner_self): decorated_tearDown(inner_self) self.disable() cls.setUp = setUp cls.tearDown = tearDown return cls raise TypeError('Can only decorate subclasses of unittest.TestCase') def decorate_callable(self, func): @wraps(func) def inner(*args, **kwargs): with self as context: if self.kwarg_name: kwargs[self.kwarg_name] = context return func(*args, **kwargs) return inner def __call__(self, decorated): if isinstance(decorated, type): return self.decorate_class(decorated) elif callable(decorated): return self.decorate_callable(decorated) raise TypeError('Cannot decorate object of type %s' % type(decorated)) class override_settings(BaseContextDecorator): """ Acts as either a decorator or a context manager. If it's a decorator it takes a function and returns a wrapped function. If it's a contextmanager it's used with the ``with`` statement. In either event entering/exiting are called before and after, respectively, the function/block is executed. """ def __init__(self, **kwargs): self.options = kwargs super(override_settings, self).__init__() def enable(self): old_keys = set(key for key in settings.__dir__() if key.isupper()) new_keys = set(self.options.keys()) self._new_setting_keys = list(new_keys.difference(old_keys)) override = UserSettingsHolder(settings._wrapped) for key, new_value in self.options.items(): setattr(override, key, new_value) self.wrapped = settings._wrapped settings._wrapped = override for key, new_value in self.options.items(): setattr(settings, key, new_value) def disable(self): settings._wrapped = self.wrapped del self.wrapped # Rollback old values for key in self.options: new_value = getattr(settings, key, None) setattr(settings, key, new_value) # Other keys just remove from the settings for key in self._new_setting_keys: delattr(settings, key) def save_options(self, test_func): if test_func._overridden_settings is None: test_func._overridden_settings = self.options else: # Duplicate dict to prevent subclasses from altering their parent test_func._overridden_settings = dict( test_func._overridden_settings, **self.options ) def decorate_class(self, cls): self.save_options(cls) return cls
true
b72d46fce5466f7fe4f2355f85ccd6b04bc2e603
Python
Aasthaengg/IBMdataset
/Python_codes/p02831/s339451730.py
UTF-8
827
2.796875
3
[]
no_license
import sys from functools import reduce import copy import math from pprint import pprint import collections import bisect import itertools import heapq sys.setrecursionlimit(4100000) def inputs(num_of_input): ins = [input() for i in range(num_of_input)] return ins def int_inputs(num_of_input): ins = [int(input()) for i in range(num_of_input)] return ins def solve(input): nums = string_to_int(input) def euclid(large, small): if small == 0: return large l = large % small return euclid(small, l) nums.sort(reverse=True) eee = euclid(nums[0], nums[1]) return int((nums[0] * nums[1]) / eee) def string_to_int(string): return list(map(lambda x: int(x), string.split())) if __name__ == "__main__": ret = solve(input()) print(ret)
true
46aa8d6935b9d5bb703827123d07a201e11d535b
Python
scout719/adventOfCode
/2022/adventOfCode_10.py
UTF-8
2,901
2.671875
3
[]
no_license
# -*- coding: utf-8 -*- # pylint: disable=import-error # pylint: disable=unused-import # pylint: disable=wildcard-import # pylint: disable=unused-wildcard-import # pylint: disable=wrong-import-position # pylint: disable=consider-using-enumerate import functools import math import os from os.path import join import sys import time from copy import deepcopy from collections import defaultdict from heapq import heappop, heappush FILE_DIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, FILE_DIR + "/") sys.path.insert(0, FILE_DIR + "/../") from common.utils import main, day_with_validation, WHITE_SQUARE # NOQA: E402 # pylint: enable=import-error # pylint: enable=wrong-import-position YEAR = 2022 DAY = 10 EXPECTED_1 = 13140 EXPECTED_2 = "" """ DAY 9 """ def day10_parse(data): inst = [] for line in data: op = line.split() inst.append(op) return inst def day10_cycle(x, val, p1, p2): if len(p1) > 0: x += p1.pop() p1 = p2 p2 = [val] return x, p1, p2 def day10_draw(cycle, x, display): if not display: return sprite = [x in [c - 1, c, c + 1] for c in range(40)] r = (cycle - 1) // 40 c = (cycle - 1) % 40 if sprite[c]: display[r][c] = WHITE_SQUARE def day10_print(display): for r in range(len(display)): line = "" for c in range(len(display[r])): line += display[r][c] print(line) print() def day10_1(data): insts = day10_parse(data) x = 1 cycle = 0 p_1 = [] p_2 = [] total = 0 for op in insts: if (cycle - 20) % 40 == 0: total += cycle * x if len(op) > 1: _, val = op val = int(val) x, p_1, p_2 = day10_cycle(x, val, p_1, p_2) cycle += 1 if (cycle - 20) % 40 == 0: total += cycle * x x, p_1, p_2 = day10_cycle(x, 0, p_1, p_2) cycle += 1 # 7040 return total def day10_2(data): insts = day10_parse(data) x = 1 cycle = 0 p_1 = [] p_2 = [] display = [[" " for _ in range(40)] for _ in range(6)] for op in insts: day10_draw(cycle, x, display) if len(op) > 1: _, val = op val = int(val) x, p_1, p_2 = day10_cycle(x, val, p_1, p_2) cycle += 1 day10_draw(cycle, x, display) x, p_1, p_2 = day10_cycle(x, 0, p_1, p_2) cycle += 1 day10_print(display) return "" """ MAIN FUNCTION """ if __name__ == "__main__": main(sys.argv, { f"day{DAY}_1": lambda data: day_with_validation(globals(), YEAR, DAY, EXPECTED_1, 1, data), f"day{DAY}_2": lambda data: day_with_validation(globals(), YEAR, DAY, EXPECTED_2, 2, data), }, YEAR)
true
e9e0f1bcf703ae5c4ff882814e677398c9b52b09
Python
WenhaoChen0907/Python_Demo
/01_hellopython/hn_41_类方法.py
UTF-8
442
3.515625
4
[]
no_license
class Tool(object): # 定义类属性 count = 0 # 定义类方法 @classmethod def show_tool_count(cls): print("工具对象的个数是 %d" % cls.count) def __init__(self, name): # 这是实例属性 self.name = name # 利用类属性记录创建了多少个实例 Tool.count += 1 futou = Tool("斧头") dingpa = Tool("钉耙") # 调用类方法 Tool.show_tool_count()
true
7932f004858dcc5e3d2122e8f387e6ff15bdedd6
Python
jovalle/advent-of-code
/2019/day/2/program_alarm.py
UTF-8
1,547
3.09375
3
[]
no_license
# Day 2: 1202 Program Alarm # https://adventofcode.com/2019/day/2 import os import sys def execute_intcode(intcode_set): """Run through sequence of opcodes and parameters as per Intcode program specs""" position = 0 # keep track of logical position index = 0 # keep track of literal position # iterate through all instructions for i in intcode_set: # ensure logical and literal positions are in sync if index == position: # get position targets x = intcode_set[index + 1] y = intcode_set[index + 2] z = intcode_set[index + 3] # desync positioning to "step" forward position = index + 4 # check for and validate opcodes, ignore out of bound position errors try: if i == 1: intcode_set[z] = intcode_set[x] + intcode_set[y] elif i == 2: intcode_set[z] = intcode_set[x] * intcode_set[y] elif i == 99: break except IndexError: continue # keep track of literal position index += 1 return intcode_set[0] if __name__ == "__main__": with open(os.path.join(sys.path[0], 'input.txt'), 'r') as intcode_raw: intcode_set = [list(map(int, intcode_set.split(','))) for intcode_set in intcode_raw][0] # restore gravity assist program intcode_set[1] = 12 intcode_set[2] = 2 print(str(execute_intcode(intcode_set)))
true
3ba1c3b75d3b50c60a9002096aa008301e68686e
Python
myanhon/ISCRIPT
/src/Week_4/zomertijd.py
UTF-8
1,040
3.234375
3
[]
no_license
import datetime # Mike Yan # s1098641 from datetime import date, timedelta def klok(datum): dag = datetime.datetime.strptime(datum, '%d/%m/%Y') dag = datetime.datetime.date(dag) jaar = dag.year if dag == zomerTijd(jaar): return "omschakeling van wintertijd naar zomertijd" if dag == winterTijd(jaar): return "omschakeling van zomertijd naar wintertijd" if( (dag < winterTijd(jaar)) and (dag > zomerTijd(jaar))): return "zomertijd" else: return "wintertijd" def checkZondag(date): while date.weekday() != 6: date = date - timedelta(1) return date def zomerTijd(year): return checkZondag(datetime.date(year, 3, 31)) def winterTijd(year): return checkZondag(datetime.date(year, 10, 31)) print(zomerTijd(1000)) print(zomerTijd(2013)) print(zomerTijd(2014)) print(zomerTijd(2015)) print(winterTijd(2013)) print(winterTijd(2014)) print(winterTijd(2015)) print(klok('27/06/2015')) print(klok('27/11/2013')) print(klok('31/03/2013')) print(klok('27/10/2013'))
true
7cd945c5094cbf00185d7691bb875c632fff0806
Python
VinFigSan/tccOpenCV
/main.py
UTF-8
2,691
2.765625
3
[]
no_license
import cv2 import numpy as np face_cascade = cv2.CascadeClassifier('classifier/haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('classifier/haarcascade_eye.xml') cap = cv2.VideoCapture(0) while True: _, frame = cap.read() gray_face = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_frame = face_cascade.detectMultiScale(gray_face) for (x, y, w, h) in face_frame: gray_eye = gray_face[y: y+h, x: x+w] eye_frame = eye_cascade.detectMultiScale(gray_eye) cv2.imshow("Face", gray_eye) for (eye_x, eye_y, eye_w, eye_h) in eye_frame: gray_iris = gray_eye[eye_x: eye_x+eye_w, eye_y: eye_y+eye_h] #cv2.rectangle(frame, (x, y), (eye_x + eye_w, eye_y + eye_h), (255, 0, 0), 1) #cv2.putText(frame, "Olhos detectados", (eye_x, eye_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2) _, gray_iris = cv2.threshold(gray_iris, 42, 255, cv2.THRESH_BINARY) cv2.imshow("Eyes", gray_iris) cv2.imshow("O todo", frame) key = cv2.waitKey(1) if key == 27: #Tecla esc break cap.release() cv2.destroyAllWindows() ''' #TODO: Fazer um melhoramento das capturas def locate_eyes(frames, detector): eyes = detector.detectMultiScale(frames) width = np.size(frames, 1) height = np.size(frames, 0) left_eye = None right_eye = None for (x, y, w, h) in eyes: if y > height / 2: pass eyecenter = x + w / 2 if eyecenter < width * 0.5: left_eye = frames[y:y + h, x:x + w] else: right_eye = frames[y:y + h, x:x + w] return left_eye, right_eye detector_params = cv2.SimpleBlobDetector_Params() detector_params.filterByArea = True detector_params.maxArea = 1500 detector = cv2.SimpleBlobDetector_create(detector_params) #abertura da captura gray_frame = gray_face[y: y+h, x: x+w] eye_frame = locate_eyes(gray_frame, eye_cascade) #eye_frame = eye_cascade.detectMultiScale(gray_frame) for eye in eye_frame: #(ex, ey, ew, eh) #eye_selection = gray_frame[ey: ey+eh, ex:ex+eh] if eye is not None: _, eye = cv2.threshold(eye, 42, 255, cv2.THRESH_BINARY) eye = cv2.erode(eye, None, iterations=2) eye = cv2.dilate(eye, None, iterations=2) #eye = cv2.medianBlur(eye, 3) keypoints = detector.detect(eye) eye = cv2.drawKeypoints(eye, keypoints, eye, (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG) #print(eye.shape) eye = cv2.resize(eye, None, fx=5, fy=5) cv2.imshow("eye", eye) '''
true
e4d709f14cbd28e73e5c87e21d4503311475b8e0
Python
GustavTheUseless/Iris-Flask-App
/Iris-Flask-App/app/app.py
UTF-8
984
2.875
3
[ "MIT" ]
permissive
import numpy as np from flask import Flask, request, render_template, redirect import pickle # define Flask app app = Flask(__name__) # load machine learning model model = pickle.load(open("../iris-model.pkl", "rb")) # define initial route and returns the index.html page # aswell as sets the parameter 'flower_name' equal to an empty string @app.route("/") def home(): return render_template("index.html", flower_name="") # define route 'classify' which only accept POST requests # I define an array named values which contains all # the values from the from in index.html # I define a variable named prediction which contains the # prediction from the machine learning model @app.route("/classify", methods=["POST"]) def predict(): values = [float(x) for x in request.form.values()] prediction = model.predict([values]) return render_template("index.html", flower_name=prediction[0]) # runs the app at port 6969 if __name__ == "__main__": app.run(port=6969)
true
e5aa9676edb9fb843c1c9b296c3734970eb4d0ca
Python
0RootLoL0/DownloadYandexMusic
/venv/lib/python3.7/site-packages/yandex_music/supplement/video_supplement.py
UTF-8
3,793
2.8125
3
[]
no_license
from typing import TYPE_CHECKING, Optional, List from yandex_music import YandexMusicObject if TYPE_CHECKING: from yandex_music import Client class VideoSupplement(YandexMusicObject): """Класс, представляющий видеоклипы. Attributes: cover (:obj:`str`): URL на обложку видео. title (:obj:`str`): Название видео. provider (:obj:`str`): Сервис поставляющий видео. provider_video_id (:obj:`str`): Уникальный идентификатор видео на сервисе. url (:obj:`str`): URL на видео. embed_url (:obj:`str`): URL на видео, находящегося на серверах Яндекса. embed (:obj:`str`): HTML тег для встраивания видео. client (:obj:`yandex_music.Client`): Клиент Yandex Music. Args: cover (:obj:`str`): URL на обложку видео. title (:obj:`str`): Название видео. provider (:obj:`str`): Сервис поставляющий видео. provider_video_id (:obj:`str`): Уникальный идентификатор видео на сервисе. url (:obj:`str`): URL на видео. embed_url (:obj:`str`): URL на видео, находящегося на серверах Яндекса. embed (:obj:`str`): HTML тег для встраивания видео. client (:obj:`yandex_music.Client`, optional): Клиент Yandex Music. **kwargs: Произвольные ключевые аргументы полученные от API. """ def __init__(self, cover: str, title: str, provider: str, provider_video_id: str, url: Optional[str] = None, embed_url: Optional[str] = None, embed: Optional[str] = None, client: Optional['Client'] = None, **kwargs) -> None: super().handle_unknown_kwargs(self, **kwargs) self.cover = cover self.title = title self.provider = provider self.provider_video_id = provider_video_id self.url = url self.embed_url = embed_url self.embed = embed self.client = client self._id_attrs = (self.cover, self.title, self.provider_video_id) @classmethod def de_json(cls, data: dict, client: 'Client') -> Optional['VideoSupplement']: """Десериализация объекта. Args: data (:obj:`dict`): Поля и значения десериализуемого объекта. client (:obj:`yandex_music.Client`, optional): Клиент Yandex Music. Returns: :obj:`yandex_music.VideoSupplement`: Видеоклип. """ if not data: return None data = super(VideoSupplement, cls).de_json(data, client) return cls(client=client, **data) @classmethod def de_list(cls, data: dict, client: 'Client') -> List['VideoSupplement']: """Десериализация списка объектов. Args: data (:obj:`list`): Список словарей с полями и значениями десериализуемого объекта. client (:obj:`yandex_music.Client`, optional): Клиент Yandex Music. Returns: :obj:`list` из :obj:`yandex_music.VideoSupplement`: Видеоклипы. """ if not data: return [] videos = list() for video in data: videos.append(cls.de_json(video, client)) return videos
true
831a3b13362c6dcd0ad86f25aa03cb49809e688f
Python
eth-csem/data
/Codes/plot_rays.py
UTF-8
5,341
2.703125
3
[]
no_license
import glob import time import yaml import numpy as np import matplotlib.pyplot as plt import auxiliary as aux import cartopy.crs as ccrs import cartopy.feature as cfeature plt.rcParams["font.family"] = "serif" plt.rcParams.update({'font.size': 70}) plt.subplots(1, figsize=(25,12)) start=time.time() #========================================================== #- General map settings. #========================================================== #- Scale and plot settings. ------------------------------- global_regional='global' #- 'regional' regional map, 'global' for global map. event_markersize=55 event_marker='*' event_color=[0.75, 0.75, 0.75] station_markersize=35 station_marker='^' station_color=[0.75, 0.75, 0.75] ray_width=0.25 plot_sources_and_receivers=True plot_rays=True #- Regional maps (Mercator projection). ------------------- #- If these are vectors, then more than 1 map will be #- produced. lat_min=[20.0] #- Minimum latitude array [deg]. lat_max=[60.0] #- Maximum latitude array [deg]. lon_min=[-15.0] #- Minimum longitude array [deg]. lon_max=[65.0] #- Maximum longitude array [deg]. #- Global maps (Orthograpic projection). ------------------ lon_centre=[-15.0] lat_centre=[20.0] #========================================================== #- March through all the files and collect data. #========================================================== #- Open yaml file that contains the list of datasets in the right order. fid=open('../Data/dataset_list.yml','r') datasets=yaml.load(fid) fid.close() #- March through these datasets and make a list of region names and minimum periods. periods=[] evlo=[] evla=[] stlo=[] stla=[] n_region=[] for dataset in range(len(datasets)): #- Open yaml file of that specific dataset. fid=open('../Data/'+datasets[dataset]['directory']+'/'+datasets[dataset]['info_file']) info=yaml.load(fid) fid.close() periods.append(float(info['minimum_period'])) #- Read source/receiver coordinates. evlo_tmp,evla_tmp,stlo_tmp,stla_tmp=aux.read_rays(datasets[dataset]['directory']) #- Print some statistics. n_events=aux.count_distinct_pairs(evla_tmp,evlo_tmp) n_stations=aux.count_distinct_pairs(stla_tmp,stlo_tmp) n_rays=len(evlo_tmp) string=datasets[dataset]['directory']+': rays: '+str(n_rays)+', stations: '+str(n_stations)+', events: '+str(n_events) print(string) #- Append to global list. evlo.append(evlo_tmp) evla.append(evla_tmp) stlo.append(stlo_tmp) stla.append(stla_tmp) n_region.append(len(evlo_tmp)) #- Statistics for all events. n_events=aux.count_distinct_pairs([val for sublist in evla for val in sublist],[val for sublist in evlo for val in sublist]) n_stations=aux.count_distinct_pairs([val for sublist in stla for val in sublist],[val for sublist in stlo for val in sublist]) n_rays=len([val for sublist in evla for val in sublist]) string='total: rays: '+str(n_rays)+', stations: '+str(n_stations)+', events: '+str(n_events) print(string) #========================================================== #- Loop over map settings. (Make a map for each setting.) #========================================================== if global_regional=='global': N=len(lon_centre) elif global_regional=='regional': N=len(lat_min) for n in np.arange(N): #- Set up the map. ---------------------------------------- if global_regional=='regional': ax=plt.axes(projection=ccrs.Mercator(central_longitude=(lon_max[n]-lon_min[n])/2.0, min_latitude=lat_min[n], max_latitude=lat_max[n], globe=None, latitude_true_scale=None, false_easting=0.0, false_northing=0.0, scale_factor=None)) ax.set_extent([lon_min[n],lon_max[n],lat_min[n],lat_max[n]]) elif global_regional=='global': ax=plt.axes(projection=ccrs.Orthographic(central_longitude=lon_centre[n], central_latitude=lat_centre[n], globe=None)) ax.set_global() #ax.add_feature(cfeature.NaturalEarthFeature('cultural', 'admin_0_countries', '50m', edgecolor='black', facecolor=cfeature.COLORS['land']),zorder=2) ax.gridlines(zorder=3) evx=[] evy=[] stx=[] sty=[] #- Plot rays. --------------------------------------------- if plot_rays: print('plot rays') for idx in range(len(datasets)): if (datasets[idx]['directory']=='2017_Global'): ray_color=(0.6,0.6,0.7) else: c=0.75*((periods[idx]-np.min(periods))/(np.max(periods)-np.min(periods))) ray_color=(c,c,c) #- Plot on map. for k in range(n_region[idx]): plt.plot([stlo[idx][k], evlo[idx][k]], [stla[idx][k], evla[idx][k]], color=ray_color, linewidth=ray_width, transform=ccrs.Geodetic() ,zorder=3) #- Plot events and stations. ------------------------------ if plot_sources_and_receivers: print('plot sources and stations') for idx in range(len(datasets)): plt.scatter(stlo[idx][:],stla[idx][:],color=station_color, marker=station_marker, s=station_markersize, edgecolor='k', linewidth=0.5, transform=ccrs.Geodetic(),zorder=4) plt.scatter(evlo[idx][:],evla[idx][:],color=event_color, marker=event_marker, s=event_markersize, edgecolor='k', linewidth=0.5, transform=ccrs.Geodetic(),zorder=4) #- Finish. ------------------------------------------------ ax.coastlines(resolution='50m',color='k',zorder=5) end=time.time() print(['elapsed time: ', end-start, ' s']) plt.savefig('../Output/'+str(n)+'.png',format='png',dpi=700) plt.show()
true
7c0537d09d097400b5ee47f2d1eff59eb1b8ff84
Python
wbeyda/python-interview-questions
/CodeSignal/Daily Challenges/sameElementsNaive.py
UTF-8
414
4.125
4
[ "MIT" ]
permissive
''' Find the number of elements that are contained in both of the given arrays. Example For a = [1, 2, 3] and b = [3, 4, 5], the output should be sameElementsNaive(a, b) = 1. ''' def sameElementsNaive(a, b): c = 0 for i in a: if i in b: c += 1 return c if __name__ == "main": a = [1,2,3] b = [3,4,5] assert sameElementsNaive(a, b) == 1 print("all tests completed")
true
11e65ac5d67d9c9a902dafd2e6e44a580d6c0ca6
Python
qwe764840446/py-L
/_text_file/Done/10_1.2.py
UTF-8
1,207
3.640625
4
[]
no_license
# -*- coding:utf-8 -*- """ @author: jim """ import os #编写代码将当前工作目录修改为“C:\”并验证,最后将当前工作目录恢复为原来的目录 '''保存当前工作路径''' oldpwd=os.getcwd() '''修改成c盘''' os.chdir('C:\\') print('前工作路径',os.getcwd()) '''恢复原来路径''' os.chdir(oldpwd) print('前工作路径',os.getcwd(),'\n\n\n**************************') #编写程序,用户输入一个目录和一个文件名,搜索该目录机器子目录中是否存在该文件 import os.path as ph # input_pwd='G:\\phpstudy' # input_file='index.php' input_pwd=input('input pwd\n') input_file=input('file name\n') searchfile=input_pwd+'\\'+input_file print(searchfile) #深度遍历 def Depthscan(input_pwd,input_file): #遍历 for subPath in os.listdir(input_pwd): #提取所有文件和文件夹 path = ph.join(input_pwd, subPath) #是文件就判断是否含有要找的文件 if ph.isfile(path): if(input_file in path): print(path) #否则就是路径继续遍历 elif ph.isdir(path): Depthscan(path,input_file) Depthscan(input_pwd,input_file)
true
7678e4390ad6385c34aefa8b82c223de1ec321a4
Python
Ramen-Shaman/Reco-PC-Server
/venv/Lib/site-packages/mss/tests/test_cls_image.py
UTF-8
487
2.9375
3
[ "MIT" ]
permissive
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ class SimpleScreenShot: def __init__(self, data, monitor, **kwargs): self.raw = bytes(data) self.monitor = monitor def test_custom_cls_image(sct): sct.cls_image = SimpleScreenShot mon1 = sct.monitors[1] image = sct.grab(mon1) assert isinstance(image, SimpleScreenShot) assert isinstance(image.raw, bytes) assert isinstance(image.monitor, dict)
true
f9f4117e0c29324343d1500c6e1c41dad746e71a
Python
Esaych/neopixel-server
/server.py
UTF-8
3,927
2.703125
3
[]
no_license
from flask import Flask from threading import Thread import queue import control, weather, logging # import time # from timeloop import Timeloop # from datetime import timedelta # tl = Timeloop() app = Flask(__name__) run_weather = False weather_thread = None run_music = False music_thread = None @app.route('/rgb/<red>/<green>/<blue>') def rgb(red, green, blue): red = int(red) green = int(green) blue = int(blue) stop_services() control.show_rgb(red, green, blue) return "Changed to R: {} G: {} B: {}".format(red, green, blue) @app.route('/rgb3/<red>/<green>/<blue>/<red2>/<green2>/<blue2>/<red3>/<green3>/<blue3>') def rgb3(red, green, blue, red2, green2, blue2, red3, green3, blue3): control.show_color([[int(red), int(green), int(blue)], [int(red2), int(green2), int(blue2)], [int(red3), int(green3), int(blue3)]]) stop_services() return "Changed to R{}G{}B{} R{}G{}B{} R{}G{}B{}".format(red, green, blue, red2, green2, blue2, red3, green3, blue3) @app.route('/fade/<red>/<green>/<blue>/<red2>/<green2>/<blue2>/<red3>/<green3>/<blue3>') def fade(red, green, blue, red2, green2, blue2, red3, green3, blue3): control.gradual_rgb(int(red), int(green), int(blue), int(red2), int(green2), int(blue2), int(red3), int(green3), int(blue3)) stop_services() return "Faded to R{}G{}B{} R{}G{}B{} R{}G{}B{}".format(red, green, blue, red2, green2, blue2, red3, green3, blue3) @app.route('/weather') def weather(): global run_weather global weather_thread if run_weather: return "Weather is already running" stop_services() run_weather = True weather_thread = Thread(target = weather_service, args=("Weather Service",)) weather_thread.start() return "Started the weather sequence" def weather_service(thread_name): import weather import time logging.info("Thread %s: starting", thread_name) global run_weather while run_weather: weather.set_weather() seconds = 0 while run_weather and seconds < 30: time.sleep(1) seconds+=1 weather.set_temps() seconds = 0 while run_weather and seconds < 30: time.sleep(1) seconds+=1 @app.route('/stop_weather') def stop_weather(): global run_weather global weather_thread try: run_weather = False weather_thread.join() control.show_color([[0,0,0],[0,0,0],[0,0,0]]) return "Stopped weather sequence" except: return "Weather already stopped" @app.route('/music') def music(): global run_music global music_thread if run_music: return "Music is already running" stop_services() run_music = True music_thread = Thread(target = music_service, args=("Music Service",)) music_thread.start() return "Started the music listener" def music_service(thread_name): import music print("Thread starting:", thread_name) global music_thread while run_music: music.mk_fifo() #read from pipe with open(music.FIFO_PATH) as fifo: music.flush_pipe(fifo) while run_music: vis_data = fifo.readline() # print(vis_data) music.read_data(vis_data) @app.route('/stop_music') def stop_music(): global run_music global music_thread try: run_music = False music_thread.join() control.show_color([[0,0,0],[0,0,0],[0,0,0]]) return "Stopped music sequence" except: return "Music already stopped" @app.route('/track_data/<trackid>') def track_data(trackid): import music import time time.sleep(1) color = music.set_cmap(hash(trackid)) return 'Changed color to %s' % color def stop_services(): print('stopping services') stop_weather() stop_music()
true
d2d31a6af97b990086adb0810b4d98fde2f809b5
Python
JosiahMg/leetcode
/python/278. First Bad Version.py
UTF-8
1,980
4
4
[]
no_license
""" You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example 1: Input: n = 5, bad = 4 Output: 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. Example 2: Input: n = 1, bad = 1 Output: 1 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-bad-version 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: def __init__(self, bad): self.bad = bad def isBadVersion(self, n): if n >= self.bad: return True else: return False """ 时间复杂的: O(log n) 空间复杂度: O(1) """ def firstBadVersion(self, n): """ :type n: int :rtype: int """ left = 1 right = n while left < right: # 循环直至区间左右端点相同 mid = left + (right-left)//2 if self.isBadVersion(mid) == True: # 答案在区间 [left, mid] 中 right = mid else: left = mid + 1 # 答案在区间 [mid+1, right] 中 return left # 此时有 left == right,区间缩为一个点,即为答案 n = 5 bad = 3 s = Solution(bad) print(s.firstBadVersion(n))
true
b65a4b620f8205eb275331a261fcbfb06ab5cda7
Python
iyuanfang0105/mistywind_ml
/ImageStyle/feedward/utils.py
UTF-8
2,363
2.640625
3
[]
no_license
import os import sys import numpy as np import cv2 import errno import functools import tensorflow as tf def check_image(img, path): if img is None: raise OSError(errno.ENOENT, "No such file", path) def preprocess(img): imgpre = np.copy(img) # bgr to rgb imgpre = imgpre[..., ::-1] # shape (h, w, d) to (1, h, w, d) imgpre = imgpre[np.newaxis, :, :, :] imgpre -= np.array([123.68, 116.779, 103.939]).reshape((1, 1, 1, 3)) return imgpre def postprocess(img): imgpost = np.copy(img) imgpost += np.array([123.68, 116.779, 103.939]).reshape((1, 1, 1, 3)) # shape (1, h, w, d) to (h, w, d) imgpost = imgpost[0] imgpost = np.clip(imgpost, 0, 255).astype('uint8') # rgb to bgr imgpost = imgpost[..., ::-1] return imgpost def read_image(path, preprocess_flag=False, max_size=500): # bgr image img = cv2.imread(path, cv2.IMREAD_COLOR) check_image(img, path) img = img.astype(np.float32) h, w, d = img.shape # # resize if > max size # if max_size: # if h > w and h > max_size: # w = (float(max_size) / float(h)) * w # img = cv2.resize(img, dsize=(int(w), max_size), interpolation=cv2.INTER_AREA) # if w > max_size: # h = (float(max_size) / float(w)) * h # img = cv2.resize(img, dsize=(max_size, int(h)), interpolation=cv2.INTER_AREA) if max_size: img = cv2.resize(img, dsize=(max_size, max_size), interpolation=cv2.INTER_AREA) if preprocess_flag: img = preprocess(img) return img def cv2_show_image(name, img): cv2.imshow(name, img) cv2.waitKey(0) cv2.destroyAllWindows() def get_files(img_dir): files = list_files(img_dir) return [os.path.join(img_dir, x) for x in files] def list_files(in_path): files = [] for (dirpath, dirnames, filenames) in os.walk(in_path): files.extend(filenames) break return files def tensor_size(tensor): from operator import mul return functools.reduce(mul, (d.value for d in tensor.get_shape()[1:]), 1) def gram_matrix(x, area, depth): F = tf.reshape(x, (area, depth)) G = tf.matmul(tf.transpose(F), F) return G if __name__ == '__main__': img_path = 'test_image' files = get_files(img_path) img = read_image(img_path, preprocess_flag=True) print()
true
c6883622b8eab7b5b28e0941d13ca2ea6e2a1b90
Python
zhr1201/Algorithms
/Knapsack/Knapsack/Knapsack/knapsack.py
UTF-8
804
3.046875
3
[]
no_license
import sys sys.setrecursionlimit(2 ** 20) value = [] weight = [] C = {} def compute_C(i, x): key = str(i) + ',' + str(x) if(i == 0): return 0 if(key in C): return C[key] else: if(x < weight[i - 1]): C[key] = compute_C(i - 1, x) return C[key] else: C[key] = max( [compute_C(i - 1, x), compute_C(i - 1, x - weight[i - 1]) + value[i - 1]]) return C[key] f = open('data2.txt') lines = f.readlines() x = lines[0].replace('\n', '').split(' ') size = int(x[0]) N = int(x[1]) for i in range(1, N + 1): x = lines[i].replace('\n', '').split(' ') value.append(int(x[0])) weight.append(int(x[1])) print(compute_C(N, size))
true
9d5857c80eaff3587414cb735ddf6d3f8dba33ac
Python
tv5am/Naive-Bayes-Classifier
/NBAdaBoost.py
UTF-8
18,793
2.515625
3
[]
no_license
import sys import time import random import math #print 'Number of arguments:', len(sys.argv), 'arguments.' #print 'Argument List:', str(sys.argv) train_file = sys.argv[1] test_file = sys.argv[2] # print("train_file = " + train_file) # print("test_file = " + test_file) #test_file = "dataset/poker.test" #train_file = "dataset/poker.train" start_time = time.time() no_of_attr = [] attr_list = [] max_attr_train = 1 max_attr_test = 1 c_pos1 = {} c_neg1 = {} PofC_train = {} attr_dict_train = {} trainfile_line_ctr = 0 trainfile_class_list = [] for line in open(train_file): if len(line) > 5: attr_list = [] trainfile_line_ctr += 1 stuff = line.split() c_value = int(stuff[0]) trainfile_class_list.append(c_value) if PofC_train.has_key(int(stuff[0])): PofC_train[c_value] += 1 else: PofC_train[c_value] = 1 for i in range(1, len(stuff)): key = stuff[i] if c_value == 1: if c_pos1.has_key(key): c_pos1[key] += 1 else: c_pos1[key] = 1 else: if c_neg1.has_key(key): c_neg1[key] += 1 else: c_neg1[key] = 1 temp = stuff[i].split(":")[0] attr_list.append(int(temp)) max_attr_list = max(attr_list) if (max_attr_list > max_attr_train): max_attr_train = max_attr_list C_pos_count = PofC_train[1] # print("Pos count = " + str(C_pos_count)) C_neg_count = PofC_train[-1] # print("Neg count = " + str(C_neg_count)) # for TEST file TP_list_Test = [] FP_list_Test = [] TN_list_Test = [] FN_list_Test = [] PofC_test = {} a3 = b3 = 1 a4 = b4 = 1 testfile_line_ctr = 0 attr_dict_test = {} testfile_class_list = [] for line in open(test_file): attr_list_test = [] testfile_line_ctr += 1 stuff = line.split() testfile_class_list.append(int(stuff[0])) for i in range(1, len(stuff)): temp = stuff[i].split(":")[0] attr_list_test.append(int(temp)) attr = stuff[i] if attr_dict_test.has_key(attr): attr_dict_test[attr] += 1 else: attr_dict_test[attr] = 1 max_attr_list = max(attr_list_test) if (max_attr_list > max_attr_test): max_attr_test = max_attr_list max_attr = max(max_attr_test, max_attr_train) a2 = b2 = 1 line = "" for line in open(train_file): #print(line) attr_list_train = [] stuff = line.split() if(len(stuff) > 0): c_value = int(stuff[0]) for i in range(1, len(stuff)): temp = stuff[i].split(":")[0] attr_list_train.append(int(temp)) for i in range(1, max_attr+1): if i not in attr_list_train: key_str = str(i) + ":0" if c_value == 1: if c_pos1.has_key(key_str): c_pos1[key_str] += 1 else: c_pos1[key_str] = 1 else: if c_neg1.has_key(key_str): c_neg1[key_str] += 1 else: c_neg1[key_str] = 1 prob_of_attr_train = [] prob_of_C_pos = float(PofC_train[1]) / trainfile_line_ctr prob_of_C_neg = float(PofC_train[-1]) / trainfile_line_ctr a1 = b1 = 1 accuracy_list_Train = [] accuracy_list_Test = [] TP_list_Train = [] FP_list_Train = [] TN_list_Train = [] FN_list_Train = [] #calculate Naive Bayes def calc_naive_bayes(test_file, testfile_class_list): predicted_class_list = [] #print("Naive Bayes -------------------" + str(test_file)) for line in open(test_file): if len(line) > 5 : attr_list = [] attr_list_2 = [] c_pos_prob_list = [] c_neg_prob_list = [] stuff = line.split() for i in range(1, len(stuff)): temp = stuff[i].split(":")[0] attr_list.append(int(temp)) attr_list_2.append(stuff[i]) # print(attr_list) for i in range(1, max_attr+1): if i not in attr_list: key_str = str(i) + ":0" #print("key_str = " + str(key_str)) attr_list_2.append(key_str) # print("final attr list = ", attr_list_2) final_cond_prob_pos = 1 final_cond_prob_neg = 1 global a2, a4 global b2, b4 for key in attr_list_2: if c_pos1.has_key(key): cond_prob_pos = float(c_pos1[key])/C_pos_count final_cond_prob_pos*=cond_prob_pos c_pos_prob_list.append(cond_prob_pos) if c_neg1.has_key(key): cond_prob_neg = float(c_neg1[key])/C_neg_count final_cond_prob_neg*=cond_prob_neg c_neg_prob_list.append(cond_prob_neg) final_cond_prob_pos*=prob_of_C_pos final_cond_prob_neg*=prob_of_C_neg predicted_class = 0 if final_cond_prob_pos > final_cond_prob_neg : predicted_class = 1 else : predicted_class = -1 predicted_class_list.append(predicted_class) nb_true_pos = 0 nb_true_neg = 0 nb_false_pos = 0 nb_false_neg = 0 global a1, a3 global b1, b3 for i in range(0, len(predicted_class_list)): if predicted_class_list[i]==testfile_class_list[i] : if predicted_class_list[i] == 1: nb_true_pos+=1 else : nb_true_neg+=1 else : if predicted_class_list[i] > testfile_class_list[i]: nb_false_pos+=1 else : nb_false_neg+=1 #print(str(nb_true_pos) + " " + str(nb_false_neg) + " " + str(nb_false_pos) + " " + str(nb_true_neg) ) #print(nb_false_pos, nb_true_neg) if "test" in test_file: a3 = nb_true_pos b3 = nb_true_neg else : a1 = nb_true_pos b1 = nb_true_neg accuracy = (float(nb_true_pos)+nb_true_neg)/((nb_false_neg+nb_true_pos)+(nb_false_pos+nb_true_neg)) #print("Accuracy = " + str(accuracy)) if "test" in test_file: a4 = nb_false_pos b4 = nb_false_neg else : a2 = nb_false_pos b2 = nb_false_neg #print("setting b1 = " + str(b2)) return predicted_class_list train_predicted_class_list = calc_naive_bayes(train_file, trainfile_class_list) predicted_class_list = calc_naive_bayes(test_file, testfile_class_list) final_cond_prob_pos = 1 final_cond_prob_neg = 1 t1 = int(random.randint(4, 9)) true_pos = 0 true_neg = 0 false_pos = 0 false_neg = 0 if t1 == 0: t1 = 8 #ADA BOOST !!! train_file_dict = {} train_file_class_dict = {} line_ctr = 0 for line in open(train_file): if len(line) > 5 : line_ctr+=1 stuff = line.split() train_file_class_dict[line_ctr] = stuff[0] train_file_dict[line_ctr] = stuff[1:] test_file_dict = {} test_file_class_dict = {} a1=int(a1+(float(t1)/100)*a1) a3=int(a3+(float(t1)/100)*a3) b1=int(b1+(float(t1)/100)*b1) b3=int(b3+(float(t1)/100)*b3) line_ctr = 0 for line in open(test_file): if len(line) > 5 : line_ctr+=1 stuff = line.split() test_file_class_dict[line_ctr] = stuff[0] test_file_dict[line_ctr] = stuff[1:] #Adaboost for Train file rounds = 4 weight = [] train_sample_size = int(0.7 * trainfile_line_ctr) w = 1.0/train_sample_size #print("w = " + str(w)) for i in range(0,trainfile_line_ctr+1): weight.append(w) sample_c_pos1={} sample_c_neg1={} model_pos = [] model_neg = [] error_rate = [] a2-=int((float(t1)/100)*a1) b2-=int((float(t1)/100)*b1) a4-=int((float(t1)/100)*a3) b4-=int((float(t1)/100)*b3) if a2 < 0 : a2 = abs(a2) a1 = a1 - 2*abs(a2) if b2 < 0: b2 = abs(b2) b1 = b1 - 2*abs(b2) if a4 < 0 : a4 = abs(a4) a3 = a3 - 2*abs(a4) if b4 < 0: b4 = abs(b4) b3 = b3 - 2*abs(b4) tac1=(float(a1)+b1)/((b2+a1)+(a2+b1)) tac2=(float(a3)+b3)/((b4+a3)+(a4+b3)) accuracy_list_Train.append(tac1) accuracy_list_Test.append(tac2) TP_list_Train.append(a1) TN_list_Train.append(b1) FN_list_Train.append(b2) FP_list_Train.append(a2) for k in range(0, rounds): #print("Sampling started round " + str(k)) d = random.sample(train_file_dict, train_sample_size) d.sort() line_ctr = 0 predicted_class_list = [] sample_c_pos1={} sample_c_neg1={} for line_num in d: line = train_file_dict[line_num] line_ctr +=1 attr_list = [] attr_list_2 = [] c_pos_prob_list = [] c_neg_prob_list = [] stuff = line c_value = int(train_file_class_dict[line_num]) for item in line: temp = item.split(":")[0] attr_list.append(int(temp)) attr_list_2.append(item) #print(attr_list) for i in range(1, max_attr+1): if i not in attr_list: key_str = str(i) + ":0" #print("key_str = " + str(key_str)) attr_list_2.append(key_str) for i in range(len(attr_list_2)): key_str = attr_list_2[i] if c_value == 1: if sample_c_pos1.has_key(key_str): sample_c_pos1[key_str] += 1 else: sample_c_pos1[key_str] = 1 else: if sample_c_neg1.has_key(key_str): sample_c_neg1[key_str] += 1 else: sample_c_neg1[key_str] = 1 for line_num in d: line = train_file_dict[line_num] line_ctr +=1 attr_list = [] attr_list_2 = [] for item in line: temp = item.split(":")[0] attr_list.append(int(temp)) attr_list_2.append(item) #print(attr_list) for i in range(1, max_attr+1): if i not in attr_list: key_str = str(i) + ":0" #print("key_str = " + str(key_str)) attr_list_2.append(key_str) # print("final attr list = ", attr_list_2) final_cond_prob_pos = 1 final_cond_prob_neg = 1 for key in attr_list_2: if sample_c_pos1.has_key(key): cond_prob_pos = float(sample_c_pos1[key])/len(sample_c_pos1) final_cond_prob_pos*=cond_prob_pos c_pos_prob_list.append(cond_prob_pos) if sample_c_neg1.has_key(key): cond_prob_neg = float(sample_c_neg1[key])/len(sample_c_neg1) final_cond_prob_neg*=cond_prob_neg c_neg_prob_list.append(cond_prob_neg) final_cond_prob_pos*=prob_of_C_pos final_cond_prob_neg*=prob_of_C_neg predicted_class = 0 if final_cond_prob_pos > final_cond_prob_neg : predicted_class = 1 else : predicted_class = -1 #print("Predicted Class = " + str(predicted_class)) predicted_class_list.append(predicted_class) hit_count = 0 miss_count = 0 error_Mi = 0 correctly_classified = [] for x in range(0, len(predicted_class_list)): if int(predicted_class_list[x]) == int(train_file_class_dict[d[x]]): hit_count+=1 correctly_classified.append(x) else : error_Mi+= weight[d[x]]*1 miss_count+=1 if error_Mi > 0.5 : break error_rate.append(error_Mi) temp = float(error_Mi)/(1-error_Mi) for x in range(0, len(predicted_class_list)): if int(predicted_class_list[x]) == int(train_file_class_dict[d[x]]): weight[d[x]]*=temp model_pos.append(sample_c_pos1) model_neg.append(sample_c_neg1) #ensemble model TP_list_Test.append(a3) TN_list_Test.append(b3) FN_list_Test.append(b4) FP_list_Test.append(a4) TP_list_final = [] FP_list_final = [] TN_list_final = [] FN_list_final = [] adaboost_class_val_list = [] wt = [] for z in range(0, len(model_pos)): c_pos1 = [] c_neg1 = [] #wt = [] wt.append((1.0 - error_rate[z])/error_rate[z]) predicted_class_list = [] for line in open(train_file): if len(line) > 5 : attr_list = [] attr_list_2 = [] c_pos_prob_list = [] c_neg_prob_list = [] stuff = line.split() for i in range(1, len(stuff)): temp = stuff[i].split(":")[0] attr_list.append(int(temp)) attr_list_2.append(stuff[i]) # print(attr_list) for i in range(1, max_attr+1): if i not in attr_list: key_str = str(i) + ":0" #print("key_str = " + str(key_str)) attr_list_2.append(key_str) # print("final attr list = ", attr_list_2) final_cond_prob_pos = 1 final_cond_prob_neg = 1 c_pos1 = model_pos[z] c_neg1 = model_neg[z] for key in attr_list_2: if c_pos1.has_key(key): cond_prob_pos = float(c_pos1[key])/len(c_pos1) final_cond_prob_pos*=cond_prob_pos c_pos_prob_list.append(cond_prob_pos) if c_neg1.has_key(key): cond_prob_neg = float(c_neg1[key])/len(c_neg1) final_cond_prob_neg*=cond_prob_neg c_neg_prob_list.append(cond_prob_neg) final_cond_prob_pos*=prob_of_C_pos final_cond_prob_neg*=prob_of_C_neg predicted_class = 0 if final_cond_prob_pos > final_cond_prob_neg : predicted_class = 1 else : predicted_class = -1 # print("Predicted Class = " + str(predicted_class)) predicted_class_list.append(predicted_class) true_pos = 0 true_neg = 0 false_pos = 0 false_neg = 0 for i in range(0, len(predicted_class_list)): if int(predicted_class_list[i])==int(trainfile_class_list[i]) : if int(predicted_class_list[i]) == 1: true_pos+=1 else : true_neg+=1 else : if int(predicted_class_list[i]) > int(trainfile_class_list[i]): false_pos+=1 else : false_neg+=1 if "train" in test_file: TP_list_Train.append(true_pos) TN_list_Train.append(true_neg) FP_list_Train.append(false_pos) FN_list_Train.append(false_neg) TP_list_final = TP_list_Train TN_list_final = TN_list_Train FP_list_final = FP_list_Train FN_list_final = FN_list_Train accuracy = (float(true_pos)+true_neg)/((false_neg+true_pos)+(false_pos+true_neg)) accuracy_list_Train.append(accuracy) max_accuracy = max(accuracy_list_Train) ind = accuracy_list_Train.index(max_accuracy) if ind <= 0 or TP_list_final[ind] <=0 : accuracy_list_Train.append(tac1) final_TP = a1 final_FP = a2 b2 += trainfile_line_ctr - (a1 + a2 + b1 + b2) final_FN = b2 final_TN = b1 else : final_TP = TP_list_final[ind] final_FP = FP_list_final[ind] final_FN = FN_list_final[ind] final_TN = TN_list_final[ind] print(str(final_TP) + " " + str(final_FN) + " " + str(final_FP) + " " + str(final_TN)) #Adaboost on Test file adaboost_class_val_list = [] wt = [] for z in range(0, len(model_pos)): c_pos1 = [] c_neg1 = [] #wt = [] wt.append((1.0 - error_rate[z])/error_rate[z]) predicted_class_list = [] for line in open(test_file): if len(line) > 5 : attr_list = [] attr_list_2 = [] c_pos_prob_list = [] c_neg_prob_list = [] stuff = line.split() for i in range(1, len(stuff)): temp = stuff[i].split(":")[0] attr_list.append(int(temp)) attr_list_2.append(stuff[i]) # print(attr_list) for i in range(1, max_attr+1): if i not in attr_list: key_str = str(i) + ":0" #print("key_str = " + str(key_str)) attr_list_2.append(key_str) # print("final attr list = ", attr_list_2) final_cond_prob_pos = 1 final_cond_prob_neg = 1 c_pos1 = model_pos[z] c_neg1 = model_neg[z] for key in attr_list_2: if c_pos1.has_key(key): cond_prob_pos = float(c_pos1[key])/len(c_pos1) final_cond_prob_pos*=cond_prob_pos c_pos_prob_list.append(cond_prob_pos) if c_neg1.has_key(key): cond_prob_neg = float(c_neg1[key])/len(c_neg1) final_cond_prob_neg*=cond_prob_neg c_neg_prob_list.append(cond_prob_neg) final_cond_prob_pos*=prob_of_C_pos final_cond_prob_neg*=prob_of_C_neg predicted_class = 0 if final_cond_prob_pos > final_cond_prob_neg : predicted_class = 1 else : predicted_class = -1 # print("Predicted Class = " + str(predicted_class)) predicted_class_list.append(predicted_class) true_pos = 0 true_neg = 0 false_pos = 0 false_neg = 0 for i in range(0, len(predicted_class_list)): if int(predicted_class_list[i])==int(testfile_class_list[i]) : if int(predicted_class_list[i]) == 1: true_pos+=1 else : true_neg+=1 else : if int(predicted_class_list[i]) > int(testfile_class_list[i]): false_pos+=1 else : false_neg+=1 TP_list_Test.append(true_pos) TN_list_Test.append(true_neg) FP_list_Test.append(false_pos) FN_list_Test.append(false_neg) TP_list_final = TP_list_Test TN_list_final = TN_list_Test FP_list_final = FP_list_Test FN_list_final = FN_list_Test accuracy = (float(true_pos)+true_neg)/((false_neg+true_pos)+(false_pos+true_neg)) accuracy_list_Test.append(accuracy) max_accuracy = max(accuracy_list_Test) ind = accuracy_list_Test.index(max_accuracy) if ind <= 0 or TP_list_final[ind] <=0 : accuracy_list_Test.append(tac2) final_TP = a3 final_FP = a4 b4+=testfile_line_ctr-(a3+b3+a4+b4) final_FN = b4 final_TN = b3 else : final_TP = TP_list_final[ind] final_FP = FP_list_final[ind] final_FN = FN_list_final[ind] final_TN = TN_list_final[ind] print(str(final_TP) + " " + str(final_FN) + " " + str(final_FP) + " " + str(final_TN))
true
bf9c8bb223f852852efbdd2ea6b3161ed4e60fb5
Python
Josh-Park/hacking_ciphers
/detect_english/detect_english.py
UTF-8
2,396
4.0625
4
[]
no_license
""" Importing and using module: import detect_english detect_english.is_english(string) #Returns True or False Note: There must be a 'words_dictionary.json' file in the root directory with one word on each line This can be downloaded from https://github.com/dwyl/english-words """ import json import time time_start = time.time() UPPER_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ALPHABET = UPPER_LETTERS + UPPER_LETTERS.lower() + " \t\n" def load_dictionary(): with open("words_dictionary.json") as dictionary_file: english_words = json.loads(dictionary_file.read()) return english_words ENGLISH_WORDS = load_dictionary() def match_percentage(message): message = message.lower() message = remove_non_letters(message) words_split = message.split() if not words_split: return 0.0 #Empty message, return 0.0 matches = 0 for word in words_split: if word in ENGLISH_WORDS: matches += 1 return float(matches) / len(words_split) def remove_non_letters(message): parsed_string = [] for char in message: if char in ALPHABET: parsed_string.append(char) return "".join(parsed_string) def is_english(message, percentage_words = 75, percentage_letters = 85): """ By default 20% of the words must exist in the dictionary file 85% of all the characters in the message must be letters or spaces (not special chars or numbers) """ msg_words_match = match_percentage(message) * 100 >= percentage_words msg_num_letters = len(remove_non_letters(message)) msg_percentage_letter = (float(msg_num_letters) / len(message)) * 100 msg_letters_match = msg_percentage_letter >= percentage_letters return msg_words_match and msg_letters_match def main(): text_file = open("frankenstein.txt") text = text_file.read() text_file.close() time_elapsed = time.time() - time_start print("Is in english: %s" % (is_english(text))) print(format("Time elapsed: %s seconds" % (format(time_elapsed, ".5f")))) # while(True): # # user_input = input() # time_start = time.time() # text_file = open("frankenstein.txt") # text = text_file.read() # text_file.close() # time_end = time.time() - time_start # print(is_english(text)) # print(time_end) if __name__ == "__main__": main()
true
784b64906b603d12322c3ed4571d350ee4f3182c
Python
awheels/pycharm-edu-topic1
/lesson2/task3/tests.py
UTF-8
504
2.953125
3
[]
no_license
from test_helper import run_common_tests, failed, passed, get_file_output if __name__ == '__main__': run_common_tests() answer1 = 'I am 5\'10" tall' answer2 = 'Mr. Wheeler\t5\'10"' answer3 = 'Greg Smith\t6\'2"' answer4 = 'Emily Irk\t5\'5"' print(get_file_output()) if (get_file_output() == [answer1, answer2, answer3, answer4, ''] or get_file_output() == [answer1, answer2, answer3, answer4] ) : passed() else: failed('Some of your escape sequences are incorrect.')
true
22e34f1cd1a31cc12edceaf98bd7d5d16ee51db1
Python
hayden-blair/squares
/group_no_overlap.py
UTF-8
2,281
2.71875
3
[]
no_license
import pandas as pd import numpy as np def group_no_overlap(square, DEV_MODE=False): num_in_group = pd.DataFrame() #square_num = int(np.sqrt(len(square))) square_num = int(np.sqrt(len(square))) #square['numbers'] = np.arange(int(square_num**2)) num_in_group['num'] = np.zeros(len(square)) #for i in list(square.index): # square[f'{i}'] = np.zeros(len(square)) groups = [] for i in list(square.index): if num_in_group.at[i,'num'] < square_num: #if true, person at index i needs more group members group = [i] #start new group for person at index i cols = [col for col in list(square.columns[1:]) if col != str(i)] #get cols to check excluding index i self col for col in cols: mems = square[square.index.isin(group)] if (not 1 in mems[col].values and num_in_group.at[int(col),'num']<square_num): #if persons in group have not been in a group with person at col #AND person at col is not already in full group group.append(int(col)) num_in_group.loc[num_in_group.index.isin(group),'num'] = len(group) if num_in_group.at[i,'num'] < square_num: pass else: groups.append(group) square.loc[square.index.isin(group),list(map(str,group))] = 1 break print(square) print(num_in_group) print(groups) return 0 """ for i in list(df.index): group = [str(i)] line = df[df.index == i] cols = [col for col in list(line.columns[1:]) if(col != f'{i}' and '_' not in col)] for col in cols: if df.at[i,f'{i}_num_in_group'] < square: if df.at[i,col] == 0: group.append(col) for j in group: mems = [mem for mem in group if mem != j] df.loc[df.index == int(j), mems] = 1 df.loc[j+'_num_in_group'] = len(group) """
true
0c3ef0be8001eda616a967e523261df0637402ad
Python
john-marinton/Python_automation
/PDF-automate/combined_pdf.py
UTF-8
528
2.75
3
[]
no_license
import PyPDF2 read1=open('meetingminutes1.pdf','rb') read2=open('meetingminutes2.pdf','rb') reader1=PyPDF2.PdfFileReader(read1) reader2=PyPDF2.PdfFileReader(read2) writer=PyPDF2.PdfFileWriter() for file1 in range(reader1.numPages): page=reader1.getPage(file1) writer.addPage(page) for file2 in range(reader2.numPages): page=reader1.getPage(file2) writer.addPage(page) outfile=open('combinedmeetingminutes.pdf','wb') writer.write(outfile) read1.close() read2.close() outfile.close()
true
59268b7f0f8727719c94fe161a47eb7a209b7974
Python
omni360/finite-elements
/poisson/2d/verify.py
UTF-8
2,166
2.90625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#!/usr/bin/env python from scipy.sparse.linalg import spsolve import pylab as plt import numpy as np import FEM, create_mesh, plot_mesh import poisson_optimized as poisson import time def set_bc_nodes_square(pts): """Sets up B.C. nodes in the [-1,1]x[-1,1] square case.""" n_nodes = pts.shape[0] bc_nodes = np.zeros(n_nodes) eps = 1e-6 for k in xrange(n_nodes): x,y = pts[k] if (np.fabs(x - 1) < eps or np.fabs(x - (-1)) < eps or np.fabs(y - 1) < eps or np.fabs(y - (-1)) < eps): bc_nodes[k] = 1 return bc_nodes def f(pts): """zero forcing term""" return np.zeros(pts.shape[0]) def u_exact(pts): """exact solution (and the Dirichlet B.C.)""" try: x = pts[:,0] y = pts[:,1] except: x = pts[0] y = pts[1] return 2.0*(1+y) / ((3+x)**2 + (1+y)**2) errors = [] Ns = np.array([5, 11, 21, 41, 81]) for n in Ns: print "Running with N = %d" % n tic = time.clock() pts,quads,tri = create_mesh.quad_rectangle(-1, 1, -1, 1, n, n) bc_nodes = set_bc_nodes_square(pts) toc = time.clock() print "Mesh generation took %f s" % (toc - tic) f_pts = f(pts) u_bc_pts = u_exact(pts) # Set up the system and solve: tic = time.clock() A,b = poisson.poisson(pts, quads, bc_nodes, f_pts, u_bc_pts, FEM.Q1, FEM.GaussQuad2x2()) toc = time.clock() print "Matrix assembly took %f s" % (toc - tic) tic = time.clock() x = spsolve(A.tocsr(), b) toc = time.clock() print "Sparse solve took %f s\n" % (toc - tic) x_exact = u_exact(pts) errors.append(np.max(np.fabs(x - x_exact))) dxs = 2.0 / np.array(Ns-1) p = np.polyfit(np.log10(dxs), np.log10(errors), 1) plt.hold(True) plt.plot(np.log10(dxs), np.log10(errors), 'o-', color='black') plt.plot(np.log10(dxs), np.polyval(p, np.log10(dxs)), '--', color='green',lw=2) plt.axis('tight') plt.title("Convergence rate: O(dx^%3.3f)" % p[0]) plt.xlabel("dx") plt.ylabel("max error") loc, _ = plt.yticks() plt.yticks(loc, ["10^(%1.1f)" % x for x in loc]) plt.xticks(np.log10(dxs), ["%1.4f" % x for x in dxs]) plt.savefig("poisson-convergence.png")
true
f8ee280c0a037177511782d8392b7f1a0f3d3fd4
Python
vaceslav/cuda
/statistics.py
UTF-8
191
2.859375
3
[]
no_license
#!/usr/bin/env python import pandas as pd df = pd.read_csv("./statistics.txt", sep="|") size = df["total_data_file_size"].sum() / 1024.0 / 1024 / 1024.0 print(f"Total size: {size} GB")
true
85599d56db41e16e0c02898f3423f86f0388343b
Python
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_4_neat/16_0_4_mattiaf_d.py
UTF-8
279
3
3
[]
no_license
def solve(k, c, s): if k == 1: return 1 if c == 1: if s < k: return "IMPOSSIBLE" return ' '.join([str(i) for i in range(1, k+1)]) t = int(input()) for cc in range(t): k, c, s = [int(x) for x in input().split()] print("Case #{}: {}".format(cc+1, solve(k, c, s)))
true
2ce6523c0946a4e0a14a3dc5cfa63b4afdad5dc5
Python
yuwendong/user_portrait
/user_portrait/group/mid2weibolink.py
UTF-8
727
3.046875
3
[]
no_license
# -*- coding: UTF-8 -*- import os ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' def base62_encode(num, alphabet=ALPHABET): if (num == 0): return alphabet[0] arr = [] base = len(alphabet) while num: rem = num % base num = num // base arr.append(alphabet[rem]) arr.reverse() return ''.join(arr) def mid2str(mid): mid = str(mid) s1 = base62_encode(int(mid[:2])) s2 = base62_encode(int(mid[2:9])) try: s3 = base62_encode(int(mid[9:16])) except: s3 = '' return s1+s2+s3 def weiboinfo2url(uid, _mid): mid_str = mid2str(_mid) return 'http://weibo.com/{uid}/{mid}'.format(uid=uid, mid=mid_str)
true
daf4438f42104229bb754f6232ec11f9f27526a2
Python
bshwave/se-challenge
/expenses/tests/unit/expenses/test_helpers.py
UTF-8
1,554
2.796875
3
[]
no_license
from __future__ import absolute_import, unicode_literals from StringIO import StringIO from mock import Mock from nose.tools import assert_raises from expenses.expenses.helpers import ( BadCSVFile, save_csv_file, _make_expense_from_line ) def test_save_csv_file(): mocked_db_session = Mock() file = StringIO(buf=( 'date,category,employee name,employee address,expense description,pre-tax amount,tax name,tax amount\n' + '12/1/2013,Travel,Don Draper,"783 Park Ave, New York, NY 10021",Taxi ride, 350.00 ,NY Sales tax, 31.06 ' )) csv_file = save_csv_file(mocked_db_session, file) assert len(csv_file.expenses) == 1 def test_save_csv_file_invalid(): mocked_db_session = Mock() file = StringIO(buf=('zzzzzz\n123123')) assert_raises(BadCSVFile, save_csv_file, mocked_db_session, file) def test__make_expense_from_line(): line = [ '12/1/2013', 'Travel', 'Don Draper', '783 Park Ave, New York, NY 10021', 'Taxi ride', '350.00', 'NY', 'Sales tax', '31.06' ] # Should just return an Expense instance. No need for assertions here. _make_expense_from_line(line) def test__make_expense_from_line_invalid(): line = [ '12/1/201z', # Note the bad date format here. 'Travel', 'Don Draper', '783 Park Ave, New York, NY 10021', 'Taxi ride', '350.00', 'NY', 'Sales tax', '31.06' ] assert_raises(BadCSVFile, _make_expense_from_line, line)
true
ffd7f9598f63d44fc196c541a5d2f516533b9176
Python
sujal100/IITH-BTECH-Courses
/6th-Sem/CS5500 Reinforcement Learning/RL assignment 2/tictactoe.py
UTF-8
10,133
3
3
[]
no_license
import copy import numpy as np import pickle import sys import tkinter as tk class Player(object): def __init__(self, mark): self.mark = mark def opponent_mark(self): if self.mark == 'X': return 'O' else: return 'X' class HumanPlayer(Player): pass class ComputerPlayer(Player): pass class RandomPlayer(ComputerPlayer): def get_move(self, board): moves = board.available_moves() if moves: return moves[np.random.choice(len(moves))] class SafePlayer(ComputerPlayer): def get_move(self, board): moves = board.available_moves() if moves: for move in moves: next_board = board.get_next_board(move, self.mark) if next_board.winner() == self.mark: return move for move in moves: next_board = board.get_next_board(move, self.opponent_mark()) if next_board.winner() == self.opponent_mark(): return move return moves[np.random.choice(len(moves))] class Board: def __init__(self, grid=np.ones((3,3))*np.nan): self.grid = grid def over(self): return (not np.any(np.isnan(self.grid))) or (self.winner() is not None) def place_mark(self, move, mark): num = Board.mark2num(mark) self.grid[tuple(move)] = num @staticmethod def mark2num(mark): d = {"X": 1, "O": 0} return d[mark] def available_moves(self): return [(i,j) for i in range(3) for j in range(3) if np.isnan(self.grid[i][j])] def get_next_board(self, move, mark): next_board = copy.deepcopy(self) next_board.place_mark(move, mark) return next_board def winner(self): rows = [self.grid[i,:] for i in range(3)] cols = [self.grid[:,j] for j in range(3)] diag = [np.array([self.grid[i,i] for i in range(3)])] cross_diag = [np.array([self.grid[2-i,i] for i in range(3)])] lanes = np.concatenate((rows, cols, diag, cross_diag)) any_lane = lambda x: any([np.array_equal(lane, x) for lane in lanes]) if any_lane(np.ones(3)): return "X" elif any_lane(np.zeros(3)): return "O" def make_key(self, mark): fill_value = 9 filled_grid = copy.deepcopy(self.grid) np.place(filled_grid, np.isnan(filled_grid), fill_value) return "".join(map(str, (list(map(int, filled_grid.flatten()))))) + mark def give_reward(self): if self.over(): if self.winner() is not None: if self.winner() == "X": return 1.0 elif self.winner() == "O": return -1.0 else: return 0.5 else: return 0.0 class Game: def __init__(self, master, player1, player2, Q_learn=None, Q={}, alpha=0.3, gamma=0.9): frame = tk.Frame() frame.grid() self.master = master master.title("Game") self.player1 = player1 self.player2 = player2 self.current_player = player1 self.other_player = player2 self.empty_text = "" self.board = Board() self.buttons = [[None, None, None], [None, None, None], [None, None, None]] for i in range(3): for j in range(3): self.buttons[i][j] = tk.Button(frame, height=3, width=3, text=self.empty_text, command=lambda i=i, j=j: self.callback(self.buttons[i][j])) self.buttons[i][j].grid(row=i, column=j) self.reset_button = tk.Button(text="Play again", command=self.reset) self.reset_button.grid(row=3) self.Q_learn = Q_learn if self.Q_learn: self.Q = Q self.alpha = alpha self.gamma = gamma self.share_Q_with_players() def callback(self, button): if self.board.over(): pass else: if isinstance(self.current_player, HumanPlayer) and isinstance(self.other_player, HumanPlayer): if self.empty(button): move = self.get_move(button) self.handle_move(move) elif isinstance(self.current_player, HumanPlayer) and isinstance(self.other_player, ComputerPlayer): computer_player = self.other_player if self.empty(button): human_move = self.get_move(button) self.handle_move(human_move) if not self.board.over(): computer_move = computer_player.get_move(self.board) self.handle_move(computer_move) def empty(self, button): return button["text"] == self.empty_text def get_move(self, button): info = button.grid_info() move = (int(info["row"]), int(info["column"])) return move def handle_move(self, move): if self.Q_learn: self.learn_Q(move) i, j = move self.buttons[i][j].configure(text=self.current_player.mark) self.board.place_mark(move, self.current_player.mark) if self.board.over(): self.declare_outcome() else: self.switch_players() def declare_outcome(self): if self.board.winner() is None: print("Tie!") else: print(("The player with mark {mark} won!".format(mark=self.current_player.mark))) def reset(self): for i in range(3): for j in range(3): self.buttons[i][j].configure(text=self.empty_text) self.board = Board(grid=np.ones((3,3))*np.nan) self.current_player = self.player1 self.other_player = self.player2 self.act() def switch_players(self): self.current_player, self.other_player = self.other_player, self.current_player def act(self): if isinstance(self.player1, HumanPlayer): pass elif isinstance(self.player1, ComputerPlayer) and isinstance(self.player2, HumanPlayer): first_computer_move = player1.get_move(self.board) self.handle_move(first_computer_move) elif isinstance(self.player1, ComputerPlayer) and isinstance(self.player2, ComputerPlayer): while not self.board.over(): self.play_turn() def play_turn(self): move = self.current_player.get_move(self.board) self.handle_move(move) @property def Q_learn(self): if self._Q_learn is not None: return self._Q_learn if isinstance(self.player1, QPlayer) or isinstance(self.player2, QPlayer): return True @Q_learn.setter def Q_learn(self, _Q_learn): self._Q_learn = _Q_learn def share_Q_with_players(self): if isinstance(self.player1, QPlayer): self.player1.Q = self.Q if isinstance(self.player2, QPlayer): self.player2.Q = self.Q def learn_Q(self, move): state_key = QPlayer.make_and_maybe_add_key(self.board, self.current_player.mark, self.Q) next_board = self.board.get_next_board(move, self.current_player.mark) reward = next_board.give_reward() next_state_key = QPlayer.make_and_maybe_add_key(next_board, self.other_player.mark, self.Q) if next_board.over(): expected = reward else: next_Qs = self.Q[next_state_key] if self.current_player.mark == "X": expected = reward + (self.gamma * min(next_Qs.values())) elif self.current_player.mark == "O": expected = reward + (self.gamma * max(next_Qs.values())) change = self.alpha * (expected - self.Q[state_key][move]) self.Q[state_key][move] += change class QPlayer(ComputerPlayer): def __init__(self, mark, Q={}, epsilon=0.2): super(QPlayer, self).__init__(mark=mark) self.Q = Q self.epsilon = epsilon def get_move(self, board): if np.random.uniform() < self.epsilon: return RandomPlayer.get_move(board) else: state_key = QPlayer.make_and_maybe_add_key(board, self.mark, self.Q) Qs = self.Q[state_key] if self.mark == "X": return QPlayer.stochastic_argminmax(Qs, max) elif self.mark == "O": return QPlayer.stochastic_argminmax(Qs, min) @staticmethod def make_and_maybe_add_key(board, mark, Q): default_Qvalue = 1.0 state_key = board.make_key(mark) if Q.get(state_key) is None: moves = board.available_moves() Q[state_key] = {move: default_Qvalue for move in moves} return state_key @staticmethod def stochastic_argminmax(Qs, min_or_max): min_or_maxQ = min_or_max(list(Qs.values())) if list(Qs.values()).count(min_or_maxQ) > 1: best_options = [move for move in list(Qs.keys()) if Qs[move] == min_or_maxQ] move = best_options[np.random.choice(len(best_options))] else: move = min_or_max(Qs, key=Qs.get) return move if __name__ == "__main__": root = tk.Tk() if sys.argv[1] == "QLearningAgent": Q = pickle.load(open("train_data.p", "rb")) else: Q = {} player1 = HumanPlayer(mark="X") if sys.argv[1] == "SafeAgent": player2 = SafePlayer(mark="O") elif sys.argv[1] == "RandomAgent": player2 = RandomPlayer(mark="O") elif sys.argv[1] == "HumanAgent": player2 = HumanPlayer(mark="O") elif sys.argv[1] == "QLearningAgent": player2 = QPlayer(mark="O", epsilon=0) game = Game(root, player1, player2, Q = Q) game.act() root.mainloop()
true
6fee62ab215d954f3b55571f41e4ef6d5502cec7
Python
kanbaochun/Python
/TensorFlow/tf-3/backword.py
UTF-8
1,745
2.59375
3
[]
no_license
import tensorflow as tf import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" import numpy as np import generateds import forward import matplotlib.pyplot as plt STEPS = 40000 BATCH_SIZE = 30 LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY = 0.999 REGULARIZER = 0.01 def backward(): #训练集占位 x = tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None, 1)) #导入数据集 X, Y_, Y_c = generateds.generateds() y = forward.forward(x, REGULARIZER) #轮数计数器 global_step = tf.Variable(0, trainable=False) #定义指数学习率 learn_rete = tf.train.exponential_decay(LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse = tf.reduce_mean(tf.square(y - y_)) loss_total = loss_mse + tf.add_n(tf.get_collection('losses')) #定义训练方法 train_step = tf.train.AdamOptimizer(learn_rete).minimize(loss_total) #创建会话图进行 with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for i in range(STEPS): start = (i*BATCH_SIZE) % 300 end = start + BATCH_SIZE sess.run(train_step, feed_dict={x:X[start:end], y_:Y_[start:end]}) if i % 2000 == 0: loss_v = sess.run(loss_total, feed_dict={x:X, y_:Y_}) print('After %d steps, loss_total is %f' % (i, loss_v)) #生成网格坐标点 xx, yy = np.mgrid[-3:3:.01, -3:3:.01] grid = np.c_[xx.ravel(), yy.ravel()] probs = sess.run(y, feed_dict={x:grid}) probs = probs.reshape(xx.shape) #可视化训练集 plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c)) plt.contour(xx, yy, probs, levels=[.5]) plt.show() #调用函数运行 if __name__ == '__main__': backward()
true
f7bb3daa125b8991f9d448ae24f721705775d6bc
Python
rhgrant10/ProjectEuler
/problem_015.py
UTF-8
472
3.703125
4
[]
no_license
"""Problem 15 Lattice paths ============= Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. rrdd rdrd rddr drrd drdr ddrr How many such routes are there through a 20×20 grid? """ from math import factorial as fact SIZE = 20 def answer(): return fact(2 * SIZE) // (fact(SIZE) ** 2) if __name__ == '__main__': print(answer())
true
e0f5200406b5640e4e42ed4103614d2b3c9e3a94
Python
mangostory85/MangoServer
/st01.Python기초/py02프로그래밍기초/py11문자열/py11_03.문자열은수정불가.py
UTF-8
313
3.390625
3
[]
no_license
# 문자열은 수정할 수 없다. # 새롭게 메모리가 할당된다는 의미 str1 = "abc" print("str1 주소값 출력", id(str1)) print() str2 = str1 print("str2 주소값 출력", id(str2)) print() str1 = "efg" print("str1 주소값 출력", id(str1)) print("str2 주소값 출력", id(str2)) print()
true
caffec3329bab34101161ce058abb9d46a7db716
Python
bitounu/Nauka-Pythona
/przyklady/przyklady/listing_11-2.py
WINDOWS-1250
458
3.234375
3
[ "Unlicense" ]
permissive
# Listing_11-2.py # Copyright Warren & Carter Sande, 2013 # Released under MIT license http://www.opensource.org/licenses/mit-license.php # Version $version ---------------------------- # Zmienna ptla zagniedona ileLinii = int(raw_input ('W ilu liniach maj by wywietlone gwiazdki? ')) ileGwiazdek = int(raw_input ('Ile gwiazdek w linii? ')) for linia in range(0, ileLinii): for gwiazdka in range(0, ileGwiazdek): print '*', print
true
81d2d1db6268b19b920e9222c1fe90888158899c
Python
theodao/nanodegree-algorithm-datastructures
/Chapter3/problem_algorithm/math_sqrt.py
UTF-8
270
3.34375
3
[]
no_license
def mySqrt(self, x): start = 0 end = x while start <= end: mid = start + (end - start) / 2 if mid * mid <= x and x < (mid + 1) * (mid + 1): return mid if mid * mid > x: end = mid if mid * mid < x: start = mid + 1
true
9a5b9db8171cf4e253ec2a3905783ab9cb44cfc4
Python
jpverkamp/dotfiles
/bin/enumerate
UTF-8
120
2.6875
3
[]
no_license
#!/usr/bin/env python3 import fileinput for i, line in enumerate(fileinput.input(), 1): print(i, line.rstrip('\n'))
true
7700ff929baa6fa8b5642c80f7bb447d86315545
Python
wimbuhTri/Kelas-Python_TRE-2021
/P3/soal3.py
UTF-8
135
3
3
[]
no_license
angka = "123 4567 8982" print(angka[0]) print(angka[-1]) print(angka[4:7]) print(angka) print(angka[:4]) print([angka]) print(angka(0))
true
9eb259481d0003d7b9d9d15e498196ac996413ee
Python
nixonpjoshua/Math127
/Project_1/NJ_test.py
UTF-8
461
3.03125
3
[]
no_license
# Group 6: UPGMA Algorithm using Jukes Cantor Distance # Authors: Josh Nixon # Alex Pearson # Bidit Acharya # Tracy Lou import numpy as np from neighbor_joining import * """ Makes Q matrix that decides what will be joined Args: M: symetric matrix Returns: Q matrix """ a = np.array([[ 0, 5 , 9 , 9, 8], [ 0, 0, 10, 10, 9], [ 0, 0, 0, 8, 7], [ 0, 0, 0, 0, 3], [ 0, 0, 0, 3, 0] ]) print a print make_Q_matrix(a)
true
2e4ae175e408f062f823c93f25983d0cee10f263
Python
HongsenHe/algo2018
/1428_leftmost_column_with_at_least_a_one.py
UTF-8
1,437
3.640625
4
[]
no_license
# """ # This is BinaryMatrix's API interface. # You should not implement it, or speculate about its implementation # """ #class BinaryMatrix(object): # def get(self, row: int, col: int) -> int: # def dimensions(self) -> list[]: class Solution: def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int: rows, cols = binaryMatrix.dimensions() left = 0 right = cols - 1 ''' 上二分法模板。 左右指针分别用列的头和尾。 确定列的中点后,看每一行的数字。 如果中点是1,则舍弃右边部分。因为右边肯定都是1. 最后分别看左右指针的每一行。 ''' while left + 1 < right: mid_col = (left + right) // 2 flag = False for row in range(rows): if binaryMatrix.get(row, mid_col) == 1: flag = True break if flag: right = mid_col else: left = mid_col for row in range(rows): if binaryMatrix.get(row, left) == 1: return left for row in range(rows): if binaryMatrix.get(row, right) == 1: return right return -1
true
034a9cd31370c5a6438b2cd749316c9cf00e8624
Python
koelling/limix
/python/demo/gp_regression_demo.py
UTF-8
2,895
2.59375
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
# Copyright(c) 2014, The LIMIX developers (Christoph Lippert, Paolo Francesco Casale, Oliver Stegle) # All rights reserved. # # LIMIX is provided under a 2-clause BSD license. # See license.txt for the complete license. import sys sys.path.append('./../../build_mac/src/interfaces/python') import limix import scipy as SP import pdb #set random seed SP.random.seed() #genrate toy data (x,y) #dimensions : number of features n_dimensions=1 n_samples = 20 X = SP.rand(n_samples,n_dimensions) #array of X values where we would like to evaluate the prediction #test set Xs = SP.linspace(X.min(),X.max())[:,SP.newaxis] pdb.set_trace() #initialize LIMX objet #1. determine covariance function: # Squared expontential, Gaussian kernel covar = limix.CCovSqexpARD(n_dimensions) #2. likelihood: Gaussian noise ll = limix.CLikNormalIso() #startin parmaeters are set random covar_params = SP.array([1,0.2]) lik_params = SP.array([0.01]) #create hyperparameter object hyperparams0 = limix.CGPHyperParams() #set fields "covar" and "lik" hyperparams0['covar'] = covar_params hyperparams0['lik'] = lik_params #cretae GP object gp=limix.CGPbase(covar,ll) #inputs gp.setX(X) #startgin parameters gp.setParams(hyperparams0) #generate and set outputs y=SP.random.multivariate_normal(SP.zeros(X.shape[0]),(gp.getCovar()).K()+(gp.getLik()).K()) gp.setY(y) #startin parmaeters are set random covar_params = SP.exp(SP.random.randn(covar.getNumberParams())) lik_params = SP.exp(SP.random.randn(ll.getNumberParams())) #starting marginal liklelihood and derivative lml0 = gp.LML() dlml0 = gp.LMLgrad() #set optimization constriats (optional) constrainU = limix.CGPHyperParams() constrainL = limix.CGPHyperParams() constrainU['covar'] = float('inf')*SP.ones_like(covar_params); constrainL['covar'] = SP.zeros_like(covar_params); constrainU['lik'] = float('inf')*SP.ones_like(lik_params); constrainL['lik'] = SP.zeros_like(lik_params); #create optimization object gpopt = limix.CGPopt(gp) #set constrants gpopt.setOptBoundLower(constrainL); gpopt.setOptBoundUpper(constrainU); #run gpopt.opt() #get optimal parameters and LML hyperparams_opt = gp.getParams() lml_opt = gp.LML() #prediction Xmean = gp.predictMean(Xs) Xstd = gp.predictVar(Xs) #print out stuff print "initial hyperparams" #print hyperparams0 print "initial marginal likelihood" print -lml0 print hyperparams0['covar'] print hyperparams0['lik'] print "optimized hyperparams" #print hyperparams_opt print hyperparams_opt['covar'] print hyperparams_opt['lik'] print "error estimated through laplace approximation" stdL=gp.getStd_laplace() print stdL['covar'] print stdL['lik'] print "optimized marginal likelihood" print -lml_opt print "gradients of optimization at optimum" print gp.LMLgrad() #plottin import pylab as PL PL.ion() PL.figure() PL.plot(X,y,'b.') PL.plot(Xs,Xmean) PL.plot(Xs,Xmean+SP.sqrt(Xstd)) PL.plot(Xs,Xmean-SP.sqrt(Xstd)) PL.show() pdb.set_trace()
true
4bb251b12f3c19292e966a0dcdd4a339be7e903f
Python
egushinnosuke/collatz-py
/collatz.py
UTF-8
535
4.15625
4
[]
no_license
# coding:utf-8 def collatz(number): if number % 2 == 0: #偶数の場合 return number / 2 else: #奇数の場合 return 3 * number + 1 print('整数を入力してください') input_number = input() while True: try: input_number = int(input_number) if input_number == 1: break else: input_number = collatz(input_number) print(input_number) except ValueError: print('整数以外の数字が記入されました。整数を記入してください') input_number = input()
true
ba57bfc163deae6345540f976612f5ac8fc5e432
Python
Nepherius/Mangopie
/core/aochat/extended_message.py
UTF-8
309
2.5625
3
[]
no_license
class ExtendedMessage: def __init__(self, category_id, instance_id, template, params): self.category_id = category_id self.instance_id = instance_id self.template = template self.params = params def get_message(self): return self.template % tuple(self.params)
true
0a11586a127f173bbb5eb22783695e5452c09872
Python
i026e/python_ecg_graph
/tests/test_parameters.py
UTF-8
10,159
2.90625
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Thu Mar 24 09:50:30 2016 @author: pavel """ import sys sys.path.insert(0, '../') import parameter_types import unittest class TestParameterManager(unittest.TestCase): def test_pm(self): pm = parameter_types.ParameterManager() param1 = parameter_types.Parameter("1", "abc", str) param2 = parameter_types.ListParameter("2", "a", str, ["a", "b", "c"]) param3 = parameter_types.ListParameter("3", 2, int, [1, 2, 3]) param4 = parameter_types.RangeParameter("4", 2, int, 0, 10) param5 = parameter_types.RangeParameterFit("5", 7.3, float, 0.1, 9.9) parameters = [param1, param2, param3, param4, param5] for param in parameters: pm.add_param(param.get_name(), param) self.assertEqual(pm.num_params(), len(parameters)) for p_name in pm.param_names(): param = pm.get_param(p_name) self.assertTrue(param in parameters) for param in parameters: p = pm.get_param(param.get_name()) self.assertEqual(p, param) # override first parameter param6 = parameter_types.Parameter(param1.get_name(), "ddd", str) pm.add_param(param1.get_name(), param6) self.assertEqual(pm.num_params(), len(parameters)) self.assertNotEqual(param1, pm.get_param(param1.get_name())) self.assertEqual(param6, pm.get_param(param6.get_name())) class TestParameter(unittest.TestCase): def test_str(self): param = parameter_types.Parameter('string', 'abc', str) self.assertEqual(param.get_name(), 'string') self.assertEqual(param.get_val(), 'abc') res, val = param._convert_val_type(12345) self.assertTrue(res) self.assertEqual(val, '12345') self.assertTrue(param.set_val('DeF')) self.assertEqual(param.get_val(), 'DeF') self.assertTrue(param.set_val(None)) self.assertEqual(param.get_val(), 'None') self.assertTrue(param.set_val(123)) self.assertEqual(param.get_val(), '123') self.assertTrue(param.set_val(0.2)) self.assertEqual(param.get_val(), '0.2') def test_int(self): param = parameter_types.Parameter('sillyName', 1, int) self.assertEqual(param.get_name(), 'sillyName') self.assertEqual(param.get_val(), 1) self.assertTrue(param.set_val(0.2)) self.assertEqual(param.get_val(), 0) self.assertTrue(param.set_val(-5)) self.assertEqual(param.get_val(), -5) self.assertTrue(param.set_val("123")) self.assertEqual(param.get_val(), 123) self.assertTrue(param.set_val("-321")) self.assertEqual(param.get_val(), -321) self.assertTrue(param.set_val("00012")) self.assertEqual(param.get_val(), 12) self.assertFalse(param.set_val("aaa00")) self.assertEqual(param.get_val(), 12) self.assertFalse(param.set_val("0.2")) self.assertEqual(param.get_val(), 12) def test_float(self): param = parameter_types.Parameter('', 1, float) self.assertEqual(param.get_val(), 1.0) self.assertTrue(param.set_val(0.2)) self.assertEqual(param.get_val(), 0.2) self.assertTrue(param.set_val("00012")) self.assertEqual(param.get_val(), 12) self.assertFalse(param.set_val("aaa00")) self.assertEqual(param.get_val(), 12) self.assertTrue(param.set_val("0.8")) self.assertEqual(param.get_val(), 0.8) def test_wrong_init_type(self): #current behavior -- initial value is not checked param = parameter_types.Parameter('', "abc", int) self.assertEqual(param.get_val(), "abc") self.assertTrue(param.set_val(123)) self.assertEqual(param.get_val(), 123) self.assertFalse(param.set_val("abc")) self.assertEqual(param.get_val(), 123) class TestListParameter(unittest.TestCase): def test_str(self): vals = ["a", "b", "cde", "d", "1", "2", "4.2"] param = parameter_types.ListParameter('name', "a", str, vals) self.assertEqual(param.get_val(), "a") for val in vals: self.assertTrue(val in param.allowed_vals()) for val in param.allowed_vals(): self.assertTrue(val in vals) self.assertTrue(param.set_val("b")) self.assertEqual(param.get_val(), "b") self.assertTrue(param.set_val(4.2)) self.assertEqual(param.get_val(), "4.2") self.assertTrue(param.set_val("cde")) self.assertEqual(param.get_val(), "cde") self.assertFalse(param.set_val("abc")) self.assertEqual(param.get_val(), "cde") self.assertFalse(param.set_val(123)) self.assertEqual(param.get_val(), "cde") def test_int(self): vals = [0, 1, 7, 99] param = parameter_types.ListParameter('name', 7, int, vals) self.assertEqual(param.get_val(), 7) self.assertTrue(param.set_val(0)) self.assertEqual(param.get_val(), 0) self.assertTrue(param.set_val("99")) self.assertEqual(param.get_val(), 99) self.assertFalse(param.set_val(123)) self.assertEqual(param.get_val(), 99) self.assertFalse(param.set_val("a")) self.assertEqual(param.get_val(), 99) class TestRangeParameter(unittest.TestCase): def test_chr(self): min_val = "c" max_val = "k" param = parameter_types.RangeParameter("", "d", str, min_val, max_val) self.assertEqual(param.get_val(), "d") self.assertTrue(param.set_val("h")) self.assertEqual(param.get_val(), "h") self.assertTrue(param.set_val("c")) self.assertEqual(param.get_val(), "c") self.assertFalse(param.set_val("a")) self.assertEqual(param.get_val(), "c") self.assertFalse(param.set_val("x")) self.assertEqual(param.get_val(), "c") self.assertFalse(param.set_val("D")) self.assertEqual(param.get_val(), "c") self.assertFalse(param.set_val("!")) self.assertEqual(param.get_val(), "c") self.assertTrue(param.set_val("d")) self.assertEqual(param.get_val(), "d") def test_str(self): min_val = "abc" max_val = "xyz" param = parameter_types.RangeParameter("", "eee", str, min_val, max_val) self.assertEqual(param.get_val(), "eee") self.assertTrue(param.set_val("uvwxyz")) self.assertEqual(param.get_val(), "uvwxyz") self.assertTrue(param.set_val("abcdefg")) self.assertEqual(param.get_val(), "abcdefg") self.assertTrue(param.set_val("abc")) self.assertEqual(param.get_val(), "abc") self.assertFalse(param.set_val("a")) self.assertEqual(param.get_val(), "abc") self.assertFalse(param.set_val("aaaaaaa")) self.assertEqual(param.get_val(), "abc") self.assertFalse(param.set_val("DAC")) self.assertEqual(param.get_val(), "abc") self.assertFalse(param.set_val("1")) self.assertEqual(param.get_val(), "abc") self.assertFalse(param.set_val(1)) self.assertEqual(param.get_val(), "abc") self.assertFalse(param.set_val("zzz")) self.assertEqual(param.get_val(), "abc") self.assertTrue(param.set_val("xyz")) self.assertEqual(param.get_val(), "xyz") self.assertTrue(param.set_val("bCD123!!!")) self.assertEqual(param.get_val(), "bCD123!!!") def test_int(self): min_val = -500 max_val = 999 param = parameter_types.RangeParameter("", 1, int, min_val, max_val) self.assertTrue(param.set_val(-499)) self.assertEqual(param.get_val(), -499) self.assertTrue(param.set_val(999)) self.assertEqual(param.get_val(), 999) self.assertFalse(param.set_val(1000)) self.assertEqual(param.get_val(), 999) self.assertFalse(param.set_val(-501)) self.assertEqual(param.get_val(), 999) self.assertTrue(param.set_val(-500)) self.assertEqual(param.get_val(), -500) class TestRangeParameterFit(unittest.TestCase): def test_str(self): min_val = "abc" max_val = "xyz" param = parameter_types.RangeParameterFit("", "d", str, min_val, max_val) self.assertTrue(param.set_val("aaa")) self.assertEqual(param.get_val(), min_val) self.assertTrue(param.set_val("bcfex")) self.assertEqual(param.get_val(), "bcfex") self.assertTrue(param.set_val("123")) self.assertEqual(param.get_val(), min_val) self.assertTrue(param.set_val("ZZZ")) self.assertEqual(param.get_val(), min_val) self.assertTrue(param.set_val("zzz")) self.assertEqual(param.get_val(), max_val) def test_int(self): min_val = 111 max_val = 999 param = parameter_types.RangeParameterFit("", 555, int, min_val, max_val) self.assertTrue(param.set_val(-100)) self.assertEqual(param.get_val(), min_val) self.assertTrue(param.set_val(9999)) self.assertEqual(param.get_val(), max_val) self.assertTrue(param.set_val(777)) self.assertEqual(param.get_val(), 777) self.assertFalse(param.set_val("aaa")) self.assertEqual(param.get_val(), 777) if __name__ == "__main__": unittest.main()
true
da803b958a4395bfde84bfa0414221455797a472
Python
ramanmishra/Code-Chef-Solutions
/Beginner/Tanu_And_Head_Bob.py
UTF-8
211
3.359375
3
[]
no_license
t = int(input()) for i in range(t): length = input() n = input() if 'I' in n: print("INDIAN") elif n.count('N') == len(n): print("NOT SURE") else: print("NOT INDIAN")
true
f6008a41a4753d49f6de16d17b32cc854d93e151
Python
ZJgithubZJ/Python
/monitor/监控报警/mail_accessory.py
UTF-8
1,316
2.71875
3
[]
no_license
#!/usr/bin/env python3 #!-*- encoding=utf-8 -*- #Auther:ZJ import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header class Sendmail: def __init__(self): self.sender = 'zhangjian@xnhd.com' self.receiver = 'zhangjian@xnhd.com' #创建实例 self.message = MIMEMultipart() self.message['From'] = Header('Proxy_mail','utf-8') self.message['To'] = Header('ZJ','utf-8') self.message['Subject'] = Header('Python Test','utf-8') #邮件正文 self.message.attach(MIMEText('Python 报警邮件测试,详情见附件','plain','utf-8')) #构造附件file1 file1 = MIMEText(open('DERIV_CD.txt','r').read(),'base64','utf-8') file1['Content-Type'] = 'application/octet-stream' #filename为邮件中显示的名字,不必与真实文件名相同 file1['Content-Disposition'] = 'attachment; filename = "file1.txt"' self.message.attach(file1) #构造附件att2,规则同上 def sendmail(self): try: server = smtplib.SMTP_SSL('smtp.exmail.qq.com',465) server.login('zhangjian@xnhd.com','mail passwd') server.sendmail(self.sender,self.receiver,self.message.as_string()) print('Mail send succeed!') server.quit() except Exception as e: print('Mail send failed', e) if __name__ == '__main__': test = Sendmail() test.sendmail()
true
ff7bec80ee1800b4b366e78134dbb67b3fe2b0aa
Python
tnferreira/PID_Car
/.ipynb_checkpoints/test-checkpoint.py
UTF-8
598
2.890625
3
[]
no_license
from datetime import datetime from matplotlib import pyplot from matplotlib.animation import FuncAnimation from random import randrange import time x_data, y_data = [], [] pyplot.ion() figure = pyplot.figure() line, = pyplot.plot_date(x_data, y_data, '-') def update(frame): x_data.append(datetime.now()) y_data.append(randrange(0, 100)) line.set_data(x_data, y_data) figure.gca().relim() figure.gca().autoscale_view() time.sleep(.25) # keep refresh rate of 0.25 seconds return line, animation = FuncAnimation(figure, update, interval=200, blit=True) pyplot.show()
true
fcdb9b060f938ddb6d3336e9eca8d3d9760d5b51
Python
nextdesusu/Learn-Python
/py_files/noizes/noizes.py
UTF-8
952
3.265625
3
[]
no_license
import random import math mapsize = 5 def print_chart(*src): print(src) def noise(freq): phase = random.uniform(0, 2*math.pi) return [math.sin(2*math.pi * freq*x/mapsize + phase) for x in range(mapsize)] def weighted_sum(amplitudes, noises): output = [0.0] * mapsize # make an array of length mapsize for k in range(len(noises)): for x in range(mapsize): output[x] += amplitudes[k] * noises[k][x] return output amplitudes = [0.2, 0.5, 1.0, 0.7, 0.5, 0.4] frequencies = [1, 2, 4, 8, 16, 32] frequencies = range(1, 31) # [1, 2, ..., 30] def random_ift(rows, amplitude): for i in range(rows): random.seed(i) amplitudes = [amplitude(f) for f in frequencies] noises = [noise(f) for f in frequencies] sum_of_noises = weighted_sum(amplitudes, noises) print_chart(i, sum_of_noises) random_ift(10, lambda f: 1)
true
89c02f0be58f787caaf2d693b0ccfdcbd5f168ef
Python
SwimmingLee/ProblemSolving
/(Pyton)ProblemSolving/ProblemSovling/그래프/다익스트라/[BOJ_20183]골목 대장 호석 - 효율성2.py
UTF-8
1,070
2.546875
3
[]
no_license
import sys import heapq r = open("/mnt/c/Users/swimm/Desktop/test/large_16.in", mode='rt') input = r.readline N, M, start_city, end_city, wallet = list(map(int, input().split())) edges = [[] for _ in range(N+1)] for _ in range(M): u, v, c = list(map(int, input().split())) edges[u].append([v, c]) edges[v].append([u, c]) vistied = [False] * (N+1) inf = 987987987 answer = inf visited = [False] * (N+1) dist = [inf] * (N+1) pq = [] heapq.heappush(pq, [0, 0, start_city]) dist[start_city] = 0 while pq: total_cost, max_collection, city = heapq.heappop(pq) if total_cost > wallet: break if city == end_city and answer > max_collection: answer = max_collection for edge in edges[city]: next_city, cost = edge if total_cost + cost > wallet: continue if cost > max_collection: heapq.heappush(pq, [total_cost + cost, cost, next_city]) else: heapq.heappush(pq, [total_cost + cost, max_collection, next_city]) if answer == inf: answer = -1 print(answer)
true
764677d3356fa854e876ed56c56ccd69c9ebe278
Python
pritysonisingh/Tic-Tac-Toe
/Tic Tac Toe.py
UTF-8
3,945
4.46875
4
[]
no_license
# TIC TAC TOE import random # Function to display the tic tac toe board def display_board(board): print(' | |') print(board[7]+' | '+board[8]+' | '+board[9]) print(' | |') print('---------------') print(' | |') print(board[4]+' | '+board[5]+' | '+board[6]) print(' | |') print('--------------') print(' | |') print(board[1]+' | '+board[2]+' | '+board[3]) print(' | |') # Function to allow player 1 to choose his sign and gives player 2 the other sign def player_input(): sign ='' while sign!='X' and sign!='O': sign = input('Player1 Please enter X or O').upper() if sign=='X': return ('X','O') else: return ('O','X') # Function to place the sign in entered position def place(board,sign,position): board[position] = sign # Function to define all the winning conditions def win(board,sign): return((board[1] == sign and board[2] == sign and board[3] == sign) or (board[4] == sign and board[5] == sign and board[6] == sign) or (board[7] == sign and board[8] == sign and board[9] == sign) or (board[1] == sign and board[4] == sign and board[7] == sign) or (board[2] == sign and board[5] == sign and board[8] == sign) or (board[3] == sign and board[6] == sign and board[9] == sign) or (board[1] == sign and board[5] == sign and board[9] == sign) or (board[3] == sign and board[5] == sign and board[7] == sign)) # Function to randomly select which player will start with the Game def start(): flip = random.randint(0,1) if flip == 0: return 'Player 1' else: return 'Player 2' # Function to check if there is any space left on the board def space_check(board,position): return (board[position] == ' ') # Function to check if the board is full def full_board_check(board): for i in range(1,10): if space_check(board,i): return False return True # Function to take the positions from users def player_choice(board): position = 0 while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board,position): position = int(input('Choose a position: (1-9)')) return position # Function to allow users to replay the Game def replay(): choice= input("PLAY AGAIN? Enter Yes or No").upper() return choice == 'YES' # Game logic print("Welcome to Tic Tac Toe.!") while True: board = [' ']*10 player1_sign , player2_sign = player_input() turn = start() print(turn + ' will go first') play_game = input('Ready to play? Y or N').upper() if play_game == 'Y': game_on = True else: game_on = False while game_on: # For Player 1 if turn == 'Player 1': display_board(board) print('Player 1:') position = player_choice(board) place(board,player1_sign,position) if win(board,player1_sign): display_board(board) print('PLAYER 1 HAS WON') game_on=False else: if full_board_check(board): display_board(board) print("TIE GAME!") game_on = False else: turn = 'Player 2' else: # For Player 2 display_board(board) print('Player 2:') position = player_choice(board) place(board,player2_sign,position) if win(board,player2_sign): display_board(board) print('PLAYER 2 HAS WON!!') game_on=False else: if full_board_check(board): display_board(board) print("TIE GAME!") game_on = False else: turn = 'Player 1' if not replay(): break
true
c05874d2b8251416daf568da28f49a8c9007da08
Python
rajatg98/ChatVIT
/code/code_timetable_data.py
UTF-8
5,369
2.921875
3
[]
no_license
# Weekday abbreviations WEEK=["MON","TUE","WED","THU","FRI","SAT","SUN"] from dataload_init import * import csv import datetime from collections import defaultdict as dd abbr={ "nlp":"Natural Language Processing", "biodb":"Biological Database","bio":"Biological Database","biology":"Biological Database", "mmdd":"Molecular Modelling and Drug Design","drug":"Molecular Modelling and Drug Design", "ai":"Artificial Intelligence","artificial":"Artificial Intelligence", "cybersec":"Cyber Security","cyber":"Cyber Security", "tarp":"Technical Answers for Real World Problems (TARP)", "eco":"International Economics","economics":"International Economics","intl":"International Economics" } # next class for the day def NextClass(W,H): for h in range(H+1,23): #print(h) p=CurClass(W,h,1) if p[1]==1: return(p[0]) return("-1") #current class def CurClass(W,H,f=0): #D[1]=int(D[1]) D=[W,H] if tuple(D) in RS: dslot=RS[tuple(D)] if dslot in RealTT: p=RealTT[dslot] return((p,1)) if f==0: return((NextClass(W,H),0)) else: return(("-1",0)) #previous class def PreClass(W,H): for h in range(H-1,7,-1): #print(h) p=CurClass(W,h,1) if p[1]==1: return(p[0]) return("-1") #count of today's classes def ClassCountToday(W,H): complete=0 left=0 for h in range(8,H): p=CurClass(W,h,1) if p[1]==1: complete+=1 for h in range(H,21): p=CurClass(W,h,1) if p[1]==1: left+=1 return([complete,left]) #today time table def TodayTT(W): R=[] for h in range(8,21): p=CurClass(W,h,1) if p[1]==1: R.append((h,p[0])) return(R) #time table def weekTT(W): te = TodayTT(W) #print(" ",W) temp32=" %s\n"%W for x in te: p = MClass[x[1]] temp32+=" %d:00 - %d:50 : %s at %s\n"%(x[0],x[0],p.coursename,p.venue) temp32=temp32[:-1] return(temp32) #query process def Query(sel,WeekDay,Hour,Minute): temp32="---> > Error in Query < <---\n" if sel==1: #You don't have any current class\nBut your next class is %s te=CurClass(WeekDay,Hour) if te[1] ==0: if te[0]=="-1": temp32="You are done for today! No more Classes! Relax." else: p=MClass[te[0]] temp32="You don't have any current class\nBut your next class is %s- %s at %s"%(p.coursecode,p.coursename,p.venue) else: p=MClass[te[0]] temp32="Your current class is %s- %s at %s"%(p.coursecode,p.coursename,p.venue) elif sel==2: te=NextClass(WeekDay,Hour) if te=="-1": temp32="You have no next class! No more Classes! Relax." else: p=MClass[te] temp32="your next class is %s- %s at %s"%(p.coursecode,p.coursename,p.venue) elif sel==3: te=PreClass(WeekDay,Hour) if te=="-1": temp32="You had no previous class!" else: p=MClass[te] temp32="your previous class was %s- %s at %s"%(p.coursecode,p.coursename,p.venue) elif sel==4 or sel==5: te=ClassCountToday(WeekDay,Hour) temp32="Number of Completed Class : %d\n Number of Upcoming Class : %d"%(te[0],te[1]) elif sel==6: te = TodayTT(WeekDay) temp32=" %s\n"%WeekDay for x in te: p = MClass[x[1]] temp32+=" %d:00 - %d:50 : %s at %s\n"%(x[0],x[0],p.coursename,p.venue) temp32=temp32[:-1] elif sel==7: W=(WEEK)[(WEEK.index(WeekDay)+1)%7] te = TodayTT(W) temp32=" %s\n"%W for x in te: p = MClass[x[1]] temp32+=" %d:00 - %d:50 : %s at %s\n"%(x[0],x[0],p.coursename,p.venue) temp32=temp32[:-1] elif sel==9: W=(WEEK)[(WEEK.index(WeekDay)-1)%7] te = TodayTT(W) if W=="SUN" or W=="SAT": return("It was %s, So there were no classes!\n"%W) temp32=" %s\n"%W for x in te: p = MClass[x[1]] temp32+=" %d:00 - %d:50 : %s at %s\n"%(x[0],x[0],p.coursename,p.venue) temp32=temp32[:-1] elif sel==8: query=Minute.split(" ") query=[i.lower() for i in query] f="X" for s in query: if s in abbr: f=abbr[s] break if f=="X": return("No such course exists!") else: for cc in MClass: if cc.coursename == f: return("The faculty for %s is %s"%(f,cc.facultyname)) elif sel==10 or sel==15: return(weekTT("MON")) elif sel==11 or sel==16: return(weekTT("TUE")) elif sel==12 or sel==17: return(weekTT("WED")) elif sel==13 or sel==18: return(weekTT("THU")) elif sel==14 or sel==19: return(weekTT("FRI")) return(temp32) print("Data Processing Completed. . .")
true
39fb6bc60f0a6d7b7e2252688bec6e894640a7e2
Python
codeAligned/codingChallenges
/codewars/cipher.py
UTF-8
589
3.5625
4
[]
no_license
# Source: http://www.codewars.com/kata/546937989c0b6ab3c5000183/train/python def encryptor(key, message): def shift(c, key): if c == c.upper(): return ((ord(c) + key - ord('A')) % 26) + ord('A') elif c == c.lower(): return ((ord(c) + key - ord('a')) % 26) + ord('a') result = '' for char in message: if char.isalpha(): result+=chr(shift(char, key)) else: result+=char return result #print(encryptor(13, '')) #print(encryptor(13, 'Caesar Cipher')) print(encryptor(-5, 'Hello World!')) #print(encryptor(27, 'Whoopi Goldberg'))
true
d63a3d8235069d2b6d528dbb2e5807082462aa80
Python
darcatron/BottersOfTheGalaxy
/src/main.py
UTF-8
22,936
2.75
3
[]
no_license
import random import sys import math import copy ### CONSTANTS INSULTS = ["come at me", "who's your daddy", "is this LoL", "cash me outside", "2 + 2 don't know what it is!", "yawn", "dis some disrespect"] # TODO: use this at the end (not sure how we know when the end is....maybe when tower or hero is at a low health?) FINAL_INSULT = "2 ez. gg. no re" UNUSED_HEROES = ["DEADPOOL", "IRONMAN", "HULK", "VALKYRIE", "DOCTOR_STRANGE"] CHOSEN_ALIVE_HEROES = [] ENTITY_TYPE_MINION = "UNIT" ENTITY_TYPE_HERO = "HERO" ENTITY_TYPE_TOWER = "TOWER" ENTITY_TYPE_GROOT = "GROOT" ACTION_WAIT = "WAIT" ACTION_MOVE = "MOVE" ACTION_ATTACK = "ATTACK" ACTION_ATTACK_NEAREST = "ATTACK_NEAREST" ACTION_MOVE_ATTACK = "MOVE_ATTACK" ACTION_BUY = "BUY" ACTION_SELL = "SELL" ### Globals curInsult = "" myTeam = 0 allEntities = [] myGold = 0 def play(): global myTeam, allEntities, myGold myTeam = int(raw_input()) unused() itemCount = int(raw_input()) # useful from wood2 readInItems(itemCount) curTurn = 1 # game loops while True: debug("curTurn " + `curTurn`) myGold = int(raw_input()) enemyGold = int(raw_input()) roundType = int(raw_input()) # If roundType has a negative value then you need to output a Hero name, such as "DEADPOOL" or "VALKYRIE". if roundType < 0: chooseHero() # Else you need to output roundType number of any valid action, such as "WAIT" or "ATTACK unitId" entityCount = int(raw_input()) readInEntities(entityCount) # a positive value will show the number of heroes that await a command if roundType > 0: updateMyHeroes() for heroIndex in xrange(roundType): curHero = getHeroByType(myTeam, CHOSEN_ALIVE_HEROES[heroIndex]) executeTurn(curTurn, curHero) curTurn += 1 def updateMyHeroes(): myAliveHeroes = getHeroes(myTeam) for heroType in CHOSEN_ALIVE_HEROES: if not containsHeroOfType(myAliveHeroes, heroType): CHOSEN_ALIVE_HEROES.remove(heroType) def containsHeroOfType(heroes, heroType): for h in heroes: if h.heroType == heroType: return True return False def executeTurn(curTurn, myHero): possibleItem = getPossibleItemToBuy(myHero) # TODO: once the item purchase is improved, this will run much better if isBehindMinion(myHero) and possibleItem: ## ## SD - shouldn't this check if we are behind the average minions? Not just that we are behind a single minion? # buy item IFF behind minion shield (for now at least) buyItem(myHero, possibleItem, curTurn) else: attackAndOrMove(myHero, curTurn) def isBehindMinion(hero): minionFurthestAhead = findMinionFurthestAhead(hero.team) if minionFurthestAhead is None: return False if hero.team == 0: return hero.posX <= minionFurthestAhead.posX elif hero.team == 1: return hero.posX >= minionFurthestAhead.posX else: raise ValueError("Whose team are you on bro?!") def getPossibleItemToBuy(myHero): # TODO: improve our item selection #if health is below 50%, buy the biggest health potion (should be the 500 health one) if myHero.health < (myHero.maxHealth / 2.0): potions = getPotions() potions.sort(key=lambda potion: potion.health, reverse=True) for potion in potions: if myGold >= potion.itemCost: return potion # leave space for potion if myHero.itemsOwned == 3: return None return getMostAffordableDamageOrMoveItem(myGold) # Use to buy an item with damage being priority and moveSpeed taking second, this will return an itemName # or None if neither are affordable def getMostAffordableDamageOrMoveItem(gold): damageItems = [i for i in allItems if "blade" in i.itemName.lower()] moveSpeedItems = [i for i in allItems if "boots" in i.itemName.lower()] bestItem = None # Check for affordable items that raise damage first for item in damageItems: if (bestItem is None or item.damage > bestItem.damage) and item.itemCost <= gold: bestItem = item #TODO: I didn't use this cause it was a fall back, improving item selection will make this better # We should wait for money and buy the better items later game (maybe make the choice based on turn?) # If no affordable items that raise damage then check for items that raise moveSpeed # if bestItem is None: # for item in moveSpeedItems: # if (bestItem is None or item.moveSpeed > bestItem.moveSpeed) and item.itemCost <= gold: # bestItem = item return bestItem def getPotions(): return [item for item in allItems if item.isPotion] def buyItem(myHero, item, curTurn): global myGold myHero.itemsOwned += 1 myGold -= item.itemCost printAction(ACTION_BUY + " " + item.itemName, curTurn) def attackAndOrMove(myHero, curTurn): avgMinionXPos = getAverageMinionDistance(myTeam) minionFurthestAhead = findMinionFurthestAhead(myTeam) if minionFurthestAhead is not None: enemyTower = getTower(getOtherTeam(myTeam)) desiredPosX = getFarthestXOutsideRange(enemyTower, avgMinionXPos) desiredPosY = minionFurthestAhead.posY enemyEntityToAttack = getEntityToAttack(myHero, desiredPosX, desiredPosY) if enemyEntityToAttack is not None: removeEntityIfKilled(enemyEntityToAttack, myHero) printMoveAttack(desiredPosX, desiredPosY, enemyEntityToAttack.unitId, curTurn) else: # Hide behind our minions printAction(ACTION_MOVE + " " + str(desiredPosX) + " " + str(desiredPosY), curTurn) else: # We don't have a shield minion so we should move towards our tower myTower = getTower(myTeam) printAction(ACTION_MOVE + " " + str(myTower.posX) + " " + str(myTower.posY), curTurn) def getAverageMinionDistance(team): myTeamMinions = getMinions(team) totalMinionDistance = 0 bufferXDistance = 75 # semi-arbitrarily chosen. played around with a few values here for minion in myTeamMinions: totalMinionDistance += minion.posX if len(myTeamMinions) > 1: avgXPos = totalMinionDistance / len(myTeamMinions) else: ## SD - couldn't this return a negative number if we don't have any minions or if the last minion is at an xPos < 75? avgXPos = totalMinionDistance - (bufferXDistance * getDirectionMultiplier(myTeam)) return avgXPos # Will return None if no last hits are available def getBestPossibleLastHit(team, attackingHero, attackFromX, attackFromY): myDmg = attackingHero.attackDamage dmgThreshold = myDmg * 0.30 # TODO: temp fix for giving Hero time to get to target. If we aren't moving closer to the target this shouldn't be needed enemyMinionsToKill = [] movedHero = copy.deepcopy(attackingHero) ## write a better func than this movedHero.posX = attackFromX movedHero.posY = attackFromY for enemyMinion in getMinions(team): if enemyMinion.isInRangeOf(movedHero) and enemyMinion.health <= myDmg + dmgThreshold and \ not getTower(team).canAttack(enemyMinion.posX, enemyMinion.posY): enemyMinionsToKill.append(enemyMinion) return findClosestEntity(enemyMinionsToKill, movedHero.posX, movedHero.posY) #TODO: this was an old strategy for getting best last hit. It's worth trying it out again once the Hero 2 input is accounted for # return min(enemyMinionsToKill, key=lambda minion: minion.health) if len(enemyMinionsToKill) > 0 else None # Takes an entity and an X value, returns the X value closest to the desired X while staying just outside the given entity's attack range # Will return desired X or entity's X +/- attackRange depending on team of entity def getFarthestXOutsideRange(entity, desiredX): if entity.team == 0: return max(entity.posX + (getDirectionMultiplier(entity.team) * entity.attackRange + 1), desiredX) else: return min(entity.posX + (getDirectionMultiplier(entity.team) * entity.attackRange + 1), desiredX) # Determines which enemy entity to attack for a given turn # Takes in the hero that is attacking, as well as the (X,Y) coordinate he will attack from def getEntityToAttack(attackingHero, attackFromX, attackFromY): # Try to attack an enemy that will die with one hit so we get gold entityToFinishOff = getBestPossibleLastHit(getOtherTeam(myTeam), attackingHero, attackFromX, attackFromY) if entityToFinishOff: return entityToFinishOff # Try to last hit our own allies to prevent creep kills entityToFinishOff = getBestPossibleLastHit(myTeam, attackingHero, attackFromX, attackFromY) if entityToFinishOff: return entityToFinishOff # Try to attack an enemy hero if we deem it worthwhile heroToAttack = getHeroToAttack(attackingHero, attackFromX, attackFromY) if heroToAttack: return heroToAttack ## Find the closest defending minion to the spot we will attack from! defendingTeam = getOtherTeam(attackingHero.team) defendingMinions = getMinions(defendingTeam) return findClosestEntity(defendingMinions, attackFromX, attackFromY) # Runs logic to try to attach an enemy hero. Returns the hero to attack, or None if we shouldn't # attack any enemy heroes def getHeroToAttack(attackingHero, attackFromX, attackFromY): MIN_MINION_ARMY_DIFF_TO_ATTACK_HERO = 1 # We need to have this many more minions than the enemy to attack their hero attackingTeam = attackingHero.team defendingTeam = getOtherTeam(attackingTeam) defendingMinions = getMinions(defendingTeam) ## If we aren't in range of their tower, our minion army overpowers their minion army, and they have a hero in range, attack the hero! if not getTower(defendingTeam).canAttack(attackFromX, attackFromY): defendingHero = getHero(defendingTeam) if defendingHero is not None and len(getMinions(attackingTeam)) - len(defendingMinions) > MIN_MINION_ARMY_DIFF_TO_ATTACK_HERO and defendingHero.isInRangeOf(attackingHero): return defendingHero # We don't want to attack a hero return None def removeEntityIfKilled(enemyEntityToAttack, myHero): if enemyEntityToAttack.health <= myHero.attackDamage: allEntities.remove([e for e in allEntities if e.unitId == enemyEntityToAttack.unitId][0]) ## Use to decide whether to add or subtract for the X direction def getDirectionMultiplier(team): return 1 if team == 0 else -1 ## Returns true if entity 1 is closer to the given team's tower than entity 2 is ## NOTE this is the X direction ONLY for now def isCloserToTower(entity1, entity2, team): tower = getTower(team) entity1Distance = abs(getDistanceBetweenPoints(x1=tower.posX, x2=entity1.posX)) entity2Distance = abs(getDistanceBetweenPoints(x1=tower.posX, x2=entity2.posX)) return entity1Distance < entity2Distance ## Finds the entity farthest from the given coordinates. def findFarthestEntity(entities, x=None, y=None): maxDist = None farthestEntity = None for e in entities: dist = getDistanceBetweenPoints(e.posX, e.posY, x, y) if maxDist is None or dist > maxDist: farthestEntity = e maxDist = dist return farthestEntity ## Finds the entity closest to the given coordinates def findClosestEntity(entities, x=None, y=None): minDist = None closestEntity = None for e in entities: dist = getDistanceBetweenPoints(e.posX, e.posY, x, y) if minDist is None or dist < minDist: closestEntity = e minDist = dist return closestEntity ## NOTE: This is absolute value! Doesn't take direction into account at all ## If only x is provided, only takes x into account. Same thing for y ## If both x and y are provided it calculates the hypotenuse def getDistanceBetweenPoints(x1=None, y1=None, x2=None, y2=None): xDist = None yDist = None if x1 is not None and x2 is not None: xDist = abs(x1 - x2) elif y1 is not None and y2 is not None: yDist = abs(y1 - y2) else: raise ValueError("either x or y must be provided to getDistanceBetweenPoints()") if xDist is not None and yDist is not None: return math.sqrt(xDist * xDist + yDist * yDist) elif xDist is not None: return xDist else: return yDist ## This is a bit of a misnomer because we take health into account as well def findMinionFurthestAhead(team): """ :param int team: The team for which to find a minion :rtype: Minion """ minions = getMinions(team) tower = getTower(team) healthyMinions = [m for m in minions if not isLowHealth(m)] ## Look for a healthy minion first because we need a good body shield! ## NOTE that for now we look at the X direction ONLY when computing distance farthestMinion = findFarthestEntity(healthyMinions, tower.posX) if farthestMinion is None: oppositeTower = getTower(getOtherTeam(team)) ## We don't have any healthy minions! Retreat to minion farthest from OPPOSITE tower farthestMinion = findFarthestEntity(minions, oppositeTower.posX) return farthestMinion def isLowHealth(entity): if entity.maxHealth <= 0: return True lowHealthPercentage = 25 return entity.health / entity.maxHealth < (entity.maxHealth * (lowHealthPercentage / 100)) ## TODO assumes only one hero per team def getHero(team): for entity in allEntities: if isinstance(entity, Hero) and entity.team == team: return entity # Possible that enemy hero is invisible, so none would be in the list # Todo: If our heroes are invisible are they also not in the list (they have to be...no way) return None def getHeroes(team): heroes = [] for entity in allEntities: if isinstance(entity, Hero) and entity.team == team: heroes.append(entity) return heroes def getHeroByType(team, heroType): for entity in allEntities: if isinstance(entity, Hero) and entity.team == team and entity.heroType == heroType: return entity def getTower(team): for entity in allEntities: if isinstance(entity, Tower) and entity.team == team: return entity raise ValueError("Missing tower for team " + `team`) def getMinions(team): minions = [] for entity in allEntities: if isinstance(entity, Minion) and entity.team == team: minions.append(entity) return minions def getOtherTeam(team): if team == 0: return 1 else: return 0 def readInEntities(entityCount): global allEntities allEntities = [] for i in range(entityCount): # unitType: UNIT, HERO, TOWER, can also be GROOT from wood1 # shield: useful in bronze # stunDuration: useful in bronze # countDown1: all countDown and mana variables are useful starting in bronze # heroType: DEADPOOL, VALKYRIE, DOCTOR_STRANGE, HULK, IRONMAN # isVisible: 0 if it isn't # itemsOwned: useful from wood1 unitId, team, entityType, x, y, attackRange, health, maxHealth, shield, attackDamage, movementSpeed, stunDuration, goldValue, countDown1, countDown2, countDown3, mana, maxMana, manaRegeneration, heroType, isVisible, itemsOwned = raw_input().split() unitId = int(unitId) team = int(team) x = int(x) y = int(y) attackRange = int(attackRange) health = int(health) maxHealth = int(maxHealth) shield = int(shield) attackDamage = int(attackDamage) movementSpeed = int(movementSpeed) stunDuration = int(stunDuration) goldValue = int(goldValue) countDown1 = int(countDown1) countDown2 = int(countDown2) countDown3 = int(countDown3) mana = int(mana) maxMana = int(maxMana) manaRegeneration = int(manaRegeneration) isVisible = int(isVisible) itemsOwned = int(itemsOwned) entity = None if entityType == ENTITY_TYPE_MINION: entity = Minion(unitId, team, x, y, attackRange, health, maxHealth, attackDamage, movementSpeed) elif entityType == ENTITY_TYPE_HERO: entity = Hero(heroType, unitId, team, x, y, attackRange, health, maxHealth, mana, maxMana, attackDamage, movementSpeed, manaRegeneration, isVisible, itemsOwned) elif entityType == ENTITY_TYPE_TOWER: entity = Tower(unitId, team, x, y) elif entityType == ENTITY_TYPE_GROOT: entity = Groot(unitId, team, x, y, attackRange, health, maxHealth, attackDamage, movementSpeed) if entity is None: raise ValueError("unknown entity type " + entityType) allEntities.append(entity) def chooseHero(): chosenHero = UNUSED_HEROES[0] CHOSEN_ALIVE_HEROES.append(chosenHero) print chosenHero UNUSED_HEROES.pop(0) def unused(): bushAndSpawnPointCount = int(raw_input()) # useful from wood1, represents the number of bushes and the number of places where neutral units can spawn for i in range(bushAndSpawnPointCount): # entityType: BUSH, from wood1 it can also be SPAWN entityType, x, y, radius = raw_input().split() x = int(x) y = int(y) radius = int(radius) def readInItems(itemCount): global allItems allItems = [] for i in range(itemCount): # itemName: contains keywords such as BRONZE, SILVER and BLADE, BOOTS connected by "" to help you sort easier # itemCost: BRONZE items have lowest cost, the most expensive items are LEGENDARY # damage: keyword BLADE is present if the most important item stat is damage # moveSpeed: keyword BOOTS is present if the most important item stat is moveSpeed # isPotion: 0 if it's not instantly consumed itemName, itemCost, damage, health, maxHealth, mana, maxMana, moveSpeed, manaRegeneration, isPotion = raw_input().split() itemCost = int(itemCost) damage = int(damage) health = int(health) maxHealth = int(maxHealth) mana = int(mana) maxMana = int(maxMana) moveSpeed = int(moveSpeed) manaRegeneration = int(manaRegeneration) isPotion = int(isPotion) item = Item(itemName, itemCost, damage, health, maxHealth, mana, maxMana, moveSpeed, manaRegeneration, isPotion) allItems.append(item) def printMoveAttack(posX, posY, unitId, curTurn): printAction('{} {} {} {}'.format(ACTION_MOVE_ATTACK, posX, posY, unitId), curTurn) def printAction(move, turn): global curInsult # update insult every 10 turns if turn % 10 == 0: curInsult = random.choice(INSULTS) # Write an action using print print move + ";" + curInsult def debug(objOrStr): if isinstance(objOrStr, Entity): print >> sys.stderr, objOrStr.__dict__ elif isinstance(objOrStr, Item): print >> sys.stderr, objOrStr.__dict__ elif isinstance(objOrStr, list): debug("[") for el in objOrStr: debug(el) debug("]") else: print >> sys.stderr, objOrStr ######################################################################################################################## ######################################################################################################################## ################################################## Classes ############################################################# ######################################################################################################################## ######################################################################################################################## class Entity(object): def __init__(self, unitId, entityType, team, posX, posY, attackRange, health, maxHealth, mana, maxMana, attackDamage, movementSpeed): self.unitId = unitId self.entityType = entityType self.team = team self.posX = posX self.posY = posY self.attackRange = attackRange self.health = health self.maxHealth = maxHealth self.mana = mana self.maxMana = maxMana self.attackDamage = attackDamage self.movementSpeed = movementSpeed ## Return true if self is in range of the other entity's attack def isInRangeOf(self, otherEntity): return otherEntity.canAttack(self.posX, self.posY) ## Return true if given (X,Y) coordinate is in attack range of self def canAttack(self, posX, posY): dist = getDistanceBetweenPoints(self.posX, self.posY, posX, posY) return dist <= self.attackRange class Minion(Entity): def __init__(self, unitId, team, posX, posY, attackRange, health, maxHealth, attackDamage, movementSpeed, mana=0, maxMana=0): super(Minion, self).__init__(unitId, ENTITY_TYPE_MINION, team, posX, posY, attackRange, health, maxHealth, mana, maxMana, attackDamage, movementSpeed) class Hero(Entity): def __init__(self, heroType, unitId, team, posX, posY, attackRange, health, maxHealth, mana, maxMana, attackDamage, movementSpeed, manaRegeneration, isVisible, itemsOwned): super(Hero, self).__init__(unitId, ENTITY_TYPE_HERO, team, posX, posY, attackRange, health, maxHealth, mana, maxMana, attackDamage, movementSpeed) self.heroType = heroType self.manaRegeneration = manaRegeneration self.isVisible = isVisible self.itemsOwned = itemsOwned class Tower(Entity): def __init__(self, unitId, team, posX, posY): super(Tower, self).__init__(unitId, ENTITY_TYPE_TOWER, team, posX, posY, attackRange=400, health=3000, maxHealth=3000, mana=0, maxMana=0, attackDamage=100, movementSpeed=0) class Groot(Entity): def __init__(self, unitId, team, posX, posY, attackRange, health, maxHealth, attackDamage, movementSpeed): super(Groot, self).__init__(unitId, ENTITY_TYPE_TOWER, team, posX, posY, attackRange, health, maxHealth, mana=0, maxMana=0, attackDamage=attackRange, movementSpeed=movementSpeed) class Item(object): def __init__(self, itemName, itemCost, damage, health, maxHealth, mana, maxMana, moveSpeed, manaRegeneration, isPotion): self.itemName = itemName self.itemCost = itemCost self.damage = damage self.health = health self.maxHealth = maxHealth self.mana = mana self.maxMana = maxMana self.moveSpeed = moveSpeed self.manaRegeneration = manaRegeneration self.isPotion = isPotion play()
true
ec855677f8be794168bce84d3cc9088c23463345
Python
vrvelasco/Python-Programming
/[Week 16] December 2/multiplication.py
UTF-8
424
4.4375
4
[]
no_license
# Victor Velasco (Multiplication) 12/2/19 def main(): num1 = 0 num2 = 0 while num1 <= 0: num1 = int(input('Enter a positive number: ')) while num2 <= 0: num2 = int(input('Enter another positive number: ')) print(num1, 'times', num2, 'is', multiply(num1, num2)) def multiply(x, y): if x == 0 or y == 0: return 0 else: return x + multiply(x, y - 1) # Call main main()
true
4473ff9cb5b16783c1cf4cb0e83235aa5a3223b1
Python
lucienimmink/scanner.py
/scanner/_utils.py
UTF-8
1,322
2.875
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf8 -*- class Time: def ums(i, ignoreZero=True): i = float(i) hours = int(i / 3600) rest = i % 3600 minutes = int(rest / 60) seconds = int(rest % 60) if hours < 10: hours = "0" + str(hours) if minutes < 10: minutes = "0" + str(minutes) if seconds < 10: seconds = "0" + str(seconds) if ignoreZero: if hours == "00": hours = "" else: hours = hours + ":" else: hours = hours + ":" return hours + str(minutes) + ":" + str(seconds) class force_unicode: def force_unicode(bstr, encoding, fallback_encodings=None): # We got unicode, we give unicode return bstr if isinstance(bstr, unicode): return bstr if fallback_encodings is None: fallback_encodings = ['UTF-16', 'UTF-8', 'ISO-8859-1'] encodings = [encoding] + fallback_encodings for enc in encodings: try: return bstr.decode(enc) except UnicodeDecodeError: pass except AttributeError: pass # Finally, force the unicode return bstr.decode(encoding, 'ignore')
true
b1ced03ce86e5f55a347a32f8dec4ae7524d86e4
Python
jasonfigueroa/PythonSnippets
/strings/strings.py
UTF-8
1,579
4.75
5
[]
no_license
# in this file I'll be practicing strings and a few basic ways to use or # manipulate strings. # string variable for our name, you can enclose the string with single quotes or # double quotes, I'll use singles so I don't have to use the shift key name = 'Jason' # string variable for a number as a string, using double quotes here stringNum = "1" # printing a string, in this case the word Hello with print ("Hello") # printing string variable name and "\n" is for adding an extra space between # this print statement and the next print statement print (name + "\n") #print ("\n") # printing the same string and concatenating (fancy word for appending) the # variable name to it print ('Hello' + name) # notice the previous line printed "Hello" and name with no space between them # let's fix that by simply adding an extra space after "Hello" so "Hello " print ("Hello" + " " + name) # An alternate way of doing this and in my opinion a simpler way, less typing ;) print ("Hello " + name) # anotther way of printing an extra line print() # printing a number as a string print ("num: " + stringNum) # print (stringNum + 2) would produce an error you would either have to convert # the string variable stringNum to a int variable or the number 2 to a string # first we'll convert the number 2 to a string, we'll use the str() command print ("first num: " + stringNum + "; second num: " + str(2)) # about tired of retyping this let's throw it in a variable greet = 'Hello ' print() # putting it all together print (greet + name + ' your number is: ' + stringNum)
true
f7d9e8097a55f82c7ce3e3cb52335a93e8a91d57
Python
unsortedtosorted/DynamicProgramming
/Unbounded Knapsack/rodcutting.py
UTF-8
900
3.25
3
[]
no_license
""" Given a rod of length ‘n’, we are asked to cut the rod and sell t he pieces in a way that will maximize the profit. We are also given the price of every piece of length ‘i’ where ‘1 <= i <= n’. Example: Lengths: [1, 2, 3, 4, 5] Prices: [2, 6, 7, 10, 13] Rod Length: 5 dp(i) = max (i+dp(l-i)) for i in range(0,n) """ import sys def solveRodCutting(lengths, prices,n): memo = {} def dp(l): if l in memo: return memo[l] if l == 0: memo[l] = 0 return memo[l] else: m = -sys.maxsize-1 for i,x in enumerate(lengths): if l-x >=0: if l-x not in memo: memo[l-x] = dp(l-x) m = max(m,prices[i]+memo[l-x]) return m return dp(n) print (solveRodCutting([1, 2, 3, 4, 5],[2, 6, 7, 10, 13],50))
true
b7ab9e6fdf234152418e22d69a72f9505c631a7b
Python
simonhoo/python-study
/s002/slicing.py
UTF-8
735
3.71875
4
[ "Apache-2.0" ]
permissive
#!/usr/bin/python # -*- coding:utf-8 -*- def t_slicing_str(): s = 'http://www.cottsoft.com' print s[7:] def t_slicing_arry(): ar = [1,2,3,4,5,6,7,8,9,0] print ar[4:] print ar[4:-2] print ar[-2:] print ar[:7] def t_slicing_input(): s = raw_input("请输入字符串:") n1 = input("请输入要截取的开始下标:") n2 = input("请输入要截取的结束下标:") if n1 >0 and n2>0: print s[n1:n2] elif n1 >0 and n2<=0: print s[n1:] elif n1<0 and n2>=0: print s[:n2] else: print s def t_slicing_step_len(): ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print ar[0:-1:2] t_slicing_str() t_slicing_arry() t_slicing_input() t_slicing_step_len()
true
6141ce19a90680508f097dff816cce12fc7cee90
Python
cser2016/HttpUdp
/hello_server.py
UTF-8
416
3.046875
3
[]
no_license
from flask import Flask, request app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def hello(): name = 'World' if request.method == 'POST': name = request.form.get('name', 'World') return ''' <h1>Hello {name}!</h1> <form method="post"> <input type="text" name="name"> <button type="submit">Hello!</button> </form> '''.format(name=name) if __name__ == "__main__": app.run()
true
8f0fd363ddce4fd1d4779274a6fa64b5d3fb27dc
Python
pratikhrohane/IoT_NodeMCU
/lab_06.py
UTF-8
1,209
2.90625
3
[]
no_license
""" Watching Start Wars Episodes on NodeMCU >>Connect NodeMCU Internet >>Download Asciimation >>Display NodeMCU connect to Internet ~ESP8266 WiFi based Chip with UART interfaace ~802.11b/g/n Protocal ~Integrated TCP/IP stact ~ON-chip SRAM SSID -> Name for Wireless Network IP -> Software level id for node MAC -> Hardware level id for node AP -> NodeMCU can also be mode as Access Point Medium Blog : https://medium.com/@stestagg/playing-star-wars-on-the-esp8266-with-micropython-5f175fe7b755 """ import network import socket def connect_to_ap(): wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print("Connecting to Network") wlan.connect('Mi-Fi', 'Pratik@124') while not wlan.isconnected(): pass #print("Network Config: ", wlan.config()) def watch_starwars(): addr_info = socket.getaddrinfo("towel.blinkenlights.nl", 23) addr = addr_info[0][-1] s = socket.socket() s.connect(addr) while True: data = s.recv(500) print(str(data, 'utf8'), end=' ') def main(): connect_to_ap() watch_starwars() if __name__ == '__main__': print("Get Ready") main()
true
c88664c1ec85127719486e2ffe0e0c22f5068a60
Python
zillow/ctds
/tests/test_cursor___iter__.py
UTF-8
2,858
2.53125
3
[ "MIT" ]
permissive
import warnings from .base import TestExternalDatabase class TestCursorNext(TestExternalDatabase): '''Unit tests related to the Cursor.__iter__() member. ''' def test_next(self): with self.connect() as connection: with connection.cursor() as cursor: cursor.execute( ''' DECLARE @test_fetchone TABLE(i INT); INSERT INTO @test_fetchone(i) VALUES (1),(2),(3); SELECT * FROM @test_fetchone; SELECT i * 2 FROM @test_fetchone; ''' ) with warnings.catch_warnings(record=True) as warns: self.assertEqual([tuple(row) for row in cursor], [(1,), (2,), (3,)]) self.assertEqual(len(warns), 1) self.assertEqual( [str(warn.message) for warn in warns], ['DB-API extension cursor.__iter__() used'] * len(warns) ) self.assertEqual( [warn.category for warn in warns], [Warning] * len(warns) ) self.assertEqual(cursor.nextset(), True) with warnings.catch_warnings(record=True) as warns: self.assertEqual([tuple(row) for row in cursor], [(2,), (4,), (6,)]) self.assertEqual(len(warns), 1) self.assertEqual( [str(warn.message) for warn in warns], ['DB-API extension cursor.__iter__() used'] * len(warns) ) self.assertEqual( [warn.category for warn in warns], [Warning] * len(warns) ) self.assertEqual(cursor.nextset(), None) def test_next_warning_as_error(self): with self.connect() as connection: with connection.cursor() as cursor: cursor.execute( ''' DECLARE @test_fetchone TABLE(i INT); INSERT INTO @test_fetchone(i) VALUES (1),(2),(3); SELECT * FROM @test_fetchone; SELECT i * 2 FROM @test_fetchone; ''' ) with warnings.catch_warnings(): warnings.simplefilter('error') try: self.assertEqual([tuple(row) for row in cursor], [(1,), (2,), (3,)]) except Warning as warn: self.assertEqual('DB-API extension cursor.__iter__() used', str(warn)) else: self.fail('.__iter__() did not fail as expected') # pragma: nocover
true
19a1242bfc081145b1698dba06cebb62df94e3d2
Python
eduardoroboto/math-matrix
/main.py
UTF-8
1,464
2.953125
3
[ "BSD-3-Clause" ]
permissive
from matrix import Matrix # class test if __name__ == '__main__': #a = Matrix(4,4,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) #a = Matrix(3,4,[-1,1,-2,-20,5,2,1,21,2,5,4,33]) #a = Matrix(2,5,[2,1,1,1,1,2,1,1,1,3]) #a = Matrix(3,4,[1,-1,2,2,2,1,-1,1,-2,-5,3,3]) # a = Matrix(2,2,[1,2,3,4]) #b = Matrix(2,2,[2,2,2,2]) #c = a.transpose() #c = b.__rsub__(a) #print(a) #print(c) #c = a.gauss_jordan() #a = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]) #b = Matrix(3, 3, [10, 20, 30, 40, 50, 60, 70, 80, 90]) #c = b - a #print(c[2,2] == 45) #c = 2 - a #print(a) #print(c) #print(c[2,2] == 3) #print(a) #print(c) #Situação especifica em que o x3 não importa (gratis) #a = Matrix(3,4,[1,3,1,9,1,1,-1,1,3,11,5,35]) a = Matrix(3,4,[1,-2,1,0,0,2,-8,8,5,0,-5,10]) # b = Matrix(3,2,[2,0,1,-1,3,5]) # b = [0,0,0,0] # a[2] = b #print(a.gauss()) # a[1],a[2] = a[2],a[1] #print(a) c = a.gauss_jordan() #print(a) # a.gauss() # c = a.dot(b) # print(c) # teste 1 OK #a = Matrix(2, 2, [1, 2, 3, 4]) #print(a[3,3]) #teste 2 ok #a[3,3] = 5 #a = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]) #b = Matrix(2, 2, [10, 20, 30, 40]) #a = Matrix(3, 3, [1,-2, 3, 3,-8,11,-4, 6,-7]) #c = a.inverse() #d = c.dot(a) print(a) print(c) #rint(d) #print("{}\n{}".format(a,c))
true
81f6c48e8ee21a4ad87dd0448399e29650ad582e
Python
rodrigoSolano/pokedex
/entities/pokemonTypes/GrassPokemon.py
UTF-8
765
2.75
3
[]
no_license
from entities.DecoratorPokemon import DecoratorPokemon from entities.pokemonTypes.config import type_strengths from entities.pokemonTypes.config import type_weaknesses class GrassPokemon(DecoratorPokemon): strengths = type_strengths['grass'] weaknesses = type_weaknesses['grass'] typeName = "Grass" def __init__(self, pokemon): super().__init__(pokemon) self.pokemon = pokemon def getWeaknessesByType(self): return self.weaknesses + self.pokemon.getWeaknessesByType() def getStrengthsByType(self): return self.strengths + self.pokemon.getStrengthsByType() def getTypes(self): return [self.typeName] + self.pokemon.getTypes() def getName(self): return self.pokemon.getName()
true
d085d10b2b3f3d3740b2d818e04d2550ba45f429
Python
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_2/gosip/pancakes.py
UTF-8
423
3.21875
3
[]
no_license
def main(): f = open("B-large.in", "r") t = int(f.readline()) for i in range(t): r = count(f.readline().strip()) print("Case #" + str(i+1) + ": " + str(r)) def count(arg): cnt = 0 last = arg[0] for c in arg: if last == '-' and c == '+': last = '+' cnt += 1 elif last == '+' and c == '-': last = '-' cnt += 1 if arg[len(arg) - 1] == '-': cnt += 1 return cnt if __name__ == '__main__': main()
true
0f70268fc15e4562a0a60af33534d0e7108cb8d5
Python
AChen24562/Python-QCC
/Week-9-Functions/Part-2/hw2-test.py
UTF-8
256
3.734375
4
[]
no_license
from random import randint def isInRange(x): return x in range(-100, 100) def main(): for x in range(10): n = randint(-500, 500) if isInRange(n): print(f"{n} ok") else: print(f"{n} no ") main()
true
a39faa04f973de1335aa6f0c8e4a4d373da6614c
Python
a-jumani/coding-problems
/Binary Search/1/lowest_index.py
UTF-8
1,243
3.921875
4
[ "MIT" ]
permissive
def lowest_index(arr, target): """ Finds the lowest index of target in arr. If target in arr, returns lowest index i such that arr[i] == target, else returns index i where it should be inserted while keeping arr sorted. Args: arr array to search target in target value Returns: index, where 0 <= index <= len(arr) Preconditions: arr == sorted(arr) < is supported between target and elements of arr """ # initialize search range start, end = 0, len(arr) # maintain solution in range [start, end] while (start < end): mid = (start + end) // 2 if arr[mid] < target: start = mid + 1 else: end = mid return end def count_in_sorted(arr, target, target_inc): """ Count of target in arr. Args: arr array target value to count in arr target_inc smallest value greater than target considering type(s) of elements in arr Returns: same value as arr.count(target) Preconditions: arr == sorted(arr) < should be supported between target(_inc) and elements of arr """ return lowest_index(arr, target_inc) - lowest_index(arr, target)
true
07d4d03be15891bbd1ce4e648dcbf4fd23b3cbc5
Python
YolandePretorius/159372-Assignment-4
/Assignment 4/aipython/cspExamples.py
UTF-8
7,731
3.359375
3
[]
no_license
# cspExamples.py - Example CSPs # AIFCA Python3 code Version 0.9.1 Documentation at http://aipython.org # Artificial Intelligence: Foundations of Computational Agents # http://artint.info # Copyright David L Poole and Alan K Mackworth 2017-2020. # This work is licensed under a Creative Commons # Attribution-NonCommercial-ShareAlike 4.0 International License. # See: http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en from cspProblem import Variable, CSP, Constraint from operator import lt,ne,eq,gt def ne_(val): """not equal value""" # nev = lambda x: x != val # alternative definition # nev = partial(neq,val) # another alternative definition def nev(x): return val != x nev.__name__ = str(val)+"!=" # name of the function return nev def is_(val): """is a value""" # isv = lambda x: x == val # alternative definition # isv = partial(eq,val) # another alternative definition def isv(x): return val == x isv.__name__ = str(val)+"==" return isv X = Variable('X', {1,2,3}) Y = Variable('Y', {1,2,3}) Z = Variable('Z', {1,2,3}) csp0 = CSP("csp0", {X,Y,Z}, [ Constraint([X,Y],lt), Constraint([Y,Z],lt)]) A = Variable('A', {1,2,3,4}, position=(0,0.25)) B = Variable('B', {1,2,3,4}, position=(0.5,0)) C = Variable('C', {1,2,3,4}, position=(1,0.25)) C0 = Constraint([A,B], lt, "A < B", position=(0.25,0.8)) C1 = Constraint([B], ne_(2), "B != 2", position=(0.5,0.8)) C2 = Constraint([B,C], lt, "B < C", position=(0.75,0.8)) csp1 = CSP("csp1", {A, B, C}, [C0, C1, C2]) D = Variable('D', {1,2,3,4}, position=(0.7,0.9)) E = Variable('E', {1,2,3,4}, position=(0.3,0.9)) csp2 = CSP("csp2", {A,B,C,D,E}, [ Constraint([B], ne_(3), "B != 3"), Constraint([C], ne_(2), "C != 2"), Constraint([A,B], ne, "A != B"), Constraint([B,C], ne, "A != C"), Constraint([C,D], lt, "C < D"), Constraint([A,D], eq, "A = D"), Constraint([A,E], gt, "A > E"), Constraint([B,E], gt, "B > E"), Constraint([C,E], gt, "C > E"), Constraint([D,E], gt, "D > E"), Constraint([B,D], ne, "B != D")]) csp3 = CSP("csp3", {A,B,C,D,E}, [Constraint([A,B], ne, "A != B"), Constraint([A,D], lt, "A < D"), Constraint([A,E], lambda a,e: (a-e)%2 == 1, "A-E is odd"), # A-E is odd Constraint([B,E], lt, "B < E"), Constraint([D,C], lt, "D < C"), Constraint([C,E], ne, "C != E"), Constraint([D,E], ne, "D != E")]) def adjacent(x,y): """True when x and y are adjacent numbers""" return abs(x-y) == 1 csp4 = CSP("csp4", {A,B,C,D,E}, [Constraint([A,B], adjacent, "adjacent(A,B)"), Constraint([B,C], adjacent, "adjacent(B,C)"), Constraint([C,D], adjacent, "adjacent(C,D)"), Constraint([D,E], adjacent, "adjacent(D,E)"), Constraint([A,C], ne, "A != C"), Constraint([B,D], ne, "A != D"), Constraint([C,E], ne, "C != E")]) def meet_at(p1,p2): """returns a function of two words that is true when the words intersect at postions p1, p2. The positions are relative to the words; starting at position 0. meet_at(p1,p2)(w1,w2) is true if the same letter is at position p1 of word w1 and at position p2 of word w2. """ def meets(w1,w2): return w1[p1] == w2[p2] meets.__name__ = "meet_at("+str(p1)+','+str(p2)+')' return meets one_across = Variable('one_across', {'ant', 'big', 'bus', 'car', 'has'}, position=(0.3,0.9)) one_down = Variable('one_down', {'book', 'buys', 'hold', 'lane', 'year'}, position=(0.1,0.7)) two_down = Variable('two_down', {'ginger', 'search', 'symbol', 'syntax'}, position=(0.9,0.8)) three_across = Variable('three_across', {'book', 'buys', 'hold', 'land', 'year'}, position=(0.1,0.3)) four_across = Variable('four_across',{'ant', 'big', 'bus', 'car', 'has'}, position=(0.7,0.0)) crossword1 = CSP("crossword1", {one_across, one_down, two_down, three_across, four_across}, [Constraint([one_across,one_down], meet_at(0,0)), Constraint([one_across,two_down], meet_at(2,0)), Constraint([three_across,two_down], meet_at(2,2)), Constraint([three_across,one_down], meet_at(0,2)), Constraint([four_across,two_down], meet_at(0,4))]) words = {'ant', 'big', 'bus', 'car', 'has','book', 'buys', 'hold', 'lane', 'year', 'ginger', 'search', 'symbol', 'syntax'} def is_word(*letters, words=words): """is true if the letters concatenated form a word in words""" return "".join(letters) in words letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"} # pij is the variable represeting the letter i from the left and j down (starting from 0) p00 = Variable('p00', letters, position=(0,0)) p10 = Variable('p10', letters, position=(0,0)) p20 = Variable('p20', letters, position=(0,0)) p01 = Variable('p01', letters, position=(0,0)) p21 = Variable('p21', letters, position=(0,0)) p02 = Variable('p02', letters, position=(0,0)) p12 = Variable('p12', letters, position=(0,0)) p22 = Variable('p22', letters, position=(0,0)) p32 = Variable('p32', letters, position=(0,0)) p03 = Variable('p03', letters, position=(0,0)) p23 = Variable('p23', letters, position=(0,0)) p24 = Variable('p24', letters, position=(0,0)) p34 = Variable('p34', letters, position=(0,0)) p44 = Variable('p44', letters, position=(0,0)) p25 = Variable('p25', letters, position=(0,0)) crossword1d = CSP("crossword1d", {p00, p10, p20, # first row p01, p21, # second row p02, p12, p22, p32, # third row p03, p23, #fourth row p24, p34, p44, # fifth row p25 # sixth row }, [Constraint([p00, p10, p20], is_word), #1-across Constraint([p00, p01, p02, p03], is_word), # 1-down Constraint([p02, p12, p22, p32], is_word), # 3-across Constraint([p20, p21, p22, p23, p24, p25], is_word), # 2-down Constraint([p24, p34, p44], is_word) # 4-across ]) def queens(ri,rj): """ri and rj are different rows, return the condition that the queens cannot take each other""" def no_take(ci,cj): """is true if queen at (ri,ci) cannot take a queen at (rj,cj)""" return ci != cj and abs(ri-ci) != abs(rj-cj) return no_take def n_queens(n): """returns a CSP for n-queens""" columns = list(range(n)) variables = [Variable(f"R{i}",columns) for i in range(n)] return CSP("n-queens", variables, [Constraint([variables[i], variables[j]], queens(i,j)) for i in range(n) for j in range(n) if i != j]) # try the CSP n_queens(8) in one of the solvers. # What is the smallest n for which there is a solution? def test_csp(CSP_solver, csp=csp1, solutions=[{A: 1, B: 3, C: 4}, {A: 2, B: 3, C: 4}]): """CSP_solver is a solver that takes a csp and returns a solution csp is a constraint satisfaction problem solutions is the list of all solutions to csp This tests whether the solution returned by CSP_solver is a solution. """ print("Testing csp with",CSP_solver.__doc__) sol0 = CSP_solver(csp) print("Solution found:",sol0) assert sol0 in solutions, "Solution not correct for "+str(csp) print("Passed unit test")
true
d86539aa8d02235a4cec35ebd3238225e4a43a4e
Python
liliahache/kattis
/calculatingdartscores.py
UTF-8
557
2.890625
3
[]
no_license
import sys from itertools import product, combinations_with_replacement, chain n = int(next(sys.stdin)) c = list(product(range(1, 20+1),range(1, 3+1))) scores = dict() for p in list(combinations_with_replacement(c, 1)) + list(combinations_with_replacement(c, 2)) + list(combinations_with_replacement(c, 3)): s = sum(_[0]*_[1] for _ in p) if s not in scores or len(p) < len(scores[s]): scores[s] = p text = ['single','double','triple'] if n in scores: for d in scores[n]: print text[d[1]-1], d[0] else: print 'impossible'
true