text
stringlengths
37
1.41M
import sys import pickle class Account: """ This class contains attributes of an account. """ def __init__(self, username, password): # type: (str, str) -> None self.username: str = username self.password: str = password def to_string(self): # type: () -> str return "Username: " + str(self.username) + "\nPassword: " + str(self.password) + "\n" def main(): """ This class is used to run the program. :return: """ accounts: list # initial value print("Enter 1 to sign-up.") print("Enter 2 to login.") filename: str = "Accounts Saved" try: accounts = pickle.load(open(filename, "rb")) except FileNotFoundError: accounts = [] option: int = int(input("Please enter a number: ")) while option < 1 or option > 2: option = int(input("Invalid input! Please enter a number: ")) if option == 1: usernames_used: list = [accounts[i].username for i in range(len(accounts))] username: str = input("Please enter your username: ") while username in usernames_used: username = input("Username already used! Please enter another username: ") password: str = input("Please enter your password: ") new_account: Account = Account(username, password) print("Your new account's details are as below.\n", new_account.to_string()) accounts.append(new_account) else: print("Please login to your account.") username: str = input("Please enter your username: ") password: str = input("Please enter your password: ") has_match: bool = False # initial value for account in accounts: if account.username == username and account.password == password: has_match = True break if not has_match: print("Invalid username or password!") else: print("Login successful!") pickle.dump(accounts, open(filename, "wb")) sys.exit() main()
from twython import TwythonStreamer import json # appending data to a global variable is pretty poor form # but it makes the example much simpler tweets = [] class MyStreamer(TwythonStreamer): """our own subclass of TwythonStreamer that specifies how to interact with the stream""" def on_success(self, data): """what do we do when twitter sends us data? here data will be a Python object representing a tweet""" # only want to collect English-language tweets if data['lang'] == 'en': #tweet = data.split(',"text":"')[1].split('","source')[0] tweet = data['text'] tweets.append(tweet) #with open('tweetes.txt', 'a') as t_obj: #t_obj.write(tweet) # stop when we've collected enough if len(tweets) >= 100: self.disconnect() def on_error(self, status_code, data): print(status_code, data) self.disconnect() stream = MyStreamer("Consumer Key", "Consumer Secret ", "Access Token", "Access Token Secret") # starts consuming public statuses that contain the keyword 'data' stream.statuses.filter(track='donald trump') #with open('tweets.json', 'w') as f_obj: #json.dump(tweets,f_obj) for r_tweet in tweets: print(r_tweet)
import tkinter as tk import os import csv from tkinter import messagebox window = tk.Tk() window.title('Login') window.geometry('300x200+100+100') def option(): with open("login_credentials.csv", "r") as csv_file: data = csv.reader(csv_file, delimiter=",") for i in data: if i[1] == e1.get() and i[2] == e2.get(): window.destroy() os.system('option.py') e1.delete(0, "end") e2.delete(0, "end") messagebox.showwarning("Wrong Credentials!!!", "Your User Name or Password is incorrect. Please Try Again!!!") def signup(): window.destroy() os.system('signup.py') l1 = tk.Label(window, text="User Name :-") l1.place(x=20, y=60) l2 = tk.Label(window, text="Password :-") l2.place(x=20, y=90) l3 = tk.Label(window, text="LogIN") l3.place(x=120, y=10) e1 = tk.Entry(window) e1.place(x=120, y=60) e2 = tk.Entry(window, show="*") e2.place(x=120, y=90) b1 = tk.Button(window, text ="LogIn", command=option) b1.place(x=70, y=130) b2 = tk.Button(window, text ="SignUp", command=signup) b2.place(x=170, y=130) window.mainloop()
""" In order to improve customer experience, Amazon has developed a system to provide recommendations to the customers regarding the items they can purchase. Based on historical customer purchase information, an item association can be defined as - if an item A is ordered by a customer, then item B is also likely to be ordered by the same customer (e.g. Book 1 is frequently ordered with Book 2). All items that are linked together by an item association can be considered to be in the same group. An item without any association can be considered to be in the same group. An item without any association to any other item can be considered to be in its own item association group of size 1. Given a list of item association relationships (i.e. group of items likely to be ordered together). Write an algorithm that outputs the largest item association group. If two groups have the same number of items then select the group which contains the item that appears first in lexicographic order. INPUT The input to the function/method consists of an argument - itemAssociation, a list containing pairs of string representing the items that are ordered together. OUTPUT Return a list of strings representing the largest item association group, sorted lexicographically. EXAMPLE Input itemAssociation [[Item1, Item2], [Item3, Item4], [Item4, Item5]] Output [Item3. Item4. Item5] EXPLANATION There are two item association groups: group1: [Item1, Item2] group2: [Item3, Item4, Item5] In the available item associations, group2 has the largest association So, the output is [Item3, Item4, Item5] """ class Solution: def largestItemAssociation(self, itemAssociation): if len(itemAssociation) < 2: return itemAssociation all_sets = set() max_count = 0 for i in range(len(itemAssociation)): for j in range(i+1, len(itemAssociation)): first_set = frozenset(itemAssociation[i]) second_set = frozenset(itemAssociation[j]) if first_set & second_set == frozenset(): all_sets.add(first_set) all_sets.add(second_set) else: all_sets.add(first_set.union(second_set)) largest = [] associations = sorted([sorted(list(s)) for s in all_sets]) for assoc in associations: if len(assoc) > len(largest): largest = assoc return largest if __name__ == "__main__": arr = [["Item3", "Item4"]] solution = Solution() print(solution.largestItemAssociation(arr))
def isUnique(s): table = {} for ch in s: if ch in table: return False table[ch] = 1 return True def isUnique_2(s): s = sorted(list(s)) for i in range(1, len(s)): if s[i - 1] == s[i]: return False return True def isUnique_3(s): num = 0 for i in range(len(s)): pos = (1 << (ord(s[i]) - ord('a'))) if pos & num: return False num |= pos return True if __name__ == "__main__": print(isUnique_3("abcde")) print(isUnique_3("abacd"))
def bmi1(): high = float(input('請輸入身高(公分): ')) weight = float(input('請輸入體重: ')) high = high / 100 bmi = weight / (high * high) bmi = str(round(bmi, 2)) return bmi def judge1(bmi): if bmi < 18.5: judge = '過輕' elif bmi >= 18.5 and bmi < 24: judge = '正常' elif bmi >= 24 and bmi < 27: judge = '過重' elif bmi >= 27 and bmi <30: judge = '輕度肥胖' elif bmi >= 30 and bmi <35: judge = '中度肥胖' elif bmi >= 35: judge = '重度肥胖' return judge def main(): bmi = bmi1() judge = judge1(float(bmi)) print('您的bmi指數為' + bmi + ', ' + judge) main()
# https://www.acmicpc.net/problem/1157 if __name__ == '__main__': str = input() str = str.upper() char_dict = dict() for i in str: if i in char_dict.keys(): char_dict[i] += 1 else: char_dict[i] = 1 max_value = max([(char_dict[key], key) for key in char_dict]) print(max_value) if list(char_dict.values()).count(max_value[0]) is 1: print(max_value[1]) else: print('?')
# coding: utf-8 # ## Analyze A/B Test Results # # This project will assure you have mastered the subjects covered in the statistics lessons. The hope is to have this project be as comprehensive of these topics as possible. Good luck! # # ## Table of Contents # - [Introduction](#intro) # - [Part I - Probability](#probability) # - [Part II - A/B Test](#ab_test) # - [Part III - Regression](#regression) # # # <a id='intro'></a> # ### Introduction # # A/B tests are very commonly performed by data analysts and data scientists. It is important that you get some practice working with the difficulties of these # # <a id='probability'></a> # #### Part I - Probability # # In[1]: import pandas as pd import numpy as np import random import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') #We are setting the seed to assure you get the same answers on quizzes as we set up random.seed(42) # `1.` Now, read in the `ab_data.csv` data. Store it in `df`. # a. Read in the dataset and take a look at the top few rows here: # In[2]: df = pd.read_csv('ab_data.csv') df.head(10) # b. Use the below cell to find the number of rows in the dataset. # In[3]: df.shape # c. The number of unique users in the dataset. # In[4]: df['user_id'].nunique() # d. The proportion of users converted. # In[5]: df[df['converted'] == 1].user_id.count()/df['user_id'].count() # e. The number of times the `new_page` and `treatment` don't line up. # In[6]: df_t = df.query('group == "treatment"') df_c = df.query('group == "control"') n_mis = df_t.query('landing_page == "old_page"').user_id.count() + df_c.query('landing_page == "new_page"').user_id.count() n_mis # f. Do any of the rows have missing values? # In[7]: df.info() # `2.` For the rows where **treatment** is not aligned with **new_page** or **control** is not aligned with **old_page**, #we cannot be sure if this row truly received the new or old page. # # a. Now use the answer to the quiz to create a new dataset. # In[8]: df_t_o = df_t.query('landing_page == "old_page"') df_c_n = df_c.query('landing_page == "new_page"') mis = pd.concat([df_t_o,df_c_n]) df2 = df mis_index = mis.index df2 = df2.drop(mis_index) # In[9]: # Double Check all of the correct rows were removed - this should be 0 df2[((df2['group'] == 'treatment') == (df2['landing_page'] == 'new_page')) == False].shape[0] # `3.` Use **df2** and the cells # a. How many unique **user_id**s are in **df2**? # In[10]: df2['user_id'].nunique() # b. There is one **user_id** repeated in **df2**. What is it? # In[11]: df2[df2.duplicated('user_id')] # c. What is the row information for the repeat **user_id**? # In[12]: df2.query('user_id == 773192') # d. Remove **one** of the rows with a duplicate **user_id**, but keep dataframe as **df2**. # In[13]: df2.drop(labels=1899,axis=0,inplace=True) # In[14]: df2.query('user_id == 773192') # a. What is the probability of an individual converting regardless of the page they receive? # In[15]: df2.query('converted == 1').user_id.count()/df2.user_id.count() # b. Given that an individual was in the `control` group, what is the probability they converted? # In[16]: df2_c = df2.query('group == "control"') df2_c.query('converted == 1').user_id.count()/df2_c.user_id.count() # c. Given that an individual was in the `treatment` group, what is the probability they converted? # In[17]: df2_t = df2.query('group == "treatment"') df2_t.query('converted == 1').user_id.count()/df2_t.user_id.count() # d. What is the probability that an individual received the new page? # In[18]: df2.query('landing_page == "new_page"').user_id.count()/df2.user_id.count() # **The rate of the control group (old page) is higher than the teatment group (new page). But, the difference is just roughly 0.2%. # From the data , the probability that an individual recieved a new page is roughly 50%, this means that it is not possible to be a big difference in conversion with being given more opportunities. ** # <a id='ab_test'></a> # ### Part II - A/B Test # # Notice that because of the time stamp associated with each event, you could technically run a hypothesis test continuously as each observation was observed. # # However, then the hard question is do you stop as soon as one page is considered significantly better than another or does it need to happen consistently for a certain amount of time? How long do you run to render a decision that neither page is better than another? # # # # `1.` For now, consider you need to make the decision just based on all the data provided. If you want to assume that the old page is better unless the new page proves to be definitely better at a Type I error rate of 5%, what should your null and alternative hypotheses be? You can state your hypothesis in terms of words or in terms of **$p_{old}$** and **$p_{new}$**, which are the converted rates for the old and new pages. # Null-Hypothesis: # # **$H_{0}$**: **$p_{old}$** >= **$p_{new}$** # # Alternative-hypothesis: # # **$H_{1}$**: **$p_{old}$** < **$p_{new}$** # `2.` Assume under the null hypothesis, $p_{new}$ and $p_{old}$ both have "true" success rates equal to the **converted** success rate regardless of page - that is $p_{new}$ and $p_{old}$ are equal. Furthermore, assume they are equal to the **converted** rate in **ab_data.csv** regardless of the page. <br><br> # # Use a sample size for each page equal to the ones in **ab_data.csv**. <br><br> # # Perform the sampling distribution for the difference in **converted** between the two pages over 10,000 iterations of calculating an estimate from the null. <br><br> # # Use the cells below to provide the necessary parts of this simulation. If this doesn't make complete sense right now, don't worry - you are going to work through the problems below to complete this problem. You can use **Quiz 5** in the classroom to make sure you are on the right track.<br><br> # a. What is the **convert rate** for $p_{new}$ under the null? # In[19]: p_new = df2.query('landing_page == "new_page"').converted.mean() p_old = df2.query('landing_page == "old_page"').converted.mean() p_mean = np.mean([p_new, p_old]) p_mean # In[20]: p_n0 = p_mean p_o0 = p_mean # **$H_{0}$**:p_n0 = 0.1196 # In[21]: df2.head() # b. What is the **convert rate** for $p_{old}$ under the null? <br><br> # **$H_{0}$**:p_o0 = 0.1196 # c. What is $n_{new}$? # In[22]: n_new = df2.query('landing_page == "new_page"').user_id.count() n_new # d. What is $n_{old}$? # In[23]: n_old = df2.query('landing_page == "old_page"').user_id.count() n_old # e. Simulate $n_{new}$ transactions with a convert rate of $p_{new}$ under the null. Store these $n_{new}$ 1's and 0's in **new_page_converted**. # In[24]: new_page_converted = np.random.choice([1,0],size=n_new,p=[p_mean,(1-p_mean)]) new_page_converted.mean() # f. Simulate $n_{old}$ transactions with a convert rate of $p_{old}$ under the null. Store these $n_{old}$ 1's and 0's in **old_page_converted**. # In[25]: old_page_converted = np.random.choice([1,0],size=n_old,p=[p_mean,(1-p_mean)]) old_page_converted.mean() # g. Find $p_{new}$ - $p_{old}$ for your simulated values from part (e) and (f). # In[26]: p_diff = new_page_converted.mean() - old_page_converted.mean() p_diff # h. Simulate 10,000 $p_{new}$ - $p_{old}$ values using this same process similarly to the one you calculated in parts **a. through g.** above. Store all 10,000 values in **p_diffs**. # In[27]: p_diffs = [] for _ in range(10000): b_sample = df2.sample(df2.shape[0],replace=True) new_page_converted = np.random.choice([1,0],size=n_new,p=[p_mean,(1-p_mean)]) old_page_converted = np.random.choice([1,0],size=n_old,p=[p_mean,(1-p_mean)]) p_diff = new_page_converted.mean() - old_page_converted.mean() p_diffs.append(p_diff) # i. Plot a histogram of the **p_diffs**. Does this plot look like what you expected? Use the matching problem in the classroom to assure you fully understand what was computed here. # In[28]: p_diff = p_new-p_old # In[29]: p_diffs = np.array(p_diffs) plt.hist(p_diffs); plt.axvline(x=p_new-p_old,c='r',label="real diff") plt.axvline(x=(p_diffs.mean()),c='y',label="simulated diff") # j. What proportion of the **p_diffs** are greater than the actual difference observed in **ab_data.csv**? # In[30]: (p_diffs > p_diff).mean() # k. In words, explain what you just computed in part **j.**. What is this value called in scientific studies? What does this value mean in terms of whether or not there is a difference between the new and old pages? # **It is p-value.If the sample confored to null-hypothesis,the expected proportion is greater than the real-diff to be 0.5.But the 0.9 of the population in simulated sample is greater than the real_diff.We can find that there is no evidence to reject the null hypothesis** # l. We could also use a built-in to achieve similar results. Though using the built-in might be easier to code, the above portions are a walkthrough of the ideas that are critical to correctly thinking about statistical significance. Fill in the below to calculate the number of conversions for each page, as well as the number of individuals who received each page. Let `n_old` and `n_new` refer the the number of rows associated with the old page and new pages, respectively. # In[31]: old = df2.query('landing_page == "old_page"') new = df2.query('landing_page == "new_page"') # In[32]: import statsmodels.api as sm convert_old = old.query('converted == 1').user_id.count() convert_new = new.query('converted == 1').user_id.count() n_old = df2.query('landing_page == "old_page"').user_id.count() n_new = df2.query('landing_page == "new_page"').user_id.count() # In[33]: convert_old, convert_new, n_old, n_new # m. Now use `stats.proportions_ztest` to compute your test statistic and p-value. [Here](http://knowledgetack.com/python/statsmodels/proportions_ztest/) is a helpful link on using the built in. # In[36]: z_score, p_value = sm.stats.proportions_ztest(count=[convert_new,convert_old], nobs=[n_new,n_old],alternative='larger') # In[37]: (z_score, p_value) # n. What do the z-score and p-value you computed in the previous question mean for the conversion rates of the old and new pages? Do they agree with the findings in parts **j.** and **k.**? # **From the histogram we can say that there is about -1.31 standard deviations between the lines,and the p-value is about 0.905.It's close to j.So that we can't reject the null-hypothesis.** # <a id='regression'></a> # ### Part III - A regression approach # # `1.` In this final part, you will see that the result you acheived in the previous A/B test can also be acheived by performing regression.<br><br> # # a. Since each row is either a conversion or no conversion, what type of regression should you be performing in this case? # **Logistic regression.** # b. The goal is to use **statsmodels** to fit the regression model you specified in part **a.** to see if there is a significant difference in conversion based on which page a customer receives. However, you first need to create a colun for the intercept, and create a dummy variable column for which page each user received. Add an **intercept** column, as well as an **ab_page** column, which is 1 when an individual receives the **treatment** and 0 if **control**. # In[38]: df3 = df2 df3.head() # In[39]: df3['intercept']=pd.Series(np.zeros(len(df3)),index=df3.index) df3['ab_page']=pd.Series(np.zeros(len(df3)),index=df3.index) df3.head() # In[40]: #creat new columns row = df3.query('group == "treatment"').index df3.set_value(index=df3.index, col='intercept', value=1) df3.set_value(index=row, col='ab_page', value=1) #change type df3[['intercept','ab_page']] = df3[['intercept','ab_page']].astype(int) # In[41]: df3.query('group == "treatment"').head() # c. Use **statsmodels** to import your regression model. Instantiate the model, and fit the model using the two columns you created in part **b.** to predict whether or not an individual converts. # In[42]: logit = sm.Logit(df3['converted'],df3[['ab_page','intercept']]) result = logit.fit() # d. Provide the summary of your model below, and use it as necessary to answer the following questions. # In[43]: result.summary() # e. What is the p-value associated with **ab_page**? Why does it differ from the value you found in the **Part II**?<br><br> **Hint**: What are the null and alternative hypotheses associated with your regression model, and how do they compare to the null and alternative hypotheses in the **Part II**? # **The p-value associated with ab_page is 0.190. # This is because Part II incorrectly used a two-tailed test,leading to the same direction of the two inspections.If the "one-tailed test" is correctly used in Part II, it should be different. # We added an intercept which is meant to let the p-value is more accurate.But, this p-value is still much too high to reject the null hypothesis.** # f. Now, you are considering other things that might influence whether or not an individual converts. Discuss why it is a good idea to consider other factors to add into your regression model. Are there any disadvantages to adding additional terms into your regression model? # **I consider whether the users'duration on the page, user gender, age, or the place of residence will affect the convertion rate.The men &women ,or different age,area of user may be a little biased on the version of page.And from analysis of every users' duration on page ,we can also know whether the user willing to upgreat the version. But it's not advisable to add many factors.Because sometimes in regression analysis, the kind of factor and the expression of this factor is only a kind of speculation, the intestability and diversity make regression analysis restricted in some cases.** # g. Now along with testing if the conversion rate changes for different pages, also add an effect based on which country a user lives. You will need to read in the **countries.csv** dataset and merge together your datasets on the approporiate rows. [Here](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html) are the docs for joining tables. # # Does it appear that country had an impact on conversion? Don't forget to create dummy variables for these country columns - **Hint: You will need two columns for the three dummy varaibles.** Provide the statistical output as well as a written response to answer this question. # In[44]: df_countries = pd.read_csv('countries.csv') df_countries.country.unique() # In[45]: df_dummies = pd.get_dummies(df_countries,columns=['country']) df4 = df3.merge(df_dummies,on='user_id') df4.head() # h. Though you have now looked at the individual factors of country and page on conversion, we would now like to look at an interaction between page and country to see if there significant effects on conversion. Create the necessary additional columns, and fit the new model. # # Provide the summary results, and your conclusions based on the results. # In[46]: logit = sm.Logit(df4['converted'],df4[['intercept','country_CA','country_UK']]) result = logit.fit() result.summary() # **From result we can say that it seems having a certain influence on the conversion rate,but it is not high enough.The next we add page&country to see weather it influence on conversion rate.** # In[47]: df4['page_CA'] = df4['ab_page'] * df4['country_CA'] df4['page_UK'] = df4['ab_page'] * df4['country_UK'] # In[50]: logit1 = sm.Logit(df4['converted'],df4[['intercept', 'country_CA','country_UK', 'ab_page', 'page_CA','page_UK']]) result1 = logit1.fit() result1.summary() # **It seems that the p-values for all columns have been increased when we added each factor.The z-score of the intercept is also very large.** # Comment: # # 1.At first it looks like there is a difference in conversion rates between old and new page, but there is not enough evidence to reject the null hypothesis. From the analysis shown in this report, the new page is not better than the old version. # # 2.We also found that users have approximately 50% chance of receiving old or new page. But it doesn't depend on countries with approximately the same conversion rates as US or UK. # # 3.Although we used page&country, it seems having a certain influence on the conversion rate, but it is not high enough.The z-score of the intercept is also very large. So I am thinking about the other reasons,for example the quality ,design of the webside. # <a id='conclusions'></a> # ## Conclusions # # Congratulations on completing the project! # # ### Gather Submission Materials # # Once you are satisfied with the status of your Notebook, you should save it in a format that will make it easy for others to read. You can use the __File -> Download as -> HTML (.html)__ menu to save your notebook as an .html file. If you are working locally and get an error about "No module name", then open a terminal and try installing the missing module using `pip install <module_name>` (don't include the "<" or ">" or any words following a period in the module name). # # You will submit both your original Notebook and an HTML or PDF copy of the Notebook for review. There is no need for you to include any data files with your submission. If you made reference to other websites, books, and other resources to help you in solving tasks in the project, make sure that you document them. It is recommended that you either add a "Resources" section in a Markdown cell at the end of the Notebook report, or you can include a `readme.txt` file documenting your sources. # # ### Submit the Project # # When you're ready, click on the "Submit Project" button to go to the project submission page. You can submit your files as a .zip archive or you can link to a GitHub repository containing your project files. If you go with GitHub, note that your submission will be a snapshot of the linked repository at time of submission. It is recommended that you keep each project in a separate repository to avoid any potential confusion: if a reviewer gets multiple folders representing multiple projects, there might be confusion regarding what project is to be evaluated. # # It can take us up to a week to grade the project, but in most cases it is much faster. You will get an email once your submission has been reviewed. If you are having any problems submitting your project or wish to check on the status of your submission, please email us at dataanalyst-project@udacity.com. In the meantime, you should feel free to continue on with your learning journey by continuing on to the next module in the program.
import numpy as np import matplotlib.pyplot as plt # Lección 05 # # Proyecto básico de machine learning # Manejo de datos # Graficación de datos data = np.loadtxt("DataS.txt") print("primeros 10 datos: ", data[:10], "\n") # Numero de datos print("Numero de datos: ",data.shape) x = data[0] y = data[1] print("x: ", x) print("y: ", y) # Verificación de los datos generados # Dimensión de los vectores x, y # -------------------------------------------------------------- print("dimension de x: ",x.ndim) print("dimension de y: ",y.ndim) # Investigamos el número de valores, tipo nan, que contiene el vector # -------------------------------------------------------------- print(np.sum(np.isnan(y))) #BÚSQUEDA PREDICTIVA EN EL ENTORNO numpy DE python # DESDE AQUI SE COMIENZA A GRAFICAR # EL CÓDIGO, A PARTIR DE ESTE PUNTO, ES EL QUE SE ESTUDIO PREVIAMENTE # Se dibuja, de manera abstracta, el punto (x,y) # con círculos de tamaño 10 # -------------------------------------------------------------- plt.scatter(x, y, s=10) # Títulos del gráfico # -------------------------------------------------------------- plt.title("Numero de casos Covid-19") plt.xlabel("Semanas") plt.ylabel("# de casos") # Se dibujan las marcas del gráfico # -------------------------------------------------------------- plt.xticks([w*23.85 for w in range(10)],['S %i' % w for w in range(10)]) plt.autoscale(tight = False) # dibuja una cuadrícula punteada ligeramente opaca # -------------------------------------------------------------- plt.grid(True, linestyle='-', color='0.75') # EL CÓDIGO REUTILIZADO TERMINA AQUÍ. A PARTIR DE ESTE PUNTO SE GENERAN # NUEVAS INSTRUCCIONES PARA EL AJUSTE DE LA CURVA # Función que calcula el error (vector) def error(f , x, y): return np.sum((f(x)-y)**2) # A CONTINUACIÓN SE UTILIZA LA FUNCIÓN DE AJUSTE POLINOMIAL # fp1 (parámetros de la función respuesta) # residuals, que es el error del ajuste realizado # Ambos valores serán estudiados más abajo en el documento # -------------------------------------------------------------- fp1, residuals, rank, sv, rcond = np.polyfit(x, y, 1, full=True) print("Parámetros del modelo: %s" % fp1, '\n') print("Error devuelto por el ajuste:", residuals, '\n') # Mediante la función poly1d, se crea la recta a partir de # los parámetros generados por el ajuste (disponibles en fp1) # -------------------------------------------------------------- f1 = np.poly1d(fp1) # Error después de generar la recta (igual al recibido) # -------------------------------------------------------------- print("Error después de generar la recta:", error(f1, x, y), '\n') # Se dibuja la recta que se ajusta a los puntos # -------------------------------------------------------------- # linespace # -------------------------------------------------------------- # Se utiliza la función: linspace. # El primer parámetro es el primer valor a utilizar en x, # que para nuestro caso es el valor cero. # El siguiente parámetro es es el último valor en x, que para nuestro # caso se encuentra en la posición final de x. # Puesto que se x inicia en la posición 0, el último valor se obtiene # en la posición (x - 1), lo cual explica la instrucción x[-1] # El tercer parámetro, 1000, indica el número de divisiones a # realizar en cuanto a los puntos tomados. Para nuestro ejemplo, # basta con que dicho valor no sea negativo. Otros valores diferentes a 1000 # funcionan igualmente bien. # -------------------------------------------------------------- fx = np.linspace(0,x[-1], 1000) # Se generan los puntos verticales. A partir de fx, se calculan # los valores en y: f1(fx). Los otros parámetros se autoexplican # -------------------------------------------------------------- plt.plot(fx, f1(fx), linewidth=4, color="red") # Se muestra en la esquina superior izquierda (upper left) # el grado del polinomio del ajuste (1 = línea recta) # -------------------------------------------------------------- """plt.legend(["Grado d=%i" % f1.order], loc="upper left")""" # POLINOMIO DE GRADO 2 # NOTA: En la función polyfit, el valor 2, como parámetro, # hace referencia a un polinomio de segundo grado # ---------------------------------------------------------------- f2p = np.polyfit(x, y, 2) print("Parámetros del modelo: %s" % f2p) print("Ecuación: f(x) = 0.0105322215 * x**2 - 5.26545650 * x + 1974.76082\n") # Se genera la gráfica # ---------------------------------------------------------------- f2 = np.poly1d(f2p) # Error después de generar la gráfica # ---------------------------------------------------------------- print("Error después de generar la curva:",error(f2, x, y)) # Se realiza la gráfica de salida (sobre las anteriores) # ---------------------------------------------------------------- #plt.plot(fx, f2(fx), linewidth=4, color="yellow") # Se agrega un texto explicativo sobre el grado utilizado # Se escriben ambos valores para grado 1 y grado 2 en la # misma instrucción # ---------------------------------------------------------------- """plt.legend(["Grado d=%i\n" % f1.order, "Grado d=%i" % f2.order], loc="upper left")""" # ESPACIO PARA MOSTRAR (insert plt.show()) # GRADO 3 Y 10 f3p = np.polyfit(x, y, 3) f3 = np.poly1d(f3p) #plt.plot(fx, f3(fx), linewidth=4, color="green") f10p = np.polyfit(x, y, 10) f10 = np.poly1d(f10p) #plt.plot(fx, f10(fx), linewidth=2, color="black") """plt.legend(["Grado d=%i" % f1.order, "Grado d=%i" % f2.order, "Grado d=%i" % f3.order, "Grado d=%i" % f10.order], loc="upper left")""" # GRADO 1 Y 53 f53p = np.polyfit(x, y, 53) f53 = np.poly1d(f53p) plt.plot(fx, f53(fx), linewidth=4, color="#ffff00") plt.legend(["Grado d=%i" % f1.order, "Grado d=%i" % f53.order], loc="upper left") plt.show()
# writing a simple face detection proram # import modules import cv2 import numpy as np # Now we load in the facial classifiers face_detect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml'); # now we create a video capture object to capture videos from webcam cap = cv2.VideoCapture(0); # we create a loop to capture video frame by frame while True: ret,image = cap.read(); # now we need to convert the image to gray for the classifier to work gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY); # now we create list to store the faces we detected in image frame by frame faces = face_detect.detectMultiScale(gray, 1.3, 5) # now we detect multiple faces and draw rectangle on them for (x,y,w,h) in faces: # now we draw rectangle on the original image not the gray cv2.rectangle(image, (x,y), (x+w, y+h), (0, 255, 0), 2) # now we show in a window cv2.imshow('Frame', image) # Now to close the program we need to specify a waitkey and compare to a key to close the frame k= cv2.waitKey(30) & 0xFF == ord('q') if k == 27: break # Now we release the camera and destroy all of it
"""写程序把一个单向链表顺序倒过来(尽可能写出更多的实现方法,标出所写方法 的空间和时间复杂度)""" class Node(object): def __init__(self,item): self.item = item self.next = None #第一种方法: def loopList(node): while node.next != None: node.next.next = node node=node.next #利用三个指针逐个反转 def f1(head): p = head q = head.next
"""求和问题,给定一个数组,数组中的元素唯一,数组元素数量 N >2,若数组中的 两个数相加和为 m,则认为该数对满足要求,请思考如何返回所有满足要求的数对(要 求去重),并给出该算法的计算复杂度和空间复杂度(2018-4-23-lyf)""" #时间复杂度是O(n**2) #空间复杂度是O(n) def two_num_sum_list(list,sum): hash = set() for i in range(len(list)): for j in range(i+1,len(list)): if (list[i] + list[j] )== sum: hash.add((list[i],list[j])) return hash #滑动相加: def twoNum(nums,taget): i,j = 0,len(nums)-1 nums.sort() _list = [] while i < j: twosum = sum([nums[i],nums[j]]) if twosum == taget: _list.append([nums[i],nums[j]]) i+=1 j-=1 while nums[i] == nums[i-1]: i+=1 while nums[j] == nums[j+1]: j-=1 elif twosum > taget: j-=1 else: i+=1 return _list if __name__=="__main__": list=[1,2,3,4,5,6,7,8] num = 9 print(two_num_sum_list(list,num)) print(twoNum(list,num))
import random new=open('s.txt','w') new.write('computer mouse keyword') new.close() punct = (".", ";", "!", "?", ",") count = 0 new_word = "" inputfile = 's.txt' with open(inputfile, 'r') as fin: for line in fin.readlines(): for word in line.split(): if len(word) > 3: if word.endswith(punct): word1 = word[1:-2] word1 = random.sample(word1, len(word1)) word1.insert(0, word[0]) word1.append(word[-2]) word1.append(word[-1]) else: word1 = word[1:-1] word1 = random.sample(word1, len(word1)) word1.insert(0, word[0]) word1.append(word[-1]) new_word = new_word + ''.join(word1) + " " else: new_word = new_word + word + " " with open((inputfile[:-4] + "_scrambled.txt"), 'a+') as fout: fout.write(new_word + "\n") new_word = "" inputfile2 = input("Enter the file name:") with open(inputfile2, 'r') as f: print(f.read())
import collections def calculations(x): def max_of_elements(x): print("Maximum element in the list :", max(x)) def min_of_elements(x): print("Minimum element in the list :", min(x)) def mean_of_list(x): sum=0 for i in range(0,len(x)): sum= sum + x[i] mean = sum//len(x) print("Mean :",mean) def median_of_list(x): x.sort() if(len(x)%2!=0): median = (len(x)+1)//2 print("Median :",median) elif(len(x)%2==0): median = ((len(x)//2)+(len(x)//2)+1)//2 print("Median :",median) def mode_of_list(x): data = collections.Counter(x) data_list = dict(data) max_value = max(list(data.values())) mode_val = [num for num, freq in data_list.items() if freq == max_value] if len(mode_val) == len(x): print("No mode is Avaialble") else: print("Mode :" + ', '.join(map(str, mode_val))) max_of_elements(x) min_of_elements(x) mean_of_list(x) median_of_list(x) mode_of_list(x) x = [4,6,2,2,9,7,1,2] print("The list is : ",x) calculations(x)
import threading import time import random exitFlag = 0 class myThread(threading.Thread): def __init__(self, threadID, name, counter, results): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter self.results = results def run(self): print("Starting " + self.name + "\n") print_time(self.name, 3, self.counter, self.results) print("Exiting " + self.name + "\n") def print_time(threadName, counter, delay, results): i = 0 while counter: if exitFlag: threadName.exit() time.sleep(delay) result = random.randint(1, 10) while result in results: result = random.randint(1, 10) results[i] = result i += 1 print("%s: %s \n" % (threadName, str(result))) counter -= 1 # Create new threads results = [None] * 9 thread1 = myThread(1, "Thread-1", 1, results) thread2 = myThread(2, "Thread-2", 2, results) thread3 = myThread(3, "Thread-3", 3, results) # Start new Threads thread1.start() thread2.start() thread3.start()
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:loftybay count = 0 ages_ing = 15 while count < 3: ages = int (input("亲输入一个我心里想的数字:")) if ages == ages_ing: print("恭喜您,猜对了") break elif ages > ages_ing: print("猜大了") else: print("猜小了") count = count +1 if count == 3: counting = input("你还要继续玩吗?") if counting != 'n': count = 0
#!/usr/bin/env python import csv from _ast import Num from math import sqrt ifile = open('sample.csv', "rb") reader = csv.reader(ifile) results = [] rownum = 0 for row in reader: # Save header row. if rownum == 0: header = row else: colnum = 0 for col in row: print '%-8s: %s' % (header[colnum], col) colnum += 1 if (colnum==1) and (len(row)>1): results.append(float(row[1])) if len(row)>1: print "row1 is: ", row[1] rownum += 1 ifile.close() print "Try to math: ", results[3]+results[7] print "Try to math: ", float(float(results[3])+float(results[7])) my_sum=0; for this_num in results: my_sum=my_sum+float(this_num) print "my_sum is: ", my_sum print results total_len=0; for i in range(0,len(results)-1): #total_len = total_len + float(results[i+1])-float(results[i]); #total_len = total_len + sqrt(pow(results[i+1]-results[i],2) + pow(p[i+1]-p[i],2)) total_len = total_len + sqrt(pow(float(results[i+1])-float(results[i]),2)) print "total_len is: ", total_len # sum = np.zeros(len(data[0])) # # for vector in data[1:]: # vector = map(float, vector) # sum = np.add(vector, sum) # results = [] # with open("sample.csv") as csvfile: # reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) # change contents to floats # for row in reader: # each row is a list # results.append(row) # # print results
# SIMPLE EXAMPLE OF PROPERTY DECORATOR - GETTER, SETTER AND DELETER class Employee: def __init__(self, first, last): self.first = first self.last = last @property def email(self): return "{}.{}@mail.com".format(self.first, self.last).lower() @property def fullname(self): return "{} {}".format(self.first, self.last) # SETTER @fullname.setter def fullname(self, name): first, last = name.split(" ") self.first = first self.last = last # SETTER @fullname.setter def fullname(self, name): first, last = name.split(" ") self.first = first self.last = last @fullname.deleter def fullname(self): print("Deleted Name") self.first = None self.last = None emp1 = Employee("Eric", "Smith") emp1.first = 'Jim' emp1.fullname = "Rief Rief" print(emp1.first) print(emp1.fullname) print(emp1.email)
# Longest Increasing subsequence # Problem Definition: # Given a sequence , find the largest subset such that for every # i < j, ai < aj. # import sys # # This problem requires us to use dynamic programming technique. # # We should identify a sub structure similar to a DAG (directed acyclic graph) # that we formulate into a recursive function. # # Let S[0 to n] be the full sequence. If LIS(i) is the size of the longest # sequence that S[i] is the last element of, we have: # # LIS(i) = 1 if i = 0 or S[j] > S[i] for all j < i # LIS(i) = 1 + max(List(j)) for all j < i and S[j] < S[i] # # This is O(n^2) algorithm def longestIncreasingSubsequence(seq): if not seq: return (0, []) LIS = [1] # first element of the sequence prev = [-1] # this is the end of any sequence construction involving this element maxLIS = 1 maxIndex = 0 for index in xrange(1, len(seq)): # Find the max and prev position maxVal = 0 prevIndex = -1 for j in xrange(index-1, -1, -1): if seq[j] < seq[index] and LIS[j] > maxVal: maxVal = LIS[j] prevIndex = j LIS.append(1+maxVal) prev.append(prevIndex) if (1+maxVal) > maxLIS: maxLIS = 1 + maxVal maxIndex = index if __debug__: print str(LIS) + " " + str(maxLIS) if __debug__: print str(prev) + " " + str(maxIndex) liSeq = [] # The sequence itself while prev[maxIndex] != -1: liSeq.append(seq[maxIndex]) maxIndex = prev[maxIndex] liSeq.append(seq[maxIndex]) liSeq.reverse() return (maxLIS, liSeq) def unitTest(seq, sol): print "Testing: " + str(seq) + " - Expecting: " + str(sol) actualSol = longestIncreasingSubsequence(seq) if actualSol == sol: print "OK" else: print "FAILED - Got: " + str(actualSol) def main(): unitTest([1,2,3,4,5,6,2,3,4,5,6,7,8,2,3,4,5,6,3,5,6,10], (9, [1,2,3,4,5,6,7,8,10])) unitTest([1,2,1,3], (3, [1,2,3])) unitTest([9,8,7,6,5,4,3,2,1,0], (1,[9])) unitTest([], (0,[])) if __name__ == "__main__": main() # This is a useless function i wrote; this was a mistake def longestIncreasingConsecutiveSubsequence(seq): assert seq seqLen = len(seq) # first element is the longest in the beginning (longestIndex, longestLength) = (0, 1) # position of the current elements' increasing sequence memoiz = (longestIndex, longestLength) for index in xrange(1, seqLen): # if current element keeps the current sequence increasing if seq[index] > seq[index-1]: memoiz = (memoiz[0], memoiz[1] + 1) if memoiz[1] > longestLength: (longestIndex, longestLength) = memoiz else: memoiz = (index, 1) return seq[longestIndex:(longestIndex+longestLength)]
__author__ = 'Ed Cannon' #groupby multiple columns: grouped = df.groupby(['A', 'B']) import pandas as pd from filter_df import load_csv import sys def groupby_single_column(df,col,oper): ''' aggregation functions available: mean, sum, size, count, std, var, sem, describe, first, last, nth, min, max :param df: input data frame :param col: column to group by :param oper: operation to apply to groupby :return: groupy data frame ''' if oper == 'sum': return df.groupby(col).sum() elif oper == 'mean': return df.groupby(col).mean() elif oper == 'std': return df.groupby(col).std() elif oper == 'count': return df.groupby(col).count() elif oper == 'describe': return df.groupby(col).describe() else: return df if __name__ == '__main__': df = load_csv(sys.argv[1]) print groupby_single_column(df,'class','mean')
''' Author: Rahul Title: Find Who tweeted most ''' from collections import OrderedDict #number of test cases t = int(input()) #input tweets as list tweets = [] for i in range(0,t): z = int(input()) for j in range(0, z): y = input() tweets.append(y) # dictionary for counting the no, of tweets count_tweets = {} #adding name and no. of tweets in to dictionary for tweet in tweets: var = tweet.split(" ") if var[0] in count_tweets.keys(): count_tweets[var[0]] = count_tweets[var[0]] + 1 else: count_tweets[var[0]] = 1 #sorting according to name sorted_tweets_count = OrderedDict(sorted(count_tweets.items())) for key, value in sorted_tweets_count.items(): if sorted_tweets_count[key] > 1: print("{} {}".format(key, value))
def ft_map(function_to_apply, list_of_inputs): return (function_to_apply(element) for element in list_of_inputs) if __name__ == '__main__': def square(x): return x * x results = list(map(square, [1, 2, 3, 4, 5])) ft_results = list(ft_map(square, [1, 2, 3, 4, 5])) print(results) print(ft_results) print(results == ft_results)
import numpy def dot(x, y): """Computes the dot product of two non-empty numpy.ndarray, using a for-loop. The two arrays must have the same dimensions. Args: x: has to be an numpy.ndarray, a vector. y: has to be an numpy.ndarray, a vector. Returns: The dot product of the two vectors as a float. None if x or y are empty numpy.ndarray. None if x and y does not share the same dimensions. Raises: This function should not raise any Exception. """ if not type(x) == numpy.ndarray or x.size < 1: return None; if not type(y) == numpy.ndarray or y.size < 1: return None; if x.size != y.size: return None; res = 0 for i, _ in numpy.ndenumerate(x): res += x[i] * y[i] return res; def mat_vec_prod(x, y): """Computes the product of two non-empty numpy.ndarray, using a for-loop. The two arrays must have compatible dimensions. Args: x: has to be an numpy.ndarray, a matrix of dimension m * n. y: has to be an numpy.ndarray, a vector of dimension n * 1. Returns: The product of the matrix and the vector as a vector of dimension m * 1. None if x or y are empty numpy.ndarray. None if x and y does not share compatibles dimensions. Raises: This function should not raise any Exception. """ if not type(x) == numpy.ndarray or x.size < 1 or len(x.shape) <= 1: return None; if not type(y) == numpy.ndarray or y.size < 1 or len(y.shape) <= 1: return None; res = numpy.array([]) for nb in x: res = numpy.append(res, dot(nb, y)) return res; if __name__ == "__main__": W = numpy.array([ [ -8, 8, -6, 14, 14, -9, -4], [ 2, -11, -2, -11, 14, -2, 14], [-13, -2, -5, 3, -8, -4, 13], [ 2, 13, -14, -15, -14, -15, 13], [ 2, -1, 12, 3, -7, -3, -6]]) X = numpy.array([0, 15, -9, 7, 12, 3, -21]).reshape((7,1)) Y = numpy.array([2, 14, -13, 5, 12, 4, -19]).reshape((7,1)) print(mat_vec_prod(W, X)) print(W.dot(X)) print(mat_vec_prod(W, Y)) print(W.dot(Y))
import numpy def mat_mat_prod(x, y): """Computes the product of two non-empty numpy.ndarray, using a for-loop. The two arrays must have compatible dimensions. Args: x: has to be an numpy.ndarray, a matrix of dimension m * n. y: has to be an numpy.ndarray, a vector of dimension n * p. Returns: The product of the matrices as a matrix of dimension m * p. None if x or y are empty numpy.ndarray. None if x and y does not share compatibles dimensions. Raises: This function should not raise any Exception. """ res = [[0 for x in range(len(x))] for y in range(len(y[0]))] for i in range(len(x)): for j in range(len(y[0])): for b in range(len(y)): res[i][j] += x[i][b] * y[b][j] return numpy.array(res) if __name__ == "__main__": W = numpy.array([ [ -8, 8, -6, 14, 14, -9, -4], [ 2, -11, -2, -11, 14, -2, 14], [-13, -2, -5, 3, -8, -4, 13], [ 2, 13, -14, -15, -14, -15, 13], [ 2, -1, 12, 3, -7, -3, -6]]) Z = numpy.array([ [ -6, -1, -8, 7, -8], [ 7, 4, 0, -10, -10], [ 7, -13, 2, 2, -11], [ 3, 14, 7, 7, -4], [ -1, -3, -8, -4, -14], [ 9, -14, 9, 12, -7], [ -9, -4, -10, -3, 6]]) print(mat_mat_prod(W, Z)) print(W.dot(Z)) print(mat_mat_prod(Z,W)) print(Z.dot(W))
import codecs import random lista = [] resolver = "" intentos = 0 with open("palabras.txt", "r", encoding="utf8") as palabras: palabras_contenido = palabras.readline() while len(palabras_contenido) > 0: palabras_contenido = palabras_contenido.replace("\n", "").split(" ") for i in palabras_contenido: if i not in lista and len(i) > 3: lista.append(i) palabras_contenido = palabras.readline() def inicio(): global resolver global intentos palabra = random.choice(lista) print("bienvenido al juego del ahorcado para ganar tienes que adivinar la palabra antes de que se te acaben los intentos") intentos = len(palabra) / 3 intentos = int(intentos) + 2 resolver = ("_"*int(len(palabra))) print(resolver) print(intentos) adios_tildes(palabra) def juego(palabra): global resolver global intentos print(palabra) letras = set(palabra) usado = [] while len(letras) > 0 and intentos > 0: print("te quedan: " + str(intentos) + " intentos has probado con: " + " ".join(usado)) resolver = [letras if letras in usado else "_" for letras in palabra] print("hasta el momento has adivinado:" + " ".join(resolver)) opcion = input("elige una letra") if opcion in usado: print("ya habias intentado esa letra") if opcion in letras: usado.append(opcion) letras.remove(opcion) print("oh pues " + opcion + " si esta en la plabra") else: intentos -= 1 print("lo lamento pero " + opcion + " no esta en la palabra") usado.append(opcion) if intentos == 0: print("oh vaya parece que perdiste pero diste lo mejor y es lo que importa") if len(letras) == 0: print("genial ganaste se nota que sabes leer") def adios_tildes(palabra): palabra = palabra.replace("à", "a") palabra = palabra.replace("è", "e") palabra = palabra.replace("ì", "i") palabra = palabra.replace("ò", "o") palabra = palabra.replace("ù", "u") return juego(palabra.lower()) inicio()
# 解决一个锁子产生的死锁问题 threading模块中有RLock,其相比Lock多了一个count变量,该变量用来记录上锁次数 import time from threading import Thread, RLock class Mythread(Thread): def run(self): if lock.acquire(): print("线程%s上锁成功..."%self.name) time.sleep(1) lock.acquire() lock.release() print("线程%s解锁成功..."%self.name) lock.release() if __name__ == "__main__": print("主线程开始") lock = RLock() t1 = Mythread() t2 = Mythread() t1.start() t2.start() print("主线程结束")
from threading import Thread g_num = 0 def task1(): global g_num for i in range(1000000): g_num+=1 print("子线程1g_num的值为:%d"%g_num) def task2(): global g_num for i in range(1000000): g_num+=1 print("子线程2g_num的值为:%d"%g_num) t1 = Thread(target=task1) t1.start() t2 = Thread(target=task2) t2.start() print("主线程g_num的值为:%d"%g_num) #两个线程各对全局变量g_num加了1000000次  答案应该是2000000  但此时结果却不是 #  因为可能会发生的是在两个线程执行g_num+=1这条语句时相当于两步,第一步是其中一个线程A先算等号右边的,当计算完后将结果准备赋值给g_num时,操作系统让另一个线程B执行,此时A值还没赋值完成,线程B执行这句话语句时,取原来值,所以造成不是2000000的结果!!! # 解决办法是进行加锁  互斥锁的概念引进来
import math class Node: def __init__(self, dataVal = None): self.dataVal = dataVal self.nextVal = None class LinkedList: def __init__(self, n): self.headVal = Node(n) self.size = 1 def add(self, n): tmpNew = Node(n) tmp = self.headVal while(tmp.nextVal != None): tmp = tmp.nextVal tmp.nextVal = tmpNew self.size += 1 def remove(self, n): tmp = self.headVal while(n - 1 > 0): tmp = tmp.nextVal n -= 1 tmp.nextVal = tmp.nextVal.nextVal self.size -= 1 def p(self): tmp = self.headVal while(tmp.nextVal != None): print(tmp.dataVal, end=" ") tmp = tmp.nextVal print(tmp.dataVal) def inter(self, ll): ith = self.headVal jth = ll.headVal for i in range(self.size): for j in range(ll.size): if(ith == jth): return True jth = jth.nextVal ith = ith.nextVal return False def main(): dd = LinkedList(8) dd.add(3) dd.add(8) dd.add(4) if __name__ == "__main__": main()
class Stacks: def __init__(self): self.data = [] def push(self, stack, n): self.data.append((stack, n)) def pop(self, stack): for i in range(len(self.data) - 1, -1, -1): if(self.data[i][0] == stack): self.data.pop(i) return def top(self, stack): for i in range(len(self.data) - 1, -1, -1): if(self.data[i][0] == stack): return self.data[i] def p(self, stack): for i in range(len(self.data)): if(self.data[i][0] == stack): print(self.data[i][1], end=" ") print("") def main(): s = Stacks() s.push(1, 4) s.push(1, 5) s.push(1, 6) s.push(2, 33) s.push(2, 44) s.push(2, 55) s.push(2, 66) s.push(1, 7) s.push(1, 8) s.push(3, 1984) s.p(1) s.p(2) s.p(3) print("") print(s.top(1)) s.pop(1) print(s.top(2)) s.pop(2) print(s.top(3)) s.pop(3) print("") s.p(1) s.p(2) s.p(3) if __name__ == "__main__": main()
class Node: def __init__(self, dataVal = None): self.dataVal = dataVal self.nextVal = None class LinkedList: def __init__(self, n): self.headVal = Node(n) self.size = 1 def add(self, n): tmpNew = Node(n) tmp = self.headVal while(tmp.nextVal != None): tmp = tmp.nextVal tmp.nextVal = tmpNew self.size += 1 def remove(self, n): tmp = self.headVal while(n - 1 > 0): tmp = tmp.nextVal n -= 1 self.size -= 1 tmp.nextVal = tmp.nextVal.nextVal def swap(self, n1, n2): tmp = n1.dataVal n1.dataVal = n2.dataVal n2.dataVal = tmp def part(self, p): tmp = self.headVal count = 0 for i in range(self.size): if(tmp.nextVal.dataVal >= p): self.add(tmp.nextVal.dataVal) self.size -= 1 tmp.nextVal = tmp.nextVal.nextVal else: tmp = tmp.nextVal tmp = self.headVal if(tmp.dataVal >= p): self.add(tmp.dataVal) self.size -= 1 self.headVal = tmp.nextVal def p(self): tmp = self.headVal while(tmp.nextVal != None): print(tmp.dataVal, end=" ") tmp = tmp.nextVal print(tmp.dataVal) def main(): ll = LinkedList(33) ll.add(2) ll.add(75) ll.add(5) ll.add(1) ll.add(100) ll.add(0) ll.p() ll.part(5) ll.p() if __name__ == "__main__": main()
import sys def isUnique(str): for i in range (0, len(str)): for j in range (i + 1, len(str)): if(str[i] == str[j]): return False return True def main(): if len(sys.argv) < 2: print("Use: $ python isunique.py word1 word2 word3 etc") else: for arg in sys.argv[1:]: print(isUnique(arg)) if __name__ == "__main__": main()
def check_grid(infile): # to check 1-9 in each columns #cols = [[row[i] for row in infile] for i in range(0,9)] list(infile) lst = infile lst_col = [] no_row = len(lst) no_col = len(lst[0]) for j in range(0,no_col): tmp = [] for i in range(0,no_row): tmp.append(lst[i][j]) lst_col.append(tmp) cols = lst_col print(cols) #cols = infile leg = 0 for i in range(0,9): for j in range(0,9): if cols[i].count(cols[i][j]) <=1: leg = leg + 0 else: leg = leg + 1 #to check 1-9 in each rows count = 0 row = infile for i in range(0,9): for j in range(0,9): if row[i].count(row[i][j]) <= 1: count = count + 0 else: count = count + 1 # to check 1-9 in each 3*3 matrix ''' angle = [] for t in range(0,3): ang = infile[t] for u in range(0,3): angle.append(ang[u]) foot = 0 for be in range(0,9): if angle.count(angle[be]) <= 1: foot = foot + 0 else: foot = foot + 1 ''' if(count + leg) == 0: print("Sudoku is Valid.") else: print("Sudoku is Invalid.") ###################################################### def sudoko_checker(): try: file = input("Enter your File name:") fi = open(file, "r") infile = fi.read() grid = [list(i) for i in infile.split()] print(grid) print("The total number in this puzzle is:",len(grid)) check_grid(grid) except FileNotFoundError: print("The inputted file doesn't exist.") ########################################################### sudoko_checker()
from math import sqrt def is_prime(num): # make sure n is a positive integer num = abs(int(num)) # 0 and 1 are not primes if num < 2: return False # 2 is the only even prime number if num == 2: return True # all other even numbers are not primes if not num & 1: return False # range starts with 3 and only needs to go up # the square root of n for all odd numbers for x in range(3, int(num**0.5) + 1, 2): if num % x == 0: return False return True # Solution 2 - Improved Solution if num <= 1: return False i = 2 while i <= sqrt(num): if num%i == 0: return False i += 1 return True
import random import heapq class Median: def __init__(self, data): self.data = data self.min_heap = [] self.max_heap = [] self.medians = [] def simplest_way(self): analyzed_now_list = list() medians = list() for elem in self.data: analyzed_now_list.append(elem) sorted_data = list(sorted(analyzed_now_list)) length = len(sorted_data) if length % 2 != 0: medians.append(sorted_data[length // 2]) else: medians.append((sorted_data[length // 2] + sorted_data[length // 2 - 1]) / 2) return medians def _add_numbers(self, elem): """В MAX_heap хранятся МИНИМАЛЬНЫЕ элементы и самый большой из них - корень В MIN_heap хранятся МАКСИМАЛЬНЫЕ элементы и самый маленький из них - корень""" if len(self.max_heap) == 0 or elem < self.max_heap[0]: # если элемент меньше минимального из максимальных heapq.heappush(self.max_heap, elem) # вставляем его в кучу к минимальным heapq._heapify_max(self.max_heap) # heappush работает для heapmin, надо отдельно восстановить свойства else: # иначе вставляем к большим элементам heapq.heappush(self.min_heap, elem) heapq.heapify(self.min_heap) def _rebalance(self): """Суть метода ребаланса: определить большую и меньшую кучи, если разница в их размере больше 1, то делаем перекидывание вершины кучи из большей в меньшую, то есть если большая - с меньшими элементами, то к меньшей с большими элементами уйдет максимальный из меньших элементов, соответственно, если большая куча с большими элементами, то в меньшую кучу с меньшими элементами уйдет минимальный из больших, таким образом на пиках куч всегда содержатся срединные элементы некоторого потока, и в случае если длины не равны, то медианой будет вершины большей по размеру кучи, иначе среднее арифметическое пиков двух куч""" flag_max = True max_heap_length = len(self.max_heap) min_heap_length = len(self.min_heap) bigger_heap = self.max_heap if max_heap_length > min_heap_length else self.min_heap flag_max = True if max_heap_length > min_heap_length else False smaller_heap = self.min_heap if max_heap_length > min_heap_length else self.max_heap if len(bigger_heap) - len(smaller_heap) >= 2: if flag_max: # то есть большая куча является max_heap (protected), меньшая min_heap (default) heapq.heappush(smaller_heap, heapq._heappop_max(bigger_heap)) else: heapq.heappush(smaller_heap, heapq.heappop(bigger_heap)) heapq._heapify_max(smaller_heap) # heappush не работает нормально с heap_max, восстанавливаем кучу def _get_median(self): """В случае если длины куч не равны, то медианой будет вершина большей по размеру кучи, иначе среднее арифметическое вершин двух куч, то есть максимального из меньших элементов и минимального из больших""" max_heap_length = len(self.max_heap) min_heap_length = len(self.min_heap) bigger_heap = self.max_heap if max_heap_length > min_heap_length else self.min_heap smaller_heap = self.min_heap if max_heap_length > min_heap_length else self.max_heap if len(bigger_heap) == len(smaller_heap): return (bigger_heap[0] + smaller_heap[0]) / 2 else: return bigger_heap[0] def using_heaps_now(self): """Строятся две кучи: MAX_heap и MIN_heap. В MAX_heap заносятся меньшие элементы, в MIN_heap - большие. При этом если у одной кучи будет перекос по длине, будет произведен сдвиг с одной кучи до другой""" for elem in self.data: self._add_numbers(elem) self._rebalance() self.medians.append(self._get_median()) return self.medians def add_number(self, elem: int): self._add_numbers(elem) self._rebalance() self.medians.append(self._get_median()) return self.medians if __name__ == '__main__': answers = list() for _ in range(50): A = Median([random.randint(0, 1000) for _ in range(random.randint(1000, 2000))]) medians = A.simplest_way() medians_advanced = A.using_heaps_now() answers.append(medians == medians_advanced) print(all(answers))
#!/usr/bin/env python3 basic_salary = 1500 bonus_rate = 200 commission_rate = 0.02 numberofcamera = int(input("Enter the number of inputs sold: ")) price = float(input("Enter the total prices: ")) bonus = (bonus_rate * numberofcamera) commission = (commission_rate * numberofcamera * price) print("Bonus = %6.2f" % bonus) print("Commision = %6.2f" % commission) print("Gross salary = %6.2f" % (basic_salary + bonus + commission))
import numpy as np import matplotlib.pyplot as plt def Parametric_Classification(data, k, x): """ Determine which class has the highest posterior probability for the x-value and return the class number. Parameters: data(np.array): A n × 2 set of (training) input data. Where the first column is a one-dimensional set of data, and the second column is the Class, ranging from 0 to k-1. k(int): The number of classes. x(int): An test input to classify. Return: (int): The class with the highest posterior probability for x. """ (means, stds) = build_model(data, k) posteriors = [] # Calculate posterior probabilities in ecah class for the input x. for class_index in range(k): posteriors.append(normfun(x, means[class_index], stds[class_index])) # A plot for validation. produce_plot(data, means, stds, k) return posteriors.index(max(posteriors)) def build_model(data, k): """ Calculate means and variances for each class. Parameters: data(np.array): A n × 2 set of (training) input data. Where the first column is a one-dimensional set of data, and the second column is the Class, ranging from 0 to k-1. k(int): The number of classes. Returns: means(list): The list of mu. stds(list): The list of sigma. """ means = [] stds = [] for class_index in range(k): positions_of_elements = np.where(data[:, 1] == class_index)[0] current_class = data[positions_of_elements, 0] means.append(np.mean(current_class)) stds.append(np.std(current_class)) return means, stds def normfun(x, mu, sigma): """ Gaussian distribution function. """ return np.exp(-((x-mu)**2)/(2*sigma**2)) / (sigma*np.sqrt(2*np.pi)) def produce_plot(data, means, stds, k): """ produce a plot of Gaussian distribution functions. Parameters: data(np.array): A n × 2 set of (training) input data. Where the first column is a one-dimensional set of data, and the second column is the Class, ranging from 0 to k-1. means(list): The list of mu. stds(list): The list of sigma. k(int): The number of classes. """ left = data[:, 0].min() right = data[:, 0].max() interval = 0.5 * (right-left) x = np.linspace(left-interval, right+interval, 1000) plt.figure() for class_index in range(k): y = [normfun(s, means[class_index], stds[class_index]) for s in x] plt.plot(x, y, label='k = ' + str(class_index)) plt.title('Likelihood') plt.xlabel('x') plt.ylabel('p(x|Ci)') plt.legend() plt.show() # iris_1.txt is derivated from iris.txt but replace all ',' with ' ', # all 'Iris-setosa' with 0, all 'Iris-versicolor' with 1 and all # 'Iris-virginica' with 2. iris_1 = np.loadtxt('iris_1.txt') m_data = iris_1[:, [0, 4]] print(Parametric_Classification(m_data, 3, 5.1))
""" this module is meant to handle the automation part of communicating with Alexa. Future: use https requests to call main module. In post payload, include a scribe type Make web request to run alexa -- if valid scribe type then - generate text - create mp3 from text (gTTS) - convert mp3 to wav - tell program to send wav file to AVS and play response """ import wave from gtts import gTTS import speech_recognition from pydub import AudioSegment class Response: def __init__(self): content = None name = None namespace = None class Scribe(object): def __init__(self): """ AlexaAudio initialization function. @PARAM scribe -- the type of message """ self.msg_q = [] self.resp_q = [] # array (queue) of Response Objects def generate_audio(self, msg, fname='files/command'): """takes in a file path and creates a wav file to be sent to AVS @PARAM fname -- a filename to create (or replace) the new wav file returns: fname on success, None otherwise """ # generate MP3 ext = '.mp3' blank_noise = ' ' # we use blank noise to ensure our words are heard text = blank_noise + msg + blank_noise tts = gTTS(text= text, lang='en') f = fname + ext tts.save(f) # convert MP3 to wav b/c AVS needs wav file self.convert_to_wav(fname) return fname + '.wav' def convert_to_wav(self, fname): ext = '.wav' sound = AudioSegment.from_mp3(fname + '.mp3') f = fname + ext sound.export(f, format="wav") def read_response(self, audio, fname='files/response.wav'): # Alexa uses the MP3 format for all audio responses # if fname[-4:] != '.mp3': # return -1 r = speech_recognition.Recognizer() try: resp = r.recognize_google(audio) print ('Alexa responsed with %s' % resp) self.resp_q.append(resp) except r.UnknownValueError: print("Google Speech Recognition could not understand audio") return -1 except r.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) return -1 except: return -1 return 0 def check_response(self, words): """checks to make sure all the words are present in the response from Alexa @PARAM words -- an array of words returns: boolean or -1 if no response in Scribe object """ if len(self.resp_q) < 1: return -1 resp = self.resp_q.pop(0) r = resp.split() for w in words: if not w in r: return False return True def get_msg_q(self): return self.msg_q def get_resp_q(self): return self.resp_q """Some generic commands programs might use that ensure better successs # # generate messages # def custom_msg(self, msg): self.msg_q.append(msg) # self.generate_audio() def set_alarm(self, time, am=True): msg = 'set alarm at ' + time + ' A M ' self.msg_q.append(msg) # self.generate_audio(fname) def delete_alarm(self, time, am=True): msg = 'delete alarm at ' + time + ' A M ' self.msg_q.append(msg) # self.generate_audio(fname) def play_spotify(): def pause_spotity(): def stop_spotify(): def joke(): # good for testing """
from tkinter import * #Importing tkinter root = Tk() root.title("Wiktarina") root.geometry("300x300") #Doing the first quiz def que_one(): question = Label(root, text="Wisit gruza i ee nelza skuzat?") answer = Entry() btn = Button(root, text="Otwetit!", command=lambda: game1(que_two())) question.grid(row=0) answer.grid(row=1) btn.grid(row=2) def game1(que_two): if answer.get().lower() == "lampo4ka": que_two() else: messagebox.showerror("Ozibka, poprobui izy raz") #Doing the second quiz def que_two(): question_2 = Label(root, text="Zimoi i letom odnowo zweta?") answer_2 = Entry() btn_2 = Button(root, text="Otwet!") question_2.grid(row=0) answer_2.grid(row=1) btn_2.grid(row=2) root.mainloop()
class A: def pr(self): print('A') # 오버라이딩, 재정의 되었다. class SubA1(A): def pr(self): print('pr1') class SubA2(A): # def pr(self): # print('pr2') pass class SubA3: #print('Suba3') pass class MyApp(A): def pr(self): self.my_print() def my_print(self): print('my print') def fff(self): self.my_print() self.my_print() def f(ss): if isinstance(ss, A): ss.pr() else: print('다른 객체 입니다') pass s = SubA1() s2 = SubA2() s.pr() s2.pr() print('---------------') a = A() s3 = SubA3() myapp = MyApp() f(a) f('korea') f(s3) f(myapp)
import sqlite3 conn = sqlite3.connect('d:/pythonProject/sqlite/example.db') c = conn.cursor() # Never do this -- insecure! symbol = 'RHAT' c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol) # Do this instead t = ('RHAT',) sql='SELECT * FROM stocks WHERE symbol=?' c.execute(sql, t) print(c.fetchone()) # Larger example that inserts many records at a time purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ] c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases) conn.commit() c.execute('select * from stocks ORDER BY price') rows=c.fetchall() for row in rows: print(row) for row in c.execute('SELECT * FROM stocks ORDER BY price'): print(row) c.close()
#!/usr/bin/env python import sys import lxml.html import urllib2 def get_tweets(tweeter): """ get_tweets(tweeter) - Returns a list of the 5 most recent tweets for tweeter. """ tweets = [] tweets_url = 'https://twitter.com/' + tweeter try: html = urllib2.urlopen(tweets_url).read() except: return tweets parsed_html = lxml.html.fromstring(html) tweet_elements = parsed_html.cssselect('.tweet-text') for tweet_element in tweet_elements[:5]: tweets.append(tweet_element.text_content()) return tweets def print_tweets(tweeter, tweets): """ print_tweets(tweeter,tweets) - Display tweets for tweeter.""" print '>>>', tweeter , '<<<' print '\n\n'.join(tweets) def main(): if len(sys.argv) < 2: print 'Usage: %s [twitter-username] [twitter-usernameN] ...' % sys.argv[0] sys.exit(1) for tweeter in sys.argv[1:]: print_tweets(tweeter, get_tweets(tweeter)) if __name__ == '__main__': main()
#importing libraries: import requests from gpiozero import MotionSensor import time from picamera import PiCamera camera = PiCamera() #define the PiCamera() to camera variable camera.resolution = (1920, 1080) #set the resolution to 1920x1080 pir = MotionSensor(4) #setup input for MotionSensor (PIR sensor) at GPIO Pin 4 switch = True #create switch variable for loop sequence, and set to True to begin with url = 'https://www.dropbox.com/request/obcoRUWqRSSYgWuNVAv1' #url for request pull to upload to dropbox #defining send_alert function to send alert when motion has been triggered def send_alert(): camera.capture('/home/pi/Dropbox-Uploader/capture.jpg') #takes a photo of the motion detected, via the camera module files = {'file': open('/home/pi/Dropbox-Uploader/capture.jpg', 'rb')} #makes sure to open the file, in the specified directory, as a 'read-binary' (rb) file r2 = requests.post(url, files=files) #uses request function to post to url with specified files print(r2.status_code) #print(r2.text) r = requests.post("https://maker.ifttt.com/trigger/trigger/with/key/de2f5UHFaIUzOvNTYF1f9k") #uses post request function for IFTTT trigger, with API included if r.status_code == 200: #if successfull print("Alert Sent") #prints and verifies that alert has been sent else: print("Error") #prints and verifies that alert hasn't been sent #defining loop function that checks whether motion has been detected or not def loop(): if pir.motion_detected: #using library to check if PIR sensor has detected any motion print("Motion detected!") #prints that motion has been detected send_alert() #calls the send_alert function above switch = False #switches the switch variable to false, for loop sequence purposes else: print("No motion detected.") #prints that no motion has been detected switch = False #switches the switch variable to false, for loop sequence purposes while switch == True: loop() #calls the loop function, in order for it to check it constantly time.sleep(15) #delays it though by 15seconds, so it doesn't do it all the time switch = True
try: i=int(input("enter ur number")) if i<3: b=(i/i-3) elif i==3: raise ZeroDivisionError else: raise TypeError except ZeroDivisionError: print("u hv choosen 3") except TypeError: print(" u hv chosen greater than 3") else: print(b) finally: print("completed")
from knightJumpsOut import knightJumpsOut def getMovePosition(move_dir, x_prev, y_prev): """ This function calculates the new position of the knight after it moves to any of the possible 8 directions assign x_new and y_new to -100 if the knight moves out of the chess board. (-100, -100) is just a signal to the knightMovesForNTimes() function, so that, it does not increment the count of n (number of times the knight should move) """ if move_dir == 1: x_new = x_prev + 1 y_new = y_prev + 2 if x_new > 8: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() elif y_new > 8: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() #print("New position of the knight is ({}, {})\n".format(x_new, y_new)) # if knight moves outside of the chessboard #if x_new < 0 or y_new < 0 or x_new > 8 or y_new > 8: #x_new, y_new = knightJumpsOut() elif move_dir == 2: x_new = x_prev - 1 y_new = y_prev + 2 if x_new < 0: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() elif y_new > 8: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() #print("New position of the knight is ({}, {})\n".format(x_new, y_new)) # if knight moves outside of the chessboard #if x_new < 0 or y_new < 0 or x_new > 8 or y_new > 8: #x_new, y_new = knightJumpsOut() elif move_dir == 3: x_new = x_prev + 1 y_new = y_prev - 2 if x_new > 8: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() elif y_new < 0: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() #print("New position of the knight is ({}, {})\n".format(x_new, y_new)) # if knight moves outside of the chessboard #if x_new < 0 or y_new < 0 or x_new > 8 or y_new > 8: #x_new, y_new = knightJumpsOut() elif move_dir == 4: x_new = x_prev - 1 y_new = y_prev - 2 if x_new < 0: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() elif y_new < 0: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() #print("New position of the knight is ({}, {})\n".format(x_new, y_new)) # if knight moves outside of the chessboard #if x_new < 0 or y_new < 0 or x_new > 8 or y_new > 8: #x_new, y_new = knightJumpsOut() elif move_dir == 5: x_new = x_prev + 2 y_new = y_prev + 1 #print("New position of the knight is ({}, {})\n".format(x_new, y_new)) # if knight moves outside of the chessboard #if x_new < 0 or y_new < 0 or x_new > 8 or y_new > 8: #x_new, y_new = knightJumpsOut() if x_new > 8: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() elif y_new > 8: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() elif move_dir == 6: x_new = x_prev + 2 y_new = y_prev - 1 if x_new > 8: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() elif y_new < 0: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() #print("New position of the knight is ({}, {})\n".format(x_new, y_new)) # if knight moves outside of the chessboard #if x_new < 0 or y_new < 0 or x_new > 8 or y_new > 8: #x_new, y_new = knightJumpsOut() elif move_dir == 7: x_new = x_prev - 2 y_new = y_prev + 1 if x_new < 0: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() elif y_new > 8: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() #print("New position of the knight is ({}, {})\n".format(x_new, y_new)) # if knight moves outside of the chessboard #if x_new < 0 or y_new < 0 or x_new > 8 or y_new > 8: #x_new, y_new = knightJumpsOut() else: x_new = x_prev - 2 y_new = y_prev - 1 if x_new < 0: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() elif y_new < 0: x_new = x_prev y_new = y_prev # print a message that the knight moves out of the board, so reverting to previous position knightJumpsOut() #print("New position of the knight is ({}, {})\n".format(x_new, y_new)) # if knight moves outside of the chessboard #if x_new < 0 or y_new < 0 or x_new > 8 or y_new > 8: #x_new, y_new = knightJumpsOut() return x_new, y_new
#!/usr/bin/python3 from random import shuffle, choice class Card(): # Card ranks low_ranks = [x for x in range(2, 11)] high_ranks = ['j', 'q', 'k', 'a'] ranks = low_ranks + high_ranks # Card suits suits = ['spades', 'clubs', 'hearts', 'diamonds'] # Suits and ranks textual representation ranks_str = {2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten', 'j':'jack', 'q':'queen', 'k':'king', 'a':'ace'} # suits unicode suits_uni = { 'spades' : u'\u2660', 'clubs' : u'\u2663', 'hearts' : u'\u2665', 'diamonds' : u'\u2666'} def __init__(self, rank, suit, is_visible=True): self.rank = rank self.suit = suit self.is_visible = is_visible def __str__(self): if self.is_visible: return '[{}{}]'.format(self.rank, Card.suits_uni[self.suit]) else: return '[XX]' def set_visible(self, is_visible=True): self.is_visible = is_visible def __repr__(self): if self.is_visible: return '{} of {}'.format(Card.ranks_str[self.rank], self.suit) else: return '??' def get_suit(self): return self.suit def get_rank(self): return self.rank @classmethod def random(cls, is_visible=True): rank = choice(Card.ranks) suit = choice(Card.suits) return cls(rank, suit, is_visible) class CardTest(): def __init__(self): c1 = Card.random() print(c1) print(c1, repr(c1)) c2 = Card.random(False) print(c2) print(c2, repr(c2)) def main(): CardTest() if __name__ == '__main__': main()
#largest prime factor of the number ''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ''' #get the prime numbers upto 6008123 def is_prime(n): for i in range(2, (n//2 + 1)): if n% i == 0: #that means it is a prime return False return True print(set(filter(is_prime, range(2, 600851475143))))
print('合計点と平均点を求めます') n = int(input('学生の人数:')) tnsu = [None] * n for i in range(n): tnsu[i] = int(input('{}番の点数'.format(i + 1))) sum = 0 for i in range(n): sum += tnsu[i] print('合計は{}点です'.format(sum)) print('平均は{}点です'.format(sum / n))
sum = 0 for i in range(1,11): sum += int(input(str(i) + "回目の入力:")) print("合計:",sum,sep="")
import random num1 = random.randint(0,9) num2 = random.randint(0,9) num3 = random.randint(0,9) num4 = random.randint(0,9) print(num1,"+",num2,"×",num3,"-",num4) t = num1 + num2 * num3 - num4 n = int(input("計算結果は?:")) if t == n: print("正解です!") else: print("不正解です。正解は",t,"です。")
capital = '東京' area = 2193 print('日本の首都は',capital,'面積は',area) print('吾輩は猫である。',end='') print('名前はまだない。',end='') print('お名前を入力してください') name = input() print('こんにちは',name,'さん!') n = input("文字の入力:") c = int(input("整数の入力:")) t = int(input("小数の入力:")) print("入力された文字 =",n) print("入力された整数 =",c) print("入力された小数 =",t)
n = int(input('挨拶は何回:')) for i in range(1,n+1): print('No.',i,'こんにちは')
#program to count the number of times the number price occurs in a string and if it occurs next to punctuation and capital s=input("enter any string: ") def count(s): count=0 for word in s.lower().split(): if 'price' in word: count=count+1 return count print(count(s))
#program to generate random numbers from 1 to 20 and append them in list import random a=[] n=int(input("enter the number of elements:")) for i in range(n): a.append(random.randint(1,20)) print("randomised list is:{}".format(a))
#program to check if a given key exists in the dictionary or not a={} n=int(input("enter the number of elements: ")) for i in range(n): k=input("enter the keys: ") v=int(input("enter the values: ")) a.update({k:v}) print(a) y=input("enter the key to check: ") if y in a.keys(): print("key is present and value of the key is: ") print(a[y]) else: print("key isn't present")
#program to prove that two string variables of same value point same memory loaction str1="siddhi" str2="siddhi" print("str1: ",hex(id(str1))) print("str2: ",hex(id(str2)))
#program to check whether number is armstrong number or not n=int(input("enter any number: ")) a=list(map(int,str(n))) #to convert int into str and list it b=list(map(lambda x:x**3,a)) #to multiply each element in string by 3 of list a print(a) print(b) if(sum(b)==n): print("armstrong number") else: print("not a armstrong number")
#program to get numbers divsible by 15 from a list lst=[] n=int(input("enter the number of elements: ")) for i in range(n): x=int(input("enter the element: ")) lst.append(x) result=list(filter(lambda p:(p%15==0),lst))#this p if x even gives the same answer print(result)
import time import datetime def seconds_countdown(x): now = int(time.strftime("%s")) countdown = int(input("How many seconds would you like to count?\n")) while True: near = int(time.strftime("%s")) if countdown > 0: print(countdown) time.sleep(1) countdown -= 1 else: break ''' print(time.ctime(), ' This is the time.ctime() function') print(time.localtime(), 'This is the .localtime() function') print(time.gmtime(), 'This is .gmtime() ') print(time.asctime(), 'This is .asctime() ') print(time.time(), 'This is .time() ') ''' def delta_time(x): now = time.time() time.sleep(x) later = time.time() print('This program ended in ', later - now, ' seconds') def convert_input_to_time_value(x): input_time = input("When would you like this program to finish?\n") int_time = time.strptime(input_time, '%Y %m %d %H %M %S') now = time.time() time_until = int(round(time.mktime(int_time) - now)) print('You\'ve got %f seconds remaining ' % time_until) convert_input_to_time_value(1)
text = [] max_length = 0 for _ in range(5): word = input() if len(word) > max_length: max_length = len(word) text.append(word) out= '' for i in range(max_length): for j in range(5): if i < len(text[j]) and text[j][i] != '': out += text[j][i] print(out)
seen, heard = map(int, input().split()) people = [] from collections import Counter for person in range(seen+heard): p = input() people.append(p) counted = Counter(people) both = [] for name, cnt in counted.items(): if cnt == 2: both.append(name) both.sort() print(len(both)) for name in both: print(name)
T = int(input()) prime_digit = {2:[6,2,4,8], 3:[1,3,9,7], 5:[5], 7:[1, 9,3,7]} def divide(num): primes = {2:0, 3:0, 5:0, 7:0} for prime in primes.keys(): while num % prime == 0 : primes[prime] += 1 num = num // prime return primes, num def getlast_digit(prime_divided): total_end = 1 for k, v in prime_divided.items(): if v : end_index = v % (len(prime_digit.get(k))) total_end *= prime_digit.get(k)[end_index] return total_end if total_end < 10 else int(str(total_end)[-1]) def which_server(a, b): prime, noneprime = divide(a) prime = dict(map(lambda x : (x[0], x[1] * b), prime.items())) end_digit = getlast_digit(prime) noneprime, temp = divide(noneprime) noneprime = dict(map(lambda x : (x[0], x[1] * b), noneprime.items())) end_digit *= getlast_digit(noneprime) end_digit = end_digit if end_digit < 10 else int(str(end_digit)[-1]) print(end_digit if end_digit != 0 else 10) for _ in range(T): a, b = map(int, input().split()) end = 1 for __ in range(b): end = (end*a) % 10 if end == 0: print(10) else: print(end)
def solution(amountText): answer = True if amountText.startswith(',') or amountText.endswith(','): return False splitted = amountText.split(',') if splitted[0].startswith('0'):return False for i in range(len(splitted)): if i > 0 and len(splitted[i]) != 3 : return False if not splitted[i].isdigit(): return False return answer print(solution('01,001,009'))
num = input() from collections import Counter counter = Counter(num) sixnine = 0 others = 0 for c in counter.items(): if c [0] in ['6', '9']: sixnine += c[1] else: others = max(others, c[1]) print(max(sixnine//2 + sixnine%2, others))
import heapq from collections import deque def update_next(new=None): global # () for j in wait: if wait pass def solution(jobs): second = 0 done = 0 end = False job = False jobque = deque(jobs) wait = [] next = jobs[0] while done != len(jobs): if second == jobque[0][0]: update_next(jobque.popleft()) if second > end : job = next update_next() if job is False: job = next second += 1 pass answer = [] return answer
# second lowest grade. records = {} names = [] for _ in range(int(input())): name = input() score = float(input()) if score in records.keys(): temp = records[score] temp.append(name) records[score] = temp else: records[score] = [name] lowest = min(records.keys()) second = False for i in sorted(records.keys()): if i > lowest and not second : second = True names.extend(records[i]) for i in sorted(names): print(i)
def josephus(num, target): from collections import deque q = deque(list(range(1, num + 1))) order = [] while q: value = q.popleft() q.append(value) value = q.popleft() q.append(value) order.append(q.popleft()) return order def main(): print(josephus(15, 3)) # [3, 6, 2, 7, 5, 1, 4]이 반환되어야 합니다 if __name__ == "__main__": main()
from matplotlib import pyplot as plt #import statsmodels.api as sm import statsmodels.formula.api as smf # This is different # import pandas as pd import numpy as np # Generating the data N = 20 error_scale = 2.0 x = np.linspace(10,20,N) y_true = 1.5 + 3 * x y_measured = y_true + np.random.normal(size=N, loc=0, scale=error_scale) # Generate the pandas dataframe data = {"x":x, "y_measured":y_measured, "y_true":y_true} df = pd.DataFrame(data) # Plot the data. What type is it? What should we expect from it? plt.plot(df["x"], df["y_true"], '-k', label="True relation") plt.plot(df["x"], df["y_measured"], 's', label="Measured data") plt.xlabel("x") plt.ylabel("y") plt.legend(loc="upper left", fontsize=10, numpoints=1) plt.show() # Ordinary Least Squares = Linear Regression model = smf.ols(formula="y_measured ~ x", data=df) fitted_model = model.fit() coeffs = fitted_model.params print fitted_model.summary() print "The model obtained is y = {0} + {1}*x".format(*coeffs) print coeffs # Plot the data. What type is it? What should we expect from it? y_model = fitted_model.predict(df["x"]) plt.plot(df["x"], df["y_true"], '-k', label="True relation") plt.plot(df["x"], df["y_measured"], 'sw', label="Measured data") plt.plot(df["x"], y_model, ':r', label="Obtained relationship") plt.xlabel("x") plt.ylabel("y") plt.legend(loc="upper left", fontsize=10, numpoints=1) plt.show()
#What: Getting data from API (forecast.io API) #Where: https://courses.thinkful.com/DATA-001v2/assignment/3.2.2 import sqlite3 as sql import requests import datetime # Define some parameters my_api_key = "1c961049c5a9d5fef2e405478a1eadc5" cities = { "Atlanta": '33.762909,-84.422675', "Austin": '30.303936,-97.754355', "Boston": '42.331960,-71.020173', "Chicago": '41.837551,-87.681844', "Cleveland": '41.478462,-81.679435'} # Get the format for the api url = "https://api.forecast.io/forecast/{0}/{1},{2}" # Task: # We need to take each city, and query for every day in the past 30 days # For each returned value, we need to store the data and the temperature on the table # Create the table conn = sql.connect("max_daily_temp.db") c = conn.cursor() c.execute('''DROP TABLE IF EXISTS max_daily_temp''') c.execute('''CREATE TABLE max_daily_temp (date text, city text, max_temp float)''') # Get the values end_date = datetime.datetime.now() delta = datetime.timedelta(days=1) for city in cities.keys(): for i in range(31): # Update the date date = end_date - i*delta datetime_str = date.strftime('%Y-%m-%dT%H:%M:%S') # Get the latlon latlon = cities[city] # Create the url api_link = url.format(my_api_key, latlon, datetime_str) # Get the data and transform it to json r = requests.get(api_link).json() # Get the info and transform to a dict using the json method # Get the max_temp, through the keys and first element of the list, then dict again. max_temp = r["daily"]["data"][0]["temperatureMax"] # Put it on the database date_str = datetime_str.split("T")[0] values = (date_str, city, max_temp) print values c.execute("INSERT INTO max_daily_temp VALUES (?,?,?)",values) # Now save the database and close it conn.commit() conn.close() ########################################################################################### # Just to check that everything was saved. Let's open it with pandas dataframe and print it ########################################################################################### import pandas as pd conn2 = sql.connect('max_daily_temp.db') df = pd.read_sql_query("SELECT * FROM max_daily_temp ORDER BY date, city", conn2, index_col=None) print "Saved database max_daily_temp.db, read with pandas:" print df print "Now group, and print the descrition makes all the work for us" grouped = df.groupby("city") print(grouped.describe()) ########################################################################################### # Discussion ########################################################################################### """ What are the drawbacks of the current implementation? How could we improve it? # Would it be better to use executemany to include more data at once? # apikey is exposed. # Also, the double loop is ugly. What about using some python iterators. # Also, more stats... what else can we know about this data? """
# Quick crash course on sqlite3 # See: https://docs.python.org/2/library/sqlite3.html import sqlite3 def print_table(cursor): for row in cursor.execute('SELECT * FROM persons ORDER BY name'): print row return ################################################################################ # Connect to a database ################################################################################ # We call it conn because it's a connection, it's not the database itself conn = sqlite3.connect('persons.db') # All interactions with the database are called querys # And they require to be used through a cursor c = conn.cursor() ################################################################################ # Querys "posting" info ################################################################################ # Querys that "put" information in the table. # They are applied using the .execute() method. They are immediately accesible # from the pysql library, but the changes only affect the database (persons.db) # If you commit the changes before closing the connection. # Example: Delete a table # This completely destroys the table, so be careful before dropping tables c.execute('''DROP TABLE IF EXISTS persons''') # Example: Create table c.execute('''CREATE TABLE persons (name text, gender text, age int)''') # Example: Insert one row of data c.execute("INSERT INTO persons VALUES ('Sebastian Flores','M','32')") # Example: Insert several rows of data data = [('Maria Jose', 'F', 32), ('Lorenzo','M','28'), ('Janet','F','28')] c.executemany("INSERT INTO persons VALUES (?, ?, ?)", data) # Save (commit) the changes to the database conn.commit() ################################################################################ # Querys "delivering" info ################################################################################ # Querys that "get" information from the table. # They are applied using the .execute() method. # The retrieved values can be accessed: # using .fetchone(): Gives you only the first row from the query # using .fetchall(): Gives you all the rows from the query, at once # using a iterator: Gives you all the rows from the query, one by one # Examples using .fetchone() print "Examples using fetchone()" c.execute('SELECT * FROM persons WHERE age=28') print c.fetchone() target_age = (28,) c.execute('SELECT * FROM persons WHERE age=?',target_age) print c.fetchone() # Examples using .fetchall() print "Examples using fetchall()" c.execute('SELECT * FROM persons WHERE age=32') print c.fetchall() target_age = (32,) c.execute('SELECT * FROM persons WHERE age=?',target_age) print c.fetchall() # Examples using an iterator print "Examples using iterator()" for row in c.execute('SELECT * FROM persons WHERE age=28'): print row target_age = (28,) for row in c.execute('SELECT * FROM persons WHERE age=?',target_age): print row ################################################################################ # Disconnect to a database ################################################################################ # Beware of loosing data, be sure to commit your changes conn.close()
# Quick crash course on sqlite3 and pandas # See: https://docs.python.org/2/library/sqlite3.html import sqlite3 import pandas as pd # Auxiliar function def print_table(cursor): for row in cursor.execute('SELECT * FROM persons ORDER BY name'): print row return ################################################################################ # Mission: # Open a pandas dataframe with the content of a given database ################################################################################ conn = sqlite3.connect('persons.db') c = conn.cursor() df = pd.read_sql_query("SELECT * FROM persons ORDER BY name", conn, index_col=None) print "Dataframe created from the database" print df, "\n" # OBS: In a larger table, you can (and probably will) select # only a few rows df_small = pd.read_sql_query("SELECT name, age FROM persons WHERE age=28", conn, index_col="name") print "Small dataframe loaded from the database" print df_small, "\n" # OBS: the index_col in the dataframe cannot be modified (?!) ################################################################################ # Using the data is easier in pandas ################################################################################ df["age"] = df["age"] + 1 # Happy birthday, everyone df["gender"] = "U" # Unspecified print "Modified dataframe" print df, "\n" # Nevertheless, the database has not been affected by the changes! print "Original database (Notice the format is completely different)" conn.commit() for row in c.execute('SELECT * FROM persons ORDER BY name'): print row print "" df = pd.read_sql_query("SELECT * FROM persons ORDER BY name", conn, index_col=None) print "Reloading the dataframe created from the database" print df, "\n" print "Takeaway: Dataframes from databases are hardcopied values" print " and modifications must be explicitely imposed"
# -*- coding: utf-8 -*- """ Created on Thu Sep 20 08:48:56 2018 @author: ali hussain """ class Rectangle(): def __init__(self,length,breadth): self.length=length self.breadth=breadth def area(self): return self.length*self.breadth a=int(input("Enter length :")) b=int(input("Enter breadth :")) obj=Rectangle(a,b) print(obj.area())
def cheche(x,y): # x mean number of loop , y its static mean number your enter ex: 7 Center = round(y/2+0.5) diff = abs(Center-x) # abs function conver nigatave to positive space = abs((diff+diff+2)-y) if x == 1 or x == y: return " "*diff + "*" + " "*diff else: return " "*diff+"*"+" "*space+"*"+" "*diff num = int(input("enter num: ")) for xx in range(1,num+1): print(cheche(xx,num))
n = int(input("첫 번째 수 입력 : ")) m = int(input("두 번째 수 입력 : ")) def find_even_number(): numbers = [ i for i in range(n, m+1) if i%2 == 0] for s in numbers : print(s, '짝수') if s == (n + m) / 2 : print (s, '중앙값') find_even_number()
# import time name = input("what is your name?") print('nice to meet you,', name) # time.sleep(5) # print('sleep off') greet = input(f"how are you, {name}?") print(greet)
#SWM v2 feature transformation import numpy as np #import matplotlib.pyplot as plt def feature_transformation(feature_vector): """Adjusts and rescales the values of SWMv2 features to fall within an appropriate range. ARGUEMENTS feature_vector: a list of the features values of a single state of the SWM v2 simulator RETURNS adjusted_vector: a list of the same length as feature_vector, containing the transformed values of each feature. """ #create the return list adjusted_vector = [0.0] * len(feature_vector) #means and standard deviations from emperical data #values from get_means_and_stds() # heat ave: 0.500375296248 # humidity ave: 0.500926956231 # timber ave: 2.77865692101 # vulnerability ave: 0.364513749217 # habitat ave: 2.02501996769 # heat STD: 0.288972166094 # humidity STD: 0.288167851971 # timber STD: 2.79279655522 # vulnerability STD: 0.376634871739 # habitat STD: 5.00511964501 # HEAT HUMID TIMB VULN HAB feature_means = ( 0.5, 0.5, 2.7787, 0.3645, 2.0250) feature_STDs = ( 0.2888, 0.2888, 2.7927, 0.3766, 5.0051) #the feature transformations are done one-at-a-time to allow for custom handling of each one. #The generic goal is: mean=0 STD = 0.5 #NOTE: the constant has not been added to the features, so in SWMv2.1, there are only 5 feature values #Transform feature 0 # "heat" value adjusted_vector[0] = (feature_vector[0] - feature_means[0]) / (feature_STDs[0] * 2) #Transform feature 1 # "humidity" value adjusted_vector[1] = (feature_vector[1] - feature_means[1]) / (feature_STDs[1] * 2) #Transform feature 3 # "timber" value adjusted_vector[2] = (feature_vector[2] - feature_means[2]) / (feature_STDs[2] * 2) #Transform feature 4 # "vulnerability" value adjusted_vector[3] = (feature_vector[3] - feature_means[3]) / (feature_STDs[3] * 2) #Transform feature 5 # "habitat" value adjusted_vector[4] = (feature_vector[4] - feature_means[4]) / (feature_STDs[4] * 2) #return the transformed features return adjusted_vector def heat_transformation(heat_value): """Get the transformed heat value (esp for SWMv1)""" input_vector = [heat_value, 0, 0, 0, 0] trans_vector = feature_transformation(input_vector) return trans_vector[0]
from sys import argv from os.path import exists script, input_file, output_file = argv print(f"Dies input file exist? {exists(input_file)}") #check if files exist print(f"Does output file exist? {exists(output_file)}") print("hit RETURN to continue, CTRL-C to abort.") input() file_copy = open(input_file, 'r') #open file file_data = file_copy.read() #read file and store file_data file_data = file_data.lower() #replace uppercase with lowercase punc = '''!()-[]{};:'"\, <>./?@#$%^&*_~''' #non alphabetical characters for element in file_data: #traverse file and remove all non letters if element in punc: file_data = file_data.replace(element, " ") word_list = file_data.split() #store in a list dictionary = {} for word in word_list: dictionary[word] = dictionary.get(word, 0) + 1 #add words and increment values out_file = open(output_file, 'w') #open file out_file.truncate() #delete everything for ele in sorted(dictionary): #traverse dictionary and sort keys and values string = str(dictionary[ele]) + "\t" + str(ele) #key and value out_file.write(string) #write to file out_file.write("\n") #add new line after evry key and value wrote out_file.close() file_copy.close()
badu_abil=False badu_punt=False helbidea=input("Sartu zure e-posta helbidea: ") # for i in helbidea: # if(i=="@"): # badu_abil=True # if(i=="."): # badu_punt=True if "." in helbidea: badu_abil=True if "@" in helbidea: badu_punt=True if badu_abil and badu_punt: print("Ados, aurrera egin dezakezu.") else: print("Hori ez da e-posta helbide bat.")
#using index function we can access the value in a tuple since it is ordered mytuple = (1,2,3,4,5,6) mytuple[2]
import myMath as m n = int(input()) x = float(input()) x *= 3.14/180 val = 0 num = 1 for i in range(1, n+1): if(i % 2 != 0): val += m.power(x, num) / m.fact(num) else: val -= m.power(x, num) / m.fact(num) num += 2 print("sin(", x, ") =", val)
from __future__ import division import math water_density=1000 #kg/m3 gravity=9.8 #m/s2 def pipe_velocity(pipe_diameter, demand_m3_s): area=math.pi*(pipe_diameter*0.001/2)**2 pipe_velocity=demand_m3_s/area return pipe_velocity def headloss(pipe_diameter, pipe_length, demand_m3_s): headloss=0.03*pipe_length*(pipe_velocity(pipe_diameter, demand_m3_s)**2)/(2*pipe_diameter*0.001*9.81) return headloss def total_head(pipe_diameter, demand_m3_s, pump_pressure, pipe_length): vel_pressure = (pipe_velocity(pipe_diameter, demand_m3_s)**2)*water_density/2 cons_pressure = pump_pressure/10*101325 headloss_pressure = headloss(pipe_diameter, pipe_length, demand_m3_s)*gravity*water_density total_head = (vel_pressure + cons_pressure + headloss_pressure)/(gravity*water_density) return total_head pipe_vel = pipe_velocity(100, 20) head = headloss(100, 8000, 20) total_head_ = total_head(100, 20, 0, 8000) print (pipe_vel, head, total_head_)
from TicTacToe.bots import player class Human(player.Player): """ A text based human player """ def __init__(self, symbol, opponent, name="Human"): """ name - Name of the player : String symbol - Symbol to play with : String opponent - Symbol to play against : String """ Player.__init__(self, name, symbol, opponent) def get_move(self, board): """ Get the move from the human board - The current board : Board position - The position to move to : Tuple len == 2 board -> position """ print("Player %s what is your move:" % self.name) position = (input("i: "), input("j: ")) return position
#!/usr/bin/python3 """ an algorithm to calculate minimumOperations necessary to get to a number of characters. Full exercise: In a text file, there is a single character H. Your text editor can execute only two operations in this file: Copy All and Paste. Given a number n, write a method that calculates the fewest number of operations needed to result in exactly n H characters in the file. """ def minOperations(n): """ minimumOperations :param n: number to reach calculating minimumOperations before get to it :return: an integer, which is the fewest number of operations needed to result in exactly n H characters in the file or 0 if n is impossible to achieve """ if n <= 0: return 0 if n == 1: return 0 operations = 0 characters = 1 additive = 1 while characters < n: if n % characters == 0: operations += 2 additive = characters characters += additive # print('DIVISIBLE! operations: {}, characters: {}' # .format(operations, characters)) else: characters += additive operations += 1 # print('NON! operations: {}, characters: {}' # .format(operations, characters)) return operations
#!/usr/bin/python import mysql.connector city = input("Enter A CITY NAME: ") print ("City entered was: ", city) # Setup MySQL Connection # Pass viewer: *AAB3E285149C0135D51A520E1940DD3263DC008C db = mysql.connector.connect(host="173.194.242.211", user="root", password="InfectiousTraining", db="IM_Task_2") cursor = db.cursor() queryword = city query = ("SELECT ct.city_id, c.country_id, c.name AS Country_Name, c.alpha2, c.alpha3, ct.Region_Region_id, r.name AS Region_Name, r.iso_code AS Region_ISO_Code, ct.city_id, ct.name AS City_Name, ct.iso_code AS City_ISO_Code, c.targetable FROM IM_Task_2.City ct INNER JOIN IM_Task_2.Country c ON ct.Country_country_id=c.country_id LEFT JOIN IM_Task_2.Region r ON ct.Region_Region_id=r.Region_id WHERE ct.name = '"+queryword+"'") query2 = ("SELECT COUNT(*) FROM IM_Task_2.City ct INNER JOIN IM_Task_2.Country c ON ct.Country_country_id=c.country_id LEFT JOIN IM_Task_2.Region r ON ct.Region_Region_id=r.Region_id WHERE ct.name = '"+queryword+"'") cursor.execute(query) results = cursor.fetchall() cursor.execute(query2) result=cursor.fetchone() number_of_rows=result[0] print (number_of_rows) for row in results: if (number_of_rows > 0): print(row) print("Here are the details to the following city that you have entered:") print(" Country ID is : ",row[1],". The Country it belongs to is: ",row[2],". The 2 letter abrivation is: ",row[3],". The 3 letter abrivation is: ",row[4],".") print(" Region ID is: ",row[5],". The Region it belongs to is: ",row[6],". The ISO Code for the region is: ",row[7],".") print(" City ID: ",row[8]," The city: ",row[9],". The ISO Code for the city is: ",row[10],".") if(row[11]!= '0'): print(" This country is targetable.") else: print(" At the moment this country is not targetable.") else: print("No resultsfoundat thistime!") #for (ct.city_id, ct.Region_Region_id, ct.Region_Country_country_id, ct.name, ct.iso_code, r.iso_code, r.name, c.alpha2, c.alpha3, c.name, c.targetable) in cursor: # print("{},{},{},{},{},{},{},{},{},{},{}".format( # ct.city_id, ct.Region_Region_id, ct.Region_Country_country_id, ct.name, ct.iso_code, r.iso_code, r.name, c.alpha2, c.alpha3, c.name, c.targetable)) #cursor.close() #db.close()
def mergesort(array): if len(array) <= 1: return array else: left = mergesort(array[:len(array)//2]) right = mergesort(array[len(array)//2:]) combined = [] #counters i = 0 j = 0 #while the counter hasn't reached the end of the array while i < len(left) and j < len(right): #find lowest element and append (compare the elements) if left[i] < right[j]: combined.append(left[i]) i += 1 else: combined.append(right[j]) j += 1 if i == len(left): #reached end of left combined = combined + right[j:] else: #reached end of right combined = combined + left[i:] return combined def inversions(array): if len(array) <= 1: return array, 0 else: left, left_count = inversions(array[:len(array)//2]) right, right_count = inversions(array[len(array)//2:]) combined = [] split_count = 0 #counters i = 0 j = 0 #while the counter hasn't reached the end of the array while i < len(left) and j < len(right): #find lowest element and append (compare the elements) if left[i] < right[j]: combined.append(left[i]) i += 1 else: #right side, any of these get called, means inversion split across left and right #number of inversions is the number of elements remaining on left side, because these are the ones whose lines are intersected combined.append(right[j]) j += 1 #because index starts from 0 while len starts from 1, hence -1 #above statement is wrong, because pointer i is pointing before the element, so if at len(left) - 1 means still have one element that hasn't been inserted yet split_count += (len(left) - i) if i == len(left): #reached end of left, right insertions are only noteworthy when they are crossing something in the left array combined = combined + right[j:] else: #reached end of right combined = combined + left[i:] return combined, left_count + right_count + split_count
password = input() new_pass = [] for character in password: new_pass.append(chr(ord(character)+3)) print("".join(map(str,new_pass)))
import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # mo = phoneNumRegex.search('Call me 415-555-1011 tomorrow, or at 415-555-9999 for my office line.') # print(mo.group()) print(phoneNumRegex.findall('Call me 415-555-1011 tomorrow, or at 415-555-9999 for my office line.'))
""" Challenge #3: Create a function that takes a string and returns it as an integer. Examples: - string_int("6") ➞ 6 - string_int("1000") ➞ 1000 - string_int("12") ➞ 12 """ def string_int(txt: str) -> int: # Your code here # check to make sure that `txt` makes sense as an integer # the `isnumeric` function checks if a string can be represented # as a number # if `txt` is a valid number: if txt.isnumeric() is True: # take the string input and convert it to an integer # the `int` function does this for us in Python # call the `int` function, passing it the `txt` input converted_int = int(txt) # return the converted result return converted_int # what do we do if `txt` is not a valid number? else: # we'll return an error indicating that `txt` is not a valid number # use string interpolation to print out the actual value of `txt` # use f-strings in Python return f"'{txt}' is not a valid number" # return int(txt) return converted_int or f"'{txt}' is not a valid number" print(string_int("1000")) print(string_int("hi"))
""" Given an array of integers `nums`, define a function that returns the "pivot" index of the array. The "pivot" index is where the sum of all the numbers on the left of that index is equal to the sum of all the numbers on the right of that index. If the input array does not have a "pivot" index, then the function should return `-1`. If there are more than one "pivot" indexes, then you should return the left-most "pivot" index. Example 1: Input: nums = [1,7,3,6,5,6] Output: 3 Explanation: The sum of the numbers to the left of index 3 (1 + 7 + 3 = 11) is equal to the sum of numbers to the right of index 3 (5 + 6 = 11). Also, 3 is the first index where this occurs. Example 2: Input: nums = [1,2,3] Output: -1 Explanation: There is no index that satisfies the conditions in the problem statement. """ from typing import List # def get_left_sum(nums, index): # if index == 0: # return 0 # return sum(nums[0:index]) # def get_right_sum(nums, index): # if index == len(nums) - 1: # return 0 # return sum(nums[index+1:]) # def pivot_index(nums: List[int]) -> int: # # Your code here # # 1. for each number, we'll go ahead and sum up everything to its left # # and everything to its right # # check if those sums are equal # # as soon as we find such a number, we'll return it # # O(n^2) # for i in range(len(nums)): # O(n) # # get the left sum # # these two sum steps have us touch every other list element # # for j in range(len(nums)) # # O(n) # left_sum = get_left_sum(nums, i) # O(n/2) # # get the right sum # right_sum = get_right_sum(nums, i) # O(n/2) # if left_sum == right_sum: # return i # return -1 # O(2 * n) ~ O(n) def pivot_index(nums): left = 0 right = sum(nums) # O(n) for i, num in enumerate(nums): # O(n) right -= num if left == right: return i left += num return -1 print(pivot_index([1,7,3,6,5,6]))
""" You are given a binary tree. You need to write a function that can determine if it is a valid binary search tree. The rules for a valid binary search tree are: - The node's left subtree only contains nodes with values less than the node's value. - The node's right subtree only contains nodes with values greater than the node's value. - No duplicates in the binary tree. - Both the left and right subtrees must also be valid binary search trees. Example 1: Input: 5 / \ 3 7 Output: True Example 2: Input: 10 / \ 2 8 / \ 6 12 Output: False Explanation: The root node's value is 10 but its right child's value is 8. Example 3: 10 / \ 2 18 / \ 6 21 Output: False """ # Definition for a binary tree node. class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right # is this function expecting an answer? def is_valid_BST(root): # Your code here # keep track of the valid range as we're traversing down the tree # when we go left, limit the upper bound to be root - 1 # when we go right, limit the lower bound to be root + 1 # check if the current node's value falls within the range # check the root's left child # if the left's child value >= root's value # return False # check the root's right child # if the right's child value <= root's value # return False # otherwise, return True return recurse(root, float('-inf'), float('inf')) def recurse(root, min_bound, max_bound): # base case(s) # check the current value against the range # we've traversed the whole tree and never saw a False, so return True if root is None: return True # if the current value falls outside the range, return False if root.value < min_bound or root.value > max_bound: return False # how do we get closer to our base case? # recurse with the left child and update the range left = recurse(root.left, min_bound, root.value - 1) # recurse with the right child and update the range right = recurse(root.right, root.value + 1, max_bound) # if either left or right is False, return False return left and right
# Determine if a string sequence of {}[]() is valid # '[{]}' is invalid def validBracketSequence(sequence): # determine if the string is a valid sequence of brackets # empty is valid # stack = [] for char in sequence: if char in {'(', '[', '{'}: stack.append(char) # what happens if we encounter an empty stack? elif not stack: return False else: # try to pop if char == ')' and stack[-1] == '(': stack.pop() elif char == ']' and stack[-1] == '[': stack.pop() elif char == '}' and stack[-1] == '{': stack.pop() else: return False if stack: return False return True # # This was failed attempt 1 - I naively went at it # # like another parenthesis-counting problem. # # It fails on '[{]}' type seqs # # def validBracketSequence(sequence): # # determine if the string is a valid sequence of brackets # # empty is valid # # # squiggle_stack = 0 # square_stack = 0 # curve_stack = 0 # for char in sequence: # if squiggle_stack < 0 or square_stack < 0 or curve_stack < 0: # return False # if char == '{': # squiggle_stack += 1 # if char == '[': # square_stack += 1 # if char == '(': # curve_stack += 1 # if char == '}': # squiggle_stack -= 1 # if char == ']': # square_stack -= 1 # if char == ')': # curve_stack -= 1 # if squiggle_stack != 0 or square_stack != 0 or curve_stack != 0: # return False # return True
# # Binary trees are already defined with this interface: # class Tree(object): # def __init__(self, x): # self.value = x # self.left = None # self.right = None def max_depth(node): if node is None: return 0 max_l = max_depth(node.left) max_r = max_depth(node.right) if max_l is False or max_r is False: # we've found an imbalanced subtree. Return it up. return False if abs(max_l - max_r) > 1: return False return max(max_l, max_r) + 1 def balancedBinaryTree(root): a = max_depth(root) if a is False: return False return TrueB
""" Given only a reference to a specific node in a linked list, delete that node from a singly-linked list. Example: The code below should first construct a linked list (x -> y -> z) and then delete `y` from the linked list by calling the function `delete_node`. It is your job to write the `delete_node` function. ```python class LinkedListNode(): def __init__(self, value): self.value = value self.next = None x = LinkedListNode('X') y = LinkedListNode('Y') z = LinkedListNode('Z') x.next = y y.next = z delete_node(y) ``` *Note: We can do this in O(1) time and space! But be aware that our solution will have some side effects...* """ class ListNode(): def __init__(self, value): self.value = value self.next = None # ###starter code for this file ## # def delete_node(node_to_delete): # # Your code here # delete_node(y) x = ListNode(4) y = ListNode(10) z = ListNode(15) x.next = y y.next = z ### hijacking the file for homework # # given a monotonically increasing linked list l (with head l), insert value def insertValueIntoSortedLinkedList(l, value): ins = ListNode(value) current = l if l: if ins.value < l.value: # replace the head ins.next = l return ins while current.next: # exhausts at the end of the ll if ins.value < current.next.value: ins.next = current.next current.next = ins return l current = current.next current.next = ins return l else: l = ins return l # Notes: in order, the flow of logic # 1) checks if there's a head (if not, return ins) # 2) checks if the head needs replaced with ins (in the event ins is smaller than the entire list) # 3) traverses the list, handling 2 cases: no current.next, meaning we've found the # end of the list and need only tack on ins, or ins.value < current.next.value, in which case it's time # to unhook the list, insert ins, and rehook. # # Note how it does the while n times and the head checks once each, but two cases go into each n check # (because the end could be anywhere) # Singly-linked lists are already defined with this interface: # class ListNode(object): # def __init__(self, x): # self.value = x # self.next = None # def mergeTwoLinkedLists(l1, l2): # O(n + m) time # Merge two monotonically increasing ll's # # #main code assumes l1 and l2 # --> handle situations where either runs out (while .next) # take min(current1.next, current2.next) # if l1 and l2: # if l1.value < l2.value: # base = l1 # feeder = l2 # else: # base = l2 # feeder = l1 # # Now we're ready to do n + m while loop comparisons. # anchor = None # slider = base # while slider.next and feeder: # if feeder.value < slider.next.value: # anchor = feeder.next # feeder.next = slider.next # slider.next = feeder # feeder = anchor # else: # slider = slider.next # # hook up the rest of the remaining list, return head # # we either ran out of feeder or base. # if not slider.next: # slider.next = feeder # return base # # if there is no slider.next, slider.next = feeder, return base # return base # if l1: # return l1 # if l2: # return l2 # return []
# We only multiply when some logic is nested # When code is stacked sequentially on top of one another # we add their respective runtimes # O(1) + O(1) + O(1) + O(0.5n) + O(2000) # O(0.5n + 2000 + 1 + 1 + 1) # O(0.5n + 2003) # O(n + 2003) # O(n) def do_a_bunch_of_stuff(items): last_idx = len(items) - 1 # getting the length is O(1) print(items[last_idx]) # accessing an array element via index - O(1) # we'll consider printing/console logging O(1) middle_idx = len(items) / 2 # arithmetic operations - O(1) idx = 0 # initializing a variable - O(1) # 0.5n * 1 * 1 = 0.5n while idx < middle_idx: # this loop only runs over half our items # 1000 * n # ~ n print(items[idx]) # O(1) idx = idx + 1 # O(1) # O(2000 * 1) = O(2000) for num in range(2000): # O(2000) print(num) # O(1) # O(n) + O(n) = O(2 * n) = O(n) def removeDuplicate(arr): differents = {} # initializing a variable - O(1) # O(n) * O(1) * O(1) * O(1) = O(n) for i in arr: # O(n) if i not in differents: # O(1) differents[i] = [] # O(1) - Setting `i` as a key in the dict and setting its # value to an empty list differents[i] += [i] # 1. appending onto the end of the list - O(1) # 2. accessing the key in the dictionary - O(1) return differents.keys() # the `keys` method takes all the keys in the dictionary # and returns them all as a list # O(n) print(removeDuplicate([1,1,2,4,5,5,3,3,1,2]))
""" Challenge #4: Create a function that takes length and width and finds the perimeter of a rectangle. Examples: - find_perimeter(6, 7) ➞ 26 - find_perimeter(20, 10) ➞ 60 - find_perimeter(2, 9) ➞ 22 """ def find_perimeter(length, width): # takes in length and width, integers # returns perimeter # perimeter = 2*length + 2*width if type(length) == int and type(width) == int: return 2*length + 2*width else: return TypeError(f'Either length: {length} or width: {width} is not an integer.') #print(type(3) == float) print(find_perimeter(2,8))
""" Challenge #6: Return the number (count) of vowels in the given string. We will consider `a, e, i, o, u as vowels for this challenge (but not y). The input string will only consist of lower case letters and/or spaces. """ def get_count(input_str: str) -> int: # Your code here # count number of vowels # keep a counter to keep track of number of vowels num_vowels = 0 # we need to inspect every character in the input string # to see if it's a vowel # keep a list or a string of all the vowels we care about vowels = "aeiou" # iterate through the characters of our input string # we don't care about the indices of each character for char in input_str: # how do we know it's a vowel? # doesn't look like there's a built-in function/method for this # as we iterate, we can check if the current character is part of the # vowel string/list if char in vowels: # if it is, increment our counter num_vowels += 1 # return our counter return num_vowels print(get_count("abcdefghijklmnopqrstuvwxyz"))
""" Challenge #7: Given a string of lowercase and uppercase alpha characters, write a function that returns a string where each character repeats in an increasing pattern, starting at 1. Each character repetition starts with a capital letter and the rest of the repeated characters are lowercase. Each repetition segment is separated by a `-` character. Examples: - repeat_it("abcd") -> "A-Bb-Ccc-Dddd" - repeat_it("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" - repeat_it("cwAt") -> "C-Ww-Aaa-Tttt" """ def repeat_it(input_str): # Solution 1 return '-'.join(c.upper() + c.lower() * i for i, c in enumerate(input_str)) # Solution 2 return '-'.join((a * i).title() for i, a in enumerate(input_str, 1)) # Solution 3 output = "" for i in range(len(input_str)): output+=(input_str[i]*(i+1))+"-" return output.title()[:-1] # Solution 4 i = 0 result = '' for letter in input_str: result += letter.upper() + letter.lower() * i + '-' i += 1 return result[:len(result)-1]
""" Demonstration #2 Given a non-empty array of integers `nums`, every element appears twice except except for one. Write a function that finds the element that only appears once. Examples: - single_number([3,3,2]) -> 1 - single_number([5,2,3,2,3]) -> 5 - single_number([10]) -> 10 """ def single_number(nums): # Your code here pass def csFindAddedLetter(str_1, str_2): # takes in two strings # str_2 = str_1, shuffled, plus one letter somewhere. # return that letter # # so we have two strings of arbittary length that are identical except for one character # that character might be a repeat # str1 = list(str_1) str2 = list(str_2) for char in str1: str2.remove(char) return str2.pop() test1 = 'abcdefgaaaaa' test2 = 'afdegcbaaahaa' #print(csFindAddedLetter(test1, test2)) def csFirstUniqueChar(input_str): # takes in a string # return the index of the first character that doesn't repeat # else return -1 dct = {} lst = [] for char in input_str: if char not in dct: dct[char] = 0 lst.append(char) else: if char in lst: lst.remove(char) if lst: return input_str.index(lst[0]) return -1 # for char in str you could add it to a list and also into a dict # then if you find that char again (i.e. if char in dict), remove it from the list # # look at a character # check if it's in the dictionary. If not, add it and add it to the list. # {'a'} ['a'] # Next character is a 'b', Not in the dictionary. Added. {'a', 'b'} ['a', 'b'] # next character is an 'a'. It's in the dict, so if it's in the list, remove it. ['b'] # next is 'a'. In the dict. If it's in the list, remove it. (it isn't, so nothing happens) # next is 'c'. Add to dict. Add to list. ['b', 'c'] # then 'd', 'e', 'f' --> ['b' cdef] # then f --> in dict, remove from list bcde # when done, return list[0] print(csFirstUniqueChar('vvv')) print(csFirstUniqueChar('ilovelambda')) print(csFirstUniqueChar('lambdavelambda'))
def square_of_sum(count): square = 0 tot = 0 for num in range(count + 1): tot += num square = tot * tot return square def sum_of_squares(count): tot = 0 for num in range(count + 1): tot += (num * num) return tot def difference(count): return square_of_sum(count) - sum_of_squares(count)
def find_anagrams(word, candidates): result = [i for i in candidates if i.lower() != word.lower( ) and sorted(i.lower()) == sorted(word.lower())] return result
def is_equilateral(sides): if sides[0] + sides[1] <= sides[2] \ or sides[2] + sides[1] <= sides[0] \ or sides[0] + sides[2] <= sides[1]: return False elif sides[0] == sides[1] and sides[0] == sides[2]: return True else: return False def is_isosceles(sides): if sides[0] + sides[1] <= sides[2] \ or sides[2] + sides[1] <= sides[0] \ or sides[0] + sides[2] <= sides[1]: return False elif sides[0] == sides[1] \ and sides[0] == sides[2]: return True elif sides[0] == sides[1] \ and not sides[0] == sides[2]: return True elif sides[0] == sides[2] \ and not sides[0] == sides[1]: return True elif sides[2] == sides[1] \ and not sides[2] == sides[0]: return True else: return False def is_scalene(sides): if sides[0] + sides[1] <= sides[2] \ or sides[2] + sides[1] <= sides[0] \ or sides[0] + sides[2] <= sides[1]: return False elif not sides[0] == sides[1] \ and not sides[0] == sides[2] \ and not sides[2] == sides[1]: return True else: return False