blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
e77e5854a648a29d8780d866dab118cd99e9cb2d
cloud-abyss/pythonProject1
/day02/practice01.py
145
3.65625
4
# 将华氏温度转换为摄氏温度 f=float(input('请输入华氏温度:')) c=(f-32)/1.8 print('华氏温度%.1f==摄氏温度%.1f' %(f,c))
2dfabe76e6664805f92811f5cd634835354793f6
renansald/Python
/cursos_em_video/Desafio35.py
394
3.9375
4
reta1 = float(input("Informe a primeira reta: ")) reta2 = float(input("Informe a segunda reta: ")) reta3 = float(input("Informe a terceira reta: ")) aux = (reta1 + reta2 + reta3)/2 if((reta1 <= 0) or (reta2 <= 0) or (reta3 <= 0) or (aux-reta1 <= 0) or (aux-reta2 <= 0) or (aux-reta3 <= 0)): print("Não é possível criar um triângulo") else: print("É possível criar um triângulo")
3d18a5e63ded60b21d38ce75b91b2504510b498f
OusmaneT/Projet3_GLO1901
/quoridorx.py
4,291
3.5
4
""" Class Quoridorx - Phase 3 Écrit par : Maxime Carpentier Vincent Bergeron Ousmane Touré Le 16 décembre 2019 Ce programme contient la classe avec toutes les méthodes pour jouer au jeu Quoridor en graphique """ import quoridor import turtle class Quoridorx(quoridor.Quoridor): """ Classe Quoridor, contient toutes les fonctions nécéssaires pour jouer au jeu Quoridor en mode graphique. """ def afficher(self): """ Fonction pour afficher le jeu en mode graphique """ # On crée la fenêtre fen = turtle.Screen() fen.title("Jeu Quoridor") fen.setup(width=800, height=800) # On définie nos formes, les bords, les murs et les pions bord = ((0, 0), (0, 10), (600, 10), (600, 0), (0, 0)) mur = ((0, 0), (0, 10), (-110, 10), (-110, 0), (0, 0)) pion = ((-10, -10), (10, -10), (10, 10), (-10, 10), (-10, -10)) turtle.addshape('pion', pion) turtle.addshape('bord', bord) turtle.addshape('mur', mur) # On trace les bords du plateau # On va ce placer dans le coin inférieur droit du plateau joe = turtle.Turtle() joe.penup() joe.backward(350) joe.left(90) joe.forward(300) joe.pendown() joe.shape('bord') joe.pencolor('black') joe.fillcolor('black') joe.stamp() # On fait tous les bords un par un joe.penup() joe.right(90) joe.forward(590) joe.pendown() joe.stamp() joe.penup() joe.right(90) joe.forward(590) joe.pendown() joe.stamp() joe.penup() joe.right(90) joe.forward(590) joe.pendown() joe.stamp() joe.penup() # On place les pions # On définie le pion du joueur 1 en rouge alex = turtle.Turtle() alex.shape('pion') alex.penup() alex.pencolor('red') alex.fillcolor('red') alex.backward(55) alex.left(90) alex.backward(280) # On définie le pion du joueur 2 en vert robot = turtle.Turtle() robot.shape('pion') robot.penup() robot.pencolor('green') robot.fillcolor('green') robot.backward(55) robot.left(90) robot.forward(290) # On place le pion du joueur 1 en fonction des coordonées x = (5 - self.joueur1["pos"][0])*68 - 5 y = (self.joueur1["pos"][1] - 1)*68 + 10 alex.forward(y) alex.left(90) alex.forward(x) # On place le pion du joueur 2 en fonction des coordonées x = (5 - self.joueur2["pos"][0])*68 - 5 y = (9 - self.joueur2["pos"][1])*68 +16 robot.backward(y) robot.right(90) robot.backward(x) # On place ce place à l'origine pour les murs # On définie le turtle pour les murs mure = turtle.Turtle() mure.shape('mur') mure.penup() mure.pencolor('blue') mure.fillcolor('blue') mure.backward(370) mure.right(90) mure.forward(300) mure.left(90) # On place d'abord tous les murs verticaux un par un en lisant la liste for liste in self.verticaux: x = (liste[0] - 1)*68 + 10 y = (liste[1] - 1)*68 + 15 mure.forward(x) mure.left(90) mure.forward(y) mure.right(90) mure.stamp() mure.left(90) mure.backward(y) mure.right(90) mure.backward(x) # On change le sens de la forme mure.right(90) # On place les murs horizontaux for liste in self.horizontaux: x = (liste[0] - 1)*68 + 30 y = (liste[1] - 1)*68 mure.backward(y) mure.left(90) mure.forward(x) mure.right(90) mure.stamp() mure.left(90) mure.backward(x) mure.right(90) mure.forward(y) # On cache le turtle des murs dans les bords du plateau mure.fillcolor('black') mure.pencolor('black') mure.left(90) mure.forward(10) mure.right(90) mure.backward(10)
866bc556625dfa73cac7990cc1e2ef6b4148945b
17mirinae/Python
/Python/DAYOUNG/3_for문/구구단.py
81
3.5625
4
n = int(input()) for x in range(1, 10): print("%d * %d = %d" %(n, x, n*x))
efe4cde9e2bd6d76710393b3ab1fc582ccf5a26d
arpanrau/TextMining
/wikipedia_sentiment_revised.py
3,400
3.78125
4
#scrapes wikipedia and performs sentiment analysis to figure out what wikipedia thinks about #congress democrats and republicans from pattern.web import * from pattern.en import * def sentiment_finder(searchterm): """Finds sentiment of a given article on wikipedia. accepts string searchterm where searchterm is the title of a wikipedia article. Returns vector of (sentiment, objectivity) where sentiment is between -1.0 and 1.0 and objectivity is between 0 and 1""" try: article = Wikipedia().search(searchterm) #pull article from wikipedia articletext = str.splitlines(article.plaintext().encode('utf-8')) founde = False for i in range(len(articletext)): #loop thru and find the first line in the article if articletext[i] == '* e': #First line of article content marked by *e if article starts with bulleted lists index = i founde = True if founde == False: #if we haven't found e yet, no bulleted list so we automatically pull 1st paragraph index = 0 return sentiment(articletext[index+2]) #return sentiment. +2 accounts for first empty lines except: return (0,0) #returns no wikipedia sentiment if error is thrown #populate list of current voting members of house and senate republicans = [] democrats = [] senators = Wikipedia().search('Current members of the United States House of Representatives') #pulls wikipedia article for senators senatorsections = senators.sections[5] #pulls section of senators wikipedia article to read (voting members) senatorlist = senatorsections.tables[0]#pulls list of current senators in table form #iterates thru the table and classifies article names with Democrats and Republicans for i in range(len(senatorlist.rows)): namelist = senatorlist.rows[i][1] namelength = (len(namelist)-((len(namelist)-3)/2)) #custom index based on how pattern returns the names name = namelist[namelength-1:len(namelist)] if senatorlist.rows[i][3] == 'Republican': #NOTE: encode to string republicans.append(name.encode('utf-8')) if senatorlist.rows[i][3] == 'Democratic': democrats.append(name.encode('utf-8')) republicanscores = [] democraticscores = [] republicancount = 0.0 democratcount = 0.0 #iterate thru list of republicans and find sentiment for i in republicans: print i republicancount += 1.0 republicanscores.append(sentiment_finder(i)) #iterate thru list of democrats and find sentiment for i in democrats: print i democratcount += 1.0 democraticscores.append(sentiment_finder(i)) republicanaverage = [0,0] democrataverage = [0,0] #sum and average democrat and republican scores for i in democraticscores: democrataverage[0] += i[0] democrataverage[1] += i[1] for i in republicanscores: republicanaverage[0] += i[0] republicanaverage[1] += i[1] republicanaverage[0] = republicanaverage[0]/republicancount republicanaverage[1] = republicanaverage[1]/republicancount democrataverage[0] = democrataverage[0]/democratcount democrataverage[1] = democrataverage[1]/democratcount #Print final scores print "final scores" print "Republicans" print republicanaverage print "Democrats" print democrataverage
008130f93a8f1b0478b33d7e0a0d223a8e4f5217
magdalena-natalia/PR3TimeMachine
/interactions.py
521
3.53125
4
import datetime def ask_for_input(question): """ Ask an user for input. """ response = '' while not response: response = input(question) return response def ask_for_date(question): """ Ask an user for a date and return it as datetime object. """ response = ask_for_input(question) try: response_date_obj = datetime.datetime.strptime(response, '%d.%m.%Y') except ValueError: response_date_obj = None ask_for_date(question) return response_date_obj
f5415708d6838f1cbbce45dd9728a9a396de05da
spencerzhang91/coconuts-on-fire
/find_friend_20150326.py
485
3.546875
4
def network(L, first = None, second = None): connection = [] for item in L: connection.append({item.split('-')[0], item.split('-')[1]}) print(connection) l = [item for item in connection if item.issuperset({first})] print(l) if {first, second} in connection: return True else: pass test_L = ['a1-a2', 'a2-a3', 'a2-a8', 'a3-a4', 'a3-a5', 'a5-a8', 'a8-a7', 'a6-a7'] network(test_L,'a1','a6')
dd3c609f9a2f95c2669ac4c866a6ff9f4bfdac7a
kangmihee/EX_python
/py_hypo_tensor/pack/ten21mnist.py
2,376
3.546875
4
# MNIST 분류 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("./data/", one_hot = True) training_epochs = 25 batch_size = 100 # 데이터 처리를 100개 묶음으로 처리 x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) # w = tf.Variable(tf.zeros([784, 10])) # b = tf.Variable(tf.zeros([10])) #logits = tf.matmul(x, w) + b #hypothesis = tf.nn.softmax(logits) #hypothesis = tf.nn.relu(logits) #cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y)) # 정확도 향상을 위해 layer 추가 w1 = tf.Variable(tf.random_normal([784, 256])) w2 = tf.Variable(tf.random_normal([256, 256])) w3 = tf.Variable(tf.random_normal([256, 10])) b1 = tf.Variable(tf.random_normal([256])) b2 = tf.Variable(tf.random_normal([256])) b3 = tf.Variable(tf.random_normal([10])) L1 = tf.nn.relu(tf.add(tf.matmul(x, w1), b1)) # Hidden layer L2 = tf.nn.relu(tf.add(tf.matmul(L1, w2), b2)) hypothesis = tf.add(tf.matmul(L2, w3), b3) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=hypothesis, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) for epoch in range(training_epochs): avg_cost = 0 total_batch = int(mnist.train.num_examples / batch_size) # 확룰적 학습 for i in range(total_batch): batch_x, batch_y = mnist.train.next_batch(batch_size) _, c = sess.run([optimizer, cost], feed_dict={x:batch_x, y:batch_y}) avg_cost += c / total_batch if (epoch + 1) % 5 == 0: print('epoch:', '%03d'%(epoch + 1), 'cost:','{:.5f}'.format(avg_cost)) # 모델 평가 cor_pred = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(cor_pred, tf.float32)) print('accuracy : ', sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})) # 숫자 이미지 예측하기 import random r = random.randrange(mnist.test.num_examples) print(r) #print(mnist.test.labels[0:1]) print('실제값 : ', sess.run(tf.argmax(mnist.test.labels[r:r+1], 1))) print('예측 값: ', sess.run(tf.argmax(hypothesis, 1), feed_dict={x:mnist.test.images[r:r+1]}))
10503b426f388917032cb1415d7d001397a847f3
MrAliTheGreat/Programming
/Python/Coding/Practice/MileStone2.py
4,067
3.765625
4
from random import shuffle from random import randint class Player(): def __init__(self,money=100): self.money=money self.player_cards=[] def place_bet(self,bet): flag_bet=False if bet <= self.money: print(f'You have bet {bet}$') self.money-=bet flag_bet=True else: print("You don't have enough money bet lower!") return flag_bet def win_prize(self,prize): self.money+=prize print(f'Congrats! You won {prize}$') def show_remaining_money(self): print(f'You have {self.money}$ left!') def hit(self,deck): random_index=randint(0,len(deck)-1) ace=[1,11] if deck[random_index]==1 or deck[random_index]==11: choice=int(input('You Have Gotten an ACE!\nWhich one do you want as your ace 1 or 11? ')) self.player_cards.append(choice) ace.remove(choice) deck.remove(choice) deck.remove(ace[0]) else: self.player_cards.append(deck[random_index]) return deck def sum_cards(self): return sum(self.player_cards) def __str__(self): return str(self.player_cards) class Cards(): def __init__(self): self.cards=list(range(2,11))*4 for item in ['Jack','King','Queen']: self.cards.append(10) for item in ['Spades', 'Hearts', 'Diamonds', 'Clubs']: self.cards.append(1) self.cards.append(11) def shuffle_cards(self): shuffle(self.cards) return self.cards def __str__(self): return str(self.cards) class Dealer(): def __init__(self): self.dealer_cards=[] self.random_index_dealer=randint(0,1) def hit(self,deck): random_index=randint(0,len(deck)-1) random_index_choice=randint(0,1) ace=[1,11] if deck[random_index]==1 or deck[random_index]==11: self.dealer_cards.append(ace[random_index_choice]) deck.remove(ace[random_index_choice]) ace.remove(ace[random_index_choice]) deck.remove(ace[0]) else: self.dealer_cards.append(deck[random_index]) return deck def sum_cards(self): return sum(self.dealer_cards) def show_all_hand(self): print(self.dealer_cards) def __str__(self): return str(self.dealer_cards[self.random_index_dealer]) if __name__ == '__main__': flag_game=True while True: flag=True cards=Cards() print('Unshuffled Cards!') print(cards) cards=cards.shuffle_cards() print('Shuffled Cards!') print(cards) new_player=Player() # Money is 100 by default # Receiving first 2 cards for player cards=new_player.hit(cards) cards=new_player.hit(cards) print('Player Cards!') print(new_player) new_dealer=Dealer() # Receiving first 2 cards for dealer cards=new_dealer.hit(cards) cards=new_dealer.hit(cards) print('Dealer Cards only 1!') print(new_dealer) # Placing bet while True: try: bet_player=int(input('How much do you want to bet? ')) except: print('Your input is NOT valid please enter a new input!\n') else: break flag_bet_main=new_player.place_bet(bet_player) while True: if not flag_bet_main: bet_player=int(input('How much do you want to bet? ')) flag_bet_main=new_player.place_bet(bet_player) else: break # For Player while flag: choice_game=input('Do you want to Hit or Stay? ').lower() if choice_game=='hit': cards=new_player.hit(cards) print('Player Cards!') print(new_player) print(f'Sum of your cards is: {new_player.sum_cards()}') if new_player.sum_cards()>21: print('Computer Won!') print('Computer Cards Were:') new_dealer.show_all_hand() flag_game=False flag=False elif choice_game=='stay': flag=False if not flag_game: break # For Dealer while new_dealer.sum_cards()<=21: if new_dealer.sum_cards()>new_player.sum_cards() and new_dealer.sum_cards()<=21: flag_game=False break cards=new_dealer.hit(cards) if flag_game: print('You Won!') new_player.win_prize(bet_player*2) new_player.show_remaining_money() print('Computer Cards Were:') new_dealer.show_all_hand() break else: print('Computer Won!') print('Computer Cards Were:') new_dealer.show_all_hand() break
73c337e5a7b12151226fb6e3a3a55e95834dcade
zaetae/gomycode
/6th/Q5.py
168
3.59375
4
import numpy as np array=np.array([[1,8,9,7],[4,8,3,1],[7,8,6,10]]) for i in range (array.shape[0]): #to loop through rows in array print(array[i].mean())
c5a987fe5ce6cffd53d216545aa62adedea1b8e1
Jinx-Heniux/Python-2
/maths/leap_year.py
389
3.875
4
""" https://en.wikipedia.org/wiki/Leap_year """ def is_leap_year(year: int) -> bool: """ >>> all(is_leap_year(year) for year in [1600, 2000, 24000]) True >>> all(is_leap_year(year) for year in [1999, 2001, 2002]) False """ return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 if __name__ == "__main__": from doctest import testmod testmod()
0f8cc6df257e651db41eaa502a777f917193eaa5
adelgar/python-for-everybody-book
/Chapter 03 (Conditional execution)/exercise2.py
452
3.96875
4
inp1 = input('Enter Hours: ') try: hours = float(inp1) inp2 = input('Enter Rate: ') try: rate = float(inp2) if hours > 40: worked = hours - 40 extra = worked * 1.5 inp3 = (40 + extra) * rate pay = str(round(inp3, 2)) print('Pay: ' + pay) else: inp3 = hours * rate pay = str(round(inp3, 2)) print('Pay: ' + pay) except: print('Error, please enter numeric input') except: print('Error, please enter numeric input')
41b69d20aa147123113eb3835f729722a50125d8
BruceWeng/Restaur-Predict
/Project3/binarify.py
3,584
3.6875
4
import csv, re, sys, string from util import * from os import path from math import log # Limit the number of features for testing BCL_LIMIT = -1 def getColList(fname, clColIndex): """ Return a list of values of the column in the CSV file Parameters ---------- fname: str The name of the CSV file columns: str The name of the column in the CSV file to get Returns ------- List of values of the specified columns """ colList = {'text': [], 'clabel': []} with open(fname) as f: reader = csv.reader(f) header = reader.next() textColIndex = header.index('text') for row in reader: text = row[textColIndex].lower().replace('\n', ' ').translate(None, string.punctuation) while ' ' in text: text = text.replace(' ', ' ') clabel = row[clColIndex] colList['text'].append(text) colList['clabel'].append(int(clabel)) return colList def getMostFrequentWords(dataList, start = 0, length = 0): """ Returns the most frequently appeared words in the data Parameters ---------- dataList: dict(text: list(str), clabel: list(int)) The data to count unique words from start: int, optional Cut off the first start most frequent words length: int, optional The number of most frequent words to return from start Returns ------- List of strings that are the start-th to (start + length)-th most frequently used words """ splittedText = " ".join(dataList['text']).split(" ") if length == 0 or start + length > len(splittedText): length = max(0, len(splittedText) - start) dprt("Setting length to " + str(length)) uniqueWords = {} for keyword in splittedText: if keyword == '': continue uniqueWords[keyword] = uniqueWords.get(keyword, 0) + 1 lst = sorted(uniqueWords, key = uniqueWords.get, reverse = True) return lst[start:start + length] def classify(dataList, dictionary, limit = -1, start = 0): """ Constructs bag of words in binary format. The corresponding word will have 1 if the data has the word, or 0 if data does not have the word. Parameters ---------- dataList: dict(text: list(str), clabel: list(int)) The data to build on dictionary: listof(str) The dictionary to build on limit: int, optional To limit the number of row. Good for testing. -1 means no limit start: int Specify where to start building in from in dataList Returns ------- A key-value pair with word being the key and whether the word appeared in dictionary being value (0 = did not appear, 1 = appeared) """ bagOfWords = [] if start >= len(dataList['text']): dprt("Start >= length of datalist: " + str(start) + " >= " + str(len(dataList['text']))) return bagOfWords for i in range(start, len(dataList['text'])): if limit == 0: break else: limit -= 1 doc = dataList['text'][i] label = dataList['clabel'][i] docFeature = [] for word in dictionary: docFeature.append(1 if " " + word + " " in doc else 0) docFeature.append(1 if label == 5 else 0) docFeature.append(1 if label == 1 else 0) bagOfWords.append(docFeature) return bagOfWords
6220dffa7d908db306e8c55a56930ccdd2132b4e
srmishraqa/Python-For-Beginners-and-Selenium
/Comparison Operator/Example1.py
177
4.21875
4
temp = int(input("Enter the temperature : ")) if temp > 30 : print("It is a hot day") elif temp < 10: print("It is a cold Day") else: print("It is a pleasant day")
cb72c6160d6e2d0358aeb64a7118b098f0c3aa37
detcitty/100DaysOfCode
/python/2020/03-March/2020-03-22/intergerArray.py
518
3.796875
4
# https://www.codewars.com/kata/52a112d9488f506ae7000b95/train/python import re def is_int_array(arr): # your code here end_value = None if not arr: end_value = True else: for e in arr: regex_exp = "(\.)(\d*$)" test = re.search(regex_exp, str(e)) if(type(e) is not float or type(e) is not int or test.groups()[] is None): end_value = False break end_value = True return(end_value) is_int_array([1,2,3])
1a73a7cb6b6fbdc1ad35eb4befee3f04c0d0d5c8
daniel-reich/ubiquitous-fiesta
/HaxQfQTEpo7BFE5rz_12.py
257
3.53125
4
def alternate_pos_neg(lst): i = 0 k = 0 if lst.count(0): return False while i < len(lst): if lst[i] < 0: k += 1 i += 1 if i == len(lst): break if lst[i] > 0: k += 1 i += 1 return k == 0 or k == len(lst)
922434c86319eac24ca445fe1fb71082b5034c07
vortep72/python2
/05_circles.py
1,085
3.96875
4
class Circle: def __init__(self, center_coords, radius): self.center = center_coords self.radius = radius def intersect(self, other_circle): """ Проверяет пересекается ли текущая окружность с other_circle :return: True/False """ distance_center_circle = ((self.center[0] - other_circle.center[0]) ** 2 + (self.center[1] - other_circle.center[1]) ** 2) ** 0.5 sum_radius = self.radius + other_circle.radius if distance_center_circle <= sum_radius: return True else: return False # Окружности заданы координатами центров и радиусами circle1 = Circle((1, -1), 1) circle2 = Circle((1, 4), 4) # Задание: проверьте пересекаются ли данные окружности if circle1.intersect(circle2): print("Окружности пересекаются") else: print("Окружности НЕ пересекаются")
e887297e5608e0d8736bc3fa9ebf7e6449b30e51
GeekyMonk07/PythonProjects
/Project2/Project2.py
716
3.90625
4
import random randNumber = random.randint(1,100) # print (randNumber) guesses = 0 userGuess = None while(userGuess != randNumber): userGuess = int(input("Enter your Guess : ")) guesses += 1 if(userGuess == randNumber): print(f"Your Guess is Correct!") else: if(userGuess > randNumber): print("Wrong Guess! Enter a samller Number") else: print("Wrong Guess! Enter a larger Number") print(f"Your score is {guesses} guesses!") with open ("Project2/highscore.txt") as f: highscore = int(f.read()) if(guesses < highscore): print("You just broke the Highscore!!") with open ("Project2/highscore.txt",'w') as f: f.write(str(guesses))
83e2ebbe522303d992f2af4d0975d9a34b5c5ecf
tjkemp/gym-buy-high-sell-low
/gym_bhsl/math/average.py
1,137
4.28125
4
import itertools from typing import List, Sequence, Union import numpy as np def moving_average( values: Union[Sequence[float], Sequence[int]], window: int ) -> List[float]: """Calculate moving average. Args: values: a list of values for which to calculate average window: the length of window for which to calculate moving averages Returns: a list of floats of the size `values - windows + 1` Example: >>> moving_average([0, 0, 1, 2, 4, 5, 4], 3) [0.33333, 1.0, 2.33333, 3.66666, 4.33333] """ if window > len(values): raise ValueError("Window length must be less or equal to length of values") average = np.convolve(values, np.ones(window), "valid") / window return average.tolist() def right_average(values: Sequence[float], num_items: int) -> float: """Calculate average of `num_items` rightmost values in a sequence.""" if not 0 < num_items <= len(values): raise ValueError(f"Invalid value for average: {num_items}") return ( sum(itertools.islice(values, len(values) - num_items, len(values))) / num_items )
68f692eeeff3f8e3af93a9112b8e5538fa9e3e63
Thomas-j1/IN1000
/oblig1/beslutninger.py
359
3.90625
4
""" Spør om bruker vil ha brus og skriver ut svar basert på input """ jaEllerNei = input("Vil du ha brus, ja eller nei?: ") #ja eller nei input fra bruker if jaEllerNei == "ja": print("Her har du en brus!") elif jaEllerNei == "nei": print("Den er grei.") else: print("Det forstod jeg ikke helt") #skriver ut svar basert på ja eller nei input
f229d2d2bcdb2762464e087fc7b5b1d3dd8ce094
GitHubUPB/maicolrepositorio
/5.py
226
3.96875
4
n=int(input("ingrese el numero a estudio")) if ((n>0 and n%7!=0) and (n%2==0 and n%9!=0)) or (n%2!=0 and (n>100 and n<5000)) and (n%7!=0 or n%5==0): print("el numero es chevere") else: print("el numero no es chevere")
9fc43587c9b710b8f97688208904395e430962e0
rk280392/hackerrank_python
/fizzbuzz.py
343
3.640625
4
num = int(input("")) my_nums = [int(i) for i in input().split()] for i in range(1, my_nums[-1]+1): # if i%3 != 0 and i%5 !=0: # print(i) if i % 15 == 0: print("FizzBuzz") continue elif i % 3 == 0: print("Fizz") continue elif i % 5 == 0: print("Buzz") continue print(i)
9999f39402124771f4cc13fd377a7a724616126a
amanpanda/flex-your-sighs
/lexicon_generator.py
11,043
3.59375
4
from random import sample from numpy.random import choice from numpy.random import random import math from enum import Enum import pandas as pd import os MAX_CHOICE_SIZE = 100000000 # Approaches for homophones class HomophoneStrat(Enum): # max probability between homophones maxprob = 0 # add probabilities of homophones addprobs = 1 # treat homophones as competitors compete = 2 # Methods of selecting words in a sublexicon class LexModMethod(Enum): # graph doesn't change same = 0 # all nodes below given threshold frequency are removed threshold = 1 # given proportion of words are removed (uniformly random) random = 2 # words chosen using probability of having been seen given num word instances freqprob = 3 # words chosen using probability of encountering and remembering gien num word instances forgetting = 4 def lexicon_by_threshold(lexicon, freq_dict, threshold): """Removes all words in the lexicon with a frequency lower than 'threshold', returns the new lexicon """ l = [] for word in lexicon: if freq_dict[word] >= threshold: l.append(word) return l def remove_by_threshold(lexicon, freq_dict, threshold): """Removes all words in the lexicon with a frequency lower than 'threshold', returns the words to be removed from the full lexicon to create the new lexicon """ l = [] for word in lexicon: if freq_dict[word] <= threshold: l.append(word) return l def lexicon_by_random(pron, percentage): """Remove percentage*100% of the given lexicon pseudorandomly, returns the new lexicon """ pron = sample(pron, round(len(pron) * (1 - percentage))) return pron def remove_by_random(pron, percentage): """Remove percentage*100% of the given lexicon pseudorandomly, returns the list of words to remove from the full lexicon to create the new lexicon """ pron = sample(pron, round(len(pron) * (percentage))) return pron def lexicon_by_freqprob(lexicon, freq_dict, word_insts): """Generates a lexicon by randomly drawing word_insts words from the lexicon with replacement with weights directly proportional to their frequencies, and then removing duplicates. Loop is there to prevent memory error b/c of too large value given to numpy.random.choice() """ probabilities = [] total_freq = sum(freq_dict.values()) for word in lexicon: word_prob = freq_dict[word] / total_freq probabilities.append(word_prob) newlex = set() while word_insts > 0: if word_insts < MAX_CHOICE_SIZE: words_seen = choice(lexicon, word_insts, replace=True, p=probabilities) word_insts = 0 else: words_seen = choice(lexicon, MAX_CHOICE_SIZE, replace=True, p=probabilities) word_insts = word_insts - MAX_CHOICE_SIZE newlex.update(words_seen) newlex = list(newlex) return newlex def remove_by_freqprob(lexicon, freq_dict, word_insts): """Does the same thing as lexicon_by_freqprob except returns the words to remove from the full lexicon as opposed to the words to include """ newlex = lexicon_by_freqprob(lexicon, freq_dict, word_insts) for item in newlex: lexicon.remove(item) return lexicon def lexicon_by_forget(lexicon, freq_dict, word_insts, memory_stability): """Generates a lexicon by including each word with the probability that someone who encounters and remembers. Memory stability meaning: One unit of time is used to encounter word_insts number of words Memory stability is the amount of time needed to forget about 2 / 3 (63.2%) of the material This parameter might be subject to change. """ newlex = [] total_freq = sum(freq_dict.values()) for word in lexicon: word_prob = freq_dict[word] / total_freq if word_prob != 0: # Poisson process, expected number of events lmb = word_insts * word_prob + (random() * 2 - 1) * math.sqrt(word_insts * word_prob) # time from last refresh last_refresh = 1 / lmb + (random() * 2 - 1) * (2 / (l * l)) # forget curve prob_remem = math.exp(-last_refresh / memory_stability) else: prob_remem = 0 if random() <= prob_remem: newlex.append(word) return newlex def remove_by_forget(lexicon, freq_dict, word_insts, memory_stability): """Generates a lexicon by removing each word with the probability that someone who did not both encounter and remember. """ removelist = [] total_freq = sum(freq_dict.values()) for word in lexicon: word_prob = freq_dict[word] / total_freq if word_prob != 0: # Poisson process, expected number of events lmb = max(word_insts * word_prob + (random() * 2 - 1) * math.sqrt(word_insts * word_prob), 0) if lmb != 0: # time from last refresh last_refresh = 1 / lmb # forget curve. prob_remem = math.exp(-last_refresh / memory_stability) else: prob_remem = 0 else: prob_remem = 0 if random() >= prob_remem: removelist.append(word) return removelist def expected_overlap(lexicon, freq_dict, word_insts, homophone_strat): # expectation of sum of prob = sum of expectation of prob total_freq = sum(freq_dict.values()) expected_overlap = 0 # for word in freq_dict: for word in lexicon: # pr = prob(w drawn once, its freq prob) word_prob = freq_dict[word] / total_freq if word_prob != 0: # prob(w not drawn once) = 1 - pr # prob(w not in lexicon 1) = prob(w not drawn once)^word_insts # prob(w in lexicon 1) = 1 - prob(w not in lexicon 1) prob_in_lexicon = 1 - ((1 - word_prob) ** word_insts) # prob(w in lexicon 1 and lexicon 2) = prob(w in lexicon 1)^2 prob_in_both = prob_in_lexicon ** 2 # prob(w in lexicon 1 or lexicon 2) = 1 - prob(w not in lexicon 1)^2 prob_in_either = 1 - ((1 - prob_in_lexicon) ** 2) if prob_in_either == 0: print(prob_in_lexicon, prob_in_both, prob_in_either) return 0 # expected probability of overlap = prob(w in both) / prob(w in either) # sum the above value over all words to get expected overlap size! expected = (prob_in_both) else: expected = 0 expected_overlap += expected if homophone_strat == 0: homophone = "use max frequency" elif homophone_strat == 1: homophone = "use sum frequency" else: homophone = "treat as competitor" print("Expected overlap using homophone strategy -", homophone, ":", expected_overlap) def get_freq_dict(homophone_strat, data, frequencies): # calculate frequency only based on SUBTLEX freq_dict = {} for i in range(len(data)): log_freq = frequencies[i] if not math.isnan(log_freq): log_freq = round(math.pow(10, log_freq)) else: log_freq = 0 if data['Pron'][i] in freq_dict: if homophone_strat == HomophoneStrat.maxprob.value: freq_dict[data['Pron'][i]] = max(log_freq, freq_dict[data['Pron'][i]]) elif homophone_strat == HomophoneStrat.addprobs.value: freq_dict[data['Pron'][i]] = log_freq + freq_dict[data['Pron'][i]] elif homophone_strat == HomophoneStrat.compete.value: homophone_num = 1 while (data['Pron'][i] + ":" + str(homophone_num)) in freq_dict: homophone_num += 1 freq_dict[(data['Pron'][i] + ":" + str(homophone_num))] = log_freq else: freq_dict[data['Pron'][i]] = log_freq return freq_dict def get_lexicon(method, strat_parameter, homophone_strat, data, frequencies): """Returns a lexicon from a csv and optionally alters the lexicon method: value of LexModMethod Enum associated with lexicon modification methods (LexModMethod.same, LexModMethod.threshold, LexModMethod.random, LexModMethod.freqprob, LexModMethod.forgetting) to get the enum, use LexModMethod(method) strat_parameter: value associated with method - threshold: threshold frequency - random: proportion of words to removed - freqprob, forgetting: number of word instances homophone_strat: value of HomophoneStrat Enum associated with homophone strategy (HomophoneStrat.maxprob, HomophoneStrat.addprobs, HomophoneStrat.compete) to get the enum, use HomophoneStrat(homophone_strat) Returns a list of all the words in the generated lexicon """ # if an enum is passed in, converts to appropriate int if isinstance(method, Enum): method = method.value if isinstance(homophone_strat, Enum): homophone_strat = method.value # gets dictionary where keys: word pronunciations and values: frequencies freq_dict = get_freq_dict(homophone_strat, data, frequencies) # delete repeated words if not treating homophones as competitors # pron is a list containing all the words in the full lexicon if homophone_strat != HomophoneStrat.compete.value: pron = list(set(data['Pron'])) else: pron = list(freq_dict.keys()) if method == LexModMethod.threshold.value: pron = remove_by_threshold(pron, freq_dict, strat_parameter) elif method == LexModMethod.random.value: pron = remove_by_random(pron, strat_parameter) elif method == LexModMethod.freqprob.value: pron = remove_by_freqprob(pron, freq_dict, strat_parameter) elif method == LexModMethod.forgetting.value: pron = remove_by_forget(pron, freq_dict, strat_parameter, 1) return pron def get_spanish_data(): # import data freq_data = pd.read_csv(os.path.join(os.path.dirname(__file__), 'datasets/spanish/nwfreq.txt'), sep="\t", header=None, encoding='latin-1') freq_data.columns = ["word", "freq"] pron_data = pd.read_csv(os.path.join(os.path.dirname(__file__), 'datasets/spanish/nwphono.txt'), sep="\t", header=None, encoding='latin-1') pron_data = pron_data.iloc[:, 0:2] pron_data.columns = ["word", "pron"] # get rid of dashes in pron, which are syllable markers pron_data['pron'] = pron_data['pron'].str.replace('-', '') full_data = pd.merge(freq_data, pron_data, on='word') return full_data def get_spanish_lexicon(): """Returns a Spanish lexicon, in the same format as the get_lexicon function returns. Mostly temporary, need to make the other functions so things aren't hardcoded. """ data = get_spanish_data() pron = list(data['pron']) # do the homophone stuff return pron
19d589356891d58c1ccc185f0a69ad4be5e78166
Dmitry-White/HackerRank
/Python/Sets/captains_room.py
983
3.546875
4
""" Created on Wed Aug 09 23:34:11 2017 @author: Dmitry White """ # TODO: Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms. # One fine day, a finite number of tourists come to stay at the hotel. # The tourists consist of: # A Captain. # An unknown group of families consisting of K members per group where K ≠ 1. # The Captain was given a separate room, and the rest were given one room per group. # Mr. Anant has an unordered list of randomly arranged room entries. # The list consists of the room numbers for all of the tourists. # The room numbers will appear K times per group except for the Captain's room. # Mr. Anant needs you to help him find the Captain's room number. # The total number of tourists or the total number of groups of families is not known to you. # You only know the value of K and the room number list. n = int(input()) s = list(map(int,input().split())) set_s = set(s) print((sum(set_s)*n - sum(s))//(n-1))
a7ea2bf6fd5fc18c69cb3d8d756253f34960c474
Lckythr33/CodingDojo
/src/python_stack/flask/flask_fundamentals/hello_flask/routing.py
986
3.671875
4
from flask import Flask # Import Flask to allow us to create our app app = Flask(__name__) # Create a new instance of the Flask class called "app" @app.route('/') # The URL FOR BROWSER AFTER LOCALHOST:5000/ def hello_world(): return 'Hello World!' # Return the string 'Hello World!' as a response @app.route('/dojo') # The URL FOR BROWSER AFTER LOCALHOST:5000/ def dojo(): return 'Dojo!' # Return the string 'Hello World!' as a response @app.route('/say/<name>') # for a route '/hello/____' anything after '/hello/' gets passed as a variable 'name' def hello(name): print(name) return "Hello, " + name @app.route('/repeat/<num>/<word>') def repeatWord(num, word): return int(num) * word @app.errorhandler(404) def page_not_found(e): return "Sorry! No Response. Try Again!." if __name__=="__main__": # Ensure this file is being run directly and not from a different module app.run(debug=True) # Run the app in debug mode.
6c41f22826846d6259a987dd0f633ce3ce89b8ff
19mateusz92/pythonPrograms
/lista3/palindrom.py
369
3.84375
4
#!/usr/bin/env python3 def function(word): head=0 tail=len(word)-1 while(head < tail): if word[head]==word[tail]: head+=1 tail-=1 else: return False return True word=(input("wpisz łańcuch znaków aby sprawdzić czy jest palindromem:\n")) print(function(word))
94f85d6d2404c97b8b55f74fb0ac810be2b8b389
WilliamYi96/Machine-Learning
/DS-Python-Implementations/Basic/stack/divideBy2.py
321
3.703125
4
from pythonds.basic.stack import Stack def divideBy2(decimal): s = Stack() while decimal > 0: number = decimal % 2 s.push(number) decimal = decimal // 2 final = "" while not s.isEmpty(): final += str(s.pop()) return final print(divideBy2(15)) print(divideBy2(8))
3ee3e1a26d4136b5913c8211a76e75f5beb021dc
Aminaba123/Solving-problems-in-python
/List Problems.py
11,195
4.34375
4
# Python Expression Results Description len([1, 2, 3]) 3 Length [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition 3 in [1, 2, 3] True Membership for x in [1, 2, 3]: print x, 1 2 3 Iteration # Difference between append vs. extend list methods in Python? # What's the difference between the list methods append() and extend()? # append adds an element to a list, and extend concatenates the first list with another list (or another iterable, not necessarily a list.) append: Appends object at the end. x = [1, 2, 3] x.append([4, 5]) print (x) gives you: [1, 2, 3, [4, 5]] extend: Extends list by appending elements from the iterable. x = [1, 2, 3] x.extend([4, 5]) print (x) gives you: [1, 2, 3, 4, 5] ################################################################################## # How do I check if a list is empty? if len(li) == 0: print('the list is empty') # Using the implicit booleanness of the empty list is quite pythonic if not a: print("List is empty") ################################################################################## # How to concatenate two lists in Python? listone = [1, 2, 3] listtwo = [4, 5, 6] You can use the + operator to combine them mergedlist = listone + listtwo [1,2,3,4,5,6] ################################################################################## a = [[1,2,3], [4,5,6], [7,8,9]] [x for xs in a for x in xs] -- [1, 2, 3, 4, 5, 6, 7, 8, 9] map(str, (x for xs in a for x in xs)) ['1', '2', '3', '4', '5', '6', '7', '8', '9'] ################################################################################## a = [1, 2, 3] b = [4, 5, 6] c = a + b c = [] a = [1, 2, 3] b = [4, 5, 6] c += (a + b) ################################################################################## # Finding the index of an item given a list containing it in Python ["foo", "bar", "baz"].index("bar") --1 [i for i, e in enumerate([1, 2, 1]) if e == 1] -- [0, 2] for i, j in enumerate(['foo', 'bar', 'baz']): if j == 'bar': print(i) # As a list comprehension: [i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'bar'] ################################################################################## # Getting the last element of a list in Python # How can I count the occurrences of a list item? # If you only want one item's count, use the count method: [1, 2, 3, 4, 1, 4, 1].count(1) --3 dict((i,a.count(i)) for i in a) # is really, really slow for large lists. My solution def occurDict(items): d = {} for i in items: if i in d: d[i] = d[i]+1 else: d[i] = 1 return d #################### import time from collections import Counter def countElement(a): g = {} for i in a: if i in g: g[i] +=1 else: g[i] =1 return g #################### a = [1,2,3,45,6,7,7,8,9,99,2,0,8,0,0,2,111,2,2] countElement(a) {0: 3, 1: 1, 2: 5, 3: 1, 6: 1, 7: 2, 8: 2, 9: 1, 45: 1, 99: 1, 111: 1} a = [1,2,3,45,6,7,7,8,9,99,2,0,8,0,0,2,111,2,2,"salaa"] countElement(a) {0: 3, 1: 1, 2: 5, 3: 1, 6: 1, 7: 2, 8: 2, 9: 1, 45: 1, 99: 1, 111: 1, 'salaa': 1} ################################################################################## # Accessing the index in 'for' loops? for idx, val in enumerate(ints): print(idx, val) # Use enumerate to get the index with the element as you iterate: for index, item in enumerate(items): print(index, item) index = 0 # Python's indexing starts at zero for item in items: # Python's for loops are a "for each" loop print(index, item) index += 1 index = 0 while index < len(items): print(index, items[index]) index += 1 for index in range(len(items)): print(index, items[index]) # Old fashioned way: for ix in range(len(ints)): print ints[ix] # List comprehension: [ (ix, ints[ix]) for ix in range(len(ints))] # It's pretty simple to start it from 1 other than 0: for index, item in enumerate(iterable, start=1): print index, item for i in range(len(ints)): print i, ints[i] ################################################################################## enumerate(): S = [1,30,20,30,2] for index, elem in enumerate(S): print(index, elem) ################################################################################## # How do I remove an element from a list by index in Python? # Use del and specify the index of the element you want to delete: a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] del a[-1] a = ['a', 'b', 'c', 'd'] a.pop(1) a = [1, 2, 3, 4, 5, 6] index = 3 # Only positive index a = a[:index] + a[index+1 :] # a is now [1, 2, 3, 5, 6] ############################################## a = ['a', 'b', 'c', 'd'] def remove_element(list_,index_): clipboard = [] for i in range(len(list_)): if i is not index_: clipboard.append(list_[i]) return clipboard print(remove_element(a,2)) ################################################################################## # How to read a file line-by-line into a list? with open(fname) as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] with open('filename') as f: lines = f.readlines() lines = [line.rstrip('\n') for line in open('filename')] ########################################### with open("file.txt", "r") as ins: array = [] for line in ins: array.append(line) ########################################### lines = tuple(open(filename, 'r')) with open("myfile.txt", encoding="utf-8") as file: x = [l.strip() for l in file] x = [] with open("myfile.txt") as file: for l in file: x.append(l.strip()) ################################################################################## # How to clone or copy a list? b = a[:] b = a.copy() b = []; b.extend(a) b = a[0:len(a)] b, = a b = list(a) b = [i for i in a] b = copy.copy(a) b = [] for item in a: b.append(item) newList = oldList[:] ################################################################################## # How to trim a list in Python # Suppose I have a list with X elements # [4,76,2,8,6,4,3,7,2,1...] [1,2,3,4,5,6,7,8][:5] [1, 2, 3, 4, 5] [1,2,3][:5] [1, 2, 3] x = [6,7,8,9,10,11,12] x[:5] [6, 7, 8, 9, 10] # To trim a list in place without creating copies of it, use del: t = [1, 2, 3, 4, 5] # delete elements starting from index 4 to the end del t[4:] t [1, 2, 3, 4] del t[5:] t [1, 2, 3, 4] range(10)[3::2] => [3, 5, 7, 9] test[3:] = [3, 4, 5, 6, 7, 8, 9] test[:3] = [0, 1, 2] print(mylist[len(mylist) - 1]) ################################################################################## # Break A List Into N-Sized Chunks # Create a list of first names first_names = ['Steve', 'Jane', 'Sara', 'Mary','Jack','Bob', 'Bily', 'Boni', 'Chris','Sori', 'Will', 'Won','Li'] # Create a function called "chunks" with two arguments, l and n: def chunks(l, n): # For item i in a range that is a length of l, for i in range(0, len(l), n): # Create an index range for l of n items: yield l[i:i+n] # Create a list that from the results of the function chunks: list(chunks(first_names, 5)) #################################################################################### # Basic List Operations Python Expression Results Description len([1, 2, 3]) 3 Length [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition 3 in [1, 2, 3] True Membership for x in [1, 2, 3]: print x, 1 2 3 Iteration ############################# Indexing, Slicing, and Matrixes ########################## L = ['spam', 'Spam', 'SPAM!'] Python Expression Results Description L[2] SPAM! Offsets start at zero L[-2] Spam Negative: count from the right L[1:] ['Spam', 'SPAM!'] Slicing fetches sections ######## Built-in List Functions & Methods ######## # cmp(list1, list2) # Compares elements of both lists. # len(list) # Gives the total length of the list. # max(list) # Returns item from the list with max value. # list(seq) # Converts a tuple into list. # list.append # Appends object obj to list # list.count # Returns count of how many times obj occurs in list # list.extend # list.index # list.insert # list.pop # Removes and returns last object or obj from list # list.remove # Removes object obj from list # list.reverse() # Reverses objects of list in place # list.sort # Sorts objects of list, use compare func if given ############################################################################################################ xyz_list = frag_str.split() nums = [] coords = [] for i in range(int(len(xyz_list)/4)): nums.append(xyz_list[i*4]) coords.append(xyz_list[i*4+1:(i+1)*4]) nums = np.concatenate(nums) coords = np.concatenate(coords) ############################################################################################################ L = [1, 2, 3, 4, 5, 6, 7] li = [] count = 0 for i in L: if count % 2 == 1: li.append(i) count += 1 ############################################################################################################ some_list[start:stop:step] ############################################################################################################ def chunk(iterable, chunk_size): """Generate sequences of `chunk_size` elements from `iterable`.""" iterable = iter(iterable) while True: chunk = [] try: for _ in range(chunk_size): chunk.append(iterable.next()) yield chunk except StopIteration: if chunk: yield chunk break ############################################################################################################ arr[nr:nr+b.shape[0], 1:] = b ############################################################################################################ import numpy as np #Create a numpy array np_arr = np.array([1,2,3,4,5]) #change the contents index = 0 while index < np_arr.size: np_arr[index] = 100 index += 1 #Iterate and display for item in np_arr: print(item) ############################################################################################################
c11337de191b01d582d9cefe66fd608bfe81ae9f
Siddhantham/pythonAssg
/seventeenTableInReverse.py
151
3.515625
4
lis = [] for i in range(1,21): lis.append("17 * "+ str(i) + " = " + str(17*i) ) lis = lis[::-1] for i in range(len(lis)): print(lis[i])
eaa752f05c580d4796449482a0ea3698910940f3
gauravssnl/python3-network-programming
/echo_server.py
1,835
3.859375
4
import socket host = 'localhost' data_payload = 2048 backlog = 5 # we need to define encode function for converting string to bytes string # this will be use for sending/receiving data via socket encode = lambda text: text.encode() # we need to define deocde function for converting bytes string to string # this will convert bytes string sent/recieved via socket to string decode = lambda byte_text: byte_text.decode() def echo_server(port): # create a TCP socket sock = socket.socket() # enable reuse address/port sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bind socket to port server_address = (host, port) print("Starting up echo server on %s port %s" % server_address) sock.bind(server_address) # Listen to clients,backlog argument specifies the maximum number of # queued connections sock.listen(backlog) while True: print("Waiting to receive message from client") client, addr = sock.accept() print("Connected client :{}".format(addr)) data = client.recv(data_payload) if data: # decode is used to convert bytes string to string data = decode(data) print("Data Received from client : {}".format(data)) # encode is used to convert string to bytes string # required by send function client.send(encode(data)) print("Data sent back to client : {}".format(data)) # end connection client.close() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Socket echo Server Example') parser.add_argument("--port", action="store", dest="port", type=int, required=True) given_args = parser.parse_args() port = given_args.port echo_server(port)
c6ed7d9bc9ae3a9cd3272b029dea3a61792ade6d
priyankasomani9/basicpython
/Assignment12/basic12.1_findUniqeValue.py
627
3.8125
4
from itertools import chain test_dict = {'gfg' : [5, 6, 7, 8], 'is' : [10, 11, 7, 5], 'best' : [6, 12, 10, 8], 'for' : [1, 2, 5]} print("The original dictionary is : " + str(test_dict)) res = list(sorted({ele for val in test_dict.values() for ele in val})) print("The unique values list is : " + str(res)) #way2 res1 = list(sorted(set(chain(*test_dict.values())))) print("The unique values list is : " + str(res1)) #way3 dict = {'511':'Vishnu','512':'Vishnu','513':'Ram','514':'Ram','515':'sita'} list=[] for val in dict.values(): if val in list: continue else: list.append(val) print(list)
51a5058c4b9cd5cad24874c74727b864e9899675
sfdye/leetcode
/all-possible-full-binary-trees.py
734
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def allPossibleFBT(self, N): """ :type N: int :rtype: List[TreeNode] """ def build(N): if N == 1: yield TreeNode(0) else: for i in range(1, N, 2): for left in build(i): for right in build(N - i - 1): root = TreeNode(0) root.left = left root.right = right yield root return list(build(N))
376db44884f242b57fae2f055ee34cbd8567daa1
daisypandey/Assignment_05
/CDInventory.py
3,312
3.859375
4
#------------------------------------------# # Title: CDInventory.py # Desc: Use dictionaries as the inner data type (list of dictionaries) # Allows the user to load inventory from file, add CD data, view the current inventory, # delete CD from inventory, save data to a text file, and exit the program. # Change Log: (Who, When, What) # Daisy Pandey, August 9, 2020, Assignment 5: CD Inventory Script # Daisy Pandey, August 11, 2020, updated code as suggested from code review #------------------------------------------# # Declare variables dicRow = {} # dic of data row lstTbl = [] # list of dictionaries to hold data strChoice = '' # User input strFileName = 'CDInventory.txt' # data storage file objFile = None # file object # Get user Input print('The Magic CD Inventory\n') while True: # Display menu allowing the user to choose: print() print('[l] load Inventory from file\n[a] Add CD\n[i] Display Current Inventory') print('[d] delete CD from Inventory\n[s] Save Inventory to file\n[x] exit') strChoice = input('l, a, i, d, s or x: ').lower() # convert choice to lower case at time of input print() if strChoice == 'x': # Exit the program if the user chooses to break if strChoice == 'l': # Load existing data lstTbl.clear() objFile = open(strFileName, 'r') for row in objFile: lstRow = row.strip().split(',') dicRow = {'id': int(lstRow[0]), 'title': lstRow[1], 'artist': lstRow[2]} lstTbl.append(dicRow) print(row) print('Above are the items loaded from the file into the memory.') objFile.close() elif strChoice == 'a': # Add data to the table (list of dictionaries) each time the user wants to add data cdId = int(input('Enter an ID: ')) cdTitle = input('Enter the CD\'s Title: ') cdArtistName = input('Enter the Artist\'s Name: ') dicRow = {'id':cdId, 'title': cdTitle, 'artist': cdArtistName} lstTbl.append(dicRow) elif strChoice == 'i': # Display the current data to the user each time the user wants to display the data print('ID, CD Title, Artist') for row in lstTbl: print(*row.values(), sep = ', ') elif strChoice == 'd': # Delete an entry from inventory delEntry = int(input('What entry do you want to delete? ')) for entry in range(len(lstTbl)): if lstTbl[entry]['id'] == delEntry: del lstTbl[entry] print() print('Your entry is deleted from inventory.') break elif strChoice == 's': # Save the data to a text file CDInventory.txt if the user chooses so objFile = open(strFileName, 'a') for row in lstTbl: strRow = '' for item in row.values(): strRow += str(item) + ',' strRow = strRow[:-1] + '\n' objFile.write(strRow) print('Your data has been saved to the file.') objFile.close() else: print('Please choose either l, a, i, d, s or x!')
6b9520223f9866409c7bccf3c07bd13bf28c5104
OneDayOneCode/1D1C_Agosto
/sumayproducto.py
779
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Calcular e imprimir la suma de 1+2+3+4+5+6.......+50 # Asignamos a una variable el rango del 1 - 51, osea los primeros 50 números r = range(1, 51) # Con la función sum se suman los números de una lista print sum(r), "Es el resultado de sumar del 1 al 50, uno a uno!" # Calcular e imprimir el producto 1*2*3*4*5...*50 #Declaramos dos variables n = 1 h = 1 # Con un ciclo while hacemos lo siguiente.. while n <= 10: # Mientras n sea menor o igual a 20 entonces... # Multiplicamos h por el valor de n durante cada recorrido del ciclo h *= n # Ahora a la variable n le sumamos 1 y continua el ciclo n += 1 # Al final se imprime el nuevo valor de h print "El resultado de multiplicar del 1 al 50 uno a uno no da.. ", h
8a882bc3b46bae87fe0dae7835dddb7fd8ac8f9c
csufangyu/study_sklearn
/ch3/贝叶斯分类.py
5,525
3.546875
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 13 21:27:15 2017 @author: Thinkpad 主要是介绍贝叶斯分类器 1.高斯贝叶斯分类器 class sklearn.naive_bayes.GaussianNB 高斯贝叶斯分类器没有参数 2.多项式贝叶斯分类器 class sklearn.naive_bayes.MultinomialNB(alpha=1.0,fit_prior=True,class_prior=None) 参数含义如下: alpha:一个浮点数,指定alpha的值 fit_prior:布尔值,如果为Ture,则不用去学习P(y=ck),以均匀分布替代,否则则去学习P(y=ck) class_prior:一个数组。它指定了每个分类的先验概率P(y=c1),P(y=c2).....,若指定了该参数 则每个分类的先验概率无需学习 伯努利贝叶斯分类器 class sklearn.naive_bayes.BernoulliNB(alpha=1.0,binarize=0.0,fit_prior=Ture, class_prior=None) 参数含义如下: alpha:一个浮点数,指定alpha的值 binarize:一个浮点数或者None 如果为浮点数则以该数值为界,特征值大于它的取1,小于的为0 如果为None,假定原始数据已经二值化 fit_prior:布尔值,如果为Ture,则不用去学习P(y=ck),以均匀分布替代,否则则去学习P(y=ck) class_prior:一个数组。它指定了每个分类的先验概率P(y=c1),P(y=c2).....,若指定了该参数 则每个分类的先验概率无需学习 """ from sklearn import datasets,cross_validation,naive_bayes import numpy as np import matplotlib.pyplot as plt def show_digits(): digits=datasets.load_digits() fig=plt.figure() print('vector from image 0:',digits.data[0]) for i in range(25): ax=fig.add_subplot(5,5,i+1) ax.imshow(digits.images[i],cmap=plt.cm.gray_r,interpolation='nearest') plt.show() def load_data(): digits=datasets.load_digits() return cross_validation.train_test_split(digits.data,digits.target,test_size=0.25, random_state=0) #用高斯分类器来查看效果 def test_GaussianNB(*data): X_train,X_test,y_train,y_test=data cls=naive_bayes.GaussianNB() cls.fit(X_train,y_train) print("training score:%.2f"%(cls.score(X_train,y_train))) print("testing score:%.2f"%(cls.score(X_test,y_test))) #测试多项式贝叶斯分类器 def test_MultinomialNB(*data): X_train,X_test,y_train,y_test=data cls=naive_bayes.MultinomialNB() cls.fit(X_train,y_train) print("training score:%.2f"%(cls.score(X_train,y_train))) print("testing score:%.2f"%(cls.score(X_test,y_test))) #检验不同alpha值对于分类结果的影响 def test_MultinomialNB_alpha(*data): X_train,X_test,y_train,y_test=data alphas=np.logspace(-2,5,num=200) training_score=[] testing_score=[] for alpha in alphas: cls=naive_bayes.MultinomialNB(alpha=alpha) cls.fit(X_train,y_train) training_score.append(cls.score(X_train,y_train)) testing_score.append(cls.score(X_test,y_test)) #绘图 fig=plt.figure() ax=fig.add_subplot(1,1,1) ax.plot(alphas,training_score,label="training score") ax.plot(alphas,testing_score,label="testing score") ax.set_xlabel('alpha') ax.set_ylabel('score') ax.set_title("MultinomoalNB") ax.set_xscale("log") plt.show() #查看伯努利分类器效果 def test_BernoulliNB(*data): X_train,X_test,y_train,y_test=data cls=naive_bayes.BernoulliNB() cls.fit(X_train,y_train) print("training score:%.2f"%(cls.score(X_train,y_train))) print("testing score:%.2f"%(cls.score(X_test,y_test))) ## 查看不同alpha值的影响 def test_BernoulliNB_alpha(*data): X_train,X_test,y_train,y_test=data alphas=np.logspace(-2,5,num=200) training_score=[] testing_score=[] for alpha in alphas: cls=naive_bayes.BernoulliNB(alpha=alpha) cls.fit(X_train,y_train) training_score.append(cls.score(X_train,y_train)) testing_score.append(cls.score(X_test,y_test)) #绘图 fig=plt.figure() ax=fig.add_subplot(1,1,1) ax.plot(alphas,training_score,label="training score") ax.plot(alphas,testing_score,label="testing score") ax.set_xlabel('alpha') ax.set_ylabel('score') ax.set_title("BerbuonlliNB") ax.set_xscale("log") plt.show() ##查看不同阙值的影响 def test_BernoulliNB_binarize(*data): X_train,X_test,y_train,y_test=data min_x=min(np.min(X_train.ravel()),np.min(X_test.ravel()))-0.1 max_x=max(np.max(X_train.ravel()),np.max(X_test.ravel()))-0.1 binarizes=np.linspace(min_x,max_x,endpoint=True,num=100) training_score=[] testing_score=[] for binarize in binarizes: cls=naive_bayes.BernoulliNB(binarize=binarize) cls.fit(X_train,y_train) training_score.append(cls.score(X_train,y_train)) testing_score.append(cls.score(X_test,y_test)) ##绘图 fig=plt.figure() ax=fig.add_subplot(1,1,1) ax.plot(binarizes,training_score,label="training score") ax.plot(binarizes,testing_score,label="testing score") ax.set_xlabel('binarize') ax.set_ylabel('score') ax.set_title("BerbuonlliNB") plt.show() if __name__=="__main__": #show_digits() X_train,X_test,y_train,y_test=load_data() #test_GaussianNB(X_train,X_test,y_train,y_test) #test_MultinomialNB(X_train,X_test,y_train,y_test) #test_MultinomialNB_alpha(X_train,X_test,y_train,y_test) #test_BernoulliNB_alpha(X_train,X_test,y_train,y_test) test_BernoulliNB_binarize(X_train,X_test,y_train,y_test)
a716329fcd26f3b327e81ce6a0b94d5b4c00b0b7
neelrshah/Infinity-Coders-YouTube---Python-Course
/04_Strings/04_Strings.py
800
4.53125
5
# String Basics # Creating a String # s = "Python" # Printing a String # print(s) # String Concatenation # s1 = "hello" # s2 = "world" # print(s1 + s2) # Indexing and accessing elements of String # s = "Python" # print(s[0]) # print(s[-1]) # Slicing of String # s = "hello world" # # s[start : ending : gaps] # print(s[0:5]) # print(s[:-3]) # print(s[::2]) # in-biuld Strings functions # lower(), upper(), swapcase(), isupper(), islower(), capitalize(), len(), # isdigit(), isalnum(), isalpha() s = "python" # print(s.upper()) # print(s.lower()) # s2 = "PytHoN" # print(s2.swapcase()) # print(s.isupper()) # print(s.islower()) # print(s.capitalize()) # print(len(s)) s1 = "123" s2 = "AB12" s3 = "abc" print(s1.isdigit()) print(s3.isalpha()) print(s2.isalnum())
8031a6a131724ac3ad993a8b23e8541f97c2594b
BusgeethPravesh/Python-Files
/Question4.py
323
3.6875
4
"""Write a Python program that will find the L.C.M. of two input number.""" a=int(input("Enter the first number:")) b=int(input("Enter the second number:")) if(a > b): min1= a else: min1= b while True: if(min1 % a==0 and min1 % b==0): print("LCM is:",min1) break min1+=1
a107d95779001e88f8f2944c502262ae6deea318
afossey/codingame-solutions
/difficulty_average/aneo.py
1,031
3.65625
4
import sys import math # https://www.codingame.com/ide/puzzle/aneo speed = int(input()) light_count = int(input()) distances = [] durations = [] for i in range(light_count): distance, duration = [int(j) for j in input().split()] distances.append(distance) durations.append(duration) # Write an answer using print # To debug: print("Debug messages...", file=sys.stderr, flush=True) print(str(speed) + " " + str(light_count) + " " + str(distances) + " " + str(durations), file=sys.stderr, flush=True) def isLightGreen(i, seconds): lightIsGreen = True for second in range(1, seconds + 1): if (second % durations[i]) == 0: lightIsGreen = not lightIsGreen return lightIsGreen def allLightsGreen(s): for light in range(light_count): d = (distances[light] * 3600) / (s * 1000) if not isLightGreen(light, math.floor(d)): return False return True for s in reversed(range(1, speed + 1)): if allLightsGreen(s): print(str(s)) break
ddb9df0ab7147905f47eb3d40e925a2b62b3efde
bawejakunal/hackerrank
/ctci-connected-cell-in-a-grid.py
1,466
3.5625
4
""" https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid """ from collections import deque def isValidCell(grid, r, c): return not (r < 0 or r >= len(grid) or c < 0 or c >= len(grid[r]) or grid[r][c] != 1) def dfsGetSize(grid, r, c): if not isValidCell(grid, r, c): return 0 s = 1 grid[r][c] = -1 # mark visited for y in range(r-1, r+2): for x in range(c-1, c+2): s += dfsGetSize(grid, y, x) return s def bfsGetSize(grid, r, c): if not isValidCell(grid, r, c): return 0 q = deque() s = 0 grid[r][c] = -1 q.append((r, c)) while len(q) > 0: y, x = q.popleft() s += 1 # add neigbors to queue for _y in range(y-1, y+2): for _x in range(x-1, x+2): if isValidCell(grid, _y, _x): grid[_y][_x] = -1 q.append((_y, _x)) return s def getBiggestRegion(grid): bigr = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == 1: bigr = max(bigr, dfsGetSize(grid, r, c)) return bigr def main(): n = int(input().strip()) m = int(input().strip()) grid = [] for grid_i in range(n): grid_t = list(map(int, input().strip().split(' '))) grid.append(grid_t) print(getBiggestRegion(grid)) if __name__ == '__main__': main()
2e3087ee441641dc9cb3b50ac52eb5df84211577
miaomiao-chong/py
/py_admin/adminUser.py
3,145
3.609375
4
import search import insert import handleUserTable import update import delete def adminUser(): while 1: print(''' 1.查询操作(单表查询、打印全表、复杂查询) 2.建立新表/删除新表(管理员用户/普通用户表) 3.插入学生数据/选课信息/管理员用户/普通用户 4.更改学生专业信息/成绩信息/用户密码 5.删除学生相关信息/管理员用户/普通用户 ''' ) choose=input("输入要选择的功能") if choose == '1': print(" 查询操作子界面") print(" ========================") print(''' 1.单表查询 2.查询特定学生的选课信息 3.查询特定学院/专业的所有学生 4.查询小于60分的所有学生 5.查询选修了某门课的所有学生的信息及成绩 6.查询某姓的所有学生 7.打印全表 ''') a=eval(input()) search.search(a) elif choose == '2': print(" 建表/删表子界面(管理员用户表与普通用户表)") print(" ========================") print(''' 1.建表 2.删表 ''') a = eval(input()) if a==1: adminOrPutong=eval(input("新建哪个表? 1:管理员 2:普通用户")) handleUserTable.createUserTable(adminOrPutong) if a==2: adminOrPutong = eval(input("删除哪个表? 1:管理员 2:普通用户")) handleUserTable.dropUserTable(adminOrPutong) elif choose == '3': print(" 插入操作子界面") print(" ========================") print(''' 1.增加学生数据 2.增加选课信息 3.增加管理员用户 4.增加普通用户 ''') a = eval(input()) insert.insert(a) elif choose=='4': print(" 更改操作子界面") print(" ========================") print(''' 1.更改学生专业信息 2.更改学生成绩信息 3.更改管理员用户密码 4.更改普通用户密码 ''') a = eval(input()) update.update(a) elif choose == '5': print(" 删除操作子界面") print(" ========================") print(''' 1.删除学生信息 2.删除管理员用户 3.删除普通用户 ''') a = eval(input()) delete.delete(a) choose=-1 # 实现子功能的循环执行 a = input("输入0退出,其他键继续") if a == '0': break print("跳出循环了")
c732a4ed4ac2130b49873302f77aec52b514ec6e
FrancescoSRende/FrancescoSRende.github.io
/Python Contest Questions/iterativeBinarySearch.py
1,942
4.0625
4
# Returns index of x in arr if present, else -1 def binary_search(arr, low, high, x): # Check base case if high >= low: mid = (high + low) // 2 # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it can only # be present in left subarray elif arr[mid] > x: return binary_search(arr, low, mid - 1, x) # Else the element can only be present in right subarray else: return binary_search(arr, mid + 1, high, x) else: # Element is not present in the array return -1 arr = [2, 3, 4, 10, 40] x = 10 # Function call result = binary_search(arr, 0, len(arr)-1, x) if result != -1: print("Element is present at index", str(result)) else: print("Element is not present in array") def binarySearchMario(A, x): c = sorted(A) left = 0 right = len(A) - 1 while left <= right: middle = int((left + right) / 2) if x == A[middle]: return middle elif x < A[middle]: right = middle - 1 else: left = middle + 1 def binarySearchMiskew(a, value): left = 0 right = len(a) - 1 while(left <= right): middle = (left + right) // 2 if (a[middle] < value): left = middle + 1 elif (a[middle] > value): right = middle - 1 else: return middle return -1 # -1 is an invalid index, so if it is returned, we know that we havent found the object # def myBinarySearch(n, arr): # arr = arr.sort() # high = len(arr)-1 # low = 0 # mid = (high + low) // 2 # while mid > 0: # if arr[mid] == n: # return mid # elif n > arr[mid]: # mid = (high + mid) // 2 # elif n < arr[mid]: # mid = (low + mid) // 2
26c65904c7f729e071633dffeb9e14f2da51ad99
lmdiazangulo/hopfions
/anim.py
562
3.609375
4
#Este codigo abre "1D.h5", generado por "1Dh5.py" y muestra una animacion import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as ani import h5py as h5 #Open h5 file fin = h5.File('1D.h5','r') N = fin.attrs['N'] iterations = fin.attrs['iterations'] L = 10 x = np.linspace(0,L,N+1) Ex = fin['0']['Ex'][:] ### Animation ### fig,ax = plt.subplots() line, = ax.plot(x,Ex) def iteration(i): Ex = fin[str(i)]['Ex'][:] line.set_ydata(Ex) return line, animation = ani.FuncAnimation(fig, iteration, iterations, interval=25) plt.show()
aebb309852dbeae693e2fe080d9726555e365e01
Silberschleier/al-exercises
/sheet05/assignment38/plot.py
593
3.71875
4
import matplotlib.pyplot as plt def run(x0, a, iterations): results = [x0] for _ in range(iterations): x0 = a * x0 * (1 - x0) results.append(x0) return results if __name__ == '__main__': x0_1, x0_2 = 0.228734167, 0.228734168 a = 3.75 results_1 = run(x0_1, a, 1000) results_2 = run(x0_2, a, 1000) diff = [a - b for a, b in zip(results_1, results_2)] plt.plot(results_1[100:120]) plt.plot(results_2[100:120]) plt.title('a = {}'.format(a)) plt.show() plt.plot(diff[0:1000]) plt.title('a = {}'.format(a)) plt.show()
ca7c6d592b32b27c332fbf61538f4b9548900605
ncturoger/LeetCodePractice
/Linked_List/Reorder_List.py
1,892
3.84375
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ heads = [] while head: heads.append(head) head = head.next direct = 1 last_node = None while heads: if direct == 1: node = heads.pop(0) else: node = heads.pop() node.next = None direct *= -1 if last_node: last_node.next = node # forward_heads = [] # backward_heads = [] # direct = 1 # while head: # if direct == 1: # forward_heads.append(head) # else: # backward_heads.append(head) # direct *= -1 # head = head.next # last_head = None # first = forward_heads[0] # for i in forward_heads: # print("forward_heads:" + str(i.val)) # for j in backward_heads: # print("backward_heads:" + str(j.val)) # while forward_heads: # head = forward_heads.pop(0) # if last_head: # last_head.next = head # if backward_heads: # head.next = backward_heads.pop() # head.next.next = None # last_head = head.next # else: # head.next = None node_1 = ListNode(1) node_2 = ListNode(2) node_3 = ListNode(3) node_4 = ListNode(4) node_1.next = node_2 node_2.next = node_3 node_3.next = node_4 print(Solution().reorderList(node_1))
4cf6757651d767beef9ce6ca40ec820cca7afbdb
ChikusMOC/Exercicios-Capitulo-5
/cap5_ex29.py
1,155
4.03125
4
""" Exercicio 29 - Faça uma prova de matemática para crianças que estão aprendendo a somar números inteiros menores do que 100. Escolha números aleatórios entra 1 e 100, e mostra na tela a pergunta: qual é a soma de a + b, onde a e b são numeros aleatórios. Peça a resposta. Faça cinco perguntas ao aluno, e mostre pra ele as perguntas e as respostas corretas, alem de quantas vezes o aluno acertou. """ from random import * i = 0 aux = 0 aux1 = 0 list = [] list2 = [] list3 = [] print('Qual o resultado das somas:') while i < 5: val1 = randint(1, 100) val2 = randint(1, 100) list.append([val1, val2]) i = i + 1 for a, b in list: try: list2.append(a+b) print(f'Qual é a soma de {a}+{b}? ') var = int(input()) list3.append(var) except ValueError: print('Você digitou algo errado, vamos pra proxima questão.') for a in list2: for b in list3: if a == b: var1, var2 = list[aux1] aux = aux + 1 print(f'Parabens, voçê acertou a questão {var1}+{var2}={b}') aux1 = aux1 + 1 print(f'De {aux1} respostas você acertou {aux}')
7fd265bda5808efec05f1cb125234f91ab1a6c1d
WillTheSun/interviewCake
/03_highest_product_of.py
700
4.15625
4
def my_function(list_of_ints): highest = max(list_of_ints[0:3]) lowest = min(list_of_ints[0:3]) lowest_product_two = list_of_ints[0] * list_of_ints[1] highest_product_two = lowest_product_two highest_product_of_3 = lowest_product_two * list_of_ints[2] for x in list_of_ints[2:]: highest_product_of_3 = max(x*highest_product_two, x*lowest_product_two, highest_product_of_3) highest_product_two = max(highest_product_two, x*highest, x*lowest) lowest_product_two = min(lowest_product_two, x*highest, x*lowest) highest = max(x, highest) lowest = min(x, lowest) return highest_product_of_3 print(my_function([-10, -10, 1, 3, 2]))
c65742c3924f2fa1c7d495c30f710f62c221df11
BenTildark/sprockets-d
/DTEC501-Lab3-1/lab3-1_q4.py
1,846
4.4375
4
""" Write a program to ask the user to enter their first/given name. Your program must display the following message: Please enter your first name: Then output the following: Hi EnteredFirstName, please enter the first integer: and once the user has entered the integer, display the following message: Please enter the second integer: Divide the first integer by the second integer display the following message: EnteredFirstName, the answer to FirstInteger floor divided by SecondInteger is Result with a remainder of Remainder where EnteredFirstName is the users first name and FirstInteger and SecondInteger are the respective integers the user entered. Result is the floored division value of the two integers. Remainder is the modulus value of the two integers. Example Please enter your first name: Harry Hi Harry, please enter the first integer: 30 Please enter the second integer: 4 Harry, the answer to 30 floor divided by 4 is 7 with a remainder of 2. """ # The lines of text you need to use to generate the output are given below for you. Do not alter anything inside the quotes. # "Please enter your first name: " # "Hi {}, please enter the first integer: " # "Please enter the second integer: " # "{}, the answer to {} floor divided by {} is {} with a remainder of {}." first_name = input("Please enter your first name: ") first_addend = int(input("Hi {}, please enter the first integer: ".format(first_name))) second_addend = int(input("Please enter the second integer: ")) def equation(first_arg, second_arg, third_arg): answer = second_arg // third_arg modulus = second_arg % third_arg result = "{}, the answer to {} floor divided by {} is {} with a remainder of {}.".format(first_arg, second_arg, third_arg, answer, modulus) print(result) equation(first_name, first_addend, second_addend)
6d024c99512cf4dc7b1fd0118c49aa2fcc8809ce
huseyin1701/goruntu_isleme
/2. hafta - python devam/7_or.py
67
3.609375
4
a = 5 b = 8 if a == 5 or b == 10: print("işler tıkırında")
31639b72107323d6cfbf3bd3b4497cf22df984f4
Mustafalw02/MustafaPythonAssignment
/exercise_ii_a/sum_of_digits.py
196
4.125
4
# -*- coding: utf-8 -*- x = int(input('Enter a five digit number: ')) sum = 0 sum += x%10 x //= 10 sum += x%10 x //= 10 sum += x%10 x //= 10 sum += x%10 x //= 10 sum += x%10 x //= 10 print(sum)
4dc7160cf47309833f027b1ebb7283f7e87ea674
PyRPy/algorithms_books
/Others/gfg_dp_binomialCoeff.py
1,910
3.671875
4
# gfg_binomialCoeff # https://www.geeksforgeeks.org/binomial-coefficient-dp-9/ def binomialCoeff(n, k): if k > n: return 0 if k == 0 or k == n: return 1 # recursive call return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k) # test n = 5 k = 2 print("the value of C(%d, %d) is %d" % (n, k, binomialCoeff(n, k))) # use 2D array for DP def binomialCoeff2(n, k): C = [[0 for x in range(k+1)] for x in range(n+1)] # bottom up manner for i in range(n+1): for j in range(min(i, k) + 1): # base case if j == 0 or j == i: C[i][j] = 1 else: C[i][j] = C[i-1][j-1] + C[i-1][j] return C[n][k] print("values of C[" + str(n) + "][" + str(k) + "] is " + str(binomialCoeff2(n, k))) # use pascal triangle and less memory def binomialCoeff3(n, k): C = [0 for i in range(k+1)] C[0] = 1 for i in range(1, n+1): j = min(i, k) while j > 0: C[j] = C[j] + C[j-1] j -= 1 return C[k] print("the value of C(%d, %d) is %d" % (n, k, binomialCoeff3(n, k))) # with help of look-up table # naive recurisve + look-up table def binomialCoeffUtil(n, k, dp): # return if dp[n][k] != -1: return dp[n][k] # store if k == 0: dp[n][k] = 1 return dp[n][k] if k == n: dp[n][k] = 1 return dp[n][k] # save value in lookup table before return dp[n][k] = (binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp)) return dp[n][k] def binomialCoeff4(n, k): # make a temp lookup table dp = [[-1 for y in range(k+1)] for x in range(n+1)] return binomialCoeffUtil(n, k, dp) print("values of C[" + str(n) + "][" + str(k) + "] is " + str(binomialCoeff4(n, k)))
b27a8253071c1b4f8756c7a80e1954ddf931e288
Plasmoxy/MaturitaInformatika2019
/python/strukturovane_typy/sifra.py
312
3.640625
4
v = input("text: ") # funguje aj na desifrovanie def sifra(s): out = "" l = len(s) parne = l%2==0 for i in range(0, l if parne else l-1, 2): out += s[i+1] + s[i] if not parne: out += s[-1] # pridaj posledny znak ak neparne return out print(sifra(sifra(v)))
2a691e19c25db8c1286386eed34d64bf7b5cd7a9
AnyaKvon/coffee
/code.py
2,892
4.3125
4
class Coffee: def __init__(self, water, milk, beans, cash): self.water = water self.milk = milk self.beans = beans self.cash = cash class CoffeeMachine: espresso = Coffee(250, 0, 16, 4) latte = Coffee(350, 75, 20, 7) cappuccino = Coffee(200, 100, 12, 6) def __init__(self): self.water = 400 self.milk = 540 self.beans = 120 self.cups = 9 self.cash = 550 def take(self): print(f'\nI gave you ${self.cash}\n') self.cash = 0 def fill(self): print(f'\nWrite how many ml of water do you want to add:') self.water += int(input()) print(f'Write how many ml of milk do you want to add:') self.milk += int(input()) print(f'Write how many grams of coffee beans do you want to add:') self.beans += int(input()) print(f'Write how many disposable cups of coffee do you want to add:\n') self.cups += int(input()) def remaining(self): print(f'\nThe coffee machine has:\n{self.water} of water\n{self.milk} of milk\n{self.beans} of coffee beans\n{self.cups} of disposable cups\n{self.cash} of money\n') def buy(self): i = input('\nWhat do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:') if i == 'back': return True elif i == '1': self.change(self.espresso) elif i == '2': self.change(self.latte) elif i == '3': self.change(self.cappuccino) def change(self, name): if self.water > name.water: if self.milk > name.milk: if self.beans > name.beans: if self.cups > 0: print('I have enough resources, making you a coffee!\n') self.water -= name.water self.milk -= name.milk self.beans -= name.beans self.cups -= 1 self.cash += name.cash else: print(f'Sorry, not enough cups!\n') else: print(f'Sorry, not enough beans!\n') else: print(f'Sorry, not enough milk!\n') else: print(f'Sorry, not enough water!\n') def actions(self, l): if l == 'buy': self.buy() elif l == 'fill': self.fill() elif l == 'take': self.take() elif l == 'remaining': self.remaining() def menu(self): print('Write action (buy, fill, take, remaining, exit):') action = input() while action != 'exit': self.actions(action) print('Write action (buy, fill, take, remaining, exit):') action = input() coffee = CoffeeMachine() coffee.menu()
194fc6361b2670ef1314e4b26ac7a28d2daf4b93
wangwq1325/wangwq
/python/iteration/findMinMax.py
209
3.9375
4
#!/usr/bin/env python #-*- coding:utf-8 -*- def findMinMax(*L): for i in L: minnum = min(L) maxnum = max(L) return (minnum,maxnum) x = findMinMax(1,2,3,4,6) print x
f4fd46b4fe8d3637253cdbbafef7a78096ef624d
b96705008/py-lintcode-exercise
/basic/ch5/word_break.py
1,262
3.59375
4
class Solution: """ @param: s: A string @param: dict: A dictionary of words dict @return: A boolean """ def wordBreak(self, s, dic): # write your code here if s is None or dic is None: return False if len(s) == 0: return True max_len = self.get_max_len(dic) return self.dfs_find(max_len, s, 0, dic) def get_max_len(self, dic): max_len = float('-inf') for w in dic: if len(w) > max_len: max_len = len(w) return max_len def dfs_find(self, max_len, s, start_index, dic): if start_index >= len(s): return True i = start_index while i < len(s): word = s[start_index:i+1] if len(word) > max_len: break print word if word in dic: print word is_found = self.dfs_find(max_len, s, i+1, dic) if is_found: return is_found i = i + 1 return False sol = Solution() s = 'lintcodefhaskjhfkjahfkjhfjkhkjwqhfqkhkjhfkjwhhhhhhhejkqww' dic = ['lint', 'code'] print sol.wordBreak(s, dic)
951a02ddaab92ca7330ca2cfa329252cdd0eebb5
jonycse/pythonSampleCode
/decoratonSample.py
391
3.609375
4
class MyDecorator(object): def __init__(self, f): self.doSomethingCopy=f print "This line will call on decoration" def __call__(self,p,q): print "This line will work when we call the function 'doSomething' " self.doSomethingCopy(p+1,q+1) @MyDecorator def doSomething(a,b): print "I am doing something" print "A ",a," B ",b doSomething(3,4)
4b18ab6102e5888fab73ff4382dedb7b02fa6a71
neoBontia/cse210-student-jumper
/jumper/game/jumper.py
1,604
4.03125
4
class Jumper: """This class is responsible for handling the actions of the player. It will facilitate the guessing and if the game is still playable. Stereotype: Information Holder, Service Provider Attr: guess (character): the letter guessed by the jumper. lives (number): how many lives the jumper still has. """ def __init__(self): """Constructor of the Jumper class Args: self (Jumper): An instance of the Jumper class """ self.guess = "" self.lives = 4 def guessALetter(self): """Method in charge of prompting the jumper which letter they will guess. Args: self (Jumper): An instance of the Jumper class """ self.guess = input("Guess a letter [A-Z]: ") def getGuess(self): """Method in charge of passing the letter guessed by the jumper. Args: self (Jumper): An instance of the Jumper class """ return self.guess def updateLives(self, correct): """Method in charge of updating the number of lives the jumper still has depending on their guess. Args: self (Jumper): An instance of the Jumper class correct (boolean): Determines if the guess is correct or not """ if not correct: self.lives -= 1 def getLives(self): """Method in charge of passing the number of lives the jumper still has Args: self (Jumper): An instance of the Jumper class """ return self.lives
8735c75d6efbc3e5b0d62da00ee73b8a8fe07de5
umbs/practice
/IK/Graphs/HW/AlienDictionary.py
1,114
3.78125
4
from collections import defaultdict def topo(node, graph, visited, stack): visited.add(node) for neigh in graph[node]: if neigh not in visited: topo(neigh, graph, visited, stack) stack.append(node) def find_order(words): ''' words: An array of strings ''' graph = defaultdict(list) # Build graph. Go over consecutive words, say a,b. Compare chars # sequentially in both words until chars mismatch. If mismatch happens at # inded j, then a[j] is before b[j] in the dictionary for i in range(1, len(words)): a, b = words[i-1], words[i] j = 0 while j < (min(len(a), len(b))): if a[j] != b[j]: break j += 1 if j < min(len(a), len(b)): graph[a[j]].append(b[j]) ''' for key in graph: print(key, graph[key]) ''' visited = set() stack = list() for k in graph: if k not in visited: topo(k, graph, visited, stack) print(stack) if __name__ == "__main__": find_order(["baa", "abcd", "abca", "cab", "cad"])
51051a9e056f6ba0294cf804d92ee6624932076e
jpslat1026/Mytest
/Section2/2.1/10.py
366
3.9375
4
# 10.py #by John Slattery on December 13, 2018 #This will tell you the average amount of words you havre in a sentce def main(): words = input("Enter a sentce: ") words = words.split(" ") k = len(words) c = 0 for i in words: v = len(i) c = c + v aw = c / k print(aw, "is the average amount of words you have in a sentce") main()
d3ff3479f57745e660a55ddc01bc40e083751325
snowhuand/python
/python_2/Programming1 Lecture/week10_revision.py
682
4.03125
4
""" Given: subjects= {"CP1401": (60, 70, 80), "CP1404": (70, 80, 90)} print the above data with string formatting like the following: CP1401 60% 70% 80.00% """ def print_marks(subjects={"dummy", (0, 0, 0)}): for key, value in subjects.items(): print("{:^15}{:>10d}%{:>10d}%{:10.2f}%".format(key, value[0], value[1], value[2])) subjects= {"CP1401": (60, 70, 80), "CP1404": (70, 80, 90)} #print_marks(subjects) """ Define a class called Computer with appropriate methods (__init__(), __str__()). eg of calling: asus = Computer("Asus","i7") print(asus) # will results in "The name is Asus, processor i7" """
16ac6be1c6ab112ac1857d2bb0291e8e92fdcdfb
Pyk017/Competetive-Programming
/Interview_Preparation_Questions/Interview_Questions(Coding_Club_PSIT)/Possible_Subsets.py
622
3.953125
4
""" Given a set of distinct integers, nums, return all possible subsets(the power set). Note: The Solution set must not contain duplicate subsets. Input : [1, 2, 3] Output : [ [3], [2], [1], [1, 2, 3], [1, 3], [2, 3], [1, 2], [] ] """ def subsets(array): subset = [0]*len(array) helper(array, subset, 0) def helper(array, subset, i): if i == len(array): print(subset) else: # subset[i] = [] helper(array, subset, i+1) subset[i] = array[i] helper(array, subset, i+1) arr = list(map(int, input("Enter array elements :- ").split())) subsets(arr)
ac24a9e4645c91ccd58fa0ac86ecc41f268a59d9
Vishal45-coder/Day4
/Assignment4_rangeofnum.py
398
3.75
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 23 10:59:30 2020 @author: vishal """ X = 1000 Y = 7000 def checkRange(num): # using comaparision operator if (a>X and a<Y): print(f"{a} is in between ({X} {Y})") else: print(f"The number {a} is not in range ({X}, {Y})") # Test Input a=int(input(("Enter the number you want to search"))) checkRange(a)
81fe2450e750d08612e2a653bcffda8c05aeaf37
karolinanikolova/SoftUni-Software-Engineering
/3-Python-Advanced (May 2021)/workshop/lab/tic_tac_toe/main.py
993
4.15625
4
from workshop.lab.tic_tac_toe.core.logic import play def print_initial_board_positions(): print("This is the numeration of the board:") print("| 1 | 2 | 3 |") print("| 4 | 5 | 6 |") print("| 7 | 8 | 9 |") def create_empty_board(): return [[" ", " ", " "] for _ in range(3)] def setup(): player_1 = input("Player one name: ") player_2 = input("Player two name: ") player_1_sign = input(f"{player_1}, choose your sign (X or O): ").upper() while not player_1_sign in ["X", "O"]: player_1_sign = input(f"{player_1}, choose your sign (X or O): ").upper() player_2_sign = "O" if player_1_sign == "X" else "X" print(f"{player_1} starts first!") print_initial_board_positions() board = create_empty_board() players = {player_1: player_1_sign, player_2: player_2_sign} turns_mapper = {0: player_2, 1: player_1} play(players, board, turns_mapper) def start_game(): setup() if __name__ == "__main__": start_game()
2989deb12897b53c056b3c58754e6b7a837bad94
vaisaghvt/MistakeCorrectionScript
/extractPhrases.py
1,820
4.15625
4
def extractPhrase(match, line): """Returns the phrase which was matched. Rather than just the matched pattern, it returns the complete phrase in which the match occured """ startCount = 0 endCount = len(line) for i in range(match.start() - 1, -1, -1): if line[i] == ' ' or line[i] == '\n' or line[i] == '\\': startCount = i break for i in range(match.end(), len(line), 1): if line[i] == ' ' or line[i] == '\n' or line[i] == '\\': endCount = i break return line[startCount:endCount] def extractPreviousPhrase(match, line): """Returns the phrase before the one that was matched""" startCount = 0 endCount = 0 for i in range(match.start() - 1, -1, -1): if line[i] == ' ' or line[i] == '\n' or line[i] == '\\': endCount = i break for i in range(endCount - 1, -1, -1): if line[i] == ' ' or line[i] == '\n' or line[i] == '\\': startCount = i break return line[startCount:endCount] def extractNextPhrase(match, line): """Returns the phrase after the one which was matched.""" startCount = 0 endCount = 0 for i in range(match.end() + 1, len(line), 1): if line[i] == ' ' or line[i] == '\n' or line[i] == '\\': startCount = i break for i in range(startCount + 1, len(line), 1): if line[i] == ' ' or line[i] == '\n' or line[i] == '\\': endCount = i break return line[startCount:endCount] def extractNextWord(pos, para): """ Returns the word starting at passed position""" word = '' for i in range(pos, len(para)): if para[i] == ' ' or not para[i].isalpha(): return (word, i) else: word += para[i]
7b4a63b2f0156ef0225c609006f347c36aaab872
erkanuz/Python-Coursework
/application/languages.py
184
3.546875
4
class Language: def __init__(self, main, second): self.main = main self.second = second def print(self): print(self.main + " " + self.second, end="")
05a09acae41f14da89124160326efe990ac3b3cd
D3nii/Random
/Python/dics.py
244
3.78125
4
Hamza = {"name" : "Hamza", "age" : "18", "height" : "5.11"} Bilal_Bhai = {"name" : "Bilal", "age" : "23", "height" : "6.1"} people = [Hamza, Bilal_Bhai] for ppl in people: print("The name is", ppl["name"], "and his age is", ppl["age"])
2b2a0b093f345c503492512810f0b92fa740cac6
eessm01/100-days-of-code
/real_python/testing_lambdas.py
740
4.03125
4
import unittest """Real Python. How to Use Python Lambda Functions Python lambdas can be tested similary to regular functions. It's possible to use both unittest and doctest. """ addtwo = lambda x: x + 2 addtwo.__doc__ = """Add 2 to a number. >>> addtwo(2) 4 >>> addtwo(2.2) 4.2 >>> addtwo(3) # Should fail 6 """ class LambdaTest(unittest.TestCase): def test_add_two(self): self.assertEqual(addtwo(2), 4) def test_add_two_point_two(self): self.assertEqual(addtwo(2.2), 4.2) def test_add_three(self): # Should fail self.assertEqual(addtwo(3), 5) if __name__ == "__main__": import doctest unittest.main(verbosity=2) # doctest.testmod(verbose=True)
041acbc02b3094837c7643d1be710fa3134d1852
harshVRastogi/python-examples
/src/exercise5-input/VariableArguments.py
799
4.125
4
# using import you include the feature you specify after import keyword # every language has a vast pool of features or libraries or modules # which are imported when the user requires to keep the program as small as possible from sys import argv # here python unpacks the variables you entered in the console # enter exact number of variables you have declared with argv script, first, second, third = argv # argv stand for argument variable # arguments are the values you pass to a module print "The script name is:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third # to run the script type # python VariableArguments.py first_variable second_variable third_variable # the value of the variables would be anything
bb7b46553c7d8774a5befd9ddaaa911a23731ae5
Nithanaroy/PythonSnippets
/Intuit3.py
533
3.890625
4
""" Given a string, return the minimum number characters that should be added to that string to make it a palidrome """ def shortPalin(s): e = len(s) - 1 i = 0 c = 0 while i < len(s) / 2: if s[i] != s[e]: s = insertAtIndex(s, i, s[e]) c += 1 e += 1 i += 1 e -= 1 print s return c def insertAtIndex(s, i, c): return s[0:i] + c + s[i:] # print insertAtIndex('apple', 0, 'a') # print insertAtIndex('apple', 6, 'a') print shortPalin('abcddba')
a41b421cf088986543cefce0b521e6b7c97c5cb3
LarissaMidori/curso_em_video
/exercicio037.py
901
4.4375
4
''' Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. ''' print(f'{"=**=" * 15}') print(f'CONVERSOR DE BASES NUMÉRICAS: ') print(f'{"=**=" * 15}') num = int(input(' Digite um número inteiro: ')) print(f''' Escolha umas das opções para converter: 1 - converter para BINÁRIO 2 - converter para OCTAL 3 - converter para HEXADECIMAL ''') base = int(input('Digite sua opção: ')) if base == 1: print(f'O número {num} convertido para BINÁRIO vale {bin(num)[2:]}') #[2:] fatia os 2 primeiros índices da string elif base ==2: print(f'O número {num} convertido para OCTAL vale {oct(num)[2:]}') elif base == 3: print(f'O número {num} convertido para HEXADECIMAL vale {hex(num)[2:]}') else: print(f'Opção inválida! Por favor, tente novamente.')
d9169f3072c6dbc0f8adcf0ed3f2cd2fec6fc091
SantiagoJSG/Trabajo_Final_30_Abril
/Ejercicio22.py
299
3.953125
4
# Ejercicio 22 print("El programa está orientado a determinar si el número ingresado es par o impar (solo se aceptan números enteros).") numero = int(input("Digite un número entero: ")) if numero % 2 == 0: print("Ingreso un número par") else: print("Ingreso un número impar")
b3b1e31a8a6480840f6f08c6f02d8beb6c2440b5
hacmorgan/8-bit-cpu
/wirelen
341
3.59375
4
#!/usr/bin/env python import sys def wirelen( num_pins ): print( "{}mm".format(float(num_pins)*2.54+14) ) def main(): while True: try: wirelen( eval(input("Number of pins: ")) ) except NameError: print( "invalid input", file=sys.stderr ) if __name__ == '__main__': sys.exit(main())
d63a47d4c938e61a6b3887ff9714df7fda3314bb
cacciatora/LintCode
/Rotate Array.py
773
3.859375
4
class Solution: """ @param nums: an array @param k: an integer @return: rotate the array to the right by k steps """ def rotate(self, nums, k): # Write your code here k = k % len(nums) left = 0 p = len(nums) - k - 1 while left < p: nums[left], nums[p] = nums[p], nums[left] left += 1 p -= 1 right = len(nums) - 1 p = len(nums) - k while p < right: nums[p], nums[right] = nums[right], nums[p] p += 1 right -= 1 left = 0 right = len(nums) - 1 while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 return nums
d348516646697897e7c2700ed4cc71cee9763f05
DDDlyk/learningpython
/05_高级数据类型/ddd_10_字典基本使用.py
358
4.1875
4
xiaoming_dict = {"name": "小明"} # 1、取值 print(xiaoming_dict["name"]) # 在取值的时候,如果指定的可以不存在,程序会报错。 # print(xiaoming_dict["123"]) # 2、增加/修改 xiaoming_dict["age"] = 18 xiaoming_dict["name"] = "小小明" # 3、删除 # xiaoming_dict.pop("name") xiaoming_dict.pop("name123") print(xiaoming_dict)
2fceac6c317a831b868d88e9be9a539e07203f93
ehpor/hcipy
/hcipy/optics/surface_profiles.py
3,675
3.5
4
import numpy as np from ..field import Field def spherical_surface_sag(radius_of_curvature): '''Makes a Field generator for the surface sag of an even aspherical surface. Parameters ---------- radius_of_curvature : scalar The radius of curvature of the surface. Returns ------- Field generator This function can be evaluated on a grid to get the sag profile. ''' return conical_surface_sag(radius_of_curvature, conic_constant=0) def parabolic_surface_sag(radius_of_curvature): '''Makes a Field generator for the surface sag of an even aspherical surface. Parameters ---------- radius_of_curvature : scalar The radius of curvature of the surface. Returns ------- Field generator This function can be evaluated on a grid to get the sag profile. ''' return conical_surface_sag(radius_of_curvature, conic_constant=-1) def conical_surface_sag(radius_of_curvature, conic_constant=0): r'''Makes a Field generator for the surface sag of a conical surface. The surface profile is defined as: .. math:: z = \frac{cr^2}{1 + \sqrt{1-\left(1+k\right)c^2r^2}} with `z` the surface sag, `c` the curvature and `k` the conic constant. Parameters ---------- radius_of_curvature : scalar The radius of curvature of the surface. conic_constant : scalar The conic constant of the surface Returns ------- Field generator This function can be evaluated on a grid to get the sag profile. ''' def func(grid): x = grid.x y = grid.y r = np.hypot(x, y) curvature = 1 / radius_of_curvature alpha = (1 + conic_constant) * curvature**2 * r**2 sag = r**2 / (radius_of_curvature * (1 + np.sqrt(1 - alpha))) return Field(sag, grid) return func def even_aspheric_surface_sag(radius_of_curvature, conic_constant=0, aspheric_coefficients=None): r'''Makes a Field generator for the surface sag of an even aspherical surface. The surface profile is defined as: .. math:: z = \frac{cr^2}{1 + \sqrt{1-\left(1+k\right)c^2r^2}} + \sum_i=0 a_i r^{2i+4} With `z` the surface sag, `c` the curvature, `k` the conic constant and :math:`a_i` the even aspheric coefficients. It is important to note that this definition deviates from the Zemax definition of an even aspheric surface. In Zemax the 2nd order term is also included in the expansion, which is unnessary because the conic surface itself already accounts for the 2nd order term. Parameters ---------- radius_of_curvature : scalar The radius of curvature of the surface. conic_constant : scalar The conic constant of the surface aspheric_coefficients : array_like Contains the high-order even aspheric coefficients. Returns ------- Field generator This function can be evaluated on a grid to get the sag profile. ''' if aspheric_coefficients is None: aspheric_coefficients = [] def func(grid): x = grid.x y = grid.y r = np.hypot(x, y) # Start with a conic surface curvature = 1 / radius_of_curvature alpha = (1 + conic_constant) * curvature**2 * r**2 sag = r**2 / (radius_of_curvature * (1 + np.sqrt(1 - alpha))) # Add aspheric coefficients # Only use the even modes and start at 4, because 0 is piston and 2 is the conic surface for ai, coef in enumerate(aspheric_coefficients): power_index = 4 + ai * 2 sag += coef * r**power_index return Field(sag, grid) return func
cea41650826b1db80b942997354e467885ab830f
mizhi/project-euler
/python/problem-104.py
1,510
4.03125
4
#!/usr/bin/env python # The Fibonacci sequence is defined by the recurrence relation: # # Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1. # # It turns out that F541, which contains 113 digits, is the first # Fibonacci number for which the last nine digits are 1-9 pandigital # (contain all the digits 1 to 9, but not necessarily in order). And # F2749, which contains 575 digits, is the first Fibonacci number for # which the first nine digits are 1-9 pandigital. # # Given that Fk is the first Fibonacci number for which the first nine # digits AND the last nine digits are 1-9 pandigital, find k. from math import sqrt from math import floor from sys import exit def pandigital(o1): cs="123456789" o1s=list(str(o1)) o1s.sort() return cs == "".join(o1s) sqrt5 = sqrt(5) phi = (1 + sqrt5) / 2 iphi = -1 / phi lastphi = 1 lastphib = 0 lastiphi = 1 lastiphib = 0 def bigfib(n): global iphi, phi, sqrt5, lastphi, lastphib, lastiphi, lastiphib while lastphib < n: lastphi *= phi if lastphi > 10**9: lastphi /= 10 lastphib += 1 while lastiphib < n: lastiphi *= iphi if lastiphi > 10**9: lastiphi /= 10 lastiphib += 1 return int((lastphi - lastiphi) / sqrt5) fn = 0 fn_1 = 1 fn_2 = 0 n = 2 while True: fn = fn_1 + fn_2 fn %= 10**9 fn_2, fn_1 = fn_1, fn if pandigital(fn): firstn = bigfib(n) if pandigital(firstn): break n += 1 print n
a196d7e2af36c66d756e4842367abbf018cb4ab5
jdtayyub/HLC-Work-Python-Multi-Obstacle
/scene/scenes.py
2,486
4.1875
4
class Scene2D: """Class defining the environment Values of the abstract properties * **_x,_y,_z,_width,_height,_depth** = "Dimensions of the scene" * **_objects** = "a dictionary of objects of the 'physical object' class" Members * **_visualise** (): """ _x = 0 _y = 0 _width = 0 _height = 0 _objects = [] def __init__(self, x, y, width, height): self._x = x self._y = y self._width = width self._height = height def add_object(self, obj): if "2d" not in obj.dimension: print('Only 2D objects can be added in a 2D scene') return self._objects.append(obj) return self def get_2D_info(self): # Function returning only 2D information (coords & dims) of the scene, In case of calling the function from the # Scene3D class, z and depth are omitted and only a projection over x,y is returned return {'x':self._x, 'y':self._y, 'width':self._width, 'height':self._height} def get_objects(self): return self._objects def get_obj_names(self): # Display function to output the names of the objects currently in the present scene object for 2d and 3d # INCOMPLETE return self def visualise(self): return self class Scene3D(Scene2D): """Class defining the 3D environment Inheritance: Scene2D class which defines the 2D Environment Values of the abstract properties * **_x,_y,_z,_width,_height,_depth** = "Dimensions of the scene" * **_objects** = "a dictionary of objects of the 'physical object' class" Members * **_visualise** (): """ _z = 0 _depth = 0 _objects = [] #List of objects in the scene as objects of objects def __init__(self, x, y, z, width, height, depth): Scene2D.__init__(self, x, y, width, height) self._z = z self._depth = depth def add_object(self, obj): if "3d" not in obj.dimension: print('Errors: Only 3D objects can be added in a 3D scene.') return self._objects.append(obj) def get_3D_info(self): #Function returning 3D information (coords & dims) of the scene return {'x':self._x, 'y':self._y, 'z':self._z, 'width':self._width, 'height':self._height, 'depth':self._depth} def visualise(self): return self
9d8d646d8a80306ac9399076fe5686c22e25089a
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4414/codes/1635_2704.py
168
3.828125
4
nota=float(input("nota:")) bonificacao=input("S ou N :") if(bonificacao=="S"): notafinal= nota + nota*0.10 print(notafinal) else: notafinal=nota print(notafinal)
ae96f971595c8c348a91d39a7efa0acb7497daa9
DRubioG/Traductor-a-braille
/diccionario.pyw
12,024
3.5
4
from tkinter import * def ast(): return chr(9679) def blc(): return chr(9675) #str="" def linea0(str): return str+blc()+' '+blc()+' ' def linea1(str): return str+blc()+' '+ ast()+' ' def linea2(str): return str+ast()+' '+blc()+' ' def linea3(str): return str+ast()+' '+ast()+' ' def esp(str): return str+' '*3 def biblioteca(lista): i=0 flag=0 linea=0 str="" while(i!=len(lista)): #comprobaciones if lista[i].isnumeric(): if linea==0: str=linea1(str) elif linea==1: str=linea1(str) elif linea==2: str=linea3(str) if lista[i].isupper(): if linea==0: str=linea1(str) elif linea==1: str=linea0(str) elif linea==2: str=linea1(str) #Letras if (lista[i].lower()=='a')|(lista[i]=='1'): if linea==0: str=linea2(str) elif linea==1: str=linea0(str) elif linea==2: str=linea0(str) elif (lista[i].lower()=='b')|(lista[i]=='2'): if linea==0: str=linea2(str) elif linea==1: str=linea2(str) elif linea==2: str=linea0(str) elif (lista[i].lower()=='c')|(lista[i]=='3'): if linea==0: str=linea3(str) elif linea==1: str=linea0(str) elif linea==2: str=linea0(str) elif (lista[i].lower()=='d')|(lista[i]=='4'): if linea==0: str=linea3(str) elif linea==1: str=linea1(str) elif linea==2: str=linea0(str) elif (lista[i].lower()=='e')|(lista[i]=='5'): if linea==0: str=linea2(str) elif linea==1: str=linea1(str) elif linea==2: str=linea0(str) elif (lista[i].lower()=='f')|(lista[i]=='6'): if linea==0: str=linea3(str) elif linea==1: str=linea2(str) elif linea==2: str=linea0(str) elif (lista[i].lower()=='g')|(lista[i]=='7'): if linea==0: str=linea3(str) elif linea==1: str=linea3(str) elif linea==2: str=linea0(str) elif (lista[i].lower()=='h')|(lista[i]=='8'): if linea==0: str=linea2(str) elif linea==1: str=linea3(str) elif linea==2: str=linea0(str) elif (lista[i].lower()=='i')|(lista[i]=='9'): if linea==0: str=linea1(str) elif linea==1: str=linea2(str) elif linea==2: str=linea0(str) elif (lista[i].lower()=='j')|(lista[i]=='0'): if linea==0: str=linea1(str) elif linea==1: str=linea3(str) elif linea==2: str=linea0(str) elif lista[i].lower()=='k': if linea==0: str=linea2(str) elif linea==1: str=linea0(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='l': if linea==0: str=linea2(str) elif linea==1: str=linea2(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='m': if linea==0: str=linea3(str) elif linea==1: str=linea0(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='n': if linea==0: str=linea3(str) elif linea==1: str=linea1(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='o': if linea==0: str=linea2(str) elif linea==1: str=linea1(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='p': if linea==0: str=linea3(str) elif linea==1: str=linea2(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='q': if linea==0: str=linea3(str) elif linea==1: str=linea3(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='r': if linea==0: str=linea2(str) elif linea==1: str=linea3(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='s': if linea==0: str=linea1(str) elif linea==1: str=linea2(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='t': if linea==0: str=linea1(str) elif linea==1: str=linea3(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='u': if linea==0: str=linea2(str) elif linea==1: str=linea0(str) elif linea==2: str=linea3(str) elif lista[i].lower()=='v': if linea==0: str=linea2(str) elif linea==1: str=linea2(str) elif linea==2: str=linea3(str) elif lista[i].lower()=='x': if linea==0: str=linea3(str) elif linea==1: str=linea0(str) elif linea==2: str=linea3(str) elif lista[i].lower()=='y': if linea==0: str=linea3(str) elif linea==1: str=linea1(str) elif linea==2: str=linea3(str) elif lista[i].lower()=='z': if linea==0: str=linea2(str) elif linea==1: str=linea1(str) elif linea==2: str=linea3(str) elif lista[i].lower()=='á': if linea==0: str=linea2(str) elif linea==1: str=linea3(str) elif linea==2: str=linea3(str) elif lista[i].lower()=='é': if linea==0: str=linea1(str) elif linea==1: str=linea2(str) elif linea==2: str=linea3(str) elif lista[i].lower()=='í': if linea==0: str=linea1(str) elif linea==1: str=linea0(str) elif linea==2: str=linea2(str) elif lista[i].lower()=='ó': if linea==0: str=linea1(str) elif linea==1: str=linea0(str) elif linea==2: str=linea3(str) elif lista[i].lower()=='ú': if linea==0: str=linea1(str) elif linea==1: str=linea3(str) elif linea==2: str=linea3(str) elif lista[i].lower()=='ñ': if linea==0: str=linea3(str) elif linea==1: str=linea3(str) elif linea==2: str=linea1(str) elif lista[i].lower()=='w': if linea==0: str=linea1(str) elif linea==1: str=linea3(str) elif linea==2: str=linea1(str) #caracteres elif lista[i]=='&': if linea==0: str=linea3(str) elif linea==1: str=linea1(str) elif linea==2: str=linea3(str) elif lista[i]=='.': if linea==0: str=linea0(str) elif linea==1: str=linea0(str) elif linea==2: str=linea1(str) elif lista[i]==',': if linea==0: str=linea0(str) elif linea==1: str=linea2(str) elif linea==2: str=linea0(str) elif (lista[i]=='¿')|(lista[i]=='?'): if linea==0: str=linea0(str) elif linea==1: str=linea2(str) elif linea==2: str=linea1(str) elif (lista[i]=='¡')|(lista[i]=='!'): if linea==0: str=linea0(str) elif linea==3: str=linea2(str) elif linea==2: str=linea1(str) elif lista[i]==';': if linea==0: str=linea0(str) elif linea==1: str=linea2(str) elif linea==2: str=linea2(str) elif lista[i]=='"': if linea==0: str=linea0(str) elif linea==1: str=linea2(str) elif linea==2: str=linea3(str) elif lista[i]=='(': if linea==0: str=linea2(str) elif linea==1: str=linea2(str) elif linea==2: str=linea1(str) elif lista[i]==')': if linea==0: str=linea1(str) elif linea==1: str=linea1(str) elif linea==2: str=linea2(str) elif lista[i]=='-': if linea==0: str=linea0(str) elif linea==1: str=linea0(str) elif linea==2: str=linea3(str) elif lista[i]=='*': if linea==0: str=linea0(str) elif linea==1: str=linea1(str) elif linea==2: str=linea2(str) elif lista[i]==' ': if linea==0: str=esp(str) elif linea==1: str=esp(str) elif linea==2: str=esp(str) i=i+1 if i==len(lista): i=0 if linea==0: bl1.configure(text=str) bl1.config(font=20) elif linea==1: bl2.configure(text=str) bl2.config(font=20) elif linea==2: bl3.configure(text=str) bl3.config(font=20) print(str) #pinta en el terminal el texto en braille str="" linea=linea+1 if linea==3: break wd=Tk() wd.title("Traductor") wd.geometry('800x200') wd.resizable(0,0) lbl=Label(wd, text="Dame el texto") bl0=Label(wd) bl1=Label(wd) bl2=Label(wd) bl3=Label(wd) lbl.grid(column=0, row=0) txt=Entry(wd, width=100) txt.grid(column=1, row=0) txt.focus() #txt.focus() def clicked(): bl1.grid(column=1, row=2) bl2.grid(column=1, row=3) bl3.grid(column=1, row=4) biblioteca(txt.get()) bl0.configure(text=txt.get()) bl0.grid(column=1, row=1) bl0.config(font=20) txt.delete(0, END) btn=Button(wd, text="traducir", command=clicked) btn.grid(column=2, row=0) btn.focus() wd.mainloop()
0a77d11e52c8b667af91b37aba4830e9bec208f7
scj1420/Class-Projects-Research
/Class/ACME_Volume_1-Python/LinearSystems/linear_systems.py
6,277
3.671875
4
# linear_systems.py """Volume 1: Linear Systems. <Name> <Class> <Date> """ import numpy as np import scipy as sp from scipy import linalg as la # Problem 1 def ref(A): """Reduce the square matrix A to REF. You may assume that A is invertible and that a 0 will never appear on the main diagonal. Avoid operating on entries that you know will be 0 before and after a row operation. Parameters: A ((n,n) ndarray): The square invertible matrix to be reduced. Returns: ((n,n) ndarray): The REF of A. """ A = np.array(A) A = A.astype(float) for j in range(len(A)): for i in range(j+1, len(A)): A[i] -= A[j] * (A[i][j]/A[j][j]) return A # Problem 2 def lu(A): """Compute the LU decomposition of the square matrix A. You may assume that the decomposition exists and requires no row swaps. Parameters: A ((n,n) ndarray): The matrix to decompose. Returns: L ((n,n) ndarray): The lower-triangular part of the decomposition. U ((n,n) ndarray): The upper-triangular part of the decomposition. """ A = np.array(A) A = A.astype(float) (n,n) = np.shape(A) U = np.copy(A) L = np.eye(n, dtype=float) for j in range(n): for i in range(j+1, n): L[i][j] = U[i][j]/U[j][j] U[i][j:] = U[i][j:] - L[i][j]*U[j][j:] return L, U # Problem 3 def solve(A, b): """Use the LU decomposition and back substitution to solve the linear system Ax = b. You may again assume that no row swaps are required. Parameters: A ((n,n) ndarray) b ((n,) ndarray) Returns: x ((m,) ndarray): The solution to the linear system. """ L, U = lu(A) y = [] for k in range(len(b)): lysum = 0 for j in range(k): lysum += L[k][j] * y[j] y.append(b[k] - lysum) x = [] for k in range(len(y)-1, -1, -1): uxsum = 0 for j in range(k+1, len(y)): uxsum += U[k][j]*x[len(y)-1 - j] x.append((y[k] - uxsum)/U[k][k]) x = np.array(x[::-1]) return x.flatten() # Problem 4 def prob4(): """Time different scipy.linalg functions for solving square linear systems. For various values of n, generate a random nxn matrix A and a random n-vector b using np.random.random(). Time how long it takes to solve the system Ax = b with each of the following approaches: 1. Invert A with la.inv() and left-multiply the inverse to b. 2. Use la.solve(). 3. Use la.lu_factor() and la.lu_solve() to solve the system with the LU decomposition. 4. Use la.lu_factor() and la.lu_solve(), but only time la.lu_solve() (not the time it takes to do the factorization). Plot the system size n versus the execution times. Use log scales if needed. """ import time from matplotlib import pyplot as plt t_inv = [] t_solve = [] t_luf = [] t_lus = [] X = [2**i for i in range(12)] for n in X: A = np.random.random((n,n)) b = np.random.random(n) t1 = time.time() A_inv = la.inv(A) A_inv @ b t2 = time.time() la.solve(A, b) t3 = time.time() L,P = la.lu_factor(A) t4 = time.time() la.lu_solve((L,P), b) t5 = time.time() t_inv.append(t2-t1) t_solve.append(t3-t2) t_luf.append(t5-t3) t_lus.append(t5-t4) plt.ion() ax1 = plt.subplot(121) ax1.plot(X, t_inv, label='inverse') ax1.plot(X, t_solve, label='solve') ax1.plot(X, t_luf, label='LU factorization') ax1.plot(X, t_lus, label='LU solve') ax1.legend(loc='upper left') ax2 = plt.subplot(122) ax2.loglog(X, t_inv, basex=2, basey=2) ax2.loglog(X, t_solve, basex=2, basey=2) ax2.loglog(X, t_luf, basex=2, basey=2) ax2.loglog(X, t_lus, basex=2, basey=2) # Problem 5 def prob5(n): """Let I be the n × n identity matrix, and define [B I ] [-4 1 ] [I B I ] [ 1 -4 1 ] A = [ I . . ] B = [ 1 . . ], [ . . I] [ . . 1] [ I B] [ 1 -4] where A is (n**2,n**2) and each block B is (n,n). Construct and returns A as a sparse matrix. Parameters: n (int): Dimensions of the sparse matrix B. Returns: A ((n**2,n**2) SciPy sparse matrix) """ from scipy import sparse Iden = sparse.diags([1], [0], shape=(n,n)) B = sparse.diags([1,-4,1], [-1,0,1], shape=(n,n)) A = sparse.lil_matrix((n**2, n**2)) for i in range(n): A[i*n:(i+1)*n,i*n:(i+1)*n] = B if i > 0: A[(i-1)*n:i*n,i*n:(i+1)*n] = Iden A[i*n:(i+1)*n,(i-1)*n:i*n] = Iden return A # Problem 6 def prob6(): """Time regular and sparse linear system solvers. For various values of n, generate the (n**2,n**2) matrix A described of prob5() and vector b of length n**2. Time how long it takes to solve the system Ax = b with each of the following approaches: 1. Convert A to CSR format and use scipy.sparse.linalg.spsolve() 2. Convert A to a NumPy array and use scipy.linalg.solve(). In each experiment, only time how long it takes to solve the system (not how long it takes to convert A to the appropriate format). Plot the system size n**2 versus the execution times. As always, use log scales where appropriate and use a legend to label each line. """ from matplotlib import pyplot as plt from scipy.sparse import linalg as spla import time t_csr = [] t_npa = [] n = [2**i for i in range(1,7)] for i in n: A = prob5(i) b = np.random.random(i**2) t1 = time.time() Acsr = A.tocsr() spla.spsolve(Acsr, b) t2 = time.time() Anpa = A.toarray() la.solve(Anpa, b) t3 = time.time() t_csr.append(t2-t1) t_npa.append(t3-t2) plt.ion() plt.loglog(n, t_csr, basex=2, basey=2, label='CSR') plt.loglog(n, t_npa, basex=2, basey=2, label='NP array') plt.legend(loc="upper left")
2bf4964e746ed924390cb74b527417c79db38875
JenZhen/LC
/lc_ladder/Adv_Algo/binary-search/Maximum_Average_Subarray_II.py
2,163
4.0625
4
#! /usr/local/bin/python3 # https://www.lintcode.com/problem/maximum-average-subarray-ii/description # Given an array with positive and negative numbers, find the maximum average subarray which length should be greater or equal to given length k. # It's guaranteed that the size of the array is greater or equal to k. # Example # Given nums = [1, 12, -5, -6, 50, 3], k = 3 # Return 15.667 // (-6 + 50 + 3) / 3 = 15.667 """ Algo: Binary Search D.S.: Solution: Same with Maximum_Average_Subarray.py 1. 找到可行解的范围: min(nums), max(nums) 2. 猜答案 (二分): 对可行解范围进行二分,因为可以取float,所以需要使用epsilon, 方法和sqrt_II相同 l + epsilon < r: 3. 检验条件,来判断答案应该在哪一侧 ## TODO: 对子问题更加熟练 子问题:平均值为mid时,能不能找到一个子数组 使得子数组长度 >=k 如果有,说明可以尝试更大的平均值,l = mid, 反之,r = mid 剩余l,r位置,先尝试更大的r,如果不满足>=k,取l 4. 调整搜索范围 特征:**biggest** average that has length >= k Time: O(len(nums) * log(max - min)) Corner cases: """ class Solution: """ @param: nums: an array with positive and negative numbers @param: k: an integer @return: the maximum average """ def maxAverage(self, nums, k): # write your code here if not nums or not k: return 0 l, r = min(nums), max(nums) epsilon = 10 ** -6 while l + epsilon < r: mid = (l + r) / 2 if self.check(nums, k, mid): l = mid else: r = mid if self.check(nums, k, r): return r else: return l def check(self, nums, k, avg): ttl = [0] * (len(nums) + 1) minPre = [0] * (len(nums) + 1) for i in range(1, len(nums) + 1): ttl[i] = ttl[i - 1] + (nums[i - 1] - avg) minPre[i] = min(minPre[i - 1], ttl[i]) if i >= k and ttl[i] - minPre[i - k] >= 0: return True return False # Test Cases if __name__ == "__main__": s = Solution()
14f8b34e740dd3aca6b19cb4b9adea8f12baf3ae
kevinlichang/XiangQi
/main.py
21,106
3.640625
4
# Author: Kevin Chang # Description: Creates a game call XiangQi. The game is played on a 9x10 board, with 7 different types of pieces # that have their own individual behaviors and rulesets. The goal of the game is to capture the enemy's general piece. # The game is over when a player's general piece has no spaces to move without being in check. import pygame from player import Player from piece import General, Advisor, Elephant, Horse, Chariot, Cannon, Soldier class XiangqiGame: """Represents the entire board for the XiangQi game.""" def __init__(self): """Creates an instance of the 9x10 board.""" self._board = [["_______" for column in range(9)] for row in range(10)] # Initialize board self._row_dimensions = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) self._col_dimensions = (0, 1, 2, 3, 4, 5, 6, 7, 8) self._game_state = "UNFINISHED" # Initialize with red and black player. Game starts on red players turn. red_player = Player("red") blk_player = Player("black") self._red_player = red_player self._blk_player = blk_player self._current_player = self._red_player self._opp_player = self._blk_player # Initialize starting positions of pieces # Initialize General positions red_gen = General("GENERAL", [0, 4], "red", red_player, self._board) self._board[0][4] = red_gen blk_gen = General("GENERAL", [9, 4], "black", blk_player, self._board) self._board[9][4] = blk_gen # Initialize Advisor pieces red_advisor1 = Advisor("ADVISOR", [0, 3], "red", red_player, self._board) self._board[0][3] = red_advisor1 red_advisor2 = Advisor("ADVISOR", [0, 5], "red", red_player, self._board) self._board[0][5] = red_advisor2 blk_advisor1 = Advisor("ADVISOR", [9, 3], "black", blk_player, self._board) self._board[9][3] = blk_advisor1 blk_advisor2 = Advisor("ADVISOR", [9, 5], "black", blk_player, self._board) self._board[9][5] = blk_advisor2 # Initialize Elephant pieces red_elephant1 = Elephant("ELEPHNT", [0, 2], "red", red_player, self._board) self._board[0][2] = red_elephant1 red_elephant2 = Elephant("ELEPHNT", [0, 6], "red", red_player, self._board) self._board[0][6] = red_elephant2 blk_elephant1 = Elephant("ELEPHNT", [9, 2], "black", blk_player, self._board) self._board[9][2] = blk_elephant1 blk_elephant2 = Elephant("ELEPHNT", [9, 6], "black", blk_player, self._board) self._board[9][6] = blk_elephant2 # Initialize Horse pieces red_horse1 = Horse("HORSE", [0, 1], "red", red_player, self._board) self._board[0][1] = red_horse1 red_horse2 = Horse("HORSE", [0, 7], "red", red_player, self._board) self._board[0][7] = red_horse2 blk_horse1 = Horse("HORSE", [9, 1], "black", blk_player, self._board) self._board[9][1] = blk_horse1 blk_horse2 = Horse("HORSE", [9, 7], "black", blk_player, self._board) self._board[9][7] = blk_horse2 # Initialize Chariot pieces red_chariot1 = Chariot("CHARIOT", [0, 0], "red", red_player, self._board) self._board[0][0] = red_chariot1 red_chariot2 = Chariot("CHARIOT", [0, 8], "red", red_player, self._board) self._board[0][8] = red_chariot2 blk_chariot1 = Chariot("CHARIOT", [9, 8], "black", blk_player, self._board) self._board[9][0] = blk_chariot1 blk_chariot2 = Chariot("CHARIOT", [9, 8], "black", blk_player, self._board) self._board[9][8] = blk_chariot2 # Initialize Cannon pieces red_cannon1 = Cannon("CANNON", [2, 1], "red", red_player, self._board) self._board[2][1] = red_cannon1 red_cannon2 = Cannon("CANNON", [2, 7], "red", red_player, self._board) self._board[2][7] = red_cannon2 blk_cannon1 = Cannon("CANNON", [7, 1], "black", blk_player, self._board) self._board[7][1] = blk_cannon1 blk_cannon2 = Cannon("CANNON", [7, 7], "black", blk_player, self._board) self._board[7][7] = blk_cannon2 # Initialize Soldier pieces red_soldier1 = Soldier("SOLDIER", [3, 0], "red", red_player, self._board) self._board[3][0] = red_soldier1 red_soldier2 = Soldier("SOLDIER", [3, 2], "red", red_player, self._board) self._board[3][2] = red_soldier2 red_soldier3 = Soldier("SOLDIER", [3, 4], "red", red_player, self._board) self._board[3][4] = red_soldier3 red_soldier4 = Soldier("SOLDIER", [3, 6], "red", red_player, self._board) self._board[3][6] = red_soldier4 red_soldier5 = Soldier("SOLDIER", [3, 8], "red", red_player, self._board) self._board[3][8] = red_soldier5 blk_soldier1 = Soldier("SOLDIER", [6, 0], "black", blk_player, self._board) self._board[6][0] = blk_soldier1 blk_soldier2 = Soldier("SOLDIER", [6, 2], "black", blk_player, self._board) self._board[6][2] = blk_soldier2 blk_soldier3 = Soldier("SOLDIER", [6, 4], "black", blk_player, self._board) self._board[6][4] = blk_soldier3 blk_soldier4 = Soldier("SOLDIER", [6, 6], "black", blk_player, self._board) self._board[6][6] = blk_soldier4 blk_soldier5 = Soldier("SOLDIER", [6, 8], "black", blk_player, self._board) self._board[6][8] = blk_soldier5 # Add starting pieces to respective player active pieces lists red_player.set_active_pieces([red_gen, red_advisor1, red_advisor2, red_elephant1, red_elephant2, red_horse1, red_horse2, red_chariot1, red_chariot2, red_cannon1, red_cannon2, red_soldier1, red_soldier2, red_soldier3, red_soldier4, red_soldier5]) blk_player.set_active_pieces([blk_gen, blk_advisor1, blk_advisor2, blk_elephant1, blk_elephant2, blk_horse1, blk_horse2, blk_chariot1, blk_chariot2, blk_cannon1, blk_cannon2, blk_soldier1, blk_soldier2, blk_soldier3, blk_soldier4, blk_soldier5]) self._red_general = red_gen self._blk_general = blk_gen def get_game_state(self): """Returns the game state.""" return self._game_state def set_game_state(self, red_or_black): """Sets the game state depending on color specified.""" if red_or_black == "red": self._game_state = "RED_WON" elif red_or_black == "black": self._game_state = "BLACK_WON" def is_in_check(self, red_or_black): """Returns True if a player is in check, else False.""" if self._current_player.get_player_color() == red_or_black: return self._current_player.get_check_status() else: return self._opp_player.get_check_status() def get_board(self): """Returns the current board.""" return self._board def print_board(self): """Prints out the current board instance.""" for row in range(10): for col in range(9): if row == 9 and col == 8: if self._board[row][col] != "_______": print(self._board[row][col].get_name()) else: print(self._board[row][col]) else: if self._board[row][col] != "_______": print(self._board[row][col].get_name(), end=" ") else: print(self._board[row][col], end=" ") if row != 9: print(" ") print(" ") if row == 4: print(" ") print(" ") def change_turn(self): """Changes the current player turn to the other player.""" if self._current_player == self._red_player: self._current_player = self._blk_player else: self._current_player = self._red_player if self._opp_player == self._red_player: self._opp_player = self._blk_player else: self._opp_player = self._red_player def general_sight_test(self, num=1): """ Checks that the generals do not 'see' each other (no blocking pieces between generals), which is illegal. :param num: used to keep track of spot being checked during recursion. :return: True if generals 'see' each other. Else False """ # Get red and black General Current Positions (gcp) red_gcp = self._red_general.get_position() blk_gcp = self._blk_general.get_position() if red_gcp[1] == blk_gcp[1]: # If the generals are in same column spaces = blk_gcp[0] - red_gcp[0] if num == spaces: # Base case: if no blocking pieces, Generals see each other. debug("Illegal move. Generals see each other.") return True if self._board[red_gcp[0] + num][red_gcp[1]] == "_______": return self.general_sight_test(num + 1) # debug("Generals do not see each other") return False def all_pieces_move_test(self, player, pos): """ Checks to see if any of a Player's active pieces can move to a specified position. :param player: the player whose pieces are being tested :param pos: the specified position :return: True if at least one piece can move to specified spot. False if no pieces can. """ pieces_list = player.get_active_pieces() # List of all active pieces of the Player for piece in pieces_list: if piece.legal_move_test(pos) == True: debug(piece.get_name(), "can move there.") return True return False def in_check_test(self, testing_player, enemy): """ Tests if a General piece is in check. :param testing_player: Player whose general is being tested for being in check or not. :param enemy: The opponent of the tested player :return: True if general is in check. Else False. """ if self._red_general.get_piece_color() == testing_player.get_player_color(): gen = self._red_general elif self._blk_general.get_piece_color() == testing_player.get_player_color(): gen = self._blk_general gp = gen.get_position() # get current player General's position return self.all_pieces_move_test(enemy, gp) def end_game_test(self, testing_player, enemy): """ Tests to see if a player is in checkmate or in a stalemate :param in_check_player: The player that is in check that is being tested :param enemy: the opponent of the tested player :return: True if player is checkmated or in stalemate and ending the game. Else False """ # Get the correct player color and corresponding general piece and palace coordinates if self._red_general.get_piece_color() == testing_player.get_player_color(): gen = self._red_general palace = ([0, 3], [0, 4], [0, 5], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5]) elif self._blk_general.get_piece_color() == testing_player.get_player_color(): gen = self._blk_general palace = ([7, 3], [7, 4], [7, 5], [8, 3], [8, 4], [8, 5], [9, 3], [9, 4], [9, 5]) board = self._board color = testing_player.get_player_color() pieces_list = testing_player.get_active_pieces() # Test each spot in the palace to see if the general can move there. # If the general can move there, test to see if it would still be in check in that spot # If there is a spot that is not in check, return False for spot in palace: if gen.legal_move_test(spot) == True and spot != gen.get_position(): if board[spot[0]][spot[1]] == "_______" or board[spot[0]][spot[1]].get_piece_color() != color: if self.all_pieces_move_test(enemy, spot) == False: return False # If the in-check player has more pieces besides just the general, check all other active pieces for # potential moves that can get the player out of check. if len(pieces_list) > 1: for num in range(1, len(pieces_list)): for row in self._row_dimensions: for col in self._col_dimensions: piece = pieces_list[num] if piece.legal_move_test([row, col]) == True: if board[row][col] == "_______" or board[row][col].get_piece_color() != color: o_pos = piece.get_position() # Original Position of the current piece holder = board[row][col] # Holding onto the test spot's original state board[o_pos[0]][ o_pos[1]] = "_______" # Temporarily move the testing piece to do a in check test board[row][col] = piece check_test = self.in_check_test(testing_player, enemy) board[row][col] = holder # Return the board to original state board[o_pos[0]][o_pos[1]] = piece if check_test == False: # If the move places general out of check, return False return False debug("Checkmate!", enemy.get_player_color(), "wins.") return True def make_move(self, curr_pos, new_pos): """ Makes a move for current player on a piece :param curr_pos: the current position of piece to be moved :param new_pos: the new position the piece is moving to :return: True if move is legal. Else return False """ if self.get_game_state() != "UNFINISHED": debug("Game Over", self.get_game_state()) return False board = self._board # Convert input strings into coordinates on the board cp = curr_pos # current position coordinates as a list np = new_pos # intended new position coordinates as a list # Check if inputted positions are inside board dimensions if cp[0] not in self._row_dimensions or cp[1] not in self._col_dimensions: debug("Selection is outside of board") return False if np[0] not in self._row_dimensions or np[1] not in self._col_dimensions: debug("Move is outside of the board") return False # Check if there is even a piece at current position selected if board[cp[0]][cp[1]] == "_______": debug("There is no piece selected") return False if cp == np: # Return False if new_pos is same as curr_pos debug("No new move made") return False piece = board[cp[0]][cp[1]] # Get the piece that is selected move_spot = board[np[0]][np[1]] # The spot the player intends to move to # Check if piece selected belongs to the current player if piece.get_player() != self._current_player: debug("Player can only move their own pieces.") return False if move_spot != "_______" and move_spot.get_player() == piece.get_player(): debug("Player cannot eat their own piece.") return False if piece.legal_move_test(np) is False: # Check if new_pos is legal to the piece debug("Illegal move") return False # Make the move and change piece position. Then test for check status, checkmates, or generals' sightlines. board[cp[0]][cp[1]] = "_______" board[np[0]][np[1]] = piece piece.set_position(np) # Check if generals "see" each other if self.general_sight_test() == True: board[cp[0]][cp[1]] = piece # Reset original positions piece.set_position(cp) board[np[0]][np[1]] = "_______" return False # Check if current player's own General would be in check if self.in_check_test(self._current_player, self._opp_player) == True: board[cp[0]][cp[1]] = piece # Reset original positions piece.set_position(cp) board[np[0]][np[1]] = "_______" debug("Cannot move there. You're General would be in check.") return False # Check if opponent player's general is in check if self.in_check_test(self._opp_player, self._current_player) == True: self._opp_player.set_check_status(True) debug(self._opp_player.get_player_color(), "player in check.") # If there is a piece to be taken on the new position if move_spot != "_______": enemy = move_spot.get_player() enemy.piece_taken(move_spot) # If the current player was in check, reset in check status to False after the current move. if self._current_player.get_check_status() == True: self._current_player.set_check_status(False) debug(self._current_player.get_player_color(), "player no longer in check.") debug(piece.get_name(), " moved to ", piece.get_position()) self.change_turn() # Swap the current and opponent player slots. # Test to see if next player is checkmated or in stalemate. If True, then game is over. if self.end_game_test(self._current_player, self._opp_player) == True: self.set_game_state(self._opp_player.get_player_color()) return True def show_turns(self): debug("Current", self._current_player.get_player_color()) debug("Opponent", self._opp_player.get_player_color()) def debug(msg1, msg2="", msg3="", msg4=""): DEBUG = True if DEBUG == True: print(msg1, msg2, msg3, msg4) # Define some colors BGC = (0, 0, 0) BLACK = (50, 50, 50) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # This sets the WIDTH and HEIGHT of each grid location WIDTH = 70 HEIGHT = 70 # This sets the margin between each cell MARGIN = 5 # Initialize pygame pygame.init() # Set the HEIGHT and WIDTH of the screen WINDOW_SIZE = [680, 755] screen = pygame.display.set_mode(WINDOW_SIZE) # Set title of screen pygame.display.set_caption("XiangQi Game") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() game = XiangqiGame() grid = game.get_board() pos_holder = [] board_coord = [] # -------- Main Program Loop ----------- while not done: font = pygame.font.SysFont('Calibri', 18, False, False) for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop elif event.type == pygame.MOUSEBUTTONDOWN: # User clicks the mouse. Get the position pos = pygame.mouse.get_pos() pos_holder = [pos[0], pos[1]] # Change the x/y screen coordinates to grid coordinates column = pos[0] // (WIDTH + MARGIN) row = pos[1] // (HEIGHT + MARGIN) # Set that location to one if not board_coord: board_coord = [row, column] else: game.make_move(board_coord, [row, column]) board_coord = [] print("Click ", pos, "Grid coordinates: ", row, column) # Set the screen background screen.fill(BGC) # Draw the grid for row in range(10): for column in range(9): color = WHITE piece = grid[row][column] piece_name = "" if piece != "_______": piece_name = piece.get_name() if piece.get_piece_color() == "red": color = RED else: color = BLACK pygame.draw.rect(screen, color, [(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) text = font.render(piece_name, True, WHITE) screen.blit(text, [(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN]) # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()
92f1711d53814d98d0e4aefa7dbcd4c2730edc79
ka3254/test-xx
/python/demo.py
2,110
4.125
4
# print('你好'+"带我玩"*3,end="111") # print(123) # print(2.333) """ print((2+2-1*1/0.5)*2) print(True,False) print(1>3) print(1<3) print(1==2 or 1<3) print(1==2 and 1<3) print(None) print(()) print([]) print({})""" # name='张三' # print(name) # #运算输出 # res= (1+2+4+5*2/(4*2))%3 # print(res) #获取内容并切换成小数进行运算 # a=input("输入:") # b=input("输入2") # d=int(input("输入3")) # print(float(a)+float(b)+d) # c=type(b) # print(c) #获取字段长度 # a=len("dasdadsdasd") # print(a) #判断输入字符串是奇数还是偶数 # print("True为奇,False为偶") # a=len(input("请输入")) # c=int(a)%2 # print(c>0) ''' 元组 # 元组意义在于少写变量 # 变量会占用内存越多占用的内测就越多 b=('xx','yy') #元组内包涵元组为2维元组,套几层,为几维元组 a=(1,2,3,4,"das",True,None,b) # print(a) # # 下标是计算机自动给值的编号,计算机技术从0开始,取值直接元组[值下标] # print(a[5]) # #多层元组取值方式为下标依次深入 # print(a[-1][1]) # print( a.index(3)) # #多层元组使用方法需要先定位到该元组再使用 # print(a[-1].index('xx')) # print(a.count("das")) #切片 左闭右开(包括左标值,不包括右标值) print(a[0:3]) ''' # 数组 b=('x','y') a=[1,2,3,4,"das",True,None,b,1] print(a) # 数组修改例: # n=int(input('输入')) # a.append(n) #a.insert(0,值)也可直接插入数据,但是因为a是嵌套数组,所以需要指定目标组,则a.insert(a[0],值)才能成功 # a.insert(0,n) # print( a.pop(5)) # #extend方法是将对象数组的内容插入到目标数组的后端 # #拼接输出的方法也可以达到输出效果 print(a+c) # c=['xx','yy'] # a.extend(c) # print(a) d=[2,3,4,6,5] #sort是按从小到大排序,且针对于有大小关系的内容 # d.sort(reverse=True)为从大到小倒置 # d.sort() # clear为删除数组中的内容 # d.clear() # remove 方法的括号中是删除的是值,不是下标 # d.remove(2) # reverse方法单独使用仅仅是将数组本身的顺序倒置,并不会按大小倒序 d.reverse() print(d)
89d3d4ba267d9d859a62801ff845d676d0778e7e
omidcc/leetcode
/4. Median of Two Sorted Arrays/median.py
351
3.515625
4
def findMedianSortedArrays(nums1, nums2): mergedArray = nums1 + nums2 i = 0 mergedArray.sort() n = len(mergedArray) median = 0.0 if n % 2: median = mergedArray[int(n/2)] else: median = (mergedArray[(int(n/2))-1] + mergedArray[int(n/2)])/2.0 return median print(findMedianSortedArrays([1, 2], [3, 4]))
ba5eaaa5bd6c3dfa35db79f8a338969a28006806
MMMinoz/p3.py
/Python.py
6,605
3.828125
4
#DrawPython蟒蛇 import turtle as tur # #设置窗体大小 startx,starty非必需,默认在屏幕中间 # turtle.setup(width,height,startx,starty) # #海龟到(x,y)坐标 # turtle.goto(x , y) # #海龟向前移动d # #当d值为正数时向前移动 # #当d为负数时向后移动 # turtle.fd(d) # #画笔向后移动d # turtle.bk(d) # #r弧形半径 # #当radius值为正数时,圆心在当前位置/小海龟左侧 # #当radius值为负数时,圆心在当前位置/小海龟右侧 # #angle弧形角度 当无该参数或参数为None时,绘制整个圆形 # #当extent值为正数时,顺小海龟当前方向绘制。 # #当extent值为负数时,逆小海龟当前方向绘制。 # turtle.circle(r,angle) # #改变海龟行进方向,只改变方向并不前进 # #在执行完tur.fd()后,小乌龟恢复到正X方向 # #angle为绝对度数 # turtle.seth(angle) # #海龟左转/右转angle度 # #angle为海龟度数 # turtle.left(angle) # tur.setup(650,350) # #抬笔 # tur.penup() # tur.fd(-250) # #落笔 # tur.pendown() # tur.pensize(25) # tur.pencolor("pink") # tur.seth(-40) # for i in range(4): # tur.circle(40,80) # tur.circle(-40,80) # tur.circle(40,80/2) # tur.fd(40) # tur.circle(16,180) # tur.fd(40*2/3) # tur.done() # tur.setup(400,400) # tur.goto(100,100) # tur.goto(0,-200) # tur.goto(-100,100) # tur.goto(0,0) # tur.seth(45) # tur.circle(-100,90) # tur.circle(-200,120) # tur.colormode(255) # tur.color("pink") # tur.left(45) # tur.fd(150) # tur.right(135) # tur.fd(200) # tur.left(135) # tur.fd(150) # tur.done() # tur.setup(500,500) # tur.pencolor("purple") # tur.width(25) # tur.penup() # tur.fd(-250) # tur.pendown() # tur.seth(-40) # for i in range(4): # tur.circle(40,80) # tur.circle(-40,80) # tur.circle(40,40) # tur.fd(40) # tur.circle(16,180) # tur.fd(40) # tur.done() #tur.seth()在执行完tur.fd()后,小乌龟恢复到正X方向 #而tur.left()/tur.right()执行完后方向不恢复 # tur.setup(500,500) # tur.penup() # tur.pencolor("black") # tur.pendown() # for i in range(4): # tur.seth(90*i) # tur.fd(150) # tur.right(90) # tur.circle(-100,45) # tur.goto(0,0) # # tur.done() # tur.setup(500,500) # tur.penup() # tur.color("yellow") # tur.fillcolor("red") # tur.width("5") # tur.fd(-150) # tur.pendown() # # tur.begin_fill() # for i in range(5): # tur.fd(300) # tur.right(144) # tur.end_fill() # # tur.write("五角星",font=('宋体',20,'normal')) # # tur.done() # 椭圆 tur.setup(500,500) tur.seth(90) len = 1 for i in range(2): for j in range(60): if j <30: len += 0.2 else: len -=0.2 tur.fd(len) tur.left(3) tur.done() #树枝 #利用克隆和递归 # tur.setup(800,800) # tur.width(5) # tur.color("green") # # tur.goto(0,-200)#起点 # tur.seth(90) # def branch(plist, len): # 自定义函数,画树枝 # if (len > 15): # 递归的退出条件 # list = [] # 新画笔列表 # for p in plist: # 遍历旧画笔列表 # p.forward(len) # q = p.clone() # p.left(65) # q.right(65) # list.append(p) # 存入新画笔列表 # list.append(q) # 存入新画笔列表 # branch(list, len * 0.65) # 递归,list为新画笔列表,树枝长65% # # branch([tur], 200) # tur.done() # 集合 set类 去重 # 列表有序,集合无序 # S = {'P','Y','t','h','O','n'} # T = {'P','Y','T'',h','o','n'} # S - T#差 # S | T#并 # S & T#交 # S ^ T#补 # S >= T (S <= T) #判断包含关系 # # S.add(x)#向S中添加x(如果x不在S中) # S.remove(x)#若S中有x则删除,没有则报错 # S.discard(x)#若S中有x则删除,没有不报错 # S.clear()#清空 # S.pop()#从集合中随机返回一个元素,并删除,若S为空则返回异常 # S.copy()#返回S的一个副本 # #创建空集合只能由set # s = set({}) # print(s) # # 序列 # 字符串类型 列表类型 元组类型 # # ls lt指向同一个 只是名字不同 # ls = ['P','Y','t','h','O','n'] # lt = ls # #在列表中增加一个元素 # ls.append(1234) # print(ls) # #在k位置插入一个元素 # ls.insert(3,'python') # print(ls) # #倒转 # ls.reverse() # print(ls) # #删除ls中某个位置的元素 # del ls[1] # #删除ls中某切片的元素 # del ls[1:4] # #返回n的索引 # ls.index(n) # max(ls) # # 映射 字典类型dict # d = {"中国":"北京","美国":"华盛顿","法国":"纽约"} # print(d["中国"]) # print(d.keys()) # print(d.values()) # #若key存在,则返回value,否则输出default # print(d.get("中国","不存在")) # #若key存在,则取出value,否则输出default # print(d.pop("中国","不存在")) # #返回键值对元组 # print(d.items()) # #随机取出一个键值对,以元组形式返回 # print(d.popitem()) # dd = {"a":"b","c":"d"} # #添加新元素 # d["a"] = 1 # d["b"] = 2 # import jieba # #精确模式,返回一个列表类型的分词结果 # # jieba.lcut(s) # print(jieba.lcut("python是一门编程语言")) # #全模式,返回一个列表的分词结果,存在冗余 # # jieba.lcut(s,cut_all=True) # print(jieba.lcut("python是一门编程语言",cut_all=True)) # #搜索引擎模式,返回一个列表类型的分词结果,存在冗余 # print(jieba.lcut_for_search("python是一门编程语言")) # #想分词词典增加新词w # # jieba.add_word(w) # jieba.add_word("啦啦啦") # print(jieba.lcut("python是一门编程语言啦啦啦啦")) # def getText(): # txt = open("D:\\Python\\hamlet.txt","r").read() # txt = txt.lower() # for ch in '|"!#$%()*+,-./;:<=>?@[\\]^_{|}~': # txt = txt.replace(ch," ") # return txt # hamletTxt = getText() # words = hamletTxt.split() # counts = {} # for word in words: # counts[word] = counts.get(word,0)+1 # items = list(counts.items()) # items.sort( key = lambda x: x[1],reverse = True ) # for i in range(10): # word,count = items[i] # print("{0:<10}{1:>5}".format(word,count)) # # import jieba # txt = open("沉默的羔羊.txt","r",encoding="utf-8").read() # words = jieba.lcut(txt) # counts = {} # for word in words: # if len(word) == 1: # continue # else: # counts[word] = counts.get(word,0) + 1 # items = list(counts.items()) # items.sort(key = lambda x:x[1],reverse=True) # for i in range(15): # word,count = items[i] # print("{0:<10}{1:>5}".format(word,count)) dic = {} s = input() x = eval(s) try: for i in x: dic[x[i]] = i print(dic) except: print("输入错误")
303ea276783a7ac30f8ac77789801cdb98b12df0
silviagajdos/chatbot
/client_code-1.py
3,845
3.671875
4
import socket from Printer import dictPrinter mealDict = {1:"Breakfast", 2:"Lunch", 3:"Dinner"} cuisineDict = {1:"African", 2:"British", 3:"Chinese", 4:"French", 5:"Fast Food", 6:"Indian", 7:"Italian", 8:"Japanese", 9:"Korean", 10:"Lebanese", 11:"Mexican", 12:"Turkish"} def Main(): #connection to ChatBot host = '127.0.0.1' port = 50091 thisSocket = socket.socket() thisSocket.connect((host,port)) #Reading first message to ChatBot nameIntro = thisSocket.recv(1024).decode() print('Message Received from ChatBot: '+ str(nameIntro)) #client name message = raw_input("Message to ChatBot: ") #Continue conversation with ChatBot until end is types while message != "end": #send message to Chatbot thisSocket.send(message.encode()) #Receive Message from ChatBot RMess = thisSocket.recv(1024).decode() #Print message from ChatBot print("Message Received from ChatBot: "+ str(RMess) + "\n") #print mealDict dictPrinter(mealDict) #choose meal message = raw_input("Message to ChatBot: ") thisSocket.send(message.encode()) #choose cuisine cuisineChoice = thisSocket.recv(1024).decode() print("Message Received from ChatBot: "+ str(cuisineChoice)) dictPrinter(cuisineDict) message = raw_input("Message to ChatBot: ") thisSocket.send(message.encode()) #does price matter? message = thisSocket.recv(1024).decode() print("Message Received from ChatBot: "+ str(message)) message = raw_input("Message to ChatBot: ") thisSocket.send(message.encode()) message = thisSocket.recv(1024).decode() print("Message Received from ChatBot: "+ str(message)) message = raw_input("Message to ChatBot: ") thisSocket.send(message.encode()) #does rating matter message = thisSocket.recv(1024).decode() print("Message Received from ChatBot: "+ str(message)) message = raw_input("Message to ChatBot: ") thisSocket.send(message.encode()) message = thisSocket.recv(1024).decode() print("Message Received from ChatBot: "+ str(message)) message = raw_input("Message to ChatBot: ") thisSocket.send(message.encode()) #recieve list of final restaurants message = thisSocket.recv(1024).decode() print("Message Received from ChatBot: "+ str(message)) #End or repeat message = thisSocket.recv(1024).decode() print("Message Received from ChatBot: " + str(message)) message = raw_input("Message to ChatBot: ") thisSocket.send(message.encode()) message = thisSocket.recv(1024).decode() if message == "end": break elif message == "repeat": continue #Close Socket thisSocket.close() #Display conversation is over print("Conversation between user and ChatBot Ended") #Check if running directly from this file if __name__ == '__main__': Main()
03733307ed44e7db11d511e47c24f6193f90494b
imask22/Python-Assignment
/ask/module3/validation_negative.py
303
3.921875
4
print("enter exit to exit the loop") while(1): ask=input("Enter no of product = ") whp=input("Enter wholesale price : ") if(whp=="exit"): break elif("-" in whp): continue else: whp=float(whp) print("retail price = ",whp*0.5*float(ask))
2b0740af2a4c8083bdedb35a35afd7d3255f8277
hauphanlvc/CS114
/CodeGiup/Thoa_ChieuCaoCuaCay.py
967
3.75
4
import collections class Node: def __init__(self,data): self.left=None self.right=None self.val=data def insert_tree(root,data): if root is None: return Node(data) else: if root.val==data: return root elif root.val<data: root.right=insert_tree(root.right,data) else: root.left=insert_tree(root.left,data) return root def Height(root): if root==None: return 0 else: a=Height(root.left) b=Height(root.right) if (a>b): return(a+1) else: return(b+1) root=None q=collections.deque() while True: l=([int(x) for x in input().split()]) if l[0]==3: break if l[0]==0: q.appendleft(l[1]) if l[0]==1: q.append(l[1]) if l[0]==2: if q.count(l[2])!=0: vt=q.index(l[1],0,len(q)) q.insert(vt+1,l[2]) else: q.appendleft(l[2]) while len(q)!=0: x=q.popleft() root=insert_tree(root,x) print(Height(root))
1c3a8b7e0f0ab924feda9535fe7d884dbf559930
astrochialinko/StanCode
/SC201/Class_Demo/SC201_L4/titanic_survived.py
5,263
3.75
4
""" File: titanic_survived.py Name: Chia-Lin Ko ---------------------------------- This file contains 3 of the most important steps in machine learning: 1) Data pre-processing 2) Training 3) Predicting """ import math TRAIN_DATA_PATH = 'titanic_data/train.csv' NUM_EPOCHS = 1000 ALPHA = 0.01 def sigmoid(k): """ :param k: float, linear function value :return: float, probability of the linear function value """ return 1/(1+math.exp(-k)) def dot(lst1, lst2): """ : param lst1: list, the feature vector : param lst2: list, the weights : return: float, the dot product of 2 list """ return sum(lst1[i]*lst2[i] for i in range(len(lst1))) def main(): # Milestone 1 training_data = data_pre_processing() # ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'] weights = [0]*len(training_data[0][0]) # Milestone 2 training(training_data, weights) # Milestone 3 predict(training_data, weights) # Milestone 1 def data_pre_processing(): """ Read the training data from TRAIN_DATA_PATH and get ready for training! :return: list[Tuple(data, label)], the value of each data on (['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'], 'Survived') """ training_data = [] with open(TRAIN_DATA_PATH, 'r') as f: is_first = True for line in f: if is_first: is_first = False else: feature_vector, label = feature_extractor(line) training_data.append((feature_vector, label)) return training_data def feature_extractor(line): """ : param line: str, the line of data extracted from the training set : return: list, the feature vector """ data_list = line.split(',') feature_vector = [] label = int(data_list[1]) # ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'] for i in range(len(data_list)): if i == 2: # Pclass feature_vector.append((int(data_list[i])-1)/(3-1)) elif i == 5: # Gender if data_list[i] == 'male': feature_vector.append(0) else: feature_vector.append(1) elif i == 6: # Age if data_list[i].isdigit(): feature_vector.append((float(data_list[i])-0.42)/(80-0.42)) else: feature_vector.append((29.699-0.42)/(80-0.42)) # average age elif i == 7: # SibSp feature_vector.append((int(data_list[i])-0)/(8-0)) elif i == 8: # Parch feature_vector.append((int(data_list[i])-0/(6-0))) elif i == 10: # Fare feature_vector.append((float(data_list[i])-0)/(512.33-0)) elif i == 12: # Embarked if data_list[i] == 'C': feature_vector.append((0-0)/2) elif data_list[i] == 'Q': feature_vector.append((2-0)/2) else: # S and missing value feature_vector.append((1-0)/2) return feature_vector, label # Milestone 2 def training(training_data, weights): """ : param training_data: list[Tuple(data, label)], the value of each data on (['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'], 'Survived') : param weights: list[float], the weight vector (the parameters on each feature) """ for epoch in range(NUM_EPOCHS): cost = 0 for x, y in training_data: ################################# h = sigmoid(dot(x, weights)) cost += -(y*math.log(h)+(1-y)*math.log(1-h)) # w = w - alpha * dL_dw # wi = wi - alpha * (h-y)*xi for i in range(len(x)): weights[i] = weights[i] - ALPHA * (h-y) * x[i] ################################# cost /= (2*len(x)) if epoch%100 == 0: print('Cost over all data:', cost) # Milestone 3 def predict(training_data, weights): """ : param training_data: list[Tuple(data, label)], the value of each data on (['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'], 'Survived') : param weights: list[float], the weight vector (the parameters on each feature) """ acc = 0 num_data = 0 for x, y in training_data: predict = get_prediction(x, weights) print('True Label: ' + str(y) + ' --------> Predict: ' + str(predict)) if y == predict: acc += 1 num_data += 1 print('---------------------------') print('Acc: ' + str(acc / num_data)) def get_prediction(x, weights): """ : param x: list[float], the value of each data on ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'] : param weights: list[float], the weight vector (the parameters on each feature) : return: float, the score of x (if it is > 0 then the passenger may survive) """ k = dot(x, weights) h = sigmoid(k) if h > 0.5: return 1 else: return 0 ''' # other solution if k > 0: return 1 else: return 0 ''' if __name__ == '__main__': main()
abc7ebb9f9cbdcac540f54e0e65deeb1812f2f2f
zwwpaul/CISC481-681_Programming1
/pancake.py
1,932
3.53125
4
class Pancake: def __init__(self, o): self.g = 0 self.h = 0 self.choice = o[4] self.elements = o self.maximum = int(self.elements[0] + self.elements[1] + self.elements[2] + self.elements[3]) self.length = len(o) self.path_dic_dfs =[] self.total_g = 0 self.path_dic_ucs = {} self.root=None self.parent=None self.left=None self.mid=None self.right=None self.visited = [] self.cakelist = [] self.astar = 0 # To eliminate all the element from the element list def clean_pancake(self): self.elements[:] = [] # To check whether pancake has the same value def check_same(self): flag = False for i in range(0, len(self.elements) - 1): for j in range(i + 1, len(self.elements)): if self.elements[i] == self.elements[j]: return True else: flag = False return flag # To update the value of h def update_h(self): self.h = 4 if self.elements[0] == "4": self.h = self.h - 1; if self.elements[1] == "3": self.h = self.h - 1; if self.elements[2] == "2": self.h = self.h - 1; if self.elements[3] == "1": self.h = self.h - 1; # To determine whether the process is end def is_end(self): if self.h == 0: return True else: return False def set_next(self): temp2 = [] temp3 = [] temp4 = [] temp2.append(self.elements[0]) temp2.append(self.elements[1]) temp2.append(self.elements[3]) temp2.append(self.elements[2]) temp2.append(self.choice) p2=Pancake(temp2) p2.g=2 self.cakelist.append(p2) temp3.append(self.elements[0]) temp3.append(self.elements[3]) temp3.append(self.elements[2]) temp3.append(self.elements[1]) temp3.append(self.choice) p3=Pancake(temp3) p3.g=3 self.cakelist.append(p3) temp4.append(self.elements[3]) temp4.append(self.elements[2]) temp4.append(self.elements[1]) temp4.append(self.elements[0]) temp4.append(self.choice) p4=Pancake(temp4) p4.g=4 self.cakelist.append(p4)
751835d654ea5f34d314204c2a854a8eb925a807
jedzej/tietopythontraining-basic
/students/kojalowicz_piotr/lesson_02/While loop/The second maximum.py
254
3.984375
4
integer = int(input()) firstMax = 0 secendMax = 0 while integer != 0: if firstMax < integer: secendMax = firstMax firstMax = integer elif secendMax < integer: secendMax = integer integer = int(input()) print(secendMax)
2f5e9926cf8f88a2e446dad5abf90c382d18946f
DirtNap/EulerSolutions
/p0010.py
225
3.5625
4
from util import prime_generator def main(): result = 0 for pn in prime_generator(2000000): result += pn print(f'The sum of prime numbers below 2000000 is {result}') if __name__ == '__main__': main()
98f8573110081a17ce7a41bbd31d2d04be6cd3a6
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/matrix/a83e05dd1d384c52a3364af6cafd9bd7.py
525
3.578125
4
class Matrix(object): def __init__(self, matrix): self.matrix = matrix # generate rows as list of lists self.rows = [] # first split on newline for item in self.matrix.split('\n'): # then split on space and convert string to int self.rows.append(map(int, item.split(' '))) # generate columns as list of lists # use '*' (splat) operator to unpack the argument list self.columns = [list (tuple) for tuple in zip(*self.rows)]
2d5d7427742d7ac9911e49ae3ebef0b8d0ff1ea1
yashshinde03/NLP
/NLP.py
538
3.5
4
import pandas as pd data = pd.read_csv('amazon_alexa.tsv',delimiter='\t')#read dataset # print(data.shape)#shape of dataset # print(data.head()) Head of dataset #If any missing value is their # print(data.isnull().sum()) # print(data.describe()) checking description of data # print(data.describe(include='object')) to check reviews #To check variation for valuecount # print(data['variation'].value_counts()) #To calculate the length of reviews # data['length'] = data['verified_reviews'].apply(len) # print(data['length'])
19ff245d7b1e41f95fbb23f78e29fa9d4b021c8c
xistadi/Python-practice
/PythonCourseYT-andrievskii/Урок 29 Тестирование/names.py
376
3.78125
4
from work import full_name print("Для остановки теста введите 'Q' ") while True: first = input("\nВведите ваше имя: ") if first == "Q": break last = input("\nВведите ваше фамилию: ") if last == "Q": break format_name = full_name(first, last) print("\tформатирование имени: " + format_name)
ea51bd964de87f131ec8ba33ccf8c3b288ec631e
kaitoulee/python-learn
/pylearn1.py
431
3.875
4
# coding=utf-8 __author__ = 'kaitouLee' #变量定义 ''' a = 10 b = 2 c = a + b print (c) ''' #判断定义 ''' 判断成绩是否及格 score = 90 if score>=80 : print("very Good") elif score >= 50 : print("good") elif score<=30 : print("no good") else : print("很差") ''' #判断条件是否成立 x = 5 if x>0: print 'x>0' a = 2 b = 8 if a < b: print'a<b' if a>b: print'a>b'
8654c0f5b5b7aeb59d2cef8fd96f83f896bc6a40
pppssm/discretemathpython
/sort.py
415
3.703125
4
def bubblesort(L): result = list(L) for x in xrange(len(result)-1): for y in xrange(len(result)-x-1): if (result[y] > result[y+1]): result[y], result[y+1] = result[y+1], result[y] return result def selectionsort(L): temp = list(L) result = [] while (len(temp) > 0): m = min(temp) result.append(m) temp.remove(m) return result
a8fe0e0f8c9be134def2723493b24fd510ccb60d
gabriellaec/desoft-analise-exercicios
/backup/user_114/ch41_2019_04_05_02_06_05_447383.py
157
4.03125
4
palavra=input('tentativa senha: ') if palavra!='desisto': palavra=input('tentativa senha: ') elif palavra=='desisto': print('Você acertou a senha!')
13cd261193732728dd907e963f342fe83e803e4d
mgmavely/turtle-racer
/main.py
952
4.1875
4
from turtle import Turtle, Screen import random screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput("Place Your Bet!", "Which turtle will win the race?") colors = ["red", "orange", "yellow", "green", "blue", "indigo"] turtles = [] y_coord = -100 for turtle_index in range(0,6): new_turtle = Turtle(shape="turtle") new_turtle.color(colors[turtle_index]) new_turtle.penup() new_turtle.goto(x=-230, y=y_coord) y_coord += 40 turtles.append(new_turtle) valid_race = False if user_bet: valid_race = True winner = "" while valid_race: for i in turtles: rng = random.randint(0, 10) i.forward(rng) if i.xcor() >= 230: winner = i.pencolor() valid_race = False break if winner == user_bet: print(f"Congrats! {winner} has won the race!") else: print(f"Sorry, {winner} beat {user_bet} to the finish line!") screen.exitonclick()
52683cdee91397d40ea4ee81da32e8783bedf76b
xizhang77/CodingInterview
/Twitter-OA/get-set-go.py
717
3.78125
4
# -*- coding: utf-8 -*- ''' Get set go ''' class Solution(object): def combinationSum(self, calories, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ calories.sort() check = set( [0] ) for cal in calories: if cal == target or target - cal in check: return True if cal + min( check ) > target: break temp = [ ] for val in check: temp.append( val + cal ) print temp check = check.union( set( temp ) ) return False s = Solution() print s.combinationSum( [2,9,5,1,6], 12 ) print s.combinationSum( [2,3,15,1,16], 8)
c55c1843a4d200a3bbaa29a9105b597179268a43
samiulla7/learn_python
/file_handling/file.py
2,102
3.78125
4
# ''' # Method Description # close() Close an open file. It has no effect if the file is already closed. # detach() Separate the underlying binary buffer from the TextIOBase and return it. # fileno() Return an integer number (file descriptor) of the file. # flush() Flush the write buffer of the file stream. # isatty() Return True if the file stream is interactive. # read(n) Read atmost n characters form the file. Reads till end of file if it is negative or None. # readable() Returns True if the file stream can be read from. # readline(n=-1) Read and return one line from the file. Reads in at most n bytes if specified. # readlines(n=-1) Read and return a list of lines from the file. Reads in at most n bytes/characters if specified. # seek(offset,from=SEEK_SET) Change the file position to offset bytes, in reference to from (start, current, end). # seekable() Returns True if the file stream supports random access. # tell() Returns the current file location. # truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location. # writable() Returns True if the file stream can be written to. # write(s) Write string s to the file and return the number of characters written. # writelines(lines) Write a list of lines to the file. # ''' # f = open("test.txt") # open file in current directory # f = open("C:/Python33/README.txt") # specifying full path # f = open("test.txt") # equivalent to 'r' or 'rt' # f = open("test.txt",'w') # write in text mode # f = open("img.bmp",'r+b') # read and write in binary mode # f = open("test.txt",mode = 'r',encoding = 'utf-8') # try: # f = open("test.txt",encoding = 'utf-8') # # perform file operations # finally: # f.close() with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file\n") f.write("This file\n\n") f.write("contains three lines\n") f = open("test.txt",'r',encoding = 'utf-8') f.read(4) # read the first 4 data # Output : 'This' f.read() # read in the rest till end of file # Output : 'my first file\nThis file\ncontains three lines\n'