blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
efdab853d59d23b60963aa22d19d57d35e508419
ulgoon/fcwps-project1
/ssungs_project1/hanoitower.py
669
3.6875
4
def hanoi_tower(disk_num, first, third, seccond): # recursion 함수로 disk_num이 1이 될때까지 반복 if __name__=='__main__': if disk_num == 1: print('{}번 원반을 {}에서 {}로 이동'.format(1, first, third)) else: # 시작점과 이동점, 도착점위치를 받는 위치 변경으로 변경 hanoi_tower(disk_num-1,first,seccond,third) print('{}번 원반을 {}에서 {}로 이동'.format(disk_num, first, third)) hanoi_tower(disk_num-1,seccond,third,first) hanoi_tower(3, 'First', 'Third', 'Seccond') # 원반갯수 , 시작점, 도착점, 이동점
e722a5c47ce6c2207fed0b31f8739f8c433de46d
supriyaprasanth/test
/9_july/test3.py
763
3.65625
4
from Exam import random file = open('ex.txt','r+') nwfile = open('ex1.txt','r+') print(file.read()) file.seek(0) #function to scramble the words def scramble(i): l = len(i) m = l-1 first = i[0] last = i[m] i = list(i) scram = "" index = 0 nwwrd = "" for j in range(len(i)-2): index = random.randint(1, (m - 1)) scram = scram + i[index] i.pop(index) m = m-1 nwwrd = first + scram + last return nwwrd #to write to the new file def filewrite (scram) : nwfile.write(scram) nwfile.write(" ") res = "" scam = "" line = file.read().split() for i in line: if len(i)>3: scram = scramble(i) filewrite(scram) else: scram = i filewrite(scram)
a7725cac689335bf9a189a90bfffa5301dc32fec
taylor009/Code-Challenges
/hackerRank/practice/stringFormating.py
321
3.640625
4
def string_formatter(number): width = len(bin(number)[2:]) for i in range(1, number + 1): deci = str(i) octa = oct(i)[2:] hexa = (hex(i)[2:]).upper() bina = bin(i)[2:] print(deci.rjust(width), octa.rjust(width), hexa.rjust(width), bina.rjust(width)) string_formatter(17)
b0efd75f689b154449b1e66c455b3c101b3bf635
glilley54/Week_2Day_4_All_work
/tdd_fizzbuzz/e48_solution/src/fizzbuzz.py
619
4.375
4
# function will take an integer as an argument def fizzbuzz(input): # check if we have received an integer: if type(input) != int: # return error message return "Please enter an integer" # check if it is divisible by both: elif input % 3 == 0 and input % 5 == 0: # return fizzbuzz return "fizzbuzz" # check if number is divisible by 3: elif input % 3 == 0: # return fizz return "fizz" # check if it is divisible by 5: elif input % 5 == 0: # return buzz return "buzz" # else return input as string return str(input)
1a07c9f44f56ab08143e87fdc2ace4014129235f
Anthony4421/Python-Exercises
/padlockchallenge6.py
613
4.0625
4
#Padlock Code Challenge - www.101computing.net/padlock-code-challenge-6/ ''' code = Total number of 3-digit combinations where one digit is equal to the sum of the other two digits. ''' code = 0 #Used three for loops to loop through individual digits #from 000 to 999 #Compares x,y and z to see if either are equal to sum of other two digits #Add 1 to code each time the condition is met #Successfully unlocked the padlock with code 136 for x in range(0,10): for y in range(0,10): for z in range(0,10): if (x == y+z) or (y == z+x) or (z == x+y): code +=1 print(code)
dda5c4e07fc09a304fe992bc7734b5b72ba1246c
picardcharlie/python-201
/04_functions-and-scopes/04_06_sandwich_stand.py
548
4.125
4
# Write a function called `make_sandwich()` that sticks to the following: # - takes a type of bread as its first, required argument # - takes an arbitrary amount of toppings # - returns a string representing a sandwich with the bread on top # and bottom, and the toppings in between. def make_sandwich(bread = "Sourdough", *args): sandwich = str(bread) + " " for toppings in args: sandwich += toppings + " " sandwich += str(bread) return sandwich items = ["cheese", "beef"] print(make_sandwich("White bread", *items))
9d6172cacf977c4c7f8c45f517d124fbdd2b6500
tanmayaggarwal/character-level-RNN
/main.py
2,245
4.25
4
# # This application builds a character-level RNN using LSTMs with PyTorch # The network will train character by character on some text, then generate new text # character by character. # Input: text from any book # Output: model will generate new text based on the text from input book # There are four main steps included in this application: # a. Load in text data # b. Pre-process the data, encoding characters as integers and creating one-hot input vectors # c. Define an RNN that predicts the next character when given an input sequence # d. Train the RNN and use it to generate new text # standard imports import numpy as np import torch from torch import nn import torch.nn.functional as F # load in data input_source = 'data/input_source.txt' # change source as needed from load_data import load_data text = load_data(input_source) # Tokenization (converting text to and from integers) from tokenization import tokenization chars, encoded = tokenization(text) # defining the one hot encoding function; parameters: (array, n_labels) from one_hot_encode import one_hot_encode # making training mini-batches from get_batches import get_batches # test implementation batches = get_batches(encoded, 8, 50) x, y = next(batches) # printing out the first 10 items in a sequence print ('x\n', x[:10, :10]) print ('\ny\n', y[:10, :10]) # check if GPU is available train_on_gpu = torch.cuda.is_available() if (train_on_gpu): print('Training on GPU!') else: print('No GPU available, training on CPU; consider making n_epochs very small.') # define the network with PyTorch from CharRNN import CharRNN # train the function from train import train # instantiating the model # set model hyperparameters n_hidden = 256 n_layers = 2 net = CharRNN(chars, n_hidden, n_layers) print(net) # set training hyperparameters batch_size = 10 seq_length = 100 n_epochs = 20 # train the model train(net, encoded, epochs=n_epochs, batch_size=batch_size, seq_length=seq_length, lr=0.001, print_every=10) # save the model from checkpoint import checkpoint f = checkpoint(net) # predict the next character from predict import predict # priming and generating text from sample import sample print(sample(net, 1000, prime="Hello", top_k=5))
a91fa3321e770003373f9fa7bd3870e8de2443f0
IshitaG-2002IGK/basic-programs
/5(b)-binary search.py
659
3.859375
4
print("20CS241_ISHITA G") data=[] n=int(input("Enter the number of elements in the array:")) print("Enter the elements in an Ascending order !") for i in range(0,n): x = int(input("Enter the element %d :"%(i+1))) data.append(x) e=int(input("Enter the element to be searched :")) first=0 last=n-1 found=False while(first<=last and not found): mid=(first+last)//2 if data[mid]==e: found=True else: if e<data[mid]: last=mid-1 else: first=mid+1 if found: print("Element",e,"found at the position",mid+1,".") else: print("Element",e,"NOT found in the array!")
613d903953eea906e4bef1371ce76c860538cde6
NicholusMuwonge/Simple-Learning-challenges
/GroupAnograms.py
191
3.875
4
from itertools import groupby some=['eat', 'em','tea', 'lump', 'me', 'plum'] annogramed=[list(arranged) for words,arranged in groupby(sorted(some, key=sorted),sorted)] print (annogramed)
9d0aa30e7ad120f47895a3086522d4afa521e7fe
Guanhuachen1995/Leetcode_practice
/algorithm/461. Hamming Distance/461.py
319
3.6875
4
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ count=0 while x!=0 or y !=0: if (x & 1) != (y & 1): count = count +1 x=x>>1 y=y>>1 return count
ffb1dd003b877d5b472bfa84603a2615a9f3897c
devendra-gh/ineuron_assignments
/python-assignment-1.py
2,417
4.15625
4
import math """" 1. Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. """ # Definition for Get Valid Numbers function def get_valid_numbers(range_start=None, range_stop=None): try: if range_start is None or range_stop is None: raise ValueError if not isinstance(range_start, int) or not isinstance(range_stop, int): raise TypeError valid_nums = [] range_start = int(range_start) range_stop = int(range_stop) for num in range(range_start, range_stop + 1): if num % 7 == 0 and num % 5 != 0: valid_nums.append(num) print(*valid_nums, sep=', ') except ValueError: print(f"Please provide input values {ValueError}") except TypeError: print(f"Please provide valid input number {TypeError}") get_valid_numbers(2000, 3200) """ 2. Write a Python program to accept the user's first and last name and then getting them printed in the the reverse order with a space between first name and last name. """ # Definition for Get Name reverse order function def get_name_reverse_order(): name = list() first_name = input('Please enter first name: ').strip() last_name = input('Please enter last name: ').strip() name.extend([first_name, last_name]) rev_name = [i[::-1] for i in name] print("\nReverse First and Last name's letters is: " + " ".join(rev_name)) print("Reverse First and Last Name is: " + " ".join(name[::-1])) print("Reverse First and Last Name's with letters is: " + " ".join(rev_name[::-1])) get_name_reverse_order() """ 3. Write a Python program to find the volume of a sphere with diameter 12 cm. Formula: V=4/3 * π * r 3 """ # Definition for Get Sphere volume function def get_sphere_volume(diameter=None): try: if diameter is None: raise ValueError radius = diameter / 2 volume = (4 / 3) * math.pi * (radius ** 3) print(f"Sphere's volume is: {volume:.3f} cm\u00b3") except ValueError: print(f"Please provide diameter value {ValueError}") except TypeError: print(f"Please provide valid input number for diameter {TypeError}") get_sphere_volume(12)
2b10195127a33f5174d4be3cb78d0e63b5fe5cde
CristinaMarzo/PrimeraEvaluacion
/Calculadora par-impar.py
252
3.8125
4
def calculadora(): print 'Bienvenido a la calculadora de numeros pares o impares.' n = input('Introduzca su numero aqui: ') if n % 2 ==0: print 'Su numero es par' else: print 'Su numero es impar' calculadora()
053ee66b58ab0dc9240cf8eef2fc5f765cbaa7ec
Ledz96/ML_Project_1
/utils_predictions_manipulation.py
502
3.515625
4
# -*- coding: utf-8 -*- """Utils functions for handling predictions""" import numpy as np def probability_to_prediction(y,threshold=0.5): """given an array of probabilities y, returns a prediction (1 or -1) for each""" replacer = lambda p: 1 if p > threshold else -1 vfunc = np.vectorize(replacer) return vfunc(y) def get_prediction_accuracy(y, pred_y): """given a true y and a prediction, gets the predition accuracy""" return (np.array(y == pred_y)).sum()/len(y)
f3e3ba7493ca929f2d9c74c84e5be9f1d9abf103
DavidAndrade27/DataScienceAndMLBassics
/IA_dovo_r/3_Clustering/K-means/K-means-clustering.py
1,844
4.09375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 10 18:03:14 2020 Clustering using K-means Important: 1 . Random initialization of centroids (consider using the k-means ++ algorithm) 2 . Determine the number of clusters (consider the elbow method) @author: andra """ # Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Reading the dataset dataset = pd.read_csv("Mall_Customers.csv") X = dataset.iloc[:, [3,4]].values # Elbow method to determine the number of clusters from sklearn.cluster import KMeans wcss = [] for i in range(1, 11): kmeans_det = KMeans(n_clusters = i, init="k-means++", max_iter = 300, n_init = 10, random_state = 0) kmeans_det.fit(X) wcss.append(kmeans_det.inertia_) # + square plt.plot(range(1,11), wcss) plt.title("Elobow method") plt.xlabel("Clusters number") plt.y_label("WCSS(k)") plt.show() # the most optimal value of clusters are 5 # Apply k-means method for data segmentation kmeans = KMeans(n_clusters = 5, init="k-means++", max_iter = 300, n_init = 10, random_state = 0) y_kmeans = kmeans.fit_predict(X) # Vis of clusters plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = "red", label = "Cluster 1") plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = "blue", label = "Cluster 2") plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = "green", label = "Cluster 3") plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = "cyan", label = "Cluster 4") plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = "magenta", label = "Cluster 5") plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s = 300, c = "yellow", label = "Baricenters") plt.title("Clients clusters") plt.xlabel("Annual income (K$)") plt.ylabel("Expense score (1-100") plt.legend() plt.show()
7eab03472f265969761aa57574ce6b3962416136
BarryMolina/ITDEV-154
/assignment-4/stack.py
1,001
3.953125
4
from node import Node class Stackll: def __init__(self): self.head = None # object representation def __repr__(self): nodes = [] for node in self: nodes.append(node.data) return f"[{', '.join(nodes)}]" def __iter__(self): node = self.head while node is not None: yield node node = node.next # add node to beginning of list def push(self, node): # sets nodes next value to the start of linked list node.next = self.head # sets the start of the linked list to point at the new node self.head = node # removes the first node and returns it def pop(self): # if the list is empty if not self.head: raise Exception("Stack is empty") # otherwise set a new node variable equal to the first node node = self.head # delete the first node in the list self.head = self.head.next return node
535ec4903f18dafc4748d490ba16286fedee15d9
BitBitcode/Numerical-Analysis
/矩阵相关/矩阵运算.py
1,011
3.5625
4
import numpy # 二维输出 A_matrix = numpy.mat("1,2,3; 4,5,2; 7,8,9") B_matrix = numpy.mat("1,2,3; 4,5,2; 7,8,9") print("原矩阵:\n", A_matrix.A) # 转置矩阵 A_matrix_T = A_matrix.T print("转置矩阵为:\n", A_matrix_T) # 共轭转置矩阵 A_matrix_H = A_matrix.H print("共轭转置矩阵为:\n", A_matrix_H) # 逆矩阵 A_matrix_N = A_matrix.I print("逆矩阵为:\n", A_matrix_N) # 矩阵乘法 A_nm = numpy.mat("1,2,3; 4,5,6; 7,8,9") B_kl = numpy.mat("7,8,9; 1,2,3; 4,5,6") # 方法一:已经定义为矩阵的情况下,直接用乘号 print("矩阵乘法A*B = \n", A_nm*B_kl) # 方法二:如果没有定义为矩阵,而是定义为二维数组,但需要用矩阵的乘法(而不是简单的对应元素相乘),那么需要用dot() A = numpy.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) B = numpy.array([ [7, 8, 9], [1, 2, 3], [4, 5, 6] ]) print("二维数组对应相乘:\n", A*B) print("二维数组矩阵乘法dot(A,B) = \n", numpy.dot(A,B))
bc99cc6b2e41cc77edeaebf09bda9d44a1c91bbf
santoshankr/parliament
/parliament/finding.py
1,119
3.53125
4
class severity: """ Used by Findings """ MALFORMED = 1 # Policy is so broken it cannot be checked further INVALID = 2 # Policy does not comply with documented rules HIGH = 3 MEDIUM = 4 LOW = 5 class Finding: """ Class for storing findings """ issue = "" severity = "" location = {} def __init__(self, issue, severity, location): self.issue = issue self.severity = severity self.location = location def __repr__(self): """ Return a string for printing """ return "{} - {} - {}".format(self.severity_name(), self.issue, self.location) def severity_name(self): if self.severity == severity.MALFORMED: return "MALFORMED" elif self.severity == severity.INVALID: return "INVALID" elif self.severity == severity.HIGH: return "HIGH" elif self.severity == severity.MEDIUM: return "MEDIUM" elif self.severity == severity.LOW: return "LOW" else: raise Exception("Unknown severity: {}".format(self.severity))
66d3ac24e1659a3bacdec83cb7b55844244d06c3
anantkaushik/leetcode
/238-product-of-array-except-self.py
835
3.59375
4
""" Problem Link: https://leetcode.com/problems/product-of-array-except-self/description/ Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Note: Please solve it without division and in O(n). Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) """ class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: p = 1 res = [] for i in range(len(nums)): res.append(p) p *= nums[i] p = 1 for i in range(len(nums)-1,-1,-1): res[i] = res[i] * p p *= nums[i] return res
36664faea454e5d08427dfb841d6e2f7efeaefa2
Hemanthkumar2112/gcd-of-two-numbers
/gcd and gcd_eculid.py
337
3.671875
4
a = 98 b = 56 def gcd(x,y): if x==0: return y if y==0: return x if x>y: return gcd(x-y,y) return gcd(x,y-x) def gcd_eculid(x,y): if x==0: return y elif y==0: return x else: return gcd(y,x%y) gcd_eculid(a,b) ##14 more efficient gcd(a,b) ####14
03f634dc1e1e7094ac7261f10f5043d2f3700656
rohitm131/opencv
/drawing and writing on image.py
707
3.59375
4
import cv2 import numpy as np img = cv2.imread('watch.jpg', 1) #cv2.IMREAD_COLOR = 1 #drawing shapes cv2.line(img, (0, 0), (150, 150), (255, 255, 255), 15) cv2.rectangle(img, (15, 25), (200, 150), (0, 255, 0), 5) cv2.circle(img, (100, 63), 55, (0, 0, 255), -1) #-1 to fill the circle with color #drawing a polygon pts = np.array([[10,5], [20,30], [70,20], [50,10]], np.int32) #pts = pts.reshape((-1, 1, 2)) cv2.polylines(img, [pts], True, (0, 255, 255), 3) #writing on image font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, 'openCV !', (0, 130), font, 1, (200, 255, 255), 2, cv2.LINE_AA) #to show cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()
3acbf3aedffd5f591826bbcc2fb98255c9a20664
hieubz/Crack_Coding_Interview
/leetcode/easy/print_all_permutation.py
670
3.578125
4
class Tools: def __init__(self): self.permutation_arr = {} @staticmethod def to_string(list_chars): return ''.join(list_chars) # O(n!) def permute(self, string, l, r): if l == r: self.permutation_arr[(self.to_string(string))] = 1 else: for step in range(l, r + 1): string[l], string[step] = string[step], string[l] self.permute(string, l + 1, r) string[l], string[step] = string[step], string[l] # backtrack strings = 'ABC' leng = len(strings) arr = list(strings) tools = Tools() tools.permute(arr, 0, leng - 1) print(tools.permutation_arr)
d6d96f5d315f4685a3a7069318f271592018eb30
ebondy/Python
/ListOverlap.py
980
4.15625
4
#!/usr/bin/env python3 #Author: Eric Bondy #List overlap practice import random #Import the random module ListA = [random.randint(0, 51) for i in range(1, (random.randint(1, 51)))] #Generate two random lists of integers between 0-50 with a random length between 1-50 ListB = [random.randint(0, 51) for i in range(1, (random.randint(1, 51)))] ResultList = [] #Empty result list to append matching values for i in ListA: #Search through the two lists for matching values and avoid duplicates if i in ListB and i not in ResultList: ResultList.append(i) print("List A is below") #Print all 3 lists to check for errors print(ListA) print("List B is below") print(ListB) print("Result List is below") print(ResultList)
30bb48b833570df2c1b48cbecec51acb911f23a5
Rayna-911/LeetCode
/LC/python/Reorder List.py
1,086
3.8125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return nothing def reorderList(self, head): if head == None or head.next == None: return head #slice list to two slow = head quick = head while quick.next and quick.next.next: slow = slow.next quick = quick.next.next head1 = head head2 = slow.next slow.next = None #reverse list2 p1 = head2 p2 = head2.next head2.next = None while p2: tmp = p2 p2 = p2.next tmp.next = p1 p1 = tmp head2 = p1 #merge two lists pf = head1 pe = head2 while pe: temp1 = pf.next temp2 = pe.next pf.next = pe pe.next = temp1 pf = temp1 pe = temp2
9d33f05c5942fff37f4fc5fc3e4787b38e07a15e
rhaeguard/algorithms-and-interview-questions-python
/string-questions/one_away_string.py
1,397
3.859375
4
""" One away string It means if two strings are 1 edit away 1 edit - add, delete, change letter to other letter (even itself) """ def one_away_string(st1, st2): if abs(len(st1) - len(st2)) > 1: return False if st1 == st2: return True if len(st1) < len(st2): st1, st2 = st2, st1 dictionary = {} for ch in st1: if ch not in dictionary: dictionary[ch] = 1 else: dictionary[ch] += 1 for ch in st2: if ch in dictionary: dictionary[ch] -= 1 one_count = 0 for k, v in dictionary.items(): if v == 1: one_count += 1 return one_count == 1 def one_away_string_v2(st1, st2): if abs(len(st1) - len(st2)) > 1: return False if st1 == st2: return True if len(st1) == len(st2): pass_for_once = 0 for i in range(len(st1)): if st1[i] != st2[i]: pass_for_once += 1 if pass_for_once == 1: return True else: return False if len(st1) < len(st2): st1, st2 = st2, st1 j = 0 pass_for_once = 0 for ch in st1: if ch != st2[j]: pass_for_once += 1 if pass_for_once > 1: return False continue j += 1 if pass_for_once == 1: return True else: return False
fc56ce68360a6bf55b39835871d69a5c9b9a9769
JoseCordobaEAN/refuerzo_programacion_2018_1
/sesion_5/imprimir_numeros.py
154
3.515625
4
import time # Vamos a imprimir los numeros entre 0 y -10 usando python numero =0 while numero > -11: print(numero) numero -=1 time.sleep(1)
eb491a1feb6ef8294124367e5d350579fbaca5cf
EdwaRen/Competitve-Programming
/Leetcode/37-sudoku-solver.py
1,795
3.96875
4
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead. Backtracking solution that iterates all possible combinations and stops recursing when a board is invalid """ self.dfs(board) return board def dfs(self, board): i, j = self.nextIncomplete(board) if i == -1 and j == -1: return True for n in range(1, 10): if self.isValid(board, i, j, str(n)): board[i][j] = str(n) if self.dfs(board): return True board[i][j] = '.' return False def nextIncomplete(self, board): for i in range(9): for j in range(9): if board[i][j] == '.': return (i, j) return (-1, -1) def isValid(self, board, row, col, n): # Check if the column is valid for i in range(9): if board[i][col] == n: return False # Check if row is valid for i in range(9): if board[row][i] == n: return False # Check if encapsulating square is valid for i in range(3): for j in range(3): if board[(row - row%3) + i][(col - col%3) + j] == n: return False return True z = Solution() board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] print(z.solveSudoku(board))
9c82f6839b77fc333d681d56698dbc56ed0b99b5
andylampi/esercizi_workbook_python
/capitolo_7/esercizio_158.py
1,262
3.84375
4
#!/bin/python3 import os def remove(file_1): counter_2 = 0 counter_1 = 0 list_prove = list() list_complete = list() file_find = os.path.abspath(file_1) file_open = open(file_find, "r") list_file = list(file_open) for counter in range(0, len(list_file)): string = "" moment = list() moment = list(list_file[counter]) for index_moment in moment: if index_moment != " ": string += index_moment elif index_moment == " ": list_complete.append(string) string = "" for index_moment in list_complete: if index_moment == " " or index_moment == "": list_complete.pop(counter_2) counter_2 += 1 else: counter_2 +=1 counter_2 =0 for index_moment in list_complete: if index_moment.startswith("#"): list_complete.pop(counter_2) counter_2 += 1 else: counter_2 += 1 print(list_complete) def main(): try: file_1=input("Enter the name of the file: ") remove(file_1) except FileNotFoundError: print("file not found!") if __name__ == '__main__': main()
228fcb83d8ca4257fa64949da8bc07c2d243b679
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/leetcode/LeetCode/959 Regions Cut By Slashes.py
3,047
4.1875
4
#!/usr/bin/python3 """ In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space. These characters divide the square into contiguous regions. (Note that backslash characters are escaped, so a \ is represented as "\\".) Return the number of regions. Example 1: Input: [ " /", "/ " ] Output: 2 Explanation: The 2x2 grid is as follows: Example 2: Input: [ " /", " " ] Output: 1 Explanation: The 2x2 grid is as follows: Example 3: Input: [ "\\/", "/\\" ] Output: 4 Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.) The 2x2 grid is as follows: Example 4: Input: [ "/\\", "\\/" ] Output: 5 Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.) The 2x2 grid is as follows: Example 5: Input: [ "//", "/ " ] Output: 3 Explanation: The 2x2 grid is as follows: Note: 1 <= grid.length == grid[0].length <= 30 grid[i][j] is either '/', '\', or ' '. """ from typing import List class DisjointSet: def __init__(self): """ unbalanced DisjointSet """ self.pi = {} def union(self, x, y): pi_x = self.find(x) pi_y = self.find(y) self.pi[pi_y] = pi_x def find(self, x): # LHS self.pi[x] if x not in self.pi: self.pi[x] = x if self.pi[x] != x: self.pi[x] = self.find(self.pi[x]) return self.pi[x] class Solution: def regionsBySlashes(self, grid: List[str]) -> int: """ in 1 x 1 cell 3 possibilities ___ | | |___| ___ | /| |/__| ___ |\ | |__\| 4 regions in the ___ |\ /| |/_\| """ m, n = len(grid), len(grid[0]) ds = DisjointSet() T, R, B, L = range(4) # top, right, bottom, left for i in range(m): for j in range(n): e = grid[i][j] if e == "/" or e == " ": ds.union((i, j, B), (i, j, R)) ds.union((i, j, T), (i, j, L)) if e == "\\" or e == " ": # not elif ds.union((i, j, T), (i, j, R)) ds.union((i, j, B), (i, j, L)) # nbr if i - 1 >= 0: ds.union((i, j, T), (i-1, j, B)) if j - 1 >= 0: ds.union((i, j, L), (i, j-1, R)) # unnessary, half closed half open # if i + 1 < m: # ds.union((i, j, B), (i+1, j, T)) # if j + 1 < n: # ds.union((i, j, R), (i, j+1, L)) return len(set( ds.find(x) for x in ds.pi.keys() )) if __name__ == "__main__": assert Solution().regionsBySlashes([ " /", "/ " ]) == 2 assert Solution().regionsBySlashes([ "//", "/ " ]) == 3
96c6a1824bb4cd7d6cb752aa14b442e121dcef0b
m1ghtfr3e/Competitive-Programming
/Leetcode/Python/April-30-day-Challenge/moveZero_2.py
325
3.859375
4
def moveZero(nums): x = 0 # we use it as a pointer for i in nums: if i != 0: nums[x] = i x += 1 for i in range(x, len(nums)): nums[i] = 0 return nums if __name__ == '__main__': print(moveZero([0,1,0,3,12])) print(moveZero([0,0,1]))
dbe5557dd951d7ccc080f7f229c0a614f8ce9728
Dipanshisharma97/spychat
/oddeven.py
110
4.09375
4
a=input("enter a number") if a%2==0: print " it is an even number" else: print "it is a odd number"
f5215d9326de93313b3636a47be4530151b57bba
MonilSaraswat/hacktoberfest2021
/basicCalculator.py
1,119
4.21875
4
def inputValues(): firstNumber = int(input("Enter first number : ")) secondNumber = int(input("Enter second number : ")) return [firstNumber , secondNumber] choice = 'Y' while(choice in ('Y' , 'y')): values = inputValues() operation = input("What Do you want to perform : ") if (operation in ('+' ,'plus' , 'add' , 'adition')): print("Output is :" , values[0]+values[1]) choice = input("Do you want to continue... Y/N ") elif(operation in ('-' ,'minus' , 'subtract' , 'subtraction')): print("Output is :" , abs(values[0]-values[1])) choice = input("Do you want to continue... Y/N ") elif(operation in ('*' , 'multiply' , 'multiplication')): print("Output is :" , values[0]*values[1]) choice = input("Do you want to continue... Y/N ") elif(operation in ('/' , 'divide' , 'division')): print("Output is :" , values[0]/values[1]) choice = input("Do you want to continue... Y/N ") else: choice = input("Not a correct Input.. \n Do you want to continue... Y/N ") else: print("Thanks for using my calculator")
a0af3002fc2e01654b9140a7b55c71bbc073007a
abimarticio/practice-problems
/basic/prob_12.py
729
4.25
4
# Get the Hamming distance. # Hamming distance is the number of positions at which the corresponding symbols in compared strings are different. # Input # KAROLIN # KERSTIN # Output # 3 def get_hamming_distance(first_text: str, second_text: str): count = 0 for index in range(len(first_text)): if first_text[index] != second_text[index]: count += 1 return count def main(): first_text = input("Enter text: ") second_text = input("Enter text: ") if len(first_text.upper()) == len(second_text.upper()): hamming_distance = get_hamming_distance(first_text=first_text, second_text=second_text) print(hamming_distance) else: print("Not equal in length!") main()
40535cdf2f07100843be82b5c64bd71d75f7c945
Harsh1t-coder/Python
/Alarmclock.py
568
3.578125
4
#Alarm Clock from datetime import datetime import urllib import webbrowser time=input("ENter the alarm time : HH:MM:SS ") hour = time[0:2] minu = time[3:5] sec= time[6:8] print("Setting your alarm") while True: now = datetime.now() curr_hour = now.strftime("%H") curr_min = now.strftime("%M") curr_sec = now.strftime("%S") if(hour == curr_hour): if(minu == curr_min): if(sec == curr_sec): print("Wakeup Sid") webbrowser.open("https://www.youtube.com/watch?v=iNpXCzaWW1s") break
7302ec38f9b7748836bf0f34cdb5ebbbefc8993e
KX-Lau/python_algorithms
/02_反转链表.py
528
3.90625
4
class Node: def __init__(self, data): self.data = data self.next = None class Solution: """反转链表, 输出表头""" def ReverseList(self, pHead): # 空链表或链表只有一个结点 if pHead is None or pHead.next is None: return pHead cur_node = pHead pre = None while cur_node is not None: p_next = cur_node.next cur_node.next = pre pre = cur_node cur_node = p_next return pre
24cf7942192af48a50b0de8176a90fc87f3b4c3c
jaswanthrk/CV
/blob_detection.py
1,081
3.5
4
# BLOBS : GROUPS OF CONNECTED PIXELS THAT ALL SHARE A COMMON PROPERTY # simpleBlobDetector : CREATE DETECTOR => INPUT IMAGE INTO DETECTOR => OBTAIN KEY POINTS => DRAW KEY POINTS import cv2 import numpy as np image = cv2.imread('images/Sunflowers.jpg', cv2.IMREAD_GRAYSCALE) detector = cv2.SimpleBlobDetector() keypoints = detector.detect(image) # DRAW DETECTED BLOBS AS RED CIRCLES. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of # THE CIRCLE CORRESPONDS TO THE SIZE OF BLOB. blank = np.zeros( (1, 1) ) blobs = cv2.drawKeypoints(image, keypoints, blank, (0, 255, 255), cv2.DRAW_MATCHES_FLAGS_DEFAULT) # Show keypoints cv2.imshow("Blobs", blobs) cv2.waitKey() cv2.destroyAllWindows() # cv2.drawKeypoints(input image, keypoints, blank_output_array, color, flags) # flags : # cv2.DRAW_MATCHES_FLAGS_DEFAULT # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS # cv2.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG # cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS # cv2.DRAW_MATCHES_FLAGS_DEFAULT # cv2.DRAW_MATCHES_FLAGS_DEFAULT
48fccc209d27af25587c06c0e000dea63d2eeb18
kdanyss/ExerciciosPython
/Lista 3/questao3.py
674
3.875
4
name = str (input ('Diga teu nome: \n')) while len(name) <= 3: name = str (input ('Inválido. Diga teu nome: \n')) idade = int (input ('Diga tua idade: \n')) while idade < 0 or idade > 150: idade = int (input ('Inválido. Diga tua idade: \n')) salario = float (input ('Diga teu salário: \n')) while salario < 0: salario = float (input ('Inválido. Diga teu salário: \n')) sexo = input ('Sexo: f ou m \n') while sexo != 'f' and sexo != 'm': sexo = input ('Inválido. Sexo: f ou m \n') civil = input ('Estado civil s/c/n/d \n') while civil != 's' and civil != 'c' and civil != 'n' and civil != 'd': civil = input ('Inválido. Estado civil s/c/n/d \n')
b4932eec2902dcdfbfaf2e3f0b6131cbb1749296
sswietlik/helloPython
/nr10_Operacje_WEJŚCIA_I_WYJŚCIA/nr002_moduł_OS_LAB.py
628
3.625
4
import os import time dir = input('podaj ścieżkę dostępu do katalogu') if not os.path.isdir(dir): print('%s must be a directory' % dir) else: file = input('Wprowadź nazwę pliku :' % dir) path = os.path.join(dir,file) if not os.path.isfile(file): print('file not exist') #print('File %s does not exist!' % path) else: print('data ostatniej modyfikacji pliku', os.path.getmtime(file)) print('rozmiar pliku w bajtach', os.path.getsize(file)) print('bieżący katalog ', os.getcwd(file)) print('podaje ścieżkę względna pliku', os.path.abspath(file))
3cb950597cffe2da2fdc26c263b826f39f130198
Shiwoo-Park/crawlpy
/utils/log.py
8,319
3.78125
4
#!/usr/bin/env python #coding: utf8 import logging import sys import logging.handlers from os import path,makedirs,listdir,remove #define handler FILE_HANDLER = 0 ROTATING_FILE_HANDLER = 1 TIMED_ROTATING_FILE_HANDLER = 2 STREAM_HANDLER = 3 CRITICAL = logging.CRITICAL ERROR = logging.ERROR WARNING = logging.WARNING INFO = logging.INFO DEBUG = logging.DEBUG NOTSET = logging.NOTSET logDict = dict() class Log: """ Logger class based on logging module you can make logger without root logger if you don't want to write log to many files, just create Log with name and filename and also Log has hierarchy. If you do like this p_logger = Log("babo",filename="babo.log") c_logger = Log("babo.son",filename="babo.son.log") c_logger.error("HAHAHA") "HAHAHA" will be written to babo.log and babo.son.log and if you want to write log separately, just do like this. b_logger = Log("babo",filename="babo.log") m_logger = Log("mungchungi", filename="munchungi.log") b_logger.error("HEHEHEHEHE") m_logger.error("HUHUHUHUHU") if you already made root logger, then "HEHEHEHEHE" and "HUHUHUHUHU" will be written to root logfile """ def __init__(self, name=None, **kwargs): """ type of args filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. See http://www.python.org/doc/current/lib/node422.html datefmt Use the specified date/time format. level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. **kwargs can be filename = "./aaa.log", filemode = "a", format='%(asctime)s %(levelname)s %(message)s' type of level CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 default value of args filename : ./wstmp.log format : '%(asctime)s %(levelname)s %(message)s' level : DEBUG """ self.logger = logging.getLogger(name) if name == None: self.name = 'root' else: self.name = name logDict[self.name] = self if len(self.logger.handlers) == 0: level = kwargs.get("level",INFO) stream = kwargs.get("stream",None) filename = kwargs.get("filename",None) if filename: self._checkDir(filename) mode = kwargs.get("filemode",'a') hdlr = logging.FileHandler(filename,mode) else: stream = kwargs.get("stream") hdlr = logging.StreamHandler(stream) format = kwargs.get("format",'%(asctime)s %(filename)s:%(lineno)s %(levelname)s %(message)s') dfs = kwargs.get("datefmt", "%y-%m-%d %H:%M:%S") fmt = logging.Formatter(format,dfs) hdlr.setFormatter(fmt) self.logger.addHandler(hdlr) self.logger.setLevel(level) self.format = format self.dfs = dfs self.level = level def __str__(self): """ return logger name and handlers and its child """ ret_str = "logger name : %s\n"%self.name n_logger = self.logger for name in logging.Logger.manager.loggerDict: if name.find(self.name) >= 0 and name != self.name: ret_str += " child : " + name +"\n" for h in n_logger.handlers[:]: ret_str += " handler : " + str(h) +"\n" return ret_str def __repr__(self): """ return logger name and handlers """ return self.__str__() def _checkDir(self, filename): """ check directoy. unless dir exists, make dir """ if len(path.dirname(filename)) > 0 and not path.exists(path.dirname(filename)): makedirs(path.dirname(filename)) def debug(self, msg, *args, **kwargs): """ write debug level log """ self.logger.debug(msg, *args, **kwargs) def error(self, msg, *args, **kwargs): """ write error level log """ self.logger.error(msg,*args,**kwargs) def warning(self, msg, *args, **kwargs): """ write warning level log """ self.logger.warning(msg,*args,**kwargs) def critical(self, msg, *args, **kwargs): """ write critical level log """ self.logger.critical(msg, *args, **kwargs) def info(self, msg, *args, **kwargs): """ write info level log """ self.logger.info(msg, *args, **kwargs) def removeHandler(self): """ remove all handler """ n_logger = self.logger for h in n_logger.handlers[:]: n_logger.removeHandler(h) def addHandler(self, type, filename=None, **kwargs): """ add handler * type of handler FILE_HANDLER = 0 ROTATING_FILE_HANDLER = 1 TIMED_ROTATING_FILE_HANDLER = 2 STREAM_HANDLER = 3 It can be added. * type of kwargs FILE_HANDLER : mode ROTATING_FILE_HANDLER : mode, maxBytes, backupCount TIMED_ROTATING_FILE_HANDLER : when,interval, backupCount * type of when 'S' : second 'M' : minute 'H' : hour 'D' : day 'W' : week 'midnight' : 00:00 if u set when = 'S',interval = 1, then logger will rotate file every second if u set when = 'midnight', interval = 1, then logger will rotate file at midnight every day For more information, See http://www.python.org/doc/current/lib/node410.html return 0 when succeeded, else return -1 """ try: if filename != None: self._checkDir(filename) else: filename = './wstmp.log' if type == FILE_HANDLER: mode = kwargs.get("mode", "a") fh = logging.handlers.FileHandler(filename,mode) elif type == ROTATING_FILE_HANDLER: mode = kwargs.get("mode", "a") maxBytes = kwargs.get("maxBytes", 512) backupCount = kwargs.get("backupCount", 5) fh = logging.handlers.RotatingFileHandler(filename,mode,maxBytes,backupCount) elif type == TIMED_ROTATING_FILE_HANDLER: when = kwargs.get("when", "midnight") interval = kwargs.get("interval", 1) backupCount = kwargs.get("backupCount", 0) fh = logging.handlers.TimedRotatingFileHandler(filename, when, interval, backupCount) elif type == STREAM_HANDLER: fh = logging.StreamHandler() else: sys.stderr.write("we don't have that kind of Handler\n") return -1 level = kwargs.get("level", self.level) format = kwargs.get("format", self.format) dfs = kwargs.get("datefmt",self.dfs) fh.setLevel(level) fh.setFormatter(logging.Formatter(format,dfs)) self.logger.addHandler(fh) return 0 except Exception,msg: sys.stderr.write("%s\n"% msg) return -1 def resetHandler(self, type, filename=None, **kwargs): """ remove all other handler and add new handler """ try: self.removeHandler() self.addHandler(type, filename, **kwargs) except Exception,msg: sys.stderr.write("%s\n"%msg) def getLogger(name=None, **kwargs): """ return logger by name """ if name == None: if len(logging.getLogger().handlers) == 0: t_logger = Log(**kwargs) logDict['root'] = t_logger return t_logger.logger else: try: return logDict['root'].logger except: return logging.getLogger() else: if name in logDict: return logDict[name].logger else: t_logger = Log(name,**kwargs) logDict[name] = t_logger return t_logger.logger def logTest(): p_logger = getLogger("babo.ppp") p_logger.error("TEST") p_logger.debug("FFFF") if __name__ == "__main__": try: root_logger = Log() root_logger.resetHandler(TIMED_ROTATING_FILE_HANDLER, "./time_rotating.log", when = 'S', backupCount=10) root_logger.addHandler(STREAM_HANDLER) root_logger.addHandler(ROTATING_FILE_HANDLER, "./rotating_file.log", mode='w', maxBytes=1024, backupCount=2, level=ERROR) babo_logger = Log("babo", filename="babo.log") babo_logger.addHandler(ROTATING_FILE_HANDLER, "./test.log", mode='a', maxBytes=512, backupCount=2) babo_kkk_logger = Log("babo.kkk", filename='./babo.kkk.log') babo_ppp_logger = Log("babo.ppp", filename='./babo.ppp.log') mungchungi_logger = Log("mungchungi", filename='./mungchungi.log') for i in range(0,100): root_logger.debug("AAAasdf asdfasdf asdfasdf") babo_kkk_logger.debug("PPP") babo_ppp_logger.debug("KKK") mungchungi_logger.debug("LLL") print babo_kkk_logger print babo_logger logTest() except Exception,msg: sys.stderr.write("%s\n"%msg)
91ef7c63e63abf8e18f2109083a3f4fa34dd09fd
solomon585858/BasePython
/homework_01/main.py
1,191
4.21875
4
def power_numbers(*numbers): """ функция, которая принимает N целых чисел, и возвращает список квадратов этих чисел """ return [number ** 2 for number in numbers] # filter types ODD = "odd" EVEN = "even" PRIME = "prime" def is_prime(numbers): prime_list = [] for num in numbers: if num > 1: for i in range(2, num): if (num % i) == 0: break else: prime_list.append(num) return prime_list def filter_numbers(numbers, filter_type): """ функция, которая на вход принимает список из целых чисел, и возвращает только чётные/нечётные/простые числа (выбор производится передачей дополнительного аргумента) """ if filter_type == ODD: return list(filter(lambda x: x % 2 == 1, numbers)) elif filter_type == EVEN: return list(filter(lambda x: x % 2 == 0, numbers)) elif filter_type == PRIME: return is_prime(numbers)
d4b8894a47573a2986af41af5ca59703fb973fd4
James-Joe/jun_dev.py
/madlibs.py
861
4.1875
4
print("Welcome to Mad libs!") #This function provides the basic functionallity of the game. #The function finishes by calling play_again(), which gives the player #the choice to try again or quit the program. def mad_lib(): part_1 = "I went to the store and saw a " print(part_1) entry_1 = input() part_2 = "I went in and ask the assistant where did he find the " + entry_1 + " and he said " print(part_2) entry_2 = input() print(part_1 + entry_1 + part_2 + entry_2) play_again() def play_again(): print("Thanks for playing. Do you want to play again? [Y/N]") entry_3 = input() if entry_3 == "Y" or entry_3 == "y": mad_lib() elif entry_3 == "N" or entry_3 == "n": print("Okay! see you later!") else: print("Sorry that isn't a valid input.") play_again() mad_lib()
2f110050d358f6b5a01a7f6096c31389aec15414
VdovichenkoSergey/QAutomation_python_pytest
/Profile/Person.py
1,138
3.625
4
import datetime class Person: def __init__(self, full_name, year_of_birth): self.full_name = str(full_name) self.year_of_bitrh = int(year_of_birth) self.name_parsing = self.full_name.split() def first_name(self): f_name1 = self.name_parsing[0] return f_name1 def surname(self): surname = self.name_parsing[1] return surname def age_in(self, year_in=None): if year_in is None: year_in = datetime.datetime.now().year # оператор нужен для того # чтбы каждый объект имел свое значение по умолчанию years_old = year_in - self.year_of_bitrh return years_old def __str__(self): message = f'Atributes of your object: \n \n'\ f'Full name: {self.full_name} \n'\ f'Year of birth: {self.year_of_bitrh} \n' return message # a = Person('Sergey Vdovichenko', 1955) # print() # print(a) # print(a.first_name()) # print(a.surname()) # print(a.year_of_bitrh) # print(a.age_in(2020))
6eaeb2de9cc2b448f450f0a218ada87f124e811a
GenerationTRS80/JS_projects
/python_starter/py_json.py
392
3.8125
4
# JSON is commonly used with data APIS. Here how we can parse JSON into a Python dictionary #Import JSON module import json #Sample JSON userJSON = '{"first_name":"John","last_name":"Doe","age":30}' #Parse to ** DICTIONARY ** user = json.loads(userJSON) print(user) print(user['first_name']) car ={'make': 'Mazda','model':'Mustang','year':1970} carJSON = json.dumps(car) print(carJSON)
8043be9245f16fb8eea6768df98978a794c07262
IkuyaYamada/plural_form
/plural.py
1,438
3.703125
4
#singular to plural def get_words(): """ comment gizagiza """ rows = int(input()) words_list = [] for i in range(rows): words_list.append(input()) return(words_list) get_words = get_words() target = [x[-2:] for x in get_words] rest = [x[:-2] for x in get_words] def appender(target): appender = [] for i in target: #zone "es" if (i in ("sh", "ch")) or (i[-1] in ("s", "o", "x")): appender.append(i + "es") #zone "ves" elif (i == "fe"): appender.append("ves") elif (i[-1] == "f"): appender.append(i[0] + "ves") #zone "ies" elif (i[-1] == "y") and (i[0] not in ("a", "i", "u", "e", "o")): appender.append(i[0] + "ies") #zone "s" else: appender.append(i + "s") return(appender) appender = appender(target) results = [x+y for x,y in zip(rest,appender)] for i in results: print(i) """ ・末尾が s, sh, ch, o, x のいずれかである英単語の末尾に es を付ける ・末尾が f, fe のいずれかである英単語の末尾の f, fe を除き、末尾に ves を付ける ・末尾の1文字が y で、末尾から2文字目が a, i, u, e, o のいずれでもない英単語の末尾の y を除き、末尾に ies を付ける ・上のいずれの条件にも当てはまらない英単語の末尾には s を付ける """
c3baf716d2cda2d2d49a86432b87598378464ea0
dersenok/python3_Les2
/venv/LES_1/Les_1_task_7.py
437
4
4
# 7. Определить, является ли год, # который ввел пользователем, # високосным или невисокосным. y = int(input('Введите год в формате YYYY: ')) if y % 4 != 0: print("Обычный") elif y % 100 == 0: if y % 400 == 0: print("Високосный") else: print("Обычный") else: print("Високосный")
e746c5927f0a1757bc0148a3b84e90efc4030100
szymonj99/PythonPractice
/diceRollingGenerator.py
396
4.1875
4
#!/usr/bin/env python3 //Runs on Python 3 import random diceLowerLimit = 1 diceUpperLimit = 6 def diceThrow(): diceResult = random.randint(diceLowerLimit,diceUpperLimit) print("You threw:",diceResult,".") diceAnotherThrow = input("Do you wish to throw again?\n") if diceAnotherThrow == "yes" or diceAnotherThrow == "y": diceThrow() else: exit() diceThrow()
c1bde90ee255a8cb67c722deed6225f93762e8ac
marb61a/Course-Notes
/Artificial Intellingence/Python/Notebooks/PyImageSearch University/OpenCV 104/simple_equalization.py
1,049
3.671875
4
# USAGE # python simple_equalization.py --image images/moon.png # This uses the cv2.equalizeHist function # It applies equalisation globally across the entire image rather than # piecemeal which is the approach that the adaptive equalisation takes. # This can lead to washout effects in an image if there is a bright light # source # import the necessary packages import argparse import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", type=str, required=True, help="path to the input image") args = vars(ap.parse_args()) # load the input image from disk and convert it to grayscale print("[INFO] loading input image...") image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # apply histogram equalization print("[INFO] performing histogram equalization...") equalized = cv2.equalizeHist(gray) # show the original grayscale image and equalized image cv2.imshow("Input", gray) cv2.imshow("Histogram Equalization", equalized) cv2.waitKey(0)
ed88d9018d8e401bdfffa51174fa1a578df63229
prabhatse/ds-algo-practice
/data_structure/heap.py
5,351
3.53125
4
from __future__ import division import sys """ Array LinkedList Space O(n) O(n) Get Min/Max O(1) O(1) Dequeue O(1) O(1) Size O(1) O(1) """ class MinHeap(object): def __init__(self, capacity): self.array = [float('inf')]*capacity self.capacity = capacity self.heap_size = 0 def __len__(self): return len(self.array) def swap(self, l, r): self.array[l], self.array[r] = self.array[r], self.array[l] def left_child(self, index): return (2*index + 1) def right_child(self, index): return (2*index + 2) def parent(self, index): return (index -1) // 2 def min_heapify(self, index): smallest = index left = self.left_child(index) right = self.right_child(index) if left < self.heap_size and self.array[left] < self.array[index]: smallest = left if right < self.heap_size and self.array[right] < self.array[smallest]: smallest = right if smallest != index: # Swapping smallest and index values self.swap(smallest, index) self.min_heapify(smallest) def get_mini(self): if self.heap_size: return self.array[0] return None def extract_min(self): if not self.heap_size: return None if len(self.array) == 1: self.heap_size -= 1 return self.array[0] minimum = self.array[0] # Move the last element to the root self.array[0] = self.array[self.heap_size - 1] self.heap_size -= 1 self.min_heapify(index=0) return minimum def decrease_key(self, index, key): self.array[index] = key self._bubble_up(index) def insert_key(self, key): if key is None: return TypeError('key cannot be None') self.array[self.heap_size] = value self.heap_size += 1 self._bubble_up(self.heap_size - 1) def delete_key(self, index): self.decrease_key(index, -1*float('inf')) self.extract_min() def peek_min(self): return self.array[0] if self.array else None def _bubble_up(self, index): if index == 0: return index_parent = self.parent(index) if self.array[index] < self.array[index_parent]: # Swap the indices and recurse self.swap(index, index_parent) self._bubble_up(index_parent) class MaxHeap(object): def __init__(self, capacity): self.array = [-1*float('inf')]*capacity self.capacity = capacity self.heap_size = 0 def __len__(self): return len(self.array) def swap(self, l, r): self.array[l], self.array[r] = self.array[r], self.array[l] def left_child(self, index): return (2*index + 1) def right_child(self, index): return (2*index + 2) def parent(self, index): return (index -1) // 2 def max_heapify(self, index): largest = index left = self.left_child(index) right = self.right_child(index) if left < self.heap_size and self.array[left] > self.array[index]: largest = left if right < self.heap_size and self.array[right] > self.array[largest]: largest = right if largest != index: # Swapping smallest and index values self.swap(largest, index) self.max_heapify(largest) def get_max(self): if self.heap_size: return self.array[0] return None def extract_max(self): if not self.heap_size: return None if len(self.array) == 1: self.heap_size -= 1 return self.array[0] minimum = self.array[0] # Move the last element to the root self.array[0] = self.array[self.heap_size - 1] self.heap_size -= 1 self.max_heapify(index=0) return minimum def decrease_key(self,index , key): self.array[index] = key self._bubble_up(index) def insert_key(self, key): if key is None: return TypeError('key cannot be None') self.array[self.heap_size] = value self.heap_size += 1 self._bubble_up(self.heap_size - 1) def delete_key(self, index): self.decrease_key(index, 1*float('inf')) self.extract_max() def peek_min(self): return self.array[0] if self.array else None def _bubble_up(self, index): if index == 0: return index_parent = self.parent(index) if self.array[index] > self.array[index_parent]: # Swap the indices and recurse self.swap(index, index_parent) self._bubble_up(index_parent) def _build_max_heap(self): if not self.heap_size: return None start = (self.heap_size -2) // 2 for i in range(start, -1, -1): self.max_heapify(i) def heap_sort(self): self._build_max_heap() while self.heap_size > 1: self.swap(0, self.heap_size - 1) self.heap_size -= 1 self.max_heapify(0) return self.array
09453e8452699000f20810b3618d762423cc7f6c
mradu97/python-programmes
/primRecur.py
299
3.8125
4
pr = 0 i =2 def prime_rec(n): global pr global i if (n % i) == 0: pr=1 i = i +1 if n > i: prime_rec(n) if pr==0: print("no is prime") else: print("no is not prime") j = int(input("Enter some number")) prime_rec(j)
b7c60fcf76fbab9d4627120ba680f7a9b0d4a0cd
oguh43/bilicka
/ulohy_2.py
2,692
3.578125
4
import re import sys import time from random import randint from itertools import permutations def ask(): x = str(input("\n1) Pankrac\n2) Tajna sprava\n3) Sedi mucha na stene\n4) Alergia\n5) Rigorozka\n6) Statisticky urad\nPre ukoncenie stlacte ENTER\n>")) if x == "1": pankrac() elif x == "2": tajna() elif x == "3": mucha() elif x == "4": alergia() elif x == "5": rigorozka() elif x == "6": statistika() elif x == "": sys.exit() else: print(x,"is not a valid character, please try again") ask() def pankrac(): y = str(input("Veta?\n>")).split(" ") ls = [] ls1 = [] nn = 0 for i in range(0, len(y)): if y[i].istitle() == True: ls.append(y[i].swapcase()) elif y[i].isupper() == True: sp = list(y[i]) for n in sp: if nn == 0: ls1.append(n.swapcase()) nn = nn + 1 else: ls1.append(n) ls.append("".join(ls1)) else: ls.append(y[i]) print(" ".join(ls)) print(" ".join([word[0].lower()+word[1:].upper() if word[0].isupper() else word for word in input("Sentence?\n>>> ").split(" ")])) time.sleep(1) ask() def tajna(): x = list(str(input("Veta?\n>"))) count = -1 popls = [] for i in x: count = count + 1 if i == " ": popls.append(count) plusindex = 0 for i in popls: x.pop(i + plusindex) plusindex = plusindex-1 append_num = len(popls) for i in range(0,append_num): x.insert(randint(1,len(x)-1)," ") print("".join(x)) time.sleep(1) ask() def mucha(): p = str(input("Pismeno?\n>")) x = list(str(input("Veta?\n>"))) for i in x: if i == "a" or i == "e" or i == "i" or i == "o" or i == "u": print(p, end = "") elif i == "A" or i == "E" or i == "I" or i == "O" or i == "U": print(p.upper(), end = "") else: print(i, end = "") time.sleep(1) ask() def alergia(): a = list(str(input("Veta?\n>"))) for n in a: if n.isalpha() == True or n == " ": print(n, end = "") time.sleep(1) ask() def rigorozka(): x = permutations(str(input("Text?\n>")).split(" ")) for i in x: print(" ".join(i)) time.sleep(1) ask() def statistika(): text = str(input("Veta?\n>")).upper() letters = {} for i in re.findall(r"\w", text): if i not in letters: letters[i] = 1 else: letters[i] += 1 SortedByCount = dict(sorted(letters.items(), key = lambda x: x[1], reverse = True)) print(" ".join(SortedByCount.keys())) time.sleep(1) ask() ask()
b1661445ad9ed61b3a2f93a67628e430ed58d877
IBMStreams/streamsx.health
/loinc_generate.py
1,236
3.625
4
import argparse parser = argparse.ArgumentParser() parser.add_argument("--start", type=int) parser.add_argument("--num", type=int) parser.add_argument("--noX", action="count") args = parser.parse_args() start = args.start num = args.num noX = args.noX def nextTen(n): if (n % 10): n = n + (10 - n % 10) return n def addChecksum(code): codeStr = str(code) # 1. convert code to character array and reverse to assign positions codeArr = list(codeStr)[::-1] # 2. get the odd numbered values and convert to integer odd = int("".join(codeArr[0::2])) # 3. multiply by 2 mult = odd*2 # 4. Take the even digit positions even = int("".join(codeArr[1::2])) # 5. Append the even value to the front of the value in #3 app = str(even) + str(mult) # 6. Add the digits together appArr = list(str(app)) sum = 0 for x in appArr: sum += int(x) # 7. Find next multiple of 10 multTen = nextTen(sum) cksum = multTen - sum return str(code) + "-" + str(cksum) # main program codes = [] for i in range(start, start+num): code = addChecksum(i) if noX == None: code = "X" + code codes.append(code) for c in codes: print(c)
46ba09f1fc08b0bd6ce77a1003a3ad4de1dca71d
blankd/hacker-rank
/python/src/blankd/hackerrank/python/str/yourname.py
345
3.625
4
''' Created on Jun 11, 2017 @author: blankd https://www.hackerrank.com/challenges/whats-your-name ''' #No need to one line this in a file def print_full_name(fname, lname): strTemplate = "Hello %s %s! You just delved into python." print strTemplate % (fname, lname) if __name__ == '__main__': print_full_name(raw_input(), raw_input())
8dab84e5c295bb1ae8670e07ef84a12a8b9b9cb3
Emmanuel102/Program_Assignment
/firstpractice.py
425
3.546875
4
from typing import ForwardRef print("Hello World!!!") # step 1 name = 'LeBron' # string age = 35 salary = 37.44 # float plays_basketball = True #boolean jersey_number = '23' # string # step 2 car_name = 'ford' x = 50 my_first_name = 'Kurowei' print(type(name)) print(type(age)) print(type(salary)) print(type(plays_basketball)) print(type(jersey_number)) print(type(car_name)) print(type(x)) print(type(my_first_name))
6480d550a68b7286bb13ff363ecfa3bbc9a37a3b
bucioluis/python-exercises
/leap_year.py
676
4.3125
4
################################################################################ # This program calculates the leap year from given year ################################################################################ year = int(input("Please input a year: ")) # message = " " #if year > 0: # divisible by 100 if year % 100 == 0: if year % 400 == 0: # iff also divisible by 400 days = "29" else: days = "28" else: # not divisible by 100 but iff divisible by 4 if year % 4 == 0: days = "29" else: days = "28" print(f"In the year {year}, there are {days} days in February.") #message += " days in February."
4ef9f46d7b327b2f6425d8ad3465e76b6e187c3a
tomheon/hazardchamber
/parse.py
2,724
3.546875
4
""" Parsing (and unparsing) boards, teams, games, etc. """ from pyparsing import Keyword, Word, nums, Or, Optional, Group import board from constants import BOARD_SIDE import tiles def create_board_parser(side): Edge = Keyword('|') Yellow = Keyword('Y') Blue = Keyword('BL') Black = Keyword('BK') Purple = Keyword('P') Red = Keyword('R') Green = Keyword('G') Color = Or([Yellow, Blue, Black, Purple, Red, Green]) Direction = Or([Keyword('>'), Keyword('<')]) Strength = Word(nums) Strike = Keyword('S') + Direction + Strength Attack = Keyword('A') + Direction + Strength Protect = Keyword('P') + Direction + Strength TurnsLeft = Word(nums) Countdown = Keyword('CD') + TurnsLeft Special = Or([Strike, Attack, Protect, Countdown]) Colored = Color + Optional(Special) Teamup = Keyword('T') Critical = Keyword('C') Empty = Keyword('E') Uncolored = Or([Teamup, Critical, Empty]) Square = Group(Optional(Or([Colored, Uncolored]), default='*') + Edge) Row = Group(Edge + (Square * side)) Board = Row * side return Board STANDARD_BOARD_PARSER = create_board_parser(BOARD_SIDE) def strip_pipes(sq): return [c for c in sq if c != '|'] def to_tile(s): if len(s) == 1: t = s[0] if t == '*': return tiles.NullTile() elif t == 'C': return tiles.CriticalTile() elif t == 'T': return tiles.TeamupTile() elif t == 'E': return tiles.EmptyTile() else: return tiles.ColoredTile(color=t) else: sub = s[1] if sub == 'P': return tiles.ProtectTile(color=s[0], strength=s[3], direction=s[2]) elif sub == 'A': return tiles.AttackTile(color=s[0], strength=s[3], direction=s[2]) elif sub == 'S': return tiles.StrikeTile(color=s[0], strength=s[3], direction=s[2]) elif sub == 'CD': return tiles.CountdownTile(color=s[0], turns_left=s[2]) else: raise Exception("Bad subtype: %s" % s) return s def parse_row(row): stripped = [strip_pipes(s) for s in row if s != '|'] return [to_tile(s) for s in stripped] def parse_board(s_board, parser=STANDARD_BOARD_PARSER): rows = parser.parseString(s_board) return board.Board([parse_row(row) for row in rows]) def unparse_board(board): return str(board)
5881ae193e053921dbd7eea8dee68d34747296d2
janaalbinali/python-foundations
/age_calculator.py
1,080
4.1875
4
from datetime import datetime def check_birthdate(year,month,day): today = datetime(2020,1,26) birthdate = datetime(year, month, day) if today > birthdate: return True return False def calculate_age(year,month,day): today = datetime(2020,1,26) birthdate = datetime(year,month,day) user_age = int((today-birthdate).days /365) print("You are %d years old" %(user_age)) year = int(input("Enter year of birth")) month = int (input("Enter month of birth")) day = int (input("Enter day of birth")) if check_birthdate (int(year), int(month), int(day)) == True calculate_age(int(year,), int(month), int(day)) else print("Input is invalid") person = { "name": "Khalid", "age": 24, "gpa": 3.6, "hobbies": ["Swimming", "Gyming"], "employed": True } for key in person: print("This person's %s is %s" %(key, person[key])) person2 = { "name": "Khalid": "age":24: "gpa":4 "hobbies": ["Football", "DOH", "Desserts"], "employed": True } print(person['hobbies']) people = [person, person2]
307fcb97686a26689864a2b78635d63dce1e0d5b
supercym/python_leetcode
/070_Climbing_Stairs.py
572
3.53125
4
# Author: cym def climbStairs(n): """ :type n: int :rtype: int """ # ********* Low Efficient ************* # if n > 2: # total = climbStairs(n-1) + climbStairs(n-2) # elif n == 2: # return 2 # else: # return 1 # return total # ********* High Efficient ************* d = {1: 1, 2: 2, 3: 3} if n < 4: return d[n] m = 4 while m <= n: d[m] = d[m-1] + d[m-2] m += 1 return d[n] if __name__ == "__main__": print(climbStairs(35))
802b88ffa28463f47221ef6b7d75f5c9837e73a6
Shreyash-A/ComputerProjectES102
/HandCricket.py
1,504
4.1875
4
import random #printing game rules print(" Welcome") print("Lets play Hand Cricket") print("Winning Rules are as follows:") print("You need to enter runs from 1 to 6 \n Then computer will choose a random number \n Whose number is greater WINS \n If both are equal you are out " ) name = input("Enter your name:") #taking user input while True: print("Your choice \n 1. 1 \n 2. 2 \n 3. 3 \n 4. 4 \n 5. 5 \n 6. 6 \n ") userinput = int(input("Your turn: ")) while userinput > 6 or userinput < 1: userinput= int(input("Please enter valid number :")) userinput = str(userinput) print("Your choice: " + userinput) print("\nNow computer's turn") #taking computer choice compChoice = random.randint(1, 6) compChoice = str(compChoice) print("Computer choice is: " + compChoice) print(userinput + " V/s " + compChoice) compChoice = int(compChoice) userinput = int(userinput) #deciding winner if compChoice >= userinput : print(" Computer Wins") print("Do you want to play again? (Y/N)") ans = input() if ans == 'n' or ans == 'N': break #declaring winner and asking to play again else: print(name, "WIN CONGRATULATIONS") print("Do you want to play again? (Y/N)") ans = input() if ans == 'n' or ans == 'N': break print("\nThanks for playing")
701334cb6b276b23efd1076ebbdd00a0aa9d8012
dkokonkwo/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
361
4.375
4
#!/usr/bin/python3 """defines function to print square""" def print_square(size): """prints square of given size with '#' character""" if type(size) is not int: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") for row in range(size): print("#"*size, end="") print()
c818bbdc1abc018887c1c37be214d85349b980b4
gjwei/leetcode-python
/easy/RemoveDuplicatesfromSortedArray.py
507
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created by gjwei on 2017/2/21 """ class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 2: return len(nums) id = 1 for i in range(1, len(nums)): if nums[i] != nums[i - 1]: nums[id] = nums[i] id += 1 return id S = Solution() print(S.removeDuplicates([1, 2, 3, 3]))
7234fa3d267a83769f4cdd82d6cb1b85b0d6461c
ic3top/KPI-labs
/Python-Gui-Labs/Sem_1/CPC_3/Task_7.py
77
3.640625
4
res = 0 for num in range(0, -21, -2): res += num print(f'Result: {res}')
3ed74909480b4fbe016cbad311f3e732dadc9cf0
vaibhavkrishna-bhosle/DataCamp-Data_Scientist_with_python
/25-Machine Learning with Tree-Based Models in Python/Classification and Regression Trees/Linear regression vs regression tree¶.py
819
3.796875
4
''' Linear regression vs regression tree In this exercise, you'll compare the test set RMSE of dt to that achieved by a linear regression model. We have already instantiated a linear regression model lr and trained it on the same dataset as dt. The features matrix X_test, the array of labels y_test, the trained linear regression model lr, mean_squared_error function which was imported under the alias MSE and rmse_dt from the previous exercise are available in your workspace. ''' # Predict test set labels y_pred_lr = lr.predict(X_test) # Compute mse_lr mse_lr = MSE(y_test, y_pred_lr) # Compute rmse_lr import numpy as np rmse_lr = np.sqrt(mse_lr) # Print rmse_lr print('Linear Regression test set RMSE: {:.2f}'.format(rmse_lr)) # Print rmse_dt print('Regression Tree test set RMSE: {:.2f}'.format(rmse_dt))
f042bb02db6b4840ffef61b3a9cd66e31c11e755
edencheng/NSD_Python
/07_file-access_activity.py
400
4.0625
4
file = open("devices.txt","a") #allow to append a item to the file while True: newItem = input("Please Enter the New Devices: ") if newItem == "exit": print("All done!") break file.write(newItem+"\n") file.close() device_list = [] file = open("devices.txt","r") for item in file: device_list.append(item) print(device_list) file.close()
0326fde6a63e57fa035dd04afe0f4f27a1e75c39
ethan-haynes/coding-problems
/python/src/mm.py
313
3.53125
4
def mm(n, m1, m2, m): for i in range(0,n): for j in range(0,n): val = 0 for k in range(0,n): val += m1[i][k] * m2[k][j] m[i][j] = val return m n=2 print(mm( n, [[1,3],[4,2]], [[1,3],[2,1]], [x[:] for x in [[0] * n] * n] ) )
dbf70672adb72124b417cb57742b5ce4c7f1cc67
robinwettstaedt/codewars-kata
/7KYU/count_vowels.py
315
3.84375
4
""" Return the number (count) of vowels in the given string. We will consider a, e, i, o, u as vowels for this Kata (but not y). The input string will only consist of lower case letters and/or spaces. """ def getCount(s): return s.count("a") + s.count("e") + s.count("i") + s.count("o") + s.count("u")
ebc00c6a2d4556677cad9b34ff7eaa4f45c2e0c1
l897284707/index
/继承/__init__.py
962
3.65625
4
# class Amphibian: # name='两栖动物' # def features(self): # print('幼年用鳃呼吸') # print('成年用肺兼皮肤呼吸') # class Frog(Amphibian): # def attr(self): # print(f'青蛙是{self.name}') # print('我会呱呱叫') # frog=Frog() # print(frog.name) # frog.features() # frog.attr() # def digui (ar): # if ar==2: # return 1 # else: # return ar*sum(ar-1) # a=digui(20) def gongbei(): nu1=int(input()) nu2=int(input()) if (nu1>nu2): max=nu1 while True: if max%nu1==0 and max%nu2==0: print('为%d'%max) break else: max+=1 elif nu2>nu1: max=nu2 while True: if max%nu1==0 and max%nu2==0: print('为%d'%max) break else: max+=1 else: return '最小公倍数为%d'%nu1 a=gongbei()
0daaca97e67258d2ada9fbb56d88b0491c446aff
bu3nAmigue/livecoding-tools
/Troop/src/message.py
9,016
3.546875
4
""" Server/message.py ----------------- Messages are sent as a series of arguments surrounnded by <arrows><like><so>. """ from __future__ import absolute_import import re import inspect import json def escape_chars(s): return s.replace(">", "\>").replace("<", "\<") def unescape_chars(s): return s.replace("\>", ">").replace("\<", "<") class NetworkMessageReader: def __init__(self): self.string = "" self.re_msg = re.compile(r"<(.*?>?)>(?=<|$)", re.DOTALL) def findall(self, string): """ Returns all values in a message as a list """ return self.re_msg.findall(string) def convert_to_json(self, string): """ Un-escapes special characters and converts a string to a json object """ return json.loads(unescape_chars(string)) def feed(self, data): """ Adds text (read from server connection) and returns the complete messages within. Any text un-processed is stored and used the next time `feed` is called. """ # Most data is read from the server, which is bytes in Python3 and str in Python2, so make # sure it is properly decoded to a string. string = data.decode() if type(data) is bytes else data if string == "": raise EmptyMessageError() # Join with any existing text full_message = self.string + string # Identify message tags data = self.findall(full_message) # i is the data, pkg is the list of messages i, pkg = 0, [] # length is the size of the string processed length = 0 while i < len(data): # Find out which message type it is cls = MESSAGE_TYPE[int(data[i])] # This tells us how many following items are arguments of this message j = len(cls.header()) try: # Collect the arguments args = [self.convert_to_json(data[n]) for n in range(i+1, i+j)] msg_id, args = args[0], args[1:] pkg.append(cls(*args)) pkg[-1].set_msg_id(msg_id) # Keep track of how much of the string we have processed length += len(str(pkg[-1])) except IndexError: # If there aren't enough arguments, return what we have so far break except TypeError as e: # Debug info print( cls.__name__, e ) print( string ) i += j # If we process the whole string, reset the stored string self.string = full_message[length:] return pkg class MESSAGE(object): """ Abstract base class """ data = {} keys = [] type = None def __init__(self, src_id, msg_id=0): self.data = {'src_id' : int(src_id), "type" : self.type, "msg_id": msg_id} self.keys = ['type', 'msg_id', 'src_id'] def __str__(self): return "".join([self.format(item) for item in self]) def set_msg_id(self, value): self.data["msg_id"] = int(value) @staticmethod def format(value): return "<{}>".format(escape_chars(json.dumps(value))) def bytes(self): return str(self).encode("utf-8") def raw_string(self): return "<{}>".format(self.type) + "".join(["<{}>".format(repr(item)) for item in self]) def __repr__(self): return str(self) def __len__(self): return len(self.data) def info(self): return self.__class__.__name__ + str(tuple(self)) def __iter__(self): for key in self.keys: yield self.data[key] def dict(self): return self.data def __getitem__(self, key): return self.data[key] def __setitem__(self, key, value): if key not in self.keys: self.keys.append(key) self.data[key] = value def __contains__(self, key): return key in self.data def __eq__(self, other): if isinstance(other, MESSAGE): return self.type == other.type and self.data == other.data else: return False def __ne__(self, other): if isinstance(other, MESSAGE): return self.type != other or self.data != other.data else: return True @staticmethod def compile(*args): return "".join(["<{}>".format(json.dumps(item)) for item in args]) @staticmethod def password(password): return MESSAGE.compile(-1, -1, password) @classmethod def header(cls): # args = inspect.getargspec(cls.__init__).args # args[0] = 'type' args = ['type', 'msg_id'] + inspect.getargspec(cls.__init__).args[1:] return args # Define types of message class MSG_CONNECT(MESSAGE): type = 1 def __init__(self, src_id, name, hostname, port, dummy=False): MESSAGE.__init__(self, src_id) self['name'] = str(name) self['hostname'] = str(hostname) self['port'] = int(port) self['dummy'] = int(dummy) class MSG_OPERATION(MESSAGE): type = 2 def __init__(self, src_id, operation, revision): MESSAGE.__init__(self, src_id) self["operation"] = [str(item) if not isinstance(item, int) else item for item in operation] self["revision"] = int(revision) class MSG_SET_MARK(MESSAGE): type = 3 def __init__(self, src_id, index, reply=1): MESSAGE.__init__(self, src_id) self['index'] = int(index) self['reply'] = int(reply) class MSG_PASSWORD(MESSAGE): type = 4 def __init__(self, src_id, password, name): MESSAGE.__init__(self, src_id) self['password']=str(password) self['name']=str(name) class MSG_REMOVE(MESSAGE): type = 5 def __init__(self, src_id): MESSAGE.__init__(self, src_id) class MSG_EVALUATE_STRING(MESSAGE): type = 6 def __init__(self, src_id, string, reply=1): MESSAGE.__init__(self, src_id) self['string']=str(string) self['reply']=int(reply) class MSG_EVALUATE_BLOCK(MESSAGE): type = 7 def __init__(self, src_id, start, end, reply=1): MESSAGE.__init__(self, src_id) self['start']=int(start) self['end']=int(end) self['reply']=int(reply) class MSG_GET_ALL(MESSAGE): type = 8 def __init__(self, src_id): MESSAGE.__init__(self, src_id) class MSG_SET_ALL(MESSAGE): type = 9 def __init__(self, src_id, document, peer_tag_loc, peer_loc): MESSAGE.__init__(self, src_id) self['document'] = str(document) self["peer_tag_loc"] = peer_tag_loc self["peer_loc"] = peer_loc class MSG_SELECT(MESSAGE): type = 10 def __init__(self, src_id, start, end, reply=1): MESSAGE.__init__(self, src_id) self['start']=int(start) self['end']=int(end) self['reply']=int(reply) class MSG_RESET(MSG_SET_ALL): type = 11 class MSG_KILL(MESSAGE): type = 12 def __init__(self, src_id, string): MESSAGE.__init__(self, src_id) self['string']=str(string) class MSG_CONNECT_ACK(MESSAGE): type = 13 def __init__(self, src_id, reply=0): MESSAGE.__init__(self, src_id) self["reply"] = reply class MSG_REQUEST_ACK(MESSAGE): type = 14 def __init__(self, src_id, flag, reply=0): MESSAGE.__init__(self, src_id) self['flag'] = int(flag) self["reply"] = reply class MSG_CONSTRAINT(MESSAGE): type = 15 def __init__(self, src_id, constraint_id): MESSAGE.__init__(self, src_id) self['constraint_id'] = int(constraint_id) # self.peer_id = int(peer) # class MSG_CONSOLE(MESSAGE): type = 16 def __init__(self, src_id, string): MESSAGE.__init__(self, src_id) self['string'] = str(string) # Create a dictionary of message type to message class MESSAGE_TYPE = {msg.type : msg for msg in [ MSG_CONNECT, MSG_OPERATION, MSG_SET_ALL, MSG_GET_ALL, MSG_SET_MARK, MSG_SELECT, MSG_REMOVE, MSG_PASSWORD, MSG_KILL, MSG_EVALUATE_BLOCK, MSG_EVALUATE_STRING, MSG_RESET, MSG_CONNECT_ACK, MSG_REQUEST_ACK, MSG_CONSTRAINT, MSG_CONSOLE, ] } # Exceptions class EmptyMessageError(Exception): def __init__(self): self.value = "Message contained no data" def __str__(self): return repr(self.value) class ConnectionError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class DeadClientError(Exception): def __init__(self, name): self.name = name def __str__(self): return "DeadClientError: Could not connect to {}".format(self.name) if __name__ == "__main__": msg = MSG_SET_MARK(42, 24) print(msg,) print(msg.header())
0c2a50402a21ee30d52bd854a4eaeed47ed4a52e
RyanCirincione/BrainInspiredComputingRepo
/Assignment2/LineDetector.py
383
3.546875
4
import math def createLine(degrees): angle = degrees * math.pi / 180 matrix = [] for i in range(11): matrix.append([0] * 11) x = 0.0 y = 0.0 while x < 6 and y < 6 and x > -6 and y > -6: matrix[5 + int(y)][5 + int(x)] = 1 matrix[5 - int(y)][5 - int(x)] = 1 x += math.cos(angle) y += math.sin(angle) return matrix
39fd982f7c634e06095443356961580d29cd8475
sungminoh/algorithms
/leetcode/solved/679_24_Game/solution.py
2,828
3.9375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 sungminoh <smoh2044@gmail.com> # # Distributed under terms of the MIT license. """ You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. You are restricted with the following rules: The division operator '/' represents real division, not integer division. For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12. Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator. For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed. You cannot concatenate numbers together For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid. Return true if you can get such expression that evaluates to 24, and false otherwise. Example 1: Input: cards = [4,1,8,7] Output: true Explanation: (8-4) * (7-1) = 24 Example 2: Input: cards = [1,2,1,2] Output: false Constraints: cards.length == 4 1 <= cards[i] <= 9 """ import math from functools import lru_cache from typing import List import pytest import sys class Solution: def judgePoint24(self, cards: List[int]) -> bool: def split(arr, n): if n == 0: yield tuple(), arr else: visited = set() for i in range(len(arr)): one = arr[i] rest = arr[:i] + arr[i+1:] for l1, l2 in split(rest, n-1): r1, r2 = sorted((*l1, one)), sorted(l2) k = (tuple(r1), tuple(r2)) if k not in visited: visited.add(k) yield k def make(nums): if len(nums) == 1: yield nums[0] else: for i in range(1, len(nums)//2 + 1): for l1, l2 in split(nums, i): for n1 in make(l1): for n2 in make(l2): yield from (n1+n2, n1-n2, n2-n1, n1*n2) if n2 > 0: yield n1/n2 if n1 > 0: yield n2/n1 return any(math.isclose(x, 24) for x in make(tuple(cards))) @pytest.mark.parametrize('cards, expected', [ ([4,1,8,7], True), ([1,2,1,2], False), ([3,3,8,8], True), ]) def test(cards, expected): assert expected == Solution().judgePoint24(cards) if __name__ == '__main__': sys.exit(pytest.main(["-s", "-v"] + sys.argv))
d1a6cf1b658d460a48d5b05ae64b714ae7386a45
bethmlowe/Python
/avg_sale_calc.py
3,149
4.1875
4
#=============================================================================== #Program: Average Sale Calculator #Programmer: Elizabeth Byrne #Date: June 19, 2021 #Abstract: This program will input a salesperson's name follwed by the # first sale amount then the number of sales as indicated below # for a used car delearship. The program will then display the # sales person's average, highest, and lowest sale. #=============================================================================== #define the main function def main(): #create a variable to control the loop keep_going = 'y' #create a counter for salespersons number_of_salespersons = 0 #process each salesperson's sales while keep_going == 'y' or keep_going == 'Y': #use a function to process each salesperson process_salesperson() number_of_salespersons += 1 #are there more salespersons? keep_going = input('Are there more salespersons? (enter y for yes): ') #display the total number of salespersons print ('There were', number_of_salespersons, 'salespersons processed.') #process each salesperson's sales def process_salesperson(): #get the salesperson's name name = input("What is the salesperson's name? ") print ('Enter', name + "'s amount for first sale: "), first_sale = float(input()) #validate the sale is > 0 and < 25000 while first_sale < 0 or first_sale > 25000: print ("ERROR: the sale cannot be less than 0 or greater than 25000.") first_sale = float(input("Please enter a correct sale amount: ")) #initialize total, lowest, and highest sale to first sale total_sales = first_sale lowest_sale = first_sale highest_sale = first_sale #get the number of sales for this salesperson print ('How many sales does', name, 'have?') number_of_sales = int(input()) for number in range(2, number_of_sales + 1): #get the sales amount print ('Enter', name + "'s sale #" + str(number) + ':'), sale = float(input()) #validate the sale is > 0 and < 25000 while sale < 0 or sale > 25000: print ('ERROR: the sale cannot be less than 0 or grater than \ 25000.') sale = float(input("Please enter a correct sales amount: ")) #accumulate the sales total_sales += sale #check for highest sale if sale > highest_sale: highest_sale = sale #check for lowest sale elif sale < lowest_sale: lowest_sale = sale #compute average sale average_sale = float(total_sales) / number_of_sales #display the average, highest, and lowest sale print('') print(name + "'s average sale was: $", format(average_sale, ".2f"), \ sep='') print(name + "'s highest sale was: $", format(highest_sale, ".2f"), \ sep='') print(name + "'s lowest sale was: $", format(lowest_sale, ".2f"), \ sep='') print('') #call the main function main()
fcf86017662e1d4fc65a5942afa4de195f1dce91
rafaelperazzo/programacao-web
/moodledata/vpl_data/168/usersdata/264/76257/submittedfiles/exercicio24.py
182
3.84375
4
# -*- coding: utf-8 -*- import math x= int(input('Digite x:')) y= int(input('Digite y:')) i=1 while (i<=x): if(x%i)==0 and (y%i)==0: MDC=i i=i+1 print (MDC)
f6d33b7ae8931af971ba648e577baefac0fe4aa1
munsangu/20190615python
/START_PYTHON/2日/07.フォーマッティング/02.フォーマッティング.py
845
3.796875
4
#변수를 이용하여 포매팅 가능 num = 3 print("I eat %s cakes"%num) print("\n===2개 이상의 포매팅===") #2개 이상의 포맷문자 %() 괄호로 묶어줍니다. print("I eat %s %s cakes"%(num, "cakes")) print("\n===포매팅을 활용한 정렬===") #%와 s사이에 양수로 적어주시면 그 숫자만큼 공간을 확보하고 우측정렬 print("%10s%5s"%("name","age")) print("=" * 20) print("%10s%5s"%("jinwoo","30")) print("%10s%5s"%("donyu1","30")) print("%10s%5s"%("bomin","22")) print("=" * 20) print("%-10s%-5s"%("jinwoo","30")) print("%-10s%-5s"%("donyu1","30")) print("%-10s%-5s"%("bomin","22")) print("\n===포매팅을 활용한 소수점 표현===") #%.2f : 소수점 2자리까지 표시 # 자료형을 모를땐 전부 %s => 단 소수점 표현빼고는... a = 3.141592 print("%.2f"%a) print("%.2s"%a)
5154db2044902741379c967525ef6d5128f42635
pedrohbraz/python_codes
/imposto.py
210
3.984375
4
salario = int(input('Salario? ')) imposto = input('Imposto em % (ex:27.5)? ') if not imposto: imposto = 27.5 else: imposto = float(imposto) print("valor: {} ".format(salario - (salario * (imposto * 0.01))))
8e20afba2037a7a0110a911064713a73ad1fffac
Arpit599/Data-Structures-with-Python
/Arrays/Basic/invPermutation.py
410
3.8125
4
def inversePermutation (arr, n) : arr1 = [0] * n for i in range(n): arr1[arr[i] - 1] = i + 1 return arr1 # Driver Code Starts for tc in range(0, int(input("Enter the number of test cases: "))): n = int(input("Enter n: ")) arr = list(map(int, input("Enter the array: ").strip().split())) ans = inversePermutation(arr, n) print("The inverse permutation is", *ans)
be9d9d36faba6dca13247b7faa657c2e09ae6e48
shubgene/AdditionalExercise3
/cone_area.py
680
4
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 21 21:48:53 2018 @author: shurastogi """ class Cone: def __init__(self,radius,height): self.radius=radius self.height=height def area_of_cone(self): pi=3.14159265 area=float(pi*self.radius*(self.radius+((self.height**2+self.radius**2)**(1/2.0)))) print("Area of cone with radius: {} and height: {} is : {}".format(self.radius,self.height,area)) radius_input=float(input("Please enter the radius of the cone:")) height_input=float(input("Please enter the height of the cone:")) cone_object=Cone(radius_input,height_input) cone_object.area_of_cone()
b1023fb0da0e81206f2f1dec8bbba32fb3229d64
katarinarosiak/python_fundamentals
/excercises/fundamentals/lettercase_counter.py
1,238
4.5
4
# Lettercase Counter # Write a method that takes a string, and then returns a hash that contains 3 entries: one represents the number of characters in the string that are lowercase letters, one the number of characters that are uppercase letters, and one the number of characters that are neither. import string def is_letter(letter): alpha = list(string.ascii_lowercase + string.ascii_uppercase) return letter in alpha def letter_case_count(str_of_letters): counted_letters = {"lowercase": 0, "uppercase": 0, "neither": 0} for letter in list(str_of_letters): if letter.upper() == letter and is_letter(letter): counted_letters["uppercase"] += 1 elif letter.lower() == letter and is_letter(letter): counted_letters["lowercase"] += 1 else: counted_letters["neither"] += 1 return counted_letters # Examples # Copy Code print(letter_case_count("abCdef 123")) # == { lowercase: 5, uppercase: 1, neither: 4 } print(letter_case_count("AbCd +Ef")) # == { lowercase: 3, uppercase: 3, neither: 2 } print(letter_case_count("123")) # == { lowercase: 0, uppercase: 0, neither: 3 } print(letter_case_count("")) # == { lowercase: 0, uppercase: 0, neither: 0 }
ef04eced5e56c77913c2017619879206c76279a1
Malar86/python-programming-problems
/pg3.py
179
3.8125
4
import random n=5 while n>0: a=int(input("enter a number")) b=random.randrange(0,5) if(a==b): print("you won") break else: print("you lost")
eb2df8c0db09badb3e77d511ec3e623b642b90b3
dhk1349/Algorithm
/Algorithm Assignment/dp_binomial coefficient.py
710
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 8 16:52:46 2020 @author: dhk13 """ def bin(n,k): #n, k represents nCk #Dvide and conquer using the concept of Pascal's triangle. if(k==0 or n==k): return 1 else: return bin(n-1, k-1)+bin(n-1, k) def bin2(n,k): #Tihs function adopted dynamic programming. #Uses the concept of Pascals's triangle. result=[[None]*(k+1) for i in range(n+1)] for i in range(n+1): for j in range(min(k,i)+1): if(j==0 or j==i): result[i][j]=1 else: result[i][j]=result[i-1][j-1]+result[i-1][j] return result[i][j] print(bin(10,5), bin2(10,5))
cdf81dda4136b48d7c9cc9cab2f391469eff7f9d
x43s3y/circle_motion
/drawCircle.py
531
4
4
import turtle turtle.colormode(255) window = turtle.Screen() window.title("circle motion") window.bgcolor("pink") red,green,blue = 100,255,0 draw = turtle.Turtle() draw.color(red,green,blue) radius = 150 for i in range(12): try: draw.circle(radius) draw.penup() draw.setposition(i*0, 10) draw.left(30) draw.pendown() green = green - 20 blue = blue + 20 draw.color(red,green,blue) turtle except Exception as e: print(e) window.mainloop()
3e5b4f931d137f51c6d856b1e86efa6302ee5970
Auto-SK/Sorting-Algorithms
/bucket_sort.py
803
3.796875
4
# -*- coding: utf-8 -*- """ @project: Sorting-Algorithms @version: v1.0.0 @file: bucket_sort.py @brief: Bucket Sort @software: PyCharm @author: Kai Sun @email: autosunkai@gmail.com @date: 2021/8/5 14:15 @updated: 2021/8/5 14:15 """ def bucket_sort(arr): min_val = min(arr) max_val = max(arr) res = [] # 桶的初始化 bucket_size = 5 # 桶的大小 bucket_count = (max_val - min_val) // bucket_size + 1 # 桶的数量 buckets = [[] for _ in range(bucket_count)] # 利用映射函数将数据分配到每个桶中 for a in arr: i = (a - min_val) // bucket_size buckets[i].append(a) for bucket in buckets: bucket.sort() for bucket in buckets: res.extend(bucket) # 从 list 中提取 return res
96ba44d461dbfba684da27736930eb0521f38529
saintograph/codewars-solutions
/isThisATriangle.py
205
4
4
def add(a, b): return a + b def is_triangle(a, b, c): if add(a, b) <= c: return False if add(a, c) <= b: return False if add(c, b) <= a: return False return True
8989fbdab9c326e7149b30a608ffe4be5edbd070
DJBorn/practice
/python/data_structures/linked_list.py
1,338
3.984375
4
class LinkedList: def __init__(self): self.head = None self.tail = None def print_list(self): output = "" cur_node = self.head while cur_node is not None: output += f"{cur_node['value']} " cur_node = cur_node["next"] print(output) def add_value(self, value): if self.head is None: self.head = self._create_node(value) self.tail = self.head else: self.tail["next"] = self._create_node(value) self.tail = self.tail["next"] def remove_value(self, value): while self.head is not None and self.head["value"] == value: self.head = self.head["next"] cur_node = self.head while cur_node is not None: if cur_node["value"] == value: cur_node["value"] = cur_node["next"]["value"] cur_node["next"] = cur_node["next"]["next"] continue cur_node = cur_node["next"] def _create_node(self, value): return {"value": value, "next": None} my_list = LinkedList() my_list.print_list() my_list.add_value(2) my_list.add_value(2) my_list.add_value(1) my_list.add_value(5) my_list.add_value(2) my_list.add_value(12) my_list.print_list() my_list.remove_value(2) my_list.print_list()
ecb18199f9d45503e9585a723350d3d8c01c1d03
foqiao/A01027086_1510
/midterm_review/most_vowels.py
899
4.21875
4
def most_vowels(tuple): vowel_in_tuple = [] vowel_rank = set() vowel_amount = 0 tuple_of_string = range(0, len(tuple)) for i in tuple_of_string: if tuple[i] == ',': vowel_in_tuple.append(" ") if tuple[i] == 'a': vowel_in_tuple.append(tuple[i]) if tuple[i] == 'e': vowel_in_tuple.append(tuple[i]) if tuple[i] == 'i': vowel_in_tuple.append(tuple[i]) if tuple[i] == 'o': vowel_in_tuple.append(tuple[i]) if tuple[i] == 'u': vowel_in_tuple.append(tuple[i]) for j in range(0, len(vowel_in_tuple)): if vowel_in_tuple[j] != " ": vowel_amount += 1 if vowel_in_tuple[j] == " ": vowel_rank.add(vowel_amount) tuple_input = tuple(input("Please enter a combination of strings(must separated by comma): ")) most_vowels(tuple_input)
189a1be81821808a6024417757cdd8ccc238cc39
gjq91459/mycourse
/Scientific Python/matplotlib/subplots/3_subplots.py
1,118
3.734375
4
import matplotlib.pyplot as plt # plot multiple subplots within one figure def plotSomeExtraData(axes): for i in range(0,8): axes[i].plot([50, 75, 100]) def plotSomeData(axes): for i in range(0,8): axes[i].plot([4, 9, 16, 25, i**2]) def setCustomAxis(fig): left = 0.15 bottom = 0.1 width = 0.3 height = 0.1 ax7 = fig.add_axes([left, bottom, width, height]) return ax7 def setDefaultAxes(fig): rows = 4 columns = 2 ax1 = fig.add_subplot(rows, columns, 1) # first plot ax2 = fig.add_subplot(rows, columns, 2) # second plot ax3 = fig.add_subplot(rows, columns, 3) # third plot ax4 = fig.add_subplot(rows, columns, 4) # etc ax5 = fig.add_subplot(rows, columns, 5) ax6 = fig.add_subplot(rows, columns, 6) ax8 = fig.add_subplot(rows, columns, 8) return ax1, ax2, ax3, ax4, ax5, ax6, ax8 def main(): fig = plt.figure() ax1, ax2, ax3, ax4, ax5, ax6, ax8 = setDefaultAxes(fig) ax7 = setCustomAxis(fig) axes = [ax1,ax2,ax3,ax4,ax5,ax6,ax7,ax8] plotSomeData(axes) plotSomeExtraData(axes) plt.show() main()
e422554deab94dc0b4cbd8259b19d2efddecfe2b
KronosOceanus/python
/Tk多窗口/myWindow.py
766
3.78125
4
# 窗口类 import tkinter as tk from tkinter import messagebox class myWindow: def __init__(self,root,myTitle,flag): # 创建窗口 self.top=tk.Toplevel(root,width=300,height=200) # 设置窗口标题 self.top.title(myTitle) # 顶端显示 self.top.attributes('-topmost',1) # 根据不同情况放置不同组件 if flag==1: label=tk.Label(self.top,text=myTitle) label.place(x=50,y=50) elif flag==2: def buttonOK(): tk.messagebox.showinfo(title='Pthon', message='shit') button=tk.Button(self.top,text=myTitle,command=buttonOK) button.place(x=50,y=50)
fed722f028d28f19296568b77513cdb23190e1e6
saurabhkadam09/Training
/iteration.py
299
3.53125
4
#a=[10,20,30,40] #itr=iter(a) #print(itr.__next__()) class repeat: def __init__(self,m): self.k=1 def __iter__(self): return self def __next__(self): val=self.k self.k=self.k+1 return val b=[11,22,33,44] itr2=repeat(b) print(itr2.__next__())
ab6243933f0ad00f901e0755405659a448bb2af5
asymmetry/leetcode
/0050_implement_pow/solution_1.py
580
3.5625
4
#!/usr/bin/env python3 # O(log(n)) class Solution: def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 elif n == -1: return 1 / x else: val = self.myPow(x, n // 2) if n % 2 == 0: return val * val else: return x * val * val if __name__ == '__main__': print(Solution().myPow(2.00000, 10)) print(Solution().myPow(2.10000, 3)) print(Solution().myPow(2.00000, -2))
e666def88e719e2a02ec97b9852d25c3b0a0fce8
gbhuvneshwar/hypertype
/hypertype.py
7,926
4.09375
4
""" (↑t) - hypertype ~~~~~~~~~~~~~~~~ Haskell inspired type system and pattern matching for Python. """ import inspect class BaseType: """Base class for all types. """ def valid(self, value): raise NotImplementedError() def __or__(self, other): return OneOf([self, other]) class SimpleType(BaseType): """Type class to the simple types like string, integer etc. """ def __init__(self, type_, label=None): self.type_ = type_ self.label = label or str(type_) def valid(self, value): return isinstance(value, self.type_) def __repr__(self): return self.label class AnyType(BaseType): """Type class to match any value. """ def valid(self, value): return True def __repr__(self): return "Any" class Literal(BaseType): """Type class to match a literal value. Plus = Literal("+") print(Plus.valid("+")) # True """ def __init__(self, value, label=None): self.value = value self.label = label def valid(self, value): return self.value == value def __repr__(self): return self.label or "<{}>".format(self.value) class List(BaseType): """Type class to represent a list of values. List is a homogeneous collection and each element of the collection must be of the specified type. Numbers = List(Integer) print(Numbers.valid([1, 2, 3]) # True """ def __init__(self, type_): self.type_ = type_ def valid(self, value): return isinstance(value, list) and all(self.type_.valid(v) for v in value) def __repr__(self): return "List({})".format(self.type_) class Tuple(BaseType): """Tuple represents is a fixed length record. Point = Tuple([Integer, Integer]) Point.valid([1, 2]) # True """ def __init__(self, *types): self.types = types def valid(self, value): return isinstance(value, (list, tuple)) \ and len(value) == len(self.types) \ and all(t.valid(v) for t, v in zip(self.types, value)) def __repr__(self): return "Tuple({})".format(", ".join(str(t) for t in self.types)) class Record(BaseType): """Type class to represent a record with fixed keys. Point = Record({"x": Integer, "y": Integer}) print(Point.valid({"x": 1, "y": 2})) # True """ def __init__(self, schema): self.schema = schema def valid(self, value): return isinstance(value, dict) \ and all(k in value and type_.valid(value[k]) for k, type_ in self.schema.items()) def __repr__(self): return "Record({})".format(self.schema) class Dict(BaseType): """Type class to represent homogeneous key-value pairs. PriceList = Dict(String, Float) PriceList.valid({ "apple": 10.0, "mango": 10.0, }) // True """ def __init__(self, schema): self.schema = schema def valid(self, value): return isinstance(value, dict) \ and all(k in value and type_.valid(value[k]) for k, type_ in self.schema.items()) def __repr__(self): return "Record({})".format(self.schema) class OneOf(BaseType): """Type class to match one of the given types. Value = Integer | List[Integer] print(Value.valid(1)) # True print(Value.valid([1, 2, 3])) # True """ def __init__(self, types): self.types = types def valid(self, value): return any(t.valid(value) for t in self.types) def __or__(self, other): return OneOf(self.types + [other]) def __repr__(self): return " | ".join(str(t) for t in self.types) class Reference(BaseType): """The Reference represents a Forward Reference to a type. When defining types for recursive data structures, it is required to use the type in defining itself. In Python, it wouldn't be possible to it that and way and Reference solves that issues. BinOp = Literal("+") | Literal("*") Expr = Reference() Expr.set( Integer | Record({"left": Expr, "op": BinOp, "right": Expr}) ) print(Expr.valid(1)) # True print(Expr.valid({"left": 1, "op": "+", "right": 2})) # True print(Expr.valid({ "left": 1, "op": "+", "right": { "left": 2, "op": "*", "right": 3 }})) # True """ def __init__(self, label=None): self.type_ = None self.label = label def set(self, type_): self.type_ = type_ def __irshift__(self, type_): self.type_ = type_ return self def valid(self, value): if not self.type_: raise Exception("Undefined Reference: " + self.label or "<Unnamed>") return self.type_.valid(value) def __repr__(self): if self.label: return self.label if self.type_: return repr(self.type_) else: return "Reference()" String = SimpleType(str, label="String") Integer = SimpleType(int, label="Integer") Float = SimpleType(float, label="Float") Boolean = SimpleType(bool, label="Boolean") Nothing = SimpleType(type(None), label="Nothing") Any = AnyType() # It is more natural to call it a Type when declaring it. Type = Reference _methods = {} class MultiMethod: """MultiMethod implements function polymorphism based on the type of the data. See the method decorator for more details. """ def __init__(self, name): self.name = name self._methods = [] self.nargs = -1 def add_method(self, method): specs = inspect.getfullargspec(method) if specs.varargs or specs.varargs or specs.kwonlyargs: raise Exception("hyptertype methods supports only simple arguments. varargs, kwargs etc. are not supported.") if self.nargs >= 0 and self.nargs != len(specs.args): raise Exception( "Method {} is expected to have {} args. Found {}.".format( self.name, self.nargs, len(specs.args))) argtypes = [specs.annotations.get(a, Any) for a in specs.args] t = Tuple(*argtypes) self._methods.append((t, method)) self.nargs = len(specs.args) def __call__(self, *args): if len(args) != self.nargs: raise TypeError( "method {} expects {} args, given {}".format( self.name, self.nargs, len(args))) for t, method in self._methods: valid = t.valid(args) if valid: return method(*args) raise ValueError("Unable to find a matching method for {}".format(self.name)) def __repr__(self): return "Method:{}".format(self.name) def method(f): """Decorator to mark a function as a hypertype method. Hypertype method implements multiple-dispatch or function polymorphism based on the type of the arguments. The types of the arguments are specified using the function annotations. This is some what like the pattern-matching in Haskell as we the types are nothing but the shape of the data. @method def display(n Integer): print(n, "is an integer") @method def display(s String): print(s, "is a string") display(42) # 42 is an integer display("Magic") # Magic is a string """ m = _methods.setdefault(f.__name__, MultiMethod(f.__name__)) m.add_method(f) return m def nested_apply(value, method): if isinstance(value, list): return [method(v) for v in value] elif isinstance(value, dict): return {k: method(v) for k, v in value.items()} else: return method(value)
d07398f56eedc98ecc2d52c58fb0c59370b9b4af
bits2018wilp/python-lab
/src/main/prep/swap_in_pair_list.py
648
3.75
4
from src.main.prep.node import Node def print_ll(h): lst = [] while h: lst.append(h) h = h.next print(lst) head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) tmp = head h2 = head.next prev = None while tmp: #breakpoint() t = tmp.next if t: if not prev: tmp.next = t.next t.next = tmp else: prev.next = t tmp.next = t.next t.next = tmp prev = tmp tmp = tmp.next print(prev) print_ll(h2)
58ebf7e7ca781ce05ccfc44b4fcdc7272c5a2224
basu0001/first-pr-Hacktoberfest--2019
/codes/algorithms/quick_sort/python/quicksort.py
772
3.96875
4
def partition(li, start, end): pivot = li[start] left = start + 1 right = end done = False while not done: while left <= right and li[left] <= pivot: left += 1 while right >= left and li[right] >= pivot: right -= 1 if right < left: done = True else: li[left], li[right] = li[right], li[left] li[start], li[right] = li[right], li[start] return right def quicksort(li, start=0, end=None): if not end: end = len(li) - 1 if start < end: pivot = partition(li, start, end) # Recursively perform same operation on first and last halves of list quicksort(li, start, pivot - 1) quicksort(li, pivot + 1, end) return li
fbb42e2fac5b1e59f82ed2fbe5259e952523baf2
JRYSR/store
/python基础/day07/表格.py
1,490
3.5625
4
import xlrd # 打开文件 wb = xlrd.open_workbook(filename=r"F:\python自动化测试\day07_mysql工具类与excel读取\2020年每个月的销售情况.xlsx") # 确定选项卡 # month = input("请输入月份数字(1-12):") # for month in range(1, 13): # sheet = wb.sheet_by_name("%s月"%(month)) # # 获取表格有多少行,多少列 # rows = sheet.nrows # cols = sheet.ncols # info = "行:%s,列:%s" # print(info%(rows, cols)) # print("行:%s,列:%s"%(rows, cols)) # 获取每一行的数据并打印 sumyear = 0 for month in range(1, 13): sheet = wb.sheet_by_name("%s月"%(month)) rows = sheet.nrows cols = sheet.ncols sum = 0 for i in range(1, rows): income = sheet.row_values(i) sum += income[2] * income[4] sumyear += sum # print("%s月销售总额:¥%s"%(month, round(sum, 2))) print("2020年全年销售总额:¥%s"%round(sumyear, 2)) # 获取每一列的数据并打印 # for i in range(0, cols): # print(sheet.col_values(i)) dic = {"1": 0} dic["1"] = dic["1"] + 12 print(dic) season1 = [2, 3, 4] season2 = [5, 6, 7] season3 = [8, 9, 10] for month6 in range(1, 13): if month6 in season1: print(month6, end="-") elif month6 in season2: print(month6, end="*") elif month6 in season3: print(month6, end="+") else: print(month6, end="/") dic1 = {"1": 1, "2": 2} a = input("请输入键:") b = int(input("请输入值:")) dic1[a] += b print(dic1)
8d87fb42934ea268ed3765186e7b5e886a385c32
sjafernik/Hangman
/hangman_2_WORK.py
7,030
3.9375
4
import random import re import sys import string #from words import word_list from display_hangman import stages from display_hangman_hard import stages_hard def Main(): f=open("countries_capitals.txt", "r") word_list=f.read().replace('\n'," | ").split(" | ") #word_list = open("countries_capitals.txt", "r") f.close() word=random.choice(word_list).lower() player_name=input('You can close the game anytime - just write "quit". \nHello player, What is your name?\n') if player_name == "quit": print('Goodbye') sys.exit(0) player_answer=input(f"Hello {player_name} Do you wanna play in hangman?\n").lower() if player_answer == "quit": print('Goodbye') sys.exit(0) while player_answer != 'yes' and player_answer != 'no': player_answer=input(f"Answer: 'yes' or 'no'. {player_name}, do you wanna play in hangman?\n").lower() if player_answer == 'yes': levels=input("Let's play. Enter your level: (h)ard or (e)asy?\n") if levels == "quit": print('Goodbye') sys.exit(0) while levels != 'h' and levels != 'e': levels=input('Enter your level: (h)ard or (e)asy\n') if levels == 'h': lives = 4 while len(word)<(5): word=random.choice(word_list).lower() Play(word, lives) else: lives=6 while len(word)>=(5): word=random.choice(word_list).lower() Play(word, lives) elif player_answer == "quit": print('Goodbye') sys.exit(0) else: print('Goodbye') def Play(word,lives): i=0 word_guessing_ = [] word_list=list(word) word_length=[] for i in word: if i.isalpha(): word_length.append(i) i='_' word_guessing_.append(i) else: word_guessing_.append(i) word_guessing =''.join(word_guessing_) print(f"The word is {len(word_length)} letters length") print(word_guessing) stages_iterator=iter(stages) stages_hard_iterator=iter(stages_hard) guess=False guessed_letters=[] if lives == 4: while lives>0 and guess == False: char=input('Guess the letter:\n') if char == "quit": print('Goodbye') sys.exit(0) if len(char)==1 and char.isalpha(): if char in guessed_letters: print('You have already guessed this letter ' + char) elif char not in word: print(char, "is not in the word.") lives -= 1 guessed_letters.append(char) print(f"You have {lives} lives") print(next(stages_hard_iterator)) _stage=(stages_hard_iterator) word_guessing=string.capwords(word_guessing, sep=None) print(word_guessing) else: print(f"Good job {char} is in the word!") guessed_letters.append(char) word_as_list = list(word_guessing) indices = [i for i, letter in enumerate(word) if letter == char] for index in indices: word_as_list[index] = char word_guessing = "".join(word_as_list) word_guessing=string.capwords(word_guessing, sep=None) print(word_guessing) if "_" not in word_guessing: print('Great! You guessed the word!') guess = True elif len(char.lower()) == len(word.lower()): #and char.isalpha(): if char.lower() == word.lower(): word=string.capwords(word, sep=None) print(f'Great! You guessed the word {word}!') guess=True else: print('No, You have not guessed the word.') lives-=1 print(f"You have {lives} lives") print(next(stages_hard_iterator)) _stage=(stages_hard_iterator) word_guessing=string.capwords(word_guessing, sep=None) print(word_guessing) elif len(char.lower()) != len(word.lower()): print(f"The word must be {len(word)} letters.") if lives==0: word_guessing=string.capwords(word_guessing, sep=None) print(f'You lose. The word was {word}') elif lives == 6: while lives>0 and guess == False: char=input('Guess the letter:\n').lower() if char == "quit": print('Goodbye') sys.exit(0) if len(char)==1: #and char.isalpha(): if char in guessed_letters: print('You have already guessed this letter ' + char) elif char not in word: print(char, "is not in the word.") lives -= 1 guessed_letters.append(char) print(f"You have {lives} lives") print(next(stages_iterator)) _stage=(stages_hard_iterator) word_guessing=string.capwords(word_guessing, sep=None) print(word_guessing) else: print(f"Good job {char} is in the word!") guessed_letters.append(char) word_as_list = list(word_guessing) indices = [i for i, letter in enumerate(word) if letter == char] for index in indices: word_as_list[index] = char word_guessing = "".join(word_as_list) word_guessing=string.capwords(word_guessing, sep=None) print(word_guessing) if "_" not in word_guessing: print('Great! You guessed the word!') guess = True elif len(char.lower()) == len(word.lower()): #char.isalpha(): if char.lower() == word.lower(): word=string.capwords(word, sep=None) print(f'Great! You guessed the word {word}!') guess=True else: print('No, You have not guessed the word.') lives-=1 print(next(stages_iterator)) _stage=(stages_hard_iterator) word_guessing=string.capwords(word_guessing, sep=None) print(word_guessing) elif len(char.lower()) != len(word.lower()): print(f"The word must be {len(word)} letters.") if lives==0: word=string.capwords(word, sep=None) print(f'You lose. The word was {word}') Main()
4ffeb71eef1e54c60b3104655c0ea862d7fc6a57
ryanthomasdonald/python
/week-1/python-exercises/small-ex10.py
135
3.953125
4
side = int(input("How big is the square? ")) for i in range(side): for i in range(side): print("*", end = " ") print()
b7873a256a1cee54a448db4adecb2afdcd65d87c
Moro-Afriyie/10-Days-Of-Statistics-Hackerrank
/10 Days of Statistics/Poisson Distribution I.py
614
3.84375
4
from math import factorial def poisson(k, mean): ''' poission probability the probability of getting exactly k successes when the average number of success or mean is given :param k: the actual natural number of successes that occur in the specified region :param mean: the average number of successes that occur in the specified region or mean :return: poisson probability ''' e = 2.71828 poisson_probability = ((mean**k)*(e**-mean))/factorial(k) return poisson_probability mean = float(input()) k = int(input()) print('{:.3f}'.format(poisson(k, mean)))
8fb55aa5a1d485826674d521823d9791f6206053
mayankmr2-dev/Python-Interview-Prep
/adjacentproduct.py
365
3.671875
4
# Adjacent Element Product # Lets Suppose # 0 1 2 3 4 # mylist = [1, 2, 3, 4, 5] # Expected Output - 5*4 = 20 # we have to iterate till 4 mylist = list(map(int, input().split(","))) print(mylist) sum = [] for i in range(len(mylist)-1): # range is 4 i.e. 0 1 2 3 sum.append(mylist[i]*mylist[i+1]) largest_element = max(sum) print(largest_element)
06ba0d773ab491371232c49a9d8911b3dc70b02b
nkchangliu/puzzles
/leetcode/target_sum.py
697
3.5
4
def target_sum(lst, s): if len(lst) == 0 and s == 0: return 1 elif len(lst) == 0: return 0 cache = {} cache[lst[0]] = 1 cache[-lst[0]] = 1 if lst[0] == 0: cache[0] = 2 for i in range(1, len(lst)): new_cache = {} for key in cache: new_key = key + lst[i] new_cache[new_key] = cache[key] if new_key not in new_cache else new_cache[new_key] + cache[key] new_key = key - lst[i] new_cache[new_key] = cache[key] if new_key not in new_cache else cache[key] + new_cache[new_key] cache = new_cache return cache[s] if s in cache else 0 print(target_sum([1, 1, 1, 1, 1], 3))
39bb97fe38df161f39d67fd8bb95e02a9c0d1da3
chars32/grupo-python
/semana3/Sem3Eje2+CarlosGarcia.py
533
4.03125
4
#Hacer un metodo que reciba cuatro parametros, y devuelve el primero #por el segundo, el tercero entre el cuarto, y el segundo menos el tercero. #funcionRara(10,5,6,3) #(50,2,-1) def funcionRara(): lista = [] lista2 = [] print "Dame 4 numeros" print "---------------" for x in range(4): numero = input("Dame un numero: ") lista.append(numero) print "" print "tus numeros son:", lista lista2 = [(lista[0] * lista[1]), (lista[2] / lista[3]), (lista[1] - lista[2])] print "el resultado es:", lista2 funcionRara()
24b43bddc911e8934f753805b6986aa269673ff6
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-JamilErasmo
/semana 6/ejercicios-clase-06-1bim-JamilErasmo/ejemplos-while/Ejemplo07.py
484
3.78125
4
suma_total = float(0) contador = 0 bandera = True print("Ingrese las notas de los estudiantes de su materia") while (bandera): calificacion = float(input("Ingrese calificacion: ")) suma_total = suma_total + calificacion contador = contador + 1 temporal = int(input("Ingrese el valor -1 para salir del ciclo: ")) if temporal == -1: bandera = False promedio_final = float (suma_total / contador) print("El promedio final es: %.2f\n"%(promedio_final))
cbaf7d1af5b51850a60aa09c8870f35db863811f
m365462129/AutomatedTesting1
/UIAutomatedTest/04pytest/test_fixtures_02.py
720
3.703125
4
print("-------------------------02") def multiply(a,b): return a * b class TestMultiply: @classmethod def setup_class(cls): print("--setup_class--") @classmethod def teardown_class(cls): print("--teardown_class--") def setup_method(self,method): print("--setup_method--") def teardown_method(self,method): print("--teardown_method--") def setup(self): print("--setup--") def teardown(self): print("--teardown--") def test_numbers_5_6(self): print("--test_numbers_5_6--") assert multiply(5,6) == 30 def test_string_b_2(self): print("--test_string_b_2--") assert multiply("b",2) == "bb"
968307035e279453a183eb05adf8f8e2378bae6b
ucsb-cs8-m18/code-from-class
/08-22/guess_the_number.py
385
4.15625
4
import random up_to = int(input("What number do you want to guess up to? ")) assert(up_to >= 1) number = random.randint(1, up_to) # pick a number from 1 to 100 guess = -1 while guess != number: guess = int(input("Enter your guess: ")) if guess < number: print("Too low") elif guess > number: print("Too high") else: print("You got it!")
66506840d9c9bd6f5145a0018c5490fd22984bdf
deepkumarchaudhary/python-poc
/Prep/passingCars.py
552
3.75
4
#The function should return -1 if the number of pairs of passing cars exceeds 1,000,000,000. ##For example, given: # A[0] = 0 # A[1] = 1 # A[2] = 0 # A[3] = 1 # A[4] = 1 #the function should return 5, as explained above. #(0,1) (0,3) (0,4) (2,3) (2,4) MAX_PAIRS = int(1e9) def solution(A): east = passes = 0 for direction in A: if direction == 0: east += 1 else: passes += east if passes > MAX_PAIRS: return -1 return (passes) pass A = [0, 1, 0, 1, 1] print(solution(A))