blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a0c16d1e4eecc96e437924ee7335013261e18810
sumonbis/DS-Pipeline
/notebooks/featured-70/time-travel-eda.py
7,650
3.59375
4
#!/usr/bin/env python # coding: utf-8 # ## Exploration of the date features ## # In[1]: import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: train = pd.read_csv('../input/act_train.csv', parse_dates=['date']) test = pd.read_csv('../input/act_test.csv', parse_dates=['date']) ppl = pd.read_csv('../input/people.csv', parse_dates=['date']) df_train = pd.merge(train, ppl, on='people_id') df_test = pd.merge(test, ppl, on='people_id') del train, test, ppl # First just so we know what we're dealing with, let's take a look at the range of the two date variables # In[3]: for d in ['date_x', 'date_y']: print('Start of ' + d + ': ' + str(df_train[d].min().date())) print(' End of ' + d + ': ' + str(df_train[d].max().date())) print('Range of ' + d + ': ' + str(df_train[d].max() - df_train[d].min()) + '\n') # So we can see that all the dates are a few years in the future, all the way until 2023! Although we now though that [this is because the data was anonymised](https://www.kaggle.com/c/predicting-red-hat-business-value/forums/t/22642/data-question/130058#post130058), so we can essentially treat these as if they were the last few years instead. # # We can also see that date_x is on the order of 1 year, while date_y is 3 times longer, even though they both end on the same day (the date before they stopped collecting the dataset perhaps?) # # ---- # # We'll go on more into looking at how the two features relate to each other later, but first let's look at the structure of the features separately. # # ### Feature structure ### # # Here I'm grouping the activities by date, and then for each date working out the number of activities that happened on that day as well as the probability of class 1 on that day. # In[4]: date_x = pd.DataFrame() date_x['Class probability'] = df_train.groupby('date_x')['outcome'].mean() date_x['Frequency'] = df_train.groupby('date_x')['outcome'].size() date_x.plot(secondary_y='Frequency', figsize=(20, 10)) # This plot shows some very interesting findings. There appears to be a very apparent weekly pattern, where on weekends there are much less events, as well as the probability of a event being a '1' class being much lower. # # We can see that during the week the classes are pretty balanced at ~0.5 while on weekends they drop to 0.4-0.3 (this could be very useful information). # # We can also see some very big peaks in number of activities around the September-October time frame, which we will look into later in the EDA. But first, let's do the same with the other date feature, date_y! # In[5]: date_y = pd.DataFrame() date_y['Class probability'] = df_train.groupby('date_y')['outcome'].mean() date_y['Frequency'] = df_train.groupby('date_y')['outcome'].size() # We need to split it into multiple graphs since the time-scale is too long to show well on one graph i = int(len(date_y) / 3) date_y[:i].plot(secondary_y='Frequency', figsize=(20, 5), title='date_y Year 1') date_y[i:2*i].plot(secondary_y='Frequency', figsize=(20, 5), title='date_y Year 2') date_y[2*i:].plot(secondary_y='Frequency', figsize=(20, 5), title='date_y Year 3') # There also appears to be a weekly structure to the date_y variable, although it isn't as cleanly visible. However, the class probabilities appear to swing much lower (reaching 0.2 on a weekly basis) # # We have to take these class probabilities with a grain of salt however, since we are hitting very low numbers of samples in each day with the date_y (in the hundreds). # # ---- # # ### Test set ### # # However, all of this information is useless if the same pattern doesn't emerge in the test set - let's find out if this is the case! # # Since we don't know the true class values, we can't check if the same class probability appears in the test set, however we can check that the distribution of samples is the same. # In[6]: date_x_freq = pd.DataFrame() date_x_freq['Training set'] = df_train.groupby('date_x')['activity_id'].count() date_x_freq['Testing set'] = df_test.groupby('date_x')['activity_id'].count() date_x_freq.plot(secondary_y='Testing set', figsize=(20, 8), title='Comparison of date_x distribution between training/testing set') date_y_freq = pd.DataFrame() date_y_freq['Training set'] = df_train.groupby('date_y')['activity_id'].count() date_y_freq['Testing set'] = df_test.groupby('date_y')['activity_id'].count() date_y_freq[:i].plot(secondary_y='Testing set', figsize=(20, 8), title='Comparison of date_y distribution between training/testing set (first year)') date_y_freq[2*i:].plot(secondary_y='Testing set', figsize=(20, 8), title='Comparison of date_y distribution between training/testing set (last year)') # In[7]: print('Correlation of date_x distribution in training/testing sets: ' + str(np.corrcoef(date_x_freq.T)[0,1])) print('Correlation of date_y distribution in training/testing sets: ' + str(np.corrcoef(date_y_freq.fillna(0).T)[0,1])) # This gives us some interesting results. For date_x, we observe in the graph (and also in the high correlation value) that the training and testing sets have a very similar structure - this provides strong evidence that the training and testing sets are split based on people, and not based on time or some other unknown factor. Once again, we also observe the peaks (outliers?) in the September/October region. # # However, the date_y is less clear cut. There is a low correlation between the two sets, although there is definitely some relationship that we can see visually. There appears to be very many spikes in the test set in the first year (what could this mean?) That being said, in the last year of date_y the relationship between the two sets is much more apparent. Let's try looking at the correlations over the years. # In[8]: print('date_y correlation in year 1: ' + str(np.corrcoef(date_y_freq[:i].fillna(0).T)[0,1])) print('date_y correlation in year 2: ' + str(np.corrcoef(date_y_freq[i:2*i].fillna(0).T)[0,1])) print('date_y correlation in year 3: ' + str(np.corrcoef(date_y_freq[2*i:].fillna(0).T)[0,1])) # Wow, that is definitely a huge improvement over time! Something about the structure of the first year of date_y doesn't match up, so we should keep that in mind (If anyone has any theories I would love to hear them). # # ---- # ### Probability features ### # # To wrap up the first part of this EDA, I'm going to try turning the date class probabilities into features that we could use in our model, and then we can take a look at the AUCs that they give. # In[9]: from sklearn.metrics import roc_auc_score features = pd.DataFrame() features['date_x_prob'] = df_train.groupby('date_x')['outcome'].transform('mean') features['date_y_prob'] = df_train.groupby('date_y')['outcome'].transform('mean') features['date_x_count'] = df_train.groupby('date_x')['outcome'].transform('count') features['date_y_count'] = df_train.groupby('date_y')['outcome'].transform('count') _=[print(f.ljust(12) + ' AUC: ' + str(round(roc_auc_score(df_train['outcome'], features[f]), 6))) for f in features.columns] # It looks like the date probability features have very high predictive power! I think we might be onto something here. # # Anyway, that's all I've got for now. I'll be back with more graphs and text soon, in the meantime if anyone has any theories or questions feel free to ask/discuss in the comments. # # **Make sure to upvote if this was useful (and motivate me to make more!)**
383daeb888ab0748ebc5e9df45a983b998d1977f
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4138/codes/1637_2446.py
372
3.71875
4
s = int(input(" insira a senha: ")) a = s // 100000 b = s //10000 - (a * 10) c = s // 1000 - ((a * 100) + (b * 10)) d = s // 100 - ((a * 1000) + (b *100) + (c * 10)) e = s // 10 - ((a * 10000) + (b *1000) + (c * 100) + (d * 10)) f = s % 10 sp = b + d + f si = a + c + e if (sp % si != 0): mensagem = "senha invalida" else: mensagem = "acesso liberado" print(mensagem)
dddb18e98800f14bb8557349439d937b9776a6a0
puzzledpromise/pybites
/275/domains.py
1,295
3.515625
4
from collections import Counter import bs4 import requests COMMON_DOMAINS = ("https://bites-data.s3.us-east-2.amazonaws.com/" "common-domains.html") TARGET_DIV = {"class": "middle_info_noborder"} def get_common_domains(url=COMMON_DOMAINS): """Scrape the url return the 100 most common domain names""" page = requests.get(url) soup = bs4.BeautifulSoup(page.content, 'html.parser') table_rows = soup.find('div', class_='middle_info_noborder').find('table').find_all('tr') result = [] for tr in table_rows: entry = list(tr.children)[2] result.append(str(entry)[4:-5]) return result def get_most_common_domains(emails, common_domains=None): """Given a list of emails return the most common domain names, ignoring the list (or set) of common_domains""" if common_domains is None: common_domains = get_common_domains() count = [] for e in emails: e_parts = e.split("@") if e_parts[1] not in common_domains: count.append(e_parts[1]) counter = Counter(count) return counter.most_common() # your code if __name__ == "__main__": emails=["a@gmail.com", "b@pybit.es", "c@pybit.es", "d@domain.de"] print(get_most_common_domains(emails))
e7f4291d18799e962453f77c82c9b15dc3019bb6
drakonorozdeniy/Programming
/Practice/Autum/Python/19. Медвежья память.py
444
3.625
4
print("Введите длину пароля:") lenght=int(input()) print("Введите символы") simbols=str(input()) code = [''] code_new = [] for i in range(lenght): for j in code: for k in simbols: code_new += [j + k] code = code_new code_new = [] for j, i in zip(code, range(len(code))): if (not all([k in j for k in simbols])): del code[i] for i in range(len(code)): print(code[i],end=" ")
9ed36759106473343375505cb78d83c5cc44b0d3
zerihunz/pyz
/operators.py
405
4.15625
4
a = 3 + 5 print(a) b = 'some' + 'bar' print(b) c = -5.2 print(c) d = 'la' * 5 print(d) #Power operator is ** e = 2 ** 6 print(e) #Division operator is /, Divide and floor operator is //, what that means is divide x by y and round the answer to the nearest integer, if one of the values is float, the result is a float #Prints 4 f = 13 // 3 print(f) #Prints -5 f = -13 // 3 print(f) f = 9 // 1.81 print(f)
2760434dc1ba24dab9a1f62b6f61f6f86d1d1bcd
dg5921096/Books-solutions
/Python-For-Everyone-Horstmann/Chapter3-Decisions/P3.19.py
774
4.125
4
# Write a program that prompts the user to provide a single character from the alpha­ # bet. Print Vowel or Consonant, depending on the user input. If the user input is # not a letter (between a and z or A and Z), or is a string of length > 1, print an error # message. from sys import exit character = str(input("Enter a character: ")) if len(character) == 1 and character.isalpha(): if character == 'a' or character == 'A' or character == 'e' or character == 'E' or character == 'i'\ or character == 'I' or character == 'o' or character == 'O' or character == 'u' or character == 'U': print("The character is a vowel.") else: print("The character is a consonant") else: exit("Invalid input. Not a character or more than 1 character.")
f4ade422306e224cf7f8cc94818c069c816a6ab1
joewaldron/ALevel
/thequiz.py
1,441
4.625
5
''' Anything written here is called a comment - the computer ignores it, so this lets you explain what your code does. This type of comment can have as many lines as you like, as long as it is between the sets of three apostrophes. ''' # Comments can also look like this, starting with a hash symbol. # Useful if something doesn't work and you want to ask for advice! name = input("Please enter your name:") print("Well hello,", name) if name.find('s') > 0: print("did you know you have an 's' in your name?") # It is important to use the tab key for any instructions that need to happen only if the above condition is true # This is how Python knows which bits of your code need to be run in which order. else: print("There's no 's' in your name!") country = input("please tell me what country you're from... ") nexta = input("Shall I tell you the capital? Please write 'y' or 'n'.") if nexta == "y" or nexta == "Y": print("the capital of", country, "is...", country.upper()[0], "! Aren't I clever ;)?") elif nexta == "n" or nexta == "N": # elif stands for else, if - it's shorter! print("oh go on.") # to understand how this works, try to run the program and get all of these outputs. else: print("I didn't understand that...") ''' I have used some other functions here which I am sure you can work out what they do by running this code! Below you can write your quiz questions as per the task... '''
0c39dd1a17927a4779c1f73c9ec1ea79c5392ea4
hsuanhauliu/leetcode-solutions
/medium/product-of-array-except-self/solution.py
987
3.859375
4
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: """ Two-pass approach One the first pass, use the list to record the product of all elements on the left side including the number itself. On the second pass, we traverse backward. The product excluding self would be all products on the left and right side. We can use a single variable to record the current product of all elements on the right side. Time: O(n) Space: O(1): excluding output space """ length = len(nums) res = [1] * length res[0] = nums[0] for i in range(1, length - 1): res[i] = res[i-1] * nums[i] res[-1] = res[-2] right_product = nums[-1] for i in reversed(range(1, length - 1)): res[i] = res[i-1] * right_product right_product *= nums[i] res[0] = right_product return res
a1f4376d0e586e49364e342cdcd8196052d6bb26
QuirinoC/46Exercises
/simpleIO32.py
1,030
4
4
def get_user_file(): try: print("\nFile must be in the same folder, \n\ Please write with extension, if the file is \n\ a .docx please write file.docx\n") userInput = input("\nFile name: ") # DEBUG #userInput = "palindrome.txt" file_ = open(userInput,"r+") #file_ = open(input("Name of file: \n"),"r+") file_string = file_.read() file_.close() except: print ("There is no such file") get_user_file(userInput) return file_string def is_palindrome(string): ''' The following line creates a list containing the elements in the string excepting a blank space, and then joins it again to the same string ''' string = "".join([i for i in string if (i != " ")]) if string.lower() == string[::-1].lower(): return True def print_palindrome(list): for i in list: if is_palindrome(i): print (i) userFile = get_user_file() userFile = userFile.split("\n") print_palindrome(userFile)
45217849c1944795fd4518695d9f293f1e16c1a5
jayzane/leetcodePy
/greedy/665_check_possibility.py
1,598
3.8125
4
from typing import * class Solution: """ 给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。 我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。 示例 1: 输入: [4,2,3] 输出: True 解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。 示例 2: 输入: [4,2,1] 输出: False 解释: 你不能在只改变一个元素的情况下将其变为非递减数列。 说明: n 的范围为 [1, 10,000]。 """ def checkPossibility(self, nums: List[int]) -> bool: pass def check_possibility(nums: List[int]) -> bool: """ :param nums: :return: >>> check_possibility([3, 4, 2, 3]) False >>> check_possibility([4, 2, 3]) True >>> check_possibility([4, 3, 2]) False >>> check_possibility([2]) True >>> check_possibility([2, 3, 4, 7, 9, 10, 5, 12, 15]) True """ if not nums: return False decr_cnt: int = 0 # 逆序计数 for index in range(1, len(nums)): if nums[index] >= nums[index - 1]: continue decr_cnt += 1 if decr_cnt > 1: return False if index > 1 and nums[index] < nums[index - 2]: # [4, 5, 3] nums[index] = nums[index - 1] else: # [2, 5, 3] nums[index - 1] = nums[index] return True if __name__ == '__main__': import doctest doctest.testmod()
7d2aa9ce7ecda857408648b35472e5e03ce214be
Kim-Do-Yun/studyname
/question_pile/question221-230.py
1,004
4.03125
4
def print_reverse(string): print(string[::-1]) print_reverse("python") def print_score(score_list): print(sum(score_list)/len(score_list)) print_score([1,2,3]) def print_even(even_list): for i in even_list: if i%2 == 0: print(i) def print_keys(dic): for keys in dic.keys(): print(keys) def print_value_by_key(dic,key): print(dic[key]) my_dict = {"10/26" : [100, 130, 100, 100], "10/27" : [10, 12, 10, 11]} print_value_by_key(my_dict,"10/26") def print_5xn(line): num = int(len(line)/5) for i in range(num+1): print(line[i*5:i*5+5]) def print_mxn(line,num): number = int(len(line)/num) for i in range(number+1): print(line[i*num:i*num+num]) def calc_monthly_salary(mon): money = int(mon/12) return money def my_print (a, b) : print("왼쪽:", a) print("오른쪽:", b) my_print(a=100, b=200) def my_print (a, b) : print("왼쪽:", a) print("오른쪽:", b) my_print(b=100, a=200)
9d55c4853b8f2253b229a3fc2e6dbe40f9a44674
Dude036/cs1400-sp18
/2-01/main.py
1,316
4.375
4
#!/usr/bin/python ''' Case Studies will be homework assignments from now on ''' # Using Turtle - https://docs.python.org/3.3/library/turtle.html import turtle from random import randrange turtle.circle(15) turtle.circle(35, steps=3) # input("Wait") turtle.colormode(255) turtle.penup() turtle.goto(0, 150) turtle.pensize(12) turtle.pendown() # Ignore this line for _ in range(36): turtle.forward(35) turtle.right(10) turtle.pensize(randrange(100)) turtle.pencolor(randrange(255), randrange(255), randrange(255)) turtle.done() # Math with dates in datetime - https://docs.python.org/3/library/datetime.html from datetime import datetime currentTime = datetime.now() hour = currentTime.hour print(hour+9%12, ':', currentTime.minute, ':', currentTime.second) """ Case Study - Compute the Distance between two points.with Turtle """ x1 = int(input("What's the first X Coordinate? ")) y1 = int(input("What's the first Y Coordinate? ")) x2 = int(input("What's the second X Coordinate? ")) y2 = int(input("What's the second Y Coordinate? ")) import turtle turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) import math Distance = math.sqrt((x2-x1)**2 + (y2 - y1)**2) print("Distance between the two points: ", Distance) input("Stop") pi = 3.14159265357 print(round(pi, 7))
9332f911b41e40769962486e18eca5dcbceab532
Kori3a/M-PT1-38-21
/Tasks/Olga Tuchinskaya/HW7/characters.py
784
3.65625
4
from random import randint class Creature: def __init__(self, health, attack, level): self.health = health self.attack = attack self.level = level class Hero(Creature): def __init__(self): Creature.__init__(self, randint(170, 280), randint(20, 40), 23) class Monster(Creature): def __init__(self): Creature.__init__(self, randint(190, 300), randint(25, 35), 26) H = Hero() M = Monster() def fight(): count = 0 while H.health > 0 or M.health > 0: H.health = H.health - M.attack M.health = M.health - H.attack count += 1 if H.health > M.health: return f"The Hero won, he gave {count} times!" else: return f"The Monster won, he gave {count} times!" print(fight())
0a26b51b8e7cdea122e0283b7ae74b5def156912
AhnJG/AI-Project
/Perceptron_Xor/Perceptron_Xor_3.py
1,389
3.53125
4
#b가 없으면 x1 = 0, x2 = 0인 상태에서 학습시킬 수 없다 #3층 네트워크, 1L : 2, 2L : 1, 3L : 1 import numpy as np X = np.array([[0,0,1,1],[0,1,0,1]]) #2,4 Y = np.array([0, 1, 1, 0]).reshape((1,4))#1,4 W1 = np.random.rand(1,2) * 2 - 1 #1,2 W2 = np.random.rand(1,1) * 2 - 1 #1,1 theta = 0.1 b1 = 0 b2 = 0 def propagate(W1, W2, b1, b2, X): L1 = sigmoid((np.dot(W1, X) + b1)) #(1,2)*(2,4) -> (1,4) L2 = sigmoid(W2 * L1 + b2) #(1,1)*(1,4) -> (1,4) return L1, L2 def sigmoid(X): return 1/(1 + np.exp(-X)) def optimizer(W1, W2, b1, b2, L1, L2, X, Y, theta): W1 = W1 - theta * np.dot((1 / Y.shape[1]) * (L2 - Y) * (L2) * (1 - L2) * W2 * (L1) * (1 - L1), X.T) b1 = b1 - theta * np.sum((1 / Y.shape[1]) * (L2 - Y) * (L2) * (1 - L2) * W2 * (L1) * (1 - L1), axis=1) W2 = W2 - theta * (1 / Y.shape[1]) * (L2 - Y) * (L2) * (1 - L2) * L1 b2 = b2 - theta * np.sum((1 / Y.shape[1]) * (L2 - Y) * (L2) * (1 - L2), axis=1) return W1, b1, W2, b2 def predict(X): _, pre = propagate(W1, W2, b1, b2, X) pre = np.where(pre > 0.5, 1, 0) return pre for _ in range(1, 301): L1, L2 = propagate(W1, W2, b1, b2, X) W1, b1, W2, b2 = optimizer(W1, W2, b1, b2, L1, L2, X, Y, theta) if _ % 10 == 0: print('진행: ', _, '현재 W*X+b: ', L2) result = predict(X) print(result)
a02b3a94e68236e9df0b286028f824c222e1748d
nptit/checkio-3
/StickSawing.py
734
3.59375
4
#!/usr/bin/python def checkio(number): k = int(number ** 0.5) table = [x * (x + 1) / 2 for x in range(1, k + 1)] candidates = [([], -1)] #just try all for i in range(k - 1): for j in range(i + 1, k): if sum(table[i:j + 1]) == number: candidates.append((table[i:j + 1], j - i)) candidates.sort(key = lambda x: x[1]) return candidates[-1][0] #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio(64) == [15, 21, 28], "1st example" assert checkio(371) == [36, 45, 55, 66, 78, 91], "2nd example" assert checkio(225) == [105, 120], "3rd example" assert checkio(882) == [], "4th example"
420a26c598dc46ec8be5cc4db4607230fd063fb0
BUEC500C1/health-monitor-4-heros
/AlertModule/Alert/alertModule.py
2,999
3.984375
4
''' 4 main functions: Receive message Set threshold Alarm Send data to display ''' # import needed libraries import sys import time import requests import json import urllib3 # receive information def recMsg(msg, val): # Once we did not receive data, # we will request again from traffic control for information. try: if msg is None: # The variable print('Message is None') # call a for loop to remind user for i in range(3): msg2 = input("please type in a value for msg") alertMod(msg2, val) except NameError: print ("This message is not defined") else: print ("Message is received and has a value") # set threshold to compare with received value def setThre(val, msg1, msg2, msg3, msg4): # Once there is no threshold, set up a new one. th = 100 # test value for threshold, we can change based on collected information usrVal = int(val) if usrVal > th: print("Current value is bigger than threshold, alarm and program ends!") alarm() time.sleep(1) sys.exit() elif usrVal == th: print("Current value is same to threshold, warning! Sending data to display...") time.sleep(2) sendData(msg1, msg2, msg3, msg4) else: print("Current value is less than threshold, ok! Sending data to display...") time.sleep(2) sendData(msg1, msg2, msg3, msg4) # alarm function def alarm(): # alarm user for several times for i in range(3): print("Val is too big, alarm!") time.sleep(5) # after 5s sleep, we give another 3 times alarm print("Val is too big, alarm!") time.sleep(5) # after 5s sleep, we give another 3 times alarm - last time print("Val is too big, alarm!") # send data as post method to display API def sendData(msg1, msg2, msg3, msg4): # spo2 bp hr awrr --- "SpO2", "Blood Pressure", "HR", "PR" kindsInfo = ["spo2", "bp", "hr", "awrr"] dataInfo = [msg1, msg2, msg3, msg4] for i in range(4): url = 'http://127.0.0.1:5000/' + kindsInfo[i] info = dataInfo[i] s = json.dumps({ "value" : info }) #print(info) #print(type(info)) r = requests.post(url, data=s, verify=False) print(r.text) mes = msg1+'/'+ msg2 + '/'+ msg3 +'/' + msg4 # after post data to url, print the result print("sent data: " + mes + ".") # alert module def alertMod(msg, val): recMsg(msg, val) if __name__ == '__main__': urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) msg1 = input("type in value for Sp02 \n") msg2 = input("type in value for Blood Pressure \n") msg3 = input("type in value for HR \n") msg4 = input("type in value for PR \n") # i.e. "{'Blood_Pressure': 100, 'Pulse': 75, 'Oxygen_Level': 340}" msg = msg1+'/'+ msg2 + '/'+ msg3 +'/' + msg4 val = input("type in an int value \n") # based on blodd pressure value, we set threshold to compare with, in this example is 100. alertMod(msg, val) setThre(val, msg1, msg2, msg3, msg4)
01d5336a83b8b8aa4196ff13686e45e6a884e865
dcosmic/thinkcspy3
/ch06/06.13-slope_and_intercept.py
1,332
3.90625
4
import sys import math def isnum(x): if isinstance(x, int) or isinstance(x, float): return True else: return False def slope(x1, y1, x2, y2): if isnum(x1) and isnum(y1) and isnum(x2) and isnum(y2): if x1 == x2: slp == math.inf else: slp = (y2 - y1) / (x2 - x1) return slp else: return None def intercept(x1, y1, x2, y2): if x1 < x2: inter = y1 - x1 * slope(x1, y1, x2, y2) elif x1 == x2: inter == None elif x1 > x2: inter = y2 - x2 * slope(x1, y1, x2, y2) else: inter = None return inter def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller’s line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def test_suite(): """ Run the suite of tests for code in this module (this file). """ test(slope(5, 3, 4, 2) == 1.0) test(slope(1, 2, 3, 2) == 0.0) test(slope(1, 2, 3, 3) == 0.5) test(slope(2, 4, 1, 2) == 2.0) test(intercept(1, 6, 3, 12) == 3.0) test(intercept(6, 1, 1, 6) == 7.0) test(intercept(4, 6, 12, 8) == 5.0) test_suite() # Here is the call to run the tests
d87a8bcc3357b7d383fda77c53dad89133c716e9
Half-Quarter/algorithms_in_python
/data_structure/heap_sort.py
1,463
3.6875
4
# basic definition """ A is a num array, using 1-coordinate. For Node i, its value = A[i] PARENT Node is i/2 LEFT CHILD Node is 2i RIGHT CHILD Node is 2i+1 """ def max_heapify(A,i): l_i = (i+1)*2 - 1 r_i = (i+1)*2 +1 -1 l = A[l_i] ori = A[i] try: r = A[r_i] except: r = min(ori,l) - 1 # in case we choose the node which only have one left child node. largest = ori largest_i = i if l > ori: largest_i = l_i largest = l if r > largest: largest_i = r_i largest = r if largest_i != i: A[i] = largest A[largest_i] = ori if largest_i not in range(len(A)/2,len(A)+1): # if largest_i not in the leaves nodes. return max_heapify(A,largest_i) return A def build_max_heap(A): for i in range(len(A)/2-1, -1, -1): A = max_heapify(A,i) return A def heapsort(A): A = build_max_heap(A) #print 'max heap A: ',A for i in range(len(A)-1,1,-1): cache = A[i] A[i] = A[0] A[0] = cache try: A = max_heapify(A[:i],0) + A[i:] except: # when sorting single node array, it will raise error. # if we not iterate the single node array, it will put the smallest two reverse because of the max_heapify process. pass return A test = [4,1,3,2,16,9,10,14,8,7] #print max_heapify(test,1) #print heapsort(test)
ec1f007d3ad7389902ba0085dfd8ebdaaee4c267
menduhkesici/Project_Euler
/Problem 27 - Quadratic primes.py
487
3.546875
4
def isPrime(n): if n < 0: return False for x in range(2, int(n**0.5) + 1): if n % x == 0: return False # NOT prime number return True # prime number max_primes = 0 max_a_b = 0 for a in range(-999,1000): for b in range(-1000,1001): n = 0 while True: quad_exp = n**2 + a * n + b if isPrime(quad_exp) == True: n += 1 else: break if (n - 1) > max_primes: max_primes = n - 1 max_a_b = a * b print(max_a_b) # Answer: -59231
68912a09e5c386daba4393a4e66daf46d67d16fb
Martin-Ascouet/Tp12_2nd_anee
/Exercice4.py
192
3.578125
4
def listSum(l): if len(l) != 0: a = l[0] del l[0] return a+listSum(l) return 0 print(listSum([])) # 0 print(listSum([42])) # 42 print(listSum([3,1,5,2])) # 11
9728dd42abedbdd6320be1a8153fd76a03b9bd22
alexjercan/algorithms
/old/hackerrank/interview-kit/triple-sum.py
1,073
3.546875
4
#!/bin/python3 import math import os import random import re import sys # Complete the triplets function below. def triplets(a, b, c): r = 0 xs, ys, zs = sorted(list(set(a))), sorted( list(set(b))), sorted(list(set(c))) cnt = 0 xys = {} i = 0 for y in ys: while i < len(xs) and xs[i] <= y: cnt += 1 i += 1 xys[y] = cnt cnt = 0 zys = {} i = 0 for y in ys: while i < len(zs) and zs[i] <= y: cnt += 1 i += 1 zys[y] = cnt for y in ys: r += xys[y] * zys[y] return r if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') lenaLenbLenc = input().split() lena = int(lenaLenbLenc[0]) lenb = int(lenaLenbLenc[1]) lenc = int(lenaLenbLenc[2]) arra = list(map(int, input().rstrip().split())) arrb = list(map(int, input().rstrip().split())) arrc = list(map(int, input().rstrip().split())) ans = triplets(arra, arrb, arrc) fptr.write(str(ans) + '\n') fptr.close()
a6c3c33ebf2f2da51e2d9fa739e95e67c31b4d7c
aquatiger/LaunchCode
/mystery drawing.py
799
3.84375
4
# Draw a picture based on the txt file mystery # When UP go to the next line, read x,y coordinates, go to that point # When DOWN go to the next line, read x,y coordinates, go to that point and continue until UP import turtle wn = turtle.Screen() # Set up the window and its attributes wn.bgcolor("beige") hadir = turtle.Turtle() # create hadir hadir.color('orange') hadir.speed(0) datums = open("C:/Users/Roger/Documents/GitHub/LaunchCode/mystery.txt", "r") for aline in datums: splitted = aline.split() try: coords = [int(i) for i in splitted] x = coords[0] y = coords[1] hadir.goto(x, y) except: if splitted[0] == "UP": hadir.pu() elif splitted[0] == "DOWN": hadir.pd() turtle.exitonclick()
82f3f1fc30bbc88f704a21a28ab20bd3386235bf
behraam/moving2
/moving2.py
5,244
3.734375
4
import pandas as pd import matplotlib.pyplot as plt from datetime import datetime as dt def calculate_amortization_amount(principal, interest_rate, period): x = (1 + interest_rate) ** period return principal * (interest_rate * x) / (x - 1) def amortization_schedule(principal, interest_rate, period): amortization_amount = calculate_amortization_amount(principal, interest_rate, period) number = 1 balance = principal total_interest = 0 total_principal = 0 while number <= period: interest = balance * interest_rate principal = amortization_amount - interest balance = balance - principal total_interest = total_interest + interest total_principal = total_principal + principal yield number, amortization_amount, interest, principal, total_interest, total_principal, balance \ if balance > 0 else 0 number += 1 def stamp_duty(purchase_price): if purchase_price <= 125000: return "No stamp Duty" elif 125000 < purchase_price <= 250000: return "Didn't code for this" elif 250000 < purchase_price <= 850000: duty1 = 125000 * 0.02 duty2 = (purchase_price - 250000) * 0.05 duty = int(duty1 + duty2) return duty elif 850000 < purchase_price: return "Didn't code for this" def equity_calc(selling_price, mortgage): if selling_price > mortgage: equity = int(selling_price - mortgage) return equity else: return ArithmeticError def diff_month(start_date, end_date): d1 = end_date d2 = start_date return (d1.year - d2.year) * 12 + (d1.month - d2.month) def mortgage_data(data, principal, interest_rate, period, months1): amortization = list(amortization_schedule(principal, interest_rate/100/12, period*12)) amortization_df = pd.DataFrame(amortization) amortization_df.columns = ["number", "amortization_amount", "interest", "principal", 'total_interest', 'total_principal', "balance"] amortization_row = amortization_df[amortization_df.number == months1] column_of_interest = data result = amortization_row[column_of_interest].values[0] return result start = dt(2018, 11, 10) # end = dt(2020, 12, 31) end = dt.today() principal1 = 271999 interest_rate1 = 2.09 period1 = 25 months = (diff_month(start, end)) selling1 = 320000 buying1 = 575000 savings1 = 7000 savings_rate = 1000 desired_deposit_p = 0.1 moving_costs = int(5000) solicitor = int(1200) def savings_projection(end1, savings_rate1): end = end1 savings_rate = savings_rate1 if diff_month(end, dt.today()) == 0: savings = savings1 return savings else: month_in_future = diff_month(dt.today(), end) future_savings = month_in_future * savings_rate savings = savings1 + future_savings return savings savings = int(savings_projection(end, savings_rate)) deposit = int(desired_deposit_p * buying1) mortgage = (mortgage_data("balance", principal1, interest_rate1, period1, months)) equity = (equity_calc(selling1, mortgage)) duty = int(stamp_duty(buying1)) total_cash = equity + savings total_expenses = deposit + moving_costs + solicitor + duty # print(amortization_df, sep='\n') # df_obj.plot(x='number', y=['amortization_amount', 'total_principal'], figsize=(10, 5), grid=True) #plt.show() # Print section # print(f'----- Input Data -----') print(f'Selling price £{selling1:,}') print(f'New house price £{buying1:,}') print(f'Assumed date for calculation {end}') print(f'---- Equity ------') print(f'Equity in the house = £{equity:,} (mortgage of £{int(mortgage):,})') print(f'Savings = £{savings:,}') print(f'===========> Total Cash = £{total_cash:,}') print(f'----- Expenses -----') print(f'Money needed for deposit of {int(desired_deposit_p * 100):,}% = £{deposit:,}') print(f'Stamp Duty = £{duty:,}') print(f'Solicitor & Moving costs = £{moving_costs + solicitor:,}') print(f'===========> Total expenses = £{total_expenses:,}') if total_cash < total_expenses: left = total_expenses - total_cash print(f'You have to save = £{left:,}') else: left = total_cash - total_expenses print(f'You have more than required = £{left:,}') year = 2019 month = 8 # TODO Find out today's month df1 = pd.DataFrame({"date": [end], "total_cash": [total_cash]}) cols = ["date", "equity", "savings", "total_cash", "left_to_save", "deposit", "stamp_duty", "total_expenses"] lst = [] # Try and work out the break even point while total_cash < total_expenses: end = dt(year, month, 28) months = diff_month(start, end) mortgage = (mortgage_data("balance", principal1, interest_rate1, period1, months)) equity = (equity_calc(selling1, mortgage)) savings = int(savings_projection(end, savings_rate)) total_cash = equity + savings left = total_expenses - total_cash lst.append([end, equity, savings, total_cash, left, deposit, duty, total_expenses]) if month == 12: month = 1 year += 1 else: month += 1 df1 = pd.DataFrame(lst, columns=cols) print(df1, sep='\n') df1.plot(x='date', y=['total_cash', 'total_expenses'], figsize=(10, 5), grid=True) plt.show()
3226200139d535e1b6ddf9ecfacdaf0beb325c20
zhangxianyou33/python_demo
/io_biancheng/open_file.py
1,461
4.25
4
#方法一:使用系统内置函数open def open_file(): try: file = open(r"test.txt", "r") print("文件名称:",file.name) print("文件是否已关闭:",file.closed) print("文件访问模式:", file.mode) finally: file.close() print("使用close方法,关闭文件状态为:", file.closed) open_file() print("======open方法,写入文件======") def open_write(): try: f = open("test.txt", "w") f.write("这是使用open,写入的文件\nhello word\n第三行\n") finally: f.close() open_write() print("======使用with方法,读取文件======") def with_read(): with open(r"test.txt", "r") as file: data = file.readline() while data: print(data, end="") data = file.readline() with_read() #方法二:使用with方法 print("======使用with方法,写入文件======") def with_write(): with open("test.txt", "w") as f: f.write("使用with的write方法,写入文件,旧的文件已经被覆盖\n") with_write() with_read() print("======使用with方法追加文件======") def with_add(): with open("test.txt", "a") as f: f.write("这是with的追加文件!!!\n") with_add() with_read() print("======使用with方法,迭代读取文件======") def for_read(): with open("test.txt", "r") as f: for i in f: print(i, end="") for_read()
80dccbceb92f2a9b75892ca7dc5236c1bb82be6f
rajatsharma98/CS677
/HW/lyndon97_8_1_8.py
1,235
3.59375
4
import os import pandas as pd import numpy as np wd = os.getcwd() input_dir = wd file_read = os.path.join(input_dir,"tips.csv") df = pd.read_csv(file_read) df['tip_percent'] = 100.0 * df['tip']/df['total_bill'] df_smoke = df[df['smoker'] == 'Yes'] df_nonsmoke = df[df['smoker'] == 'No'] # calculate cor [total_bill, tip] among smoke/non-smoke cor1 = df_smoke['tip'].corr(df_smoke['total_bill']) cor2 = df_nonsmoke['tip'].corr(df_nonsmoke['total_bill']) smoke_tips_mean = df_smoke['tip_percent'].mean() nonsmoke_tips_mean = df_nonsmoke['tip_percent'].mean() r2_cor1 = cor1**2 r2_cor2 = cor2**2 print("We use r-square to evaluate the what percentage of the total " "\nvariation in the variables is explained by this correlation.") print("The r-square of smokers is 67.5% and nonsmokers is 23.8%," "\nwhich means the relationship between tips and meal prices are " "\nstrongly associated among non-smokers than those smokers." "\nThus the correlation between smokers and non-smokers are different.") # print(smoke_tips_mean,nonsmoke_tips_mean) print("Also, the average tips percentage of smokers is 16.32%, and non-smokers is 15.93%," "\nwhich means smokers will give more tips than non-smokers.")
32a7cbb5434e362f6028ff4c433c4cf437aa11dc
Jhruzik/pyreiseamt
/pyreiseamt/scraper.py
6,430
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Import Modules from bs4 import BeautifulSoup import requests import re # List all available Countries def list_countries(): """List all available countries for extraction This function will create a connection to the website of the German Foreign Office and fetch the latest list of available countries. Returns ----------- The function returns None. However, a formatted list of countries is printed to the screen. Four countries per row, sperated by ' | '. """ # Open First Page base_url = "https://www.auswaertiges-amt.de/de/ReiseUndSicherheit/reise-und-sicherheitshinweise" base_html = requests.get(base_url).content base_soup = BeautifulSoup(base_html, "lxml") # Collect Remaining Pages total_links = base_soup.find_all("a", {"class" : "pagination__list-link"}) total_links = [base_url + "/" + x["href"] for x in total_links] total_links.append(base_url) # Function to list all Countries on Page with Link def _find_countries(url): # Find Content countries_html = requests.get(url).content countries_soup = BeautifulSoup(countries_html, "lxml") countries_boxes = countries_soup.find_all("div", {"class" : "c-teaser--country is-image-headline"}) # Find Country Names countries_names = [] for box in countries_boxes: headline = box.find("h3", {"class" : "teaser__headline"}) country = headline.get_text().strip() countries_names.append(country) # Find Links countries_links = [] for box in countries_boxes: link = box.find("a")["href"] link = "https://www.auswaertiges-amt.de"+link countries_links.append(link) # Join to Dict if len(countries_names) == len(countries_links): country_dict = dict(zip(countries_names, countries_links)) else: raise ValueError("Number of Country Names and Number of Links does not match.") return(country_dict) # Collect all Countries on all Pages all_dict = dict() for link in total_links: dict_tmp = _find_countries(link) all_dict.update(dict_tmp) # Return all Countries in a Dictionary return(all_dict) # Extract Information for a Single Country def extract_country(url): """Scrape information for a given country Given a certain countries url, this function will return a dictionary containing information on country specific securitiy issues, general travel guidance, and medical issues. Every top category is subdivided by several sub-categories. The result will be a structured dictionary. Parameters ----------- url: string The url of a single country as string. Returns ----------- text_dict: A dictionary consisting of four top categories. Every top category is associated with another dictionary containing sub-categories for the respective top category. """ # Find Raw Content country_html = requests.get(url).content country_soup = BeautifulSoup(country_html, "lxml") # Find Country Name country = country_soup.find("span", {"class" : "heading__title-text"}).get_text().strip() country = re.search("(^.+):", country).group(1) # Define Function to find Text for Section def _collect_text(start, end): siblings = start.next_siblings # Find Elements next to Header collect_dict = {} # Iterate through Siblings for sibling in siblings: if sibling.name == end: # Stop as soon as stop criterion is met break if sibling.name == "h3": sub_section = sibling.get_text().strip() sibling = next(siblings) while sibling == "\n": sibling = next(siblings) text = sibling.get_text() text = re.sub("^"+sub_section, "", text) tmp_dict = {sub_section : text} collect_dict.update(tmp_dict) elif sibling.name == "p": # If Element is 'p', then add text try: sub_section = sibling.em.get_text().strip() text = sibling.get_text() text = re.sub("^"+sub_section, "", text) tmp_dict = {sub_section : text} collect_dict.update(tmp_dict) except Exception: pass # Define Result section_name = start.get_text() section_dict = {section_name : collect_dict} return(section_dict) # Init Dictionary to collect Information on Country text_dict = {"Country" : country} # Get Country Specific Info def _country_specific_filter(tag): cond1 = tag.name == "h2" cond2_1 = "Landesspezifische Sicherheitshinweise" in tag.get_text() cond2_2 = "Landesspezifischer Sicherheitshinweis" in tag.get_text() cond2_3 = "Sicherheit" in tag.get_text() return(cond1 & (cond2_1 | cond2_2 | cond2_3)) start = country_soup.find(_country_specific_filter) end = "h2" specific_info = _collect_text(start, end) text_dict.update(specific_info) # Get General Information def _general_filter(tag): cond1 = tag.name == "h2" cond2_1 = "Allgemeine Reiseinformationen" in tag.get_text() cond2_2 = "Reiseinfos" in tag.get_text() return(cond1 & (cond2_1 | cond2_2)) start = country_soup.find(_general_filter) end = "h2" general_info = _collect_text(start, end) text_dict.update(general_info) #Get Medical Information def _medical_filter(tag): cond1 = tag.name == "h2" cond2_1 = "Medizinische Hinweise" in tag.get_text() cond2_2 = "Gesundheit" in tag.get_text() return(cond1 & (cond2_1 | cond2_2)) start = country_soup.find(_medical_filter) end = "h2" medical_info = _collect_text(start, end) text_dict.update(medical_info) return(text_dict)
9279d7f850031f1577e7f82f0bd45989ec62093d
joshua-hampton/my-isc-work
/python_work/numpy_exercises/numpydimensions.py
326
3.96875
4
#!/usr/bin/python import numpy as np ''' Quick code to find the maximum number of dimensions a numpy array can have ''' a=1 dim=[1] while True: try: print np.zeros(dim) print 'number of dimensions:',len(dim) dim.append(a) except ValueError: print 'max number of dimensions in numpy array:',len(dim[:-1]) exit()
3164466f73b761f160c63c730d20836df1192f65
l3eamster/Data_Structure
/labTest/Stack.py
3,932
3.9375
4
class Stack : def __init__(self,list = []) : #สร้าง empty list if list == []: self.items = [] else: self.items = list def __str__(self) : #พิมพ์ของที่อยู่ใน stack จากล่างขึ้นบน return str(self.items) def __len__(self) : #ส่งค่าจำนวนสมาชิกใน stack return len(self.items) def isEmpty(self) : #ส่งค่า True ถ้า Stack ว่าง, False ถ้าไม่ว่าง return len(self.items) == 0 def push(self,i) : #นำของเก็บใน stack self.items.append(i) def pop(self) : #นำของออกจาก stack if self.items != []: return self.items.pop() def peek(self) : return self.items[-1] def checkPriority(current, next): priorCur = 0 priorNext = 0 if current in ['+','-']: priorCur = 1 else: priorCur = 2 if next in ['+','-']: priorNext = 1 else: priorNext = 2 return priorCur >= priorNext def operation(infix): count = 0 for i in infix: if i in ['+','-','*','/']: count += 1 return str(count) def operand(infix): count = 0 for i in infix: if 'a' <= i <= 'z' or 'A' <= i <= 'Z': count += 1 return str(count) def inToPost(infix): s = Stack() postFix = '' for i in infix: if 'a' <= i <= 'z' or 'A' <= i <= 'Z': postFix += i elif i == '(': s.push(i) elif i == ')': while not s.isEmpty(): if s.peek() == '(': s.pop() break postFix += s.pop() elif i in ['+','-','*','/']: while not s.isEmpty() and checkPriority(s.peek(), i): if s.peek() == '(': break postFix += s.pop() s.push(i) while not s.isEmpty(): postFix += s.pop() return postFix def inToPre(infix): reversed_infix = '' tmp = infix[::-1] for i in tmp: if i == '(': reversed_infix += ')' elif i == ')': reversed_infix += '(' else : reversed_infix += i prefix = inToPost(reversed_infix) prefix = prefix[::-1] return prefix def postToIn(postfix): infix = '' s = Stack() for i in postfix: if 'a' <= i <= 'z' or 'A' <= i <= 'Z': s.push(i) elif i in ['+','-','*','/']: tmp1 = s.pop() tmp2 = s.pop() tmp = '(' + tmp2 + i + tmp1 + ')' s.push(tmp) while not s.isEmpty(): infix += s.pop() return infix # s1 = 'a+b*c-d' # s2 = 'a+b*c-(d/e+f)*g' # s3 = '(a+b)*c/d' # result1 = abc*+d- # result2 = abc*+de/f+g*- # result3 = ab+c*d/ # s1 = input('Enter infix expression : ') # print('Result postfix expression : '+ inToPost(s1)) # print('Number of operation : '+ operation(s1)) # print('Number of operand : '+ operand(s1)) # s2 = input('Enter infix expression : ') # print('Result postfix expression : '+ inToPost(s2)) # print('Number of operation : '+ operation(s2)) # print('Number of operand : '+ operand(s2)) # s3 = input('Enter infix expression : ') # print('Result postfix expression : '+ inToPost(s3)) # print('Number of operation : '+ operation(s3)) # print('Number of operand : '+ operand(s3)) # s1 = input('Enter infix expression : ') # print('Result prefix expression : '+ inToPre(s1)) s1 = input('Enter postfix expression : ') print('Result infix expression : '+ postToIn(s1))
fcb042235ebc244420132573f2dede7003fa58ce
biswajithgopinathan/StudentInterventionSystem
/student_intervention.py
6,404
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 31 22:35:29 2017 @author: Biswajith Gopinathan """ # Building a student Intervention Progam """1. Classification vs Regression Your goal is to identify students who might need early intervention - which type of supervised machine learning problem is this, classification or regression? Why? The type of problem is 'Classification' as the objective is to find out the students will pass or not.""" # Import the libraries import numpy as np import pandas as pd # Read Student Data student_data = pd.read_csv("student-data.csv") print ("Student Data read succefully !!") # Display the below values about the datasets n_students = len(student_data) n_features = student_data.shape[1]-1 n_passed = len(student_data[student_data['passed']== 'yes']) n_failed = len(student_data[student_data['passed']== 'no']) grad_rate = 100.0* n_passed/n_students # Display the details as we done so far print ("Total number of students: {}".format(n_students)) print ("Total number of students who passed {}".format(n_passed)) print ("Total number of students who failed {}".format(n_failed)) print ("Number of features : {}".format(n_features)) print ("Graduation rate of the class {0:.2f}".format(grad_rate)) #Preparing the Data for medelling, trainig and testing #Identify feature and target columns - Data contains non-numeric features. Machine learning algorithms expect numeric values to perform computations # Extract feature (X) and target (y) columns feature_cols = list(student_data.columns[:-1]) # all columns but last are features target_col = student_data.columns[-1] # last column is the target/label print ("Feature column(s):-\n{}".format(feature_cols)) print ("Target column: {}".format(target_col)) X_all = student_data[feature_cols] # feature values for all students y_all = student_data[target_col] # corresponding targets/labels print ("\nFeature values:-") print (X_all.head()) # print the first 5 rows # Preprocess feature columns by converting categorical columns to numerical columns def preprocess_features(X): outX = pd.DataFrame(index=X.index) # output dataframe, initially empty # Check each column for col, col_data in X.iteritems(): # If data type is non-numeric, try to replace all yes/no values with 1/0 if col_data.dtype == object: col_data = col_data.replace(['yes', 'no'], [1, 0]) # Note: This should change the data type for yes/no columns to int # If still non-numeric, convert to one or more dummy variables if col_data.dtype == object: col_data = pd.get_dummies(col_data, prefix=col) # e.g. 'school' => 'school_GP', 'school_MS' outX = outX.join(col_data) # collect column(s) in output dataframe return outX X_all = preprocess_features(X_all) print ("Processed feature columns ({}):-\n{}".format(len(X_all.columns), list(X_all.columns))) # Split data into training and test sets split the data (both features and corresponding labels) into training and test sets. from sklearn import cross_validation from sklearn.cross_validation import train_test_split # First, decide how many training vs test samples we want num_all = student_data.shape[0] # same as len(student_data) num_train = 300 # about 75% of the data num_test = num_all - num_train X_train,X_test,y_train,y_test = cross_validation.train_test_split(X_all,y_all,train_size=300) print ("Training set: {} samples".format(X_train.shape[0])) print ("Test set: {} samples".format(X_test.shape[0])) # Training and Evaluating Models # Currently implementing 3 supervised learning models that are available in scikit learn # 1. Decision Trees # 2. Gaussian Naive Bayes # 3. Support Vector Machines # Train a model # This is a generic method which used for fitting the selected model import time def train_classifier(clf, X_train, y_train): print ("Training {}...".format(clf.__class__.__name__)) start = time.time() clf.fit(X_train, y_train) end = time.time() trainingtime=end-start print ("Done!\nTraining time (secs): {:.3f}".format(trainingtime)) return trainingtime from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier() # Fit model to training data DTC_trainingtime_300=train_classifier(clf, X_train, y_train) # note: using entire training set here # Predict on training set and compute F1 score from sklearn.metrics import f1_score def predict_labels(clf, features, target): print ("Predicting labels using {}...".format(clf.__class__.__name__)) start = time.time() y_pred = clf.predict(features) end = time.time() print ("Done!\nPrediction time (secs): {:.3f}".format(end - start)) return f1_score(target.values, y_pred, pos_label='yes') train_f1_score = predict_labels(clf, X_train, y_train) print ("F1 score for training set: {}".format(train_f1_score)) # Predict on test data print ("F1 score for test set: {}".format(predict_labels(clf, X_test, y_test))) # Train and predict using different training set sizes def train_predict(clf, X_train, y_train, X_test, y_test): print ("------------------------------------------") print ("Training set size: {}".format(len(X_train))) train_classifier(clf, X_train, y_train) print ("F1 score for training set: {}".format(predict_labels(clf, X_train, y_train))) print ("F1 score for test set: {}".format(predict_labels(clf, X_test, y_test))) train_predict(clf, X_train[0:100], y_train[0:100], X_test, y_test) train_predict(clf, X_train[0:200], y_train[0:200], X_test, y_test) train_predict(clf, X_train, y_train, X_test, y_test) # Implement Gaussian Nave Baye's Theorem for train classifier from sklearn.naive_bayes import GaussianNB clfG=GaussianNB() train_classifier(clfG, X_train, y_train) # Implement prediction using different training set sizes train_predict(clfG, X_train[0:100], y_train[0:100], X_test, y_test) train_predict(clfG, X_train[0:200], y_train[0:200], X_test, y_test) train_predict(clfG, X_train, y_train, X_test, y_test) # Implement Support Vector Machine for train classifier from sklearn.svm import SVC clf=SVC() train_classifier(clf, X_train, y_train)
e3ca56a83a63c1261fc574d7f9c31276737c2166
Rich-Mala-05/Esercizi-di-pagina-73
/es5-6_pag292.py
1,148
3.78125
4
class Prodotto: def __init__(self, tipo, peso, marca, taglia, stagione): self.tipo = tipo self.peso = peso self.marca = marca self.taglia = taglia self.stagione = stagione def assegna_prezzo(self): print("Hai chiesto alla cassiera quanto costa questo capo di abbigliamento") prezzi = [100,120,135,150,165,180] import random self.prezzo = random.choice(prezzi) print("Lei ti rispondere che costa", self.prezzo, "$") def info(self): print("Tipo:", self.tipo) print("Peso:", self.peso) print("Marca:", self.marca) print("Taglia:", self.taglia) print("Stagione:", self.stagione) print("Prezzo:", self.prezzo) tipo1 = input("Quale capo di abbigliamento stai cercando? ") peso1 = int(input("Indica il peso in grammi dell'indumento che cerchi ")) marca1 = input("Quale marca cerchi ") taglia1 = input("Di che taglia hai bisogno? (S, M, L) ") stagione1 = input("Cerchi un prodotto per l'inverno o per l'estate? ") p1 = Prodotto(tipo1, peso1, marca1, taglia1, stagione1) p1.assegna_prezzo() p1.info()
29b8d18abaae47ea807f4efa9f37250a4b610354
swetakum/Rosalind
/FIndingMotifinDNA.py
2,401
3.703125
4
# Given two strings ss and tt, tt is a substring of ss if tt is contained as a contiguous collection of symbols in # ss (as a result, tt must be no longer than ss). # The position of a symbol in a string is the total number of symbols found to its left, including itself # (e.g., the positions of all occurrences of 'U' in "AUGCUUCAGAAAGGUCUUACG" are 2, 5, 6, 15, 17, and 18). # The symbol at position ii of ss is denoted by s[i]s[i]. # # A substring of ss can be represented as s[j:k]s[j:k], where jj and kk represent the starting and ending # positions of the substring in ss; for example, if ss = "AUGCUUCAGAAAGGUCUUACG", then s[2:5]s[2:5] = "UGCU". # # The location of a substring s[j:k]s[j:k] is its beginning position jj; note that tt will have multiple # locations in ss if it occurs more than once as a substring of ss (see the Sample below). # # Given: Two DNA strings ss and tt (each of length at most 1 kbp). # Return: All locations of tt as a substring of ss. import re def findMotif(ss,tt): # motifs = [m.start()+1 for m in re.finditer(tt,ss, overlapped= True)] motifs = [] k = 0 while k < len(ss): k = ss.find(tt, k) if k == -1: return motifs else: motifs.append(k+1) k += 1 # change to k += len(sub) to not search overlapping results return motifs ss ='TTGCATAGGTTGCATAGGTGCATAGGGCATAGGGCATCGCATAGGAAGCATAGGGCATAGGACTACCTGCATAGGAGCATAGGATGAATGAGGTCTTGTGCATAGGCCGGGCATAGGGTGTGTCCGCGCATAGGGCATAGGGCATAGGACAACCCGCTCGCCGCATAGGCGCATAGGGCGCATAGGAGCATAGGGCATAGGAGGAAAGTGTCTAGCATAGGGACTAGTATGGGGCATAGGGCATAGGGCATAGGGGCATAGGTGTGCATAGGAGTAGCATAGGCGCATAGGGCTGTCGCATAGGGCATAGGCTGCATAGGTGGCATAGGGCTCTCTTAAATAAATAGCATAGGACTTATATTGGCATAGGAGCTTTTAAAGCATAGGGACGCATAGGTGCATAGGAGCATAGGGCATAGGTTTCCGCATAGGTTGACATGCATAGGGAGGGCATAGGTTTGCATAGGCCTTAGTGCATAGGGCATAGGGCGCATAGGGCATAGGGGCATAGGTGGAGGCATAGGACTGCATAGGGGCATAGGGCATAGGGCATAGGCACGGCATAGGAGCATAGGAAGCATAGGGCATAGGCGCATAGGCCATGCATAGGGCATAGGAACGCATAGGAAAGCATAGGGCATAGGCGTTAACGGGCATAGGCGCATAGGCTGCATAGGATCGCATAGGTGGAGAGCATAGGCGGCATAGGTTGCAGCATAGGAGGCATAGGGCATAGGCGCATAGGAGCCATCGCGCATAGGCTGTCACTTAGTTCGGGGCCGCATAGGGCATAGGCAGGCATAGGGGCATAGGCAGCGGGGATTGGCGGGCATAGGGGCGAGCATAGGGCATAGGTGTTAGCATAGGTGGCATAGGGTAGCATAGGACGCATAGGCGCATAGGCACAGCGATTGCATAGGTAGCATAGGGCATAGGGGGAGCAAACGCATAGGAAGCATAGGAATGCATAGG' tt = 'GCATAGGGC' print(findMotif(ss,tt))
ad59e63a88296bc747486c1f36d3d4b7186fc476
celsopa/theHuxley
/HUX - 2174.py
212
3.671875
4
m3Agua = float(input()) custoAgua = float(input()) totalAgua = m3Agua*1000*custoAgua print("{:.2f}".format(custoAgua)) print("{:.2f}".format(custoAgua*80/100)) print("{:.2f}".format((custoAgua*80/100)+custoAgua))
553588bbe3b900c718efc99eef21e2d9a48223a0
RumorsHackerSchool/PythonChallengesSolutions
/Guy/hackerrank.com/Arithmetic_Operators.py
516
4.0625
4
''' Task Read two integers from STDIN and print three lines where: The first line contains the sum of the two numbers. The second line contains the difference of the two numbers (first - second). The third line contains the product of the two numbers. Input Format The first line contains the first integer, . The second line contains the second integer, . ''' if __name__ == '__main__': a = int(raw_input()) b = int(raw_input()) print a + b if b > a: print b - a else: print a - b print a * b
9dd2ec87213039e919e8fba2994faf61db1e6a95
MayeshMohapatra/ImageSegmentation-UNet
/model.py
2,401
3.5
4
from tensorflow.keras.layers import ( Conv2D, BatchNormalization, Activation, MaxPool2D, Conv2DTranspose, Concatenate, Input, ) from tensorflow.keras.models import Model # implementing on unet architecture ##Simple Conv block with 2 3x3 conv layers def Convolution_block(input, num_filters): x = Conv2D(num_filters, 3, padding="same")(input) x = BatchNormalization()(x) x = Activation("relu")(x) x = Conv2D(num_filters, 3, padding="same")(x) x = BatchNormalization()(x) x = Activation("relu")(x) return x # Encoder block for downsampling """Contracting path consists of repeated application of 3x3 conv(unpadded), each followed by ReLU and a 2x2 max pooling operation with stride 2 for downsampling at each downsampling the number of feature channels is doubled.""" # x will be used as skip connection, used in decoder def encoder_block(input, num_filters): x = Convolution_block(input, num_filters) p = MaxPool2D((2, 2))(x) return x, p # Decoder block for upsampling, """Expansive path consisting of an upsampling of the feature map followed by a a 2x2 conv(up-conv) that halves the number of feature channels. concatenation with the cropped feature map from the contracting path and two 3x3 conv layers""" # skip_features comes from x from the encoder def decoder_block(input, skip_features, num_filters): x = Conv2DTranspose(num_filters, (2, 2), strides=2, padding="same")(input) x = Concatenate()([x, skip_features]) x = Convolution_block(x, num_filters) return x ## Constructing the unet architecture,according to the arxiv paper def build_unet(input_shape): inputs = Input(input_shape) ## Downsampling, left side of unet s1, p1 = encoder_block(inputs, 64) s2, p2 = encoder_block(p1, 128) s3, p3 = encoder_block(p2, 256) s4, p4 = encoder_block(p3, 512) ## Bridge connection layers b1 = Convolution_block(p4, 1024) ## Upsampling, right side of unet d1 = decoder_block(b1, s4, 512) d2 = decoder_block(d1, s3, 256) d3 = decoder_block(d2, s2, 128) d4 = decoder_block(d3, s1, 64) outputs = Conv2D(1, 1, padding="same", activation="sigmoid")(d4) model = Model(inputs, outputs, name="U-Net") return model if __name__ == "__main__": input_shape = (512, 512, 3) model = build_unet(input_shape) model.summary()
a477b207c81bbbff6e34a298ed55c6573dcd3698
issokov/BlackJackAndFeatures
/engine/card.py
612
3.796875
4
from enum import Enum, unique @unique class VALUE(Enum): TWO = 0 THREE = 1 FOUR = 2 FIVE = 3 SIX = 4 SEVEN = 5 EIGHT = 6 NINE = 7 TEN = 8 JACK = 9 QUEEN = 10 KING = 11 ACE = 12 @unique class SUIT(Enum): HEARTS = 0 DIAMONDS = 1 CLUBS = 2 SPADES = 3 class Card: def __init__(self, suit: SUIT, value: VALUE): self.suit = suit self.value = value def __str__(self): return f"{self.suit.name} {self.value.name}" def __eq__(self, other): return self.suit == other.suit and self.value == other.value
1b3eb41ec455b839cc6d521c61c36fe7956b02f7
bssrdf/pyleet
/F/FindCompoundWordsinList.py
1,353
4
4
''' Given a list of words, find words in that list that are made up of other words in the list. For example, if the list were ["race", "racecar", "car"], return ["racecar"]. ''' from collections import defaultdict class Node(defaultdict): def __init__(self): super().__init__(Node) self.terminal = False class Trie(object): def __init__(self, wl): self.root = Node() for w in wl: self.add_word(w) def __contains__(self, word): node = self.root for c in word: node = node.get(c) if node is None: return False return node.terminal def add_word(self, word): node = self.root for c in word: node = node[c] node.terminal = True def is_combination(self, word): node= self.root for i,c in enumerate(word): node = node.get(c) if not node: break if node.terminal and word[i+1:] in self: return True return False class Solution(object): def findCompoundWord(self, words): return [w for w in words if Trie(words).is_combination(w)] if __name__ == "__main__": print(Solution().findCompoundWord(["race", "racecar", "car", "after", "thought", "afterthought"]))
3c08ccdd1eb368e79d246636b75e85a9c574b3f2
Xu-Guo/GQQLeetCode
/Array/287_FindtheDuplicateNumber.py
797
3.609375
4
class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) - 1 mi, ma = 1, n while mi <= ma: mid = mi + (ma - mi) / 2 less, equal, high = 0, 0, 0 for num in nums: if num == mid: equal += 1 elif num >= mi and num < mid: less += 1 elif num <= ma and num > mid: high += 1 if equal > 1: return mid elif less > mid - mi: ma = mid - 1 else: mi = mid + 1 return -1 if __name__ == '__main__': s = Solution() print s.findDuplicate([3, 1, 4, 2, 4])
7df8995e594f8a1af2779d36d24fd2c55c988f11
NicolasOng/BlockchainSimulation
/message.py
412
3.5
4
class Message: def __init__(self, header, data): self.header = header self.data = data def __str__(self): return "HEADER:\n\t" + self.header + "\nDATA:\n\t" + self.data.__str__() def encode(self): ''' encodes the message to bytes. assumes that the message has a header of "Block", and data of a block, since that's the message being sent over the network. ''' return self.data.encode()
6f4545f820bbf901e75e9242f9ade0640bbf6722
ramugadde/Python-Practice
/PythonSessions/B_Python_BasicPractice/M_FunctionsTypes2.py
331
3.515625
4
print("********Function with return values**************") def returnValue(): print("Good morning") return 10 x= returnValue() print("Returned value:",x) print("********Function with default return values**************") def returnValue(): print("Good morning") x= returnValue() print("Returned value:",x)
708f8773376a026dbc5f90966276732634db6457
anyatran/school
/CG/SciPy/DateYChart_01.py
395
3.75
4
# -*- coding: utf-8 -*- import datetime from time import sleep start = datetime.datetime.now() sleep(5) #delay the python script for 5 seconds. stop = datetime.datetime.now() elapsed = stop - start if elapsed > datetime.timedelta(minutes=4): print "Slept for greater than 4 minutes" if elapsed > datetime.timedelta(seconds=4): print "Slept for greater than 4 seconds"
cb01794ce752e44f7f88c56384b59bd736bc5759
aaronbushell1984/Python
/Day 3/Functions.py
1,974
4.40625
4
# ***LESSON*** # Rewrite this function into reusable functions number = int(input("Please enter a number:")) if number % 3 == 0 and number % 5 == 0: print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) # Rewrite to def is_fizz(number): """returns if the number is divisible by 3""" return number % 3 == 0 def is_buzz(number): """returns if the number is divisible by 5""" return number % 5 == 0 def is_fizz_buzz(number): """returns if the number is divisible by 3 and 5""" return is_fizz and is_buzz def apply_fizz_buzz_rules(number): """checks divisible by 3, 5 or both and returns Fizz and Buzz accordingl""" if is_fizz_buzz(number): return "FizzBuzz" elif is_fizz(number): return "Fizz" elif is_buzz(number): return "Buzz" else: return f"{number} is not FizzBuzz" # ***SLIDES*** # Definition of a function consists of header and body def square(x): """Returns the square of x.""" return x * x # • Docstring contains information about what the function does; to display, enter: help(square) # NB FUNCTIONS MUST BE DECLARED BEFORE USED # A Boolean function usually tests its argument for the presence or absence of some property # • Returns True if property is present; False otherwise # • Example: def odd(x): """ Returns True if x is odd or False otherwise.""" if x % 2 == 1: return True else: return False odd(5) # True odd(6) # False # main serves as the entry point for a script """Illustrates the definition of a main function.""" def main( ): """The main function for this script.""" number = float(input("Enter a number: ")) result = square(number) print("The square of", number, "is", result) def square(x): """Returns the square of x""" return x * x # The entry point for program execution main() # There is a new way of doing this...
7daede4fae945a0287a320c3168dad557f3bc408
gotha331/python-learning
/10-异常/04-try_expect_finally结构.py
696
3.5
4
# Files: # Author:jiang liu # Date :2020/3/26 19:21 # Tool :PyCharm # 无论是否发生异常,都会执行finally部分 # try: # a = input("请输入一个被除数:") # b = input("请输入一个除数:") # c = float(a) / float(b) # except BaseException as e: # print(e) # else: # print("除的结果是:", c) # finally: # print("我是finally中的语句,无论发生异常与否,都执行!") # # print("程序结束!") # 示例 try: f = open("d:/a.txt", "r") content = f.readline() print(content) except BaseException as e: print(e) print("文件未找到") finally: print("run in finally,关闭资源") # f.close()
47d94611fb97332e902073ba75296f21e455707d
NanZhang715/AlgorithmCHUNZHAO
/Week_07/findKthLargest.py
1,589
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 215. 数组中的第K个最大元素 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/ """ from typing import List class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: """ 思路: 快排 """ k = len(nums) - k left, right = 0, len(nums) - 1 while True: pivot = self.partition(nums, left, right) print(pivot, nums) if pivot == k: return nums[pivot] elif pivot > k: right = pivot - 1 else: left = pivot + 1 def partition(self, nums, beg, end): pivot_index = beg pivot = nums[beg] left, right = pivot_index + 1, end while True: while left <= right and nums[left] < pivot: left += 1 while left <= right and nums[right] >= pivot: right -= 1 if left > right: break else: nums[left], nums[right] = nums[right], nums[left] nums[pivot_index], nums[right] = nums[right], nums[pivot_index] return right if __name__ == '__main__': nums, k = [3, 2, 1, 5, 6, 4], 2 rst = Solution().findKthLargest(nums, k) print("result is", rst)
6141c4dbe8d061c7a2807c361434722657f0148a
hkelder/Python
/Lesson2/palindrome.py
298
4.4375
4
# Ask the user for a string and print out whether this string is a palindrome or not. def palindrome(): userString = input("Enter something:").lower() if userString[::-1] == userString: print("It's a palindrome") else: print("This is a normal string.") palindrome()
9b9d577e45bcb4da3fd3e3e07d647b8b3bdefc11
vensder/py_hw_2016
/hw8_A_shapes.py
2,875
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # 2016_python.py # # Student Dmitry Makarov <vensder@gmail.com> import math class Point: ''' Базовый класс "точка", которая имеет две координаты ''' def __init__(self, x, y): self.x = x self.y = y class Shape: ''' Базовый класс "фигура" ''' def __init__(self, width, color): self.width = width self.color = color class Triangle(Shape): ''' Класс "треугольник" (наследник фигуры) ''' def __init__(self, width, color, p1, p2, p3): super().__init__(width, color) self.p1 = p1 self.p2 = p2 self.p3 = p3 class Rectangle(Shape): ''' Класс "прямоугольник" (наследник фигуры) ''' def __init__(self, width, color, p1, p2, p3, p4): super().__init__(width, color) self.p1 = p1 self.p2 = p2 self.p3 = p3 self.p4 = p4 class Circle(Shape): ''' Класс круг (дополнительно считаем площадь, на всякий случай, и проверяем, что радиус больше нуля) ''' def __init__(self, width, color, p0, r): super().__init__(width, color) self.p0 = p0 self.r = r def area(self): return math.pi * self.r ** 2 @property def r(self): return self._r @r.setter def r(self,r): if r < 0: raise ValueError('Radius should be nonnegative') self._r = r # Let's create the object Triangle t1 = Triangle(1,'blue', Point(0,0), Point(1,1), Point(1,0)) # Let's create the object Rectangle r1 = Rectangle(1,'red', Point(0,0), Point(0,1), Point(2,1), Point(2,0)) # Let's create the Circle: c1 = Circle(2, 'green', Point(1,1), 1) # Let's print width line, color and coord of our first triangle print('Triangle:') print('Width: {}, color: {}'.format(t1.width, t1.color)) print('First point coordinate: ({},{})'.format(t1.p1.x, t1.p1.y)) print('Second point coordinate:({},{})'.format(t1.p2.x, t1.p2.y)) print('Next point coordinate:({},{})'.format(t1.p3.x, t1.p3.y)) print('\n') print('Rectangle:') # Let's print width line, color and coord of our Rectangle print('Width: {}, color: {}'.format(r1.width, r1.color)) print('First point coordinate: ({},{})'.format(r1.p1.x, r1.p1.y)) print('Second point coordinate:({},{})'.format(r1.p2.x, r1.p2.y)) print('Next point coordinate:({},{})'.format(r1.p3.x, r1.p3.y)) print('Next point coordinate:({},{})'.format(r1.p4.x, r1.p4.y)) print('\n') print('Circle') print('Width: {}, color: {}'.format(c1.width, c1.color)) print('Center: ({},{}), radius: {}'.format(c1.p0.x, c1.p0.y, c1.r)) print('Area of the Circle:', c1.area())
b86eeb22b303e017b5c6013f335f9e3ab3975674
illuminous/pythonScripts
/outfileParse_stageII.py
2,389
3.515625
4
import profile def fidYear(inputfile): perimeterfile = {} global perimeterfile poly = open(inputfile, 'r') FID = -1 #start counter at -1 because of header """analyse the polygon perimeter file and store the FID and associated year in a dictionary""" for polyline in poly.readlines(): polysplit = polyline.split(',') year = polysplit[7] perimeterfile[FID]=year FID+=1 print '###############' poly.close() def overlap(inputfile, outfile): """open the biogeography tools outfile and store the results in a dictionary where the key is the FID and the values are the overlapping polygons stored as an FID""" intersectfile = {} global intersectfile f = open(inputfile, 'r') for line in f.readlines(): lineclean = line.rstrip('\n') splitter =lineclean.split(':') polyID = splitter[0] splitter2 = splitter[1:] for item in splitter2: newitem = item.split(',') try: intersectfile[int(polyID)] = newitem except:pass print '###############' f.close() """start iterating through the itnersectfile dictionary and swap out FIDs for year values""" FIDYEAR={} for k, v in intersectfile.iteritems(): # for the polygon FID in the intersectfile try: if perimeterfile.has_key(int(k)): apple = [perimeterfile.get(int(k))] orangelist = [] for item in v: orange = perimeterfile.get(int(item)) orangelist.append(str(orange)) FIDYEAR[perimeterfile.get(int(k))]=orangelist else: pass except: pass """if the year intersect with it's year, write it out""" results = open(outfile, 'w') for k, v in FIDYEAR.iteritems(): if k in v: results.write(k) results.write('\n') else: pass results.close() def main(): fidYear('f:/landcover/analysis5/NR_ID_001_0_perimeter.txt') overlap('f:/landcover/analysis5/NR_ID_001_0_out.txt', 'f:/landcover/analysis5/NR_ID_001_0_YearResults.csv') if __name__ == "__main__": profile.run('main()')
8fa8dd213dff9c4aa6ff0fc132d3a127fc3492a6
arv1983/Hackaton
/hackathon.py
725
3.640625
4
hackathon_1 = ["Team Kenzie", "Team Ateliware", "Team VHSYS", "Team Mirum"] hackathon_2 = ["Team Ateliware", "Team Kenzie", "Team VHSYS", "Team Mirum"] hackathon_3 = ["Team Mirum", "Team Ateliware","Team VHSYS", "Team Kenzie"] def get_score(team_name, teams): return 'O ' + team_name + 'ficou classificada em ' + str(teams.index(team_name) + 1) + ' lugar' get_score_1 = get_score("Team Ateliware", hackathon_1) print(get_score_1) # // A Team Ateliware ficou classificada em 2 get_score_2 = get_score("Team Kenzie", hackathon_1) print(get_score_2) # // A Team Kenzie ficou classificada em 1 get_score_3 = get_score("Team Mirum", hackathon_3) print(get_score_3) # // A Team Mirum ficou classificada em 1 # ok # ok # ok
5360ad601f6d0b2be61fc069046767305f3f052d
kamilhabrych/python-semestr5-lista7
/zad7_7.py
761
3.609375
4
import random def sortuj(l): l.sort() print(l) lista = [] for x in range(100): dlugosc = random.randint(3,8) slowo = '' for y in range(dlugosc): losowana_litera = random.randint(97,122) litera = chr(losowana_litera) slowo += litera lista.append(slowo) print(lista) sortuj(lista) print() lista2 = [] samogloski = ['a','i','e','u','o','y'] for i in range(100): dlugosc = random.randint(3,7) slowo = random.choice(samogloski) for j in range(dlugosc): losowana_litera = random.randint(97,122) litera = chr(losowana_litera) if litera not in slowo: slowo += litera lista2.append(slowo) sortuj(lista2)
cfb0bda884fa22246986fb6dd3aacde006644386
summercake/Python_Jose
/02.Strings.py
444
3.90625
4
print('Hello') print('This is also a string') print("I'm a string") print('I\'m a string') print("I\'m a string") print('Here is a new line \n and here is the second line') print("Here is a new line \t and here is the second line") print(len('Hello world')) s = "Hello World" print(s) print(s[0]) print(s[2]) print(s[2:]) print(s[:2]) print(s[:4]) print(s[4:]) print(s[:-1]) print(s[::-1]) letter = 'zz' b = letter * 10 print(b) print(type(b))
bcda1cc42939b066adeb47a7993cc6e7ad7a88c7
vivekpabani/powerball-game
/powerball/main.py
747
3.671875
4
#!/usr/bin/env python """ The main script to run the powerball game simulation. """ __author__ = "vivek" from .game import Game from .player import Player def main(): # The game simulation is done with following steps: # # 1. Create a game instance with no players. # 2. Invoke the begin method, which asks for player data and # favorite numbers until stopped. # 3. Once players data is entered, invoke the method to generate # winning number. # 4. Display players data and winning numbers. print('\n') game = Game() game.begin() game.generate_winning_numbers() game.display_players() game.display_winning_numbers() print('\n') if __name__ == "__main__": main()
e321326d2f73ed6b6c97cb8278628c3ec5f5cbe9
manamster/GameOfPig
/computerPlayer.py
1,988
3.953125
4
import time class Computer(object): def __init__(self, name, score = 0): """Sets name, total, and round points""" self.name = str(name) self.totalPoints = score self.roundPoints = score self.probability = 1 print("This computer is hard mode be careful!\n") def getTotal(self): """Returns the total points""" return(self.totalPoints) def getRound(self): """Returns the round points""" return(self.roundPoints) def getName(self): """Returns the name assigned to the class at creation""" return(self.name) def updateScore(self, change): """Adds to the round score""" self.roundPoints += change def resetRound(self): """Resets the round score if the got a 1 on either die""" self.roundPoints = 0 def resetTotal(self): """Resets the total score if they were super greedy and rolled snake eyes""" self.totalPoints = 0 def updateTotal(self): """Updates the total points by adding the round points to previous total points""" self.totalPoints += self.roundPoints #self.roundPoints = 0 def resetProb(self): """This resets the probablility like it is the first roll""" self.probability = 0.695 def calcProb(self): """This multiplies the probability by the probability of a single roll not having two 1's""" self.probability *= 0.695 def takeChance(self): """This is a function that calls the other functions and decides wether to run the roll depending on if it has to many points that round or if it gets to low of a probability""" self.calcProb() print("Calculating ...\n") time.sleep(0.5) if self.roundPoints >= 20: flag = "n" elif self.probability < 0.3: flag = "n" else: flag = "y" return(flag) def __str__(self): """This returns the name, round points, and total points of the class""" return(self.name + " has " + str(self.roundPoints) + " this round and " + str(self.totalPoints) + " in total.")
f66b4a1fbbc2006b71197db847f791b1616d20c2
lightopen/queue-in-python
/queue.py
1,580
3.828125
4
class Queue(object): """ 循环队列 默认队列容量为4,可在实例化时自定义 """ def __init__(self, capacity=4): self.capacity = capacity self.index = -1 self.head = 0 self.tail = 0 self.queue = [] self.length = 0 # 计数,返回长度 def count(self): return self.length # 判满 def full(self): if self.count() == self.capacity: return True return False # 判空 def empty(self): if self.count() == 0: return True return False # 清除队列 def clear(self): self.head = 0 self.tail = 0 self.queue = [] self.length = 0 # 插入队尾 def put_in(self, value): if self.full(): return False self.queue.append(value) self.tail = (self.tail + 1) % self.capacity self.length += 1 return True # 冒出队头 def get_out(self): if self.empty(): return False frist = self.queue[0] del(self.queue[0]) self.head = (self.head + 1) % self.capacity self.length -= 1 return frist # 实现迭代 def __iter__(self): self.index = -1 return self def __next__(self): self.index += 1 if self.index == self.length: raise StopIteration return self.queue[self.index]
0b52c35ba9484f202044ef6271d4241496d5437f
KiaHKR/uFood
/src/bin/validation.py
430
3.65625
4
"""Runs a script to check that the user's OS is supported.""" import platform suppOS = ["Windows"] def checkOS(os): """Check that OS is Supported.""" if os not in suppOS: msg1 = "Your operating system ({}) is not supported in this build. " msg2 = "Compatible operating system(s): {}" x = ", ".join(suppOS) raise SystemExit(msg1.format(os) + msg2.format(x)) checkOS(platform.system())
216a594c01feef5a940078794c4b0134011d8d3c
damngamerz/python-practice
/practice/while.py
102
3.78125
4
count = 0 while count<10: print("count:",count) count+=1 print("Good bye!")
6c89278e1854e34e4a86d40ce7980932ccd393bd
yg-kim-korean/This_is_CodingTest
/Sort/UptoDown.py
348
3.84375
4
n = int(input('몇개 넣을래? : ')) array = [] for i in range(n): array.append(int(input(str(i+1)+'번째 숫자 : '))) # for i in range(1,len(array)): # for j in range(i,0,-1): # if array[j] > array[j-1]: # array[j],array[j-1] = array[j-1],array[j] array.sort(reverse=True) for i in array: print(i , end = ' ')
5f923f72a76337142824ad81d034e1fa9ca3cd54
itineraries/scheduler-and-mapper
/pickle_nyu_unwritten_times.py
3,244
3.609375
4
#!/usr/bin/env python3 ''' This module is responsible for telling pickle_nyu how long it takes the bus to get from one place to another. Normally, the schedule has this information. However, for some reason, NYU decided not to include the information for some stops. That's why it has to be provided by this module. The information is stored in "Driving Time Overrides.csv". When this module does not know the driving time from one stop to another, those two stops are written to this file with a question mark for the time. It is up to you to put the correct time in. ''' import atexit, csv, multiprocessing, os.path, sys from common import file_in_this_dir UNWRITTEN_TIMES_CSV = file_in_this_dir("Driving Time Overrides.csv") linit = multiprocessing.Lock() unwritten_times = None def save(): ''' This function saves the driving times back to UNWRITTEN_TIMES_CSV. There is no need to call this function from outside the module; it is automatically called when the module is exited. This function is not thread-safe. ''' global unwritten_times if unwritten_times is not None: unwritten_times.pop(("", ""), 0) with open(UNWRITTEN_TIMES_CSV, "w", newline="", encoding="UTF-8") as f: writer = csv.writer(f) writer.writerow(("From", "To", "Minutes")) for (f, t), minutes in unwritten_times.items(): writer.writerow((f, t, minutes)) def read(): ''' This function reads the driving times from UNWRITTEN_TIMES_CSV and populates this module's internal data. There is no return value. There is no need to call this function from outside the module because get_minutes calls this function automatically if it has not been called already. This function is not thread-safe. ''' global unwritten_times unwritten_times = {("", ""): 0} try: with open(UNWRITTEN_TIMES_CSV, "r", newline="", encoding="UTF-8") as f: for line in csv.DictReader(f): try: minutes = int(line["Minutes"]) except ValueError: pass else: unwritten_times[(line["From"], line["To"])] = minutes except FileNotFoundError: pass except KeyError as e: print( "The", repr(e.args[0]), "column is missing the driving times.", "Fix it here:", repr(UNWRITTEN_TIMES_CSV) ) return atexit.register(save) def get_minutes(last_header, curr_header): global unwritten_times # If the driving times have not been loaded, load them. with linit: if unwritten_times is None: read() # Get the time from the dictionary. try: minutes = unwritten_times[(last_header, curr_header)] except KeyError: print( "We need the driving time from ", repr(last_header), " to ", repr(curr_header), ". Please edit ", repr(UNWRITTEN_TIMES_CSV), " to include this information.", sep="", file=sys.stderr ) unwritten_times[(last_header, curr_header)] = "?" else: if minutes != "?": return minutes return None
cafaf42bed178c4f871df70083121a839ecba7e7
alexandre146/avaliar
/media/codigos/294/294sol64.py
87
3.734375
4
a = int(input()) b = int(input()) consumo = (a/b) print("%.3f"%(consumo) +' km/l')
9f5b28132b1fd01c099491baee29e09f34abac35
luizfelipe1914/Listas-Python
/Lista 02/Questao5.py
340
4.125
4
#!/usr/bin/env python3 #-*- encoding: UTF-8 -*- def main(): try: number = int(input("Informe um número: ")) except: print("Apenas valores numéricos são aceitos!") if(number % 2 == 0): print(f"{number} é par.") else: print(f"{number} é ímpar.") if(__name__ == "__main__"): main()
abde31fef9613d0d3adefcd09df8672ac71b8226
eduardoanj/cursopyton
/Nova pasta (2)/python/ex 42.py
184
3.53125
4
#Escreva um algoritmo para imprimir os 10 primeiros # números inteiros maiores que 100. #enquanto eu sei quantos são, utilize o for for i in range(100, 110): print (i + 1)
2f49066b97332020524b72cc09b490c8a54b0e60
pjhu/effective-script
/lintcode/lintcode/search_range_in_binary_search_tree.py
1,277
3.59375
4
# -*- utf-8 -*- """ eleventh http://www.lintcode.com/en/problem/search-range-in-binary-search-tree/ """ import profile import queue # Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class SearchRangeInBinarySearchTree(object): """ @param root: The root of the binary search tree. @param k1 and k2: range k1 to k2. @return: Return all keys that k1<=key<=k2 in ascending order. """ def search_range_in_binary_search_tree(self, root, k1, k2): if not root: return [] q = queue.Queue() q.put(root) l = [] if k1 <= root.val <= k2: l.append(root.val) while not q.empty(): node = q.get() if node.left: q.put(node.left) if k1 <= node.left.val <= k2: l.append(node.left.val) if node.right: q.put(node.right) if k1 <= node.right.val <= k2: l.append(node.right.val) return sorted(l) if __name__ == '__name__': obj = SearchRangeInBinarySearchTree() root = TreeNode(1) print(profile.run("obj.search_range_in_binary_search_tree(root, 1, 10)"))
062235d5e7cfe20b0113efbc3c37eafe7a5eacb2
rahul118bbsr/Indus-Script-Analysis
/ConditionalProbability.py
1,075
3.671875
4
import operator def conditionalProbability(fileDir, given): output = {} given = given.strip().split("-") for line in fileDir: line = line.strip().split('-') for i in range (len(line)): startIndex = i stopIndex = i + len(given) if(stopIndex < len(line) and line[startIndex : stopIndex] == given): nextWord = line[stopIndex] output.setdefault(nextWord, 0) output[nextWord] += 1 return output fileDir = open("/Users/aleesha/Documents/FIT/semester 2/AI/Assignment/nGramProject/corpus.txt") condition = input("Enter the condition: ") output = conditionalProbability(fileDir, condition) sorted_x = sorted(output.items(), key=operator.itemgetter(1), reverse=True) count = 0; fileDir = open("/Users/aleesha/Documents/FIT/semester 2/AI/Assignment/nGramProject/corpus.txt") for line in fileDir: line = line.strip().split('-') if condition in line: count += 1 #print(sorted_x) for x in sorted_x: print(x, "Conditional Probability: \t", x[1]/count)
ed0db4ed28dd8c94378c5e14f384a7aab03b2027
juhosalmi/study_planner
/src/course.py
874
3.578125
4
''' Created on 22.3.2013 @author: jtsalmi ''' from period import Period class Course(object): def __init__(self, name, ects, period, description, prerequisites): self.name = name # Name of the course self.ects = int(ects) # Number of credits self.period = period # The periods in which the course will be held self.description = description # Course description self.prerequisites = prerequisites # WHich courses should the student have completed before attending this course def courseLength(self): return self.period.length() def __str__(self): string = self.name + ': ' + self.ects + 'op, ' + self.period.__str__() + ', ' + self.description + ', Esitiedot: ' for each in self.prerequisites: string = string + each + ', ' return string
4a732146e083740df4e5ef38766ce89e96451d5c
giancarlo-garbagnati/RosalindSolns
/08-DivideAndConquer/01_dc_bins.py
2,514
3.765625
4
""" http://rosalind.info/problems/bins/ Binary search is the ultimate divide-and-conquer algorithm. To find a key k in a large file containing keys A[1..n] in sorted order, we first compare k with A[n/2], and depending on the result we recurse either on the first half of the file, A[1..n/2], or on the second half, A[n/2+1..n]. The recurrence now is T(n)=T(n/2)+O(1). Plugging into the master theorem (with a=1,b=2,d=0) we get the familiar solution: a running time of just O(logn). Source: Algorithms by Dasgupta, Papadimitriou, Vazirani. McGraw-Hill. 2006.[http://rosalind.info/glossary/algo-algorithms-by-dasgupta-papadimitriou-vazirani-mcgraw-hill-2006/] Problem The problem is to find a given set of keys in a given array. Given: Two positive integers n≤105 and m≤105, a sorted array A[1..n] of integers from −105 to 105 and a list of m integers −105≤k1,k2,…,km≤105. Return: For each ki, output an index 1≤j≤n s.t. A[j]=ki or "-1" if there is no such index. Sample Dataset 5 6 10 20 30 40 50 40 10 35 15 40 20 Sample Output 4 1 -1 -1 4 2 """ # Building file name probnum = 'bins' filename = '../data/rosalind_' + probnum + '.txt' #filename = '../data/rosalind_' + probnum + '_sample.txt' data_input = open(filename, 'r') in_file = [x.replace('\n','') for x in data_input.readlines()] n = int(in_file[0]) m = int(in_file[1]) n_sorted_list = [int(x) for x in in_file[2].split()] m_queries = [int(x) for x in in_file[3].split()] from math import ceil # find the query using binary search def bin_search(n_sorted, query, left=0, right=None): if right is None: right = len(n_sorted)-1 # sanity check if right >= left: #middle = int(left + (right-left)/2) middle = ceil(left + (right-left)/2) if n_sorted[middle] == query: return middle elif n_sorted[middle] > query: #look further down return bin_search(n_sorted, query, left, middle-1) else: # n_sorted[middle] < query: #look further up return bin_search(n_sorted, query, middle+1, right) else: # not found return -1 #for m_query in n_sorted_list: for m_query in m_queries: index = bin_search(n_sorted_list, m_query) if index >= 0: index += 1 print(index, end = ' ') print() # Simply copy pasting the answer into Rosalind's text box didn't seem to work for me. Instead, # moving this script output to a file 'python 01_dc_bins.py > output.txt' and then uploading # through the file upload worked.
6f9f34df9c6ddf07c77edc2901640997fffbdb0e
Joshua0128/JudgeGirl-Coding-GYM
/一轉示範/自製資料結構 python 示範/main.py
349
3.609375
4
from MyStack import * from Student import Student mStack = MyStack() try: for i in range(9,-1,-1): mStack.push(Student(i)) for element in mStack: print (str(element), end=" ") print() while(True): print(str(mStack.pop()), end=" ") except NoElementException as err: print ("The Stack is empty.")
101828f41cdef50e8b423367d217c7a18bd144d9
AntoData/CoronavirusWebScraper
/api/MapGenerator.py
14,253
3.75
4
# Created on 21 jul. 2019 # @author: ingov # We use folium to generate the maps import folium # We use LinearColormap to create scales for pair of colours-values from branca.colormap import LinearColormap # We use branca to create the legend for our map import branca # We import this module to manage data frames import pandas def color_scale(color1: str, color2: str, value: float, min_value: float, max_value: float) -> LinearColormap: """ :param color1: This parameter is a string that contains a hexadecimal color (format #XXXXXX) or a valid color (for instance red, orange, yellow, blue) that establishes the first color in that range of values, the color that will be associated with minValue :param color2: This parameter is a string that contains a hexadecimal color (format #XXXXXX) or a valid color (for instance red, orange, yellow, blue) that establishes the second color in that range of values the color that will be associated with maxValue :param value: This parameter is a number, the value we have to paint with a color between color1 and color2 and that has to be between minValue and maxValue :param min_value: This parameter is a number, the lowest value possible within this range we are defining :param max_value: This parameter is a number, the highest value possible within this range we are defining :return: LinearColorMap object """ return LinearColormap([color1, color2], vmin=min_value, vmax=max_value)(value) def get_color(feature: dict, data_map: dict, colours: dict, map_property: str): """ This function gets the object feature that represents the property feature in the json, a dictionary with the data_coronavirus (we use a data_frame and turn it into a dictionary), and a map with the ranges and colours where the key is the value and the value is the color associated to that value :param feature: Contains the property feature in the json of our map :param data_map: A dictionary with the data_coronavirus (we use a data_frame and turn it into a dictionary) :param colours: Dictionary with the ranges and colours where the key is the value and the value is the color associated to that value. It is important to notice that we can mix string values that will be static values (no range for them) and ranges. We will have to put all string/static values first in the map and them the number values that will be paired to make ranges. Also important to notice, the keys are the values and the values are the color a string with the hexadecimal color (#XXXXXX) or a valid color name :param map_property: Property in feature we will use to identify the zones defined in the json :return: the colour for the region we are iterating over, if it was a string/static value we will just return the colour in the map colours. But if it is a float we will evaluate inside which range it is and use the previously defined funcion color_scale to get the right color """ # We get the keys of the dict colours which are the range of values to consider to # colour this map, we will use it to compare the values in the dictionary with the values # for each row in the dictionary dataMap colours_key = list(colours.keys()) # We get the value of the associated to the region of our json that is going to be painted # in our data_coronavirus frame (well, the dictionary that we got from our data_frame), in this case # the property we use in the json (mapProperty) to get the value has to be a child of # properties. Also, our key values have to coincide with the property in the json that is # represented by mapProperty print(feature['properties'][map_property]) value = data_map.get(feature['properties'][map_property]) try: number = int(value) value = number except TypeError: try: number = float(value) value = number except TypeError: pass # If value is not None, it means it is in our dataMap so we have to color that area if value is not None: # If value is not int or float, it means is a static value if not isinstance(value, (int, float)): i = 0 # We iterate through the different values that are associated with colors while i < len(colours_key) and value is not None: # If our value is equal to the value associated with a certain color, we return # that color if colours_key[i] == value: return colours.get(colours_key[i]) i = i + 1 else: # We iterate through the values that define the ranges of colours that we got from # our dictionary of colors (key:value, value:colour) i = 1 while i < len(colours_key) and value is not None: # if our current value is in that range, we use the function color_scale # that we defined previously to get the corresponding shade of the colour # for that value if isinstance(colours_key[i - 1], (int, float)) and isinstance(colours_key[i], (int, float)): lower_value = float(colours_key[i - 1]) upper_value = float(colours_key[i]) num_value = float(value) if lower_value <= num_value <= upper_value: return color_scale(colours.get(lower_value), colours.get(upper_value), num_value, lower_value, upper_value) i = i + 1 def build_map(v_map: folium.Map, json_data: str, data_map: dict, colours: dict, v_caption: str, v_caption2: str, map_property: str) -> folium.Map: """ This function is the one that builds the map in v_map :param v_map: Folium map object we will use as the base to build the regions and paint them :param json_data: Route to the json we will use to divide our map into regions and to paint them :param data_map: A dictionary with the data_coronavirus (we use a data_frame and turn it into a dictionary) :param colours: Dictionary with the ranges and colours where the key is the value and the value is the color associated to that value. It is important to notice that we can mix string values that will be static values (no range for them) and ranges. We will have to put all string/static values first in the map and them the number values that will be paired to make ranges. Also important to notice, the keys are the values and the values are the color a string with the hexadecimal color (#XXXXXX) or a valid color name :param v_caption: Text we will put in the legend for the linear colours in the map :param v_caption2: Text we will put in the legend for the static colours in the map :param map_property: Property in feature we will use to identify the zones defined in the json :return: the map divided in regions, with the regions painted and coloured according to the values we indicated in the dictionary dataMap """ # We color the map in v_map using the feature GeoJson # and add it to the map folium.GeoJson( data=json_data, style_function=lambda feature: { 'fillColor': get_color(feature, data_map, colours, map_property), 'fillOpacity': 0.7, 'color': None, 'weight': 1, } ).add_to(v_map) # We create a legend for the colours which we have painted our map with colours_keys = list(colours.keys()) # coloursValues = list(colours.values()) linear_legend_keys = [] linear_legend_values = [] nonlinear_legend_keys = [] nonlinear_legend_values = [] num_value = True for v_colour in colours_keys: if isinstance(v_colour, (int, float)): linear_legend_values.append(colours[v_colour]) linear_legend_keys.append(v_colour) else: nonlinear_legend_keys.append(v_colour) nonlinear_legend_values.append(colours[v_colour]) num_value = False # We create a colormap object to be used as legend if len(linear_legend_keys) > 1 and len(linear_legend_values) > 1: colormap = branca.colormap.LinearColormap(linear_legend_values) colormap = colormap.to_step(index=linear_legend_keys) colormap.caption = v_caption # We add the colormap to our map colormap.add_to(v_map) # We this value corresponds to an static value, we will add it to the legend for static values if not num_value: html_legend = """ <div style='position: fixed;bottom:50px;left:50px;border:2px solid grey;z-index:9999; font-size:14px'> &nbsp; """ + v_caption2 for key in nonlinear_legend_keys: html_legend += '<br> &nbsp; ' + key + ' &nbsp;' html_legend += '<svg width="40" height="11">' color = colours[key].replace(' ', "") rgb_color = list(int(color[i:i + 2], 16) for i in (1, 3, 5)) html_legend += ' <rect width="40" height="11" style="fill:rgb({0},{1},{2});stroke-width:3;stroke:' \ 'rgb(0,0,0)" />'.format(rgb_color[0], rgb_color[1], rgb_color[2]) html_legend += '</svg>' html_legend += """ </div> """ v_map.get_root().html.add_child(folium.Element(html_legend)) return v_map def put_markers(v_map: folium.map, v_data: pandas.DataFrame, col_lat: str, col_lon: str, col_popup: str, marker_colour: str) -> folium.Map: """ :param v_map: Folium map object we will use as the base to build the regions and paint them :param v_data: A data_frame with the data_coronavirus :param col_lat: Name of the column in the data_frame where the latitude for the point where we want to display the marker is saved :param col_lon: Name of the column in the data_frame where the longitude for the point where we want to display the marker is saved :param col_popup: Name of the column in the data_frame where the message for the popup for that marker is saved :param marker_colour: Colour for the marker :return: Our map v_map with the markers added """ # we go through the data_frame for i in range(0, v_data.shape[0]): # And create and add a marker for every row folium.Marker(location=[v_data.loc[i][col_lat], v_data.loc[i][col_lon]], popup="<b>{0}</b>".format(v_data.loc[i][col_popup]), icon=folium.Icon(color=marker_colour, size=1)).add_to(v_map) return v_map def put_generic_markers(v_map, v_data, func_html, col_lat, col_lon, marker_colour): """ :param v_map: Folium map object we will use as the base to build the regions and paint them :param v_data: A data_frame with the data_coronavirus :param func_html: This is a function that will provide the HTML code for the popup for that every marker :param col_lat: Name of the column in the data_frame where the latitude for the point where we want to display the marker is saved :param col_lon: Name of the column in the data_frame where the longitude for the point where we want to display the marker is saved :param marker_colour: Colour for the marker :return: Our map v_map with the markers added """ # we go through the data_frame for i in range(0, v_data.shape[0]): # And create and add a marker for every row folium.Marker(location=[v_data.loc[i][col_lat], v_data.loc[i][col_lon]], popup=func_html(v_data.loc[i]), icon=folium.Icon(color=marker_colour, size=1)).add_to(v_map) return v_map def put_circles_in_map(v_map, data_frame, popup_field, latitude_field, longitude_field, value_field, proportion, color='crimson', fill_color=None): """ This function draws circles with a proportion related to the value of a field in a data_frame :param v_map: Map where we want to draw the circles :param data_frame: data_frame where we have the data_coronavirus we will use as value for the radius of these circles (we will multiply by proportion to get the radius) :param popup_field: Field in our data_frame we will use as information to display in the pop-up that is opened when we click in one of these circles we are drawing :param latitude_field: Field in our data_frame where we store the latitude of the point where we want to display a circle for a particular row :param longitude_field: Field in our data_frame where we store the longitude of the point where we want to display a circle for a particular row :param value_field: Field with the data_coronavirus we will use to get the radius of our circle. We will multiply this by proportion :param proportion: Proportion of the size we want our circles to have in relation to our values :param color: Color for the border of the circle. By default 'crimson' :param fill_color: Color of the interior of the circle. By default, None (so it won't be filed) :return Our map v_map with the circles added """ # For each row in the data_frame we paint a circle using the columns we set up before # for that particular eow for i in range(0, len(data_frame)): if fill_color is None: v_map.add_child(folium.Circle( location=(data_frame.iloc[i][latitude_field], data_frame.iloc[i][longitude_field]), popup=data_frame.iloc[i][popup_field], radius=int(data_frame.iloc[i][value_field] * proportion), color=color, fill=False)) else: v_map.add_child(folium.Circle( location=(data_frame.iloc[i][latitude_field], data_frame.iloc[i][longitude_field]), popup=data_frame.iloc[i][popup_field], radius=int(data_frame.iloc[i][value_field] * proportion), color=color, fill=True, fill_color=fill_color)) # We return our map with the circle return v_map
d730afaac0970063547e66afa1d8721a43ee9610
jiaruipeng1994/jLeetCode
/l115_Distinct-Subsequences_DP-Matrix_Space-optimization_暴力递归-动态规划.py
5,286
3.8125
4
#!/usr/bin/python3 # coding: utf-8 ################################################################## ## Description # Given a string S and a string T, count the number of distinct subsequences of S which equals T. # A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters # without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). # Here is an example: # S = "rabbbit", T = "rabbit" # Return 3. ################################################################## ## Solution # The idea is the following: # we will build an array mem where mem[i+1][j+1] means that S[0..j] contains T[0..i] that many times as distinct subsequences. # Therefor the result will be mem[T.length()][S.length()]. # we can build this array rows-by-rows: # the first row must be filled with 1. That's because the empty string is a subsequence of any string but only 1 time. # So mem[0][j] = 1 for every j. So with this we not only make our lives easier, but we also return correct value if T is an empty string. # the first column of every rows except the first must be 0. This is because an empty string cannot contain a non-empty string as a substring # -- the very first item of the array: mem[0][0] = 1, because an empty string contains the empty string 1 time. # So the matrix looks like this: # S 0123....j # T +----------+ # |1111111111| # 0 |0 | # 1 |0 | # 2 |0 | # . |0 | # . |0 | # i |0 | # From here we can easily fill the whole grid: for each (x, y), we check if S[x] == T[y] we add the previous item and the previous item # in the previous row, otherwise we copy the previous item in the same row. The reason is simple: # 左边和左上角相加 # if the current character in S doesn't equal to current character T, then we have the same number of distinct subsequences as # we had without the new character. # if the current character in S equal to the current character T, then the distinct number of subsequences: # the number we had before plus the distinct number of subsequences we had with less longer T and less longer S. # An example: # S: [acdabefbc] and T: [ab] # first we check with a: # * * # S = [acdabefbc] # mem[1] = [0111222222] # then we check with ab: # * * ] # S = [acdabefbc] # mem[1] = [0111222222] # mem[2] = [0000022244] # And the result is 4, as the distinct subsequences are: # S = [a b ] # S = [a b ] # S = [ ab ] # S = [ a b ] # Recurrence relation: # dp[i][j] = dp[i - 1][j] + (dp[i - 1][j - 1] if s[i - 1] == t[j - 1]) class Solution(object): def numDistinct(self, s, t): dp = [[1] * (len(s)+1)] + [[0] * (len(s)+1) for y in range(len(t))] for j in range(1, len(t)+1): for i in range(1, len(s)+1): dp[j][i] += dp[j-1][i-1] + dp[j][i-1] if s[i-1] == t[j-1] else dp[j][i-1] return dp[-1][-1] print(Solution().numDistinct('rabbbit', 'rabbit')) # 3 ################################################################## ## Space optimization # The states are only from top and left-top. Thus, 1-D array is enough and uses some temp variables to roll the array all the way down. class Solution(object): def numDistinct(self, s, t): dp = [1] + [0] * len(t) for i in range(1, len(s) + 1): pre = dp[0] for j in range(1, len(t) + 1): pre, dp[j] = dp[j], dp[j] + pre * (s[i - 1] == t[j - 1]) # represent the three lines below; 这里的 pre 值得是 dp[i-1][j-1] return dp[-1] print(Solution().numDistinct('rabbbit', 'rabbit')) # 3 # tmp = dp[j] # dp[j] = dp[j] + pre * (s[i - 1] == t[j - 1]) # pre = tmp ################################################################## ## 从暴力递归 -> 记忆化搜索 -> 动态规划 # ``` cpp # int process(string &S, string &T, int ss, int se, int ts, int te){ # if (ts > te){return 1;} # int i; # int res = 0; # for (i = ss; i < se - (te - ts)+1; i++){ # if (T[ts] == S[i]){res += process(S, T, i+1, se, ts + 1, te);} # } # return res; # } # process(S, T, 0, S.size()-1, 0, T.size()-1); # ``` # S 是母串, T 是子串; s 就是 start 的意思, e 是 end 的意思, ss 、 se 、 ts 、 te 意思自然明白了 # 递归过程如下: # 1. 递归返回条件为: 如果 ts > te, 说明子串已经全部匹配完, 所以返回 1, 算一种情况 # 2. 对于母串, 从 ss 下标开始, 一直到(ss - (te - ts) + 1)下标结束, 其中 te-ts+1 为子串的长度 # 3. i 遍历母串的每一个初始位置, 如果 T[ts] == S[i], 说明第一个字符匹配了, 继续进入递归过程, res 累加记录每次的结果, 最后返回 ################################################################## # 这里的暴力递归显然有很多的重复计算, 所以我们可以通过记忆化的方式, 将结果先保存下来, # 仔细观察上面的递归函数, 只有参数 ss 和 ts 在变化, 所以可以用一张二维的表记录下每组 ss 和 ts 对应的值, 以后直接查表即可
9f6977008ac13b376128e980aafb0a7cb855d2ab
ballib/SC-T-111-PROG
/prof/Lokaprof/Lokaprof_2016/points.py
920
3.859375
4
def open_file(filename): try: with open(filename, 'r') as file: file_list = [] for line in file.readlines(): points = [] x, y = line.rstrip().split() points.append(int(x)) points.append(int(y)) file_list.append(points) return file_list except FileNotFoundError: print("File {} not found".format(filename)) def find_range(data): nums_in_range = [] for points in data: if points[0] <= 50 and points[1] <= 50: nums_in_range.append(points) return nums_in_range def print_points(numbers): print("Points in the upper left quadrant are:") for x in numbers: print(*x) def main(): file_name = input("Enter name of file ") data = open_file(file_name) nums_in_range = find_range(data) print_points(nums_in_range) main()
9e2d6414020d163115197f64e13cccf6204ed574
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/bdgmul001/question4.py
1,093
4.375
4
# program that uses recursive functions to find all palindromic primes between two integers supplied as input (start and end points are included). # Mulisa Badugela # BDGMUL001 # 08 MAY 2014 import sys sys.setrecursionlimit (30000) N =eval(input('Enter the starting point N:\n')) # user input start point if N == 1 : N=N+1 M = eval(input('Enter the ending point M:\n')) # user input end point print('The palindromic primes are:') def palindrome(num): # function to check for palindrome if len(num) <= 1 : return True else : if num[0] == num[len(num)-1]: return palindrome(num[1:len(num)-1]) else: return False def prime(N,M): # function to check for primes if (M>N**(1/2)): return True if N%M == 0 : return False else: return prime(N,M+1) def palindromic_primes(N,M): if N>M: return '' else : if palindrome(str(N)) and prime(N,2): print(N) palindromic_primes(N+1,M) palindromic_primes(N,M)
6e1200d7b5d13e454f4380c2128480594b7dd400
mpetrozzi78/PyPoll-and-PyBank
/Python-Bank-and-Python-Poll/PyPoll.py
2,532
3.921875
4
# First we'll import the os module # This will allow us to create file paths across operating systems import os # Module for reading CSV files import csv # Module to do the sorting import operator #csvpath = os.path.join('..', 'Resources', 'election_data.csv') election_file = open('election_data.csv', "r") # Splt the data on commas csv1 = csv.reader(election_file, delimiter=',') # Skip the Header header = next(csv1) # Setting Variables sum_votes = 0 # Dictionary of results results = {} # Calculations for each row for row in csv1: # Calculating total votes of all candidates sum_votes = sum_votes + 1 # assigning values to the results dictionary # If the candidate on the csv file is already present in our dictionary if row[2] in results.keys(): # if "key_name" in dic_name.keys(): # Add the counter value of the corresponding key results[row[2]] += 1 # If the candidate is not present in our dictionary else: results[row[2]] = 1 # Sorting the dictionary after gone through all the calculations for each row of the csv file sorted_results = sorted(results.items(), key=operator.itemgetter(1), reverse=True) #Printing the results print("'''''''''''''''''''''''''''''''''") print("ELECTION RESULTS") print("--------------------------------") print("Total Votes: " + str(sum_votes)) print("--------------------------------") #print (sorted_results) for k, v in sorted_results: val=str(v) percent=round((float(val)/float(sum_votes))*100) print(k + ": " + str(percent) + '%' + ' ('+ str(v) + ')') print("--------------------------------") # Print the greatest number with candidate maximum = max(results, key=results.get) print("Winner: " + maximum) print("--------------------------------") #print(maximum, results[maximum]) #Export a Text file with the results import sys file = open('Election_Results_Output.txt', 'a') sys.stdout = file print("'''''''''''''''''''''''''''''''''") print("ELECTION RESULTS") print("--------------------------------") print("Total Votes: " + str(sum_votes)) print("--------------------------------") #print (sorted_results) for k, v in sorted_results: val=str(v) percent=round((float(val)/float(sum_votes))*100) print(k + ": " + str(percent) + '%' + ' ('+ str(v) + ')') print("--------------------------------") # Print the greatest number with candidate maximum = max(results, key=results.get) print("Winner: " + maximum) print("--------------------------------") file.close()
76c23193444355920da20c9b0e38eb548d2b5b43
yabirgb/algoritmicaGrupo
/greedy/Genetico/read.py
890
3.59375
4
from math import sqrt filename = "ulysses16" def distance(t1, t2): return sqrt( (t2[1] - t1[1])**2 + (t2[2] - t1[2])**2 ) def coordenadas(filename): with open("datosTSP/" + filename + ".tsp", 'r') as f: cities = [] size = int(f.readline().split(" ")[1]) for city in range(size): data = list(map(float, f.readline().lstrip().split(" "))) cities.append((data[0], data[1], data[2])) del data return cities mapear = coordenadas(filename) matrix = [[distance(x, y) for y in mapear] for x in mapear] print(matrix) #Supongamos que tenemos el vector de la solución s = [(1, 23.42, 23.12), (2, 12,12)] def outofhere(solution): output = "" for city in solution: output += "{0} {1} {2}\n".format(*city) with open(filename+".out", 'w') as f: f.write(output) outofhere(s)
9361436143ec7724ca36b9ff044137e0aaf79b6f
Zahed75/Python_practice
/list_quiz.py
1,042
4.3125
4
# print the second value fruits = ["apple", "mango", "litchi"] print(fruits[1]) # change the value from apple to the litchi fruits = ["apple", "mango", "litchi"] fruits[0] = "litchi" print(fruits) # use to the append method to add orange fruits = ["apple", "banana", "mango", "litchi"] fruits.append("orange") print(fruits) # Use the insert method to add "lemon" as the second item in the fruits list. f = ["apple", "banana", "cherry"] f.insert(1, "lemon") print(f) #Use the remove method to remove "banana" from the fruits list. fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits) #Use negative indexing to print the last item in the list. fruits = ["apple", "banana", "cherry"] print(fruits[-1]) #Use a range of indexes to print the third, fourth, and fifth item in the list. fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(fruits[2:5]) #Use the correct syntax to print the number of items in the list. fruits = ["apple", "banana", "cherry"] print(len(fruits))
3881fca601873f24fd58c3361b3f44f622011996
fulcrumandco/TDBv0.1
/TheDarkBelow.py
6,664
3.546875
4
from sys import exit import xml.etree.ElementTree as ET from xml.etree.ElementTree import parse, Element import random from random import randint, choice error_list = ["I didn't understand that.", "What are you saying?", "That doesn't compute.", "Dude, what.", "You aren't making sense.", "That's highly illogical."] inventory = [] area = "" def restart(): print "Would you like to try again?" next = raw_input("> ") if next == "yes": start() else: print("You have surrendered to the darkness. Better luck next time!") exit(0) def dead(why): print why, "The end!" restart() def quit(): print "Are you sure you'd like to quit?" next = raw_input("> ") if next == "yes": print("You have surrendered to the darkness. Better luck next time!") else: pass # Game start and room 1 def start(): description = """ You stand before a glowing portal of shimmering opal, which appears to be carved directly into the cliff face. It is surrounded on all sides by hideous gargoyles and ornate statues depicting the heroes who have come before you. The portal wavers, beckoning you to step forward and enter into the depths it conceals.\n""" print description print "Do you step into the portal?" while True: next = raw_input("> ") if next == "yes": print "You step forward into the portal, and a cold wave washes over you." entry() elif next == "no": print "Fear clutches at you, and you step back from the portal." dead(""" With a small 'pop', the portal vanishes, leaving you surrounded by high cliffs and steep walls. You shiver as the wind picks up, and look around for a way to start a fire... eventually, the light from the clifftop fades away.""") elif next == "look": print description elif next == "quit": dead("You have surrendered to the darkness. Better luck next time!") else: print "Yes or no, adventurer." # Room 2. Connects to Dwelling and Altar. Items: Torch. Light mechanic to be added later. def entry(): area = "entry" description = """ The portal spits you out into a large, dark room, lit only by a single torch. It looks like you could pry the torch off the wall. Dim flickers of light come from two different passages, one to your left and one to your right. """ print description while True: next = raw_input("> ") if "left" in next: print "You head off to the left, through the rough-hewn tunnel." print "It appears to have grotesque paintings on the walls - monsters flash" print "in the torchlight. The dark gives you a chill." altar() elif "right" in next: print "You head off to the right, into the darker, narrower passage." print "The path ahead is littered with small bones, and a smell rises in your" print "nostrils. Something rotten floats on the air in this corridor." dwelling() elif next == "look": print description elif next == "take torch": inventory.append("Torch") print "After some effort, the torch breaks free of the sconce holding it to the wall. You take it." else: print(random.choice(error_list)) # Room 3. Connects to Entry and Empty Hall. # Items: Knife and Potion. Need description and elif for "look at altar". def altar(): description = ''' There is an altar of bones standing before you, with crude pewter icons. There is painting on the walls, in what looks like blood. The path continues forward, into the dark, and back the way you came.''' knife_taken = False bottle_taken = False print description # Next section looks for knife and bottle objects (not official objects) and if the player has # taken them already or not. This is a good example of why this needs to be rewritten, since # it has to be coded in to the "look" option below, as well. There's a better way to do this. if knife_taken == False: print " Something shiny gleams on top of the gruesome surface." else: pass if bottle_taken == False: print " There is a small bottle of something dark sitting on the bones." else: pass while True: next = raw_input("> ") if "look at bottle" in next: print "The bottle appears to be filled with a murky, smooth substance the color of blood. Do you take it?" answer = raw_input("> ") if answer == "yes": inventory.append("Potion") bottle_taken = True print "You take the bottle." else: print "You leave the bottle on the altar." elif "look at" in next: print "The object appears to be a knife. Do you take it?" answer = raw_input("> ") if answer == "yes": inventory.append("Knife") knife_taken = True print "You take the knife." else: print "You leave the knife on the altar." elif next == "look": print description if knife_taken == False: print "Something shiny gleams on top of the gruesome surface." else: pass if bottle_taken == False: print "There is a small bottle of something dark sitting on the bones." else: pass elif next == "go forward": print "You step forward into the dark tunnel, wondering where you will pop out next." empty_hall() elif next == "go back": entry() else: print(random.choice(error_list)) # Room 4. No items here. Connects to Kitchen and Entry. def dwelling(): description = """ The room you enter appears to be some kind of living space. The low ceiling has a small hole in it, which appears to go all the way to the surface. There are a couple small beds against one wall. The room appears empty aside from the beds. """ # Room 5. No items here. Connects to altar and Large Hall. def empty_hall(): description = """ """ print "Welcome, Adventurer!" start()
682240fdc8d48fb268816f89c587351cc5d01795
connor-mcnaboe/CaesarCipher
/ceasarCipher.py
2,750
3.984375
4
#Programmed by Connor McNaboe #Questions or suggestions refer to https://github.com/zerodarkbirdy/CaesarCipher # #This program takes a text file and encrypts it using a caesar cipher. import argparse import os import time import sys parser = argparse.ArgumentParser() # Define comamand line args parser.add_argument("-k", type=int, help="Enter a keyvalue") parser.add_argument("-f", help="Enter filename that will be encrypted") parser.add_argument("-e", help="Option to encrypt", action="store_true") parser.add_argument("-d", help="Option to decrypt", action="store_true") args = parser.parse_args() key = args.k #agruments to variables txt = args.f ecrpt = args.e dcrpt = args.d def main(k, f, encrpt, dcrpt): #Declare variables ascii_dict = create_ascii_dict() #Check all arguments are filled if k is None or f is None: sys.exit("Error: Enter both key and filename") if encrpt is False and dcrpt is False: sys.exit("Error: Enter an option to encrypt or decrypt a file") if k > 255: k = k % 255 createFile(f, k, ascii_dict, encrpt, dcrpt) #Encrypt File def create_ascii_dict(): # Create ascii dictionary ascii_dict = dict() ascii_in_number = range(0,256) for i in ascii_in_number: ascii_dict[str(i)] = chr(i) return ascii_dict def crypt(txt, key, ascii_dict, dcrpt, encrpt): #Encrypt the file txt2 = [] for value in txt: txt2 += [k for k, v in ascii_dict.iteritems() if v == value] #Map all values in the txt to value in ascii dict txt2 = [int(i) for i in txt2]# Convert to integer if encrpt is True: txt2 = [i + key for i in txt2] #Increment w/ key elif dcrpt is True: txt2 = [i - key for i in txt2] txt2 = [i + 256 if i < 0 else i - 256 if i > 256 else i for i in txt2] txt2 = [str(i) for i in txt2] txt_e = [] for i in txt2: txt_e += ascii_dict[i] #Re-map to ascii return txt_e def rtnTxt(txt): #Put the string back together txt = ''.join(txt) return txt def createFile(txt, key, ascii_dict, encrpt, dcrpt): # Create new encrypted file statBar = ['#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', "100%"] status = '' for i in statBar: sys.stdout.flush() time.sleep(0.15) sys.stdout.write(i) try: with open(os.path.expanduser(txt), 'r+') as f: p = str(f.read()) except IOError: print("Error: Enter filename in current directory") exit() e = rtnTxt(crypt(p, key, ascii_dict, dcrpt, encrpt)) if encrpt is True: with open("encryptedFile.txt", "w") as eFile: eFile.write(e) eFile.close() print('\nDone Encrypting\n') elif dcrpt is True: with open("decyptedFile.txt", "w") as dFile: dFile.write(e) dFile.close() print('\nDone Decrypting\n') main(key, txt, ecrpt, dcrpt)
aa82c75a941804ee7ddbda65b23db10f8468e86f
yuenliou/leetcode
/496-next-greater-element-i.py
3,481
3.5625
4
#!/usr/local/bin/python3.7 # -*- coding: utf-8 -*- from typing import List class Solution: def _nextGreaterElement(self, nums: List[int]) -> List[int]: """ 思路1:暴力解 思路2:单调栈 [2,1,2,4,3] """ res = [0] * len(nums) stack = [] # 倒着往栈里放 for i in range(len(nums) - 1, -1, -1): # 维护了一个 递增栈 while len(stack) and stack[-1] <= nums[i]: stack.pop() # nums[i] 身后的 next great number if len(stack): res[i] = stack[-1] else: res[i] = -1 stack.append(nums[i]) return res def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: """ 思路1:暴力解 思路2:单调栈 [2,1,2,4,3] 作文题:No, it's asking you to take an element in the first array and then find the same element in the second array and then look to the right in the second array to find a greater one. I couldn`t understand this until I looked into some solutions in the discussi """ res = [-1] * len(nums1) stack = [] map = {} # 先处理 nums2,把对应关系存入哈希表 for i in range(len(nums2)): while len(stack) and stack[-1] < nums2[i]: map[stack.pop()] = nums2[i] stack.append(nums2[i]) # 遍历 nums1 得到结果集 for i in range(len(nums1)): if nums1[i] in map: res[i] = map[nums1[i]] return res def main(): # param = [4, 1, 2] # param2 = [1, 3, 4, 2] param = [3, 1, 2] param2 = [1, 3, 2, 4] solution = Solution() ret = solution._nextGreaterElement([2, 1, 2, 4, 3]) print(ret) ret = solution.nextGreaterElement(param, param2) print(ret) '''496. 下一个更大元素 I 给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。 请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。 nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。   示例 1: 输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出: [-1,3,-1] 解释: 对于 num1 中的数字 4 ,你无法在第二个数组中找到下一个更大的数字,因此输出 -1 。 对于 num1 中的数字 1 ,第二个数组中数字1右边的下一个较大数字是 3 。 对于 num1 中的数字 2 ,第二个数组中没有下一个更大的数字,因此输出 -1 。 示例 2: 输入: nums1 = [2,4], nums2 = [1,2,3,4]. 输出: [3,-1] 解释:   对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。 对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。   提示: 1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 104 nums1和nums2中所有整数 互不相同 nums1 中的所有整数同样出现在 nums2 中   进阶:你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/next-greater-element-i 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' if __name__ == '__main__': main()
03c0e1f942558bbc7e67891e430e4030ec1ede07
mchez808/OOPython
/ch1-oop-basics/instance_book.py
2,833
4.3125
4
# instance methods and attributes class Book(object): """ [from PEP 257] The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring. """ def __init__(self, title, author, pages, price): """Inits Book with parameters""" self.title = title self.author = author self.pages = pages self.price = price self.__secret = "SECRET ATTRIBUTE" def get_price(self): """return price of book. instance method (not class method)""" if hasattr(self, "_discount"): return self.price - (self.price * self._discount) else: return self.price def set_discount(self, amount): """modifies discount on book object. (A mutator)""" self._discount = amount # note: _discount underscore serves as hint to devs that this attribute is internal to the class # and should not be accessed from outside the class's logic # note: Python doesn't formally enforce this encapsulation. if __name__ == "__main__": b1 = Book("War and Peace", "Leo Tolstoy", 1225, 39.95) b2 = Book("The Catcher in the Rye", "JD Salinger", 234, 29.95) print(b1.get_price()) b2.set_discount(0.10) print(b2.get_price()) # note: dunder properties are hidden by the interpreter try: print(b1.__secret) except AttributeError as e: print("note: successful demonstration of dunder attribute.") # The error is because that property can't be seen outside the class. # However, this is not a perfect mechanism. So the way that Python does this is by prefixing the name of the attribute with the class name. This is called name mangling. # The reason for this feature is to prevent sub classes, which we'll learn about later, from inadvertently overriding the attribute, # but other classes can subvert this simply by using the class name. So if I go back to the code and just simply put _book in front of this... print(b1._Book__secret) # It says now this is a secret attribute. You can see now that I can access the property. So it's not a perfect solution. # Nevertheless, you can use this approach to make sure that subclasses don't use the same name for an attribute that you've already used. Now in some cases that's exactly what you want. You do want subclasses to overwrite things sometimes. But if you need to make sure that they don't, then the double underscore can prevent that.
6d2f3963f2367f2ee692a902061090fc8d1ca6ca
palakbaphna/pyprac
/Strings/12NumOfWOrds.py
271
4.28125
4
#Given a string consisting of words separated by spaces. # Determine how many words it has. To solve the problem, use the method count. #s = 'In the hole in the ground there lived a hobbit' s = input() t = s.count(' ') print("No of words in the given string =", (t+1))
2ecb017b7880809956d1976fd275f7324cf26189
itspratham/Python-tutorial
/Python_Contents/geeksforgeeks/matrix/prg1.py
276
3.78125
4
# Count zeros in a sorted matrix # def countzero(arr): # count = 0 # for i in range(len(arr)): # for j in range(len(arr)): # if arr[i][j] == 0: # count = count +1 # return count # # print(countzero([[0,0,0],[0,0,1],[0,1,1]]))
78e77dfb7487c4a0e147bed43537737558d0da65
developer579/Practice
/Python/Python Lesson/Second/Lesson8/Sample2.py
347
3.671875
4
class Person: def getName(self): return self.name def getAge(self): return self.age pr1 = Person() pr1.name = "鈴木" pr1.age = 23 n1 = pr1.getName() a1 = pr1.getAge() pr2 = Person() pr2.name = "佐藤" pr2.age = 38 n2 = pr2.getName() a2 = pr2.getAge() print(n1,"さんは",a1,"才です。") print(n2,"さんは",a2,"才です。")
9474029aa43223974c8ef522b9c6986a42fafac5
thabo-div2/python_functions
/main.py
549
4.0625
4
# Exercise 1 - Python Functions # Defining an argument def distance_from_zero(x): # Passing an argument if type(x) == int or type(x) == float: # Checking the type of variants return abs(x) else: return "Nope" print(distance_from_zero(-5)) print(distance_from_zero(6)) print(distance_from_zero("what?")) # Exercise 2 def is_leap(year): leap = False if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): return True return leap year = int(input("Enter the year: ")) print(is_leap(year))
56591910a0ce88d83c1f8aee3116ea9b2d0850c5
rubenvereecken/challenges
/Cracking the Coding Interview/Extra/itertools.py
408
3.859375
4
__author__ = 'ruben' def permutations(array): if len(array) == 1: yield [array[0]] else: for i, el in enumerate(array): pre = array[0:i] post = array[i+1:len(array)] next = permutations(pre + post) for perm in next: yield [el] + perm if __name__ == '__main__': print(list(permutations([x for x in range(3)])))
9867d1c8aa6477cf4b0d5055ca5bc9d330cf7b36
lxh1997zj/-offer_and_LeetCode
/剑指offer-牛客顺序/to_offer_20.py
1,305
3.796875
4
# !/usr/bin/env python3 # -*- coding:utf-8 -*- '定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1)),在该栈中,调用min、push、pop的时间复杂度都是O(1)' class Solution: def __init__(self): self.stack = [] self.minstack = [] def push(self, node): # write code here self.stack.append(node) if self.minstack == [] or node < self.min(): self.minstack.append(node) else: self.minstack.append(self.min()) def pop(self): # write code here if self.stack == [] or self.minstack == []: return self.stack.pop() self.minstack.pop() def top(self): # write code here return self.stack[-1] def min(self): # write code here return self.minstack[-1] """ 把每次的最小元素保存起来放在另一个辅助栈里. 引入两个栈,一个栈每次push实际的数字,另一个minStack,如果push的数字小于minStack栈顶的数字,push新的数字,否则就繁殖,把最小栈栈顶的数字再压入一遍。 """ S = Solution() S.push(3) S.push(4) S.push(2) S.push(1) print(S.min()) S.pop() print(S.min()) S.pop() print(S.min())
1f8515352a5dc921e979c54bb46f96fc782dbda7
nlfox/leetcode
/20_Valid_Parentheses.py
586
3.671875
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] m = {'{': '}', '[': ']', '(': ')'} for i in xrange(len(s)): if m.has_key(s[i]): stack.append(s[i]) else: if stack == []: return False if m[stack.pop()] == s[i]: continue else: return False if stack != []: return False return True print Solution().isValid("")
12e01791ff9e57b65d91cd75c74876319936adec
frankkarsten/MTG-Math
/Burn_with_interaction.py
11,934
3.640625
4
import random from collections import Counter from itertools import combinations import math list_of_opening_hands = [] for Guide in range(8): for Bolt in range(8): for Charm in range(8): for Land in range(8): if Guide + Bolt + Charm + Land == 7: hand = { 'Goblin Guide': Guide, 'Lightning Bolt': Bolt, 'Boros Charm': Charm, 'Sacred Foundry': Land } list_of_opening_hands.append(hand) def binom(n, k): """ Parameters: n - Number of elements of the entire set k - Number of elements in the subset It should hold that 0 <= k <= n Returns - The binomial coefficient n choose k that represents the number of ways of picking k unordered outcomes from n possibilities """ answer = 1 for i in range(1, min(k, n - k) + 1): answer = answer * (n + 1 - i) / i return int(answer) def multivariate_hypgeom(deck, needed): """ Parameters: deck - A dictionary of cardname : number of copies needed - A dictionary of cardname : number of copies It should hold that the cardname keys of deck and needed are identical Returns - the multivariate hypergeometric probability of drawing exactly the cards in 'needed' from 'deck' when drawing without replacement """ answer = 1 sum_deck = 0 sum_needed = 0 for card in deck.keys(): answer *= binom(deck[card], needed[card]) sum_deck += deck[card] sum_needed += needed[card] return answer / binom(sum_deck, sum_needed) def simulate_one_game(hand, library, drawfirst): """ Parameters: hand - A dictionary, with the same cardnames as in deck, with number drawn library - A list of 53 or more cards, most of which will be shuffled (but after mull one or more cards on the bottom may be known) drawfirst - A boolean that is True if on the draw and False on the play Returns - A number that represents the kill-turn where 20 damage was dealt """ #Initialize variables turn = 1 opp_life = 20 opp_Push = 1 opp_Dispel = 1 battlefield = {} for card in decklist.keys(): battlefield[card] = 0 #Loop over turns while True: #Draw a card if on the draw or if turn 2 or later if drawfirst or turn >= 2: card_drawn = library.pop(0) hand[card_drawn] += 1 #Play a land and tap all lands for mana if (hand['Sacred Foundry'] > 0): hand['Sacred Foundry'] -= 1 battlefield['Sacred Foundry'] += 1 mana_available = battlefield['Sacred Foundry'] #Play Goblin Guide if possible, and attack playable_goblins = min(mana_available, hand['Goblin Guide']) hand['Goblin Guide'] -= playable_goblins mana_available -= playable_goblins battlefield['Goblin Guide'] += playable_goblins if opp_Push > 0 and battlefield['Goblin Guide'] > 0: opp_Push -= 1 battlefield['Goblin Guide'] -= 1 opp_life -= battlefield['Goblin Guide'] * 2 #Cast as many 1-mana Bolts as possible, unless that would leaves us with 1 mana remaining and Charm in hand #Example: If we have 3 lands, 2 Bolts, and 1 Charm, we want to cast one Bolt and one Charm if mana_available >= 1 and hand['Lightning Bolt'] >= mana_available: hand['Lightning Bolt'] -= mana_available opp_life -= 3 * mana_available mana_available = 0 if opp_Dispel > 0: opp_Dispel -= 1 opp_life += 3 if mana_available >= 2 and hand['Lightning Bolt'] in [mana_available - 1, mana_available - 2] and hand['Boros Charm'] >= 1: hand['Lightning Bolt'] -= mana_available - 2 opp_life -= 3 * (mana_available - 2) hand['Boros Charm'] -= 1 opp_life -= 4 if opp_Dispel > 0: opp_Dispel -= 1 opp_life += 4 mana_available = 0 #Spend excess mana on Charms playable_charms = min(mana_available // 2, hand['Boros Charm']) hand['Boros Charm'] -= playable_charms mana_available -= playable_charms * 2 opp_life -= playable_charms * 4 if opp_Dispel > 0 and playable_charms > 0: opp_Dispel -= 1 opp_life += 4 #Spend excess mana on Bolts playable_bolts = min(mana_available, hand['Lightning Bolt']) hand['Lightning Bolt'] -= playable_bolts mana_available -= playable_bolts opp_life -= playable_bolts * 3 if opp_Dispel > 0 and playable_bolts > 0: opp_Dispel -= 1 opp_life += 3 if (opp_life <= 0): break else: turn += 1 return turn def simulate_one_specific_hand(hand, bottom, drawfirst, num_iterations): """ Parameters: hand - A dictionary, with the same cardnames as in deck, with number drawn bottom - A dictionary, with the same cardnames as in deck, with cards that will be put on the bottom (This is due to London mull. Bottom order is currently arbitrary and assumed to be irrelevant.) drawfirst - A boolean that is True if on the draw and False on the play num_iterations - Simulation sample size. Could be 10 if precision isn't important, could be 100,000 if it's important. Returns - A list representing [expected kill-turn where 20 damage was dealt, P(turn 3 kill), P(turn 4 kill), P(turn 5 kill), P(turn 6+ kill)] """ kill_turn_sum = 0.0 for i in range(num_iterations): #Copy opening hand information into a variable that can be manipulated in the simulation sim_hand = {} for card in decklist.keys(): sim_hand[card] = hand[card] #Construct the library: first the random part, which gets shuffled sim_library = [] for card in decklist.keys(): sim_library += [card] * ( decklist[card] - sim_hand[card] - bottom[card]) random.shuffle(sim_library) #Then put the bottom part on the bottom #The order is assumed not to matter here for card in bottom.keys(): sim_library += [card] * bottom[card] #Simulate the actual game kill_turn = simulate_one_game(sim_hand, sim_library, drawfirst) kill_turn_sum += kill_turn return kill_turn_sum/num_iterations def what_to_put_on_bottom (hand, drawfirst, number_bottom, num_iterations): """ Parameters: hand - A dictionary, with the same cardnames as in deck, with number drawn drawfirst - A boolean that is True if on the draw and False on the play number_bottom - The number of cards that needs to be put on the bottom num_iterations - Simulation sample size. Could be 10 if precision isn't important, could be 10,000 if it's important. Returns - A dictionary, with the same cardnames as in deck, with the best set of cards to put on the bottom Note - the optimization criterion is minimized. That's appropriate if it's a kill-turn. """ best_goal = 50 best_bottom = {} #Transform hand into a list to be able to iterate handily hand_list = [] for card in hand.keys(): hand_list += [card] * hand[card] #Iterate over all tuples of length number_bottom containing elements from hand_list #There may be duplicates right now, that's bad for runtime but shouldn't affect the maximum for bottom in combinations(hand_list, number_bottom): bottom_dict = {} for card in decklist.keys(): bottom_dict[card] = 0 for card in bottom: bottom_dict[card] += 1 remaining_hand = {} for card in decklist.keys(): remaining_hand[card] = hand[card] - bottom_dict[card] goal = simulate_one_specific_hand(remaining_hand, bottom_dict, drawfirst, num_iterations) if (goal <= best_goal): best_goal = goal for card in decklist.keys(): best_bottom[card] = bottom_dict[card] return best_bottom def simulate_one_handsize(handsize, drawfirst): """ Parameters: handsize - Opening hand size, could be in {0, 1, ..., 6, 7} drawfirst - A boolean that is True if on the draw and False on the play Returns - the probability of achieving the goal with this opening hand size and play/draw setting Note - for handsize > 1 the value of success_probability(handsize - 1) needs to be known!!! """ sum_kill_turn = 0.0 #Construct library as a list library = [] for card in decklist.keys(): library += [card] * decklist[card] for hand in list_of_opening_hands: #Determine probability of drawing this hand opening_hand = hand.copy() prob = multivariate_hypgeom(decklist, opening_hand) #The following numbers can be adjusted manually to increase/decrease total runtime sample_size_per_bottom = math.ceil(20000 * handsize * prob) sample_size_per_hand_under_best_bottom = math.ceil(100000 * handsize * prob) #Determine the set of cards that are best to put on the bottom if (handsize < 7): best_bottom = what_to_put_on_bottom(opening_hand, drawfirst, 7 - handsize, sample_size_per_bottom) else: best_bottom = {} for card in decklist.keys(): best_bottom[card] = 0 #Take the bottom part from the hand part for card in opening_hand.keys(): opening_hand[card] = opening_hand[card] - best_bottom[card] #For a one-card opening hand we auto-keep if (handsize <= 1): kill_turn_outcomes = simulate_one_specific_hand(opening_hand, best_bottom, drawfirst, sample_size_per_hand_under_best_bottom) exp_kill_turn = kill_turn_outcomes #For a larger opening hand we choose keep or mull based on success probability if (handsize > 1): kill_turn_when_keep = simulate_one_specific_hand(opening_hand, best_bottom, drawfirst, sample_size_per_hand_under_best_bottom) kill_turn_when_mull = kill_turn_list[handsize - 1] exp_kill_turn = min(kill_turn_when_keep, kill_turn_when_mull) sum_kill_turn += exp_kill_turn * prob return sum_kill_turn optimal_lands = 20 optimal_killturn = 10 for Lands in range(20, 26 + 1): decklist = { 'Goblin Guide': 12, 'Lightning Bolt': 16, 'Boros Charm': 32 - Lands, 'Sacred Foundry': Lands } final_kill_turn_for_7 = 0 Results = "For "+ str(Lands) +" lands: " for drawfirst in [True, False]: kill_turn_list = [None] * 10 for handsize in range(1, 8): kill_turn_list[handsize] = simulate_one_handsize(handsize, drawfirst) if (handsize == 7): final_kill_turn_for_7 += kill_turn_list[handsize] / 2.0 Results += f'{kill_turn_list[handsize]:.4f} on the draw, ' if drawfirst else f'{kill_turn_list[handsize]:.4f} on the play, ' Results += f'{final_kill_turn_for_7 :.4f} overall.' print(Results) if (final_kill_turn_for_7 < optimal_killturn): optimal_lands = Lands def hand_to_text(hand): """ Parameters: hand - A dictionary, with the same cardnames as in deck, with number drawn Returns - The hand in nice text form """ text = "" for card in hand.keys(): if hand[card] > 0: text += str(hand[card]) + " " + card + " " return text decklist = { 'Goblin Guide': 8, 'Lightning Bolt': 16, 'Boros Charm': 32 - optimal_lands, 'Sacred Foundry': Lands } with open("burn_output.csv","w") as file: file.write("Hand, drawfirst, probability, keep or mull at 7, exp kill turn at 7, keep or mull at 6, best bottom at 6, keep or mull at 5, best bottom at 5") file.write("\n") for drawfirst in [True, False]: for hand in list_of_opening_hands: #Determine probability of drawing this hand opening_hand = hand.copy() prob = multivariate_hypgeom(decklist, opening_hand) file.write(hand_to_text(hand) + "," + str(drawfirst) + "," + str(prob)+ ",") for handsize in [7, 6, 5]: #Determine the set of cards that are best to put on the bottom if (handsize < 7): best_bottom = what_to_put_on_bottom(opening_hand, drawfirst, 7 - handsize, 10000) else: best_bottom = {} for card in decklist.keys(): best_bottom[card] = 0 #Take the bottom part from the hand part for card in opening_hand.keys(): opening_hand[card] = opening_hand[card] - best_bottom[card] #Choose keep or mull based on success probability kill_turn_when_keep = simulate_one_specific_hand(opening_hand, best_bottom, drawfirst, 50000) kill_turn_when_mull = kill_turn_list[handsize - 1] if (kill_turn_when_mull < kill_turn_when_keep): file.write("Mull!,") else: file.write("Keep!,") if (handsize == 7): file.write(str(kill_turn_when_keep)+",") if (handsize < 7): file.write(hand_to_text(best_bottom)+",") file.write("\n") file.close()
27ee51ca0050278be04461d6cb832f22a0928fe1
1buraknegis/Python-Tkinter-examples
/radioButton.py
708
3.515625
4
import tkinter as tk form = tk.Tk() form.title("RadioButton") form.geometry("500x450") x = tk.StringVar() def kontrol(): if x.get() == "1": print("buton1") elif x.get() == "2": print("buton2") else: print("buton2 ve buton1") buton = tk.Button(form, text="tıkla", fg="black", bg="red", activebackground="green", command=kontrol) buton.pack() radio = tk.Radiobutton(form, text="radio1", activebackground="red", value="1", variable=x) radio.pack() radio2 = tk.Radiobutton(form, text="Radio", activebackground="green", value="2", variable=x) radio2.pack() form.mainloop()
47e8eb7df50a4ac811640a35bd329063deaefd6d
MohammedAlewi/competitive-programming
/leetcode/Tree Problems/Construct Binary Search Tree from Preorder Traversal.py
1,431
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.preorder=None self.bsd=None self.tree=None self.index=0 def bstFromPreorder(self, preorder: List[int]) -> TreeNode: size= 10000*len(preorder) self.bsd=['null']*(size) self.preorder=preorder length=len(self.preorder) for i in range(length): self.construct(i) self.tree=TreeNode(None) self.tree=self.const_tree(tree=self.tree,i=0) return self.tree def construct(self,i,j=0): if len(self.bsd)>j and self.bsd[j]=='null': self.bsd[j]=self.preorder[i] elif self.preorder[i]<self.bsd[j]: self.construct(i,2*(j+1)-1) elif self.preorder[i]>=self.bsd[j] : self.construct(i,2*(j+1)) def const_tree(self,tree,i): if self.bsd[i]=='null':return; tree.val=self.bsd[i] if len(self.bsd)>2*(i+1) and tree.val!='null': tree.left=TreeNode('null') tree.right=TreeNode('null') tree.left=self.const_tree(tree.left,2*(i+1)-1) tree.right=self.const_tree(tree.right,2*(i+1)) return tree else: return tree
c3b1196717ce806c474a45a059f96fe5cda759e4
JSYoo5B/TIL
/PS/ProjectEuler/P007/sieve_of_eratosthenes_functional.py
765
4.15625
4
#!/usr/bin/env python3 """ Sieve of Eratosthenes 1. Get all prime numbers which is less than given number by the Sieve of Eratosthenes algorithm. (Loop till the sqrt of given number) 2. Search the complete divisor from the prime numbers in descending order. """ from math import sqrt REQUEST = 10001 LIMIT = 1000000 def SieveOfEratosthenes(number): primes = [x for x in range(2, number)] for factor in range(2, int(sqrt(number))): primes = list(filter(lambda x: x == factor or x % factor != 0, primes)) return primes if __name__ == '__main__': # Supposes that Prime factor may not exceed sqrt of given number primes = SieveOfEratosthenes(LIMIT) if len(primes) >= REQUEST: print(primes[REQUEST - 1])
4ac452616e32a8aebb7897705a36ffe933b33267
min-0/pitapat_python
/GUI/Color Pen.py
715
3.53125
4
from tkinter import * top = Tk() def paint(event): x1, y1 = (event.x - 1, event.y - 1) x2, y2 = (event.x + 1, event.y + 1) cnvs.create_oval(x1, y1, x2, y2, outline=penC, fill=penC) def redColor(): global penC penC = 'red' def greenColor(): global penC penC = 'green' def blueColor(): global penC penC = 'blue' cnvs = Canvas(top, width=500, height=150) cnvs.pack() cnvs.bind('<Button1-Motion>', paint) b1 = Button(top, text='빨간색', command=redColor) b2 = Button(top, text='초록색', command=greenColor) b3 = Button(top, text='파란색', command=blueColor) b1.pack(side=LEFT, ipadx=50) b2.pack(side=LEFT, ipadx=50) b3.pack(side=LEFT, ipadx=50) top.mainloop()
7929cc3ff992b439df93253ec29be142ff094e49
hongyong3/TIL
/Algorithm/Swea/D1_6318.py
131
3.765625
4
word = 'abcdef' mat = {} for i in range(len(word)): mat[word[i]] = i for k, v in mat.items(): print("{}: {}".format(k, v))
f60e3cfc05524cf261d15314f5c79e24058b2b3b
vnallani259/VenkyPhython
/python/simple.py
348
3.734375
4
num = eval(input("Please enter an integer in the range 0...9999: ")) if num < 0: num = 0 if num > 9999: num = 9999 print(end="[") digit = num//1000 print(digit, end="") num %= 1000 digit = num//100 print(digit, end="") num %= 100 digit = num//10 print(digit, end="") num %= 10 print(num, end="") print("]")
6997ae87f4d381e101747985982494e4cd5ef32e
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_117/1255.py
1,044
3.59375
4
import sys def get_horizontal(lawn, row): return lawn[row] def get_vertical(lawn, col): return [row[col] for row in lawn] def check_lawn(lawn): for y, row in enumerate(lawn): for x, cell in enumerate(row): h = get_horizontal(lawn, y) v = get_vertical(lawn, x) higher_h = [el for el in h if el > cell] higher_v = [el for el in v if el > cell] #print x, y, cell, ':', h, v if higher_h and higher_v: return False return True def solve(filename): with open(filename, 'r') as input_f: T = int(input_f.readline()) for x in range(0, T): M, N = map(int, input_f.readline().split()) lawn = [map(int, input_f.readline().split()) for r in range(0, M)] r = check_lawn(lawn) if r: print "Case #%s: YES" % (x+1) else: print "Case #%s: NO" % (x+1) if __name__ == '__main__': filename = sys.argv[1] solve(filename)
52b07d4448f00bdec6e9034ba98003346070bf7b
CAVIND46016/Project-Euler
/Problem20.py
463
4
4
#n! means n × (n − 1) × ... × 3 × 2 × 1 #For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, #and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. #Find the sum of the digits in the number 100! from functools import reduce def factorial(n): return reduce(lambda x,y:x*y,range(1,n+1),1); def main(): L = 100 print ("{}".format(sum(map(int, str(factorial(L)))))) if(__name__ == "__main__"): main();
04b3f02c9e67bd6fc62d991bf1576bb450b117e5
bmihovski/PythonFundamentials
/stateless.py
1,666
4.21875
4
""" You will be given groups of 2 strings, each on a new line. There will ALWAYS be at least 2 input lines, and there will NEVER be a case when there are less than 2 input strings, for a given element of the input. Now to the main logic - the elements of the input. You can refer to the elements of the input as states. Each state also has a fiction - the collapsing factor. Your task is to collapse each state, by its given fiction. The collapsing is done by removing all occurrences of the fiction in the state, and after that - removing the first and last element of the fiction. You must then repeat the process, until the fiction's length becomes 0. When you finish the process, you must print what is left from the state. If the state is also empty, you should print "(void)". NOTE: Border spaces should be removed. Both the state and the fiction are strings, and will be given each on a separate line. You must read sequences of DOUBLE lines, and print the result from the collapsing, until you receive the command "collapse". Examples Input astalavista baby aaa aaaa aa this will be funny rhight this collapse bow chicka mow wow mow ahaia hai collapse Output stlvist bby (void) will be funny rght bw chicka ww (void) """ while True: str_to_filter = input() if 'collapse' in str_to_filter: break fiction = input() if fiction in str_to_filter: str_to_filter = str_to_filter.replace(fiction, '') for _ in range(len(fiction), 2, -1): fiction = fiction[1:-1] str_to_filter = str_to_filter.replace(fiction, '') if str_to_filter == '': print(f'(void)') else: print(str_to_filter)
fee192054c80568ef1147c2fdf7f65a6ec94c306
907117139/lianxi
/第四周/交互式循环代码.py
295
3.96875
4
#average.py def main(): sum=0 count=0 moredate="yes" while moredate[0]=="y": x=eval(input("enter a number>>")) sum=sum+x count +=1 moredate=input("Do you have more number(yes or no)") print("\n The average of the numbers is",sum/count) main()
c4cee250505b4d6409d9c7230fbce4ac313da256
vaibhavg12/Problem-Solving-in-Data-Structures-Algorithms-using-Python3
/Algorithms/2 Graph/GraphAdjMatrix.py
6,160
3.515625
4
#!/usr/bin/env python import heapq import sys from collections import deque class Graph(object): def __init__(self, cnt): self.count = cnt self.adj = [[0 for _ in range(cnt)] for _ in range(cnt)] def AddDirectedEdge(self, source, destination, cost=1): self.adj[source][destination] = cost def AddUndirectedEdge(self, source, destination, cost=1): self.AddDirectedEdge(source, destination, cost) self.AddDirectedEdge(destination, source, cost) def Print(self): for i in range(self.count): print "Vertex " , i , " is connected to : ", for j in range(self.count): if self.adj[i][j] != 0: print j ,"" print("") graph = Graph(4) graph.AddUndirectedEdge(0, 1) graph.AddUndirectedEdge(0, 2) graph.AddUndirectedEdge(1, 2) graph.AddUndirectedEdge(2, 3) graph.Print() """ Vertex 0 is connected to : 1 2 Vertex 1 is connected to : 0 2 Vertex 2 is connected to : 0 1 3 Vertex 3 is connected to : 2 """ class PriorityQueue(object): def __init__(self): self.pQueue = [] self.count = 0 def Add(self, key, value): heapq.heappush(self.pQueue, (key, value)) def UpdateKey(self, key, value): heapq.heappush(self.pQueue, (key, value)) def Pop(self): val = heapq.heappop(self.pQueue) return val def Size(self): return len(self.pQueue) def printPath(count, previous, dist): for i in range(count): if dist[i] == sys.maxsize: print("node id" , i , "prev" , previous[i] , "distance : Unreachable") else: print("node id" , i , "prev" , previous[i] , "distance :" , dist[i]) def Dijkstra(gph, source): previous = [-1] * gph.count dist = [sys.maxsize] * gph.count visited = [False] * gph.count dist[source] = 0 previous[source] = -1 pq = PriorityQueue() for i in range(gph.count): pq.Add(sys.maxint, i) pq.UpdateKey(0, source) while pq.Size() != 0: val = pq.Pop() source = val[1] visited[source] = True for dest in range(gph.count): alt = gph.adj[source][dest] + dist[source] if gph.adj[source][dest] > 0 and alt < dist[dest] and visited[dest] == False: dist[dest] = alt previous[dest] = source pq.UpdateKey(alt, dest) printPath(graph.count, previous,dist) def Prims(gph): previous = [-1] * gph.count dist = [sys.maxsize] * gph.count visited = [False] * gph.count source = 0 dist[source] = 0 previous[source] = -1 pq = PriorityQueue() for i in range(gph.count): pq.Add(sys.maxint, i) pq.UpdateKey(0, source) while pq.Size() != 0: val = pq.Pop() source = val[1] visited[source] = True for dest in range(gph.count): alt = gph.adj[source][dest] if gph.adj[source][dest] > 0 and alt < dist[dest] and visited[dest] == False: dist[dest] = alt previous[dest] = source pq.UpdateKey(alt, dest) printPath(graph.count, previous,dist) """ graph = Graph(9) graph.AddUndirectedEdge(0, 1, 4) graph.AddUndirectedEdge(0, 7, 8) graph.AddUndirectedEdge(1, 2, 8) graph.AddUndirectedEdge(1, 7, 11) graph.AddUndirectedEdge(2, 3, 7) graph.AddUndirectedEdge(2, 8, 2) graph.AddUndirectedEdge(2, 5, 4) graph.AddUndirectedEdge(3, 4, 9) graph.AddUndirectedEdge(3, 5, 14) graph.AddUndirectedEdge(4, 5, 10) graph.AddUndirectedEdge(5, 6, 2) graph.AddUndirectedEdge(6, 7, 1) graph.AddUndirectedEdge(6, 8, 6) graph.AddUndirectedEdge(7, 8, 7) #Dijkstra(graph, 0) Prims(graph) # graph.Print() """ def HamiltonianCycleUtil(graph , path, added): # Base case: full length path is found # this last check can be modified to make it a path. if len(path) == graph.count: if graph.adj[ path[-1] ][ path[0] ] == 1: path.append(path[0]) return True else: return False for vertex in range(graph.count): # there is a path from last element and next vertex if graph.adj[path[-1]][vertex] == 1 and added[vertex] == False: path.append(vertex) added[vertex] = True if HamiltonianCycleUtil(graph, path, added): return True # backtracking path.pop() added[vertex] = False return False def HamiltonianCycle(graph): path = [] path.append(0) added = [False]*graph.count added[0] = True if HamiltonianCycleUtil(graph, path, added): print "Hamiltonian Cycle found", path return True print "Hamiltonian Cycle not found" return False def HamiltonianPathUtil(graph , path, added): # Base case: full length path is found if len(path) == graph.count: return True for vertex in range(graph.count): # there is a path from last element and next vertex # and next vertex is not already included in path. if graph.adj[path[-1]][vertex] == 1 and added[vertex] == False: path.append(vertex) added[vertex] = True if HamiltonianPathUtil(graph, path, added): return True # backtracking path.pop() added[vertex] = False return False def HamiltonianPath(graph): path = [] path.append(0) added = [False]*graph.count added[0] = True if HamiltonianPathUtil(graph, path, added): print "Hamiltonian Path found", path return True print "Hamiltonian Path not found" return False """ graph = Graph(5) graph.adj = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1,], [1, 1, 0, 0, 1], [0, 1, 1, 1, 0] ] print HamiltonianPath(graph) g2 = Graph(5) g2.adj = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1,], [1, 1, 0, 0, 0], [0, 1, 1, 0, 0] ] print HamiltonianPath(g2) """
915bee4e9ad5f90ff490470c05065b97d402209a
snehaljadhav7/Data-Science
/Assignment1/calculatingBMI.py
236
4.21875
4
#!/bin/python3 import math weight_pounds = int(input("Enter your weight in pounds:")) height_inches = int(input("Enter your height in inches:")) BMI=703*(weight_pounds / (height_inches*height_inches)) print("Your BMI is",round(BMI,1))
a714f0d37f8d54d4b139e574c0c5baa8bc7bd864
zenggang888/blogs
/Python/learning/函数.py
556
3.765625
4
def add_num(): total = 0 for i in range(1,101): print(i) total = total + i return total def factorial(n): total = 1 if n < 0: return None elif n == 0: return 1 else: for i in range(1,n+1): total = total*i return total print(factorial(-1)) print(factorial(0)) print(factorial(10)) def recursive(n): if n < 0: return None elif n == 0: return 1 else: return n * recursive(n-1) print(recursive(-1)) print(recursive(0)) print(recursive(10))
45b74623ce1696ab13f409c4f998195747f38b9c
UESTCYangHR/leecode_test
/search-in-rotated-sorted-array-ii.py
925
3.71875
4
# coding=utf-8 # @Time: 3/15/2019 2:45 PM from typing import List class Solution: def search(self, nums: List[int], target: int) -> bool: pol = len(nums) - 1 while pol > 0 and nums[pol] >= nums[pol-1]: pol -= 1 ans = self.binary_search(target, nums[:pol]) if ans == -1: ans = self.binary_search(target, nums[pol:]) if ans != -1: return True else: return False else: return True def binary_search(self, target, nums): index = -1 l = 0 r = len(nums) - 1 while l <= r: mid = (l + r) // 2 if nums[mid] < target: l = mid + 1 elif nums[mid] > target: r = mid - 1 else: index = mid break return index
49e4e7cad6bd0566409a5fa4a376e3a597662ead
prpllrhd/morePYTHON
/cookbook/lambda/lambda1.py
343
3.796875
4
#!/usr/bin/env python3 """ example: using lambda key to sort a tuple of second field instead of first one """ import os def script(): pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[1]) print (pairs) def help(): print (__doc__) def main(): help() script() if __name__=="__main__": main()
5956a08c5b5435b8593de27a82b46eb31dc7ef16
maecchi/PE
/pe055.py
549
3.765625
4
#!/usr/bin/env python #-*- coding: utf-8 -*- # # pe055.py - Project Euler # LIMIT = 10000 count = 0 # 数字が回文数であるかを判定する def isPalindrome (number): digit_number = list(str(number)) reverse_digit_number = digit_number[::-1] return digit_number == reverse_digit_number def checkPalindrome(number): for x in xrange(1, 50): number += int(''.join(list(str(number))[::-1])) if isPalindrome(number): return True return False for x in xrange(1, LIMIT): if not checkPalindrome(x): count += 1 print count
1caec6ff5e1fe41f901c362842a041b19b1c0550
grrrrnt/smart-parking
/MissingDigit.py
5,507
3.875
4
import re pre = str() num = str() suf = str() numCheck = str() numCorrect = str() def sufValue(str): switcher = { "A": 0, "Z": 1, "Y": 2, "X": 3, "U": 4, "T": 5, "S": 6, "R": 7, "P": 8, "M": 9, "L": 10, "K": 11, "J": 12, "H": 13, "G": 14, "E": 15, "D": 16, "C": 17, "B": 18 } return switcher.get(str) def convertint(x): return ord(x)-96 print ("NOTE: ONLY APPLIES FOR SINGLE MISSING DIGIT IN LICENSE PLATE NUMBER\n") # pre = input("Enter prefix: ").lower() # num = input("Enter visible numbers: ") # suf = input("Enter suffix: ") while True: prenumsuf = str() prenumsuf = input("Enter license plate, including prefix and suffix: ") try: num = (re.findall('\d+', prenumsuf))[0] except: print("Error: The license plate is not valid.") continue numDef = num pre = (re.findall("[a-zA-Z]+", prenumsuf))[0].lower() suf = (re.findall("[a-zA-Z]+", prenumsuf))[1] if int(num[:1]) == 0: numCheck = num # To verify answer later, if num input starts with 0 (converted to int later) if len(pre) == 3: preTrunc = str(pre[1:3]) elif len(pre) == 2: preTrunc = pre elif len(pre) == 1: preTrunc = "`"+pre else: print("Error: Please ensure the prefix is correct.") exit() if len(num) > 4 or len(num) < 1: print("Error: The license plate is not valid.") continue elif len(num) == 1: num = "00"+num elif len(num) == 2: num = "0"+num if len(suf) != 1: print("Error: Please ensure the suffix is correct.") continue preValue1 = int(convertint(preTrunc[0]))*9 preValue2 = int(convertint(preTrunc[1]))*4 # Values if first digit is missing numFirstValue1 = int(num[0])*4 numFirstValue2 = int(num[1])*3 numFirstValue3 = int(num[2])*2 # Values if second digit is missing numSecondValue1 = int(num[0])*5 numSecondValue2 = int(num[1])*3 numSecondValue3 = int(num[2])*2 # Values if third digit is missing numThirdValue1 = int(num[0])*5 numThirdValue2 = int(num[1])*4 numThirdValue3 = int(num[2])*2 # Values if fourth digit is missing numFourthValue1 = int(num[0])*5 numFourthValue2 = int(num[1])*4 numFourthValue3 = int(num[2])*3 totalValue1 = preValue1 + preValue2 + numFirstValue1 + numFirstValue2 + numFirstValue3 totalValue2 = preValue1 + preValue2 + numSecondValue1 + numSecondValue2 + numSecondValue3 totalValue3 = preValue1 + preValue2 + numThirdValue1 + numThirdValue2 + numThirdValue3 totalValue4 = preValue1 + preValue2 + numFourthValue1 + numFourthValue2 + numFourthValue3 # If first digit is missing arbValue = list(range(1,20)) numList1 = list() try: numList1 = [19*i + sufValue(suf.upper()) - totalValue1 for i in arbValue] except: print("Error: Please ensure the suffix is correct.") continue for i in numList1: if (i%5 == 0) and (i/5 <= 9) and (i/5 >= 0): numCorrect = str(1000*int(i/5) + int(num)) if numCheck in numCorrect and len(numCorrect)-len(numDef) <= 1: # To check for cases where num input started with 0 print("The actual license plate may be: " + pre.upper() + numCorrect + suf.upper()) else: i = i + 1 # If second digit is missing numList2 = list() numList2 = [19 * i + sufValue(suf.upper()) - totalValue2 for i in arbValue] for i in numList2: if (i % 4 == 0) and (i / 4 <= 9) and (i / 4 >= 0): numCorrect = str(100*int(i/4) + 1000*int(num[:1]) + int(num[1:])) if numCheck in numCorrect and len(numCorrect)-len(numDef) <= 1: print("The actual license plate may be: " + pre.upper() + numCorrect + suf.upper()) else: i = i + 1 # If third digit is missing numList3 = list() numList3 = [19 * i + sufValue(suf.upper()) - totalValue3 for i in arbValue] for i in numList3: if (i % 3 == 0) and (i / 3 <= 9) and (i / 3 >= 0): numCorrect = str(10*int(i/3) + 100*int(num[:2]) + int(num[2:])) if numCheck in numCorrect and len(numCorrect)-len(numDef) <= 1: print("The actual license plate may be: " + pre.upper() + numCorrect + suf.upper()) else: i = i + 1 # If fourth digit is missing numList4 = list() numList4 = [19 * i + sufValue(suf.upper()) - totalValue4 for i in arbValue] for i in numList4: if (i % 2 == 0) and (i / 2 <= 9) and (i / 2 >= 0): numCorrect = str(int(i/2) + 10*int(num)) if numCheck in numCorrect and len(numCorrect)-len(numDef) <= 1: print("The actual license plate may be: " + pre.upper() + numCorrect + suf.upper()) else: i = i + 1 exitCmd = str() exitCmd = input("Exit? Y/N -- ") if exitCmd == "Y" or exitCmd == "y": break elif exitCmd == "N" or exitCmd == "n": continue