blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
6558d052e684878a271533df745aa0aaf398d710
apollo-chiu/password-retry
/pssw-try3.py
267
3.84375
4
key = 'a123456' x = 3 while x > 0: x = x - 1 psw = input('請輸入密碼: ') if psw == key: print('登入成功!') break else: print('密碼錯誤!') if x > 0: print('還有', x, '次機會') else: print('沒機會嘗試了! 要鎖帳號了啦!')
a9540bff47bfe8f9939f81c00fefa3348e91675c
tianshuaifei/kaggle
/feature.py
1,222
3.890625
4
import numpy as np #类别变量处理 treat categorical features as numerical ones #1 labelencode #2 frequency encoding #3 mean-target encoding #https://www.kaggle.com/c/petfinder-adoption-prediction/discussion/79981 # Mean-target encoding is a popular technique to treat categorical features as numerical ones. # The mean-target encoded value of one category is equal to the mean target of all samples of # the corresponding category (plus some optional noise for regularization). from sklearn.preprocessing import LabelEncoder for name in f_feature: lab = LabelEncoder() data["le_" + name] = lab.fit_transform(data[name].astype("str")) data["%s_count_num"%fea]=data[fea].map(data[fea].value_counts(dropna=False)) def frequency_encoding(variable): t = df_train[variable].value_counts().reset_index() t = t.reset_index() t.loc[t[variable] == 1, 'level_0'] = np.nan t.set_index('index', inplace=True) max_label = t['level_0'].max() + 1 t.fillna(max_label, inplace=True) return t.to_dict()['level_0'] for variable in ['age', 'network_age']: freq_enc_dict = frequency_encoding(variable) data[variable+"_freq"] = data[variable].map(lambda x: freq_enc_dict.get(x, np.nan))
69b848ed2eeae8f3090a9c35b2cdf12bc4dd29e5
Rita626/HK
/Leetcode/237_刪除鏈表中的節點_05170229.py
1,671
4.21875
4
#題目:请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = None #直觀的認為可以直接刪除 #結果:答案錯誤,只是將要刪除的值變為None而已 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = None #改為以下一節點取代要刪除的值,並將(想像中)重複的下一個節點刪除 #結果:答案錯誤,題目要求的值卻時刪除了,但也將後面的值刪掉了 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next #同樣以下一節點取代要刪除的值,並將後面節點整個前移 #結果:通過,用時28ms,內存消耗13MB
4e485050a23b744142df8dc609002818dd9044c9
Eduardo-Chavez/Unidad2Evaluacio-n
/Iniciales_login.py
194
3.9375
4
usuario = input ("Ingresa tu usuario: ") contra = input ("Ingesa tu contraseña: ") if usuario == "utng" and contra == "mexico": print ("Bienvenido") else: print ("Datos incorrectos")
2991c345efe646cedda8aeaeeebe06b2a4cc6842
drmason13/euler-dream-team
/euler1.py
778
4.34375
4
def main(): """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ test() print(do_the_thing(1000)) def do_the_thing(target): numbers = range(1, target) answer = [] for i in numbers: #print(i) if is_multiple_of(i, 3) or is_multiple_of(i, 5): answer.append(i) #ends here => i won't be a thing after this return(sum(answer)) def test(): result = do_the_thing(10) if result == 23: print("success") print(result) else: print("check again pinhead") print(result) def is_multiple_of(num, multiple): #print("is_multiple_of") return num % multiple == 0 main()
0c9c7fbf5ea0ed3591fd4aee2c9ac9de4b2392a6
paulbradshaw/scrapers
/festivaltweetsjson.py
1,713
3.65625
4
#!/usr/bin/env python import json import csv import requests import urllib import scraperwiki jsonurlgh = 'https://raw.githubusercontent.com/paulbradshaw/scraping-for-everyone/gh-pages/webpages/cheltenhamjazz-export.json' jsonurl = 'https://paulbradshaw.github.io/scraping-for-everyone/webpages/cheltenhamjazz-export.json' trumpjson = 'https://petition.parliament.uk/petitions/178844.json' #fetch the json from the URL response = urllib.urlopen(jsonurl) #load it into variable called x x = json.loads(response.read()) #let's see what we have print x print len(x) #drill down a bit into the 'posts' branch which contains everything print x['posts'] #store that in a new variable posts = x['posts'] #how many items? print len(x['posts']) #this only grabs the ID number of each #create an empty list to store the ID numbers, which we can then loop through to grab each tweet postids = [] for post in posts: print post postids.append(post) #create empty dict to store the data record = {} #loop through the codes for code in postids: print x['posts'][code] #test that we can grab the text print x['posts'][code]['text'] #start storing each field in the dict record['text'] = x['posts'][code]['text'] record['authorid'] = x['posts'][code]['author'] try: record['imageurl'] = x['posts'][code]['image'] except KeyError: record['imageurl'] = 'NULL' record['lon'] = x['posts'][code]['lon'] record['lat'] = x['posts'][code]['lat'] record['timestamp'] = x['posts'][code]['timestamp'] #this is the tweet code that we are using record['tweetid'] = code record['fulljson'] = str(x['posts'][code]) scraperwiki.sql.save(['tweetid'], record)
1ce80703b6e762b4913a7c906fc23143363e2bae
paulbradshaw/scrapers
/westminstercouncilevents.py
1,660
3.578125
4
#!/usr/bin/env python import scraperwiki import urlparse import lxml.html import urllib2 import datetime #more on datetime here: https://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/ now = datetime.datetime.now() currentmonth = now.month currentyear = now.year currentday = now.day print str(now) print "Current month: %d" % currentmonth print "Current year: %d" % currentyear print "Current day: %d" % currentday baseurl = "http://committees.westminster.gov.uk/" #Note the M=6 part of the URL and DD=2018 - these will need to be updated with the current month/year - also D=26 with day juneurl = "http://committees.westminster.gov.uk/mgCalendarAgendaView.aspx?MR=0&M=6&DD=2018&CID=0&OT=&C=-1&D=26" latesturl = "http://committees.westminster.gov.uk/mgCalendarAgendaView.aspx?MR=0&M="+str(currentmonth)+"&DD="+str(currentyear)+"&CID=0&OT=&C=-1&D="+str(currentday) print latesturl record = {} headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} timeout=0.25 req = urllib2.Request(latesturl, None, headers) #adapting some of the code from https://stackoverflow.com/questions/3569152/parsing-html-with-lxml doc = lxml.html.parse(urllib2.urlopen(req)) print doc listlinks = doc.xpath('//ul[@class="mgCalendarWeekEventList"]/li/a') print len(listlinks) for link in listlinks: print link.text_content() print link.attrib['href'] record['event'] = link.text_content() record['url'] = baseurl+link.attrib['href'] record['searchurl'] = latesturl scraperwiki.sqlite.save(['url'], record, table_name="westminsterevents")
01c12a1ab03ab87a404dbd42b9a755be0ed03173
maymashd/BFDjango
/week 1/Informatics mcc/Cycle While/D.py
151
3.5625
4
import math n=int(input()) i=1 ok=False while i<=n: if i==n: ok=True i=i*2 if (ok==True): print("YES") else: print ("NO")
e2e7128884e11dbc5dba935b8986c987663633db
maymashd/BFDjango
/week 1/Informatics mcc/Array/B.py
140
3.609375
4
import array n=int(input()) a=input() arr=a.split(" ") for i in range(0,len(arr)): if (int(arr[i])%2==0): print(arr[i],end=' ')
5ff1f253950b663e79b8d4450e458aa43937d802
maymashd/BFDjango
/week 1/Informatics mcc/Cycle For/K.py
105
3.5
4
import math cnt=0 n=int(input()) for i in range(1,n+1): a=int(input()) cnt=cnt+a print(cnt)
27662057212e19516566758c0cdde3eb883a90a2
valeriuursache/scratchpad
/module 3/cat_strings.py
637
3.71875
4
if __name__ == "__main__": #Concatenation #You can concatenate two strings together using + leia = "I love you." han = "I know." print(leia + ' ' + han) ship = "Millinium Falcon" # Python starts at 0, slices TO the end index (not included) print("'" + ship[10:] + "'") bold_statement = ship + "is the fastest in the galaxy" print (bold_statement) print(ship) ship = 'S' + ship[1:] print(ship) jedi_masters = "Obi-Wan Kenobi, Qui-Gon Gin" print('Anakin' in jedi_masters) council_mermbers = ("Anakin, Obi-Wan Kenobi, Yoda, Qui-Gon Gin") print('Anakin' in council_mermbers)
6f1aa43d0614cd211b0c92a48b182cf662e230fa
nmaswood/Random-Walk-Through-Computer-Science
/lessons/day4/exercises.py
720
4.25
4
def fib_recursion(n): """ return the nth element in the fibonacci sequence using recursion """ return 0 def fib_not_recursion(n): """ return the nth element in the fibonacci sequence using not recursion """ return 0 def sequence_1(n): """ return the nth element in the sequence S_n = S_{n-1} * 2 + 1 """ return 0 def factorial_recursive(n): """ Calculate the factorial of n using recursion """ return 0 class LinkedList(): def __init__(self, val): self.val = val self.next = None """ Use the LinkedList Data Type Create a linked list with the elements "fee" -> "fi" -> "foo" -> "fum" and print it backwards """
5f31e4cdf81801c19d737535ca94fb49ceab59fb
dangriffin13/Project_Euler
/euler21_amicable_numbers.py
662
3.578125
4
import math t = int(input()) def sum_of_divisors(number): s = 0 stop = int(math.floor(math.sqrt(number))) for i in range(2,stop): if number%i == 0: s += i + number/i return int(s+1) amicable_numbers = [] for i in range(100001): y = sum_of_divisors(i) if sum_of_divisors(y) == i and i != y and i not in amicable_numbers: if y < 100001: amicable_numbers.extend([i, y]) #print(amicable_numbers) else: amicable_numbers.append(i) #print(amicable_numbers) for _ in range(t): n = int(input()) print(sum([i for i in amicable_numbers if i < n]))
cd4d8070eeaa1eff50473cb6d89f3cedbf973b66
LawlessJ/Object_Oriented_Programming_Project
/Script.py
2,987
3.703125
4
from datetime import datetime class Menu: def __init__(self, name, items, start_time, end_time): self.name = name self.items = items self.start_time = datetime.strptime(start_time, "%I %p") self.end_time = datetime.strptime(end_time, "%I %p") self.times = [self.start_time, self.end_time] def __repr__(self): return "We are currently serving {name} menu items from {start} until {end}.".format(name = self.name, start=self.start_time, end=self.end_time) def calculate_bill(self, purchased_items): #2 arg is a list total_bill = 0 for item in purchased_items: total_bill += self.items.get(item, 0) return total_bill class Franchise: def __init__(self, address, menus): self.address = address self.menus = menus def __repr__(self): return "This location of Basta Fazzoolin can be found at {address}.".format(address = self.address) def available_menus(self, time): the_time = datetime.strptime(time, "%I %p") for menu_items in range(len(self.menus)): if the_time >= self.menus[menu_items].start_time and the_time <= self.menus[menu_items].end_time: print(self.menus[menu_items]) class Business: def __init__(self, name, franchises): self.name = name self.franchises = franchises brunch = Menu("Brunch", {'pancakes': 7.50, 'waffles': 9.00, 'burger': 11.00, 'home fries': 4.50, 'coffee': 1.50, 'espresso': 3.00, 'tea': 1.00, 'mimosa': 10.50, 'orange juice': 3.50}, "11 AM", "4 PM") #print(brunch.items) #print(brunch.start_time) early_bird = Menu("Early-bird", {'salumeria plate': 8.00, 'salad and breadsticks (serves 2, no refills)': 14.00, 'pizza with quattro formaggi': 9.00, 'duck ragu': 17.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 1.50, 'espresso': 3.00,},"3 PM", "6 PM") #print(early_bird.start_time) dinner = Menu("Dinner", {'crostini with eggplant caponata': 13.00, 'ceaser salad': 16.00, 'pizza with quattro formaggi': 11.00, 'duck ragu': 19.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00,},"5 PM","11 PM") kids = Menu("Kids Menu", {'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00}, "11 AM","9 PM") #print(brunch) #print(brunch.items) #print(brunch.calculate_bill(["pancakes", "home fries", "coffee"])) #print(early_bird.calculate_bill(["salumeria plate", "mushroom ravioli (vegan)"])) flagship_store = Franchise("1232 West End Road", [brunch, early_bird, dinner, kids]) new_installment = Franchise("12 East Mulberry Street", [brunch, early_bird, dinner, kids]) #print(new_installment.available_menus("12 PM")) #print(new_installment.available_menus("5 PM")) bus_1 = Business("Basta Fazoolin' with my Heart", [flagship_store, new_installment]) arepas_menu = Menu("Take a' Arepa", {'arepa pabellon': 7.00, 'pernil arepa': 8.50, 'guayanes arepa': 8.00, 'jamon arepa': 7.50}, "10 AM", "8 PM") arepas_place = Franchise("189 Fitzgerald Avenue", [arepas_menu]) bus_2 = Business("Take a' Arepa", [arepas_place])
51ed6228cc6ff33b400a250782b2b0d9b16daf09
RohilH/Convolutional-Neural-Network-using-TensorFlow
/cnnTensorFlow.py
2,468
3.515625
4
from keras.models import Sequential from keras.layers import Dense, Conv2D, Flatten import matplotlib.pyplot as plt from keras.datasets import mnist from keras.utils import to_categorical import numpy as np # (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = np.load("data/x_train.npy") X_train = (X_train - np.mean(X_train, axis=0)) / np.std(X_train, axis=0) y_train = np.load("data/y_train.npy") X_test = np.load("data/x_test.npy") X_test = (X_test - np.mean(X_test, axis=0))/np.std(X_test, axis=0) y_test = np.load("data/y_test.npy") #--------------------------------------------- X_train = X_train.reshape(50000,28,28,1) X_test = X_test.reshape(10000,28,28,1) y_train = to_categorical(y_train) y_test = to_categorical(y_test) ''' The code above simply loads the data and one-hot encode it. We load the MNIST data from the files given to us. ''' #--------------------------------------------- #create model model = Sequential() # allows us to create model step by step #add model layers ''' Kernel size is typically 3 or 5. Experimenting with a value of 4 didn't decrease the accuracy significantly, i.e. only by like 1% or so. ''' model.add(Conv2D(64, kernel_size=5, activation='tanh', input_shape=(28,28,1))) # Adds a convolution layer ''' Each model.add(Conv2D...) essentially adds another layer to the neural network. Instead of using an affine forward to do so, we depend on a convolution instead, taking a square cluster of kernel_size, and looping through the image. At each iteration of the for loop, we take the convolution of the feature (the square cluster) and the part of the image that we're on. Once we do this, we can get a 2D array using the answers from each convolution, based on where in the image each patch is located. ''' model.add(Conv2D(32, kernel_size=3, activation='tanh')) model.add(Flatten()) # Turns 2d array into 1d array model.add(Dense(10, activation='softmax')) # condenses layers down into final 10 classes # compile model using accuracy as a measure of model performance model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ''' Optimizer: 'Adam' an optimizer that adjusts the learning rate while training loss: categorical_crossentropy most commonly used in classification metrics: prints accuracy of CNN ''' #train model model.fit(X_train, y_train,validation_data=(X_test, y_test), epochs=3) # Runs the model
bed140408d860cdaa01ba616ac984a3beb4029ae
benoitantelme/python_ds_ml_bootcamp
/05-Data-Visualization-with-Matplotlib/02-Matplotlib Exercises.py
3,412
3.75
4
#!/usr/bin/env python # coding: utf-8 # ___ # # <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> # ___ # # Matplotlib Exercises # # Welcome to the exercises for reviewing matplotlib! Take your time with these, Matplotlib can be tricky to understand at first. These are relatively simple plots, but they can be hard if this is your first time with matplotlib, feel free to reference the solutions as you go along. # # Also don't worry if you find the matplotlib syntax frustrating, we actually won't be using it that often throughout the course, we will switch to using seaborn and pandas built-in visualization capabilities. But, those are built-off of matplotlib, which is why it is still important to get exposure to it! # # ** * NOTE: ALL THE COMMANDS FOR PLOTTING A FIGURE SHOULD ALL GO IN THE SAME CELL. SEPARATING THEM OUT INTO MULTIPLE CELLS MAY CAUSE NOTHING TO SHOW UP. * ** # # # Exercises # # Follow the instructions to recreate the plots using this data: # # ## Data # In[1]: import numpy as np x = np.arange(0, 100) y = x * 2 z = x ** 2 # ** Import matplotlib.pyplot as plt and set %matplotlib inline if you are using the jupyter notebook. What command # do you use if you aren't using the jupyter notebook?** # In[3]: import matplotlib.pyplot as plt # ## Exercise 1 # # ** Follow along with these steps: ** # * ** Create a figure object called fig using plt.figure() ** # * ** Use add_axes to add an axis to the figure canvas at [0,0,1,1]. Call this new axis ax. ** # * ** Plot (x,y) on that axes and set the labels and titles to match the plot below:** # In[4]: fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) ax.plot(x, y) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('title') # ## Exercise 2 # ** Create a figure object and put two axes on it, ax1 and ax2. Located at [0,0,1,1] and [0.2,0.5,.2,.2] # respectively.** # In[39]: fig2 = plt.figure() ax21 = fig2.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) ax22 = fig2.add_axes([0.2, 0.5, .2, .2]) # ** Now plot (x,y) on both axes. And call your figure object to show it.** # In[42]: ax21.plot(x, y) ax22.plot(x, y) # ## Exercise 3 # # ** Create the plot below by adding two axes to a figure object at [0,0,1,1] and [0.2,0.5,.4,.4]** # In[6]: fig3 = plt.figure() ax31 = fig3.add_axes([0.1, 0.1, 0.9, 0.9]) # left, bottom, width, height (range 0 to 1) ax32 = fig3.add_axes([0.17, 0.5, .4, .4]) # ** Now use x,y, and z arrays to recreate the plot below. Notice the xlimits and y limits on the inserted plot:** # In[5]: ax31.plot(x, z) ax31.set_xlabel('x') ax31.set_ylabel('z') ax32.plot(x, y) ax32.set_xlabel('x') ax32.set_ylabel('y') ax32.set_title('zoom') # ## Exercise 4 # # ** Use plt.subplots(nrows=1, ncols=2) to create the plot below.** # In[48]: fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,2)) # ** Now plot (x,y) and (x,z) on the axes. Play around with the linewidth and style** # In[51]: axes[0].plot(x, y, 'g') axes[0].set_xlabel('x') axes[0].set_ylabel('y') axes[0].set_title('plot 1') axes[1].plot(x, z, 'r') axes[1].set_xlabel('x') axes[1].set_ylabel('z') axes[1].set_title('plot 2') plt.show() # ** See if you can resize the plot by adding the figsize() argument in plt.subplots() are copying and pasting your # previous code.** # In[32]: # # Great Job!
d460b9928fa6276cd94ab510d3c24b7aa8932a34
shanefay/MachineLearning
/assignment2/estimate_scorer.py
2,528
3.515625
4
from sklearn.metrics import make_scorer from sklearn.model_selection import train_test_split, cross_validate def split_estimate(estimator, X, y, metrics, test_size=0.3): """Score an estimated model using a simple data split. A 70/30 split of training to testing data is used by default. Args: estimator: Scikit-learn model estimator. X: Feature data matrix. y: Target data array. metrics: Metrics to be used for scoring the estimated model. A Dictionary of metric names to metric evaluation functions. e.g. {'accuracy': scklearn.metrics.accuracy_score, etc.} test_size (optional): The proportion of the data to be used for testing. Returns: A dictionary of metric names to scores. The scores are the metrics on the test targets verses predicted targets. """ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, shuffle=False) estimator.fit(X_train, y_train) y_pred = estimator.predict(X_test) # print(y_test,y_pred) # print(y_test.min) return {name: metric(y_test, y_pred) for name, metric in metrics.items()} def cross_val_estimate(estimator, X, y, metrics, k_fold=20): """Score an estimated model using k-fold cross validation. 20-fold cross validation is used by default. Args: estimator: Scikit-learn model estimator. X: Feature data matrix. y: Target data array. metrics: Metrics to be used for scoring the estimated model. A Dictionary of metric names to metric evaluation functions. e.g. {'accuracy': scklearn.metrics.accuracy_score, etc.} test_size (optional): The proportion of the data to be used for testing. Returns: A dictionary of metric names to scores. The scores are the metrics on the k-fold test targets verses predicted targets. As there are k-fold test sets, the mean of each metric is taken as the scores with a confidence interval (20-fold gives 90% CI). """ scoring = {name: make_scorer(metric) for name, metric in metrics.items()} scores = cross_validate(estimator, X, y, cv=k_fold, scoring=scoring) return {name: confidence_interval_score(scores['test_' + name]) for name in scoring} def confidence_interval_score(score_list): mean = score_list.mean() score_list.sort() low = score_list[1] high = score_list[-2] return '{:.3f} [{:+.3f}, {:+.3f}]'.format(mean, low-mean, high-mean)
4d0f3b2e8eb544407de5ed9cd04ef2347628ff19
Inlinesoft/POC.ECS.Python.App
/utilities/email.py
2,975
3.59375
4
import smtplib import definitions class Email: """ Send out emails (with or without attachments) using this class. Usage: With attachment email = Email(server_name) email.send_mail(send_from, send_to, subject, text, files) Without attachment email = Email() email.send_mail(send_from, send_to, subject, text) """ # variable _user_name = None _server = None # methods def __init__(self): """ This method initialises the local variable :return: none """ # Initialize the User name self._server = smtplib.SMTP(definitions.EMAIL_PRIMARY_SMTP_ADDRESS, 587) self._user_name = definitions.EMAIL_ACCOUNT_USERNAME self._password = definitions.EMAIL_ACCOUNT_PASSWORD self._server = smtplib.SMTP('smtp.gmail.com') self._server.ehlo() self._server.starttls() self._server.login(self._user_name, self._password) def __str__(self): """ This is to return the calss name, which will can be used to pass to the logging methods :return: A string with class details """ ret_data = f"<<{self.__class__.__name__}>> :: " return ret_data def set_user_name(self, user_name): """ setter method for user_name :param user_name: :return: """ self._user_name = user_name def get_user_name(self): """ getter method for username :param user_name: :return: """ return self._user_name def set_password(self, password): """ setter method for password :param password: :return: """ self._password = password def get_password(self): """ getter method for password :param password: :return: """ return self._password def set_smtp_server(self, value): """ setter method for server :param value: :return: """ self._server = value def get_smtp_server(self): """ getter method for smtp server :return: """ return self._server def send_mail_using_smtp(self, send_from, send_to, subject, text, files=None, text_type='text'): """ Send mail sends out email to list of email participants :param send_from: :param send_to: :param subject: :param text: :param files: :param server: :return: """ is_email_sent = True try: body = '\r\n'.join(['To: %s' % send_to, 'From: %s' % send_from, 'Subject: %s' % subject, '', text]) self._server.sendmail(send_from, send_to, body) except Exception as exp: raise (exp) return is_email_sent
2512b1f39ae0d570fae3dda36f2950254a085549
jfernand196/Ejercicios-Python
/funcion_all.py
146
3.71875
4
# verificarf que todos los items iteravles cumplan una condicion lista = [2, 4, 6, 7] print(all(x > 4 for x in lista)) h = "juan" print(type(h))
60dab56c8c06bc13f3c182ec1dbb11832298c6d2
jfernand196/Ejercicios-Python
/farmeteos de string y float.py
190
3.734375
4
palabra = "!aprendiendo python!" print("%.6s" % palabra) print("%.12s" % palabra) real = 2.6578 print("valor es: %f" % real) print("valor es: %.2f" % real) print("valor es: %.13f" % real)
1bb1c0e327300b98526b91d88217cd75360260bf
jfernand196/Ejercicios-Python
/concatenar_lista.py
319
3.53125
4
# simular la funcion join numeros = [2,4,5,77] #opcion 1 #print('juan'.join([str(n) for n in numeros])) #print('juan'.join(numeros)) #opcion 2 def concatenar_listas(lista): resultado= '' for i in lista: resultado +=str(i) return resultado numeros = [2,4,5,77] print(concatenar_listas(numeros))
30163909aeaaa4efaa8d27365f4631b18390aab4
jfernand196/Ejercicios-Python
/operador_not.py
382
3.53125
4
#Operador logico de negacion de verdad: NOT print('Operador logico de negacion de verdad : NOT') llueve = True print('contenido de la variable llueve:', llueve) llueve = not llueve print('contenido de la variable llueve:', llueve) print() edad = 17 resultado = not edad < 18 print('Resultado', resultado) edad = 19 resultado = not edad < 18 print('Resultado', resultado)
7b884b25dd4b1f427e61c8259d7673e9f49706cb
jfernand196/Ejercicios-Python
/makeitreal03.py
390
3.953125
4
# Duplica cada elemento # Escribe una función llamada duplicar que reciba un arreglo de números como parámetro y retorne un # nuevo arreglo con cada elemento duplicado (multiplicado por dos). # duplicar([3, 12, 45, 7]) # retorna [6, 24, 90, 14] # duplicar([8, 5]) # retorna [16, 10] def duplicar(x): return [i*2 for i in x] print(duplicar([3, 12, 45, 7])) print(duplicar([8, 5]))
42d3e9a30261a005a547a0957c4e53d2a19d5911
jfernand196/Ejercicios-Python
/examen_makeitreal.py
610
4.21875
4
# Temperaturas # Escribe una función llamada `temperaturas` que reciba un arreglo (que representan temperaturas) y # retorne `true` si todas las temperaturas están en el rango normal (entre 18 y 30 grados) o `false` de # lo contrario. # temperaturas([30, 19, 21, 18]) -> true # temperaturas([28, 45, 17, 21, 17, 70]) -> false def temperaturas(x): r= [] for i in x: o=0 if i>= 18 and i<=30: r.append(i) return r print(temperaturas([30, 19, 21, 18])) #-> true print(temperaturas([28, 45, 17, 21, 17, 70])) #-> false
661cafb9861064d8006a56dceaf4177a0131bf31
jfernand196/Ejercicios-Python
/gen_num_primos.py
652
3.578125
4
## Generar n cantidad de numeros primos consecutivos # 2, 3, 5, 7, 11 ... def generar_primo(): numero = 2 yield numero while True: temp = numero while True: temp += 1 contador = 1 contador_divisores = 0 while contador <= temp: if temp % contador == 0: contador_divisores +=1 if contador_divisores > 2: break contador += 1 if contador_divisores == 2: yield temp g = generar_primo() primos = [next(g) for _ in range(20)] print(primos)
38b85a7e4050e345f3b1eedadb288fcec5dad51a
jfernand196/Ejercicios-Python
/letcode_1678.py
855
4.09375
4
# You own a Goal Parser that can interpret a string command. The command consists of an alphabet # of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", # "()" as the string "o", and "(al)" as the string "al". The interpreted strings are # then concatenated in the original order. # Given the string command, return the Goal Parser's interpretation of command. # Example 1: # Input: command = "G()(al)" # Output: "Goal" # Explanation: The Goal Parser interprets the command as follows: # G -> G # () -> o # (al) -> al # The final concatenated result is "Goal". # Example 2: # Input: command = "G()()()()(al)" # Output: "Gooooal" # Example 3: # Input: command = "(al)G(al)()()G" # Output: "alGalooG" command = "G()()()()(al)" output = command.replace('()', 'o').replace('(al)', 'al') print(output)
342bd4524146685a04fb5bbc20fe03f51d4baedd
jfernand196/Ejercicios-Python
/try_except_else_finally.py
435
3.921875
4
# Programa que le pide al usuario la edad (edad entero) y comprueba #si ese usuario es mayor de edad (18 años) try: numero = int(input('introduce tu edad: ')) except ValueError: print('no has introduciod un nuemero entero') else: if numero >= 18: print('eres mayo de edad') else: print('no eres mayor de edad') finally: print('el codigo ha terminado') ## finally se ejecuta siempre
d13db4be9d30a72dbe1edb5af5178d3b897fbf4d
jfernand196/Ejercicios-Python
/area_triangulo.py
466
3.859375
4
## Calcular el area de un triangulo base = None altura = None while True: try: base = float(input('escriba la base del triangulo: ')) break except: print('Debe de escribir un numero.') while True: try: altura = float(input('escriba la altura del triangulo: ')) break except: print('Debe de escribir un numero.') area = base * altura / 2 print("el area del triangulo es igual a {}".format(area))
2b8f6de2b9ac1a87bbc8a2e27df982fb72bef80f
ChetanVDhawan/PythonDataStructures
/LinkedList.py
2,290
4.03125
4
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.start = None def add(self, data): node = Node(data) if self.start is None: self.start = node return temp = self.start while temp.next is not None: temp = temp.next temp.next = node def pop(self): if self.start is None or self.start.next is None: self.start = None print("[]") return temp = self.start while temp.next.next is not None: temp = temp.next temp.next = None def delete(self,data): if self.start is None: print("Nothing to delete") if self.start.data == data: self.start = self.start.next temp = self.start while temp.next is not None: if temp.next.data == data: temp.next = temp.next.next return temp =temp.next print("Data isnt in list") def length(self): count = 0 temp = self.start while temp is not None: count=count+1 temp = temp.next print(f"count is {count}") return count def insert(self,position,data): count = 0 node = Node(data) if position == 0: self.start,self.start.next = node,self.start return temp = self.start while temp is not None: if position > 0 and position <= self.length(): if count == position -1: temp.next, temp.next.next = node, temp.next else: print("Index out of bounds") return temp = temp.next count = count + 1 def print(self): temp = self.start while temp is not None: print(temp.data) temp = temp.next if __name__ == "__main__": l1 = LinkedList() l1.add("Chetan") l1.add("Dhawan") l1.add("Prasad") l1.add("yui") l1.add("Raj") l1.delete("hasdhs") l1.print() print("=============") l1.length() l1.insert(5,"DID") l1.print() print("=============")
59b2ff13da21c4d38f95749450ba726579c69209
piranna/asi-iesenlaces
/0708/listas/ej234.py
568
3.96875
4
# -*- coding: cp1252 -*- #$Id$ """ Disea un programa que elimine de una lista todos los elementos de valor par y muestre por pantalla el resultado. (Ejemplo: si trabaja con la lista [1, -2, 1, -5, 0, 3] sta pasar a ser [1, 1, -5, 3].) """ # mtodo 1: con while lista = [1, -2, 1, -5, 0, 3] i = 0 while i < len(lista): if lista[i] % 2 == 0: del lista[i] else: i += 1 print lista # mtodo 2: usar remove lista = [1, -2, 1, -5, 0, 3] for el in lista: if el%2 == 0: lista.remove(el) print lista
bae04ed2f85dc7b04153764d391fedf3f3148106
piranna/asi-iesenlaces
/0708/examenes/27feb/1234.py
3,292
3.765625
4
# -*- coding: utf-8 -*- def listadoAlumnos(listaAlumnos, curso, grupo=0): """ Entrada: una lista de alumnos como la indicada anteriormente, el nombre de un curso y opcionalmente el número de un grupo. Devuelve una lista con los datos de los alumnos del curso y grupo indicados. Si no se indica grupo, devolverá todos los alumnos del curso indicado. """ resultado = [] for alumno in listaAlumnos: if grupo: if alumno[1] == curso and alumno[2]==grupo: resultado.append(alumno) else: if alumno[1] == curso: resultado.append(alumno) return resultado def media(notas): return sum(notas)/len(notas) def alumnoMedia(listaAlumnos): """ Entrada: una lista de alumnos como la indicada anteriormente. Devuelve una lista de parejas: nombre de alumno, media de las notas. """ resultado = [] for al in listaAlumnos: resultado.append([al[0], media(al[-1])]) return resultado def listadoDeAlumnosAprobados(rutaFichero, listaAlumnos, curso, grupo=0): """ Entrada: una lista de alumnos como la indicada anteriormente, la ruta de un fichero, el nombre de un curso y opcionalmente el número de un grupo. Salida: crea un fichero con los datos de los alumnos del curso que aprueban. Si no se especifica grupo, se refiere a todo el curso. Los datos se grabarán con la siguiente estructura: nombre del alumno; media de las asignaturas nombre del alumno; media de las asignaturas nombre del alumno; media de las asignaturas """ f = open(rutaFichero, 'w') alumnos = listadoAlumnos(listaAlumnos, curso, grupo) medias = alumnoMedia(alumnos) for al in medias: if al[1] >= 5: f.write("%s;%d\n" % (al[0], al[1])) f.close() def mejorNota(rutaFichero): """ Entrada: una ruta de un fichero que tiene la estructura creada anteriormente. Salida: imprime en pantalla el alumno (o alumnos) que tienen la mejor nota con el siguiente formato: Nombre de alumno: nota. """ f = open(rutaFichero) mejores = [] mejor = -1 # inicializado con dato no válido for linea in f: nombre, nota = linea.split(';') nota = int(nota) if nota == mejor: mejores.append([nombre, nota]) if nota > mejor: mejor = nota mejores = [[nombre, nota]] for nombre, nota in mejores: print nombre,'-->', nota if __name__ == '__main__': # datos de test lista_alumnos = [ ["Pérez, Juan", "ASI", 1, [4, 5, 8, 3] ], ["Alvarez, Maria", "ESI", 2, [8,6,5,9,4]], ["Rivas, Ana", "ASI", 1, [3,4,5]], ["Marcos, Carlos", "ASI", 2, [9,9,9]], ["Vera, Carmen", "ASI", 2, [8,9,10]] ] # funciones de test # alumnos de ASI print listadoAlumnos(lista_alumnos, "ASI") print # alumnos de 1º de ASI print listadoAlumnos(lista_alumnos, "ASI",1) print # media de todos los alumnos print alumnoMedia(lista_alumnos) print # media de los de ASI print alumnoMedia(listadoAlumnos(lista_alumnos, "ASI")) print # listado aprobados listadoDeAlumnosAprobados('aprueban_Asi.txt', lista_alumnos, 'ASI') mejorNota('aprueban_Asi.txt')
4733fe243f4582efe2705f4181188a2920f3f846
piranna/asi-iesenlaces
/0708/repeticiones/ej118.py
989
3.84375
4
# -*- coding: utf-8 -*- """ $Id$ Realiza un programa que proporcione el desglose en billetes y monedas de una cantidad entera de euros. Recuerda que hay billetes de 500, 200, 100, 50, 20, 10 y 5 € y monedas de 2 y 1 €. Debes recorrer los valores de billete y moneda disponibles con uno o más bucles for-in. """ # Presentación print "*" * 50 print "Desglose de billetes" print "*" * 50 # Petición de la cantidad cantidad = int(raw_input("Introduzca un número positivo ")) # Variable para evitar tantas repeticiones billetes = [500, 200, 100, 50, 20, 10, 5] for billete in billetes: parcial = cantidad / billete # división entera: x billetes de billete if parcial: print parcial, "billetes de", billete, "euros" cantidad = cantidad % billete # actualizamos la cantidad que queda por repartir parcial = cantidad / 2 if parcial: print parcial, "monedas de 2 euros" cantidad = cantidad % 2 if cantidad: print cantidad, "monedas de 1 euro"
42bb3d5df47e7eb91425f7a92e19872ed16e3483
piranna/asi-iesenlaces
/0708/repeticiones/ej109.py
861
4.21875
4
# -*- coding: utf-8 -*- """ $Id$ Calcula el factorial de un número entero positivo que pedimos por teclado Si tienes dudas de lo que es el factorial, consulta http://es.wikipedia.org/wiki/Factorial """ # Presentación print "*" * 50 print "Programa que calcula el factorial de un número" print "*" * 50 # Petición del número positivo numero = int(raw_input("Introduzca un número positivo ")) while numero < 0: # Aseguramos que el número es positivo numero = int(raw_input("Introduzca un número positivo ")) # Por defecto: factorial de 0 es 1 factorial = 1 for n in range(1, numero + 1): # +1 porque si no range llegaría sólo hasta numero-1 # n va tomando los valores desde 1 hasta numero factorial = factorial * n print "El factorial del número", numero, "es", factorial # Sugerencia: programa el bucle con un while y compara
ba9b41a053ff6e6ea6df38fae9807cb3ecd49220
piranna/asi-iesenlaces
/0708/examenes/23nov/exa10.py
1,744
4.09375
4
# -*- encoding: utf-8 -*- # $Id$ """ Escribe una función que reciba una lista de nombres y que imprima la lista ordenada. La lista tendrá la siguiente estructura: [ “Ana, Martínez, Blasco”, “Nombre,Apellido1, Apellido2”, ...]. La ordenación se hará según el siguiente criterio: Apellido1 – apellido2 – Nombre. Es decir, se ordena por el primer apellido, si coincide, se ordena por el segundo apellido y si coincide también, se ordena por el nombre. El listado se hará de forma tabulada dejando 15 espacios para cada elemento. """ def esMayor(nombre1, nombre2): """ nombre tiene la estructura "Nombre, Apellido1, Apellido2" por eso hacemos un split(',') para separar la información Un nombre es mayor, cuando el primer apellido es mayor. Si no se compara el segundo apellido y en última instancia el nombre """ nom1, ape1_1, ape1_2 = nombre1.split(',') nom2, ape2_1, ape2_2 = nombre2.split(',') if ape1_1 > ape2_1: return True elif ape1_1 == ape2_1: if ape1_2 > ape2_2: return True elif ape1_2 == ape2_2: if nom1 > nom2: return True return False def ordenaListaNombres(lNombres): """ compara apellido1, apellido2 y nombre """ for x in range(1, len(lNombres)): for y in range(len(lNombres)-x): if esMayor(lNombres[y], lNombres[y+1]): lNombres[y], lNombres[y+1] = lNombres[y+1], lNombres[y] lista = ["Ana, Marco, Perez", "Pablo, Marco, Jimenez","Ana, Marco, Jimenez"] ordenaListaNombres(lista) print lista
597e97399626f74acfdadf7a75811a102fa19ff4
piranna/asi-iesenlaces
/0708/repeticiones/ej129.py
930
3.734375
4
# -*- coding: utf-8 -*- """ $Id$ Haz un programa que calcule el máximo comun divisor (mcd) de dos enteros positivos. El mcd es el número más grande que divide exactamente a ambos numeros. Documentación: http://es.wikipedia.org/wiki/M%C3%A1ximo_com%C3%BAn_divisor """ # Presentación print "*" * 50 print "Programa máximo común divisor" print "*" * 50 # AVISO: falta validar que so positivos numero1 = int(raw_input("Introduce el primer número: ")) numero2 = int(raw_input("Introduce el segundo número: ")) # prueba a sustituir esto por una sentencia con if mayor = max(numero1, numero2) menor = min(numero1, numero2) candidato = 1 for valor in range(2, menor + 1): if mayor % valor == 0 and menor % valor == 0: candidato = valor print "El mcd de %d y %d es %d" % (numero1, numero2, candidato) """ Propuesta: implementar el algoritmo de euclides: http://es.wikipedia.org/wiki/Algoritmo_de_Euclides """
4c4716e3d4b6710d9452f20af531be6c2cd5a9f5
piranna/asi-iesenlaces
/0708/repeticiones/mayormenor.py
756
3.84375
4
# -*- coding: cp1252 -*- """ $Id$ Trabajos con series de nmeros Mayor, menor, media ... Cuidado con los valores no vlidos al procesar una serie """ num = int(raw_input("Introduce un num positivo: ")) mayor = num # candidato el primero menor = num total = 0 veces = 0 while num >=0: if num > mayor: # Sustituir el que habamos guardado antes mayor = num if num < menor: # Sustituir el que habamos guardado antes menor = num veces += 1 total += num num = int(raw_input("Introduce un num positivo: ")) print "El mayor es", mayor print "El menor es", menor print "Suma de los nmeros", total print "Media de los nmeros", total / float(veces)
54582356e4fb4257a8066bdcca0f4612837deca9
piranna/asi-iesenlaces
/0708/repeticiones/esprimo.py
564
3.890625
4
# -*- coding: utf-8 -*- """ $Id$ Calcula si un número es primo. Ej. pág 118. Hay que mejorar el algoritmo. """ num = int(raw_input("Introduzca un número: ")) creo_que_es_primo = True for divisor in range (2, num ): if num % divisor == 0: creo_que_es_primo = False # Esta parte necesita una mejora. Prueba con un número muy grande # creo_que_es_primo ya es un booleano. # No es necesario compararlo creo_que_es_primo == True if creo_que_es_primo: print 'El número', num ,'es primo' else: print 'El número', num ,'no es primo'
3c55d755d5a00cab0e2ef1847d1c90672d6ac23a
zllu2/iMSA_577
/lessons/Module2/notebooks/helper_code/mlplots.py
1,071
3.734375
4
import pandas as pd import numpy as np import seaborn as sns # Convenience function to plot confusion matrix # This method produces a colored heatmap that displays the relationship # between predicted and actual types from a machine learning method. def confusion(test, predict, labels, title='Confusion Matrix'): ''' test: true label of test data, must be one dimensional predict: predicted label of test data, must be one dimensional labels: list of label names, ie: ['positive', 'negative'] title: plot title ''' bins = len(labels) # Make a 2D histogram from the test and result arrays pts, xe, ye = np.histogram2d(test, predict, bins) # For simplicity we create a new DataFrame pd_pts = pd.DataFrame(pts.astype(int), index=labels, columns=labels ) # Display heatmap and add decorations hm = sns.heatmap(pd_pts, annot=True, fmt="d") hm.axes.set_title(title, fontsize=20) hm.axes.set_xlabel('Predicted', fontsize=18) hm.axes.set_ylabel('Actual', fontsize=18) return None
44a036e4b3d596c701892a3905bb27e369f93018
seanx92/hotel_retrieval
/hotels/search.py
6,175
3.53125
4
import shelve import time import heapq from tokenization import tokenize def search(name, address, onlyOverall=True, tags=["cleanliness", "service", "value", "location", "sleep_quality", "rooms"]): ''' This function is used for finding the conjunctive result by searching by "address" and "name". ''' address_search_result = searchByAddress(address) name_search_result = searchByName(name) if len(address_search_result) == 0 and len(name_search_result) == 0: return getDefaultData() elif len(address_search_result) == 0:#if no search resuls for address search return, final result is the result of name search result = name_search_result elif len(name_search_result) == 0:#if no search result for name search retuan, final result is the result of address search result = address_search_result else:#if both of the address and name search have results, intersect the result if len(address_search_result) > len(name_search_result): result = intersect_two(name_search_result, address_search_result) else: result = intersect_two(address_search_result, name_search_result) # if len(result) == 0:#if no result after intersection, use the result of address search as final result # print "I'm in the no intersected result part" # result = address_search_result # print "time before ranking is:", time.time() - start # print result return rankResult(result, onlyOverall, tags) def rankResult(result_ids, onlyOverall=True, tags=["cleanliness", "service", "value", "location", "sleep_quality", "rooms"]): '''This function is used for rank the results by overall rating or tags. ''' hotel_score = shelve.open('hotels/static/data/hotel_score.db') result = [] for id in result_ids: result.append((id, hotel_score[str(id)])) if onlyOverall: result = rankByOverall(result) else: result = rankByTags(result, tags) hotel_score.close() mid3 = time.time() hotels = shelve.open('hotels/static/data/hotels.db') for i in range(len(result)): result[i] = (str(result[i]),hotels[str(result[i])]) hotels.close() print "read hotel data from db time is:", time.time() - mid3 return result def rankByOverall(hotel_list): '''This function rank the input hotel_list with the average overall rating. ''' temp = [] for hotel_tuple in hotel_list: temp.append((float(hotel_tuple[1]["overall"]), hotel_tuple[0])) result = getTopResults(temp) return result#sorted(hotel_list, key=lambda x: x[1]["average_scores"]["overall"], reverse=True) def rankByTags(hotel_list, tags): '''This function rank the input hotel_list with the weighted averaged rating for the given tag list. ''' length = len(tags) temp = [] result = [] for hotel_tuple in hotel_list: score = 0 for tag in tags: score += hotel_tuple[1][tag] score /= length temp.append((score, hotel_tuple[0])) result = getTopResults(temp) return result def getTopResults(hotel_scores): h = [] result = [] count = 30#how many results need to be return for h_s in hotel_scores: if count > 0: heapq.heappush(h, h_s) count = count - 1 elif h_s[0] > h[0]: heap.heappushpop(h, h_s) h.sort(key=lambda x: x[0], reverse=True) for hotel_scores in h: result.append(hotel_scores[1]) return result def searchByName(name): '''This function is used for searching by name. ''' name_hotel = shelve.open('hotels/static/data/index_nameHotel.db') query_list = tokenize(name) keys = name_hotel.keys() result = [] for term in query_list: if term in keys: result.append(name_hotel[term]) if len(result) > 1: result = intersect(result) elif len(result) == 1: result = result[0] name_hotel.close() return result def searchByAddress(address): '''This function is used for searching by address. ''' address_hotel = shelve.open('hotels/static/data/index_addressToHotel.db') query_list = tokenize(address) result = [] keys = address_hotel.keys() for term in query_list: if term in keys: result.append(address_hotel[term]) if len(result) > 1: result = intersect(result) elif len(result) == 1: result = result[0] address_hotel.close() return result def intersect(resultLists): '''This function is used for intersecting given lists. ''' resultLists.sort(key=lambda x: len(x)) result = resultLists[0] i = 1 while i < len(resultLists): result = intersect_two(result, resultLists[i]) i += 1 return result def intersect_two(resultList1, resultList2): '''This function is used for intersecting two given lists. It is useful for intersect() function and when intersect the search result getting from name searching and address searching. ''' result = [] i = 0 j = 0 while i < len(resultList1) and j < len(resultList2): if int(resultList1[i]) == int(resultList2[j]): result.append(resultList1[i]) i = i + 1 j = j + 1 elif int(resultList1[i]) < int(resultList2[j]): i = i + 1 else: j = j + 1 return result def getDefaultData(): hotels = shelve.open('hotels/static/data/hotels.db') result = [] i = 30 j = 0 while i > 0: if str(j) in hotels: result.append((str(j), hotels[str(j)])) i = i - 1 j = j + 1 hotels.close() return result # start = time.time() # result = search('hilton', 'new york', False, ["service", "sleep_quality","cleanliness", "location"]) # # result = search('continental','') # print "uses time:", time.time() - start # print "there are", len(result), "hits" # #print result # for item in result: # #print item["name"] # print item[0], item[1]["name"], item[1]["hotel_id"]#, item["address"] # #print search('', 'hotel', False, ["cleanliness"])'''
c10d96e43b1b728b1f42250686fcae0d9aae2b69
jcguy/AdventOfCode2017
/problem4.py
827
3.703125
4
#!/usr/bin/env python3 # Advent of Code, Problem 4 # James Corder Guy def main(): # Part 1 num_valid = 0 with open("problem4.txt") as f: for line in f: phrase = line.replace("\n", "").split(" ") if sorted(phrase) == sorted(list(set(phrase))): num_valid += 1 print("Part 1: {}".format(num_valid)) # Part 2 num_valid = 0 with open("problem4.txt") as f: for line in f: phrase = line.replace("\n", "").split(" ") new_phrase = [] for word in phrase: new_phrase.append("".join(sorted(word))) phrase = new_phrase if sorted(phrase) == sorted(list(set(phrase))): num_valid += 1 print("Part 2: {}".format(num_valid)) if __name__ == "__main__": main()
795f82845050e500086eea28a79bdfc9654ed8b7
anwenliucityu/atomman
/mep/integrator/rungekutta.py
820
3.5
4
# coding: utf-8 def rungekutta(ratefxn, coord, timestep, **kwargs): """ Performs Runge-Kutta ODE integration for a timestep. Parameters ---------- ratefxn : function The rate function to use. coord : array-like object The coordinate(s) of the last timestep. timestep : float The timestep value to use. **kwargs : any Any extra keyword parameters to pass on to ratefxn. Returns ------- array-like object The coordinate(s) moved forward by timestep. """ k1 = timestep * ratefxn(coord, **kwargs) k2 = timestep * ratefxn(coord - 0.5 * k1, **kwargs) k3 = timestep * ratefxn(coord - 0.5 * k2, **kwargs) k4 = timestep * ratefxn(coord - k3, **kwargs) return coord + k1 / 6 + k2 / 3 + k3 / 3 + k4 / 6
f9e60194c6a8df0e7755f45703ca36915db08388
maisha815/Solitaire_Cypher
/cipher.py
2,513
4.03125
4
import c_functions import os.path def validate_file_name(message): """ (str) -> str Prompt user the message to type the name of a file. Keep re-prompting until a valid filename that exists in the same directory as the current code file is supplied. Return the name of the file. """ file_name = input(message) while not os.path.exists(file_name): print("Invalid filename! Please try again.") file_name = input(message) return file_name def choose_encrypt_decrypt(): """ () -> str Prompt user to enter if they choose the encryption or decryption process. Keep re-prompting until a valid process is given. Return the process chosen. """ message = 'Shall we encrypt %s or decrypt %s? ' %( c_functions.ENCRYPT, c_functions.DECRYPT) process = input(message) while not (process == c_functions.ENCRYPT or process == c_functions.DECRYPT): print('Invalid process! I will ask again...') process = input(message) if process == c_functions.ENCRYPT: print("Okay! Let's Encrypt this message into absolute gibberish!") elif process == c_functions.DECRYPT: print("Let's Decrypt this puzzle and see what secret lies ahead!") return process def main_operation(): """ () -> NoneType Perform the chosen process using a deck supplied and a message supplied. If the process is 'e', encrypt; if 'd', decrypt. Stop the process if a valid card is not supplied. """ prompt_user = 'Enter the filename of the card deck: ' access_deck_file = open(validate_file_name(prompt_user), 'r') deck_to_use = c_functions.read_deck(access_deck_file) access_deck_file.close() if not (c_functions.validate_deck(deck_to_use)): print('This is not a valid card deck.') print('Stopping the process.') return prompt = 'Enter the filename of the message: ' access_message_file = open(validate_file_name(prompt), 'r') messages = c_functions.read_message(access_message_file) access_message_file.close() # validating a message file is not needed as anything will be # encrypted or decrypted if it is an alphabet, numerals will be ignored. process = choose_encrypt_decrypt() for message in c_functions.process_message(deck_to_use, messages, process): print(message) if __name__ == "__main__": main_operation()
a7248417ac7f1924cd5db4323c8b3903bdda1047
grimsley217/608-mod1
/range.py
175
4.25
4
#range.py """This prints the range of values from the integers provided.""" x=min(47, 95, 88, 73, 88, 84) y=max(47, 95, 88, 73, 88, 84) print('The range is', x, '-', y, '.')
da79c29a1fa65206d5446bf374974aaef57b09e2
luiz-vinicius/IP-UFRPE-EXERCICIOS
/lista4_ex_8.py
265
3.640625
4
from random import randint s1 = str(input("Digite o 1º texto: ").replace("","")) s2 = str(input("Digite o 2º texto: ").replace("","")) len_s1 = len(s1) len_s2 = len(s2) print(len_s1) menor = len_s1 if(len_s2<menor): menor = len_s2 r = randint(0,menor) print(r)
9a28fbd169078b2133058156d9f7c3c8f86d38ae
luiz-vinicius/IP-UFRPE-EXERCICIOS
/aula_lista_ex_2.py
157
4.09375
4
lista = [] for x in range(10): v = float(input("Digite um valor: ")) lista.append(v) lista.reverse() for i,p in enumerate(lista): print(i+1,"º = ",p)
3323f4d0504f59a298ff413e4e79de25f23f79b0
luiz-vinicius/IP-UFRPE-EXERCICIOS
/lista3_ex_8.py
291
3.75
4
nome = str(input("Digite o nome do funcionário: ")) sal = float(input("Digite o salário bruto do funcionário: ")) des = sal *5/100 sal_liq = sal - des print("Nome do funcionário: {} \nSalário Bruto {:.2f} \nDesconto: {:.2f} \nSalário Líquido: {:.2f}".format(nome, sal, des, sal_liq))
03fc80b0a61c1c6a16672f55488287f969f0a0e3
luiz-vinicius/IP-UFRPE-EXERCICIOS
/if_ex_9.py
471
3.953125
4
peso = float(input("Digite seu peso: ")) altura = float(input("Digite sua altura: ")) imc = peso/(altura*2) if(imc<20): print("Abaixo do peso") elif(imc>20 and imc<=25): print("Peso ideal") elif(imc>25 and imc<=30): print("Sobrepeso") elif(imc>30 and imc<=35): print("Obesidade Moderada") elif(imc>35 and imc<=40): print("Obesidade Severa") elif(imc>40 and imc<=50): print("Obesidade Mórbida") else: print("Super Obesidade")
91e92a5aaf939ad7a970b43c0e9ac2984d8c3c80
luiz-vinicius/IP-UFRPE-EXERCICIOS
/lista4_ex_3.py
109
3.796875
4
nome = str(input("Digite o seu nome completo:")) espaço = nome.split(" ") print(espaço[-1],",",espaço[0])
e7c8dc1d1cf897ec181b2ddf648f0cda2b25af14
luiz-vinicius/IP-UFRPE-EXERCICIOS
/while_ex_1.py
523
3.796875
4
qnt_alunos = 0 qnt_altura = 0 while True: idade = int(input("Digite a idade: ")) if(idade<=100 and idade>0): altura = float(input("Digite a altura: ")) if(altura==0): break if(idade>=13): qnt_alunos +=1 if(altura>=1.5): qnt_altura +=1 else: print("Digite uma idade valida!") print("Quantidade de alunos com mais de 13 anos: {} \nE maiores de que 1.50m: {}".format(qnt_alunos, qnt_altura))
1cab19115488ffde362ca1a725cf79bce4d17030
luiz-vinicius/IP-UFRPE-EXERCICIOS
/if_ex_7.py
247
4.0625
4
v = input("Digite \nM-Matutino \nV-Vespertino \nN-Noturno \n: ") if(v=='M'or v=='m'): print("Bom dia!") elif(v=='V' or v=='v'): print("Boa Tarde!") elif(v=='N' or v=='n'): print("Boa Noite!") else: print("Valor Inválido!")
56aa08c0b985d4c08aba410e2c6f82ce2908be0a
luiz-vinicius/IP-UFRPE-EXERCICIOS
/for_ex_1.py
596
3.59375
4
c = 0 for i in range(10): qnt = int(input("Digite a quantidade itens vendidos pelo vendedor: ")) if(qnt>0 and qnt<=19): c = qnt*0.10 print("A comissão do {}º vendedor será de: {}%".format(i+1,c)) elif(qnt>=20 and qnt<50): c = qnt*0.15 print("A comissão do {}º vendedor será de {}%".format(i+1,c)) elif(qnt>=50 and qnt<75): c = qnt*0.20 print("A comissão do {}º vendedor será de {}%".format(i+1,c)) else: c = qnt*0.25 print("A comissão do {}º vendedor será de {}%".format(i+1,c))
de9ed90bb6c7ea52a2e457dfcddbe8014ff15f23
JoelsonSartoriJr/study-astronomy
/Nbody/main.py
2,983
3.578125
4
import numpy as np import matplotlib.pyplot as plt from acceleration import acceleration from energy import energy def main(): """ Init simulation N-body parameters""" N = 100 # Number of particles t = 0 # Time of the simulation tEnd = 10.0 # time at which simulation ends dt = 0.01 # timestep softening = 0.01 # softening length G = 1.0 # Newtons Gravitational Constant plotRealTime = True # plotting as the simulation goes along np.random.seed(42) mass = 20.0*np.ones((N, 1))/N # total mass of particles is 20 pos = np.random.randn(N, 3) vel = np.random.randn(N, 3) # Convert to Center of Mass frame vel -= np.mean(mass*vel, 0) / np.mean(mass) # Calculate init gravitational accelerations acc = acceleration(pos, mass, G, softening) # Calculate initial energy of system KE, PE = energy(pos, vel, mass, G) # Number of timesteps Nt = int(np.ceil(tEnd/dt)) # Save energies, particles orbits for plotting trails pos_save = np.zeros((N, 3, Nt+1)) pos_save[:, :, 0] = pos KE_save = np.zeros(Nt+1) KE_save[0] = KE PE_save = np.zeros(Nt+1) PE_save[0] = PE t_all = np.arange(Nt+1)*dt # pre figure fig = plt.figure(figsize=(4, 5), dpi=80) grid = plt.GridSpec(3, 1, wspace=0.0, hspace=0.3) ax1 = plt.subplot(grid[0:2,0]) ax2 = plt.subplot(grid[2, 0]) #simulation Main loop for i in range(Nt): vel += acc*dt/2.0 pos += vel*dt acc = acceleration(pos, mass, G, softening) vel += acc*dt/2.0 t += dt KE, PE = energy(pos, vel, mass, G) # Save energies pos_save[:, :, i+1] = pos KE_save[i+1] = KE PE_save[i+1] = PE # Plot in real time if plotRealTime or (i == Nt -1): plt.sca(ax1) plt.cla() xx = pos_save[:,0,max(i-50,0):i+1] yy = pos_save[:,1,max(i-50,0):i+1] plt.scatter(xx,yy,s=1,color=[.7,.7,1]) plt.scatter(pos[:,0],pos[:,1],s=10,color='blue') ax1.set(xlim=(-2, 2), ylim=(-2, 2)) ax1.set_aspect('equal', 'box') ax1.set_xticks([-2,-1,0,1,2]) ax1.set_yticks([-2,-1,0,1,2]) plt.sca(ax2) plt.cla() plt.scatter(t_all,KE_save,color='red',s=1,label='KE' if i == Nt-1 else "") plt.scatter(t_all,PE_save,color='blue',s=1,label='PE' if i == Nt-1 else "") plt.scatter(t_all,KE_save+PE_save,color='black',s=1,label='Etot' if i == Nt-1 else "") ax2.set(xlim=(0, tEnd), ylim=(-300, 300)) ax2.set_aspect(0.007) plt.pause(0.001) plt.sca(ax2) plt.xlabel('time') plt.ylabel('Energy') ax2.legend(loc='nbody.png', dpi=240) return 0 if __name__=="__main__": main()
efc673e72bf226503ca35988255ae723ce7b9071
keerthanachinna/first
/vowel1.py
176
4.125
4
c=input("enter the character") if(c=='a' or c=='A' or c=='e' or c=='E' or c=='i' or c=='I' or c=='o' or c=='O' or c=='u'or=='U'): print (c+,"vowel") else: print(c+,"consoant")
a7e7e5f0d0d6ea259a65432cfb51d99778ec1aa4
kaviyakaviyarasan98/practice
/factorial.py
86
3.671875
4
num=int(input()) i=1 fact=1 while(i<=5): fact=fact*i i=i+1 print(fact)
c4f579fb11e9282776556fe875783bdc04344f59
kanwar101/Python_Review
/src/Chapter07/parrot.py
265
3.921875
4
prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " message = "" active = True while active: message = input ("Do you want to Quit? ") if message != 'quit': print (message) else: active=False
7a932affcbd170fa57dcb114ac972460b47e3b54
kanwar101/Python_Review
/src/Chapter08/pizza.py
242
4.09375
4
def make_pizza(size, *toppings): """Print dynamic list of toppings""" print (f"You ordered {size} pizza with following toppings:") for topping in toppings: print (topping) #make_pizza( size='thin crust','olives', 'peppers','onion')
daacca98ea87613f501c1db9e060948ff3e7d018
kanwar101/Python_Review
/src/Chapter06/aliens.py
436
3.953125
4
aliens_0 = {'color':'green', 'point':5} alient_1 = {'color':'blue', 'point':7} alient_2 = {'color':'white', 'point':10} aliens =[aliens_0,alient_1, alient_2] for alien in aliens: print(alien) print("next item in the list") empty_aliens = [] for value in range(0,10): new_alien = {'color':'Orange', 'points':value*2} empty_aliens.append (new_alien) print (empty_aliens) print ("Only first 5 element") print (empty_aliens[:5])
d2ab2cc50739a52b7a3fcfac1af26f54a621bb07
kanwar101/Python_Review
/src/Chapter11/test_name_function.py
351
3.5
4
import unittest from name_function import get_formatted_name class NameTestCase (unittest.TestCase): """Test for the name funtion""" def test_first_last_name (self): """testing formatted names""" formatted_name = get_formatted_name('Bob', 'Crow') self.assertEqual ('Bob Crow', formatted_name) if __name__ == '__main__': unittest.main()
98379659dbbd937bfc5db774006c392ce352f08d
kanwar101/Python_Review
/src/Chapter06/alien.py
739
3.5625
4
alien_0={'key1':'value1', 'key2':'value2','key3':'value3'} print (alien_0['key1']) alien_0['key4'] = 'value4' print (alien_0) empty_dict={} empty_dict['system'] = 'HP' empty_dict['OS'] = 'Chrome' empty_dict['processor']='intel' print (empty_dict) empty_dict['system']='Dell' print (empty_dict) # if loop with dictionaries alien_0={'x_position':0, 'y_position':25, 'speed':'fast'} print (f"Original Position {alien_0['x_position']}") if alien_0['speed'] == 'slow': x_increment = 1 elif alien_0['speed'] == 'medium': x_increment =2 else: x_increment = 3 alien_0 ['x_position'] = alien_0 ['x_position'] + x_increment print (alien_0) # remove value pair from dictionary del alien_0['speed'] print (alien_0) # dictionary usage
ded6b6fb5db245ede155d1ceb4f9a67a4c68e0b9
kanwar101/Python_Review
/src/Chapter11/name_function.py
164
3.84375
4
def get_formatted_name (first, last, middle =''): """Print formatted name""" if middle: return f"{first} {middle} {last}" else: return f"{first} {last}"
2790f8ae5a5e897fa6d95dfafd5008c8169f0b53
kanwar101/Python_Review
/src/Chapter04/slice_list.py
151
3.5
4
players = ['bob','dan','steve','reddy'] print (players[1:3]) print (players[-1:]) print (players[-2:]) for player in players[2:4]: print (player)
b976f86e302748c97bcd5033499a0f2a928bcbdc
taddes/python-blockchain
/data_structures_assignment.py
1,053
4.40625
4
# 1) Create a list of “person” dictionaries with a name, age and list of hobbies for each person. Fill in any data you want. person = [{'name': 'Taddes', 'age': 30, 'hobbies': ['bass', 'coding', 'reading', 'exercise']}, {'name': 'Sarah', 'age': 30, 'hobbies': ['exercise', 'writing', 'crafting']}, {'name': 'Pepper', 'age': 5, 'hobbies': ['hunting', 'eating plants', 'napping']}] # 2) Use a list comprehension to convert this list of persons into a list of names (of the persons). name_list = [name['name'] for name in person ] print(name_list) # 3) Use a list comprehension to check whether all persons are older than 20. age_check = all([age['age'] > 20 for age in person ]) print(age_check) # 4) Copy the person list such that you can safely edit the name of the first person (without changing the original list). copied_person = person[:] print(copied_person) print(person) # 5) Unpack the persons of the original list into different variables and output these variables. name, age, hobbies = person print(name) print(age)
8820ec93b9d0c2cffea06dca6d832ac02b53996b
marboh1126/homework
/hw-3.py
326
3.71875
4
class Dog: def __init__(self, name, age): self.name = name self.age = age def bow(self): print('bowbowbow') def sayName(self): print('Name: ' + self.name) def sayAge(self): print('Age: ' + str(self.age)) dog = Dog('Masato', 24) dog.bow() dog.sayName() dog.sayAge()
866b64d7ad1da8e45faed0f702565fa0544e12c1
changfenxia/gb-python
/lesson_1/ex_4.py
558
3.9375
4
''' 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. ''' number = input("Введите целое положительное число: ") max = int(number[0]) x = 0 while x < len(number): if (int(number[x]) > max): max = int(number[x]) x += 1 print(f"Самое большая цифра в числе {number}: {max}")
0eea84be3a43149c15164ee857b647d8fc7fd08b
changfenxia/gb-python
/lesson_5/ex_6.py
1,395
3.5
4
''' 6. Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, содержащий название предмета и общее количество занятий по нему. Вывести словарь на экран. Примеры строк файла: Информатика: 100(л) 50(пр) 20(лаб). Физика: 30(л) — 10(лаб) Физкультура: — 30(пр) — Пример словаря: {“Информатика”: 170, “Физика”: 40, “Физкультура”: 30} ''' # helper function to strip non-digits from string def string_to_int(x): return int(''.join(filter(str.isdigit, x))) classes_dict = {} with open('classes.txt') as my_file: lines = my_file.read().split('\n') for line in lines: subject_name, hours = line.split(':') hours = [string_to_int(x) for x in hours.split() if len(x) > 1] classes_dict[subject_name] = sum(hours) print(classes_dict)
e1ddd1d2897462bc6d6831993acdd9b9257554b2
changfenxia/gb-python
/lesson_1/ex_2.py
503
4.3125
4
''' 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. ''' time_seconds = int(input("Enter time in seconds: ")) hours = time_seconds // 3600 minutes = (time_seconds % 3600) // 60 seconds = time_seconds - (hours * 3600) - (minutes * 60) print(f"{hours:02d}:{minutes:02d}:{seconds:02d}")
672968de994d9c62f0edb21db7e9339c8bb2a2dd
felipedelta0/URIOnlineJudge
/1010 - URI Online Judge - Solved.py
1,202
3.953125
4
# -*- coding: utf-8 -*- ''' Neste problema, deve-se ler o código de uma peça 1, o número de peças 1, o valor unitário de cada peça 1, o código de uma peça 2, o número de peças 2 e o valor unitário de cada peça 2. Após, calcule e mostre o valor a ser pago. Entrada O arquivo de entrada contém duas linhas de dados. Em cada linha haverá 3 valores, respectivamente dois inteiros e um valor com 2 casas decimais. Saída A saída deverá ser uma mensagem conforme o exemplo fornecido abaixo, lembrando de deixar um espaço após os dois pontos e um espaço após o "R$". O valor deverá ser apresentado com 2 casas após o ponto. Exemplos de Entrada Exemplos de Saída 12 1 5.30 VALOR A PAGAR: R$ 15.50 16 2 5.10 13 2 15.30 VALOR A PAGAR: R$ 51.40 161 4 5.20 1 1 15.10 VALOR A PAGAR: R$ 30.20 2 1 15.10 ''' entrada = input() entrada2 = input() numerosStr = entrada.split(" ") numerosStr2 = entrada2.split(" ") numeros = [float(num) for num in numerosStr] numeros2 = [float(num) for num in numerosStr2] cod, qtd, val = numeros cod1, qtd1, val1 = numeros2 valf = (qtd * val) + (qtd1 * val1) print ("VALOR A PAGAR: R$ {:.2f}".format(valf))
edd4db95c5ca029c1378e16677318becafac984f
Artamamo/hwsys
/hw.py
1,778
3.75
4
import sys str = sys.argv n=0 uppercase = False EnglishCheck = False NumberCheck = False fail = False Check = False try: n=len(str[1]) except: print("請輸入字串") if n<8: print("長度小於8") sys.exit(0) elif n>16: print("長度大於16") sys.exit(0) list1 =list(str[1]) for i in range(0,n): if 65 <= ord(list1[i]) <= 90: uppercase = True EnglishCheck = True if 97 <= ord(list1[i]) <=122: EnglishCheck = True if 48 <= ord(list1[i]) <=57: NumberCheck = True if (65 <= ord(list1[i]) <= 90) == False and (97 <= ord(list1[i]) <=122) == False and (48 <= ord(list1[i]) <=57) == False: Check = True if EnglishCheck == False: print("缺少英文") sys.exit(0) elif uppercase == False: print("請輸入至少一個大寫英文") sys.exit(0) elif NumberCheck == False: print("缺少數字") sys.exit(0) elif Check == False: print("缺少符號") sys.exit(0) temp = list1[0] for i in range(1,n): if ord(temp)+1 == ord(list1[i]) and ord(temp)!=64 and ord(temp)!=47 and ord(temp)!=96 : continuous = True if 65 <= ord(list1[i]) <=90: print("大寫英文不可連續") fail = True elif 97 <= ord(list1[i]) <=122: print("小寫英文不可連續") fail = True elif 48 <= ord(list1[i]) <=57: print("數字不可連續") fail = True else: continuous = False temp = list1[i] if fail == True: sys.exit(0) if continuous == False and uppercase == True and EnglishCheck == True and NumberCheck == True: print("success")
95cbcc07243fb919699df576b9bb1458637ddd49
sroy8091/daily_coding_problem
/find_missing_positive.py
1,039
3.859375
4
""" This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3 """ def swap_positions(list, pos1, pos2): get = list[pos1], list[pos2] list[pos2], list[pos1] = get return list def segregate(arr): j = 0 for i in range(len(arr)): if arr[i] <= 0: swap_positions(arr, i ,j) j += 1 return j def find_missing(arr): j = segregate(arr) for i in range(j, len(arr)): if arr[i] - 1 < len(arr)-1 and arr[arr[i]-1] > 0: arr[arr[i]-1] = -arr[arr[i]-1] for i in range(len(arr)): if arr[i] > 0: return i + 1 def main(): arr = [3, 4, -1, 1] print(find_missing(arr)) if __name__=="__main__": main()
4d22bc86b5997a8b622aebd80dc81a956863a926
RDH06/Python
/28-07-2018classprogram/Some_Process.py
598
3.546875
4
import os def File_to_Listwrds(fname): if not os.path.isfile(fname): return[] wordlst = [] with open(fname,'r') as fob: wordlst = [] for walk in fob: flst = walk.strip("\n").split() wordlst.extend(flst) return wordlst def search_word(wlst,word): rlst=[] for walk in wlst: if word in walk: rlst.append(walk) return rlst def word_count(wlst,word): count = 0 for walk in wlst: if walk == word: count +=1 return count
f4b1f6480bbe645be84bbfc89b23b224bc87435c
kishannerella/CSE537
/P3/submit.py
4,025
3.625
4
#do not modify the function names #You are given L and M as input #Each of your functions should return the minimum possible L value #Or return -1 if no solution exists for the given L #Your backtracking function implementation import time def isSafe(assignments,marker): assignments[marker] = 1 keys = assignments.keys() dist = [] for i in range(0,len(keys)-1): for j in range(i+1,len(keys)): if assignments[i] == 1 and assignments[j] == 1: if (j-i) in dist: assignments[marker] = 0 return False dist.append(j - i) assignments[marker] = 0 return True def isSafefinal(assignments): keys = assignments.keys() dist = [] for i in range(0,len(keys)-1): for j in range(i+1,len(keys)): if assignments[i] == 1 and assignments[j] == 1: if (keys[j] - keys[i]) in dist: return False dist.append(keys[j] - keys[i]) #print sorted(dist) return True def print_ans(assignments): keys = assignments.keys() ans = [] for key in keys: if(assignments[key]==1): ans.append(key) print ans print "\n" def BTUtil(L,M,assignments,start): counter = M if counter == 0: #print assignments if isSafefinal(assignments): print_ans(assignments) return False return False for i in range(start,L+1): if(isSafe(assignments,i)): assignments[i] = 1 counter = counter - 1 x = BTUtil(L,counter,assignments,i+1) if x == False: counter = counter + 1 assignments[i] = 0 else: return True return False #print assignments def BT(L, M): "*** YOUR CODE HERE ***" counter = M assignments = {} return BTUtil(L,M,assignments,0) return -1 def FCassigmnets(assignments,counter,marker): assignments[marker] = 1 keys = assignments.keys() #print assignments dist = [] for i in range(0,len(keys)-1): for j in range(i+1,len(keys)): if assignments[i] == 1 and assignments[j] == 1: if (j-i) in dist: assignments[marker] = 0 return False dist.append(j - i) remaining = [key for key,val in assignments.items() if val==0 and key>marker] count = len(remaining) for item in remaining: for key in keys: if assignments[key] == 1 and (item - key) in dist: count = count - 1 break assignments[marker] = 0 if count >= counter: return True return False def FCUtil(L,M,assignments,start): counter = M if counter == 0: #print assignments if isSafefinal(assignments): print_ans(assignments) return False return False for i in range(start,L+1): if(FCassigmnets(assignments,counter-1,i)): assignments[i] = 1 counter = counter - 1 x = FCUtil(L,counter,assignments,i+1) if x == False: counter = counter + 1 assignments[i] = 0 else: return True return False #Your backtracking+Forward checking function implementation def FC(L, M): "*** YOUR CODE HERE ***" counter = M assignments = {} remaining = range(0,L+1) for item in remaining: assignments[item] = 0 #print remaining return FCUtil(L,M,assignments,0) return -1 #Bonus: backtracking + constraint propagation def CP(L, M): "*** YOUR CODE HERE ***" return -1 print time.time() BT(34,8) print time.time() FC(34,8) print time.time()
920f126b9081a52fd2882375de6a026e29470590
teamroke/tessas_first_program
/Tessa.py
378
3.609375
4
import random def get_name(weather): nickname = input('What is your nickname? ') print(f'That is funny, hello {nickname}') print(f'It is {weather} outside!') return nickname for i in range(1,5): print(f'You rolled a: {random.randint(1,20)}') print('argh!') name = input('What is your name? ') print(f'Hello, {name}!') nick = get_name('sunny') print(nick)
255f6298f6215d04542086661c9fb3c8121d7f76
lhotse-speech/lhotse
/lhotse/parallel.py
2,663
3.71875
4
import queue import threading from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor from typing import Callable, Generator, Iterable def parallel_map( fn: Callable, *iterables: Iterable, num_jobs: int = 1, queue_size: int = 5000, threads: bool = False, ) -> Generator: """ Works like Python's ``map``, but parallelizes the execution of ``fn`` over ``num_jobs`` subprocesses or threads. Under the hood, it spawns ``num_jobs`` producer jobs that put their results on a queue. The current thread becomes a consumer thread and this generator yields items from the queue to the caller, as they become available. Example:: >>> for root in parallel_map(math.sqrt, range(1000), num_jobs=4): ... print(root) :param fn: function/callable to execute on each element. :param iterables: one of more iterables (one for each parameter of ``fn``). :param num_jobs: the number of parallel jobs. :param queue_size: max number of result items stored in memory. Decreasing this number might save more memory when the downstream processing is slower than the producer jobs. :param threads: whether to use threads instead of processes for producers (false by default). :return: a generator over results from ``fn`` applied to each item of ``iterables``. """ thread = SubmitterThread( fn, *iterables, num_jobs=num_jobs, queue_size=queue_size, threads=threads ) thread.start() q = thread.queue while thread.is_alive() or not q.empty(): try: yield q.get(block=True, timeout=0.1).result() except queue.Empty: # Hit the timeout but thread is still running, try again. # This is needed to avoid hanging at the end when nothing else # shows up in the queue, but the thread didn't shutdown yet. continue thread.join() class SubmitterThread(threading.Thread): def __init__( self, fn: Callable, *iterables, num_jobs: int = 1, queue_size: int = 10000, threads: bool = False, ) -> None: super().__init__() self.fn = fn self.num_jobs = num_jobs self.iterables = iterables self.queue = queue.Queue(maxsize=queue_size) self.use_threads = threads def run(self) -> None: executor = ThreadPoolExecutor if self.use_threads else ProcessPoolExecutor with executor(self.num_jobs) as ex: for args in zip(*self.iterables): future = ex.submit(self.fn, *args) self.queue.put(future, block=True)
56aeca5ce7c3654160344be4329f5a8b821c16f8
shadowleaves/deep_learning
/cnn/tflayer_text_cnn.py
5,843
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Simple example using convolutional neural network to classify IMDB sentiment dataset. References: - Andrew L. Maas, Raymond E. Daly, Peter T. Pham, Dan Huang, Andrew Y. Ng, and Christopher Potts. (2011). Learning Word Vectors for Sentiment Analysis. The 49th Annual Meeting of the Association for Computational Linguistics (ACL 2011). - Kim Y. Convolutional Neural Networks for Sentence Classification[C]. Empirical Methods in Natural Language Processing, 2014. Links: - http://ai.stanford.edu/~amaas/data/sentiment/ - http://emnlp2014.org/papers/pdf/EMNLP2014181.pdf """ from __future__ import division, print_function, absolute_import import tensorflow as tf import tensorlayer as tl import numpy as np # from tensorlayer.prepro import pad_sequences # import tflearn # from tflearn.layers.core import input_data, dropout, fully_connected # from tflearn.layers.conv import conv_1d, global_max_pool # from tflearn.layers.merge_ops import merge # from tflearn.layers.estimator import regression from tflearn.data_utils import to_categorical, pad_sequences from tflearn.datasets import imdb # IMDB Dataset loading train, test, _ = imdb.load_data(path='imdb.pkl', n_words=10000, valid_portion=0.1) X_train, y_train = train X_val, y_val = test # Data preprocessing # Sequence padding X_train = pad_sequences(X_train, maxlen=100, value=0.) X_val = pad_sequences(X_val, maxlen=100, value=0.) y_train = np.array(y_train, dtype='int32') y_val = np.array(y_val, dtype='int32') # Converting labels to binary vectors # y_train = to_categorical(y_train, nb_classes=2) # Y_val = to_categorical(Y_val, nb_classes=2) # Building convolutional network # embedding sess = tf.InteractiveSession() embd_dims = 128 nbf = 128 # doesn't have to be equal to embedding dims x = tf.placeholder(tf.int32, shape=[None, 100], name='x') y_ = tf.placeholder(tf.int64, shape=[None, ], name='y_') # network = tl.layers.InputLayer(x, name='input') network = tl.layers.EmbeddingInputlayer(inputs=x, vocabulary_size=10000, embedding_size=embd_dims, name='embedding_layer') branch1 = tl.layers.Conv1dLayer(network, act=tf.nn.relu, shape=[3, nbf, nbf], stride=1, padding='VALID', name='branch1', ) branch2 = tl.layers.Conv1dLayer(network, act=tf.nn.relu, shape=[4, nbf, nbf], stride=1, padding='VALID', name='branch2', ) branch3 = tl.layers.Conv1dLayer(network, act=tf.nn.relu, shape=[5, nbf, nbf], stride=1, padding='VALID', name='branch3', ) # reg1 = tf.contrib.layers.l2_regularizer(0.01)(branch1.all_layers[-1]) # reg2 = tf.contrib.layers.l2_regularizer(0.01)(branch2.all_layers[-1]) # reg3 = tf.contrib.layers.l2_regularizer(0.01)(branch3.all_layers[-1]) network = tl.layers.ConcatLayer([branch1, branch2, branch3], concat_dim=1, name='concat_layer') network = tl.layers.ExpandDimsLayer(network, axis=3, name='expand_dims') shape = [z.value if z.value else -1 for z in network.all_layers[-1].shape.dims[:-1]] network = tl.layers.ReshapeLayer(network, shape=shape) # network = tl.layers.ExpandDimsLayer(network, axis=3, name='expand_dims') k = network.all_layers[-1].shape[1].value network = tl.layers.MaxPool1d(network, # filter_size=[k, 1], filter_size=k, strides=1, # padding='valid', ) network = tl.layers.FlattenLayer(network) network = tl.layers.DropoutLayer(network, keep=0.5) network = tl.layers.DenseLayer(network, n_units=2, act=tf.identity) network.print_layers() # define cost function and metric. y = network.outputs # y_ = tf.reshape(y_, [32, 2]) # y = tf.reshape(y, [32, 2]) # y_op = tf.argmax(tf.nn.softmax(y), 1) cost = tl.cost.cross_entropy(y, y_, 'cost') # + reg1 + reg2 + reg3 correct_prediction = tf.equal(tf.argmax(y, 1), y_) acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) y_op = tf.argmax(tf.nn.softmax(y), 1) # define the optimizer train_params = network.all_params train_op = tf.train.AdamOptimizer( learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False, ).minimize(cost, var_list=train_params) # initialize all variables in the session tl.layers.initialize_global_variables(sess) # print network information network.print_params() network.print_layers() # train the network tl.utils.fit(sess, network, train_op, cost, X_train, y_train, x, y_, acc=acc, batch_size=32, n_epoch=5, print_freq=1, X_val=X_val, y_val=y_val, eval_train=False) sess.close() # import pdb # pdb.set_trace() # y = network.outpu # y = network.outputs # cost = tl.cost.cross_entropy(y, y_, 'cost') # import pdb # pdb.set_trace() # # import pdb # # pdb.set_trace() # network = regression(network, optimizer='adam', learning_rate=0.001, # loss='categorical_crossentropy', name='target') # # Training # model = tflearn.DNN(network, tensorboard_verbose=0) # model.fit(X_train, y_train, n_epoch=5, shuffle=True, validation_set=( # X_val, Y_val), show_metric=True, batch_size=32)
edf5c327f33d0adac1a3638e4f67ab810ad40c7d
shadowleaves/deep_learning
/mxnet/mxnet_binary.py
8,507
3.515625
4
#!/usr/bin/env python import mxnet as mx import numpy as np from rnn import rnn_unroll, DataIter # from minpy_binary import create_dataset, printSample def create_dataset(nb_samples, sequence_len): """Create a dataset for binary addition and return as input, targets.""" max_int = 2**(sequence_len - 1) # Maximum integer that can be added # Transform integer in binary format format_str = '{:0' + str(sequence_len) + 'b}' nb_inputs = 2 # Add 2 binary numbers nb_outputs = 1 # Result is 1 binary number X = np.zeros((nb_samples, sequence_len, nb_inputs)) # Input samples T = np.zeros((nb_samples, sequence_len, nb_outputs)) # Target samples # Fill up the input and target matrix for i in xrange(nb_samples): # Generate random numbers to add nb1 = np.random.randint(0, max_int) nb2 = np.random.randint(0, max_int) # Fill current input and target row. # Note that binary numbers are added from right to left, # but our RNN reads from left to right, so reverse the sequence. X[i, :, 0] = list(reversed([int(b) for b in format_str.format(nb1)])) X[i, :, 1] = list(reversed([int(b) for b in format_str.format(nb2)])) T[i, :, 0] = list(reversed([int(b) for b in format_str.format(nb1 + nb2)])) return X, T # Show an example input and target def printSample(x1, x2, t, y=None): """Print a sample in a more visual way.""" x1 = ''.join([str(int(d)) for d in x1]) x2 = ''.join([str(int(d)) for d in x2]) t = ''.join([str(int(d[0])) for d in t]) if y is not None: y = ''.join([str(int(d[0])) for d in y]) print('x1: {:s} {:2d}'.format(x1, int(''.join(reversed(x1)), 2))) print('x2: + {:s} {:2d} '.format(x2, int(''.join(reversed(x2)), 2))) print(' ------- --') print('t: = {:s} {:2d}'.format(t, int(''.join(reversed(t)), 2))) if y is not None: print('y: = {:s} {:2d}'.format(y, int(''.join(reversed(y)), 2))) print '\n' def xavier(shape, coef=1.0): n_in, n_out = shape a = np.sqrt(6.0 / (n_in + n_out)) * coef res = mx.random.uniform(low=-a, high=a, shape=shape) return res def loss_func(label, pred, ep=1e-10): loss = -np.sum(np.multiply(label, np.log(pred + ep)) + np.multiply((1 - label), np.log(1 - pred + ep))) \ / (pred.shape[0] * pred.shape[1]) return loss # class RMSProp(mx.optimizer.Optimizer): # def __init__(self, decay=0.95, momentum=0.9, **kwargs): # super(RMSProp, self).__init__(**kwargs) # self.decay = decay # self.momentum = momentum # def create_state(self, index, weight): # """Create additional optimizer state: mean, variance # Parameters # ---------- # weight : NDArray # The weight data # """ # return (mx.nd.zeros(weight.shape, weight.context), # cache # # mx.nd.zeros(weight.shape, weight.context), # g # mx.nd.zeros(weight.shape, weight.context)) # delta # def update(self, index, weight, grad, state, ep=1e-6): # """Update the parameters. # Parameters # ---------- # index : int # An unique integer key used to index the parameters # weight : NDArray # weight ndarray # grad : NDArray # grad ndarray # state : NDArray or other objects returned by init_state # The auxiliary state used in optimization. # """ # assert(isinstance(weight, mx.nd.NDArray)) # assert(isinstance(grad, mx.nd.NDArray)) # lr = self._get_lr(index) # # wd = self._get_wd(index) # self._update_count(index) # cache, delta = state # # grad = grad * self.rescale_grad # # if self.clip_gradient is not None: # # grad = clip(grad, -self.clip_gradient, self.clip_gradient) # cache[:] = (1 - self.decay) * (grad * grad) + self.decay * cache # # g[:] = (1 - self.decay) * grad + self.decay * g # grad_norm = grad / mx.nd.sqrt(cache + ep) # + wd * weight # delta[:] = (self.momentum) * delta - lr * grad_norm # weight[:] += delta # # import pdb # # pdb.set_trace() if __name__ == '__main__': # Create dataset nb_train = 2000 # Number of training samples nb_test = 100 num_hidden = 3 n_inputs = 2 n_labels = 1 # Addition of 2 n-bit numbers can result in a n+1 bit number seq_len = 7 # Length of the binary sequence batch_size = 100 # Create training samples seed = 2 np.random.seed(seed) mx.random.seed(seed) init_states = [ ('init_h', (batch_size, num_hidden)), # ('wx', (num_hidden, n_inputs)), # , num_hidden)), # ('wh', (num_hidden, num_hidden)), # ('b', (num_hidden, )), # ('wa', (n_labels, num_hidden)), # ('ba', (n_labels, )), ] # X, T = create_dataset(nb_train, seq_len) data_train = DataIter(nb_train, batch_size, seq_len, n_inputs, n_labels, init_states, create_dataset=create_dataset) # data_eval = DataIter(500, batch_size, n_inputs, init_states) wx = mx.sym.Variable('wx') wh = mx.sym.Variable('wh') b = mx.sym.Variable('b') wa = mx.sym.Variable('wa') ba = mx.sym.Variable('ba') sym = rnn_unroll(wx, wh, b, wa, ba, seq_len=seq_len, n_inputs=2, num_hidden=3, n_labels=1, batch_size=batch_size) # mod = mx.mod.Module(sym) # from sys import platform # ctx = mx.context.gpu(0) if platform == 'darwin' else mx.context.cpu(0) arg_params = { 'init_h': mx.nd.zeros((batch_size, num_hidden)), 'wx': xavier((num_hidden, n_inputs)), 'wh': xavier((num_hidden, num_hidden)), 'b': mx.nd.zeros((num_hidden, )), 'wa': xavier((n_labels, num_hidden)), 'ba': mx.nd.zeros((n_labels, )), } from utils.timedate import timing import logging head = '%(asctime)-15s %(message)s' logging.basicConfig(level=logging.DEBUG, format=head) opt_params = {'learning_rate': 0.01, 'gamma1': 0.5, 'gamma2': 0.8, # decay=0.5, # decay, gamma1 # momentum=0.8, # momentum, gamma2 } # optimizer = mx.optimizer.RMSProp(**opt_params) eval_metric = mx.metric.create(loss_func) n_epochs = 20 t0 = timing() if False: model = mx.model.FeedForward( # ctx=ctx, symbol=sym, num_epoch=n_epochs, optimizer='RMSProp', # optimizer_params=opt_params, # eval_metric=eval_metric, arg_params=arg_params, **opt_params ) model.fit(X=data_train, eval_metric=eval_metric, batch_end_callback=mx.callback.Speedometer(batch_size, 20), ) else: module = mx.mod.Module(sym, data_names=('data',), label_names=('label',), ) module.bind(data_shapes=data_train.provide_data, label_shapes=data_train.provide_label, for_training=True, # default ) module.init_params(arg_params=arg_params) if False: module.fit(data_train, optimizer='RMSProp', # mx.optimizer.RMSProp, optimizer_params=opt_params, num_epoch=n_epochs, eval_metric=eval_metric, ) else: module.init_optimizer(kvstore='local', optimizer='RMSProp', optimizer_params=opt_params) for epoch in xrange(n_epochs): for idx, batch in enumerate(data_train): module.forward(batch, is_train=True) module.backward() module.update() module.update_metric(eval_metric=eval_metric, labels=batch.label) res = module.score(data_train, eval_metric) print res[0] timing(t0, 'mxnet', 's')
3bc0d6c4c609c1b412a9f4cc8d0855519079178a
guispecian/FATEC-MECATRONICA-1600792021024-Guilherme
/LTP1-2020-2/Pratica06/programa09.py
216
3.796875
4
#Repetição Infinita (Cuidado, pois se a variavel somatorio for = 1; o programa nunca acaba) somatoria = 0 while True: print(somatoria) somatoria = somatoria + 10 if somatoria == 100: break print("Fim")
67878144c8ee495452dbd731515c0858a040c586
guispecian/FATEC-MECATRONICA-1600792021024-Guilherme
/LTP1-2020-2/Pratica11/programa01.py
478
4.0625
4
#Calculo da area do triangulo #Função para calculo do semiperimetro def semiperimetro(a,b,c): return (a+b+c)/2 #Função para calculo da area def area(a,b,c): s = semiperimetro(a,b,c) return (s*(s-a)*(s-b)*(s-c)) ** 0.5 #Programação Principal #Informe os lados A, B e c a = int(input('Informe o valor do lado A:')) b = int(input('Informe o valor do lado B:')) c = int(input('Informe o valor do lado C:')) #Calculo da area print('O valor da area é:', area(a,b,c))
70c81e53b62d9adcedb92dbec0e4d7a2eb4b46e0
anhtu96/algorithms
/sorting/counting_sort.py
586
3.5
4
def counting_sort_1(arr): maxval = max(arr) sorted_arr = [] L = [None] * (maxval + 1) for i in arr: if L[i]: L[i].append(i) else: L[i] = [i] for i in L: sorted_arr.extend(i) return sorted_arr def counting_sort_2(arr): maxval = max(arr) sorted_arr = [None] * len(arr) C = [0] * (maxval + 1) for i in arr: C[i] += 1 for i in range(len(C)): if i > 0: C[i] += C[i-1] for i in reversed(arr): sorted_arr[C[i] - 1] = i C[i] -= 1 return sorted_arr
b699ab088ff08f3c0c5c9f6cbb4d2a1564acd528
anhtu96/algorithms
/graph_algorithms/bfs.py
652
3.9375
4
from collections import deque class BFSResult(object): def __init__(self): self.level = {} self.parent = {} def bfs(g, s): """ Queue-based implementation of BFS. Args: - g: a graph with adjacency list adj s.t g.adj[u] is a list of u's neighbors. - s: source vertex. """ r = BFSResult() r.parent = {s: None} r.level = {s: 0} queue = deque() queue.append(s) while queue: u = queue.popleft() for n in g.neighbors(u): if n not in r.level: r.parent[n] = u r.level[n] = r.level[u] + 1 queue.append(n) return r
b5ea314bac79c17cc8ff66f43b999cc6a02ac2fb
EliasKassapis/Deep-Learning
/assignment_1/code/mlp_numpy.py
3,136
4.125
4
""" This module implements a multi-layer perceptron (MLP) in NumPy. You should fill in code into indicated sections. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from modules import * class MLP(object): """ This class implements a Multi-layer Perceptron in NumPy. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward and backward. """ def __init__(self, n_inputs, n_hidden, n_classes): """ Initializes MLP object. Args: n_inputs: number of inputs. n_hidden: list of ints, specifies the number of units in each linear layer. If the list is empty, the MLP will not have any linear layers, and the model will simply perform a multinomial logistic regression. n_classes: number of classes of the classification problem. This number is required in order to specify the output dimensions of the MLP TODO: Implement initialization of the network. """ ######################## # PUT YOUR CODE HERE # ####################### self.n_hidden = n_hidden #initialize input layer a_0 = LinearModule(n_inputs,n_hidden[0]) z_0 = ReLUModule() self.layers = [a_0] self.layer_out = [z_0] #initialize hidden_layers for l in range(len(n_hidden)-1): current_a = LinearModule(n_hidden[l],n_hidden[l + 1]) current_z = ReLUModule() self.layers.append(current_a) self.layer_out.append(current_z) #initialize last layer a_N = LinearModule(n_hidden[-1],n_classes) z_N = SoftMaxModule() self.layers.append(a_N) self.layer_out.append(z_N) # raise NotImplementedError ######################## # END OF YOUR CODE # ####################### def forward(self, x): """ Performs forward pass of the input. Here an input tensor x is transformed through several layer transformations. Args: x: input to the network Returns: out: outputs of the network TODO: Implement forward pass of the network. """ ######################## # PUT YOUR CODE HERE # ####################### #forward pass for i in range(len(self.n_hidden)+1): x = self.layers[i].forward(x) x = self.layer_out[i].forward(x) # raise NotImplementedError ######################## # END OF YOUR CODE # ####################### return x def backward(self, dout): """ Performs backward pass given the gradients of the loss. Args: dout: gradients of the loss TODO: Implement backward pass of the network. """ ######################## # PUT YOUR CODE HERE # ####################### for i in range(len(self.n_hidden), -1, -1): dout = self.layer_out[i].backward(dout) dout = self.layers[i].backward(dout) # raise NotImplementedError ######################## # END OF YOUR CODE # ####################### return
b0a0ec721c9f7571a4f294c1b05aa07b3b82c2eb
marcozpina/DevNet
/AgendaTelefonica.py
1,362
4.09375
4
agenda_telefonica = {} while True: print () print ("-------- .: Menu :. --------\n") print ("1.- Ingresar nuevo contacto\n") print ("2.- Eliminar contacto\n") print ("3.- Consultar contactos\n") print ("4.- Salir del programa\n") select = int (input("Selecciona una opcion: ")) print () if select == 1: name = str (input("Nombre: ")) #last = str (input("Apellido: ")) phone = input ("Telefono: ") print () if name not in agenda_telefonica: agenda_telefonica [name] = phone print (" -- Contacto agregado correctamente --\n") elif select == 2: name = input ("Selecciona el nombre que quieres eliminar: ") if name in agenda_telefonica: del (agenda_telefonica [name]) print ("Contacto eliminado correctamente\n") else: print ("Este contacto no existe") elif select == 3: if name in agenda_telefonica: for name,phone in agenda_telefonica.items(): print ("Estos son todos los contactos: \n") print (f"Nombre: {name}, Telefono: {phone}") else: print ("No hay contactos aún") elif select == 4: print (" .: Hasta pronto :. \n") break else: print ("Opcion inválida")
0ef332e089b580d4c64f222ea88a6c8c0fb6d52e
arinanda/huffman-code-implementation-webapps
/storage/compressor/huffman/adaptive_huffman/adaptive_huffman.py
1,600
3.625
4
from common.util import Node def insert_node(null, char): char_node = Node(char, 1) empty_node = Node(parent=null.parent, left=null, right=char_node) char_node.parent = empty_node if null.parent: if null is null.parent.left: null.parent.left = empty_node else: null.parent.right = empty_node null.parent = empty_node return char_node def get_code(node): code = str() while node.parent is not None: if node.parent.left is node: code = '0' + code else: code = '1' + code node = node.parent return '0' + code def swap(a, b): if a and b: if a.value > b.value: if a.parent.left is a: a.parent.left = b else: a.parent.right = b if b.parent.left is b: b.parent.left = a else: b.parent.right = a a.parent, b.parent = b.parent, a.parent def update_tree(root): while root: if root.parent: sibling = root.parent.right if root.parent.left is root else root.parent.left swap(root.left, sibling) swap(root.right, sibling) swap(root.left, root.right) if root.left and root.right: root.value = root.left.value + root.right.value root = root.parent def print_tree(root, space=0): if space == 0: print('\n\n') if root: print('%s%s' % (' ' * space, str(root))) print_tree(root.left, space+2) print_tree(root.right, space+2)
30da36f468a59b34608639ecf55725b37457a0a1
daniel-paul/Farm-Simulation
/Agent.py
8,522
3.65625
4
import math import copy import random import time from Simulator import Simulator # Main Agent class class Agent: def __init__(self, size, timeLimit): self.simulator = Simulator(size) # Simulator instance of the farm self.monteCarlo = MonteCarloTreeSearch(size) # Instance of the MonteCarloTreeSearch self.timeLimit = timeLimit # Limit of time for action (in seconds) self.totalFood = 0 # Total food harvested by the agent def run(self): while not self.simulator.complete: nextMove = self.monteCarlo.findNextMove(self.simulator, self.timeLimit) # Decide next action self.totalFood += makeMove(self.simulator, nextMove) # Execute it print(nextMove.actionName) # Print action completed print("Total food units: " + str(self.totalFood)) # Helper function that applies the action contained in move to the simulator instance def makeMove(simulator, move): if move.action == 0: return simulator.plantBean(move.actionX, move.actionY) elif move.action == 1: return simulator.plantCorn(move.actionX, move.actionY) elif move.action == 2: return simulator.harvest(move.actionX, move.actionY) else: return simulator.simulateDay() # Class that implements the MonteCarloTreeSearch class MonteCarloTreeSearch: def __init__(self, size): self.size = size self.tree = Tree(size) self.maxScore = 15 * size * size # this is an approximation of the max score possible, # to have the scores in a range from 0 to 1 def findNextMove(self, simulator, timeLimit): start_time = time.time() while time.time() - start_time < timeLimit: # Creates a copy of the simulator, all the moves will be applied in this copy tempSimulator = copy.deepcopy(simulator) # Select a Leaf Node from the tree and applies all the moves to the simulator leaf = self.selectLeafNode(self.tree.root, tempSimulator) if not tempSimulator.complete: # If the node is not terminal expands it self.expandNode(leaf) nodeToExplore = leaf if len(leaf.children) > 0: # Selects a random Child from the Leaf and applies that action to the simulator nodeToExplore = leaf.getRandomChild(tempSimulator) # Applies random movements to the last node and gets the final score simulationResult = self.simulateRandomPlay(nodeToExplore, tempSimulator) # Applies the score to the all the explored nodes involved self.backPropagation(nodeToExplore, simulationResult) # Selects the best child bestChild = self.tree.root.getBestChild() self.tree.root = bestChild bestChild.parent = False # Return the action return bestChild.action # Selects the best child now using UCB score until reach a leaf Node, if one of the actions is not possible, # removes it from the children and selects another def selectLeafNode(self, node, simulator): while len(node.children) > 0: success = -1 while success == -1: best = None bestScore = -1 for child in node.children: score = child.getUCBscore() if score > bestScore: best = child bestScore = score success = makeMove(simulator, best.action) if success == -1: node.children.remove(best) best.food = node.food + success node = best return node # Expand the node, creating a new child for each possible Move def expandNode(self, node): possibleMoves = node.getPossibleMoves() for action in possibleMoves: newNode = Node(self.size, action) newNode.parent = node node.children.append(newNode) # Simulate 'random' plays from the simulator and returns the efficiency of the farm def simulateRandomPlay(self, node, simulator): food = node.food while not simulator.complete: food += self.randomMove(simulator) return food / self.maxScore # Applies the score to all the nodes until reach the root def backPropagation(self, node, score): while node: node.score += score node.visitCount += 1 node = node.parent # Generate a 'random' move, it will only call simulateDay() if there is not any other option def randomMove(self, simulator): possibleMoves = self.size * self.size * 3 move = random.randint(0, possibleMoves - 1) success = -1 count = 0 while count < possibleMoves and success == -1: opt = move % 3 posX = int(move / 3) % self.size posY = int(int(move / 3) / self.size) if opt == 0: success = simulator.plantBean(posX, posY) elif opt == 1: success = simulator.plantCorn(posX, posY) else: success = simulator.harvest(posX, posY) count += 1 move = (move + 1) % possibleMoves if success == -1: success = simulator.simulateDay() return success # Tree class used by the MonteCarlo Tree Search class Tree: def __init__(self, size): action = Action(-1, 0, 0) self.root = Node(size, action) # Node class class Node: def __init__(self, size, action): self.size = size self.action = action # Information about the last action performed to reach the node self.parent = None # Parent of the Node self.children = [] # List of child nodes self.visitCount = 0.0 # Number of visits to this node self.score = 0.0 # Sum of all the scores obtained by this node self.c = 1.41 self.food = 0 # Food harvested until this node # Returns the UCB score of the node def getUCBscore(self): if self.visitCount == 0.0: return 1000000 else: return self.score / self.visitCount + self.c * math.sqrt(math.log(self.parent.visitCount) / self.visitCount) # Returns the child with best average score def getBestChild(self): best = None bestScore = -1 for child in self.children: score = child.score / child.visitCount if child.visitCount > 0 else 0 if score > bestScore: bestScore = score best = child return best # Returns a random child node and applies the action contained by it to the simulator, # if the action is not valid it chooses a different child and remove the previous from the list def getRandomChild(self, simulator): success = -1 while success == -1: childNumber = random.randint(0, len(self.children) - 1) success = makeMove(simulator, self.children[childNumber].action) if success == -1: self.children.remove(self.children[childNumber]) self.children[childNumber].food = self.food + success return self.children[childNumber] # Generate an array containing all the possible actions def getPossibleMoves(self): possibleMoves = [] action = Action(3, 0, 0) action.actionName = "Next day" possibleMoves.append(action) for i in range(self.size): for j in range(self.size): action = Action(0, i, j) action.actionName = "Plant beans in: " + str(i) + "," + str(j) possibleMoves.append(action) action = Action(1, i, j) action.actionName = "Plant corn in: " + str(i) + "," + str(j) possibleMoves.append(action) action = Action(2, i, j) action.actionName = "Harvest: " + str(i) + "," + str(j) possibleMoves.append(action) return possibleMoves # Indicates an action performed by the agent class Action: def __init__(self, action, x, y): self.actionName = None # Description of the action self.action = action # 0 plant beans, 1 plant corn, 2 harvest, 3 next day self.actionX = x # coordinate x of the action (for plant or harvest) self.actionY = y # coordinate y of the action (for plant or harvest)
a098d9405d28447a47f63db41a3500732cd21cb0
roshna1924/Python
/ICP4/sourcecode/naivebayes.py
962
3.75
4
#----------- Importing dataset -----------# import pandas as pd glass=pd.read_csv("glass.csv") #Preprocessing data X = glass.drop('Type',axis=1) Y = glass['Type'] #----------Splitting Data-----------# # Import train_test_split function from sklearn import model_selection # Split dataset into training set and test set X_train,X_test,Y_train,Y_test=model_selection.train_test_split(X,Y,test_size=0.2) #-----------Model Generation ----------# #Import Gaussian Naive Bayes model from sklearn.naive_bayes import GaussianNB #Create a Gaussian Classifier model=GaussianNB() #Train the model using the training sets model.fit(X_train,Y_train) #Predict the response for test dataset Y_pred=model.predict(X_test) #----------Evaluating the model -------------# from sklearn import metrics # Model Accuracy, how often is the classifier correct? print("accuracy score:",metrics.accuracy_score(Y_test,Y_pred)) print(metrics.classification_report(Y_test, Y_pred))
7cdaebe77cfb044dfc16e01576311244caae283f
roshna1924/Python
/ICP1/Source Code/operations.py
590
4.125
4
num1 = int(input("Enter first number: ")) num2 = int(input("Enter Second number: ")) operation = int(input("Enter 1 for addition\n" "Enter 2 for Subtraction\n" "Enter 3 for multiplication\n" "Enter 4 for division\n")) def arithmeticOperations(op): switcher = { 1: "Result of addition : " + str(num1 + num2), 2: "Result of Subtraction : " + str(abs(num1 - num2)), 3: "Result of multiplication : " + str(num1 * num2), 4: "Result of division : " + str(num1 / num2) } print(switcher.get(op, "invalid operation\n")) arithmeticOperations(operation)
bf98bd690471b14034136df54ebe676bb2e5b920
ryanpjbyrne/coffeecode2
/hello.py
90
3.71875
4
print("hello world") fruits= ["apple", "pear", "oranges"] for i in fruits: print(i)
0909e53fa788ef88debd3a3bceb5226b7e371332
vincentGuerlais/matCutPy
/matCutPy.py
2,116
3.546875
4
#! /usr/bin/env python import os import sys #################### ### Get Help #################### # print the help and exit the programm def getHelp() : print """matCutPy help Usage : python matCutPy.py input_file cutoff matCutPy generate a list of IDs with a total of estimated RNA-Seq fragment counts above a specified cutoff. The output file is named 'input_file'.cut """ sys.exit() # Is the first argument a call for help ? or is there the amount of required arguments ? if len(sys.argv)!=3 : getHelp() #################### ### Variables #################### #input file name inFileName = sys.argv[1] #output file name outFileName = inFileName + '.cut' #cutoff value cutoff_var = int(sys.argv[2]) #Do the files exist ? if not os.path.isfile(inFileName) : print inFileName, " can't be found \n" getHelp() #################### ### Functions #################### def readMatrix(matrixFile, outFileName, cutoff) : readFile = open(matrixFile, 'r') outFile = open(outFileName, 'w') readFile.readline() for line in readFile : cols = line.split() if keepID(cols,cutoff) : outFile.write(cols[0]+'\n') readFile.close() outFile.close() def keepID(colList,cutoff): #Returns True if 1/4 of the values are above the cutoff keep = False supColNb = 0 cols = colList[1:] #number of col needed to be true minColNb = len(cols)/4 if len(cols)%4 != 0 : minColNb += 1 for col in cols : if float(col) > cutoff : supColNb += 1 if supColNb >= minColNb : keep = True return keep #################### ### Main #################### #printing a line to know that the programm is running. to be removed ? print "running matCutPy" readMatrix(inFileName, outFileName, cutoff_var) #programm is over print "done matCutPy"
8d7937fd6aa3583e7c7937587f550f7809ac5f7a
aghyadalbalkhi-ASAC/Game_of_Greed
/game_of_greed/game_logic.py
2,593
3.5625
4
from abc import abstractmethod, ABC from collections import Counter import random class GameLogic(ABC): def __init__(self): pass @staticmethod def calculate_score(tupleInt): rules={ 1:{1:100,2:200,3:1000,4:2000,5:3000,6:4000}, 2:{1:0,2:0,3:200,4:400,5:600,6:800}, 3:{1:0,2:0,3:300,4:600,5:900,6:1200}, 4:{1:0,2:0,3:400,4:800,5:1200,6:1600}, 5:{1:50,2:100,3:500,4:1000,5:1500,6:2000}, 6:{1:0,2:0,3:600,4:1200,5:1800,6:2400}, 7:1500, #stight 8:1500 #three pairs } #input -> tuple(integers) counter = Counter(tupleInt) result= counter.most_common() # output -> integer depend on the rules score=0 if len(tupleInt) == 0: return 0 if counter.most_common(1)[0][1] == 1 and len(tupleInt) == 6: return rules[7] if len(tupleInt) == 6 and len(result)==3 and result[0][1] == 2: return rules[8] for i in result: score+=rules[i[0]][i[1]] return score #implement the rules @staticmethod def roll_dice(dice_result=6): '''#input - > integer (1-6) //randint for the dice number in the round #output -> tuples of the values of theses dices ''' rand = [random.randint(1,6) for i in range(dice_result)] return tuple(rand) class Banker(ABC): def __init__(self): self.balance=0 self.shelved=0 def shelf(self,amount): # input -> amount of point self.shelved+=amount # shelf should temporarily store unbanked points. def bank(self): # The Total Points self.balance+=self.shelved self.clear_shelf() # add the amount of shelf to the bank and clear shelf # output -> the total of Point def clear_shelf(self): #remove all unbanked points //Falkel self.shelved=0 if __name__ == "__main__": greed = GameLogic() tuple2 = (5,) print(GameLogic.roll_dice()) print(GameLogic.roll_dice(2)) print(GameLogic.roll_dice(5)) print(GameLogic.roll_dice(6)) print(dir(Banker))
b314f7dbe6ddf2741b5f782b4abecdb9c6fbc5e9
ColinPLambe/MediumWebScraper
/mediumScraper.py
2,567
3.53125
4
from bs4 import BeautifulSoup import requests import sys import os.path """ Colin Lambe A Webscraper to get the number of words, number of claps, and article text from articles on Medium.com Uses BeatifulSoup4 and Requests """ class MediumScraper: def scrape(self, url, minWords, minClaps): #gets the article source code from the url source = requests.get(url).text page = BeautifulSoup(source, "lxml") #the article itself still with html context article = page.find('article') #the name of the article name = article.find('h1').text #if file already exists don't save again stripped_name = name.replace(" ", "") if os.path.isfile(f"./{stripped_name}.txt") : print("File has already been processed") else: #gather the html free text of the article from the paragraph tags text = [] for par in article.find_all('p'): text = text + par.text.split(" ") #finds the claps button and determines the number of claps for button in page.find_all('button'): if "claps" in button.text: num_claps = button.text num_claps = num_claps.split(" ")[0] if "K" in num_claps: num_claps = int(float(num_claps.replace("K", "")) * 1000) elif "M" in num_claps: num_claps = int(float(num_claps.replace("M", "")) * 1000000) else: num_claps = int(num_claps) if text.__len__() > minWords: if num_claps > minClaps: MediumScraper.save_contents(self, url, name, text.__len__(), num_claps, " ".join(text)) else: print("Not Enough Claps") else: print("Not Enough Words") """ Saves the article to a file file name is the name of the article with white space removed and .txt extension file format follows: name url number of words number of claps article text """ def save_contents(self,url, name, words, claps, text): stripped_name = name.replace(" ", '') file = open(f"{stripped_name}.txt", "w") file.write(f"""Article Name: {name} Article Url: {url} Number of Words: {words} Number of Claps: {claps} {text}""") if __name__ == "__main__": MediumScraper.scrape(MediumScraper, sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
b749422d017a275cf98d99062a852942d7bd6178
Mara-d/Prototype-sorting-algorithms-with-numbers
/Prototype-Sorting Algorithms/Sorting Algorithms Proto.py
7,294
3.96875
4
import time import random import tkinter as tk from tkinter import * import threading # This is a prototype, seeing numbers getting sorted in real time helps me visualize the algorithms better, # This program is by far finished, this is just a concept # I plan to have an OOP approach in the future window = tk.Tk(className="Sorting Algorithms with NUMBERS") window.geometry("1200x800") window['bg'] = 'grey' a_list = [i for i in range(20)] def bubble_sort(nums): random.shuffle(nums) swapped = True while swapped: swapped = False for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: nums[i], nums[i + 1] = nums[i + 1], nums[i] time.sleep(2) for output in range(1): frame = Frame(window, width=150, height=5, padx=20, pady=5) frame.grid(row=2, column=0, columnspan=7) blank = Text(frame, wrap=WORD) blank.pack() blank.insert(END, nums) blank.configure(state=DISABLED) swapped = True def selection_sort(nums): random.shuffle(nums) for i in range(len(nums)): lowest_value_index = i for j in range(i + 1, len(nums)): if nums[j] < nums[lowest_value_index]: lowest_value_index = j nums[i], nums[lowest_value_index] = nums[lowest_value_index], nums[i] time.sleep(2) frame = Frame(window, width=150, height=5, padx=20, pady=5) frame.grid(row=2, column=0, columnspan=7) blank = Text(frame, wrap=WORD) blank.pack() blank.insert(END, nums) blank.configure(state=DISABLED) def insertion_sort(nums): random.shuffle(nums) for i in range(1, len(nums)): item_to_insert = nums[i] j = i - 1 while j >= 0 and nums[j] > item_to_insert: nums[j + 1] = nums[j] j -= 1 nums[j + 1] = item_to_insert time.sleep(2) frame = Frame(window, width=150, height=5, padx=20, pady=5) frame.grid(row=2, column=0, columnspan=7) blank = Text(frame, wrap=WORD) blank.pack() blank.insert(END, nums) blank.configure(state=DISABLED) def heapify(nums, heap_size, root_index): largest = root_index left_child = (2 * root_index) + 1 right_child = (2 * root_index) + 2 if left_child < heap_size and nums[left_child] > nums[largest]: largest = left_child if right_child < heap_size and nums[right_child] > nums[largest]: largest = right_child if largest != root_index: nums[root_index], nums[largest] = nums[largest], nums[root_index] heapify(nums, heap_size, largest) def heap_sort(nums): random.shuffle(nums) n = len(nums) for i in range(n, -1, -1): heapify(nums, n, i) for i in range(n - 1, 0, -1): nums[i], nums[0] = nums[0], nums[i] heapify(nums, i, 0) time.sleep(2) frame = Frame(window, width=150, height=5, padx=20, pady=5) frame.grid(row=2, column=0, columnspan=7) blank = Text(frame, wrap=WORD) blank.pack() blank.insert(END, nums) blank.configure(state=DISABLED) def merge(left_list, right_list): sorted_list = [] left_list_index = right_list_index = 0 left_list_length, right_list_length = len(left_list), len(right_list) for _ in range(left_list_length + right_list_length): if left_list_index < left_list_length and right_list_index < right_list_length: if left_list[left_list_index] <= right_list[right_list_index]: sorted_list.append(left_list[left_list_index]) left_list_index += 1 else: sorted_list.append(right_list[right_list_index]) right_list_index += 1 elif left_list_index == left_list_length: sorted_list.append(right_list[right_list_index]) right_list_index += 1 elif right_list_index == right_list_length: sorted_list.append(left_list[left_list_index]) left_list_index += 1 time.sleep(2) for output in range(1): frame = Frame(window, width=150, height=5, padx=20, pady=5) frame.grid(row=2, column=0, columnspan=7) blank = Text(frame, wrap=WORD) blank.pack() blank.insert(END, sorted_list) blank.configure(state=DISABLED) return sorted_list def merge_sort(nums): random.shuffle(nums) if len(nums) <= 1: return nums mid = len(nums) // 2 left_list = merge_sort(nums[:mid]) right_list = merge_sort(nums[mid:]) return merge(left_list, right_list) def partition(nums, low, high): pivot = nums[(low + high) // 2] i = low - 1 j = high + 1 while True: i += 1 while nums[i] < pivot: i += 1 j -= 1 while nums[j] > pivot: j -= 1 if i >= j: return j time.sleep(2) frame = Frame(window, width=150, height=5, padx=20, pady=5) frame.grid(row=2, column=0, columnspan=7) blank = Text(frame, wrap=WORD) blank.pack() blank.insert(END, nums) blank.configure(state=DISABLED) nums[i], nums[j] = nums[j], nums[i] def quick_sort(nums): random.shuffle(nums) def _quick_sort(items, low, high): if low < high: split_index = partition(items, low, high) _quick_sort(items, low, split_index) _quick_sort(items, split_index + 1, high) _quick_sort(nums, 0, len(nums) - 1) t1 = threading.Thread(target=lambda: bubble_sort(a_list)) t1.setDaemon(True) t2 = threading.Thread(target=lambda: selection_sort(a_list)) t2.setDaemon(True) t3 = threading.Thread(target=lambda: insertion_sort(a_list)) t3.setDaemon(True) t4 = threading.Thread(target=lambda: heap_sort(a_list)) t4.setDaemon(True) t5 = threading.Thread(target=lambda: merge_sort(a_list)) t5.setDaemon(True) t6 = threading.Thread(target=lambda: quick_sort(a_list)) t6.setDaemon(True) quit_button = tk.Button(window, text="Quit", command=window.destroy).grid(row=0, column=1, pady=10, padx=40) merge_button = tk.Button(window, text="Merge Sort", command=lambda: t5.start()).grid(row=0, column=2, pady=10, padx=40) bubble_button = tk.Button(window, text="Bubble Sort", command=lambda: t1.start()).grid(row=0, column=3, pady=10, padx=40) quick_button = tk.Button(window, text="Quick Sort", command=lambda: t6.start()).grid(row=0, column=4, pady=10, padx=40) selection_button = tk.Button(window, text="Selection Sort", command=lambda: t2.start()).grid(row=0, column=5, pady=10, padx=40) insertion_button = tk.Button(window, text="Insertion Sort", command=lambda: t3.start()).grid(row=0, column=6, pady=10, padx=40) heap_button = tk.Button(window, text="Heap Sort", command=lambda: t4.start()).grid(row=0, column=7, pady=10, padx=40) if __name__ == "__main__": window.mainloop()
416b79accfdae13f2df358b5b9636403e75b6f62
CxrlosKenobi/cs50
/pset6/Sentimental/readability.py
694
4.0625
4
from cs50 import get_string letters = 0 words = 1 sentences = 0 text = get_string("Text: ") # Here we count the letters in the string for i in range(len(text)): if (text[i] >= 'a' and text[i] <= 'z') or (text[i] >= 'A' and text[i] <= 'Z'): letters += 1 # Here we count the words in the string if text[i] == ' ': words += 1 # Here we count the sentences in the string if text[i] == '.' or text[i] == '!' or text[i] == '?': sentences += 1 # Finnally calculate the index L = letters / words * 100 S = sentences / words * 100 index = round(0.0588 * L - 0.296 * S - 15.8) if index < 1: print("Before Grade 1") elif index >= 16: print("Grade 16+") else: print(f"Grade {index}")
3c839f5ce1fc572fc78255520368ea3ef6952a48
vimleshtech/python_sep2
/oops2.py
389
3.53125
4
class emp: #first argument will take add of object #at least one argument need to recieve def newEmp(self): print(self) self.sid =input('etner data :') self.name =input('enter name :') def show(a): print(a) print(a.sid) print(a.name) o = emp() print(o) o.newEmp() o.show()
4626384e435e06e14c4c69eecd3f760a7c03278f
ivapanic/natprog-2019-2020
/Prijemni/KFC.py
1,280
3.640625
4
import sys def main(): m_meat, s_soy, h_bread = map(float, input().split()) pm_kn, ps_kn = map(float, input().split()) if h_bread == 0: max_earnings = 0 print(max_earnings) elif m_meat == 0 and s_soy == 0: max_earnings = 0 print(max_earnings) else: is_there_any_meat = m_meat > 0 is_there_any_soy = s_soy > 0 if not is_there_any_meat: pm_kn = 0 elif not is_there_any_soy: ps_kn = 0 more_expensive = m_meat if not is_there_any_soy or pm_kn > ps_kn else s_soy better_price = pm_kn if more_expensive == m_meat else ps_kn cheaper = s_soy if more_expensive == m_meat else m_meat worse_price = ps_kn if more_expensive == m_meat else pm_kn is_there_enough_bread = h_bread >= m_meat + s_soy if is_there_enough_bread: max_earnings = more_expensive*better_price + cheaper*worse_price elif h_bread <= more_expensive: max_earnings = h_bread*better_price else: max_earnings = more_expensive*better_price + (h_bread-more_expensive)*worse_price print(int(max_earnings) if float(max_earnings).is_integer() else max_earnings) if __name__ == "__main__": main()
7aa71ae51a60ec0437058f1dbe26e9c8d070764f
BorisBelovA/Python-Labs
/7.1.py
711
3.796875
4
def makeSurnameDict(): my_file = open("students.csv", encoding='utf8') i = 0 dict = {} while True: line = my_file.readline() if(len(line) != 0): #print(line.split(';')) dict[i] = line.split(';') i+=1 else: break dict.pop(0) for i in range(1,len(dict)): dict[i][3] = dict[i][3].replace('\n','') #print(dict) return dict def SortBySurname(i): return i[1] def sortSurname(dict): n = 1 dict = dict surnamArr = [] for i in range(1,len(dict)+1): surnamArr.append(dict[i]) return sorted(surnamArr,key=lambda i: i[n]) dict = makeSurnameDict() print(sortSurname(dict))
bfed59521e007e81c2d062b67feed94de0807a3c
BorisBelovA/Python-Labs
/5.2.py
442
3.8125
4
def makeSurnameArray(): my_file = open("students.csv", encoding='utf8') arr = [] for line in my_file: arr.append(line.split(';')) arr = arr[1::1] for elem in arr: elem[3] = elem[3].replace('\n','') return arr def sortSurname(arr): surnamArr = [] i = 0 while(i<len(arr)): surnamArr.append(arr[i][1]) i+=1 return sorted(surnamArr) print(sortSurname(makeSurnameArray()))
800b7e087ff43e689a00fc75a9bf4a0eb76a490c
BorisBelovA/Python-Labs
/4.2.py
162
3.609375
4
import random i = 0 list = [] while (i<10): list.append(random.randint(0,20)) i+=1 print(list) list = list[2::1] list.append(1) list.append(2) print(list)
cf7b22bbb77b7a208a8573982d2f78e05a01f3a8
arpancodes/100DaysOfCode__Python
/day-9/blind-auction.py
899
3.734375
4
from os import system, name from art import logo # define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') print(logo) print("Welcome to the silent auction for 'The best painting'") all_bids = [] def init(): name = input("What is your name? ") bid = int(input("What is your bid? Rs.")) all_bids.append({ "name": name, "bid": bid }) def calculate_highest_bid(): max_bid = {"name": "", "bid": 0} for x in all_bids: if x["bid"] > max_bid["bid"]: max_bid = x print(f'The maximum bid was Rs.{(max_bid["bid"])} by {max_bid["name"]}') while True: init() should_continue = input("Are there more bidders? Type \"yes\" or \"no\": ") if should_continue == "yes": clear() elif should_continue == "no": clear() calculate_highest_bid() break
1a50d400abbf33d7692ee73d847c7b90b317ab5d
Mahesh-5/Python
/Tic_Tac_Toe.py
3,959
3.90625
4
import random from itertools import combinations class Board(object): def __init__(self): self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)} def display(self): """ Displays tic tac toe board """ d_board = '\nTIC TAC TOE:\n' for pos, obj in self.board.items(): if obj == None: d_board += ' _ ' elif obj == ' X ': d_board += ' X ' elif obj == ' O ': d_board += ' O ' if pos%3 == 0: d_board += '\n' print(d_board) def getAvailable(self): """ Returns available positions """ available = [] for pos, obj in self.board.items(): if obj == None: available.append(pos) return available class Tic_Tac_Toe(Board): pieces = [' O ', ' X '] def __init__(self): super().__init__() self.piece = Tic_Tac_Toe.pieces.pop(random.choice([0,1])) self.cp_piece = Tic_Tac_Toe.pieces[0] def user_setPiece(self, position): """ Position parameter denoted by a number on the keypad (1-9) """ self.board[position] = self.piece def user_getPiece(self): return self.piece def cp_setPiece(self): self.board[random.choice(self.getAvailable())] = self.cp_piece def cp_getPiece(self): return self.cp_piece def checkWin(self, player): """ Checks if move by either the user or computer results in a win """ def at_least_one(A, B): for i in A: for j in B: if i == j: return True return False win_patterns = [(1,2,3),(4,5,6),(7,8,9), (1,4,7),(2,5,8),(3,6,9), (3,5,7),(1,5,9)] spots = [k for k, v in self.board.items() if v == player] spots.sort() player_combinations = list(combinations(spots,3)) if at_least_one(player_combinations, win_patterns) == True: return True return False def checkFullBoard(self): if None not in self.board.values(): self.display() print('Draw! Game board full!') return True return False #--------- def main(): # Setup game game = Tic_Tac_Toe() input('Hello user! Welcome to Tic Tac Toe! Press any key to continue') if game.user_getPiece() == 'X': print('You are X. You are going first.') else: print('You are O. You are going second.') game.cp_setPiece() # Main game loop while True: game.display() position = input('Use the number pad on the lefthand side of your keyboard\nto select your position (1-9):') try: position = int(position) if position in range(1,10): if position in game.getAvailable(): game.user_setPiece(position) else: print('----Please input an available position.') continue else: print('----Please input a number between 1 and 9.') except ValueError: print('----Please input a number.') continue # FOR USER # Check for win if game.checkWin(game.user_getPiece()) == True: game.display() print('Congratulations! You win!') break # Check for full board if game.checkFullBoard() == True: break # FOR COMPUTER game.cp_setPiece() # Check for win if game.checkWin(game.cp_getPiece()) == True: game.display() print('Sorry. You lost.') break # Check for full board if game.checkFullBoard() == True: break if __name__ == '__main__': main()
6cae3ccc0e4287a1ff3225051c788e8a8733ebc0
MaryLivingston21/IndividualProject
/Animal.py
598
3.71875
4
class ANIMAL: def __init__(self, name, breed, age): self.name = name self.breed = breed self.age = age def to_string(self): return self.name + ": a " + str(self.age) + " year old " + self.breed + '\n' def get_name(self): return self.name def get_breed(self): return self.breed def get_age(self): return self.age def __eq__(self, other): return self.name == other.name and self.breed == other.breed and self.age == other.age def __hash__(self): return hash((self.name, self.breed, self.age))
6fe0f6441a3135f71e16c2b276a12c957858ccb5
RyanPeking/tkinter
/贪吃蛇.py
5,763
3.5625
4
import queue import random import threading import time from tkinter import Tk, Button, Canvas class Food(): def __init__(self, queue): self.queue = queue self.new_food() def new_food(self): ''' 功能:产生一个食物 产生一个食物的过程就是随机产生一个食物坐标的过程 :return: ''' # 注意横纵坐标产生的范围 x = random.randrange(5, 480, 10) y = random.randrange(5, 480, 10) self.position = x,y # position存放食物的位置 self.exppos = x-5, y-5, x+5, y+5 # 队列,就是一个不能够随意访问内部元素,只能从头弹出一个元素 # 并只能从队尾追加元素的list # 把一个食物产生的消息放入队列 # 消息的格式,自己定义 # 我的定义是:消息是一个dict,k代表消息类型,v代表此类型的数据 self.queue.put({"food": self.exppos}) class Snake(threading.Thread): ''' 蛇的功能: 1. 蛇能动,由我们的上下左右按键控制 2. 蛇每次动,都需要重新计算蛇头的位置 3. 检测是否游戏完事的功能 ''' def __init__(self, world, queue): threading.Thread.__init__(self) self.world = world self.queue = queue self.points_earned = 0 self.food = Food(queue) self.snake_points = [(495, 55), (485, 55), (465, 55), (455, 55)] self.start() self.direction = 'Left' def run(self): if self.world.is_game_over: self._delete() while not self.world.is_game_over: self.queue.put({"move": self.snake_points}) time.sleep(0.5) self.move() def move(self): ''' 负责蛇的移动 1. 重新计算蛇头的坐标 2. 当蛇头跟食物相遇,则加分,重新生成食物,通知world,加分 3. 否则,蛇需要动 :return: ''' new_snake_point = self.cal_new_pos()#重新计算蛇头位置 # 蛇头位置跟食物位置相同 if self.food.position == new_snake_point: self.points_earned += 1#得分加1 self.queue.put({"points_earned": self.points_earned}) self.food.new_food() else: # 需要注意蛇的信息的保存方式 self.snake_points.pop(0) # 判断程序是否退出,因为新的蛇可能撞墙 self.check_game_over(new_snake_point) self.snake_points.append(new_snake_point) def cal_new_pos(self): last_x, last_y = self.snake_points[-1] if self.direction == "Up": new_snake_point = last_x, last_y - 10# 每次移动10个像素 elif self.direction == "Down": new_snake_point = last_x, last_y + 10 elif self.direction == "Right": new_snake_point = last_x + 10, last_y elif self.direction == "Left": new_snake_point = last_x - 10, last_y return new_snake_point def key_pressed(self, e): # keysym是按键名称 self.direction = e.keysym def check_game_over(self, snake_point): ''' 判断依据是蛇头是否和墙相撞 :param snake_point: :return: ''' x, y = snake_point[0], snake_point[1] if not -5 < x < 505 or not -5 < y < 315 or snake_point in self.snake_points: self.queue.put({'game_over':True}) class World(Tk): def __init__(self, queue): Tk.__init__(self) self.queue = queue self.is_game_over = False # 定义画板 self.canvas = Canvas(self, width=500, height=300, bg='gray') self.canvas.pack() self.snake = self.canvas.create_line((0,0), (0,0), fill="black",width=10) self.food = self.canvas.create_rectangle(0,0,0,0,fill='#FFCC4C', outline='#FFCC4C') self.points_earned = self.canvas.create_text(450, 20, fill='white', text='score:0') self.queue_handler() def queue_handler(self): try: while True: task = self.queue.get(block=False) if task.get("game_over"): self.game_over() if task.get("move"): points = [x for point in task['move'] for x in point] # 重新绘制蛇 self.canvas.coords(self.snake, *points) # 同样道理,还需要处理食物,得分 if task.get("food"): self.canvas.coords(self.food, *task['food']) elif task.get("points_earned"): self.canvas.itemconfigure(self.points_earned, text='SCORE:{}'.format(task['points_earned'])) except queue.Empty: if not self.is_game_over: self.canvas.after(100, self.queue_handler) def game_over(self): ''' 游戏结束,清理现场 :return: ''' self.is_game_over = True self.canvas.create_text(200, 150, fill='white', text="Game Over") qb = Button(self,text="Quit", command=self.destroy) # rb = Button(self, text="Again", command=lambda:self.__init__(self.queue)) self.canvas.create_window(200, 180, anchor='nw', window=qb) # self.canvas.create_window(200, 220, anchor='nw', window=rb) if __name__ == '__main__': q = queue.Queue() world = World(q) snake = Snake(world, q) world.bind('<Key-Left>', snake.key_pressed) world.bind('<Key-Right>', snake.key_pressed) world.bind('<Key-Down>', snake.key_pressed) world.bind('<Key-Up>', snake.key_pressed) world.mainloop()