blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
373ea31569d28fdfde9edd3ad787c79b8e0be363
jordoin/nute
/MagicThings/MagicOrb/intSqrt.py
688
3.640625
4
from math import sqrt def intQuadro(v, n, shift = 1): return v * v / n def intSqrtTable(n, shift = 1): return (intQuadro(v, n, shift) for v in xrange(n + 1)) def strIntSqrtTable(n, shift = 1): return ', '.join(str(v) for v in intSqrtTable(n, shift)) def printIntSqrtTable(n, indent, maxLength, shift = 1): s = ' ' * indent length = indent for w in strIntSqrtTable(n, shift).split(' '): w = w.replace(',', ', ') if length + len(w) >= maxLength: print s s = ' ' * indent length = indent s += w length += len(w) if s: print s printIntSqrtTable(255, 8, 80)
a5cd3caa423ec6774f53b111184ad7ba85308fc6
mdagaro/pyminesweeper
/Menu.py
1,782
4.03125
4
import pygame class Button: """ Button to exist on the main menu. Does a function when clicked. """ def __init__(self,location,on_click=None,text='button',size=(100,30),buffer = (0,0)): """ Constructor :param location: where the button will appear on the screen :param on_click: what function the button will do when clicked :param text: the text displayed on the button :param size: the height and width of the button, default = (100,30) :param buffer: how much the text will be offset from the upper left corner """ if on_click is None: on_click = lambda: None self._click = on_click self.text = text self.location = self.x, self.y = location self.buffer = self.bufferx, self.buffery = buffer self.font_location = (self.x + self.bufferx, self.y + self.buffery) self.rect = pygame.Rect(location,size) def draw(self,screen,fonthandler): pygame.draw.rect(screen, pygame.Color('green'), self.rect) screen.blit(fonthandler[('consolas', 24)].render(self.text, True, pygame.Color('black')), self.font_location) def on_click(self): """ Does function when clicked with safeguards. """ try: self._click() except TypeError as err: print("Button.on_click must be a function\n{0}".format(err)) raise class Menu: """ A class to hold the buttons on the main menu screen. """ def __init__(self, buttons=()): """ Constructor :param buttons: the buttons to be added to the main menu screen """ self.visible = True self.buttons = buttons def draw(self, screen, fonts): """ Draws the main menu screen. :param screen: the screen to be drawn on :param fonts: a fonthandler for easy font access """ if self.visible: screen.fill(pygame.Color('black')) for b in self.buttons: b.draw(screen,fonts)
496bf4547a2eb0b1dc7b05d501e8fe642dcc6349
eduardoanj/cursopyton
/Nova pasta (2)/exercGuanabara/ex3542.py
951
4.125
4
lado1 = float(input('Digite o primeiro lado: ')) lado2 = float(input('Digite o segundo lado: ')) lado3 = float(input('Digite o terceiro lado: ')) if ((lado1 + lado2) <= lado3): print('não forma um triangulo!!') else: if ((lado2 + lado3) <= lado1): print('não forma um triangulo!!') else: if ((lado3 +lado1) <= lado2): print('não forma triangulo!!') else: if lado1 == lado2 == lado3: print('Forma um triângulo equilátero') elif lado1 == lado2 and lado2 != lado3: print('Forma um triângulo isóceles') elif lado2 == lado3 and lado3 != lado1: print('Forma um triângulo isóceles') elif lado3 == lado1 and lado1 != lado2: print('Forma um triângulo isóceles') elif lado1 != lado2 and lado2 != lado3 and lado3 != lado1: print('É um triângulo escaleno')
f2a437e213e27cef99d7a8767bacc30e77698ff4
joohyun333/programmers
/백준/DP/외판원 순회.py
203
3.59375
4
# https://www.acmicpc.net/problem/2098 def isIn(i, a): print(bin(i)[2:]) print(bin(a)[2:]) if a & (1 << (i - 2)) != 0: return True else: return False print(isIn(8, 9))
a57e2c9bb84bc6cf57996e1b8413aa8c4744fbc9
JohnGoure/leetcode-solutions
/compress.py
527
3.734375
4
def compress(word): letterCount = {} compress = False for letter in word: if letter in letterCount: letterCount[letter] += 1 else: letterCount[letter] = 1 if letterCount[letter] > 1: compress = True if compress == True: compressedWord = "" for letter in letterCount: compressedWord += letter compressedWord += str(letterCount[letter]) return compressedWord return word print(compress('John'))
ca6fda4171e630dd1c22d307280e086d63dc79dd
ZahraAnam/Audio_work
/file_reader.py
830
3.53125
4
import os import sys def scan_folder(parent): # iterate over all the files in directory 'parent' for file_name in os.listdir(parent): if file_name.endswith(".wav"): # if it's a txt file, print its name (or do whatever you want) print(file_name) else: current_path = "".join((parent, "/", file_name)) if os.path.isdir(current_path): # if we're checking a sub-directory, recursively call this method scan_folder(current_path) parent_path = '/home/anam/Desktop/Leipzig' #scan_folder(parent_path) shpfiles = [] for dirpath, subdirs, files in os.walk(parent_path): for x in files: if x.endswith(".wav"): print(os.path.join(dirpath, x)) print("\n") print(os.path.split(dirpath))
8cd2c469671ab21d73cf73a6a71ad1073c245465
scriptclump/algorithms
/small-program/2power_range.py
206
4.0625
4
def power(num): # use anonymous function result = list(map(lambda x: 2 ** x, range(num))) print("The total num are:",num) for i in range(num): print("2 raised to power",i,"is",result[i]) power(10)
c068f6fb1db2fdad4414f362391a22fbb631cc64
Teja2229/assignment
/list7.py
169
3.859375
4
list7=[22,11,33,44,55] print("original list:") print(list7) for i in list7: if(i%2 == 0): list7.remove(i) print("list after removing even numbers:") print(list7)
b6cee2c4586775679583ae70aa482c238258f2de
MatthewPlemmons/holbertonschool-higher_level_programming
/0x06-python-classes/102-square.py
888
4.09375
4
#!/usr/bin/python3 class Square: def __init__(self, size=0): self.size = size @property def size(self): return self.__size @size.setter def size(self, value): if type(value) is not int and type(value) is not float: raise TypeError('size must be an number') if value < 0: raise ValueError('size must be >= 0') else: self.__size = value def area(self): return self.__size ** 2 def __lt__(self, sq): return self.area() < sq.area() def __le__(self, sq): return self.area() <= sq.area() def __eq__(self, sq): return self.area() == sq.area() def __ne__(self, sq): return self.area() != sq.area() def __gt__(self, sq): return self.area() > sq.area() def __ge__(self, sq): return self.area() >= sq.area()
7d979f2ff52e84058bc39d8d41010db28c1abb0d
lindameh/cpy5p2
/q05_find_month_days.py
1,153
4.15625
4
def check_leap(): if year % 4 == 0: if year % 100 != 0 or year % 400 == 0: return True else: return False else: return False year = int(input("Enter year: ")) month = int(input("Enter month in number: ")) if month == 1: print("January {} has 31 days".format(year)) elif month == 3: print("March {} has 31 days".format(year)) elif month == 4: print("April {} has 30 days".format(year)) elif month == 5: print("May {} has 31 days".format(year)) elif month == 6: print("June {} has 30 days".format(year)) elif month == 7: print("July {} has 31 days".format(year)) elif month == 8: print("August {} has 31 days".format(year)) elif month == 9: print("September {} has 30 days".format(year)) elif month == 10: print("October {} has 31 days".format(year)) elif month == 11: print("November {} has 30 days".format(year)) elif month == 12: print("December {} has 31 days".format(year)) elif month == 2: if check_leap(): print("February {} has 29 days".format(year)) else: print("February {} has 28 days".format(year))
fa0846885e3555ba03d9ef2629f0445ecaeed937
JDSanto/intro-distribuidos-tp1
/src/lib/server.py
673
3.53125
4
class Server: def __init__(self, host, port, logger): """ Creates the Server object, which will be used to receive and send files. `dest_folder` is the folder where the files will be saved. """ self.host = host self.port = port self.logger = logger def start(self): """ Starts the server, which will wait and process client connections and requests. """ raise NotImplementedError() def wait_for_connection(self): raise NotImplementedError() def stop_server(self): """ Stops the server. """ raise NotImplementedError()
695ecfc3ec8b381b55543cd20700428eb6de5e8f
chenchcgt/python-challenge
/PyBank/main.py
2,624
3.703125
4
import os import csv csvpath = os.path.join("Resources","budget_data.csv") months = 0 total_amount = 0 maximum = 0 minimum = 0 amount_prior = 0 difference_current = 0 difference_sum = 0 avg_month = 0 avg = 0 compare_current = 0 with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") headers = next(csvreader, None) # Loop through rows for row in csvreader: months = months + 1 total_amount = total_amount + int(row[1]) if row[0] != 'Jan-2010': difference_current = int(row[1]) - amount_prior difference_sum = difference_sum + difference_current amount_prior = int(row[1]) compare_current = difference_current # Calculate average by total months - first month avg_month = months - 1 avg = difference_sum/avg_month # Compare if current difference is larger than max if compare_current >= maximum: maximum = compare_current max_month_desc = row[0] # Compare if current difference is lower than min elif compare_current <= minimum: minimum = compare_current min_month_desc = row[0] else: amount_prior = int(row[1]) # with open(csvpath) as csvfile: # csvreader = csv.reader(csvfile, delimiter=",") # headers = next(csvreader, None) # maximum = max(csvreader, key=lambda row: int(row[1])) # with open(csvpath) as csvfile: # csvreader = csv.reader(csvfile, delimiter=",") # headers = next(csvreader, None) # minimum = min(csvreader, key=lambda row: int(row[1])) # Output print print(f"Financial Analysis") print(f"__________________") print(f"Total Months: {months}") print(f"Total :$ {total_amount}") print(f"Average Change: $ {round(avg,2)}") print(f"Greatest Increase in Profits: {max_month_desc} (${maximum})") print(f"Greatest Decrease in Profits: {min_month_desc} (${minimum})") # Write to file titles = ["Total Months", "Total: $", "Average Change: $", "Greatest Increase in Profits: ", "Greatest Decrease in Profits: "] values = [months, total_amount, round(avg,2), max_month_desc+'('+str(maximum)+')', min_month_desc+'('+str(minimum)+')'] result_csv = zip(titles, values) output_file = os.path.join("analysis","budget_final.csv") with open(output_file, "w") as finalfile: writer = csv.writer(finalfile) writer.writerow(['Financial Analysis']) writer.writerow(['_____________________']) writer.writerows(result_csv)
2ae3ca2f068a403a397f63f375cfe3a4872212f0
al-mahi/AI_II_CS5793
/BasicClassifiers/BasicClassifiersComplexData.py
6,039
3.703125
4
#!/usr/bin/python """ Author: S M Al Mahi CS5793: Artificial Intelligence II Assignment 1: Basic classifiers Solution for Part 5 """ from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from KDTree import cKDTree if __name__ == "__main__": """ Part#5 Increasing complexity Create a new set of training and test data. This time, each classification will be produced by multiple distributions, rather than just one. Draw 1000 samples each from ten different overlapping Gaussian distributions. Five of them should be labeled as class 0 and the others class 1. An example is shown in Figure 2. Perform the same linear and nearest neighbor classification processes, calculate the classification accuracy and plot the results. """ N = 1000 mean0 = [0, 0] cov0 = [[.5, 0], [0, 20]] X0 = np.random.multivariate_normal(mean0, cov0, N) mean1 = [2.5, 7] cov1 = [[3, 0], [0, 1]] X1 = np.random.multivariate_normal(mean1, cov1, N) mean2 = [2.5, -6] cov2 = [[3, 0], [0, 1]] X2 = np.random.multivariate_normal(mean2, cov2, N) mean3 = [5, 0.5] cov3 = [[0.5, 0], [0, 10]] X3 = np.random.multivariate_normal(mean3, cov3, N) mean4 = [0, -4] cov4 = [[10, 0], [2, 1]] X4 = np.random.multivariate_normal(mean4, cov4, N) # class 2 mean5 = [3, 3] cov5 = [[2, 0], [0, 2]] X5 = np.random.multivariate_normal(mean5, cov5, N) mean6 = [3.5, 2] cov6 = [[3, 2], [0, 1]] X6 = np.random.multivariate_normal(mean6, cov6, N) mean7 = [4, 1.5] cov7 = [[1, 0], [0, 5]] X7 = np.random.multivariate_normal(mean7, cov7, N) mean8 = [1.5, 1] cov8 = [[2, 3], [0, 10]] X8 = np.random.multivariate_normal(mean8, cov8, N) mean9 = [5, -2] cov9 = [[10, 3], [0, 1]] X9 = np.random.multivariate_normal(mean9, cov9, N) X = np.vstack((X0, X1, X2, X3, X4, X5, X6, X7, X8, X9)) y = np.vstack((np.zeros(shape=(5*N, 1), dtype='int'), np.ones(shape=(5*N, 1), dtype='int'))) mask = np.random.random(size=(10*N)) < .8 training_X = X[mask] training_y = y[mask] test_X = X[np.logical_not(mask)] test_y = y[np.logical_not(mask)] plt.plot(X[:5 * N, 0], X[:5 * N, 1], 'x', c='b', label="data calss 0") plt.plot(X[5 * N:, 0], X[5 * N:, 1], 'x', c='r', label="data calss 1") plt.title("Data from multiple multi variant 2d Gaussian") plt.legend(loc="lower right") plt.show() beta = np.linalg.inv(training_X.T.dot(training_X)).dot(training_X.T).dot(training_y) y_hat = test_X.dot(beta) >= 0.5 # differs from problem description. (?) print("Linear Classifier accuracy from multiple multi variant 2d Gaussian distribution: {:.2%}".format(float(sum(y_hat == test_y)) / len(test_y))) training_from_class0 = training_X[training_y.flatten() == 0] training_from_class1 = training_X[training_y.flatten() == 1] correct_from_class0 = test_X[np.logical_and(test_y.flatten() == 0, y_hat.flatten() == 0)] correct_from_class1 = test_X[np.logical_and(test_y.flatten() == 1, y_hat.flatten() == 1)] incorrect_from_class0 = test_X[np.logical_and(test_y.flatten() == 0, y_hat.flatten() == 1)] incorrect_from_class1 = test_X[np.logical_and(test_y.flatten() == 1, y_hat.flatten() == 0)] plt.plot(training_from_class0[:, 0], training_from_class0[:, 1], 'x', c='b', label='Training set from class 0') plt.plot(training_from_class1[:, 0], training_from_class1[:, 1], 'x', c='r', label='Training set from class 1') plt.plot(correct_from_class0[:, 0], correct_from_class0[:, 1], 'o', c='y', label='Correctly classified test set from class 0') plt.plot(correct_from_class1[:, 0], correct_from_class1[:, 1], 's', c='c', label='Correctly classified test set from class 1') plt.plot(incorrect_from_class0[:, 0], incorrect_from_class0[:, 1], '.', c='m', label='Incorrectly classified test set from class 0') plt.plot(incorrect_from_class1[:, 0], incorrect_from_class1[:, 1], '.', c='k', label='Incorrectly classified test set from class 1') plt.legend(loc='lower right', fontsize='small') plt.title("Linear Classifier from multiple multi variant 2d Gaussian distribution") plt.show() kdtreeClassifier = cKDTree(training_X) y_hat = training_y[kdtreeClassifier.query(test_X[:], k=1)[1]] print("KDTree Classifier accuracy from multiple multi variant 2d Gaussian distribution: {:.2%}".format( float(sum(y_hat == test_y)) / len(test_y))) correct_from_class0 = test_X[np.logical_and(test_y.flatten() == 0, y_hat.flatten() == 0)] correct_from_class1 = test_X[np.logical_and(test_y.flatten() == 1, y_hat.flatten() == 1)] incorrect_from_class0 = test_X[np.logical_and(test_y.flatten() == 0, y_hat.flatten() == 1)] incorrect_from_class1 = test_X[np.logical_and(test_y.flatten() == 1, y_hat.flatten() == 0)] plt.plot(training_from_class0[:, 0], training_from_class0[:, 1], 'x', c='b', label='Training set from class 0') plt.plot(training_from_class1[:, 0], training_from_class1[:, 1], 'x', c='r', label='Training set from class 1') plt.plot(correct_from_class0[:, 0], correct_from_class0[:, 1], 'o', c='y', label='Correctly classified test set from class 0') plt.plot(correct_from_class1[:, 0], correct_from_class1[:, 1], 's', c='c', label='Correctly classified test set from class 1') plt.plot(incorrect_from_class0[:, 0], incorrect_from_class0[:, 1], '.', c='m', label='Incorrectly classified test set from class 0') plt.plot(incorrect_from_class1[:, 0], incorrect_from_class1[:, 1], '.', c='k', label='Incorrectly classified test set from class 1') plt.legend(loc='lower right', fontsize='small') plt.title("KDtree Classifier from multiple multi variant 2d Gaussian distribution") plt.show()
1c480ed31d1e97753bca63aeb689fbff9c25b6b8
TheAlgorithms/Python
/data_structures/binary_tree/binary_tree_traversals.py
5,373
4.09375
4
# https://en.wikipedia.org/wiki/Tree_traversal from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class Node: data: int left: Node | None = None right: Node | None = None def make_tree() -> Node | None: r""" The below tree 1 / \ 2 3 / \ 4 5 """ tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) return tree def preorder(root: Node | None) -> list[int]: """ Pre-order traversal visits root node, left subtree, right subtree. >>> preorder(make_tree()) [1, 2, 4, 5, 3] """ return [root.data, *preorder(root.left), *preorder(root.right)] if root else [] def postorder(root: Node | None) -> list[int]: """ Post-order traversal visits left subtree, right subtree, root node. >>> postorder(make_tree()) [4, 5, 2, 3, 1] """ return postorder(root.left) + postorder(root.right) + [root.data] if root else [] def inorder(root: Node | None) -> list[int]: """ In-order traversal visits left subtree, root node, right subtree. >>> inorder(make_tree()) [4, 2, 5, 1, 3] """ return [*inorder(root.left), root.data, *inorder(root.right)] if root else [] def reverse_inorder(root: Node | None) -> list[int]: """ Reverse in-order traversal visits right subtree, root node, left subtree. >>> reverse_inorder(make_tree()) [3, 1, 5, 2, 4] """ return ( [*reverse_inorder(root.right), root.data, *reverse_inorder(root.left)] if root else [] ) def height(root: Node | None) -> int: """ Recursive function for calculating the height of the binary tree. >>> height(None) 0 >>> height(make_tree()) 3 """ return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order(root: Node | None) -> Sequence[Node | None]: """ Returns a list of nodes value from a whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. """ output: list[Any] = [] if root is None: return output process_queue = deque([root]) while process_queue: node = process_queue.popleft() output.append(node.data) if node.left: process_queue.append(node.left) if node.right: process_queue.append(node.right) return output def get_nodes_from_left_to_right( root: Node | None, level: int ) -> Sequence[Node | None]: """ Returns a list of nodes value from a particular level: Left to right direction of the binary tree. """ output: list[Any] = [] def populate_output(root: Node | None, level: int) -> None: if not root: return if level == 1: output.append(root.data) elif level > 1: populate_output(root.left, level - 1) populate_output(root.right, level - 1) populate_output(root, level) return output def get_nodes_from_right_to_left( root: Node | None, level: int ) -> Sequence[Node | None]: """ Returns a list of nodes value from a particular level: Right to left direction of the binary tree. """ output: list[Any] = [] def populate_output(root: Node | None, level: int) -> None: if root is None: return if level == 1: output.append(root.data) elif level > 1: populate_output(root.right, level - 1) populate_output(root.left, level - 1) populate_output(root, level) return output def zigzag(root: Node | None) -> Sequence[Node | None] | list[Any]: """ ZigZag traverse: Returns a list of nodes value from left to right and right to left, alternatively. """ if root is None: return [] output: list[Sequence[Node | None]] = [] flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if not flag: output.append(get_nodes_from_left_to_right(root, h)) flag = 1 else: output.append(get_nodes_from_right_to_left(root, h)) flag = 0 return output def main() -> None: # Main function for testing. # Create binary tree. root = make_tree() # All Traversals of the binary are as follows: print(f"In-order Traversal: {inorder(root)}") print(f"Reverse In-order Traversal: {reverse_inorder(root)}") print(f"Pre-order Traversal: {preorder(root)}") print(f"Post-order Traversal: {postorder(root)}", "\n") print(f"Height of Tree: {height(root)}", "\n") print("Complete Level Order Traversal: ") print(level_order(root), "\n") print("Level-wise order Traversal: ") for level in range(1, height(root) + 1): print(f"Level {level}:", get_nodes_from_left_to_right(root, level=level)) print("\nZigZag order Traversal: ") print(zigzag(root)) if __name__ == "__main__": import doctest doctest.testmod() main()
47168d5f8825aeecf06143d1a2a53983055798bb
10354828/programming_big_data_pp
/CA1/functions_calculator.py
1,325
4.15625
4
# Name: Paul Prew # Student Number: 10354828 # Programming for Big Data # CA 1 # The following are functions that are called by the program named # 'app_calculator.py'. import math def calc_add(num1,num2) : result = num1 + num2 return result def calc_subtract(num1, num2) : result = num1 - num2 return result def calc_multiply(num1, num2) : result = num1 * num2 return result def calc_divide(num1, num2) : if num2 == 0: result = 'Divide by Zero Error!' else: result = num1 / num2 return result def calc_exp(num1, num2) : result = num1 ** num2 return result def calc_squareroot(num) : if num < 0 : result = 'Number Error!' else : result = math.sqrt(num) return result def calc_square(num) : result = calc_exp(num, 2) return result def calc_cube(num) : result = calc_exp(num, 3) return result # if degrees = 180 or 360 then sine(degrees) is 0 def calc_sine(deg): if deg % 180 == 0 : result = 0 else : result = math.sin(math.radians(deg)) return result # if degrees = 90 or 270 then cosine(degrees) is 0 def calc_cosine(deg): if (deg - 90)% 180 == 0 : result = 0 else : result = math.cos(math.radians(deg)) return result
50b91525131379a69dc3c2319b57aea7a21e687e
parasjain-12/HackerEarth-Solution
/Monk Takes a Walk.py
224
3.53125
4
t = int(input()) for _ in range(t): s = input() s = s.lower() c=0 for i in range(len(s)): if s[i] =='a' or s[i] =='e' or s[i] =='i' or s[i] =='o' or s[i] =='u': c+=1 print(c)
d7f6b461023c28ba3427b8c2ecef83eefcf31eac
Amenable-C/Python_practice
/sumAndDifference.py
406
3.703125
4
codeMate = ''' def sum(a, b): return a + b def diff(a, b): return abs(a - b) ''' with open('sumAndDiff.py', 'w') as f: f.write(codeMate) import sumAndDiff s = input("Input two numvers: ") nums = s.split(', ') n1 = int(nums[0]) n2 = int(nums[1]) print("Sum =", sumAndDiff.sum(n1, n2)) # 바로 sum 쓰면 안됨. 모듈이름 먼저 적어줘야 함. print("Diff =", sumAndDiff.diff(n1, n2))
ceea1a81fad56ccbed8e3ac1671fb24b91bf1104
aedaniel411/uaf-programacion-python
/2020b/fibo2.py
128
3.890625
4
n = int (input('Cuantos numeros de fibonacii?')) i = 0 a, b = 0, 1 while i < n : print(a) a, b = b, a+b i = i + 1
c16ae19bc18c042bd972333a50d654f1d23d21ab
sandeepmaxpayne/Udacity_Computer_Vision_Nanodegree
/Computer Vision Intro/Project1_Facial_Key_Point/models.py
2,245
3.796875
4
## TODO: define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TODO: Define all the layers of this CNN, the only requirements are: ## 1. This network takes in a square (same width and height), grayscale image as input ## 2. It ends with a linear layer that represents the keypoints ## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs # As an example, you've been given a convolutional layer, which you may (but don't have to) change: # 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel self.conv1 = nn.Conv2d(1, 32, 5, padding=2) #32x224x224 self.pool1 = nn.MaxPool2d(4, 4) #32*56*56 ## Note that among the layers to add, consider including: # maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting ## initializing other convolution layers self.conv2 = nn.Conv2d(32,64, 3, padding=1) #64X56X56 self.pool2 = nn.MaxPool2d(4, 4) #64X14X14 self.linear1 = nn.Linear(64*14*14, 500) self.linear2 = nn.Linear(500, 68*2) def forward(self, x): ## TODO: Define the feedforward behavior of this model ## x is the input image and, as an example, here you may choose to include a pool/conv step: ## x = self.pool(F.relu(self.conv1(x))) drop1 = nn.Dropout(0.1) drop2 = nn.Dropout(0.2) drop3 = nn.Dropout(0.3) x = drop1(self.pool1(F.relu(self.conv1(x)))) x = drop2(self.pool2(F.relu(self.conv2(x)))) x = x.view(x.size(0), -1) # flatten x = drop3(F.relu(self.linear1(x))) x = self.linear2(x) # a modified x, having gone through all the layers of your model, should be returned return x
2b6a39584d2eddb70f05663e5d7d3139c190a077
ksshin21/python_basic
/11 integer_summing.py
687
3.5625
4
# 11일차 #합계구하기 - for 반복문 1차시도(KS) # 이 프로그램은 음수를 포함한 두 정수 범위(양 끝 수 포함)의 합계를 구합니다. # 프로그램을 종료하기 위해서는 문자 'q'를 입력하세요. while True: print('\nIf you want to stop, press q ...') start = input('시작 수(음수 포함 정수) : ') if start == 'q': # 음수도 처리하기 위해 마침 문자를 따로 지정 break first = int(start) # first = int(first)로 작성해도 가능 last = int(input('끝 수(음수 포함 정수) : ')) sum = 0 for i in range(first, last+1): sum += i print('합계 : ', sum)
7df192d0e3690c813e6990b4f5db3d8944f5e6e1
nkhanhng/namkhanh-fundamental-c4e15
/session3/homework/update_guess_my_number.py
486
3.890625
4
from random import randint print('''Think of a number from 0 to 100 "c" if my guess is 'C'orrect "s" if my guess is 'S'maller than your number "l" if my guess is 'L'arger than your number''') x = randint(1, 100) loop = True count = 0 while loop: print("Is", x," your number", end=' ') ans = input() count += 1 if ans == "c": print("I knew it") loop = False elif ans == "s": x = randint(x,100) elif ans == "l": x = randint(1,x)
e2ca594e02ec1f91db93f238bdc7e629bc6ae135
cassieeric/python_crawler
/网络爬虫实战基础章节学习记录/chapter3--正则表达式的使用/re.sub.py
148
3.578125
4
# -*- coding: utf-8 -*- import re st = "忙完这阵子,就可以接着忙下阵子了" new_st = re.sub(r'忙', '过', st) print(new_st)
c91c33b7dcd989cac8a2defa1ee31054c0b85b68
devedu-AI/Data-Flair-Python-Course
/5.Working_On_Python_Part-3/High Low.py
199
3.609375
4
def high_low(n): for row in range(1,n+1): for col in range(row,n+1): print(col,end=' ') for col in range(n-1,row-1,-1): print(col,end=' ') print()
ff4fbdc774f1cc800026d05bfdb7fe0d9a0986f0
FelipeRodri03/Trabajos-algoritmos-y-programaci-n
/Taller python/Ejercicio6.py
345
3.796875
4
""" Entradas Cantidad de hombres-->int-->a Cantidad de mujeres-->int-->b Salidas Porcentaje de hombres-->float-->d Porcentaje de mujeres-->float-->e """ inp=(input(). split(" ")) a,b=inp a=int(a) b=int(b) #caja negra c=a+b d=(a*100)/c e=(b*100)/c print("El porcentaje de hombres es "+str(d)+"%" ) print("El porcentaje de mujeres es "+str(e)+"%")
ad6f8af9a027ced4b44b07a1fc0039175cc87077
htang22/python_simple_projects
/question_3.py
841
4.53125
5
def swap_pair(user_input): new_word = "" last_letter = "" list_word_char = [letter for letter in user_input] odd_char = [letter for letter in list_word_char[:-1:2]] #List comprehension does the same thing a a for loop but better. Example of a fore loop below # odd_char = [] # for letter in user_input[:-1:2]: # odd_char.append(letter) even_char = [letter for letter in list_word_char[1::2]] if len(user_input) % 2 == 1: #Checks to see if the the user word length is odd last_letter = list_word_char[-1] odd_char = [letter for letter in list_word_char[:-1:2]] for n in range(len(user_input)//2): new_word += f"{even_char[n]}{odd_char[n]}" new_word += last_letter return new_word user_word = input("Enter a word: ") print(swap_pair(user_word))
562b93e3e33458fbf8893b14b5030b7aa3819c3e
AlexPlatin/Grokking_Algorithms_book
/Recursive_tryings.py
788
3.984375
4
def recursive_factorial(x: int) -> int: if x == 1: return 1 else: return x * recursive_factorial(x - 1) def loop_factorial(x: int) -> int: if x == 1: return 1 else: for i in range(x - 1, 0, -1): x *= i return x def recursive_sum(list_values: list) -> int: if len(list_values) == 0: return 0 else: return list_values.pop(0) + recursive_sum(list_values) def recursive_max(list_values: list) -> int: if len(list_values) == 2: return list_values[0] if list_values[0] > list_values[1] else list_values[1] submax = recursive_max(list_values[1:]) return list_values[0] if list_values[0] > submax else submax if __name__ == '__main__': print(recursive_sum([2, 20, 3, 4]))
69b38898844a70dbfd3e693c3842de37c29a0e7a
vinayvsalunkhe/pythonex
/LISTex.py
317
4.34375
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 4 09:14:06 2020 @author: Admin """ #python program to find largest number in a list a=[] n=int(input("enter the number of elements:")) for i in range(1,n+1): b=int(input("enter element:")) a.append(b) a.sort() print("Largest element is:",a[n-1])
930f10b3d7a0a50350360fd5a143023782a7b530
encorechow/CS519
/homework3/xyz.py
937
3.875
4
#import pdb def find(arr): ''' Find all triples (x, y, z) that meet the form x + y = z. ''' sort_arr = sorted(arr) result = [] #pdb.set_trace() # For each element in an array we find the corresponding x and y by two pointers. for i, ele in enumerate(sort_arr): p1 = 0 p2 = len(arr) - 1 while p1 < p2: # Filter the same index p1 = p1 + 1 if p1 == i else p1 p2 = p2 - 1 if p2 == i else p2 if p1 >= p2: break if sort_arr[p1] + sort_arr[p2] == ele: result.append((sort_arr[p1], sort_arr[p2], ele)) p1 += 1 p2 -= 1 elif sort_arr[p1] + sort_arr[p2] < ele: p1 += 1 else: p2 -= 1 return result if __name__ == "__main__": print(find([1, 4, 2, 3, 5])) print(find([4,5,2,3,7,9,8])) print(find([2,3]))
00151d27d5747091603f83967363362a19cbcf6f
gilady19-meet/yl1201718
/cheack.py
823
3.625
4
rom turtle import * import random import time colormode(255) tracer(0) hideturtle() class Circle(Turtle): def __init__(self,x,y,dx,dy,radius): Turtle.__init__(self) self.pu() self.goto(x,y) self.dx = dx self.dy = dy self.shape("circle") self.shapesize(radius/10) self.radius = radius r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) self.color(r,g,b) def move(self): curentx = self.xcor() curenty = self.ycor() self.goto(curentx + self.dx,curenty + self.dy) my_x = random.randint(-100,100) my_y = random.randint(-100,100) circle1 = Circle(my_x,my_y,1,1,60) my_x = random.randint(-100,100) my_y = random.randint(-100,100) circle2 = Circle(my_x,my_y,1,1,60) while True: circle1.move() circle2.move() getscreen().update() time.sleep(0.01) mainloop()
a90b175edf7be4a4fa7ab961a3497332d949212a
smanilov/sisyphus-boulder
/sishead.py
9,981
3.9375
4
import sys def print_usage(): # Print usage if len(sys.argv) < 5: format = """ Usage: %s source_file token_file unroll_factor output_file source_file a file containing c/c++/java source code token_file a file containing one token per line; These tokens are used to identify which loops to unroll - the ones containing any of the tokens in their bodies. Empty lines are ignored. unroll_factor the times each loop body should be copied in the output file output_file name of the output file """ sys.exit(format % sys.argv[0]) def read_source_file(): # Read source file source_file_name = sys.argv[1] source_file = open(source_file_name) return source_file.read() def read_token_file(): # Read token file; filter empty lines token_file_name = sys.argv[2] token_file = open(token_file_name) tokens_str = token_file.read() tokens = tokens_str.split('\n') return [t for t in tokens if t] def read_unroll_factor(): # Read source file unroll_factor = sys.argv[3] return int(unroll_factor) def read_output_file_name(): # Read source file return sys.argv[4] def find_all_scopes(text): # Find all scopes print "Finding all scopes..." open_scope = "{" close_scope = "}" open_comment = ["/*", "//"] close_comment = ["*/", "\n"] open_string = "\"" close_string = "\"" not_close_string = "\\\"" in_comment = -1 in_string = False scopes = [] stack = [] for i in range(len(text)): # handle strings and comments if not in_comment is -1: if text.startswith(close_comment[in_comment], i): in_comment = -1 continue # don't check anything else if in_string: if text.startswith(close_string, i) and \ not text.startswith(not_close_string, i-1): in_string = False continue # don't check anything else # not in_string and not in_comment for j in range(len(open_comment)): if text.startswith(open_comment[j], i): in_comment = j if text.startswith(open_string, i): in_string = True # actual scope building logic if text.startswith(open_scope, i): stack.append(i) if text.startswith(close_scope, i): try: k = stack.pop() scopes.append((k, i)) except IndexError: print "Unexpected closing bracket at index", i raise return scopes def find_all_for_loops(text, scopes): # Find all for loops print "Finding all for loops..." for_loops = [] token = "for" index = text.find(token) while not index is -1: found = -1 for i in range(len(scopes)): # if the closing brace is after the for keyword then # either that scope is the for body, or it is contained # by it if scopes[i][1] > index: found = i break if found is -1: print "could not find for loop body" continue i = found while i + 1 < len(scopes): i += 1 if scopes[i][0] < index: # scope containing for keyword break if scopes[i][0] < scopes[found][0]: # scope containing scope found = i continue if scopes[i][0] > scopes[found][1]: # next scope continue # see if the scope belongs to the for loop semicols = 0 for i in range(index, scopes[found][0]): if text[i] is ";": semicols += 1 if not semicols is 2: # TODO: C++11 curly braces initialization print "could not find for loop body" print "index:", index, "found:", found, \ "semicols:", semicols else: for_loops.append((index, found)) index = text.find(token, index + 1) return for_loops def detect_loops_for_unrolling(for_loops, tokens, text, scopes): # Search for tokens print "Detecting loops for unrolling..." unroll_loop = [False] * len(for_loops) for token in tokens: index = text.find(token) while not index is -1: found = -1 for i in range(len(for_loops)): s = scopes[for_loops[i][1]] if s[0] < index and s[1] > index: found = i break # find nested loops that contain the token i = found while i + 1 < len(for_loops): i += 1 f = scopes[for_loops[found][1]] s = scopes[for_loops[i][1]] if s[0] < index and s[1] > index: # s contains the token found = i if s[0] < f[0] or s[1] > f[1]: break if not found is -1: found2 = -1 for i in range(found, len(for_loops)): s = scopes[for_loops[i][1]] # if index is out of the scope s if s[0] > index or s[1] < index: found2 = i - 1 break # if index was in all of the nested scopes then # make the inner-most for loop its owner if found2 is -1: found2 = len(for_loops) - 1 found = found2 unroll_loop[found] = True index = text.find(token, index + 1) return unroll_loop def get_loop_iterator(mod): """Empty result indicates error.""" i = mod.find("++") if not i is -1: if i is 0: return mod[i + 2 : ] else: return mod[ : i] i = mod.find("+=") if not i is -1: return mod[ : i] return "" def get_loop_increment(mod): """-1 as a result indicates error.""" if not mod.find("++") is -1: return 1 i = mod.find("+=") if not i is -1: return int(mod[i + 2 : ]) return -1 def gen_unroll_for_decl(old_for_declaration, itr, inc, unroll_factor): new_inc = inc* unroll_factor l = old_for_declaration.rfind(";") h = old_for_declaration.rfind(")") new_decl = old_for_declaration[ : l + 1] new_decl += " " + itr + " += " + str(new_inc) new_decl += old_for_declaration[h : ] return new_decl import re def gen_new_text(text, for_loops, scopes, unroll_loop, unroll_factor): print "Generating output..." ident = " " new_line = "\n" new_text = "" offset = 0 for i in range(len(unroll_loop)): if unroll_loop[i]: new_text += text[offset : for_loops[i][0]] # get loop body s = scopes[for_loops[i][1]] loop_body = text[s[0] + 2 + len(ident): s[1]] # isolate loop modifier l = text.rfind(";", for_loops[i][0], s[0]) h = text.rfind(")", for_loops[i][0], s[0]) mod = text[l + 1 : h] # drop empty spaces mod = re.sub(' ', '', mod) itr = get_loop_iterator(mod) inc = get_loop_increment(mod) decl = text[for_loops[i][0] : scopes[for_loops[i][1]][0] + 1] new_for = gen_unroll_for_decl(decl, itr, inc, unroll_factor) new_text += new_for + new_line + ident for j in range(unroll_factor): new_text += re.sub(itr, itr + " + " + str(j), loop_body) offset = scopes[for_loops[i][1]][1] new_text += text[offset : ] return new_text def write_output_file(new_text, output_file_name): print "Writing to file..." f = open(output_file_name, "w") f.write(new_text) f.close()
dba95cae497d6770ff037751e15112b76b930625
shubham-pal-au9/DSA
/basic_code/array/max_min.py
415
4
4
# Maximum and minimum of an array using minimum number of comparisons # Solution def max_min(lst): lst.sort() for i in range(len(lst)-1,-1,-1): print "Maximum is",lst[i] break for i in range(0,len(lst)): print "Minimum is:",lst[i] break """ print(max(lst)) print(min(lst)) """ if __name__ == '__main__': lst = [9, 2, 3, 4, 5, 6] max_min(lst)
3fd8d678591c5b1024758a3bfb5a36b7cc31bb28
dvega920/IT-140-Mod-6
/6.12_LAB:Varied-amount-of-input-data.py
745
4.4375
4
# 6.12 LAB: Varied amount of input data # Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max. # # Ex: If the input is: # # 15 20 0 5 # the output is: # # 10 20 # user_input = input() # used list comprehensions to convert string numbers into integers. use sum() to sum the values of i and then divide by # length of user_input.split() (floor result) and assign to variable avg. avg = sum([int(i) for i in user_input.split()]) // len(user_input.split()) # used list comprehensions to convert string numbers into integers. use max() to find the maximum number in the list max = max([int(i) for i in user_input.split()]) print(avg, max)
8a1d6359dc9e4e5ea623f0eb3e1fd9ee7ab15432
davidharvey1986/timeDelay
/PlaneLenser/ContourCounter.py
2,979
3.703125
4
import math class ContourCounter: """ Counts the lengths of contours on a 2d array and the surfaces within them. """ def __init__(self, data): self.data = data def Measure(self, contourLevels): """ Measures the length of contours of specified levels, and the surface within them. contourLevels is a list of contours, or a single value. """ if isinstance(contourLevels, (int, float)): contourLevels = [contourLevels] contours = sorted(contourLevels) def valueToContourIndex(value): """ Does what is says. Maps float value from self.data to index in contourLevels. """ c = -1 # contour index while (c + 1 < len(contourLevels)) and value > contourLevels[c + 1]: c += 1 return c result = [] for it in contourLevels: result.append({ "level" : it, "surface" : 0, "circumference" : 0, # all borders "circumferenceLower" : 0, # only borders with lower values "circumferenceUpper" : 0, # only borders with upper values "circumference_over_sqrtSurface" : None, "circumferenceLower_over_sqrtSurface" : None, "circumferenceUpper_over_sqrtSurface" : None, "integral" : 0 }) def BumpContour(now, before): if now < 0 or now == before: return result[now]["circumference"] += 1 if now > before: result[now]["circumferenceLower"] += 1 elif now < before: result[now]["circumferenceUpper"] += 1 def BumpContours(now, before): BumpContour(now, before) BumpContour(before, now) # HERE WE GO! shape = self.data.shape previousContour = valueToContourIndex(self.data[0][0]) for y in range(shape[0]): valuesFromRowAbove = [valueToContourIndex(it) for it in self.data[y - 1 if y > 0 else 0]] for x in range(shape[1]): c = valueToContourIndex(self.data[y][x]) cAbove = valuesFromRowAbove[x] BumpContours(previousContour, c) BumpContours(cAbove, c) previousContour = c if c > -1: result[c]["surface"] += 1 result[c]["integral"] += self.data[x][y] for it in result: if not it["surface"] == 0: sqtsur = math.sqrt(it["surface"]) it["circumference_over_sqrtSurface"] = it["circumference"] / sqtsur it["circumferenceLower_over_sqrtSurface"] = it["circumferenceLower"] / sqtsur it["circumferenceUpper_over_sqrtSurface"] = it["circumferenceUpper"] / sqtsur return result
4253f4ed293eecb43ece3e64fccda1ff1344c3bb
tclap27/CS104
/conditions.py
154
4.09375
4
temp = input("please enter a value: ") temp = int(temp) if(temp >= 70): print("no jacket required") elif(temp < 70): print("Wear a jacket")
0d5490a0135cf873ab4bf1cc909bbc86fae2af7e
yszpatt/PythonStart
/pythonlearn/train/prac21.py
461
4.03125
4
#!/usr/bin/env python # coding:utf-8 # 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。 # 以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 x2 = 1 for day in range(9, 0, -1): x1 = (x2 + 1) * 2 x2 = x1 print(x2)
d9b123b9d76b724eb31eb89916fccb4d19a52307
1024Person/LearnPy
/Day5/string_find.py
933
3.609375
4
# find string and replace string # method : find() rfind() lfind() rinsex() lindex() replace() s1 = 'transport' result = 'l' in s1 print(result) # s2 = 'ASdsadf' # print(s2.casefold()) # casefold ---->funcation:make every charater字母 postion = s1.find('r') # return index of find str while postion != -1: print(postion) print(s1[postion:]) postion = s1.find('r',postion + 1,len(s1)) # arguments 参数 # http://it.jhliujj.cn/python1982casde/picture/course-level1.png url = 'http://it.jhliujj.cn/python1982casde/picture/course-level1.png' p = url.rfind('/') file_name = url[p + 1:] print(file_name) p = url.rfind('.') file_kz = url[p + 1:] print(file_kz) # 找不到的话,就会报异常 # p = 'hello'.index('x') # print(p) # # replace s1 = 'www.baidu.com' s2 = s1.replace('.','360') # 如果不指定第三个参数,那么就是全部替换, # 第三个参数,指定最多替换多少次 print(s2)
909606bcce11782b89b5a861e4b089453a1a44d8
Changkyuuu/Chapter3
/condition.py
653
4.03125
4
# if -elso a = 1 if a > 5: print('big') a = 1 if a < 5: print('big') # 요고만 출략 a = 3 if a > 5: print('big') else: print('small') # a가 5보다 크면 big를 출력하고 아니면 small을 출력해라 # if - elif - n = -1 if n > 0: print('양수') elif n < 0: print('음수') else: print('0') # spam : 100 # egg : 500 # spagetti : 2000 price = 0 goods = 'egg' if goods == 'spam': price = 100 elif goods == 'egg': price = 500 elif goods == 'spagetti': price == 2000 print(price) # 상황연산자 # message = a>5 ? 'big' : 'small' 다른언어에서는 a = 5 print( 'big 'if a > 5 else 'small')
a137f7177d9fc069e1449a52eaa41925f5e4fc02
karthik-siru/practice-simple
/DP/dsa_31.py
1,264
3.671875
4
''' -> Always look for these two properties 1) Optimal substructure 2) Overlapping The longest common suffix has following optimal substructure property. If last characters match, then we reduce both lengths by 1 LCSuff(X, Y, m, n) = LCSuff(X, Y, m-1, n-1) + 1 if X[m-1] = Y[n-1] If last characters do not match, then result is 0, i.e., LCSuff(X, Y, m, n) = 0 if (X[m-1] != Y[n-1]) Now we consider suffixes of different substrings ending at different indexes. The maximum length Longest Common Suffix is the longest common substring. LCSubStr(X, Y, m, n) = Max(LCSuff(X, Y, i, j)) where 1 <= i <= m and 1 <= j <= n ''' class Solution: def longestCommonSubstr(self, S1, S2, n, m): # code here LcSuffix = [[0 for i in range(n+1)] for j in range (m+1)] result = 0 for i in range (m+1): for j in range(n+1) : if i ==0 or j ==0 : LcSuffix[i][j] = 0 elif S2[i-1] == S1[j-1] : LcSuffix[i][j] = 1 + LcSuffix[i-1][j-1] result = max(result , LcSuffix[i][j]) else : LcSuffix[i][j] = 0 return result
9025eab34b12a318393bc182d6755f678f935aa5
Dragon91011/Camp-Code
/pirate.py
1,019
4.25
4
speech = {"hello":"arrrrr", "friend": "matey", "scallywags": "people", "water": "rum" ,"food": "turkey leg"} def engtopirate(englishstring): #need dictonary, e.g speech = {'hello':'arrrrr'} #split english string into list of words englishlist = englishstring.split(" ") piratees = "" #fro every word in that list, for word in englishlist: #print("Right now, I'm looking at word <%s>" %word) #check if wird in dictonary # if word in dictonary, use that value if word in speech: if word in speech: #print(" I found the word! The word is now:") piratees = piratees + " " + speech[word] # print(piratees) #if word not in dictonary,use same word looked up. if word not in speech: piratees = piratees + " " + word #return the pirate sentence return piratees piratephrase = engtopirate(" Hello good friend") print(piratephrase)
4e2e445d8bce337333e3f5a2c1b2d11ea3b71cb1
shivamchandra3/test_python_scripts
/largest_so_far_for_loop.py
227
3.9375
4
largest_so_far= -1 print('Before1', largest_so_far) for the_num in [21, 31, 15, 23, 45]: if the_num>largest_so_far: largest_so_far= the_num print(largest_so_far, the_num) print('After', largest_so_far)
2baadada39ecbd0ae4ffc4406a7ba0e5b099a427
Ananya-KU/Best-Enlist-CV-2021-Python-tasks
/Day10.py
915
4.1875
4
# Create a real time scenario for inheritance example Banking concept class bank_Account: def __init__(self): self.balance=400 print("Welcome to Canara Bank") def display(self): print("\n Net Available Balance=",self.balance) #Inheritance class Deposit(bank_Account): def deposit(self): amount = int(input("Enter the amount you want to deposite: ")) self.balance += amount print("\n Amount Deposited:",amount) #Multiple Inheritance class withdraw(bank_Account): def withdraw(self): amount = int(input("Enter the amount you want to withdraw: ")) if (self.balance <= amount): self.balance -= amount print("\n withdraw amount:", amount) else: print("\n Insufficient balance ") a= bank_Account() p=Deposit() p.deposit() q=withdraw() q.withdraw() q.display()
6ff2be1eedd5129134be656ca875e56916c34a3e
ehsan-keshavarzian/pythonlangutil
/pythonlangutil/tests/overload.py
520
3.828125
4
import unittest from pythonlangutil.examples.overload import OverloadTest class Test(unittest.TestCase): def test_overload(self): hit = OverloadTest() self.assertEqual(hit.my_method("Joe"), "Dear Joe", "msg") self.assertEqual(hit.my_method("Joe", True), "Mr. Joe", "msg") self.assertEqual(hit.my_method(1, "Joe"), "Dear Joe", "msg") self.assertRaises(Exception, hit.my_method) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
9370a148b388438432498c7d106d78738d66c3b3
shriya246/Python-Internship
/Day3task3.py
110
3.953125
4
#IF ELSE STATEMENT n1=20 n2=30 if n1>n2: print("n1 is greater") else: print("n2 is greater")
f5237b8d9b3c0f860132ef6792bc2bb9de781d33
chebizarro/foss4gna-python-qgis
/pyqgis_code/python_basics/point.py
370
4.09375
4
class Point: """ Class to model a point in 2D space.""" """ Size of our marker in pixels """ marker_size = 4 def draw(self): """Draw the point on the map canvas""" print "drawing the point" def move(self, new_x, new_y): """ Move the point to a new location on the map canvas""" print "moving the point"
960999417971c0b44c1be7b4e3ec98ef1b360fd6
Ltre/python2-demo
/test3.py
1,043
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Administrator' print '====================================' if 1 > 2: print 'fuck' else: print 'nima' print '====================================' if 1 > 2: print 'fuck' print 'fuck' print 'fuck' else: print 'nima' print 'nima' print 'nima' print '====================================' if 1 > 2: print 'fuck' elif 1 == 1: print 'wocao' else: print 'nima' print '====================================' list = [2,3,4,5,6,7,8] for l in list: print l print '====================================' sum = 0 # notice: sum() is also a function list = [2,3,4,5,6,7,8] for i in list: sum += i print sum print '====================================' print range(5) print range(6,10) print range(1,100,10) print range(1,101,10) print range(1,102,10) print '====================================' name = raw_input('your name:') print name print int(name) # 若输入非整数,则报错 print '===================================='
c9826fb1512f8185564a7a3099d4f8168fcc4aaa
emhart/Misc_Func
/MontyHall.py
1,943
3.65625
4
''' Python version of the Monty Hall problem by EM Hart 2/20/2012 Change scenario by changing the code in strat_dictionary (0,1,2) ''' #from matplotlib import pyplot import numpy.random as np import numpy from scipy import * from matplotlib import pyplot #create an array for Wins pwins = zeros(1000) #####Create an an array of all possible values potential = array([1,2,3]) #####Change this to change your strategy strat_dict = ["Stay","Switch","Random"] master_strat = strat_dict[2] for k in range(1000): wins = zeros(100) for i in range(100): ####Assign a prize value prize = np.random_integers(1,3,1) ###Now make a guess guess = np.random_integers(1,3,1) ####Now we need to figure out which of the doors are revealed if prize == guess: reveals = potential[where(prize!=potential)] reveals = reveals[np.random_integers(0,1,1)] ####Here is where I might have used which in R if prize != guess: reveals = potential[where(prize!=potential)] reveals = reveals[where(guess != reveals)] ####This formulation allows me to have Random strategy if master_strat == "Random": strat = strat_dict[np.random_integers(0,1,1)] if master_strat == "Stay": strat = "Stay" if master_strat == "Switch": strat = "Switch" #Now its simple if we just stay if strat == "Stay": guess = guess ####Switch is a bit more complicated, this is a very inelegant solution compared to R if strat == "Switch": switch = concatenate((guess,reveals)) for j in range(3): exc = potential[j] in switch if exc==False: guess = potential[j] if guess == prize: wins[i]=1 pwins[k]= wins.sum() pwins = pwins/1000 pyplot.hist(pwins,100) pyplot.show()
69c2ebd3d6b771f2c7e33df9c9c1d3fa1ddc5eaf
Logan-cruz/Laccpythondocs
/program/chickenCalculator.txt
551
4.09375
4
#Logan Cruz+ #Chicken cooking calculator def coalNeeded(chickens): chickens/8 return chickens def chickenNeeded(coal): coal*8 return coal answer = input("do you want to calculate chickens or coal today mortal? ") if answer == "Coal" or "coal": chickens= input("How many chickens do you have? ") chickens= int(chickens) print(coalNeeded(chickens)) elif answer == "Chickens" or "chickens": coal=input("How many coal do you have? ") coal=int(coal) print(chickenNeeded(coal)) else: print("That was void and null.")
27f575ad6356cacce633e018daf292c9e7922040
Daniiarz/neobis-1-file-projects
/python/Functions/voting.py
312
3.5
4
num = int(input()) result = [] def voting_result(kek): c0 = 0 c1 = 0 for k in kek: if k == "1": c1 += 1 else: c0 += 1 return (c0 > c1 and "0") or "1" for i in range(num): result.append(voting_result(input().split(" "))) print("\n".join(result))
b4729b95c5cee845f664bec45aea6a8bf049f598
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_199/3294.py
691
3.671875
4
cases = int(raw_input().split()[0]) def to_bool_array(line): return [c == '+' for c in line] def apply(arr, pos, k): for i in range(pos, pos + k): arr[i] = not arr[i] def is_ok(bool_array): return reduce(lambda a, b: a and b, bool_array, True) for i in range(cases): data = raw_input().split() line = data[0] k = int(data[1]) bool_array = to_bool_array(line) counter = 0 for j in range(0, len(bool_array) - k + 1): if not bool_array[j]: apply(bool_array, j, k) counter += 1 if is_ok(bool_array): print 'Case #%d: %d' % (i + 1, counter) else: print 'Case #%d: IMPOSSIBLE' % (i + 1,)
3df9eb78c6bb8ec24acc16c50008f076bf0c73aa
xpessoles/Informatique
/P_05_AlgorithmiqueProgrammation/01_Recursivite/TD_02/programmes/Exercice_0n_dragon_v2.py
596
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from math import cos,sin,pi def TracerSegment(L,ori,x,y): #print("appel",x,y) x.append(x[-1]+L*cos(ori*pi/2)) y.append(x[-1]+L*sin(ori*pi/2)) print("appel",x,y) return x,y def DessineDragon(n,ori): x,y=[0],[0] L=1 if n==0 : print("appel",x,y) x,y = TracerSegment(L,ori,x,y) print("",x,y) else : DessineDragon(n-1,ori) ori = -ori DessineDragon(n-1,ori) return x,y x,y = DessineDragon(2,1) print(x,y)
8493f37401bae4da7c0bc5376861ece6b521dcfc
neil-ash/pe
/pe10_redo.py
1,110
3.609375
4
# 10 redone # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # # Find the sum of all the primes below two million. ############################################################################################################## # Sieve of Eratosthenes method # get input (end point) endpt = int(input('Find all prime numbers up to: ')) # 30 # make list list = [] for x in range(0, endpt + 1): # (0, 31) list.append(x) # check list and delete numbers that aren't prime # for a given divisor (2 -> 7) check all numbers in list for i in range(2, int(endpt ** 0.5) + 1): # (2, 8) FIX for j in range(2, endpt + 1): # (2, 31) # if number is bigger than divisor and divisible, replace with -1 if (j > i) and (j % i == 0): #print(j, "is divisible by", i) list[j] = -1 # make new list with only prime numbers sum = 0 new_list = [] for k in list: # check if list element is != -1 and not 0, 1 if k > 1: new_list.append(k) sum += k # free memory from old list, display new list del list print('\n', new_list, '\n', 'Sum is', sum)
a65e7d17b420e710c5c220970356ea7f67692168
AdamZhouSE/pythonHomework
/Code/CodeRecords/2216/60586/309449.py
103
3.984375
4
s=input() if s==("-1/2+1/2"): print("0/1") elif s==("5/3+1/3"): print("2/1") else: print(s)
517d5e7c28efca7fb6ff62f02acbbf99fa0b1b6a
GGL12/myStudy
/leetcode/剑指offer/min_stack.py
1,676
3.859375
4
class Solution: # def __init__(self): # ''' # 映射栈的最小值情况 # ''' # self.stack = [] # self.min_map_stack = [] # def push(self, node): # if self.min_map_stack: # if self.min_map_stack[-1] < node: # self.min_map_stack.append(self.min_map_stack[-1]) # else: # self.min_map_stack.append(node) # else: # self.min_map_stack.append(node) # self.stack.append(node) # # def pop(self): # if self.stack == []: # return None # if self.min_map_stack == []: # return None # self.min_map_stack.pop() # return self.stack.pop() # # def top(self): # if self.stack == []: # return None # return self.stack[-1] # # def min(self): # if self.min_map_stack: # return self.min_map_stack[-1] # else: # return None ''' 第二种:永远在最后一个元素保留当前的最小值 ''' def __init__(self): self.stack = [] self.save_min_stack = [] def push(self, node): if self.save_min_stack: if self.save_min_stack[-1] > node: self.save_min_stack.append(node) else: self.save_min_stack.append(node) self.stack.append(node) def pop(self): if self.save_min_stack[-1] == self.stack[-1]: self.save_min_stack.pop() return self.stack.pop() def top(self): return self.stack[-1] def min(self): return self.save_min_stack[-1]
80b56ee06f67edf6bace5b54bc4b3ea9cd402637
rijorobins/LuminarDjangoPython
/LuminarProject/RegularExpressions/quantifiers.py
437
4.21875
4
import re #QUANTIFIERS pattern="aaaaabbbbaabaaabahbaa" #x="a+" #it will check single and sequence a #x="a*" #x="a?" #x="^a" #checks if given string starting with a or not ? #x="a$" # checks if given string ends with a or not? #x="a{2}" #it will check for 2 number of a's #x="a{2,3}" #minimum 2 a and maximum 3 a x="a{2,3}" matcher=re.finditer(x,pattern) for match in matcher: print("LOC",match.start()) print(match.group())
d97bfaa38f7b3dcee4ac3bd5f7283a702e137088
zuowutan/stu_python
/condition_stu.py
1,760
4.3125
4
#!/usr/bin/python # coding=utf-8 # Python 的条件语句 if else 学习: # a = 6 # if a > 10: # print "a大于10" # else: # print "a小于10" # # --------------------------------------------------------- # # # Python 的多重条件语句 if elif elif ... else 学习: # if a > 2: # print "a大于2" # elif a < 9: # print "a小于9" # elif a > 7: # print "a大于7" # elif a > 9: # print "a大于9" # elif a > 11: # print "a大于11" # else: # print "a..." # # # --------------------------------------------------------- # # - or (逻辑或):表示两个条件有一个成立(只需要一个为true)时,整个判断条件成功; # # - and(逻辑与):表示只有两个条件同时成立(同时为true)的情况下,整个判断条件才成功。 # data = 5 # if data >= 0 and data <= 10: # 判断值是否在0-10之间 # print '数值在0-10之间' # else: # print "不在0-10之间" # # data = 10 # if data < 20 or data > 5: # 判断值是否在小于20或大于5 # print '数值小于20或数值大于5' # else: # print '数值不在范围之内' # # data = 8 # # 判断值是否在0~5或者10~15之间 # if (data >= 0 and data <= 5) or (data >= 10 and data <= 15): # print '数值在0~5或者10~15之间' # else: # print '数值不在范围之内' # # --------------------------------------------------------- # 解决Python复合布尔表达式中的一些问题: a = 0 b = 1 # 这里把 **and**换成**or**程序就会报错 if a!=0 and b/a > 2: h = True else: h = False g = a > 0 if g or h: print "符合条件" else: print "不符合条件" # if (a > 0) or (b / a > 2): # print "符合条件" # else: # print "不符合条件"
ab57753aa6cdf5987ff4c1a7e8914c4304103d6b
zhangchizju2012/LeetCode
/524.py
1,213
3.59375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Apr 11 12:22:37 2017 @author: zhangchi """ class Solution(object): def findLongestWord(self, s, d): """ :type s: str :type d: List[str] :rtype: str """ result = "" for item in d: if len(item) > len(s): pass else: difference = len(s) - len(item) i = 0 j = 0 label = True itemLength = len(item) while label: if item[i] == s[j]: i += 1 j += 1 else: j += 1 difference -= 1 if difference < 0: label = False if i == itemLength: break if label == True: if len(item) > len(result): result = item elif len(item) == len(result): if item < result: result = item return result
6e473f04c0e0496c2fa2c326033f6db9c9ead2a6
itsanti/uii_py_dev
/HW02/tasks.py
2,730
4.21875
4
''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' for k in range(1, 6): print(k, 0) ''' Задача 2 Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5. ''' fives = 0 for k in range(1, 11): if int(input('Введите число ' + str(k) + ': ')) == 5: fives += 1 print('fives count:', fives) ''' Задача 3 Найти сумму ряда чисел от 1 до 100. Полученный результат вывести на экран. ''' s_ = 0 for k in range(1, 101): s_ += k print('сумма ряда чисел от 1 до 100:', s_) ''' Задача 4 Найти произведение ряда чисел от 1 до 10. Полученный результат вывести на экран. ''' p = 1 for k in range(1, 11): p *= k print('произведение ряда чисел от 1 до 10:', p) ''' Задача 5 Вывести цифры числа на каждой строчке. ''' integer_number = 2129 size = len(str(integer_number)) - 1 while size >= 0: print(integer_number // 10 ** size) integer_number %= 10 ** size size -= 1 ''' Задача 6 Найти сумму цифр числа. ''' integer_number = 123321 s_ = 0 while integer_number > 0: s_ += integer_number % 10 integer_number //= 10 print('сумма цифр числа 123321:', s_) ''' Задача 7 Найти произведение цифр числа. ''' integer_number = 1234 p = 1 while integer_number > 0: p *= integer_number % 10 integer_number //= 10 print('произведение цифр числа 1234:', p) ''' Задача 8 Дать ответ на вопрос: есть ли среди цифр числа 5? ''' integer_number = 12534 while integer_number > 0: if integer_number % 10 == 5: print('Yes, five exists in number.') break integer_number //= 10 else: print('No, five not exists in number.') ''' Задача 9 Найти максимальную цифру в числе ''' integer_number = 123978 max_ = 0 while integer_number > 0: max_ = integer_number % 10 if integer_number % 10 > max_ else max_ integer_number //= 10 print('max digit in number:', max_) ''' Задача 10 Найти количество цифр 5 в числе ''' integer_number = 1255345 fives = 0 while integer_number > 0: if integer_number % 10 == 5: fives += 1 integer_number //= 10 print('fives count in 1255345:', fives)
3801beeb59f1775edc396b0a6ef60a1bfa04ce76
mengyuliu/question_leet
/34.search-for-a-range.py
1,763
3.859375
4
# # [34] Search for a Range # # https://leetcode.com/problems/search-for-a-range/description/ # # algorithms # Medium (31.59%) # Total Accepted: 180.5K # Total Submissions: 571.3K # Testcase Example: '[5,7,7,8,8,10]\n8' # # Given an array of integers sorted in ascending order, find the starting and # ending position of a given target value. # # Your algorithm's runtime complexity must be in the order of O(log n). # # If the target is not found in the array, return [-1, -1]. # # # For example, # Given [5, 7, 7, 8, 8, 10] and target value 8, # return [3, 4]. # # class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) ==0: return [-1, -1] left, right = 0 , len(nums)-1 while (left<=right): middle = (left+right)/2 val = nums[middle] if val == target: if middle == 0: start =0 end = start while end+1 <= len(nums)-1 and nums[end+1] == target: end+=1 return [start, end] else: prev_val = nums[middle-1] if prev_val < val: start = middle end = start while end + 1 <= len(nums) - 1 and nums[end + 1] == target: end += 1 return [start, end] else: right = middle -1 elif val > target: right = middle -1 else: left = middle +1 return [-1, -1]
5e57794a02e70854b23be97efdfbbaff65914144
ashwinitangade/PythonProgramming
/PythonAss1/10.py
666
4.5625
5
#Using assignment operators, perform following operations
Addition, Substation, Multiplication, Division, Modulus, Exponent and Floor division operations num1 = 50 num2 = 20 result = 0 result = num1 + num2 print('Value of result using + operator:',result) result += num1 print('Value of result using += operator:',result) result *= num1 print('Value of result using *= operator:',result) result /= num1 print('Value of result using /= operator:',result) result %= num1 print('Value of result using %= operator:',result) result **= num1 print('Value of result using **= operator:',result) result //= num1 print('Value of result using //= operator:',result)
836ae1ff548b0f70289a4bac2ed886a4cf00c114
erdemru/Recipe-propose
/Recipe.py
1,814
4.03125
4
recipe_book = open('recipes.txt','r') #recipes book, should be in the same directory with the py file print("Hello! Are you starving? I am here for you:)") #welcome, only one time def main_menu(): #main menu, we want to go back to this list to keep the user in the software go_back = True while go_back == True: print("\n 1. I want to enter the ingredients to find a recipe " "\n 2. I want to see all the recipes." "\n 3. I want to look for the main course recipes." "\n 4. I want to look for the dessert course recipes." "\n 5. Quit") try: the_choice = int(input("Choose your purpose (1,2,3,4,5): ")) return(the_choice) break except ValueError: print("please enter a number") continue def desserts(): for line in recipe_book: line = line.strip() if line.find('dessert') == -1:continue #this is to continue the loop (find modulunde eger aranan bulunmazsa deger -1 olarak doner) #print(line) #this prints our options print(line[0:(line.find(':'))]) #this is to remive to colons def main_course(): for line in recipe_book: line = line.strip() if line.find('main') == -1:continue print(line[0:(line.find(':'))]) def dish_name(): for line in recipe_book: line = line.strip() if line.find(':') == -1:continue #all of the dishnames in the recipe book has ':' print(line[0:(line.find(':'))]) option = main_menu() if option == 1: #list the ingredients print('ahah') if option == 2: #list the recipes dish_name() if option == 3: #list main courses main_course() if option == 4: #list desserts desserts() if option == 5: #quit print('Goodbye.') quit()
9e1a1ffb9bf08f7d9b02c4f3071702abf7349435
mistersiddd/Balloon-Shooter
/balloonshooter.py
3,051
3.59375
4
import turtle wn = turtle.Screen() wn.title("Balloon") wn.bgcolor("black") wn.setup(width=800,height=600) wn.tracer(0) score = 0 missed_score = 0 # Balloon baloon=turtle.Turtle() baloon.speed(0) # not the speed of the paddle baloon.shape("circle") baloon.shapesize(stretch_wid=3, stretch_len=3) baloon.color("white") baloon.penup() # using the pen up baloon.goto(-350,0) # gun B gun=turtle.Turtle() gun.speed(0) # not the speed of the paddle gun.shape("turtle") gun.tilt(180) gun.shapesize(stretch_wid=3, stretch_len=3) gun.color("white") gun.penup() # using the pen up gun.goto(350,0) # #eraser # eraser=turtle.Turtle() # eraser.speed(0) # not the speed of the paddle # eraser.shape("square") # eraser.tilt(0) # eraser.shapesize(stretch_wid=10, stretch_len=10) # eraser.color("black") # eraser.penup() # using the pen up # # bullet bullet=turtle.Turtle() bullet.speed(0) # not the speed of the paddle bullet.shape("square") bullet.color("white") bullet.penup() # using the pen up # Pen pen=turtle.Turtle() pen.speed(0) pen.color("red") pen.penup() pen.hideturtle() pen.goto(0,260) def baloon_up(): y=baloon.ycor() y+=20 baloon.sety(y) def baloon_down(): y=baloon.ycor() y-=20 baloon.sety(y) def gun_up(): y=gun.ycor() y+=20 gun.sety(y) def gun_down(): y=gun.ycor() y-=20 gun.sety(y) def shoot(): bullet.goto(gun.xcor(), gun.ycor()) bullet.dx=3 bullet.dy=0 global score global missed_score score_flag = False # loc_score = score while bullet.xcor() > -420: bullet.sety(bullet.ycor() + bullet.dy) bullet.setx(bullet.xcor() - bullet.dx) baloon.sety(baloon.ycor() - 2) #ballon loop if baloon.ycor() <= -294: baloon.sety(baloon.ycor() + 594) if abs(baloon.xcor() - bullet.xcor()) <= 40 and abs(baloon.ycor() - bullet.ycor()) <= 40: # print("balloon xcord = "+str(baloon.xcor())) # print("balloon ycor = "+str(baloon.ycor())) # print("bullet xcoord = "+str(bullet.xcor())) # print("bullet ycoord = "+ str(bullet.ycor())) score_flag = True score += 1 # print("in if in loop score = "+str(score)) wn.update() if not score_flag: missed_score += 1 # eraser.sety(280) # eraser.setx(-10) pen.clear() pen.write("Missed score = "+ str(missed_score), align="center", font=("Arial", 24, "normal")) wn.update() print("missed score = "+str(missed_score)) print("balloon xcord = "+str(baloon.xcor())) print("balloon ycor = "+str(baloon.ycor())) print("bullet xcoord = "+str(bullet.xcor())) print("bullet ycoord = "+str(bullet.ycor())) else: score_flag = False #print("score = " + str(score)) wn.clearscreen() pen.write("Missed score = "+ str(missed_score), align="center", font=("Arial", 24, "normal")) wn.listen() # wn.onkeypress(baloon_up,"w") wn.onkeypress(gun_up,"Up") # wn.onkeypress(baloon_down,"s") wn.onkeypress(gun_down,"Down") wn.onkeypress(shoot, "space") # Main Loop while True: # Update the screen wn.update() # Move the bullet baloon.sety(baloon.ycor() - 2) if baloon.ycor() <= -294: baloon.sety(baloon.ycor() + 594)
11cd3cb7dc2676ac12ee613b0e77fbd5b8db8ae8
Vladk550/SomeCode
/Filter.py
517
3.59375
4
class Filter: def __init__(self, iterable, filter_function): self.iterable = iterable self.filter_function = filter_function self.iter = None def __iter__(self): #self.iter = iter(self.iterable) for elem in self.iterable: if self.filter_function(elem): yield elem #return self if __name__ == "__main__": lst = [1, 2, 3, 1, 10] fn = lambda x: x > 2 new = [x for x in Filter(lst, fn)] print new
9810ad535809e83846c48907194aab0dc8c130c7
sheepinriver/pyML
/pyML/visualization.py
2,125
3.578125
4
import numpy as np import matplotlib.pyplot as plt from .kNN import KNNClassifier def draw_2D_kNN(X, y, X_predict, k=5): """画一个二维的散点图和折线图,用以演示kNN算法""" assert X.shape[1] == X_predict[1] == 2, \ 'X and x_predict must have two features ' assert X.shape[0] == y.shape[0], \ 'The size of X must be equal to the size of y' assert k >= 1, 'k must be valid' # 实例一个画布 - 当只有一个图的时候,不是必须的 plt.figure(figsize=(16, 12)) y_categories = np.unique(y) for y_category in y_categories: plt.scatter(X[y == y_category, 0], X[y == y_category, 1], c=y_category, label='Category {:s}'.format(str(y_category)) ) kNN_classifier = KNNClassifier(k) kNN_classifier.fit(X, y) neighbour_indices = kNN_classifier.neighbour_indices(X_predict) for i in len(X_predict): for j in range(k): # 每次循环构造两个点 plot_x = [X_predict[i, 0], X[neighbour_indices[i], 0]] plot_y = [X_predict[i, 1], X[neighbour_indices[i], 1]] # 画两点之间点连线 plt.plot(plot_x, plot_y, color='r') plt.tick_params(direction="out" , length=6 , width=2 , colors="w" # , grid_color='r' # , grid_alpha=0.5 ) plt.legend() plt.title('kNN Classifier', color='w') plt.show() def plot_decision_boundary(model, axis): x0, x1 = np.meshgrid( np.linspace(axis[0], axis[1], int((axis[1] - axis[0]) * 100)).reshape(-1, 1), np.linspace(axis[2], axis[3], int((axis[3] - axis[2]) * 100)).reshape(-1, 1), ) X_new = np.c_[x0.ravel(), x1.ravel()] y_predict = model.predict(X_new) zz = y_predict.reshape(x0.shape) from matplotlib.colors import ListedColormap custom_cmap = ListedColormap(['#EF9A9A', '#FFF59D', '#90CAF9']) plt.contourf(x0, x1, zz, linewidth=5, cmap=custom_cmap)
516e263fe9c5bd394306d9785752f5f552c79159
Igjanka/pte_et_c2_2021
/ora4/max.py
280
3.828125
4
import random random.randint(3, 5) random.random() my_list = [] for i in range(20): my_list.append(random.randint(1, 101)) print(my_list) max = my_list[0] for i in range(len(my_list)): if max < my_list[i]: max = my_list[i] print(max) my_list.sort(reverse=True)
81dd88c3a9b6e1ca8061fe0a5a9cee4d716daaa7
Bikashacharaya/Jspider_Python
/Right_Angle_Triangle/pat_5.py
219
3.9375
4
''' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ''' n = int(input("Enter any value: ")) x = 1 for row in range(1, n+1): for col in range(1, row+1): print(x, end=" ") x = x+1 print()
7d2ef4dd2b3565fbd812df99149ddbef2a9f3c49
HardeepGill2395/python-learning
/First Program.py
162
3.96875
4
print ("Hello everyone") s = input(" Enter your name \n") age = int(input(" Enter your age \n")) print("Hi " +s*5 + " your age is " +str(age*10)) print("Hello")
2136bcf42459f0964ff3f28681949d694acbfd45
mmikhalina/colloquium
/26.py
582
3.78125
4
""" Напишіть програму аналізу значень температури хворого за добу: визначте мінімальне і максимальне значення, середнє арифметичне. Заміри температури виробляються шість раз на добу і результати вводяться з клавіатури у масив T. Mikhalina Myroslav 122D """ T = [] for i in range(1, 6): T.append(float(input("Enter "))) print("min =", min(T), "max =", max(T), "average =", sum(T)/len(T))
91747062361d9b1b171f6ef1c441c23d467a7cba
weiguangjiayou/LeetCode
/LeetCode/LeetCode61rotate-list.py
858
3.921875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/31 10:08 AM # @Author : Slade # @File : LeetCode61rotate-list.py # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head: return head check = tmp = head length = 1 while check.next: length += 1 check = check.next check.next = head move = k % length move_step = length - move - 1 while move_step > 0 and tmp: tmp = tmp.next move_step -= 1 res = tmp.next tmp.next = None return res
5ae7a4e7119c4e109db0f325a0c97ae65388ea10
rez433/python
/kmom06/file/string.py
1,610
3.96875
4
#!/usr/bin/env python3 # pylint: disable=missing-function-docstring, missing-module-docstring filename = "items.txt" def menu(): print( """ 1. Show file content 2. Add item, append 3. Replace content 4. Remove an item """ ) return int(input("Choice: ")) def choice(inp): if inp == 1: print(readfile()) elif inp == 2: write_to_file("\n" + input("Item to add: "), "a") elif inp == 3: replace_content() elif inp == 4: remove_item() else: exit() def readfile(): # with - as for reading a file automatically closes it after reading is done with open(filename) as filehandle: content = filehandle.read() return content def write_to_file(content, mode): # open file with "w" to clear file from content and write new string to it with open(filename, mode) as filehandle: filehandle.write(content) def replace_content(): item = "" result = "" while item != "q": result += item + "\n" item = input("Item to add: ") write_to_file(result, "w") def remove_item(): content = readfile() remove = input("What item should be removed: ") if remove in content: # check if item to remove exists if content.index(remove) == 0: # if the item is the first line in the file modified_content = content.replace(remove, "") else: modified_content = content.replace("\n" + remove, "") write_to_file(modified_content.strip(), "w") if __name__ == "__main__": while(True): choice(menu())
10725c03b0cc0a00aff11a7558990468d229ea5c
garthus23/holbertonschool-higher_level_programming
/0x03-python-data_structures/5-no_c.py
233
3.65625
4
#!/usr/bin/python3 def no_c(my_string): result_str = "" for i in range(0, len(my_string)): if my_string[i] != 'c' and my_string[i] != 'C': result_str = result_str + my_string[i] return (result_str)
513e2c95e67791ea5f27e3352efbd87b1afc6fd4
Fulvio7/curso-python-guppe
/guppe/exercicios_secao_8/ex_13.py
1,001
4.375
4
""" 13- Faça uma função que receba dois valores numéricos e um símbolo. Este símbolo representará a operação que se deseja efetuar com os números, conforme a tabela abaixo: + -> adição - -> subtração * -> multiplicação / -> divisão """ def calculadora(n1, n2, operacao): if operacao == '+': return n1 + n2 elif operacao == '-': return n1 - n2 elif operacao == '*': return n1 * n2 elif operacao == '/': if n2 == 0: return f'Erro: divisão por zero.' else: return n1 / n2 operacoes_validas = ('+', '-', '*', '/') print('Calculadora com Função') num1 = int(input('Digite o 1º número: ')) num2 = int(input('Digite o 2º número: ')) print('Operações válidas: ') print('[+] -> adição') print('[-] -> subtração') print('[*] -> multiplicação') print('[/] -> divisão') op = '' while op not in operacoes_validas: op = input('Digite a sua opção: ') print(calculadora(num1, num2, op))
be40d10b229e6b257d86f6fff04850e245e9cc2c
dana-gz/pythonProject
/05_methods/new_hunt_the_thimble.py
382
3.765625
4
secret_number = 5 previous_guess = -100 while True: user_number = int(input("Give me your guess: ")) if user_number == secret_number: break if abs(user_number - secret_number) < abs(previous_guess): print('warm!') previous_guess = abs(secret_number -user_number) else: print('cold!') print("Congratulations - you guessed right!")
bfbe2276306b9590c636a2ae28f70277ae2b1866
n-chaitanya/Prolem-Solving-Q
/stringWordReverse.py
952
3.640625
4
# #string reverse class TestCases: def __init__(self,input,output): self.input = input self.output = output c1 = TestCases('My name is Chaitanya Nagulapalli','yM eman si aynatiahC illapalugaN') c2 = TestCases('uppercase','esacreppu') c3 = TestCases(' ',' ') testList = [c1,c2,c3] def stringWordReverse(string): x = [] l = [] s = '' a = '' for i in string: x.append(i) for j in x: if(j== ' '): l.append(s) s = '' else: s = s+j l.append(s) for i in l: c = i.split() for j in c: for k in j[::-1] : a += k # print(k) # print(k,end='') # print(' ',end='') a += ' ' return a #stringWordReverse('My name is Chaitanya Nagulaplli') for i in testList: value = stringWordReverse(str(i.input)) if(value==str(i.output)): print('Passed') else: print('failed')
3e4bad68e6f27404712c8c81d23285bd8f07844a
Akrog/project-euler
/016.py
330
3.921875
4
#!/usr/bin/env python """Power digit sum Problem 16 Published on 03 May 2002 at 06:00 pm [Server Time] 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ result = sum(map(int, str(1 << 1000))) print "The sum of the digits of the number 2^1000 is", result
9f2d728e62edaa986ac8b5eb9877c8ddcad6976a
watchtree/Algorithms_python
/testOffer/printMatrix.py
4,825
4.09375
4
#!/usr/bin/env python #-*- coding:utf-8 -*- # author:wttree # datetime:2018/10/13 19:20 # software: PyCharm # question:输入一个矩阵(不一定是标准的n*n),按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. class Solution: #v1.0分为两个部分函数完成,一是PrintMatrixInCircle打印矩阵某一圈的数字, def printMatrix(self, matrix): newmat = [] if matrix == None: return None rows = len(matrix) #矩阵行数 columns = len(matrix[0]) #矩阵列数 start = 0 while rows > start * 2 and columns > start * 2: mat = self.PrintMatrixInCircle(matrix, columns, rows, start) newmat.extend(mat) start += 1 return newmat def PrintMatrixInCircle(self, matrix, columns, rows, start): endX = columns - 1 - start endY = rows - 1 -start mat = [] for i in range(start, endX + 1): number = matrix[start][i] mat.append(number) #包含end=''作为print()BIF的一个参数,会使该函数关闭“在输出中自动包含换行”的默认行为。其原理是:为end传递一个空字符串,这样print函数不会在字符串末尾添加一个换行符,而是添加一个空字符串。这个只有Python3有用,Python2不支持 if start < endY: #在矩阵大小为奇数项时, 最后一次只输出其中心值 for i in range(start + 1, endY + 1): number = matrix[i][endX] mat.append(number) if start < endX and start < endY: for i in range(endX-1, start-1, -1): number = matrix[endY][i] mat.append(number) if start < endX and start < endY-1: for i in range(endY-1, start, -1): number = matrix[i][start] mat.append(number) return mat #v2.0组合单个函数版本 def printMatrix2(self, matrix): newmat = [] if matrix == None: return None rows = len(matrix) columns = len(matrix[0]) start = 0 while rows > start*2 and columns > start*2: endX = columns - 1 - start endY = rows - 1 - start mat = [] for i in range(start, endX + 1): number = matrix[start][i] mat.append(number) if start < endY: for i in range(start + 1, endY + 1): number = matrix[i][endX] mat.append(number)\ if start < endX and start < endY: for i in range(endX - 1, start - 1, -1): number = matrix[endY][i] mat.append(number) if start < endX and start < endY - 1: for i in range(endY - 1, start, -1): number = matrix[i][start] mat.append(number) newmat.extend(mat) start += 1 return newmat #模仿魔方逆时针旋转,输出并删除一行后,进行一次逆时针旋转,重复多次 def printMatrix3(self, matrix): result = [] while(matrix): result += matrix.pop(0) if not matrix or not matrix[0]: break matrix = self.turn(matrix) return result def turn(self, matrix): num_r = len(matrix) num_c = len(matrix[0]) newmat = [] for i in range(num_c): newmat2 = [] for j in range(num_r): newmat2.append(matrix[j][i]) newmat.append(newmat2) newmat.reverse() return newmat #单个函数实现魔方翻转打印 def printMatrix4(self, matrix): result = [] while(matrix): result += matrix.pop(0) if not matrix or not matrix[0]: break num_r = len(matrix) num_c = len(matrix[0]) newmat = [] for i in range(num_c): newmat2 = [] for j in range(num_r): newmat2.append(matrix[j][i]) newmat.append(newmat2) newmat.reverse()#反向列表中的元素 matrix = newmat return result matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] matrix2 = [[1],[2],[3],[4],[5]] matrix3 = [[1,2],[3,4],[5,6],[7,8],[9,10]] S = Solution() out = S.printMatrix4(matrix) print(out) print('\n') out = S.printMatrix4(matrix2) print(out) print('\n') out = S.printMatrix4(matrix3) print(out)
8b88edb5a75a2c8ae021163bdbe11089b88b6f6b
tmoriartywcc/week10
/makename.py
192
4.03125
4
first_name = input('enter first name: ') middle_name = input('enter middle name: ') last_name = input('enter last name: ') name = first_name + ' ' + middle_name + ' ' + last_name print(name)
b18609cde09810784b1c2ce40381ee7ab7ee6d43
samaro19/Random_Code
/decode_ceaser.py
717
3.859375
4
dict = { -2: '!', -1: '?', 0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', } message = input("input text to decode: ") three_back = [] decoded = [] if message != '': message = message.split(", ") print(message) for msg1 in message: three_back.append(int(msg1) - 3) print(three_back) for msg in three_back: print(dict[int(msg)]) decoded.append(dict[int(msg)]) print(" ") print(''.join(decoded))
ae90340100414a975d8a06b22d1affd2a213ecba
SiervoDeAnubis/el_python
/functions.py
831
3.8125
4
# A function is a block of code which only runs when it is called. In Python, we do not use parentheses and curly brackets, we use indentation with tabs or spaces def sayHello(name='Cecilia'): """ Prints Hello and the name """ print('Hello ' + name) # Return Value def getSume(num1, num2): total = num1 + num2 return total print(getSume(1, 2)) def addOneToNum(num): num = num + 1 # num += 1 return num print(addOneToNum(3)) # A lambda function is a small anonymous function. # A lambda function can take any number of arguments, but can only have one expression. Very similar to JS arrow functions def getSum(num1, num2): return num2 + num1 # getsum = lambda num1, num2 : num1 + num2 def addOneToNumLambda(num): return num + 1 print(getSum(9, 1)) print(addOneToNumLambda(3))
04d566f13e2bc89d2adcc98cc7ecfed641e3ab88
SpooderManEXE/Hacktoberfest2020-Expert
/Python Programs/Huffman_Coding.py
1,326
3.8125
4
string = 'BCAADDDCCACACAC' # Creating tree nodes class NodeTree(object): def __init__(self, left=None, right=None): self.left = left self.right = right def children(self): return (self.left, self.right) def nodes(self): return (self.left, self.right) def __str__(self): return '%s_%s' % (self.left, self.right) # Main function implementing huffman coding def huffman_code_tree(node, left=True, binString=''): if type(node) is str: return {node: binString} (l, r) = node.children() d = dict() d.update(huffman_code_tree(l, True, binString + '0')) d.update(huffman_code_tree(r, False, binString + '1')) return d # Calculating frequency freq = {} for c in string: if c in freq: freq[c] += 1 else: freq[c] = 1 freq = sorted(freq.items(), key=lambda x: x[1], reverse=True) nodes = freq while len(nodes) > 1: (key1, c1) = nodes[-1] (key2, c2) = nodes[-2] nodes = nodes[:-2] node = NodeTree(key1, key2) nodes.append((node, c1 + c2)) nodes = sorted(nodes, key=lambda x: x[1], reverse=True) huffmanCode = huffman_code_tree(nodes[0][0]) print(' Char | Huffman code ') print('----------------------') for (char, frequency) in freq: print(' %-4r |%12s' % (char, huffmanCode[char]))
8c7c0437f9dd4c99f1a4800b7eca62dfeaf96c20
Ingrubenl/appTest7
/basic_calc2.py
373
3.859375
4
#Basic calc to junior insers #Developer : Ruben Dario lasso #Libraries############################## import os ######################################### #Funtion############################## def calc(x,y): suma = x + y print("la suma es: ",suma) #Main############################## print("press number 1: ") a = int(input()) b = int(input("press number 2: ")) calc(a,b)
9ff1f8b51435f8eed93b7e32d3886897a16ebcf2
qiuyucc/pythonRoad
/BasicReview/01String.py
5,377
4.0625
4
# 字符串中的字符可以是特殊符号、英文字母、中文字符、日文的平假名或片假名、希腊字母、Emoji字符 # s1 = 'hello, world!' # s2 = 'hello, world!' # # print(s1, s2) # # s3 =''' # hello, # world # ''' # # print(s3, end=' ') # r 原始字符串, 使用了R或者r, 转义字符串就会变成原始字符串 s1 = '\time up \now' print(s1) #字符串s2中没有转义字符,每个字符都是原始含义 s2 = r'\time up \now' print(s2) # 字符串中 \ 后面可以接一个8进制,或者16进制来表示字符,例如\141, \x61都表示小写字母a s1 = '\141\142\143' s2 = '\u9648\u660a' print(s1, s2) # Python为字符串类型提供了非常丰富的运算符,我们可以使用+运算符来实现字符串的拼接,可以使用*运算符来重复一个字符串的内容, # 可以使用in和not in来判断一个字符串是否包含另外一个字符串, # 我们也可以用[]和[:]运算符从字符串取出某个字符或某些字符。 s1 = 'hello' + ' ' + 'world' print(s1) # hello world s2 = '!' * 3 print(s2) s1 += s2 print(s1) s1 *= 2 print(s1) # 用*实现字符串的重复是非常有意思的一个运算符,在很多编程语言中,要表示一个有10个a的字符串, # 你只能写成"aaaaaaaaaa",但是在Python中,你可以写成'a' * 10。你可能觉得"aaaaaaaaaa"这种写法也没有什么不方便的, # 那么想一想,如果字符a要重复100次或者1000次又会如何呢? s1 = 'a whole new world' s2 = 'hello world' print(s1 == s2, s1 < s2) # False True print(s2 == 'hello world') # True print(s2 == 'Hello world') # False print(s2 != 'Hello world') # True s3 = '骆昊' print(ord('骆'), ord('昊')) # 39558 26122 s4 = '王大锤' print(ord('王'), ord('大'), ord('锤')) # 29579 22823 38180 print(s3 > s4, s3 <= s4) # True False #is 用来比较内存地址 s1 = 'hello world' s2 = 'hello world' s3 = s2 print(s1 == s2, s2 == s3) print(s1 is s2, s2 is s3) #成员变量 #python 中可以用in 和 not in 判断一个字符串中是否存在另一个字符或者字符串 s1 = 'hello, world' print('wo' in s1) # True s2 = 'goodbye' print(s2 in s1) # False #index of string s = 'abc123456' N = len(s) # 获取第一个字符 print(s[0], s[-N]) # a a # 获取最后一个字符 print(s[N-1], s[-1]) # 6 6 # 获取索引为2或-7的字符 print(s[2], s[-7]) # c c # 获取索引为5和-4的字符 print(s[5], s[-4]) # 3 3 #-------------------------------切片 #如果要从字符串中取出多个字符,我们可以对字符串进行切片,运算符是[i:j:k],其中i是开始索引,索引对应的字符可以取到;j是结束索引, # 索引对应的字符不能取到;k是步长,默认值为1,表示从前向后获取相邻字符的连续切片,所以:k部分可以省略。 # 假设字符串的长度为N,当k > 0时表示正向切片(从前向后获取字符),如果没有给出i和j的值,则i的默认值是0,j的默认值是N; # 当k < 0时表示负向切片(从后向前获取字符),如果没有给出i和j的值,则i的默认值是-1,j的默认值是-N - 1。 # 如果不理解,直接看下面的例子,记住第一个字符的索引是0或-N,最后一个字符的索引是N-1或-1就行了。 s = 'abc123456' # i=2, j=5, k=1的正向切片操作 print(s[2:5]) # c12 # i=-7, j=-4, k=1的正向切片操作 print(s[-7:-4]) # c12 # i=2, j=9, k=1的正向切片操作 print(s[2:]) # c123456 # i=-7, j=9, k=1的正向切片操作 print(s[-7:]) # c123456 # i=2, j=9, k=2的正向切片操作 print(s[2::2]) # c246 # i=-7, j=9, k=2的正向切片操作 print(s[-7::2]) # c246 # i=0, j=9, k=2的正向切片操作 print(s[::2]) # ac246 # i=1, j=-1, k=2的正向切片操作 print(s[1:-1:2]) # b135 # i=7, j=1, k=-1的负向切片操作 print(s[7:1:-1]) # 54321c # i=-2, j=-8, k=-1的负向切片操作 print(s[-2:-8:-1]) # 54321c # i=7, j=-10, k=-1的负向切片操作 print(s[7::-1]) # 54321cba # i=-1, j=1, k=-1的负向切片操作 print(s[:1:-1]) # 654321c # i=0, j=9, k=1的正向切片 print(s[:]) # abc123456 # i=0, j=9, k=2的正向切片 print(s[::2]) # ac246 # i=-1, j=-10, k=-1的负向切片 print(s[::-1]) # 654321cba # i=-1, j=-10, k=-2的负向切片 print(s[::-2]) # 642ca # 变量值 占位符 格式化结果 说明 # 3.1415926 {:.2f} '3.14' 保留小数点后两位 # 3.1415926 {:+.2f} '+3.14' 带符号保留小数点后两位 # -1 {:+.2f} '-1.00' 带符号保留小数点后两位 # 3.1415926 {:.0f} '3' 不带小数 # 123 {:0>10d} 0000000123 左边补0,补够10位 # 123 {:x<10d} 123xxxxxxx 右边补x ,补够10位 # 123 {:>10d} ' 123' 左边补空格,补够10位 # 123 {:<10d} '123 ' 右边补空格,补够10位 # 123456789 {:,} '123,456,789' 逗号分隔格式 # 0.123 {:.2%} '12.30%' 百分比格式 # 123456789 {:.2e} '1.23e+08' 科学计数法格式 s = 'hello, world' # center方法以宽度20将字符串居中并在两侧填充* print(s.center(20, '*')) # ****hello, world**** # rjust方法以宽度20将字符串右对齐并在左侧填充空格 print(s.rjust(20)) # hello, world # ljust方法以宽度20将字符串左对齐并在右侧填充~ print(s.ljust(20, '~')) # hello, world~~~~~~~~
ce4c1157007406cf548c019bd2bd09ddbe026478
sdierauf/uw-cse
/143/PyHelloWorld/moar.py
702
3.640625
4
''' Created on Feb 28, 2013 @author: Stefan ''' colors = ['red', 'blue', 'green'] print(colors) sum = 0 for i in range(100): sum += i print(sum) sum = 0 numbers = [1, 3, 5, 6, 7, 5, 6, 7, 9, 0, 1, 2, 6, 7, 4] for i in numbers: print(i) sum += i print('sum is: ' + str(sum)) print(sum) i = 0 while i < len(numbers): print(str(i) + 'th place: ' + str(numbers[i])) i += i+1 friends = ['john', 'ian', 'justin', 'joe', 'whore', 'simon'] #make new list of reversed i = len(friends) friendsreversed = [] while i > 0: friendsreversed.append(friends[i - 1]) i -= 1 print(friendsreversed) #make friends reversed with no new objects
8a3c376715d74a068077eeb55da2591f2e73f733
Grawlin/Bootrain-Data-Science
/BootrainAssignment4.py
2,218
3.859375
4
title = 'Exercise N°{}' print(title.format(1), '\n') my_list = [34, 56, 76, 45, 2, 12, 67, 98, 37, 54, 66] min_list = my_list.copy() min_1 = min(my_list) #Save de lowest number min_list.pop(min_list.index(min(min_list))) #Removes the lowest number from the copy of the original list min_2 = min(min_list) #Save the lowest number from the new list sum_min = min_1 + min_2 max_list = my_list.copy() max_1 = max(my_list) #Save de highest number max_list.pop(max_list.index(max(max_list))) #Removes the highest number from the copy of the original list max_2 = max(max_list) #Save the highest number from the new list sum_max = max_1 + max_2 print(my_list,'\n') print('Sum two lowest numbers from list:', sum_min, '\n') print('Sum two highest numbers from list:', sum_max, '\n') print(title.format(2), '\n') names = ["David", "Michael", "John", "James", "Greg", "Mark", "William", "Richard", "Thomas", "Steven", "Mary", "Susan", "Maria", "Karen", "Lisa", "Linda", "Donna", "Patricia", "Debra"] scores = [99, 87, 78, 86, 68, 94, 76, 97, 56, 98, 76, 87, 79, 90, 73, 93, 82, 69, 97, 98] name = input('Enter your name: ') print('') print(name) print('Your score is:', scores[names.index(name)], '\n') print(title.format(3), '\n') print('The maximum score is:', max(scores)) print('The amount of people that obtained that score is:', scores.count(max(scores)), '\n') print(title.format(4), '\n') months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] n_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] months_days = [months, n_days] print(title.format(5), '\n') #month_winter = [months_days[0][11], *months_days[0][0:2]] #days_winter = [months_days[1][11], *months_days[1][0:2]] summer = [months_days[0][5:8] , months_days[1][5:8]] fall = [months_days[0][8:11], months_days[1][8:11]] winter = [[months_days[0][11], *months_days[0][0:2]], [months_days[1][11], *months_days[1][0:2]]] spring = [months_days[0][2:5], months_days[1][2:5]] print(title.format(6), '\n') print('Summer lasts', summer[1][0] + summer[1][1] + summer[1][2], 'days')
99e93ead13224349ce471d58667be97ac726e6fa
awestover/python-ev3
/arm/arm/tablev/Vector.py
1,210
3.953125
4
""" vector class for representing 2d arrays """ import math class V(): """ either pass a 2D array or x,y """ def __init__(self, *args): self.x = 0 self.y = 0 if len(args) == 1: self.x = args[0][0] self.y = args[0][1] if len(args) == 2: self.x = args[0] self.y = args[1] # to string method def __repr__(self): return "[\t" + str(self.x) + ",\t" + str(self.y) + "\t]" """ this returns what this vector plus another vector (does not modify self's vector) """ def __add__(self, other): return V(self.x+other.x, self.y+other.y) """ this returns what this vector minus another vector (does not modify self's vector) """ def __sub__(self, other): return V(self.x-other.x, self.y-other.y) """ returns the result of scalar multiplication with this vector """ def __mul__(self, scalar): return V(self.x*scalar, self.y*scalar) """ size of this vector """ def mag(self): return math.sqrt(self.x**2 + self.y**2) """ gets a perpendicular to the segment """ def getPerp(self): vv = V(-self.y, self.x) vv.toUnit() return vv """ scales by 1/magnitude(self) no return value """ def toUnit(self): m = self.mag() self.x=self.x/m self.y=self.y/m
821577bf9245a4bb64c541b7846edd3cda3eae25
thomasbreydo/little-scripts
/alphabet_info.py
378
3.625
4
#!/usr/bin/env python3 from string import ascii_lowercase as al from termcolor import cprint a = 0 print() for i, c in enumerate(al): if a > 25: print(' '*8, end='') else: cprint(al[a:a+5].ljust(5).upper(), 'white', 'on_blue', end=' | ') a += 5 cprint(c.upper(),'white', end=':') cprint(f"{i: 2}" if i <= 13 else i - 26,'white') print()
bd2a607a605da5d2cfb1c15665eb981363dd7065
erjan/coding_exercises
/the_most_similar_path_in_graph.py
5,570
3.796875
4
''' We have n cities and m bi-directional roads where roads[i] = [ai, bi] connects city ai with city bi. Each city has a name consisting of exactly three upper-case English letters given in the string array names. Starting at any city x, you can reach any city y where y != x (i.e., the cities and the roads are forming an undirected connected graph). You will be given a string array targetPath. You should find a path in the graph of the same length and with the minimum edit distance to targetPath. You need to return the order of the nodes in the path with the minimum edit distance. The path should be of the same length of targetPath and should be valid (i.e., there should be a direct road between ans[i] and ans[i + 1]). If there are multiple answers return any one of them. ''' from collections import defaultdict from functools import cache class Solution: def mostSimilar(self, n: int, roads: List[List[int]], names: List[str], targetPath: List[str]) -> List[int]: name_to_idx = defaultdict(set) for i, name in enumerate(names): name_to_idx[name].add(i) conn = defaultdict(list) for a, b in roads: conn[a].append(b) conn[b].append(a) @cache def dp(i, length): edit = 0 if i in name_to_idx.get(targetPath[-length], [-1]) else 1 if length == 1: return (edit, [i]) cost, path = min([dp(j, length-1) for j in conn[i]], key=lambda x:x[0]) return (edit + cost, [i] + path) cost, path = min([dp(i, len(targetPath)) for i in range(n)], key=lambda x:x[0]) return path --------------------- class Solution: def mostSimilar(self, n: int, roads: List[List[int]], names: List[str], targetPath: List[str]) -> List[int]: # algorithm: dynamic programming # step1: build graph through adjacent matrix # step2: run dp to get the minimum cost # step3: rebuild graph # if we would like to know the min cost for city v at targetPath i # we need to know the min cost for cities u connecting to city v at targetPath i-1 # cost(v, targetPath i) = min(cost(cities_connect_u, targetPath i-1))+possible_edit_cost(v) # time complexity: O(m*n^2) # space complexity: O(n(n+m)) m = len(targetPath) # build graph graph = [[] for i in range(n)] for r in roads: graph[r[0]].append(r[1]) graph[r[1]].append(r[0]) # idx negative one for dummy graph.append([i for i in range(n)]) # idx zero for dummy dp = [[10**9]*n for i in range(m+1)] dp[0] = [0]*n paths = [[-1]*n for i in range(m)] # each target i in the target path for i in range(1, m+1): # each city # calculate the cost for each at target i for v in graph[-1]: # use dp to calculate it for u in graph[v]: if dp[i][v]>dp[i-1][u]: dp[i][v] = dp[i-1][u] paths[i-1][v] = u dp[i][v] += names[v]!=targetPath[i-1] # get the final city from dp table res = [-1] endCost = 10**9 for i in range(n): if endCost>dp[m][i]: endCost = dp[m][i] res[0] = i # rebuild the path from final city to first city for i in range(m-1, 0, -1): res.append(paths[i][res[-1]]) return res[::-1] ----------------------------------------------------------------- class Solution: def mostSimilar(self, n: int, roads: List[List[int]], names: List[str], targetPath: List[str]) -> List[int]: path_length = len(targetPath) ajl = collections.defaultdict(set) for src, dest in roads: ajl[src].add(dest) ajl[dest].add(src) @functools.lru_cache(None) def min_distance_with_given_end_city(target_idx, end_city_idx): '''returns the min distance and the id of the source city for the path ending in end_city_idx''' city_cost = 1 - (targetPath[target_idx] == names[end_city_idx]) if target_idx == 0: return city_cost, None # there is no source city for the first city in the path mindist = path_length srccity = None for source_city_idx in ajl[end_city_idx]: distfrom, fromcity = min_distance_with_given_end_city(target_idx - 1, source_city_idx) if distfrom < mindist: mindist = distfrom srccity = source_city_idx return mindist + city_cost, srccity # now let's start from the last city in the path and find the route back which has minimum cost target_position = path_length - 1 last_city_choices = [(min_distance_with_given_end_city(target_position, end_city_idx), end_city_idx) \ for end_city_idx in range(n)] (mindist, src_city_idx), end_city_idx = min(last_city_choices) route = collections.deque([end_city_idx]) while src_city_idx is not None: route.appendleft(src_city_idx) target_position -= 1 mindist, src_city_idx = min_distance_with_given_end_city(target_position, src_city_idx) return route
58f50ad0109156fb7f61062042bb4ccaf823fe6a
rafaelperazzo/programacao-web
/moodledata/vpl_data/126/usersdata/233/29902/submittedfiles/ap2.py
423
4.03125
4
# -*- coding: utf-8 -*- a=float(input('Digite um número:')) b=float(input('Digite um número:')) c=float(input('Digite um número:')) d=float(input('Digite um número:')) if a>=b and a>=c and a>=d: if b<=c and b<=d: print('%d'%a) print('%d'%b) if c<=b and c<=d: print('%d'%a) print('%d'%c) if d<=b and d<=c: print('%d'%a) print('%d'%d)
9e1bd00a437ee331cd97e6f3b030d9c53d7f0c7e
hivauz/grokking_git_commands
/e.py
1,343
3.859375
4
import time n = 6 result_matrix = [[0 for x in range(n)] for y in range(n)] def print_matrix( r): for i in range(n): for j in range(n): print(r[i][j], end = '\t') print() counter = 1 k = n # row left to right print("the middle is" + str((n//2+1))) for i in range(n//2+1): time.sleep(2) print("********************************************") print("i: " + str(i) + " k: " + str(k)) for di in range(i,k): print("[" + str(i) + "]" + "[" + str(di) + "]", end=' ') result_matrix[i][di] = counter counter+=1 print() #print_matrix(result_matrix) for di in range(i+1,k): print("[" + str(di) + "]" + "[" + str(k-1) + "]", end=' ') result_matrix[di][k-1] = counter counter+=1 print() #print_matrix(result_matrix) for di in range(-(i+2), -(k+1),-1): print("[" + str(k-1) + "]" + "[" + str(di) + "]", end=' ') result_matrix[k-1][di] = counter counter+=1 print() #print_matrix(result_matrix) for di in range(-(i+2),-k,-1): print("[" + str(di) + "]" + "[" + str(i) + "]", end=' ') result_matrix[di][i] = counter counter+=1 print() #print() #print_matrix(result_matrix) k = k-1 print("\n\n\n--------------------") #print_matrix(result_matrix) print(result_matrix[5][-2])
7b4c3951ba452363a57faa3d67d579ee6c88146b
melisarv/holbertonschool-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
349
3.96875
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): while len(tuple_a) < 2: tuple_a += (0,) while len(tuple_b) < 2: tuple_b += (0,) first_tuple = tuple_a, tuple_b sum1 = sum([par[0] for par in first_tuple]) sum2 = sum([par[1] for par in first_tuple]) last_tuple = sum1, sum2 return (last_tuple)
ae21c061854b509f7e92bce6821b2eb09951df5d
LucasWarner/ISC4U_CULM
/Main/MonthlySchedule.py
4,557
3.828125
4
# ------------------------------------------------------------------------------- # Name: MonthlySchedule.py # Purpose: File to create and display the monthly schedule # Author: Warner.Lucas, McKeen.Kaden # # Created: 13/04/2018 # ------------------------------------------------------------------------------ import datetime #Setup the global variables #Used for box creation s = 78 rows = 5 collumns = 7 #Information about weeks and months month_days = [31,29,31,30,31,30,31,31,30,31,30,31] first_day_of_month = [1,4,4,0,2,5,0,3,6,1,4,6] days_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] #Lists to hold events [date, name] events = [] repeating_events = [] #Calculate on which day the month starts time = datetime.datetime.now() this_month = time.month D = 1 M = time.month Y = time.year if M < 3: M = M + 12 Y = Y - 1 d = (floor(2.6 * M - 5.39) + floor((Y - (100 * (floor(Y / 100)))) / 4) + floor((floor(Y / 100)) / 4) + D + (Y - (100 * (floor(Y / 100)))) - (2 * (floor(Y / 100)))) - (7 * floor((floor(2.6 * M - 5.39) + floor((Y - (100 * (floor(Y / 100)))) / 4) + floor((floor(Y / 100)) / 4) + D + (Y - (100 * (floor(Y / 100)))) - (2 * (floor(Y / 100)))) / 7)) #Add event (Called from the main file) def addEvent(is_weekly, name, date): global events, repeating_events if is_weekly: repeating_events.append([int(date)-1, name]) print(repeating_events) else: events.append([int(date), name]) #Draws the monthly schedule def display(): global x_offset, y_offset, d, events, repeating_events x_offset = 202 y_offset = 200 on_number = 1 box_y_range = (month_days[this_month]+d-1)/7 + (1-(((month_days[this_month]+d-1)/7)%1)) event_in_box = [0 for i in range(month_days[this_month])] stroke(0) strokeWeight(2) fill(255) #Draw box rect(x_offset,y_offset,7*s,box_y_range*s) for box_y in range(box_y_range): for box_x in range(7): if box_y == 0: fill(255) textSize(s/6) text(days_of_week[box_x], box_x*s + x_offset + s/15, y_offset - s/10) fill(0) line(box_x*s + x_offset, box_y*s + y_offset, (box_x+1)*s + x_offset, box_y*s + y_offset) line(box_x*s + x_offset, box_y*s + y_offset, box_x*s + x_offset, (box_y+1)*s + y_offset) if 7*box_y + (box_x+1) > d and on_number <= month_days[this_month]: #Draw day number fill(0) textSize(s/6) text(str(on_number), float(box_x*s) + float(s)*1/15 + x_offset, float((box_y+1)*s) - float(s)*8/10 + y_offset) textSize(s/8) #Draw events for event in events: if event[0] <= month_days[this_month]: if on_number == event[0] and event_in_box[on_number-1] < 4: if len(event[1]) < 15: text(event[1][:15], float(box_x*s) + float(s)*1/15 + x_offset, float((box_y+1)*s) - float(s)*6.5/10 + float(s)*2/10*event_in_box[on_number-1] + y_offset) else: text(event[1][:13]+"...", float(box_x*s) + float(s)*1/15 + x_offset, float((box_y+1)*s) - float(s)*6.5/10 + float(s)*2/10*event_in_box[on_number-1] + y_offset) event_in_box[on_number-1] += 1 #Draw repeating events for repeat_e in repeating_events: if ((on_number + d - 1) % 7) == repeat_e[0] and event_in_box[on_number-1] < 4: if len(repeat_e[1]) < 15: text(repeat_e[1][:15], float(box_x*s) + float(s)*1/15 + x_offset, float((box_y+1)*s) - float(s)*6.5/10 + float(s)*2/10*event_in_box[on_number-1] + y_offset) else: text(repeat_e[1][:13]+"...", float(box_x*s) + float(s)*1/15 + x_offset, float((box_y+1)*s) - float(s)*6.5/10 + float(s)*2/10*event_in_box[on_number-1] + y_offset) event_in_box[on_number-1] += 1 #Increase day number on_number += 1 line(7*s + x_offset, 0 + y_offset, 7*s + x_offset, box_y_range*s + y_offset) line(0 + x_offset, box_y_range*s + y_offset, 7*s + x_offset, box_y_range*s + y_offset)
5d44b555ef290ba906dbed7d592f73faba537a35
yeshixuan/Python
/05-Spider/01-爬虫基础/02-requests模块相关/v25-session.py
661
3.671875
4
""" session 模拟一次回话 ss = requests.session() ss.post(url,data=data,headers=headers) rsp = ss.get(url) ssl证书 rsp = requests.get(url,verify=False) """ import requests proxy = { "http":"211.23.149.29:80", # "https":"163.172.215.202:3128" } # 创建session对象,可以保持cookie值 ss = requests.session() url = "https://fanyi.baidu.com/sug" data = { "kw":"girl" } headers = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" } rsp = ss.post(url,data=data, headers=headers, proxies=proxy, verify=False) print(rsp.text) print(rsp.json())
8a871902f3cce1cc9ccdc503a305687ef00360c2
letspython3x/erp_department_store
/forms/validate_forms.py
7,321
3.59375
4
from abc import ABC, abstractmethod class ValidatePayload(ABC): """ Abstract Class for validating the forms """ @abstractmethod def __init__(self, **kw): pass @abstractmethod def validate(self): """Validate the received payload""" class ValidateProduct(ValidatePayload): def __init__(self, products, **kw): super(ValidateProduct, self).__init__(**kw) self.products = products def validate(self): if self.products: if isinstance(self.products, dict): return self.__validate(self.products) @staticmethod def __validate(product): assert isinstance(product.get('product_name'), str) assert isinstance(product.get('serial_no'), str) assert isinstance(product.get('description'), str) assert isinstance(product.get('supplier_id'), str) assert isinstance(product.get('category_id'), str) assert isinstance(product.get('unit_price'), int) or isinstance(product.get('unit_price'), float) assert isinstance(product.get('sell_price'), int) or isinstance(product.get('sell_price'), float) assert isinstance(product.get('units_in_stock'), int) assert isinstance(product.get('is_active'), int) return True class ValidateUser(ValidatePayload): def __init__(self, user=None, **kw): super(ValidateUser, self).__init__(**kw) self.user = user def validate(self): if self.user: if isinstance(self.user, dict): return self.__validate(self.user) @staticmethod def __validate(user): first_name = user.get('first_name') middle_name = user.get('middle_name', "#") last_name = user.get('last_name') email = user.get("email") client_type = user.get("client_type") primary_phone = user.get("primary_phone") secondary_phone = user.get("secondary_phone") fax = user.get("fax") gender = user.get("gender") is_active = user.get("is_active") membership = user.get("membership") postal_code = user.get("postal_code") state = user.get("state") city = user.get("city") country = user.get("country") address = user.get("address") contact_title = user.get("contact_title") assert isinstance(first_name, str) assert isinstance(middle_name, str) assert isinstance(last_name, str) assert isinstance(client_type, str) assert isinstance(contact_title, str) assert isinstance(is_active, bool) assert isinstance(gender, str) assert isinstance(primary_phone, str) assert isinstance(secondary_phone, str) assert isinstance(email, str) assert isinstance(fax, str) assert isinstance(membership, str) assert isinstance(state, str) assert isinstance(city, str) assert isinstance(country, str) assert isinstance(postal_code, str) assert isinstance(address, str) return True class ValidateOrder(ValidatePayload): def __init__(self, order, **kw): super(ValidateOrder, self).__init__(**kw) self.order = order def validate(self): if self.order: if isinstance(self.order, dict): return self.__validate(self.order) @staticmethod def __validate(order): assert isinstance(order.get('client_id'), int) assert isinstance(order.get('store_id'), int) assert isinstance(order.get('order_type'), str) assert isinstance(order.get('payment_type'), str) assert isinstance(order.get('client_type'), str) assert isinstance(order.get('discount_on_total'), (int, float)) # and not isinstance(x, bool) assert isinstance(order.get('total_tax'), (int, float)) assert isinstance(order.get('discounted_sub_total'), (int, float)) assert isinstance(order.get('order_total'), (int, float)) assert isinstance(order.get('item_rows'), list) line_items = order.get('item_rows', []) for product in line_items: assert isinstance(product.get('product_name'), str) assert isinstance(product.get('category_name'), str) assert isinstance(product.get('quantity'), int) assert isinstance(product.get('quoted_price'), (int, float)) assert isinstance(product.get('item_discount'), (int, float)) assert isinstance(product.get('tax'), (int, float)) assert isinstance(product.get('line_item_total'), (int, float)) return True class ValidateStore(ValidatePayload): def __init__(self, store, **kw): super(ValidateStore, self).__init__(**kw) self.store = store def validate(self): if self.store: if isinstance(self.store, dict): return self.__validate(self.store) @staticmethod def __validate(store): # store_id, store_name, address, city, postal_code, country, phone, store_admin, category_id store_name = store.get('store_name') category_id = store.get('category_id') store_admin = store.get('store_admin') address = store.get('address') phone = store.get('phone') city = store.get('city') country = store.get('country') postal_code = store.get('postal_code') assert isinstance(store_name, str) assert isinstance(category_id, str) assert isinstance(store_admin, str) assert isinstance(address, str) assert isinstance(phone, str) assert isinstance(city, str) assert isinstance(country, str) assert isinstance(postal_code, str) return True class ValidateTrader(ValidatePayload): def __init__(self, store, **kw): super(ValidateTrader, self).__init__(**kw) self.name = store.get('name') self.address = store.get('address') self.country = store.get('country') def validate(self): assert isinstance(self.name, str) assert isinstance(self.address, str) assert isinstance(self.country, str) return True class ValidateCategory(ValidatePayload): def __init__(self, category, **kw): super(ValidateCategory, self).__init__(**kw) self.name = category.get('category_name') self.description = category.get('description') def validate(self): assert isinstance(self.name, str) assert isinstance(self.description, str) return True class ValidateAccount(ValidatePayload): def __init__(self, account, **kw): super(ValidateAccount, self).__init__(**kw) self.account = account def validate(self): if self.account: if isinstance(self.account, dict): return self.__validate(self.account) @staticmethod def __validate(account): assert isinstance(account.get('account_type'), str) assert isinstance(account.get('account_id'), int) assert isinstance(account.get('account_name'), str) assert isinstance(account.get('amount_paid'), (int, float)) assert isinstance(account.get('amount_due'), (int, float)) assert isinstance(account.get('account_created_at'), str)
65a081225916f30775835b66fc5629c97c57ce8b
hambali999/Let-s-Study-Python
/FUNCTIONAL/file-handling/lab4/3a.py
2,195
3.765625
4
import random def method1(): diceCount = [0, 0, 0, 0, 0, 0, 0] throws = 100 diceList = [] for i in range(1, throws+1): randomThrow = (random.randrange(1,6+1)) diceList.append(randomThrow) face1 = diceList.count(1) face2 = diceList.count(2) face3 = diceList.count(3) face4 = diceList.count(4) face5 = diceList.count(5) face6 = diceList.count(6) print("Dice\tOccurrence") print(f"1\t{face1}") print(f"2\t{face2}") print(f"3\t{face3}") print(f"4\t{face4}") print(f"5\t{face5}") print(f"6\t{face6}") print(len(diceList)) #just to make sure there are 100 throws def method2(): diceCount = [0, 0, 0, 0, 0, 0, 0] throws = 100 diceList = [] for i in range(1, throws+1): randomThrow = (random.randrange(1,6+1)) diceList.append(randomThrow) for i in diceList: if i == 1: diceCount[1] += 1 elif i == 2: diceCount[2] += 1 elif i == 3: diceCount[3] += 1 elif i == 4: diceCount[4] += 1 elif i == 5: diceCount[5] += 1 elif i == 6: diceCount[6] += 1 else: pass print(diceCount) print("Dice\tOccurrence") for i in range(7): print(f"{i}\t{diceCount[i]}") print(f"Total\t{sum(diceCount)}") # print(len(diceList)) #just to make sure there are 100 throws def method3(): # this function simulates throwing of a dice, 100 times # it keeps tracks of the number of occurences of each face value (1-6). # it displays the number of occurences after 100 throws. diceCount = [0]*7 #type in pdf, not *6 #loop 100times for i in range(100): num = random.randint(1,6) #generate a random value (1-6) diceCount[num]+=1 #update diceCount (increment respective index by 1) #print summary print("Dices \tSummary") print(diceCount) #print dice values and occurrences for i in range(1,7): print(f"{i}\t{diceCount[i]}") print(f"Total\t{sum(diceCount)}") method3() #method3, BEST METHOD, CONCISE & SIMPLE, but takes time to understand
4f9f79af7a81dec36c1a4b31317670cbaa1216a6
MicaelSousa15/PTS
/16.py
205
3.875
4
string = ['Arroz','Macarrão','Carne'] print(string) p_string = string.pop() print(string) print(p_string) # O metodo pop tira da lista, mas pode ser salvo em alguma outra variavel se colocado # string.pop
7700a0bf63d35899e0931026d650450121a76ee6
AzimAstnoor/BasicPython
/ToFindTheMultiplicationTableOfAnyNo.py
227
4.09375
4
a = float(input('Enter the Number you want the multiplication table')) d = float(input('Enter the N. you want to find the multiplaction table till')) c = 1 while c < d: b = a*c print(c, ' * ', a, ' = ', b) c = c + 1
438f1379de0583f53a170aebfef0ba37b8bc57b9
LeanderLXZ/learning-python
/Python Notes/6_07_Sets.py
1,181
4.5
4
# Sets num_set = {1, 3, 4, 5} word_set_1 = {"spam", "eggs", "sausage"} word_set_2 = set(["spam", "eggs", "sausage"]) print(3 in num_set) print(word_set_1) print(word_set_2) print("spam" in word_set_1) # Create an empty set my_set = set() # Create an empty dictionary dict = {} # Sets are unordered, which means they cannot be indexed. # They cannot contain duplicate elements. # Method ''' add - add an element to a set. remove - remove a specific element from a set. pop - remove an arbitrary element from a set. ''' my_set.add("spam") num_set.remove(3) word_set_1.pop() print(my_set) print(num_set) print(word_set_1) print('\n') # Sets can be combined using mathematical operations. ''' | - Union operator combines two sets from a new one containing items in either. & - Intersection operator gets items only in both. - - Difference operator gets items in the first set but not in the second. ^ - Symmetric difference operator gets items in either set, but not both. ''' first = {1, 2, 3, 4, 5, 6} second = {4, 5, 6, 7, 8, 9} print(first | second) print(first & second) print(first - second) print(second - first) print(first ^ second)
2e63fd6f8cd68f225b291b12b34d95e5105c18b8
thiejen/python_excercises
/pilot/28.max_of_three.py
282
4.125
4
#! /usr/local/bin/python # -*- coding: utf-8 -*- def find_max(a,b,c): tmp = a if tmp < b: tmp = b if tmp < c: tmp = c return tmp x = raw_input("Input 3 numbers: ") xs = x.strip().split(' ') print 'Max is {}'.format(find_max(xs[0], xs[1], xs[2]))
7250c672ad1b6b10dcf6a5703899e5c95bfc80d2
h-mora10/miso-agiles
/src/Fibonacci.py
591
4.21875
4
# -*- coding: utf-8 -*- def fibonacci(numero): if numero <= 1: return numero else: return fibonacci(numero - 1) + fibonacci(numero - 2) # Número que será el límite superior de la serie numMax = int(raw_input("Ingrese hasta cuál número desea calcular la Serie de Fibonacci?: ")) # Ciclo que calcular la serie resultado = [] numActual = 0 fibActual = fibonacci(numActual) while fibActual < numMax: resultado.append(fibActual) numActual = numActual + 1 fibActual = fibonacci(numActual) # Impresión de la serie print "Serie de Fibonacci: ", resultado
6d1957a10c716e4d1a9a18824d2fc87b7529b3fb
miky-roze/python-unittest
/04_shopping_basket_project/tests/test_shopping.py
2,274
3.671875
4
import unittest from main_codes.shopping_basket import ShoppingBasket from parameterized import parameterized class TestShoppingBasketWithNoProducts(unittest.TestCase): @classmethod def setUpClass(cls): print('\n[INFO] Setting up basket without any product...') cls.basket = ShoppingBasket() def test_size_of_basket_should_be_empty(self): self.assertEqual(len(self.basket), 0) def test_getting_product_out_of_range_should_raise_error(self): with self.assertRaises(IndexError): self.basket.get_product(0) def test_total_amount_should_be_zero(self): self.assertEqual(self.basket.total(), 0) class TestShoppingBasketWithOneProduct(unittest.TestCase): @classmethod def setUpClass(cls): print('\n[INFO] Setting up basket with one product...') cls.basket = ShoppingBasket().add_product('milk', 3.0) def test_size_of_basket_should_be_one(self): self.assertEqual(len(self.basket), 1) def test_total_amount_should_have_tax(self): self.assertAlmostEqual(self.basket.total(), 3.0 * 1.21) def test_getting_product(self): p = self.basket.get_product(0) self.assertEqual(p.__repr__(), "Product(name='milk', price=3.0, quantity=1)") def test_getting_product_out_of_range_should_raise_error(self): with self.assertRaises(IndexError): self.basket.get_product(1) class TestShoppingBasketWithTwoProducts(unittest.TestCase): @classmethod def setUpClass(cls): print('\n[INFO] Setting up basket with two products...') cls.basket = ShoppingBasket() \ .add_product('milk', 3.0) \ .add_product('water', 2.0) def test_size_of_basket_should_be_two(self): self.assertEqual(len(self.basket), 2) @parameterized.expand([ (0, 'milk'), (1, 'water') ]) def test_order_of_products(self, index, result): self.assertEqual(self.basket.get_product(index).name, result) def test_total_amount_should_have_tax(self): self.assertAlmostEqual(self.basket.total(), 5.0 * 1.21) def test_getting_product_out_of_range_should_raise_error(self): with self.assertRaises(IndexError): self.basket.get_product(2)
40c00c4ac0aaa8c06afab26f8daaacbd35d24fdd
Honoriot/Python_code
/OOP/Class Code4.py
1,214
4
4
class transport: def __init__(self, People_sit): self.People_sit = People_sit def Num_Of_People(self): print("People travels " + str(self.People_sit)) @staticmethod def Dur_Of_Travel(value): print("Travelling for " + str(value) + " time.") class automobile: def __init__(self, Wheel): self.Wheel = Wheel def Number_Of_Wheel(self): print("Has " + str(self.Wheel) + " wheels") class car(transport, automobile): def __init__(self, milage, People_sit, Wheel): self.milage = milage super().__init__(People_sit) #self.People_sit = People_sit self.Wheel = Wheel def Milage(self): print("Milage given: " + str(self.milage)) class truck(car): def __init__(self, load, milage, People_sit, Wheel): self.load = load self.milage = milage self.People_sit = People_sit self.Wheel = Wheel def Load(self): print("Load Carry: " + str(self.load)) truck1 = car(23, 3, 6) truck2 = truck(4500, 1000, 2, 12) truck1.Num_Of_People() truck1.Dur_Of_Travel(34) truck2.Load() truck2.Dur_Of_Travel(300) Aero = transport(250) Aero.Num_Of_People() Aero.Dur_Of_Travel(2)