blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
31d0035d01ba78f8c6c09028322b4723faea9d85
hoangtv8699/ML-DL-start
/machine-learning/multilayer-neural-network.py
3,568
3.875
4
from __future__ import print_function import numpy as np from sklearn.neural_network import MLPClassifier def softmax_stable(Z): """ Compute softmax values for each sets of scores in Z. each ROW of Z is a set of scores. """ e_Z = np.exp(Z - np.max(Z, axis=1, keepdims=True)) A = e_Z / e_Z.sum(axis=1, keepdims=True) return A def crossentropy_loss(Yhat, y): """ Yhat: a numpy array of shape (Npoints, nClasses) -- predicted output y: a numpy array of shape (Npoints) -- ground truth. NOTE: We don’t need to use the one-hot vector here since most of elements are zeros. When programming in numpy, in each row of Yhat, we need to access to the corresponding index only. """ id0 = range(Yhat.shape[0]) return -np.mean(np.log(Yhat[id0, y])) def mlp_init(d0, d1, d2): """ Initialize W1, b1, W2, b2 d0: dimension of input data d1: number of hidden unit d2: number of output unit = number of classes """ W1 = 0.01 * np.random.randn(d0, d1) b1 = np.zeros(d1) W2 = 0.01 * np.random.randn(d1, d2) b2 = np.zeros(d2) return (W1, b1, W2, b2) def mlp_predict(X, W1, b1, W2, b2): """ Suppose that the network has been trained, predict class of new points. X: data matrix, each ROW is one data point. W1, b1, W2, b2: learned weight matrices and biases """ Z1 = X.dot(W1) + b1 # shape (N, d1) A1 = np.maximum(Z1, 0) # shape (N, d1) Z2 = A1.dot(W2) + b2 # shape (N, d2) return np.argmax(Z2, axis=1) def mlp_fit(X, y, W1, b1, W2, b2, eta): loss_hist = [] for i in range(20000): # number of epoches # feedforward Z1 = X.dot(W1) + b1 # shape (N, d1) A1 = np.maximum(Z1, 0) # shape (N, d1) Z2 = A1.dot(W2) + b2 # shape (N, d2) Yhat = softmax_stable(Z2) # shape (N, d2) if i %1000 == 0: # print loss after each 1000 iterations loss = crossentropy_loss(Yhat, y) print("iter %d, loss: %f" %(i, loss)) loss_hist.append(loss) # back propagation id0 = range(Yhat.shape[0]) Yhat[id0, y] -=1 E2 = Yhat/N # shape (N, d2) dW2 = np.dot(A1.T, E2) # shape (d1, d2) db2 = np.sum(E2, axis = 0) # shape (d2,) E1 = np.dot(E2, W2.T) # shape (N, d1) E1[Z1 <= 0] = 0 # gradient of ReLU, shape (N, d1) dW1 = np.dot(X.T, E1) # shape (d0, d1) db1 = np.sum(E1, axis = 0) # shape (d1,) # Gradient Descent update W1 += -eta*dW1 b1 += -eta*db1 W2 += -eta*dW2 b2 += -eta*db2 return (W1, b1, W2, b2, loss_hist) means = [[-1, -1], [1, -1], [0, 1]] cov = [[1, 0], [0, 1]] N = 20 X0 = np.random.multivariate_normal(means[0], cov, N) X1 = np.random.multivariate_normal(means[1], cov, N) X2 = np.random.multivariate_normal(means[2], cov, N) X = np.concatenate((X0, X1, X2), axis = 0) y = np.asarray([0]*N + [1]*N + [2]*N) alpha = 1e-1 # regularization parameter clf = MLPClassifier(solver='lbfgs', alpha=alpha, hidden_layer_sizes=(100)) clf.fit(X, y) y_pred = clf.predict(X) acc = 100*np.mean(y_pred == y) print('training accuracy: %.2f %%' % acc) # suppose X, y are training input and output, respectively d0 = 2 # data dimension d1 = h = 30 # number of hidden units d2 = C = 3 # number of classes eta = 1 # learning rate (W1, b1, W2, b2) = mlp_init(d0, d1, d2) (W1, b1, W2, b2, loss_hist) =mlp_fit(X, y, W1, b1, W2, b2, eta) y_pred = mlp_predict(X, W1, b1, W2, b2) acc = 100*np.mean(y_pred == y) print('training accuracy: %.2f %%' % acc)
bad7c60a04b0acb67051f91a12743f33e6e3d2a4
michaelhuo/pcp
/remove_duplicates.py
383
3.859375
4
def remove_duplicates(head): #TODO: Write - Your - Code if not head: return head keys = set() result = head keys.add(result.data) curr = result node = result.next while node: data = node.data print(keys) if data not in keys: keys.add(data) curr.next = node curr = curr.next node = node.next curr.next = None return result
8edc815fd89c831fc7a25275b12bd70b3623f264
RamonFidencio/exercicios_python
/EX068.py
925
3.5625
4
import random cont=0 while True: pc = random.randint(1,10) con=0 usu=int(input('Digite um valor: ')) pi = input('PAR ou IMPAR [P/I]: ').upper() prd= (usu*pc) cont +=1 if pi == 'P': if prd%2 ==0: print('\n\n','-'*30,'\nVOCE VENCEU !!!') print(f'Voce jogou {usu} e o computador {pc}. Total {prd} PAR') else: print('\n\n','-'*30,'\nVOCE PERDEU. GAME OVER {} tentativas'.format(cont)) print(f'Voce jogou {usu} e o computador {pc}. Total {prd} IMPAR') break elif pi == 'I': if prd%2 ==0: print('\n\n','-'*30,'\nVOCE PERDEU. GAME OVER {} tentativas'.format(cont)) print(f'Voce jogou {usu} e o computador {pc}. Total {prd} PAR') break else: print('\n\n','-'*30,'\nVOCE VENCEU !!!') print(f'Voce jogou {usu} e o computador {pc}. Total {prd} IMPAR')
60f33cb16e00b66eb9d659861d43d84804442d0f
haukurarna/2018-T-111-PROG
/projects/hw4/priceOfStock.py
1,516
4.1875
4
def get_shares(): ''' Returns a valid number of shares input by user ''' while True: try: shares = input("Enter number of shares: ") return int(shares) except ValueError: print("Invalid number!") def get_price_info_as_strings(): ''' Returns price info input by user as strings ''' price_info = input("Enter price (dollars, numerator, denominator): ") return price_info.split() def get_price_info(): ''' Returns valid price info input by user ''' while True: try: dollars, numerator, denominator = get_price_info_as_strings() return int(dollars), int(numerator), int(denominator) except ValueError: print("Invalid price!") def convert(dollars, numerator, denominator): ''' Converts a price stated with integer values into a float ''' return dollars + numerator/denominator def displayResult(shares, dollars, numerator, denominator, value): ''' Display results ''' print("{:d} shares with market price {:d} {:d}/{:d} have value ${:.2f}".format(shares, dollars, numerator, denominator, value)) # Main program starts here repeat = 'y' while repeat.lower() == 'y': # Read data from user and compute and display stock value shares = get_shares() dollars, numer, denom = get_price_info() price = convert(dollars, numer, denom) value = price * shares displayResult(shares, dollars, numer, denom, value) repeat = input("Continue: ")
f12660c503d72f613ee60f63ac53594a631763f8
melvinanthonyrancap/Exercises-for-Programmers-57-Challenges-Python
/Answers/exercise23.py
1,400
3.703125
4
import os os.system('cls') user_input = input("Is the car silent when you turn the key? ") if user_input.lower() == "y" or user_input.lower() == "yes": user_input = input("Are the battery terminals corroded? ") if user_input.lower() == "y" or user_input.lower() == "yes": print("Clean terminals and try starting agian.") elif user_input.lower() == "n" or user_input.lower() == "no": print("The battery cables maybe by damaged.\nReplace cables and try again.") elif user_input.lower() == "n" or user_input.lower() == "no": user_input = input("Does the car make a clicking noise?") if user_input.lower() == "y" or user_input.lower() == "yes": print("Replace the battery.") elif user_input.lower() == "n" or user_input.lower() == "no": user_input = input("Does the crank up but fail to start? ") if user_input.lower() == "y" or user_input.lower() == "yes": print("Check spark plug connections.") elif user_input.lower() == "n" or user_input.lower() == "no": user_input = input("Does the engine start and then die? ") if user_input.lower() == "y" or user_input.lower() == "yes": user_input = input("Does your car have fuel injection? ") if user_input.lower() == "y" or user_input.lower() == "yes": print("Get it in for service.") elif user_input.lower() == "n" or user_input.lower() == "no": print("Check to ensure the choke is opening and closing.")
43e8bbed07f817944989f61abd5805dd671fe48b
anujastrivedi/PycharmProjects
/MagnusTraining/Excercise1/Question9.py
477
4.25
4
# Print multiplication table of 24, 50 and 29 using loop def print_table(table): i = 1 while i <= 10: mul = table * i print(f"{table} * {i} = {mul}") i += 1 if __name__ == "__main__": while True: table = input("Enter number to print the table or \'q\' to exit : ") if table == "q": break elif table.isnumeric(): print_table(int(table)) else: print("Unknown command..")
5118cf1f0a9337a463d47734f08dbc44b67d3565
Yifei-Deng/myPython-foundational-level-practice-code
/29(b).py
355
4.25
4
''' 视频中老师演示的代码 python开发基础29-元组 ''' #元组的切片操作 a = (1,2,3,4,5,6,7) print(a[1:6]) #强制类型转换 b = ['@','!','#'] #list to tuple c = tuple(b) print(c) print(type(c)) print(tuple('okay')) #string to tuple ''' Outputs: (2, 3, 4, 5, 6) ('@', '!', '#') <class 'tuple'> ('o', 'k', 'a', 'y') '''
a5667049448db340c96e351b8bc68ab872c9e9e7
anton-dovnar/LeetCode
/HashTable/Easy/500.py
553
3.703125
4
""" Keyboard Row """ class Solution: def findWords(self, words: List[str]) -> List[str]: keyboard_row = [] for word in words: word_lower = word.lower() if set(word_lower) == set(word_lower) & set("qwertyuiop"): keyboard_row.append(word) elif set(word_lower) == set(word_lower) & set("asdfghjkl"): keyboard_row.append(word) elif set(word_lower) == set(word_lower) & set("zxcvbnm"): keyboard_row.append(word) return keyboard_row
1d3aa6ba62852fdcfe9a9d27e0992327e0f0e33c
yinhuax/leet_code
/datastructure/Stack/MinStack.py
650
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Mike # @Contact : [email protected] # @Time : 2020/12/18 23:47 # @File : MinStack.py class MinStack(object): def __init__(self): """ initialize your data structure here """ self.min_stack = [float('inf')] self.stack = [] def push(self, x: int) -> None: self.stack.append(x) self.min_stack.append(min(x, self.min_stack[-1])) def pop(self) -> None: self.stack.pop() self.min_stack.pop() def top(self) -> int: return self.stack[-1] def getMin(self) -> int: return self.min_stack[-1]
7050eb5e889c54d73ab268f10eb6d5d8376b6106
ecmadao/Coding-Guide
/Notes/Python/Python及应用/clicker.py
4,199
4.1875
4
import click import os """ $ pip3 install click """ @click.command() @click.option('--count', default=1, help='Number of hello') @click.option('--name', prompt='your name', help='Input your name here') def hello_prompt(count, name): """ prompt option, user must input a option """ print('{} says:'.format(name)) for i in range(count): click.echo('helloooooo world') @click.command() @click.option('--count', default=1, help='number of greetings') @click.argument('name') def hello(count, name): for x in range(count): click.echo('Hello {}!'.format(name)) @click.command() @click.argument('says', nargs=-1) @click.argument('name', nargs=1) def hello_multiply_arg(says, name): """ Variadic Arguments If nargs is set to -1, then an unlimited number of arguments is accepted. """ print('{} says:'.format(name)) for said in says: print(said) @click.command() @click.option('--options', '-op', default=2) def default_option(options): """ Multi Value Options options number must equal nargs """ for option in range(options): print(option) @click.command() @click.option('--op', nargs=2) def multi_options(op): """ Multi Value Options options number must equal nargs """ for option in op: print(option) @click.command() @click.option('--item', type=(int, str, int)) def tuple_option(item): """ Tuples as Multi Value Options options number must equal length of type options type must equal type """ for i in item: print(i) @click.command() @click.option('--message', '-m', multiple=True) def multiple_options(message): """ receive multiple options, use like this: $ python3 clicker.py -m message1 $ python3 clicker.py -m message1 -m message2 **do not:** $ python3 clicker.py -m message1 message2 """ for msg in message: print(msg) @click.command() @click.option('--happy/--no-happy', default=True) def boolean_option(happy): """ --happy means True --no-happy means False """ if happy: print('happy') else: print('sad') @click.command() @click.option('--happy', is_flag=True) def boolean_option_flag(happy): """ --happy means True --no-happy means False """ if happy: print('happy') else: print('sad') @click.command() @click.option('--site', '-s', type=click.Choice(['a', 'b', 'c']), default='a') def choice_option(site): """ option value must be one of click.Choice(['a', 'b', 'c']) """ print(site) @click.command() @click.argument('name', default='ecmadao') def arg_with_default(name): """ argument with default """ print(name) @click.command() @click.option('--name', '-n', prompt=True, default='ecmadao') @click.option('--age', '-a', prompt=True, default=24) def prompt_option(name, age): """ 带有输入提示和默认值的option """ print('I am {}'.format(name)) print('and {} years old'.format(age)) @click.command() @click.option('--username', prompt=True, default=lambda: os.environ.get('USER', '')) def get_user_env(username): """ 带有输入提示和默认值(调用函数)的option """ print("Hello,", username) @click.command() @click.option('--goods', prompt=True) def goods(goods): """ 带有输入提示的option """ print(goods) @click.command() @click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True) def password_option(password): """ 密码输入 """ click.echo('your password is {password}'.format(password=password)) def print_version(ctx, param, value): print(ctx) print(param) if not value or ctx.resilient_parsing: click.echo('Version 1.0000000000') return click.echo('Version 1.0') ctx.exit() @click.command() @click.option('--version', is_flag=True, callback=print_version, expose_value=False, is_eager=True) def callback_option(): """ 带有回调的option """ click.echo('Hello World!') def abort_if_false(ctx, param, value): if not value: ctx.abort() @click.command() @click.option('--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='Are you sure you want to drop the db?') def dropdb(): """ yes/no 选项的带有回调的option """ click.echo('Dropped all tables!') if __name__ == '__main__': password_option()
7ed8670877d09283d913c498332eb6f112c99b1b
Miguelflj/Prog1
/sala/Ex2.8.py
178
3.96875
4
#UFMT Ccomp #Miguel Freitas #Soma com parada -1 def main(): soma=0 a=input("Digite um valor: ") while (a != -1): soma = soma + a a=input("Digite um numero: ") print(soma) main()
4c11ab726db9abc269c07936c87a48356eee5c4d
Allen8838/Data-Science-Projects
/NYC Taxi/Modeling/feature_engineering.py
5,299
3.9375
4
"""create additional features""" import pandas as pd import numpy as np def create_cols_distances(df): """distance may be a critical feature for predicting trip durations. creating a haversine distance, manhattan distance and bearing (direction the car is heading)""" #create a column for haversine distance df['distance'] = haversine_array(df['pickup_longitude'], df['pickup_latitude'], df['dropoff_longitude'], df['dropoff_latitude']) df['manhattan_distance'] = dummy_manhattan_distance(df['pickup_longitude'], df['pickup_latitude'], df['dropoff_longitude'], df['dropoff_latitude']) df['bearing'] = bearing_array(df['pickup_longitude'], df['pickup_latitude'], df['dropoff_longitude'], df['dropoff_latitude']) return df def create_avg_speed_cols(df): """since we have distance and duration, we can calculated an additional feature of speed""" #create speed column. this should be correlated with the day component #and may give additional insight df['avg_speed_haversine'] = 1000*df['distance'].values/df['trip_duration'] df['avg_speed_manhattan'] = 1000*df['manhattan_distance'].values/df['trip_duration'] return df def haversine_array(lon1, lat1, lon2, lat2): """Calculate the great circle distance between two points on the earth (specified in decimal degrees) All args must be of equal length. """ R = 6371.0 # radius of the earth in km lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 c = 2 * np.arcsin(np.sqrt(a)) km = R * c return km def dummy_manhattan_distance(lat1, lng1, lat2, lng2): a = haversine_array(lat1, lng1, lat1, lng2) b = haversine_array(lat1, lng1, lat2, lng1) return a + b def bearing_array(lat1, lng1, lat2, lng2): """calculates direction the taxi is traveling""" lng_delta_rad = np.radians(lng2 - lng1) lat1, lng1, lat2, lng2 = map(np.radians, (lat1, lng1, lat2, lng2)) y = np.sin(lng_delta_rad) * np.cos(lat2) x = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(lng_delta_rad) return np.degrees(np.arctan2(y, x)) def convert_time_sin_cos(df, column): """need to convert time to a cyclical form to help the algorithm learn that 23 hours and 0 hours are closed to each other""" sin_var = np.sin(2 * np.pi * df[column]/23.0) cos_var = np.cos(2 * np.pi * df[column]/23.0) return sin_var, cos_var def find_center_points(df, lat1, long1, lat2, long2): """see if center points help us in predicting trip duration""" df['center_latitude'] = (df[lat1].values + df[long2].values) / 2 df['center_longitude'] = (df[long1].values + df[lat2].values) / 2 return df def modify_datetime_test(df): """created this separate function because testing set does not have dropoff datetime.""" df['pickup_hour'] = pd.to_datetime(df['pickup_datetime']).dt.hour df['pickup_minute'] = pd.to_datetime(df['pickup_datetime']).dt.minute df['pickup_hour_sin'], df['pickup_hour_cos'] = convert_time_sin_cos(df, 'pickup_hour') df['pickup_date'] = pd.to_datetime(df['pickup_datetime']).dt.date df['pickup_day'] = pd.to_datetime(df['pickup_datetime']).dt.weekday df['pickup_day'] = pd.to_datetime(df['pickup_datetime']).dt.weekday df['pickup_weekofyear'] = pd.to_datetime(df['pickup_datetime']).dt.weekofyear df["month"] = pd.to_datetime(df['pickup_datetime']).dt.month df["year"] = pd.to_datetime(df['pickup_datetime']).dt.year return df def modify_datetime_train(df): """creating additional time features for training set""" df['pickup_hour'] = pd.to_datetime(df['pickup_datetime']).dt.hour df['dropoff_hour'] = pd.to_datetime(df['dropoff_datetime']).dt.hour df['pickup_minute'] = pd.to_datetime(df['pickup_datetime']).dt.minute df['dropoff_minute'] = pd.to_datetime(df['dropoff_datetime']).dt.minute df['pickup_hour_sin'], df['pickup_hour_cos'] = convert_time_sin_cos(df, 'pickup_hour') df['dropoff_hour_sin'], df['dropoff_hour_cos'] = convert_time_sin_cos(df, 'dropoff_hour') #split datetime between dates and time #using normalize even though it gives us 0:00 time, but the resulting column is a datetime object, #which allows us to further process for day of week df['pickup_date'] = pd.to_datetime(df['pickup_datetime']).dt.date df['dropoff_date'] = pd.to_datetime(df['dropoff_datetime']).dt.date #create day of the week for both pickup date and dropoff dates df['pickup_day'] = pd.to_datetime(df['pickup_datetime']).dt.weekday df['dropoff_day'] = pd.to_datetime(df['dropoff_datetime']).dt.weekday #get week of year to capture effects of holidays df['pickup_weekofyear'] = pd.to_datetime(df['pickup_datetime']).dt.weekofyear df["month"] = pd.to_datetime(df['pickup_datetime']).dt.month df["year"] = pd.to_datetime(df['pickup_datetime']).dt.year #one hot encode day of the week for both pickup and dropoff df = pd.get_dummies(df, columns=['pickup_day', 'dropoff_day']) return df
41a91ff436e6cf25479f28d166a4ea577644485c
YskSt030/LeetCode_Problems
/1578.MinimumDeletionCosttoAvoidRepeatingLetters.py
1,710
3.6875
4
""" Given a string s and an array of integers cost where cost[i] is the cost of deleting the character i in s. Return the minimum cost of deletions such that there are no two identical letters next to each other. Notice that you will delete the chosen characters at the same time, in other words, after deleting a character, the costs of deleting other characters will not change. Example 1: Input: s = "abaac", cost = [1,2,3,4,5] Output: 3 Explanation: Delete the letter "a" with cost 3 to get "abac" (String without two identical letters next to each other). Example 2: Input: s = "abc", cost = [1,2,3] Output: 0 Explanation: You don't need to delete any character because there are no identical letters next to each other. Example 3: Input: s = "aabaa", cost = [1,2,3,4,1] Output: 2 Explanation: Delete the first and the last character, getting the string ("aba"). Constraints: s.length == cost.length 1 <= s.length, cost.length <= 10^5 1 <= cost[i] <= 10^4 s contains only lowercase English letters. """ class Solution: def minCost(self, s: str, cost: List[int]) -> int: if len(s) == 1: return 0 p,q = 0,0 ret = 0 while True: if p == len(s) - 1: return ret if s[p] != s[p + 1]: p += 1 q = p if p == len(s): return ret else: while s[p] == s[q]: q += 1 if q == len(s): break tmp = sum(cost[p:q]) - max(cost[p:q]) ret += tmp if q == len(s): return ret p = q
04fffac964ec14cd1985f2397cee9e31e4822d9a
OlgaDrach/7
/лаб.7 (А).py
524
3.734375
4
#а) Дан текст, за яким слідує крапка. В алфавітному порядку вивести на екран (по разу) #усі малі українські голосні букви, що входять в цей текст.(Драч Ольга 122_Д) s = int(input(‘Введіть речення ‘) s1 = {'a', 'е', 'и', 'і', 'о', 'у', 'я', 'ю', 'є', 'ї'} if s[-1] == '.': s.replace('.', '') b = list(s) s1.intersection_update(b) print(s) print(sorted(s1))
b5007dd9d74717af69d7c2a8ae67bc997ec4ae8d
MaximZolotukhin/erik_metiz
/chapter_4/exercise_4.3.py
194
3.9375
4
""" Считаем до 20: используйте цикл for для вывода чисел от 1 до 20 включительно """ for number in range(1, 21): print(number, end=' ')
1d1d649df156c99f2b7a173038078104bd896ffa
justawho/Python
/chapter2Q13.py
147
4.15625
4
print ('For loop example:') for i in range(1,11): print (i) print() j = 1 print ('While loop example:') while j < 11: print (j) j= j+1
e6d6ad7dd795ba5987f6fe1a300798429644c9e4
alkrauss48/talks
/python-documentation/code/example3.py
252
3.53125
4
def generate_total_price(amounts): return sum( [amt for amt in amounts if isinstance(amt, (float, int)) and amt > 0 ] ) * 1.08 if __name__ == '__main__': print(generate_total_price([1.78, -100, 10.88, 5.23, 'a']))
05984eb9a2bf6a477b7379cfcff0f6110da4bbc0
BJamesLebo/FirstRepository
/MonthlyLoanPayment.py
414
4.03125
4
#This program calculates and returns the monthly payments for a loan def calculate_payment (principal,annual_interest_rate,duration): if annual_interest_rate==0: return principal/(duration*12) r = (annual_interest_rate/100)/12 #monthly interest rate n = duration*12 #no. of monthly payments during loan monthly_payment = principal * ((r*(1+r)**n) / ((1+r)**n-1)) return monthly_payment
5a1096cff6d3cc4535c189b2338ed19c105e2834
Bovey0809/Algorithm
/leetcode/912.sort-an-array.py
947
3.609375
4
# # @lc app=leetcode id=912 lang=python3 # # [912] Sort an Array # # @lc code=start import random class Solution: def sortArray(self, nums): def merge(left, right): result = [] while left and right: if left[0] < right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) if left: result += left if right: result += right return result def mergeSort(nums): if len(nums) == 1: return nums mid = len(nums) // 2 left = mergeSort(nums[:mid]) right = mergeSort(nums[mid:]) return merge(left, right) return mergeSort(nums) # @lc code=end my = Solution() test = [random.randint(1, 20) for _ in range(random.randint(0, 20))] print(my.sortArray(test))
ea714c60f77d0c935d37c7f673fee0a975c49bb2
BaN4NaJ0e/webDJ
/votedb.py
1,507
3.578125
4
# coding: utf-8 import sqlite3 import time def setupDB(): # open sqlite db connection connection = sqlite3.connect("uservotedb.db") cursor = connection.cursor() cursor.execute("""DROP TABLE IF EXISTS votedb """) cursor.execute("""CREATE TABLE IF NOT EXISTS votedb ( trackid INTEGER, userip TEXT, timestamp FLOAT)""") # commit all new entries connection.commit() #close db connection.close() def insertVote(trackid, ip): connection = sqlite3.connect("uservotedb.db") cursor = connection.cursor() timestamp = time.time() voteinfos = [trackid, ip, timestamp] sql = "INSERT INTO votedb VALUES (?, ?, ?)" cursor.execute(sql, voteinfos) # commit all new entries connection.commit() #close db connection.close() def checkQuota(trackid, ip): connection = sqlite3.connect("uservotedb.db") cursor = connection.cursor() t = (trackid, ip) # check if user voted for this song in the past cursor.execute("""SELECT timestamp FROM votedb WHERE trackid=? AND userip=?;""", t ) pathTuple = cursor.fetchall() if len(pathTuple) > 0 : # user already voted for this song return False else: # first vote for this song by user return True # after song was played, trackid/ip will be deleted so user can vote it again def resetVotes(trackid): connection = sqlite3.connect("uservotedb.db") cursor = connection.cursor() t = (trackid) cursor.execute("""DELETE FROM votedb WHERE trackid=? ;""", t ) # commit delete connection.commit() #close db connection.close()
9474fd8021a2fee53eac5012f2695cbd75076aa2
SACHSTech/basic-practice-Ahastan
/cake_jog.py
652
4.59375
5
''' ------------------------------------------------------------------------------- Name: cake_jog.py Purpose: Find out how far the user mus jog based on how many slices of cake they had Author: Surees.A Created: 02/12/2020 ------------------------------------------------------------------------------- ''' # How much cake have they eaten calories_cake = int(input("How many pieces of cake have you eaten? ")) # total number of calories from the cake total_calories = (calories_cake*225) # how far they must jog jogging_distance = (total_calories/100) print ("To burn off the calories eaten by the cake, you must jog" , str(jogging_distance) , "km")
9a817af941b650647c8b24053bd1e9d921c0c9b1
charlcater/aoc2020
/day_09/aoc2020_09.py
1,843
3.71875
4
# Advent of Code 2020 # --- Day 9: Encoding Error --- def two_sum(nums, target): compls = set() for x in nums: if x in compls: return True compls.add(target - x) return False def part1(nums): # more efficient solution, O(n) for i, target in enumerate(nums[25:]): if not two_sum(nums[i:i + 25], target): break return target # this is quadrtic time # i = 0 # low = 0 # high = 25 # for number in numlist[high:]: # for n in numlist[low+i:high+i]: # valid = 0 # nn = number - n # if nn > 0 and nn in numlist[low+i:high+i]: # # print('{} is valid'.format(number)) # valid = 1 # i += 1 # break # else: # pass # if valid == 0: # # print('invalid: {}'.format(number)) # return(number) def part2(number, numbers): maxlen = len(numbers) i = 0 # index in input list while i < maxlen-1: doSum = True j = 1 total = 0 while doSum: # print(numbers[i:i+j]) total = sum(x for x in numbers[i:i+j]) # print(total) if total == number: # minval = max(numbers[i:i+j]) # maxval = min(numbers[i:i+j]) # print(minval, maxval) return(min(numbers[i:i+j]) + max(numbers[i:i+j])) elif total < number: j += 1 else: i += 1 doSum = False nums = [int(entry.strip('\n')) for entry in open("input.txt", "r").readlines()] print('Part 1: first invalid number = {}'.format(part1(nums))) print('Part 2: encryption weakness = {}'.format(part2(part1(nums), nums)))
2fcc30ffffb2f29cbc4c0214d863dab2fba009a1
LaurenKScott/COMP151-the-lighthouse
/adventure.py
1,431
4.28125
4
# File: adventure.py # A simple text adventure game """ HOW TO PLAY Objective - get to the top of the lighthouse and signal for help. Instructions - when prompted, enter a command into the terminal. commands are one or two word phrases consisting of a verb and a noun or direction. use commands to move around the map and to interact with objects """ # import modules import iteminventory as ii import gmap as mp import gameparse as pr #Initialize player's empty inventory (see iteminventory.py) player_inv = ii.player_inv #initialize island map (see map.py for tile info) island = mp.game_map #Initialize parser (see gameparse.py for command info) parser = pr.cmdp #set win condition def win_condition(): if island.get_location() == mp.tile10 and island.get_location().item is None: print("you win") return True return False # gameplay function, takes string user_command and parses input. then translates into executable command def play_game(): user_command = input("Enter a command: ") parser.parse(user_command) print() parser.command_choose() print() def main(): # start of game, print initial tile description print("THE LIGHTHOUSE") print() print(island.get_location().get_description()) while parser.continue_game() and not win_condition(): play_game() else: print("Goodbye.") if __name__ == '__main__': main()
3aa187ff23419ff03fa73b6e9f93d8a7f81af809
TunedMystic/django-file-upload
/picsApp/simpleFileSize.py
581
3.59375
4
""" Amtex Training Project "Image Upload Program" Sandeep Jadoonanan October 24, 2014 """ def getSize(amt): """ This function takes a file size (in bytes) and converts the output into readable format. Supports file sizes in: 'bytes', 'kb', and 'mb'. """ fmt = lambda x: "{:,}".format(x) fstr = lambda x, y: float("%.1f" % (x / float(y))) kb = 1024 mb = (1024 * 1024) if amt >= mb: amt = fmt(fstr(amt, mb)) + " mb" return amt if amt >= kb: amt = fmt(fstr(amt, kb)) + " kb" return amt return fmt(amt) + " bytes"
6ccaf672427ecda1990573a8b3bc2fab89154247
vinaygupta7/my-projects
/python_learning/22_method_overriding.py
464
3.859375
4
class Rectangle(): def __init__(self,length,breadth): self.length=length self.breadth=breadth def getArea(self): print(self.length*self.breadth,' is area of rectangle') class square(Rectangle): def __init__(self,side): self.side=side Rectangle.__init__(self,side,side) def getArea(self): print(self.side*self.side, " is the area of square.") s=square(4) r= Rectangle(2,4) s.getArea() r.getArea()
4468d98bc7f05358a2ac8178677cb0d315070dd3
coy0725/leetcode
/python/876_Middle_of_the_Linked_List.py
657
3.875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): # def middleNode(self, head): # """ # :type head: ListNode # :rtype: ListNode # """ # res = [] # while head: # res.append(head) # head = head.next # return res[len(res) / 2] def middleNode(self, head): # Fast point is 2 times faster than slow point fast = slow = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
8a71b43e06fbeeb5d90450c579ca6c99deb92eb5
vmilkovic/automate_the_boring_stuff_with_python
/Chapter 7/strongPasswordDetection.py
876
3.765625
4
import re, pyperclip passLength = re.compile(r'.{8,}') # >= 8 characters passUpper = re.compile(r'[A-Z]') # Contains an upper case letter passLower = re.compile(r'[a-z]') # Contains a lower case letter passDigit = re.compile(r'[0-9]') # Contains a digit def checkPasswordStrength(password): if passLength.search(password) is None: return False elif passUpper.search(password) is None: return False elif passLower.search(password) is None: return False elif passDigit.search(password) is None: return False else: return True password = str(pyperclip.paste()) if checkPasswordStrength(password) == True: print('Strong password.') else: print('Weak password.') # Or if re.compile(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$').search(password): print('Strong password.') else: print('Weak password.')
e7c87c499b0bf9f28fc6ab3e8a3a3308c8d2ffd3
chav-aniket/cs1531
/labs/20T1-cs1531-lab02/reverse.py
1,617
4.28125
4
def reverse_words(string_list): ''' Given a list of strings, return a new list where the order of the words is$ For example, >>> reverse_words(["Hello World", "I am here"]) ['World Hello', 'here am I'] ''' ret = [] for x in string_list: t = x.split(" ") t.reverse() r = " ".join(t) ret.append(r) return ret def test_one(): ''' Tests the retention of capital letters ''' list_one = ["Yes I am", "rAwR xDd", "my OH my"] list_one_reversed = ["am I Yes", "xDd rAwR", "my OH my"] assert reverse_words(list_one) == list_one_reversed def test_two(): ''' Tests the retention of punctuation ''' list_two = ["We're done here.", "mayhaps, we shall?", "no... I don't think I will"] list_two_reversed = ["here. done We're", "shall? we mayhaps,", "will I think don't I no..."] assert reverse_words(list_two) == list_two_reversed def test_three(): ''' Tests the retention of double spaces ''' list_three = ["spaces here", " leading trailing "] list_three_reversed = ["here spaces", " trailing leading "] assert reverse_words(list_three) == list_three_reversed def test_four(): ''' Tests empty strings ''' list_four = ["", ""] list_four_reversed = ["", ""] assert reverse_words(list_four) == list_four_reversed def test_five(): ''' Tests what happens when there are no spaces ''' list_five = ["aiwuy./er,g/?ar!?><aR?v.,arb"] list_five_reversed = ["aiwuy./er,g/?ar!?><aR?v.,arb"] assert reverse_words(list_five) == list_five_reversed
2bc8f39dc9f4c208ffc943065172362597a23df6
arihant-2310/Python-Programs
/second smallest single number.py
172
3.890625
4
a=[] n= input('enter number of elements:-') for i in range(n): e= input('enter element') a.append(e) a.sort() print('second smallest element:-') print a[1]
fc1d0045d0d76916ddbb8c472180b746efa71f3f
hisubhajit/Python-demo
/conditionDemo1.py
338
4.15625
4
print("This a first conditional demo program"); x = input("Please enter something: "); print("You have entered: "+x+ " , which is a "+str(type(x))); ''' If condition below code is example of if condition in python ''' print("Demo for IF condition"); name = input("Enter your name: "); if(len(name) > 5): print("Your name is big");
16cc0add8a50a930aa9c940b936688069b120ccd
mylove1/PythonSamples
/python3/algorithm.py
364
3.921875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # -*- author: [email protected] import random def createNumArrayList(): size = 10 num_array = [] for i in range(size): num_array.append(random.randint(1,100)) return num_array #print(createNumArrayList()) def quickSearch(num_array): if num_array!=[]: base_num = num_array[0]
8d231062ba949cc95969e373fb5d9aa731ba40d9
colevahey/pickem
/.py/login.py
1,212
3.625
4
import json import hashlib import adduser users = open('./users.json', 'r') userdata = json.loads(users.read()) def login(): uname = input("\033[H\033[2JUsername?\n>> ") password = input("Password?\n>> \033[8m") print("\033[0m") hash_object = hashlib.sha224(password.encode()) hashpassword = hash_object.hexdigest() try: if userdata[uname]["password"] == hashpassword: print("\033[H\033[2JWelcome back " + uname) print("Your current record is " + str(userdata[uname]["wins"]) + "-" + str(userdata[uname]["losses"])) print() input("Press enter to continue") return uname else: print("That password is incorrect") input("Try again? [Press enter to continue]") print() return login() except KeyError: print("That user does not exist") create = input("Try again [Press enter] or create new user [Press c enter]?\n>> ") if create.lower() == "c": print() print("NEW USER:\n") return adduser.main() else: print() return login() if __name__ == '__main__': login()
66b47bdcf0d23644c4a46ee3f3f80d277f4155fe
weidizhang/genesis-asset-trader
/backtest_strategy.py
2,937
3.6875
4
import pandas as pd from predict import Predict # Essentially, alternate buy and sell transactions by alternating minimas # and maximas; must start with a buy (minima) # # Used for backtesting, mimicking behavior of buying or selling on the first # received minima or maxima signal, and applying the rule that buys and sells # must alternate, i.e. 3 buys in a row is illegal # # Can prohibit selling on a loss (a maxima's price or value must be greater # than the previous minima's price or value), in the case that a user enforces # this rule in a real world trading situation def alternate_extremas(df, sell_at_loss = False): remove_extremas = [] prev_type = 1 # Say the previous type is a maxima so that it must start with a buy (minima) prev_value = 0 for i, row in df.iterrows(): extrema_type = row["Extrema"] value = row["HLCAverage"] if extrema_type == 0: continue elif extrema_type == prev_type or ((not sell_at_loss) and extrema_type == 1 and value < prev_value): remove_extremas.append(i) continue prev_type, prev_value = extrema_type, value Predict.delete_extremas(df, remove_extremas) return len(remove_extremas) # Used for backtesting to enforce that the last transaction must be a "sell" # (maxima) to give a better picture of profitability # # Assumes that alternate_extremas was already applied to df def end_with_sell(df): last_extrema = df[df["Extrema"] != 0][::-1].iloc[0] if last_extrema["Extrema"] == -1: Predict.delete_extremas(df, last_extrema.name) # Used for backtesting to generate a summary of resultant of the # transactions made at extremas predicted by the predict module as a result # of the model combined with heuristics and other strategies # # Assumes that all preceeding profits are reinvested in future transactions # # Assumes that alternate_extremas and end_with_sell have been applied to df def generate_tx_summary(df): # As a percentange, NOT as a decimal def profit_loss(current_val, start_val): return ((current_val - start_val) / start_val) * 100 summary = [] extremas = df[df["Extrema"] != 0] units_owned = None current_val = start_val = 0 for i, row in extremas.iterrows(): date = row["Date"] extrema_type = row["Extrema"] value = row["HLCAverage"] if extrema_type == -1: # Buy if units_owned is None: units_owned = 1 start_val = current_val = value else: units_owned = current_val / value else: # Sell current_val = value * units_owned units_owned = 0 summary.append((date, extrema_type, units_owned, current_val, profit_loss(current_val, start_val))) df_summary = pd.DataFrame(summary, columns = ["Date", "Extrema", "UnitsOwned", "Value", "ProfitLoss"]) return df_summary
9182abbec90ec73371bf7f172e00b5ead3c25198
preeyankae/Innovative-Hacktober
/python_strings/str5.py
458
3.96875
4
value = 20 str = 'This another way of a string with a value {}'.format(value) print(str) value = 30 str = f'This another way of a string with a value {value}' print(str) Umm, I'm the one that made this pull request, you deleted it and said there were conflicts but there weren't cause you then merged it back into the master Because of this, I lost one of my pull request and had to start over my review period, please don't try to do that again, thanks.
555671538d750d280fc0db0374d582b8e31ce57d
hanlulu1998/Coursera-Machine-Learning
/ex2-logistic regression/Python/ex2funcReg.py
2,362
3.75
4
import matplotlib.pyplot as plt import numpy as np from ex2func import sigmoid, plotData def mapFeature(X1, X2): # MAPFEATURE Feature mapping function to polynomial features # # MAPFEATURE(X1, X2) maps the two input features # to quadratic features used in the regularization exercise. # # Returns a new feature array with more features, comprising of # X1, X2, X1.^2, X2.^2, X1*X2, X1*X2.^2, etc.. # # Inputs X1, X2 must be the same size degree = 6 out = np.ones(X1.shape)[:, None] for i in range(1, degree + 1): for j in range(i + 1): temp = (X1 ** (i - j)) * (X2 ** j) out = np.hstack((out, temp[:, None])) return out def costFunctionReg(theta, X, y, l): # COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization # J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using # theta as the parameter for regularized logistic regression and the # gradient of the cost w.r.t. to the parameters. m = len(y) z = X.dot(theta) h = sigmoid(z) J = 1 / m * sum(-y * np.log(h) - (1 - y) * np.log(1 - h)) + l / (2 * m) * sum(theta ** 2) grad = 1 / m * sum((h - y)[:, None] * X) grad[1:-1] = grad[1:-1] + l / m * theta[1:-1] return J, grad # serve scipy.optimize.minimize function def costfunc(theta, X, y, l): return costFunctionReg(theta, X, y, l)[0] def gradfunc(theta, X, y, l): return costFunctionReg(theta, X, y, l)[1] def plotDecisionBoundary(theta, X, y): # PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with # the decision boundary defined by theta plotData(X[:, [1, 2]], y) if X.shape[1] <= 3: plot_x = np.array([np.min(X[:, 1]) - 2, np.max(X[:, 1]) + 2]) plot_y = (-1 / theta[2]) * (theta[1] * plot_x + theta[0]) plt.plot(plot_x, plot_y) plt.legend(['Admitted', 'Not admitted', 'Decision Boundary']) plt.axis([30, 100, 30, 100]) else: u = np.linspace(-1, 1.5, 50) v = np.linspace(-1, 1.5, 50) z = np.zeros((len(u), len(v))) for i in range(len(u)): for j in range(len(v)): z[i, j] = mapFeature(u[i].reshape(1, ), v[j].reshape(1, )).dot(theta) print(z.shape) plt.contour(u, v, z, levels=0, linewidth=2)
be8cf0b046e72e146be67f775b018e94f48720d6
hanwjdgh/NLU-basic
/8. Deep Learning/3. LSTM/test1.py
1,127
3.5
4
from keras.models import Model from keras.layers import Input, Dense, LSTM import numpy as np x = np.array([[[1.], [2.], [3.], [4.], [5.]]]) y = np.array([[6.]]) xInput = Input(batch_shape=(None, 5, 1)) xLstm = LSTM(3)(xInput) #Lstm = LSTM(3, return_sequences=False)(xInput) many-to-one을 의미 xOutput = Dense(1)(xLstm) model = Model(xInput, xOutput) model.compile(loss='mean_squared_error', optimizer='adam') print(model.summary()) model.fit(x, y, epochs=50, batch_size=1, verbose=0) model.predict(x, batch_size=1) """ _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_2 (InputLayer) (None, 5, 1) 0 _________________________________________________________________ lstm_2 (LSTM) (None, 3) 60 _________________________________________________________________ dense_2 (Dense) (None, 1) 4 ================================================================= """
88ac87a1ea7e34476a3ca6407b7b7022b3a1c7c7
granth19/Old-Python-Stuff
/MyClassTestMultiple.py
1,652
3.859375
4
class Vehicle: def __init__(self,sp): self.wheels = 4 self.speed = sp def accelerate(self,value): self.speed+=value def __str__(self): return "A vehicle with " + str(self.wheels) + " wheels." def stop(self): temp = self.speed self.speed = 0 return -temp class Car(Vehicle): def __init__(self, sp): Vehicle.__init__(self,sp) def __str__(self): return "A car going " + str(self.speed) + " mph." class Motorcycle(Vehicle): def __init__(self,sp): Vehicle.__init__(self,sp) self.wheels = 2 def wheelie(self): print "Yeehaw!!" class Truck(Vehicle): def __init__(self,sp,pl,cap): Vehicle.__init__(self,sp) self.payload=pl self.capacity=cap def __str__(self): return "A Truck with a capacity of " + str(self.capacity) + " and a payload of " + str(self.payload) def load(self,amount): if amount + self.payload <= self.capacity: self.payload += amount return self.payload else: return -1 def dump(self,amount): if amount <= self.payload: self.payload-=amount return self.payload else: return -1 ''' c1 = Car(10) #Car.accelerate(c1,-4) c1.accelerate(-4) print c1 m1 = Motorcycle(30) m1.accelerate(5) print m1 print m1.speed m1.wheelie() print c1.stop() print c1.speed ''' t1=Truck(20,200,500) print t1 print t1.load(100) print t1 print t1.dump(100) print t1 print t1.load(500) print t1.dump(500)
fd38b4f0b16dee299739a1dc1369ecb6db2d5b81
msc-27/AoC2019
/day22/day22-2.py
2,099
3.546875
4
with open('input') as f: lines = [x.strip('\n') for x in f] ssv = [x.split(' ') for x in lines] # Code for arithmetic mod p def modexp(a,b,p): # Calculate a^b mod p r = 1 power = a while b: if b % 2 == 1: r = (r * power) % p power = (power * power) % p b //= 2 return r # Fermat's Little Theorem: a^(p-1) ≡ 1 (mod p) # Therefore a . a^(p-2) ≡ 1 (mod p) def modinv(a,p): return modexp(a,p-2,p) p = 119315717514047 # deck size (assumed prime) N = 101741582076661 # number of shuffles # Function to perform a reverse shuffle, so that we can track where a # particular card came from before the shuffle. # Observe that in terms of modulo arithmetic, a 'cut' is a subtraction # operation and a 'deal with increment' is a multiplication operation. # The reverse shuffle therefore turns these into additions and # multiplication by inverses respectively, mod p. def revshuf(pos): for line in ssv[::-1]: if line[0] == 'cut': n = int(line[1]) pos += n pos %= p if line[0] == 'deal' and line[1] == 'into': pos = p - pos - 1 if line[0] == 'deal' and line[1] == 'with': incr = int(line[3]) pos = pos * modinv(incr,p) pos %= p return pos # The entire sequence of steps can be reduced to a single linear function: # shuf(x) = Ax + b (mod p) # The reverse shuffle, likewise: # revshuf(x) = Cx + d (mod p) # We wish to find C and d, and hence calculate revshuf^N(2020), where N # is the number of shuffles performed (defined above) # d = revshuf(0) # C = revshuf(1) - d # revshuf^2(x) = C^2.x + Cd + d # revshuf^3(x) = C^3.x + C^2.d + Cd + d # revshuf^N(x) = C^N.x + d( 1 + C + C^2 + ... + C^(N-1) ) # To get the tricky term: # s = 1 + C + C^2 + ... + C^(N-1) # Cs = C + C^2 + C^3 + ... + C^N # Cs-s = C^N - 1 # s = inv(C-1) . (C^N - 1) # So let's do this! d = revshuf(0) C = (revshuf(1) - d) % p s = (modinv(C-1,p) * (modexp(C,N,p) - 1)) % p term1 = (modexp(C,N,p) * 2020) % p term2 = (d * s) % p answer = (term1 + term2) % p print(answer)
4aad30e7261c187f086d57e45d069cc697ecc6d1
npstar/HackBulgaria
/week0/3/wc.py
681
3.578125
4
import sys def main(): count = 0 if sys.argv[1] == "chars": filename = sys.argv[2] file = open(filename, "r") content = file.read() for i in content: count += 1 print(count) elif sys.argv[1] == "words": filename = sys.argv[2] file = open(filename, "r") content = file.read() content = content.split(" ") print(len(content)) elif sys.argv[1] == "lines": filename = sys.argv[2] file = open(filename, "r") content = file.read() content = content.split("\n") print(len(content)) file.close() if __name__ == '__main__': main()
a5344c28a56f096a315b5d8573682c745c4d2747
jreag1/Examples
/Project_Euler/E02.py
540
3.6875
4
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. def answertwo(): ans = 0 a = 1 #First term b = 2 #Second term while a <= 4000000: if a%2 == 0: ans += a a, b = b, a+b return ans if __name__ == "__main__": print(answertwo()) #Returns 4613732
b713922ac7562903228e8af3f6cf4bc8bedbd11e
liyunfei1994/MyProject
/Data Structure/convert_to_binary.py
318
3.71875
4
import stack def divideby2(number): remstack = stack.Stack() while number >0: rem = number % 2 remstack.push(rem) number = number // 2 binstring = "" while not remstack.isEmpty(): binstring += str(remstack.pop()) return binstring print(divideby2(23)) # 10111
5ddb6c3f20a3158c8031414c5824b3c147e394f9
ThapaKazii/Myproject
/test4.py
494
4.03125
4
# Take five marks input from the user and then input into the list and then print the sum of all marks TOC=float(input("Enter the marks of TOC: ")) Maths=float(input("Enter the marks of Maths: ")) Programming=float(input("Enter the marks of Programming: ")) Statistics=float(input("Enter the marks of Statistics: ")) IT=float(input("Enter the marks of IT: ")) list=[TOC, Maths, Programming, Statistics, IT] print(list) total=int(sum(list)) print('The sum of all the subjects is: ',total)
4a051cba8cbd4680e9afb86d450c5868a24b6ee5
hksoftcorn/Algorithm
/p_stack_01/sol1.py
334
3.6875
4
stack = [] class Stack: def __init__(self): self.data = [] def is_empty(self): return False if len(self.data) else True def push(self, item): self.data.append(item) def pop(self): if not self.is_empty(): return self.data.pop() else: return None
c134f7b2c622dfe2bb8d629e8140a062944851ef
garciaha/DE_daily_challenges
/2020-08-23/sig_figs.py
1,679
4.65625
5
"""Significant Figures Write a function that takes in a string representation of an integer or decimal number and returns the number of significant figures in the number. Significant figures are an important part of science because they provide an easy way to show the precision of a measurement at a glance. In general, the more significant figures a number has, the more precise the measurement. Significant figures are calculated by looking at the digits of a number and determining the total number of digits that are "significant". The rules for deciding which digits are significant are as follows: Non-zero digits are significant. 0's in between non-zero digits (from any distance) are significant. Leading 0's (those to the left of all non-zero digits) are not significant. Trailing 0's (those to the right of all non-zero digits) are significant only if the number contains a decimal point .. If the entire number is equal to 0, return 0 for the number of significant figures. Negative signs have no effect on the number of significant figures. Notes - Each input consists of the digits 0-9, along with up to one decimal point . and/or negative sign -. - Just because two numbers are equal doen't mean that their number of sig figs are equal. For example, 1.02 has 3 sig figs while 1.020 has 4. - The function should correctly handle numbers that begin with a decimal point. - You might find regex helpful for this problem. """ def sig_figs(number): pass if __name__ == "__main__": assert sig_figs("15030") == 4 assert sig_figs("0.0067") == 2 assert sig_figs("-290.00") == 5 assert sig_figs("-8080.") == 4 print("All cases passed!")
5efc38849b4dc53d5825c3f7c079d6bde4cc2052
thefiltitoff/python_tasks
/pr4_extra/Objects.py
902
3.75
4
""" Использование встроенных функций Напишите код, который выведет на экране все переменные объекта произвольного пользовательского класса. Напишите код, который по имени метода, заданному строкой, вызовет этот метод в объекте некоторого пользовательского класса. """ import own_hash def get_object_variables(obj): return [x for x in dir(obj) if not x.startswith('__')] def invoke_object_method(obj, m): try: func = getattr(obj, m) return func() except AttributeError: print('Method do not found') if __name__ == '__main__': table = HashTable() print(get_object_variables(table)) print(invoke_object_method(table, '__len__'))
0009fe5b3b239edb8ece3d093120c1298fca62a3
dockerizeme/dockerizeme
/hard-gists/2b19fd6f758ffd2e8ab9ec7d1f3f4b2c/snippet.py
4,548
3.6875
4
# Toy example of using a deep neural network to predict average temperature # by month. Note that this is not any better than just taking the average # of the dataset; it's just meant as an example of a regression analysis using # neural networks. import logging import datetime import pandas as pd import torch import torch.nn as nn from torch.autograd import Variable import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') log = logging.getLogger(__name__) BATCH_SIZE = 12 HIDDEN_SIZE = 512 NUM_LAYERS = 2 NUM_EPOCHS = 100 LEARNING_RATE = 0.005 DROPOUT = 0.2 class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size, n_layers=1, dropout=DROPOUT): super(RNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.encoder = nn.Embedding(input_size, hidden_size) self.m = nn.Sequential(nn.ReLU(), nn.Dropout(p=0.2), nn.ReLU()) self.decoder = nn.Linear(hidden_size, output_size) def forward(self, inp, hidden): inp = self.encoder(inp) # output = BATCH_SIZE, SEQLEN, HIDDEN_SIZE # ex. torch.Size([30, 50, 512]) output = self.m(inp) # Now BATCHSIZE * SEQLEN, HIDDEN_SIZE # torch.Size([1500, 512]) output = output.contiguous().view(-1, hidden.size(2)) # Should now be BATCH_SIZE * SEQLEN, VOCAB_SIZE # torch.Size([1500, 154]) logits = self.decoder(output) return logits, hidden def init_hidden(self): # The hidden state will use BATCH_SIZE in the 1st position even if we hand data as batch_first return Variable(torch.zeros(self.n_layers, BATCH_SIZE, self.hidden_size).cuda()) def main(): print_every = 10 # Data from https://www.kaggle.com/berkeleyearth/climate-change-earth-surface-temperature-data # licened under https://creativecommons.org/licenses/by-nc-sa/4.0/ df = pd.read_csv('GlobalLandTemperaturesByState.csv') df = df.loc[df.State == 'Massachusetts'] df = df.dropna() df['dt'] = pd.to_datetime(df.dt) df = df.loc[df.dt >= datetime.datetime(1800, 1, 1)] # Dates before this are too variable df = df.loc[df.dt < datetime.datetime(2012, 1, 1)] # 2013 has incomplete data df['month'] = df.dt.dt.month df['year'] = df.dt.dt.year rnn = RNN(12, HIDDEN_SIZE, 1, n_layers=NUM_LAYERS) rnn.cuda() optimizer = torch.optim.Adam(rnn.parameters(), lr=LEARNING_RATE) criterion = torch.nn.MSELoss(size_average=False) criterion.cuda() loss_avg = 0 total_count = 0 for epoch in range(0, NUM_EPOCHS + 1): df = df.sample(frac=1) # Shuffle # For each year in the sequence, create a batch of length 12 (each month) for year in range(df.year.min(), df.year.max()): data = df.loc[df.year == year] inp = Variable(torch.LongTensor([int(i - 1) for i in data.month.values]), requires_grad=False).cuda() targets = Variable(torch.FloatTensor([float(f) for f in data.AverageTemperature.values]), requires_grad=False).cuda() hidden = rnn.init_hidden() rnn.train() rnn.zero_grad() output, _ = rnn(inp, hidden) loss = criterion(output, targets) loss_avg += loss.data[0] # [ BATCHSIZE x SEQLEN ] optimizer.zero_grad() loss.backward() optimizer.step() total_count += 1 if epoch % print_every == 0: log.info("epoch=%d, %d%% loss=%.4f", epoch, epoch / NUM_EPOCHS * 100, loss_avg / total_count) torch.save(rnn, "weather-predictor") # I'm an American df['f'] = df.AverageTemperature.apply(lambda x: (9.0 / 5.0 * x) + 32) temps = [] # Prediction stage: predict by month for i in range(0, 12): rnn.eval() inp = Variable(torch.LongTensor([[i]]), volatile=True).cuda() hidden = rnn.init_hidden() logits, hidden = rnn(inp, hidden) pred = logits[-1, :].data[0] temp = (9.0 / 5.0 * pred) + 32 temps.append(temp) print("Average temp in month ", i + 1, int(temp)) # Compare against the most recent year for which we have data excluded from our training set year = df.loc[df.year == 2012] p = pd.DataFrame([year.f, temps], index=[year.month]) p.plot() plt.show() if __name__ == '__main__': main()
0fbdbf7b75de2cfc1dc460fc687303263522ed9e
roboteer5291/advent-of-code
/2019/Day 2/solution.py
2,329
3.796875
4
def parse_file(file_name): # File to data format file = open(file_name) text = file.read() return parse_other_input(text) def parse_other_input(text): # Other input to data format vals = text.split(",") ints = [] for i in vals: ints.append(int(i)) return ints def solve_part_1(data): pointer_location = 0 while True: if pointer_location >= len(data): print(str(data)) print(pointer_location) print("We went too far") return -1 opcode = int(data[pointer_location]) if opcode == 99: # print("99: " + str(data[0])) return data[0] if pointer_location >= len(data) - 3: print("We went to far 2") return -1 arg_1_pos = data[pointer_location + 1] arg_2_pos = data[pointer_location + 2] result_pos = data[pointer_location + 3] if arg_1_pos >= len(data) or arg_2_pos >= len(data) or result_pos >= len(data): print(str(data)) print(pointer_location) print(arg_1_pos) print(arg_2_pos) print(result_pos) print("args are too far") return -1 elif opcode == 1: arg_1 = data[data[pointer_location + 1]] arg_2 = data[data[pointer_location + 2]] data[data[pointer_location + 3]] = arg_1 + arg_2 elif opcode == 2: arg_1 = data[data[pointer_location + 1]] arg_2 = data[data[pointer_location + 2]] data[data[pointer_location + 3]] = arg_1 * arg_2 else: # print("Bad opcode pos: " + str(pointer_location) + " val: " + str(data[pointer_location])) return -1 pointer_location += 4 def solve_part_2(data): for noun in range(0, 100): for verb in range(0, 100): new_data = data.copy() new_data[1] = noun new_data[2] = verb print(str(noun) + " " + str(verb)) if solve_part_1(new_data) == 19690720: print(str(noun) + " " + str(verb)) return 100 * noun + verb print("Not found yet") return -1 print("Part 1: " + str(solve_part_1(parse_file("input.txt")))) # print("Part 2: " + str(solve_part_2(parse_file("input.txt"))))
d8cdd92c743ca20158241c40c07a83cdc7795031
nathanlmetze/Algorithms_Python
/Algorithms.py
2,393
4
4
# ONLY ASSUMPTION IS THAT THE GRAPH IS SETUP THE SAME WAY USING A DICTIONARY # BY NATHAN M # Helper class used to store each node and what it is connected to class adjacency_list(object): def __init__(self, key): self.key = key self.connections = {} def add_adjacency(self, neighbor, weight = 0): self.connections[neighbor] = weight def get_key(self): return self.key def get_adjacencies(self): return self.connections.keys() # Graph used to build the complete structure of nodes class graph(object): def __init__(self): self.verticies = {} def add_vertex(self, key): vertex = adjacency_list(key) self.verticies[key] = vertex return vertex def add_edge(self, start_node, end_node, weight = 0): if start_node not in self.verticies: self.add_vertex(start_node) if end_node not in self.verticies: self.add_vertex(end_node) # Forms the relationship between two nodes self.verticies[start_node].add_adjacency(self.verticies[end_node], weight) # Used to iterate over dictionary def __iter__(self): return iter(self.verticies.values()) def depth_first(graph, root): visited, stack = [], [root.get_key()] while stack: vertex = stack.pop() print("Vertex: %s" % vertex) if vertex not in visited: visited.append(vertex) print("Visited: %s" % visited) for entry in graph.verticies[vertex].get_adjacencies(): stack.append(entry.get_key()) return visited def breath_first(graph, root): visited, stack = [], [root.get_key()] while stack: vertex = stack.pop(0) print("Vertex: %s" % vertex) if vertex not in visited: visited.append(vertex) print("Visited: %s" % visited) for entry in graph.verticies[vertex].get_adjacencies(): stack.append(entry.get_key()) return visited # Example Graph setup adj_list = graph() for index in range(4): adj_list.add_vertex(index) adj_list.add_edge(0, 1) adj_list.add_edge(0, 3) adj_list.add_edge(1, 2) adj_list.add_edge(2, 4) adj_list.add_edge(2, 3) print("RUNNING DEPTH FIRST") print(depth_first(adj_list, adj_list.verticies[0])) print("RUNNING BREATH FIRST") print(breath_first(adj_list, adj_list.verticies[0]))
efd11710b5fb7919c94ca23d5df1ca1a2765d687
banderquartz/Python-Learning
/weekly_exercises/odd_even.py
373
4.0625
4
''' Created on Nov 18, 2014 @author: mike ''' while True: try: num = int(input("Please enter an integer: ")) if num % 2 == 0: print("The number " + str(num) + " is even.") else: print("The number " + str(num) + " is odd.") break except ValueError: print("Ooops! That wasn't an integer! Try again.\n")
2a89206f5d1375fba64768eb04f2cbb3e988ae69
wavesCHJ/First
/learn05_map_reduce_filter_sorted.py
3,942
3.96875
4
#map/reduce #我们先看map。map()函数接收两个参数,一个是函数,一个是Iterable, #map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。 def f(x): return x * x r = map(f, [1,2,3,4,5]) print(list(r)) r = map(str, [1,2,3,4,5]) print(list(r)) #再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...]上, #这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算, #其效果就是: #reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) from functools import reduce def add(x, y): return x + y print(reduce(add, [1, 3, 5, 7, 9])) #相加的和 def add2(x, y): return x * 10 + y print(reduce(add2, [1, 3, 5, 7, 9])) #将序列变为一个数 #把str转换为int的函数 def str2int(s): def fn(x, y): return x * 10 + y def char2num(c): return ord(c) - 48 return reduce(fn, map(char2num, s)) print(str2int('12344') + 1) #practice #利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。 #输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']: def fun1(s): return s[:1].upper() + s[1:].lower() print(list(map(fun1, ['adam', 'LISA', 'barT']))) #字符串是不可变对象,因此不能直接改变字符串的内容,一般是重新生成一个 #字符串修改某一个位置的字符, #一种可行的方式,是将字符串转换为列表,修改列表的元素后,再重新连接为字符串 s = 'abcdefghijk' l = list(s) l[0] = 'A' newS = ''.join(l) print(newS) #请编写一个prod()函数,可以接受一个list并利用reduce()求积: def prod(L): def fun_p(x, y): return x * y return reduce(fun_p, L) print(prod([1,2,3,4,5])) print('\n') #filter #和map()类似,filter()也接收一个函数和一个序列。和map()不同的是, #filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。 def is_odd(n): return n % 2 == 1 print(list(filter(is_odd, [1, 2, 3, 4, 5]))) #把一个序列中的空字符串删掉 def not_empty(s): return s and s.strip() l = list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])) print(l) #回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数: def is_palindrome(n): return (str(n) == str(n)[::-1]) #string[::-1] 字符串翻转 l = list(filter(is_palindrome, [12321, 12345, 34543, 909])) print(l) print('\n') #sorted #排序的核心是比较两个元素的大小。如果是数字,我们可以直接比较, #但如果是字符串或者两个dict呢?直接比较数学上的大小是没有意义的, #因此,比较的过程必须通过函数抽象出来 #Python内置的sorted()函数就可以对list进行排序: l = sorted([36, 5, -12, 9, -21]) print(l) #此外,sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序, #例如按绝对值大小排序: l = sorted([36, 5, -12, 9, -21], key = abs) print(l) l = sorted(['bob', 'about', 'Zoo', 'Credit']) #默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面 print(l) l = sorted(['bob', 'about', 'Zoo', 'Credit'], key = str.lower, reverse = True) #忽略大小写的排序,并且反向排序 print(l) #practice #假设我们用一组tuple表示学生名字和成绩: L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] #请用sorted()对上述列表分别按名字排序 def sort_by_name(t): return t[0] #再按成绩从高到低排序: def sort_by_grade(t): return t[1] l = sorted(L, key = sort_by_name) print(l) l = sorted(L, key = sort_by_grade, reverse = True) print(l)
d34979539879f6e93d54cb0c4e7511a74a84f0d2
boboyiyi/learn_python
/book1/data_type/l_list.py
1,203
3.796875
4
# -*- coding: utf-8 -*- ''' 列表支持所有类似string的序列操作 ''' test_list = [180, 'fanbo', 1.80] print len(test_list) print test_list[0] # 索引 print test_list[:-1] # 切片 print test_list + [158, 'cxm', 1.58] # 连接 print test_list * 3 #类型特定的方法 test_list.append('hehe') print test_list # 这里貌似append的返回值是NONE,所以直接printf会打印NONE print test_list.pop(2) test_list1 = ['aa', 'cc', 'bb'] test_list1.sort() print test_list1 test_list1.reverse() print test_list1 test_list.extend(['dd', 'ee']) print test_list print dir(test_list1) # 嵌套 # python支持列表嵌套其他任意类型 M = [[1,2,3], [4,5,6], [7,8,9]] # 列表嵌套列表可以表示矩阵或者二维数组 print M[1][0] #列表解析 print M[0] # 可以简单地用index获取矩阵的行 # 我们现在需要用简单的方式来获取列,这里用到列表解析 print [row[0] for row in M] # 这里row变量可以随便给,比如i也可以,列表解析即在列表中运行一个表达式创建一个新的列表 print [i[1] for i in M if i[1] % 2 == 0] # 只能说这个特性太棒了! print [M[i][i] for i in [0,1,2]] print [c * 2 for c in 'spam']
582911f5be92b01103c01cc23201a7309f1f089c
GlauberC/UFRN
/CompeticaoProgramacao/aula01/d.py
140
3.5
4
testes = int(input()) for test in range(0,testes): n, m = input().split() x = int(int(n) / 3) y = int(int(m) / 3) print(x*y)
c48ca7c35767340f0d9d80e945db67281198dc01
Justinpy8/desktop_excercis
/Exc_3.4to3.7.py
2,047
4.15625
4
# 3.4 guests = ['Tony', 'Kevin', 'Holly'] print(guests[0] + ' I would like to invite you to our house warming party dinner.') print(guests[1] + ' I would like to invite you to our house warming party dinner.') print(guests[2] + ' I would like to invite you to our house warming party dinner.') # 3.5 print(guests[-1] + ' Cannot make it to our party') guests.remove('Holly') guests.append('Chel') print(guests[0] + ' I would like to invite you to our house warming party dinner.') print(guests[1] + ' I would like to invite you to our house warming party dinner.') print(guests[2] + ' I would like to invite you to our house warming party dinner.') # 3.6 print(guests[0] + ' I found a bigger table, so I am going to invite 3 more friends.') print(guests[1] + ' I found a bigger table, so I am going to invite 3 more friends.') print(guests[2] + ' I found a bigger table, so I am going to invite 3 more friends.') guests.insert(0, 'Dan') guests.insert(2, 'Nikky') guests.append('Cindy') print(guests) print(guests[0] + ' I would like to invite you to our house warming party dinner.') print(guests[1] + ' I would like to invite you to our house warming party dinner.') print(guests[2] + ' I would like to invite you to our house warming party dinner.') print(guests[3] + ' I would like to invite you to our house warming party dinner.') print(guests[4] + ' I would like to invite you to our house warming party dinner.') print(guests[5] + ' I would like to invite you to our house warming party dinner.') # 3.7 msg = ' I am sorry, you are being uninvited because I can only invite two people to the party.' canceledguest0 = guests.pop(0) print(canceledguest0 + msg) canceledguest1 = guests.pop(1) print(canceledguest1 + msg) canceledguest2 = guests.pop(2) print(canceledguest2 + msg) canceledguest3 = guests.pop(2) print(canceledguest3 + msg) print(guests) msg2 = ' I am happy to inform you that you are still being invited to the party.' print(guests[0] + msg2) print(guests[1] + msg2) del guests[0] del guests[1] print(guests)
5030639b7d50db1c67beb08985d44250705b1e91
pallavi12coder/pallaviuike2020
/6.py
971
3.859375
4
#To retrieve all records and columns from table import pymysql #STEP 1 : create connection string python with mysqlserver servername="localhost" username="root" password="" dbname="school_vedant" #dbname means database name try: con=pymysql.connect(servername,username,password,dbname) #con user defined object name #con object of connect() except Exception: print("Connection Error") else: print("Connection successfully") #Step 2 : #Creating a cursor object using the cursor() method cur = con.cursor() #step 3: Query fire query="SELECT * FROM STUDENT" #step 4: Query run use execute method of cursor try: cur.execute(query) except Exception : print("Query Error") else: #Fetching all rows from the table result = cur.fetchall() #here result user defined object , hold all records in this object print(result) #here result object tuple type , means no changes the record cur.close() con.close()
791db0c033b27c2d95df208011c6cc4385b69c11
youthinnovationclub/2019MoonLanding50thAnniversaryProject
/PythonProject/terrain.py
2,090
3.84375
4
import turtle import random # TODO: decide off screen behaviour def getYPoint(x): """ Finds the y point of the line given an x """ global coords afterX = 0 afterY = 0 for coord in coords: if x == coord[0]: return coord[1] beforeX = afterX beforeY = afterY afterX = coord[0] afterY = coord[1] if x > beforeX and x < afterX: break # proportion of distance on the x axis * difference in Y + y starting point return ((x-beforeX)/(afterX-beforeX))*(afterY-beforeY)+beforeY def aboveLine(x,y): """ Takes point coordinates and returns boolean whether the point is above the line.""" yPoint = getYPoint(x) if y > yPoint: return True else: return False def onPad(x): """ Returns whether the lander is on the pad """ global pad tolerance = 20 if x > pad.xcor() - tolerance and x < pad.xcor() + tolerance: return True else: return False WIDTH = 400 HEIGHT = 400 # All figures are proportional to the width and height STARTX = -int(WIDTH/2) STARTY = -int(HEIGHT*0.375) MOVEMENT = HEIGHT/20 LOWER_BOUNDS = int(STARTY+1.5*MOVEMENT) UPPER_BOUNDS = int(STARTY-1.5*MOVEMENT) PAD_LIMITS = WIDTH/2-10 turtle.Screen().setup(WIDTH,HEIGHT) turtle.Screen().bgpic("sky.jpg") numPads = 1 coords = [] # Initiate turtle pad = turtle.Turtle() pad.speed(0) pad.shape("square") #pad.turtlesize(2,0.5) pad.hideturtle() pad.penup() pad.goto(STARTX,STARTY) coords.append((STARTX,STARTY)) pad.pendown() pad.fillcolor('lightgray') pad.begin_fill() # Proceedurally generate terrain randomly while pad.xcor() < WIDTH/2: newX = pad.xcor() + random.randint(int(WIDTH/40),int(WIDTH/8)) if pad.ycor() > LOWER_BOUNDS or pad.ycor() < UPPER_BOUNDS: newY = random.randint(UPPER_BOUNDS,LOWER_BOUNDS) else: newY = pad.ycor() + random.randint(-MOVEMENT,MOVEMENT) coords.append((newX,newY)) pad.goto(newX,newY) pad.goto(WIDTH/2,-HEIGHT/2) pad.goto(-WIDTH/2,-HEIGHT/2) pad.end_fill() # Place landing pad pad.penup() padX = random.randint(-PAD_LIMITS,PAD_LIMITS) pad.goto(padX,getYPoint(padX)) pad.setheading(0) pad.showturtle()
dc27b35a1e746758f8f72ba3cc2304c675c4ebb1
Tanay2112/Python-Codes
/sameRowWord.py
418
3.984375
4
word=input() r1="qwertyuiop" r2="asdfghjkl" r3="zxcvbnm" c=0 if word[0] in r1: for ch in word: if not ch in r1: c=-1 break elif word[0] in r2: for ch in word: if not ch in r2: c=-1 break else: for ch in word: if not ch in r3: c=-1 break if c==-1: print("no") else: print("yes")
91f17d264faf50e1bbf3143b26b9090d3bc2212d
sgupta25/Python-Camp-2016
/guessing game 1-.py
1,961
3.84375
4
try: n=5 while n >0: n = n -1 print "you have five tries to sink a battle ship" print " you have to guess 5 numbers between 1-20" print "if you hit a mine, the game is over" x = raw_input ("enter a number") x = float (x) if x == 1: print 'no battle ship' print str(n) + ' more tries' if x == 2: print 'no battle ship' print str(n) + "more tries" if x == 3: print 'good job, battle ship found and sunk' print 'you win' if x == 4: print 'good job, battle ship found and sunk' print 'you win' if x == 5: print 'you hit a mine!' print 'game over!' if x == 6: print 'you hit a mine!' print 'game over!' if x == 7: print 'you hit a mine!' print 'game over!' if x == 8: print 'no battle ship' print str(n) + 'more tries' if x == 9: print 'no battle ship' print str(n) + ' more tries' if x == 10: print 'no battle ship' print str(n) + ' more tries' if x == 11: print 'you hit a mine!' print 'game over!' if x == 12: print 'good job, battle ship found and sunk' print 'you win' if x == 13: print 'no battle ship' print str(n) + " more tries" if x == 14: print 'no battle ship' print str(n) + " more tries" if x == 15: print 'no battle ship' print str(n) + " more tries" if x == 16: print 'good job, battle ship found and sunk' print 'you win' if x == 17: print 'no battle ship' print str(n) + ' more tries' if x == 18: print 'no battle ship' print str(n) + ' more tries' if x == 19: print 'you hit a mine!' print 'game over!' if x == 20: print 'no battle ship' print str(n) + "more tries" except: "error, type numeric values"
bb063e0516b9276c5684846ee4db0a2f2b83b154
sunweiye12/python-BasicLearning
/02_面向对象/py_02_基础语法.py
3,350
3.96875
4
# -----------------------------------知识点------------------------------------------- """ 1.内置函数( __方法名__ 格式的方法是 Python 提供的 内置方法 / 属性):一下是常用的内置方法 01 __new__ 方法 创建对象时,会被 自动 调用 02 __init__ 方法 对象被初始化时,会被 自动 调用 03 __del__ 方法 对象被从内存中销毁前,会被 自动 调用 04 __str__ 方法 返回对象的描述信息,print 函数输出使用(类似于 toString 函数) 2.定义简单的类 1.类名的命名规则要符合大驼峰命名法 2.方法格式和之前学习的函数一样,区别在于第一个参数必须是 self(***) 格式如下: class 类名: def 方法1(self, 参数列表): pass def 方法2(self, 参数列表): pass 3.方法中的self参数 在类封装的方法内部,self 就表示当前调用方法的这个对象(就相当于this) 4.初始化方法( __init__) ---> 属性的定义 1>.使用类名()创建对象时,会自动执行初始方法,并对象在内存中分配空间 2>.在初始化方法内部定义属性 格式如下: class Cat: def __init__(self, name): print("初始化方法 %s" % name) self.name = name tom = Cat("Tom") lazy_cat = Cat("大懒猫") 5.创建对象 格式: 对象变量 = 类名() 对象变量 = 类名(arge) 参数自动传递到初始方法中(****ß) """ # -----------------------------------练习------------------------------------------- print("-----------------------------------类的定义(方法)-------------------------------------------") # 定义一个类 class Cat: # name = None # 设置类的属性(在初始化方法中定义了name 属性,因此此处可以省去声明) def __init__(self, name=""): # 内置方法,在创建对象的时候自动调用 print("初始化方法") self.name = name # 设置类的属性 def eat(self): # 设置类的方法 print("%s 爱吃鱼" % self.name) def drink(self): print("%s 要喝水" % self.name) def __str__(self): # 相当于toString的方法 return "我是小猫:%s" % self.name # Cat.name = "tom123" # 在类的外面给类添加字段(非常不推荐在类的外部给对象增加属性 ) # 创建猫1对象 tom = Cat("tom") # tom.name = "tom" tom.eat() tom.drink() print(tom) # 创建猫2对象 rose = Cat() rose.name = "rose" rose.eat() rose.drink() print(rose) print("-----------------------------------类的定义(属性)-------------------------------------------") class Cat: def __init__(self, name=""): # 相当于构造方法(每个参数都设置初始值,保证在创建对象的时候不传参数也可以) print("初始化方法 %s" % name) self.name = name def drink(self): print("%s 要喝水" % self.name) # 生成对象 tom = Cat("Tom") # 传递传递参数 Tom lazy_cat = Cat("大懒猫") # 传递参数 大懒猫 rose = Cat() # 没有传递参数 默认为 ""
bc89cd2beacaedee09502e3f1d47d9694b95b554
SutronPyto/LinkPython
/src/dga.py
3,913
3.546875
4
# Example: demonstrates formatting a message in DGA format import re from sl3 import * class SetupError(Exception): pass def cell_sig_str_bars(): """ Returns the cell modem signal strength in bars :return: signal strength in bars (0 to 4) :rtype: int """ # assume there is no signal sig_str = 0 status_cell = command_line("!STATUS CELL") # the reply to that command will have a line such as # Cell signal: 3/4 bars at 2019/11/08 14:40:10 # we need the number of bars, which is 3 in the example above # split it into lines all_lines = status_cell.split("\r\n") # go through each line, looking for signal strength found = False for one_line in all_lines: if ("Cell signal:" in one_line): found = True break if found: try: # strip leading whitespace clean_line = one_line.lstrip() # split the string into tokens separated by space tokens = clean_line.split(' ') # get the token before the / (e.g. 3/4) sig_tok = tokens[2].split('/') sig_str = int(sig_tok[0]) except ValueError: pass except IndexError: pass return sig_str def bars_to_dbm(bars): """ Converts cell modem signal strength from bars to dBm :param bars: sig str in bars, 0 to 4 :type bars: int :return: sig str in dBm :rtype: int """ rssi = 0 if bars == 1: rssi = 5 elif bars == 2: rssi = 13 elif bars == 3: rssi = 21 elif bars == 4: rssi = 28 db = rssi*2 - 113 return db @TXFORMAT def dga_format(txformat): """ This script provides DGA formatting for transmissions It is required that the system be setup for CSV formatting Example incoming TXform in CSV on SL3: 04/20/2017,19:55:00,PRECI,2.50,,G 04/20/2017,19:55:00,TAIRE,2.50,,G 04/20/2017,19:55:00,BATER,2.50,,G Expected TXform output from script: 'SELFTIMED ON UNIT: DGATEST DATE: 04/20/2017 TIME: 19:55:00 PRECI 2.50 G OK TAIRE 2.50 G OK BATER 2.50 G OK ' :param txformat: CSV string :return: reformat to DGA format requirements. :rtype: str """ # PC testing returns a False for scheduled reading and True when used on SL3 when scheduled. # This allows you to test code on PC and load it into SL3 without having to modify any code. if is_scheduled() == True: tx_format = command_line("!tx{} format".format(index()), 50).strip() if not ("CSV" in tx_format): raise SetupError("Wrong tx{} format setup. Change format to CSV.".format(index())) if is_being_tested(): # if tested on sl3 and txformat does not have legitimate value passed in, set to typical value if not (txformat.strip().split("/")[0].isdigit()): txformat = "\r\n05/12/2017,15:18:00,Temp,26.00,,G\r\n05/12/2017,15:18:00,Batt,12.51,,G\r\n\r\n" meas_list = txformat.strip().split("\r\n") st_name = command_line("!station name", 100).strip() m_date, m_time = meas_list[0].split(",")[:2] dga_form = "SELFTIMED ON UNIT: {} DATE: {} TIME: {}".format(st_name, m_date, m_time) # Iterating through all measurements in tx buffer and appending meas name, # value, and quality to dga formatted tx buffer for measurement in meas_list: fields = measurement.split(",") m_name, m_val = fields[2], fields[3] if m_val == "MISSING": dga_form += " {} {} OK ".format(m_name, m_val) else: m_qual = fields[5] dga_form += " {} {} {} OK ".format(m_name, m_val, m_qual) # signal strength sig_str = bars_to_dbm(cell_sig_str_bars()) # e.g. "SIGNAL 3 G OK " dga_form += " SIGNAL {} G OK ".format(sig_str) dga_form += " " return dga_form
fc10dd2e6bacc01aa1f752dafc9b47a2d989f55f
gurnit1/Python_Projects
/Practice of Computing Using Python/Facebook/Project07Facebook.py
3,223
3.890625
4
""" File of function stubs for Project 07 @author: enbody """ # Uncomment the following lines when you run the run_file tests # so the input shows up in the output file. # #import sys #def input( prompt=None ): # if prompt != None: # print( prompt, end="" ) # aaa_str = sys.stdin.readline() # aaa_str = aaa_str.rstrip( "\n" ) # print( aaa_str ) # return aaa_str # def open_file(): ''' Remember the docstring''' print("Please enter the file: ") fileName = input() file = open(fileName, "r") return file def read_file(fp): ''' Remember the docstring''' # Read n and initizlize the network to have n empty lists -- # one empty list for each member of the network n = fp.readline() n = int(n) network = [] for i in range(n): network.append([]) # You need to write the code to fill in the network as you read the file # Hint: append appropriate values to the appropriate lists. # Each iteration of the loop will have two appends -- why? for line in fp: list = line.split() network[int(list[0])].append(int(list[1])) network[int(list[1])].append(int(list[0])) return network def num_in_common_between_lists(list1, list2): ''' Remember the docstring''' set1 = set(list1) set2 = set(list2) return len(set1.intersection(set2)) def init_matrix(n): '''Create an nxn matrix, initialize with zeros, and return the matrix.''' matrix = [] for row in range(n): # for each of the n rows matrix.append([]) # create the row and initialize as empty for column in range(n): matrix[row].append(0) # append a 0 for each of the n columns return matrix def calc_similarity_scores(network): ''' Remember the docstring''' n = len(network) matrix = init_matrix(n) for i in range(n): for j in range(n): matrix[i][j] = num_in_common_between_lists(network[i], network[j]) return matrix def recommend(user_id,network,similarity_matrix): ''' Remember the docstring''' sList = similarity_matrix[user_id] #print(sList) max = -1 maxUser = -1 #print(network[user_id]) for i in range(len(sList)): existing = False if i == user_id: continue for j in network[user_id]: #print(str(i) + " " + str(j) + " " + str(sList[i]) + " " + str(max) + " " + str(maxUser)) if j == i: existing = True break if existing == False and sList[i] > max: max = sList[i] maxUser = i return maxUser def main(): # by convention "main" doesn't need a docstring file = open_file() network = read_file(file) matrix = calc_similarity_scores(network) while(True): print("Enter an integer in the range 0 to " + str(len(network) - 1) + ": ") num = int(input()) print("The suggested friend for " + str(num) + " is " + str(recommend(num, network, matrix))) print("Do you want to continue (yes/no)? ") resp = input() if(resp.lower() == "yes"): continue else: break if __name__ == "__main__": main()
e4ffbe461144747dfa9860c573eb700e23a2b4d7
arovit/Coding-practise
/dynamic_prog/magic_index.py
724
3.890625
4
#!/usr/bin/python def find_magic_index(array, start, end, mlist): print "start %s end %s "%(start, end) if not (start < end): return mindex = (end - start)/2 if mindex == 0: return else: mindex += start if array[mindex] > mindex: find_magic_index(array, start, mindex, mlist) elif array[mindex] < mindex: find_magic_index(array, mindex, end, mlist) else: mlist.append(mindex) find_magic_index(array, start, mindex, mlist) find_magic_index(array, mindex, end, mlist) array = map(int, raw_input("Enter the array ").strip().split(' ')) magic_list = [] find_magic_index(array, 0, len(array), magic_list) print magic_list
b78ba92d6fa9b2689ab326c7e01babc412c09622
ohadomrad/Examples
/ImagesWithKeras/ConvertImageWithKeras.py
1,074
3.625
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 3 08:25:53 2019 Use Keras img_to_array() function to convert a loaded image in PIL format into a Numpy array (for deep learning models). Use Keras array to img() function to convert a Numpy array of pixels data into a PIL image. In the example, load image, convert it to a Numpy array and then convert the array back into a PIL image @author: dina """ from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from keras.preprocessing.image import array_to_img import argparse ap = argparse.ArgumentParser() ap.add_argument('-i', '--image', required = True, help = "Path to the image") args = vars(ap.parse_args()) #load image img = load_img(args['image']) print("\img type ", type(img)) #convert image to numpy array img_array = img_to_array(img) print("\narray type ", img_array.dtype) print("\narray shape ", img_array.shape) # convert back to image img_pil = array_to_img(img_array) print("\n\nimg from numpy array type ", type(img_pil))
fb7935a3d1a600b40a4871e43a351b65bd0720a5
AmbujaAK/practice
/python/nptel-Aug'18/assg2.py
293
3.609375
4
def wellbracketed(s): depth = 0 for i in range(0,len(s)): if s[i] == '(': depth += 1 elif s[i] == ')': if depth > 0: depth -= 1 else : print('False') return depth == 0 s = input() wellbracketed(s)
2268b51b7c199f05fc84df48c7aeb5c4c287c075
Tinkotsu/geekbrains_hw
/task_3.py
957
3.703125
4
class Cell: def __init__(self, amount): self.amount = int(amount) def __add__(self, other): new = Cell(self.amount + other.amount) return new def __sub__(self, other): if self.amount - other.amount > 0: new = Cell(self.amount - other.amount) return new def __mul__(self, other): new = Cell(self.amount * other.amount) return new def __truediv__(self, other): if other.amount > 0: new = Cell(self.amount // other.amount) return new def make_order(self, n): if n > 0: res = '' rest = self.amount while rest > 0: if rest > n: res += '*' * n + '\n' else: res += '*' * rest rest -= n return res cell1 = Cell(10) cell2 = Cell(2) new_cell = cell1 * cell2 print(new_cell.make_order(3))
8f5ac614500148f59570dedbdb4f85b9ef46751a
benmaier/numpyarray_to_latex
/numpyarray_to_latex/utils.py
843
3.59375
4
""" Provide helper functions. """ import numpy as np def math_form(number, is_imaginary=False, mathform=True): r""" Convert a float number formatted in scientific notation to the corrsponding LateX format (e.g. ``2\times10^{2}``). """ if mathform: if 'e' in number: significand, exponent = number.split('e') if exponent.startswith('+'): exponent = exponent.lstrip('+') exponent = exponent.lstrip('0') elif exponent.startswith('-'): exponent = exponent.lstrip('-') exponent = exponent.lstrip('0') exponent = '-' + exponent if exponent != '': number = significand + '\\times 10^{'+ exponent + '}' else: number = significand return number
f8d8894f176c023e7b1ef58254c9a478a28949a6
starman011/python_programming
/02_Lists&tuples/03_pr_03.py
82
3.578125
4
#to check that a tuple value cannot be changes a = (1,2,4,56,3) a[0] = 45 print(a)
54aae5f25aafd50666df3443b80c4ecd8305ea1c
SafonovMikhail/python_000577
/001146StepikPyBegin/Stepik001146PyBeginсh09p01st07TASK06_20210125.py
760
3.984375
4
# str1 = input() str1 = 'abcdefghijklmnop' # for i in range(0, len(str1) - 1, 2): for i in range(0, len(str1) - 1, 2): print(str1[i]) ''' На вход программе подается одна строка. Напишите программу, которая выводит элементы строки с индексами 0, 2, 4, ... в столбик. Формат входных данных На вход программе подается одна строка. Формат выходных данных Программа должна вывести элементы строки с индексами 0, 2, 4, ..., каждое на отдельной строке. Sample Input: abcdefghijklmnop Sample Output: a c e g i k m o '''
b7f126427439c26b649ee20394aea79b937b2af0
egreen18/DegreeDesign
/modelclass.py
1,111
3.796875
4
#Class object for storing data on each class class Class(object): #Initilzation and attribute definition def __init__(self): self.program = '' self.title = '' self.credits = 0 self.description = '' self.prereqs = [] self.terms = [] #Method for loading stored data, called in loadJSON def load(self,JSON): self.program = JSON['program'] self.title = JSON['title'] self.credits = JSON['credits'] self.description = JSON['description'] self.prereqs = JSON['prereqs'] self.terms = JSON['terms'] #Catalog object for storing collections of classes class Catalog(object): #Method for easily grabbing the class names within a catalog def names(self): return list(self.__dict__.keys()) #College object for storing collections of catalogs class College(object): #Method for easily grabbing the catalog names within a college def names(self): return list(self.__dict__.keys()) class Semester(object): pass class Degree(object): pass
0e52fae02742566e5d8ce662c68b71d3ae7fb5ec
jaitul25/Triangle567
/TestTriangle.py
827
3.515625
4
import unittest from Triangle import classify_triangle class TestTriangles(unittest.TestCase): def testEquilateralTriangle1(self): self.assertEqual(classify_triangle(5,5,5),'Equilateral Triangle') def testEquilateralTriangle2(self): self.assertEqual(classify_triangle(7,7,7),'Equilateral Triangle') def testIsocelesTriangle3(self): self.assertEqual(classify_triangle(7,7,3),'Isosceles Triangle') def testIsocelesTriangle4(self): self.assertEqual(classify_triangle(5,7,7),'Isosceles Triangle') def testRightTriangle5(self): self.assertEqual(classify_triangle(3,4,5),'Right Angled Triangle') def testScaleneTriangleA(self): self.assertEqual(classify_triangle(7,8,9),'Scalene Triangle') if __name__ == '__main__': unittest.main()
9aaaf7ed305bfcdd73c288fc32f60a0d94eae08d
Textualize/textual
/src/textual/case.py
524
3.9375
4
import re from typing import Match, Pattern def camel_to_snake( name: str, _re_snake: Pattern[str] = re.compile("[a-z][A-Z]") ) -> str: """Convert name from CamelCase to snake_case. Args: name: A symbol name, such as a class name. Returns: Name in camel case. """ def repl(match: Match[str]) -> str: lower: str upper: str lower, upper = match.group() # type: ignore return f"{lower}_{upper.lower()}" return _re_snake.sub(repl, name).lower()
b69eb76a540a62c35230687927eef1aca6c77544
ayananygmetova/Web-Dev-2020
/week8/coding_bat/list-1.py
2,538
3.5625
4
<<<<<<< HEAD #first_last6 def first_last6(nums): if nums[0]==6 or nums[len(nums)-1]==6: return True else: return False #same_first_last def same_first_last(nums): if len(nums)==1: return True else: if len(nums)>1 and nums[0]==nums[len(nums)-1]: return True return False #make_pi def make_pi(): pi = [3,1,4] return pi #common_end def common_end(a, b): if a[len(a)-1]==b[len(b)-1] or a[0]==b[0]: return True return False #sum3 def sum3(nums): return nums[0]+nums[1]+nums[2] #rotate_left3 def rotate_left3(nums): nums = [nums[1], nums[2], nums[0]] return nums #reverse3 def reverse3(nums): nums = nums[::-1] return nums #max_end3 def max_end3(nums): maximum = max(nums[0],nums[2]) new_array = [maximum,maximum,maximum] return new_array #sum2 def sum2(nums): sum=0 if len(nums)==1: return nums[0] elif len(nums)==0: return 0 else: for i in range(2): sum+=nums[i] return sum #middle_way def middle_way(a, b): new_array = [a[1],b[1]] return new_array #make_ends def make_ends(nums): new_arr = [nums[0],nums[len(nums)-1]] return new_arr #has23 def has23(nums): if nums[0]==2 or nums[1]==2 or nums[0]==3 or nums[1]==3: return True ======= #first_last6 def first_last6(nums): if nums[0]==6 or nums[len(nums)-1]==6: return True else: return False #same_first_last def same_first_last(nums): if len(nums)==1: return True else: if len(nums)>1 and nums[0]==nums[len(nums)-1]: return True return False #make_pi def make_pi(): pi = [3,1,4] return pi #common_end def common_end(a, b): if a[len(a)-1]==b[len(b)-1] or a[0]==b[0]: return True return False #sum3 def sum3(nums): return nums[0]+nums[1]+nums[2] #rotate_left3 def rotate_left3(nums): nums = [nums[1], nums[2], nums[0]] return nums #reverse3 def reverse3(nums): nums = nums[::-1] return nums #max_end3 def max_end3(nums): maximum = max(nums[0],nums[2]) new_array = [maximum,maximum,maximum] return new_array #sum2 def sum2(nums): sum=0 if len(nums)==1: return nums[0] elif len(nums)==0: return 0 else: for i in range(2): sum+=nums[i] return sum #middle_way def middle_way(a, b): new_array = [a[1],b[1]] return new_array #make_ends def make_ends(nums): new_arr = [nums[0],nums[len(nums)-1]] return new_arr #has23 def has23(nums): if nums[0]==2 or nums[1]==2 or nums[0]==3 or nums[1]==3: return True >>>>>>> 02dce2f7d1883584c5b5f3cac5f0e37321f79bfe return False
049313910326e74c095b85d9be4b331db9de906c
pranaymate/PythonExercises
/ex040.py
354
4.09375
4
first = float(input('First score: ')) second = float(input('Second score: ')) grade = (first + second) / 2 print('Getting {} and {}, the final grade will be {}'.format(first, second, (first+second) / 2)) if grade >= 7: print('The student has passed!') elif 5 <= grade < 7: print('the student in recovery.') else: print('The student FAILED!')
0280579537e24b4a04d15821f3bf1687bf9e108c
HishamKhalil1990/math-series
/tests/test_series.py
1,756
3.71875
4
from math_series.series import fibonacci,lucas,sum_series def test_fibonacci(): expected = 3 input = 4 actual = fibonacci(input) assert actual == expected def test_lucas(): expected = 29 input = 7 actual = lucas(input) assert actual == expected def test_sum_series_fibonacci(): expected = 13 input = 7 actual = sum_series(input) assert actual == expected def test_sum_series_lucas(): expected = 7 input = 4 actual = sum_series(input,2,1) assert actual == expected def test_sum_series_other(): expected = 44 input = 5 actual = sum_series(input,3,7) # {0:3, 1:7, 2:10, 3:17, 4:27, 5:44, 6:71, 7:115, 8:186} assert actual == expected def test(): expected = { 'fibonacci-4':3, 'fibonacci-6':8, 'fibonacci-8':21, 'lucas-4':7, 'lucas-6':18, 'lucas-8':47, 'series_fibonacci-4':3, 'series_fibonacci-6':8, 'series_fibonacci-8':21, 'series_lucas-4':7, 'series_lucas-6':18, 'series_lucas-8':47, 'series_other-4':27, 'series_other-6':71, 'series_other-8':186, } actual = {} number = 4 for i in range(15): if i <= 2: actual[f"fibonacci-{number}"] = fibonacci(number) elif i <= 5: actual[f"lucas-{number}"] = lucas(number) elif i <= 8: actual[f"series_fibonacci-{number}"] = sum_series(number) elif i <= 11: actual[f"series_lucas-{number}"] = sum_series(number,2,1) else: actual[f"series_other-{number}"] = sum_series(number,3,7) if number == 8: number = 4 else: number += 2 assert actual == expected
1fc6bd6244d3d98b338b6b813103dfc00f16e75f
ararage/flask_python
/classes_objects.py
844
3.640625
4
lottery_player_dict = { 'name':'Rolf', 'numbers':(5,9,12,3,1,21) } class LotteryPlayer: def __init__(self,name): self.name = name self.numbers = (5,9,12,3,1,21) def total(self): return sum(self.numbers) player = LotteryPlayer("Rolf") player.numbers = (5,9,12,3,1,21) player2 = LotteryPlayer("John") #print (player.name) #print(player.total()) print(player.numbers == player2.numbers) class Student: def __init__(self,name,school): self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) @staticmethod def goToSchool(): print ("I'm going to school") anna = Student("Anna","MIT") anna.marks.append(56) anna.marks.append(16) print (anna.average()) print(Student.goToSchool())
d249827c01c6d14b04eb7bbdcfedbb82d9b16cf3
txqgit/LeetCode
/CodePython/DictTree/648_Replace Words.py
1,273
3.921875
4
class Node: def __init__(self, value=None): self.val = value self.is_leaf = False self.children = {} class Tire: def __init__(self): self.root = Node() def insert(self, word): node = self.root for w in word: if node.children.get(w, None) is None: node.children[w] = Node(w) node = node.children[w] node.is_leaf = True def search(self, word): node = self.root path = '' for w in word: if node.children.get(w, None) is None: return '' node = node.children[w] path += w if node.is_leaf: return path class Solution: def replaceWords(self, dict, sentence): tire = Tire() for word in dict: tire.insert(word) list_sentence = sentence.split(' ') ans = [] for word in list_sentence: cur = tire.search(word) if len(cur): ans.append(cur) else: ans.append(word) return ' '.join(ans) dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" solution = Solution() print(solution.replaceWords(dict, sentence))
5b23048fc9a3c5f30b3e073cd75f5b0f729c1424
FluffyTrooper2001/cp1404practicals
/prac_08/unreliable_car.py
543
3.5625
4
from car import Car import random class UnreliableCar(Car): def __init__(self, fuel, name, reliability): super().__init__(fuel, name) assert reliability <= 100 and reliability >= 0 self.reliability = reliability def drive(self, distance): rand_num = random.randint(0,100) if rand_num < self.reliability: return super().drive(distance) else: return 0 def __str__(self): return f"{super().__str__()}, reliability {self.reliability}"
2896c7146083aacfc259dfd52cbc1616ed40a325
HolyQuar/git_operation
/python_operation/datad_structures_2/list_expressions_nested_functions.py
1,157
4.03125
4
if __name__=='__main__': from math import pi pi_str=[str(round(pi,i)) for i in range(1,6)] print(pi_str) # Consider the following example of a 3x4 matrix # implemented as a list of 3 lists of length 4 matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] # transpose rows and columns transpose_matrix=[[row[i] for row in matrix ]for i in range(4)] print(transpose_matrix) print('---------------------------------------') transpose_equivalent=[] for i in range(4): transpose_equivalent.append([row[i] for row in matrix]) print(transpose_equivalent) transpose_equivalent_2 = [] for i in range(4): transpose_row=[] for row in matrix: transpose_row.append(row[i]) transpose_equivalent_2.append(transpose_row) print(transpose_equivalent_2) # prefer built-in functions to complex flow statements. # zip() zip_matrix=list(zip(*matrix)) print('zip_matrix',zip_matrix) l=[] for matrixs in zip_matrix: # tuple --> list list_r=list(matrixs) l.append(list_r) print('zip:',l)
f2d36b59287c059a82b84db89fbe511b89560368
Akashdeep-Patra/problemSolving
/Math/Points inside Rectangle.py
2,246
3.578125
4
""" Points inside Rectangle Problem Description You are given a rectangle with co-ordinates represented by arrays A and B, where the sides might not be parallel to the x-y axis. Given N points on x-y plane whose co-ordinates are represented by arrays C and D, count the number of points that lie strictly inside the rectangle. All the coordinates have integral values. Problem Constraints 1 <= N <= 102 -107 <= A[i], B[i], C[i], D[i] <= 107 Input Format First arguement is an interger array A of size 4 denoting the x co-ordinates of all the four corners of the rectangle. Second arguement is an interger array B of size 4 denoting the y co-ordinates of all the four corners of the rectangle. Third argument is an integer array C of size N denoting the x co-ordinates of all the N points. Fourth argument is an integer array D of size N denoting the y co-ordinates of all the N points. Output Format Return an single integer denoting the count of points that lies strictly inside the rectangle. Example Input Input 1: A = [0, -2, 2, 4] B = [0, 2, 6, 4] C = [1, 2, 1, 5, -3] D = [3, 4, 2, 5, 1] Example Output Output 1: 3 Example Explanation Explanation 1: Thus, rectangle has the coordinates (0,0), (-2,2), (2,6) and (4,4). We see points (1, 3), (2, 4), (1, 2) lies strictly inside the rectangle whereas (5, 5), (-3, 1) lies outside the rectangle """ def getArea(a,b,c): return abs((c[0]*(a[1]-b[1])+a[0]*(b[1]-c[1])+b[0]*(c[1]-a[1]))) def isInside(a,b,c,d,p): s=0 t=getArea(a,b,p) if(t==0): return False s+=t t=getArea(b,c,p) if(t==0): return False s+=t t=getArea(c,d,p) if(t==0): return False s+=t t=getArea(d,a,p) if(t==0): return False s+=t return s==getArea(a,b,c)+getArea(c,d,a) class Solution: # @param A : list of integers # @param B : list of integers # @param C : list of integers # @param D : list of integers # @return an integer def solve(self, a, b, c, d): ans=0 A=[a[0],b[0]] B=[a[1],b[1]] C=[a[2],b[2]] D=[a[3],b[3]] for i in range(len(c)): p=[c[i],d[i]] if(isInside(A,B,C,D,p)): ans+=1 return ans
f869200706bae4f16b595ec8aa6f55c60233e156
kostyantynHrytsyuk/py-garch
/arrays.py
4,442
4.0625
4
""" File : arrays.py An Abstract Data Type (ADT) for presenting a collection with fixed size """ import datetime import ctypes import pandas as pd class Array(object): def __init__(self, length, values=None): """ Constructor for array creates inner collection and initialize it with values if provided :param length: Size of collection :param values: Elements of collection """ assert length > 0, "Length of array must be > 0" self._len = length py_array = ctypes.py_object * length self._values = py_array() if values: if len(values) > length: raise Exception('Income data is too big') for i, v in enumerate(values): self._values[i] = v else: self.erase(None) def __len__(self): """ :return: the length of array """ return self._len def erase(self, stub): for i in range(self._len): self._values[i] = stub def __getitem__(self, index): """ :param index: position of element :return: element on position index """ assert 0 <= index < len(self), "Index out of range" return self._values[index] def __setitem__(self, index, value): """ Set value on position index in collection :param index: position of element :param value: new value at index """ assert 0 <= index < len(self), "Index out of range" self._values[index] = value def __iter__(self): """ :return: Iterator for collection """ return _ArrayIterator(self._values) class _ArrayIterator: def __init__(self, arr): """ Constructor for iterator for ADT. Initializes inner collection and sets current index :param arr: Array that will be iterated """ self._collection = arr self._current_position = 0 def __iter__(self): """ :return: Iterator for collection """ return self def __next__(self): """ :return: Next element in collection """ if self._current_position < len(self._collection): el = self._collection[self._current_position] self._current_position += 1 return el else: raise StopIteration class ArrayDateIndex(Array): """ ADT with possibility to index collection with dates """ def __init__(self, length, dates, values=None): """ Constructor for array creates inner collection and initialize it with values if provided. Also, initialize list to keep indices as dates and check if provided list with dates is the same size as array :param length: Size of collection :param dates: Sorted list with dates. Must be the same size as length :param values: Elements of collection """ assert len(dates) == length, "List with dates must be the same size as array" self._dates = dates super().__init__(length, values) def __getitem__(self, index): if type(index) == int: assert 0 <= index < len(self), "Index out of range" return self._values[index] elif type(index) == datetime.date: i = self._binary_date_search(0, len(self._dates), index) return self._values[i] else: raise Exception("Wrong index type!") def __setitem__(self, index, value): if type(index) == int: assert 0 <= index < len(self), "Index out of range" self._values[index] = value elif type(index) == datetime.datetime: i = self._binary_date_search(0, len(self._dates), index) self._values[i] = value else: raise Exception("Wrong index type!") def _binary_date_search(self, s, f, index): mid = (s+f)//2 curr = self._dates[mid] if curr < index: return self._binary_date_search(mid, f, index) elif curr > index: return self._binary_date_search(s, mid, index) else: return mid def to_pandas(self): data = {'Date': self._dates, 'Price': self._values} df = pd.DataFrame(data, columns=['Date', 'Price']) return df
f81d1b37817d00eba34b59a5e5efc9bef35dbb7e
AK-1121/code_extraction
/python/python_26620.py
126
3.609375
4
# Format a string with a space between every two digits s = "534349511" print ' '.join([s[i:i+2] for i in range(0,len(s),2)])
b48e1aac779c177c26d24a0cf311478b55bef812
sonbui00/HackerRank-Algorithms
/Warmup/plus_minus_test.py
466
3.671875
4
import unittest from plus_minus import plusMinus class TestSimpleArrayFunction(unittest.TestCase): def test_plus_minus(self): data = [ [6, [-4, 3, -9, 0, 4, 1], ['0.500000', '0.333333', '0.166667']] ] for item in data: self.assertEqual( item[2] ,plusMinus(item[0], item[1]) ,"Test plusMinus() with n = {0} and arr = {1}, expect return value is {2}" .format(item[0], item[1], item[2]) ) if __name__ == '__main__' : unittest.main()
dc57838e0bc565a41b975cfef11500ad7dc19ea8
SDSS-Computing-Studies/004d-for-loops-ssm-0123
/problem1.py
538
4.3125
4
#!python3 """ ###### Problem 1 Ask the user to enter in the width and height of a box. This should be an integer value less than 10 Draw a box filled with "*" symbols that matches the width and height. You will need 2 nested loops to draw the contents of 1 row and the number of rows. inputs: int number outputs: example: enter a number:4 **** **** **** **** """ while True: x = input("Enter a number") x = int(x) if x>10: break ran = range(1,x+1) for I in ran : print("*"*x) break
c1a4e5269a791e1fc2a928b2507f294e7f4ea8a7
deepakjoshishri/Movie-Website
/media.py
2,565
3.703125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # Parent class class Media: """ This class provides a way to store generic information related to media""" # documentation for base class def __init__(self, title, poster_image, genre, trailer_youtube): self.title = title self.poster_image_url = poster_image self.genre = genre self.trailer_youtube_url = trailer_youtube # Child class of Media class Movie(Media): """ This is an extenion of Media class that stores information related to movies specifically""" # documentation for child class which # inherits attributes of Media class as parent # Constructor for child class def __init__(self, title, poster_image, genre, youtube_trailer, duration, storyline, director, producer): # Calling parent class constructor super().__init__(title, poster_image, genre, youtube_trailer) self.duration = duration self.storyline = storyline self.director = director self.producer = producer # Child class of Movie class Anime(Movie): """ This is an extenion of Media class that stores information related to movies specifically""" # documentation for child class which inherits # attributes of My class as parent # Constructor for child class def __init__(self, title, poster_image, genre, youtube_trailer, duration, storyline, director, producer, no_of_seasons, importat_characters): # Calling Base class constructor super().__init__(title, poster_image, genre, youtube_trailer, duration, storyline, director, producer) self.no_of_episodes = no_of_episodes self.important_characters = important_characters # Child class of Media class TVShows(Media): """ This is an extenion of Media class that stores information related to movies specifically""" # documentation for child class which inherits # attributes of Media class as parent # Constructor for child class def __init__(self, title, poster_image, genre, youtube_trailer, no_of_episodes, storyline, director, producer): # Calling Base class constructor super().__init__(title, poster_image, genre, youtube_trailer) self.no_of_episodes = no_of_episodes
7c238959abf883312b033b8a08bab36f6d3dbd44
marcelo-py/Exercicios-Python
/exercicios-Python/dasaf075.py
567
3.765625
4
n1 = int(input('Digite um numero')) n2 = int(input('Digite outro número')) n3 = int(input('Mais um numro')) n4 = int(input('Agora o último numero')) lista = (n1, n2, n3, n4) print('os números digitados foram {}'.format(lista)) print('O número 9 apareceu {}x'.format(lista.count(9))) if 3 in lista: print('O numero 3 aparece primeiro na posição {}'.format(lista.index(3)+1)) else: print('O valor 3 não foi digitado nenhuma vez') print('Os valores pared digitados foram',end=' ') for n in lista: if n % 2 == 0: print('{}'.format(n),end=' ')
c2e3c6e9d82c193fd87f48a9ab04fdfc3d11a167
bala4rtraining/python_programming
/python-programming-workshop/pythondatastructures/while/pass.py
243
4.03125
4
import random def m(): # Get random number. n = random.randint(0, 3) print(n) # Return true if number is less than 3. return n <= 2 # Call method until it returns false. while m(): # Do nothing in the loop. pass
997740da26865460380ef16e0ab706e89440e9bd
PanagiotisSamios/Pythonexer
/Askisi_6.py
509
3.921875
4
import calendar calendar.setfirstweekday(calendar.SUNDAY) month = int(input('Give month in number ')) if month > 12 or month < 0: print ('not valid month') else: year = int(input('Give year ')) print ('\t', '\t', calendar.month_name[month], year, '\n') print ("S\tM\tT\tW\tT\tF\tS") calendar = calendar.monthcalendar(year, month) for i in range (len(calendar)): for j in range (7): if calendar[i][j] == 0: print ('\t', end='') else: print ( calendar[i][j],'\t', end='') print ('\n')
e1ad30ee912b198b04fba12066158921d22eb910
Yigang0622/LeetCode
/verifyPostorder.py
975
3.609375
4
# LeetCode # verifyPostorder # Created by Yigang Zhou on 2020/9/20. # Copyright © 2020 Yigang Zhou. All rights reserved. # 剑指 Offer 33. 二叉搜索树的后序遍历序列 # https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/ from typing import List class Solution: def verifyPostorder(self, postorder: List[int]) -> bool: print(postorder) return self.verify(postorder, 0, len(postorder) - 1) def verify(self, postorder, i, j): if i >= j: return True parent = postorder[j] print(postorder[i:j + 1], 'parent is', parent) m = i while postorder[m] < parent: m += 1 temp = m while temp < j: if postorder[temp] < parent: return False temp += 1 return self.verify(postorder, i, m-1) and self.verify(postorder, m, j - 1) postorder = [4,6,7,5] r = Solution().verifyPostorder(postorder) print(r)
6f330d23564fed43dbeb922543cb95796a0a1ae7
Sanchez-Antonio/python-learn-in-spanish
/colecciones/diccionarios.py
1,127
4.03125
4
#los diccionarios nos permiten además de almacenar cualquier tipo de valor # identificar cada elemento por una clave (Key). #Para definir un diccionario, se encierra el listado de valores entre llaves. # Las parejas de clave y valor se separan con comas, y la clave y el valor se separan con dos puntos. diccionario = {"ramón":1999,"jonny":2000,"alexis":2001,"luis":2000} print("a continuación las edades de mis amigos con su nombre:) -->") #con un for usando el metodo itemps recorre la clave y valor de cada objeto (key),(value) for key,value in diccionario.items(): print(key,value) #para mostrar el valor de una determinada clave --> diccionario["alexis"] #para cambiar el valor de una determinada clave diccionario["alexis"]=99 #borrar algúna clave con su valor del(diccionario["jonny"]) #se pueden usar operadores para trabajar valores (valor +=1) usando de referencia la clave diccionario["alexis"]+=1 #tambien se pueden sumar distintos valores de claves alexis + luis suma=diccionario["alexis"]+ diccionario["luis"] print(suma) #agregar diccionario dentro de una lista lista=[] lista.append(diccionario)
4544bba1424d1c381871ad48e51f5a390d74fd39
RP-Hall/harry-plotter
/src/Graph.py
4,289
3.59375
4
""" This is the class which represents a Graph object """ from parser import * import numpy as np class Graph: errorMsg = None def __init__(self, expr=None, filename=None, dim=None, xMin=None, xMax=None, yMin=None, yMax=None, plotType=None, lineType="Solid", opacity="additive", lineWidth=2, name = None, colString=None): """ Constructs the Graph object based on the source and stores the points. Can be constructed from expr or file. From expr: If dimension is given, then use that. Otherwise guess from expression. y=f(x) or f(x) is treated as 2D and self.points = [[],[]]. z=f(x,y) or f(x,y) is treated as 3D and self.points = [[],[], []]. From file: if first line contains 2 numbers, it is 2D if first line contains 3 numbers, it is 3D """ try: self.expr=expr self.filename=filename self.dim=dim if xMin != None: self.xMin=float(xMin) else: self.xMin=None if xMax != None: self.xMax=float(xMax) else: self.xMax=None if yMin != None: self.yMin=float(yMin) else: self.yMin=None if yMax != None: self.yMax=float(yMax) else: self.yMax=None self.plotType = plotType self.lineType=lineType self.opacity = opacity self.lineWidth=lineWidth self.colString = colString self.name = name if expr: self.source="expr" else: self.source="file" ## From expr if self.source=="expr": # If dimension is given, use that if dim: if dim == 2: self.points = data2D_generator(self.expr, self.xMin, self.xMax) elif dim == 3: self.points = data3D_generator(self.expr, self.xMin, self.xMax, self.yMin, self.yMax) else: self.points = None # Dimension is not given, try to guess from expression else: self.points = generateData(self.expr, self.xMin, self.xMax, self.yMin, self.yMax) # Error if self.points == None: self.errorMsg = "Oops!!Invalid expression" ## From File else: f = open(filename, "r") lines = f.read().splitlines() d = len(lines[0].split()) #Dimension from file if d == 2: lineNum=1 self.points=[[],[]] for line in lines: # Error if len(line.split()) != 2: f.close() self.errorMsg = "Error on line number " + str(lineNum) raise Exception() x=float(line.split()[0]) y=float(line.split()[1]) self.points[0].append(x) self.points[1].append(y) lineNum+=1 f.close() elif d == 3: lineNum=1 self.points=[[],[],[]] for line in lines: # Error if len(line.split()) != 3: f.close() self.errorMsg = "Error on line number " + str(lineNum) raise Exception() x=float(line.split()[0]) y=float(line.split()[1]) z=float(line.split()[2]) self.points[0].append(x) self.points[1].append(y) self.points[2].append(z) lineNum+=1 f.close() else: f.close() raise Exception() ## Some error except: self.points=None
718c40189800b016079665c375e55fef51b90fa1
rafaelmdurante/cs50pset
/psets/pset6/dna/dna.py
2,365
3.734375
4
# handle system args import sys # handle csv files import csv def main(): # validate args validate_args(sys.argv) # calculate short tandem repetitions match = find_match(sys.argv[1], sys.argv[2]) # print match print(match) def validate_args(args): # validate amount of args if len(args) < 3: print('Usage: python dna.py data.csv sequence.txt') sys.exit(1) def find_match(database_file, sequence_file): # get list of dicts as database database = get_database(database_file) # extract the short tandem repetitions based on the first dict # since they all have the same keys strs = get_strs(database[0]) # count strs inside a sequence strscounter = countstrs(strs, sequence_file) # find match for person in database: matchcounter = 0 for key in person: if key != 'name' and strscounter[key] == int(person[key]): matchcounter += 1 if matchcounter == len(strs): return person['name'] return 'No match' def get_database(file): # open file with open(file) as f: # open file as a dictionary reader = csv.DictReader(f) # start a list named database database = [] # iterate over the csv file for row in reader: database.append(row) return database def get_strs(dictionary): strs = [] for key in dictionary: if key != 'name' and key not in strs: strs.append(key) return strs def countstrs(strslist, sequence_file): # get sequence sequence = get_sequence(sequence_file) strsdict = {} for combination in strslist: # counter line counter = [0] * len(sequence) for i in range(len(sequence) - len(combination), -1, -1): j = i + len(combination) if sequence[i:j] == combination: if j >= len(sequence): counter[i] = 1 else: counter[i] = counter[j] + 1 strsdict[combination] = max(counter) return strsdict def get_sequence(file): # open file with open(file) as f: # get sequence and replace newline to nothing so it stores a string sequence = f.read().replace('\n', '') # return the sequence return sequence main()
b17fa0301cd45ffd97a23ba793da0ff18e8a196f
sum1t9/python-beginner
/exception handling.py
195
4.15625
4
while True: try: number = int(input("Enter a number :")) break except: print("You did not enter a number") print("Thank yor for entering a number")
b6ea536daa54288dd53f4a5a2841236cde8fdb18
rafaelperazzo/programacao-web
/moodledata/vpl_data/9/usersdata/134/4336/submittedfiles/crianca.py
398
3.734375
4
# -*- coding: utf-8 -*- from __future__ import division p1 = input('Digite o peso da criança da esquerda:') c1 = input('Digite o comprimento do lado esquerdo da gangorra:') p2 = input('Digite o peso da criança da direita:') c2 = input('Digite o comprimento do lado direito da gangorra:') if p1*c1==p2*c2: print('0') if (p1*c1)>(p2*c2): print('-1') elif (p2*c2)>(p1*c1): print('1')
d5dff22deadad0d9f8e1724e204f0e3da2c2fc00
nyowusu/ProgramFlow
/while_loops.py
1,171
4.03125
4
import random highest = 10 play = ['yes', 'Yes', 'y', 'Y'] # guess = int(input("Guess a number between 1 and {} ".format(highest).strip())) guessAgain = 'y' numGuess = 0 # while guess != answer: # if guess > answer: # guess = int(input("Guess lower than {} ".format(guess).strip())) # else: # guess = int(input("Guess higher than {} ".format(guess).strip())) # else: # print("Well done! You got it! ") while guessAgain in play: answer = random.randint(1, highest) numGuess = 0 print(answer) guess = int(input("Guess a number between 1 and {} ".format(highest).strip())) if guess == answer: print("Well done! You guessed it the first time! ") else: numGuess += 1 while guess != answer: if guess > answer: guess = int(input("Guess lower than {} ".format(guess).strip())) elif guess < answer: guess = int(input("Guess higher than {} ".format(guess).strip())) numGuess += 1 print("Well done! You guessed it after {} try(ies) ".format(numGuess)) guessAgain = input("Do you want to guess a different number? y/n ")
f0c412a342d408369528ac7177748dae06b3e772
trevisanj/aleatools
/aleatools/scripts/text2png.py
2,969
3.703125
4
#!/usr/bin/env python """ Converts text to PNG image Creates specially to convert ASCII monospace diagrams to PNG image Based on gist: https://gist.github.com/destan/5540702 """ from PIL import ImageFont from PIL import Image from PIL import ImageDraw import argparse import sys import os def text2png(lines, fullpath, color ="#000", bgcolor ="#FFF", fontfullpath = None, fontsize = 13, padding = 3, box=False, boxcolor="#008080", boxwidth=3): # REPLACEMENT_CHARACTER = u'\uFFFD' # NEWLINE_REPLACEMENT_STRING = ' ' + REPLACEMENT_CHARACTER + ' ' font = ImageFont.load_default() if fontfullpath is None else ImageFont.truetype(fontfullpath, fontsize) # #prepare linkback # linkback = "created via http://ourdomain.com" # fontlinkback = ImageFont.truetype('font.ttf', 8) # linkbackx = fontlinkback.getsize(linkback)[0] # linkback_height = fontlinkback.getsize(linkback)[1] # #end of linkback line_height = font.getsize(lines[0])[1] img_height = line_height * len(lines) + 2*padding + (0 if not box else 2*boxwidth) img_width = max([font.getsize(x)[0] for x in lines])+2*padding + (0 if not box else 2*boxwidth) img = Image.new("RGBA", (img_width, img_height), bgcolor) draw = ImageDraw.Draw(img) y = padding + (0 if not box else boxwidth) for line in lines: draw.text( (padding + (0 if not box else boxwidth), y), line, color, font=font) y += line_height if box: for i in range(boxwidth): draw.rectangle((i, i, img_width-i-1, img_height-i-1), None, boxcolor) # # add linkback at the bottom # draw.text( (width - linkbackx, img_height - linkback_height), linkback, color, font=fontlinkback) img.save(fullpath) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Convert text file to PNG') parser.add_argument('-f', type=str, help='Font filename (e.g. "FreeMono.ttf"). See PIL docs for how PIL finds the font filename', required=False) parser.add_argument('-s', type=int, default=12, help='Font size (default: 12). Ignored if no font filename is specified', required=False) parser.add_argument('-p', type=int, default=4, help='Padding (default: 4)', required=False) parser.add_argument('-b', action="store_true", help="Draws box around") parser.add_argument('input', type=str, nargs=1, help='Input filename') parser.add_argument('output', type=str, default="(automatic)", nargs="?", help='Output filename') args = parser.parse_args() fn_input = args.input[0] fn_output = args.output if fn_output == "(automatic)": fn_output = os.path.splitext(fn_input)[0]+".png" print("Output filename: {}".format(fn_output)) with open(fn_input, "r") as file: lines = file.readlines() lines = [x.replace("\n", "") for x in lines] # sys.exit() text2png(lines, fn_output, fontfullpath=args.f, fontsize=args.s, padding=args.p, box=args.b)
126c4328120ea3dabd21940487431903c7ecd3e9
bilge-gocer/simple_python_projects_from_pycharm
/factors.py
308
4.1875
4
# Count factorial numbers in a given range def factorial(num): result = 1 for x in range(1, num + 1): result = result * x return result number1 = int(input("Enter a number: ")) number2 = int(input("Enter another number: ")) for n in range(number1, number2): print(n, factorial(n))
2eaaab2b0eb23e31f1a3575fa0e4a34d424599b2
uoayop/study.algorithm
/baekjoon/15953.py
975
3.578125
4
#15953 상금헌터 import sys def f1_money(a): if (a==1): return f1[0] elif (a==2 or a==3): return f1[1] elif (4<=a and a<=6) : return f1[2] elif (7<=a and a<=10) : return f1[3] elif (11<=a and a<=15) : return f1[4] elif (16<=a and a<=21): return f1[5] else: return 0 def f2_money(a): if (a==1): return f2[0] elif (a==2 or a==3): return f2[1] elif (4<=a and a<=7) : return f2[2] elif (8<=a and a<=15) : return f2[3] elif (16<=a and a<=31) : return f2[4] else: return 0 f1= [5000000,3000000,2000000,500000,300000,100000] f2= [5120000,2560000,1280000,640000,320000] T = int(sys.stdin.readline().rstrip()) for i in range(0,T): money = 0 order = sys.stdin.readline().rstrip().split() a = int(order[0]) b= int(order[1]) money = f1_money(a)+f2_money(b) print(money)
698c03f0dde6490c074ffb09f82bec197504e09e
maumneto/IntroductionComputerScience
/CodeClasses/SequentialCodes/cod2.py
336
3.75
4
nome = input('Entre com o nome: ') matricula = int(input('Entre com a matrícula: ')) curso = input('Entre com o seu curso: ') idade = int(input('Entre com a sua idade: ')) email = input('Digite seu email: ') print('Nome: ', nome) print('matrícula: ', matricula) print('Curso: ', curso) print('Idade: ', idade) print('Email: ', email)
2edc16b0f632eb27070c07134a14f7cdadf5389d
AozzyA/homeCode
/boolean.py
690
3.96875
4
import ast # This is a boolean parser. It handles the following expressions # True and True X # True or True X # True and False X # True or False X # False and False X # False or True X # False and True X # False or False X userTyped = input('Enter a boolean experession.').strip() words = userTyped.split(' ') a = words[1] t1 = ast.literal_eval(words[0].title()) t2 = ast.literal_eval(words[2].title()) if a ==('or'): print('or') if t1 or t2: print('True') else: print('False') else: print('and') if t1 and t2: print('True') else: print('False') #if t1 and t2: # print("true1") #elif t1 or t2: # print("true2")
25f5b6f75e54838581efa34faa2afac035c4b42a
LowerDeez/python-cookbook
/memory_management_in_cyclic_data_structures(tree).py
4,331
3.859375
4
from typing import List, Dict, Optional import weakref """ A simple example of a cyclic data structure is a tree structure where a parent points to its children and the children point back to their parent. For code like this, you should consider making one of the links a weak reference using the weakref library. For example: """ class Node: def __init__(self, id_: int, title: str, parent_id: Optional[int]): self.id = id_ self.title = title self.parent_id = parent_id self._parent = None self.children = [] def __repr__(self): return 'Node(id={!r:}, title={!r:})'.format(self.id, self.title) def __iter__(self): return iter(self.children) def __len__(self): return len(self.children) # property that manages the parent as a weak-reference @property def parent(self): return self._parent if self._parent is None else self._parent() @parent.setter def parent(self, node_: Node): self._parent = weakref.ref(node_) def add_child(self, node_: Node): self.children.append(node_) node_.parent = self class Tree: def __init__(self, items: List[Dict]) -> None: self.nodes = [] for item in items: self.create_node(item) self.populate_children() def __iter__(self): return iter(self.nodes) def __len__(self): return len(self.nodes) def create_node(self, item: Dict) -> Node: """ Create `Node` instance from `Dict` """ n = Node( id_=item.get('id'), title=item.get('title'), parent_id=item.get('parent_id') ) self.nodes.append(n) return n def populate_children(self) -> None: """ Populates children for all nodes """ for n in self.nodes: children = filter(lambda x: x.parent_id == n.id, self.nodes) for child in children: n.add_child(child) @staticmethod def descendants(n: Node) -> List: """ All child nodes and all their child nodes. """ children = n.children.copy() # first variant stack = [children] while stack: children = stack[-1] if children: child = children.pop(0) yield child if child.children: stack.append(child.children) else: stack.pop() # second variant # for child in children: # yield child # children.extend(n.children) @staticmethod def ancestors(n: Node) -> List: """ All parent nodes and their parent nodes - see :any:`ancestors`. """ parents = [] node_ = n while node_: node_ = node_.parent parents.insert(0, node) # parents.append(node) return parents @staticmethod def children(n: Node) -> List: """ All child nodes. """ return n.children def root(self, n: Node) -> Optional[int]: """ Tree Root Node. """ ancestors = self.ancestors(n) return ancestors[0] if ancestors else [] # return ancestors[-1] if ancestors else [] data = [ {'id': 1, 'title': 'Category #1', 'parent_id': None}, {'id': 2, 'title': 'Category #2', 'parent_id': None}, {'id': 3, 'title': 'Category #3', 'parent_id': 1}, {'id': 4, 'title': 'Category #4', 'parent_id': 2}, {'id': 5, 'title': 'Category #5', 'parent_id': 3}, {'id': 6, 'title': 'Category #6', 'parent_id': 4}, {'id': 7, 'title': 'Category #7', 'parent_id': 6}, {'id': 8, 'title': 'Category #8', 'parent_id': 5}, {'id': 9, 'title': 'Category #9', 'parent_id': 5} ] tree = Tree(items=data) if __name__ == '__main__': print(tree.nodes) for node in tree.nodes: print(node) print(node.children) # solver.ancestors(5) # [3, 1] # solver.descendants(2) # [4, 6, 7] # solver.children(6) # [7] # solver.root(8) # 1 # print('Children for 6:', solver.children(6)) # print('Root for 8:', solver.root(8)) # print('Ancestors for 5:', solver.ancestors(5)) # print('Descendants for 2:', solver.descendants(2))
92d6a460fd63bb187d94fff02a4ced14f657656f
founek2/python
/docs/_lessons/lesson4/uniq.py
421
4
4
# that takes a list and returns a new list with unique elements of the first list def uniq(list): values = [] for x in list: if x not in values: values.append(x) return values assert uniq([1, 2, 3]) == [1, 2, 3] assert uniq([10, 10, 3]) == [10, 3] assert uniq([10, 2, 10]) == [10, 2] assert uniq([15, 5, 0, -3, 2, 1, -1, 0, 0, 0, 0]) == [15, 5, 0, -3, 2, 1, -1] assert uniq([]) == []