blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
87c81a7b3e7797bada95933f433016d2b81aaa44
BenThomas33/practice
/python/crack_interview/ch11/sort.py
696
3.546875
4
import copy dic1 = {} for c in "abcdefghijklmnopqrstufwxyz": dic1[c] = 0 def v(str1): global dic1 dic2 = copy.copy(dic1) res = "" for i in str1: if i.lower() in dic2: dic2[i.lower()] += 1 for c in "abcdefghijklmnopqrstufwxyz": if dic2[c] > 0: res += c + str(dic2[c]) return res def sort_for_anagrams(A): dic1 = {} for i in A: if v(i) in dic1: dic1[v(i)] .append(i) else: dic1[v(i)] = [i] res = [] for i in dic1.values(): res.extend(i) return res if __name__ == '__main__': A = ['hahah', 'cccddd', 'aahhh', 'dcdcdc'] print sort_for_anagrams(A)
606bdb4aa1e37eae5b4001246b02b093890d1d39
ctnormand1/active_learning_demonstration
/code/st-app.py
4,622
3.6875
4
import streamlit as st import pandas as pd import sqlite3 import plotly.graph_objects as go import plotly as py import numpy as np from sqlalchemy import create_engine def main(): st.title('Active Learning for AI') st.markdown( """ This is a demonstration of active learning applied to a convolutional neural network for image classification. Data comes from the CIFAR-10 dataset, which is commonly used as an introduction to computer vision. """ ) st.header('What is active learning?') st.markdown( """ Active learning is a set of techniques that allows models to be trained more efficiently with less data. The benefits of active learning are greatest in cases of supervised learning where large quantities of data need to be labeled by human annotators. As opposed to random sampling, active learning provides a level of selectivity to the data that is labeled and added to the training dataset. This ensures that human annotators are labeling the data that will have the greatest impact on the model and lead to more robust predictions. """ ) st.header("What's the benefit?") st.markdown( """ In many cases, active learning can allow a model to reach target accuracy with less training data. The following chart shows the effect of an active learning strategy called uncertainty sampling applied to the CIFAR-10 dataset. """ ) st.write(make_plotly_figure()) st.header('Want to learn more?') st.markdown( """ You absolutely should! Active learning comprises a really useful set of techniques, and I only scraped the surface with the time I had to do this project. Please check out the GitHub repository to learn more about my methodology. If this project sparked your interest, I'd recommend that you read the book [_Human-in-the-Loop Machine Learning_]( https://www.manning.com/books/human-in-the-loop-machine-learning) by Robert Monarch. This book was the inspiration for this project, and it provides fascinating perspective on the intersection of humans and machines. """ ) def make_plotly_figure(): # conn_str ='sqlite:///../data/experiment_data/generated_data.db' conn_str ='sqlite:///../data/experiment_data/2021-09-02-experiment.db' engine = create_engine(conn_str) sql = ''' SELECT a.trial_id, a.batch, a.test_acc, a.config_id, unc_pct FROM (results INNER JOIN trials ON results.trial_id = trials.trial_id) as a INNER JOIN configurations ON a.config_id = configurations.config_id ''' df = pd.read_sql(sql, engine) grouped = df.groupby(['unc_pct', 'batch'])['test_acc'].mean() fig = go.Figure() fig.add_trace( go.Scatter( line=dict(color="#0B88B4", width=3), name='Random Sampling', x=grouped.loc[0].index * 1000, y=grouped.loc[0])) fig.update_yaxes(range=[0, 1], tickformat=',.0%', title='Accuracy') fig.update_xaxes(title='Samples in Training Dataset') fig.update_layout(title=dict(text='Active Learning Demonstration', x=0.12), legend=dict( orientation='h', x=0, y=1.2 )) ix_lvl_1 = grouped.index.get_level_values(0).unique() for x in [i/100 for i in range(101)]: if x in ix_lvl_1: s = grouped.loc[x] else: ix_2 = ix_lvl_1[np.where(ix_lvl_1 >= x)[0][0]] ix_1 = ix_lvl_1[np.where(ix_lvl_1 >= x)[0][0] - 1] s = grouped.loc[ix_1] + (((x - ix_1) / (ix_2 - ix_1)) * (grouped.loc[ix_2] - grouped.loc[ix_1])) fig.add_trace( go.Scatter( visible=False, line=dict(color="#78CCCF", width=3), name="Random and Uncertainty Sampling", x=s.index * 1000, y=s)) # Make 10th trace visible fig.data[1].visible = True # # Create and add slider steps = [] for i in range(len(fig.data) - 1): step = dict( method="update", args=[{"visible": [True] + [False] * len(fig.data)}], label=str(i) + '%' # layout attribute ) step["args"][0]["visible"][i + 1] = True # Toggle i'th trace to visible steps.append(step) # sliders = [dict( active=0, currentvalue={"prefix": "Uncertainty sampling: "}, pad={"t": 50}, steps=steps, )] # fig.update_layout( sliders=sliders ) return fig if __name__ == '__main__': main()
dca325135ed210e7b0180cede1f885ec8fa1be57
GusW/python_main
/study/concurrency/threads_concurrent_futures.py
1,069
3.53125
4
import concurrent.futures from datetime import datetime from time import perf_counter, sleep def _sync_sec(seconds: float) -> None: sleep(seconds) return f'{datetime.now()} - dummy sleep {seconds}s' if __name__ == "__main__": time_init = perf_counter() with concurrent.futures.ThreadPoolExecutor() as executor: # submit returns future objects results = [executor.submit(_sync_sec, 2.5) for _ in range(100)] # need to call as_completed to return from the futures list(map(lambda x: print(x.result()), concurrent.futures.as_completed(results))) print( f'Time elapsed with submit/as_completed => {round(perf_counter()-time_init, 2)}s') # OR time_init = perf_counter() with concurrent.futures.ThreadPoolExecutor() as executor: items = [2.5] * 100 # executor map will submit and return to a whole iterable results = executor.map(_sync_sec, items) list(map(print, results)) print(f'Time elapsed with map => {round(perf_counter()-time_init, 2)}s')
a9b508fe2073e966fe3cc3016bbe22dcdf3f723f
JorgeLuisCampos/Python-Course
/Python101 GitHub/Mis Ejercicios/Objetos_Baraja.py
720
3.71875
4
# -*- coding: utf-8 -*- import random class Baraja(object): def __init__(self): self.palos = ["Espadas", "Corazones", "Tréboles", "Diamantes"] self.rangos = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "As"] self.maso = [] for palo in self.palos: for rango in self.rangos: self.maso.append(rango + " de " + palo) def barajear(self): random.shuffle(self.maso) def repartir(self): print(self.maso.pop()) # self.maso.pop(0) """ Usando (instanciando) el objeto """ baraja = Baraja() baraja.barajear() baraja.repartir() baraja.repartir() baraja.repartir() baraja.repartir() baraja.repartir()
50371d4da016af406987835b389afc4b92c34640
himnsuk/Python-Practice
/Interview/Array/rearrange.py
210
3.84375
4
def rearrange(A): for i in range(len(A)): A[i:i+2] = sorted(A[i:i+2], reverse = i%2) return A A = [i for i in range(1,11)] print(rearrange(A)) # Output => [1, 3, 2, 5, 4, 7, 6, 9, 8, 10]
6950477c0a04b6cf7861496e7fbfbfa0b850bab2
arinablake/python
/homework1.py
4,301
4.375
4
# Ask for the total price of the bill, then ask how many diners there are. # Divide the total bill by the number of diners and show how much each person must pay. bill_total = float(input('What is a bill total?')) diners = int(input('How many diners are?')) each_person_pays = bill_total / diners print(f'Each person has to pay {round(each_person_pays, 2)}') # Write a program that will ask for a number of days and # then will show how many hours, minutes and seconds are in that number of days. num_days = int(input('Enter the number of days ')) hours = num_days * 24 minutes = hours * 60 seconds = minutes * 60 print(f'In {num_days} days: {hours} hours, {minutes} minutes, {seconds} seconds') # Task the user to enter a number over 100 and then enter a number under 10 # and tell them how many times the smaller number goes into the larger number in a user-friendly format. num1 = int(input('Enter the number over 100 ')) num2 = int(input('Enter the number under 10 ')) times_bigger = num1 // num2 print(f'{num2} goes into {num1} {times_bigger} times ') # Ask the integer number and return the second power of this number. num = int(input('Enter an integer number ')) second_power = num ** 2 print(f'Second power of {num} is {second_power}') # Ask the integer number and power what you would like to get. Return result num = int(input('Enter an integer number ')) power = int(input('Enter the power ')) num_power = num ** power print(f'{power} power of {num} is {num_power}') # Ask the user to enter their first name and then display the length of their name. name = input('Enter your first name ') print(len(name)) # Ask the user to enter their first name and then ask them to enter their surname. # Join them together with a space between and display the name and the length of the whole name. first_name = input('Enter your first name ') last_name = input('Enter your last name ') name = f'{first_name} {last_name}' print(f'{name} {len(name)}') # Ask the user to enter their first name and surname in lower case. # Change the case to title case and join them together. Display the finished result. first_name = input('Enter your first name in lower case ') last_name = input('Enter your last name in lower case ') name = f'{first_name} {last_name}' print(name.title()) # Enter a random string, which includes only digits. # Write a function sum_digits which will find a sum of digits in this string digits_string = input('Enter a random string, which includes only digits ') result = 0 for i in digits_string: result += int(i) print(result) # Ask the user to enter their favorite color. # If they enter “red”, “RED” or “Red” display the message “I like red too”, # otherwise display the message “I don’t like [color], I prefer red”. fav_color = input('Enter your favorite color ') if fav_color == 'red' or fav_color == 'RED' or fav_color == 'Red': print('I like red too') else: print(f'I don’t like {fav_color}, I prefer red') # Ask the user’s age. # If they are 18 or over, display the message “You can vote”, # if they are aged 17, display the message “You can learn to drive”, # if they are 16, display the message “You can buy a lottery ticket”, # if they are under 16, display the message “You can go Trickor-Treating”. age = int(input('What is your age? ')) if age >= 18: print('You can vote') elif age == 17: print('You can learn to drive') elif age == 16: print('You can buy a lottery ticket') else: print('You can go Trickor-Treating') # Ask the user to enter a number. # If it is under 10, display the message “Too low”, # if their number is between 10 and 20, display “Correct”, otherwise display “Too high”. num = int(input('Enter a number ')) if num < 10: print('Too low') elif num < 20: print('Correct') else: print('Too high') # Ask the user to enter 1, 2, or 3. # If they enter a 1, display the message “Thank you”, # if they enter a 2, display “Well done”, # if they enter a 3, display “Correct”. If they enter anything else, display “Error message”. num = int(input('Enter a number 1, 2, or 3 ')) if num == 1: print('Thank you') elif num == 2: print('Well done') elif num == 3: print('Correct') else: print('Error message')
f1556a2e3331538d6c657002a40bf558694ad319
Allen-C-Guan/Leetcode-Answer
/python_part/Leetcode/Data Structure/BinaryTree/Medium/114. Flatten Binary Tree to Linked List/Solution.py
895
4
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ''' 题中没有说要求,但是要求是用pre-order来展开。所以我们就用preorder。 思路为: 1. 我们把right subtree 放在left subtree的最右下角的位置 2. 把left subtree 放在 right subtree的位置 3. left subtree 清零。 ''' class Solution: def flatten(self, root: TreeNode) -> None: if root is None: return if root.left is not None: if root.right is None: root.right = root.left else: cur = root.left while cur.right: cur = cur.right cur.right = root.right root.right = root.left root.left = None self.flatten(root.right)
0b9bbac65d96a6263739322dccb5adda2286fc70
kiettran95/Wallbreakers_Summer2019
/week2/python/NumberOfAtoms_726.py
1,482
3.59375
4
class Solution: def countOfAtoms(self, formula: str) -> str: stack = [] i = 0 while i<len(formula): atom=formula[i] i += 1 if atom == ("("): stack+="(" elif atom == (")"): num = "" while i<len(formula) and formula[i].isdigit(): num+=formula[i] i+=1 num = int(num) if num else 1 temp=[] while stack and stack[-1] != "(": (a,b) = stack.pop() temp.insert(0,(a,b*num)) stack.pop() stack.extend(temp) else: while i<len(formula) and formula[i].islower(): atom+=formula[i] i+=1 count = "" while i<len(formula) and formula[i].isdigit(): count+=formula[i] i+=1 stack.append((atom, int(count) if count else 1)) saved=dict() for (atom, count) in stack: if atom not in saved: saved[atom] = 0 saved[atom] += count print(saved) ans=str() for (atom,count) in sorted(saved.items()): ans+=atom if count==1 else atom+str(count) return ans
1db011f86bf6951518d716c9ce450bc1816edfcd
DakEnviy/om-lab1
/algo/find_min_golden_ratio.py
904
3.6875
4
from math import sqrt def find_min_golden_ratio(func, left, right, epsilon): x1 = left + ((3 - sqrt(5)) / 2) * (right - left) x2 = right - ((3 - sqrt(5)) / 2) * (right - left) val1 = func(x1) val2 = func(x2) while (right - left) > epsilon: if val1 == val2: left = x1 right = x2 x1 = left + ((3 - sqrt(5)) / 2) * (right - left) x2 = right - ((3 - sqrt(5)) / 2) * (right - left) val1 = func(x1) val2 = func(x2) if val2 < val1: left = x1 x1 = x2 x2 = right - ((3 - sqrt(5)) / 2) * (right - left) val1 = val2 val2 = func(x2) if val1 < val2: right = x2 x2 = x1 x1 = left + ((3 - sqrt(5)) / 2) * (right - left) val2 = val1 val1 = func(x1) return (left + right) / 2
0b310149a136736f59e734e2d95c9dd6681813f8
Prempatrick/Python-Projects
/Machine Learning/predictive2.py
1,457
3.765625
4
import pandas as pd import numpy as np import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler fruits=pd.read_csv("https://raw.githubusercontent.com/susanli2016/Machine-Learning-with-Python/master/fruit_data_with_colors.txt", delimiter="\t") #There are four types of fruits fruits.fruit_name.value_counts() ''' orange 19 apple 19 lemon 16 mandarin 5 ''' # plotting the same sns.countplot(fruits['fruit_name']) # Plotting the box plots for the fruits.drop('fruit_name', axis=1). plot(kind='box', layout=(3,3),sharex= False, sharey=False, subplots=True, figsize=(9,9)) sns.pairplot(fruits.drop('fruit_name', axis=1)) # To build model we create target variables and predictors feature_names= ['mass', 'width', 'height', 'color_score'] X= fruits[feature_names] y= fruits['fruit_label'] X.describe() X_train,X_test,y_train, y_test= train_test_split(X,y,test_size=0.2) scaler= MinMaxScaler() X_train= scaler.fit_transform(X_train) X_test= scaler.fit_transform(X_test) # Building Logistic Regression from sklearn.linear_model import LogisticRegression logreg= LogisticRegression() modellog1= logreg.fit(X_train,y_train) modellog1.score(X_train,y_train) # Implementing the Decision Tree from sklearn.tree import DecisionTreeClassifier clf= DecisionTreeClassifier() modelclass1= clf.fit(X_train,X_test) modelclass1.fit()
40ec3c29b9b9d9a0192e88ff80070245809eadf2
CarlosG4rc/CursoPy
/Curso Python/Diccionarios.py/diccionarios.py
1,066
3.96875
4
colores = {'amarillo':'yellow','azul':'blue','verde':'green'} print(colores) print(colores['azul']) numeros = {10:'diez',20:'veinte'} print(numeros[10]) colores['amarillo'] = 'white' print(colores) del(colores['amarillo']) print(colores) edades = {'Hector':27, 'Juan':45, 'Maria':34} print(edades) edades['Hector']+=1 print(edades) for edad in edades: #no se accede a las edades si no a las palabras clave print(edad) for clave in edades: #de esta manera si accedemos a los datos, por medio de la s claves print(edades[clave]) for clave in edades: print(clave,edades[clave]) for clave,valor in edades.items(): print(clave,valor) personajes = [] #lista p = {'Nombre':'Gandalf', 'Clase':'Mago', 'Raza':'Humano'} personajes.append(p) print(personajes) p = {'Nombre':'Legolas', 'Clase':'Arquero', 'Raza':'Elfo'} personajes.append(p) p = {'Nombre':'Gimli', 'Clase':'Guerrero', 'Raza':'Enano'} personajes.append(p) print(personajes) for p in personajes: print(p['Nombre'],p['Clase'],p['Raza'])
ef89ad9f4303df3eec45b521bb904d0785bcfeb7
MarHakopian/Intro-to-Python-HTI-3-Group-2-Marine-Hakobyan
/Homework_5/is_palindrome2.py
308
4.1875
4
def is_palindrome(text): if len(text) <= 1: return True elif len(text) > 1 and text[0] == text[-1]: text = text[1:-1] return is_palindrome(text) else: return False input_text = input("Please enter the text: ") print("Yes" if is_palindrome(input_text) else "No")
6898cbe0127f0154f89f42e45c0f2ad8a6a095b1
IgorEM/Estudos-Sobre-Python
/operadores.py
104
3.703125
4
x = 2 y = 3 soma = x + y print ( x == y) print ( x < y) print (soma > y) print (soma == (y + x))
e7eeee22a1e5e38d645ad982b2dfe6aca7d07ab4
vismantic-ohtuprojekti/qualipy
/qualipy/filters/multiple_salient_regions.py
4,637
3.859375
4
""" Filter for detecting multiple salient regions. The detection works by first extracting the full saliency map using an object extraction algorithm. The saliency map is binarized using a threshold which is calculated individually for each image as the weighted average of 3/4 of the biggest saliency values. Using this threshold, the image is binarized into solid regions. All regions and their sizes are calculated using OpenCV's contour detection. The actual prediction is constructed by dividing the sum of of the areas of all the regions by the area of the largest region and squaring the result. This way if the saliency map contains some small independent areas, the whole image is not considered to have multiple salient regions. """ import cv2 import numpy from ..utils.image_utils import read_image from ..utils.object_extraction import extract_object from filter import Filter def count_threshold(saliency_map): """Calculates the threshold used for the binarization. Calculated as the weighted average of 3/4 of the biggest saliency values. :param saliency_map: the full saliency map :type saliency_map: numpy.ndarray :returns: int -- the threshold """ rounded_saliency_map = numpy.around(saliency_map, decimals=-1) unique, count = numpy.unique(rounded_saliency_map, return_counts=True) smallest_large_index = unique.shape[0] * 3 / 4 return numpy.average(unique[-smallest_large_index:], axis=0, weights=count[-smallest_large_index:]) def count_areas(saliency_map): """Returns a list of areas of all coherent white regions produced by binarization using a calculated threshold. :param saliency_map: the full saliency map :type saliency_map: numpy.ndarray :returns: numpy.ndarray -- list of the areas of the regions """ # count threshold and use it to binarize the saliency map limit = count_threshold(saliency_map) _, thresh = cv2.threshold(saliency_map, limit, 255, cv2.THRESH_BINARY) # find coherent regions contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) return numpy.array([cv2.contourArea(contour) for contour in contours]) class MultipleSalientRegions(Filter): """Filter for detecting images with multiple salient regions""" name = 'multiple_salient_regions' speed = 5 def __init__(self, threshold=0.5, invert_threshold=False, is_saliency_map=False): """Initializes a multiple salient regions filter :param threshold: threshold at which the given prediction is changed from negative to positive :type threshold: float :param invert_threshold: whether the result should be greater than the given threshold (default) or lower for an image to be considered positive :type invert_threshold: bool :param: is_saliency_map: whether the given image is already a saliency map :type is_saliency_map: bool """ super(MultipleSalientRegions, self).__init__(threshold, invert_threshold) self.is_saliency_map = is_saliency_map def predict(self, image_path, return_boolean=True, ROI=None): """Predict if a given image has multiple salient regions :param image_path: path to the image :type image_path: str :param return_boolean: whether to return the result as a float between 0 and 1 or as a boolean (threshold is given to the class) :type return_boolean: bool :param ROI: possible region of interest as a 4-tuple (x0, y0, width, height), None if not needed :returns: the prediction as a bool or float depending on the return_boolean parameter """ if self.is_saliency_map: saliency_map = read_image(image_path, ROI) else: saliency_map, _ = extract_object(image_path) areas = count_areas(saliency_map) # if areas is empty, there are no salient regions in the image if not areas.shape[0]: return False if return_boolean else 0. prediction = (numpy.sum(areas) / numpy.amax(areas)) ** 2 - 1.0 prediction = min(prediction, 1) # limit prediction to range [0, 1] if return_boolean: return self.boolean_result(prediction) return prediction
72e842199274cb7619b28a598cc2f9dd6c8ad469
770120041/DataMiningWebsite
/polls/logic/Classification/DT.py
1,877
3.71875
4
# Descision Tree Algorithm import pandas as pd # Function importing Dataset def importdata(): balance_data = pd.read_csv( 'https://archive.ics.uci.edu/ml/machine-learning-' + 'databases/balance-scale/balance-scale.data', sep=',', header=None) # Printing the dataswet shape print("Dataset Lenght: ", len(balance_data)) print("Dataset Shape: ", balance_data.shape) # Printing the dataset obseravtions print("Dataset: ", balance_data.head()) return balance_data # Function to split the dataset def splitdataset(balance_data): # Seperating the target variable X = balance_data.values[:, 1:5] Y = balance_data.values[:, 0] # Spliting the dataset into train and test X_train, X_test, y_train, y_test = [],[],[],[] return X, Y, X_train, X_test, y_train, y_test # Function to make predictions def prediction(X_test, clf_object): # Predicton on test with giniIndex y_pred = clf_object.predict(X_test) print("Predicted values:") print(y_pred) return y_pred # Function to calculate accuracy def cal_accuracy(y_test, y_pred): pass # print("Confusion Matrix: ", # confusion_matrix(y_test, y_pred)) # # print("Accuracy : ", # accuracy_score(y_test, y_pred) * 100) # # print("Report : ", # classification_report(y_test, y_pred)) # Driver code def main(): # Building Phase data = importdata() X, Y, X_train, X_test, y_train, y_test = splitdataset(data) # Operational Phase print("Results Using Gini Index:") # Prediction using gini # cal_accuracy(y_test, y_pred_gini) print("Results Using Entropy:") # Prediction using entropy # y_pred_entropy = prediction(X_test, clf_entropy) # cal_accuracy(y_test, y_pred_entropy) # Calling main function if __name__ == "__main__": main()
4feb8447bcad93bf28b8f66657937d95bed03b8b
sahlamina/oop_calculator
/calc2.py
895
4.15625
4
import operators2 class Calc2: def calc(self): num1 = int(input("Please enter your first number ")) num2 = int(input("Please enter your second number ")) operator = input("Which operation will you like to perform +, -, *, /? ") if operator == "+": print(str(num1) + " Plus " + str(num2) + " equals ", operators2.addition(num1, num2)) elif operator == "-": print(str(num1)) + " minus " + str(num2) + " equals ", operators2.subtraction(num1, num2) elif operator == "*": print(str(num1) + " times " + str(num2) + " equals ", operators2.multiply(num1, num2)) elif operator == "/": print(str(num1) + "divided by " + str(num2) + " equals ", operators2.division(num1, num2)) else: print("Please enter a valid input") sharp = Calc2() sharp.calc()
4746e1b74810176d4c0687406fbe7fe954cf8e8e
Fandresena380095/Some-Projects-in-python
/recursion fonctionnel.py
178
3.9375
4
a = int(input("First number : ")) b = int(input("Second number : ")) x = int(input("maximum number : ")) c = a+b while c<x: a=b b=c print(b) c = a+b
e271047cb2e83cf45f676e5fb8c017ccf28e9b1b
dorianbenitez/Homework2_CS4395
/Homework2_drb160130.py
5,726
3.9375
4
####### # File: Homework2_drb160130.py # Author: Dorian Benitez (drb160130) # Date: 9/6/2020 # Purpose: CS 4395.001 - Homework 2 (Word Guessing Game) ####### import sys import nltk from nltk import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords import random # Function to preprocess the raw text def preprocessing(raw): # Tokenize the lowercase raw text tokens = word_tokenize(raw.lower()) # Store the stopwords stop_words = set(stopwords.words('english')) # Reduce the tokens to only those that are alpha, not in the NLTK stopword list, and have length > 5 tokens = [t for t in tokens if t.isalpha() and t not in stop_words and len(t) > 5] # Lemmatize the tokens and use set() to make a list of unique lemmas unique_lemmas = sorted(list(set([WordNetLemmatizer().lemmatize(r) for r in tokens]))) # Do POS tagging on the unique lemmas and print the first 20 tagged items lemmas_unique_tags = nltk.pos_tag(unique_lemmas) # Create a list of only those lemmas that are nouns noun_lemmas = list([x[0] for x in lemmas_unique_tags if x[1].startswith("N")]) # Print the number of tokens and the number of nouns # Calculate the lexical diversity of the tokenized text and output it print('\nNumber of Tokens:', len(tokens)) print('\nNumber of Nouns:', len(noun_lemmas)) print("\nLexical diversity: %.2f" % (len(unique_lemmas) / (len(tokens)))) print('\nFirst 20 Tagged Items:', lemmas_unique_tags[:20]) return tokens, noun_lemmas # Guessing game function def guessing_game(list): # Give the user 5 points to start with user_score = 5 # Randomly choose one of the 50 words in the top 50 list random_word_from_list = random.choice(list)[0] is_in_word = [] guessed_letter = [] print("\n\nScore: ", user_score, "\n") for element in random_word_from_list: print('_', end=" ") # The game ends when the total user score is negative while user_score > -1: user_letter_input = input('\n\nPlease enter a letter: ').lower() # The user is prompted to retry with a proper value if not user_letter_input.isalpha() and user_letter_input != "!": print("\nType a valid letter, please!") # The user is prompted to retry if they entered a duplicate letter elif user_letter_input in guessed_letter: print("\nYou already tried this letter, try again!") # The game ends when the user enters ‘!’ elif user_letter_input != "!": # Populate a list that holds all user guesses guessed_letter.append(user_letter_input) # If the letter is in the word, fill in all matching letter _ with the letter and add 1 point to the user score if user_letter_input in random_word_from_list: user_score += 1 is_in_word.append(user_letter_input) print("\nThis letter IS in the word") # If the letter is not in the word, subtract 1 from the user score and print message else: print("\nThis letter is NOT in the word") user_score -= 1 # Update and print the current state of the game count = 0 for element in random_word_from_list: if element in is_in_word: print(element, end=" ") count += 1 else: print('_', end=" ") # Right or wrong, give user feedback on their score for this word after each guess print("\nScore:", user_score) # Game ends if the user guesses the word correctly if count == len(random_word_from_list): # Ask the user if they want to play again play_again_decision = input("\n\nCongrats, you won!!! Play again? (Y/N) ") if play_again_decision.lower() == "y": guessing_game(list) else: print("\nThank you for playing!") sys.exit(0) else: print("\nThank you for playing!") sys.exit(0) # Keep a cumulative total score and end the game if it is negative print("\n\nYou lost by score...the word was:", random_word_from_list) # Ask the user if they want to play again play_again_decision = input("\nPlay again? (Y/N) ") if play_again_decision.lower() == "y": guessing_game(list) else: print("\nThank you for playing!") sys.exit(0) if __name__ == '__main__': # Send the filename to the main program in a system argument. # If no system arg is present, print an error message and exit the program. if len(sys.argv) > 1: input_file = sys.argv[1] print('Input file: ', input_file) with open('anat19.txt', 'r') as f: raw_text = f.read() tokens, noun_lemmas = preprocessing(raw_text) common_list = [] # Dictionary of {noun:count of noun in tokens} items from the nouns and tokens lists counts = {t: tokens.count(t) for t in noun_lemmas} # Sort the dictionary by count and print the 50 most common words and their counts # Save these words to a list because they will be used in the guessing game sorted_counts = sorted(counts.items(), key=lambda x: x[1], reverse=True) print("50 most common words:") for i in range(50): common_list.append(sorted_counts[i]) print(sorted_counts[i]) # Start a guessing game with the list of 50 words guessing_game(common_list) else: print('File name missing')
aefe35f5176ef9f984fe703f2bcc82cd5e578a44
maybemichael/sudoku
/leetcode.py
6,460
3.890625
4
# Definition for singly-linked list. class ListNode2: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: new_list = ListNode() current = new_list # value1 = 0 # value2 = 0 carry = 0 nodes1 = [] nodes2 = [] while l1 or l2 is not None: if l1: value1 = l1.val l1 = l1.next else: value1 = 0 if l2: value2 = l2.val l2 = l2.next else: value2 = 0 print(f"Value 1: {value1}, Value 2: {value2}") total = value1 + value2 + carry print(f"After *** Value 1: {value1}, Value 2: {value2}") merp = total % 10 print(f"This is the total: {merp}") nodes1.append(value1) nodes2.append(value2) print(f"Nodes 1: {nodes1}, Nodes 2: {nodes2}") carry = total // 10 print(f"Carry // 10: {carry}") current.next = ListNode(total % 10) print(f"Current Next Value: {current.next.val}") current = current.next if carry > 0: current.next = ListNode(carry) return new_list.next def detectCycle(head: ListNode) -> ListNode: single = head double = head visited = set() while single: if double.next: double = double.next if single not in visited: visited.add(single) if single.next: single = single.next if double in visited: return double if double.next: double = double.next # if double.next.next: # double = double.next.next # if single.next: # single = single.next # if double is single: # return single # if double.next: # double = double.next # if double.next: # double = double.next return ListNode(-1) m_node1 = ListNode(3) m_node2 = ListNode(2) m_node3 = ListNode(0) m_node4 = ListNode(-4) m_node1.next = m_node2 m_node2.next = m_node3 m_node3.next = m_node4 m_node4.next = m_node1 m_node5 = ListNode(1) m_node6 = ListNode(1) m_node7 = ListNode(2) m_node6.next = m_node7 m_node7.next = m_node6 x = detectCycle(m_node1) # print(x.val) x = detectCycle(m_node6) # print(x.val) node1 = ListNode(2) node2 = ListNode(4) node3 = ListNode(3) node1.next = node2 node2.next = node3 node4 = ListNode(5) node5 = ListNode(6) node6 = ListNode(4) node7 = ListNode(3) node4.next = node5 node5.next = node6 # node6.next = node7 node8 = ListNode(7) node9 = ListNode(3) node8.next = node9 node10 = ListNode(0) node11 = ListNode(1) node12 = ListNode(8) node11.next = node12 node13 = ListNode(0) node14 = ListNode(5) node15 = ListNode(5) solution = Solution() # x = solution.addTwoNumbers(node1, node4) # y = solution.addTwoNumbers(node10, node8) # z = solution.addTwoNumbers(node11, node13) # q = solution.addTwoNumbers(node14, node15) # while x: # print(f"This is x: {x.val}") # x = x.next # while y: # print(f"This is y {y.val}") # y = y.next # while z: # print(f"This is y {z.val}") # z = z.next # while q: # print(f"This is y {q.val}") # q = q.next def two_strings(s1, s2): char_set = set(s1) for c in s2: if c in char_set: return "YES" return "NO" nums = [2, 7, 11, 15] target = 9 def twoSum(nums: [int], target: int) -> [int]: quickness = set(nums) for num in nums: goal = target - num if goal in quickness: index1 = nums.index(num) index2 = nums.index(goal) return [index1, index2] nums2 = [3,2,4] target2 = 6 nums3 = [3, 3] target3 = 6 nums4 = [2222222,2222222] target4 = 4444444 def twoSum2(nums: [int], target: int) -> [int]: for i in range(len(nums)): goal = target - nums[i] index1 = i original = nums[i] nums[i] = target + 1 quickness = set(nums) if goal in quickness: index2 = nums.index(goal) return [index1, index2] nums[i] = original def twoSum3(nums: [int], target: int) -> [int]: keys = [num for num in nums] values = [item for item in range(len(nums))] quickness = dict(zip(keys, values)) for i in range(len(nums)): goal = target - nums[i] if goal in quickness: if i is not quickness[goal]: return [i, quickness[goal]] def twoSum4(nums: [int], target: int) -> [int]: for i in range(len(nums)): goal = target - nums[i] for j in range(i + 1, len(nums)): if goal == nums[j]: print(i) return [i, j] # x = twoSum4(nums, target) # print(f"This is x: {x}") # x = twoSum4(nums2, target2) # print(f"This is x: {x}") # x = twoSum4(nums3, target3) # print(f"This is x: {x}") # x = twoSum4(nums4, target4) # print(f"This is x: {x}") test1 = "abacabad" test2 = "abacabaabacaba" def first_not_repeating_character(s): counted_set = dict() for i in range(len(s)): letter = s[i] if letter in counted_set: counted_set[letter] += 1 else: counted_set.setdefault(letter, 1) for letter in s: if counted_set[letter] is 1: return letter return "_" x = first_not_repeating_character(test2) print(f"This is x: {x}") # print(f"This is repeating: {counted_set}") head1 = [10, 20, 30, 40, 50] k1 = 1 class ListNode(object): def __init__(self, x): self.value = x self.next = None def remove_kth_from_end(head, k): order = [] current = head previous = current count = 0 while current is not None: if count % k is 0: previous = current current = current.next print(f"Previous: {previous.val}, Current: {current.val}") one = ListNode(20) two = ListNode(19) three = ListNode(18) four = ListNode(17) five = ListNode(16) six = ListNode(15) seven = ListNode(14) eight = ListNode(13) nine = ListNode(12) ten = ListNode(11) one.next = two two.next = three three.next = four four.next = five five.next = six six.next = seven seven.next = eight eight.next = nine nine.next = ten remove_kth_from_end(one, 0)
e92ac6ffc4b95c08f7b142981e298cbb0586778c
nishaagrawal16/Datastructure
/Tree/simple_tree/sum_of_precedence_nodes.py
1,376
3.78125
4
# Date: 13-Dec-2019 # Sum of precedence of Nodes # 10(120) # / \ # 20(90) 30(30) # / \ # 40(40) 50(50) # O(n) # TODO class Node: def __init__(self, value): self.info = value self.left = None self.right = None class Tree: def __init__(self): self.root = None def createTree(self): n1 = Node(10) n2 = Node(20) n3 = Node(30) n4 = Node(40) n5 = Node(50) self.root = n1 n1.left = n2 n1.right = n3 n2.left = n4 n2.right = n5 def SumOfPrecedence(self, root): if root: precedence_sum = 0 self.SumOfPrecedence(root.left) self.SumOfPrecedence(root.right) print(root.info, end=' ') if root.left: precedence_sum = precedence_sum + root.left.info if root.right: precedence_sum = precedence_sum + root.right.info if precedence_sum: root.info = precedence_sum print("Sum of nodes precedence: ", root.info) def main(): print('***************** TREE ******************\n') t = Tree() t.createTree() t.SumOfPrecedence(t.root) if __name__ == '__main__': main() # Output: # ------- # # ***************** TREE ****************** # # 40 Sum of nodes precedence: 40 # 50 Sum of nodes precedence: 50 # 20 Sum of nodes precedence: 90 # 30 Sum of nodes precedence: 30 # 10 Sum of nodes precedence: 120
56fafa70d945a08fca789249729e155fbc8e5139
javedinfinite/practice_questions
/no_equal_pair_indices.py
566
3.703125
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def getCount(A,val): c = 0 for i, v in enumerate(A): if(val==v): c+=1 return c def solution(A): # write your code in Python 3.6 c = 0 original_list = A.copy() unique_list = list(set(A)) print(original_list) print(unique_list) for item in unique_list: count = getCount(original_list, item)-1 print(count) c+=count return c test = [3,5,6,3,3,5] # test = [3,3,3] print(solution(test))
84370f5d7a00c09ec8ad5208955a780236158e1a
UdhaikumarMohan/Strings-and-Pattern
/Remove/dirty_1.py
522
4.125
4
# Write code to remove the all occurrence of a dirty word from a given sentence. def dirty_1(String,word): str ="" li = String.lower().split() for a in li: if not (a==word or a[:-1]==word): str+=a+" " return str String = """Indian Goverment cancelled the special status of jammu and kashmir, and divided it into two union territories named kashmir and ladakh. These partition was opposed by the state leaders of jammu and kashmir""" word = "kashmir" print(dirty_1(String,word))
d4e6dd4094689ca754b37094de8709a36ec9bdd5
Vinicius-de-Morais/Exercicios
/Desafios/Desafio_1.py
944
3.8125
4
import random as r funcionarios = [] def adiciona_funcionario(): contador = 0 while len(funcionarios) <= 9: funcionario = input('Qual o nome do Funcionario?\n') salario = float(input('Qual o salario?\n')) combo = [funcionario,salario] funcionarios.append(combo) contador += 1 if contador == 3: for x in range(len(funcionarios)): salario = funcionarios[x][1] salario += round((salario * 0.05), 2) funcionarios[x].insert(1, salario) funcionarios[x].pop(2) contador = 0 for x,y in funcionarios: print(f'Nome: {x} Salario: {y}') sorteado = r.choice(funcionarios) sorteado[1] += round(sorteado[1] * 0.10, 2) print(f'''Parabens ao funcionario {sorteado[0]} ele foi sorteado e gratificado com 10% de aumento Agora seu salário é de {sorteado[1]}''') adiciona_funcionario()
d42d871a9ec36f3cca1ff020f1d43f254f514ac0
deepika-jaiswal/hands_on_python
/checkeoro.py
92
4.0625
4
num=int(input()) if (num%2==0): print("no is even") else: print("no is odd")
fd70132321f3270561c8a17fc34e95a3ba0ab4e9
jf20541/Multi-LinearRegressionModel
/src/MR_data.py
587
3.546875
4
import pandas as pd import MR_config def clean_data(data): """Clean xlsx file, set index, replace NaN values, convert to csv file Args: data [float]: set data as pandas dataframe """ data = data.set_index("Year") data = data.astype(float) if data.isnull().values.any() == False: data.to_csv(MR_config.CLEAN_DATA, index_label=False) print("No Null-Values found") else: print("Null-Values found and fillna") if __name__ == "__main__": df = pd.DataFrame(pd.read_excel(MR_config.TRAINING_FILE)) clean_data(df)
c9f973c4afd9c7ac5283dad3d88ab52879382303
StechAnurag/python_basics
/28_for_loop.py
910
4.3125
4
# FOR Loop # Iterables in python - Lists, Tuples, Sets, Dictionary, Strings for item in 'Zero to mastery': print(item) # with lists for el in [1, 2, 3, 4, 5]: print(el) # with sets for el in {1, 2, 3, 4}: print(el) # with tuples for i in (1, 2, 4): print(i) # Nested for loops for item in [1, 2, 3]: for el in ['x', 'y', 'z']: print(item, el) # with dict bird = { 'name' : 'Swan', 'can_fly': True, 'can_swim': True, 'avg_weight': 2.5 } for item in bird: print(item) # prints the keys not values for item in bird.items(): print(item) # prints a tuple of (key,value) # improved version of above for item in bird.items(): key,value = item # tuple unpacking print(key,value) # Shorthand vesrsion of above for key, value in bird.items(): print(key, value) for item in bird.values(): print(item) # prints value for item in bird.keys(): print(item) # prints the keys
87928877afe839b0a8cc13281273a86e3611ca13
trojanosall/Python_Practice
/Basic_Part_1/Solved/Exercise_79.py
676
4.25
4
# Write a Python program to get the size of an object in bytes. import sys str1 = "one" str2 = "four" str3 = "three" str4 = "THREE" myint = 1698 myfloat = 1896.36983 print() print("Memory size of " + str1 + " = " + str(sys.getsizeof(str1)) + " bytes") print("Memory size of " + str2 + " = " + str(sys.getsizeof(str2)) + " bytes") print("Memory size of " + str3 + " = " + str(sys.getsizeof(str3)) + " bytes") print("Memory size of " + str4 + " = " + str(sys.getsizeof(str4)) + " bytes") print("Memory size of " + str(myint) + " = " + str(sys.getsizeof(myint)) + " bytes") print("Memory size of " + str(myfloat) + " = " + str(sys.getsizeof(myfloat)) + " bytes")
9a5d70da3a61889d9c0b69f03f33bd7d54205a0a
adipixel/conding-questions
/DataStructures/Tree/level_order_traversal.py
478
3.984375
4
""" Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.data (the value of the node) """ def levelOrder(root): if root == None: return queue = [] queue.append(root) while(len(queue) > 0): print queue[0].data, node = queue.pop(0) if node.left != None: queue.append(node.left) if node.right != None: queue.append(node.right)
9b450808fa1cf936782f3af43d557c2287df09f5
EvgeniyBudaev/python_learn
/options/deep_and_shallow_copy.py
1,592
4.4375
4
import copy list1 = [1, 2, 3, [4, 5, 6]] copied_list = list1.copy() copied_list[3].append(7) print(list1) # [1, 2, 3, [4, 5, 6, 7]] print(copied_list) # [1, 2, 3, [4, 5, 6, 7]] # Поверхностная копия shallow_copy = copy.copy(list1) shallow_copy[3].append(8) print(list1) # [1, 2, 3, [4, 5, 6, 7, 8]] print(copied_list) # [1, 2, 3, [4, 5, 6, 7, 8]] # Глубокое копирование deep_copy = copy.deepcopy(list1) deep_copy[3].append(9) print(list1) # [1, 2, 3, [4, 5, 6, 7, 8]] print(deep_copy) # [1, 2, 3, [4, 5, 6, 7, 8, 9]] class Point(): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})" a = Point(1, 2) b = copy.copy(a) a.x = 3 print(a) # Point(3, 2) print(b) # Point(1, 2) class Line(): def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 def __copy__(self): # так работает неглубокое копирование cls = self.__class__ result = cls.__new__(cls) result.__dict__.update(self.__dict__) return result def __deepcopy__(self, memo): # рекурсивное копирование всех объектов cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result for k, v in self.__dict__.items(): setattr(result, k, copy.deepcopy(v, memo)) return result l1 = Line(a, b) l2 = copy.copy(l1) l1.p1.x = 4 print(l1.p1) # Point(4, 2) print(l2.p1) # Point(4, 2) l3 = Line(a, b) l4 = copy.deepcopy(l3) l3.p1.x = 6 print(l3.p1) # Point(6, 2) print(l4.p1) # Point(4, 2)
4b2a17b97cdc77b61f7e42c8d7418db3ac1daaec
shentong-hbu/Coronary-Artery-Tracking-via-3D-CNN-Classification
/infer_tools_tree/tree.py
609
3.578125
4
# -*- coding: UTF-8 -*- # @Time : 04/08/2020 15:38 # @Author : QYD # @FileName: tree.py # @Software: PyCharm class TreeNode(object): def __init__(self, value, start_point_index, rad=None): self.value = value if rad is not None: self.rad = [[i] for i in rad] else: self.rad = None self.start_point_index = start_point_index self.child_list = [] def add_child(self, node): self.child_list.append(node) def __repr__(self): return 'TreeNode of %d points with %d child nodes'%(len(self.value),len(self.child_list))
afe46128a79ec9bf4b20e3ae7943e3120d48f74f
gutucristian/examples
/ctci/python/Dijkstra/main.py
1,304
3.984375
4
from min_heap import MinHeap from node import Node from graph import Graph heap = MinHeap() graph = Graph() A = Node("A", 0) B = Node("B") C = Node("C") D = Node("D") E = Node("E") F = Node("F") A.add_neighbors(B=3, C=1) B.add_neighbors(A=3, C=1, D=5) C.add_neighbors(A=1, B=1, D=2, E=4) D.add_neighbors(B=5, C=2, E=1, F=6) E.add_neighbors(C=4, D=1, F=3) F.add_neighbors(D=6, E=3) graph.add_nodes(A=A,B=B,C=C,D=D,E=E,F=F) graph.dijkstra(A) print("Shortest path to node F:", end='') graph.print_shortest_path(F) print("\nShortest path to E:", end='') graph.print_shortest_path(E) print("\nShortest path to B:", end='') graph.print_shortest_path(B) # A = (Node("A", 4), 4) # format: (node, priority) # heap.push(A[0], A[1]) # print("min heap: {}".format(heap)) # heap.push(Node("B", 1), 1) # print("min heap: {}".format(heap)) # heap.push(Node("C", 2), 2) # print("min heap: {}".format(heap)) # heap.push(Node("D", 5), 5) # print("min heap: {}".format(heap)) # heap.pop() # E = (Node("E", 3), 3) # print("min heap: {}".format(heap)) # heap.push(E[0], E[1]) # print("min heap: {}".format(heap)) # heap.update_priority(A[0], 1) # print("min heap: {}".format(heap)) # heap.push(Node("F", 9), 9) # print("min heap: {}".format(heap)) # heap.update_priority(A[0], 10) # print("min heap: {}".format(heap))
38b8e3011a60e86db8958e18116cc73a30318cf3
Chewie23/fury-train
/PyProjects/HW_3.py
8,575
3.828125
4
def num_to_str(num): """ 6.8 convert numeric value to read as string ex. 89 -> "eighty-nine" """ ones_db = {1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine"} teens_db = {10:"ten", 11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen", 15:"fifteen", 16:"sixteen", 17:"seventeen", 18:"eighteen", 19:"nineteen"} tens_db = {2:"twenty", 3:"thirty", 4:"forty", 5:"fifty", 6:"sixty", 7:"seventy", 8:"eighty", 9:"ninety"} spelled = [] for n in [1000, 100, 10, 1]: if n == 1000 and num // n > 0: spelled.extend((ones_db[num // n], "thousand")) elif n == 100 and num // n > 0: spelled.extend((ones_db[num // n], "hundred")) elif n == 10 and num // n >= 2: spelled.append(tens_db[num // n]) elif n == 10 and num // n == 1: spelled.append(teens_db[num]) return ' '.join(spelled) elif n == 1 and num // n > 0: spelled.append(ones_db[num // n]) num = num % n return ' '.join(spelled) print(num_to_str(918)) print(num_to_str(849)) print(num_to_str(89)) """Output nine hundred eighteen eight hundred forty nine eighty nine """ def newuser(): """ Adding functionality for 7.5f """ import re db = {} prompt = 'login desired: ' while True: name = input(prompt) an_alpha_numeric_char = True alphanumeric = '^[\w]' for char in name: if re.search(alphanumeric, char) is None: an_alpha_numeric_char = False if not an_alpha_numeric_char: prompt = "Name contains illegal character(s). Try again: " continue if name in db: prompt = 'name taken, try another: ' continue else: break pwd = input('passwd: ') db[name] = pwd """output (N)ew User Login (E)xisiting User Login (Q)uit (R)emove User (S)how Users and Password Enter Choice: n You picked: (n) login desired: SDFSD#$##$%SDGFSGS Name contains illegal character(s). Try again: q passwd: q """ def rot13(sentence): """ 7.10 create an encryption that is a cypher that moves the letter 13 places Ex. a = n; b = o; z = m; w = join """ import string lower_z = 122 cap_Z = 90 rotation = 13 new_sent = [] for char in sentence: if char in string.ascii_lowercase: rot13_char = ord(char) + rotation if rot13_char > lower_z: rot13_char = ord(char) - rotation elif char in string.ascii_uppercase: rot13_char = ord(char) + rotation if rot13_char > cap_Z: rot13_char = ord(char) - rotation else: rot13_char = ord(char) #if out of spec, keep as is! new_sent.append(chr(rot13_char)) return ''.join(new_sent) sentence = "The quick brown Fox Jumped over The lazy Dog" print("before:", sentence) print ("after: ", rot13(sentence), "\n") sentence = "Gur dhvpx oebja Sbk Whzcrq bire Gur ynml Qbt" print("before:", sentence) print ("after: ", rot13(sentence)) """Output before: The quick brown Fox Jumped over The lazy Dog after: Gur dhvpx oebja Sbk Whzcrq bire Gur ynml Qbt before: Gur dhvpx oebja Sbk Whzcrq bire Gur ynml Qbt after: The quick brown Fox Jumped over The lazy Dog """ def num_of_const_vow_words(sentence): """ 8.10 determine the amount of consonants, vowels and words in a string """ vowels = "aioue" vowel_count = 0 consonant_count = 0 word_count = 0 words = sentence.split(" ") for phrase in words: word_count += 1 for char in phrase: if char in vowels: vowel_count += 1 elif char != " ": consonant_count += 1 return (vowel_count, consonant_count, word_count) sentence = "Once more unto the breach, dear friends, once more" print ("The sentence: " + "'" + sentence + "'\nhas %d vowels, %d consonants, %d words" % num_of_const_vow_words(sentence)) """Output The sentence: 'Once more unto the breach, dear friends, once more' has 16 vowels, 26 consonants, 9 words """ def strip_pound_sig(file): """ 9.1 Stripping away any '#' signs in front of the lines in a file """ fo = open(file, "r") print("BEFORE:") for line in fo: print(line.strip("\n")) fo.seek(0) print ("\nAFTER:") for line in fo: no_pound_line = line.strip('#') print (no_pound_line.strip("\n")) strip_pound_sig("document.txt") """Output BEFORE: Once more unto the breach, dear friends, once more; Or close the wall up with our English dead. # In peace there's nothing so becomes a man As modest stillness and humility: #But when the blast of war blows in our ears, Then imitate the action of the tiger; # Stiffen the sinews, summon up the blood, Disguise fair nature with hard-favour'd rage; AFTER: Once more unto the breach, dear friends, once more; Or close the wall up with our English dead. In peace there's nothing so becomes a man As modest stillness and humility: But when the blast of war blows in our ears, Then imitate the action of the tiger; Stiffen the sinews, summon up the blood, Disguise fair nature with hard-favour'd rage; """ def display_num_lines(n, f): """ 9.2 display the first "n" lines of "f" file """ fo = open(f, "r") for i, txt in enumerate(fo): if i <= n: print(txt.strip("\n")) num = int(input("Please enter an integer: ")) f = input("Please enter your file: ") display_num_lines((num - 1), f) """Output Please enter an integer: 3 Please enter your file: document.txt Once more unto the breach, dear friends, once more; Or close the wall up with our English dead. # In peace there's nothing so becomes a man """ def count_lines_of_file(f): """ 9.3 display number of lines in a document """ fo = open(f, "r") num_lines = 0 for num in fo: num_lines += 1 return num_lines f = input("Please enter your file: ") print ("number of lines in file: %d" % count_lines_of_file(f)) """Output Please enter your file: document.txt number of lines in file: 8 """ """ 10.7 a) The first snippet tries Statement A and sees if it yields an error. If no error, then it proceeds to Statement B. This helps use determine if Statement A has an error or not. b) The second snippet tried BOTH statement A and B, and if one yields an error, you will not know which one. If both had errors, then the except will catch only one, and not tell you which raised the error. This is bad since it doesn't tell us anything useful to fix our code. """ def demo_trace(fxn): """ problem 12, HW 3 demo module trace Literally tracks and traces a function through a program/script """ import trace tracer = trace.Trace(count = False, trace = True) tracer.run(fxn) sentence = "H" fxn = "rot13(sentence)" demo_trace(fxn) """Output --- modulename: HW_3, funcname: <module> <string>(1): --- modulename: HW_3, funcname: rot13 HW_3.py(65): import string HW_3.py(67): lower_z = 122 HW_3.py(68): cap_Z = 90 HW_3.py(69): rotation = 13 HW_3.py(71): new_sent = [] HW_3.py(72): for char in sentence: HW_3.py(73): if char in string.ascii_lowercase: HW_3.py(77): elif char in string.ascii_uppercase: HW_3.py(78): rot13_char = ord(char) + rotation HW_3.py(79): if rot13_char > cap_Z: HW_3.py(83): new_sent.append(chr(rot13_char)) HW_3.py(72): for char in sentence: HW_3.py(84): return ''.join(new_sent) --- modulename: trace, funcname: _unsettrace trace.py(77): sys.settrace(None) """ def demo_timeit(): """ problem 12, HW 3 demo the module timeit module times the performance of a statement/function """ import timeit t = timeit.Timer(lambda: "print (rot13(sentence))") print ("Time:", t.timeit(2)) print ("Repeat:", t.repeat(3)) sentence = "Once more unto the breach, dear friends, once more" fxn = "print (rot13(sentence))" demo_timeit() """Output Time: 2.8738345574500055e-06 Repeat: [0.10536955459669838, 0.10393510060473689, 0.10435714373688812] """
5c67e6d276e6c8887a7f822fbc9c6638b19805b2
ZenTauro/telematicos
/python_back/ServTelemBack/sensor.py
1,242
3.5
4
#!/usr/bin/python # -*- coding: utf-8 -*- from random import randint from typing import Dict def get_sensors(): tmp = temperature() hum = humidity() noi = sound() bri = light() mov = motion() return { "temp": tmp.get(), "humid": hum.get(), "noise": noi.get(), "bright": bri.get(), "movement": mov.get(), } class temperature(): def get(self) -> int: value = randint(19, 22) return value class humidity(): def get(self) -> int: value = randint(30, 60) return value class light(): def get(self) -> int: value = randint(0, 100) return value class sound(): def get(self) -> int: value = randint(20, 80) return value class motion(): def get(self) -> bool: value = randint(0, 1) return value == 1 class red(): def put(self, id: int) -> Dict[str, int]: print("Color rojo:"+str(id)) return {'red': id} class green(): def put(self, id) -> Dict[str, int]: print("Color verde:"+str(id)) return {'green': id} class blue(): def put(self, id) -> Dict[str, int]: print("Color azul:"+str(id)) return {'blue': id}
bc173d7d456ef68301e042137287161d2f72d663
FabioLeonam/exercises
/hacker_rank/linked_list/sorted_insert.py
1,547
3.796875
4
# Complete the sortedInsert function below. # # For your reference: # # DoublyLinkedListNode: # int data # DoublyLinkedListNode next # DoublyLinkedListNode prev # # def sortedInsert(head, data): new_node = DoublyLinkedListNode(data) # Case 1: empty list if head == None: head = new_node return head #Case 2: Insert at head elif head.data > data: head.prev = new_node new_node.next = head head = new_node return head else: pointer = head while(pointer.data < data): #Case 3: Insert at tail if pointer.next == None: pointer.next = new_node new_node.prev = pointer return head else: pointer = pointer.next # Case 4: Insert at somewhere middle pointer.prev.next = new_node new_node.prev = pointer.prev pointer.prev = new_node new_node.next = pointer return head if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): llist_count = int(input()) llist = DoublyLinkedList() for _ in range(llist_count): llist_item = int(input()) llist.insert_node(llist_item) data = int(input()) llist1 = sortedInsert(llist.head, data) print_doubly_linked_list(llist1, ' ', fptr) fptr.write('\n') fptr.close()
b05e97000eed3c4abc636492aae3fff52892acc4
sulemanmahmoodsparta/Data24Repo
/Football_Game/Game Code/a_Players.py
1,855
3.96875
4
import random # for player generation from abc import ABC, abstractmethod PlayerPositions = ["Goalkeeper","Defender","Midfielder","Attacker"] # An Abstract class that cannot be initialised class Players(ABC): @abstractmethod def __init__(self, fname, lname, value, position): self.id = 0 self.first_name = fname self.last_name = lname self.value = value self.position = position class Goalkeeper(Players): # Overriding base class abstract initialiser def __init__(self, fname, lname, value): super().__init__(fname, lname, value, "Goalkeeper") class Defender(Players): # Overriding base class abstract initialiser def __init__(self, fname, lname, value): super().__init__(fname, lname, value, "Defender") class Midfielder(Players): # Overriding base class abstract initialiser def __init__(self, fname, lname, value): super().__init__(fname, lname, value, "Midfielder") class Striker(Players): # Overriding base class abstract initialiser def __init__(self, fname, lname, value): super().__init__(fname, lname, value, "Striker") # Random Name Generation fnames = ["Liam","Noah","Oliver","Elijah","William", "James","Benjamin","Lucas","Henry","Alexander"] lnames = ["Smith","Jones","Brown","Taylor","Wilson", "Davies","Evans","Johnson","Thomas","Roberts"] def generate_name(): index = random.randint(0, len(fnames) - 1) fname = fnames[index] index = random.randint(0, len(lnames) - 1) lname = lnames[index] return fname, lname def generate_player(position): fname, lname = generate_name() value = random.randint(75, 125) if position == "Goalkeeper": return Goalkeeper(fname, lname, value, position) return Players(fname,lname, value, position)
3ce8e95e0cdf849d2c434197aaffc427177505a5
DeltaDeutsch/3.-Python-Homework-Deutsch
/Pypoll Deutsch May 3 2021.py
2,349
3.828125
4
#Pypoll Deutsch #Define Variables total_votes = 0 Candidates_votes = {} list_of_candidates = [] winning_candidate = "" winning_count = 0 """ The total number of votes cast () * A complete list of candidates who received votes * The percentage of votes each candidate won * The total number of votes each candidate won * The winner of the election based on popular vote. """ #Import and read election file import csv with open(r"C:\users\deuts\P hw\election_data.csv") as file: reader = csv.reader(file) header = next(reader) #read the header row for row in reader: #Calculate total votes total_votes += 1 # Get Candidate name candidate_name = row[2] if candidate_name not in list_of_candidates: list_of_candidates.append(candidate_name) # Initialize the candidates votes Candidates_votes[candidate_name] = 0 # Increase the candidate vote by 1 Candidates_votes[candidate_name] = Candidates_votes[candidate_name] + 1 print(Candidates_votes) with open('output.txt', "w") as txt_file: election_results = ( f"Totatl Votes: {total_votes} \n" ) txt_file.write(election_results) for candidates in Candidates_votes: votes = Candidates_votes.get(candidates) percentage_votes = votes/total_votes percentage_votes ="%{:,.2f}".format(percentage_votes) if votes > winning_count: winning_candidate = candidates winning_count = votes voting_results = ( f" Candidate: {candidates} \n" f"Percentage votes: {percentage_votes} \n" f"Total Votes : {votes} \n" ) txt_file.write(voting_results) winner = ( f"The winner is: {winning_candidate} \n" ) txt_file.write(winner) #Loop through file and count votes by candidate: Correy, Khan, Li, O'Tooley #Counter/Iterator """ Print * The total number of votes cast * A complete list of candidates who received votes * The percentage of votes each candidate won * The total number of votes each candidate won * The winner of the election based on popular vote.
d9bd5a54cb829d172ef1e2848af16bc0b5acfe13
rashmierande/practice
/strings/Palindrome.py
310
3.78125
4
def is_Palin(str1): return str1[::-1]== str1 print(is_Palin("hello")) print(is_Palin("123")) print(is_Palin("111")) print(is_Palin("aba")) def is_pal(str1): r=str1[::-1] for i in range(0,len(str1)+1//2): if str1[i]!=r[i]: return False return True print(is_pal("aabac17"))
1a95ec6308ef19d7573f3ff1eda184941cfad8b2
Jack2ee-dev/NKLCB_homework
/programmersSkillCheckLevel1/no2/solution.py
267
3.59375
4
def solution(array, commands): answer = [] for command in commands: start = command[0] end = command[1] order = command[2] temp = array[start-1:end] temp.sort() answer.append(temp[order-1]) return answer
c9b30321bde82b1a80ec64b3a7ce0e5b6465a50f
gau-nernst/search-algos
/search.py
9,761
3.546875
4
class Search(): valid_strat = {'bfs', 'dfs', 'ldfs', 'ids', 'ucs', 'greedy', 'a_star'} def __init__(self, strategy): assert strategy in self.valid_strat self.strat = strategy def __call__(self, start, end, adj_list, max_depth=3, heuristic=None): print("Strategy:", self.strat) print("Start:", start) print("End:", end) print() if self.strat == 'dfs' or self.strat == 'bfs': self.bfs_dfs(self.strat, start, end, adj_list) elif self.strat == 'ldfs': self.ldfs(start, end, adj_list, max_depth=max_depth) elif self.strat == 'ids': for i in range(1, max_depth+1): print("Max depth:", i) self.ldfs(start, end, adj_list, max_depth=i) print() print() elif self.strat == 'ucs': self.ucs(start, end, adj_list) elif self.strat == 'greedy': self.greedy(start, end, adj_list, heuristic=heuristic) elif self.strat == 'a_star': self.a_star(start, end, adj_list, heuristic=heuristic) def bfs_dfs(self, strat, start, end, adj_list): from collections import deque assert strat == 'bfs' or strat == 'dfs' if strat == 'dfs': candidates = [] elif strat == 'bfs': candidates = deque() candidates.append(start) visited = set() parent = {} step = 1 while candidates: print("Step", step) step += 1 if strat == 'dfs': current_node = candidates.pop() elif strat == 'bfs': current_node = candidates.popleft() print("Current node:", current_node) if current_node == end: print("Found the destination") print() self.print_path(start, end, parent, adj_list) return visited.add(current_node) print("Visited nodes:", visited) print(f"Neighbors of {current_node}: {adj_list[current_node]}") print() for x in adj_list[current_node]: if x not in visited and x not in candidates: candidates.append(x) parent[x] = current_node print("Candidates:", candidates) if candidates: print("Next node to examine:", candidates[-1] if strat == 'dfs' else candidates[0]) print() print() print(f"Does not found a path from {start} to {end}") def ldfs(self, start, end, adj_list, max_depth=1): candidates = [] candidates.append((start,0)) parent = {} step = 1 print("start:", candidates) print() print() while candidates: print("Step", step) step += 1 current_node, depth = candidates.pop() print("Current node:", current_node) print("Current depth:", depth) print(f"Neighbors of {current_node}: {adj_list[current_node]}") if current_node == end: print("Found the destination") print() self.print_path(start, end, parent, adj_list) return if depth < max_depth: for x in adj_list[current_node]: if current_node in parent and x == parent[current_node]: continue candidates.append((x,depth+1)) parent[x] = current_node else: print("Reach max depth") print(candidates) print() print() print(f"Does not found a path from {start} to {end} with depth {depth}") def ucs(self, start, end, adj_list): candidates = set() path_cost = {} parent = {} step = 1 candidates.add(start) path_cost[start] = 0 while candidates: print("Step", step) step += 1 min_node = None min_cost = float('inf') for node in candidates: if path_cost[node] < min_cost: min_node = node min_cost = path_cost[node] candidates.remove(min_node) current_node = min_node print("Current node:", current_node) if current_node == end: print("Found the destination") print() self.print_path(start, end, parent, adj_list) return print(f"Neighbors of {current_node}: {adj_list[current_node]}") print("Path cost:", path_cost) print() for x in adj_list[current_node]: if x in parent and parent[x] == current_node: continue new_cost = path_cost[current_node] + adj_list[current_node][x] if x not in path_cost or new_cost < path_cost[x]: parent[x] = current_node path_cost[x] = new_cost candidates.add(x) print("Candidates:", candidates) print() print() print(f"Does not found a path from {start} to {end} with depth {depth}") def greedy(self, start, end, adj_list, heuristic): assert heuristic current_node = start path = [] step = 1 path.append(start) while current_node != end: print("Step", step) step += 1 print("Current node:", current_node) neighbors = list(adj_list[current_node].keys()) neighbors_est_cost = [heuristic(x, end) for x in neighbors] if not neighbors: print(f"Does not found a path from {start} to {end} with depth {depth}") return n = {neighbors[i]: round(neighbors_est_cost[i]) for i in range(len(neighbors))} print(f"Neighbors of {current_node}: {n}") next_node = None min_est_cost = float('inf') for i in range(len(neighbors)): if neighbors_est_cost[i] < min_est_cost: next_node = neighbors[i] min_est_cost = neighbors_est_cost[i] path.append(next_node) current_node = next_node print() print() print("Found the destination") print() print("Full path: ", end="") print(*path, sep=' → ') total = 0 for i in range(len(path)-1): a = path[i] b = path[i+1] total += adj_list[a][b] print(f"\t{a} → {b}: {adj_list[a][b]}") print(f"Total cost: {total}") def a_star(self, start, end, adj_list, heuristic): assert heuristic candidates = set() path_cost = {} heuristic_cost = {} parent = {} step = 1 candidates.add(start) path_cost[start] = 0 while candidates: print("Step", step) step += 1 min_node = None min_cost = float('inf') for node in candidates: if node not in heuristic_cost: heuristic_cost[node] = heuristic(node, end) total_cost = path_cost[node] + heuristic_cost[node] if total_cost < min_cost: min_node = node min_cost = total_cost candidates.remove(min_node) current_node = min_node print("Current node:", current_node) if current_node == end: print("Found the destination") print() self.print_path(start, end , parent, adj_list) return print(f"Neighbors of {current_node}: {adj_list[current_node]}") print("Path cost:", path_cost) n = {k: round(v) for k,v in heuristic_cost.items()} print("Heuristic cost:", n) print() for x in adj_list[current_node]: if x in parent and parent[x] == current_node: continue new_cost = path_cost[current_node] + adj_list[current_node][x] if x not in path_cost or new_cost < path_cost[x]: parent[x] = current_node path_cost[x] = new_cost candidates.add(x) print("Candidates:", candidates) print() print() print(f"Does not found a path from {start} to {end} with depth {depth}") def print_path(self, start, end, parent, adj_list): print("Full path: ", end="") x = end path = [x] while x != start: x = parent[x] path.append(x) path.reverse() print(*path, sep=' → ') total = 0 for i in range(len(path)-1): a = path[i] b = path[i+1] total += adj_list[a][b] print(f"\t{a} → {b}: {adj_list[a][b]}") print(f"Total cost: {total}")
eb0f7b3c30d4540680feb8ea0a2a77aa5e402240
tech-vin/tkinter-Exercies
/2.py
193
3.75
4
# create title to widjet and label from tkinter import * root = Tk() root.title('This is the title of the window') label = Label(root, text="Representing Label") label.pack() root.mainloop()
c3613d1209e07c7f4c04d43d3159b530c884dbc7
jaadyyah/APSCP
/2017_jaadyyahshearrion_4.02a.py
984
4.5
4
# description of function goes here # input: user sees list of not plural fruit # output: the function returns the plural of the fruits def fruit_pluralizer(list_of_strings): new_fruits = [] for item in list_of_strings: if item == '': item = 'No item' new_fruits.append(item) elif item[-1] == 'y': item = item[:-1] + 'ies' new_fruits.append(item) elif item[-1] == 'e': item1 = item + 's' new_fruits.append(item1) elif item[-2:] == 'ch': item2 = item + 'es' new_fruits.append(item2) else: item3 = item + 's' new_fruits.append(item3) return new_fruits fruit_list = ['apple', 'berry', 'melon', 'peach'] print("Single Fruit: " + str(fruit_list)) new_fruits_list = fruit_pluralizer(fruit_list) print("Plural Fruit: " + str(new_fruits_list)) # claire checked me based on the asssaignements she said I did a gud
fb1efbb8d885e116c665ee9c351f9247a649a719
gallofb/Python_linux
/py_test/栈与队列/push_and_pop.py
906
3.6875
4
# -*- coding:utf-8 -*- #栈的压如弹出序列 class Solution: def IsPopOrder(self, pushV, popV): if pushV != None and popV != None and len(pushV) == len(popV): stack = [] i = 0 while popV: p = popV.pop(0) while i < len(pushV): stack.append(pushV[i]) if pushV[i] != p: # list.append(pushV[i]) i +=1 else: # list.append(pushV[i]) i +=1 break if p == stack[-1]: stack.pop(-1) else: return False return True return False if __name__ == '__main__': so = Solution() list1 = [1,2,3,4,5] list2 = [4,5,3,2,1] print(so.IsPopOrder(list1,list2))
20aacc63fbe22210095ee0d8e49b1f3fd7749ba0
FranckCHAMBON/ClasseVirtuelle
/Term_NSI/devoirs/4-dm2/Corrigé/PROF/E6.py
535
3.5
4
""" auteur : Franck CHAMBON https://prologin.org/train/2003/semifinal/nombres_impairs """ def nombres_impairs(n: int, m: int) -> list: """Renvoie la liste des nombres impairs entre `n` et `m` inclus. >>> nombres_impairs(42, 51) [43, 45, 47, 49, 51] """ liste = [] i = n if i % 2 == 0: i += 1 while i <= m: liste.append(i) i += 2 return liste import doctest doctest.testmod() n, m = map(int, input().split()) impairs = nombres_impairs(n, m) print(" ".join(map(str, impairs)))
07b40e151845f33384e1f58a4d4af77917705f9f
Rahelsc/forHezi
/get_anastasia_to_ariel.py
2,234
3.703125
4
import math # code complexity: |V| def Dijkstra_init(graph, vertex): for key in graph.keys(): graph[key]['d'] = 0 if key == vertex else math.inf graph[key]['p'] = None # relax gets 2 vertices (neighbor and current)- when e is (current,neighbor) def relax(graph, neighbor, current, e): # if (distance from s to neighbor) is greater than (distance from s to current + distance from current to neighbor) if graph[neighbor]["d"] > graph[current]["d"] + e["weight"]: graph[neighbor]["d"] = graph[current]["d"] + e["weight"] graph[neighbor]["p"] = current def getMinimal(graph, pq): minimal = pq[0] for current in pq: if graph[current]["d"] < graph[minimal]["d"]: minimal = current return minimal def Dijkstra(graph, vertex): Dijkstra_init(graph, vertex) pq = list(graph.keys()) while len(pq) > 0: current = getMinimal(graph, pq) for edge in graph[current]["adj"]: relax(graph, edge["dst"], current, edge) pq.remove(current) graph = { "maalot": { "adj": [{"dst": "haifa", "weight": 1}, {"dst": "herzelia", "weight": 10}, {"dst": "tel aviv", "weight": 50}]}, "tel aviv": {"adj": [{"dst": "petach-tikva", "weight": 5}]}, "petach-tikva": {"adj": [{"dst": "rosh-haayn", "weight": 1}]}, "rosh-haayn": {"adj": [{"dst": "ariel", "weight": 1}]}, "ariel": {"adj": []}, "ramat gan": {"adj": [{"dst": "tel aviv", "weight": 2}]}, "herzelia": {"adj": [{"dst": "ramat gan", "weight": 7}]}, "haifa": {"adj": [{"dst": "ariel", "weight": 100}, {"dst": "herzelia", "weight": 80}]} } def shortpath(graph, source, middle, destination): path = [] Dijkstra(graph, middle) current = destination while current is not None: path.insert(0, current) prev = graph[current]["p"] if prev == middle: break current = prev Dijkstra(graph, source) current = middle while current is not None: path.insert(0, current) prev = graph[current]["p"] if prev == source: path.insert(0, prev) break current = prev print(path) shortpath(graph, "maalot", "herzelia", "ariel")
606c28434e0552b5dfce957ab837d3d911cfcbd8
yaelRashlin/checkio-solutions
/home/backward_string_by_word.py
694
4.03125
4
def backward_string_by_word(text: str) -> str: import re return "".join([y[::-1] for x in re.findall("(\w+)(\s+)?", text) for y in x]) if __name__ == '__main__': print("Example:") print(backward_string_by_word('')) # These "asserts" are used for self-checking and not for an auto-testing assert backward_string_by_word('') == '' assert backward_string_by_word('world') == 'dlrow' assert backward_string_by_word('hello world') == 'olleh dlrow' assert backward_string_by_word('hello world') == 'olleh dlrow' assert backward_string_by_word('welcome to a game') == 'emoclew ot a emag' print("Coding complete? Click 'Check' to earn cool rewards!")
8c2b8a5f76d4d2cd7470512761bdaca5e15a975e
arnabid/QA
/sortsearch/divide2Integers.py
977
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 15 20:50:05 2017 @author: arnab """ def divide(dividend, divisor): maxintp = 2147483647 maxintn = -2147483648 if divisor == 0: raise ValueError("divisor is 0") if dividend == 0: return 0 if divisor == 1: return min(max(maxintn, dividend), maxintp) if divisor == -1: return min(max(maxintn, -dividend), maxintp) positive = (dividend > 0) is (divisor > 0) dividend, divisor = abs(dividend), abs(divisor) denominator, result = divisor, 1 while dividend > denominator: denominator <<= 1 result <<= 1 while denominator > dividend: denominator -= divisor result -= 1 if not positive: result = -result return min(max(maxintn, result), maxintp) if __name__ == '__main__': dividend = int(raw_input()) divisor = int(raw_input()) print (divide(dividend, divisor))
fd48edd5c45535b2f425d600a62972b84297b59a
EwanThomas0o/Self_teaching
/bin_tree_traversal.py
7,333
4.25
4
#A binary tree is a structure where each node has at most two children # root node # / \ # / \ # left child right child # The depth of a node is how many nodes it is away from the root # The dead ends of the tree are called leaves, and the height of a node is how many nodes another node is from its furthest leaf # In a complete binary tree, every level except possibly the last, is completely filled and all nodes in the last level are as far left as possible. # A full binary tree (sometimes referred to as a proper or plane binary tree) is a tree in which every node has either 0 or 2 children. #----- Implementation -----# #Defining a queue class, used later on for level-order traversal (line 167) class Queue(object): def __init__(self): self.items = [] #Is just an empty array def enqueue(self, item): self.items.insert(0, item) #insert an item at the 0th index (end of the queue) def dequeue(self): if not self.is_empty(): #remove the last element return self.items.pop() def is_empty(self): return len(self.items) == 0 #empty checker def peek(self): if not self.is_empty(): #Since queues are first-in, first out the next item out is the last item in the list return self.items[-1].value def __len__(self): #size of queue return self.size() def size(self): return len(self.items) class node(object): def __init__(self,value): #Creates an object called node to be used in tree self.value = value self.left = None self.right = None class binar_tree(object): def __init__(self,root): #creates a tree as an object, must start tree with root so we call node and input a val to start. self.root = node(root) def print_tree(self, traversal_type): if traversal_type == "preorder": return self.preorder_print(tree.root, "") elif traversal_type == "inorder": return self.inorder_print(tree.root, "") elif traversal_type == "postorder": return self.postorder_print(tree.root, "") elif traversal_type == "levelorder": return self.levelorder_print(tree.root) else: print("Traversal type " + str(traversal_type) + " is not supported.") return False def preorder_print(self, start, traversal): #Start is current node, traversal is the string that records visited nodes if start: #Checking to see if starting node is null traversal += (str(start.value) + "-") traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal def inorder_print(self, start, traversal): #Start is current node, traversal is the string that records visited nodes if start: #Checking to see if starting node is null traversal = self.preorder_print(start.left, traversal) traversal += (str(start.value) + "-") traversal = self.preorder_print(start.right, traversal) return traversal def postorder_print(self, start, traversal): #Start is current node, traversal is the string that records visited nodes if start: #Checking to see if starting node is null traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) traversal += (str(start.value) + "-") return traversal def levelorder_print(self, start): #Theres also a way to do this in reverse! Instead of pushing into a string, push into a stack then pop off things from the stack! if start is None: # First-in last out nature of stack means that the levelorder print will now be in reverse! Stacks are great for reversing things! return q = Queue() q.enqueue(start) #Add first node to the queue, gotta start somewhere! traversal = "" while len(q) > 0: traversal += str(q.peek()) + "-" node = q.dequeue() #removes last element in list from the q (first-in first-out) if node.left: q.enqueue(node.left) #gets value from left if node.right: q.enqueue(node.right) return traversal # ___1___ tree = binar_tree(1) # / \ tree.root.left = node(2) # / \ tree.root.right = node(3) # / \ tree.root.left.left = node(4) # 2 3 tree.root.left.right = node(5) # / \ / \ tree.root.right.left = node(6) # / \ / \ tree.root.right.right = node(7) # 4 5 6 7 #now that we've built our tree lets traverse it #----- Traversal -----# # Traversal is the process of visitin each node in a tree data structure,exactly once. Unlike linear linked lists which can be accessed in a logical fashion, bin trees can be # accessed in many different ways. # Can be traversed depth-first or bredth-first # Some depth-first traversal methods are in-order, pre-order and post-order. #----- Pre-order Traversal -----# # 1. Check if current node is empty or null # 2. Display data or current node # 3. Traverse left subtree by calling pre-order method recursively # 4. Traverse right subtree by calling pre-order method # visit, left, right #----- In-order Traversal -----# # 1. Check if current node is empty or null # 2. Traverse left subtree by calling pre-order method recursively # 3. Display data or current node # 4. Traverse right subtree by calling pre-order method # left, visit, right #----- post-order Traversal -----# # 1. Check if current node is empty or null # 2. Traverse left subtree by calling pre-order method recursively # 3. Traverse right subtree by calling pre-order method # 4. Display data or current node #left, right, visit print(tree.print_tree("preorder")) print(tree.print_tree("inorder")) print(tree.print_tree("postorder")) print(tree.print_tree("levelorder")) #----- Level-Order traversal -----# # This is a type of bredth-first traversal. instead of using a stack we use a queuing system instead. We have to define a class called Queue (opposite of stack) # as first index is last in the queue and last index is first in the queue (cyle via A[-1]) # We basically look at each level and look at what values are one each level # ___1___ Level 1 # / \ # / \ # / \ # 2 3 Level 2 # / \ # / \ # 4 5 Level 3 # we start at Level 1: We add 1 to the queue # Then we remove from q and add it to the traversal string # we move on to Level 2: We add 2 and 3 (the children of the node we de-"q"ed) the to the q # : we remove 2 from the q and then add 4 and 5 to the q (as they are the children of 2 which we just de-"q"ed) # Level 3: We remove 3 and because it has no children we can then simply remove 4 and 5 too, This will make Traversal = 12345
e6324c17afec834dfe495f816981810e91396aa9
QilinGu/price_watcher
/commodity.py
1,126
3.921875
4
# File for a class Commodity # Each Commodity has three data members # url_address: a string containing the weblink url address # original_price: a float of the original price of the item # current_price: a float of the real-time price of the item class Commodity: #constructor def __init__(self, url, first_price, curr_price): self.url_address = url self.original_price = first_price self.current_price = curr_price # Update the real-time price, the price may go up, go down or stay the same def update(self, updated_price): self.current_price = updated_price # Check if the price have gone down # If the price have gone down, then give indication to the user # Otherwise, do nothing def check(self): if self.current_price < self.original_price: # Found an item that is on sale print "Item whose URL is: %s" % (self.url_address) print "The price drops from %f to %f" % (self.original_price, self.current_price) return True else: return False
d826e79efb91623d68fe30ad73109aa98ea0bfbe
kailvin7/kailvin-python
/learn/file_io.py
672
3.984375
4
#!/usr/bin/env python # -*- coding:UTF-8 -*- """ #raw_input 函数 str = raw_input("plz input:") print "your inputing is ",str #input函数 // input函数和raw_input函数类似,但是它可以接受一个Python表达式作为输入,并将运算结果返回 str = input("请输入:") print "你输入的内容是:",str """ #open函数 test_name = r"E:\pycharm\learn\for range.py" test_fo = open(test_name,"a+") test_file = test_fo.read() print test_file test_fo.close() test_fo = open(test_name,"a+") test_fo.write("\nThis is write test for practicing\n") test_fo.close() test_fo = open(test_name,"a+") test_file = test_fo.read() print test_file test_fo.close()
b10927893e7c1b1cc16c9b89dd3470799e8a98a7
TurnUpTheMike/CamouflagePuzzle
/camo/solution/puzzleutility.py
1,256
3.90625
4
class PuzzleUtility: """ These are common functions that multiple classes use """ def __init__(self, properties): self.properties = properties # which column of the puzzle row grid that the "chosen letter" will appear self.chosen_letter_index = self.properties.puzzle_row_length // 2 def letter_ndx_of_word(self, word, letter): """ the earliest letter in the word that the letter exists more than word.find this accounts for long words where the letter might not fit at the beginning of the word :param word: :param letter: :return: """ word_length = len(word) earliest_index = self.earliest_possible_index_choice(word_length) letter_index = word.find(letter, earliest_index) return letter_index def earliest_possible_index_choice(self, word_length): """ The word may be too long for the chosen letter to fit every letter index This is the earliest index of the word that the chosen letter can be :param word_length: :return: """ if self.chosen_letter_index > word_length - 1: return 0 return (word_length - 1) - self.chosen_letter_index
5d9a2a002e45e4027042c070fdc70b9dadffbbe5
zhulei2017/Python-Offer
/sword-to-offer/43.1.py
731
3.5625
4
def print_probability(nums): if nums < 1: return [] data1 = [0] + [1] * 6 + [0] * 6 * (nums-1) data2 = [0] + [0] * 6 * nums flag = 0 for v in range(2, nums+1): if flag: for k in range(v, 6*v+1): data1[k] = sum([data2[k-j] for j in range(1, 7) if k > j]) flag = 0 else: for k in range(v, 6*v+1): data2[k] = sum([data1[k-j] for j in range(1, 7) if k > j]) flag = 1 ret = [] total = 6 ** nums data = data2[nums:] if flag else data1[nums:] for v in data: ret.append(v*1.0/total) print(data) return ret if __name__ == "__main__": test = 3 print(print_probability(test))
434b8d0d1cf5cdc6b515012054a8f4babdf42bd1
JacksonMike/python_exercise
/python练习/老王开枪/Test1.py
584
3.609375
4
a = "Jim" b = "Jack" c = "Mike" d = "Hard" name_list = [a,b,c] name_list.append(d) e = name_list.count(b) print(e) print(name_list) for a in name_list: print(a) infor_tuple = ("Jim",12,12) print(infor_tuple) print(infor_tuple.count("Jim")) for item in infor_tuple: print(item) o = {"name":"Jim","age":15,"job":"cook"} print("%s %d %s"%(o["name"],o["age"],o["job"])) card_list =[{"name":"Jim","age":12},{"name":"Jack","age":13}] for temple in card_list: print(temple) print(temple["name"]) string = "Hello World" for m in string: print(m) a = 10 print("%x"%id(a))
67a53c73107f77bc2cf3c17b114bd92f6c317be8
blue2525989/caesar
/caesar.py
1,016
3.9375
4
import string def alphabet_position(char): bet = string.ascii_letters pos = bet.find(char) if pos > 25: new_pos = pos - 26 return new_pos else: return pos def rotate_letter(letter, n): if letter.isupper(): start = ord('A') elif letter.islower(): start = ord('a') else: return letter c = ord(letter) - start i = (c + n) % 26 + start return chr(i) def encrypt(word, n): res = '' for letter in word: if letter != ' ': res += rotate_letter(letter, n) elif letter == ' ': res += ' ' return res def main(): choice = '' while choice != 'q': choice = input("Please enter a sentence to encrypt\nq to quit\n") if choice == 'q': break else: time = input("Please enter the number of times to rotate characters\n") time = int(time) print(encrypt(choice, time)) if __name__ == '__main__': main()
6500131604b6ab13a1074ab4a2710feb846558ca
Aasthaengg/IBMdataset
/Python_codes/p03108/s474201214.py
1,535
3.515625
4
import math def P(n, r): return math.factorial(n)//math.factorial(n-r) def C(n, r): return P(n, r)//math.factorial(r) class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def __str__(self): return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots()) N, M = map(int, input().split()) uf = UnionFind(N) query = [list(map(int, input().split())) for _ in range(M)] ans = C(N,2) ans_arr = [0]*M ans_arr[M-1] = ans for i in range(M-1): A, B = query[M-1-i][0]-1, query[M-1-i][1]-1 if not uf.same(A,B): ans -= uf.size(A) * uf.size(B) ans_arr[M-2-i] = ans uf.union(A,B) for i in ans_arr: print(i)
7c7e3e6fa35ca4d0a5b41c290fa8dfdbf2f1daeb
GustavoGarciaPereira/Topicos-Avancados-em-Informatica-I
/exercicios_strings/exe1.py
326
4
4
''' Escreva um programa que leia uma palavra qualquer e conte o número de vogais ''' print("exe1") string = input("escreva a palavra: ") cont = 0 for i in string: if i.upper() == 'A' or i.upper() == 'E' or i.upper() == 'I' or i.upper() == 'O' or i.upper() == 'U': cont +=1 print("quantidade de vogais", cont)
de1908cd3e2aa667336bc749d431aeab6353b996
amitturare/Basic-Python-Problems
/Calculator.py
1,818
4.25
4
''' a = float(input("Enter one number")) b = float(input("Enter another number")) print("Print 1 for Addition") print("Print 2 for Substraction") print("Print 3 for Multiplication") print("Print 4 for Division") print("Print 5 for Modulus") try: c = int(input("Enter your choice: ")) if(c == 1): print('Addition of a and b = ', a + b) elif(c == 2): print('Substraction of a and b = ', a - b) elif(c == 3): print('Multiplication of a and b = ', a * b) elif(c == 4): print('Division of a and b = ', a / b) elif(c == 5): print('Modulus of a and b = ', a % b) except: print("Enter the number from the following above.") ''' #OR def calc(a,b): print("Type 1 for Addition\nType 2 for Substraction\nType 3 for Multiplication\nType 4 for Division\nType 5 for Modulus\nType 6 to Exit") while True: c = int(input("Enter your choice: ")) if(c == 1): print('Addition of a and b =', a + b) elif(c == 2): print('Substraction of a and b =', a - b) elif(c == 3): print('Multiplication of a and b =', a * b) elif(c == 4): print('Division of a and b =', a / b) elif(c == 5): print('Modulus of a and b =', a % b) elif(c == 6): d = input('Do you want to continue? ') if d == 'yes': a = float(input("Enter one number: ")) b = float(input("Enter another number: ")) continue else: break a = float(input("Enter one number: ")) b = float(input("Enter another number: ")) calc(a,b)
f771cf234d4d7a26c160fae5cef4bc3740007eea
gitfernandojmm/devcode_python_notas
/cap04/4_break-continue.py
433
3.859375
4
# /usr/bin/env python # coding=utf-8 # break x = 0 while True: if x == 10: break x += 1 print('Salio del bucle infinito') lista_enteros = [1, 2, 3, 4, 5] for x in lista_enteros: if x == 3: break print(x) # continue x = 0 while x < 10: if x == 4: continue x += 1 print(x) lista_enteros = [1, 2, 3, 4, 5] for x in lista_enteros: if x == 3: continue print(x)
7aa6affd0c2ee4e979b7bfef6067dc5a77782ebe
SJmdy/PythonForLeetCode
/src/stack_or_queue.py
4,209
3.640625
4
# 使用栈或队列解决的问题 # 1047. 删除字符串中的所有相邻重复项 # # 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。在 S 上反复执行重复项删除操作,直到无法继续删除。在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 # # LC: [1047. 删除字符串中的所有相邻重复项](https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/) def remove_duplicates(s: str) -> str: if len(s) == 0: return s stack = [] for i in range(0, len(s)): if len(stack) == 0 or s[i] != stack[-1]: stack.append(s[i]) else: stack.pop() return "".join(stack) # 224. 基本计算器 [✔] # # 实现一个基本的计算器来计算一个简单的字符串表达式 s 的值。 # # 注:'s' must consist of values in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '(', ')', ' '] only # # LC: [224. 基本计算器](https://leetcode-cn.com/problems/basic-calculator/) # # 解题思路:递归求解 | 栈 [✔] # # op: 当前所应该进行的操作,+ 或 - # # ops: 栈,存放`()`外部的操作符,整体对`()`中的内容是 + 或 -。例如 `-(1 - (2 + 3))`,那么第一个括号对应的符号为 # `-`,第二个括号对应的符号为 `+`;对于任何公式`s`,都可以转化为`+(s)`的形式,因此ops初始化压入`+`。 # # op具体为`+` 或 `-` 取决于ops栈顶符号和当前的操作符;若当前的符号为`'+'`,那么op与ops栈顶保持已知;否则,op为ops栈顶的 # 相反操作 def calculate(s: str) -> int: s = s.replace(' ', '') if len(s) == 0: return 0 stack = [True] op = True left_cur = 0 res = 0 while left_cur < len(s): if s[left_cur] == '+': op = stack[-1] left_cur += 1 elif s[left_cur] == '-': op = not stack[-1] left_cur += 1 elif s[left_cur] == '(': stack.append(op) left_cur += 1 elif s[left_cur] == ')': stack.pop() left_cur += 1 else: # 数字 digit_cur = left_cur + 1 while digit_cur < len(s) and s[digit_cur].isdigit(): digit_cur += 1 digit = int(s[left_cur: digit_cur]) if op: res += digit else: res -= digit left_cur = digit_cur return res # 227. 基本计算器 II [✔] # # 给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。整数除法仅保留整数部分。 # # LC: [227. 基本计算器 II](https://leetcode-cn.com/problems/basic-calculator-ii/) # # 解题思路:栈 def calculate_2(s: str) -> int: s = s.replace(' ', '') if len(s) == 0: return 0 def get_num(cur: int, s: str) -> (int, int): # 获取从 cur 起的数字;s[cur]是数字 digit_cur = cur + 1 while digit_cur < len(s) and s[digit_cur].isdigit(): digit_cur += 1 return int(s[cur: digit_cur]), digit_cur left_cur = 0 flag = True calcu = [] while left_cur < len(s): print("calcu: ", calcu) if s[left_cur] == '+': flag = True left_cur += 1 elif s[left_cur] == '-': flag = False left_cur += 1 elif s[left_cur] == '*': digit, digit_cur = get_num(cur=left_cur + 1, s=s) prev_digit = calcu.pop() calcu.append(prev_digit * digit) left_cur = digit_cur elif s[left_cur] == '/': digit, digit_cur = get_num(cur=left_cur + 1, s=s) prev_digit = calcu.pop() calcu.append(prev_digit // digit) left_cur = digit_cur else: digit, digit_cur = get_num(cur=left_cur, s=s) calcu.append(digit if flag else 0 - flag) left_cur = digit_cur return sum(calcu)
746cc6d9d51df422ec1634c629adb4afd90d031d
fstoltz/schoolwork
/Datastructures and algorithms/DSALibrary_fredriks/test_Queue.py
951
3.65625
4
import unittest from Queue import Queue """ Things are working fine as of 1/12-2017 """ class TestQueue(unittest.TestCase): def test_01_create_queue(self): q = Queue() q.enqueue(50) q.enqueue(100) q.enqueue(150) value = q.dequeue() self.assertEqual(value, 50) def test_02_adv_queue_stuff(self): q = Queue() q.enqueue(50) q.enqueue(55) q.enqueue(60) q.enqueue(65) li = q.toList() self.assertEqual(li, [50, 55, 60, 65]) nextInLine = q.dequeue() li = q.toList() self.assertEqual(li, [55, 60, 65]) nextInLine = q.dequeue() nextInLine = q.dequeue() nextInLine = q.dequeue() li = q.toList() self.assertEqual(li, []) q.enqueue(10) li = q.toList() self.assertEqual(li, [10]) if __name__ == '__main__': unittest.main(verbosity=2)
3a44379c89fd057e1d6934f2bf215d305f8c43e8
python-practice-b02-927/volkova
/lab2/task_11.py
224
3.921875
4
def circle(r): for i in range (50): t.forward(math.pi *r / 50) t.left(360 / 50) import turtle t = turtle.Turtle() import math for i in range(8): circle(100+20*i) t.left(180) circle(100+20*i)
299a909e0454f6350072ff968328a2881773d927
brunasimaens/pubele2020
/exercicios_completos/ex2-2.py
439
3.828125
4
import sys import re # neste programa apenas contamos o numero de ocorrencias da palavra "". def search(word): with open("dicionario_medico.txt", "r") as f: content = f.readlines() ocorrencia = 0 linhas = [] for i, line in enumerate(content): matches = findall(word ,line) if matches: ocorrencia += len(matches) linhas.append(line) print("Numero total de ocorrencias da palavra" + word + ": " + ocorrencia)
2f3eb07894e37386429f634774e40d6e84216df0
emilianocasijr/Reviewer
/common_voice_recognition.py
980
3.578125
4
# This program is used to store the common voice recognition of various commands in the program import speech_recognition as sr import csv r = sr.Recognizer() data = {} key = "" while(1): key = input("Enter key: ") if key == "end": break print("Say " + key) for i in range(50): print(i, end = ': ') with sr.Microphone() as source: audio = r.listen(source) try: voice_data = r.recognize_google(audio, language='en-PH') except sr.UnknownValueError: print("Didn't recognize. Skipping.") continue except sr.RequestError: print("Service is down. Skipping.") continue print(voice_data) data[voice_data] = key with open('voice_recognition_data.csv', 'w', newline= "") as csv_file: writer = csv.writer(csv_file) for key, value in data.items(): writer.writerow([key,value])
6111e391ac32a1781a0981d7fc16bff283e01f13
Pattadon7642/100-Days-Python
/Rock Paper Scissors.py
1,019
3.984375
4
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' list_input = [rock, paper, scissors] player_choose = int(input(f'What do you choose? Type 0 for ock, 1 for Paper or 2 for Scisscors.\n')) if player_choose == 0: print(rock) elif player_choose == 1: print(paper) elif player_choose == 2: print(scissors) print('Computer choose:') computer_choose = random.randint(0,len(list_input)-1) if computer_choose == 0: print(rock) elif computer_choose == 1: print(paper) elif computer_choose == 2: print(scissors) if computer_choose > player_choose: print('Computer win!!!') elif computer_choose == player_choose: print('Draw') else: print('Player win!!!')
0892399580ec60774d623692662040c9d077d650
Computer-engineering-FICT/Computer-engineering-FICT
/I семестр/Програмування (Python)/Лабораторні/Лисенко 6116/Python/Презентації/ex23/Ex25.py
184
3.515625
4
class MyClass: def __init__ (self, y): self.x = y def hash (self) : return hash(self.x) m = MyClass(10) d = {} d[m] = "Значення" print(d[m])
d77765cd57f7594bbe6da9a3ea975b6e9239c04d
livolleyball/python_smart
/python_cookbook/DataStructuresAndAlgorithms.py
894
4.09375
4
# coding:utf8 # 1.1 将list或者tuple分割成变量 p = (4, 5) x, y = p print("x:", x, "y:", y) data = ["a", "b", "c", "d"] A, B, C, D = data print(A, B, C, D) s = 'hello' a, b, c, d, e = s print(a, b, c, d, e) # a,b,c,d,e,f=s # ValueError: not enough values to unpack (expected 6, got 5) data = [12.1, "b", "c", 5, (3, 4, 5)] _, B, C, _, _ = data print(B, C) # 1.2 从任意长度的可迭代对象中获取元素 def drop_first_last(grades): first, *middle, last = grades return sum(middle) / len(middle) print(drop_first_last([1, 3, 4, 0])) data = [12.1, "b", "c", 5, (3, 4, 5)] A, B, *left = data print(left) records = [("foo", 1, 2), ("bar", "hello"), ("foo", 3, 4, 5)] def do_foo(*args): print('foo', *args) def do_bar(s): print("bar", s) for tag, *args in records: if tag == "foo": do_foo(*args) elif tag == "bar": do_bar(*args)
e5d9e90dc394684518809add8ba7473b3959d0a5
LucasLima337/CEV_Python_Exercises
/exercicios/ex090.py
945
3.8125
4
# Dicionário em Python # condição de aprovamento >= 7 aluno = dict() grupo = [] cont = 0 while True: aluno['nome'] = str(input(f'\nNome do {cont + 1}º aluno: ')).strip().title() aluno['media'] = float(input(f'Média de {aluno["nome"]}: ')) if aluno['media'] >= 7: aluno['situacao'] = 'Aprovado' else: aluno['situacao'] = 'Reprovado' grupo.append(aluno.copy()) while True: question = str(input('\nDeseja continuar? [S/N]: ')).strip().lower()[0] if question in 'sn': break else: print('\nDado inválido, tente novamente!\n') if question == 's': cont += 1 else: print('') for a in grupo: print('=-=' * 10) print(f'Nome: {a["nome"]}') print(f'Média: {a["media"]:.1f}') print(f'Situação: {a["situacao"]}') print('=-=' * 10) print('') break
b2613302caa6a6a333e32f9bbf9bcc1ca9c180bb
sasa33k/PSCourse
/_02_PyFunctionsFilesYieldLambda.py
2,712
3.703125
4
students = [] def get_students_titlecase(): students_titlecase = [] for student in students: students_titlecase.append(student["name"].title()) return students_titlecase def print_students_titlecase(): students_titlecase = get_students_titlecase() print(students_titlecase) def add_student(name, student_id=0): student = {"name": name, "student_id": student_id} students.append(student) # READ / WRITE FILES def save_file(student): try: f = open("students.txt", "a") # access mode: w-overwrite entire file, r-reading a text file, a-appending, rb-reading a binary file, wb - writing to a binary file f.write(student + "\n") f.close() except Exception: print("Could not save file") def read_file(): try: f = open("students.txt", "r") for student in f.readlines(): # replace f.readlines with read_students(f) add_student(student) f.close() except Exception: print("Could not read file") # GENERATOR function, every time yield a single line, continue for all lines def read_students(f): for line in f: yield line # LAMBDA functions @ higher order functions, take function as argument, e.g. filter function double = lambda x: x * 2 def double(x): return x * 2 """ Generators in Python (use "yield" at least once) - iterators, laxily evaluated ("next" on demand), can model infinite sequence, are composable into pipelines (for natural stream processing) """ def gen123(): yield 3 yield 2 yield 4 g = gen123() next(g) # 3 next(g) # 2 for v in gen123(): print(v) """ Stateful generators - complex control flow, lazy evaluation e.g. get first 3 unique numbers --> exit once found """ (x*x for x in range (1,101)) # generator, use once only list(x*x for x in range (1,101)) sum(x*x for x in range (1,101)) # no need additional () # sum(x*x for x in range (1,101) if is_prime(x)) ] any([False, False, True]) all([False, False, True]) #zip in tuples sun = [1,2] mon = [3,4] for item in zip(sun,mon): print(item) """ (1, 3) (2, 4) """ for sun,mon in zip(sun,mon): print((sun+mon)/2) #chain # add_student("Mark",332) student_list = get_students_titlecase() read_file() print_students_titlecase() student_name = input("Enter student name: ") student_id = input("Enter student ID:") add_student(student_name, student_id) save_file(student_name) def var_args(name, *args): print(name) print(args) def var_kwargs(name, **kwargs): # keyword arguments print(name) print(kwargs["description"], kwargs["feedback"]) var_kwargs("Mark", description="desc", feedback=None, Sub=True)
fd03ae6217f18d3c15f7af01ee1646aeba7651c7
B05611003/108-2_python_hw
/1081.py
67
3.671875
4
a = int(input()) if a%2 == 0: print("Tom") else: print("Jerry")
c43b9f4a739bf2c36a735143fbabda49d34c4c53
810Teams/pre-programming-2018-solutions
/Online/0057-Bedtime.py
376
3.828125
4
""" Pre-Programming 61 Solution By Teerapat Kraisrisirikul """ def main(): """ Main function """ sleep = int(input())*60 + int(input()) awake = int(input())*60 + int(input()) if awake <= sleep: awake += 24*60 if awake - sleep < 7*60: print('Not enough') elif awake - sleep < 10*60: print('Enough') else: print('Too much') main()
e2a7c955c6a223bb52d2c6aea54c49ec072afbbe
blancasserna/Mo3
/python/Preu_a_pagar1.py
121
3.640625
4
edat = int(input("Indica la teva edat:")) if (edat < 5) or (edat >= 65) : print ("Gratis") else: print ("No gratis")
5a7aa39bbcdf7abd69ff8d5f896699679aa73ef7
banma12956/banma-leetcode
/lc77.py
193
3.609375
4
import itertools n=5 k=3 comb = list(itertools.combinations(range(1, n+1), k)) print(comb) answer = [] answer_temp = [] for i in range(len(comb)): answer.append(list(comb[i])) print(answer)
9cc4fef03af193b716ea06b7fa2db28a031c7192
mikooh/learnsite
/learnsite/views.py
2,121
3.546875
4
from django.http import HttpResponse # this is basically just some django code, that allows us to very simply return back, some information as HTTP response. we can essentially send back the 'hello' below. from django.shortcuts import render import operator # def home(request): # return HttpResponse('Hello') # just returning 'hello' won't work because we can't just send a string. we need to send an HTTP response. we can also directly write html instead of 'Hello'. for e.g. return HttpResponse(<h1>'Hello'</h1>) and this would work. def home(request): return render(request, 'home.html') # render... first argument request takes in the parameter and second is the path to the template where we want to send the user after the request. def count(request): fulltext = request.GET['fulltext'] # .get will pull the information provided in the 'fulltext'. and then we assign it to fulltext variable. # print(fulltext) # and this print will show up in the terminal/command prompt. wordlist = fulltext.split() # split() breaks the sentence into a list of words, by identifying the spaces. worddictionary = {} for word in wordlist: if word in worddictionary: # increase worddictionary[word] += 1 else: # add word to dictionary worddictionary[word] = 1 sortedwords = sorted(worddictionary.items(), key=operator.itemgetter(1), reverse=True) # .items will turn a dictionary key:value pair into one item in the list... ultimately a list with key value pairs stored like [(name, shridhar), (height, 180)]. also operator needs to be imported. return render(request, 'count.html', {'fulltext': fulltext, 'count': len(wordlist), 'sortedwords': sortedwords}) # here in the curly brackets... 'fulltext' refers to the variable that we will pass in our count.html page... and then it will display the value contained in the fulltext which is written after the :. here, fulltext is a variable that contains the value of that we got from the URL through .get. def about(request): return render(request, 'about.html')
fa6078a33ff4099f307a2b793537f66e59f6a2f5
boddachappu/interviewnotes
/DataStructures/DataStructures.py
2,018
3.84375
4
class Node: def __init__(self, data=None, pointer=None): self.data = data self.pointer = pointer def getPointer(self): return self.pointer def setPointer(self, new): self.pointer = new class LL: def __init__(self): self.head = None def insertEnd(self, val): current = self.head while current.pointer is not None: current = current.getPointer() current.setPointer(Node(val)) def insertMiddle(self, f, i): current = self.head if current: while current.data != f: current = current.getPointer() oldAddress = current.getPointer() new = Node(i) current.setPointer(new) new.setPointer(oldAddress) def inserStart(self, value): node = Node(value) node.pointer = self.head self.head = node def display(self): current = self.head if current: res = '' while current.pointer is not None: res += current.data current = current.getPointer() res += current.data return res ob = LL() ob.inserStart('a') ob.insertEnd('c') ob.insertMiddle('a', 'b') ob.insertEnd('z') ob.insertMiddle('c', 'd') print(ob.display()) class Stack: def __init__(self): self.data = [] def push(self, data): self.data.append(data) def pop(self): self.data.pop() def __str__(self): return "".join([str(val) for val in self.data]) ob = Stack() ob.push(1) ob.push(2) ob.push(3) ob.push(10) print(ob) ob.pop() print(ob) class Queue: def __init__(self): self.data = [] def enQueue(self, data): self.data.append(data) def deQueue(self): self.data.pop(0) def __str__(self): return "".join([str(val) for val in self.data]) ob = Queue() ob.enQueue(1) ob.enQueue(2) ob.enQueue(3) ob.enQueue(10) print(ob) ob.deQueue() print(ob)
9438e05943ea8fd5c6f77190eff68ab6870bc560
MFTECH-code/Exercicios-logicos-python-02
/ex07.py
213
4.125
4
num = int(input("Digite um número inteiro: ")) if (num % 5 == 0 and num % 10 == 0): print(f'{num} é divisivel por 5 e 10 ao mesmo tempo') else: print(f'{num} não é divisivel por 5 e 10 ao mesmo tempo')
090d66834f6cb0d83987c8eba18403765c28cbb3
Fixer38/University-Notes
/semester-1/progra-ex/manip2/ex2-null.py
101
3.8125
4
nb = int(input("Entrez un nombre: ")) if nb == 0: print("nb nul") else: print("nb non nul")
a1ad701ae83f3ff436c1ca2a0cc2b05d8c5b9d5e
Javigner/Bootcamp-Python-for-Machine-Learning
/Day00/ex02/whois.py
200
3.734375
4
import sys if sys.argv[1].isnumeric() == False or len(sys.argv) != 2: print("ERROR") else: if (int(sys.argv[1]) % 2 == 0): print("I'm Even.") else: print("I'm Odd.")
4c1c5203335d2ff52ed91f17ede55a507cf617a6
mikkosoi/Python-programming
/13.py
618
4
4
''' Write multiple functions that print the following information when called: ''' def dog_sleeps(name, time): #prints: X sleeps Y hours print name, " sleeps ", time, " hours" def dog_walks(name, speed): #prints: X walks Y speed print name, " walks ", speed, " speed" def dog_runs(name, speed): #prints: X runs Y speed print name, " runs ", speed, " speed" def dog_barks(name, sound): #prints: X barks with a sound Y print name, " barks with a sound ", sound #For example: name = "Musti" dog_walks(name, 10) #Musti walks 10.00km/h speed dog_barks(name,"wuf wuf") # Musti barks with a sound "wuf wuf"
0b896b503be27ca339d51e0ab79a146356a2b7e9
jasapozne/Project-Euler
/euler_problem25.py
285
3.71875
4
def fibonacci(n): a = 0 b = 1 while a <= n: a, b = b, a + b return a def fibonacci_1000_stevk(): k = 11 while True: k += 1 fib = fibonacci(k) if len(str(fib)) > 999: break return k print(fibonacci_1000_stevk())
6349fcb5aad610888dd2b773ca448cbd0bb02b41
SolomonLake/Scheduling-Python
/make_output.py
925
3.78125
4
def make_output(out_dict,output_name): """ Given an output dictionary that looks like {course_number : [Room, Teacher, Time, students]} makes an a file at output_name that is essentially a .tsv """ with open(output_name,'w') as f: output = ["Course\tRoom\tTeacher\tTime\tStudents"] for course in out_dict: line_out = [str(course)] rtts_list = [ str(out_dict[course]["room"]), str(out_dict[course]["teacher"]), str(out_dict[course]["time"]), " ".join([str(item) for item in out_dict[course]["students"]]) ] line_out.extend(rtts_list) output.append(("\t").join(line_out)) f.write(("\n").join(output)) #This is just a little test to make sure it is working as desired #out_dict = {1:{"Room":1,"Teacher":2,"Time" :2, "Students" :[2,3,4,7,8,9,10]},2:{"Room":3,"Teacher" : 2, "Time" : 4, "Students" : [4,9]}} #print out_dict #print make_output(out_dict, "outtt.txt")
0c605019e96ad3ad9b0c00af35f42e5042f52ac6
sirkibsirkib/python_tut
/tasks/task1_converter/converter.py
434
4.15625
4
""" TODO """ lb_per_kg = 2.204 km_per_mi = 1.6 print('Input your value:') string_value = input() value = float(string_value) print('Input your unit:') unit = input() if unit == 'kg': print(str(value*lb_per_kg) + ' lb') elif unit == 'lb': print(str(value/lb_per_kg) + ' kg') elif unit == 'mi': print(str(value*km_per_mi) + ' km') elif unit == 'km': print(str(value/km_per_mi) + ' mi') else: print('Unknown unit!')
c895a94a2b0c2e12f428bb956a990cb5e5ed2a10
garyalex/pythonpractice
/pybites/107.py
341
4.03125
4
def filter_positive_even_numbers(numbers): """Receives a list of numbers, and filters out numbers that are both positive and even (divisible by 2), try to use a list comprehension""" return list(i for i in numbers if (i % 2 == 0 and i > 0)) nums = [1, 2, 4, -1, 11, 6, 0, 8] print(filter_positive_even_numbers(nums))
f6a61a83db50b18147d2e11bfe224dd0be674409
anish531213/Interesting-Python-problems
/InsertionSort.py
229
4.125
4
def InsertionSort(arr): for i in range(1, len(arr)): for j in range(i, 0, -1): if l[j] < l[j-1]: l[j], l[j-1] = l[j-1], l[j] l = [3, 9, 7, 1, 3, 4, 8, 2, -1, -5] InsertionSort(l) print(l)
ca284c839f4116d24825b68eafbc0b78e14892ed
basnetroshan/Python-Revision
/strings.py
1,561
3.796875
4
a = "Double Hello" #double quote b = 'Single Hello' #single quote print(a) print(b) #Multi line String in double quote c = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(c) #Multi line String in single quote d= '''\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''' print(d) #String is the array of unicode character e = "Hello, Roshan" print(e[1]) #returns value of 1 position #slicing print(e[2:8])#returns value of position from 2 to 8(not included) #Negative indexing print (e[-5:-2]) #returns value from position 5 to 2, count starting from end of string print(len(e)) #returns the length of the string #Strip p = " HELLO ROSHAN " print(p.strip()) #returns "HELLO ROSHAN", removes whitespace from the start and end of the string #lower q=print(p.lower()) #upper q = 'hello there' print(q.upper()) #replace r = "Yeh Yu-Yun" print(r.replace('-', 'R')) #replaces the string with another string #split print(r.split('-')) #splits the string if it finds the instances of the seperator #Check String txt = 'Nepal has an estimated population of 26.4 million' chk = 'mill' in txt #check if the phrase is in the given string chk1 = 'lapeN' in txt chk3 = 'mill' not in txt chk4 = 'lapeN' not in txt print (chk) print(chk1) print(chk3)#returns False print(chk4)#returns True #Concatenation using + operator first = "Roshan" last = "Basnet" full_name = first + " " + last print(full_name)
e96767e093d5acfd072a689f8f7757fb672b2fba
annh3/coding_practice
/alien_dictionary_2.py
1,777
4.1875
4
def alien_dictionary(words): # Here's how you do a double for loop list comprehension reverse_adj_list = {c: [] for word in words for c in word} # add edges to the adjacency list """ I think the structure that you need to understand here is that information is only useful up to the “first difference” That’s what alphabetical order means Same as numeric order right? Because we have a total ordering on symbols """ for word1, word2 in zip(words, words[1:]): for c1, c2 in zip(word1, word2): if c1 != c2: # then c2 --> c1 in our graph reverse_adj_list[c2].append(c1) break # DFS output = [] seen = {} # False = gray, True = black # Defining this function internally """ Note that if the graph has cycles, then the alphabet is invalid """ """ Graph Coloring In directed graphs, we often detect cycles by using graph coloring All nodes start out as white Once they're visited they become grey Once all of their outgoign nodes have been fully explored, they become black We know there is a cycle if we enter a node that is currently grey All nodes that are currently on the stack are grey Nodes are changed to balck when they are removed from the stack """ def visit(node): # we don't need to return anything if node in seen: return seen[node] # return this color, if this node[seen] = False # this is grey for c in reverse_adj_list[node]: result = visit(c) # get rid of our check, so that we can detect cycle if not result: # node is grey return False # cycle seen[node] = True # we managed to visit without a cycle output.append(node) return True if not all(visit(node) for node in reverse_adj_list): return "" else: return "".join(output) if __name__ == "__main__": test()
08c48354f15d42c6fbdd4f9c060c1a0fe0a3e494
itsdeepakverma/anu_repo
/day1_CC.py
5,421
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 18 11:24:40 2018 @author: sharm """ #Challenge 1 n=input("Enter a number ") import math x=math.factorial(int(n)) print("factorial of number is:",x) #challenge 2 r=input("enter radius of the circle :") from math import pi area= pi* int(r)*int(r) circum=2*pi*int(r) print("area is : {} \n and circumference is :{} ".format(area,circum)) #challenge3 help(str.join) name= input("enter your first and last name") res= name.replace(' ',"*") print(res) #challenge 4 dir(str) help(str) #res= name.lower() name= input("Enter a string") print(name.swapcase()) #challenege 5 str4= 'RESTART' #print(str4.replace('R','$')) str7=str4[2:].replace('R','$') print(str7) strr=(str4.lstrip('R')).replace('R','$') print('R'+strr) #challenege6 str5="anuja sharma" print(str5) name= str5.split() type(name) resu=' '.join(name[::-1]) print(resu) #challenge 9 print("\"Anuja\"\n\"sharma\" ") #challenge 10 print("26" u'\u00b0') #challenge 11 print("UNIX" u'\u00AE' " and Sun Microsystems" u'\u2122' " are" u'\u00A9' ", 2018 Oracle") #challenge 12 print(u'\u0905\u0928\u0941\u091C\u093E \u0936\u0930\u094D\u092E\u093E') print(u'\u0935\u093F\u091C\u095F') #challenege 13 i=1 for i in range(1,9): #for c in range(1,5): if(i%2==0): a= u'\u006f \u002A ' print(a*4) else: b=u'\u002A \u006f ' print(b*4) #challenge 14 def BMI(): str1="""World Health Organization(WHO) BMI values(8 Levels) . Severe Thinness: less than 16 . Moderate Thinness: between 16 and 16.9 . Mild Thinness: between 17 and 18.4 . Normal: between 18.5 and 24.9 . Overweight: between 25 and 29.9 . Obese class I : between 30 and 34.9 . Obese class II: between 35 and 39.9 . Obese class III: 40 or greater""" print(str1) a=input("enter") """ weight_hin=input(u'\u0915\u0943\u092A\u094D\u092F\u093E \u0905\u092A\u0928\u093E \u0935\u091C\u0928 \u0907\u0928\u092A\u0941\u091F \u0915\u0930\u0947\u0902') height_hin= input(u'\u0915\u0943\u092A\u094D\u092F\u093E \u0905\u092A\u0928\u0940 \u0932\u092E\u094D\u092C\u093E\u0908 \u0907\u0928\u092A\u0941\u091F \u0915\u0930\u0947\u0902') weight=float(weight_hin) height=float(height_hin) res=weight/(height*height) print(res)""" BMI() #age calculator st_age= input("Enter your current age") age=int(st_age) fu_yr=input("how many year later you want to know your future age ") future=int(fu_yr) pa_yr=input("how many year before you want to know your age") past=int(pa_yr) future_age= age+future past_age= age-past print("you will be {} years old after {} years \n you were {} year old {} years ago".format(future_age,future,past_age,past) ) #height calculator def height(hi): #height=input("enter your height") total= hi.split('.') feet=int(total[0]) inch=int(total[1]) #print(feet) m_feet= feet*0.3048 m_inch=inch*0.0254 m_height=m_feet + m_inch print("you height converted in meteres is {}".format(m_height)) return(m_height) #height() #bmi calculator def bmi(weight_hin,h_m): # weight_hin=input(u'\u0915\u0943\u092A\u094D\u092F\u093E \u0905\u092A\u0928\u093E \u0935\u091C\u0928 \u0907\u0928\u092A\u0941\u091F \u0915\u0930\u0947\u0902') #height_hin= input(u'\u0915\u0943\u092A\u094D\u092F\u093E \u0905\u092A\u0928\u0940 \u0932\u092E\u094D\u092C\u093E\u0908 \u0907\u0928\u092A\u0941\u091F \u0915\u0930\u0947\u0902') weight=float(weight_hin) #h_m=height(height_hin) #height=float(height_hin) res=weight/(h_m) bmi=res/h_m print("your bmi is {}".format(bmi)) return bmi #bmi() # height convertor, bmi calculator, ponderal index def main(): weight_hin=input(u'\u0915\u0943\u092A\u094D\u092F\u093E \u0905\u092A\u0928\u093E \u0935\u091C\u0928 \u0907\u0928\u092A\u0941\u091F \u0915\u0930\u0947\u0902') height_hin= input(u'\u0915\u0943\u092A\u094D\u092F\u093E \u0905\u092A\u0928\u0940 \u0932\u092E\u094D\u092C\u093E\u0908 \u0907\u0928\u092A\u0941\u091F \u0915\u0930\u0947\u0902') print("your height in meters") h_m=height(height_hin) print("you bmi") b=bmi(weight_hin,h_m) print("Ponderal Index calculator") pic= b/h_m print("your ponderal Index is {}".format(pic)) main() # heart rate calculator age=input("enter your age") mhr=220-int(age) l_thr= .70*mhr h_thr= .85*mhr print("your maximum heart rate is {} and lower Target heart rate is {} and higher Target heart rate is{}".format(mhr,l_thr,h_thr)) #temperature calculator temp=input("Enter today's temperature in centigrade") fah= (int(temp)*(9/5))+32 kel= int(temp)+273 print("temperature in fahrenheit is {}\n temp in kelvin is {} ".format(fah,kel)) #Gas milage calculator dis= input("enter distance covered in KM before petrol tank of your car was empty") petrol=input("enter petrol you filled initially") avg= float(dis)/int(petrol) print(avg) #Ride cost calculator dis=input("total distance covered (to and fro) in km") price=input("petrol price per litre") avg=input("give average of your car") total_petrol=float(dis)/float(avg) total_price= total_petrol * float(price) print(total_price) #Gravity Calculator Distance= (-9.81* 10 * 10)/2 print(Distance) # Weighted Score Calculator assignment str1="anuja sharma" print(str1.strip(" ")) str1.casefold()
726979fb4c9e10fde0292a0a4a415bf29a3bdbaa
wakafengfan/Leetcode
/dp/rabbit.py
1,234
4.03125
4
""" 小兔的叔叔从外面旅游回来给她带来了一个礼物,小兔高兴地跑回自己的房间,拆开一看是一个棋盘,小兔有所失望。不 过没过几天发现了棋盘的好玩之处。从起点(0,0)走到终点(n,n)的最短路径数是C(2n,n),现在小兔又想如果不穿越对角线(但可接触对角线上的格点), 这样的路径数有多少?小兔想了很长时间都没想出来,现在想请你帮助小兔解决这个问题,对于你来说应该不难吧! Input 每次输入一个数n(1<=n<=35),当n等于-1时结束输入。 Output 对于每个输入数据输出路径数,具体格式看Sample。 Sample Input 1 3 12 -1 Sample Output 1 1 2 2 3 10 3 12 416024 """ import numpy as np def chess(): a = np.array([[0]*40]*40) # 到达(i,j)需要的路径数 for i in range(1, 37): a[0][i] = 1 for i in range(1, 37): # row for j in range(i, 37): # col if i == j: a[i][j] = a[i-1][j] # 如遇对角线,和上边相同 else: a[i][j] = a[i-1][j] + a[i][j-1] return a n = 0 while n != -1: n = input("请输入") n = int(n) a_= chess() print(a_[n][n] *2)
ea5312aa8e072f20adc94cdc3d90562c824f0320
Lusius045/LucioRP
/Estructuras repetitivas/TP2.py
564
4.0625
4
print("-------------------------------------------------------") print("SUMA DE DIVISORES:") print("-------------------------------------------------------") print("Ingrese números aleatorios, para concluir, ingrese un número negativo") num = int(input()) while (num > 0): suma = 0 for i in range (1,num+1): if num % i==0: suma = suma + i print("La suma de los divisores del número es: ", suma) print("Ingrese números aleatorios, para concluir, ingrese un número negativo") num= int(input())
e2a0eb9ec199bf83ec8051a52791eb5e22aa0e75
ntkawasaki/complete-python-masterclass
/13: Using Databases/Exception Handling/intro.py
353
4
4
# wrap code in try and except to prevent a crash def factorial(n): """Calculate n! recursively.""" if n <= 1: return 1 else: return n * factorial(n - 1) try: print(factorial(1000)) except (RecursionError, ZeroDivisionError): print("[Factorial Error/Zero Division Error]") print("\nThe program is terminating.")
68400430d4d414579210550d5f8faee661520201
zequequiel/ramda.py
/ramda/remove.py
354
3.640625
4
from toolz import curry @curry def remove(index, length, list): """Removes the sub-list of list starting at index start and containing count elements. Note that this is not destructive: it returns a copy of the list with the changes. No lists have been harmed in the application of this function""" return list[:index] + list[index + length :]
88df94d1422b7adf5b7ce7a5fdda352e65aa1ccd
chriswtanner/lectures
/lecture12/scope_example.py
233
4.03125
4
def main(): names = ["malik", "stephanie", "ellie", "rico"] for name in names: print(name) i = 3 print(i) # this is the main entry point of our entire Python program if __name__ == "__main__": main()
a32ada2d856b88e755dac19228fde49293694acf
VTBEST12/turtle-art-design
/I dont know what to name it.py
3,049
3.609375
4
import turtle turtle.colormode(255) bob=turtle.Turtle() turtle.bgcolor("black") bob.width(5) bob.speed(500) c = (217,98,175) for times in range(40): c = ("lime") bob.color(c) bob.circle(100) bob.right(7000) for times in range(30): c = ("orange") bob.color(c) bob.circle(100) bob.right(678) for times in range(20): c = ("magenta") bob.color(c) bob.circle(100) bob.right(461) for times in range(10): c = ("yellow") bob.color(c) bob.circle(100) bob.right(150) for times in range(7): c = ("red") bob.color(c) bob.circle(100) bob.right(90) bob.penup() bob.goto(-600,300) bob.pendown() for times in range(40): c = ("sky blue") bob.color(c) bob.circle(100) bob.right(7000) for times in range(30): c = ("green") bob.color(c) bob.circle(100) bob.right(678) for times in range(20): c = ("pink") bob.color(c) bob.circle(100) bob.right(461) for times in range(10): c = ("white") bob.color(c) bob.circle(100) bob.right(150) for times in range(7): c = ("brown") bob.color(c) bob.circle(100) bob.right(90) bob.penup() bob.goto(600,-300) bob.pendown() for times in range(40): c = (119,221,231) bob.color(c) bob.circle(100) bob.right(7000) for times in range(30): c = (253,252,116) bob.color(c) bob.circle(100) bob.right(678) for times in range(20): c = (227,37,107) bob.color(c) bob.circle(100) bob.right(461) for times in range(10): c = (116,66,200) bob.color(c) bob.circle(100) bob.right(150) for times in range(7): c = (252,108,133) bob.color(c) bob.circle(100) bob.right(90) bob.penup() bob.goto(-600,-300) bob.pendown() for times in range(40): c = (116,66,200) bob.color(c) bob.circle(100) bob.right(7000) for times in range(30): c = (227,37,107) bob.color(c) bob.circle(100) bob.right(678) for times in range(20): c = (159,226,191) bob.color(c) bob.circle(100) bob.right(461) for times in range(10): c = (255,110,74) bob.color(c) bob.circle(100) bob.right(150) for times in range(7): c = (252,108,133) bob.color(c) bob.circle(100) bob.right(90) bob.penup() bob.goto(600,300) bob.pendown() for times in range(40): c = (237,237,237) bob.color(c) bob.circle(100) bob.right(7000) for times in range(30): c = (255,29,206) bob.color(c) bob.circle(100) bob.right(678) for times in range(20): c = (238,32,77) bob.color(c) bob.circle(100) bob.right(461) for times in range(10): c = (253,252,116) bob.color(c) bob.circle(100) bob.right(150) for times in range(7): c = (28,211,162) bob.color(c) bob.circle(100) bob.right(90)
e662c85702ae36deaeaadd037884ded7dd2d8cbc
rybakovas/Python
/Python/Exercises/exerc5.py
239
3.796875
4
# Remove the duplicate itens in a list numbers = [1, 4, 3, 2, 1, 5, 4, 10] unique =[] for number in numbers: if number not in unique: unique.append(number) print(unique) # By Victor Rybakovas Sep 2019 - http://bit.ly/linkedin-victor
a40f0fc3d628501d01e2bd7fdcef1c31bb1aa3ab
tangneng/study_python
/files_to_folder.py
1,243
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/8/25 9:12 # @Author : superyang713 # @File : file_folder.py # @desc: 把相同文件类型的文件移动到一个文件夹中 import os import shutil def main(): dest_folder = 'E:\\N迈外迪' sort_files(dest_folder) def sort_files(dest_folder): """ parameters: dest_folder: 要整理的文件夹的绝对地址。 return: 首先按照文件的后缀建立文件夹。然后将文件放入对应的文件夹内。 特例: 只有后缀或没有后缀的文件将会不予处理。 """ files = [f for f in os.listdir(dest_folder) if os.path.isfile(os.path.join(dest_folder, f))] for f in files: new_folder = os.path.join(dest_folder, os.path.splitext(f)[-1][1:]) if not os.path.exists(new_folder): os.mkdir(new_folder) try: shutil.move(os.path.join(dest_folder, f), new_folder) except shutil.Error: if f.startswith('.'): print('{} is a dot file.'.format(f)) else: print('{} does not have file extension.'.format(f)) if __name__ == '__main__': main()
f6d46195b9961d7108b27a2e71e2a52b542c8950
KaranKaur/Leetcode
/458 - PoorPigs.py
2,073
4.125
4
""" There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour. Answer this question, and write an algorithm for the follow-up general case. If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison. """ """ Logic: With 2 pigs, poison killing in 15 minutes, and having 60 minutes, we can find the poison in up to 25 buckets in the following way. Arrange the buckets in a 5 by 5 square: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Now use one pig to find the row (make it drink from buckets 1, 2, 3, 4, 5, wait 15 minutes, make it drink from buckets 6, 7, 8, 9, 10, wait 15 minutes, etc). Use the second pig to find the column (make it drink 1, 6, 11, 16, 21, then 2, 7, 12, 17, 22, etc). Having 60 minutes and tests taking 15 minutes means we can run four tests. If the row pig dies in the third test, the poison is in the third row. If the column pig doesn't die at all, the poison is in the fifth column (this is why we can cover five rows/columns even though we can only run four tests). With 3 pigs, we can similarly use a 5 by 5 by 5 cube instead of a 5 by 5 square and again use one pig to determine the coordinate of one dimension (one pig drinks layers from top to bottom, one drinks layers from left to right, one drinks layers from front to back). So 3 pigs can solve up to 125 buckets. In general, we can solve up to (floor(minutesToTest / minutesToDie) + 1)pigs buckets this way, so just find the smallest sufficient number of pigs for example like this: """ def poor_pigs(buckets, min_to_die, min_to_test): pigs = 0 while (min_to_test/min_to_die + 1)** pigs < buckets: pigs += 1 return pigs print(poor_pigs(25, 15, 60))
4c1c3597e7301190c6b4182c0b51f03d9b1db38e
rishabht1219/software-engineering
/services/Interfaces/ICharacter.py
369
3.578125
4
from abc import ABCMeta, abstractmethod class ICharacter(metaclass=ABCMeta): """interface for the player and bear class""" @abstractmethod def move_up(self, position): pass @abstractmethod def move_down(self, position): pass @abstractmethod def move_left(self, position): pass @abstractmethod def move_right(self, position): pass
583bf829ba9fdc2a64f0ad9d1dae1f90cf1e4b3a
qixiaobo/navi-misc
/python/menu.py
798
3.78125
4
#!/usr/bin/env python import sys def menu(title, items): while True: print title itemNumber = 0 itemMap = {} for item, value in items.iteritems(): itemNumber += 1 print "%d. %s" % (itemNumber, item) itemMap[itemNumber] = value try: choice = int(sys.stdin.readline()) return itemMap[choice] except ValueError: print "Not a number, you dork" except KeyError: print "Choose something on the menu!" print if __name__ == '__main__': def runCheeseWidgets(): print "Yay, cheese" def moreBeef(): print "moo" r = menu("Boing", { "Cheese": runCheeseWidgets, "Beef": moreBeef, }) print r r()
2fb821d3432b5012844939ef9021407a6d54332a
dqureshiumar/competitive-coding-python
/xor-operation-in-an-array.py
377
3.625
4
#Author : Umar Qureshi #Leetcode's XOR Operation in an Array Python3 Solution # Problem Link : https://leetcode.com/problems/xor-operation-in-an-array/ class Solution: def xorOperation(self, n: int, start: int) -> int: nums = [] for i in range(n): nums.append(start + 2 * i) x = 0 for y in nums: x = x ^ y return x
1797ef75ac808b8ef5e2163150656f2d527d46b0
Leahxuliu/Data-Structure-And-Algorithm
/Python/巨硬/C19.找下标值与值相同的点.py
451
3.625
4
''' 有序数组找到num[i] == i的那个,进阶:数组有可能有重复值 1. 无 ''' def find(nums): if nums == []: return -1 l = 0 r = len(nums) - 1 while l <= r: mid = l + (r - l) // 2 if mid == nums[mid]: return mid elif mid < nums[mid]: r = mid - 1 else: l = mid + 1 return -1 a = find([-1,0,2,6]) print(a) a = find([-1,0,3,6]) print(a)
8550fecf338ea66c6a9b1d59cbeb4ba982006e6f
sdmgill/python
/Learning/Chapter10/10.3-Exceptions.py
940
4.1875
4
# generate an error - can't divide by 0 print(5/0) # use try/except block to handle to error try: print(5/0) except ZeroDivisionError: print("You can't divide by 0 dumbass.") # add to this print("Give me two numbers and I'll divide them.") print("Enter 'q' to quit.") while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("Second number: ") try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by 0 dumbass!") else: print(answer) # generate an error - file not found filename = 'alice.txt' with open(filename) as f_obj: contents = f_obj.read() # add exception handling filename = 'alice.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg)
00b0690298e4322de5c9d28507ae0ecb67497ad7
arpitp07/UChicago_MScA_RTIS
/Week 6/Week_6_distance.py
6,655
3.53125
4
#!/bin/python3 import math import os import random import re import sys import time random.seed(123) k_bit = 32 # # Complete the Node and CircularLinkedList class below. # class Node: # implement here. see case1 below for required attributes def __init__(self, data, k=k_bit): self.id = random.getrandbits(k) self.data = data self.next = None self.finger = {} def __repr__(self): return f'{self.data}' class CircularLinkedList: # implement here. see case 2 below for required attribute def __init__(self): self.head = None def sorted_insert(self, node): curr = self.head if not self.head: self.head = node self.head.next = self.head return elif curr.next == self.head: node.next = curr.next curr.next = node else: while True: if distance(curr.id, node.id) + distance(node.id, curr.next.id) == distance(curr.id, curr.next.id): node.next = curr.next curr.next = node return curr = curr.next def get_list(self): curr = self.head ls = [] while True: ls.append([curr.id, curr.data, curr.finger]) if curr.next == self.head: break curr = curr.next return ls def distance(a, b, k=k_bit): # implement here. measures the clockwise distance from node a to node b with respect to the id. if a > b: return 2**k - (a - b) else: return b - a def find_node(start, key): # takes an existing node in the list as the start value and searchs for the node which is responsible for the given key curr = start while True: if distance(curr.id, key) + distance(key, curr.next.id) == distance(curr.id, curr.next.id): return curr.next curr = curr.next def store(start, key, value): # finds the node responsible for the key starting from the "start" node and returns the value of the key stored in that node node = find_node(start, key) node.data[key] = value return def lookup(start, key): #find the value stored at the key starting at the node "start" and traversing the list node = find_node(start, key) return node.data[key] def update(node, k=k_bit): # updates the finger table for given node for i in range(k): finger_key = (node.id + 2**i)%2**k node.finger[i+1] = find_node(node, finger_key) def find_finger(node, key, k=k_bit): # use the nodes finger table to get the node closest to the key curr = node i = 1 dist = distance(curr.id, key) while True: if distance(curr.id, key) + distance(key, curr.next.id) == distance(curr.id, curr.next.id): return curr.next elif distance(curr.finger[i].id, key) > dist: curr = curr.finger[i-1] dist = distance(curr.id, key) i=1 elif i==k: curr = curr.finger[i] dist = distance(curr.id, key) i=1 else: i+=1 def finger_lookup(start, key): # find the value stored at the key using finger table lookups starting with node "start" node = find_finger(start, key) return node.data def finger_store(start, key, value): # store key value pair using finger tables starting with node "start" node = find_finger(start, key) node.data = value return def case3(): # what is the largest possible node id in the network if k=32? answer = 2**32 print(str(answer)+ '\n') pass def setup1(): arr = [x for x in range(0, 2 ** 5)] cll = CircularLinkedList() for i in range(len(arr)): temp = Node(arr[i]) cll.sorted_insert(temp) current = cll.head while True: update(current) current = current.next if current == cll.head: break return cll def case1(): node = Node({}, k_bit) print(str(node.id) + '\n') print(str(node.data) + '\n') print(str(node.next) + '\n') print(str(node.finger) + '\n') def case2(): cll = CircularLinkedList() print(str(cll.head) + '\n') l = [cll.sorted_insert(Node({}, k_bit)) for x in range(10)] cllist = cll.get_list() for e in cllist: for d in e: print(str(d) + ' ') print('\n') def case4(): d1 = distance(10, 10) d2 = distance(10, 100) d3 = distance(100, 10) print(str(d1) + '\n') print(str(d2) + '\n') print(str(d3) + '\n') def case5(): cll = CircularLinkedList() l = [cll.sorted_insert(Node({}, k_bit)) for x in range(10)] node = find_node(cll.head, 462568970) print(str(node.id) + '\n') print(str(node.data) + '\n') print(str(node.next.id) + '\n') def case6(): cll = CircularLinkedList() l = [cll.sorted_insert(Node({}, k_bit)) for x in range(10)] store(cll.head, 1606153229, 4) value = lookup(cll.head, 1606153229) print(str(value) + '\n') def case7(): # tests speed of regular insert arr = [x for x in range(0, 2 ** 12)] start = CircularLinkedList() start_time = time.time() for i in range(len(arr)): temp = Node(arr[i]) start.sorted_insert(temp) process_time = time.time() - start_time print("SortedInsert took {} seconds".format(process_time)) def case8(): cll = setup1() node = find_node(cll.head, 344973245) print(str(node.data)+'\n') n28 = node.finger[28] n30 = node.finger[30] print(str(n28.data)+ '\n') print(str(n30.data) + '\n') def case9(): cll = setup1() value = finger_lookup(cll.head, 344973245) print(str(value)+'\n') new_k = 2415140493 finger_store(cll.head, new_k, 701) val = finger_lookup(cll.head, new_k) print(str(val) + '\n') node = find_node(cll.head, new_k) print(str(node.data) + '\n') print(str(node.id) + '\n') # if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') # case_num = input() # globals()['case' + str(case_num)]() # .close() ########## QC ########## cll = setup1() l_node = [] curr = cll.head while True: l_node.append(curr) curr = curr.next if curr == cll.head: break l_id = [x.id for x in l_node] index = 3 l_node[index].finger = {} update(l_node[index]) node = find_finger(l_node[29], l_node[28].id-1) # node = find_node(l_node[0], cll.head.id) print(node.data, node.id) ########## Test Cases ########## # case1() # case2() # case3() # case4() # case5() # case6() # case7() # case8() # case9()