blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
8a56bdf0bd3b0ac390c9af5809e7378c9faf1283
glbter/kpi-computing
/algorithms_theory/binary_tree_linked_list.py
5,366
3.8125
4
class Tree: def __init__(self): self.root = None def add(self, elem): newNode = Tree.TreeNode(elem) if self.root == None: self.root = newNode else : current = self.root prev = current while current != None : prev = current if len(elem) < current.value: current = current.left elif len(elem) > current.value : current = current = current.right elif len(elem) == current.value : current.innerList.add(elem) return current = prev if len(elem) < current.value : current.left = newNode else : current.right = newNode def remove(self, elem): if self.root == None: return else: current = self.root while current != None : if len(elem) < current.value : current = current.left elif len(elem) > current.value : current = current = current.right elif len(elem) == current.value: current.innerList.remove(elem) return def find(self, elem) : if self.root == None: print("not found") return None else : current = self.root while current != None : if len(elem) < current.value: current = current.left elif len(elem) > current.value : current = current = current.right elif len(elem) == current.value : return current.innerList.find(elem) print("not found") return None def inOrderTraversal(self, root): if root != None: self.inOrderTraversal(root.left) root.innerList.listTraversal() self.inOrderTraversal(root.right) def strucktureTraverse(self): self.inOrderTraversal(self.root) class TreeNode: def __init__(self, value): self.value = len(value) self.innerList = Tree.LinkedList() self.innerList.add(value) self.right = None self.left = None class LinkedList: def __init__(self): self.first = None class LLNode(): def __init__(self, value): self.value = value self.next = None def listTraversal(self): current = self.first while current : print(current.value) current = current.next def add(self, elem): #elem -> new value of list newNode = Tree.LinkedList.LLNode(elem) if self.first == None : self.first = newNode elif elem < self.first.value : tmp = self.first self.first = newNode self.first.next = tmp else : current = self.first prev = current while elem > current.value and current.next != None : prev = current current = current.next if elem <= current.value : oldNext = prev.next prev.next = newNode newNode.next = oldNext elif current.next == None : current.next = newNode def find(self,elem): current = self.first while elem != current.value and current.next != None : current = current.next if current == None : print("not found") return None elif elem == current.value : return current def remove(self,elem): current = self.first if current == None : return if elem == current.value : self.first = current.next else : while elem != current.next.value \ and current.next.next != None : current = current.next if elem == current.value : current.next = current.next.next if elem == current.next.value : current.next = None def test(): tree = Tree() tree.add("wow") tree.add("hel") tree.add("hello world") tree.add("tree works") tree.add("list works too") tree.add("lol") tree.add("kek") tree.strucktureTraverse() tree.remove("wow") tree.remove("hello world") tree.remove("hel") print("") tree.strucktureTraverse() print(tree.find("kek")) tree.add("ab") tree.add("aa") tree.add("ae") tree.add("ad") tree.add("ac") tree.strucktureTraverse() print("") print(tree.find("kek").value) print(tree.find("aa").value) test()
bf82af4eec931bcad6e329fb79f28ac03c2fa529
JMcWhorter150/python_grocery_list
/grocery_list.py
1,221
4.09375
4
# reused functions def make_grocery_list(): groceries = [] while True: user_input = input('What do you need from the grocery store? ') if user_input == '': break else: groceries.append(user_input) return groceries def print_grocery_list(grocery_list): for i in range(len(groceries)): print(f'{i}: {groceries[i]}') # make and print groceries groceries = make_grocery_list() print_grocery_list(groceries) is_replacing_groceries = input('Do you want to replace any items? (Y/n)') if is_replacing_groceries == "Y" or is_replacing_groceries == "": start = int(input('From which index do you want to replace? ')) end = int(input('To what index do you want to replace? ')) if end - start > 0: new_groceries = make_grocery_list() groceries[start : end + 1] = new_groceries # + 1 because slicing does not include end number print_grocery_list(groceries) elif end - start == 0: new_input = input('What do you need from the grocery store? ') groceries[start] = new_input print_grocery_list(groceries) else: print('Invalid number range') else: print('Enjoy shopping!')
d4b95201fead3666539f9b9dea049aaca630e5cf
prashantpandey9/codesseptember2019-
/hackerearth/number_pattern.py
111
3.578125
4
d=int(input()) for k in range(d,1,-1): for kk in range(d,1,-1): print(k,end='') print("")
b0ae99a1defe08ad10fa8feca0adc0967ba859b4
Full-Stack-Artisan/LeeLeeCoCo
/002_346_moving_average_from_data_stream/py_code_2.py
635
3.8125
4
from collections import deque class MovingAverage: def __init__(self, size: int): """ Initialize your data structure here. """ self._queue = deque() self._sum = 0 self._size = size def next(self, val: int) -> float: if len(self._queue) == self._size: el = self._queue.popleft() self._sum -= el self._queue.append(val) self._sum += val return self._sum /len(self._queue) # Your MovingAverage object will be instantiated and called as such: # obj = MovingAverage(size) # param_1 = obj.next(val)
fca95ab6866c297c2dd575206614ec748e8f1c9d
agzimmerman/darts-and-prime-numbers
/darts_and_prime_numbers.py
2,964
3.90625
4
''' This script answers a question that came up while playing darts at Sowieso the other night. Someone observed that, when you look at any two adjacent sections, their number very often summed to prime numbers. We counted nine. I suppose I should double check that number on a standard dart board found on the internet, and put that here. But for now the question is: Is this actually unusual? If someone were to place the numbers at random, then, on average, how many adjacent pairs would sum to prime numbers? *** SPOILER ALERT!!! *** Unless there is a mistake in this script (which is quite likely), the expected value is six, but the variance is four, so the observed count on a standard dart board is within two standard deviations, and therefore not so remarkable. The minimums and maximums are quite interesting. Here is a sample output: Samples Mean Var Min Max 100 6.090 3.982 2 12 1000 6.035 4.194 0 14 10000 5.918 4.040 0 14 100000 5.896 4.023 0 16 1000000 5.894 4.028 0 16 Tested on... Python 2.7.12 :: Anaconda custom (64-bit) Python 2.7.6 ''' import random import math import numpy ''' This is a function for checking if a number is prime, found at https://stackoverflow.com/questions/18833759/python-prime-number-checker''' def is_prime(n): if n % 2 == 0 and n > 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) ''' A dart board is divided into twenty sections, each with a unique number from 1 to 20 Achtung! This can lead to confusion in this script, because we index the sections from 0 to 19.''' section_count = 20 numbers = range(1, section_count + 1) ''' We employ the Monte Carlo integration method to estimate the expected value of the number of ajacted pairs that sum to a prime number. ''' large_number = 1000000 report_at = (100, 1000, 10000, 100000, 1000000) prime_counts = [] ''' Run the Monte Carlo loop ''' print(" Samples Mean Var Min Max") for sample in range(1, large_number + 1): random.shuffle(numbers) # This randomizes the order of the list of numbers, modifying the list in place ''' Count the adjacted pairs that sum to prime numbers ''' prime_count = 0 for section in range(section_count): adjacent_section = (section + 1)%(section_count - 1) # Handle the periodic boundary condition if is_prime(numbers[section] + numbers[adjacent_section]): prime_count += 1 prime_counts.append(prime_count) ''' Update the expected value, and report it regularly to check for convergence ''' if sample in report_at: print " %7d %6.3f %6.3f %3d %3d" % (sample, numpy.mean(prime_counts), numpy.var(prime_counts), numpy.min(prime_counts), numpy.max(prime_counts))
7615b4cd331d617c5e52ca40bd5490aeeb279125
StevenCM199/Introduccion-a-la-programacion
/Recursion de cola/divide3.py
490
3.984375
4
#Recibir un numero y eliminar los digitos divisibles entre 3 def divide3 (num): if isinstance(num,int): return divide3_aux(num,0,0) else: return "Error: el número no es un entero" def divide3_aux(num,resultado,pot): if (num == 0): return resultado elif (num%10) % 3 == 0: return divide3_aux(num//10, resultado, pot) else: return divide3_aux(num//10, resultado+num%10*(10**pot),pot+1)
21a43144a7759af3bc15df40b278359f71845762
JeIIicoe/Python-Testing
/tests/test.py
535
3.71875
4
def tester(a, b) : print( 'Addition:\t' , a , '+' , b , '=' , a + b ) print( 'Subtraction:\t' , a , '-' , b , '=' , a - b ) print( 'Multiplication:\t' , a , 'x' , b , '=' , a * b ) print( 'Division:\t' , a , '/' , b , '=' , a / b ) print( 'Floor Division:\t' , a , '//' , b , '=' , a // b ) print( 'Modulos:\t' , a , '%' , b , '=' , a % b ) print( 'Exponent:\t ' , a , '² = ' , a ** 2 , sep = '') a = int(input("What do you want your first number to be: ")) b = int(input("Second number: ")) tester(a, b)
dd2914d92e26e4c13a239be931f2df76cf47d36c
f-fathurrahman/ffr-komputasi-material
/autoforce/util_flake.py
1,705
3.890625
4
# + import numpy as np from numpy.linalg import norm def generate_random_cluster(n, d, dim=3): """ Generates a random cluster of n points such that all nearest neighbor distances are equal to d. n: number of points d: nearest neighbor distances dim: Cartesian dimensions """ def random_unit_vector(dim=3): u = np.random.uniform(-1., 1., size=dim) u /= norm(u) return u c = np.zeros((1, dim)) for _ in range(1, n): # u: random direction u = random_unit_vector(dim) # p: projection of all points on u-axis p = (u*c).sum(axis=1) # first collision -> x*u s = np.argsort(p)[::-1] for j, k in enumerate(s): # y: min distance of point k from u-axis y = norm(c[k]-p[k]*u) if y <= d: x = p[k] + np.sqrt(d**2-y**2) break # check the distance with other nearby points for k in s[j:]: if x-p[k] > d: break # y: distance of point k with the new point (x*u) y = norm(c[k]-x*u) if y < d: z = norm(c[k]-p[k]*u) x = p[k] + np.sqrt(d**2-z**2) # append x*u to the cluster c = np.r_[c, x*u.reshape(1, dim)] return c def test_generate_random_cluster(n=1000, d=1., dim=3): cls = generate_random_cluster(n, d, dim=dim) dmat = np.linalg.norm(cls[None]-cls[:, None], axis=-1) # replace diganal zeros with a large number dmat += np.eye(n)*(dmat.max() + 1.) dmin = dmat.min(axis=1) return np.allclose(dmin, d) if __name__ == '__main__': assert test_generate_random_cluster()
2d68b383821e1686239563cfaf38ff143ea8d135
ConorODonovan/online-courses
/Udemy/Python/Complete Python Bootcamp/Blackjack/Blackjack_deck_class.py
684
3.546875
4
''' Deck class ''' class Deck: def __init__(self, suits, ranks): from Blackjack_card_class import Card self.deck = [] for suit in suits: for rank in ranks: self.deck.append(Card(suit, rank)) def __str__(self): deck_str = "" for i in self.deck: if i != self.deck[-1]: deck_str += str(i) + ", " else: deck_str += str(i) return deck_str def get_deck_as_list(self): return self.deck def shuffle_deck(self): import random random.shuffle(self.deck) return self.deck
c63b3c7e7567e42926e12e151171ce70fff95620
alexshacked/algorithms
/data_structures/disjoint_set.py
1,389
3.703125
4
class DisjointSet: def __init__(self): self.forest = {} def makeSet(self, x): exist = self.forest.has_key(x) if not exist: self.forest[x] = {'parent': x, 'rank': 0} def find(self,x): exist = self.forest.has_key(x) if not exist: return None if self.forest[x]['parent'] != x: self.forest[x]['parent'] = self.find(self.forest[x]['parent']) return self.forest[x]['parent'] def union(self, x, y): xroot = self.find(x) yroot = self.find(y) if xroot == yroot: return if self.forest[xroot]['rank'] < self.forest[yroot]['rank']: self.forest[xroot]['parent'] = yroot elif self.forest[xroot]['rank'] > self.forest[yroot]['rank']: self.forest[yroot]['parent'] = xroot else: self.forest[yroot]['parent'] = xroot self.forest[xroot]['rank'] = self.forest[xroot]['rank'] + 1 if __name__ == '__main__': set = DisjointSet() set.makeSet(1) set.makeSet(2) set.makeSet(3) set.makeSet(4) set.makeSet(5) set.makeSet(6) set.makeSet(7) set.makeSet(8) set.union(1, 2) set.union(2, 5) set.union(5, 6) set.union(6, 8) set.union(3, 4) print set.find(1) == set.find(8) print set.find(1) == set.find(7) print 'finished'
b17846518551748c8daa4978e35141eb20b1e0e8
asettouf/projectEuler
/pb50.py
1,366
3.859375
4
import math def constructListOfPrime(lim): pp = 2 ps = [pp] toAdd = False while pp < lim: pp += 1 toAdd = True for a in ps: if a > math.sqrt(pp): break if pp%a == 0: toAdd = False break if toAdd: ps.append(pp) return ps def lengthSumOfPrime (primeList, prime): temp = 0 count = 0 #print primeList for pp in primeList: #print temp temp+= pp count+= 1 if temp == prime: #print prime return count if temp > prime: break return 0 SIZE_PRIME = 1000000 def findLongestLength(): primeList = constructListOfPrime(SIZE_PRIME) #print primeList max = 0 counter = 1 for i in primeList[len(primeList) - 1000 : -1]: for j in range(0,counter): liTmp = primeList[j:counter] if (len(liTmp) < max +1): break buff = lengthSumOfPrime(liTmp, i) if buff > max: print i #print max #print i res = i max = buff counter += 1 return res print str(findLongestLength()) #Not a good script, execution time is too long if we check everything, #thus we select an arbitrary subset of all primes that contains one prime at least #under the (correct) assumption that the function that returns the max length #is always growing, simply meaning that a subset containing at least the last value correct #that is a prime which is a sum of consecutive primes, returns the correct result
40b6ba1c4aa3e5d7ba46325aa7654b1ee65c9bbe
tanuja333/ML_Training
/ML_Simplilearn/example_exercise_simple_linear_regression_TaxiFare_forDemoV1.py
1,412
3.921875
4
# Simple Linear Regression """ Created on Wed May 9 06:59:15 2018 @author: Shivendra This is Simple Linear Model illustration code for ML training """ # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Now, Lets import the data set # Read from data file # slice the input and output data # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split distance_points_train, distance_points_test, fare_train, fare_test = train_test_split(distance, fare, test_size = 0.33, random_state = 0) # Fitting Simple Linear Regression Model to the taxi fare training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(distance_points_train, fare_train) # Predicting the Test set results #fare_pred = # Visualising the Training set results plt.scatter(distance_points_train, fare_train, color = 'red') plt.plot(distance_points_train, regressor.predict(distance_points_train), color = 'blue') plt.title('Distance Vs fare (Training set)') plt.xlabel('Dsitance') plt.ylabel('Fare') plt.show() # Visualising the Test set results plt.scatter(distance_points_test, fare_test, color = 'red') plt.plot(distance_points_test, regressor.predict(distance_points_test), color = 'blue') plt.title('Distance Vs Fare(Test set)') plt.xlabel('Distance') plt.ylabel('Fare') plt.show()
e1cd9a3bb927d66c65566077cdd5de543f7b50b9
CircleZ3791117/CodingPractice
/source_code/LC10_RegularExpressionMatch.py
2,991
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'CZ' """ Description: Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like . or *. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Example 3: Input: s = "ab" p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)". Example 4: Input: s = "aab" p = "c*a*b" Output: true Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab". Example 5: Input: s = "mississippi" p = "mis*is*p*." Output: false """ class Solution: # Recursive method def isMatch(self, s: str, p: str) -> bool: if not p: return not s # first match first_match = bool(s) and p[0] in [s[0], '.'] if len(p) >= 2 and p[1] == '*': return self.isMatch(s, p[2:]) or first_match and self.isMatch(s[1:], p) else: return first_match and self.isMatch(s[1:], p[1:]) def isMatch2(self, s: str, p: str) -> bool: memo = {} def dp(i, j): if (i, j) not in memo: if j == len(p): ans = i == len(s) else: first_match = i < len(s) and p[j] in [s[i], '.'] if j + 1 < len(p) and p[j + 1] == '*': ans = dp(i, j + 2) or first_match and dp(i + 1, j) else: ans = first_match and dp(i + 1, j + 1) memo[i, j] = ans return memo[i, j] return dp(0, 0) def isMatch3(self, s, p): # define dp matrix dp = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)] dp[0][0] = True j = 1 while j < len(p): if p[j] == '*': dp[0][j+1] = True else: break j += 2 i = 1 while i < len(s) + 1: j = 1 while j < len(p) + 1: if p[j-1] == s[i-1] or p[j-1] == '.': dp[i][j] = dp[i-1][j-1] elif p[j-1] == '*': if p[j-2] == s[i-1] or p[j-2] == '.': dp[i][j] = dp[i-1][j] or dp[i][j-2] else: dp[i][j] = dp[i][j-2] else: dp[i][j] = False j += 1 i += 1 return dp[len(s)][len(p)]
cac1ec82a0a207a3184cc3d0873741dd6a451bb6
imnikkiz/Interfaces-and-Main-Loops
/arithmetic.py
566
3.9375
4
def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): a = float(num1) b = float(num2) return a / b def square(num1): return num1 * num1 def cube(num1): return num1 * num1 * num1 def power(num1, num2): return num1 ** num2 def mod(num1, num2): return num1 % num2 operators = { "+": add, "-": subtract, "*": multiply, "/": divide, "square": square, "cube": cube, "pow": power, "mod": mod }
4ae85640c5bf96a7cce955efcf5370624771f2c4
immuno121/Contactless_Sensing
/LSTM.py
14,252
4
4
# -*- coding: utf-8 -*- r""" Sequence Models and Long-Short Term Memory Networks =================================================== At this point, we have seen various feed-forward networks. That is, there is no state maintained by the network at all. This might not be the behavior we want. Sequence models are central to NLP: they are models where there is some sort of dependence through time between your inputs. The classical example of a sequence model is the Hidden Markov Model for part-of-speech tagging. Another example is the conditional random field A recurrent neural network is a network that maintains some kind of state. For example, its output could be used as part of the next input, so that information can propogate along as the network passes over the sequence. In the case of an LSTM, for each element in the sequence, there is a corresponding *hidden state* :math:`h_t`, which in principle can contain information from arbitrary points earlier in the sequence. We can use the hidden state to predict words in a language model, part-of-speech tags, and a myriad of other things. LSTM's in Pytorch ~~~~~~~~~~~~~~~~~ Before getting to the example, note a few things. Pytorch's LSTM expects all of its inputs to be 3D tensors. The semantics of the axes of these tensors is important. The first axis is the sequence itself, the second indexes instances in the mini-batch, and the third indexes elements of the input. We haven't discussed mini-batching, so lets just ignore that and assume we will always have just 1 dimension on the second axis. If we want to run the sequence model over the sentence "The cow jumped", our input should look like .. math:: \begin{bmatrix} \overbrace{q_\text{The}}^\text{row vector} \\ q_\text{cow} \\ q_\text{jumped} \end{bmatrix} Except remember there is an additional 2nd dimension with size 1. In addition, you could go through the sequence one at a time, in which case the 1st axis will have size 1 also. Let's see a quick example. """ # Author: Robert Guthrie import torch import torch.nn as nn import torch.utils.data import torch.nn.functional as F import torch.optim as optim #import torchvision #import torchvision.transforms as transforms import csv import numpy as np import torchvision from torchvision import transforms from logger import Logger torch.manual_seed(1) ###################################################################### ''' lstm = nn.LSTM(3, 3) # Input dim is 3, output dim is 3 inputs = [torch.randn(1, 3) for _ in range(5)] # make a sequence of length 5 # initialize the hidden state. hidden = (torch.randn(1, 1, 3), torch.randn(1, 1, 3)) for i in inputs: # Step through the sequence one element at a time. # after each step, hidden contains the hidden state. out, hidden = lstm(i.view(1, 1, -1), hidden) # alternatively, we can do the entire sequence all at once. # the first value returned by LSTM is all of the hidden states throughout # the sequence. the second is just the most recent hidden state # (compare the last slice of "out" with "hidden" below, they are the same) # The reason for this is that: # "out" will give you access to all hidden states in the sequence # "hidden" will allow you to continue the sequence and backpropagate, # by passing it as an argument to the lstm at a later time # Add the extra 2nd dimension inputs = torch.cat(inputs).view(len(inputs), 1, -1) hidden = (torch.randn(1, 1, 3), torch.randn(1, 1, 3)) # clean out hidden state out, hidden = lstm(inputs, hidden) print(out) print(hidden) ''' # Here we define our model as a class #############Define Variables######################################## input_size=1 hidden_size=64 output_dim=1 num_layers=3 num_epochs=75 learning_rate=1 #sequence_length = 1021 #1021#number of samples the network will see? # best = 5 # overfit = 50 batch_size = 1 test_batch_size=1#57#=seq_length #57 ####################--------------------############################# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') cuda = True ###################Loading the Data############################### ################################ filename='seq_length_1000.csv' ################################# x_train=[] y_train=[] with open(filename,'r') as csvfile: csv_reader=csv.reader(csvfile,delimiter=',') for row in csv_reader: #print('row',len(row)) #print('row-before',len(row)) row=[x for x in row if x!=''] x_train.append(row[2:-1])# first 2 columns are not required- patient id and posture y_train.append(row[-1]) #print('row-after',len(row)) ''' since we cannot convert a variable length list to a numpy array, we keep out input as list. Hence since it is diifcult to slice over the 2nd dimension of the list, we remove first 2 column before appending. ''' #print((x_train[0][0])) #print((y_train[0])) x_train=x_train[1:] #first row is headings.so avoid it. y_train=y_train[1:] #print((y_train[0])) #print((x_train[0][0])) #y_train=x_train[:,-1]# last column is y labels. #y_train=np.expand_dims(y_train,axis=1)#126X1 #x_train=x_train[:,:-1]# remove the last column from #126X1021 ''' There are a total of 126X1021=128,646 data points. experiment 1: seq length=6. Thus we reshape x_train to 21441X6 ''' #num_samples=int(((x_train.shape[0]*x_train.shape[1])/sequence_length)) #print(num_samples) #x_train=np.reshape(x_train,(num_samples,sequence_length)) #print(len(x_train[9])) #print(len(y_train)) #x_train=np.expand_dims(x_train,axis=2) #print(x_train.shape)#126X1021== NXTXD #x_train=x_train.astype(np.float64) x_train=[[float(val) for val in sublist ] for sublist in x_train ] y_train=[float(val) for val in y_train ] y_train=np.array(y_train) y_train=np.expand_dims(y_train,axis=1)#126X1 y_train=y_train.tolist() #temp=np.array(x_train[0]) #print(temp.shape) #print((y_train[0][:])) #print(len(y_train[0])) x_test=x_train y_test=y_train ##############################XXXXXXXXXXXXXXX######################### #######################Data Loaders################################## #print(x_train.shape) #print(y_train.shape) #print(x_train) class TrainDataset(torch.utils.data.Dataset): def __init__(self): self.len_dataset = len(x_train)#126 def __getitem__(self,index): #Convert to tensor #print(y_train.shape) #print(index) #self.x_train_tensor = torch.from_numpy(x_train[index,:]).to(device) #x_train=np.array(x_train[index]) self.x_train_tensor = torch.FloatTensor(x_train[index][:]).to(device) #self.x_train_tensor = self.x_train_tensor.float() self.y_train_tensor = torch.FloatTensor(y_train[index][:]).to(device) #raw/filtered #self.y_train_tensor = torch.from_numpy(y_train[index]).to(device) #raw/filtered #self.y_train_tensor = self.y_train_tensor.float() return self.x_train_tensor, self.y_train_tensor def __len__(self): return self.len_dataset class TestDataset(torch.utils.data.Dataset): def __init__(self): self.len_dataset = len(x_test)# 70#1200#570 def __getitem__(self,index): #Convert to tensor #self.x_test_tensor = torch.from_numpy(x_test[index,:]).to(device) self.x_test_tensor = torch.FloatTensor(x_test[index][:]).to(device) #self.x_test_tensor = self.x_test_tensor.float() #self.y_test_tensor = torch.from_numpy(y_test[index,:]).to(device) self.y_test_tensor = torch.FloatTensor(y_test[index][:]).to(device) #raw/filtered #self.y_test_tensor = self.y_test_tensor.float() #print(self.y_test_tensor.shape,'y_test_tensor') return self.x_test_tensor, self.y_test_tensor def __len__(self): return self.len_dataset #objects to dataset classes train_dataset = TrainDataset() test_dataset = TestDataset() #Initializing the dataloaders train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=False) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=test_batch_size, shuffle=False) ###########################-------------############################## class LSTM(nn.Module): def __init__(self, input_size, hidden_size, batch_size, output_size=1, num_layers=2): super(LSTM, self).__init__() self.input_size = input_size# 1 self.hidden_size = hidden_size self.batch_size = batch_size self.num_layers = num_layers#2 # Define the LSTM layer self.lstm = nn.LSTM(self.input_size, self.hidden_size, self.num_layers) # Define the output layer self.linear = nn.Linear(self.hidden_size, output_size) def forward(self, x): # Forward pass through LSTM layer # shape of lstm_out: [seq_length, batch_size, hidden_dim] # shape of self.hidden: (a, b), where a and b both # have shape (num_layers, batch_size, hidden_dim). h0 = torch.zeros(self.num_layers, self.batch_size, self.hidden_size).to(device) #2 for bidirectional c0 = torch.zeros(self.num_layers, self.batch_size, self.hidden_size).to(device) #shape of x: (seq_len, batch, input_size) lstm_out, _ = self.lstm(x,(h0,c0)) #out: tensor of shape ( seq_length, batch_size, hidden_size) # Only take the output from the final timestep # Can pass on the entirety of lstm_out to the next layer if it is a seq2seq prediction #lstm_out=lstm_out[-1,:,:] #lstm_out=np.expand_dims(lstm_out,axis=0) #print('henlo',lstm_out.shape) y_pred = self.linear(lstm_out[-1,:,:])#1Xbatch_sizeXhidden_size--> 1Xbatch_sizeXoutput_size[which is 1] #print('henlo',y_pred.shape) return y_pred#1 model = LSTM(input_size, hidden_size, batch_size, output_dim, num_layers) #model.load_state_dict(torch.load('lstm_seq_length_50.pth')) loss_fn = torch.nn.L1Loss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) ##########tensorboard################################################ logger = Logger('./logs/run8') ##################-------------### # Print model's state_dict print("Model's state_dict:") for param_tensor in model.state_dict(): print(param_tensor, "\t", model.state_dict()[param_tensor].size()) ##################### # Train model ##################### total_step = len(train_loader) for epoch in range(num_epochs): for i, (data,labels) in enumerate(train_loader):#data will be 1021, and label=1, #print(epoch) #data = data.reshape(-1, sequence_length, input_size).to(device) #() #print(data[0]) #print(labels.shape) sequence_length=data.shape[1] #print('data.shape',data.shape[1]) data = data.reshape(sequence_length,-1, input_size).to(device) #() #labels = labels.reshape(-1, sequence_length, num_classes).to(device)#() labels = labels.reshape(-1, output_dim).to(device)#() #print(data.shape) #print(labels.shape) # data=data.float() labels = labels.float() #Forward Pass outputs = model(data) #print(outputs.shape) #print(outputs[:]) #print(labels[:]) loss = loss_fn(outputs, labels[:,:]) #Backward and optimize optimizer.zero_grad() loss.backward() optimizer.step() #if (i+1) % 2000== 0: print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.9f}' .format(epoch+1, num_epochs, i+1, total_step, loss.item())) # ================================================================== # # Tensorboard Logging # # ================================================================== # # 1. Log scalar values (scalar summary) info = { 'loss': loss.item() } for tag, value in info.items(): logger.scalar_summary(tag, value, epoch+1) # 2. Log values and gradients of the parameters (histogram summary) for tag, value in model.named_parameters(): tag = tag.replace('.', '/') logger.histo_summary(tag, value.data.cpu().numpy(), epoch+1) logger.histo_summary(tag+'/grad', value.grad.data.cpu().numpy(), epoch+1) # 3. Log training images (image summary) ''' info = { 'images': images.view(-1, 28, 28)[:10].cpu().numpy() } for tag, images in info.items(): logger.image_summary(tag, images, epoch+1) ''' #Saving the model torch.save(model.state_dict(),'lstm_seq_length_50.pth') ## sequence leghts differ #========================================================= ########### INERTIA NETWORK TEST ############ #========================================================= model.load_state_dict(torch.load('lstm_seq_length_50.pth')) with torch.no_grad(): correct = 0 total = 0 total_error=0 true_total_error = 0 for i,(test_data, labels) in enumerate(test_loader): test_sequence_length=test_data.shape[1] test_data = test_data.reshape(test_sequence_length, -1, input_size).to(device) labels = labels.reshape(-1, output_dim).to(device) #true_labels = true_labels.reshape(-1, test_sequence_length, num_classes).to(device) outputs = model(test_data) error=torch.sum((abs(outputs-labels))) #mean squared error #error = torch.sum(torch.abs(outputs-labels)) #mean absolute error total_error+=error.data total+=labels.size(1) print(error.data) print(total_error, 'total_error') print(total, 'total') print('mean absolute error',total_error/total) #print('Test Accuracy of the model: {} %'.format(error / total))
ac13b247ea8616ade8f45c400c426d94e90e403e
memling/TomaszMering_python
/2.5_Pozdrawiacz.py
276
3.515625
4
# Program 'Pozdrawiacz' # Demonstruje użycie zmiennej # (Z książki "Python dla każdego" Michaela Dawsona, wydawnictwo Helion) # Python 3.7.1 name = "Ludwik" print(name) print("Cześć,", name, ".") input("\n\nAby zakończyć program, naciśnij klawisz Enter.")
26516fcb9df9de26469719c7e48d391f6d1b7fc2
Yang-Jianlin/python-learn
/LeetCode/T-2.py
1,216
3.796875
4
from LeetCode.链表排序 import CreateLink from LeetCode.链表排序 import LinkNode class Solution: def addTwoNumbers(self, l1, l2): newlink = LinkNode(None) new_l1 = l1.next new_l2 = l2.next num_l1 = 0 num_l2 = 0 i = 1 j = 1 while new_l1: num_l1 = num_l1 + new_l1.element * i i *= 10 new_l1 = new_l1.next while new_l2: num_l2 = num_l2 + new_l2.element * j j *= 10 new_l2 = new_l2.next num_sum = num_l1 + num_l2 num = list(str(num_sum)) for i in num: node = LinkNode(int(i)) node.next = newlink.next newlink.next = node return newlink def print_node(node): new_head = node while new_head.next: print(new_head.next.element, end='-->') new_head = new_head.next print('None') if __name__ == '__main__': link1 = CreateLink() link2 = CreateLink() nums1 = [2, 4, 3] nums2 = [5, 6, 4] for i in nums1: link1.add_tail(i) for j in nums2: link2.add_tail(j) s = Solution() print_node(s.addTwoNumbers(link1.head, link2.head))
7ea38af0a77efcf35d4709e86251693dc8e9e1ea
ymeysa25/Python
/Password Generator/app.py
3,809
3.71875
4
# Import Suitable Library import string import random from tkinter import * from tkinter import messagebox from PIL import ImageTk from PIL import Image # Declare CONSTANT VARIABLE LETTERS = string.ascii_letters NUMBERS = string.digits PUNCTUATION = string.punctuation # ================================== Function Block ====================================== def password_generator_bychoice(choice_list, length=8): ''' User can choose password character combination which could either be digits, letters, punctuation or combibation of either of them. :returns list <class 'list'> of boolean. Defaults to [True, True, True] for invalid choice 0th list item represents NUMBERS 1st list item represents LETTERS 2nd list item represents PUNCTUATION ''' string_constant = "" string_constant += NUMBERS if choice_list[0] else '' string_constant += LETTERS if choice_list[1] else '' string_constant += PUNCTUATION if choice_list[2] else '' # convert string_constant from string to list and shuffle string_constant = list(string_constant) random.shuffle(string_constant) try: # generate random password and convert to string random_password = random.choices(string_constant, k=length) random_password = ''.join(random_password) except: random_password = "Select Checkbox" return random_password def press(): ''' Function that will be used when Generate button is clicked ''' # Collect all Var from CheckBox into a List choice_list = [bool(_number.get()), bool(_letter.get()), bool(_punctuation.get()) ] # when length is '', length for password generator will be default if entry.get() == '': label['text'] = password_generator_bychoice(choice_list) # Entry Input is Digit elif entry.get().isdigit(): # Get Entry Value length = int(entry.get()) # Set Label Text to password generator return label['text'] = password_generator_bychoice(choice_list, length) # Entry Input is not Digit else: messagebox.showinfo("Warning", "Length in Numbers Only") def checkbutton(app, text, var): c = Checkbutton(app, text= text, variable= var) return c def imageopen(path, size = (30,30)): img = Image.open(path) img.thumbnail(size, Image.ANTIALIAS) return img # ======================================== END ====================================== # ============================= Adding Window Components =========================== app = Tk() app.title("Password Generator") app.iconbitmap("password.ico") _number = IntVar() _letter = IntVar() _punctuation = IntVar() # ======================================== END ====================================== # ==================================== Main Design ================================== label = Label(app, text = "Max Length") label.grid(column = 1) entry = Entry(app , font=("Calibri",20),justify="right") entry.grid(row = 1, columnspan = 3, ipadx=5, ipady = 5) cb_letter = checkbutton(app, "Number", _number) cb_letter.grid(row = 2, column = 0) cb_string = checkbutton(app, "Letter", _letter) cb_string.grid(row = 2, column = 1) cb_punctuation = checkbutton(app, "Punctuation", _punctuation) cb_punctuation.grid(row = 2, column = 2) button = Button(app, text = "Generate", command = lambda : press()) button.grid(row = 3, column = 1) label = Label(app, text = "Hasil", font = 20) label.grid(row = 4, column = 1) copy_logo = ImageTk.PhotoImage(imageopen("copy.png")) button = Button(app, image = copy_logo, command = lambda : copyToClipBoard()) button.grid(row = 4, column = 2) app.mainloop() # ======================================== END ======================================
4028a5460c0035becbe6e07b2124c25e44f17917
whdesigns/Python3
/1-basics/2-guis/1-classes-and-objects/Grid-Intro/DropDown-Menu/bot.py
952
4.21875
4
from tkinter import * # | CREATING DROP DOWN MENUS | def doNothing(): print("ok ok I won't...") root = Tk() menu = Menu(root) root.config(menu=menu) #States that we're setting up a menu and its equal the variable declared above. subMenu = Menu(root) menu.add_cascade(label="File", menu=subMenu) # This is the name of the file e.g. "File" and "submenu" is where it will be placed. subMenu.add_command(label="New Project...", command=doNothing) subMenu.add_command(label="New...", command=doNothing) # Adding another item to the menu. subMenu.add_separator() # This will create a lines to separate one group of items from another e.g. much like \n. subMenu.add_command(label="Exit", command=doNothing) editMenu = Menu(menu) # Creating another item in the main menu menu.add_cascade(label="Edit", menu=editMenu) # Naming the drop down menu editMenu.add_command(label="Redo", command=doNothing) # Naming the item inside the menu root.mainloop()
efc08c013e87c66de4bb57df3e5e42800573bef4
un4ckn0wl3z/pythonpract
/advance_buit-in/any_and_all.py
615
3.984375
4
friends = [ { "name": "Anuwat", "location": "Nakhon Si Thammarat" }, { "name": "Pansa", "location": "Chonburi" }, { "name": "Surachad", "location": "Phattalung" }, { "name": "Chaiyapat", "location": "Phuket" } ] your_location = input("Where are right now? ") friends_nearby = [friend for friend in friends if friend['location'] == your_location] if any(friends_nearby): print("You are not alone!") """ * 0, 0.0 * None, * [], (), {} * False """ if all([1,2,3,0,5,6]): print('True') else: print('False')
620b25ea4f1c0a0f76a5c5c6959b906688065cc8
greenteawarrior/blackjack
/blackjack_func.py
6,809
3.84375
4
import random #emilywang #softdes spring 2013 #functional programming #blackjack #making a deck def makedeck(howmanydecks=1): deck = [] #initial value of deck #an element of deck... [name of suit, [name of card, vlaue of card]] # [string, [string, integer]] #each element of the name lists is.. [name of thingy is a string, its value is an integer] suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names = [['Ace', 1], ['2', 2], ['3', 3], ['4', 4], ['5', 5], ['6', 6], ['7', 7], ['8', 8], ['9', 9], ['10', 10], ['Jack', 10], ['Queen', 10], ['King', 10]] #rank_name_dictionary = {'Ace':1, '2':2....} n = 0 #initial value for how many decks you want to make in this pile while n < howmanydecks: for suit in suit_names: some_suit = [] for rank in rank_names: some_suit.append([suit, rank]) deck.append(some_suit) #print (some_suit) n += 1 print ("This contains " + str((len(deck)/4)) + " decks.") return deck #a list def bj_move (deck, person, currenttotal, decision): if person == 'player': if decision == 'hit': print () print ('Hit!') playercard = random.choice(random.choice(deck)) playercardname = str(playercard[1][0]) + ' of ' + playercard[0] print ('You got a ' + playercardname) newtotal = currenttotal + playercard[1][1] print ('You now have a hand of ' + str(newtotal) + '.') return newtotal if decision == 'stand': print () print ('Stand!') print ('As promised, you still have a hand of ' + str(currenttotal) + ".") return currenttotal if person == 'dealer': if decision == 'stand': print ("The dealer must stand.") return currenttotal else: print ("The dealer shall hit.") dealercard = random.choice(random.choice(deck)) newtotal = currenttotal + dealercard[1][1] return newtotal def takingturns(deck, current, currenttotal): if current == 'player': print () print ("Now, what will you do- hit or stand? A 'hit' is to take another card in hopes of getting closer but not exceeding 21. A 'stand' is to do nothing in hopes that you'll beat the dealer with your current hand. Choose wisely.") decision = str(input("Type 'hit' or 'stand' into the computer.")) currenttotal = bj_move (deck, current, currenttotal, decision) return currenttotal, decision if current == 'dealer': print () print ("Dealer's turn!") if currenttotal >= 17: decision = 'stand' if currenttotal <= 16: decision = 'hit' currenttotal = bj_move (deck, current, currenttotal, decision) return currenttotal, decision def game_over(playerturn, dealerturn): #unpacking the variables playercurrenttotal = playerturn[0] playerchose = playerturn[1] dealercurrenttotal = dealerturn[0] dealerchose = dealerturn[1] gameovermessage = ('\n' + "Game over." + '\n' + "Dealer hand total:" + str(dealercurrenttotal) + '\n' + "Your hand total: " + str(playercurrenttotal)) if playerchose == 'hit': if playercurrenttotal == 21: if dealercurrenttotal == 21: print (gameovermessage) print ("Both you and the dealer win. How fortuitous! (or maybe not). Play again?") return if dealercurrenttotal < 21: print (gameovermessage) print ("Nice hand! Sir, you are victorious.") return if playercurrenttotal < 21 and dealercurrenttotal == 21: print (gameovermessage) print ("Sir, you have lost. Dealer got a hand of 21 before you did. Play again?") return if playercurrenttotal > 21: print (gameovermessage) print ("Bust! Sir, you have lost. Play again?") return if dealercurrenttotal > 21: print (gameovermessage) print ("Dealer bust! Sir, you are victorious.") return else: return False if playerchose == 'stand': if playercurrenttotal < 21 and dealercurrenttotal == 21: print (gameovermessage) print ("Sir, you have lost. Dealer got a hand of 21.") return if playercurrenttotal == 21 and dealercurrenttotal == 21: print (gameovermessage) print ("Both you and the dealer win. How fortuitous! (or maybe not). Play again?") return if playercurrenttotal < 21 and dealercurrenttotal > 21: print (gameovermessage) print ("Dealer bust! Sir, you are victorious.") return if playercurrenttotal == dealercurrenttotal: print (gameovermessage) print ("Looks like a tie. Play again?") return if dealerchose == 'stand': if playercurrenttotal < dealercurrenttotal: print (gameovermessage) print ("Alas and alack, the dealer wins. Play again?") return if playercurrenttotal > dealercurrenttotal: print (gameovermessage) print ("Sir, you are victorious!") return else: return False else: return False else: return False def blackjacking (): deck = makedeck(4) #this game is using 4 decks! print () welcome = """Hi there! Let's play Blackjack! No money bets though! By the way, an Ace is worth 1 in this particular program.""" print (welcome) print () startnow = str(input("Press y if you'd like to begin.")) if startnow == 'y': print () print ("Yay, let's play! The goal is to have a hand which is higher than the dealer's but does not exceed 21. Now let's see...") print () print ("These are your cards (and the sum if you're too lazy to add).") playercard1 = random.choice(random.choice(deck)) playercard1name = str(playercard1[1][0]) + ' of ' + playercard1[0] playercard2 = random.choice(random.choice(deck)) playercard2name = str(playercard2[1][0]) + ' of ' + playercard2[0] playercurrenttotal = playercard1[1][1]+playercard2[1][1] print ("Card 1: " + playercard1name) print ("Card 2: " + playercard2name) print ("Current total: " + str(playercurrenttotal)) print () dealercard1 = random.choice(random.choice(deck)) dealercard1name = str(dealercard1[1][0]) + ' of ' + dealercard1[0] dealercard2 = random.choice(random.choice(deck)) dealercard2name = str(dealercard1[1][0]) + ' of ' + dealercard1[0] dealercurrenttotal = dealercard1[1][1]+dealercard2[1][1] print ("You're allowed to see one of the dealer's cards.") print ("Dealer's card: " + dealercard1name) # #player's first turn after deal # playerturn = takingturns (deck, 'player', playercurrenttotal) # #dealer's first turn after deal # dealerturn = takingturns (deck, 'dealer', dealercurrenttotal) # checkpoint = game_over(playerturn, dealerturn) # # print ("checkpoint is:") # # print (checkpoint) checkpoint = False while checkpoint == False: playerturn = takingturns (deck, 'player', playercurrenttotal) dealerturn = takingturns (deck, 'dealer', dealercurrenttotal) checkpoint = game_over(playerturn, dealerturn) else: #the person didn't type y to start the game. print ("Invalid key press. Restart the program if you'd like to play!") blackjacking()
ba4873664408a1df566cb43bd606471e0e3d4271
ychalier/dice
/dice/misc/progress_bar.py
2,521
4.09375
4
import threading import queue import time class ProgressThread(threading.Thread): """ Basic utility to show progress over an iterative task. """ def __init__(self, q, total): super().__init__() self.q = q self.total = total self.current = 0 def run(self): start = time.time() while True: try: while True: self.current = self.q.get(block=False) except queue.Empty: pass elapsed = time.time() - start if self.current == self.total or self.current is None: break remaining = (float(self.total) * elapsed / (self.current + 1))\ - elapsed if self.current == 0: print("\rProgress: {} ({}%) | Elapsed: {} | Remaining: {}" .format(self.current, int(100 * float(self.current) / self.total), time.strftime("%H:%M:%S", time.gmtime(elapsed)), "--:--:--"), end="") else: print("\rProgress: {} ({}%) | Elapsed: {} | Remaining: {}" .format(self.current, int(100 * float(self.current) / self.total), time.strftime("%H:%M:%S", time.gmtime(elapsed)), time.strftime("%H:%M:%S", time.gmtime(remaining))), end="") print("\rProgress: {} (100%) | Elapsed: {} | Remaining: 00:00:00" .format( self.total, time.strftime("%H:%M:%S", time.gmtime(elapsed)))) class ProgressBar(): def __init__(self, total): self.current = 0 self.q = queue.Queue() self.thread = ProgressThread(self.q, total) def start(self): return self.thread.start() def increment(self): self.update(self.current + 1) def update(self, current): self.current = current self.q.put(current) def stop(self): self.q.put(None) self.thread.join() def iterate(iterable, callback, msg=None, length=None): if length is None: length = len(iterable) bar = ProgressBar(length) if msg is not None: print(msg) bar.start() for item in iterable: callback(item) bar.increment() bar.stop()
63e5790860586d29346a835dc01dc8db49978825
junjiegithub/test001
/20220927/break01.py
341
3.765625
4
#break:当某些条件成立,退出整个循环 #循环吃5个苹果,吃完第3个吃饱了,第四个和第5个不吃了(不执行) --==4或>3 i=1 while i<=5: #条件:如果吃到4或>3打印吃饱了,不吃了 if i==4: print('吃饱了,不吃了') break print(f'吃了第{i}个苹果') i+=1
e592f0dfd12297e08989f05a44367e8d26ed13fa
Peter1509/Homework05
/Homework_05/PostsDefault_table.py
611
3.53125
4
from smartninja_sql.sqlite import SQLiteDatabase db = SQLiteDatabase("BlogDB_main.sqlite") db.execute("""CREATE TABLE IF NOT EXISTS Posts_Default( PostDefaultId integer primary key autoincrement, PostName text, PostText text); """) postname = "Hallo an Alle" posttext = "Grüße aus Walhalla. Wer hat noch lust auf eine Schlacht?" db.execute(""" INSERT INTO POSTS_DEFAULT (PostName, PostText) VALUES (?, ?) """, (postname, posttext)) db.pretty_print ("SELECT * FROM POSTS_DEFAULT")
5dc186a389b17d25fee07aaf000c3b5c22aab5aa
Aasthaengg/IBMdataset
/Python_codes/p02627/s933475021.py
68
3.796875
4
a=input() if('a'<=a and 'z'>=a): print('a') else: print('A')
39f584038856a18d6928acc63a7c53db93142b64
xmaseve/Lambda
/lambda.py
466
4.09375
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 04 20:32:29 2016 @author: YI """ #the usage of lambda list1=[1,2,6,4] list2=[3,4,2,6] data=zip(list1,list2) #data sorted by the first element of the tuple data.sort() #output: [(1, 3), (2, 4), (4, 6), (6, 2)] #sort by the second element data.sort(key=lambda x: x[1]) #output: [(6, 2), (1, 3), (2, 4), (4, 6)] #parallel sorting data.sort() list1, list2 = map(lambda x: list(x), zip(*data))
3ccaf2b37b094fc6081ee9563edc5c8c3dd2ff23
Ti1mmy/ICS-201
/Loops 1/Loops 1 - 1.py
544
4.5625
5
# Create a program that will ask the user for a word. The program will iterate through the string and print out each character except for the vowels. word = input('Please type in a word: ') # vowels = ['A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u'] # doesn't work for replace(), therefore used string include_y = input('Consider y a vowel? (y/n): ') if include_y != 'y': vowels = 'aeiouAEIOU' else: vowels = 'aeiouyAEIOUY' for char in vowels: word = word.replace(char, "") for character in word: print(character)
e861625fc7b2bf67b92d898041d31b20d82a84be
JeaneC/jsnake
/snake.py
2,416
3.5625
4
import pygame from pygame.sprite import Sprite from pygame.sprite import Group from turnPoint import TurnPoint class Snake(Sprite): """A class to represent the snake""" def __init__(self, ai_settings, screen, stats): """Initialize thhe snake.""" super(Snake, self).__init__() self.screen = screen self.screen_rect = screen.get_rect() # Screen's rectangle self.ai_settings = ai_settings self.stats = stats self.rect = pygame.Rect(self.ai_settings.screen_width/2, self.ai_settings.screen_height/2, ai_settings.snake_width, ai_settings.snake_height) self.center = self.rect.centerx self.y = self.rect.y # Testing these variables out self.color = self.ai_settings.jred self.length = self.stats.score self.head = False self.head2 = False self.lock = False self.end = False self.moving_right = False self.moving_left = False self.moving_down = False self.moving_up = False # Create it's turn points self.turnPoints = Group() def blitme(self): """Draw the snake""" self.screen.fill(self.color, self.rect) def stop(self): self.moving_right = self.moving_left = self.moving_down = self.moving_up = False def update(self): """Update snake's position""" if self.moving_right and self.rect.right < self.screen_rect.right: self.center += self.ai_settings.snake_speed_factor elif self.moving_left and self.rect.left > 0: self.center -= self.ai_settings.snake_speed_factor elif self.moving_up and self.rect.y > 0: self.y -= self.ai_settings.snake_speed_factor elif self.moving_down and self.rect.y < self. ai_settings.screen_height - 20: self.y += self.ai_settings.snake_speed_factor self.rect.centerx = self.center self.rect.y = self.y def direction(self): if self.moving_right: print("Right") elif self.moving_left: print("Left") elif self.moving_up: print("Up") elif self.moving_down: print("Down") else: print("Not moving") def updateBody(self): for x in range(0, self.length + 1): print(5)
c85c222303954ec3605c30ef6f266c6a4f5ff8c0
amartini93/materia_python
/Actividades/AC04/13622625_AldoMartini.py
2,260
4.09375
4
# coding=utf-8 # Completen los métodos # Les estamos dando un empujoncito con la lectura del input # Al usar la clausula: "with open('sonda.txt', 'r') as f", el archivo se cierra automáticamente al salir de la función. def sonda(): list_minerals = [] dict_minerals = {} with open('sonda.txt', 'r') as f: for line in f: list_minerals.append(line.replace('\n', '').split(',')) key = '' for i in list_minerals[:][]: if i != '[' and i != ']': key += str(i) key += ',' print(key) # for mineral in list_minerals: # dict_minerals[mineral[0:-1]] = mineral[-1] # print(dict_minerals) # n_questions = int(input('Cuantas veces consultara coordenadas?')) # for question in range(n_questions): # coordenates = input('Ingrese las coordenadas separadas por comas: ') # coordenates = coordenates.split(',') # for key, value in dict_minerals.items(): # print(key, value, coordenates) # if key == coordenates: # print(value) ## no me esta funcionando porque reemplazo el value, etnoces pierdo algunos minerales, pero aveces coincide y corre. ## voy a seguir con lo otro def traidores(): with open('bufalos.txt', 'r') as f: b_list = set() for line in f: line = line.replace('\n', '') b_list.add(line) with open('rivales.txt', 'r') as f: t_list = set() for line in f: line = line.replace('\n', '') t_list.add(line) print(t_list.intersection(b_list), 'Son unos traidores, asesinenlos!!') def pizzas(): with open('pizza.txt', 'r') as f: for line in f.read().splitlines(): pass if __name__ == '__main__': exit_loop = False functions = {"1": sonda, "2": traidores, "3": pizzas} while not exit_loop: print(""" Elegir problema: 1. Sonda 2. Traidores 3. Pizzas Cualquier otra cosa para salir Respuesta: """) user_entry = input() if user_entry in functions: functions[user_entry]() else: exit_loop = True
a4781c4e37baa74bd08c8879903e4431e3b2c598
minwiley/sqlalchemy_SurfsUp-
/app_mw.py
4,822
3.5625
4
# Step 2 - Climate App # Now that you have completed your initial analysis, design a Flask API based on the queries that you have just developed. # Use FLASK to create your routes. # Dependencies import numpy as np import pandas as pd import datetime as dt import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from sqlalchemy import create_engine, func, inspect, desc from flask import Flask, jsonify engine = create_engine("sqlite:///Resources/hawaii.sqlite") # reflect an existing database into a new model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) Base.classes.keys() # Save references to each table Measurement = Base.classes.measurement Station = Base.classes.station session = Session(engine) # R&R dates 11/1/18-11/15/18 - 15 days inspector = inspect(engine) inspector.get_table_names() inspector = inspect(engine) columns = inspector.get_columns('station') for c in columns: print(c['name'], c['type']) inspector = inspect(engine) columns = inspector.get_columns('measurement') for c in columns: print(c['name'], c['type']) # Query All Records in the the Database data_station = engine.execute("SELECT * FROM station") for record_stat in data_station: print(record_stat) # Query All Records in the the Database data_measurement = engine.execute("SELECT * FROM measurement LIMIT 25") for record_measure in data_measurement: print(record_measure) app = Flask(__name__) @app.route("/") def home(): print("Server received request for 'Home' page.") return ( f'Now entering the Surfs Up Weather API!<br/><br/>' f'Available Endpoints<br/><br/>' f'/api/v1.0/precipitation ' f'<a href="/api/v1.0/precipitation">/api/v1.0/precipitation<a/><br/><br/>' f'/api/v1.0/stations ' f'<a href="/api/v1.0/stations">/api/v1.0/stations<a/><br/><br/>' f'/api/v1.0/tobs ' f'<a href="/api/v1.0/tobs">/api/v1.0/tobs<a/><br/><br/>' f'/api/v1.0/<start> ' f'<a href="/api/v1.0/<start>">/api/v1.0/<start><a/><br/><br/>' f'/api/v1.0/<start>/<end> ' f'<a href="/api/v1.0/<start>/<end>">/api/v1.0/<start>/<end><a/>' ) # Routes # /api/v1.0/precipitation # Convert the query results to a Dictionary using date as the key and prcp as the value.Return the JSON representation of your dictionary. @app.route("/api/v1.0/precipitation") def precipitation(): results_dacp = session.query(Measurement.date, Measurement.prcp).filter(Measurement.date >= "2016-08-24").\ group_by(Measurement.date).all() precip_list = [results_dacp] return jsonify(precip_list) # /api/v1.0/stations # Return a JSON list of stations from the dataset. @app.route("/api/v1.0/stations") def stations(): station_list = session.query(Measurement.station).all() station_lists = list(np.ravel(station_list)) return jsonify(station_lists) # /api/v1.0/tobs # query for the dates and temperature observations from a year from the last data point. Return a JSON list of Temperature Observations (tobs) for the previous year. @app.route("/api/v1.0/tobs") def tobs(): results_tob = session.query(Measurement.tobs).filter(Measurement.date >= "2016-08-24").all() tobs_list = [results_tob] return jsonify(tobs_list) # /api/v1.0/<start> and /api/v1.0/<start>/<end> # Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range. When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date. # When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive. @app.route('/api/v1.0/<start>', methods=["GET"]) def start_stats(start=None): results = session.query(func.min(Measurement.tobs), func.max(Measurement.tobs),func.avg(Measurement.tobs)).\ filter(Measurement.date >= start).all() weather_stats = [] for Tmin, Tmax, Tavg in results: weather_stats_dict = {} weather_stats_dict["Minimum Temperature"] = Tmin weather_stats_dict["Maximum Temperature"] = Tmax weather_stats_dict["Average Temperature"] = Tavg weather_stats.append(weather_stats_dict) return jsonify(weather_stats) @app.route("/api/v1.0/<start>/<end>", methods=["GET"]) def calc_stats(start=None, end=None): results = session.query(func.min(Measurement.tobs), func.max(Measurement.tobs),func.avg(Measurement.tobs)).\ filter(Measurement.date >= start).filter(Measurement.date <= end).all() start_end = [] for Tmin, Tmax, Tavg in results: start_end_dict = {} start_end_dict["Minimum Temperature"] = Tmin start_end_dict["Maximum Temperature"] = Tmax start_end_dict["Average Temperature"] = Tavg start_end.append(start_end) return jsonify(start_end) if __name__ == "__main__": app.run(debug=True)
62a3ca2fe58422f0481cf19512042382a40f40e6
vaishnavinambiar/Function-abstraction-exercises
/tc_factorial.py
355
3.578125
4
import unittest def recur_factorial(n): if n ==1: return n else: return n*recur_factorial(n-1) class MyTest(unittest.TestCase): def test1_fact(self): self.assertEqual(recur_factorial(5), 120) def test2_fact(self): self.assertEqual(recur_factorial(2), 3) if __name__ == '__main__': unittest.main()
98976316c5a937d6343f7c162d9976886d9e5fa9
eshatwo/Python
/python_OOP/car.py
1,044
3.71875
4
class Car: def __init__(self, price, speed, fuel, milaege): self.price = price self.speed = speed self.fuel = fuel self.milaege = milaege self.tax = 0 def taxing(self): if self.price > 10000: self.tax = 0.15 else: self.tax = 0.12 return self def display_all(self): disp = { "Price" : self.price, "Speed" : self.speed, "Fuel" : self.fuel, "Milaege" : self.milaege, "Tax" : self.tax } print(disp) return self car1 = Car(2000, "35mph", "Full", "15mpg") car2 = Car(2000, "5mph", "Not Full", "105mpg") car3 = Car(2000, "15mph", "Kind of Full", "95mpg") car4 = Car(2000, "25mph", "Full", "25mpg") car5 = Car(2000, "45mph", "Empty", "25mpg") car6 = Car(20000000, "35mph", "Empty", "15mpg") car1.taxing().display_all() car2.taxing().display_all() car3.taxing().display_all() car4.taxing().display_all() car5.taxing().display_all() car6.taxing().display_all()
9a153b22783fe79ca672f9658752297d489c47c8
brat-chndr2001/pythonproject
/Order Details(Pricing)/orderdetails.py
1,777
4.21875
4
print("CHOOSE YOUR FAVOURITE RESTAURANT") print("----------------------") print("The list of reataurants are:") print("1) Khana khajana") print("2) Olive garden") print("3) Karachi darbar") x = input("Choose your desired restaurant number: ") if x == "1": print("The meals in the restaurant are :") print("1) Hyderabadi Chicken Biryani") print("2) Mushroom Munchurian") print("3) Brownie") a = input("Choose your desired dish number you want to order: ") if a == "1": print("The price of Hyderabadi Chicken Biryani:- Rs 250 ") elif a == "2": print("The price of Mushroom Munchurian:- Rs 175") elif a == "3": print("The price of Brownie:- Rs 100") elif x == "2": print("The meals in the restaurant are :") print("1) Chicken Fried rice") print("2) French Fries") print("3) Chocolate Ice Cream") b = input("Choose your desired dish number you want to order: ") if b == "1": print("The price of Chicken Fried rice:- Rs 180") elif b == "2": print("The price of French Fries:- Rs 110") elif b == "3": print("The price of Chocolate Ice Cream:- Rs 80") elif x == "3": print("The meals in the restaurant are :") print("1) Butter Nun") print("2) Dal Makhani") print("3) Kulfi") c = input("Choose your desired dish number you want to order: ") if c == "1": print("The price of Butter Nun:- Rs 35") elif c == "2": print("The price of Dal Makhani:- Rs 150") elif c == "3": print("The price of Kulfi:- Rs 50") print("\nThanks a lot for choosing our restaurent , we hope you enjoy the food and visit again.") print("------------------------------------------------------------")
e7df0a1fa87b49205f84adeac3be75a2636fff0c
Helloworld616/algorithm
/SWEA/Sort/1966_숫자를정렬하자/sol5.py
820
3.78125
4
import sys sys.stdin = open('input.txt') def merge_sort(numbers): N = len(numbers) if N < 2: return numbers mid_idx = N // 2 left = numbers[:mid_idx] right = numbers[mid_idx:] sorted_left = merge_sort(left) sorted_right = merge_sort(right) merged = [] l = r = 0 while l < len(sorted_left) and r < len(sorted_right): if sorted_left[l] < sorted_right[r]: merged.append(sorted_left[l]) l += 1 else: merged.append(sorted_right[r]) r += 1 merged += sorted_left[l:] merged += sorted_right[r:] return merged T = int(input()) for tc in range(1, T+1): N = int(input()) numbers = list(map(int, input().split())) sorted_numbers = merge_sort(numbers) print(f'#{tc} {sorted_numbers}')
49739785e85560f74bf7e0560d2ee134ad2bcd38
davidsuffolk/Python-Input-Sorter
/6.1 Programming Assignment.py
2,058
4.40625
4
#File: 6.1 Programming Assignment #Name: David Suffolk #Date: April 19th, 2019 #Course: DSC510-T303 Introduction to Programming (2195-1) #Assignment Number: 6.1 #Purpose: Gather temperature inputs, validate their value, return largest, smallest, and total entries. #Create an empty list called temperatures temperatures = [] #Error Handling: function will test that input is a number. If any letters are added, the program will close def testTemperature(x): try: i = float(x) newTemp = i/1 #dividing by one to validate input is a number except: print("Invalid Entry. Please start program again.") quit() #Program will end if anything other than a number is entered #Add and check: Function that adds validated input to list and checks length of list #If temperatures list has 5 values, the loop will end def addTemperature(d): temperatures.append(int(d)) for t in temperatures: if len(temperatures) == 5: break else: #If there are less than 5 values, a new input will be asked for and the functions will run again inp = input("Please enter a temperature\n") testTemperature(inp) addTemperature(inp) #Beginning of program for User. Instructions for 5 temperatures and prompt for first input. print("The program five temperatures. Please input one at a time.\n") inp = input("Please enter a temperature\n") #calls the function that tests the input testTemperature(inp) #calls the function that adds to list and verifies list length addTemperature(inp) #converts length of full list to string for output counter = str(len(temperatures)) #sorts values into numerical order temperatures.sort() #OUTPUT TEXT print("Thank you! Here are your results.") print("Largest Temperature: " + str(temperatures[-1])) #calls last index in sorted list print("Smallest Temperature: " + str(temperatures[0])) #calls first index in sorted list print("Total Temperatures Entered: " + counter) #uses the counter variable to output number of values print(temperatures)
950dc112f5d9bf8bd07bcc1d5967a9db9d0e6595
khadkasagar662/LabExercise1
/TkinterProject/Drop down.py
360
3.8125
4
from tkinter import * root =Tk() root.title('Drop down Menu') def show(): label =Label(root, text=clicked.get()).pack() clicked =StringVar() clicked.set("Monday") drop =OptionMenu(root,clicked,"Monday","Tuesday","Wednesday","Thrusday","Friday","saturday","sunday") drop.pack() mybutton =Button(root, text="show selection", command=show).pack() mainloop()
fc45793670553a1afd0c9b465c9010a76f6f80f2
AJ228/Freshman-Immigration-coding-challenges
/Two-sum.py
1,059
3.65625
4
class Solution(object): def twoSum(self, nums, target): #Challenge parameters """ :type nums: List[int] :type target: int :rtype: List[int] """ answer = [] #Blank list to store answer indices for i in range (len(nums)-1): #Checks all combinations from nums for j in range(len(nums)): if i != j: #Makes sure element indices are not identical if nums[i] + nums[j] == target: #Appends indices to answer if numbers add to target answer.append(i) answer.append(j) if len(answer) == 2: #Stops running once answer has two elements break return(answer) #Testing if code works properly solution = Solution() print("Testing twoSum()...",end="") assert(solution.twoSum([2,7,11,15],9) == [0,1]) assert(solution.twoSum([3,2,4],6) == [1,2]) assert(solution.twoSum([3,3],6) == [0,1]) assert(solution.twoSum([2,7,11,15],22) == [1,3]) print("Passed!")
c412079838d178c42d06ff67bbdffea18141e89d
hakaorson/CodePractise
/Dynamic/backpack.py
2,168
3.53125
4
''' Lintcode https://www.lintcode.com/problem/?tag=backpack 一系列的背包问题 ''' class Solution(): def backPack_recursive(self, m, A): # 重量等于价值的背包问题,相当于背包装满问题 if m == 0 or len(A) == 0: return 0 stuff = A[0] if stuff < m: return max(self.backPack(m-A[0], A[1:])+A[0], self.backPack(m, A[1:])) else: return self.backPack(m, A[1:]) def backPack_dynamic_n_m(self, m, A): A.insert(0, 0) matrix = [[0 for j in range(m+1)] for i in range(len(A))] for i in range(1, len(A)): for j in range(1, m+1): with_stuff = matrix[i-1][j-A[i]] + \ A[i] if (j-A[i]) >= 0 else 0 without_stuff = matrix[i-1][j] matrix[i][j] = max(with_stuff, without_stuff) if matrix[i][j] == m: return m return matrix[-1][-1] def backPack_dynamic_m(self, m, A): A.insert(0, 0) matrix = [0 for i in range(m+1)] for i in range(1, len(A)): for j in range(m, 0, -1): # 动态规划的时候会受到前面的影响,这样需要从后往前面遍历 if j >= A[i]: matrix[j] = max(matrix[j], matrix[j-A[i]]+A[i]) if matrix[j] == m: # 可以提前返回 return m return matrix[-1] def backPackII(self, m, A, V): # 最普通的01背包问题 A.insert(0, 0) V.insert(0, 0) matrix = [[0 for j in range(m+1)] for i in range(len(A))] for i in range(1, len(A)): for j in range(1, m+1): with_stuff = matrix[i-1][j-A[i]]+V[i] if (j-A[i]) >= 0 else 0 without_stuff = matrix[i-1][j] matrix[i][j] = max(with_stuff, without_stuff) return matrix[-1][-1] def backPackIV(self, nums, target): pass solu = Solution() ''' result1 = solu.backPack_dynamic_m(10, [3, 4, 8, 5]) result2 = solu.backPackII(10, [2, 3, 5, 7], [1, 5, 2, 4]) ''' result4 = solu.backPackIV([2, 3, 6, 7], 7) pass
9dab4529c8aff8acf8a05eeb8b294e218980b4bb
ai-kmu/etc
/algorithm/2020/0923_Rotate_Image/myunghak.py
442
3.625
4
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ 2차원 행렬의 경우 reverse 후에 transpose하면 시계방향으로 90도 회전하는 in-place 알고리즘이 됨 """ matrix.reverse() for i in range(0,len(matrix)): for j in range(1,len(matrix[i])-i): matrix[i][i+j], matrix[i+j][i] = matrix[i+j][i], matrix[i][i+j] #transpose
70bbd2e1f1db52a069e6794d68964457bdf8ad92
QI1002/exampool
/Leetcode/145.py
2,620
3.640625
4
#145. Binary Time Postorder Traversal class stack: def __init__(self): self.body = [] def push(self, data): self.body.append(data) def pop(self): if (len(self.body) == 0): return None else: return self.body.pop() def isEmpty(self): return True if len(self.body) == 0 else False class tree: def __init__(self, data, left = 0, right = 0): self.data = data self.left = left self.right = right def show(self): s = stack() s.push(self) while(not s.isEmpty()): l = r = None n = s.pop() if (n.left != 0): s.push(n.left) l = n.left.data if (n.right != 0): s.push(n.right) r = n.right.data print((n.data, l, r)) def getTreePreorder(head): s = stack() result = [] n = head while(True): while(n != 0): s.push(n) n = n.left if (s.isEmpty()): break n = s.pop() result.append(n.data) n = n.right return result def getTreePostorder2(head): if (head == 0): return [] a = getTreePostorder(head.left) b = getTreePostorder(head.right) c = list(a) c.extend(b) c.append(head.data) return c def getTreePostorder(head): s = stack() ss = stack() if (head == 0): return [] s.push(head) while(not s.isEmpty()): n = s.pop() ss.push(n.data) if (n.right != 0): s.push(n.right) else: ss.push([]) if (n.left != 0): s.push(n.left) else: ss.push([]) while(len(ss.body) >= 3): b = ss.pop() a = ss.pop() c = ss.pop() if (type(b) != list or type(a) != list or type(c) != int): ss.push(c) ss.push(a) ss.push(b) break d = list(a) d.extend(b) d.append(c) ss.push(d) return ss.pop() def genBinaryTree(data): if (len(data) == 0): return 0 root = tree(data[0]) q = [ root ] i = 1 while(i < len(data)): t = q.pop(0) l = tree(data[i]) q.append(l) t.left = l i += 1 if (i >= len(data)): break r = tree(data[i]) q.append(r) t.right = r i += 1 return root root = genBinaryTree(list(range(7))) root.show() print(getTreePreorder(root)) print(getTreePostorder(root)) print(getTreePostorder2(root))
09af53f4147116607b487aa0abcc5003b8c78828
saikir/my_first_python
/demo.py
1,018
4.46875
4
print ('hi') print(22/7) #comment """multiline comment can be done by keeping three double quotes""" print(22//7) #can be called floor division output is 3. print(22%7) #called as modulo division gives remainder. print("test 'ducking' string"); #Double quotes only need to be escaped in double quote strings, and the same is true for single quote strings. print('test "rocking" string') print("test \"testing\" string\nnew line") #testing the three quotes without backslash n print("""testing the three quotes without backslash n""") print('print(print("printing()")'); #print(input()); print(int('2')*float('3')) #print(int(input("Enter an int"))*2) #declaring a runtime variable x = input('Enter a number') print('twice of the entered number is : ' + x*2) #prints string twice print(int(x)*2) spam = "two eggs" print (spam) #del spam #del the variable #print(spam) #In-Place Operators y = int(x) y /= 2 print("inplace operator" + str(y)) spam += ' eggs' print('string inplace operator :' + spam);
e50832c7f6b01cdf0023b218df561129133cbda8
ayushmittal02/Python-Basics
/Intro_to_Pandas.ipynb
9,339
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd # In[ ]: flights=pd.read_csv("flights.csv") # In[ ]: flights.shape # In[ ]: flights.head() #Prints first five rows of the dataset # # Reading selected columns or rows from the dataframe # In[ ]: flights=pd.read_csv("flights.csv", usecols=[0,4]) #Reads only the 0th and 4th column # In[ ]: flights=pd.read_csv("flights.csv", nrows=3) #Reads only the first 3 rows of the dataframe flights # In[ ]: flights.columns #Displays all the columns heading of the dataframe # In[ ]: flights.ORIGIN_AIRPORT #Display a particular series(column) from the dataframe # In[ ]: flights.describe() #Gives descriptive statistics of numerical columns # # Filter rows with filter(), query() # In[ ]: flights.query("MONTH==1 & DAY==1") # In[ ]: flights[(flights.MONTH==1)&(flights.DAY==1)] # In[ ]: flights.iloc[:9] #Displays first 9 rows of the dataset # # Arrange rows with arrange(), sort() # In[ ]: flights.sort_values(['MONTH','DAY','DAY_OF_WEEK']) # In[ ]: #Sorts the particular column flights.ARRIVAL_DELAY.sort_values() # In[ ]: #Sorts the whole dataframe according to the column flights.sort_values('ARRIVAL_DELAY',ascending=False) #Sorts data in descending order of "ARRIVAL_DELAY" # # Select columns with select (),[] # In[ ]: flights[['MONTH','DAY']] # In[ ]: flights.loc[:,'MONTH':'DAY_OF_WEEK'] #Display all rows from MONTH to DAY_OF_WEEK # # Renaming columns # In[ ]: flights.rename(columns={'TAIL_NUMBER':'TAIL_NUM'}) #changes column name from "TAIL_NUMBER" to "TAIL_NUM" # In[ ]: flights.columns=flights.columns.str.replace('_',' ') #It replaces all the underscores in the columns names with spaces # # Extract distinct (unique) rows # In[ ]: flights.TAIL_NUMBER.unique() # In[ ]: flights[['ORIGIN_AIRPORT','DESTINATION_AIRPORT']].drop_duplicates() # # Add new columns # In[ ]: flights.assign(Travel_Time=flights.ARRIVAL_TIME - flights.DEPARTURE_TIME) # In[ ]: flights['Travel_Time']= flights.ARRIVAL_TIME - flights.DEPARTURE_TIME flights.head() # # Remove columns from Dataframe # In[ ]: flights.drop('Travel_Time',axis=1,inplace=True) #axis=1 to remove a column, axis=0 to remove a row # In[ ]: flights.head() # # Use string methods in pandas # In[ ]: flights.AIRLINE.str.lower() #Converts the Airline column to lowercase # In[ ]: flights.DESTINATION_AIRPORT.str.contains('PBI') # # Changing data type of column values # In[6]: orders = pd.read_table('http://bit.ly/chiporders') # In[ ]: orders.head() # In[ ]: orders.dtypes # In[ ]: orders.quantity.astype(float) #Changes data type from int to float # In[ ]: orders.item_price.str.replace('$','').astype(float).mean() # # Summarise values # In[ ]: flights.mean() #Calculates the mean of each columns # # Randomly sample rows # In[ ]: flights.sample(n=10) #Randomly selects 10 rows from the dataset as a sample # In[ ]: flights.sample(frac=0.01) #Randomly selects a samplesize of 1% of the total dataset # # Using groupby() in pandas # In[15]: drinks=pd.read_csv('http://bit.ly/drinksbycountry') # In[ ]: drinks.head() # In[ ]: drinks.groupby('continent').mean() #Calculates mean values for each continent # In[ ]: drinks.groupby('continent').beer_servings.agg(['count','max','min','mean']) #agg() uses various parameters at once # In[ ]: get_ipython().run_line_magic('matplotlib', 'inline') # In[ ]: drinks.groupby('continent').mean().plot(kind='bar') #Plots a bar chart # # Different methods in pandas series # In[ ]: movies=pd.read_csv('http://bit.ly/imdbratings') # In[ ]: movies.head() # In[ ]: movies.genre.describe() # In[ ]: movies.genre.value_counts() # In[ ]: movies.genre.value_counts(normalize=True) #Displays as a % values # In[ ]: movies.genre.unique() # In[ ]: movies.genre.nunique() # In[ ]: pd.crosstab(movies.genre,movies.content_rating) # In[ ]: get_ipython().run_line_magic('matplotlib', 'inline') # In[ ]: movies.duration.plot(kind='hist') #plots a histogram # In[ ]: movies.genre.value_counts().plot(kind='bar') #plots a bar chart # # Handling missing values in pandas # In[ ]: ufo=pd.read_csv('http://bit.ly/uforeports') # In[ ]: ufo.tail() # In[ ]: ufo.isnull().tail() #Shows True for NaN values # In[ ]: ufo.notnull().tail() #Does the opposite of isnull() # In[ ]: ufo.isnull().sum() #Calculates the total number of missing values in each column # In[ ]: ufo.dropna(how='any').shape #Drops rows if any of its entries is missing # In[ ]: ufo.dropna(how='all').shape #Drops rows only if all its entries are missing # In[ ]: ufo.dropna(subset=['City','Shape Reported'],how='any').shape #Checks missing values only in specific columns # # Using index in the dataframe # In[ ]: drinks.head() # In[ ]: drinks.set_index('country',inplace=True) #Sets column 'country' as the index # In[ ]: drinks.head() # In[ ]: drinks.index.name=None #Removes name of the index heading # In[ ]: drinks.head() # In[ ]: drinks.index.name='country' # In[ ]: drinks.loc['Brazil','beer_servings'] # In[ ]: drinks.reset_index(inplace=True) # In[ ]: drinks.head() # # Memory usage in pandas # In[ ]: drinks.info() #Shows memory usage of object references # In[ ]: drinks.info(memory_usage='deep') #Shows memory usage of the objects # In[ ]: drinks.memory_usage() # In[ ]: drinks.memory_usage(deep=True) # In[ ]: drinks['continent']=drinks.continent.astype('category') #Assigns integers to unique strings (Reducing memory usage) # In[ ]: drinks.continent.cat.codes.head() # In[ ]: drinks.memory_usage(deep=True) # In[ ]: df=pd.DataFrame({'ID':[100,101,102,103], 'quality':['Good', 'Very Good', 'Good', 'Excellent']}) # In[ ]: df # In[ ]: df['quality']=df.quality.astype('category', categories=['Good', 'Very Good', 'Excellent'], ordered=True) #Assigns integers in the order defined by 'categories' parameter # In[ ]: df.quality # In[ ]: df.sort_values('quality') # In[ ]: df[df.quality>'Good'] # # Using pandas with scikit-learn # In[ ]: train=pd.read_csv('http://bit.ly/kaggletrain') #Training data # In[ ]: train.head() # In[ ]: feature_cols=['Pclass','Parch'] #Selects two columns as features for training # In[ ]: x=train.loc[:,feature_cols] x.shape # In[ ]: y=train.Survived #Target values y.shape # In[ ]: from sklearn.linear_model import LogisticRegression logreg=LogisticRegression() logreg.fit(x,y) # In[ ]: test=pd.read_csv('http://bit.ly/kaggletest') #Testing data test.head() # In[ ]: x_new=test.loc[:,feature_cols] x_new.shape # In[ ]: new_pred_class=logreg.predict(x_new) # In[ ]: new_pred_class # In[ ]: pd.DataFrame({'PassengerID':test.PassengerId,'Survived':new_pred_class}) # # Find and remove duplicate rows in pandas # In[7]: orders.head() # In[10]: orders.shape # In[11]: orders.duplicated().sum() #Counts the total number of duplicate rows in the dataframe # In[17]: orders.loc[orders.duplicated(),:] #Shows all the duplicate rows in the dataframe # In[21]: orders.loc[orders.duplicated(keep=False),:] #Shows duplicate and its original entry in the dataframe # In[24]: orders.drop_duplicates().shape #Removes duplicate rows # In[25]: orders.drop_duplicates(subset=['order_id','item_name']).shape #Removes duplicates entries in the these 2 columns only # # Customising a Dataframe # In[37]: df=pd.DataFrame({'id':[100,101,102],'colour':['Red','Blue','Green']},columns=['colour','id'],index=[1,2,3]) #Create a dataframe using a dictionary df # In[41]: df2=pd.DataFrame([[101,'Red'],[102,'Blue'],[103,'Green']],columns=['id','colour']).set_index('id') df2 #Create a DataFrame using lists # In[46]: s=pd.Series(['square','circle','triangle'],name='shapes',index=[2,1,3]) s # In[48]: pd.concat([df,s],axis=1) #Joins the series as a column to the dataframe # # Applying functions to pandas series and dataframe # In[2]: train=pd.read_csv('http://bit.ly/kaggletrain') # In[3]: train.head() # In[6]: train['sex_num']=train.Sex.map({'female':0,'male':1}) #Using 'map' method # In[5]: train.loc[0:4,['Sex','sex_num']] # In[10]: train['name_length']=train.Name.apply(len) #Calculates the length of string # In[9]: train.loc[0:5,['Name','name_length']] # In[11]: import numpy as np train['fare_ceil']=train.Fare.apply(np.ceil) # In[12]: train.loc[0:4,['Fare','fare_ceil']] # In[14]: train.Name.str.split(',').apply(lambda x: x[0]).head() #Gets the first word of the string # In[16]: drinks.head() # In[20]: drinks.loc[:,'beer_servings':'wine_servings'].apply(max,axis=0) #Shows the max value under each column # In[23]: drinks.loc[:,'beer_servings':'wine_servings'].apply(np.argmax,axis=1) #argmax shows the column with the max value # # Merging different dataframes # In[2]: left=pd.DataFrame({'subject':['history','science'],'marks':[10,20]}) left # In[3]: right=pd.DataFrame({'subject':['history','science','literature'],'books':[4,5,9]}) right # In[5]: pd.merge(left,right,on='subject',how='outer') #'outer' takes the biggest collective set of left and right. 'inner' takes the intersection of left and right.
0053f470f420a7b96598925e499d6b362cd44f83
yukihirai0505/tutorial-program
/programming/python/machine-learning/basic.py
870
3.859375
4
# calculate print(1 - 2) print(4 * 5) print(7 / 5) print(3 ** 2) # check type print(type(10)) print(type(2.78)) print(type("hello")) # use variable x = 10 print(x) x = 100 print(x) y = 3.14 print(x * y) print(type(x * y)) # list a = [1, 2, 3, 4, 5] print(a) print(len(a)) print(a[0]) print(a[4]) a[4] = 99 print(a) print(a[0:2]) print(a[1:]) print(a[:3]) print(a[:-1]) print(a[:-2]) # dictionary me = {'height': 180} print(me['height']) me['weight'] = 70 print(me) # boolean hungry = True sleepy = False print(type(hungry)) print(not hungry) print(hungry and sleepy) print(hungry or sleepy) # if if hungry: print("I'm hungary") else: print("I'm not hungary") print("I'm sleepy") # for for i in [1, 2, 3]: print(i) # function def hello(): print("Hello World!") hello() def hello(object): print("Hello " + object + "!") hello("cat")
0321662cfde748244a93de8a0b14f1763b7bf261
XaserAcheron/damnums
/damfont.py
1,070
3.796875
4
import sys MAX_DIGITS = 5 # [TODO] document this silly thing: def genfonts(prefix, width, height): yoffset = height - 2 for charindex in range(10): char = chr(65 + charindex); for numdigits in range(2, MAX_DIGITS+1): spritewidth = width * numdigits xoffset = int(spritewidth / 2) for digit in range(1, numdigits+1): patchwidth = spritewidth - (width * digit) print ('Sprite "{}{}{}{}0", {}, {} {{ Offset {}, {} Patch "{}11{}0", {}, 0 }}'.format( prefix , numdigits , digit , char , spritewidth , height , xoffset , yoffset , prefix , char , patchwidth )) print ('') if __name__ == "__main__": if len(sys.argv) > 3: try: prefix = sys.argv[1] width = int(sys.argv[2]) height = int(sys.argv[3]) if len(prefix) == 2: genfonts(prefix, width, height) else: print ("error: [prefix] must be exactly two characters") except ValueError: print ("error: [width] and [height] must be integers") else: print ("usage: python damfont.py [prefix] [width] [height]")
45996462a5f1670fc439054c4465b9f6e421ccbe
marri88/python-base
/FOR_WHILE/prob7.py
695
3.953125
4
even ='' odd='' for index, char in enumerate (['Максат','Лязат','Данияр','Айбек','Атай','Салават','Адинай','Жоомарт','Алымбек','Эрмек','Дастан','Бекмамат','Аслан',]): if (index % 2 == 0): even += char else: odd += char print (odd) '''# 7. У вас всё тот же список имён: # names = ('Максат','Лязат','Данияр','Айбек','Атай','Салават','Адинай','Жоомарт','Алымбек','Эрмек','Дастан','Бекмамат','Аслан',) # Выведите каждое 2 имя. # Подсказка: Всего имён 13. '''
3b8befae3b0b76538e368179b319b2dad685da64
changray1201/AE402-Python
/算平均1.py
1,321
3.6875
4
scores = [] names = [] score = 0 n = int(input("請輸入全班學生人數")) #輸入人數 high = 0 low = 100 global highn,lown,avg avg = 0 highn = "" lown = "" def highscore(scores): high = 0 n = len(scores) for i in range(n) : if scores[i] >= high : high = scores[i] highn = names[i] person = list() person.append(highn) person.append(high) return person def lowscore(scores) : low = 100 n = len(scores) for i in range(n) : if scores[i] <= low : low = scores[i] lown = names[i] person = list() person.append(lown) person.append(low) return person def average(scores) : total = 0 n = len(scores) for i in scores : total += i average = total / n return average for i in range(n) : name = input("輸入名字") score = int(input("輸入分數")) #分數輸入 scores.append(score) names.append(name) print(scores) print(names) print("全班平均是:" , average(scores)) #算出平均 print(" ") print("分數最高的人是:", highscore(scores),"分") #輸出最高分的人和分數 print(" ") print("分數最低的人是:", lowscore(scores) ,"分") #輸出最低分的人和分數
6c38fa20358c8aea5b4d73baa6203da0999f6e1f
acid9reen/Artezio
/Lesson_1/task04.py
397
4.09375
4
'''Count special strings''' def special_string_counter(list_): '''Return special strings count''' counter = 0 for str_ in list_: if len(str_) > 1 and str_[:1] == str_[-1:]: counter += 1 return counter def main(): '''Run special_string_counter function with user input''' list_ = input().split() print(special_string_counter(list_)) main()
ad420cc5d043cc1cd78934c670dc00552b5788ab
zshuangyan/algorithm
/binary_tree.py
2,871
3.609375
4
class Node: def __init__(self, val): self.val = val self.left = None self.right = None class BinaryTree: def __init__(self, root=None): self.root = root def inOrder(self, node): if not node: return [] stack = [node] tmp = [] result = [] while stack: node = stack.pop() while node: tmp.append(node) node = node.left while tmp: node = tmp.pop() result.append(node.val) if node.right: stack.append(node.right) break return result def preOrder(self, node): if not node: return [] stack = [node] result = [] while stack: node = stack.pop() result.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return result def heightNode(self, node): if not node: return 0 left_height = self.heightNode(node.left) right_height = self.heightNode(node.right) max_height = max(left_height, right_height) return max_height + 1 def width(self, height): return pow(2, height) - 1 def get_child_pos(self, pos, child_height): grand_child_width = self.width(child_height-1) return pos - (grand_child_width+1), pos + (grand_child_width+1) def print_tree_matrix(self): if not self.root: return [[]] height = self.heightNode(self.root) width = self.width(height) matrix = [[" " for i in range(width)] for j in range(height)] root_pos = width // 2 stack = [(self.root, root_pos)] for i in range(height): for j in range(2**i): node, node_pos = stack.pop(0) if node: matrix[i][node_pos] = str(node.val) if i == height -1: continue left_pos, right_pos = self.get_child_pos(node_pos, height-i-1) if node: node_left = node.left node_right = node.right else: node_left = None node_right = None stack.append((node_left, left_pos)) stack.append((node_right, right_pos)) return matrix def printTree(self): if not self.root: print("Empty tree") return matrix = self.print_tree_matrix() for row in matrix: print("".join(row))
07f7eb09c3f0ae0307d49af0b098436a37da57fe
TARRAKAN/python_things
/Grokking Deep Learning/chapter2/functions.py
763
3.71875
4
def elementwise_multiplication(vec_a, vec_b): assert(len(vec_a) == len(vec_b)) output = list() for i in range(len(vec_a)): output.append(vec_a[i] * vec_b[i]) return output def elementwise_addition(vec_a, vec_b): assert(len(vec_a) == len(vec_b)) output = list() for i in range(len(vec_a)): output.append(vec_a[i] + vec_b[i]) return output def vector_sum(vec_a): output = 0 for num in vec_a: output += num return output def vector_averege(vec_a): output = 0 for num in vec_a: output += num return output/len(vec_a) print(elementwise_multiplication([1,2,3], [4,5,6])) print(elementwise_addition([1,2,3], [4,5,6])) print(vector_sum([1,2,3])) print(vector_averege([1,2,3]))
3cebb00b33da6da4bc8c2c4bd2eebd28732f4bea
VersionBeathon/Python_jerboa
/data_structures&&algorithms/question_about_dict.py
1,124
3.75
4
# _*_ coding:utf-8 _*_ # 将键(key)映射到多个值的字典(一键多值字典[multidict]) from collections import defaultdict from collections import OrderedDict import json d = { 'a': [1, 2, 3], 'b': [4, 5] } e = { 'a': {1, 2, 3}, 'b': {4, 5} } print(d) print(e) # 利用collections模块中的dafaultdict类创建字典(它会自动初始化第一个值) d = defaultdict(list) d['a'].append(1) d['a'].append(2) d['b'].append(4) print(d) d = defaultdict(set) d['a'].add(1) d['a'].add(2) d['b'].add(4) print(d) # 控制字典中元素的顺序 # 使用collections模块中的OrderedDict类 # 当对字典做迭代时,会严格按照元素初始添加的审讯进行: d = OrderedDict() d['foo'] = 1 d['bar'] = 2 d['spam'] = 3 d['grok'] = 4 for key in d: print(key, d[key]) # 想在json编码时精确控制各字段的顺序,使用OrderedDict构建数据 print(json.dumps(d)) # OrderedDict内部维护了一个双向链表,来实现字典的有序 # OrderedDict的大小是普通字典的两倍多,使用时应该认真对应用做需求分析,进而减少内存开销。
bde9f2c11f5b5e741cb875329e410aed8a33993a
lukastencer/coursera-algorithms
/lesson2/llstack.py
1,568
3.6875
4
class llstack: class node(): next = None val = None def __init__(self,nextNode,val): self.next = nextNode self.val = val head = None iterIdx = None def __iter__(self): self.iterIdx=self.head return self def next(self): if self.iterIdx == None: raise StopIteration data = self.iterIdx.val self.iterIdx = self.iterIdx.next return data def push(self,inVal): if self.head == None: self.head = self.node(None,inVal) else: tempH = self.head self.head = self.node(tempH,inVal) def pop(self): item = self.head.val; self.head = self.head.next; return item def top(self): return self.head.val def peek(self): return self.head.val def toList(self): res = [] tempP = self.head while not tempP == None: res.append(tempP.val) tempP = tempP.next return res def show(self): tempP = self.head print '-------' while not tempP == None: print tempP.val tempP = tempP.next def parse(self,inString): parts = inString.split() for part in parts: if part == '-': self.pop() else: self.push(part)
e45f36545c688ef44fb1ef36a177b969402bb3ab
CiaranGruber/Python-Tutorial-Solutions
/fahrenheit_to_celsius.py
201
3.765625
4
def main(): fahrenheit = int(input("Fahrenheit value: ")) celsius = (fahrenheit - 32) * 5 / 9 print(fahrenheit, "fahrenheit is", celsius, "celsius") if __name__ == "__main__": main()
95d9679265dd278433f8867571ee4d1590cf85c9
natemago/adventofcode2017
/day19_series_of_tubes/solution.py
2,350
3.71875
4
def read_input(f): grid = [] with open(f) as inpf: for line in inpf: grid.append([c for c in line]) return grid MN = {(-1,0):'up', (0,1):'right', (1,0):'down', (0,-1):'left'} def follow_diagram(diagram): moves = [[-1,0], [0,1], [1,0], [0,-1]] # up, right, down, left y = 0 x = diagram[0].index('|') #print(diagram) #print(y, x) d = [1,0] # initial direction, down code = '' total_steps = 1 while True: #print(x,y,diagram[y][x]) steps = 0 while True: dx, dy = x+d[1], y+d[0] if dy >= 0 and dy < len(diagram) and dx >= 0 and dx < len(diagram[dy]): #print(dy, dx, ' ',diagram[dy][dx]) if not diagram[dy][dx] in ['+', ' ']: x,y = dx, dy steps += 1 if diagram[y][x].isalpha(): code += diagram[y][x] else: if diagram[dy][dx] == '+': steps += 1 x,y = dx,dy break else: break #print('at ', diagram[y][x]) print(MN[(d[0],d[1])], steps) total_steps += steps dir_found = False for move in moves: #print(move, '==', [-d[0], -d[1]]) if move == [-d[0], -d[1]]: #print(' yep') continue dx, dy = x+move[1], y+move[0] if dy >= 0 and dy < len(diagram) and dx >= 0 and dx < len(diagram[dy]): #print(diagram[dy][dx], "diagram[dy][dx] in ['|', '-']=", diagram[dy][dx] in ['|', '-'], "diagram[dy][dx].isalpha()=",diagram[dy][dx].isalpha()) if diagram[dy][dx] in ['|', '-'] or diagram[dy][dx].isalpha(): d = move dir_found = True break if not dir_found: break return code, total_steps test_diag= ' | , | +--+ , A | C , F---|----E|--+ , | | | D , +B-+ +--+ ' print('Test:', follow_diagram([[c for c in s] for s in test_diag.split(',')])) code, steps = follow_diagram(read_input('input')) print('Part1: ', code) print('Part2: ', steps)
2f7fa2f3a4212c9984bcaeb23eae795b0d60eb85
JPCARVALH0/python_equacao_2_grau
/calculo.py
386
3.78125
4
import funcoes_calculo print("digite respectivamente os valores correspodentes a A, B, e C\npor favor utilize números por extenso\npor exemplo no lugar de 5/2 escreva 2.5 utilizando ponto no lugar de vírgula\ncerto 2.5/errado 2,5") A = float(input("digite A ")) B = float(input("digite B ")) C = float(input("digite C ")) resultado = funcoes_calculo.equa_2(A,B,C) print(resultado)
f745af7ec18b1a21f7a3fde9cd3d748234c64d1c
AaronTengDeChuan/leetcode
/leetcode/110.BalancedBinaryTree.py
1,143
3.859375
4
#!usr/bin/env python #-*-coding:utf-8-*- import sys class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def getHeight(self, root): if root == None: return 0 left = self.getHeight(root.left) if left == -1: return -1 right = self.getHeight(root.right) if right == -1: return -1 if abs(left - right) > 1: return -1 else: return 1 + max(left, right) def height_balanced(self, root, flag): if root == None: return 0 left = self.height_balanced(root.left, flag) right = self.height_balanced(root.right, flag) if abs(left - right) > 1: flag[0] = False return 1 + max(left, right) def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ #flag = [True] #self.height_balanced(root, flag) if self.getHeight(root) == -1: return False else: return True
da7624b23578e48d705f4683f477547d84ad4489
borjas93/mi_primer_programa
/agenda.py
701
4.0625
4
''' Ejercicio de una agenda de telefonos usando listas. ''' agenda = [] while True: print('') print('¿Que quieres hacer?') print('') accion = input('Añadir numero [A] / Consultar numero [C] / Corregir numero [Corregir] / Salir [S] ').capitalize() print('') if accion == 'A': nombre = input('Cual es el nombre? ').capitalize() print('') numero = input('Cual es su numero? ') agenda.append([nombre, numero]) elif accion == 'C': nombre = input('De quien quieres saber el numero? ').capitalize() print('') for item in agenda: if nombre == item[0]: print(item[1]) else: break
4555f47390891184f0b58db64f44923a0d5c2976
Leu-s/Simple-text-editor
/tk-Редактор текста.py
1,762
3.75
4
import tkinter as tk from tkinter .filedialog import askopenfilename from tkinter .filedialog import asksaveasfilename def open_file(): """Открывает файл для редактирования""" filepath = askopenfilename( filetypes=[('Text files', '*.txt'), ('All Files', '*.*')] ) if not filepath: return txt_edit.delete('1.0', tk.END) with open(filepath, 'r') as input_file: text = input_file.read() txt_edit.insert(tk.END, text) window.title(f'Simple text editor - {filepath}') def save_file(): """Сохраняем текущий файл как новый файл.""" filepath = asksaveasfilename( defaultextension='txt', filetypes=[('Text files', '*.txt'), ('All files', "*.*")] ) if not filepath: return with open(filepath, 'w') as output_file: text = txt_edit.get('1.0', tk.END) output_file.write(text) window.title(f'Simple text editor - {filepath}') window = tk.Tk() window.title('Simple text editor') window.rowconfigure(0, minsize=400, weight=1) # (<Высота первой строки, пикс>, <minsize>, <weight>) window.columnconfigure(1, minsize=400, weight=1) window.minsize(width=580, height=65) txt_edit = tk.Text(window) fr_buttons = tk.Frame(master=window, bg='#2D2A2E') btn_open = tk.Button(fr_buttons, text='Open', bg='#EDD864', command=open_file) btn_save = tk.Button(fr_buttons, text='Save as...', bg='#EDD864', command=save_file) btn_open.grid(row=1, column=0, sticky='ew', padx=5, pady=0) btn_save.grid(row=0, column=0, sticky='ew', padx=5, pady=5) fr_buttons.grid(row=0, column=0, sticky='ns') txt_edit.grid(row=0, column=1, sticky='nsew') window.mainloop()
f605e555115ad4ded79098f83ed2e75bb5dbba05
FelixDavidson/MyPythonPrograms
/ThinkPython/5_4.py
400
4.0625
4
def is_triangle(a, b, c): if a > b + c or b > a + c or c > a + b: print 'No' else: print 'Yes' def try_tri(): print 'You have three sticks. Choose 3 lengths that make a triangle.' a = int(raw_input('Choose a length for a:\n')) b = int(raw_input('Choose a length for b:\n')) c = int(raw_input('Choose a length for c:\n')) is_triangle(a, b, c) try_tri()
fcdf944e416674eb0cdf9e2002bf18180af71e1a
D-DanielS/MetodosNumericos
/metodoBisecion.py
699
3.765625
4
from f import f xi = float(raw_input("Ingrese xi: ")) xs = float(raw_input("Ingrese xs: ")) error = float(raw_input("Ingrese error: ")) xa = (xi + xs)/2.0 i = 0 itmax = 100 print("\n{:^10}{:^10}{:^10}{:^10}{:^10}{:^10}{:^10} ".format("i","xi","xs", "xa", "signo", "cambio", "error")) while(abs( f(xa)) > error and i < itmax): i += 1 xa = (xi + xs)/2.0 if f(xi) * f(xa) < 0: xs = xa signo = "negativo" limite = "superior" else: xi = xa signo = "positivo" limite = "inferior" print ("{:^10}{:^10.4f}{:^10.4f}{:^10.4f}{:^10}{:^10}{:^10.4f}".format(i,float(xi),float(xs),float(xa),signo, limite,float(f(xa)))) print "Raiz: ", xa
abc9b9641fa462186d018f5ebed85fc62aba77e3
hotai1806/reversigame
/array.py
1,949
3.59375
4
board = [['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', 'W', 'B', '.', '.', '.'], ['.', '.', '.', 'B', 'W', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.']] HEIGHT = 8 WIDTH = 8 board = [] def PrintBoard(board): for i in range(WIDTH): board.append(['.', '.', '.', '.', '.', '.', '.', '.']) print(" a b c d e f g h") for y in range(HEIGHT): print('%s' % (y + 1), end = ' ') for x in range(WIDTH): print(board[x][y], end= ' ') print() board[3][3] = "W" board[3][4] = "B" board[4][3] = "B" board[4][4] = "W" def isOnBoard(x,y): return x >= 0 and x < 7 and y >= 0 and y <= 7 def player1(0): go0 = 'a b c d e f g h'.split() go1 = '1 2 3 4 5 6 7 8'.split() while True: move = input().lower() pass def player2(0): pass def Availablemove(board,tile,xs,ys): if board[xs][ys] != " " or not isOnBoard(xs,ys): return False board[xs][ys] = tile if tile == "B" otherTile = "W" else: otherTile = "B" tilesToFlip = [] tx =[[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]] for xs, ys in tx: x, y = xs, xy x + = xdirection y + = ydirection if not isOnBoard(x,y) continue while board[x][y] == otherTile: x += xdirection y += ydirection if not isOnBoard(x, y): break if not isOnBoard(x, y): continue if board[x][y] == tile: while True x -= xdirection tilesToFlip.append([x, y]) board[xs][ys] = '.' if len(tilesToFlip) == 0: return print() return tilesToFlip
80c9f8399223a7203328cb3dd8465f70502b1d65
Nehanavgurukul/function_ques
/power_of_number.py
276
4.21875
4
def power_of_number(num1,num2): if(num2>0 and num1>0): power_of_number=num1**num2 a=power_of_number return a else: return 0 n1=int(input("enter the number")) n2=int(input("enter the number")) print(power_of_number(n1,n2))
3abe52970d58dd41884c9ef93c8bfa6a6f941d39
Venkat-Rajgopal/Python_Tricks_and_OOP
/Algorithms/change.py
528
3.921875
4
# Uses python3 import sys """ Find the minimum number of coins needed to change the input value into coins with denominations 1, 5, 10 """ def get_change(m): large = 10 mid = 5 small = 1 result = 0 coins = [large, mid, small] while m != 0: for coin in coins: if (m - coin >= 0): m -= coin result = result + 1 break return result if __name__ == '__main__': m = int(sys.stdin.readline()) print(get_change(m))
fa15218bc842f18a3474c3a78490551ddfe0ae16
saood321/ebmpFYP
/actual/MusicSelection.py
3,133
3.578125
4
import actual.DataBaseConnect mydb,mycursor=actual.DataBaseConnect.database() """ @requires: songType means happy,sad etc username of user and limit represents how many songs we want to fetch @functionality: This function select 3 top rated songs from user history @effect: returns limit of history song """ def historysongs(songtype,username,limit): if songtype==None: sql = ("""SELECT history.SongId FROM history INNER JOIN song ON history.SongId = song.SongId WHERE history.UserId='%s' ORDER BY Rating DESC LIMIT %s""" % (username, limit)) else: sql = ( """SELECT history.SongId FROM history INNER JOIN song ON history.SongId = song.SongId WHERE song.SongTypeId='%s' and history.UserId='%s' ORDER BY Rating DESC LIMIT %s""" % (songtype,username,limit)) mycursor.execute(sql) history = mycursor.fetchall() print(history) return history """ @requires: songtype represents mood happy,sad etc @functionality: This function selects 3 top overall highly rated song @effect: List of songs """ def ratedsong(songtype): sql = ("""SELECT SongId FROM song WHERE SongTypeId='%s' ORDER BY TotalRating DESC LIMIT 3 """ % (songtype)) mycursor.execute(sql) myresult = mycursor.fetchall() return myresult """ @requires: songtype represents mood of user and random_no represents how many songs that we want to get randomly @functionality: This function selects random songs from song list @effect: return list of random songs """ def randomsong(songtype,random_no): sql = ("""SELECT SongId FROM song WHERE SongTypeId='%s' ORDER BY RAND() LIMIT %s """ % (songtype, random_no)) mycursor.execute(sql) randomlist = mycursor.fetchall() return randomlist """ @requires: combine_list represents old list in which we will append new_list @functionality: This function appends two list and there is no repeation @effect: combine_list contains oldlist and newlist """ def appending(combine_list,new_list): count=0 for i in new_list: r=0 for j in combine_list: if i==j: r=2 if(r==0): combine_list.append(i) count = count + 1 return combine_list """ @requires: mood and username of current user @functionality: This function controls the whole process by ensuring there should be no repetation and list contain 10 songs @effect: return combine_list contains 10 songs """ def database(mood,username): global myresult import CheckSongType songtype1=CheckSongType.songtype(mood) songtype=songtype1[0][0] history=historysongs(songtype,username,3) myresult=ratedsong(songtype) random_no = 10 - 3 - len(history) randomlist=randomsong(songtype,random_no) combine_list=[] combine_list=appending(combine_list,myresult) combine_list=appending(combine_list,history) combine_list=appending(combine_list,randomlist) less=len(combine_list) less=10-less while less>0: a = randomsong(songtype, (less)) combine_list=appending(combine_list,a) less = len(combine_list) less = 10 - less return combine_list
f1658375f4d27a43b920464319cfae6f142a5521
sauravghoshroy/human-beahviour-prediction
/mypackage/function.py
513
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Name of the project: Individual Programming Exercise: (IPE) # Description: A program that "predicts" human behavior using a simple game. # File Name: function.py # File Description: Python code of the function that generates random numbers for the IPE program. # Author: Saurav Ghosh Roy # Last Updated: Thu 7 Feb, 2021 """ def rand_num_gen(x) : """generates a random number using the linear congruence method.""" y = ((22695477*int(x))+1) % (2**32) return y
b978e78dd713e2457bdbf275679a5505e4502683
rafal1996/CodeWars
/Array.diff.py
385
3.890625
4
# Your goal in this kata is to implement a difference function, # which subtracts one list from another and returns the result. # It should remove all values from list a, which are present in list b keeping their order. # array_diff([1,2],[1]) == [2] def array_diff(a, b): return [x for x in a if x not in b] print(array_diff([1,2], [1])) print(array_diff([1,2,2], [1]))
82f2ece78281e64b2d36e45eb3eeab959bb9ce4f
boknowswiki/mytraning
/lintcode/python/0652_factorization.py
1,235
3.640625
4
#!/usr/bin/python -t from math import sqrt class Solution: """ @param n: An integer @return: a list of combination """ def getFactors(self, num): res = [] def dfs(start, n, tmp): for i in range(start, int(sqrt(n))+1): if n % i == 0: dfs(i, n/i, tmp + [i]) res.append(tmp + [n]) dfs(2, num, []) res.pop() return res # dfs import math class Solution: """ @param n: An integer @return: a list of combination """ def getFactors(self, n): # write your code here ret = [] self.dfs(2, n, [], ret) return ret def dfs(self, start, remain, path, ret): if remain == 1 and len(path) != 1: ret.append(list(path)) return for i in range(start, int(math.sqrt(remain))+1): if remain % i == 0: path.append(i) self.dfs(i, remain/i, path, ret) path.pop() if remain >= start: path.append(remain) self.dfs(remain, 1, path, ret) path.pop() return
5427e76091a62fd5af90933f826e92c309879666
spizzirri/fundamentos-machine-learning
/_numpy.py
1,863
4.1875
4
import numpy as np """ Biblioteca de Python comúnmente usada en la ciencias de datos y aprendizaje automático (Machine Learning). Proporciona una estructura de datos de matriz que tiene diversos beneficios sobre las listas regulares. """ print("** NUMPY **\n") print("Creando un arreglo") arreglo = np.array([10, 30, 20, 4, 30, 51, 7, 2, 4, 40, 100]) print(arreglo) print("Solo la posicion 4") print(arreglo[4]) print("Desde la posicion 3 hasta el final") print(arreglo[3:]) print("Desde la posicion 3 hasta la 7 no inclusive") print(arreglo[3:7]) print("Desde la posicion 1 hasta el final saltando de a 4") print(arreglo[1::4]) print("Generando un arreglo de ceros") print(np.zeros(5)) print("Generando un arreglo de unos") print(np.ones((4, 5))) print("Consultando un tipo de dato") print(type(arreglo)) print("Generando un arreglo de 5 numeros entre el 3 y el 10") print(np.linspace(3, 10, 5)) print("Genrando una matriz") matriz = np.array( [['x', 'y', 'z'], ['a', 'c', 'e']]) print(matriz) type(matriz) print("Dimensiones de la matriz") print(matriz.ndim) print("Ordenando un vector") print(np.sort(arreglo)) print("Ordenado un vector de tipo complejo que usa cabecera") cabeceras = [ ('nombre', 'S10' ), ('edad', int) ] datos = [ ('Juan', 10), ('Maria', 70), ('Javier', 42), ('Samuel', 15) ] usuarios = np.array(datos, dtype = cabeceras) print(np.sort(usuarios, order = 'edad' )) print("Generando un arreglo con 25 numeros consecutivos") print(np.arange(25)) print("Generando un arreglo con numeros entre el 5 y el 30 no inclusivo") print(np.arange(5,30)) print("Generando un arreglo con numeros entre el 5 y el 50 saltando de a 5") print(np.arange(5, 50, 5)) print("Generando una matriz de 3 filas y 5 columnas con el valor 10") print(np.full( ( 3, 5 ), 10)) print("Generando una matriz diagonal") print(np.diag ( [1, 3, 9, 10] ))
7333c228e33d17762e3a60f676061ac8cfee07e1
ulysses-sl/algorithm-implementations
/python/linkedlist/StackQueue.py
2,997
3.59375
4
from LinkedList import SinglyLinkedList, DoublyLinkedList class SLStack: def __init__(self): self.store = None self.count = 0 def push(self, v): x = SinglyLinkedList(v) x.next = self.store self.count += 1 self.store = x def pop(self): if self.store: v = self.store.value self.store = self.store.next self.count -= 1 return v else: return None def peek(self): if self.store: return self.store.value else: return None def total(self): return self.count class DLQueue: def __init__(self): self.head = DoublyLinkedList(None) self.tail = DoublyLinkedList(None) self.head.next = self.tail self.tail.prev = self.head self.count = 0 def push(self, v): x = SinglyLinkedList(v) # connect x.next x.next = self.head.next self.head.next.prev = x # connect x.prev x.prev = self.head self.head.next = x self.count += 1 def pop(self): if self.count <= 0: return None v = self.tail.prev.value self.tail.prev.prev.next = self.tail self.tail.prev = self. tail.prev.prev self.count -= 1 return v def peek(self): if self.count > 0: return self.tail.prev.value else: return None def total(self): return self.count class SQueue: def __init__(self): self.istack = SLStack() self.ostack = SLStack() def push(self, v): self.istack.push(v) def pop(self): if self.ostack.count > 0: return self.ostack.pop() else: while self.istack.count > 0: self.ostack.push(self.istack.pop()) if self.ostack.count > 0: return self.ostack.pop() else: return None def total(self): return self.istack.total() + self.ostack.total() class QStack1: def __init__(self): self.q1 = DLQueue() self.q2 = DLQueue() def push(self, v): self.q1.push(v) while self.q2.total() > 0: self.q1.push(self.q2.pop()) self.q1, self.q2 = self.q2, self.q1 def pop(self): if self.q2.total() > 0: return self.q2.pop() else: return None def total(self): return self.q1.total() + self.q2.total() class QStack2: def __init__(self): self.q1 = DLQueue() self.q2 = DLQueue() def push(self, v): self.q1.push(v) def pop(self): if self.q1.count == 0: return None while self.q1.total() > 1: self.q2.push(self.q1.pop()) v = self.q1.pop() self.q1, self.q2 = self.q2, self.q1 return v def total(self): return self.q1.total() + self.q2.total()
b61ebe33d3692b88e494800b6863a2fe5494e38a
annpia92/Tester_School
/czykwadrat.py
166
3.5625
4
x = 101 for i in range(x+1): if i**2==x: print('podana liczba jest kwadratem', i) break else: print('podana liczba nie jest kwadratem')
1d88f94e9757ea3359138e8c55d3f018124ea716
jaskaran-23/Combat-Tanks
/tank10.py
810
3.53125
4
def pause(): paused=True message_to_screen("Paused",red,-100,size="large") message_to_screen("Press C to continue or Q to quit.",black,25,"medium") pygame.display.update() while paused: for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() quit() if event.type==pygame.KEYDOWN: if event.key==pygame.K_c: paused=False elif event.key==pygame.K_q: pygame.quit() quit() #gamedisplay.fill(light_blue) message_to_screen("Paused",red,-100,size="large") message_to_screen("Press C to continue or Q to quit.",black,25,"medium") pygame.display.update() clock.tick(5)
b18dc02fb769f4706edc70760e99d9d5073e559f
my-xh/DesignPattern
/03行为型模式/18备忘模式/模拟TodoList.py
2,032
4.09375
4
class TodoList: """待办清单""" def __init__(self): self.__work_items = [] def write_work_item(self, item): self.__work_items.append(item) def get_work_items(self): return self.__work_items class TodoListCaretaker: """ToDoList管理类""" def __init__(self): self.__todo_list = None def set_todo_list(self, todo_list): self.__todo_list = todo_list def get_todo_list(self): return self.__todo_list class Engineer: """工程师""" def __init__(self, name): self.__name = name self.__work_items = [] def add_work_item(self, item): self.__work_items.append(item) def forget(self): self.__work_items.clear() print(f'{self.__name} 工作太忙了,都忘记要做什么了!') def write_todo_list(self): """将工作项记录到TodoList""" todo_list = TodoList() for item in self.__work_items: todo_list.write_work_item(item) return todo_list def retrospect(self, todo_list): """回忆工作项""" self.__work_items = todo_list.get_work_items() print(f'{self.__name} 想起要做什么了!') def show_work_item(self): if len(self.__work_items): print(f'{self.__name} 的工作项:') for i in range(len(self.__work_items)): print(f'{i + 1}. {self.__work_items[i]};') else: print(f'{self.__name} 暂无工作项!') if __name__ == '__main__': tony = Engineer('Tony') tony.add_work_item('解决线上部分用户因昵称太长而无法显示全的问题') tony.add_work_item('完成PDF的解析') tony.add_work_item('在阅读器中显示PDF第一页的内容') tony.show_work_item() caretaker = TodoListCaretaker() caretaker.set_todo_list(tony.write_todo_list()) print() tony.forget() tony.show_work_item() print() tony.retrospect(caretaker.get_todo_list()) tony.show_work_item()
723c47fc8bf9afc4e56b0a435ddff15beae98792
edson-gonzales/SICARIOS
/test/customer_test.py
3,080
3.984375
4
#customer_test.py __author__ = 'Roy Ortiz' import unittest from admin_module.user_module.customer import Customer class CustomerTest(unittest.TestCase): def test_create_a_new_customer_instance(self): """ Will verify that a new customer instance is an instance of Customer class :return: """ first_name = "Jon" last_name = "Doe" birth_date = "01/01/2000" address = "calle hachazos" phone = "7000000" email = "[email protected]" membership = "gold" is_active = 1 new_customer = Customer(first_name, last_name, birth_date, address, phone, email, membership, is_active) self.assertTrue(isinstance(new_customer, Customer)) def test_phone_value_saved_for_customer(self): """ this will verify that the phone number is saved and persist """ first_name = "Jon" last_name = "Doe" birth_date = "01/01/2000" address = "calle hachazos" phone = "7000000" email = "[email protected]" membership = "gold" is_active = 1 new_customer = Customer(first_name, last_name, birth_date, address, phone, email, membership, is_active) self.assertEqual(new_customer.get_phone_number(), phone) def test_address_value_saved_for_customer(self): """ this will verify that a the customer address is saved and persist """ first_name = "Jon" last_name = "Doe" birth_date = "01/01/2000" address = "calle hachazos" phone = "7000000" email = "[email protected]" membership = "gold" is_active = 1 new_customer = Customer(first_name, last_name, birth_date, address, phone, email, membership, is_active) self.assertEqual(new_customer.get_address(), address) def test_email_value_saved_for_customer(self): """ this will verify that a the customer email is saved and persist """ first_name = "Jon" last_name = "Doe" birth_date = "01/01/2000" address = "calle hachazos" phone = "7000000" email = "[email protected]" membership = "gold" is_active = 1 new_customer = Customer(first_name, last_name, birth_date, address, phone, email, membership, is_active) self.assertEqual(new_customer.get_email(), email) def test_customer_status_is_saved_for_customer(self): """ this will verify that a the customer status is saved and persist """ first_name = "Jon" last_name = "Doe" birth_date = "01/01/2000" address = "calle hachazos" phone = "7000000" email = "[email protected]" membership = "gold" is_active = 1 new_customer = Customer(first_name, last_name, birth_date, address, phone, email, membership, is_active) self.assertEqual(new_customer.get_status(), is_active) if __name__ == "__main__": unittest.main()
a12371dc955643632c3b3c88ac9d03d1f781a58f
Dragonriser/DSA_Practice
/Arrays/MaxSubSum.py
408
3.703125
4
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. #CODE: class Solution: def maxSubArray(self, nums: List[int]) -> int: curSum = maxSum = nums[0] for num in nums[1:]: curSum = max(num, curSum + num) maxSum = max(maxSum, curSum) return maxSum
a401126d4d1c119f0fd1a3e25f500c196b1e423e
nflondo/myprog
/python/workbook/sort_int.py
721
4.28125
4
#!/usr/bin/python3 # Read 3 ints from user, and display them in sorted order # use built-in function min() and max() user_input = input("Enter 3 numbers (separated by a space): ") list_num = user_input.split() #splits on space by default #print("list_num: ", list_num) if len(list_num) == 3 : min_number = min(int(list_num[0]), int(list_num[1]), int(list_num[2])) max_number = max(int(list_num[0]), int(list_num[1]), int(list_num[2])) middle_num = ((int(list_num[0]) + int(list_num[1]) + int(list_num[2])) - min_number - max_number) else : print("Please enter exactly 3 numbers") #print("Min number: %d" % min_number) print("Sorted numbers: %d %d %d" % (min_number, middle_num, max_number))
c15e16fb0f780640010e13cbc8f5e03288ae1c66
ginaschmalzle/fibonacci
/fibo_func.py
275
3.796875
4
#!/usr/bin/python #find fibonocci number of the 10th element start=[0,1,1] # Fn(0), Fn(1), Fn(2) n = 10 def get_fibo(n, start): i = 3 fn1=start[1] fn2=start[2] while ( i <= n): fn = fn1 + fn2 fn1 = fn2 fn2 = fn i = i+1 return fn print get_fibo(n, start)
64ff067f003bd8be6d9c09c6df40cf9c007293d0
robertsdionne/clrs
/ch02/linear_search.py
587
3.671875
4
#!/usr/bin/env python import argparse def linear_search(items, value): for i in xrange(0, len(items)): if value == items[i]: return i return None def main(): commands = argparse.ArgumentParser(description = 'Insertion sort.') commands.add_argument( 'integers', metavar = 'N', type = int, nargs = '+', help = 'Integers to search.') commands.add_argument( '--value', metavar = 'v', type = int, help = 'Value to find.') arguments = commands.parse_args() print linear_search(arguments.integers, arguments.value) if '__main__' == __name__: main()
33e907839dbdfaa2840584850e217f2a8551d1db
QuentinDuval/PythonExperiments
/greedy/CoinPiles.py
3,999
4.0625
4
""" https://practice.geeksforgeeks.org/problems/coin-piles/0 There are N piles of coins each containing Ai (1<=i<=N) coins. Now, you have to adjust the number of coins in each pile such that for any two pile, if a be the number of coins in first pile and b is the number of coins in second pile then |a-b|<=K. In order to do that you can remove coins from different piles to decrease the number of coins in those piles but you cannot increase the number of coins in a pile by adding more coins. Now, given a value of N and K, along with the sizes of the N different piles you have to tell the minimum number of coins to be removed in order to satisfy the given condition. Note: You can also remove a pile by removing all the coins of that pile. """ from functools import lru_cache """ The following algorithm does not work. Indeed, we can also remove the coin pile entirely: 1 5 5 5 5 and k = 3 should return 1 """ def min_removal_bad(heights, k): if not heights: return 0 removals = 0 lowest = min(heights) for height in heights: if height > lowest + k: removals += height - (lowest + k) return removals """ The following algorithm work by Dynamic Programming: - We sort the piles from left minimum to right maximum - Either we keep the left pile and we remove from the right pile - Or we drop the left pile entirely and keep the right pile This works because we cannot add coins to the left pile Number of sub-solutions: O(N^2) => Space complexity: O(N^2) => Time complexity: O(N^2) (constant amount of work by recursion) """ def min_removal_dp(heights, k): if not heights: return 0 heights.sort() @lru_cache(maxsize=None) def visit(i, j): if i >= j or heights[j] - heights[i] <= k: return 0 drop_left = heights[i] + visit(i + 1, j) pop_right = visit(i, j - 1) + heights[j] - (heights[i] + k) return min(drop_left, pop_right) return visit(0, len(heights) - 1) """ DP version from bottom-up. visit(i, j) depends on: - visit(i+1, j) recurse on solutions of len - 1 - visit(i, j-1) recurse on solutions of len - 1 So you can visit by increasing delta between i and j => Space complexity decreased to O(N) """ def min_removal_dp2(heights, k): if not heights: return 0 heights.sort() n = len(heights) memo = [0] * n for delta in range(1, n): new_memo = [0] * n for i in range(n - delta): j = i + delta if heights[j] - heights[i] <= k: new_memo[i] = 0 else: drop_left = heights[i] + memo[i+1] pop_right = memo[i] + heights[j] - (heights[i] + k) new_memo[i] = min(drop_left, pop_right) memo = new_memo return memo[0] """ But you can also do this problem in a greedy fashion [1, 2, 5, 5, 5, 5], k = 3 First idea (WRONG): - compare the cost of dropping lowest value (here 1) versus the cost of adapting the next values - the first time you do not drop, there is no reason to drop anymore (the minimum is still there...) BUT THIS DOES NOT WORK: you have to keep trying for every start point Time complexity is O(N**2) Space complexity is O(1) """ # TODO - find explanation of why early cutting does not work... def min_removal(heights, k): if not heights: return 0 heights.sort() def remove_top_cost(val, heights): cost = 0 cutoff = val + k for h in reversed(heights): if h <= cutoff: break cost += h - cutoff return cost min_cost = remove_top_cost(heights[0], heights) drop_cost = 0 for start in range(1, len(heights)): drop_cost += heights[start-1] right_removals = remove_top_cost(heights[start], heights[start:]) # TODO - try a break somewhere here... wrong greedy criteria? min_cost = min(min_cost, drop_cost + right_removals) return min_cost
2314a35958a26dceadecb84ad90cc131aa88a5e8
AshkenSC/Programming-Practice
/LeetCode/0150. Evaluate Reverse Polish Notation.py
974
3.625
4
''' 150. Evaluate Reverse Polish Notation 根据 逆波兰表示法,求表达式的值 思路:用栈存储数字,遇到运算符就取出栈顶两个计算,放进栈里。 ''' class Solution: def evalRPN(self, tokens: List[str]) -> int: num_stack = list() for token in tokens: if token == '+': a = num_stack.pop() b = num_stack.pop() num_stack.append(a + b) elif token == '-': a = num_stack.pop() b = num_stack.pop() num_stack.append(b - a) elif token == '*': a = num_stack.pop() b = num_stack.pop() num_stack.append(a * b) elif token == '/': a = num_stack.pop() b = num_stack.pop() num_stack.append(int(b / a)) else: num_stack.append(int(token)) return num_stack[0]
bfe8f78a6a64ebef5e6f33a2afb2792fe77628a1
ictcubeMENA/Training_one
/codewars/7kyu/doha22/shortest_word/bench_test.py
1,832
3.6875
4
from shortest_word import find_short from shortest_word import find_short ,find_short2 def test(benchmark): assert benchmark(find_short, "bitcoin take over the world maybe who knows perhaps") == 3 def test2(benchmark): assert benchmark(find_short2, "bitcoin take over the world maybe who knows perhaps") == 3 '''''''''' ------------------------------------------------------------------------------------- benchmark: 2 tests ------------------------------------------------------------------------------------ - Name (time in us) Min Max Mean StdDev Median IQR Outliers OPS (Kops/s) Rounds Iteration s --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - test2 6.5685 (1.0) 6,063.5096 (1.0) 21.9342 (1.42) 88.4357 (1.0) 14.7790 (1.06) 3.2842 (1.0) 351;2683 45.5909 (0.71) 29348 1 test 7.3895 (1.12) 10,243.5133 (1.69) 15.4903 (1.0) 94.9479 (1.07) 13.9580 (1.0) 7.3895 (2.25) 101;658 64.5564 (1.0) 25914 1 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - Legend: Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd Quartile. OPS: Operations Per Second, computed as 1 / Mean ================================================================================= 2 passed in 4.43 seconds ================================================================================= '''''''''
4d566b935b38a51df7c7eb0bb193aca170952b6e
Adarsh-Liju/Python-Course
/inheritance_sample.py
707
4.5
4
''' Inheritance Syntax: class Base(object) Base_Body Derived(Base) Derived_Body ''' #Example 1 class Parent: pass class Son(Parent): pass print(issubclass(Son,Parent)) # issubclass(Derived_Class,Base_Class) : returns True #Example 2 class Debian: def rel_date1(self): print("Debian was released on 1993") class Ubuntu(Debian):# inheriting Debian class def rel_date2(self): print("Ubuntu was released on 2002") a=Ubuntu() # calling derived class Ubuntu a.rel_date1() a.rel_date2() ''' When we create an object of the derived class, we invoke the constructor of the derived class which in turn calls the base class constructor on the base class sub object. '''
068ce0e9e636aa44d071ab73b299109dd8928328
Iruyan-Zak/py-tmp
/position.py
303
3.78125
4
class Vector2: def __init__(self, x, y): self.x = x self.y = y def __add__(self, v): return Vector2(self.x + v.x, self.y + v.y) def __repr__(self): return "Vector2({},{})".format(self.x, self.y) v1 = Vector2(2,5) v2 = Vector2(3.5, -1) v1 += v2 print(v1)
1b56ac9127a28ba87b29d11601a200783eb3cdf7
antonkrupin/algorithms
/28_tasks/TreeOfLife.py
3,680
3.6875
4
def TreeOfLife(treeHeight, treeWidth, years, tree): for x in range(len(tree)): replacedString = tree[x].replace('+','1') replacedString = replacedString.replace('.','0') tree[x] = replacedString yearsCounter = 0 while(yearsCounter < years): yearsCounter += 1 #нечетный год if(yearsCounter%2 != 0): for x in range(len(tree)): treeString = list(tree[x]) for y in range(len(treeString)): treeChar = treeString[y] if(treeChar != '.'): treeChar = int(treeChar) treeChar += 1 treeChar = str(treeChar) treeString[y] = treeChar if(treeChar == '.'): treeChar = '1' treeString[y] = treeChar tree[x] = treeString #четный год if(yearsCounter%2 == 0): deadCoords = [] for x in range(len(tree)): treeString = list(tree[x]) for y in range(len(treeString)): treeChar = treeString[y] if(treeChar != '.'): treeChar = int(treeChar) treeChar += 1 treeChar = str(treeChar) treeString[y] = treeChar if(treeChar == '.'): treeChar = '1' treeString[y] = treeChar tree[x] = treeString for x in range(len(tree)): treeString = tree[x] for y in range(len(treeString)): if(treeString[y] != '.' and treeString[y] != '.3'): treeString[y] = int(treeString[y]) if(treeString[y] >= 3): treeString[y] = '.' deadCoords.append([x,y]) for x in range(len(deadCoords)): if(deadCoords[x][0] == 0): coordX = deadCoords[x][0] coordY = deadCoords[x][1] tree[coordX+1][coordY] = '.' elif(deadCoords[x][0] == len(tree)-1): coordX = deadCoords[x][0] coordY = deadCoords[x][1] tree[coordX-1][coordY] = '.' else: coordX = deadCoords[x][0] coordY = deadCoords[x][1] tree[coordX+1][coordY] = '.' tree[coordX-1][coordY] = '.' if(deadCoords[x][1] == 0): coordX = deadCoords[x][0] coordY = deadCoords[x][1] tree[coordX][coordY+1] = '.' elif(deadCoords[x][1] == len(tree[0])-1): coordX = deadCoords[x][0] coordY = deadCoords[x][1] tree[coordX][coordY-1] = '.' else: coordX = deadCoords[x][0] coordY = deadCoords[x][1] tree[coordX][coordY+1] = '.' tree[coordX][coordY-1] = '.' for x in range(len(tree)): for y in range(len(tree[x])): if(tree[x][y] != '.'): tree[x][y] = '+' for x in range(len(tree)): string = '' for y in range(len(tree[x])): string = string + str(tree[x][y]) tree[x] = string return tree
d1900cf4ef9a7928120d6288e562ac9107d9ead1
DenysShvets/LaboratoryWork8
/1.3.1(2).py
1,178
3.84375
4
import numpy as np while True: while True: try: n, m = 3,3 #задаем размерность матрицы a = np.zeros((n, m), dtype=int) #выделяем место для массива b = np.zeros((m, n), dtype=int) #выделяем место для массива break except ValueError: #проверка на ошибки (вводить можно только цифры) print('Only nums') for i in range(n): for j in range(m): a[i,j]=int(input(f'A[{i},{j}]=')) #задается значение матрицы пользователем print(f'Your matrix: \n {a}') for i in range(n): for j in range(m): #произведение транспонирования матрицы new = a[j, i] b[i, j] = new print(f'Your new matrix: \n {b}') result = input('Do you want to retry.If yes enter 1 if no something else') if result == '1': #перезапуск программы по нажатию continue else: break
0f25678348d22c06de6b9bfab6d53757fe8fea7f
ChronicStone/Python_philippe
/le_wagon_exercises/ex4_playgroundRefactoring/playground_refactoring.py
339
3.921875
4
def circle_math(radius): return [3.141592653589793*(radius*2), 3.141592653589793*(radius*radius)] print(circle_math(3)) values = circle_math(5) print(f"Radius=5 => Perimeter={round(values[0], 1)}, Area={round(values[1], 1)}") values = circle_math(6) print(f"Radius=6 => Perimeter={round(values[0], 1)}, Area={round(values[1], 1)}")
8a2bf00edc8b65bcdff4f1b6b8533ec1b8aba9d8
goalstrack/python-training-Day1
/python-training/arithmaticoperation.py
165
3.65625
4
x=12.4 y=2.7 print('sum is= ',x+y) print(x-y) print(x*y) print(x/y) #floor division print(x//y) #power of operator print(x**y) print(x%y)
716339cd9e1994e296c0a15d168cfa83845dde47
chris-purcell/lpthw
/scrape.py
367
3.5
4
#!/usr/bin/env python import requests from bs4 import BeautifulSoup url = "http://www.rackspace.com" r = requests.get(url) soup = BeautifulSoup(r.content) links = soup.find_all("a") for link in links: print "<a href='%s'>%s</a>" %(link.get("href"), link.text) g_data = soup.find_all("div", {"class": "info"}) for item in g_data: print item.contents[0]
d1d38e78c193e8caac9b1ab0345f75fe36452931
deniseicorrea/Aulas-de-Python
/python/ex040.py
295
3.921875
4
n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) media = (n1 + n2) / 2 print(f'A média desse aluno é {media}') if media < 5.0: print('Reprovado') elif media >= 5.0 and media < 7: print('Recuperaçao') elif media >= 7.0: print('Aprovado')
be782e6b776ad1d579f9e02c02822b37a7334f8c
AbiramiRavichandran/DataStructures
/Tree/MirrorTree.py
1,180
3.796875
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def mirror(self): lnode = self.right.mirror() if self.right else None rnode = self.left.mirror() if self.left else None self.left = lnode self.right = rnode return self def in_order_traversal(self): elements = [] if self.left: elements += self.left.in_order_traversal() elements.append(self.data) if self.right: elements += self.right.in_order_traversal() return elements def count_leaf_nodes(self): if self.left is None and self.right is None: return 1 l_count = self.left.count_leaf_nodes() if self.left else 0 r_count = self.right.count_leaf_nodes() if self.right else 0 return l_count + r_count if __name__ == "__main__": root = Node(1) root.left = Node(3) root.right = Node(2) root.right.left = Node(5) root.right.right = Node(4) print(root.in_order_traversal()) root.mirror() print(root.in_order_traversal()) print(root.count_leaf_nodes())
8cc94edbe41ae017b7593618b5df0b4e20da16d4
eMUQI/Python-study
/python_book/basics/chapter04_list_operation/04-01.py
132
3.84375
4
list_of_pizza = ["pizza1","pizza2","pizza3"] for pizza in list_of_pizza: print("I like %s"%pizza) print("I really love pizza!")
5d67061ad2e0b2c36f2a6e7d6772618799c689db
gullihans/100DaysOfCode
/Day23/car_manager.py
272
3.515625
4
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 class CarManager(Turtle): def __init__(self): super().__init__() self.color(random.choice(COLORS))
930b8c75369499186b55a83d141b04859d676a0e
michaelkornblum/python-studies
/object-oriented/cat.py
682
4.46875
4
#Given the below class: class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cats cat1 = Cat('Michael', 50) cat2 = Cat('Sheila', 52) cat3 = Cat('Roosevelt', 15) # 2 Create a function that finds the oldest cat def find_oldest(*args): cats = [] for cat in args: cats.append(cat.__dict__) cat_ages = [] for cat in cats: cat_ages.append(cat['age']) return max(cat_ages) # 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2 print(f'The oldest cat is {find_oldest(cat1, cat2, cat3)} years old')
9ecbd36f8882e44edd90a870151fd529eda944e0
RafaelMarinheiro/CS5220-MatMul
/lecture/lec01plot.py
1,498
4.125
4
import matplotlib.pyplot as plt import numpy as np def make_speedup_plot(n, rmax, tc, tt): """Plots speedup for student counting exercise. Plots the speedup for counting a class of students in parallel by rows (assuming each row has equal student counts) vs just counting the students. Args: n: Number of students in the class rmax: Maximum number of rows to consider tc: Time to count one student tt: Time to add a row count into a tally """ r = np.arange(1,rmax+1) ts = n*tc tp = ts/r + r*tt speedup = ts/tp plt.plot(r, speedup) plt.xlabel('Number of rows') plt.ylabel('Speedup') def make_speedup_file(fname, n, rmax, tc, tt): """Plots speedup for student counting exercise. This is exactly like make_speedup_plot, but instead of generating a plot directly, we generate a data file to be read by pgfplots. Args: fname: Output file name n: Number of students in the class rmax: Maximum number of rows to consider tc: Time to count one student tt: Time to add a row count into a tally """ ts = n*tc with open(fname, 'w') as f: for r in range(1,rmax+1): tp = ts/r + r*tt f.write('%d %g\n' % (r, ts/tp)) if __name__ == "__main__": n = 100 rmax = 12 tc = 0.5 tt = 3 make_speedup_file('lec01plot.dat', n, rmax, tc, tt) make_speedup_plot(n, rmax, tc, tt) plt.savefig('lec01plot.pdf')
9922b6dee796e31ce4906177d9cdf08bcefc578e
BrindhaS/Python-Problems
/strings.py
381
3.734375
4
def substrings(string): length = len(string)+1 return [string[x:y] for x in range(length) for y in range(length) if string[x:y]] x=int(input('Enter test cases')) y=int(input('Enter length')) while(x>0): s = input('Enter string') lst = substrings(s) new_list = list(filter(lambda w:w[0]==w[len(w)-1], lst)) print(len(new_list)) x=x-1
9cbc562d5da3be23506d70cd78e61af7733bdf6e
Nika-C/Bioinformatics_Genome-Answers
/bioinformatics_2_2.py
101
3.78125
4
Str = raw_input('Enter a string: ') L = list(Str) print 'The string length is ' + str(len(L)) + '.'
7d7e4a0ca5efbab70b87cdbd62f5b93475b10afb
GorobetsYury/Python_beginning
/lesson_1_task_3.py
400
3.890625
4
# Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, # пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. n = int(input('Введите число n: ')) nn = n*10 + n nnn = n*100 + nn sum_ = n + nn + nnn print(f'Сумма чисел n + nn + nnn равна: {n} + {nn} + {nnn} = {sum_}')
09a678b800dd6b50d7b9f711e38f24afd2713137
xinbeiliu/leetcode_easy_collection
/array/plus_one.py
781
4.03125
4
# Given a non-empty array of digits representing a non-negative integer, plus one to # the integer. The digits are stored such that the most significant digit is at the # head of the list, and each element in the array contain a single digit. You may # assume the integer does not contain any leading zero, except the number 0 itself. # Input: [1,2,3] # Output: [1,2,4] # Explanation: The array represents the integer 123. # Input: [4,3,2,1] # Output: [4,3,2,2] # Explanation: The array represents the integer 4321. def plus_one(digits): result = '' for num in digits: result += str(num) result = int(result) result += 1 result = str(result) ans = [] for num in result: ans.append(int(num)) return ans print(plus_one([1,2,9]))
70cbd0ab6a8a23cb07fcb7124946c7fc9a64b1c8
ritwikbera/leetcode
/quickselect.py
863
3.515625
4
import random def Partition(a): if len(a)==1: return([],a[0],[]) if len(a)==2: if a[0]<=a[1]: return([],a[0],a[1]) else: return([],a[1],a[0]) p = random.randint(0,len(a)-1) pivot = a[p] right = [] left = [] for i in range(len(a)): if not i == p: if a[i] > pivot: right.append(a[i]) else: left.append(a[i]) return(left, pivot, right) def QuickSelect(a,k): (left,pivot,right) = Partition(a) if len(left)==k-1: result = pivot elif len(left)>k-1: result = QuickSelect(left,k) else: result = QuickSelect(right,k-len(left)-1) return result if __name__ == '__main__': N = 10; k = 4; a = [random.randint(1,100) for i in range(N)] print('Input array: ', a) print('k =', k) b = QuickSelect(a,k) print('kth smallest element: ', b)
3d6e94607ecbf3b77af5c0c11086fa107d7ab2aa
PatrickUncle/python
/猜数字欢乐游戏.py
442
3.859375
4
import random #生成随机数 x = random.randint(0,100) #使用while进行无限循环 while 1: #获取用户输入 guess = input("请输入您的猜想数字:") guess = int(guess) #判断用户输入数字与随机数的大小相等关系 if guess == x: print("you are so smart!") break else: if guess < x: print("small,try again") else: print("big.try again!")
d40bd002df923296a879d2ff2ade45096d25477d
bswathireddy/learning
/leetcode/intersection-lists.py
329
3.65625
4
def intersection(nums1, nums2): output = [] i = 0 while i <= len(nums1)-1: for j in nums2: if nums1[i] == j: if j not in output: output.append(j) else: continue i += 1 return output print(intersection([1],[1]))
e047b97c9bfbad4535585f198882f88d1c8bc34a
rayandas/100Python
/Day3/13.py
441
4
4
''' Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 ''' w = input() letter, digit = 0, 0 for i in w: if (i>='a' and i<='z') or (i>='A' and i<='Z'): letter += 1 if (i>='0' and i<='9'): digit += 1 print("Letters %d \n Digit %d"%(letter,digit))