blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
da2e163239f8f68490f9d875aee5f84fb7ae70dd
DaviSilva70/Python
/Exercicio_09.py
685
4.3125
4
''' Faça um Programa que leia um numero inteiro qualquer e mostre sua tela a Tabuada ''' Numero = int(input('Digite Para Ver Sua Taboada: ')) print('_'*30) print('{} x {:2} = {}'.format(Numero,1,Numero*1)) print('{} x {:2} = {}'.format(Numero,2,Numero*2)) print('{} x {:2} = {}'.format(Numero,3,Numero*3)) print('{} x {:2} = {}'.format(Numero,4,Numero*4)) print('{} x {:2} = {}'.format(Numero,5,Numero*5)) print('{} x {:2} = {}'.format(Numero,6,Numero*6)) print('{} x {:2} = {}'.format(Numero,7,Numero*7)) print('{} x {:2} = {}'.format(Numero,8,Numero*8)) print('{} x {:2} = {}'.format(Numero,9,Numero*9)) print('{} x {:2} = {}'.format(Numero,10,Numero*10)) print('_'*30)
585d38fc8d5a14492b9f325ce782ac3c670b0aeb
jingxiufenghua/algorithm_homework
/leetcode/leetcode872.py
941
4.09375
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :leetcode872.py @IDE :PyCharm @Author :无名 @Date :2021/5/10 15:42 ''' from typing import List # 872. 叶子相似的树 # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: if not root1 and not root2 : return True if not root1 or not root2 : return False def dfs(root,nums): if not root: return if not root.left and not root.right : nums.append(root.val) return dfs(root.left,nums) dfs(root.right,nums) nums1,nums2 = [],[] dfs(root1,nums1) dfs(root2,nums2) return nums1 == nums2
02625f09bfa2b593a05a1fdcf58b7fdf5b0950cc
Robson75/Exercism
/robot_name.py
827
3.9375
4
import string import random robot_names = set() class Robot: ROBOT_NAME_LETTERS = 2 ROBOT_NAME_NUMBERS = 3 def __init__(self): self.name = "" self.create_new_name() def create_new_name(self): upper_alphabet = string.ascii_uppercase naming_successful = False while not naming_successful: self.name = "" for i in range(self.ROBOT_NAME_LETTERS): self.name += random.choice(upper_alphabet) for i in range(self.ROBOT_NAME_NUMBERS): self.name += str(random.randrange(10)) if self.name not in robot_names: robot_names.add(self.name) naming_successful = True print(self.name) return self.name def reset(self): self.create_new_name()
8ca46435e333b77b1493096a03951516ee8b8b98
singhdhananjay/TestRepo
/Demo/Generator.py
491
3.859375
4
import time # myList=[x**2 for x in range(10)] # disctionary ={x: x+1 for x in range(0, 2)} # print(myList) def First(): print("First") def Second(): print("Second") def Third(): print("Third") def Gen(): First() yield Second() yield Third() # for x in Gen(): # pass # var=Gen() # next(var) # next(var) # next(var, None) def compute(): for i in range(10): time.sleep(.5) yield i # for x in compute(): # print(x)
da91e59358b9ffd3dd092fada854e905fbc7a295
MrJapa/List-Queue-Stack
/__pycache__/queue.py
1,295
4.21875
4
from time import sleep class Queue: def __init__(self): self.elements = [] def enqueue(self, data): self.elements.append(data) return data def dequeue(self): return self.elements.pop(0) def rear(self): return self.elements[-1] def front(self): return self.elements[0] def is_empty(self): return len(self.elements) == 0 if __name__ == '__main__': queue = Queue() print(f"Er køen tom?: {queue.is_empty()}\n") sleep(2) print(f"{queue.enqueue(1)}: Er nu i køen") print(f"{queue.enqueue(2)}: Er nu i køen") print(f"{queue.enqueue(3)}: Er nu i køen") print(f"{queue.enqueue(4)}: Er nu i køen") print(f"{queue.enqueue(5)}: Er nu i køen") print(f"{queue.enqueue(6)}: Er nu i køen") print(f"{queue.enqueue(7)}: Er nu i køen") print(f"{queue.enqueue(8)}: Er nu i køen\n") sleep(2) print(f"Første element i køen: {queue.front()}\n") sleep(2) print(f"Sidste element i køen: {queue.rear()}\n") sleep(2) i = 1 while(i <= 5): print(f"{queue.dequeue()}: Er nu ude af køen") i += 1 sleep(2) print(f"\nEr køen tom?: {queue.is_empty()}\n") sleep(2) print(f"Først element i køen: {queue.front()}\n") sleep(2) while(i <= 8): print(f"{queue.dequeue()}: Er nu ude af køen") i += 1 sleep(2) print(f"\nEr køen tom?: {queue.is_empty()}\n")
42dfbdf860d02bf9cfc1473823926dc52b91b24b
waltr21/BandPanel
/Square.py
2,406
3.6875
4
import random class Square: def __init__(self, w, h, c, p): # Top left x/y coordinates of the square. self.x = random.randint(0,p.width) self.y = random.randint(0,p.height) # Dimensions of the square self.width = w self.height = h # Reference to the panel object self.panel = p # Color of square self.col = c # Movement self.velocity = (random.uniform(1.0,2.0), random.uniform(1.0,2.0)) #self.brightness = random.random() self.brightness = 0.9 self.bAdjust = 0.01 def update(self): # Move by x and y from velocity self.x += self.velocity[0] self.y += self.velocity[1] #self.brightness += self.bAdjust self.bound() self.show() def bound(self): if (self.x < 0): self.x = 0 self.velocity = (self.velocity[0] * -1, self.velocity[1]) if (self.x + self.width > self.panel.width - 1): self.x = self.panel.width - self.width self.velocity = (self.velocity[0] * -1, self.velocity[1]) if (self.y < 0): self.y = 0 self.velocity = (self.velocity[0], self.velocity[1] * -1) if (self.y + self.height > self.panel.height - 1): self.y = self.panel.height - self.height self.velocity = (self.velocity[0], self.velocity[1] * -1) if (self.brightness < 0): self.brightness = 0 self.bAdjust *= -1 if (self.brightness > 1.0): self.brightness = 1.0 self.bAdjust *= -1 def show(self): roundX = round(self.x) roundY = round(self.y) for curX in range(roundX, roundX + self.width): for curY in range(roundY, roundY + self.height): self.panel.setPixel(curX, curY, self.col, self.brightness) class BouncingSquares(): def __init__(self, w, h, numSquares, p): self.squares = [] self.panelRef = p #col = (random.randint(0,255), random.randint(0,255), random.randint(0,255)) for i in range(numSquares): col = (random.randint(0,255), random.randint(0,255), random.randint(0,255)) self.squares.append(Square(w,h,col,p)) def update(self): self.panelRef.setBackground((0,0,0)) for i in self.squares: i.update()
700330a45909d295f8782464b3463e6764590ebf
dikshaa1702/ml
/day7/Day_07_Code_Challenge.py
2,767
3.609375
4
""" Code Challenge Name: Student and Faculty JSON Filename: student.json faculty.json Problem Statement: Create a student and Faculty JSON object and get it verified using jsonlint.com Write a JSON for faculty profile. The JSON should have profile of minimum 2 faculty members. The profile for each faculty should include below information atleast: First Name Last Name Photo (Just a random url) Department Research Areas (can be multiple) Contact Details (should include phone number and email id and can have multiple ) Hint: www.jsonlint.com """ """ Code Challenge Name: JSON Parser Filename: json.py Problem Statement: Get me the other details about the city Latitude and Longitude Weather Condition Wind Speed Sunset Rise and Set timing """ """ Code Challenge Name: Currency Converter Convert from USD to INR Filename: currecncyconv.py Problem Statement: You need to fetch the current conversion prices from the JSON using REST API Hint: http://free.currencyconverterapi.com/api/v5/convert?q=USD_INR&compact=y Check with http://api.fixer.io/latest?base=USD&symbol=EUR """ """" Create a client REST API that sends and receives some information from the Server by calling server's REST API. You are expected to create two functions each for Sending and Receiving data. You need to make two api calls, one with POST method for sending data and the other with GET method to receive data All the communication i.e. sending and receiving of data with the server has to be in JSON format First send the data to cloud using the "http://13.127.155.43/api_v0.1/sending" api with the following fields (Field names should be same as shown ): Phone_Number (pass phone number as string and not as integer) Name College_Name Branch Now receive the data from cloud using the "http://13.127.155.43/api_v0.1/receiving" api with “Phone_Number” along with the number you are looking for as query parameter Print the server responses from both the cases. The first one will give response-code : 200 and response-message : "Data added Successfully", if all goes well. The second one will give all the details stored with the phone number you provided as query parameter. Both the responses will be in JSON format. Output response-code : 200 response-message : Data added Successfully Submitted_at : Mon, 11 Sep 2017 13:32:30 GMT Phone Number : 7877757144 Name : Kunal Vaid Branch : B.Tech CSE College_Name : Amity University """" # Create a new Code Challenge to POST data # Research the below wesbite and post some data on it # https://requestbin.com
f02818ec0ed8ec61986d18cddfda76a69117639d
pisskidney/leetcode
/medium/61.py
1,136
3.796875
4
#!/usr/bin/python from typing import Optional """ 61. Rotate List https://leetcode.com/problems/rotate-list/ """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def getlen(root: ListNode) -> int: n = 1 p = root while p.next: n += 1 p = p.next return n class Solution: def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if not head: return n = getlen(head) k = k % n if not head.next or k == 0: return head i = 0 p = head while i < n - k - 1: p = p.next i += 1 res = p.next p.next = None p = res while p.next: p = p.next p.next = head return res def main(): sol = Solution() root = ListNode(0, ListNode(1, ListNode(2, ListNode(3)))) p = sol.rotateRight(root, 500000) p = sol.rotateRight(None, 0) while p: print(p.val) p = p.next return 0 if __name__ == '__main__': raise SystemExit(main())
da2d8244b7b8f3b28f1713047eacd7649cdf404c
alexeib2014/Tests
/CodingPuzzle/puzzle.py
4,430
3.796875
4
DEBUG = False class PuzzleSolver(object): WORDS = ['OX', 'CAT', 'TOY', 'AT', 'DOG', 'CATAPULT', 'T'] def is_word(self, word): """ Returns true of word is in the dictionary, false otherwise. """ return word in self.WORDS def log(self, message): """ Show message on console if global DEBUG==True :param message: """ if DEBUG: print(message) def get_matrix_resolution(self, matrix): """ Check the matrix and return resolution :param matrix: :return: (height,widht) or Exception """ width = 0 height = 0 for row in matrix: if not isinstance(row,str): # check the matrix consist of strings raise Exception if height == 0: width = len(row) # remember length of the first line... else: if width != len(row): # ...and compare with others raise Exception height += 1 if width == 0 or height == 0: raise Exception return height, width def check_word_on_direction(self, matrix, wordlen, y, x, v, h): """ Check word of puzzle in given direction :param matrix: puzzle :param wordlen: length of the word :param y: start row :param x: start column :param v: vertical direction (North,South) :param h: horizontal direction (West,East) :return: True if word in self.WORDS """ word = "" for i in range(wordlen): if (y < 0 or y >= len(matrix) or x < 0 or x >= len(matrix[0])): # make sure word inside the matrix return False word += matrix[y][x] y += v x += h if self.is_word(word): self.log(word) return True return False def find_words(self, puzzle): """ Return the number of all non-distinct occurrences of the words found in puzzle, horizontally, vertically or diagonally, and also the reverse in each direction. The input to find_words (i.e. puzzle ) is a rectangular matrix of characters (list of strings). :param puzzle: Matrix of chars :return (width,height) or Exception: """ height, width = self.get_matrix_resolution(puzzle) count = 0 # Check for single symbols (have no directions) self.log("Check for 1 symbol word") for y in range(height): for x in range(width): char = puzzle[y][x] if self.is_word(char): count += 1 self.log(char) # Check for words in directions N,NE,E,SE,S,SW,W,NS for wordlen in range(2,max(width,height)+1): self.log("Check for %i symbols word" % wordlen) for y in range(height): for x in range(width): if self.check_word_on_direction(puzzle, wordlen, y, x, -1, 0): # North count += 1 if self.check_word_on_direction(puzzle, wordlen, y, x, -1, 1): # North-East count += 1 if self.check_word_on_direction(puzzle, wordlen, y, x, 0, 1): # East count += 1 if self.check_word_on_direction(puzzle, wordlen, y, x, 1, 1): # South-East count += 1 if self.check_word_on_direction(puzzle, wordlen, y, x, 1, 0): # South count += 1 if self.check_word_on_direction(puzzle, wordlen, y, x, 1, -1): # South-West count += 1 if self.check_word_on_direction(puzzle, wordlen, y, x, 0, -1): # West count += 1 if self.check_word_on_direction(puzzle, wordlen, y, x, -1, -1): # North-West count += 1 return count if __name__ == '__main__': DEBUG = True puzzle_solver = PuzzleSolver() puzzle = [ "CAT", "XZT", "YOT" ] print(puzzle_solver.find_words(puzzle)) puzzle = [ "CATAPULT", "XZTTOYOO", "YOTOXTXX" ] print(puzzle_solver.find_words(puzzle))
82f41dcec66b4fe078a1a2d67b92f33fbdab956a
aish2028/M_4
/ex3.py
289
3.9375
4
def cast_vote(age): assert age>=18,"Age should not be <18,it was:{age}" print("thank you for voting....") try: age=int(input("enter the age:")) cast_vote(age) except AssertionError as a: print(a) else: print("you entered valid age...") finally: print("End....")
b287530b7bf4a584f49a1cdffcb861fd186b2e76
Jinnzenn/MLprojects
/[course] Machine Learning by Andrew Ng/1 LinearRegression/gradientDescent.py
1,008
3.796875
4
import numpy as np from computeCost import * def gradient_descent(X, y, theta, alpha, num_iters): m = y.size #样本数 J_history = np.zeros(num_iters) #每一次迭代都有一个代价函数值 for i in range(0, num_iters): #num_iters次迭代优化 theta=theta-(alpha/m)*(h(X,theta)-y).dot(X) J_history[i] = compute_cost(X, y, theta) #用每一次迭代产生的参数 来计算代价函数值 return theta, J_history def gradient_descent_multi(X, y, theta, alpha, num_iters): # Initialize some useful values m = y.size J_history = np.zeros(num_iters) for i in range(0, num_iters): # ===================== Your Code Here ===================== # Instructions : Perform a single gradient step on the parameter vector theta # # =========================================================== # Save the cost every iteration J_history[i] = compute_cost(X, y, theta) return theta, J_history
caf6ad8b99e8456c0dadb21f390b026af41ad95d
CaizhiXu/LeetCode-Solutions-Python-Weimin
/0142. Linked List Cycle II.py
1,219
3.8125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # method 2 # without using extra space, time O(n), space O(1) class Solution2(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return None slow = head.next # mistake: slow = head fast = head.next.next # stop when a cycle if found or when reading the end while slow != fast and fast and fast.next: slow = slow.next fast = fast.next.next if not fast or not fast.next: # when no cycle return None pos = head while pos != slow: pos = pos.next slow = slow.next return pos # method 1, using extra space, time O(n), space O(n) class Solution(object): def detectCycle(self, head): visited = set() p = head while p: if p in visited: return p visited.add(p) p = p.next return p
42dd7e48d21ecf750ae7f3b878d67493444fb81f
zoepan00/DSCI_522_group-314
/src/dl_xls_to_csv.py
1,286
3.65625
4
# author: Elliott Ribner # date: 2020-01-20 '''This script take a url and downloads a csv in the data directory. You should input url that is of .xls type. Has default url value of default credit dataset if you do not send the url param as a command line argument. Override the default by sending in a url like exemplified below. Usage: src/dl_xls_to_csv.py --output=<output> [--url=<url>] Options: --output=<output> Name of file to be saved, to be stored in /data directory. Include .csv filetype. [--url=<url>] Url of data to download, must be of xsl type. Defaults to https://archive.ics.uci.edu/ml/machine-learning-databases/00350/default%20of%20credit%20card%20clients.xls ''' import pandas as pd from docopt import docopt opt = docopt(__doc__) def main(output, url="https://archive.ics.uci.edu/ml/machine-learning-databases/00350/default%20of%20credit%20card%20clients.xls"): # download xls to pandas dataframe df = pd.read_excel(url, encoding="utf-8") # save file as .csv type in the data directory df.to_csv(r"./data/%s" % (output)) assert df.shape == (30001, 25), "dimensions of accuracies is wrong" if __name__ == "__main__": if (opt["--url"]): main(url=opt["--url"], output=opt["--output"]) else: main(output=opt["--output"])
ea333af03875c5a59a6184ed8fb50b25da4a3541
Zoe0123/K-Nearest-Neighbor-and-Cross-Validation
/knn.py
3,763
3.546875
4
from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt import numpy as np SEED = 36 def load_data(real_news_path: str, fake_news_path: str) -> tuple: """Loads files in <real_news_path> and <fake_news_path> into a single dataset. Splits the datatest randomly into 70% training, 15% validation, and 15% test examples Returns each example.""" # read files to lines and store in total_news real_news = open(real_news_path, "r").readlines() total_news = real_news + open(fake_news_path, "r").readlines() # convert total_news to a matrix of token counts vectorizer = CountVectorizer() X = vectorizer.fit_transform(total_news) # need to correct: CountVectorize should have only been fitted on the training data. # targets: real or fake news y = [1]*len(real_news) + [0] * (len(total_news)-len(real_news)) # first split dataset to 70% training and 30% other examples, # then split other examples to test and validation examples X_train, X_other, y_train, y_other = train_test_split( X, y, test_size=0.3, random_state=SEED) X_test, X_val, y_test, y_val = train_test_split( X_other, y_other, test_size=0.5, random_state=SEED) return X_train, X_test, X_val, y_train, y_test, y_val def select_knn_model(data: tuple, metric='minkowski') -> None: """uses KNN classifer with different k to classify between real and fake news in <data>. Generate plot showing the training and validation accuracy for each k . Choose the model with the best validation accuracy and print its k value and test accuracy.""" k_list = list(range(1, 21)) X_train, X_test, X_val, y_train, y_test, y_val = data t_accuracy = [] v_accuracy = [] max_v = 0 # the best validation accuracy k_max_v = 1 # k value of the model with the best validation accuracy for k in k_list: # KNN model and fit it with training data knn_model = KNeighborsClassifier(n_neighbors=k, metric=metric) knn_model.fit(X_train, y_train) # compute training and validation accuracy t_accuracy.append(knn_model.score(X_train, y_train)) v_acc = knn_model.score(X_val, y_val) v_accuracy.append(v_acc) # find the best validation accuracy and its k value if v_acc > max_v: k_max_v = k # compute and print the test accuracy of the model with best validation accuracy knn_model = KNeighborsClassifier(n_neighbors=k_max_v, metric=metric) knn_model.fit(X_train, y_train) print('The knn model with k = {} has best validation accuracy, and its accuracy on test data is {}'.format( k_max_v, knn_model.score(X_test, y_test))) # plot the training and validation accuracy for each k plt.plot(k_list, t_accuracy, '-bo') plt.plot(k_list, v_accuracy, '-go') plt.xticks(np.arange(0, 21, 1)) plt.xlabel('k') plt.ylabel('accuracy') plt.title('training and validation accuracy for each k') plt.legend(['training accuracy', 'validation_accuracy']) if metric == 'cosine': plt.savefig( './1c. training and validation accuracy for each k (metric=cosine).png') else: plt.savefig('./1b. training and validation accuracy for each k.png') if __name__ == "__main__": real_news_path = "data/clean_real.txt" fake_news_path = "data/clean_fake.txt" # question 1(a) load data data = load_data(real_news_path, fake_news_path) # question 1(b) select_knn_model(data) # question 1(c) pass metric='cosine' to KNeighborsClassifier # select_knn_model(data, metric='cosine')
797e29c2b1756195f571361aee6c6acfe1ff7bcb
jerrylance/LeetCode
/922.Sort Array By Parity II/922.Sort Array By Parity II.py
1,970
3.75
4
# LeetCode Solution # Zeyu Liu # 2019.5.5 # 922.Sort Array By Parity II from typing import List # method 1 O(n)space, one pointer, even和odd分别作为索引迭代 class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: res = [0] * len(A) even = 0 odd = 1 for i in A: if i % 2 == 0: res[even] = i even += 2 else: res[odd] = i odd += 2 return res # transfer method solve = Solution() print(solve.sortArrayByParityII([4,2,5,7])) # method 2 O(1)space, two pointer, 根据当前元素奇偶性,互换i和j即可 class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: i, j, L = 0, 1, len(A) # i - even index, j - odd index while j < L: # (L - 1) is odd, j can reach the last element, so this condition is enough if A[j] % 2 == 0: # judge if the value on odd indices is odd A[j], A[i] = A[i], A[j] # if it is even, exchange the values between index j and i i += 2 # even indices get a right value, then i pointer jump to next even index else: j += 2 # if it is odd, odd indices get a right value, then j pointer jump to next odd index return A # transfer method solve = Solution() print(solve.sortArrayByParityII([4,2,5,7])) # method 3 奇偶分治法,最后合并 class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: res = [0] * len(A) odd = [] even = [] for i in A: if i % 2 != 0: odd.append(i) else: even.append(i) res[0::2] = even res[1::2] = odd return res # transfer method solve = Solution() print(solve.sortArrayByParityII([4,2,5,7]))
e37278d8e5bc4ede5dbaeb6069ed5f3c209c6134
noisebridge/PythonClass
/guest-talks/20180430-concurrency/yielding.py
617
3.578125
4
def push_and_print(q): while True: x = (yield) if x == '': return print('push_and_print: {}'.format(x)) q.append(x) q = [] p = push_and_print(q) try: # p has to be primed in order to advance to the first `yield` p.send(None) print(q) # [] p.send('a') # 'a' print(q) # ['a'] p.send('b') # 'b' print(q) # ['a', 'b'] p.next() # Equivalent to p.send(None). Prints None. print(q) # ['a', 'b', None] p.send('') # Raises StopIteration, like a generator. This needs to be caught. except StopIteration: print('Done')
1f46ce3b54efb40f17ce59654b270d13a71a2b96
p1x31/ctci-python
/yandex/yandex_43412_ml/isdisjoint_a.py
328
3.75
4
def is_quest_possible(n, quests): npc_set = set(range(n)) quest_set = set(quests) if npc_set.isdisjoint(quest_set): return True else: return False # Example usage n = int(input()) quests = list(map(int, input().split())) if is_quest_possible(n, quests): print("Yes") else: print("No")
6223117ee8da5fbc60047bc79cce4e34e55ed615
allwak/algorithms
/Sprint13/Theme2_Reursions/2j.py
1,102
3.625
4
# 0 # 01 # 0110 # 01101001 # 0110100110010110 # 01101001100101101001011001101001 #%% def search(n, k): if n == 1: # "0" return "0" if n == 2: # "01" if k == 1: return "0" else: # k == 2 return "1" if k <= 2 ** (n-2): return search(n-1, k) # если k в первой половине строки else: if k <= 2 ** (n-2) + 2**(n-3): return search(n-1, k-(2 ** (n-3))) # если k в 3-й четверти строки else: return search(n-2, k-(2 ** (n-2)) - (2 ** (n-3))) # если k в 4-й четверти строки def search2(n, k): """Более изящное решение.""" if n == 1: return 0 if k <= 2**(n-1)/2: return search2(n-1, k) else: return 1 - search2(n-1, k-2**(n-1)/2) if __name__ == "__main__": with open("input.txt") as f: n = int(f.readline()) # строка k = int(f.readline()) # индекс символа в строке print(search(n, k)) print(search2(n, k)) # %%
a3495a1146413dfc124d388ec4a36a1b1d30eab8
MindaugasJ88/Python
/Words_guessing_game.py
3,626
4.21875
4
# WORDS GUESSING GAME # User will be guessing the letters of words and will have total 6 wrong attempts # If user guesses the words within 6 wrong attempts - he wins, if not - loses # Words will be selected randomly from the list # User will be able to play again, and the words from the list will not repeat import random from IPython.display import clear_output # LIST OF THE WORDS Words_list = ['Dictionary','Python','Computer','Internet','Society','Entertainment','Building','Europe', 'Program','Function','Keyboard','Table','Newspaper','Hospital','Fence','Money','Youtube', 'Instagram','Facebook','Mouse','Webcam','Movie','Orange','Rainbow','Bottle','Watermellon'] # Function for selecting random word from the list and then remove that word from the list def random_word_func(list1): random_word = random.choice(list1) list1.pop(list1.index(random_word)) return random_word # Function to display available letters for guessing letters def random_letters_func(rand_word, user_letter): new_word = "" duplicate = 0 for letter in rand_word: if user_letter.lower() != letter.lower(): new_word += letter else: duplicate += 1 if duplicate > 1: new_word += letter return new_word # Setting game_on status - True game_on = True # Starting actual gameplay while game_on: #Picking random word from the list by calling function user_rand_word = random_word_func(Words_list) #Defining first variables for the gameplay guessing_word = '' random_letters = ''.join(random.sample(user_rand_word.lower(),len(user_rand_word))) attempts = 6 guessed_letters = 0 user_choice = "" #Iterting through all letters of the word for letter in user_rand_word: #While user input is not equal to letter of the word - run this program while user_choice.lower() != letter.lower(): #breaking out of the while and for loops if used all guessing attempts if attempts == 0: break #asking for user imput and displaying the random letters and guessed word symbols clear_output() print(f'Guessing word: {guessing_word+(len(user_rand_word)-guessed_letters)*"*"} \ \nAvailable letters: {random_letters} \nNumber of available wrong attempts: {attempts} \n') user_choice = input('Please guess the letter of the word \n') if user_choice.lower() != letter.lower(): attempts -= 1 #Else - when user input equals letter then running this program else: guessing_word += letter guessed_letters +=1 random_letters=random_letters_func(random_letters, letter) clear_output() print(f'Guessing word: {guessing_word+(len(user_rand_word)-guessed_letters)*"*"} \ \nAvailable letters: {random_letters} \nNumber of available wrong attempts: {attempts} \n') # if user used all attemps then print it to the user if attempts == 0: clear_output() print("Sorry, you used all atempts") # if user guessed the word then print it to the user elif user_rand_word == guessing_word: print('Congratulations! You had succesfully guessed the word! \n') # asking user if want to reapeat the games, if no - break the while loop repeat_game = input('Do you want to play again? YES / NO \n') if repeat_game[0].lower() != 'y': game_on = False
bbe0a8c069b05e3713275d431fa5e392a1868652
5pence/chunks2
/mean/mean.py
641
4.0625
4
"""Write a function that takes a sequence of items and returns the running average, so for example this: running_mean([1, 2, 3]) returns: [1, 1.5, 2] You can assume all items are numeric so no type casting is needed. Round the mean values to 2 decimals (4.33333 -> 4.33). See the tests for more info. Do use a function of itertools + make it a generator, Not required to get this working but required for kudos, points and prizes! """ def mean(sequence): """Calculate the running mean of the sequence passed in, returns a sequence of same length with the averages. You can assume all items in sequence are numeric."""
4a50ab5778200e8d1068694c87cbcee4ea5aa2d6
levineol/MIS304
/circle copy.py
484
3.65625
4
#Class header PI = 3.14 class Circle: #Define __init__ def __init__(self): #Define attributes self.radius = 1 self.color = "Blue" self.border = 1 #Define calc_area method def calc_area(self): area = PI * self.radius**2 return area #Define calc_circumference def calc_circumference(self): circ = 2 * PI * self.radius return circ def update_color(new_color) self.color = new_color
11476afc5b1c8382cca5e84bd1e848b9f3d4d156
vishrutkmr7/DailyPracticeProblemsDIP
/2022/12 December/db12202022.py
637
3.859375
4
""" Given an array of integers, nums, every value appears three times except one value which only appears once. Return the value that only appears once. Ex: Given the following array nums… nums = [1, 2, 2, 2, 3, 3, 3], return 1. Ex: Given the following array nums… nums = [3, 3, 2, 5, 2, 2, 5, 3, 9, 5], return 9. """ class Solution: def singleNumber(self, nums: list[int]) -> int: return (3 * sum(set(nums)) - sum(nums)) // 2 # Test Cases if __name__ == "__main__": solution = Solution() print(solution.singleNumber([1, 2, 2, 2, 3, 3, 3])) print(solution.singleNumber([3, 3, 2, 5, 2, 2, 5, 3, 9, 5]))
ae87f452512c0848501a62ddceac5e6030962a11
mmhkhan/hackerrank_codes
/ProgrammersDay.py
319
3.578125
4
year = int(input().strip()) if year<1918: if year%4==0: s = '12.09.'+str(year) else: s = '13.09.'+str(year) elif year==1918: s='26.09.'+str(year) else: if year%400==0 or (year%4==0 and year%100!=0): s = '12.09.'+str(year) else: s = '13.09.'+str(year) print(s)
327809d36cd134c2db8fd69a9dfcfffc0bf7ad70
Kayvee08/Algorithms-Python
/Sieve_of_Eratosthenes.py
1,126
4.0625
4
#The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million '''at the beginning we write down all numbers between 2 and n. We mark all proper multiples of 2 (since 2 is the smallest prime number) as composite. A proper multiple of a number x, is a number greater than x and divisible by x. Then we find the next number that hasn't been marked as composite, in this case it is 3. Which means 3 is prime, and we mark all proper multiples of 3 as composite. The next unmarked number is 5, which is the next prime number, and we mark all proper multiples of it. And we continue this procedure until we processed all numbers in the row.''' def sieve(n): li=[True for i in range(2,n)] li.insert(0,False) li.insert(1,False) for i in range(2,n): if (li[i]): j=i while i*j <n: li[i*j]=False j+=1 for i in range(2,n): if li[i]: print(i) n = int(input()) print(f"All Prime Nos less than {n} are:") sieve(n) #TIME COMPLEXITY OF THIS ALGORITHM IS n*(log(log(n)))
cb518747ddc8dcad26105663c581e088841e373c
ijhajj/Django-RestApi-Celery-RabbitMQ-Redis
/django15_project/my_django15_project/queueProdCons.py
1,658
3.703125
4
import threading import time import queue import random _queue = queue.Queue(10)#declared a Queue with max size of 10 # As inbuilt queue DataStructures is used all conditional checks will no longer be required #MAX_ITEMS = 10 #condition = threading.Condition() class ProducerThread(threading.Thread): def run(self): numbers = range(5) global _queue while True: #condition.acquire() #if len(_queue) == MAX_ITEMS: # print("Queue is full.... Producer is waiting") # condition.wait() #print("There is space in Queue.... Producer is producing") number = random.choice(numbers) #_queue.append(number) _queue.put(number) print("Produced {}".format(number)) #condition.notify() #condition.release() time.sleep(random.random()) class ConsumerThread(threading.Thread): def run(self): global _queue while True: #condition.acquire() #if not _queue: # condition.acquire() # print("Nothing in Queue... Consumer Waiting") # condition.wait() #number = _queue.pop(0) number = _queue.get() #inherently fetches the first item on the top of the queue _queue.task_done() #Exclusively tell the queue that we extracted a number print("Consumed {}".format(number)) #condition.notify() #condition.release() time.sleep(random.random()) producer = ProducerThread() producer.start() consumer = ConsumerThread() consumer.start()
64393d7f05416372b71c29a925431607541aba28
mrmukto/Python-Practise
/compare.py
306
3.6875
4
nimberofdegit = 0 numofchracter = 0 textt = input() for x in textt: x = x.lower() if textt >= 'a' and textt <= "z": numofchracter = numofchracter +1 elif (textt >= '1' and textt <= '9'): nimberofdegit = nimberofdegit + 1 print(numofchracter) print(nimberofdegit)
4409e26ba840b41b62d7f90ac39d54076f04cee6
ksayee/programming_assignments
/python/CodingExercises/DailyCodingProblem-70.py
724
3.953125
4
''' This problem was asked by Microsoft. A number is considered perfect if its digits sum up to exactly 10. Given a positive integer n, return the n-th perfect number. For example, given 1, you should return 19. Given 2, you should return 28. ''' def DailyCodingProblem70(n): st=10 cnt=0 fnl_lst=[] while cnt<n: tmp=st sum=0 while tmp!=0: rem=tmp%10 sum=sum+rem tmp=tmp//10 if sum==10: cnt=cnt+1 fnl_lst.append(st) st=st+1 return sorted(fnl_lst,reverse=True)[0] def main(): n=1 print(DailyCodingProblem70(n)) n = 2 print(DailyCodingProblem70(n)) if __name__=='__main__': main()
602009d75835f64896cb7c42c199d2aef4c43154
coddingtonbear/python-measurement
/measurement/measures/electromagnetism.py
2,284
3.59375
4
from measurement.base import AbstractMeasure, MetricUnit __all__ = [ "Capacitance", "Current", "ElectricPower", "Inductance", "Resistance", "Voltage", ] class Capacitance(AbstractMeasure): farad = MetricUnit("1", ["F", "Farad"], ["F"], ["farad"]) class Current(AbstractMeasure): ampere = MetricUnit("1", ["A", "amp", "Ampere"], ["A"], ["ampere", "amp"]) def __mul__(self, other): if isinstance(other, Voltage): return ElectricPower(self.si_value * other.si_value, "W") return super().__mul__(other) class Resistance(AbstractMeasure): ohm = MetricUnit("1", ["Ohm", "Ω"], ["Ω"], ["ohm"]) class Voltage(AbstractMeasure): volt = MetricUnit("1", ["V", "Volt"], ["V"], ["volt"]) def __mul__(self, other): if isinstance(other, Current): return ElectricPower(self.si_value * other.si_value, "W") return super().__mul__(other) class Inductance(AbstractMeasure): henry = MetricUnit("1", ["H", "Henry"], ["H"], ["henry"]) class ElectricPower(AbstractMeasure): """ Electric power is defined as :class:`Voltage` multiplied by :class:`Current`. This is why you can divide :class:`Current` to get the :class:`Voltage` by :class:`Voltage` to get the :class:`Current` or by :class:`Current` to get the :class:`Voltage`: >>> from measurement import measures >>> measures.ElectricPower('24 W') / measures.Voltage('12 V') Current(ampere="2") >>> measures.ElectricPower('24 W') / measures.Current('4 A') Voltage(volt="6") Analog to this, you can also multiply both :class:`Current` and :class:`Voltage` to get :class:`Current` to get the :class:`Voltage`: >>> from measurement import measures >>> measures.Current('2 A') * measures.Voltage('12 V') ElectricPower(watt="24") """ watt = MetricUnit( "1", ["W", "VA", "Watt", "Voltampere"], ["W", "VA"], ["watt", "voltampere"] ) def __truediv__(self, other): if isinstance(other, Current): return Voltage(volt=self.si_value / other.si_value) if isinstance(other, Voltage): return Current(ampere=self.si_value / other.si_value) return super().__truediv__(other)
25360cdf85c66033734f55cd54914cec55693e9e
pirent/python-playground
/automate_stuffs/chapter5/fantasy_inventory.py
638
3.9375
4
def displayInventory(inventory): total = 0 print('Inventory:') for k,v in inventory.items(): print(str(v) + ' ' + k) total += v print('Total number of items: ' + str(total)) def addToInventory(inventory, addedItems): for item in addedItems: current = inventory.setdefault(item, 0) inventory[item] = current + 1 inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} displayInventory(inventory) dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] addToInventory(inventory, dragonLoot) print('>>>> After added items from dragon loot <<<<') displayInventory(inventory)
6959de82ae327f4d489fa73b8420a33c95ab28db
fardeen9983/Ultimate-Dux
/Languages/Python/Basics/GettingStarted/user_input.py
359
4.34375
4
# Take input from user to perform some operation # Take string input name = input("Enter name\n") print(name) # For any other type of data like integers cast the input method's output to desired type age = int(input("Enter age\n")) print("Age : ", age) # For decimal values use float instead of int print(float(input("Enter decimal value :")))
9d169cc1ead97b8003e5c606c778de315d3c3d5d
snehasumare/Assignments_02_05_2021
/restaurant_bill.py
170
3.890625
4
bill_amount = int(input("Enter Bill amount:")) gst_percent = float(input("Enter gst percent:")) total_bill = bill_amount + (bill_amount*gst_percent/100) print(total_bill)
6d4df067c431c230e1c03cd01fd033efb4eba39f
ARC-Computer-Science-Club/Code-Review
/Project_Euler/Pine/Problem_3.py
628
3.578125
4
# largest prime factor of the number 600851475143 # Person addition: Must work with any given int from math import * NUM = 600851475143 MAX = trunc(sqrt(NUM)) # largest possible factor of the given number factor = [] factor2 = [] maxPrime = 2 isPrime = True for i in range(2, MAX): if NUM % i == 0: factor.append(i) for i in range(len(factor)): factor2.append(NUM / factor[len(factor) - i - 1]) factor += factor2 for x in factor: isPrime = True for j in range(2, trunc(sqrt(x))): if x % j == 0: isPrime = False break if isPrime: maxPrime = x print(maxPrime)
ae73d6bf144765163749904a49a317d9a5b2d43c
chandanbrahma/Linear-regression
/Salary_Data.py
1,458
4.09375
4
## importing data import pandas as pd data= pd.read_csv('E:\\assignment\\simplelinearregression\\Salary_Data.csv') data.head() data.info() data.describe() ## so we do have 2 columns with 30 rows and we need to predict the salary hike import matplotlib.pyplot as plt ##ploting the dependent variable plt.hist(data['Salary']) plt.boxplot(data['Salary']) ##ploting the independent variable plt.hist(data['YearsExperience']) plt.boxplot(data['YearsExperience']) ## plot between x and y plt.plot(data['YearsExperience'],data['Salary'],"ro");plt.xlabel("YearsExperience");plt.ylabel("Salary") ## from the plot we can visualize the coorelation between the data data.corr() ## so there is an excellent corelation of 0.978 between both the variables ##importing the statsmodels.formula.api and using ols technique for calculating best fit line import statsmodels.formula.api as smf model=smf.ols('Salary~YearsExperience',data=data).fit() # P-values for the variables and R-squared value for prepared model model.summary() ## so we got a R^2 value of 0.957 which is great, now lets predict the values and plot the graph prediction=model.predict(data) ##visualisation import matplotlib.pyplot as plt plt.title('Comparison of years of experience and prediction salary') plt.ylabel('Predicted values') plt.xlabel('Years of exp') plt.plot(data['YearsExperience'], prediction, color='blue', linewidth=3) plt.show()
64b9fb900ef32b855f310f5184aecdbf12ffe730
fly2rain/LeetCode
/fraction-to-recurring-decimal/fraction-to-recurring-decimal.py
1,874
3.78125
4
class Solution(object): def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ def abs(num): return num if num > 0 else -num def fractionUnder1(numerator, denominator): if numerator == 0: return "" fraction = "" residual_dict = {} str_idx = 0 start = 0 while numerator > 0: if numerator not in residual_dict: residual_dict[numerator] = str_idx fraction += str(numerator * 10 / denominator) numerator = numerator * 10 % denominator str_idx += 1 else: start = residual_dict[numerator] break if numerator > 0: return "%s(%s)" % (fraction[:start], fraction[start:]) else: return fraction isNegative = (numerator * denominator < 0) numerator, denominator = abs(numerator), abs(denominator) integer = int(numerator)/int(denominator) remainder = int(numerator) % int(denominator) fraction = fractionUnder1(remainder, denominator) result = ("%d.%s" % (integer, fraction)) if len(fraction) else str(integer) return "-%s" % result if isNegative else result if __name__ == '__main__': print Solution().fractionToDecimal(1, 2) print Solution().fractionToDecimal(2, 1) print Solution().fractionToDecimal(3, 2) print Solution().fractionToDecimal(2, 3) print Solution().fractionToDecimal(0, 3) print Solution().fractionToDecimal(1, 3) print Solution().fractionToDecimal(1, 6) print Solution().fractionToDecimal(-50, 8) print Solution().fractionToDecimal(-22, -2)
79d5d5ef0a51ed70cd053648d70baa192cb70bc7
hamza-yusuff/Python_prac
/python projects/sum prime.py
474
3.703125
4
def primebetter2(n): if n%2==0: return False else: maximum=n**0.5+1 for x in range(3,int(maximum),2): if n%x==0: return False break else: return True def divisor(n): dev=[] for k in range(1,n+1): if n%k==0: dev.append(k) return dev test=int(input()) for c in range(test): num=int(input()) if primebetter2(sum(divisor(num)))==True: print('Yes') else: print('No')
71b33adae26b24a967f66abd27caa8d9dec9f6f1
mrucal/PTC
/Sesiones/ST1/persona.py
1,847
3.796875
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 4 13:57:27 2017 @author: Mario """ class Persona: def __init__(self, nombre, apellido, nacimiento, fallecimiento = (-1,-1,-1), domicilio=''): self.nombre = nombre self.apellido = apellido self.nacimiento = nacimiento self.fallecimiento = fallecimiento self.domicilio = domicilio def esta_viva(self): return self.fallecimiento == (-1,-1,-1) def get_nombre(self): return self.nombre def get_apelldio(self): return self.apellido def get_nacimiento(self): return self.nacimiento def get_fallecimiento(self): return self.fallecimiento def get_domicilio(self): return self.domicilio def set_nombre(self, nombre): self.nombre = nombre def set_apelldio(self, apellido): self.apellido = apellido def set_nacimiento(self, nacimiento): self.nacimiento = nacimiento def set_fallecimiento(self, fallecimiento): self.fallecimiento = fallecimiento def set_domicilio(self, domicilio): self.domicilio = domicilio def __repr__(self): s = '\n' + self.nombre+' '+self.apellido+' \nNacimiento: '+str(self.nacimiento[0])+'/'+str(self.nacimiento[1])+'/'+str(self.nacimiento[2]) if not self.esta_viva(): s +='\nFallecimiento: '+str(self.fallecimiento[0])+'/'+str(self.fallecimiento[1])+'/'+str(self.fallecimiento[2]) if self.domicilio != '': s += '\nDireccion: '+self.domicilio s+= '\n' return s if __name__ == '__main__': p = Persona('Mario', 'Ruiz', (28,12,1991)) print(p) p.set_domicilio('Calle Horno') print(p,p.esta_viva())
6203ad93e382d511275b35754fec57207504d8b6
jonathansilveira1987/EXERCICIOS_ESTRUTURA_SEQUENCIAL
/exercicio4.py
449
3.53125
4
# 4. Faça um Programa que peça as 4 notas bimestrais e mostre a média. # Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01 media1 = float(input("Digite a primeira média: ")) media2 = float(input("Digite a segunda média: ")) media3 = float(input("Digite a terceira média: ")) media4 = float(input("Digite a quarta média: ")) media_final = ((media1 + media2 + media3 + media4) / 4) print("O resultado da média bimestral é: ", media_final)
91d6bbcbd0fbf686eaa86a0401c77e829e6c398b
ssumitk14/python-OOPs
/Inheritance.py
429
3.65625
4
class Dog: def __init__(self,name,age): self.name = name self.age = age def speak(self): print("Bark") def justPrint(self): print("Printing from Parent Class") class Cat(Dog): def __init__(self,name,age,color): super().__init__(name,age) self.color = color def speak(self): print("Meow...") obj = Cat("anyName",5,"blue") obj.speak() obj.justPrint()
78bec07654ede0247da80a2c7743651dcc88d9c5
bluvory/Com_programming1
/midterm/0327_3.py
366
3.75
4
a = 10 b = 5 a += 100 b **= 3 print(a) print(b) x = 6 y = 8 print("6 > 8 ?", x > y) print("6 = 8 ?", x == y) print("6 != 8 ?", x != y) print("안녕" * 10) if x % 2 == 0: print(x, "짝수이다") else: print(x, "홀수이다") number = int(input("세 자리 정수를 입력하시오")) n1 = number // 100 n2 = number % 100 // 10 n3 = number % 10
969f81fffd179773259451a93a641e08aa8d45d6
harikrishna-vadlakonda/Patterns
/Alphabet N.py
479
3.9375
4
for row in range(6): for col in range(6): if row in {0,5} and col in {0,5}: print('*',end=' ') elif row==1 and col in {0,1,5}: print('*',end=' ') elif row ==2 and col in {0,2,5}: print('*',end=' ') elif row == 3 and col in{0,3,5}: print('*',end=' ') elif row == 4 and col in{0,4,5}: print('*',end=' ') else: print(' ',end= ' ') print()
3b8abd73c537c0d17fea2dec63dd0a1cfd241815
martin-martin/nlpython
/exercises/identity.py
4,878
4.71875
5
# The __init__() function # so in the last exercise we created this class planet. And based on this # class, we created an object , which had all these attributes and a method # as well. But we said if we created a new instance, it would have all the same # property values. # So what's the point of creating multiple instances? class Planet: def __init__(self, name, radius, gravity, system): self.name = name self.radius = radius self.gravity = gravity self.system = system def orbit(self): return f'{self.name} is orbiting in the {self.system}' def __str__(self): return f"The planet's name is {self.name} with a radius of {self.radius} and gravity of {self.gravity}, in the {self.system}" def __repr__(self): return f'Planet Object: {self.name}, {self.radius}, {self.gravity}, {self.system}' # we need to implement another dunder method: __eq__() # this is another nice example that gives us a view through the # back door of how python works: everything is an object, defined # by classes, and all the class methods need to be written to work! def __eq__(self, other): return self.__dict__ == other.__dict__ naboo = Planet('Naboo', 400000, 10, 'Naboo System') #print(naboo) # So what we're doing is creating is multiple instannces as this class # --------------------------- # # EQUALITY AND IDENTITY # # --------------------------- # # but after implementing the __eq__ dunder method, all is well! :) # https://docs.python.org/3.6/reference/datamodel.html#object.__eq__ print(f"planets\n{'-' * 10}") hoth = Planet('Hoth', 200000, 5.5, 'Hoth System') another_hoth = hoth # creating an ALIAS (a reference to the same object) # both 'hoth' and 'another_hoth' refer to the same object print(another_hoth == hoth) # equality = same value print(another_hoth is hoth) # identity = same memory address (same object) print(id(hoth)) print(id(another_hoth)) # same memory address # EFFECTS OF ALIASING # changing something through one variable, mutates the OBJECT # therefore changes are also represented in the other variable print(another_hoth.gravity, hoth.gravity) hoth.gravity = 1 # assigning a new value to an alias print(another_hoth.gravity, hoth.gravity) # the value changed # the reason why is IDENTITY: 'is' means same memory address (same object) print(another_hoth is hoth) # what about creating a new mirror Planet with the exact same parameters? another_hoth = Planet(hoth.name, hoth.radius, hoth.gravity, hoth.system) # alternatively this could also be accomplished like so: # another_hoth = Planet('Hoth', 200000, 5.5, 'Hoth System') # NOW: is it 'equal' (does it have all the same attributes)? print(hoth == another_hoth) # True: yep # and does it have the same identity (is it the same object)? print(hoth is another_hoth) # False: nope print(id(hoth)) print(id(another_hoth)) # different memory address # --------------------------- # # AND HERE'S THE TRICKY PART # # --------------------------- # # small integers, floats and strings are CACHED in python! # https://stackoverflow.com/a/2988271/5717580 # https://stackoverflow.com/a/306353/5717580 # https://wsvincent.com/python-wat-integer-cache/ # https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce # https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers # this leads to unexpected results that don't make sense with the logic # of equality and identity. uncomment the 'b = a' statements to test # for the return values of the comparisons when creating ALIASES # everything works consistently and makes sense (except for that caching...) print(f"\n\nsmall ints\n{'-' * 10}") a = 1 # b = a b = 0 + 1 print(a == b) print(a is b) print(id(a)) print(id(b)) # same memory address... 😱 print(f"\n\nbig ints\n{'-' * 10}") a = 19998989890 # b = a b = 19998989889 + 1 print(a == b) print(a is b) print(id(a)) print(id(b)) print(f"\n\nsmall strings\n{'-' * 10}") a = 'cheese' # b = a b = 'cheese' print(a == b) print(a is b) print(id(a)) print(id(b)) # same memory address... 😱 print(f"\n\nbig strings\n{'-' * 10}") a = 'cheese' * 100 # b = a b = 'cheese' * 100 print(a == b) print(a is b) print(id(a)) print(id(b)) print(f"\n\nlists\n{'-' * 10}") a = ['cheese', 'tomatoes'] # b = a b = ['cheese', 'tomatoes'] print(a == b) print(a is b) print(id(a)) print(id(b)) print(f"\n\ntuples\n{'-' * 10}") a = (1, 2) # b = a b = (1, 2) print(a == b) print(a is b) print(id(a)) print(id(b)) print(f"\n\ndictionaries\n{'-' * 10}") a = {1: 1, 2: 2} # b = a b = {1: 1, 2: 2} print(a == b) print(a is b) print(id(a)) print(id(b))
6aa8e43724deffe8c2f3b71671fff664b834bc75
DylanJones/othello
/oldstuff/ai_bad.py
8,358
3.90625
4
#!/usr/bin/env python3 """ This module contains the various decision making functions. """ from helpers import * from heuristics import score from random import choice, shuffle import time def random(board, color): """Make a random move.""" moves = legal_moves(board, color) return choice(moves) def human(board, color): """Prompt the user for a move.""" moves = legal_moves(board, color) move = None while True: s = input("Enter the coordinates for a move >>> ") try: move = tuple(int(x.strip()) for x in s.split(',')) if move in moves: break else: raise RuntimeError() except: print("Please enter a valid move.") return move def lookahead_n(board, color, n): mv = None best = NEGATIVE_INF # so stupid. apparently we want to minimize our score instead of maximize it? # best = 3842489432 for move in legal_moves(board, color): board2 = [b[:] for b in board] # board2[move[0]][move[1]] = color make_move(board2, color, move) num = lookahead_helper(board2, color, n, next_player(board2, color)) if num > best: best = num mv = move return mv def lookahead_helper(board, color, depth, nextmv): if depth == 0: return score(board, color) best = NEGATIVE_INF # seriously - this makes no sense. # best = 342894366 for move in legal_moves(board, nextmv): board2 = [b[:] for b in board] # board2[move[0]][move[1]] = color make_move(board, nextmv, move) num = lookahead_helper(board2, color, depth - 1, next_player(board2, nextmv)) if num > best: best = num return best def minimax(board, color, n): best_min = NEGATIVE_INF best_move = None for move in legal_moves(board, color): board2 = copy_board(board) make_move(board2, color, move) mmx = minimax_helper(board2, color, color, n) if mmx > best_min: best_move = move best_min = mmx return best_move def minimax_helper(board, color, last_color, depth): moving_plr = next_player(board, last_color) if moving_plr == None or depth == 0: return score(board, color) best = NEGATIVE_INF if moving_plr == color else POSITIVE_INF for move in legal_moves(board, moving_plr): board2 = copy_board(board) make_move(board2, moving_plr, move) worstcase = minimax_helper(board2, color, moving_plr, depth - 1) if moving_plr == color: # pick the move with the best worse-case if worstcase > best: best = worstcase else: # other player's turn - pick the worst case if worstcase < best: best = worstcase return best def minimax_helper2(board, color, last_color, depth): moving_plr = next_player(board, last_color) if moving_plr == None or depth == 0: return score(board, color) if moving_plr == cinv(color): return minimax_helper2(board, cinv(color), last_color, depth) best = NEGATIVE_INF for move in legal_moves(board, moving_plr): # board2 = [list(b) for b in board] board2 = copy_board(board) make_move(board2, moving_plr, move) worstcase = minimax_helper2(board2, color, moving_plr, depth - 1) if worstcase > best: best = worstcase return best # node format (UNUSED, SHOULD DELETE COMMENT): # 0 - board # 1 - board array pointer # 2 - who moved to get this state # 3 - legal_moves for us # 4 - legal_moves for them # 5 - zorbist hash # 6 - heuristic score # 7 - depth that we searched down from this node def alphabeta(board, color, alpha, beta, moving_plr, depth): global nNode if moving_plr is None or depth == 0: nNode += 1 return score(board, color), None best = NEGATIVE_INF if moving_plr == color else POSITIVE_INF bestmv = None moves = legal_moves(board, moving_plr) for move in moves: board2 = copy_board(board) make_move(board2, moving_plr, move) mmx = alphabeta(board2, color, alpha, beta, next_player(board2, moving_plr), depth - 1)[0] # print(f"depth: {depth} alpha:{alpha} beta:{beta}") # print_board(board2) if moving_plr == color: bestmv = bestmv if best > mmx else move best = max(best, mmx) alpha = max(best, alpha) else: best = min(best, mmx) beta = min(best, beta) if beta <= alpha: # alpha-beta cutoff break return best, bestmv def alphabeta_memory(board, color, alpha, beta, moving_plr, depth): # print_board(board) global nNode if moving_plr is None or depth == 0: nNode += 1 return score(board, color), None moves = legal_moves(board, moving_plr) nodes = [] for move in moves: board2 = copy_board(board) make_move(board2, moving_plr, move) cval = transposition_lookup(board2, moving_plr) if cval is not None: nodes.append((cval[0], cval[1], move, board2)) else: nodes.append((NEGATIVE_INF, NEGATIVE_INF, move, board2)) nodes.sort(key=lambda x: x[1], reverse=True) best = NEGATIVE_INF if moving_plr == color else POSITIVE_INF bestmv = None for node in nodes: if node[0] < depth: mmx = alphabeta_memory(node[3], color, alpha, beta, next_player(node[3], moving_plr), depth - 1)[0] transposition_add(node[3], moving_plr, depth, mmx) else: # print('Hit') mmx = node[1] if moving_plr == color: bestmv = bestmv if best > mmx else node[2] best = max(best, mmx) alpha = max(best, alpha) else: best = min(best, mmx) beta = min(best, beta) if beta <= alpha: # alpha-beta cutoff # print("alpha beta cutoff") break return best, bestmv def negamax_ab(board, color, alpha, beta, moving_plr, depth): init_alpha = alpha ttval = negatrans_lookup(board, moving_plr) if ttval is not None and ttval[0] >= depth: if ttval[2] == FLAG_EXACT: return ttval[1] elif ttval[2] == FLAG_LOWER: alpha = max(alpha, ttval[1]) elif ttval[2] == FLAG_UPPER: beta = min(beta, ttval[1]) if depth == 0 or moving_plr is None: return score(board, color) * (1 if color == BLACK else -1) def get_move(board, player, best_move, still_running): global nNode """Get the best move for specified player""" i = 1 while still_running.value and i < 20: # too much s = time.time() nNode = 0 # mv = old_ab(board, player, i) # mv = alphabeta(board, player, NEGATIVE_INF, POSITIVE_INF, player, i)[1] mv = alphabeta_memory(board, player, NEGATIVE_INF, POSITIVE_INF, player, i)[1] best_move.value = 12345 print(f"nodes: {nNode}") print(f"cache: {len(cache)}") print(f"alphabeta: {time.time()-s} seconds for i={i}") pStat() jmv = to_tournament_move(mv) best_move.value = jmv i += 2 if i <= 4 else 1 return mv nNode = 0 if __name__ == '__main__': from .ai_old import alphabeta as old_ab board = from_tournament_format( "???????????@@@@@...??.oo@@...??ooo@@@..??oo@o@@..??.oo@o@..??oo@@@@@.??...@@oo.??...@ooo.???????????") for i in range(1, 9): nNode = 0 s = time.time() mv = alphabeta(board, BLACK, NEGATIVE_INF, POSITIVE_INF, BLACK, i) e = time.time() print(f'alphabeta took {e-s} seconds for i={i}') print(f"nodes: {nNode}") print(f"cache: {len(cache)}") nNode = 0 s = time.time() mv = alphabeta_memory(board, BLACK, NEGATIVE_INF, POSITIVE_INF, BLACK, i) e = time.time() print(f'alphabeta_memory took {e-s} seconds for i={i}') print(f"nodes: {nNode}") print(f"cache: {len(cache)}") nNode = 0 s = time.time() mv = old_ab(board, BLACK, i - 1) e = time.time() print(f'alphabeta_old took {e-s} seconds for i={i}') print(f"nodes: {nNode}") print(f"cache: {len(cache)}")
5521365b4642e8079f89ccccad65a9b2cb8ed738
ArturSkrzeta/Object-Oriented-Design-with-UML-and-Python-Implementation
/course_project/address.py
347
3.6875
4
class Address(): def __init__(self, id, country, city, street, postal): self.id = id self.country = country self.city = city self.street = street self.postal = postal def __repr__(self): return f"Address '{self.id}' -> {self.country}, {self.city} {self.street} {self.postal}"
37d7b94d22f4d1a9b53accdc5c444a749500adfd
karthikpalavalli/Puzzles
/leetcode/average_levels_in_binary_tree.py
930
3.78125
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: if not root: return [] current_nodes = list() next_nodes = list() current_nodes.append(root) result_level_sum = list() while current_nodes: level_sum = 0 for curr_node in current_nodes: if curr_node.left: next_nodes.append(curr_node.left) if curr_node.right: next_nodes.append(curr_node.right) level_sum += curr_node.val result_level_sum.append(level_sum / len(current_nodes)) current_nodes = next_nodes next_nodes = list() return result_level_sum
43f8bcbb7f603bd3f867b7d5caf930b8cdfdb2d7
emredog/cs231n
/assignment1/cs231n/classifiers/softmax.py
4,642
3.875
4
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. - reg: (float) regularization strength Returns a tuple of: - loss as single float - gradient with respect to weights W; an array of same shape as W """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # TODO: Compute the softmax loss and its gradient using explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# num_train = X.shape[0] num_classes = W.shape[1] scores = X.dot(W) lossTraining = 0.0 for i in xrange(num_train): # for each sample scores[i,:] += -np.max(scores[i,:]) # trick to keep numerical stability # calculate e^f / Sum_c(e^f_c) , where c is all classes normExpScores = np.exp(scores[i,:]) / np.sum(np.exp(scores[i,:])) # loss for i^th sample is -log(e^f_yi / Sum_c(e^f_c)) # so we just need the correct index of normExpScores lossTraining += -np.log(normExpScores[y[i]]) # analytic gradient is just the multiplication of i'th input and e^f / Sum_c(e^f_c) # so it boils down to (e^f / Sum_c(e^f_c)) * X[i, :] # where shapes are (10 x 1) * (1x3073) = (10 x 3073) # and this signifies the contribution of i'th sample to parameter update dscore = np.reshape(normExpScores, (num_classes, 1)) * X[i, :] # we also have to add the d(-f_yi)/dW to the i'th row (equivalent form of loss function) # which is simply X[i,:] dscore[y[i],:] -= X[i,:] dW += dscore.T # W.shape = (3073x10), so transpose dscore to fit it lossTraining /= scores.shape[0] lossRegularization = 0.5*reg*np.sum(W*W) dW = dW /num_train + reg * W loss = lossTraining + lossRegularization ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW def softmax_loss_vectorized(W, X, y, reg): """ Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive. """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # TODO: Compute the softmax loss and its gradient using no explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# num_train = X.shape[0] num_classes = W.shape[1] scores = X.dot(W) scores += -np.max(scores) # trick to keep numerical stability lossTraining = 0.0 # calculate e^f / Sum_c(e^f_c) , where c is all classes sumOfExps = np.sum(np.exp(scores), axis=1).reshape(num_train, 1) normExpScores = np.exp(scores) / sumOfExps # loss for i^th sample is -log(e^f_yi / Sum_c(e^f_c)) # so we just need the correct index of normExpScores lossTraining = np.sum(-np.log(normExpScores[range(num_train), y])) # start with e^f / Sum_c(e^f_c) dscore = normExpScores # mark correct classes with ds-1 instead of ds dscore[range(num_train), y] -= 1 # so that when we multiply, we'll also subtract X from those dW = dscore.T.dot(X) lossTraining /= scores.shape[0] lossRegularization = 0.5*reg*np.sum(W*W) dW = dW.T /num_train + reg * W loss = lossTraining + lossRegularization ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW
4907df3ff4dbe887700088a5fe9abe37cff7d708
tronje/GWV
/04/searching/searching.py
3,251
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math """Various search functions """ def bfs(env, start, goal='g', wall='x'): """Breadth first search, starting at `start`, ending at `goal`. Params: ------- env : list 2-D list representing the PlayingField to be searched shall contain Node objects start : Node Node object to start at goal : str The (length 1) string to end the search at wall : str String of length 1 that is treated as non-traversable """ # set distance for our start node start.distance = 0 # a list in python can be used lust like a queue queue = [start] while len(queue) > 0: # pop(0) is the same as dequeue current = queue.pop(0) # iterate over all neighbours for node in neighboursOf(current, env): # if it's a valid node... if node.distance == math.inf and node.value != wall: # ...set its parent node.parent = current # ...and distance node.distance = current.distance + 1 # see if we found our goal if node.value == goal: return node else: # same as enqueue queue.append(node) raise ValueError("Goal '{}' not found in env!".format(goal)) def dfs(env, start, goal='g', wall='x'): """Depth first search, starting at `start`, ending at `goal`. """ start.distance = 0 # a list in python can be used just like a stack stack = [start] while len(stack) > 0: # note: pop() is the last element # as long as we use append() to add elements, # the stack behaviour is guaranteed current = stack.pop() # iterate over neighbours for node in neighboursOf(current, env): if node.distance == math.inf and node.value != wall: node.parent = current node.distance = current.distance + 1 if node.value == goal: return node else: # same as push() stack.append(node) raise ValueError("Goal '{}' not found in env!".format(goal)) def neighboursOf(node, env, handle_portals=True): """All neighbours of a Node in an Environment Params: ------- node : Node env : List Returns: -------- A list of all neighbours """ ret = [] # up ret.append(env[node.x][node.y + 1]) # right ret.append(env[node.x + 1][node.y]) # down ret.append(env[node.x][node.y - 1]) # left ret.append(env[node.x - 1][node.y]) # handle portals if handle_portals and node.value.isdigit(): for line in env: for field in line: if (field.value == node.value and field.coords != node.coords): # append to our neighbours the neighbours # of the other portal, but without handling # portals again to avoid infinite recursion ret += neighboursOf(field, env, handle_portals=False) return ret
ccf6a2a6e9c3488ffd61933b7c4ee006445a98ff
EricHenry/practice_projects
/python/udemy/4-iteratorChallenge.py
572
4.34375
4
# create a list of items (you may use strings or numbers in the list), # then create an iterator using the iter() function. # # use a for loop to loop "n" times, where "n" is the number of items in your list # each time round the loop, use next() on your list to print the next item. # # hint: use the len() function rather than counting the number of items in he list. list = [1, 4, 2, 4, 5, 2, 4, 1, 3, 5, 4, 6, 6, 2, 6, 1, 5, 1, 3, 4, 2, 4, 6, 1, 3, 4, 1] iterableList = iter(list) for i in range(0, len(list)): nextItem = next(iterableList) print(nextItem)
e6592728ae776dcfc4107e38cad1fd55d8b5df46
553672759/xxgit
/python/old/exercise/0012.py
748
3.59375
4
#coding:utf8 ''' Created on 2017-1-11 @author: xx 第 0012 题: 敏感词文本文件 filtered_words.txt, 里面的内容 和 0011题一样,当用户输入敏感词语, 则用 星号 * 替换,例如当用户输入「北京是个好城市」, 则变成「**是个好城市」。 ''' import re def checkwords(ipstr): word_list=[] with open('filter_words.txt','r') as f: for line in f: word_list.append(line.strip()) li=word_list for word in word_list: l=len(re.findall(r'%s' %(word),ipstr)) if l>0: ipstr=ipstr.replace(word,'***') print ipstr if __name__=="__main__": ipstr=raw_input("plase input your string:\n") checkwords(ipstr)
5fdbd8a73f6166c8e51528ed20377b4dd0f0e4ac
lindameh/cpy5p4
/q6_compute_sum.py
133
3.59375
4
def sum_digits(n): if n // 10 == 0: return n else: return n % 10 + sum_digits(n//10) print(sum_digits(234))
3dd9503fc612276ffbdcc76cc39a772ec6d72134
knking/JumbleWord
/JumbleWord.py
1,485
3.734375
4
import tkinter from tkinter import * import random from tkinter import messagebox from random import shuffle answer=["google","facebook","instagram","book","krishna","yellow","king","chicken","fruits","june","king"] words=[] for i in answer: word=list(i) shuffle(word) words.append(word) num=random.randint(0,len(words)) def intital(): global words,answer,num lb1.configure(text=words[num]) def ans_check(): global words,num,answer user_input=e1.get() if user_input==answer[num]: messagebox.showinfo("Success","This is Right answer") reset() else: messagebox.showerror("Error","Nope This is NOT Right answer") e1.delete(0,END) def reset(): global num,words,answer num = random.randint(0, len(words)) lb1.configure(text=words[num]) e1.delete(0,END) root=tkinter.Tk() root.geometry("300x300") root.title("JUMBLE WORD") root.configure(background = "#000000") lb1=Label(root, bg = "#000000", fg = "#FFFFFF",font="times 20") lb1.pack(pady=30,ipady=10,ipadx=10) answers=StringVar() e1=Entry(root,font = ("Verdana", 16),textvariable=answer) e1.pack(ipadx=5,ipady=5) button1=Button(root,text="Check",font = ("Comic sans ms", 16), width = 16,bg = "#4c4b4b", fg = "#6ab04c",command=ans_check) button1.pack(pady=10) button2=Button(root,text="Reset",width=16,font = ("Comic sans ms", 16), bg = "#4c4b4b", fg = "#EA425C",command=reset) button2.pack() intital() root.mainloop()
6ef8aeeb69228294663377daa8added5bd261cc7
alanduda/python-solutions
/URI/Iniciante/Produto Simples.PY
96
3.5
4
number1 = int(input()) number2 = int(input()) PROD = number1 * number2 print(f'PROD = {PROD}')
e6a63d72456f2dd7eaf5bfcb1369068c6f2aea62
StuartSpiegel/Trixie-1.3-0
/colorRange.py
1,241
3.890625
4
from random import random # Generates a random String representing a color in HEX # def generateRandomColorHex(): # number_of_colors = 8 # color = ["#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)]) # for i in range(number_of_colors)] # print(color) # return color # This block shows a chart for testing the color instances. # for i in range(number_of_colors): # plt.scatter(random.randint(0, 10), random.randint(0, 10), c=color[i], s=200) # plt.show() # A Percentage of 0.0% will return the same color and 1.0 will return white # Everything in between will be a lighter shade of the same HUE. Imagine moving along a line between your selected # color and the pure white on an HSB model. # color is the base color selector to choose between white. # def lighter(percent): # color = random_color() # white = [255, 255, 255] # vector = white - color # return color + vector * percent # Creates an array of colors by calling the lighter method --> NumSamples amount of times (iterations) # def colorRange_Instance(numSamples, baseColor): # theColors = [numSamples] # for i in theColors: # theColors[i] = lighter(0.85) def getRGB_Instance(): rgbl = [255, 0, 0] random.shuffle(rgbl) return tuple(rgbl)
d141339186397fdf323cb61e176b065f6e6c7321
z-torn/tornconsole
/window.py
3,049
4.09375
4
""" Main Window class definition that is parent of other windows within the app """ import curses import time class Window: h = None w = None y = None x = None def __init__(self, main, name, h, w, y, x): self.name = name self.window = curses.newwin(h, w, y, x) self.main = main #Store the attributes of the window self.h = h self.w = w self.y = y self.x = x def update(self, refresh_interval=5): """Redraw the window and its contents""" self.refresh_interval = refresh_interval self.next_update = time.time() + self.refresh_interval self._redraw() def _redraw(self): """ Clear and perform the actual refresh of the window """ self.window.clear() self.populate() self.window.refresh() def populate(self): """ Main method intended to hold the information that should be inside the window """ self.new_line("Not implemented") def wait_for_key_press(self): self.new_line("Press any key to continue", add_newline=False) self.window.getch() def get_command(self, debug_window = None): """ Allows for the user to press keys, concatenating a string until the ENTER key is pressed """ command = "" x = 0 y = 0 while True: c = self.window.getch() if c == ord("\n"): return command elif c in (curses.KEY_DC,): x -= 1 self.delete() self.refresh() elif c == curses.KEY_LEFT: x -= 1 elif c == curses.KEY_RIGHT: x += 1 elif c == curses.KEY_HOME: x = y = 0 else: command += chr(c) x += 1 self.new_line(x, debug_window) def new_line(self, text, target_window=None, add_newline=True, attributes=0, pos=None): """ Add a new string to the target_window. Attributes indicate what curses properties are to be added to the string """ target_window = self.window if target_window == None else target_window #Check if the text is going to go over the size of the window max_y, max_x = target_window.getmaxyx() if len(text) > max_x: #Shorten the text to fit the contents of the window and add ... text = "{}...".format(text[:max_x - 4]) try: if pos is None: target_window.addstr(text, attributes) else: target_window.addstr(pos[0], pos[1], text, attributes) if add_newline: target_window.addstr("\n") except Exception as e: #Chances are that this is trying to add a new line and going #outside of the window geometry if e.args[0] == 'addwstr() returned ERR': pass
0324aa547e2821c715030b3f15d5d6a87c1071bf
NazGy/csc401_A3
/code/a3_levenshtein.py
4,944
3.515625
4
import os import numpy as np dataDir = '/u/cs401/A3/data/' def Levenshtein(r, h): """ Calculation of WER with Levenshtein distance. Works only for iterables up to 254 elements (uint8). O(nm) time ans space complexity. Parameters ---------- r : list of strings h : list of strings Returns ------- (WER, nS, nI, nD): (float, int, int, int) WER, number of substitutions, insertions, and deletions respectively Examples -------- >>> Levenshtein("who is there".split(), "is there".split()) (0.333, 0, 0, 1) >>> Levenshtein("who is there".split(), "".split()) (1.0, 0, 0, 3) >>> Levenshtein("".split(), "who is there".split()) (Inf, 0, 3, 0) """ # WER, the number of substitutions, the number of insertions, and the number of deletions numReferenceWords = len(r) r = [""] + r h = [""] + h matrix = [] for i in range(len(r)): matrix.append([]) for j in range(len(h)): matrix[i].append((0, 0, 0)) for i in range(1, len(r)): matrix[i][0] = (0, 0, i) for j in range(1, len(h)): matrix[0][j] = (0, j, 0) for i in range(1, len(r)): for j in range(1, len(h)): matrix[i][j] = matrix[i - 1][j - 1] if r[i] != h[j]: matrix[i][j] = (matrix[i][j][0] + 1, matrix[i][j][1], matrix[i][j][2]) if numReferenceWords: wer = (matrix[-1][-1][0] + matrix[-1][-1][1] + matrix[-1][-1][2])/(numReferenceWords) else: wer = float('Inf') return wer, matrix[-1][-1][0], matrix[-1][-1][1], matrix[-1][-1][2] import os, fnmatch, re def preprocess(text): text = text.replace(",", "") text = text.replace(".", "") text = text.replace("!", "") text = text.replace("?", "") text = text.replace("/", "") text = text.replace("-", "") text = re.sub('<.*?>', '', text) text = re.sub(' +', ' ', text) text = text.lower() return text if __name__ == "__main__": f = open("asrDiscussion.txt", "w") werGoogle = [] werKaldi = [] for subdir, dirs, files in os.walk(dataDir): for speaker in dirs: # print( speaker ) googleTranscripts = open(os.path.join( dataDir, speaker, 'transcripts.Google.txt'), 'r').readlines() kaldiTranscripts = open(os.path.join( dataDir, speaker, 'transcripts.Kaldi.txt'), 'r').readlines() transcripts = open(os.path.join( dataDir, speaker, 'transcripts.txt'), 'r').readlines() for i in range(len(transcripts)): r = preprocess(transcripts[i]).split(" ") hGoogle = preprocess(googleTranscripts[i]).split(" ") hKaldi = preprocess(kaldiTranscripts[i]).split(" ") wer, s, I, d = Levenshtein(r, hGoogle) f.write("[{speaker}] [Google] [{i}] [{wer}] S:[{s}] I:[{I}] D:[{d}]\n".format( speaker=speaker, i=i, wer=wer, s=s, I=I, d=d)) werGoogle.append(wer) wer, s, I, d = Levenshtein(r, hKaldi) f.write("[{speaker}] [Google] [{i}] [{wer}] S:[{s}] I:[{I}] D:[{d}]\n".format( speaker=speaker, i=i, wer=wer, s=s, I=I, d=d)) werKaldi.append(wer) print("std google:", np.std(werGoogle)) print("mean google:", np.mean(werGoogle)) print("std kaldi:", np.std(werKaldi)) print("mean kaldi:", np.mean(werKaldi)) # std google: 0.07954745253192308 # mean google: 0.9480132412512867 # std kaldi: 0.1472559785299535 # mean kaldi: 0.9262620840093712
eef4284a619ffc54d8ca328198dfe859ac1d9c10
aistoume/Leetcode
/AnswerCode/515FindLargestValueinEachTreeRow.py
950
3.90625
4
### Youbin 2017/06/29 ### 515 Find Largest Value in Each Tree Row # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def largestValues(self, root): if root==None: return [] que = deque([[root, 0]]) List = [root.val] while len(que)>0: curr = que.popleft() currNode = curr[0] depth = curr[1] try: x = List[depth] except IndexError: List.append(currNode.val) x = List[depth] if currNode.val > x: List[depth] = currNode.val if currNode.left !=None: que.append([currNode.left, depth+1]) if currNode.right !=None: que.append([currNode.right, depth+1]) return List s = Solution() Tree = TreeNode(1) Tree.left = TreeNode(3) Tree.right = TreeNode(2) Tree.left.left = TreeNode(5) Tree.left.right = TreeNode(3) Tree.right.right = TreeNode(9) r = s.largestValues(Tree) print r
7ff4eedd60e3eba4bf491cb83ffd65605042d5ea
ankitak2016/CPE123
/Lab6/vigenere_decryption.py
1,316
3.71875
4
def main(): f = open("vigenere_test.txt") plaintext = f.readline() numkeychar = 0 key = "turing" finalcipher = "" for a in plaintext: finalcipher = finalcipher + caesar_decrypt(a,key[numkeychar]) if(not (ord(a)>=65 and ord(a)<=90 or ord(a)>=97 and ord(a)<=122)): continue numkeychar=numkeychar+1 if(numkeychar==len(key)): numkeychar = 0 print finalcipher def caesar_decrypt(plain,key): cipher="" if(ord(key)>=65 and ord(key)<=90): caesar_key = ord(key) - 65 else: caesar_key = ord(key)-97 ciphernum = 0 for i in plain: ascii_value = ord(i) if(ascii_value>=65 and ascii_value<=90): changednum = ascii_value - 64 ciphernum = (changednum - caesar_key)%26 if(ciphernum==0): cipher = cipher + chr(90) else: cipher = cipher + chr(ciphernum+64) elif(ascii_value>=97 and ascii_value<=122): changednum = ascii_value - 96 ciphernum = (changednum - caesar_key)%26 if(ciphernum==0): cipher = cipher + chr(122) else: cipher = cipher + chr(ciphernum+96) else: cipher = cipher + i return cipher main()
ab89a906aedbe8bcde3b3d90422513a2ce7026bf
efecntrk/python_programming
/unit-2/guessgame.py
986
4.375
4
''' #guessing game -get a random number between 1 and 10 -prompt the user for to guess the number- -loop while the user guess is not equal to your number if the users guess is less than the number print 'too small' if the users guess is greater than the number print'too big' = print 'you are correct when the user gets the number right' get a random number while True: ask for guess if the guess < number print('too small') if the guess >: print('too big') else: print('you are correct....') break guess 7 number 3 too big guess ''' import random guess = [] #number = int(random.randint(1, 10)) number = 5 while True: guess = int(input('Enter your guess: ')) if guess > number: print('Too big') elif guess < number: print('Too small') else: print('You are correct') break
4faca1a50d72f532e1a3f771d7480e5ae31e89f0
obarquero/deep_learning_udacity
/softmax.py
974
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 28 14:21:31 2016 Softmax exercise: Wikipedia definition: In mathematics, in particular probability theory and related fields, the softmax function, or normalized exponential,[1]:198 is a generalization of the logistic function that "squashes" a K-dimensional vector \mathbf{z} of arbitrary real values to a K-dimensional vector \sigma(\mathbf{z}) of real values in the range (0, 1) that add up to 1. The function is given by @author: obarquero """ """Softmax.""" scores = [3.0, 1.0, 0.2] import numpy as np def softmax(x): """Compute softmax values for each sets of scores in x.""" return np.exp(x)/np.sum(np.exp(x),axis = 0) #pass # TODO: Compute and return softmax(x) print(softmax(scores)) # Plot softmax curves import matplotlib.pyplot as plt x = np.arange(-2.0, 6.0, 0.1) scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)]) plt.plot(x, softmax(scores).T, linewidth=2) plt.show()
94e4ef5b0ea0de0c0745b9f14c46ba5ba8edf329
kacpertopol/kacpertopol.github.io
/start/pl/010_Nauczanie/003_Algebra_i_Geometria/002_Zestawy_zadań/001_Zestaw_1/dual.py
3,297
4
4
#!/usr/bin/env python3 # klasa implementująca liczby dualne # # Dual(a , b) <-> a + b * epsilon class Dual: def __init__(self , one , epsilon): self.one = one self.epsilon = epsilon def __add__(self , other): if(isinstance(other , Dual)): newone = self.one + other.one newepsilon = self.epsilon + other.epsilon return Dual(newone , newepsilon) else: return Dual(self.one + other , self.epsilon) __radd__ = __add__ def __sub__(self , other): if(isinstance(other , Dual)): newone = self.one - other.one newepsilon = self.epsilon - other.epsilon return Dual(newone , newepsilon) else: return Dual(self.one - other , self.epsilon) __rsub__ = __sub__ def __mul__(self , other): if(isinstance(other , Dual)): newone = self.one * other.one newepsilon = self.one * other.epsilon + self.epsilon * other.one return Dual(newone , newepsilon) else: return Dual(self.one * other , self.epsilon * other) __rmul__ = __mul__ def __neg__(self): return Dual(-self.one , -self.epsilon) def __str__(self): return str(self.one) + " + epsilon * " + str(self.epsilon) def __repr__(self): return str(self.one) + " + epsilon * " + str(self.epsilon) # definicja funkcji exp, którą można wykorzystać z liczbami dualnymi # # n - obcięcie szeregu # x - argument exp(x) def expSeries(n , x): value = 1.0 numerator = 1.0 denominator = 1.0 for k in range(1 , n): numerator *= x denominator *= k value += numerator * (1.0 / denominator) return value # definicja funkcji sin, którą można wykorzystać z liczbami dualnymi # # n - obcięcie szeregu # x - argument sin(x) def sinSeries(n , x): numerator = x denominator = 1.0 sign = 1.0 value = x for k in range(1 , n): numerator *= x * x denominator *= (2 * k + 1) * (2 * k) sign *= -1.0 value += sign * numerator * (1.0 / denominator) return value # definicja funkcji cos, którą można wykorzystać z liczbami dualnymi # # n - obcięcie szeregu # x - argument cos(x) def cosSeries(n , x): numerator = 1.0 denominator = 1.0 sign = 1.0 value = 1.0 for k in range(1 , n): numerator *= x * x denominator *= (2 * k) * (2 * k - 1) sign *= -1.0 value += sign * numerator * (1.0 / denominator) return value if(__name__ == "__main__"): print("") print("Sprawdzamy proste przykłady ...") x = Dual(1.0 , 1.0) y = Dual(1.0 , 1.0) print("x + y = " , x + y) print("x * y = " , x * y) print("x * 2 = " , x * 2) print("2 * x = " , 2 * x) print("x + 2 = " , x + 2) print("2 + x = " , 2 + x) print("") print("Sprawdzamy czy exp'(x) = exp(x) ...") x = Dual(1.0 , 1.0) print("x = " , x) print("expSeries(10 , x) = " , expSeries(10 , x)) print("") print("Sprawdzamy czy sin'(x) = cos(x) oraz cos'(x) = -sin(x) ...") x = Dual(2.0 , 1.0) print("x = " , x) print("sinSeries(10 , x) = " , sinSeries(10 , x)) print("cosSeries(10 , x) = " , cosSeries(10 , x))
e72fccb616badf3441c1859d188699f9fb41c2fb
guotaosun/dcn_rem
/dcngui.py
1,225
3.609375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial In this example, we create a simple window in PyQt5. author: sungt last edited: January 20200403 """ import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class MainWindow(QWidget): def __init__(self, parent=None): super().__init__(parent) self.layout = QHBoxLayout() label = QLabel("Set Style:",self) combo = QComboBox(self) combo.addItems(QStyleFactory.keys()) # 选择当前窗口风格 index = combo.findText(QApplication.style().objectName(), Qt.MatchFixedString) # 设置当前窗口风格 combo.setCurrentIndex(index) combo.activated[str].connect(self.onCurrentIndexChanged) self.layout.addWidget(label) self.layout.addWidget(combo) self.setLayout(self.layout) self.setWindowTitle("Application Style") self.resize(300, 100) def onCurrentIndexChanged(self, style): QApplication.setStyle(style) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())
5475d7f0a8206f59cf6cb67961dab3db1e72b55d
piyush09/LeetCode
/Basic Calculator II.py
1,949
3.859375
4
""" Algo: Iterate through the string and use stack to calculate all the in between values. Calculate between values such as product, division, negative numbers and positive numbers. Maintain sign in order to operate it on the next numeric character value. Append them into the stack, which could be summed at the end. T.C. - O(n), iterating through all n characters in the input string. """ def calculate(s): # If no string, return 0 if not s: return "0" # Stack will contain all the values in it, as for in between product, division and negative values # Add them all at the end stack = [] num = 0 sign = "+" for i in range(len(s)): # If s[i] is a digit, then consider it # ord(s[i])-ord("0"), returns the value corresponding to that digit or can use int(s[i]) in order to get integer value if s[i].isdigit(): num = num * 10 + int(s[i]) # sign is used to do the operation, as per the previous character, as in the case of last character, needs to # preserve the sign accordingly, in order to calculate the operation as per the previous sign on it. # If s[i] is in one of the operands, then consider it if s[i] in "+-*/" or i == len(s) - 1: if sign == "+": stack.append(num) elif sign == "-": stack.append(-num) elif sign == "*": stack.append(stack.pop() * num) # In multiplication, popping last element and calculating the product. else: stack.append(int(stack.pop() / num)) # In division, popping last element and calculating the division values. num = 0 # Making num as 0 is important in it sign = s[i] # Preserving sign for operation on next numeric character # Return sum of all elements of the stack return sum(stack) s = "3+2*2" # s = "3/2" print (calculate(s))
5182737722a0d9c6cc35da8b0ee8c6296bf01365
saviaga/BinaryTrees
/transpose-matrix/transpose-matrix.py
561
3.609375
4
import numpy as np class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: #x axis - > y axis #. [0,0] [0,1][0,2] [0,0][1,0][2,0] # [[1,2,3], [[1,4,7], # [4,5,6], [2,5,8], # [7,8,9]] [3,6,9]] # cols = len(A[0]) rows = len(A) print(rows),print(cols) new = [[0 for i in range(rows)] for i in range(cols)] for r in range(cols): for c in range(rows): new[r][c] = A[c][r] return new
efde0daa9f5034326efd4dfa26e693c694e15736
Dragon631/Python_Learning
/Built-in module/pickle_module.py
782
3.78125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- import pickle str = "Hello world!" # pickle.dumps 返回一个序列化后的对象,作为字节对象bytes objects pkd = pickle.dumps(str) print(pkd) # pickle.loads 序列化数据转成字符串 pkl = pickle.loads(pkd) print(pkl) # pickle.dump 序列化对象,并将其写入文件对象中 # f = open('pkdFile.txt', 'wb') # pickle.dump(str, f) # f.close() # 使用 "with open... as ...:"的好处是不用关闭文件 with open('pkdFile.txt', 'wb') as wbf: pickle.dump(str, wbf) # pickle.load 反序列化对象,将文件中的数据解析为一个python对象 # f = open('pkdFile.txt', 'rb') # result = pickle.load(f) # print(result) with open('pkdFile.txt', 'rb') as wbf: data = pickle.load(wbf) print(data)
22a77f736a0b59fc7d0af7750ac1372cd0711fbc
suxin1/Algorithm
/Python/optimization/dynamic_programing/test_knapsack.py
2,002
3.65625
4
import random import time from knapsack_problem import Item, solve, fast_solve, greedy, value, weightInverse, density def buildItems(): names = ['clock', 'painting', 'radio', 'vase', 'book', 'computer'] vals = [175, 90, 20, 50, 10, 200] weights = [10, 9, 4, 2, 1, 20] items = [Item(names[i], vals[i], weights[i]) for i in range(len(names))] return items def buildLargeSetOfItems(num_items, max_value, max_weight): items = [] for i in range(num_items): items.append( Item( "item{}".format(i), random.randrange(1, max_value), float(random.randrange(1, max_weight)) ) ) return items def testGreedy(Items, constraint, getKey): taken, val = greedy(Items, constraint, getKey) print('Total value of items taken = ' + str(val)) for item in taken: print(' ', item) def testGreedys(maxWeight=20): Items = buildItems() print('Items to choose from:') for item in Items: print(' ', item) print('Use greedy by value to fill a knapsack of size', maxWeight) testGreedy(Items, maxWeight, value) print('Use greedy by weight to fill a knapsack of size', maxWeight) testGreedy(Items, maxWeight, weightInverse) print('Use greedy by density to fill a knapsack of size', maxWeight) testGreedy(Items, maxWeight, density) def test_decision_tree(): large_items = buildLargeSetOfItems(50, 50, 10) solve_start = time.time() value_slow, choosed_slow = solve(large_items, 50) print("solve complete in {}".format(time.time() - solve_start)) print(value_slow) print("Choosed items") for item in choosed_slow: print(item) fast_solve_start = time.time() value, choosed = fast_solve(large_items, 100) print("fast solve complete in {}".format(time.time() - fast_solve_start)) print(value) print("Choosed items") for item in choosed: print(item) test_decision_tree()
a708b4695c8a7819cd8abf00e73f91a986c5646e
MagdalenaSvilenova/Programming-Basics-Python
/Conditional Statements Advanced/For-Loop/Left and right sum.py
262
3.625
4
n = int(input()) left = 0 right = 0 for i in range(n): left += int(input()) for i in range(n): right += int(input()) if left == right: print(f'Yes, sum = {left}') else: diff = abs(left - right) print(f'No, diff = {diff}')
5da56bc52d63fb4b98f6ba703d50e946e8437751
kzh980999074/my_leetcode
/src/List/18. 4Sum.py
1,428
3.90625
4
''' iven an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: The solution set must not contain duplicate quadruplets. Example: Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [[-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2]] ''' #需要去掉重复的 def threeSum(nums, target,val0): l=len(nums) result=[] if l<=2 : return target i=1 while i<l-1: left=0 right=l-1 while left<i and right>i: value=nums[i]+nums[left]+nums[right] if value>target: right-=1 elif value<target: left+=1 else: result.append([val0,nums[left],nums[i],nums[right]]) right-=1 left+=1 while nums[right]==nums[right+1] and right>i: right-=1 while nums[left]==nums[left-1] and left<i: left+=1 i+=1 return result def fourSum(nums, target): result=[] l=len(nums) if l<4:return result nums.sort() for i in range(0,l-3): arri=threeSum(nums[i+1:],target-nums[i],nums[i]) result.extend(arri) return result arr=[-3,-2,-1,0,0,1,2,3] result=fourSum(arr,0) print(result)
61e64d170c7e9835dc270c4e0757079494860f05
brisa-araujo/final-project-NLP
/01_Code/01 Data Cleaning.py
14,208
3.59375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import re import string import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder # In[2]: #function to label encoding a column based on a dictionary def classifier(s, dictionary): for k, v in dictionary.items(): if s in v: return k # In[3]: #function to retrieve and clean beer database def clean_beers(path, to_drop, class_dict, fill_dict): df = pd.read_csv(path) #read csv valid = set(df.id[df.retired == 'f']) #create a subset of valid beer ids to be used later df = df[df.retired == 'f'] #filter df based on beers that are still in production df['availability'] = df.availability.str.strip() #clean availability empty spaces #call classifier function to re-label categorical columns that had too many values for k, v in class_dict.items(): df[k] = df[k].apply(lambda x: classifier(x, v)) #fillna from dictionary of column:criterion for k, v in fill_dict.items(): df[k] = df[k].fillna(v) #drop columns df = df.drop(columns=to_drop) return df, valid #return both the clean df and the set of valid beer ids # In[ ]: # In[4]: #function to retrieve reviews dataframe and filter interesting rows def parse_reviews(path, valid): iterator = pd.read_csv(path, chunksize=10000) #read csv by chunks, since it has about 10 million rows df = pd.DataFrame() #create empty dataframe to store filtered rows while len(df) <= 700000: #set a maximum for iteration #for each chunk of the data, filter for valid beer ids, drop rows with na and append the rest to df try: tmp = iterator.get_chunk() tmp = tmp[tmp['beer_id'].isin(valid)] tmp['text'] = tmp['text'].replace('\xa0\xa0', np.nan) tmp = tmp.dropna() df = df.append(tmp, ignore_index=True) #if the previous task cannot be performed, this means we are out of values from the csv file except: print('Out of values') return df #return filtered dataframe # In[5]: #function to finish and save beer df based on which beers have reviews def beers_subset(df_ref, df_filter, path): #get reference dataframe (in this case, the newly created reviews df)and check what is our universe of beer ids universe = df_ref.beer_id.unique() #filter beers df so to have only beers for which we have reviews df_filter = df_filter[df_filter.id.isin(universe)] return df_filter.to_csv(path, index=False) #save csv file with the result # In[6]: #function to clean review df columns def prepare_reviews(data, to_drop, to_encode): #lower float datatypes for x in data: if type(x) == float: data[x] = data[x].astype('float16') #drop columns data = data.drop(columns=to_drop) #encode variables le = LabelEncoder() for x in to_encode: data[x] = le.fit_transform(data[x]) return data #return semi-clean dataframe # In[10]: #function to finish and store review df by cleaning text variable def finish_reviews(df, col, path): #lowercase df[col] = df[col].str.lower() #no numbers df[col] = df[col].str.replace(r'\d+', ' ') #no punctuation or special characters translator = str.maketrans("","" , string.punctuation) df[col] = df[col].apply(lambda x: x.translate(translator)) #remove spaces in the beginning and end df[col] = df[col].str.strip() #Save file to csv df.to_csv(path, index=False) return df # In[8]: def kickstart_beers(): #Paths to get and store files path_beers = '../02_Data/beers.csv' path_reviews = '../02_Data/reviews.csv' path_clean_beers = '../02_Data/beers_clean.csv' path_clean_reviews = '../02_Data/reviews_clean.csv' #Variables to drop in each df to_drop_beers = ['state', 'notes', 'retired', 'name'] to_drop_reviews = ['date'] #New labels to encode in beers to_classify_beers = {'country':{'US':['US'], 'Canada':['CA'], 'America':['MX', 'CR', 'NI', 'BR', 'AR', 'PY', 'CL', 'EC', 'PE', 'DO', 'PA', 'VE', 'UY', 'CO', 'GT', 'HN', 'PR', 'HT', 'EG', 'BS', 'CU', 'JM', 'GU', 'LC', 'TT', 'AG', 'VG', 'BO', 'MQ', 'BB', 'GP', 'DM', 'GQ', 'AW', 'BZ', 'SR', 'VC', 'VI'], 'Europe':['NO', 'IT', 'SE', 'PL', 'DE', 'GB', 'RU', 'BE', 'ES', 'IE', 'DK', 'FI', 'NL', 'AT', 'FR', 'EE', 'AM', 'PT', 'CZ', 'LV', 'CH', 'UA', 'RO', 'LT', 'HU', 'RS', 'MK', 'RE', 'HR', 'GL', 'BY', 'TR', 'BG', 'FO', 'SI', 'GR', 'LU', 'GF', 'MD', 'IS', 'IR', 'SK', 'AD', 'SV', 'BA', 'JE', 'GD', 'MT', 'SM', 'AL', 'MC', 'LI', 'MO'], 'Asia':['IN', 'JP', 'TH', 'CN', 'KZ', 'ID', 'HK', 'PH', 'KG', 'IL', 'MN', 'VN', 'KR', 'GE', 'TN', 'PS', 'PG', 'AZ', 'KP', 'KH', 'UZ', 'TW', 'BM', 'IM', 'LA', 'BD', 'CW', 'MM', 'NP', 'JO', 'MW', 'LK', 'BJ', 'LB', 'AO', 'KY', 'LY', 'AE', 'SY', 'BT', 'TJ', 'IQ', 'TM', 'BF'], 'Africa':['ZW', 'ZA', 'SG', 'BG', 'CY', 'CI', 'PF', 'ME', 'GH', 'NG', 'KE', 'MG', 'MZ', 'GN', 'ET', 'UG', 'MA', 'CV', 'LS', 'WS', 'ER', 'MY', 'PK', 'RW', 'SN', 'LR', 'CG', 'DZ', 'ST', 'BW', 'TD', 'CM', 'GM', 'SZ', 'ZM', 'GW', 'GA', 'CF', 'SS', 'NE'], 'Oceania':['AU', 'NZ', 'MU', 'NC', 'FJ', 'TZ', 'TC', 'SC', 'GG', 'YT', 'FM', 'PW', 'CK', 'VU', 'TG', 'SB', 'TO']}, 'style':{'bock':['German Bock', 'German Doppelbock', 'German Eisbock', 'German Maibock', 'German Weizenbock'], 'brown_ale':['American Brown Ale', 'English Brown Ale', 'English Dark Mild Ale', 'German Altbier'], 'dark_ale':['American Black Ale', 'Belgian Dark Ale', 'Belgian Dubbel', 'German Roggenbier', 'Scottish Ale', 'Winter Warmer'], 'dark_lager':['American Amber / Red Lager', 'European Dark Lager', 'German Märzen / Oktoberfest', 'German Rauchbier', 'German Schwarzbier', 'Munich Dunkel Lager', 'Vienna Lager'], 'hybrid':['American Cream Ale', 'Bière de Champagne / Bière Brut', 'Braggot', 'California Common / Steam Beer'], 'IPA':['American Brut IPA', 'American Imperial IPA', 'American IPA', 'Belgian IPA', 'English India Pale Ale (IPA)', 'New England IPA'], 'pale_ale':['American Amber / Red Ale', 'American Blonde Ale', 'American Pale Ale (APA)', 'Belgian Blonde Ale', 'Belgian Pale Ale', 'Belgian Saison', 'English Bitter', 'English Extra Special / Strong Bitter (ESB)', 'English Pale Ale', 'English Pale Mild Ale', 'French Bière de Garde', 'German Kölsch', 'Irish Red Ale'], 'pilsener_pale_lager':['American Adjunct Lager', 'American Imperial Pilsner', 'American Lager', 'American Light Lager', 'American Malt Liquor', 'Bohemian Pilsener', 'European Export / Dortmunder', 'European Pale Lager', 'European Strong Lager', 'German Helles', 'German Kellerbier / Zwickelbier', 'German Pilsner'], 'porter':['American Imperial Porter', 'American Porter', 'Baltic Porter', 'English Porter', 'Robust Porter', 'Smoke Porter'], 'specialty':['Chile Beer', 'Finnish Sahti', 'Fruit and Field Beer', 'Herb and Spice Beer', 'Japanese Happoshu', 'Japanese Rice Lager', 'Low Alcohol Beer', 'Pumpkin Beer', 'Russian Kvass', 'Rye Beer', 'Scottish Gruit / Ancient Herbed Ale', 'Smoke Beer'], 'stout':['American Imperial Stout', 'American Stout', 'English Oatmeal Stout', 'English Stout', 'English Sweet / Milk Stout', 'Foreign / Export Stout', 'Irish Dry Stout', 'Russian Imperial Stout'], 'strong_ale':['American Barleywine', 'American Imperial Red Ale', 'American Strong Ale', 'American Wheatwine Ale', 'Belgian Quadrupel (Quad)', 'Belgian Strong Dark Ale', 'Belgian Strong Pale Ale', 'Belgian Tripel', 'British Barleywine', 'English Old Ale', 'English Strong Ale', 'Scotch Ale / Wee Heavy'], 'wheat':['American Dark Wheat Ale', 'American Pale Wheat Ale', 'Belgian Witbier', 'Berliner Weisse', 'German Dunkelweizen', 'German Hefeweizen', 'German Kristalweizen'], 'wild_sour':['American Brett', 'American Wild Ale', 'Belgian Faro', 'Belgian Fruit Lambic', 'Belgian Gueuze', 'Belgian Lambic', 'Flanders Oud Bruin', 'Flanders Red Ale', 'Leipzig Gose']}} #values to fill na in beers to_fill_beers = {'country':'Unknown', 'style':'other', 'abv':0} #variables to encode in reviews to_encode_reviews = ['username'] #call function to get and clean beer df beers, valid_ids = clean_beers(path_beers, to_drop_beers, to_classify_beers, to_fill_beers) #call function to get and filter reviews df - based on first criteria reviews_raw = parse_reviews(path_reviews, valid_ids) #call function to finish up beers dataframe, selecting only beers for which we have reviews beers_subset(reviews_raw, beers, path_clean_beers) #call function to prepare reviews df columns reviews_semi = prepare_reviews(reviews_raw, to_drop_reviews, to_encode_reviews) #call function to clean text column and finish up reviews df reviews = finish_reviews(reviews_semi, 'text', path_clean_reviews) #return clean dataframes to play with return beers, reviews # In[11]: beers, reviews = kickstart_beers()
740ec2b2458ce74785cf1d2583f5bef639026d18
MDBarbier/Python
/TextAdventure/game_controller.py
1,374
3.5625
4
#!/user/bin/python3 import HelperFunctions import dice from pprint import pprint def start_game(): HelperFunctions.new_line(1) print('Welcome to the TAG (Text Adventure Game)') HelperFunctions.new_line(2) name = HelperFunctions.get_name() HelperFunctions.new_line(1) character = roll_character() pprint(vars(character)) HelperFunctions.new_line(1) print(name + ' begins their descent into the Dungeon!') HelperFunctions.edit_config_key("playerName", name) HelperFunctions.new_line(4) print('Game Over! Goodbye ' + HelperFunctions.read_config_key("playerName")) HelperFunctions.new_line(1) def roll_character(): strength = dice.roll_dice("d20") dexterity = dice.roll_dice("d20") constitution = dice.roll_dice("d20") intelligence = dice.roll_dice("d20") while (strength + dexterity + constitution + intelligence) < 40: strength = dice.roll_dice("d20") dexterity = dice.roll_dice("d20") constitution = dice.roll_dice("d20") intelligence = dice.roll_dice("d20") return Player(strength, dexterity, constitution, intelligence) class Player: def __init__(self, strength, dexterity, constitution, intelligence): self.strength = strength self.dexterity = dexterity self.constitution = constitution self.intelligence = intelligence
80036981e6ee22a76be0b7057333976fd40a8d80
bakuganin/python
/Python/If/all.py
5,864
3.953125
4
#1 print("Введите 2 числа:") x = int(input()) y = int(input()) if x > y: print(x) else: print(y) #2 print("Введите число:") x = int(input()) if x > 0: print(1) elif x < 0: print(-1) else: print(0) #3 print("Введите 4 различных числа:") x1 = int(input()) x2 = int(input()) y1 = int(input()) y2 = int(input()) if (x1 + y1 + x2 + y2) % 2 == 0: print("YES") else: print("NO") #4 god = int(input()) if (god % 4 == 0) and (god % 100 !=0) and (god % 400 == 0): print("YES") else: print("NO") #5 import random x = random.randint(0,999) print("Первое число -",x) y = random.randint(0,999) print("Второе число -",y) z = random.randint(0,999) print("Третье число -",z) if x>y and x>z: print("Наибольшее число -",x) elif y>x and y>z: print("Наибольшее число -",y) else: print("Наибольшее число -",z) #6 print("3 (если все совпадают), 2 (если два совпадает) или 0 (если все числа различны)") import random x = random.randint(0,50) print("Первое число -",x) y = random.randint(0,50) print("Второе число -",y) z = random.randint(0,50) print("Третье число -",z) if x == y and x == z: print("3") elif y == x: print("2") elif z == x: print("2") elif z == y: print("2") else: print("0") #7 import random x1 = random.randint(0,50) print("Первое число -",x1) y1 = random.randint(0,50) print("Второе число -",y1) x2 = random.randint(0,50) print("Третье число -",x2) y2 = random.randint(0,50) print("Четвертое число -",y2) # когда ладья ходит, координата по одной из осей не меняется if x1 == x2 or y1 == y2: print("YES") else: print("NO") #8 import random x1 = random.randint(0,10) print("Первое число -",x1) y1 = random.randint(0,10) print("Второе число -",y1) x2 = random.randint(0,10) print("Третье число -",x2) y2 = random.randint(0,10) print("Четвертое число -",y2) #король может пойти в любом направление на 1 клетку #если разность между х и у будет 1 или -1 #или разность одной из диагоналей/кординат будет = 0 #значит король сможет перейти с одной клетки на другую if abs(x1-x2) <= 1 and abs(y1-y2) <= 1: print ('YES') else: print ('NO') #9 import random x1 = random.randint(0,10) print("Первое число -",x1) y1 = random.randint(0,10) print("Второе число -",y1) x2 = random.randint(0,10) print("Третье число -",x2) y2 = random.randint(0,10) print("Четвертое число -",y2) #слон всегда ходит по х на 5 клеток и у на 5 клеток #разность х1 и х2 и у1 и у2 всегда будет равна if abs(x1 - x2) == abs(y1 - y2): print('YES') else: print('NO') #10 import random x1 = random.randint(0,8) print("Первое число -",x1) y1 = random.randint(0,8) print("Второе число -",y1) x2 = random.randint(0,8) print("Третье число -",x2) y2 = random.randint(0,8) print("Четвертое число -",y2) #Эта фигура ходит как король, но уже на любое доступное количество клеток, #ну или,ферзь ходит и как ладья и как слон, #поэтому можно обьеденить два условия ладьи и слона в одно if abs(x1-x2) <= 1 and abs(y1-y2) <= 1 or x1 == x2 or y1 == y2: print ('YES') else: print ('NO') #11 if (x1 - 1 == x2 or x1 + 1 == x2) and (y1 - 2 == y2 or y1 + 2 == y2): print ('YES') elif (x1 - 2 == x2 or x1 + 2 == x2) and (y1 - 1 == y2 or y1 + 1 == y2): print ('YES') else: print ('NO') #12 import random n = random.randint(1,15) print("Первое число -",n) m = random.randint(1,15) print("Второе число -",m) k = random.randint(1,15) print("Третье число -",k) d = m*n print("Долек шоколада:",d) if k < d and ((k % n == 0) or (k % m == 0)): print("YES") else: print("NO") #13 import random n = random.randint(1,15) print("Первое число -",n) m = random.randint(1,15) print("Второе число -",m) x = random.randint(1,15) print("Третие число -",x) y = random.randint(1,15) print("Четвертое число -",y) d = m*n print("Метров в бассейне:",d) mmax = max(n, m) mmin = min(n, m) print(mmax,mmin) n = mmax - y m = mmin - x print(min(x,y,m,n)) #14 import random life = 0 print("Как тебя зовут?") name = input() n = random.randint(1,50) print("Ну тогда приступим?",name, "угадай число от 1 до 50",", у тебя 6 попыток.") while life < 6: print("Как ты думаешь, какое?") d = input() d = int(d) life = life+1 if d < n: print("число больше ") if d > n: print("число меньше ") if d == n: break if d == n: lufe = str(life) print(name, ",ты угадал число с ",life,"попытки. Ты выйграл.") if d != n: n = str(n) print("У тебя не осталось попыток. Я загадал число ",n ,"Ты проиграл.")
68b2247802f916167b98a453838ac97e9ca665ef
Kevin202044956/CS1110
/bmr.py
94
3.515625
4
grade_book = {} grade_book['grade'] = list() grade_book['grade'].append(3) print(grade_book)
f6e902fe56fe90d79dcb3977723db2f7046d4077
kidkoder432/scripts
/Python/friendtest.py
1,089
3.890625
4
#friendliness test - how friendly are two people? while True: ci = 0 person1 = input('What is your name? > ') person2 = input('What is your friend\'s name? > ') print('Now we look at your interests. Enter these as words followed by spaces. For example, "reading math science"') p1interests = input('What are your interests? > ').split() p2interests = input('What are your friend\'s interests? >').split() print('Calculating...') for i in range(10000000): print(end = '') if len(p1interests) > len(p2interests): for i in p1interests: if i in p2interests: ci += 1 else: for i in p2interests: if i in p1interests: ci += 1 if ci >= 3: print('You two are both friends. I wish you a good life and well wishes.') elif ci == 2: print('A slightly shaky friendship lies ahead. Proceed with caution') elif ci == 1: print('Hmm... maybe I was wrong about this.') else: print('WARNING: STEP AWAY FROM EACH OTHER NOW.')
ede95d60db181fe26d45187a088643bde65c27e2
vigith/Code4Fun
/Project-Euler/p30.py
1,017
3.640625
4
# Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: # 1634 = 1^(4) + 6^(4) + 3^(4) + 4^(4) # 8208 = 8^(4) + 2^(4) + 0^(4) + 8^(4) # 9474 = 9^(4) + 4^(4) + 7^(4) + 4^(4) # As 1 = 1^(4) is not a sum it is not included. # The sum of these numbers is 1634 + 8208 + 9474 = 19316. # Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. # LOGIC: # Adding 5 digit number can produce 6 digits. So max value will be 9^5*6 = 354294. Iterate # from 2 to 354294 and see whose digits' power-to-sum = number def numToArray(num): res = [] while num >= 1: res.append(num % 10) num /= 10 res.reverse() return res def sumOfPow(array, pow): return reduce(lambda x,y: x + y, [ i ** pow for i in array]) if __name__ == '__main__': max = 9 ** 5 * 6 total = 0 for i in range(2, max): if sumOfPow(numToArray(i), 5) == i: total += i print total
94f6eb78515bac25042bfb7a21563ec1bba8beb3
adharmad/project-euler
/python/4.py
578
3.875
4
# A palindromic number reads the same both ways. The largest palindrome # made from the product of two 2-digit numbers is 9009 = 91 x 99. # # Find the largest palindrome made from the product of two 3-digit numbers. # # https://projecteuler.net/problem=4 import string, sys import commonutils def main(): largest = 0 for i in range(100, 999): for j in range(100, 999): prod = i * j if commonutils.isPalindrome(str(prod)) and prod > largest: largest = prod print (largest) if __name__ == '__main__': main()
e72b912e96b4fef88bdbfb1be8e8665618ee5c62
elfgzp/Leetcode
/49.group-anagrams.py
1,658
3.765625
4
# # @lc app=leetcode.cn id=49 lang=python3 # # [49] 字母异位词分组 # # https://leetcode-cn.com/problems/group-anagrams/description/ # # algorithms # Medium (53.98%) # Total Accepted: 14K # Total Submissions: 25.5K # Testcase Example: '["eat","tea","tan","ate","nat","bat"]' # # 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 # # 示例: # # 输入: ["eat", "tea", "tan", "ate", "nat", "bat"], # 输出: # [ # ⁠ ["ate","eat","tea"], # ⁠ ["nat","tan"], # ⁠ ["bat"] # ] # # 说明: # # # 所有输入均为小写字母。 # 不考虑答案输出的顺序。 # # # class Solution1: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: m = {} for s in strs: s_sorted = ''.join(sorted(s)) res = m.get(s_sorted) if res is None: m[s_sorted] = [s] else: res.append(s) return list(m.values()) class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: """ 利用质数 map 来解题 """ pn = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] i = 97 pnm = {chr(i + j): pn[j] for j in range(26)} m = {} for s in strs: val = None for c in s: if not val: val = pnm[c] else: val *= pnm[c] res = m.get(val) if res is None: m[val] = [s] else: res.append(s) return list(m.values())
3cd1c118bf650ec078744f60f2ab659f7e62d300
ali4413/MCL-DSCI-511-programming-in-python
/exercises/exc_02_26.py
522
3.765625
4
import pandas as pd pokemon = pd.read_csv('data/pokemon.csv', index_col=0) pokemon = pokemon.loc[ : , 'attack': 'type'] # Make a groupby object on the column type # Find the mean value of each column for each pokemon type using .mean() # Save the resulting dataframe as type_means # ____ = ____.____(____).____() # ____ # Obtain from the type_means dataframe, the mean speed of the # water type pokemon by using df.loc[] # Save it in an object named water_mean_speed # ____ = ____.____[____] # Display it # ____
00d36e2c707ec24c5598b3024729f234bae38ea4
Krope/Udemy_beginners
/ex_3/test.py
417
4.40625
4
how_far = input("How far you want to travel: ") try: distance = int(how_far) except: print('Please, input correct number') if distance <= 3: print('Вы можете пройти этот путь пешком.') elif distance >= 3 and distance <= 300: print('You can drive this path.') elif distance >= 300: print('You can fly this path.') else: print('Have a safe journey')
9e8f6697e9e32dfefe4635dcf3326809af3a2230
Sjaiswal1911/PS1
/python/Phonebook/driver_final.py
1,287
4
4
from Phone_book import Phonebook decision = input("Do you wanna use the current DB ? \n Y/N:") if decision == 'Y' or decision == 'y': mode = 1 else : mode = 0 pb = Phonebook(mode) stmt = """Enter the proper index to utilise functions 1 : Add a new number 2 : Update a new Number 3 : Print all contacts 4 : Delete a contact 5 : Print contact starting with... 9 : EXIT """ while True: print(stmt) choice = int(input(">")) if choice == 1 : number = input("Please enter the number:") f_name = input("Enter First name : ") l_name = input("Enter last name : ") email_id = input("Enter email_id, press '-' if not present and press enter : \n") designation = input("Enter designation, press '-' if not present and press ente : \n") print(pb.add_contact(number, f_name, l_name, email_id, designation)) continue elif choice == 2 : print(pb.update_contacts()) continue elif choice == 3 : pb.print_contacts() elif choice == 4 : pb.delete_contacts() continue elif choice == 5: pb.print_contacts(mode = 1) continue elif choice == 9: Phonebook.db.close() break
ce0609ca7be3b2cc0db90bc56629447aad02701e
pouyaneh/adad-chap-kon
/adad chap kon.py
128
3.921875
4
num = input() for i in num: print(i + ':', end=' ') for _ in range(int(i)): print(i , end='') print()
16d0ff39b96515ae0026c0e3472e9aea2bc2c2cc
neuralfilter/hackerrank
/code_forces/astringtask.py
249
3.828125
4
l = raw_input() l = l.lower() listedl = list(l) counter = 0 vowels = ["a", "o", "y", "e", "u", "i"] newarr = [] for i in range(len(l)): if(l[i] not in vowels): newarr.append( ".") newarr.append(listedl[i]) print(''.join(newarr))
4f99fb3c135299a84a3ec75fe5f2b11a7c852e54
badamiak/learn-python-the-hard-way
/ex39_2.py
1,157
4.15625
4
states = { "Oregon" : "OR", "Florida": "FL", "California": "CA", "New York" : "NY", "Michigan" : "MI" } cities = { "CA" : "San Francisco", "MI" : "Detroit", "FL" : "Jacksonville" } cities["NY"] = "New York" cities["OR"] = "Portland" print("-"*10) print(f"NY State has: {cities['NY']}") print(f"OR State has: {cities['OR']}") print("-"*10) print(f"Michigan's abbreviation is: {states['Michigan']}") print(f"Florida's abbreviation is: {states['Florida']}") print("-"*10) print(f"Michigan has: {cities[states['Michigan']]}") print(f"Florida has: {cities[states['Florida']]}") print("-"*10) for state, abbrev in states.items(): print(f"{state} is abbreviated {abbrev}") print("-"*10) for abbrev, city in cities.items(): print(f"{city} is in {abbrev}") print("-"*10) for state, abbrev in states.items(): print(f"{state} is abbrevieated {abbrev} and has the city of {cities[abbrev]}") print("-"*10) state = states.get("Texas") if not state: print("Sorry, no Texas") city = cities.get('TX', "Doesn't exist") print(f"The city for the state 'TX' is: {city}")
27ace62a33d570435d54d96554ef7366f3f91079
adnanaq/Data-Structure-and-Algorithm
/breadth_first_search.py
781
3.921875
4
# Pesudo Code def (Graph, started_node) # G is graph and s is source, starting node let Q be the queue # enqueuing the first/source node to start the search from Q.enqueue(started_node) started_node.visited = True # marking the source node to True as we visit it while Q is not empty: # while there is node/neighbour in the Q, keep looping # Once the node is marked visited, it is dequeued from the Q and set to node variable node = Q.dequeue() # visiting every neighbour of the node variable, set earlier. for neighbour in Graph(node): if neighbour is not visited: # Adding every new neighbour to the Q which isn't visited before. Q.enqueue(neighbour) neighbour.visited = True # and marking them to True.
0ad9932ce9919bb110433deaab1fec861b6347b0
Beadsworth/ProjectEuler
/src/solutions/Prob27.py
1,572
3.90625
4
import src.EulerHelpers as Euler def quad(a, b, n): """quad form from problem""" return n**2 + a*n + b def quad_is_prime(a, b, n): """return True/False on whether quad is prime (must be positive to be prime)""" return quad(a, b, n) > 1 and Euler.is_prime(quad(a, b, n)) def get_prime_pairs(pairs, n): """return list of good pairs""" prime_pairs = [] for pair in pairs: a, b = pair if quad_is_prime(a, b, n): prime_pairs.append(pair) return prime_pairs if __name__ == '__main__': # reduce number of pairs ot valid pairs only # to pass case n = 1, a must be odd a_list = [i for i in range(-999, 999, 2)] # to pass case n = 0, b must be prime b_list = [x for x in Euler.find_first_n_primes(1000) if x < 1000] valid_pairs = [] for a in a_list: for b in b_list: # constraint for positive outcome, i.e. (n(n+a) + b) must be positive in n=1 case) if a > -1*b: valid_pairs.append((a, b)) # iterate through n, eliminating bad pairs until only one pair remains remaining_pairs = valid_pairs pairs_left = len(remaining_pairs) n = -1 while pairs_left > 1: n += 1 remaining_pairs = get_prime_pairs(remaining_pairs, n) pairs_left = len(remaining_pairs) print(pairs_left) # print results final_pair = remaining_pairs[0] final_a, final_b = final_pair print("n:{n}, pair:{pair}".format(n=n, pair=final_pair)) print("answer: {answer}".format(answer=final_a*final_b))
3b15fa7de597e3059f7a7bb44332aabe171fedf0
Miguel-leon2000/Algoritmos_de_busqueda
/ConsultaDeDatos.py
482
3.75
4
class BusquedaSecuencial: """ Metodo que realiza una busqueda secuencial, para encontrar un telefono cualquiera, ya que si existe devuelve un True y si no existe un False. """ def busqueda(self, lista, clave): encontrado = False for f in range(0, len(lista)): for c in range(0, len(lista[f])): if lista[f][c] == clave: encontrado = True break return encontrado
41629d05c332da18311341e0870a1458cdad13b8
deenabhatt/Javascipt-part-1
/trials.py
1,276
3.796875
4
"""Python functions for JavaScript Trials 1.""" def output_all_items(items): for item in items: print(item) def get_all_evens(nums): even_nums = [] for num in nums: if num % 2 == 0: even_nums.append(num) return even_nums def get_odd_indices(items): indices = [] for item in range(len(items)): if item % 2 > 0: indices.append(items[item]) return indices def print_as_numbered_list(items): i=1 for item in items: print(f"{i}. {item}") i+=1 def get_range(start=0, stop=5): nums = [] count = start while count < stop: nums.append(count) count +=1 return nums # Easier way: # for i in range(5): # print(i) def censor_vowels(word): pass # TODO: replace this line with your code def snake_to_camel(string): pass # TODO: replace this line with your code def longest_word_length(words): pass # TODO: replace this line with your code def truncate(string): pass # TODO: replace this line with your code def has_balanced_parens(string): pass # TODO: replace this line with your code def compress(string): pass # TODO: replace this line with your code
7f0df5c40d639784b8dc8dd813ad0268f65a9ad1
AntunesLeonardo/NumericalMethods
/IntegralGaussLegendre/IntegralGaussLegendre.py
3,355
3.90625
4
""" Algorithm for solving integration through Gauss-Legendre method. The input should be the limits of the interval and the number os points to be used. Author: AntunesLeonardo """ # Library import ------------------------------------------ import numpy as np import matplotlib.pyplot as plt from scipy import integrate # Variable Input ------------------------------------------ Lim_inf = 0 # Inferior limit of the interval Lim_sup = 0.8 # Superior limit of the interval points = 5 # Number of points for integration # Function to be solved ----------------------------------- def f(x): #return x + 1 #return np.sin(x) return 400*x**5-900*x**4+675*x**3-200*x**2+25*x+0.2 # Method Values ------------------------------------------- """ This function returns the value for the points and weight used in the Gauss-Legendre integration method up to 5 points. Keep this as comment and rather use output from numpy library. def PointWeight(p): c_1 = np.array([2], dtype=float) c_2 = np.array([1, 1], dtype=c_1.dtype) c_3 = np.array([5/9, 8/9, 5/9], dtype=c_1.dtype) c_4 = np.array([(18-np.sqrt(30))/36, (18+np.sqrt(30))/36, (18+np.sqrt(30))/36, (18-np.sqrt(30))/36], dtype=c_1.dtype) c_5 = np.array([(322-13*np.sqrt(70))/900, (322+13*np.sqrt(70))/900, 128/225, (322+13*np.sqrt(70))/900, (322-13*np.sqrt(70))/900], dtype=c_1.dtype) x_1 = np.array([0], dtype=c_1.dtype) x_2 = np.array([-1/np.sqrt(3), 1/np.sqrt(3)], dtype=c_1.dtype) x_3 = np.array([-np.sqrt(3/5), 0, np.sqrt(3/5)], dtype=c_1.dtype) x_4 = np.array([-np.sqrt(525+70*np.sqrt(30))/35, -np.sqrt(525-70*np.sqrt(30))/35, np.sqrt(525-70*np.sqrt(30))/35, np.sqrt(525+70*np.sqrt(30))/35], dtype=c_1.dtype) x_5 = np.array([-np.sqrt(245+14*np.sqrt(70))/21, -np.sqrt(245-14*np.sqrt(70))/21, 0, np.sqrt(245-14*np.sqrt(70))/21, np.sqrt(245+14*np.sqrt(70))/21], dtype=c_1.dtype) if p == 1: return x_1, c_1 elif p == 2: return x_2, c_2 elif p == 3: return x_3, c_3 elif p == 4: return x_4, c_4 elif p == 5: return x_5, c_5 """ # Function for integrating -------------------------------- def IntgrateGauss(Lim_a, Lim_b, p): mediumPoint = (Lim_a + Lim_b) / 2 # Medium point of the interval x_i, c_i = np.polynomial.legendre.leggauss(p) # Values for points and weight - numpy #x_i, c_i = PointWeight(p) # Values for points and weight - PointWeight function I = 0 for i in range(p): # Sum x_i[i] = mediumPoint + (Lim_b - Lim_a) * x_i[i] / 2 I += c_i[i] * f(x_i[i]) return I * (Lim_b - Lim_a) / 2 # Results display ========================================= print('\nFunção f(x) = x + 1') print('\nResultado de integração - Algoritmo:\n', IntgrateGauss(Lim_inf, Lim_sup, points)) print('\nResultado de integração - Biblioteca:\n',integrate.quadrature(f, Lim_inf, Lim_sup), '\n') # Curve plot ============================================== xPlot = np.linspace(Lim_inf, Lim_sup, (Lim_sup - Lim_inf) * 100) plt.plot(xPlot, f(xPlot), lw=2, c='GoldenRod') plt.title('Curva de f(x) no intervalo ['+str(Lim_inf)+'; '+str(Lim_sup)+']') plt.grid() plt.xlabel('x') plt.ylabel('f(x)') plt.show()
640fbeb72ebf1d51572c500d9d31b8685701845b
Code-for-All/cfapi
/utils.py
1,051
3.859375
4
from datetime import datetime def is_safe_name(name): ''' Return True if the string is a safe name. ''' return raw_name(safe_name(name)) == name def safe_name(name): ''' Return URL-safe organization name with spaces replaced by dashes. Slashes will be removed, which is incompatible with raw_name(). ''' return name.replace(' ', '-').replace('/', '-').replace('?', '-').replace('#', '-') def raw_name(name): ''' Return raw organization name with dashes replaced by spaces. Also replace old-style underscores with spaces. ''' return name.replace('_', ' ').replace('-', ' ') def convert_datetime_to_iso_8601(dt): ''' Convert the passed datetime object to ISO 8601 format ''' if not dt or type(dt) is not datetime: return None iso_string = unicode(dt.isoformat()) # add a 'Z' (representing the UTC time zone) to the end if there's no explicit time zone set if not dt.tzinfo: iso_string = u'{}Z'.format(iso_string.rstrip(u'Z')) return iso_string
c3437ced135c3a33bc264d7a3297316761b2d128
ashirwadsangwan/Algorithms-in-CPP
/CodeForces/x.py
468
3.71875
4
#def findCoin(mean, coins): if __name__ == "__main__": tests = int(input()) for i in range(tests): n = int(input()) coins = input().split() mean = (sum(int(i) for i in coins)/n) if float(mean) > int(mean): print("Impossible") if coins.count(coins[0])==len(coins): print(1) break for i in coins: if int(i)==int(mean): print(int(mean))
b5993fc6e93ca3e43533f0cd460723b2ccc59fbe
Cadet93/Smoothstack-Assignments
/Coding Exercise 8.py
3,423
4.75
5
# 1. Create a function func() which prints a text ‘Hello World’ def func(): print("Hello World") func() # 2.Create a function which func1(name) which takes a value name and prints the output “Hi My name is Google’ def func1(name): print(f"Hi, My name is {name}.") func1('Google') # 3.Define a function func3(x,y,z) that takes three arguments x,y,z # where z is true it will return x and when z is false it should return y . func3(‘hello’goodbye’,false) def func3(x,y,z): if z == True: return x else: return y result = func3('hello', 'goodbye', True) print(result) # 4.define a function func4(x,y) which returns the product of both the values. def func4(x,y): z = x*y return z total = func4(5,10) print(total) # 5. Define a function called as is_even that takes one argument , which returns true when even values is passed and false if it is not. def is_even(value): if value % 2 == 0: return True else: return False even = is_even(8) print(even) # 6. Define a function that takes two arguments, and returns true if the first value is greater than the second value # and returns false if it is less than or equal to the second. def compare(a,b): if a > b: return True else: return False result = compare(4,2) print(result) # 7.Define a function which takes arbitrary number of arguments and returns the sum of the arguments. def func_sum(*args): return sum(args) total = func_sum(3,5,9) print(total) # 8.Define a function which takes arbitrary number of arguments and returns a list containing only the arguments that are even. def func_evens(*args): return [n for n in args if n%2 == 0] print(func_evens(1,2,3,4,5,6,7,8,9,10)) # 9.Define a function that takes a string and # returns a matching string where every even letter is uppercase and every odd letter is lowercase def cap_string(st): res = [] for index in range(len(st)): if index % 2 == 0: res.append(st[index].upper()) else: res.append(st[index].lower()) return ''.join(res) print(cap_string('test')) # 10. Write a function which gives lesser than a given number if both the numbers are even, # but returns greater if one or both or odd. def even_odd(a,b): if a % 2 == 0 and b % 2 == 0: return "lesser" else: return "greater" print(even_odd(1,5)) # 11.Write a function which takes two-strings and returns true if both the strings start with the same letter. def first_letter(str1, str2): if str1[0] == str2[0]: return True else: return False print(first_letter('Fan', 'Heat')) # 12.Given a value,return a value which is twice as far as other side of 7 def square_numbers(numlist): return [num ** 2 for num in numlist] print(square_numbers([1,2,3,4,5])) # 13. A function that capitalizes first and fourth character of a word in a string. def cap_1and4(st): res = [] #Iterate over the character for index in range(len(st)): if index == 0 or index == 3: #Refer to each character via index and append modified character to list res.append(st[index].upper()) else: res.append(st[index].lower()) #Join the list into a string and return return ''.join(res) print(cap_1and4('Blizzard'))
73abc21cfbe7a2f6dacfa24f640de30b98a062d6
marieli15/Curso-Phyton
/Tareas/ejercicio4.py
430
3.859375
4
# Ejercico hecho en clase from funciones import Suma,Resta,multiplicacion print("[1] Suma") print("[2] Resta") print("[3] Multiplicacion") resp = input("¿Que operacion desea hacer?: ") num1 = int(input("Escribe el primer numero :")) num2 = int(input("Escribe el segundo numero :")) if resp == "1": print(Suma(num1,num2)) elif resp == "2": print(Resta(num1,num2)) else: print(multiplicacion(num1,num2))
ca7f75892b78d69350fbff521e40a7b14c882c1b
zdyxry/LeetCode
/array/0766_toeplitz_matrix/0766_toeplitz_matrix.py
462
3.796875
4
# -*- coding: utf-8 -*- class Solution(object): def isToeplitzMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: bool """ m = len(matrix) n = len(matrix[0]) for i in range(1, m): for j in range(1, n): if matrix[i][j] != matrix[i - 1][j - 1]: return False return True matrix=[[1,2,3,4],[5,1,2,3],[9,5,1,2]] print(Solution().isToeplitzMatrix(matrix))
c648b086d6acf43042b6e9e96ec67e1373dac8cd
RapunzeI/Python
/Chapter_5/28.py
239
3.53125
4
def geometric(sequence): for i in range(len(sequence)-2): if sequence[i+1]**2!=sequence[i]*sequence[i+2]: return False return True print(geometric([2,4,8,16,32,64,128,256])) print(geometric([2,4,6,8]))
0aad8a31458a04ad2c940ab50c329e8fb4972aa0
kanade0404/ProgrammingAlgorithm
/AtCoder/ABC122/DoubleHelix.py
86
3.625
4
s = input() print('A' if s == 'T' else 'T' if s == 'A' else 'C' if s == 'G' else 'G')
067794dc19bc7846e2ff926a614f35b94d8de0c9
Dhikigame/python_study
/exception/exception.py
347
3.78125
4
class MyException(Exception): pass def div(a, b): try: if (b <= 0): raise MyException("not minus") #raise:故意に例外発生 print(a / b) except MyException as e: print(e) else: print("no exception!") finally: print("-- end --") div(10, -8.6) # div(10, 3) # div(10, 0)
d3e8d521dff597b65596123d15edbb6c93ece938
peytondodd/LotteryNumbers
/Lo.py
2,596
4
4
#This Python program does some calculations with the winning numbers of the Powerball lottery game. #The file \"BasePower.txt\" has the winning numbers from 2007 to Sep 2018. #This is not a suggestion to play lottery or to use those numbers. #I do it to practice my GitHub and share a Python program. #num1 to num5 are the 5 numbers of the Powerball game, and the 6th number (num6) is the Power number. num1 = 0 num2 = 0 num3 = 0 num4 = 0 num5 = 0 num6 = 0 #When you add the smallest numbers of the Powerball you get 15 (=1+2+3+4+5) by the way, that combination was never a winner from 2007. #When you add the bigest numbers of the Powerball you get 335 (=65+66+67+68+69) by the way, this also never was a winner from 2007. #So there are 335 options of adding the 5 numbers of the PowerBall. sum12345=[0]*335 #In the PowerBall you need to choose 5 numbers from 1 to 69. most69=[0]*70 #The maximum Power number (the 6th one) right now in 2018 is 26, but during the years from 2007 the maximum number was changed. #So we will take 45 numbers (1 to 45). most26=[0]*46 #The file \"BasePower.txt\" has the Powerball winning numbers from 2007 to around Sep 2018. with open('BasePower.txt','r') as baseFile: try: for line in baseFile: str1 = line num1 = int(str1[13:15]) num2 = int(str1[16:18]) num3 = int(str1[19:21]) num4 = int(str1[22:24]) num5 = int(str1[25:27]) num6 = int(str1[28:30]) sumNum=num1+num2+num3+num4+num5 sum12345[sumNum]=sum12345[sumNum]+1 most69[num1]=most69[num1]+1 most69[num2]=most69[num2]+1 most69[num3]=most69[num3]+1 most69[num4]=most69[num4]+1 most69[num5]=most69[num5]+1 most26[num6]=most26[num6]+1 except Exception: print("Something wrong with the \"BasePower.txt\" file, check the spaces between the numbers") print("\nThe most frequent summation of the 5 PowerBall numbers\n") for i in range(1,335): if sum12345[i] > 14: #14 is a random number, you can decrease it to see more option. print("num1+num2+num3+num4+num5 =" ,i," apear ", sum12345[i], " times from 2007") print("\nThe most winners numbers (from 1 to 69) in the PowerBall form 2007\n") for i in range(1,70): if most69[i] > 108: #108 is a random number, you can decrease it to see more winning numbers. print("The number =",i, " was a winer " ,most69[i], " times") print("\nThe most winning Power number, (the 6th number) from 2007\n") for i in range(1,46): if most26[i]> 40: # 40 is a random number, you can decrease it to see more winning numbers. print("The Power number =",i," appear ",most26[i])
647aa5071f55f88f6cd48bd3f70f83e31ebba8bc
liamsalmon/IntroPorgramming-Labs
/Liam Salmon Homework 2.py
3,214
4.40625
4
# File: Homework 2 # Liam Salmon - INTRO TO PROGRAMMING - CMPT 120L 901 # Assignment 2 - Programming Problem 1 # Date - 1 March 2021 # Question: Why is it a good idea to first write out an algorithm in pseudocode rather than jumping immediately to Python code? # Answer: Pseudocode is just precise English that describes what a program does. It is a good idea to first write out an algorithm in pseudocode because it can communicate algorithms without the minor details needed in python code. # File: Homework 2 # Liam Salmon - INTRO TO PROGRAMMING - CMPT 120L 901 # Assignment 2 - Programming Problem 2 # Date - 1 March 2021 # convert.py
 # A program to convert Celsius temps to Fahrenheit # by: Susan Computewell def main(): print ("This program is a temperature converter") celcius = eval(input("What is the Celcius temperature?")) fahrenheit = ((9/5) * celcius) + 32 print ("The temperature", celcius, "deg Celcius = ",fahrenheit,"deg fahrenheit") main() # File: Homework 2 # Liam Salmon - INTRO TO PROGRAMMING - CMPT 120L 901 # Assignment 2 - Programming Problem 3 # Date - 1 March 2021 # convert.py
 # A program to convert Celsius temps to Fahrenheit # by: Susan Computewell def main(): print ("This program is a temperature converter") celcius = eval(input("What is the Celcius temperature?")) fahrenheit = ((9/5) * celcius) + 32 print ("The temperature", celcius, "deg Celcius = ",fahrenheit,"deg fahrenheit") input("Press the <Enter> key to quit.") main() # File: Homework 2 # Liam Salmon - INTRO TO PROGRAMMING - CMPT 120L 901 # Assignment 2 - Programming Problem 4 # Date - 1 March 2021 # futval.py # A program to compute the value of an investment # Carried 10 years into the future def main(): print("This program calculates the future value") print("of an investment") principal = eval(input("Enter the initial principal: ")) apr = eval(input("Enter the annual interest rate: ")) years = eval(input("Enter the number of years of the investment: ")) for i in range(years): principal = principal * (1 + apr) print("The value in ", years ,"years " "is:", principal) main() # File: Homework 2 # Liam Salmon - INTRO TO PROGRAMMING - CMPT 120L 901 # Assignment 2 - Programming Problem 5 # Date - 1 March 2021 def main():  print ("This program is a temperature converter") print ("1: Convert temperature from Fahrenheit to Celsius.") print ("2: Convert temperature from Celsius to Fahrenheit.") temperature = int(input("Enter your choice (1 or 2):")) if temperature >= 2: print("Enter the temperature in Celsius.") fahrenheitTemperature = ((9/5) * celciusTemperature) + 32 print ("The temperature", celciusTemperature, "deg Celsius = ",fahrenheitTemperature,"deg fahrenheit") elif temperature <= 1: print("Enter the temperature in Fahrenheit.") celciusTemperature = (-32 + fahrenheitTemperature) / (9/5) print ("The temperature", fahrenheitTemperature, "deg Celsius = ",celciusTemperature,"deg fahrenheit") else: print("invalid option") main()
