blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
441a34fbc020396140ba93ca743e0efd7355fe78
efrigo88/Python-Course-Udemy
/01. HelloWorld/sequence_operators.py
405
3.546875
4
string1 = 'He\'s ' string2 = 'probably ' string3 = 'pining ' string4 = 'for the ' string5 = 'fjords' print(string1 + string2 + string3 + string4 + string5) print() print('Hello ' * 5) print('Hello ' * (5 + 4)) print('hello ' * 5 + '4') print() today = 'friday' print('fri' in today) # True print('day' in today) # True print('thurs' in today) # False print('pika' in 'pokemon') # False
11a4aad1e6eeebaa62e4e54d3a32b26eec9119ee
joekreatera/math-integration
/RiemannTest.py
987
3.890625
4
#riemann rest for integration def linear(x): return x def quadratic(x): return x*x def riemannIntegration(fn,a,b,n): integrationTotal = 0 base = (b-a)/n halfBase = base/2 for i in range(0,n): integrationTotal = integrationTotal + fn(i*base+halfBase) return (integrationTotal*base) print("Riemann test!") totalIntegration= riemannIntegration(quadratic , 0, 3, 1) print("Riemann result 1 " , totalIntegration ) totalIntegration= riemannIntegration(quadratic , 0, 3, 2) print("Riemann result 2" , totalIntegration ) totalIntegration= riemannIntegration(quadratic , 0, 3, 3) print("Riemann result 3" , totalIntegration ) totalIntegration= riemannIntegration(quadratic , 0, 3, 4) print("Riemann result 4" , totalIntegration ) totalIntegration= riemannIntegration(quadratic , 0, 3, 5) print("Riemann result 5" , totalIntegration ) totalIntegration= riemannIntegration(quadratic , 0, 3, 100) print("Riemann result 100" , totalIntegration )
b541bcbff56bcc0ed07b5d5f4d4940c4b3e35e86
jinyoungch0i/Flask-Development
/flaskblog17.py
9,219
3.703125
4
def line_break(x): print(str(x) + '---------' + str(x) + '---------' + str(x) + '---------' + str(x) + '---------') lb = line_break ''' ~appendix * this is the seventeenth note on building a python flask application * ~lb(0): note on flask debug tool ~lb(1): custom validator for already taken username & email ~lb(2): installing & initialising flask_login and LoginManager ~lb(3): working with flask-login / LoginManager / UserMixin ''' #____________from previous flask notes (+ modification)____________ from flaskblog import app if __name__ == '__main__': app.run(debug=True) #_________________________end of app code_________________________ lb(0) # now, if you go back to your application, # there is actually something wrong with how you have this right now # that might not be obvious right off the bat. # currently, your RegistrationForm() will validate against fields such as bad emails and empty fields # but there is nothing stopping a user from trying to sign up with a username or email # that already exists in your database. # now you have a restriction set on your database model that say that those have to be unique # but that won't be caught or throw an error until you try to add that new user to the database. # let's see what it would look like # if you try to add another user or email that currently already exists # upon signing up again with the exact same credentials: ''' sqlalchemy.exc.IntegrityError sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: user.email (Background on this error at: http://sqlalche.me/e/13/gkpj) ''' # n.b you get this ugly error screen when flask throws an error and you're in debug mode # this information can be extremely useful when debugging problems in your application, # but this is also why you want to be absolutely sure # that you're never running on debug mode when deploy your website publicly # because this is just too much information that you'd expose to other people. # you can actually come to the bottom of the stack trace # and run python code to dig further into the problem. # and you need the debugger pin from your console to do this, # but it's still risky having that possibility. # i.e. never run your code in debug mode when deploying the website to the public. lb(1) # now, you might think that it be best to go into the register route in routes.py # and add in some database checks after the form was validated # to see if username/email already exists in your database. # that would be one way to do it. # but the best way to do it is to add your own custom validation for RegisterForm(). # that way, it get's checked when you actually validate the form # and will return the visual feedback like the error messages like you've seen before. # so, how do you do this? #(information from the wtforms documentation) # open up your forms.py file # and within RegistrationForm class: ''' class RegistrationForm(FlaskForm): username = StringField('Username', validators=[ DataRequired(), Length(min=2, max=20)]) email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[ DataRequired(), Length(min=8, max=20)]) confirm_password = PasswordField('Confirm Password', validators=[ DataRequired(), Length(min=8, max=20), EqualTo('password')]) submit = SubmitField('Sign Up') ''' # and, below submit, you can create a custom validation simply by creating the function: ''' [1] def validate_field(self, field): [2] if True: [3] raise ValidationError('Validation Message') ''' # what you created here is bascially a template for your validation methods. #[1]: in this format, you're going to validate_fieldname*(self, fieldname*) # fieldname* being whatever field you want to validate, #[2]: this just says if True for now, but you'll add in some kind of conditional. #[3]: if it meets that condition, then it can raise a validation error with a validation message. # this will be more clear once you customise it to your needs. # let's do that now: # you want to validate the username field: ''' [1] def validate_username(self, username): ''' # and the condition that you want to check # is whether or not the user already exists in the database # 0: from flaskblog.models import User # and now you can query whether the username submitted to the form # is already in your database by: ''' [2] user = User.query.filter_by(username=username.data).first() ''' # whereby username.data is coming from the username field of the form # and .first() is to just return the first value that you get from the database # so if there *is* a value, you'll get the first one. # if there isn't a user, you'll be returned None. # now you can change your conditional to something that you'd want to throw a ValidationError ''' [3] if user: [4] raise ValidationError('Validation Message') ''' # i.e. if this user exists, # then you'd want to throw the ValidationError # basically if user is None, it won't hit this conditional and raise the error, # but if the user is anything other than None, it would throw the error. # now the validation message is what gets sent to the form # and you want to be specific so that the user already knows what is going wrong: ''' [4] raise Validation Error('Username already exists') ''' # so, here is the validation_field all stiched up: ''' from wtforms.validators import ValidationError from flaskblog.models import User class RegistrationForm(FlaskForm): ''' ''' def validate_username(self,username): user = User.query.filter_by(username=username.data).first() if user: raise ValidationError('Username already exists') ''' # now that should give an error when a username is already taken # let's do the same validation check for if email is already stored in the database too: ''' def validate_email(self,email): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('Email already exists') ''' # simply by adding in these custom validators will solve your problem # and catch that before throwing an ugly error that you saw before in flaskblog16. # let's go back and reload your webserver # and check to see the validation checks in action! lb(2) # so you now have a pretty good registration system. # now you need to create your login system so that # your users who have created accounts can log in and log out. # to do this, you're going to be using another flask extension # called flask-login. # flask-login extension makes it really easy to manage user sessions. # first install it via pip/pipenv/etc. # then, add it to the __init__.py file like you've done with other extensions: ''' from flask_login import LoginManager ''' # and now, create an instance of the LoginManager class (login_manager = LoginManager(app)) # with all that, you are now able to use this login_manager in your application. lb(3) # the way that this works is that you add some functionality to the database models # and then it would handle all of the sessions in the background for you. # so open up models.py and import the login_manager instance #(which comes from the same place as the db instance; i.e. add login_manager to this line of import) # and now you need to add a function with a decorator @userloader # and this is for reloading the user from the user_id store in the session # it's just one thing you need to put in place for the extension to work. #(because the extension has to know how to find one of your users via id) # let's create this function load_user # which takes user_id as an argument # and then you can return the user for that user_id* # casting that user_id into an integer just to be sure. # and penultimately, decorate the function so that # the extension knows that this is the function to get a user by an id # heeding the '@login_manager.user_loader' naming convention. ''' @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) ''' # and there is one more thing that you have to do: # the extension will expect your User db.Model to have certain attributes and methods. # it's going to expect four to be exact: # one is called 'is_authenticated' # which will return True if user provided valid credentials # another is called 'is_active' # another is called 'is_anonymous' # and last one is a method called get_id() # now, you could add all of these yourself, # but this is so common that the extension provides a simple class that you can inherit from # that would add all of these attributes and method for you. # you can simply import this class from flask_login (in models.py), # and this class is called UserMixin. # and then in the User db.Model, you can just pass in UserMixin as the second argument (i.e inherit from it): ''' class User(db.Model, UserMixin): ''' #so that should be all you need to do with your flask_login extension #in order for it to manage your session for you. # # # # # # # # # # # # # # # # continue onto flaskblog18.py # # # # # # # # # # # # # # # #
cfb1b1562e75fe76678c81b6413110e3a79e4ee9
ballib/Forritun1
/Æfingaverkefni1/dæmi2.py
138
4
4
x = int(input("Enter a integer: ")) y = int(input("Enter another integer: ")) f = int(input("Enter another ineger: ")) z = x+y+f print(z)
0fad4a31f8b05b8ade59552813354372774783c4
DominiDeliya/pythonExamples
/find_duplicates_2.py
163
3.640625
4
seq = [2,3,2,-1,5,3,-1,3] seq.sort() counter = 0 seen = '' for elm in seq: if elm == seen: counter += 1 else: seen = elm print(counter)
8aef2bd6df0bac803fee802b35a34abde016eef4
veikkoEF/TkInterWithPython
/3_Button2.py
544
3.96875
4
from tkinter import * from tkinter import messagebox # Event-Definition def button_action(): messagebox.showinfo(message="Eine Meldung", title = "Infos") # Ein Fenster erstellen window = Tk() # Den Fenstertitle erstellen window.title("Hello World") # Definition von GUI-Elementen button = Button(window, text="OK", command=button_action, width="130") label = Label(window, text="Ein Label") # Hinzufügen der Elemente zum Fenster button.pack() label.pack() # Ereignisschleife auf Reaktion des Benutzers warten. window.mainloop()
84eba9e631285d50764e75a060a4167fe6a1e184
henriquelorenzini/EstruturasDeDecisao
/Exercicio05.py
819
4.28125
4
#Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar: #A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; #A mensagem "Reprovado", se a média for menor do que sete; #A mensagem "Aprovado com Distinção", se a média for igual a dez. print('Veja se você foi aprovado ou não') nota1 = float(input('Digite sua primeira nota: ')) nota2 = float(input('Digite sua segunda nota: ')) media = (nota1 + nota2)/2 if media >= 7.00 and media < 10: print('Sua média foi {:.1f} e você está aprovado!'.format(media)) elif media < 7: print('Sua média foi {:.1f} e você está reprovado!'.format(media)) elif media == 10: print('Sua media foi {:.1f} e você foi aprovado com distinção'.format(media))
5a56e6b393b6431fda9770256116edcec097be31
JAYESH-ALAGH/Study_Assist_App
/speech__recognition.py
1,248
3.5625
4
def speech_to_text(): from subprocess import call import speech_recognition as sr import os, time r= sr.Recognizer() text = {} text1 = {} def listen1(): with sr.Microphone(device_index = 2) as source: r.adjust_for_ambient_noise(source) #print("Say Something"); audio = r.listen(source) #print("got it"); return audio def voice(audio1): try: text1 = r.recognize_google(audio1) ## call('espeak '+text, shell=True) #print ("you said: " + text1); return text1; except sr.UnknownValueError: return "Sorry! Could not understand\nPlease try again" except sr.RequestError as e: return "Please check your Internet connection" audio1 = listen1() text = voice(audio1) return text text = {} ''' if __name__ == '__main__': while True: audio1 = listen1() text = voice(audio1) return if text == 'hello': text = {} print("hi") else: print("could not detect")'''
1bcaf7963ecc9cf352d74d3c901be84690cc69c2
dstruiksma/advent_of_code
/2020/py/day3.py
895
3.921875
4
def main(): f = open("/home/detmer/programming/aoc/2020/aoc_input/input_day3.txt", "r") snowslope = [] for line in f: snowslope.append(line) print("Product of amount of trees of all slopes:", traverse(1,1,snowslope) * traverse(3,1,snowslope) * traverse(5,1,snowslope) * traverse(7,1,snowslope) * traverse(1,2,snowslope)) def traverse(step,jump,snowslope): snowslope = snowslope pos = step step = step jump = jump started = False trees = 0 start = 0 for row in snowslope: if started: if row[pos] == '#': trees+=1 if pos+step > 30: pos+=step remainder = pos - 31 pos = remainder else: pos+=step if jump == 2: started = False elif jump == 1: started = True elif jump == 2: if start == 1: started = True; start = 0 start+=1 print("Amount of trees:", trees) return trees if __name__ == '__main__': main()
2c7f5d37f6858a4540abd8d4ab5ba26f569a7670
deep2612/Simple-Linear-Regression
/SimpleLRGradientDescent.py
2,722
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 5 17:33:13 2020 @author: deep """ import pandas as pd import numpy as np import matplotlib.pyplot as plt def gradientDescent(alpha, X, Y, ep = 0.0001, max_iter = 5000): print('Gradient Descent Model Begins : ') converged = False iter = 0 #m = X.shape #print(m) t0 = 0 #np.random.random(X.shape[1]) t1 = 1 #np.random.random(X.shape[1]) print('t0 : ', t0 ,', t1 :', t1) #Total Error J = sum([( t0 + t1*X[i] - Y[i] )**2 for i in range (X.size) ]) print('Initial Error J(theta) : ', J) while not converged: #computing gradient (d/d_theta J(theta)) for each training sample grad0 = 1.0/X.size * sum([( t0 + t1*X[i] - Y[i] ) for i in range (X.size)]) grad1 = 1.0/X.size * sum([( t0 + t1*X[i] - Y[i] )*X[i] for i in range (X.size)]) #Updating theta_temp temp0 = t0 - alpha*grad0 temp1 = t1 - alpha*grad1 #updating theta t0 = temp0 t1 = temp1 #mean_squared_error E = sum([( t0 + t1*X[i] - Y[i] )**2 for i in range (X.size) ]) #print('Mean_Squared Error : ', E) if (J-E) <= ep: print('Final Error : ', E) print('Converged at Iteration : ', iter) converged = True J = E #print(J) iter = iter + 1 if(iter == max_iter): print('Maximum Iterations Reached') converged = True return t0,t1 alpha = float(input("Enter the value for alpha (Learning Rate) : ")) #Reading the test and training dataset training_dataset = pd.read_csv('train.csv') test_dataset = pd.read_csv('test.csv') #Cleaning the Datasets clean_training_set = training_dataset.dropna() clean_test_set = test_dataset.dropna() X = np.array(clean_training_set.iloc[:, :-1].values) #print(X) Y = np.array(clean_training_set.iloc[:, 1].values) #print(Y) X_test = np.array(clean_test_set.iloc[:, :-1].values) Y_test = np.array(clean_test_set.iloc[:, 1].values) #calling the gradient_descent function and getting the intercepts theta0 and theta1 theta0, theta1 = gradientDescent(alpha, X, Y) print('Final theta0 :', theta0 ,', theta1 ; ', theta1) for i in range (X.size): Y_train_predict = theta0 + theta1*X #Visualizing Training Set plt.scatter(X, Y, color = 'red') plt.plot(X, Y_train_predict, color = 'blue') plt.title('Size Of House vs Price (Train set)') plt.xlabel('Size Of House') plt.ylabel('Price') plt.show() for i in range (X_test.size): Y_test_predict = theta0 + theta1*X_test #Visualizing Test Set plt.scatter(X, Y, color = 'red') plt.plot(X_test, Y_test_predict, color = 'blue') plt.title('Size Of House vs Price (Test set)') plt.xlabel('Size Of House') plt.ylabel('Price') plt.show()
11f36bef818b389ba90496742f0ed601dff502a3
loopDelicious/csinterviews
/pramp/merging.py
1,185
3.71875
4
""" Merging 2 Packages Given a package with a weight limit and an array arr of item weights, how can you most efficiently find two items with sum of weights that equals the weight limit? Your function should return 2 such indices of item weights or -1 if such pair doesn't exist. What is the runtime and space complexity of your solution? >>> sorted(merging(10, [-10, 10, 20, 15, 6])) [0, 2] """ def merging(limit, arr): """ find 2 items with sum of weights that equals the weight limit """ # Brute Force O(n^2) # for i in range(len(arr)): # for j in range(len(arr)): # if arr[i] + arr[j] == limit: # return [i, j] # # return -1 # Make a hash table to keep track of what we've seen O(n) weight_dict = {} for i in range(len(arr)): if arr[i] not in weight_dict: weight_dict[arr[i]] = i target = limit - arr[i] if target in weight_dict and i != weight_dict[target]: return [i, weight_dict[target]] return -1 if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. WAY TO GO!\n"
480ba8c83ed6ad387e4a50142dd14da48200bd81
moinox80/cm2110-2021-coursework-arctic-flunkies
/run_window_old.py
2,476
3.59375
4
import window as w import Weather_api as wa import window_mechanism as wm import curtain as c import os import csv window = w.Window() api = wa.WeatherApi() window_mechanism = wm.WindowMechanism() curtain = c.Curtain() with open('user_data.txt', mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) line_count = 0 for row in csv_reader: line_count += 1 if line_count < 1: preferred_temp = int(input("Welcome to MyWindow, please input your preferred home temperature: ")) window.set_preferred_temperature(preferred_temp) else: line_count = 0 for row in csv_reader: if line_count == 0: line_count += 1 window.set_preferred_temperature(row["temp"]) api.set_city(row["city"]) line_count += 1 while True: print(" [Time]") print("-=" + curtain.get_time() + "=-") if curtain.run_curtain() == 1: print("Curtains are currently opened") elif curtain.run_curtain() == 0: print("Curtains are currently closed") dashboard = input("-=MyWindow=- \n[1] Run window \n[2] Check weather \n[3] Open window \n[4] Close window \n[5] Change city and preferred temperature \n[6] Close app\n") if dashboard == "1": window.window_work() elif dashboard == "2": print(api.get_weather_data()) elif dashboard == "3": window_mechanism.open_window() elif dashboard == "4": window_mechanism.close_window() elif dashboard == "5": f = open('user_data.txt', 'r+') f.truncate(0) f.close() city = input("Please input your city: ") temp = int(input("Please input the your preferred temperature: ")) api.set_city(city) window.set_preferred_temperature(temp) with open('user_data.txt', mode='w') as csv_file: fieldnames = ['city'] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() writer.writerow({'city': api.get_city()}) print("Changes saved, please restart the program") break elif dashboard == "6": with open('user_data.txt', mode='w') as csv_file: fieldnames = ['city'] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() writer.writerow({'city': api.get_city()}) break
3e3b39f2a8e78dfd142a60dc496da8026dae2504
Krebbet/work2vec_workshop
/xxxx_code.py
10,260
3.703125
4
def build_dataset(words, n_words): """Process raw inputs into a dataset. This function will 1) count the number of occurances of each word 2) collect the n_words most common words 3) give each word a unique number id """ ''' words -> the corpus of words... n_words -> number of words to track ''' # setup a count list each entry has ['word',number of occurances] # for infrequent words we label them UNK for unknown count = [['UNK', -1]] # this collects the n_words most common words and counts their occurances count.extend(collections.Counter(words).most_common(n_words - 1)) # we give each word in count a numerical id. # ie. we are creating our word conversion key. dictionary = dict() for word, _ in count: dictionary[word] = len(dictionary) data = list() # We move through our corpus and convert the words into # their index values in data. # --> we also use this pass through the data to count our # 'unknown' entries unk_count = 0 for word in words: if word in dictionary: index = dictionary[word] else: index = 0 # dictionary['UNK'] unk_count += 1 data.append(index) # save our unknown cound count[0][1] = unk_count # create a reverse lookup table. reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) return data, count, dictionary, reversed_dictionary data_index = 0 # generate batch data def generate_batch(data, batch_size, num_skips, skip_window): global data_index assert batch_size % num_skips == 0 assert num_skips <= 2 * skip_window batch = np.ndarray(shape=(batch_size), dtype=np.int32) context = np.ndarray(shape=(batch_size, 1), dtype=np.int32) span = 2 * skip_window + 1 # [ skip_window input_word skip_window ] buffer = collections.deque(maxlen=span) for _ in range(span): buffer.append(data[data_index]) data_index = (data_index + 1) % len(data) for i in range(batch_size // num_skips): target = skip_window # input word at the center of the buffer targets_to_avoid = [skip_window] for j in range(num_skips): while target in targets_to_avoid: target = random.randint(0, span - 1) targets_to_avoid.append(target) batch[i * num_skips + j] = buffer[skip_window] # this is the input word context[i * num_skips + j, 0] = buffer[target] # these are the context words buffer.append(data[data_index]) data_index = (data_index + 1) % len(data) # Backtrack a little bit to avoid skipping words in the end of a batch data_index = (data_index + len(data) - span) % len(data) return batch, context data_index = 0 # generate batch data def generate_batch(data, batch_size, num_skips, skip_window): ''' From our corpus generate context-target pairings... data : the word corpus in index form. batch_size: num_skips: number of words drawn from the window used as context words. skip_window: The length of the context window to be drawn upon. ''' global data_index assert batch_size % num_skips == 0 assert num_skips <= 2 * skip_window # define our batch array? batch = np.ndarray(shape=(batch_size), dtype=np.int32) # define our context array... context = np.ndarray(shape=(batch_size, 1), dtype=np.int32) span = 2 * skip_window + 1 # [ skip_window input_word skip_window ] # create a buffer of length [total context size, widnow length *2 + the target word.] # fill with 'span words from position data_index' # note: deque objects work as a ring buffer, when an item # is added onto to the end and max length has been reached # it pushes out the first item and adds the new item to the end. buffer = collections.deque(maxlen=span) for _ in range(span): buffer.append(data[data_index]) data_index = (data_index + 1) % len(data) for i in range(batch_size // num_skips): target = skip_window # input word at the center of the buffer # no duplicates allowed targets_to_avoid = [skip_window] # create num_skip pairs of target word -> context word. for j in range(num_skips): # grab a random context word from the window while target in targets_to_avoid: target = random.randint(0, span - 1) targets_to_avoid.append(target) batch[i * num_skips + j] = buffer[skip_window] # this is the input word context[i * num_skips + j, 0] = buffer[target] # these are the context words # move the buffer down the line buffer.append(data[data_index]) data_index = (data_index + 1) % len(data) # Backtrack a little bit to avoid skipping words in the end of a batch data_index = (data_index + len(data) - span) % len(data) return batch, context # this is all essentially what they have provided through the database.... # the model they present # these will be defined in the yaml file... batch_size = 128 embedding_size = 128 # Dimension of the embedding vector. skip_window = 1 # How many words to consider left and right. num_skips = 2 # How many times to reuse an input to generate a context. learning_rate = 1.0 ##################################################################### ############# Define Model ########################################## # here we have the place holders... train_inputs = tf.placeholder(tf.int32, shape=[batch_size]) train_context = tf.placeholder(tf.int32, shape=[batch_size, 1]) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # Define our embedding matrix. embeddings = tf.Variable( tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0)) #partition out the word representations in 'train_inputs' embed = tf.nn.embedding_lookup(params = embeddings, ids = train_inputs) ''' tf.nn.embedding_lookup( params, -> our embedding matrix ids, --> the id of the words we want to pull... partition_strategy='mod', name=None, validate_indices=True, max_norm=None ) ''' # Define a single hidden layer weights = tf.Variable(tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) biases = tf.Variable(tf.zeros([vocabulary_size])) # propogate... hidden_out = tf.matmul(embed, tf.transpose(weights)) + biases # convert train_context to a one-hot format train_one_hot = tf.one_hot(train_context, vocabulary_size) # get cross - entropy loss ---> this normalizes over entire corpus of words cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=hidden_out, labels=train_one_hot)) # Define your optimization function ( tf will take care of the backprop. optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) # Compute the cosine similarity between minibatch examples and all embeddings. norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True)) normalized_embeddings = embeddings / norm valid_embeddings = tf.nn.embedding_lookup(normalized_embeddings, valid_dataset) similarity = tf.matmul(valid_embeddings, normalized_embeddings, transpose_b=True) ################################################################### ### Define NCE Model ################################################################### nce_weights = tf.Variable( tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) nce_biases = tf.Variable(tf.zeros([vocabulary_size])) nce_loss = tf.reduce_mean( tf.nn.nce_loss(weights=nce_weights, biases=nce_biases, labels=train_context, inputs=embed, num_sampled=num_sampled, num_classes=vocabulary_size)) optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(nce_loss) ##################################################################### ############# Train Model ########################################## with tf.Session(graph=graph) as session: # We must initialize all variables before we use them. init.run() print('Initialized') average_loss = 0 for step in range(num_steps): # grab batch data batch_inputs, batch_context = generate_batch(data, batch_size, num_skips, skip_window) # define the input placeholders for training. feed_dict = {train_inputs: batch_inputs, train_context: batch_context} # Run a training step (ill redefine this how me likes. _, loss_val = session.run([optimizer, cross_entropy], feed_dict=feed_dict) average_loss += loss_val # print out training loss if step % 2000 == 0: if step > 0: average_loss /= 2000 # The average loss is an estimate of the loss over the last 2000 batches. print('Average loss at step ', step, ': ', average_loss) average_loss = 0 # check the similarity ratings! # Note that this is expensive (~20% slowdown if computed every 500 steps) if step % 10000 == 0: sim = similarity.eval() for i in range(valid_size): valid_word = reverse_dictionary[valid_examples[i]] top_k = 8 # number of nearest neighbors nearest = (-sim[i, :]).argsort()[1:top_k + 1] log_str = 'Nearest to %s:' % valid_word for k in range(top_k): close_word = reverse_dictionary[nearest[k]] log_str = '%s %s,' % (log_str, close_word) print(log_str) final_embeddings = normalized_embeddings.eval()
9c5e5c2470e4a8f3552d242e1c870ed065f8f170
makutene/python
/projectEuler_32.py
807
3.828125
4
#We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. #The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. #Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. #HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. def isPan(num): n=[int(i) for i in str(num)] m=sorted(n) if n[0]!=0 and m==[x for x in range(1,10)]: return True else: return False def prods(): while True: comp=str(prod)+str(a)+str(b) if len(str(comp))<=9 and isPan(comp):
929cd6e9da8fea824ec872d7a2e59a2bc95b0d75
Kiranshankarbhat007/Python-basic-
/print_N_no.py
123
3.984375
4
n = int(input("enter a number up to which u want to print:")) def n_no(n): for i in range (n): print i n_no(n)
da1c289f46adeebe25290cacbd974ab4423e558a
renatolaq/Python-Design-Paterns
/testa_conta.py
14,632
4.09375
4
import abc from datetime import datetime from abc import ABC, abstractmethod class Cliente(ABC.abc): def __init__(self): pass @abc.abstractmethod def teste_abstract(self): pass class Transacao: def gera_transacao(self, dt, operacao, valor): a = 0 return {'data': dt, 'operacao': operacao, 'valor': valor} # Desconta todas tarifas na conta class Tarifas: def Deposito(self, valor): return valor * 0.01 def Transferencia(self, valor): return valor * 0.02 def Saque(self, valor): return valor * 0.005 class ContaBanco: # Aqui insere atributos globais quantidade = 0 def data_atual(self): now = datetime.now() return now.strftime("%d/%m/%Y %H:%M:%S") def __init__(self): self.contas = [] self.extrato = [] self.hora_atual = [] ContaBanco.quantidade # utilizado em treinamento def conta_saldo(self): print("===================================================") print("BANCO ACME - CONSULTA SALDOS " + self.data_atual()) print("=================================================== ") print("") selecao = input("INFORME SUA CONTA ") for info in self.contas: agencia = info['agencia'] conta = info['conta'] nome = info['nome'] saldo = info['saldo'] limite = info['limite'] saldo_total = info['saldo_total'] if selecao == conta: print("") print("") print("===================================================") print("BANCO ACME - CONSULTA SALDOS " + c.data_atual()) print("=================================================== ") print("AGENCIA " + agencia + "/" + conta) print(nome.upper()) print("=================================================== ") print("SALDO DISPONIVEL R$ " + "{:.2f} ".format(saldo)) print("LIMITE CREDITO R$ " + "{:.2f} ".format(limite)) print("SALDO TOTAL R$ " + "{:.2f} ".format(saldo_total)) print("=================================================== ") input("PRESSIONE < ENTER > PARA CONTINUAR") print("") print("") def conta_extrato(self): print("===================================================") print(" BANCO ACME - EXTRATO CONTA " + self.data_atual()) print("=================================================== ") print("") selecao = input("INFORME SUA CONTA ") chave = 0 for info in self.contas: agencia = info['agencia'] conta = info['conta'] nome = info['nome'] saldo = info['saldo'] limite = info['limite'] transacao = info['transacao'] if selecao == conta: print("") print("") print("===================================================") print("BANCO ACME - DEPOSITO EM CONTA - " + self.data_atual()) print("=================================================== ") print("AGENCIA " + agencia + "/" + conta) print(nome.upper()) print("=================================================== ") print(" EXTRATO DE MOVIMENTAÇÕES") print("=================================================== ") if len(transacao) == 0: print(" *** NÃO EXISTE MOVIMENTAÇÕES NA CONTA ***") else: for registro in transacao: print(registro['data'] + " " + registro['operacao'] + " " + "{:.2f} ".format(registro['valor'])) print("") print("=================================================== ") print("SALDO DISPONIVEL R$ " + "{:.2f} ".format(saldo)) print("LIMITE CREDITO R$ " + "{:.2f} ".format(limite)) print("SALDO TOTAL R$ " + "{:.2f} ".format(saldo + limite)) print("=================================================== ") print("") input("PRESSIONE < ENTER > PARA CONTINUAR") print("") print("") return chave += 1 input("CONTA NAO IDENTIFICADA < ENTER > PARA CONTINUAR") def conta_deposito(self): print("===================================================") print(" BANCO ACME - DEPOSITO CONTA " + self.data_atual()) print("=================================================== ") print("") selecao = input("INFORME SUA CONTA ") chave = 0 for info in self.contas: agencia = info['agencia'] conta = info['conta'] nome = info['nome'] saldo = info['saldo'] limite = info['limite'] if selecao == conta: print("") print("") print("===================================================") print("BANCO ACME - DEPOSITO EM CONTA - " + self.data_atual()) print("=================================================== ") print("AGENCIA " + agencia + "/" + conta) print(nome.upper()) print("=================================================== ") print("SALDO DISPONIVEL R$ " + "{:.2f} ".format(saldo)) print("=================================================== ") deposito = input("INFORME VALOR DEPOSITO ") valor_deposito = float(deposito) # calcula a tarifa sobre o deposito valor_tarifa = Tarifas.Deposito(self, valor_deposito) saldo_atualizado = saldo + float(deposito) - valor_tarifa print("=================================================== ") print("SALDO ANTERIOR R$ " + "{:.2f} ".format(saldo)) print("VALOR DEPOSITO R$ " + "{:.2f} ".format(valor_deposito)) print("SALDO ATUAL R$ " + "{:.2f} ".format(saldo_atualizado)) print("=================================================== ") # atualiza saldo da conta self.contas[chave]['saldo'] = saldo_atualizado self.contas[chave]['saldo_total'] = saldo_atualizado + limite # Gravar a Transacao registro = Transacao.gera_transacao(self, self.data_atual(), "(+) DEPOSITO ", valor_deposito) registrot = Transacao.gera_transacao(self, self.data_atual(), "(-) TAR DEPO ", valor_tarifa) self.contas[chave]['transacao'].append(registro) self.contas[chave]['transacao'].append(registrot) a = 0 input("PRESSIONE < ENTER > PARA CONTINUAR") print("") print("") return chave += 1 input("CONTA NAO IDENTIFICADA < ENTER > PARA CONTINUAR") def conta_saque(self): print("===================================================") print(" BANCO ACME - SAQUE CONTA - " + self.data_atual()) print("=================================================== ") print("") selecao = input("INFORME SUA CONTA ") chave = 0 for info in self.contas: agencia = info['agencia'] conta = info['conta'] nome = info['nome'] saldo = info['saldo'] limite = info['limite'] if selecao == conta: print("") print("") print("===================================================") print("BANCO ACME - SAQUE CONTA - " + self.data_atual()) print("=================================================== ") print("AGENCIA " + agencia + "/" + conta) print(nome.upper()) print("=================================================== ") print("SALDO DISPONIVEL R$ " + "{:.2f} ".format(saldo)) print("=================================================== ") saque = input("INFORME VALOR SAQUE ") # VALIDAR O VALOR DO SAQUE valor_saque = float(saque) saldo_mais_limite = saldo + limite autoriza = self.autoriza_saque(valor_saque, saldo_mais_limite) if autoriza: valor_tarifa = Tarifas.Saque(self, valor_saque) saldo_atualizado = saldo - float(valor_saque) - float(valor_tarifa) print("=" * 50) print("SALDO ANTERIOR R$ " + "{:.2f} ".format(saldo)) print("VALOR SAQUE R$ " + "{:.2f} ".format(valor_saque)) print("SALDO ATUAL R$ " + "{:.2f} ".format(saldo_atualizado)) print("=================================================== ") # atualiza saldo da conta sa = self.ajusta_saldo_saque(valor_saque, saldo, limite) self.contas[chave]['saldo'] = sa['saldo'] self.contas[chave]['limite'] = sa['limite'] self.contas[chave]['saldo_total'] = sa['saldo'] + sa['limite'] # Gravar a Transacao registro = Transacao.gera_transacao(self, self.data_atual(), "(-) SAQUE ", valor_saque) registrot = Transacao.gera_transacao(self, self.data_atual(), "(-) TAR SAQ.", valor_tarifa) self.contas[chave]['transacao'].append(registro) self.contas[chave]['transacao'].append(registrot) a = 0 input("PRESSIONE < ENTER > PARA CONTINUAR") print("") print("") return else: input("SAQUE NÃO AUTORIZADO < ENTER > PARA CONTINUAR") return chave += 1 input("CONTA NAO IDENTIFICADA < ENTER > PARA CONTINUAR") def autoriza_saque(self, valor_saque, saldo_mais_limite): if valor_saque > saldo_mais_limite: return False else: return True # make debit saldo and after make debit on limit and returns values updated {'saldo' 0.00, 'limite': 0,00} def ajusta_saldo_saque(self, valor_saque, saldo, limite): # ajust saldo if saldo >= valor_saque: saldo = saldo - valor_saque else: diferenca = valor_saque - (saldo + limite) saldo = diferenca * -1 limite = limite - diferenca return {'saldo': saldo, 'limite': limite} def gerar_contas(self): conta1 = {'agencia': '0001', 'conta': '00001-1', 'nome': 'Renato Pereira', 'cpf': '11707899860', 'saldo': 1000.0, 'limite': 0.0, 'saldo_total': 1000.0, 'data_abertura': '02/10/2019 10:41:10', 'transacao': [{'data': '01/10/2019 10:11:54', 'operacao': 'DEPOSITO INICIAL', 'valor': 1000.0}], 'cadastro': [{'cpf': '11707899860', 'rg': '21967629', 'telefone': '1146395855'}]} conta2 = {'agencia': '0001', 'conta': '00002-2', 'nome': 'Aline Blasco', 'cpf': '43061665897', 'saldo': 1000.0, 'limite': 0.0, 'saldo_total': 1000.0, 'data_abertura': '02/10/2019 10:41:10', 'transacao': [{'data': '01/10/2019 10:11:54', 'operacao': 'DEPOSITO INICIAL', 'valor': 1000.0}], 'cadastro': [{'cpf': '43061668597', 'rg': '21963222', 'telefone': '1146395855'}]} self.contas.append(conta1) self.contas.append(conta2) return self.contas def conta_lista(self): print("===================================================") print("BANCO ACME - CONTAS ATIVAS - " + self.data_atual()) print("=================================================== ") print("") for conta in self.contas: print(conta['agencia'] + "/" + conta['conta'] + " CPF " + conta['cpf'] + " " + conta['nome']) print("") input("PRESSIONE < ENTER > PARA CONTINUAR") def conta_abertura(self): print("") print("") print("===================================================") print("BANCO ACME - ABERTURA DE CONTAS " + self.data_atual()) print("=================================================== ") print("") input("PRESSIONE < ENTER > PARA CONTINUAR") if __name__ == '__main__': c = ContaBanco() con = c.gerar_contas() acao = True while acao == True: print("===================================================") print("BANCO ACME - ABC " + c.data_atual()) print("=================================================== ") print(" MENU CLIENTE") print("=================================================== ") print(" 0 - VERIFICAÇÃO SALDO ") print(" 1 - DEPOSITOS ") print(" 2 - SAQUE ") print(" 3 - TRANSFERENCIAS ") print(" 4 - EXTRATO CONTA") print("=================================================== ") print(" MENU ADMINISTRATIVO") print("=================================================== ") print(" 5 - LISTAGEM DE CONTAS ATIVAS ") print(" 6 - ABERTURA DE CONTAS") print(" 7 - LIBERA LIMITE CREDITO") print(" 8 - DADOS CADASTRAIS CLIENTE") print(" 99 - SAIR DO SISTEMA ") print("===================================================") escolha = input("OPÇÃO DESEJADA ") print("") if escolha == '': continue elif int(escolha) == 0: c.conta_saldo() elif int(escolha) == 1: c.conta_deposito() elif int(escolha) == 2: c.conta_saque() elif int(escolha) == 4: c.conta_extrato() elif int(escolha) == 5: c.conta_lista() elif int(escolha) == 6: c.conta_abertura() elif int(escolha) == 99: acao = False
a9167b55354e4c0d30089e443114125d413662a4
Brian-Ckwu/discrete-mathematics
/1_mathematical_thinking_in_computer_science/n_queens.py
1,593
3.796875
4
""" Finding the solutions to the N Queens problem (place n queens on a n*n chess board): 1. Brute-force search 2. Backtracking """ import itertools # 1. Brute-force search # Time complexity: O(n^2) (n == length of perm) def is_solution(perm: tuple) -> bool: for i1, i2 in itertools.combinations(range(len(perm)), 2): if abs(i1 - i2) == abs(perm[i1] - perm[i2]): return False return True # Time complexity: O(n^2 * n!) def brute_force_search(n: int) -> list: solutions = list() for perm in itertools.permutations(range(n)): # O(n!) if is_solution(perm): # O(n^2) solutions.append(perm) return solutions # 2. Backtracking method def is_sub_solution(sub_sol: list) -> bool: for i1, i2 in itertools.combinations(range(len(sub_sol)), 2): if abs(i1 - i2) == abs(sub_sol[i1] - sub_sol[i2]): return False return True def extend(perm: list, n: int, solutions: list) -> None: if len(perm) == n: solutions.append(perm) # extend the permutation for i in range(n): if i not in perm: perm.append(i) if is_sub_solution(perm): extend(perm, n, solutions) perm.pop() def back_track_search(n: int) -> list: solutions = [] extend(perm=[], n=n, solutions=solutions) return solutions if __name__ == "__main__": max_n = 10 for i in range(1, max_n + 1): solutions = back_track_search(i) # much faster than brute_force_search print(f"The number of solutions of n={i}: {len(solutions)}")
b2cb44e2cd287d580eefd56466a95326ca7e8923
calick/pythonSample
/基礎/問題/case_0003/case_0003.py
113
3.71875
4
# coding: UTF-8 num=25 if(num>=10): print("Bye") else: print("Hi") if(num>=25): print("Konnichiha")
6cc547ac909ca081aaac7232451c21dfd9cada3e
Asunqingwen/LeetCode
/简单/有效的山脉数组.py
1,031
3.8125
4
''' 给定一个整数数组 A,如果它是有效的山脉数组就返回 true,否则返回 false。 让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组: A.length >= 3 在 0 < i < A.length - 1 条件下,存在 i 使得: A[0] < A[1] < ... A[i-1] < A[i] A[i] > A[i+1] > ... > A[A.length - 1]     示例 1: 输入:[2,1] 输出:false 示例 2: 输入:[3,5,5] 输出:false 示例 3: 输入:[0,3,2,1] 输出:true   提示: 0 <= A.length <= 10000 0 <= A[i] <= 10000  ''' from typing import List class Solution: def validMountainArray(self, arr: List[int]) -> bool: len_ = len(arr) i = 0 while i < len_ - 1 and arr[i] < arr[i + 1]: i += 1 if i == len_ - 1 or i == 0: return False while i < len_ - 1 and arr[i] > arr[i + 1]: i += 1 return i == len_ - 1 if __name__ == '__main__': arr = [0, 3, 2, 1] sol = Solution() print(sol.validMountainArray(arr))
07cae87fa7fe78e70b04f3195e92838379e012f1
neilbaruwati/Python
/python_basic_programs/class3_1.py
3,473
4.03125
4
x = True print ("The initial state of x: ", x) print("The type of x:", type(x)) x = not x print("after not operation and assignment, the state x is",x) x = 3 y = 4 print ("x=",x,"y=",y) print("x==y returns", x==y) print("x!=y returns",x!=y) print("x>y returns", x>y) print("x<y returns", x<y) print ("x>=y returns",x>=y) print("x<=y returns",x<=y) number = 2 if (number ==1): print("one") elif (number==10): print("ten") elif number==20: print("twenty") else: print("we are not looby for this value") list_a = [1,2,3] list_b = [1,2,3] list_c = [4,5,6] print (list_a == list_b) print (list_a !=list_c) name = "justin" print(len(name)) print (len(name)==6) print(50%2==0) bag = [10,123,12443] for item in bag: print item for item in bag: if item==10: print("yeah!") i=10 while i<11: print("yup") i=i+1 numerator=12 denominator=2 if denominator!=0: print(numerator/denominator) else: print("division by zero not allowed") grade = 44 if grade>=90: lettergrade="A" elif grade >=80: lettergrade = "B" elif grade >= 70: lettergrade = "C" elif grade >=60: lettergrade = "D" else: lettergrade = "F" print lettergrade for name in ("jane","john","matt"): print name for i in [1,2,3,4,5,6,7,8,9,10]: print i #TO PERFORM TASK REPEATEDLY name = raw_input("please enter your name: ") age = input("How old are you, {0}?".format(name)) print "okay, your age is {0}.".format(age) if age>=18: print("you are old enough to vote") print ("please put an x in the box") else: print("please come back in {0} years".format(18-age)) print ("please guess a number between 1 and 10!!") guess = int(input()) if guess<5: print("Please guess higher") guess = int(input()) if guess == 5: print("well done") else: print("you are not good") elif guess>5: print("Please guess lower") guess = int(input()) if guess == 5: print("well done") else: print("sorry, you have not guessed correctly") else: print ("you got it first time.") x = False if x: print ("x is true") """ print ('''False:{0} None:{1} 0:{2} 0.0:{3} empty_list[]:{4} empty_tuple():{5}.format(False,bool(name),bool(0))) """ for i in range(1,120): print ("i is now {0}".format(i)) for i in range(1,13): for j in range (1,13): print("{1} times {0} is {2}".format(i,j,i*j)) """print ("==========================",end='\t') """ shopping_list = ["milk","pasta","eggs","spam","bread","rice"] for item in shopping_list: print ("Buy " + item) """ if item == "spam": continue print ("Buy " + 2 + item) """ ip_address = "225.12.12.0" x = ip_address.split(".") print x if int(x[0])<=255 and int(x[1])<=255 and int(x[2])<=255 and int(x[3])<=255: print "IP address is a valid one" number = "9,223,372,036,854,775,007" for i in range (0,len(number)): print number[i] number = "9,223,372,036,854,775,007" for i in range(0,len(number)): if number[i] in '0123456789': print number[i] number = "9,223,372,036,854,775,807" cleanednumber = '' for char in number: if char in '0123456789': cleanednumber = cleanednumber + char newnumber = int(cleanednumber) print ("the number is {}".format(newnumber))
9b762b7494e73b596d6f991f56d04624b3e43a93
rodrigueslopesantosdev/FirstRestApiPython
/Data control/Funcoes.py
812
4.03125
4
#funcoes.py #Usando funções como parametro de tupla #no exemplo abaixo o parâmetro valores é uma tupla # # def nomeFuncao (*valores): return valores #FUNÇÃO map(funcao_definida, lista_elementos) # ## def exponencial(base, expo): return base**expo elementos = [1,2,3] ''' lista = map(exponencial, elementos) print (lista) #FUNÇÃO reduce(funcao, sequencia) # def soma(val1, val2): return val1+val2 #LIST Comprehensions soma = [x**2 for x in [1,2,3,4]] print (soma) soma = [(x,x**2) for x in range(6)] print (soma) valores = ((2,3), (6,7), (10,11)) soma = [a*b for (a,b) in valores] print (soma) ''' def fatorial(numero): if (numero == 1 or numero == 0): return 1 return numero*fatorial(numero-1) fat = fatorial (6) print ("Fatoria de 6 é: " + str(fat))
2499ef1e100a94c09acaec67dcff658d908a362b
forgetbear/B_PYTHON_GIS
/PythonForArcGIS/SF_PFA2/ch12/script/argPrint.py
222
3.921875
4
# argPrint.py # Purpose: Print args with built-in 'enumerate' function. # Usage: Any arguments. # Example input: 500 miles import sys for index, arg in enumerate(sys.argv): print 'Argument {0}: {1}'.format(index, arg)
9befa5ae7272957fdbdc3f0e7b8d4e5927e767d4
kapokjyz/python
/06_if_else.py
720
4.03125
4
# 条件判断,是自动化必不可少的部分,根据不同的情况做出不同的选择 age = 20 if age >= 18: print('adult') elif age >= 6: print('teenager') else: print('kid') # if 判断条件可以简写 # if x: # print('True') # 只要x是非零数值,非空字符串,非空list等,就判断为True,否则为False # input()函数返回的是str类型 age = input('please enter you age: ') # 下面这样直接判断就会报错,因为str类型不能直接和整数比较,需要把str转换成整数 # if age >= 70: age = int(age) if age >= 70: print('old age') # str类型转换成int类型时,只能是数字形式的字符串,如果是别的则不合法,会报错
4c84817608b7845b2cb7f5f358ad4a0654011d2e
JaleelAhmed/Python-Advanced
/oops/Override.py
395
3.875
4
class User: name = "" def __init__(self, name): self.name = name def printName(self): print "Name = " + self.name class Programmer(User): def __init__(self, name): self.name = name def printName(self): print "NameProgrammer = " + self.name brian = User("Srinivas") brian.printName() diana = Programmer("Kolaparthis") diana.printName()
a08e7accbd7bc36c25830996418bb6c447b24147
KennethJHan/Bioinformatics_101
/P045.py
605
3.59375
4
import sys def Mer(n, arr1, arr2): if n == 1: return arr2 else: arr_tmp = [] for i in arr1: for j in arr2: arr_tmp.append(i+j) arr2 = arr_tmp n -= 1 return Mer(n, arr1, arr2) def isPalindrome(s): l = 0 h = len(s)-1 while(h > l): if(s[l] != s[h]): return False l += 1 h -= 1 return True n = 7 arr1 = ["A", "C", "G", "T"] arr2 = ["A", "C", "G", "T"] ret = Mer(int(n), arr1, arr2) ret2 = [] for s in ret: if(isPalindrome(s)): ret2.append(s) print(ret2)
0163f956a3e9df34577abe09b7a713c36be053bd
usako1124/teach-yourself-python
/chap10/ex_10_1.py
417
3.515625
4
class Pet: def __init__(self, kind, name): # __new__ じゃなくて __init__ self.kind = kind self.name = name def show(self): # self が必要? print(f'わたしのペットは{self.kind}の{self.name}ちゃんです!') if __name__ == '__main__': # app じゃなくて main p = Pet('ハムスター', 'のどか') # new いらない p.show() # -> じゃなくて .
5e1ecdc93e4be6302458de50017e7b40e5244a2b
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/sttjos003/mymath.py
316
4.125
4
def get_integer (x): y=input("Enter " + x + ":\n") while not y.isdigit(): y=input("Enter " + x + ":\n") x=eval(y) return (x) def calc_factorial (x): i=1 y=x while i<y: x=x*i i=i+1 return (x)
fd98b583d33e9e9dbdd9698a937d716a30d1d219
Aadil101/mini-solar-system
/body.py
1,315
3.640625
4
#body.py #Aadil Islam #February 8, 2018 from cs1lib import * class Body: # body constructor def __init__(self, mass, x, y, vx, vy, pixel_radius, r, g, b): self.mass = mass # for body movement self.x = x self.y = y self.vx = vx self.vy = vy # for drawing body self.pixel_radius = pixel_radius self.r = r self.g = g self.b = b def update_position(self, timestep): # new_x = initial_x + velocity * time self.x = self.x + timestep * self.vx self.y = self.y + timestep * self.vy def update_velocity(self, timestep, ax, ay): # new_velocity = initial_velocity + acceleration * time self.vx = self.vx + timestep*ax self.vy = self.vy + timestep*ay def draw(self, cx, cy, pixels_per_meter): # paintbrush and paint for body disable_stroke() set_fill_color(self.r, self.g, self.b) # body's coordinates originate not from (0,0) but from (200,200) --> (cx,cy) # instance variables x and y describe deviation away from this new origin # but x and y are two large! must convert via multiplying by pixels_per_meter draw_circle(cx + self.x * pixels_per_meter, cy + self.y * pixels_per_meter, self.pixel_radius)
63b3c5c2aebc94321bcd96af57763feb25645de6
davide-butera/data-analysis-with-python
/part02/part02-e04_word_frequencies/src/word_frequencies.py
548
3.859375
4
#!/usr/bin/env python3 def word_frequencies(filename="src/alice.txt"): with open(filename, 'r') as content_file: dictionary = {} for line in content_file: content = line.split() for word in content: word = word.strip("""!"#$%&'()*,-./:;?@[]_""") if word in dictionary: dictionary[word] += 1 else: dictionary[word] = 1 return dictionary def main(): word_frequencies() if __name__ == "__main__": main()
8a36a3bf707af30c3a2cf22f89bf0379bb784c18
Ozcry/PythonCEV
/ex/ex029.py
567
3.765625
4
'''Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite.''' v = float(input('\033[34mDigite a velocidade do carro:\033[m ')) m = (v - 80) * 7 if v > 80: print('\033[31mVocê foi multado!\033[m') print('\033[30mO Valor da sua multa e de R$\033[m\033[32m{:.2f}\033[m'.format(m)) print('\033[33m-----------\033[m') else: print('\033[36mParabêns! dentro do limite permitido.\033[m') print('\033[33m-----------\033[m')
042189e68f8787bce947e049b4ff5da70d63fccf
jacobgillette/CS362_HW7
/leapyear.py
400
3.6875
4
import unittest def fun(user_in): if user_in < 1: return "Invalid Input" if user_in % 4 == 0: if user_in % 100 == 0: if user_in % 400 == 0: return "Input is a leap year" else: return "Input is not a leap year" else: return "Input is a leap year" else: return "Input is not a leap year"
bfd6e98f6142eb53b9adae85fd34469c2c3b2cb4
AKDavis96/Data22python
/dictionary/forloop.py
190
3.84375
4
list_data = [1, 2, 3, 4, 5] for num in list_data: print(num*2) embedded_list = [[1,2,3], [4,5,6]] for data in embedded_list: print(data*2) for num in data: print(num*2)
96f4bee0dc6e28a3f90221fa85f1db73a7999424
rono2845/Chat-App
/server.py
972
3.59375
4
import socket from tkinter import * ## USING TKINTER TO GIVE IT A LOOK def send(listbox, entry): message = entry.get() listbox.insert('end', "Server: "+message) entry.delete(0,END) client.send(bytes(message, "utf-8")) receive(listbox) def receive(listbox): message_from_client = client.recv(50) listbox.insert('end', "Client: "+message_from_client.decode('utf-8')) root = Tk() root.title('Server') entry = Entry() entry.pack(side=BOTTOM) listbox = Listbox(root) listbox.pack() sendButton = Button(root, text="Send", command = lambda : send(listbox, entry)) sendButton.pack(side=BOTTOM) receiveButton = Button(root, text="receive", command = lambda : receive(listbox)) receiveButton.pack(side=BOTTOM) ## ACTUAL SOCKET CODES TO MAKE THE APPLICATION RUN s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST_NAME = socket.gethostname() PORT = 12345 s.bind((HOST_NAME, PORT)) s.listen(4) client, address = s.accept() root.mainloop()
35a47b06b86cfcbcdf5426e52042eb202c04bd45
chicocheco/automate_the_boring_stuff
/time_calc_prod.py
455
3.515625
4
import time # Another way to profile your code is to use the cProfile.run() function. def calc_prod(): # Calculate the product (nasobek in Czech) of the first 100,000 numbers. product = 1 for i in range(1, 100000): product *= i return product start_time = time.time() prod = calc_prod() end_time = time.time() print(f'The result is {len(str(prod))} digits long.') print(f'Took {end_time - start_time} seconds to calculate.')
221ca899e96994d05da974715ea57d8cacebb371
terrifyzhao/leetcode
/other/subarray_product.py
574
3.515625
4
class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ max_num, min_num, res = nums[0], nums[0], nums[0] for num in nums[1:]: tmp_max = max_num tmp_min = min_num max_num = max(num, tmp_max * num, tmp_min * num) min_num = min(num, tmp_max * num, tmp_min * num) if max(max_num, min_num) > res: res = max(max_num, min_num) return res s = Solution() result = s.maxProduct([-4, -3, -2]) print(result)
d31c75fbfd3067ee7a99c683c8352c5d31946aed
vincenttuan/yzu_python
/lesson09/sql2/CreateTable.py
445
3.671875
4
import sqlite3 sql = ''' CREATE TABLE Employee( ID INT PRIMARY KEY NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR(50), SALARY REAL ); ''' conn = sqlite3.connect("company.db") cursor = conn.cursor() cursor.execute(sql) conn.commit() conn.close() print('Employee 資料表建立完成')
0c24677ed0689390fe53294bb9729f6767fc2d63
tinynahran/Practical-Python-with-Applications-in-Finance
/Chapter2/2_1_5_main.py
1,271
3.703125
4
''' This module validates methods created as part of exercise 2.1.5. ''' from classFiles.loan import Loan from classFiles.car import Lexus def main(): # This is for validation of the static methods monthlyRate and annualRate. print('Annual rate converted to monthly rate for simple interest: ' + str(Loan.monthlyRate(.10)) + '\n') print('Monthly rate converted to annual rate for simple interest: ' + str(Loan.annualRate(Loan.monthlyRate(.10))) + '\n') # This is for validation of methods that relied on rate where static method is now # being used. print('calcMonthlyPmt using static method for rate: ' + str(Loan.calcMonthlyPmt(360, .07, 500000)) + '\n') lex = Lexus(80000) l = Loan(360, .07, 500000, lex) print('interestDue using static method for rate: ' + str(l.interestDue(10)) + '\n') print('interestDueR using static method for rate: ' + str(l.interestDueR(10)) + '\n') print('principalDueR using static method for rate: ' + str(l.principalDueR(10)) + '\n') print('calcBalance using static method for rate: ' + str(Loan.calcBalance(360, .07, 500000, 200)) + '\n') print('balance using static method for rate: ' + str(l.balanceR(200))) if __name__ == '__main__': main()
e3bbf6741cc76c295ba4b20540d48c3819e44ce3
Aasthaengg/IBMdataset
/Python_codes/p03624/s543789215.py
143
3.640625
4
alpha="abcdefghijklmnopqrstuvwxyz" S=input() for i in range(len(alpha)) : if alpha[i] not in S : print(alpha[i]) exit() print("None")
99f4b3bc990764982731c8626a46bd0b67a742ce
huiyi1993/store
/day03/作业5+-调换.py
162
3.75
4
A = input("请输入A:") A = int(A) B = input("请输入B:") B = int(B) print("A=",A) print("B=",B) C = A+B A =C-A B =C-B print("A=",A) print("B=",B)
e5a264fa3f1c4ec634ed156bf1ba39a802915441
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_209/605.py
1,218
3.671875
4
import os # NOQA import sys # NOQA import re # NOQA import math # NOQA from collections import Counter, deque, namedtuple # NOQA from itertools import count, product, permutations, combinations, combinations_with_replacement # NOQA # Itertools Functions: # product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD # permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD DA DB DC # combinations('ABCD', 2) AB AC AD BC BD CD # combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD def surface_area(r, h, r_above=0): return (math.pi * r**2) + (2 * math.pi * r * h) - (math.pi * r_above**2) for case in range(1, int(input()) + 1): res = None n, k = (int(x) for x in input().split()) pancakes = [] for _ in range(n): r, h = (int(x) for x in input().split()) pancakes.append((r, h)) pancakes.sort() best = 0 for combo in combinations(pancakes, k): above = 0 sa = 0 for r, h in combo: sa += surface_area(r, h, above) above = r if sa > best: best = sa print("Case #{}: {}".format(case, best))
2f47a781020c9955a395154d4c36f6df7eb51b4b
mychristopher/test
/pyfirstweek/tkinter学习/Entry控件.py
585
3.78125
4
#!/usr/bin/python # -*- coding: utf-8 -*- import tkinter #创建窗口 win = tkinter.Tk() #设置标题 win.title("caicai") #设置大小和位置 win.geometry("400x400+200+20") #绑定变量 e = tkinter.Variable() #用于显示简单的文本内容 #show 密文显示show="*" def showInfo(): print(entry.get()) entry = tkinter.Entry(win,textvariable=e) entry.pack() button = tkinter.Button(win,text="按钮",command=showInfo) button.pack() #e就代表输入框这个对象 #设置值 e.set("caicai is a small sun") #取值 print(e.get()) print(entry.get()) win.mainloop()
35d8d0628cc5b27d3d5bada8a400a1cd426f42fe
ahammer3/UCSD-AlgorithmicToolbox
/code/fibonacci_last_digit.py
369
3.921875
4
# Uses python3 import sys def fibonacci_last_digit(n): nums = [None] * (n+2) nums[0] = 0 nums[1] = 1 for i in range(2, n+1): nums[i] = (nums[i-1] + nums[i-2]) % 10 return nums[n] if __name__ == '__main__': # for stdin, end input with newline and CRTL + D input = sys.stdin.read() n = int(input) print(fibonacci_last_digit(n))
a88f8251ad55e7cdcfacfaa4a02dac87f951f9cd
kinetic-cipher/algorithms
/sorting/merge_sort.py
2,103
4.28125
4
# MergeSort # # Recursively splits into (left, right) sublists (down to length 1) and then # recursively merges back up to a single list, with the sorting occurring # during the merge. # import math # merge two sublists def merge(left_list, right_list): result = list() # merge sublists # left and righr sub-lists are potential sources, 'result' is the # destination list while( len(left_list) > 0 and len(right_list) > 0 ): len_left = len(left_list) len_right = len(right_list) if left_list[0] < right_list[0]: result.append( left_list[0] ) # consume element, now left_list = remainder of list if len(left_list) > 1: left_list = left_list[1:len_left] # consume element just placed in result else: left_list = [] else: result.append( right_list[0] ) # consume element, now right list = remainder of list if len(right_list ) > 1: right_list = right_list[1:len_right] # consume element just placed in result else: right_list = [] # one of the sub-lists has been consumed, now we mnust # finished comsuming the other (only one of the for-loops will be active) for k in range( len(left_list) ): result.append( left_list[k] ) for k in range( len(right_list) ): result.append( right_list[k] ) return result # recursive mergesort function def merge_sort( my_list ): # length-1 lists are sorted L = len(my_list) if L <= 1: return my_list # create lieft and right sub-lists m = math.floor(L/2) left_list = my_list[0:m] # left sub-list (note: m is not included in interval) right_list = my_list[m:L] # right sub-list (note: m is included in interval) # sorr the sub-lists left_list = merge_sort(left_list) right_list = merge_sort(right_list) # merge then return merge(left_list, right_list) # test my_list = [11,2,9,13,100,33,17,45,64,77] print(my_list) my_sorted_list = merge_sort(my_list) print(my_sorted_list)
01b01a7b660b3afa7391bf61a3c3e990b8051c5e
kazhiryu187/myProgramming
/c2f.py
178
4.1875
4
# Celsius to Fahrenheit converter cel = float(input('Temperature in Celsius: ')) #cel = int(cel) fah = (cel * 9/5) + 32 print("{} Celsius = {} Fahrenheit ".format(cel, fah))
61d64bae1126bb6a134a9ef4e11cc4acf4db79ab
anmig13/Testing_GithubAPI_example
/Testing_GithubAPI/main.py
696
3.734375
4
from person import Person from hello_world import Hello_World def main(): # tworzymy dwa obiekty klasy Osoba Jan = Person("Jan", "Nowak", 48) Adam = Person("Adam", "Mickiewicz", 220) # wywołujemy metodę przedstaw_sie() na każdym z nich Jan.przedstaw_sie() Adam.przedstaw_sie() wiek_Adama_przed = Adam.urodziny() Adam.przedstaw_sie() print(f"Wiek Adama sprzed urodzin: {wiek_Adama_przed}") # odwołujemy się do pól, modyfikujemy je Jan.imie = "Hugo" Jan.nazwisko = "Gumis" Jan.wiek = 5 Jan.przedstaw_sie() hello = Hello_World("Ania") hello.przywitaj_sie() if __name__ == "__main__": main()
302d7ef0e55442003fafe1367048f9d89a55622f
igauravsehrawat/HackerRank
/week-18/ghosts.py
748
3.515625
4
#!/bin/python def gcd(number1, number2) : looper = 1 gcd_number = 1 while ((looper <= number1) or (looper <= number2)) : if ((number1 % looper == 0) and (number2 % looper ==0)) : gcd_number = looper looper += 1 return gcd_number def main() : A,B,C,D = raw_input().strip().split(' ') A,B,C,D = [int(A),int(B),int(C),int(D)] ghost_count = 0 for town in xrange(1, A + 1) : for street in xrange(1, B + 1) : for apartment in xrange(1, C + 1) : for house in xrange(1, D + 1) : if (abs(town - street) % 3 == 0) : if ((street + house) % 5 == 0) : if ((town * house) % 4 == 0) : if (gcd(town, apartment) == 1) : ghost_count += 1 print ghost_count return if __name__ == "__main__" : main()
83e67e9267fd5557aaf3755441032ec364ac15f5
seunghyon/algorithm
/leetcode/11. Container With Most Water.py
346
3.640625
4
def maxArea(heights): start,end = 0, len(heights)-1 result = 0 while start < end: result = max(result,min(heights[start],heights[end]) * (end-start)) if heights[start] < heights[end]: start += 1 else: end -= 1 return result heights = [1,8,6,2,5,4,8,3,7] print(maxArea(heights))
77e38b2b407bebd1256bdb2fd4e60ac62316cfb5
woshiskc/LearnPython
/Day7/ex8.py
803
4.0625
4
# -*- coding: utf-8 -*- # define formatter . assign a format string to formatter formatter = "%r %r %r %r" test = "%r %r" # "%s %s" print formatter % (1,2,3,4) # the variables of formatter are numbers print formatter % ("one", "two", "three", "four") # the variables of formatter are strings print formatter % (True, False, False, True) # the variables of formatter are Keywords print formatter % ("Ture","False","Ture","False") print formatter % (formatter, formatter, formatter, formatter) # the variables of formatter are print formatter % ( "I had this thing.", "That you could type up right.", "But it didn't sing.", "So I said goodnight." ) print formatter % ("hi","你好","goodbye","再见") print test % ("hi","你好")#.decode('utf-8').encode('gbk'))
67e51b7a2e0796da6c72ccf9f11478260d0be0fc
BhargavReddy461/Coding
/LinkedList/insert_delete_traverse_reverse_DLL.py
2,991
3.515625
4
import gc class Node: def __init__(self, data): self.data = data self.prev = None self.next = None class DoublyLinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head if self.head is not None: self.head.prev = new_node self.head = new_node def append(self, new_data): new_node = Node(new_data) temp = self.head if self.head is None: self.head = new_node return while(temp.next): temp = temp.next new_node.prev = temp temp.next = new_node def insertAfter(self, prev_node, new_data): if prev_node is None: print(" wrong input") return new_node = Node(new_data) new_node.next = prev_node.next prev_node.next = new_node new_node.prev = prev_node if new_node.next is not None: new_node.next.prev = new_node def insertBefore(self, next_node, new_data): if next_node is None: print("wrong input") new_node = Node(new_data) new_node.prev = next_node.prev next_node.prev = new_node new_node.next = next_node if new_node.prev is not None: new_node.prev.next = new_node else: self.head = new_node def delete(self, d): if self.head is None or d is None: return if self.head == d: self.head = d.next if d.next is not None: d.prev.next = d.next if d.prev is not None: d.next.prev = d.prev gc.collect() def length(self): c = 0 temp = self.head while(temp): c += 1 temp = temp.next print(c) def reverse(self): curr = self.head temp = None if curr is None or curr.next is None: return while curr is not None: temp = curr.prev curr.prev = curr.next curr.next = temp curr = curr.prev self.head = temp.prev def traversal(self): print("\nforward traversal") last = None curr = self.head while curr: print(curr.data, end=" ") last = curr curr = curr.next print("\nreverse traversal") while last: print(last.data, end=" ") last = last.prev dlist = DoublyLinkedList() dlist.push(1) dlist.push(2) dlist.push(3) dlist.push(4) dlist.push(5) dlist.insertAfter(dlist.head.next.next, 6) dlist.insertBefore(dlist.head.next.next, 7) dlist.append(8) dlist.delete(dlist.head.next) dlist.length() dlist.traversal() dlist.reverse() dlist.traversal()
d01774c10aabb4f889404cd4cb9ac9502c0aa7d2
PyPyPythonDude/Automate_the_Boring_Stuff_with_Python
/Projects/collatz_sequence.py
623
4.53125
5
# This program performs different calculations based on whether a given # number is even or odd. def collatz(number): # Check if a number is divisible by 2 with 0 remainder. if number % 2 == 0: # Floor division means the // will always take the floor or lower number. result = number // 2 # If the remainder is 1, the number is odd. elif number % 2 == 1: result = 3 * number + 1 print(result) return result try: num = int(input("Give me a number: ")) while num > 0 and num != 1: num = collatz(num) except ValueError: print("You must enter an integer.")
04ad9dfd0acd0f9dde158b04e80963c4a33a4ada
SFoskitt/python_extra
/ex_01_max_fun.py
254
3.5
4
from sys import argv # script, first, second = argv def max(first, second): if first > second: print "first is greater", first return first else: print "second is greater", second return second # print "the answer is ", max(first, second)
48e7db0f718d96314960b4ba7ac7eacdfa1bc49e
wbsjl/ftp-server
/Data/data2.py
1,064
3.796875
4
class StackError(Exception): pass class Sstack: def __init__(self): # 约定列表最后一个元素为栈顶元素 self.elems = [] def top(self): if not self.elems: raise StackError("no stack") return self.elems[-1] def is_empty(self): return self.elems == [] def push(self,elem): self.elems.append(elem) def pop(self): if not self.elems: raise StackError("no stack") return self.elems.pop() # def detect(self,i): # list02=[] # list(i) # for item in i: # if item =="(": # list02.append(item) # if item ==")": # out_one=list02.pop() # if out_one!="(": # raise IndexError("wrong one") # print("nice") if __name__ == "__main__": st = Sstack() # print(st.top()) print(st.is_empty()) st.push(1) st.push(2) st.push(3) st.push(4) while not st.is_empty(): print(st.pop())
379e86d508328c9718c8fe397c9c470473346532
AtIasz/ccOW1
/WeekNo1/pighutch.py
269
3.96875
4
width=8 #int(input("Give me the width of the hutch: ")) height=4 #int(input("Give me the height of the hutch: ")) for i in range(height): if i==0 or i==(height-1): print("*"*width) else: print("*"+" "*(width-2)+"*")
93f522d46ebaf76d7d615ba750ea43d06c4675e6
RajiBala/Data-Structures-ADT
/TurtleLinkedList.py
6,381
4.1875
4
from node1 import * import turtle class linked_list: def __init__(self): self.head=None self.tail=None self.size=0 def size(self): self.size=size print (self.size) def insertfirst(self,elem): new=node(elem) new.next=self.head self.head=new self.size=self.size+1 print (self.head.data) def insertlast(self,elem): new=node(elem) #new.next=None self.tail.next=new self.tail=new new.next=None self.size=self.size+1 print (self.tail) def first(self): if self.isempty()==1: print ("the list is empty") else: print ("first element is ") print (self.head.data) def last(self): p=self.head while p!=None: if p.next==None: print ("last element is ") print (p.data) p=p.next def removefirst(self): if self.isempty()==1: print ("list is empty") else: print ("the firstelement removed is:",self.head.data) self.head=self.head.next self.size=self.size-1 #n=node(self.head) #def removelast(self): def insertafter(self,p,elem): node1=self.head while(node1): if(node1.data==p): new=node(elem) x=node1.get_next() #new.data=elem new.next=x node1.next=new self.current=new break else: node1=node1.next self.size=self.size+1 print ("the element",elem," is insertd after",p) def find(self,elem): current = self.head found = False while current != None and not found: if current.get_data() == elem: found = True else: current = current.get_next() if found==False: print ("false") print ("the element "),elem,("is not found") else: print ("true") print ("the element ",elem,"is found") def display(self): print("DISPLAY:") p=self.head while p.next!=None: print (p.data) p=p.next print (p.data) def isempty(self): if self.head==None: return 1 else: return 0 def remove(self,elem): current = self.head previous = None found = False while not found: if current.get_data() == elem: found = True else: previous = current current = current.get_next() if previous == None: self.head = current.get_next() else: previous.set_next(current.get_next()) print ("the element ",elem,"is removed") def removeafter(self,elem): current = self.head found = False while current != None and not found: if current.get_data() == elem: found = True print ("the elemnt found is"),elem else: current = current.get_next() if found==True: p=current.get_next() self.head=p.get_next() print ("the element is removed") else: print ("the element is not found") def disturtle(self): node1 = self.head i=0 while (node1): if(node1.next!=None): i+=10 turtle.goto(5*i,0) else: i+=10 turtle.goto(5*i,0) turtle.pendown() turtle.write(node1.data) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) node1=node1.next def tutrremove(self,elem): node1 = self.head count=0 while(node1): if(node1.next!=None): if(count==elem): turtle.pendown() turtle.forward(30) turtle.pencolor("white") turtle.left(90) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) turtle.penup() turtle.pencolor("black") node1=node1.next #turtle.goto(50*count,0) else: turtle.goto(50*count,0) turtle.penup() #turtle.write(node1.data) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) node1=node1.next count=count+1 m=linked_list() print("*** insertfirst function is called***") m.insertfirst(23) m.insertfirst(24) m.insertfirst(25) m.insertfirst(26) m.insertfirst(27) m.insertfirst(28) m.insertfirst(29) m.display() print ("*****list ends****") print ("\n") m.disturtle() #turtle.reset() print ("**** first() function called***") m.first() print ("\n") print ("**** last() function called***") m.last() print ("\n") print ("***find() function called***") m.find(24) print ("\n") print ("***find() function called***") m.find(50) print ("\n") print("*** remove() function is called***") #m.remove(26) m.tutrremove(3) print ("\n") m.display() print ("****list ends****") print ("\n") print("*** removefirst() function is called***") m.removefirst() print ("\n") #m.disturtle() #turtle.reset() print("*** insertafter() function is called***") m.insertafter(25,25.5) print ("\n") m.display() print ("****list ends****") print ("\n") #m.disturtle() #turtle.reset() turtle.exitonclick()
38562e9aaea1b41c2e4b85cc909df95320520890
daniel-reich/ubiquitous-fiesta
/e8TFAMbTTaEr7JSgd_24.py
132
3.515625
4
def left_digit(num): num=list(num) for x in num: try: x=int(x) return x except ValueError: continue
71a5ebc316ee4b71eb32f4ff467a1be87c0d962b
4gn3s/adventOfCode2016
/advent_of_code_1.py
4,297
3.609375
4
def parse_input(input_list): steps = [] for entry in input_list: if len(entry) < 2: raise Error("Input incorrect") steps.append({"dir": entry[0], "steps": int(entry[1:])}) return steps def rotate(current, next_dir): if next_dir != 'L' and next_dir != 'R': raise Error("Incorrect direction") if current == 'N': return 'W' if next_dir == 'L' else 'E' elif current == 'S': return 'E' if next_dir == 'L' else 'W' elif current == 'E': return 'N' if next_dir == 'L' else 'S' elif current == 'W': return 'S' if next_dir == 'L' else 'N' else: raise Error("Incorrect direction") def move_in_dir(direction, current_pos, steps): pos = current_pos if direction == 'N': pos = (pos[0] - steps, pos[1]) if direction == 'S': pos = (pos[0] + steps, pos[1]) if direction == 'E': pos = (pos[0], pos[1] + steps) if direction == 'W': pos = (pos[0], pos[1] - steps) return pos def distance(from_pos, to_pos): return abs(from_pos[0] - to_pos[0]) + abs(from_pos[1] - to_pos[1]) def headquarters_distance(input_list): moves = parse_input(input_list) current = 'N' current_pos = (0, 0) for move in moves: current = rotate(current, move["dir"]) current_pos = move_in_dir(current, current_pos, move["steps"]) return distance((0, 0), current_pos) def test_1(input_list, result): assert headquarters_distance(input_list) == result test_1(['R2', 'L3'], 5) test_1(['R2', 'R2', 'R2'], 2) test_1(['R5', 'L5', 'R5', 'R3'], 12) my_input = ['R3', 'L5', 'R2', 'L1', 'L2', 'R5', 'L2', 'R2', 'L2', 'L2', 'L1', 'R2', 'L2', 'R4', 'R4', 'R1', 'L2', 'L3', 'R3', 'L1', 'R2', 'L2', 'L4', 'R4', 'R5', 'L3', 'R3', 'L3', 'L3', 'R4', 'R5', 'L3', 'R3', 'L5', 'L1', 'L2', 'R2', 'L1', 'R3', 'R1', 'L1', 'R187', 'L1', 'R2', 'R47', 'L5', 'L1', 'L2', 'R4', 'R3', 'L3', 'R3', 'R4', 'R1', 'R3', 'L1', 'L4', 'L1', 'R2', 'L1', 'R4', 'R5', 'L1', 'R77', 'L5', 'L4', 'R3', 'L2', 'R4', 'R5', 'R5', 'L2', 'L2', 'R2', 'R5', 'L2', 'R194', 'R5', 'L2', 'R4', 'L5', 'L4', 'L2', 'R5', 'L3', 'L2', 'L5', 'R5', 'R2', 'L3', 'R3', 'R1', 'L4', 'R2', 'L1', 'R5', 'L1', 'R5', 'L1', 'L1', 'R3', 'L1', 'R5', 'R2', 'R5', 'R5', 'L4', 'L5', 'L5', 'L5', 'R3', 'L2', 'L5', 'L4', 'R3', 'R1', 'R1', 'R4', 'L2', 'L4', 'R5', 'R5', 'R4', 'L2', 'L2', 'R5', 'R5', 'L5', 'L2', 'R4', 'R4', 'L4', 'R1', 'L3', 'R1', 'L1', 'L1', 'L1', 'L4', 'R5', 'R4', 'L4', 'L4', 'R5', 'R3', 'L2', 'L2', 'R3', 'R1', 'R4', 'L3', 'R1', 'L4', 'R3', 'L3', 'L2', 'R2', 'R2', 'R2', 'L1', 'L4', 'R3', 'R2', 'R2', 'L3', 'R2', 'L3', 'L2', 'R4', 'L2', 'R3', 'L4', 'R5', 'R4', 'R1', 'R5', 'R3'] print(headquarters_distance(my_input)) def find_steps(prev_pos, cur_pos): if prev_pos[0] != cur_pos[0]: assert prev_pos[1] == cur_pos[1] if prev_pos[0] < cur_pos[0]: return [(x, prev_pos[1]) for x in range(prev_pos[0] + 1, cur_pos[0] + 1)] else: return [(x, prev_pos[1]) for x in range(prev_pos[0] - 1, cur_pos[0] - 1, -1)] else: assert prev_pos[0] == cur_pos[0] if prev_pos[1] < cur_pos[1]: return [(prev_pos[0], x) for x in range(prev_pos[1] + 1, cur_pos[1] + 1)] else: return [(prev_pos[0], x) for x in range(prev_pos[1] - 1, cur_pos[1] - 1, -1)] def headquarters_visited_twice_distance(input_list): moves = parse_input(input_list) current = 'N' start = (0, 0) current_pos = start visited = set(current_pos) for move in moves: current = rotate(current, move["dir"]) next_pos = move_in_dir(current, current_pos, move["steps"]) print(current_pos, next_pos) steps = find_steps(current_pos, next_pos) for step in steps: if step in visited: print(".") print(step) print(".") return distance(start, step) else: visited.add(step) current_pos = next_pos return distance(start, current_pos) def test_2(input_list, result): headquarters_visited_twice_distance(input_list) == result test_2(['R8', 'R4', 'R4', 'R8'], 4) print(headquarters_visited_twice_distance(my_input))
5ae258472df7f4cb08740f14a1a9e0b845ad5bc4
tg270798/30dayscodeHackerrank
/Day3: Intro to Conditional Statements
461
3.859375
4
#!/bin/python3 import math import os import random import re import sys def check(num): if((num<1)or(num>100)): print("value out of range") def main(num): check(num) if(num%2!= 0): print("Weird") elif(num%2 == 0): if((num>=2) and (num<=5)): print("Not Weird") elif((num>=6) and (num<=20)): print("Weird") else: print("Not Weird") n = int(input()) main(n)
50e6ec68f79afe15bb9629b503c1fa178560c180
ucsb-cs8-f18/cs8-f18-lecture-code
/lec13/while_guess.py
201
3.890625
4
import random def guess(): answer = random.randint(1, 10) guess = raw_input("Guess a number between 1 and 10: ") while int(guess) != answer: guess = raw_input("Sorry, guess again: ")
1c5fb158579a98d1d8cca224b40cfab54f0ff732
benzoa/pythonStudy
/basics/ex15_lambda.py
1,705
3.984375
4
# lambda expression(anonymous function) plus_ten = lambda x : x + 10 ''' def plus_ten(x): return x + 10 ''' print("plus_ten(1): {}".format(plus_ten(1))) call_self = (lambda x : x + 9)(1) print("self1: {}".format(call_self)) y = 3 print("self2: {}".format((lambda : y)())) plus_three = lambda x : x + y print("plus_three(1): {}".format(plus_three(1))) print("map: {}".format(list(map(plus_ten, range(5))))) exp = lambda x: str(x) if x % 3 == 0 else x values = list(range(1, 11)) print("conditional expression") print("exp1: {}".format(list(map(exp, values)))) exp = lambda x: str(x) if x % 3 == 0 else float(x) if x % 2 == 0 else x print("exp2: {}".format(list(map(exp, values)))) muls = list(range(11, 21)) exp = lambda x, y: x * y print("exp3: {}".format(list(map(exp, values, muls)))) exp = lambda x: 3 < x < 8 print("filter: {}".format(list(filter(exp, values)))) from functools import reduce exp = lambda x, y: x + y print("reduce: {}".format(reduce(exp, values))) # bit masking hVal = 0xF0 # 240, 0b1111_0000 print(f"orignal hex: {hVal:0x}, bin: {hVal:0b}") BitMask = lambda bit: 1 << bit SetBit = lambda val, bit: val | BitMask(bit) GetBit = lambda val, bit: (val & BitMask(bit)) >> bit ClearBit = lambda val, bit: val & ~BitMask(bit) ToggleBit = lambda val, bit: val ^ BitMask(bit) HighByte = lambda val: (val >> 4) & 0xff LowByte = lambda val: (val << 4) & 0xff print(f"SetBit: {SetBit(hVal, 1):0b}, {SetBit(hVal, 0):0b}") print(f"GetBit: {GetBit(hVal, 4):0b}, {GetBit(hVal, 2):0b}") print(f"ClearBit: {ClearBit(hVal, 4):0b}, {ClearBit(hVal, 6):0b}") print(f"ToggleBit: {ToggleBit(hVal, 5):0b}, {ToggleBit(hVal, 2):0b}") print(f"HighByte: {HighByte(hVal):0b}, {LowByte(hVal):0b}")
eb49101739824ff5a803e72a62e8a0e81a336d5e
Keshavpp/Assignment-Codes-Python
/regexp_1.py
550
3.640625
4
#Course- Using Python to access web data #Week 2 ; Assignment #Use http://py4e-data.dr-chuck.net/regex_sum_42.txt \\ or \\ http://py4e-data.dr-chuck.net/regex_sum_582926.txt import re fname = input("Enter file name: ") try: fh = open(fname) except: print('File cannot be opened:',fname) quit() numlist = list() for line in fh: line = line.rstrip() play = re.findall('[0-9]+',line) for i in range(0, len(play)): play[i]=int(play[i]) #number = float(play[0]) add = sum(play) numlist.append(add) adsum = sum(numlist) print(adsum)
db07f959f37a9e66806cb15f01a642b1a6c816ab
serxoz/auxilia
/lib/Song.py
1,349
3.546875
4
class Song: # explicit refers to this song being purposefully added by a user, # as opposed to by algorithm def __init__(self, name, track_id, artist, album_uri, album_name, duration, added_by=None, explicit=False, valence=None, energy=None): self.name = name self.track_id = track_id self.artist = artist self.album_uri = album_uri self.album_name = album_name self.duration = duration self.score = 0 if explicit: self.upvotes = 1 else: self.upvotes = 0 self.downvotes = 0 self.added_by = added_by self.age = 0 self.explicit = explicit self.valence = valence self.energy = energy def to_dict(self): """Returns Song args/parameters.""" return { 'name': self.name, 'track_id': self.track_id, 'artist': self.artist, 'album_uri': self.album_uri, 'album_name': self.album_name, 'duration': self.duration, 'score': self.score, 'added_by': self.added_by, 'upvotes': self.upvotes, 'downvotes': self.downvotes, 'age': self.age, 'explicit': self.explicit, 'valence': self.valence, 'energy': self.energy }
1218c34d5ba70b14a16224faeb6a53d718c21c69
ejimenezsoto/cs-module-project-recursive-sorting
/src/sorting/sorting.py
1,282
4.125
4
# TO-DO: complete the helper function below to merge 2 sorted arrays import math def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [] apos = 0 bpos = 0 while 1 < 2: if bpos >= len(arrB): return merged_arr + arrA[apos:] if apos >= len(arrA): return merged_arr + arrB[bpos:] if arrA[apos] < arrB[bpos]: merged_arr.append(arrA[apos]) apos += 1 else: merged_arr.append(arrB[bpos]) bpos += 1 return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # Your code here if len(arr) > 1: mid = math.floor((0 + len(arr)) // 2) left = arr[:mid] right = arr[mid:] a = merge_sort(left) b = merge_sort(right) arr = merge(a, b) return arr # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input def merge_in_place(arr, start, mid, end): # Your code here pass def merge_sort_in_place(arr, l, r): # Your code here pass
e1c27de70f3fb17d45003a39b64436d70714bb51
AdamZhouSE/pythonHomework
/Code/CodeRecords/2206/60590/236824.py
838
3.625
4
tests = int(input()) lists = [] for i in range(tests): temp = int(input()) lists.append(temp) #print(lists) def func(num): result = 0 ele = ((1+num)*num)/2 ele = int(ele) lists = [] for i in range(ele): lists.append(i+1) #print(lists) arr = [] for i in range(1,num+1): #print(i) temp = [] while i>0: temp.append(lists[0]) lists.remove(lists[0]) i = i-1 arr.append(temp) #print(arr) for i in range(arr.__len__()): temp = arr[i] sum = 1 for j in range(temp.__len__()): sum = sum * temp[j] arr[i] = sum #print(arr) result = 0 for i in range(arr.__len__()): result += arr[i] print(result) for i in range(lists.__len__()): func(int(lists[i]))
b28dc4e7f0a2ca3d0ee22daf9faf04e00f075a65
gsudarshan1990/PythonSampleProjects
/Advanced_Python_Objects_And_DataStructures/exercise.py
1,506
4.21875
4
""" Convert 1024 to binary and hexadecimal representation """ print(hex(1024)) print(bin(1024)) """ Round 5.23222 to two decimal places """ print(round(5.23222,2)) """ Check if every letter in the string s is lower case s = 'hello how are you Mary, are you feeling okay?' """ import string s = 'hello how are you Mary, are you feeling okay?' modified_string=s.translate(s.maketrans('','',string.punctuation)) print(modified_string) words=modified_string.split() for word in words: for letter in word: if(letter.islower()): continue else: print(letter+' is not lower') print('Every letter is not lower') """ How many times does the letter 'w' show up in the string below? s = 'twywywtwywbwhsjhwuwshshwuwwwjdjdid' """ s = 'twywywtwywbwhsjhwuwshshwuwwwjdjdid' count=s.count('w') print(count) """ Problem 5: Find the elements in set1 that are not in set2: : set1 = {2,3,1,5,6,8} set2 = {3,1,7,5,6,8} """ set1 = {2,3,1,5,6,8} set2 = {3,1,7,5,6,8} print(set1.difference(set2)) """ Problem 6: Find all elements that are in either set: """ print(set1.union(set2)) """ Problem 7: Create this dictionary: {0: 0, 1: 1, 2: 8, 3: 27, 4: 64} using a dictionary comprehension. """ dict={x:x**3 for x in range(5)} print(dict) """ Problem 8: Reverse the list below: list1 = [1,2,3,4] """ list1 = [1,2,3,4] list1.reverse() print(list1) """ Problem 9: Sort the list below: list2 = [3,4,2,5,1] """ list2 = [3,4,2,5,1] list2.sort() print(list2)
41c23b14496f660d5b9f784f5d3fd2cd6c735832
jbobo/leetcode
/longest_palindromic_subsequence_dp.py
1,156
3.828125
4
#!/usr/bin/env python3 def longestPalindromeSubseq(input_string): """ """ palindrome_length_at = [[1]*len(input_string) for i in range(len(input_string))] for length in range(2, len(input_string) + 1): for left in range(len(input_string) - length + 1): right = left + length - 1 # IF: current edges are a palindrome. if input_string[left] == input_string[right]: inner_length = 0 if length > 2: inner_length = palindrome_length_at[left + 1][right - 1] palindrome_length_at[left][right] = inner_length + 2 # ELSE: try removing left edge OR right edge. else: remove_left = palindrome_length_at[left + 1][right] remove_right = palindrome_length_at[left][right - 1] palindrome_length_at[left][right] = max( remove_left, remove_right) return(palindrome_length_at[0][-1]) if __name__ == "__main__": input_string = "BBABCB" max_length = longestPalindromeSubseq(input_string) print(max_length)
295d9d7cb3868438050edc61352d5a285bb7d58a
AlexeyAG44/python_coursera
/week_5/22_less_positive.py
551
3.78125
4
# Выведите значение наименьшего из всех положительных элементов в списке. # Известно, что в списке есть хотя бы один положительный элемент, # а значения всех элементов списка по модулю не превосходят 1000. numList = list(map(int, input().split())) resNumList = [] current = numList[0] for current in numList: if current > 0: resNumList.append(current) print(min(resNumList))
1a99ed951c0c7bb3240b2f41e6ae111f360587c7
hahaliu/LeetCode-Python3
/111.minimum-depth-of-binary-tree.py
568
3.84375
4
# ex2tron's blog: # http://ex2tron.wang # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 if root.left and root .right: return min(self.minDepth(root.left), self.minDepth(root.right))+1 else: return max(self.minDepth(root.left), self.minDepth(root.right))+1
a71e5112ccc7f8f30d238a81c30f158f4931b5b3
mauricio071/pythonExercicios
/ex032.py
273
3.953125
4
from datetime import date ano = int(input('Digite um ano: (coloque o 0 para analisar o ano atual)')) if ano == 0: ano = date.today().year if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0: print('Esse ano é/foi bisexto') else: print('Não é/foi bisexto')
a1fdc7b94d171d91a28b6c7d3354df04de0882f4
brkunver/Python-Practice
/QuadraticEquationSolver.py
877
4.15625
4
# Written by Burakhan Unver 23.12.2020 def continue_check(): while True: inp = input("Do you want to continue? y for yes, n for no\n") if inp == "y": return True elif inp == "n": return False else: print("Error, please enter 'y' or 'n'") cont = True while cont: print("Please enter coefficients of equation for ax^2+bx+c = 0") try: a = int(input("a = ")) b = int(input("b = ")) c = int(input("c = ")) except ValueError: print("Error, please enter valid numbers") continue delta = b ** 2 - 4 * a * c print("Delta is ", delta) if delta < 0: print("There is no real roots") else: x1 = (-b + delta ** 0.5) / (2 * a) x2 = (-b - delta ** 0.5) / (2 * a) if delta == 0: print("There is one real root") print("x = ", x1) else: print("There are two real roots") print("x1 = %.5f " % x1, "\nx2 = %.5f" % x2) cont = continue_check()
b4088545e8491b3c69dcb54863b96c2b52976908
DalengaMRX/Python
/Exercicios/exe10.py
281
3.9375
4
# Crie um programa que leia quanto dinheiro uma pessoa tem na # carteira e mostre quantos dolares ela pode comprar. n = float(input('Insira o valor disponível para a troca cambial: ')) dolar = n / 5.11 print('Seu dinheiro convertido em Dólar vale: {} Dólares'.format(dolar))
708f816233ed4f52a455323439fb9ed2a63f956a
PavlySz/Code-snippets
/Python/parsers/Caesar_encryption_parsers.py
1,503
3.84375
4
from collections import deque from string import ascii_lowercase, ascii_uppercase import argparse def caesar_cipher_encryption(plaintext, key): upper = deque(ascii_uppercase) upper.rotate(key) upper_str = ''.join(list(upper)) lower = deque(ascii_lowercase) lower.rotate(key) lower_str = ''.join(list(lower)) return plaintext.translate(str.maketrans(ascii_uppercase, upper_str)).translate(str.maketrans(ascii_lowercase, lower_str)) def caesar_cipher_decryption(plaintext, key): upper = deque(ascii_uppercase) upper.rotate(-key) upper_str = ''.join(list(upper)) lower = deque(ascii_lowercase) lower.rotate(-key) lower_str = ''.join(list(lower)) return plaintext.translate(str.maketrans(ascii_uppercase, upper_str)).translate(str.maketrans(ascii_lowercase, lower_str)) def main(): parser = argparse.ArgumentParser() parser.add_argument("-P", "--plaintext", help="Plain text", type=str, required=True) parser.add_argument("-K", "--key", help="key", type=int, required=True) args = parser.parse_args() plaintext = args.plaintext key = args.key ciphertext = caesar_cipher_encryption(plaintext, key) retreived_plaintext = caesar_cipher_decryption(ciphertext, key) print(f"Plaintext = {plaintext}") print(f"Key = {key}") print(f"Ciphertext = {ciphertext}") print(f"Retreived plaintext = {retreived_plaintext}") if __name__ == '__main__': main()
739563c7d1811bf05672b7cc1b6413187b444c29
Carlodinhoo/Compiladores
/Proyectos/proyecto_1/proyecto/out/fz_error_identacion.plx.py
190
3.734375
4
a = 20 cont = 1 while(cont < a): if cont%3 == 0 and cont%5 == 0: print "FizzBuzz!" elif cont%5 == 0: print "Buzz" elif cont%3 == 0: print "Fizz" else: print cont cont = cont+1
8b74db727e9d6f0c6232f8b7e76eabbbe0ec4fa9
sohaibali01/programming_AI
/test_neural.py
2,897
3.59375
4
# https://towardsdatascience.com/neural-net-from-scratch-using-numpy-71a31f6e3675 # A simple neural network solver using numpy from sklearn import datasets from matplotlib import pyplot as plt import numpy as np def load_extra_datasets(): N = 200 gaussian_quantiles = datasets.make_gaussian_quantiles(mean=None, cov=0.7, n_samples=N, n_features=2, n_classes=2, shuffle=True, random_state=None) return gaussian_quantiles gaussian_quantiles= load_extra_datasets() X, Y = gaussian_quantiles X, Y = X.T, Y.reshape(1, Y.shape[0]) # X and Y are the input and output variables m = X.shape[1] n_x = X.shape[0] # size of input layer` n_h = 4 n_y = Y.shape[0] # size of output layer # Initialize the model’s parameters W1 = np.random.randn(n_h,n_x) * 0.01 b1 = np.zeros(shape=(n_h, 1)) W2 = np.random.randn(n_y,n_h) * 0.01 b2 = np.zeros(shape=(n_y, 1)) num_iterations = 1000 learning_rate = 1 for i in range(0,num_iterations): # Implement Forward Propagation to calculate A2 (probabilities) Z1 = np.dot(W1,X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2,A1) + b2 A2 = 1/(1 + np.exp(-Z2)) # Final output prediction # Compute the cross-entropy cost logprobs = np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2)) cost = - np.sum(logprobs) / m print("Cost after iteration %i: %f" %(i, cost)) # BackPropagation/Gradient Descent # dZ2 = d(cost)/dZ2 = d(cost)/dA2 * d(A2)/dZ2 dZ2 = A2 - Y # https://stats.stackexchange.com/questions/370723/how-to-calculate-the-derivative-of-crossentropy-error-function dW2 = (1 / m) * np.dot(dZ2, A1.T) # d(cost)/dW2 = d(cost)/dZ2 * d(Z2)/dW2 (for each example) db2 = (1 / m) * np.sum(dZ2, axis=1, keepdims=True) # d(cost)/dW2 = d(cost)/dZ2 * d(Z2)/db2 (for each example) dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2)) # d(cost)/dZ1 = d(cost)/dZ2 * d(Z2)/dA1 * d(A1)/dZ1 # https://socratic.org/questions/what-is-the-derivative-of-tanh-x dW1 = (1 / m) * np.dot(dZ1, X.T) db1 = (1 / m) * np.sum(dZ1, axis=1, keepdims=True) # Update the parameters W1 = W1 - learning_rate * dW1 b1 = b1 - learning_rate * db1 W2 = W2 - learning_rate * dW2 b2 = b2 - learning_rate * db2 # use parameters to estimate final output Z1 = np.dot(W1,X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2,A1) + b2 A2 = 1/(1 + np.exp(-Z2)) # Final output prediction accuracy = float((np.dot(Y, A2.T) + np.dot(1-Y, 1-A2.T))/float(Y.size)*100) print('Accuracy: %d' %accuracy+'%') # now plot the predictions Y_hat = A2 > 0.5 fig, (ax1, ax2) = plt.subplots(1, 2) ax1.scatter(X[0, :], X[1, :], c=Y[0,:], s=40, cmap=plt.cm.Spectral) ax1.set_title('Original') ax2.scatter(X[0, :], X[1, :], c=Y_hat[0,:], s=40, cmap=plt.cm.Spectral) ax2.set_title('Output - Accuracy: %d' %accuracy+'%') plt.show()
f86f104188d305236c466f7f38c4d3a95014a5d4
gil-log/GilPyBrain
/baekjoon/steptwo/LeapYear.py
147
3.703125
4
# https://www.acmicpc.net/problem/2753 year = int(input()) if (year%4 == 0 and year%100 !=0) or (year%400 == 0): print(1) else : print(0)
5ac0a4883b65a8e61bfe8d6ea10e49551c1cbe19
Beowulfdgo/HackerRank
/Maximum Draws.py
67
3.59375
4
n=int(input()) for i in range(n): x=int(input()) print(x+1)
8ba117a2d0376eb7b67a3ab81df5ea3039fed3ba
eitan12345om/Euler-Projects
/Euler6.py
549
3.71875
4
""" The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ y = 0 z = 0 for x in range(1,101): y = x**2 + y for x in range(1,101): z = x + z z = z**2 print(z-y)
4465af6e2ff8183f6ca0e4109e3f9ef83ebd768c
Wolverinepb007/Python_Assignments
/Conv_Sum/conversion.py
369
3.828125
4
#designing the conversion function def DecimalToBinary(decimalNum): #Converting decimal numbery to binary bit=[] count=0 while count!=8: R=decimalNum%2 bit.append(R) decimalNum=decimalNum//2 count+=1 return bit
483ccd3bc201928a9c876c107b878de010b5e587
sunyiwei24601/Intern_exercise
/Leetcode/79. Word Search.py
2,523
3.65625
4
class Solution: def exist(self, board, word): rows = len(board) if rows: cols = len(board[0]) memo = [[1]*cols for i in range(rows)] def exist_word(matrix, memo, word, row, col): if len(word) == 0: return 1 if row >= rows or row < 0 or col >= cols or col < 0 or matrix[row][col] != word[0] or not memo[row][col] : return -1 else: memo[row][col] = 0 left = exist_word(matrix, memo, word[1:], row, col + 1) if left == 1: return 1 right = exist_word(matrix, memo, word[1:], row, col - 1) if right == 1 : return 1 up = exist_word(matrix, memo, word[1:], row - 1, col) if up == 1 : return 1 down = exist_word(matrix, memo, word[1:], row + 1, col) if down == 1 : return 1 memo[row][col] = 1 return -1 result = -1 for i in range(rows): for j in range(cols): result = exist_word(board, memo, word, i, j) if result == 1: return True return False def exist2(self, board, word): rows = len(board) if rows: cols = len(board[0]) memo = [[1]*cols for i in range(rows)] def exist_word(matrix, memo, word, row, col): if len(word) == 0: return 1 if row >= rows or row < 0 or col >= cols or col < 0 or matrix[row][col] != word[0] or not memo[row][col] : return -1 else: memo[row][col] = 0 left = exist_word(matrix, memo, word[1:], row, col + 1) right = exist_word(matrix, memo, word[1:], row, col - 1) up = exist_word(matrix, memo, word[1:], row - 1, col) down = exist_word(matrix, memo, word[1:], row + 1, col) return max(left, right, up, down) result = -1 for i in range(rows): for j in range(cols): result = exist_word(board, memo, word, i, j) if result == 1: return True return False if __name__ == "__main__": s = Solution() board = [["a","a","a","a"], ["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["a","a","a","b"]] print(s.exist(board, "aaaaaaaab"))
ee8a3744ba58ffe8b1fd870102ca876d46a00e9c
Vadym95/Studing
/lesson8.py
501
4.03125
4
cities = ["New York", "Moscov", "new dehli", "singapure", "Kiev"] print(cities) print(len(cities)) print(cities[0]) print(cities[2].title()) print(cities[3].upper()) cities[4] = "Tula" print(cities[4]) cities.append("Kursk") print(cities) cities.insert(1, "lviv") print(cities) del cities[3] print(cities) cities.remove("Tula") print(cities) deleted_city = cities.pop() print(cities) print(deleted_city) cities.sort() print(cities) cities.sort(reverse=True) print(cities)
cfe7747d5a43fb78881aa4e0b3e6334691e1e9b3
iliucaisi/ProgrammingInPython
/modules/fasteners/demo_1.py
729
3.5625
4
#!/usr/bin/python import random import threading import time import fasteners def read_something(ident, rw_lock): with rw_lock.read_lock(): print("Thread %s is reading something" % ident) time.sleep(1) def write_something(ident, rw_lock): with rw_lock.write_lock(): print("Thread %s is writing something" % ident) time.sleep(2) rw_lock = fasteners.ReaderWriterLock() threads = [] for i in range(0, 10): is_writer = random.choice([True, False]) if is_writer: threads.append(threading.Thread(target=write_something, args=(i, rw_lock))) else: threads.append(threading.Thread(target=read_something, args=(i, rw_lock))) try: for t in threads: t.start() finally: while threads: t = threads.pop() t.join()
f6bffb853f7226470f27be72d2eddd56ae1737a7
JesusSePe/Python
/recursivity/search.py
229
3.84375
4
def search(list1, list2): for i in list2: if i == list1[0]: return True if len(list1) == 1: return False else: return search(list1[1:], list2) print(search([1, 2, 4], [5, 3, 5]))
b3f11f5ebe248e4d212289aaeacd84ae6524b04a
BrenoSDev/PythonStart
/Introdução a Programação com Python/EX04,9.py
553
3.9375
4
#Aprovação de empréstimo bancário para compra de uma casa casa = float(input('Digite o valor da casa: R$')) salário = float(input('Digite o valor do seu salário: R$')) anos = int(input('Digite o total de anos a pagar: ')) prestação = casa / (anos*12) if prestação > salário*0.3: print('O empréstimo não poderá ser concedido, pois a prestação de R$%.2f é maior do que 30 porcento do seu salário'%prestação) else: print('O empréstimo foi concedido com sucesso!') print('O valot da prestação será de R$%.2f'%prestação)
5217291ba8e5b1f07d73a80559ec756630524621
Yasirkhana/RockPaperScissor_Python
/RockPaperScissor.py
656
3.984375
4
# 2 players from random import randint def game(p1,PC): if((p1==1 and PC==2) or (p1==2 and PC ==3) or (p1==1 and PC ==3)): result = print("PLAYER 1 WON !") return result elif((p1==1 and PC==1) or (p1==2 and PC==2) or (p1==3 and PC==3)): result = print("DRAW !") return result elif((p1==2 and PC==1) or (p1==3 and PC ==1) or (p1==2 and PC ==3)): result = print("PLAYER 1 LOST !") return result Choices = ''' 1 = Rock 2 = Paper 3 = Scissor ''' print(Choices) p1 = int(input("Player 1: Slect Your Choice: ")) PC = randint(1,3) game(p1,PC)
d9a5670bd23051f13e17872275b82b54545b7cf8
akshatfulfagar12345/EDUYEAR-PYTHON-20
/day 3(count occurence of character).py
176
3.984375
4
string=input("Enter any string:") c=input("Enter character to check frequency:") count=0 for i in string: if i==c: count+=1 print(c,"occurs",count,"time(s)",)
50c2ea3d27424c84156e254b2d66e2b1887f9f23
mattshakespeare/OU_python
/above_30.py
311
4.21875
4
#list of temperatures temperatures = [32,45,44.2] #empty list for values above 30 above_30 = [] #iterate through temperature list for temp in temperatures: #if value in temperatures is above 30 if temp > 30: #append to above_30 list above_30.append(temp) #output all values above 30 print(above_30)
cef15b42c88083455f48894c91672a9fda0d5f35
eyad-py/Hacker-Rank
/Arithmetic Operators.py
166
3.703125
4
if __name__ == '__main__': a = int(input()) b = int(input()) if 1<= a <=10**10 and 1<=b<=10**10: print(a+b) print(a-b) print(a*b)
84d3ee365ef273d116ad84ebdca44e6943ec70d4
aknouche/hangman
/Hangman/hangman.py
2,883
4
4
import random words = open("words.txt").read().splitlines() randomword = random.choice(words) # Build a hangman image to print on screen hangman_img = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | /|\ | | | =========''', ''' +---+ | | O | /|\ | / | | =========''', ''' +---+ | | O | /|\ | / \ | | ========='''] number_of_tries = 0 tries_left = 7 guesslist = [] while tries_left > 0: print(randomword) randomword_display = '*' * len(randomword) print(randomword_display) guess = input("Guess a letter from the word above or guess the whole word: ") if len(guess) > 1: # if they guess a whole word if guess == randomword: print( randomword + " is the correct word. You won!") break else: print("You guessed the wrong word! Please try again") print("You have " + str(tries_left) + " tries left to guess the whole word") else: # if they guess a letter if guess in guesslist: print("You already guessed that one") elif guess in randomword: # if letter is correct print("You guessed a correct letter!") print("You have " + str(tries_left) + " tries left to guess the whole word") guesslist.append(guess) else: # if letter is incorrect print("You guessed the wrong letter! Please try again") print("You have " + str(tries_left) + " tries left to guess the whole word") guesslist.append(guess) tries_left -= 1 number_of_tries += 1 print (hangman_img[number_of_tries - 1]) if tries_left == 0: # if max number of tries is reached try_again = input("Game over! Try again? y/n ") if try_again == "y": number_of_tries = 0 elif try_again == "n": print("Thank you, come again") input("Press Enter to confirm and leave the game...") else: print("Please enter a valid choice: y or n ")
764cba41d12ad46d261a3a0633f9244111675b13
furas/python-examples
/__scraping__/nwrfc.noaa.gov - requests/main.py
673
3.5
4
# author: Bartlomiej "furas" Burek (https://blog.furas.pl) # date: 2022.02.26 # [python - Reading a CSV file into Pandas - Stack Overflow](https://stackoverflow.com/questions/71273200/reading-a-csv-file-into-pandas/71273335?noredirect=1#comment125983964_71273335) import pandas as pd import requests import io url = "https://www.nwrfc.noaa.gov/natural/nat_norm_text.cgi?id=TDAO3.csv" response = requests.get(url) start = response.text.find('<pre>') + len('<pre>') end = response.text.find('</pre>') pre = response.text[start:end] text = pre.replace('<br>', '\n') buf = io.StringIO(text) df = pd.read_csv(buf, skiprows=2, low_memory=False) print(df.to_string())
37f19d629fe817b4cc6776e59bbc973d4741fe85
sumanblack666/datacamp-python-data-science-track
/Manipulating DataFrames with pandas/Chapter 3 - Rearranging and reshaping data.py
3,906
4.125
4
#Chapter 3 Rearranging and reshaping data #Pivoting a single variable # Pivot the users DataFrame: visitors_pivot visitors_pivot = users.pivot(index='weekday',columns='city',values ='visitors') # Print the pivoted DataFrame print(visitors_pivot) # # # # # # # # #Pivoting all variables # Pivot users with signups indexed by weekday and city: signups_pivot signups_pivot = users.pivot(index='weekday',columns='city',values='signups') # Print signups_pivot print(signups_pivot) # Pivot users pivoted by both signups and visitors: pivot pivot = users.pivot(index='weekday',columns='city') # Print the pivoted DataFrame print(pivot) # # # # # # # # #Stacking & unstacking I # Unstack users by 'weekday': byweekday byweekday = users.unstack(level='weekday') # Print the byweekday DataFrame print(byweekday) # Stack byweekday by 'weekday' and print it print(byweekday.unstack(level='weekday')) #Stacking & unstacking II # Unstack users by 'city': bycity bycity = users.unstack(level='city') # Print the bycity DataFrame print(bycity) # Stack bycity by 'city' and print it print(bycity.stack(level='city')) # # # # # # # # #Restoring the index order # Stack 'city' back into the index of bycity: newusers newusers = bycity.stack(level='city') # Swap the levels of the index of newusers: newusers newusers = newusers.swaplevel(0, 1) # Print newusers and verify that the index is not sorted print(newusers) # Sort the index of newusers: newusers newusers = newusers.sort_index() # Print newusers and verify that the index is now sorted print(newusers) # Verify that the new DataFrame is equal to the original print(newusers.equals(users)) # # # # # # # # #Adding names for readability # Reset the index: visitors_by_city_weekday visitors_by_city_weekday = visitors_by_city_weekday.reset_index() # Print visitors_by_city_weekday print(visitors_by_city_weekday) # Melt visitors_by_city_weekday: visitors visitors = pd.melt(visitors_by_city_weekday, id_vars=['weekday'], value_name='visitors') # Print visitors print(visitors) # # # # # # # # #Going from wide to long # Melt users: skinny skinny = pd.melt(users, id_vars=['weekday' ,'city']) # Print skinny print(skinny) # # # # # # # # #Obtaining key-value pairs with melt() # Set the new index: users_idx users_idx = users.set_index(['city', 'weekday']) # Print the users_idx DataFrame print(users_idx) # Obtain the key-value pairs: kv_pairs kv_pairs = pd.melt(users_idx, col_level=0) # Print the key-value pairs print(kv_pairs) #Setting up a pivot table # Create the DataFrame with the appropriate pivot table: by_city_day by_city_day = users.pivot(index='weekday',columns='city') # Print by_city_day print(by_city_day) #Using other aggregations in pivot tables # Use a pivot table to display the count of each column: count_by_weekday1 count_by_weekday1 = users.pivot_table(index='weekday', aggfunc='count') # Print count_by_weekday print(count_by_weekday1) # Replace 'aggfunc='count'' with 'aggfunc=len': count_by_weekday2 count_by_weekday2 = users.pivot_table(index='weekday', aggfunc=len) # Verify that the same result is obtained print('==========================================') print(count_by_weekday1.equals(count_by_weekday2)) #Using margins in pivot tables # Create the DataFrame with the appropriate pivot table: signups_and_visitors signups_and_visitors = users.pivot_table(index='weekday', aggfunc=sum) # Print signups_and_visitors print(signups_and_visitors) # Add in the margins: signups_and_visitors_total signups_and_visitors_total = users.pivot_table(index='weekday', aggfunc=sum, margins=True) # Print signups_and_visitors_total print(signups_and_visitors_total)
51479e64014ab9b380ac795574e3449715722735
StevenLOL/kaggleScape
/data/script198.py
10,151
3.53125
4
# coding: utf-8 # # About the dataset # This dataset is about the show about "nothing". Yeah, you guessed it right. I am talking about Seinfeld, one of the greatest sitcoms of all time. This dataset provides episodic analysis of the series including the entire script and significant amount of information about each episode. # # What have I done here? # I have tried to create a classifier to predict the name of the speaker of a given dialogue. I have used the scripts database for this purpose. So, if a line is given to the predictor, it returns the person who said or might say that line. # In[ ]: # Importing libraries and data import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') # importing data df = pd.read_csv("../input/scripts.csv") del df["Unnamed: 0"] df.head() # Now, we don't really require the EpisodeNo, SEID and Season columns so we remove them. # In[ ]: dial_df = df.drop(["EpisodeNo","SEID","Season"],axis=1) dial_df.head() # Time for some EDA # # Plot by number of dialogues spoken # In[ ]: dial_df["Character"].value_counts().head(12).plot(kind="bar") # For creating a corpus out of the data, we will create a datframe concatenating all dialogues of a character. We are choosing 12 characters(by number of dialogues) # In[ ]: def corpus_creator(name): st = "" for i in dial_df["Dialogue"][dial_df["Character"]==name]: st = st + i return st corpus_df = pd.DataFrame() corpus_df["Character"] = list(dial_df["Character"].value_counts().head(12).index) li = [] for i in corpus_df["Character"]: li.append(corpus_creator(i)) corpus_df["Dialogues"] = li corpus_df # # Preparing stopwords(words that are obsolete for NLP or words that hinder modelling). Very helpful in human speech but useless when trained for modelling # In[ ]: from sklearn.feature_extraction import text punc = ['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}',"%"] stop_words = text.ENGLISH_STOP_WORDS.union(punc) # Now, we create a text_processor function to tokenize concatenated dialogues and removing stop words # In[ ]: from nltk.tokenize import word_tokenize def text_processor(dialogue): dialogue = word_tokenize(dialogue) nopunc=[word.lower() for word in dialogue if word not in stop_words] nopunc=' '.join(nopunc) return [word for word in nopunc.split()] # Now, we apply this method # In[ ]: corpus_df["Dialogues"] = corpus_df["Dialogues"].apply(lambda x: text_processor(x)) corpus_df # Adding a length column to the new dataframe which contains length of the concatenated dialogues # In[ ]: corpus_df["Length"] = corpus_df["Dialogues"].apply(lambda x: len(x)) corpus_df # # Who has spoken the most in Seinfeld? # In[ ]: fig, ax = plt.subplots(figsize=(10,10)) sns.barplot(ax=ax,y="Length",x="Character",data=corpus_df) # Obviously, Jerry speaks the most followed by George, Elaine and Kramer # Now, we do some **correlation analysis** to find out how similar are the dialogues of different characters to each other. # (For this, we will use a library called **gensim**. Next cell is the most important yet.) # In[ ]: import gensim # Creating a dictionary for mapping every word to a number dictionary = gensim.corpora.Dictionary(corpus_df["Dialogues"]) print(dictionary[567]) print(dictionary.token2id['cereal']) print("Number of words in dictionary: ",len(dictionary)) # Now, we create a corpus which is a list of bags of words. A bag-of-words representation for a document just lists the number of times each word occurs in the document. corpus = [dictionary.doc2bow(bw) for bw in corpus_df["Dialogues"]] # Now, we use tf-idf model on our corpus tf_idf = gensim.models.TfidfModel(corpus) # Creating a Similarity objectr sims = gensim.similarities.Similarity('',tf_idf[corpus],num_features=len(dictionary)) # Creating a dataframe out of similarities sim_list = [] for i in range(12): query = dictionary.doc2bow(corpus_df["Dialogues"][i]) query_tf_idf = tf_idf[query] sim_list.append(sims[query_tf_idf]) corr_df = pd.DataFrame() j=0 for i in corpus_df["Character"]: corr_df[i] = sim_list[j] j = j + 1 # # Heatmap to detect similarity between characters' dialogues # In[ ]: fig, ax = plt.subplots(figsize=(12,12)) sns.heatmap(corr_df,ax=ax,annot=True) ax.set_yticklabels(corpus_df.Character) plt.savefig('similarity.png') plt.show() # This plot can actually depict how different the cahracters are from each other. Like **Jerry, George, Elaine and Kramer** speak highly similar lines. Maybe, that's why they are friends(This might have happened because they are usually talking to each other and also because their dialogues are more than others). **[Setting] has lowest correlation scores** well because it is the odd one out because it is not a person. **Jerry and George have highly similar dialogues with 81% correlation.** # # An awesome way to use classification # I am predicting the dialogues said by Elaine, George and Kramer only, so we will choose only their dialogues(I wanted to include Jerry, I mean what is Seinfeld without Jerry Seinfeld but I will later tell you why I didn't do that. Look for clues in markdown) # In[ ]: dial_df = dial_df[(dial_df["Character"]=="ELAINE") | (dial_df["Character"]=="GEORGE") | (dial_df["Character"]=="KRAMER")] dial_df.head(8) # Way too many dialogues by george will certainly affect the classifier. # # A text processor for processing dialogues # In[ ]: def text_process(dialogue): nopunc=[word.lower() for word in dialogue if word not in stop_words] nopunc=''.join(nopunc) return [word for word in nopunc.split()] # # Preparation for classifier # In[ ]: X = dial_df["Dialogue"] y = dial_df["Character"] # # TF-IDF Vectorizer # Convert a collection of raw documents to a matrix of TF-IDF features. Equivalent to CountVectorizer followed by TfidfTransformer. # # In information retrieval, tf–idf or TFIDF, short for term frequency–inverse document frequency, is a numerical statistic that is intended to reflect how important a word is to a document in a collection or corpus. It is often used as a weighting factor in searches of information retrieval, text mining, and user modeling. The tf-idf value increases proportionally to the number of times a word appears in the document and is offset by the frequency of the word in the corpus, which helps to adjust for the fact that some words appear more frequently in general. Nowadays, tf-idf is one of the most popular term-weighting schemes; 83% of text-based recommender systems in the domain of digital libraries use tf-idf. # # In[ ]: from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(analyzer=text_process).fit(X) # In[ ]: print(len(vectorizer.vocabulary_)) X = vectorizer.transform(X) # In[ ]: # Splitting the data into train and test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=101) # # Creating a voting classifier with Multinomial Naive Bayes, logistic regression and random forest classifier # The EnsembleVoteClassifier is a meta-classifier for combining similar or conceptually different machine learning classifiers for classification via majority or plurality voting. # # The EnsembleVoteClassifier implements "hard" and "soft" voting. In hard voting, we predict the final class label as the class label that has been predicted most frequently by the classification models. In soft voting, we predict the class labels by averaging the class-probabilities (only recommended if the classifiers are well-calibrated). # In[ ]: from sklearn.naive_bayes import MultinomialNB as MNB from sklearn.linear_model import LogisticRegression as LR from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.ensemble import VotingClassifier as VC mnb = MNB(alpha=10) lr = LR(random_state=101) rfc = RFC(n_estimators=80, criterion="entropy", random_state=42, n_jobs=-1) clf = VC(estimators=[('mnb', mnb), ('lr', lr), ('rfc', rfc)], voting='hard') # In[ ]: # Fitting and predicting clf.fit(X_train,y_train) predict = clf.predict(X_test) # In[ ]: # Classification report from sklearn.metrics import confusion_matrix, classification_report print(confusion_matrix(y_test, predict)) print('\n') print(classification_report(y_test, predict)) # So we get about 51% precision which is not bad considering the limited vocablury. George is dominant here due to high recall value of 0.80. So, unless a dialogue has words that don't exist at all in George's vocablury, there is a high chance George will the speaker of most lines. The situation was worse when Jerry was inclued. **This is why I decided to drop Jerry's dialogues from the dataset.** # # The Predictor # In[ ]: def predictor(s): s = vectorizer.transform(s) pre = clf.predict(s) print(pre) # # Now, we predict... # In[ ]: # Answer should be Kramer predictor(['I\'m on the Mexican, whoa oh oh, radio.']) # In[ ]: # Answer should be Elaine predictor(['Do you have any idea how much time I waste in this apartment?']) # In[ ]: # Answer should be George predictor(['Yeah. I figured since I was lying about my income for a couple of years, I could afford a fake house in the Hamptons.']) # In[ ]: # Now, a random sentence predictor(['Jerry, I\'m gonna go join the circus.']) # In[ ]: # A random sentence predictor(['I wish we can find some way to move past this.']) # In[ ]: # Answer should be Kramer predictor(['You’re becoming one of the glitterati.']) # In[ ]: # Answer should be Elaine predictor(['Jerry, we have to have sex to save the friendship.']) # See, this "george effect" can lead to awkward results. That's why I am trying to find a way to get rid of that high recall value and also improve the precision of classifier. I am open to suggestions. # This is not the end. More is yet to come. # Coming soon: # 1. Alternative deep learning approach using Keras # 2. Sentimental Analysis
d4aeef3871a8c6528a7f439044b2b48ab30f72b4
robertvari/pycore-210109-2
/09_anonim_functions.py
199
3.6875
4
my_lambda = lambda a, b: a+b # print(my_lambda(3, 3)) name_list = ["Vári Róbert", "Kiss Elemér", "Nagy Adrienn", "Tóth Barna"] # print(sorted(name_list)) print(sorted(name_list, key=lambda name: name.split(" ")[-1]))
ccac3371bd6b259b0de4e6d07c78ad2349eed1ca
comwork2016/algorithm
/recursion/splitnumber/sliptnumber.py
935
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created on 2016/03/08 """ [自然数拆分]任何一个大于1 的自然数n , 总可以拆分成若干个小于n 的自然数之和, 试求n的所有拆分(用不完全归纳法)。 """ def split(n): if n == 2: list = [[1, 1]] return list else: list = []; for index in range(1, int(n / 2) + 1): list.append([index, n - index]) onelist = [index] restlist = split(n - index) for l in restlist: #if the first element of restlist is larger than index,discard it, because the fomer has this type. if index <= l[0]: onelist.extend(l) list.append(onelist) # init onelist again onelist = [index] return list if __name__ == '__main__': list = split(7) for l in list: print(l)
25e64c831cf7f2023870084b8139ef34c484a640
ahmadreza-smdi/DesktopAppointmentSys
/main.py
2,358
3.625
4
from config import * global id_number = 0 class patient: def __init__(self,fname,lname,id_number,national_id ,phone_number,address,plate_number ,post_code,special_disease,blood_type): self.fname = fname self.lname = lname self.id_number = id_number self.national_id = national_id self.phone_number = phone_number self.address = address self.plate_number =plate_number self.post_code = post_code self.special_disease = special_disease self.blood_type = blood_type cur.execute(("INSERT INTO patient ( fname, lname,id ,national_id,phone_number,address ,plate_number,post_code,special_disease,blood_type) VALUES ('%s','%s','%s' ,'%s','%s','%s','%s','%s','%s','%s')") %(self.fname, self.lname,self.id_number ,self.national_id,self.phone_number, self.address ,self.plate_number,self.post_code,self.special_disease,self.blood_type)) def add_patient(): print("Please enter the requested elements") fname = input("First name:") lname = input("Last name:") id_number = id_number + 1 national_id = input ("National id:") phone_number = input ("phone number:") address = input ("Address:") plate_number = input("Plate number:") post_code = input("Post code:") special_disease = input ("Special disease:") blood_type = input("Blood type:") new =patient('%s','%s','%s' ,'%s','%s','%s','%s','%s','%s','%s')") %(fname,lname,id_number,national_id,phone_number,address,plate_number,post_code,special_disease,blood_type)) def del_patient(): del_id = input("Enter the id that you like to delete:") cur.execute(("DELETE FROM patient WHERE id = '%s'")%(del_id)) def update_patient(): up_id = input("Enter the id that you like to update:") up_field =input ("What do you want to update ?").lower() a = cur.execute(("SELECT '%s' FROM patient WHERE id = '%s'")%(del_id,up_field)) print("The last value of that was {}".format(a)) b = input("enter the new value:") cur.execute("UPDATE patient SET '%s' = '%s' WHERE id = '%s' ")%(up_field,b,up_id)
5a36bbf48b47f66761c22704325fbb3782817558
shayne-fletcher/zen
/ppf/ppf/math/root_finding.py
3,545
3.734375
4
import math from special_functions import sign, max_flt def bisect(f, min, max, tol, max_its): """Bisection method The quadratic y(x) = x^2 + 2x -1 has roots -1 - sqrt(2) = -2.4142135623730950488016887242097 and -1 + sqrt(2) = 0.4142135623730950488016887242097. >>> bisect(lambda x: x*x + 2*x - 1, -3, -2, lambda x, y: math.fabs(x-y) < 0.000001, 10) (-2.4142141342163086, -2.4142131805419922, 3) >>> bisect(lambda x: x*x + 2*x - 1, 0, 1, lambda x, y: math.fabs(x-y) < 0.000001, 10) (0.41421318054199219, 0.41421413421630859, 3) """ fmin, fmax = f(min), f(max) if fmin == 0: return (min, min, 0) if fmax == 0: return (max, max, 0) if min >= max: raise RuntimeError, "Arguments in wrong order" if fmin*fmax >= 0: raise RuntimeError, "Root not bracketed" count = max_its if count < 3: count = 0 else: count -= 3 while count and tol(min, max) == 0: mid = (min + max)/2. fmid = f(mid) if mid == max or mid ==min: break if fmid == 0: min = max = mid break elif sign(fmid)*sign(fmin) < 0: max, fmax = mid, fmid else: min, fmin = mid, fmid --count max_its -= count return (min, max, max_its) def newton_raphson(f, guess, min, max, digits, max_its): """Newton-Raphson method The quadratic y(x) = x^2 + 2x -1 has roots -1 - sqrt(2) = -2.4142135623730950488016887242097 and -1 + sqrt(2) = 0.4142135623730950488016887242097. >>> newton_raphson(lambda x: (x*x+2*x-1,2*x+2),-3,-3,-2,22,100) (-2.4142135623730949, 5) """ def _handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max): if last_f0 == 0: # must be first iteration if result == min: guess = max else: guess = min last_f0, _ = f(guess) delta = guess - result if sign(last_f0)*sign(f0) < 0: # we've crossed over so move in opposite # direction to last step if delta < 0: delta = (result - min)/2.0 else: delta = (result - max)/2.0 else: # move in same direction of last step if delta < 0: delta = (result - max)/2.0 else: delta = (result - min)/2.0 return (last_f0, delta, result, guess) f0, f1, last_f0, result = 0.0, 0.0, 0.0, guess factor = math.ldexp(1.0, 1 - digits) delta, delta1, delta2 = 1.0, max_flt(), max_flt() count = max_its while True: last_f0 = f0 delta2 = delta1 delta1 = delta f0, f1 = f(result) if f0 == 0: break if f1 == 0: last_f0, delta, result, guess = \ _handle_zero_derivative( \ f, last_f0, f0, delta, result, guess, min, max) else: delta = f0/f1 if math.fabs(delta*2.0) > math.fabs(delta2): # last two steps haven't converged, try bisection delta = ((result - max)/2.0, (result - min)/2.0)[delta > 0] guess = result result -= delta if result <= min: delta = 0.5*(guess - min) result = guess - delta if result == min or result == max: break elif result >= max: delta = 0.5*(guess - max) result = guess - delta if result == min or result == max: break # update brackets if delta > 0: max = guess else: min = guess count -= 1 if count != 0 and \ math.fabs(result*factor) < math.fabs(delta): continue else: break max_its -= count return (result, max_its) def _test(): import doctest doctest.testmod() if __name__ == '__main__': _test()
b35febe7efaee182ac64370d483d77e1aa549c5e
IvanLpJc/python-course
/funciones_avanzadas/funciones_generadoras.py
507
4.09375
4
# Son funciones que generan valores "sobre la marcha" range(0,11) # Genera valores desde 0 a 10, es lo mismo que decir range(11) for numero in range(0,11): print(numero) print("*************************************") def pares(maximo): for numero in range(maximo): if(numero % 2 == 0): yield numero # En lugar de return, utilizamos yield, que no detiene la ejecución # en este caso suelta un numero par cada vez que lo encuentra for numero in pares(11): print(numero)
98fd3091349b02bc33cfa1210060b4c02cdf1866
SatishMonad/test_practice
/PythonP/LGVariable.py
102
3.609375
4
x = "patidar" def myfunc(): x = "satish" print("This is " + x) myfunc() print("This is " + x)
72d4ee48186ea4eecea8124dc5bc0e249069b0e1
bhoffco/lc101
/crypto/caesar.py
475
4.25
4
from helpers import alphabet_position, rotate_character def encrypt(letters, rot): encrypted = "" for i in letters: if i.isalpha(): encrypted = encrypted + rotate_character(i, rot) else: encrypted = encrypted + i return encrypted def main(): letters = input("What would you like to encrpt? ") rot = int(input("What is the rotation? ")) print(encrypt(letters, rot)) if __name__ == "__main__": main()
c8812ed95984048b2964fdcc399f7093c8cd5859
markomamic22/PSU_LV
/LV1/Drugi.py
368
3.90625
4
ocjena = -1.0 while ((ocjena < 0.0) or (ocjena > 1.0)): ocjena = float(input("Unesite broj između 0 i 1: ")) def cases(ocjena): if(ocjena >= 0.9): print('A') elif(ocjena >= 0.8): print('B') elif(ocjena >= 0.7): print('C') elif(ocjena >= 0.6): print('D') elif(ocjena < 0.5): print('F') cases(ocjena)
af7cd7f4e11d845d65e6b2080e59350ed28253db
kaushik853/lpthw_python_3
/zed-python/got.py
4,740
3.9375
4
from sys import exit from textwrap import dedent class Scene(object): print("Nothing is written yet") def enter(self): print("I need to write it") exit(1) class Start(Scene): def enter(self): print(dedent( """ You are starting the Game Of Thrones. Would you survive in the Seven Kingdoms? In the game of thrones,you win or you die... """)) print(dedent(""" You need to choose whether you are a 'Lover' or 'Fighter' in GoT """)) choice = input("lover or fighter >") if choice == 'lover': char1 = Lover() char1.enter() elif choice == 'fighter': char2 = Fighter() char2.enter() class Lover(object): def dwarf(): dwarf_status = input("Are you a dwarf >") if dwarf_status == 'yes': print(dedent("""Stay low and you'll die at the ripe age of 80, with a belly full of wine and a maiden's mouth around your cock.If you can keep your mouth shut,thats it """)) elif dwarf_status == 'no': girl_status = input("Are you a girl>") if girl_status == 'yes': print("War is easier than daugthers. you may live,if you are willing to get bloody") elif girl_status == 'no': print("Pray for oak and Iron to guard you well or Else you're dead and doomed to hell.Winter is coming") def enter(self): print(dedent("""You choose to be a Lover in GoT!!!..we proceed""")) family_hist = input(" Does your family have a hostory to marry their siblings? >") if family_hist == 'yes': victory_will = input(" Are you willing to do anything for victory ?>") if victory_will == 'yes': print("You cant wake the dragon and it cost you your life..so you die") elif victory_will == 'no': dragon_awaken = input("Do you know how to wake up the dragon?") if dragon_awaken == 'yes': print("You are the blood of the dragon..fire can not kill you,but swords can.Tread carefully..Khaleesi!!") elif dragon_awaken == 'no': Lover.dwarf() elif family_hist == 'no': sibling_like = input("Would you like to marry siblings?>") if sibling_like == 'yes': print("The things you do for love may one day get you killed") elif sibling_like == 'no': Lover.dwarf() class Fighter(object): def king(): print("You need to answer a call") king_call = input("Do you call yourself a King? ") if king_call == 'yes': kill_all = input("Do you want to kill all those who oppose you?") if kill_all == 'yes': print(dedent("""A good king knows when to save his strength and when to destroy his enemies. you are not a good king """)) elif kill_all == 'no': print(dedent(""" Laws are tedious business and counting coppers worse If boredom doesn't kill you, your subjects will """)) elif king_call == 'no': kill_king = input("Do you kill kings?") if kill_king == 'yes': print(dedent("""You'll be loved for a kindness. You never did and reviled for your finest act, but you'll probably live for a time King of The North """)) elif kill_king == 'no': print("Pray for oak and Iron to guard you well or Else you're dead and doomed to hell.Winter is coming") def enter(self): print(dedent("""You choose to be a Fighter in GoT!!!..we proceed""")) bound = input("Are you bound by duty and honor?") if bound == 'yes': meddle_life = input("Does your duty and honor cause you to meddle into the lives of kings?") if meddle_life == 'yes': print("Valor is a poor substitute for numbers. you'll have an honorable death,but You'll still be dead") elif meddle_life == 'no': bro_night_watch = input("Are you a brother of the night's watch?") if bro_night_watch == 'yes': print("Long life or Short life, you'll live and die at your watch") elif bro_night_watch == 'no': Fighter.king() elif bound == 'no': Fighter.king() start_GOT = Start() start_GOT.enter()
543605bb3786ffbe4eba77f5d7426a1a31ce1c41
IamTheVine/CS-2
/Celcius_to_Fahrenheit.py
143
4
4
# Converts Celcius to Fahrenheit # By Albert Molina 23-Mar-2018 C = float(input('Enter Celcius: ')) F = (9/5) * C + 32 print(str(F) + ' Fahrenheit')