text
stringlengths
37
1.41M
''' Created on Apr 22, 2019 @author: Francesca ''' num = input("Enter your mark here:") if num =="4+": print("You got a 98" ) elif num =="4": print("You got a 90" ) elif num =="4-": print("You got a 83" ) elif num =="3+": print("You got a 78" ) elif num =="3": print("You got a 74.5" ) elif num =="3-": print("You got a 71" ) elif num =="2+": print("You got a 68" ) elif num =="2": print("You got a 64" ) elif num =="2-": print("You got a 61" ) elif num =="1+": print("You got a 58" ) elif num =="1": print("You got a 55" ) elif num =="1-": print("You got a 51" ) elif num =="0": print("You got a 49 or less" ) else: print("ERROR! place a mark between 0-4+")
import re import string def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) a = input() a = re.sub(r'[{}," "]'.format(string.punctuation), '', a) a = a.lower() print(is_palindrome(a))
n = int(input()) for i in range(1,2*n): for j in range(1,2*n): if i == j or i+j == 2*n: print('X',end='') else: print('+',end='') print('\n',end='')
def hcf(n1, n2): a = n1 while a%n2: a = a+ n1 b = n1*n2//a return b num1=int(input("")) num2=int(input("")) print(hcf(num1,num2))
""" This module implements various modules of the network. You should fill in code into indicated sections. """ import numpy as np from collections import defaultdict class LinearModule(object): """ Linear module. Applies a linear transformation to the input data. """ def __init__(self, in_features, out_features): """ Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize weights self.params['weight'] using normal distribution with mean = 0 and std = 0.0001. Initialize biases self.params['bias'] with 0. Also, initialize gradients with zeros. """ ######################## # PUT YOUR CODE HERE # ####################### w_shape = (in_features,out_features) self.params = defaultdict(float) self.grads = defaultdict(float) self.params['weights'] = np.random.normal(0,0.0001,w_shape) self.params['bias'] = np.zeros(out_features) self.grads['weights'] = np.zeros(w_shape) self.grads['bias'] = np.zeros(out_features) ######################## # END OF YOUR CODE # ####################### def forward(self, x): """ Forward pass. Args: x: input to the module Returns: out: output of the module TODO: Implement forward pass of the module. Hint: You can store intermediate variables inside the object. They can be used in backward pass computation. """ ######################## # PUT YOUR CODE HERE # ####################### self.x = x # print(self.params['weights'].shape) # print(x.shape) # print(x.dot(self.params['weights']).shape) self.out = self.x.dot(self.params['weights']) + self.params['bias'] # self.out = out ######################## # END OF YOUR CODE # ####################### # print(self.out) # self.out print('output of linear f: ',self.out) return self.out def backward(self, dout): """ Backward pass. Args: dout: gradients of the previous module Returns: dx: gradients with respect to the input of the module TODO: Implement backward pass of the module. Store gradient of the loss with respect to layer parameters in self.grads['weight'] and self.grads['bias']. """ ######################## # PUT YOUR CODE HERE # ####################### # print(self.x.shape) # print(dout.shape) self.grads['weights'] = self.x.T.dot(dout) self.grads['bias'] = np.sum(dout,axis=0,keepdims=True) dx = dout.dot(self.params['weights'].T) # print(dx.shape) # print(self.grads['weights'].shape) # exit() ######################## # END OF YOUR CODE # ####################### print('output of linear b: ',dx) return dx class SoftMaxModule(object): """ Softmax activation module. """ def forward(self, x): """ Forward pass. Args: x: input to the module Returns: out: output of the module TODO: Implement forward pass of the module. To stabilize computation you should use the so-called Max Trick - https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/ Hint: You can store intermediate variables inside the object. They can be used in backward pass computation. """ ######################## # PUT YOUR CODE HERE # ####################### print(x) s = np.max(x, axis=1) s = s[:, np.newaxis] # necessary step to do broadcasting e_x = np.exp(x - s) div = np.sum(e_x, axis=1) div = div[:, np.newaxis] self.x = e_x / div print('sanity of out of softmax f: ',self.x.sum(1)) # print(self.x.sum(1)) return self.x print('x before softmax:') # print(x) print(x) b = np.max(x) y = np.exp(x-b) # print(y) # print(y) # exit() self.x = (y / y.sum(axis = 1)) # self.x = x out =self.x print('x after softmax:') print(out) print('out sum:') print(out.sum(1)) # exit() exit() # self.x = x # b = x.max() # y = np.exp(x - b) # out = y / y.sum() ######################## # END OF YOUR CODE # ####################### return out def backward(self, dout): """ Backward pass. Args: dout: gradients of the previous modul Returns: dx: gradients with respect to the input of the module TODO: Implement backward pass of the module. """ ######################## # PUT YOUR CODE HERE # ####################### # print(dout) ds_x = self.x[:,:,None] *self.x[:,None,:] for i in range(len(self.x)): ds_x[i,:,: ] += np.diag(self.x[i,:]) dx = np.einsum('ij, ijk -> ik',dout,ds_x) print('sanity of out of softmax b: ',dx) return dx # J = -np.outer(self.x,self.x) + np.diag(self.x.flatten()) # return J # idxs = dout.shape[0] # dx = np.zeros(dout.shape) # for i in range(idxs): # d = self.x[i,:].reshape(-1,1) # d = np.eye(d.shape[0]).dot(d) - d.dot(d.T) # dx[i,:] = d.dot(dout[i,:]) # # print(dx.sum(0)) # ######################## # # END OF YOUR CODE # # ####################### # return dx class CrossEntropyModule(object): """ Cross entropy loss module. """ def forward(self, x, y): """ Forward pass. Args: x: input to the module y: labels of the input Returns: out: cross entropy loss TODO: Implement forward pass of the module. """ ######################## # PUT YOUR CODE HERE # ####################### # print(x) # print(y) # prediction_idx = x.argmax(1) # print(prediction_idx) # label_idx = y.argmax(1) # print(label_idx) # print(x) # print(x) # x = x.clip(min=1e-8,max=None) # out = (np.where(y==1,-np.log(x), 0)).sum(axis=1).mean() # for i in range(x.shape[0]): # x[i] # print(x) if x.any() <0: print('here') # print(x.sum(1)) # if x.sum() != 200: # print('meeh') out = - np.array( y*np.log(x)).sum(axis=1).mean() # out = -np.log(x[np.arange(x.shape[0]), y.argmax()]).mean() # exit() ######################## # END OF YOUR CODE # ####################### print('output of CrossE f: ',out) # print(out) return out def backward(self, x, y): """ Backward pass. Args: x: input to the module y: labels of the input Returns: dx: gradient of the loss with the respect to the input x. TODO: Implement backward pass of the module. """ ######################## # PUT YOUR CODE HERE # ####################### # print(x.shape) # print(y.shape) dx = (- y / x)/len(y) # y = y.argmax(axis=1) # m = y.shape[0] # x[range(m),y] -= 1 # dx = x/m # print(y.shape) # for i in range(m): # dx = -(1/x[i]) if y[i]== 1 else 0 # dx = - (y/x)/m ######################## # END OF YOUR CODE # ####################### print('output of CrossE b: ',dx) return dx class ELUModule(object): """ ELU activation module. """ def __init__(self,alpha=1): self.alpha = alpha # self.grads = defaultdict(float) # self.grads['weights'] = np.zeros(w_shape) # self.grads['bias'] = np.zeros(out_features) def single_forward(self,z): out = z if z >= 0 else self.alpha*(np.exp(z) -1) return out def forward(self, x): """ Forward pass. Args: x: input to the module Returns: out: output of the module TODO: Implement forward pass of the module. Hint: You can store intermediate variables inside the object. They can be used in backward pass computation. """ ######################## # PUT YOUR CODE HERE # ####################### # print(x) # self.idxs = (x>0) # print(x) # print(self.idxs) # print(self.idxs) # out = [] # print(x.shape) # print(type(x)) # print(x.shape) out = np.vectorize(self.single_forward)(x)#map(self.single_forward,x) # print(out.shape) self.z = x # self.idxs = [] # for i in range(x.shape[0]): # out.append([]) # self.idxs.append([]) # for j in range(x.shape[1]): # if x[i][j] <= 0: # self.idxs[i].append(True) # out[i].append(self.alpha*(np.exp(x[i][j])-1)) # else: # # print(x[i][j]) # self.idxs[i].append(False) # out[i].append(x[i][j]) # print('here') # exit() # ou out = np.array(out) # print(out.shape) # print(out) # exit() # out = x # print(out) ######################## # END OF YOUR CODE # ####################### print('output of ELU f: ',out) return out def single_backward(self,z): dx = z if z >= 0 else self.alpha*(np.exp(z)-1) return dx def backward(self, dout): """ Backward pass. Args: dout: gradients of the previous module Returns: dx: gradients with respect to the input of the module TODO: Implement backward pass of the module. """ ######################## # PUT YOUR CODE HERE # ####################### # print(dout) # idxs = np.where(dout>0) # print(self.idxs) # print(self.idxs) dx = np.vectorize(self.single_backward)(self.z) # print(dx.shape) # print(self.idxs.shape) # print(self.idxs) # dx = 1 if z > 0 else self.alpha*np.exp(z) # for k,(i,j) in enumerate(zip(self.idxs,dout)): # for l,(ii,jj) in enumerate(zip(i,j)): # # print(ii,jj) # if ii: # dout[k,l] = self.alpha*(np.exp(dout[k,l])) # else: # dout[k,l] = 1 # exit() # # other_idxs = not self.idxs.all() # # for i in range(dout.shape[0]): # # for j in range(dout.shape[1]): # # if i == # dout[self.idxs] = self.alpha*(np.exp(dout[self.idxs])) # dout[other_idxs] = 1 # dx = dout # print(dx.shape) # print(dx) ######################## # END OF YOUR CODE # ####################### print('output of ELU b: ',dx) return dx
class Triangle(object): number_sides = 3 def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 def check_angles(self): sum_angles = [self.angle1, self.angle2, self.angle3] if sum(sum_angles) == 180: return True else: return False class Equilateral(Triangle): angle = 60 def __init__(self): self.angle1 = self.angle self.angle2 = self.angle self.angle3 = self.angle my_triangle = Triangle(60,60,60) print my_triangle.number_of_sides print my_triangle.check_angles()
import math class MinHeap: def __init__(self, list=[]): self.heap = list self.heap_size = len(list) self.build() def print_heap(self): i=0 while i< self.heap_size: j = min(self.left(i), self.heap_size) while i<j: print(self.heap[i], end = ' ') i+=1 print("\n") return "" def parent(self, key): return int(math.floor((key-1)/2)) def left(self, key): return 2*key+1 def right(self,key): return 2*key+2 def heapify(self, i): l = self.left(i) r = self.right(i) if l<self.heap_size and self.heap[l][0]<self.heap[i][0]: min = l else: min = i if r<self.heap_size and self.heap[r][0]<self.heap[min][0]: min = r if min !=i: aux = self.heap[i] self.heap[i] = self.heap[min] self.heap[min] = aux self.heapify(min) def build(self): lastNonLeaf = int(math.floor((len(self.heap)-1)/2)) for i in range(lastNonLeaf, -1, -1): self.heapify(i) def insert(self, priority, label): newNode = [0,0] newNode[0] = priority newNode[1] = label self.heap_size+=1 self.heap.append(newNode) self.decrease_priority(self.heap_size-1, priority) def extract_min(self): if self.heap_size<1: raise Exception("heap underflow") else: min = self.heap[0] self.heap[0] = self.heap[self.heap_size-1] self.heap_size-=1 self.heapify(0) del self.heap[self.heap_size] return min def decrease_priority(self, i, priority): if priority > self.heap[i][0]: raise Exception("new priority is higher than current priority") else: self.heap[i][0] = priority while i>0 and self.heap[self.parent(i)][0] > self.heap[i][0]: aux = self.heap[i] self.heap[i] = self.heap[self.parent(i)] self.heap[self.parent(i)] = aux i = self.parent(i) def extract_max(self): if self.heap_size<1: raise Exception("heap underflow") else: max = int(math.floor(self.heap_size/2)) for i in range(int(math.floor(self.heap_size/2))+1, self.heap_size-1): if self.heap[i] > self.heap[max]: max = i maxEl = self.heap[max] if max == self.heap_size-1: del self.heap[self.heap_size-1] self.heap_size-=1 else: self.heap[max] = self.heap[self.heap_size-1] del self.heap[self.heap_size-1] self.heap_size-=1 self.heapify(max) return (max, maxEl) import unittest class TestMinHeapMethods(unittest.TestCase): def test_parent(self): heap = MinHeap() self.assertEqual(heap.parent(1), 0) self.assertEqual(heap.parent(2), 0) self.assertEqual(heap.parent(3), 1) self.assertEqual(heap.parent(4), 1) self.assertEqual(heap.parent(5), 2) self.assertEqual(heap.parent(6), 2) def test_left(self): heap = MinHeap() self.assertEqual(heap.left(0), 1) self.assertEqual(heap.left(1), 3) self.assertEqual(heap.left(2), 5) def test_right(self): heap = MinHeap() self.assertEqual(heap.right(0), 2) self.assertEqual(heap.right(1), 4) self.assertEqual(heap.right(2), 6) def test_heapify(self): heap = MinHeap() heap.heap = [[6,6],[2,2],[4,4],[3,3],[5,5]] heap.heap_size = 5 heap.heapify(0) self.assertEqual(heap.heap[0][0], 2) self.assertEqual(heap.heap[1][0], 3) self.assertEqual(heap.heap[3][0], 6) def test_extract_min(self): heap = MinHeap() heap.heap = [[6,6],[2,2],[4,4],[3,3],[5,5]] heap.heap_size = 5 heap.heapify(0) min = heap.extract_min() self.assertEqual(min[0], 2) self.assertEqual(heap.heap[0][0], 3) self.assertEqual(heap.heap[1][0], 5) for i in range(1,5): heap.extract_min() with self.assertRaises(Exception): heap.extract_min() def test_decrease_priority(self): heap = MinHeap() heap.heap = [[6,6],[2,2],[4,4],[3,3],[5,5]] heap.heap_size = 5 heap.heapify(0) heap.decrease_priority(4,0) self.assertEqual(heap.heap[0][1], 5) self.assertEqual(heap.heap[1][0], 2) self.assertEqual(heap.heap[4][0], 3) def test_extract_max(self): heap = MinHeap() heap.heap = [[6,6],[2,2],[4,4],[3,3],[5,5]] heap.heap_size = 5 heap.heapify(0) max = heap.extract_max() self.assertEqual(max[1][0], 6) self.assertEqual(heap.heap[0][0], 2) self.assertEqual(heap.heap[3][0], 5) for i in range(1,5): heap.extract_max() with self.assertRaises(Exception): heap.extract_max() if __name__ == '__main__': unittest.main()
#### Basics of randomness & simulation ## Poisson random variable # Initialize seed and parameters # Poisson distribution, which is typically used for modeling the average rate at which events occur np.random.seed(123) lam, size_1, size_2 = 5, 3, 1000 # Draw samples & calculate absolute difference between lambda and sample mean samples_1 = np.random.poisson(lam, size_1) samples_2 = np.random.poisson(lam, size_2) answer_1 = abs(lam - samples_1.mean()) answer_2 = abs(lam - samples_2.mean()) print("|Lambda - sample mean| with {} samples is {} and with {} samples is {}. ".format(size_1, answer_1, size_2, answer_2)) # Shuffle the deck np.random.shuffle(deck_of_cards) # Print out the top three cards card_choices_after_shuffle = deck_of_cards[0:3] print(card_choices_after_shuffle) # Define die outcomes and probabilities die, probabilities, throws = [1,2,3,4,5,6], [1/6, 1/6, 1/6, 1/6, 1/6, 1/6], 1 # Use np.random.choice to throw the die once and record the outcome outcome = np.random.choice(die, size=throws, p=probabilities) print("Outcome of the throw: {}".format(outcome[0])) #def perform_bernoulli_trials(n, p): """Perform n Bernoulli trials with success probability p and return number of successes.""" # Initialize number of successes: n_success n_success = 0 # Perform trials for i in range(n): # Choose random number between zero and one: random_number random_number=np.random.random() # If less than p, it's a success so add one to n_success if random_number<p: n_success +=1 return n_success
# Libreria principal para hacer la aplicación Web. import streamlit as st # Libreria para manipular datos. import pandas as pd # Libreria para hacer cálculos numéricos import numpy as np import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt # Para correr el programa, en un terminal se escribe lo siguiente: # streamlit run app.py #DATA_URL = ("/home/cicada/Downloads/rhyme/streamlit-sentiment/Tweets.csv") st.title("Sentiment Analysis of Tweets about US Airlines") # Título para la barra lateral. st.sidebar.title("Sentiment Analysis of Tweets") # Incluyendo una anotación que va en la página principal. st.markdown("This application is a Streamlit dashboard used " "to analyze sentiments of tweets 🐦🦜") st.sidebar.markdown("This application is a Streamlit dashboard used " "to analyze sentiments of tweets 🐦") # Esto es para que los datos sólo se carguen una vez. Va a ser persistente en el Caché. @st.cache(persist=True) # Función para cargar los datos que vamos a utilizar. def load_data(): data = pd.read_csv("Tweets.csv") # COnviertiendo una columna en tipo de fecha. data['tweet_created'] = pd.to_datetime(data['tweet_created']) return data # Cargando los datos. data = load_data() # Para hacer pruebas. Puedo imprimir los datos. # st.write(data) # Subtítulo en la barra lateral. st.sidebar.subheader("Show random tweet") # Creando las opciones de selección de sentimientos. EL título es Sentiment. Las opciones 'positive', 'neutral', 'negative' random_tweet = st.sidebar.radio('Sentiment', ('positive', 'neutral', 'negative')) # Esta es la funcionalidad para mostrar de forma aleatoria los tweets. # Lo mostramos en la barra lateral. Hacemos un query. La columna a utilizar es # airline_sentiment que debe ser igual la opción a la que selecciona el usuario # "random_tweet". Necesario utilizar "@" para acceder a la variable seleccionada. # La columna donde está el texto es "text". Sólo mistramos un Tweet de forma aleatoria sample(n=1) # Para sólo devolver texto y no un DataFrame indicamos la "celda" iat[0, 0], es decir la fila y la columna que en este caso es la primera (0). st.sidebar.markdown(data.query("airline_sentiment == @random_tweet")[["text"]].sample(n=1).iat[0, 0]) # Creando otro subtítulo. st.sidebar.markdown("### Number of tweets by sentiment") # Crea un selectbox con dos opciones. key='1' es para utilizar esto para diferentes visualizaciones. select = st.sidebar.selectbox('Visualization type', ['Bar plot', 'Pie chart'], key='1') sentiment_count = data['airline_sentiment'].value_counts() # Conteo de los Tweets según sentimiento. # Puedo imprimir la tabla con: st.write(sentiment_count) # Creo un DataFrame. Primera Columna es Sentimen, utiliza el Index. La segunda columna el el conteo de Tweets. sentiment_count = pd.DataFrame({'Sentiment':sentiment_count.index, 'Tweets':sentiment_count.values}) # Dejamos el checkbox hide por default. "If not". Hide True. if not st.sidebar.checkbox("Hide", True): # Texto a mostrar st.markdown("### Number of tweets by sentiment") # Lo que se debe hacer si seleccionan "Bar plot" if select == 'Bar plot': # Configurando la imagen a mostrar. Los valores en X y en Y. Los colores van de acuerdo a los Tweets. height=500 son los pixeles. fig = px.bar(sentiment_count, x='Sentiment', y='Tweets', color='Tweets', height=500) # Esto es para mostrar la gráfica. st.plotly_chart(fig) # Else para indicar la otra opción que tenemos. else: fig = px.pie(sentiment_count, values='Tweets', names='Sentiment') st.plotly_chart(fig) # Puede mostrar los datos en un mapa con st.map(data) # Se requiere tener la latitud y la altitud. st.sidebar.subheader("When and where are users tweeting from?") # Creamos un slider que va de cero a 23. Otra forma de hacer es así: # hour = st.sidebar.number_input("Hour to look at", min_value=1, max_value=24) hour = st.sidebar.slider("Hour to look at", 0, 23) # Esto me permite ver los Tweets de acuerdo a la hora seleccionada. Utilizamos la fecha de los Tweets. modified_data = data[data['tweet_created'].dt.hour == hour] # Creando checkbox que permite ver o no la visualización. La visualización es hiden by default. Toca indicar key = 1. if not st.sidebar.checkbox("Close", True, key='1'): # Mensaje st.markdown("### Tweet locations based on time of day") # Muestra los valores. st.markdown("%i tweets between %i:00 and %i:00" % (len(modified_data), hour, (hour + 1) % 24)) # Mostramos el dataframe con los datos seleccionados para gradicarlos en el mapa. st.map(modified_data) # Si se selecciona mostrar los datosm entonces, mostrarlos. if st.sidebar.checkbox("Show raw data", False): st.write(modified_data) st.sidebar.subheader("Total number of tweets for each airline") each_airline = st.sidebar.selectbox('Visualization type', ['Bar plot', 'Pie chart'], key='2') airline_sentiment_count = data.groupby('airline')['airline_sentiment'].count().sort_values(ascending=False) airline_sentiment_count = pd.DataFrame({'Airline':airline_sentiment_count.index, 'Tweets':airline_sentiment_count.values.flatten()}) if not st.sidebar.checkbox("Close", True, key='2'): if each_airline == 'Bar plot': st.subheader("Total number of tweets for each airline") fig_1 = px.bar(airline_sentiment_count, x='Airline', y='Tweets', color='Tweets', height=500) st.plotly_chart(fig_1) if each_airline == 'Pie chart': st.subheader("Total number of tweets for each airline") fig_2 = px.pie(airline_sentiment_count, values='Tweets', names='Airline') st.plotly_chart(fig_2) @st.cache(persist=True) def plot_sentiment(airline): df = data[data['airline']==airline] count = df['airline_sentiment'].value_counts() count = pd.DataFrame({'Sentiment':count.index, 'Tweets':count.values.flatten()}) return count st.sidebar.subheader("Breakdown airline by sentiment") # Vamos a comparar más de una aerolínea a la vez. choice = st.sidebar.multiselect('Pick airlines', ('US Airways','United','American','Southwest','Delta','Virgin America')) # Para que no salga ningún error, indicamos que la elección debe ser mayor a cero. if len(choice) > 0: st.subheader("Breakdown airline by sentiment") breakdown_type = st.sidebar.selectbox('Visualization type', ['Pie chart', 'Bar plot', ], key='3') # Cada figura debe tener un nombre diferente. En este caso fig_3 fig_3 = make_subplots(rows=1, cols=len(choice), subplot_titles=choice) if breakdown_type == 'Bar plot': for i in range(1): for j in range(len(choice)): fig_3.add_trace( go.Bar(x=plot_sentiment(choice[j]).Sentiment, y=plot_sentiment(choice[j]).Tweets, showlegend=False), row=i+1, col=j+1 ) fig_3.update_layout(height=600, width=800) st.plotly_chart(fig_3) else: fig_3 = make_subplots(rows=1, cols=len(choice), specs=[[{'type':'domain'}]*len(choice)], subplot_titles=choice) for i in range(1): for j in range(len(choice)): fig_3.add_trace( go.Pie(labels=plot_sentiment(choice[j]).Sentiment, values=plot_sentiment(choice[j]).Tweets, showlegend=True), i+1, j+1 ) fig_3.update_layout(height=600, width=800) st.plotly_chart(fig_3) st.sidebar.subheader("Breakdown airline by sentiment") choice = st.sidebar.multiselect('Pick airlines', ('US Airways','United','American','Southwest','Delta','Virgin America'), key=0) if len(choice) > 0: # Me muestra los datos que están en Choice. isin(choice) choice_data = data[data.airline.isin(choice)] fig_0 = px.histogram( choice_data, x='airline', y='airline_sentiment', histfunc='count', color='airline_sentiment', # facet_col='airline_sentiment' es para unir varios gráficos por esa variable. # Colocamos los lables pero le cambiamos el nombre a tweets labels={'airline_sentiment':'tweets' facet_col='airline_sentiment', labels={'airline_sentiment':'tweets'}, height=600, width=800) # Esto es para mostrar la figura creada st.plotly_chart(fig_0) # st.sidebar.header("Word Cloud") # Los botones de selección. word_sentiment = st.sidebar.radio('Display word cloud for what sentiment?', ('positive', 'neutral', 'negative')) if not st.sidebar.checkbox("Close", True, key='3'): # %s es para imprimir el sentimiento seleccionado. st.subheader('Word cloud for %s sentiment' % (word_sentiment)) df = data[data['airline_sentiment']==word_sentiment] # Uniendo los comentarios. words = ' '.join(df['text']) # Removiendo cosas que no nos dicen nada como 'http' and '@' y 'RT' processed_words = ' '.join([word for word in words.split() if 'http' not in word and not word.startswith('@') and word != 'RT']) # QUitando las palabnras que no dicen nada stopwords=STOPWORDS wordcloud = WordCloud(stopwords=STOPWORDS, background_color='white', width=800, height=640).generate(processed_words) plt.imshow(wordcloud) plt.xticks([]) plt.yticks([]) st.pyplot()
def primes(n): """Prints a statement about a number whether it is prime or not, for all the numbers in the range of 2 to n""" if n <= 0: print('Please provide numbers greater than 0') elif n > 0 and n < 2: print(n, 'is not a prime number') elif n == 2: print("2 is a prime number") else: for i in range(2, n+1): for j in range(2, i): if i % j == 0: print(i, 'equals', j , '*', i//j) break else: print(i, 'is a prime number') n = int(input("Enter the limit for prime numbers\n")) primes(n)
import math def nums(): print("Numeric operations ") print('2+2 = ', 2+2) print('50 - 5*6 = ', 50 - 5*6) print('17/3 = ', 17/3) print('17//3 = ', 17//3) print('17%3 = ', 17%3) print('2**2 = ', 2**2) print('4**0.5 = ', 4**0.5) print('2**0.5 = ', 2**0.5) length = 17 width = 3 print('Area(lxb): ', length * width, ' mt.sq') print("Euler's number (e): ", (1 + (1/100000)) ** 100000 ) print("Complex numbers (2+3i): ", (2+3j) * 20) print("PI: ", math.pi) def strs(): print(r'C:\User\name\Desktop is path to desktop') print('''\n Play snake game in python keys: <- move left -> move right v move down ^ move up Enoy !!!!!!!!! ''') print('Py' 'thon') print('Py' + 'thon') print('Mi' + 'ssi' * 2 + 'p' * 2 + 'i') text = ('Webshop is a web application' ' with persistence') print(text) word = 'Python' print(word[0]) print(word[-6]) print(word[1:3]) print(word[:4]) print(word[2:]) print('length of text: ', len(text)) print() def listings(): squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] squares_copy = squares[:] print(squares_copy[:5]) # concatenate lists with '+' operator more_squares = squares_copy + [121, 144, 169, 196, 225] print(more_squares[6:]) cubes = [1, 8, 27, 61] cubes[3] = 64 cubes.append(125) print(cubes) letters = ['a', 'b', 'c', 'd', 'e', 'f'] letters[2:5] = ['C', 'D', 'E'] print(letters) # empty list letters[:] = [] print(letters) # nested lists n = [[1, 2, 3, 4], squares, cubes] print(n) print() # nums() # strs() listings()
# coding: utf-8 # ##### Shambhavi Srivastava # In[294]: import pandas as pd import numpy as np import sklearn.metrics as sm from sklearn.neighbors import KNeighborsClassifier from sklearn.cross_validation import train_test_split import matplotlib import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') matplotlib.style.use('ggplot') # #### Introduction # # The project aims to utilize the music rating database of Yahoo! Music to develop a rating predictor system. The database contains list of users (identifiable by User ID) who have provided Rating for a particular song (identifiable by Song ID).<b>Using these three metrics, a rating predictor system is devised which could predict a particular user’s rating for a new song </b>. # In[295]: # Read the dataset yahoo_data = pd.read_csv("ydata-ymusic-rating-study-train.txt",header=None,delimiter='\t', quoting=3 , names= ['userId','SongId','Ratings']) yahoo_data.shape # In[296]: yahoo_data.head() # ### Qs 1(A) : Exploratory statistics and plots # ### Rating-Frequency Plot # # Below table shows the rating and its frequency : # # | 1 | 97844 | # |--- |------- | # | 2 | 39652 | # | 3 | 49131 | # | 4 | 48480 | # | 5 | 76597 | # In[297]: # Plot rating-frequency fig, ax = plt.subplots() yahoo_data['Ratings'].value_counts(sort=False).plot(ax=ax, kind='bar') plt.ylabel('Frequency') plt.xlabel('Rating') # #### Summary Stats : User based # In[298]: # Dataframe with relation between user and ratings, drop the song id column yahoo_user_data = yahoo_data.drop(["SongId"], axis=1) yahoo_user_data.head() # Calculate Average rating given by each user, and its SD. yahoo_user_ratings= yahoo_user_data.groupby(["userId"]).mean() yahoo_user_ratings.columns = ["Mean Rating"] yahoo_user_ratings["Standard Deviation"] = yahoo_user_data.groupby(["userId"]).std() yahoo_user_ratings["Count"] = yahoo_user_data.groupby(["userId"]).transform("count") yahoo_user_ratings.head() fig, ax = plt.subplots() yahoo_user_ratings['Mean Rating'].plot(ax=ax, kind='hist') plt.ylabel('Frequency') plt.xlabel('Mean Users Rating') yahoo_user_ratings.head() # #### Summary Stats : Song based # In[299]: # Data define the relation between songs and its ratings yahoo_song_data = yahoo_data.drop(["userId"], axis=1) yahoo_song_data.head() #Calculate the Average rating given to each song and its SD yahoo_song_ratings = yahoo_song_data.groupby(["SongId"]).mean() yahoo_song_ratings.columns = ["Mean Rating"] yahoo_song_ratings["Standard Deviation"] = yahoo_song_data.groupby(["SongId"]).std() yahoo_song_ratings["Count"] = yahoo_song_data.groupby(["SongId"]).transform("count") yahoo_song_small = yahoo_song_ratings[:1000] fig, ax = plt.subplots() yahoo_song_ratings['Mean Rating'].plot(ax=ax, kind='hist', color='k') plt.ylabel('Frequency') plt.xlabel('Mean Songs Rating') yahoo_song_ratings.head() # <i> For above summary stats : song based not surprisingly, most songs have intermediate mean rating and only few items have a mean rating on extreme high or low ends of the scale. Indeed, the distribution of song mean ratings follow a unimodal distribution, with a mode at 2.8 as shown above.</i> # <i>Interestingly, the distribution of song mean ratings presented in above is slightly different from the distribution of mean ratings of users, depicted before: the distribution is now bit skewed, with mode shifted to a mean rating of 3.8(approx). Different rating behavior of users accounts for the apparent difference between the distributions. It turns out that users who rate more songs tend to have considerably lower mean ratings.</i> # ### Qs 1(B) : Clustering # ###### Features Selection : # # <i>Below are expanded feature selection for the process of clustering. After analyses the below features seems to have higher correlations to the ratings</i> # # ##### User -based statistical features # 1. User's average rating on song x # 2. User's rating count on song x # ##### Songs-based statistical features # 4. Number of ratings # 5. Song's rating mean # #### Data Processing: # # <i>For better evaluation split the data set into two 80% and 20% for training and testing</i> # In[300]: #Split test and train data yahoo_train, yahoo_test = train_test_split(yahoo_data, test_size = 0.2) print(len(yahoo_train)) yahoo_train.head() # In[301]: # split training data into data and target yahoo_data = yahoo_train.drop(yahoo_train[[2]],axis=1) yahoo_target= yahoo_train.drop(yahoo_train[[0,1]],axis=1) # ###### Below block redfine the feature as User-based Features i.e User's average rating on song x , User's rating count on song x # In[302]: # User-based Features # User's average rating on song x user_feat = yahoo_train.drop("userId",1) user_avg_rating = user_feat[['SongId', 'Ratings']].groupby(["SongId"], as_index = False).mean() # User's rating count on song x user_ctn_ratin = user_feat[['SongId', 'Ratings']].groupby(["SongId"], as_index = False).count() # ###### Merge the above two Data frames for proper clustering and then split the data into train and test set # In[303]: #merge two data-sets on songid df_new = pd.merge(user_avg_rating,user_ctn_ratin, on='SongId') df_new.head() #Split into test and train df_new_train,df_new_test = train_test_split(df_new, test_size=0.25) df_new_train.head() # ##### K-Means Clustering # <i>This learning model involves both the input(x) and output(y). During the learning process the error between the predicted outcome and the actual outcome is used to train the system. # # Below block of code train the model for one particular user and predict the rating by user based on rating given by user in past. For this K-means is used to separate the data into <b>three clusters</b> using features as <b>"Rating Mean" and "Count of Rating"</b> w.r.t the user.The target is the actual rating provided by the user.</i> # In[304]: yahoo_user_11= yahoo_train.loc[yahoo_train["userId"]==1] yahoo_user_11.head() # merge dataframe df_main = pd.merge(yahoo_user_11,df_new_train, on='SongId') print(df_main) len_rows=len(df_main) # In[305]: # K-Means feat_cols = ["Ratings_x" , "Ratings_y"] yahoo_data = df_main[feat_cols] #data x = pd.DataFrame(yahoo_data) x.columns = ["Rating_mean" , "Count"] yahoo_target = df_main.Ratings #target y = pd.DataFrame(yahoo_target) y.columns = ["Targets"] np.unique(y) x.head() # ##### Visualise the data # <i>For data visualisation scatter plot is used looking at the Rating mean and number of ratings assigned to the song </i> # In[306]: # Set plot plt.figure() # Plot features (Rating mean , Count of Ratings) plt.subplot() plt.scatter(x.Rating_mean, x.Count, c=y.Targets) plt.title('Data Visualisation Intial') # #### Build the K-means Model : # # <i>For this first create the model and specify the number of clusters the model should find(n_clusters=3) and then fit the model</i> # In[307]: from sklearn.cluster import KMeans # K Means Cluster model = KMeans(n_clusters=3) model.fit(x) # view the results model.labels_ # ##### Visualise the classifer results : # <i>Plot the actual classes against the predicted classes from the K Means model</i> # In[308]: # Set the size of the plot plt.figure(figsize=(14,7)) # Plot the Original Classifications plt.subplot(1, 2, 1) plt.scatter(x.Rating_mean, x.Count, c=y.Targets, s=40) plt.title('Real Classification') # Plot the Models Classifications plt.subplot(1, 2, 2) plt.scatter(x.Rating_mean, x.Count, c=model.labels_, s=40) plt.title('K Mean Classification') # ##### Performance Measures : # <i>In order to measure the performance calculated the accuracy and also the confusion matrix. # # For this we need two values of y(target) which is the true(original) values and predicted models values.</i> # In[309]: # Performance Metrics sm.accuracy_score(y, model.labels_) # In[310]: # Confusion Matrix sm.confusion_matrix(y, model.labels_) # ### Qs 2(A) Story-telling and/or hypothesis generation # #### Methodology: # <i>The metric Song ID in itself is not a meaningful number for analysis since it merely represents a song. However, Song ID can be utilize to process the dataset and develop a set of features which could be used for KNN algorithm. # # For a particular user, the rating predictor mechanism is implemented as follows: # # <b>Step1.</b> For a given User ID, find the songs rated by the user and the rating provided by him/her. Lets call the list of ratings as ‘user_rating_target’ # # <b>Step2.</b> For each song found in Step1, find the number of ratings assigned to the song. Lets call this data set as ‘Ratings_y’ # # <b>Step3.</b> For each song found in Step1, find the mean of the ratings (calculated over the complete dataset). Lets call this mean rating dataset as ‘Ratings_x’ # # <b>Step4.</b>. Using “Ratings_x” and “Ratings_y” as the predicting features and by using ‘user_rating_target’ as the target, KNN algorithm is implemented. The underlying idea is to use the number of ratings for a given song and its mean rating to predict the rating given by a particular user. # # For any number of dataset entries available for a given User ID, 75% data is used for training the model and 25% is used for testing the model.</i> # # #### K-NN (K-Nearest Neighbors) # In[311]: # K-NN # user with ID 1 yahoo_user_11= yahoo_train.loc[yahoo_train["userId"]==1] yahoo_user_11.head() df_main = pd.merge(yahoo_user_11,df_new_train, on='SongId') print(df_main) len_rows=len(df_main) # In[312]: x= df_main["Ratings_x"] y = df_main["Ratings_y"] plt.scatter(x,y,color="purple") # In[313]: # KNN feat_cols = ["Ratings_x" , "Ratings_y"] yahoo_data = df_main[feat_cols] #data yahoo_target = df_main.Ratings #target np.unique(yahoo_target) # In[314]: yahoo_X_train , yahoo_X_test = train_test_split(yahoo_data, test_size=0.25) yahoo_y_train, yahoo_y_test = train_test_split(yahoo_target, test_size=0.25) yahoo_X_test.shape # In[315]: # Create and fit a nearest-neighbor classifier knn = KNeighborsClassifier(n_neighbors=3) knn.fit(yahoo_X_train, yahoo_y_train) y_hat = knn.predict(yahoo_X_test) print(metrics.accuracy_score(yahoo_y_test, y_hat)) # ##### Plot the accuarcies score for train and test data # In[316]: train_accuracies, test_accuracies = [], [] k_vals = list(range(1,int(len_rows*0.7))) print(k_vals) for k in k_vals: knn = KNeighborsClassifier(n_neighbors=k) knn.fit(yahoo_X_train, yahoo_y_train) y_train_hat = knn.predict(yahoo_X_train) y_test_hat = knn.predict(yahoo_X_test) test_accuracies.append(metrics.accuracy_score(yahoo_y_test, y_test_hat)) train_accuracies.append(metrics.accuracy_score(yahoo_y_train, y_train_hat)) plt.plot(k_vals, train_accuracies, label='train perf') plt.plot(k_vals, test_accuracies, label='test perf') plt.legend(); # <i> Consider the data graph for User ID 1. By plotting the accuracy(fig above) as a function of the ‘number of nearest neighbours’ (k), it can be seen that for test data the accuracy improves as compared to the training data. Further, it seems that for k>7 or higher, the model tends be having a consistent low inaccuracy.</i>
def titulo(msg): print('-'*30) print(f'{msg:^30}') print('-'*30) def soma(a, b): print(f'{a} + {b} = {a+b}') def contador(*val): # * desempacotamento tam = len(val) print(f'O tamanho de {val} = {tam}') def dobrar(lst): for p in range(0, len(lst)): lst[p] *= 2 print(f'Lista dobrada: {lst}') def somatodos(* val): # * desempacotamento s = 0 for num in val: s += num print(f'A soma de {val} é {s}') # Programa principal titulo('== Funções ==') soma(5, 7) soma(b=6, a=11) contador(1, 3, 5, 2, 6) valores = [1, 5, 4, 8, 10] dobrar(valores) somatodos(2, 5, 4, 48, 12, 1) print() # == FUNÇÕES 2 == titulo('== Funções 2 ==') # DOCSTRINGS em Funções e Parâmetros padrão/opcional def somar(a=0, b=0, c=0): # 'param' = 0 para definir como padrão/opcional """ -> soma os parâmetros passados e printa na tela - caso não passe um parâmetro, o mesmo valerá 0 :param a: soma com param b e c :param b: soma com param a e c :param c: soma com param a e b :return: sem retorno Função criada por Lucas Diogo Martins """ s = a + b + c print(f'A soma vale {s}') help(somar) somar(1, 3, 6) somar(5, 11) somar(b=4, c=6) print('\n', '~'*40) # Retorno de valores def fatorial(num=1): f = 1 for c in range(num, 0, -1): f *= c return f # retorna o valor da variável f f1 = fatorial(4) f2 = fatorial(5) f3 = fatorial() print(f'Os resultados são {f1}, {f2} e {f3}.') print('\n', '~'*40) # Retorno Booleano def par(n): if n % 2 == 0: return True else: return False num = int(input('Digite um número: ')) if par(num): print('é par') else: print('não é par')
numeros = [[], []] for c in range(1, 8): num = int(input(f'Digite o {c}° valor: ')) if num % 2 == 0: numeros[0].append(num) else: numeros[1].append(num) numeros[0].sort() numeros[1].sort() print(f'Os valores pares digitados foram: {numeros[0]}') print(f'Os valores ímpares digitados foram: {numeros[1]}')
nome = input('Escreva seu nome completo: ').title().split() print('Seu primeiro nome é', nome[0]) print('Seu último nome é', nome[len(nome)-1])
from time import sleep def contagem(i, f, p): print('~' * 40) if p == 0: # Segunda opção para p == 0 print('passo = 1') p = 1 # end if p < 0: p = -p # p *= -1 print(f'Contagem de {i} até {f} de {p} em {p}') sleep(1) if i <= f: while i <= f: print(i, end=' ') i += p sleep(0.3) else: while i >= f: print(i, end=' ') i -= p sleep(0.3) print('FIM') print() # Principal contagem(1, 10, 1) contagem(10, 0, 2) print('='*50) print('Agora é sua vez de personalizar a contagem!') ini = int(input('Início: ')) fim = int(input('Fim: ')) while True: # Opção para p == 0 pas = int(input('Passo: ')) if pas != 0: break print(' * ERRO: digite um valor diferente de 0!') contagem(ini, fim, pas)
val = input('Digite algo\n >') print('O tipo primitivo desse valor é', type(val)) print('Possui apenas espaços: ', val.isspace()) print('é numérico: ', val.isnumeric()) print('é alfabético: ', val.isalpha()) print('é alfanumérico: ', val.isalnum()) print('está em maiúsculas: ', val.isupper()) print('está em minúsculas: ', val.islower()) print('está capitalizado: ', val.istitle())
times = ('Flamengo', 'Palmeiras', 'Corinthians', 'Atlético-GO', 'São Paulo', 'Fluminense', 'Atlético-MG', 'Fortaleza', 'Internacional', 'Sport', 'Ceará', 'Grêmio', 'Bahia', 'Santos', 'Chapecoense', 'Bragantino', 'Athletico-PR', 'América-MG', 'Cuiabá', 'Juventude') print('-=-' * 20) print(f'Lista de Times: {times}') print('-=-' * 20) print(f'Os 5 primeiros são: {times[0:5]}') print('-=-' * 20) print(f'Os últimos 4 colocados são: {times[-4:]}') print('-=-' * 20) print(f'Times em Ordem alfabética {sorted(times)}') print('-=-' * 20) print(f'O Chapecoense está na {times.index("Chapecoense") + 1}° posição') print('-=' * 30)
from random import randint num = randint(1, 10) print('Pensei em um número de 1 à 10, será que adivinhas?') palp = int(input(' >> ')) tent = 1 while palp != num: if num > palp: palp = int(input('Mais... \n >> ')) elif num < palp: palp = int(input('Menos... \n >> ')) tent += 1 print('Adivinhou em {} tentativas'.format(tent))
print('-'*30) print('Sequência Fibonacci \n') n = int(input('Quantidade de Termos: ')) print('-'*30) t0 = 0 t1 = 1 print('{} -> {}'.format(t0, t1), end='') c = 2 while c < n: t2 = t0 + t1 print(' -> {}'.format(t2), end='') t0 = t1 t1 = t2 c += 1 print(' -> fim')
valores = list() while True: val = int(input('Digite um valor: ')) if val not in valores: valores.append(val) print('Valor adicionado com sucesso...') else: print('* Valores duplicados não são adicionados à lista...') resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0] if resp == 'N': break print('-=-'*15) valores.sort() print(f'\nVocê digitou os valores: {valores}')
try: a = float(input('Numerador: ')) b = float(input('Denominador: ')) r = a / b except: print('Infelizmente tivemos um problema :(') else: print(f'O resultado de {a} / {b} é {r:.1f}') finally: print('Volte sempre!') print() # ============================================ try: a = int(input('Numerador: ')) b = int(input('Denominador: ')) r = a / b except (ValueError, TypeError): print('Tivemos um problema de tipos de dados que você digitou') except ZeroDivisionError: print('Impossível dividir um número por zero') except KeyboardInterrupt: print('O usuário não informou os dados') except Exception as erro: print(f'Ocorreu um erro: {erro.__cause__}') else: print(r)
## Use % to print every third word in the list list = ['alpha','beta','gamma','delta','epsilon','zeta','eta'] for i, letter in enumerate(list,1): if i % 3 == 0: print(letter)
class Person: # __init__ -- potreban je za inicijalizaciju kalase # svaki argument koji passamo unutra postaje obavezan za stvaranje objekta # argument self stavljamo zato sto on referira na bas taj objekt tipa da age nije univerzalan # nego je vezan za tu osobu nad kojom je pozvan, koju stvara def __init__(self, name, age, favourite_foods): self.age= age self.name = name self.favourite_foods = favourite_foods def __str__(self): return 'Name: {} Age: {} Favourite food: {}'.format(self.name, self.age, self.favourite_foods[0]) # moramo passat self da mozemo doci do godina def birth_year(self): return 2015 - self.age people = [Person('Ed', 11,['hotdogs', 'jawbreakers']), Person('Edd', 11, ['broccoli']), Person('Eddy', 12, ['chunky puffs', 'jawbreakers'])] age_sum = 0 year_sum = 0 for person in people: age_sum += person.age year_sum += person.birth_year() print('The average age is: ' + str(age_sum / len(people))) print('The average birth year is: ' + str(int(year_sum / len(people)))) print('The people polled in this census were:') for person in people: print(person)
class NearEarthObject(object): """ Object containing data describing a Near Earth Object and it's orbits. # TODO: You may be adding instance methods to NearEarthObject to help you implement search and output data. """ def __init__(self, **kwargs): """ :param kwargs: dict of attributes about a given Near Earth Object, only a subset of attributes used """ # TODO: What instance variables will be useful for storing on the Near Earth Object? self.id = kwargs.get("id") self.name = kwargs.get("name") self.orbits = kwargs.get("orbits") self.diameter_min_km = float(kwargs.get("diameter_min_km")) self.is_potentially_hazardous_asteroid = ( True if kwargs.get("is_potentially_hazardous_asteroid")=="True" else False ) def update_orbits(self, orbit): """ Adds an orbit path information to a Near Earth Object list of orbits :param orbit: OrbitPath :return: None """ # TODO: How do we connect orbits back to the Near Earth Object? # Orbits stored in a set, hence the use of .add() self.orbits.add(orbit) def __repr__(self): """Implements a text representation of a Near Earth Object""" neo_info = ( "\nNearEarthObject {} -> [\n" "\tID: {}\n" "\tName: {}\n" "\tMin. Diameter(km): {}\n" "\tHazardous: {}\n" "\tOrbits: \n\t\t{}\n" "]\n" ).format( self.name, self.id, self.name, self.diameter_min_km, self.is_potentially_hazardous_asteroid, "\n\t\t".join( sorted([orbit._repr_cust() for orbit in self.orbits], reverse=True) ) ) return neo_info class OrbitPath(object): """ Object containing data describing a Near Earth Object orbit. # TODO: You may be adding instance methods to OrbitPath to help you implement search and output data. """ def __init__(self, **kwargs): """ :param kwargs: dict of attributes about a given orbit, only a subset of attributes used """ # TODO: What instance variables will be useful for storing on the Near Earth Object? self.neo_name = kwargs.get("neo_name") self.miss_distance_kilometers = float(kwargs.get("miss_distance_kilometers")) self.close_approach_date = kwargs.get("close_approach_date") def __repr__(self): """Implements a text representation of an Orbit""" orbit_info = ( "Orbit -> [\n" "\tNEO: {}\n" "\tClose Approach Date: {}\n" "\tMiss Distance(km): {}\n" "]" ).format( self.neo_name, self.close_approach_date, self.miss_distance_kilometers ) return orbit_info def _repr_cust(self): """Implements a text representation of an Orbit for use in representation of a Near Earth Object""" orbit_info = ( "{} (Miss Distance in km: {})" ).format(self.close_approach_date, self.miss_distance_kilometers) return orbit_info
#!/usr/bin/python import os questions = { "strong": "Do ye like yer drinks strong?", "salty": "Do ye like it with a salty tang?", "bitter": "Are ye a lubber who likes it bitter?", "sweet": "Would ye like a bit of sweetness with yer poison?", "fruity": "Are ye one for a fruity finish?" } ingredients = { "strong": ["glug of rum", "slug of whisky", "splash of gin"], "salty": ["olive on a stick", "salt-dusted rim", "rasher of bacon"], "bitter": ["shake of bitters", "splash of tonic", "twist of lemon peel"], "sweet": ["sugar cube", "spoonful of honey", "spash of cola"], "fruity": ["slice of orange", "dash of cassis", "cherry on top"] } os.system('clear') def drinks(questions, ingredients): for question in questions: print questions[question] answer = raw_input(" yes or no : ") if answer == "yes" or answer == "y": os.system('clear') print "Here's how to make your drink: \n" , ingredients[question] break else: pass return question if __name__ == '__main__': drinks(questions, ingredients)
# https://programmers.co.kr/learn/courses/30/lessons/12901 def solution(a, b): day = ["FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"] month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] count = 0 for i in range(a - 1): count += month[i] count += b return day[count % len(day) - 1] print(solution(5, 24))
# https://programmers.co.kr/learn/courses/30/lessons/17680 def solution(cacheSize, cities): if cacheSize == 0: return len(cities) * 5 answer = 0 cache = [] for city in cities: city = city.lower() if city not in cache: if len(cache) == cacheSize: cache.pop() answer += 5 else: cache.pop(cache.index(city)) answer += 1 cache.insert(0, city) # 가장 최근에 사용된 것을 맨 앞에 추가한다 return answer print(solution(3, ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "Jeju", "Pangyo", "Seoul", "NewYork", "LA"]))
# https://programmers.co.kr/learn/courses/30/lessons/12903 def solution(arr): answer = [] for i, number in enumerate(arr): if i == 0: answer.append(number) continue if arr[i - 1] != arr[i]: answer.append(number) return answer print(solution([1, 1, 3, 3, 0, 1, 1])) print(solution([4, 4, 4, 3, 3]))
# https://programmers.co.kr/learn/courses/30/lessons/12912 def solution(a, b): answer = 0 if a > b: a, b = b, a for number in range(a, b + 1): answer += number return answer print(solution(3, 5)) print(solution(3, 3)) print(solution(5, 3))
#https://programmers.co.kr/learn/courses/30/lessons/12947 def solution(x): result = 0 k = x while k > 0: result += k % 10 k //= 10 if x % result == 0: return True else: return False print(solution(10)) print(solution(12)) print(solution(11)) print(solution(13))
import sys def factorial(number): product = 1 temp = 1 while(temp < (number + 1)): product = product * temp temp = temp + 1 return product number = int(sys.argv[1]) print(factorial(number))
import numpy as np # Import datasets, classifiers and performance metrics from sklearn import datasets, svm, metrics print('Running...') traindata = np.loadtxt('c:\\users\\samarths\\desktop\\the62s\\newtrain620.csv', delimiter = ',', skiprows = 1) nums, attribs1 = np.hsplit(traindata, [1]) binarynums, attribs = np.hsplit(attribs1, [1]) images = attribs.view() labels = binarynums.ravel().astype(np.int) # To apply a classifier on this data, we need to flatten the image, to # turn the data in a (samples, feature) matrix: n_samples = len(images) data = images.reshape((n_samples, -1)) print(labels.shape) print(data.shape) print(n_samples) # Create a classifier: a support vector classifier classifier = svm.SVC(gamma=0.001) # We learn the digits on the training set classifier.fit(data, labels) testdata = np.loadtxt('c:\\users\\samarths\\desktop\\the62s\\newtest620.csv', delimiter = ',', skiprows = 1) testnums, testattribs1 = np.hsplit(testdata, [1]) testbinarynums, testattribs = np.hsplit(testattribs1, [1]) testimages = testattribs.view() expected = testbinarynums.ravel().astype(np.int) n_testsamples = len(testimages) testdatareshaped = testimages.reshape((n_testsamples, -1)) print(expected.shape) print(testdatareshaped.shape) print(n_testsamples) predicted = classifier.predict(testdatareshaped) print(predicted.shape) print("Classification report for classifier %s:\n%s\n" % (classifier, metrics.classification_report(expected, predicted))) print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))
import random def shouldendgame(): new_game = input("Do you want to play again? (y/n)\n") if new_game == "y": return False elif new_game == "n": return True else: print('Invalid input. Please enter "y" or "n"') return shouldendgame() print("Lets play guess the number!") print("The game will get harder with each round, so don't leave if the first round's too easy!") for i in range(1, 10): max = 10 ** i secret_number = random.randint(1, max) print("I'm thinking of a number between 1 and " + str(max)) guess = None while guess != secret_number: if (guess is not None): # == checks for equality (java .equals()), while is checks for being the same object (java ==) if guess < secret_number: print("Too large") else: print("Too small") guess = input("Please input your guess.\n") if guess.isdigit(): guess = int(guess) else: print(str(guess) + " is not a number.") guess = None print("You win!") if shouldendgame(): break print("Thanks for playing")
# Set up your imports here! from flask import Flask from flask import request app = Flask(__name__) @app.route('/') # Fill this in! def index(): # Create a generic welcome page. return '<h1>Hello Puppers!</h1>' @app.route('/latin/<name>') # Fill this in! def puppylatin(name): # This function will take in the name passed # and then use "puppy-latin" to convert it! # HINT: Use indexing and concatenation of strings # For Example: "hello"+" world" --> "hello world" # if the name does end with 'y' if name[-1] == 'y': # remove the 'y' + add 'iful' to the name changed_name = name[:-1] + 'iful' return 'Your new name is {}'.format(changed_name) # if the name does not end with 'y' else: # add an 'y' to the end of the name changed_name = name + 'y' return 'Your new name is {}'.format(changed_name) if __name__ == '__main__': app.run(debug=True)
# this will.... create a truth or dare? # if they pick a truth then the computer gives a statment that might put the human in akward position to answer # if they pick a dare they are told to do some harmless prank at school or on the weekend. # we need advanced data lists/arreays have a function that sets up those lists at the start of the game. # like getting monopoly game setup before you can play monopoly. # setup empty lists truthQuestions = [] dareChallenges = [] # define function we need to use later def setupTruthList(list1): # add first item to index zero of the list list1.append("Have you ever stolen from your parents") list1.append("Who is your crush at FHS") list1.append("What teacher do you trust the most") list1.append("Have you ever had a crush on a teacher? If so who? # this is a local list we pass back to who called us return list1 def setupDareList(list1): # add first item to index zero of the list list1.append("leave a happy note for a teacher") list1.append("ask a new student to eat lunch with you") list1.append("tell your fav teacher that they are your fav in front of class") # this is a local list we pass back to who called us return list1 setupTruthList(truthQuestions) setupDareList(dareChallenges) # call the function to start the game, then ask a question of the human user = input("truth? or dare?: ") #User selects either truth dare by typing in truth or dare if user == "truth": print("here comes your question....") print(truthQuestions[0]) #If user types truth, then the code spites out the question elif user == "dare": print("here comes your dare....") print(dareChallenges[0]) #If user types dare, then the code spites out a dare else: print("you didn't type it correctly, please type truth or dare") #If the user doesn't type truth or dare, the code says to retype it print("") print("") print("") print("") print("") print("")
def binomial(n, k): if (k == 1 or k == n): return 1 return binomial(n - 1, k) + binomial(n - 1, k - 1) n, k = [int(x) for x in input().split()] print(binomial(n, k))
from tkinter import * def login(): a = inp1.get() b = inp2.get() if a == 'gugas02' and b == "123456": lbl3['text'] = "bem vindo guh" lbl3['fg'] = "blue" else: lbl3['text'] = "Usuário ou senha invalida" lbl3['fg'] = "red" i = Tk() i.title("teste do Tk") lbl1 = Label(i, text="user") lbl1.pack() inp1 = Entry(i) inp1.pack() lbl2 = Label(i, text="senha") lbl2.pack() inp2 = Entry(i) inp2.pack() entrar = Button(i, text="entrar", command=login) entrar.pack() lbl3 = Label(i, text="") lbl3.pack() i.mainloop()
# # # Python 3.6.1 # # Author: Max Jacobsen # # # # Purpose: Create a GUI that allows the user to select a file to check for # newly created and modified files. Allow the user to select a folder to # move these files too. Create a button that initiates the process # # # Please change the file path for your desktop in order for this program to work correctly. # from tkinter import * import tkinter as tk import file_mod def load_gui(self): self.lbl_title = tk.Label(self.master, wraplength=450, text="Select a source folder to check for modified or newly created files made within the last day and the destination you want to move those files too.") self.lbl_title.grid(row=0, rowspan=2, padx=(20, 20), pady=(20,0), column=0, columnspan=10, sticky=N+W) self.lbl_srcfolder = tk.Label(self.master, text="Please Select a Folder", wraplength=350, justify="center") self.lbl_srcfolder.grid(row=3,rowspan=2, padx=(5,0), pady=(20,0), column=2, columnspan=8, sticky=W) self.btn_srcfolder = tk.Button(self.master,bg="#CCCCCC", width=15, height=1, text="Source Folder", command=lambda: file_mod.set_file_path(self, 'srcFolder', self.lbl_srcfolder)) self.btn_srcfolder.grid(row=3, column=0, columnspan=2, padx=(20,0), pady=(20,0), sticky=W) self.lbl_destfolder = tk.Label(self.master, text="Please Select a Folder", wraplength=350, justify="center") self.lbl_destfolder.grid(row=5, rowspan=2, padx=(5,0), pady=(20,0), column=2, columnspan=8, sticky=W) self.btn_destfolder = tk.Button(self.master,bg="#CCCCCC", width=15, height=1, text="Destination Folder", command=lambda: file_mod.set_file_path(self, 'destFolder', self.lbl_destfolder)) self.btn_destfolder.grid(row=5, column=0, columnspan=2, padx=(20,0), pady=(20,0), sticky=W) self.btn_filecheck = tk.Button(self.master,bg="#25c638", width=15, height=2, text="Check Files", command=lambda: file_mod.file_check_initiated(self.srcFolder, self.destFolder, self.lbl_checktime, self.lbl_agotime,self.btn_refresh)) self.btn_filecheck.grid(row=8, column=0, columnspan=2, padx=(20,0), pady=(40,0), sticky=W) self.lbl_checktime = tk.Label(self.master, fg="#2d8390", font=(None, 8, 'bold'), text="No previous file check time found") self.lbl_checktime.grid(row=8, padx=(15,0), pady=(20,0), column=2, columnspan=6, sticky=W) self.lbl_agotime = tk.Label(self.master, fg="black", font=(None, 8, 'bold'), text="") self.lbl_agotime.grid(row=8, padx=(15,0), pady=(60,0), column=2, columnspan=4, sticky=W) self.btn_refresh = tk.Button(self.master,bg="#CCCCCC", width=12, height=1, text="Refresh", command=lambda: file_mod.check_for_last_file_check(self.lbl_checktime, self.lbl_agotime, self.btn_refresh)) self.btn_refresh.grid(row=8, column=7, columnspan=3, padx=(0,0), pady=(40,0), sticky=W) file_mod.create_db(self) file_mod.check_for_last_file_check(self.lbl_checktime, self.lbl_agotime,self.btn_refresh) if __name__ == "__main__": pass
# Name: Jordan Strand # Date: June. 04, 2021 # Class: ICS3U1 # Description: This is the final summative, Jordan feels like he's gonna have a bad time # Creating the user input to start the game. print("HELLO, welcome to my game of YOU VS. TRASHMAN. \nIn this game you are tasked with defeating the evil Business trashman, \nwho won't stop polluting, so you'd better stop him! \nTo play, you move your character around \nwith the arrow keys, avoiding the trash. \nThe mouse is not required for this game. \nTo select either 'fight' or 'heal', press the enter key.") print("------------------------------------") # Making it so that the game won't start until you press 'ENTER' start = " " while start != "": start = input("Read over the rules to play the game, \nif you are ready for a bad time, press ENTER: ") if start != "": print("Why don't you wanna play the game? \nTry again") if start == "": print("Thank you for pressing start, \nprepare yourself!") # Starting to create the game by importing modules, and defining the borders import pygame, math, random pygame.init() RED = (255, 0, 0) BLACK = (0, 0, 0) WHITE = (255, 255, 255) ORANGE = (255, 165, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) GREY = (100, 100, 100) width = 800 height = 600 SIZE = (width, height) screen = pygame.display.set_mode(SIZE) pygame.display.set_caption("YOU-VS-TRASHMAN") # List for where the border is border_values = [310, 288, 490, 468] # Opening a file to get the information for the main character, and appending it to a list. This is so that if someone wants to change some aspects of the heart, instead of changing the whole code, they can just change the file values heart_values = [] heart = open("StrandMainCharacter.txt", "r") while start == "": values = heart.readline() values = values.rstrip("\n") heart_values.append(values) if values == "": break if int(values) >= 0: for i in range(2, int(values)): if (int(values)) >= 0: heart_values.append(values) break # Drawing the scenes. These will be all the pygame-drawn assets throughout my game def drawHeart(location, y, colour): pygame.draw.rect(screen, BLACK, (location-11, y-int(heart_values[6]), 22, 22)) pygame.draw.circle(screen, colour, (location+int(heart_values[1]), y), int(heart_values[1])) pygame.draw.circle(screen, colour, (location-int(heart_values[1]), y), int(heart_values[1])) pygame.draw.polygon(screen, colour, ([location+int(heart_values[3]), y+int(heart_values[5])], [location-int(heart_values[3]), y+int(heart_values[5])], [location, y+int(heart_values[6])])) def border(a, b, c, d): pygame.draw.rect(screen, WHITE, (a, b, c, d), int(heart_values[1])) def buttons(e, f, g, h): pygame.draw.rect(screen, ORANGE, (e, f, g, h)) def PaperBalls(random_place): if random_place_true == 1: pygame.draw.circle(screen, BLACK, (450-random_place,(300+n)-1), 13) pygame.draw.circle(screen, WHITE, (450-random_place,300+n), 13) pygame.draw.line(screen, BLACK, (445-random_place,300+n), (440-random_place,295+n), 3) pygame.draw.line(screen, BLACK, (445-random_place,300+n), (442-random_place,308+n), 3) pygame.draw.line(screen, BLACK, (455-random_place,289+n), (450-random_place,300+n), 3) pygame.draw.circle(screen, BLACK, (350+random_place,(300+n)-1), 13) pygame.draw.circle(screen, WHITE, (350+random_place,300+n), 13) pygame.draw.line(screen, BLACK, (345+random_place,300+n), (340+random_place,295+n), 3) pygame.draw.line(screen, BLACK, (345+random_place,300+n), (342+random_place,308+n), 3) pygame.draw.line(screen, BLACK, (355+random_place,289+n), (350+random_place,300+n), 3) elif random_place_true == 2: pygame.draw.circle(screen, BLACK, (450+random_place,(300+n)-1), 13) pygame.draw.circle(screen, WHITE, (450+random_place,300+n), 13) pygame.draw.line(screen, BLACK, (445+random_place,300+n), (440+random_place,295+n), 3) pygame.draw.line(screen, BLACK, (445+random_place,300+n), (442+random_place,308+n), 3) pygame.draw.line(screen, BLACK, (455+random_place,289+n), (450+random_place,300+n), 3) pygame.draw.circle(screen, BLACK, (350-random_place,(300+n)-1), 13) pygame.draw.circle(screen, WHITE, (350-random_place,300+n), 13) pygame.draw.line(screen, BLACK, (345-random_place,300+n), (340-random_place,295+n), 3) pygame.draw.line(screen, BLACK, (345-random_place,300+n), (342-random_place,308+n), 3) pygame.draw.line(screen, BLACK, (355-random_place,289+n), (350-random_place,300+n), 3) pygame.draw.circle(screen, BLACK, (400,(300+n)-1), 13) pygame.draw.circle(screen, WHITE, (400,300+n), 13) pygame.draw.line(screen, BLACK, (400,295+n), (410,305+n), 3) pygame.draw.line(screen, BLACK, (400,295+n), (390,305+n), 3) def PaperBalls2(random_place): if random_place_true == 1: pygame.draw.circle(screen, BLACK, (400+random_place,(300+n)-1), 12) pygame.draw.circle(screen, WHITE, (400+random_place,300+n), 12) pygame.draw.circle(screen, BLACK, ((300+n)-1,400+random_place), 12) pygame.draw.circle(screen, WHITE, (300+n,400+random_place), 12) pygame.draw.circle(screen, BLACK, ((500-n)+1,400+random_place), 12) pygame.draw.circle(screen, WHITE, (500-n,400+random_place), 12) pygame.draw.circle(screen, BLACK, (400+random_place,(500-n)+1), 12) pygame.draw.circle(screen, WHITE, (400+random_place,500-n), 12) if random_place_true == 2: pygame.draw.circle(screen, BLACK, (400-random_place,(300+n)-1), 12) pygame.draw.circle(screen, WHITE, (400-random_place,300+n), 12) pygame.draw.circle(screen, BLACK, ((300+n)-1,400-random_place), 12) pygame.draw.circle(screen, WHITE, (300+n,400-random_place), 12) pygame.draw.circle(screen, BLACK, ((500-n)+1,400-random_place), 12) pygame.draw.circle(screen, WHITE, (500-n,400-random_place), 12) pygame.draw.circle(screen, BLACK, (400-random_place,(500-n)+1), 12) pygame.draw.circle(screen, WHITE, (400-random_place,500-n), 12) def Earth(random_position): if random_position == 1: pygame.draw.circle(screen, BLACK, (400,(300+n)-1), 50) pygame.draw.circle(screen, BLUE, (400,300+n), 50) pygame.draw.polygon(screen, GREEN, ([365,290+n], [390,270+n], [390,310+n])) pygame.draw.polygon(screen, GREEN, ([390,310+n], [385,330+n], [395,320+n])) pygame.draw.polygon(screen, GREEN, ([410,300+n], [420,290+n], [420,320+n])) pygame.draw.polygon(screen, GREEN, ([420,290+n], [430,270+n], [435,280+n])) if random_position == 2: pygame.draw.circle(screen, BLACK, (400+50,(300+n)-1), 50) pygame.draw.circle(screen, BLUE, (400+50,300+n), 50) pygame.draw.polygon(screen, GREEN, ([365+50,290+n], [390+50,270+n], [390+50,310+n])) pygame.draw.polygon(screen, GREEN, ([390+50,310+n], [385+50,330+n], [395+50,320+n])) pygame.draw.polygon(screen, GREEN, ([410+50,300+n], [420+50,290+n], [420+50,320+n])) pygame.draw.polygon(screen, GREEN, ([420+50,290+n], [430+50,270+n], [435+50,280+n])) if random_position == 3: pygame.draw.circle(screen, BLACK, (400-50,(300+n)-1), 50) pygame.draw.circle(screen, BLUE, (400-50,300+n), 50) pygame.draw.polygon(screen, GREEN, ([365-50,290+n], [390-50,270+n], [390-50,310+n])) pygame.draw.polygon(screen, GREEN, ([390-50,310+n], [385-50,330+n], [395-50,320+n])) pygame.draw.polygon(screen, GREEN, ([410-50,300+n], [420-50,290+n], [420-50,320+n])) pygame.draw.polygon(screen, GREEN, ([420-50,290+n], [430-50,270+n], [435-50,280+n])) def TrashCan(): pygame.draw.rect(screen, BLACK, ((310+n)-1,280,20,160)) pygame.draw.circle(screen, BLACK, (310+n,420), 10) pygame.draw.circle(screen, BLACK, (310+n,400), 10) pygame.draw.circle(screen, BLACK, (310+n,380), 10) pygame.draw.circle(screen, BLACK, (310+n,360), 10) pygame.draw.circle(screen, BLACK, (310+n,340), 10) pygame.draw.circle(screen, BLACK, (310+n,320), 10) pygame.draw.circle(screen, BLACK, (310+n,300), 10) pygame.draw.rect(screen, GREY, (310+n,280,20,160)) pygame.draw.line(screen, BLACK, (320+n,280), (320+n,440), 2) pygame.draw.circle(screen, BLACK, ((320+n)-1,440), 10) pygame.draw.circle(screen, GREY, (320+n,440), 10) pygame.draw.circle(screen, BLACK, ((320+n)-1,470), 10) pygame.draw.circle(screen, GREY, (320+n,470), 10) myClock = pygame.time.Clock() running = True x = 200 y = 550 # Importing text and images fontLoad = pygame.font.SysFont("Comic Sans MS",30) fontSecondLoad = pygame.font.SysFont("Comic Sans MS",20) loading_screen = fontLoad.render("Welcome to my Game!", 1, (255, 255, 255)) loading = fontSecondLoad.render("Use the arrow keys to move your character,", 1, (255, 255, 255)) second_loading = fontSecondLoad.render("press enter to either attack or heal!", 1, (255, 255, 255)) third_loading = fontSecondLoad.render("Avoid the trash at all costs!", 1, (255, 255, 255)) screen.blit(loading_screen, pygame.Rect(50,100,50,50)) screen.blit(loading, pygame.Rect(50,180,50,50)) screen.blit(second_loading, pygame.Rect(50,210,50,50)) screen.blit(third_loading, pygame.Rect(50,240,50,50)) pygame.display.flip() pygame.time.wait(6000) pygame.draw.rect(screen, BLACK, (0, 0, 800, 600)) border(300, 280, 200, 200) businessmanPic = pygame.image.load("Strandbusinessman.jpg") businessmanPic = pygame.transform.scale(businessmanPic, (150, 150)) screen.blit(businessmanPic, pygame.Rect(320,128,20,20)) pygame.display.flip() pygame.time.wait(1000) SpeechBubble = pygame.image.load("StrandSpeechBubble.png") SpeechBubble = pygame.transform.scale(SpeechBubble, (240, 150)) screen.blit(SpeechBubble, pygame.Rect(440,70,30,30)) pygame.display.flip() pygame.time.wait(500) explosion = pygame.image.load("StrandExplosion.jpg") explosion = pygame.transform.scale(explosion, (150, 150)) # Making and rendering some text fontBusiness = pygame.font.SysFont("Comic Sans MS",12) fontAct = pygame.font.SysFont("Comic Sans MS",20) fontHealth = pygame.font.SysFont("Comic Sans MS",30) fontWin = pygame.font.SysFont("Comic Sans MS",100) fontLose = pygame.font.SysFont("Comic Sans MS",50) fontLoseSub = pygame.font.SysFont("Comic Sans MS",20) fontEpicWin = pygame.font.SysFont("Comic Sans MS",20) miss = fontHealth.render("YOU MISSED", 1, (255, 255, 255)) fight = fontAct.render("FIGHT", 1, (255, 255, 255)) heal = fontAct.render("HEAL", 1, (255, 255, 255)) text = fontBusiness.render("Haha, I am an evil trash business man!", 1, (0, 0, 0)) new_text = fontBusiness.render("I'm gonna keep polluting a whole ton!", 1, (0, 0, 0)) screen.blit(text, pygame.Rect(450,100,50,50)) screen.blit(new_text, pygame.Rect(450,120,50,50)) pygame.display.flip() pygame.time.wait(50) # Using a sound to make it sound like he's talking in the begining Talking = pygame.mixer.Sound("StrandTalking.wav") Talking.play() for count in range(10): pygame.time.wait(100) Talking.play() pygame.display.flip() pygame.time.wait(2000) # Playing the song Megalovania = pygame.mixer.Sound("StrandMegalovania.wav") Megalovania.play() pygame.draw.rect(screen, BLACK, (440,50,250,152)) buttons(100,520,200,50) buttons(500,520,200,50) screen.blit(fight, pygame.Rect(110,530,200,50)) screen.blit(heal, pygame.Rect(510,530,200,50)) pygame.display.flip() pygame.time.wait(50) # Some game states key_left = False key_right = False key_up = False key_down = False # The main game loop, some sounds, and making counters to tell the game when to switch phases, and what the damage is. Also making the text to see what the enemies health is, and see what yours is. Also making the health bars. counter = 0 your_health = 100 enemy_health = 100 enemy_current_health = fontHealth.render("TRASHMAN HP: %i"%(enemy_health), 1, (255, 255, 255)) your_current_health = fontHealth.render("YOUR HP: %i"%(your_health), 1, (255, 255, 255)) screen.blit(enemy_current_health, pygame.Rect(50,50,100,100)) screen.blit(your_current_health, pygame.Rect(500,50,100,100)) def healthBar(i, j, which_health): pygame.draw.rect(screen, WHITE, (i,88,104,30)) pygame.draw.rect(screen, RED, (j,90,100,25)) pygame.draw.rect(screen, GREEN, (j,90,which_health,25)) healthBar(78, 80, enemy_health) healthBar(528, 530, your_health) Ping = pygame.mixer.Sound("StrandPing.wav") Hurt = pygame.mixer.Sound("StrandTakingDamage.wav") Enemy_hurt = pygame.mixer.Sound("StrandInflictingDamage.wav") Recovery = pygame.mixer.Sound("StrandRecovery.wav") dead_music = pygame.mixer.Sound("StrandDeadMusic.wav") Congratulations = pygame.mixer.Sound("StrandCongratulations.wav") win = 0 lose = 0 n = 1 attack_phase = 0 while running: for evnt in pygame.event.get(): if evnt.type == pygame.QUIT: running = False # Seeing whether the key is pressed down or not if evnt.type == pygame.KEYDOWN and (counter%2) != 0: if evnt.key == pygame.K_LEFT: key_left = True if evnt.key == pygame.K_RIGHT: key_right = True if evnt.key == pygame.K_UP: key_up = True if evnt.key == pygame.K_DOWN: key_down = True # Making character move for attack stage and heal stage if evnt.type == pygame.KEYDOWN and (counter%2) == 0: keys = pygame.key.get_pressed() if x == 200: if keys[pygame.K_RIGHT]: x = x + 400 pygame.draw.rect(screen, ORANGE, (x-411,y-10,22,22)) Ping.play() if x == 600: if keys[pygame.K_LEFT]: x = x - 400 pygame.draw.rect(screen, ORANGE, (x+389,y-10,22,22)) Ping.play() # This is the heal button. I'm making it so that if the player's health is less than 100, they have the option to heal themselves if the heart is over the optional button if evnt.key == pygame.K_RETURN and x == 600 and your_health < 100: Recovery.play() random_number = random.randint(5,10) your_health += random_number your_current_health = fontHealth.render("YOUR HP: %i"%(your_health), 1, (255, 255, 255)) pygame.draw.rect(screen, BLACK, (650,50,55,40)) screen.blit(your_current_health, pygame.Rect(500,50,100,100)) healthBar(528, 530, your_health) counter += 1 x = 400 y = 400 pygame.draw.rect(screen, BLACK, (0,500,800,100)) attack_phase = random.randint(1,4) # This is the attack button. I'm making it so that if they press this button, they will attack the enemy and initiate the attack phase if evnt.key == pygame.K_RETURN and x == 200: Ping.play() hit_or_miss = random.randint(1,100) # Having a random chance for you to miss your attack, a five percent chance to be exact if hit_or_miss <= 95: random_number = random.randint(5,15) # This decides how much damage you do enemy_health -= random_number enemy_current_health = fontHealth.render("TRASHMAN HP: %i"%(enemy_health), 1, (255, 255, 255)) pygame.draw.line(screen, RED, (450,170), (330,250), 5) Enemy_hurt.play() pygame.display.flip() pygame.time.wait(1000) pygame.draw.rect(screen, BLACK, (320,128,150,150)) pygame.display.flip() pygame.time.wait(200) screen.blit(businessmanPic, pygame.Rect(320,128,20,20)) pygame.display.flip() pygame.time.wait(200) pygame.draw.rect(screen, BLACK, (320,128,150,150)) pygame.display.flip() pygame.time.wait(200) screen.blit(businessmanPic, pygame.Rect(320,128,20,20)) pygame.draw.rect(screen, BLACK, (290,50,55,50)) screen.blit(enemy_current_health, pygame.Rect(50,50,100,100)) healthBar(78, 80, enemy_health) if hit_or_miss > 95: # If you miss, you do no damage screen.blit(miss, pygame.Rect(600,300,200,50)) pygame.display.flip() pygame.time.wait(2000) pygame.draw.rect(screen, BLACK, (600,300,200,50)) if enemy_health <= 0: win += 1 running = False counter += 1 x = 400 y = 400 pygame.draw.rect(screen, BLACK, (0,500,800,100)) attack_phase = random.randint(1,4) # These numbers down here indicate whether to move certain attacks in a random position, so that the player doesn't get used to the same four attacks, because they're different everytime random_place_true = random.randint(1,2) random_place = random.randint(0,20) random_position = random.randint(1,3) # This is checking whether the player should be moving or not if evnt.type == pygame.KEYUP: if evnt.key == pygame.K_LEFT: key_left = False if evnt.key == pygame.K_RIGHT: key_right = False if evnt.key == pygame.K_UP: key_up = False if evnt.key == pygame.K_DOWN: key_down = False # Making the character move for defense stage, and also having it so that depending on the attack phase, the enemy will do diferent attacks based on what phase that is. # This is the paperballs collision section if attack_phase == 1 and (counter%2) != 0: if random_place_true == 1: paper1_distance = math.hypot(400 - x, 300+n - y) paper2_distance = math.hypot(450-random_place - x, 300+n - y) paper3_distance = math.hypot(350+random_place - x, 300+n - y) if random_place_true == 2: paper1_distance = math.hypot(400 - x, 300+n - y) paper2_distance = math.hypot(450+random_place - x, 300+n - y) paper3_distance = math.hypot(350-random_place - x, 300+n - y) if paper1_distance <= 5 + 13 or paper2_distance <= 5 + 13 or paper3_distance <= 5 + 13: Hurt.play() your_health -=1 your_current_health = fontHealth.render("YOUR HP: %i"%(your_health), 1, (255, 255, 255)) pygame.draw.rect(screen, BLACK, (650,50,55,40)) screen.blit(your_current_health, pygame.Rect(500,50,100,100)) healthBar(528, 530, your_health) if your_health <= 0: lose += 1 running = False # This is the other collision detector elif attack_phase == 2 and (counter%2) != 0: if random_place_true == 1: paper4_distance = math.hypot(400+random_place - x, 300+n - y) paper5_distance = math.hypot(300+n - x, 400+random_place - y) paper6_distance = math.hypot(500-n - x, 400+random_place - y) paper7_distance = math.hypot(400+random_place - x, 500-n - y) if random_place_true == 2: paper4_distance = math.hypot(400-random_place - x, 300+n - y) paper5_distance = math.hypot(300+n - x, 400-random_place - y) paper6_distance = math.hypot(500-n - x, 400-random_place - y) paper7_distance = math.hypot(400-random_place - x, 500-n - y) if paper4_distance <= 5 + 12 or paper5_distance <= 5 + 12 or paper6_distance <= 5 + 12 or paper7_distance <= 5 + 12: Hurt.play() your_health -=1 your_current_health = fontHealth.render("YOUR HP: %i"%(your_health), 1, (255, 255, 255)) pygame.draw.rect(screen, BLACK, (650,50,55,40)) screen.blit(your_current_health, pygame.Rect(500,50,100,100)) healthBar(528, 530, your_health) if your_health <= 0: lose += 1 running = False # This is the third attack phase collision detector elif attack_phase == 3 and (counter%2) != 0: if random_position == 1: distance = math.hypot(400 - x, 300+n - y) if random_position == 2: distance = math.hypot(450 - x, 300+n - y) if random_position == 3: distance = math.hypot(350 - x, 300+n - y) if distance <= 5 + 50: Hurt.play() your_health -=1 your_current_health = fontHealth.render("YOUR HP: %i"%(your_health), 1, (255, 255, 255)) pygame.draw.rect(screen, BLACK, (650,50,55,40)) screen.blit(your_current_health, pygame.Rect(500,50,100,100)) healthBar(528, 530, your_health) if your_health <= 0: lose += 1 running = False # This is the fourth attack phase hit detection elif attack_phase == 4 and (counter%2) != 0: bar_distance = math.hypot(320+n - x, 440 - y) circle_distance = math.hypot(320+n - x, 470 - y) circle2_distance = math.hypot(310+n - x, 420 - y) circle3_distance = math.hypot(310+n - x, 400 - y) circle4_distance = math.hypot(310+n - x, 380 - y) circle5_distance = math.hypot(310+n - x, 360 - y) circle6_distance = math.hypot(310+n - x, 340 - y) circle7_distance = math.hypot(310+n - x, 320 - y) circle8_distance = math.hypot(310+n - x, 300 - y) if bar_distance <= 5 + 8 or circle_distance <= 5 + 8 or circle2_distance <= 5 + 10 or circle3_distance <= 5 + 10 or circle4_distance <= 5 + 10 or circle5_distance <= 5 + 10 or circle6_distance <= 5 + 10 or circle7_distance <= 5 + 10 or circle8_distance <= 5 + 10: Hurt.play() your_health -=1 your_current_health = fontHealth.render("YOUR HP: %i"%(your_health), 1, (255, 255, 255)) pygame.draw.rect(screen, BLACK, (650,50,55,40)) screen.blit(your_current_health, pygame.Rect(500,50,100,100)) healthBar(528, 530, your_health) if your_health <= 0: lose += 1 running = False # This is attack phase 1, this phase has three paperballs coming down from the sky at you if (counter%2) != 0 and attack_phase == 1: if key_left == True: x -= 1 if key_right == True: x += 1 if key_up == True: y -= 1 if key_down == True: y += 1 if n == 160 or n > 160: buttons(100,520,200,50) buttons(500,520,200,50) screen.blit(fight, pygame.Rect(110,530,200,50)) screen.blit(heal, pygame.Rect(510,530,200,50)) pygame.draw.rect(screen, BLACK, (300,280,200,200)) x = 200 y = 550 n = 0 counter += 1 n += 1 PaperBalls(random_place) if n == 1: pygame.draw.rect(screen, (BLACK), (290,280,220,220)) # This is attack phase 2, this takes the familliar paper balls from before, and adds a twist to them if (counter%2) != 0 and attack_phase == 2: if key_left == True: x -= 1 if key_right == True: x += 1 if key_up == True: y -= 1 if key_down == True: y += 1 if n == 200 or n > 200: buttons(100,520,200,50) buttons(500,520,200,50) screen.blit(fight, pygame.Rect(110,530,200,50)) screen.blit(heal, pygame.Rect(510,530,200,50)) pygame.draw.rect(screen, BLACK, (300,280,200,200)) x = 200 y = 550 n = 0 counter += 1 n += 1 PaperBalls2(random_place) if n == 1: pygame.draw.rect(screen, (BLACK), (285,280,230,235)) # This is attack phase 3, it draws a big earth which you then have to avoid if (counter%2) != 0 and attack_phase == 3: if key_left == True: x -= 1 if key_right == True: x += 1 if key_up == True: y -= 1 if key_down == True: y += 1 if n == 150 or n > 150: buttons(100,520,200,50) buttons(500,520,200,50) screen.blit(fight, pygame.Rect(110,530,200,50)) screen.blit(heal, pygame.Rect(510,530,200,50)) screen.blit(enemy_current_health, pygame.Rect(50,50,100,100)) pygame.draw.rect(screen, BLACK, (300,280,200,210)) x = 200 y = 550 n = 0 counter += 1 n += 1 Earth(random_position) if n == 1: pygame.draw.rect(screen, (BLACK), (290,280,220,220)) pygame.draw.rect(screen, (BLACK), (300,253,200,25)) screen.blit(businessmanPic, pygame.Rect(320,128,20,20)) # This is attack phase 4, it draws a garbage can which you have to carefully navigate through if (counter%2) != 0 and attack_phase == 4: if key_left == True: x -= 1 if key_right == True: x += 1 if key_up == True: y -= 1 if key_down == True: y += 1 if n == 170 or n > 170: buttons(100,520,200,50) buttons(500,520,200,50) screen.blit(fight, pygame.Rect(110,530,200,50)) screen.blit(heal, pygame.Rect(510,530,200,50)) pygame.draw.rect(screen, BLACK, (300,280,200,200)) x = 200 y = 550 n = 0 counter += 1 n += 1 TrashCan() if n == 1: pygame.draw.rect(screen, (BLACK), (290,280,220,220)) # Seeing where the border is, and if the heart is there, then it can't go any further if x == border_values[0]: x += 1 if x == border_values[2]: x -= 1 if y == border_values[1]: y += 1 if y == border_values[3]: y -= 1 # Drawing the whole game drawHeart(x, y, RED) border(300, 280, 200, 200) pygame.display.flip() myClock.tick(60) # Quitting out of the game Death = pygame.mixer.Sound("StrandDeath.wav") Explosion = pygame.mixer.Sound("StrandExplosion.wav") Megalovania.stop() if win == 1: # This is the win screen. If you beat the boss you will be taken to the win screen, other than the lose screen. And if the game detects that you won with 0 damage taken, you'll get a bonus message at the bottom too. pygame.draw.rect(screen, BLACK, (0,0,800,600)) screen.blit(businessmanPic, pygame.Rect(320,128,20,20)) pygame.display.flip() pygame.time.wait(1000) screen.blit(SpeechBubble, pygame.Rect(440,70,30,30)) Dead = fontBusiness.render("Well it appears i've died", 1, (0, 0, 0)) screen.blit(Dead, pygame.Rect(450,100,50,50)) pygame.display.flip() Talking.play() for count in range(7): pygame.time.wait(100) Talking.play() pygame.display.flip() pygame.time.wait(2000) pygame.draw.rect(screen, BLACK, (440,50,250,152)) pygame.display.flip() Explosion.play() pygame.time.wait(4000) screen.blit(explosion, pygame.Rect(320,128,20,20)) pygame.display.flip() pygame.time.wait(500) for i in range(100,300): pygame.draw.rect(screen, RED, (425-i,300-i,10,10)) pygame.draw.rect(screen, RED, (410+i,300-i,10,10)) pygame.draw.rect(screen, RED, (425-i,200+i,10,10)) pygame.draw.rect(screen, RED, (410+i,200+i,10,10)) pygame.display.flip() pygame.time.wait(2000) for count in range(1,255): pygame.draw.rect(screen, (count ,count ,count), (0,0,800,600)) pygame.display.flip() pygame.time.wait(40) pygame.time.wait(2000) if your_health >= 100: epic_win = fontEpicWin.render("AND WITH NO DAMAGE TAKEN NICELY DONE!", 1, (255, 0, 0)) screen.blit(epic_win, pygame.Rect(50,400,50,50)) win = fontWin.render("YOU WON!", 1, (255, 0, 0)) screen.blit(win, pygame.Rect(150,100,50,50)) Congratulations.play() pygame.display.flip() running = True if lose == 1: # This is the lose screen, if you die, then your heart will explode and you have to try again pygame.draw.rect(screen, BLACK, (0,0,800,600)) drawHeart(x, y, RED) pygame.display.flip() Death.play() pygame.time.wait(1000) pygame.draw.rect(screen, BLACK, (0, 0, 800, 600)) for i in range(1,600): pygame.draw.rect(screen, BLACK, ((x+i)-1,(y-i)-1,11,11)) pygame.draw.rect(screen, RED, (x+i,y-i,6,6)) pygame.draw.rect(screen, BLACK, ((x-i)+1,(y-i)+1,11,11)) pygame.draw.rect(screen, RED, (x-i,y-i,6,6)) pygame.draw.rect(screen, BLACK, ((x+i)-1,(y+i)-1,11,11)) pygame.draw.rect(screen, RED, (x+i,y+i,6,6)) pygame.draw.rect(screen, BLACK, ((x-i)+1,(y+i)-1,11,11)) pygame.draw.rect(screen,RED, (x-i,y+i,6,6)) pygame.display.flip() pygame.time.wait(2000) dead_music.play() lose = fontLose.render("YOU LOST, TRY AGAIN", 1, (255, 255, 255)) sub_to_jorxdefier = fontLoseSub.render("Your punishment is you now have to subscribe to the YouTube channel Jorxdefier", 1, (255, 255, 255)) screen.blit(lose, pygame.Rect(50,100,50,50)) screen.blit(sub_to_jorxdefier, pygame.Rect(20,400,50,50)) pygame.display.flip() running = True while running: for evnt in pygame.event.get(): if evnt.type == pygame.QUIT: running = False heart.close() pygame.quit() print("Thank you so much for playing my game!")
# -*- coding: utf-8 -*- height = 1.75 weight = 80.5 bmi = weight/(height * height) print ('bmi:',bmi) if bmi < 18.5: print ('too thin') elif bmi < 25: print ('normal') elif bmi < 32: print ('too fat') else: print ('very fat')
def read_credentials(path: str) -> (str, str): """ Reads file given at path with format name=value """ with open(path, 'r') as f: user, pw = "", "" for line in f.readlines(): if "user" in line: user = line.split('=')[1].strip() elif "pw" in line: pw = line.split('=')[1].strip() print(user, pw) return (user, pw)
# Get the users choices user1_answer = input("Player1, do you want to choose rock, paper or scissors? ").lower() user2_answer = input("Player2, do you want to choose rock, paper or scissors? ").lower() # Run the algorithm to see who wins if user1_answer == user2_answer: print("It's a tie!") elif user1_answer == 'rock': if user2_answer == 'scissors': print("Rock wins!") else: print("Paper wins!") elif user1_answer == 'scissors': if user2_answer == 'paper': print("Scissors win!") else: print("Rock wins!") elif user1_answer == 'paper': if user2_answer == 'rock': print("Paper wins!") else: print("Scissors win!") else: print("Invalid input! You have not entered rock, paper or scissors, try again.")
UserEntry = tuple(input("Please enter a list of numbers separated by a comma: ").split(",")) print(UserEntry) for num in UserEntry: num = int(num) if num % 5 == 0: print (num)
import urllib, re, os.path url = "http://www.pythonchallenge.com/pc/def/equality.html" fh = urllib.urlopen(url) in_comment = False chars = "" for line in fh: if in_comment: chars += "".join(re.findall('[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]',line)) elif re.match("<!--",line): in_comment = True else: pass print chars
#!/usr/bin/env python3 def last_8(some_int): """Return the last 8 digits of an int :param int some_int: the number :rtype: int """ return int(str(some_int)[-8:]) def optimized_fibonacci(f): #covering edge cases when f = 0 or 1 if (f==0): return 0 elif(f==1): return 1 else: #initializing the first elements a=0 b=1 #loop to calculate the next element for i in range(f-1): a,b=b,a+b return b class SummableSequence(object): def __init__(self, *initial): # initialize instance variable as below self.backup = initial def __call__(self, i): #re-initialize the list self.init=[] for x in range(len(self.backup)): self.init.append(self.backup[x]) #covering the edge cases where i<n if (i < len(self.init)): return (self.init[i]) else: #loop to get result for j in range(i + 1 - len(self.init)): temp = 0 for m in range(len(self.init)): temp += self.init[m] for m in range(len(self.init) - 1): self.init[m] = self.init[m + 1] self.init[len(self.init) - 1] = temp return self.init[len(self.init) - 1] if __name__ == "__main__": print("f(100000)[-8:]", last_8(optimized_fibonacci(100000))) new_seq = SummableSequence(5, 7, 11) print("new_seq(100000)[-8:]:", last_8(new_seq(100000)))
Comprar = input("indique su compra:") abducir = input("indique su abduccion:") estudiar = input("indique cuanto estudia:") if (jamon = "si") or ((abduccion ="si") and (dia = "J")) or (estudiar = "mucho")): print ("aprobar M03")
""" 날짜 : 2021/04/26 이름 : 김철학 내용 : 파이썬 String 예제 교재 p48 """ # 문자열 더하기 str1 = 'Hello' str2 = 'Python' str3 = str1 + str2 print('str3 :', str3) # 문자열 곱하기 name = '홍길동' print('name * 3 :', name * 3) # 문자열 길이(문자갯수) msg = 'Hello World' print('msg 길이 :', len(msg)) # 문자열 인덱스 print('msg 1번째 문자 :', msg[0]) print('msg 7번째 문자 :', msg[6]) print('msg -1번째 문자 :', msg[-1]) print('msg -5번째 문자 :', msg[-5]) # 문자열 자르기(substring) print('msg 0~5까지 문자열 :', msg[0:5]) print('msg 처음~5까지 문자열 :', msg[:5]) print('msg 6~11까지 문자열 :', msg[6:11]) print('msg 6~마지막까지 문자열 :', msg[6:]) # 문자열 분리 people = '김유신|김춘추|장보고|강감찬|이순신' p1, p2, p3, p4, p5 = people.split('|') print('p1 :', p1) print('p2 :', p2) print('p3 :', p3) print('p4 :', p4) print('p5 :', p5) # 문자열 이스케이프 print('서울\n대전\n대구\n부산\n광주') print('서울\t대전\t대구\t부산\t광주') print('저는 \'홍길동\' 입니다.') print("저는 '홍길동' 입니다.")
""" 날짜 : 2021/04/29 이름 : 김철학 내용 : 파이썬 내장함수 교재 p118 """ import math import random import time # 수학관련 # 절대값 r1 = abs(-5) print('r1 :', r1) # 올림값 r2 = math.ceil(1.2) r3 = math.ceil(1.8) print('r2 :', r2) print('r3 :', r3) # 내림값 r4 = math.floor(1.2) r5 = math.floor(1.8) print('r4 :', r4) print('r5 :', r5) # 반올림 r6 = round(1.2) r7 = round(1.8) print('r6 :', r6) print('r7 :', r7) # 제곱근 r8 = math.sqrt(4) r9 = math.sqrt(9) print('r8 :', r8) print('r9 :', r9) # random num1 = random.random() print('num1 :', num1) # 0 ~ 1 사이에 실수 num2 = num1 * 10 print('num2 :', num2) # 0 ~ 45 사이에 실수 num3 = math.ceil(num2) print('num3 :', num3) # 1 ~ 45 사이에 정수 num4 = math.ceil(random.random() * 45) print('num4 :', num4) # 1 ~ 45 사이에 정수 # 날짜,시간 t1 = time.time() print('t1 :', t1) # Unix time t2 = time.ctime() print('t2 :', t2) # 변환된 Unix time now = time.localtime(time.time()) year = time.strftime('%Y', now) month = time.strftime('%m', now) date = time.strftime('%d', now) hour = time.strftime('%H', now) min = time.strftime('%M', now) sec = time.strftime('%S', now) print('%s년 %s월 %s일' % (year, month, date)) print('%s시 %s분 %s초' % (hour, min, sec))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 7 21:20:36 2019 @author: ankit """ ## Building CNN to classify cats and dogs from keras.models import Sequential # To initialize the neural network from keras.layers import Convolution2D # To Convolute the input image from keras.layers import MaxPooling2D # Max pooling to for dimension flexibility from keras.layers import Flatten # To give it to the ANN from keras.layers import Dense # To add layers to the network #Initializing the CNN classifier = Sequential() # Convoluting classifier.add(Convolution2D(32,3,3,activation='relu',input_shape = (64,64,3))) # Max pooling classifier.add(MaxPooling2D(pool_size=(2,2))) # Flattening classifier.add(Flatten()) # Full connection classifier.add(Dense(output_dim = 128, activation = 'relu')) classifier.add(Dense(output_dim = 1, activation = 'sigmoid')) # softmax activation if more than 2 outputs # compiling the CNN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Stochastic gradient descent, loss function and metric of result # fitting the CNN to the images ## Data augmentation from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) training_set = train_datagen.flow_from_directory('dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary') test_set = test_datagen.flow_from_directory('dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary') classifier.fit_generator(training_set, steps_per_epoch=8000, epochs=25, validation_data= test_set, validation_steps= 2000)
import pandas as pd #Creo un dataset mis_empleados = pd.DataFrame({"nombre": ["Nico", "Estefi", "Jorge", "Pedro", "Jesica", "Hector"], "edad":[33, 44, 29, 45, 37, 28], "sueldo":[40000, 66000, 102222, 32089, 342132, 234343]}) #Agrego una columna con el nuevo sueldo actualizado #Utilizo la funcion apply y defino la funcion lambda mis_empleados["Sueldo Actualizado"] = mis_empleados.apply(lambda x: x["sueldo"]*1.2, axis=1) print(mis_empleados)
# -*- coding: utf-8 -*- """ Created on Sat May 22 19:44:14 2021 @author: Nico """ #MAXIMO NUMERO EN UNA LISTA PROPIA numero_actual=0 mi_lista=[3,4,213,453,23,534,534354363415] for numero in mi_lista: if numero>numero_actual: numero_actual=numero print("EL MAXIMO NUMERO ES: ", numero_actual)
x=5 y=7 sumar_numeros = lambda x,y : x + y #usando variables print("resultado= ",sumar_numeros(x,y)) #usando numeros enteros print("resultado= ",sumar_numeros(10,7)) print("resultado= ",sumar_numeros( sumar_numeros(1,1),7 ) )
# -*- coding: utf-8 -*- """ Created on Sun Mar 21 18:11:27 2021 @author: la03237 """ #Defino cuantos numeros quiero que tenga la serie cuantosnumerosquiero = 100 #Defino las variables para la formula. Al principio serán 2: 0 y 1 numero1 = 0 numero2 = 1 #Defino variable la cual contendrá el resultado de la suma para cada par de numeros numeron = 0 #Defino cuantos numeros voy cuantosnumerosvoy = 0 #Titulo print ("SECUENCIA DE FIBONACCI POR NICO") #Ahora a hacer la loop hasta llegar a los 100 numeros de la serie while (cuantosnumerosvoy < cuantosnumerosquiero): print (numero1) numeron = numero1 + numero2 #Actualizo para que siempre el resultado sea la suma de los ultimos 2 numeros numero1 = numero2 numero2 = numeron #Actualizo mi cuenta cuantosnumerosvoy += 1
#DEFINO LA VARIABLE CON EL TIPO DE CAMBIA exchange_rate_ARS = 150 #DEFINO LA FUNCION CON EL PARAMETRO PESOS def conversion(pesos): dolares = pesos/exchange_rate_ARS return dolares #LE PIDO AL USUARIO QUE INGRESE LA CANTIDAD DE PESOS #QUE SERÁ EL PARAMETRO DE LA FUNCION pesos = float(input("INGRESE CANTIDAD DE PESOS: ")) #IMPRIMO LLAMANDO A LA FUNCION print ("LE CORRESPONDE:", conversion(pesos), "DOLARES")
import random def push(stack,element): stack.append(element) return stack def pop(stack): element = stack.pop() return stack,element def coppare(stack): #pila1=[] #pila2=[] #item=[] y = random.randint(1,len(stack)-1) stack = stack[y:len(stack)] + stack[0:y] """ for i in range (0,y): item = pop(stack) push(pila1,item) for i in range (y,len(stack)): item = pop(stack) push(pila2,item) for i in range (0,y): item = pop(pila1) push(stack,item) for i in range (y,len(stack)): item = pop(pila2) push(stack,item) """ return stack class carta(object): #metodo costruttore della classe def __init__(self,seme,numero): self.seme = seme self.numero = numero def stampa (self): print(f"Il seme della carta è {self.seme} e la carta è {self.numero}") # c = carta("Cuori",13) # c.stampa() Semi = ["C","P","F","D"] Mazzo = [] for i in range(1,14): for s in Semi: push(Mazzo,carta(s,i)) Mazzo = coppare(Mazzo) for i in Mazzo: i.stampa()
''' Computes simple affine cipher ( (a*x + b) % 26 ) ''' Alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] alpha = int(input("Enter alpha")) beta = int(input("Enter beta")) message = input("Enter message") def affine(a, b, letter): return (a*letter + b) % 26 def encode(secret): secret = secret.replace(' ', '') secret = secret.upper() ciphertext = '' for letter in secret: orig = Alphabet.index(letter) coded = affine(alpha, beta, orig) newletter = Alphabet[coded] ciphertext = ciphertext + newletter return ciphertext print(encode(message))
''' Takes message and key and encrypts message using provided key in a Vigenere cipher (currently no decrypting function) ''' Alphabet = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z') def shift(orig, shifter): post = (Alphabet.index(orig) + Alphabet.index(shifter)) % 26 postletter = Alphabet[post] return postletter key = input("Enter the key (no spaces): ") key = key.upper() message = input("Enter the message to be encrypted: ") message = message.replace(" ", "").upper() crypto = "" for i in range(len(message)): print(i) cryptoletter = shift(message[i], key[i%len(key)]) crypto += cryptoletter print(crypto)
i = 1 while i <= 10: print(i, end=' ', sep='!') i += 1 else: print('Конец цикла while') for _ in range(1, 11): print(_, end=' ') else: print('Конец цикла for')
#CS 2302 Data Structures Fall 2019 MW 10:30 #Sergio Ortiz #Assignment - Lab #2 - Part 2 #Instructor - Olac Fuentes #Teaching Assistant - Anindita Nath #September 20, 2019 #This program implements quicksort non - recursively #as well as select_modified_quick using a while loop class stackRecord(object): def __init__(self, L, start, end): self.L = L self.start = start self.end = end #partition(): the main function of quicksort #gets a pivot from a list, and moves everything #less than it to the left of it and everything #greater than it to the right #inputs: L - a list to be sorted # start - the start index of the list # end - the end index of the list #output: the index of the pivot def partition(L, start, end): i = (start - 1) pivot = L[end] for j in range(start, end): if(L[j] <= pivot): i += 1 L[i], L[j] = L[j], L[i] L[i+1], L[end] = L[end], L[i+1] return(i + 1) #quick_sort_nr(): a non recursive implementation #of the naturally recursive algorithm, quicksort #input: L - the list to be sorted def quick_sort_nr(L): start = 0 end = len(L) - 1 quick_sorter_nr(L, start, end) #quick_sorter_nr(): the actual implementation #of the non recursive quicksort using a stack #inputs: L - the list to be sorted # start - the start index of the list # end - the end index of the list def quick_sorter_nr(L, start, end): stack = [stackRecord(L, start, end)] while(len(stack) > 0): h = stack.pop(-1) if(h.start < h.end): part = partition(h.L, h.start, h.end) stack.append(stackRecord(h.L, h.start, part - 1)) stack.append(stackRecord(h.L, part + 1, h.end)) #while_select(): an implementation of the #select_modified_quick algorithm without using recursion #or stacks #inputs: L - the list to be traversed # k - the index of the desired element #outputs: the value of L[k] def while_select(L,k): start = 0 end = len(L) - 1 return while_selector(L, start, end, k) #while_selector(): the algorithm for select_modified_quick #using a while loop #inputs: L - the list to be traversed # start - the beginning index # end - the end index # k - the index of the element we are looking for #outputs: the value of L[k] def while_selector(L, start, end, k): pivot = partition(L, start, end) while(pivot != k): if(k < pivot): pivot = partition(L, start, pivot -1) elif(k > pivot): pivot = partition(L, pivot + 1, end) return L[pivot] if __name__ == "__main__": L1 = [6,3,7,3,1,7,8,9,6,4,1,6] quick_sort_nr(L1) print(L1) L = [4,2,7,3,2] print(while_select(L, 0))
#CS 2302 Data Structures Fall 2019 MW 10:30 #Sergio Ortiz #Assignment - Lab #5 #Instructor - Olac Fuentes #Teaching Assistant - Anindita Nath #November 1, 2019 #This program will compare the runtimes between #a Hash Table with Chaining and a Hash Table with #Linear Probing import Sergio_Ortiz_HashC as hc import Sergio_Ortiz_HashLP as hlp import numpy as np import time #buildChaining() - function to build a hash table with chaining #inputs : None #outputs: a hash table with a lot of english words def buildChaining(): T = None T = hc.HashTableChain(65) f = open("glove.6B.50d.txt", encoding = "utf8") line = f.readline().split(' ') #creates a list, splits at spaces while line[0] != '': #for some reason when I reached the end of the #file it would keep creating lists with the empty [''] T.insert(line[0], np.asarray(line[1:-1])) line = f.readline().split(' ') f.close() return T #buildLinear() - builds a hash table with linear probing #inputs: None #outputs : a hash table with a lot of English Words def buildLinear(): counter = 5000 T = None T = hlp.HashTableLP(99999) #f = open("words.txt", encoding = "utf8") f = open("glove.6B.50d.txt", encoding = "utf8") line = f.readline().split(' ') #creates a list, splits at spaces while counter > 0: #line[0] != '': #for some reason when I reached the end of the #file it would keep creating lists with the empty [''] if ord(line[0][0]) > 64: T.insert(line[0], np.asarray(line[1:-1])) line = f.readline().split(' ') counter -= 1 f.close() return T #chooseTable() - Method for the user to choose which hash table #inputs: None #outputs: a number representing either a chaining or linear probing table def chooseTable(): print('(1) Hash Table with Chaining') print('(2) Hash Table with Linear Probing') choice = int(input('Which Hash Table do you want to use? ')) return choice #main() - main method where all the functions go #No inputs or outputs def main(): choice = chooseTable() while choice != 1 and choice != 2: print() print('Please enter 1 or 2') choice = chooseTable() if choice == 1: start = time.time() table = buildChaining() end = time.time() elapsed = end - start print('Time to build Hash Table with Chaining: ', elapsed) start = time.time() SimilaritiesChaining(table) end = time.time() elapsed = end - start print('Time to get similarities: ', elapsed) if choice == 2: start = time.time() table = buildLinear() end = time.time() elapsed = end - start print('Time to build Hash Table with Linear Probing ', elapsed) start = time.time() SimilaritiesLinear(table) end = time.time() elapsed = end - start print('Time to get similarities: ', elapsed) def SimilaritiesChaining(T): word_file = open("words.txt", "r") line = word_file.readline().split(' ') while line[0] != '': word1 = line[0] word2 = line[1].strip('\n') a = T.getEmbedding(str(word1)) b = T.getEmbedding(str(word2)) numerator = np.dot(a, b) den1 = np.linalg.norm(a) den2 = np.linalg.norm(b) sim = (numerator) / ((den1) * (den2)) print("Similarity [",str(word1),",",str(word2),"] = ", str(sim)) line = word_file.readline().split(' ') def SimilaritiesLinear(T): word_file = open("words.txt", "r") line = word_file.readline().split(' ') while line[0] != '': word1 = line[0] word2 = line[1].strip('\n') a = T.getEmbedding(str(word1)) b = T.getEmbedding(str(word2)) numerator = np.dot(a, b) den1 = np.linalg.norm(a) den2 = np.linalg.norm(b) sim = (numerator) / ((den1) * (den2)) print("Similarity [",str(word1),",",str(word2),"] = ", str(sim)) line = word_file.readline().split(' ') if __name__ == "__main__": main()
""" Создайте список из всех нечётных чисел от 1 до 100 и передайте его в функцию, которая переставляет его элементы в случайном порядке (например, 99 11 43 19 … 7 91 3 1). Примечание: использовать метод random.shuffle не допускается. def shuffle_list(list_to_shuffle): # no return (shuffles list in place) pass """ import random lst_odd = [] for i in range (1,100): if (i % 2) != 0: lst_odd.append(i) def shuffle_list(list_to_shuffle): for i in range (0, len(list_to_shuffle)): random_index = random.randint (0, (len(list_to_shuffle)-1)) temp_elem = list_to_shuffle[i] temp_random = list_to_shuffle[random_index] list_to_shuffle[i] = temp_random list_to_shuffle[random_index] = temp_elem print (list_to_shuffle) shuffle_list(lst_odd)
""" Написать функцию решения квадратного уравнения. def solve_quadratic_equation(a, b, c): # returns 2 values: either 2 roots, 1 root and None or 2 Nones """ import math def solve_quadratic_equation (a, b, c) : d = b**2 - 4*a*c #print(d) if d == 0: x = (- b) / (2 * a) return x, None elif d < 0: return None, None elif d > 0: x1 = (- b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) x2 = (- b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) return x1, x2 print(solve_quadratic_equation(2, 4, 2))
""" Два поезда движутся на скорости V1 и V2 навстречу друг другу. Между ними 10 км. пути. Через 4 км пути первый поезд может свернуть на запасной путь. При заданных скоростях узнать столкнутся ли поезда. def have_trains_crashed(v1, v2): # returns boolean value """ def have_trains_crashed(v1, v2): return 4 / v1 >= 6 / v2 print ('Will trains crash? ', have_trains_crashed(2,3))
""" Написать программу, которая преобразует имя переменной в формате snake_case в формат CamelCase. Для простоты считаем, что имя переменной всегда состоит из 3-х слов. Например: 'employee_first_name' -> 'EmployeeFirstName' """ snake_case = 'employee_first_name' snake_case_lst = snake_case.split('_') print(snake_case_lst) word_1 = snake_case_lst[0] word_2 = snake_case_lst [1] word_3 = snake_case_lst [2] print(word_1, word_2, word_3) CamelCase = word_1.capitalize()+word_2.capitalize()+word_3.capitalize() print('For snake_case <', snake_case, '> CamelCase will be: <', CamelCase, '>')
#!/usr/bin/python import Tkinter class SimpleApp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.entry = Tkinter.Entry(self) self.entry.grid(column = 2, row = 2, sticky="EW") Tkinter.Label(self.entry, text = "Enter Origin: ", borderwidth=1).grid(row = 1, column = 0, sticky= "EW", ipadx = 2, ipady = 2) Tkinter.Label(self.entry, text = "Enter Destination: ", borderwidth=1).grid(row = 2, column = 0, ipadx = 2, ipady = 2) Tkinter.Label(self.entry, text= "Directions: ", borderwidth=1).grid(row = 3, column = 0, ipadx = 2, ipady = 2) if __name__ == "__main__": app = SimpleApp_tk(None) app.title("Tunnel Navigation") app.mainloop()
def who_wins(a, b): if(a == "R" and b == "S"): print("A Wins") return 1 elif(a == "S" and b == "P"): print("A Wins") return 1 elif(a == "P" and b == "R"): print("A Wins") return 1 elif(a == b): print("DRAW") return 0 else: print("B Wins") return 0 rounds = int(input()) comps = input() player_1 = 0 for i in range(rounds): next_round = comps[:2] # gets the first two letters player_1 += who_wins(next_round[0]+"", next_round[1]+"") comps = comps[2:] # removes the first two letters if(player_1 >= rounds / 2 and rounds % 2 == 1): print("A Wins Tournament") elif(player_1 > rounds / 2 and rounds % 2 == 0): print("A Wins Tournamet") elif(player_1 == rounds / 2 and rounds % 2 == 0): print("DRAW") else: print("B Wins Tournament")
## ejemplo ciclo for nombre = str(input("Ingrese su nombre: ")); edad = int(input("Ingrese su edad: ")); edad_lista = []; aux = 0; while aux < edad: aux = aux + 1; edad_lista.append(aux); for i in edad_lista: print(i); ## ejemplo con range lista_range = list(range(10)); print(lista_range[0]); print(lista_range); lista_dos = list(range(2,6)); print(lista_dos);
# -*- coding: utf-8 -*- import datetime import math import random class Solution(): def __init__(self): random.seed(datetime.datetime.now()) def crack(self, prec=3): inside, total, diff = 0, 0, 1 scale = 10 ** (prec) base = int(float('{0:.{prec}f}'.format(math.pi, prec=prec)) * scale) while diff != 0: x2 = random.random() ** 2 y2 = random.random() ** 2 if x2 + y2 < 1.0: inside += 1 total += 1 pi = float(inside) / total * 4 diff = int(pi * scale) - base return float('{0:.{prec}f}'.format(pi, prec=prec)) if __name__ == '__main__': solver = Solution() print(solver.crack(5))
# -*- coding: utf-8 -*- class Solution(): def is_valid(self, board, row): if row in board: return False col = len(board) for occupied_col, occupied_row in enumerate(board): if abs(occupied_row - row) == abs(occupied_col - col): return False return True def put_queen(self, board, n): if n == len(board): return 1 count = 0 for row in range(n): if self.is_valid(board, row): count += self.put_queen(board + [row], n) return count def crack(self, n): return self.put_queen([], n) if __name__ == '__main__': inputs = [ 8, ] for n in inputs: print() print(' Input:', n) solver = Solution() count = solver.crack(n) print(' Output:', count)
# -*- coding: utf-8 -*- class Solution(): def crack(self, nums, word_size=32): target = 0 for i in range(word_size): sum_bits = 0 x = 1 << i for j in range(len(nums)): if nums[j] & x: sum_bits += 1 if sum_bits % 3: target |= x return target if __name__ == '__main__': inputs = [ [6, 1, 3, 3, 3, 6, 6], [13, 19, 13, 13], ] for nums in inputs: print('\n Input: {}'.format(nums)) solver = Solution() target = solver.crack(nums) print(' Output: {}'.format(target))
# -*- coding: utf-8 -*- def break_text(sentence, k): words = sentence.split() broken_text = [] char_count = -1 current_words = [] idx = 0 while idx < len(words): word = words[idx] if len(word) > k: return None if char_count + len(word) + 1 <= k: char_count += len(word) + 1 current_words.append(word) idx += 1 else: broken_text.append(' '.join(current_words)) char_count = -1 current_words = [] broken_text.extend(current_words) return broken_text if __name__ == '__main__': sentence = 'the quick brown fox jumps over the lazy dog' k = 10 print(' Input:', sentence) print(' k:', k) texts = break_text(sentence, k) print(' Output:') print('\n'.join(texts))
# -*- coding: utf-8 -*- class Solution: def findMedianSortedArrays(self, nums1, nums2) -> float: half = (len(nums1) + len(nums2)) // 2 if (len(nums1) + len(nums2)) & 0x1 == 0: lhs = find_kth(nums1, nums2, half) rhs = find_kth(nums1, nums2, half + 1) return (lhs + rhs) / 2 else: return find_kth(nums1, nums2, half + 1) def find_kth(nums1, nums2, k): # Always assume the length of nums1 is equal or smaller than that of nums2. if len(nums1) > len(nums2): return find_kth(nums2, nums1, k) if len(nums1) == 0: return nums2[k - 1] if k == 1: return min(nums1[0], nums2[0]) # Divide k into two parts. ia = min(k // 2, len(nums1)) ib = k - ia if nums1[ia - 1] < nums2[ib - 1]: return find_kth(nums1[ia:], nums2, k - ia) elif nums1[ia - 1] > nums2[ib - 1]: return find_kth(nums1, nums2[ib:], k - ib) else: return nums1[ia - 1] if __name__ == '__main__': inputs = [ ([], [2, 3]), ([1, 3], [2]), ([1, 3], [2, 4]), ] s = Solution() for nums1, nums2 in inputs: print(' nums1 = {}'.format(nums1)) print(' nums2 = {}'.format(nums2)) median = s.findMedianSortedArrays(nums1, nums2) print('The median is {}\n'.format(median))
#The player decides between two caves, which hold either treasure or certain doom. import random import time def introduction(): print('''Welcome Player. Would you like to play a game? (yes or no)''') decision = input('> ') while True: try: if decision.lower() == 'no' or decision.lower() == 'n': print('good-bye') break else: start() except ValueError: print('Sorry player, didn\'t understand your input.\nPlease type again.') continue else: break def start(): print('''You are in a land full of dragons. In front of you, you see two caves. In one cave, the dragon is friendly and will share his treasure with you. The other dragon is greedy and hungry, and will eat you on sight. Which cave will you go into? (1 or 2)''') caves() def caves(): caveNumber = input('> ') if caveNumber.lower() == '1': first_path() elif caveNumber.lower() == '2': second_path() else: print("Try that again.") caves() def first_path(): print('''You approach the cave... It is dark and spooky... A large dragon jumps out in front of you! He opens his jaws and...''') time.sleep(2) print('''Gobbles you down in one bite! Do you want to play again? (yes or no)''') play_again() def second_path(): print('''You approach the cave... It is dark and spooky... The cave goes on... You find a Torch on the wall and light it.''') time.sleep(2) print('''The light brightens the room and so see nothing but gold piled in the cave. Do you want to play again? (yes or no)''') play_again() def play_again(): choice = input('> ') if choice.lower() == 'yes': start() elif choice.lower() == 'no': print("good-bye") else: print("sorry, what was that?") play_again() introduction()
""" Link to the question - https://leetcode.com/problems/next-permutation/ """ class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) i = n - 1 while i > 0: if nums[i] > nums[i - 1]: j = n - 1 while j >= i: if nums[j] > nums[i - 1]: nums[j], nums[i - 1] = nums[i - 1], nums[j] break j -= 1 break i -= 1 limit = (n - i)//2 count = 0 while count < limit: nums[i + count], nums[n - count - 1] = nums[n - count - 1], nums[i + count] count += 1
import pygame from math import * import time win = pygame.display.set_mode((400, 600)) running = True t = pygame.time.Clock() fps = 1 def draw_circle(): circle_surface = pygame.Surface((100, 100)) pygame.draw.arc(circle_surface, (0, 0, 255), circle_surface.get_rect(), 0, 2 * pi) win.blit(circle_surface, (200, 300)) def draw_centered_circle(): x, y = 200, 200 print(100 * math.sin(1), 100 * math.cos(1)) radius_1 = 100 radius_2 = 2 pygame.draw.circle(win, (0, 0, 0), (x, y), 6, 1) pygame.draw.circle(win, (255, 255, 255), (x, y - 100), 6, 1) pygame.draw.line(win, (255, 255, 255), (x, y), (x, y - radius_1), 2) while running: #draw_centered_circle() draw_circle() for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit() pygame.display.update()
list=[1,2,2,3,'a','a'] # a=input("enter the values:") # list.append(a) x=[] for i in list: # for i not in x: if not i in x: x.append(i) print("non duplicate values:") print(x)
# coding=utf-8 print('时尚大方') if True: print'add', 'same line' else: print('adsfsfdfg') # raw_input("按下 enter 键退出,其他任意键显示...\n") ''' 注释 ''' total = 1 +\ 2 + \ 3 print(total) str = 'abcde' print str[-2], str[1:4], str[1:], str * 2 list = [1,2,3,4] print list[:], list * 2, list + [5,6] dict = { 'a': 1, "b": 2 } print dict.keys(), dict.values(), 11 //2 print 1 in list, 2 not in list, 'a' in dict print list == [1,2,3,4], list is [1,2,3,4] print "My name is %s and weight is %d kg!" % ('Zara', 21) import math print dir(math)
import math import generator # Funguje, jistota def baby_step(g, A, B, p): babystep_count = int(math.ceil(math.sqrt(p - 1))) pole = {} #baby step for i in range(babystep_count): pole[pow(g, i, p)] = i # giant step c = pow(g, babystep_count * (p - 2), p) for j in range(babystep_count): y = ((A * pow(c, j, p)) % p) if y in pole: tajnaAlice = int(j * babystep_count + pole[y]) print("\nTajná hodnota 'a': " + str(int(tajnaAlice))) klic = pow(B, tajnaAlice, p) print("Tajný klíč: " + str(klic)) break return None # Pokus o zpracování větších čísel # pole nabere příliš velkou velikost a počítač už to nezvládá, pro 8GB RAM # NEFUNGUJE :( """ def baby_step3(g, A, p): N = int(math.ceil(math.sqrt(p - 1))) print("N: " + str(N)) pole = {} if N > 1: M = int(N / 2) print(M) else: M = N hodnota = 0 while hodnota < N: # Baby step. pole.clear() for i in range(M): if hodnota == N: break if hodnota != N: pole[pow(g, hodnota, p)] = hodnota hodnota += 1 c = pow(g, N * (p - 2), p) promena = 0 for j in range(N): y = ((A * pow(c, promena, p)) % p) promena += 1 if y in pole: print(pole[y]) list1 = {} list1[pole[y]] = promena for j in range(N): y = ((A * pow(c, j, p)) % p) if y in list1: return j * N + list1[y] """
from Pieces import * from Chessboard import * class Knight(Pieces): """ Represent the pieces of type Knight. """ name = 'Knight' VALUE = 30 def __init__(self, position, color): """ Create a Knight Based on the Piece class. :param position: Position on the chessboard :param color: Color of hte Piece: white::0, black::1 """ Pieces.__init__(self, position, color,"N") add_piece_location(position, self) def moves_attack(self): moves = list() # List of possible moves file_pos = int(convert_file(self.position[0])) rank_pos = int(self.position[1]) """ Check for all the position where the Knight could go. is_space_available check in Chessboard """ if rank_pos + 2 <= 8: if file_pos + 1 <= 8 and position_status(self, str(convert_file(file_pos + 1)) + str(rank_pos + 2)) == 1: file_letter = convert_file(file_pos + 1) moves.append(file_letter + str(rank_pos + 2)) if file_pos - 1 > 0 and position_status(self, str(convert_file(file_pos - 1)) + str(rank_pos + 2)) == 1: file_letter = convert_file(file_pos - 1) moves.append(file_letter + str(rank_pos + 2)) if rank_pos - 2 > 0: if file_pos + 1 <= 8 and position_status(self, str(convert_file(file_pos + 1)) + str(rank_pos - 2)) == 1: file_letter = convert_file(file_pos + 1) moves.append(file_letter + str(rank_pos - 2)) if file_pos - 1 > 0 and position_status(self, str(convert_file(file_pos - 1)) + str(rank_pos - 2)) == 1: file_letter = convert_file(file_pos - 1) moves.append(file_letter + str(rank_pos - 2)) if file_pos + 2 <= 8: if rank_pos + 1 <= 8 and position_status(self, str(convert_file(file_pos + 2)) + str(rank_pos + 1)) == 1: file_letter = convert_file(file_pos + 2) moves.append(file_letter + str(rank_pos + 1)) if rank_pos - 1 > 0 and position_status(self, str(convert_file(file_pos + 2)) + str(rank_pos - 1)) == 1: file_letter = convert_file(file_pos + 2) moves.append(file_letter + str(rank_pos - 1)) if file_pos - 2 > 0: if rank_pos + 1 <= 8 and position_status(self, str(convert_file(file_pos - 2)) + str(rank_pos + 1)) == 1: file_letter = convert_file(file_pos - 2) moves.append(file_letter + str(rank_pos + 1)) if rank_pos - 1 > 0 and position_status(self, str(convert_file(file_pos - 2)) + str(rank_pos - 1)) == 1: file_letter = convert_file(file_pos - 2) moves.append(file_letter + str(rank_pos - 1)) return moves def moves_blocked(self): moves = list() # List of possible moves file_pos = int(convert_file(self.position[0])) rank_pos = int(self.position[1]) """ Check for all the position where the Knight could go. is_space_available check in Chessboard """ if rank_pos + 2 <= 8: if file_pos + 1 <= 8 and position_status(self, str(convert_file(file_pos+1))+str(rank_pos+2)) == -1: file_letter = convert_file(file_pos + 1) moves.append(file_letter + str(rank_pos + 2)) if file_pos - 1 > 0 and position_status(self, str(convert_file(file_pos-1))+str(rank_pos+2)) == -1: file_letter = convert_file(file_pos - 1) moves.append(file_letter + str(rank_pos + 2)) if rank_pos - 2 > 0: if file_pos + 1 <= 8 and position_status(self, str(convert_file(file_pos+1))+str(rank_pos-2)) == -1: file_letter = convert_file(file_pos + 1) moves.append(file_letter + str(rank_pos - 2)) if file_pos - 1 > 0 and position_status(self, str(convert_file(file_pos-1))+str(rank_pos-2)) == -1: file_letter = convert_file(file_pos - 1) moves.append(file_letter + str(rank_pos - 2)) if file_pos + 2 <= 8: if rank_pos + 1 <= 8 and position_status(self, str(convert_file(file_pos+2))+str(rank_pos+1)) == -1: file_letter = convert_file(file_pos + 2) moves.append(file_letter + str(rank_pos + 1)) if rank_pos - 1 > 0 and position_status(self, str(convert_file(file_pos+2))+str(rank_pos-1)) == -1: file_letter = convert_file(file_pos + 2) moves.append(file_letter + str(rank_pos - 1)) if file_pos - 2 > 0: if rank_pos + 1 <= 8 and position_status(self, str(convert_file(file_pos-2))+str(rank_pos+1)) == -1: file_letter = convert_file(file_pos - 2) moves.append(file_letter + str(rank_pos + 1)) if rank_pos - 1 > 0 and position_status(self, str(convert_file(file_pos-2))+str(rank_pos-1)) == -1: file_letter = convert_file(file_pos - 2) moves.append(file_letter + str(rank_pos - 1)) return moves def moves(self): """ Returns the list of possible moves for the Knight. :return: List of possible moves :rtype list """ moves = list() # List of possible moves file_pos = int(convert_file(self.position[0])) rank_pos = int(self.position[1]) """ Check for all the position where the Knight could go. is_space_available check in Chessboard """ if rank_pos + 2 <= 8: if file_pos + 1 <= 8 and is_space_available(file_pos+1, rank_pos+2, self.COLOR): file_letter = convert_file(file_pos + 1) moves.append(file_letter + str(rank_pos + 2)) if file_pos - 1 > 0 and is_space_available(file_pos - 1, rank_pos + 2, self.COLOR): file_letter = convert_file(file_pos - 1) moves.append(file_letter + str(rank_pos + 2)) if rank_pos - 2 > 0: if file_pos + 1 <= 8 and is_space_available(file_pos + 1, rank_pos - 2, self.COLOR): file_letter = convert_file(file_pos + 1) moves.append(file_letter + str(rank_pos - 2)) if file_pos - 1 > 0 and is_space_available(file_pos - 1, rank_pos - 2, self.COLOR): file_letter = convert_file(file_pos - 1) moves.append(file_letter + str(rank_pos - 2)) if file_pos + 2 <= 8: if rank_pos + 1 <= 8 and is_space_available(file_pos + 2, rank_pos + 1, self.COLOR): file_letter = convert_file(file_pos + 2) moves.append(file_letter + str(rank_pos + 1)) if rank_pos - 1 > 0 and is_space_available(file_pos + 2, rank_pos - 1, self.COLOR): file_letter = convert_file(file_pos + 2) moves.append(file_letter + str(rank_pos - 1)) if file_pos - 2 > 0: if rank_pos + 1 <= 8 and is_space_available(file_pos - 2, rank_pos + 1, self.COLOR): file_letter = convert_file(file_pos - 2) moves.append(file_letter + str(rank_pos + 1)) if rank_pos - 1 > 0 and is_space_available(file_pos - 2, rank_pos - 1, self.COLOR): file_letter = convert_file(file_pos - 2) moves.append(file_letter + str(rank_pos - 1)) return moves
from Tkinter import * root = Tk() root.title("Prime Checker") global numberPrime introText = "Prime Checker. Programmed by David McClarty. Last updated 01/06/2018.\n\ Type your number into the program to see if your number is prime or not.\n\ Press the 'info' button for more information and more cool things this program does.\n\ Note: Numbers as large as 9 digits will take 5 seconds or more to calculate.\n\ This program was coded in Python 2.7, written by David McClarty, and was first coded on 1/04/2017." primeList = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] startNum = 0 finishNum = 0 stepsize = 0 inputStartNum = None inputFinishNum = None inputStepSize = None def onButtonClick(): numberPrime = inputPrime.get() outputPrime.delete(1.0, END) try: primeTest(int(numberPrime)) except ValueError: if float(numberPrime) % 1 != 0: outputPrime.insert(END, "Decimals are not integers and therefore cannot be prime.\n") else: outputPrime.insert(END, "I don't know what " + str(numberPrime) + " means.") def primeTest(numberPrime): try: primeBoolean = True if numberPrime < 0: outputPrime.insert(END, "Negative numbers aren't really prime numbers.\n") numberPrime = abs(numberPrime) if numberPrime == 1: outputPrime.insert(END, "1, while only divisible by 1 or itself, is not considered a prime, because it can't be used in prime factorization.\n") elif numberPrime == 0: outputPrime.insert(END, "0 has an infinite amount of factors, and therefore isn't prime.\n") else: x = 101.0 for number in range(len(primeList)): if float(numberPrime) % (primeList[number]) == 0 and primeList[number] != numberPrime: primeBoolean = False x = primeList[number] break if primeBoolean: while x-1 <= (numberPrime / 101.0): if float(numberPrime) % x == 0: primeBoolean = False break x = x + 2.0 if primeBoolean: outputPrime.insert(END, str(numberPrime) + " is a prime\n") else: outputPrime.insert(END, str(numberPrime) + " is divisible by " + str(x) + "\n") except ValueError: outputPrime.delete(1.0, END) outputPrime.insert(END, "Please insert a number.") outputPrime = Text(root, bg = "grey", height = 13) outputPrime.insert(END, introText) outputPrime.pack() inputPrime = Entry(root, bg = "white") inputPrime.pack() enterButton = Button(root, text = "Enter", command = onButtonClick) enterButton.pack() root.geometry('500x300') root.mainloop()
import random WoordLijst = ["computer", "python", "stoel", "tafel", "jas", "deur", "gordijn", "tapijt", "bloem"] #Dit onderdeel pakt met behulp van random een random woord uit de WoordLijst GeheimWoord = WoordLijst[random.randrange(0, len(WoordLijst))] GeradenLetters = [] levens = 10 #dit onderdeel kijkt of een letter al geraden is. def gewonnen(): for i in range(len(GeheimWoord)): if not GeheimWoord[i] in GeradenLetters: return(False) return(True) #Dit onderdeel print de goeie letters uit zoals ##a## def WihWoord(): for a in range(len(GeheimWoord)): if GeheimWoord[a] in GeradenLetters: print(GeheimWoord[a], '', end='') else: print("# ", end=" ") print(" ") print('_ ' * len(GeheimWoord)) WihWoord() #Als true is dan doe de volgende dingen. while True: letter = input("raad een letter of type het woord ") #Dit onderdeel checkt of een letter of woord goed is of al geraden is if len(letter) == 1: if letter in GeradenLetters: print("Die letter heb je al geraden") WihWoord() else: GeradenLetters += letter #Als het letter in het woord zit dan heeft de speler gewonnen if letter in GeheimWoord: print("Dat is goed! Die letter zit in het woord.") WihWoord() #Dit onderdeel checkt of alle letters zijn geraden met behulp van gewonnen() die een true of false aangeeft if gewonnen(): print("Alle letters zijn geraden! Je hebt gewonnen") print("Het woord was: " + GeheimWoord) break else: print("Dat is fout. Die letter zit niet in het woord") print("-1") levens -= 1 WihWoord() #Als de player het goeie woord in typed dan heeft de speler gewonnen, zo niet dan gaan er 2 levens weg. elif letter == GeheimWoord: print("Het woord is geraden! Je hebt gewonnen") break else: print("Dat is niet het goeie woord") print('-2') levens -= 2 WihWoord() #Dit checkt of de speler nog levens heeft. if levens <= 0: print("Jammer, je hebt verloren. Het woord was"+ GeheimWoord) break print("Je hebt nog" ,levens, "levens over") print("Bedankt voor het spelen. Gemaakt door Sami Akazim uit 6-1vh3")
# 存在重复 # 给定一个整数数组,判断是否存在重复元素。 # # 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。 # # 示例 1: # # 输入: [1,2,3,1] # 输出: true # 示例 2: # # 输入: [1,2,3,4] # 输出: false # 示例 3: # # 输入: [1,1,1,3,3,4,3,2,4,2] # 输出: true class Solution: def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ for i in range(1,len(nums)): if nums[-i] in nums[:-i]: return True else: return False if __name__ == '__main__': s = Solution() l = [1,2,3,4] print(s.containsDuplicate(l))
# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 # # 有效字符串需满足: # # 左括号必须用相同类型的右括号闭合。 # 左括号必须以正确的顺序闭合。 # 注意空字符串可被认为是有效字符串。 # # 示例 1: # # 输入: "()" # 输出: true # 示例 2: # # 输入: "()[]{}" # 输出: true # 示例 3: # # 输入: "(]" # 输出: false # 示例 4: # # 输入: "([)]" # 输出: false # 示例 5: # # 输入: "{[]}" # 输出: true class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ in_list = {'(': 1, '[': 2, '{': 3} out_list = {')': 1, ']': 2, '}': 3} stack = [] if s == []: return True if s in out_list or s in in_list: return False for k in s: if k in in_list: stack.append(in_list[k]) if k in out_list: if out_list[k] != stack.pop(-1): return False return True # 范例 class Solution__: def isValid(self, s): """ :type s: str :rtype: bool """ a = {')': '(', ']': '[', '}': '{'} l = [None] for i in s: if i in a and a[i] == l[-1]: l.pop() else: l.append(i) return len(l) == 1 # # class Solution1: # def scoreOfParentheses(self, S): # """ # :type S: str # :rtype: int # """ # print(S) # if len(S) > 2: # if S[1] == '(' and S[-2] == ')': # return 2 * self.scoreOfParentheses(S[1:-1]) # elif S[1] == '(' and S[-2] == '(': # return 1 + self.scoreOfParentheses(S[:-2]) # elif S[1] == ')' and S[-2] == ')': # return 1 + self.scoreOfParentheses(S[2:]) # elif S[1] == ')' and S[-2] == '(': # return 2 + self.scoreOfParentheses(S[2:-2]) # else: # if len(S) == 2: # return 1 # else: # return 0 # # def isValid(self, s): # """ # :type s: str # :rtype: bool # """ # a = {')': '(', ']': '[', '}': '{'} # l = [None] # for i in s: # if i in a and a[i] == l[-1]: # l.pop() # else: # l.append(i) # return len(l) == 1 # # # if __name__ == '__main__': # s = Solution1() # S = '((()()))(()())' # r = s.scoreOfParentheses(S) # print(r)
import random, json, os def create_numbers_list(size, min, max, isFloat = False): numbers = [] for i in range(size): if isFloat: numbers.append(min + (random.random() * max)) else: numbers.append(random.randint(min, max)) return numbers def write_to_file(data, filename, location = ''): with open(f"{location}{filename}", "w") as f: json.dump(data, f) def load_file(filename, location=''): with open(f"{location}{filename}", 'r') as f: return json.load(f) def selection_sort(values): sorted_list = [] for i in range(0, len(values)): index_to_move = index_of_min(values) sorted_list.append(values.pop(index_to_move)) return sorted_list def index_of_min(values): min_index = 0 for i in range(1, len(values)): if values[i] < values[min_index]: min_index = i return min_index numbers = None if os.path.exists('./numbers-10k.json'): print('loading...') numbers = load_file('numbers-10k.json') else: numbers = create_numbers_list(10000, 0, 100, True) # print('numbers = {0}'.format(numbers)) # dict = None # if os.path.exists: dict = load_file('test.json') # print('dict["test"] = {0}'.format(dict['test'])) # write_to_file({"test": 123, "test2": 321}, 'test.json') # numbers = create_numbers_list(1000, 0, 100, True) # write_to_file(numbers, 'numbers-1k.json') # print(selection_sort(numbers)) # print('sorted = {0}'.format(sorted))
def recursive_binary_search(list, target): #returns true or false if target exists in list #list must be sorted for this to work if len(list) == 0: return False middleIndex = len(list) // 2 #get the value at middleIndex middleValue = list[middleIndex] #check if middleValue is target and return middleIndex if true print('middleValue = {0}'.format(middleValue)) if list[len(list) // 2] == target: return True sub_list = list[middleIndex + 1:] if middleValue > target: sub_list = list[:middleIndex] return recursive_binary_search(sub_list , target)
# app/schema/hash.py # Password encryption from passlib.context import CryptContext pwd_ctx = CryptContext(schemes=["bcrypt"], deprecated="auto") class Hash: """Helps to hash and verifying passwords using multiple algorithms.""" @staticmethod def bcrypt(password: str) -> str: """Encrypts the password entered by the user. Args: password (str): Password entered by the user. Returns: str: Hashed password. """ return pwd_ctx.hash(password) def verify(hashed_password: str, plain_password: str) -> bool: """Check if the hashed password matches the entered password. Args: hashed_password (str): Hashed password. plain_password (str): Password entered by the user. Returns: bool: True if there is a match but False. """ return pwd_ctx.verify(plain_password, hashed_password)
# !/usr/bin/env python """ Provides the gcd and s, t of Euclidian algorithim for a given m, n The algorithim states that the GCD of 2 numbers is equal to a product of the one of the numbers and a coefficient, s added with the product of the remaining number and a coefficient, t. """ def gcd(m,n,buffer): """Returns the GCD through recursion, and the quotient buffer""" if ((m % n) == 0): return n else: buffer.append(-1*(m // n)) return gcd(n, (m % n), buffer) def euclid(s,t,buffer): """ Returns s and t after recursion """ if (len(buffer) == 0): return s,t else: t1 = s + t * buffer[len(buffer)-1] del buffer[len(buffer)-1] return euclid(t, t1, buffer) def fn(m,n): """ Initilizes, and prints, the GCD and S and T values""" buffer = [] if (m > n): large = m small = n gcd_ = gcd(m,n,buffer) else: large = n small = m gcd_ = gcd(n,m,buffer) s_t = euclid(1, buffer[len(buffer)-1], buffer[:len(buffer)-1]) print("The GCD is {:d}".format(gcd_)) if (s_t[0] > s_t[1]): print("{:d} = {:d} * {:d} - {:d} * {:d}".format( gcd_, s_t[0], large, -1*s_t[1], small)) else: print("{:d} = {:d} * {:d} - {:d} * {:d}".format( gcd_, s_t[1], small, -1*s_t[0], large)) if (large == m): print("S is {:d} and T is {:d}".format(s_t[0], s_t[1])) else: print("S is {:d} and T is {:d}".format(s_t[1], s_t[0])) UserInput1 = int(input("Enter a pair of numbers: \n")) UserInput2 = int(input()) fn(UserInput1,UserInput2) input("Press enter to quit")
''' A Convolutional Network implementation example using TensorFlow library. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/) Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ ''' from __future__ import print_function import numpy as np import tensorflow as tf import scipy.io as sio import matplotlib as plt sess = tf.InteractiveSession() # Import MNIST data #from tensorflow.examples.tutorials.mnist import it_data #mnist = input_data.read_data_sets("tmp/data/MNIST/", one_hot=True) train_location ='Data/train.mat' test_location = 'Data/test.mat' def load_train_data(): train_dict = sio.loadmat(train_location) X = np.asarray(train_dict['X']) X_train = [] for i in range(X.shape[3]): X_train.append(X[:,:,:,i]) X_train = np.asarray(X_train)/255.0 Y_train = train_dict['y'] for i in range(len(Y_train)): if Y_train[i]%10 == 0: Y_train[i] = 0 Y_train = tf.one_hot(Y_train,10) Y_train=tf.reshape(Y_train,[73257,10]) return (X_train,Y_train) def load_test_data(): test_dict = sio.loadmat(test_location) X = np.asarray(test_dict['X']) X_test = [] for i in range(X.shape[3]): X_test.append(X[:,:,:,i]) X_test = np.asarray(X_test)/255.0 Y_test = test_dict['y'] for i in range(len(Y_test)): if Y_test[i]%10 == 0: Y_test[i] = 0 Y_test = tf.one_hot(Y_test,10) Y_test=tf.reshape(Y_test,[26032,10]) return (X_test,Y_test) X_train, Y_train = load_train_data() X_test,Y_test=load_test_data() # Parameters learning_rate = 0.001 training_iters = 200000 batch_size = 50 display_step = 10 # Network Parameters # MNIST data input (img shape: 28*28) n_classes = 10 # MNIST total classes (0-9 digits) dropout = 0.5 # Dropout, probability to keep units # tf Graph input x = tf.placeholder(tf.float32, [None, 32,32,3]) #定义一个占位符 代表一种数据 y = tf.placeholder(tf.float32, [None, n_classes]) keep_prob = tf.placeholder(tf.float32) #dropout (keep probability) # Create some wrappers for simplicity def conv2d(x, W, strides=1): # Conv2D wrapper, with bias and relu activation x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') # x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def avgpool2d(x, k=2): # MaxPool2D wrapper return tf.nn.avg_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='VALID') # Create model def conv_net(x, weights,dropout): # Reshape input picture x = tf.reshape(x, shape=[-1, 32, 32, 3]) # Convolution Layer conv1 = conv2d(x, weights['wc1']) # Max Pooling (down-sampling) conv1 = avgpool2d(conv1, k=2) # Convolution Layer conv2 = conv2d(conv1, weights['wc2']) # Max Pooling (down-sampling) conv2 = avgpool2d(conv2, k=2) # Fully connected layer # Reshape conv2 output to fit fully connected layer input fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.matmul(fc1, weights['wd1']) fc1 = tf.nn.relu(fc1) # Apply Dropout fc1 = tf.nn.dropout(fc1, dropout) # Output, class prediction #out = tf.add(tf.matmul(fc1, weights['out']), biases['out']) out=tf.matmul(fc1,weights['out']) return out # Store layers weight & bias weights = { # 5x5 conv, 1 input, 32 outputs 'wc1': tf.Variable(tf.truncated_normal([5, 5, 3, 32],stddev=0.1)), # 5x5 conv, 32 inputs, 64 outputs 'wc2': tf.Variable(tf.truncated_normal([5, 5, 32, 64],stddev=0.1)), # fully connected, 7*7*64 inputs, 1024 outputs 'wd1': tf.Variable(tf.truncated_normal([8*8*64, 1024],stddev=0.1)), # 1024 inputs, 10 outputs (class prediction) 'out': tf.Variable(tf.truncated_normal([1024, n_classes],stddev=0.1)) } a = tf.Variable(tf.truncated_normal([1,1])) '''biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'out': tf.Variable(tf.random_normal([n_classes])) }''' # Construct model pred = conv_net(x, weights,keep_prob) # Define loss and optimizer #交叉熵 一种表达两个向量之间差距的的指标 #reduce_mean:Computes the mean of elements across dimensions of a tensor. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) #亚当算法 一种基于梯度下降的优化算法 但比较稳定 optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Evaluate model #argmax()返回最大值的索引 #correct_pred是一个一维的只有true or false的序列 correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Initializing the variables init = tf.global_variables_initializer() # Launch the graph with tf.Session() as sess: sess.run(init) current = 0; y_train = sess.run(Y_train) y_test = sess.run(Y_test) for i in range(1): if (current >= 73200): batch_data = X_train[current:current + 56, :, :, :] batch_label = y_train[current:current + 56, :] current = 0 else: batch_data = X_train[current:current + 50, :, :, :] batch_label = y_train[current:current + 50, :] current = current + 50 if i % 100 == 0: train_accuracy = accuracy.eval(feed_dict={ x: batch_data, y: batch_label, keep_prob: 1.0}) print("step %d, training accuracy %g" % (i, train_accuracy)) sess.run(optimizer, feed_dict={x: batch_data, y: batch_label, keep_prob: dropout}) WC1 = weights['wc1'].eval() WC2 = weights['wc2'].eval() WD1 = weights['wd1'].eval() OUT = weights['out'].eval() sio.savemat("W_conv1.mat", mdict={'W_conv1': WC1}) sio.savemat("W_conv2.mat", mdict={'W_conv2': WC2}) sio.savemat("W_fc1.mat", mdict={'W_fc1': WD1}) sio.savemat("W_fc2.mat", mdict={'W_fc2': OUT}) test_x = X_test[1:1000, :, :, :] test_y = y_test[1:1000, :] print("test accuracy %g" % accuracy.eval(feed_dict={x: test_x, y: test_y, keep_prob: 1.0}))
#Sequal DB information ''' This is the file that configures the sqlite DB to store high scores. This file is only run once to construct the SQL DB ''' import sqlite3 database_file = "score_db.db" #You can write raw SQL as a string sql_create_scores_table = ("""CREATE TABLE IF NOT EXISTS high_scores ( id integer PRIMARY KEY, user text NOT NULL, score integer NOT NULL );""") fakeNames = [("TPH", 0),("TPH", 0),("TPH", 0),("TPH", 0),("TPH", 0),("TPH", 0),("TPH", 0),("TPH", 0),("TPH", 0),("TPH", 0)] #Create a connection with database conn = sqlite3.connect(database_file) c = conn.cursor() #Execute that raw SQL c.execute(sql_create_scores_table) print "Sucessfully created new database." #Adding Fake data c.executemany("INSERT INTO high_scores(user, score) VALUES (?,?)",fakeNames) print "Fake users added successfully. " conn.commit() conn.close()
import sqlite3 class DictDB(): def __init__(self, filename="devild.db"): self.createDB(filename) def createDB(self, filename="devild.db"): self.conn = sqlite3.connect(filename) self.cur = self.conn.cursor() self.cur.executescript(''' CREATE TABLE IF NOT EXISTS Dict ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT, pos TEXT, mean TEXT, ex TEXT ); ''') def insertWord(self, name, pos, meaning, example): self.cur.execute('''INSERT OR IGNORE INTO Dict (name, pos, mean, ex) VALUES (?, ?, ?, ?)''', (name, pos, meaning, example)) self.conn.commit() def searchWord(self, searchTerm="", tags=["name"]): self.cur.execute("SELECT * from Dict ORDER BY name") if searchTerm != "": self.cur.execute(f"""SELECT * from Dict WHERE LOWER(name) LIKE '%{searchTerm.lower()}%' ORDER BY name""") return self.cur.fetchall() def getOneWord(self, prop="id", value=0): self.cur.execute(f"SELECT * from Dict WHERE {prop} = ?", (value,)) return self.cur.fetchone() def deleteWord(self, prop="id", value=0): self.cur.execute(f"DELETE from Dict WHERE {prop} = ?", (value,)) self.conn.commit() def updateWord(self, with_prop, with_value, where_prop="id", where_value=0): if type(with_prop) == str and type(with_value) == str: self.cur.execute( f"UPDATE Dict SET {with_prop} = ? WHERE {where_prop} = ?", (with_value, where_value)) self.conn.commit() else: if len(with_prop) != len(with_value): print("Length of with_prop and with_value are not same") return for i in range(len(with_prop)): self.updateWord( with_prop[i], with_value[i], where_prop, where_value) def closeDB(self): self.conn.close()
s = input() if(len(s) >= 6 and s[2] == s[3] and s[4] == s[5]): print('Yes') else: print('No')
#coding: UTF-8 import sys class Algo: @staticmethod def greatest_common_divisor(x, y): while True: r = x%y if r==0: print(y) break x, y = y, r l = list(map(int, input().split())) X = l[0] Y = l[1] Algo.greatest_common_divisor(X, Y)
import sys N = int(input()) S = input() for s in S: if s == 'Y': print('Four') sys.exit() print('Three')
nums = input().split() a = int( nums[0]) b = int( nums[1]) c = int( nums[2]) if a > b: tmp = a a = b b = tmp if b > c: tmp = b b = c c = tmp if a > b: tmp = a a = b b = tmp print( a, b, c)
import math N=int(input()) a=math.ceil(N/(1.08)) if math.floor(a*1.08)==N: print(a) else: print(':(')
n = int(input()) count = 0 for i in range(n + 1): if i % 2 != 0: count += 1 print(float(count / n))
class Digraph: #入力定義 def __init__(self,vertex=[]): self.vertex=set(vertex) self.edge_number=0 self.vertex_number=len(vertex) self.adjacent_out={v:{} for v in vertex} #出近傍(vが始点) self.adjacent_in={v:{} for v in vertex} #入近傍(vが終点) #頂点の追加 def add_vertex(self,*adder): for v in adder: if v not in self.vertex: self.adjacent_in[v]={} self.adjacent_out[v]={} self.vertex_number+=1 self.vertex.add(v) #辺の追加(更新) def add_edge(self,From,To,weight=1): for v in [From,To]: if v not in self.vertex: self.add_vertex(v) if To not in self.adjacent_in[From]: self.edge_number+=1 self.adjacent_out[From][To]=weight self.adjacent_in[To][From]=weight #辺を除く def remove_edge(self,From,To): for v in [From,To]: if v not in self.vertex: self.add_vertex(v) if To in self.adjacent_out[From]: del self.adjacent_out[From][To] del self.adjacent_in[To][From] self.edge_number-=1 #頂点を除く def remove_vertex(self,*vertexes): for v in vertexes: if v in self.vertex: self.vertex_number-=1 for u in self.adjacent_out[v]: del self.adjacent_in[u][v] self.edge_number-=1 del self.adjacent_out[v] for u in self.adjacent_in[v]: del self.adjacent_out[u][v] self.edge_number-=1 del self.adjacent_in[v] #Walkの追加 def add_walk(self,*walk): pass #Cycleの追加 def add_cycle(self,*cycle): pass #頂点の交換 def __vertex_swap(self,p,q): self.vertex.sort() #グラフに頂点が存在するか否か def vertex_exist(self,v): return v in self.vertex #グラフに辺が存在するか否か def edge_exist(self,From,To): if not(self.vertex_exist(From) and self.vertex_exist(To)): return False return To in self.adjacent_out[From] #近傍 def neighbohood(self,v): if not self.vertex_exist(v): return [] return list(self.adjacent[v]) #出次数 def out_degree(self,v): if not self.vertex_exist(v): return 0 return len(self.adjacent_out[v]) #入次数 def in_degree(self,v): if not self.vertex_exist(v): return 0 return len(self.adjacent_in[v]) #次数 def degree(self,v): if not self.vertex_exist(v): return 0 return self.out_degree(v)-self.in_degree(v) #頂点数 def vertex_count(self): return len(self.vertex) #辺数 def edge_count(self): return self.edge_number #頂点vを含む連結成分 def connected_component(self,v): pass #Warshall–Floyd def Warshall_Floyd(D): """Warshall–Floyd法を用いて,全点間距離を求める. D:負Cycleを含まない有向グラフ """ T={v:{} for v in D.vertex} #T[u][v]:uからvへ for u in D.vertex: for v in D.vertex: if v==u: T[u][v]=0 elif v in D.adjacent_out[u]: T[u][v]=D.adjacent_out[u][v] else: T[u][v]=float("inf") for u in D.vertex: for v in D.vertex: for w in D.vertex: T[v][w]=min(T[v][w],T[v][u]+T[u][w]) return T #================================================ from itertools import permutations N,M,R=map(int,input().split()) Y=list(map(int,input().split())) D=Digraph(list(range(1,N+1))) for _ in range(M): a,b,c=map(int,input().split()) D.add_edge(a,b,c) D.add_edge(b,a,c) Dist=Warshall_Floyd(D) Z=float("inf") for P in permutations(Y): X=0 for i in range(R-1): X+=Dist[P[i]][P[i+1]] Z=min(Z,X) print(Z)
input_line = input().split() if int(input_line[0]) + int(input_line[1]) + int(input_line[2]) != 17: print("NO") pass elif input_line[0] == input_line[1] == "5": print("YES") pass elif input_line[1] == input_line[2] == "5": print("YES") pass elif input_line[0] == input_line[2] == "5": print("YES") else: print("NO")
def bubbleSort(n,A): flag = True cnt = 0 while flag: flag = False for j in range(n-1, 0, -1): if A[j-1] > A[j]: A[j-1],A[j] = A[j],A[j-1] cnt += 1 flag = True print(*A) print(cnt) if __name__ == '__main__': N = int(input()) A = list(map(int,input().split())) bubbleSort(N, A)