blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
50736978b3dfddfec0882186d7829f341e1c71a6
almiranda86/PythonLab
/PythonLab/PythonLab/mostCommonLetter.py
1,148
3.78125
4
def checkio(text: str) -> str: t = text.lower().replace(" ","") myDict = {} count = 0 for x in t : if x.isalpha(): if x in myDict: myDict[x] += count+1 else: myDict[x] = count+1 if all(value == 1 for value in myDict.values()): return list(sorted(myDict))[0] else: return max(sorted(myDict), key=myDict.get) if __name__ == '__main__': print("Example:") #print(checkio("Hello World!")) #These "asserts" using only for self-checking and not necessary for auto-testing #assert checkio("Hello World!") == "l", "Hello test" #assert checkio("How do you do?") == "o", "O is most wanted" #assert checkio("One") == "e", "All letter only once." #assert checkio("Oops!") == "o", "Don't forget about lower case." #assert checkio("AAaooo!!!!") == "a", "Only letters." #assert checkio("abe") == "a", "The First." #print("Start the long test") #assert checkio("a" * 9000 + "b" * 1000) == "a", "Long." #print("The local tests are done.") assert checkio("Lorem ipsum dolor sit amet") == "m", "Hello test"
5494ffcfe34a12e7fbb148a7fada72ecedf8ff92
Mostafa-At-GitHub/Data-Structures-and-Algorithms-codes
/CS_LAB_MA252/Dynamic Programming/longest.py
823
3.703125
4
def printlcs(b,X,i,j): if i==0 or j==0: return if b[i][j]=="proceed": printlcs(b,X,i-1,j-1) print(X[i-1]) elif b[i][j]=="^": printlcs(b,X,i-1,j) else: printlcs(b,X,i,j-1) def lcs(A,B): la=len(A) lb=len(B) w, h = la, lb; c = [[0 for x in range(h+1)] for y in range(w+1)] #c is length of lcs b = [[0 for x in range(h+1)] for y in range(w+1)] for i in range(0,w): for j in range(0,h): if A[i]==B[j]: c[i+1][j+1]=c[i][j]+1 b[i+1][j+1]="proceed" elif c[i][j+1]>=c[i+1][j]: c[i+1][j+1]=c[i][j+1] b[i+1][j+1]="^" else: c[i+1][j+1]=c[i+1][j] b[i+1][j+1]=" " printlcs(b,A,la,lb) return c[la][lb] A=str(input("Enter the first dna strand:::")) B=str(input("Enter the second dna strand:::")) print("The length of longest common subsequence is {}".format(lcs(A,B)))
6be6d862ae3bd299bc4af5f3f71166a11660b336
crh2302/capstone
/delete/convert_to_full_hash.py
2,004
3.609375
4
import pandas """ The purpose of this file was to convert small commit hashes into full commit hashes. This module does not take part in the collection of metrics """ def read_data(file_name, column_names): data = pandas.read_csv(file_name) df = pandas.DataFrame(data) df.columns = column_names return df def select_unique_data(my_data, column_names): df_unique = my_data.groupby(column_names).size().reset_index().rename(columns={0: 'count'}) del df_unique['count'] return df_unique def add_hash(data_frame, commit_hashes_df): dict_prev_found = {} data_frame["hash"] = "" for index, row in data_frame.iterrows(): row_list = row[0:1] counter = 0 for row_i in row_list: if row_i in dict_prev_found: value = dict_prev_found[row_i] data_frame["hash"][index] = value[0][0] else: value = commit_hashes_df[commit_hashes_df.commit_hashes.str.startswith(row_i)].values if value.size == 0: print(f"index:{index}") print("value.size == 0:") print(f"row_i{row_i}") print(f"Value:{value}") else: dict_prev_found[row_i] = value data_frame["hash"][index] = 0 if value.size == 0 else value[0][0] counter = counter + 1 return data_frame def convert_to_full_hash(): my_column_names = ["commit_hashes"] my_file_name = r'D:\capstone\data\demma.csv' data = read_data(my_file_name, my_column_names) data = select_unique_data(data, my_column_names) my_column_names = ["commit_hashes"] my_file_name = 'commit_full_hash_demma.csv' commit_hashes_df = read_data(my_file_name, my_column_names) commit_hashes_df = select_unique_data(commit_hashes_df, my_column_names) data = add_hash(data, commit_hashes_df) data.loc[:, data.columns == 'hash'].to_csv("data.csv", index=None)
a3c5134b05e18ec48a2634d8d36f7204acea3018
mlipshultz/Asymmetrik-programming-challenge
/Business_card_parser.py
5,343
3.953125
4
import re import sys #The business card parser class will be doing all of the heavy lifting in figuring out #the different pieces of contact information class BusinessCardParser: #We will define a series of private helper functions for parsing out the pieces of contact information. def __parseName(self, document): matches = [] #We will have a list of words which will disqaulify a word from being a name. #These will either be job title words, or words generally appearing in a company name. list_of_disqualif_words = ['software', 'developer', 'analytic', 'tech', 'technology', 'engineer', 'ltd', 'llc', 'technologies', 'analyst', 'solutions', 'cloud', 'computing'] #This list could be added to with user input. As users find conflicts they could determine what to #add to this list. I left it with some basic words for the sake of time. for line in document: #Here we want to match any line with 2 or more capitalized words (which can have hyphens) regex = re.search(r'^[A-Z][a-z\-]+(\s[A-Z][a-z\-]+)+', line) if regex != None: matches.append(regex.group(0)) matches_to_remove = set() if not matches: return "No name found" elif len(matches) == 1: return matches[0] else: for match in matches: #We want to look at each word in the matches we found to see if we can find a #disqualifying word. for name in match.split(' '): if name.lower() in list_of_disqualif_words: matches_to_remove.add(match) for item in matches_to_remove: matches.remove(item) #This case means we filtered out all potentional matches, we may still want to return a value #so the behavior of this could be changed to return when the list has one entry left if not matches: return "No name found" else: return matches[0] def __parsePhoneNumber(self, document): #If we find a match on this regular expression, we have a possible phone number. #It is possible that we find two possible numbers, so we then need to narrow down #to the correct phone number if we do. matches = [] for line in document: #We search for something that looks like a phone number using the below regex. regex = re.search(r'(\d?).*(\d{3}).*(\d{3}).*(\d{4}).*', line) if regex != None: matches.append(line) if not matches: return "No Phone number found" #If we have only a single match, take just the digits from that line elif len(matches) == 1: digits = [character for character in matches[0] if character.isdigit()] return ''.join(digits) else: #If we have more than one match to the regular expression, we will need to find which #is the line we are looking for. #By using the characters in "telephone", we can get a good idea of if this is the phone number #that we are looking for. chars_to_look_for = "telphon" max_matches = 0 most_matched_line = '' for match in matches: current_matches = 0 match = match.lower() for char in chars_to_look_for: if char in match: current_matches += 1 if current_matches >= max_matches: max_matches = current_matches most_matched_line = match #We return the digits from the line with the most matching characters to "telephone" digits = [character for character in most_matched_line if character.isdigit()] return ''.join(digits) def __parseEmail(self, document): for line in document: #We will search for a line which any valid characters or dots, an @ sign, more valid characters, # a dot, followed by more valid characters. regex = re.search(r"[\w\.]+@\w+\.\w+", line) if regex != None: return regex.group(0) #Error case, we return no email if we could not find a anything with our regex. return "No email address found" def getContactInfo(self, document): #First we remove leading and trailing whitespaces. This will remove new line characters. document = [line.strip() for line in document] phone_number = self.__parsePhoneNumber(document) email_address = self.__parseEmail(document) name = self.__parseName(document) return ContactInfo(name, phone_number, email_address) #The contact info class will contain a name, phone number, and email address #and provide getters to those variables. class ContactInfo: def __init__(self, name, phone_number, email_address): self.name = name self.phone_number = phone_number self.email_address = email_address def getName(self): return self.name def getPhoneNumber(self): return self.phone_number def getEmailAddress(self): return self.email_address def main(): document = [] if len(sys.argv) != 2: print('Please use 1 input argument which is the text file you would like to parse') return else: try: with open(sys.argv[1], 'r') as infile: document = infile.readlines() except: print("Failed to open file: " + sys.argv[1]) print("Please provide a valid file name") return parser = BusinessCardParser() contact_info = parser.getContactInfo(document) print("Name: {}".format(contact_info.getName())) print("Phone: {}".format(contact_info.getPhoneNumber())) print("Email: {}".format(contact_info.getEmailAddress())) if __name__ == "__main__": main()
5600d557d505b2fb6283996edfc9c3f097174717
banjocat/codeeval_solutions
/31/main.py
345
3.515625
4
import sys def main(): with open(sys.argv[1]) as f: for line in f: solve(line) def solve(line): (word, end) = line.split(',') letter = end.strip() pos = -1 for x in range(0, len(word)): if word[x] == letter: pos = x print(pos) if __name__ == '__main__': main()
4166493515218391c7706e54d1012e547d530a57
mattgarrett/hits
/crawl.py
3,551
3.84375
4
#!/usr/bin/python #matt garrett #cse 417 #crawl is a python implementation of a simple wikipedia crawler to explore #the wikipedia graph. It is built on top of BeautifulSoup. import sys import urllib2 from bs4 import BeautifulSoup import re #the regex to match an internal wikipedia link wikiLink = re.compile("^/wiki/[^:#]*$") #accepts a target url of the form /wiki/HITS_algorithm or /wiki/Ferrari #accepts a depth the current url is at #accepts a depth to stop searching at #accepts a list of lists of documents to append to #accepts a corrisponding list of outbound links to append to #accepts a list of problem urls to append to #explores the target url, stopping at depth stop, storing all results #in documents, outbound, and problems def explore(url, depth, stop, documents, outbound, problems): if (url not in documents and depth < stop): print("adding = " + url + ", documents size = " + str(len(documents))) documents.append(url) outbound.append([]) fullUrl = "http://en.wikipedia.org" + url #User-Agent must be set because wikipedia blocks crawlers request = urllib2.Request(fullUrl, headers={"User-Agent" : "Superman"}) try: socket = urllib2.urlopen(request) page = socket.read() socket.close() #cuts off references section of the page page = re.sub('id="References.*', '', page) soup = BeautifulSoup(page) #this div is the article itself, it is what we want to search article = soup.find("div", {"id" : "mw-content-text"}) index = documents.index(url) if article: for link in article.find_all("a", {"href" : wikiLink}): if (link.get("href") not in documents): explore(link.get("href"), depth + 1, stop, documents, outbound, problems) outbound[index].append(link.get("href")) else: documents.pop() outbound.pop() problems.append(url) #didn't want to deal with exceptions breaking my code while #4 hours into crawling, this fixes that problem except IOError, (errno): print "HUGE ERROR MOVING ON" documents.pop() outbound.pop() #accpets a list of documents and a corresponding list of lists of #outbound urls, writes the adjacency list to the specified outFile def dumpLists(documents, outbound, outFile): f = open(outFile, "w") for index, url in enumerate(documents): f.write(url + ":\n") for link in outbound[index]: f.write(" " + link + "\n") #accepts a list of urls and writes them to sdtout def dumpProblems(problems): print("Problems") for url in problems: print(" " + url) #prints usage information for crawl def showUsage(): print("Crawl Usage:") print(" crawl targetUrl searchDepth outFile") print("Examples:") print(" crawl /wiki/HITS_algorithm 3 hits.dump") print(" crawl /wiki/Ferrari 5 ferrari.dump") #yeah I'm used to java, learning python is weird def main(): if (len(sys.argv) < 4): showUsage() else: url = sys.argv[1] stop = int(sys.argv[2]) outFile = sys.argv[3] documents = [] outbound = [] problems = [] explore(url, 0, stop, documents, outbound, problems) dumpLists(documents, outbound, outFile) dumpProblems(problems) main()
4471b582aa890ff026efad9fdc5ebf86f1bb30b9
salonikalsekar/Python
/programs/binarySearch.py
452
3.65625
4
pos = -1 def search(list, n ): l = 0 u = len(list) - 1 while l <= u: mid = (l + u) // 2 if list[mid] == n: globals()['pos'] = mid return True else: if n > list[mid]: l = mid + 1 ; else: u = mid - 1; return False list = [3,6,77,8,94] n = 9 if search(list, n): print("found at position", pos+1) else: print("not found")
ab18d6fceb444644ddf2931fd6ee12d796784d5f
SandraAlcaraz/FundamentosProgramacion
/quiz2-1.py
110
3.671875
4
hora=9 minutos=23 segundos=45 print(hora,minutos,segundos,sep=":") print("%i:%i:%i"%(hora,minutos,segundos))
bdd36183aca316ce0e936d155d7501edc7d1069e
nptit/python-snippets
/class.py
1,624
4.125
4
class A(object): def __init__(self): self.a = 1 def x(self): print "A.x" def y(self): print "A.y" def z(self): print "A.z" class B(A): def __init__(self): A.__init__(self) self.a = 2 self.b = 3 def y(self): print "B.y" def z(self): print "B.z" class C(object): def __init__(self): self.a = 4 self.c = 5 def y(self): print "C.y" def z(self): print "C.z" class D(C, B): def __init__(self): C.__init__(self) B.__init__(self) self.d = 6 def z(self): print "D.z" obj = D() print D.__mro__ print obj.a class Spell(object): def __init__(self, incantation, name): self.name = name self.incantation = incantation def __str__(self): return self.name + ' ' + self.incantation + '\n' + self.getDescription() def getDescription(self): return 'No description' def execute(self): print self.incantation class Accio(Spell): def __init__(self): Spell.__init__(self, 'Accio', 'Summoning Charm') def getDescription(self): return "This charm summons an object to the caster, potentially over a significant distance." class Confundo(Spell): def __init__(self): Spell.__init__(self, 'Confundo', 'Confundus Charm') def getDescription(self): return 'Causes the victim to become confused and befuddled.' def studySpell(spell): print spell # spell = Accio() # spell.execute() # studySpell(spell) # studySpell(Confundo()) #rint Accio()
fa37af86ad4edc02d7c1faeaee0dc866d26acff7
trvsed/100-exercicios
/ex049.py
247
3.8125
4
while True: t=int(input('Digite um número para saber a sua tabuada: ')) for c in range(1, 11): print('{} x {} = {}'.format(t, c, t*c)) cont=str(input('Deseja continuar? (s/n): ')).lower() if cont !='s': break
f959211a86d8f499a9f3d84cc9ecf4a6306994f6
Bundaberg-Joey/Pybanez
/pybanez/utilities.py
500
3.578125
4
def shared_notes(*args): """Identify notes belonging to all multiple passed lists of notes. Parameters ---------- *args : list, shape(num_notes, ) 1D List of notes. Returns ------- unique_notes : list shape(num_unique_notes, ) Alphabetically sorted list of notes which are present in all `*args` """ combined_notes = [] for a in args: combined_notes += a unique_notes = sorted(list(set(combined_notes))) return unique_notes
cea660e35fae2810739d45f79832cce69e9db939
RyosukeNAKATA/leetcode
/March_LeetCoding_Challenge_2021/day6.py
877
3.859375
4
""" Question: Short Encoding of Words A valid encoding of an array of words is any reference string s and array of indices indices such that: - words.length == indices.length - The reference string s ends with the '#' character. - For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i]. Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words. """ class Solution: def minimumLengthEncoding(self, words: List[str]) -> int: """ :type List[str] :rtype: int """ word_set = set(words) for word in words: if word in word_set: for i in range(1, len(word)): word_set.discard(word[i:]) return len("#".join(list(word_set))) + 1
181bdd31606f9b8ec46f7634f95964bc4debd25d
henry1034/Challenge-Project-of-CodeCademy
/python/Hypothesis_Testing_with_Python/Testing_a_Sample_Statistic/Simulating_a_Binomial_Test/binomial_testing_with_scipy.py
785
3.5625
4
import numpy as np import pandas as pd from scipy.stats import binom_test # calculate p_value_2sided here: p_value_2sided = binom_test( 41, # the number of observed successes n = 500, # the number of total trials p = 0.1 # the expected probability of success ) print(p_value_2sided) print(f"IF the true probability of purchasing is 0.1, the probability of observing 41 or fewer purchasing OR 59 or more purchasing is {p_value_2sided} ({(p_value_2sided * 100):.2f}%)") print() # calculate p_value_1sided here: p_value_1sided = binom_test( 41, n = 500, p = 0.1, alternative = "less" ) print(p_value_1sided) print(f"IF the true probability of purchasing is 0.1, the probability of observing 41 or fewer purchasing is {p_value_1sided} ({(p_value_1sided * 100):.2f}%)")
f5ab7d33cb9346bed3eb3004525952e3535cf89c
templeorz/test001
/第七章 输入和while循环 课后练习.py
5,499
4.21875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 7-1 汽车租赁 : 编写一个程序, 询问用户要租赁什么样的汽车, 并打印一条消息, 如“Let me see ifI can find you a Subaru”。 # 7-2 餐馆订位 : 编写一个程序, 询问用户有多少人用餐。 如果超过8人, 就打印一条消息, 指出没有空桌; 否则指出有空桌。 # 7-3 10的整数倍 : 让用户输入一个数字, 并指出这个数字是否是10的整数倍。 car_rental = 'What kind of car would like rent?' car = input(car_rental) print('\n Let me see if I can find you a ' + car + '.') # # number = input('How many person are eating ?') number = int(number) if number > 8: print("No seat now") else: print('please , come in') number1 = input('please ,enter What you like ?') number1 = int(number1) if number1 % 10 == 0: print(str(number1) + '这个数是十的整数' ) else: print(str(number1) + '这个数不是十的整数倍') # 7-4 比萨配料 : 编写一个循环, 提示用户输入一系列的比萨配料, 并在用户输入' quit' 时结束循环。 每当用户输入一种配料后, 都打印一条消息, 说我们会在比萨 # 中添加这种配料。 # 7-5 电影票 : 有家电影院根据观众的年龄收取不同的票价: 不到3岁的观众免费; 3~12岁的观众为10美元; 超过12岁的观众为15美元。 请编写一个循环, 在其中询问用 # 户的年龄, 并指出其票价。 # 7-6 三个出口 : 以另一种方式完成练习 7-4或练习 7-5, 在程序中采取如下所有做法。 #       在while 循环中使用条件测试来结束循环。 #       使用变量active 来控制循环结束的时机。 #       使用break 语句在用户输入' quit' 时退出循环。 # 7-7 无限循环 : 编写一个没完没了的循环, 并运行它(要结束该循环, 可按Ctrl +C, 也可关闭显示输出的窗口) pizza_add = '' while pizza_add != 'quit': pizza_add = input('\vplease add the ingredients to pizza') if pizza_add != 'quit': print('we will add ' + pizza_add + 'in pizza') else: print('') # while True: age_range = input('please enter your age and we will tell you the appropriate fare: ') # age_range = int(age_range) if str(age_range) == 'quit': break elif int(age_range) <= 3: print('Your ticket is free') elif int(age_range) in range(3,13): print('yours ticket is 10 dollar') elif int(age_range) > 12: print('Your ticket is 15 dollar') #原来7-4就是while循环中用条件测试,不再复写 active = True while active: pizza_add = input('Please add the ingredients to pizza: ') if pizza_add != 'quit': print('we will add ' + pizza_add + 'in pizza') else: active = False print('') while True: pizza_add = input('Please add the ingredients to pizza: ') if pizza_add == 'quit': break else: print('we will add ' + pizza_add + 'in pizza') while True: print('hold on') # 7-8 熟食店 : 创建一个名为sandwich_orders 的列表, 在其中包含各种三明治的名字; 再创建一个名为finished_sandwiches 的空列表。 遍历列 # 表sandwich_orders , 对于其中的每种三明治, 都打印一条消息, 如I made your tuna sandwich , 并将其移到列表finished_sandwiches 。 所有三明 # 治都制作好后, 打印一条消息, 将这些三明治列出来。 # 7-9 五香烟熏牛肉( pastrami) 卖完了 : 使用为完成练习 7-8而创建的列表sandwich_orders , 并确保' pastrami' 在其中至少出现了三次。 在程序开头附近添加 # 这样的代码: 打印一条消息, 指出熟食店的五香烟熏牛肉卖完了; 再使用一个while 循环将列表sandwich_orders 中的' pastrami' 都删除。 确认最终的列 # 表finished_sandwiches 中不包含' pastrami' 。 # 7-10 梦想的度假胜地 : 编写一个程序, 调查用户梦想的度假胜地。 使用类似于“Ifyou could visit one place in the world, where would you go?”的提示, 并编写一个打印调查 # 结果的代码块。 sandwich_orders = ['guita','pastrami','chess','pastrami','banana','pastrami' ] finished_sandwiches = [] while sandwich_orders: finished_sandwiches.append(sandwich_orders[-1]) print('I am made you ' + sandwich_orders.pop() + ' sandwich') print('all finish ') for a in finished_sandwiches: print('\v'+ str(a) ) # sandwich_orders = ['guita','pastrami','chess','pastrami','banana','pastrami' ] finished_sandwiches = [] while sandwich_orders: if sandwich_orders[-1] != 'pastrami': finished_sandwiches.append(sandwich_orders[-1]) print('I made you '+sandwich_orders.pop()+' sandwich.') else: sandwich_orders.pop() print('pastrami has been sold out.') responses = {} while True: name1 = input('what\'s your name ? ') dream_place = input('If you could visit one place in zhe world ,where you want to go: ') responses[name1] = dream_place #证明responses[name1] = dream_place,这是一种将信息储存到列表中的形式 # #Python中的key 不可以是 list类型 因为 list是可变的 不能被hash if dream_place == 'quit': break for name1,dream_place in responses.items(): print(name1 + ' would like visit ' + dream_place + 'in the dream ')
054083474f6d5c63ff72e77387d3b33c5730bd63
Rohithmarktricks/20186097_CSPP-1
/cspp1-assignments/m11/p3/assignment3.py
1,031
3.828125
4
''' Assignment-3 @author : Rohithmarktricks ''' def is_valid_word(word, hand, word_list): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ count = 0 new_hand = hand.copy() if word in word_list: for i in word: if i in new_hand and new_hand[i] > 0: count += 1 new_hand[i] -= 1 return bool(count == len(word)) def main(): ''' Main function to call the list and dictionary. ''' word = input() n_int = int(input()) adict = {} for i in range(n_int): del i data = input() l_list = data.split() adict[l_list[0]] = int(l_list[1]) l_list_2 = input().split() print(is_valid_word(word, adict, l_list_2)) if __name__ == "__main__": main()
e25091fe0d7d6054bc5b655b7b87b70548eff05a
PeterL64/UCDDataAnalytics
/8_Introduction_To_Data_Visualization_With_Seaborn/3_Visualizing_A_Categorical_And_A_Quantitative_Variable/3_Customizing_Bar_Plots.py
794
3.921875
4
# Customizing bar plots import matplotlib.pyplot as plt import seaborn as sns # Use sns.catplot() to create a bar plot with "study_time" on the x-axis and final grade ("G3") on the y-axis, # using the student_data DataFrame. sns.catplot(x='study_time', y='G3', data=student_data, kind='bar') # Using the order parameter, rearrange the categories so that they are in order from lowest study time to highest. sns.catplot(x='study_time', y='G3', data=student_data, \ kind='bar', order=["<2 hours", "2 to 5 hours", "5 to 10 hours", ">10 hours"]) # Update the plot so that it no longer displays confidence intervals. sns.catplot(x='study_time', y='G3', data=student_data, kind='bar',\ order=["<2 hours", "2 to 5 hours", "5 to 10 hours", ">10 hours"], ci=None) plt.show()
b6d6c14801205ff9781e2c5cdeb4749375dd52d9
Eboru77/see-segment
/see/JupyterGUI.py
5,889
3.625
4
"""This produces a GUI that allows users to switch between segmentation algorithms and alter the parameters manually using a slider. It shows two images, one with the original image with the resulting mask and one with the original image with the negative of the resulting mask.""" import matplotlib.pylab as plt import ipywidgets as widgets from IPython.display import display, clear_output from pathlib import Path from see import Segmentors import imageio def showtwo(img, img2): """Show two images side by side.""" fig = plt.figure(figsize=(20, 20)) my_ax = fig.add_subplot(1, 2, 1) my_ax.imshow(img) my_ax = fig.add_subplot(1, 2, 2) my_ax.imshow(img2) return fig def showthree(img, img1, img2): """Show three images side by side.""" fig = plt.figure(figsize=(20, 20)) my_ax = fig.add_subplot(1, 3, 1) my_ax.imshow(img) my_ax = fig.add_subplot(1, 3, 2) my_ax.imshow(img1) my_ax = fig.add_subplot(1, 3, 3) my_ax.imshow(img2) return fig def show_segment(img, mask): """Show both options for segmenting using the current mask. Keyword arguments: img -- original image mask -- resulting mask from segmentor """ im1 = img.copy() im2 = img.copy() im1[mask > 0, :] = 0 im2[mask == 0, :] = 0 fig = showtwo(im1, im2) return fig def pickimage(folder='Image_data/Examples/'): #def pickimage( directory = Path(folder) allfiles = sorted(directory.glob('*')) filelist = [] masklist = [] for file in allfiles: if file.suffix ==".jpg" or file.suffix ==".jpeg" or file.suffix ==".JPEG" or file.suffix ==".png": if not "_GT" in file.name: filelist.append(file) mask = directory.glob(f"{file.stem}_GT*") for m in mask: masklist.append(m) w = widgets.Dropdown( options=filelist, value=filelist[0], description='Choose image:', ) def update(w): clear_output(wait=True) # Clear output for dynamic display display(w) w.img = imageio.imread(w.value) index = filelist.index(w.value) w.mask = imageio.imread(masklist[index]) if len(w.mask.shape) > 2: w.mask = w.mask[:,:,0] fig = showtwo(w.img, w.mask) print(f"import imageio") print(f"data.img = imageio.imread(\'{w.value}\')") print(f"data.mask = imageio.imread(\'{masklist[index]}\')") def on_change(change): if change['type'] == 'change' and change['name'] == 'value': update(w) w.observe(on_change) update(w) return w def picksegment(algorithms): w = widgets.Dropdown( options=algorithms, value=algorithms[0], description='Choose Algorithm:', ) def on_change(change): if change['type'] == 'change' and change['name'] == 'value': clear_output(wait=True) # Clear output for dynamic display display(w) print(Segmentors.algorithmspace[change['new']].__doc__) print(f"\nsegmentor_name=\'{w.value}\'") w.observe(on_change) display(w) print(Segmentors.algorithmspace[w.value].__doc__) print(f"\nalg.value=\'{w.value}\'") return w def segmentwidget(img, gmask, params=None, alg=None): """Generate GUI. Produce slider for each parameter for the current segmentor. Show both options for the masked image. Keyword arguments: img -- original image gmask -- ground truth segmentation mask for the image params -- list of parameter options alg -- algorithm to search parameters over """ if params: if alg: params[0] = alg; seg = Segmentors.algoFromParams(params) else: if alg: algorithm_gen = Segmentors.algorithmspace[alg] seg = algorithm_gen() else: seg = Segmentors.segmentor() widg = dict() widglist = [] for ppp, ind in zip(seg.paramindexes, range(len(seg.paramindexes))): thislist = eval(seg.params.ranges[ppp]) name = ppp current_value = seg.params[ppp] if not current_value in thislist: #TODO: We should find the min distance between current_value and this list and use that instead. current_value = thislist[0] thiswidg = widgets.SelectionSlider(options=tuple(thislist), disabled=False, description=name, value=current_value, continuous_update=False, orientation='horizontal', readout=True ) widglist.append(thiswidg) widg[ppp] = thiswidg # algorithms = list(Segmentors.algorithmspace.keys()) # w = widgets.Dropdown( # options=algorithms, # value=algorithms[0], # description='Choose Algorithm:', # ) def func(img=img, mask=gmask, **kwargs): """Find mask and fitness for current algorithm. Show masked image.""" print(seg.params["algorithm"]) for k in kwargs: seg.params[k] = kwargs[k] mask = seg.evaluate(img) fit = Segmentors.FitnessFunction(mask, gmask) fig = showtwo(img, mask) # I like the idea of printing the sharepython but it should be below the figures. #print(seg.sharepython(img)) # plt.title('Fitness Value: ' + str(fit[0])) layout = widgets.Layout(grid_template_columns='1fr 1fr 1fr') u_i = widgets.GridBox(widglist, layout=layout) out = widgets.interactive_output(func, widg) display(u_i, out) return seg.params
bb5056cafde9b0023ff190de4418caf1507b52fc
Yona-Dav/DI_Bootcamp
/Week_4/Day5/challenges_1.py
5,940
4.15625
4
#Exercise 1 #Write a script that inserts an item at a defined index in a list. list = [1,2,3,4] list.insert(2,62) # in index2 print(list) #Exercise 2 # Write a script that counts the number of spaces in a string sentence = "This is a Beautiful Day" print(sentence.count(' ')) # Exercise 3 # Write a script that calculates the number of upper case letters and lower case letters in a string. import string upper_letter = string.ascii_uppercase lower_letter = string.ascii_lowercase count_upper = 0 count_lower = 0 for l in sentence: if l in upper_letter: count_upper += 1 elif l in lower_letter: count_lower +=1 print(f'Number of upper case letter : {count_upper} \nNumber of lower case letter: {count_lower}') # Exercise 4 # Write a function to find the sum of an array without using the built in function: numbers = [1,5,4,2] def summ(numbers): total = 0 for i in numbers: total += i return total print(summ(numbers)) # Exercise 5 # Write a function to find the max number in a list def max_number(list_number): max = int() for i in numbers: if i>max: max = i return max print(max(numbers)) # Exercise 6 # Write a function that returns factorial of a number def factorial(num): count = 1 for i in range(1,num+1): count *=i return count print(factorial(4)) # Exercise 7 # Write a function that counts an element in a list (without using the count method): def count_element(list_element, element): count =0 for i in list_element: if i == element: count +=1 return count my_list = ['a','a','t','o'] print(count_element(my_list,'a')) # Exercise 8 # Write a function that returns the L2-norm (square root of the sum of squares) of the sum of a list: def norm(list): total = 0 for i in list: total += i*i return int(total**(1/2)) print(norm([1,2,2])) # Exercise 9 # Write a function to find if an array is monotonic (sorted either ascending of descending) def is_mono(arr): if arr == sorted(arr) or arr == sorted(arr, reverse=True): return True else: return False print(is_mono([7,6,5,5,2,0])) print(is_mono([2,3,3,3])) print(is_mono([1,2,0,4])) # Exercise 10 # Write a function that prints the longest word in a list. def longuest_word(list): longuest = '' for i in list: if len(i)>len(longuest): longuest = i return longuest print(longuest_word(['your','computer','javascript','python'])) # Exercise 11 # Given a list of integers and strings, put all the integers in one list, and all the strings in another one. mix_list = [1,'you',2,8,956,'hello','world'] int_list = [] str_list = [] for i in range(len(mix_list)): if isinstance(mix_list[i],int)==True: int_list.append(mix_list[i]) else: str_list.append(mix_list[i]) print(int_list) print(str_list) # Exercise 12 # Write a function to check if a string is a palindrome: def is_palindrome(word): if word == word[::-1]: return True else: return False print(is_palindrome('radar')) print(is_palindrome('John')) # Exercise 13 # Write a function that returns the amount of words in a sentence with length > k: def sum_over_k(sentence,num): count =0 for word in sentence.split(' '): print(word) if len(word)>num: count+=1 return count sentence3 = 'Do or do not there is no try' print(sum_over_k(sentence3,2)) # Exercise 14 # Write a function that returns the average value in a dictionary (assume the values are numeric): def average_value(dictionary): total = 0 for value in dictionary.values(): total += value return total/len(dictionary) print(average_value({'a': 1,'b':2,'c':8,'d': 1})) # Exercise 15 # Write a function that returns common divisors of 2 numbers: def common_div(num1,num2): div = [] for i in range(1,num1+1): for j in range(1,num2+1): if num1%i==0 and num2%j==0 and i==j: div.append(i) return div print(common_div(20,10)) # Exercise 16 # Write a function that test if a number is prime: def is_prime(num): for i in range(2,num): if num%i==0: return False return True print(is_prime(11)) # Exercise 17 # Write a function that prints elements of a list if the index and the value are even: def even_index(list): even_list=[] for i in range(len(list)): if i%2==0 and list[i]%2==0: even_list.append(list[i]) return even_list print(even_index([1,2,2,3,4,5])) # Exercise 18 # Write a function that accepts an undefined number of keyworded arguments and return the count of different types: def type_count(**args): count_int = 0 count_str = 0 count_float = 0 count_bool = 0 for key, value in args.items(): if isinstance(value, bool)==True: count_bool += 1 elif isinstance(value, int)==True: count_int += 1 elif isinstance(value, str)==True: count_str += 1 elif isinstance(value, float)==True: count_float += 1 return f'int:{count_int}, str:{count_str}, float:{count_float}, bool:{count_bool}' print(type_count(a=1,b='string',c=1.0,d=True,e=False)) # Exercise 19 # Write a function that mimics the builtin .split() method for strings. sen = 'this is crazy' my_new_list = [] for i in range(len(sen)): if sen[i]==' ': my_new_list.append(sen[:i]) def split(sentence, delimiters): my_new_list = [] word='' for i in sentence: if i not in delimiters: word += i else: my_new_list.append(word) word = '' my_new_list.append(word) return my_new_list print(split('You are amazing',' ')) # Exercise 20 # Convert a string into password format. password = 'mypassword' password_hidden = '*'*len(password) print(password_hidden)
69eb8dcacd87ed1f1b872fda555db813d534e02d
softechie/ProjectEagle_L6_AI_ML_NLP
/PythonNLTK/nltk_02_sent_work_tokenize.py
422
3.8125
4
from nltk.tokenize import sent_tokenize, word_tokenize example_text = "Hello Mr. Pythonpro, how are you doing today? welcome to the python programming" print ("word list","\n","~~~~~~~~~~") print (word_tokenize(example_text)) print ("sentence list","\n","~~~~~~~~~~~~~") print (sent_tokenize(example_text)) print ("\n","Let us print all the sentences","\n") for i in sent_tokenize(example_text): print(i)
c7d38122c0004b4220dfcde49a5e68e3c5b5c2de
962245899/t07-maira-sandoval
/bucle04.py
629
4.0625
4
#validar el nombre de un mes nombre_de_un_mes="" no_es_el_nombre_de_un_mes=True while(no_es_el_nombre_de_un_mes): nombre_de_un_mes=input("Nombre de un mes:") no_es_el_nombre_de_un_mes=(nombre_de_un_mes != "enero" and nombre_de_un_mes != "febrero" and nombre_de_un_mes != "marzo" and nombre_de_un_mes != "abril" and nombre_de_un_mes != "mayo" and nombre_de_un_mes != "junio" and nombre_de_un_mes != "julio" and nombre_de_un_mes != "agosto" and nombre_de_un_mes != "setiembre" and nombre_de_un_mes != "octubre" and nombre_de_un_mes != "noviembre" and nombre_de_un_mes != "diciembre" ) #fin del bucle print("fin")
18c2b521d6ea5c2d9052c868a76c8b84c422d68c
VZakharuk/sofrserve_pythonc
/ClassWork/cw13/mile_to_km.py
303
3.734375
4
# variant with map # def miles_to_km(numb_miles): # return numb_miles*1.6 # list_miles = [1.0, 2.0, 1.4, 2.5] # list_km = list(map(miles_to_km, list_miles)) # print(list_km) # variant with lambda list_miles = [1.0, 2.0, 1.4, 2.5] list_km = list(map(lambda x: x*1.6, list_miles)) print(list_km)
ad08dfdd705b0ac724e798474e4730f43bba9b67
jordanjj8/exercising_with_python
/slice.py
965
4.28125
4
# Jordan Leung # 2/13/2019 # printing out what is given print("Given: ") cubes = [num**3 for num in range(1,11)] print(cubes) # printing out the first three items print("The first three items in the list are: ") print(cubes[:3]) # printing out the middle of the list print("Three items from the middle of the list are: ") mid = int(len(cubes)/2) mid_Start = int(mid - 1) mid_End = int(mid + 2) print(cubes[mid_Start:mid_End]) # printing out the last three items in the list print("The last three iems in the list are: ") print(cubes[-3:]) # making a copy of a list by slicing and verifying that they are stored seperately my_fav_foods = ['cookies', 'clams', 'pickles'] friends_foods = my_fav_foods[:] my_fav_foods.append('okura') friends_foods.append('buns') print("My favorite foods include: ") for food in my_fav_foods: print(food) print("My friend's favorite foods include: ") for food in friends_foods: print(food)
237b020210e0a9c7cb59528ad6852e646f1f83f8
Rebecca-Simms/Python-Challenges
/FizzBuzz Challenge/FizzBuzz.py
382
3.734375
4
def fizzbuzz_compute(maxnumb): fizzbuzz = [] for i in range(0, maxnumb + 1): word = '' if i % 3 == 0: word += "Fizz" if i % 5 == 0: word += "Buzz" if i % 7 == 0: word += "Pop" if word == '': word += str(i) fizzbuzz.append(word) return fizzbuzz print(fizzbuzz_compute(100))
ccf96f9711d950dba0b8ea01ea711151c4daf6bd
lucabianco78/QCBsciprolab2020
/exercises/readFile_gz.py
505
3.78125
4
import argparse import gzip parser = argparse.ArgumentParser(description="""Reads and prints a text file""") parser.add_argument("filename", type=str, help="The file name") parser.add_argument("-z", "--gzipped", action="store_true", help="If set, input file is assumed gzipped") args = parser.parse_args() inputFile = args.filename fh = "" if(args.gzipped): fh = gzip.open(inputFile, "rt") else: fh = open(inputFile, "r") for line in fh: line = line.strip("\n") print(line) fh.close()
45bcb952e6936d45717ab49fa8a910edaeedaa3e
dydwnsekd/coding_test
/programmers/python/소수_찾기.py
611
3.640625
4
# https://programmers.co.kr/learn/courses/30/lessons/12921 def solution(n): sieve = [True] * (n+1) m = int(n ** 0.5) for i in range(2, m + 1): if sieve[i] == True: for j in range(i+i, n+1, i): sieve[j] = False return sieve[2:].count(True) """ def isdecimal(n): if n == 2 or n == 3: return True for i in range(2, n): if n % i == 0: return False return True def solution(n): answer = 0 for i in range(2, n+1): if isdecimal(i): answer += 1 return answer """
be3d010d24ec82183280cc2e011a1db5b2001c38
BreenIsALie/-Python-Hello-World
/ex13.py
497
3.734375
4
__author__ = 'BreenIsALie' # Exercise 13, Exercises taken from http://learnpythonthehardway.org/book/ # Parameters, unpacking and Variables # import the argument variable (argv) for use. This is a MODULE (IMPORTANT TO REMEMBER) from sys import argv # Take input from argv and assign it to variables script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third
b4f4d967bc3e22c44d6e57d88219da46908984cb
rcarino/Project-Euler-Solutions
/problem36.py
474
3.5625
4
__author__ = 'rcarino' def is_5and2_palindromic(n): binary = bin(n)[2:] return is_palindrome(str(n)) and is_palindrome(binary) def is_palindrome(s): end = len(s) for i in range(end/2 + 1): if s[i] != s[end - 1 - i]: return False return True def palindromes_base_5and2(n): rtn = [] for i in range(0, n): if is_5and2_palindromic(i): rtn.append(i) return rtn print sum(palindromes_base_5and2(1000000))
56fac970d8344fc0c446d41d82830a4f4c10dc95
PGYangel/python_test
/dataType/numbers.py
3,977
4.125
4
# Number(数字) # 数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间。 num = 1 print(num) ''' del语句的语法是 del var1[,var2[,var3[....,varN]]]] 您可以通过使用del语句删除单个或多个对象的引用。例如: del var del var_a, var_b ''' ''' Python 支持四种不同的数值类型: 整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点。 长整型(long integers) - 无限大小的整数,整数最后是一个大写或小写的L。 浮点型(floating point real values) - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250) 复数(complex numbers) - 复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。 注意:python不支持long类型 ''' ''' Python math 模块、cmath 模块 Python 中数学运算常用的函数基本都在 math 模块、cmath 模块中。 Python math 模块提供了许多对浮点数的数学运算函数。 Python cmath 模块包含了一些用于复数运算的函数。 cmath 模块的函数跟 math 模块函数基本一致,区别是 cmath 模块运算的是复数,math 模块运算的是数学运算。 要使用 math 或 cmath 函数必须先导入: import math import cmath ''' ''' Python数学函数 函数 返回值 ( 描述 ) abs(x) 返回数字的绝对值,如abs(-10) 返回 10 ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5 cmp(x, y) 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1 exp(x) 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045 fabs(x) 返回数字的绝对值,如math.fabs(-10) 返回10.0 floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4 log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0 log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0 max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。 min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。 modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。 pow(x, y) x**y 运算后的值。 round(x [,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。 sqrt(x) 返回数字x的平方根 ''' ''' Python随机数函数 函数 描述 choice(seq) 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。 randrange([start,] stop [,step]) 从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1 random() 随机生成下一个实数,它在[0,1)范围内。 seed([x]) 改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。 shuffle(lst) 将序列的所有元素随机排序 uniform(x, y) 随机生成下一个实数,它在[x,y]范围内。 ''' ''' Python三角函数 函数 描述 acos(x) 返回x的反余弦弧度值。 asin(x) 返回x的反正弦弧度值。 atan(x) 返回x的反正切弧度值。 atan2(y, x) 返回给定的 X 及 Y 坐标值的反正切值。 cos(x) 返回x的弧度的余弦值。 hypot(x, y) 返回欧几里德范数 sqrt(x*x + y*y)。 sin(x) 返回的x弧度的正弦值。 tan(x) 返回x弧度的正切值。 degrees(x) 将弧度转换为角度,如degrees(math.pi/2) , 返回90.0 radians(x) 将角度转换为弧度 ''' ''' Python数学常量 常量 描述 pi 数学常量 pi(圆周率,一般以π来表示) e 数学常量 e,e即自然常数(自然常数)。 '''
f6902f120114efd5e328f0e478138f207dc72f3f
Upasna4/Training
/primeornot.py
161
4
4
n=int(input("enter a number")) f=0 for i in range(2,n): if (n%i==0): print("composite number") f=1 break if(f==0): print("prime")
787445b8cb127df7996a1c4c0577ae68c3a4e8c5
egbeyongtanjong/MIT_Data_Analysis_2020
/Lecture_notes/Lecture5.py
3,518
4.21875
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 10 08:36:06 2020 @author: Egbeyong """ """ There are three data structures used in python to collect items: Tuples, lists, and dictionaries tuples and lists are ordered sequence of objects. It makes sense to talk about the first object, the second object, the last object, and so on You can get slices of tuples The major difference between list and tuples is that tuples are immutable. Once created, you cannot change its value, you can create a new tuple, but you cannot change the value of the old one. Lists are the first mutable objects we are dealing with. Both lists and tuples need not be homogeneous. A list and a tuple can contain different primitives, and even lists of lists, or tuple of tuples. list.append(list1) actually mutates list, and it has side effects we invoke append coz we are interested in the side effects Dictionaries or dicts (as they are spelled in python) are not ordered and two, the indices need not be integers and they are not called integers, they are called keys Watch out for aliasing (one object with two names) with mutabe objects L1 = [2] L2 = L1 L2[0] = 'a' print(L1) prints a (since both list point to the same object) Now copying L1 to L2 produces a different side effect L1 = [2] L2 = L1[:] L2[0] = 'a' print(L1) prints [2] (since both list point to different objects) """ #******************************************************************** """ #example of tuple x = (0,1,2,3,4) print(x[0]) """ #********************************************************************* """ #Useful example of tuple, find all divisors of 100 and save in a \ #tuple divisors = () for x in range(1, 101): if 100%x == 0: divisors += (x,) #creates a new tuple in each run print(divisors) print(divisors [1:3]) #slicing tuples divisors = (1,2,3,4) #creates another new tuple print(divisors) #***************************************************************** # Illustrating the beauty and peril of mutation #L2 updates when ever printed, eventhough L2 was never modified #after L1 was modified. L1 = [2,3] L2 = ['a',L1,L1] print(L2) """ #************************************************************** """ # Now we are moving on to talk about dictionaries #A set of key value pairs #acccessed by looking at the keys D = {1: 'one', 'deux':'two','pi':3.14159} D1 = D print(D1['deux']) D1[1] = 'uno' print(D[1]) print(D.keys()) del D[1] print(D) """ #***************************************************************** #Example showing what we can do with dictionaries #Obtaining translations with dictionary EtoF = {'bread':'du pain', 'wine':'du vin','eats':'mange',\ 'drinks':'bois','likes':'aime',1:'un','6.00':'6.00'} print(EtoF) if 'du pain' in EtoF: #evaluates to false, only keys will evaluate to true print("True") print() print(EtoF.keys()) #built-in method to print all keys #method to translate word def translateWord(word, dictionary): if word in dictionary: return dictionary[word] else: return word #method to translate sentence def translate(sentence): translation = '' word = '' for c in sentence: if c != ' ': word = word + c else: translation = translation + ' ' + translateWord(word, EtoF) word = '' return translation[1:] + ' ' + translateWord(word, EtoF) #test examples print(translate('John eats bread')) print(translate('Steve drinks wine')) print(translate('John likes 6.00'))
0b4d756c4f917a2f9071b65fa6c52b968211a9ec
jdb45/Guess-Number-Game
/tests/test_guess_the_number.py
854
3.765625
4
import unittest from guess_the_number import Guess_The_Number class TestGuessTheNumber(unittest.TestCase): # testing to make sure the check guess function is correctly displaying the right message def test_check_guess(self): self.assertEqual('guess is too low!', Guess_The_Number.check_guess(2, 4)) self.assertEqual('guess is too low!', Guess_The_Number.check_guess(3, 7)) self.assertEqual('guess is too high!', Guess_The_Number.check_guess(7, 2)) self.assertEqual('guess is too high!', Guess_The_Number.check_guess(10, 4)) # testing to make sure the random number generator is assigning a number in-between the right range def test_random_number(self): range_list = range(1, 10) get_random_num = Guess_The_Number.get_random_Number() self.assertIn(get_random_num, range_list)
9c31580ca962d7d179baefb5bad77186b9a4019f
kozlakowski/Fibonacci-w-explanation
/fibonacci.py
285
3.859375
4
iloscLiczb = int(input("Ile liczb fibonacciego chcesz uzyskac: ")) lista = [] num1 = 0 num2 = 1 for i in range(iloscLiczb): num1 = num2 - num1 print("Aktualne num1:", num1) num2 = num1 + num2 print("Aktualne num2:", num2) lista.append(num1) print(lista)
d4aec054a464f776924dd42b12874bd9fc3226c9
saattrupdan/stay_awake
/stay_awake.py
1,101
3.921875
4
def stay_awake(interval: int = 3, failsafe: bool = False): ''' Keeps the computer awake. INPUT interval: int = 3 How often the movement should occur, in minutes failsafe: bool = False Enable PyAutoGUI's failsafe, which disables the GUI if the mouse is moved to the top left corner ''' import pyautogui from time import sleep from datetime import datetime from itertools import cycle pyautogui.FAILSAFE = failsafe for even in cycle([True, False]): sleep(interval * 60) pyautogui.press('shift') # Move cursor one pixel down or up vertical_change = 1 if even else -1 pyautogui.move(0, vertical_change) print(f"Movement made at {datetime.now().time()}") if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-i', '--interval', type = int, default = 3) parser.add_argument('-f', '--failsafe', type = bool, default = False) args = vars(parser.parse_args()) stay_awake(**args)
2659a4c21942136e6b37a1f3ed2eae77c9fbcef2
coolwonny/Jupyter_Workspace
/pracitice.py
3,338
3.828125
4
# grocery = ["Water", "Butter", "Eggs", "Apples", "Cinnamon", "Sugar", "Milk"] # print(f"The first two items: {grocery[:2]}") # print(f"The last five items: {grocery[-5:]}") # print(f"Every other items: {grocery[1::2]}") # grocery.append("flour") # grocery[3] = "Gala Apples" # print(f"The total number of items: {len(grocery)}") # grocery.pop() # print(grocery) # grocery.append("Cream") # del grocery[2] # print(grocery) # print(f"Index of Gala Apples is {grocery.index("Gala Apples")}") # trading_pnl = [ -224, 352, 252, 354, -544, # -650, 56, 123, -43, 254, # 325, -123, 47, 321, 123, # 133, -151, 613, 232, -311 ] # total = 0 # count = 0 # average = 0 # minimum = 0 # maximum = 0 # profitable_days = [] # unprofitable_days = [] # for x in trading_pnl: # total += x # count += 1 # if minimum == 0: # minimum = x # elif x < minimum: # minimum = x # elif x > maximum: # maximum = x # if x > 0: # profitable_days.append(x) # elif x <= 0: # unprofitable_days.append(x) # average = total / count # Percentage_profitable = round((len(profitable_days)) / count * 100, 2) # precentage_unprofitable = 100 - Percentage_profitable # print(f"Number of total trading days: {count}") # print(f"Total profits and losses: {total}") # print(f"Daily average profit and loss: {average}") # print(f"Worst loss: {minimum}") # print(f"Best gain: {maximum}") # print(f"Number of profitable days: {len(profitable_days)}") # print(f"Number of unprofitable days: {len(unprofitable_days)}") # print(f"Percentage of profitable days: {Percentage_profitable}%") # print(f"Percentage of unprofitable days: {precentage_unprofitable}%") # print(f"Profitable days: {profitable_days}") # print(f"Unprofitable days: {unprofitable_days}") banks = { "JP Morgan Chase": 327, "Bank of America": 302, "Citigroup": 173, "Wells Fargo": 273, "Goldman Sachs": 87, "Morgan Stanley": 72, "U.S. Bancorp": 83, "TD Bank": 108, "PNC Financial Services": 67, "Capital One": 47, "FNB Corporation": 4, "First Hawaiian Bank": 3, "Ally Financial": 12, "Wachovia": 145, "Republic Bancorp": .97 } banks["Citigroup"] = 170 banks["American Express"] = 33 del banks["Wachovia"] print(banks) total = 0 count = 0 average = 0 minimum = 0 maximum = 0 minimum_key = "" maximum_key = "" mega_cap = [] large_cap = [] mid_cap = [] small_cap = [] for x, y in banks.items(): total += y count += 1 if minimum == 0: minimum = y minimum_key = x print(minimum_key) elif y < minimum: y = minimum x = minimum_key elif y > maximum: y = maximum x = maximum_key print(maximum_key) # if y >= 300: # mega_cap.append(x) # elif y >= 10: # large_cap.append(x) # elif y >= 2: # mid_cap.append(x) # elif y >= 0.3: # small_cap.append(x) # average = total / count # print(f"Total market cap: {total}") # print(f"Total number of banks: {count}") # print(f"Average market cap: {average}") # print(f"largest bank: {maximum_key}") # print(f"smallest bank: {minimum_key}") # print() # print(f"Mega Cap banks: {mega_cap}") # print(f"Large cap: {large_cap}") # print(f"mid cap: {mid_cap}") # print(f"small cap:{small_cap}")
14eb2a56190d242154d8344c8feaafb164ee10be
melamri/Python_Applications
/04 Functions/Taking_a_Vaca.py
1,362
4.5
4
"""Define a function called rental_car_cost with an argument called days. Calculate the cost of renting the car: Every day you rent the car costs $40. if you rent the car for 7 or more days, you get $50 off your total. Alternatively (elif), if you rent the car for 3 or more days, you get $20 off your total. You cannot get both of the above discounts. Return that cost. Just like in the example above, this check becomes simpler if you make the 7-day check an if statement and the 3-day check an elif statement.""" def rental_car_cost(days): cost = 40 * days if days >= 7: cost -= 50 elif days < 7 and days >= 3: cost -= 20 return cost """In the below example, we first give the player 10 tickets for every point that the player scored. Then, we check the value of score multiple times. First, we check if score is greater than or equal to 10. If it is, we give the player 50 bonus tickets. If score is just greater than or equal to 7, we give the player 20 bonus tickets. At the end, we return the total number of tickets earned by the player. Remember that an elif statement is only checked if all preceding if/elif statements fail.""" def finish_game(score): tickets = 10 * score if score >= 10: tickets += 50 elif score >= 7: tickets += 20 return tickets
a90349514cac600cbbcebd9fb49821a21c887de8
AlexseyPivovarov/python_scripts
/lesson4_1523633686/player us player.py
1,815
3.75
4
from os import system, name cls = "cls" if name == "nt" else "clear" board = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "] ] chip = ["X", "O"] i = 0 win = 0 while True: gamer = i % 2 # interface system(cls) print(" 1 2 3") print("1 {0[0][0]}|{0[0][1]}|{0[0][2]} Игрок: {1}".format(board, gamer + 1)) print(" ------- Ваша фишка: {}".format(chip[gamer])) print("2 {0[1][0]}|{0[1][1]}|{0[1][2]} Для хода введите номера строки и столбца (например: 22)".format(board)) print(" ------- Для выхода введите 'е'") print("3 {0[2][0]}|{0[2][1]}|{0[2][2]}".format(board)) if win == 1: print("Победил игрок {}".format(gamer + 1)) break elif win == -1: print("Ничья") break # input xy = input("Ваш ход: ") # checking input if xy != "e": if len(xy) != 2: continue try: x, y = int(xy[0])-1, int(xy[1])-1 except: continue if x > 2 or y > 2 or board[x][y] != " ": continue board[x][y] = chip[gamer] # check for win for index in [0, 1, 2]: if board[index][0] == board[index][1] == board[index][2] != " ": win = 1 continue if board[0][index] == board[1][index] == board[2][index] != " ": win = 1 continue if win: continue if board[0][0] == board[1][1] == board[2][2] != " " or board[0][2] == board[1][1] == board[2][0] != " ": win = 1 continue i += 1 if i > 8: i -= 1 win = -1 continue else: # exit game break
ca0d85198b9379043d9d0a8c88caa05a766eb0d4
Chrisboris/python-work
/power.py
206
4.21875
4
base = int(input("Enter base : ")) power = int(input("Enter power: ")) def pow(base,power): result = 1 for x in range(power): result = result*base return result print(pow(base,power))
8fa617ef14fe216fe00e1dda399942104fa505e4
teerapat-ch/DataScienceProjects
/Machine Learning A-Z Code/Chapter 4 Clustering/Hierarchical_Clustering/hc.py
1,235
3.796875
4
# Hierarchical Clustering # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:, [3, 4]].values # y = dataset.iloc[:, 3].values # Using the dendrogram to find the optimal number of clusters import scipy.cluster.hierarchy as sch dendrogram = sch.dendrogram(sch.linkage(X, method='ward')) plt.title('Dendrogram') plt.xlabel('Customers') plt.ylabel('Euclidean distances') plt.show() # Fitting hierarchical clustering to the mall dataset from sklearn.cluster import AgglomerativeClustering hc = AgglomerativeClustering(n_clusters = 5, affinity ='euclidean',linkage = 'ward') y_hc = hc.fit_predict(X) #Visualising the clusters plt.scatter(X[y_hc==0,0],X[y_hc==0,1],s=100,c='red',label='Careful') plt.scatter(X[y_hc==1,0],X[y_hc==1,1],s=100,c='blue',label='Standard') plt.scatter(X[y_hc==2,0],X[y_hc==2,1],s=100,c='green',label='Target') plt.scatter(X[y_hc==3,0],X[y_hc==3,1],s=100,c='yellow',label='Careless') plt.scatter(X[y_hc==4,0],X[y_hc==4,1],s=100,c='brown',label='Sensible') plt.title("Clusters of clients") plt.xlabel("Annual Income") plt.ylabel('Spending Score (1-100)') plt.legend() plt.show()
25571a454111d39ee5518385e37fe23364808eea
subho2107/Hacker-Rank
/Data Structures/Stack/Poisonous Plants.py
1,389
3.9375
4
""" PROBLEM LINK:https://www.hackerrank.com/challenges/poisonous-plants/problem """ #!/bin/python3 import math import os import random import re import sys # Complete the poisonousPlants function below. def poisonousPlants(p): day = 0 stackArr = [] pos = 0 stackArr.append([]) stackArr[0].append(p[0]) for i in range(1, len(p)): if (p[i] <= p[i - 1]): stackArr[pos].append(p[i]) else: pos += 1 stackArr.append([]) stackArr[pos].append(p[i]) length = len(stackArr) while len(stackArr) != 1: i = 1 while (i < len(stackArr)): stackArr[i].pop(0) if (len(stackArr[i]) != 0): if (stackArr[i][0] <= stackArr[i - 1][len(stackArr[i - 1]) - 1]): stackArr[i - 1] += stackArr[i] stackArr.pop(i) i -= 1 else: stackArr.pop(i) i -= 1 if (i >= len(stackArr) - 1): break i += 1 day += 1 return day if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) p = list(map(int, input().rstrip().split())) result = poisonousPlants(p) fptr.write(str(result) + '\n') fptr.close()
455be873dfb644c24725a0e8daf179a13396f0f0
dlin94/leetcode
/array/414_third_max_number.py
536
3.53125
4
class Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 3: return max(nums) s = set(nums) if len(s) < 3: return max(s) m1 = None m2 = None m3 = None for x in s: if x > m1: m1, m2, m3 = x, m1, m2 elif x < m1 and x > m2: m2, m3 = x, m2 elif x < m2 and x > m3: m3 = x return m3
e2a9f26dc5c6c56582daa002a4c3c616fa7834a7
Akagi201/learning-python
/lpthw/ex42.py
1,432
4.28125
4
#!/usr/bin/env python # Exercise 42: Is-A, Has-A, Objects, and Classes ## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a Animal class Dog(Animal): def __init__(self, name): ## Dog has-a name self.name = name ## Cat is-a animal class Cat(Animal): def __init__(self, name): ## Cat has-a name self.name = name ## Person is-a object class Person(object): def __init__(self, name): ## Person has-a name self.name = name ## Person has-a pet of some kind self.pet = None ## Employee is-a person class Employee(Person): def __init__(self, name, salary): ## run the __init__ method of a parent class reliably super(Employee, self).__init__(name) ## Employee has-a salary self.salary = salary ## Fish is-a object class Fish(object): pass ## Salmon is-a Fish class Salmon(Fish): pass ## Halibut is-a fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## satan is-a Cat satan = Cat("Satan") ## mary is-a Person mary = Person("Mary") ## mary's pet is satan mary.pet = satan ## frank is-a Employee, his salary is 120000 frank = Employee("Frank", 120000) ## frank's pet is rover frank.pet = rover ## flipper is-a Fish flipper = Fish() ## crouse is-a Salmon crouse = Salmon() ## harry is-a Halibut harry = Halibut()
d7af183a88284380542a46559f490bdbefdcd9f3
dwayneglevene/myfirstflask
/model.py
135
3.5
4
def foodAte(food): if food.lower() == "waffles": return "thats a nice breakfast" else: return "Ok sounds good"
c2d2b2e04cf5f85fffd1c9126dd3f30b36348dd9
metchel/poker
/test_hand.py
2,597
3.5
4
import unittest from hand import Hand, HandRanker, Rank from card import Card, Suit, Value class TestHand(unittest.TestCase): def test_royal_flush(self): ranker = HandRanker() cards = [ Card('S', 14), Card('S', 13), Card('S', 12), Card('S', 11), Card('S', 10) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.ROYAL_FLUSH) def test_straight_flush(self): ranker = HandRanker() cards = [ Card('S', 13), Card('S', 12), Card('S', 11), Card('S', 10), Card('S', 9) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.STRAIGHT_FLUSH) def test_four_of_a_kind(self): ranker = HandRanker() cards = [ Card('S', 13), Card('H', 13), Card('D', 13), Card('C', 13), Card('S', 9) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.FOUR_OF_A_KIND) def test_full_house(self): ranker = HandRanker() cards = [ Card('S', 13), Card('H', 13), Card('D', 13), Card('C', 9), Card('S', 9) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.FULL_HOUSE) def test_flush(self): ranker = HandRanker() cards = [ Card('S', 13), Card('S', 12), Card('S', 11), Card('S', 3), Card('S', 9) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.FLUSH) def test_straight(self): ranker = HandRanker() cards = [ Card('D', 13), Card('H', 12), Card('C', 11), Card('C', 10), Card('S', 9) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.STRAIGHT) def test_three_of_a_kind(self): ranker = HandRanker() cards = [ Card('S', 13), Card('H', 13), Card('D', 13), Card('C', 11), Card('S', 9) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.THREE_OF_A_KIND) def test_two_pair(self): ranker = HandRanker() cards = [ Card('S', 13), Card('H', 13), Card('D', 12), Card('C', 9), Card('S', 9) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.TWO_PAIR) def test_pair(self): ranker = HandRanker() cards = [ Card('S', 13), Card('H', 13), Card('D', 12), Card('C', 3), Card('S', 9) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.PAIR) def test_high_card(self): ranker = HandRanker() cards = [ Card('S', 13), Card('H', 11), Card('D', 3), Card('C', 10), Card('S', 9) ] hand = Hand(cards) self.assertEqual(ranker.rank(hand), Rank.HIGH_CARD) if __name__ == '__main__': unittest.main()
a8d136117927b83dcc10cdb3b3470f1b9b46959b
Roshanbhuvad/Peewee--Python-MySQLite
/Insert_table/count_instances.py
600
3.546875
4
#To calculate the number of model instances in the table, we can use the count() method. import peewee import datetime db = peewee.SqliteDatabase('test2.db') class Note(peewee.Model): text = peewee.CharField() created = peewee.DateField(default=datetime.date.today) class Meta: database = db db_table = 'notes' n = Note.select().count() print(n) n2 = Note.select().where(Note.created >= datetime.date(2018, 10, 20)).count() print(n2) """The example counts the number of all instances and the number of instances where the date is equal or later than 2018/10/20. O/P: 7 4 """
70f41797d4b40cbebbf422a28f41083c2b98e60d
andrehmiguel/treinamento
/exercicioLista_EstruturaDecisao/ex27.py
1,121
4.0625
4
# 27. Uma fruteira está vendendo frutas com a seguinte tabela de preços: # ======================================================== # |Até 5 Kg |Acima de 5 Kg # Morango |R$ 2,50 por Kg |R$ 2,20 por Kg # Maçã |R$ 1,80 por Kg |R$ 1,50 por Kg # ========================================================= # Se o cliente comprar mais de 8 Kg em frutas ou o valor total da compra # ultrapassar R$ 25,00, receberá ainda um desconto de 10% sobre este total. # Escreva um algoritmo para ler a quantidade (em Kg) de morangos e a # quantidade (em Kg) de maças adquiridas e escreva o valor a ser pago pelo # cliente. morango = float(input('Digite a quantidade (Kg) de morangos: ')) maca = float(input('Digite a quantidade de (Kg) de maçãs: ')) if morango <= 5: preco_mo = 2.50 * morango else: preco_mo = 2.20 * morango if maca <= 5: preco_ma = 1.80 * maca else: preco_ma = 1.50 * maca preco = preco_ma + preco_mo if preco > 25 or (morango + maca) > 8: desconto = (preco * 10) / 100 preco = preco - desconto print(f'Valor da compra: R$ {preco:.2f}')
033102ee055525bc49f07beb1db77ea3eeb25cf8
Francois-Aubet/UCL_MSc_ML_code
/algorithms/Algorithm.py
567
3.59375
4
from abc import ABCMeta, abstractmethod import numpy as np class Algorithm(): """ The abstract parent class for all the algorithms. """ # we define the class as an abstract class: __metaclass__ = ABCMeta def __init__(self, dataset, meta_data): """ Constructor """ self._dataset = dataset self._meta_data = meta_data @abstractmethod def extract_neural_path(self): """ @:return: """ raise NotImplementedError("Must override methodB")
8fe49f33d844a8da056321e24aeb2adeba87f5b3
erikac613/PythonCrashCourse
/3-9.py
151
3.65625
4
guests = ['geddy lee', 'john cleese', 'st. vincent', 'john lennon', 'kate bush', 'patrick stewart'] print("There will be a total of " + str(len(guests))) + " guests at dinner."
222ba51b9e8284415e506727cf070f626835d26c
KrushikReddyNallamilli/Python-100days-Challenge
/semoprime.py
495
3.9375
4
import math def checkSemiprime(num): cnt = 0 for i in range(2, int(math.sqrt(num)) + 1): while num % i == 0: num /= i cnt += 1 if cnt >= 2: break if(num > 1): cnt += 1 return cnt == 2 def semiprime(n): if checkSemiprime(n) == True: print("NO") else: print("YES") lst = [] n = int(input()) for i in range(0, n): ele = int(input()) semiprime(ele)
70426b8a776ba3da815beedb3986acc356716d80
pbehnke/algorithmx-python
/algorithmx/graphics/types.py
1,892
3.609375
4
from typing import Dict, Union, Iterable, Callable, TypeVar, Any T = TypeVar('T') ElementFn = Union[Callable[[Any], T], Callable[[Any, int], T]] """ A function taking a selected element's data as input. This is typically provided as an argument in a selection method, allowing attributes to be configured differently for each element. :param ElementFn.data: The data associated with the element. If the :meth:`~graphics.Selection.data` method was used previously in the method chain, it will determine the type of data used. If the selection has no associated data, it will fall back on its parent's data (as is the case for :class:`~graphics.LabelSelection`). Otherwise, the information used to construct the selection will serve as its data (such as node ID values and edge tuples). :param ElementFn.index: (Optional) The index of the element in the selection, beginning at 0, determined by its position in the list initially used to construct the selection. """ ElementArg = Union[ElementFn[T], T] """ Allows an argument to be provided either directly, or as a function of each element's data (see :data:`ElementFn` and :meth:`~graphics.Selection.data`). """ NumExpr = Union[int, float, str, Dict] """ A number, or an expression evaluating to a number. Expressions must be in the form ``mx+c``, described by either an ``{ m, x, c }`` dictionary, or an expression string such as "-2x+8". Both ``m`` and ``c`` are constants, while ``x`` is a variable corresponding to some other attribute. Below is a list of valid variables and the context in which they can be used: * "cx": Half the width of the canvas. * "cy": Half the height of the canvas. * nodes * "x": Half the width of the node. * "y": Half the height of the node. * labels * "r": Distance from the center of the node to its boundary given the angle attribute of the label. """
220090199640617a2c02e51d297ab72785429848
JakubKazimierski/PythonPortfolio
/AlgoExpert_algorithms/Medium/FindSucessor/FindSuccessor.py
1,971
4.1875
4
''' Find Sucessor from AlgoExpert.io January 2021 Jakub Kazimierski ''' class BinaryTree: ''' Write a function that takes in a Binary Tree (where nodes have an additional pointer to their parent node) as well as a node contained in that tree and returns the given node's successor. A node's successor is the next node to be visited (immediately after the given node) when traversing it's tree using the in-order tree-traversal technique. A node has no successor if it's the last node to be visited in the in-order traversal. If a node has no successor, your function should return None/null. Each BinaryTree node has an integer value, a parent node, a left child node, and a right chid node. Children nodes can either be BinaryTree nodes themselves or None/null. ''' def __init__(self, value, left=None, right=None, parent=None): self.value = value self.left = left self.right = right self.parent = parent def findSuccessor(tree, node): ''' Use inorderTraverse logic traverse(left) vist traverse(right) Time O(h) where h is level of the tree | space O(1) ''' if node.right is not None: return getLeftmostChild(node.right) elif node.parent is not None and node.parent.left == node: return node.parent elif node.parent is not None and node.parent.right == node: return findMostRightParent(node) else: return None def getLeftmostChild(node): ''' Time O(h) | space O(1) Returns leftmost child of subtree. ''' while node.left is not None: node = node.left return node def findMostRightParent(node): ''' Find first right parent. O(h) time | O(1) space ''' while node.parent is not None and node == node.parent.right: node = node.parent return node.parent
7589c18be5f69b8bb6586946106740aa45a003b0
bagusdewantoro/datascience
/algebra_vector.py
3,452
3.5
4
vector = [ [0, 0], [2, 5], [1, 3], [3, 6], [5, 7] ] def jarak(v, w): return [vi + wi for vi, wi in zip(v,w)] Notes = """ 1. Perlu fungsi untuk bikin list vector: [0, 0], [2, 5], [3, 8], [6, 14], [11, 21] Caranya: - initial = vector[0] --> sama dengan vector[-1] = [0,0] - titik2 = jarak(vector[0], vector[1]) = jarak([0,0], [2,5]) = [2,5] - titik3 = jarak(titik2, vector[2]) = jarak([2,5], [1,3]) = [3,8] - titik4 = jarak(titik3, vector[3]) = jarak([3,8], [3,6]) = [6,14] - titik5 = jarak(titik4, vector[4]) = jarak([6,14], [5,7]) = [11,21] 2. Perlu fungsi untuk pilih axis X atau Y (karena matplotlib akan ambil masing-masing axis) """ def axis(delta, sumbu): """Delta untuk list vectornya. Sumbu 0 = X, Sumbu 1 = Y""" a = [delta[0]] # loop_pertama: a = [[0,0]] for titik in delta: ulang = len(a) # loop_pertama: len(a) = 1 if ulang == len(delta): # loop_pertama: ulang=1. len(delta)=5. jadi belum break break new1 = jarak(a[-1], delta[ulang]) # loop_pertama: jarak([0,0], [2,5]) = [2,5] a.append(new1) # loop_pertama: a.append([2,5]) = [[0,0], [2,5]] # print(a) b = [] for posisi in a: # assume sumbu = 1 koordinat = posisi[sumbu] # loop_pertama: koordinat = [0,0][1] = 0 b.append(koordinat) # loop_pertama: b = [0] # print(b) return b sumbuX = axis(vector, 0) sumbuY = axis(vector, 1) #==================== PLOT VECTOR =================================== from matplotlib import pyplot as plt """ plt.plot(sumbuX, sumbuY, color='green', marker='o', linestyle='solid') plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.show() """ #========================= VECTOR OPERATIONS ========================================== from typing import List import math Vector = List[float] vector1 = [1,2,3] vector2 = [4,7,9] vector3 = [3,4] vector4 = [8,16] # print("Vector 1 = ", vector1) # print("Vector 2 = ", vector2) # print("Vector 3 = ", vector3) # print("Vector 4 = ", vector4) # Dot def dot(v:Vector, w:Vector) -> float: """ Cek di https://www.mathsisfun.com/algebra/vectors-dot-product.html """ assert len(v) == len(w), "length kedua vector harus sama" return sum(v_i * w_i for v_i, w_i in zip(v,w)) # print("\nVector 1 Dot Vector 2 = ", dot(vector1, vector2)) # 1*4 + 2*5 + 3*6 = 4 + 10 + 18 = 32 # Sum of squares def sum_of_squares(v:Vector) -> float: """ Jumlah dari kuadrat masing-masing elemen vector """ return dot(v, v) # print("Sum of squares dari vector 1 = ", sum_of_squares(vector1)) # Magnitude def magnitude(v:Vector) -> float: """ Panjang vector """ return math.sqrt(sum_of_squares(v)) # print("Panjang vector 3 = ", magnitude(vector3)) # Distance between two vectors def distance(v:Vector, w:Vector) -> float: """ Jarak antar dua vector """ # Kurangi dua vector tersebut: vectorbaru = [] for v_i, w_i in zip(v, w): pengurangan = v_i - w_i vectorbaru.append(pengurangan) # Pakai pythagoras:, pertama, jumlahkan kuadrat vector baru: jumlah = sum_of_squares(vectorbaru) # Akart dari jumlah kuadrat tadi: jarak = math.sqrt(jumlah) return jarak # print("Jarak antara vector 3 dan vector 4 = ", distance(vector3, vector4))
32007a58e18c39c534ab8fc46ddb6bf1388b079c
Kaciras/leetcode
/easy/Q26_RemoveDuplicatesFromSotredArray.py
447
3.6875
4
from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: last, length = None, 0 for n in nums: if last != n: nums[length] = n last = n length += 1 return length if __name__ == '__main__': input_0 = [1, 1, 2] print(str(Solution().removeDuplicates(input_0)) + " " + str(input_0)) input_1 = [0,0,1,1,1,2,2,3,3,4] print(str(Solution().removeDuplicates(input_1)) + " " + str(input_1))
a1b9d0dd64a41d70b26953b83001fb798884b6fb
jmsevillam/Herramientas-Computacionales-UniAndes
/Homework/Hw5/Solution/problem1.py
1,132
3.921875
4
class Dog: def __init__(self,name,posx,posy): self.name=name self.posx=posx self.posy=posy self.awaken=False self.hungry=False self.counter=0 def awake(self): if self.awaken: print(self.name+' is already awaken') else: self.awaken=True print(self.name+' is no longer slept') def move(self,x1,y1): if self.hungry: print(self.name+' is hungry') elif self.awaken: self.posx+=x1 self.posy+=y1 self.counter+=1 else: print(self.name+' is slept') if self.counter>=3: self.hungry=True def feed(self): self.counter=0 self.hungry=False print(self.name+' is no longer hungry') MyDog=Dog('Lambda',0,0) print(MyDog.posx,MyDog.posy) MyDog.move(1,1) MyDog.awake() MyDog.move(1,0) print(MyDog.posx,MyDog.posy) MyDog.move(0,1) print(MyDog.posx,MyDog.posy) MyDog.move(1,1) print(MyDog.posx,MyDog.posy) MyDog.move(1,1) print(MyDog.posx,MyDog.posy) MyDog.feed() MyDog.move(1,0) print(MyDog.posx,MyDog.posy)
4d1ba5f2ebe79eaabcf62c1f1f9c217ae5f57c46
marianac99/Mision-04
/ventaSoftware.py
1,274
3.953125
4
#Mariana Caballero Cabrera A01376544 # Programa que calcule el precio de software aplicando un descuento dependiendo de las unidades que se compren #Calcula el descuento dependiendo de las unidades compradas def calcularDescuento(unidades): descuento = 0 if unidades < 10: descuento = 0 else: if unidades >= 10: descuento = unidades * 1500 * .20 else: if unidades >= 20: descuento = unidades * 1500 * .30 else: if unidades >= 50: descuento = unidades * 1500 * .40 else: if unidades >= 100: descuento = unidades*1500*.50 return descuento #Función princpal def main(): unidades = int(input("Teclea número de paquetes: ")) if unidades > 0: precio = unidades * 1500 descuento = calcularDescuento(unidades) costoTotal = precio - descuento print ("El costo es de: $%.2f" % (precio)) print ("Con un descuento de: $%.2f" %(descuento)) print ("Queda un total de: $%.2f" % (costoTotal)) else: print ("Error, no puedo calcular") # llamamos a la función principal main()
883b552320415f059fbd93a74ebd887ebac8d4ba
SEOULVING-C1UB/Daily-Algorithm
/Daily-Algo/2020-09-01 Stack2/Forth/권기현_forth.py
1,047
3.609375
4
import sys sys.stdin = open('forthinput.txt') def postfix_calculator(postfix): operand_stack=[] try : for i in postfix: if i == '.': result = operand_stack.pop() if operand_stack: return 'error' else: return result elif i == '+': operand_stack.append(operand_stack.pop(-2) + operand_stack.pop()) elif i == '-': operand_stack.append(operand_stack.pop(-2) - operand_stack.pop()) elif i == '*': operand_stack.append(operand_stack.pop(-2) * operand_stack.pop()) elif i == '/': operand_stack.append(int(operand_stack.pop(-2) / operand_stack.pop())) else: operand_stack.append(int(i)) except: return 'error' total_tc = int(input()) for tc in range(1, total_tc+1): postfix = list(input().split()) result = postfix_calculator(postfix) print('#%d '%(tc)+ str(result))
5d448a9c7e65ed382ebe5a2079e84205c5c72a1a
jain-sasuke/guess-the-number
/guess.py
1,699
3.9375
4
from random import randint a = randint(1,100) i = 0 b = 0 #print(a) print ("WELCOME TO GUESS THE NUMBER!") print("I'm thinking of a number between 1 and 100") print("If your guess is more than 10 away from my number, I'll tell you you're in COLD zone") print("If your guess is within 10 of my number, I'll tell you you're in WARM zone") print("If your guess is farther than your most recent guess, I'll say you're getting COLDER") print("If your guess is closer than your most recent guess, I'll say you're getting WARMER") print("LET'S PLAY!") print("If you lose your temper type 'LOSE'") while True: # try and except to take valid input without breaking try: num = input('enter number: ') if num.lower() == 'lose': print(f'The number is {a} YOU LOSE') break num = int(num) if num < 1 or num > 100: print("Out of bound") continue elif num == a: # addding number of guesses. i += 1 print(f'You have guess the number {a} and your guesses are {i}') break # checking for guesses in which zone according to rules. elif i >= 1: if abs(num - a) <= abs(b - a): b = num print('Warmer') i += 1 else : b= num print ('colder') i += 1 else: if abs(num - a) < 10 : b = num print ('Warm') i += 1 else : b = num print ('Cold') i += 1 except: print('Enter valid input') continue
7397236e0699ab3080f3bbe78ddbe2230cb7644c
chrisxue815/leetcode_python
/problems/test_0605.py
648
3.59375
4
import unittest from typing import List import utils # O(n) time. O(1) space. Array. class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: if n <= 0: return True prev = -2 for i, planted in enumerate(flowerbed): if planted: n -= (i - prev - 2) >> 1 if n <= 0: return True prev = i n -= (len(flowerbed) - prev - 1) >> 1 return n <= 0 class Test(unittest.TestCase): def test(self): utils.test(self, __file__, Solution) if __name__ == '__main__': unittest.main()
9b707d4eea3a5b3c734f2303cbcc6d464468a58f
LivInTheLookingGlass/python-go
/Go/stone.py
12,092
3.75
4
class stone(): def __init__(self, color, left=None, right=None, up=None, down=None, board=None, coord=(None, None)): self.color = color if color == 'white': self.opposite_color = 'black' elif color == 'black': self.opposite_color = 'white' self.left = left if left: self.left.right = self self.right = right if right: self.right.left = self self.up = up if up: self.up.down = self self.down = down if down: self.down.up = self self.board = board self.coord = coord def __repr__(self): string = "<" + self.color + " stone:" if self.coord != (None, None): string += " coords=" + str(self.coord) string += " liberties=" + str(self.liberties()) if self.left: string += " left=" + self.left.color if self.right: string += " right=" + self.right.color if self.up: string += " up=" + self.up.color if self.down: string += " down=" + self.down.color return string + ">" def __del__(self): self.cleanup() def neighbors(self): n = [self.left, self.right, self.up, self.down] while n.count(None): n.remove(None) return n def neighboring_enemies(self): n = self.neighbors() remove = [] for stone in n: if stone.color == self.color: remove.append(stone) for stone in remove: n.remove(stone) return n def liberties(self): return 4 - len(self.neighbors()) def connected(self, so_far=[]): conn = so_far + [self] for i in self.neighbors(): if i and i.color == self.color and i not in conn: conn = i.connected(so_far=conn) return conn def all_connected(self, so_far=[]): conn = so_far + [self] for i in self.neighbors(): if i not in conn: conn = i.all_connected(so_far=conn) return conn def thickness(self): return len(self.connected()) def is_captured(self): for i in self.connected(): if i.liberties(): return False return True def capture(self, override=False): if self.is_captured() or override: count = 0 for i in self.connected(): count += 1 if i.board: i.board.__remove__(*i.coord) else: i.__del__() return count return 0 def cleanup(self): if self.left: if self.left.color == "edge": del self.left else: self.left.right = None if self.right: if self.right.color == "edge": del self.right else: self.right.left = None if self.up: if self.up.color == "edge": del self.up else: self.up.down = None if self.down: if self.down.color == "edge": del self.down else: self.down.up = None def empty_neighbors(self): if self.coord == (None, None): self.map_relative_positions() ret = [] if not self.left: ret.append((self.coord[0] - 1, self.coord[1])) if not self.right: ret.append((self.coord[0] + 1, self.coord[1])) if not self.up: ret.append((self.coord[0], self.coord[1] - 1)) if not self.down: ret.append((self.coord[0], self.coord[1] + 1)) return ret def is_capturable(self): if self.num_eyes() >= 2: # Groups with two+ eyes are not capturable return False elif self.board: # Otherwise try asking the board if the capturing placements are suicidal/legal stones = self.connected() tests = set() for stone in stones: for i in stone.empty_neighbors(): tests.add(i) count = 0 for test in tests: try: if not self.board.test_placement(self.opposite_color, test[0], test[1]): count += 1 except: count += 1 return count < 2 else: return True def map_relative_positions(self, first=True, set_origin=True, start_pos=(0, 0)): """When there isn't a board in place, set relative coordinates according to the stone network""" if self.board: # If there's a board, they'll manage this return if first: # First reset the coordinates of all stones for stone in self.all_connected(): stone.coord = (None, None) if set_origin: # Set yourself as the origin self.coord = start_pos if self.left: # If the stone to your left is an edge, make yourself x = 0 if self.left.color == 'edge': self.coord = (0, self.coord[1]) # If the stone to your left has the wrong coordinates, correct it and recurse if self.left.coord != (self.coord[0] - 1, self.coord[1]): self.left.coord = (self.coord[0] - 1, self.coord[1]) self.left.map_relative_positions(first=False, set_origin=False) if self.right: # If the stone to your right has the wrong coordinates, correct it and recurse if self.right.coord != (self.coord[0] + 1, self.coord[1]): self.right.coord = (self.coord[0] + 1, self.coord[1]) self.right.map_relative_positions(first=False, set_origin=False) if self.up: # If the stone above you is an edge, make yourself y = 0 if self.up.color == 'edge': self.coord = (self.coord[0], 0) # If the stone above you has the wrong coordinates, correct it and recurse if self.up.coord != (self.coord[0], self.coord[1] - 1): self.up.coord = (self.coord[0], self.coord[1] - 1) self.up.map_relative_positions(first=False, set_origin=False) if self.down: # If the stone below you has the wrong coordinates, correct it and recurse if self.down.coord != (self.coord[0], self.coord[1] + 1): self.down.coord = (self.coord[0], self.coord[1] + 1) self.down.map_relative_positions(first=False, set_origin=False) if first: # If you were the first, make sure the left and upward edges are 0 leftmost = self upmost = self for stone in self.all_connected(): if leftmost.coord[0] > stone.coord[0]: leftmost = stone if upmost.coord[1] > stone.coord[1]: upmost = stone if leftmost.color != 'edge' and leftmost.coord[0] != 0: # Unless it's already correct... leftmost.map_relative_positions(first=False, set_origin=True, start_pos=(0, leftmost.coord[1])) if upmost.color != 'edge' and upmost.coord[1] != 0: # Unless it's already correct... upmost.map_relative_positions(first=False, set_origin=True, start_pos=(upmost.coord[0], 0)) def num_eyes(self): return len(self.get_eyes()) def get_eyes(self): stones = self.connected() eyes = set() to_check = set() # If you aren't associated with a board, make sure coords are correct if not self.board: self.map_relative_positions() # Collect a list of all empty positions next to/within your grouping for stone in stones: for coord in stone.empty_neighbors(): to_check.add(coord) # For each of the unique candidates, count if they're an eye for coord in to_check: if self.is_eye(coord, stones): eyes.add(coord) return list(eyes) def is_eye(self, coord, stones=None): # Begin setup if not stones: stones = self.connected() right_edge, down_edge = 0, 0 if self.board: # If there's a board, it knows the edges right_edge = self.board.sizex + 2 down_edge = self.board.sizey + 2 else: # Otherwise, map your relative positions self.map_relative_positions() for stone in stones: # Then find the stones farthest to the right and downward if stone.coord[0] > right_edge: right_edge = stone.coord[0] if stone.coord[1] > down_edge: down_edge = stone.coord[1] # Now that we have the coordinates and bounds, grab the eye's neighbors neighbors = [(coord[0] - 1, coord[1]), (coord[0] + 1, coord[1]), (coord[0], coord[1] - 1), (coord[0], coord[1] + 1)] good = [] # Begin checking for i in neighbors: if i in [s.coord for s in stones]: # If there's a connected stone in the neighboring spot, mark the spot as good good.append(i) if len(good) == 4: # If all four are good, it's an eye for sure return True elif len(good) < 2: # If there's fewer than two surrounding stones of the same color, it's for sure not return False else: # Otherwise we need to check edges for i in good: neighbors.remove(i) if len(neighbors) == 2 and (neighbors[0][0] == neighbors[1][0] or neighbors[0][1] == neighbors[1][1]): return False for i in neighbors: # Short version: If the position is not just outside the board, return False # This returns false positives if the stones are not on a board and have no connected edge if i[0] not in range(-1, right_edge + 1) or i[1] not in range(-1, down_edge + 1): return False elif i[0] in range(0, right_edge) and i[1] in range(0, down_edge): return False return True def can_be_uncapturable(self, moves, passed_board=None, silent=False): """Serially brute forces every combination of moves up to x to see if a group can be made uncapturable Warning: This is blocking, and can take a long time at depths >= 4 Warning: This makes a copy of the board for each level of depth""" if not passed_board: # Inherit the object's board passed_board = self.board if not passed_board: # If the object has no board... raise ValueError("You can't call this without an associated board") if not passed_board[self.coord].is_capturable(): # If the current configuration is uncapturable, you're done if not silent: print(passed_board) return True if moves > 0: # If you have moves left, recurse for every move to a direct neighbor from .board import board coords = set() for s in passed_board[self.coord].connected(): for coord in s.empty_neighbors(): coords.add(coord) for coord in coords: b = board.from_history(passed_board.move_history) try: b.place(self.color, coord[0], coord[1], turn_override=True) except: return False if self.can_be_uncapturable(moves - 1, b, silent): return True # Otherwise return False return False
f2328184b234a87a3fd33a15ed7fc1ea96cc4eea
sangeethadetne/python
/List.py
818
4.0625
4
lucky_numbers = [4,64,7,76,35,55,] friends = ["John","Shawn","Shandy","Toby","Shandy","Shandy"] friends.extend(lucky_numbers)# add the list to another list friends.append("Sangeetha")# add the elements to the list friends.insert(3,"Geetha")# Inserts the elemenst at specified position friends.remove("Shandy") lucky_numbers.sort() print(lucky_numbers) print(friends) friends.reverse() print(friends) friends2=friends.copy() print("The friends2 list is : " + str(friends2)) print("The index of the element is : " + str(friends.index("Shawn"))) print("The popped element is : " + friends.pop()) print("The count of the word from the list : " + str(friends.count("Shandy"))) #friends.clear()# clear the elements from the list print(friends[1:3]) print(friends[1]) #print([2:]) print(friends[2:])
c66decef915c66471943540e932f8b792cc58f8c
AntonBrazouski/thinkcspy
/12_Dictionaries/12_03c.py
308
4.0625
4
# dictionary methods inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print(list(inventory.values())) print(list(inventory.items())) for (k, v) in inventory.items(): print("Got", k, "that maps to", v) for k in inventory: print("Got", k, "taht maps to", inventory[k])
aea008976cc88f6440a638929cfe7b1b67b2f0c4
acpark22/daily_challenges
/louis/1/i.py
2,075
4.59375
5
""" [intermediate] challenge #1 create a program that will allow you to enter events organizable by hour. There must be menu options of some form, and you must be able to easily edit, add, and delete events without directly changing the source code. (note that by menu i dont necessarily mean gui. as long as you can easily access the different options and receive prompts and instructions telling you how to use the program, it will probably be fine) """ def displaySchedule (): print "H: Event" for time, event in events.items(): print "%s: %s" % (time, event) def addEvent (): time = raw_input("Enter a time the event will take place: ") event = raw_input("Enter the name of the event to add: ") events[time] = event def editEvent (): displaySchedule() hour = raw_input("Enter the hour of the event you'd like to edit: ") change = raw_input("Would you like to change the time or event? enter 'time' or 'event': ") if change == 'time': newHour = raw_input("Enter the new time for this event: ") events[newHour] = events[hour] del events[hour] elif change == 'event': newEvent = raw_input("Enter the new event for this hour: ") events[hour] = newEvent print "Change is made, here is the new schedule:" displaySchedule() def deleteEvent (): displaySchedule() hour = raw_input("Enter the hour of the event you'd like to delete: ") if hour in events: del events[hour] print "New schedule:" displaySchedule() else: print "No events take place in that hour." # START HERE # initialize variables events = { '2' : 'appointment', '5' : 'dinner', '9' : 'date' } menu = "Welcome to Events Organizer!\nYou can 'add', 'edit', 'delete', or 'view' events by typing the action, or type 'exit' to quit:\n" options = {'add' : addEvent, 'edit' : editEvent, 'delete' : deleteEvent, 'view' : displaySchedule } choice = '' # Menu while choice != 'exit': choice = raw_input(menu) options.get(choice, lambda: None)()
00dfaf61555b394cab271f7a13188071d7b5cdcd
ssarangi/algorithms
/epi/primitive_types/5_3_convert_base.py
1,570
3.609375
4
""" The MIT License (MIT) Copyright (c) <2015> <sarangis> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ """ Write a function that performs base conversion. Specifically, the input is an integer base b1, a string s, representing an integer x in base b1, and another integer base b2; the output is the string representing the integer x in base b2. Assume 2 <= b1, b2 <= 16. Use 'A' to represent 10, 'B' for 11, ... and 'F' for 15 """ def convert_base(int_b1, b1, b2): pass def main(): int_b2 = convert_base("314", 10, 16) print(int_b2) if __name__ == "__main__": main()
b32fd9516002b2a6de870b756c21c73a7040cc66
mahimadubey/leetcode-python
/add_binary/solution3.py
968
3.625
4
""" Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". """ class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ a = a[::-1] b = b[::-1] m = len(a) n = len(b) i = 0 c = 0 res = ['0' for _ in range(max(m, n) + 1)] while i < m or i < n or c > 0: tmp = c if i < m: tmp += int(a[i]) if i < n: tmp += int(b[i]) bit = tmp % 2 c = tmp / 2 res[i] = str(bit) i += 1 res = res[::-1] for i, c in enumerate(res): if c != '0': res = res[i:] break else: res = ['0'] return ''.join(res) s = Solution() print s.addBinary('11', '1') print s.addBinary('111', '0010')
58604ef760280489bdcaf8d87899bf171545d5d5
DeborahPerez/CrackingTheCodingInterviewPython37
/unique.py
2,313
4.0625
4
############################################################################### # USAGE: # python3.7 isUnique.py # DESCRIPTION: # 1.1 Is Unique # Implement an algorithm to determine if a string has all unique # characters. # Input: # String # Output: # Boolean # ----------------------------------------------------------------------------- # CREATED BY: Deborah Perez # VERSION: 20190315 ############################################################################### # 1.1 Is Unique # Implement an algorithm to determine if a string has all unique # characters. # Comment the section below to test the solution without additional data # structures ############################################################################### import unittest from collections import Counter def isUnique(string): if len(string) > 128: return False c = Counter() for char in string: c.update(char) if c[char] > 1: return False return True ############################################################################### # What if you cannot use additional data structures? # Comment the above block and uncomment the block below to test the solutions # without additional data structures ############################################################################### # import unittest # # def isUnique(string): # if len(string) > 128: # return False # # uniqueList = [] # for char in string: # ordChar = ord(char) # if ordChar in uniqueList: # return False # uniqueList.append(ordChar) # return True ############################################################################### class Test(unittest.TestCase): test_T = [('abcdefg'), ('5679asdf'), (' ')] test_F = [('dsadsadafasfsa'), ('dsadsa356u7hhaaa'), ('#$%^fdsfs##$')] def test_unique(self): for test in self.test_T: answer = isUnique(test) self.assertTrue(answer) for test in self.test_F: answer = isUnique(test) self.assertFalse(answer) if __name__ == "__main__": unittest.main()
639e743d95636e20520455551f36aea7f8aa682e
ricwtk/misc
/202003-ai-labtest-results/Submissions/17003906.py
2,659
4.03125
4
""" Lab Test (AI CSC3206 Semester March 2020) Name: Leong Wen Hao Student ID: 17003906 """ import pandas as pd from sklearn import datasets import matplotlib.pyplot as pt # import glass.csv as DataFrame data = pd.read_csv("glass.csv", names=["Id", "RI", "Na", "Mg", "Al", "Si", "K", "Ca", "Ba", "Fe", "Glass type"], index_col=0) ''' Instructions 1. split the data into 70% training and 30% testing data - use Na, Mg, Al, Si, K, Ca, Ba, and Fe (i.e. all columns except Glass type) as the input features. - use Glass type as the target attribute. 2. plot the accuracy of knn classifiers for all odd value of k between 3 to 100, i.e. k = 3, 5, 7, ..., 100. This is achieved by fulfilling the following tasks: i. create a loop to A. fit the training data into knn classifiers with respective k. B. calculate the accuracy of applying the knn classifier on the testing data. C. print out the accuracy for each k. ii. plot a line graph with the y-axis being the accuracy for the respective k and x-axis being the value of k. You DO NOT need to save the graph. ''' # start your code after this line attribute_columns = ["Na", "Mg", "Al", "Si", "K", "Ca", "Ba", "Fe"] target_columns = ["Glass type"] data = { 'attributes': pd.DataFrame(data, columns = attribute_columns), 'target': pd.DataFrame(data, columns = target_columns) } #split the data for test and train from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(data['attributes'], data['target'], test_size=0.3) data['train'] = { 'attributes': x_train, 'target': y_train } data['test'] = { 'attributes': x_test, 'target': y_test } from sklearn.neighbors import KNeighborsClassifier knc = KNeighborsClassifier(5) input_columns = data['attributes'].columns[:2].tolist() x_train = data['train']['attributes'][input_columns] y_train = data['train']['target'] knc.fit(x_train, y_train) x_test = data['test']['attributes'][input_columns] y_test = data['test']['target'] y_predict = knc.predict(x_test) k_values = [] accuracies = [] start = 3 stop = 100 step = 2 for k in range(start, stop, step): k_values.append(k) knc = KNeighborsClassifier(k) knc.fit(x_train, y_train) accuracy = knc.score(x_test, y_test) accuracies.append(accuracy) print("\nK: {} \nAccuracy: {}".format(k, accuracy)) pt.figure() pt.plot(k_values, accuracies) #labels pt.xlabel("k") pt.ylabel("accuracy") pt.title("accuracy vs k") pt.show()
e368ddf25aeb3e4b9be7e164159beab2e46c07b9
KindleHsieh/OOP_book_practice
/test.py
683
3.828125
4
class ContactList(list): def search(self, name): matching_contacts = [] for contact in self: if name in contact.name: matching_contacts.append(contact) return matching_contacts class Contact: all_contacts = [] def __init__(self, name, email): self.name = name self.email = email self.all_contacts.append(self) c1 = Contact("John A", "JJA.net") c2 = Contact("John B", "JJB.net") c3 = Contact("Jean A", "JeC.net") print( # [contact.name for contact in Contact.all_contacts.search('John')] [contact.name for contact in Contact.all_contacts if 'John' in contact.name] ) a = 1 print( dir(a) )
65615746f0d749f4f973b74a3dae8db2fbb3c003
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3999/codes/1635_1053.py
310
3.828125
4
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigir seu código. nome=input() if(nome=="cervo"): mensagem="cervo eh patrono do Harry Potter" else: mensagem= nome + " nao eh patrono do Harry Potter" print(mensagem)
6ee5d13936c0f734d8a865143abf75516278cd6e
sudhi76/data-analysis
/linearregg.py
1,232
3.671875
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 4 22:29:22 2019 @author: DELL """ #importing libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #importing the dataset df = pd.read_csv('Salary_Data.csv') x = df.iloc[:,:-1].values y = df.iloc[:,:1].values #spliting the dataset into training set and test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 1/3, random_state = 0) #fitting simple lenear reggresion to train set from sklearn.linear_model import LinearRegression regg = LinearRegression() regg.fit(X_train, y_train) #predicting the test result y_predict = regg.predict(X_test) #visualizing the training set plt.scatter(X_train, y_train, color= 'red') plt.plot(X_train, regg.predict(X_train), color= 'blue') plt.title('salary vs experience(training set)') plt.xlabel('years of experience') plt.ylabel('salary') plt.show() #visualizing the test set plt.scatter(X_test, y_test, color= 'red') plt.plot(X_test, regg.predict(X_train), color= 'blue') plt.title('salary vs experience(test set)') plt.xlabel('years of experience') plt.ylabel('salary') plt.show()
0d270bc70a7f87849cd883666ebf2783b7cfb6a6
YoungXueya/LeetcodeSolution
/src/113. Path Sum II.py
819
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if not root: return [] res=[] path=[root.val] self.helper(root,path,sum-root.val,res) return res def helper(self,root,path,sum,res): # print(root.val,path) if not root.left and not root.right and sum==0: res.append(path) return if root.left: # print(curPath) self.helper(root.left,path+[root.left.val],sum-root.left.val,res) if root.right: self.helper(root.right,path+[root.right.val],sum-root.right.val,res)
51ab9add6264d68996a00d8c3f5545f40377ca4b
PramodShenoy/Competitive-Coding
/Hackerrank/Code-Heat/card.py
642
3.5625
4
def subset_sum(numbers, target, partial=[], partial_sum=0): if partial_sum == target: yield partial if partial_sum >= target: return for i, n in enumerate(numbers): remaining = numbers[i + 1:] yield from subset_sum(remaining, target, partial + [n], partial_sum + n) cards = list(map(int, input().split(' '))) cards.sort() score = 0 score +=len(list(subset_sum(cards,15))) from collections import Counter a = dict(Counter(cards)) import math def nCr(n,r): f = math.factorial return f(n) / f(r) / f(n-r) for i, j in a.items(): if j>1: score+=nCr(j,2) print(int(score))
23d644e8e6fc486ad64b254266b5dca0a452b8c2
vrrp/Workshop2018Python
/Modulo1/proyectos/fibo.py
330
3.890625
4
# Módulo de números Fibonacci def fib(n): a,b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print("se ejecuto fib") def fib2(n): a,b = 0, 1 resultado = [] while b < n: resultado.append(b) a, b = b, a+b print(resultado) return resultado if __name__ == "__main__": import sys fib2(int(sys.argv[1]))
17187d5cb148361d83e1e5957f9c886d54ee1c7e
ammar-assaf/Assignment2
/Logic-1/date_fashion.py
134
3.796875
4
def date_fashion(you, date): if date<=2 or you<=2: return 0 elif date >=8 or you >=8: return 2 else: return 1
bf0fa5169c55b45d38fde41c8f26f750187e4e50
YQ-7/code-interview-guide
/c5_string/trie.py
2,327
3.953125
4
import unittest class TreeNode(object): """ 搜索树节点,存储a~z """ def __init__(self): self.path = 0 # 记录元素 self.end = 0 self.map = [None] * 26 class Trie(object): """ 搜索树 """ def __init__(self): self.root = TreeNode() def insert(self, word): """ 插入元素work """ if word is None: return node = self.root node.path += 1 for c in word: index = ord(c) - ord('a') if node.map[index] is None: node.map[index] = TreeNode() node = node.map[index] node.path += 1 node.end += 1 def search(self, word): """ 判断word是否存在 """ if word is None: return False node = self.root for c in word: index = ord(c) - ord('a') if node.map[index] is None: return False node = node.map[index] return node.end != 0 def delete(self, word): """ 删除work,有多个时只删除一个 """ if not self.search(word): return node = self.root for c in word: index = ord(c) - ord('a') node.map[index].path -= 1 if node.map[index].path == 0: node.map[index] = None return node = node.map[index] node.end -= 1 def prefix_number(self, pre): """ 统计以pre为前缀的元素个数 """ if pre is None: return 0 node = self.root for c in pre: index = ord(c) - ord('a') if node.map[index] is None: return 0 node = node.map[index] return node.path class MyTestCase(unittest.TestCase): def test_trie(self): trie = Trie() self.assertFalse(trie.search("abc")) trie.insert("abc") trie.insert("abcd") trie.insert("b") self.assertTrue(trie.search("abc")) trie.insert("b") trie.delete("b") self.assertTrue(trie.search("b")) trie.delete("b") self.assertFalse(trie.search("b")) if __name__ == '__main__': unittest.main()
5b9e36ef2de411d02b83cc8c4c597aad4e26d71c
Jigar710/Python_Programs
/Matplotlib/with_pandas/p2.py
377
3.875
4
''' with dataframe bar plots group the values in each row together in a group in bars, side by side, for each value''' from matplotlib import pyplot as plt import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(6,4), index = ['one','two','three','four','fifth','sixth'], columns = pd.Index(['A','B','C','D'],name='Genus')) print(df) df.plot.bar() plt.show()
b40c682fd49d588029b81d5df9a70a5a5f876138
Ashoksugu7/DSA
/Leetcode/Thousand_Separator.py
704
3.734375
4
""" Thousand Separator User Accepted:0 User Tried:0 Total Accepted:0 Total Submissions:0 Difficulty:Easy Given an integer n, add a dot (".") as the thousands separator and return it in string format. Example 1: Input: n = 987 Output: "987" Example 2: Input: n = 1234 Output: "1.234" Example 3: Input: n = 123456789 Output: "123.456.789" Example 4: Input: n = 0 Output: "0" Constraints: 0 <= n < 2^31 """ class Solution: def thousandSeparator(self, n: int) -> str: beg=str(n) for i in range(len(beg)-3,0, -3): print(i) beg=beg[:i]+"."+beg[i:] print(beg) return beg obj = Solution() print(obj.thousandSeparator(1234567))
1963fae6757386a237aa54ecca1edb4640b0c206
Victor-GuilhermeCN/LibrarySystem
/db.py
2,178
3.71875
4
import pymysql class Databank: def __init__(self): """This function starts the Databank class""" self.con = pymysql.connect(user='root', passwd='') self.cursor = self.con.cursor() def database(self): """This method creates the database, and selects it.""" try: self.cursor.execute('CREATE DATABASE library') except Exception as error: print(error) else: self.cursor.execute('USE library') print('Database created successfully!') def connection(self): """This method connect with the database, after the database has been created!""" try: self.cursor.execute('USE library') except Exception as error: print('Unsuccessful connection') def table_books(self): """This method creates the books table in the library database.""" try: self.connection() self.cursor.execute('CREATE TABLE IF NOT EXISTS books (id_books int(10) PRIMARY KEY AUTO_INCREMENT, title ' 'varchar(255) not null, author varchar(255) not null, price decimal(10,2), bar_code ' 'varchar(13), stock int(10))') except Exception as error: print(error) else: print('Table Created successfully!') def table_client(self): """This method creates the client table in the library database.""" try: self.connection() self.cursor.execute('CREATE TABLE IF NOT EXISTS client (cpf varchar(11) PRIMARY KEY, name varchar(255) ' 'not null, last_name varchar(255) not null, birth_date date, password varchar(16))') except Warning as error: print(error) else: print('Created Successfully') def create_db(self): self.database() self.connection() self.table_books() self.table_client() if __name__ == '__main__': db = Databank() # db.create_db() # db.create_table() # db.verify_connection() db.connection() # db.table_client()
cb132d73d5ef2e32f2eea86bf2ded2641137a9d3
subashinie/my_captain_assignment2
/dictionary.py
589
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Aug 20 12:48:38 2021 @author: suba """ car={"brand":"ferrari", "horsepower":"812", "torque":"718Nm", "year":"2021"} a=car.copy() print(a) x=('Ford','BMW','RR') y='5' cars=dict.fromkeys(x,y) print(cars) X=car.get("torque") print(X) Y=car.items() print(Y) m=car.keys() print(m) car.pop("year") print(car) car.popitem() print(car) M=car.setdefault("oil","petrol") print(M) print(car) car.update({"clutch":"auto"}) print(car) N=car.values() print(N) car.clear() print(car)
3987695eb8fb31dff3ec8f128f40909cb5b144a8
tekiegirl/SafariPython
/main.py
1,027
4.03125
4
print("Hello Python World!") print('"Hello" Python World!', 99, "is the count", sep="**", end="") print("next") x = "123" print(x) print(type(x)) print(x + str(99)) print(int(x) + 99) x = 99 print(x) print(type(x)) x = 12.34 print(x) print(type(x)) # IEEE 754, 64bit E+-308 x = 1000000000 print(x) x = x * x * x * x * x * x * x * x * x print(x) # int type has "unbounded" range # x = 1000000000 # x = x ** x # Takes WAY too long!!! print("hello again") x = 99 print(f" the value is {x + 3}") print(3 < 4) print(type(3 < 4)) print(bool(99)) x = 10 y = 10 print(x == y) print(x != y) x = "Hello" # y = "He" # y += "llo" y = "Hello" print(x) print(y) print(x == y) # __eq__ method "dunder" method i.e. "double underscore" print(x is y) x = None print(x) print(type(x)) z = None print("z is", z) del z # print("z is", z) # can't do this any more! print(3 / 4) # / is floating point!!! print(3 // 4) # // is int type division print(-7 % 3) # % is MODULUS, not REMAINDER (differ with negative numbers)
0c963837e0b9bca82b325edc2ebbb3c36b192f67
BuiltinCoders/PythonTutorial
/oops concept practice/operator overloading & dunder methods.py
1,318
4.46875
4
# Defining a method for an operator and that process is called operator overloading. # Operator overloading refers to setting up the functionality of perticular operator for perticular situation. # Operator in python can be overloaded using dunder method. # These methods are called when a given operator is used on the objects. class Employee: no_of_employee = 8 def __init__(self, name, salary, role): self.name = name self.salary = salary self.role = role def printdetails(self): return f"Employee name is {self.name}, his salary is {self.salary} and his role is {self.role}" def __add__(self, other): return self.salary + other.salary def __truediv__(self, other): return self.salary / other.salary def __sub__(self, other): return self.salary - other.salary def __repr__(self): return f"Employee('{self.name}',{self.salary}, '{self.role}')" def __str__(self): return f"Employee name is {self.name}, his salary is {self.salary} and his role is {self.role}" emp1 = Employee("harry", 346, "programmer") emp2 = Employee("rohan", 563, "tester") # print(emp1.printdetails()) print(emp1 + emp2) print(emp2 / emp1) print(emp1 - emp2) print(str(emp1)) print(repr(emp1)) print(emp1.__str__())
bf704913638de1851f89c56d5703458e8c240540
sanket17/python_basic
/conditionalStat.py
161
3.953125
4
lang = 'Python' print(lang) if lang == 'C': print('C Language') elif lang == "Python": print('Python Language') else: print('Programming is great')
7a4bf2bc945c0a0a57c9fb2df372d394c6f2589a
informramiz/Route-Planner
/astar/student_code.py
2,681
3.5625
4
import math import math from queue import PriorityQueue from helpers import Map def shortest_path(M: Map, start, goal): if start == goal: return [start] intersections_count = len(M.intersections) is_frontier = [False for _ in range(intersections_count)] is_explored = [False for _ in range(intersections_count)] g_distance = [math.inf for _ in range(intersections_count)] h_distance = [euclidean_distance(M, i, goal) for i in range(intersections_count)] priority_queue = PriorityQueue() priority_queue.put_nowait((0, start)) is_frontier[start] = True g_distance[start] = 0 parent = {start: None} while priority_queue.qsize() > 0: node_f, node = priority_queue.get_nowait() if is_explored[node]: continue is_explored[node] = True if node == goal: path = build_path(parent, start, goal) return path # add neighbors to frontiers add_frontiers(M, node, g_distance, h_distance, is_frontier, is_explored, priority_queue, parent) def add_frontiers(M: Map, node, g_distance, h_distance, is_frontier, is_explored, priority_queue, parent): for neighbor in M.roads[node]: # ignore explored nodes if is_explored[neighbor]: continue # calculate cost of path from start to this neighbor g_distance_of_neighbor = g_distance[node] + euclidean_distance(M, node, neighbor) # now use heuristic estimation and path of covered cost to get an idea of path cost to goal f = g_distance_of_neighbor + h_distance[neighbor] if not is_frontier[neighbor]: is_frontier[neighbor] = True g_distance[neighbor] = g_distance_of_neighbor # neighbor has not be visited before priority_queue.put_nowait((f, neighbor)) # keep track of it's parent parent[neighbor] = node else: # neighbor has been visited before, check if new path is low cost if g_distance_of_neighbor < g_distance[neighbor]: g_distance[neighbor] = g_distance_of_neighbor parent[neighbor] = node priority_queue.put_nowait((f, neighbor)) def build_path(parent, start, goal): path = [goal] current_parent = parent[goal] while current_parent != start: path.append(current_parent) current_parent = parent[current_parent] path.append(start) path.reverse() return path def euclidean_distance(M: Map, p1: int, p2: int): x1, y1 = M.intersections[p1] x2, y2 = M.intersections[p2] return math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))
05f734d4d17962e6ff9ff4ca11b4b6e3794c47e6
connorKeir/cp1404practicals
/prac_05/hex_colours.py
714
4.25
4
HEX_COLOURS = { "aliceblue": "#f0f8ff", "aquamarine1": "#7fffd4", "black": "#000000", "blue2": "#0000ee", "chartreuse1": "7fff00", "coral": "#ff7f50", "cornsilk3": "#cdc8b1", "cyan1": "#00ffff", "darkgoldenrod": "#b8860b", "darkviolet": "#9400d3" } def main(): """search for hex-code by colour name.""" colour_name = input("Enter a colour name: ").lower() while colour_name != '': if colour_name in HEX_COLOURS: print("{}'s hex-code is {}".format(colour_name, HEX_COLOURS[colour_name])) else: print("There is no hex-code for {}".format(colour_name)) colour_name = input("Enter a colour name: ").lower() main()
334d3ff75a8e3c9a7cf76a429309cd7ecf37fdbb
ruidge/TestPython
/Test/tips.py
382
3.734375
4
#格式化 print('Age: %s. Gender: %s' % (25, True)) r = 2.5 s = 3.14 * r ** 2 print(f'The area of a circle with radius {r} is {s:.2f}') #if的判断 x = 0 # x = "" # x = None # x = 'None' # x = -1 if x: print('True') else: print('False') #for的判断 sum = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum + x print(sum) if __name__ == '__main__': print()
19bec2ede7abe5a1498f327d6549f6d149a53e84
TomasBalbinder/Projekty
/natural_numbers.py
841
4.15625
4
''' Create a program who writte how many units, tens, hundreds and thousands make up the nubmer on the input input: natural number output: numbers of units, tens, hundreds, thousands 1. read input value 2. calculation 3. output ''' natural_numbers = int(input("Enter the number: ")) output = natural_numbers ten_thousands = output // 10000 residue = output % 10000 print("You get: %.0f" % ten_thousands,"ten thousands") thousands = residue // 1000 residue = output % 1000 print("You get: %.0f " % thousands,"thousands") hundreds = residue // 100 residue = output % 100 print("You get: %.0f " % hundreds,"hundreds") tens = residue // 10 residue = output % 10 print("You get: %.0f " % tens,"tens") units = residue // 1 residue = output % 1 print("You get: %.0f " % units,"units")
59c5c9c8385bde699eb12b9506176e6065fdbb4f
ankit-rane/Travel-Hack
/ticket-booking.py
2,349
4.09375
4
global f f = 0 # this t_movie function is used to select movie name def t_movie(): global f f = f + 1 print("which country do you want to visit?") print("1. India ") print("2 The United States of America ") print("3. The United Kingdom") print("4 Back") movie = int(input("choose your country: ")) if movie == 4: center() theater() return 0 if f == 1: theater() # this theater function used to select screen def theater(): print("which transport do you wish to go by: ") print("1. Flight") print("2. Cruise") a = int(input("choose your screen: ")) ticket = int(input("number of ticket do you want?: ")) timing(a) # this timing function used to select timing for movie def timing(a): time1 = { "1": "10.00", "2": "1.10", "3": "4.20", "4": "7.30" } time2 = { "1": "10.15", "2": "1.25", "3": "4.35", "4": "7.45" } if a == 1: print("choose your time:") print(time1) t = input("select your time:") x = time1[t] print("successfull!, enjoy the journey " + x) elif a == 2: print("choose your time:") print(time2) t = input("select your time:") x = time2[t] print("successfull!, enjoy the journey " + x) return 0 def movie(theater): if theater == 1: t_movie() elif theater == 2: t_movie() elif theater == 3: t_movie() elif theater == 4: city() else: print("wrong choice") def center(): print("which flight do you wish to travel with? ") print("1. Jet airways") print("2. Qatar") print("3. Lufthansa") print("4. Back") a = int(input("choose your option: ")) movie(a) return 0 # this function is used to select city def city(): print("Hi welcome to travel ticket booking: ") print("where you want to travel?:") print("1. Mumbai") print("2. New York") print("3. London") place = int(input("choose your option: ")) if place == 1: center() elif place == 2: center() elif place == 3: center() else: print("wrong choice")
c1fdfbed8315f7d91fbd700a4180eaedabf56713
leigh93/100daysofPython
/day25/theory.py
1,560
3.953125
4
import csv # with open('weather_data.csv') as file: # data = file.readlines() # print(data) # with open('weather_data.csv') as data_file: # data = csv.reader(data_file) # print(data) # temperatures = [] # new_list = [] # for row in data: # if row[1] != 'temp': # temperatures.append(int(row[1])) # temperatures.pop(0) # print(temperatures) # PANDAS is designed for use with csv files import pandas as pandas data = pandas.read_csv('weather_data.csv') print(data) print(type(data)) #dataframe print(data['temp']) print(type(data['temp'])) #Series # convert data to dictionary consult documentation for these methods # data_dict = data.to_dict() # print(data_dict) # # temp_list = data['temp'].to_list() # print(temp_list) # average_temp = sum(temp_list) / len(temp_list) # print(average_temp) # # print(data['temp'].mean()) # print(data['temp'].max()) # # # Get Data in columns # print(data['condition']) # print(data.condition) # # these are the same # # # Get Data in Rows # monday = data[data.day == 'Monday'] # print(data[data.day == 'Monday']) # print((monday.temp * 9/5) + 32) # # (0°C × 9/5) + 32 # hottest_temp = data['temp'].max() # hottest_temp = data.temp.max() # hottest_day = data[data['temp'] == hottest_temp] # hottest_day.day # print(hottest_day) # print(hottest_day.condition) # Create a dataframe from scratch data_dict = { 'students': ['Amy', 'James', 'Angela'], 'scores': [76, 56, 65] } data = pandas.DataFrame(data_dict) print(data) data.to_csv('new_data.csv')
8963f474badec9e241792169c167d28123ea0495
joshf26/CU-Boulder-Computer-Graphics-Club-Image-Compression-Talk
/image_helper.py
4,432
3.640625
4
import PIL.Image import PIL.ImageDraw import PIL.ImageFont # Note: This was only tested on Ubuntu 18.04. You may have to modify this to # point to an existing font file. FONT_PATH = '/usr/share/gazebo-9/media/fonts/arial.ttf' FONT = PIL.ImageFont.truetype(FONT_PATH, 32) def convert_to_image(path): """ Given a path to an jpeg, png, or any other format that PIL supports, return an instance of the Image class defined below that stores that image. """ image = PIL.Image.open(path) pixels = image.load() result = Image(image.size) for x in range(image.size[0]): for y in range(image.size[1]): result[x][y].r = pixels[x, y][0] result[x][y].g = pixels[x, y][1] result[x][y].b = pixels[x, y][2] return result class Size: """ Stores an width and height, which is easier than having to access indexes of a tuple. """ def __init__(self, width, height): self.width = width self.height = height @property def as_tuple(self): return self.width, self.height class Pixel: """ Stores RGB values representing a pixel, which is easier than having to access indexes of a tuple. """ def __init__(self, r_or_iter, g=None, b=None): # The first parameter can optionally be an iterable holding all three # values. if isinstance(r_or_iter, int): self.r = r_or_iter self.g = g self.b = b else: self.r = r_or_iter[0] self.g = r_or_iter[1] self.b = r_or_iter[2] @property def as_tuple(self): return self.r, self.g, self.b class Image: """ The main wrapper class around PIL's Image class. Accessing pixels is much easier since you can subscript an instance. """ def __init__(self, path_or_size=(500, 500)): # If the parameter is a path, open the file and read in the pixels. if isinstance(path_or_size, str): with open(path_or_size) as file: self.pixels = [[Pixel(list(map(int, pixel.split(',')))) for pixel in line.strip().split('|')] for line in file] # If the parameter is a `Size`, create a black image of that size. elif isinstance(path_or_size, Size): self.pixels = [[Pixel(0, 0, 0) for _ in range(path_or_size.width)] for _ in range(path_or_size.height)] # Else, assume it is an iterable containing size information, and create # a black image of that size. else: self.pixels = [[Pixel(0, 0, 0) for _ in range(path_or_size[0])] for _ in range(path_or_size[1])] if len(self.pixels) == 0 or len(self.pixels[0]) == 0: raise Exception('Cannot create an image with width or height 0.') def __getitem__(self, index): return self.pixels[index] def __str__(self): return str(self.pixels) @property def size(self): return Size(len(self.pixels), len(self.pixels[0])) def show(self, title, scale=1): """ Displays the image in a popup window. """ # Convert the image to a PIL Image. image = PIL.Image.new('RGB', self.size.as_tuple) pixels = image.load() for x in range(self.size.width): for y in range(self.size.height): pixels[x, y] = self.pixels[x][y].as_tuple # Scale the image. image = image.resize(( self.size.width * scale, self.size.height * scale, )) # Add the title text. draw = PIL.ImageDraw.Draw(image) draw.text((15, 15), title, (255, 0, 0), font=FONT) # Call PIL to display the image. image.show() def save(self, path): """ Save the image as a `.image` file (plaintext). """ # Convert the data to a string. data = '' for x in range(self.size.width): for y in range(self.size.height): data += ','.join(map(str, self.pixels[x][y].as_tuple)) if not y == self.size.height - 1: data += '|' if not x == self.size.width - 1: data += '\n' # Write the string to the file. with open(path, 'w') as file: file.write(data)
1a4f848078b71002fc49023e03238a120ada1e30
ilee38/practice-python
/coding_problems/CTCI_sorting_searching/group_anagrams.py
551
3.9375
4
#!/usr/bin/env python3 """ Problem 10.2 from CtCI book """ def group_anagrams(A): if len(A) == 0 or A is None: return None word_map = {} key = '' for word in A: key = ''.join(sorted(word)) #the sorted() built-in function returns a list, so if key not in word_map: #it needs to be converted to str in order to be hashable (for the dict) word_map[key] = [word] else: word_map[key].append(word) index = 0 for k in word_map.keys(): for v in word_map[k]: A[index] = v index += 1 return A
735a43a3a66b7c4ca13f225f080a8618fb8d8604
maxbergmark/old-work
/Egna projekt/Bella/read_word.py
249
3.90625
4
f=open("ordlista.txt","r") s=f.read() l=s.split("\n") avg=(len(s))/(len(l)) print(len(l),avg) total_letters=0 for word in l: total_letters+=len(word) avg2=total_letters/(len(l)) print(avg2) print(sum([len(word) for word in l])/len(l))
c3464cb644fef6d9e179afe13c8e13e9145d91a7
jbbarrau/problems
/balls/balls.py
1,504
4.0625
4
# http://www.careercup.com/question?id=5145121580384256 # n is the number of balls (n = 3^d) # Time: O(log n) - Space: O(n) class BallSet: def __init__(self,ballset): #ballset is list of 81 weights #the index is the identifier of the ball # 81 = 3 * 3 * 3 * 3 self.pickedlist = [] listlength = len(ballset) inputlist = ballset while listlength != 1: listlength = listlength/3 firstpart = inputlist[0:listlength] secondpart = inputlist[listlength:2*listlength] thirdpart = inputlist[2*listlength:3*listlength] remaininglist, listnumber = self.minimumweight(firstpart,secondpart,thirdpart) self.pickedlist.append(listnumber) inputlist = remaininglist def GetBallId(self): multiplier = 27 index = 0 for i in self.pickedlist: index += i * multiplier multiplier /= 3 return index def minimumweight(self,a,b,c): # a,b,c are sublists: We use the fact that 2 of the lists of the same weight whereas one is lighter if self.sum(a) < self.sum(b): return (a,0) elif self.sum(b) < self.sum(c): return (b,1) elif self.sum(c) < self.sum(a): return (c,2) def sum(self,list): totalWeight = 0 for weight in list: totalWeight += weight return totalWeight
d440e2fec4521eef14d6129a17a0f3659ebcd0ca
britannica/euler-club
/Week5/euler5_sbosco.py
707
3.640625
4
# euler 5 from functools import reduce def primes(n): primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) n //= d d += 1 if n > 1: primfac.append(n) return primfac def insertprimes(allfacs, primfacs): for j in allfacs: # print('j',j, primfacs) try: primfacs.remove(j) except: pass allfacs = allfacs + primfacs # print ('A', primfacs, allfacs) return allfacs allfacs = [] for i in range(2, 21): primfacs = primes(i) allfacs = insertprimes(allfacs, primfacs) # print (i, primfacs, allfacs) print(reduce(lambda x, y: x*y, allfacs))
784cefab02bc27c36acf866e2b1466c2839290c1
gaurav613/Pygames
/CarRacing/main.py
7,093
3.53125
4
import pygame import time, random pygame.init() #basic window creation - width and height for dynamic reference display_width =800 display_height = 600 #rgb color codes BLACK = (0,0,0) WHITE = (255,255,255) GREEN = (0,200,0) RED = (200,0,0) LIGHT_RED = (255,0,0) LIGHT_GREEN = (0,255,0) GREY = (119,136,153) PURPLE = (255,0,255) #text sizes smallText = pygame.font.Font('freesansbold.ttf', 20) mediumText = pygame.font.Font('freesansbold.ttf', 30) largeText = pygame.font.Font('freesansbold.ttf',60) gameDisplay = pygame.display.set_mode((display_width,display_height)) #setting height and width of game window pygame.display.set_caption("Car Racing") #title of game window carImg = pygame.image.load("Images/car.png") taxiImg = pygame.image.load("Images/frontal-taxi-cab.png") clock = pygame.time.Clock() #timing for game pause = True #method to draw a block which will act as an obstacle def things(x,y,w,h): gameDisplay.blit(taxiImg,(x,y)) #draws the car(in this case, the image) at (x,y) position def car(x,y): gameDisplay.blit(carImg, (x,y)) def text_objects(text, font): textSurface = font.render(text, True, BLACK) return textSurface, textSurface.get_rect() #display a message in the center of the screen def message_display(message): largeText = pygame.font.Font('freesansbold.ttf',30) TextSurf, TextRect = text_objects(message, largeText) TextRect.center = ((display_width/2),(display_height/2)) gameDisplay.blit(TextSurf, TextRect) pygame.display.update() time.sleep(2) game_loop() #display message and buttons to start over/quit def crash(): TextSurf, TextRect = text_objects("GAME OVER!", largeText) TextRect.center = ((display_width/2),(display_height/2)) gameDisplay.blit(TextSurf, TextRect) while True: for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() quit() button("PLAY AGAIN",200,450,120,50,GREEN,LIGHT_GREEN,"play") button("QUIT",500,450,100,50,RED,LIGHT_RED,"quit") pygame.display.update() clock.tick(15) #method to display button with clicking def button(message, x, y, w, h, inactive, active, action = "None"): mouse = pygame.mouse.get_pos() clicked = pygame.mouse.get_pressed() #highlight button when hovered over if (x+w > mouse[0] > x and y+h > mouse[1] > y): pygame.draw.rect(gameDisplay,active,(x,y,w,h)) if clicked[0] == 1 and action!="None":#left click if action == "play": game_loop() elif action == "quit": pygame.quit() quit() elif action=="unpause": CONTINUE() else: pygame.draw.rect(gameDisplay,inactive,(x,y,w,h)) #add text over button TextSurf, TextRect = text_objects(message, smallText) TextRect.center = ( (x + (w/2)), (y+(h/2)) ) gameDisplay.blit(TextSurf, TextRect) #scoring- increment the score once the obstacle is avoided, and display on the top right def add_score(score): font = pygame.font.SysFont(None,25) text = font.render("Score: "+ str(score), True, BLACK) gameDisplay.blit(text,(0,0)) #changing pause to false when continue def CONTINUE(): global pause pause = False #pause screen def isPaused(): TextSurf, TextRect = text_objects("PAUSED", largeText) TextRect.center = ((display_width/2),(display_height/2)) gameDisplay.blit(TextSurf, TextRect) while pause: for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() quit() button("CONTINUE",200,450,120,50,GREEN,LIGHT_GREEN,"unpause") button("QUIT",500,450,100,50,RED,LIGHT_RED,"quit") pygame.display.update() clock.tick(15) #load a start screen def game_intro(): intro = True while intro: for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() quit() gameDisplay.fill(WHITE) TextSurf, TextRect = text_objects("Dodger", largeText) TextRect.center = ((display_width/2),(display_height/2)) gameDisplay.blit(TextSurf, TextRect) button("START",200,450,100,50,GREEN,LIGHT_GREEN,"play") button("QUIT",500,450,100,50,RED,LIGHT_RED,"quit") pygame.display.update() clock.tick(15) #game loop def game_loop(): #setting the starting position of car x = 0.45 * display_width y = 0.8 * display_height x_change = 0 #change in x direction(when key is pressed) thing_startx = random.randrange(0,display_width) thing_starty = -600 thing_speed = 5 thing_width = 100 thing_height = 100 thing_repeat = [random.randrange(0,display_width-thing_width)] thing_count = 1 score = 0 #starting score is zero global pause #the game is about not crashing into another object- so a crash variable is used to end the game isCrashed = False gameExit = False car_width = 128 while not gameExit: #creating a list of events(in this case, key presses) that may happen for event in pygame.event.get(): if event.type == pygame.QUIT:#in this event, the user decides to quit the game pygame.quit() quit if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 if event.key == pygame.K_RIGHT: x_change = 5 if event.key == pygame.K_p: pause = True isPaused() #when key is released, there must be no change in position if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or pygame.K_RIGHT: x_change = 0 x+=x_change gameDisplay.fill(WHITE)#change background color things(thing_startx , thing_starty, thing_width, thing_height) thing_starty += thing_speed car(x,y) #important to print score last, so that there's no overlapping add_score(score) #crash if the car hits the window boundary if x > (display_width - car_width) or x < 0: crash() #block goes off the screen, reset. Also means that the car avoided the obstacle, increasing the score if thing_starty > display_height : thing_starty = 0 - thing_height thing_startx = random.randrange(0, (display_width-thing_width)) score += 1 if(score%5== 0): thing_speed += 2 if (y+22 < thing_starty + thing_height) and (y+22>thing_starty): if( (thing_startx + thing_width) > x > (thing_startx - car_width) ): crash() pygame.display.update() #can update specific parameters, or entire display(no parameters) clock.tick(60) #frames per second game_intro() game_loop() pygame.quit() quit
3d28564441795c156583bb04ecefb5f2db846daa
duckworthd/configurati
/configurati/loaders/utils.py
698
3.671875
4
import code import re def substitute(s): """Contents of `...` evaluated in Python""" if isinstance(s, basestring) and s.count("`") == 2: match = re.search("""^`([^`]+)`$""", s) contents, rest = match.group(1), s[match.end():] return evaluate(contents) else: return s def evaluate(line): """Evaluate a line and return its final output""" # XXX this isn't smart enough to know about semicolons/newlines in strings, # or code where the final result relies on indentation line = re.split(";|\n", line) line[-1] = "OUTPUT = " + line[-1] line = ";".join(line) interpreter = code.InteractiveConsole() interpreter.push(line) return interpreter.locals["OUTPUT"]
cac00dcb55e873a0dfa413924a1cd97ae96f51b6
AlliotTech/python-scripts
/Learnpy/network/tcpWeb/objWeb.py
3,674
3.578125
4
# -*- coding:utf-8 -*- # 第6个. # 使用面向对象思想进行封装. # 目标: 能够使用面向对象思想,对web服务器进行封装. """ 1. 功能分析 - 使用面向对象思想进行封装. - 通过对象方法start(),启动web服务器. 2. 实现思路 - 创建HttpServer类. - 创建HttpServer类的构造方法,并在构造方法中对tcp_server_socket创建初始化. - 创建start()方法,用来web服务器启动。 """ import socket import os class WebServer(object): # 初始化方法 def __init__(self): tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) tcp_server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) tcp_server_socket.bind(("18.18.23.254",8882)) tcp_server_socket.listen() # 定义实例属性,保存套接字对象 self.tcp_server_socket = tcp_server_socket def start(self): """启动web服务器""" while True: new_client_socket,ip_port = self.tcp_server_socket.accept() print("新客户端来了:",ip_port) # 调用功能函数 self.request_handler(new_client_socket,ip_port) def request_handler(self,new_client_socket,ip_port): request_data = new_client_socket.recv(1024) if not request_data: print("{}客户端已经下线.".format(str(ip_port))) new_client_socket.close() return # 根据客户端浏览器请求的资源路径,返回请求资源. # 1) 把请求协议解码,得到请求报文的字符串 request_text = request_data.decode() # 2) 得到请求行 # - 查找,第一个\r\n出现的位置. loc = request_text.find("\r\n") # - 截取字符串,从开头嫁娶到第一个\r\n出现的位置. request_line = request_text[:loc] print(request_line) # - 把请求行,按照空格拆分, 得到列表. request_line_list = request_line.split(" ") print(request_line_list) # 得到请求的资源路径 file_path = request_line_list[1] # print(file_path) print("{a}正在请求:{b}".format(a=str(ip_port),b=file_path)) # 设置默认首页 # if file_path == "/": # file_path = "/index.html" # 9. 拼接响应报文. # 9.1 响应行 response_line = "HTTP/1.1 200 OK\r\n" # 9.2 响应头 response_header = "Server:Python3-vscodeIDE/2.1\r\n" # 9.3 响应空行 response_blank = "\r\n" # 9.4 响应主体 indexpath = "F:\\PythonProject\\python-scripts\\DevOps\\network\\tcpWeb\\static\\index.html" try: # 返回固定页面, 通过with读取文件. with open(indexpath,"rb") as file: # 把读取的文件内容返回给客户端. response_body = file.read() except Exception as e: # 重新修改响应行为404 response_line = "HTTP/1.1 404 Not Found\r\n" # 响应的内容为错误. response_body = "Error! {}".format(str(e)) # 把内容转换为字节码 response_body = response_body.encode() response_data = (response_line + response_header + response_blank).encode() + response_body # 10. 发送响应报文. new_client_socket.send(response_data) # 11. 关闭连接. new_client_socket.close() def main(): # 创建WebServer类的对象 ws = WebServer() # 对象.start() 启动web服务器 ws.start() if __name__=="__main__": main()
cce8918ab3d3a05a1750a8e02f8cfeb0e3742386
GrishaAdamyan/All_Exercises
/To read and sort the table.py
969
3.59375
4
#row = int(input()) #col = int(input()) #table = [[input() for j in range(col)] for i in range(row)] #for i in range(len(table)): #if i == 0 or i == len(table)-1: #print('\t'.join(table[i])) #else: #for k in range(len(table[i]) - 1): #for j in range(len(table[i]) - 1 - k): #if table[i][j] > table[i][j + 1]: #table[i][j], table[i][j + 1] = table[i][j + 1], table[i][j] #print('\t'.join(table[i])) row = int(input()) col = int(input()) table = [[input() for j in range(col)] for i in range(row)] for i in range(len(table)): if i == 0 or i == len(table)-1: print('\t'.join(table[i])) else: table[i].sort() print('\t'.join(table[i])) #4 #3 #amazing #three #club #happy #seven #worms #desirable #ace #peak #sinister #lady #peak #amazing three club #happy seven worms #ace desirable peak #sinister lady peak
e1aa8c198dead18462c19d2bb94fd498198e8b9f
michalwojewoda/python
/Exercises/Coding Bat/Warmup-1.py
3,132
3.890625
4
# Given an int n, return True if it is within 10 of 100 or 200. # Note: abs(num) computes the absolute value of a number. def near_hundred(n): return ((abs(100-n) <=10) or (abs(200 - n) <=10)) #The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. def sleep_in(weekday, vacation): if not weekday or vacation: return True else: return False #Given a string, return a new string where the first and last chars have been exchanged. def front_back(str): if len(str) <=1: return str mid = str[1:len(str)-1] return str[len(str)-1] + mid + str[0] print(front_back("Michael")) #We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. #We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble. def monkey_trouble(a_smile, b_smile): if a_smile and b_smile: return True if not a_smile and not b_smile: return True return False print(monkey_trouble) # We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. # We are in trouble if the parrot is talking and the hour is before 7 or after 20. # Return True if we are in trouble. def parrot_trouble(talking, hour): return (talking and (hour < 7 or hour >20)) # Given 2 int values, return True if one is negative and one is positive. # Except if the parameter "negative" is True, then return True only if both are negative. def pos_neg(a, b, negative): if negative: return (a < 0 and b < 0) else: return ( a < 0 and b > 0) or (a > 0 and b < 0) # Given two int values, return their sum. Unless the two values are the same, then return double their sum. def sum_double(a, b): if ( a == b): return (a+b)*2 else: return (a+b) # Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. def makes10(a, b): return a == 10 or b == 10 or (a+b) == 10 # Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. def not_string(str): if len(str) >= 3 and str[:3] == "not": return str else: return "not " + str # Given a string, we'll say that the front is the first 3 chars of the string. # If the string length is less than 3, the front is whatever is there. # Return a new string which is 3 copies of the front. def front3(str): return str[:3] * 3 # def front3(str): front_end = 3 if len(str) < front_end: front_end = len(str) front = str[:front_end] return front + front + front print(front3("AS")) # Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. def diff21(n): if n <= 21: return 21 -n else: return (n - 21) * 2 # random integer integer = -20 print('Absolute value of -20 is:', abs(integer)) #random floating number floating = -30.33 print('Absolute value of -30.33 is:', abs(floating))
0214e7527bab7f7725454ad0ab6e3bf90893ffae
LucaMarconato/deutsch
/dienstprogramme.py
536
3.5
4
# von https://stackoverflow.com/questions/2460177/edit-distance-in-python def levenshtein_distanz(s1, s2): if len(s1) > len(s2): s1, s2 = s2, s1 distanzen = range(len(s1) + 1) for i2, c2 in enumerate(s2): distanzen_ = [i2 + 1] for i1, c1 in enumerate(s1): if c1 == c2: distanzen_.append(distanzen[i1]) else: distanzen_.append(1 + min((distanzen[i1], distanzen[i1 + 1], distanzen_[-1]))) distanzen = distanzen_ return distanzen[-1]
710c1cd0280831e99f04600793bdbe1b1ba736aa
sunnytake/CodeAndDecode
/左神/初级班/第二课/二叉堆.py
1,694
3.90625
4
# coding=utf-8 ''' 小顶堆 ''' def upAdjust(array): ''' 上浮调整 ''' child_index = len(array) - 1 parent_index = (len(array) - 1) // 2 # temp保存插入的叶子节点值,用于最后的赋值 temp = array[child_index] while parent_index >= 0 and temp < array[parent_index]: # 无需真正交换,单向赋值即可 array[child_index] = array[parent_index] child_index = parent_index parent_index = (child_index - 1) // 2 array[child_index] = temp def downAdjust(array, parent_index, length): ''' 下沉调整 :param array: 待调整的堆 :param parent_index: 要下沉的父节点 :param length: 堆的有效大小 ''' # temp保存父节点的值,用于最后的赋值 temp = array[parent_index] child_index = 2 * parent_index + 1 while child_index < length: if child_index + 1 < length and array[child_index + 1] < array[child_index]: child_index += 1 if temp <= array[child_index]: break array[parent_index] = array[child_index] parent_index = child_index child_index = 2 * child_index + 1 array[parent_index] = temp def buildHeap(array): ''' 构建堆 :param array: 待调整的堆 ''' # 从最后一个非叶子节点开始,依次下沉调整 for index in range(len(array) // 2, -1, -1): downAdjust(array, index, len(array)) if __name__ == '__main__': array = [1, 3, 2, 6, 5, 7, 8, 9, 10, 0] upAdjust(array) print('up adjust', array) array = [7, 1, 3, 10, 5, 2, 8, 9, 6] buildHeap(array) print('build heap', array)
00c157ee0b3b97bc0477c3752339dc695302b725
Nubstein/Python-exercises
/Strings/Ex6_strings.py
832
4.21875
4
#Data por extenso. Faça um programa que solicite a data de nascimento # (dd/mm/aaaa) do usuário e imprima a data com o nome do mês por extenso. meses_ext= ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"] data=input(" Insira uma data em formato dd/mm/aaaa: ") data2=data.split("/") #Split para fazer com que cada numero separadado por / barra, seja um elemento da lista data2 print(data2) print(data2[0],"de",meses_ext[int(data2[1])-1],"de",data2[2]) #sabendo que lista data2 tem 3 elementos, pedi para imprimir o primeiro elemnto [0], #o segundo elemento foi formado pelo segundo elemento da data2[1]-1, #pois assim consigo uma correspondencia respectiva entre as duas listas data2 e meses_ext considerando q python indexa aparti de zero
d70e58a2040642b2875e75a520b9ca35d890c9d6
mippzon/python-mini-projects
/practice-python/08-rock-paper-scissor.py
218
3.65625
4
print('Welcome to the Rock Paper Scissor game!') player_points = 0 computer_points = 0 possible_actions = ['rock', 'paper', 'scissor'] player_action = int(input('Enter 1 for Rock, 2 for Paper or 3 for Scissor: '))