blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
bae54183f26da0fbd491b73ab2f92afa70e56c27
smlacava/Metis
/data_loader.py
1,204
3.578125
4
from scipy.io import loadmat from pathlib import Path import numpy as np class data_loader(): def load_data(self, data_file): """ The load_data method allows to load a matrix from a file (.mat). :param data_file: is the name of the file (with its path) containing the matrix :return: the loaded matrix """ if '.mat' in data_file: data = self._load_mat(data_file) return np.squeeze(np.array(data)).tolist() def _load_mat(self, data_file): """ The _load_mat method loads a matrix from a .mat file (FOR INTERNAL USE ONLY). :param data_file: is the name of the file (with its path) containing the matrix :return: the loaded matrix """ data = loadmat(r'%s' % data_file) for k in data.keys(): if not ('__' in k): data = data[k] for i in range(1, 5): if not (isinstance(data, np.ndarray)) or data.shape == (1, 1) or data.shape == (1,) or data.shape == (): data = data[0] else: return data
56e2a73c20f998213a9fecc4e581f4931b551d40
WeijieH/ProjectEuler
/PythonScripts/10001st_prime.py
636
4.0625
4
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' def ith_prime(i): count = 0 n = 1 while count < i: n += 1 if isprime(n): count += 1 continue return n def isprime(n): """Returns True if n is prime.""" if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 ==0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True print(ith_prime(10001))
e64fa593fa30d03523e513dc0d3ffe1dff69cca6
Onotoko/codeforces
/graph/guilty_prince.py
1,671
3.53125
4
from queue import Queue """ The idea: - Read data into a matrix which has shape [h+2, w+2] (added padding to all border) - Build a graph with (h+2)*(w+2) nodes - Build a list edges. Two points (i,j) and (i,j+1) it called edges if (i,j) = '.' and (i,j+1) = '.' - Remember store position of start '@' - Using BFS algorithm to found path for prince The complexity: - Read data: O(h) - Build edges: O(h*w) - Using BFS: O((w*h) + (w*h)*4) ~ O(w*h)(because each of vertex we have almost 4 edges) -> The complexity: O(w*h) """ q = Queue() T = int(input()) cnt = 0 while cnt < T : cnt+=1 w, h = map(int, input().split()) h = h+2 w = w+2 visited = [False for _ in range(h*w)] edges = [[-1] for _ in range(h*w)] matrix = [] start = 0 tol_cells = 0 #Read data matrix.append('#'* w) for _ in range(1,h-1): matrix.append('#' + input() + '#') matrix.append('#'*w) #Build edges for i in range(1,h-1): for j in range(1,w-1): vertex = [] if matrix[i][j] == '.' or matrix[i][j] == '@': if matrix[i][j+1] == '.': vertex.append(i*w + (j+1)) if matrix[i][j-1] == '.': vertex.append(i*w + (j-1)) if matrix[i+1][j] == '.': vertex.append((i+1)*w + j) if matrix[i-1][j] == '.': vertex.append((i-1)*w + j) edges[i*w + j] = vertex if matrix[i][j] == '@': start = i*w + j #Using BFS algorithm to find total cells q.put(start) visited[start] = True tol_cells += 1 while( not q.empty()): start = q.get() edge = edges[start] for i in range(len(edge)): if(visited[edge[i]] == False): visited[edge[i]] = True q.put(edge[i]) tol_cells+=1 print("Case {0}: {1}".format(cnt,tol_cells))
451d287b72e8f4d2c68f62b6aa629a6aa436a23a
randhid/learnpyhardway
/ex6.py
701
4.28125
4
types_of_people = 10 x = f"There are {types_of_people} types of people." # making string variables using the pre defined # variables binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}." #printing statements print(x) print(y) # using print statements with the strign variables # three levels of embedded strings print(f"I said: {x}") print(f"I also said: {y}") # Set a boolean, not the capital letter hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" print(joke_evaluation.format(hilarious)) w = " This is the lef side of..." e= "a string with a right side" # this adds both strings together in the order from # left to right print(w + e)
8956cbce23c196dc454218093e4c402324ada03a
darioradio1man/yandex_training
/lesson3/turtles.py
308
3.71875
4
def turtles_truth(n: int) -> int: count = 0 s = set() for _ in range(n): s.add(input()) for i in s: j = list(map(int, i.split())) if j[0] + j[1] == n - 1 and j[0] >= 0 and j[1] >= 0: count += 1 return count n1 = int(input()) print(turtles_truth(n1))
7262de4fe2c621332cf31090aa770f8a3cac5464
jormao/holbertonschool-higher_level_programming
/0x0B-python-input_output/7-save_to_json_file.py
405
4
4
#!/usr/bin/python3 """7-save_to_json_file.py - Save Object to a file""" import json def save_to_json_file(my_obj, filename): """function that writes an Object to a text file, using a JSON representation ARGS: my_obj: object to write in a text file filename: text file """ with open(filename, mode='w', encoding='utf-8') as a_file: json.dump(my_obj, a_file)
178a0fd06825bcff318cbd45260769f98a7642a3
aeberspaecher/TheoHandouts
/Mechanik-GreensFkt/deltaPlot.py
2,021
3.859375
4
#!/usr/bin/env python #-*- coding:utf-8 -*- """Plot various representations of the Dirac's Delta function. """ import numpy as np import matplotlib as mpl mpl.use("module://backend_pgf") import matplotlib.pyplot as plt plt.figure(figsize=(5,3)) def rectangle(x, x0, epsilon): y = np.zeros(len(x)) y[np.where(np.abs(x- x0) <= epsilon/2.0)] = 1.0/epsilon #plt.plot(x, np.abs(x- x0)) #plt.show() return y def gauss(x, x0, epsilon): return 1.0/(np.sqrt(2*np.pi)*epsilon)*np.exp(-(x-x0)**2/(2.0*epsilon**2)) # TODO: fix Normierung! def lorentz(x, x0, epsilon): return 1.0/np.pi * epsilon/((x-x0)**2 + epsilon**2) def sinc(x, x0, epsilon): y = np.ones(len(x)) y[np.where(x != 0.0)] = 1.0/epsilon*np.sin(np.pi*(x-x0)/epsilon)/(np.pi*(x-x0)) return y if(__name__ == '__main__'): x = np.linspace(-3, +3, 750) yRect1 = rectangle(x, -2.0, 0.5) yRect2 = rectangle(x, -2.0, 0.3) yRect3 = rectangle(x, -2.0, 0.2) plt.plot(x, yRect1, c="b", lw=1.25, ls="-.") plt.plot(x, yRect2, c="b", lw=1.25, ls="--") plt.plot(x, yRect3, c="b", lw=1.25, ls="-") yGauss1 = gauss(x, -1.0, 0.35) yGauss2 = gauss(x, -1.0, 0.15) yGauss3 = gauss(x, -1.0, 0.075) plt.plot(x, yGauss1, c="r", lw=1.25, ls="-.") plt.plot(x, yGauss2, c="r", lw=1.25, ls="--") plt.plot(x, yGauss3, c="r", lw=1.25, ls="-") yLor1 = lorentz(x, 0.0, 0.25) yLor2 = lorentz(x, 0.0, 0.125) yLor3 = lorentz(x, 0.0, 0.07) plt.plot(x, yLor1, c="black", lw=1.25, ls="-.") plt.plot(x, yLor2, c="black", lw=1.25, ls="--") plt.plot(x, yLor3, c="black", lw=1.25, ls="-") ySinc1 = sinc(x, 2.001, 0.6) ySinc2 = sinc(x, 2.001, 0.5) ySinc3 = sinc(x, 2.001, 0.4) plt.plot(x, ySinc1, c="gray", lw=1.25, ls="-.") plt.plot(x, ySinc2, c="gray", lw=1.25, ls="--") plt.plot(x, ySinc3, c="gray", lw=1.25, ls="-") plt.xlabel("$t$") plt.ylabel("$\delta_\epsilon$") plt.tight_layout() #plt.show() plt.savefig("delta-plot.pgf")
25ac379390d92b13f58164103b955bb4dcf5624e
UWSEDS/hw4-exceptions-and-unit-tests-samirpdx
/data_action.py
1,257
3.59375
4
import pandas as pd import os import requests def get_data(url): #df = pd.DataFrame() url = url csv_name = url[url.rfind("/")+1:] check = "" if os.path.exists(csv_name): #print("File exists locally, skipping download.") check = "File exists locally, skipping download." else: try: req = requests.get(url) assert req.status_code == 200 # if the download failed, this line will generate an error with open(csv_name, 'wb') as f: f.write(req.content) #df = pd.read_csv(csv_name) #print("Download performed successfully.") check = "Download performed successfully." except AssertionError: #print("URL does not point to a file that exists.") check = "URL does not point to a file that exists." return check def delete_data(url): url = url csv_name = url[url.rfind("/")+1:] check = "" try: os.remove(csv_name) #print("File successfully removed locally.") check = "File successfully removed locally." except FileNotFoundError: #print("File from URL not found locally.") check = "File from URL not found locally." return check
14c642df153620f7abb20c96f5317736269f47cc
leoliuyt/workspace_python
/python_grammar/my_controltest.py
394
3.921875
4
#!/usr/local/bin/python3 inputStrH = input("请输入身高(m):") inputStrW = input("请输入体重(kg):") h = float(inputStrH) w = float(inputStrW) bim = w / (h**2) print(bim) if bim < 18.5: print("过轻") elif bim >= 18.5 and bim < 25: print("正常") elif bim >= 25 and bim < 28: print("正常") elif bim >= 28 and bim < 32: print("肥胖") else: print("严重肥胖")
7395f488158de2536275ca7ffdbb64b494a5e934
Thesohan/DS_python
/bit_manipulation/no_of_bits.py
443
4.125
4
""" Write a function that takes an unsigned integer and returns the number of 1 bits it has. Example: The 32-bit integer 11 has binary representation 00000000000000000000000000001011 so the function should return 3. """ class Solution: # @param A : integer # @return an integer def numSetBits(self, A): count=0 for i in range(31,-1,-1): if A &(1<<i)!=0: count+=1 return count
ef9a2463f898541e86818be75bd49523108ce6f2
YogalakshmiS/thinkpython
/chapter 5/Exc 5.3.py
965
4.28125
4
''' Exercise 5.3. Fermat’s Last Theorem says that there are no positive integers a, b, and c such that a n + b n = c n for any values of n greater than 2. 1. Write a function named check_fermat that takes four parameters—a, b, c and n—and that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that a n + b n = c n the program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.” ''' def check_fermat(a, b, c, k): if k > 2 and (a**k + b**k == c**k): print("Holy smokes, Fermat was wrong!") else: print("No, that doesn’t work.") def check_numbers(): a = int(input("Choose a number for a: ")) b = int(input("Choose a number for b: ")) c = int(input("Choose a number for c: ")) k = int(input("Choose a number for k: ")) return check_fermat(a, b, c, k) check_numbers()
48b8b066340095001f0c337de40dde5838d6e2d2
isfaaghyth/algorithm-playground
/Game of Thrones - I/solution.py
1,451
3.75
4
""" https://www.hackerrank.com/challenges/game-of-thrones/problem Dothraki are planning an attack to usurp King Robert's throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom. But, to lock the door he needs a key that is an anagram of a certain palindrome string. The king has a string composed of lowercase English letters. Help him figure out whether any anagram of the string can be a palindrome or not. Input Format A single line which contains the input string. Each character of the string is a lowercase English letter. Output Format A single line which contains YES or NO in uppercase. Sample Input 0 aaabbbb Sample Output 0 YES Explanation 0 A palindrome permutation of the given string is bbaaabb. Sample Input 1 cdefghmnopqrstuvw Sample Output 1 NO Explanation 1 You can verify that the given string has no palindrome permutation. Sample Input 2 cdcdcdcdeeeef Sample Output 2 YES Explanation 2 A palindrome permutation of the given string is ddcceefeeccdd. """ #!/bin/python3 import sys def gameOfThrones(s): from collections import Counter count = Counter(s) odd = 0 for i in count.values(): if i % 2 == 0: continue else: odd += 1 if odd > 1: break return "YES" if odd < 2 else "NO" s = input().strip() result = gameOfThrones(s) print(result)
cf6d8b130d85e58d16e14cc980fbc90dbed337fc
toledoneto/Python-TensorFlow
/02 TensorFlow Basics/07 TF Regression Exercise.py
3,651
3.5
4
# Regression Exercise # # California Housing Data # # This data set contains information about all the block groups in California from the 1990 Census. # In this sample a block group on average includes 1425.5 individuals living in a geographically compact area. # # The task is to aproximate the median house value of each block from the values of the rest of the variables. # # It has been obtained from the LIACC repository. # The original page where the data set can be found is: http://www.liaad.up.pt/~ltorgo/Regression/DataSets.html. # # The Features: # # * housingMedianAge: continuous. # * totalRooms: continuous. # * totalBedrooms: continuous. # * population: continuous. # * households: continuous. # * medianIncome: continuous. # * medianHouseValue: continuous. import pandas as pd import tensorflow as tf from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler # Import the cal_housing_clean.csv file with pandas data = pd.read_csv('cal_housing_clean.csv') print(data.columns) print(data.describe()) print(data.info()) y = data['medianHouseValue'] x = data.drop(columns='medianHouseValue', axis=1) print(x.head()) print(y.head()) # Separate it into a training (70%) and testing set(30%) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=101) # Use sklearn preprocessing to create a MinMaxScaler for the feature data. Fit this scaler only to the training data. # Then use it to transform X_test and X_train. Then use the scaled X_test and X_train along with pd.Dataframe # to re-create two dataframes of scaled data. scaler = MinMaxScaler() scaler.fit(x_train) x_train = pd.DataFrame(data=scaler.transform(x_train), columns=x_train.columns, index=x_train.index) x_test = pd.DataFrame(data=scaler.transform(x_test), columns=x_test.columns, index=x_test.index) # Create the necessary tf.feature_column objects for the estimator. # They should all be trated as continuous numeric_columns. age = tf.feature_column.numeric_column('housingMedianAge') nrooms = tf.feature_column.numeric_column('totalRooms') nbedrooms = tf.feature_column.numeric_column('totalBedrooms') population = tf.feature_column.numeric_column('population') household = tf.feature_column.numeric_column('households') medianIncome = tf.feature_column.numeric_column('medianIncome') feat_cols = [age, nrooms, nbedrooms, population, household, medianIncome] # Create the input function for the estimator object. input_func = tf.estimator.inputs.pandas_input_fn(x=x_train, y=y_train, batch_size=10, num_epochs=1000, shuffle=True) # Create the estimator model. Use a DNNRegressor model = tf.estimator.DNNRegressor(hidden_units=[6, 6, 6], feature_columns=feat_cols) # Train the model for ~1,000 steps model.train(input_fn=input_func, steps=25000) # Create a prediction input function and then use the .predict method off your estimator model # to create a list or predictions on your test data predict_input_func = tf.estimator.inputs.pandas_input_fn( x=x_test, batch_size=10, num_epochs=1, shuffle=False) pred_gen = model.predict(predict_input_func) predictions = list(pred_gen) print("Predições: " + str(list(predictions))) # Calculate the RMSE final_preds = [] for pred in predictions: final_preds.append(pred['predictions']) mse = mean_squared_error(y_test, final_preds)**0.5 print("RSME: " + str(mse))
b6880bc3c60319d0149b1dd417397650d95b03d6
Aasthaengg/IBMdataset
/Python_codes/p03796/s827733716.py
141
3.65625
4
N = int(input()) power = 1 for i in range(1,N+1): power *= i if power >= 10**9+7: power %= 10**9+7 print(power % (10**9+7))
3e117dd63a4596fa8a8f303744f91a447c13aad5
jaecheolkim99/CodingPlayground
/LeetCode/Compare Version Numbers.py
3,098
4.09375
4
""" Compare two version numbers version1 and version2. If version1 > version2 return 1; if version1 < version2 return -1; otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate number sequences. For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0. [BEST] class Solution(object): def compareVersion(self, version1, version2): l1 = [int(i) for i in version1.split('.')] l2 = [int(i) for i in version2.split('.')] i = len(l2) - 1 while i >= 0: if l2[i]: break l2 = l2[:-1] i -= 1 i = len(l1) - 1 while i >= 0: if l1[i]: break l1 = l1[:-1] i -= 1 for i in range(min(len(l2), len(l1))): if l1[i] < l2[i]: return -1 elif l2[i] < l1[i]: return 1 if len(l1) > len(l2): return 1 elif len(l2) > len(l1): return -1 return 0 """ class Solution(object): def checkZero(self, list_version, idx, max_idx, type): for i in range(idx, max_idx): if list_version[i] != 0: if type == 0: return -1 return 1 return 0 def convertListStrToInt(self, lst): intLst = [] first_zero = 0 for i in range(len(lst)): if int(lst[i]) != 0 and first_zero != 0: intLst.append(int(lst[i])) else: intLst.append(int(lst[i])) first_zero += 1 return intLst def compareVersion(self, version1, version2): """ :type version1: str :type version2: str :rtype: int """ s_ver1 = version1.split(".") s_ver2 = version2.split(".") s_ver1 = self.convertListStrToInt(s_ver1) s_ver2 = self.convertListStrToInt(s_ver2) len_ver1 = len(s_ver1) len_ver2 = len(s_ver2) max_len = max(len_ver1, len_ver2) for i in range(max_len): idx = i + 1 if len_ver1 < idx: return self.checkZero(s_ver2, i, len_ver2, 0) if len_ver2 < idx: return self.checkZero(s_ver1, i, len_ver1, 1) if idx == len_ver1 and idx == len_ver2: if s_ver1[i] < s_ver2[i]: return -1 if s_ver1[i] > s_ver2[i]: return 1 return 0 if s_ver1[i] < s_ver2[i]: return -1 if s_ver1[i] > s_ver2[i]: return 1
63354e69bb1ac1f7c084dfb44ef83bdf4310f6f0
icoding2016/study
/DS/array_kadane.py
3,304
3.84375
4
""" Largest Sum Contiguous Subarray (via Kadane’s Algorithm) Given an array arr[] of size N. The task is to find the sum of the contiguous subarray within a arr[] with the largest sum. The idea of Kadane’s algorithm is to maintain a variable max_ending_here that stores the maximum sum contiguous subarray ending at current index and a variable max_so_far stores the maximum sum of contiguous subarray found so far, Everytime there is a positive-sum value in max_ending_here compare it with max_so_far and update max_so_far if it is greater than max_so_far. At each position (i), the max_sub[i] = max(max_sub[i-1], a[i]) Kadane's algorithm has a time complexity of O(n) and a space complexity of O(1), where n is the length of the input array. """ import random import typing as t N=20 A = [random.randint(-100,100) for i in range(N)] A_override = [-81, 70, -86, 25, -88, 64, -32, 40, -1, -99, -17, -10, -9, -92, 76, 49, 17, 14, -6, 70] # T(N^3) # Rouphly, N*N*N (i, j, sum()) # MorePrecise, (N-1)^2+(N-2)^2+...+1 = N(N+1)(2N+1)/6 => N^3 # S(N^2), # In the worst case, if every subarray is distinct and considered large, the space complexity would be O(n^2), # where n is the length of the input list a. def LargestContinuousSub(a:list) -> t.Tuple[t.List, int]: large_arr=[] large_sum=None for i in range(len(a)): for j in range(i+1,len(a)): s = sum(a[i:j+1]) if not large_sum or s > large_sum: large_arr = [a[i:j+1]] large_sum = s elif s == large_sum: large_arr.append(a[i:j+1]) return (large_arr, large_sum) # T(N) # S(1) def kadane(a:list) -> t.Tuple[t.List, int]: largest_sub_start = largest_sub_end = 0 largest_sum = a[0] for i in range(1, len(a)): if a[i] > largest_sum + a[i]: largest_sub_start = largest_sub_end = i largest_sum = a[i] else: largest_sub_end = i largest_sum = largest_sum + a[i] return (a[largest_sub_start:largest_sub_end+1], largest_sum) # T(N) # S(N^2) the largest_sub stores N substring whose size could be N in worst case # We can simply use a O(N) space to record current largest sub # or O(1) to record the pos of start/end. def kadane_bad_space_complexity(a:list) -> t.Tuple[t.List, int]: largest_sub = [None for i in range(len(a))] # largest_sub at i largest_sum = [None for i in range(len(a))] largest_sub[0] = [a[0]] largest_sum[0] = a[0] for i in range(1, len(a)): if a[i] > largest_sum[i-1] + a[i]: largest_sub[i] = [a[i]] largest_sum[i] = a[i] else: largest_sub[i] = largest_sub[i-1] + [a[i]] largest_sum[i] = largest_sum[i-1] + a[i] large_pos = 0 for i in range(len(largest_sum)): if largest_sum[i] > largest_sum[large_pos]: large_pos = i return (largest_sub[large_pos], largest_sum[large_pos]) def test(): a = A_override if A_override else A print(f"A: {a}") large_arr, large_sum = LargestContinuousSub(a) print(f"by LargestContinuousSub:\n{large_arr}, {large_sum}") large_arr, large_sum = kadane(a) print(f"by Kadane:\n{large_arr}, {large_sum}") test()
ac1111ef6e07b2609495e92227e31c021aaac065
Antherine/First-day-of-Python
/templates/hello_world.py
583
3.984375
4
# encoding: utf-8 def main(x): """ 你好 :param x: :return: """ if x == 2: print "hello, world" else: print "F**k you, world" def calculator(x, op, y): if op == "+": return x + y elif op == "-": return x - y elif op == "x": return x * y elif op == "/": return x / y else: raise Exception("OMG!") import math r = 7 h = 9 z = (math.pi * r**2) * h print z a = 0 while a < 1: a = a + 1 print a print calculator(8888, "+", 99) if __name__ == "__main__": main(6)
3389147655ce338f0389eb5d9482fdfdbabc343a
openturns/openturns.github.io
/openturns/master/_downloads/1d69a82405aa339fe03c15bbefb04818/plot_random_mixture_distribution_discrete.py
1,069
3.75
4
""" Create a discrete random mixture ================================ """ # %% # In this example we are going to build the distribution of the value of the sum of 20 dice rolls. # # .. math:: # Y = \sum_{i=1}^{20} X_i # # where :math:`X_i \sim U(1,2,3,4,5,6)` # # %% from __future__ import print_function import openturns as ot import openturns.viewer as viewer from matplotlib import pylab as plt ot.Log.Show(ot.Log.NONE) # %% # create the distribution associated to the dice roll X = ot.UserDefined([[i] for i in range(1,7)]) # %% # Roll the dice a few times X.getSample(10) # %% N = 20 # %% # Create the collection of identically distributed Xi coll = [X] * N # %% # Create the weights weight = [1.0] * N # %% # create the affine combination distribution = ot.RandomMixture(coll, weight) # %% # probability to exceed a sum of 100 after 20 dice rolls distribution.computeComplementaryCDF(100) # %% # draw PDF graph = distribution.drawPDF() view = viewer.View(graph) # %% # draw CDF graph = distribution.drawCDF() view = viewer.View(graph) plt.show()
ab064b2a02706735a92d64dbf786f4083b83cb88
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/mrgsac001/question1.py
463
4.21875
4
"""palindromes Sachin Murugan 9/5/2014""" string=input("Enter a string:\n") def Palindrome(string): #testing for base case if len(string)== 0 or len(string)==1: #check if word is only 1 or zero letters print("Palindrome!") else: if string[0]==string[-1]:#check first and last letter Palindrome(string[1:-1])#make problem smaller else: print("Not a palindrome!") Palindrome(string)
e842c92514d23208bb483f1423526375dfeda48f
minseoch/algorithm
/300-LongestIncreasingSubsequence.py
2,250
3.828125
4
# 300. Longest Increasing Subsequence # https://leetcode.com/problems/longest-increasing-subsequence/discuss/152065/Python-explain-the-O(nlogn)-solution-step-by-step class Solution: # O(n*m) solution. m is the sub[]'s length def lengthOfLIS(self, nums): sub = [] print(f"nums={nums}") for val in nums: pos, sub_len = 0, len(sub) print(f"val = {val}, pos={pos}, sub_len={sub_len}") while (pos <= sub_len): # update the element to the correct position of the sub. print(f" pos={pos}, sub_len={sub_len}") if pos == sub_len: sub.append(val) print(f" pos == sub_len, sub={sub}") break elif val <= sub[pos]: sub[pos] = val print(f" val <= sub[pos], sub={sub}") break else: pos += 1 print(f" pos={pos}") print(f"len(sub)={len(sub)}, sub={sub}") return len(sub) # O(nlogn) solution with binary search def lengthOfLIS2(self, nums): def binarySearch(sub, val): lo, hi = 0, len(sub) - 1 print(f"sub={sub}, val={val}, lo={lo}, hi={hi}") while (lo <= hi): mid = lo + (hi - lo) // 2 print(f"lo={lo}, hi={hi}, mid={mid}, sub[mid]={sub[mid]}") if sub[mid] < val: lo = mid + 1 print(f"lo={lo}") elif val < sub[mid]: hi = mid - 1 print(f"hi={hi}") else: print(f"return mid {mid}") return mid print(f"return lo ={lo}") return lo sub = [] for val in nums: print(f"val={val}") pos = binarySearch(sub, val) print(f"pos={pos}") if pos == len(sub): sub.append(val) print(f"1.sub={sub}") else: sub[pos] = val print(f"2.sub={sub}") return len(sub) nums = [10,9,2,5,3,7,101,18] # nums = [3,2,5,6] obj = Solution() print(obj.lengthOfLIS2(nums))
96fdd0185ab2348d6163db7441264991b2c51dbe
CarlosPolo019/taller-algoritmo-condicionales
/punto5.py
461
3.96875
4
valorCarro = float(input('Digite el valor del carro: ')) valorTerreno = float(input('Digite el valor del terreo: ')) incrementoTerreno = 0.10 * valorTerreno * 3 desvaluacionCarro = 0.10 * valorCarro * 3 print(f'Valor Terreno {desvaluacionCarro}') if (desvaluacionCarro < (incrementoTerreno*0.50)): print(f'Calculos Finalizados') print(f'Usted debe comprar el carro') else: print(f'Calculos Finalizados') print(f'Usted debe comprar el terreno')
c2be250bca11b5af8c8e1c1b38470ee6b76ff25a
Yi-Pin-chen/yzu_python_20210414
/day05/List 串列2.py
739
3.609375
4
import random as r scores=[100,-10,90,80,999] # error_scores=scores.pop(1) # print(error_scores,scores) # error_scores=scores.pop(3) # print(error_scores,scores) #利用POP () 將不合法的分數挑出 for x in scores: if x> 100 or x < 0: error_scores = scores.pop(scores.index(x)) print(scores) #利用POP () 將不合法的分數挑出 scores1=[100,-10,90,-80,999] ErrorScores=[] for s in scores1: if s> 100 or s < 0: ErrorScores.append(s) print(scores1) print(ErrorScores) for e in ErrorScores: scores1.pop(scores1.index(e)) print(scores1) #反轉 scores=[1,7,3,5] scores.reverse() print(scores) #排序 scores.sort() print(scores) #洗牌(請先 import random as r ) r.shuffleu(scores) print(scores)
b9ef3cae09d0e7bd97d046057e825bfdb4cfd022
laurachaves/pendulo
/pendulo.pyde
633
3.59375
4
teta = PI/3 R = 200 #comprimento g = 980.0 #aceleração da gravidade vt = 0.01 h = R-R*cos(teta) EM = g*h+(vt**2)/2 oldt = millis()/1000.0 ver = 1.0 def setup(): size(800,800) def draw(): global oldt, teta, R, vt, g, h, EM, ver t = millis()/1000.00 dt = t - oldt oldt = t omega = ver*vt/R teta -= omega*(dt) x = R*sin(teta) y = R-R*cos(teta) #print("2",EM-g*y) if EM < g*y: ver *= -1 else: vt = (2*(EM-g*y))**0.5 background(255) stroke(0) posx = 400+x posy = R-y line(400,0,posx, posy) fill(0) ellipse(posx,posy,20, 20)
3ea1ec72d315a57c1bb1c8609ae3689ac3f3f362
tanchao/algo
/interviews/amazon/rotate_min.py
763
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'tanchao' def find_min(A): if not A: return None if len(A) == 1: return A[0] left, right = 0, len(A) - 1 while left < right and A[left] >= A[right]: mid = left + (right - left) / 2 if A[mid] < A[right]: right = mid elif A[mid] > A[left]: left = mid + 1 else: left += 1 return A[left] if __name__ == '__main__': print find_min([3,4,5,6,7,0,1,2]) print find_min([]) print find_min([3]) print find_min([3,4,1,2]) print find_min([3,1,2]) print find_min([3,3,3,3,2]) print find_min([3,4,1,2,2,2,2,2,2,2]) print find_min([3,2,2,2,2,2]) print find_min([1,1,1,1,1,1,1,1,1,2,2,2,2,2])
75287a08413994b22206e38d142dac5ccf16bbc1
zhenhuiguo1995/CS5001
/Othello_Part_2/Othello/player.py
597
3.9375
4
class Player(): """Instantiates a human player or a computer player object""" def __init__(self, name, board, color): self.name = name self.board = board self.color = color def has_legal_move(self): """Return a boolean value representing if the player has a legal move or not.""" return self.board.has_legal_move(self.color) def move(self, x, y, flips): """Given two Integers and a set, return nothing. Player make a move.""" self.board.add_tile(x, y, self.color) self.board.flip(flips, self.color)
cb59b63c23fd2ce97f024e21036a985143970231
Aasthaengg/IBMdataset
/Python_codes/p02582/s949198943.py
157
3.9375
4
s=input() if (s=="RRR"): print(3) elif (s=="SRR" or s=="RRS"): print(2) elif (s=="SSR" or s=="RSS" or s=="SRS" or s=="RSR"): print(1) else: print(0)
6c7f78bf245e88ccf32447cdef2fdefe75c0b4aa
sumanshreyansh/python-projects
/billcalculator.py
297
4.09375
4
#to make a program which keeps adding number till the user doesn't press q. sum = 0 while(True): a = input("Enter the price \n") if a != "q": sum = sum + int(a) print(f"order so far {sum}") else: print("The total price is ",sum) break
29c18bc3fe30d4223ff74d2d6e8de6578ae85d6f
nithi-sree/IBMLabs
/LeapYear.py
322
4.15625
4
year = int(input("Enter the year: ")) if(year%4) == 0: if (year%100) == 0: if (year%400) == 0: print(f"{year} is a leap year") else: print(f"{year} is not a leap year") else: print(f"{year} is a leap year") else: print(f"{year} is not a leap year")
ba9757e0d0a846e044ad67642fea35df0b8ff3b2
microsoft/Reactors
/coding-languages-frameworks/code-garden-advent-of-code-2022/day10.py
2,060
3.53125
4
#!/usr/bin/env python3 instructions = [x.strip() for x in open("day10-data.txt").readlines()] class CPU: def __init__(self): self.clock = 0 self.X = 1 self.signal_beats = [] self.display = [] def log(self): if (self.clock+20) % 40 == 0: print(self.clock, self.X, self.signal_strength()) self.signal_beats.append(self.signal_strength()) def setPixel(self): if abs(self.clock%40 - self.X) <= 1: self.display.append('#') else: self.display.append('.') def drawDisplay(self): for i in range(self.clock): if i % 40 == 0: print() print(self.display[i], end="") def step(self): self.setPixel() self.clock += 1 self.log() def noop(self): self.step() def addx(self, val): self.step() self.step() self.X += val def signal_strength(self): return self.clock * self.X cpu = CPU() for i in instructions: #print(">", i) if i == "noop": cpu.noop() elif i.startswith("addx"): val = int(i.split(" ")[1]) cpu.addx(val) #print(">>", cpu.clock, cpu.X) print("Signal sum:", sum(cpu.signal_beats)) cpu.drawDisplay() # Renee's code # x = 1 # cycle_x = [] # with open("day10-data.txt") as f: # for line in f: # inst = line.strip().split(" ") # if inst[0] == "noop": # cycle_x.append(x) # else: # num = inst[1] # cycle_x.append(x) # cycle_x.append(x) # x += int(num) # total = 0 # for i in range(19, len(cycle_x), 40): # print(cycle_x[i - 1], i + 1) # total += cycle_x[i - 1] * (i + 1) # print(total) # for i, x in enumerate(cycle_x): # if i%40 == x-1 or i%40 == x or i%40 == x + 1: # print("#", end="") # else: # print(".", end="") # if i + 1 in list(range(0, len(cycle_x), 40)): # print()
9b1f954e78e2759a4282a3be2056b5651e4899db
TanveerAhmed98/Full-Stack-Programming
/Programming Concepts/error_handling.py
380
3.953125
4
def read_file(file_name): try: file = open(file_name, "r") stuff = file.read() print(stuff) file.close() except: print("There is an error in read file function") read_file("apple.txt") password = input("Please enter the password: ") if len(password) < 10: raise Exception ("The length of a password must be greate than ten")
8d99772a839081b35f3ab27608c26d0b73030d37
wjymath/leetcode_python
/108. Convert Sorted Array to Binary Search Tree/Convert_Sorted_Array_to_Binary_Search_Tree.py
647
3.734375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ input_l = len(nums) if input_l == 0: return None t = TreeNode(nums[len(nums) // 2]) t.left = self.sortedArrayToBST(nums[:input_l // 2]) t.right = self.sortedArrayToBST(nums[input_l // 2 + 1:]) return t if __name__ == "__main__": print(Solution().sortedArrayToBST([-10,-3,0,5,9]))
9458758501f45a7d531d5f84020fb2b50778b9a5
pearlselvan/PythonPractise
/DS/PriorityQueueUsingheapq.py
832
3.875
4
''' A priority queue is common use for a heap, and it presents several implementation challenges: http://www.bogotobogo.com/python/python_PriorityQueue_heapq_Data_Structure.php ''' # Simplest try: import Queue as Q # ver. < 3.0 except ImportError: import queue as Q q = Q.PriorityQueue() q.put(10) q.put(1) q.put(5) while not q.empty(): print q.get(), ''' 1 5 10 ''' ''' Note that depending on the Python versions, the name of the priority queue is different. So, we used try and except pair so that we can adjust our container to the version. ''' #Sample B - tuple try: import Queue as Q # ver. < 3.0 except ImportError: import queue as Q q = Q.PriorityQueue() q.put((10,'ten')) q.put((1,'one')) q.put((5,'five')) while not q.empty(): print q.get(), ''' (1, 'one') (5, 'five') (10, 'ten') '''
06ebfa7a313d82d47078a8c3a293243787a5758b
Min3710/Mypython
/chaper 2/p03.py
145
3.625
4
radius=int(input("반지름을 입력하세요")) size=3.14159*radius*radius#rdaius**2 print("반지름이",radius,"인 원의 넓이=",size)
ba37906f8b325810cc8bf3f60069dbdc435f6fbb
kimdg1105/Algorithm_Solving
/BOJ/10814.py
397
3.546875
4
N = int(input()) list = [] for i in range(N): age, name = input().split() list.append([age, name, i]) # for i in range(N): # for j in range(N): # if list[j][0] > list[i][0]: # temp = list[j][0] # list[j][0] = list[i][0] # list[i][0] = temp list.sort(key=lambda x: (int(x[0]), int(x[2]))) for i in range(N): print(list[i][0], list[i][1])
8be1c3c159422a305e036dca57ae1e6e0f3e8cc1
zhousir1234/zhourui
/python入门/第二章.py
708
3.84375
4
#1.输入直角三角形的两个直角边的长度a、b求c的长度 num1=float(input('请输入一条边的长')) num2=float(input('请输入另外一条边的长')) a=num1 b=num2 c=((a**2)+(b**2))**(1/2) print('c的长度是',c) #2. 编写一个程序,用于实现两个数的交换 num1=float(input('请输入一个数')) num2=float(input('请输入另一个数')) a=num1 b=num2 #使用3个变量 c=a a=b b=c print('b的值为',b) #使用两个变量 #使用两个变量的第一种方法 a = a+b #取两个数的和 b = a-b #然后a-b等于a然后赋值给b a = a-b #然后a-b等于b然后赋值给a,完成值的交换 #使用两个变量的第二种方法 a,b = b,a
7d453088c2129fe4c1d9274f1a65e80897f0bf87
sankey94/Python
/Python Base Work/fibonacci.py
110
3.875
4
num=int(input("Enter number:" )) a=0 b=1 print(a) for i in range(num): c=a+b print(c) b=a a=c
3a77ccc29a7d025f158003fa6535e75aa5ccb735
jasonncleveland/cs2613
/assignments/A4/read_csv.py
264
3.9375
4
import csv def read_csv(filename): """Read a CSV file, return list of rows""" rows = [] with open(filename, 'r') as csv_file: reader = csv.reader(csv_file, delimiter=',') for row in reader: rows.append(row) return rows
4d658a19044192671889554ddd9a225a0b0a73e1
TheMoonlsEmpty/test
/类/类练习2.0.py
1,896
3.71875
4
# 利用上题的类,生成20个随机数字,两两配对,形成二维坐标,并这些坐标打印出来 import random # 方法一: class Randomint7: def __init__(self, count=10, start=1, stop=100): self._count = count self.start = start self.stop = stop self._gen = self._generate() # 生成器对象 def _generate(self): # 用生成器的无限生成,要多少不在这里控制。 while True: yield [random.randint(self.start, self.stop) for _ in range(self._count)] def generate(self, count=0): # 这里做控制判断 if count > 0: self._count = count # return next(self._gen) ret = next(self._gen) return ret ri = Randomint7() class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return '<Point {} : {}>'.format(self.x, self.y) # ===================================================================# # 两种变现形式: # points = [Point(k, v) for k, v in zip(ri.generate(), ri.generate())] points = [Point(*v) for v in zip(ri.generate(), ri.generate())] # ===================================================================# # 下面是三种显示方式: print('第一种方法', points, len(points)) # ========================= for x in points: print('第二种方法', x) # ========================= for point in points: print('第三种方法:<Point {} : {}>'.format(point.x, point.y)) # 方法二: import random class Sj: def __init__(self, count, start, end): self.count = count self.start = start self.end = end def show(self): list = [random.randint(self.start, self.end) for i in range(self.count)] print(list) print([(list[i], list[i+1])for i in range(0, self.count-1, 2)]) x = Sj(20,2,100) x.show()
0df9200bcd9a6aec68d1587d742528e137656a9e
busekara/image-processing
/ders-4.py
1,576
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[20]: import math #standart sapma ve ortalama hesaplama fonksiyonu def my_f_1(my_list=[2,4,3,40,5,6,3,3,2,1]): toplam=0 total=0 for i in my_list: toplam+=i #hist=? mean=toplam/len(my_list) #ortalama #print(mean) for i in my_list: total+=(i-mean)*(i-mean) var=total/(len(my_list)-1) var=math.sqrt(var) #print(var) #std=? return mean,var # In[21]: print(my_f_1()) # In[40]: my_histogram={} #liste my_list=[2,4,3,40,5,6,3,3,2,1] #degerlerın frekansını buluyor. for i in my_list: if i in my_histogram.keys(): my_histogram[i]+=1 else: my_histogram[i]=1 #my_histogram[1]=10 # value:1 değerinde olanın key:10 yap gibi. # my_histogram[2]=15 # my_histogram[40]=40 print(my_histogram) # In[41]: import matplotlib.pyplot as plt import numpy as np # In[53]: def my_f_2(image_1=plt.imread('istanbul.jpg')): print(image_1.ndim,image_1.shape) m,n,p=image_1.shape my_histogram={} for i in range(m): for j in range(n): if (image_1[i,j,0] in my_histogram.keys()): my_histogram[image_1[i,j,0]]+=1 else: my_histogram[image_1[i,j,0]]=0 # image_1[i,j,1] # image_1[i,j,2] return my_histogram # In[54]: print(my_f_2()) # In[59]: x=[] y=[] my_histogram=my_f_2() for key in my_histogram.keys(): x.append(key) #value y.append(my_histogram[key]) #key plt.bar(x,y) plt.show() print(x) print(y) # In[ ]:
e55fa48df9d9d61aca5d16ac4725baa48cdc4900
korowood/algorithm-and-data-structures
/5 - Хеш-таблицы/A. Set.py
1,830
3.515625
4
""" Реализуйте множество с использованием хеш таблицы. input: insert 2 insert 5 insert 3 exists 2 exists 4 insert 2 delete 2 exists 2 output: true false false """ import sys class HashSet: def __init__(self): self.M = 10 ** 6 self.A = 4481 self.P = 2004991 self.data = ['' for _ in range(self.M)] def hash(self, key): return ((key * self.A) % self.P) % self.M def add(self, key): key_hash = self.hash(key) while not self.free(key_hash): if self.data[key_hash] == key: return key_hash = self.hash(key_hash + 1) self.data[key_hash] = key def exists(self, key): key_hash = self.hash(key) while not self.is_empty(key_hash): if self.data[key_hash] == key: return "true" else: key_hash = self.hash(key_hash + 1) return "false" def delete(self, key): key_hash = self.hash(key) while not self.is_empty(key_hash): if self.data[key_hash] == key: self.data[key_hash] = 'rip' break else: key_hash = self.hash(key_hash + 1) def free(self, x): if self.data[x] == '' or self.data[x] == 'rip': return True return False def is_empty(self, x): if self.data[x] == '': return True return False hs = HashSet() ans = [] for line in sys.stdin.buffer.read().decode().splitlines(): arr = list(line.split()) if arr[0][0] == "i": hs.add(int(arr[1])) elif arr[0][0] == 'd': hs.delete(int(arr[1])) elif arr[0][0] == 'e': ans.append(hs.exists(int(arr[1]))) sys.stdout.buffer.write("\n".join(ans).encode())
ca98a1e382c29063737107b65ff3b3232a65c7df
aparajit0511/DS-Algo
/linked list/Reverse Linked List.py
469
3.84375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: ptr = new = None current = head while current is not None: ptr = current current = current.next ptr.next = new new = ptr head = new return head
3d9e0e132fc6ed24fae7b8c48b221e5ff00cb303
shimmee/competitive-programming
/AtCoder/Practice/茶緑埋め/ARC006B.py
2,005
3.53125
4
# ARC006B - あみだくじ # URL: https://atcoder.jp/contests/arc006/tasks/arc006_2 # Date: 2021/02/20 # ---------- Ideas ---------- # 今なんの列にいるのかnowで管理しながら,左右に'-'があれば移動する,という感じで上から下に走査する # ------------------- Answer -------------------- #code:python N, L = map(int, input().split()) field = [input() for _ in range(L)] goal = input() idx = goal.index('o') // 2 for now in range(N): i = now for y in range(L): if (now*2 + 1 < len(field[0])) and (field[y][now*2 + 1] == '-'): now += 1 elif (now*2 - 1 > 0) and field[y][now*2 - 1] == '-': now -= 1 if now == idx: print(i + 1) exit() # ACしたけど # nowを0-Nではなく,そもそも籤のあるインデックスで管理してみたほうが楽なのではないか N, L = map(int, input().split()) field = [input() for _ in range(L)] goal = input().index('o') for now in range(0, (N-1)*2+1, 2): i = now for y in range(L): if (now + 1 < len(field[0])) and (field[y][now + 1] == '-'): now += 2 elif (now - 1 > 0) and field[y][now - 1] == '-': now -= 2 if now == goal: print(i//2+1) exit() # ------------------ Sample Input ------------------- 10 2 | |-| |-| |-| |-| | |-| |-| |-| |-| |-| o 3 2 | |-| |-| | o 4 2 | | | | | | | | o 9 8 | | | | | | | | | |-| | |-| | |-| | | | |-| | |-| | | | |-| | | | | |-| | | | |-| | | |-| | | |-| |-| | | | |-| | |-| | |-| | | | | | | |-| | | o # ----------------- Length of time ------------------ # 24分AC # -------------- Editorial / my impression ------------- # 最後の当たり行がローカル環境だとinput()で上手く読み込めなくて,テストできなくて困った。 # 効率の悪い方法でといてしまった気がする。 # ----------------- Category ------------------ #AtCoder #あみだくじ #変な入力
de0808e51214bbb009111f12697f806037f1db56
LaBravel/Tedu-code
/python_base/weekly test02/5.py
329
3.609375
4
def calculate(i,j = 0) : k = i + j i = int(k / 2) j = int(k % 2) return [i,j] L = [int(input("有多少钱?")),0] num = 0 while 1 : num += L[0] L = calculate(*L) if sum(L) == 1 and L[0] == 1 : num += 1 break elif sum(L) == 1 and L[1] == 1 : break print("能买",num,'瓶')
c438e46b3e054242945310092c189c1fd3cc289e
pydevjason/Python-VS-code
/scope_closures.py
596
4.0625
4
# a closure is a programming pattern in which a scope retains access to an enclosing scopes names # example def outer(): candy = "Snickers" def inner(): return candy return inner() # returning inner is the closure print(outer()) print() def multiply(a, b): return a * b def divide(a, b): return a / b def calculate(func, a, b): return func(a, b) print(calculate(multiply, 10, 5)) print() def a(): def b(): def c(): return val return c() return b() print(a()) val = "Hello"
c683dcf4128c66c84ff242955e239ed37b1f3748
kirypto/Challenges
/AdventOfCode/2019/day2.py
2,049
3.546875
4
from itertools import product from typing import List, Tuple, Union from python_tools.advent_of_code.puzzle_runner_helpers import AdventOfCodeProblem, TestCase from python_tools.advent_of_code.y2019_int_code_computer import IntCodeComputer def part_1_solver(part_1_input: List[int]) -> List[int]: input_program, noun, verb = part_1_input modified_program = list(input_program) if noun is not None: modified_program[1] = noun if verb is not None: modified_program[2] = verb return IntCodeComputer(modified_program).run() def part_2_solver(part_2_input: Tuple[List[int], int]) -> Tuple[int, int]: input_program, desired_output = part_2_input possible_verbs = possible_nouns = list(range(min(100, len(input_program)))) all_possible_noun_verb_combinations = product(possible_nouns, possible_verbs) for noun, verb in all_possible_noun_verb_combinations: modified_program = input_program if noun is not None: modified_program[1] = noun if verb is not None: modified_program[2] = verb result = IntCodeComputer(input_program).run() if result[0] == desired_output: return noun, verb return -1, -1 def translate_input(puzzle_input_raw: str, part_num: int) -> Union[Tuple[List[int], int, int], Tuple[List[int], int]]: if part_num == 1: return [int(x) for x in puzzle_input_raw.split(",")], 12, 2 else: return [int(x) for x in puzzle_input_raw.split(",")], 19690720 part_1_test_cases = [ TestCase([2, 0, 0, 0, 99], ([1, 0, 0, 0, 99], None, None)), TestCase([2, 3, 0, 6, 99], ([2, 3, 0, 3, 99], None, None)), TestCase([2, 4, 4, 5, 99, 9801], ([2, 4, 4, 5, 99, 0], None, None)), TestCase([30, 1, 1, 4, 2, 5, 6, 0, 99], ([1, 1, 1, 4, 99, 5, 6, 0, 99], None, None)) ] part_2_test_cases = [ TestCase((5, 6), ([2, -1, -1, 0, 99, 3, 4], 12)) ] problem = AdventOfCodeProblem( part_1_test_cases, part_1_solver, part_2_test_cases, part_2_solver, translate_input )
06184a9d213045bf1748ee132468043b1bda76c7
chiragbagde/PHI-Education
/data structures/priority queue.py
1,257
4.15625
4
class PriorityQueue(): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str("priority: "+str(i[0])+ " element: "+str(i[1])+" ") for i in self.queue]) def isEmpty(self): return len(self.queue) == 0 def insert(self, data, priority): self.queue.append((priority, data)) self.queue.sort(reverse=True) def delete(self): if(len(self.queue)<=0): print("queue underflow") return -1 else: return self.queue.pop() if __name__ == '__main__': n = int(input("enter number of elements in Queue: ")) myQueue = PriorityQueue() for i in range(n): el = int(input("enter element in Queue: ")) p = int(input("enter priority : ")) myQueue.insert(el,p) print(myQueue) while(True): choice = int(input("\n ------------------------------------------------ \nEnter your choice: \n 1.print() \n 2.delete() \n 3.Exit \n ------------------------------------------------ \n")) if choice == 1: print(myQueue) elif choice == 2: myQueue.delete() print(myQueue) else: break
d2e3afaf3e1dab6b735464bdc4cd64d1865e4397
calvindajoseph/patternrecognition
/ClassifierGUI.py
2,271
4
4
""" A simple tkinter GUI for model demonstration. """ # Ignore warnings import warnings warnings.filterwarnings("ignore") # Import ModelClassifier from ModelClasses import ModelClassifier # Import tkinter import tkinter as tk # Set the classifier # May take some time, especially if loaded to CPU classifier = ModelClassifier() # Set main window window = tk.Tk() window.title("Sequence Classifier") def predict(): """ The model prediction. Full workings are simpler to explain in ClassifierExample.py """ first = str(first_sentence.get()) second = str(second_sentence.get()) prediction_str = classifier.print_prediction(first, second) txt_logs.delete('1.0', tk.END) txt_logs.insert(tk.INSERT, prediction_str) # Set tkinter variables for first and second sentence first_sentence = tk.StringVar() second_sentence = tk.StringVar() # Set label for the first sentence lbl_first_sentence = tk.Label(master=window, text="First Sentence:") lbl_first_sentence.grid( row=0, column=0, sticky="w", padx=5, pady=5) # Set label for the second sentence lbl_second_sentence = tk.Label(master=window, text="Second Sentence:") lbl_second_sentence.grid( row=1, column=0, sticky="w", padx=5, pady=5) # Set entry space for the first sentence entry_first_sentence = tk.Entry(master=window, width=50, textvariable=first_sentence) entry_first_sentence.grid( row=0, column=1, sticky="nswe", padx=5, pady=5) # Set entry space for the second sentence entry_second_sentence = tk.Entry(master=window, width=50, textvariable=second_sentence) entry_second_sentence.grid( row=1, column=1, sticky="nswe", padx=5, pady=5) # Set the button to run the classifier btn_classify = tk.Button( master=window, text="Classify", command=predict) btn_classify.grid( row=2, column=0, columnspan=2, sticky="nswe", padx=5, pady=5) # Text that contains the results txt_logs = tk.Text( master=window, height=15, width=50, fg="white", bg="black") txt_logs.grid( row=3, column=0, columnspan=2, sticky="nswe", padx=5, pady=5) txt_logs.insert(tk.INSERT, "Prediction") # Mainloop the window window.mainloop()
412e6c6aaaa4f737ba831ba6151451056bfc58f0
blessey15/pehia-python-tutorials
/q7.py
203
3.65625
4
l=[] print('Enter the no. of rows & columns:') (r, c)=map(int, input().split(',')) for i in range(r): a=[] for j in range(c): y=i*j a.append(y) l.append(a) print(l)
fcea316a1c4e15eb7533a16cca5dabeaaf2c7581
815382636/codebase
/python/foundation_level/my_caculate.py
558
3.734375
4
""" 1.使用 and 、 or 时,尽量将每一小部分用()括起来,利于和他人配合工作,防止歧义等 """ """ 数值之间做逻辑运算 (1)and运算符,只要有一个值为0,则结果为0,否则结果为最后一个非0数字 (2)or运算符,只有所有值为0结果才为0,否则结果为第一个非0数字 """ print(0 and 1) print(2 and 3) print(0 or 0) print(0 or 1) print(2 or 3) """ 算数运算优先级: 混合运算优先级顺序: () 高于 ** 高于 * / // % 高于 + - """
4cc58a287a8fe864968bcc37688cd51e87f6cc67
ZimingGuo/MyNotes01
/MyNotes_01/Step01/2-BASE02/day04_08/demo03.py
1,445
3.9375
4
# author: Ziming Guo # time: 2020/2/11 """ demo03: 函数内存图 """ # 在方法区中存储函数代码,不执行函数体 def fun01(a): a = 100 num01 = 1 # 因为调用函数,所以开辟一块内存空间,叫做栈帧 # 用于存储在函数内部定义的变量(包含参数). fun01(num01) # 这句话就是要把 num01 给 a # 也就是让 a 指向 num01 所指向的数据 # 这句话就是:在内存里开辟了一块栈帧,告诉栈帧 a = num01 # 函数执行完毕后,栈帧立即释放(其中定义的变量也会销毁,即 a 也没了). # 也就是栈帧立即销毁了 # 栈帧立即销毁了,里面的变量都销毁了 # 但是变量所指向的对象是否销毁了,不知道(要看这个数据的引用级数) print(num01)#1 def fun02(a): # 改变的是传入的可变对象 a[0] = 100 list01 = [1] fun02(list01) print(list01[0])# 100 def fun03(a): # 改变的是fun03栈帧中变量a的指向 a = 100 # 如果要是这样写的话,改变的就不是列表里的元素了 # 而是 a 不再指向原来那个列表了,指向了一个新的数值 # 可变类型 可以改变,而不是一定会改变 list01 = [1] fun03(list01) print(list01[0])# 1 def fun04(a): a[1] = [200] list01 = [1,[2,3]] fun04(list01) # 此时调用函数了,所以开辟了栈帧区域 print(list01[1])# [200]
83f51c51de853f1053812650fd76442d74f01b7b
Palash51/Python-Programs
/program/selection.py
353
3.640625
4
def sel_sort(A): for i in range(len(A)): least = i for j in range(i+1,len(A)): if A[j] < A[least]: least = j temp = A[i] A[i] = A[least] A[least] = temp # swap(A,least,i) #def swap(A,x,y): # temp = A[x] # A[x] = A[y] # A[y] = temp A = [1,3,8,4,2,5,9,7] fun = sel_sort(A) #print fun print A
f4b8ee28747c4891c943427c05b0623f758381d4
jofre44/EIP
/scripts/calculator.py
1,456
4.03125
4
class calculadora: _counter = 0 def __init__(self, num_1, num_2): try: num_1 = float(num_1) num_2 = float(num_2) except: raise ValueError('Valores introducidos no son numeros') calculadora._counter += 1 self.id = calculadora._counter self.num_1 = num_1 self.num_2 = num_2 if self.id == 1: print("Inicializando clase Calculadora por primera vez") print("Actividad 4. Programacion Avanzada en Python") print("Alumno: Jose Sepulveda \n") def sumar(self, num_1=None, num_2=None): if num_1 == None: num_1 = self.num_1 if num_2 == None: num_2 = self.num_2 return num_1 + num_2 def restar(self, num_1=None, num_2=None): if num_1 == None: num_1 = self.num_1 if num_2 == None: num_2 = self.num_2 return num_1 - num_2 def multiplicar(self, num_1=None, num_2=None): if num_1 == None: num_1 = self.num_1 if num_2 == None: num_2 = self.num_2 return num_1 * num_2 def dividir(self, num_1=None, num_2=None): if num_1 == None: num_1 = self.num_1 if num_2 == None: num_2 = self.num_2 if num_2 == 0: print("Error! Division por cero no definida") return None return num_1 / num_2
cd775bd9ec6e53258c96aa3c4607707588ef0cfd
roxolea5/pythonRefresh
/Sesion1/retos.py
2,479
4.0625
4
# Reto 1 print("Ingresa el primer número") reto1_str1 = input() reto1_num1 = int(reto1_str1) print("Ingresa el segundo número") reto1_str2 = input() reto1_num2 = int(reto1_str2) print ("El resultado de la concatenación de {} y {} es {}".format(reto1_str1, reto1_str2, reto1_str1 + reto1_str2)) print ("El resultado de la concatenación de {} y {} es {}".format(reto1_num1, reto1_num2, reto1_num1 + reto1_num2)) # Reto 2 print("Ingresa el primer número") reto2_num1 = int(input()) print("Ingresa el segundo número") reto2_num2 = int(input()) print ("El resultado de la resta de {} y {} es {}".format(reto2_num1, reto2_num2, reto2_num1 - reto2_num2)) print ("El resultado del módulo de {} y {} es {}".format(reto2_num1, reto2_num2, reto2_num1 % reto2_num2)) reto2_dato1 = True reto2_dato2 = False print("Operacion or de un true y un false ") print(reto2_dato1 or reto2_dato2) # Reto3 print("Dame un numero y te daré su tabla de multiplicar hasta 10") reto3_num = int(input()) tabla = [1,2,3,4,5,6,7,8,9,10] for num in tabla: print("{} * {} = {}".format(reto3_num, num, reto3_num * num)) # Reto4 print("Selecciona el topping que quieres en tu helado: \n 1. 'oreo' \n 2. 'm&m' \n 3. 'fresas' \n 4. 'brownie'") reto4_sabor = int(input()) if reto4_sabor == 1: print ("El helado de oreo tiene un precio de $19.00") elif reto4_sabor == 2: print ("El helado con m&m tiene un precio de $25.00") elif reto4_sabor == 3: print ("El helado con fresas tiene un precio de $22.00") elif reto4_sabor == 4: print ("El helado con brownie tiene un precio de $28.00") else: print("Esa opción no está disponible") # Reto 5 print("Ingresa el primer número") num_1 = int(input()) print("Ingresa el segundo número") num_2 = int(input()) print("Seleciona la operación a realizar") print("1: Suma") print("2: Resta") print("3: Multiplicación") print("4: División") operation = input() if operation == '1': op_name = 'suma' result = num_1 + num_2 elif operation == '2': op_name = 'resta' result = num_1 - num_2 elif operation == '3': op_name = 'multiplicación' result = num_1 * num_2 elif operation == '4': op_name = 'división' if num_2 == 0: print("Imposible división entre 0") result = "ERROR" else: result = num_1 / num_2 else: print("Opción inválida") op_name = 'operación indefinida' result = 'ERROR' print("La {} de {} con {} es {}".format(op_name, num_1, num_2, result))
a7bf909b39f09af1cfbd580fc85d404d45c3cb38
Niksonber/production
/sql.py
4,857
3.671875
4
import sqlite3 import os import io class DB(): def __init__(self): self.name = 'data.db' self.exists = False if os.path.isfile(self.name): self.exists = True self.pedidos = "(client_id)" def initDB(self): self.connection = sqlite3.connect(self.name) self.crsr = self.connection.cursor() if not self.exists: sql_command = """CREATE TABLE impressoras ( impressora_id INTEGER PRIMARY KEY, impressora_nome VARCHAR(15) );""" # execute the statement self.crsr.execute(sql_command) sql_command = """CREATE TABLE manutencao ( impressora_id INTEGER, man_inicio DATE, man_fim DATE, FOREIGN KEY(impressora_id) REFERENCES impressoras(impressora_id) );""" # execute the statement self.crsr.execute(sql_command) # SQL command to create a table in the database sql_command = """CREATE TABLE pecas ( peca_id INTEGER PRIMARY KEY, peca_nome VARCHAR(30), n_orcamento INTEGER, material VARCHAR(5), qualidade VARCHAR(5), tempo_de_impressao REAL, finalizada BOOLEAN, massa REAL);""" # execute the statement self.crsr.execute(sql_command) sql_command = """CREATE TABLE colaboradores ( colaborador_id INTEGER PRIMARY KEY, colaborador_nome VARCHAR(20) , colaborador_contato VARCHAR(30), colaborador_associacao VARCHAR(20), colaborador_data_associacao DATE, colaborador_data_desassociacao DATE);""" self.crsr.execute(sql_command) sql_command = """CREATE TABLE clientes ( cliente_id INTEGER PRIMARY KEY, cliente_nome VARCHAR(20) , cliente_contato VARCHAR(30), cliente_data_de_contato DATE);""" self.crsr.execute(sql_command) sql_command = """CREATE TABLE pedidos ( n_orcamento INTEGER PRIMARY KEY, cliente_id INTEGER, coladorador_id INTEGER, origem VARCHAR(5), data_pedido DATE, data_deadline DATE, preco REAL, finalizada BOOLEAN, FOREIGN KEY(cliente_id) REFERENCES clientes(cliente_id), FOREIGN KEY(coladorador_id) REFERENCES colaboradores(colaborador_id) );""" self.crsr.execute(sql_command) #save self.connection.commit() def insertInDB(self, tableName, data): #TODO: insert name of table aux = """ VALUES (""" for i in range(len(data)): if i != len(data)-1: aux = aux + """?,""" else: aux = aux + """?)""" command = """INSERT INTO """ + tableName + aux self.crsr.execute(command, data) self.connection.commit() def search(self, datas, tables, conditions='', modifiers=''): command = "SELECT {0} FROM {1}".format(datas, tables) if conditions != '': command = command + " WHERE {0}".format(conditions) if modifiers != '': command = command + " {0}".format(modifiers) #self.crsr.execute("SELECT * FROM impressoras") self.crsr.execute(command) rows = self.crsr.fetchall() print(rows) def createBackup(self): with io.open('db.bu', 'w') as f: for linha in self.connection.iterdump(): f.write('%s\n' % linha) if __name__ == "__main__": db = DB() db.initDB() #db.insertInDB('impressoras',(1,'bla')) db.search('*', 'impressoras', "impressora_id=1")
59b95287136977497a0860abdc6e8524e84ec2ff
puneethrchalla/ds-algos
/recursion/recursive_range.py
163
3.734375
4
def recursive_range(num): if num == 1: return 1 return num + recursive_range(num-1) print(recursive_range(6)) # 21 print(recursive_range(10)) # 55
7227de6f763ed78f50d40c7782a653c5cac9fd63
Aigarsss/py
/bubble.py
3,424
4.09375
4
# bubble sort. check out https://www.calhoun.io/lets-learn-algorithms-implementing-bubble-sort/ # li = [4, 6, 1, 2, 5, 13, 46] # def bubble_sort(a): # for x in range(len(a)): # for i in range(len(a)-1): # if a[i] > a[i+1]: # a[i], a[i+1] = a[i+1], a[i] # return a # print(li) # print(bubble_sort(li)) ############################ bubble sort again # # Sweep part non optimized # example = [5, 4, 2, 3, 1, 0] # def sweep(numbers): # n = len(numbers) # first_index = 0 # second_index = 1 # while second_index < n: # first_number = numbers[first_index] # second_number = numbers[second_index] # if first_number > second_number: # numbers[first_index] = second_number # numbers[second_index] = first_number # first_index += 1 # second_index += 1 # def bubble_sort(numbers): # n = len(numbers) # for i in range(n): # sweep(numbers) # return numbers # #print(sweep(example)) # print(bubble_sort(example)) # Sweep part optimized # example = [5, 4, 2, 3, 1, 0] # def sweep(numbers, prevPasses): # prev passess added # n = len(numbers) # first_index = 0 # second_index = 1 # while second_index < (n - prevPasses): # prev passess added # first_number = numbers[first_index] # second_number = numbers[second_index] # if first_number > second_number: # numbers[first_index] = second_number # numbers[second_index] = first_number # first_index += 1 # second_index += 1 # def bubble_sort(numbers): # n = len(numbers) # for i in range(n): # sweep(numbers, i) # i passess added # return numbers # #print(sweep(example)) # print(bubble_sort(example)) ######################################## # 1. Sort a list of 25 numbers in REVERSE order # Given the array of numbers: # nums = [21, 4, 2, 13, 10, 0, 19, 11, 7, 5, 23, 18, 9, 14, 6, 8, 1, 20, 17, 3, 16, 22, 24, 15, 12] # def sort_desc(nums): # n = len(nums) # for i in range(n): # first_index = 0 # second_index = 1 # while second_index < n: # a = nums[first_index] # b = nums[second_index] # if nums[first_index] < nums[second_index]: # nums[second_index] = a # nums[first_index] = b # first_index += 1 # second_index += 1 # return nums # print(sort_desc(nums)) ################# # print('a'>'b') # houses = ['Tim', 'Tommy', 'Brad'] # def deliver_presents_iteratively(): # for i in houses: # print("Present delivered to: " + i) # print(deliver_presents_iteratively()) # print(5//2) # recursion # 1 + + 3 ... 10 # def sum_recursive(current_number, accumulated_sum): # #base case # if current_number == 11: # return accumulated_sum # else: # return sum_recursive(current_number + 1, accumulated_sum + current_number) # print(sum_recursive(1,0)) #### factorial 5! = 5x4x3x2x1 # num = 5 # def factorial(num): # if num == 0: # return 1 # else: # return num * factorial(num-1) # print(factorial(num)) # print(factorial(num)) # 1 1 2 3 5 8 13 21 34 55 # 1 2 3 4 5 6 7 8 9 10 def fib(n): return n print(fib(5)) print([i for i in range(10) if i>6]) f = lambda a: a+a print(f(5))
46bc020b5f29cef13c594a24fb2fd25b9096eda7
aheui/snippets
/_tools/aheuilize/aheuilize.py
1,845
3.90625
4
import math def divide(a): b = int(a / 2) if a % 2 == 1: return [b, b + 1] return [b, b] def factorization(a): primes = [] factor = 2 if a < 2: return [a] while a > 1: while a % factor: factor += 1 primes.append(factor) a = int(a / factor) return primes def compress_factors(a): is_first_2 = True is_first_3 = True cnt_2 = 0 cnt_3 = 0 result = [] for i in a: if i == 2: cnt_2 += 1 if is_first_2: is_first_2 = False elif not cnt_2 % 3: result.append(8) elif i == 3: cnt_3 += 1 if is_first_3: is_first_3 = False elif not cnt_3 % 2: result.append(9) else: result.append(i) if cnt_2 % 3 == 2: result.append(4) elif cnt_2 % 3 == 1: result.append(2) if cnt_3 % 2 == 1: result.append(3) return result def is_prime(a): sqrt = int(math.sqrt(a)) if a < 2: return False i = 2 while a % i and i <= sqrt: i += 1 return sqrt + 1 == i def number2Aheui(a): cnt = -1 result = "" table = [ "바", "받반타", "반", "받", "밤", "발", "밦", "밝", "밣", "밢" ] if a < 10: return table[a] if is_prime(a): for i in divide(a): result += number2Aheui(i) result += "다" return result else: for i in compress_factors(factorization(a)): result += number2Aheui(i) cnt += 1 for i in range(cnt): result += "따" return result def trace2Aheui(a): result = "" for i in range(len(a)): result += number2Aheui(ord(a[i]))+"맣" return result
7cc0d7514cedf6e5fa21b1e87f1400d87a0fcf0b
Giby666566/programacioncursos
/tarea4.py
278
4.21875
4
#congetura de collatz numero=int(input('dame un número ')) while numero>=1: if numero%2==0: print(numero) numero=numero/2 elif numero%2==1: print(numero) numero=(numero*3)+1 if numero==1: print(numero) break
ec64b987cce394bc9cb016f8d274a9b652cb12c0
davidyc/GitHub
/davidyc/simplepython/file.py
1,306
3.78125
4
poem = '''\ Программировать весело. Если работа скучна, Чтобы придать ей весёлый тон - используй Python! ''' f = open('poem.txt', 'w') # открываем для записи (writing) f.write(poem) # записываем текст в файл f.close() # закрываем файл f = open('poem.txt') # если не указан режим, по умолчанию подразумевается # режим чтения ('r'eading) while True: line = f.readline() if len(line) == 0: # Нулевая длина обозначает конец файла (EOF) break print(line, end='') f.close() # закрываем файл import pickle # имя файла, в котором мы сохраним объект shoplistfile = 'shoplist.data' # список покупок shoplist = ['яблоки', 'манго', 'морковь'] # Запись в файл f = open(shoplistfile, 'wb') pickle.dump(shoplist, f) # помещаем объект в файл f.close() del shoplist # уничтожаем переменную shoplist # Считываем из хранилища f = open(shoplistfile, 'rb') storedlist = pickle.load(f) # загружаем объект из файла print(storedlist)
13e8c28e6341bb3d0a3fe9c23569ef5ad82f435d
leonardocouy/mini_curso_python
/input.py
483
4
4
nome = input("Digite seu nome:") idade = int(input("Digite sua idade: ")) dinheiro = float(input("Digite quant dinheiro: R$")) print("%s, você tem %i anos e R$%.2f" % (nome, idade, dinheiro)) try: num = int(input("Digite um numero:")) print(num) except ValueError: print("Ops, verifique se digitou um numero valido") try: num = int(input("Digite um numero:")) print(num) except ValueError: raise ValueError("Ops, verifique se digitou um numero valido")
92f5d37272ac5b92976d5d5f21c18d4715de8be7
xjtu-BeiWu/python_base
/base_tensorflow/rnn_classification_example.py
2,661
3.515625
4
# -*- coding: utf-8 -*- # Author: bellawu # Date: 2021/3/15 21:33 # File: rnn_classification_example.py # IDE: PyCharm import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorflow.python.ops.rnn import dynamic_rnn tf.set_random_seed(1) mnist = input_data.read_data_sets('MNIST_DATA', one_hot=True) lr = 0.001 training_iters = 100000 batch_size = 128 n_inputs = 28 n_steps = 28 n_hidden_units = 128 n_classes = 10 x = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) y = tf.placeholder(tf.float32, [None, n_classes]) w = { 'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])), 'out': tf.Variable(tf.random_normal([n_hidden_units, n_classes])) } b = { 'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])), 'out': tf.Variable(tf.constant(0.1, shape=[n_classes, ])) } def rnn(x_inputs, weights, biases): # x_inputs(128 batch, 28 steps, 28 inputs)-->(128*28, 28 inputs) # -1表示根据n_inputs大小计算出数组的另外一个shape的属性值,使其符合原来的维度 x_inputs = tf.reshape(x_inputs, [-1, n_inputs]) # x_in(128 batch * 28 steps, 128 hidden) = # x_inputs(128*28, 28) * weights(28 inputs, 128 hidden) + biases(128 hidden, ) x_in = tf.matmul(x_inputs, weights['in']) + biases['in'] # x_in(128 batch, 28 step, 128 hidden) x_in = tf.reshape(x_in, [-1, n_steps, n_hidden_units]) lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units) init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32) outputs, states = dynamic_rnn(lstm_cell, x_in, initial_state=init_state) outputs = tf.unstack(tf.transpose(outputs, [1, 0, 2])) results = tf.matmul(outputs[-1], weights['out']) + biases['out'] return results prediction = rnn(x, w, b) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) train_op = tf.train.AdamOptimizer(lr).minimize(cost) correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) step = 0 while step * batch_size < training_iters: batch_x_input, batch_y_input = mnist.train.next_batch(batch_size) batch_xs = batch_x_input.reshape([batch_size, n_steps, n_inputs]) sess.run([train_op], feed_dict={ x: batch_xs, y: batch_y_input, }) if step % 20 == 0: print(sess.run(accuracy, feed_dict={ x: batch_xs, y: batch_y_input, })) step += 1
dc647f44294b38b6116bb845b2a24ffabf661421
JohnsonWang0319/MystanCodeProjects
/stanCode_Projects/my_drawing/bouncing_ball.py
1,689
3.6875
4
""" File: Bouncing_ball.py Name: Johnson """ from campy.graphics.gobjects import GOval from campy.graphics.gwindow import GWindow from campy.gui.events.timer import pause from campy.gui.events.mouse import onmouseclicked VX = 3 DELAY = 10 GRAVITY = 1 SIZE = 20 REDUCE = 0.9 START_X = 30 START_Y = 40 # Global Variables window = GWindow(800, 500, title='bouncing_ball.py') times = 0 ball = GOval(SIZE, SIZE, x=START_X, y=START_Y) on_the_run = False def main(): """ This program simulates a bouncing ball at (START_X, START_Y) that has VX as x velocity and 0 as y velocity. Each bounce reduces y velocity to REDUCE of itself. """ onmouseclicked(start) def start(mouse): global times, on_the_run if not on_the_run: # Make sure when the ball is bouncing the mouseclicked won't work on_the_run = True ball.filled = 'True' window.add(ball) vy = 0 while on_the_run: if times < 3: # Let the ball can only bounce three times if ball.y + SIZE >= window.height: vy = -vy * REDUCE vy += GRAVITY if ball.x + SIZE >= window.width: # Let the ball recover to its original condition times += 1 ball.x = START_X ball.y = START_Y vy = 0 on_the_run = False ball.move(VX, vy) vy += GRAVITY print(vy, ball.y) pause(DELAY) else: break if __name__ == "__main__": main()
b1bae692accd519aab2e2f1616a97d1d88cc3819
leeyou34/JumpToPython
/02-6 집합 자료형/set.py
1,025
3.84375
4
# 집합(set)자료형 : { 값, , ,} # 요소의 순서가 정해져 있지 않다(unordered) # 요소의 중복(X) s = {1,5,2,2,3,3,7} print('s=', s) print(8 in s) s = set('apple') print('s=', s) s = set('자바211기 화이팅!') print('s=', s) s = set() print('type(s)', type(s)) a = {1,2,3,4,5,6} b = {3,4,5,6,7,8} print('a=', a) print('b=', b) s = a | b print('a | b = ', a | b ) s = set.union(a,b) s = a & b s = a - b # set 조작하기 a = {1,2,3,4} print('a=', a) # 로또 번호 생성기 만들기 import random lotto=random.sample(range(1,46),6) print(lotto) import random print(int(random.random()*45)+1) print('______________________lotto gen program______________') print() print('몇 세트를 만드시겠습니까?') set_num = int(input('정수입력:')) print('_________________________') for n in range(set_num): lotto=set() while len(lotto) < 6: lotto.add(int(random.random()*45) +1) print(lotto)
e2ee0dbe3da76948e048c60aeb85aeaecb139a8d
mike567984/Computer-vision-with-ants
/ants.py
533
3.71875
4
import cv2 import numpy as np def canny(image): gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)#changes the 3 color grops to gray only for easy detecetion of edges canny = cv2.Canny(gray, 50 ,150)#sets threashold to the low and high and anything inbetween is shown/uses dirivite in all directions return canny image = cv2.imread('ant_one.jpg') ant_image= np.copy(image)#create a new matrix of the imamge canny = canny(ant_image) cv2.imshow("result",canny)#show the image but in gray cv2.waitKey(0)#infinitely shows image
3fe6785a397763917fb62502b319f12a37aa3d7b
hyjae/udemy-data-wrangling
/DataExtraction/NREL_csv.py
1,121
3.75
4
""" The data comes from NREL (National Renewable Energy Laboratory) website. Each file contains information from one meteorological station, in particular - about amount of solar and wind energy for each hour of day. The data should be returned as a list of lists (not dictionaries). You can use the csv modules "reader" method to get data in such format. Another useful method is next() - to get the next line from the iterator. You should only change the parse_file function. """ import csv import os DATADIR = "" DATAFILE = "745090.csv" def parse_file(datafile): name = "" list = [] with open(datafile,'r') as f: name = f.readline().split(',')[1] colnames = f.readline().split(',') for line in f: data = [x.strip() for x in line.split(',')] list.append(data) return name, list def test(): datafile = os.path.join(DATADIR, DATAFILE) name, data = parse_file(datafile) print(name) assert name == "MOUNTAIN VIEW MOFFETT FLD NAS" assert data[0][1] == "01:00" assert data[2][0] == "01/01/2005" assert data[2][5] == "2" test()
26120b7b7711c9a36ad09b1334be3ca5f89750ec
gordonfierce/blackjack
/blackjack/dealer.py
1,350
3.734375
4
from blackjack.hand import Hand class Dealer: """The dealer is one of the two agents in the game, and plays deterministically against the player. Responsibilities: The dealer posesses a hand. The dealer will hit whenever the dealer's hand is under 17. The dealer discards cards at the end of a round. Collaborators: The dealer posesses a hand. The dealer is one of the two agents in the game. """ def __init__(self): self.hand = Hand() def deal(self, deck): self.hand.grab(deck.draw()) self.hand.grab(deck.draw()) def show_first_card(self): card_string = self.hand.show_cards(just_one=True) print("The dealer has a: {}".format(card_string)) def show_cards(self): card_list = self.hand.show_cards() card_string = ", ".join(card_list) hand_value = self.hand.value() print("The dealer has: {} ({})".format(card_string, hand_value)) def hit_from_deck(self, deck): self.hand.grab(deck.draw()) def dump_cards(self): self.hand = Hand() def choose_to_hit(self): return self.hand.value() < 17 def get_value(self): return self.hand.value() def is_bust(self): return self.hand.value() > 21 def has_blackjack(self): return self.hand.is_blackjack()
720802def1a11569203c8bbcd023054f67fa2603
Sujjzit/Codefights
/splittingint.py
243
3.609375
4
Example For n = 1230, the output should be isLucky(n) = true; For n = 239017, the output should be isLucky(n) = false. def isLucky(n): return sum(map(int, list(str(n)[:(len(str(n))/2)]))) == sum(map(int, list(str(n)[(len(str(n))/2):])))
52107a682c08dcb701b699c4178e146c20acb48d
asim09/Algorithm
/decorator/decorator.py
751
3.8125
4
import time import functools def do_twice(func): def wrapper_do_twice(*args, **kwargs): # func(*args, **kwargs) func(*args, **kwargs) return func(*args, **kwargs) return wrapper_do_twice def timer(func): """Print the runtime of the decorated function""" @functools.wraps(func) def wrapper_timer(*args, **kwargs): start_time = time.clock() # 1 # print start_time value = func(*args, **kwargs) end_time = time.clock() # 2 run_time = end_time - start_time # 3 # print run_time # print("Finished {func.__name__!r} in {run_time:.4f} secs") # print 'finished in ' + str(run_time) + ' sec' return value return wrapper_timer
a16ac9217deaf5e6485cacd9e0e3581f2b7da25f
nilam1996/first_test
/armstrong.py
209
4.09375
4
index=0 sum=0 input=int(raw_input("Enter your num")) num=input while(num>0): reminder=num%10 sum+=reminder**3 num//=10 if sum==input: print("number is armstrong") else: print("number is not armstrong")
c200ca889c354e2b2da185e7de5f779b7db90f6d
memphis95/Algorithms
/cses/Introductory Problem/8_two_sets_2.py
1,136
4.0625
4
""" PS: To divide the numbers 1,2,...,n into two sets of equal sum """ def is_two_sets(n): a = [] b = [] sum_n = (n * (n+1))//2 """ The below approach as works : each set of values have same sum so that will be 1/2 of sum_of_n_numbers assign subset_sum = 1/2 (sum_of_n_numbers) for each number from n to 1: if number is less than or equal to the subset_sum: append the number to the subset A decrease the subset_sum by number else: append the number to the subset B main idea -> fill the one of the subsets with the numbers whose summation equals to subset_sum """ if sum_n%2 ==0: subset_sum = sum_n //2 for i in range(n,0,-1): print(i, subset_sum) if i <= subset_sum: subset_sum -= i a.append(i) else: b.append(i) print("YES") print(len(a)) # print(*a, sep=' ') print(len(b)) # print(*b, sep=' ') else: print("NO") if __name__ == "__main__": number = int(input()) is_two_sets(number)
a67dc87a28d9452580871951c78c9d92e11392d3
rsurpur20/ComputerScienceHonors
/game.py
3,577
4.28125
4
# Roshni Surpur # 9/24/18 # OMH # For this assignment, you will work on a text game. Examples of text games are choose your own adventures, perhaps a dice or card game with text output, fortune tellers, etc. Choose content for your game that is engaging; games that don’t have a compelling goal or that don’t provide a positive user experience are not ideal. Have people outside of the class test your game to give you feedback on areas for improvement! # rock paper scissors import random def rockpaperscissors(): options=["rock", "paper","scissors"] computerchoice=random.choice(options) # print(computerchoice) def paper(userchoice,computerchoice): if userchoice=="rock": print("you lose") elif userchoice=="scissors": print("you win") else: print("Tie!") def scissors(userchoice,computerchoice): if userchoice=="paper": print("you lose") elif userchoice=="rock": print("you win") else: print("Tie!") def rock(userchoice,computerchoice): if userchoice=="scissors": print("you lose") elif userchoice=="paper": print("you win") else: print("Tie!") def playgame(userchoice): print("User choose:",userchoice) print("Computer choose:",computerchoice) if computerchoice=="paper": paper(userchoice,computerchoice) elif computerchoice=="scissors": scissors(userchoice,computerchoice) elif computerchoice=="rock": rock(userchoice,computerchoice) def ask(): userchoice=str.lower(input("Choose 'rock','paper','scissors'. \n")) if userchoice in ("rock","scissors","paper"): playgame(userchoice) else: print("I did not understand you answer.") ask() ask() def cardgame(): num={ 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 11:"J", 12:"Q", 13:"K" } # print(random.choice(list(num.values()))) sign=["spades","diamonds","clover","hearts"] computernumber=random.choice(list(num.keys())) # print(num.values()) computersign=random.choice(sign) usernumber=random.choice(list(num.keys())) usersign=random.choice(sign) # print(computernumber) # print(usernumber) if computernumber>usernumber: print("Computer: %s%s"%(num[computernumber],computersign)) print("User: %s%s"%(num[usernumber],usersign)) print("you lose") elif computernumber<usernumber: print("Computer: %s%s"%(num[computernumber],computersign)) print("User: %s%s"%(num[usernumber],usersign)) print("you win") elif computernumber==usernumber: print("tie") print("Computer: %s%s"%(random.choice(list(num.values())),computersign)) print("User: %s%s"%(random.choice(list(num.values())),usersign)) else: print("error") def start(): game=input("Which game would you like to play?\n Type 1 for a cardgame. Type 2 for Rock, Paper, Scissors.") if game in ("1","2"): gameinput=int(game) if gameinput==1: cardgame() elif gameinput==2: rockpaperscissors() else: print("Error Try Again") start() else: print("Did not Understand. Try Again.") start() start()
e31fb0f35973a161249b594e20493bd73399c7db
SilviaAmAm/tf_hackathon
/cubic_function.py
2,378
3.921875
4
""" This script is an example of how to overfit a cubic function using a small feed forward neural network with only one hidden layer. """ import numpy as np import tensorflow as tf import seaborn as sns import matplotlib.pyplot as plt # -------------- ** Generating sample data ** ------------------ x = np.linspace(-2.0, 2.0, 200) x_col = np.reshape(x, (len(x), 1)) y_col = x_col ** 3 # Network parameters hidden_neurons = 15 learning_rate = 0.5 iterations = 500 # -------------- ** Building the graph ** ------------------ # Input data x_ph = tf.placeholder(dtype=tf.float32, shape=[None, 1]) y_ph = tf.placeholder(dtype=tf.float32, shape=[None, 1]) # Creating the weights weights1 = tf.Variable(tf.random_normal([hidden_neurons, 1]), name="W_in-to-hid") bias1 = tf.Variable(tf.zeros([hidden_neurons]), name="b_in-to-hid") weights2 = tf.Variable(tf.random_normal([1, hidden_neurons]), name="W_hid-to-out") bias2 = tf.Variable(tf.zeros([1]), name="b_hid-to-out") # Model z2 = tf.add(tf.matmul(x_ph, tf.transpose(weights1)), bias1) # output of layer1, size = n_sample x hidden_neurons h2 = tf.nn.sigmoid(z2) model = tf.add(tf.matmul(h2, tf.transpose(weights2)), bias2) # output of last layer, size = n_samples x 1 # Cost function cost = tf.reduce_mean(tf.nn.l2_loss(t=(model - y_ph))) # Optimisation operation optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # -------------- ** Running the graph ** ------------------ # Initialisation of the model init = tf.global_variables_initializer() training_cost = [] # Running the graph with tf.Session() as sess: sess.run(init) for iter in range(iterations): opt, c = sess.run([optimizer, cost], feed_dict={x_ph: x_col, y_ph: y_col}) training_cost.append(c) y_pred = sess.run(model, feed_dict={x_ph: x_col}) # -------- ** Plotting the results ** ------------ sns.set() fig1, ax1 = plt.subplots(figsize=(6,6)) ax1.scatter(range(len(training_cost)), training_cost, label="Training cost", marker="o") ax1.set_xlabel('iterations') ax1.set_ylabel('training cost') ax1.legend() plt.show() # -------- ** Plotting the predictions ** ------------- fig2, ax2 = plt.subplots(figsize=(6,6)) ax2.scatter(x, y_col, label="original", marker="o") ax2.scatter(x, y_pred, label="predictions", marker="o") ax2.set_xlabel('x') ax2.set_ylabel('y') ax2.legend() plt.show()
aeb7425b250c2060592666628cd22a96e9d8f15f
mazurcaionut/Python-2.7-programs
/sentence.py
611
3.609375
4
from Tkinter import * e = "Enuntul este aici.Scrie raspunsul:" rc = "raspunsul corect" fereastra = Tk() fereastra.title("Intrebare") fereastra.geometry("300x100") cadru = Frame(fereastra) cadru.grid() enunt = Label(cadru,text=e) enunt.grid() raspuns=Entry(cadru) raspuns.grid() def handler_buton(): if raspuns.get() == rc: rezultatLbl["text"] = "Bravo!" else: rezultatLbl["text"] = "Ai gresit." verificare = Button(cadru,text = "Verifica",command= handler_buton) verificare.grid() rezultatLbl= Label(cadru) rezultatLbl.grid() fereastra.mainloop()
ba557439bd6ee144bae9d0bb01f297f9d1026c4c
rhivent/py_basic
/19abstract_class.py
1,739
3.65625
4
''' abstract class itu semacam class templating, dimana kita hanya mengakses method2,varibel2 yg ada di dlm abstract class, dan kita tidak ingin menginstasiasi class abstract karena hanya berisi interface/ template method yg digunakan oleh Child class atau implement dari kelas lain caranya membuat abstract class yaitu: akses built-in module in python utk method abstract yaitu dari ABC module, yaitu module built-in dari python utk abstract class from abc import ABC, abstractmethod ketika inherit dari ABC module maka perlu decorative dari klass yg menggunakan ABC module tiap method dibuat abstract dengan menambah @abstractmethod di atas method yg ingin dijadikan abstract ketika sudah ada abstract maka kita tidak bisa menginstasiasi seperti cara biasa misal shape = Shape() ==> akan terjadi error utk subclass yg inherit dari superclass yg sudh di jadikan abstrak class maka perlu mengdefinisika semua abstrak method di dlm subclass tersebut jika tidak maka akan error krn subclass tidak mendefinisikan semua method yg dilm abstrak kelas Abstrak class harus mempunyai minimal 1 method abstrack dan mengimport ABC module serti meninherit ABC module di dlm class yg ingin dijadikan abstrak. Method yg dijadikan abstrak harus ada decorative @abstractmethod di atas method yg di deklarasikan/definisikan ''' from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass class Square(Shape): def __init__(self,side): self.__side = side def area(self): return self.__side * self.__side def perimeter(self): return self.__side * self.__side square = Square(5) print(square.area()) print(square.perimeter())
67672fe727895f8474674f5adaabba5b0d6ebc3c
chrisesharp/aoc-2019
/day22/shuffle.py
1,167
3.671875
4
def new_stack(stack): return stack[::-1] def increment(stack, point): i=0 new_stack=[0]*len(stack) while stack: new_stack[i]=stack.pop(0) i = (i+point)%len(new_stack) return new_stack def cut(stack, point): return stack[point:] + stack[:point] def shuffle(input, stack): for line in input.strip().split("\n"): if line.find("new stack") >= 0: stack = new_stack(stack) elif line.find("increment") >= 0: point = int(line.split()[3]) stack = increment(stack, point) elif line.find("cut") >= 0: point = int(line.split()[1]) stack = cut(stack, point) return stack def create_deck(size): stack = [0]*size for i in range(size): stack[i] = i return stack def play(input): n = 10007 times = 1 stack = create_deck(n) for i in range(times): stack = shuffle(input, stack) return stack if __name__ == "__main__": input = open("input.txt").read() stack = play(input) print("Part 1: ", stack.index(2019)) print("Part 2 is a maths problem, not a programming problem! See foo2.py")
c2f70acc01adc3d01cc526e360a9815106306225
Farhajaleel/pythonProject
/CO1/15_color_list.py
388
4.03125
4
# printout all colors from color list 1 not contained in color list 2 color_list_1 = ["red", "black", "green", "yellow", "silver", "orange"] color_list_2 = ["blue", "white", "silver", "gold", "grey", "black"] print("Color list 1:", color_list_1) print("Color list 2:", color_list_2) print("Colors for list 1 not contained in list 2:", [i for i in color_list_1 if i not in color_list_2])
1fd54da0f0cc4637cde869459ef78da07f149062
nozimica/engin310-python
/scripts/e10while01.py
608
4.1875
4
# -*- coding: cp1252 -*- # creo un arreglo vaco valores = [] # le solicito nmeros al usuario num = raw_input('Ingrese un nmero ("" para terminar): ') # mientras no me entregue un "" while num != "": # lo recibido lo convierto a nmero y lo agrego al arreglo valores = valores + [float(num)] # vuelvo a solicitar nmeros al usuario num = raw_input('Ingrese un nmero ("" para terminar): ') # despus de que recib "", aplico la funcin que calcula la desviacin estndar print("Los valores son:") print(valores) print("La desviacin estndar es:") calcularDesvEst(valores)
f3327f6aa558461947f302d1af4773efc8603305
petrLorenc/python-academy
/lesson5/for_search_solution.py
626
3.5
4
text = ''' Situated about 10 miles west of Kemmerer, Fossil Butte is a ruggedly impressive topographic feature that rises sharply some 1000 feet above Twin Creek Valley to an elevation of more than 7500 feet above sea level. The butte is located just north of US 30N and the Union Pacific Railroad, which traverse the valley.''' target = input("What word should I look for?") words = text.split() found = False position = 0 for word in words: word = word.strip(';,._/:') if word == target: print('POSITION: ' + str(position)) found = True position += 1 if not found: print('NO SUCH WORD')
d4a3be7ad09be93d0645c159c1466227328d845b
zaldeg/codewars
/test2.py
548
3.578125
4
def mmultiply_matrix(a, b): return [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] Q = [[5, 3], [2, 2]] print(multyply_fib(Q, Q)) # def multiply_matrix(a, b): # result = [[0 for i in range(len(b[0]))] for j in range(len(a))] # for y in range(len(result)): # for x in range(len(result[0])): # result[y][x] = sum([a[y][i] * b[i][x] for i in range(len(b))]) # return result
e21f0d7ab06ae4dc4d762ad2aea683637d955dd5
Deepika-Purushan/Python_Activities
/Activity6.py
152
4.25
4
""" Using Loops:Write a Python program to construct the following pattern, using a nested loop number. """ for i in range(10): print(str(i)*i)
ad65e56b799b7555daef91086c11e1f62a2e2466
youguanxinqing/RoadOfDSA
/算法训练营/07-递归/098/中序遍历-数组法.py
707
3.53125
4
# # @lc app=leetcode.cn id=98 lang=python3 # # [98] 验证二叉搜索树 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root: TreeNode) -> bool: cache = [] self.helper(root, cache) for i in range(1, len(cache)): if cache[i-1] >= cache[i]: return False return True def helper(self, node, cache): if node is None: return self.helper(node.left, cache) cache.append(node.val) self.helper(node.right, cache) # @lc code=end
6dd6b2974cdffcfcecf4b6b3336cee1dad6791b7
Trolley33/python-dump
/misc/bottles.py
270
3.671875
4
import sys import time for i in range(1,100): if 100-i>1: plural="bottles" else: plural="bottle" print("{0} {1} of beer on the wall, {0} {1} of beer, take one down, pass it around and there's {2} {1} of beer on the wall.".format(100-i,plural,99-i)) time.sleep(2)
db221f00ffccda25f7f8bed0932f799371bd7982
AbiramiRavichandran/DataStructures
/Tree/SortedLevels.py
956
4.125
4
import queue as Q class Node: def __init__(self, data): self.data = data self.left = self.right = None def print_levels(root): if not root: return current = Q.PriorityQueue() next_ = Q.PriorityQueue() q = [root] current.put(root.data) while q: n = len(q) while n: node = q.pop(0) data = current.get() print(data, end=" ") if node.left: q.append(node.left) next_.put(node.left.data) if node.right: q.append(node.right) next_.put(node.right.data) n -= 1 print() current, next_ = next_, current if __name__ == "__main__": root = Node(7) root.left = Node(6) root.right = Node(5) root.left.left = Node(4) root.left.right = Node(3) root.right.left = Node(2) root.right.right = Node(1) print_levels(root)
0011695dc9c6a08a901af7bfc4ddd34aba0c8034
morluna/Elements-of-Software-Design
/Assignment 10/ExpressionTree.py
4,423
3.796875
4
# File: ExpressionTree.py # Description: This program performs creates a tree from a given expression and computes the answer # Student's Name: Marcos Ortiz # Student's UT EID: mjo579 # Course Name: CS 313E # Unique Number: 51320 # # Date Created: 11/28/2016 # Date Last Modified: 12/02/2016 import time import sys sys.setrecursionlimit(10000) class Stack (object): def __init__(self): self.items = [ ] def isEmpty (self): return self.items == [ ] def push (self, item): self.items.append (item) def pop (self): return self.items.pop () def peek (self): return self.items [len(self.items)-1] def size (self): return len(self.items) class BinaryTree (object): def __init__(self, initdata = "root"): self.data = initdata self.left = None self.right = None self.stack = Stack() self.postorderString = "" self.inorderString = "" self.inorderCalculation = 0 self.preorderString = "" def insertLeft(self,newNode): if self.left == None: self.left = BinaryTree(newNode) else: t = BinaryTree(newNode) t.left = self.left self.left = t def insertRight(self,newNode): if self.right == None: self.right = BinaryTree(newNode) else: t = BinaryTree(newNode) t.right = self.right self.right = t def getLeftChild(self): return self.left def getRightChild(self): return self.right def setRootVal(self,value): self.data = value def getRootVal(self): return self.data def createTree (self, expr): operatorList = ['+', '-', '*', '/'] currentNode = self stack = Stack() for index in range(0, len(expr)-1): currentToken = expr[index] if currentToken == ")": currentNode = stack.pop() elif currentToken == "(": stack.push(currentNode) currentNode.insertLeft(currentToken) currentNode = currentNode.getLeftChild() elif currentToken in operatorList: currentNode.setRootVal(currentToken) currentNode.insertRight(currentToken) stack.push(currentNode) currentNode = currentNode.getRightChild() else: currentNode.setRootVal(currentToken) currentNode = stack.pop() def evaluate (self, root): operatorList = ['+', '-', '*', '/'] if root != None: self.evaluate(root.getLeftChild()) self.evaluate(root.getRightChild()) element = root.getRootVal() if element in operatorList: num1 = self.stack.pop() num2 = self.stack.pop() if element == "+": answer = num2 + num1 elif element == "-": answer = num2 - num1 elif element == "*": answer = num2 * num1 else: answer = num2 / num1 self.stack.push(answer) self.inorderCalculation = answer else: self.stack.push(eval(element)) return self.inorderCalculation def preorder (self, root): if root != None: self.preorderString += root.getRootVal() + " " self.preorder(root.getLeftChild()) self.preorder(root.getRightChild()) return self.preorderString def postorder (self, root): if root != None: self.postorder(root.getLeftChild()) self.postorder(root.getRightChild()) self.postorderString += root.getRootVal() + " " return self.postorderString def main(): # 1. Open file and read data in_file = open("treedata.txt", "r") # 2. Read file line by line for line in in_file: # 3. Perform line specific tasks line = line.strip() print("Infix expression: ", line) line = line.split() # 4. Instantiate tree and create it tree = BinaryTree() tree.createTree(line) # 5. Print results print("\tValue: ", tree.evaluate(tree)) print("\tPrefix expression: ", tree.preorder(tree)) print("\tPostfix expression: ", tree.postorder(tree)) print() main()
a4cd2fbdd29b59173ca9b76b4176fa116d6f5523
aruzhansadakbayeva/WebDevelopment
/lab7/task1/informatics/b/e.py
87
3.78125
4
a=int(input()) b=int(input()) if a>b: print('1') elif b>a: print('2') else: print('0')
810488225eb5feaf2a6910a6e118588fee7ebaa3
aoyono/sicpy
/Chapter2/exercises/exercise2_17.py
542
3.734375
4
# -*- coding: utf-8 -*- """ https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#%_thm_2.17 """ from Chapter2.themes.lisp_list_structured_data import car, cdr, lisp_list def last_pair(l): if cdr(l) is None: return car(l), # Simulates the fact that we don't really include None in a pair return last_pair(cdr(l)) def run_the_magic(): print('(last-pair (list 23 72 149 34))') print( last_pair( lisp_list(23, 72, 149, 34) ) ) if __name__ == '__main__': run_the_magic()
469432e7affd422c94b193a248d18439e7bfd324
Ddjones001/data_structures
/Binary Search.py
1,779
3.96875
4
def binary_search(search_list, number_to_find): left_index = 0 right_index = len(search_list) - 1 mid_index = 0 while left_index <= right_index: mid_index = (left_index + right_index) // 2 mid_number = search_list[mid_index] if mid_number == number_to_find: return mid_index if mid_number < number_to_find: left_index = mid_index + 1 else: right_index = mid_index - 1 return -1 def binary_search_recursive(search_list, number_to_find, left_index, right_index): if right_index < left_index: return -1 mid_index = (left_index + right_index) // 2 mid_number = search_list[mid_index] if mid_number == number_to_find: return mid_index if mid_number < number_to_find: left_index = mid_index + 1 else: right_index = mid_index - 1 return binary_search_recursive(search_list,number_to_find,left_index,right_index) def get_reoccuring_numbers(search_list, number_to_find): index = binary_search(search_list,number_to_find) indicies = [index] i = index - 1 while i >= 0: if search_list[i] == number_to_find: indicies.append(i) else: break i = i - 1 #right_side search i = index + 1 while i < len(search_list): if search_list[i] == number_to_find: indicies.append(i) else: break i += 1 return sorted(indicies) if __name__ == '__main__': search_list = [5,5,10,15,15,15,20,25] number = 25 index = get_reoccuring_numbers(search_list,number) print(f"The number: {number} was found at index(s): {index} using binary search")
119f1c4dfbeada760dd06813f558f3ae8c0a06aa
acc-cosc-1336/cosc-1336-spring-2018-zachdiamond000
/src/midterm/main_exam.py
478
4.375
4
#write import statement for reverse string function from exam import reverse_string ''' 10 points Write a main function to .... Loop as long as user types y. Prompt user for a string (assume user will always give you good data). Pass the string to the reverse string function and display the reversed string ''' again = 'y' while again == 'y': string1 = input('Please input a string: ') reverse_string(string1) print(rstring) again = input('continue...')
0e9b6a9547e046df55d884f4835fbbf35d616ff8
TemistoclesZwang/Algoritmo_IFPI_2020
/exerciciosComCondicionais/A_CONDICIONAIS/02A_EX21.py
642
4.15625
4
# 21. Realize arredondamentos de números utilizando a regra usual da matemática: se a parte fracionaria for # maior do que ou igual a 0,5, o numero é arredondado para o inteiro imediatamente superior, caso # contrario, é arredondado para o inteiro imediatamente inferior. def main(): numero = float(input('Insira um número do tipo float: ')) verificar(numero) def verificar(numero): if numero % 1 >= 0.5: numero = (numero // 1) + 1 print(f'Seu número foi arredondado para: {numero}') else: numero = numero - (numero % 1) print(f'Seu número foi arredondado para: {numero}') main()
ca79c72bf7984495c76f125f202a180844e5e73d
masinogns/boj
/algorithm/2.Data_Structure_1/BOJ_basic_17.py
1,033
3.90625
4
""" BOJ_basic_14 : 스택 문제 참고 """ if __name__ == '__main__': queue = list() N = int(input()) for numbers in range(N): InputCommand = list(input().split()) queueSize = len(queue) if InputCommand[0] == "push": queue.append(InputCommand[1]) elif InputCommand[0] == "pop": if queueSize != 0: print(queue[0]) del queue[0] else: print(-1) elif InputCommand[0] == "size": print(queueSize) elif InputCommand[0] == "empty": if queueSize != 0: print(0) else: print(1) elif InputCommand[0] == "front": if queueSize != 0: print(queue[0]) else: print(-1) elif InputCommand[0] == "back": if queueSize != 0: print(queue[queueSize-1]) else: print(-1)
ba19336f4b2654f456a2f435d1d899d2ac785f75
Tamara-Adeeb/Python_stack
/_python (the underscore IS IMPORTANT)/python_fundamentals/For_Loop_Basic II.py
3,383
4.34375
4
#Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". def biggie_size(a): for i in range(len(a)): if a[i] > 0: a[i] = "big" return a print(biggie_size([-1, 3, 5, -5])) #Count Positives - Given a list of numbers, create a function to replace the last # value with the number of positive values. (Note that zero is not considered to be a positive number). def count_positives(a): count = 0 for i in a: if i > 0: count += 1 a[-1] = count return a print(count_positives([-1,1,1,1])) # #Sum Total - Create a function that takes a list and returns the sum of all the values in the list. def sum_total(a): sum = 0 for i in a: sum += i return sum print(sum_total([1,2,3,4])) print(sum([1,2,3,4])) # #Average - Create a function that takes a list and returns the average of all the values.x def average(a): sum = 0 for i in a: sum += i return sum/len(a) print(average([1,2,3,4])) # #Length - Create a function that takes a list and returns the length of the list. def length(a): return len(a) def length1(a): count = 0 for i in a: count += 1 return count print(length([37,2,1,-9])) print(length1([37,2,1,-9])) # #Minimum - Create a function that takes a list of numbers and returns the minimum # # value in the list. If the list is empty, have the function return False. def minimum(a): min = a[0] if len(a) == 0: return False for i in a: if min > i: min = i return min print(minimum([37,2,1,-9])) # #Maximum - Create a function that takes a list and returns the maximum value in the list. # # If the list is empty, have the function return False. def maximum(a): max = a[0] if len(a) == 0: return False for i in a: if max < i: max = i return max print(maximum([37,2,1,-9])) # #Ultimate Analysis - Create a function that takes a list and returns a dictionary that has the sumTotal, # # average, minimum, maximum and length of the list. # Example: ultimate_analysis([37,2,1,-9]) should # return {'sumTotal': 31, 'average': 7.75, 'minimum': -9, 'maximum': 37, 'length': 4 } def ultimate_analysis(a): sum = 0 min = max = a[0] dir = {} for i in a: sum += i if max < i: max = i if min > i: min = i avr = sum/len(a) dir["sumTotal"] = sum dir["average"] = avr dir["minimum"] = min dir["maximum"] = max dir["length"] = len(a) return dir #*********************************** def ultimate_analysis2(a): dir = {"sumTotal": sum(a), "average": sum(a)/len(a), "minimum":min(a), "maximum":max(a), "length":len(a)} return dir print(ultimate_analysis([37,2,1,-9])) print(ultimate_analysis2([37,2,1,-9])) # #Reverse List - Create a function that takes a list and return that list with values reversed. # # Do this without creating a second list. (This challenge is known to appear during basic technical interviews.) # Example: reverse_list([37,2,1,-9]) should return [-9,1,2,37] def reverse_list1(a): return a[::-1] def reverse_list2(a): for i in range(int(len(a)/2)): a[i], a[-1-i] = a[-1-i], a[i] return a print(reverse_list1([37, 2, 1, -9, 8])) print(reverse_list2([37, 2, 1, -9, 8]))
8263dd504d7433ff0675ffb7ceec09458898ee51
dkarpelevich/checkio
/BLIZZARD/when-is-friday.py
410
3.59375
4
from datetime import date def friday(day): day = day.split('.') day_number = date(int(day[2]), int(day[1]), int(day[0])).weekday() return 4 - day_number if day_number <= 4 else 4 - day_number + 7 if __name__ == '__main__': print(friday('23.04.2018')) assert friday('23.04.2018') == 4 assert friday('01.01.1999') == 0 print("Coding complete? Click 'Check' to earn cool rewards!")
2a3942dca2863ed0f528cd6584cc0d1965edecb8
jialing3/corner_cases
/Relue/Eu94.py
1,997
4
4
''' let x be the length_of_two_sides then height = sqrt( (1.5 x +/- 0.5) (0.5x -/+ 0.5) ) if x is even, then height needs to be even if x is odd, then height needs to be int for y in range(1, 10 ** 9 // 4 + 1) x = 2y covers the even cases x = 2y + 1 covers the odd cases but, the *real* problem here is there exists a precision issue for large y when y = 46302366, if we take the case of x = 2y + 1, and look for ( (3 * y + 2) * y ) ** 0.5, we'll get 80198051, whose square is 6431727384198601, not 6431727384198600 (tmp ** 0.5) ** 2 == tmp takes care of the precision issue ''' total_perimeter = 0 for y in range(1, 10 ** 9 // 6 + 1): # x = 2y, need sqrt( (3y +/- 0.5) (y -/+ 0.5) ) to be even tmp_0 = 3 * y + 0.5 tmp_1 = y - 0.5 if tmp_0 % 2 == 0 or tmp_1 % 2 == 0: tmp = tmp_0 * tmp_1 if tmp % 4 == 0: if (tmp ** 0.5) % 1 == 0 and int(tmp ** 0.5) ** 2 == tmp: perimeter = 6 * y + 1 total_perimeter += perimeter print(2 * y, 2 * y, 2 * y + 1, perimeter) tmp_0 = 3 * y - 0.5 tmp_1 = y + 0.5 if tmp_0 % 2 == 0 or tmp_1 % 2 == 0: tmp = tmp_0 * tmp_1 if tmp % 4 == 0: if (tmp ** 0.5) % 1 == 0 and int(tmp ** 0.5) ** 2 == tmp: perimeter = 6 * y - 1 total_perimeter += perimeter print(2 * y, 2 * y, 2 * y - 1, perimeter) # x = 2y + 1, need sqrt( (3y + 1.5 +/- 0.5) (y + 0.5 -/+ 0.5) ) to be int tmp = (3 * y + 2) * y if (tmp ** 0.5) % 1 == 0 and int(tmp ** 0.5) ** 2 == tmp: perimeter = 6 * y + 4 total_perimeter += perimeter print(2 * y + 1, 2 * y + 1, 2 * y + 2, perimeter) tmp = (3 * y + 1) * (y + 1) if (tmp ** 0.5) % 1 == 0 and int(tmp ** 0.5) ** 2 == tmp: perimeter = 6 * y + 2 total_perimeter += perimeter print(2 * y + 1, 2 * y + 1, 2 * y, perimeter) print(total_perimeter) # Alternatively, one could resort to using pythagorean triples
1289e1e6dd504cdb526fe5b96204ed34ca52614a
YtrioSalmitoAzevedo/URI-Online-Judge
/Iniciante/1044 Múltiplos.py
183
3.578125
4
multiplos = raw_input().split(" ") a, b = multiplos a, b = int(a),int(b) if a > b: mm,m=a,b else: mm,m=b,a if mm % m == 0: print "Sao Multiplos" else: print "Nao sao Multiplos"
d4b85a537febb709f164519d3a58836be0891b40
Clockwork757/DragonHacks-2018
/US_CODE/Room.py
2,667
3.734375
4
#======================================== #Project Name: Room Type/Size #Date: 04/15/2017 #Programmer Name: Matthew Marschall #Modified: 01/06/2018 #Modifier: Dresden Feitzinger #======================================== import numpy as np class Point: ''' Return a cartesian coordinate point ''' def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): ''' Return a string representation of the coordinate point ''' return "({0}, {1})".format(self.x, self.y) def get_x(self): ''' Return the x coordinate ''' return self.x def get_y(self): ''' Return the y coordinate ''' return self.y class Room(): ''' Superclass for room types ''' def __init__(self, t, name="Room"): #--- Public ----------- self.type = t # type of room self.name = name # name of room self.area = None # area of room #---------------------- def get_area(self): ''' Return area of the room ''' return self.area def set_area(self, area): ''' Set room area ''' self.area = area class Circle(Room): ''' Create a room of type circle ''' def __init__(self, r, name="Room"): ''' Takes one positional argument: radius ''' #--- Initialize Superclass ------- t = 0 Room.__init__(self, t, name) self.set_area(4*np.pi*(r**2)) #--- Public ---------------------- self.diameter = r*2 self.radius = r #--------------------------------- def get_radius(self): ''' Return radius of the circle in centimeters ''' return self.radius def calc_circumference(self): ''' Calculate the circumference of the room ''' return 2 * np.pi * self.radius class Rectangle(Room): ''' Create a room of type rectangle ''' def __init__(self, w, l, name="Room"): #--- Initialize Superclass ------- t = 1 Room.__init__(self, t, name) self.set_area(w*l) #--------------------------------- #--- Public ---------------------- self.length = l self.width = w #--------------------------------- def get_width(self): ''' Return rectangle width in centimeters ''' return self.width def get_length(self): ''' Return rectangle height in centimeters ''' return self.length def calc_perimeter(self): ''' Return rectangle perimeter in centimeters ''' return ((2 * self.width) + (2 * self.length))
124de78de94d4ab0034424507a42b7add24b8dcc
amyamyc/SI507_Project1_Flask
/SI507_project_1.py
1,308
3.609375
4
from flask import Flask from lab3_code import * app = Flask(__name__) @app.route('/') def home(): return 'Just the home page, nothing interesting.' @app.route('/bank/<name>') def see_new_bank_name(name): new_bank_name = Bank(name, Dollar, 0) return "Welcome to {}".format(new_bank_name.name) @app.route('/dollar/<amt>') def see_dollar(amt): new_dollar = Dollar(int(amt)) # creating an instance of class Dollar return new_dollar.__str__() @app.route('/yuan/<amt>') def see_yuan(amt): new_yuan = Yuan(int(amt)) #creating an instance of the class Yuan return new_yuan.__str__() @app.route('/pound/<amt>') def see_pound(amt): new_pound = Pound(int(amt)) return new_pound.__str__() @app.route('/bank/<name>/<currency>/<value>') def message(name, currency, value): if currency == "Dollar": currency_class = Dollar elif currency == "Pound": currency_class = Pound elif currency == "Yuan": currency_class = Yuan else: return "Invalid URL inputs for bank" # Have to call the Dollar class because Bank class requires an instance of the currency class x = Bank(name, currency_class, int(value)) string = x.__str__() return "Welcome to the {} bank!".format(x.name) + string if __name__ == "__main__": app.run()
5cad1d316bb02c8e06138912df0513bd195cba60
yjh8806/python-2019-July
/13일/15.함수/03.function.py
485
3.921875
4
def odd_even(num): if num % 2 == 0: print("짝수입니다.") else: print("홀수입니다.") num = int(input("정수 입력 : ")) odd_even(num) def total(a): result = 0 for i in range(1, a + 1): result += i return result #반환값 print("누적합계 : %d"%total(10)) #제곱 def power(a, b): result = 1 for i in range(b): result *= a return result print(power(2, 3)) print(power(2, 10))
5e09da630f90f1e76706d15fccae24f133d6f750
modelarious/Artificial_Net_Simple
/inputFuncs.py
6,226
3.84375
4
import pandas as pd import numpy as np import sys def get_Samples(data='Balance_Data.csv', categorical=True): ''' read in a csv file must have a column named 'class' must have the same number of features for each training example any holes in data must have value NaN if categorical is False, every column apart from the class column is assumed to contain continuous data and is normalized if categorical is True, it is assumed that the unique elements of each column are unique states that that column can take on, and maps an integer to each state for that column ''' try: dataframe = pd.read_csv(data) except pd.io.common.EmptyDataError: sys.exit("Must not provide get_Samples with a blank file") except OSError: sys.exit("File doesn't exist") # drop any column that contains no data dataframe = dataframe.dropna(axis=1, how='all') # drop any row that has nan in it dataframe = dataframe.dropna() # drop any column that consists entirely of the same value nunique = dataframe.apply(pd.Series.nunique) dropColumns = nunique[nunique == 1].index dataframe = dataframe.drop(dropColumns, axis=1) # if we have managed to delete all the data with the last few steps # or an empty data file was specified if len(dataframe) <= 0: sys.exit("No data except column names!") # get column names columns = dataframe.columns.values.tolist() # if "Class" isn't a column title throw an error if "Class" not in columns: sys.exit("Class not a column in the data") # no longer need this in our list of columns, as we'll use it to specify # all the columns that are inputs to our neural net columns.remove("Class") # If this leaves us with no more columns, throw an error if len(columns) == 0: sys.exit("Need more than just class column") # create labels for our data inputY = dataframe.loc[:, ['Class']].as_matrix() # no need to iterate over it anymore dataframe.drop(['Class'], axis=1) #get the number of output classes unique_classes = np.unique(inputY) num_unique_classes = len(unique_classes) num_samples = len(inputY) # these next few lines take the class that is requested by each label, # and marks that point in the row as 1 and the rest as 0 # for example: # we are told that sample 4 has label 3 out of 4 possible labels, # so we create the label [0,0,1,0] # and store it in the array at the proper place dict_map = {} for i in range(num_unique_classes): dict_map[unique_classes[i]] = i #num_samples long, num_unique_classes wide Y = np.zeros([num_samples, num_unique_classes]) for i in range(num_samples): curr_class = inputY[i] curr_class_encode = dict_map[curr_class[0]] Y[i][curr_class_encode] = 1.0 # maps unique column states to integers # if a column can take on values 'a' and 'b', then 'a' is 0, 'b' is 1 # then replace all 'a's in the column with 0 and 'b's with 1 if categorical == True: for col in dataframe.select_dtypes(exclude=['int', 'float']).columns: dataframe[col] = pd.Categorical( dataframe[col], categories=dataframe[col].unique()).codes # create our input data X = dataframe.loc[:, columns].as_matrix() print("\nNumber of samples:", num_samples) print("Number of categories:", num_unique_classes) print("Number of features per sample:", len(columns)) #normalize input data means = np.mean(X, axis=0) stddevs = np.std(X, axis=0) X[:,0] = (X[:,0] - means[0]) / stddevs[0] X[:,1] = (X[:,1] - means[1]) / stddevs[1] return X, Y def MNIST_Data_Get(): from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) inputX = np.concatenate((mnist.test.images, mnist.train.images, mnist.validation.images), axis=0) inputY = np.concatenate((mnist.test.labels, mnist.train.labels, mnist.validation.labels), axis=0) return inputX, inputY def generate_Random_Samples(num, IN_X, IN_Y, overlap=False): total_samples = IN_X.shape[0] testingNum = int(total_samples*0.1) #fix divide by 0 errors if testingNum == 0: testingNum += 1 # if overlap is true, there may be some overlap between # training and testing data # not typically a good idea, but fun to play with if overlap == False: if num + testingNum > total_samples: num = total_samples - testingNum string = "Too many samples requested for generate_Random_Samples. "\ "\nMaximum selectable is " + str(total_samples) + " with overlap=True or "\ + str(num) + " with it off." print(string) ind = np.random.choice( range(total_samples), num + testingNum, replace=False) training_indices = ind[:num] testing_indices = ind[num:] else: if num > total_samples: num = total_samples string = "Too many samples requested for generate_Random_Samples. "\ "\nMaximum selectable is " + str(total_samples) + " with overlap=True or "\ + str(num) + " with it off." print(string) if total_samples == num: training_indices = np.arange(total_samples) else: training_indices = np.random.choice( range(total_samples), num, replace=False) testing_indices = np.random.choice( range(total_samples), testingNum, replace=False) trainX = IN_X[training_indices] trainY = IN_Y[training_indices] testX = IN_X[testing_indices] testY = IN_Y[testing_indices] print("Number of training samples", num) print("Number of testing samples", testingNum) return trainX, trainY, testX, testY
3cbd0542b51c0f128b56179bb64919b839b1c697
basharbme/BioPrinterGCode
/Generator/tkinter_utils.py
4,409
3.765625
4
#!/usr/bin/python # -*- coding: utf-8 -*- from Tkinter import * # from x import * is bad practice from ttk import * import Tkinter as tk # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame # Button with press and release events class HoldableButton(Button): def __init__(self, root, text="hold me"): self.running = False Button.__init__(self, root, text=text) def _start(event): self.start(event) def _stop(event): self.stop(event) self.bind("<ButtonPress-1>", _start) self.bind("<ButtonRelease-1>", _stop) def isHeld(self): return self.running def start(self, event): self.running = True def stop(self, event): self.running = False class VerticalScrolledFrame(Frame): """A pure Tkinter scrollable frame that actually works! * Use the 'interior' attribute to place widgets inside the scrollable frame * Construct and pack/place/grid normally * This frame only allows vertical scrolling """ def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) # create a canvas object and a vertical scrollbar for scrolling it vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) # reset the view canvas.xview_moveto(0) canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with it self.interior = interior = Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas and frame width and sync them, # also updating the scrollbar def _configure_interior(event): # update the scrollbars to match the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): # update the canvas's width to fit the inner frame canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != canvas.winfo_width(): # update the inner frame's width to fill the canvas canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas) class CreateToolTip(object): """ create a tooltip for a given widget """ def __init__(self, widget, text='widget info'): self.waittime = 500 #miliseconds self.wraplength = 180 #pixels self.widget = widget self.text = text self.widget.bind("<Enter>", self.enter) self.widget.bind("<Leave>", self.leave) self.widget.bind("<ButtonPress>", self.leave) self.id = None self.tw = None def enter(self, event=None): self.schedule() def leave(self, event=None): self.unschedule() self.hidetip() def schedule(self): self.unschedule() self.id = self.widget.after(self.waittime, self.showtip) def unschedule(self): id = self.id self.id = None if id: self.widget.after_cancel(id) def showtip(self, event=None): x = y = 0 x, y, cx, cy = self.widget.bbox("insert") x += self.widget.winfo_rootx() + 25 y += self.widget.winfo_rooty() + 20 # creates a toplevel window self.tw = tk.Toplevel(self.widget) # Leaves only the label and removes the app window self.tw.wm_overrideredirect(True) self.tw.wm_geometry("+%d+%d" % (x, y)) label = tk.Label(self.tw, text=self.text, justify='left', background="#ffffff", relief='solid', borderwidth=1, wraplength = self.wraplength) label.pack(ipadx=1) def hidetip(self): tw = self.tw self.tw= None if tw: tw.destroy()
7757dafa1e43e0f7c69b94e95e32a3522f000c24
NC-Coyote/Portfolio
/Digit Recognizer - Convolutional Neural Network/digitRecognizer.py
4,912
4.09375
4
# Handwritten digit recognition for MNIST dataset using Convolutional Neural Networks # Step 1: Import all required keras libraries from keras.datasets import mnist # This is used to load mnist dataset later from keras.utils import np_utils as npu # This will be used to convert your test image to a categorical class (digit from 0 to 9) import tensorflow as tf # Step 2: Load and return training and test datasets def load_dataset(): # 2a. Load dataset X_train, X_test, y_train, y_test via imported keras library (X_train, y_train), (X_test, y_test) = mnist.load_data() # 2b. reshape for X train and test vars - Hint: X_train = X_train.reshape((X_train.shape[0], 28, 28, 1)).astype('float32') X_train = X_train.reshape((X_train.shape[0], 28, 28, 1)).astype('float32') X_test = X_test.reshape((X_test.shape[0], 28, 28, 1)).astype('float32') # 2c. normalize inputs from 0-255 to 0-1 - Hint: X_train = X_train / 255 X_train /= 255.0 X_test /= 255.0 # 2d. Convert y_train and y_test to categorical classes - Hint: y_train = np_utils.to_categorical(y_train) y_train = npu.to_categorical(y_train) y_test = npu.to_categorical(y_test) # 2e. return your X_train, X_test, y_train, y_test return X_train, y_train, X_test, y_test # Step 3: define your CNN model here in this function and then later use this function to create your model def digit_recognition_cnn(): # 3a. create your CNN model here with Conv + ReLU + Flatten + Dense layers model = tf.keras.models.Sequential() # convolution layer 1 model.add(tf.keras.layers.Conv2D(filters=30, kernel_size=(5, 5), activation='relu', input_shape=(28,28,1))) # pooling layer 1 model.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2)) # convolution layer 2 model.add(tf.keras.layers.Conv2D(filters=15, kernel_size=(3, 3), activation='relu')) # pooling layer 2 model.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2)) # dropout (20%) model.add(tf.keras.layers.Dropout(0.20)) # flatten model.add(tf.keras.layers.Flatten()) # dense layer 1 (128 units + ReLU) model.add(tf.keras.layers.Dense(units=128, activation='relu')) # dense layer 2 (50 units + ReLU) model.add(tf.keras.layers.Dense(units=50, activation='relu')) # dense layer 3 (10 units + softmax) model.add(tf.keras.layers.Dense(units=10, activation='softmax')) # 3b. Compile your model with categorical_crossentropy (loss), adam optimizer and accuracy as a metric model.compile(optimizer = 'adam', loss='categorical_crossentropy', metrics = ['accuracy']) # 3c. return your model return model # Load MNIST data X_train, y_train, X_test, y_test = load_dataset() # Step 4: Call digit_recognition_cnn() to build your model builtModel = digit_recognition_cnn() # Step 5: Train your model and see the result in Command window. Set epochs to a number between 10 - 20 and batch_size between 150 - 200 builtModel.fit(X_train, y_train, epochs = 15, batch_size = 175) # Step 6: Evaluate your model via your_model_name.evaluate() function and copy the result in your report builtModel.evaluate(X_test, y_test, verbose = 0) # Step 7: Save your model via your_model_name.save('digitRecognizer.h5') builtModel.save('digitRecognizer.h5') # Code below to make a prediction for a new image. # Step 8: load required keras libraries from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from keras.models import load_model import numpy as np # Step 9: load and normalize new image def load_new_image(path): # 9a. load new image newImage = load_img(path, color_mode = "grayscale", target_size=(28, 28)) # 9b. Convert image to array newImage = img_to_array(newImage) # 9c. reshape into a single sample with 1 channel (similar to how you reshaped in load_dataset function) newImage = newImage.reshape(1, 28, 28, 1).astype('float32') # 9d. normalize image data - Hint: newImage = newImage / 255 newImage /= 255.0 # 9e. return newImage return newImage # Step 10: load a new image and predict its class def test_model_performance(): # 10a. Call the above load image function img = load_new_image('sample_images/digit7.png') # 10b. load your CNN model (digitRecognizer.h5 file) loadedModel = load_model('digitRecognizer.h5') # 10c. predict the class - Hint: imageClass = your_model_name.predict_classes(img) #imageClass = loadedModel.predict_classes(img) # apparently, this is depricated so I used the np.argmax... command on the following line imageClass = np.argmax(loadedModel.predict(img), axis=-1) # 10d. Print prediction result print("\nThe handwritten number is: ", imageClass[0]) print("\n\n") # Step 11: Test model performance here by calling the above test_model_performance function test_model_performance()