blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ed878f5c85a164124b98a12df55e0d462592b4dd
marco-c/gecko-dev-wordified
/third_party/python/rsa/rsa/prime.py
4,222
3.53125
4
# - * - coding : utf - 8 - * - # # Copyright 2011 Sybren A . St vel < sybren stuvel . eu > # # Licensed under the Apache License Version 2 . 0 ( the " License " ) ; # you may not use this file except in compliance with the License . # You may obtain a copy of the License at # # http : / / www . apache . org / licenses / LICENSE - 2 . 0 # # Unless required by applicable law or agreed to in writing software # distributed under the License is distributed on an " AS IS " BASIS # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied . # See the License for the specific language governing permissions and # limitations under the License . ' ' ' Numerical functions related to primes . Implementation based on the book Algorithm Design by Michael T . Goodrich and Roberto Tamassia 2002 . ' ' ' __all__ = [ ' getprime ' ' are_relatively_prime ' ] import rsa . randnum def gcd ( p q ) : ' ' ' Returns the greatest common divisor of p and q > > > gcd ( 48 180 ) 12 ' ' ' while q ! = 0 : if p < q : ( p q ) = ( q p ) ( p q ) = ( q p % q ) return p def jacobi ( a b ) : ' ' ' Calculates the value of the Jacobi symbol ( a / b ) where both a and b are positive integers and b is odd : returns : - 1 0 or 1 ' ' ' assert a > 0 assert b > 0 if a = = 0 : return 0 result = 1 while a > 1 : if a & 1 : if ( ( a - 1 ) * ( b - 1 ) > > 2 ) & 1 : result = - result a b = b % a a else : if ( ( ( b * b ) - 1 ) > > 3 ) & 1 : result = - result a > > = 1 if a = = 0 : return 0 return result def jacobi_witness ( x n ) : ' ' ' Returns False if n is an Euler pseudo - prime with base x and True otherwise . ' ' ' j = jacobi ( x n ) % n f = pow ( x n > > 1 n ) if j = = f : return False return True def randomized_primality_testing ( n k ) : ' ' ' Calculates whether n is composite ( which is always correct ) or prime ( which is incorrect with error probability 2 * * - k ) Returns False if the number is composite and True if it ' s probably prime . ' ' ' # 50 % of Jacobi - witnesses can report compositness of non - prime numbers # The implemented algorithm using the Jacobi witness function has error # probability q < = 0 . 5 according to Goodrich et . al # # q = 0 . 5 # t = int ( math . ceil ( k / log ( 1 / q 2 ) ) ) # So t = k / log ( 2 2 ) = k / 1 = k # this means we can use range ( k ) rather than range ( t ) for _ in range ( k ) : x = rsa . randnum . randint ( n - 1 ) if jacobi_witness ( x n ) : return False return True def is_prime ( number ) : ' ' ' Returns True if the number is prime and False otherwise . > > > is_prime ( 42 ) False > > > is_prime ( 41 ) True ' ' ' return randomized_primality_testing ( number 6 ) def getprime ( nbits ) : ' ' ' Returns a prime number that can be stored in ' nbits ' bits . > > > p = getprime ( 128 ) > > > is_prime ( p - 1 ) False > > > is_prime ( p ) True > > > is_prime ( p + 1 ) False > > > from rsa import common > > > common . bit_size ( p ) = = 128 True ' ' ' while True : integer = rsa . randnum . read_random_int ( nbits ) # Make sure it ' s odd integer | = 1 # Test for primeness if is_prime ( integer ) : return integer # Retry if not prime def are_relatively_prime ( a b ) : ' ' ' Returns True if a and b are relatively prime and False if they are not . > > > are_relatively_prime ( 2 3 ) 1 > > > are_relatively_prime ( 2 4 ) 0 ' ' ' d = gcd ( a b ) return ( d = = 1 ) if __name__ = = ' __main__ ' : print ( ' Running doctests 1000x or until failure ' ) import doctest for count in range ( 1000 ) : ( failures tests ) = doctest . testmod ( ) if failures : break if count and count % 100 = = 0 : print ( ' % i times ' % count ) print ( ' Doctests done ' )
0e86fc33e75f4301bf4d52192b434c25cda7ad80
hackingmath/challenges
/LeetCode/star.py
655
3.625
4
from itertools import combinations def lowest(a,b): if a == 0 or b == 0: return True if a / b not in [1,-1]: print(a,b) return False return True def align(arr): pairs = 0 for pair in combinations(arr,2): x,y = pair[0][0]-pair[1][0],pair[0][1]-pair[1][1] if lowest(x,y): pairs += 1 return pairs with open("star.txt",'r') as f: t = int(f.readline()) for i in range(t): n=int(f.readline()) stars = list() for i in range(n): stars.append([int(x) for x in f.readline().split()]) print(align(stars)*2)
13cd737b8f9a3ec99760e9e3dd5aa54e29e56764
ebyau/guessing-game
/assignment.py
1,880
3.890625
4
import random def play_mind_game(): first_list = list(range(10)) random.shuffle(first_list) digits = (first_list[:3]) print(digits) lives = 5 while True: entry = input("hello there! please any 3 digit number") present = [] c = 0 lives -= 1 print(f"{lives} chances left") if lives == 0: print(f"thanks for trying") break else: continue if len(entry) != 3: print("Only 3 digit numbers allowed") continue try: int(entry) / 3 entries = list(entry) for x in entries: if int(x) in digits: print(f"{x} is a close") present.append(int(x)) else: pass if len(present) == 0: print("Nope") continue else: for i in present: index_entries = entries.index(str(i)) index_digits = digits.index(i) if index_digits == index_entries: print(f"{i} is a match ") c += 1 else: print(f"but {i} is in the wrong position") continue if c == 3: print(f"{entry} is the correct number") again = input("Do you want to play again") if again == "yes": play_mind_game() else: print("Thanks bye see ya!") break else: continue except ValueError: print("Only 3 digit numbers are allowed") continue play_mind_game()
3d249105e59c988599324efca69b1dd98550c8c5
Brice-76/ATP13
/Ex2.py
4,524
3.859375
4
from Ex1 import Node class BinaryTree : def __init__(self,root): self.__root=root def get_root(self): return self.__root def is_root(self,node): if self.__root == node : return True else : return False def size(self,node): if node == None : return 0 if node.get_left() == None and node.get_right() == None : return 1 else : return 1+self.size(node.get_right())+self.size(node.get_left()) def size_2(self, node):# professeur if node is None: return 0 else: return self.size(node.get_left()) + 1 + self.size(node.get_right()) def print_value(self,node): if node == None : return if node.get_left() == None and node.get_right() ==None : print(node) else : print(node) self.print_value(node.get_left()) self.print_value(node.get_right()) def print_value_2(self,node): if node is None: return " " else: return self.print_value_2(node.get_left()) + self.print_value_2(node.get_right()) def sum_value(self,node): if node== None : return 0 if node.get_left() == None and node.get_right() ==None : return node.get_val() else : return node.get_val()+self.sum_value(node.get_right())+self.sum_value(node.get_left()) def numberLeaves(self, node) : if node==None : return 0 if node.get_left() == None and node.get_right() == None : return 1 else : return self.numberLeaves(node.get_right())+self.numberLeaves(node.get_left()) def numberInternalNodes(self, node) : if node== None : return 0 if node.get_left() == None and node.get_right() == None : return 0 else : return 1+self.numberInternalNodes(node.get_right())+self.numberInternalNodes(node.get_left()) def height(self, node) : if node is None : return 0 else : gauche=1+self.height(node.get_right()) droite=1+self.height(node.get_left()) return max(gauche-1,droite-1) # pour enlever la hauteur de la racine def belongs(self, node, val) : if node is None : return 0 if node.get_val() is val : return 1 else : a=self.belongs(node.get_right(),val) b=self.belongs(node.get_left(),val) if a == 1 or b == 1 : return True def ancestors(self, node, val, lst=[]) : #qui affiche les antécédents d'un noeud ayant la valeur val if node == None : return else : lst.append(node.get_val()) self.ancestors(node.get_left(),val) self.ancestors(node.get_right(),val) if val in lst : return def ancestors_2(self,node,val,lst=[]): def descendants(self, node, val) :#qui affiche les descendants d'un noeud ayant la valeur val if node is None : return False if int(node.get_val() )== int(val) : print('les descendants sont : ',node.get_right(),node.get_left()) else : self.descendants(node.get_right(),val) self.descendants(node.get_left(),val) if __name__ =='__main__' : N1=Node(12) Tree=BinaryTree(N1) N2=Node(5) N3=Node(17) N1.set_left(N2) N1.set_right(N3) N4=Node(4) N5=Node(6) N6=Node(19) N2.set_left(N4) N2.set_right(N5) N3.set_right(N6) N7=Node(3) N8=Node(18) N9=Node(21) N4.set_left(N7) N6.set_left(N8) N6.set_right(N9) N10=Node(1) #N9.set_right(N10) # # if __name__ == '__main__' : # a faire avec des set... # n6 = Node(6,None,None) # n7 = Node(21,None,None) # n8 = Node(18,None,None) # n9 = Node(3,None,None) # n5 = Node(4,None,n9) # n4 = Node(19,n7,n8) # n3 = Node(17,n4,None) # n2 = Node(5,n6,n5) # n1 = Node(12, n3, n2) Tree=BinaryTree(N1) #print(Tree.size(N1)) #print(Tree.size_2(N1)) #Tree.print_value(N1) #print(Tree.print_value_2(N1)) #print(Tree.sum_value(N1)) #print(Tree.numberLeaves(N1)) #print(Tree.numberInternalNodes(N1)) #print(Tree.belongs(N1,21)) #print(Tree.height(N1)) print(Tree.ancestors(N1,19)) Tree.descendants(N1,19)
4b492c9902354b4371a1ee168543f1438cda4f3e
logansdmi/spikeinterface
/spikeinterface/core/default_folders.py
2,096
3.640625
4
""" 'global_tmp_folder' is a variable that is generated or can be set manually. It is useful when we do extractor.save(name='name'). """ import tempfile from pathlib import Path ######################################## global temp_folder global temp_folder_set base = Path(tempfile.gettempdir()) / 'spikeinterface_cache' temp_folder_set = False def get_global_tmp_folder(): """ Get the global path temporary folder. """ global temp_folder global temp_folder_set if not temp_folder_set: base.mkdir(exist_ok=True) temp_folder = Path(tempfile.mkdtemp(dir=base)) return temp_folder def set_global_tmp_folder(folder): """ Set the global path temporary folder. """ global temp_folder temp_folder = Path(folder) global temp_folder_set temp_folder_set = True def is_set_global_tmp_folder(): """ Check is the global path temporary folder have been manually set. """ global temp_folder_set return temp_folder_set def reset_global_tmp_folder(): """ Generate a new global path temporary folder. """ global temp_folder temp_folder = Path(tempfile.mkdtemp(dir=base)) #  print('New global_tmp_folder: ', temp_folder) global temp_folder_set temp_folder_set = False ######################################## global dataset_folder dataset_folder = Path.home() / 'spikeinterface_datasets' global dataset_folder_set dataset_folder_set = False def get_global_dataset_folder(): """ Get the global dataset folder. """ global dataset_folder global dataset_folder_set if not dataset_folder_set: dataset_folder.mkdir(exist_ok=True) return dataset_folder def set_global_dataset_folder(folder): """ Set the global dataset folder. """ global dataset_folder dataset_folder = Path(folder) global temp_folder_set dataset_folder_set = True def is_set_global_dataset_folder(): """ Check is the global path dataset folder have been manually set. """ global dataset_folder_set return dataset_folder_set
ea815b7a6e6aad69da00092c48c48fa7451ee32a
citlali-trigos-raczkowski/introduction-to-computer-science
/6.0002/1-space-cows-transportation/ps1b.py
1,851
4.1875
4
########################### # 6.0002 Problem Set 1b: Space Change # Name: Citlali Trigos # Collaborators: none # Date: 6/12/20 #================================ # Part B: Golden Eggs #================================ # Problem 1 def dp_make_weight(egg_weights, target_weight): """ Find number of eggs to bring back, using the smallest number of eggs. Assumes there is an infinite supply of eggs of each weight, and there is always a egg of value 1. Parameters: egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk) target_weight - int, amount of weight we want to find eggs to fit memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation) Returns: int, smallest number of eggs needed to make target weight """ # BASE CASE: if no more egg options or target_weight met: return 0 # OTHERWISE: we always want the heaviest we can currently take so: # 1. sort eggs from largest to smallest # 2. if the largest is too heavy, remove it and return back # 3. else return while taking it & update both vars if egg_weights==[] or target_weight==0: return 0 sorted_eggs = sorted(egg_weights, reverse = True) if target_weight - sorted_eggs[0] < 0: return dp_make_weight(sorted_eggs[1:], target_weight) else: return 1 + dp_make_weight(sorted_eggs, target_weight - sorted_eggs[0]) # EXAMPLE TESTING CODE, feel free to add more if you'd like if __name__ == '__main__': egg_weights = (1, 5, 10, 25) n = 99 print("Egg weights = (1, 5, 10, 25)") print("n = 99") print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)") print("Actual output:", dp_make_weight(egg_weights, n)) print()
fec727642786580aabe819885b6f39ae7ce0a6ad
yangyuebfsu/ds_study
/leetcode_practice/1299.py
637
3.953125
4
*** 1299. Replace Elements with Greatest Element on Right Side Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. After doing so, return the array. Example 1: Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1] *** class Solution: def replaceElements(self, arr: List[int]) -> List[int]: i=len(arr)-2 largest=arr[-1] while i>-1: temp=arr[i] arr[i]=largest largest=max(temp, largest) i=i-1 arr[-1]=-1 return arr
fc1ce82c733f668d03dcf98c65d1a62202f07f93
simyy/leetcode
/binary-tree-inorder-traversal.py
877
3.953125
4
# -*- coding: utf-8 -*- # https://leetcode.com/problems/binary-tree-inorder-traversal/ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[in """ rs = [] self.recursion(root, rs) return rs def recursion(self, root, rs): if not root: return if root.left: self.recursion(root.left, rs) rs.append(root.val) if root.right: self.recursion(root.right, rs) if __name__ == '__main__': root = TreeNode(1) n1 = TreeNode(2) n2 = TreeNode(3) root.right = n1 n1.left = n2 s = Solution() print s.inorderTraversal(root)
b870496805ba1603bbdc2de2ef27f8693f915591
webclinic017/dyno
/src/strategies/random_trader.py
3,666
3.640625
4
import numpy as np import pandas as pd import Quandl # Necessary for obtaining financial data easily from backtest import Strategy, Portfolio class RandomForecastingStrategy(Strategy): """Derives from Strategy to produce a set of signals that are randomly generated long/shorts. Clearly a nonsensical strategy, but perfectly acceptable for demonstrating the backtesting infrastructure!""" def __init__(self, symbol, bars): """Requires the symbol ticker and the pandas DataFrame of bars""" self.symbol = symbol self.bars = bars def generate_signals(self): """Creates a pandas DataFrame of random signals.""" signals = pd.DataFrame(index=self.bars.index) signals['signal'] = np.sign(np.random.randn(len(signals))) # The first five elements are set to zero in order to minimise # upstream NaN errors in the forecaster. signals['signal'][0:5] = 0.0 return signals class MarketOnOpenPortfolio(Portfolio): """Inherits Portfolio to create a system that purchases 100 units of a particular symbol upon a long/short signal, assuming the market open price of a bar. In addition, there are zero transaction costs and cash can be immediately borrowed for shorting (no margin posting or interest requirements). Requires: symbol - A stock symbol which forms the basis of the portfolio. bars - A DataFrame of bars for a symbol set. signals - A pandas DataFrame of signals (1, 0, -1) for each symbol. initial_capital - The amount in cash at the start of the portfolio.""" def __init__(self, symbol, bars, signals, initial_capital=100000.0): self.symbol = symbol self.bars = bars self.signals = signals self.initial_capital = float(initial_capital) self.positions = self.generate_positions() def generate_positions(self): """Creates a 'positions' DataFrame that simply longs or shorts 100 of the particular symbol based on the forecast signals of {1, 0, -1} from the signals DataFrame.""" positions = pd.DataFrame(index=signals.index).fillna(0.0) positions[self.symbol] = 100*signals['signal'] return positions def backtest_portfolio(self): """Constructs a portfolio from the positions DataFrame by assuming the ability to trade at the precise market open price of each bar (an unrealistic assumption!). Calculates the total of cash and the holdings (market price of each position per bar), in order to generate an equity curve ('total') and a set of bar-based returns ('returns'). Returns the portfolio object to be used elsewhere.""" # Construct the portfolio DataFrame to use the same index # as 'positions' and with a set of 'trading orders' in the # 'pos_diff' object, assuming market open prices. portfolio = self.positions*self.bars['Open'] pos_diff = self.positions.diff() # Create the 'holdings' and 'cash' series by running through # the trades and adding/subtracting the relevant quantity from # each column portfolio['holdings'] = (self.positions*self.bars['Open']).sum(axis=1) portfolio['cash'] = self.initial_capital - (pos_diff*self.bars['Open']).sum(axis=1).cumsum() # Finalise the total and bar-based returns based on the 'cash' # and 'holdings' figures for the portfolio portfolio['total'] = portfolio['cash'] + portfolio['holdings'] portfolio['returns'] = portfolio['total'].pct_change() return portfolio
2aec4b785ee783cb24eec47483895334f3fceca2
jimmyjwu/chest_X-ray_diagnosis
/model/net.py
7,630
3.5
4
"""Defines the neural network, losss function and metrics""" import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision from sklearn.metrics import roc_auc_score class DenseNet169(nn.Module): """ The DenseNet169 model, with the classification layer modified to output 14 classes and forward() modified to also return feature vectors. Note: This model includes a sigmoid in its last layer. Do not place a sigmoid in the loss or accuracy functions. """ def __init__(self, parameters, return_features=False): """ Initializes the layers of the model. Arguments: parameters.out_size: (int) number of output classes output_features: (bool) whether forward() should output the feature vector for a given input in addition to the prediction """ super(DenseNet169, self).__init__() # Record whether user wants forward() to return feature vectors self.return_features = return_features # Obtain a standard DenseNet169 model pre-trained on ImageNet self.densenet169 = torchvision.models.densenet169(pretrained=True, drop_rate=parameters.dropout_rate) # Train only the last few/classification layers # for parameter in self.densenet169.parameters(): # parameter.requires_grad = False # By default, the input to the final layer has size 1024 number_of_features = self.densenet169.classifier.in_features # Replace the standard DenseNet169 last layer with a linear-sigmoid sequence with 14 outputs self.densenet169.classifier = nn.Sequential( nn.Linear(number_of_features, parameters.out_size), nn.Sigmoid() ) def forward(self, x): """ Runs a given input x through the network and returns: - The output/prediction for x - The feature vector for x, as defined in the figure below DenseNet runs the input through the following sequence of layers: +----------+ +----+ +---------------+ +----------+ x -->| features |-->|ReLU|-->|average pooling|--feature-->|classifier|--output--> +----------+ +----+ +---------------+ vector +----------+ See documentation: https://github.com/pytorch/vision/blob/master/torchvision/models/densenet.py Arguments: x: (Variable) a batch of images, of dimensions [batch_size, 3, 224, 224] Returns: output: (Variable) label probabilities for each image; dimensions [batch_size, 14] """ feature_vector = self.densenet169.features(x) feature_vector = F.relu(feature_vector, inplace=True) feature_vector = F.avg_pool2d(feature_vector, kernel_size=7, stride=1).view(feature_vector.size(0), -1) output = self.densenet169.classifier(feature_vector) # Return the feature vector if desired by user if self.return_features: return output, feature_vector else: return output class DenseNet121(nn.Module): """ The CheXNet model, with forward() modified to also return feature vectors. Note: This model includes a sigmoid in its last layer. Do not place a sigmoid in the loss or accuracy functions. """ def __init__(self, parameters, return_features=False): """ Initializes the layers of the model. Arguments: parameters.out_size: (int) number of output classes output_features: (bool) whether forward() should output the feature vector for a given input in addition to the prediction """ super(DenseNet121, self).__init__() # Record whether user wants forward() to return feature vectors self.return_features = return_features # Obtain a standard DenseNet121 model pre-trained on ImageNet self.densenet121 = torchvision.models.densenet121(pretrained=True, drop_rate=parameters.dropout_rate) # Train only the last few/classification layers # for parameter in self.densenet121.parameters(): # parameter.requires_grad = False # By default, the input to the final layer has size 1024 number_of_features = self.densenet121.classifier.in_features # Replace the standard DenseNet121 last layer with a linear-sigmoid sequence with 14 outputs self.densenet121.classifier = nn.Sequential( nn.Linear(number_of_features, parameters.out_size), nn.Sigmoid() ) def forward(self, x): """ Runs a given input x through the network and returns: - The output/prediction for x - The feature vector for x, as defined in the figure below DenseNet runs the input through the following sequence of layers: +----------+ +----+ +---------------+ +----------+ x -->| features |-->|ReLU|-->|average pooling|--feature-->|classifier|--output--> +----------+ +----+ +---------------+ vector +----------+ See documentation: https://github.com/pytorch/vision/blob/master/torchvision/models/densenet.py Arguments: x: (Variable) a batch of images, of dimensions [batch_size, 3, 224, 224] Returns: output: (Variable) label probabilities for each image; dimensions [batch_size, 14] """ feature_vector = self.densenet121.features(x) feature_vector = F.relu(feature_vector, inplace=True) feature_vector = F.avg_pool2d(feature_vector, kernel_size=7, stride=1).view(feature_vector.size(0), -1) output = self.densenet121.classifier(feature_vector) # Return the feature vector if desired by user if self.return_features: return output, feature_vector else: return output def loss_fn(outputs, labels): """ Compute the cross entropy loss given outputs and labels. Args: outputs: (Variable) dimension batch_size x 14 - output of the model labels: (Variable) dimension batch_size x 14 - label of every type of disease [0, 1] (1 represents contains such disease;) Returns: loss (Variable): cross entropy loss for all images in the batch Note: you may use a standard loss function from http://pytorch.org/docs/master/nn.html#loss-functions. This example demonstrates how you can easily define a custom loss function. """ weight = torch.mean(labels, 0) return F.binary_cross_entropy(outputs, labels, weight=weight) # -torch.sum(torch.add(torch.mul((1-weight), torch.mul(labels, torch.log(outputs))), # torch.mul(weight, torch.mul(1-labels, torch.log(1-outputs))))) def accuracy(outputs, labels): """ Compute the accuracy, given the outputs and labels for all images. Args: outputs: (np.ndarray) dimension batch_size x 14 - log softmax output of the model labels: (np.ndarray) dimension batch_size x 14 - label of every type of disease [0, 1] (1 represents contains such disease;) Returns: List of AUROCs of all classes. """ AUROCs = [] for i in range(outputs.shape[1]): AUROCs.append(roc_auc_score(labels[:, i], outputs[:, i])) return AUROCs # maintain all metrics required in this dictionary- these are used in the training and evaluation loops metrics = { 'accuracy': accuracy, # could add more metrics such as accuracy for each token type }
9fa9db3f12304c14849dc96d485b45cd3ba77658
1914866205/python
/pythontest/day41数学内置函数.py
634
3.859375
4
""" 数学内置函数 """, 10 # 长度 dic = {'a': 1, 'b': 3} print(len(dic)) a = [{'name': 'xiaoming', 'age': 18, 'gender': 'male'}, {'name': 'xiaohong', 'age': 19, 'gender': 'female'}] # 最大值 print(max(a, key=lambda x: x['age'])) # pow(x,y,z=Nome,/) x为底的y次幂,如果有z,取余 print(pow(3, 2, 4)) # 四舍五入,第二个参数代表小数点后保留几位 print(round(3.1415926535897962), 3) a = [1, 5, 4, 3, 5] # 求和 print(sum(a)) # 指定求和的初值为10 print(sum(a, 10)) # 求绝对值或负数的模 print(abs(-6)) # 分别取商和余数 print(divmod(10, 3)) # 定义复数 print(complex(1, 2))
eb30300767e2d0229d38f0d4a5fba27989f670bd
acheney/python-labs
/lab01/trobertson/fancy.py
335
3.96875
4
# fancy.py # Asks the user for their first, last, and nickname, then welcomes the user # # Tyler Robertson # January 4, 2013 def main() : first = input("Enter your first name: ") last = input("Enter your last name: ") nick = input("Enter your nickname: ") print("Welcome back, ",first," \"",nick,"\" ",last,"!",sep='') main()
dc814f401d6b589c35bbc21600e66e041ad97273
Shorokhov-A/repo-algorithms_python
/lesson_3/task_3_5.py
736
4.0625
4
numbers = (5, -5, -18, -10, 0, 5, 12, -3, -11, -19, -7, -3) print(numbers) negative_els = [] for item in numbers: if item < 0: negative_els.append(item) if negative_els: max_negative_el = negative_els[0] for item in negative_els: if item > max_negative_el: max_negative_el = item max_el_idx = [idx for idx in range(len(numbers)) if numbers[idx] == max_negative_el] print(f'Максимальный отрицательный элемент в массиве: {max_negative_el}\n' f'Позиция элементов в массиве: {", ".join(map(str, max_el_idx))}') else: print('В массиве отсутствуют отрицательные элементы.')
ac9eedd9f99dc895c4a6d6e460926830c7f2604a
gesmith19/mit
/ProblemSet6/ps6recur1.py
459
4.4375
4
def reverseString(aStr): """ Given a string, recursively returns a reversed copy of the string. For example, if the string is 'abc', the function returns 'cba'. The only string operations you are allowed to use are indexing, slicing, and concatenation. aStr: a string returns: a reversed string """ print aStr if aStr == '': return aStr else: return reverseString(aStr[1:]) + aStr[0]
60888df318772a1f4ee2fd56764df45aa8d61acb
abespitalny/CodingPuzzles
/Leetcode/reverse_integer.py
504
3.796875
4
def reverse(x: int) -> int: is_negative = False if x < 0: is_negative = True x = -x ans = 0 while x > 0: last_digit = x % 10 x //= 10 ans = (ans * 10) + last_digit if is_negative: ans = -ans # Checks if the answer overflowed the bounds of a 32-bit integer: if (ans >= (1 << 31)) or (ans < (-1 << 31)): return 0 return ans print(reverse(123)) print(reverse(-123)) print(reverse(120)) print(reverse(1534236469))
df3c88934a316d3aa6f28970a31ed2475eb9d4de
D-Girouard/mycode
/challenge1.py
241
3.609375
4
#!/usr/bin/env name= input ("STATE YOUR NAME SUCKA:") date= input ("WHAT DAY IS IT SUCKA:") color= input ("WHAT'S YOUR FAVORITE COLOR SUCKA: ") print ("HELLO, " + name + " happy " +date, "SUCKA!!!") print ("ALSO...." + color + " SUCKS!! ")
417ed556bd7460a78f2d238df3770b786bc95a6f
simonava5/Programming-and-Scripting-Assignments
/projecteuler5.py
373
3.609375
4
# Simona Vasiliauskaite # 02/03/2018 # Project Euler 5 # Exercise 5 # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? i = 1 for x in (range(2, 21)): # all the numbers from 2 to 20 if i % x > 0: # test if the remainder of i is more than 0 for n in range(2, 21): if (i*n) % x == 0: i *= n break print(i)
603ad3aa3fa3bbe327341aec70bd20fe9780eb09
HarsimratKM/python
/Assignment 1/versionControl.py
11,752
4
4
#versioncontrol.py # Author: Harsimrat Kaur # Last Modified by: Hrsimrat Kaur #Date last Modified: 23rd May 2013 #Program description: older version of the game #VERSION 0: #This version had only 2 decision level and no story, was built up using the dragon.py import time def displayIntro(): print ('You are stuck in ') print ('you see two caves. In one cave, the dragon is friendly') print ('and will share his treasure with you. The other dragon') print ('is greedy and hungry, and will eat you on sight.') print def chooseCave(): cave = '' while cave != '1' and cave != '2': print ('Which cave will you go into? (1 or 2)') cave = raw_input() return cave def checkCave(chosenCave): print ('You approach the cave...') time.sleep(2) print ('It is dark and spooky...') if chosenCave == "1": print ('you chose cave 1a') chosenCave = raw_input() if chosenCave == "1": print ('you chose cave 2a') elif chosenCave == "2": print ('you chose cave 2b') elif chosenCave == "2": print('you chose cave 1b') chosenCave = raw_input() if chosenCave == "1": print ('you chose cave 2c') elif chosenCave == "2": print ('you chose cave 2d') def main(): playAgain = 'yes' while playAgain == 'yes' or playAgain == 'y': displayIntro() caveNumber = chooseCave() checkCave(caveNumber) print ('Do you want to play again? (yes or no)') playAgain = raw_input() if __name__ == "__main__": main() #Version 0.1 #story added, third decision level added import time def displayIntro(): print ('You are driving on a lonely road on your roadtrip') time.sleep(2) print ('The fog starts to thickens.......') time.sleep(2) print ('You slow down since you cant see anything') time.sleep(2) print ('the last thing you remember is your car crashing into a weird figure') time.sleep(2) def chooseCave(): cave = '' while cave != 'left' and cave != 'right': print ('You wake up in cave, the walls are all covereg in human skulls and bones, its the Catacombs') time.sleep(2) print ('You look around to make sense of the place, you see a piece of paper and try reading whats written on it') time.sleep(2) print ('GET OUT OF HERE! FOLLOW THE CAVES, THERE IS ONLY ONE WAY OUT') time.sleep(2) print ('You see two way out of the room, which door do you go though? left or right?') cave = raw_input() return cave def checkCave(chosenCave): print ('You approach the cave...') time.sleep(2) print ('It is dark and spooky...') if chosenCave == "left": print ('You enter the next cave, theres a torch on the wall, you take it') print ('You see another two exits from the room, which room do you go to? left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You enter another room and yet again, there are two doors in front of you, left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You go into the room......Its a dead end!') print ('Just as you think about turning back, the walls start crumbling down on you and you......') elif chosenCave == "right": print ('You enter a room way bigger than the ones before, you go in deeper') print ('Suddenly, you hear a sound behind you, before you get the chance to turn back, you feel the hands that are about to snap your neck') elif chosenCave == "right": print ('You enter another room with another pile of bones in the center, there are right doors, left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You enter the room and get eaten to death by Zombies') elif chosenCave == "right": print ('The room is narrow and long, you go deeper....') print ('You hear the sound of a car, you start running towards it') print ('You found the way out of the catacombs!!!!!!') print ('Congratulations, you win :)') elif chosenCave == "right": print('You chose to go through the second door, the next room also has two exits, which door do you choose? left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You enter another room, you hear something, Its a ZOMBIE!') print ('you pick up one of the broken bones on the floor and stab it in its head left0 times') time.sleep(2) print ('You try to catch your breath but you know you cant stay for long in this place') print ('You see two caves, which one do you go into left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You go into the room and see its swarmed by zombies') print ('They sense you there, and get o you before you had the chance to turn back') elif chosenCave == "right": print ('The room is narrow and long, you go deeper....') print ('All of a sudden, a zombie jumps on you and bites you!') print ('You manage to kill the zombie, but you lost so much blood in th process that your body gives up') elif chosenCave == "right": print ('You enter the next room, theres a reek of rotten flesh all around the place') print ('You see another two exits, which one do you choose this time? left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You go left, and you see the night sky!!!!!') print ('Suddenly you feel your feet sinking into the ground') print ('Its a Marsh.....you get trapped and die') elif chosenCave == "right": print ('You find yoursef back in the room you started') print ('Only this time, you are not alone') print ('There are 4 zombie dogs in the room, you try to fight them but fail') def main(): playAgain = 'yes' while playAgain == 'yes' or playAgain == 'y': displayIntro() caveNumber = chooseCave() checkCave(caveNumber) print ('Do you want to play again? (yes or no)') playAgain = raw_input() if __name__ == "__main__": main() #Version 0.2 #Final refinement of the game, 1 and 2 replaced by left and right import time def displayIntro(): print ('You are driving on a lonely road on your roadtrip') time.sleep(2) print ('The fog starts to thickens.......') time.sleep(2) print ('You slow down since you cant see anything') time.sleep(2) print ('the last thing you remember is your car crashing into a weird figure') time.sleep(2) def chooseCave(): cave = '' while cave != 'left' and cave != 'right': print ('You wake up in cave, the walls are all covereg in human skulls and bones, its the Catacombs') time.sleep(2) print ('You look around to make sense of the place, you see a piece of paper and try reading whats written on it') time.sleep(2) print ('GET OUT OF HERE! FOLLOW THE CAVES, THERE IS ONLY ONE WAY OUT') time.sleep(2) print ('You see two way out of the room, which door do you go though? left or right?') cave = raw_input() return cave def checkCave(chosenCave): if chosenCave == "left": print ('You enter the next cave, theres a torch on the wall, you take it') time.sleep(2) print ('You see another two exits from the room, which room do you go to? left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You enter another room and yet again, there are two doors in front of you, left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You go into the room......Its a dead end!') time.sleep(2) print ('Just as you think about turning back, the walls start crumbling down on you and you......') elif chosenCave == "right": print ('You enter a room way bigger than the ones before, you go in deeper') time.sleep(2) print ('Suddenly, you hear a sound behind you, before you get the chance to turn back, you feel the hands that are about to snap your neck') elif chosenCave == "right": print ('You enter another room with another pile of bones in the center, there are right doors, left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You enter the room and get eaten to death by Zombies') elif chosenCave == "right": print ('The room is narrow and long, you go deeper....') time.sleep(2) print ('You hear the sound of a car, you start running towards it') time.sleep(2) print ('You found the way out of the catacombs!!!!!!') time.sleep(2) print ('Congratulations, you win :)') elif chosenCave == "right": print('You chose to go through the second door, the next room also has two exits, which door do you choose? left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You enter another room, you hear something, Its a ZOMBIE!') print ('you pick up one of the broken bones on the floor and stab it in its head left0 times') time.sleep(2) print ('You try to catch your breath but you know you cant stay for long in this place') print ('You see two caves, which one do you go into left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You go into the room and see its swarmed by zombies') print ('They sense you there, and get o you before you had the chance to turn back') elif chosenCave == "right": print ('The room is narrow and long, you go deeper....') print ('All of a sudden, a zombie jumps on you and bites you!') print ('You manage to kill the zombie, but you lost so much blood in th process that your body gives up') elif chosenCave == "right": print ('You enter the next room, theres a reek of rotten flesh all around the place') print ('You see another two exits, which one do you choose this time? left or right?') chosenCave = raw_input() if chosenCave == "left": print ('You go left, and you see the night sky!!!!!') print ('Suddenly you feel your feet sinking into the ground') print ('Its a Marsh.....you get trapped and die') elif chosenCave == "right": print ('You find yoursef back in the room you started') print ('Only this time, you are not alone') print ('There are 4 zombie dogs in the room, you try to fight them but fail') def main(): playAgain = 'yes' while playAgain == 'yes' or playAgain == 'y': displayIntro() caveNumber = chooseCave() checkCave(caveNumber) print ('Do you want to play again? (yes or no)') playAgain = raw_input() if __name__ == "__main__": main()
980168a00cc927abaa31dcf6e436814ed49e4dae
Pebaz/coding-problems
/py/10-11-19.py
1,167
3.90625
4
def show_matrix(matrix): for row in matrix: print(('{:<3}' * len(row)).format(*row)) def create_matrix(length): fill = iter(range(length ** 2 + 1)) return [ [next(fill) for i in range(length)] for i in range(length) ] def rotate_matrix(m): print('Before:') show_matrix(m) side = len(m[0]) zones = side // 2 print('') for i in range(zones): the_side = range(i, side - i) # Save each side top = [m[i][r] for r in the_side] left = [m[side - r - 1][i] for r in the_side] bot = [m[side - i - 1][side - r - 1] for r in the_side] right = [m[r][side - i - 1] for r in the_side] # Swap them for buf_index, r in enumerate(the_side): m[side - r - 1][i] = top [buf_index] # Left = Top m[side - i - 1][side - r - 1] = left [buf_index] # Bot = Left m[r][side - i - 1] = bot [buf_index] # Right = Bot m[i][r] = right[buf_index] # Top = Right print('After:') show_matrix(m) rotate_matrix(create_matrix(4))
3d5213329f4a1ce202fd13f399bf132cc1b4bae5
wenmengqiang/learn-python-the-hard-way
/ex24.py
899
3.828125
4
#encoding:utf-8 print "Let's practise everything." print 'You\' d need to know \'bout escape with \\ that do \n newlines and \t tabs.' poem =""" \t The lovely world with magic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\twhere there is none. """ print "-------------" print poem print "-------------" five=10-2+3-6 print "This should be five:%s"%five def secret_formula(started): jelly_beans=started*500 jars=jelly_beans /1000 crates=jars /100 return jelly_beans,jars,crates start_point=10000 beans,jars,crates=secret_formula(start_point) print "With a starting point of:%d"%start_point print "We'd have %d beans,%d jars,%d crates"%(beans,jars,crates) start_point=start_point /10 print "We can also do that this way:" print "We'd have %d beans,%d jars,and %d crates."%secret_formula(start_point)
04752e57b8035c274f67e4f4d4ef8179251d4bc3
chrislevn/Coding-Challenges
/Orange/KMP/Text_Editor.py
2,039
3.515625
4
def KMP_preprocess(p, prefix): """ Preprocess function for KMP algoritm Args: p (str): pattern string prefix (list): output prefix """ prefix[0] = 0 m = len(p) Len = 0 i = 1 while i < m: if p[i] == p[Len]: Len += 1 prefix[i] = Len i += 1 else: if Len != 0: Len = prefix[Len - 1] else: prefix[i] = 0 i += 1 def KMP_search(t, p, prefix): """ Search string in prefix Args: t (str): input string p (str): pattern string prefix (list): output prefix """ n = len(t) m = len(p) i = j = 0 count = 0 while i < n: if p[j] == t[i]: i += 1 j += 1 if j == m: count += 1 j = prefix[j - 1] elif i < n and p[j] != t[i]: if j != 0: j = prefix[j - 1] else: i += 1 return count def binary_process(left, right, string, freq): """ Check string in O(nlogn) complexity Args: left (int): starting index right (int): ending index string (str): check str freq (int): check frequency number """ global result while (left <= right): mid = (right + left) // 2 check = string[0:mid+1] prefix = [0] * len(check) KMP_preprocess(check, prefix) count = KMP_search(text, check, prefix) if count >= freq: result = check left = mid + 1 else: right = mid - 1 if __name__ == "__main__": text = input() original = input() freq = int(input()) count = '' result = '' binary_process(0, len(original)-1, original, freq) print(result if result != '' else 'IMPOSSIBLE')
b2921283d2ad1ee3329c81dfc14512f7b0808823
kameron-mcadams/Money-Counter
/money_counter.py
631
3.8125
4
pennies = int(input("How many pennies do you have?")) nickels = int(input("How many nickels do you have?")) dimes = int(input("How many dimes do you have?")) quarters = int(input("How many quarters do you have?")) halfDollars = int(input("How many half dollars do you have?")) dollars = int(input("How many dollars do you have?")) numPennies = pennies * 1 numNickels = nickels * 5 numDimes = dimes * 10 numQuarters = quarters * 25 numHalfDollars = halfDollars * 50 numDollars = dollars * 100 total = numPennies + numNickels + numDimes + numQuarters + numHalfDollars + numDollars money = total / 100 print("You have $" ,money, ".")
49e085c948960fce6a0a35acb72c87bb370e2c5a
RubyJing/100DaysStudy
/Day01-15/Day07/tuple_test.py
1,411
3.796875
4
import sys """ 使用元组: 与列表类似,也是一种容器数据类型,可以用一个变量(对象)来存数多个数据 不同点:元组的数据不能被修改 """ # 定义元组 t = ('今天', 7, True, 14.40) print(t) # 获取元组中的元素 print(t[0]) # 今天 print(t[3]) # 14.4 # 遍历元组中的值 for member in t: print(member, end=',') # 今天,7,True,14.4 print() # 重新给元组赋值 # t[0] = '罗云熙' # TypeError: 'tuple' object does not support item assignment # 变量t重新引用了新的元组,原来的元组将被垃圾回收 t = ('罗云熙', 7, True, 14.40) print(t) # ('罗云熙', 7, True, 14.4) # 将元组转换成列表 person = list(t) print(person) # ['罗云熙', 7, True, 14.4] # 列表是可以修改他的元素的 person[3] = '31.0' print('列表大小:', sys.getsizeof(person)) print(person) # ['罗云熙', 7, True, '31.0'] # 将列表转换成元组 tuple_new = tuple(person) print('元组大小:', sys.getsizeof(tuple_new)) print(tuple_new) # ('罗云熙', 7, True, '31.0') """ 思考: 为什么有了列表,还需要元组 1.元组中的元素无法修改: 如果不需要对元素进行添加、删除、修改的时候,可以考虑使用元组,(多线程) 当然如果一个方法要返回多个值,使用元组也是不错的选择。 2.元组在创建时间和占用的空间上优于列表 """
752dca251b3d236b2b7141e7cf5b8d8be465b162
KillToTheReal/Algorithms
/Sorting_algorithms/radix_sort.py
1,154
3.828125
4
def radix_sort(arr, decimal_places=2): counts = [0] * 10 len_arr = len(arr) # sort loop for step in range(decimal_places): temp_arr = [0] * len_arr print("Step",step) for item in arr: last_num = check_number(item, step) counts[last_num] += 1 # compute prefix sum for i in range(1, 10): counts[i] += counts[i-1] for i in range(len_arr - 1, -1, -1): item = arr[i] last_num = check_number(item, step) index_num = counts[last_num] - 1 counts[last_num] -= 1 temp_arr[index_num] = item arr = temp_arr counts = [0] * 10 del temp_arr print(arr) return arr def check_number(num, pos=0): if num < pos * 10: return 0 res = 0 for _ in range(pos+1): res = num % 10 num = num // 10 return res arr=[] a = input("Введите кол-во эл-тов массива: ") for i in range(int(a)): n = input() arr.append(int(n)) b = input("Введите максимальную степень десяти встречающуюся в массиве(10^n):") print("Sorted array", radix_sort(arr,int(b)))
ccde22affe7f01bff4b8d72e6d759c066b096230
INTO-CPS-Association/mono-camera-robot-tracking
/Code/Models/SquareModels.py
1,744
3.53125
4
class RobotSquare: def __init__(self, square, distance = None, angle = None, id = None): self._square = square self._angle = angle self._distance = distance self._id = id self._corners = None self._center = None self._setup(square) def _setup(self, square): if self._id is None: self._id = square["id"] self._corners = square["corners"] self._center = square["center"] def get_center(self, type = ''): if type == '': return self._center elif type.lower() == 'x': return self._center[0] elif type.lower() == 'y': return self._center[1] else: return self._center def get_id(self): return self._id def valid(self): return self._id > 0 def set_angle(self, angle, type = 'deg'): if type.lower() == 'deg': self._angle = angle elif type.lower() == 'rad': self._angle = math.radians(angle) else: self._angle = angle def get_angle(self, type = 'deg'): if self._angle == None: return -1 if type.lower() == 'deg': return self._angle elif type.lower() == 'rad': return math.radians(self._angle) else: return self._angle def set_distance(self, distance): self._distance = distance def get_distance(self): if self._distance == None: return -1 return self._distance def get_corners(self): return self._corners def print(self): print("ID: " + str(self._id)) print("Corners: " + str(self._corners)) print("Center: " + str(self._center)) print("Angle: " + str(self._angle)) print("Distance: " + str(self._distance))
27533f13e2b008478c40892f4ce47d917a02ec84
Vampirskiy/Algoritms_python
/unit3/Task 2.py
654
4.1875
4
# Task 2 # Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5, (индексация начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа. A = [8, 3, 15, 6, 4, 2] B = [] ind = 0 for i in A: if i % 2 == 0: B.append(ind) ind += 1 print(f'Индексы четных чисел: {B}')
ee2a267d0436551970b4bddede6a6296c7f422b8
j-vieira/AlgoritmosED
/python/lista1/exercicio3.py
135
3.65625
4
a = 5 #int print(a) a = 1 or 0 #boolean print(a) a = "a" #char print(a) a = 65/13*4+1 #float print(a) a = "teste" #string print(a)
c3e36b996fe37a864ab6d24f5c9b2f868a287c73
fo5u/basics-of-python
/7_classes_objects.py
1,692
4.21875
4
class PersonalInfo: def __init__(self): self.name = 'Alex' self.age = 25 self.grades = (44, 55, 66) def total(self): return sum(self.grades) / len(self.grades) student = PersonalInfo() print(student.name) print(student.age) print(student.grades) print(student.total()) # Or you can print them all print(student.name, "is", student.age, "years old", "and his grades", student.grades) # Example 1 class University: def __init__(self, name, location, rank): self.name = name self.location = location self.rank = rank school_1 = University(name='MIT', location='USA', rank=1) print(school_1.name) school_2 = University(name='Harvard', location='USA', rank=2) print(school_2.name) print(school_1.name, "and", school_2.name, "are both in the", school_1.location) # Example 2 class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) first_student = Student('Rose', 'Oxford') first_student.marks.append(44) first_student.marks.append(55) print(first_student.marks) print(first_student.average()) # Example 3 class Store: def __init__(self, name): self.name = name self.items = [] def add_item(self, name, price): '''Create a dictionary with keys name and price, and append that to self.items''' item = {'name': name, 'price': price} self.items.append(item) def stock_price(self): '''Add together all item prices in self.items and return the total''' return sum([item['price'] for item in self.items])
8eb9c255d19a7a2afd0e48e8be3e6b0e45c81f5d
RodolpheBeloncle/100-days-Python
/tip-calculator-start.py
832
4.125
4
print("Welcome to the tip Calculator") bill = input("What was the total bill ?: ") billStringToFloat = float(bill) #-------------------------------- amountOfTips = input("What percentage of tips would you like to give ? 10 ,12 or 15 : ") amountOfTipsStringToFloat = int(amountOfTips) #-------------------------------- numberOfPeople = input("How Many People to split the bill ? : ") numberOfPeopleStringToInt = int(numberOfPeople) #-------------------------------- def splitBillWithTips(totalBill,tips,nbPeople): peopleToSplit = totalBill / nbPeople percentageTip = tips totalToPay = round((peopleToSplit * (percentageTip/100)) + peopleToSplit,2) print(F"Each Person should pay {totalToPay}") #-------------------------------- splitBillWithTips(billStringToFloat,amountOfTipsStringToFloat,numberOfPeopleStringToInt)
4ce1533c8ab87fec1721d0d38c56c2e5bb9dc6d0
disaisoft/python-course
/project3/app.py
247
3.5625
4
from datetime import date from datetime import datetime #obtener la fecha actual. d = date.today() d.strftime("/%d/%m/%y") print(d) # obtener la fecha con el dia, mes, ano y la hora dt=datetime.now() dt.strftime("%A %d/%B/%y %H:%M:%S") print(dt)
864030d847c54e999486b41afe7e9e8f2fc0779c
daniel-reich/ubiquitous-fiesta
/suhHcPgaKdb9YCrve_18.py
276
4.21875
4
def even_or_odd(s): even = sum(int(i) for i in s if int(i) % 2 ==0); odd = sum(int(i) for i in s if int(i) % 2 ==1); if even == odd: return 'Even and Odd are the same'; elif odd > even: return "Odd is greater than Even"; return "Even is greater than Odd";
51dcb075e822e2bd48740ec10f22d9b3e304275e
matheusforlan/TST-P1
/afinidademusical/afinidade.py
404
3.53125
4
#coding:utf-8 def meu_in(elemento,sequencia): for e in sequencia: if e == elemento: return True return False def tem_afinidade(l1, l2): afinidade = 0 for c in range(len(l1)): if meu_in(l1[c],l2): afinidade += 1 if afinidade >= 3: return True return False l1 = ['zeze', 'bruno e marrone', 'joao', 'pedro', 'u2'] l2 = ['zeze', 'joao', 'u2', 'jquest'] assert tem_afinidade(l1, l2) == True
d518d89261e9c4f8277e3521f7bef923d66b7c9b
SmischenkoB/campus_2018_python
/Yurii_Smazhnyi/3/PokerHands.py
4,522
3.671875
4
suits = ("H", "D", "C", "S") cards = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A") categories = ("Straight Flush", "Four of a kind", "Full house", "Flush", "Straight", "Three of a kind", "Two pair", "One Pair", "High card") def is_flush(hand): """ Check is flush in hand :param hand: string hand with cards :hand type: str. :returns: bool result of check :rtype: bool. """ result = False for s in suits: if hand.count(s) == 5: result = True break return result def is_straight(hand): """ Check is straight in hand :param hand: string hand with cards :hand type: str. :returns: bool result of check :rtype: bool. """ card_in_row = 0 result = False for c in cards: if c in hand: card_in_row += 1 if card_in_row == 5: result = True break continue card_in_row = 0 return result def is_straight_flush(hand): """ Check is straight flush in hand :param hand: string hand with cards :hand type: str. :returns: bool result of check :rtype: bool. """ result = True if not is_flush(hand): result = False if not is_straight(hand): result = False return result def is_same_cards_in_hand(hand, count_of_cards): """ Check is some count of cards in hand :param hand: string hand with cards :param count_of_cards: count of card that mast be same :hand type: str. :count_of_cards: int. :returns: bool result of check :rtype: bool. """ result = False for c in cards: if hand.count(c) == count_of_cards: result = True return result def is_full_house(hand): """ Check is full house in hand :param hand: string hand with cards :hand type: str. :returns: bool result of check :rtype: bool. """ return is_same_cards_in_hand(hand, 2) and is_same_cards_in_hand(hand, 3) def is_four_of_a_kind(hand): """ Check is flush in hand :param hand: string hand with cards :hand type: str. :returns: bool result of check :rtype: bool. """ return is_same_cards_in_hand(hand, 4) def is_three_of_kind(hand): """ Check is three of kind in hand :param hand: string hand with cards :hand type: str. :returns: bool result of check :rtype: bool. """ return is_same_cards_in_hand(hand, 3) def is_two_pair(hand): """ Check is two pair in hand :param hand: string hand with cards :hand type: str. :returns: bool result of check :rtype: bool. """ pair_count = 0 for c in cards: if hand.count(c) == 2: pair_count += 1 return pair_count == 2 def is_one_pair(hand): """ Check is pair in hand :param hand: string hand with cards :hand type: str. :returns: bool result of check :rtype: bool. """ return is_same_cards_in_hand(hand, 2) def get_rank_of_hand(hand): """ Checks hand and returns it rank :param hand: string hand with cards :hand type: str. :returns: int score of hand :rtype: int. """ result = len(categories) if is_straight_flush(hand): result = 0 elif is_four_of_a_kind(hand): result = 1 elif is_full_house(hand): result = 2 elif is_flush(hand): result = 3 elif is_straight(hand): result = 4 elif is_three_of_kind(hand): result = 5 elif is_two_pair(hand): result = 6 elif is_one_pair(hand): result = 7 else: result = 8 return result def pick_best_poker_hands(list_of_hands): """ Take list of hands with cards and pick the best :param list_of_hands: list of strings with hand of cards :list_of_hands: list of strings. :returns: string best hand :rtype: str. """ best_hand_index = 0 best_hand_score = len(categories) for i in range(len(list_of_hands)): if(best_hand_score > get_rank_of_hand(list_of_hands[i])): best_hand_index = i return list_of_hands[best_hand_index] hands = ["4D 5S 6S 8D 3C", "2S 4C 7S 9H 10H", "3S 4S 5D 6H JH", "3H 4H 5C 6C JD"] print(pick_best_poker_hands(hands))
3656caba1f6f20699e14a45bf773df9ac80fa25a
Rushin95/LeetCode_Practice
/binary_tree_right_side_view.py
958
3.734375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] """ ans = [] if root: this_level = [root] ans.append(root.val) while this_level and root: new_level = [] for node in this_level: if node.left: new_level.append(node.left) if node.right: new_level.append(node.right) if len(new_level) > 0: right_node = new_level[-1] ans.append(right_node.val) this_level = new_level else: break return ans
02f70db5315d3417e2e43881d15febf87550bfc4
dheredia19/COMP-SCIENCE
/guess.py
436
3.953125
4
import random mine = random.randint(1,10) print("Guess my number, or not. I don't care...") def goback(): guess = int(input()) if guess == mine: print("Wow, smartypants, you did it. Now go away.") quit() else: print("Wrong! Of course you're wrong. I'm not surprised.") if guess < mine: print("Hint: my number is higher than your guess.") else: print("Hint: my number is lower than your guess.") goback() goback()
41bb47b99b047e4d1d64a4327567a5b2a35db73f
shincap8/holbertonschool-machine_learning
/math/0x04-convolutions_and_pooling/6-pool.py
1,780
3.96875
4
#!/usr/bin/env python3 """Function that performs pooling on images""" import numpy as np def pool(images, kernel_shape, stride, mode='max'): """Performs a convolution on images using multiple kernels Args: images: `numpy.ndarray` with shape (m, h, w) containing multiple grayscale images m: `int`, is the number of images h: `int`, is the height in pixels of the images w: `int`, is the width in pixels of the images c: `int`, is the number of channels in the image kernel_shape is a tuple of (kh, kw) containing the kernel shape for the pooling kh: `int`, is the height of the kernel kw: `int`, is the width of the kernel stride is a `tuple` of (sh, sw) sh: `int`, is the stride for the height of the image sw: `int`, is the stride for the width of the image mode: `str`, indicates the type of pooling max: indicates max pooling avg: indicates average pooling Returns: output: `numpy.ndarray` containing the convolved images """ c = images.shape[3] m, h, w = images.shape[0], images.shape[1], images.shape[2] kh, kw = kernel_shape[0], kernel_shape[1] sh, sw = stride[0], stride[1] nw = int(((w - kw) / stride[1]) + 1) nh = int(((h - kh) / stride[0]) + 1) pooled = np.zeros((m, nh, nw, c)) for i in range(nh): x = i * stride[0] for j in range(nw): y = j * stride[1] image = images[:, x:x + kh, y:y + kw, :] if mode == 'max': pooled[:, i, j, :] = np.max(image, axis=(1, 2)) else: pooled[:, i, j, :] = np.average(image, axis=(1, 2)) return pooled
033885210ef9177f6fa5f3d09d884351478da0e3
AlexisGrolleau/TP13
/Exercice2.py
1,504
3.859375
4
from Exercice1 import * class BinaryTree: def __init__(self,root): self.__root = root def getRoot(self): return self.__root def isRoot(self,Node): if Node == self.__root: return True else: return False def size(self, node): if node is None: return 0 else: return self.size(node.getLeft()) + 1 + self.size(node.getRight()) def sumValues(self,node): if node is None: return 0 else: return self.sumValues(node.getLeft()) + node.getVal() + self.sumValues(node.getRight()) def numberLeaves(self, node): if node is None: return 0 else: if node.getLeft() and node.getRight() is None: print("True") else: return self.numberLeaves(node.getLeft() + node.getRight()) arbre = BinaryTree(Node(12,None,None)) arbre.getRoot().setLeft(Node(5,None,None)) arbre.getRoot().getLeft().setLeft(Node(4,None,None)) arbre.getRoot().getLeft().setRight(Node(6,None,None)) arbre.getRoot().getLeft().getLeft().setLeft(Node(3,None,None)) arbre.getRoot().setRight(Node(17,None,None)) arbre.getRoot().getRight().setRight(Node(19,None,None)) arbre.getRoot().getRight().getRight().setLeft(Node(18,None,None)) arbre.getRoot().getRight().getRight().setRight(Node(21,None,None)) print(arbre.size(arbre.getRoot())) print(arbre.sumValues(arbre.getRoot())) print(arbre.numberLeaves(arbre.getRoot()))
3fb9a3a0fe1be1406a7637138a31955bb46ea3ec
mulder974/Escape-Game
/Programme_de_trad.py
2,290
3.84375
4
def decode_alien(): m=input("Saisissez la phrase à traduire: ") dict_alien_fr = { '.':'.', '!':'!', '?':'?', ',':',', '': '', '__': ' ', '/\\' : 'a', ']3': 'b', '(': 'c', '|)': 'd', '[-': 'e', '/=': 'f', '(_,': 'g', '|-|': 'h', '|': 'i', '_T': 'j', '/<': 'k', '|_': 'l', '|\\/|': 'm', '|\\|': 'n', '()': 'o', '|^': 'p', '()_': 'q', '/?': 'r', '_\\~': 's', '~|~': 't', '|_|': 'u', '\\/': 'v', '\\/\\/': 'w', '><': 'x', '`/': 'y', '~/_': 'z' } a=''.join(dict_alien_fr[i] for i in m.split(m[0])) print("\n" + "Voici la traduction en francais:" + "\n" + "\n" + a + "\n") def decode_fr(): m=input("Saisissez la phrase à traduire en alien: ") trad="" dict_fr_alien = { '.':'.', '!':'!', '?':'?', ',':',', '': '', ' ': '__', 'a': '/\\', 'b': ']3', 'c': '(', 'd': '|)', 'e': '[-', 'f': '/=', 'g': '(_,', 'h': '|-|', 'i': '|', 'j': '_T', 'k': '/<', 'l': '|_', 'm': '|\\/|', 'n': '|\\|', 'o': '()', 'p': '|^', 'q': '()_', 'r': '/?', 's': '_\\~', 't': '~|~', 'u': '|_|', 'v': '\\/', 'w': '\\/\\/', 'x': '><', 'y': '`/', 'z': '~/_' } a = m.lower() a = list(a) for i in a: if i == "é": a[a.index("é")] = "e" elif i =="è": a[a.index("è")] = "e" elif i =="ê": a[a.index("ê")] = "e" elif i == "à" : a[a.index("à")] = "a" elif i =="'" : a[a.index("'")]= " " m="".join(a) for i in m: trad+= "}"+ dict_fr_alien[i] print("\n" + "Voici la traduction en alien:" + "\n" + "\n" + trad + "\n") menu = """S'il vous plaît, faites votre choix: 1) traduction francais-alien 2) traduction alien-francais 0) quitter Your selection: """ print("Bienvenu dans l'outil de traduction ! ") user_input = input(menu) while user_input != "0": if user_input == "1": decode_fr() elif user_input == "2": decode_alien() else: print("Please select a number from 1 to 2, or 0 to exit") user_input = input(menu)
c54b48c5c6ecd38c87842e7e854874277eab584d
quando110704/DoHongQuan-C4T-HDT-B10
/session7/liSt.py
147
3.671875
4
items = ['com', 'pho', 'chao'] print(items) items.append('coca') print(items) new_items = input("new items: ") items.append(new_items) print(items)
b06fbff99e9c78a18fcdaf07fb9f9126e371f781
Ran1s/mvc-proj
/View.py
990
3.609375
4
class View: def __init__(self): pass # def __init__(self, controller): # self.controller = controller def set_controller(self, controller): self.controller = controller def print_question(self): print(self.current_question.value) def print_unkown_command(self, command): print("Ошибка: %s - неизвестная команда" % command) def get_answer(self): return input() def set_current_question(self, current_question): self.current_question = current_question def is_answer(self, answer): for ans in self.current_question.answers: if ans.value == answer: return True return False def show(self): self.print_question() answer = self.get_answer() while not self.is_answer(answer): self.print_unkown_command(answer) answer = self.get_answer() self.controller.set_answer(answer)
6617eef3b62b07baf4a4260cbdf62f654ab9e46c
greenfox-zerda-lasers/matheb
/week-03/day-3/08.py
1,293
4.03125
4
# Create a new class called `Person` that has a first_name and a last_name (takes it in it's constructor) # It should have a `greet` method that prints it's full name # Create a `Student` class that is the child class of `Person` # it should have a method to add grades # it should have a `salute` method that prints it's full name and the average of it's grades as well class Person(): def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def greet(self): print(self.first_name + self.last_name) class Student(Person): grades = [] count = 0 i = 0 #def __init__(self, first_name, last_name): #Person.__init__(self, first_name, last_name) #self.grade = grade def add_grades(self, grade): self.grades.append(grade) self.count = self.count + grade self.i = self.i + 1 def salute(self): print (self.first_name + self.last_name + str(self.count/self.i)) #student = Student("Kelly ", "Sheep", 5) #kelly = Person("Kelly ", "Sheep") kelly = Student("Kelly ", "Sheep ") kelly.greet() kelly.add_grades(1) kelly.add_grades(3) kelly.add_grades(5) kelly.add_grades(3) kelly.salute() #first.salute() sam = Person("Sam ", "Flower") sam.greet()
74af2cc01693f1c3d663aef4432ecaccbef8bc22
muhiqsimui/MatematikaGkAsik
/fibonaci.py
395
4.03125
4
#fibonaci # OLD CODE NOT GOOD TO SLOW def fibonaci(n): a,b = 0,1 while a<n: print(a, end=' ') a,b=b,a+b print() fibonaci(100) # THIS IS BETTER VERY FAST LIKE USAIN BOLTZ I RECOMENDED TO YOU TRUST ME XD USE TO YOUR PROJECT def fibonacci(num): if (num <= 1): return num return fibonacci(num - 2) + fibonacci(num - 1); fibonacci(100)
0eab7ff439d8d9659f0ff076b44a28d84bb91c4a
faizan2sheikh/PythonPracticeSets
/Sem2Set3/Q4.py
1,932
4.0625
4
class Publication: title:str price:float def __init__(self,title,price): self.title=str(title) self.price=float(price) def get_data(self): self.title=str(input('Enter title: ')) self.price=float(input('Enter price: ')) def put_data(self): print(f'Publication name is {self.title}') print(f'Publication price is {self.price}') class Sales: last1:float last2:float last3:float def __init__(self,l1,l2,l3): self.last1=int(l1) self.last2=int(l2) self.last3=int(l3) def get_data(self): self.last1=int(input('Enter last month sale: ')) self.last2=int(input('Enter second last month sale: ')) self.last3=int(input('Enter third last month sale: ')) def put_data(self): print(f'last month sale: {self.last1}') print(f'second last month sale: {self.last2}') print(f'third last month sale: {self.last3}') class Disk(Sales,Publication): def __init__(self,l1,l2,l3,title,price): Sales.__init__(self,l1,l2,l3) Publication.__init__(self,title,price) diskType:str def get_data(self): Disktype={'c':'CD','d':'DVD'} disk_in=input('Enter Disk type: ') self.diskType=Disktype[disk_in] def put_data(self): print(f'Disk type is {self.diskType}') class Book(Sales,Publication): pageCount:int def get_data(self): self.pageCount=int(input('Enter Page Count: ')) def put_data(self): print(f'Publication\'s Page Count is {self.pageCount}') class Tape(Sales,Publication): playingTime:float def get_data(self): self.playingTime=float(input('Enter playing time: ')) def put_data(self): print(f'Publication\'s playing time is {self.playingTime}') d1=Disk(24,32,24,'ALchemist',500) d1.get_data() d1.put_data()
e44a55b280967a49308faaa3127dee8c0107babc
kpranjal2047/Cryptography-Assignment
/Assignment 2/Main.py
6,375
3.671875
4
## Cryptography Assignment 2 ## Implementation of BlockChain ## Created by-- ## Kumar Pranjal - 2018A7PS0163H ## Yash Arora - 2018A4PS0002H ## Abhik Santra - 2018A8PS0612H ## Ayush Singh Chauhan - 2018B4PS0818H import pickle from os.path import exists from Block import Block from Record import Record from User import User from Util import zkpdiscretelog difficulty = 4 previousHash = '0' blockchain = [] records = [] users = [] teachers = [] p = 11 g = 2 imported = False if exists('state'): while True: opt = input('Previous data found... Import? (yes/no): ') if opt == 'yes': with open('state', 'rb') as f: previousHash, blockchain, records, users, teachers = pickle.load(f) imported = True print('Import Successful') break elif opt == 'no': break else: print('Unrecognized option\n') def verifyTransaction(record: list, previousHash: str, data: Record) -> str: print('Trying to mineBlock...') block = Block(record, previousHash, data) block.mineBlock(difficulty) if verifyChain(block): blockchain.append(block) return block.getBlockHash() def verifyChain(block: Block) -> bool: for i in range(1, len(blockchain)): if not blockchain[i].getPreviousHash() == blockchain[i-1].getBlockHash(): return False if len(blockchain) > 0 and not blockchain[-1].getBlockHash() == block.getPreviousHash(): return False return True def viewUser() -> None: value = input('Are you a teacher or student? (t/s): ') if value == 't': teac = input('Enter your name: ') passwd = input('Enter your pass: ') flag = False for teacher in teachers: if teacher.getName() == teac and teacher.getPass() == passwd: for block in blockchain: if block.teacher_name() == teac: print( 'TimeStamp at which data was recorded: ' + str(block.getTimeStamp())) print('Teacher:' + teac) print('Student:' + block.student_name()) print('His Academic Data:') block.printData() print() flag = True if flag: break if not flag: print('Teacher Not Found') elif value == 's': stud = input('Enter your name: ') y = 0 for user in users: if user.getName() == stud: x = int(user.getPass()) y = pow(g, x, p) if not zkpdiscretelog(y): return flag = False for user in users: if user.getName() == stud: for block in blockchain: if block.student_name() == stud: print('Time: ' + str(block.getTimeStamp())) print('Teacher:' + block.teacher_name()) print('Student:' + stud) print("Student's Academic Data:") block.printData() print() flag = True if flag: break if not flag: print('Student Not Found') else: print('Option not recognized') if __name__ == '__main__': if not imported: teacher1 = User() teacher1.setName('Abhik') teacher1.setPass('1') teachers.append(teacher1) users.append(teacher1) teacher2 = User() teacher2.setName('Pranjal') teacher2.setPass('2') teachers.append(teacher2) users.append(teacher2) teacher3 = User() teacher3.setName('Yash') teacher3.setPass('3') teachers.append(teacher3) users.append(teacher3) choice = 'yes' while choice == 'yes': option = input('What do you want to do? (view/add/register): ') if option == 'register': name = input('Enter name: ') passwd = input('Enter password (integer only): ') passwd_v = input('Verify password: ') if passwd == passwd_v: new_student = User() new_student.setName(name) new_student.setPass(passwd) users.append(new_student) else: print('Password verification failed') elif option == 'add': tname = input('Enter teacher name: ') tpass = input('Enter teacher password: ') sname = input('Enter student name: ') y = 0 for user in users: if user.getName() == sname: x = int(user.getPass()) y = pow(g, x, p) if not zkpdiscretelog(y): continue new_rec = Record() new_rec.addUsers(tname, sname) flag = False for teacher in teachers: if teacher.getName() == tname and teacher.getPass() == tpass: for user in users: if user.getName() == sname: while True: ip = input('Enter data (y/n): ') if ip == 'y': newdata = input('Enter Data: ') new_rec.addData(newdata) elif ip == 'n': records.append(new_rec) previousHash = verifyTransaction( records, previousHash, new_rec) flag = True break else: print('Option not recognized') if flag: break if flag: break if not flag: print('Something Wrong!!!') elif option == 'view': viewUser() choice = input('Do you want to continue? (yes/no): ') with open('state', 'wb') as f: dump = (previousHash, blockchain, records, users, teachers) pickle.dump(dump, f)
9c7828f5406ee99defc76121cfe922051c947e48
sergiiop/PlatziCodingChallenge
/dia12_next_birthday.py
727
4.25
4
from datetime import datetime, date def calculator(date_birthday): now = date.today() next_date_birth = date(now.year, date_birthday.month, date_birthday.day) if next_date_birth < now: next_date_birth = date( now.year + 1, date_birthday.month, date_birthday.day) missing = next_date_birth - now missing = str(missing.days) return missing def run(): print("Welcome to Calculator the next birthday") birthday = input("Please, write your date of birth (dd/mm/yy)") formato = "%d/%m/%Y" date_birthday = datetime.strptime(birthday, formato) missing = calculator(date_birthday) print(missing+" days until your birthday!") if __name__ == "__main__": run()
799502c12d8392b5828d271db9b02c6a614db5bb
JHyuk2/Hyuk2Coding
/SWAG/IM/list1/4831_전기버스.py
588
3.53125
4
''' input value 3 3 10 5 1 3 5 7 9 3 10 5 1 3 7 8 9 5 20 5 4 7 9 14 17 ''' def longest_way(pos, steps): if pos + k >= n: return steps tmp_list = [i+pos for i in range(k, 0, -1)] # 갈 수 있는 모든 거리 for d in tmp_list: if d in station_list: return longest_way(d, steps+1) else: return 0 for tc in range(int(input())): # k: 최대이동거리, n: 가야하는 거리, m: 정류장의 수 k, n, m = map(int, input().split()) station_list = list(map(int, input().split())) print(f'#{tc+1} {longest_way(0, 0)}')
068e9a2c5e7142e77e34d719d6342223b98552c6
MishinK/Django_pool
/d01/ex05/all_in.py
1,381
3.796875
4
#coding=utf8 import sys def get_key(d, val): for k, v in d.items(): if v.lower() == val.lower(): return k def get_val(d, key): for k, v in d.items(): if k.lower() == key.lower(): return v def capital_city(state): states = { "Oregon" : "OR", "Alabama" : "AL", "New Jersey" : "NJ", "Colorado" : "CO" } capital_cities = { "OR" : "Salem", "AL" : "Montgomery", "NJ" : "Trenton", "CO": "Denver" } if (get_val(states, state)): return(capital_cities[get_val(states, state)]) def state(capital): states = { "Oregon" : "OR", "Alabama" : "AL", "New Jersey" : "NJ", "Colorado" : "CO" } capital_cities = { "OR" : "Salem", "AL" : "Montgomery", "NJ" : "Trenton", "CO": "Denver" } if (get_key(capital_cities, capital)): return(get_key(states, get_key(capital_cities, capital))) def all_in(str): lst_str = str.split(',') for elem in lst_str: name = elem.strip(" ") if (name != ''): if (capital_city(name)): print("{0} is the capital of {1}".format(capital_city(name), state(capital_city(name)))) elif (state(name)): print("{0} is the capital of {1}".format(capital_city(state(name)), state(name))) else: print("{0} is neither a capital city nor a state".format(name)) if __name__ == '__main__': if (len(sys.argv) == 2): all_in(sys.argv[1])
fbfddc5dd86f7b97fca224a17635c08ea7383036
Luxios22/RSA
/RSA.py
2,121
3.828125
4
import random # compute gcd # gcd(a,b)=gcd(b, a%b) def gcd(a, b): if b == 0: return a return gcd(b, a % b) if a % b else b def is_prime(n): """Primality test using 6k+-1 optimization.""" if n <= 3: return n > 1 if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True class RSA(object): def __init__(self, prime_length=1000) -> None: self.prime_length = prime_length # Beforehand: # 1. Generate two distinct p,q, check their primality. # and let n=pq. def generate_primes(self): while True: p=random.randint(0, self.prime_length) q=random.randint(0, self.prime_length) if is_prime(p) & is_prime(q): n = p * q return p, q, n # 2. Find e in [0,n) that is relatively prime to (p-1)(q-1), i.e., # gcd(e, (p-1)(q-1))=1. Then store (e, n) as the public key. def get_public_key(self, p, q, n): while True: e = random.randint(0, n-1) if gcd(e, (p-1)*(q-1)) == 1: return (e, n) # 3. Compute d in [0,n) for de is congruent to 1 mod (p-1)(q-1), # keep (d, n) as the secret key. def get_private_key(self, e, p, q, n): while True: d = random.randint(0, n-1) if (d*e) % ((p-1)*(q-1)) == 1: return (d, n) # Encryption: m^= rem(m**e, n) def encrpt(self, m, e, n): return m**e % n # Decryption: m = rem((m^)**d, n) def decrypt(self, m_hat, d, n): return m_hat**d % n def main(): rsa = RSA() p, q, n = rsa.generate_primes() e, _ = rsa.get_public_key(p, q, n) d, _ = rsa.get_private_key(e, p, q, n) m = int(input("input m:")) if m >= n : print("your input is out of bounds") raise ValueError me = rsa.encrpt(m, e, n) print("original and encrpyted message: ", m, me) print("decrypted messege: ", rsa.decrypt(me, d, n)) if __name__ == "__main__": main()
8cc701c29f54bc48c53083b5beea3a9daa384cde
Candy-Robot/python
/基本语法学习/类和对象.py
825
3.59375
4
""" class Person(): name = '小甲鱼' def print_name(self): print(self.name) p = Person() p.print_name() class Juzheng(): def setRect(self,length,width): self.length = length self.width = width def getRect(self): print(self.length) print(self.width) def getArea(self): print("Area is "+str(self.length*self.width)) """ class tickey(): def __init__(self,weekend = False,child = False): self.money = 100 if weekend == True: self.exp = 1.2 elif weekend == False: self.exp = 1 if child == True: self.discount = 0.5 elif child == False: self.discount = 1 def showprice(self): price = self.money*self.exp*self.discount return price
92aeaaa4e24d5cc3c393c44ea7cfe4095eeba18e
AjayKarki/DWIT_Training
/Week2/Day7/Count_chars.py
230
3.75
4
user_input = input("Enter any word") count_dict = dict() for ch in user_input: if ch not in count_dict.keys(): count_dict[ch] = 1 else: count_dict[ch] += 1 print(count_dict) # print(user_input.count('p'))/
2755c642ddf1bb758bd9f81c12b9f65aa14fa00d
JuanluOnieva/pyCDI
/cdi/Analysis.py
3,594
3.59375
4
""" This script contains the necessary functions to deal with the data, obtain data frame and show some graphics """ import matplotlib.pyplot as plt from pyspark.sql import DataFrame from pyspark.sql.utils import AnalysisException from py4j.protocol import Py4JError import pandas as pb def get_data_frame_count_type_of_topic(data_frame: DataFrame) -> pb.DataFrame: """ From all the data, it takes the columns TopicID and Question and for each topic, count the number of+ different SubTopic/Question :param data_frame: generate with pyspark, and contain all the data from the csv file :return: data frame of panda package """ try: data_frame = data_frame \ .select("TopicID", "Question") \ .distinct() \ .groupBy("TopicID") \ .count() \ .sort("TopicID") except Py4JError: raise AnalysisException('One columns is incorrect') print("The following table represent the number of the type of each topic") data_frame.show() data_frame_pandas = data_frame.toPandas() return data_frame_pandas def get_rdd_count_type_of_topy(rdd: list) -> pb.DataFrame: """ Take an specific list from rdd spark, which is formed as list of tuples (Topic, Question) :param rdd: list of tuples(Topic, Question) :return: data frame of package Pandas """ data_frame_pandas = pb.DataFrame(rdd, columns=['Topic', 'Question']) print(data_frame_pandas) return data_frame_pandas def get_data_frame_count_male_gender_by_topic(data_frame: DataFrame) -> pb.DataFrame: """ From all the data, it takes the columns TopicID, and count the topic based on the gender :param data_frame: generate with pyspark, and contain all the data from the csv file :return: data frame of panda package """ data_frame_topic = data_frame \ .filter(data_frame["Stratification1"].contains("Male")) \ .distinct() \ .groupBy("TopicID") \ .count() \ .sort("TopicID") print("The following table represent the number of men group by the topic: ") data_frame_topic.show() data_frame_pandas = data_frame.toPandas() return data_frame_pandas def get_data_frame_count_black_ethnicity_by_topic(data_frame: DataFrame) -> pb.DataFrame: """ From all the data, it takes the columns TopicID, and count the topic based on the ethnicity :param data_frame: generate with pyspark, and contain all the data from the csv file :return: data frame of panda package """ data_frame_topic = data_frame \ .filter(data_frame["Stratification1"].contains("Black, non-Hispanic")) \ .distinct() \ .groupBy("TopicID") \ .count() \ .sort("TopicID") print("The following table represent the number of black ethnicity people group by the topic: ") data_frame_topic.show() data_frame_pandas = data_frame.toPandas() return data_frame_pandas def plot_type_of_topic(data_frame: pb.DataFrame) -> None: """ Plot a data frame with bar type :param data_frame: :return: """ plt.interactive(False) plt.figure() data_frame.plot(kind='bar', x= data_frame['TopicID']) plt.show() def plot_type_of_two_topic(data_frame1: pb.DataFrame, data_frame2: pb.DataFrame) -> None: """ Plot a data frame with bar type :param data_frame: :return: """ plt.interactive(False) plt.figure() data_frame1.plot(kind='bar', x= data_frame['TopicID']) data_frame2.plot(kind='bar', x= data_frame['TopicID']) plt.show()
a3e0df83439768b6b7e81c02170bb1e94e7cbf33
NIAN-EVEN/SUSTC-CSE5018-AOA
/genetic_algorithm.py
6,545
3.5625
4
import copy from local_search import * import numpy as np ''' 单独存储一个list记录每一代最好的个体,每一代结束后都进行一遍localsearch 群体的iterative local search, 就是演化算法 ''' def selections(num, combinations): seletedGroup = [] # 轮盘赌方法 sum = 0 scores = [] total = 0 newCombination = [] for combi in combinations: scores.append(1/(combi[0].score+combi[1].score)*1000000 - 10) total += scores[-1] newCombination.append(combi) for i in range(num): if np.random.rand() < 0.2: randnum = int(np.random.rand() * num) count = 0 for combi in newCombination: count += 1 if count == randnum: seletedGroup.append(combi) continue randnum = np.random.rand() * total number = 0 for score, combi in zip(scores, newCombination): if number <= randnum and number + score > randnum: seletedGroup.append(combi) break number += score return seletedGroup def rankBasedSelect(combinations): selectedGroup = [] num = len(combinations) rang = len(pop) * (len(pop) + 1) / 2 for i in range(num): # rand为0-range的随机数 rand = np.random.rand() * rang # 在整个range中j占比∑(1~j-1)-∑(1~j)部分 # 对rand反向求是哪个数累加而成再加1即实现按照排序选择的功能 p = int((np.sqrt(8 * rand + 1) - 1) / 2) + 1 selectedGroup.append(pop[len(pop) - p]) return selectedGroup def crossover(order1, order2, crossSize): cityNum = len(order1) # 因为是排序问题,所以一定是成段基因含有有效信息,离散基因无效 pos = [np.random.randint(cityNum)] pos.insert(0, int(pos[0]-crossSize)) newOrder1 = copy.deepcopy(order1) newOrder2 = copy.deepcopy(order2) if pos[0] < 0: for i in range(cityNum): newOrder1[i] = order1[i+pos[0]] newOrder2[i] = order2[i+pos[0]] pos[1] -= pos[0] pos[0] = 0 exchange1 = [] # gene1有,gene2中没有的 exchange2 = [] # gene2有,gene1中没有的 # 交叉 for i in range(pos[0], pos[1]): tmp = newOrder1[i] newOrder1[i] = newOrder2[i] newOrder2[i] = tmp # 计算缺省对应关系 for i in range(pos[0], pos[1]): if pos[0] < 0: print(newOrder1[pos[0]: pos[1]]) if newOrder1[pos[0]: pos[1]].count(newOrder2[i]) == 0: exchange2.append(newOrder2[i]) if newOrder2[pos[0]: pos[1]].count(newOrder1[i]) == 0: exchange1.append(newOrder1[i]) for i in range(0, pos[0]): if newOrder1[pos[0]: pos[1]].count(newOrder1[i]) == 1: newOrder1[i] = exchange2[exchange1.index(newOrder1[i])] if newOrder2[pos[0]: pos[1]].count(newOrder2[i]) == 1: newOrder2[i] = exchange1[exchange2.index(newOrder2[i])] for i in range(pos[1], cityNum): if newOrder1[pos[0]: pos[1]].count(newOrder1[i]) == 1: newOrder1[i] = exchange2[exchange1.index(newOrder1[i])] if newOrder2[pos[0]: pos[1]].count(newOrder2[i]) == 1: newOrder2[i] = exchange1[exchange2.index(newOrder2[i])] return newOrder1, newOrder2 def reproduction(parents, adj, crossSize): newOrder1, newOrder2 = crossover(parents[0].order, parents[1].order, crossSize) return oneLocalSearch(Solution(newOrder1, adj), adj), oneLocalSearch(Solution(newOrder2, adj), adj) def mutation(solution, adj): newOrder = doubleBridge(solution.order) return oneLocalSearch(Solution(newOrder, adj), adj) def init(filename, cityNum, popSize): city = loadCity(filename, cityNum) adj = getAdjMatrix(city) # TODO: greedy local init # order = greedyTSP(city, adj) # randomly init pop = [] for i in range(popSize): if np.random.rand() < 0.5: order = np.random.permutation(cityNum).tolist() solution = oneLocalSearch(Solution(order, adj), adj) else: solution = oneLocalSearch(Solution(greedyTSP(city, adj), adj), adj) pop.append(solution) pop.sort(key=lambda x:x.score) return pop, adj def stop(crossSize, time): if crossSize == 0 or time > TIME_LIMIT: return False else: return True if __name__ == "__main__": FILENAME = "TSP.csv" POPSIZE = 10 CITY_NUM = 100 TIME_LIMIT = 12*60*60 MAX_STAY_NUM = 50 PARENTS = 10 RESULT_FILE = "GAresult" ############################################## # FILENAME = sys.argv[1] # "TSP.csv" # POPSIZE = int(sys.argv[2]) # 100 # CITY_NUM = int(sys.argv[3]) # 100 # TIME_LIMIT = int(sys.argv[4]) # 12*60*60 # MAX_STAY_NUM = int(sys.argv[5]) # 50 # PARENTS = int(sys.argv[6]) # 20 # RESULT_FILE = sys.argv[7] # "GAresult.csv" ############################################## start = time.time() crossSize = CITY_NUM / 2 pop, adj = init(FILENAME, CITY_NUM, POPSIZE) generaSolution = [pop[0]] # stayRocord++ when position i is not better than before stayRecord = [0 for i in range(POPSIZE)] scoreRecord = [x.score for x in pop] generation = 1 bestScore = pop[0].score bestGeneration = 1 while stop(crossSize, start-time.time()): print("generate: ", generation) print(pop[0]) # 平均距离越短的段我们认为是较优段,遗传的时候应尽量保留较优段 # select for parents in selections(PARENTS, combinations(pop, 2)): offs = reproduction(parents, adj, crossSize) pop.extend(offs) # delete pop.sort(key=lambda x: x.score) del pop[POPSIZE:len(pop)] # mutation for i in range(POPSIZE): if scoreRecord[i] > pop[i].score: scoreRecord[i] = pop[i].score else: stayRecord[i] += 1 if stayRecord[i] >= MAX_STAY_NUM: pop[i] = mutation(pop[i], adj) pop.sort(key=lambda x: x.score) generation += 1 generaSolution.append(pop[0]) if generation-bestGeneration == 100 and pop[0].score == bestScore: crossSize -= 1 if pop[0].score < bestScore: bestScore = pop[0].score bestGeneration = generation print("best: ", generation) print(pop[0]) tofile(RESULT_FILE, generaSolution)
b16199e31669a439c25278df234a8310dfc0dba9
saltafossi/lego_dimensions_protocol
/checksum/verify_nfc_checksums.py
3,186
3.671875
4
#------------------------------------------------------------------------------- # Name: module2 # Purpose: # # Author: User # # Created: 23/11/2015 # Copyright: (c) User 2015 # Licence: <your licence> #------------------------------------------------------------------------------- import os def generate_checksum_for_command(command): """ Given a command (without checksum or trailing zeroes), generate a checksum for it. """ assert(len(command) <= 31) # Add bytes, overflowing at 256 result = 0 for word in command: result = result + word if result >= 256: result -= 256 return result def generate_checksum_from_valid_packet(packet): """Given a packet, generate the checksum for it. This function is intended for sniffed packets. Also to make sure we knwo how to calculate valid checksums. """ assert(len(packet) is 32) print("packet: "+repr(packet)) # Remove trailing zeros (if any) position = 0 last_non_zero_position = 0 for cropword in packet: position += 1 if cropword != 0x00: last_non_zero_position = position if last_non_zero_position == 32: # Handle unpadded packets no_trailing_zeros = packet[:] else: # Remove padding no_trailing_zeros = packet[:last_non_zero_position] # Remove last byte (checksum) command = no_trailing_zeros[:-1] expected = no_trailing_zeros[-1] # Compute checksum result = generate_checksum_for_command(command) print("result: "+repr(result)) if (result == expected) or (result == 0): return result else: print("locals():"+repr(locals())) assert(False) def convert_to_byte_list(packet_line_string): """ Take line from usb-mitm stdout and make it into a python libusb statement 01[32]: 55 14 c6 16 01 1e 01 ff 00 18 01 1e 01 ff 00 18 01 1e 01 ff 00 18 ea 00 00 00 00 00 00 00 00 00 becomes """ packet_byte_strings = packet_line_string.split(" ")[1:] bytelist = [] for packet_byte_string in packet_byte_strings: bytelist += [int(packet_byte_string, 16)] return bytelist input_file_path = os.path.join("..","logs", "2015-11-16_with_known_led_commands_removed.log") raw_output_dir = os.path.join("binned_log", "nfc_raw") if not os.path.exists(raw_output_dir): os.makedirs(raw_output_dir) with open(input_file_path, "r") as input_file: for line in input_file: if "[32]" not in line:# All USB endpoints for the device take 32-byte packets continue #81[32]: 55 01 15 6b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 endpoint_number = line.split("[")[0] byte_strings = line.split(" ")[1:] command = "0x"+byte_strings[1]+"_0x"+byte_strings[2] # Isolate the command before the checksum bytelist = convert_to_byte_list(line[:-1]) # Compare expected to actual checksums #print(bytelist) expected_checksum = generate_checksum_from_valid_packet(bytelist) def main(): pass if __name__ == '__main__': main()
6f07bcca69bafd2a27fcfca940c3dfedd796479e
bandofcs/boilerplate-arithmetic-formatter
/arithmetic_arranger.py
5,491
3.890625
4
import re #Enable checking by printing to console DEBUG= False def arithmetic_arranger(problems, count=None): #Variables definition #To be printed out firstrow=list() secondrow=list() thirdrow=list() forthrow=list() #Length of each operand firstlen=0 secondlen=0 thirdlen=0 maxlen=0 #Result variable third=None #Check that no more than 5 problems if len(problems) > 5: return "Error: Too many problems." #Go through each problem for problem in problems: #Make sure that inputs are only digits try: first=int(''.join(re.findall("^([^\s]+)", problem))) except: if DEBUG: print("regex is"+''.join(re.findall("^./S", problem))) return "Error: Numbers must only contain digits." #Make sure that operand cannot be more than 4 digits if first > 9999: return "Error: Numbers cannot be more than four digits." if DEBUG: print(first) #Make sure that inputs are only digits try: second=int(''.join(re.findall("([^\s]+)$", problem))) except: return "Error: Numbers must only contain digits." #Make sure that operand cannot be more than 4 digits if second > 9999: return "Error: Numbers cannot be more than four digits." if DEBUG: print(second) #Make sure that operator is only +/- operator=''.join(re.findall("[+-]", problem)) if operator != "+" and operator != "-": return "Error: Operator must be '+' or '-'." if DEBUG: print(operator) #print empty spaces for second problem and beyond if maxlen>0: firstrow.append(" ") secondrow.append(" ") thirdrow.append(" ") if count==True and maxlen>0: forthrow.append(" ") #Find the number of digits in the first operand if first>999: firstlen=4 elif first>99: firstlen=3 elif first>9: firstlen=2 elif first<10: firstlen=1 #Find the number of digits in the second operand if second>999: secondlen=4 elif second>99: secondlen=3 elif second>9: secondlen=2 elif second<10: secondlen=1 #Find the bigger number of digits between the 2 operands maxlen=max(secondlen,firstlen)+2 if count==True: if operator =="+": third=first+second elif operator == "-": third=first-second if third>9999: thirdlen=5 for i in range(maxlen-thirdlen): forthrow.append(" ") forthrow.append(str(third)) elif third>999: thirdlen=4 for i in range(maxlen-thirdlen): forthrow.append(" ") forthrow.append(str(third)) elif third>99: thirdlen=3 for i in range(maxlen-thirdlen): forthrow.append(" ") forthrow.append(str(third)) elif third>9: thirdlen=2 for i in range(maxlen-thirdlen): forthrow.append(" ") forthrow.append(str(third)) elif third>-1: thirdlen=1 for i in range(maxlen-thirdlen): forthrow.append(" ") forthrow.append(str(third)) elif third>-10: thirdlen=2 for i in range(maxlen-thirdlen): forthrow.append(" ") forthrow.append(str(third)) elif third>-100: thirdlen=3 for i in range(maxlen-thirdlen): forthrow.append(" ") forthrow.append(str(third)) elif third>-1000: thirdlen=4 for i in range(maxlen-thirdlen): forthrow.append(" ") forthrow.append(str(third)) elif third>-10000: thirdlen=5 for i in range(maxlen-thirdlen): forthrow.append(" ") forthrow.append(str(third)) #Append spaces followed by first operand for i in range(maxlen-firstlen): firstrow.append(" ") firstrow.append(str(first)) #Append operator followed by spaces and second operand secondrow.append(operator) for i in range(maxlen-secondlen-1): secondrow.append(" ") secondrow.append(str(second)) #Append "-" equals to the bigger number of digits between the 2 operands +2 for i in range(maxlen): thirdrow.append("-") if DEBUG: print(''.join(firstrow)) print(''.join(secondrow)) print(''.join(thirdrow)) print(''.join(forthrow)) firstrow.append("\n") secondrow.append("\n") if count==True: thirdrow.append("\n") arranged_problems=''.join(firstrow + secondrow + thirdrow + forthrow) return arranged_problems arranged_problems=''.join(firstrow + secondrow + thirdrow) if DEBUG: print(type(arranged_problems)) return arranged_problems
7bf551528806430c66326b578d95fd96dfee6189
Camille-Arsac/python
/dog/dog.py
418
3.515625
4
class Dog: def __init__(self, name, age, owner, trick): self.name = name self.age = age self.owner = owner self.trick = trick def learn(self, trick): self.trick.append(trick) def same_trick(self, dog): same_tricks = [] for trick in self.trick: if trick in dog.trick: same_tricks.append(trick) return same_tricks
4d28d079222049a3f52650423ec9e93ab6e8bd5c
Bhargavi0326/Python-Strings
/print sorted list.py
74
3.609375
4
S=input() li=S.split() A=sorted(li) for i in A: print(i,end=" ")
dfa70c585b7dd60f8076cd5656bec1efeb9485f4
jyu197/comp_sci_101
/apt7/GreenIndexes.py
307
3.625
4
''' Created on Nov 4, 2015 @author: Jonathan ''' def green(pixels): greens = [] for pixel in pixels: values = pixel.split(",") if int(values[1]) > int(values[0]) + int(values[2]): greens.append(pixels.index(pixel)) return greens if __name__ == '__main__': pass
26b27dd776d9f454418913dba250757e73fa0925
sarahkittyy/Functional2
/interpreter/clean.py
398
3.515625
4
import re def removeSpaces(line): depth = False ret = "" for char in line: if char in ['"', "'"]: depth = not depth if depth: ret += char elif not depth and re.match('\\s', char) == None: ret += char return ret def clean(lines): cleaned = [] for line in lines: line = removeSpaces(line) line = re.sub(r'^\s*$', '', line) if line: cleaned.append(line) return cleaned
2bb99930cd03e5deee78aca5029d7ac6342a6dc2
quzeyang/quzheyang
/rpsls.py
1,392
3.953125
4
#coding:gbk """ һСĿRock-paper-scissors-lizard-Spock ߣ ڣ2019/11/20 """ import random # 0 - ʯͷ # 1 - ʷ # 2 - ֽ # 3 - # 4 - # ΪϷҪõԶ庯 def name_to_number(name): if name=="ʯͷ": return 0 if name=="ʷ": return 1 if name=="": return 2 if name=="": return 3 if name=="": return 4 if name!="ʯͷ" and name!="ʷ" and name!="" and name!="" and name!="": return 99 def number_to_name(number): if number==0: return "ʯͷ" if number==1: return "ʷ" if number==2: return "" if number==3: return "" if number==4: return "" def rpsls(player_choice): print("ѡΪ:",player_choice) a=name_to_number(player_choice) comp_number=random.randrange(0,5) b=number_to_name(comp_number) print("ѡΪ:",b) c=a-comp_number if c in range(-4,-2) or c in range(1,3): print("Ӯ") if c in range(-2,0) or c in range(3,5): print("Ӯ") if c==0: print("ͻһ") if a==99: print("Error: No Correct Name") print("ӭʹRPSLSϷ") print("----------------") print("ѡ:") choice_name=input() rpsls(choice_name)
fff327735a9d699d9bc2769d9d51e00107c07d00
manishbalyan/python
/function.py
134
3.71875
4
def square(number): sqr_num = number **2 return sqr_num input_num = 5 output_num = square(input_num) print output_num
2f49c988d058480c409d3a3ca6a37bc5f99e8b74
rafaelperazzo/programacao-web
/moodledata/vpl_data/63/usersdata/245/31962/submittedfiles/swamee.py
240
3.609375
4
# -*- coding: utf-8 -*- import math f=float(input('Digite o valor de f:')) l=float(input('Digite o valor de l:')) q=float(input('Digite o valor de q:')) dh=float(input('Digite o valor de Delta h:')) v=float(input('Digite o valor de teta:'))
24509cba69187ad590ce53c9cd6f9df859366b13
bakaInc/AppliedPythonAtom
/homeworks/homework_01/hw1_det.py
940
3.71875
4
#!/usr/bin/env python # coding: utf-8 ''' Метод, считающий детерминант входной матрицы, если это возможно, если невозможно, то возвращается None Гарантируется, что в матрице float :param list_of_lists: список списков - исходная матрица :return: значение определителя или None ''' def calculate_determinant(list_of_lists): det = 0 x = len(list_of_lists) sign = 1 ind = 0 for y in range(x): if len(list_of_lists[ind]) != x: return None ms = [] for k in range(x - 1): ms.append([]) for m in range(x): if m != y: ms[k].append(list_of_lists[k + 1][m]) det += sign * list_of_lists[ind][y] * (calculate_determinant(ms) or 1) sign = -sign return det
d59def2d5703464933f43543c8e881b618b97a44
MinaPecheux/Advent-Of-Code
/2015/Python/day9.py
2,881
3.671875
4
### ============================================= ### [ ADVENT OF CODE ] (https://adventofcode.com) ### 2015 - Mina Pêcheux: Python version ### --------------------------------------------- ### Day 9: All in a Single Night ### ============================================= from networkx import Graph, all_simple_paths # [ Input parsing functions ] # --------------------------- def parse_input(data): '''Parses the incoming data into processable inputs. :param data: Provided problem data. :type data: str :return: List of connections in the graph. :rtype: list(tuple(str, str, dict)) ''' connections = [] for line in data.strip().split('\n'): points, dist = line.split(' = ') dist = int(dist) entry, exit = points.split(' to ') connections.append((entry, exit, { 'weight': dist })) return connections # [ Computation functions ] # ------------------------- ### PART I + II def compute_route_lengths(graph): '''Computes all the possible paths in the graph and stores the length of each. The given graph represents the map with cities modeled as nodes and connections between cities modeled as edges weighted by the distance. :param graph: Graph that represents the map. :type graph: nx.Graph :return: Lengths of all the paths. :rtype: list(int) ''' lengths = [] for source in graph.nodes: for target in graph.nodes: if source == target: # ignore same node continue for path in all_simple_paths(graph, source, target): if len(set(path)) != len(graph.nodes): continue length = 0 for i in range(len(path) - 1): length += graph.get_edge_data(path[i], path[i+1])['weight'] lengths.append(length) return lengths # [ Base tests ] # -------------- def make_tests(): '''Performs tests on the provided examples to check the result of the computation functions is ok.''' graph = Graph() graph.add_edges_from(parse_input( '''London to Dublin = 464 London to Belfast = 518 Dublin to Belfast = 141''')) route_lengths = compute_route_lengths(graph) assert min(route_lengths) == 605 assert max(route_lengths) == 982 if __name__ == '__main__': # check function results on example cases make_tests() # get input data data_path = '../data/day9.txt' connections = parse_input(open(data_path, 'r').read()) # prepare graph and path lengths graph = Graph() graph.add_edges_from(connections) route_lengths = compute_route_lengths(graph) ### PART I solution = min(route_lengths) print('PART I: solution = {}'.format(solution)) ### PART II solution = max(route_lengths) print('PART II: solution = {}'.format(solution))
6b0498f1a6db6f514f48dd510439998135d98478
gomtinQQ/algorithm-python
/codeUp/codeUpBasic/1581.py
584
3.546875
4
''' 1581 : (함수 작성+포인터) swap 함수 만들기 (Call by Reference) 함수명 : myswap 매개 변수(parameter) : 정수형 포인터 변수 변수 2개(매개변수를 반드시 int∗로 사용) 반환 형(return type) : 없음(void) 함수 내용 : 첫 번째 포인터가 가리키는 변수의 값이 두 번째 포인터가 가리키는 변수의 값보다 클 경우 두 값을 서로 바꾼다. ''' def myswap(a, b): tmp = 0 if(a > b): tmp = a a = b b = tmp print(a, b) a, b = input().split() a = int(a) b = int(b) myswap(a, b)
8ba58f7b06f559d5c0129b021e54d8af65e0cb19
umyuu/Sample
/src/Python3/Q74082/list_rotate.py
647
3.9375
4
# -*- coding: utf-8 -*- from collections import deque def main(): n = int(input()) # ずらす個数 code = [1, 2, 3, 4] items = deque(code) print(items) items.rotate(n * -1) print(items) # dequeからlistに戻す code = list(items) print(code) def test(): n = int(input()) # ずらす個数 code = [1, 2, 3, 4] memo = code for i in range(4): code[i] = memo[(i + n) % 4] # nだけ配列のインデクスを右にずらしたい print(memo) # => [2, 3, 4, 2] 3番目がうまくいかない print(code) # => [2, 3, 4, 2] if __name__ == '__main__': main() #test()
6b3683b6b1666261f589bd5180f2941e0203c566
Catalin-David/Expenses
/Expense.py
3,211
3.796875
4
class Expense: def __init__(self, day= 1, amount=0, tip=""): ''' Function initializes a new Expense params: day (default:1) - day of the expense (integer between 1-30) amount (default:0) - amount that is paid (integer) tip - type of expense/object that was purchased ''' try: self._day = int(day) if self._day < 1 or self._day > 30: raise ValueError("Day should be between 1 and 30") except: raise ValueError("Day should be an integer") try: self._amount = int(amount) if self._amount < 0: raise ValueError("Amount of expense should be positive") except: raise ValueError("Amount of expense should be an integer") self._type = tip @property def Day(self): ''' Property that returns the day of an expense ''' return self._day @Day.setter def Day(self, value): ''' Function is a setter for parameter day of an expense ''' try: value = int(value) except: raise ValueError("Day should be an integer") if value < 1 or value > 30: raise ValueError("Day should be between 1 and 30") self._day = value @property def Amount(self): ''' Property that returns the amount of an expense ''' return self._amount @Amount.setter def Amount(self, value): ''' Function is a setter for parameter amount of an expense ''' try: value = int(value) except: raise ValueError("Amount of expense should be an integer") if value < 0: raise ValueError("Amount of expense should be positive") self._amount = value @property def Type(self): ''' Property that returns the type of an expense ''' return self._type @Type.setter def Type(self, value): ''' Function is a setter for parameter type of an expense ''' self._type = value def __str__(self): ''' Function creates a model for priting an object of type Expense ''' return "(Day: " +str(self.Day) + ", Amount: " + str(self.Amount) + ", Type: " + self.Type + ")" def __lt__(self, other): ''' Function creates a model for comparing two objects of type Expense ''' return self._day < other._day def tests(): try: expense = Expense("32", "100", "Food") assert False except ValueError: assert True try: expense = Expense("10.5", "100", "Food") assert False except ValueError: assert True try: expense = Expense("30", "100.5", "Food") assert False except ValueError: assert True try: expense = Expense("1", "-100", "Food") assert False except ValueError: assert True expense1 = Expense("25", "100", "Food") expense2 = Expense("18", "2500", "Gucci") assert expense2 < expense1 tests()
df8d860662fe2981ab9c5a3f2a6d1fd83609a742
Jon-117/py.projects
/prime numbers.py
289
3.765625
4
high_n=float(input("prime numbers up to...")) num = 0 while True: num+=1 ''' numcheck=num % range(0,(high_n+1.0)) if numcheck.is_integer(): print(num) ''' print(num) ''' i=0 while True: False i+= 1 if i == ((i/i) and (i/1)) : print(i) '''
50c5ecb8740866a06db06ee7931e0a365f9dd26a
mlech456/pyp-w1-gw-language-detector
/language_detector/main.py
730
3.953125
4
# -*- coding: utf-8 -*- """This is the entry point of the program.""" from languages import LANGUAGES def detect_language(text, languages=LANGUAGES): stats = {} #Creating a dynamic counter for language in languages: name = language['name'] stats[name] = 0 for item in text.split(' '): #iterates through each word in text for language in languages: #iterates through each language name = language['name'] for word in language.get('common_words'): #iterates through each common word if item == word: stats[name] += 1 #Adds to the dynamic counter return max(stats, key=stats.get)
f633fae18296eba731f7153ac4f823c8c57aa80c
kaw19/python
/notebooks/1_Basic/pedra_papel_tesoura.py
2,023
3.8125
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 13 22:16:26 2019 @author: kaw """ import random # Mostra instruções print("Regras do jogo Pedra, papel e tesoura: \n" + "Pedra X Papel -> Papel vence\n" + "Pedra X Tesoura -> Pedra vence\n" + "Papel X Tesoura -> Tesoura vence\n") while True: print("Escolha:\n 1. Pedra\n 2. Papel\n 3. Tesoura\n") escolha = int(input("Usuário: ")) while escolha > 3 or escolha < 1: escolha = int(input("Escolha um objeto válido: ")) if escolha == 1: objeto_escolhido = 'Pedra' elif escolha == 2: objeto_escolhido = 'Papel' else: objeto_escolhido = 'Tesoura' print("Escolha do usuário: " + objeto_escolhido) print("\nAgora eu escolho...") # Computador escolhe randomicamente um número # entre 1 , 2 e 3. Usando o método 'randint' do módulo 'random' escolha_comp = random.randint(1, 3) # busca nova escolha se o objeto escolhido pelo computador # for o mesmo escolhido pelo usuário while escolha_comp == escolha: escolha_comp = random.randint(1, 3) if escolha_comp == 1: objeto_escolhido_comp = 'Pedra' elif escolha_comp == 2: objeto_escolhido_comp = 'Papel' else: objeto_escolhido_comp = 'Tesoura' print("Escolha do computador: " + objeto_escolhido_comp) print(objeto_escolhido + " X " + objeto_escolhido_comp) if((escolha == 1 and escolha_comp == 2) or (escolha == 2 and escolha_comp == 1)): print("Papel vence => ", end = "") result = "Papel" elif((escolha == 1 and escolha_comp == 3) or (escolha == 3 and escolha_comp == 1)): print("Pedra vence => ", end = "") result = "Pedra" else: print("Tesoura vence => ", end = "") result = "Tesoura" if result == objeto_escolhido: print(">>> Usuário venceu <<<") else: print(">>> Computador venceu <<<") # print() resp = input("\n\nQuer jogar novamente? ( /N) ") if resp == 'n' or resp == 'N': break print("\nObrigado por jogar!")
23816b7f972b2a249beff3c4b9335ad7088ad711
CppChan/Leetcode
/medium/mediumCode/c/sumo_logic/putandget.py
771
3.765625
4
class Solution(object): dic = {} def __init__(self, name, year, location): self.dic[(name,year)] = location def put(self, name, year, location): self.dic[(name,year)] = location def getyear(self, name, year): if (name, year) not in self.dic: closest,itemlist,res = float('inf'),self.dic.items(),"" for item in itemlist: if abs(item[0][1]-year)<closest: closest = abs(item[0][1]-year) res = self.dic[item[0]] return res else:return self.dic[(name, year)] if __name__ == "__main__": s = Solution('xijia',1995,'a') s.put('chen',1994,'a') s.put('bao',1996,'g') s.put('luo',1998,'q') print s.getyear('ss',1992)
5d641e0bc03aef8011f601d248bb557e4cd8d45c
stewSquared/project-euler
/p037.py
870
3.640625
4
from math import sqrt from itertools import count, islice def primesUntil(n): composite = [False for _ in range(n)] for m in range(2, int(sqrt(n))): if not composite[m]: for i in range(m**2, n, m): composite[i] = True return [i for (i, m) in enumerate(composite) if (not m)][2:] primes = primesUntil(10**6) def prime(n): if n < 2: return False for m in range(2, int(sqrt(n))+1): if n%m == 0: return False else: return True def rightTruncatable(p): return prime(p) and (True if p < 10 else rightTruncatable(int(str(p)[1:]))) def leftTruncatable(p): return prime(p) and (True if p < 10 else leftTruncatable(int(str(p)[:-1]))) ans = sum(filter(lambda p: (leftTruncatable(p) and rightTruncatable(p) and p > 10), primes())) print(ans)
d99e2e27d661525743a8611a9fd2dc061acc2d53
silkyg/python-practice
/Assignment_2_Decision_Control/Check_year_is_leapyear.py
278
4.3125
4
#Program to check whether the year is a leap year or not year=int(input("Enter a valid year :")) if year%4==0 : print("%d is a Leap year"%year ) elif year % 400 == 0 and year % 100 != 0: print("%d is a Leap year" % year) else : print("%d is a not a Leap year"%year )
52c917a8c59b119bb4ca3b2617371b2f242dd17c
captain-crumbs/websniff
/websniff.py
357
3.703125
4
import urllib import argparse parser = argparse.ArgumentParser() parser.add_argument("url", help="The URL of the site to be image sniffed") args = parser.parse_args() print args.url # We get a file-like object at the specified url f = urllib.urlopen(args.url); # Read from the object and store the contents of the page in s s = f.read() f.close() print s
d81c068a0f3fdf07017ba919ad5094de9357d52a
darwin-nam/python-algorithm
/codeup/6070.py
273
4.25
4
month = input() month = int(month) if(month==1 or month==2 or month==12) : print("winter") elif(3<=month and month<6) : print("spring") elif(6<=month and month<9) : print("summer") elif(9<=month and month<12) : print("fall") else : print("input a number between 1 to 12")
abaac9afe461023d1ad515e3f3a0b3aaccc2cc74
dbsgh9932/TIL
/variable/03_variable_ex1.py
427
3.6875
4
name='홍길동' no=2016001 year=4 grade='A' average=93.5 level=10 print('성명 :',name) print('학번 : '+str(no)) print('학년 : '+str(year)) print('학점 :',grade) print('평균 : '+str(average)) # 포맷코드 사용 (%표시는 %%(그 자체를 표기)) print('성명 : %s'%name) print('학번 : %d'%no) print('학년 : %d'%year) print('학점 : %c'%grade) print('평균 : %.1f'%average) print('등급 : %d%%'%level)
bfbd51a9400a8ac12f3beea0960d653d09b70034
woodjb/ISAT252
/Hangman.py
607
3.921875
4
import random answerlist = ["python","benton","computer","class","javascript","JMU","ISAT",] random.shuffle(answerlist) answer = list(answerlist[0]) display = [] display.extend(answer) for i in range(len(display)): display[i] = "_" print("The topic is: 252\n") print (' '.join(display)) print () count = 0 while count < len(answer): guess = input("Please guess a letter: ") guess = guess.lower() print (count) for i in range(len(answer)): if answer[i] == guess : display[i] = guess count = count + 1 print (' '.join(display)) print () print ("You Guessed the Word!")
565ac8f2f1e65ec380daa250befa95ca6faa2a18
krikavap/python-kurz
/dedictvi.py
635
3.75
4
""" dedictvi.py algoritmus pro rozdělení majetku mezi libovolný počet potomků každý dostane stejnou částku + zůstane nerozdělený zbytek vstup: částka k rozdělení, počet potomků výstup: částka na jednoho potomka a výše nerozděleného zbytku """ castka = int(input("Zadej částku, která se bude rozdělovat: ")) potomci = int(input("Zadej počet potomků: ")) if potomci > 0: castka_rozdelit = castka // potomci zbytek = castka % potomci print(f"Každý potomek dostane {castka_rozdelit:,.2f} Kč. Nerozdělený zbytek činí {zbytek:,.2f} Kč.") else: print("Nutno zadat počet potomků!")
bbaded358226faa82713c0d5c7cb22cf51b34e36
srikanthpragada/PYTHON_29_OCT_2020
/demo/oop/isinstance_demo.py
155
3.65625
4
def add(n1, n2): if isinstance(n1, str): return int(n1) + int(n2) else: return n1 + n2 print(add(10, 20)) print(add("10", "20"))
039f1824df824286e318d58bd3ddf87243d72313
Aasthaengg/IBMdataset
/Python_codes/p02801/s823636358.py
143
3.734375
4
C = input() # 文字列と数値の変換 # ord('文字') / chr(数値) で変換できる ord_s = ord(C) chr_s = chr(ord_s + 1) print(chr_s)
7774254b9037273f5152349776869c0800468b87
kylemaa/Hackerrank
/LeetCode/top-k-frequence-elements.py
656
3.59375
4
import collections import heapq class Solution: def topKelements(self, nums, k): count = collections.defaultdict(int) for n in nums: count[n] += 1 heap = [] for key, v in count.items(): # heap push method heapq.heappush(heap, (v, key)) if len(heap) > k: # heap pop the ones that least frequent based on the value v (pop the smallest/ min-heap) heapq.heappop(heap) res = [] while len(heap) > 0: res.append(heapq.heappop(heap)[1]) return res print(Solution().topKelements([3, 3, 1, 1, 2, 5, 7, 8], 2))
b205116bf47669f70b54b28f582bfa35689542a4
JargonKnight/Intro-To-Graphics
/Final Project - Part A/0.1/level1.py
9,567
3.625
4
'''Author: Jesse Higgins Last Modified By: Jesse Higgins Date Last Modified: July 25th 2013 Program Description: Leapy is a fun little frogger game with unique levels and requires you to collect all the objects in that level in order to move on to the next. version 0.1: - simply created a bunch of classes for the first level and created instances of them to make the background - the player frogger was also created - main menu was added for the game as well ''' import pygame pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((1000, 640)) class Animals(pygame.sprite.Sprite): def __init__(self, pic, direction, posy): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25,25)) self.image = pygame.image.load(pic) self.rect = self.image.get_rect() self.rect.centery = posy self.counter = 100 self.dx = 10 self.dir = direction self.setDir() def update(self): self.counter += 1 self.rect.centerx += self.dx if self.rect.left > screen.get_width(): self.rect.left = 0 if self.rect.centerx < 0: self.rect.centerx = 1000 def setDir(self): if self.dir == "left": self.rect.centerx = 1000 self.dx = -10 else: self.rect.centerx = 0 self.dx = 10 def changeSpeed(self,speed): self.dx = speed class Frogger(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25,25)) self.image = pygame.image.load("Resources/Frogger_Up0.gif") self.rect = self.image.get_rect() self.rect.center = (450, 600) def update(self): self.rect.center = (450,600) class Water(pygame.sprite.Sprite): def __init__(self,posx, posy): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25,25)) self.image = pygame.image.load("Resources/Water.gif") self.rect = self.image.get_rect() self.rect.centerx = posx self.rect.centery = posy class Bridge(pygame.sprite.Sprite): def __init__(self, posx, posy): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25,25)) self.image = pygame.image.load("Resources/Bridge.gif") self.rect = self.image.get_rect() self.rect.centerx = posx self.rect.centery = posy class Grass(pygame.sprite.Sprite): def __init__(self, posx, posy): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25,25)) self.image = pygame.image.load("Resources/GrassGrow_0.gif") self.frame = 0 self.rect = self.image.get_rect() self.rect.centerx = posx self.rect.centery = posy self.LoadImages() self.GrassGrow = False def LoadImages(self): self.imageStand = pygame.image.load("Resources/GrassGrow_0.gif") self.imagesGrassGrow = [] for i in range(9): imgName = "MoreGrass/GrassGrow_%d.gif" % i tmpImage = pygame.image.load(imgName) self.imagesGrassGrow.append(tmpImage) self.counter = 100 def update(self): self.counter += 1 if self.GrassGrow: if self.counter > 1: self.frame += 1 if self.frame >= len(self.imagesGrassGrow): self.frame = 0 self.counter = 0 self.GrassGrow = False self.image = self.imagesGrassGrow[self.frame] def reset(self): self.GrassGrow = True self.counter = 0 class Label(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.font = pygame.font.SysFont("None", 50) self.text = "" self.center = (120,110) self.counter = 0 def update(self): self.image = self.font.render(self.text, 1, (0,0,0)) self.rect = self.image.get_rect() self.rect.center = self.center self.counter += 1 if self.counter > 60: self.text = "" class Walls(pygame.sprite.Sprite): def __init__(self, posx, posy, Length, Width): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((Length, Width)) self.image.fill((0,0,0)) self.rect = self.image.get_rect() self.rect.centerx = posx self.rect.centery = posy class Coins(pygame.sprite.Sprite): def __init__(self, posx, posy): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25,25)) self.rect = self.image.get_rect() self.LoadImages() self.image = self.imageStand self.rect = self.image.get_rect() self.rect.centerx = posx self.rect.centery = posy self.frame = 0 def LoadImages(self): self.imageStand = pygame.image.load("FroggerCoins/FroggerCoin_0.gif") self.imagesCoinSpin = [] for i in range(50): imgName = "FroggerCoins/FroggerCoin_%d.gif" % i tmpImage = pygame.image.load(imgName) self.imagesCoinSpin.append(tmpImage) self.counter = 100 def update(self): self.counter += 1 if self.counter > 2: self.frame += 3 if self.frame >= len(self.imagesCoinSpin): print "Coins Working" self.frame = 0 self.animation = True self.image = self.imagesCoinSpin[self.frame] self.counter = 0 def main(): pygame.display.set_caption("Leapy") background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((43, 124, 36)) screen.blit(background, (0,0)) animal1 = Animals("FroggerEnemies/FroggerGator0_right.gif", "right", 175) animal2 = Animals("FroggerEnemies/FroggerGator0_right.gif", "right", 400) animal3 = Animals("FroggerEnemies/FroggerGator0_left.gif", "left", 500) animal4 = Animals("FroggerEnemies/FroggerGator0_left.gif", "left", 35) human1 = Animals("FroggerEnemies/LawnMower0_left.gif", "left", 350) human2 = Animals("FroggerEnemies/LawnMower0_right.gif", "right", 225) human3 = Animals("FroggerEnemies/LawnMower0_left.gif", "left", 450) water = Water(-5, 100) water2 = Water(100, 100) water3 = Water(150, 100) water4 = Water(200, 100) water5 = Water(300, 100) water6 = Water(350, 100) water7 = Water(400, 100) water8 = Water(500, 100) water9 = Water(550, 100) water10 = Water(600, 100) water11 = Water(700, 100) water12 = Water(750, 100) water13 = Water(800, 100) water14 = Water(900, 100) water15 = Water(950, 100) water16 = Water(1000, 100) bridge = Bridge(50, 100) bridge2 = Bridge(250, 100) bridge3 = Bridge(450, 100) bridge4 = Bridge(650, 100) bridge5 = Bridge(850, 100) grass1 = Grass(500, 250) grass2 = Grass(200, 375) grass3 = Grass(600, 475) frogger = Frogger() label = Label() label.text = "***LEVEL 1***" label.center = (500,300) wall1 = Walls(500, -15, 1000, 25) wall2 = Walls(1015,-15, 25, 1400) wall3 = Walls(500, 653, 1000, 25) wall4 = Walls(-15, -15, 25, 1400) coin1 = Coins(600, 200) allAnimals = pygame.sprite.Group(animal1, animal2, animal3, animal4, human1, human2, human3) allPlayers = pygame.sprite.Group(frogger) allWater = pygame.sprite.Group(water, water2, water3, water4, water5, water6, water7, water8, water9, water10, water11, water12, water13, water14, water15, water16) allBridge = pygame.sprite.Group(bridge, bridge2, bridge3, bridge4, bridge5) allGrass = pygame.sprite.Group(grass1, grass2, grass3) allLabels = pygame.sprite.Group(label) allWalls = pygame.sprite.Group(wall1, wall2, wall3, wall4) allCoins = pygame.sprite.Group(coin1) clock = pygame.time.Clock() keepGoing = True while keepGoing: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False animal1.changeSpeed(20) animal2.changeSpeed(5) animal3.changeSpeed(-17) human1.changeSpeed(-20) allGrass.clear(screen, background) allAnimals.clear(screen, background) allWater.clear(screen, background) allBridge.clear(screen, background) allWalls.clear(screen, background) allCoins.clear(screen, background) allPlayers.clear(screen, background) allLabels.clear(screen, background) allAnimals.update() allCoins.update() allPlayers.update() allGrass.update() allLabels.update() allGrass.draw(screen) allAnimals.draw(screen) allWater.draw(screen) allBridge.draw(screen) allCoins.draw(screen) allWalls.draw(screen) allPlayers.draw(screen) allLabels.draw(screen) pygame.display.flip()
cd001f45018cc03f10be76c316bb02aaa6d44899
csse120-201830/16-Exam2
/src/problem4.py
10,473
3.65625
4
""" Exam 2, problem 4. Authors: David Mutchler, Dave Fisher, Matt Boutell, Amanda Stouder, their colleagues and PUT_YOUR_NAME_HERE. April 2018. """ # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE. import time import testing_helper def main(): """ Calls the TEST functions in this module. """ # ------------------------------------------------------------------------- # Uncomment the following calls to the testing functions one at a time # as you work the problems. # ------------------------------------------------------------------------- print('Un-comment the calls in MAIN one by one') print(' to run the testing code as you complete the TODOs.') # run_test_problem4a() # run_test_problem4b() ############################################################################### # TODO: 2. READ the doc-string for the is_prime function below. # It is the same is_prime function that you have used previously, # except that it returns False for all integers less than 2. # # *** Throughout these problems, *** # *** you must CALL functions wherever appropriate. *** # # Once you are confident that you understand the contents of this comment, # change the TO-DO for this problem to DONE. ############################################################################### def is_prime(n): """ What comes in: An integer. What goes out: -- Returns True if the given integer is prime, else returns False. All integers less than 2 are treated as NOT prime. Side effects: None. Examples: -- is_prime(11) returns True -- is_prime(12) returns False -- is_prime(2) returns True -- is_prime(0) returns False Note: The algorithm used here is simple and clear but slow. """ if n < 2: return False for k in range(2, (n // 2) + 1): if n % k == 0: return False return True def run_test_problem4a(): """ Tests the problem4a function. """ ########################################################################### # THESE TESTS ARE ALREADY DONE. DO NOT CHANGE THEM. # You may add more tests if you wish, but you are not required to do so. ########################################################################### print() print('--------------------------------------------------') print('Testing the problem4a function:') print('--------------------------------------------------') format_string = ' problem4a( {} )' passed_tests = 0 # Test 1: print() print('Test 1:') strings = ['Nope', '', 'Hello', 'Goodbye', 'More stuff'] expected = 'Hello' print(' This test case calls:') print(format_string.format(strings)) print(" Expected:", expected) actual = problem4a(strings) print(" Actual: ", actual) result = print_result_of_test(expected, actual) passed_tests = passed_tests + result # Test 2: print() print('Test 2:') strings = ['SixSix', 'I am nine', 'This', 'is definitely fun!'] expected = -1 print(' This test case calls:') print(format_string.format(strings)) print(" Expected:", expected) actual = problem4a(strings) print(" Actual: ", actual) result = print_result_of_test(expected, actual) passed_tests = passed_tests + result # Test 3: print() print('Test 3:') strings = ('01234567', '0123456789', '0123', '0123456') expected = '0123456' print(' This test case calls:') print(format_string.format(strings)) print(" Expected:", expected) actual = problem4a(strings) print(" Actual: ", actual) result = print_result_of_test(expected, actual) passed_tests = passed_tests + result if passed_tests == 3: testing_helper.print_colored('\n*** PASSED all 3 tests! Good! ***', color='blue') else: testing_helper.print_colored('\n*** FAILED at least one test! ***', color='red') def problem4a(strings): """ What comes in: A sequence of strings. What goes out: Returns the first string in the sequence whose length is prime, or -1 if there is no string in the sequence whose length is prime. Side effects: None. Examples: problem4a(['Nope', '', 'Hello', 'Goodbye', 'More stuff']) returns 'Hello' because: -- the length of 'Nope' is 4 (which is NOT prime) -- the length of the empty string is 0 (which is NOT prime), and -- the length of 'Hello' is 5 (which IS prime) problem4a(['SixSix', 'I am nine', 'This', 'is definitely fun!']) returns -1 because the lengths of the strings are 6, 9, 4, and 18, respectively, none of which are prime. problem4a(('01234567', '0123456789', '0123', '0123456')) returns '0123456' because the lengths of the strings are 8, 10, 4, and 7, respectively, only the last of which is prime. Type hints: :type [str] """ # ------------------------------------------------------------------------- # TODO: 3. Implement and test this function. # Tests have been written for you (above). # ------------------------------------------------------------------------- def run_test_problem4b(): """ Tests the problem4b function. """ ########################################################################### # THESE TESTS ARE ALREADY DONE. DO NOT CHANGE THEM. # You may add more tests if you wish, but you are not required to do so. ########################################################################### print() print('--------------------------------------------------') print('Testing the problem4b function:') print('--------------------------------------------------') format_string = ' problem4b( {} )' passed_tests = 0 # Test 1: print() print('Test 1:') seq = [('SixSix', 'I am nine', 'This', 'is definitely fun!'), ('Nope', '', 'Hello', 'Goodbye', 'More stuff'), ('', 'This is seventeen', 'abc'), ('none', 'here')] expected = True print(' This test case calls:') print(format_string.format(seq)) print(" Expected:", expected) actual = problem4b(seq) print(" Actual: ", actual) result = print_result_of_test(expected, actual) passed_tests = passed_tests + result # Test 2: print() print('Test 2:') seq = [('SixSix', 'I am nine', 'This', 'is definitely fun!'), ('Nope', 'even', 'not prime'), ('', 'This is eighteen!!', '1234567890'), ('none', 'here')] expected = False print(' This test case calls:') print(format_string.format(seq)) print(" Expected:", expected) actual = problem4b(seq) print(" Actual: ", actual) result = print_result_of_test(expected, actual) passed_tests = passed_tests + result if passed_tests == 2: testing_helper.print_colored('\n*** PASSED all 2 tests! Good! ***', color='blue') else: testing_helper.print_colored('\n*** FAILED at least one test! ***', color='red') # ----------------------------------------------------------------------------- # *** IMPORTANT: THIS PROBLEM COUNTS ONLY 2 POINTS # AND HAS AN ELEGANT SOLUTION. DO NOT GET STUCK ON IT! # ----------------------------------------------------------------------------- def problem4b(list_of_tuples_of_strings): """ What comes in: A list of tuples of strings. What goes out: Returns True if there is any string in the list of tuples of strings whose length is prime. Side effects: None. Examples: problem4b( [('SixSix', 'I am nine', 'This', 'is definitely fun!'), ('Nope', '', 'Hello', 'Goodbye', 'More stuff'), ('', 'This is seventeen', 'abc'), ('none', 'here')] ) returns True because it DOES have strings whose lengths are prime (namely, 'Hello', 'Goodbye', 'This is seventeen', and 'abc') problem4b( [('SixSix', 'I am nine', 'This', 'is definitely fun!'), ('Nope', 'even', 'not prime'), ('', 'This is eighteen!', '1234567890'), ('none', 'here')] ) returns False because the lengths of the strings are 6, 9, 4, 18, 4, 4, 9, 0, 18, and 10, respectively, none of which are prime. Type hints: :type [str] """ # ------------------------------------------------------------------------- # TODO: 4. Implement and test this function. # Tests have been written for you (above). # *** IMPORTANT: THIS PROBLEM COUNTS ONLY 2 POINTS # AND HAS AN ELEGANT SOLUTION. DO NOT GET STUCK ON IT! # ------------------------------------------------------------------------- ############################################################################### # Our tests use the following to print error messages in red. # Do NOT change it. You do NOT have to do anything with it. ############################################################################### def print_result_of_test(expected, actual): return testing_helper.print_result_of_test(expected, actual) # To allow color-coding the output to the console: USE_COLORING = True # Change to False to revert to OLD style coloring testing_helper.USE_COLORING = USE_COLORING if USE_COLORING: # noinspection PyShadowingBuiltins print = testing_helper.print_colored else: # noinspection PyShadowingBuiltins print = testing_helper.print_uncolored # ----------------------------------------------------------------------------- # Calls main to start the ball rolling. # The try .. except prevents error messages on the console from being # intermingled with ordinary output to the console. # ----------------------------------------------------------------------------- try: main() except Exception: print('ERROR - While running this test,', color='red') print('your code raised the following exception:', color='red') print() time.sleep(1) raise
4c1aa3500a1b7b27dcff8c5227bf07422226cc17
mrfaiz/distributed-system-ws20-21
/lab3/server/historires.py
802
3.515625
4
from threading import Lock from data import Data from utility import currrent_time_secs class Histories: def __init__(self): self.lock = Lock() self.history_list: [Data] = [] self.latest_history_entry_time = currrent_time_secs() ## Global static variable, common for all history objects def appendHistory(self, data: Data): with self.lock: self.latest_history_entry_time = currrent_time_secs() self.history_list.append(data) def clearHistory(self): with self.lock: self.history_list.clear() def get_history_list(self): with self.lock: return self.history_list def get_latest_history_entry_time(self): with self.lock: return self.latest_history_entry_time
fa515d7e16764d27c37778c3a53c9f61da80d7cb
gusLopezC/Python-Curso
/21.decoradores.py
589
3.625
4
#decorador es una funcion que recibe una una #funciones y crea una funcion #A recibe como parametro B para poder crear C def decorado(valido): def fundecorado(func):#AyB def nueva_funcion(*args,**kwargs):#C print("Vamos a ejecutar la funcion") resultado = func(*args,**kwargs) print("se ejecuto la funcion") return resultado return nueva_funcion#C return fundecorado @decorado def saluda(): print("Hola") @decorado(valido= True) def suma(n1,n2): return n1+n2 #saluda() resultado=suma(5,4) print(resultado)
23c36e451cc88339364fa405d97f1b42fe0438c9
ljseok/PrimeNumebrAlgorithm
/ImprovePrimeNumebr.py
355
3.59375
4
import math def is_prime_number(x): # 소수 판별 함수 정의 for i in range(2,int(math.sqrt(x))+1): # 2부터 x의 제곱근 까지 모든 수를 확인한다 if x % i == 0: # 해당수로 나누어 떨어진다면 return False # 소수가 아님 return True # 소수 print(is_prime_number(4)) print(is_prime_number(17))
3918481af5f3142ef9b4b1658d731d5a5f082883
thomas-marcoux/assignments
/AI/red_planet/source/planet.py
642
3.625
4
import math import point class Planet(point.Point): def __init__(self, name, dist, mass, angle, vel): self.name = name self.mass = mass self.vel = vel super().__init__(dist, angle) def rotate(self, time): self.angle += self.vel * time self.setCartesianCoord() Sun = Planet("Sun", 0.0, 100.0, 0.0, 0.0) Mercury = Planet("Mercury", 100.0, 20.0, math.pi/2.0, 2.0*math.pi/288) Venus = Planet("Venus", 200.0, 40.0, math.pi/2.0, 2.0*math.pi/225) Earth = Planet("Earth", 400.0, 100.0, math.pi/2.0, 2.0*math.pi/365) Mars = Planet("Mars", 800.0, 80.0, math.pi/2.0, 2.0*math.pi/687)
bb66d3d91efca0c70547d9326c2a43f58df3a38b
ariprasathsakthivel/DataStructures
/Strings/CharacterReplace.py
1,086
3.921875
4
''' @Author: Ariprasath @Date: 2021-09-11 19:19:30 @Last Modified by: Ariprasath @Last Modified time: 2021-09-11 19:40:00 @Title : Replace a charater into $ ''' class Error(Exception): def __init__(self,message): super().__init__(self.message) class EmptyStringError(Error): def __init__(self): self.messgae="The string is empty" super().__init__(self.message) def char_replace(sample_data): ''' Description: Checks the first character in a string throughout the string and replaces it with $ Parameter: sample_data(string): a strings containing letters, numbers etc,.. Return: sample_data(string): string that is replaced with the $ character Raises: EmptyStringError: Thrown when the passed string is empty ''' replace_val=sample_data[0] sample_data=sample_data[1:].replace(sample_data[0],"$") return replace_val+sample_data if __name__=="__main__": sample_data="restart" try: print(char_replace(sample_data)) except EmptyStringError as E: print(E)
001402f83d8943c13741c39eac07fe6a5fbb4420
nalssee/SICP
/eceval/syntax.py
312
3.703125
4
def is_self_evaluating(exp): """number, string, booleans """ return \ isinstance(exp, int) or isinstance(exp, float) \ or (isinstance(exp, str) and len(exp) >= 2 and exp[0] == '"' and exp[-1] == '"') \ or exp == 'true' or exp == 'false' def text_of_quotation(exp): pass
ebe673e043cdc5e9bc368ec9b75fe98f35631c3b
markuspettbor/fysproj
/numtools.py
3,503
3.75
4
import numpy as np # This is our code #some usefull things def integrate(func, t, teacher_is_strict = True): ''' Function for integration. Assumes func is a function that evaluates a numpy array of x-values. If teacher_is_strict is True, the midpoint method is used. If not, the built-in numpy trapz-function is used. Returns sum, which is integrated evaluated over the range of x. ''' try: assert teacher_is_strict dt = np.diff(t) t_mid = t[:-1] + dt/2 sum = np.sum(func(t_mid)*dt) except AssertionError: sum = np.trapz(func(t), t) return sum def norm(vector, ax = 0): #normalises a vector return np.linalg.norm(vector, axis = ax) def unit_vector(vector, ax = 0): #creates the unit vector return vector/norm(vector, ax) def euler_cromer_simple(x, v, dt, acc = 0): # Euler chromer scheme v = v + dt*acc x = x + dt*v return v, x def leapfrog(x0, v0, t, acc): ''' Calculates integral using a Leapfrog method. x0, y0 are initial values, t is a vector of intervals. Note that it is assumed that dt = t(1) - t(0) is constant. It has to be, in order for energy to be conserved, apparently. acc is a method or function that evaluates the acceleration at a given time t. Assumes x0, v0 are of same length ''' x = np.zeros((len(t), len(x0))) v = np.zeros((len(t), len(v0))) x[0] = x0 v[0] = v0 for i in range(len(t)-1): dt = t[i+1] - t[i] x[i+1] = x[i] + v[i]*dt + 0.5*acc(x[i], t[i])*dt**2 v[i+1] = v[i] + 0.5*(acc(x[i], t[i]) + acc(x[i+1], t[i+1]))*dt return np.transpose(x), np.transpose(v) def leapfrog_simple(x0, v0, dt, acc): x = x0 + v0*dt + 0.5*acc(x0)*dt**2 v = v0 + 0.5*(acc(x0)+ acc(x))*dt return x, v def euler_fuel_consumption(speed, mass, force, consumption, dt = 0.001): a = force/mass speed = speed + a*dt mass = mass - consumption*dt return speed, mass def rotate(vector, angle): # Rotation matrix x1 = np.cos(angle) x2 = np.sin(angle) rotmatrix = np.array([[x1, -x2], [x2, x1]]) return np.dot(rotmatrix, vector) def angle_between(v1, v2): """ https://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python Returns the angle in radians between vectors 'v1' and 'v2':: """ v1_u = unit_vector(v1) v2_u = unit_vector(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) def create_radial_velocity(v, v_pec_r, i): vr = v[1]*np.sin(i) #ROW OR COL??? v_real = vr + v_pec_r return noiceify(v_real, 0, max(vr)/5) def least_squares(function, vars): pass return noiceify(v_real, 0, max(vr)/5) def noiceify(x, mu, sig): return (x + np.random.normal(mu, sig, len(x))) #mu sigma length from scipy.interpolate import interp1d def interp_xin(t,x): if len(x.shape) == 2 and len(x) == 2: x_int = np.zeros(len(x)).tolist() for j in range(len(x)): x_int[j] = interp1d(t,x[j]) elif len(x.shape) == 3 and len(x) == 2: x_int = np.zeros([len(x), len(x[0])]).tolist() for i in range(len(x[0])): for j in range(len(x)): x_int[j][i] = interp1d(t,x[j,i]) else: assert(False, 'The function is not the correct shape, needs to be\ 2d or 3d with x/y/z... in the first spot [x = dimension of array,\ i = number of things with x as dimension, and n = length of i]') return x_int
bf597158843338a7d6ed6a71a83fcfac5e1f24f6
jmvazquezl/programacion
/Prácticas Phyton/P4/P4E5 - IMPORTE Y DIGA SI EL CAJERO LE PUEDE SACAR EL DINERO.py
1,128
3.53125
4
# JOSE MANUEL - P4E5 - IMPORTE EN EUROS Y DIGA SI EL CAJERO AUTOMATICO LE PUEDE # DAR DICHO IMPORTE UTILIZANDO EL MISMO BILLETE Y EL MÁS GRANDE importe = int(input("Introduce el importe que quieres sacar: ")) if (importe % 500 == 0): cantidad = importe // 500 print('', importe, 'el cajero te devuelve', cantidad, 'billete de 500') elif (importe % 200 == 0): cantidad = importe // 200 print('', importe, 'el cajero te devuelve', cantidad, 'billete de 200') elif (importe % 100 == 0): cantidad = importe // 100 print('', importe, 'el cajero te devuelve', cantidad, 'billete de 100') elif (importe % 50 == 0): cantidad = importe // 50 print('', importe, 'el cajero te devuelve', cantidad, 'billete de 50') elif (importe % 20 == 0): cantidad = importe // 20 print('', importe, 'el cajero te devuelve', cantidad, 'billetes de 20') elif (importe % 10 == 0): cantidad = importe // 10 print('', importe, 'el cajero te devuelve', cantidad, 'billete de 10') elif (importe % 5 == 0): cantidad = importe // 5 print('', importe, 'el cajero te devuelve', cantidad, 'billete de 5')
15433013a66e68e4d70586002e92e3aa865e1e20
mbartido/RNGSimulator
/minion.py
398
3.640625
4
# Minion class class minion: health = 0 name = "" def __init__(self, health, name): self.health = health self.name = name def __str__(self): return "(Name: " + str(self.name) + ", Health: " + str(self.health) + ")" def isDead(self): if (self.health == 0): return True else: return False
52881a0fc55f4245088f4ce2578715ebe51063e8
wuxu1019/leetcode_sophia
/hard/heap/test_23_Merge_k_Sorted_Lists.py
906
4
4
""" Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ kdata = [(l.val, i) for i, l in enumerate(lists) if l] rt = p = ListNode(0) heapq.heapify(kdata) while kdata: data, location = heapq.heappop(kdata) p.next = lists[location] p = p.next lists[location] = lists[location].next if lists[location]: heapq.heappush(kdata, (lists[location].val, location)) return rt.next
4f5db4f11fa3b70da64aee5b03653208b93a37d4
Ftoma123/100daysprograming
/day24.py
907
4.3125
4
#copy dictionary using copy() dict1 = { 'brand':'Ford', 'model':'Mustang', 'year':1934 } new_dict = dict1.copy() print(new_dict) #copy dictionary using dict() new_dict1 = dict(dict1) print(new_dict1) #Nested Dictionaries family_dict = { 'child1':{ 'name':'Noura', 'year':2000 }, 'child2':{ 'name':'Nada', 'year':2006 }, 'child3':{ 'name':'Nasser', 'year':2012 } } print(family_dict) #Nested Dictionaries by creating 3 indivisual dict then incluse them in other dict child1 = { 'name':'Abodi', 'year': 2008 } child2 = { 'name':'Ftoma', 'year': 2005 } child3 = { 'name':'Monera', 'year': 2019 } family_dic1 ={ 'child1': child1, 'child2': child2, 'child3': child3 } print(family_dic1) #creat dictionay using dict() dict2 = dict(brand='Ford', model='Mustang', year=1934) print(dict2)
7dbb990d12c86424a130417b922782f4584916a8
leticiamchd/Curso-Em-Video---Python
/Desafio015.py
184
3.71875
4
dias = int(input('Quantos dias de aluguel do carro ? ')) km = float(input('Quantos km percorridos no total ? ')) print('O valor total do aluguel foi de R${}'.format(dias*60+km*0.15))
a4395b57140bbbc8355cae894bf8eef91f7ba94d
KaioPlandel/Estudos-Python-3
/livro/ex3.36.py
167
3.75
4
#crie uma função que abrevie o dia da semana mostrando apenas os 3 primeiras letras def abreviacao(st): return st[0:3].upper() print(abreviacao('terça feira'))
3c3d3401b92f68e8b58b5e09948ca25873a43a03
thehitmanranjan/Handwritten-Digit-Recognition
/Handwritten Digit Recognition.py
10,066
3.796875
4
#!/usr/bin/env python # coding: utf-8 # In[8]: import numpy as np import matplotlib.pyplot as plt #conda install -c conda-forge tensorflow #conda install -c anaconda keras or conda install -c anaconda keras or nothing from tensorflow import keras from keras.datasets.mnist import load_data # # 1. Load the Dataset # In[9]: data=load_data() #Returns a tuple np.shape(data) # The data has two rows and two columns. # 1. First row is the training data and the second row is the testing data # 2. First column consists of images and the second column is the labels of the images. # In[10]: #Unpack the data. #First row is unpacked into training tuples #Second row is unpacked into testing tuples (train_images,train_labels),(test_images,test_labels)=data # In[11]: #Print the first training tuple image train_images[0] # The above data is represented in the for of 28*28 pixel. There are 28 rows, each comprising of 28 values. The images are stored as numpy arrays # In[12]: #Print the first training label train_labels[0] # In[13]: #Put all the labels in a set so as to find all the unqiue labels. set(train_labels) #or np.unique(train_labels) # # 2. Visualize the dataset # To show some images of the dataset with their labels. # In[14]: #plt.figure(figsize=(width,height)) is used to set the width and height of the image. plt.figure(figsize=(10,10)) for i in range(5): #plt.subplot(row,columns,index of the subplot):- used to create a figure. plt.subplot(1,5,i+1)#index of the subplot says, which position the subplot will take #No xticks or yticks plt.xticks([]) plt.yticks([]) #plt.imshow() i used to show data as an image. plt.imshow(train_images[i],cmap=plt.cm.binary) #cmap used to change the image to binary plt.xlabel(train_labels[i]) #Label of the image # # 3. Data Preprocessing # Scaling the data. (Convert all the pixel values which are in the range (0-225) to (0-1). This is to reduce the complexity of data and faster training process) # In[15]: #Before scaling,the pixels of first training image are as follows: np.unique(train_images[0]) # In[16]: train_images=train_images/255.0 test_images=test_images/255.0 # In[17]: #After scaling, the pixels of first training image are as follows: np.unique(train_images[0]) # # 4. Build the model # STEPS TO BUILD THE MODEL: # # 1. Set up the input layer, hidden layer and the output layer # 2. Complete the model # Building block of a neural network in Keras Library is the LAYER. It is a sequential object. # Each layer consists of several perceptons. # In[18]: model=keras.Sequential([ #Flatten is used to flatten the input layer keras.layers.Flatten(input_shape=(28,28)), #in Hidden Layer, the first argument is the no. of neurons, chosen at random keras.layers.Dense(128,activation='sigmoid'), #Last Layer has 10 neurons because there is only 10 output neurons (0-9) keras.layers.Dense(10,activation='softmax') ]) # EXAMINE THE STRUCTURE OF WEIGHTS OF THE HIDDEN LAYER # In[19]: #To get the hidden layer from the model hidden_layer=model.layers[1] #Returns a list of two numpy arrays: #1. Matrix of weights. #2. Array of biases. weights=hidden_layer.get_weights() #Shape of weight: (784,128) signifies that each neuron of input layer is connected to each neuron of the hidden layer #Shape of biases: 128 signifies the bias of each neuron of hidden layer print('Shape of weights: ',np.shape(weights[0])) print('Shape of biases: ',np.shape(weights[1])) # EXAMINE THE STRUCTURE OF WEIGHTS OF THE OUTPUT LAYER # In[ ]: #To get the output layer from the model output_layer=model.layers[2] #Returns a list of two numpy arrays: #1. Matrix of weights. #2. Array of biases. weights=output_layer.get_weights() #Shape of weight: (128,10) signifies that each neuron of hidden layer is connected to each neuron of the output layer #Shape of biases: 10 signifies the bias of each neuron of output layer print('Shape of weights: ',np.shape(weights[0])) print('Shape of biases: ',np.shape(weights[1])) # # Compile the model # Before training, we have to compile the model, otherwise and exception will be thrown during training. # 1. Loss Functions: # This measures how accurate the model is during training. We will use SPARSE CATEGORICAL CROSS ENTROPY as the loss function # 2. Optimizer: # This is how the model is updated based on the data it sees and its loss function. We will use Stocastic Gradient Descent (SGD) # 3. Metrics: # Used to montior the training and testings steps. The following example uses acuracy, the fraction of images that are correcylt classified. # In[20]: #lr= Learning rate #decay= #momentum=Technique to drive sgd faster towards the optimal state. sgd=keras.optimizers.SGD(lr=0.5,decay=1e-6,momentum=0.5) #A metric function is similar to a loss function, except that the results from evaluating a metric are not used when training the model. model.compile(optimizer=sgd,loss='sparse_categorical_crossentropy',metrics=['accuracy']) # # 4. Train the model # 1. Feed the training data to the model (train_images and train_labels) # In[22]: #epochs=no. of times to itearate over the entire dataset #batch_size=no. of samples after which the weights are to be updated #validation_split=ratio of training data to be used as validation data history=model.fit(train_images,train_labels,epochs=10,batch_size=100,validation_split=0.1) # # 5. Visualize the training model # Visulaize validation loss against loss over the training data set per epoch # The fit() method on a Keras Model returns a History object. The History.history attribute is a dictionary recording training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable) # In[23]: #to store validation loss values val_losses=history.history['val_loss'] #to story training loss values losses=history.history['loss'] #for x-coordinates of the plot function indices=range(len(losses)) plt.figure(figsize=(10,5)) plt.plot(indices,val_losses,color='r') plt.plot(indices,losses,color='g') #To display Legend plt.legend(['Validation loss','Loss']) plt.xlabel('Epochs') plt.ylabel('Loss') # If the loss of the training set is less than the loss over the validation set, it is known as Overfitting. # # When the validation loss is slightly higher than the training loss, it's okay. But, if the validation loss is very high than the training loss, it's Overfitting. # # 6. Compute accuracy and make predictions # # Evaluate the model by computing the accuracy over testing data # In[24]: #Returns the loss value & metrics values for the model in test mode. test_loss, test_acc=model.evaluate(test_images, test_labels) print('Test Accuracy', test_acc) print('Test Loss', test_loss) # # Make predictions # In[26]: #Generates output predictions for the input samples. #Returns Numpy array(s) of predictions (in the form of confidence levels for each class for each image) predictions=model.predict(test_images) # # Define a function to display image along with confidence levels # Confidence levels show how confident is the model to predict ambiguous images. # In[28]: def plot_confidence(images,labels,predictions): #15 is the width and 30 is the height of the figure plt.figure(figsize=(15,30)) #to set spacing between the plots. hspace=spacing between rows. wspace=spacing between columns. plt.subplots_adjust(top=0.99,bottom=0.01,hspace=1.5,wspace=0) #Location of a particular plot. plot_index=0; for i in range(len(images)): plot_index+=1 #plt.subplot(no. of rows,no. of columns, plot no.) #First columns=images. Second column=bar plot of confidence level plt.subplot(len(images),2,plot_index) #Display the image in grayscale plt.imshow(images[i],cmap=plt.cm.binary) #Correct label correct_label=str(labels[i]) #Predicted label is the argument in predictions with highest confidence #argmax() Returns the indices of the maximum values along an axis. #The value of the prediction will be max on the predicetd label. #The predicted label and numpy array's index are same for this problem. predicted_label=str(np.argmax(predictions[i])) title='Correct label: '+correct_label+'\n'+'Predicted Label: '+predicted_label if predicted_label!=correct_label: plt.title(title,backgroundcolor='r',color='w') else: plt.title(title,backgroundcolor='g',color='w') #To remove the xticks and yticks plt.xticks([]) plt.yticks([]) plot_index+=1 plt.subplot(len(images),2,plot_index) #Display the bar graph with x axis as digits 0-9 and y axis as the predictions of those digits plt.bar(range(10),predictions[i]) plt.xticks(range(10)) plt.ylim(0,1) #as the confidence level lies in that range # In[41]: #Select first 10 images and their label from the testing datasets. #Also select the first 10 predictions. images=test_images[:10] labels=test_labels[:10] test_predictions=predictions[:10] plot_confidence(images,labels,test_predictions) # # 7. Display the images that could not be classified correctly by the model # In[31]: incorrect_indices=list() for i in range(len(predictions)): predicted_label=np.argmax(predictions[i]) if predicted_label!=test_labels[i]: incorrect_indices.append(i) print('No. of incorrectly classified images: ',len(incorrect_indices)) #Select the first 10 incorrect indices. incorrect_indices=incorrect_indices[:10] incorrect_images=[test_images[i] for i in incorrect_indices] incorrect_labels=[test_labels[i] for i in incorrect_indices] incorrect_predictions=[predictions[i] for i in incorrect_indices] plot_confidence(incorrect_images,incorrect_labels,incorrect_predictions) # In[ ]:
121c6e3fae13a965fde294dcf69bac29da82df2e
Sinlawat/Laland
/BMI.py
1,544
3.65625
4
import math from tkinter import * def description(x): if x > 30: return "อ้วนมาก" elif x > 25 and x <= 30: return "อ้วน" elif x > 23 and x <= 25: return "น้ำหนักเกิน" elif x > 18.6 and x <= 23: return "ปกติ" elif x < 18.5: return "ผอมเกินไป" def LeftClickCalculateButton(event): showLabel.configure(text=float(textboxWeight.get())/math.pow(float(textboxHeight.get())/100,2)) def LeftClickShowButton(event): bmi = float(textboxWeight.get())/math.pow(float(textboxHeight.get())/100,2) ResultLabel.configure(text=description(bmi)) mainWindow = Tk() lableHeight = Label(mainWindow,text = "ส่วนสูง (Cm.)") lableHeight.grid(row=0,column=0) textboxHeight = Entry(mainWindow) textboxHeight.grid(row=0,column=1) lableWeight = Label(mainWindow,text = "น้ำหนัก (Kg.)") lableWeight.grid(row=1,column=0) textboxWeight = Entry(mainWindow) textboxWeight.grid(row=1,column=1) calculateButton = Button(mainWindow,text = "คำนวณ") calculateButton.bind('<Button-1>',LeftClickCalculateButton) calculateButton.grid(row=2,column=0) showLabel = Label(mainWindow,text="ผลลัพธ์") showLabel.grid(row=2,column=1) showButton = Button(mainWindow,text = "แสดงผล") showButton.bind('<Button-1>',LeftClickShowButton) showButton.grid(row=3,column=0) ResultLabel = Label(mainWindow,text = "สรุปผล") ResultLabel.grid(row=3,column=1) mainWindow.mainloop()
85733ff859a3d9b52996d023910d4c9cbcf9c823
lvoinescu/python-daily-training
/custom_alphabetical_order/main.py
2,532
4.21875
4
# Given a list of words, and an arbitrary alphabetical order, verify that the words # are in order of the alphabetical order. # # Example: # # Input: # words = ["abcd", "efgh"], order="zyxwvutsrqponmlkjihgfedcba" # # Output: False # # Explanation: 'e' comes before 'a' so 'efgh' should come before 'abcd' # # Example 2: # # Input: # words = ["zyx", "zyxw", "zyxwy"], # order="zyxwvutsrqponmlkjihgfedcba" # # Output: True # # Explanation: The words are in increasing alphabetical order def is_sorted_given_order(words, order): order_index = {} i = 0 order_index[""] = -1 for character in order: order_index[character] = i i += 1 char_index = 0 done = False while not done: max_char = "" for word in words: done = True if char_index >= len(word): continue else: done = False if max_char is not None and order_index[word[char_index]] < order_index[max_char]: return False if order_index[word[char_index]] > order_index[max_char]: max_char = word[char_index] char_index += 1 return True def is_regularly_sorted(words): char_index = 0 done = False while not done: max_char = "" for word in words: done = True if char_index >= len(word): continue else: done = False if max_char is not None and word[char_index] < max_char: return False if word[char_index] > max_char: max_char = word[char_index] char_index += 1 return True print("ab abx abf:", "sorted" if is_regularly_sorted(["ab", "abx", "abf"]) else "not sorted") print("ab abd abf:", "sorted" if is_regularly_sorted(["ab", "abd", "abf"]) else "not sorted") print("a ab abd abf:", "sorted" if is_regularly_sorted(["a"",ab", "abd", "abf"]) else "not sorted") print("ax ab abd abf:", "sorted" if is_regularly_sorted(["ax", "ab", "abd", "abf"]) else "not sorted") print("ax ab abcd abf:", "sorted" if is_regularly_sorted(["a", "ab", "abxd", "abf"]) else "not sorted") print() sample1 = ["abcd", "efgh"] order1 = "zyxwvutsrqponmlkjihgfedcba" print(sample1, "Sorted" if is_sorted_given_order(sample1, order1) else "not sorted", "according to order", order1) # False sample2 = ["zyx", "zyxw", "zyxwy"] order2 = "zyxwvutsrqponmlkjihgfedcba" print(sample2, "Sorted" if is_sorted_given_order(sample2, order2) else "not sorted", "according to order", order2) # # True
3aa6fcc0e32e26f1e3af55bb6d19a54fc6e80e30
9a24f0/USTH
/ML/lab1/petrol.py
1,033
3.59375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn import metrics dataset = pd.read_csv("data/petrol_consumption.csv") print(dataset) X = dataset[['Petrol_tax', 'Average_income', 'Paved_Highways', 'Population_Driver_licence(%)']] y = dataset['Petrol_Consumption'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) regressor = LinearRegression() regressor.fit(X_train, y_train) coeff_df = pd.DataFrame(regressor.coef_, X.columns, columns=['Coefficient']) print(coeff_df) y_pred = regressor.predict(X_test) df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred}) print(df) print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred)) print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred)) print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
12527b261943cc4df52b8c59398ccf26e3c58fea
Aludeku/Python-course-backup
/lista exercícios/PythonTeste/desafio090.py
479
3.84375
4
aluno = {} aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Média de {aluno["nome"]}: ')) if aluno['media'] >= 7: aluno['status'] = 'aprovado' elif 5 <= aluno['media'] <= 7: aluno['status'] = 'recuperação' else: aluno['status'] = 'reprovado' print('-=' * 20) print(f' -O nome é igual a {aluno["nome"]}.') print(f' -A média é igual à {aluno["media"]}.') print(f' -A situação de {aluno["nome"]} é de {aluno["status"]}.') print(' -end.')