blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
45bf63c9502b11034635a78932daacd316844858
thangpxph/python_training
/project_v1_2_algotithm.py
405
4.09375
4
x =6 y =13 num = 0 while True: if x > y: num += 1 y+=1 elif y == x: break elif y % 2 == 0: while True: if x >= y: break if y % 2 == 0: num += 1 y /= 2 else: break else: num+=1 y +=1 print("the minimum number of steps to x = y: " + str(num))
3cd2ec079532e4dd74e4caf91f7e6062eda3f9e0
Michael-Paluda/Competitive
/competitive/Elevator_Problem.py
957
4.0625
4
import time def calculate_elevator_path(floors, pos, goal, up, down): t0 = time.time() moves = 0 impossible = False while pos != goal: t1 = time.time() if t1 - t0 > .8: return 'use the stairs' if impossible == True: return 'use the stairs' if pos > goal and down != 0: while pos - down < 1: impossible = True pos += up moves += 1 pos -= down moves += 1 elif pos < goal and up != 0: while pos + up > floors: impossible = True pos -= down moves += 1 pos += up moves += 1 else: return 'use the stairs' return moves floors, start, goal, up, down, = map(int, input().split()) print(calculate_elevator_path(floors, start, goal, up, down))
fc17be27e3410e4ba5bc92d00089eb5b8a25a6e3
martinsutherland1/functions_start_point
/src/python_functions_practice.py
1,315
3.625
4
# write functions on this file only, functions need to be based on python_functions # under the folder tests # You'll need to delete @unit.test.skip lines in order for tests to run in file below # run tests via run_tests.py def return_10(): return 10 def add(num_1 , num_2) : return num_1 + num_2 def subtract(num_1, num_2): return num_1 - num_2 def multiply(num_1, num_2): return num_1 * num_2 def divide(num_1, num_2): return num_1 / num_2 def length_of_string(string_1): return len(string_1) def join_string(string_1, string_2): return string_1 + string_2 def add_string_as_number(string_1, string_2): return int(string_1) + int(string_2) def number_to_full_month_name(num): if num == 1: return "January" elif num == 3: return "March" elif num == 4: return "April" elif num == 9: return "September" elif num == 10: return "October" def number_to_short_month_name(num): month_name = number_to_full_month_name(num)[0:3] return month_name def volume_of_cube(l): return l ** 3 def reverse_string(x): return x[::-1] # reverse_test = reverse_string("hello") # print(reverse_test) def fahrenheit_to_celcius(fahrenheit): return (fahrenheit - 32) * 5/9 print((150-32) * 5/9)
8771272d87971d468a97be2fb7c63ba233bf0015
Aasthaengg/IBMdataset
/Python_codes/p02259/s875350623.py
475
3.71875
4
def bsort(array): i = 0 counter = 0 while i < len(array)-1: for c in range(len(array)-1,i,-1): if array[c]<array[c-1]: a = array[c-1] array[c-1] = array[c] array[c] = a counter += 1 i = i+1 resul = ' '.join([str(i) for i in array]) print(resul) print(counter) n = int(input()) inputarr = input().split() intarr = [int(i) for i in inputarr] bsort(intarr)
7cdbc7fe3ce22c9a4563462b1498cdf48ed5be62
alisonvpereira/Phython.github.io
/Week_4_Session_1_Excercises/01_Variables_and_User_Input.py
2,695
4.28125
4
# Q1 Write a program that takes two numbers from the user, # and outputs their sum. #1 print("------ Start of Q1 ------") first_input = input("Enter a number: ") second_input = input("Enter another number: ") output = int(first_input) + int(second_input) print(f"Your output is {output}") print() print("Round 2...") print() #2 first_input = input("Enter a number: ") second_input = input("Enter another number: ") output = int(first_input) + int(second_input) print(f"Your output is {output}") print() print("Round 3...") print() #3 first_input = input("Enter a number: ") second_input = input("Enter another number: ") output = float(first_input) + int(second_input) print(f"Your output is {output}") print("------ End of Q1 ------") print() # Q2 Write a program that takes two numbers from the user, # and outputs the equation representing the multiplication of the two numbers. # 1 print("------ Start of Q2 ------") first_input = input("Enter a number: ") second_input = input("Enter another number: ") output = int(first_input) * int(second_input) print(f"{first_input} * {second_input} = {output}") print() print("Round 2...") print() # 2 first_input = input("Enter a number: ") second_input = input("Enter another number: ") output = int(first_input) * int(second_input) print(f"{first_input} * {second_input} = {output}") print() print("Round 3...") print() # 3 first_input = input("Enter a number: ") second_input = input("Enter another number: ") output = float(first_input) * int(second_input) print(f"{first_input} * {second_input} = {output}") print("------ End of Q2 ------") print() # Q3 Write a program that takes a distance in kilometers from the user, # and output the distance in meters andcentimeters. #1 print("------ Start of Q3 ------") kms = input("Enter kilometers to convert: ") meters = int(kms) * 1000 cms = int(kms) * 100000 print(f"{kms}km = {meters}m") print(f"{kms}km = {cms}cm") print() print("Round 2...") print() #2 kms = input("Enter kilometers to convert: ") meters = int(float(kms) * 1000) cms = int(float(kms) * 100000) print(f"{kms}km = {meters}m") print(f"{kms}km = {cms}cm") print("------ End of Q3 ------") print() # Q4 Write a program that takes the users name and height (in centimeters), # and outputs a summary sentence. #1 print("------ Start of Q4 ------") name = input("What is your name? ") print(f"Hi {name}!") height = input("How tall are you in centimeters? ") print(f"{name} is {height}cms tall") print() print("Round 2...") print() #2 name = input("What is your name? ") print(f"Hi {name}!") height = input("How tall are you in centimeters? ") print(f"{name} is {height}cms tall") print("------ End of Q4 ------")
c5d4faeb916bd51132f6f6681cbbb0f82ec2c6c6
hanyunxuan/leetcode
/953. Verifying an Alien Dictionary.py
2,237
4.03125
4
""" In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language. Example 1: Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. Example 2: Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. Example 3: Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info). """ words = ["hello","leetcode","ahhd"] order = "hlabcdefgijkmnopqrstuvwxyz" # my solution for i in range(len(words) - 1): word1 = words[i] word2 = words[i + 1] if len(word1) >= len(word2): for j in range(len(word1)): num1 = order.index(word1[j]) if j + 1 > len(word2): num2 = 0 else: num2 = order.index(word2[j]) if num1 > num2: print(False) elif num1 == num2: continue else: break else: for j in range(len(word2)): num2 = order.index(word2[j]) if j + 1 > len(word1): num1 = 0 else: num1 = order.index(word1[j]) if num1 > num2: print(False) elif num1 == num2: continue else: break print(True) # amazing solution order_dict={x:i for i,x in enumerate(order,1)} words=[[order_dict[w] for w in word]for word in words] return all(w1<=w2 for w1,w2 in zip(words,words[1:]))
02b27165d985f213f1798363061e576a4416cbbf
Swopnab/Simple_School_Assignments
/Assignment_!.py
5,549
4.15625
4
#sum of 2 integers a = int(input("enter a number")) b = int(input("enter a number")) c = a + b print(c) #sum,product,difference and quotient of 2 integers a = int(input("enter the greater number ")) b = int(input("enter the another number ")) c = a + b d = a * b e = a - b f = a // b print(f"the sum is {c} \nthe product is {d} \nthe difference is {e} \nthe quotient is {f}") #square and square root of any number a = int(input("enter a number ")) b = a ** 2 c = a ** (1. / 2.) print(f"the square is {b} \nthe square root is {c}") #cube and cube root of any number a = int(input("enter a number ")) b = a ** 3 c = a ** (1. / 3.) print(f"the cube is {b} \nthe cube root is {c}") #area and perimeter of a rectangle a = int(input("enter length ")) b = int(input("enter breadth ")) print(f"the area is {a * b} \nthe perimeter is {2 * (a + b)}") #volume of a sphere a = int(input("enter radius ")) print(f"the volume is {(4 / 3) * (3.14) * (a ** 3)}") #area and circumference of a circle r = int(input("enter radius ")) print(f"the area is {3.14 * r ** 2} \nthe circumference is {2 * 3.14 * r}") #distance between two points using distance formula a, b = input("enter the coordinates of a point ").split() c, d = input("enter the coordinates of another point ").split() a = int(a) b = int(b) c = int(c) d = int(d) print(f"the distance between the point is {((c - a) ** 2 + (d - b) ** 2) ** 1 / 2}") #roots of a quadratic equation import cmath print('ax2 + bx + c=0') x, y, z = input("enter the vaue of a ,b and c from the equation").split() a = float(x) b = float(y) c = float(z) d = (b ** 2) - (4 * a * c) x1 = (-b - cmath.sqrt(d)) / (2 * a) x2 = (-b + cmath.sqrt(d)) / (2 * a) print(f"the solution are {x1} and {x2}") #simple interest and amount of any principal amount p = int(input("enter principal ")) t = int(input("enter time ")) r = int(input("enter rate of interest ")) si = (p * t * r) / 100 sa = (si + p) print(f"the simple interest is {si} \nthe amount is {sa}") #area of a triangle using Heron’s formula a = int(input("enter first side of triangle ")) b = int(input("enter second side of triangle ")) c = int(input("enter third side of triangle ")) s = (a + b + c) / 2 ar = (((s * (s - a) * (s - b) * (s - c)) / (1. / 2.))) print(f"the area of triangle is {ar} ") #temperature in Celsius and convert into Fahrenheit c = int(input("enter celsius ")) f = ((c / (5 / 9)) + 32) print(f"the output is {f} ") #area of 4 walls.[A=2H(L+B)] l = int(input("enter lenght ")) b = int(input("enter breadth ")) h = int(input("enter height ")) ar = (2 * h) * (l + b) print(f"the area if 4 walls {ar}") # area of 4 walls and ceiling.[A=2H(L+B)+LB] l = int(input("enter lenght ")) b = int(input("enter breadth ")) h = int(input("enter height ")) ar = ((2 * h) * (l + b) + (l * b)) print(f"the area if 4 walls {ar}") #volume of hemisphere.[V=(2/3)πR3] r = int(input("enter radius ")) v = ((2 / 3) * (3.14) * (r ** 3)) print(f"the volume is {v}") #Nepali currency into Dollar and Indian Currency nrs = int(input("enter currency in nepali ")) usd = nrs / 115 ic = nrs * 1.6 print(f"the currency in us dollar is{usd} \nthe the currency in indian currency is {ic}") #cost price and selling price and calculate profit. [P=SP-CP] cp = int(input("enter cost price ")) sp = int(input("enter selling price ")) p = sp - cp print(f"the profit is {p}") #cost price and selling price and calculate profit percentage. [PP=((SP-CP)/CP)*100] cp = int(input("enter cost price ")) sp = int(input("enter selling price ")) pp = ((sp - cp) / cp) * 100 print(f"the profit percentage is {pp}") #cost price and selling price and calculate loss percentage.[LP=((CP-SP)/CP)*100] percentage.[LP = ((CP - SP) / CP) * 100] cp = int(input("enter cost price ")) sp = int(input("enter selling price ")) lp = ((cp - sp) / cp) * 100 print(f"the loss percent is {lp}") # distance.[S=UT+1/2(AT2)] u = int(input("enter initial velocity ")) a = int(input("enter acceleration ")) t = int(input("enter time taken ")) s = ((u * t) + (1. / 2.) * (a * (t ** 2))) print(f"the distance is {s}") #potential energy of body. [PE=MGH where G=9.8] G = 9.8] m = int(input("enter mass of the body ")) g = 9.8 h = int(input("enter height ")) pe = m * g * h print(f"the potential energy is {pe}") # selling price where profit percentage and cost price is given. [SP=CP(100+PROFIT%)/100] cp = int(input("enter cost price ")) pp = int(input("enter profit percent ")) sp = (cp * (100 + pp) / 100) print(f"the selling price is {sp} ") #time in seconds and convert into hours, minutes and seconds a = int(input("enter time in seconds ")) h = a // 3600 m = ((a // 60) - (h * 60)) s = a - ((h * 60 * 60) + (m * 60)) print(f"{h} hours \n {m} minutes \n {s} seconds ") #time in hours and convert into second and minutes h = float(input("enter time in hours ")) m = h * 60 s = h * 3600 print(f"the conversion on minutes is {m} \n and in seconds is {s}") #distance in kilometers and convert into metres and centimeters k = float(input("enter distance in kilometer ")) m = k * 1000 c = m * 100 print(f"the conversion in meter is {m} \n and in centimeter is {c}") #distance in meters and convert into kilometers and centimeters m = float(input("enter distance in meter ")) k = m / 1000 c = m * 100 print(f"the conversion in kilometer is {k} \n and in centimeter is {c}")
6b64290b07a81e68b6989a2c98c027ab8385e6be
HZ-8/BioInf
/Chapter 1/ApproximatePatternMatching.py
337
3.546875
4
import HammingDistance as HD def ApproximatePatternMatching(Pattern, Text, dist): '''Finds in Text all Patterns and similar patterns of distance <-dist''' pos = [] k = len(Pattern) for i in range(len(Text) - k + 1): if HD.HammingDistance(Text[i: i + k], Pattern) <= dist: pos.append(i) return pos
3bd6a5f71ead73c8f0a047e93eaf5f8442b7cd45
Adonyo-Emmanuel/DefeatTBUganda
/On-Time Flight Arrivals.py
27,015
3.796875
4
#!/usr/bin/env python # coding: utf-8 # You can create additional projects and notebooks as you work with Azure Notebooks. You can create notebooks from scratch, or you can upload existing notebooks. # # Jupyter notebooks are highly interactive, and since they can include executable code, they provide the perfect platform for manipulating data and building predictive models from it. # # Enter the following command into the first cell of the notebook: # In[2]: get_ipython().system(u'curl https://topcs.blob.core.windows.net/public/FlightData.csv -o flightdata.csv') # In[3]: import pandas as pd df = pd.read_csv('flightdata.csv') df.head() # ### Clean and prepare data # Before you can prepare a dataset, you need to understand its content and structure. In the previous lab, you imported a dataset containing on-time arrival information for a major U.S. airline. That data included 26 columns and thousands of rows, with each row representing one flight and containing information such as the flight's origin, destination, and scheduled departure time. You also loaded the data into a Jupyter notebook and used a simple Python script to create a Pandas DataFrame from it. # # A DataFrame is a two-dimensional labeled data structure. The columns in a DataFrame can be of different types, just like columns in a spreadsheet or database table. It is the most commonly used object in Pandas. In this exercise, you will examine the DataFrame — and the data inside it — more closely. # In[4]: df.shape Getting a row and column count Now take a moment to examine the 26 columns in the dataset. They contain important information such as the date that the flight took place (YEAR, MONTH, and DAY_OF_MONTH), the origin and destination (ORIGIN and DEST), the scheduled departure and arrival times (CRS_DEP_TIME and CRS_ARR_TIME), the difference between the scheduled arrival time and the actual arrival time in minutes (ARR_DELAY), and whether the flight was late by 15 minutes or more (ARR_DEL15). Here is a complete list of the columns in the dataset. Times are expressed in 24-hour military time. For example, 1130 equals 11:30 a.m. and 1500 equals 3:00 p.m. TABLE 1 Column Description YEAR Year that the flight took place QUARTER Quarter that the flight took place (1-4) MONTH Month that the flight took place (1-12) DAY_OF_MONTH Day of the month that the flight took place (1-31) DAY_OF_WEEK Day of the week that the flight took place (1=Monday, 2=Tuesday, etc.) UNIQUE_CARRIER Airline carrier code (e.g., DL) TAIL_NUM Aircraft tail number FL_NUM Flight number ORIGIN_AIRPORT_ID ID of the airport of origin ORIGIN Origin airport code (ATL, DFW, SEA, etc.) DEST_AIRPORT_ID ID of the destination airport DEST Destination airport code (ATL, DFW, SEA, etc.) CRS_DEP_TIME Scheduled departure time DEP_TIME Actual departure time DEP_DELAY Number of minutes departure was delayed DEP_DEL15 0=Departure delayed less than 15 minutes, 1=Departure delayed 15 minutes or more CRS_ARR_TIME Scheduled arrival time ARR_TIME Actual arrival time ARR_DELAY Number of minutes flight arrived late ARR_DEL15 0=Arrived less than 15 minutes late, 1=Arrived 15 minutes or more late CANCELLED 0=Flight was not cancelled, 1=Flight was cancelled DIVERTED 0=Flight was not diverted, 1=Flight was diverted CRS_ELAPSED_TIME Scheduled flight time in minutes ACTUAL_ELAPSED_TIME Actual flight time in minutes DISTANCE Distance traveled in miles The dataset includes a roughly even distribution of dates throughout the year, which is important because a flight out of Minneapolis is less likely to be delayed due to winter storms in July than it is in January. But this dataset is far from being "clean" and ready to use. Let's write some Pandas code to clean it up. One of the most important aspects of preparing a dataset for use in machine learning is selecting the "feature" columns that are relevant to the outcome you are trying to predict while filtering out columns that do not affect the outcome, could bias it in a negative way, or might produce multicollinearity. Another important task is to eliminate missing values, either by deleting the rows or columns containing them or replacing them with meaningful values. In this exercise, you will eliminate extraneous columns and replace missing values in the remaining columns. # One of the first things data scientists typically look for in a dataset is missing values. There's an easy way to check for missing values in Pandas. To demonstrate, execute the following code in a cell at the end of the notebook: # In[5]: df.isnull().values.any() # #### Checking for missing values # ##### The next step is to find out where the missing values are. To do so, execute the following code: # In[6]: df.isnull().sum() # Number of missing values in each column # # Curiously, the 26th column ("Unnamed: 25") contains 11,231 missing values, which equals the number of rows in the dataset. This column was mistakenly created because the CSV file that you imported contains a comma at the end of each line. To eliminate that column, add the following code to the notebook and execute it: # In[7]: df = df.drop('Unnamed: 25', axis=1) df.isnull().sum() # The DataFrame with column 26 removed # # The DataFrame still contains a lot of missing values, but some of them aren't useful because the columns containing them are not relevant to the model that you are building. The goal of that model is to predict whether a flight you are considering booking is likely to arrive on time. If you know that the flight is likely to be late, you might choose to book another flight. # # The next step, therefore, is to filter the dataset to eliminate columns that aren't relevant to a predictive model. For example, the aircraft's tail number probably has little bearing on whether a flight will arrive on time, and at the time you book a ticket, you have no way of knowing whether a flight will be cancelled, diverted, or delayed. By contrast, the scheduled departure time could have a lot to do with on-time arrivals. Because of the hub-and-spoke system used by most airlines, morning flights tend to be on time more often than afternoon or evening flights. And at some major airports, traffic stacks up during the day, increasing the likelihood that later flights will be delayed. # # Pandas provides an easy way to filter out columns you don't want. Execute the following code in a new cell at the end of the notebook: # In[8]: df = df[["MONTH", "DAY_OF_MONTH", "DAY_OF_WEEK", "ORIGIN", "DEST", "CRS_DEP_TIME", "ARR_DEL15"]] df.isnull().sum() # The output shows that the DataFrame now includes only the columns that are relevant to the model, and that the number of missing values is greatly reduced: The only column that now contains missing values is the ARR_DEL15 column, which uses 0s to identify flights that arrived on time and 1s for flights that didn't. Use the following code to show the first five rows with missing values: # In[9]: df[df.isnull().values.any(axis=1)].head() # The reason these rows are missing ARR_DEL15 values is that they all correspond to flights that were canceled or diverted. You could call dropna on the DataFrame to remove these rows. But since a flight that is canceled or diverted to another airport could be considered "late," let's use the fillna method to replace the missing values with 1s. # # Use the following code to replace missing values in the ARR_DEL15 column with 1s and display rows 177 through 184: # In[10]: df = df.fillna({'ARR_DEL15': 1}) df.iloc[177:185] # The dataset is now "clean" in the sense that missing values have been replaced and the list of columns has been narrowed to those most relevant to the model. But you're not finished yet. There is more to do to prepare the dataset for use in machine learning. # # The CRS_DEP_TIME column of the dataset you are using represents scheduled departure times. The granularity of the numbers in this column — it contains more than 500 unique values — could have a negative impact on accuracy in a machine-learning model. This can be resolved using a technique called binning or quantization. What if you divided each number in this column by 100 and rounded down to the nearest integer? 1030 would become 10, 1925 would become 19, and so on, and you would be left with a maximum of 24 discrete values in this column. Intuitively, it makes sense, because it probably doesn't matter much whether a flight leaves at 10:30 a.m. or 10:40 a.m. It matters a great deal whether it leaves at 10:30 a.m. or 5:30 p.m. # # In addition, the dataset's ORIGIN and DEST columns contain airport codes that represent categorical machine-learning values. These columns need to be converted into discrete columns containing indicator variables, sometimes known as "dummy" variables. In other words, the ORIGIN column, which contains five airport codes, needs to be converted into five columns, one per airport, with each column containing 1s and 0s indicating whether a flight originated at the airport that the column represents. The DEST column needs to be handled in a similar manner. # In this exercise, you will "bin" the departure times in the CRS_DEP_TIME column and use Pandas' get_dummies method to create indicator columns from the ORIGIN and DEST columns. # # Use the following command to display the first five rows of the DataFrame: # In[11]: df.head() # The DataFrame with unbinned departure times # # Use the following statements to bin the departure times: # In[12]: import math for index, row in df.iterrows(): df.loc[index, 'CRS_DEP_TIME'] = math.floor(row['CRS_DEP_TIME'] / 100) df.head() Confirm that the numbers in the CRS_DEP_TIME column now fall in the range 0 to 23:The DataFrame with binned departure times Now use the following statements to generate indicator columns from the ORIGIN and DEST columns, while dropping the ORIGIN and DEST columns themselves: # In[13]: df = pd.get_dummies(df, columns=['ORIGIN', 'DEST']) df.head() The DataFrame with indicator columns Use the File -&gt; Save and Checkpoint command to save the notebook. The dataset looks very different than it did at the start, but it is now optimized for use in machine learning. # ### Build Machine Learning Model # To create a machine learning model, you need two datasets: one for training and one for testing. In practice, you often have only one dataset, so you split it into two. In this exercise, you will perform an 80-20 split on the DataFrame you prepared in the previous lab so you can use it to train a machine learning model. You will also separate the DataFrame into feature columns and label columns. The former contains the columns used as input to the model (for example, the flight's origin and destination and the scheduled departure time), while the latter contains the column that the model will attempt to predict — in this case, the ARR_DEL15 column, which indicates whether a flight will arrive on time. # # Switch back to the Azure notebook that you created in the previous section. If you closed the notebook, you can sign back into the Microsoft Azure Notebooks portal , open your notebook, and use the Cell -&gt; Run All to rerun the all of the cells in the notebook after opening it. # # In a new cell at the end of the notebook, enter and execute the following statements: # In[14]: from sklearn.model_selection import train_test_split train_x, test_x, train_y, test_y = train_test_split(df.drop('ARR_DEL15', axis=1), df['ARR_DEL15'], test_size=0.2, random_state=42) # The first statement imports scikit-learn's train_test_split helper function. The second line uses the function to split the DataFrame into a training set containing 80% of the original data, and a test set containing the remaining 20%. The random_state parameter seeds the random-number generator used to do the splitting, while the first and second parameters are DataFrames containing the feature columns and the label column. # # train_test_split returns four DataFrames. Use the following command to display the number of rows and columns in the DataFrame containing the feature columns used for training: # In[15]: train_x.shape Now use this command to display the number of rows and columns in the DataFrame containing the feature columns used for testing: # In[16]: test_x.shape How do the two outputs differ, and why? Can you predict what you would see if you called shape on the other two DataFrames, train_y and test_y? If you're not sure, try it and find out. # In[17]: train_y.shape # In[18]: train_x.shape # There are many types of machine learning models. One of the most common is the regression model, which uses one of a number of regression algorithms to produce a numeric value — for example, a person's age or the probability that a credit-card transaction is fraudulent. You'll train a classification model, which seeks to resolve a set of inputs into one of a set of known outputs. A classic example of a classification model is one that examines e-mails and classifies them as "spam" or "not spam." Your model will be a binary classification model that predicts whether a flight will arrive on-time or late ("binary" because there are only two possible outputs). # # One of the benefits of using scikit-learn is that you don't have to build these models — or implement the algorithms that they use — by hand. Scikit-learn includes a variety of classes for implementing common machine learning models. One of them is RandomForestClassifier, which fits multiple decision trees to the data and uses averaging to boost the overall accuracy and limit overfitting. # Execute the following code in a new cell to create a RandomForestClassifier object and train it by calling the fit method. # In[20]: from sklearn.ensemble import RandomForestClassifier model = RandomForestClassifier(random_state=13) model.fit(train_x, train_y) # Training the model Now call the predict method to test the model using the values in test_x, followed by the score method to determine the mean accuracy of the model: # In[21]: predicted = model.predict(test_x) model.score(test_x, test_y) # Testing the model # # The mean accuracy is 86%, which seems good on the surface. However, mean accuracy isn't always a reliable indicator of the accuracy of a classification model. Let's dig a little deeper and determine how accurate the model really is — that is, how adept it is at determining whether a flight will arrive on time. # There are several ways to measure the accuracy of a classification model. One of the best overall measures for a binary classification model is Area Under Receiver Operating Characteristic Curve (sometimes referred to as "ROC AUC"), which essentially quantifies how often the model will make a correct prediction regardless of the outcome. In this unit, you'll compute an ROC AUC score for the model you built previously and learn about some of the reasons why that score is lower than the mean accuracy output by the score method. You'll also learn about other ways to gauge the accuracy of the model. # # Before you compute the ROC AUC, you must generate prediction probabilities for the test set. These probabilities are estimates for each of the classes, or answers, the model can predict. For example, [0.88199435, 0.11800565] means that there's an 89% chance that a flight will arrive on time (ARR_DEL15 = 0) and a 12% chance that it won't (ARR_DEL15 = 1). The sum of the two probabilities adds up to 100%. Run the following code to generate a set of prediction probabilities from the test data: # In[23]: from sklearn.metrics import roc_auc_score probabilities = model.predict_proba(test_x) Now use the following statement to generate an ROC AUC score from the probabilities using scikit-learn's roc_auc_score method: # In[24]: roc_auc_score(test_y, probabilities[:, 1]) # Generating an AUC score - 67% # # Why is the AUC score lower than the mean accuracy computed in the previous exercise? # # The output from the score method reflects how many of the items in the test set the model predicted correctly. This score is skewed by the fact that the dataset the model was trained and tested with contains many more rows representing on-time arrivals than rows representing late arrivals. Because of this imbalance in the data, you're more likely to be correct if you predict that a flight will be on time than if you predict that a flight will be late. # # ROC AUC takes this into account and provides a more accurate indication of how likely it is that a prediction of on-time or late will be correct. # # You can learn more about the model's behavior by generating a confusion matrix, also known as an error matrix. The confusion matrix quantifies the number of times each answer was classified correctly or incorrectly. Specifically, it quantifies the number of false positives, false negatives, true positives, and true negatives. This is important, because if a binary classification model trained to recognize cats and dogs is tested with a dataset that is 95% dogs, it could score 95% simply by guessing "dog" every time. But if it failed to identify cats at all, it would be of little value. # # Use the following code to produce a confusion matrix for your model: # In[25]: from sklearn.metrics import confusion_matrix confusion_matrix(test_y, predicted) # Generating a confusion matrix # # But look at the second row, which represents flights that were delayed. The first column shows how many delayed flights were incorrectly predicted to be on time. The second column shows how many flights were correctly predicted to be delayed. Clearly, the model isn't nearly as adept at predicting that a flight will be delayed as it is at predicting that a flight will arrive on time. What you want in a confusion matrix is large numbers in the upper-left and lower-right corners, and small numbers (preferably zeros) in the upper-right and lower-left corners. # # Other measures of accuracy for a classification model include precision and recall. Suppose the model was presented with three on-time arrivals and three delayed arrivals, and that it correctly predicted two of the on-time arrivals, but incorrectly predicted that two of the delayed arrivals would be on time. In this case, the precision would be 50% (two of the four flights it classified as being on time actually were on time), while its recall would be 67% (it correctly identified two of the three on-time arrivals). You can learn more about precision and recall from https://en.wikipedia.org/wiki/Precision_and_recall # # Scikit-learn contains a handy method named precision_score for computing precision. To quantify the precision of your model, execute the following statements: # In[26]: from sklearn.metrics import precision_score train_predictions = model.predict(train_x) precision_score(train_y, train_predictions) Examine the output. What is your model's precision? -99%Measuring precision Scikit-learn also contains a method named recall_score for computing recall. To measure you model's recall, execute the following statements: # In[27]: from sklearn.metrics import recall_score recall_score(train_y, train_predictions) What is the model's recall? - 86% # Use the File -&gt; Save and Checkpoint command to save the notebook. # # In the real world, a trained data scientist would look for ways to make the model even more accurate. Among other things, they would try different algorithms and take steps to tune the chosen algorithm to find the optimum combination of parameters. Another likely step would be to expand the dataset to millions of rows rather than a few thousand and also attempt to reduce the imbalance between late and on-time arrivals. But for our purposes, the model is fine as-is. # ### Visualize Output of Model # # In this unit, you'll import Matplotlib into the notebook you've been working with and configure the notebook to support inline Matplotlib output. # # 1. Switch back to the Azure notebook that you created in the previous section. If you closed the notebook, you can sign back into the Microsoft Azure Notebooks portal , open your notebook, and use the Cell -&gt; Run All to rerun the all of the cells in the notebook after opening it. # # 2. Execute the following statements in a new cell at the end of the notebook. Ignore any warning messages that are displayed related to font caching: # In[28]: get_ipython().magic(u'matplotlib inline') import matplotlib.pyplot as plt import seaborn as sns sns.set() # The first statement is one of several magic commands supported by the Python kernel that you selected when you created the notebook. It enables Jupyter to render Matplotlib output in a notebook without making repeated calls to show. And it must appear before any references to Matplotlib itself. The final statement configures Seaborn to enhance the output from Matplotlib. # # 3. To see Matplotlib at work, execute the following code in a new cell to plot the ROC curve for the machine-learning model you built in the previous lab: # In[29]: from sklearn.metrics import roc_curve fpr, tpr, _ = roc_curve(test_y, probabilities[:, 1]) plt.plot(fpr, tpr) plt.plot([0, 1], [0, 1], color='grey', lw=1, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') # ROC curve generated with Matplotlib # # The dotted line in the middle of the graph represents a 50-50 chance of obtaining a correct answer. The blue curve represents the accuracy of your model. More importantly, the fact that this chart appears at all demonstrates that you can use Matplotlib in a Jupyter notebook. # # The reason you built a machine-learning model is to predict whether a flight will arrive on time or late. In this exercise, you'll write a Python function that calls the machine-learning model you built in the previous lab to compute the likelihood that a flight will be on time. Then you'll use the function to analyze several flights. # # Enter the following function definition in a new cell, and then run the cell. # In[30]: def predict_delay(departure_date_time, origin, destination): from datetime import datetime try: departure_date_time_parsed = datetime.strptime(departure_date_time, '%d/%m/%Y %H:%M:%S') except ValueError as e: return 'Error parsing date/time - {}'.format(e) month = departure_date_time_parsed.month day = departure_date_time_parsed.day day_of_week = departure_date_time_parsed.isoweekday() hour = departure_date_time_parsed.hour origin = origin.upper() destination = destination.upper() input = [{'MONTH': month, 'DAY': day, 'DAY_OF_WEEK': day_of_week, 'CRS_DEP_TIME': hour, 'ORIGIN_ATL': 1 if origin == 'ATL' else 0, 'ORIGIN_DTW': 1 if origin == 'DTW' else 0, 'ORIGIN_JFK': 1 if origin == 'JFK' else 0, 'ORIGIN_MSP': 1 if origin == 'MSP' else 0, 'ORIGIN_SEA': 1 if origin == 'SEA' else 0, 'DEST_ATL': 1 if destination == 'ATL' else 0, 'DEST_DTW': 1 if destination == 'DTW' else 0, 'DEST_JFK': 1 if destination == 'JFK' else 0, 'DEST_MSP': 1 if destination == 'MSP' else 0, 'DEST_SEA': 1 if destination == 'SEA' else 0 }] return model.predict_proba(pd.DataFrame(input))[0][0] # This function takes as input a date and time, an origin airport code, and a destination airport code, and returns a value between 0.0 and 1.0 indicating the probability that the flight will arrive at its destination on time. It uses the machine-learning model you built in the previous lab to compute the probability. And to call the model, it passes a DataFrame containing the input values to predict_proba. The structure of the DataFrame exactly matches the structure of the DataFrame we used earlier. # Note: Date input to the predict_delay function use the international date format dd/mm/year. # # 2. Use the code below to compute the probability that a flight from New York to Atlanta on the evening of October 1 will arrive on time. The year you enter is irrelevant because it isn't used by the model. # In[31]: predict_delay('1/10/2018 21:45:00', 'JFK', 'ATL') # Predicting whether a flight will arrive on time # # 3. Modify the code to compute the probability that the same flight a day later will arrive on time: # In[32]: predict_delay('2/10/2018 21:45:00', 'JFK', 'ATL') # How likely is this flight to arrive on time? If your travel plans were flexible, would you consider postponing your trip for one day? # # 4. Now modify the code to compute the probability that a morning flight the same day from Atlanta to Seattle will arrive on time: # In[33]: predict_delay('2/10/2018 10:00:00', 'ATL', 'SEA') # Is this flight likely to arrive on time? # # You now have an easy way to predict, with a single line of code, whether a flight is likely to be on time or late. Feel free to experiment with other dates, times, origins, and destinations. But keep in mind that the results are only meaningful for the airport codes ATL, DTW, JFK, MSP, and SEA because those are the only airport codes the model was trained with. # # 4. Execute the following code to plot the probability of on-time arrivals for an evening flight from JFK to ATL over a range of days: # In[34]: import numpy as np labels = ('Oct 1', 'Oct 2', 'Oct 3', 'Oct 4', 'Oct 5', 'Oct 6', 'Oct 7') values = (predict_delay('1/10/2018 21:45:00', 'JFK', 'ATL'), predict_delay('2/10/2018 21:45:00', 'JFK', 'ATL'), predict_delay('3/10/2018 21:45:00', 'JFK', 'ATL'), predict_delay('4/10/2018 21:45:00', 'JFK', 'ATL'), predict_delay('5/10/2018 21:45:00', 'JFK', 'ATL'), predict_delay('6/10/2018 21:45:00', 'JFK', 'ATL'), predict_delay('7/10/2018 21:45:00', 'JFK', 'ATL')) alabels = np.arange(len(labels)) plt.bar(alabels, values, align='center', alpha=0.5) plt.xticks(alabels, labels) plt.ylabel('Probability of On-Time Arrival') plt.ylim((0.0, 1.0)) # Probability of on-time arrivals for a range of dates # # 3. Modify the code to produce a similar chart for flights leaving JFK for MSP at 1:00 p.m. on April 10 through April 16. How does the output compare to the output in the previous step? # # 4. On your own, write code to graph the probability that flights leaving SEA for ATL at 9:00 a.m., noon, 3:00 p.m., 6:00 p.m., and 9:00 p.m. on January 30 will arrive on time. Confirm that the output matches this: # # # Probability of on-time arrivals for a range of times # # If you are new to Matplotlib and would like to learn more about it, you will find an excellent tutorial at https://www.labri.fr/perso/nrougier/teaching/matplotlib/. There is much more to Matplotlib than what was shown here, which is one reason why it is so popular in the Python community.
bf934d4d093bc41824cb9e8d4ffa4187937151e0
cvijayarenu/programming
/euler/26.py
509
3.828125
4
def get_longest_recurring_cycle(max): curr_max = (0,0) for i in range(2, max): frac = get_franction(i) if frac > curr_max[0]: curr_max = (i, frac) return curr_max[0] def get_franction(num): fraction = [] divisor = 10 while divisor not in fraction: fraction.append(divisor) divisor = (divisor % num) * 10 if divisor in fraction or divisor == 0: break return len(fraction) print get_longest_recurring_cycle(1000)
f8f0f8aaaa597ff0a7b7838b3cb5b0a20a387eec
anversa-pro/ejerciciosPython
/tuplas.py
1,268
4.34375
4
#usr/bin/python # -*- coding: utf-8 -*- print("""Las tuplas son similares a las listas, pero no se pueden modificar despues de creadas, son inmutables. se crean separando por (,) los elementos que las componen """) print("") tupla = "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "septiembre", "Octubre", "Noviembre", "Diciembre" print(tupla) print("""Para distinguir una tupla constituida por un solo elemento de una variable, se debe poner una coma detrás de ese elemento""") print("") variable = 1 tupla_un_elemento = 1, print(tupla_un_elemento) print(type(tupla_un_elemento)) print(variable) print(type(variable)) print("""Por buenas practivas se recomienda usar parentesis al escribir una tupla, esto ayuda a que el codigo sea muchoa mas legible""") print("") tupla = ("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "septiembre", "Octubre", "Noviembre", "Diciembre") print("") print("""Para aceder a la tupla se usa los corchetes indicando la posicion""") print("") print(tupla[3]) # muestra Abril print(tupla[3:6]) # muestra Abril, Mayo; Junio print(tupla[:6]) # Imprime desde Enero a Junio print(tupla[6:]) # Imprime desde Julio a diciembre print(tupla[::2]) # Imprime los meses de dos en dos
b7b42b80baed08111777b0e58826b7d65a41061a
nathanliu1/PyMongoWorkshop
/finishedCode.py
2,853
3.921875
4
import pymongo import sys from pymongo import MongoClient def enterOneEntry(): title = input("Enter the task title: ") finished = input("Is your task finished? ") if finished.lower() == "yes" : finished = True else: finished = False importance = input("How important is this task (1-10)") entry = {"title": title, "done": finished, "importance": importance} result = collection.insert_one(entry) print("Your entry was successfully added!") print(result) def findOneEntry(): label = input("Enter the field to search in: ") search = input("Enter the value to search for: ") result = collection.find_one({label:search}) print(result) def findAllEntries(): label = input("Enter the field to search in: ") search = input("Enter the value to search for: ") for entry in collection.find({label:search}): print(entry) def countAllEntries(): label = input("Enter the field to search in: ") search = input("Enter the value to search for: ") result = collection.find({label:search}).count() print("There are " + result + "entries matching the search criteria") def deleteOneEntry(): label = input("Enter the field to search in: ") search = input("Enter the value to search for: ") result = collection.delete_one({label:search}) print("Your entry was successfully deleted!") print(result) def showAllEntries(): if collection.find().count() < 1: print("Your collection is empty") else: for entry in collection.find(): print(entry) def entryNotUnderstood(): print("I don't recognize your input, please reenter your selection") print("Press any button to continue") def findOption(selection): try: return {"1" : enterOneEntry,"2" : findOneEntry,"3" : findAllEntries, "4" : countAllEntries, "5" : deleteOneEntry, "6" : showAllEntries}[selection] except KeyError: return entryNotUnderstood def main(argv): while True: print('\n') print("Welcome to our MongoDB Workshop. Please select an option") print ('-'*60) print("(1) Enter an entry into our database") print("(2) Query our database for an entry") print("(3) Query our database for multiple entries") print("(4) Query our database for a count of entries") print("(5) Remove one entry from our database") print("(6) List all entries from our database") print ('-'*60) selection = input() findOption(selection)() input() if __name__ == "__main__": client = MongoClient('insert database connection name here') db = client.testdatabase collection = db.tasks main(sys.argv)
290cbc3479348741d4f7bce9a3d634c5a7c9e274
alex-dukhno/python-tdd-katas
/old-katas/roman-numbers/day-6.py
1,213
3.5625
4
# -*- codeing: utf-8 -*- class Converter(object): def __init__(self): self.factors = {10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"} def convert(self, n): if n < 1: return "" arabic = sorted(list(filter(lambda e: e <= n, self.factors)))[-1] roman = self.factors.get(arabic) return roman + self.convert(n - arabic) import unittest class RomanNumberTest(unittest.TestCase): def setUp(self): self.converter = Converter() def test_converts_0(self): self.assertEqual("", self.converter.convert(0)) def test_converts_1(self): self.assertEqual("I", self.converter.convert(1)) def test_converts_5(self): self.assertEqual("V", self.converter.convert(5)) def test_converts_2(self): self.assertEqual("II", self.converter.convert(2)) def test_converts_4(self): self.assertEqual("IV", self.converter.convert(4)) def test_converts_10(self): self.assertEqual("X", self.converter.convert(10)) def test_converts_9(self): self.assertEqual("IX", self.converter.convert(9)) def test_converts_29(self): self.assertEqual("XXIX", self.converter.convert(29))
e971bd3a15e00da85a7f555b21ffb98a61cabf46
NahusenayH/ComptetiveProgramming
/take1/CD13/LinkedListComponents.py
484
3.546875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def numComponents(self, head: ListNode, G: List[int]) -> int: consCount = 0 temp = head G = set(G) print(G) while temp: if temp.val in G and (not temp.next or temp.next.val not in G): consCount += 1 temp = temp.next return consCount
89c472fad97cefe27f7ad23c3304c69f03b28bab
xblh2018/LeetcodePython
/spiral_matrix.py
2,120
4.21875
4
#!/usr/bin/env python ''' http://leetcode.com/2010/05/printing-matrix-in-spiral-order.html ''' from __future__ import division import random ''' Leetcode: Spiral Matrix Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. ''' # Each circle starts at (i,i) # (i,i) -----> (i,m-1-i) # ^ | # | v # (n-1-i,i) <--- (n-1-i,m-1-i) def spiral_matrix_traversal(M): rets = [] m = len(M); n = len(M[0]) for i in range(min(m,n)//2): # starting point (i,i) x,y = i,i # Those -1 or +1 are tricky; avoid duplication for y in range(i,n-i): rets.append(M[x][y]) for x in range(i+1,m-i): rets.append(M[x][y]) for y in reversed(range(i,n-i-1)): rets.append(M[x][y]) for x in reversed(range(i+1,m-i-1)): rets.append(M[x][y]) print rets return rets ''' Leetcode: Spiral Matrix II Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] ''' def spiral_matrix_print(n): # initialize M = [[0 for j in range(n)] for i in range(n)] cur = 1 for i in range(n//2+1): # starting point (i,i) x,y = i,i # Those -1 or +1 are tricky; avoid duplication for y in range(i,n-i): M[x][y] = cur; cur += 1 for x in range(i+1,n-i): M[x][y] = cur; cur += 1 for y in reversed(range(i,n-i-1)): M[x][y] = cur; cur += 1 for x in reversed(range(i+1,n-i-1)): M[x][y] = cur; cur += 1 print '\n'.join(map(str,M)), '\n' return M if __name__ == '__main__': M = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]] #print '\n'.join(map(str,M)) #spiral_matrix_traversal(M) spiral_matrix_print(3) spiral_matrix_print(5) spiral_matrix_print(6)
0fff9ab315ad17391aa172fab7b211532d4df205
ulitol97/Ejercicios-POO
/Ejercicios Python/2-Advanced Python Exercises/Exercise3/tree_set.py
2,864
3.796875
4
class Person: """Sample person class""" def __init__(self, name, surname, age=18, dni='1234567V'): self.name = name self.surname = surname self.age = age self.dni = dni def compare_to(self, person): if not (self.surname == person.surname): if self.surname >= person.surname: return 1 else: return -1 else: if self.name >= person.name: return 1 else: return -1 class TreeSet: """My TreeSet implementation""" def __init__(self, comparator=None): self.contents = [] # Implemented as an array for simplicity self.comparator = comparator def add(self, person): if len(self.contents) == 0: self.contents.append(person) return # No specific comparator if self.comparator is None: for i in range(0, len(self.contents)): if person.compare_to(self.contents[i]) == -1: self.contents.insert(i, person) return else: self.contents.append(person) else: for i in range(0, len(self.contents)): if self.comparator.compare(person, self.contents[i]) == -1: self.contents.insert(i, person) return else: self.contents.append(person) def __str__(self): ret = "[" for p in self.contents: ret += "[{0}]".format(p.name) return ret + "]" class ComparatorDNI: """A comparator by DNI for the TreeSet to use""" def compare(self, person1, person2): if person1.dni >= person2.dni: return 1 else: return -1 class ComparatorAge: """A comparator by age for the TreeSet to use""" def compare(self, person1, person2): if person1.age >= person2.age: return 1 else: return -1 if __name__ == '__main__': """Sample main to test the functionality of the TreeSet with each comparator""" tree_set = TreeSet() # Standard tree set tree_set_dni = TreeSet(ComparatorDNI()) # Tree set comparing by DNI tree_set_age = TreeSet(ComparatorAge()) # Tree set comparing by age p1 = Person("Edu", "A", 70, "251436") p2 = Person("Alex", "B", 28, "251427") p3 = Person("Marcial", "C", 15, "251851") tree_set.add(p1) tree_set.add(p2) tree_set.add(p3) tree_set_dni.add(p1) tree_set_dni.add(p2) tree_set_dni.add(p3) tree_set_age.add(p1) tree_set_age.add(p2) tree_set_age.add(p3) print("\nComparison by Surname-Name") print(tree_set) print("\nComparison by Age") print(tree_set_age) print("\nComparison by DNI") print(tree_set_dni)
630f75d226b2c2bc8443d91de13a2376001c3115
adamjralph/expenses
/expenses.py
3,081
3.875
4
from datetime import date import ast def read_data(): try: with open('expense_data.txt', 'r') as f: data = f.read() data_dict = ast.literal_eval(data) return data_dict except FileNotFoundError: open('expense_data.txt', 'w') data_dict = {} return data_dict except SyntaxError: print('Dictionary is empty!') data_dict = {} return data_dict def create_id(data): # Do i need the id_num or can I just use max_id as is? id_num = 0 if data: max_id = max(k for k, v in data.items()) id_num = max_id return id_num else: return id_num def add_item(): while True: name = str(input('Please enter item name: ')) if len(name) > 10: print('Item name must not be longer than 10 characters. \nPlease try again.') else: return name def add_price(): while True: try: price = float(input('Please enter price: ')) return price except: print('Please enter a numberical value.') def add_category(): while True: category = input('Please enter category: ') if len(category) > 10: print('Category name must not be longer than 10 characters. \nPlease try again.') else: return category def add_date(): print('Date of purchase.') while True: choose_date = input("Type 't' for today's date or 'd' to enter date manually. ") if choose_date.lower() == 't': return date.today().strftime('%Y-%m-%d') elif choose_date.lower() == 'd': year = date_item('Year', 4, 'four') month = date_item('Month', 2, 'two') day = date_item('Day', 2, 'two') return f'{year}-{month}-{day}' else: print("Please enter 't' or 'd'") def date_item(ymd, length, str_len): while True: enter_ymd = input(f'Please enter {ymd}: ') try: int(enter_ymd) except ValueError: print(f'Please enter {str_len} digits only.') if len(enter_ymd) != length: print(f'{ymd} must be {str_len} digits.') else: return enter_ymd def create_entry(data): new_id = create_id(data) entry_list = [add_item(), add_price(), add_category(), add_date()] data[new_id + 1] = entry_list def write_dict(data_dict): data_file = open('expense_data.txt', 'w') data_file.write(str(data_dict)) print('Data written to file.') data_file.close() def session_on(data): while True: session = input("To enter a new expense please type 'e' or to quit type 'q': ") if session.lower() == 'q': write_dict(data) print('Session ended. Goodbye!') break elif session.lower() == 'e': create_entry(data) else: print("Please enter 'e' or 'q'") data = read_data() session_on(data)
790c73ee101ab0c540cd02996679e736a1b4deee
tianwei1992/socket_python
/liaoxuefeng/echo_tcp_server.py
2,948
3.546875
4
""" 服务器进程首先要绑定一个端口并监听来自其他客户端的连接。如果某个客户端连接过来了,服务器就与该客户端建立Socket连接,随后的通信就靠这个Socket连接了。 """ import socket import threading import time #这个server是最基础的:它接收客户端连接,把客户端发过来的字符串加上Hello再发回去。 #1创建socket #其中,参数AF_INET指定使用IPv4协议,如果要用更先进的IPv6,就指定为AF_INET6。SOCK_STREAM指定使用面向流的TCP协议 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) """ client的第二步是建立连接,server则是绑定ip和端口,然后监听这个连接 """ #2绑定提供服务的ip+port,并开始listen #server有多块网卡,可以绑定其中某一块网卡的IP,也可以用0.0.0.0绑定所有,还可以用127.0.0.1绑定到本机地址,如果绑定127.0.0.1,客户端必须同时在本机运行才能连接,也就是说,外部的计算机无法连接进来。 s.bind(('127.0.0.1', 10000)) s.listen(5) print('Waiting for connection...') #3监听到客户端连接请求,给与响应 def tcplink(sock, addr): #print(sock)#<socket.socket fd=196, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 10000), raddr=('127.0.0.1', 49272)> #print(addr)#('127.0.0.1', 49272) #这里的响应行为是:1先发送"Welcome!" 2再根据收到的data发送'Hello'+data print('Accept new connection from %s:%s...' % addr)#Accept new connection from 127.0.0.1:49239... sock.send(b"Welcome!") while True: data = sock.recv(1024) time.sleep(1) if not data or data.decode('utf-8') == 'exit': break #拿到data,先按utf8解码,再修改,修改后按utf8编码编码,再发送 sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8')) sock.close() print('Connection from %s:%s closed.' % addr) while True: # (1)accept()会等待并返回一个客户端的连接: sock, addr = s.accept() # (2)创建新线程来处理TCP连接: #创建新线程时,有两个参数target和args,target是响应行为,args是客户端的sock和源信息,也会作为参数传给target t = threading.Thread(target=tcplink, args=(sock, addr)) t.start() # (3)定义具体的响应行为,即tcplink的实现 """ 注意到: 字符串都是byte类型而不是str类型,然后实际传输的数据都是经过utf8编码的数据,这意味着发送前要对字符串按utf8编码,接收后第一件事情是按utf8解码 再次,关于编码解码的必要性:换行符经过utf8编码后是\r\n,可以想想如果不经过编码按原始的来,这个换行要怎么传输?所以传输都是经过编码的!当客户端收到\r\n,并不表示服务端表达的是\r\n,可以理解为\r\n类似于密文,绝对不是字面意思。需要经过解码,得到服务端想表达的是换行符! """
ce4e241cb68b3d724a610214a445095905bcedef
Jonathan-aguilar/DAS_Sistemas
/Ago-Dic-2019/Luis Llanes/Practica1/ejercicio7-4.py
348
3.9375
4
print("Por favor, ingrese los ingredientes que quiere añadir a su pizza \nCuando ya no desee ningun elemento mas introduzca 'quit'\n") mensaje = "" while mensaje != "quit": mensaje = input("Nuevo ingrediente: ") mensaje = mensaje.lower() if mensaje != "quit": print("Hemos agregado el ingrediente '"+ mensaje +"' a su pizza")
f4f7829d151cc872632afce5c6d156e98e6b2e5c
SandyHuang0305/iftest02
/02.py
304
3.859375
4
x = input('請輸入運算符號:') a = int(input('請輸入數字:')) b = int(input('請輸入數字:')) if x == ('+'): print('答案為',a+b) elif x ==('-'): print('答案為',a-b) elif x == ('*'): print('答案為',a*b) elif x == ('/'): print('答案為',int(a/b)) else: print('輸入錯誤')
853d9bc938e8de958ba473ee48ca3d27b07cf2f0
smartao/estudos_python
/03_estrutura_controle/04_for_v3_dicionarios.py
836
3.796875
4
#!/usr/bin/python3 # Criando um dicionario produto = {'nome': 'Caneta Chic', 'preco': 14.99, 'importada': True, 'estoque': 793} # Tambem seria valido o for usando # for chave in produto.keys(): print('\nImprimindo as chaves do diconario:') for chave in produto: print(chave) print('\nImprimindo os valores do dicionario:') for valor in produto.values(): print(valor) print('\nImprimindo chaves e valores do dicionario:') for chave, valor in produto.items(): print(chave, '=', valor) ''' Observação Mesmo fora do FOR as variaves chave e valor ainda retornaram o ultimo valor Exemplo: ''' print('\nUltimo valor chave e estoque: ' + chave, valor) # Fontes: # Curso Python 3 - Curso Completo do Básico ao Avançado Udemy Aula 77 a 81 # https://github.com/cod3rcursos/curso-python/tree/master/estruturas_controle
d043485b8926d4ed7eaec423e1be15105d427f3c
manugarcia101/Python
/Python (Intermediate)/6.Enumerate.py
707
4.28125
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 11 14:03:40 2018 @author: Manu """ #!Python 3.6.3 #Author: Manuel García López #Enumerate ''' Basically we are going to try to return a tuple, with th count of how many times an object is inside somewhere, and the obj ''' example = ['left','right','up','down'] #this is not the right way of printing smth for i in range(len(example)): print(i,example[i]) #the right way is this: #why? Because it is nicer and we will expect a result more accurate #to the reality for i,j in enumerate(example): print(i,j) #another example of using an enumerate over a dict newDict = dict(enumerate(example)) print(newDict) [print(i,j) for i,j in enumerate(newDict)]
72b62801403ac650a6f95f397e2ccbfda87a2b21
ThtGuyBro/Python-sample
/foobar.py
224
3.90625
4
water = 30 for num in range(1, water + 1): if num % 3 == 0 and num % 5 == 0: print("foobar") elif num % 3 == 0: print ("foo") elif num % 5 == 0: print("bar") else: print(num)
5e3418e680b041b87b118267a99906c3b40123b3
TKhuslen/cs110-spring-2020
/10am/Class25/blackjack.py
1,567
3.921875
4
""" File: blackjack.py Author: Darren Strash Implement classes for a blackjack game. """ import random RANKS = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"] SUITS = ["D", "C", "S", "H"] class PlayingCard: def __init__(self, rank, suit): self._rank = rank self._suit = suit def __str__(self): return str(self._rank) + self._suit def __repr__(self): return self.__str__() def get_rank(self): return self._rank def get_suit(self): return self._suit def is_face(self): return self._rank == "J" or \ self._rank == "Q" or \ self._rank == "K" class Deck: def __init__(self): self._deck = [] for rank in RANKS: for suit in SUITS: card = PlayingCard(rank, suit) self._deck.append(card) self.shuffle() def shuffle(self): random.shuffle(self._deck) def __str__(self): return str(self._deck) def deal_one_card(self): return self._deck.pop() def main(): deck = Deck() print("The original deck:", deck) print("Drawn card: ", deck.deal_one_card()) print("Drawn card: ", deck.deal_one_card()) print("The new deck:", deck) # real_card = PlayingCard("J", "D") # card_string = str(real_card) # print(card_string) # print(real_card) # print("Rank:", real_card.get_rank(), ", Suit:", real_card.get_suit()) # print("Is Face?:", real_card.is_face()) # print(real_card) if __name__ == "__main__": main()
b9e2686165244ad294363a467768f80a2e6422c4
Rudigus/general-python
/pesquisa_e_ordenacao/stability_analysis.py
1,346
4.03125
4
from utils.elementGenerator import getRandomRepeatingListWithRange from utils.elementSorter import bubbleSort, insertionSort, selectionSort, quickSort def printElements(elements): for i in range(len(elements)): print(f"({elements[i].value}, {elements[i].id})", end = "") if(i < len(elements) - 1): print(", ", end="") else: print() def testStability(sortFunction, sortName, stable): print(f"{sortName} - Before Ordering\n") elements = getRandomRepeatingListWithRange(10, 4) printElements(elements) print(f"\n{sortName} - After Ordering\n") sortFunction(elements) printElements(elements) if stable: print(f"\n{sortName} is stable because the order of repeated elements does not change after the sorting, which is shown when you compare elements with the same value: their ID always increases as you move from left to right.\n") else: print(f"\n{sortName} is unstable because the order of repeated elements may change after the sorting, so if you compare elements with the same value, you can have an element to the right of another one but with a smaller ID.\n") print("Format: (value, id)\n") testStability(bubbleSort, "Bubble Sort", True) testStability(insertionSort, "Insertion Sort", True) testStability(selectionSort, "Selection Sort", False) testStability(quickSort, "Quick Sort", False)
3280b7da5abda559f8699a795836e5cb595fae84
starryKey/LearnPython
/04-TKinter基础/TkinterExample09.py
958
3.59375
4
# 画一个五角星 import tkinter import math as m baseFrame = tkinter.Tk() w = tkinter.Canvas(baseFrame, width=300, height=300, background="gray" ) w.pack() center_x = 150 center_y = 150 r = 150 # 依次存放五个点的位置 points = [ #左上点 # pi是一个常量数字,3.1415926 center_x - int(r * m.sin(2 * m.pi / 5)), center_y - int(r * m.cos(2 * m.pi / 5)), #右上点 center_x + int(r * m.sin(2 * m.pi / 5)), center_y - int(r * m.cos(2 * m.pi / 5)), #左下点 center_x - int(r * m.sin( m.pi / 5)), center_y + int(r * m.cos( m.pi / 5)), #顶点 center_x, center_y - r, #右下点 center_x + int(r * m.sin(m.pi / 5)), center_y + int(r * m.cos(m.pi / 5)), ] # 创建一个多边形 w.create_polygon(points, outline="green", fill="yellow") w.create_text(150,150, text="五角星") baseFrame.mainloop()
54629c7a3e4211c8071bdfebb115a13c8cfe1094
xcode2010/wkkim_ML
/TIL/Python_Data/pythonclass/4_class_robot.py
282
3.71875
4
class Robot(): def __init__(self, name, pos): self.name = name self.pos = pos def move(self): self.pos += 1 print("{0} position: {1}".format(self.name,self.pos)) robot1 = Robot('R1', 0) robot2 = Robot('R2', 10) robot1.move() robot2.move()
467d9cfae5290fc3a94f8aeec3adf2a10da4c2ae
sharelinux/python_algorithm_practice
/selection_sort.py
537
3.75
4
def selectionSort(nums): """选择排序法""" for i in range(len(nums) - 1): min_index = i # i位置默认最小值 for j in range(i + 1, len(nums)): # 从 i+1 位置循环到末尾找最小值 if nums[min_index] > nums[j]: # 如果出现小于i位置值,则交换 min_index = j nums[i], nums[min_index] = nums[min_index], nums[i] return nums aList = [1, 9, 3, 7, 4, 5, 8, 2, 6] print("selection_sort: %s" % selectionSort(aList))
fcd28636fff905cb8e0b361fa2dd2323a30f43e6
ngt1986/Projects
/Project Euler/14.py
978
4.0625
4
# The following iterative sequence is defined for the set of positive integers: # # n → n/2 (n is even) # n → 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 # It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. # # Which starting number, under one million, produces the longest chain? # # NOTE: Once the chain starts the terms are allowed to go above one million. def hailstone(n,chain = 1): if n == 1: return chain if n % 2 == 0: return hailstone(n/2, chain +1) else: return hailstone(3*n+1, chain+1) max_chain = (0, 0) for i in range(1,1000000): chain = hailstone(i) if chain > max_chain[0]: max_chain = (chain, i) print(max_chain) print(max_chain)
1d4a95d3a5f46e4d6c982a59540c8cab52893660
RRCHcc/python_base
/python_base/day03/exercise05.py
1,085
4.0625
4
""" 练习1:在控制台输入一个整数,判断是奇数还是偶数,要求用真值表达式 练习2:在控制台中获取一个年份,如果闰年给变量day赋值29,赋值28 """ #练习1 # int_integer = int(input("请输入一个整数")) # if int_integer < 1: # print("输入有误") # elif int_integer%2 ==0: # print("偶数") # else: # print("奇数") #练习2 # year = int(input("请输入一个年份")) # day = 29 if not year%4 and year%100 or not year%400 else 28#(条件表达式) # #(条件表达式)变量 = 结果1 if 条件 else 结果2 # print(day) num01 = 800 num02 = 900 num03 = num01 print(num01 is num02) # false print(id(num01) == id(num02)) print(num03 is num01) # true #int_number = int(input("请输入一个整数")) # int_number%2 == 1: # if int_number%2:#bool( 5 % 2 ) # print("奇数") # else: # print("偶数") # # #year = int(input("请输入一个年份:")) # day = 29 if year%4 == 0 and year%100 != 0 or year%400 == 0 else 28 # 下列简洁 #day = 29 if not year%4 and year%100 or not year%400 else 28
7a06a8b813c49f8322eff9da2d3a71338b8ed6a5
Beira-BF/Euler-Project
/000006.py
625
3.703125
4
# Sum square difference # Problem 6 # The sum of the squares of the first ten natural numbers is, # 12 + 22 + ... + 102 = 385 # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. a=[] b=[] for i in range (1,101): a.append(i*i) b.append(i) print(a,b) c=sum(a) print(c) d=sum(b) print(d) e=d*d print(e) print(abs(e-c))
ea2eb3e0d410e9eea04473a523d480cb0ab4e6e6
sanathNU/eYRC-Python-Codechef-Challenge
/STAR_PY.py
1,161
3.828125
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 14 09:52:37 2021 @author: FranticUser """ ''' Created for solving the CodeChef Problem STAR_PY Problem Statement: Given a number N, generate a star pattern such that on the first line there are N stars and on the subsequent lines the number of stars decreases by 1. The pattern generated should have N rows. In every row, every fifth star (*) is replaced with a hash (#). row should have the required number of stars (*) and hash (#) symbols. ''' ''' Sample Input 1 5 Sample Output ****# **** *** ** * ''' #list comprehension for taking all inputs ls = [int(input()) for i in range(int(input()))] for items in ls: #creating individual strings with '*' and then replacing every 5th element with '#' temp = items * '*' temp1=[] for a in range(1,items+1): if a%5==0 and a!=0: temp1.append('#') else: temp1.append('*') #printing each temp string for b in range(items): print(''.join(temp1)) temp1=temp1[:-1]
0f021e1bd51522bcc09de1c9f48836b88a41b01b
fredfeng0326/LeetCode
/let575.py
613
3.6875
4
# 575. Distribute Candies class Solution: def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ len1 = len(set(candies)) if len1 > len(candies)/2: return int(len(candies)/2) else: return len1 def distributeCandies2(self, candies): """ :type candies: List[int] :rtype: int """ sister_count = len(candies) // 2 unique_candies = set(candies) return min(sister_count, len(unique_candies)) a = Solution() print (a.distributeCandies([1,1,2,3]))
31d8440ac80cb03c5ff01d6ad42b439a2b7215d2
Yashirathore11/scientific_calci
/Garvit/conversion.py
2,206
4.15625
4
def binary_to_decimal(binary): decimal, i = 0, 0 while binary != 0: dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary // 10 i += 1 return decimal def octal_to_decimal(octal): decimal, i = 0, 0 while octal != 0: dec = octal % 10 decimal = decimal + dec * pow(8, i) octal = octal // 10 i += 1 return decimal def hexadecimal_to_decimal(hexadecimal): decimal, i = 0, 0 while hexadecimal != 0: dec = hexadecimal % 10 decimal = decimal + dec * pow(16, i) hexadecimal = hexadecimal // 10 i += 1 return decimal def binary_to_octal(binary): decimal = binary_to_decimal(binary) octal = oct(decimal).replace("0o", "") return octal def binary_to_hexadecimal(binary): decimal = binary_to_decimal(binary) hexadecimal = hex(decimal).replace("0x", "") return hexadecimal def octal_to_binary(octal): decimal = octal_to_decimal(octal) binary = bin(decimal).replace("0b", "") return binary def octal_to_hexadecimal(octal): decimal = octal_to_decimal(octal) hexadecimal = hex(decimal).replace("0x", "") return hexadecimal def hexadecimal_to_decimal(hexadecimal): decimal, i = 0, 0 while hexadecimal != 0: dec = hexadecimal % 10 decimal = decimal + dec * pow(16, i) hexadecimal = hexadecimal // 10 i += 1 return decimal def hto(): hexadecimal = int(input("Enter valid Hexadecimal number: ")) decimal = hexadecimal_to_decimal(hexadecimal) octal = oct(decimal).replace("0o", "") print("Octal number is: ", octal) def hexadecimal_to_binary(hexadecimal): decimal = hexadecimal_to_decimal(hexadecimal) binary = bin(decimal).replace("0b", "") return binary def decimal_to_binary(decimal): binary = bin(decimal).replace("0b", "") return binary def decimal_to_hexadecimal(decimal): hexadecimal = hex(decimal).replace("0x", "") return hexadecimal def decimal_to_octal(decimal): octal = oct(decimal).replace("0o", "") return octal
0aa13744040459162b497c8af5057cb74c32ec1c
mankaranurag/python-programs
/IntroductionFirstSteps/14_try_except.py
238
3.765625
4
try: number = int(input("Enter a number : ")) print(number) number = 10 / number except ZeroDivisionError as err: print("Divided by zero -> " + str(err)) except ValueError as err: print("Invalid Input -> " + str(err))
af71d1540b6ffd4b6a3f6729f397d8ddb6196e6e
jdchristesen/projectEuler
/pandigital_multiples.py
919
3.515625
4
import time start_time = time.clock() digits = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] answers = [] test = 987654321 longest = 0 while longest == 0: if len(set(str(test))) == 9 and '0' not in str(test): print(test) for i in range(2, 5): first = int(str(test)[:i]) second = first * 2 third = first * 3 two_str = str(first) + str(second) three_str = str(first) + str(second) + str(third) if '0' not in two_str and len(two_str) == 9 and len(set(two_str)) == 9: longest = int(two_str) break elif '0' not in two_str and len(three_str) == 9 and len(set(three_str)) == 9: longest = int(three_str) break test -= 1 print(longest) print(first, second, third) print(set(str(first) + str(second))) print('Time: {}'.format(time.clock() - start_time))
67a6c7b2ca10582ea4d0f5c3d2b3c386dd5a4bf8
Maxime-Favier/Isep-informatique
/semestre1/tp5/tp3.py
183
3.875
4
def factoriel(x): if x == 0: return 1 z = 1 for i in range(1,x +1): #print(i) z = z*i return z n = int(input("factoriel")) print(factoriel(n))
9bd0c0152aa02b7fbab5ab17439e69d693b7c185
gopalbala/codingninjas
/pythondatastructures/ReverseQueue.py
401
3.515625
4
import queue def reverseQueue(q1): if q1.qsize() == 0: return item = q1.get() reverseQueue(q1) q1.put(item) #### Implement Your Code Here from sys import setrecursionlimit setrecursionlimit(11000) li = [int(ele) for ele in (input().split()[1:])] q1 = queue.Queue() for ele in li: q1.put(ele) reverseQueue(q1) while(q1.empty() is False): print(q1.get(),end= ' ')
ad2f6e2a55791d1bb209a94a8b8f421424fa4303
dudfo2347924/pyworks
/ch.03/loop_example/seats.py
581
3.765625
4
#자리 배치도 프로그램 customer_num = int(input("입장객의 수 입력 : ")) col_num = int(input("좌석 열의 수 입력 : ")) if customer_num % col_num == 0: row_num = int(customer_num / col_num) elif customer_num % col_num != 0: row_num = int(customer_num / col_num + 1) '''print("%d개의 줄이 필요합니다." % row_num)''' print('자리배치도') for i in range(0, row_num): for j in range(1,col_num+1): seats = i*col_num+j if seats > customer_num: break; print(seats, end = ' ') print()
dd96b8c70354d0a06846a88cefa1b8d3ae79f345
skyegrey/490final_project
/import_data.py
2,467
3.515625
4
import csv import numpy as np import pandas as pd columns = ['Using IP Address', 'Long URL', 'Using URL Shortening', 'URL has @ Symbol', 'Redirect Using //', 'Adding Prefix or Suffix to Domain', 'Subdomain and Multisubdomains', 'HTTPS', 'Domain Registration Length', 'Favicon', 'Using Non-standard Port', 'Existence of HTTPS Token in Domain', 'Request URL', 'URL Anchor', 'Links in metascript and Link Tabs', 'Server Form Handler', 'Submitting Information to Email', 'Abnormal URL', 'Website Forwarding', 'Status Bar Customization', 'Disabling Right Click', 'Using Pop-up Window', 'IFrame Redirection', 'Age of Domain', 'DNS Record', 'Website Traffic', 'Page Rank', 'Google Index', 'Number of Links Pointing to Page', 'Statistical Reports Based Feature', 'Safe Website'] def import_data(csv_string): """ Takes in a csv string, returns a list of values as integers :param csv_string: name of the csv file to take in :return: data frame containing integer values of feature with labeled columns """ values = [] with open(csv_string, 'r') as csv_file: reader = csv.reader(csv_file, delimiter=',') for row in reader: for i in range(0, len(row)): row[i] = int(row[i]) values.append(row) values = np.array(values) value_table = pd.DataFrame(values) value_table.columns = ['Using IP Address', 'Long URL', 'Using URL Shortening', 'URL has @ Symbol', 'Redirect Using //', 'Adding Prefix or Suffix to Domain', 'Subdomain and Multisubdomains', 'HTTPS', 'Domain Registration Length', 'Favicon', 'Using Non-standard Port', 'Existence of HTTPS Token in Domain', 'Request URL', 'URL Anchor', 'Links in metascript and Link Tabs', 'Server Form Handler', 'Submitting Information to Email', 'Abnormal URL', 'Website Forwarding', 'Status Bar Customization', 'Disabling Right Click', 'Using Pop-up Window', 'IFrame Redirection', 'Age of Domain', 'DNS Record', 'Website Traffic', 'Page Rank', 'Google Index', 'Number of Links Pointing to Page', 'Statistical Reports Based Feature', 'Safe Website'] # print(value_table) return value_table
32e68de82962b54ee648ccb035ec80e90a981c4b
daniel-reich/turbo-robot
/88RHBqSA84yT3fdLM_9.py
965
4.34375
4
""" Create a function that takes a single word string and does the following: 1. Concatenates `inator` to the end if the word ends with a consonant, otherwise, concatenate `-inator` instead. 2. Adds the word length of the original word to the end, supplied with "000". The examples should make this clear. ### Examples inator_inator("Shrink") ➞ "Shrinkinator 6000" inator_inator("Doom") ➞ "Doominator 4000" inator_inator("EvilClone") ➞ "EvilClone-inator 9000" ### Notes For the purposes of this challenge, vowels will be **a, e, i, o** and **u** only. """ def inator_inator(text): originalText = text vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] for v in vowels: if text[-1] == v: text += "-inator" text += " " text += str(len(originalText)) text += "000" return text text += "inator" text += " " text += str(len(originalText)) text += "000" return text
b2bb610448bbf127eac92945190357a784f77526
infinite-Joy/programming-languages
/python-projects/algo_and_ds/catalan_numbers.py
662
4.03125
4
""" Finding the catalan numbers """ # the numbers can be done using the catalan numbers # but the actual values needs to be done using backtracking. def catalan(n): # reference http://www.geometer.org/mathcircles/catalan.pdf if n == 0 or n == 1: return 1 # Table to store results of subproblems dp = [0 for _ in range(n+1)] # initialise the first two values of the table dp[0] = 1 dp[1] = 1 # fill entries using the recursive formula for i in range(2, n+1): for j in range(i): dp[i] += dp[j] * dp[i-j-1] print(i, j, dp[i]) print(dp) return dp[n] print(catalan(3))
acd1a9f6b2a3ff6a346f91c6090e4485550ceaa7
Ntalemarvin/ds_salary_proj
/python/math_opperators.py
210
3.75
4
#Built in Functions like round(), abs() #abs() returns a postive number if when a number is negative x = -2.9 print(abs(x)) x = 2.9 print(round(x)) #math module import math import math print(math.ceil(2.9))
637a85ccf9be6f6fbe588a854ac1bcf9c57059c6
AndreiBoris/Backend-Mini-Projects
/vagrant/catalog/database_extra.py
1,593
3.625
4
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem engine = create_engine('sqlite:///restaurantmenu.db') # makes the connection between our class definitions and corresponding tables in # the database Base.metadata.bind = engine # A link of communication between our code executions and the engine created above DBSession = sessionmaker(bind = engine) # In order to create, read, update, or delete information on our database, # SQLAlchemy uses sessions. These are basically just transactions. WE can write # a bunch of commands and only send them when necessary. # # You can call methods from within session (below) to make changes to the # database. This provides a staging zone for all objects loaded into the # database session object. Until we call session.commit(), no changes will be # persisted into the database. session = DBSession() myFirstRestaurant = Restaurant(name = "Pizza Plaza") # staging zone session.add(myFirstRestaurant) # add into database session.commit() # Check a database to confirm changes session.query(Restaurant).all() # This will give hexadecimal location of found objects cheesepizza = MenuItem( name = "Cheese Pizza", description = "Made with all natural goat cheese", course = "Entree", price = "$14.99", restaurant = myFirstRestaurant) session.add(cheesepizza) session.commit() session.query(MenuItem).all() # Store first result from a query into the Restaurant table firstResult = session.query(Restaurant).first() # Access the name column of firstResult firstResult.name
7b3e911816d0951d93037f0ffd34973e75c424b5
ggoudy/Python
/Learning Python/Classes/classes and objects.py
364
3.890625
4
# Create a Class class thisismyclass: x = 15 y = 10 # Create a Object p1 = thisismyclass() print(p1.x * p1.y) class Person: def __init__(self, name, age): self.name = name self.age = age myname = input("Please type your name: ") myage = int(input("Please type your age: ")) p2 = Person(myname, myage) print(p2.name) print(p2.age)
ddb412cedc90b21e14c374785d069a8dff183a14
alakd1985/Python-with-Selenium
/List/Exercise/longer word.py
100
3.65625
4
#Write a Python program to find the list of words that are longer than n from a given list of words
f2cf982df87d76da0b723bd728e1d12ff080218e
cnoturno/curso-python-3
/controle/for_1.py
662
4.1875
4
#!python3 for i in range(10): print(i) for i in range(1, 11): print(i) for i in range(1, 100, 7): # 1 a 100 de 7 em 7 print(i) for i in range(20, 0, -3): print(i) nums = [2, 4, 6, 8] for n in nums: print(n, end=',') texto = 'Python é muito massa!' for letra in texto: print(letra, end=' ') for n in {1, 2, 3, 4, 4, 4}: print(n, end=' ') produto = { 'nome': 'Caneta', 'preco': 8.80, 'desc': 0.5 } for atrib in produto: print(atrib, '=>', produto[atrib]) for atrib, valor in produto.items(): print(atrib, '=>', valor) for valor in produto.values(): print(valor, end=' ') for atrib in produto.keys(): print(atrib, end=' ')
58a7638afbc020dc37761e052904a33ec3ef6a7d
ArunDharavath/DailyCodingProblem
/prob2.py
333
3.59375
4
l = list(map(int, input().split(" "))) #list to store input elements prod = 1 new = [] #output list #nested for loop to store product of all elements except the indexed element. for i in range(0,len(l)): prod = 1 for x in range(0,len(l)): if i == x: continue else: prod *= l[x] new.append(prod) print(new)
72e940d718cea6d0463a8ca639edb99d6ecf37dc
AbdulSholikhin89/bootcamp
/bootcamp6/bintangsegitiga.py
244
3.953125
4
string = "" baris = 1 x =int(input("masukan angka :")) #looping baris while baris <= x: kolom = baris #looping kolom while kolom > 0: string = string + "*" kolom = kolom - 1 string = string + "\n" baris = baris + 1 print(string)
dd6a6e2272d122a7a53c389b0e73af1de868ce52
clusterknot/Data-Structures-and-Algorithms-Specialization
/Algorithm Toolbox/week2_algorithmic_warmup/3_greatest_common_divisor/gcd_self.py
402
3.796875
4
def gcd(a,b) : if a >= b: smaller = b larger = a else: smaller = a larger = b rem = larger%smaller if rem ==0: return smaller while rem !=0: rem = larger % smaller if rem == 0: return smaller larger = smaller smaller = rem n = input() a = int(n.split()[0]) b = int(n.split()[1]) print(gcd(a,b))
4dc6c571a6ea67bac7341f1127e18854aeaba08f
hspradlin8/PythonBasics
/password_checker.py
431
4.09375
4
# not a good way to verify passwords # showing examples of While Loops import sys #all caps mean constant MASTER_PASSWORD = 'opensesame' password = input("Please enter the super secret password: ") while password != MASTER_PASSWORD: if attempt_count > 3: sys.exit("Too many invalid password attempts") password = input("Invalid password. Try again: ") attempt_count += 1 print("Welcome to secret town")
dc5ebef53f1e8d8efd0783b9cce0e43aae6ef7dd
Dingkang2/python-
/第四课.练习.py
340
3.8125
4
import sys while True: age = input('请输入你的年龄') if age == 'exit': sys.exit() else: age = int(age) if age < 3 and age >0: print('免费') elif age <= 0: print('error') elif age >= 3 and age < 12: print('10元') else: print('15元')
0589679259c7fbab2e5b2564abab7c07cd3b85df
Ayush7911/Python-Rn
/ifex1.py
380
4.125
4
age=int(input('Age: ')) if age<=0: print('Invalid input for age') elif age<=1: print('Youre an infant') elif age<=12: print('Youre a kid') elif age<=19: print('You are teenager') elif age<=45: print('you are a adult') elif age<=59: print('you are middle-aged') elif age<=60: print('tou are old') elif age<=120: print('You are way too old')
5336abaaa942b4f466723e352a278404e947925e
dchmerenko/courseraPy
/04/hw0499.py
182
3.734375
4
def func(): x = int(input()) if x != 0: func() if int(x ** 0.5) ** 2 == x: print(x, end=' ') return -1 if func() != -1: print(0)
fd8f08f2cc1fbad5d3bec834404eedf258e05879
PlutoaCharon/CodeExercise_Python
/排序算法/选择排序.py
340
3.953125
4
def selectSort(arr): for i in range(len(arr) - 1): minNum = i for j in range(i + 1, len(arr)): if arr[minNum] > arr[j]: minNum = j arr[i], arr[minNum] = arr[minNum], arr[i] return arr if __name__ == '__main__': arr = [2, 5, 3, 4, 1] ans = selectSort(arr) print(ans)
60cdfb04f12cd1217c2968e79beb3be75bb30e1a
arpitsomani8/Python-Programming-Projects
/Spiral Traversing/Spiral_traversing.py
945
3.953125
4
""" @author: Arpit Somani """ def spiral(m,n,a): k=0 l=0 #k=index of starting row #l=index of starting cloumn while(k<m and l<n): #printing first row from remaining rows for i in range(l,n): print(a[k][i],end=" ") k+=1 #printing last column from remaining rows for i in range(k,m): print(a[i][n-1],end=" ") n-=1 if(k<m): #printing the last row from remaining rows for i in range(n-1,l-1,-1): print(a[m-1][i],end=" ") m-=1 if(l<n): #printing the first column from remaining columns for i in range(m-1,k-1,-1): print(a[i][l],end=" ") l+=1 a=[] count=1 for i in range (4): l=[] for j in range(4): l.append(count) count+=1 a.append(l) spiral(4,4,a)
3443892dee5fe5c16eb0cf4de753a24f77bb6d06
edaley5177/PublicWork
/Python/CodeFights/AvoidObstacles.py
838
3.828125
4
# You are given an array of integers representing coordinates of obstacles situated on a straight line. # Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer. # Find the minimal length of the jump enough to avoid all the obstacles. def avoidObstacles(inputArray): #I have to find the first integer that is not a multiple of all the numbers in the arra #starting at 2 x=2 z=-1 while(z==-1): i=0#iterator for inner loop to search whole array while(i<len(inputArray)): if(inputArray[i]%x ==0): x+=1 i=50#restart loop with next x i+=1 if(i<50): return x
a903c80bd262f2a7ea29527b4ce0007ff5c7ffc5
rmcguire-dev/hello-world
/fibfast.py
581
4.09375
4
"""Fibonacci Number. Given an integer n, find the nth Fibonacci number Fn. Specification Input: The input consists of a single integer n. Constraints: 0 <= n <= 45. Output Format: Output Fn Samples >>> n = 10 >>> fibonacci_fast(n) 55 >>> # Explanation: To achieve the value 55 >>> # take the 10th number of the sequence """ def fibonacci_fast(n): if n == 0: return 0 else: f = [0, 1] for i in range(2, n + 1): f.append(f[i - 2] + f[i - 1]) return f[-1] n = int(input()) print(fibonacci_fast(n))
05c39e2ba0f045ef874dd1b1f73a85f9152ff071
Indhuu/git-github
/python/strings_1.py
302
4.125
4
# String example import sys str = input ('Enter a string value : ') if str.isalpha() == False: print ('Error message') sys.exit() elif str.isalpha() == True: print (len(str)) if (len(str)%2) == 1: print ('odd number') else: print ('even number')
c1728592d3e3ae69c6cdf72a3483dfb46730b69c
datature/discolight
/src/discolight/loaders/image/types.py
909
3.609375
4
"""Base types for image loaders.""" from abc import ABC, abstractmethod class ImageLoader(ABC): """A class that loads images. Image loaders can be used in a with context. """ _include_in_factory = True @abstractmethod def __enter__(self): """Initialize the image loader.""" raise NotImplementedError @abstractmethod def __exit__(self, _exc_type, _exc_val, _exc_tb): """Close the image loader.""" raise NotImplementedError @staticmethod @abstractmethod def params(): """Return a Params object describing constructor parameters.""" raise NotImplementedError @abstractmethod def load_image(self, image_name): """Load an image with the given name. The image should be returned as an openCV image in HxWxC format, in RGB color space. """ raise NotImplementedError
ea3b8f0bcac278b31b1352fc304651786b29f933
lucasbflopes/codewars-solutions
/7-kyu/fizz-buzz/python/solution.py
143
3.703125
4
def fizzbuzz(n): return ["FizzBuzz" if i%3 == 0 and i%5 == 0 else "Fizz" if i%3 == 0 else "Buzz" if i%5 == 0 else i for i in range(1, n+1)]
8133035aebb5ed885f037a2b05b2509cb6229db3
deborabr21/Python
/PartI_Introduction_To_Programming/4_Arithmetic_Operators_Exercise_1.py
154
4.0625
4
#Create a program that creates two variables x and y. #Set x to 15 and y to 4 then print the remainder when you divide x by y. x=15 y=4 print (x % y)
e6a4814f04fc2b78a5d7c3b870d7460bd07c4076
rstewart2702/python-algoritmic-thinking
/DisjointSets.py
2,164
3.671875
4
# union-find, disjoin-set implementation? from graph import Vertex as Vertex, Graph as Graph, GraphPaths as GraphPaths class UFNode: def __init__(self, vtx): self.vtx = vtx self.parent = None # class DisjointSets: def __init__(self, vertices): self.sets = {} for v in vertices: self.sets[v] = UFNode(v) # def union(self, v1, v2): rep1v = self.find(v1).vtx rep2v = self.find(v2).vtx self.sets[rep2v].parent = rep1v # def union1(self, v1, v2): """This version of the \"union\" operation doesn't do enough! It does not perform needed path-traversal to get to the ultimate parent of either of the vertices in question. The test output should prove this out.""" self.sets[v2].parent = v1 # def find(self, vtx): """Return the ultimate, representing-member of the subset that contains the vertex named by vtx.""" find_hops=0 curV = self.sets[vtx] while(curV.parent is not None): curV = self.sets[curV.parent] find_hops = find_hops+1 # # print('Found ',curV.vtx, ' in ',find_hops,' hops') return curV if __name__ == '__main__': vList = ['v1','v2','v3','v4','v5','v6','v7','v8','v9','v10','v11'] x = DisjointSets(vList) # x.union('v5','v6') x.union('v9','v8') x.union('v11','v10') print([ x.find(itm).vtx for itm in vList] ) x.union('v9','v10') print([ x.find(itm).vtx for itm in vList] ) print(x.find('v8').vtx) print([ x.find(itm).vtx for itm in vList ] ) print() # y = DisjointSets(vList) y.union1('v5','v6') y.union1('v9','v8') y.union1('v11','v10') print('Representative of v10 is: ',y.find('v10').vtx) print([ y.find(itm).vtx for itm in vList] ) y.union1('v9','v10') print('Representative of v11 is: ',y.find('v11').vtx) print('Representative of v10 is: ',y.find('v10').vtx) print([ y.find(itm).vtx for itm in vList] ) # print(y.find('v8').vtx) print([ y.find(itm).vtx for itm in vList] )
e1c10c30ea6397e9d58bbb3c28d7ccd1b02c5a8a
erjan/coding_exercises
/longest_word_in_dictionary_through_deleting.py
1,371
3.90625
4
''' Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. ''' class Solution: def findLongestWord(self, s: str, dictionary: List[str]) -> str: #Sort the dictionary by length and then lexographical order dictionary.sort(key= lambda x: (-len(x),x)) for d in dictionary: count = 0 i = j = 0 while j < len(d) and i < len(s): #Start counting whenever a character matches if s[i] == d[j]: j += 1 count += 1 i += 1 #return as soon as you find all the characters from dictionary word in s if count == len(d): return d return '' ---------------------------------------------------------------------------------- #AA#> Two level Sort of words: 1st length, 2nd lexiographic order dictionary.sort(key = lambda x: (-len(x),x)) for word in dictionary: j = 0 #AA#> word pointer for i in range(len(s)): #AA#> string pointer if s[i] == word[j]: j+=1 if j == len(word): return word return ''
db1dbeefe66e525553188b7860388813f103f638
Hyun-JaeUng/TIL
/PythonExam/Day6/setLab1.py
484
3.859375
4
import random x =set() # 빈 세트는 이 방법 뿐 y =set() # 난수 추출하여 저장 while True: x.add(random.randint(1,20)) if len(x) == 10: break while True: y.add(random.randint(1,20)) if len(y) == 10: break print("집합 1 :", x) print("집합 2 :", y) print("합 집합", x|y) print("집합 1 - 집합 2 차집합 :", x-y) print("집합 2 - 집합 1 차집합 :", y-x) print("집합 1과 2가 각자 가지고 있는 데이터 :", x^y)
d9627abc22cd3095a998fde40c62bdc9705fa93c
akhilbommu/AlgoExpert.io
/BalancedBrackets.py
670
3.671875
4
def balancedBrackets(string): openBracketList = ['(', '{', '['] closeBracketList = [')', '}', ']'] d = {")": "(", "]": "[", "}": "{"} stack = [] for ch in string: if ch in openBracketList: stack.append(ch) elif ch in closeBracketList: if len(stack) == 0: return False elif d[ch] == stack[-1]: stack.pop() else: return False return True if len(stack) == 0 else False print(balancedBrackets("((({})()))")) print(balancedBrackets("(a)")) print(balancedBrackets("(141[])(){waga}((51afaw))()hh()")) print(balancedBrackets("()()[{()})]"))
927fedfd729a481a0ce4d07a5730700c047feea7
SpireX-/Python
/Tasks/task7.py
392
3.59375
4
#! /usr/bin/dev python # -*- coding:utf8 -*- def rem_noabc(string,abc): not_exists = set() for i,c in enumerate(string): exists = False for a in abc: if c == a: exists=True break if not exists: not_exists.add(c) for c in not_exists: string = string.replace(c,'') return string if __name__ == '__main__': abc=('a','b','c','d','e','t') print rem_noabc("abstract",abc)
375a3e18d17d5279f632a9a9ec353bebd8c00689
stheartsachu/Miscellinuous
/student_grade.py
483
3.5
4
arr = ["Harsh","Beria","Varun","Kakunami","Vikas"] arr1 = [20, 20, 19, 19, 21] s_rade = [[i, j] for i, j in zip(arr, arr1)] s_rade.sort(key=lambda x: x[1]) s_h_n = [] for i in range(len(s_rade)): s_h_n.append(s_rade[i][1]) s_h_n_set = list(set(s_h_n)) second_last = [] for i in range(len(s_rade)): if s_h_n_set[1] == s_rade[i][1]: second_last.append(s_rade[i]) second_last.sort(key=lambda x: x[0]) for i in range(len(second_last)): print(second_last[i][0])
7071faba776ed941dd930ca8a175e906a357cb12
akosthekiss/picire
/tests/resources/inp-sumprod10.py
135
3.828125
4
#!/usr/bin/env python3 sum = 0 prod = 1 for i in range(1,11): sum += i prod *= i print(f'sum: {sum}') print(f'prod: {prod}')
7783885fc1795c5dcebb05f845add1ad8114b5c7
austinchen15/Small-Python-Projects
/HW09.py
7,465
4.21875
4
# #HW09 # #Austin Chen # #This module contains problems 1-4 for Homework #9. # from graphics import * import math # #This function will convert user input into camel case. # input: none # def camelCase(): print("Camel Case") #User will input a phrase to be stored in userInput userInput = input("Enter a non-numerical phrase to be converted into camel case: ") #This will split the user's input to a list with each space seperating a part of the index userInput = userInput.split(" ") #Creates a new list variable of the first index in userInput firstWord = userInput[0] #Converts all letters to lowercase firstWord = firstWord.lower() #Slices string down to only the 0th index, or 1st value. firstWord = firstWord[0] #Prints value, end="" to keep on the same line print(firstWord,end="") #Creates a list of all words after the first otherWords = userInput[1:] #Used for increasing the amount of letters used in subsequent words x = 2 #For "word" in list of otherWords for word in otherWords: #Capitalize the word word = word.capitalize() #Slice the word, x will start at 2 and rise by 1 to allow more letters in each subsequent word word = word[0:x] #Print the newly formatted word print(word,end="") #x modifier x = x + 1 print("") print("") camelCase() # #This function will use a Caesar cipher to read a message and key, then save the encoded message and a #decoding key to a different text file. # input: none # def caesar(): print("Caesar Cipher") #Alphabet string to use aBet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" #Name the input and output files userFile = input("Enter the text file name with the extension .txt: ") outFile = input("Enter a name for the file containing the encoded message and decoding key. Use extension .txt: ") outFile = open(outFile, "w") #Read the input file inFile = open(userFile, "r") #Read the entire file, assign to openedFile openedFile = inFile.read() #Split file by \n splitFile = openedFile.split("\n") #Will be separated into two variables: message and key message = splitFile[0] key = eval(splitFile[1]) #Assignment to stuff before ForLoop letterIndex = 0 shiftedLetterIndex = 0 finalMessage = "" #ForLoop will go through each character in the message for i in message: #For each letter, find the index value within the Alphabet string. letterIndex = aBet.find(i) #Shift the letter by key. Key%52 so that the shift exists (so for like 700 it will still work) shiftedLetterIndex = letterIndex - (key%52) #Add the shifted letter to the final message finalMessage = finalMessage + (aBet[shiftedLetterIndex]) #The decoding key is the length of my alphabet list - key. It will create a value to loop back around the string. decodingKey = 53 - key #Output file text #I originally had a bunch of instructions on how to decode before I figured out how to get a decoding value #So I left it here but did not print it in the document. decodingKey1 = "Alphabet index: ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' " decodingKey2 = "Index values: '0123456789...........................................' " decodingKey3 = "The original phrase was shifted " + str((key%52)) + " index value(s) to the left to produce message in the first line." decodingKey4 = "To decode, look at the Alphabet index. Locate letter to decode, and move " + str((key%52)) + " space(s) to the" decodingKey5 = "right. Loop around to the beginning of the index if necessary." decodingKey6 = "Tip: click in front of the letter to decode. For example, |J. Press your right arrow key " + str((key%52)) decodingKey7 = "times, and your decoded letter will be in front of your | cursor. Make sure to loop around when necessary." decodingKey8 = "Decoding Key: " + str(decodingKey) #Output file print print(finalMessage, file=outFile) #print("", file=outFile) #print(decodingKey1, file=outFile) #print(decodingKey2, file=outFile) #print(decodingKey3, file=outFile) #print("", file=outFile) #print(decodingKey4, file=outFile) #print(decodingKey5, file=outFile) #print(decodingKey6, file=outFile) #print(decodingKey7, file=outFile) print("", file=outFile) print(decodingKey8, file=outFile) #Close files inFile.close() outFile.close() print("Done") print("") caesar() # #This function will create a horizontal chart of student class averages. # input: none # def grades(): print("Grades") #Read the file, split the data by lines fileName = input("What text file should I read the grades from? ") openedFile = open(fileName,"r") rawData = openedFile.read() slicedData = rawData.split("\n") #Create window size and coordinate plane window = GraphWin("Grades", 700, 500) window.setCoords(0,0,100,100) #Will be used to calculate the numbers to use for the bars and how many times to loop #Uses the raw data space = 90/len(slicedData) loops = len(slicedData) #x assignment before ForLoop x = 0 #ForLoop will loop "loops"-1. I'm not sure why -1, but it fixed my problems # My original problem was that when I got to the last iteration, firstSplit didn't # have anything in it and therefore mod2 would be unhappy and spit out red error text. for i in range(loops-1): slicedDataIndex = slicedData[i] firstSplit = slicedDataIndex.split(" ") #Will create seperate variables for indices 0 and 1 in firstSplit mod1 = firstSplit[0] mod2 = eval(firstSplit[1]) #Labeling the bar p1 = Point(5,85-x) initials = Text(p1,"{0:3}".format(mod1)) initials.draw(window) #Drawing the bar bar = Rectangle(Point(10,80-x),Point(mod2, 90-x)) bar.draw(window) fill = Text(Point(mod2/2, 85-x),"{0:0.1f}%".format(mod2)) fill.draw(window) x = x + space #Click to close window window.getMouse() window.close() print("") grades() # #This function will calculate compound interest. # input: none # def interest(): print("Interest Calculator") #Input for all four variables to use in equation principal = eval(input("Enter amount of investment: ")) interest = eval(input("Enter annual interest rate as decimal: ")) compoundRate = eval(input("Enter how many times to compound a year: ")) compoundLength = eval(input("Enter how many years on the investment: ")) #Format of the top of the table print() yearsAmount = "Year Investment" print("{0}".format(yearsAmount)) space = " " line1 = ("-----------------------") print("{0}".format(line1)) #ForLoop will repeat how many years + 1 times for i in range(compoundLength+1): print(i," ${0:0.2f}".format(principal)) #Equation for compound interest. It excludes the t because the forloop will repeat each time. # Repetitions of the forloop will show intermediate years of compounding principal = round(principal*((1+(interest/compoundRate))**(compoundRate)),2) print("") interest()
4ea430fc4cb5a6e8e3a34d334bdaeafbe82a105f
ctec121-spring19/spring-2019-final-project-MichaelLionHart
/src/Controller.py
2,298
3.71875
4
# Controller.py # # For TicTacToe from View import * from Model import * class Controller: def __init__(self): self.v = View() self.m = Model(self.v) def play(self): done = False while not done: self.playAGame() # ask for input from user to determine whether to keep playing # if user clicks, continue self.v.setMessage('Click to start a new game') x = self.v.click() if x is True: done = False else: done = True # outer loop that just says play a game and do you want to play another def playAGame(self): done = False personA_turn = True self.v.setMessage("Player A's Turn") while not done: cell = self.v.getClickPoint() print('get click point finished: ', cell) # determine if cell is already in gameBoard (True if not) if self.m.returnGameBoard(cell) is True: # if it's player A's turn, print 'X' and populate gameBoard with an 'X' if personA_turn is True: self.m.populateBoard(cell, 'X') # if not, print 'O' and populate gameBoard with an 'O' else: self.m.populateBoard(cell, 'O') # if cell is already taken, tell user to pick another cell else: self.v.setMessage("please choose a valid cell") # is there a winner? if self.m.winner() is True: # if so, print winning message and end game print('winner') self.v.setMessage("Winner!") done = True # is board full? if self.m.boardFull() is True: self.v.setMessage("It is a draw") done = True # is it player A's turn? if personA_turn is True: personA_turn = False self.v.setMessage("Player B's Turn") else: personA_turn = True self.v.setMessage("Player A's Turn") pass def ControllerTest(): c = Controller() c.play() pass if __name__ == "__main__": ControllerTest()
1d5b419c17dd164b858e05ec3ae86960786e5617
SelyanKab/FormationPython
/Variables/formationPython.py
1,124
3.890625
4
# Programme d'introduction des variables, conditions et expressions logiques. print("Début du programme") # Definition de la variable a. input() permet de lire une valeur à partir du clavier. a = input("Quel est votre âge: ") nom = input("Quel est vore nom? ") # la commande if permet de tester si une condition est satisfaite. # int(a) permet de trasformer la caractère a qui est lu en un nombre entier. if int(a) >= 18: # Si la condition est satisfaite, on exécute ce bloc. # print() permet d'afficher à l'écran print( nom + " vous êtes majeur" ) # le + permet de cancaténer deux chaines de caractères p = input("Quelle est la catégorie de votre permis? ") if int(p) == 1: print("Vous pouvez conduire une voiture") else: if int(p) == 2: print("Vous pouvez conduire un camion") else: print("Vous ne pouvez pas conduire") print("J'en ai marre") else: # Si la condition n'est pas satisfaite, on exécute ce bloc. print("Vous êtes mineur") print("Je suis à l'intérieure de else") print("Fin du programme")
133ae19bc93ea511c390ce2b549a7f2180f393c5
IqbalHadiSubekti/Latihan01
/latihan_baru.py
333
3.78125
4
hari = int(input("masukkan nilai X = ")) if (hari == 0): print("Minggu") elif (hari == 1): print("Senin") elif (hari == 2): print("Selasa") elif (hari == 3): print("Rabu") elif (hari == 4): print("Kamis") elif (hari == 5): print("Jum'at") elif (hari == 6): print("Sabtu") else: print("Kode salah")
a48ade9983ad92588ef6c75dfd62c3bf27ee9ba3
zhaolixiang/python_cookbook
/15-1.py
886
3.5625
4
myList=[1,4,-5,10,-7,2,3,-1] print([n for n in myList if n>0]) print([n for n in myList if n<0]) myList=[1,4,-5,10,-7,2,3,-1] pos=(n for n in myList if n >0) for x in pos: print(x) values=['1','2','-3','-','4','N/A','5'] def is_int(val): try: x=int(val) return True except ValueError: return False ivals=list(filter(is_int,values)) print(ivals) import math myList=[1,4,-5,10,-7,2,3,-1] print([math.sqrt(n) for n in myList if n>0]) myList=[1,4,-5,10,-7,2,3,-1] print([n if n>0 else 0 for n in myList]) print([n if n<0 else 0 for n in myList]) from itertools import compress address=[ '5412 N CLARK1', '5148 N CLARK2', '5800 E CLARK3', '2122 N CLARK4', '5645 M CLARK5', '1060 W CLARK6', ] counts=[0,3,10,4,1,7] #构建一个列表,它相应的count值要大于5 more5=[n>5 for n in counts] print(more5) print(list(compress(address,more5)))
d492257a5df16fe4a4611537af8a76d99cecf731
Arihaan/AutomateTheBoringStuff
/ChessDictionaryValidator.py
2,585
3.9375
4
def is_valid_chess_board(board): valid_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] # array with valid position letters valid_pieces = ['king', 'queen', 'bishop', 'knight', 'rook', 'pawn'] # array with chess piece types black_pieces = 0 white_pieces = 0 total_pieces = 0 bpawns = 0 wpawns = 0 bking = 0 wking = 0 # the above code and variables may be shortened by the use of a dictionary (unfortunately not fluent enough in them) # validating chess piece positions and quantity for position in board.keys(): total_pieces += 1 if int(position[0]) < 1 or int(position[0]) > 8: return "Improper Chess Board: Position " + position + " exceeds board limit (<1 or >8)" elif position[1] not in valid_letters: return "Improper Chess Board: Position " + position + " exceeds board limit (>h)" elif total_pieces > 16: return "Improper Chess Board: Over 16 pieces on the board" for piece in board.values(): # validating chess piece names if piece[0] != 'b' and piece[0] != 'w': return "Improper Chess Board: Piece " + piece + " is neither black or white" elif piece[1:] not in valid_pieces: return "Improper Chess Board: Piece " + piece + " is not a valid chess piece" # validating chess piece quantity by color if piece[0] == 'b': black_pieces += 1 if black_pieces > 16: return "Improper Chess Board: Over 16 black pieces" elif piece[0] == 'w': white_pieces += 1 if white_pieces > 16: return "Improper Chess Board: Over 16 white pieces" # validating quantity of kings and pawns if piece == 'bking': bking += 1 if bking > 1: return "Improper Chess Board: More than 1 Black King piece" elif piece == 'wking': wking += 1 if wking > 1: return "Improper Chess Board: More than 1 White King piece" elif piece == 'bpawn': bpawns += 1 if bpawns > 8: return "Improper Chess Board: More than 8 Black Pawn pieces" elif piece == 'wpawn': wpawns += 1 if wpawns > 8: return "Improper Chess Board: More than 8 White Pawn pieces" return "Valid Chess Board" try_board = {'2h': 'bking', '3b': 'bpawn', '2a': "wking"} print(is_valid_chess_board(try_board))
d3d49a3002f09cb4ab3123a874a61fe9124e007a
JackieLeeTHU11/CodeNotes
/algorithms/sort/quicksort.py
955
3.6875
4
# coding=utf-8 def partition(targetlist, low, high): x = targetlist[low] while (low<high): # print low, high while ((low<high) & (targetlist[high]<=x)): high -= 1 targetlist[low] = targetlist[high] while ((low<high) & (targetlist[low]>=x)): low += 1 targetlist[high] = targetlist[low] targetlist[low] = x return low, targetlist # search the kth larger number def search(targetlist, i, j, k): if (i<=j): q, _ = partition(targetlist, i, j) print q if (q-i+1==k): print "the", q+1, "th max number is: ", targetlist[q] return elif (q-i+1<k): search(targetlist, q+1,j,k-(q-i+1)) else: search(targetlist, i, q-1, k) print targetlist # quick sort code def quicksort(targetlist, low, high): if low<high: q,_=partition(targetlist,low,high) quicksort(targetlist,low,q) quicksort(targetlist,q+1,high) # main l1 = [4,2,6,10,1,8,23,9,6,4,0,12] search(l1, 0, len(l1)-1, 4) quicksort(l1,0,len(l1)-1) print l1
717ff76397dd46ab2fb7b4357846bd0eb0ff65e9
daydaychallenge/leetcode-python
/00516/longest_palindromic_subsequence.py
1,415
3.75
4
class Solution: def longestPalindromeSubseq(self, s: str) -> int: """ #### [516. Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. **Example 1:** Input: ``` "bbbab" ``` Output: ``` 4 ``` One possible longest palindromic subsequence is "bbbb". **Example 2:** Input: ``` "cbbd" ``` Output: ``` 2 ``` One possible longest palindromic subsequence is "bb". Parameters ---------- s: str Returns ------- int Examples -------- >>> sol = Solution() >>> sol.longestPalindromeSubseq('bbbab') 4 >>> sol.longestPalindromeSubseq('cbbd') 2 Notes ----- References --------- """ d = {} def dp(s): if s not in d: max_len = 0 for c in set(s): l, r = s.find(c), s.rfind(c) max_len = max(max_len, 1 if l == r else 2+dp(s[l+1:r])) d[s] = max_len return d[s] return dp(s)
d21778fa798669d232aae653697e62ca33bc32b9
wangzhe/rep_chain_validator
/validator.py
3,785
3.515625
4
from abc import abstractmethod class AbstractValidator: validator_successor = None def set_validator_successor(self, validator_successor): self.validator_successor = validator_successor def validate(self, some_behavior): result = self.validate_self_logic(some_behavior) if result: if self.validator_successor is not None: return self.validator_successor.validate(some_behavior) return result @staticmethod def contain_all_element(full_list, sub_list): return all(elem in full_list for elem in sub_list) @abstractmethod def validate_self_logic(self, reservation): pass class FromTypeValidator(AbstractValidator): from_type_list = ["a", "b", "c", "d"] def validate_self_logic(self, some_behavior): print("go for from type validator") if some_behavior is None: print("some behavior class error") return False # Check the full list contain both under type and exclude type under_from_type_list = some_behavior.under_from_type_list exclude_from_type_list = some_behavior.exclude_from_type_list if (under_from_type_list is None) or (exclude_from_type_list is None): print("some regarding belong type not set") return False if not self.contain_all_element(self.from_type_list, under_from_type_list): print("I find some from under_type, I don't know") return False if not self.contain_all_element(self.from_type_list, exclude_from_type_list): print("I find some exclude type, I don't know") return False # Check no overlap under_from_type_set = set(under_from_type_list) exclude_from_type_set = set(exclude_from_type_list) if under_from_type_set & exclude_from_type_set: print("Oh no, overlap") return False # Chech union is full list from_type_set = set(self.from_type_list) union_under_n_exclude = under_from_type_set.union(exclude_from_type_set) if from_type_set != union_under_n_exclude: print("Oh no, some type are not include") return False return True class ToTypeValidator(AbstractValidator): to_type_list = ["x", "y", "z"] def validate_self_logic(self, some_behavior): print("go for to type validator") if some_behavior is None: print("some behavior class error") return False # Check the full list contain both under type and exclude type under_to_type_list = some_behavior.under_to_type_list exclude_to_type_list = some_behavior.exclude_to_type_list if (under_to_type_list is None) or (exclude_to_type_list is None): print("some regarding belong type not set") return False if not self.contain_all_element(self.to_type_list, under_to_type_list): print("I find some to under_type, I don't know") return False if not self.contain_all_element(self.to_type_list, exclude_to_type_list): print("I find some exclude type, I don't know") return False # Check no overlap under_to_type_set = set(under_to_type_list) exclude_to_type_set = set(exclude_to_type_list) if under_to_type_set & exclude_to_type_set: print("Oh no, overlap") return False # Chech union is full list from_type_set = set(self.to_type_list) union_under_n_exclude = under_to_type_set.union(exclude_to_type_set) if from_type_set != union_under_n_exclude: print("Oh no, some type are not include") return False return True
6180c218ea51caf666dd80df0930f1e31f14051a
apbetioli/10DaysOfStatistics
/Day1/standard_deviation/standard_deviation.py
471
3.828125
4
from math import pow, sqrt def mean(n, numbers): sum = 0 for num in numbers: sum += float(num) return sum / n def standard_deviation(n, numbers): u = mean(n, numbers) sum = 0 for num in numbers: sum += pow(float(num)-u, 2) sd = sqrt( sum / n ) return sd def main(): n = int(raw_input()) numbers = raw_input().split() print "%.1f" % standard_deviation(n, numbers) main()
70951e1efa2a7e10255d4e20855f168ee8b3c290
yashasvi-goel/Algorithms-Open-Source
/Encryption/RSA/Python/RSA.py
1,127
4.46875
4
# Code for RSA Encryption and Decryption def RSA(): p = int(input("Enter prime value for p: ")) q = int(input("Enter prime value for q: ")) # Calculate the public key n = p * q print("Public key is: " + str(n)) e = int(input("Enter a small exponent and greater then 1: ")) h = (p - 1)*(q - 1) # Can be any constant value k = 2 # Calculating the private key pri = int((k * h + 1) / e) print("Private key is: " + str(pri)) T = "" text = input("Enter Letters to encrypt: ") # Changing the entered letters into ints # Combing the ints and changing them into a string # Ex: Entered: HI -> H = 8 and I = 9 then string = 89 for i in text: number = ord(i) - 64 T += str(number) print(i + " value is: " + T) # Changing the string of the combined ints into a int T = int(T) # Encrypting the letters based on the public key encr = (T**e) % n print(encr) # Decrypting the letters based on the private key Decr = (encr**pri) % n print("The decrypted value is: " + str(Decr) + " which is " + text) RSA()
92fd06bc410319d8c99620b4ce09b8a556992542
marwabatha/Design-and-Programming-Assignment
/server .py
1,316
3.640625
4
#The server recieves a message from the client and reads a text file and sends the data to the client. import socket # Import socket module port = 60000 # Reserving an unreserved port. ssocket = socket.socket() # Create a socket object called ssocket host = socket.gethostname() # Get local machines name for host. ssocket.bind((host, port)) # Binding to the port. ssocket.listen(5) # Waiting for the clients connection. print ('Job seeker waiting') while True: connect, addr = ssocket.accept() # Establishing connection with job creator. print ('Got connection from', addr) data = connect.recv(1024) print('Job received', repr(data)) #Job confirmation. filename='mytext.txt' f = open(filename,'rb') #Opening file. x = f.read(1024) #Reading a file while (x): #While data exist run. connect.send(x) print('Sent data: ',repr(x)) #Prints the data present x x = f.read(1024) #Read from file in variable x f.close() print('Done receiving jobs') #print message. connect.send('Thank you for connecting'.encode()) connect.close()
8f8fc839541388a7af8e9a821902e5a785a4091c
wait17/data_structure
/10.7/01.升级链表代码.py
4,545
3.828125
4
class Node: def __init__(self, data, next1=None): # next1=None 可不写(写next参数,则必须给定默认值,否则次次需要传入值),不写的话,需要在下面(self.next)设置默认值 self.data = data # 前一个data是属性,后一个data是传入的值(即上方的data) self.next = next1 def __repr__(self): # return "node({})".format(self.data) return f"node({self.data})" # 把一个对象表示成字符串形式 # n = Node(1) # print(n) # 查/索引 # 增 插入 # insert方法: 五种情况 # 1 下标越界 # 2 空链表 # 3 从头插入 # 4 从尾插入 # 5 中间插入 # 删 # 改 # 反转链表 # 返回值(表示) class LinkList: def __init__(self): # 初始化链表(定义属性) # 多了尾属性和长度属性,操作更方便 self.head = None # 维护头结点 self.tail = None # 维护尾结点 self.size = 0 # 维护链表长度 def get(self, index): # 下标是下标, 长度(size)是长度, 下标通常比长度小一 current = self.head if current is None: raise Exception("空链表") elif index >= self.size: raise IndexError("Index out of range!") for _ in range(index): # 从1开始,对应正常思维的下标,index为3, 取到第三个节点; 若从0开始,则是代码思维的下标,index为3, 取到第四个节点 --> 代码思维 # 此时从0开始(联系size属性),对应下边代码 # 循环index - 1次 current = current.next return current def insert(self, index, data): new_node = Node(data) if index < 0 or index > self.size: # 去掉index > self.size, 则下边下标大于长度时可以插入新节点(尾部插入) raise IndexError("下标越界") else: if self.size == 0: # 空链表 self.head = new_node self.tail = new_node elif index == 0: # 从头插入 new_node.next = self.head self.head = new_node elif index == self.size: # 从尾插入 条件改为index >= self.size, 则下标超出的也能插入到尾部 self.tail.next = new_node self.tail = new_node else: # 中间插入 prev = self.get(index - 1) new_node.next = prev.next # 链表思想: 先安排后事, 再放手一搏 prev.next = new_node self.size += 1 # 插入节点后, 维护长度属性 def remove(self, index): if index < 0 or index >= self.size: raise IndexError("索引越界") if self.size == 0: raise Exception("The linked list is empty!") else: if index == 0: # 删除头 remove_node = self.head self.head = self.head.next remove_node.next = None elif index == self.size - 1: # 删除尾 prev = self.get(index - 1) remove_node = self.tail prev.next = None self.tail = prev else: prev = self.get(index - 1) remove_node = prev.next prev.next = prev.next.next remove_node.next = None self.size -= 1 return remove_node # 根据python标准, 一般删除函数的返回值是被删除的元素 def reverse(self): pre = None current = self.head while current: # 反转链表三大步四小步 next_node = current.next current.next = pre pre = current current = next_node self.tail = self.head self.head = pre def set(self, index, data): current = self.head for _ in range(index): current = current.next current.data = data def __repr__(self): current = self.head string_repr = "" while current: # 把一个对象表示成字符串形式, 但形成方式特殊(遍历链表后拼接) string_repr += "{}-->".format(current) # 箭头只是可视化表示,内部不是靠线或者箭头连接,靠前一个储存下一个的内存地址联系 current = current.next return string_repr + "END" ll = LinkList() ll.insert(0, 1) ll.insert(0, 2) ll.insert(2, 3) ll.insert(2, 4) ll.remove(2) print(ll.get(2)) ll.set(1, 5) ll.reverse() print(ll)
718960f27c4aec47c2f5189340b3f7593df85beb
FraGoTe/pythonCourse
/firstWeek/marcardores.py
211
3.578125
4
a = 45 b = 56 print ('su edad es', a) print ('la edad es', a, ' de sofia') print ('Con marcadores su edad es %d'%b) print ('Su sueldo es %f'%b) a = 'este es a' print (a) a, b = b, a print (a) print (b)
f6deb8da0c5344a80f95bf74e3be2744250948e9
nbmillon/project
/blocks.py
481
4.09375
4
#for i in range (1,13): # print("No. {} squared is {} and cubed is {:4}".format(i,i**2,i**3)) name = input("what's your name: ") age = int(input("How are old are you, {0} ".format(name))) if age >= 18: print("You can vote") print("Please put an x in the box") else: print("Please come back in {0} years".format(18-age)) if age < 18: print("Please come back in {0} years".format(18-age)) else: print("You can vote") print("Please put an x in the box")
95abc4c7a8115492b412f97986dbac48e05eb1ee
jaford/thissrocks
/Python_Class/py3intro3day 2/ANSWERS/set_sieve.py
356
3.8125
4
#!/usr/bin/env python import sys if len(sys.argv) == 2: limit = int(sys.argv[1]) else: limit = 50 flags = set() print(2, end=' ') # we know 2 is prime for num in range(3, limit, 2): # only test odd numbers if num not in flags: print(num, end=' ') for x in range(num, limit, num): flags.add(x)
bda493431553d64db480394dfa6ec1f6db9b95af
andreaspts/DL_DEEPNET_vs_CONVNET_on_MNIST
/CONVNET_vs_CONVNET.py
8,696
4.125
4
''' Created on 12.03.2019 @author: Andreas In this exercise we use Keras to analyze the MNIST dataset. To this aim, we use two CONVNETs and compare the results. For each unit (Preparation of the data, Defining and training the model, Evaluating the model and Presentation of the results) we may repeat importing of packages for overview purposes. Parts of the code are inspired by the book: Deep learning with python by F. Chollet, (Manning, 2018); ''' # -------------- Preparation of the data for the CONVNET1 -------------- # We initialize keras and mount the required packages, e.g. the data set itself import keras from keras.datasets import mnist from keras.utils import to_categorical # needed to encode the labels categorically # We get the training images and labels as well as the test images and labels (train_images, train_labels), (test_images, test_labels) = mnist.load_data() train_imagesCONVNET1 = train_images.reshape((60000, 28, 28, 1)) # images are stored in an array of shape (60000, 28, 28) of type unit8 with values in the interval [0,255] train_imagesCONVNET1 = train_imagesCONVNET1.astype('float32') / 255 # transforming the array to type float32 with values in the interval to [0,1] test_imagesCONVNET1 = test_images.reshape((10000, 28, 28, 1)) # see above test_images = test_imagesCONVNET1.astype('float32') / 255 # see above train_labelsCONVNET1 = to_categorical(train_labels) test_labelsCONVNET1 = to_categorical(test_labels) # -------------- Preparation of the data for the CONVNET2 -------------- # We initialize keras and mount the required packages, e.g. the data set itself import keras from keras.datasets import mnist from keras.utils import to_categorical # needed to encode the labels categorically # We get the training images and labels as well as the test images and labels (train_images, train_labels), (test_images, test_labels) = mnist.load_data() train_imagesCONVNET2 = train_images.reshape((60000, 28, 28, 1)) # images are stored in an array of shape (60000, 28, 28) of type unit8 with values in the interval [0,255] train_imagesCONVNET2 = train_imagesCONVNET2.astype('float32') / 255 # transforming the array to type float32 with values in the interval to [0,1] test_imagesCONVNET2 = test_images.reshape((10000, 28, 28, 1)) # see above test_images = test_imagesCONVNET2.astype('float32') / 255 # see above train_labelsCONVNET2 = to_categorical(train_labels) test_labelsCONVNET2 = to_categorical(test_labels) # -------------- Defining and training the CONVNET1 model -------------- from keras.preprocessing import sequence from keras import layers from keras import models from keras.callbacks import TensorBoard from time import time # Setting up the model architecture: A CONVNET with maxpooling layers and 2 fully connected layers with softmax output modelCONVNET1 = models.Sequential() modelCONVNET1.add(layers.Conv2D(32,(3,3), activation = 'relu', input_shape = (28,28,1))) modelCONVNET1.add(layers.MaxPooling2D((2,2))) modelCONVNET1.add(layers.Conv2D(64, (3,3),activation ='relu')) modelCONVNET1.add(layers.MaxPooling2D((2,2))) modelCONVNET1.add(layers.Conv2D(64, (3,3),activation = 'relu')) modelCONVNET1.add(layers.Flatten()) modelCONVNET1.add(layers.Dense(64, activation = 'relu')) modelCONVNET1.add(layers.Dense(10,activation='softmax')) # Print the model architecture modelCONVNET1.summary() # Compilation of the mode: adding optimizer and loss for back propagation # loss function: specifies how the network measures its performance on the training set # optimizer: providing a mechanism by which the network will update itself based on the data it is fed with and the loss function # another optimizer could be the rmsprop # accuracy metric: to monitor the fraction of images which were correctly classified modelCONVNET1.compile(optimizer='Adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) # Tensorboard callback, here optional #callbacks = [TensorBoard(log_dir = 'logs/{}'.format(time()),histogram_freq=1, # write_graph=True, write_images=True,)] # training the network via the fit method historyCONVNET1 = modelCONVNET1.fit(train_imagesCONVNET1, train_labelsCONVNET1, epochs = 30, batch_size = 64, validation_split=0.1)#, callbacks=callbacks) # -------------- Defining and training the CONVNET2 model -------------- from keras.preprocessing import sequence from keras import layers from keras import models from keras import regularizers from keras.callbacks import TensorBoard from time import time # Setting up the model architecture: A CONVNET with maxpooling layers and 2 fully connected layers with softmax output modelCONVNET2 = models.Sequential() modelCONVNET2.add(layers.Conv2D(32,(3,3), input_shape = (28,28,1))) modelCONVNET2.add(layers.BatchNormalization()) modelCONVNET2.add(layers.Activation("relu")) modelCONVNET2.add(layers.MaxPooling2D((2,2))) modelCONVNET2.add(layers.Conv2D(64, (3,3)))#,activation ='relu')) modelCONVNET2.add(layers.BatchNormalization()) modelCONVNET2.add(layers.Activation("relu")) modelCONVNET2.add(layers.MaxPooling2D((2,2))) modelCONVNET2.add(layers.Conv2D(64, (3,3)))#,activation ='relu')) modelCONVNET2.add(layers.BatchNormalization()) modelCONVNET2.add(layers.Activation("relu")) modelCONVNET2.add(layers.Flatten()) modelCONVNET2.add(layers.Dense(64, activation = 'relu')) #kernel_regularizer=regularizers.l2(0.001), #modelCONVNET2.add(layers.Dropout(0.2)) modelCONVNET2.add(layers.Dense(10,activation='softmax')) # Print the model architecture modelCONVNET2.summary() # Compilation of the mode: adding optimizer and loss for back propagation # loss function: specifies how the network measures its performance on the training set # optimizer: providing a mechanism by which the network will update itself based on the data it is fed with and the loss function # another optimizer could be the rmsprop # accuracy metric: to monitor the fraction of images which were correctly classified modelCONVNET2.compile(optimizer='Adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) # Tensorboard callback, here optional #callbacks = [TensorBoard(log_dir = 'logs/{}'.format(time()),histogram_freq=1, # write_graph=True, write_images=True,)] # training the network via the fit method historyCONVNET2 = modelCONVNET2.fit(train_imagesCONVNET2, train_labelsCONVNET2, epochs = 30, batch_size = 64, validation_split=0.1)#, callbacks=callbacks) # -------------- Evaluating the CONVNET1 model -------------- # We are of course evaluating the model on the test set. test_lossCONVNET1, test_accCONVNET1 = modelCONVNET1.evaluate(test_imagesCONVNET1, test_labelsCONVNET1) print("The test accuracy of the CONVNET1 model amounts to: ",test_accCONVNET1*100 ,"%") # -------------- Evaluating the CONVNET2 model -------------- # We are of course evaluating the model on the test set. test_lossCONVNET2, test_accCONVNET2 = modelCONVNET2.evaluate(test_imagesCONVNET2, test_labelsCONVNET2) print("The test accuracy of the CONVNET2 model amounts to: ",test_accCONVNET2*100 ,"%") #------------------PRESENTATION OF RESULTS (PLOT OF ACCs)--------------- import matplotlib.pyplot as plt accCONVNET1 = historyCONVNET1.history['acc'] val_accCONVNET1 = historyCONVNET1.history['val_acc'] lossCONVNET1 = historyCONVNET1.history['loss'] val_lossCONVNET1 = historyCONVNET1.history['val_loss'] accCONVNET2 = historyCONVNET2.history['acc'] val_accCONVNET2 = historyCONVNET2.history['val_acc'] lossCONVNET2 = historyCONVNET2.history['loss'] val_lossCONVNET2 = historyCONVNET2.history['val_loss'] # we run over the same number of epochs for both model epochs = range(1, len(accCONVNET1) + 1) plt.plot(epochs, accCONVNET1, '--ro', label='CONVNET1 Training acc') plt.plot(epochs, val_accCONVNET1,'--rx', label='CONVNET1 Validation acc') plt.plot(epochs, accCONVNET2, '--bo', label='CONVNET2 (Batch Normalization) Training acc') plt.plot(epochs, val_accCONVNET2, '--bx', label='CONVNET2 (Batch Normalization) Validation acc') # plotting of training and validation accuracies plt.title('Training and validation accuracy') plt.legend() plt.xlabel('epochs') plt.ylabel('accuracy') plt.figure() plt.plot(epochs, lossCONVNET1, '--ro', label='CONVNET1 Training loss') plt.plot(epochs, val_lossCONVNET1, '--rx', label='CONVNET1 Validation loss') plt.plot(epochs, lossCONVNET2, '--bo', label='CONVNET2 (Batch Normalization) Training loss') plt.plot(epochs, val_lossCONVNET2, '--bx', label='CONVNET2 (Batch Normalization) Validation loss') # plotting of training and validation losses plt.title('Training and validation loss') plt.legend() plt.xlabel('epochs') plt.ylabel('loss') plt.show() #--------------------------------------------------------
9de7be6d2ce39a4374b4811f5090c80ae3514707
IsmaelFarah101/week1
/warmup.py
381
4.4375
4
name = input('Enter name here: ') month = input('Enter month here: ') ## this program gets name and month from user and prints out a greeting and the number of words in the name and a Salutation if the month is august print('Hello ' + name) print('This is the length of letters in your name: ', len(name)) if month == 'August' or month == 'august': print('Happy Birth Month')
060d5e6ca38f1945c5520b231582394ca56b0c50
valdot00/hola_python
/18 funciones avanzadas/99_funciones_generadas.py
286
3.671875
4
#funciones generadoras range(0,11) print(range(0,11)) for numero in range(0,11): print(numero) def pares (maximo): for numero in range(maximo): if (numero % 2 == 0): yield numero maximo = 11 for numero in pares(maximo): print(numero)
7950880877c478fabb82e03aee7a3884dc53f1aa
NagahShinawy/problem-solving
/geeksforgeeks/lists/ex18.py
493
4.1875
4
""" Given a list of numbers, write a Python program to print all even numbers in given list. Example: Input: list1 = [2, 7, 5, 64, 14] Output: [2, 64, 14] Input: list2 = [12, 14, 95, 3] Output: [12, 14] """ def find_evens(numbers): # using list comp return [num for num in numbers if num % 2 == 0] def find_evens2(numbers): # using filter return list(filter(lambda num: num % 2 == 0, numbers)) print(find_evens([2, 7, 5, 64, 14])) print(find_evens2([2, 7, 5, 64, 14]))
c8be927b19ae551012aca8cd8cbee2b616a8c912
apsz/python-learning
/First Chapter/awful_poetry.py
609
3.609375
4
#!/usr/bin/python3 import random ARTICLES = ('the', 'a', 'an') SUBJECTS = ('cat', 'dog', 'man', 'woman') VERBS = ('sang', 'ran', 'jumped') ADVERBS = ('loudly', 'quietly', 'well', 'badly') SENTENCE_TYPE = ('asva', 'asv') def main(): for i in range(5): sentence_type = random.choice(SENTENCE_TYPE) if sentence_type == 'asva': print(random.choice(ARTICLES), random.choice(SUBJECTS), random.choice(VERBS), random.choice(ADVERBS)) else: print(random.choice(ARTICLES), random.choice(SUBJECTS), random.choice(VERBS)) main()
6f6e41279b9bcbbf12ee255c06417cbb8b6f2d84
lensabillion/CS487
/posetiveSummation.py
1,012
3.859375
4
def sumOfPosetive(): firstnumber =input("enter the first number") secondnumber=input("enter the second number") if len(firstnumber)<len(secondnumber): smallernumber = firstnumber largernumber = secondnumber else: smallernumber =secondnumber largernumber = firstnumber i=len(largernumber)-1 digit_difference=len(largernumber)-len(smallernumber) if len(largernumber)-digit_difference>0: for j in range(0,digit_difference): smallernumber = "0" +smallernumber total= "" carry =0 summation = 0 while i >= 0 : num1 = int(largernumber[i]) num2 = int(smallernumber[i]) summation = num1+num2+carry carry =summation // 10 summation = summation % 10 total =str(summation)+total i=i-1 if carry!=0: total = str(carry)+total return total print(sumOfPosetive())
d3dc69ae4179039d41029e5ceb5ac8905cc16269
haobinzheng/ixia_automation
/dynamic.py
708
3.703125
4
#Given a list of integers and another integer Y, find all subset of the list that add up to Y. For example, array = [1,2,-1,5,10,22,5,8,-3], Y = 5 a = [1,2,-1,5,10,22,5,8,-3] Y=5 # size == 1: [1] [2] [-1] [5] [10] [22] [5] [8] [-3] # size ==2: [1,2] [1,-1] [1,5] [1,10] [1,22] .... # [2,-1] [2,5] [2,10] [2,22] [2,5].... # size ==3: array = [1,2,-1,5,10,22,8,-3] def sublist(array): if len(array) == 0: return [[]] final = [] first = array[0] rest = array[1:] temp = sublist(rest) for i in temp: final.append([first] + i) final.extend(temp) return final subs = sublist(array) for sub in subs: if sum(sub) == 5: print(sub)
0eeb8959022245f1de7be32e3e8dc7a31fd5f77a
prsiik/python-sem-1
/laba 2/11(butterfly).py
148
3.5625
4
import turtle as tr tr.shape('turtle') tr.left(90) n=50 def butterfly(n): tr.circle(n) tr.circle(-n) x=1 while x<=20: butterfly(n) n+=5 x+=1
beb8d61f282c1f074922a2b92e2448c2499cf04a
mkioga/32_python_Blackjack
/Import_test.py
21,469
4.3125
4
# ======================================================== # Import_test.py ==> Importing Techniques # ======================================================== # We can include Blackjack program in another program # We will import "Blackjack1.py" and see how it runs # import Blackjack1 # NOTE we only use this for Blackjack1. We comment them out when doing Blackjack2 # We also need to have at least one line of code in the program. So we will use print(__name__) # We will discuss about print(__name__) later # print(__name__) # NOTE we only use this for Blackjack1. We comment them out when doing Blackjack2 # When we run this program with only above two lines, it automatically runs the "Blackjack1" code # And we are able to play the game just as if we ran the "Blackjack1" file itself # Also note that the print(__name__) is only executed after you close the Blackjack window # NOTE: code imports and runs the "Blackjack1" code # But we would like for it to just import the program and not execute the code immediately, so we can be able to # Call the code to execute it when we want # In this example, we may want the main program (import_test) to provide a menu of games and then the user can # choose the game they want and execute it. # When you import a python module, its code is loaded into memory and then executed. # This is why the blackjack game executed when we imported it. # Here is the link to read more about the import system # https://docs.python.org/3/reference/import.html # ====================================== # Calling python file from command line # ====================================== # if you want to run imported python module in command line (cmd), you can use code similar to this # C:\Users\moe\Documents\Python\IdeaProjects\32_Blackjack> <<=== Make sure to reference correct directory # C:\Users\moe\Documents\Python\IdeaProjects\32_Blackjack>dir # 03/25/2018 12:24 PM 13,656 Blackjack1.py <<=== Python file exists here # C:\Users\moe\Documents\Python\IdeaProjects\32_Blackjack> # C:\Users\moe\Documents\Python\IdeaProjects\32_Blackjack>python -m Blackjack1.py <<== It will run # 8.6 # cardspng/01_of_clubs.png # cardspng/02_of_clubs.png # cardspng/03_of_clubs.png # ====================================== # Executing Module only when we run it # ====================================== # Now in our case, we want to only execute the Blackjack code when we run the module # Importing a module sorts out name spaces and executes code # One thing that happens is that an attribute (__main__) of the module called is said to be the name of the module. # This is the file name for that path or extension # When a python module is executed as a script, the name is set to __main__ # you can see this when you run the command. It prints __main__ (NOTE: Not __name__) # We can also see this by printing out an attribute before our code runs # We can go to "Blackjack1.py" file and add "print(__name__)" right after "def shuffle" function # Test 1 # When we run "Import_test.py" when "print(__name__) is not activated in "Blackjack1.py" # We get result of __main__ after program ends # Test 2 # When we run "Import_test.py" when "print(__name__) is activated in "Blackjack1.py" # We get result of "Blackjack1" right after version 8.6 and then __main__ after program ends # Therefore as a result of this, preventing the code from executing when the module is imported becomes very easy # We just have to check the value of the name attribute and only execute the code if it has the value __main__ (in this case) # So we go to "Blackjack1.py" and make test to say if __name__ equals __main__, then we can run the program # This will also be done after module "def shuffle" in this case i.e. before the main program # Test 3 # With test "if __name__ == "__main__" activated in "Blackjack1.py", if we run the imported code on "Import_test.py" # We only get __main__ showing up after version 8.6 and the code does not execute. # VITAL TO UNDERSTAND # The program not running automatically means that the import is working correctly i.e. not running automatically # When we import "Blackjack1.py" into "Import_test.py", its name is "Blackjack1" (Test 2 above) and not "__main__" # Therefore it will fail test ==> "if __name__ == "__main__" and hence not execute the code under this test. # That is how we make sure imported modules don't run automatically. # So we are able to import the code and not execute it automatically # ======================================= # How to run code that has been imported # ======================================= # In this example, since we have now imported "Blackjack1.py", we can try to run it using command "Blackjack1.new_game()" # This gives an error "'dealer_card_frame' is not defined" # This is because the code after "if __name__ == "__main__" is not running, hence all these variables e.g. dealer_card_frame # Are not defined # Blackjack1.new_game() # Running code using this command gives error at this time # ================= # blackjack2 # ================= # ============================== # How to resolve this issue # ============================== # We will do this in "Blackjack2.py" so as to preserve "Blackjack1.py" # So you can comment out "import Blackjack1" and "print(__name__) above # The way to resolve this is to decide which bits of the "Blackjack2.py" module should be executed # when the module is imported and then move the test for __main__ to allow that to happen # So we will need to change the "Blackjack1.py" module to include a function called "play" # that is resposible for "running the code that starts the game". # NOTE that "running the code that starts the game" is not the initialization i.e. the code after the "mainWindow = tkinter.Tk()" # Then we will test if the "Play" function can be used to run the game when it is imported # Now we go to "Blackjack2.py" # NOTE: We want this initialization to be executed on "Import_test.py" when it gets imported (code after test for __main__) # We will create a new function called "play" in "Blackjack2.py". See explanation there # import Blackjack2 # # print(__name__) # We will call the play function using this command. # NOTE we will not use new_game() anymore # When we run "Import_test.py" now, it works perfectly. # NOTE: if you comment th "Blackjack2.play()" comment and run code, you will see the program does not run the game # Blackjack2.play() # ====================== # print card placements # ====================== # you can also print card placements from "Import_test.py" using "print(Blackjack2.cards)" # When we print the cards, it gives you card placements like "[('01', <tkinter.PhotoImage object at 0x0553FD10>), # In "Blackjack2.py", we used command "print(cards)" # We can do same thing here using "print(Blackjack2.cards)" # print(Blackjack2.cards) # =============== # Blackjack3 # =============== # =============================================== # Creating module to put code repeated in # "new_game" and "play" modules in "Blackjack2.py # =============================================== # We know that this code below is in both modules "new_game" and "play" in "Blackjack2.py # We want to create a function to put this code so it is just called in other modules instead of being repeated # deal_player() # one card for player # dealer_hand.append(deal_card(dealer_card_frame)) # one card for dealer # dealer_score_label.set(score_hand(dealer_hand)) # Displays the Card value of dealer in screen # deal_player() # one card for player # We will do this in "Blackjack3.py" # import Blackjack3 # Imports Blackjack3 # print(__name__) # Prints the name of the program. __main__ # Blackjack3.play() # Calls the Play module in Blackjack3.py # print(Blackjack3.cards) # Optional. Prints card positions e.g. ('01', <tkinter.PhotoImage object at 0x050CFF30>) # ============================================== # Importing and Underscores in Variable names # ============================================== # ============ # Blackjack4 # ============ # We will talk about underscores in variable names # When we CTRL + click a python module, it takes you to its source code and you notice # that many object names starts and/or end with underscore (or double underscores) (__) # We have previously discussed ending a name with a single underscore (_) when we looked at the # spinbox widget in tkinter, and we can set the range of values that appear in the spinbox using # "to" and "from" underscore arguments, but because "from" is a python keyword, we used "from_" instead of just "from" # The convention is to use a single underscore after a name if it would otherwise conflict with a # name that is built into python i.e. python keyword # import Blackjack4 # # print(__name__) # Blackjack4.play() # print(Blackjack4.cards) # ========================== # Other uses of underscores # ========================== # Unlike other languages, python has no concept of "private" or "protected" variables # That means its possible to do things with a module that you probably should not do. # We will demonstrate this with our "Blackjack4" module # It is useful to be able to call play function "Blackjack4.play()" # it is also useful to be able to print the cards list "print(Blackjack4.cards)" to create decks for other games # Beyond that, there is nothing else in the "Blackjack4.py" module that makes any sense to use once it has been imported # There is a "score_hand" function, but that is really very specific to "Blackjack4" and coule not be used to decide # which of two poker hands have been up because its completely different algorithm # In java for example, the "play" function and "cards" would be made available to other programs, everything else would be # Marked "private" so it is hidden and would not actually show # But python does not have any "private" objects, so we can do some silly things after importing "Blackjack4" module # import Blackjack4 # print(__name__) # Here for example, we are going to call "deal_card(dealer_card_frame)" to show you it can be done in python # because python has no private objects. # However this is not a wise thing to do. but we do it here for demonstration # When we run this, the program runs and we now see "dealer" has two cards to begin with instead of one # But only the second card's value is included in the dealer score (instead of the total of both) # This is because we gave access to areas of Blackjack4 game which we would ordinarily not want someone who has # imported the game to access because it is sort of like breaking the game. # This is compounded by the fact that there is nothing in intellij that indicates that we should not be calling this function # Blackjack4.deal_card(Blackjack4.dealer_card_frame) # # Blackjack4.play() # print(Blackjack4.cards) # =========================================== # protected function (defined using _itsname # =========================================== # By convention, starting a name with an underscore (_) indicates that it should be treated as "Protected", # meaning it is not intended to be used outside the module that it exist in. # There is a little more to that when dealing with "Classes" and we will talk about that when looking at object oriented programming. # Import_test 1: Refactor #========================= # We can go back to "Blackjack4 and refactor function "deal_card" and call it "_deal_card" # NOTE that it renames it in both "Blackjack4.py" and in "Import_test.py" # # # import Blackjack4 # print(__name__) # # # NOTE that intellij here gives warning "Access to a protected member _deal_card of a module" # # This is because anything starting with _ is a protected member, hence _deal_card is a protected member # # NOTE that even with this warning, we can still run the program and it works # # Blackjack4._deal_card(Blackjack4.dealer_card_frame) # deal_card renamed here after refactoring # # Blackjack4.play() # print(Blackjack4.cards) # # # So if you find yourself using an object with a name starting with underscore (_), bear in mind that # # it is protected and you should not be accessing it if it exist in a module that you did not write/not in your code. # # # Another point is it is good to import modules as shown e.g. import Blackjack4 # # so that when using functions from imported module, you will specify the module first and then function e.g. Blackjack4.play # # This will easily help you to know that the functions you are using are from the imported module # =========================== # Using import Blackjack4: # ========================== # By default, when using "import Blackjack4", names starting with _ are not imported # There is another implication of using underscore (_) to start up a name # if you use an alternate way of importing Blackjack4, anything with a name starting with # underscore (_) is not actually imported. # We have recommended before that we don't do an import * from a module because all of the names from the imported module # then become part of your module namespace and it is easy to lose track of what name belong to what. # To demonstrate this, we will import "Blackjack4.py" and then display all the global namespaces in "Blackjack4.py" # import Blackjack4 # Here we are trying to print all the global names # Note that after we run this command, it prints first "Global from Blackjack4.py = __name__" # Then gets an error message: RuntimeError: dictionary changed size during iteration # This is because the new variable we have created has altered the dictionary itself. # So we cannot actually use this method to access the globals. # for x in globals(): # print("Global from Blackjack4.py = {}".format(x)) # A solution to this is to take a copy of the globals dictionary and iterate through that. # We make a copy of globals and put it in variable g. # so if we change g, it will not change the original dictionary # # g = sorted(globals()) # # # Then loop through g to access the global names # # for x in g: # print("Global from Blackjack4.py = {}".format(x)) # When we run above code, we get this result and no errors # We can see the list of names is small, all starting with __ # And the only object here is Blackjack4 that we imported. # Global from Blackjack4.py = Blackjack4 # Global from Blackjack4.py = __annotations__ # Global from Blackjack4.py = __builtins__ # Global from Blackjack4.py = __cached__ # Global from Blackjack4.py = __doc__ # Global from Blackjack4.py = __file__ # Global from Blackjack4.py = __loader__ # Global from Blackjack4.py = __name__ # Global from Blackjack4.py = __package__ # Global from Blackjack4.py = __spec__ # ================================================= # importing all using "from Blackjack4 import * " # ================================================= # When importing all using "from Blackjack4 import * " , names starting with _ are not imported # Now we import all modules from Blackjack4 # from Blackjack4 import * # # g = sorted(globals()) # Then loop through g to access the global names # for x in g: # print("Global from Blackjack4.py = {}".format(x)) # We see its importing all the functions and variables from "Blackjack4.py" # Everything in "Blackjack4" module namespace appears in "Import_test" # This includes all names with no underscores, and all that "start" and "end" with two underscores (__) # NOTE: If we created an an object called "cards" in "Import_test.py", then the # object "cards" from "Blackjack4" would not be available because it will be replaced by # the new "cards" object we created. # NOTE that our "_deal_card" function from "Blackjack4" is not imported. # And if you try to use it, you will get an error of "Unresolved reference" # So the python import mechanism takes note of this convention and it will # not import any object that start with underscore (_) when using "import * " # When we import Blackjack4, the objects from the Blackjack4 module are not imported separately # So everything, even names beginning with underscore (_) are available when # prefixing them with Blackjack4. e.g. Blackjack4._deal_card # _deal_card(dealer_card_frame) # We get error "Unresolved reference" on this command # Global from Blackjack4.py = __annotations__ # Global from Blackjack4.py = __builtins__ # Global from Blackjack4.py = __cached__ # Global from Blackjack4.py = __doc__ # Global from Blackjack4.py = __file__ # Global from Blackjack4.py = __loader__ # Global from Blackjack4.py = __name__ # Global from Blackjack4.py = __package__ # Global from Blackjack4.py = __spec__ # Global from Blackjack4.py = button_frame # Global from Blackjack4.py = card_frame # Global from Blackjack4.py = cards # Global from Blackjack4.py = deal_dealer # Global from Blackjack4.py = deal_player # Global from Blackjack4.py = dealer_button # Global from Blackjack4.py = dealer_card_frame # Global from Blackjack4.py = dealer_hand # Global from Blackjack4.py = dealer_score_label # Global from Blackjack4.py = deck # Global from Blackjack4.py = initial_deal # Global from Blackjack4.py = load_images # Global from Blackjack4.py = mainWindow # Global from Blackjack4.py = new_game # Global from Blackjack4.py = new_game_button # Global from Blackjack4.py = play # Global from Blackjack4.py = player_button # Global from Blackjack4.py = player_card_frame # Global from Blackjack4.py = player_hand # Global from Blackjack4.py = player_score_label # Global from Blackjack4.py = random # Global from Blackjack4.py = result # Global from Blackjack4.py = result_text # Global from Blackjack4.py = score_hand # Global from Blackjack4.py = shuffle # Global from Blackjack4.py = shuffle_button # Global from Blackjack4.py = tkinter # ======================== # Double underscore (__) at the start (Not end) # ======================== # Using Double underscore (__) at the "start" of a Name invokes pythons name mangling rules # This convention exist to prevent name clashes when sub classing objects # We will look at this more in object oriented programming. # In our "Blackjack4" module, starting name with two Underscores (__) will not serve any useful purpose # because anything that starts with two underscores (__) automatically starts with one (_) # So "import * " will not import them # =================================================== # Names Starting and Ending with two underscores (__) # ==================================================== # ================================== # Import_test 2: renaming __name__ # ================================== # These names should never be changed. # The names that start and end with two underscores are things you should not be changing # Example is the __name__ that we used to restrict the code when the module was imported. # We will try to change __name__ in "Blackjack4.py" and you will see what happens # we will use ==> __name__ = "__main__" just above "mainWindow = tkinter.Tk()" in "Blackjack4.py" # First we test this before modifying __name__ in "Blackjack4.py". It works fine # import Blackjack4 # Blackjack4._deal_card(Blackjack4.dealer_card_frame) # Blackjack4.play() # After we change __name__ in "Blackjack4.py" and then run code here, first you see window runs fine # But Dealer has only one card instead of two. Meaning the code under "Import_test.py" has not executed. # This is the original effect that we saw when we imported Blackjack. # Because __name__ has been set to __main__, the test that restricts code execution on import is no longer # valid and the code runs when we import the module. # When we close the program window, we get this error: # _tkinter.TclError: can't invoke "label" command: application has been destroyed # This is because by closing the window, we have destroyed all the tkinter objects so that nothing works # and the game cannot be played according to the play function # NOTE: Python does not prevent you from modifying these variables # But if you modify them, the results are undefined and you can run into all sorts of errors. # Now we will remove the __name__ = "__main__" in "Blackjack4.py" # =================================== # Underscore and double underscore (throwaway value) # =================================== # A variable that is just named _ with nothing else indicates a throwaway value. # Underscore (_) by itself is a valid variable name and rather than thinking up a name for something that # will not be used, the convention is to call it _ (underscore) or __ (double undescore) # Examples of things that you may have to access but will not use include tuples # We want to use some of the values of a tuple but not all of them # In this example, we will assign Name, Age and Country to a tuple named "personal_details" personal_details = ("Dylan", 42, "American") # Then we can access just the Name and Country by unpacking tuple "personal_details" into different variables # NOTE here we are unpacking age to a variable named _ which we don't intend to use name, _, country = personal_details print(name, _, country) # if we print including variable _, it will print fine. print(name, country) # But since we did not intend to use _, we will not print it # So _ and __ are valid variable names and are normally used when you don't want to access them # otherwise you should give them a more descriptive name.
43e291e5c3bf19647224fb0d23718fb64b0c028f
matheusgratz/python-extra-activities
/Python Basic - Part I/e024.py
236
3.953125
4
def isVowel(string): if (string == "a") or (string == "e") or (string == "i") or (string == "o") or (string == "u"): result = True else: result = False return result print(isVowel("a")) print(isVowel("w"))
d1848ed7270b21b5638142b18d5416829a0f04a8
MaxPowerWasTaken/project_euler
/p1.py
546
4.28125
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ RANGE = 1000 mult_factor1 = 3 mult_factor2 = 5 mults = [] for i in range(1000): if i % mult_factor1 == 0 or i % mult_factor2 == 0: mults.append(i) print(f"Sum of mults of {mult_factor1} and {mult_factor2} up to {RANGE} is {sum(mults)}") """better way with list comprehensions sum([x for x in range(1000) if x % 3== 0 or x % 5== 0]) """
4bc67175949c5b905abf0e97ea779dc6cc7229b7
rcaixias/estudopython
/ex028.py
166
3.953125
4
from random import randrange x = int(input('Digite um número de 1 a 5: ')) if randrange(1, 5) == x: print('Você acertou') else: print('Número errado')
1d783d392e94653ddd861cc40f796c2b1fe4999c
WillieShubert/DojoAssignments
/Python/Python_OOP/animal/animal.py
1,211
4
4
class Animal(object): def __init__(self, name): print 'New Animal!!!' self.name = name self.health = 100 # define methods def displayHealth(self): # pass self into all methods to access attributes print str(self.name) print "Health: "+str(self.health) def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self animal1 = Animal('animal') animal1.run().run() print animal1.displayHealth() # class Dog(Animal): def __init__(self, name): super(Dog, self).__init__(name) self.health = 150 def pet(self): self.health += 5 return self mydog = Dog('Dog') mydog.walk().walk().walk().run().run().pet() print mydog.displayHealth() class Dragon(Animal): def __init__(self, name): super(Dragon, self).__init__(name) self.health = 170 def fly(self): self.health -= 10 return self fire = Dragon('Charles') fire.walk().walk().walk().run().run().fly().fly() print "This is a Dragon!!" print fire.displayHealth() animal2 = Animal('Dreamer') animal2.run().run().pet().fly() #this doesn't work :-) print animal2.displayHealth()
5cc9ea713701dd511e722f184e41f98107f2b23e
Pseud0n1nja/TensorFlow-Playground
/Multi-class-classification-TensorFlow.py
1,583
3.53125
4
import tensorflow as tf from tensorflow.contrib.learn.python.learn.datasets import base import numpy as np # Load datasets. #Data Scource #http://download.tensorflow.org/data/iris_training.csv #http://download.tensorflow.org/data/iris_test.csv training_set = base.load_csv_with_header(filename = "iris_training.csv", features_dtype=np.float32, target_dtype=np.int) test_set = base.load_csv_with_header(filename= "iris_test.csv", features_dtype=np.float32, target_dtype=np.int) # Model creation # Specifying features (real-value data) feature_name = "flower_features" feature_columns = [tf.feature_column.numeric_column(feature_name, shape=[4])] #Using/Inheriting Linear Classifier from Estimator classifier = tf.estimator.LinearClassifier( feature_columns=feature_columns, n_classes=3, model_dir="/Users/iris_model") #Defining Input function def input_fn(dataset): def func(): features = {feature_name: tf.constant(dataset.data)} label = tf.constant(dataset.target) return features, label return func # raw data -> input function -> feature columns -> model ### Training classifier.train(input_fn=input_fn(training_set), steps=1000) ### Evaluation accuracy_score = classifier.evaluate(input_fn=input_fn(test_set), steps=100)["accuracy"] # Evaluate accuracy. print('\nAccuracy: {0:f}'.format(accuracy_score))
3e7e8757d203226cdfe97ae5666cdbb3fbd9c6a2
irfansantoso/Belajar-Python-Basic
/BelajarPython/perulangan.py
506
4.0625
4
# for index in range(): # action # action juga # diluar for for i in range(5): print(i) print("\n") for z in range(3): print("Perulangan ke-"+str(z+1)) # klo gk pake text perulangan, gk perlu pake str(), langsung aja z+1 print("\n") for x in range(3): print("#" * (x+1)) print("\n") for k in range(3): print(" "*(3-k-1) + "@"*(2*k+1)) print("\n") for m in range(1,7): if m is 5: print("nilai adalah 5") #break continue print("nilai sekarang",m)