e4e12af2196e51dfbd0c1b9deea3104459ea3864
sonam2905/My-Projects
/Python/Exercise Problems/circular_linked_list_traversal.py
316
4.0625
4
# Function to print nodes in a given Circular linked list def printList(self): temp = self.head # If linked list is not empty if self.head is not None: while(True): # Print nodes till we reach first node again print(temp.data, end = " ") temp = temp.next if (temp == self.head): break
203445c6cd9ff63ea1cc811ed637e2ce7b5c39d5
remidiy/datastructs_algos
/trees/cartesian_tree.py
650
3.8125
4
""" Cartesian tree : is a heap ordered binary tree, where the root is greater than all the elements in the subtree """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): # @param A : list of integers # @return the root node in the tree def __int__(self): self.tree = None def buildTree(self, A): if len(A) == 0 : return None val = max(A) i = A.index(val) tree = TreeNode(val) tree.left = self.buildTree(A[:i]) tree.right = self.buildTree(A[i+1:]) return tree
a7fe7cfbd0fdc7292bbda20f38275f9c8919c51b
fooyou/Exercise
/python/3rd_cook_book/Chapter_4_Iterators_Generators/iterator_protocol.py
3,339
4.0625
4
#!/usr/bin/env python # coding: utf-8 # @File Name: iterator_protocol.py # @Author: Joshua Liu # @Email: liuchaozhen@neusoft.com # @Create Date: 2016-01-27 15:01:21 # @Last Modified: 2016-01-27 16:01:18 # @Description: ''' Problem: Building custom objects on which you would like to support iteration, but would like an easy way to implement the iterator protocol. Solution: Example ''' class Node: def __init__(self, value): self._value = value self._children = [] def __repr__(self): return 'Node({!r})'.format(self._value) def add_child(self, node): self._children.append(node) def __iter__(self): return iter(self._children) def depth_first(self): yield self for c in self: yield from c.depth_first() if __name__ == '__main__': root = Node(0) child_1 = Node(1) child_2 = Node(2) root.add_child(child_1) root.add_child(child_2) child_1.add_child(Node(3)) child_1.add_child(Node(4)) child_2.add_child(Node(5)) for ch in root.depth_first(): print(ch) ''' Outputs: Node(0) Node(1) Node(3) Node(4) Node(2) Node(5) Now, see how `yield` works. Discussion: Python's iterator protocol requires __iter__() to return a special iterator object that implements a __next__() operation and uses a StopIteration exception to signal completion. However, implementing such objects can often be a messy affair. For example: ''' class Node2: def __init__(self, value): self._value = value self._children = [] def __repr__(self): return 'Node({!r})'.format(self._value) def add_child(self, other_node): self._children.append(other_node) def __iter__(self): return iter(self._children) def depth_first(self): return DepthFirstIterator(self) class DepthFirstIterator(object): # depth-first traversal def __init__(self, start_node): self._node = start_node self._children_iter = None self._child_iter = None def __iter__(self): return self def __next__(self): # Return myself if just started; create an iterator for children if self._children_iter is None: self._children_iter = iter(self._node) return self._node # If processing a child, return its next item elif self._child_iter: try: nextchild = next(self._child_iter) return nextchild except StopIteration: self._child_iter = None return next(self) # Advance to the next child and start its iteration else: self._child_iter = next(self._children_iter).depth_first() return next(self) ''' See the DepthFirstIterator class works in the same way as the generator version, but it's a mess because the iterator has to maintain a lot of complex state about where it is in the iteration process. Frankly, nobody likes to write mind-bending code like that. Define your iterator as a generator and be done with it. ''' root = Node2(0) child_1 = Node2(1) child_2 = Node2(2) root.add_child(child_1) root.add_child(child_2) child_1.add_child(Node2(3)) child_1.add_child(Node2(4)) child_2.add_child(Node2(5)) for ch in root.depth_first(): print(ch)
595840985bbad449a86180c3eba138a93ff7835b
Vjoglekar/programs
/BinarySearch.py
455
3.75
4
L=[1,25,36,7,52,0] key=7 L.sort() print(L) def binary_search(searchList,key): length=len(searchList) low=0 upper= length - 1 while(low <= upper): middle=(low + upper)//2 if(key == searchList[middle]): return middle elif (key < searchList[middle]): upper = middle - 1 elif (key > searchList[middle]): low= middle + 1 return False r=binary_search(L,key) print(r)
c1e9b2999ce97b8c5562c939b735158c5ad788e6
wesleymerrick/Data-Sci-Class
/DatSciInClassStuff/Feb3Exercise.py
676
3.5625
4
from __future__ import print_function from bs4 import BeautifulSoup import urllib """ Exercises from 2/3/17 """ # In python, pull and print out the main body text of the following website: # http://www.thekitchn.com/17-outrageous-recipes-for-super-bowl-sunday-227804 # Then pull and list all the links. r = urllib.urlopen("http://www.thekitchn.com/17-outrageous-recipes-for-super-bowl-sunday-227804").read() soup = BeautifulSoup(r, "html.parser") stuff = soup.find_all("div", class_="typset--longform") otherstuff = stuff[0].find_all('p') for i in otherstuff: print(i.get_text()) otherstuff2 = stuff[0].find_all('ul') for i in otherstuff2: print(i.get_text())