blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
29c1568e375eb6682e7f50ebdf428c4a35bd8342
makenafetzer/Hog
/hog_test.py
3,260
3.8125
4
"""CS 61A Presents The Game of Hog.""" from dice import four_sided, six_sided, make_test_dice from ucb import main, trace, log_current_line, interact GOAL_SCORE = 100 # The goal of Hog is to score 100 points. ###################### # Phase 1: Simulator # ###################### def roll_dice(num_rolls, dice=six_sided): """Simulate rolling the DICE exactly NUM_ROLLS>0 times. Return the sum of the outcomes unless any of the outcomes is 1. In that case, return the number of 1's rolled. """ # These assert statements ensure that num_rolls is a positive integer. assert type(num_rolls) == int, 'num_rolls must be an integer.' assert num_rolls > 0, 'Must roll at least once.' # BEGIN PROBLEM 1 points = 0 ones_counter = 0 for i in range(num_rolls): roll = dice() if roll == 1: ones_counter += 1 points += roll if ones_counter: return ones_counter return points # END PROBLEM 1 def free_bacon(opponent_score): """Return the points scored from rolling 0 dice (Free Bacon).""" # BEGIN PROBLEM 2 if opponent_score < 10: return opponent_score + 1 digits = [] for x in str(opponent_score): digits.append(int(x)) return max(digits) + 1 def hogtimus_prime(score): """Returns the next highest prime if the player's current score is prime. >>>hogtimus_prime(11) >>>13 """ def is_prime(score): if score == 1: return False elif score == 2: return True for i in range(2, (score//2 + 2)): if score%i == 0: return False return True def next_prime(score): score += 1 # so that we are testing the confirmed prime number + 1 while not(is_prime(score)): # runs the while loop until is_prime returns true score += 1 return score if is_prime(score): return next_prime(score) return False def take_turn(num_rolls, opponent_score, dice=six_sided): """Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free Bacon). Return the points scored for the turn by the current player. Also implements the Hogtimus Prime and When Pigs Fly rules. num_rolls: The number of dice rolls that will be made. opponent_score: The total score of the opponent. dice: A function of no args that returns an integer outcome. """ # Leave these assert statements here; they help check for errors. assert type(num_rolls) == int, 'num_rolls must be an integer.' assert num_rolls >= 0, 'Cannot roll a negative number of dice in take_turn.' assert num_rolls <= 10, 'Cannot roll more than 10 dice.' assert opponent_score < 100, 'The game should be over.' # BEGIN PROBLEM 2 if num_rolls == 0: return free_bacon(opponent_score) else: uncapped_score = roll_dice(num_rolls, dice) if hogtimus_prime(uncapped_score): uncapped_score = hogtimus_prime(uncapped_score) print(uncapped_score) elif uncapped_score > (25 - num_rolls): return (25 - num_rolls) return uncapped_score print(take_turn(1,0,make_test_dice(3))) # END PROBLEM 2
5fea068656b4ea644207186d1060f8944ae6f26c
HrishikeshHPillai/Learn-Python-With-Hrishikesh
/Sum of elements of a list (Recursion).py
387
3.984375
4
#Author: Hrishikesh H Pillai #Date: 24/11/2019 #Title: Sum of Elements of a List (Recursion) def sum_of_list(list): if len(list)==0: return 0 else: return list[0]+sum_of_list(list[1:]) while True: try: a=eval(input("Enter the list: ")) except SyntaxError: print("Please enter a valid input: ") continue print(sum_of_list(a))
25ca3450e7b46d3144875f3681c20369f2003279
EbukaNweje/My-python-Project
/pythonClass/dataTypes/dataTypesAssignment/userInput.py
257
3.9375
4
# name = input() # print(name.upper()) num = "What is your first number:" sub = input (num) num2 = "What is your second number:" sub2 = input(num2) print(int(sub) + int(sub2)) a = (2,48,16,21,1) b = (20,10,40,2,0) c = max(a) d = max(b) e = c//d print(e)
1d39a016bacf4a8cf8fad552af7bc17f082fca0f
effat-100/sample
/test5.py
138
4.125
4
import re pattern = r"Bangla" result = re.match(pattern, "Bangladesh") if result: print("Match Found!") else: print("No match")
9d2ce506da18633c6f808b3bf9430b94623ac554
17mirinae/Python
/Python/SEOKCHAN/정렬/5.소트인사이드.py
241
3.78125
4
#!/usr/bin/env python3 # coding: utf-8 def main(): n = input() nums = list(map(int, list(n))) nums.sort(reverse=True) res = '' for i in nums: res += str(i) print(res) if __name__ == '__main__': main()
c7ba695836adbc1c58b12bf3e44424529556ed74
anthager/dp-evaluation
/dpevaluation/utils/row_validator.py
1,119
4.03125
4
import pandas as pd import numpy as np from functools import reduce def rows_validator(df: pd.DataFrame, columns: dict) -> pd.DataFrame: ''' Okay this is a handful. Given a dataframe and an array of conditions with name, upper and lower returns only the rows that are between the lower and upper bound (both inclusive). This is done by generating a series containing boolean values for each row for each of the columns. When we have a series for with the shape (,<rows>) for each of the columns, these are converted to numpy arrays of ints and reduced togheter to a single (,<rows>) vector. If a row in this vector has the value of len(columns) it fullfills all conditions and should be included in the resulting dataframe ''' column_conditions = [((df[column['name']] <= column['upper']) & ( df[column['name']] >= column['lower'])).to_numpy(np.int) for column in columns if column['name'] in df.columns] conditions = np.array(list(map(lambda num: num == len( column_conditions), reduce(lambda a, c: a + c, column_conditions)))) return df[conditions]
84fcd9aa40138807f63b079b6c55ca7a80d455f4
zhaoxuhui/RStoolkit
/common.py
2,137
3.71875
4
# coding=utf-8 import os import platform import shutil def getSeparator(): """ Get the separator for different systems. :return: String,the separator.e.g. "/" on linux. """ sysstr = platform.system() if (sysstr == "Windows"): separator = "\\" elif (sysstr == "Linux"): separator = "/" else: separator = "/" return separator def copyFilesTo(paths, dstPath): """ A function for copying files to certain dir. :param paths: A list of file paths. :param dstPath: A string,the destination dir for files. :return: Nothing. """ for i in range(len(paths)): shutil.copy(paths[i], dstPath) print (i * 1.0 / len(paths)) * 100, "% finished." def gatherDifferentTypeFiles(root_dir, file_types): """ A function for gather different types of files at one time. :param root_dir: String,directory you want to search,e.g."E:/images/" :param file_types: A list contains different file types.Each item is a string. :return: A list of file paths. """ paths = [] for parent, dirname, filenames in os.walk(root_dir): for filename in filenames: for item in file_types: if filename.endswith(item): paths.append(parent + getSeparator() + filename) continue print paths.__len__(), " files loaded." return paths def findAllFiles(root_dir, file_type): """Find the all the files you want in a certain directory. :param root_dir: String,directory you want to search,e.g."E:/images/" :param file_type: String,file type,e.g. "jpg","png","tif"... :return: list,returns A list contains files' paths Usage: findAllFiles("E:/images/", "jpg") It will return a list of jpg image paths. """ paths = [] for parent, dirname, filenames in os.walk(root_dir): for filename in filenames: if filename.endswith(file_type): paths.append(parent + getSeparator() + filename) return paths
d37d53779202fd281e0bb77dd7b24249eb63e935
JyHu/PYStudy
/source/sublime/QuesIn2CTO/ques24.py
276
3.625
4
#coding:utf-8 ''' 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 ''' def countNum(num): i, j = 1, 1 nsum = 0.0 for k in range(num): i, j = j, i + j nsum += j / (i * 1.0) return nsum print countNum(20)
1b2e2b3dbc2b5759cc79e1e6b1a934779915f00b
Umang070/Python_Programs
/for.py
296
3.78125
4
n=int(input("HOW MANY NUMBER U WANT TO SUM:")) total=0 for i in range(1,n+1): total+=i print(total) #for i in range(0,len(n)): # total+=int(n[i]) #print(total) for i in range(1,11): if i == 5 : continue print(i)
21ebcf89afa2d85eddbf3f39977fb9d9a159dd51
mfreund/python-labs
/18_lambdas/18_02_return.py
216
4.0625
4
''' Write a lambda function that does not take in an arguments but returns a value. Print the return value. ''' return_1 = lambda: 1 print(return_1()) # PEP 8 STANDARD def return_2(): return 2 print(return_2())
6ec22d8a6428cf057d17b26b4a5634ea49d39a2d
HenriqueNO/Python-cursoemvideo
/Desafios/Desafio_106.py
717
3.875
4
def helpme(): """ -> Uma função com help mais personalizado com cores :return: retorna com o comando que você deseja ver o manual """ perg = '' while perg != 'fim': print('\033[1;31m~~'*20) print(f'{"SISTEMA DE AJUDA PYHELP":^40}') print('~~'*20, '\033[m') perg = str(input('Função ou Biblioteca > ')).lower().strip() if perg != 'fim': print('\033[1;32m~~' * 20) print(f' Acessando o manual do comando {perg}') print('~~' * 20, '\033[m') print('\033[1;34m') help(perg) print('\033[m') print('\033[1;32m~~'*6) print(' Até logo!') print('~~'*6, '\033[m') helpme()
8872d57191d4b02511df7a56ab6c6fa4bdf5ef39
runzedong/Leetcode_record
/Python/Merge_K_linklist.py
1,627
4
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ def merge_two_list(self, l1, l2): """ :list1 ListNode :list2 ListNode :rtype head-ListNode """ print('now merge_two_list get starting') head=ListNode(None) curr=head while True: if not l1: curr.next=l2 break if not l2: curr.next=l1 break if l1.val<l2.val: curr.next=l1 l1=l1.next else: curr.next=l2 l2=l2.next curr=curr.next while head.next!=None: print(head.next.val) head=head.next return head.next def show_result(self,n1,na): while n1!=None: print(n1.val) n1=n1.next print('************') while na!=None: print(na.val) na=na.next new_head=ListNode(None) new_head=self.merge_two_list(n1,na)# 参数传递问题? while new_head!=None: print(new_head.val,end=' ') new_head=new_head.next n1=ListNode(3) n2=ListNode(6) n3=ListNode(7) n4=ListNode(9) n1.next=n2 n2.next=n3 n3.next=n4 na=ListNode(2) nb=ListNode(5) nc=ListNode(8) nd=ListNode(8) na.next=nb nb.next=nc nc.next=nd test=Solution() test.show_result(n1,na)
c6e9e1f1724312e6ec7213807ae5533a78a3da8a
cs-fullstack-2019-fall/python-classobject-b-cw-marcus110379
/cw.py
2,534
4.125
4
def main(): problem1() problem2() problem3() # Create a class Dog. Make sure it has the attributes name, breed, color, gender. Create a function that will print all attributes of the class. Create an object of Dog in your problem1 function and print all of it's attributes. class Dog: def __init__(self, name, breed, color, gender): self.name = name self.breed = breed self.color = color self.gender = gender def printAll(self): print(f"{self.name}, {self.breed},{self.color},{self.gender}") # !! : use string formatting to take advantage of f strings def problem1(): myDog = Dog("Rocky", "poodle", "black","male") myDog.printAll() # Problem 2: # We will keep having this problem until EVERYONE gets it right without help # Create a function that has a loop that quits with the equal sign. If the user doesn't enter the equal sign, ask them to input another string. def user(): userInput = input("enter a string") while userInput != "=": userInput = input("enter another string") def problem2(): user() # Problem 3: # Create a class Product that represents a product sold online. A product has a name, price, and quantity. # The class should have several functions: # a) One function that can change the name of the product. # b) Another function that can change the name and price of the product. # c) A last function that can change the name, price, and quantity of the product. # Create an object of Product and print all of it's attributes. class Product: def __init__(self, name, price, quantity): self.name = name self.price = price self.quantity = quantity def funcA(self, name): # !! : this is a bad function name self.name = name def funcB(self, name, quantity): # !! : this is a bad function name AND change the name and price of the product self.name = name self.quantity= quantity def funcC(self, name, price, quantity): # !! : this is a bad function name self.name = name self.price = price self.quantity = quantity def problem3(): product1 = Product("genie", "$25", "1") print(product1.name, product1.price, product1.quantity) product1.funcA("test1a") print(product1.name, product1.price, product1.quantity) product1.funcB("test2a", "test2b") print(product1.name, product1.price, product1.quantity) product1.funcC("test3a", "test3b", "test3c") print(product1.name, product1.price, product1.quantity) main()
0eda38cc8987c5159786abbe74ee650f6ef769f6
SotirisZegk/First-Python-Task
/E17052.py
1,948
3.984375
4
import operator #remove duplicates function from list def removeDuplicates(mylist): bmylist=[] for i in mylist: if i not in bmylist: bmylist.append(i) mylist=bmylist print("List without duplicate numbers:",mylist) sortList(mylist) #Sort function for list def sortList(newlist): newlist.sort() print("Sorted List:",newlist) #Remove function for dictionary def removeDuplicates2(a_dict): b_dict={} for key,value in a_dict.items(): if value not in b_dict.values(): b_dict[key]=value a_dict=b_dict print ("Dictionary without duplicates:",a_dict) sortList2(a_dict) #Sort function for dictionary def sortList2(mydict): newa_dict= sorted(mydict.items(), key=operator.itemgetter(1)) mydict=newa_dict print("Sorted Dictionary:",mydict) #list input list1=[] print("First we are gonna create a list.") n=int(input("Enter number of elements in the list : ")) #Zhtaw ton arithmo twn elements pou tha uparxoun sthn lista print("Enter the numbers : ") for i in (range(0,n)): ele= int(input()) list1.append(ele) print("Current List:",list1) removeDuplicates(list1) #Kalw thn removeduplicate kai tautoxrona afou afairethoun oi diploeggrafes , kanw kai sort thn lista mou. print("-----------------------------------------") #dictionary input dict1={} print("Now we are gonna create a dictionary.") n=int(input("Enter number of elements in the list : ")) #Zhtaw ton aritmo twn element pou tha uparxoun sto dictionary for i in (range(0,n)): print("First enter your key and then your value:") mykey= input() myvalue=input() dict1[mykey]=myvalue print("Current Dictionary:",dict1) removeDuplicates2(dict1) #Kalw thn removeduplicate2 kai tautoxrona afou afairethoun oi diploeggrafes , kanw kai sort to dictionary mou.
a67804f33561a55abe5373e72ff890d5d2b5fc9b
rochaalexandre/complete-python-course
/content/6_files/csv_read.py
343
4.0625
4
file = open('csv_data.txt', 'r') lines = file.readlines() file.close() lines = [line.strip() for line in lines[1:]] for line in lines: data = line.split(',') name = data[0].title() age = data[1] university = data[2].title() degree = data[3].capitalize() print(f'{name} is {age}, studying {degree} at {university}.')
1815eb67806f1f25c2e864812b6707ca03e5aebd
cpvhunter/LeetCode
/1003.py
461
3.921875
4
class Solution: def isValid(self, S: str) -> bool: stk = list() for ch in S: stk.append(ch) if len(stk) >= 3 and "".join(stk[-3:]) == "abc": stk.pop() stk.pop() stk.pop() return not stk solution = Solution() print(solution.isValid("aabcbc")) print(solution.isValid("abcabcababcc")) print(solution.isValid("abccba")) print(solution.isValid("cababc"))
4fd851c4b53d7aee7a46df86a890bd75dcbb3aec
JDavid121/Script-Curso-Cisco-Python
/218 assert instruction.py
469
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 27 23:48:58 2020 ASSERTION INSTRUCTION @author: David """ import math x = float(input("Enter a number: ")) assert x >= 0.0 x = math.sqrt(x) print(x) # you may want to put it into your code where you want to be # absolutely safe from evidently wrong data, and where you # aren't absolutely sure that the data has been carefully # examined before (e.g., inside a function used by someone else)
a64fafffc56d46d65214cc9bc5c67cb41198b7e5
bmoretz/Daily-Coding-Problem
/py/dcp/problems/linkedlist/del_middle.py
676
4.09375
4
'''Delete Middle Node. Implement an algorithm to delete a node in the middle (i.e., any node but the first and last, not necessarily the exact middle) of a singly linked list, given only access to that node. Example: Input: the node c from the linked list a -> b -> c -> d -> e -> f Result: nothing is returned, but the new linked list looks like: a -> b -> d -> e -> f ''' ''' O(N) run-time, O(1) space.''' def delete_middle1(node): if node == None: return None prev = None while node.next != None: node.next.data, node.data = node.data, node.next.data prev = node node = node.next if prev != None: prev.next = None
856cf90b0dc84d2ee834ae957f2ca0da98aa3776
Submitty/Submitty
/python_submitty_utils/submitty_utils/string_utils.py
277
3.859375
4
import random import string def generate_random_string(length): """ Return an uppercase string of n letters. :return: :rtype: string """ choices = string.ascii_letters + string.digits return ''.join(random.choice(choices) for i in range(length))
99f5434f1f32c198e2f79d2a7d3c79a8f562a7d4
coders-as/as_coders
/20210629_COS_Pro_1급_기출_3차/3차 문제/3차 1급 2_initial_code.py
1,148
3.5
4
def func_a(arr, s): return s in arr def func_b(s): length = len(s) for i in range(length // 2): if s[i] != s[length - i - 1]: return False return True def func_c(palindromes, k): palindromes = sorted(palindromes) if len(palindromes) < k: return "NULL" else: return palindromes[k - 1] def solution(s, k): palindromes = [] length = len(s) for start_idx in range(length): for cnt in range(1, length - start_idx + 1): sub_s = s[start_idx : start_idx + cnt] if func_@@@(@@@) == True: if func_@@@(@@@) == False: palindromes.append(sub_s) answer = func_@@@(@@@) return answer #아래는 테스트케이스 출력을 해보기 위한 코드입니다. s1 = "abcba" k1 = 4 ret1 = solution(s1, k1) #[실행] 버튼을 누르면 출력 값을 볼 수 있습니다. print("solution 함수의 반환 값은", ret1, "입니다.") s2 = "ccddcc" k2 = 7 ret2 = solution(s2, k2) #[실행] 버튼을 누르면 출력 값을 볼 수 있습니다. print("solution 함수의 반환 값은", ret2, "입니다.")
8b5372f1dcaad5e2ba87a70a9da1039f5507173e
AbdurRehman-coder/VsCode-programs
/python programs/problem_1.py
730
3.71875
4
import math ''' # solve the problem with help of loop y = [] for i in range(0,8): y.append(i**2 - i/(i+3)) print(y) ''' # With help of comprehension loops c = [(x**2) - (x/(x+3)) for x in range (8)] print(c) # Create a list with following elements a = [ 9, 1, 3**2, 7/4, 0, 0.25 * 8.5, 0.8, math.sin(3.14/8)] print(a) # Create a list with first element 3 and last element 27 # will increment 4 b/w them. y = [] for n in range(3, 28, 4): y.append(n) print(y) c = [ n for n in range(3, 28, 4)] print(c) # Create a list of 8 equally spaced elements b/w 68 and 12. #inc = int((68-12)/7) c = [ n for n in range(68,11, -7)] print(c) x = [-4, -1, 2, 5] y = [8] z = [14,18,22,26,30] for a,b,c in zip(x,y,z): print(a,b,c)
515606667b36ea517c8a8a434aa3f7478d761593
Ima8/CheckIO_Solutions
/Largest Rectangle in a Histogram.py
340
3.53125
4
def largest_histogram(histogram): ans = 0 for i in range(len(histogram)): for k in range(histogram[i] + 1): for j in range(i,len(histogram)): if histogram[j] < k : break if ans < (j - i + 1 ) * k : ans = (j - i + 1 ) * k return ans
223816b5680b50bf0fb16ded3608624d3f45412c
PoojaPracash/word_search_project
/max_comments.py
1,159
3.90625
4
# This program outputs the person who tweeted the most # A class to initialize dictionary and to perform basic functions class DictInit: # Constructor def __init__(self): self.iDict = dict() # Function to add item to dictionary def addItem(self, x): if x in self.iDict: self.iDict[x] += 1 else: self.iDict[x] = 1 return self.iDict # Function to find max tweeted person def findMax(self, y): return [key for key in oDict if oDict[key] == max(oDict.values())] if __name__ == '__main__': # create an object from class dictionary = DictInit() # Total number of test cases test_cases = int(input()) # Final resultant list with max tweeted person's name Final_list = [] for i in range(test_cases): tweet_num = int(input()) for i in range(tweet_num): a = input().split() b = a[0].strip() oDict = dictionary.addItem(a[0]) m = dictionary.findMax(oDict) for item in m: Final_list.append(item) for name in Final_list: print(name, "%d" % oDict[name])
6698d38e0796425ac01e9239e3743eae16e4c648
srikanthn81n/Scripting_Basics_Project
/calculator.py
474
3.9375
4
from operator import pow, add, sub, mul, truediv operators = { '+' : add, '-' : sub, '*' : mul, '/' : truediv } #print(operators) def calculate(s): if s.isdigit(): return float(s) for k in operators.keys(): left, operator, right = s.partition(k) if operator in operators: return operators[operator](calculate(left), calculate(right)) calc = input("Enter required Calculation:\n") #type(calculate(calc)) print("Answer is: " + str(calculate(str(calc))))
8948b88ec7ed20968695dbad8eab966d6ea77aab
Ming-H/leetcode
/424.longest-repeating-character-replacement.py
927
3.5
4
# # @lc app=leetcode id=424 lang=python3 # # [424] Longest Repeating Character Replacement # # @lc code=start class Solution: def characterReplacement(self, s: str, k: int) -> int: l = 0 c_frequency = {} longest_str_len = 0 for r in range(len(s)): if not s[r] in c_frequency: c_frequency[s[r]] = 0 c_frequency[s[r]] += 1 # Replacements cost = cells count between left and right - highest frequency cells_count = r - l + 1 if cells_count - max(c_frequency.values()) <= k: longest_str_len = max(longest_str_len, cells_count) else: c_frequency[s[l]] -= 1 if not c_frequency[s[l]]: c_frequency.pop(s[l]) l += 1 return longest_str_len # @lc code=end
96ae128268fae4c2a513c567b49343b9d82983ff
wilsonduarte/misionTIC
/semana_1/ejercicios/ejercicio_2.py
324
3.984375
4
def calcular_factorial(entero): entero = int(entero) if entero <= 1: return 1 factorial = entero * calcular_factorial(entero-1) return factorial entero = input("Ingrese un número entero positivo: ") factorial = calcular_factorial(entero) print("El factorial de: ", entero, "es: ", factorial)
cc9b9e78afa836662fcc4f9aab0118571a99e8b5
csvw/CNN-Numpy-Implementation
/CNN2/Relu.py
918
4.03125
4
import numpy as np # Citation: gradient for Relu obtained from the following article: # https://medium.com/@karpathy/yes-you-should-understand-backprop-e2f06eab496b class Relu: def __init__(self): self.last_input = 0 self.last_batch = 0 # def apply(self, input_vector): # self.last_input = input_vector # input_vector[input_vector <= 0] = 0 # return input_vector def apply(self, input_tensor): self.last_batch = input_tensor #print("Changed? " + str(np.sum(input_tensor[0]))) input_tensor[input_tensor <= 0] = 0 #print("Changed: " + str(np.sum(input_tensor[0]))) return input_tensor # def backprop(self, dLoss_dOutput): # dLoss_dOutput[self.last_input <= 0] = 0 # return dLoss_dOutput def backprop(self, dLoss_dOutput): dLoss_dOutput[self.last_batch <= 0] = 0 return dLoss_dOutput
35334661846e10b552aed771a47e6ae14f44f58c
kashifihsan/MyPython
/intro01.py
3,143
3.671875
4
import sys #print('hello worlccd') #courses = ['history','math','english','urdu'] #print(courses) #def add(a,b): # return a+b #a = 10 #def changeit(b): # print("The value of b is",b) # b=100 # print("The new value of b is",b) #changeit(a) #a = [10,20,30] #def func(d): # print("The value of d is",d) # d[0] = 90 # print("The new value of d is",d) #func(a) #f = open("D:/testyfy.txt",'r') #print(f.readline()) #print(f.readline()) # class ClassName: # var = "this is a class variable" # def func(self): # print("IM inside the class") # obj1 = ClassName() # print(obj1.var) # obj1.func() # obj2 = ClassName() # obj2.var = "this is update ...." # print(obj1.var,"\n",obj2.var) # obj2.func() # print(ClassName.var) # class student: # def __init__(self,name,branch,year): # self.n = name # self.b = branch # self.y = year # def print_method(self): # print("Name :", self.n) # print("branch :", self.b) # print("year :", self.y) # obj = student("kash", "VFTD", "htr") # obj.print_method() # # ********** # class Vehicle: # name = "" # kind = "car" # color = "" # value = 100.00 # def description(self): # desc_str = "%s is a %s %s worth $%.3f." % (self.name, self.kind, self.color, self.value) # return desc_str # car1 = Vehicle() # car2 = Vehicle() # car1.name = "Ferrari" # car1.kind = "Red convertible" # car1.color = "Red" # car1.value = 70000.00 # car2.name = "Jeep" # car2.kind = "Van" # car2.color = "Blue" # car2.value = 15000.00 # print(car1.description()) # print(car2.description()) # ************* # class fruit: # def __init__(self): # print("I am fruit") # class citrus(fruit): # def __init__(self): # super().__init__() # print("I am citrus as well") # obj = citrus() # ************ # class A: # x = 1 # class B(A): # pass # class C(B): # pass # tr = C() # print(tr.x) # import numpy as np # x = np.arange(16).reshape(4,4) # print(x) # a = ['m','o','n','t','y',' ','p'] # print(a[0:4]) import pandas as pd # data = [1,2,3,4] # series1 = pd.Series(data) # print(series1) # print(type(series1)) # series1 = pd.Series(data, index = [['a','b','c','d'],['a','b','w','d'],['a','b','w','d']]) # print(series1) # Dictionary into DataFrame: # dictionary = {'fruits':['mangoes','apples','bananas'],'count':[10,20,30]} # df = pd.DataFrame(dictionary) # print(df) # Making Dataframe from lists player = ['Player1','Player2','Player3'] point = [8,9,6] title = ['Game1','Game2','Game3'] df1 = pd.DataFrame({'Player':player, 'Points':point, 'Title':title}) print(df1,'\n') player = ['Player1','Player5','Player6'] power = ['Punch','Kick','Elbow'] title = ['Game1','Game5','Game6'] df2 = pd.DataFrame({'Player':player, 'Power':power, 'Title':title}) print(df2, '\n') # print(df1.merge(df2, on = 'Player', how = 'inner'),'\n') # print(df1.merge(df2, on = 'Title', how = 'inner'),'\n') # print('left merge with player') # print(df1.merge(df2, on = 'Player', how = 'left')) # print('Right merge with player') # print(df1.merge(df2, on = 'Player', how = 'right')) print('outer merge with player') print(df1.merge(df2, on = 'Player', how = 'outer'))
15bb04cb94d170573cb692ddeab7a0041b52d2ab
Anubhav82/Python
/seven.py
1,446
4.40625
4
# *args # def add(a,b): # return a+b # def new_add(*args): # total = 0 # When we use *args it stores the value in tuple. # for i in args: # total += i # return total # print(new_add(1,2,3,3,44,5,)) # when we give argument in list and tuple # simply we have to do this # l =[1,2,3,4] # print(new_add(*l)) # to unpacking the list. # def cube(n,l): # if l: # return [i**n for i in l] # else: # return "pass" # list1= [1,2,3] # num = 3 # print(cube(num,list1)) # # **kwargs # def func(**kwargs): # for k,v in kwargs.items(): # When we use *kwargs it stores the value in dictionary. # print(f"{k} : {v}") # func(first_name = 'anubhav', last_name = 'choudhary') #PADK # parameters # *args # default parameters # **kwargs # def func(name, *args, last_name = 'unknowm', **kwargs): # print(name) # print(*args) # print(last_name) # print(**kwargs) # func('anubhav', 1,2,3, a= 2,b=3) # EXERCISE - 1 # def func(l,**kwargs): # if kwargs.get('reverse_str') == True: # return [name[::-1].title() for name in l] # else: # return [name.title() for name in l] # print(func(['anubhav', 'choudhary'],reverse_str = True))
8585ca9e470b358598741385a41b336dd4962b09
rahulsomani26/python-istanbul
/day1/first.py
879
4.40625
4
# This is a single line comment ''' Multiline comment can span accross multiple lines ''' """ This is also a multiline comment """ # num1 = 10 # num2 = 2 # sum = num1 + num2 # # print(sum) # minus = num1 - num2 # mult = num1 * num2 # divi = num1/num2 # division operator will always give u a floating point result ( Float data type ) # ans = num1//num2 # Floor Division operator # print(sum,minus,mult,divi,ans) # remainder = 5 % 2 # 5/2 remainder is 1 # print(f' The remainder of dividing {5} by {2} is {remainder}') ''' The f-string prefix anything enclosed within '' or " " with f use {} placeholders to hold values within {} u supply the variable name ''' # name = 'Amin' # age = 24 # print(f'Hello {name} your age is {age}') print(5**3)
1da22ac15c85fc224357e48fe431f06c7590cac9
benjaV2/POLYRIZE
/MagicList/magic_list.py
1,191
3.84375
4
from dataclasses import dataclass class MagicList: def __init__(self, cls_type=None): self.cls_type = cls_type self.array = [] self.max_index = 0 def __getitem__(self, item): if item > self.max_index: raise IndexError("list index out of range") if item == self.max_index: if self.cls_type is None: raise IndexError("list index out of range") else: new_item = self.cls_type() self.array.append(new_item) self.max_index += 1 return new_item else: return self.array[item] def __setitem__(self, key, value): if key > self.max_index: raise IndexError("list index out of range") elif key == self.max_index: self.max_index += 1 self.array.append(value) else: self.array[key] = value def __repr__(self): return str(self.array) if __name__ == "__main__": @dataclass class Person: age: int = 1 a = MagicList(cls_type=Person) a[0].age = 5 # a[1] = 3 # a[0] = 2 print(a)
639444989124bccdd3824c1920237b99c213c06d
kampanella0o/python_basic
/lesson1/l1_ex2.py
130
3.8125
4
number1 = input("Number one: ") number2 = input("Number two: ") number3 = input("Number three: ") print(number3, number2, number1)
d2b1efbb8723730f7ac10dd81a6f8f87a8832c16
bestgopher/dsa
/stack_queue/stack_usage.py
1,416
3.65625
4
from stack_queue.stack import ArrayStack def reverse_file(filename): """Overwrite given file with its contents line-by-line reversed.""" s = ArrayStack() original = open(filename) for line in original: s.push(line.rstrip("\n")) original.close() # now we overwrite with contents in LIFO order output = open(filename + '_test.txt', "w") while not s.is_empty(): output.write(s.pop() + '\n') output.close() def is_matched(expr): """Return True if all delimiters are properly matched; False otherwise.""" lefty = "({[" rightly = ")}]" s = ArrayStack() for i in expr: if i in lefty: s.push(i) else: if s.is_empty() or lefty.index(s.pop()) != rightly.index(i): return False return s.is_empty() def is_matched_html(html: str): """Return True if all HTML tags are properly match; False otherwise.""" s = ArrayStack() j = html.find("<") while j != -1: k = html.find(">", j + 1) if k == -1: return False tag = html[j + 1: k] if not tag.startswith("/"): s.push(tag) else: if s.is_empty() or tag[1:] != s.pop(): return False j = html.find("<", k + 1) return s.is_empty() if __name__ == '__main__': reverse_file("stack.py") print(is_matched("([]){([])}[]"))
92a1264346f08994b98f8bb09305fd4357acab2e
swagmagician/classondemand
/lambda/custom/number_intent.py
2,766
3.5625
4
import random def number_intent(handler_input): """Handler for processing guess with target.""" # type: (HandlerInput) -> Response session_attr = handler_input.attributes_manager.session_attributes target_num = session_attr["guess_number"] guess_num = int(handler_input.request_envelope.request.intent.slots[ "number"].value) number_1 = session_attr['number_1'] number_2 = session_attr['number_2'] session_attr["no_of_guesses"] += 1 session_attr["counter"] += 1 ans = number_1 + number_2 if guess_num == number_1 + number_2: session_attr['number_1'] = random.randint(0, 100) session_attr['number_2'] = random.randint(0, 100) session_attr["game_score"] += 1 if session_attr["counter"] == 3: speech_text = ( "Correct. Congratulations! You scored a {} out of 3 points! Thank you for playing!".format(session_attr["game_score"])) reprompt = "Say yes to start a new game or no to end the game" session_attr["game_state"] = "ENDED" handler_input.attributes_manager.persistent_attributes = session_attr handler_input.attributes_manager.save_persistent_attributes() else: speech_text = ( "Correct. Your next question is what is {} + {}".format( session_attr['number_1'], session_attr["number_2"])) reprompt = "Say yes to start a new game or no to end the game" elif guess_num != number_1 + number_2: session_attr['number_1'] = random.randint(0, 100) session_attr['number_2'] = random.randint(0, 100) if session_attr["counter"] == 3: speech_text = ( "Incorrect. The correct answer is: {}. Congratulations, you finished the game! You scored a {} out of 3 points! Thank you for playing!".format( ans, session_attr["game_score"])) reprompt = "Say yes to start a new game or no to end the game" session_attr["game_state"] = "ENDED" handler_input.attributes_manager.persistent_attributes = session_attr handler_input.attributes_manager.save_persistent_attributes() else: speech_text = ( "Incorrect. The correct answer is: {}. Your next question is what is {} + {}".format( ans, session_attr['number_1'], session_attr["number_2"])) reprompt = "Say yes to start a new game or no to end the game" else: speech_text = "Sorry, I didn't get that. Try saying a number." reprompt = "Try saying a number." handler_input.response_builder.speak(speech_text).ask(reprompt) return handler_input.response_builder.response
fdd4c17c52eca177e69c32c130d1e99f5cdd1d39
QingmuDeng/SoftDesSP18_FinalProject
/CNN/resize.py
7,172
3.625
4
""" Creates and pickles the dataset that is fed into the cnnImage script. Running make_dataset() creates the full dataset for testing on a supercomputer, running make_small_dataset() creates a smaller training/test set for testing the CNN on a PC. """ import cv2 import os, sys, glob, pickle import numpy as np def reshape_img(filename, dim): """ Takes filepath, reads image, reshapes to a 64x64 image, reads all RGB values and converts to a 2d array, returns the array. filename: a str of the filepath to the image dim: an int of the desired dimension of the output image (64 in this case). returns: np array of dtype=float32. """ #Initialize the numpy array img_array = np.zeros(shape=(dim*dim,3)) dimension = (dim, dim) #Read the image image = cv2.imread(filename) #Convert image to 64x64 square resized = cv2.resize(image, dimension, interpolation = cv2.INTER_AREA) count = 0 #Loops through every pixel, converts from BGR to RGB, normalizes range to be between 0-1 instead of 0-255, stores in a row of img_array. for length in range(dim): for height in range(dim): pixel = resized[length, height] blue, green, red = pixel[0], pixel[1], pixel[2] r, g ,b = red/255, green/255, blue/255 img_array[count] = [r, g, b] count += 1 return np.float32(img_array) def flip_img(filename, dim): """ Takes filepath, reads image, reshapes to a 64x64 image and flips horizontally over midline, reads all RGB values and converts to a 2D array. """ #Initialize numpy array img_array = np.zeros(shape=(dim*dim, 3)) dimension = (dim, dim) #Read the image load =cv2.imread(filename) #Convert image to 64x64 square resized = cv2.resize(load, dimension, interpolation = cv2.INTER_AREA) #Flip image image = cv2.flip(load, 1) count = 0 #Loops through every pixel, converts from BGR to RGB, normalizes range to be between 0-1 instead of 0-255, stores in a row of img_array. for length in range(dim): for height in range(dim): pixel = resized[length, height] blue, green, red = pixel[0], pixel[1], pixel[2] r, g ,b = red/255, green/255, blue/255 img_array[count] = [r, g, b] count += 1 return np.float32(img_array) def make_dataset(save_path='dataset/scaled_data'): """Takes the save_path as an argument. Returns the full dataset in 4 pickled files: train_img_array, train_label, test_img_array, testlabel, where each is a numpy array. train_img_array and test_img_array: contain RGB pixel values of every img in the dataset trainlabel and testlabel: contain the appropriate label for each image in the dataset stored as int32. 0=happiness, 1=sadness, 2=violence, 3=mysterious.""" #Initialize the numpy arrays trainlabel= np.zeros(shape=(4000,1), dtype = 'int32') testlabel = np.zeros(shape=(2284,1), dtype='int32') train_img_array = np.zeros(shape=(4000,32*32, 3), dtype= 'float32') test_img_array = np.zeros(shape=(2284, 32*32, 3), dtype= 'float32') #Initialize the counters train_count = 0 test_count = 0 keywords = ['happiness', 'sadness', 'violence', 'mysterious'] #Loop through the keywords, convert each image into a numpy matrix of pixel intensities, add result and corresponding label to the appropriate dataset array. for keyword in keywords: #Initialize counters to track distribution of training and test images per keyword. train_num_images = 0 test_num_images = 0 label = None print(keyword) #Loops through each image in the keyword folder for infile in glob.glob("dataset/"+keyword+"/*.jpg"): index = keywords.index(keyword) #Sorts first 500 images into training set, all others go to test set if train_num_images < 1000: train_img_array[train_count,:,:] = reshape_img(infile, 32) #print(train_img_array[train_count,:,:]) trainlabel[train_count] = index #train_num_images += 1 train_count += 1 train_img_array[train_count,:,:] = flip_img(infile, 32) #stores flipped image as np array trainlabel[train_count] = index train_num_images += 2 train_count += 1 else: test_img_array[test_count] = reshape_img(infile, 32) testlabel[test_count] = index #test_num_images +=1 test_count += 1 test_img_array[test_count,:,:] = flip_img(infile, 32) #stores flipped image as np array testlabel[test_count] = index test_num_images +=2 test_count += 1 print(str(train_num_images), str(test_num_images)) #Saves final arrays into files f = open('train_img_array.pckl', 'wb') pickle.dump(train_img_array, f) f.close() f2 = open('test_img_array.pckl', 'wb') pickle.dump(test_img_array, f2) f2.close() f3 = open('trainlabel.pckl', 'wb') pickle.dump(trainlabel, f3) f3.close() f4 = open('testlabel.pckl', 'wb') pickle.dump(testlabel, f4) f4.close() def make_small_dataset(save_path='dataset/scaled_data'): trainlabel= np.zeros(shape=(200,1), dtype='int32') testlabel = np.zeros(shape=(100,1), dtype='int32') train_img_array = np.zeros(shape=(200,64*64, 3), dtype='float32') test_img_array = np.zeros(shape=(100, 64*64, 3), dtype='float32') train_count = 0 test_count = 0 keywords = ['happiness', 'sadness', 'violence', 'mysterious'] #Loops through each keyword for keyword in keywords: count=0 label = None print(keyword) #Loops through each image in the folder, converts to matrix, finds label, and adds to appropriate dataset for infile in glob.glob("dataset/"+keyword+"/*.jpg"): index = keywords.index(keyword) #Sorts first 50 into training set, next 25 into test, then moves on to next keyword if count < 50: train_img_array[train_count,:,:] = reshape_img(infile, 64) trainlabel[train_count] = index count += 1 train_count += 1 elif 50<=count<75: test_img_array[test_count] = reshape_img(infile, 64) testlabel[test_count] = index count += 1 test_count += 1 else: break print(str(train_count), str(test_count)) #save the data f = open('train_img_array_smol.pckl', 'wb') pickle.dump(train_img_array, f) f.close() f2 = open('test_img_array_smol.pckl', 'wb') pickle.dump(test_img_array, f2) f2.close() f3 = open('trainlabel_smol.pckl', 'wb') pickle.dump(trainlabel, f3) f3.close() f4 = open('testlabel_smol.pckl', 'wb') pickle.dump(testlabel, f4) f4.close() if __name__ == "__main__": #print(reshape_img("dataset/happiness/30631585.jpg", 64)) make_dataset()
75ea976e7e40ed281de87496ca7ff3930e2e4ac8
Systemad/OOP-Python
/classes/classTest.py
386
3.765625
4
class friends: def __init__(self, namn, postNum, postOrt, address): self.namn = namn self.postNum = postNum self.postOrt = postOrt self.address = address def allInfo(self): return '{} {} {} {}'.format(self.namn, self.postNum, self.postOrt, self.address) friend1 = friends('Dan', 'Hejhe', '2121', 'Hejgatan') print(friend1.allInfo())
bc0863294188fab33e4646da4b3a8ed636057fa7
microgenios/cod
/03/xx/07-sklearn/c-ipython/2015/2015lab3/Lab3-probability.py
22,123
3.65625
4
#!/usr/bin/env python # coding: utf-8 # ## Probability and Distributions # In[18]: # The %... is an iPython thing, and is not part of the Python language. # In this case we're just telling the plotting library to draw things on # the notebook, instead of on a separate window. get_ipython().magic(u'matplotlib inline') # See all the "as ..." contructs? They're just aliasing the package names. # That way we can call methods like plt.plot() instead of matplotlib.pyplot.plot(). import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as plt import pandas as pd import time pd.set_option('display.width', 500) pd.set_option('display.max_columns', 100) pd.set_option('display.notebook_repr_html', True) import seaborn as sns sns.set_style("whitegrid") sns.set_context("poster") # ### What is probability? # # Suppose you were to flip a coin. Then you expect not to be able to say whether the next toss would yield a heads or a tails. You might tell a friend that the odds of getting a heads is equal to to the odds of getting a tails, and that both are $1/2$. # # This intuitive notion of odds is a **probability**. # # Consider another example. If we were tossing a 'fair' six-sided dice, we may thus equivalently say that the odds of the dice falling on any one of its sides is $1/6$. Indeed if there are $C$ different equally likely possibilities, we'd expect that the probability of any one particular outcome would be $1/C$. # # The examples of the coin as well as the dice illustrate the notion of probability springing from **symmetry**. Here we think of probability of of the number 4 on the dice as the ratio: # # $$\frac{Number\: of\: cases\: for\: number\: 4}{number\: of\: possibilities} = \frac{1}{6},$$ # assuming equally likely possibilities. # # # # #### Probability from a model # # But now think of an event like an election, say a presidential election. You cant exactly run multiple trials of the election: its a one-off event. But you still want to talk about the likelyhood of a candidate winning. However people do make **models** of elections, based on inputs such as race, age, income, sampling polls, etc. They assign likeyhoods of candidates winning and run large numbers of **simulations** of the election, making predictions based on that. Forecasters like Nate Silver, Sam Wang, And Drew Linzer, made incredibly successfull predictions of the 2012 elections. # # Or consider what a weather forecaster means when he or she says there is a 90% chance of rain today. Presumably, this conclusion has been made from many computer **simulations** which take in the weather conditions known in the past, and propagated using physics to the current day. The simulations give different results based on the uncertainty in the measurement of past weather, and the inability of the physics to capture the phenomenon exactly (all physics is some approximation to the natural world). But 90% of these simulations show rain. # # In all of these cases, there is either a model (a fair coin, an election forecasting model, a weather differential equation), or an experiment ( a large number of coin tosses) that is used to **estimate** a probability, or the odds, of an **event** $E$ occuring. # # ### Testing a model # # We can test the model of a fair coin by having carried out a large number of coin flips. You would do, or imagine doing, a large number of flips or **trials** $N$, and finding the number of times you got heads $N_H$. Then the probability of getting heads would be # $$\frac{N_H}{N}.$$ # # #### Probability as frequency # # But, if you didnt know about the fairness of the coin, you can think of another notion probability as a **relative frequency**: if there are multiple ways an **event** like the tossing of a coin can happen, lets look at multiple trials of the event and see the fraction of times one or other of these ways happened. # #### Simulating the results of the model # # We dont have a coin right now. So let us **simulate** this process on a computer. To do this we will use a form of the **random number generator** built into `numpy`. In particular, we will use the function `np.random.choice`, which will with equal probability for all items pick an item from a list (thus if the list is of size 6, it will pick one of the six list items each time, with a probability 1/6). # In[19]: def throw_a_coin(N): return np.random.choice(['H','T'], size=N) throws=throw_a_coin(40) print "Throws:"," ".join(throws) print "Number of Heads:", np.sum(throws=='H') print "p1 = Number of Heads/Total Throws:", np.sum(throws=='H')/40. # Notice that you do not necessarily get 20 heads. # # Now say that we run the entire process again, a second **replication** to obtain a second sample. Then we ask the same question: what is the fraction of heads we get this time? Lets call the odds of heads in sample 2, then, $p_2$: # In[20]: throws=throw_a_coin(40) print "Throws:"," ".join(throws) print "Number of Heads:", np.sum(throws=='H') print "p2 = Number of Heads/Total Throws:", np.sum(throws=='H')/40. # Let's do many more trials # In[21]: throws=throw_a_coin(10000) print "First 1000 Throws:"," ".join(throws)[:1000] print "Number of Heads:", np.sum(throws=='H') print "p for 10,000 = Number of Heads/Total Throws:", np.sum(throws=='H')/10000. # The larger number of trials we do, the closer we seem to get to half the tosses showing up heads. Lets see this more systematically: # In[22]: trials=[10, 20, 50, 70, 100, 200, 500, 800, 1000, 2000, 5000, 7000, 10000] plt.plot(trials, [np.sum(throw_a_coin(j)=='H')/np.float(j) for j in trials], 'o-', alpha=0.6); plt.xscale("log") plt.axhline(0.5, 0, 1, color='r'); plt.xlabel('number of trials'); plt.ylabel('probability of heads from simulation'); plt.title('frequentist probability of heads'); # Thus, the true odds **fluctuate** about their long-run value of 0.5, in accordance with the model of a fair coin (which we encoded in our simulation by having `np.random.choice` choose between two possibilities with equal probability), with the fluctuations becoming much smaller as the number of trials increases. These **fluctations** are what give rise to probability distributions. # # Each finite length run is called a **sample**, which has been obtained from the **generative** model of our fair coin. Its called generative as we can use the model to generate, using simulation, a set of samples we can play with to understand a model. # ### A simple Election Model # # In the last section, we made a simple simulation of a coin-toss on the computer from a fair-coin model which associated equal probability with heads and tails. Let us consider another model here, a table of probabilities that [PredictWise](http://www.predictwise.com/results/2012/president) made on October 2, 2012 for the US presidential elections. # PredictWise aggregated polling data and, for each state, estimated the probability that the Obama or Romney would win. Here are those estimated probabilities: # In[23]: predictwise = pd.read_csv('predictwise.csv').set_index('States') predictwise.head() # Each row is the probability predicted by Predictwise that Romney or Obama would win a state. The votes column lists the number of electoral college votes in that state. # # Remember that simulation is used in different ways in the modelling process. Simulations might be used to propagate differential equations which describe the weather from different initial conditions. In this case they are used to create the model. In the coin flips case, they are used to illustrate the predictions of the model of a fair coin. This example is in the same spirit: we are given a (somehow obtained) list of win probabilities for the states of the US. # In the case of the tossed coins, even though we had a model which said that the probability of heads was 0.5, there were sequences of flips in which more or less than half the flips were heads. Similarly, here, if the probability of Romney winning in Arizona is 0.938, it means that if somehow, there were 10000 replications with an election each, Romney would win in 938 of those Arizonas **on the average** across the replications. And there would be some samples with Romney winning more, and some with less. We can run these **simulated** universes on a computer though not in real life. # # #### Simulating the model # # To do this, # we will assume that the outcome in each state is the result of an independent coin flip whose probability of coming up Obama is given by the Predictwise state-wise win probabilities. Lets write a function `simulate_election` that uses this **predictive model** to simulate the outcome of the election given a table of probabilities. # # In the code below, each column simulates a single outcome from the 50 states + DC by choosing a random number between 0 and 1. Obama wins that simulation if the random number is $<$ the win probability. If he wins that simulation, we add in the electoral votes for that state, otherwise we dont. We do this `n_sim` times and return a list of total Obama electoral votes in each simulation. # In[24]: def simulate_election(model, n_sim): simulations = np.random.uniform(size=(51, n_sim)) obama_votes = (simulations < model.Obama.values.reshape(-1, 1)) * model.Votes.values.reshape(-1, 1) #summing over rows gives the total electoral votes for each simulation return obama_votes.sum(axis=0) # The following code takes the necessary probabilities for the Predictwise data, and runs 10000 simulations. If you think of this in terms of our coins, think of it as having 51 biased coins, one for each state, and tossing them 10,000 times each. # # We use the results to compute the number of simulations, according to this predictive model, that Obama wins the election (i.e., the probability that he receives 269 or more electoral college votes) # In[25]: result = simulate_election(predictwise, 10000) print (result >= 269).sum() # In[26]: result # There are roughly only 50 simulations in which Romney wins the election! # # #### Displaying the prediction # # Now, lets visualize the simulation. We will build a histogram from the result of `simulate_election`. We will **normalize** the histogram by dividing the frequency of a vote tally by the number of simulations. We'll overplot the "victory threshold" of 269 votes as a vertical black line and the result (Obama winning 332 votes) as a vertical red line. # # We also compute the number of votes at the 5th and 95th quantiles, which we call the spread, and display it (this is an estimate of the outcome's uncertainty). By 5th quantile we mean that if we ordered the number of votes Obama gets in each simulation in increasing order, the 5th quantile is the number below which 5\% of the simulations lie. # # We also display the probability of an Obama victory # # In[27]: def plot_simulation(simulation): plt.hist(simulation, bins=np.arange(200, 538, 1), label='simulations', align='left', normed=True) plt.axvline(332, 0, .5, color='r', label='Actual Outcome') plt.axvline(269, 0, .5, color='k', label='Victory Threshold') p05 = np.percentile(simulation, 5.) p95 = np.percentile(simulation, 95.) iq = int(p95 - p05) pwin = ((simulation >= 269).mean() * 100) plt.title("Chance of Obama Victory: %0.2f%%, Spread: %d votes" % (pwin, iq)) plt.legend(frameon=False, loc='upper left') plt.xlabel("Obama Electoral College Votes") plt.ylabel("Probability") sns.despine() # In[28]: plot_simulation(result) # The model created by combining the probabilities we obtained from Predictwise with the simulation of a biased coin flip corresponding to the win probability in each states leads us to obtain a histogram of election outcomes. We are plotting the probabilities of a prediction, so we call this distribution over outcomes the **predictive distribution**. Simulating from our model and plotting a histogram allows us to visualize this predictive distribution. In general, such a set of probabilities is called a **probability distribution** or **probability mass function**. # ### Random Variables # # From wikipedia: In probability theory, the **sample space** of an experiment or random trial is the set of all possible outcomes or results of that experiment. For one coin toss, [H,T] make up the sample space. # # A **random variable** is a mapping from a sample space to the set of real numbers. It assigns a real number to each outcome in the sample space. # # For example, consider the event of a coin toss that we have seen before. There are two outcomes in the sample space, a heads and a tails. We can ask the question, whats the probability of a heads or a tails? For an unbiased coin, these are, by symmettry, 1/2 each. The random variable here is the number of heads, and its probability is P(0)=1/2, and P(1)=1/2. # # Another random variable is the number of heads in two coin tosses. There, P(0)=1/4, P(1)=1/2, P(2)=1/4. # # Random variables provide the link from events and sample spaces to data, and it is their **probability distribution** that we are interested in. # # A random variable is called **discrete** if it has a countable number of values ^[The technical definition of countable is that there is a 1-1 correspondence with the integers 1,2,3...]. The number of heads in 2 coin tosses is a discrete random variable. # # ### Bernoulli Random Variables (in scipy.stats) # # The **Bernoulli Distribution** represents the distribution for coin flips. Let the random variable X represent such a coin flip, where X=1 is heads, and X=0 is tails. Let us further say that the probability of heads is p (p=0.5 is a fair coin). # # We then say: # # $$X \sim Bernoulli(p),$$ # # which is to be read as **X has distribution Bernoulli(p)**. The **probability distribution function (pdf)** or **probability mass function** associated with the Bernoulli distribution is # # \begin{eqnarray} # P(X = 1) &=& p \\ # P(X = 0) &=& 1 - p # \end{eqnarray} # # for p in the range 0 to 1. # The **pdf**, or the probability that random variable $X=x$ may thus be written as # # $$P(X=x) = p^x(1-p)^{1-x}$$ # # for x in the set {0,1}. # # The **mean**, or **expected value** of this distribution can be calculated analogously to the mean value of data by noting that X=1 happens with frequency p*N, and X=0 happens with frequency (1-p)*N, so we have # # $$\frac{p \times N \times 1+(1-p) \times N \times 0}{N}$$ # # and thus it is p. # # Let us engage in some term defining right now. $X$ is a random variable, and when we say $X=x$ we are asking "what if the random variable X takes the value x. $P(X=x)$ asks: what is the probability that the random variable X takes the value x. Finally $p$ is a parameter of the Bernoulli distribution, and as we have seen, one of the things we want to do in data analysis is: having seen some data, what can we infer to be the values of p, so that we can make future predictions for X. # In[29]: from scipy.stats import bernoulli #bernoulli random variable brv=bernoulli(p=0.3) brv.rvs(size=20) # Note: **some of the code, and ALL of the visual style for the distribution plots below was shamelessly stolen from https://gist.github.com/mattions/6113437/ **. # In[30]: event_space=[0,1] plt.figure(figsize=(12,8)) colors=sns.color_palette() for i, p in enumerate([0.1, 0.2, 0.5, 0.7]): ax = plt.subplot(1, 4, i+1) plt.bar(event_space, bernoulli.pmf(event_space, p), label=p, color=colors[i], alpha=0.5) plt.plot(event_space, bernoulli.cdf(event_space, p), color=colors[i], alpha=0.5) ax.xaxis.set_ticks(event_space) plt.ylim((0,1)) plt.legend(loc=0) if i == 0: plt.ylabel("PDF at $k$") plt.tight_layout() # Let us parse the intent of the above code a bit. We run 10,000 simulations. In each one of these simulations, we toss 51 biased coins, and assign the vote to obama is the output of `np.random.uniform` is less than the probablity of an obama win. # # ### Uniform Distribution (in numpy) # # The first thing to pick up on here is that `np.random.uniform` gives you a random number between 0 and 1, uniformly. In other words, the number is equally likely to be between 0 and 0.1, 0.1 and 0.2, and so on. This is a very intuitive idea, but it is formalized by the notion of the **Uniform Distribution**. # # We then say: # # $$X \sim Uniform([0,1),$$ # # which is to be read as **X has distribution Uniform([0,1])**. The **probability distribution function (pdf)** associated with the Uniform distribution is # # \begin{eqnarray} # P(X = x) &=& 1 \, for \, x \in [0,1] \\ # P(X = x) &=& 0 \, for \, x \notin [0,1] # \end{eqnarray} # # What assigning the vote to Obama when the random variable **drawn** from the Uniform distribution is less than the Predictwise probability of Obama winning (which is a Bernoulli Parameter) does for us is this: if we have a large number of simulations and $p_{Obama}=0.7$ , then 70\% of the time, the random numbes drawn will be below 0.7. And then, assigning those as Obama wins will hew to the frequentist notion of probability of the Obama win. But remember, of course, that in 30% of the simulations, Obama wont win, and this will induce fluctuations and a distribution on the total number of electoral college votes that Obama gets. And this is what we see in the histogram below. # ### Empirical Distribution # This is an **empirical Probability Mass Function** or **Probability Density Function**. The word **density** is strictly used when the random variable X takes on continuous values, as in the uniform distribution, rather than discrete values such as here, but we'll abuse the language and use the word probability distribution in both cases. # # Lets summarize: the way the density arose here that we did ran 10,000 tosses (for each state), and depending on the value, assigned the state to Obama or Romney, and then summed up the electoral votes over the states. # # There is a second, very useful question, we can ask of any such probability density: what is the probability that a random variable is less than some value. In other words: $P(X < x)$. This is *also* a probability distribution and is called the **Cumulative Distribution Function**, or CDF (sometimes just called the **distribution**, as opposed to the **density**). Its obtained by "summing" the probability density function for all $X$ less than $x$. # In[31]: CDF = lambda x: np.float(np.sum(result < x))/result.shape[0] for votes in [200, 300, 320, 340, 360, 400, 500]: print "Obama Win CDF at votes=", votes, " is ", CDF(votes) # In[32]: votelist=np.arange(0, 540, 5) plt.plot(votelist, [CDF(v) for v in votelist], '.-'); plt.xlim([200,400]) plt.ylim([-0.1,1.1]) plt.xlabel("votes for Obama") plt.ylabel("probability of Obama win"); # ### Binomial Distribution (in scipy.stats) # # Let us consider a population of coinflips, n of them to be precise, $x_1,x_2,...,x_n$. The distribution of coin flips is the binomial distribution. By this we mean that each coin flip represents a bernoulli random variable (or comes from a bernoulli distribution) with mean $p=0.5$. # # At this point, you might want to ask the question, what is the probability of obtaining $k$ heads in $n$ flips of the coin. We have seen this before, when we flipped 2 coins. What happens when when we flip 3? # # (This diagram is taken from the Feynman Lectures on Physics, volume 1. The chapter on probability is http://www.feynmanlectures.caltech.edu/I_06.html) # ![3 coin flips](3flips.png) # # We draw a possibilities diagram like we did with the 2 coin flips, and see that there are different probabilities associated with the events of 0, 1,2, and 3 heads with 1 and 2 heads being the most likely. # The probability of each of these events is given by the **Binomial Distribution**, the distribution of the number of successes in a sequence of $n$ independent yes/no experiments, or Bernoulli trials, each of which yields success with probability $p$. The Binomial distribution is an extension of the Bernoulli when $n>1$ or the Bernoulli is the a special case of the Binomial when $n=1$. # # $$P(X = k; n, p) = {n\choose k}p^k(1-p)^{n-k} $$ # # where # # $${n\choose k}=\frac{n!}{k!(n-k)!}$$ # # The expected value $E[X]=np$ and the variance is $Var[X]=np(1-p)$ # # How did we obtain this? The $p^k(1-p)^{n-k}$ comes simply from multiplying the probabilities for each bernoulli trial; there are $k$ 1's or yes's, and $n-k$ 0's or no's. The ${n\choose k}$ comes from counting the number of ways in which each event happens: this corresponds to counting all the paths that give the same number of heads in the diagram above. # # We show the distribution below for 200 trials. # In[33]: from scipy.stats import binom plt.figure(figsize=(12,6)) k = np.arange(0, 200) for p, color in zip([0.1, 0.3, 0.7, 0.7, 0.9], colors): rv = binom(200, p) plt.plot(k, rv.pmf(k), '.', lw=2, color=color, label=p) plt.fill_between(k, rv.pmf(k), color=color, alpha=0.5) q=plt.legend() plt.title("Binomial distribution") plt.tight_layout() q=plt.ylabel("PDF at $k$") q=plt.xlabel("$k$") # ### The various ways to get random numbers # # 1. `np.random.choice` chooses items randomly from an array, with or without replacement # 2. `np.random.random` gives us uniform randoms on [0.0,1.0) # 3. `np.random.randint` gives us random integers in some range # 4. `np.random.randn` gives us random samples from a Normal distribution, which we talk about later. # 5. `scipy.stats.distrib` gives us stuff from a distribution. Here distrib could be `binom` for example, as above. `distrib.pdf` or `distrib.pmf` give us the density or mass function, while `cdf` gives us the cumulaive distribution function. Just using `distrib` as a function with its params creates a random variable generating object, from which random variables can be generated in the form `distrib(params).rvs(size)`. # In[ ]:
3aaa84832f7444b3b16626a560853d5fa3613a09
Shobhits7/Programming-Basics
/Python/Pattern Programs/Alphabet_Pattern_02.py
442
3.84375
4
# Print the following pattern for the given N number of rows. # Pattern for N = 3 # A # BC # CDE # Input format : # Integer N (Total no. of rows) # Output format : # Pattern in N lines n = int(input()) i = 1 start_chr = chr(ord("A") + i - 1) while i <= n: j = 1 while j <= i: x = ord(chr(ord("A") + i - 1)) chra = chr(x + j - 1) print(chra, end="") x += 1 j += 1 print() i += 1
2e8b24e9cd5a2c268a265619330448fc55ae6315
hechty/datastructure
/4.10-hanoi-tower.py
487
3.953125
4
#! /usr/bin/env python3 # -*-coding:utf-8-*- from Stack import Stack step = 0 def hanoi(n, A, B, C): global step if n < 1: return else: hanoi(n-1, A, C, B) step += 1 print("第 {:^10d} 步: 从 {} 号杆移动 {:^4d} 号盘子到 {} 号杆".format(step, A,n,C)) hanoi(n-1, B, A, C) s = int(input("请输入汉诺塔阶数:")) hanoi(s, "1", "2", "3") print("{:^4d} 阶汉诺塔盘,需要移动 {:^20d} 步".format(s, step))
97d804e50f1fa44ca460e920e92bae0fc754fd89
ANKerD/competitive-programming-constests
/uri/upsolving/1031/code.py
150
3.515625
4
from math import log while True: n = int(raw_input()) if n == 0: break x = int(log(n,2)) n-=1<<(x) print n,x print 2*n+1
a8324df587e832f67a8e7b0b4d5ddb684e57fe76
Gaurav-Pande/DataStructures
/leetcode/binary-tree/deepest_leaves_sum.py
864
3.796875
4
# link: https://leetcode.com/problems/deepest-leaves-sum/ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def deepestLeavesSum(self, root): """ :type root: TreeNode :rtype: int """ track_sum = {} return self.dfs(root, 0, track_sum) def dfs(self, root,depth,track_sum): if not root: return if depth in track_sum: track_sum[depth] = track_sum[depth] + root.val else: track_sum[depth] = root.val self.dfs(root.left, depth+1,track_sum) self.dfs(root.right, depth+1, track_sum) return list(track_sum.items())[-1][1]
ff4690a7f870ad135423dbc27a8843a2d4a89f12
binchen15/leet-python
/recursion/prob1137.py
352
3.765625
4
# tribonacci number class Solution(object): def tribonacci(self, n): """ :type n: int :rtype: int """ tribo = [0, 1, 1] if n <= 2: return tribo[n] for i in range(3, n+1): new = tribo[-1] + tribo[-2] + tribo[-3] tribo.append(new) return tribo[-1]
b0e445b2ce394087cb38c468c53aa85a0b17cb06
SPiotr568/palindromes
/palindrome.py
875
3.859375
4
def readFile(file_name): words = [] with open(file_name) as f: for line in f: words.append(line.rstrip().lower()) return words def countPalindromes(words): n = 0 for w in words: print(f'Is \'{w}\' palindrome?') pal = "" for l in w: pal = l + pal print("Reversed: ",pal) if pal==w: n += 1 print("YES!") else: print("NO!") print("----------------------------------") return n fileName = "palindromes.txt" try: words = readFile(fileName) except FileNotFoundError as file_err: print(f'Error with \'{fileName}\' file! More info: ', file_err) except: print(f'Undefined error!') else: words = readFile(fileName) print("Words from txt file: ",words) print("Number of palindromes: ", countPalindromes(words))
d76a4a596beadaff59b44b4f1778ffe9a459a1d6
d-cole/ML_Numpy_TF_Misc
/logistic.py
4,666
3.703125
4
""" Methods for doing logistic regression.""" import numpy as np from utils import sigmoid def logistic_predict(weights, data): """ Compute the probabilities predicted by the logistic classifier. Note: N is the number of examples and M is the number of features per example. Inputs: weights: (M+1) x 1 vector of weights, where the last element corresponds to the bias (intercepts). data: N x M data matrix where each row corresponds to one data point. Outputs: y: :N x 1 vector of probabilities of being second class. This is the output of the classifier. """ # TODO: Finish this function Z = np.dot(data, weights[0:-1,:]) + weights[-1,:] y = (1/(1 + np.exp(-Z))) return y def evaluate(targets, y): """ Compute evaluation metrics. Inputs: targets : N x 1 vector of targets. y : N x 1 vector of probabilities. Outputs: ce : (scalar) Cross entropy. CE(p, q) = E_p[-log q]. Here we want to compute CE(targets, y) frac_correct : (scalar) Fraction of inputs classified correctly. """ # TODO: Finish this function log_pred = np.log2(1-y) log_targets = np.log2(targets) log_pred[log_pred==-np.inf]=0 log_targets[log_targets==-np.inf]=0 ce = -(np.dot((1-targets).T, log_pred) + np.dot(log_targets.T, (y)))[0,0] #Source: http://stackoverflow.com/questions/1623849/fastest-way-to-zero-out-low-values-in-array greater_05_idx = y > 0.5 less_05_idx = y < 0.5 y[greater_05_idx] = 0 y[less_05_idx] = 1 num_wrong = 0 for i in range(0, np.shape(y)[0]): if y[i] != targets[i]: num_wrong += 1 frac_correct = 1 - (float(num_wrong))/(np.shape(y)[0]) return ce, frac_correct def logistic(weights, data, targets, hyperparameters): """ Calculate negative log likelihood and its derivatives with respect to weights. Also return the predictions. Note: N is the number of examples and M is the number of features per example. Inputs: weights: (M+1) x 1 vector of weights, where the last element corresponds to bias (intercepts). data: N x M data matrix where each row corresponds to one data point. targets: N x 1 vector of targets class probabilities. hyperparameters: The hyperparameters dictionary. Outputs: f: The sum of the loss over all data points. This is the objective that we want to minimize. df: (M+1) x 1 vector of accumulative derivative of f w.r.t. weights, i.e. don't need to average over number of sample y: N x 1 vector of probabilities. """ y = logistic_predict(weights, data) if hyperparameters['weight_regularization'] is True: f, df = logistic_pen(weights, data, targets, hyperparameters) else: Z = np.dot(data, weights[:-1]) + weights[-1] f = (np.dot(targets.T, Z) + np.sum(np.log(1 + np.exp(-Z))))[0,0] p_c1 = (np.exp(-Z))/(1+np.exp(-Z)) df = (np.dot((targets - p_c1).T, data)).T df0 = np.sum(targets - (np.exp(-Z)/(1+np.exp(-Z)) )) df = np.vstack((df,df0)) return f, df, y def logistic_pen(weights, data, targets, hyperparameters): """ Calculate negative log likelihood and its derivatives with respect to weights. Also return the predictions. Note: N is the number of examples and M is the number of features per example. Inputs: weights: (M+1) x 1 vector of weights, where the last element corresponds to bias (intercepts). data: N x M data matrix where each row corresponds to one data point. targets: N x 1 vector of targets class probabilities. hyperparameters: The hyperparameters dictionary. Outputs: f: The sum of the loss over all data points. This is the objective that we want to minimize. df: (M+1) x 1 vector of accumulative derivative of f w.r.t. weights, i.e. don't need to average over number of sample """ w_decay = hyperparameters['weight_decay'] Z = np.dot(data, weights[:-1]) + weights[-1] p_c1 = (np.exp(-Z)) / (1+np.exp(-Z)) f = ((np.dot(targets.T, Z) + np.sum(np.log(1 + np.exp(-Z)))) - (np.dot(weights.T,weights)) / 2*w_decay)[0,0] df = (np.dot((targets - p_c1).T, data)).T - w_decay*(weights[:-1]) df0 = np.sum(targets - (np.exp(-Z)/(1+np.exp(-Z)) )) df = np.vstack((df,df0)) return f, df
6930d43f09bbaeeb9f43d0be44e3722a1c0b288f
zhlthunder/python-study
/python 语法基础/d20_进程和线程/进程/3.多任务.py
758
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #author: """ multiprocessing 是一个跨平台的多进程模块,提供了一个Process类来代表一个进程对象; """ from multiprocessing import Process from time import sleep import os ##子进程需要执行的代码 def run(arg): while True: #os.getpid() 获取当前进程id号 #os.getppid() 获取当前进程的父进程 print("sunck is a %s girl---%s--%s"%(arg,os.getpid(),os.getppid())) sleep(1.2) if __name__ == '__main__': print("主进程--%s"%(os.getpid())) #创建子进程 #target说明进程执行的任务 p=Process(target=run,args=("nice",),) p.start() while True: print("sunck is a good man") sleep(1)
2ffb1729d6105ad8d233620cc07111545f849931
SatyaanM/leetcode
/problem1.py
440
3.515625
4
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: list = [] for x in range(len(nums)): for y in range(len(nums)): if nums[x] == nums[y] and x == y: continue else: if nums[x] + nums[y] == target: list.append(x) list.append(y) return list
d07acf8efa6636e87c302511b655d18d485fad5c
ThyagoHiggins/LP-Phython
/Aulas e Exercicios/Exercicios/Lista 4/Questão 3.py
627
3.609375
4
cont= 0 cpf = str(input('Informe seu CPF (xxx.xxx.xxx-xx): ')).strip() if len(cpf) != 13: print(' Erro 1 : Quantidade de caracteres digitados fora do padrão!') cont +=1 if cpf[3] != "." or cpf[7] != "." or cpf[11] != "-": print("Erro 2 : Estrutura errada use xxx.xxx.xxx-xx!") cont += 1 else: if len(cpf[:3]) != 3 or len(cpf[4:7]) != 3 or len(cpf[8:11]) != 3 or len(cpf[12:]) != 2: print('Erro 3: Quantidade de números incorreto, use o formato xxx.xxx.xxx.xx!') cont += 1 else: print(f'{cpf} no formato válido') print (f'Foram encontrados {[cont]} erros na digitação')
b6e0e4da1dcda8c1ebacff1532a288b5cdd70b41
jsw166098/codingtestweb
/sourcecode/sys.stdin.readline.py
300
3.5625
4
# sys.stdin.readline import sys ## 문자열로 저장 str = sys.stdin.readline() print(type(str)) ### <class 'str'> ## 다중 할당 str1, str2 = sys.stdin.readline().split() print(str1, str2) ### 123 123 ## map 사용 num1, num2 = map(int, sys.stdin.readline().split() ) print(num1+num2)
5efd76fc0eab8048c8eb0aa288442aae81c83f40
rafaelperazzo/programacao-web
/moodledata/vpl_data/27/usersdata/77/7765/submittedfiles/divisores.py
327
3.703125
4
# -*- coding: utf-8 -*- from __future__ import division import math n=int(input('Digite o valor de n:')) a=int(input('Digite o valor de a:')) b=int(input('Digite o valor de b:')) mult=1 contador=1 while contador<n: if mult%i == 0 or mult%j == 0: print('mult') contador=contador+1 mult=mult+1
b1f7875b2750f33d81e2d40eef9fe957829ffc69
RedoneRony/Hungry_Pythoner-learning-python-
/touple.py
224
4.0625
4
number=(1,2,3) #touple unpacking a,b,c=number print(a) print(b) print(c) print(number) #when one variable store more number in touple a,b,*c,d=(1,2,3,4,5,6,7,8) print(a) print(b) print(c) print(d)
a1b59de8a1ab320ef8b43163da90f83610b440cd
balakrish2001/Basics
/prob sheet 1/factorial.py
130
3.921875
4
def fact(i): if(i==1): return 1 return i*fact(i-1) num=int(input("Enter a number:")) print(fact(num))
79fa77e74fb7404b226ee68ba3a57ced7140a7b3
ngparas/worst-aid-parsing
/parsing_utils.py
12,440
3.578125
4
"""Classify Statements as either Actions, Conditionals, or Informational """ import re import spacy # use some garbage globals until we know what this app will look like nlp = spacy.load('en') CALL_911_KEYPHRASES = ["call 911"] DOCTOR_KEYPHRASES = ["call a doctor", "call your child's doctor", "when to see a doctor", "when to call a doctor", "see a doctor", "call the doctor"] LOOP_WORDS = ["until", "while"] def split_sentences(text): """Util function to parse sentences This function uses Spacy to parse sentences Args: text (string): a text string to be split into sentences Return: A list of strings """ parsed_text = nlp(text) text_list = list(parsed_text.sents) if text_list[0].text[0].isdigit() and text_list[0].text[-1] == ".": return [text] return [i.text for i in parsed_text.sents] def is_action(sentence): """Predicate to determine if a sentence is an action This function returns true if a sentence from an online medical procedure is an action (e.g. a step) or not. It could also be an informational sentence or a conditional. Args: sentence (String): A sentence from a medical procedure Return: Boolean: True if an action, else False """ tagged_sentence = nlp(sentence) # catch some special cases up front if tagged_sentence[0].text.lower() == 'continue': return True result = True verb_counter = 0 for token in tagged_sentence: # Find a verb, we can tell impaeratives from verbs with an implied 'you' if token.pos_ == 'VERB': verb_counter += 1 if token.text.lower() != 'is': if not any(i.dep_ in ['nsubj', 'nsubjpass'] for i in token.children): result = result and True else: result = result and False else: result = result and False if verb_counter > 0: return result else: return True def extract_conditional_clauses(sentence): """Function to extract if clauses from a sentence This function takes a sentence and returns the conditional and unconditional clauses. Args: sentence (String): A sentence from a medical procedure Return: A Dict with two key value pairs. 'conditionals' has a list of the conditional clauses. 'nonconditionals' has a list of the rest of the clauses. """ tagged_sentence = nlp(sentence) tagged_sentence_text = tagged_sentence.text excluded_clauses = ['if necessary', 'if possible'] conditional_heads = [i.head for i in tagged_sentence if i.text.lower() in ['if', 'while', 'until']] conditional_phrases = [" ".join(j.text for j in i.subtree) for i in conditional_heads] # much efficient, very code cond_results = [] for i in conditional_phrases: if sum(1 for j in conditional_phrases if i in j) == 1: if i.lower() not in excluded_clauses: cond_results.append(i) # Found conditional clauses, now get the rest of it min_match_index = None max_match_index = None rest = tagged_sentence_text for clause in cond_results: search_clause = ''.join(clause.split()) search_clause = '\s*'.join(search_clause) match = re.search(search_clause, rest) if match is not None: if min_match_index is None or match.start() < min_match_index: min_match_index = match.start() if max_match_index is None or match.end() > max_match_index: max_match_index = match.end() # subset string to stuff outside of matches # TODO : be more clever about this if min_match_index is None or max_match_index is None: pass else: rest = rest[:min_match_index] + rest[max_match_index:] rest = rest.replace(" ,", ",").replace(" .", ".").replace(" '", "'") min_match_index = None max_match_index = None for i, result in enumerate(cond_results): if " n't " in result: cond_results[i] = result.replace(" n't ", " not ") if rest.startswith(", "): rest = rest[len(", "):] rest = rest[0].upper() + rest[1:] return {"conditionals": cond_results, "nonconditionals": rest} def is_911(sentence): """Given a sentence, returns whether it relates to a 911 conditional Keyword arguments: sentence -- the string that contains the sentence """ return any(keyphrase in sentence.lower() for keyphrase in CALL_911_KEYPHRASES) def extract_911_clauses(sentence): """Given a sentence, returns a list of dictionary representations of the clauses Keyword arguments: sentence -- the string that contains the sentence """ clauses = sentence.split("if") return {'substeps' : [], 'type': '911-conditional', 'text': sentence} def is_doctor(sentence): """Given a sentence, returns whether it relates to a doctor conditional Keyword arguments: sentence -- the string that contains the sentence """ return any(keyphrase in sentence.lower() for keyphrase in DOCTOR_KEYPHRASES) def extract_doctor_clauses(sentence): """Given a sentence, returns a list of dictionary representations of the clauses Keyword arguments: sentence -- the string that contains the sentence """ return {'substeps': [], 'type': 'doctor-conditional', 'text': sentence} def is_list(sentence): """Given a sentence, returns whether it is a list header Keyword arguments: sentence -- the string that contains the sentence """ return sentence.endswith(':') and not is_911(sentence) and not is_doctor(sentence) def is_loop_action(sentence): """Returns true if sentence is an action containing a "loop word" as defined in LOOP_WORDS sentence -- string containing the sentence of interest """ # Looks like is_action needs some work, let's look into that # print(is_action(sentence)) # print(any(loop_word in sentence.lower() for loop_word in LOOP_WORDS)) # return is_action(sentence) and any(loop_word in sentence.lower() for loop_word in LOOP_WORDS) return any(loop_word in sentence.lower() for loop_word in LOOP_WORDS) def extract_loop_action_clauses(sentence): """Returns a list of first aid graph nodes with the looping conditional type associated with the node. Use if is_loop_action(sentence) is true sentence -- string containing the sentence of interest """ for loop_word in LOOP_WORDS: if loop_word in sentence.lower(): clauses = extract_conditional_clauses(sentence) conditionals = clauses["conditionals"] loop_condition = next(x for x in conditionals if is_loop_action(x)) action = sentence.replace(loop_condition, "") if not len(action) is 0: return {'type': loop_word + '-conditional', 'text': sentence, 'loop-condition': loop_condition, 'action': action} else: return {'type': loop_word + '-conditional', 'text': sentence, 'loop-condition': loop_condition, 'action': action} return {} if __name__ == '__main__': samples = ["Rest the sprained or strained area.", "If necessary, use a sling for an arm injury or crutches for a leg or foot injury.", "Splint an injured finger or toe by taping it to an adjacent finger or toe.", "Ice for 20 minutes every hour.", "Never put ice directly against the skin or it may damage the skin.", "Use a thin towel for protection.", "Compress by wrapping an elastic (Ace) bandage or sleeve lightly (not tightly) around the joint or limb.", "Specialized braces, such as for the ankle, can work better than an elastic bandage for removing the swelling.", "Elevate the area above heart level if possible.", "Give an over-the-counter NSAID (non-steroidal anti-inflammatory drug) like ibuprofen (Advil, Motrin), acetaminophen (Tylenol), or aspirin.", "Do not give aspirin to anyone under age 19.", "There is a 'popping' sound with the injury.", "Continue RICE for 24 to 48 hours, or until the person sees a doctor.", "The doctor may want to do X-rays or an MRI to diagnose a severe sprain or strain or rule out a broken bone.", "The doctor may need to immobilize the limb or joint with a splint, cast, or other device until healing is complete.", "Physical therapy can often be helpful to bring an injured joint back to normal.", "In severe cases, surgery may be needed.", "If the nail is torn, use sterile scissors to cut off rough edges to prevent further injury.", "use sterile scissors to cut off rough edges to prevent further injury.", "Use sterile scissors to cut off rough edges if the nail is torn", "Make an appointment with a doctor if you still have pain after two weeks of home treatment, if the knee becomes warm, or if you have fever along with a painful, swollen knee."] # for s in samples: # print("\n") # print(s) # print(is_action(s)) print(extract_conditional_clauses("If the person doesn't respond, call 911 immediately and start CPR if necessary.")) for s in samples: print(s) print(extract_conditional_clauses(s)) print('\n') SAMPLES = [ "Avoid spicy or greasy foods and caffeinated or carbonated drinks until 48 hours after all symptoms have gone away.", "Apply direct pressure until bleeding stops.", "Flush with lukewarm water for 15 to 30 minutes.", "For severe burns, continue flushing until you see a doctor or you arrive in an emergency room.", "Don't rub eyes.", "Apply ice and elevate hand to reduce swelling.", "Avoid sex, tampons, or douching while you're bleeding.", "Apply ice to reduce swelling while waiting for medical care.", "6. Monitor the Person Until Help Arrives" ] print(extract_conditional_clauses(SAMPLES[1])) for sample in SAMPLES: if is_loop_action(sample): print(extract_loop_action_clauses(sample)) else: print("Not a loop action.") samples = ["Rest the sprained or strained area.", "If necessary, use a sling for an arm injury or crutches for a leg or foot injury.", "Call 911 NOW if:", "Call 911 NOW if the person is:", "Call 911 if the person has these symptoms of alcohol poisoning:", "Call 911 now if the person has had severe reactions in the past or has any of these symptoms:", "Call 911 if the person:", "Call 911", "Call 911 if:", "Call 911 if the person loses consciousness or has:"] for s in samples: print(s) if(is_911(s)): print(extract_911_clauses(s)) else: print("Not a Call 911 sentence.") print('\n') SAMPLES = ["Call your child's doctor immediately if your child has any of the following:", "Call 911 NOW if:", "4. When to See a Doctor", "3. When to Call a Doctor", "Call a doctor if the person has:", "3. Ease Into Eating", "See a doctor immediately for these symptoms:", "Call the doctor as soon as possible if the person has:", "For a mild reaction:"] for s in SAMPLES: print(s) if is_doctor(s): print(extract_doctor_clauses(s)) else: print("Not a doctor-related sentence.") print("\n") """Implement fuzzy match functionality with word vectors """ def word_vector_match(query, available_keys): max_similarity = 0 max_key = None q = nlp(query) for key in available_keys: k = nlp(key) similarity = k.similarity(q) if similarity > max_similarity: max_similarity = similarity max_key = key return max_key, max_similarity
66714bf3217c095e7915aaefa1ac341f7642c3a4
qtpham1998/robotics
/particleDataStructures.py
3,794
3.9375
4
#!/usr/bin/env python # Some suitable functions and data structures for drawing a map and particles import time import random from math import cos, sin, pi # Constants NUMBER_OF_PARTICLES = 100 # Functions to generate some dummy particles data: def calcX(): return random.gauss(80,3) + 70*(math.sin(t)); # in cm def calcY(): return random.gauss(70,3) + 60*(math.sin(2*t)); # in cm def calcW(): return random.random() def calcTheta(): return random.randint(0,360) # A Canvas class for drawing a map and particles: # - it takes care of a proper scaling and coordinate transformation between # the map frame of reference (in cm) and the display (in pixels) class Canvas: def __init__(self,map_size=210): self.map_size = map_size; # in cm; self.canvas_size = 768; # in pixels; self.margin = 0.05*map_size self.scale = self.canvas_size/(map_size+2*self.margin) def drawLine(self,line): x1 = self.__screenX(line[0]) y1 = self.__screenY(line[1]) x2 = self.__screenX(line[2]) y2 = self.__screenY(line[3]) print ("drawLine:" + str((x1,y1,x2,y2))) def drawParticles(self,data): display = [(self.__screenX(d[0]),self.__screenY(d[1])) + d[2:] for d in data] print ("drawParticles:" + str(display)) def __screenX(self,x): return (x + self.margin)*self.scale def __screenY(self,y): return (self.map_size + self.margin - y)*self.scale # A Map class containing walls class Map: def __init__(self): self.walls = [] def add_wall(self,wall): self.walls.append(wall) def clear(self): self.walls = [] def draw(self): for wall in self.walls: canvas.drawLine(wall) # Simple Particles set class Particles: def __init__(self): self.n = NUMBER_OF_PARTICLES self.data = [] for i in range(self.n): self.data.append(Particle(84, 30, 0)) def draw(self): canvas.drawParticles(self.data) # A Particle class Particle: def __init__(self, x, y, theta, w=1/NUMBER_OF_PARTICLES): self.x = x self.y = y self.theta = theta self.w = w def calcX(self, dist): return self.x + (dist + random.gauss(0, 0.5)) * cos(self.theta / 180 * pi) def calcY(self, dist): return self.y + (dist + random.gauss(0, 0.5)) * sin(self.theta / 180 * pi) def calcTheta(self, degrees): return self.theta + (degrees + random.gauss(0, 0.1)) def updateParticleCoords(self, dist): return updateParticle(self, dist, 0) def updateParticleAngle(self, degrees): return updateParticle(self, None, degrees) def updateParticle(self, dist, degrees): x = self.x y = self.y theta = self.calcTheta(degrees) #theta = theta + 360 if theta < 0 else theta #theta = theta - 360 if theta > 360 else theta if(dist != None): x = self.calcX(dist) y = self.calcY(dist) return Particle(x, y, theta) def getCoords(self): return (self.x, self.y, self.theta, self.w) canvas = Canvas(); # global canvas we are going to draw on mymap = Map() # Definitions of walls # a: O to A # b: A to B # c: C to D # d: D to E # e: E to F # f: F to G # g: G to H # h: H to O mymap.add_wall((0,0,0,168,"a")); # a mymap.add_wall((0,168,84,168,"b")); # b mymap.add_wall((84,126,84,210,"c")); # c mymap.add_wall((84,210,168,210,"d")); # d mymap.add_wall((168,210,168,84,"e")); # e mymap.add_wall((168,84,210,84,"f")); # f mymap.add_wall((210,84,210,0,"g")); # g mymap.add_wall((210,0,0,0,"h")); # h mymap.draw() particleSet = Particles()
e617ec3a3416cd624c35365387ed176ceca255d8
benj2468/holiday-coding-challenge
/src/day3/day3.py
805
3.640625
4
def readForSlope(x_slope, y_slope, line, line_num): if line_num > 0 and line_num % y_slope == 0: x = int(line_num * (x_slope / y_slope)) line_diff = 0 val = line[x % line_size] if val == '#': return 1 return 0 with open('./input.txt') as file: trees1 = trees2 = trees3 = trees4 = trees5 = 0 line_num = 0 trees = 0 line = file.readline() line_size = len(line)-1 while line: trees1 += readForSlope(1,1, line, line_num) trees2 += readForSlope(3,1, line, line_num) trees3 += readForSlope(5,1, line, line_num) trees4 += readForSlope(7,1, line, line_num) trees5 += readForSlope(1,2, line, line_num) line = file.readline() line_num += 1 print(trees1 * trees2 * trees3 * trees4 * trees5)
c1c0091fb94bf1be4711a6cf7d25b198cefe4b9e
emamaj/NewPartofPython
/PycharmProjects/Learning/slownik.py
135
3.765625
4
#jak dziala slownik Dict = {"Hania": 15, "Ziuta": 12, "Jadzka":22} print(Dict) Dict ["Hania"] = 6 print(Dict) print(Dict[Ziuta1])
e259badbf9b6be19ff2acf7173abdc125def652e
zameerhossain/basic_algoritm
/add_two_numbers.py
90
3.671875
4
print("Input the num1 and num2 ") a,b=map(int,input().split(" ")) print('the sum is:',a+b)
aaad26766dbaf3819cebe370c7f5117283fd1630
HarithaPS21/Luminar_Python
/python_fundamentals/flow_of_controls/iterating_statements/while_loop.py
339
4.15625
4
# loop - to run a block of statements repeatedly # while loop -run a set of statements repeatedly until the condition becomes false #Syntax # while condition: # code # inc/dec operator a=0 while a<=10: print("hello") # prints "hello" 11 times a+=1 print("\nwhile decrement example") i=10 while i>0: print(i) i-=1
421327287c068a074f8bd19d45b08dd9b9ee6620
Hermi999/Design-Of-Computer-Programs
/bridge_successors_refactored.py
5,245
3.859375
4
""" n people are walking in the dark. They come to a river which can be crossed by walking over a bridge. The side the people are before crossing is called "here" and the other side "there". Because it's dark people can only cross by using a light. Only 2 person can cross the bridge at the same time. One of them has to carry the light. Each person take an individual and unique amount of time to cross the bridge. The goal is to get the path which takes the smallest amount of time. INVENTORY person represented by numbers people represented as frozensets (immutable & therefore hashable) here all people left there all people right light also part of the frozenset state (here, there) action (person1, person2, arraw) arrow = "<-" or "->" path list of [state, (action, t), state, (action,t ), ... ] with t...total time elapsed successor dictionary of {state:action} pairs """ import cProfile def bsuccessors2(state): """Return a dict of {state:action} pairs. A state is a (here, there) tuple, where here and there are frozensets of people (indicated by their travel times) and/or the light. Action is represented as a tuple (person1, person2, arrow), where arrow is '->' for here to there and '<-' for there to here. When only one person crosses, person2 will be the same as person1.""" here, there = state if 'light' in here: return dict(((here - frozenset([a, b, 'light']), # state there | frozenset([a, b, 'light'])), # action (a, b, '->')) # action for a in here if a is not 'light' for b in here if b is not 'light') else: return dict(((here | frozenset([a, b, 'light']), there - frozenset([a, b, 'light'])), (a, b, '<-')) for a in there if a is not 'light' for b in there if b is not 'light') def path_cost(path): """The total cost of a path (which is stored in a tuple with the final action.""" # path = (state, (action, total_cost), state, ... ) if len(path) < 3: return 0 else: return path[1::2][-1][-1] def bcost(action): """Returns the cost (a number) of an action in the bridge problem.""" # An action is an (a, b, arrow) tuple; a and b are # times; arrow is a string. a, b, arrow = action return max(a,b) def bridge_problem(here): "Find the fastest (least elapsed time) path to the goal in the bridge problem." here = frozenset(here) | frozenset(['light']) explored = set() # set of states we have visited # State will be a (peoplelight_here, peoplelight_there, time_elapsed) # E.g. ({1, 2, 5, 10, 'light'}, {}, 0) frontier = [ [(here, frozenset())] ] # ordered list of paths we have blazed while frontier: path = frontier.pop(0) here1, there1 = state1 = final_state(path) if not here1 or (len(here1)==1 and 'light' in here1): ## That is, nobody left here return path explored.add(state1) pcost = path_cost(path) for (state, action) in bsuccessors2(state1).items(): if state not in explored: total_cost = pcost + bcost(action) path2 = path + [(action, total_cost), state] add_to_frontier(frontier, path2) return Fail Fail = [] def final_state(path): return path[-1] def add_to_frontier(frontier, path): "Add path to frontier, replacing costlier path if ther is one." # (This could be done more efficiently). # Find if there is an old path to the final state of this path. If 2 paths # have the same final state we just want to keep the path with the lowest # cost. old = None for i,p in enumerate(frontier): if final_state(p) == final_state(path): old = i break if old is not None and path_cost(frontier[old]) < path_cost(path): return # Old path was better, do nothing elif old is not None: del frontier[old] # old path was worse; delete it ## Now add the new path and re-sort frontier.append(path) #cProfile.run("print(path_states(bridge_problem([4,3,7,5])))") def test2(): here1 = frozenset([1, 'light']) there1 = frozenset([]) here2 = frozenset([1, 2, 'light']) there2 = frozenset([3]) assert bsuccessors2((here1, there1)) == { (frozenset([]), frozenset([1, 'light'])): (1, 1, '->')} assert bsuccessors2((here2, there2)) == { (frozenset([1]), frozenset(['light', 2, 3])): (2, 2, '->'), (frozenset([2]), frozenset([1, 3, 'light'])): (1, 1, '->'), (frozenset([]), frozenset([1, 2, 3, 'light'])): (2, 1, '->')} assert path_cost(('fake_state1', ((2, 5, '->'), 5), 'fake_state2')) == 5 assert path_cost(('fs1', ((2, 1, '->'), 2), 'fs2', ((3, 4, '<-'), 6), 'fs3')) == 6 assert bcost((4, 2, '->'),) == 4 assert bcost((3, 10, '<-'),) == 10 return 'tests pass' return 'tests pass' print(test2())
09f1e29a4efdb817dc3f5c34e1ca2ccb5f818f4d
zionhjs/algorithm_repo
/1on1/new_course/809-expressiveword.py
734
3.640625
4
import collections class Solution: def expressiveWords(self, S: str, words: List[str]) -> int: n = len(S) m = len(words) if n < 3 or m < 1: return 0 # code counter = collections.Counter(S) print("counter:", counter) for word in words: if len(word) < len(counter): words.remove(words) # helper def helper(word): # i -> word, j -> S i, j = 0, 0 while j < n: if counter[S[j]] >= 3: if S[j+1] == S[j]: j += 1 count = 0 for word in words: if helper(word): count += 1 return count
cdd6209ed8784b47b5709e0dc6d6801731fd1dfe
co360/study_python
/property1.py
526
3.65625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 ubuntu <ubuntu@VM-0-13-ubuntu> # # Distributed under terms of the MIT license. """ """ class Area: def __init__(self, area): self.__area = area @property def area(self): return self.__area @area.setter def area(self, area): self.__area = area @area.deleter def area(self): self.__area = 'xxx' a = Area(100) print(a.area) a.area = 200 print(a.area) del a.area print(a.area)
19171969c807528269668a0ee5c480291d59c3d9
bgoonz/UsefulResourceRepo2.0
/_MY_ORGS/Web-Dev-Collaborative/blog-research/ciriculumn/week.16-/python-lecture/14-built-ins-custom-sort.py
462
3.828125
4
# Processing Lists # - any, all # - filter # - map # - zip # - custom sort users = [ {'id': 12323, 'displayName':'Joe Smith', 'email':'joe.smith@here.com'}, {'id': 22312, 'displayName': 'Bob Smith', 'email': 'bob.smith@here.com'}, {'id': 37373, 'displayName': 'angel chen', 'email': 'angel.chen@here.com'}, ] print(users) def sorter(user): return user['displayName'].lower() users.sort(key=sorter) print(users) reverseUsers = sorted(users, key=sorter, reverse=True) print(reverseUsers)
12efd9f629c66b2362cb06f194912aac9274535b
pangfeiyo/PythonLearn
/甲鱼python/课程代码/第31讲/动动手.py
1,625
3.65625
4
# 0.编写一个程序,要求使用pickle将文件(record.txt)里的对话按照以下要求腌制成不同文件 # -- 小甲鱼的对话单独保存为boy_*.txt的文件(去掉"小甲鱼:") # -- 小客服的对话单独保存为girl_*.txt的文件(去掉'小客服:') # -- 文件中总共有三段对话,分别保存为boy_1.txt, girl_1.txt, boy_2.txt, girl_2.txt, boy_3.txt, girl_3.txt共6个文件 # (提示:文件中不同的对话间已经使用'==============='分割) import pickle def save_file(boy, girl, count): file_name_boy = 'boy_' + str(count) + '.txt' file_name_girl = 'girl_' + str(count) + '.txt' boy_file = open(file_name_boy, 'wb') # 记得一定要加 b 吖 girl_file = open(file_name_girl, 'wb') # 记得一定要加 b 吖 pickle.dump(boy, boy_file) pickle.dump(girl, girl_file) boy_file.close() girl_file.close() def split_file(file_name): count = 1 boy = [] girl = [] f = open(file_name) for each_line in f: if each_line[:6] != '======': # split(":",1) 以":"为分割,分割次数1 (role, line_spoken) = each_line.split(':', 1) if role == '小甲鱼': boy.append(line_spoken) if role == '小客服': girl.append(line_spoken) else: save_file(boy, girl, count) boy = [] girl = [] count += 1 save_file(boy, girl, count) f.close() split_file('record.txt') # 读取 pickle_file = open('boy_1.txt','rb') file = pickle.load(pickle_file) print(file)
091ff205a0b6b46bc2026702c8cd0cd5c1314ef0
kevinfal/CSC120
/Assignment5/long/zipper.py
2,516
4.125
4
""" File: zipper.py Author: Kevin Falconett Purpose: provides zipper() which merges two Linked lists into one list containing each element in both lists alternated """ from list_node import * def zipper(list1,list2): """ merges two linked lists into a single list containing each element of both lists alternated thus "zippering" it Parameters: list1 (ListNode): Linked List/node to be "zippered" list2 (ListNode): second Linked List/node to "zipper" Returns: (ListNode) - zippered, contains each element of list1 and list2 alternated, if one list runs out early it uses the rest of the other list Preconditions: None """ zippered = None head = list1 head2 = list2 zip_curr = None use_list1 = True # flag to determine which list to use if head is None and head2 is None: return None if head is None: return head2 elif head2 is None: return head while head is not None and head2 is not None: # first iteration if zippered is None: zippered = head head = head.next zippered.next = None zip_curr = zippered use_list1 = False # use second list if not none if not use_list1 and head2 is not None: zip_curr.next = head2 head2 = head2.next zip_curr = zip_curr.next zip_curr.next = None use_list1 = True # use first list if not none if use_list1 and head is not None: zip_curr.next = head head = head.next zip_curr = zip_curr.next zip_curr.next = None use_list1 = False # if one head is empty, use the rest of the other if head is None: zip_curr.next = head2 elif head2 is None: zip_curr.next = head return zippered def main(): """ Used to test the functionality of zipper(). Provides linked lists to test with, values can be changed """ list1 = ListNode(1) list1.next = ListNode(3) list1.next.next = ListNode(5) list2 = ListNode(2) list2.next = ListNode(4) list2.next.next = ListNode(6) result = zipper(list1,list2) print(result) if __name__ == "__main__": main()
6f103bc964fe03097db08e7fee3ac23335ad4d40
jbhennes/CSCI-220-Programming-1
/Chapter 5 Strings/numerology3.py
439
3.984375
4
# Numerology # Stalvey def main(): print ("Calculates a numerology score of your name. \n") name = input("Enter your name: ") newName = name.lower() total = 0 for ch in newName: value = ord(ch) - ord("a") + 1 ## print (ch, value) #debug statement total = total + value print ("The numerological score for \'" + name + "\'", end="") print (" is " + str(total) + ".") main()
d78255f0a3c71d1c58217ef05e4de0409da22cd0
ppjjhh0515/datacamp-ds-python
/Writing Efficient Code with pandas/1. Selecting rows and columns efficiently/1. The need for efficient Coding/Measuring Time.py
1,463
4.53125
5
''' Measuring time I In the lecture slides, you saw how the time.time() function can be loaded and used to assess the time required to perform a basic mathematical operation. Now, you will use the same strategy to assess two different methods for solving a similar problem: calculate the sum of squares of all the positive integers from 1 to 1 million (1,000,000). Similar to what you saw in the video, you will compare two methods; one that uses brute force and one more mathematically sophisticated. In the function formula, we use the standard formula N∗(N+1)(2N+1)6 where N=1,000,000. In the function brute_force we loop over each number from 1 to 1 million and add it to the result. Instructions 100 XP Calculate the result of the problem using the formula() function. Print the time required to calculate the result using the formula() function. Calculate the result of the problem using the brute_force() function. Print the time required to calculate the result using the brute_force() function. ''' # Calculate the result of the problem using formula() and print the time required N = 1000000 fm_start_time = time.time() first_method = formula(N) print("Time using formula: {} sec".format(time.time() - fm_start_time)) # Calculate the result of the problem using brute_force() and print the time required sm_start_time = time.time() second_method = brute_force(N) print("Time using the brute force: {} sec".format(time.time() - sm_start_time))
1028fab46cc1683a1255e5b0348424977ca488e8
N8Brooks/schrute_farms_algos
/lcs.py
2,242
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 24 12:05:44 2020 @author: nathan """ from itertools import combinations def lcs_combstr(a, b): both = (a[i:j] for i, j in combinations(range(len(a) + 1), 2) if a[i:j] in b) return max(both, key=len, default="") def lcs_combset(a, b): a = {a[i:j] for i, j in combinations(range(len(a) + 1), 2)} a.intersection_update(b[i:j] for i, j in combinations(range(len(b) + 1), 2)) return max(a, key=len, default="") def lcs_trie(a, b): trie = dict() for i in range(len(a) + 1): cur_a = trie for c in a[i:]: cur_a = cur_a.setdefault(c, dict()) cur_a["#"] = tuple() for i in range(len(b) + 1): cur_b = trie for c in b[i:]: cur_b = cur_b.setdefault(c, dict()) cur_b["$"] = tuple() stack = [(trie, "")] longest = "" while stack: cur, sub = stack.pop() longest = max(longest, sub, key=len) stack.extend( ( val, sub + key, ) for key, val in cur.items() if "#" in val and "$" in val ) return longest def lcs_dynamic(a, b): m = len(a) + 1 n = len(b) + 1 memo = [0] * n longest = 0 index = 0 for i in range(1, m): memo = [0] + [ memo[j - 1] + 1 if a[i - 1] == b[j - 1] else 0 for j in range(1, n) ] for i, x in enumerate(memo): if x > longest: longest = x index = i return a[index - longest : index] if __name__ == "__main__": import pandas as pd from random import choices from string import ascii_lowercase as alpha from time import time algorithms = [lcs_combstr, lcs_combset, lcs_trie, lcs_dynamic] df = pd.DataFrame(columns=[algo.__name__ for algo in algorithms]) for i in range(13): a = "".join(choices(alpha, k=2 ** i)) b = "".join(choices(alpha, k=2 ** i)) record = pd.Series() for algo in algorithms: t0 = time() print(algo(a, b)) t1 = time() record[algo.__name__] = t1 - t0 df.loc[2 ** i] = record
99e8ba0f4e5f43ebcc802a1e91c153888bd66550
henokyen/whereismytweet
/Spark/graph_retweets2.py
4,670
3.515625
4
# Builds the retweet graph from the retweets stored in Redis import cfg import time import json import redis # unconnected (retweeters): # just a temporary container for redis dicts for final step unconnected = [] # connected (retweeters): # conduct search through connected RT'ers while adding new edges connected = [] # result graph: 2 lists links = [] nodes = [] # Adds nodes and links between them to the graph def addToGraph (parent, child): global links if (child): nodes.append(child) if (parent): links.append({'source':getNodeIndex(parent), 'target':getNodeIndex(child)}) # links are made between indices of nodes def getNodeIndex (user): global nodes for i in range(len(nodes)): if (user['id'] == nodes[i]['id']): return i return -1 #form the Neo4j database, fetch users who are followed by this user. # Note getting this information from Twitter is very time consuming. #Therefore, a Neo4j databse was created to hold a simulated twitter like social network. #The data is from https://snap.stanford.edu/data/soc-pokec.html def fecthFriends(user): userid = "User_"+str(user['id']) rel = "MATCH (a:User)-[:Follows]->(b:User {name: {S}}) RETURN a.name as name" follwed_list = list(cfg.graph.cypher.execute(rel,{"S":userid})) for followed in follwed_list: cfg.red.hset("friends:%s" % user['id'], followed.name.strip("User_"), "") #get all the people this child could have retweeted from #returns 1 if this child retweeted from any of the existing node that is already in the graph, 0 otherwise def isFriend(parent,child): key = REDIS_FRIENDS_KEY % child['id'] if (not cfg.red.exists(key)): fecthFriends(child) return cfg.red.hexists(key, parent['id']) # a new node gets connected to a node that is already in the graph, # that is a retweeter gets into the graph only after the retweeter that he retweets from is in the graph def reverseSearch(user,source): global nodes, connected # discard if duplicate, is that retweet is already part of the graph if user in nodes: return # assume node is isolated until parent is found parent = None # connect user by iterating through already-connected nodes, # i.e., find from which other user this current user could have retweeted retweets for existing in connected: if isFriend(existing,user): parent = existing break if parent is not None: print (" New edge: %s <=== %s" % (parent['screen_name'], user['screen_name'])) addToGraph(parent, user) else: print (" User %s is isolated" % user['screen_name']) addToGraph(None, user) # retweeter has been connected connected.append(user) # Building the graph starts by continuously checking for a Redis cache for a start signal, meaning checking if a user has tweeted while True: if cfg.red.llen('start') == 0: time.sleep(30) else: tweetId = cfg.red.lindex('start',0) break retweetiD = tweetId + "i" # if there is a retweet graph already constructed for this tweet, fetch that graph and build upon it if cfg.red.llen(retweetiD)!= 0: print "Reading a prevoius retweet graph from Redis keyed at: ",retweetiD data = json.loads(cfg.red.lindex(retweetiD,0)) nodes = data ["nodes"] links = data["links"] root = nodes[0] connected = nodes #otherwise, start a graph from a scratch, by first retrivig the orignal tweet else: root = json.loads(cfg.red.lindex("Orig",0)) connected.append(root) addToGraph(None, root) # building the re-tweet graph continues until a 'Stop' signal is sensed quit = 0 while (quit == 0): # check for "Stop" signal, i.e., if enough retweet has been collected. If so, lpop it if (cfg.red.lindex(tweetId,0) == "Stop"): cfg.red.lpop(tweetId) quit = 1 # if the list is empty, sleep and wait for retweets to arrive llen = cfg.red.llen(tweetId) if llen == 0: print("Retweet queue is empty, sleeping for 40 seconds.") time.sleep(40) continue # otherwise, pop retweets and put them into the graph print("Forming a graph with %s retweets retrieved from Redis..." % llen) for i in range(0, min(llen,30)): popped = json.loads(cfg.red.rpop(tweetId)) ] unconnected.append(popped) for retweeter in unconnected: reverseSearch(retweeter,root) graph = json.dumps({'nodes':nodes ,'links':links}, indent=2); cfg.red.lpush (str(tweetId)+"i", graph) # clear unconnected so we don't re-attach unconnected = []
e96dadbe87a6b08f8e58c49db919d0dded596fdc
sbtries/Class_Polar_Bear
/Code/Reece/python/lab3.py
780
4.15625
4
# Reece Adams - lab3.py - Grading # import math grade = input("Enter your grade: ") try: grade = (float(grade)) if grade > 100 or grade < 0: raise ValueError except ValueError: print("Inavlid grade... goodbye.") exit() # Math for letter_grade --------------------------- # if grade >= 90: letter_grade = 'A' elif grade >= 80: letter_grade = 'B' elif grade >= 70: letter_grade = 'C' elif grade >= 60: letter_grade = 'D' else: letter_grade = 'F' # Math for symbol ---------------------------- # ones_digit = grade % 10 print(ones_digit) if grade >= 60: if ones_digit >= 7 or grade == 100: letter_grade += '+' elif ones_digit <= 3: letter_grade += '-' print(f'Your grade {grade} results in a(n) {letter_grade}')
d405b1e3b043a10ab17704eaec16347d6bd3e490
kyungphilDev/AI_pacman
/submission.py
14,524
3.546875
4
# ID: 20170499 NAME: Park Kyungphil ###################################################################################### # Problem 2a # minimax value of the root node: 6 # pruned edges: h, m, x ###################################################################################### from collections import deque from util import manhattanDistance from game import Directions import random import util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def __init__(self): self.lastPositions = [] self.dc = None def getAction(self, gameState): """ getAction chooses among the best options according to the evaluation function. getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} ------------------------------------------------------------------------------ Description of GameState and helper functions: A GameState specifies the full game state, including the food, capsules, agent configurations and score changes. In this function, the |gameState| argument is an object of GameState class. Following are a few of the helper methods that you can use to query a GameState object to gather information about the present state of Pac-Man, the ghosts and the maze. gameState.getLegalActions(): Returns the legal actions for the agent specified. Returns Pac-Man's legal moves by default. gameState.generateSuccessor(agentIndex, action): Returns the successor state after the specified agent takes the action. Pac-Man is always agent 0. gameState.getPacmanState(): Returns an AgentState object for pacman (in game.py) state.configuration.pos gives the current position state.direction gives the travel vector gameState.getGhostStates(): Returns list of AgentState objects for the ghosts gameState.getNumAgents(): Returns the total number of agents in the game gameState.getScore(): Returns the score corresponding to the current state of the game It corresponds to Utility(s) The GameState class is defined in pacman.py and you might want to look into that for other helper methods, though you don't need to. """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (oldFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() oldFood = currentGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn='scoreEvaluationFunction', depth='2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) ###################################################################################### # Problem 1a: implementing minimax class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (problem 1) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Terminal states can be found by one of the following: pacman won, pacman lost or there are no legal moves. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 Directions.STOP: The stop direction, which is always legal gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game gameState.getScore(): Returns the score corresponding to the current state of the game It corresponds to Utility(s) gameState.isWin(): Returns True if it's a winning state gameState.isLose(): Returns True if it's a losing state self.depth: The depth to which search should continue """ # BEGIN_YOUR_ANSWER (our solution is 30 lines of code, but don't worry if you deviate from this) def max_value(gameState, depth): value = [float('-inf'), Directions.STOP] for act in gameState.getLegalActions(0): res = miniMax(gameState.generateSuccessor(0, act), depth+1, 1) if value[0] < res: value = [res, act] return value def min_value(gameState, depth, agentIndex): value = float('inf') if agentIndex == gameState.getNumAgents()-1: for act in gameState.getLegalActions(agentIndex): value = min(value, miniMax(gameState.generateSuccessor(agentIndex, act), depth+1, 0)) return value else: for act in gameState.getLegalActions(agentIndex): value = min(value, miniMax(gameState.generateSuccessor(agentIndex, act), depth, agentIndex+1)) return value def miniMax(gameState, depth, agentIndex): if depth == self.depth*2: return gameState.getScore() if gameState.isLose() or gameState.isWin(): return gameState.getScore() if agentIndex == 0: return max_value(gameState, depth)[0] else: return min_value(gameState, depth, agentIndex) return max_value(gameState, 0)[1] # END_YOUR_ANSWER ###################################################################################### # Problem 2b: implementing alpha-beta class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (problem 2) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ # BEGIN_YOUR_ANSWER (our solution is 42 lines of code, but don't worry if you deviate from this) def max_value(gameState, depth, partial_min, partial_max): value = [float('-inf'), Directions.STOP] for act in gameState.getLegalActions(0): if value[0] > partial_min: return value res = miniMax(gameState.generateSuccessor(0, act), depth+1, 1, partial_min, partial_max) if value[0] < res: value = [res, act] partial_max = max(partial_max, value[0]) return value def min_value(gameState, depth, agentIndex, partial_min, partial_max): value = float('inf') if agentIndex == gameState.getNumAgents()-1: for act in gameState.getLegalActions(agentIndex): if value < partial_max: return value value = min(value, miniMax(gameState.generateSuccessor(agentIndex, act), depth+1, 0, partial_min, partial_max)) partial_min = min(partial_min, value) return value else: for act in gameState.getLegalActions(agentIndex): if value != float('inf') and value < partial_max: return value value = min(value, miniMax(gameState.generateSuccessor(agentIndex, act), depth, agentIndex+1, partial_min, partial_max)) partial_min = min(partial_min, value) return value def miniMax(gameState, depth, agentIndex, partial_min, partial_max): if depth == self.depth*2: return gameState.getScore() if gameState.isLose() or gameState.isWin(): return gameState.getScore() if agentIndex == 0: return max_value(gameState, depth, partial_min, partial_max)[0] else: return min_value(gameState, depth, agentIndex, partial_min, partial_max) # initiate get Action partial_min = float('inf') partial_max = float('-inf') return max_value(gameState, 0, partial_min, partial_max)[1] # END_YOUR_ANSWER ###################################################################################### # Problem 3a: implementing expectimax class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (problem 3) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ # BEGIN_YOUR_ANSWER (our solution is 30 lines of code, but don't worry if you deviate from this) def max_value(gameState, depth): value = [float('-inf'), Directions.STOP] for act in gameState.getLegalActions(0): res = miniMax(gameState.generateSuccessor(0, act), depth+1, 1) if value[0] < res: value = [res, act] return value def exp_value(gameState, depth, agentIndex): actionNum = 0 totValue = 0 if agentIndex == gameState.getNumAgents()-1: for act in gameState.getLegalActions(agentIndex): actionNum += 1 totValue += miniMax(gameState.generateSuccessor(agentIndex, act), depth+1, 0) return totValue / actionNum else: for act in gameState.getLegalActions(agentIndex): actionNum += 1 totValue += miniMax(gameState.generateSuccessor(agentIndex, act), depth, agentIndex+1) return totValue / actionNum def miniMax(gameState, depth, agentIndex): if depth == self.depth*2: return self.evaluationFunction(gameState) if gameState.isLose() or gameState.isWin(): return self.evaluationFunction(gameState) if agentIndex == 0: return max_value(gameState, depth)[0] else: return exp_value(gameState, depth, agentIndex) return max_value(gameState, 0)[1] # END_YOUR_ANSWER ###################################################################################### # Problem 4a (extra credit): creating a better evaluation function def betterEvaluationFunction(currentGameState): """ Your extreme, unstoppable evaluation function (problem 4). """ # BEGIN_YOUR_ANSWER (our solution is 60 lines of code, but don't worry if you deviate from this) def bfs(currentGameState): check = [[False]*100 for i in range(100)] q = deque() q.append([currentGameState, 0]) cur_x, cur_y = currentGameState.getPacmanPosition() check[cur_x][cur_y] = True while q: cur_gameState, cur_Num = q.popleft() for act in cur_gameState.getLegalActions(0): newGameState = cur_gameState.generateSuccessor(0, act) nx, ny = newGameState.getPacmanPosition() if not check[nx][ny]: check[nx][ny] = True for capsule in currentGameState.getCapsules(): cap_x, cap_y = capsule if nx == cap_x and ny == cap_y: return cur_Num+1 if currentGameState.hasFood(nx, ny): return cur_Num+7 q.append([newGameState, cur_Num+1]) return 40 score = scoreEvaluationFunction(currentGameState) return score-bfs(currentGameState) # END_YOUR_ANSWER # Abbreviation better = betterEvaluationFunction
cecf6aaad8ba91b47878908c74b1e25cd8b7f943
lauv1993/jzoffer
/Python/41-和为S的连续正数序列.py
500
3.53125
4
# -*- coding:utf-8 -*- class Solution: def sum(self, a, b): return (a + b) * (b - a + 1) / 2 def FindContinuousSequence(self, tsum): # write code here res = [] low, high = 1, 2 while low < high: t = self.sum(low, high) if t == tsum: res.append(list(range(low, high + 1))) low += 1 elif t < tsum: high += 1 else: low += 1 return res
063be24ae8772d31dfd8ffdc8d26b9bc20f7a117
htorrespo/html-table-to-excel
/html_table_to_excel.py
1,395
3.515625
4
import xlwt def html_table_to_excel(table): """ html_table_to_excel(table): Takes an HTML table of data and formats it so that it can be inserted into an Excel Spreadsheet. """ data = {} table = table[table.index('<tr>'):table.index('</table>')] rows = table.strip('\n').split('</tr>')[:-1] for (x, row) in enumerate(rows): columns = row.strip('\n').split('</td>')[:-1] data[x] = {} for (y, col) in enumerate(columns): data[x][y] = col.replace('<tr>', '').replace('<td>', '').strip() return data def export_to_xls(data, title='Sheet1', filename='export.xls'): """ export_to_xls(data, title, filename): Exports data to an Excel Spreadsheet. Data should be a dictionary with rows as keys; the values of which should be a dictionary with columns as keys; the value should be the value at the x, y coordinate. """ workbook = xlwt.Workbook() worksheet = workbook.add_sheet(title) for x in sorted(data.iterkeys()): for y in sorted(data[x].iterkeys()): try: if float(data[x][y]).is_integer(): worksheet.write(x, y, int(float(data[x][y]))) else: worksheet.write(x, y, float(data[x][y])) except ValueError: worksheet.write(x, y, data[x][y]) workbook.save(filename) return
7f9a86b0a47b4356f4229f7261e4fa64c772ad2b
nazirabolat/PP2Summer2020
/k.py
266
3.953125
4
input_line = input().split() days, h = int(input_line[0]), int(input_line[1]) valid = False for i in range(days): average = sum([int(x) for x in input().split()]) / 3 if average >= h: valid = True break if valid: print("YES") else: print("NO")
7d6c5da291c99fd09260b522271daf5f64232233
Cutecodes/coursera-ml-py
/machine-learning-ex2/ex2/plotData.py
635
3.84375
4
import matplotlib.pyplot as plt import numpy as np def plot_data(X, y): plt.figure() # ===================== Your Code Here ===================== # Instructions : Plot the positive and negative examples on a # 2D plot, using the marker="+" for the positive # examples and marker="o" for the negative examples # for i in range(y.shape[0]): if 1==y[i]: plt.scatter(X[i][0],X[i][1],c='y',marker='+') else: plt.scatter(X[i][0],X[i][1],c='b',marker='o') #plt.xlabel('Exam 1 score') #plt.ylabel('Exam 2 score') plt.pause(0.5)
f46eea5bc57134daad340c6cd47a95e2271745bb
palhaogv/Python-exercises
/ex054.py
338
3.78125
4
# crie um programa que leia o ano de nascimento de 7 pessoas e informe quais são maiores de idade e quais não for c in range (1, 8): i = int(input('Digite o ano que você nasceu: ')) if 2020 - i > 18: print(f'\33[31mVocê é maior de idade.\33[m') else: print(f'\33[33mVocê não é maior de idade.\33[m')
ff1ef9f775d00eff04cc439e240e76ff50caed87
yoursamlan/FunWithTurtle
/random number visualization.py
416
3.78125
4
import turtle, random from turtle import * turtle.speed(0) #turtle.bgcolor('blue') turtle.pencolor("red") k = 1; while k <= 360: for r1 in range(0,720): turtle.left(r1) turtle.forward(k) turtle.backward(k) turtle.right(r1) k+=1 j = 10; while j <= 360: turtle.pencolor("green") r = random.randint(1,360) turtle.left(r) turtle.forward(j) turtle.backward(j) turtle.right(r) j+=1
3bc2089094c658bdfcfa3bf0fdbc77747beb9086
Treelovah/Colorado-State-University
/Python-220/week-4/PA1.py
3,226
4.09375
4
''' TODO Copy your PA1 code here ''' ''' PA1: Boolean functions and truth-table inputs -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_- For PA1 you will implememnt a number of Boolean functions, such as implies, nand, etc. a) Boolean functions You are provided with a set of undefined functions.You will create the bodies for these 2 parameter functions, such that they return the appropriate Boolean value (True or False). The formal parameters are always p and q (in that order) Notice the difference between npIMPnq and nqIMPnp: In npIMPnq you return not p implies not q (not first param implies not second param), for example npIMPnq(True,False) returns True. In nqIMPnp you return not q implies not p (not second param implies not first param), for example nqIMPnp(True,False) returns False. b) Truth-table inputs The function make_tt_ins(n) will create a truth table for all combinations of n Boolean variables. A truth table is an arrayList of 2**n arrayLists of n Booleans. For example make_tt_ins(2) returns [[False, False], [False, True], [True, False], [True, True]] Notice the recursive nature of make_tt_ins(n): It consists of a truth-table(n-1), each row prefixed with False followed by the same truth-table(n-1), each row prefixed with True, with a base case for n==1: [[False], [True]] Two functions are provided: run(f) and main, so that you can test your code. python3 PA1.py <fName> tests your Boolean function <fName> python3 PA1.p=y tt <n> tests your function make_tt_ins(<n>) ''' import sys, itertools # p implies q def implies(p, q): return True if (p and q) or (not p and q) or (not p and not q) else False # not p implies not q def npIMPnq(p,q): return True if (p and q) or (p and not q) or (not p and not q) else False # not q implies not p def nqIMPnp(p,q): return True if (p and q) or (not p and q) or (not p and not q) else False # p if and only if q: (p implies q) and (q implies p) def iff(p, q): return True if (p and q) or (not p and not q) else False # not ( p and q ) def nand(p, q): return True if (p and not q) or (not p and q) or (not p and not q) else False # not p and not q def npANDnq(p,q): return True if (not p and not q) else False # not ( p or q) def nor(p, q): return True if (not p and not q) else False # not p or not q def npORnq(p,q): return True if (p and not q) or (not p and q) or (not p and not q) else False def make_tt_ins(n): table = list(itertools.product([False, True], repeat=n, ) ) return list(map(list, table)) #provided def run(f): print(" True,True : ", f(True,True)) print(" True,False : ", f(True,False)) print(" False,True : ", f(False,True)) print(" False,False: ", f(False,False)) print() #provided if __name__ == "__main__": print("program", sys.argv[0]) f1 = sys.argv[1] print(f1) if(f1 == "implies"): run(implies) if(f1 == "iff"): run(iff) if(f1 == "npIMPnq"): run(npIMPnq) if(f1 == "nqIMPnp"): run(nqIMPnp) if(f1 == "nand"): run(nand) if(f1 == "nor"): run(nor) if(f1 == "npANDnq"): run(npANDnq) if(f1 == "npORnq"): run(npORnq) if(f1 == "tt"): print(make_tt_ins(int(sys.argv[2])))
b703a79e4710e1c2e409b67f3d2c2dd638eef77f
FocalChord/compsci-235-labs
/lab-1/code-examples/debugging/factorial.py
110
3.6875
4
def factorial(n): val = 1 for i in range(1, n): val *= i return val print(factorial(5))
d757fe5a5ebf0514c3c22c3da89774d471efc4c1
Ajinkya-Sonawane/Problem-Solving-in-Python
/Binary Search/Linked Lists/Add Linked Lists.py
848
3.5625
4
# https://binarysearch.com/problems/Add-Linked-Lists # class LLNode: # def __init__(self, val, next=None): # self.val = val # self.next = next class Solution: def solve(self, l0, l1): sentinal = LLNode(0,None) head = sentinal sum_ = 0 carry = 0 while l0 or l1: if l0 and l1: sum_ = l0.val + l1.val + carry l0 = l0.next l1 = l1.next elif not l0: sum_ = l1.val + carry l1 = l1.next elif not l1: sum_ = l0.val + carry l0 = l0.next carry = sum_ // 10 sentinal.next = LLNode(sum_%10,None) sentinal = sentinal.next if carry: sentinal.next = LLNode(carry,None) return head.next
deaef805005d9cfdf07e9b07f0e9050ffb3828d8
Charch1t/spectrum-inteeernship-drive-2021
/prgm3.py
229
3.796875
4
#To find all the prime numbers from 1 to n n = 7 for num in range(1 , n+1): if num>1: for j in range(2 , num): if (num % j == 0): break else: print(num)
7f06224036e41593097462ad066e13d65e0c0ac3
jdleo/Leetcode-Solutions
/solutions/1315/main.py
835
3.765625
4
# 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 sumEvenGrandparent(self, root: TreeNode, parent: TreeNode = None, grandparent: TreeNode = None) -> int: # base case if not root: return 0 # only take this value if grandparent is even valued res = root.val if grandparent and grandparent.val % 2 == 0 else 0 # add sums from left and right subtrees # but make parent grandparent, and cur node parent res += self.sumEvenGrandparent(root.left, root, parent) res += self.sumEvenGrandparent(root.right, root, parent) return res
5705ba29a77f99bc51aa1b7dc5be2d4062113cff
gzgdouru/python_study
/python3_cookbook/chapter04/demo07.py
250
3.671875
4
''' 迭代器切片 ''' import itertools def count(n): while True: yield n n += 1 if __name__ == "__main__": c = count(0) # print(c[:10]) for i in itertools.islice(c, 10, 20): print(i, end=" ") print("")
3f3c3d4e681a0e84f45d95f9f356319842fb9cc6
fuku68/MatrixProgrammer
/chapter0/work_0.5.6.py
123
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- print('>>> {2**x for x in {1,2,3,4,5}}') print({2**x for x in {1,2,3,4,5}})
04e679cf55e83358cf2d5f963491ddb9222b9b15
codemstrneel/usaco_python
/progs/general/runround/runround.py
4,104
4.1875
4
""" Runaround numbers are integers with unique digits, none of which is zero (e.g., 81362) that also have an interesting property, exemplified by this demonstration: If you start at the left digit (8 in our number) and count that number of digits to the right (wrapping back to the first digit when no digits on the right are available), you’ll end up at a new digit (a number which does not end up at a new digit is not a Runaround Number). Consider: 8 1 3 6 2 which cycles through eight digits: 1 3 6 2 8 1 3 6 so the next digit is 6. Repeat this cycle (this time for the six counts designed by the ‘6’) and you should end on a new digit: 2 8 1 3 6 2, namely 2. Repeat again (two digits this time): 8 1 Continue again (one digit this time): 3 One more time: 6 2 8 and you have ended up back where you started, after touching each digit once. If you don’t end up back where you started after touching each digit once, your number is not a Runaround number. Given a number M (that has anywhere from 1 through 9 digits), find and print the next runaround number higher than M, which will always fit into an unsigned long integer for the given test data. PROGRAM NAME: runround INPUT FORMAT A single line with a single integer, M SAMPLE INPUT (file runround.in) 81361 Copy OUTPUT FORMAT A single line containing the next runaround number higher than the input value, M. SAMPLE OUTPUT (file runround.out) 81362 """ """ ID: neel1 TASK: runround LANG: PYTHON3 """ inpFile = open('runround.in', 'r') outFile = open('runround.out', 'w') import sys INT_MAX = sys.maxsize; # Function to count distinct # digits in a number def countDistinct(n): # To count the occurrence of digits # in number from 0 to 9 arr = [0] * 10; count = 0; # Iterate over the digits of the number # Flag those digits as found in the array while (n != 0): r = int(n % 10); arr[r] = 1; n //= 10; # Traverse the array arr and count the # distinct digits in the array for i in range(10): if (arr[i] != 0): count += 1; return count; # Function to return the total number # of digits in the number def countDigit(n): c = 0; # Iterate over the digits of the number while (n != 0): r = n % 10; c+=1; n //= 10; return c; # Function to return the next # number with distinct digits def nextNumberDistinctDigit(n): while (n < INT_MAX): # Count the distinct digits in N + 1 distinct_digits = countDistinct(n + 1); # Count the total number of digits in N + 1 total_digits = countDigit(n + 1); if (distinct_digits == total_digits): # Return the next consecutive number return n + 1; else: # Increment Number by 1 n += 1; return -1; def checkRunRound(numArr): global lenNumArr currIdx = 0 boolNumArr = [False] * lenNumArr for i in range(lenNumArr): if boolNumArr[(currIdx + numArr[currIdx]) % lenNumArr] == True: return False else: boolNumArr[(currIdx + numArr[currIdx]) % lenNumArr] = True currIdx = (currIdx + numArr[currIdx]) % lenNumArr if i == lenNumArr - 1: if currIdx == 0: return True return False def checkDiffNum(numArr): global lenNumArr boolArr = [False] * 10 for i in range(lenNumArr): if numArr[i] == lenNumArr: return False if numArr[i]==0: return False if boolArr[numArr[i]] == True: #print(numArr[i]) return False else: boolArr[numArr[i]] = True return True currNum = int(inpFile.readline()) + 1 while True: numArr = [int(d) for d in str(currNum)] lenNumArr = len(numArr) if checkDiffNum(numArr): if checkRunRound(numArr): break currNum =nextNumberDistinctDigit(currNum) outFile.write(str(currNum) + "\n") outFile.close()
e5dbbccfa04d2254a828e6429d74166b6a47af74
smohapatra1/scripting
/python/practice/start_again/2020/11062020/Exercise04.py
211
4.09375
4
#Define a function that takes 3 arguments x, y and z #if z is True, return x, if z is False return y def bool(x,y,z): if z == "True": print (x) else: print (y) bool("Hello","False", "x")
a48c1a9f011e67677d96469ceb9dfa1d5bcaaf9b
Thejesh-404/A-December-of-Algorithms
/December-16/day-16.py
457
3.6875
4
import requests api_address ='http://api.openweathermap.org/data/2.5/weather?appid=71ebadb9a97ad010c0248b72657635c5&q=' city1=input("enter city1 name :") city2=input("enter city2 name :") url1 = api_address + city1 url2 = api_address + city2 json_data1= requests.get(url1).json() json_data2= requests.get(url2).json() data1=json_data1['main']['temp'] data2=json_data2['main']['temp'] print("the difference in temperature is") print(data1-data2)
a408a5bf545f55815c79f044d1755efa984c3cbe
Th3Lourde/l33tcode
/problemSets/top75/721.py
1,916
3.671875
4
class Solution: def accountsMerge(self, accounts): newAccounts = [] for account in accounts: newAccounts.append([account[0], set(account[1:])]) updated = True # print("-------------------") while updated: # Go through each account and perform a merge i = 0 updated = False # print(newAccounts) while i < len(newAccounts): name, emailSet = newAccounts[i] skipList = [] tmpAccounts = [] for idx in range(len(newAccounts)): if i == idx: continue _, compareSet = newAccounts[idx] if emailSet.intersection(compareSet) != set(): # Have intersection updated = True emailSet = emailSet.union(compareSet) skipList.append(idx) # Update the emailSet # print(skipList) newAccounts[i][1] = emailSet for idx, val in enumerate(newAccounts): if idx not in skipList: tmpAccounts.append(val) newAccounts = tmpAccounts i += 1 # print("-------------------") # print(newAccounts) # return newAccounts resp = [] for idx in range(len(newAccounts)): term = [newAccounts[idx][0]] rhs = list(newAccounts[idx][1]) rhs.sort() term = term + rhs resp.append(term) return resp print(Solution().accountsMerge([["David","David0@m.co","David4@m.co","David3@m.co"],["David","David5@m.co","David5@m.co","David0@m.co"],["David","David1@m.co","David4@m.co","David0@m.co"],["David","David0@m.co","David1@m.co","David3@m.co"],["David","David4@m.co","David1@m.co","David3@m.co"]]))
458fc49e83ee7f223d459a70c7050edc702d683a
idanivanov/catdtree
/catdtree/tree_node.py
2,154
4.15625
4
class TreeNode(object): """A node of the decision tree. Each TreeNode object acts as a node in the decision tree. A node is characterized by: * split_filter: Check __init__. * condition_str: Check __init__. * children: A list of the children of this node. """ def __init__(self, split_filter, condition_str): """Construct the tree node. Args: * split_filter: function. Put simply, this is the filter which says which data will reach this node from its parent and which will not. It is a function defined as follows: - Input `(X, y)`, where `X` is a pandas.DataFrame of independent variables, and `y` is a pandas.Series of the dependent variable. - Output `(X_f, y_f)` are a filtered version of `X` and `y`. * condition_str: string. A string representation of the node. This string is intended to shortly explain the split_filter in an understandable manner. """ self.split_filter = split_filter self.condition_str = condition_str self.children = [] def add_child(self, tree_node): """Add a child of the current node. Args: * tree_node: TreeNode. The child. """ self.children.append(tree_node) def show(self, level=0): """Visualize the subtree rooted at this node recursively. Args: * level: (default=0) int. The depth of the current recursive call. Returns: A string visualization of the subtree structure. """ assert level >= 0 if level: prefix = u'| ' * (level - 1) + u'|--> ' else: prefix = u'' s = prefix + unicode(self) + u'\n' for child in self.children: s += child.show(level + 1) return s def __repr__(self): """String representation of the node.""" return self.condition_str def __str__(self): """String representation of the node.""" return self.condition_str
1c5701caae8c93f616489c14e6122e78b4967896
SemmiDev/Python-Basic
/TipsAndTrickPemrogramanPython/stringconcat-16.py
231
3.625
4
listku = ['sam','dev','otong'] kalimat = '' # cara lama for kata in listku: kalimat += kata + " " print(kalimat) # cara pythonic # separator kalimat2 = ' '.join(listku) kalimat3 = ':'.join(listku) print(kalimat2) print(kalimat3)
690e79d2da39d22e93bcebbe7703107cd47455d3
eunzi-kim/CODE_Practice
/BAEKJOON/2/14681.py
206
3.640625
4
# 사분면 고르기 x = int(input()) y = int(input()) if x > 0 and y > 0: result = 1 elif x < 0 and y > 0: result = 2 elif x < 0 and y < 0: result = 3 else: result = 4 print(result)
cc30a8075175b9e63ece33ceb6e5558f8e218d8a
w00zie/graph_exploration
/utils/plot_graph.py
1,912
3.875
4
import numpy as np import networkx as nx import matplotlib.pyplot as plt import os import itertools def draw_graph(path_to_map): """This method draws a graph with the use of pyplot. The graph has to be in the form of a 3D tensor of shape (2, n, n) where n is the number of nodes. The first element of this tensor has to be the adjacency matrix and the second one a matrix filled with ones on obstacle nodes. """ # Get the adjacency matrix and the obstacles list state = np.load(path_to_map) adj, obstacles = state[0], state[1].nonzero()[0] n_nodes = adj.shape[0] G = nx.from_numpy_matrix(adj) grid_size = int(np.sqrt(n_nodes)) pos = np.array(list(itertools.product(range(grid_size), range(grid_size)))) valid_nodes = [n for n in range(n_nodes) if n not in obstacles] pos = [(y, 9-x) for (x, y) in pos] fig = plt.figure(figsize=(7, 7)) nx.draw_networkx_edges(G, pos=pos, width=3.0) nx.draw_networkx_nodes(G, pos=pos, nodelist=valid_nodes, node_color='black', node_size=0) nx.draw_networkx_nodes(G, pos=pos, nodelist=obstacles, node_color='r', node_size=800) # Other things you might be interested in plotting # nx.draw_networkx_labels(G, pos=pos, font_size=10, # font_family='sans-serif') # weights = nx.get_edge_attributes(G,'weight') # nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights) fname = path_to_map.split('/')[-1] fname = fname.split('.')[0] plt.title(fname) plt.show() if __name__ == '__main__': env_dir = 'mazes/5x5/' envs = [f for f in os.listdir(env_dir) if f.endswith('.npy')] for env in envs: draw_graph(env_dir+env)
16ad9f70eea3783f9ba599fbea80ca1a220a4503
lilindian16/UniBackup
/2017/COSC121/Assignments/Assignment 2/trial task 2 word funcgtion.py
401
4
4
def dog_latinify_sentence(sentence): """This function will convert a whole sentence from english to doglatin """ sentence = input("Enter English Sentence: ") listed_string = sentence.split() result = [] for word in listed_string: new_words = dog_latinify_word(word) result.append(new_words) stringed_result = ' '.join(result) return (stringed_result)
a84d0da1f9512db23aaf1c58958e470fbd33ffea
d-Rickyy-b/pyBrematic
/pyBrematic/utils/rand.py
210
3.515625
4
# -*- coding: utf-8 -*- from random import seed, randint class Rand(object): def __init__(self, generator_seed): seed(generator_seed) def next_bool(self): return randint(0, 1) == 1
3cdaae49adbd36235280d021bed0df4ded5ad562
Ajaysingh647/Dictionary_python
/Basic_Intro..py
605
4.3125
4
''' dictionary is a muteable and a unordered set of collection enclosed with the square bracket[] its have the each item is the pair of key and value. Ex. of dict is info of a student. ''' info={'name':'ajay' ,'roll no.':'03','section':'C','address':'GLA university'} print(info,type(info)) #read operation print(info['roll no.']) #write operation info['roll no.']=100 info['father']='Brijpal singh' #dict empty dct={} dct=dict() #initialized a empty dict # initialize the dictionarywith items my_info={'name':'ajay singh','sec':['c','D'],'roll no.':'03'} print('name:-', my_info['name'])
12b9fc33915f9e83c3348a4fdb8e4f4e6915ba07
Danielmoraisg/data_management
/Data_transformation.py
1,955
3.828125
4
import numpy as np import streamlit as st def by_itself (column, operation): if operation == 'Cosine': return np.cos(column) elif operation == 'Tangent': return np.tan(column) elif operation == 'Sine': return np.sin(column) elif operation == 'Natural logarithm': return np.log(column) elif operation == 'Tangent': return np.tan(column) def by_number (column, operation): if operation == 'sum': number = st.number_input('what is the number', value = 2.0) return column.apply(lambda x: x+number) elif operation == 'logarithm': base = st.number_input('what is the base', value = 10.0) return np.log(column) / np.log(base) elif operation == 'root': number = st.number_input('what is the number of the root e.g., square root = 2', value = 2.0) return column.apply(lambda x: x**(1/number)) elif operation == 'exponent': number = st.number_input('what is the exponent', value = 2.0) return column.apply(lambda x: x**number) elif operation == 'multiplication': number = st.number_input('what is the number', value = 2.0) return column.apply(lambda x: x*number) elif operation == 'division': number = st.number_input('what is the number', value = 2.0) return column.apply(lambda x: x/number) elif operation == 'subtraction': number = st.number_input('what is the number', value = 2.0) return column.apply(lambda x: x-number) def by_column(cols, operations): if operations =='sum': return cols.sum(axis = 1) else: expression = '' for i in cols: #st.write(cols[i]) if operations == 'subtraction': expression +="cols['%s']-"%i elif operations == 'division': expression +="cols['%s']/"%i elif operations == 'multiplication': expression +="cols['%s']*"%i elif operations == 'exponent': expression +="cols['%s']**"%i if operations == 'exponent': return eval(expression[:-2]) else: return eval(expression[:-1])
d0d8870d5fa52319de7d95680f005b6a85a4a620
hguochen/code
/python/questions/clone_graph.py
1,749
3.8125
4
# imagine given a network of nodes, nodes object contains list of nodes to which it is connected # goal: write a copy function that duplicates the entire structure of the graph # can have cycles # directed edge # no min max size of graph # connected graph class Node(object): def __init__(self): self.nodes = [Node1, Node2, ...] # array of Node object def insert_node(node): self.nodes.append(node) return def get_nodes(): return self.nodes def get_memory_address(): pass # hash table # key: value? # new_node: old_node # assumption: # graph could be cyclic or acyclic # graph has list of nodes # graph no min max size def duplicate_graph(node): """ Time: O(|V| + |E|} Space: O(|V| + |E|} """ if node is None: return None # memory_add_of_old_node: new_cloned_node mapping_table = {} queue = [node] # populating all ndoes into mapping_table while len(queue) > 0: curr = queue.pop(0) # put cloned node into map new_curr = Node() mapping_table[curr.get_memory_address()] = new_curr neighbours = curr.get_nodes() for i in xrange(len(neigbhours)): address = neighbours[i].get_memory_address() if address not in mapping_table: new_node = Node() mapping_table[address] = new_node else: new_node = mapping_table[address] new_curr.insert_node(new_node) # put new neighbours into curr new node if neigbhours[i].get_memory_address() not in mapping_table: queue.append(neighbours[i]) # visit all nodes return mapping_table[node.get_memory_address()]
30c7cb8c9d069f2d644c042701ac0399630c4563
jamil-said/code-samples
/Python/Python_code_challenges/sumUpNumbers.py
1,101
4.09375
4
""" sumUpNumbers CodeMaster has just returned from shopping. He scanned the check of the items he bought and gave the resulting string to Ratiorg to figure out the total number of purchased items. Since Ratiorg is a bot he is definitely going to automate it, so he needs a program that sums up all the numbers which appear in the given input. Help Ratiorg by writing a function that returns the sum of numbers that appear in the given inputString. Example For inputString = "2 apples, 12 oranges", the output should be sumUpNumbers(inputString) = 14. Input/Output [execution time limit] 4 seconds (py3) [input] string inputString Guaranteed constraints: 0 ≤ inputString.length ≤ 105. [output] integer """ def sumUpNumbers(s): temp = '' res = [] for c in s: if c.isdigit(): temp += c else: if temp: res.append(int(temp)) temp = '' if temp: res.append(int(temp)) return sum(res) print(sumUpNumbers("2 apples, 12 oranges")) # 14 print(sumUpNumbers("123450")) # 123450
259ace0fc9e9ec5e5248b86d92f4009f052a100a
glatif1/Practice-Programs-in-Python
/MiniPrograms/loopoperations.py
405
4.0625
4
usernum=0 usersum=0 numofinputs=0 largest=0 while usernum != -1: usernum = int(input("Enter number or -1 for total:")) usersum = usersum + usernum numofinputs = numofinputs + 1 if usernum > usernum: largest == usernum numofinputs = numofinputs -1 usersum =usersum +1 useravg = usersum/numofinputs print("The Sum is:", usersum) print("The average is:", useravg) print("The max is:", largest)
ac818bbccdea5285d0a9caeae183f4e476248b3b
adebayo5131/Python
/StringSyntax.py
1,261
4.40625
4
print('I\'m 5 years old.\n\tHow old are you?\n\t\tDo you want to ask me a question?') word = 'Adebayo5131' print(word.isalpha()) print(word.isalnum()) print(word.isdecimal()) print(word.istitle()) print(word.isupper()) print(word.islower()) word2 = 'the begining of a new world' print(word2.title()+'\n') #Join method joinMethod ='.'.join(['cats', 'dogs' ,'rats']) print(joinMethod) print() joinMethod =','.join(['cats', 'dogs' ,'rats']) print(joinMethod) print() joinMethod ='\n\n'.join(['cats', 'dogs' ,'rats']) print(joinMethod+'\n') splitMethod = 'This is how split method works' print(splitMethod.split()) #split on a particular string splitMethod = 'This is how split method works' print(splitMethod.split('i')) #rjust() and ljust() string ='Hello' print(string.rjust(10) +'\n') string ='Hello' print(string.ljust(10) +'\n') string ='Hello' print(string.rjust(15,'*') +'\n') string ='Hello' print(string.ljust(15,'~') +'\n') string ='Hello' print(string.center(10,'*') +'\n') #strip removes white spaces word3 =" Adebayo Ajagunna" neword = word3 print(word3.center(20,'*')) print(neword.strip()) #lstrip() rstrip() print('x '.strip()) print('Adebayo Edward AjagunnA'.strip('Ae')) #Repalce wordToReplace ='Adebayo Ajagunna' print('\n'+wordToReplace.replace('a', 'o'))
4cc94fb1c461b7535a0acfb63264b554f1b7891d
adityav/gameoflife
/gameoflife/gameoflife.py
2,793
3.90625
4
"""Game of Life algorithm """ import logging from collections import defaultdict from .gameboard import GameBoard log = logging.getLogger(__name__) class GameOfLife: def __init__(self, initial_gameboard: GameBoard): self.gameboard = initial_gameboard def simulate(self): """runs the game of life for 1 cycle It is a 2 step process 1) count the number of living neighbours for a cell 2) using above, apply rules to figure out which cells will live in next generation """ init_state = self.gameboard # step 1: count the number of living neighbours for a cell count_alive_neighbours = self.count_alive_neighbours(init_state) # step 2: now we apply the rules to get the next gameboard next_state = self.apply_rules(init_state, count_alive_neighbours) self.gameboard = next_state return self def count_alive_neighbours(self, state: GameBoard) -> dict: """Returns a dict which contains the count of number of living neighbours of a cell dict[(row, col)] is the count of neighbours for cell(row, col) """ count_neighbours = defaultdict(int) for cell in state.cells: # explore the 8 directions for offset_row in [-1, 0, 1]: for offset_col in [-1, 0, 1]: if offset_row == 0 and offset_col == 0: continue row = cell[0] + offset_row col = cell[1] + offset_col if state.is_valid_cell(row, col): count_neighbours[(row, col)] += 1 return count_neighbours def apply_rules(self, state: GameBoard, count_alive_neighbours: dict): """Apply the rules of the game and generate the new gameboard""" next_state = state.empty_board() for (row, col), count in count_alive_neighbours.items(): if state.is_alive(row, col): if count == 2 or count == 3: log.debug("(%s, %s) continues living", row, col) next_state.add(row, col) else: log.debug("(%s, %s) dies", row, col) else: if count == 3: log.debug("(%s, %s) is born", row, col) next_state.add(row, col) return next_state def simulate_n(self, num_gens: int = 1): """Simulate the game for given number of iterations""" for i in range(num_gens): self.simulate() log.info("Generation: %s", 1 + i) self.gameboard.display() return self def display(self): self.gameboard.display() def print_board(self): self.gameboard.print_board()
44ac72f97ada5445658bfc22f8096164617dab73
setr/cs429
/a3/classify.py
8,087
3.90625
4
""" Assignment 3. Implement a Multinomial Naive Bayes classifier for spam filtering. You'll only have to implement 3 methods below: train: compute the word probabilities and class priors given a list of documents labeled as spam or ham. classify: compute the predicted class label for a list of documents evaluate: compute the accuracy of the predicted class labels. """ from collections import defaultdict import glob import math import os class Document(object): """ A Document. Do not modify. The instance variables are: filename....The path of the file for this document. label.......The true class label ('spam' or 'ham'), determined by whether the filename contains the string 'spmsg' tokens......A list of token strings. """ def __init__(self, filename=None, label=None, tokens=None): """ Initialize a document either from a file, in which case the label comes from the file name, or from specified label and tokens, but not both. """ if label: # specify from label/tokens, for testing. self.label = label self.tokens = tokens else: # specify from file. self.filename = filename self.label = 'spam' if 'spmsg' in filename else 'ham' self.tokenize() def tokenize(self): self.tokens = ' '.join(open(self.filename).readlines()).split() class NaiveBayes(object): def __init__(self): self.vocab = set() self.class_terms = defaultdict(lambda: defaultdict(lambda: 1)) self.class_prior = dict() def get_word_probability(self, label, term): """ Return Pr(term|label). This is only valid after .train has been called. Params: label: class label. term: the term Returns: A float representing the probability of this term for the specified class. >>> docs = [Document(label='spam', tokens=['a', 'b']), Document(label='spam', tokens=['b', 'c']), Document(label='ham', tokens=['c', 'd'])] >>> nb = NaiveBayes() >>> nb.train(docs) >>> nb.get_word_probability('spam', 'a') 0.25 >>> nb.get_word_probability('spam', 'b') 0.375 """ return self.class_terms[label][term] def get_top_words(self, label, n): """ Return the top n words for the specified class, using the odds ratio. The score for term t in class c is: p(t|c) / p(t|c'), where c'!=c. Params: labels...Class label. n........Number of values to return. Returns: A list of (float, string) tuples, where each float is the odds ratio defined above, and the string is the corresponding term. This list should be sorted in descending order of odds ratio. >>> docs = [Document(label='spam', tokens=['a', 'b']), Document(label='spam', tokens=['b', 'c']), Document(label='ham', tokens=['c', 'd'])] >>> nb = NaiveBayes() >>> nb.train(docs) >>> nb.get_top_words('spam', 2) [(2.25, 'b'), (1.5, 'a')] """ score = [] for term in self.class_terms[label]: prob = self.class_terms[label][term] not_c = sum([(self.class_terms[c][term] if term in self.class_terms[c] else 1) for c in self.class_terms if c != label]) odds = (prob * 1.0) / (not_c * 1.0) score.append((odds, term)) return sorted(score, reverse=True, key= lambda x: x[0])[:n] def train(self, documents): """ Given a list of labeled Document objects, compute the class priors and word conditional probabilities, following Figure 13.2 of your book. Store these as instance variables, to be used by the classify method subsequently. Params: documents...A list of training Documents. Returns: Nothing. """ # Need Vocabulary, dict of class:prior, dict of class: term: prob # vocab = set # class_prior = {class : prior} # class_terms = {class : {term : probability}} class_index = defaultdict(list) # { class : [[tokens]] } # list of docs, with docs being a list of tokens. class_termcount = defaultdict(lambda: defaultdict(lambda:1)) class_total = defaultdict(lambda: 1) for d in documents: class_index[d.label].append(d.tokens) self.vocab |= set(d.tokens) # |= union for token in d.tokens: class_termcount[d.label][token] += 1 class_total[d.label] +=1 for c in class_index: #num class_docs / num docs prior = (len(class_index[c]) * 1.0) / (len(documents) * 1.0) # freq of class in collection # for every term that exists in the collection # term_count = the number of times that term appears in the class's docs # total = running count of term's appearance in the class prob = dict() for t in self.vocab: prob[t] = (class_termcount[c][t]) / (class_total[c]) # now to just add everything to class globals self.class_prior[c] = prior self.class_terms[c] = prob def classify(self, documents): """ Return a list of strings, either 'spam' or 'ham', for each document. Params: documents....A list of Document objects to be classified. Returns: A list of label strings corresponding to the predictions for each document. """ label_list = list() for doc in documents: doc_vocab = {token for token in doc.tokens} score = dict() for c in self.class_terms: # log(P(c)) * sum([ log10(P(t|c)) ]) score[c] = math.log10(self.class_prior[c]) score[c] += sum([math.log10(self.class_terms[c][term] if term in self.class_terms[c] else 1) for term in doc_vocab]) label, _ = max(score.items(), key=lambda x:x[1]) label_list.append(label) return label_list def evaluate(predictions, documents): """ Evaluate the accuracy of a set of predictions. Return a tuple of three values (X, Y, Z) where X = percent of documents classified correctly Y = number of ham documents incorrectly classified as spam X = number of spam documents incorrectly classified as ham Params: predictions....list of document labels predicted by a classifier. documents......list of Document objects, with known labels. Returns: Tuple of three floats, defined above. """ total = len(documents) correct = 0 num_ham = 0 num_spam = 0 for i in range(len(documents)): p = predictions[i] d = documents[i].label if p == d: correct += 1 elif p == "ham": num_ham += 1 else: num_spam += 1 return ((correct/total), num_ham, num_spam) def main(): """ Do not modify. """ if not os.path.exists('train'): # download data from urllib.request import urlretrieve import tarfile urlretrieve('http://cs.iit.edu/~culotta/cs429/lingspam.tgz', 'lingspam.tgz') tar = tarfile.open('lingspam.tgz') tar.extractall() tar.close() train_docs = [Document(filename=f) for f in glob.glob("train/*.txt")] print('read', len(train_docs), 'training documents.') nb = NaiveBayes() nb.train(train_docs) test_docs = [Document(filename=f) for f in glob.glob("test/*.txt")] print('read', len(test_docs), 'testing documents.') predictions = nb.classify(test_docs) results = evaluate(predictions, test_docs) print('accuracy=%.3f, %d false spam, %d missed spam' % (results[0], results[1], results[2])) print('top ham terms: %s' % ' '.join('%.2f/%s' % (v,t) for v, t in nb.get_top_words('ham', 10))) print('top spam terms: %s' % ' '.join('%.2f/%s' % (v,t) for v, t in nb.get_top_words('spam', 10))) if __name__ == '__main__': main()