blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
04fd43b02302b2a0b9c0ee1254d5c5d246fea65d
ksercs/lksh
/2014/Работа в ЛКШ/Python/Зачет/4-/dictionary.py
947
3.671875
4
def merge(a, b): i = 0 j = 0 c = [] while len(a) > i and len(b) > j: if a[i] < b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 return c + a[i:] + b[j:] def merge_sort(a): if len(a) <= 1: return a else: left = a[:len(a) // 2] right = a[len(a) // 2:] return merge(merge_sort(left), merge_sort(right)) fin = open("dictionary.in", "r") fout = open("dictionary.out", "w") words = [] count = int(fin.readline()) ans = [] * count help = [True] * count for i in range(count): word = fin.readline().strip() words.append(word) ans = merge_sort(words) for i in range(count): for j in range(i+1, count): if ans[i] == ans[j]: help[j] = False for i in range(count): if help[i] == True: print(ans[i], file=fout) fout.close()
0c2b106922cba23effa358b57f4bb439f54512bf
anishihara/Extremely-Simple-Search-Engine
/Index/add_to_index.py
1,150
3.5625
4
#Define a procedure, add_to_index, #that takes 3 inputs: # - an index: [[<keyword>,[<url>,...]],...] # - a keyword: String # - a url: String #If the keyword is already #in the index, add the url #to the list of urls associated #with that keyword. #If the keyword is not in the index, #add an entry to the index: [keyword,[url]] index = [] #add_to_index(index,'udacity','http://udacity.com') #add_to_index(index,'computing','http://acm.org') #add_to_index(index,'udacity','http://npr.org') #print index => [['udacity', ['http://udacity.com', 'http://npr.org']], ['computing', ['http://acm.org']]] def add_to_index(index,keyword,url): index_keyword = filter(lambda x: x[0] == keyword,index) #found a keyword in index if len(index_keyword) > 0: i = index.index(index_keyword[0]) keyword_urls = index[i] if url not in keyword_urls[1]: keyword_urls[1].append(url) else: index.append([keyword,[url]]) add_to_index(index,'udacity','http://udacity.com') print index add_to_index(index,'computing','http://acm.org') print index add_to_index(index,'udacity','http://npr.org') print index
455d1c6cd3cc0cacfa0af40e8964c9224b208e05
lhliew/flood-warning
/Task1B.py
994
3.78125
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 29 16:13:48 2017 @author: laide """ """prints a list of tuples (station name, town, distance) for the 10 closest and the 10 furthest stations from the Cambridge city centre, (52.2053, 0.1218).""" from floodsystem.geo import stations_by_distance from floodsystem.stationdata import build_station_list def run(): #Input coordinates of Cambridge city centre Reference_coordinate = (52.2053, 0.1218) #Create list of tuples (station name, distance) TheList = stations_by_distance (build_station_list(), Reference_coordinate) #Create list of tuples (station name, town, distance) for the 10 closest and furthest stations closest = [(s.name, s.town, d) for s, d in TheList[:10]] furthest = [(s.name, s.town, d) for s, d in TheList[-10:]] print ("The closest 10 stations are:") print (closest) print ("The furthest 10 stations are:") print (furthest) if __name__ == "__main__": run()
c6aba21fbf37f63ad68af55eba72810364a870f3
wlau88/data_science_knowledge
/oop/blackjack.py
1,573
3.625
4
''' This script has all the functionalities to play blackjack ''' from blackjack_player import * from utilities import * from deck import * class Blackjack(object): def __init__(self): self.dealer = Dealer() self.player = Player() self.deck = Deck() self.play() def play(self): while self.player.money > 0: self.play_one_round() def play_one_round(self): bet_size = self.player.bet() self.deck.shuffle() deck = self.deck self.player.hand = [] self.dealer.hand = [] for i in xrange(2): deck = self.player.draw_card(deck) deck = self.dealer.draw_card(deck) if is_blackjack(self.player.hand): print "Blackjack!!" print "You have: ", print_hand(self.player.hand) self.player.win_money(1.5 * bet_size) return #Keep giving the choice to player to hit or stand while True: if hand_value(self.player.hand) >= 21: break if not self.player.hit_or_stand(self.dealer.hand[0]): break deck = self.player.draw_card(deck) player_value = hand_value(self.player.hand) if player_value > 21: self.player.lose_money(bet_size) return #Hit the dealer until at or over 17 while True: if hand_value(self.dealer.hand) >= 21: break if not self.dealer.hit(): break deck = self.dealer.draw_card(deck) dealer_value = hand_value(self.dealer.hand) if player_value > dealer_value: self.player.win_money(bet_size) elif dealer_value > player_value: self.player.lose_money(bet_size) else: print "Push!" if __name__ == '__main__': blackjack = Blackjack() blackjack.play()
c6682dd152882ad52cd884894f8d0af17ce2482a
hkd8/ChengJoeHW
/HW3(Python)/ChengJoeSolution/PyRollCHENGsolved.py
2,540
4
4
#ALL I DO IS IMPORT import csv import os csvpath = 'C:\\Users\\cheng\\Desktop\\UKED201811DATA5\\02-Homework\\03-Python\\Instructions\\PyPoll\\Resources\\election_data.csv' with open(csvpath, 'r') as csvfile: #READERS AND SKIP THAT HEADER csvreader = csv.reader(csvfile, delimiter=',') next(csvreader,None) #MAKING MY BLANK LISTS DOWNTOWN WALKING FAST candidate = [] votes = [] name = [] #storing the candidate data for row in csvreader: candidate.append(row[2]) candidateCOUNT = [[x,candidate.count(x)] for x in set(candidate)] for row in candidateCOUNT: name.append(row[0]) votes.append(row[1]) #Using ZIP function, combining name to votes to get a count candidateZIP = zip(name, votes) candidateLIST = list(candidateZIP) #winner winner chicken dinner using max function to find who had most winner = max(votes) #matching most votes to a name for row in candidateLIST: if row[1] == winner: winnerNAME = row[0] #using LENGTH to count each vote voteTOTAL = len(candidate) #making candidate totals correyTOTAL = candidate.count('Correy') correyPERCENT = int(correyTOTAL) / int(voteTOTAL) otooleyTOTAL = candidate.count("O'Tooley") otooleyPERCENT = otooleyTOTAL / voteTOTAL liTOTAL = candidate.count('Li') liPERCENT = liTOTAL / voteTOTAL khanTOTAL = candidate.count('Khan') khanPERCENT = khanTOTAL / voteTOTAL #note using .3% to get to 3 decimals print(f'Election Results') print(f'-----------------------------') print(f'Total Votes: {voteTOTAL}') print(f'-------------------------------') print(f'Khan: {khanPERCENT:.3%} ({khanTOTAL:,})') print(f'Correy: {correyPERCENT:.3%} ({correyTOTAL:,})') print(f'Li: {liPERCENT:.3%} ({liTOTAL:,})') print(f"O'Tooley: {otooleyPERCENT:.3%} ({otooleyTOTAL:,})") print(f'-----------------------------') print(f'Winner: {winnerNAME}') print(f'----------------------------') #we making more texts f=open("PyRollRESULTS.txt","w+") f.write(f'Election Results\n') f.write(f'-----------------------------\n') f.write(f'Total Votes: {voteTOTAL:,}\n') f.write(f'-------------------------------\n') f.write(f'Khan: {khanPERCENT:.3%} ({khanTOTAL:,})\n') f.write(f'Correy: {correyPERCENT:.3%} ({correyTOTAL:,})\n') f.write(f'Li: {liPERCENT:.3%} ({liTOTAL:,})\n') f.write(f"O'Tooley: {otooleyPERCENT:.3%} ({otooleyTOTAL:,})\n") f.write(f'--------------------------------\n') f.write(f'Winner: {winnerNAME}\n') f.write(f'--------------------------------\n') #MOMMA WE MADE IT 2.0 f.close()
b0f95c0297eaf2d93558674e0935e9c1c3fd9fe6
karlloic/python-for-everybody
/PythonAccessWebData/bsAssgn1.py
404
3.5
4
# Scraping Numbers from HTML using BeautifulSoup import urllib from BeautifulSoup import * content = urllib.urlopen('http://python-data.dr-chuck.net/comments_279060.html').read() bso = BeautifulSoup(content) spanTags = bso('span') total = 0 for spanTag in spanTags: total += int(spanTag.contents[0]) print('Count ' + str(len(spanTags))) print('Sum ' + str(total)) print(type(spanTag.contents[0]))
7de25dd92ba804f5a80c3b818524cbb50b97cd1c
jose01carrillo30/Table-7-Shared-Repo
/stats.py
1,803
3.609375
4
# By submitting this assignment, I agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # Names: Alexander Bockelman # Jose Carrillo # Patrick Chai # Jackson Sanders # Section: 211 # Assignment: Python Statistics Project # Date: 24 11 2018 """ Module that contains all statistic functions defined for this package. functions: mean median mode varience standard_dev min max range count sum """ print("stats imported") def mean(list): total = 0 for i in list : total += i avg = total / count(list) return avg def median(list): min = list[0] for i in list : if list[i] < min : min = list[i] middle = round(count(list) / 2) median = list[middle] return median def mode(list): """ TODO: this docstring """ raise NotImplementedError return float def variance(list): summ = 0 for val in list: summ = summ + ((float(list[val]) - mean(list)) ** 2) var_val = summ / len(list) return var_val def standard_dev(list): from math import sqrt std_dev = sqrt(variance(list)) return std_dev def min(list): min_val = 9*(10**1000) for i in list: if i < list[list.index(i) - 1] and i < min_val: min_val = i return min_val def max(list): max_val = 0 for i in list: if i > list[list.index(i) - 1] and i > max_val: max_val = i return max_val def range(list): change = max(list) - min(list) return change def count(list): counter = 0 for i in list : counter += 1 return counter def sum(list): summ = 0 for i in list : summ += i return summ
1b7c08513aad3d25055a4ad6d91d8decbffc2c30
lzzhang212/PythonEx
/LeetCode/060.permutationSequence/permutationSequence.py
1,423
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: lzzhang # @Date: 2018-06-08 14:41:43 # @Last Modified by: lzzhang # @Last Modified time: 2018-06-12 14:45:14 import math class Solution: def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ # 穷举解法超时 # def dfs(path, res, nums, visited): # if len(path) == len(nums): # res.append(path + []) # return # for i in range(len(nums)): # if i not in visited: # path.append(nums[i]) # visited.append(i) # dfs(path, res, nums, visited) # visited.pop() # path.pop() # ans = [] # visited = [] # nums = [i for i in range(1,n+1)] # dfs([], ans, nums, visited) # return ''.join('%s' %each for each in ans[k-1]) fact = [math.factorial(n-i-1) for i in range(n)] visited = [0 for _ in range(n)] ans = '' k -= 1 for i in range(n): t = k//fact[i] for j in range(n): if not visited[j]: if t == 0: break t -= 1 ans += str(j+1) k %= fact[i] visited[j] = 1 return ans
cf25b1ec130d998540bbeadf5a9896de4a4ad346
vishalamc/pythonexamples
/pandasEx3.py
189
3.984375
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.DataFrame(np.random.rand(10, 3), columns =['a', 'b', 'c']) print(df) df.plot.bar() plt.show()
5f371145a27d18ad49212e358201f651f3902f35
jjmarrs/PythonScripts
/Games/TicTacToe.py
1,809
4.15625
4
#This program is not yet finished import random def displayGrid(): print(" | | ") print(" 1 | 2 | 3 ") print(" | | ") print("---------------------") print(" | | ") print(" 4 | 5 | 6 ") print(" | | ") print("---------------------") print(" | | ") print(" 7 | 8 | 9 ") print(" | | ") def explainGame(): print("\nWelcome to the quick run through of the game 'Tic Tac Toe'") print("As you can see on the board above, there are 9 individual squares") print("You will be asked the option of choosing an 'X' or an 'O'") print("After your selection is made, the game will officialy begin.") print("\nYou will choose a number and place a corresponding X or O in that square.") print("The main goal of the game is to get 3 of your 'X's' or 'O's' in 3 vertical, horizontal" " or diagonal squares.") print("Once you do that you win, and if the opponent (the computer in this case) does the above, they win.") print("Good luck and have fun!") askSelection() def askSelection(): userChoice =(input("\nChoose your weapon: X or O?")) if userChoice == 'X': selection = 'X' else: selection = 'O' youSure = input("You have selected " + userChoice + (" Is that right? (y/n)")) if youSure == 'n': askSelection() else: begin() def begin(): board = [1,2,3,4,5,6,7,8,9] def startGame(): print("\nHello user, welcome to the game of Tic Tac Toe\n") displayGrid() userInput = (input("do you know how to play? (y/n)")) if userInput == ' n': explainGame() else: askSelection() startGame() #NOT YET FINISHED #Soon(TM)
015e218286b5bf8b9f1f645d9505c6ee5d6a40e2
AI888666/Tedu
/regex2.py
364
3.5
4
""" 正则表达式演示2 """ import re s = "1949年10月1日,中国人民共和国成立" it = re.finditer(r"\d+", s) for item in it: print(item.group()) # 匹配开头位置 obj = re.match(r"\d+", s) print(obj.group()) # 匹配第一处 obj = re.search(r"\d+", s) print(obj.group()) # 完全匹配 obj = re.fullmatch(r".+", s) print(obj.group())
0d607d64f27e07690ffe736a567fa81713274d6d
masterdungeon/code-cademy
/python/Lists and Functions/3. Appending to a list.py
63
3.546875
4
n = [1, 3, 5] # Append the number 4 here n.append(4) print n
11a2b45a58b566c8fedab474107f642baae94b50
LeslieWilson/python_playground
/chapter-five/Chapt5.py
2,829
4.40625
4
# what is a class? # a class is an instance of an object. For example leslie is the class of human, and it describes the props I'll have. An example of a class is how I called the point below, "center". Thats the classname for the instance of the object. # a method is a function that lives inside the object, invoked using dot-notation. its a message we send to the object. so like, below where i say oval.draw, I'm invoking the method draw on the oval to make it appear. #an argument consists of one or several parameters that denote the subroutine of the program. so it is the data you pass into a method I suppose. like, below where it says "for year in range (1,11)" those numbers would be the arguments. I hope I'm correct about that. # below is just some random scribbling as I read the chapter... #open a graphics window win = GraphWin('Shapes') #draw a red circle centered at point (100, 100) with radius 30 center = Point(100,100) circ = Circle(center, 30) circ.setFill('red') circ.draw(win) #put a textual label in teh center of the circle label = Text(center, "Red Circle") label.draw(win) #draw a square using a rectangle object rect = Rectangle(Point(30,30), Point(70,70)) rect.draw(win) #draw a line segment using a line objects line = Line(Point(20,30), Point(180,165)) line.draw(win) # draw an oval using the Oval object oval = Oval(Point(20,150), Point(180,199)) oval.draw(win) # examples # leftEye = Circle(Point(80, 50), 5) leftEye.setFill('yellow') leftEye.setOutline('red') rightEye = leftEye.clone() # above makes right the same as left righEye.move(20, 0) head = Circle(Point 90,50),50) rightEye.draw(win) leftEye.draw(win) head.draw(win) # GRAPH example def main (): #Introduction print "This program plots the growth of a 10-year investment" #get principle and interest rate principal = input ("enter the initial principal: ") apr = input ("enter the annualized interest rate: ") #create a graphics window with labels on left edge win = GraphWin("Investment Growth Chart", 320, 240) win.setBackground("white") Text(Point(20,230), ' 0.0K').draw(win) Text(Point(20,180), ' 2.5K').draw(win) Text(Point20,130), ' 5.0K').draw(win) # draw bar for initial principal height = principal * 0.02 bar = Rectangle(Point(40,230), Point(65,230-height)) bar.setFill("green") bar.setWidth(2) bar.draw(win) # draw bars for sucessive years for year in range(1,11): #calculate value for the next year principal = principal * (1 + apr) #draw bar for this value x11 = year * 25 + 40 height = principal * 0.02 bar = Rectangle(Point(x11,230), Point(x11+25, 230-height)) bar.setFill("green") bar.setWidth(2) bar.draw(win) raw_input("Press <Enter> to quit")
158aade14b46d1ca61b9159d119a730c0a1e59b2
gowriaddepalli/Leetcode_solutions
/daily-temperatures/daily-temperatures.py
1,669
3.859375
4
''' The logic is as follows: The Brute force is to do O(n^2). Compare each element with the rest of the array elements. But a better approach is to take a stack and start iterating through the index from the end. Algo: 1. Iterate the array from the rightmost part of the array (Reason we need to see the future to calculate result for present.) Time-> (o(n)) 2. Use a linear data storage system to return the difference/next greater temperature. (Storage-> o(n)) 3. Use a stack to storage the temperatures that are greater than the current temp, and the stack stores the nearest greater temp on the top. So, the idea is to: while iterating the element previously, put the element in the stack, if the next element has temp greater than the top of stack, pop it off, else push it. Once done, calculate the index diff between the top of the index and the current index. Disclaimer, we are pushing indexes into the stack, so as not to tackle cases of repetitive elements. ''' class Solution: def dailyTemperatures(self, T: List[int]) -> List[int]: return_value = [0] * len(T) stack = [] for i in range(len(T)-1, -1, -1): # Handle the case where we remove elements from stack(stack is not empty and the current element is ): while stack and T[i]>= T[stack[-1]]: stack.pop() if stack: # Handle the case to get the index and stack not empty. return_value[i] = stack[-1] - i # Subtract the difference from the top. stack.append(i) # Irrespective in every iteration add the index of the element to the stack. return return_value
54c681ba6c425f697fec6a8699b53da3a544148b
engelsong/DataStructure
/08-图7 公路村村通 & Kruskal算法.py
5,024
3.890625
4
class MinHeap(object): def __init__(self, MinData=0): self.Size = 0 self.Data = [(0, 0)] self.Dict = {(0, 0): 0} def IsEmpty(self): res = False if self.Size == 0: res = True return res def Comp(self, item1, item2): res = False if self.Dict[item1] > self.Dict[item2]: res = True return res def Insert(self, item, weight): self.Dict[item] = weight if self.IsEmpty(): self.Data.append(item) self.Size += 1 else: self.Size += 1 self.Data.append(item) pos = self.Size while self.Comp(self.Data[pos / 2], item): self.Data[pos] = self.Data[pos / 2] pos /= 2 self.Data[pos] = item def Delete(self): if self.IsEmpty(): raise Exception("the heap is empty!") res = self.Data[1] weight = self.Dict.pop(res) temp = self.Data.pop(self.Size) self.Size -= 1 parent = 1 child = parent * 2 while child <= self.Size: if child != self.Size and self.Comp(self.Data[child], self.Data[child + 1]): child += 1 if self.Comp(self.Data[child], temp): break else: self.Data[parent] = self.Data[child] parent = child child = parent * 2 if not self.IsEmpty(): self.Data[parent] = temp return res, weight class FUSet(object): def __init__(self, Num): self.data = [i for i in range(Num)] self.parent = [-1 for i in range(Num)] def Find(self, item): res = None if item not in self.data: res = -1 self.data.append(item) self.parent.append(-1) else: index = self.data.index(item) while self.parent[index] >= 0: index = self.parent[index] res = index return res def Union(self, item1, item2): root1 = self.Find(item1) root2 = self.Find(item2) if root1 != -1: if root2 != -1: if self.parent[root1] >= self.parent[root2]: if self.parent[root1] < 0: temp = self.parent[root1] self.parent[root1] = root2 self.parent[root2] += temp elif self.parent[root1] < self.parent[root2]: temp = self.parent[root2] self.parent[root2] = root1 self.parent[root1] += temp else: self.parent[root1] -= 1 else: index1 = self.data.index(item1) if root2 != -1: self.parent[index1] = root2 self.parent[root2] -= 1 else: index2 = self.data.index(item2) self.parent[index2] = index1 self.parent[index1] -= 1 def Check(self, item1, item2): res = False root1 = self.Find(item1) root2 = self.Find(item2) if root1 != root2: self.Union(item1, item2) res = True return res class DGraph(object): def __init__(self, maxVertexNum=1): self.maxVertexNum = maxVertexNum self.Vertex = [i for i in range(maxVertexNum)] self.Edge = [[0 for i in range(maxVertexNum)] for i in range(maxVertexNum)] self.EdgeHeap = MinHeap() self.TheSet = FUSet(maxVertexNum) def addOneEdge(self, v1, v2, weight=1): self.Edge[v1][v2] = weight self.Edge[v2][v1] = weight self.EdgeHeap.Insert((v1, v2), weight) def connectedVertex(self, Vertex): res = [] for v in range(len(self.Vertex)): if self.Edge[Vertex][v] != 0: res.append(v) return res def Kruskal(self): MST=[] res = 0 while len(MST) < self.maxVertexNum - 1 and not self.EdgeHeap.IsEmpty(): temp, weight = self.EdgeHeap.Delete() if self.TheSet.Check(temp[0], temp[1]): MST.append(temp) res += weight if len(MST) < self.maxVertexNum - 1: return -1 else: return res # mygraph = DGraph(7) # mygraph.addOneEdge(0, 3, 1) # mygraph.addOneEdge(1, 3, 3) # mygraph.addOneEdge(3, 4, 7) # mygraph.addOneEdge(3, 6, 4) # mygraph.addOneEdge(3, 5, 8) # mygraph.addOneEdge(2, 3, 2) # mygraph.addOneEdge(0, 1, 2) # mygraph.addOneEdge(1, 4, 10) # mygraph.addOneEdge(4, 6, 6) # mygraph.addOneEdge(5, 6, 1) # mygraph.addOneEdge(2, 5, 5) # mygraph.addOneEdge(0, 2, 4) # mygraph.addOneEdge(4, 7, 2) maxVertexNum, EdgeNum = map(int, raw_input().split()) mygraph = DGraph(maxVertexNum) for i in range(EdgeNum): v1, v2, weight = map(int, raw_input().split()) mygraph.addOneEdge(v1 - 1, v2 -1, weight) print mygraph.Kruskal()
cc29c8c51f5b263ae3e006b946506df694846415
Akhichow/PythonCode
/contrived.py
219
4.03125
4
numbers = [7, 42, 30, 12, 60] for number in numbers: if number % 8 == 0: # Reject the numbers print("The numbers are unacceptable") break else: print("All values are acceptable")
2af20201b9f89c85e392bcf9f134f52e90542820
OblakM/FizzBuzz
/FizzBuzz.py
355
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- print "Dobrodošli v igri FizzBuzz!" izbor = int(raw_input("Izberi številko med 1 in 100: ")) for x in range(1, izbor+1): if x % 3 == 0 and x % 5 == 0: print "Fizzbuzz" elif x % 3 == 0: print "Fizz" elif x % 5 == 0: print "Buzz" else: print x
a859c4d13018d55a739e285899f57be3527a984f
kirillzx/my_python
/HW_5/postfix.py
736
3.8125
4
def calc(expr): ''' >>> calc("1 2 + 4 * 3 +") '15' >>> calc("1 2 3 * + 2 -") '5' ''' stack=[] for i in expr: if i.isdigit(): stack.append(int(i)) elif i == '+': first = stack.pop() second = stack.pop() stack.append(int(first)+int(second)) elif i == '-': first = stack.pop() second = stack.pop() stack.append(int(second)-int(first)) elif i == '*': first = stack.pop() second = stack.pop() stack.append(int(second)*int(first)) return str(stack[0]) print(calc("1 2 3 * + 2 -")) import doctest doctest.testmod()
4ad94356a9812833910b6c66deccadb4276f73fb
yoshimura19/samples
/python/kisoen/kisoen/day4/test60b2.py
441
3.53125
4
#coding:utf-8 #csvモジュールver import csv import StringIO #文字列をCSVとして処理 import sys #f = open(sys.argv[0], "r") output = [] try: while True: s = raw_input() fh = StringIO.StringIO(s) #擬似的なファイルを作成 reader = csv.reader(fh) for row in reader: output.append(row) except: pass for individual in output: print "\t".join(individual)
b2813712e2ee69ce36a0e83256af197316115fb3
jonr10/acebot
/expert_finder.py
666
3.96875
4
# Code to return a list of names of who in the team knows a certain skill. import pandas as pd def return_expert (skill): '''Function which searches skills matrix for experts, returning their names.''' skills_df = pd.read_csv('/Users/admin/Documents/Away_Days/acebot/skills_matrix.csv') try: experts = skills_df[skill].dropna().tolist() if len(experts) == 0: answer = 'Nobody has recorded knowledge in ' + skill + ', try Robin.' elif len(experts) == 1: answer = experts[0] else: answer = ', '.join(experts) except: answer = "acebot hasn't heard of " + skill return answer
7d246bba3683cf245f7e01369664d6f0cfffc4bc
mardiaz353/workingThruBool
/printfives.py
1,274
3.984375
4
for x in range(0,100): if x % 5 == 0: message = "%s is divisible by 5." print(message % x) #integer variables x = 20 #string variables text = "I like coding." #lists groceries = ["apples", "bananas", "milk", "eggs"] #boolean variables #These can be set to equal True or False #wearingHat = False #wearingBlack = True #print(wearingHat) print("Is it raining today?") #Evaluator not cooperating #Continue here next week #userInput = str(input()) #goodWeather = string #if userInput == "yes" or "Yes" or "y" or "Y": # goodWeather = True #elif userInput == "No" or "no" or "n" or "N": # goodWeather = False #else: # print("...") #if goodWeather is True: # print("You should take an umbrella with you today.") #elif goodWeather is False: # print("You don't need to lug an umbrella around.") #else: # print("I don't know what you mean.") print("Enter a 1 for yes and a 0 for no") userInput = int(input()) if userInput == 1: goodWeather = True print("Better take an umbrella") elif userInput == 0: goodWeather = False print("No need for an umbrella") #The above works, therefore, the issue must have something to do #with using a string to get a user input vs a number to relate #the boolean variable goodWeather to
731bd4fa1059f7167fa6a9147b8e5ad1a8539e99
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/2cc92142d8e54a388a3804b6a2a1c412.py
1,159
3.78125
4
import string import re class Phrase: def __init__(self, input_phrase): """Keep the constructor unit test happy. May as well create member phrase.""" self.phrase = input_phrase def simplified_phrase(self): """Prepare and butcher phrase into a string of single-space separated words.""" # Remove punctuation new_phrase = re.sub('[%s]' % re.escape(string.punctuation), '', self.phrase) # Collapse multiple adjacent spaces new_phrase = re.sub(' +', ' ', new_phrase) # Return value should be ready to be consumed by word_count() return new_phrase def word_count(self): """Count the words in the phrase input into the constructor.""" word_counter = {} for word in self.simplified_phrase().split(' '): normalized_word = word.lower() if word_counter.has_key(normalized_word): # increment count for repeated word word_counter[normalized_word] += 1 else: # first time we have encountered a word word_counter[normalized_word] = 1 return word_counter
4d93c23e5c5f484082cbdef237320ddb83f078e8
samlee916/Python-Crash-Course
/StringReplace.py
152
4.25
4
#An example of string replacing a = "Hello World" #implementing the replace function a = a.replace("Hello", "Goodbye")#replaces hello with goodbye print(a)
abdb89d988b4963cfd557b5cc31743385a37991a
shikhinarora/basic-data-structures
/stack.py
711
3.734375
4
class Stack: top = None # add and remove form here def __init__(self): self.top = None def is_empty(self): return self.top is None def peek(self): if self.top is None: return 'Empty stack' else: return self.top.data def push(self, data): node = Node(data) node.nxt = self.top self.top = node def pop(self): if self.top is not None: data = self.top.data self.top = self.top.nxt return data else: return 'Empty stack' class Node: data = None nxt = None def __init__(self, data): self.data = data
9135cf2281ac4e479a814cc9adf2acc5aa8fca4c
lalitsiraswa/TicTacToe
/Tic-Tac-Toe Multiplayer.py
3,544
4.0625
4
game_board = {1 : " ", 2 : " ", 3 : " ", 4 : " ", 5 : " ", 6 : " ", 7 : " ", 8 : " ", 9 : " "} def print_game_board(): print(" | | ") print(f" {game_board[1]} | {game_board[2]} | {game_board[3]} ") print(" | | ") print("-----------------") print(" | | ") print(f" {game_board[4]} | {game_board[5]} | {game_board[6]} ") print(" | | ") print("-----------------") print(" | | ") print(f" {game_board[7]} | {game_board[8]} | {game_board[9]} ") print(" | | ") def playGame(): turn = "X" count = 0 while(count < 9): print_game_board() place = int(input(f"Please Select A Position To Place An '{turn}'[1-9] : ")) if game_board[place] == " ": game_board[place] = turn else: print("That Place Is Already Filled.\nPlease Choose Other Place?") continue if game_board[1] != " ": if(game_board[1] == game_board[2] == game_board[3]): print_game_board() print("\nGame Over.\n") print("**** " +turn + " won. ****") break if(game_board[1] == game_board[5] == game_board[9]): print_game_board() print("\nGame Over.\n") print("**** " +turn + " won. ****") break if(game_board[1] == game_board[4] == game_board[7]): print_game_board() print("\nGame Over.\n") print("**** " +turn + " won. ****") break if game_board[2] != " ": if(game_board[2] == game_board[5] == game_board[8]): print_game_board() print("\nGame Over.\n") print("**** " +turn + " won. ****") break if game_board[3] != " ": if(game_board[3] == game_board[6] == game_board[9]): print_game_board() print("\nGame Over.\n") print("**** " +turn + " won. ****") break if(game_board[3] == game_board[5] == game_board[7]): print_game_board() print("\nGame Over.\n") print("**** " +turn + " won. ****") break if game_board[4] != " ": if(game_board[4] == game_board[5] == game_board[6]): print_game_board() print("\nGame Over.\n") print("**** " +turn + " won. ****") break if game_board[7] != " ": if(game_board[7] == game_board[8] == game_board[9]): print_game_board() print("\nGame Over.\n") print("**** " +turn + " won. ****") break if turn == "X": turn = "0" else: turn = "X" count = count + 1 if count == 9: print("\nGame Over.\n") print("It's a Tie!!") restart = input("Do want to play Again?(y/n)") if restart == "y" or restart == "Y": for keys in game_board.keys(): game_board[keys] = " " playGame() if __name__ == "__main__": print("----------------------------------------") print("Welcome To Tic-Tac_Toe !") playGame()
f2f47deb6c48a0bc979a40412dfba59c0998c84b
tammytdo/SP2018-Python220-Accelerated
/Student/tammyd_Py220/Py220_lesson10/jit_test.py
3,877
3.515625
4
""" Exploring PyPy Code with notes """ # pypy is a fast, compliant alternative implementation of the Python language with several advantages and distinct features # speed = it is a just in time compiler that is faster than python # memory usage # compatibility # stackless import math import time TIMES = 10000000 # take a snapshot of system clock init = time.clock() # run an operation for i in range(TIMES): value = math.sqrt(1 + math.fabs(math.sin(i - math.cos(i)))) print("No function: %s" % (time.clock() - init)) # Factoring the math into a function def calcMath(i): return math.sqrt(i + math.fabs(math.sin(i - math.cos(i)))) # take another snapshot of system clock init = time.clock() for i in range(TIMES): calue = calcMath(i) # check the difference. This time there is a function. #factored out this expression and put it into a fuction print("Function: %s" % (time.clock() - init)) # run TIMES = 1000000 under python 3.5. # output # No function: 1.141732 # Function: 1.2815550000000002 # run TIMES = 100000000 under python 3.5. # # not yet using jit compiler. still using standard python # output # No function: 111.869146 # Function: 123.371944 # Rick changed into another environment. ## Python 3.6.4 was slower than Python 2.7.14! # now let's try Pypy. # It will run on top of Python 2.7.13 # Tammys-MBP:Py220_lesson10 tammydo$ pypy jit_test.py # output # No function: 0.845679 # Function: 0.863227 # Pypy is so much faster! # # ------------------------------------------------------- # # Timeit tutorial # # rriehle # from timeit import timeit as timer # my_repititions = 10000 # my_range = 10000 # my_lower_limit = my_range / 2 # my_list = list(range(my_range)) # def multiply_by_two(x): # return x * 2 # def greater_than_lower_limit(x): # return x > my_lower_limit # print("\n\nmap_filter_with_functions") # # map_filter_with_functions = map(multiply_by_two, filter(greater_than_lower_limit, my_list)) # # print(*map_filter_with_functions) # print(timer( # 'map_filter_with_functions = map(multiply_by_two, filter(greater_than_lower_limit, my_list))', # globals=globals(), # number=my_repititions # )) # print("\n\nmap_filter_with_lambdas") # # map_filter_with_lambdas = map(lambda x: x * 2, filter(lambda x: x > my_lower_limit, my_list)) # # print(*map_filter_with_lambdas) # print(timer( # 'map_filter_with_lambdas = map(lambda x: x * 2, filter(lambda x: x > my_lower_limit, my_list))', # globals=globals(), # number=my_repititions # )) # print("\n\ncomprehension") # # comprehension = [x * 2 for x in my_list if x > my_lower_limit] # # print(*comprehension) # print(timer( # 'comprehension = [x * 2 for x in my_list if x > my_lower_limit]', # globals=globals(), # number=my_repititions # )) # print("\n\ncomprehension_with_functions") # # comprehension_with_functions = [multiply_by_two(x) for x in my_list if greater_than_lower_limit(x)] # # print(*comprehension_with_functions) # print(timer( # 'comprehension_with_functions = [multiply_by_two(x) for x in my_list if greater_than_lower_limit(x)]', # globals=globals(), # number=my_repititions # )) # print("\n\ncomprehension_with_lambdas") # # comprehension_with_lambdas = [lambda x: x * 2 for x in my_list if lambda x: x > my_lower_limit] # # comprehension_with_lambdas = [(lambda x: x * 2)(x) for x in my_list if (lambda x: x)(x) > my_lower_limit] # # print(*comprehension_with_lambdas) # print(timer( # 'comprehension_with_lambdas = [(lambda x: x * 2)(x) for x in my_list if (lambda x: x)(x) > my_lower_limit]', # globals=globals(), # number=my_repititions # )) # # Consider order of operations between the forms. # # In map_filter_with_functions the filter is applied before the map expression # # Is that true in the other variatins?
1d5e315f7aaba915a01b88326dd4e2f91b31cf0f
devil122/Leetcode
/009.isPalindrome.py
1,039
4.34375
4
'''第9题: 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 链接:https://leetcode-cn.com/problems/palindrome-number/ ''' class solution: #方法1:将整数转换为字符串 def isPalindrome1(self,x): if x >=0 : x_str = str(x) x_palindrome = x_str[::-1] x_converse = int(x_palindrome) return True if x_converse==x else False else: return False #方法2:还是字符串,简洁实现 def isPalindrome2(self,x): x_str = str(x) l = len(x_str) h =l//2 return x_str[:h]==x_str[-1:-h-1:-1] #方法3:直接对其求反转之后的数,不使用字符串反转 def isPalindrome3(self,x): if x<0: return False y,res = x,0 while y!=0: res = res*10+y%10 y //= 10 return True if res==x else False #测试 s = solution() print(s.isPalindrome3(0))
6602ebeb4713997bffd5eb83828b87c5d23b897c
PierreVieira/Python_Examples
/Generators.py
280
3.84375
4
""" Generators seriam as tuple comprehension. """ print(all(nome[0] == 'C' for nome in ['Carlos', 'Camila', 'Cassiano'])) gen = (i for i in range(10)) for c in gen: print(c) #Na segunda utilização já não tem mais nada disponível em gen for c in gen: print(c)
eeae711847e9e4fde225b527f79f4e0ea1399298
genedeh/8gradeGame
/PowerClass.py
575
3.578125
4
class Power: Energy = "50%" def __init__(self, speed, strength, agility): self.speed = speed self.strength = strength self.agility = agility def __str__(self): return f"({self.agility}, {self.speed}, {self.strength})" def __eq__(self, other): return self.speed == other.speed and self.strength == other.strength def __gt__(self, other): return self.speed > other.speed and self.strength > other.strength power = Power(2.2, 100, 2000) other = Power(2.2, 4, 3) print(power.agility)
c3f0ea2c9f5a45b7ac607e025040e7dd022c0a38
pi-2021-2-db6/lecture-code
/aula03-vars-e_s/antecessor_sucessor.py
236
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Dado um inteiro positivo, calcular o antecessor e o sucessor @author: Prof. Diogo SM """ x = int(input("Digite um inteiro: ")) print(f"Antecessor: {x - 1}") print(f"Sucessor: {x + 1}")
a0f530a838a9ee225ebfd03628757d4430fcd37d
noahjeffers/CS50
/pset6/cash.py
1,087
4.15625
4
from cs50 import get_float # Main method for determining how much change is owed to a person def main(): cents = valid_input() # multiplies the change owed by 100 to find out how many cents are owed cents = cents * 100 # Converts the float to an int to round down every time # Divides the cents by 25 to find out how many quarters # then places the remainder of cents / 25 into the variable change quarters = int(cents / 25) change = cents % 25 # Repeats the previous two steps with each different demonination to find the vaid change dimes = int(change / 10) change = change % 10 nickels = int(change / 5) change = change % 5 pennies = change / 1 # adds all of the different types of coins together to find out how much change is required totalChange = quarters + dimes + nickels + pennies print(int(totalChange)) # A method to return a valid input that is greater than 1 cent def valid_input(): while True: n = get_float("Change owed: ") if n >= .01: break return n main()
5b3d002343c49658febf6e645cd754c9b9ab05dd
dbmccoy/sample
/Python/ex9.py
583
3.8125
4
import random playing = True play_counts = 0 while playing == True: n = random.randint(1,9) isInt = False print('let\'s play a a game') print('type "exit" to quit') while isInt == False: try: i = float(input('enter a number> ')) except: if(i == 'exit'): break isInt = True if(i == n): print('wow u got it') elif(i < n): print('too low') else: print('too high') play_counts += 1 print('you played ' + play_counts + ' times')
1bd275df7a0de790414b6394c46dcf9b85de8c41
sophieball/BiggerLab_2019_winter
/pong_2_balls/ball.py
1,429
3.828125
4
import pygame class Ball: def __init__(self, c, r, d_x, d_y, i_p): self.color = c self.radius = r self.delta_x = d_x self.delta_y = d_y self.spot = i_p self.lose = False self.point = 0 def draw_ball(self, screen): pygame.draw.circle(screen, self.color, self.spot, self.radius) def move_ball(self, width, height, board_x, board_width, board_height): # if lost, no need to move if self.lose: return self.lose collide = False # automatically moves the circle x = self.spot[0] y = self.spot[1] x = x + self.delta_x # within board range if (x < self.radius) or (x > width - self.radius): self.delta_x = -1 * self.delta_x y = y + self.delta_y # check collision if board_x <= x and x <= board_x + board_width and \ y >= height - board_height - self.radius: collide = True self.point += 1 # bounce if hits board if (y < self.radius) or collide: self.delta_y = -1 * self.delta_y collide = False # game over if not hits board elif y > height + self.radius: self.lose = True self.spot = (x, y) return self.lose def print_points(self): return self.point class Dog: def __init__(self, n, h, w): self.name = n self.height = h self.weight = w print self.name, self.height def call(self): print self.name qiuqiu = Dog("qiuqiu", 0.5, 30) qiuqiu.call() yongshi = Dog("yongshi", 0.8, 10) yongshi.call() xiquan = Dog("xiquan", 0.2, 30)
80ac29fda6653fe9ab1ebd4190ce7a0d0f98adf7
tranphibaochau/LeetCodeProgramming
/Medium/validate_stack_sequences.py
536
3.75
4
#Given two sequences pushed and popped with distinct values, #return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack. #Hint: Greedy Algorithm def validateStackSequences(pushed, popped): result = [] l = 0 for n in pushed: result.append(n) while result and result[-1] == popped[l]: #pop the stack as long as you see it at the top of the popped result.pop() l+=1 return not result
fc829327a7e52b62bc8d5e328e4adafd331ef9df
Qudratullo/ocr
/neural/layers.py
4,793
3.515625
4
import numpy as np def l2_regularization(W, reg_strength): """ Computes L2 regularization loss on weights and its gradient Arguments: W, np array - weights reg_strength - float value Returns: loss, single value - l2 regularization loss gradient, np.array same shape as W - gradient of weight by l2 loss """ # TODO: Copy from the previous assignment loss = reg_strength * np.sum(W * W) grad = reg_strength * 2 * W return loss, grad def softmax(predictions): ''' Computes probabilities from scores Arguments: predictions, np array, shape is either (N) or (batch_size, N) - classifier output Returns: probs, np array of the same shape as predictions - probability for every class, 0..1 ''' preds = predictions.copy() preds -= np.max(preds, axis=1, keepdims=True) return np.exp(preds) / np.sum(np.exp(preds), axis=1, keepdims=True) def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments: probs, np array, shape is either (N) or (batch_size, N) - probabilities for every class target_index: np array of int, shape is (1) or (batch_size) - index of the true class for given sample(s) Returns: loss: single value ''' n_samples = probs.shape[0] return np.mean(-np.log(probs[np.arange(n_samples), target_index])) def softmax_with_cross_entropy(preds, target_index): """ Computes softmax and cross-entropy loss for model predictions, including the gradient Arguments: predictions, np array, shape is either (N) or (batch_size, N) - classifier output target_index: np array of int, shape is (1) or (batch_size) - index of the true class for given sample(s) Returns: loss, single value - cross-entropy loss dprediction, np array same shape as predictions - gradient of predictions by loss value """ probes = softmax(preds) loss = cross_entropy_loss(probes, target_index) dprediction = probes.copy() n_samples = probes.shape[0] dprediction[np.arange(n_samples), target_index] -= 1 dprediction /= n_samples return loss, dprediction class Param: """ Trainable parameter of the model Captures both parameter value and the gradient """ def __init__(self, value): self.value = value self.grad = np.zeros_like(value) # @np.vectorize def ReLU(x): return x if x > 0 else 0 # def ReLU(X): # return (X + np.abs(X)) / 2 class ReLULayer: def __init__(self): pass def forward(self, X): # Hint: you'll need to save some information about X # to use it later in the backward pass self.input = X.copy() return np.maximum(0, self.input) def backward(self, d_out): """ Backward pass Arguments: d_out, np array (batch_size, num_features) - gradient of loss function with respect to output Returns: d_result: np array (batch_size, num_features) - gradient with respect to input """ d_cur = self.input > 0 d_result = d_out * d_cur return d_result def params(self): # ReLU Doesn't have any parameters return {} class FullyConnectedLayer: def __init__(self, n_input, n_output): self.W = Param(0.001 * np.random.randn(n_input, n_output)) self.B = Param(0.001 * np.random.randn(1, n_output)) self.X = None def forward(self, X): # Your final implementation shouldn't have any loops self.X = Param(X.copy()) result = self.X.value.dot(self.W.value) + self.B.value return result def backward(self, d_out): """ Backward pass Computes gradient with respect to input and accumulates gradients within self.W and self.B Arguments: d_out, np array (batch_size, n_output) - gradient of loss function with respect to output Returns: d_result: np array (batch_size, n_input) - gradient with respect to input """ # Compute both gradient with respect to input # and gradients with respect to W and B # Add gradients of W and B to their `grad` attribute # It should be pretty similar to linear classifier from # the previous assignment d_input = d_out.dot(self.W.value.T) grad_weights = self.X.value.T.dot(d_out) grad_bias = np.sum(d_out, axis=0).reshape(1, -1) self.W.grad += grad_weights self.B.grad += grad_bias return d_input def params(self): return {'W': self.W, 'B': self.B}
a782a9e0bcf49591bb1b10860f4a6a68bae87c35
annazwiggelaar/Python_assessment
/Program 3 Anna Zwiggelaar & Lieke Spoelstra.py
2,856
3.890625
4
# Program by Anna Zwiggelaar and Lieke Spoelstra. import random bingo_list = [] random_bingo_list = [] with open("bingo.txt", "r") as myfile: # add file words to bingo list for word in myfile: bingo_list.append(word.rstrip("\n")) def generate_random_list(word_list, rand_list): while len(rand_list) < 25: word = random.choice(word_list) if word in rand_list: continue else: rand_list.append(word.rstrip("\n")) def generate_card(word_list, rand_list): generate_random_list(word_list, rand_list) x = rand_list a = 0 card = [[x[a], x[a + 1], x[a + 2], x[a + 3], x[a + 4]], [x[a + 5], x[a + 6], x[a + 7], x[a + 8], x[a + 9]], [x[a + 10], x[a + 11], x[a + 12], x[a + 13], x[a + 14]], [x[a + 15], x[a + 16], x[a + 17], x[a + 18], x[a + 19]], [x[a + 20], x[a + 21], x[a + 22], x[a + 23], x[a + 24]]] return card def print_card(card): # print bingo card, equal distance between words for row in card: print("{: >20} {: >20} {: >20} {: >20} {: >20}".format(*row)) def mark_word(coordinate1, coordinate2, card): # replace word that was shown with an X card[coordinate1][coordinate2] = "X" def play_game(word_list, rand_list): card = generate_card(word_list, rand_list) print_card(card) for i in range(25): index1 = int(input("Please enter the first coordinate of the word (x coordinate) : ")) index2 = int(input("Please enter the second coordinate of the word (y coordinate): ")) mark_word(index1, index2, card) print_card(card) print("This program will generate a bingo card at random from the words you " "entered in program 1.\nProgram 2 draws words from the pool of 35 words " "entered by you.\nWhen a word comes up in program 2 that is on your " "bingo card, you need to enter the coordinates of that word on your " "card in order to mark it.\nThe way to do this is to enter the coordinate " "of the row (the x coordinate) first and then enter the coordinate of " "the word on that row (the y coordinate).\nThe first row has coordinate 0, " "the second row has coordinate 1, etc. The first word on a row has " "coordinate 0, the second word has coordinate 1, etc.\nSo, the second " "word on the third row would have coordinates 2 (for the row) and 1 " "(for the word).") ready_to_start = input("Enter 'yes' when ready to start the game: ") if ready_to_start == "yes": play_game(bingo_list, random_bingo_list) new_game = input("Do you want to play another game? ") if new_game == "yes": del random_bingo_list[0:len(random_bingo_list)+1] play_game(bingo_list, random_bingo_list) elif new_game == "no": print("Thank you for playing. You may close all programs.")
d0b102940a2cd39fa058d2a900b7bbf337ff7500
JohnWZ/l_c_repo
/1_two_sum.py
239
3.578125
4
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for num1 in List: for num2 in List: if num1 + num2 == target and num1 != num2: return arr[num1, num2]
3c27bf63ce070fae59b1caf936b161f85d98ddc2
lifeoftheone/python-program
/pythoncode/practical 4.py
226
3.984375
4
a=int(input("enter the marks")) print("your grade is") if(a>=80): print("A") elif(a>=60): print("B") elif(a>=50): print("C") elif(a>=45): print("D") elif(a>=25): print("E") else: print("F")
e54513a17a4369032de04030d24aed373bbcb748
thekevinsmith/leetcode-python
/problems/two_sum.py
1,201
4.0625
4
# Okay, we have an input list and a target sum, we need to achieve the # target sum through the use of integers in the input list/array. # 1. take the target and subtract until we reach zero, allow a backtrack option # 2. add to a variable and compare, until we get what we need. # 3. find the closest highest possible int, then fill up until reached. # build a list as we progress, and make that track the total sum, then if we # need to remove something, we can # input, target and list of supply. # output is the index of all the required elements. # question: is the supplied list/array already sorted? # so initially I completely misunderstood this problem... I should be using # TWO numbers to find the solution, that makes it a hell of a lot easier!!! def two_sum(supply, target): # Brute Force, optimized. for i in range(0, len(supply)): for j in range(i + 1, len(supply)): if supply[i] > target or supply[j] > target: pass elif supply[i] + supply[j] == target: return [i, j] # this problem could be further optimized by using a hash map. def main(): print("Hello World") if __name__ == "__main__": main()
4ea5fce725b7622cb6a5743f830fe4ec28adb4eb
shen-huang/selfteaching-python-camp
/19100101/raoxin007/d3_exercise_calculator.py
941
4.03125
4
#简易加减乘除计算器程序 #定义加法函数 def add(x,y): return x+y #定义减法函数 def subtract(x,y): return x-y #定义乘法函数 def multiply(x,y): return x*y #定义除法函数 def divide(x,y): return x/y #定义执行方式,当执行脚本本身,执行如下代码 if __name__ == '__main__': print("选择运算:") print("1、加") print("2、减") print("3、乘") print("4、除") choise = input("输入你的选择(1/2/3/4):") num1 = int(input("输入第一个数字: ")) num2 = int(input("输入第二个数字: ")) if choise == '1': print(num1,"+",num2,"=",add(num1,num2)) elif choise == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choise == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choise == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("你输入的有误,请重新输入")
cd18dd5a85a09408c18666e47f3c7f528e28c296
DanielG1397/mdrp-sim
/utils/datetime_utils.py
2,177
3.890625
4
import math from datetime import time, datetime, date, timedelta from typing import Union def min_to_sec(minutes: float) -> Union[float, int]: """Convert minutes to seconds""" return minutes * 60 def hour_to_sec(hours: float) -> Union[float, int]: """Convert hours to seconds""" return hours * 3600 MAX_SECONDS = hour_to_sec(23) + min_to_sec(59) + 59 def sec_to_hour(seconds: float) -> float: """Convert seconds to hours""" return seconds / 3600 def sec_to_time(seconds: int) -> time: """Convert seconds since the day started to a time object""" def next_precision_frac(interval: float) -> float: """Convert time interval to fractional next precision""" return round(math.modf(interval)[0] * 60, 4) def next_precision(interval: float) -> int: """Convert fractional time interval to next precision""" return min(round(next_precision_frac(interval)), 59) mod_seconds = MAX_SECONDS if seconds >= MAX_SECONDS else seconds raw_hours = mod_seconds / 3600 return time( hour=math.floor(raw_hours), minute=next_precision(raw_hours), second=next_precision(next_precision_frac(raw_hours)) ) def time_to_sec(raw_time: time) -> Union[float, int]: """Convert time object to seconds""" return hour_to_sec(raw_time.hour) + min_to_sec(raw_time.minute) + raw_time.second def time_to_query_format(query_time: time) -> str: """Parse a time object to a str available to use in a query""" return f'\'{query_time.hour}:{query_time.minute}:{query_time.second}\'' def time_diff(time_1: time, time_2: time) -> float: """Returns the difference in seconds of time_1 - time_2""" diff = datetime.combine(date.today(), time_1) - datetime.combine(date.today(), time_2) return diff.total_seconds() def time_add(time_to_add: time, seconds: float) -> time: """Adds the desired seconds to the time provided""" return (datetime.combine(date.today(), time_to_add) + timedelta(seconds=seconds)).time() def time_to_str(time_to_convert: time) -> str: """Converts a time object to str""" return time_to_convert.strftime('%H:%M:%S')
81ca9e9631e82dfb321dce30f1e4d3b118d7cc5f
vishalpmittal/practice-fun
/funNLearn/src/main/java/dsAlgo/leetcode/P4xx/P496_NextGreaterElementI.py
1,643
4.125
4
""" Tag: array, integer You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4]. Output: [3,-1] Explanation: For number 2 in the first array, the next greater number for it in the second array is 3. For number 4 in the first array, there is no next greater number for it in the second array, so output -1. Note: - All elements in nums1 and nums2 are unique. - The length of both nums1 and nums2 would not exceed 1000. """ def nextGreaterElement(nums1, nums2): d, st = {}, [] for n in nums2: while len(st) and st[-1] < n: d[st.pop()] = n st.append(n) ans = [] for x in nums1: ans.append(d.get(x, -1)) return ans def test_code(): assert nextGreaterElement([4, 1, 2], [1, 3, 4, 2]) == [-1, 3, -1] print("Tests Passed!!") test_code()
cd4b296072962c76d49e09393822a9cbbff13ec3
shivesh01/Python-Basics
/Numpy/Numpy_2.py
195
3.5625
4
# Numpy Array import numpy as np A = np.array([[1, 2, 3], [3, 4, 5]]) print(A) A = np.array([[1.1, 2, 3], [3, 4, 5]]) print(A) A = np.array([[1, 2, 3], [3, 4, 5]], dtype=complex) print(A)
8d77834aaefbfa28a31150c6ad8359362b6b4326
Rounak259/HackerEarth
/Basic Programming/roy_and_profile_picture.py
356
3.625
4
acc_dim = int(input()) test_case = int(input()) for i in range(0, test_case): w, h = input().split() w = int(w) h = int(h) if (w==acc_dim and h==acc_dim) or (w==h and w>acc_dim): print("ACCEPTED") else: if w<acc_dim or h<acc_dim: print("UPLOAD ANOTHER") else: print("CROP IT")
5bec8158c4c96392342872da7d0650c4abb8d4f5
pasaunders/code-katas
/src/scores.py
144
3.53125
4
"""Average the values in a list and round to the nearest whole number.""" def average(scores): return int(round(sum(scores)/len(scores)))
aaf21059cf4f6b0bab503c4c1bf152bf59fcf79b
MarcosFantastico/Python
/Exercicios/ex076.py
727
3.578125
4
print('=' * 40) print(f'{" LISTAGEM DE PREÇOS ":^40}') print('=' * 40) produtos = ('Lapis', 1.50, 'Borracha', 1.00, 'Cola', 4.69, 'Caderno', 3.50, 'Mochila', 120.30) '''print(f'{produtos[0]:.<30}R${produtos[1]:>7.2f}\n{produtos[2]:.<30}R${produtos[3]:>7.2f}\n{produtos[4]:.<30}R$' f'{produtos[5]:>7.2f}\n{produtos[6]:.<30}R${produtos[7]:>7.2f}\n{produtos[8]:.<30}R${produtos[9]:>7.2f}')''' for pos, prod in enumerate(produtos): if pos % 2 == 0: print(f'{prod:.<30}', end='') else: print(f'R${prod:>7.2f}') '''for pos in range(0, 10): if pos % 2 == 0: print(f'{produtos[pos]:.<30}', end='') else: print(f'R${produtos[pos]:>7.2f}')''' print('=' * 40)
d5a1a4875974bd2237cebfa9803dbb27997367d0
AlexOvey/pythonDoc
/pythonSwitch.py
1,555
4.1875
4
import sys import os import turtle # def PrintBlue(): # print("You chose blue!\r\n") # def PrintRed(): # print("You chose Red!\r\n") # def PrintOrange(): # print("You chose Orange!\r\n") # def PrintYellow(): # print("You chose Yellow!\r\n") # def PrintGreen(): # print("You chose Green!\r\n") # colorSelect = { # 0: PrintBlue, # 1: PrintRed, # 2: PrintOrange, # 3: PrintYellow, # 4: PrintGreen # } # selection = 0 # while (selection !=5): # print("0. Blue") # print("1. Red") # print("2. Orange") # print("3. Yellow") # print("4. Green") # print("5. Quit") # selection = int(input("Select a color option: ")) # if (selection >= 0) and (selection<5): # colorSelect[selection]() def draw_square(animal, size): """ make animal draw a square with sides of length size. """ for _ in range(): animal.width(2) animal.color("brown") animal.forward(size) animal.left(90) window = turtle.Screen() #set up the window and its attribute window.bgcolor("#ffffff") #or window.bgcolor("#00000f") window.title("drawing square with turtle") alex = turtle.Turtle() #Create alex jame = turtle.Turtle() draw_square(alex, 300) #or draw_square(jame, 268)#call the function to draw the square window.mainloop() def draw_hexagon(animal, size): for _ in range(8): animal.width(2) animal.color("#00000f") animal.forward(size) animal.left (60) window = turtle.Screen() window.bgcolor("f7f7f7f7f") window.title("drawing Hexagon with turtle") james = turtle.Turtle() draw_hexagon(james, 100) window.mainloop()
8d77275a231e3c324403d1ca6dd1e1271c1d37f5
BrettMcGregor/dailyprogrammer
/easy_30.py
503
4.125
4
# Write a program that takes a list of integers # and a target number and determines if any two # integers in the list sum to the target number. # If so, return the two numbers. If not, return # an indication that no such integers exist. from itertools import permutations as perm def sum_target(nums, target): a = perm(nums, 2) while True: x, y = next(a) print(x,y) if x + y == target: return x, y return False print(sum_target([1, 3, 4, 5, 6], 9))
59c6d3458d61cf65aa045b2e8917e205728ae4cf
ldunphy1/504
/Additional_Files/dijkstra_timedtests.py
6,521
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 9 13:41:35 2016 @author: montgomt """ from itertools import combinations from imp import reload import csv from graph import Graph from time import time import dijkstra reload(dijkstra) import os def graph_from_file(filename,num_nodes): '''reads edgelist from file and creates a graph object''' g = Graph() for i in range(1,num_nodes+1): g.add_vertex(str(i)) with open(filename,'r') as f: reader = csv.reader(f, delimiter = ',') for row in reader: g.add_edge(row[0],row[1],int(row[2])) return g def single_timed_test(g,u,v,structure): '''runs a single instance of the Dijkstra algorithm on a graph g with starting node u and ending node v. structure refers to the type data structure used''' t0 = time() dijkstra.dijkstra(g,g.get_vertex(u),structure) target = g.get_vertex(v) path = [target.get_id()] dijkstra.shortest(target, path) t1 = time() return t1-t0 def repeat_timed_test(G,u,v,numtests): '''tests all graphs in G for shortest path from u to v a repeated number of times using all three data structures. Returns results as a 2D list, with rows representing test and columns representing data structure result for that test.''' #results = [[None,None,None] for i in range(numtests)] for i in range(numtests): print(' Running Test #',i) bin_duration = single_timed_test(G[i],str(u),str(v),'Binomial') fib_duration = single_timed_test(G[i],str(u),str(v),'FibHeap') minh_duration = single_timed_test(G[i],str(u),str(v),'MinHeap') results[i] = [bin_duration,fib_duration,minh_duration] return results '''------------run the tests when file is executed--------------''' if __name__ == '__main__': '''Testing by graph size in number of nodes and by density There are 'numtests' versions of each graph for each size/density''' numtests = 5 '''graph containers''' g100_10 = [None]*numtests g200_10 = [None]*numtests g300_10 = [None]*numtests g400_10 = [None]*numtests g500_10 = [None]*numtests g100_75 = [None]*numtests g200_75 = [None]*numtests g300_75 = [None]*numtests g400_75 = [None]*numtests g500_75 = [None]*numtests '''build graphs for each test of each graph size and density''' script_dir = os.path.dirname("__file__") for i in range(numtests): filename100_10 = os.path.join(script_dir,'Edgelists/E100_10_' +str(i+1) +'.csv') filename200_10 = os.path.join(script_dir,'Edgelists/E200_10_' +str(i+1) +'.csv') filename300_10 = os.path.join(script_dir,'Edgelists/E300_10_' +str(i+1) +'.csv') filename400_10 = os.path.join(script_dir,'Edgelists/E400_10_' +str(i+1) +'.csv') filename500_10 = os.path.join(script_dir,'Edgelists/E500_10_' +str(i+1) +'.csv') filename100_75 = os.path.join(script_dir,'Edgelists/E100_75_' +str(i+1) +'.csv') filename200_75 = os.path.join(script_dir,'Edgelists/E200_75_' +str(i+1) +'.csv') filename300_75 = os.path.join(script_dir,'Edgelists/E300_75_' +str(i+1) +'.csv') filename400_75 = os.path.join(script_dir,'Edgelists/E400_75_' +str(i+1) +'.csv') filename500_75 = os.path.join(script_dir,'Edgelists/E500_75_' +str(i+1) +'.csv') g100_10[i] = graph_from_file(filename100_10,100) g200_10[i] = graph_from_file(filename200_10,200) g300_10[i] = graph_from_file(filename300_10,300) g400_10[i] = graph_from_file(filename400_10,400) g500_10[i] = graph_from_file(filename500_10,500) g100_75[i] = graph_from_file(filename100_75,100) g200_75[i] = graph_from_file(filename200_75,200) g300_75[i] = graph_from_file(filename300_75,300) g400_75[i] = graph_from_file(filename400_75,400) g500_75[i] = graph_from_file(filename500_75,500) r100to500_10 = [None]*5 print('Running Dijkstra tests for 100 nodes,10% density...') r100to500_10[0] = repeat_timed_test(g100_10,1,100,numtests) print('Running Dijkstra tests for 200 nodes,10% density...') r100to500_10[1] = repeat_timed_test(g200_10,1,200,numtests) print('Running Dijkstra tests for 300 nodes,10% density...') r100to500_10[2]= repeat_timed_test(g300_10,1,300,numtests) print('Running Dijkstra tests for 400 nodes,10% density...') r100to500_10[3] = repeat_timed_test(g400_10,1,400,numtests) print('Running Dijkstra tests for 500 nodes,10% density...') r100to500_10[4] = repeat_timed_test(g500_10,1,500,numtests) r100to500_75 = [None]*5 print('Running Dijkstra tests for 100 nodes,75% density...') r100to500_75[0] = repeat_timed_test(g100_75,1,100,numtests) print('Running Dijkstra tests for 200 nodes,75% density...') r100to500_75[1] = repeat_timed_test(g200_75,1,200,numtests) print('Running Dijkstra tests for 300 nodes,75% density...') r100to500_75[2]= repeat_timed_test(g300_75,1,300,numtests) print('Running Dijkstra tests for 400 nodes,75% density...') r100to500_75[3] = repeat_timed_test(g400_75,1,400,numtests) print('Running Dijkstra tests for 500 nodes,75% density...') r100to500_75[4] = repeat_timed_test(g500_75,1,500,numtests) for n in range(100,200,100): filename = 'results' +str(n)+'_10.csv' with open(filename,'wb') as f: writer = csv.writer(f,delimiter=',') for i in range(numtests): writer.writerow(r100to500_10[int(n/100)-1][i]) filename = 'results' +str(n)+'_75.csv' with open(filename,'wb') as f: writer = csv.writer(f,delimiter=',') for i in range(numtests): writer.writerows(r100to500_75[int(n/100)-1][i]) '''Testing by trying all combinations of start/finish nodes ***Currently only runs test on one graph..need to change hardcode to use different ones***''' sfnodes = list(combinations(range(1,200),2)) results_combos = [None]*len(sfnodes) for i,combo in enumerate(sfnodes): print('Start/Finish combination test #', i) results_combos[i] = repeat_timed_test(g200_10,combo[0],combo[1],1) with open('results_combos_200.csv','wb') as fn: writer = csv.writer(fn,delimiter=',') for row in results_combos: writer.writerow(row)
e081e86479fef455e3a3ccba073a570101730206
RenanBertolotti/Python
/Uri Judge - Python/URI-1097.py
307
3.921875
4
"""Você deve fazer um programa que apresente a sequencia conforme o exemplo abaixo. Entrada Não há nenhuma entrada neste problema. Saída Imprima a sequencia conforme exemplo abaixo.""" valor = 7 for i in range(1, 10, 2): for j in range(valor, (valor - 3), -1): print(f"I={i} J={j}") valor += 2
d089f2a07d66d6f247393e5168e08e7171bc79cd
andymc1/ipc20161
/lista1/ipc_lista1.12.py
376
3.71875
4
#ipc_lista1.12 #Professor: Jucimar Junior #Any Mendes Carvalho - 1615310044 # # # # #Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo que calcule seu peso ideal, usando a seguinte fórmula: \n (72.7*altura) - 58 altura = input("Digite sua altura em metros, separa por ponto (ex: 1.70): ") vT = 72.7 * altura resultado = vT - 58 print "Seu peso ideal e ",resultado
ffa48e13ca56b07b0e65d00de1e0e8a27e8b84db
ElliotPenson/cryptography
/stream.py
2,315
3.96875
4
#!/usr/local/bin/python """ stream.py @author Elliot and Erica """ import sys import random from cryptography_utilities import (string_to_binary, file_to_binary, binary_to_file) def psuedo_random_register_fn(key): """Provide a register function that gives the next bit in the keystream. In this case use the key to seed into python's pseudo-random number generator. """ random.seed(key) def register_fn(): return str(random.randint(0, 1)) return register_fn def xor_combiner(binary): """Collapse a sequence of bits into a single bit by XOR.""" return '1' if reduce(lambda x, y: x != y, binary) else '0' def setup_register(key, register_fn, size=50): """Generate an initial register with the key. If the key doesn't fill the minimum register size, call register_fn until it does. """ binary_key = list(string_to_binary(key)) if len(binary_key) < size: return binary_key + [register_fn() for _ in range(size - len(binary_key))] else: return binary_key def update_register(register, register_fn): """Nondestructively advance the bit register.""" return register[1:] + [register_fn()] def stream_cipher(binary_text, key, combiner_fn, register_fn): """Encrypt or decrypt a binary string of text by combining a maintained register with each successive bit of binary_text. :param binary_text: a string of 1s and 0s :param key: an alphanumeric password :param combiner_fn: takes the register and outputs a single bit :param register_fn: gives the next bit in the keystream """ register = setup_register(key, register_fn) output = '' for bit in binary_text: register = update_register(register, register_fn) output += '1' if combiner_fn(register) != bit else '0' return output def main(args): if len(args) != 4: print ('usage: {} <key> <input_file> <output_file>').format(args[0]) return 1 _, key, input_file, output_file = args binary_input = file_to_binary(input_file) converted_text = stream_cipher(binary_input, key, xor_combiner, psuedo_random_register_fn(key)) binary_to_file(converted_text, output_file) if __name__ == '__main__': main(sys.argv)
4a4b999ff1fbc251760559241300abb465c3b82e
PlumpMath/DesignPattern-1033
/python/templateMethod/templateMethod.py
1,243
3.859375
4
#! /user/bin/env python # -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod class AbstractDisplay(metaclass = ABCMeta): @abstractmethod def openChar(self): pass @abstractmethod def printInput(self): pass @abstractmethod def closeChar(self): pass def display(self): self.openChar() for i in range(0, 5): self.printInput() self.closeChar() class CharDisplay(AbstractDisplay): def __init__(self, ch): self.__ch = ch def openChar(self): print('<<', end = '') def printInput(self): print(self.__ch, end = '') def closeChar(self): print('>>') class StringDisplay(AbstractDisplay): def __init__(self, string): self.__string = string self.__width = len(string.encode("UTF-8")) def openChar(self): self.__printLine() def printInput(self): print('|' + self.__string + '|') def closeChar(self): self.__printLine() def __printLine(self): print('+', end = '') for i in range(0, self.__width): print('-', end = '') print('+') if __name__ == '__main__': d1 = CharDisplay('H') d2 = StringDisplay("Hello, World.") d3 = StringDisplay("こんにちは。") d1.display() d2.display() d3.display()
32158d2c15e3eb87c0c7cf25aad6dad286b8750d
korean5078/osp_repo
/py_lab/fibo_num.py
256
3.96875
4
#!/usr/bin/python3 count = 1 n = int(input("fibonacci number? ")) a = 1 b = 1 c = 1 print(1,end=',') while count < n: if n != count+1: print(c,end=',') else: print(c) final = c a = b b = c c = a+b count = count+1 print("F%d = %d" %(n, final))
876ea3c0d443f7b69822dacee8af2beb7bf7cd6a
bmareddy/leetcode
/Python/709_to_lower_case.py
184
3.609375
4
class Solution: def toLowerCase(self, str: str) -> str: return "".join(chr(ord(c) + ord("a") - ord("A")) if ord(c) >= ord("A") and ord(c) <= ord("Z") else c for c in str)
c8f3a45a62faf37272b1c43b8495fa9577f35b45
nee-datascience/Softmax-Classification-Machine-Learning
/classifier.py
16,003
3.828125
4
import os import sys import numpy as np import pandas as pd from sklearn.linear_model import SGDClassifier # Do not change the code above # These libraries may be all those you need LABELS = ['setosa', 'versicolor', 'virginica'] # Insert your code below class SoftmaxModel: """ A softmax classifier to fit, predict and score model How to build the model (SoftmaxModel): It is just a normal class that will take an array as coefficients during initialisation. During class initialisation, we will pass a 3 5 matrix which will be used as the initial coefficient ( ) of the model. """ def __init__(self, value): self.value = value #input_3_5_np_array self.coeff = None self.X_train = None self.y_train = None self.epochs = None self.learning_rate = None self.prob_predict = None self.y_prob_max = None def fit(self, X_train, y_train, epochs, learning_rate): """ Fit model using softmax calculation (function) to find predict probability and gradient descent to update the coefficient. Repeat softmax function and gradient descent to update the predict probability and coefficient for each epoch time. How to train the model (fit): We will pass X_train, y_train, the number of epochs (the number of times we will update the coefficient), and the learning rate to the fit function. The fit function will return the coefficient after training. """ self.coeff = self.value # Input - add bias '1' first column to X_train X_train = X_add_bias_col(X_train) for i in range(epochs): # Softmax function prob_predict = softmax(X_train, self.coeff) #print('prob_predict:',prob_predict.shape, prob_predict) # Gradient Descent function self.coeff = gradient_descent(X_train, y_train, self.coeff, prob_predict, learning_rate) return self.coeff # Theata def predict(self, X_test): """ Predict the output labels. How to predict: Prediction will take X_test as the data feature that needs to be predicted. We will output a list of prediction labels based on the coefficient (an attribute of the model) we trained during the last stage. """ # Input - add bias '1' first column to X_train X_test = X_add_bias_col(X_test) prob_test = softmax(X_test, self.coeff) #print('predict:', prob_test.shape, prob_test) # 47, 3 # Get max vertical axis = 1 self.y_prob_max = np.argmax(prob_test, axis=1) #####y_prob_max_onehot = onehot_encoding(self.y_prob_max, 3) #print('self.y_prob_max:', self.y_prob_max.shape, self.y_prob_max) #print('y_prob_max_onehot:', y_prob_max_onehot.shape, y_prob_max_onehot) # Decode LABELS y_prob_max_label is for display only y_prob_max_label = decode_onehot(self.y_prob_max) ###y_prob_max_label = np.array(LABELS)[np.array(pd.DataFrame(y_prob_max_label).idxmax(axis=1))] #print('y_prob_max_label:', y_prob_max_label) return y_prob_max_label #return self.y_prob_max def score(self, X_test, y_test): """ Accuracy score of the model How to get the accuracy (score): We will compare the predicted labels with the ground true labels (y_test), to estimate the accuracy of the model prediction. """ # Mandatory: Call predict function # Do Not remove # y_prob_max_label = self.predict(X_test) #print('self.y_prob_max:', self.y_prob_max.shape, self.y_prob_max) y_test_max = np.argmax(y_test, axis=1) #print('y_test_max:',y_test_max.shape, y_test_max) accuracy = np.mean(np.equal(y_test_max, self.y_prob_max)) #print('accuracy:', accuracy) return accuracy def pre_process(trainfile, testfile): """ To pre-process the input file and provide X features and y labels with one-hot encoding as output. """ X_train, y_train = pre_process_file(trainfile) X_test, y_test = pre_process_file(testfile) return X_train, y_train, X_test, y_test def pre_process_file(file): """ To pre-process the input file by removing unit cm from sepal length and sepal width and converting mm to cm for sepal width and provide X features and y labels with one-hot encoding as output.""" num_class = len(LABELS) # number of classes dataframe = pd.read_csv(file) dataframe = dataframe.values # X array for features dataframe2 = dataframe[:,1:5] # Y array for labels dataframe3 = dataframe[:,5:6] # X features - Get and Round up 4 columns to 1 decimal point for item in dataframe2: item[0] = round(float(item[0].replace('cm','').strip()),1) item[1] = round(float(item[1].replace('mm','').strip())/1000,1) item[2] = round(item[2],1) item[3] = round(item[3],1) X_array = np.array(dataframe2, dtype=np.float) # Y labels - One hot encoding for item in dataframe3: if item[0] == 'setosa': item[0] = int(0) elif item[0] == 'versicolor': item[0] = int(1) elif item[0] == 'virginica': item[0] = int(2) y_array = onehot_encoding(dataframe3, num_class) return X_array, y_array def onehot_encoding(y, num_class): """ One-hot encoding for labels setosa as 0 0 1, versicolor as 0 1 0 and virginica as 1 0 0 """ y = np.asarray(y, dtype='int32') if len(y) > 1: y = y.reshape(-1) if not num_class: num_class = np.max(y) + 1 y_matrix = np.zeros((len(y), num_class), dtype=int) y_matrix[np.arange(len(y)), y] = 1 return y_matrix def decode_onehot(y_prob_max): """ TO decode one-hot encoding for labels 0 as setosa, 1 as versicolor and 2 as virginica """ # Y labels - One hot decoding y_prob_max_label = y_prob_max.astype(str) # Modifying array values for x in np.nditer(y_prob_max_label, op_flags = ['readwrite']): if x == '0': x[...] = 'setosa' elif x == '1': x[...] = 'versicolor' elif x == '2': x[...] = 'virginica' y_prob_max_label = np.array(y_prob_max_label) return list(y_prob_max_label) # Return output as a list def X_add_bias_col(X_train): """ Input - add bias '1' first column to X_train """ # Input - add bias '1' first column to X_train Xrows, Xcols = np.shape(X_train) #103, 4 X_train = np.hstack((np.ones((Xrows,1)),X_train)) # 103, 5 #print('X_train:',X_train.shape, X_train) return X_train def softmax(X_train, coeff): """ Softmax calculation to calculate Probability that y belongs to class k (has label k) — for the 3 species. Numerator: is the coefficients for belonging to class k, and X(i) is the feature values. Denominator: is the coefficients for belonging to class j, and X(i) is the feature values. We sum up over all classes (3 in this case). For example: if is a 3 x 5 matrix filled with 1’s, then will be [1, 1, 1, 1, 1] (the first row), and X(i) will be the values of the feature data (sepal_length, sepal_width, petal_length and petal_width) plus one column to represent the bias, so it will read as [1, sepal_length, sepal_width, petal_length, petal_width]T. We will then multiply them together. In the denominator we just need to perform exact same computation and add it all up PER EACH CLASS (K = 3 classes in this case). """ # Theata, weight, prob of 3 classes #coeff = np.dot(coeff, X_train.T) # 3, 5 dot 5, 103 (after transpose) => 3, 103 coeff = coeff @ X_train.T # 3, 5 dot 5, 103 (after transpose) => 3, 103 coeff = coeff.T #=> 103, 3 #print('softmax coeff:', coeff.shape, coeff) # CORRECT! numerator = np.exp(coeff) # 3,103 => z 103, 3 #print('numerator:',numerator.shape, numerator) denominator = np.sum(np.exp(coeff),axis=1) # e_x.sum(axis=0) #print('denominator:', denominator.shape, denominator) prob_predict = (numerator.T/denominator).T # 103, 3 divide by 1 => 103, 3 #print('prob_predict:',prob_predict.shape, prob_predict) ###total_prob = np.sum(prob_predict, axis=1) # Verification: sum axis=1 is horizontal sum ###print('total_prob:', total_prob.shape, total_prob) return prob_predict def gradient_descent(X_train, y_train, coeff_gd, prob_predict, learning_rate): """ Gradient descent to update the coefficient The Predict Probability we get from the softmax function will be used to perform the gradient descent. X(i) is defined identically as for the previous state, and Plabel(y(i) = k) will be either 1 (if the i-th datum belongs to class k) or 0, usign the one hot encoding of pre-process. The learning rate is a scalar value. """ # Gradient Descent function ############################ # z = z + c1 * c2 * X(i) # z is coefficient # c1 is y_labels with onehot encoding - prob predict (from softmax function) # c2 is learning rate # X(i) is X_features input ############################ #coeff_gd = coeff_gd + np.dot((y_train - prob_predict), X_train_5dim) * learning_rate #print('y_train:', y_train.shape, y_train) # 103,3 #print('prob_predict:', prob_predict.shape, prob_predict) # 103,3 ### coeff_gd = np.add(coeff_gd, (np.dot(np.subtract(y_train, prob_predict).T, X_train_5dim) * learning_rate)) coeff_gd = np.add(coeff_gd, np.dot((y_train-prob_predict).T, X_train) * learning_rate) #print('y_train - prob_predict:', a.shape, a) # 103,3 => transpose 3, 103 dot X 103, 5 => 3, 5 #print('coeff_gd:', coeff_gd.shape, coeff_gd) return coeff_gd def get_y_labels(y_labels): """ Get labels to be used in skl function """ #LABELS = ['setosa', 'versicolor', 'virginica'] max_label_index_df = pd.DataFrame(y_labels).idxmax(axis=1) max_label_index_matrix = np.array(max_label_index_df) y_decode_labels = np.array(LABELS)[max_label_index_matrix] return y_decode_labels def skl(X_train, y_train, X_test, y_test, random_state, max_iter): """ sklearn model testing - the function will return the score of the sklearn model https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier Input four numpy arrays, namely, X_train, y_train, X_test and y_test, as well as random_state and max_iter. How to construct the model: We just need to pass the values of random_state and max_iter when we define a SGDClassifier. In this project, we use “log” as the loss function. Tolerance will set to 1e-3 by default. Fit and score will be easily retrieved by studying the material linked to above. """ # To decode one-hot encoding y_train and y_test to return labels as output y_train_labels = get_y_labels(y_train) y_test_labels = get_y_labels(y_test) #print('y_train_labels:',y_train_labels) #print('y_test_labels:',y_test_labels) clf = SGDClassifier(max_iter=max_iter, tol=1e-3, loss='log', random_state=random_state) #To fit and score the model clf.fit(X_train, y_train_labels) return clf.score(X_test, y_test_labels) def main(): try: # Sample test cases from PDF X_train, y_train, X_test, y_test = pre_process('train1.csv','test1.csv') print(X_train[:5]) print(y_train[:5]) X_train, y_train, X_test, y_test = pre_process('train2.csv', 'test2.csv') print(y_train[:5]) print(X_train[:5]) X_train, y_train, X_test, y_test = pre_process('train2.csv', 'test2.csv') # Initial coefficient is np.full((3,5), 0.5) model = SoftmaxModel(np.full((3, 5), 0.5)) print(np.round(model.fit(X_train, y_train, 300, 1e-4), 3)) X_train, y_train, X_test, y_test = pre_process('train3.csv', 'test3.csv') model = SoftmaxModel(np.full((3, 5), 0.5)) print(np.round(model.fit(X_train, y_train, 500, 1.5e-4), 3)) X_train, y_train, X_test, y_test = pre_process('train1.csv', 'test1.csv') model = SoftmaxModel(np.full((3, 5), 0.5)) model.fit(X_train, y_train, 1000, 1e-4) print(model.predict(X_test)) print(round(model.score(X_test, y_test),3)) X_train, y_train, X_test, y_test = pre_process('train5.csv', 'test5.csv') model = SoftmaxModel(np.full((3, 5), 0.5)) model.fit(X_train, y_train, 500, 1.5e-4) print(model.predict(X_test)) print(round(model.score(X_test, y_test),3)) X_train, y_train, X_test, y_test = pre_process('train4.csv', 'test4.csv'); print(round(skl(X_train, y_train, X_test, y_test, 1, 1000), 3)) X_train, y_train, X_test, y_test = pre_process('train3.csv', 'test3.csv'); print(round(skl(X_train, y_train, X_test, y_test, 2, 500), 3)) # Testing X_train, y_train, X_test, y_test = pre_process('train1.csv','test1.csv') model = SoftmaxModel(np.full((3,5), 0.5)) model.fit(X_train, y_train, 1000, 1e-4) print(np.round(model.fit(X_train, y_train,1000,1e-4),3)) #print(np.round(model.fit(X_train, y_train,300,1e-4),3)) #print('Predict:') model.predict(X_test) model.score(X_test, y_test) #Sklearn model testing ###print('Sklearn model testing') X_train, y_train, X_test, y_test = pre_process('train4.csv','test4.csv') #print('X_train4:',X_train, 'y_train4:', y_train) #print('X_test4:',X_test, 'y_test4:', y_test) print((skl(X_train, y_train, X_test, y_test, 1, 1000), 3)) #print((skl(X_train, y_train, X_test, y_test, 2, 500), 3)) ################### Exceptions ################### except ValueError: print('Caught ValueError') except ZeroDivisionError: print('Caught ZeroDivisionError') except TypeError: print('Caught TypeError') except Exception: print('Caught Exception') except StopIteration: print('Caught StopIteration') except SystemExit: print('Caught SystemExit') except StandardError: print('Caught StandardError') except ArithmeticError: print('Caught ArithmeticError') except OverflowError: print('Caught OverflowError') except FloatingPointError: print('Caught FloatingPointError') except AssertionError: print('Caught AssertionError') except AttributeError: print('Caught AttributeError') except EOFError: print('Caught EOFError') except ImportError: print('Caught ImportError') except KeyboardInterrupt: print('Caught KeyboardInterrupt') except LookupError: print('Caught LookupError') except IndexError: print('Caught IndexError') except KeyError: print('Caught KeyError') except NameError: print('Caught NameError') except UnboundLocalError: print('Caught UnboundLocalError') except EnvironmentError: print('Caught EnvironmentError') except IOError: print('Caught IOError') except SyntaxError: print('Caught SyntaxError') except IndentationError: print('Caught IndentationError') except SystemError: print('Caught SystemError') except SystemExit: print('Caught SystemExit') except RuntimeError: print('Caught RuntimeError') except NotImplementedError: print('Caught NotImplementedError') if __name__ == '__main__': main()
5e07e78406addc23540d1a8a684619d34945a367
JunaidQureshi05/FAANG-ques-py
/01_Two_no_sum.py
498
3.625
4
# O(n^2) Time | O(1) Space # Brute Force Approach def pair_with_sum_1(array,target): for i in range(len(array)): for j in range(i+1,len(array)): if array[i] + array[j] ==target: return [i,j] return [] # Optimized def pair_with_sum(array,target): memoize ={} for i in range(len(array)): potentialMatch = target - array[i] if potentialMatch in memoize: return [memoize[potentialMatch],i] else: memoize[array[i]] = i return [] print(pair_with_sum([1,3,9,2],11))
b27d723eff7750a2cfcd9d6db72854bdf1da7e73
RianGirard/python_selection_sort
/selection_sort.py
821
4.125
4
arr = [5,9,8,4,3,1,2,6] print(arr) def selection_sort(lis): for i in range(len(lis)): # this loop defines our outer passes through the array, starting with "i=zero" index = i # this is our "marker" index, a placeholder for the lowest value found for j in range(i+1, len(lis)): # this loop defines our inner passes through the array, each time "forgetting" the prior digit (i+1) if lis[index] > lis[j]: # if our marker value > the value j from the inner pass... index = j # ...then shift the marker to the value j; this always puts the marker value on the lowest "j" lis[i], lis[index] = lis[index], lis[i] # now that marker is on lowest "j" from inner loop, swap the marker with "i" from outer loop print(lis) selection_sort(arr)
4e8ac2336ffb6c09f9451c938e457e0f80a7b655
alanchu394/New-York-Education-Analysis
/Functions/Function8.py
599
3.5
4
#written 12/8/2020 import numpy as np #function expects 2 inputs: a 1d numpy array and a bound def Function8(data, x): writtenBy = "Alan Chu" #sort the 1d numpy array data = np.sort(data) length = len(data) #calculate lower and upper mass lowerM = (100 - x)/2 upperM = (100- lowerM) #find the index lowerI = int(round(lowerM / 100 * length - 1, 0)) upperI = int(round(upperM / 100 * length - 1, 0)) #find the index within the data a = data[lowerI] b = data[upperI] return a,b #function returns the lower and upper bound of the data
bac20f3fb924c45d304d1154f9f69db718effa7b
urinaldisa/Algorithms-Collection-Python
/Algorithms/other/counting_inversions.py
1,230
4.125
4
def merge_sort(array): total_inversions = 0 if len(array) <= 1: return (array, 0) midpoint = int(len(array) / 2) (left, left_inversions) = merge_sort(array[:midpoint]) (right, right_inversions) = merge_sort(array[midpoint:]) (merged_array, merge_inversions) = merge_and_count(left, right) return (merged_array, left_inversions + right_inversions + merge_inversions) def merge_and_count(left, right): count_inversions = 0 result = [] left_pointer = right_pointer = 0 left_len = len(left) right_len = len(right) while left_pointer < len(left) and right_pointer < len(right): if left[left_pointer] <= right[right_pointer]: result.append(left[left_pointer]) left_pointer += 1 elif right[right_pointer] < left[left_pointer]: count_inversions += left_len - left_pointer result.append(right[right_pointer]) right_pointer += 1 result.extend(left[left_pointer:]) result.extend(right[right_pointer:]) return (result, count_inversions) if __name__ == "__main__": array = [9, 2, 1, 5, 2, 3, 5, 1, 2, 32, 12, 11] print(array) result = merge_sort(array) print(result)
69abfa0f1ca56011f0ceb984978036c5c1f0aa60
serdarkuyuk/LeetCode
/106-construct-binary-tree-from-inorder-and-postorder-traversal.py
1,267
3.84375
4
inorder = [9,3,15,20,7] postorder = [9,15,7,20,3] # 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 buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: mydict = {item : index for index, item in enumerate(inorder)} inorderRange = [0, len(inorder)] postorderRange = [0, len(postorder)] def helper(inorderRange, postorderRange): inorderBegining, inorderEnd = inorderRange postorderBegining, postorderEnd = postorderRange # base if postorderEnd <= postorderBegining: return None #assigning root indice = mydict[postorder[postorderEnd - 1]] root = TreeNode(inorder[indice]) #assing left root.left = helper([inorderBegining, indice], [postorderBegining, postorderBegining + indice - inorderBegining]) #assing right root.right = helper([indice+1, inorderEnd], [postorderBegining + indice - inorderBegining, postorderEnd-1]) return root return helper(inorderRange, postorderRange)
91ac929124db647820e98b9f88382d0e9d5c5ec8
angela-andrews/learning-python
/ex8.py
518
3.796875
4
# printing {} formatting formatter = "{} {} {} {}" # passing the format function a tuple to be interpolated into the 4 brackets # in the formatter variable. print(formatter.format(1,2,3,4)) print(formatter.format("one", "two", "three", "four")) print(formatter.format(True, False, True, False)) print(formatter.format(formatter, formatter, formatter, formatter)) # A tuple full of strings print(formatter.format( "Testing my own", ".format and printing", "Still got to look this up.", "Time for bed" ))
c3283528e0cff87d2ca7ab2e52c8f31297126ab1
jels/ple-ieslosenlaces
/ficheros/carta_personalizada.py
759
3.6875
4
""" 0. Crear los dos ficheros externos 1. Abrir desde el programa y mostrar en pantalla """ # Abrir ficheros --> f = open(ruta) fcarta = open("carta.txt") fclientes = open('clientes.txt') # leer fichero --> contenido = f.read() carta = fcarta.read() #clientes = fclientes.read() for cliente in fclientes: nombre, apellido, deuda = cliente.split() nombre_completo = nombre + ' ' + apellido.upper() carta_tmp = carta.replace('$CLIENTE$', nombre_completo) carta_tmp = carta_tmp.replace('$DEBE$', deuda) print carta_tmp f = open(nombre+'_'+apellido+'.txt', 'w') f.write(carta_tmp) f.close() raw_input() # mostrar contenido --> print contenido ##print carta ##print '* ' * 20 ##print clientes
4f5c905209845ad929b731df0adc366a49150006
Yucheng7713/CodingPracticeByYuch
/Algorithm/countInversion.py
1,064
3.5
4
class countInversion: def mergeCount(self, lst_a, lst_b): i = j = 0 merged_lst = [] numOfInv = 0 while i < len(lst_a) or j < len(lst_b): if i < len(lst_a) and (j == len(lst_b) or lst_a[i] < lst_b[j]): merged_lst += [lst_a[i]] i += 1 else: merged_lst += [lst_b[j]] j += 1 numOfInv += (len(lst_a) - i) return numOfInv, merged_lst def numOfInversion(self, nums): n = len(nums) if n == 0: return if n == 1: return 0, nums x, B = self.numOfInversion(nums[:n // 2]) y, C = self.numOfInversion(nums[n // 2:]) z, D = self.mergeCount(B, C) return x + y + z, D class readIntoList: def readFromFile(self): txt_file = open("integer.txt", "r") nums = txt_file.read().split('\n') txt_file.close() return [int(n) for n in nums] nums = readIntoList().readFromFile() print(countInversion().numOfInversion(nums))
0d85e7978ec7204305a6292ce3ea77d76944e9cb
FBK-NILab/app-classifyber
/subsampling.py
4,715
4.125
4
"""Functions to get a subset of objects that represents the initial dataset. The objects in such subset are sometimes called landmarks or prototypes. """ import numpy as np def furthest_first_traversal(dataset, k, distance, permutation=True): """This is the farthest first traversal (fft) algorithm which selects k objects out of an array of objects (dataset). This algorithms is known to be a good sub-optimal solution to the k-center problem, i.e. the k objects are sequentially selected in order to be far away from each other. Parameters ---------- dataset : array of objects an iterable of objects which supports advanced indexing. k : int the number of objects to select. distance : function a distance function between two objects or groups of objects, that given two groups as input returns the distance or distance matrix. permutation : bool True if you want to shuffle the objects first. No side-effect on the input dataset. Return ------ idx : array of int an array of k indices of the k selected objects. Notes ----- - Hochbaum, Dorit S. and Shmoys, David B., A Best Possible Heuristic for the k-Center Problem, Mathematics of Operations Research, 1985. - http://en.wikipedia.org/wiki/Metric_k-center See Also -------- subset_furthest_first """ if permutation: idx = np.random.permutation(len(dataset)) dataset = dataset[idx] else: idx = np.arange(len(dataset), dtype=np.int) T = [0] while len(T) < k: z = distance(dataset, dataset[T]).min(1).argmax() T.append(z) return idx[T] def subset_furthest_first(dataset, k, distance, permutation=True, c=2.0): """The subset furthest first (sff) algorithm is a stochastic version of the furthest first traversal (fft) algorithm. Sff scales well on large set of objects (dataset) because it does not depend on len(dataset) but only on k. Parameters ---------- dataset : list or array of objects an iterable of objects. k : int the number of objects to select. distance : function a distance function between groups of objects, that given two groups as input returns the distance matrix. permutation : bool True if you want to shuffle the objects first. No side-effect. c : float Parameter to tune the probability that the random subset of objects is sufficiently representive of dataset. Typically 2.0-3.0. Return ------ idx : array of int an array of k indices of the k selected objects. See Also -------- furthest_first_traversal Notes ----- See: E. Olivetti, T.B. Nguyen, E. Garyfallidis, The Approximation of the Dissimilarity Projection, Proceedings of the 2012 International Workshop on Pattern Recognition in NeuroImaging (PRNI), pp.85,88, 2-4 July 2012 doi:10.1109/PRNI.2012.13 """ size = compute_subsample_size(k, c=c) if permutation: idx = np.random.permutation(len(dataset))[:size] else: idx = range(size) return idx[furthest_first_traversal(dataset[idx], k, distance, permutation=False)] def compute_subsample_size(n_clusters, c=2.0): """Compute a subsample size that takes into account a possible cluster structure of the dataset, in n_clusters, based on a solution of the coupon collector's problem, i.e. k*log(k). Notes ----- See: E. Olivetti, T.B. Nguyen, E. Garyfallidis, The Approximation of the Dissimilarity Projection, Proceedings of the 2012 International Workshop on Pattern Recognition in NeuroImaging (PRNI), pp.85,88, 2-4 July 2012 doi:10.1109/PRNI.2012.13 """ return int(max(1, np.ceil(c * n_clusters * np.log(n_clusters)))) def compute_subset(dataset, distance, num_landmarks, landmark_policy='sff'): """Wrapper code to dispatch the computation of the subset according to the required policy. """ if landmark_policy == 'random': landmark_idx = np.random.permutation(len(dataset))[:num_landmarks] elif landmark_policy in ('fft', 'minmax'): landmark_idx = furthest_first_traversal(dataset, num_landmarks, distance) elif landmark_policy == 'sff': landmark_idx = subset_furthest_first(dataset, num_landmarks, distance) else: if verbose: print("Landmark selection policy not supported: %s" % landmark_policy) raise Exception return landmark_idx
89cf7af5a1a5fe08800a5ccc8370c7a2fdb14493
PEGGY-CAO/ai_python
/exam1/question5.py
562
4.28125
4
# Use NumPy random-number generation to create an array of twelve random grades in the range 60 through 100, # then reshape the result into a 3-by-4 array. # the averages of the grades in each column # and the averages of the grades in each row. import numpy as np array = np.random.randint(60, 101, size=12).reshape(3, 4) print(array) print("Calculate the average of all the grades") print(np.mean(array)) print("the averages of the grades in each column") print(array.mean(axis=0)) print("the averages of the grades in each row.") print(array.mean(axis=1))
88dbc16990dc98abbd983c8f3895bfe46aee490b
serebryakov-d/PyNEng_3.6
/exercises/06_control_structures/task_6_1b.py
1,602
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Задание 6.1b Сделать копию скрипта задания 6.1a. Дополнить скрипт: Если адрес был введен неправильно, запросить адрес снова. Ограничение: Все задания надо выполнять используя только пройденные темы. ''' #ip_addr=input('Enter dotted decimap IP address:') #ip_addr='65.11.11.11.45' correct_ip=False while correct_ip==False: ip_addr=input('Enter dotted decimal IP address:') ip_l=ip_addr.split('.') digit_num=True for N in ip_l: digit_num*=N.isdigit() try: digit_val=True for N in ip_l: digit_val*=(int(N) in range(0,256)) if (len(ip_l)==4) and digit_num and digit_val: ip1=int(ip_addr.split('.')[0]) if ip1 >= 1 and ip1 <= 223: result='unicast' correct_ip=True elif ip1 >= 224 and ip1 <= 239: result='multicast' correct_ip=True elif ip_addr=='255.255.255.255': result='local broadcast' correct_ip=True elif ip_addr=='0.0.0.0': result='unassigned' correct_ip=True else: result='unused' correct_ip=True else: result='Incorrect IPv4 address' print(result) except ValueError: result='Incorrect IPv4 address' print(result) print(result)
3f8c2e18484dc189ac0aae8f7698b14551b120d7
Yutapotter/naturelan-_100
/chapter2/script16.py
473
3.5
4
import math def file_nsplit(url,n): with open(url) as f: lines=f.readlines() count=len(lines) unit=math.ceil(count/n)#1行あたりの行数 for i,offset in enumerate(range(0,count,unit),1): with open("chile_{:02d}.txt".format(i),"w") as out_file: for line in lines[offset:offset+unit]: out_file.write(line) n=int(input("数字を入力してください")) url="hightemp.txt" file_nsplit(url,n)
e62de9875d5c634af8706791a7a52e8aa840c2a5
Tottoro932/Optimization
/home_work_2.1.py
1,468
3.625
4
import math import math #f(x)=tg(x)-2*sin(x) def f(x): return(math.tan(x)-2*math.sin(x)) def f1(x): return((1/math.cos(x)**2)-2*math.cos(x)) def f2(x): return(2*math.sin(x)/math.cos(x)**3+2*math.sin(x)) a=0 b=math.pi/4 E=0.03 col_steps=0 # метод касательных print("медод касательных") c=0 kol=0 if f1(a)<0 and f1(b)>0: while abs(b-a)>E or abs(f(b)-f(a))>E or kol<5: col_steps += 1 kol+=1 c=(f(b)-f(a)+f1(a)*a-f1(b)*b)/(f1(a)-f1(b)) if f1(c)==0: break if f1(c)<0: a=c else: b=c if f1(a)==0: c=a else: c=b print ("точка минимума: ",c) print("количество шагов: ", col_steps) # метод Ньютона-Рафсона a=0 b=math.pi/4 E=0.03 col_steps=0 print("метод Ньютона-Рафсона") kol=0 while abs(f1(b))>E or kol<5: if abs(f1(b))<E: kol+=1 b=b-f1(b)/f2(b) col_steps+=1 print("точка минимума: ",b) print("количество шагов: ", col_steps) # метод секущих (хорд) a=0 b=math.pi/4 E=0.03 col_steps=0 print("метод секущих") kol=0 c=10 while abs(f1(c))>E or kol<5: kol+=1 c=b-(b-a)*f1(b)/(f1(b)-f1(a)) a=b b=c col_steps+=1 print("точка минимума: ", c) print("количество шагов: ", col_steps)
b88ec320b1e1cfc5d4f5587f94a4cb85c80031df
gregseda/Python-Programming-Fundamentals
/Homework 3/HW3_test.py
3,267
3.796875
4
""" CLI program to test HW3 homework """ # Greg Seda # For each test function, test *all* the cases shown in the instructions import argparse from HW3 import words_containing, len_safe, unique def test_words_containing(): """Return True/False if the test of words_containing passes/fails""" sentence = "Anyone who has never made a mistake has never tried anything" sentence2 = "The cow jumped over the moon" new_list = words_containing(sentence, 'a') new_list2 = words_containing(sentence, 'x') new_list3 = words_containing('', 'x') new_list4 = words_containing(sentence2, 't') if new_list == [ 'Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']: if new_list2 == []: if new_list3 == []: if new_list4 == ['The', 'the']: return True else: return False def test_len_safe(): """Return True/False if the test of len_safe passes/fails""" my_dict = {'a': 23, 'b': 8} x = len_safe(my_dict) y = len_safe([]) z = len_safe(0.25) n = len_safe(7) m = len_safe('cat') p = len_safe('') animals = ['dog', 'cat', 'bird', 'cat', 'fish'] q = len_safe(animals) if x == 2: if y == 0: if z == -1: if n == -1: if m == 3: if p == 0: if q == 5: return True else: return False def test_unique(): """Return True/False if the test of unique passes/fails""" numbers = [4, 5, 2, 6, 2, 3, 5, 8] nums = unique(numbers) try: x = next(nums) y = next(nums) z = next(nums) m = next(nums) n = next(nums) q = next(nums) if x == 4: if y == 5: if z == 2: if m == 6: if n == 3: if q == 8: next(nums) except StopIteration: return True return False if __name__ == "__main__": # Set up argparse information here parser = argparse.ArgumentParser() parser.add_argument("-u", "--unique", help="Flag to test the unique function from HW3", action="store_true") parser.add_argument("-w", "--words", help="Flag to test words_containing function from HW3", action="store_true") parser.add_argument("-l", "--len", help="Flag to test the len_safe function from HW3", action="store_true") args = parser.parse_args() # Based on user input, run test(s) requested and print results # The ONLY printing should happen here. No other parts of the code # should print things. if args.unique: if test_unique(): print("unique passed") else: print("unique failed") if args.words: if test_words_containing(): print("words passed") else: print("words failed") if args.len: if test_len_safe(): print("len_safe passed") else: print("len_safe failed")
8950d4f29e4013b39195ea9bc38fa6f124a6f169
vidstige/aoc
/2017/6.py
1,063
3.71875
4
def reallocate(memory): selected = memory.index(max(memory)) tmp = list(memory) redist = tmp[selected] tmp[selected] = 0 n = selected + 1 while redist > 0: tmp[n % len(tmp)] += 1 redist -= 1 n += 1 return tuple(tmp) def count(initial): history = set() memory = initial c = 0 while memory not in history: history.add(memory) print(memory) memory = reallocate(memory) c += 1 return c def count_inf(initial): history = set() memory = initial # find the first repeating while memory not in history: history.add(memory) memory = reallocate(memory) # forget all states history = set() c = 0 while memory not in history: history.add(memory) memory = reallocate(memory) c += 1 return c print(count_inf((0, 2, 7, 0))) data = "5 1 10 0 1 7 13 14 3 12 8 10 7 12 0 6" print(count(tuple(int(x) for x in data.split()))) print(count_inf(tuple(int(x) for x in data.split())))
d6d4df8b2053057f69e157dc5242f2bbfe4b68f1
VihaanS22/Python-User-Intro-Form
/countWords.py
318
4.25
4
introString=input("Enter string :") characterCount=0 wordCount=1 for i in introString: characterCount=characterCount+1 if(i==' '): wordCount=wordCount+1 print("Number of words in the string:") print(wordCount) print("Number of characters in the string:") print(characterCount)
c1af2e8b1a9d7afb418226cb973913ce62c4e70d
Ocho262/Python_Challenges_2
/simple_math_2.py
499
3.90625
4
first_number = raw_input("What is the first number?") second_number = raw_input("What is the second number?") int_1 = int(first_number) int_2 = int(second_number) addition = int_1 + int_2 subtraction = int_1 - int_2 multiplication = int_1 * int_2 division = int_1 / int_2 simplemath = [] simplemath.append(addition) simplemath.append(subtraction) simplemath.append(multiplication) simplemath.append(division) print(simplemath[0]) print(simplemath[1]) print(simplemath[2]) print(simplemath[3])
57ad5b452b7918fb82fdc3606011e655c8bec5f4
zhoulouzhu/feng
/python scripts/PageObject/related/args.py
341
3.5625
4
def fun_args1(args): print("args,is %s" %args) def fun_args2(args1,args2): print("args1 is %s args2 is %s"%(args1,args2)) def fun_var_args(*args): for value in args: print("args:",value) # fun_args1('51zxw') # fun_args1() # fun_args2('51zxw','Python') # fun_args2('51zxw') #fun_var_args("sd ","sd") fun_var_args()
591f083a525e2a99dbcbc0f3dfa0f70f0555432d
rush2catch/algorithms-leetcode
/Basic Data Structures/array/leet_268_MissingNumber_bit.py
774
3.75
4
# Problem: Missing Number # Difficulty: Easy # Category: Array # Leetcode 268:https://leetcode.com/problems/missing-number/#/description # Description: """ Given an sorted array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? """ class Solution(object): def bit_manipulation(self, nums): missing = 0 i = 0 while i < len(nums): missing = missing ^ i ^ nums[i] i += 1 return missing ^ i obj = Solution() nums1 = [7, 5, 3, 4, 1, 0, 2] nums2 = [3, 0, 1, 2] print(obj.bit_manipulation(nums1)) print(obj.bit_manipulation(nums2))
022744b7df7f642e808e03aab83c5841955a65a1
MarvAntero/Pokemon_game
/Pessoa.py
9,403
3.765625
4
from Pokemon import * #Importando todos os dados de Pokemon.py para Pessoa.py from Item import * ##Tem muito nos games: RNG - Random Name Generate #random.ranint(a,b) - Gera n aleatorio entre a e b #random.ranchoice(lista) - escolhe randomicamente um elemento do interior da lista #random.uniform(a,b) - retorna float entre a e b #lista[] NOMES = ["May", "Gary", "andy", "Clark", "Misty", "Ane", "Marie", "Rick"] POKEMONS = [PokemonAgua("Squirtle"), PokemonAgua("Lapras"), PokemonFogo("Charmander"), PokemonFogo("Arcanine"), PokemonEletrico("Pikachu"), PokemonEletrico("Electabuzz"), PokemonInseto("Beedrill"), PokemonInseto("Butterfree"), PokemonGrama("Bulbassaur"), PokemonGrama("Gloom"), PokemonPedra("Onix"), PokemonPedra("Rhyhorn"), PokemonVoador("Pidgeot"), PokemonVoador("Spearow") ] class Pessoa: #Classe mais geral def __init__(self, nome=None, pokemons=[], dinheiro=100,itens = []): #inicializando -> passagem dos argumentos if nome == None: self.nome = random.choice(NOMES) #argumento nome não é obrigatorio else: self.nome = nome self.pokemons = pokemons self.dinheiro = dinheiro if itens == []: self.itens = [] else: self.itens = itens def mostrar_pokemons(self,a): #Método para mostrar os pokemons que possuo if self.pokemons: print("Pokemons de {}: ".format(self.nome)) for pokemon in self.pokemons: print(pokemon) print("Status de {}".format(pokemon)) print("hp---{}/{}\tlevel---{}\nExperiencia---{}/{}\tAtaque---{}\nEspecie---{}".format(pokemon.hp,(pokemon.lvl+20),pokemon.lvl,pokemon.experiencia,(2*pokemon.lvl + 300),pokemon.ataque,pokemon.especie)) if a == True: curar = input(print("Deseja curar/reviver algum pokemon?(s/n)")) if curar == 's': print("Insira o nome do pokemon a ser curado") nome_poke = input() for pokemon in self.pokemons: if nome_poke == pokemon: print("Escolha o item a ser usado") self.mostrar_itens() escolher_item = int(input()) for i in range(len(self.itens)): if escolher_item == i: item_escolhido = self.itens[i] break item_escolhido.action(pokemon) elif curar == 'n': print("Seus pokemons te amam!") else: print("{} nao possui nenhum pokemon".format(self.nome)) def escolher_aleatorio_pokemon(self): if self.pokemons: pokemon_escolhido = random.choice(self.pokemons) print("{} escolheu {}".format(self, pokemon_escolhido)) return pokemon_escolhido else: print("ERRO: O inimigo não possui pokemons disponives") def ganhar_dinheiro(self, quantidade): self.dinheiro += quantidade print("Voce ganhou ${}".format(quantidade)) self.mostrar_dinheiro() def mostrar_dinheiro(self): print("Voce possui: ${} em sua conta".format(self.dinheiro)) class Player(Pessoa): #classe filha player tipo = "Players" def __str__(self): #Método para escolher o que será mostrado quando printar o objeto criado return self.nome def capturar_pokemon(self, pokemon): self.pokemons.append(pokemon) print("{} capturado com sucesso!".format(pokemon)) def mostrar_itens(self): for i in range(len(self.itens)): print("{} -- {} ".format(i,self.itens[i])) def adquirir_item(self): print("Escolha o item a ser comprado: ") print("1 -- Potion") print("2 -- Revive") escolha = int(input()) while True: if escolha == 1: item = Potion(preco = 50) self.itens.append(item) self.dinheiro -= item.preco print("{} adquirido!".format(item)) break elif escolha == 2: item = Revive(preco = 100) self.itens.append(item) self.dinheiro -= item.preco print("{} adquirido!".format(item)) break else: print("Faça uma escolha valida") def escolher_pokemon(self): #print("Escolha um dos seus pokemons: ") i = 0 for pokemon in self.pokemons: print("{} : {}".format(i,pokemon)) i+=1 while True: try: escolha = int(input("Eu escolho o pokemon de indice: ")) return self.pokemons[escolha] except Exception as error: print("Escolha uma opção valida") print(error) def batalhar(self,pessoa): print("{} iniciou uma batalha com {}".format(self,pessoa)) pessoa.mostrar_pokemons(False) pokemon_inimigo = pessoa.escolher_aleatorio_pokemon() meu_pokemon = self.escolher_pokemon() if meu_pokemon and pokemon_inimigo: while True: print("Escolha uma açao:") print("1 - atacar") print("2 - fugir") print("3 - usar item") acao = int(input()) try: if acao == 1: vitoria = meu_pokemon.atacar(pokemon_inimigo,True) if vitoria == True: print("{} ganhou a batalha".format(self)) ganhei_dinheiro = pokemon_inimigo.lvl*100 self.ganhar_dinheiro(ganhei_dinheiro) ganhei_exp = pokemon_inimigo.lvl +50 meu_pokemon.experiencia += (ganhei_exp) meu_pokemon.passar_lvl() break vitoria_inimiga = pokemon_inimigo.atacar(meu_pokemon,False) if vitoria_inimiga == True: print("{} ganhou a batalha".format(pessoa)) break if acao == 2: chance_de_escapar = random.random() if chance_de_escapar >=0.8: print("voce conseguiu fugir da batalha") break else: print("Voce nao conseguiu escapar da batalha e ainda vai tomar uma surra, volte a luta guerreiro!!") vitoria_inimiga = pokemon_inimigo.atacar(meu_pokemon,False) if vitoria_inimiga == True: print("{} ganhou a batalha".format(pessoa)) break if acao == 3: print("Escolha o item a ser usado") self.mostrar_itens() escolher_item = int(input()) for i in range(len(self.itens)): if escolher_item == i: item_escolhido = self.itens[i] break item_escolhido.action(meu_pokemon) except ValueError: print("Insira um valor dentro do range de opçoes valido") else: print("Nao eh possivel essa batalha ocorrrer") def explorar(self): a = random.random() if a <= 0.3: pokemon = random.choice(POKEMONS) print("Um pokemon selvagem apareceu!: {}".format(pokemon)) escolha = input("Deseja capturar o pokemon? (s/n): ") while True: try: if escolha == 's': if random.random() >= 0.5: self.capturar_pokemon(pokemon) break else: print("O pokemon fugiu") break if escolha == 'n': print("Voce deixou o pokemon ir embora") except: print("Faça uma escolha valida") if a >= 0.7: inimigo = Inimigo() print("Um inimigo apareceu!") self.batalhar(inimigo) else: print("Essa exploração nao deu em nada") class Inimigo(Pessoa): #Classe filha inimigo tipo = "Inimigo" def __init__(self, nome=None, pokemons=None): if not pokemons: pokemons_aleatorios = [] for i in range(random.randint(1, 6)): pokemons_aleatorios.append(random.choice(POKEMONS)) super().__init__(nome=nome, pokemons=pokemons_aleatorios) #Passa os pokemons aleatorios para o init da classe pai else: super().__init__( nome = nome, pokemons = pokemons ) # como já passei os pokemons, n faz nada def __str__(self): return self.nome
12650633f7e8f6142afd1360d192fc12acb0e662
MarianDanaila/Competitive-Programming
/LeetCode_30days_challenge/2022/January/Linked List Cycle II.py
631
3.671875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: if not head or not head.next: return None slow = head.next fast = head.next.next while fast and fast.next and slow != fast: slow = slow.next fast = fast.next.next if fast is None or fast.next is None: return None entry = head while entry != slow: entry = entry.next slow = slow.next return entry
97cfdbb8bfb33247bfdf106fe9f14b491646f195
Vasilic-Maxim/LeetCode-Problems
/problems/575. Distribute Candies/2 - Sorting.py
358
3.515625
4
from typing import List class Solution: """ Time: O(n * log(n)) Space: O(1) """ def distributeCandies(self, candies: List[int]) -> int: candies.sort() kinds = 1 for i in range(1, len(candies)): if candies[i] != candies[i - 1]: kinds += 1 return min(len(candies) // 2, kinds)
200c57e49dccbbd8de055184684a74dfc637d38f
WiseAngel/python_algorithms
/sort/quick_sort.py
1,825
3.9375
4
import random arr = random.sample(range(0, 20), 10) print (arr) def quick_sort(arr): if len(arr) <= 1: return (arr) sep = arr[0] # sep = arr[random.randint(0, len(arr)-1)] left = [x for x in arr if x < sep] right = [x for x in arr if x > sep] mid = [x for x in arr if x == sep] return quick_sort(left) + quick_sort(mid) + quick_sort(right) print(quick_sort(arr)) # def partition(nums, low, high): # # Выбираем средний элемент в качестве опорного # # Также возможен выбор первого, последнего # # или произвольного элементов в качестве опорного # pivot = nums[(low + high) // 2] # i = low - 1 # j = high + 1 # while True: # i += 1 # while nums[i] < pivot: # i += 1 # j -= 1 # while nums[j] > pivot: # j -= 1 # if i >= j: # return j # # Если элемент с индексом i (слева от опорного) больше, чем # # элемент с индексом j (справа от опорного), меняем их местами # nums[i], nums[j] = nums[j], nums[i] # def quick_sort(nums): # # Создадим вспомогательную функцию, которая вызывается рекурсивно # def _quick_sort(items, low, high): # if low < high: # # This is the index after the pivot, where our lists are split # split_index = partition(items, low, high) # _quick_sort(items, low, split_index) # _quick_sort(items, split_index + 1, high) # _quick_sort(nums, 0, len(nums) - 1) # return (nums)
af3418fc2361ccb52a7a68e6e59f97b19e51fed1
wadefletch/advent-of-code-2020
/09/solution.py
886
3.59375
4
def part_one(input): preamble = 25 input = [int(x) for x in input] for i, line in enumerate(input): if i < preamble: continue space = input[i - preamble:i] solves = 0 for x in space: for y in space: if x + y == line: solves += 1 if solves == 0: return line def part_two(input): input = [int(x) for x in input] target = part_one(input) size = 2 while True: for x in input[:-size]: r = sum(input[x:size + 1]) if r == target: out = input[x:size + 1] return min(out) + max(out) size += 1 if __name__ in '__main__': input = open('input.txt').readlines() # or sometimes # input = open('input.txt').read() print(part_one(input)) print(part_two(input))
957258317de79d11ba5fb90fe4bfa537706c9b07
github-wombat/netc
/sample/env/python_env
295
3.625
4
#!/usr/bin/python3 import os import sys #print("環境変数") #env = os.environ #for key,value in env.items(): # print('{0}: {1}'.format(key,value)) #print() #print("標準入力") #data = sys.stdin.read() #print(data) #print(data.swapcase()) argv = sys.argv for v in argv: print(v)
4280a54c2029aee024ae384751cbec19586e9358
sujata-c/Evaluation-Criteria-Assignment-8
/type_conversion.py
2,062
4.71875
5
# different data types in python def implicit_type_conversion(): """Implicit Type Conversion is automatically performed by the Python interpreter. """ integer_type = 20 bool = True float_type = 30.87 complex_type = 8j print("Data type of interger_type before type conversion: ", type(integer_type)) print("Data type of float_type before type conversion: ", type(float_type)) print("Data type of bool before type conversion: ", type(bool)) type_conversion1 = float_type + integer_type # implicit type conversion of interger to float print("Data type after implicit type conversion :", type(type_conversion1)) type_conversion2 = bool + integer_type print("Data type after implicit type conversion :", type(type_conversion2)) type_conversion3 = complex_type + float_type print("Data type after implicit type conversion :", type(type_conversion3)) def explicit_type_conversion(): """ Explicit Type Conversion , the data types of objects are converted using predefined functions by the user""" integer_type = 40 float_type = 80.09 string_type = "Hello World" list_type = [1, 2, 3, 4, 5] set_type = {6, 7, 8, 9, 10} print("Data type of interger_type before type conversion: ", type(integer_type)) print("Data type of float_type before type conversion: ", type(float_type)) print("Data type of string_type before type conversion: ", type(string_type)) print("Data type of interger_type after type conversion to float: ", type(float(integer_type))) print("Data type of interger_type after type conversion to string: ", type(str(integer_type)), str(integer_type)) print("Data type of string_type after type conversion to list: ", type(list(string_type))) for i in list(string_type): print(i, end = ' ') if __name__ == '__main__': print("-----------------Implicit Conversion-------------") implicit_type_conversion() print("-----------------Explicit Conversion----------------------") explicit_type_conversion()
1702eb3928da14c80a2a6ba3e92e8d635f7850a8
ashishchovatiya/python
/pr27.py
195
3.65625
4
a, b = map(int, input("enter the two number A & B for A/B = ").split(' ')) try: c = a / b except ZeroDivisionError: print('Division by Zero Exception') else: print('A/B = ', c)
8ccbec13b55f537ce3090038a8f250370b5ad962
CodeForContribute/Algos-DataStructures
/HotQuestions/Array/lastIndexOne.py
227
3.625
4
def lastIndex(string, n): for j in range(n-1,-1, -1): if string[j] == '1': return j return -1 if __name__ == '__main__': string = '000000001' n = len(string) print(lastIndex(string, n))
0f63507e8747323838916fdef504fb0985253dad
joelrorseth/Snippets
/Python Snippets/Data Structures/doubly_linked_list.py
1,655
4.09375
4
# # Doubly Linked List # # This implementation maintains a next and previous pointer for each node, # and each list maintains a head and tail. This yeilds improvements over # singly linked lists, including the ability to insert / remove from either # end in O(1), as well as easy fwd / bkwd traversal in O(n). # # Joel Rorseth # class Node: def __init__(self, val): self.val = val self.prev = None self.next = None class DLList: def __init__(self): self.head = None self.tail = None def insert_front(self, val): new_node = Node(val) if self.head: new_node.next = self.head self.head.prev = new_node self.head = new_node else: self.head = new_node self.tail = new_node def insert_back(self, val): new_node = Node(val) if self.tail: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node else: self.head = new_node self.tail = new_node def pop_front(self): if self.head: self.head.next.prev = None self.head = self.head.next def pop_back(self): if self.tail: self.tail.prev.next = None self.tail = self.tail.prev def print(self): cur = self.head while cur: print(cur.val, end=" -> ") cur = cur.next print("None") ll = DLList() ll.insert_front(3) ll.insert_front(2) ll.insert_front(1) ll.insert_back(4) ll.insert_back(5) ll.print() ll.pop_front() ll.print() ll.pop_back() ll.print()
1225edfa8266f7bb791260a8d5036cd85e8d0bfc
dmt1100/gb-python-intro
/hw2/task5.py
252
3.640625
4
# задача №5 my_list = [7, 5, 3, 3, 2] print(f"Текущий рейтинг: {my_list}") rating = int(input("Введите рейтинг: ")) y = 0 for i in my_list: if rating <= i: y += 1 my_list.insert(y, rating) print(my_list)
0996a041df3e1c8ec6372d9f8c2f88a1bc71c5ff
mve17/SPISE-2019
/Pygame Day 2/test_triangleutils.py
1,200
4.21875
4
import unittest from math import pi as PI from triangleutils import * class TestRotateTriangleUtilMethods(unittest.TestCase): """ This is a unit test class to test the functions in the traiangle_utils module. See https://docs.python.org/2/library/unittest.html """ def test_degrees_to_radians(self): self.assertEqual(degrees_to_radians(180), PI) def test_triangle_polygon(self): triangle = create_triangle(0, 0) # Is the size of the polygon correct? self.assertEqual(len(triangle), 3) # Are the dimensions correct? self.assertEqual(triangle[0][0], 0) self.assertEqual(triangle[0][1], 50) self.assertEqual(triangle[1][0], 20) self.assertEqual(triangle[1][1], -10) self.assertEqual(triangle[2][0], -20) self.assertEqual(triangle[2][1], -10) def test_rotate_point(self): x, y = rotate_a_point((0, 60), 90, 0, 0) # We use the "almost equal" to account for rounding errors in conversion # to integers to floating point numbers self.assertAlmostEqual(x, -60) self.assertAlmostEqual(y, 0) if __name__ == '__main__': unittest.main()
9c888a4a237a66dc88a8f0d705d700a04119c966
fabioeomedeiros/Python-Base
/087_Matriz_v2.py
925
4.03125
4
#087_Matriz_v2.py matriz = [[0, 0, 0], [0, 0, 0,], [0, 0, 0]] sp = st = m = 0 print("") for i in range(0,3): for j in range(0,3): matriz[i][j] = int(input(f"Digite um número: [{i}, {j}] ")) print("") print(matriz) print("") for i in range(0,3): st += matriz[i][2] for j in range(0,3): print(f"[{matriz[i][j]:^5}]",end="") if matriz[i][j] % 2 == 0: sp += matriz[i][j] print("") print("") # a) feito separadamente # sp = 0 # for i in range(0,3): # for j in range(0,3): # if matriz[i][j] % 2 == 0: # sp += matriz[i][j] # b) feito separadamente # st = 0 # for i in range(0,3): # st += matriz[i][2] for j in range(0,3): if matriz[1][j] > m: m = matriz[1][j] print(f"a) A soma dos valores pares é {sp}.") print(f"b) A soma dos valores da 3ª coluna é {st}.") print(f"c) O maior número da 2ª linha é {m}.") print("")
5e9a2f86c8c017cd9e087a5702c783076031a1ad
shreyrai99/CP-DSA-Questions
/HackerRank/Extra Long Factorials/Extra Long Factorial.py
213
3.84375
4
"""It's very easy to handle large numbers in python. To calculate the factorial Just import the factorial function from the math module and apply it""" from math import factorial n=int(input()) print(factorial(n))
4bf7dec801926644f238381c25a566abebfc12d2
shekhar270779/ML_Python
/Python_Intro.py
427
3.640625
4
import sys import time print(sys.version) # to find python version print("Hello and Welcome to Python") seconds = time.time() # returns no. of seconds passed since epoch local_time = time.ctime(seconds) # returns local time print(local_time) # adding additional time commands tm = time.localtime(seconds) print(tm.tm_year) print(time.asctime()) # returns current time print("time to sleep") time.sleep(5) print("wakeup")
e4561e1d38ceed8a8b61c06d9ab113baf8fa2fc1
soothy/MIT-OCW-2016-python
/hangman.py
6,422
3.828125
4
import random import string WORDLIST_FILENAME = "../../../../Desktop/ps2/ps2/words.txt" myList = [] strl = " " guesses = 6 checklist=[] def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r') # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print(" ", len(wordlist), "words loaded.") return wordlist wordlist = load_words() def choose_word(wordlist): random.choice(wordlist) """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) secret_word=choose_word(wordlist) for i in range(len(secret_word)): myList.append('_') print(secret_word) def is_word_guessed(secret_word, letters_guessed): set_letters_guessed = set(letters_guessed) for word in secret_word: intersection = set_letters_guessed.intersection(secret_word) if intersection == set_letters_guessed: return False else: return True def get_guessed_word(secret_word, letters_guessed): for char in secret_word: if char in letters_guessed: for n in range(len(secret_word)): if secret_word[n] == letters_guessed: myList[n] = letters_guessed guess_word = strl.join(myList) guessed_word = guess_word.replace(" ","") return guessed_word def boolean_guess(secret_word, letters_guessed): for char in letters_guessed: if char in secret_word: return True else: return False s = list(string.ascii_lowercase) def get_available_letters(s,letters_guessed): for char in letters_guessed: if char in s: s.remove(char) return s def boolean_available_letters(s,letters_guessed): for char in letters_guessed: if char not in s: return True else: return False def check_vowel(letters_guessed): if letters_guessed =='a' or letters_guessed=='e' or letters_guessed =='i' or letters_guessed =='o' or letters_guessed=='u': return True else: return False tries=3 print("Welcome to hangman!") print("I am thinking of a word that is ",len(secret_word),"letters long") print("You have",guesses, "guesses left") print("Available letters: ",strl.join(s)) while guesses !=0: while True: letters_guessed = input("input letter: ") if (letters_guessed.isalpha() == 0 or len(letters_guessed) != 1 or boolean_available_letters(s,letters_guessed)==1): tries=tries-1 print("You have ",tries,"remaining") if tries == 0: if guesses !=1: guesses -= 1 print("You have ",guesses,"guesses left") tries =3 else: exit() continue else: break is_guessed=is_word_guessed(secret_word,letters_guessed) boolean=boolean_guess(secret_word,letters_guessed) getguessedword=get_guessed_word(secret_word,letters_guessed) if (boolean == False and check_vowel(letters_guessed)==True): guesses-= 2 print(get_available_letters(s,letters_guessed)) print ("you have ",guesses,"guesses remaining") elif(boolean==False): guesses-=1 print(get_available_letters(s, letters_guessed)) print("you have ", guesses, "guesses remaining") else: print(get_available_letters(s, letters_guessed)) print(getguessedword) if getguessedword == secret_word: print("You have completed hangman!") break lenlist=[word for word in wordlist if len(word)==len(secret_word)] def match_with_gaps(getguessedword, other_word): letters_guessed = [] for i in range(len(getguessedword)): current_letter = getguessedword[i] other_letter = other_word[i] if current_letter.isalpha(): if current_letter != other_letter: return False else: if current_letter == '_' and other_letter in letters_guessed: return False return True def show_possible_matches(getguessedword): matchlist = [] for word in lenlist: if match_with_gaps(getguessedword, word) == True: matchlist.append(word) if len(matchlist) == 0: print("no matches found") def hangman_with_hints(secret_word): ''' secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should start with 6 guesses * Before each round, you should display to the user how many guesses s/he has left and the letters that the user has not yet guessed. * Ask the user to supply one guess per round. Make sure to check that the user guesses a letter * The user should receive feedback immediately after each guess about whether their guess appears in the computer's word. * After each guess, you should display to the user the partially guessed word so far. * If the guess is the symbol *, print out all words in wordlist that matches the current guessed word. Follows the other limitations detailed in the problem write-up. ''' # FILL IN YOUR CODE HERE AND DELETE "pass" pass # When you've completed your hangman_with_hint function, comment the two similar # lines above that were used to run the hangman function, and then uncomment # these two lines and run this file to test! # Hint: You might want to pick your own secret_word while you're testing. if __name__ == "__main__": # pass # To test part 2, comment out the pass line above and # uncomment the following two lines. secret_word = choose_word(wordlist) ############### # To test part 3 re-comment out the above lines and # uncomment the following two lines. #secret_word = choose_word(wordlist) #hangman_with_hints(secret_word)
1888ad50141c5cd66143cfd3d71eaa6b77128949
rhiannon-17/python-kokonut
/mes_fonctions.py
306
3.703125
4
def eratosthene(b): liste = [True]*(b+1) liste[0],liste[1] = False, False for i in range(b+1): if liste[i] == True: yield i for k in range(i**2, b+1, i): liste[k] = False def main(): print("kokonut song") print("kiki et bibi et koko")
96ec108cb0ac2c756220ac07685f16e393ef7706
x4nth055/pythoncode-tutorials
/general/url-shortener/cuttly_shortener.py
589
3.5625
4
import requests import sys # replace your API key api_key = "64d1303e4ba02f1ebba4699bc871413f0510a" # the URL you want to shorten url = sys.argv[1] # preferred name in the URL api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}" # or # api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}&name=some_unique_name" # make the request data = requests.get(api_url).json()["url"] if data["status"] == 7: # OK, get shortened URL shortened_url = data["shortLink"] print("Shortened URL:", shortened_url) else: print("[!] Error Shortening URL:", data)
4125b19e8db1174e22ed26ea533e3d5a3ef027f8
Thaysfsil/short_exercise
/codeValidation.py
3,080
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 19 22:00:15 2018 @author: thayssilva """ import re def Inwardcode(InwardCode):#Verify Inward Code validationInward= False #Letter Exceptions: resemble_digits=['C', 'I', 'K', 'M', 'O', 'V'] #verify 9AA format if InwardCode[0].isnumeric() and (not InwardCode[1].isnumeric()) and ( not InwardCode[2].isnumeric()) : #verify AA letters if (InwardCode[1] not in resemble_digits) and (InwardCode[2] not in resemble_digits): validationInward = True else: return validationInward else: return validationInward return validationInward def OutwardCode(OutwardCode): validationOutward=False #Letter Exceptions: not_in_first = ['Q', 'V','X'] not_in_second =['I','J','Z'] not_in_third = ['I', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'V', 'X', 'Y', 'Z'] in_fourth=['A', 'B', 'E', 'H', 'M', 'N', 'P', 'R', 'V', 'W', 'X', 'Y'] #Verify Outward Code state="First" for x in range(len(OutwardCode)): if state == "First": #verify first Digit if OutwardCode[x].isnumeric() or OutwardCode[x] in not_in_first: return validationOutward else: state="Second" elif state == "Second": #verify second Digit if OutwardCode[x].isnumeric(): state="Third" elif OutwardCode[x] not in not_in_second: state="Fourth" else: return validationOutward elif state == "Third": #verify third digit if second digit is number if OutwardCode[x].isnumeric() or OutwardCode[x] not in not_in_third: pass else: return validationOutward elif state == "Fourth": #verify third digit if second digit is letter if OutwardCode[x].isnumeric(): state="Fifth" else: return validationOutward elif state == "Fifth": #verify fourth digit when exist if OutwardCode[x].isnumeric() or OutwardCode[x] in in_fourth: pass else: return validationOutward validationOutward = True return validationOutward def ValidatePostcode(postcode): if (" ") in postcode: postcode = postcode.upper().split() else: return "Postcode invalid format" if len(postcode) !=2: return "Postcode invalid format" else: outward,inward = postcode[0],postcode[1] if (len(outward)<=4 and len(inward) ==3): if not(re.match("^[a-zA-Z0-9_]*$", outward) and re.match("^[a-zA-Z0-9_]*$", inward)): return "Postcode does not accept special character" else: return "Postcode invalid format" if (Inwardcode(inward) and OutwardCode(outward)): return True else: return False
efffe1ee43653fece102beba2d3a9509cb028e7e
AmanPriyanshu/genetic-algorithms
/linear_regression_with_ga.py
2,822
3.671875
4
import numpy as np import random import matplotlib.pyplot as plt def create_dataset(n, slope): data = np.empty([n, 2]) for i in range(n): x = random.randint(-100, 100) y = slope*x data[i][0], data[i][1] = x, y return data def lr_predict(X, w): y_pred = X*w[0] return y_pred def lr_cost(y_pred, Y): rms = np.sqrt(np.sum(np.square(y_pred-Y))) return rms def lr_grad(w, Y, y_pred, X, alpha): dw = [0] dw[0] = np.mean(X*(y_pred-Y)) w[0] = w[0] - alpha*dw[0] return w def lr_approach(iterations, data): w = [0] c = 0 for i in range(iterations): y_pred = lr_predict(data.T[0], w) #print(y_pred) rms = lr_cost(y_pred, data.T[1]) #print(rms) w = lr_grad(w, data.T[1], y_pred, data.T[0], 0.0001) #print(w) if int(w[0]+1) == 602: break c += 1 return w, c def linear_regression(iterations=1000): data = create_dataset(100, 602) w, c = lr_approach(iterations, data) print(int(w[0]+1), 'at iteration', c) return c """ Let us do the same thing using GA and compare the results """ # Assuming slope ranges from -1000 to 1000. This will be the sample space for our individuals. # Assume here every individual in a generation is represented by its index numbers and its genes by the value stored within that index def generate_parent_gen(n): generation = [] for i in range(n): generation.append(random.randint(-1000, 1000)) return generation def fitness_scorer(generation, data): fitness = [] for individual in range(len(generation)): y_pred = generation[individual]*data.T[0] fitness.append(np.sqrt(np.sum(np.square(y_pred-data.T[1])))) return fitness # since we have only one gene here let us take the average of the parents + the fittest def offspring_gen(gen): gen_new = [] for i in range(len(gen)): gen_new.append((gen[0] + random.choice(gen) + random.choice(gen))/3) return gen_new def genetic_algorithm(): iterations = 10 data = create_dataset(100, 602) gen = generate_parent_gen(1000) value = 0 c = 0 for i in range(iterations): fitness = fitness_scorer(gen, data) fitness, gen = (list(t) for t in zip(*sorted(zip(fitness, gen)))) if fitness[0] == 0.0: value = gen[0] break # Let's fix population to 1000, so killing 500 fitness, gen = fitness[:500], gen[:500] gen_new = offspring_gen(gen) gen = gen + gen_new value = gen[0] c += 1 print(value, 'at iteration', c) return c def imager(cga, clr): plt.scatter([i for i in range(cga.shape[0])], cga, color='green', marker='.') plt.scatter([i for i in range(cga.shape[0])], clr, color='red', marker='.') plt.savefig('ga_vs_lr.png') plt.clf() def main(): cga = [] clr = [] for i in range(100): cga.append(genetic_algorithm()) clr.append(linear_regression()) cga = np.array(cga) clr = np.array(clr) print(np.mean(cga)) print(np.mean(clr)) imager(cga, clr) main()
e943961f0962786b347265c976174e24cfc8319a
supershinu/hagman-game
/my_hangman.py
3,955
3.96875
4
import random def hangman(): word = random.choice(["steve","ironman","thor","loki","thanos","blackpanther","spiderman","blackwidow","wanda","hulk"]) valid_letters ='abcdefghijklmnopqrstuvwxyz' guessmade = '' turns = 10 while len(word)>0 : main="" for letter in word : if letter in guessmade : main = main + letter else : main = main + "_" +" " if main == word : print(main) print ("congratulations ,you win!!!") break print("guess the word:",main) guess =input() if guess in valid_letters: guessmade = guess + guessmade else: print("enter valid input:") guess= input() if guess not in word : turns = turns - 1 if turns == 9: print("9 turns left") print(" -------- ") if turns == 8: print("8 turns left") print(" -------- ") print(" O ") print(" ") print(" ") if turns == 7: print("7 turns left") print(" -------- ") print(" O ") print(" | ") print(" ") print(" ") if turns == 6: print("6 turns left") print(" -------- ") print(" O ") print(" | ") print(" / ") print(" ") print(" ") if turns == 5: print("5 turns left") print(" -------- ") print(" O ") print(" | ") print(" / \ ") print(" ") print(" ") if turns == 4: print("4 turns left") print(" -------- ") print(" \ O ") print(" | ") print(" / \ ") print(" ") print(" ") if turns == 3: print("3 turns left") print(" -------- ") print(" \ O / ") print(" | ") print(" / \ ") print(" ") print(" ") if turns == 2: print("2 turns left") print(" -------- ") print(" \ O /| ") print(" | ") print(" / \ ") print(" ") print(" ") if turns == 1: print("1 turns left") print("Last breaths counting, Take care!") print(" -------- ") print(" \ O_|/ ") print(" | ") print(" / \ ") print(" ") print(" ") if turns == 0: print("You loose") print("You let a kind man die") print(" -------- ") print(" O_| ") print(" /|\ ") print(" / \ ") print(" ") print(" ") print("the correct word is:", word) break name = input("your name name :") print("Welcome" , name ) print("-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/") print("try to guess the word related to avengers in less than 10 attempts") hangman() print()
31864e54abeeb272432b83c9b4141e6ad246e854
sumanblack666/datacamp-python-data-science-track
/Natural Language Processing Fundamentals in Python/Chapter 1 - Regular expressions & word tokenization.py
5,109
4.59375
5
#---------------------------------------------------------------------------------------------------------------# #Chapter 1 Regular expressions & word tokenization #---------------------------------------------------------------------------------------------------------------# ##Practicing regular expressions: re.split() and re.findall() # Import the regex module import re # Write a pattern to match sentence endings: sentence_endings sentence_endings = r"[.?!]" # Split my_string on sentence endings and print the result print(re.split(sentence_endings, my_string)) # Find all capitalized words in my_string and print the result capitalized_words = r"[A-Z]\w+" print(re.findall(capitalized_words, my_string)) # Split my_string on spaces and print the result spaces = r"\s+" print(re.split(spaces, my_string)) # Find all digits in my_string and print the result digits = r"\d+" print(re.findall(digits, my_string)) #---------------------------------------------------------------------------------------------------------------# #Word tokenization with NLTK # Import necessary modules from nltk.tokenize import sent_tokenize from nltk.tokenize import word_tokenize # Split scene_one into sentences: sentences sentences = sent_tokenize(scene_one) # Use word_tokenize to tokenize the fourth sentence: tokenized_sent tokenized_sent = word_tokenize(sentences[3]) # Make a set of unique tokens in the entire scene: unique_tokens unique_tokens = set(word_tokenize(scene_one)) # Print the unique tokens result print(unique_tokens) #---------------------------------------------------------------------------------------------------------------# #More regex with re.search() # Search for the first occurrence of "coconuts" in scene_one: match match = re.search("coconuts", scene_one) # Print the start and end indexes of match print(match.start(), match.end()) # Write a regular expression to search for anything in square brackets: pattern1 pattern1 = r"\[.*\]" # Use re.search to find the first text in square brackets print(re.search(pattern1, scene_one)) # Find the script notation at the beginning of the fourth sentence and print it pattern2 = r"[\w\s]+:" print(re.match(pattern2, sentences[3])) #---------------------------------------------------------------------------------------------------------------# #Regex with NLTK tokenization # Import the necessary modules from nltk.tokenize import regexp_tokenize from nltk.tokenize import TweetTokenizer # Define a regex pattern to find hashtags: pattern1 pattern1 = r"#\w+" # Use the pattern on the first tweet in the tweets list regexp_tokenize(tweets[0], pattern1) # Write a pattern that matches both mentions and hashtags pattern2 = r"([#|@]\w+)" # Use the pattern on the last tweet in the tweets list regexp_tokenize(tweets[-1], pattern2) # Use the TweetTokenizer to tokenize all tweets into one list tknzr = TweetTokenizer() all_tokens = [tknzr.tokenize(t) for t in tweets] print(all_tokens) #---------------------------------------------------------------------------------------------------------------# #Non-ascii tokenization # Tokenize and print all words in german_text all_words = word_tokenize(german_text) print(all_words) # Tokenize and print only capital words capital_words = r"[A-ZÜ]\w+" print(regexp_tokenize(german_text, capital_words)) # Tokenize and print only emoji emoji = "['\U0001F300-\U0001F5FF'|'\U0001F600-\U0001F64F'|'\U0001F680-\U0001F6FF'|'\u2600-\u26FF\u2700-\u27BF']" print(regexp_tokenize(german_text, emoji)) #---------------------------------------------------------------------------------------------------------------# #Charting practice # Split the script into lines: lines lines = holy_grail.split('\n') # Replace all script lines for speaker pattern = "[A-Z]{2,}(\s)?(#\d)?([A-Z]{2,})?:" lines = [re.sub(pattern, '', l) for l in lines] # Tokenize each line: tokenized_lines tokenized_lines = [regexp_tokenize(s, "\w+") for s in lines] # Make a frequency list of lengths: line_num_words line_num_words = [len(t_line) for t_line in tokenized_lines] # Plot a histogram of the line lengths plt.hist(line_num_words) # Show the plot plt.show() #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------------------------------------------------------------------------#
d7218ce32a135c39624faa843d903877ae423a4f
vmred/Coursera
/coursera/python-basic-programming/week5/hw19.py
269
3.71875
4
def greaterThanNeighbourhoods(items): arr = list(map(int, items.split())) count = 0 for i in range(1, len(arr) - 1): if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]: count += 1 return count print(greaterThanNeighbourhoods(input()))
8aaae4fc1a863357a7135bb39396cf95460b9da4
SRG08/Searching-Sorting-and-Pointers-Algorithms
/Merge_Sort.py
2,539
4.3125
4
from random import randint # Merge Sort: # This divide and conquer algorithm splits a list in half, and keeps splitting the list by 2 until it only has singular elements. # Adjacent elements become sorted pairs, then sorted pairs are merged and sorted with other pairs as well. # This process continues until we get a sorted list with all the elements of the unsorted input list. # def create_array(min = -100, max = 50, size = 10): return [randint(min,max) for _ in range(size)] def Merge_part(left_item_list, right_item_list): Sorted_items = [] # Create an empty list for sorted items left_item_index, right_item_index = 0, 0 # Initially set the index of lists to "0" # initialize condition for While loop until we get the list items split to single items # until this condition is false the iteration continues while left_item_index < len(left_item_list) and right_item_index < len(right_item_list): # checking if the value in the left list item is less than the right list item if left_item_list[left_item_index] < right_item_list[right_item_index]: # appending the less value to the sorted list Sorted_items.append(left_item_list[left_item_index]) # Incrementing the value with 1 left_item_index += 1 else: # appending the less value to the sorted list Sorted_items.append(right_item_list[right_item_index]) # Incrementing the value with 1 right_item_index += 1 # if after iteration last value remains in any list if left_item_index == len(left_item_list): # Extend the value to right list Sorted_items.extend(right_item_list[right_item_index:]) else: # extend the values to left list Sorted_items.extend(left_item_list[left_item_index:]) return Sorted_items def Merge_sort(item_list): # the list has 0 or 1 element/item if len(item_list) <= 1: return item_list left, right = Merge_sort(item_list[:len(item_list) // 2]), Merge_sort(item_list[len(item_list) // 2:]) return Merge_part(left, right) if __name__ == "__Main__": Merge_sort() # list1 = [randint(-100, 100) for _ in range(0, 5)] list1 = create_array() print("list1 : {}".format(list1)) # list2 = [randint(-100, 100) for _ in range(0, 10)] # print("list2 : {}".format(list2)) # list3 = (list1 + list2) print("Final List: {}".format(Merge_sort(list1))) # print(Merge_part(list1, list2)) # print(Merge_part(list2))s # print(Merge_part(list1))
568a8197fbcc1db3abc15be5472c797e4dcbab62
andrewlee1807/boring
/binary_search.py
434
3.640625
4
def binarySearch(low, high): # mid = (low + high) // 2 print(low, high) mid = int(low + (high - low) * (k - a[low]) / (a[high] - a[low])) print(mid) if a[mid] == k: return mid if low == high: return -1 if a[mid] > k: return binarySearch(low, mid-1) if a[mid] < k: return binarySearch(mid+1, high) a = list(range(10)) print(a) k = 5 print(binarySearch(0, len(a)-1))