blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
41013f1755fb67eb83fc864e9b6b6d5ce1b524ab
Poolitzer/telegram_bot_frontend
/conversation.py
378
3.53125
4
# -*- coding: utf-8 -*- class Conversation(object): def __init__(self, worker, user, type): if worker == user: raise ValueError("Worker can't be the same as user") self.worker = worker self.user = user self.type = type def __repr__(self): return "Conversation(worker: {}, user: {})".format(self.worker, self.user)
0b8b33519a877bbc9f8d81f3cbca2a196a75d5da
dhazu/Mygit
/python_workbook/if-elif/ex56.py
2,791
4.1875
4
"""Exercise 56: Cell Phone Bill A particular cell phone plan includes 50 minutes of air time and 50 text messages for $15.00 a month. Each additional minute of air time costs $0.25, while additional text messages cost $0.15 each. All cell phone bills include an additional charge of $0.44 to support 911 call centers, and the entire bill (including the 911 charge) is subject to 5 percent sales tax. Write a program that reads the number of minutes and text messages used in a month from the user. Display the base charge, additional minutes charge (if any), additional text message charge (if any), the 911 fee, tax and total bill amount. Only display the additional minute and text message charges if the user incurred costs in these categories. Ensure that all of the charges are displayed using 2 decimal places.""" ## Solution: # ask the user to enter the talk time and number of text message minutes = int(input("Enter the number of minutes of air time: ")) text = int(input("Enter the number of text messgae send: ")) # charge of the 911 call center fee_911 = 0.44 # apply the condition and calculate the base_price, tax and total_bil if minutes <= 50 and text <= 50: base_price = 15 # base price is $15.00 tax = (base_price + fee_911) * 0.05 # tax is 5 percent total_bil = base_price + fee_911 + tax else: if minutes > 50 and text <= 50: diff1 = minutes - 50 base_price = 15 + diff1 * 0.25 # each additional air time will costs $0.25 tax = (base_price + fee_911) * 0.05 total_bil = base_price + fee_911 + tax elif text > 50 and minutes <= 50: diff2 = text - 50 base_price = 15 + diff2 * 0.15 # each additional text messages will costs $0.15 tax = (base_price + fee_911) * 0.05 total_bil = base_price + fee_911 + tax elif minutes > 50 and text > 50: diff1 = minutes - 50 diff2 = text - 50 base_price = 15 + diff1 * 0.25 + diff2 * 0.15 tax = (base_price + fee_911) * 0.05 total_bil = base_price + fee_911 + tax # Display the result # Display the additional minutes and text (if any) if minutes > 50 and text <= 50: print("Additional minutes = {:>11}".format(diff1)) elif text > 50 and minutes <= 50: print("Additional text msg = {:>11}".format(diff2)) elif minutes > 50 and text > 50: print("Additional miutes = {:>11}".format(diff1)) print("Additional text msg = {:>11}".format(diff2)) else: pass print("-" * 50) # print a dash line print("Base price is = ${:>10.2f}".format(base_price)) print("911 fee is = ${:>10.2f}".format(fee_911)) print("tax amount is = ${:>10.2f}".format(tax)) print("Total amount is = ${:>10.2f}".format(total_bil))
b0c3cbf5423694c3695dec0db4f29440f47320f2
KETULPADARIYA/Computing-in-Python
/5.2 Control Structures/4 Functions/23 VowelsAndConsonants.py
1,398
4.375
4
#In this problem, your goal is to write a function that can #either count all the vowels in a string or all the consonants #in a string. # #Call this function count_letters. It should have two #parameters: the string in which to search, and a boolean #called find_consonants. If find_consonants is True, then the #function should count consonants. If it's False, then it #should instead count vowels. # #Return the number of vowels or consonants in the string #depending on the value of find_consonants. Do not count #any characters that are neither vowels nor consonants (e.g. #punctuation, spaces, numbers). # #You may assume the string will be all lower-case letters #(no capital letters). #Add your code here! def count_letters(a,s): a= a.replace(' ' , "") k =0 if s ==False: for i in a : if i =='u' or i == 'a'or i =='e'or i =='o'or i =='i': k +=1 else: for i in a : if i !='u' and i != 'a' and i !='e'and i !='o'and i !='i': k +=1 return k #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print 14, then 7. a_string = "up with the white and gold" print(count_letters(a_string, True)) print(count_letters(a_string, False))
b12ac80d77148ab34b40095937d15f56083a5e53
incipient1/Introduction_To_Algorithms_3rd_py3
/02_sorting_and_order_statistics/08_3_quick_sort_hoare.py
483
3.546875
4
def hoare_partiton(A,p,r): x = A[p] i = p j = r while True: while A[j] > x: j -= 1 while A[i] < x: i += 1 if i < j: A[j], A[i] = A[i], A[j] else: return j def quick_sort_hoare(A,p,r): if p < r: q = hoare_partiton(A,p,r) quick_sort_hoare(A,p,q-1) quick_sort_hoare(A,q+1,r) return A A = [13,9,5,12,8,7,4,11,2,6,21] print(quick_sort_hoare(A,0,len(A)-1))
58adaf34e8177b99f19b084358684f51ec9da485
crossin/Crossin-practices
/python_weekly_modual/collections-ordereddict.py
565
3.71875
4
import collections dic = {'c':1,'a':2,'b':3} # sorted_tuple = sorted(dic.items(),key=lambda x:x[0]) new_dic = collections.OrderedDict(dic) print(new_dic) # # d = {} # d['a'] = 1 # d['b'] = 2 # d['c'] = 3 # print(d) # 提取 items # print (new_dic.items()) # # 提取 keys # print(new_dic.keys()) # # 提取 values # print(new_dic.values()) # # 复制 字典 # print(new_dic.copy()) # popitem # print(new_dic.popitem()) # print (new_dic) # move_to_end() # print(new_dic) # new_dic.move_to_end('a') # print(new_dic) # while True:
6d330b264c3f828bafb7bbcd64f5accdc0cef368
ElielMendes/Exercicios-da-Faculdade-e-projeto-de-Numerologia-Karmica
/.vscode/aula7.py/ex5.py
775
3.796875
4
aprovado = 0 exame = 0 reprovado = 0 acm_media = 0 for cont in range(1,7): print(f'----------Notas do {cont}ª aluno------------- ') n1 = float(input('Digite a 1ª nota: ')) n2 = float(input('Digite a 2ª nota: ')) media = (n1 + n2) / 2 acm_media += media if media < 3: reprovado += 1 mensagem = 'REPROVADO' if media > 3 and media < 7: exame += 1 mensagem = 'EXAME' if media >= 7: aprovado += 1 mensagem = 'APROVADO' print(f'A média de notas do {cont}ª aluno é: {media}. {mensagem} ') print(f'Total de alunos reprovados: {reprovado}') print(f'Total de alunos de exame: {exame}') print(f'Total de alunos aprovados: {aprovado}') print(f"A média da classe é: {acm_media / cont}")
57d1fbe543d1e2fcbd048b6cc089e9eda1c03b5f
mayank-prasoon/folder_manager
/Folder Manager/main.py
4,507
3.53125
4
from tkinter import Tk from tkinter.filedialog import askdirectory import databasemanager as DM import foldercreator as fc import os import exicutesoftware import tomatotimer as tt dm = DM.DatabaseManager() class Welcome: def welcome(self): welcome = input( "\twelcome to the software\nplease choose from the following command....\n1. last\n2. all\n3. new\n4. setting\n5. exit\n\t") if welcome == 'last' or welcome == '1': project_list = dm.search_all() print("this was the last project you were working on: " + str(project_list[-1][1] + ' | ' + project_list[-1][2] + ' | ' + project_list[-1][5])) Project().lastproject() if welcome == 'new' or welcome == '3': print("please complete the following in order to start a new project....\n\n") Project().new_project(askdirectory(title='Select the location'), input('name of the project: '), input("\ncategory of the project: ")) if welcome == 'all' or welcome == '2': Project().all_project() if welcome == 'setting' or welcome == '4': pass if welcome == 'exit' or welcome == '5': pass class Project: def all_project(self): """dispaly all the projects""" print( 'these are all your project please choose one from the following\n') for y in range(len(dm.search_all())): print(y, dm.search_all()[y][1], dm.search_all()[y][2], dm.search_all()[y][5]) try: num = input('\n\topen: ') print(str(dm.search_all()[int(num)][3])) try: time = input("please set the alarm: ") except: print("what ever you typed, it was not a not integer") time = input("please set the alarm: ") Project().openproject(str(dm.search_all()[int(num)][3]), str( dm.search_all()[int(num)][2])) tt.TomatoTimer().break_time(time) tt.TomatoTimer().add_work_hour(num, time) except: print('an error has occur:\n\t' + str(num) + ' is not a number\nplease choose the number like 1,2,3') Welcome().welcome() def openproject(self, location, cat): """Opens a project that was called""" location = str(location) location = os.path.realpath(location) RunProgram().run(cat, location) os.startfile(location) def lastproject(self): """Last project which was produced""" if input('should if open = ' + str(dm.search_all()[-1][3]) + '\n (yes/no)\n\t').casefold() == 'yes': location = str(dm.search_all()[-1][3]) cat = str(dm.search_all()[-1][2]) location = os.path.realpath(location) try: time = input("please set the alarm: ") except: print("what ever you choose was not a not integer") time = input("please set the alarm: ") RunProgram().run(cat, location) os.startfile(location) tt.TomatoTimer().break_time(time) tt.TomatoTimer().add_work_hour(-1, time) else: print('home page...') Welcome().welcome() def new_project(self, location, name, cat): """Creates a new project""" fc.FolderManager().build_folder(location, name, cat) if input('do you want to open all the programs: ') == 'yes': if cat == 'art': exicutesoftware.NewProjectFiles().open_art() if cat == 'comic': exicutesoftware.NewProjectFiles().open_comic() if cat == 'gamedev': exicutesoftware.NewProjectFiles().open_gamedev() os.startfile(location) class RunProgram: def run(self, cat, location): if input('do you want to open all the programs: ') == 'yes': if cat == 'art': exicutesoftware.OpenLastFiles().open_art(location, 'art') if cat == 'comic': exicutesoftware.OpenLastFiles().open_comic(location, 'comic') if cat == 'gamedev': exicutesoftware.OpenLastFiles().open_gamedev(location, 'gamedev') else: pass a = Welcome().welcome()
618f678090a964caa78ef86e8199a2e3390ee522
ArlexDu/PythonWeb
/exercise/thread.py
999
3.671875
4
''' import time, threading def loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n += 1 print('thread %s >>> %s' % (threading.current_thread().name,n)) time.sleep(1) print('thread %s ended.' % threading.current_thread().name) if __name__ == '__main__': print('thread %s is running...' % threading.current_thread().name) t = threading.Thread(target = loop,name='LoopThread') t.start() t.join() print('thread %s ended.'%threading.current_thread().name) ''' import threading local_school = threading.local() def process_student(): std = local_school.student print('Hello,%s (in %s)' % (std,threading.current_thread().name)) def process_thread(name): local_school.student = name process_student() if __name__ =='__main__': t1 = threading.Thread(target = process_thread,args=('Happy',),name='Thread-A') t2 = threading.Thread(target = process_thread,args=('Arlex',),name='Thread-B') t1.start() t2.start() t1.join() t2.join()
323dbdfe8a7bfeeaa473b3dea54404f054360187
hguochen/algorithms
/python/interviews/g_interview.py
1,670
4.1875
4
#Say you're dealing with data that has a lot of repeated characters in it. You'd like to take advantage of that to compress the data. In particular, you are given the following run-length encoding scheme: An encoded string is normally passed through verbatim. However, if there is a decimal number followed by the character 'x', then the character after the x will be repeated that many times." #For example: "abc11xkd55s" -> "abckkkkkkkkkkkd55s" # #5x j #11x k #3x 2 #4x: ## python #input: string of infinite chars #output: parsed string where instructions are parsed #case 1:string len 0 #case 2: normal string w/o any instructions #case 3: with 1 or more instructions #import re #O(n) #def parsed_string(string): #result = “” #temp = “” #reg_exp = “da-z” #tokens = string_tokenize(string) # 7 elements #for i in xrange(len(tokens)): #if re.match(reg_exp, tokens[i]): #num = int(tokens[i][-1]) #alp = tokens[i][-1] #result += alp * (num) #else: #result += tokens[i] #return result #def string_tokenize(string): #tokens = [] #reg_exp = “da-z” ## run through the string ## if encounter reg_exp ## token.append() #return tokens # list #string_tokenize(“abc5xjflks11xk48ugjkl3x2dfjkl”) #return [abc, 5xj, flks, 11xk, 48ugjkl, 3x2, dfjkl] import re def parse(a_string): pattern = re.compile(r'([0-9]+)x([a-z])') matches = pattern.findall(a_string) for match in matches: repl = match[1] * int(match[0]) a_string = re.sub(pattern, repl, a_string) return a_string if __name__ == "__main__": print parse('abc11xkd55s')
c27e175c8746d55593c950fffb25ec06556774f4
praveenRI007/Basics-of-python-programming
/basics of python programming in 1hour/python basics #5_if else booleans.py
1,406
4.1875
4
if True : print('condition was true') language = 'python' if language == 'java': print('language is java') elif language =='python': print('language is python') else : print('no match') # and or not user = 'admin' logged_in = True #and if user == 'admin' and logged_in: print('admin page') else: print('bad credits') #or if user == 'admin' or logged_in: print('admin page') else: print('bad credits') #not logged_in = False if not logged_in: print('please login') else: print('welcome') a=[1,2,3] b=a print(id(a)) print(id(b)) print(a is b) print(a == b) print(id(a)==id(b)) condition = None if condition: print('evaluated to true') else : print('evaluated to false') condition = 0 if condition: print('evaluated to true') else : print('evaluated to false') condition = [] if condition: print('evaluated to true') else : print('evaluated to false') condition = 10 if condition: print('evaluated to true') else : print('evaluated to false') condition = {} if condition: print('evaluated to true') else : print('evaluated to false') #empty value correspond to false ''' OUTPUT condition was true language is python admin page admin page please login 2079305220808 2079305220808 True True True evaluated to false evaluated to false evaluated to false evaluated to true evaluated to false '''
78a7d53202e3e7b217c5c57b06bea72e1f07ca0d
GitHub-zd/python-test
/func-test.py
1,877
3.796875
4
def math_func(maths): if 0 <= maths <= 100: if maths < 75: print("数学的评价为:bad") elif 75 <= maths <85: print("数学评价为:good") else: print("数学评价为:great") else: print("分数输入错误,请重新输入") def english_func(english): if 0 <= english <= 100: if english < 80: print("英语的评价为:bad") elif 80 <= english < 90: print("英语评价为:good") else: print("英语评价为:great") else: print("分数输入错误,请重新输入") def history_func(history): if 0 <= history <= 100: if history < 70: print("历史的评价为:bad") elif 70 <= history <78: print("历史评价为:good") else: print("历史评价为:great") else: print("分数输入错误,请重新输入") def zhesuan_func(maths,english,history): new_maths = maths * 1.1 new_english = english * 1.1 new_history = history * 0.8 new_total = new_maths+new_english+new_history print("折算完总分数为:",new_total) return new_total def total_func(new_total): if new_total >= 270: print("分数等级为A+") elif new_total >= 240: print("分数等级为A") elif new_total >= 210: print("分数等级为B+") elif new_total >= 190: print("分数等级为:B") else: print("分数等级为C") if __name__ == '__main__': maths = int(input("请输入数学的分数:")) english = int(input("请输入英语的分数:")) history = int(input("请输入历史的分数:")) math_func(maths) english_func(english) history_func(history) r = zhesuan_func(maths,english,history) total_func(r)
430beae98f2017f6546c686106a76a6f452b97cf
Ashleshk/Python-For-Everybody-Coursera
/Course-2-python_data_structures/assignment9.4_dictionaries_count.py
1,074
4.03125
4
# 1. Get file name # 2. Open file # 3. Look for 'From' each line # 4. Get second word from each line # 5. Create dictionary # 6. Map address/count to dictionary # 7. Count most common using maximum loop # 1. Get file name # fname = raw_input('Enter file: ') # 2. Open file fhandle = open('mbox-short.txt') # 5. Create dictionary counts = dict() # 3. Look for 'From' each line for line in fhandle: words = line.split() # Guardian pattern for blank lines if len(words) < 1: continue # To ignore all sentences starting from "From:" if words[0] == 'From:': continue # To ignore all sentences not starting from "From " if words[0] != 'From': continue word = words[1] # 6. Map address/count to dictionary counts[word] = counts.get(word, 0) + 1 # print words # 7. Count most common using maximum loop bigcount = None bigword = None for word, count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count print bigword, bigcount # print counts
26c5b3b335cf32130f39ee94e6d1dbfa0ab1f1a7
JonatanCadavidTorres/Courses_Platzi
/algorithms/lineal_search.py
596
3.90625
4
import random def lineal_search(the_list, objective): match = False for element in the_list: # O(n) if element == objective: match = True break return match if __name__ == '__main__': list_size = int(input('What is the size of the list? ')) objective = int(input('What number do you want to find? ')) the_list = [random.randint(0, 100) for i in range(list_size)] find_it = lineal_search(the_list, objective) print(the_list) print(f'El element {objective} {"is" if find_it else "is not"} in the list')
8a9e99b3b72069278dcd1d5d2287399ae80390ee
NanaAY/cs108_projects
/homework07/find_genes.py
1,734
4.28125
4
'''A Python program that displays all the genes in a genome Created Spring 2018 Homework07 @author: Nana Osei Asiedu Yirenkyi (na29)''' #Function definition for finding a gene def find_gene(genome): '''receives a genome and returns all possible genes or false if otherwise''' if "ATG" in genome: a_t_g = genome.find("ATG") if ("TAA" in genome) and (genome.find("TAA") > a_t_g): t_a_a = genome.find("TAA") new_gene = genome[a_t_g + 3:t_a_a] gene_list.append(new_gene) genome = genome[t_a_a:] return genome elif ("TAG" in genome) and (genome.find("TAG") > a_t_g): t_a_g = genome.find("TAG") new_gene = genome[a_t_g + 3:t_a_g] genome = genome[t_a_g:] gene_list.append(new_gene) return genome elif "TGA" in genome and (genome.find("TGA") > a_t_g): tga = genome.find("TGA") new_gene = genome[a_t_g + 3 : tga] genome = genome[tga:] gene_list.append(new_gene) return genome else: return False #Prompts the user to enter a genome user_genome = input("Enter a genome string:").upper() #Creates an empty list to keep track of genes found gene_list = [] #Infinite loop for finding possible genes in genome while True: user_genome = find_gene(user_genome) if len(gene_list) <= 0: print("No gene is found") break if user_genome == False: break #Printing genes order = 1 if len(gene_list) > 0: for g in gene_list: if ("ATG" or "TAG" or "TAA" or "TGA" not in g) and (len(g) % 3 == 0) : print("Gene", order ,':', gene_list[order-1]) order += 1
739a7b73a2018df0ec1d710e9d90ed98b2dbb999
Alleinx/Notes
/modeling/Integral/Area.py
615
4.09375
4
#This program calculate the Area under a curve using "Finite sums" # function : f(x) = x^2 # Domain : [0,1] import math def calculate_value(x): return pow(x, 2) def main(): slice_num = 8 #The more slice token, the more precise the result is. stride = 1 / slice_num lower_area = 0 upper_area = 0 i = 0.0 while(i < 1): lower_area += calculate_value(i) * stride i += stride print('lower bound:', lower_area) i = 0.0 while (i < 1): upper_area += calculate_value(i+stride) * stride i += stride print('upper bound:', upper_area) main()
93f37467fb36e2e39628f7d45aeb85bd4072717d
macrespo42/Bootcamp_42AI
/day00/ex07/filterword.py
350
3.640625
4
import sys import string def error(): print("ERROR") sys.exit(0) if (len(sys.argv) == 3): try: min = int(sys.argv[2]) except: error() for ch in string.punctuation: sys.argv[1] = sys.argv[1].replace(ch, "") lst = sys.argv[1].split(" ") final = [] for elt in lst: if (len(elt) > min): final.append(elt) else: error() print(final)
2c40bd1503e27ac827d1ec689110f35de5214abd
openjamoses/ML-Kaggle
/Preprocessing.py
3,724
4.0625
4
""" Functions used to vizualize, process, and augmente the Image dataset """ import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt def plot_digit(Xrow): """ Plot a single picture """ size = int(np.sqrt(Xrow.shape[-1])) image = Xrow.reshape(size, size) plt.imshow(image, cmap = mpl.cm.binary) plt.axis("off") plt.show() def plot_digits(instances, images_per_row = 3, **options): """ Plots a series of images Parameters ---------- instances : ndarray Instances in the data one wants to plot. images_per_row : int, optional The default is 3. **options : Dict Keyword arguments to give plt.imshow. ------- """ size = int(np.sqrt(instances.shape[1])) images_per_row = min(len(instances), images_per_row) images = [instance.reshape(size,size) for instance in instances] n_rows = (len(instances) - 1) // images_per_row + 1 row_images = [] n_empty = n_rows * images_per_row - len(instances) images.append(np.zeros((size, size * n_empty))) for row in range(n_rows): rimages = images[row * images_per_row : (row + 1) * images_per_row] row_images.append(np.concatenate(rimages, axis = 1)) image = np.concatenate(row_images, axis = 0) plt.imshow(image, cmap = mpl.cm.binary, **options) plt.axis("off") plt.show() def crop_images(instances, reduce = 1): """ Reduce sizes of Images by removing "reduce" pixels on each edge """ nsize = int( np.sqrt(instances.shape[1]) ) reduce_size = nsize - 2 * reduce cropped = np.zeros((instances.shape[0], reduce_size ** 2) , dtype = 'u1') for i in range(reduce_size): cropped[:, reduce_size*i: reduce_size*(i+1)] = \ instances[:, (i+1)*nsize+reduce:(i+2)*nsize-reduce] return cropped def reverse_images(instances): """ Take the horizontal symmetry of each image Parameters ---------- instances : ndarray Images to be reversed horizontally, one image per row. Returns ------- flipped : ndarray Flipped images. """ flipped = instances.copy() nsize = int( np.sqrt(instances.shape[1]) ) for i in range(nsize): flipped[:, nsize*i:nsize*(i+1)] = \ np.flip(flipped[:, nsize*i:nsize*(i+1)], axis = 1) return flipped def translate_images(instances, all_delta_i, all_delta_j): """ Translate each images in specified directions Parameters ---------- instances : ndarray Images to be reversed horizontally, one image per row. all_delta_i : list List of translations over the first index. all_delta_j : list List of translations over the second index. Returns ------- translates : ndarray Translated images """ if not len(all_delta_i) == len(all_delta_j): raise ValueError("The size of the two lists must match") nimages = instances.shape[0] nsize = int( np.sqrt(instances.shape[1]) ) translated = np.zeros( (len(all_delta_i) * nimages, instances.shape[1]) , dtype = np.dtype('u1')) nsize = int( np.sqrt(instances.shape[1]) ) z = lambda i, j: i * nsize + j for t in range( len(all_delta_i) ): delta_i = all_delta_i[ t ] delta_j = all_delta_j[ t ] for pixel_idx in range(instances.shape[1]): row = int(pixel_idx / nsize) col = pixel_idx % nsize translated[t*nimages:(t+1)*nimages, pixel_idx] = \ instances[:, z(row - delta_i % nsize, col - delta_j % nsize)] return translated
ee9ee336ac38914526a2bfae9e3625617672136d
gabriellaec/desoft-analise-exercicios
/backup/user_061/ch68_2019_04_03_21_56_51_670379.py
190
3.609375
4
def separa_trios(lista_alunos): i=0 while i<len(lista_alunos): if lista_alunos % 3 != 0: trio[0] = (lista_alunos % 3) trios.append(lista_alunos[::3])
dbe5f7d024f7a94efce2d95bd0f1e96cf3004d3c
y43560681/y43560681-270201054
/lab7/example1.py
280
4.0625
4
n = int(input("How many names and ages will you enter? ")) name_store = [] age_store = [] a = '' for i in range(n): name = input("Please enter a name : ") age = input("Please enter a age : ") if int(age) > 18: name_store.append(name) for i in name_store: print(i)
3dbf52c53dafe2e3cfb6ec3a65dda80045452847
Mostofa-Najmus-Sakib/Applied-Algorithm
/Leetcode/Python Solutions/Recursion & Backtracking/GenerateParentheses.py
1,876
3.921875
4
""" LeetCode Problem: 22. Generate Parentheses Link: https://leetcode.com/problems/generate-parentheses/submissions/ Language: Python Written by: Mostofa Adib Shakib Time complexity: Bounded by a catalan number """ """ Conditions that makes parenthesis balanced: 1) An empty string is a string in which parenthesis are balanced. 2) The addition of a leading left parenthesis and a trailing right parenthesis to a string in which parenthesis are matched. 3) The concatenation of two strings in which parenthesis are balanced results in a new string where the parenthesis are also balanced. Constraits: 1) The number of opening parenthesis should be less than the twice the maximum of pair required(Condition 1) 2) The number of closing parenthesis should be less than the number of opening parenthesis(Condition 2) """ class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ def backtrack(array, current_string, NoleftParenthesis, NoRightParenthesis, maximumLength): if len(current_string) == maximumLength *2: # if have found one of the solutions array.append(current_string) return if NoleftParenthesis < maximumLength: # we can place an opening parenthesis backtrack(array, current_string + '(', NoleftParenthesis+1, NoRightParenthesis, maximumLength) if NoRightParenthesis < NoleftParenthesis: # we can place a closing parenthesis backtrack(array, current_string + ')', NoleftParenthesis, NoRightParenthesis+1, maximumLength) array = [] # the array containing all the solutions backtrack(array, "", 0, 0, n) # calling the helper method return array # returns the answer array at the end
b2f3b96ef02f284510f786dc46c9571711bab788
tashakim/puzzles_python
/checkSubtree.py
586
3.90625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, s, t): def match(s, t): if not s or not t: return s is t return (s.val == t.val and match(s.left, t.left) and match(s.right, t.right)) if match(s, t): return True if not s: return False return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
ee052bca48277341e4f0695b6ab4c6521794a356
frimmy/LPTHW-exs
/ex15.py
717
4.09375
4
#imports from the python system the argv class/features/modules from sys import argv #defines two arguments entered on the CL script, filename = argv #defines txt as the file name enetered on the CL and # assigns the txt obj to the variable 'text' txt = open(filename) # prints a line and the filename entered on the CL print "Here's your file %r:" % filename #prints the txt file out print txt.read() #prints an instruction print "Type the filename again:" #assings user input of file name to variable 'file_again' file_again = raw_input("> ") # assigns the opened txt file to 'txt_again' variable txt_again = open(file_again) # prints a read file to CL print txt_again.read() txt.close() txt_again.close()
63196d41c5693e89f888d3edb65638496a4fe826
zinechant/code
/ita/cities.py
2,339
3.5
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'closestStraightCity' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts following parameters: # 1. STRING_ARRAY c # 2. INTEGER_ARRAY x # 3. INTEGER_ARRAY y # 4. STRING_ARRAY q # MAX_DIST = 2000000000 import bisect def closest(arr, val): ans = (MAX_DIST + 10, "NONE") x = bisect.bisect_right(arr, (val, "")) if x > 0: ans = (arr[x][0] - arr[x-1][0], arr[x-1][1]) if x < len(arr) - 1: alt = (arr[x+1][0] - arr[x][0], arr[x+1][1]) if alt < ans: ans = alt return ans def closestStraightCity(c, x, y, q): xs = {} ys = {} cities = {} for i in range(len(c)): cities[c[i]] = (x[i], y[i]) if x[i] not in xs: xs[x[i]] = [] if y[i] not in ys: ys[y[i]] = [] xs[x[i]].append((y[i], c[i])) ys[y[i]].append((x[i], c[i])) for x in xs: xs[x] = sorted(xs[x]) for y in ys: ys[y] = sorted(ys[y]) ans = [] for city in q: if city not in cities: ans.append("NONE") continue x, y = cities[city] res = closest(xs[x], y) alt = closest(ys[y], x) if alt < res: res = alt ans.append(res[1]) return ans if __name__ == '__main__': c = ["fastcity", "bigbanana", "xyz"] x = [23, 23, 23] y = [1, 10, 20] q = ["fastcity", "bigbanana", "xyz"] print(closestStraightCity(c, x, y, q)) # fptr = open(os.environ['OUTPUT_PATH'], 'w') # c_count = int(input().strip()) # c = [] # for _ in range(c_count): # c_item = input() # c.append(c_item) # x_count = int(input().strip()) # x = [] # for _ in range(x_count): # x_item = int(input().strip()) # x.append(x_item) # y_count = int(input().strip()) # y = [] # for _ in range(y_count): # y_item = int(input().strip()) # y.append(y_item) # q_count = int(input().strip()) # q = [] # for _ in range(q_count): # q_item = input() # q.append(q_item) # result = closestStraightCity(c, x, y, q) # fptr.write('\n'.join(result)) # fptr.write('\n') # fptr.close()
ccf7a0c8ccf77c29b20dcb5cdebc3646cb897c4e
maxvalrus/python_learn
/codefights/checkPalindrome.py
294
3.625
4
def checkPalindrome(inputString): i = 0 max = len(inputString) // 2 while i <= max: if inputString[i] == inputString[-i - 1]: i += 1 else: return False return True if __name__ == "__main__": print(checkPalindrome('aabaa'))
66600da7f2d7f9cdf35eb2006d1862652c2c4f8b
NicholasArnaud/Python_FileUtility
/Renaming/music.py
524
3.5625
4
import os def change_name(location): directory = os.listdir(location) os.chdir(location) newlist = [] for filename in directory: if filename.endswith(".mp3"): newlist.append(filename) os.rename(filename, filename[:-4]) if filename.endswith(" - Copy"): newlist.append(filename) os.rename(filename, filename[:-6]) print newlist #C:\Users\Public\Music\Sample Music dir = raw_input("Enter the directory you want to search \n") change_name(dir)
f949cafaa54c7287357cec2bc61c0ce77c014f28
Darshan1917/python_complete
/demo_oops.py
904
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 6 17:44:39 2018 @author: dumapath """ # this is a place we have oops concepts demo # class creation import datetime class User: #init is a constructer and must be present in the program def __init__(self,fname,lname,dob): self.fname = fname self.lname = lname self.email = fname+lname+"@gmail.com" self.dob = dob def fullname(self): return self.fname+' '+self.lname # def age(self,dob): # today = datetime.date.today() # bday = self.dob.strftime("%Y-%m-%d") # bday_new =bday[0:4] # age_in_years = int(today-bday_new) # return age_in_years # user1 is an instance of User and we can use the functions in User user1 = User("John","david",'1971-07-05') print(user1.fullname().split(" ")) print(user1.dob) #print(user1.age("1971-07-05"))
daa3ae1166bb20ee631f9281050d758fd2c1b8ed
langet0695/minigenerator
/main.py
6,488
3.71875
4
# Author: Travis Lange # Description: This is an experiment to develop an algorithm that can generate a mini cross word (5x5) puzzle. # TO DO: # Identify why there is a possible ordering of words that won't work import random import json # import dictConfig # possible_words = dictConfig.WordGenerator() # # # possible_words = [ ("open_", "test"), ("snark", "test"), ("tapas", "_"), ("_rice", "_"), ("isbns", "test"), ("_hug_", "test"), ("korea", "test"), ("_take", "test"), ("pot__", "test"), ("apart", "test"), ("pass_", "test"), ("sepia", "test"), ("snack", "test"), ("__see", "test"), ("SODAS", "Fast-food drinks"), ("TOROS", "Corrida de ___ (“Running of the Bulls”)"), ("SHAME", "Feeling of humiliation"), ("OCEAN", "Separator of continents"), ("_CABS", "Yellow symbols of N.Y.C."), ("_asks", "test"), ("_NESS", "Loch ___ monster"), ("SAMOA", "Girl Scout cookie sprinkled with coconut"), ("BEARD", "Dopey is the only one of the Seven Dwarfs without one"), ("ACHOO", "Sound preceding Bless you!"), ("COSTS", "Counterpart of benefits, in a business analysis"), ("_bag_", "something placed in an overhead compartment"), ("_nne_", "opposite of SSW"), ("sarah", "comedian Silverman"), ("argue", "make the case for"), ("sines", "test"), ("_kiss", "test"), ("hosni", "test"), ("urban", "test"), ("genre", "test"), ("doozy", "total wower"), ("_nne_", "opposite of SSW"), ("baron", "industry tycoon"), ("argon", "element suggested here NOPQSTU"), ("gauze", "wrap in a first aid kit"), ("_sad_", "feeling blue"), ("_hey_", "what the...") ] failures = [] board = [ ["_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_"] ] def boardConstructor(possibilties, boardName, failures=[]): row = 0 loop_count = 0 # shortPos = possibilties[0:100] topLineFail = [] while row < 5: for word in possibilties: # print("exploring a new word: ", word[0]) if row < 5: if word[0] not in failures: if addWord(boardName, word[0], row) is True: # print("This is the row we added: ", row) # printBoard(boardName) row = row + 1 print('new row ', row) loop_count = 0 # failures = [] loop_count += 1 if loop_count > 1 and row != 0: print('did not make it') print('this is the row ', row) printBoard(boardName) print('this is possibilities: ') print(possibilties) row -= 1 removeWord(boardName, row, failures) loop_count = 0 elif loop_count > 1 and row == 0: failures = [] print('failure') # using random shuffle controls for situations where the possiblities cannot work with code random.shuffle(possibilties) return boardName def removeWord(aboard, row=0, failures=[]): """ Method to remove a word""" removalWord = '' # if aboard[row] == ["_", "_", "_", "_", "_"]: # print("Throught if filter") for position in range(0, 5): # add word to new empty row removalWord = removalWord + aboard[row][position] # print(removalWord) failures.append(removalWord) aboard[row] = ["_", "_", "_", "_", "_"] print(failures) def addWord(aboard, word, row=0): """ Method to check and see if a word can be added""" # print("entering add word: ", word) # print("this is row:", row) # print("this is board[row]: ", aboard[row]) #if aboard[row] == ["_", "_", "_", "_", "_"]: #print("Throught if filter") for position in range(0, 5): # add word to new empty row letter = word[position] aboard[row][position] = letter vWord0 = "" vWord1 = "" vWord2 = "" vWord3 = "" vWord4 = "" word_true = [0, 0, 0, 0, 0] # creates an array with 0 bools in each position. # We will know our word doesn't fit if there are any 0's at the end. for row in range(0, row + 1): # construct the beginning of each column word for column in range(0, 5): if column == 0: vWord0 = vWord0 + aboard[row][column] # print('this is vWord0: ', vWord0) if column == 1: vWord1 = vWord1 + aboard[row][column] # print('this is vWord1: ', vWord1) if column == 2: # print("This is vWord2: ", vWord2) vWord2 = vWord2 + aboard[row][column] # print("This is vWord2: ", vWord2) if column == 3: # print("This is vWord3: ", vWord3) vWord3 = vWord3 + aboard[row][column] # print("This is vWord3: ", vWord3) if column == 4: # print("This is vWord4: ", vWord4) vWord4 = vWord4 + aboard[row][column] # print("This is vWord4: ", vWord4) for element in possible_words: # print("Ths is element word: ", element[0]) if vWord0 in element[0]: # print("word0 is in") word_true[0] = 1 if vWord1 in element[0]: # print("vword1 is in: ", vWord1) word_true[1] = 1 if vWord2 in element[0]: # print("vword2 is in: ", vWord2) word_true[2] = 1 if vWord3 in element[0]: word_true[3] = 1 if vWord4 in element[0]: word_true[4] = 1 # print("this is word_true: ", word_true) if 0 in word_true: # print('no go') for position in range(0, 5): # add word to new empty row aboard[row][position] = "_" return False else: # print("we have a true") row += 1 return True def printBoard(board): for row in board: print(row) # Press the green button in the gutter to run the script. if __name__ == '__main__': print('this is the start') printBoard(board) random.shuffle(possible_words) boardConstructor(possible_words, board, failures) print('this is the end') printBoard(board) # See PyCharm help at https://www.jetbrains.com/help/pycharm/
f826fcf0ba599a8a9547aaed6f41bfc93cab28b6
chaofan-zheng/python_leanring_code
/month01/面向对象/类和对象/day02/demo03-属性各种写法.py
1,184
4
4
""" 属性各种写法 """ """# 读写属性 # 适用性:有一个实例变量,但是需要对读取和写入进行限制 # 快捷键:props + 回车""" class MyClass: def __init__(self, data=0): self.data = data @property def data(self): return self.__data @data.setter def data(self, value): self.__data = value m01 = MyClass(10) print(m01.data) """# 只读属性 # 适用性: 有一个私有变量,不想让别人改,只想让别人拿。只想提供读取功能,不想提供类外修改 # 快捷键 prop + 回车""" class MyClass: def __init__(self, data=0): self.__data = data @property def data(self): return self.__data m01 = MyClass(10) print(m01.data) # m01.data =20 #'MyClass' object has no attribute '_MyClass__data' """ 只写属性 适用性:只需要修改实例变量,不需要读取 快捷键:无 """ class MyClass: def __init__(self, data=0): self.data = data data = property() @data.setter def data(self, value): self.__data = value m01 = MyClass(10) # print(m01.data) # AttributeError: unreadable attribute m01.data = 20
adbd066d244ff11f89e47a5bbd29d4040e1fcfac
HomeroValdovinos/hello-world
/Cursos/devf/Lesson03/position_string.py
134
3.515625
4
my_list = [1, 2, 3, 4, 5, 6] print my_list[2] print my_list[2:5] print my_list[5:] print my_list[:5] print my_list[:]
c4add82b0a1a6c8ab5f3e6e89881ac15f0f82f76
Carvanlo/Python-Crash-Course
/Chapter 9/number_served.py
714
3.671875
4
class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print(self.restaurant_name.title()) print(self.cuisine_type) def open_restaurant(self): print(self.restaurant_name.title() + " is open.") def set_number_served(self, number): self.number_served = number def increment_number_served(self, number): self.number_served += number restaurant = Restaurant('tang', 'chinese') print(restaurant.number_served) restaurant.set_number_served(3) print(restaurant.number_served) restaurant.increment_number_served(20) print(restaurant.number_served)
6d2c6af169b2217822f346f13a9461d8ddc7638d
charanvengatesh/Main-Repo
/Mini-Programs/Python/Numbers to Words.py
5,861
3.921875
4
''' NumWord v2.9.0 ''' print('This is an amazing 5 digit Number to Word Converter\nIt was a 3-day challenge\nHere you go!!\n') num = input(' Number (0 - 99999): ') def Num(Number): Number = str(Number) digit1 = { 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 0:'' } digit2 = { 0:'ten', 1:'eleven', 2:'twelve', 3:'thirteen', 4:'fourteen', 5:'fifteen', 6:'sixteen', 7:'seventeen', 8:'eighteen', 9:'nineteen', } tenth = { 2:'twenty', 3:'thirty', 4:'fourty', 5:'fifty', 6:'sixty', 7:'seventy', 8:'eighty', 9:'ninety' } print('\n______________________________________________\n') if int(Number) == 0: print('zero') Number = Number.lstrip('0') if len(Number) == 1: print(digit1[int(Number)]) elif len(Number) == 2: list(str(Number)) if int(Number) <= 19: print(digit2[int(Number[1])]) elif int(Number) > 19: if int(Number[1]) == 0: print(tenth[int(Number[0])]) else: print(tenth[int(Number[0])] + ' ' + digit1[int(Number[1])]) elif len(Number) == 3: list(str(Number)) if int(Number[1]) == 0: if int(Number[2]) == 0: print(digit1[int(Number[0])] + ' hundred ' ) else: print(digit1[int(Number[0])] + ' hundred and ' + digit1[int(Number[2])]) elif int(Number[1]) == 1: print(digit1[int(Number[0])] + ' hundred and ' + digit2[int(Number[2])]) else: print(digit1[int(Number[0])] + ' hundred and ' + tenth[int(Number[1])] + ' ' + digit1[int(Number[2])]) elif len(Number) == 4: list(str(Number)) if int(Number[1]) == 0 and int(Number[2]) == 0 and int(Number[3]) == 0: print(digit1[int(Number[0])] + ' thousand ' ) elif int(Number[1]) == 0 and int(Number[2]) == 0: print(digit1[int(Number[0])] + ' thousand and ' + digit1[int(Number[3])]) elif int(Number[1]) == 0: if int(Number[2]) == 1: print(digit1[int(Number[0])] + ' thousand and '+ digit2[int(Number[3])]) else: print(digit1[int(Number[0])] + ' thousand and '+ tenth[int(Number[2])] + ' ' + digit1[int(Number[3])]) elif int(Number[2]) == 1: print(digit1[int(Number[0])] + ' thousand ' + digit1[int(Number[1])] + ' hundred and ' + digit2[int(Number[3])]) elif int(Number[2]) == 0: print(digit1[int(Number[0])] + ' thousand ' + digit1[int(Number[1])] + ' hundred and ' + digit1[int(Number[3])]) else: print(digit1[int(Number[0])] + ' thousand ' + digit1[int(Number[1])] + ' hundred and ' + tenth[int(Number[2])] + ' ' + digit1[int(Number[3])]) elif len(Number) == 5: list(str(Number)) if int(Number[2]) == 0 and int(Number[3]) == 0 and int(Number[4]) == 0: if int(Number[0]) == 1: print(digit2[int(Number[1])] + ' thousand ') elif int(Number[0]) != 1: if int(Number[1]) == 0: print(tenth[int(Number[0])] + ' thousand') elif int(Number[1]) != 0: print(tenth[int(Number[0])] + ' ' + digit1[int(Number[1])]+ ' thousand') elif int(Number[2]) == 0 and int(Number[3]) == 0: if int(Number[0]) == 1: print(digit2[int(Number[1])] + ' thousand and ' + digit1[int(Number[4])]) elif int(Number[0]) != 1: print(tenth[int(Number[0])] + ' ' + digit1[int(Number[1])] + ' thousand and ' + digit1[int(Number[4])]) elif int(Number[3]) == 0 and int(Number[4]) == 0: if int(Number[0]) == 1: print(digit2[int(Number[1])] + ' thousand and ' + digit1[int(Number[2])] + ' hundred') elif int(Number[0]) != 1: print(tenth[int(Number[0])] + ' ' + digit1[int(Number[1])] + ' thousand and ' + digit1[int(Number[2])] + ' hundred') elif int(Number[2]) == 0: if int(Number[0]) == 1: if int(Number[3]) == 1: print(digit2[int(Number[1])] + ' thousand and '+ digit2[int(Number[4])]) else: print(digit2[int(Number[1])] + ' thousand and '+ tenth[int(Number[3])] + ' ' + digit1[int(Number[4])]) else: if int(Number[3]) == 1: print(tenth[int(Number[0])] + ' ' + digit1[int(Number[1])] + ' thousand and ' +digit2[int(Number[4])]) else: print(tenth[int(Number[0])] + ' ' + digit1[int(Number[1])] + ' thousand and '+ tenth[int(Number[3])] + ' ' + digit1[int(Number[4])]) else: if int(Number[0]) == 1: if int(Number[3]) == 1: print(digit2[int(Number[1])] + ' thousand ' + digit1[int(Number[2])] + ' hundred and ' + digit2[int(Number[4])]) elif int(Number[3]) == 0: print(digit2[int(Number[1])] + ' thousand ' + digit1[int(Number[2])] + ' hundred and ' + digit1[int(Number[4])]) else: print(digit2[int(Number[1])] + ' thousand ' + digit1[int(Number[2])] + ' hundred and ' + tenth[int(Number[3])] + ' ' + digit1[int(Number[4])]) else: if int(Number[3]) == 1: print(tenth[int(Number[0])] + ' ' + digit1[int(Number[1])] + ' thousand ' + digit1[int (Number[2])] + ' hundred and '+digit2[int(Number[4])]) elif int(Number[3]) == 0: print(tenth[int(Number[0])] + ' ' + digit1[int(Number[1])] + ' thousand ' + digit1[int(Number[2])] + ' hundred and ' + digit1[int(Number[4])]) else: print(tenth[int(Number[0])] + ' ' + digit1[int(Number[1])] + ' thousand ' + digit1[int(Number[2])] + ' hundred and ' + tenth[int(Number[3])] + ' ' + digit1[int(Number[4])]) print('______________________________________________') Num(num)
14c4826d2f6903432d3da2eee1c97e62191b2d2a
Faikavi/HW1_Image-Processing
/etc_function.py
415
3.5
4
def createHistogram(converted_img): grey_level = [] frequency = [] histogram = {} for i in range(len(converted_img)): if converted_img[i] not in grey_level: grey_level.append(converted_img[i]) grey_level.sort() for i in range(len(grey_level)): frequency.append(converted_img.count(grey_level)) histogram = dict(zip(grey_level, frequency)) return histogram
29ea61555556ef84eb71f88b4d76dcdcdc48a63c
teenitiny/py-exercise
/algorithm/stack_algo.py
2,028
3.734375
4
""" Evaluating Postfix Expressions Create a new stack While there are more tokens in the expressioin Get the next token if the token is an operand Push the operand onto the stack Else if the token is an operator Pop the two operands from the stack Apply the operator to the two operands just opped Push the resulting value onto the stack """ """ Converting Infix to Postfix 1. Start with an empty postfix expression and an empty stack, which will hold operators and left parentheses. 2. Scan across the infix expression from left to right. 3. On encountering an operand, append it to the postfix expression. 4. On encountering a left parenthesis, push it onto the stack. 5. On encountering an operator, pop off the stack all operator that have equal or higher precedence, append them to the postfix expression, and then push te scanned operator onto the stack 6. On encountering a right parenthesis, shift operators from the stack to the postfix expression until meeting the matching left parenthesis, which is discarded. 7. On encountering the end of the infix expression, transfer the remaining operators from the stack to the postfix expression """ """ BackTracking stack Create an empty stack Push the starting state onto the stack While the stack is not empty Pop the stack and exmine the state if the state represents an ending state Return SUCCESSFUL CONCLUSION Else if the state has not been visited previously Mark the state as visited Push onto the stack all unvisited adjacent states Return UNSUCCESSFUL CONCLUSION Instantiate a stack Locate the character "P" in the grid Push its location onto the stack While the stack is not empty Pop location. (row, colum), off the stack if the grid contains "T" at this location, then A path has been found Return True Else if this location does not contain a dot Place a dot in the grid at this location Examine the adjacent cells to this one and for each one that contains a space. push its location onto the stack Return False """
334f08eb931bac3a6aa8fc9320188f76adfcfd39
Dagmoores/PythonStudies
/Projeto_Integrador_Estudos/problema_pratico3-3.py
821
3.9375
4
#Retirado do livro Introdução à Computação em Python - Um Foco no Desenolvimento de Aplicações - PERKOVIC, Ljubomir #Traduza estas declarações em instruções if/else do Python: #(a)Se ano é divisível por 4, exiba 'Pode ser um ano bissexto.'; caso contrário, exiba 'Definitivamente não é um ano bissexto.' #(b)Se a lista bilhete é igual à lista loteria, exiba 'Você ganhou!'; se não, exiba 'Melhor sorte da próxima vez…'. #Resolução (a) ano = eval(input('Em que ano estamos? ')) if ano % 4 ==0: print('Pode ser um ano bissexto.') else: print('Definitivamente não é um ano bissexto.') #Resolução (b) bilhete = eval(input('Quais os números do seu bilhete? ')) loteria = [10, 23, 54, 56] if bilhete == loteria: print('Você ganhou!') else: print('Melhor sorte da próxima vez…')
941c4c67aede72d0887d7527e5038b1b003e5774
dwillia2/pythonStuff
/modules/printModule.py
126
3.859375
4
def printNoNewLine(string): print(string, end = "") def reverseString(string): tempString = string[::-1] return tempString
3cac1017099644cbb46869b1a43ba752bbcc1978
arslanislam845/DevNation-Python-assignments
/5.May26/q4.py
839
4.03125
4
import math def Factors(x): print("Factors of the given number is : ") for i in range(1,x+1): if x % i==0: print(i) def primeFactors(n): print("Prime factors of the given number is : ") while n % 2 == 0: print (2) n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: print (i) n = n / i if n > 2: print (n) def is_prime(n1): print("True for prime number and false for not a prime number : ") if n1==1: return False elif (n1==2): return True; else: for x in range(2,n1): if(n1 % x==0): return False return True y=input("Enter the number : ") y=int(y) a=print(is_prime(y)) Factors(y) primeFactors(y)
6b54c8b15680678196904f7ab4f8a99b8977d141
luizdefranca/Curso-Python-IgnoranciaZero
/Aulas Python/Exercícios Extras/Python Brasil/3 - Estrutura de Repetição/Ex 44.py
1,351
4.1875
4
""" 44. Em uma eleição presidencial existem quatro candidatos. Os votos são informados por meio de código. Os códigos utilizados são: o 1 , 2, 3, 4 - Votos para os respectivos candidatos o (você deve montar a tabela ex: 1 - Jose/ 2- João/etc) o 5 - Voto Nulo o 6 - Voto em Branco Faça um programa que calcule e mostre: o O total de votos para cada candidato; o O total de votos nulos; o O total de votos em branco; o A percentagem de votos nulos sobre o total de votos; o A percentagem de votos em branco sobre o total de votos. Para finalizar o conjunto de votos tem-se o valor zero. """ print("1 - Jose\n2 - João\n3 - Pedro\n4 - Joana") jose = joao = pedro = joana = nulo = branco = 0 voto = int(input("Digite seu voto: ")) while voto != 0: if voto == 1: jose += 1 elif voto == 2: joao += 1 elif voto == 3: pedro += 1 elif voto == 4: joana += 1 elif voto == 5: nulo += 1 else: branco += 1 voto = int(input("Digite seu voto: ")) print("Total de Votos: ") print("Jose:", jose) print("João:", joao) print("Pedro:", pedro) print("Joana:", joana) print("Nulo:", nulo) print("Branco:", branco) total = jose+joao+pedro+joana+nulo+branco print("Porcentagem de Votos nulos: %g%%"%(100*nulo/total)) print("Porcentagem de Votos brancos: %g%%"%(100*branco/total))
26cb6dacb4eaaa19c81c50f20f3867e6158dd0d7
ArhiTegio/GB-Python-Basic_2
/Lesson_2/03.Months.py
960
3.8125
4
print('Выбор месяца но номеру') check_months = frozenset(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']) months_dict = {'1': 'Январь', '2': 'Февраль', '3': 'Март', '4': 'Апрель', '5': 'Май', '6': 'Июнь', '7': 'Июль', '8': 'Август', '9': 'Сенябрь', '10': 'Октябрь', '11': 'Ноябрь', '12': 'Декабрь'} months_list = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сенябрь', 'Октябрь', 'Ноябрь', 'Декабрь'] n = '' while True: n = input('Введите номер месяца: ') if n.isdigit() and n in check_months: print('Значение по листу: ' + months_list[int(n) - 1]) print('Значение по словарю: ' + months_dict[n]) break else: if n == '': break
4f5d64ba60ddd719331d54f514a6154d6c1b6081
karuns/pylearn
/oop/CatClass.py
268
3.5625
4
class Cat: number = 0 def __init__(self,color,legs): self.color = color self.legs = legs felix = Cat("red",4) felix.number = felix.number+2 print felix.color print felix.legs garf =Cat("b",3) Cat.number = Cat.number+1 print Cat.number
e48318e1dc8b9e8e57699af9d4654f3f9403ddf0
akjalbani/Test_Python
/Misc/Network/validate_ip.py
341
3.796875
4
def validate_ip(addr): a = addr.split('.') if len(a) != 4: return False for x in a: if not x.isdigit(): return False i = int(x) if i < 0 or i > 255: return False return True addr=input("Enter the IP address:") address=validate_ip(addr) if address: print('Valid IP') else: print("Invalid IP")
bff6baaaf2c7d54fa533569433574a815a70603b
t0mm4rx/ftprintfdestructor
/inputs.py
2,306
3.640625
4
import random import string def random_string(length): letters = string.ascii_letters + string.digits + " " return ''.join(random.choice(letters) for i in range(length)) def input_string(): choice = random.choice([0, 1, 2]) if (choice == 0): return '"{}"'.format(random_string(random.randint(1, 100))) if (choice == 1): return "NULL" if (choice == 2): return '""' def input_uint(): return str(random.randint(0, 2147483647)) def input_short_uint(): return str(random.randint(0, 100)) def input_int(): choice = random.choice([0, 1, 2, 3]) if (choice == 0): return str(random.randint(-2147483648, 2147483647)) if (choice == 1): return str(2147483647) if (choice == 2): return str(-2147483647) if (choice == 3): return str(0) def input_char(): choice = random.choice([0, 1]) if (choice == 0): return "'" + random.choice(string.ascii_letters + string.digits) + "'" if (choice == 1): return "'\\0'" def random_arg(): format = "%" data = [] choices = ["s", "c", "i", "d", "x", "X", "%", "u"] width = "" size = "" flags = "" type = random.choice(choices) if (random.random() > .5): if (random.random() > .8): width = "*" data.append(str(random.randint(-10, 10))) else: width = str(random.randint(1, 20)) if (random.random() > .5): if (random.random() > .8): size = ".*" if (type != "%" and type != "c"): data.append(str(random.randint(-10, 10))) else: size = "." + str(random.randint(0, 5)) choice = random.choice([0, 1, 2]) if (choice == 0): flags = "" elif (choice == 1): flags = "-" else: flags = "0" if (type == "s"): format += flags.replace("0", "") format += width format += size data.append(input_string()) if (type == "c"): format += flags.replace("0", "") format += width data.append(input_char()) if (type == "i" or type == "d"): format += flags format += width format += size data.append(input_int()) if (type == "x"): format += flags format += width format += size data.append(input_int()) if (type == "X"): format += flags format += width format += size data.append(input_int()) if (type == "%"): data = [] data.append("") if (type == "u"): format += flags format += width format += size data.append(input_int()) format += type return (format, data)
f13e9a92a05f1945b6a17e947a57ad93d49f2dde
kirankhandagale1/Python_training
/Excercise2/p2_1.py
394
3.734375
4
# Write the program to print vowels and consonant letters from gnulinux. while True: print("....print only constant and vowels...") input1=raw_input("Enter the char.....") if(input1>='0' and input1<='9'): print("costant no = ",input1) elif(input1=='a' or input1=='e' or input1=='i' or input1=='o' or input1=='u'): print("These is vowels = ",input1) else: print("unkonown choice..")
feeade4ea30a3df0b610d1c7f77b12e57cdb6903
runzezhang/Code-NoteBook
/lintcode/1266-find-the-difference.py
1,018
3.703125
4
# Description # 中文 # English # Given two strings s and t which consist of only lowercase letters. # String t is generated by random shuffling string s and then add one more letter at a random position. # Find the letter that was added in t. # Have you met this question in a real interview? # Example # Example: # Input:s = "abcd",t = "abcde" # Output:'e' # Explanation:'e' is the letter that was added. class Solution: """ @param s: a string @param t: a string @return: the letter that was added in t """ def findTheDifference(self, s, t): # Write your code here s = sorted(s) t = sorted(t) print(s,t) for i in range(len(s)): if s[i] != t[i]: return t[i] return t[-1] # flag = 0 # for i in range(len(s)): # # 计算每一位字符的Ascll码之差 # flag += (ord(t[i]) - ord(s[i])) # flag += ord(t[-1]) # return chr(flag)
3ed66bda5cafffea672259efef5e1c92b2c219c3
suryak24/python-code
/45.py
95
3.6875
4
n=int(input("Enter the number:")) count=1 while count<=n: n=n/10 count+=1 print(count)
f8e09d8c55630500086d544b45fba87f76c2afcb
Picolino66/resmat-1-2
/Resmat1/amador e carol/carol.py
7,358
3.78125
4
from math import* #importa funções matemáticas import math print ("Digite o nome do arquivo: ") nome_arq=input() arquivo = nome_arq + '.dat' #junção de string para ler o nome_arq do escrita carregar = open(arquivo, 'r') #abrir escrita para carregar #ler as entradas do escrita figuras = int(carregar.readline()) arestas = 0 arestas_fig=[] for i in range(figuras): aux = int(carregar.readline()) arestas_fig.append(aux) arestas = arestas + arestas_fig[i] ponto_x=[] ponto_y=[] for i in range(arestas): x, y = map(float, carregar.readline().split()) ponto_x.append(x) ponto_y.append(y) unidade = str(carregar.readline()) salvar = nome_arq + '.out' escrita = open(salvar,'w')#abrir para escrever no escrita escrita.write("Propriedades Geométricas da Figura") escrita.write ("\n") escrita.write(" NÚMERO DE CONTORNOS NA FIGURA: ") escrita.write(str(figuras)) escrita.write ("\n") escrita.write(" NÚMERO TOTAL DE VÉRTICES: ") escrita.write(str(arestas)) escrita.write ("\n") escrita.write ("\n") i=0 j=0 percorre=0 #percorre a figura fim=0 #fim identifica quando a figura estiver na ultimo ponto para poder fechar com o primeiro ponto inicio=0 #inicio armazena a posição inicial da figura area=[] perimetro=[] total_area=0.0 total_perimetro=0.0 area.append(0.0) perimetro.append(0.0) soma_area=0.0 soma_perimetro=0.0 #cacluco centro de gravidade ponto_x,ponto_y centro_gravidade_x=[] total_gravidade_x=0.0 centro_gravidade_y=[] total_gravidade_y=0.0 centro_gravidade_x.append(0.0) centro_gravidade_y.append(0.0) soma_gravidade_x=0 soma_gravidade_y=0 #laço para fazer as equações for i in range(figuras): for j in range(arestas_fig[i]): if(fim==(arestas_fig[i]-1)): soma_perimetro+=sqrt(((ponto_x[inicio]-ponto_x[percorre])**2)+((ponto_y[inicio]-ponto_y[percorre])**2)) soma_area+=ponto_x[percorre]*ponto_y[inicio]-ponto_x[inicio]*ponto_y[percorre] soma_gravidade_x+=((ponto_x[percorre]+ponto_x[inicio])*(ponto_x[percorre]*ponto_y[inicio]-ponto_x[inicio]*ponto_y[percorre])) soma_gravidade_y+=((ponto_y[percorre]+ponto_y[inicio])*(ponto_x[percorre]*ponto_y[inicio]-ponto_x[inicio]*ponto_y[percorre])) else: soma_perimetro+=sqrt(((ponto_x[percorre+1]-ponto_x[percorre])**2)+((ponto_y[percorre+1]-ponto_y[percorre])**2)) soma_area+=ponto_x[percorre]*ponto_y[percorre+1]-ponto_x[percorre+1]*ponto_y[percorre] soma_gravidade_x+=((ponto_x[percorre]+ponto_x[percorre+1])*(ponto_x[percorre]*ponto_y[percorre+1]-ponto_x[percorre+1]*ponto_y[percorre])) soma_gravidade_y+=((ponto_y[percorre]+ponto_y[percorre+1])*(ponto_x[percorre]*ponto_y[percorre+1]-ponto_x[percorre+1]*ponto_y[percorre])) percorre+=1 fim+=1 perimetro.append(soma_perimetro) area.append(soma_area) fim=0 inicio=arestas_fig[i]+inicio soma_area=0 soma_perimetro=0 centro_gravidade_x.append(soma_gravidade_x) centro_gravidade_y.append(soma_gravidade_y) soma_gravidade_x=0 soma_gravidade_y=0 for i in range(len(area)):#somar area,somar perimetro total_area+=area[i] total_perimetro+=perimetro[i] total_gravidade_x+=centro_gravidade_x[i] total_gravidade_y+=centro_gravidade_y[i] total_area*=0.5 total_gravidade_x/=(6*total_area) total_gravidade_y/=(6*total_area) escrita.write("A area da sua figura e: ") escrita.write("{:.6f}".format(total_area)) escrita.write(unidade+'² \n') escrita.write("O perimetro de sua figura e: ") escrita.write("{:.6f}".format(total_perimetro)) escrita.write(unidade+'\n') escrita.write("Coordenada do CG no eixo ponto_x: ") escrita.write("{:.6f}".format(total_gravidade_x)) escrita.write(unidade+' \n') escrita.write("Coordenada do CG no eixo ponto_y: ") escrita.write("{:.6f}".format(total_gravidade_y)) escrita.write(unidade+' \n') #momento inercia for i in range(arestas): ponto_x[i] = ponto_x[i] - total_gravidade_x ponto_y[i] = ponto_y[i] - total_gravidade_y inerciaX=[] totalinerciaX=0.0 inerciaY=[] totalinerciaY=0.0 produtoinercia=[] totalprodutoinercia=0.0 a=[] percorre=0 fim=0 inicio=0 inerciaX.append(0.0) inerciaY.append(0.0) produtoinercia.append(0.0) somaix=0 somaiy=0 somaixy=0 ax=0 for i in range(figuras): for j in range(arestas_fig[i]): if(fim==(arestas_fig[i]-1)): ax=((ponto_x[percorre]*ponto_y[inicio])-(ponto_x[inicio]*ponto_y[percorre])) a.append(ax) somaix+=a[percorre]*(pow(ponto_y[percorre],2)+ponto_y[percorre]*ponto_y[inicio]+pow(ponto_y[inicio],2)) somaiy+=a[percorre]*(pow(ponto_x[percorre],2)+ponto_x[percorre]*ponto_x[inicio]+pow(ponto_x[inicio],2)) somaixy+=a[percorre]*(ponto_x[percorre]*ponto_y[inicio]+2*ponto_x[percorre]*ponto_y[percorre]+2*ponto_x[inicio]*ponto_y[inicio]+ponto_x[inicio]*ponto_y[percorre]) else: ax=((ponto_x[percorre]*ponto_y[percorre+1])-(ponto_x[percorre+1]*ponto_y[percorre])) a.append(ax) somaix+=a[percorre]*(pow(ponto_y[percorre],2)+ponto_y[percorre]*ponto_y[percorre+1]+pow(ponto_y[percorre+1],2)) somaiy+=a[percorre]*(pow(ponto_x[percorre],2)+ponto_x[percorre]*ponto_x[percorre+1]+pow(ponto_x[percorre+1],2)) somaixy+=a[percorre]*(ponto_x[percorre]*ponto_y[percorre+1]+2*ponto_x[percorre]*ponto_y[percorre]+2*ponto_x[percorre+1]*ponto_y[percorre+1]+ponto_x[percorre+1]*ponto_y[percorre]) percorre+=1 fim+=1 fim=0 inicio=arestas_fig[i]+inicio inerciaX.append(somaix) inerciaY.append(somaiy) produtoinercia.append(somaixy) somaix=0 somaiy=0 somaixy=0 for i in range(len(inerciaX)): totalinerciaX+=inerciaX[i] totalinerciaY+=inerciaY[i] totalprodutoinercia+=produtoinercia[i] totalinerciaX = totalinerciaX/12 totalinerciaY = totalinerciaY/12 totalprodutoinercia = totalprodutoinercia/24 momentoinercia = totalinerciaY + totalinerciaX escrita.write("Momento de inercia em ponto_x: ") escrita.write("{:.6f}".format(totalinerciaX)) escrita.write(unidade+'4 \n') escrita.write("Momento de inercia em ponto_y: ") escrita.write("{:.6f}".format(totalinerciaY)) escrita.write(unidade+'4 \n') escrita.write("Produto de inercia em xy: ") escrita.write("{:.6f}".format(totalprodutoinercia)) escrita.write(unidade+'4 \n') escrita.write("Momento Polar de Inercia: ") escrita.write("{:.6f}".format(momentoinercia)) escrita.write(unidade+'4 \n') inerciamax = (totalinerciaX+totalinerciaY)/2 + sqrt(((totalinerciaX-totalinerciaY)/2)**2+(totalprodutoinercia**2)) inerciamin = (totalinerciaX+totalinerciaY)/2 - sqrt(((totalinerciaX-totalinerciaY)/2)**2+totalprodutoinercia**2) escrita.write("A inercia minima de sua figura é: ") escrita.write("{:.6f}".format(inerciamin)) escrita.write(unidade+'4 \n') escrita.write("A inercia maxima de sua figura é: ") escrita.write("{:.6f}".format(inerciamax)) escrita.write(unidade+'4 \n') teta1 = (math.atan(-totalprodutoinercia/((totalinerciaX-totalinerciaY)/2)))/2 teta1 = teta1*180/math.pi teta2 = teta1 + 90 escrita.write("O Teta1 de sua figura é: ") escrita.write("{:.6f}".format(teta1)) escrita.write("º") escrita.write('\n') escrita.write("O Teta2 de sua figura é: ") escrita.write("{:.6f}".format(teta2)) escrita.write("º") escrita.write('\n') raiomin = sqrt(inerciamin/total_area) raiomax = sqrt(inerciamax /total_area) escrita.write("O raio minimo de giracao: ") escrita.write("{:.6f}".format(raiomin)) escrita.write(unidade+' \n') escrita.write("O raio maximo de giracao: ") escrita.write("{:.6f}".format(raiomax)) escrita.write(unidade+' \n') escrita.close() print ("Arquivo salvo.")
d3c4a30a051ccb8ae4e7abb108c45879733a6749
tzvetandacov/Programming0
/week8/is_increasing.py
182
3.8125
4
def is_increasing(seq): for index in range(0, len(seq) -1): if seq[index] > seq[index + 1]: return False return True print(is_increasing([1,2,3,6,7]))
f21ab28dffd50fa592a13fab5e71f5aca37d4316
mondas-mania/advent-of-code
/2022/Day_1/day1_part2.py
338
3.59375
4
input_file = open('input.txt', 'r') calories_sums = [sum([int(calorie) for calorie in calories.split('\n')]) for calories in input_file.read().strip().split('\n\n')] sorted_calories = sorted(calories_sums, reverse=True) top_three = sorted_calories[0:3] print(f"The top three elves have a total of {sum(top_three)} calories between them.")
be6d9bf14f8297dd36d57ba87fcba5dc63a97825
chenweisomebody126/codebase
/python/log_base/memory_size.py
1,322
3.671875
4
from __future__ import division import sys import psutil def get_object_size(obj, units='Mb'): """Calculate the size of an object. Parameters: obj (obj or str or array): Object. units (str): Units [bytes, Kb, Mb, Gb] Returns: size (float): Size of the object. Examples: >>> get_object_size(7, 'bytes') 24 >>> get_object_size("ABC", 'bytes') 36 """ s_bytes = sys.getsizeof(obj) if units == 'bytes': return s_bytes elif units == 'Kb': return s_bytes/1024 elif units == 'Mb': return s_bytes/1024/1024 elif units == 'Gb': return s_bytes/1024/1024/1024 else: raise AttributeError("Units not correct") def get_ram_memory(units='Mb'): """Get the RAM memory of the current machine. Parameters: units (str): Units [bytes, Kb, Mb, Gb] Returns: size (float): Memory size. Examples: >>> get_ram_memory('Gb') 4.0 """ s_bytes = psutil.virtual_memory()[0] if units == 'bytes': return s_bytes elif units == 'Kb': return s_bytes/1024 elif units == 'Mb': return s_bytes/1024/1024 elif units == 'Gb': return s_bytes/1024/1024/1024 else: raise AttributeError("Units not correct")
e154d1366e2cb527ce0b897002f601b693c50ba2
kalorie/RobotDemo
/demo/MyObject.py
330
3.625
4
class MyObject(object): def __init__(self, name=None): self.name = name def eat(self, what): return '%s eats %s' % (self.name, what) def __str__(self): return self.name def get_variables(self): return {'MY_OBJECT': MyObject('Robot'), 'MY_DICT': {1: 'one', 2: 'two', 3: 'three'}}
f36a12da5fbf437be1bc6128fc84e88e5b46701f
eestevez/swighandles
/testMemory.py
791
3.5625
4
from standard import A,Handle_A, simpleFunction def myfun(mya): ha = mya.handle() count = mya.RefCount() print "Refcount after ha=handle():", count print "\nCreate new handle:" ha2 = Handle_A(mya) count = mya.RefCount() print "Refcount after creating new handle ha2:", count apointer = ha.GetObject() count = apointer.RefCount() print "Refcount after getting object from handle ha:", count apointer2 = ha2.GetObject() count = apointer2.RefCount() print "Refcount after getting object from handle ha2:", count a = A() print "Call myfun" myfun(a) # call a function that requires a handle simpleFunction(a.handle()) # a should not be destructed, as it always holds a own handle to itself print "After call myfun" print "Exit program"
001957658ab4e3eb85397c97ccbaf079c95fb566
ujjwalthapa/Election_results_python
/PyPoll/poll.py
2,345
3.6875
4
#Importing operating software and csv module import os import csv #Creating lists voter_id = list() candidate = list() county = list() #Declaring variable value total_profit = 0 #Set path for the csv file csvpath = "../Resources/election_data.csv" #Open the CSV file with open(csvpath,newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') #for loop to create a new variable row_list next(csvreader) for row in csvreader: row_list= list(row) voter_id.append(row_list[0]) candidate.append(row_list[2]) county.append(row_list[1]) total_vote = (len(voter_id)) candidate_set = set(candidate) print(candidate_set) khan_count = (candidate.count('Khan')) correy_count = (candidate.count('Correy')) li_count = (candidate.count('Li')) otooley_count = (candidate.count('O\'Tooley')) print (otooley_count) print (khan_count) print (li_count) print (total_vote) print('Khan: '+ str((khan_count/total_vote)*100)+ '% ('+str(khan_count)+')') #print('Khan: %.3f\% (%d)'%(((khan_count/total_vote)*100),khan_count)) print('Correy: '+ str((correy_count/total_vote)*100)+ '% ('+str(correy_count)+')') print('Li: '+ str((li_count/total_vote)*100)+ '% ('+str(li_count)+')') print('O\'Tooley: '+ str((otooley_count/total_vote)*100)+ '% ('+str(otooley_count)+')') print ("Winner: Khan") ''' #Election Results #------------------------- Total Votes: 3521001 ------------------------- Khan: 63.000% (2218231) Correy: 20.000% (704200) Li: 14.000% (492940) O'Tooley: 3.000% (105630) ------------------------- Winner: Khan ------------------------- ''' #In this challenge, you are tasked with helping a small, rural town modernize its vote-counting process. (Up until now, Uncle Cleetus had been trustfully tallying them one-by-one, but unfortunately, his concentration isn't what it used to be.) #You will be give a set of poll data called election_data.csv. The dataset is composed of three columns: Voter ID, County, and Candidate. Your task is to create a Python script that analyzes the votes and calculates each of the following: #The total number of votes cast #A complete list of candidates who received votes #The percentage of votes each candidate won #The total number of votes each candidate won #The winner of the election based on popular vote.
3c458282f8fc7dbb9ecc2985aa55ec4a99ce356e
toothless92/linear_gradient_py
/lingradpy.py
4,454
4.09375
4
class Linear_Gradient_Maker(): ''' This module is for calculating the hex color codes of a gradient going through an arbitrary number of colors. The result is a linear gradient between each ajacent color. Written by Mike Reilly. Please contact mreilly92@gmail.com with questions. ''' def __init__(self): # Set empty things self.steps_between = None self.colors = [] self.color_comps = [] def set_number_of_steps(self,steps_between): # Use this method to set the number of steps from color to color. # E.g. a value of '10' with two colors will give 11 total points. # a value of '10' with three colors will give 21 total points. try: # Fix data types self.steps_between = int(steps_between) except: # Handler for non-numbers being entered raise Exception("Error: Number of steps must be an integer.") if self.steps_between == 0: # Can't have zero steps raise Exception("Error: Number of steps cannot be 0.") def add_color(self,color): # Use this method to add more color points (one with each call) # to draw gradients between. try: # Add new color code to list self.colors.append(color) # Test to make sure the value given is 6 characters long if len(self.colors[-1]) != 6: error() # Red, green, and blue values are stored separately. self.color_comps.append({}) self.color_comps[-1]['r'] = int(color[0:2],16) self.color_comps[-1]['g'] = int(color[2:4],16) self.color_comps[-1]['b'] = int(color[4:6],16) except: # Catch errors from converting hex to int, which will # indicate that the user used an incorrect format. raise Exception("Colors must be valid hex color codes in format ######.") def get_linear_gradient(self): # This method returns the list of color codes for the full gradient if self.steps_between is None: raise Exception("Error: Must set number of color steps.") if self.colors == []: raise Exception("Error: Must set colors.") # Initialize empty lists gradient = [""]*(self.number_steps) for rgb in ['r', 'g', 'b']: # Iterate through each color component for block in range(len(self.colors)-1): # Iterate through each gradient segment for i in range(steps_between): # Iterate through each step in the gradient segment if i == 0: # The first step, which is one of the anchor colors code = self.color_comps[block][rgb] else: # Calculate the new RGB values using a linear weighting calculation code = self.color_comps[block][rgb] * (steps_between-i)/steps_between + \ self.color_comps[block+1][rgb] * (i)/steps_between # Append the list element with the hex code. Integers are rounded before conversion. gradient[i+block*steps_between] = gradient[i+block*steps_between] + f"{round(code):02x}" # Do last color value code = self.color_comps[-1][rgb] number_steps = (len(self.colors)-1)*self.steps_between + 1 gradient[self.number_steps-1] = gradient[self.number_steps-1] + f"{round(code):02x}" # Return list of RGB hex code strings return gradient if __name__ == "__main__": # Sample implementation: # Initialize object lin_grad = Linear_Gradient_Maker() # Set number of steps from color to color lin_grad.set_number_of_steps(input("Input number of steps from color to color: ")) # Add color points for the gradient while True: color = input("Input next color code (######). Enter \'n\' to finish: ") if color == 'n': break lin_grad.add_color(color) # Run the method to return the gradient code list gradient = lin_grad.get_linear_gradient() # Print results print("\n") for i in range(len(gradient[1:])+1): print(str(i) + ":\t" + gradient[i])
05989c515b8b27de343a117e0f79996b77e9de15
yangshimin/spider
/设计模式/duck_pattern.py
1,783
3.5
4
from abc import ABCMeta, abstractmethod class QuackBehaivor(metaclass=ABCMeta): @abstractmethod def quack(self): raise NotImplementedError class Quack(QuackBehaivor): def quack(self): print('我是一只会Quack的鸭子') class SQuack(QuackBehaivor): def quack(self): print('我是一只会SQuack的鸭子') class MuteQuack(QuackBehaivor): def quack(self): print('我是一只会MuteQuack的鸭子') class FlyBehaivor(metaclass=ABCMeta): @abstractmethod def fly(self): raise NotImplementedError class FlyWithWing(FlyBehaivor): def fly(self): print('我是一只会fly with wing 的鸭子') class FlyNoWay(FlyBehaivor): def fly(self): print('我是一只fly with no way 的鸭子') class Duck(object): def __init__(self, flytype, quacktype): self.quack = quacktype() self.fly = flytype() def performfly(self): self.quack.quack() def performquack(self): self.fly.fly() def swim(self): print('所有鸭子都会游泳呢~') def othermethod(self): pass class YellowDuck(Duck): def __init__(self, flytype=FlyWithWing, quacktype=Quack): super(YellowDuck, self).__init__(flytype, quacktype) def othermethod(self): print('duck quack with fly') class GreenDuck(Duck): def __init__(self, flytype=FlyNoWay, quacktype=MuteQuack): super(GreenDuck, self).__init__(flytype, quacktype) def othermethod(self): print('duck quack with no quack') if __name__ == '__main__': yellowduck = YellowDuck() yellowduck.performquack() yellowduck.performfly() print('*' * 40) greenduck = GreenDuck() greenduck.performquack() greenduck.performfly()
d7b5069527ede2736fa8d507cdd8ae5cff3f1a3e
HendersonSC/project_B
/projectB.py
4,006
4.15625
4
# COSC 505: Summer 2019 # ProjectB - Group 12 # Damilola Olayinka Akamo # Nicole Callais # Shane Christopher Henderson # Stephen Opeyemi Fatokun # # 07/22/2019 # A python program retrieving lotto data from an internet website, and plotting # the frequency of each number to show the most frequently occuring number. from urllib.request import Request, urlopen from urllib.error import URLError import shutil import tempfile import pandas as pd import matplotlib.pyplot as plt import numpy as np #sfatokun # Tally the occurances of each winning number def count_num(df): count = np.zeros(75,dtype=np.int32) for i in range(1,6): nums = df["ball"+str(i)].values for j in nums: count[j-1] += 1 return count #sfatokun # Tally the occurances of each winning number def count_pb(df): count = np.zeros(75,dtype=np.int32) nums = df["Mega Ball"].values for j in nums: count[j-1] += 1 print(count) return count #ncallais # Extracting the Winning Numbers and Mega Ball data def create_plot(lotto_data_frame): # sfatokun # Getting the frequency of occurrence for each winning number win_count = count_num(df) mega_count = count_pb(df) # Line plot of the Winning Number and Mega Ball ## ncallais plt.title('Winning Lotto Numbers Frequency') nums = np.arange(1,76) print(nums) # Label lines plt.plot(nums, win_count, label='Lotto Numbers') plt.plot(nums, mega_count, label='Megaball') # Label x & y axes plt.ylabel('Frequency') plt.xlabel('Ball Number') ## Add legend in upper right corner plt.legend(prop={'size': 6}, loc="upper right") ### Calculate modes win_mode = win_count.argmax() + 1 win_mode_count = win_count[win_mode] mega_mode = mega_count.argmax() + 1 mega_mode_count = mega_count[mega_mode-1] print(mega_mode,mega_mode_count) ## Plot arrow for mega mode and label mega_label = 'Megaball = '+ str(mega_mode) meg_pos = (mega_mode,mega_mode_count) meg_txt_pos = (mega_mode+4,mega_mode_count*1.15) plt.annotate(s=mega_label, xy=meg_pos, xytext=meg_txt_pos, \ fontsize=8, arrowprops=dict(facecolor='black',shrink=0.05), \ horizontalalignment='left', verticalalignment='top') ## Plot win mode line and label win_label = 'Most frequent = '+ str(win_mode) plt.axvline(x=win_mode, color = 'red') x_text_annotation = plt.annotate(s=win_label, textcoords='axes fraction', \ xy=((win_mode/75)+.1,.95), fontsize=8) ## Show plot plt.show() #shende25 # Get the data from the remote resource def get_file(url): # Try contacting the server and getting the data try: response = urlopen(Request(url)) except URLError as e: # Catch errors related to the URL if hasattr(e, 'reason'): print('Connection failed!') print('Reason: ', e.reason) # Catch errors related to the server elif hasattr(e, 'code'): print('Server Error!') print('Error code: ', e.code) return None # Get the data and store for use as a temporary else: # Setup and return temporary file for holding data data_file = tempfile.NamedTemporaryFile() shutil.copyfileobj(response,data_file) data_file.seek(0) return data_file #shend25 # Get a working data frame with just necessary information def get_work_df(data_file): # Create "master" dataframe df = pd.read_csv(data_file) # For the sake of expedience separate out wining numbers and powerball df_nums = pd.DataFrame(data=df["Winning Numbers"].str.split().to_list(), \ columns=["ball1","ball2","ball3","ball4","ball5"]).astype(np.int8) df_nums["Mega Ball"] = pd.DataFrame(data=df["Mega Ball"]).astype(np.int8) return df_nums #shende25 if __name__ == "__main__": # Get data from remote resource data_file = get_file(input("Enter URL: ",)) if data_file: df = get_work_df(data_file) create_plot(df)
cf3fd7d6d3dfab837dba524bd1c1e9ab213d45ed
Katherinaxxx/leetcode
/502. IPO.py
2,154
3.5625
4
''' Author: Catherine Xiong Date: 2021-09-08 19:16:27 LastEditTime: 2021-09-08 19:33:26 LastEditors: Catherine Xiong Description: 给你 n 个项目。对于每个项目 i ,它都有一个纯利润 profits[i] ,和启动该项目需要的最小资本 capital[i] 。 最初,你的资本为 w 。当你完成一个项目时,你将获得纯利润,且利润将被添加到你的总资本中。 总而言之,从给定项目中选择 最多 k 个不同项目的列表,以 最大化最终资本 ,并输出最终可获得的最多资本。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/ipo 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' # 递归 没有通过所有case class Solution: def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int: if k == 0 or not profits: return w c = capital.pop(0) p = profits.pop(0) return max(self.findMaximizedCapital(k-1, w+p, profits, capital), self.findMaximizedCapital(k, w, profits, capital)) if w >= c else self.findMaximizedCapital(k, w, profits, capital) # 堆排序+贪心 class Solution: def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int: info=list(zip(profits, capital)) info=sorted(info, key=lambda x:x[1]) # 按照所需资本数额从小到大排序 i_proj=0 # 标记下一个应该check的项目编号 n_proj=0 # 记录已经做过的项目数量 prof_available=[] # 保存当前可做的项目对应的收益列表 用heapq插入/弹出 while n_proj<k: # 更新(补充)可做的项目的获益列表 while i_proj<len(info) and w>=info[i_proj][1]: heapq.heappush(prof_available, -info[i_proj][0]) i_proj+=1 # 从当前可做的项目中找到纯利润最大的 if len(prof_available)>0: w+=(-heapq.heappop(prof_available)) n_proj+=1 else: break # 没有可做的项目 则跳出循环 return w
b0811c3831e5d7dfddafbd32f9016bac39192027
divyat09/Stance_Classification_Tweets
/Feature.py
7,380
3.5
4
import re import pandas as pd from collections import Counter ''' #Making the matrix automatically using sklearn vectorizer = CountVectorizer(lowercase=True, stop_words="english") matrix = vectorizer.fit_transform(list_tweets) print matrix.shape ''' #Calculate the count of word specificially when it occurs with the Target def count_word_target(word,target): count=0 index=[] #Taking a subset from data so that only those rows are taken which have target in Local Target column for item in data['Local Target']: item=str(item).lower().replace(" ","") index.append(target in item) data_sub=data[index] #Making list of all tweets tweets_sub=[] for item in data_sub['Tweet']: tweets_sub.append(str(item)) removelist="#" # Lowercase, then replace any non-letter, space, or digit character in the headlines except Hashtag tweets_sub = [re.sub(r'[^\w\s\d'+removelist+']','',t.lower()) for t in tweets_sub] # Replace all spaces in string tweets_sub = [re.sub("\s+", " ", t) for t in tweets_sub] tweets_sub = [re.sub(" ", "", t) for t in tweets_sub] #No of times the word occurs in Tweet column of new data set where all values in Local Target column contain target for item in tweets_sub: if word in item: count=count+1 return count #Calculate the PMI of a knowledge source and determine if it to be selected for the feature set def pmi(word): count=0 pmi_word_t1=0 pmi_word_t2=0 pmi_word_t3=0 pmi_word_t4=0 pmi_word=0 #Total count of word in the Tweet column of data for item in tweets: if word in item: count=count+1 print word,"\t",count,"\n","\n" #Find the PMI of each word with various targets target='babyrights' if count!=0: pmi_word_t1=count_word_target(word,target)/float(count) target='womenrights' if count!=0: pmi_word_t2=count_word_target(word,target)/float(count) target='christianity' if count!=0: pmi_word_t3=count_word_target(word,target)/float(count) target='adoption' if count!=0: pmi_word_t4=count_word_target(word,target)/float(count) #Select the class which has max PMI for word and further checks for PMI pmi_word=max(pmi_word_t1,pmi_word_t2,pmi_word_t3,pmi_word_t4) if pmi_word==pmi_word_t1 and pmi_word>= 0.65 : return word if pmi_word==pmi_word_t2 and pmi_word>= 0.65 : return word if pmi_word==pmi_word_t3 and pmi_word>= 0.65 : return word if pmi_word==pmi_word_t4 and pmi_word>= 0.65 : return word #Return value to show that this word is not right to selected in the feature set return 0 #Build the Feature Set from List of Knowledege Sources def Features(feature_set): features=[] list_total=[] ''' list_words_1=['Medical Care','Liberal','liberalism','Women Health','Health','Profeminist', 'Prochoice','Bodily Autonomy', 'Rapeculture','Rape','Win for women','ReproductiveRights','Reproductive Health','Feminist','Feminism','ReproRights','Right','choose', 'Pregnancy'] list_words_2=['promarriage','Mother Teresa','Death Penalty','Baby','Child','Murder','Kill', 'ProLife' , 'Promurder', 'ProLifeYouth','ProLifeGen','Probaby', 'Protect Voiceless' , 'Life','Protect Life', 'Legalised Murder', 'Human Life', 'Hitler','Humanity', 'Unborn','Voiceless','Human','Innocent'] list_words_3=['God','atheism','atheist','Catholic','Religious','Jesus','Bible','Christian','Church','Prayer'] list_words_4=['Fostering','Adoption','Adopt'] list_hashtag_1=['#SCOTUS','#Feminism','#Rapeculture', '#WomensRights', '#ReproductiveRights', '#MyBodyMyRights', '#Reprojustice','#womensrights', '#Reprorights', '#Rape','#prochoice' '#YourBody', '#AbortionRight','#womenshealth','#prochoice', '#reprohealth',"#RightToChoose"] list_hashtag_2=['#murder', '#voiceless', '#AbortionIsMurder', '#prolife', '#ProLifeYouth','#ProLifeGen', '#killing', '#child', '#Life', '#Mother', '#InnocentLives', '#ProtectLife', '#LifeIsBeautiful', '#AllLivesMatter', '#BlackLivesMatter', '#LifeWins' , '#Unborn' , '#MotherTeresa', '#ISIS'] list_hashtag_3=['#jesus', '#bible', '#God','#Catholic', '#Christian','Christianity'] list_hashtag_4=['#adopt','#adoption'] list_words=list_words_1+list_words_2+list_words_3+list_words_4 list_hashtags=list_hashtag_1+list_hashtag_2+list_hashtag_3+list_hashtag_4 list_total=list_words+list_hashtags # Replace sequences of whitespace and Lowercase list_total = [re.sub("\s", "", t.lower()) for t in list_total] ''' list_total=feature_set for item in list_total: word=pmi(item) if word!=0: features.append(word) return features def stance_feature_set(target): #Making list of all tweets sub_data=data[target==data['Local Target']] sub_tweets=[] for item in sub_data['Tweet']: sub_tweets.append(str(item)) removelist="#" # Lowercase, then replace any non-letter, space, or digit character in the headlines except Hashtag from tweets sub_tweets = [re.sub(r'[^\w\s\d'+removelist+']','',t.lower()) for t in sub_tweets] # Replace sequences of whitespace with a space character from tweets so that we can split it into words using " " sub_tweets = [re.sub("\s+", " ", t) for t in sub_tweets] #Feature Set made by selecting all the words form tweets sub_feature_set = list(set(" ".join(sub_tweets).split(" "))) #Removing StopWords from our feaure set as they are useless and wont yeild much f =open('/home/divyat/Desktop/RTE/Data/TrainingData/stop_words.txt','r') stop_words=f.read().split('\n') sub_feature_set = [w for w in sub_feature_set if w not in stop_words] #Printing the result to a file f=open('/home/divyat/Desktop/RTE/Data/TrainingData/'+target+'.txt','w') for item in sub_feature_set: print item f.write(item+'\n') f.close() def target_feature_set(): #Feature Set made by selecting all the words form tweets feature_set = list(set(" ".join(tweets).split(" "))) #Removing StopWords from our feaure set as they are useless and wont yeild much f =open('/home/divyat/Desktop/RTE/Data/TrainingData/stop_words.txt','r') stop_words=f.read().split('\n') feature_set = [w for w in feature_set if w not in stop_words] #Selecting features with high pmi from list of feature_set features= Features(feature_set) print len(features) #Printing the result to a file f=open('/home/divyat/Desktop/RTE/Data/TrainingData/features.txt','w') for item in features: print item f.write(item+'\n') f.close() #Main Code Starts Here #Making some global variables data=pd.read_excel('/home/divyat/Desktop/RTE/Data/TrainingData/Training_Set_New.xlsx', index_col=None, na_values=['NA'] ) #Making list of all tweets tweets=[] for item in data['Tweet']: tweets.append(str(item)) removelist="#" # Lowercase, then replace any non-letter, space, or digit character in the headlines except Hashtag from tweets tweets = [re.sub(r'[^\w\s\d'+removelist+']','',t.lower()) for t in tweets] # Replace sequences of whitespace with a space character from tweets so that we can split it into words using " " tweets = [re.sub("\s+", " ", t) for t in tweets] #Making features for case of classifying tweeets into their secondary targets target_feature_set() #Making features for specific case of stance analysis after I have classified all tweets into their secondary targets stance_feature_set('Baby Rights') stance_feature_set('Women Rights') stance_feature_set('Christianity') stance_feature_set('Adoption') stance_feature_set('Abortion') stance_feature_set('Other')
c9c54ae12c2f4a129034887957baf6f94452221d
gitHirsi/PythonNotes
/001基础/019面向对象_继承/04子类重写父类的同名属性和方法.py
894
3.875
4
""" @Author:Hirsi @Time:2020/6/11 23:44 """ # 师傅类 class Master(object): def __init__(self): self.kongfu = '《独门煎饼果子大法》' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子') # 学校类 class School(object): def __init__(self): self.kongfu = '《乾坤煎饼果子大法》' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子') # 子类重写父类的同名属性和方法 结论: 如果子类和父类有同名属性和方法,子类创建对象调 # 用属性和方法的时候,调用的是子类里面的 class Prentice(School, Master): def __init__(self): self.kongfu = '《独创煎饼果子大法》' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子') hirsi = Prentice() hirsi.make_cake()
9bcbd59a957b7099af4c4ded107d4cbf13bc02f6
imZTY/mydemo
/try-learn.python/project/docx2html/test.py
444
3.5
4
# -*- coding:utf-8 -*- import re def f(x): if x>=6: return 0; return x * x r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print type(r) l=list(r) print r print l #m=input("birthday:") #print m def abcd(m): print m.group() print "Ƚķ" return "111111111111111" abc="<img src='dasdadsa.jpg'/>12312312" match_number=re.compile(r'<img.*?/>') dadasdasd=match_number.sub(abcd,abc) print "--------------------" print dadasdasd
3862a86b753c67b220800ee8c661f5f91298fbc5
88b67391/AlgoSolutions
/python3-leetcode/leetcode009-leetcode9-palindrome-number.py
338
3.734375
4
class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False else: str0 = str(x) reversedStr = str0[::-1] if reversedStr == str0: return True return False # Below is testing sol = Solution() print(sol.isPalindrome(616))
c440163228ee19440664cacfd30e3cfbf5bff61b
Akhil-64/Data-structures-using-Python
/Assignment Recursion 3.py
1,357
3.578125
4
#Q3. Finding the length of connected cells of 1’ s (regions) in an matrix of 0s and 1’s. def Safe(m, row, col, visited): #function to check if a given row,col can be included in DFS return ((row >= 0) and (row < row1) and(col >= 0) and (col < col1) and (m[row][col] and not visited[row][col])) def DFS(m, row, col, visited, count): #function to do DFS for a 2D boolean matrix. It only considers the 8 neighbours as adjacent vertices rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] visited[row][col] = True for k in range(8): if (Safe(m, row + rowNbr[k],col + colNbr[k], visited)): count[0] += 1 DFS(m, row + rowNbr[k], col + colNbr[k], visited, count) def largestRegion(M): #this is the main function that returns the largest region in the given 2d matrix visited = [[0] * col1 for i in range(row1)] result = -999999999999 for i in range(row1): for j in range(col1): if (M[i][j] and not visited[i][j]): count = [1] DFS(M, i, j, visited , count) result = max(result , count[0]) return result row1 = 5 col1 = 5 M = [[1,1,0,0,0], [0,1,1,0,0], [0,0,1,0,1], [1,0,0,0,1], [0,1,0,1,1]] print(largestRegion(M))
69447c2b042f1836baa7c7cec42a96f4bc871b10
tommydo89/CTCI
/8. Recursion and Dynamic Programming/permutationWithDups.py
674
4.03125
4
# Write a method to compute all permutations of a string whose characters are not necessarily unique. The list of permutations should not have duplicates. def permutations(string): results = [] recursivePermutation(list(set(string)), [], results) return results def recursivePermutation(remaining, permutation, results): if len(permutation) > 0: results.append(permutation) if len(remaining) == 0: # if there are no more letters, end the recursion return for char in remaining: copy_remaining = remaining[:] copy_remaining.remove(char) # remove the current character from the copy recursivePermutation(copy_remaining, permutation[:] + [char], results)
7563e483382a3bdedfe13cf2c4924a569db4553f
jihongsheng/python3
/python入门/day_2_列表/2-4-使用方法sort()对表进行永久性排序.py
865
4.0625
4
# -*- coding: UTF-8 -*- # "Python方法sort() 让你能够较为轻松地对列表进行排序。假设你有一个汽车列表, # 并要让其中的汽车按字母顺序排列。为简化这项任务,我们假设该列表中的所有值都是小写的。" cars = ['bmw', 'audi', 'toyota', 'subaru'] # 方法sort();永久性地修改了列表元素的排列顺序。现在,汽车是按字母顺序排列的,再也无法恢复到原来的排列顺序: cars.sort() print(cars) print("-" * 80) # 你还可以按与字母顺序相反的顺序排列列表元素,为此,只需向sort() 方法传递参数reverse=True 。 # 下面的示例将汽车列表按与字母顺序相反的顺序排列: cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort(reverse=True) print(cars) print("-" * 80) # 同样,对列表元素排列顺序的修改是永久性的:
7308e97300e43706e907f0f7439ae3386a190fa2
BrandonHung343/Hack112
/circle.py
2,915
3.578125
4
import pygame from pygameGame import * import math, string, copy, time, random import numpy as np def remove_holes(surface, background=(0, 0, 0)): """ Removes holes caused by aliasing. The function locates pixels of color 'background' that are surrounded by pixels of different colors and set them to the average of their neighbours. Won't fix pixels with 2 or less adjacent pixels. Args: surface (pygame.Surface): the pygame.Surface to anti-aliasing. background (3 element list or tuple): the color of the holes. Returns: anti-aliased pygame.Surface. """ width, height = surface.get_size() array = pygame.surfarray.array3d(surface) contains_background = (array == background).all(axis=2) neighbours = (0, 1), (0, -1), (1, 0), (-1, 0) for row in range(1, height-1): for col in range(1, width-1): if contains_background[row, col]: average = np.zeros(shape=(1, 3), dtype=np.uint16) elements = 0 for y, x in neighbours: if not contains_background[row+y, col+x]: elements += 1 average += array[row+y, col+x] if elements > 2: # Only apply average if more than 2 neighbours is not of background color. array[row, col] = average // elements return pygame.surfarray.make_surface(array) class gameObject(pygame.sprite.Sprite): pass class myProject(PygameGame): def init(self): #circle self.circleList = [] self.angleList = [] def mousePressed(self, x, y): self.createCircle(x,y,random.randint(20,50)) def drawCircle(self, x, y, r, angle, screen): rect = (x-r, y-r, 2*r, 2*r) pygame.draw.arc(screen, (153,153,255), rect, angle + 3*math.pi/4, angle + 5*math.pi/4,10) pygame.draw.arc(screen, (255,153,204), rect, angle + math.pi/4, angle + 3*math.pi/4,10) pygame.draw.arc(screen, (255,255,153), rect, angle + -math.pi/4, angle + math.pi/4, 10) pygame.draw.arc(screen, (153,255,204), rect, angle + -3*math.pi/4, angle + -math.pi/4,10) def timerFired(self, dt): for i in range (len(self.angleList)): self.angleList[i] += 0.05 def createCircle(self,x,y,r): self.circleList.append((x,y,r)) self.angleList.append(0) def redrawAll(self, screen): for i in range (len(self.circleList)): x, y, r = self.circleList[i] angle = self.angleList[i] self.drawCircle(x,y,r, angle, screen) #creating and running the game game = myProject() game.run()
7ec138770513c71dbddc12f66869dbf42b695fe3
zhuxiaodong2019/VIP9Base2
/objecttest/testobject4.py
1,132
3.5
4
# -*- coding: utf-8 -*- ''' @Time    : 2021/1/23 17:37 @Author  : zxd ''' #super #师傅类 class Master(): def __init__(self): self.kongfu = '[五香煎饼果子]' def make_cake(self): print(f'运用{self.kongfu}制作五香#####') #学校继承老师傅类 class School(Master): def __init__(self): self.kongfu = '[香辣煎饼果子]' def make_cake(self): print(f'运用{self.kongfu}制作香辣#####') #super()就是父类的意思 def make_cake2(self): super().__init__() super().make_cake() # scho = School() # scho.make_cake() # scho.make_cake2() #徒弟类 class Prentice(School): def __init__(self): self.kongfu = '[独创煎饼果子]' def make_cake(self): #如果先调用父类的属性和方法,父类的属性方法会覆盖子类的属性方法,故先调用子类的初始化方法 self.__init__() print(f'运用{self.kongfu}制作独创#####') def make_old_cake(self): super().__init__() super().make_cake() xiaoming = Prentice() xiaoming.make_cake() xiaoming.make_old_cake()
40946d2824afc0a38382c8294bbaa6745ad967b2
guntankoba/csv_subtitles
/util_csv.py
423
3.6875
4
# -*- coding:utf-8 -*- import csv def read_csv(file_name): """ [row, row, row]の形式の2次元リストを返す""" file = [] with open(file_name) as f: for row in csv.reader(f): file.append(row) return file def write_csv(file_name, rows): with open(file_name, 'w') as o: writer = csv.writer(o, delimiter=',') for row in rows: writer.writerow(row)
b5cf2bef535359e2e51739d931e7ad75097be528
avengerryan/daily_practice_codes
/eleven_sept/py_set_methods/copy.py
581
4.4375
4
# python set copy() : returns shallow copy of a set # the copy() method returns a shallow copy of the set """ # using = operator numbers = {1, 2, 3, 4} new_numbers = numbers print(new_numbers) """ """ # NOTE: numbers = {1, 2, 3, 4} new_numbers = numbers new_numbers.add(5) print('numbers: ', numbers) print('new_numbers: ', new_numbers) """ # e.g.1: how the copy() method works for sets numbers = {1, 2, 3, 4} new_numbers = numbers.copy() new_numbers.add(5) print('numbers: ', numbers) print('new_numbers: ', new_numbers)
4c0920e80f2c5ccda19dd013942b5edafc69381e
OlegNG86/SkillBoxLessons
/python_homeworks/lesson_005/02_district.py
1,090
3.5
4
# -*- coding: utf-8 -*- # Составить список всех живущих на районе и Вывести на консоль через запятую # Формат вывода: На районе живут ... # подсказка: для вывода элементов списка через запятую можно использовать функцию строки .join() # https://docs.python.org/3/library/stdtypes.html#str.join from district.central_street.house1 import room1 as cent1room, room2 as cent2room from district.central_street.house2 import room1 as r1, room2 as r2 from district.soviet_street.house1 import room1 as sh1r1, room2 as sh1r2 from district.soviet_street.house2 import room1 as sh2r1, room2 as sh2r2 # from district.soviet_street.house1 import room1.folks as rf print('На Центральной улице живут: ') print(', '.join(cent1room.folks + cent2room.folks + r1.folks + r2.folks)) print('\nНа Советской улице живут: ') print(', '.join(sh1r1.folks + sh1r2.folks + sh2r1.folks + sh2r2.folks))
1470c125a2ea5121b3d25173e11714a6219cf5fb
LYoung-Hub/Algorithm-Data-Structure
/insertionSortList.py
1,124
3.953125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None dummy = ListNode('-Inf') dummy.next = head sorted_end = dummy.next inner = dummy.next while sorted_end.next: curr = sorted_end.next sorted_end.next = curr.next if inner.val > curr.val: inner = dummy while inner != sorted_end and inner.next.val < curr.val: inner = inner.next curr.next = inner.next inner.next = curr if inner == sorted_end: sorted_end = curr return dummy.next if __name__ == '__main__': four = ListNode(4) two = ListNode(2) one = ListNode(1) three = ListNode(3) four.next = two two.next = one one.next = three solu = Solution() print solu.insertionSortList(four)
8c8f451a16712caf58a12ec7aae75712b8a11015
reyeskevin9767/modern-python-bootcamp-2018
/36-challenges/05-vowel-count/app.py
645
4.09375
4
# * Exercise ''' vowel_count('awesome') # {'a': 1, 'e': 2, 'o': 1} vowel_count('Elie') # {'e': 2, 'i': 1} vowel_count('Colt') # {'o': 1} ''' # def vowel_count(word): # lower_case_word = word.lower() # new_word = [char for char in lower_case_word if char in "aeiou"] # dict_words = {} # for word in new_word: # if word not in dict_words: # dict_words[word] = 1 # else: # dict_words[word] += 1 # return dict_words def vowel_count(string): lower_s = string.lower() return {letter: lower_s.count(letter) for letter in lower_s if letter in "aeiou"} print(vowel_count('Elie'))
816fe7c6bea4cff60111282b55b7ce1d90c0f836
VIadik/School
/fractal/Cross.py
398
3.734375
4
import turtle def Cross(l, level): if level != 0: Cross(l / 3, level - 1) turtle.left(90) Cross(l / 3, level - 1) turtle.right(90) Cross(l / 3, level - 1) turtle.right(90) Cross(l / 3, level - 1) turtle.left(90) Cross(l / 3, level - 1) else: turtle.forward(l) return Cross(400, 4) turtle.mainloop()
4210e71fb1c3eb6c2c8748e86b2fbc12133f0aa8
kirbylovesfood/Exercises
/Str Char Manipulation.py
1,005
4.15625
4
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> str = "Python is User-friendly" str_split = str.split(" ") print(str) print(str.upper()) #to capitalize the string print(str.lower()) #to put in lowercase the string print(len(str)) print("the string is %d letter long" %len(str)) #to know the size of the string print(str[0]) print(str[1]) print(str[2]) print(str[3]) print(str[4]) print(str[5]) #to call each and every letter in the index print(str[0:6]) #to print everything in the range of index 0-6 print(str_split) #to split it into term print("Do you know that %s is not only cool but %s also %s" %(str_split[0],str_split[1],str_split[2])) str1 = " and is so cool" str2 = ". Python is a general-purpose interpreted, " str3 = "interactive, object-oriented, " str4 = "and high-level programming language" print str + str1 + str2 + str3 + str4
63bbf982c35ac29e353538d562958b87ea7c37f4
meghanagottapu/Leetcode-Solutions
/leetcode_py/Anagrams.py
1,553
3.734375
4
from collections import defaultdict class Solution: # @param {string[]} strs # @return {string[]} def anagrams(self, strs): dict = defaultdict(list) map(lambda s: dict[''.join(sorted(s))].append(s), strs) return [y for x in dict.keys() for y in dict[x] if len(dict[x]) > 1] if __name__ == "__main__": a = Solution() # print a.anagram("django", "naogdj") print a.anagrams(["django", "naogdj"]) print a.anagrams(['a', 'a', 'a']) print a.anagrams(['a', 'abc', 'cba', 'ba', 'ab', 'a', '', '']) print a.anagrams(["", ""]) class Solution: def anagram(self, s, t): # write your code here s = ''.join(sorted(list(s))) t = ''.join(sorted(list(t))) return s == t def anagrams(self, strs): anagram_map, res = {}, [] for str in strs: sorted_str = ''.join(sorted(str)) # list2str if sorted_str in anagram_map: anagram_map[sorted_str].append(str) else: anagram_map[sorted_str] = [str] for anagrams in anagram_map.values(): if len(anagrams) > 1: res += anagrams return res if __name__ == "__main__": a = Solution() # print a.anagram("django", "naogdj") print a.anagrams(["django", "naogdj"]) print a.anagrams(['a', 'a', 'a']) print a.anagrams(['a', 'abc', 'cba', 'ba', 'ab', 'a', '', '']) print a.anagrams(["", ""]) # https://leetcode.com/discuss/18664/sharing-my-very-concise-solution-with-explanation
347b322ee9da33aa02eff04a17614b9fa1b163d7
ljm9748/Algorithm_ProblemSolving
/practice/0406_practice/SWEA_5177_이진 힙_이정민.py
594
3.53125
4
# 트리 자리바꿔주는 함수 def treecheck(last): if last<0: return if tree[last]<tree[last//2]: tree[last],tree[last//2]=tree[last//2],tree[last] treecheck(last//2) # 합계찾는 함수 def findsum(node): global answer if node<1: return answer += tree[node] findsum(node//2) for tc in range(int(input())): N=int(input()) tree = [0]*(N+1) inp=list(map(int, input().split())) for i in range(N): tree[i+1]=inp[i] treecheck(i+1) answer=0 findsum(N//2) print('#{} {}'.format(tc+1,answer))
d5676710d78543e097bc68405335c802651bce5d
edu-athensoft/stem1401python_student
/py200622_python2/day13_py200803/homework/stem1402_python_homework_7_ken.py
1,421
4.28125
4
""" For August 3rd, 2020. Ken. stem1402_python_homeowrk_7_ken idea: ok """ # def pangram_checker(string): def ispangram(string): string = string.lower() # global pangram pangram = True alphabet_checker = { "a" : False, "b" : False, "c" : False, "d" : False, "e" : False, "f" : False, "g" : False, "h" : False, "i" : False, "j" : False, "k" : False, "l" : False, "m" : False, "n" : False, "o" : False, "p" : False, "q" : False, "r" : False, "s" : False, "t" : False, "u" : False, "v" : False, "w" : False, "x" : False, "y" : False, "z" : False } for char in string: # if char in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": if char in "abcdefghijklmnopqrstuvwxyz": alphabet_checker[char] = True for valuebool in alphabet_checker: # if alphabet_checker[valuebool] == False: if not alphabet_checker[valuebool]: pangram = False return pangram print("----------- Pangram checker -----------\n") string = input("Please input the string you would like to check: ") # pangram_checker(string) if ispangram(string): print("Your string is a pangram.") else: print("Your string isn't a pangram.")
687cb2ed0de1e88a4bd65e915ec1a7b602aebbf8
JiaXingBinggan/For_work
/code/stack/min_stack.py
996
4
4
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.items = [] self.items_ = [] # 辅助栈,存最小的 def push(self, x): """ :type x: int :rtype: None """ self.items.append(x) if not self.items_ or self.items_[-1] >= x: # 当辅助栈最后一个元素大于或等于x时,可以添加 self.items_.append(x) def pop(self): """ :rtype: None """ if self.items.pop() == self.items_[-1]: # 当栈顶元素相同时,都要出栈 self.items_.pop() def top(self): """ :rtype: int """ return self.items[-1] def min(self): """ :rtype: int """ return self.items_[-1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.min()
51671779b49c8112395c6e818d8ea1b59ff4ac56
Vador05/iec_codeclub
/day2/firstquiz.py
597
4.15625
4
while(True): print("Are you Male or Female?") gender= input() if(gender=="female"): print("Can you give me your phone number?") phone=input() if(phone!=""): print("Do you like beer?") beer=input() elif(gender=="male"): print("Do you like beer?") beer=input() if(beer!=""): print("Can you give me your phone number?") phone=input() else: print("I'm not interested thanks =)") exit() print("#########New Person##########") print("Gender: "+gender) print("Phone: "+phone) print("Likes beer: "+beer)
b3a3b9295475ed53dc7ba3e9032143189801276c
Tingting0618/python-server-book1
/employees/request.py
6,525
3.640625
4
import sqlite3 import json from models import Employee, Location def get_all_employees(): # Open a connection to the database with sqlite3.connect("./kennel.db") as conn: # Just use these. It's a Black Box. conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Write the SQL query to get the information you want db_cursor.execute(""" SELECT e.id, e.name, e.address, e.location_id, l.name location_name, l.address location_address FROM employee e LEFT JOIN location l on e.location_id = l.id """) # Initialize an empty list to hold all animal representations employees = [] # Convert rows of data into a Python list dataset = db_cursor.fetchall() # Iterate list of data returned from database for row in dataset: # Create an animal instance from the current row. # Note that the database fields are specified in # exact order of the parameters defined in the # Customer class above. employee = Employee(row['id'], row['name'], row['address'], row['location_id']) # Create a Location instance from the current row location = Location(row['location_id'], row['location_name'], row['location_address']) employee.location = location.__dict__ employees.append(employee.__dict__) # Use `json` package to properly serialize list as JSON return json.dumps(employees) # Function with a single parameter def get_single_employee(id): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Write the SQL query to get the information you want db_cursor.execute(""" SELECT e.id, e.name, e.address, e.location_id, l.name location_name, l.address location_address FROM employee e LEFT JOIN location l on e.location_id = l.id WHERE e.id = ? """, (id, )) # Load the single result into memory data = db_cursor.fetchone() # Create an animal instance from the current row employee = Employee(data['id'], data['name'], data['address'], data['location_id']) # Create a Location instance from the current row location = Location(data['id'], data['location_name'], data['location_address']) employee.location = location.__dict__ return json.dumps(employee.__dict__) def get_employees_by_location(location_id): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Write the SQL query to get the information you want db_cursor.execute(""" SELECT e.id, e.name, e.address, e.location_id FROM employee e WHERE e.location_id = ? """, (location_id, )) employees = [] dataset = db_cursor.fetchall() for row in dataset: employee = Employee(row['id'], row['name'], row['address'], row['location_id']) employees.append(employee.__dict__) return json.dumps(employees) def create_employee(new_employee): with sqlite3.connect("./kennel.db") as conn: db_cursor = conn.cursor() db_cursor.execute(""" INSERT INTO employee ( name, address, location_id) VALUES ( ?, ?, ?); """, (new_employee['name'], new_employee['address'], new_employee['location_id'], )) # The `lastrowid` property on the cursor will return # the primary key of the last thing that got added to # the database. id = db_cursor.lastrowid # Add the `id` property to the animal dictionary that # was sent by the client so that the client sees the # primary key in the response. new_employee['id'] = id return json.dumps(new_employee) # def create_employee(employee): # # Get the id value of the last animal in the list # max_id = EMPLOYEES[-1]["id"] # # Add 1 to whatever that number is # new_id = max_id + 1 # # Add an `id` property to the animal dictionary # employee["id"] = new_id # # Add the animal dictionary to the list # EMPLOYEES.append(employee) # # Return the dictionary with `id` property added # return employee # def delete_employee(id): # # Initial -1 value for animal index, in case one isn't found # employee_index = -1 # # Iterate the ANIMALS list, but use enumerate() so that you # # can access the index value of each item # for index, employee in enumerate(EMPLOYEES): # if employee["id"] == id: # # Found the animal. Store the current index. # employee_index = index # # If the animal was found, use pop(int) to remove it from list # if employee_index >= 0: # EMPLOYEES.pop(employee_index) def delete_employee(id): with sqlite3.connect("./kennel.db") as conn: db_cursor = conn.cursor() db_cursor.execute(""" DELETE FROM employee WHERE id = ? """, (id, )) def update_employee(id, new_employee): with sqlite3.connect("./kennel.db") as conn: db_cursor = conn.cursor() db_cursor.execute(""" UPDATE Employee SET name = ?, address = ?, location_id = ? WHERE id = ? """, (new_employee['name'], new_employee['address'], new_employee['location_id'], id, )) # Were any rows affected? # Did the client send an `id` that exists? rows_affected = db_cursor.rowcount if rows_affected == 0: # Forces 404 response by main module return False else: # Forces 204 response by main module return True # EMPLOYEES = [ # { # "id": 1, # "name": "Tingting", # "address": "Nashville Road 1", # "locationId": 1 # }, # { # "id": 2, # "name": "Albert", # "address": "Nashville Road 2", # "locationId": 2 # } # ]
821e11c14a58db4023971849a8621b9d22a564f0
alejandroMAD/python-exercises
/data-structures/get_sum.py
167
3.65625
4
from functools import reduce def get_sum(list): return reduce((lambda total, element: total + element), list) total = get_sum([1, 2, 3, 4, 5, 6]) print(total)
de4b5333fc4f9183edefc420063ed9f418181e91
immanuelpotter/wordcloudifier
/program/wordcloudifier.py
1,671
3.6875
4
#!/usr/bin/env python #Take in user's long string of input, run the text against nltk, spit out a wordcloud import re import time import wordcloud as wcld import matplotlib.pyplot as plt class Wordcloudifier: def __init__(self,stopwords): try: stopwords_list = open(stopwords).read().split() except IOError: return "That's not a file!" self.stopwords_list = stopwords_list self.user_words = None def user_text_and_clean(self): text = str(raw_input("Enter your text here.\n")) lowercase = text.lower() noPunc = re.sub(r'[-./?!,":;()\']', ' ', lowercase) noPuncSplit = noPunc.split() self.user_words = noPuncSplit def get_stopwords_list(self): return self.stopwords_list def get_user_words(self): return self.user_words def iterate(self): #Need to iterate through these words and match which AREN'T in stopwords list i = 0 n = len(list(self.user_words)) while i < n: element = self.user_words[i] if element in self.stopwords_list: del self.user_words[i] n = n-1 else: i = i+1 return self.user_words def display(self): wordcloud = wcld.WordCloud(width=1000, height=500).generate(' '.join(list(self.user_words))) plt.figure(figsize=(15,8)) plt.imshow(wordcloud) plt.axis("off") plt.pause(10) # time.sleep(5) plt.close() if __name__ == "__main__": wc = Wordcloudifier('stopwords.txt') wc.user_text_and_clean() wc.iterate() wc.display()
9b79f181b52183cc5c88d6e34eb922144e408d4a
hujuu/py-test
/paiza/C036辞書の追加.py
1,021
3.875
4
first = input() first = first.split() two = input() two = two.split() first_rap = input() second_rap = input() first_dic = {} second_dic = {} for x in range(1, 5): temp = first_rap.split() first_dic[x] = int(temp[x-1]) win_lst = [] one_left = int(first[0]) if first_dic[one_left] < first_dic[int(first[1])]: win_lst.append(int(first[0])) else: win_lst.append(int(first[1])) if first_dic[int(two[0])] < first_dic[int(two[1])]: win_lst.append(int(two[0])) else: win_lst.append(int(two[1])) record_lst = [] for x in range(1, 3): temp = second_rap.split() record_lst.append(int(temp[x-1])) if first_dic[int(two[0])] < first_dic[int(two[1])]: win_lst.append(int(two[0])) else: win_lst.append(int(two[1])) #print(record_lst) if win_lst[0] < win_lst[1]: if record_lst[0] < record_lst[1]: print(win_lst[0]) print(win_lst[1]) else: print(win_lst[1]) print(win_lst[0]) else: if record_lst[0] < record_lst[1]: print(win_lst[1]) print(win_lst[0]) else: print(win_lst[0]) print(win_lst[1])
82d38645adc33f2aaded760076d1f91a34433eb1
hazemshokry/Algo
/Leetcode/BST.py
1,391
4.15625
4
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(self, root): self.root = Node(root) def preorder_search(self, start, find_val): """Helper method - use this to create a recursive search solution.""" if start: if start.value == find_val: return True else: return self.preorder_search(start.left, find_val) return self.preorder_search(start.right,find_val) return False def preorder_print(self, start, traversal): """Helper method - use this to create a recursive print solution.""" if start is not None: traversal = traversal + str(start.value) + "->" traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal def insert(self, new_val): pass def search(self, find_val): return self.preorder_search(self.root, find_val) if __name__ == '__main__': # Set up tree tree = BST(4) # Insert elements tree.insert(2) tree.insert(1) tree.insert(3) tree.insert(5) # Check search # Should be True print (tree.search(4)) # Should be False print (tree.search(6))
f3e734a4104d79c3d4e79d5c81a5b88f3558c747
dev-schueppchen/programmier-aufgaben
/aufgaben-mittel/aufgabe01/loesungen/python/main.py
416
3.953125
4
def get_smallest_dividend(num): for i in range(2, num + 1): if num % i == 0: return i def prime_factorizing(num): factors = [] current = num while current > 1: dividend = get_smallest_dividend(int(current)) factors.append(dividend) current /= dividend return factors input = int(input('Zahl: ')) print(input, 'in prime is ', prime_factorizing(input))
efe4c9880a20122f84a6faaacff838daa9c927cc
svn89nine/python-prac-1
/bmi_calc_v2.py
193
3.796875
4
h = float(input("Your height in Inches: ")) w = float(input("Your weight in pounds: ")) i = h * 0.0254 p = w * 0.4536 import math sh=(math.pow(i,2)) bmi= p / sh print("Your BMI: "+ str(bmi))
f8c497636600e0ad100e27194deab0fd11ee9299
vad2der/Python_examples
/Clustering/clustering_methods.py
10,097
3.703125
4
''' Algorithmic Thinking Project 3: Closest pairs and clustering algorithms four functions: slow_closest_pairs(cluster_list) fast_closest_pair(cluster_list) - implement fast_helper() hierarchical_clustering(cluster_list, num_clusters) kmeans_clustering(cluster_list, num_clusters, num_iterations) where cluster_list is a list of clusters in the plane ''' import math import alg_cluster import user41_QUCWvLQtmY_25 as viz import urllib2 import codeskulptor def pair_distance(cluster_list, idx1, idx2): """ Helper function to compute Euclidean distance between two clusters in cluster_list with indices idx1 and idx2 Returns tuple (dist, idx1, idx2) with idx1 < idx2 where dist is distance between cluster_list[idx1] and cluster_list[idx2] """ return (cluster_list[idx1].distance(cluster_list[idx2]), min(idx1, idx2), max(idx1, idx2)) def slow_closest_pair_backup(cluster_list): """ Compute the set of closest pairs of cluster in list of clusters using O(n^2) all pairs algorithm Returns the set of all tuples of the form (dist, idx1, idx2) where the cluster_list[idx1] and cluster_list[idx2] have minimum distance dist. """ pairs = [] closest_pairs = [] temp_tuple = (float('inf'), -1, -1) for ind_u, dummy_cluster_u in enumerate(cluster_list): for ind_v, dummy_cluster_v in enumerate(cluster_list): if ind_u < ind_v: pair_uv = pair_distance(cluster_list, ind_u, ind_v) pairs.append(pair_uv) if pair_uv[0] < temp_tuple[0]: temp_tuple = pair_uv for pair in pairs: if pair[0] == temp_tuple[0]: closest_pairs.append(pair) return eval(tuple(set(closest_pairs))[0]) def slow_closest_pair(cluster_list): """ Takes a list of Cluster objects and returns a closest pair where the pair is represented by the tuple (dist, idx1, idx2) with idx1 < idx2 where dist is the distance between the closest pair cluster_list[idx1] and cluster_list[idx2]. This function should implement the brute-force closest pair method described in SlowClosestPair from Homework 3. """ closest_pair = (float('inf'), -1, -1) cluster_list_len = len(cluster_list) for idx_1 in range(cluster_list_len): for idx_2 in range(cluster_list_len): if idx_1 != idx_2: cluster1, cluster2 = cluster_list[idx_1], cluster_list[idx_2] cluster_dist = cluster1.distance(cluster2) if cluster_dist < closest_pair[0]: closest_pair = (cluster_dist, idx_1, idx_2) return closest_pair def fast_closest_pair(cluster_list): """ Takes a list of Cluster objects and returns a closest pair where the pair is represented by the tuple (dist, idx1, idx2) with idx1 < idx2 where dist is the distance between the closest pair cluster_list[idx1] and cluster_list[idx2]. This function should implement the divide-and-conquer closest pair method described FastClosestPair from Homework 3. """ cluster_list_len = len(cluster_list) if cluster_list_len <= 3: closest_pair = slow_closest_pair(cluster_list) else: split = cluster_list_len / 2 left_list = cluster_list[:split] right_list = cluster_list[split:] closest_left = fast_closest_pair(left_list) closest_right = fast_closest_pair(right_list) min_halves = min(closest_left, (closest_right[0], closest_right[1] + split, closest_right[2] + split)) mid = 0.5 * (cluster_list[split - 1].horiz_center() + cluster_list[split].horiz_center()) min_cross = closest_pair_strip(cluster_list, mid, min_halves[0]) closest_pair = min(min_halves, min_cross) return closest_pair def closest_pair_strip(cluster_list, horiz_center, half_width): """ Takes a list of Cluster objects and two floats horiz_center and half_width. horiz_center specifies the horizontal position of the center line for a vertical strip. half_width specifies the maximal distance of any point in the strip from the center line. This function should implement the helper function described in ClosestPairStrip from Homework 3 and return a tuple corresponding to the closest pair of clusters that lie in the specified strip. (Again the return pair of indices should be in ascending order.) As one important coding note, you will need to sort a list of clusters by the horizontal (as well as vertical) positions of the cluster centers. This operation can be done in a single line of Python using the sort method for lists by providing a key argument of the form: cluster_list.sort(key = lambda cluster: cluster.horiz_center()) """ index_list = [idx for idx in range(len(cluster_list)) \ if abs(cluster_list[idx].horiz_center() - horiz_center) < half_width] index_list.sort(key=lambda idx0: cluster_list[idx0].vert_center()) strip_len = len(index_list) closest_pair = (float('inf'), -1, -1) for idx1 in range(strip_len - 1): for idx2 in range(idx1 + 1, min(idx1 + 4, strip_len)): point1 = index_list[idx1] point2 = index_list[idx2] current_dist = (cluster_list[point1].distance(cluster_list[point2]), min(point1, point2), max(point1, point2)) closest_pair = min(closest_pair, current_dist) return closest_pair def hierarchical_clustering(cluster_list, num_clusters): """ Takes a list of Cluster objects and applies hierarchical clustering as described in the pseudo-code HierarchicalClustering from Homework 3 to this list of clusters. This clustering process should proceed until num_clusters clusters remain. The function then returns this list of clusters. """ list_len = len(cluster_list) while list_len > num_clusters: cluster_list.sort(key=lambda cluster: cluster.horiz_center()) closest_pair = fast_closest_pair(cluster_list) cluster_list[closest_pair[1]].merge_clusters( cluster_list[closest_pair[2]]) cluster_list.pop(closest_pair[2]) list_len -= 1 return cluster_list def kmeans_clustering(cluster_list, num_clusters, num_iterations): """ Compute the k-means clustering of a set of clusters Input: List of clusters, number of clusters, number of iterations Output: List of clusters whose length is num_clusters """ def center_distance(cluster_center, center_point): """ input: cluster_center(type = tuple) center_point(type = tuple) output: distance between the two points """ return math.sqrt((cluster_center[1] - center_point[1]) ** 2 + (cluster_center[0] - center_point[0]) ** 2) # initialize k-means clusters to be initial clusters with largest populations pop_and_index = [(cluster_list[idx].total_population(), idx) for idx in range(0, len(cluster_list))] pop_and_index.sort() pop_order = [pop_and_index[idx][1] for idx in range(0, len(pop_and_index))] centers = [(cluster_list[idx].horiz_center(), cluster_list[idx].vert_center()) for idx in pop_order[:-(num_clusters+1):-1]] for dummy_ind in range(0, num_iterations): kmeans_clusters = [] for idx in range(0, num_clusters): kmeans_clusters.append(alg_cluster.Cluster(set([]), centers[idx][0], centers[idx][1], 0, 0.0)) for cluster in cluster_list: cluster_center = (cluster.horiz_center(), cluster.vert_center()) dists = [center_distance(cluster_center, center) for center in centers] kmeans_clusters[dists.index(min(dists))].merge_clusters(cluster) centers = [(k_cluster.horiz_center(), k_cluster.vert_center()) for k_cluster in kmeans_clusters] return kmeans_clusters def compute_distortions(cluster_list, data_table): """ Takes a list of clusters and uses cluster_error to compute its distortion. """ return sum([cluster.cluster_error(data_table) for cluster in cluster_list]) def load_data_table(data_url): """ Import a table of county-based cancer risk data from a csv format file """ data_file = urllib2.urlopen(data_url) data = data_file.read() data_lines = data.split('\n') print "Loaded", len(data_lines), "data points" data_tokens = [line.split(',') for line in data_lines] return [[tokens[0], float(tokens[1]), float(tokens[2]), int(tokens[3]), float(tokens[4])] for tokens in data_tokens] def run(): DIRECTORY = "http://commondatastorage.googleapis.com/codeskulptor-assets/" DATA_3108_URL = DIRECTORY + "data_clustering/unifiedCancerData_3108.csv" DATA_896_URL = DIRECTORY + "data_clustering/unifiedCancerData_896.csv" DATA_290_URL = DIRECTORY + "data_clustering/unifiedCancerData_290.csv" DATA_111_URL = DIRECTORY + "data_clustering/unifiedCancerData_111.csv" data_table = load_data_table(DATA_3108_URL) singleton_list = [] for line in data_table: singleton_list.append(alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3], line[4])) codeskulptor.set_timeout(200) cluster_list = hierarchical_clustering(singleton_list, 15) print "Displaying", len(cluster_list), "hierarchical clusters" #cluster_list = kmeans_clustering(singleton_list, 15, 5) #print "Displaying", len(cluster_list), "k-means clusters" viz.plot_it(data_table, cluster_list) def create_cluster_list(url): data_table = viz.load_data_table(url) singleton_list = [] for line in data_table: singleton_list.append(alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3], line[4])) return singleton_list, data_table #run()
d7a0cda8734ab23e5df98ad1a5c1223cdd9adbed
ogulcandemirbilek/ProgramingLab
/Online_Hafta04&Odev04/180401061_hw_4.py
2,581
3.609375
4
#min_heapyfy(array,i) : array ve i olmak üzere iki parametre alır. Array bizim heap düzenine sokacak olduğumuz dizi, i ise belirleyeceğimiz index'i temsil ediyor. Fonksiyon belirlediğimiz index'in Minheap düzeninde olmayan child ları da dahil olmak üzere MinHeap düzenine sokar. #build_min_heapy(array) : array parametresini alır ve döngü ile len(array)//2(Dizinin son parent'ı olduğu için) indexinden dizinin ilk indexine kadar min_heapyfy fonksiyonununu çalıştırır. ve bütün diziyi MinHeap düzenine sokar. #heapsort(array) : array parametresini alır ve heap düzenine sokar daha sonra sorted şekilde sıralayarak geri dödürür. #insertItemToHeap(MinHeapyArray,i) : MinHeap düzeninde ki bir array'i ve ekleyeceğimiz elemanı i ile parametre olarak alır. Elemanı MinHeap düzenin de diziye ekler. #removeItemFrom(myheap_1) : Parametre olarak aldığı MinHeap düzenin de ki array'in son elemanını siler. def min_heapyfy(array,i): left = 2*i+1 right = 2*i+2 length = len(array)-1 smallest = i if left<=length and array[i]>array[left]: smallest = left if right<=length and array[smallest]>array[right]: smallest = right if smallest != i: array[i],array[smallest] = array[smallest],array[i] min_heapyfy(array,smallest) def build_min_heapy(array): for i in reversed(range(len(array)//2)): min_heapyfy(array,i) my_array_1 = [8,10,3,4,7,15,1,2,16] min_heapyfy(my_array_1,4) print(my_array_1) my_array_1 = [8,10,3,4,7,15,1,2,16] build_min_heapy(my_array_1) print(my_array_1) def heapsort(array): array = array.copy() build_min_heapy(array) sorted_array = [] for _ in range (len(array)): array[0],array[-1] = array[-1],array[0] sorted_array.append(array.pop()) min_heapyfy(array,0) return sorted_array Sorted_Array = heapsort(my_array_1) print(Sorted_Array) def insertItemToHeap(MinHeapy_array,item): MinHeapy_array.append(item) i = len(MinHeapy_array)-1 if i<=0: return parent = (i-1)//2 while parent>=0 and MinHeapy_array[parent] > MinHeapy_array[i]: MinHeapy_array[parent],MinHeapy_array[i] = MinHeapy_array[i],MinHeapy_array[parent] i = parent parent = (i-1)//2 def removeItemFrom(myheap_1): index = len(myheap_1) if index<=0: print("heap zaten boş") return myheap_1.pop() insertItemToHeap(my_array_1,5) print(my_array_1) removeItemFrom(my_array_1) print(my_array_1)
add66478ded2a6e33a30a84aeea4aa8fb20d6f80
h4ckfu/magical_universe
/code_per_day/day_47_to_48.py
881
3.921875
4
from collections import defaultdict class CastleKilmereMember: """ Creates a member of the Castle Kilmere School of Magic """ def __init__(self, name: str, birthyear: int, sex: str): self._name = name self.birthyear = birthyear self.sex = sex self._traits = defaultdict(lambda: False) def add_trait(self, trait, value=True): self._traits[trait] = value def exhibits_trait(self, trait): value = self._traits[trait] if value: print(f"Yes, {self._name} is {trait}!") else: print(f"No, {self._name} is not {trait}!") return value if __name__ == "__main__": bromley = CastleKilmereMember('Bromley Huckabee', '1959', 'male') bromley.add_trait('tidy-minded') bromley.add_trait('kind') bromley.exhibits_trait('kind') bromley.exhibits_trait('mean')
303ce6bcd37bb26ad35be19bf9a0866c3c17f993
DouglasCarvalhoPereira/Interact-OS-PYTHON
/M4/VeirificIs_Sucesfull_or_not.py
329
3.703125
4
#!/usr/bin/env python #Script que verifica se o código foi executado com sucesso ou não. import os import sys filename=sys.argv[1] if not os.path.exists(filename): with open(filename, 'w') as f: f.write("New file created\n") else: print("Error, the file {} already exists!".format(filename)) sys.exit(1)
5a61bb0dea1ee778428302bd28138b02795d4fb5
officialstephero/codeforces
/Codeforces solutions/Petya and strings.py
183
3.875
4
first = input() first = first.lower() second = input() second = second.lower() if first < second: print('-1') if first > second: print('1') if first == second: print('0')
2dda7901d5acfc09717c76b3652d5b0878033071
Svetlanamsv/pass_word
/main.py
165
3.71875
4
print("Enter twice password") answer1=input() answer2=input() if answer1==answer2: print("Password is right") else: print("There is mistake in the password")
1f3d79f8c68779d79d02ee5e0b8c09e879692cc6
Walrick/Projet_3
/package/item.py
595
3.8125
4
#!/usr/bin/python3 # -*- coding: utf8 -*- class Item: """ Class Item for item management """ def __init__(self, name, data, x, y): """ init the item """ self.name = name self.data = data self.x = x self.y = y self.bag = False def pickup_item(self): """ if the item in the bag """ self.bag = True def set_placement(self, x, y): """ set the item placement """ self.x = x self.y = y def get_placement(self): """ get the item placement """ return (self.x, self.y)
d99aa48ea25023fecdfffaaffeadd5a750356d45
westgate458/LeetCode
/P0485.py
476
3.5
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 7 20:43:38 2020 @author: Tianqi Guo """ class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ # steps: # 1) join the list to form a string # 2) split the string by 0 # 3) check length of each segments of 1's # 4) find the max length return(max(map(len,''.join(map(str,nums)).split('0'))))
d1591773d30377c0c3f91179e9d34fc96cf93b4a
LalitTyagi/New-Onboards-Training-Solution
/Python/ProblemSet01/PS0104.py
1,235
4.125
4
#Practice using the Python interpreter as a calculator: #a) The volume of a sphere with radius r is 4/3pr3. What is the volume of a sphere with radius 5? #Hint: 392.7 is wrong! import math r=int(input()) print( 4/3*math.pi*(r**3)) #b) Suppose the cover price of a book is Rs.24.95, but bookstores get a 40% discount. Shipping costs #Rs.3 for the first copy and 0.75p for each additional copy. What is the total wholesale cost for #60 copies? price = 24.95*0.6 ship_cost = 3 ship_cost_copy = 0.75 total_sum = price + ship_cost + (price + ship_cost_copy)*59 print('Total wholesale cost for 60 copies is {0:.2f}'.format(total_sum)) #c) If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at #tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast? start_time = (6*60 + 52)*60 easy_time = (8*60 + 15)*2 tempo_time = (7*60 + 12)*3 breakfast_hour = (start_time + easy_time + tempo_time)/(60*60) breakfast_int_hour = int(breakfast_hour) breakfast_minute = (breakfast_hour - breakfast_int_hour)*60 breakfast_int_minute = int(breakfast_minute) print('Breakfast is at {}.{}'.format(breakfast_int_hour,breakfast_int_minute))
69576315428860e0f5427750a2254f45a267c441
orlova-lb/PythonIntro06
/lesson_05/strings.py
1,958
3.515625
4
# print(chr(0x26bd)) # print('\u26bd') # print(chr(9917)) # # print(ord('⚽')) # print(hex(ord('⚽'))) # # wave = '~' # boat = '\U0001F6A3' # seagull = '\u033C' # fish = '\U0001F41F' # penguin = '\U0001F427' # wale = '\U0001F40B' # octopus = '\U0001F419' # # row = wave * 10 + boat + wave * 15 + '\n' # fish_row = wave * 4 + fish + wave * 21 + '\n' # wale_row = wave * 10 + wale + wave * 15 + '\n' # penguin_row = wave * 7 + penguin + wave * 18 + '\n' # octopus_row = wave * 17 + octopus + wave * 8 + '\n' # # sea = row + fish_row + wale_row + penguin_row + octopus_row # print(sea) # a = """ # ;lsfdjhl;kfdjga # fdig # # sfdhkb'ofdj # [dogjeragf'sda # """ # print(a) ''' ''' # s = 'Hello World!' # # s = input('Please enter a string: ') # l = len(s) # print(l, s) # print('Hello ' + 'World!') # print('Hello ' * 5) s = 'HELLO' """ 0 1 2 3 4 -> ERROR H E L L O ERROR <- -5 -4 -3 -2 -1 """ print(s[1], s[-4]) """ slice str[start: stop: step] """ s = 'Python/HILLEL/PythonIntro06' # print(s[0: 6]) # print(s[:6]) # print(s[7: 13]) # print(s[14: 9874908362089]) # print(s[14:]) # print(s[:]) # print(s[1::2]) # print(s[::-1]) # # print(s[-20: -14]) # # for i in range(len(s)): # range(15) # if not i % 2: # i % 2 == 0 # print(s[i], end='') # print() # # for symbol in s: # print(symbol, end='') # print() for i in range(0, len(s), -1): # range(15) # if not i % 2: # i % 2 == 0 print(s[i], end='') print() """ methods """ s = 'Python/HILLEL/PythonIntro06' idx = s.find('t') print(idx) idx = s.find('t', idx + 1) print(idx) idx = s.find('t', idx + 1) print(idx) idx = s.find('t', idx + 1) print(idx) idx = s.find('t') while idx >= 0: print(idx) idx = s.find('t', idx+1) print(s.replace('t', 'T')) print(s.upper()) print(s.lower()) s = s.lower() print(s.capitalize()) s = ' Python/HILLEL/PythonIntro06 ' print('"' + s.strip() + '"')
bdafa9e2d3440e65b21370fe80795659ae6446da
arunson/eBay-RAM
/cs130/eram/utils.py
1,855
3.53125
4
from cs130.eram.review_modules import review_module # Filters a space-delimited string based on a blacklist. # The blacklist should be a list of lowercase words. # The input will automatically be lowercased. def filter(string, blacklist) : # Lowercase the input lowercase = string.lower() word_list = lowercase.split(' ') filtered_words = [] for word in word_list: if word not in blacklist: filtered_words.append(word) return ' '.join(filtered_words) def get_first_n_words(string, n) : word_list = string.split(' ') return_val = "" for word in (word_list[:n]) : return_val += word + " " return return_val def compute_weighted_mean(score_and_review_list) : weighted_sum = 0 total_weights = 0 for (score, review_count) in score_and_review_list : if (score != -1) : weighted_sum += int(score) * int(review_count) total_weights += int(review_count) if total_weights == 0 : return -1 else : return weighted_sum / total_weights # Returns the score, number of reviews, and last used query def query_review_module_by_title(review_module, title, mode) : # In quick mode, do not attempt to guess what query would work. if mode == "quick": number_of_tries = 1 else: number_of_tries = 3 print "\nSearch Mode: " + mode # This is getting redundant number_of_words = 4 while (number_of_tries > 0) : query = get_first_n_words(title, number_of_words) print "\nSearch Term: " + query (score, reviews_count) = review_module.get_score(query, "title") number_of_tries -= 1 number_of_words -= 1 if ( score != -1 or reviews_count != -1 ): break return (score, reviews_count, query)
9e774c735d1a836da022ba8140f9e7a87fc96cd5
b72u68/coding-exercises
/Project Euler/p7.py
395
3.765625
4
# 10001st prime import math def check_prime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n))): if n % i == 0: return False return True def main(): counter = 0 num = 2 while counter < 10001: if check_prime(num): counter += 1 num += 1 return num - 1 if __name__ == "__main__": print(main())
7ff066725aac30991a2025378f36dc6a0a280a45
masterashu/Semester-3
/ADSA/Lab/Lab7/u_knapsack.py
752
3.625
4
def get_max(I, cost): m = 0 for w,v in I: if w == cost: m = max(m, v) return m def UnboundedKnapsack(I, cost): I.sort() arr = [0]*(cost+1) for i in range(1, cost+1): arr[i] = max(arr[i], get_max(I, i)) for j in range(i): arr[i] = max(arr[i], arr[i-j] + arr[j]) print("Max Value:", arr[cost]) if __name__ == "__main__": print("Unbounded Knapsack") n = int(input("Enter No of Items: ")) I = [] print("Enter weight and value: ") for _ in range(n): i,j = map(int, input().split()) I.append((i,j)) # print(I) # I = [(5, 10), (10,30), (15,20)] UnboundedKnapsack(I, int(input("Enter Total Cost: ")))
495d0c3f3992c4cf96ad82da94d3d70cfd9fbb1e
ebiggers/libdeflate
/scripts/gen_bitreverse_tab.py
523
3.953125
4
#!/usr/bin/env python3 # # This script computes a table that maps each byte to its bitwise reverse. def reverse_byte(v): return sum(1 << (7 - bit) for bit in range(8) if (v & (1 << bit)) != 0) tab = [reverse_byte(v) for v in range(256)] print('static const u8 bitreverse_tab[256] = {') for i in range(0, len(tab), 8): print('\t', end='') for j, v in enumerate(tab[i:i+8]): print(f'0x{v:02x},', end='') if j == 7: print('') else: print(' ', end='') print('};')
875ffe11b5e30a033006835e8405f5a0615bac8d
billylin14/CSE415_Assignments
/a6-starter-files/binary_perceptron.py
2,553
3.828125
4
'''binary_perceptron.py One of the starter files for use in CSE 415, Winter 2021 Assignment 6. Version of Feb. 18, 2021 ''' def student_name(): return "Billy Lin" # Replace with your own name. def classify(weights, x_vector): '''Assume weights = [w_0, w_1, ..., w_{n-1}, biasweight] Assume x_vector = [x_0, x_1, ..., x_{n-1}] Note that y (correct class) is not part of the x_vector. Return +1 if the current weights classify this as a Positive, or -1 if it seems to be a Negative. ''' n = 0 for i in range(len(x_vector)): n += weights[i]*x_vector[i] n += weights[-1] if n>=0: return +1 else: return -1 def train_with_one_example(weights, x_vector, y, alpha): '''Assume weights are as in the above function classify. Also, x_vector is as above. Here y should be +1 if x_vector represents a positive example, and -1 if it represents a negative example. Learning rate is specified by alpha. ''' classified_num = classify(weights, x_vector) if classified_num == y: #if correctly classified return (weights, False) # No, there was no change to the weights else: #if misclassified #y == +1, classified as -1 -> underestimated -> plus #y == -1, classified as +1 -> overestimated -> minus for i in range(len(x_vector)): weights[i] += y*alpha*x_vector[i] weights[-1] += y*alpha #biased weight return (weights, True) # Yes, there was a change to the weights # From here on use globals that can be easily imported into other modules. WEIGHTS = [0,0,0] ALPHA = 0.5 n_epochs = 0 def train_for_an_epoch(training_data, reporting=False): '''Go through the given training examples once, in the order supplied, passing each one to train_with_one_example. Update the global WEIGHT vector and return the number of weight updates. (If zero, then training has converged.) ''' global WEIGHTS, ALPHA, n_epochs changed_count = 0 for example in training_data: x_vector = example[:-1] y = example[-1] (new_weight, changed) = train_with_one_example(WEIGHTS, x_vector, y, ALPHA) if changed: WEIGHTS = new_weight changed_count += 1 if reporting: print(WEIGHTS, changed_count) n_epochs += 1 if reporting: print("n_epochs=", n_epochs) return changed_count TEST_DATA = [ [-2, 7, +1], [1, 10, +1], [3, 2, -1], [5, -2, -1] ] def test(): print("Starting test with 3 epochs.") for i in range(3): train_for_an_epoch(TEST_DATA) print(WEIGHTS) print("End of test.") if __name__=='__main__': test()
a5936ef5d7c847c0081980ba2954f4184aae1be1
gabriellaec/desoft-analise-exercicios
/backup/user_097/ch48_2019_09_30_19_58_14_296160.py
237
3.8125
4
meses = ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"] nomeMes = input("Informe o nome do mês: ") i = 0 while(meses[i]!=nomeMes): i = i + 1 print(i+1)
18040fa7d7b909853ff7c0ab610cbc784c8ab3ca
MarkusHarrison21/PythonCourse
/Chapters4.py
2,044
4.59375
5
# =========================================== Turtles =========================================== # Turtles are the name of a slow running visual program in Python # A module in Python is a way of providing useful code to be used by another program (among other things, the module can contain functions we can use). # Turtles are a module import turtle # creating a canvas (a blank screen for turtle to draw on) t = turtle.Pen() # You should see a blank box with an arrow in the center, that arrow is the turtle # If the turtle is an hourglass something is wrong, check that you have turtle installed, or try restarting the shell # Making the turtle move # Turtles move by pixels, 50 pixels in this case t.forward(50) # We have turned the turtle by 90 degrees, it should now be looking upwards # Turning does not move the turtle, it only changes the direction the turtle is looking t.left(90) # Moved the turtle up by 50 t.forward(50) # Turned the turtle left t.left(90) # Moved left 50 pixels t.forward(50) # Turned the turtle downwards t.left(90) # Moved turtle down 50 t.forward(50) # Turtle turned right t.left(90) # ---------------------------------- # The are good ways to keep the turtle open since it closes the moment it is done running. # Having the turtle open in a window and manually exit # window = turtle.Screen() # ....... # window.exitonclick() # Set this up at the end (we'll go over inputs later) # input("Press any key to exit ...") # Slap this at the end, the easiest solution # turtle.done() # --------------------------------- # Used to erase the canvas and puts turtle at starting position # t.reset() # Used to just clear the canvas but leaves the turtle where it was left #t.clear() # You can also move backwards t.backward(100) # You can also pick the pen up to stop drawing but still move t.up() t.right(90) t.forward(20) t.left(90) # Putting the pen back down to draw again t.down() t.forward(100) turtle.done()