blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5d3c19f976eb9ab855cd73c7597a07878076a7d6
VigneshKarthigeyan/DS
/Linked_List/user_inp_ll.py
738
3.75
4
#Add the user input data to Linked list class Node: def __init__(self,val): self.data=val self.next=None class LL: def __init__(self): self.head=None def printll(self): temp=self.head while(temp!=None): print(temp.data,end=' ') temp=temp.next print() def append(self,val): n_node=Node(val) temp=self.head while(temp.next!=None): temp=temp.next temp.next=n_node if __name__ == '__main__': ll1=LL() for i in range(0,4): x=int(input()) if(i==0): n=Node(x) ll1.head=n else: ll1.append(x) ll1.printll()
78baaad6885ac919eeeda1b29dccdaeed81659a0
ty1cube/Python-Is-Easy
/input and output/Tic-Tac-Toe-Part-B.py
3,298
4.3125
4
## # Tic Tac Toe, Part B Lecture ## # _*_ coding: utf-8 _*_ """ # The game should be similar to # | | 0 #----- 1 # | | 2 #----- 3 # | | 4 """ #!python3 # Define the function drawField that will print the game field # We will try to put our current field into the draw field def drawField(field): for row in range(5): #0,1,2,3,4 #0,.,1,.,2 # if row is even row write " | | " if row%2 == 0: practicalRow = int(row/2) # print writing lines # In this case , we have to adapt our field (3*3) to the actual drawing (5*5) # We can divde by 2 to get the correct maping for column in range(5): # will take values 0 (in drawing) -> 0 (in actual field), 1->., 2->1, 3->., 4->2 # if column is even, we will print a space # The even columns gives us the move of each player if column%2 == 0: # Values 0,2,4 # The actual column that should be used in our field # Make sure our values are integers practicalColumn = int(column/2) # Values 0,1,2 if column != 4: # Print the specific field print(field[practicalColumn][practicalRow],end="") # Continue in the same line else: print(field[practicalColumn][practicalRow]) # Jump to the next line else: # The odd value just give us vertical lines print("|",end="") else: print("-----") """ # We need to do the following 1. Apply and Save the move 2. Check which player turn is "X" or "O" """ # Create a variable for the Players Player = 1 # Create a list with each element corresponds to a column # currentField = [element1, element2, element3] # Let's simulate our playing field # In the first time, each list that correpond to a column will contains 3 empty spaces for the rows currentField = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] # A list that contains 3 lists # We will draw the current field drawField(currentField) # Create an infinite loop for the gamez while(True): # True == True / is always true (We can also use while(1)) # Display the player's turn print("Players turn: ",Player) # Ask user for input: to specify the desired row and column MoveRow = int(input("Please enter the row\n")) # Convert the row to integer MoveColumn = int(input("Please enter the column\n")) # Convert the column to integer if Player == 1: # Make move for player 1 # Access our current field # We only want to make one move when that specific field is empty if currentField[MoveColumn][MoveRow] == " ": currentField[MoveColumn][MoveRow] = "X" # Once Player 1 make his move we change the Player to 2 Player = 2 else: # Make move for player 2 if currentField[MoveColumn][MoveRow] == " ": currentField[MoveColumn][MoveRow] = "O" Player = 1 # At the end, draw the current field representation drawField(currentField)
4021bebd1e31f1c93a086e1db23a136ca007eb57
monalisa6/Titanic-Survival
/visualize.py
2,589
3.515625
4
import pandas as pd import matplotlib.pyplot as plt import utils # panda dataframe for loading csv files df = pd.read_csv("data/train.csv") utils.clean_data(df) fig = plt.figure(figsize=(24, 10)) # shows how many survived and how many died plt.subplot2grid((5,3), (0,0)) df.Survived.value_counts(normalize=True).plot(kind="bar", alpha=0.5) plt.title("Survived") # shows age of those who survived plt.subplot2grid((5,3), (0,1)) plt.scatter(df.Survived, df.Age, alpha=0.1) plt.title("Age wrt Survived") # shows how many passengers in each class plt.subplot2grid((5,3), (0,2)) df.Pclass.value_counts(normalize=True).plot(kind="bar", alpha=0.5) plt.title("Pclass") # shows distribution of age wrt passenger class plt.subplot2grid((5,3), (1,0), colspan=2) for x in [1,2,3]: df.Age[df.Pclass == x].plot(kind="kde") plt.title("Pclass wrt Age") plt.legend(("1st", "2nd", "3rd")) # shows how many embarked per port plt.subplot2grid((5,3), (1,2)) df.Embarked.value_counts(normalize=True).plot(kind="bar", alpha=0.5) plt.title("Embarked") # shows how many survived that have or doesn't have cabins plt.subplot2grid((5,3), (2,0), colspan=3) df.Cabin[df.Survived == 1].value_counts().plot(kind="bar", alpha=0.5) plt.title("Cabin wrt Survived") # shows how many survived w cabins and died with cabins plt.subplot2grid((5,3), (3,0), colspan=3) for x in [0,1,2,3]: df.Survived[df.Cabin == x].plot(kind="kde") plt.title("Survived wrt Cabin") plt.legend(("none", "A", "B", "C")) #, "D", "E", "F", "G")) print(len(df[(df.Survived == 1) & (df.Cabin != 0)])) #136 39.77% print(len(df[(df.Survived == 1) & (df.Cabin == 1)])) #A = 7 print(len(df[df.Cabin == 1])) #15 46.7% print(len(df[(df.Survived == 1) & (df.Cabin == 2)])) #B = 35 print(len(df[df.Cabin == 2])) #47 74.5% print(len(df[(df.Survived == 1) & (df.Cabin == 3)])) #C = 35 print(len(df[df.Cabin == 3])) #59 59.3% print(len(df[(df.Survived == 1) & (df.Cabin == 4)])) #D = 25 print(len(df[df.Cabin == 4])) #33 75.76% print(len(df[(df.Survived == 1) & (df.Cabin == 5)])) #E = 25 print(len(df[df.Cabin == 5])) #33 75.76% print(len(df[(df.Survived == 1) & (df.Cabin == 6)])) #F = 7 print(len(df[df.Cabin == 6])) #12 58.3% print(len(df[(df.Survived == 1) & (df.Cabin == 7)])) #G = 2 print(len(df[df.Cabin == 7])) #4 50% print(len(df[df.Survived == 1])) #342 print(len(df[df.Cabin != 0])) #204 plt.show()
6e0ab4c01cbb8ee9d65a78819adef7beb473441c
Utkarsh016/fsdk2019
/day7/currency.py
649
3.78125
4
""" Code Challenge Name: Currency Converter Convert from USD to INR Filename: currecncyconv.py Problem Statement: You need to fetch the current conversion prices from the JSON using REST API Hint: http://free.currencyconverterapi.com/api/v5/convert?q=USD_INR&compact=y Check with http://api.fixer.io/latest?base=USD&symbol=EUR """ import requests amount=input("Enter the amount") amount=int(amount) url1="https://free.currconv.com/api/v7/convert?q=USD_INR&compact=ultra&apiKey=3f76a8efcff1260f96f6" response=requests.get(url1) response=response.json() amount=amount*response["USD_INR"] print(amount)
fd8c60f1f70e09e066bd2d87c64af6007ea5a82c
moyehia2020/Mastering-Python
/web-Exercises 1 to 8 .py
2,099
3.8125
4
#[1] my_skills = ["HTML", "CSS", "JavaScript", "PHP", "Python"] x = 0 for i in my_skills: x+=1 print(x,i) #-------------------------------- print("====" * 9) #-------------------------------- #[2] def getNumbersBefore(num): for i in range(1,num): print(i, end="") if num <= 0 : print("Negative Numbers & Zero Not Allowed") return num print(getNumbersBefore(10)) # 12345678910 getNumbersBefore(0) # Negative Numbers & Zero Not Allowed getNumbersBefore(-1) # Negative Numbers & Zero Not Allowed #-------------------------------- print("====" * 9) #-------------------------------- #[3] word = "Elzero Web School" word1 = "Elzero Web School" word2 = "Youtube World" word3 = "We Love PHP" def getFirstLetter(word): word = word.split() for ii in word: print(ii[0], end="") return"" print(getFirstLetter(word)) # "EWS" print(getFirstLetter(word1)) # "EWS" print(getFirstLetter(word2)) # "YW" print(getFirstLetter(word3)) # "WLP" #-------------------------------- print("====" * 9) #-------------------------------- #[4] my_string = "I Love Elzero Web School" def countSubStrings(thesub, thestr): return thestr.count(thesub) print(countSubStrings("l", my_string)) # 4 #-------------------------------- print("====" * 9) #-------------------------------- #[5] numbers = [1, 2, 2, 2, 4, 5, 7, 2, 2, 8, 9] numbers = set(numbers) for n in numbers: print(n) #-------------------------------- print("====" * 9) #-------------------------------- #[6] thenumber = 195650432 def addCharacters(num) : return "{:,.2f}".format(num) print(addCharacters(thenumber)) # 195,650.432 #-------------------------------- print("====" * 9) #-------------------------------- #[7] my_skills = ["HTML", "CSS", "JS", "Python", ["Flask", "Django"], "MySQL"] for skill in my_skills: if type(skill) == list: for i in skill: print(f"--- {i}") else: print(f"- {skill}") #-------------------------------- print("====" * 9) #-------------------------------- #[8] my_list = [100, 20, 10, 11, -2, 1, 4, 200] print(min(my_list))
5776dbdcae93997a6aad93c23c9a13444dbea7c4
VictorBenoiston/Segundo_trabalho_calculo_numerico
/Questao_02/Sistema_linear.py
1,281
3.71875
4
from math import sqrt # Montando o sistema em si, é possível notarmos que c = 6,67 # Daí, ficamos com: # Linha 1: 36a+6b+c=17.33 # Linha 2: 100a+10b+c=42.67 # Achando a e b por meio de escalonamento: matriz = [[36, 6, 10.66], [100, 10, 36]] # Pivô = 36 # mL2 = 100/36 = 25/9 # Achando a nova linha 2: x = [36, 6, 10.66] for c in range(0, 3): elemento = matriz[1][c] - ((25/9) * matriz[0][c]) x.append(elemento) # Temos agora que b = -0.958 e a = 0.45569 def p2x(x): resultado = (0.45569 * (x ** 2)) - 0.958 * x + 6.667 return resultado def p2y(y): # resultado = (0.45569 * (x ** 2)) - 0.958 * x + (6.667 - y) a = 0.45569 b = -0.958 c = 6.667 - y def raizes(a, b, c): delta = b ** 2 - (4 * a * c) raiz_delta = sqrt(delta) return raiz_delta raiz_delta = raizes(a, b, c) x1 = ((b * (-1)) + raiz_delta) / (2 * a) x2 = ((b * (-1)) - raiz_delta) / (2 * a) if x1 > 0: return x1 if x2 > 0: return x2 else: print('inválido') p2x = p2x(7) print(f'O polinomio resultante será: P2(x)=0.45569x²-0.958x+6.667') print(f'No dia 07, a amostra atinge: {p2x:.2f}g') print(f'Utilizando interpolação inversa, vimos que a amostra chegará a marca de 10g em: x= {p2y(10):.2f}')
3aeab62672665da2514c63d86d3a6fbbe72a6926
aroraakshit/coding_prep
/partition_list.py
995
3.5625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 40ms def partition(self, head: ListNode, x: int) -> ListNode: if not head: return None init = ListNode(None) delete_later = init init.next = head forw = head while forw.next != None and forw.val < x: forw = forw.next init = init.next if not forw.next: return head while forw.next != None: if forw.next.val < x: tmp = forw.next forw.next = forw.next.next tmp.next = init.next if init.val == None: # new head head = tmp init.next = tmp init = init.next else: forw = forw.next del delete_later return head
f175025f24c343e3aa7162cb621f5d69f078ca4e
petertarnue/Python_Projects
/Data Analysis.py
4,080
3.9375
4
from csv import reader opened = open('artworks_final.csv', encoding='utf-8') read_file = reader(opened) moma = list(read_file) moma = moma[1:] print('\n') # Cleaning unwanted characters from the nationality and gender # column of moma dataset. nationality_f = [] gender_f = [] for row in moma: nationality = row[2] nationality = nationality.replace('(','') nationality = nationality.replace(')', '') nationality = nationality.title() if not nationality: nationality = "Nationality Unknown" row[2] = nationality nationality_f.append(nationality) gender = row[5] gender = gender.replace('(','') gender = gender.replace(')', '') gender = gender.title() if not gender: gender = " Gender unknown/Other" row[5] = gender gender_f.append(gender) ''' Data analysis question to answer: 1. Calculate how old the artist was when they created their work. 2.analyze and interpret the distribution of artist ages. 3.Create functions which summarize our data. 4.Print summaries in an easy-to-read-way. ''' unwanted_symbol = ['(',')','c.','','s'] def strip(string): for value in unwanted_symbol: string = string.replace(value, '') return string # 1. Calculating how old the artist was when they created their work. ages = [] for row in moma: c3 = row[3] c4 = row[4] c6 = row[6] birth_date = strip(c3) death_date = strip(c4) if birth_date != "": birth_date = int(birth_date) row[3] = birth_date if death_date != "": death_date = int(death_date) row[4] = death_date c_6 = strip(c6) if "-" in c_6: date = c_6.split("-") date_one = date[0] date_two = date[1] date_one = int(date_one) date_two = int(date_two) date = (date_one + date_two) / 2 date = round(date) if type(birth_date) == int: age = date - birth_date else: age = 0 ages.append(age) final_ages = [] for age in ages: if age > 20: final_age = age else: final_age = "Unknown" final_ages.append(final_age) print(final_ages) # Finding the frequencies of the nationality and # gender column of the moma dataset. gender_freq = {} for gd in gender_f[1:]: if gd not in gender_freq: gender_freq[gd] = 1 else: gender_freq[gd] += 1 nationality_freq = {} for nt in nationality_f[1:]: if nt not in nationality_freq: nationality_freq[nt] = 1 else: nationality_freq[nt] += 1 # Analysis of nationality column of moma dataset. # First method for nat, num in nationality_freq.items(): ex1 = "There are {num:,} {nat} pepple who contributed to the artworks of moma dataset." output = ex1.format(num = num, nat = nat) # second method ex = "The population of {c} is {s:,.2f} millions " for nat, size in nationality_freq.items(): out = ex.format(c=nat,s=size) #print(out) for gender, gen_size in gender_freq.items(): example = "There are {size:,} {gen} who contributed to this beautiful work" out = example.format(size = gen_size, gen = gender) exa = "The number of {f} who are actively working is {n:,}" for gen, g_size in gender_freq.items(): out = exa.format(f=gen, n=g_size) #print(out) # Analysis of Artist column in the moma dataset. artist_freq = {} for row in moma[1:]: artist = row[1] if artist in artist_freq: artist_freq[artist] += 1 else: artist_freq[artist] = 1 text = "{at_name} has contributed {nu} number artwork to this company." for art, num in artist_freq.items(): output = text.format(at_name = art, nu=num) #print(output) def art_summary(artist): num_artwork = artist_freq[artist] templete_string = "There are {num} artwork done by {name} in the moma dataset" output = templete_string.format(num=num, name= artist) print(output)
a909abdc274075fdc76997002d9188e12958049c
Laxmivadekar/lucky-list
/removing empty list.py
371
3.9375
4
a= [5, 6, [], 3, [], [], 9] # print('actual list is'+str(a)) # # Remove empty List from List # # using filter # res = list(filter(None, a)) # print(res) i=0 b=[] while i<len(a): if a[i]!=[]: b.append(a[i]) i=i+1 print(b) # Remove empty List from List # The original list is: [5, 6, [], 3, [], [], 9] # List after empty list removal: [5, 6, 3, 9]
d1249ebcc28881ba2915820ec246d12615162e6e
akilamg/Machine_Learning
/hw1_code_question/logistic.py
4,664
3.953125
4
""" Methods for doing logistic regression.""" import numpy as np from utils import sigmoid def logistic_predict(weights, data): """ Compute the probabilities predicted by the logistic classifier. Note: N is the number of examples and M is the number of features per example. Inputs: weights: (M+1) x 1 vector of weights, where the last element corresponds to the bias (intercepts). data: N x M data matrix where each row corresponds to one data point. Outputs: y: :N x 1 vector of probabilities of being second class. This is the output of the classifier. """ # TODO: Finish this function new_data = np.ones((data.shape[0], weights.shape[0])) new_data[:, :-1] = data z = new_data.dot(weights) y = sigmoid( z ) return y def evaluate(targets, y): """ Compute evaluation metrics. Inputs: targets : N x 1 vector of targets. y : N x 1 vector of probabilities. Outputs: ce : (scalar) Cross entropy. CE(p, q) = E_p[-log q]. Here we want to compute CE(targets, y) frac_correct : (scalar) Fraction of inputs classified correctly. """ # TODO: Finish this function ce = np.sum( -targets.T.dot( np.log(y) ) ) frac_correct = 0 for t,y_ in zip(targets,y): if t == round(y_): frac_correct += 1 frac_correct = frac_correct/float(y.shape[0]) return ce, frac_correct def logistic(weights, data, targets, hyperparameters): """ Calculate negative log likelihood and its derivatives with respect to weights. Also return the predictions. Note: N is the number of examples and M is the number of features per example. Inputs: weights: (M+1) x 1 vector of weights, where the last element corresponds to bias (intercepts). data: N x M data matrix where each row corresponds to one data point. targets: N x 1 vector of targets class probabilities. hyperparameters: The hyperparameters dictionary. Outputs: f: The sum of the loss over all data points. This is the objective that we want to minimize. df: (M+1) x 1 vector of accumulative derivative of f w.r.t. weights, i.e. don't need to average over number of sample y: N x 1 vector of probabilities. """ y = logistic_predict(weights, data) if hyperparameters['weight_regularization'] is True: f, df = logistic_pen(weights, data, targets, hyperparameters) else: # TODO: compute f and df without regularization new_data = np.ones((data.shape[0], data.shape[1] + 1)) new_data[:, :-1] = data z = new_data.dot(weights) f = np.squeeze( ( np.ones( (targets.shape) ) - targets).T.dot( z ) )+ np.sum( np.log( ( 1.0 + np.exp( -z ) ) ) ) df = new_data.T.dot( y - targets ) return f, df, y def logistic_pen(weights, data, targets, hyperparameters): """ Calculate negative log likelihood and its derivatives with respect to weights. Also return the predictions. Note: N is the number of examples and M is the number of features per example. Inputs: weights: (M+1) x 1 vector of weights, where the last element corresponds to bias (intercepts). data: N x M data matrix where each row corresponds to one data point. targets: N x 1 vector of targets class probabilities. hyperparameters: The hyperparameters dictionary. Outputs: f: The sum of the loss over all data points. This is the objective that we want to minimize. df: (M+1) x 1 vector of accumulative derivative of f w.r.t. weights, i.e. don't need to average over number of sample """ y = logistic_predict(weights, data) # TODO: Finish this function new_data = np.ones((data.shape[0], data.shape[1] + 1)) new_data[:, :-1] = data bias_weights = weights[weights.shape[0]-1] non_bias_weights = weights[:-1] z = new_data.dot(weights) non_bias_weights_pow_2 = np.square(non_bias_weights) log_p_w = - hyperparameters['weight_decay'] * np.sum( non_bias_weights_pow_2 ) /2.0 f = np.squeeze( ( np.ones((targets.shape) ) - targets ).T.dot(z)) + np.sum(np.log((1.0 + np.exp(-z)))) - log_p_w df_0 = np.sum(y - targets).reshape(1,1) df_j = data.T.dot(y - targets) + hyperparameters['weight_decay'] * non_bias_weights df = np.concatenate((df_j, df_0), axis=0) return f, df
d7674c8452d36b885b5d5bf1ba9b05e8822e2b4b
Jyotisri65/Python_development
/method_function_example.py
403
3.5625
4
''' ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter animal_crackers('Levelheaded Llama') --> True animal_crackers('Crazy Kangaroo') --> False ''' def animal_crackers(a): x=[] for y in a.split( ): x.append(y) if x[0][0]==x[1][0]: return True else: return False animal_crackers('Levelheaded Llama')
48249b6b67acc038a99bc1ef9d8301d27642c974
mtargon48/Engineering_4_notebook
/Python/splitlikemyparents.py
176
3.90625
4
#def split(text): text = input("slap a word in there big boi: ") woogoo = list(text) for i in woogoo: if(i == " "): print ('-') else: print(i+"\n")
904016527c39250d3a3b948660552835f30b85cb
GymBoss01/Odd-number
/Латанов ИСиП 1 ПР 8 Нечетные числа.py
138
3.578125
4
a=int(input("")) b=int(input("")) z=[] z.append(a) z.append(b) for i in range(a,b): if(i % 2 !=0): print(i)
3413a8a2721e297b849c28ee56244dfc86907a48
nehabais31/LeetCode-Solutions
/1721. Swapping Nodes in a Linked List.py
1,598
3.859375
4
# -*- coding: utf-8 -*- """ You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). """ class Node: def __init__(self,data = None): self.data = data self.next = None class Linked_List: def __init__(self): self.head = None def add_elements(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return tail = self.head while tail.next: tail = tail.next tail.next = new_node def print_list(self): print_val = self.head while print_val: # not NOne print(print_val.data, end = ' ') print_val = print_val.next class Solution: def swapNodes(self, head, k): slow = fast = head # For getting the kth node from beginning for i in range(k-1): fast = fast.next first = fast while fast.next: fast = fast.next slow = slow.next # At end of loop slow is pointing to kth node from end # Swap their data slow.data, first.data = first.data , slow.data return head ll = Linked_List() ll.add_elements(1) ll.add_elements(2) ll.add_elements(3) ll.add_elements(4) ll.add_elements(5) sol = Solution() sol.swapNodes(ll.head, 2) ll.print_list()
03aeccb60062fc25b2d215778928a160b209d4c8
SZTankWang/dataStructure_2020Spring
/hw2/question3_has_duplicate.py
901
4.0625
4
def has_duplicate(list1): """ remember to mention your runtime as comment! :param l: List -- list of integers :return: True if list1 has duplicate, return False otherwise. """ mem = {} #----O(1) for n in list1: #-----This for loop has O(n) runtime if n in mem: mem[n] += 1 #----O(1) else: mem[n] = 1 #----O(1) for i in mem.values(): #------This for loop has another O(n) runtime if i != 1: return True #----O(1) return False ###In all, the program has an O(n) runtime ''' Note: To get autograded on gradescope, you program can't print anything. Thus, please comment out the main function call, if you are submitting for auto grading. ''' def main(): print(has_duplicate([0,6,2,4,9])) # False print(has_duplicate([0,6,2,4,9,1,2])) # True if __name__ == '__main__': main()
bffcde3abadcd715f723580f77fd364dbfa35240
faustfu/hello_python
/iter02.py
339
3.828125
4
# Use iterator to get the first matched item without "break" statement and flags. items = ['book','apple','cup','rock'] def is_short(item:str)->bool: return len(item)<4 try: matched = next( item for item in items if is_short(item) ) print('The first matched item is', matched) except StopIteration: raise 'No one matched!'
8858d127e7336c7bf3d4f92664b0a527b23117c1
leilacey/LIS-511
/Chapter 3/pizza.py
1,186
4.34375
4
#4-1 Pizzas pizzas = ["Pepporoni", "Cheese", "Hawaiian", "Philly", "Smoked Mozzerella"] for pizza in pizzas: print ("I like " + pizza + " pizza.") print('I really love pizza') #4-2 Animals animals = ["Penguins", "Chickens", "Flamingos"] for animal in animals: print(animal + " are a bird.") print("All of these animals are birds.") #4-10 Slices print("The first three items in the list are:") for pizza in pizzas[:3]: print(pizza) print("The middle three items in the list are:") for pizza in pizzas[1:4]: print(pizza) print("The last three items in the list are:") for pizza in pizzas[-3:]: print(pizza) #4-11 My Pizzas, Your Pizzas friend_pizzas = pizzas[:] pizzas.append("Meat") friend_pizzas.append("Everything") print("My favorite pizzas are ") for pizza in pizzas: print(pizza + " ") print("My friend's favorite pizzas are ") for pizza in friend_pizzas: print(pizza + " ") #4-12 More Loops my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] print("My favorite foods are: ") for food in my_foods: print(food + " ") print("\nMy friend's favorite foods are: ") for food in friend_foods: print(food + " ")
6de42992acd079ef9638c45c10e29eb9d6e220b1
curiousest/interview-prep
/programming_tests/reverse_list.py
1,462
3.90625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: if m == n: return head curr_node = head if m == 1: prev_node = head curr_node = head.next first_reversed_node = head else: for _ in range(m - 2): curr_node = curr_node.next anchor_node = curr_node first_reversed_node = curr_node.next prev_node = curr_node.next curr_node = curr_node.next.next for _ in range(n - m): next_node = curr_node.next curr_node.next = prev_node prev_node = curr_node curr_node = next_node first_reversed_node.next = curr_node if m == 1: return prev_node else: anchor_node.next = prev_node return head first = ListNode(0) prev = first for i in range(1, 5): x = ListNode(i) prev.next = x prev = x def printit(node): while node is not None: print(node.val) node = node.next printit(first) print("start-------") z = Solution().reverseBetween(first, 1, 2) print("SOLUTION++++") printit(z)
16876cf9009dee2368fe67df67fa9c69e6308917
henuliyanying/pythonDemo
/countData.py
561
4.0625
4
#定义一个列表,并计算某个元素在列表中出现的次数 # def countX(lst,x): # count = 0 # for i in lst: # if(i == x): # count = count +1 # return count # lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] # x = 8 # print(countX(lst, x)) def countX(lst,x): return lst.count(x) lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print(countX(lst, x)) #总结:计算一个元素在一个列表中出现的个数 # 1、采用for循环,判断每个元素是否等于指定元素 # 2、直接使用python的内置函数count()
34337a96f8368bce2e517a575897374e44dbbcd7
league-python-student/level0-module1-bloobglob
/_03_if_else/_5_circle_calculator/circle_calculator.py
1,051
4.6875
5
from tkinter import simpledialog, Tk, messagebox import math # Write a Python program that asks the user for the radius of a circle. # Next, ask the user if they would like to calculate the area or circumference of a circle. # If they choose area, display the area of the circle using the radius. # Otherwise, display the circumference of the circle using the radius. if __name__ == '__main__': window = Tk() window.withdraw() radius = simpledialog.askinteger('Radius', 'Please enter a radius for your circle') input = simpledialog.askstring('Area or Circumference', 'Would you like the area or circumference?') if input.lower() == 'area': calculation = radius*radius*math.pi messagebox.showinfo('Area', 'The area is ' + str(calculation)) elif input.lower() == 'circumference': calculation = 2*math.pi*radius messagebox.showinfo('Circumference', 'The circumference is ' + str(calculation)) else: messagebox.showerror('Option Not Found', "Sorry, I don't understand")
3189215878f345ddf36882f296ae887b45e61805
FeedTheMind/exercise_playground
/python/misc_exercises/reverse/reverse.py
325
4.21875
4
def reverse(iterable): '''Returns reversed version of single iterable item Arguments: iterable = iterable item Returns: Reversed form ''' return iterable[::-1] print(reverse('!olleH')) print(reverse('!eybdooG')) forwards = map(reverse, ['!eybdooG ,!olleH']) print(list(forwards))
4d3d37836f6b5f84a3699021cd41e88d973159a8
MP-C/Python_games_Intro
/JobQuiz.py
3,790
4.28125
4
#environement #print => python <name>.pow #intro print("\n ***** Welcome to my first job founder quiz in Python! *****\n") playing = input("Do you want to play ?") # space in ? " allows visable anwser if playing != "yes": print("I am sorry. It is painfull reading this. I hope you come back later\n") quit() print("Ok! Let's play the Job Recrutement's Game \n") score = 0 #Question 1 answer = input ("What is my the name? ").lower() if (answer == "mario carvalho" or "mario"): print('Correct, next question!\n ') score += 1 elif (answer == "mario carvallo" or "carvalho"): print ("really?...almost there!\n") score +=0.5 else: print("Incorrect..nice try!\n") #question2 answer = input ("How many languages I speak ? ").lower() if (answer == "4"): print("Correct! You really paid atention. \n") score += 1 elif (answer == "3" ): print ("yes, you can say that\n") score +=1 else: print("Nop..sorry\n") #Question 3 answer = input ("What is my nationality ?\n ").lower() if (answer == "portugese" or "Portugese"): print("YES I AM!..You scored +1!\n") score += 1 else: print("You are not intirelly incorrect..but, no\n") #Question 4 answer = input ("How many programming languages I can code ? ").lower() if (answer == "4"): print("You are right!\n") score += 1 elif (answer == "3" ): print ("Oh yeah, nicelly done. But I usually say almost 4!\n") else: print("Really?! Are you sure?.. :/ \n") #Question 5 answer = input ("Do I know about React (Native&Expo), Express.js and Node.js ? ").lower() if (answer == "yes"): print("Yes, You know me!\n") score += 1 else: print("humm, well.. I am quite sure you aren't correct\n") #Question 6 answer = input ("Did I already work with Git, GitHub and Bash ? ").lower() if (answer == "yes"): print("In deed! \n") score += 1 elif (answer == "no" ): print ("Well, can you read again my skills description collumn, please ?\n") else: print("lol\n") #Question 7 answer = input ("Am I Prince2 and MBA certification, or only one? in this case, witch one? ").lower() if (answer == "yes"): print("Oh yeah! I AM!\n") score += 1 elif (answer == "Prince2" or "MBA"): print ("really?...almost there!\n") else: print("whats happened here?!..let's see next question..\n") #Question 8 answer = input ("What I like most: surf or diving? ").lower() if (answer == "surf"): print("Right, and next time, we will go together !\n") score += 1 elif (answer == "diving" ): print ("It doesn't appear on my CV..!\n") else: print("ai ai ai caramba\n") #Question 9 answer = input ("Did I alreafy work with:\na) MySQL, PostMAN and Node.Js\nb) a bit of postgreSQL, and a)\nc) None of above ?\n").lower() if (answer == "b" or "b)"): print ("CORRECT, it is b!\n") score += 1 elif (answer == "a" or "a)"): print("almost!..it is b\n") else: print("Ups..no..sorry\n") #Question 10 answer = input ("Last one, do I like manager some projects? yes or no? ").lower() if (answer == "yes"): print("I can't hide.. You are right!\n") score += 1 elif (answer == "no\n" ): print ("we must know each other..") else: print("no..not that..\n") ##score if (score == 10): print("All questions are correct. Nice one! As you can see, I do Python prety well, for a beginer, don't I ? ") elif (score == 0): print("Sorry, we must get to know each other better. Why not let me assign the job contract and found out what else I can do ? ") else: print("You got " + str(score) + " points on this questions.") #correct questions number print("that means then " + str((score/10) *100) + " % of this answers are correct. Nice job, you are almost thre!\n Another game?")#percentage quit() #finished
c7714546430a53c6adb455ff108681ce19c61504
zzlpeter/algorithm_practice
/Part1_Array/Code3_RandomPool.py
886
4.09375
4
"""设计RandomPool结构 功能: 不重复插入、删除、等概率随机返回 """ import random class RandomPool(object): def __init__(self): self.keyIndexMap = dict() self.indexKeyMap = dict() self.size = 0 def insert(self, key): if self.keyIndexMap.get(key) == None: self.size += 1 self.keyIndexMap[key] = self.size self.indexKeyMap[self.size] = key def delete(self, key): if self.keyIndexMap.get(key) != None: deleteIndex = self.keyIndexMap[key] lastKey = self.indexKeyMap[self.size] self.keyIndexMap[lastKey] = deleteIndex self.keyIndexMap.pop(key) self.indexKeyMap[deleteIndex] = lastKey self.indexKeyMap.pop(self.size) self.size -= 1 def getRandom(self): if self.size == 0: raise IndexError("The structure is empty!") randNum = int(random.random() * self.size + 1) return self.indexKeyMap[randNum]
ef484b7b6462ef6291b4610441686a515599a852
slz37/Personal-Projects
/Project Euler/coded_triangle_numbers.py
1,015
3.703125
4
#Triangle Number Definition def triangle(n): #First Term i = 1 term = 0.5 * i * (i + 1) #Run Until Term >= Sum of Digits while term < n: #Update i i += 1 #New Term term = 0.5 * i * (i + 1) #Boolean if Triangle Word if term == n: return True else: return False #Open File and Store Names words = open('words.txt', 'r') words = words.read().split(',') #Initial count = 0 alphabet = {'A': 1, 'B':2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, \ 'Q': 17, 'R': 18, 'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26} #Iterate For All Words for i in range(len(words)): #Length of Word size = len(words[i]) - 2 #Sum SUM = 0 #Iterate For Each Letter for j in range(1, size + 1): SUM += alphabet[words[i][j]] #Triangle Number if triangle(SUM): count += 1 #Output print count
554ecd7c0b38f9af5a8ed822bdc89d41d6ea0519
johnptmcdonald/pytorch_dl_cv
/walkthrough/linear_regression_03.py
1,646
3.828125
4
import torch import torch.nn as nn torch.manual_seed(1) x = torch.randn(100,1)*10 #100 rows, 1 column y = x + 3*torch.randn(100,1) class LR(nn.Module): def __init__(self, input_size, output_size): super().__init__() self.linear = nn.Linear(input_size, output_size) def forward(self, x): pred = self.linear(x) return pred model = LR(1,1) # ****************************** # Gradient descent # ****************************** criterion = nn.MSELoss() #define the loss function optimizer = torch.optim.SGD(model.parameters(), lr=0.01) #define the optimizer (stochastic gradient descent), and the thing we want to optimize (the model parameters) epochs = 100 losses = [] for i in range(epochs): y_pred = model.forward(x) loss = criterion(y_pred, y) print('epoch:', i, 'loss:', loss.item()) losses.append(loss) # https://stackoverflow.com/questions/53975717/pytorch-connection-between-loss-backward-and-optimizer-step # When you call loss.backward(), all it does is compute gradient of loss w.r.t all the parameters in loss that have requires_grad = True and store them in parameter.grad attribute for every parameter. # optimizer.step() updates all the parameters based on parameter.grad optimizer.zero_grad() #the optimizer zeroes out the grads of any tensors it is optimizing loss.backward() #computes the gradients for all tensors that have required_grad=True and were used in the calculation. The model parameters (which are tensors) then store their gradient optimizer.step() #the optimizer goes through each tensor it should be optimizing, and steps each one in the -ve direction of its stored gradient
97dab3f15faf1900eea530697b397a2d1277d993
nsmedira/python-for-everybody
/Data Structures/8_lists/exercise4.py
759
4.15625
4
# open the file romeo.txt try : filehandle = open('romeo.txt') except : print('Error opening file.') exit() # create a variable to hold all the words in romeo.txt in a list list_words = [] # read it line by line for line in filehandle : # for each line, split the line into a list of words using the split function words = line.split() #print(words) # for each word, check to see if the word is already in a list for line in words : # if a word is not in the list, add it to the list if not ( line in list_words ) : list_words.append(line) #print(list_words) # when the program completes, sort and print the resulting words in alphabetical order list_words.sort() print(list_words)
eb3704dfb5f450dd1ec738d60049efd0c79de160
Peixinho20/Python
/python/mundo1/a7/d6.py
329
3.984375
4
''' Crie uma algoritmo que leia um número e mostre o seu dobro, triplo e a raiz quadrada. até a aula 7 ''' n = float(input('Digite um número: ')) a = n*2 b = n*3 c = n**(1/2) print('O seu dobro é \033[4;37;46m{}\033[m, o seu triplo é \033[7;30;46m{}\033[m e a sua raiz quadrada é \033[0;31;40m{:.3f}\033[m'. format(a,b,c))
86e0adab45ea6e0a3350b5ac3c79d16c62dc811e
marinasupernova/codewars
/21-vowel-code/index.py
621
3.6875
4
def encode(st): output = st output = output.replace("e", "2") output = output.replace("a", "1") output = output.replace("o", "4") output = output.replace("u", "5") output = output.replace("i", "3") return output def decode(st output = st output = output.replace("2", "e") output = output.replace("1", "a") output = output.replace("4", "o") output = output.replace("5", "u") output = output.replace("3", "i") return output print(encode('hello')) print(encode('How are you today?')) print(encode('This is an encoding test.')) print(decode('h2ll4'))
dec10ca970efe66a583435d736aecea063109b7b
lhalbert/Coursera_Intro2Python
/Stopwatch.py
1,808
3.5625
4
# template for "Stopwatch: The Game" import simplegui import math # define global variables counter = 0 msgTime = "0:00.0" attempts = 0 score = 0 # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D def format(t): global msgTime A = t // 600 B = ((t // 10) % 60) / 10 C = ((t // 10) % 60) % 10 D = str(t)[len(str(t))-1:] msgTime = str(A)+":"+str(B)+str(C)+"."+str(D) #print msgTime[5:0] return msgTime # define event handlers for buttons; "Start", "Stop", "Reset" def start(): timer.start() #print timer.is_running() def stop(): global attempts, score, msgTime timer.stop() attempts += 1 #add a point if stopped on whole number if msgTime[5:] == "0": score += 1 else: return None def reset(): #reset all global variables to start new game global attempts, score, msgTime, counter attempts = 0 score = 0 msgTime = "0:00.0" counter = 0 # define event handler for timer with 0.1 sec interval def timer_handler(): global counter counter += 1 format(counter) # define draw handler def draw(canvas): global time canvas.draw_text(msgTime,[40, 100], 50, "Green") canvas.draw_text("Attempts:"+str(attempts), [2,20], 20, "Red") canvas.draw_text("Score:"+str(score), [130,20], 20, "Red") # create frame frame = simplegui.create_frame("Stop Watch'", 200, 150) timer = simplegui.create_timer(100, timer_handler) # register event handlers btnStart = frame.add_button("Start", start, 50) btnStop = frame.add_button("Stop", stop, 50) btnReset = frame.add_button("Reset", reset, 50) frame.set_draw_handler(draw) # start frame frame.start() # Please remember to review the grading rubric
baabcccdfafcf6f5a6a4ca6a71f1dc4de8e28d95
alpaziz/soultions
/lab_12/fib_while.py
360
3.953125
4
# Solution one: without recursion: def fib(n): first = 1 second = 1 count = 0 while(count < n): # increment the count count +=1 # save old first old_first = first # Update values first = second second = old_first + second return(first) def main(): print(fib(n=6)) if __name__ == '__main__': main()
21bde3e3dfd586c629d7f0a6fffb786b80e4ce4d
TakezoCan/rpgGame
/RPG_Game/Characters/get_weap.py
1,458
3.59375
4
from utilities import util def weapInput(prompt): weapon = input(prompt) return weapon.strip() def getWeapon(): class weapon(object): weapon_name = "" objects = {} def __init__(self, name, att_die, cost): self.name = name self.att_die = att_die, self.cost = cost weapon.objects[self.name] = self fist = weapon("fist", 2, 0), kubaton = weapon("kubaton", 4, 5), knife = weapon("knife", 4, 5), stick = weapon("stick", 4, 0), rusty_sword = weapon("rusty-sword", 6, 10), short_sword = weapon("short-sword", 7, 50), sword = weapon("sword", 8, 100), tanto = weapon("tanto", 10, 300), katana = weapon("katana", 15, 500), staff = weapon("staff", 10, 150) tempWeap = "" while True: tempWeap = weapInput("\nChoose your weapon. >> ") if tempWeap in weapon_list: yes = util.yesOrNo(tempWeap + ", is this the weapon you want? (Y/N) >> ") if yes: charWeap = weapon.objects[tempWeap] return charWeap.att_die else: pass else: continue weapon_list = { "fist", "kubaton", "knife", "stick", "rusty_sword", "short_sword", "sword", "tanto", "katana", "staff" }
11980578a97163f55a927fbd41e6af371fb85ae4
marcoscollares/Python-Scripts
/Aula #7/desafio006.py
342
3.90625
4
print('Desafio 006') print('\033[34mQual número você quer inserir?\033[m') n1 = int(input('Digite o número aqui: ')) dobro = n1*2 triplo = n1*3 raiz = n1*(1/2) print('O número digitado foi \033[1;35m{}\033[m, o seu dobro é \033[1;31m{}\033[m, o triplo \033[1;33m{}\033[m e a raiz \033[1;34m{}\033[m.'.format(n1, dobro, triplo, raiz))
f42a90bbfaa0ee27ad48cd8806efbd420bb2a0fd
mbg17/superlist
/day22/初始面向对象.py
1,533
3.640625
4
class Dog: def __init__(self, name, blood, aggr, kind): self.name = name self.blood = blood self.aggr = aggr self.kind = kind def bite(self, person): person.blood -= self.aggr print('%s被咬了,掉了%s血' % (person.name, self.aggr)) class Person: def __init__(self, name, blood, aggr, sex): self.name = name self.blood = blood self.aggr = aggr self.sex = sex def attack(self, dog): dog.blood -= self.aggr print('%s被打了,掉了%s血' % (dog.name, self.aggr)) class Game: def __init__(self, person, dog): self.person = person self.dog = dog def start(self): while True: self.dog.bite(self.person) if self.dog.blood == 0: print('%s死了' % self.dog.name) break self.person.attack(jin) if self.person.blood == 0: print('%s死了' % self.person.name) break jin = Dog('金老板', 100, 20, 'teddy') ren = Person('我', 100, 20, '男') Game(ren, jin).start() # 类中的静态变量可以被对象和类调用 # 类.__dict__ 只能查看不能修改 # 实例出来的对象指向同一个类 # 不可变类变量最好用类调用 ,可变类变量可以用对象调用 # 练习题 # 创建一个类,没实例化一个对象就记录下来 class foo: count = 0 def __init__(self): foo.count += 1 f_1 = foo() f_2 = foo() print(f_2.count)
cdd400973110469e0dce2534fcd1e715de1129a0
ae-freeman/Hackerrank-challenges
/dicts-hashmaps/count-triplets.py
1,445
3.953125
4
#!/bin/python3 import math import os import random import re import sys # Complete the countTriplets function below. def countTriplets(arr, r): #initialise dicts and count r2 = {} r3 = {} count = 0 #loop through array for k in arr: #if the current value is in the dict for third numbers, then there has been two previous numbers that will satisfy a triplet for this number k, so increase the count for how many times there is a satisfied triplet if k in r3: count += r3[k] #if the current value is in the dict for second numbers, there has been a number before that will satisfy the condition. Need to add value * r to the third numbers dict so it is ready to find new triplets. if k in r2: #if it is already there, increase it, could be multiple triplets if k*r in r3: r3[k*r] += r2[k] else: r3[k*r] = r2[k] #Otherwise, it needs to be added to r2 to see if any future numebrs will satisfy the condition. if k*r in r2: r2[k*r] += 1 else: r2[k*r] = 1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
cc586894f4a036ac7d5c6dc5e346046bf146b399
PlumpMath/SICPviaPython
/Chapter-2/2.2/Exercise-2.27.py
1,251
3.71875
4
# Scheme primitive procedures cons = lambda x, y: lambda m: m(x, y) car = lambda z: z(lambda p, q: p) cdr = lambda z: z(lambda p, q: q) makeList = lambda *items: None if items == () else cons(items[0], makeList(*items[1:])) appendList = lambda list1, list2: list2 if list1 == None else cons(car(list1), appendList(cdr(list1), list2)) def printList(items): displayList = lambda items: '[' + displayItems(items) + ']' displayItems = lambda items: displayItem(car(items)) if cdr(items) == None \ else displayItem(car(items)) + ', ' + displayItem(cdr(items)) if not callable(cdr(items)) \ else displayItem(car(items)) + ', ' + displayItems(cdr(items)) displayItem = lambda item: '[]' if item == None \ else str(item) if not callable(item) \ else displayList(item) print(displayList(items)) # Deep reverse def deepReverse(items): if items == None: return None elif callable(car(items)): return appendList(deepReverse(cdr(items)), makeList(deepReverse(car(items)))) else: return appendList(deepReverse(cdr(items)), makeList(car(items))) x = makeList(makeList(1, 2), makeList(3, 4)) printList(deepReverse(x)) # [[4, 3], [2, 1]]
6ef2481d44864b95c539ec7b297c7727804fa385
Kite1024/DAB-testrun2
/algorithm.py
2,366
3.984375
4
from lib import run_algorithm, Direction, GameState def step(state: GameState): """ This method is called every time the pawn is about to move. :param state: contains the state of the game. See readme.md for the available functions. :return: the direction in which the pawn has to move. """ return doublestep(state) def simplestep(state: GameState): """ Simple algorithm """ # If the cell below is free, go south if state.cell_safe(state.pawn_row() + 1, state.pawn_column()).is_empty(): return Direction.SOUTH # If the cell to the right is free, go east if state.cell_safe(state.pawn_row(), state.pawn_column() + 1).is_empty(): return Direction.EAST # If the cell above is free, go north if state.cell_safe(state.pawn_row() - 1, state.pawn_column()).is_empty(): return Direction.NORTH # If the cell ot the left is free, go west if state.cell_safe(state.pawn_row(), state.pawn_column() - 1).is_empty(): return Direction.WEST # Any normal print output is shown in the gameconsole. print("Oh no! Nowhere to go") # If nothing is returned, the pawn will move in the same direction as the previous step def doublestep(state: GameState): """ Checks for non-wall entities """ """ Simple algorithm """ # If the cell below is free, go south if state.cell_safe(state.pawn_row() + 1, state.pawn_column()).is_empty() and state.cell_safe(state.pawn_row() + 2, state.pawn_column()).is_empty(): return Direction.SOUTH # If the cell to the right is free, go east if state.cell_safe(state.pawn_row(), state.pawn_column() + 1).is_empty() and state.cell_safe(state.pawn_row(), state.pawn_column() + 2).is_empty(): return Direction.EAST # If the cell above is free, go north if state.cell_safe(state.pawn_row() - 1, state.pawn_column()).is_empty() and state.cell_safe(state.pawn_row() - 2, state.pawn_column()).is_empty(): return Direction.NORTH # If the cell ot the left is free, go west if state.cell_safe(state.pawn_row(), state.pawn_column() - 1).is_empty() and state.cell_safe(state.pawn_row(), state.pawn_column() - 2).is_empty(): return Direction.WEST # Any normal print output is shown in the gameconsole. print("Oh no! Nowhere to go") run_algorithm(step)
e3ec80452888995b0cf027a9dbe122737f58459a
albertoferreirademelo/13-random-programs-bioinformatics
/py1-Ferreira.py
422
3.71875
4
#Sequences input seq1 = "ATACCGGCCTATAACXCGGAA" seq2 = "ATGATATGGAGGAGGTAGCCGCG.CGCCATGCGCGCTXATATTTTGGTAT" #needed variables list_DNA = [] #Task 1 (attaching DNA string from sequence 2 to sequence 1. task1 = seq1+seq2 print (task1) #making a list with legal DNA sequences. for i in task1: if (i == 'A' or i == 'T' or i == 'C' or i == 'G'): list_DNA.append(i) print (list_DNA)
b9fa6441073746288fe4947c541bc4670e75be19
born2trycn/SunNing
/20191207-2.py
448
3.828125
4
month = 1 day = 1 if (month==12): if (day == 24): print('今天是平安夜哦,记得吃苹果) elif (day == 25): print('圣诞老人会给你小礼物哦') if (month == 1): if (day == 1): print('今天是新年哦,新的一年也要好好努力呀') elif (day == 15): print('今天是元宵节!汤圆很好吃!') if (month == 2): if (day == 2): print('二月二,龙抬头')
2ef589a8d6013e81198c54cb8c6505634e87a02d
dbms-ops/learn_python_3
/1_learn_python_3/8-类与对象/8-子类中扩展property.py
2,251
3.75
4
#!/data1/Python2.7/bin/python2.7 # -*-coding:utf-8-*- # @date: 2020/4/16 20:51 # @user: Administrator # @fileName: 子类中扩展property # @description: 扩展定义在父类中的property # ; # class Person: def __init__(self, name): self.name = name # Getter function @property def name(self): return self._name # Setter function @name.setter def name(self, value): if not isinstance(value, str): raise TypeError('Excepted a string') self._name = value # Deleter function @name.deleter def name(self): raise AttributeError("Can't delete attribute") class SubPerson(Person): """ 继承自 Person 并扩展了 name 属性的功能 """ @property def name(self): print("Getting name") return super().name @name.setter def name(self, value): print("Setting name to ", value) super(SubPerson,SubPerson).name.__set__(self, value) @name.deleter def name(self): print('Deleting name') super(SubPerson, SubPerson).name.__delete__(self) def sub_person_example(): s = SubPerson('Guido') print(s) print(s.name) s.name = "Larry" # A descriptor class String: def __init__(self, name): self.name = name def __get__(self, instance,cls): if isinstance is None: return self return instance.__dict__[self.name] def __set__(self, instance, value): if not isinstance(value, str): raise TypeError('Except a string') instance.__dict__[self.name] = value # A class with a descriptor class Person: name = String('name') def __init__(self, name): self.name = name # Extending a descriptor with a property class SubPerson(Person): @property def name(self): print('Getting name') return super().name @name.setter def name(self, value): print('Setting name to', value) super(SubPerson,SubPerson).name.__set__(self,value) @name.deleter def name(self): print('Deleting name') super(SubPerson,SubPerson).name.__delete__(self) def main(): sub_person_example() if __name__ == '__main__': main()
f6824417f791963cf6d7ceca3c8f4561eb1afa21
kpunith8/python_samples
/classes_oop.py
1,561
4.21875
4
class Person: # constructor def __init__(self, real_name): self.real_name = real_name def report(self): print("I'm {}".format(self.real_name)) class Agent(Person): # Agent inherits Person class # class object attribute planet = "Earth" def __init__(self, real_name, eye_color, height): Person.__init__(self, real_name) self.eye_color = eye_color self.height = height def report(self): print("Overriding the Person's report()") # _ defines a private method which won't be accessible directly def _secrets(self): print("secrets") # Pythons built-in functions can be overridden, this function prints the string representation of this class def __str__(self): return "Name is {}, eye colour is {}, and height is {}.".format( self.real_name, self.eye_color, self.height ) # agent = Agent("Punith", "black", 165) # agent1 = Agent("Rama", "blue", 178) # agent.report() # allows calling Person's methods using Agent's object # agent._secrets() # print(agent) # print(agent1) # print(agent.real_name, agent.eye_color, agent.height) # print(agent1.real_name, agent1.eye_color, agent1.height) class Circle: pi = 3.14 def __init__(self, radius=1): self.radius = radius def area(self): return Circle.pi * self.radius * self.radius def perimeter(self): return 2 * Circle.pi * self.radius # circle = Circle(3) # print("Area of circle:", circle.area(), " Perimeter:", circle.perimeter())
acddd3dcaa291a3b854b0da23050fd62fdfdad7e
drdcs/Algorithms-and-System-Design
/StackQueue/nextGreaterElement.py
1,471
3.828125
4
""" Next greater element: input: [18,7,6,12,15] output:[-1,12,12,15,-1] 18, 7, 6, """ class Stack: def __init__(self): self.stack = [] def isEmpty(self): return len(self.stack) == 0 def push(self, val): self.stack.append(val) def pop(self): if self.isEmpty(): print("Error: stack is empty") else: return self.stack.pop() def __repr__(self): return f"value: {self.stack}" def getNextGreater(array): s = Stack() s.push(array[0]) for i in range(1, len(array)): next = array[i] if s.isEmpty() == False: # if stack is not empty element = s.pop() # if poped element is smaller than the next # append the result # keep popping up while element are smaller # and stack is not empty while element < next: print("element: ", element, "next: ", next) if s.isEmpty == True: break element = s.pop() # if element is greater than next then push # the element if element > next: s.push(element) s.push(next) if __name__ == '__main__': array = [18,7,6,1,15] # stack = Stack() # for i in array: # stack.push(i) # print(stack) # stack.pop() # stack.pop() # print(stack) print(getNextGreater(array))
1dad04a33f71cb1c922e399113d4b69d4ffa271d
austinma1/Canadian-Computing-Competition-Solutions
/ccc2019j3.py
439
3.96875
4
def count (string): while len(string) > 0: list = [string[0]] for i in range(1,len(string)): if string[i] == string[0]: list.append(string[i]) else: break print(len(list),list[0],end=" ") string = string[len(list):] return x = int(input()) strings = [input().strip()for i in range(x)] for string in strings: count(string) print()
7aa86e8db123e4fab33d21ea7872c2d35c8e0d87
alisid03/ACM-Research-Coding-Challenge-F21
/SentiAnalyses.py
1,225
4.03125
4
#string import to remove punctuation and translate text into cleanedText import string #NLTK library that will be used from nltk.corpus import stopwords from nltk.corpus.reader.chasen import test from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize #text is stored in here text = open('input.txt').read() #changes all letters in the text to lowercase(to ensure that the words we are comparing are all the same case) lower_case = text.lower() """Remove punctuations""" cleaned_text = lower_case.translate(str.maketrans('','',string.punctuation)) #This function uses the sentiment analyzer to determine the sentiment score of the text and outputs the result def SentimentAnalysis(analyze_text): score = SentimentIntensityAnalyzer().polarity_scores(analyze_text) neg = score['neg'] pos = score['pos'] neu = score['neu'] print (score) if pos > neg : print("The text has a positve sentiment") elif neg > pos : print("The text has a negative sentiment") else: print("The text has a neutral sentiment") SentimentAnalysis(cleaned_text)
9a73399989fc78a7c22f5d49adf147160b30724a
ccoughlin/SkinDepth
/material/MaterialDB.py
5,589
3.609375
4
'''MaterialDB.py - defines a SQLITE3 backend for Material I/O Chris Coughlin ''' import sqlite3 import Material class MaterialDB(object): '''Handles mapping between the SQLite database and the Material class''' def __init__(self, dbfile): '''Required parameter - filename of database to use. Can use ':memory:' as per sqlite3 module to keep database in memory only.''' self.dbfilename = dbfile def connect(self): '''Connects to the instance's database and creates the database cursor. Raises sqlite3.OperationalError if unable to open the database. ''' self.dbconnection = sqlite3.connect(self.dbfilename) self.dbcursor = self.dbconnection.cursor() def create(self): '''Creates the materials table in the database''' self.dbcursor.execute( '''create table if not exists materials(name text unique, notes text, conductivity_iacs real, rel_permeability real)''' ) self.update() def update(self): '''Commits the changes to the database''' self.dbconnection.commit() def add(self, newmaterial, update=False): '''Adds / replaces (if material of same name already exists in database) a material to the database. If update is True, the changes are commited to the database after execution (default is False). ''' if isinstance(newmaterial, Material.Material): self.dbcursor.execute('insert or replace into materials values (?,?,?,?)', ( newmaterial.name, newmaterial.notes, newmaterial.iacs, newmaterial.mu_r )) if update: self.update() def retrieve(self, materialname): '''Retrieves the material of the given name from the database, or None if not found.''' self.dbcursor.execute('select * from materials where name=?', (materialname,)) row = self.dbcursor.fetchone() if row is None: return row else: return Material.Material( name = row[0], notes = row[1], sigma_iacs = row[2], mu_rel = row[3] ) def retrieveall(self): '''Retrieves all the materials currently in the database''' allmaterials = [] self.dbcursor.execute('select * from materials order by name asc') alldata = self.dbcursor.fetchall() if alldata is not None: for row in alldata: allmaterials.append( Material.Material( name = row[0], notes = row[1], sigma_iacs = row[2], mu_rel = row[3] ) ) return allmaterials def delete(self, materialname, update=False): '''Deletes the material of the given name from the database. If update is True, the changes are commited to the database after execution (default is False). ''' self.dbcursor.execute("delete from materials where name=?", (materialname,)) if update: self.update() def undo(self): '''Rollback the changes to the database since the last commit.''' self.dbconnection.rollback() def close(self, update=False): '''Closes the connection to the database. If update is True, changes are commited to the database prior to close (default is False). ''' if update: self.update() self.dbconnection.close() def exportsql(self, export_file): '''Wrapper for dumping database to SQL script text file''' with open(export_file, 'w') as fidout: for row in self.dbconnection.iterdump(): fidout.write('%s\n' % row) def importsql(self, import_file): '''Imports a SQL script and executes, returning the total number of changes made.''' self.connect() self.create() dbwalker = MaterialDB(":memory:") dbwalker.connect() with open(import_file, 'r') as fidin: dbwalker.dbconnection.executescript(fidin.read()) imported_records = dbwalker.retrieveall() for amaterial in imported_records: self.add(amaterial) return self.dbconnection.total_changes def importdb(self, import_file): '''Attempts to import a SQLite database into the current. Only materials not already in the database are imported. Returns the total number of additions made to the database. ''' try: otherdb = MaterialDB(import_file) otherdb.connect() otherdb.dbcursor.execute('select * from materials order by name asc') import_materials = otherdb.dbcursor.fetchall() if import_materials is not None: for newmaterial in import_materials: self.dbcursor.execute('insert or ignore into materials values (?,?,?,?)', newmaterial) materials_added = self.dbconnection.total_changes self.update() otherdb.close() return materials_added except sqlite3.OperationalError: #Unable to read the import database raise
c36daf0819d6280171b39f62bef969be3c969ac5
doraemon1293/Leetcode
/archive/1275. Find Winner on a Tic Tac Toe Game.py
1,367
3.546875
4
class Solution: def tictactoe(self, moves: list) -> str: def f(arrs): f = False for i in range(3): if all([x == "X" for x in arrs[i]]): return "A" if all([x == "O" for x in arrs[i]]): return "B" if all([x == "X" for x in list(zip(*arrs))[i]]): return "A" if all([x == "O" for x in list(zip(*arrs))[i]]): return "B" if " " in arrs[i]: f = True if all([x == "X" for x in [arrs[0][0], arrs[1][1], arrs[2][2]]]): return "A" if all([x == "O" for x in [arrs[0][0], arrs[1][1], arrs[2][2]]]): return "B" if all([x == "X" for x in [arrs[0][2], arrs[1][1], arrs[2][0]]]): return "A" if all([x == "O" for x in [arrs[0][2], arrs[1][1], arrs[2][0]]]): return "B" return "Pending" if f else "Draw" arrs = [[" "] * 3 for _ in range(3)] for i in range(len(moves)): x, y = moves[i] p = "X" if i % 2 == 0 else "O" arrs[x][y] = p for x in arrs: print(x) return f(arrs) moves = [[2,0],[1,1],[0,2],[2,1],[1,2],[1,0],[0,0],[0,1]] print(Solution().tictactoe(moves))
a2b7bd1fbde4f3f9b4c9622293a9d808fb107a5d
alex-lenk/python_fast_start
/les01.py
229
3.59375
4
# coding : utf-8 print ("Моя первая программа") print ("Привет программист") name = input("Ваше имя:") print ("Привет", name, "добро пожаловать в мир python!")
0c15968a458c8d542ee48711b305cf2cc7ba123e
JulianMendezw/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
119
3.59375
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): return [[x[i]**2 for i in range(len(x))]for x in matrix]
c7b8517ab037ec06752b3319bb45da4343d2bdd4
leinian85/year2019
/month01/code/day07/exercise01.py
309
3.5625
4
''' 字典推导式 ''' list01 = ["张无忌","赵敏","小昭","周芷若"] list02 = [101,102,103,104] dict_all = {item:len(item) for item in list01} print(dict_all) dict_all2 = {list01[i]:list02[i] for i in range(0,4)} print(dict_all2) dict_all03 = {v:k for k,v in dict_all2.items()} print(dict_all03)
2fc3d05f42005193a318967ab445f8b0d674e0e6
EppalaMounika/DS290521E
/W09 D02/27 July Jupyter.py
3,382
3.765625
4
#!/usr/bin/env python # coding: utf-8 # In[9]: import time,csv class Product: 'Common base class for all Product' prodCount = 0 prod_list=[] H =[] def __init__(self, PROD, MANF, PRICE, QUAN): self.PROD = PROD self.MANF = MANF self.PRICE = PRICE self.QUAN = QUAN Product.prodCount += 1 Product.prod_list.append([self.PROD, self.MANF, self.PRICE, self.QUAN]) def displayCount(self): print("Total Product %d" % Product.prodCount) def displayProduct(self): print("PROD : ", self.PROD, " MANF: ", self.MANF, " PRICE: ", self.PRICE , " QUAN: ", self.QUAN) print(Product.prod_list) def deleteProduct(self): PROD = input('enter the product you want to Delete\n\n') for i in range(len(Product.prod_list)): if Product.prod_list[i][0] == PROD: Product.prod_list.pop(i) H.append('Delete') break print(Product.prod_list) def CreateProduct(self): print('Enter the below details\n\n') pn= input('enter product name: ') time.sleep(1) mf= input('enter mfname: ') time.sleep(1) price = input('enter price: ') time.sleep(1) qn=input('enter quantity: ') Product.prod_list.append([pn,mf,price,qn]) print(Product.prod_list) H.append('Create') def ViewProduct(self): PROD = input('enter the product you want to View\n\n') print('showing details for: ',PROD) for i in range(len(Product.prod_list)): if Product.prod_list[i][0] == PROD: print("PROD : ",Product.prod_list[i][0]) print("MANF: ", Product.prod_list[i][1]) print("PRICE: ", Product.prod_list[i][2]) print("QUANTITY: ", Product.prod_list[i][3]) break H.append('View') # In[1]: class Signup: def __init__(self): self.cred = {} def reg(self, user, passw): self.cred[user] = passw def check(self, user, pas): print(self.cred ) if user in self.cred.keys() and pas == self.cred[user] : print("Successful! Welcome to amazon") else: print('Incorrect Entry!') # In[ ]: s = Signup() refresh = False while refresh == False: action = (input('What would you like to do? enter Reg Login exit \n')) if action == 'Reg': Name = (input('Please enter username ')) passw= (input('Please enter password ')) s.reg(Name, passw) if action == 'Login': Name1 = (input('Please enter Username ')) passw1 = (input('Please enter Password ')) s.check(Name1,passw1) refresh =True if action == 'exit': print("See you later!") refresh =True # In[4]: P =Product('PROD','MANF','PRICE','QUAN') print(P.prod_list) P.CreateProduct() P.CreateProduct() P.CreateProduct() P.CreateProduct() # # In[10]: P =Product('PROD','MANF','PRICE','QUAN') print(P.prod_list) P.CreateProduct() P.CreateProduct() P.CreateProduct() P.CreateProduct() P.ViewProduct() P.deleteProduct() # In[6]: # In[ ]: # In[ ]:
60d9fae4fec7e40d6240b46dfcc7dadab17879ea
JagdishChavan081/diabetes_prediction
/diabetes_Ml/2_code/app.py
2,898
3.921875
4
# Description: This program detets if someone has diabets using machine learning and Python ! #Import the Libraries import pandas as pd from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import RandomForestClassifier from PIL import Image import streamlit as st #create a title and sub-title st.write(""" # Diabetes Detection Detect if someone has diabetes using machine learning and python ! """) #Open and display an Image image = Image.open('/home/jc/project/diabetes_Ml/5_resources/download.jpeg') st.image(image,caption='Diabetes using ML',use_column_width=True) #get The data df = pd.read_csv('/home/jc/project/diabetes_Ml/3_dset/diabetes.csv') #set the subheader on web app st.subheader('Data Information: ') #show the data as a table st.dataframe(df) #show statictics on data st.write(df.describe()) #show the data as a chart st.bar_chart(df) #Split the data into independent 'x' and dependent 'y' variables x = df.iloc[:,0:8].values y=df.iloc[:,-1].values #split the dataset into 75% training and 25% testing x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.25, random_state=0) # get the feature input from the user def get_user_input(): Pregnancies = st.sidebar.slider('Pregnancies',0,17,3) Glucose= st.sidebar.slider('Glucose',0,199,117) BloodPressure = st.sidebar.slider('BloodPresure',0,122,72) SkinThickness = st.sidebar.slider('SkinThickness',0,99,23) Insulin = st.sidebar.slider('Insulin',0.0,846.0,30.5) BMI = st.sidebar.slider('BMI',0.0,67.1,32.0) DiabetesPedigreeFunction = st.sidebar.slider('DiabetesPedigreeFunction',0.078,2.42,0.3725) Age = st.sidebar.slider('Age',21,81,29) #store a dictonary into a variable user_data = {"Preagnancies":Pregnancies, "Glucose":Glucose, "BloodPressure":BloodPressure, "SkinThickness":SkinThickness, "Insulin":Insulin, "BMI":BMI, "DiabetesPedigreeFunction":DiabetesPedigreeFunction, "Age":Age } #transform the data into data frame features = pd.DataFrame(user_data, index=[0]) return features #Store the user inpt into a variable user_input=get_user_input() #set a subheader and display the user input st.subheader('User Input') st.write(user_input) #create and train the model RandomForestClassifier = RandomForestClassifier() RandomForestClassifier.fit(x_train, y_train) #show the models metrics st.subheader('Model Test Accuracy Score:') st.write(str(accuracy_score(y_test, RandomForestClassifier.predict(x_test)) *100)+"%") #Store the model prediction in a variable prediction = RandomForestClassifier.predict(user_input) #set a subheader and display the classification st.subheader('Classification') st.write(prediction)
b242f65a23bc751c3299fa72a76bc04d84e6eba6
tsarep/learning_py
/1.3.py
609
4
4
# Реализуйте при помощи python и библиотеки math (import math) нахождение корней квадратного уравнения по формуле дискриминанта. # На всякий случай общая формула дискриминанта x1,2=−b±√(b2−4ac)/2a import math print('Введите a:') a = int(input()) print('Введите b:') b = int(input()) print('Введите c:') c = int(input()) x1 = -b + math.sqrt(b * b - 4 * a * c) / 2 * a x2 = -b - math.sqrt(b * b - 4 * a * c) / 2 * a print('x1 = ', x1) print('x2 = ', x2)
5a7d096f2da06b830d4b8ce4b070318c60ecd8b7
jishnusen/pykarel
/run.py
1,442
4.28125
4
#!/usr/bin/env python3 import Karel # Above code is setup # Once you complete a level, check with a programmer! # Then, they will give you the next level level = 5 # Want an extra challenge? # When you get to level 3, try to get the robot to move using the # .front_is_clear() and .check_beeper() functions # Setup code startPosition = {1:[10,1],2:[2,1],3:[2,11],4:[2,2],5:[16,1]} karel = Karel.Robot(startPosition[level][0], startPosition[level][1], Karel.SOUTH, beepers=100) world = Karel.World("worlds/level"+str(level)+".txt") world.add_robot(karel) world.set_speed(1) # End setup code # This is Karel: ►, Karel is your robot # Your objective: Navigate through the maze to reach the end # How do I move? # There are 3 basic functions, or commands for the robot # # .move() - moves the robot forward one space # .turnleft() - turns the robot to the left 90 degrees # .turnright() - turns the robot to the right 90 degrees # # Functions (commands) for later levels: # .pick_beeper() - picks up a beeper (represented by symbol 'o') # .put_beeper() - puts down a beeper (if you have one) # .front_is_clear() - checks if you are able to move forward safely # .check_beeper() - checks if a beeper is in front of you # .beeper_count() - tells you the number of beepers that you have # Put your code below: karel.move() karel.move() karel.turnleft() karel.move() karel.move() karel.move() karel.turnright() karel.move() karel.move()
83a1c139c3ef685b45c9230af47f3c90ae9ec8d9
Hondral49/Trabalho-Python---ALYSSON-SANTIN
/exercicio_dez.py
790
3.890625
4
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] somapar = maior = somacoluna = 0 for l in range(0, 3): for c in range(0, 3): matriz[l] [c] = int(input(f'Digite um valor para [{l}, {c}]: ')) print('xsz' * 55) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz [l] [c]:^5}]', end= '') if matriz [l] [c] % 2 == 0: somapar += matriz [l] [c] print() print('xsz' * 55) print(f'A soma dos valores pares é: {somapar} ') for l in range(0, 3): somacoluna += matriz [l] [2] print(f'A soma dos numeros da terceira coluna é: {somacoluna}') for c in range(0, 3): if c == 0: maior = matriz[1] [c] elif matriz [1] [c] > maior: maior = matriz[1] [c] print(f'O maior valor da segunda linha é: {maior}')
3f9c704a8a10cb5df13c53f9ae30fcda8d775ea9
tiwariaditya15/pythonPractice
/decorators.py
525
3.640625
4
class Duck : def __init__(self, **args): self.properties = args def getProperties(self): return self.properties def getProperty(self, key): return self.properties.get(key, None) @property def color(self): return self.properties.get('color', None) @color.setter def color(self, c) : self.properties['color'] = c @color.getter def color(self) : return self.properties obj = Duck(color = "red") obj.color = 'Red' print(obj.color)
395e33e4dc4cafc404b90f7bc55a99b8c84a6688
RIMPOFUNK/FirstLyceumCourse
/Lesson 3 (Простые встроенные функции)/Classwork/Каникулы капризного ребёнка.py
386
4.25
4
town1 = input() town2 = input() towns = ["Пенза", "Тула"] if town1 not in towns and town2 not in towns or town1 == town2\ or town1 in towns and town2 in towns and town1 != town2\ or town2 == "Тула" or town1 == "Пенза": print("НЕТ") elif town1 == "Пенза" or town1 == "Тула" or town2 == "Тула" or town2 == "Пенза": print("ДА")
7671eff466be489947203b2e0e316893d7fc3931
Dheeraj-1999/interview-questions-competitve-programming
/python/programs python/factorial using rec.py
143
3.71875
4
def fact(a): global b if a>1: b=a*fact(a-1) return b b=1 a=int(input("enter the number")) c=fact(a) print(c)
3fdf945a4a513edd99c947f557ef84f2fadaaee1
cseharshit/Python_Practice_Beginner
/74.reverse_word_sequence.py
138
3.984375
4
def string_rev(str): str = str.split() str.reverse() return ' '.join(str) print(string_rev(input("Insert some strings: ")))
f493309c134804da7b183c1344c18175a4981c53
sky-dream/LeetCodeProblemsStudy
/[0169][Easy][Majority Element]/MajorityElement_3.py
338
3.640625
4
#solution 3, sort, # leetcode time cost : 152 ms # leetcode memory cost : 13.2 MB # Time Complexity: O(nlgn) # Space Complexity: O(1) or O(N) class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return nums[len(nums)//2]
0a3e870a9b32421cbb888566ae25d5e442fbb4f9
yilunchen27/leetcode_learn
/LeetCode_Python-master/Algorithm-Easy/568_Binary_Tree_Tilt.py
1,151
4.125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTilt(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 def subTreeSum(root): if not root: return 0 lsum = subTreeSum(root.left) rsum = subTreeSum(root.right) self.ans += abs(lsum - rsum) return root.val + lsum + rsum subTreeSum(root) return self.ans """ The tilt of the whole tree is defined as the sum of all nodes' tilt. Example: Input: 1 / \ 2 3 Output: 1 Explanation: Tilt of node 2 : 0 Tilt of node 3 : 0 Tilt of node 1 : |2-3| = 1 Tilt of binary tree : 0 + 0 + 1 = 1 Note: The sum of node values in any subtree won't exceed the range of 32-bit integer. All the tilt values won't exceed the range of 32-bit integer. """
1e81662388d538e549dbd9be334da5a3e2d249a5
DongGeun2/Python_Study
/StuDy/Int_Folder/Int_Treat.py
351
3.671875
4
print(abs(-5)) # 절대값 : 5 print(pow(4, 2)) # 4^2 = 16 print(max(5, 10)) # 최대값 : 10 print(min(5, 10)) # 최저값 : 5 print(round(4.6)) # 올림 : 5 #--------------------------------------- from math import * # math 모든 함수 사용 print(floor(3.99)) # 내림 : 3 print(ceil(3.99)) # 올림 : 4 print(sqrt(25)) # 제곱근 5
79a95c6f3c120202940f94f7f3f942e484c63e43
Sushanthkengunte/analysis
/seperate_Maps.py
279
3.765625
4
import pandas as pd filename = "Data/sample.csv" # columns = ["a","b","c","d","e","f","g","h","i","j","k"] df = pd.read_csv(filename,sep=",",header=None,names = ["a","b","c","d","e","f","g","h","i","j","k"]) print(df) # df2 = df[df.f != "MIRAMAR" ] # df = df[df.f == "MIRAMAR"]
14f76df424a7567c4d11ff7394b305209ddfe4e0
MicahEng/Hazy_star
/Python/19.5.17_spider/analyze.py
1,813
3.5
4
#coding=utf-8 from bs4 import BeautifulSoup #全部的收缩结果 def parseHtml(text): soup = BeautifulSoup( text, features="lxml" ) tags = soup.find_all( 'span' ) #寻找所有的span标签 for tag in tags: cont = tag.string if( cont is not None and cont.startswith( '百度为您找到相关结果约' )): #此处可进行查询优化 cont = cont.lstrip( '百度为您找到相关结果约' ) cont = cont.rstrip( '个' ) cont = cont.replace( ',', '' ) return eval(cont) def printurl(text): #打印出所有搜索结果中网站的URl以及网站名字 soupurl = BeautifulSoup( text, features="lxml" ) #通过分析,搜索结果的标题都是存放在h3中的 tagsurl = soupurl.find_all( 'h3' ) #使用循环将网站以及对应的url传入到字典中 dicturl = {} for tagurl in tagsurl: url = [x['href'] for x in tagurl.select('a')][0] #使用列表生成式子,以及select方法提取搜索结果的url dicturl.update({tagurl.get_text():url}) return dicturl #排除广告 def parseHtmlSel(text): soupSel = BeautifulSoup( text, features="lxml" ) tagsSel = soupSel.find_all('a') sum = 0 #用于计数 for tagSel in tagsSel: if(tagSel.string == "广告"): #求取单个页面不是广告的搜索条目的个数 sum += 1 return sum def EndSel(text): #用于结束搜索的函数 flag = True temp = [] soupEnd = BeautifulSoup( text, features="lxml" ) #通过分析,搜索结果的标题都是存放在h3中的 tagsEnd = soupEnd.find_all( 'a' ) for tagEnd in tagsEnd: temp.append(tagEnd.string) if('下一页>' not in temp): flag = False return flag
128bb67a2bf84ea1ee462828dfc37bdc20e4fc72
TaylorJohnson1024/Python-Assignments
/Assignment 3/Assignment 3 - Taylor Johnson.py
2,211
4.3125
4
#Taylor Johnson #Assignment 3 #September 12, 2016 #This function outputs an 'E' made up of smaller "E's" #The function takes two inputes, the "E's" width and height #The "E" itself is composed of 5 parts #If the user inputs a height non-divisible by 5 than the remainder is appropriately distributed to specific part(s) #If the user inputs a width non-divisible by 4 than the width is rounded to its nearest integer def PrintE(): EWidth, EHeight = eval(input("Enter the width and height of the letter E: ")) HeightRemainder = EHeight % 5 Count = 0 STRINGE = "E" EWidth1 = 0 EWidth2 = 0 EWidth3 = 0 EWidth4 = 0 EWidth5 = 0 EHeight1 = 0 EHeight2 = 0 EHeight3 = 0 EHeight4 = 0 EHeight5 = 0 #Distribution of remaining height lines if (HeightRemainder == 1): EHeight3 += 1 elif (HeightRemainder == 2): EHeight2 += 1 EHeight4 += 1 elif (HeightRemainder == 3): EHeight1 += 1 EHeight3 += 1 EHeight5 += 1 elif (HeightRemainder == 4): EHeight1 += 1 EHeight2 += 1 EHeight4 += 1 EHeight5 += 1 #Setting the character limits for each part's width and height EWidth1 += EWidth EWidth2 += EWidth // 4 EWidth3 += EWidth // 2 EWidth4 += EWidth // 4 EWidth5 += EWidth EHeight1 += EHeight // 5 EHeight2 += EHeight1 + EHeight // 5 EHeight3 += EHeight2 + EHeight // 5 EHeight4 += EHeight3 + EHeight // 5 EHeight5 += EHeight4 + EHeight // 5 #Assignment just requires "loops", not specifically "for" loops #Loop Part 1 while (Count < EHeight1): print(STRINGE * EWidth1) Count += 1 #Loop Part 2 while (Count < EHeight2): print(STRINGE * EWidth2) Count += 1 #Loop Part 3 while (Count < EHeight3): print(STRINGE * EWidth3) Count += 1 #Loop Part 4 while (Count < EHeight4): print(STRINGE * EWidth4) Count += 1 #Loop Part 5 while (Count < EHeight5): print(STRINGE * EWidth5) Count += 1 input("Press enter to close program.") PrintE()
1eb2b3bb6c1e5bb69dc88d0bc870f0222076806f
yibre/Computer_Algorithm
/prob1EX1.py
6,229
3.515625
4
# -*- coding: utf-8 -*- ''' #### problem 1-1. finding minimum #### Input: target change n denomination D = [d1,...,dj] Temporary lists: M[n], denotes a minimum number of coins to make change of n SE380 cents. R[n], denotes a way to make change of n SE380 cents, using M[n] number of cents. Output: Output shoud be a list, with following components. [number_of_necessary_coins, coin1_num, coin2_num, ... , coinj_num] 리스트, 전체 코인의 숫자와 코인의 개수 별 종류 ''' def minchange_student(n, D): # initialize list. M = [0 for i in range(n + 1)] R = [[0 for col in range(len(D))] for row in range(n + 1)] # previous provided code K = [[0 for i in range(n + 1)] for i in range(len(D))] ''' 코드 설명을 위해 n = 11, D = [1, 5, 6, 8] 로 가정하고 각 코드가 끝날 때마다 리스트 K의 상태를 업데이트하겠습니다. K = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] K는 list of list 형태로 열의 개수는 코인의 종류이며 행의 개수는 n+1개입니다. K[i][j]는 j 원일때 코인의 종류가 D[:i+1]까지 있다고 가정하고 최소한의 코인으로 지불할 수 있는 코인의 수입니다. ex) K[1][10] = 10원일때 1원짜리와 5원짜리로 10원을 최소한의 코인으로 지불하는데 필요한 코인의 수 ''' for i in range(0, n+1): K[0][i] = i ''' K = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] K의 첫번째 열은 1원짜리 코인으로 n원까지 지불하는데 필요한 코인의 수입니다 ''' for i in range(1,len(D)): for j in range(0, n+1): if (j == D[i]) or (j > D[i]): # case 1 K[i][j] = min(K[i-1][j], K[i][j-D[i]]+1) else: # case 2 K[i][j] = K[i-1][j] ''' K = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] K[1]을 예시로 1원과 5원짜리밖에 없는데 n원을 지불해야 한다고 가정하면, 우선 1~4원을 지불할 때, 즉 case 2에 해당할 때, 5원짜로는 1~4원을 지불할 수 없으므로 K[0][j] 방법대로 지불해야합니다. 고로 K = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [0, 1, 2, 3, 4, min(0+1, 5), 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] 그러나 5원 이상을 지불할 때, 즉 case 1에 해당할 때 n원 금액을 두 가지 방법으로 지불할 수 있습니다 i) 5원짜리로 지불하는 방법 ( K[1][j-5] 의 코인에서 5원 하나를 지불하니 +1개를 더함 ) ii) 1원짜리로 지불하는 방법 ( K[0][j] 개수의 코인으로 지불할 수 있음) i과 ii의 방법 중 더 작은 코인으로 지불할 수 있는 방법을 선택해야합니다. min(0+1, 5) 0+1은 K[1][0]의 수에 5원 코인 1개를 더한 수치이고 5는 1원짜리 다섯개로 지불하는 수치입니다. 따라서 min(K[i-1][j], K[i][j-D[i]]+1) 이와 같은 방식으로 마지막 코인의 열까지 전부 채워주면 마지막 행 마지막 열이 가장 해당 액수를 지불하는 가장 최소 코인의 수가 됩니다 ''' return find_coins(K, len(D)-1, n, D) # 이중 리스트를 거슬러 올라가며 list[i][j]가 어디에서 왔는지 찾고, 만약 D[i] 코인이 사용되었으면 이를 반환합니다 def find_coins(list, i, j, D): coins = [] while (list[i][j] != 0): if list[i][j] == list[i-1][j]: i = i-1 else: coins.append(D[i]) j = j-D[i] temp2 = coins temp = [0 for i in range(len(D))] for k in range(len(temp2)): for i in range(len(D)): if temp2[k] == D[i]: temp[i] += 1 return temp ''' #### problem 1-2. finding number of distinctive ways. #### Input: target change n denomination D= [d1,...,dj] Temporary lists: N[m][n], denotes a number of distinctive ways to make change of n SE380 cents with m kind of denominations. Output: 얼마나 다양한 방법으로 지불할 수 있는가 an integer value which denotes a number of distinctive ways to make change of n SE380 cents. ''' def numways_student(n, D): N = [[0 for col in range(n + 1)] for row in range(len(D) + 1)] for i in range(len(D)+1): N[i][0] = 1 ''' 코드의 설명을 위해 n = 10, D = [1, 4, 7] 로 가정하고 N의 상태를 업데이트하겠습니다 N = [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ''' for i in range(len(D)): for j in range(1, n+1): if (j > D[i]) or (j == D[i]): # case 1 N[i][j] = N[i-1][j]+N[i][j-D[i]] else: # case 2 N[i][j] = N[i-1][j] ''' N[i+1][j]는 j원을 D[0]~D[i] 까지의 코인을 사용해서 지불할 수 있는 방법의 개수입니다 N= [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3], [1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] N[-1][j]는 1원을 이용하여 지불할 수 있는 방법의 개수입니다. case 2의 경우, 총액 10원을 낸다고 할 때 4원으로 1~3원을 지불할 수 없으니 해당 열보다 한 칸 전, 즉 N[i-1][j] 열의 방법을 가져와야 합니다. 그러나 case 1의 경우, 4원 이상부터는 4원을 쓰는 방법과 해당 열의 한 칸 전 방법을 고수하는 두 가지 방법이 있으니 N[i][j] = N[i-1][j]+N[i][j-D[i]] 가 됩니다. ''' return N[len(D)-1][n] # test case # print(numways_student(10, [1, 4, 7])) # print(minchange_student(11, [1,5,6,8]))
e0aaf4db06f5cf6b0ba527f5e7e2d925fe551080
owdqa/OWD_TEST_TOOLKIT
/scripts/csv_writer.py
1,663
3.546875
4
import os from datetime import datetime from csv import DictWriter class CsvWriter(object): def __init__(self, device, version): self.device = device self.version = version def create_report(self, fieldnames, row, outfile, daily=True): """Create a new entry in the CSV report file. Write a new row in the CSV report file given by outfile, corresponding to the fields in fieldnames. If daily is True, it will generate a different header, if the file is not found. """ write_header = False if not os.path.isfile(outfile): write_header = True with open(outfile, 'a+') as csvfile: csvwriter = DictWriter(csvfile, fieldnames=fieldnames, delimiter=',', lineterminator='\n') headers = dict((h, h) for h in fieldnames) # If the file is new, let's write the required header if write_header: # Write the week number, in the ISO 8601 format header = self.generate_header(daily) csvfile.write(header) # Write the CSV header row csvwriter.writerow(headers) # Write the data csvwriter.writerow(row) def generate_header(self, daily=True): header = "" if daily: header = "Last test executions, DATE: {}\n".format(datetime.now().strftime("%d/%m/%Y %H:%M")) header += "Device: {}\n".format(self.device) header += "Version: {}\n".format(self.version) else: header = "WEEK NUMBER: {}\n".format(datetime.now().isocalendar()[1]) return header
999ea61d1afb2caaaee2fe0a6e238af259f73f12
monteua/Python
/String/31.py
260
4.25
4
''' Write a Python program to print the following floating numbers with no decimal places. ''' x = 3.1415926 y = -12.9999 print "Original number:", x print "New number:", '{:.0f}'.format(x) print "Original number:", y print "New number:", '{:.0f}'.format(y)
4ffdb036e5903d27dc208adac96281e1f50a00a6
akffhaos95/pythonCode
/basic/sqlite/sqliteTest3.py
234
3.578125
4
import sqlite3 conn = sqlite3.connect("example.db") c = conn.cursor() sql = 'SELECT * FROM STOCKS ORDER BY PRICE' c.execute(sql) rows = c.fetchall() print(rows) print(type(rows)) for i in rows: print(i) c.close() conn.close()
f7c25fb009be5e13a5c966cd5c7716b0653ba811
lopez86/NYCDataTools
/nyc/plotting/MapPlotter.py
3,820
3.578125
4
""" MapPlotter.py Plot a map of data given the data and a mapper object that contains the shapes information. """ __author__ = "Jeremy P. Lopez" __date__ = "2017" __copyright__ = "(c) 2017, Jeremy P. Lopez" from matplotlib.collections import PatchCollection from descartes import PolygonPatch from shapely.geometry.polygon import Polygon from shapely.geometry import shape import matplotlib as mpl import matplotlib.pyplot as plt import numpy class MapPlotter: """ A class to make plots of geospatial data given a mapper object containing the region polygons. """ def __init__(self,mapper): """ Initialize the object using a given mapper. Attributes: mapper: The mapper object cmap: A matplotlib colormap name nan_color: A default color for missing values region_list: A list of region codes if not all regions are to be plotted metadata: A dataframe with metadata. """ self.mapper = mapper self.cmap = 'inferno' self.nan_color = [0.7,0.7,0.7] self.region_list = None self.metadata = None def set_cmap(self,c): """ Set the colormap. """ self.cmap = c def set_nan_color(self,c): """ Set the color for NaN/empty values. """ self.nan_color = c def set_region_list(self,rl): """ Set the list of regions if only some regions are to be plotted. """ self.region_list = rl def plot(self,values,ax,area_norm=False,color_label=""): """ Make a plot. Parameters: values: A dictionary type object with the values. ax: The matplotlib axis object area_norm: If true, divide values by the region areas. color_label: The label on the color axis. Note: The colorbar object is saved as self.cbar for further customization. """ if area_norm is True: self.metadata = self.mapper.get_metadata() self._patches = [] self._nanpatches = [] xlimits = numpy.array([200.1,-200.1]) ylimits = numpy.array([200.1,-200.1]) self._value_arr = [] for region in self.mapper.regions: sh = shape(region['geometry']) reg_id = self.mapper.get_region_id(region) if self.region_list is not None and \ reg_id not in self.region_list: continue bounds = sh.bounds xlimits = [numpy.min([xlimits[0],bounds[0]]), numpy.max([xlimits[1],bounds[2]])] ylimits = [numpy.min([ylimits[0],bounds[1]]), numpy.max([ylimits[1],bounds[3]])] try: value = values[reg_id] if area_norm is True: value /= self.metadata.loc[reg_id,'area'] self._value_arr.append(value) self._patches.append(PolygonPatch(sh)) except: self._nanpatches.append(PolygonPatch(sh)) self._p = PatchCollection(self._patches,cmap=self.cmap,alpha=0.8) self._p.set_array(numpy.array(self._value_arr)) self._np = PatchCollection(self._nanpatches,color=self.nan_color, alpha=0.5) ax.add_collection(self._p) ax.add_collection(self._np) xlimits = [xlimits[0]-0.01,xlimits[1]+0.01] ylimits = [ylimits[0]-0.01,ylimits[1]+0.01] ax.set_xlim(xlimits) ax.set_ylim(ylimits) ax.set_ylabel('Latitude [deg]') ax.set_xlabel('Longitude [deg]') self.cbar = plt.colorbar(self._p,cmap=self.cmap,ax=ax) self.cbar.set_label(color_label,rotation=270)
3761a329529f47684b57f059a38906e644ca740c
leonwooster/leonwoo-server-Python
/MLPPytorch.py
1,705
3.65625
4
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F # Get reproducible results torch.manual_seed(0) # Define the model class MLP(nn.Module): def __init__(self, num_inputs, num_hidden_layer_nodes, num_outputs): # Initialize super class super().__init__() # Add hidden layer self.linear1 = nn.Linear(num_inputs, num_hidden_layer_nodes) # Add output layer self.linear2 = nn.Linear(num_hidden_layer_nodes, num_outputs) def forward(self, x): # Forward pass through hidden layer with x = F.relu(self.linear1(x)) # Foward pass to output layer return self.linear2(x) # Num data points num_data = 1000 # Network parameters num_inputs = 1000 num_hidden_layer_nodes = 100 num_outputs = 10 # Training parameters num_epochs = 200 # Create random Tensors to hold inputs and outputs x = torch.randn(num_data, num_inputs) y = torch.randn(num_data, num_outputs) # Construct our model by instantiating the class defined above model = MLP(num_inputs, num_hidden_layer_nodes, num_outputs) # Define loss function loss_function = nn.MSELoss(reduction='sum') # Define optimizer optimizer = optim.SGD(model.parameters(), lr=1e-4) for t in range(num_epochs): # Forward pass: Compute predicted y by passing x to the model y_pred = model(x) # Compute and print loss loss = loss_function(y_pred, y) print(t, loss.item()) # Zero gradients, perform a backward pass, and update the weights. optimizer.zero_grad() # Calculate gradient using backward pass loss.backward() # Update model parameters (weights) optimizer.step()
59ee506ec48573bf400280401e971011d7f75649
gospelg/oupinger
/main.py
1,309
3.546875
4
import socket from time import sleep #identifies the txt file with the list of computers to resolve the_file = raw_input('Where is the file with the list of computers to test? \n') #this is the file that contains the computers that did not match the ip pattern out_file = 'wrongoucomputers.txt' #this file is the list of computers whose dns name could not be resolved err_file = 'couldnotresolve.txt' #this asks the user what ip pattern they would like to match. bingo = raw_input("What ip case would you like to match? (anything that does not contain this string will be flagged) \n") #opens the file and adds each line to a list with open(the_file, 'r') as f: la_lista = f.read().splitlines() #resolves the dns name for a certain index of the list. Checks to see if the pattern is contained in the ip address it resolved def checker(x): try: dog = socket.gethostbyname(la_lista[x]) if bingo not in dog: with open(out_file, 'a') as g: g.write(la_lista[x] + '\n') else: pass except: with open(err_file, 'a') as k: k.write(la_lista[x] + ' could not find host address for this one \n') #calls checker on every index in la_lista for i in range(len(la_lista)): checker(i) print 'Your files are in whatever directory cmd is running in now.' sleep(20)
d72f5c8233da8c9a6ee04bd6f955f8a517405f04
chinaylssly/elevator
/schedule.py
7,062
3.5
4
# _*_ coding:utf-8 _*_ from elevator import Elevator from globaltask import GlobalTask from threading import Thread from config import MAX_FLOOR,MIN_FLOOR from time import sleep import random from copy import deepcopy class FactoryElevator(object): count=0 @classmethod def add_elevator(cls,): cls.count+=1 return Elevator(name=cls.count) class Schedule(object): def __init__(self,count=3): self.elevators=[FactoryElevator.add_elevator() for i in range(count)] self.GlobalTask=GlobalTask def __new__(cls): ##单例模型 if hasattr(cls,'instance'): print u'Schedule exists instance' else: cls.instance=object.__new__(cls) return cls.instance def analyze_distance(self,elevator,task_flag,floor): ##计算任务与电梯距离 if elevator.isalive: if elevator.flag==1 : if floor>=elevator.destination: distance=floor - elevator.current_floor elif floor < elevator.destination and floor >= elevator.current_floor: if task_flag==1: distance=floor - elevator.current_floor else: # distance=elevator.destination - elevator.current_floor + elevator.destination - floor distance=MAX_FLOOR*2 else: # distance=elevator.destination - elevator.current_floor + elevator.destination - floor distance=MAX_FLOOR*2 elif elevator.flag==0: distance=abs(elevator.current_floor - floor) else: ## elevator.flag==-1 if floor >=elevator.current_floor: # distance=elevator.current_floor - elevator.destination + floor - elevator.destination distance=MAX_FLOOR*2 elif floor <=elevator.destination: distance= elevator.current_floor - floor else: if task_flag ==-1: distance = elevator.current_floor - floor else: # distance = elevator.current_floor - elevator.destination + floor - elevator.destination distance=MAX_FLOOR*2 else: ##elevator已关闭 print u'%s already stop'%(elevator) distance=MAX_FLOOR*2 return distance def add_globaltask_to_localtask(self,): ##任务分配算法 flagdict={'exigency_up':1,'up':1,'exigency_down':-1,'down':-1} print u'analyze the best blue print!' ##deepcopy一个globaltask的副本,集合和字典在遍历的时候不能被修改 tempdict=deepcopy(GlobalTask.task) for key,value in tempdict.items(): task_flag=flagdict.get(key) for floor in value: distancelist=[] for elevator in self.elevators: distance=self.analyze_distance(elevator=elevator,task_flag=task_flag,floor=floor) distancelist.append(distance) print u'GlobalTask.task["%s"]=%s distancelist is %s'%(key,floor,distancelist) min_distance=min(distancelist) if min_distance==MAX_FLOOR*2: ##所有电梯的运行进度与任务都不一致 isaccept=False else: index=distancelist.index(min_distance) elevator=self.elevators[index] isaccept=elevator.add_localtask(floor=floor,refer='globaltask') ##调度还会出现一个问题,提交了相同任务多次,可能会导致同一个任务会被分配到多个电梯中,这是无法避免的,也无需优化 if isaccept: ##有电梯接受了globaltask中的楼层申请 print u'%s accept globaltask flag=%s,floor=%s'%(elevator,key,floor) else: ##所有的电梯运行状态都与globaltask中的任务冲突,即任务没有被接受,暂留任务于globaltask print u'no elevator accept globaltask flag=%s,floor=%s,this task is invalid'%(key,floor) self.GlobalTask.task[key].remove(floor) print u'remove %s from GlobalTask.task["%s"]'%(floor,key) def add_localtask_by_elevator_index(self,index,floor): ##向电梯添加本地任务 if index < len(self.elevators): self.elevators[index].add_localtask(floor=floor,refer='localtask') else: print 'elevator:%s dont exists'%(index+1) def stop_elevator_by_index(self,index,): ##用于关闭电梯 elevator=self.elevators[index] elevator.stop() print u'close elevator:%s,set isalive to False'%(elevator.name) def add_globaltask_with_flag(self,floor,flag): ##添加全局任务 if flag == 1: self.GlobalTask.add_up(floor=floor) elif flag == -1: self.GlobalTask.add_down(floor=floor) def add_elevator(self,): ##增加电梯 elevator=FactoryElevator.add_elevator() self.elevators.append(elevator) return elevator def get_elevators_count(self,): ##查看电梯数目 return FactoryElevator.count return len(self.elevators) def restart_elevator(self,name=None): ##重启关闭的电梯 print u'try restart all stop elevator' for elevator in self.elevators: ##已启动的电梯不受影响 if name is None: if elevator.isalive is False: elevator.restart() else: if elevator.name == name: elevator.restart() def show_all_elevators_status(self,): print u'--------------------------------' print u'--------------------------------' print u'current elevators count is : %s'%(FactoryElevator.count) for elevator in self.elevators: if elevator.isalive: if elevator.flag == 0: print u'%s is empty,task is: %s'%(elevator,elevator.localtask) print else: print u'%s is runing,task is: %s'%(elevator,elevator.localtask) print else: print u'%s already broken, task is: %s'%(elevator,elevator.localtask) print for key,value in GlobalTask.task.items(): print u'GlobalTask.task["%s"] is %s'%(key,value) print u'--------------------------------' print u'--------------------------------' def test(): elevators=[FactoryElevator.add_elevator() for i in range(5)] print FactoryElevator.count if __name__ =='__main__': test()
edc34c5e917642ceefe9bb067e889e9b79eb0b84
ChrisWilko/Advent-Of-Code-2018
/Day2/Day2AdventOfCode.py
761
3.5625
4
from collections import Counter def first(): two = 0 three = 0 with open('input.txt', 'r') as file: for line in file: freq = Counter(line) if 2 in freq.values(): two += 1 if 3 in freq.values(): three += 1 return two*three def second(): with open('input.txt', 'r') as file: lines = [line.rstrip() for line in file] for i, one in enumerate(lines): for two in lines[i+1:]: same = [] for l1, l2 in zip(one, two): if l1 == l2: same.append(l1) if len(two)-len(same) == 1: return ''.join(same) print(first()) print(second())
9296d476077356af5188ab886cc15a3f1f47239e
shahad-mahmud/learning_python
/day_1/data_types.py
488
4.03125
4
# type() -> returns data type # string -> any type of text # integer -> any type of whole number # float, double -> partial number # boolean -> Ture or False name = 'Saba' # string print(type(name)) age = 10 # integer print(type(age)) income = 10000.5 # float print(type(income)) isStudent = True # boolean print(type(isStudent)) # write a progarm to explore deta type # a. write four variables and assign values of four data types # b. print the data types of the variables
6abdf758dc5157ff5752089400052b77f97d563e
danny-hunt/Advent-of-Code-2019
/day6.py
531
3.578125
4
with open('day6.txt', 'r') as text_input: orbitlist = text_input.read().split() orbitlist = [orbit.split(')') for orbit in orbitlist] orbit_dict = dict() for orbit in orbitlist: orbit_dict.update({orbit[1] : orbit[0]}) def count_orbits(object): value = 0 if object in orbit_dict: value += count_orbits(orbit_dict[object]) return value + 1 else: return value total_orbits = 0 for key in orbit_dict: total_orbits += count_orbits(key) print(total_orbits) # Answer is 151345
0be472a33e55c6f9d5aa614bcbb7953264187314
CollegeBoreal/INF1039-202-19A-01
/4.Variables/300118196.py
235
4
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 25 15:08:28 2019 """ # déclaration of variable x = 1 print(x*2) x = 4 print(2*x) if(x==4): print('x = 4') else: print('on ne sait pas') # string a = 'x = 4' print ( a )
a3a1b1797558c68a7d46eee8f1132f53d1d04b98
Ameya-k1709/Object-Oriented-Programming-in-Python
/class.py
1,410
4.4375
4
# creating a class named programmers class Employee: company = 'Microsoft' # the company attribute is a class attirbute because every programmers is from microsoft number_of_employees = 0 def __init__(self, name, age, salary, job_role): # This is a constructor self.name = name # These are instance attributes as "self" is given. This will refer to the object. self.age = age self.salary = salary self.job_role = job_role Employee.number_of_employees += 1 def giveProgrammerInfo(self): print(f'\nThe name of the programmer is {self.name}') print(f'The age of the programmer is {self.age}') print(f'The salary of the programmer is {self.salary}') print(f'The job role of the programmer is {self.job_role}') print(f'The company of the programmer is {self.company} ') # Here objects are created using the Employee class ameya = Employee('Ameya', 22, 200000, 'Manager - Data Scientist') akshay = Employee('Akshay', 32, 100000, 'Senior Business Analyst') prathamesh = Employee('Prathamesh', 25, 50000, 'Solution Architect') nilesh = Employee('Nilesh', 30, 10000, 'Database Architect') # here the class method is called by the objects ameya.giveProgrammerInfo() akshay.giveProgrammerInfo() prathamesh.giveProgrammerInfo() print(Employee.number_of_employees)
e8c20e33cfcd17128f4c4ddba59212c7c643020b
bitVil/6.0001
/pset1/ps1c.py
1,608
3.921875
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 20 19:03:52 2019 @author: David Fox Input: A positive real number. Output: the savings rate needed to afford a down payment, given values of parameters. Description: Uses bisection search on range 0 to 10000 (dividing by 10000 to get decimal in computation) checks if current savings is within 100 of down payment, updates search value based on this comparison. """ annual_salary_og = float(input('Enter your annual salary: ')) ## Parameters total_cost = 1000000 semi_annual_raise = 0.07 portion_down_payment = 0.25 r = 0.04 month_cap = 36 steps = 0 hi = 10000 lo = 0 while(lo < hi): annual_salary = annual_salary_og current_savings = 0 months_spent_saving = 0 mid = (lo + hi)//2 ## Compute months_spent_saving and current_savings for current values. while(current_savings < total_cost * portion_down_payment and months_spent_saving < month_cap): current_savings += (annual_salary/12) * (mid/10000) + current_savings * (r/12) months_spent_saving += 1 if (months_spent_saving % 6 == 0): annual_salary += annual_salary * semi_annual_raise ## Update hi or lo. if (abs(current_savings - total_cost * portion_down_payment) < 100): break elif (total_cost * portion_down_payment < current_savings): hi = mid else: lo = mid + 1 steps += 1 if (lo >= hi): print("It is not possible to pay the down payment in three years.") else: print("Best savings rate: ", mid/10000) print("Steps in bisection search: ", steps)
51c1b226905bae98787735f088e2d3ff9cee430e
deborasoliveira/crud-bsi-1
/professorar.py
6,095
3.640625
4
professor = [] #PARA SALVAR CADASTRO, ATUALIZAÇÃO E REMOÇÃO def salvar_cadastrop(): global professor arq = open('professor.txt', 'w', encoding = "utf-8") for i in professor: nome_professor = str(i[0]) cpf_professor = str(i[1]) dpt_professor = str(i[2]) arq.write('%s %s %s\n' %(nome_professor, cpf_professor, dpt_professor)) arq.close() #CADASTRO def cadastro_prof(): while True: try: op = int(input("Para cadastrar professor digite 1, para retornar ao menu principal digite 2: ")) if op == 1: nome_professor = input("Digite seu nome para cadastro aqui: ") #ADICIONAR DADOS DO PROFESSOR cpf_professor = input("Digite seu cpf para cadastro aqui: ") dpt_professor = input("Digite seu departamento para cadastro aqui: ") for i in range(len(professor)): if cpf_professor in professor[i][1]: #CASO ELE SEU CPF JÁ ESTEJA NA LISTA, SIGNIFICA QUE JÁ ESTÁ CADASTRADO print("Professor já cadastrado. ") else: professor.append([nome_professor, cpf_professor, dpt_professor]) #CASO CONTRÁRIO, ELE SERÁ ADICIONADO À LISTA DE PROFESSORES print("Cadastro realizado com sucesso: {}, {}, {}".format(nome_professor, cpf_professor, dpt_professor)) salvar_cadastrop() #FUNÇÃO PARA SALVAR CADASTRO break elif op == 2: #CASO ELE ESCOLHA A OPÇÃO 2, O PROGRAMA SERÁ FINALIZADO break else: print("Opção inválida.") #CASO ELE ESCOLHA QUALQUER OUTRA OPÇÃO, SERÁ CONSIDERADA INVÁLIDA except EOFError: break #REMOVER CADASTRO def remover_cadastro(): while True: try: op = int(input("Para remover o cadastro digite 1, para retornar ao menu principal digite 2: ")) if op == 1: del_professor = input("Para a remoção de cadastro, digite seu cpf aqui: ") #PARA EXERCUTAR A REMOÇÃO É PRECISO INFORMAR O CPF for i in range(len(professor)): if del_professor in professor[i][1]: #CASO O ALUNO ESTEJA CADASTRADO, A REMOÇÃO É EFETUADA professor.remove(professor[i]) print("Professor removido com sucesso.") salvar_cadastrop() else: print("Cadastro não encontrado.") #CASO CONTRÁRIO, SERÁ INFORMADO DE QUE ESTE CPF NÃO ESTÁ CADASTRADO break elif op == 2: #CASO ELE ESCOLHA A OPÇÃO 2, O PROGRAMA DEIXARÁ DE RODAR break else: print("Operação inválida.") #CASO ELE ESCOLHA OUTRA OPÇÃO, ELA SERÁ CONSIDERADA INVÁLIDA except EOFError: break #CONSULTAR CADASTRO def consultar_cadastro(): while True: try: op = int(input("Para consultar cadastro digite 1, para retornar ao menu principal digite 2: ")) if op == 1: consulta_prof = input("Para consulta, digite seu cpf aqui: ") #PARA A CONSULTA É NECESSÁRIO A VERIFICAÇÃO DO CPF for i in range(len(professor)): if professor[i][1] == consulta_prof: #SE O CPF ESTIVER NA LISTA, O CADASTRO SERÁ CONSULTADO NORMALMENTE print("NOME: {}\nCPF: {}\nDEPARTAMENTO: {}".format(professor[i][0], professor[i][1], professor[i][2])) else: print("Cadastro não encontrado.") #CASO CONTRÁRIO, SRÁ INFORMADO DE QUE NÃO HÁ CADASTRO COM ESTE CPF elif op == 2: break #FINALIZAR PROGRAMA else: print("Operação inválida.") #CASO A OPÇÃO DELE SEJA DIFERENTE DAS APRESENTADAS, ELA SERÁ CONSIDERADA INVÁLIDA except EOFError: break #ATUALIZAR CADASTRO def atualizar_prof(): while True: try: op = int(input("Para atualizar cadastro digite 1, para retornar ao menu principal digite 2: ")) if op == 1: alt_professor = input("Digite seu CPF para ter acesso à atualização: ") for i in range(len(professor)): if alt_professor in professor[i][1]: opc = int(input("Para atualizar o nome digite 1, para atualizar o cpf digite 2, e 3 para departamento: ")) if opc == 1: nome = input("Digite seu nome aqui: ") professor[i][0] = nome print("NOME: {}\nPROFESSOR: {}\nDEPARTAMENTO: {}".format(professor[i][0], professor[i][1], professor[i][2])) # ENFEITAR + ESSA PARTE!!!!!!!!!!!!!!!!!!!!!!!!!!!! print("Cadastro alterado com sucesso.") salvar_cadastrop() elif opc == 2: cpf = input("Digite seu cpf: ") professor[i][1] = cpf print("NOME: {}\n CPF: {}\n DEPARTAMENTO: {}".format(professor[i][0], professor[i][1], professor[i][2])) # ENFEITAR ESSA PARTE!!!!!!!!!!!!!!!!!!!!!!! print("Cadastro alterado com sucesso.") salvar_cadastrop() elif opc == 3: dpt = input("Digite seu departamento aqui: ") professor[i][2] = dpt print("NOME: {}\nCPF: {}\n DEPARTAMENTO: {}".format(professor[i][0], professor[i][1], professor[i][2])) print("Cadastro alterado com sucesso") salvar_cadastrop() break else: print("Cadastro não encontrado.") elif op == 2: break else: print("Operação inválida.") except EOFError: break
bdcbf20d1ed0ff304d502279dc3f69133998e0f8
AnonymousWudi/leetcode
/303. Range Sum Query - Immutable.py
822
3.546875
4
# coding=utf-8 """ question url: https://leetcode.com/problems/range-sum-query-immutable/ """ class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.nums = nums if nums: self.value_list = [nums[0]] for i in nums[1:]: self.value_list.append(i+self.value_list[-1]) def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ return self.value_list[j] - self.value_list[i] + self.nums[i] # Your NumArray object will be instantiated and called as such: # numArray = NumArray(nums) # numArray.sumRange(0, 1) # numArray.sumRange(1, 2)
1dcf626c29e39cdd32a98ec3e33be11ed6fa0cff
capric8416/leetcode
/algorithms/python3/number_of_music_playlists.py
1,205
3.84375
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip.  You create a playlist so that: Every song is played at least once A song can only be played again only if K other songs have been played Return the number of possible playlists.  As the answer can be very large, return it modulo 10^9 + 7.   Example 1: Input: N = 3, L = 3, K = 1 Output: 6 Explanation: There are 6 possible playlists. [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]. Example 2: Input: N = 2, L = 3, K = 0 Output: 6 Explanation: There are 6 possible playlists. [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], [1, 2, 2] Example 3: Input: N = 2, L = 3, K = 1 Output: 2 Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2]   Note: 0 <= K < N <= L <= 100 """ """ ==================== body ==================== """ class Solution: def numMusicPlaylists(self, N, L, K): """ :type N: int :type L: int :type K: int :rtype: int """ """ ==================== body ==================== """
20b659498d4b4b1af784227508d7c5d0e0cc3eb4
jingruhou/practicalAI
/Basics/BeginnerPython/4-8_list实现队列和栈.py
1,822
4.46875
4
# list实现队列 queue = [] # 定义一个空list,当作队列 queue.insert(0, 1) # 向队列里放入一个整型元素 1 queue.insert(0, 2) # 向队列里放入一个整形元素 2 queue.insert(0, "hello") # 向队列里面放入一个字符型元素 hello print("取第一个元素:", queue.pop()) # 从队列里面取一个元素,根据先进先出原则,输出 1 print("取第二个元素: ", queue.pop()) # 从队列里面取一个元素,根据先进先出原则,输出 2 print("取第三个元素: ", queue.pop()) # 从队列里面取一个元素,根据先进先出原则,输出 hello # list 实现栈 stack = [] # 定义一个空list,当作栈 stack.append(1) # 向栈里面放入一个元素 1 stack.append(2) # 向栈里面放入一个元素 2 stack.append("hello") # 向栈里面放入一个元素 hello print("取第一个元素", stack.pop()) # 从栈里面取一个元素,然后根据后进先出原则,输出 hello print("取第二个元素", stack.pop()) # 从栈里面取一个元素,然后根据后进先出原则,输出 2 print("取第三个元素", stack.pop()) # 从栈里面取一个元素,然后根据后进先出原则,输出 1 from collections import deque queueandstack = deque() # 创建一个空结构体,既可以当队列又可以当栈 queueandstack.append(1) # 向空结构体里放入一个整形元素 1 queueandstack.append(2) # 向空结构体里放入一个整形元素 2 queueandstack.append("hello") # 向空结构体放入一个字符型元素 hello print(list(queueandstack)) print(queueandstack.popleft()) # 从队列里面取一个元素,根据先进先出原则,输出 1 print(queueandstack.pop()) # 从栈里面取一个元素,根据后进先出原则,输出 hello print("Now queue is", list(queueandstack))
a06f7cb9f7e2d5ff4eb63fc835ee6aeb92fa6308
jhb86253817/coursera-nlp
/week3/assignment/part1.py
1,874
3.78125
4
#! /usr/bin/python __author__ = "Haibo Jin" import json #part1, exercise of week3, from coursera NLP course lectured by Michael Collins #a program which can replace the infrequent words(count < 5) by symbol _RARE_, in the parse_train.dat def replace_infreq(filename): """replace the infrequent words(count < 5) by symbol _RARE_, given the target file, based on 'cfg.counts'.""" #getting counts from cfg.counts file_in = open('cfg.counts', 'rb') file_out = open('parse_train2.dat', 'wb') #recording rare words rare = set() #for a specific word, summing the counts of all different kinds of POS rare_sum = {} for line in file_in: line = line.split() if line[1] == 'UNARYRULE': if line[3] in rare_sum: rare_sum[line[3]] += int(line[0]) else: rare_sum[line[3]] = int(line[0]) #choosing those words with less than 5 counts for key in rare_sum.keys(): if rare_sum[key] < 5: rare.add(key) file_in.close() #replace the rare words in target file file_in = open(filename, 'rb') for tree in file_in: tree = json.loads(tree) tree_new = tree_replace(tree, rare) tree_new = json.dumps(tree_new) file_out.write(tree_new + '\n') def tree_replace(tree, rare): """based on given rare words, replace the infrequent words in the given tree.""" #recursively replace infrequent words if isinstance(tree, list) and len(tree) == 3: new_1 = tree_replace(tree[1], rare) new_2 = tree_replace(tree[2], rare) return [tree[0], new_1, new_2] elif isinstance(tree, list) and len(tree) == 2: new = tree_replace(tree[1], rare) return [tree[0], new] else: if tree in rare: return '_RARE_' else: return tree if __name__ == '__main__': replace_infreq('parse_train.dat')
77b1d9ebe3843980a2df2bf8645261bc1f06c9c8
manuck/myAlgo
/프로그래머스/쇠막대기.py
365
3.53125
4
import sys sys.stdin = open('쇠막대기_input.txt') arrangement = input() answer = 0 arrangement = arrangement.replace("()", "ㅣ") # print(arrangement) stack = [] for c in arrangement: # print(stack) if c == '(': stack.append('(') answer += 1 elif c == ')': stack.pop() else: answer += len(stack) print(answer)
e68d1512bbe4eede186478ee776624d6cd67d272
R-ISWARYA/python
/prime number16.py
179
3.71875
4
lower=900 upper=1000 print("prime number between ",lower,"and"upper,"are:") for num in rang(lower,upper+1): if num>1: for i in range (2,num): if(num%i)==0: break else: print(num)
dbebae2ef32fa258fe929a3792b36748cce4e953
ssar0014/PrimeFactors-of-VeryLarge-Numbers
/primefac.py
517
4
4
from math import sqrt from itertools import count, islice def isPrime(n): if n<2: return False if n==2: return True for i in islice(count(2), int(sqrt(n)-1)): if not n%i: return False return True fact_list = [] def isFact(n): for i in islice(count(1),n): if not n%i: fact_list.append(i) num = int(input('Enter a number: ')) isFact(num) prime_fact_list= list(filter(isPrime,fact_list)) print('The prime factors of ',num,'are: ',prime_fact_list)
498ef6ecb81b27197762bc4f5d8d301174d56735
danielleberre/satsmt19handson
/sittingresearchers.py
861
3.5
4
#!/usr/bin/python3 import sys def var(i,j,m): """ parameters: i: researcher id between 1 and m j: seat id between 1 and m-1 m: total number of researchers """ return (i-1)*(m-1)+j def at_least_one(i,m): literals=[] for j in range(1,m): literals.append(var(i,j,m)) literals.append(0) print(' '.join(map(str,literals))) def at_most_one(j,m): for i in range(1,m+1): for k in range(i+1,m+1): print("-%d -%d 0" % (var(i,j,m),var(k,j,m))) if (len(sys.argv)!=2): m = 4 else: m = int(sys.argv[1]) print ("c beginMapping") for i in range(1,m+1): for j in range(1,m): print ("c %d=R%dS%d" %(var(i,j,m),i,j)) print ("c endMapping") print ("p cnf %d %d" % (m*m-m,m+(m-1)*m*(m-1)/2)) for i in range(1,m+1): at_least_one(i,m) for j in range(1,m): at_most_one(j,m)
3b72ba09916cafcf3efe79df11bb1ae865311d6d
tony36486/Machine-Learning
/Ex3/ex_multi_list.py
431
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 17 19:30:47 2017 python 3.6ver @author: tony this code is a exercise of ML class exercise:multi_dim list """ #multi_dim list multi_dim = [[1,2,3],[4,5,6],[7,8,9]] for index_a in range(len(multi_dim)): for index_b in range(len(multi_dim[index_a])): print('index_a:', index_a, ', index_b:', index_b, ', text:',multi_dim[index_a][index_b]) print(max(multi_dim[2]))
fcf31090003944cfa243610aa08a4865898638a4
MalarSankar/learning
/class_assignment1.py
680
3.890625
4
class Time: def __init__(self,hours,mins): self.hours=hours self.mins=mins def display_total_min(self): print(self.hours*60+self.mins,"mins") def add(t1,t2): tot_add=t1.hours*60+t1.mins+t2.hours*60+t2.mins tot_hour=int(tot_add/60) tot_min=tot_add%60 print("the adition of times is",tot_hour,"hours and",tot_min,"mins") def sub(t1,t2): tot_sub=abs((t1.hours*60+t1.mins)-(t2.hours*60+t2.mins)) tot_hour = int(tot_sub / 60) tot_min = tot_sub % 60 print("the subraction of times is", tot_hour, "hours and", tot_min, "mins") t1=Time(5,7) t2=Time(4,7) t1.display_total_min() add(t1,t2)
dc058007500c0ab57966f2ea43a9e7e554130266
Hindol1234/1
/1.py
289
4.1875
4
marks=int(input("Enter the marks:")) grade='' if marks>75: grade='o' elif marks>60 and marks<=75: grade='A' elif marks>50 and marks<=60: grade='B' elif marks>40 and marks<=50: grade='C' else: grade='D' print("GRADE=",grade) input("Please input for exit:")
f593954619f9fc234dd2b1d6fdc64cf21958a787
laoniu85/udacity_nd000
/stage2.py
3,680
3.96875
4
import random from quiz_lib import * welcom_message="""\ It's a quize about oppsite word. got 5 point first. if your answer is wrong you ponit will +1(if combo will +2) if your point is below 0 you will fail. if the answer is pharse you should connect the word with ' ' eg. "to free" """ level_choose_message="""Input the level to want play. (1) easy -> you need achieve 10 point(you got answer). (2) middle -> you need achieve 20 point.(wrong will -2 point) (3) hard -> you need to achieve 30 point.(wrong will -3 point) """ level_choose_error_message="level choose error!" quiz_word_replacer = "_QUIZ_WORD_" quiz_message="""\ Please give an oppsite word of "_QUIZ_WORD_" """ point_replacer = "_POINT_" combo_replacer = "_COMBO_" quiz_count_repalcer="_QUIZ_COUNT_" quiz_point_info="Point: _POINT_ Combo: _COMBO_ Quiz Count: _QUIZ_COUNT_" quiz_right_message="""\ Your anwer is right! """ quiz_wrong_message="""\ Your anwer is wrong! """ right_answer_replacer="_RIGHT_ANSWER_" show_answer_message="""\ Right anser is _RIGHT_ANSWER_. """ win_message="""You win the game! """ loose_message="""You loose the game! """ achieve_easy=10 minus_easy=1 achieve_middle=20 minus_middle=2 achieve_hard=30 minus_hard=3 point_start=5 plus = 1 combo_plus = 2 minus = -1 achieve = 10 show_answer=True passed_quiz=[] def is_right_answer(answer,quiz): answers=quiz[1].split(",") return answer in answers def random_choose_quiz(): while(True): quiz = quiz_lib[random.randint(0,len(quiz_lib)-1)] if quiz not in passed_quiz: return quiz def choose_level(): level = raw_input("please select the level(1/2/3)\n") while True: print level_choose_message if level == '1': show_answer=True achieve=achieve_easy minus=minus_easy break if level == '2': achieve = achieve_middle minus = achieve_hard show_answer=False break if level == '3': achieve = achieve_hard minus = minus_hard show_answer=False break print level_choose_error_message def print_status(point,combo_count,quiz_count): print quiz_point_info.replace(point_replacer,str(point))\ .replace(combo_replacer,str(combo_count))\ .replace(quiz_count_repalcer,str(quiz_count)) def print_result(point,achieve): if(point>=achieve): print win_message else: print loose_message def check_quiz(quiz): answer = raw_input(quiz_message.replace(quiz_word_replacer,quiz[0])) return is_right_answer(answer,quiz) def play_quiz(): print welcom_message point = point_start passed_quiz=[] quiz_count = 0 combo_count=1 choose_level() while(point >= 0 and point < achieve): quiz = random_choose_quiz() if(check_quiz(quiz)): point+=combo_plus if (combo_count>1) else plus combo_count+=1 print quiz_right_message else: combo_count=1 point+=minus print quiz_wrong_message if show_answer: print show_answer_message.replace(right_answer_replacer,quiz[1]) quiz_count+=1 print_status(point,combo_count,quiz_count) print_result(point,achieve) def test_quiz(): assert is_right_answer("rear",['front','rear']) assert is_right_answer("to allow",['to forbid','to allow,to let,to permit']) assert not is_right_answer("to bellow",['to forbid','to allow,to let,to permit']) #assert is_right_answer("to bellow",['to forbid','to allow,to let,to permit']) #test_quiz() play_quiz()
6ad3db3cf885e8f1c8bbada742e88600db3d9298
ludamad/7DayRL2013
/source/geometry.py
3,773
3.84375
4
import math # Lots of ugly operator overloading, but it makes the rest of the code prettier. class Pos: def __init__(self, x, y): self.x = x self.y = y def distance(self, pos): dx, dy = pos.x - self.x, pos.y - self.y return math.sqrt(dx*dx+dy*dy) def sqr_distance(self, pos): dx, dy = pos.x - self.x, pos.y - self.y return max(abs(dx), abs(dy)) def __add__(self, pos): return Pos(self.x+pos.x, self.y+pos.y) def __sub__(self, pos): return Pos(self.x-pos.x, self.y-pos.y) def __mul__(self, pos): return Pos(self.x*pos.x, self.y*pos.y) def __div__(self, pos): return Pos(float(self.x)/pos.x, float(self.y)/pos.y) def __eq__(self, pos): if type(self) != type(pos): return False return self.x == pos.x and self.y == pos.y def __ne__(self, pos): return not (self == pos) def __str__(self): return "Pos(" + str(self.x) + ", " + str(self.y) + ")" class Size: def __init__(self, w, h): self.w = w self.h = h def __add__(self, size): return Size(self.w+size.w, self.h+size.h) def __sub__(self, size): return Size(self.w-size.w, self.h-size.h) def __mul__(self, size): return Size(self.w*size.w, self.h*size.h) def __div__(self, size): return Size(float(self.w)/size.w, float(self.h)/size.h) def __eq__(self, size): if type(self) != type(size): return False return self.w == size.w and self.h == size.h def __ne__(self, size): return not (self == size) def __str__(self): return "Size(" + str(self.w) + ", " + str(self.h) + ")" class Rect: def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h # Iterates the range of x to x + width def x_values(self): return range(self.x, self.x + self.w) # Iterates the range of y to y + height def y_values(self): return range(self.y, self.y + self.h) # Iterates all the values of the rectangle def xy_values(self): return ( Pos(x,y) for y in self.y_values() for x in self.x_values() ) def edge_values(self): for x in self.x_values(): yield Pos(x, self.y) yield Pos(x, self.y + self.h - 1) for y in range(self.y+1, self.y-1 + self.h): yield Pos(self.x, y) yield Pos(self.x + self.w - 1, y) def top_left(self): return Pos(self.x,self.y) def bottom_right(self): return Pos(self.x+self.w-1, self.y+self.h-1) def padding(self, pad): return Rect(self.x - pad, self.y - pad, self.w + pad * 2, self.h + pad * 2) def center(self): center_x = self.x + int(self.x2 / 2) center_y = self.y + int(self.y2 / 2) return Pos(center_x, center_y) def __add__(self, pos): return Rect( self.x + pos.x, self.y + pos.y, self.w, self.h) def within(self, xy): return xy.x >= self.x and xy.x < self.x + self.w and xy.y >= self.y and xy.y < self.y + self.h # Returns true if this rectangle intersects with another one def intersects(self, other): return (self.x < other.x+other.w and self.x+self.w > other.x and self.y < other.y+other.h and self.y+self.h > other.y) def __eq__(self, rect): if type(self) != type(rect): return False return self.x == rect.x and self.y == rect.y and self.w == rect.w and self.h == rect.h def __ne__(self, rect): return not (self == rect) def __str__(self): return "Rect( x=" + str(self.x) + ", y=" + str(self.y) + ", w=" + str(self.w) + ", h=" + str(self.h) + ")" def make_rect(pos, size): return Rect(pos.x, pos.y, size.w, size.h)
d1c30d87f1a0906d36e3ba870360eb427471a44c
enginaryum/python-functional-programming
/code_samples.py
1,916
3.796875
4
# from __future__ import print_function class1 = [20, 10, 90, 10, 80, 70] class2 = [50, 40, 90, 30, 80, 70] class3 = [70, 90, 90, 80, 80, 70] all_exam_results = [class1, class2, class3] all_exam_results_dict = { 'class1': [20, 10, 90, 10, 80, 70], 'class2': [50, 40, 90, 30, 80, 70], 'class3': [70, 90, 90, 80, 80, 70], } # 1. Calculate Mean - function definition - def calculate_mean(list): total = 0 for number in list: total += number return total / len(list) calculate_mean(class1) calculate_mean(class2) calculate_mean(class3) results = [] for _class in all_exam_results: results.append(calculate_mean(_class)) print(results) # 2. Calculate Mean for each classes - map function - print map(calculate_mean, all_exam_results) # 3. Calculate mean - lambda function - print map(lambda x: calculate_mean(x), all_exam_results) # 4. Calculate mean - reduce function - def calculate_mean(_list): return reduce(lambda x, y: x + y, _list) / len(_list) # 5. Calculate Mean - lambda function - calculate_mean = lambda list: reduce(lambda x,y: x+y, list) / len(list) print calculate_mean(class1) # 6. Calculate mean for each classes - list format - print map(calculate_mean, all_exam_results) # 7. Calculate mean for each classes - dict format - print map(lambda (k,v) : {k: calculate_mean(v)}, all_exam_results_dict.iteritems()) # 8. Calculate mean for each class in dict and return new dict with mean and notes print map(lambda (k, v) : {k: {'mean': calculate_mean(v), 'notes': v}}, all_exam_results_dict.iteritems()) print all_exam_results_dict # 9 - Calculate mean for each classes in dict and return same dict with new keys map(lambda (k, v) : all_exam_results_dict.update({k : {'mean': calculate_mean(v), 'notes': v}}), all_exam_results_dict.iteritems()) # print all_exam_results_dict
6d3da136a39ca1be35bea639f01682531094241f
rmarren1/code_problem_snippets
/bit_twiddling/pow.py
304
3.90625
4
def pow(x, y): "Given a double x and an integer y, compute x**y" s = 1 while y: if y & 1: s *= x x *= x y >>= 1 return s assert pow(2, 4) == 2**4 assert pow(1, 0) == 1**0 assert pow(4, 8) == 4**8 assert pow(1, 10) == 1**10 assert pow(10, 1) == 10**1
e8ccd79b9f1d0dd560865fce1cc285b1d78dcc41
devferx/platzi-curso-python-basico
/05-operadores-logicos.py
406
4.03125
4
es_estudiante = True print("es estudiante", es_estudiante) trabaja = False print("trabaja", trabaja) print(es_estudiante and trabaja) print(es_estudiante or trabaja) print("es estudiante:", not es_estudiante) numero1 = 5 numero2 = 5 numero3 = 10 print(numero1 == numero2) print(numero1 != numero2) print(numero3 > numero1) print(numero3 < numero1) print(numero3 >= numero1) print(numero3 <= numero1)
602a94f6cbca9808b8dbf1614ff2a001b8efaeee
balajiramesh138/ML-project
/problem_statement_3.py
1,787
3.59375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns dataset=pd.read_csv("used cars and bikes.csv") #print(dataset.columns) sns.heatmap(dataset.isnull()) #plt.show() plt.scatter(dataset['owner'],dataset['selling_price']) plt.xlabel('owner') plt.ylabel('selling_price') #plt.show() #visualising numerical variables plt.figure(figsize=(15, 15)) sns.pairplot(dataset) #plt.show() #visualising categorical variables plt.figure(figsize=(10, 20)) plt.subplot(4,2,1) sns.boxplot(x = 'vehicle_type', y = 'selling_price', data = dataset) plt.subplot(4,2,2) sns.boxplot(x = 'fuel', y = 'selling_price', data = dataset) plt.subplot(4,2,3) sns.boxplot(x = 'owner', y = 'selling_price', data = dataset) plt.tight_layout() plt.show() #creating dummy variables vehicle=pd.get_dummies(dataset['vehicle_type'],drop_first=True) #print(vehicle) Fuel=pd.get_dummies(dataset['fuel'],drop_first=True) #print(Fuel) Owner=pd.get_dummies(dataset['owner'],drop_first=True) #print(Owner) dataset.drop(['vehicle_type','name','fuel','owner'],axis=1,inplace=True) dataset=pd.concat([dataset,vehicle,Fuel,Owner],axis=1) #print(dataset) from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(dataset.drop('selling_price',axis=1),dataset['selling_price'],test_size=0.20,random_state=50) from sklearn.linear_model import LinearRegression linreg=LinearRegression() linreg.fit(x_train,y_train) y_pred=linreg.predict(x_test) #print(y_pred) y_pred1=linreg.predict([[2014,28000,1,0,0]]) #print(y_pred1) from sklearn.metrics import mean_squared_error #print(mean_squared_error(y_test,y_pred)) #print(linreg.score(x_test, y_test)*100,'% Prediction Accuracy')
e644554fed5aef54f0e8685e8313572c36208f91
chelvanai/pytorch-regression-classification
/regres2.py
1,300
3.640625
4
import numpy as np from torch import nn import torch from sklearn.model_selection import train_test_split import pandas as pd df = pd.read_csv('house-price-only-rooms-and-price.csv') x = df[['rooms']] y = df["price"] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) input_rows = x_train.shape[1] x_train = torch.from_numpy(x_train.values.astype(np.float32)) y_train = torch.from_numpy(y_train.values.astype(np.float32)) class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.linear = torch.nn.Linear(1, 1) # One in and one out def forward(self, x): y_pred = self.linear(x) return y_pred model = Model() print(model.linear.weight) criterion = torch.nn.MSELoss(reduction='sum') optimizer = torch.optim.SGD(model.parameters(), lr=0.01) for epoch in range(500): # 1) Forward pass: Compute predicted y by passing x to the model y_pred = model(x_train) # 2) Compute and print loss loss = criterion(y_pred, y_train.view(y_train.shape[0], 1)) print(f'Epoch: {epoch} | Loss: {loss.item()} ') # Zero gradients, perform a backward pass, and update the weights. optimizer.zero_grad() loss.backward() optimizer.step() print(x_train) print(y_train.view(y_train.shape[0], 1))
74a0529f5744252e36a11889392dd3882fadd7f6
AdGw/PracticalTasks
/Python/Money, Money, Money.py
944
3.9375
4
'''Mr. Scrooge has a sum of money 'P' that he wants to invest. Before he does, he wants to know how many years 'Y' this sum 'P' has to be kept in the bank in order for it to amount to a desired sum of money 'D'. The sum is kept for 'Y' years in the bank where interest 'I' is paid yearly. After paying taxes 'T' for the year the new sum is re-invested. Note to Tax: not the invested principal is taxed, but only the year's accrued interest Your task is to complete the method provided and return the number of years 'Y' as a whole in order for Mr. Scrooge to get the desired sum.''' P = 1000 I = 0.05 T = 0.18 D = 1100 def calculate_years(P, I, T, D): counter = 0 if D == P: return 0 while P <= D: after_year = P * (I + 1) tax = (after_year - P) * T sum_year = after_year - tax P = sum_year counter += 1 if P >= D: return counter calculate_years(P, I, T, D)
e43de700059c31e5db0c7a7f6e837c0556186b3b
ChiselD/pyglatin
/pyglatin.py
2,946
4.21875
4
# THINGS TO FIX # 1. multiple consonants at start of word - DONE! # 2. printing on separate lines - DONE! # 3. non-alphabetical strings # 3a. if user includes numbers, return error - DONE! # 3b. if user includes punctuation, move it to correct location # 4. omitted capitalization # separate variables for the two possible endings ay = 'ay' yay = 'yay' # create list to hold words of sentence in order sentence = [] # reference list that tracks all vowels vowels = ['a','e','i','o','u','y'] # function to run on words starting with vowels def vowel(word): vowel_word = word + yay sentence.append(vowel_word) # function to run on words starting with consonants def consonant(word, first): # this variable will hold all letters before first vowel first_chunk = '' # I don't think there are any words in English that start with 'y' + another consonant (?) if first == 'y': first_chunk = first elif word[0] == 'q' and word[1] == 'u': first_chunk = 'qu' else: for letter in word: # look at each letter in word to see if it is a vowel if letter not in vowels: # as long as it's not, add it onto the end of the 'first_chunk' variable first_chunk += letter else: # as soon as you reach the first vowel in the word, break the loop break # consonant_word = all letters from first vowel to end + all letters before that + ay consonant_word = word[len(first_chunk):len(word)] + first_chunk + ay sentence.append(consonant_word) # function to check if user input contains any digits def has_number(input): # returns True if the string contains a digit return any(char.isdigit() for char in input) # function to turn the user input into its Pig Latin equivalent def pig_latinize_string(input): # lowercase user-entered string for practical purposes text = input.lower() # split original text into array of separate words words = text.split() # check each word: is it vowel-category or consonant-category? for word in words: # make variable to hold first letter only first = word[0] # if first letter is vowel, run vowel function if first in vowels and first != 'y': vowel(word) # if first letter is consonant, run consonant function else: consonant(word, first) # print each word in final 'sentence' list for item in sentence: print item, # function that runs all the other functions (ALL HAIL MASTER FUNCTION) def main(): # reset sentence list to empty sentence = [] # prompt user for text to Pig-Latinize original = raw_input("Enter your text: ") # confirm that user-entered string is not empty if len(original) > 0: # if string contains numbers, refuse it and re-prompt if has_number(original): print "Please enter a string that contains only letters and punctuation." main() # otherwise, let's DO this thing else: pig_latinize_string(original) else: # if user-entered string is empty, throw error and re-prompt print "No input!" main() main()
763f0da71e14a1f0a7fd8305f3ea7cb36e46c52f
guilherme-witkosky/MI66-T5
/Lista 5/L5E03.py
237
3.953125
4
#Faça um programa, com uma função que necessite de três argumentos, e que forneça a soma desses três argumentos. #Exercicio 3 def exe3(num1, num2, num3): print("A soma do argumentos é:", (num1 + num2 + num3)) exe3(1, 2, 3)
14a18b2b0a03d9e52759ce48859d4ebc752b539a
zzandland/Algo-DS
/GrokkingDP/5/min_del_add.py
1,393
4.03125
4
# Problem Statement # # Given strings s1 and s2, we need to transform s1 into s2 by deleting and inserting characters. Write a function to calculate the count of the minimum number of deletion and insertion operations. # Example 1: # Input: s1 = "abc" # s2 = "fbc" # Output: 1 deletion and 1 insertion. # Explanation: We need to delete {'a'} and insert {'f'} to s1 to transform it into s2. # Example 2: # Input: s1 = "abdca" # s2 = "cbda" # Output: 2 deletions and 1 insertion. # Explanation: We need to delete {'a', 'c'} and insert {'c'} to s1 to transform it into s2. # Example 3: # Input: s1 = "passport" # s2 = "ppsspt" # Output: 3 deletions and 1 insertion # Explanation: We need to delete {'a', 'o', 'r'} and insert {'p'} to s1 to transform it into s2. from typing import Tuple def bu(s1: str, s2: str) -> Tuple[int, int]: """ >>> bu('abc', 'fbc') (1, 1) >>> bu('abdca', 'cbda') (2, 1) >>> bu('passport', 'ppsspt') (3, 1) """ A, B = len(s1), len(s2) if B > A: A, B = B, A dp = [[0 for _ in range(B+1)] for _ in range(2)] for i in range(A): for j in range(1, B+1): if s1[i] == s2[j-1]: dp[1][j] = dp[0][j-1] + 1 else: dp[1][j] = max(dp[0][j], dp[1][j-1]) dp[0] = dp[1] return (A-dp[1][-1], B-dp[1][-1]) if __name__ == '__main__': import doctest doctest.testmod()