blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
018fd7991faeacf03e61a1507ce0f610a1d4a668
activehuahua/python
/pythonProject/base/capitalize.py
191
3.84375
4
import string def normalize(name): return name.capitalize() L1 = ['adam','LISA','barT'] #L2 = list(map(normalize,L1)) L2 = [] for item in L1: L2.append(item.capitalize()) print(L2)
6aadee1fb4f03b5d670437f74b278c635e0e1162
vvakrilov/python_basics
/08. Pre_Exam/01. Moon.py
226
3.6875
4
import math average_speed = float(input()) fuel_per_100km = float(input()) distance = 384400 * 2 time = math.ceil(distance / average_speed) + 3 fuel = fuel_per_100km * distance / 100 print(f"{time}\n" f"{int(fuel)}")
d6d0137403291e598d5956738617f460063b5d87
Hozok/HTTPServer
/index.py
1,036
3.671875
4
#coding:utf-8 import cgi import hashlib import os print("Content-type: text/html; charset=utf-8") # Pour préciser que tout ce qui va suivre après dans un print est du code HTML en utf-8. html = """<!DOCTYPE html> <head> <meta charset="utf-8"> <title>Test test</title> </head> <body> """ # Voici donc le code html au dessus et en dessous, qui doit bien sur respecter la syntaxe. Malheureusement, un des seuls inconvénient c'est que le code html d'au dessus n'est pas la coloration syntaxique normal du html. print(html) # Voici l'endroit ou vous écrivez votre code HTML : print("<h1>Ceci est un gros titre !</h1>") print(""" <ul> <li>Ceci</li> <li>est</li> <li>une</li> <li>liste</li> </ul> """) print("<p>Ceci est un texte !</p>") html = """ </body> </html> """ print(html) # Donc voila le code principal et simplifié pour créer vos pages HTML, vous pouvez le modifier à votre guise, mais ce script reste un exemple à prendre en compte. # Pour voir votre page dans votre navigateur web : localhost/index.py
ff8aefc5ef0f915ff846e3ca6b4f2c4a1e3dd2b2
cs-fullstack-fall-2018/python-review-ex2-jpark1914
/python_review2.py
657
3.9375
4
#====Phase 1===== import random randomNumber = random.randint(0,10) #====Phase 2===== guessedNum = int(input("Guess a number between 0 - 10")) print("First guess is always wrong try again") #====Phase 3===== while(guessedNum != randomNumber and guessedNum != 'q'): guessedNum = int(input("")) if(guessedNum == randomNumber): print("THAT IS A CORRECT GUESS") break elif(guessedNum < randomNumber): print("Guess a little higher Or press 'q' to quit.") elif(guessedNum > randomNumber): print("Aim lower or press 'q' to quit.") else: print("Tis an error, try a different number") continue
0d8ee3ca062285e1762d040a441c919cac13359b
geekidharsh/elements-of-programming
/primitive-types/reverse-int.py
417
3.96875
4
# given an int, return the reverse of itself. # inp: 1234 # return: 4321 # perform operation on |x| and return along with the sign of x. using built in function abs() def reverse_int(x): rev = 0 x_remaining=abs(x) while x_remaining: rev = 10*rev + x_remaining%10 x_remaining //=10 return -rev if x < 0 else rev # time complexity is O(n) where n is the number of digits in x print(reverse_int(-1234))
504d40da67dda945eeb6b5a0dd07c3276aa95a78
mircica10/pythonDataStructuresAndAlgorithms
/ds-lists.py
1,969
3.859375
4
class List: def __init__(self, val, next = None): self.val = val self.next = next def printList(self, list): res = '' if list is None: return '' while list is not None: res += str(list.val) + ',' list = list.next return res[0:len(res) - 1] def reverseListHelper(self, list): if list.next is None: return (list, list) (prev, root) = self.reverseListHelper(list.next) prev.next = list list.next = None return (list, root) def reverseList(self, list): (list, root) = self.reverseListHelper(list) return root def sortList(self, list): swap = True while swap == True: swap = False index = list while index.next is not None: if index.val > index.next.val: aux = index.val index.val = index.next.val index.next.val = aux swap = True index = index.next return list def deleteDuplicates(self, list): index = list while index.next is not None: if index.next is not None and index.val == index.next.val: index.next = index.next.next index = index.next index = index.next return list def initTest(): l7 = List(9) l6 = List(2, l7) l5 = List(3, l6) l4 = List(4, l5) l3 = List(5, l4) l2 = List(2, l3) l1 = List(1, l2) return l1 l1 = initTest() assert('1,2,5,4,3,2,9' == l1.printList(l1) ) # l1.printList(l1) l = l1.reverseList(l1) assert('9,2,3,4,5,2,1' == l1.printList(l)) l1 = initTest() l = l1.sortList(l1) assert('1,2,2,3,4,5,9' == l1.printList(l)) l1 = initTest() l = l1.sortList(l1) l2 = l.deleteDuplicates(l) assert('1,2,3,4,5,9' == l2.printList(l2))
0a6efc745543a184c93b1d05bb545e983f33c7a6
whyisee/Hadoop-Cluster-Easy
/python/P201/pc_jjxs.py
4,089
3.515625
4
#!/bin/env python import urllib.parse #负责url编码处理 import urllib.request from lxml import etree import os def loadPage(url, filename): """ 作用:根据url发送请求,获取服务器响应文件 url: 需要爬取的url地址 filename : 处理的文件名 """ #print ("正在下载 " + filename) headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36"} request = urllib.request.Request(url, headers = headers) return urllib.request.urlopen(request).read() def writePage(html, filename): """ 作用:将html内容写入到本地 html:服务器相应文件内容 """ print ("正在保存 " + filename) # 文件写入 with open(filename, "wb+") as f: f.write(html) print ("-" * 30) def bookDownload(url,filePath,baseUrl): """ 作用:下载 """ html = loadPage(url,"33753") #"/txt/33727.htm" #writePage(html, "33753") dom = etree.HTML(html) a_text = dom.xpath('//li[@class="downAddress_li"]/a/@href') html = loadPage(baseUrl+a_text[0],"33753") #writePage(html, "33753_z") dom = etree.HTML(html) a_text = dom.xpath('//tr/td/a[@class="strong green"]/@href') #print(a_text[0]) html = loadPage(baseUrl+a_text[0],"33753") writePage(html, filePath) def jiujiuSpider(url, href, filePath): """ 作用:爬虫调度器,负责组合处理每个页面的url url : url的前部分 beginPage : 起始页 endPage : 结束页 """ html = loadPage(url+"/"+href, href) pathName=href.split("/")[2] if not os.path.exists(pathName): os.mkdir(pathName) writePage(html, filePath+"/"+pathName+"/"+pathName+".html") beginPage=2 endPage=10 dom = etree.HTML(html) a_text = dom.xpath('//div[@id="catalog"]/div/a/@href') b_text = dom.xpath('//div[@id="catalog"]/div/a/@title') #print(b_text) #print(a_text) i=0 for ele_book in a_text: print(b_text[i]) bookDownload("https://www.jjxsw.la"+ele_book,pathName+"/"+b_text[i]+".txt","https://www.jjxsw.la") i=i+1 for page in range(beginPage, endPage + 1): #pn = (page - 1) * 50 filename = "第" + str(page) + "页.html" fullurl = url+"/"+href + "index_" + str(page)+".html" #print fullurl html = loadPage(fullurl, filename) #print html dom = etree.HTML(html) #a_text = dom.xpath('//div[@id="catalog"]/div/a/@href') a_text = dom.xpath('//div[@id="catalog"]/div/a/@href') b_text = dom.xpath('//div[@id="catalog"]/div/a/@title') i=0 for ele_book in a_text: print(b_text[i]) bookDownload("https://www.jjxsw.la"+ele_book,pathName+"/"+b_text[i]+".txt","https://www.jjxsw.la") i=i+1 #print(a_text) #writePage(html, filename) #print ('谢谢使用') #url = "https://whyisee.github.io/" #word = {"wd":"传智播客"} #word = urllib.parse.urlencode(word) #转换成url编码格式(字符串) #newurl = url + "?" + word # url首个分隔符就是 ? # #headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"} # #request = urllib.request.Request(newurl, headers=headers) #response = urllib.request.urlopen(request) # #print (response.read()) html=loadPage("https://www.jjxsw.la/support/sitemap.html","久久小说") dom = etree.HTML(html) #获取 a标签下的文本 #a_text = dom.xpath('/a/text()') #a_text = dom.xpath('//div/div/div/div/div/a/text()') a_text = dom.xpath('//div/div/div/div/div/ul/li/a/@href') #print(dom) print(a_text) for ele in a_text: print(ele) jiujiuSpider("https://www.jjxsw.la",ele,"./") #jiujiuSpider("https://www.jjxsw.la",a_text[0],"./") #bookDownload("https://www.jjxsw.la/txt/33753.htm","","https://www.jjxsw.la") #writePage(html,"久久小说地图.html")
20bb7e744f18c0d3cb607f1828025e24f33af802
Disunito/hello-world
/python_work/Chap_five/hello_admin.py
1,092
4.25
4
#5-8 Make a list of five or more usernames, including the name 'admin'. #Imagine you are writting code that will print a greeting to each user after #they log in to a website. Loop through the list, and print a greeting #each other. # -If the username 'admin', print a special gretting, such as Hello admin, # would you like a status report. # -Otherwise, print a generic greeting, such as Hello Jaden, Thank you for # logging in agian. usernames = [ 'admin', 'slutbunny', 'DooMguy', 'iKa', 'thebaron'] #usernames = [] if usernames: for name in usernames: if name == 'admin': print('Welcome back Admin, would you like a system report?\n') else: print(f'Welcome back {name.title()}, good to see you.\n') else: print('We need more users, Dave...') current_users = [user.lower() for user in usernames] new_users = ['disunito', 'ikA', 'audreythorn', 'bbbenson', 'DooMguy'] for user in new_users: if user.lower() in current_users: print('Sorry, that username is taken.') else: print(f'Welcome {user.title()}!')
2c242bc4614f993ebb781cc6bd42a5f008945bc1
newjokker/PyUtil
/Z_other/Game/LearnPygame/列表转棋盘.py
1,705
3.640625
4
# -*- coding: utf-8 -*- # -*- author: jokker -*- import pygame import sys import random def run(): clock = pygame.time.Clock() # 定时器 screen = pygame.display.set_mode([320, 400]) x, y = (0, 0) heigt, width = (10, 10) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: # 当按下关闭按键 pygame.quit() sys.exit() # 接收到退出事件后退出程序 elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT: x += 5 elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT: x -= 5 elif event.type == pygame.KEYDOWN and event.key == pygame.K_UP: y -= 5 elif event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN: y += 5 screen.fill((0, 0, 0)) # 屏幕中填充颜色 # 创建随机砖块 bricks = [] for i in range(100): x, y = random.randrange(1, 30), random.randrange(1, 40) color = (random.randrange(1, 255), random.randrange(1, 255), random.randrange(1, 255)) brick_temp = {'loc': (x*10, y*10), 'height': 10, 'width': 10, 'color': color} bricks.append(brick_temp) # 将砖块全部可视化出来 for each_brick in bricks: x, y = each_brick['loc'] height, width = each_brick['height'], each_brick['width'] color = each_brick['color'] pygame.draw.rect(screen, color, (x, y, heigt, width)) # 画一个矩阵 pygame.display.update() clock.tick(15) if __name__ == '__main__': run()
0b01d2e7921a6d0c9dfcb0fb39c98b009000cd18
ahmedmeshref/Leetcode-Solutions
/test.py
733
3.78125
4
def PreorderTraversal(strArr): preorderArr = [] def preOrderCalculator(node_ind, num_missing_leafs): # base case if node_ind >= len(strArr) or strArr[node_ind] == "#": return 2 preorderArr.append(strArr[node_ind]) left_child = (node_ind * 2) + 1 - num_missing_leafs val = preOrderCalculator(left_child, num_missing_leafs) num_missing_leafs += 2 if val else 0 right_child = left_child + 1 preOrderCalculator(right_child, num_missing_leafs) preOrderCalculator(0, 0) return ' '.join(preorderArr) # keep this function call here print(PreorderTraversal(["5", "2", "6", "1", "9", "10", "#", "#", "#", "#", "#", "4", "#"]))
99771f9937180fcdf72db09959efd454a762d6eb
GuilhermeFariasn7/infosatc-lp-avaliativo-02
/questao7.py
1,362
4.3125
4
#7- Faça 4 listas: Filmes,jogos,livros e esporte ->> FILMES = ["O poderoso chefão","Parasitas","Fast and Furious", "O menino do pijama listrado","Tá dando onda"] #A - adicionar itens a lista: FILMES.append("frozen") FILMES.append("Diario de um banana") print(FILMES) JOGOS = ["Cs go","LOL","Valorant","GTA V","The last of us"] #A - adicionar itens a lista: JOGOS.append("need for speed underground 2") JOGOS.append("Farcry 5") print(JOGOS) LIVROS = ["menina traduzida","Diario de um banana","a culpa é das estrelas","O homem de giz","Gelato"] #A - adicionar itens a lista: LIVROS.insert(1,"Frozen") LIVROS.insert(2,"Galinha pintadinha volume 2") print(LIVROS) ESPORTES = ["volei","futebol","basquete","handeibol","surf"] #A - adicionar itens a lista: ESPORTES.append("Skate") ESPORTES.append("Atletismo") print(ESPORTES) #B - Juntar todas as lista em uma lista só: listaGeral = [FILMES,JOGOS,LIVROS,ESPORTES] print("lista com as lista dentro da lista: ",listaGeral) #C - Acesse (mostrar) algum item da lista livros: print("Mostrando da lista livros o livro(menina traduzida)",LIVROS[3]) #D - . Remova um item da lista esporte. del ESPORTES[3] print(ESPORTES) #E - Adicione uma lista chamada “disciplinas”, no item b. (sem criar uma lista separada). DISCIPLINAS = ["Física","Química"] listaGeral = listaGeral + DISCIPLINAS print(listaGeral)
d37927187ae5ef4fbd630ad10acaca899f7e0ae3
ljyxy1997/WUST
/4.29/class5-列表操作,多维列表.py
609
3.96875
4
a_list=[1,2,30,30,30,4,2] print(a_list) a_list[0]=100#修改列表中第0个元素 print(a_list) a_list.append(200)#列表最后加元素 print(a_list) a_list.insert(2,300)#在列表中插入一个元素 print(a_list) del a_list[2]#删除列表第3个元素 print(a_list) a_list.remove(30)#删除一个叫30的元素 print(a_list) a=a_list.pop()#弹出列表中最后一个元素 print(a) print(a_list) b=a_list.pop(1)#弹出列表中第二个元素 print(b) print(a_list) b_list=[[1,2],[4,5],[7,8]] print(b_list[1]) #打印第二个元素 print(b_list[2][1]) #打印第三个列表里面第二个元素
348b6cf0b4c9584fb8020ee730cd7e84172a53df
mukund7296/python-3.7-practice-codes
/kjson.py
117
3.5
4
import json # some JSON: x = '{ "name":"John", "age":30, "city":"New York"}' y=json.loads(x) print(y['age'])
556e3818d1299c7ae4cc156ec68e3221dc0d499e
lll-Mike-lll/botstock
/try_29_random number.py
372
3.859375
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 27 15:02:02 2019 @author: Lenovo """ import random nums = [x for x in range(10)] random.shuffle(nums) print(nums) # ============================================================================= # nums = [x for x in range(100)] # print(nums) # =============================================================================
b62f93479867a32bee366e5193b9490d8ef70384
A-N-A-R-K-H/Matrix_Factorization-Recommendation_Engine
/best_model.py
7,333
3.703125
4
""" Colby Wise COMS6998 - Homework1 Matrix Factorization Factorizers a N x M user:item matrix into U: N x r and V: r X M matrices where: - U - User : feature matrix - V - Movie: feature matrix Calculates mean squared error (MSE) and mean reciprocal rank (MMR) on test data after the training data decomposition """ import pandas as pd import numpy as np import time import pickle import math from preprocessing import * from model_evaluation import * """ Class MatrixFactorize takes train and test data then factors the training data in U,V matrix decompositions. Using U,V it then predicts movie ratings on the test data returning the MSE and MRR on test data """ class MatrixFactorize(object): """ Initialization @param: train - pandas dataframe of training data test - pandas dataframe of test data lr - learning rate r - features to learn epoch - epochs to run training lambd - regularization rate (lambda) """ def __init__(self, train, test, lr, r, iters, lambd): self.lr = lr self.features = r self.iters = iters self.lambd = lambd self.train = train self.test = test all_data = pd.concat([train, test]) self.n_items = len(all_data['movieId'].unique()) self.n_users = len(all_data['userId'].unique()) print("Number of users:", self.n_users) print("Number of movies:", self.n_items) self.U = np.random.randn(self.n_users, self.features) self.V = np.random.randn(self.features, self.n_items) self.loss_record = {"train": [], "test": [], "epoch": [], "r": self.features,"lr" : self.lr} """ Updates loss dictionary that captures training/test MSE during training @param: test_mse - MSE from test data train_mse - MSE from train data epoch - current epoch of training @Return: None """ def record_loss(self, test_mse, train_mse, epoch): self.loss_record["train"].append(train_mse) self.loss_record["test"].append(test_mse) self.loss_record["epoch"].append(epoch) """ Predict rating using current U, V matrices @param: test_sample - random sample from test data U - User matrix V - Movie matrix show - default(False), prints subset of predict values @Return: mse - mean squared error for test sample """ def predict(self, test_sample, U, V, show=False): preds = [] loss = 0 print("Running test validation...") cntr = 1 for row in test_sample.itertuples(): user, movie, rating = row[2], row[3], row[4] pred = np.dot(U[user,:], np.transpose(V[:,movie]) ) preds.append(pred) if not (cntr % 10**5) and show: print("u: {} \t m: {} \t r: {} \t r_hat: {}".format(user, movie, rating, pred)) err = rating - pred loss += err**2 cntr += 1 MSE = (loss/len(preds)) return MSE """ Punny name ... saves pickle objects during training phase @param: out - data structure (dict, etc) to save fname - filename @Return: None """ def god_save_the_queen(self, out, fname): with open(fname, "wb") as f: pickle.dump(out, f) """ Uses train and test data to learn U,V matrix decomposition """ def factorizeMatrix(self): print("Factorizing...") print("=> learning rate: {}, epochs: {}, r: {}".format(self.lr, self.iters, self.features)) epoch_start = time.time() for epoch in range(1,self.iters+1): print("\nStarting iteration {}...".format(epoch)) self.lr = self.lr * .995 # Hacky annealing best_test_MSE = 50 cntr = 1 _s = time.time() for row in self.train.itertuples(): user, movie, rating = row[2], row[3], row[4] err = rating - np.dot( self.U[user,:], np.transpose(self.V[:,movie]) ) train_MSE = err ** 2 dV = self.lr * (err * 2 * self.U[user,:] - self.lambd * self.V[:,movie]) dU = self.lr * (err * 2 * self.V[:,movie] - self.lambd * self.U[user,:]) self.V[:,movie] = self.V[:,movie] + dV self.U[user,:] = self.U[user,:] + dU cntr += 1 # Periodically Print Progress if not (cntr % 10**5): _e = time.time() print( "\n {} min runtime to process {:,} rows...\n".format(int((_e-_s)//60), cntr) ) test_sample = self.test.sample(frac=0.05) U, V = self.U, self.V test_MSE = calc_MSE(test_sample, U, V, show=False) self.record_loss(test_MSE, train_MSE, epoch) print( "Train MSE: {0:0.4f}, Test MSE: {1:0.4f}".format(train_MSE, test_MSE)) # Periodically Check Test MSE if test_MSE <= best_test_MSE: best_test_MSE = test_MSE u_outfile = "U_mat:_r={}_lambda={}_epoch={}.pkl".format(self.features, self.lambd, epoch) v_outfile = "V_mat:_r={}_lambda={}_epoch={}.pkl".format(self.features, self.lambd, epoch) loss_file = "loss:{:.3f}_r={}_lambda={}_epoch={}.pkl".format(test_MSE, self.features, self.lambd, epoch) self.god_save_the_queen(self.U, u_outfile) self.god_save_the_queen(self.V, v_outfile) self.god_save_the_queen(self.loss_record, loss_file) # Track epoch runtime epoch_end = time.time() print("\n Epoch {} runtime: {} min".format(epoch, int((epoch_end-epoch_start)//60))) MRR = calc_MRR(self.test, self.U, self.V) with open('MRR.txt', 'w') as f: f.write("log:_MRR={:.3f}:_r={}_lambda={}".format(MRR, self.features, self.lambd)) return self.U, self.V, self.loss_record if __name__ == "__main__": def update_movieId(movie): return item_toKey[movie] def update_userId(user): return user_toKey[user] # Helper method to view class properties def properties(cls): return [i for i in cls.__dict__.keys() if i[:1] != '_'] train_file = 'ml-20m/train.csv' test_file = 'ml-20m/test.csv' train = get_data(train_file) test = get_data(test_file) all_data = pd.concat([train, test]) key_toUser, user_toKey = get_user_dicts(all_data) key_toItem, item_toKey = get_item_dicts(all_data) train['userId'] = train['userId'].apply(update_userId) train['movieId'] = train['movieId'].apply(update_movieId) test['userId'] = test['userId'].apply(update_userId) test['movieId'] = test['movieId'].apply(update_movieId) lr = .01 r = 40 epochs = 3 lamda = .02 MF = MatrixFactorize(train, test, lr, r, epochs, lamda) U, V, loss_record = MF.factorizeMatrix() #print( properties(MF) )
e3d4bf1b5481690bb35eb1d9f482b1b60543bd7b
nihald16/Python-Programs
/split.py
145
3.71875
4
string="hi i am a programer" print(type(string)) a=string.split(" ") print(a,"\n",type(a)) a="-".join(string) print(a) print(type(a))
717bbb395428edb399c64e9847e90a5820920c08
Tanmay53/cohort_3
/submissions/sm_028_sagar/week_13/day_4/session_1/count_occurences_string.py
327
3.78125
4
string = 'masaischool' occr = {} #occurences of each character for char in string: isFound = False for key in occr: if(key == char): isFound = True occr[key] = occr[key]+1 break # print(char,isFound) if(isFound == False): occr[char] = 1 print(occr)
6cbc40d5852cb72b56df2596752064108690ef8d
serdardoruk/Bloomberg-Common-DS-Algo-Python-Solutions
/arrayValuesOfIndices.py
1,223
3.640625
4
''' Input a = [21,5,6,56,88,52], output = [5,5,5,4,-1,-1] . Output array values is made up of indices of the element with value greater than the current element but with largest index. So 21 < 56 (index 3), 21 < 88 (index 4) but also 21 < 52 (index 5) so we choose index 5 (value 52). Same applies for 5,6 and for 56 its 88 (index 4). If there is no greater element then use -1 and last element of the array will always have value of -1 in output array since there is no other elment after it. Follow up to consider the input as a stream, how can we only update smaller element (use specific Data structure), running time and space complexity discussion. Input a = [21,5,6,56,88,52], output = [5,5,5,4,-1,-1] ''' from heapq import heappush, heappop def find_right_index(nums): heap = [] for i, val in enumerate(nums): heappush(heap, (-val, i)) print(heap) res = [-1]*len(nums) maxIdx = -1 while heap: _, curIdx = heappop(heap) if curIdx > maxIdx or nums[maxIdx] == nums[curIdx]: maxIdx = max(curIdx, maxIdx) continue res[curIdx] = maxIdx maxIdx = max(curIdx, maxIdx) return res print(find_right_index([21,5,6,56,88,52]))
fa4024757d899635360db79b14fcb4e3d5e610af
jessy1082/itp_week_1
/day_3/test.py
1,012
3.8125
4
list_4 = ["abc", 34, True, 40, "male"] list_5 = [["John", "Smith"], ["Jane", "Doe"]] print(type(list_5)) # <class 'list'> print(len(list_5)) # 2 fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(fruits[0]) # "apple" print(fruits[-1]) # "mango" print(fruits[-7]) # "apple" print(fruits[2:5]) # ['cherry', 'orange','kiwi'] print(fruits[:4]) # "apple", "banana", "cherry", "orange" # NOT INCLUDE KIWI print(fruits[2:]) # "cherry", "orange", "kiwi", "melon", "mango" print(fruits[-4:-1]) # "orange" (-4) to, but NOT including "mango" (-1) fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] if "apple" in fruits: print("Yes, 'apple' is in the fruits list") fruits[0] = "strawberry" print(fruits) fruits[1:3] = ["blackcurrant", "watermelon"] print(fruits) more_fruits = ["raspberry", "coconut", "pineapple"] more_fruits[1:2] = ["grape", "durian"] print(more_fruits) sports = ["football","soccer","baseball"] sports.append("lacrosse") print(sports)
bc9f45158341a38bb908793c649916dd56eb0775
amcgrat/UCD_DATACAMP
/WEEK_4.py
1,118
3.890625
4
import pandas as pd import numpy as np #raad the .csv file netflix_data = pd.read_csv(r"C:\Users\amcgrat\\Desktop\netflix_titles.csv") #Take a first look to understand the data #print(netflix_data.head()) #print(netflix_data.shape) #Count missing values in each column missing_values_count = netflix_data.isnull().sum() #print(missing_values_count[0:]) #Drop rows where data is missing droprows= netflix_data.dropna() print(netflix_data.shape,droprows.shape) print (droprows.head()) #Drop Columns where data is missing dropcolumns = netflix_data.dropna(axis=1) print(netflix_data.shape,dropcolumns.shape) #Fill all missing values with 0 cleaned_data = netflix_data.fillna(0) #Fill all missing values to the value that comes next in the same column cleaned_data = netflix_data.fillna(method='bfill', axis=0).fillna(0) #Drop all rows that are duplicate drop_duplicates= netflix_data.drop_duplicates() print(netflix_data.shape,drop_duplicates.shape) #Drop Duplicate Rows based on specific columns drop_duplicates= netflix_data.drop_duplicates(subset=['show_id']) print(netflix_data.shape,drop_duplicates.shape)
c286fd68f207fee0d0a91dcd511762eeb75fdc78
yoyocheknow/leetcode_python
/3_lengthOfLongestSubstring.py
2,250
3.796875
4
# -*- coding:utf-8 -*- class Solution(object): # 其实这道题我卡了很久,原因是不知道python从i+1的地方遍历,然后就想到用while的方式,每次for循环一次,就把上一次循环过的字符删掉 def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if not s: return 0 tmp_list=[] max_length=1 length=len(s) s_copy=list(s) while(length>0): for i, v in enumerate(s_copy): if v not in tmp_list: tmp_list.append(v) else: max_length=len(tmp_list) if len(tmp_list)>max_length else max_length tmp_list = [] s_copy.pop(0) break length-=1 return max_length # 上面那个算法是不知道如何i+1遍历,可以用range(),但是这个o(n^2),会超时,但是和上一个其实是一个思路 def lengthOfLongestSubstring1(self, s): """ :type s: str :rtype: int """ if not s: return 0 tmp_list=[] max_length=1 s_copy=list(s) for i in range(len(s_copy)): for j in range(i, len(s_copy)): if s_copy[j] not in tmp_list: tmp_list.append(s_copy[j]) else: max_length = len(tmp_list) if len(tmp_list) > max_length else max_length tmp_list = [] break return max_length #滑动窗口的思想解决 def lengthOfLongestSubstring2(self, s): """ :type s: str :rtype: int """ length, i, j, max_length = len(s), 0, 0, 0 s_copy = list(s) slide_window=set() while(i<length and j <length): if s_copy[j] not in slide_window: slide_window.add(s_copy[j]) j+=1 max_length=max(max_length, j-i) else: slide_window.remove(s_copy[i]) i+=1 return max_length if __name__ == "__main__": r = Solution().lengthOfLongestSubstring1('abaabcbb') print r
e628908685020e60cc86acd6d4c4e14edd6280a2
UMBC-CMSC-Hamilton/cmsc201-spring2021
/files_dir/fileio_slices.py
7,131
4.15625
4
if __name__ == '__main__': """ How do you open a file? There's a built-in-function File name is a string, literal, or a variable. """ if False: x = 3 # pycharm is reading everything as being based in the main directory. # because we're in a subdirectory, we need to tell it that. # two ways to denote directories # my_file_name = 'files_dir\\blah.txt' my_file_name = 'files_dir/blah.txt' # this one is best print(my_file_name) # reason is, \\ are an escape sequence which stands for one backslash # backslashes are the windows style directory markings, forward slash is linux/mac style # you can always use the linux style even in windows, and python generally fixes it up for you. # \\ like \n \r \t (\a <-- doesn't always work) ... """ 3 modes in python, read, write, and append for now, let's talk about read mode. Accidentally just try to read from the file name string, rather than the file itself. Open is a function that takes two strings, file_name, mode, returns "file" object """ my_file = open(my_file_name) # we're in read MODE, default is 'r' print(my_file.read()) # .read() reads the entire file at once # .read() can be dangerous if you don't know that the file will be small. Take a long time. # most of the time you won't use read, but you should know it exists and use it if it makes sense my_file.close() # tells the OS (windows/linux/mac) that we're finished looking at the file my_file = open(my_file_name, 'r') # we're in read MODE # the plural one, readlines makes a list of the lines the_lines = my_file.readlines() # creates a list of each line print(the_lines[3]) for line in the_lines: print(line) # if you haven't stripped the new line, there will be two newlines print(line.strip('\n')) print(line, end="") print('\n\n\n') # little hiccup in the function. (not a bug, it's a feature) # my_file.read().split('\n') and my_file.readlines() readlines will still have the newline characters... # a bit subtle maybe? my_file.close() my_file = open(my_file_name, 'r') # we're in read MODE """ How can we explain this behavior? a file has a "cursor" it's a place where the OS thinks is the current position. """ my_line = my_file.readline() while my_line: print("here is a line: " + my_line.strip('\n')) my_line = my_file.readline() # when my_file.readline() reaches "EOF = end of file" then it'll return empty string # empty string evaluates to false. my_file.close() """ Elegant, beautiful, great way to do it. Use python's in-built iteration processes """ my_file = open(my_file_name) # most common way to read for my_line in my_file: print('iteration is great\t', my_line.strip()) # python is basically saying to the file "what's next?" # the file will call readline for you and put that result into the variable. # not closing a file in read mode == not the end of the world, you're going to be ok my_file.close() # not closing a file in write mode == 'unpredictable... scary times' """ Write and Append modes Write mode. """ write_file_name = 'files_dir/movies.txt' write_file = open(write_file_name, 'w') movie_name = input('Tell me movie: ') while movie_name != 'quit': # difference between these two is that write takes a string, writelines takes a List[str] write_file.write(movie_name + '\n') # readlines /read/readline does not REMOVE a newline character # write does not add newline characters # have to add the new line in movie_name = input('Tell me movie: ') # naughty human write_file.close() input('This is useless just a placeholder, hang on...') """ Massive warning, danger label on 'w' mode. Write mode will annihilate your file, set it to empty, delete everything, goodbye file contents """ write_file = open(write_file_name, 'w') book_name = input('Tell me book: ') while book_name != 'quit': # difference between these two is that write takes a string, writelines takes a List[str] write_file.write(book_name + '\n') # readlines /read/readline does not REMOVE a newline character # write does not add newline characters # have to add the new line in book_name = input('Tell me book: ') write_file.close() """ Maybe you don't want that... there's a slight compromise way to do that mode = 'a' = append mode Opens the file (just like write mode) Sets the cursor to the end Doesn't blank the file Is ready to write. """ append_file = open(write_file_name, 'a') # uber-mega-definitely important to get right. book_name = input('Tell me game: ') while book_name != 'quit': # difference between these two is that write takes a string, writelines takes a List[str] append_file.write(book_name + '\n') # readlines /read/readline does not REMOVE a newline character # write does not add newline characters # have to add the new line in book_name = input('Tell me game: ') append_file.close() """ Rule: it takes about 2-3x as long as i think to do any given task. There we go. """ new_test = 'files_dir/test.txt' new_test_file = open(new_test, 'w') # test.txt didn't exist until i created it with this command. lines = ['apple', 'bag', 'cheese', 'dog'] for i in range(len(lines)): # definitely have to add the newlines lines[i] = lines[i] + '\n' new_test_file.writelines(lines) # I didn't think writelines (even though you might think based on the name... ) added the \n characters # as it turns out i was actually right, huh... new_test_file.close() """ 3 things to keep in mind: 1) close your files 2) only use 'w' mode when you want to erase the file, otherwise 'a' 3) newlines, read doesn't strip them, write doesn't add them. read/write from/to a file needs max control. Python gives you that control. All you need to know is r, w, a. You probably won't need byte mode unless I specify. You won't need the + modes. r+, w+, a+ all kinds of weird partial modes read/write """
d3ee02507c3e1f4e4e559d2b4bc620f04d542247
Indra-Ratna/LAB9-1114
/lab9_problem4.py
216
3.515625
4
#Indra Ratna #CS-UY 1114 #2 Nov 2018 #Lab 9 #Problem 4 def mycount(lst,n): count=0 for element in lst: if(element == n): count+=1 return count print(mycount([7,2,1,3,7,9],7))
70389e06f7d1863e66a43cac9a85cca1be36f290
upsharma8/Python_Programs
/Python Programs/demo16.py
551
4
4
#File Handling #How to acess a file #Step 1- Create a file to be access #Step 2- Access the file ''' open('E:\\upmanyu\\Python\\myname.txt','r') print(r.read()) r=open('E:/upmanyu/Python/myname.txt','w') r.write('I am a python programmer \n I like to write python code') r.close() print('File written succesfully') ''' #copy a file data #open old file oldfile=open('E:\\upmanyu\\Python\\myname.txt','r') newfile=open('E:\\upmanyu\\Python\\hello.txt','w') newfile.write(oldfile.read()) newfile.close() print('Data copied')
ff8e7bb527961d2813417f40e5fcc3c03f056b94
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/mknnit002/util.py
2,194
3.796875
4
#mknnit002 #question2 ass 7 def create_grid(grid): """create a 4x4 grid""" for i in range (4): grid.append([0]*4) #append each row of the grid one at a time return grid def print_grid(grid): """print out 4x4 grid in 5-width columns within a box""" print("+--------------------+") #prints the top of the box for row in range(4): print("|", end="") #prints the left side of the box for col in range (4): if grid[row][col]==0: print(" "*5, end="") #prink blank spaces if item is a zero else: print(grid[row][col],(5-len(str((grid[row][col]))))*" ", sep="",end="") print("|") #print left of box print("+--------------------+") #print bottom of box def check_lost(grid): """return True if there are no 0 values and no adjacent values that are equal; otherwise False""" for row in range(4): for col in range (4): if grid[row][col]==0: return False if row!=3: if gird[row][col]==grid[row+1][col]: return False if col!=3: if grid[row][col]==grid[row][col+1]: return False return True def check_one(grid): """return True if a value>=32 is found in the grid; otherwise False""" for row in range(4): for col in range(4): if gird[row][col]>=32: return True return False def copy_grid(grid): """return a copy of the grid""" copygrid=[] for row in reange(4): rowlist=[] for col in range (4): rowlist.append(grid[row][col]) copygrid.append(rowlist) return copy_grid def grid_equal(grid1, grid2): """check if two grids are equal- return boolean value""" for row in range(4): for col in range (4): if grid1[row][col]!=grid2[row][col]: return False return True
ab38e492222ce3e77a98b3dbf9184f2b6e2dc3c6
anuunnikrishnan/Python
/PYTHON 1/DbconnectPython/Dbconnection2.py
457
3.65625
4
from DbconnectPython.openconnection import * db=getconnection() print(db) # prepare a cursor object using cursor() method cursor=db.cursor() # Drop table if it already exists using execute() method cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # Create table as per requirement sql="""CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20), LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT)""" cursor.execute(sql)
1645d55d7dfe1291c84e1ae05e4dbf1262fff745
AlgorithmStars/Jeongmin
/leetCode/06longestPalindrome.py
981
3.609375
4
class Solution: def findShortPalindromeIndex(self, s:str) -> tuple[int, int]: if len(s) == 1: return for start in range(len(s) - 2): if s[start] == s[start + 2]: #odd palindrome yield start, start + 2 if s[start] == s[start + 1]: # even palindrome yield start, start + 1 if s[len(s) - 2] == s[len(s) - 1]: yield len(s) - 2, len(s) - 1 def longestPalindrome(self, s:str) -> str: palinGenerator = self.findShortPalindromeIndex(s) result = "" for start, end in palinGenerator: while (start >= 1 and end <= len(s) - 2) and (s[start -1] == s[end +1]): start -= 1 end += 1 result = max(result, s[start:end+1], key=len) return result if len(result) else s[0] sol = Solution() string = ["babad", "cbbd", "fff", "a", "ac"] for s in string: print(sol.longestPalindrome(s))
4f2158b8fee86e2d4f29765e127f075139e6fbb6
PetrTimof/pyth2
/less3.py
2,841
3.546875
4
# 1 def non_zero_del(var1, var2): try: result = var1 / var2 except ZeroDivisionError: return "Вы разделили на ноль и перешли на следующий уровень бытия! Поздравляю!" else: return result temp = non_zero_del(int(input('Введите делимое:\n')), int(input('Введите делитель:\n'))) print(temp) # 2 def data_printer(**kwargs) -> str: line = '' for kw, args in kwargs.items(): line += f'{kw}: {args}, ' return line user_answer_template = { 'имя': '', 'фамилия': '', 'год рождения': '', 'город проживания': '', 'адрес эл. почты': '', 'номер телефона': '' } for key in user_answer_template.keys(): user_answer = input(f'Пожалуйста, введите {key}:\n') user_answer_template[key] = user_answer print(data_printer(**user_answer_template)) # 3 def my_func(first_number: int, second_number: int, third_number: int) -> int: if first_number >= second_number: if second_number >= third_number: return first_number + second_number else: return first_number + third_number else: if first_number >= third_number: return first_number + second_number else: return second_number + third_number numbers = [] while True: try: user_number = int(input('Введите, пожалуйста, целое число:\n')) except ValueError as e: print(f'{e}. Это не число, введите число') else: numbers.append(user_number) if len(numbers) > 2: break a, b, c = numbers print(my_func(a, b, c)) # 4 def my_func(x, y): if y == 0: return 1 elif y == 1: return x result = x for _ in range(1, my_func(x, abs(y) - 1)): result += x return result if y > 0 else 1. / result # 5 def split_sum(): end_counter = False int_sum = 0 while not end_counter: string = input('Введите, пожалуйста, строку чисел, разделенных пробелом. Если вы хотите остановиться, ' 'введите ~.\n') result_list = list(string.split(' ')) for el in range(len(result_list)): if result_list[el] == '~': end_counter = True break else: try: int_sum += int(result_list[el]) except ValueError as e: print(f'{e} - этот символ не был учтен, поскольку это не число.') print(int_sum) if __name__ == '__main__': split_sum()
0e05d3777858898a466c080299a6d1b0730b69ae
avanishsingh07/CodeChef_DSA
/»_Factors_Finding.py
189
3.59375
4
n = int(input("Enter the number")) l = [] count = 0 for i in range(1,n+1): if n % i == 0: count = count +1 l.append(i) print(count) for j in l: print(j, end = " ")
6653eab81f09a61c4631f8308b38e89679427652
prithvi020397/awesomeScripts
/yt_clipper/yt_clipper.py
2,891
3.90625
4
#! /usr/bin/env python3 import re import argparse import subprocess def find_url(string): """ Finds an arbitrary number of URLs in a string and returns them in a list. Taken from: https://www.geeksforgeeks.org/python-check-url-string/""" regex = ( r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s" r"()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s(" r")<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))" ) url = re.findall(regex, string) return [x[0] for x in url] # Parse arguments parser = argparse.ArgumentParser(description="make clips from youtube videos") parser.add_argument("url", help="video url") parser.add_argument("start", help="HH:MM:SS") parser.add_argument("end", help="HH:MM:SS") parser.add_argument("-s", "--scale", help="scale image vertically (in px)", type=int, default=-2) parser.add_argument("-a", "--audio-only", action="store_true", dest="audio_only") parser.add_argument("-g", "--gif", action="store_true") parser.add_argument("-f", "--fps", type=int, default=12, help="gif fps") parser.add_argument("-o", "--output") parser.add_argument("-q", "--quiet", action="store_true") args = parser.parse_args() # Get video ID to use as default file name get_id = subprocess.Popen( ["youtube-dl", "--get-id", args.url], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, ) video_id = None while not video_id: # Sometimes `get_id` returns nothing out, err = get_id.communicate() get_id.wait() video_id = out.strip() # Remove newlines # Get video and audio URLs get_url = subprocess.Popen( ["youtube-dl", "-g", args.url], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, ) out, err = get_url.communicate() get_url.wait() video_url, audio_url = find_url(out) # Define ffmpeg commands ffmpeg_cmd = f"ffmpeg -ss {args.start} -to {args.end} -i {video_url} -ss {args.start}\ -to {args.end} -i {audio_url} -map 0:v -map 1:a -c:v libx264 -c:a aac\ -vf scale={args.scale}:-2:flags=lanczos -y {video_id}.mp4" if args.audio_only: ffmpeg_cmd = f"ffmpeg -ss {args.start} -to {args.end} -i {audio_url} -c:a aac -y\ {video_id}.aac" if args.gif: ffmpeg_cmd = ( f"ffmpeg -ss {args.start} -to {args.end} -i {video_url}" f" -filter_complex [0:v]fps={args.fps},scale={args.scale}:-2" ":flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse" f" -y {video_id}.gif" ) # Split command in a list to use later with subprocess.Popen ffmpeg_args = ffmpeg_cmd.split() if args.output: ffmpeg_args[-1] = args.output if args.quiet: ffmpeg_args = ffmpeg_args + ["-v", "fatal"] # Run ffmpeg make_clip = subprocess.Popen(ffmpeg_args) make_clip.wait()
4ee7d820d8f32386cf5b3c0296f0cef7208252c7
KhanyiMM/Pre-bootcamp-python
/Task 4.py
183
3.984375
4
def three(x,y): total_sum = x + y if '3' in str(total_sum): return True elif x == 3 or y == 3: return True else: return False print(three(7,8))
cd68ed20c520f22a480d640590feb8c388b3a87d
cedro-gasque/cs-module-project-recursive-sorting
/src/sorting/sorting.py
2,665
4
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): arr = [] a = b = 0 while a < len(arrA) and b < len(arrB): l = arrA[a] < arrB[b] n = not l arr.append(arrA[a] * l + arrB[b] * n) a += l b += n arr.extend(arrA[a:]) arr.extend(arrB[b:]) return arr # TO-DO: implement the Merge Sort function below recursively merge_sort = lambda arr : arr if len(arr) <= 1 else merge( merge_sort( arr[:len(arr)//2] ), merge_sort( arr[len(arr)//2:] ) ) # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input def merge_in_place(arr, start, mid, end): if arr[start] > arr[end]: arr[start:mid], arr[mid:end] = arr[mid:end], arr[start:mid] # "This is also a lot faster (4x) than most of the other solutions, # for 100k elements on my Core2Duo with Python2.7 (Ubuntu15.10 x86-64). # It doesn't make any mmap/munmap system calls while running, # so it's actually swapping in-place instead of making the interpreter # allocate and free scratch memory." # - a random stack overflow comment from 2016 so maybe it's still true lol merge_sort_in_place = lambda arr, l, r : arr if r - l <= 1 else merge_in_place( merge_sort_in_place( arr, l, (l + r) // 2 ), merge_sort_in_place( arr, (l + r) // 2, r ) )
25ed1ca68b6618791ab658b86940770d02658631
flyfatty/PythonTutorial
/leetcode/tree/106.py
845
3.65625
4
# @Time : 2020/10/14 13:23 # @Author : LiuBin # @File : 106.py # @Description : # @Software: PyCharm """从中序与后序遍历序列构造二叉树 关键字: 后序遍历 思路: 1、利用后序遍历列表定位root 2、利用中序遍历列表定位左右子树,注意是先右再左 3、递归缩减问题规模 """ from utils import TreeNode from typing import List class Solution: def buildTree(self, inorder: List[int], postorder: List[int]): if not postorder or not inorder: return root_val = postorder.pop() root = TreeNode(root_val) idx = inorder.index(root_val) root.right = self.buildTree(inorder[idx + 1:], postorder) root.left = self.buildTree(inorder[:idx], postorder) return root print(Solution().buildTree([9, 3, 15, 20, 7], [9, 15, 7, 20, 3]))
972f8b85276b235ebcfa947435b7de0eb15f65b7
CompPhysics/MachineLearning
/doc/src/week36/programs/test2.py
1,727
4.09375
4
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression np.random.seed(2021) def fit_beta(X, y): return np.linalg.pinv(X.T @ X) @ X.T @ y true_beta = [2, 0.5, 3.7] x = np.linspace(0, 1, 11) y = np.sum( np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0 ) + 0.1 * np.random.normal(size=len(x)) degree = 3 X = np.zeros((len(x), degree)) # Include the intercept in the design matrix for p in range(degree): X[:, p] = x ** p beta = fit_beta(X, y) # Intercept is included in the design matrix clf = LinearRegression(fit_intercept=False).fit(X, y) print(f"True beta: {true_beta}") print(f"Fitted beta: {beta}") print(f"Sklearn fitted beta: {clf.coef_}") plt.figure() plt.scatter(x, y, label="Data") plt.plot(x, X @ beta, label="Fit") plt.plot(x, clf.predict(X), label="Sklearn (fit_intercept=False)") # Do not include the intercept in the design matrix X = np.zeros((len(x), degree - 1)) for p in range(degree - 1): X[:, p] = x ** (p + 1) # Intercept is not included in the design matrix clf = LinearRegression(fit_intercept=True).fit(X, y) # Use centered values for X and y when computing coefficients y_offset = np.average(y, axis=0) X_offset = np.average(X, axis=0) beta = fit_beta(X - X_offset, y - y_offset) intercept = np.mean(y_offset - X_offset @ beta) print(f"Manual intercept: {intercept}") print(f"Fitted beta (sans intercept): {beta}") print(f"Sklearn intercept: {clf.intercept_}") print(f"Sklearn fitted beta (sans intercept): {clf.coef_}") plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)") plt.plot(x, clf.predict(X), "--", label="Sklearn (fit_intercept=True)") plt.grid() plt.legend() plt.show()
90889eef40379753e32ac7a61da5b49a921e1dac
andigibson93/snake-game
/pysnake/snake.py
6,055
3.5
4
from pygame.locals import * from random import randint import pygame import time SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SNAKE_SIZE=25 APPLE_SIZE=20 BANANA_SIZE=20 CHERRY_SIZE=20 GRAPE_SIZE=20 class Fruit: x = 0 y = 0 def __init__(self,x,y): self.x = x * APPLE_SIZE self.y = y * APPLE_SIZE def draw(self, surface, image): surface.blit(image,(self.x, self.y)) class Player: x = [0] y = [0] direction = 0 length = 3 updateCountMax = 2 updateCount = 0 def __init__(self, length): self.length = length for i in range(0,2000): self.x.append(-100) self.y.append(-100) # initial positions, no collision. self.x[1] = 1*SNAKE_SIZE self.x[2] = 2*SNAKE_SIZE def update(self): self.updateCount = self.updateCount + 1 if self.updateCount > self.updateCountMax: # update previous positions # for (i = length -1; i>0; i--) for i in range(self.length-1,0,-1): self.x[i] = self.x[i-1] self.y[i] = self.y[i-1] # update position of head of snake if self.direction == 0: self.x[0] = self.x[0] + SNAKE_SIZE if self.direction == 1: self.x[0] = self.x[0] - SNAKE_SIZE if self.direction == 2: self.y[0] = self.y[0] - SNAKE_SIZE if self.direction == 3: self.y[0] = self.y[0] + SNAKE_SIZE if self.x[0] > SCREEN_WIDTH: self.x[0] = 0 if self.y[0] > SCREEN_HEIGHT: self.y[0] = 0 if self.x[0] < 0: self.x[0] = SCREEN_WIDTH - SNAKE_SIZE if self.y[0] < 0: self.y[0] = SCREEN_HEIGHT - SNAKE_SIZE self.updateCount = 0 def moveRight(self): if self.direction != 1: self.direction = 0 def moveLeft(self): if self.direction != 0: self.direction = 1 def moveUp(self): if self.direction != 3: self.direction = 2 def moveDown(self): if self.direction != 2: self.direction = 3 def draw(self, surface, image): for i in range(0,self.length): surface.blit(image,(self.x[i],self.y[i])) class Game: #checks if the snake and the apple collides, and snake collides with itself def isCollision(self,x1,y1,x2,y2, asize, bsize): if x1 + asize > x2 and x1 < x2 + bsize: if y1 + asize > y2 and y1 < y2 + bsize: return True return False class App: windowWidth = SCREEN_WIDTH windowHeight = SCREEN_HEIGHT player = 0 apple = 0 def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self._fruit_surf = list() self._fruit_number = 1 self.game = Game() self.player = Player(5) #change the size of the player self.apple = Fruit(5,5) def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Pygame pythonspot.com example') self._running = True self._image_surf = pygame.image.load("snake.png").convert() self._apple_surf = pygame.image.load("apple.png").convert() self._fruit_surf.append(pygame.image.load("apple.png").convert()) self._fruit_surf.append(pygame.image.load("banana.png").convert()) self._fruit_surf.append(pygame.image.load("grape.png").convert()) self._fruit_surf.append(pygame.image.load("cherry.png").convert()) def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.player.update() # does snake eat apple? for i in range(0,self.player.length): if self.game.isCollision(self.apple.x,self.apple.y,self.player.x[i], self.player.y[i],APPLE_SIZE, SNAKE_SIZE): self.apple.x = randint(2,SCREEN_WIDTH - APPLE_SIZE) #where the apples are placed on the screen self.apple.y = randint(2,SCREEN_HEIGHT - APPLE_SIZE) self.player.length = self.player.length + 1 self._fruit_number = randint(0, len(self._fruit_surf)-1) # does snake collide with itself? for i in range(2,self.player.length): if self.game.isCollision(self.player.x[0],self.player.y[0],self.player.x[i], self.player.y[i],SNAKE_SIZE, SNAKE_SIZE): print("You lose! Collision: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") exit(0) pass def on_render(self): self._display_surf.fill((0,0,0)) self.player.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._fruit_surf[self._fruit_number]) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False clock = pygame.time.Clock() while( self._running ): pygame.event.pump() keys = pygame.key.get_pressed() if (keys[K_RIGHT]): self.player.moveRight() if (keys[K_LEFT]): self.player.moveLeft() if (keys[K_UP]): self.player.moveUp() if (keys[K_DOWN]): self.player.moveDown() if (keys[K_ESCAPE]): self._running = False self.on_loop() self.on_render() clock.tick(50) self.on_cleanup() if __name__ == "__main__" : print("Hello") theApp = App() theApp.on_execute()
527aef6e93a1966a3f349ed5e79e9d5a34612905
sgriffith3/2020-12-07-PyNDE
/funcy.py
405
3.953125
4
""" This is an example of a basic function. """ def add_111(any_number): """ This function adds 111 to any_number """ response = any_number + 111 print(f"Your number is: {response}") return response add_111(55) add_111(5) add_111(89) add_111(3.14) print(add_111(42)) x = add_111(add_111(1)) print(x, "coolio") # def print(*objects, sep=" ", end="\n" ...): # print("something")
ad1ea5d5eaccebf301240d604f66cc34cc9ffa01
mwroffo/FastCardsOnline
/app/Deck.py
3,990
4.125
4
from Card import Card """ Representing a deck of flash`Card`s. There are plenty of prebaked structures for this purpose, but for the sake of data structures practice, I built this from scratch. In data structures terms, this is most like a List. It allows inserts and removals at head, tail, or anywhere in the middle, in addition to sets and contains, indexOf, etc. 2018-07-22 mwroffo """ class Deck: """ Models a deck of flash`Card`s. Knows the deck's name and the cards in it. Iterable. Allows dups. """ def __init__(self, name, cards=[]): """ init a deck with list of cards as arg, or empty list """ self._name = name self._cards = cards # a `Deck` is a `list` of `Card`s self._size = len(cards) def getSize(self): return self._size def doesContain(self, other): for i in range(len(self._cards)): if self._cards[i] == other: return True # should `break` automatically with retur return False def set(self, index, card): """ sets the card at index `index` to equal `card` """ self._cards[index] = card def indexOf(self, card): """ return index of `card`. if not found, return -1 """ for i in range(len(self._cards)): if self._cards[i] == card: return i return -1 def tailInsert(self, card): """ add a `Card` to the end of the deck """ self._cards.append(card) self._size += 1 def headInsert(self, card): """ add a `Card` to the front of the deck """ self._cards.insert(0, card) self._size += 1 def insertAt(self, card, index): """ add a `Card` before index `index` """ self._cards.insert(index, card) self._size += 1 def remove(self, card): """ remove the matching `Card` from the deck """ self._cards.remove(card) self._size -= 1 def clear(self): """ empties the `Deck` """ self._cards = [] self._size = 0 def getName(self): """ returns the name of the `Deck` """ return self._name def setName(self, name): """ sets the name of the `Deck` """ self._name = name def getCards(self): """ returns the `Card`s in the `Deck` as a `list`. """ return self._cards def setCards(self, cards): """ sets the `Card`s in the `Deck` to `cards`. """ self._cards = cards self._size = len(cards) def __str__(self): """ returns a str representation of the deck """ cardstrs = [] for card in self.getCards(): cardstrs.append(str(card)) return "{} CARDS IN DECK {}: {}".format(str(self._size), self.getName().upper(), cardstrs) def _main(): """ test client """ # test card constructor card = Card("Who murdered a man for Annagret?", "Andreas Wolf did. He\'s very charismatic.") card2 = Card("What is Purity\'s mother\'s name?", "Anabel.") deck = Deck("Purity Trivia", [card, card2]) # test constructor: init deck with a list card3 = Card("Who is it that knows Andreas Wolf\'s great secret?", "Tom. And his daughter, Purity.") deck.tailInsert(card3) # test set: deck.set(1, Card("I am now", "The second card")) print(deck) print() # test insertAt: card4 = Card("I will be inserted", "third") deck.insertAt(card4, 2) print(deck) print() # test index of index = deck.indexOf(card4) print("EXPECTED 2, ACTUAL {}".format(str(index))) # test card set methods: card4.setTerm("I will be") card4.setDefinition("gone") deck.set(index, card4) print("EXPECTED third card to change, ACTUAL {}".format(str(deck))) # test removal deck.remove(card4) print("EXPECTED third card to be removed, ACTUAL {}".format(deck)) if __name__ == '__main__': _main()
f39ded82b49866952dc9e686639312704c85cf8a
suppressf0rce/ProgramTranslators_Homework1
/src/Token.py
1,121
4.1875
4
# Token types # # EOF (end-of-file) token is used to indicate that # there is no more input left for lexical analysis INTEGER, PLUS, MINUS, MUL, DIV, EOF, OPEN_PARENTHESES, CLOSE_PARENTHESES, STRING, ASSIGN, COMMA, EQUALS, LESS, GREATER, LEQUALS, GEQUALS = ( 'INTEGER', 'PLUS', 'MINUS', 'MUL', 'DIV', 'EOF', 'OPEN_PARENTHESES', 'CLOSE_PARENTHESES', 'STRING', 'ASSIGN', 'COMMA', 'EQUALS', 'LESS', 'GREATER', 'LEQUALS', 'GEQUALS ' ) class Token(object): def __init__(self, type, value): # token type: INTEGER, PLUS, MINUS, MUL, DIV, or EOF self.type = type # token value: non-negative integer value, '+', '-', '*', '/', or None self.value = value def __str__(self): """String representation of the class instance. Examples: Token(INTEGER, 3) Token(PLUS, '+') Token(MUL, '*') """ return 'Token({type}, {value})'.format( type=self.type, value=repr(self.value) ) def __repr__(self): return self.__str__()
854e433fd05d867c6983a63dcc21f038108158a1
letsgolesco/Project-Euler
/problem_22.py
1,016
3.78125
4
# Names scores # # File given: names.txt, containing over 5000 first names # Begin by sorting the list into alphabetical order # Then work out the alphabetical value for each name # (sum of numbers corresponding to each letter) # Multiply this value by its position in the sorted list # That's the name score! # # What's the total of all name scores? # Function to find namescore def namescore(name, index): score = 0 # Iterate over chars & sum their values for char in name: score += ord(char) - 64 # Use unicode value & shift so A = 1 score *= index + 1 # Multiply by spot in list return score # Read in names file f = open('names.txt', 'r') bigstr = f.readline().replace('"', '') # Remove quotes names = bigstr.split(',') # Comma split names.sort() # Thank you based python # Iterate over names & sum their namescores total = 0 for j in range(len(names)): ns = namescore(names[j], j) total += ns print total
036a4525469b44316dc47bc2caee3e6b03fa8c58
praneethpeddi/Python-Assignments
/Oct20th-Dictionaries/diff_copy_assignment.py
377
4.28125
4
# assigning using assignment operator dict1 = {1: 'one', 2: 'two', 3: 'three', 4: 'four'} dict2 = dict1 dict2.clear() print(dict1) print(type(dict1)) print(dict2) print(type(dict2)) print() # assigning using the copy method dict1 = {1: 'one', 2: 'two', 3: 'three', 4: 'four'} dict2 = dict1.copy() dict2.clear() print(dict1) print(type(dict1)) print(dict2) print(type(dict2))
71c6c990cb067a053461d52af67c6a7f6bfa3c21
crystalDf/Automate-the-Boring-Stuff-with-Python-Chapter-10-Debugging
/traceback_format.py
262
3.65625
4
import traceback try: raise Exception('This is the error message.') except: error_file = open('errorInfo.txt', 'w') print(error_file.write(traceback.format_exc())) error_file.close() print('The traceback info was written to errorInfo.txt.')
bcf8b2e0750fb6d7d77df4712f801d44404ac7ff
gvolsky/Python-algorithms-practice
/BST.py
6,268
3.625
4
class BSTNode: def __init__(self, key, val, parent): self.NodeKey = key self.NodeValue = val self.Parent = parent self.LeftChild = None self.RightChild = None class BSTFind: def __init__(self): self.Node = None self.NodeHasKey = False self.ToLeft = False class BST: def __init__(self, node): self.Root = node def FindNodeByKey(self, key): finded_node = BSTFind() if self.Root is None: return finded_node node = self.Root while node is not None: if node.NodeKey == key: finded_node.Node = node finded_node.NodeHasKey = True return finded_node if key < node.NodeKey: if node.LeftChild is None: finded_node.Node = node finded_node.ToLeft = True return finded_node node = node.LeftChild else: if node.RightChild is None: finded_node.Node = node return finded_node node = node.RightChild def AddKeyValue(self, key, val): finded_node = self.FindNodeByKey(key) if finded_node.NodeHasKey: return False if finded_node.Node is None: self.Root = BSTNode(key, val, None) elif finded_node.ToLeft: finded_node.Node.LeftChild = BSTNode(key, val, finded_node.Node) else: finded_node.Node.RightChild = BSTNode(key, val, finded_node.Node) def FinMinMax(self, FromNode, FindMax): finded_element = BSTFind() if FromNode is None: return finded_element node = FromNode if FindMax: while node.RightChild is not None: node = node.RightChild finded_element.Node = node else: while node.LeftChild is not None: node = node.LeftChild finded_element.Node = node return finded_element def DeleteNodeByKey(self, key): removed_node = self.FindNodeByKey(key) if not removed_node.NodeHasKey: return False if removed_node.Node.LeftChild is None and removed_node.Node.RightChild is None: if removed_node.Node.Parent is None: self.Root = None elif removed_node.Node.Parent.LeftChild == removed_node.Node: removed_node.Node.Parent.LeftChild = None else: removed_node.Node.Parent.RightChild = None removed_node.Node.Parent = None elif removed_node.Node.RightChild is None: if removed_node.Node.Parent is None: self.Root = removed_node.Node.LeftChild removed_node.Node.LeftChild = None removed_node.Node.LeftChild.Parent = None else: removed_node.Node.LeftChild.Parent = removed_node.Node.Parent if removed_node.Node.Parent.LeftChild == removed_node.Node: removed_node.Node.Parent.LeftChild = removed_node.Node.LeftChild else: removed_node.Node.Parent.RightChild = removed_node.Node.LeftChild removed_node.Node.Parent = None elif removed_node.Node.LeftChild is None: if removed_node.Node.Parent is None: self.Root = removed_node.Node.RightChild removed_node.Node.RightChild = None removed_node.Node.RightChild.Parent = None else: removed_node.Node.RightChild.Parent = removed_node.Node.Parent if removed_node.Node.Parent.LeftChild == removed_node.Node: removed_node.Node.Parent.LeftChild = removed_node.Node.RightChild else: removed_node.Node.Parent.RightChild = removed_node.Node.RightChild removed_node.Node.Parent = None else: insert_node = self.FinMinMax(removed_node.Node.RightChild, False) if insert_node.Node.RightChild is None: if removed_node.Node.RightChild != insert_node.Node: insert_node.Node.Parent.LeftChild = None insert_node.Node.Parent = removed_node.Node.Parent if removed_node.Node.Parent is not None: if removed_node.Node.Parent.LeftChild == removed_node.Node: removed_node.Node.Parent.LeftChild = insert_node.Node else: removed_node.Node.Parent.RightChild = insert_node.Node else: self.Root = insert_node.Node else: if insert_node.Node == removed_node.Node.RightChild: insert_node.Node.Parent = removed_node.Node.Parent else: insert_node.Node.RightChild.Parent = insert_node.Node.Parent insert_node.Node.Parent.LeftChild = insert_node.Node.RightChild insert_node.Node.Parent = removed_node.Node.Parent if removed_node.Node.Parent is not None: if removed_node.Node.Parent.LeftChild == removed_node.Node: removed_node.Node.Parent.LeftChild = insert_node.Node else: removed_node.Node.Parent.RightChild = insert_node.Node else: self.Root = insert_node.Node insert_node.Node.LeftChild = removed_node.Node.LeftChild insert_node.Node.LeftChild.Parent = insert_node.Node if insert_node.Node != removed_node.Node.RightChild: insert_node.Node.RightChild = removed_node.Node.RightChild insert_node.Node.RightChild.Parent = insert_node.Node def Count(self): if self.Root is None: return 0 left_count = BST(self.Root.LeftChild).Count() right_count = BST(self.Root.RightChild).Count() return 1 + left_count + right_count
2a53bacaa3ebddac6bff10bef303c2cec25a69ac
s0409/DATA-STRUCTURES-AND-ALGORITHMS
/LONGEST CONSECUTIVE SUBSEQUENCE/main.py
457
3.765625
4
def longestsub(arr,n): #create hash s=set() ans=0 #insert all elements to hash for ele in arr: s.add(ele) #look for arr[i]-1 for i in range(n): if arr[i]-1 not in s: j=arr[i] while j in s: j+=1 ans=max(ans,j-arr[i]) return ans #driver code if __name__=="__main__": arr=[1,3,5,9,8,4,2] n=len(arr) print(longestsub(arr,n))
03f2c7f18b203cf6cac51f264e813730ac196cfa
cy275/Statistics_Calculator
/Stat_Calculator/Median.py
217
3.734375
4
def median(a): a = sorted(a) list_length = len(a) num = list_length//2 if list_length % 2 == 0: median_num = (a[num] + a[num + 1])/2 else: median_num = a[num] return median_num
2424d4fca4b1c3e51647f3101ee983fbe900a627
LocNguyenHuu2k/LocNguyen
/list_practice.py
505
3.6875
4
games = ["CSGO", "PUBG", "Leage of Legend", "Star Craft 2"] print(*games,sep=", ") new_games = input("What games would you like to add?") games.append(new_games) print(*games,sep=", ") remove_game = input("What game would you like to remove?") games.remove(remove_game) print(*games,sep=", ") for game, index in enumerate(games): print(game, "." , index) pos_remove = int(input("Postion to remove = ? ")) games.pop(pos_remove) for game, index in enumerate(games): print(game, "." , index)
967374a6092bdadf0f75662a1d85e012d208aa00
kitizl/spongePy
/spongePy.py
1,103
3.78125
4
#! python3 import sys import random def spongify(s): output = "" for i in range(len(s)): if i%2 == 0: output += s[i].upper() else: output += s[i].lower() return output def sponge_real(s): output = "" for i in range(len(s)): if random.randint(0,1): output += s[i].upper() else: output += s[i].lower() return output def usage_text(): print(""" Usage: python3 spongePy.py [option] < [input-file] > [output-file] [option] -r : To activate realistic mode instead of normal (default) mode Everything after that is optional. If you'd like to use the samples, set [input-file] to sample-inputs/[filename]. """) def do_the_thing(function_name): while True: try: print(function_name(input())) except EOFError: break if len(sys.argv) == 2 and sys.argv[1] == '-r' : do_the_thing(sponge_real) elif len(sys.argv) == 2: print("Input Error : Please recheck command.") # add usage text else: do_the_thing(spongify)
a1838322f123312e2009600c0af5ccac4d968024
pmheintz/PythonTutorials
/methods/methods_demo2.py
508
4.25
4
""" Working with more methods Adding documentation """ def sum_nums(n1, n2): """ Get the sum of 2 numbers :param n1: first number :param n2: second number :return: sum of n1 and n2 """ return n1 + n2 sum1 = sum_nums(1, 2) print(sum1) print(sum_nums(5, 7)) string_add = sum_nums("one", "two") print(string_add) print("*" * 20) def isMetro(city): l = ["sfo", "nyc", "la"] if city in l: return True else: return False x = isMetro("boston") print(x)
5e40f7e89c9ea1d4c5e4d7665a8743645b6233db
All3yp/Daily-Coding-Problem-Solutions
/Solutions/179.py
716
4
4
""" Problem: Given the sequence of keys visited by a postorder traversal of a binary search tree, reconstruct the tree. For example, given the sequence 2, 4, 3, 8, 7, 5, you should construct the following tree: 5 / \ 3 7 / \ \ 2 4 8 """ from typing import List from DataStructures.Tree import BinarySearchTree, Node def bst_from_postorder(postorder: List[int]) -> BinarySearchTree: tree = BinarySearchTree() if postorder: tree.add(postorder[-1]) for val in postorder[-2::-1]: tree.add(val) return tree if __name__ == "__main__": print(bst_from_postorder([2, 4, 3, 8, 7, 5])) """ SPECS: TIME COMPLEXITY: O(n log(n)) SPACE COMPLEXITY: O(n) """
f3f46edd2095db1cab58f27d92b568b96a3e9600
scric/Python3.x-2017
/begginger/2017-03-07/第四章 - 持久存储 - try/missingFile.py
926
3.953125
4
# 尝试打开一个不存在的文件 # try: # data=open('missing.txt') # print(data.readline(),end='') # except IOError: # print('File error') # finally: # data.close() ''' 出现错误 Traceback (most recent call last): File error File "D:/Python/python-git/begginger/2017-03-07/missingFile.py", line 12, in <module> data.close() NameError: name 'data' is not defined ''' # 修正方法,在finally上添加一个判断语句。 # try: # data=open('missing.txt') # print(data.readline(),end='') # except IOError as err: # print('File error'+str(err)) # finally: # if 'data' in locals(): # locals() BIF 会返回当前作用域中定义的所有名的集合 # data.close() # 不过还是不清楚什么导致了错误 # 使用with try: with open('missing.txt',"w") as data: print("It's...",file=data) except IOError as err: print('File error'+str(err))
8fc723c6bea4f557dddd68cd1d8fdf78fe61fc27
stefanolocci/English-Italian-Direct-Translator
/En_It_Translator/utils/NumberUtility.py
1,657
3.703125
4
class NumberUtility: def is_ordinal_number(self, word): try: int(word.replace('th', '')) return True except ValueError: return False def is_number(self, word): try: float(word) return True except ValueError: return False def __int_to_roman(self, num): """ Convert an integer to a Roman numeral. """ if not isinstance(num, type(1)): return False if not 0 < num < 4000: return False ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I') result = [] for i in range(len(ints)): count = int(num / ints[i]) result.append(nums[i] * count) num -= ints[i] * count return ''.join(result) def is_roman_number(self, num): """ Convert a Roman numeral to an integer. """ if not isinstance(num, type("")): return False num = num.upper() nums = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} sum = 0 for i in range(len(num)): try: value = nums[num[i]] # If the next place holds a larger number, this value is negative if i + 1 < len(num) and nums[num[i + 1]] > value: sum -= value else: sum += value except KeyError: return False # easiest test for validity... return self.__int_to_roman(sum) == num
700eb342c6eda26665431b0f2b77b34c0d831248
danrfiuza/learningpython
/datetimeexample.py
507
3.96875
4
import time; import datetime import calendar ticks = time.time() now = datetime.datetime.now() # print("Number of ticks since 12:00am, Jan 1,1970: ",ticks,end="\n") # cal = calendar.month(now.year, now.month) # print ("Here is the calendar:",end="\n") # print (cal) date = input('Wanna see calendar? type a date on this format: dd/mm/yyyy: ') date = date.split("/") day = int(date[0]) month = int(date[1]) year = int(date[2]) print ("Here is the calendar:",end="\n") print (calendar.month(year,month))
567f1004a4cd606b6458abd21585abc577350ba3
iwwxiong/leetcode.python
/5.longest-palindromic-substring/test_longest_palindromic_substring.py
928
3.6875
4
from longest_palindromic_substring import Solution, is_palindrome def test_is_palindrome(): assert is_palindrome("a") is True assert is_palindrome("aa") is True assert is_palindrome("ab") is False assert is_palindrome("abcb") is False assert is_palindrome("aba") is True def test_longestPalindrome(): s = Solution() assert s.longestPalindrome("a") == "a" assert s.longestPalindrome("ab") == "a" assert s.longestPalindrome("abba") == "abba" assert s.longestPalindrome("aaaa") == "aaaa" assert s.longestPalindrome("ababa") == "ababa" def test_longestPalindromeV2(): s = Solution() assert s.longestPalindromeV2("a") == "a" assert s.longestPalindromeV2("ab") == "a" assert s.longestPalindromeV2("aaa") == "aaa" assert s.longestPalindromeV2("abba") == "abba" assert s.longestPalindromeV2("aaaa") == "aaaa" assert s.longestPalindromeV2("ababa") == "ababa"
c3a2537add062a6b9a66ba203cfd83874c428f9f
lytr777/EvoGuess
/method/solver/models/option.py
691
3.609375
4
class SolverOption: def __init__(self, name, value): self.name = name self.value = value def str(self, form): return form % (self.name, self.value) def __str__(self): return self.str('%s=%s') def __eq__(self, other): if hasattr(other, 'name'): return self.name == other.name return False def __hash__(self): return hash(self.name) __all__ = [ 'SolverOption' ] if __name__ == '__main__': a = SolverOption('a', 1) b = SolverOption('b', 1) c = SolverOption('c', 1) s = set([a, b, c]) a2 = SolverOption('a', 1) d = SolverOption('d', 1) for o in s: print(o)
de93c76ce532000608a092c47b2060192459da58
dikshaa1702/ml
/mini project/challenge1.py
573
3.90625
4
# -*- coding: utf-8 -*- """ Created on Tue May 7 19:30:18 2019 @author: DiPu """ import random guess=random.randrange(1,11) print("enter number") no=int(input()) if(guess==no): print("player wins and computer lose") else: print("player lose and computer wins") print("random no: {0}".format(guess,no)) print("guess no: {1}".format(guess,no)) if no==guess: print("guess write") elif ((no<=guess+2) or (no>=guess-2)): print("too high") else: print("too low") while guess!=no: print("enter number") no=int(input()) print("guess matched")
d38cdb22f512683edc15a7f2d12cda9c6f4b52f0
MacJei/pyspark_py
/pyspark_1.py
47,319
4.1875
4
# What is Spark, anyway? # Spark is a platform for cluster computing. Spark lets you spread data and computations over clusters with multiple nodes (think of each node as a separate computer). Splitting up your data makes it easier to work with very large datasets because each node only works with a small amount of data. # # As each node works on its own subset of the total data, it also carries out a part of the total calculations required, so that both data processing and computation are performed in parallel over the nodes in the cluster. It is a fact that parallel computation can make certain types of programming tasks much faster. # # However, with greater computing power comes greater complexity. # # Deciding whether or not Spark is the best solution for your problem takes some experience, but you can consider questions like: # # Is my data too big to work with on a single machine? # Can my calculations be easily parallelized? # Using Spark in Python # The first step in using Spark is connecting to a cluster. # # In practice, the cluster will be hosted on a remote machine that's connected to all other nodes. There will be one computer, called the master that manages splitting up the data and the computations. The master is connected to the rest of the computers in the cluster, which are called slaves. The master sends the slaves data and calculations to run, and they send their results back to the master. # # When you're just getting started with Spark it's simpler to just run a cluster locally. Thus, for this course, instead of connecting to another computer, all computations will be run on DataCamp's servers in a simulated cluster. # # Creating the connection is as simple as creating an instance of the SparkContext class. The class constructor takes a few optional arguments that allow you to specify the attributes of the cluster you're connecting to. # # An object holding all these attributes can be created with the SparkConf() constructor. Take a look at the documentation for all the details! # # For the rest of this course you'll have a SparkContext called sc already available in your workspace. # EXERCISE # Examining The SparkContext # In this exercise you'll get familiar with the SparkContext. # # You'll probably notice that code takes longer to run than you might expect. This is because Spark is some serious software. It takes more time to start up than you might be used to. You may also find that running simpler computations might take longer than expected. That's because all the optimizations that Spark has under its hood are designed for complicated operations with big data sets. That means that for simple or small problems Spark may actually perform worse than some other solutions! # # INSTRUCTIONS # 100 XP # Get to know the SparkContext. # # Call print() on sc to verify there's a SparkContext in your environment. # print() sc.version to see what version of Spark is running on your cluster. # Verify SparkContext print(sc) # Print Spark version print(sc.version) #output: # Welcome to # ____ __ # / __/__ ___ _____/ /__ # _\ \/ _ \/ _ `/ __/ '_/ # /__ / .__/\_,_/_/ /_/\_\ version 2.1.0 # /_/ # # Using Python version 3.5.2 (default, Nov 17 2016 17:05:23) # SparkSession available as 'spark'. # # <script.py> output: # <pyspark.context.SparkContext object at 0x7fbf72930c18> # 2.1.0 # Using DataFrames # Spark's core data structure is the Resilient Distributed Dataset (RDD). This is a low level object that lets Spark work its magic by splitting data across multiple nodes in the cluster. However, RDDs are hard to work with directly, so in this course you'll be using the Spark DataFrame abstraction built on top of RDDs. # # The Spark DataFrame was designed to behave a lot like a SQL table (a table with variables in the columns and observations in the rows). Not only are they easier to understand, DataFrames are also more optimized for complicated operations than RDDs. # # When you start modifying and combining columns and rows of data, there are many ways to arrive at the same result, but some often take much longer than others. When using RDDs, it's up to the data scientist to figure out the right way to optimize the query, but the DataFrame implementation has much of this optimization built in! # # To start working with Spark DataFrames, you first have to create a SparkSession object from your SparkContext. You can think of the SparkContext as your connection to the cluster and the SparkSession as your interface with that connection. # # Remember, for the rest of this course you'll have a SparkSession called spark available in your workspace! # # Which of the following is an advantage of Spark DataFrames over RDDs? # Operations using DataFrames are automatically optimized. # EXERCISE # Creating a SparkSession # We've already created a SparkSession for you called spark, but what if you're not sure there already is one? Creating multiple SparkSessions and SparkContexts can cause issues, so it's best practice to use the SparkSession.builder.getOrCreate() method. This returns an existing SparkSession if there's already one in the environment, or creates a new one if necessary! # # INSTRUCTIONS # 100 XP # Import SparkSession from pyspark.sql. # Make a new SparkSession called my_spark using SparkSession.builder.getOrCreate(). # Print my_spark to the console to verify it's a SparkSession. # Import SparkSession from pyspark.sql from pyspark.sql import SparkSession # Create my_spark my_spark = SparkSession.builder.getOrCreate() # Print my_spark print(my_spark) # Using Python version 3.5.2 (default, Nov 17 2016 17:05:23) # SparkSession available as 'spark'. # # <script.py> output: # <pyspark.sql.session.SparkSession object at 0x7fbf5f08df28> # EXERCISE # Viewing tables # Once you've created a SparkSession, you can start poking around to see what data is in your cluster! # # Your SparkSession has an attribute called catalog which lists all the data inside the cluster. This attribute has a few methods for extracting different pieces of information. # # One of the most useful is the .listTables() method, which returns the names of all the tables in your cluster as a list. # # INSTRUCTIONS # 100 XP # See what tables are in your cluster by calling spark.catalog.listTables() and printing the result! # Print the tables in the catalog print(spark.catalog.listTables()) # EXERCISE # Are you query-ious? # One of the advantages of the DataFrame interface is that you can run SQL queries on the tables in your Spark cluster. If you don't have any experience with SQL, don't worry (you can take our Introduction to SQL course!), we'll provide you with queries! # # As you saw in the last exercise, one of the tables in your cluster is the flights table. This table contains a row for every flight that left Portland International Airport (PDX) or Seattle-Tacoma International Airport (SEA) in 2014 and 2015. # # Running a query on this table is as easy as using the .sql() method on your SparkSession. This method takes a string containing the query and returns a DataFrame with the results! # # If you look closely, you'll notice that the table flights is only mentioned in the query, not as an argument to any of the methods. This is because there isn't a local object in your environment that holds that data, so it wouldn't make sense to pass the table as an argument. # # Remember, we've already created a SparkSession called spark in your workspace. # # INSTRUCTIONS # 100 XP # Use the .sql() method to get the first 10 rows of the flights table and save the result to flights10. The variable query contains the appropriate SQL query. # Use the DataFrame method .show() to print flights10. # Don't change this query query = "FROM flights SELECT * LIMIT 10" # Get the first 10 rows of flights flights10 = spark.sql(query) # Show the results flights10.show() # EXERCISE # Pandafy a Spark DataFrame # Suppose you've run a query on your huge dataset and aggregated it down to something a little more manageable. # # Sometimes it makes sense to then take that table and work with it locally using a tool like pandas. Spark DataFrames make that easy with the .toPandas() method. Calling this method on a Spark DataFrame returns the corresponding pandas DataFrame. It's as simple as that! # # This time the query counts the number of flights to each airport from SEA and PDX. # # Remember, there's already a SparkSession called spark in your workspace! # # INSTRUCTIONS # 100 XP # Run the query using the .sql() method. Save the result in flight_counts. # Use the .toPandas() method on flight_counts to create a pandas DataFrame called pd_counts. # Print the .head() of pd_counts to the console. # Don't change this query query = "SELECT origin, dest, COUNT(*) as N FROM flights GROUP BY origin, dest" # Run the query flight_counts = spark.sql(query) # Convert the results to a pandas DataFrame pd_counts = flight_counts.toPandas() # Print the head of pd_counts print(pd_counts.head()) # EXERCISE # Put some Spark in your data # In the last exercise, you saw how to move data from Spark to pandas. However, maybe you want to go the other direction, and put a pandas DataFrame into a Spark cluster! The SparkSession class has a method for this as well. # # The .createDataFrame() method takes a pandas DataFrame and returns a Spark DataFrame. # # The output of this method is stored locally, not in the SparkSession catalog. This means that you can use all the Spark DataFrame methods on it, but you can't access the data in other contexts. # # For example, a SQL query (using the .sql() method) that references your DataFrame will throw an error. To access the data in this way, you have to save it as a temporary table. # # You can do this using the .createTempView() Spark DataFrame method, which takes as its only argument the name of the temporary table you'd like to register. This method registers the DataFrame as a table in the catalog, but as this table is temporary, it can only be accessed from the specific SparkSession used to create the Spark DataFrame. # # There is also the method .createOrReplaceTempView(). This safely creates a new temporary table if nothing was there before, or updates an existing table if one was already defined. You'll use this method to avoid running into problems with duplicate tables. # # Check out the diagram to see all the different ways your Spark data structures interact with each other. # # # # There's already a SparkSession called spark in your workspace, numpy has been imported as np, and pandas as pd. # # INSTRUCTIONS # 100 XP # The code to create a pandas DataFrame of random numbers has already been provided and saved under pd_temp. # Create a Spark DataFrame called spark_temp by calling the .createDataFrame() method with pd_temp as the argument. # Examine the list of tables in your Spark cluster and verify that the new DataFrame is not present. Remember you can use spark.catalog.listTables() to do so. # Register spark_temp as a temporary table named "temp" using the .createOrReplaceTempView() method. Rememeber that the table name is set including it as the only argument! # Examine the list of tables again! # Create pd_temp pd_temp = pd.DataFrame(np.random.random(10)) # Create spark_temp from pd_temp spark_temp = spark.createDataFrame(pd_temp) # Examine the tables in the catalog print(spark.catalog.listTables()) # Add spark_temp to the catalog spark_temp.createOrReplaceTempView("temp") # Examine the tables in the catalog again print(spark.catalog.listTables()) # EXERCISE # Dropping the middle man # Now you know how to put data into Spark via pandas, but you're probably wondering why deal with pandas at all? Wouldn't it be easier to just read a text file straight into Spark? Of course it would! # # Luckily, your SparkSession has a .read attribute which has several methods for reading different data sources into Spark DataFrames. Using these you can create a DataFrame from a .csv file just like with regular pandas DataFrames! # # The variable file_path is a string with the path to the file airports.csv. This file contains information about different airports all over the world. # # A SparkSession named spark is available in your workspace. # # INSTRUCTIONS # 100 XP # Use the .read.csv() method to create a Spark DataFrame called airports # The first argument is file_path # Pass the argument header=True so that Spark knows to take the column names from the first line of the file. # Print out this DataFrame by calling .show(). # Don't change this file path file_path = "airports.csv" # Read in the airports data airports = spark.read.csv(file_path, header=True) # Show the data airports.show() # EXERCISE # Creating columns # In this chapter, you'll learn how to use the methods defined by Spark's DataFrame class to perform common data operations. # # Let's look at performing column-wise operations. In Spark you can do this using the .withColumn() method, which takes two arguments. First, a string with the name of your new column, and second the new column itself. # # The new column must be an object of class Column. Creating one of these is as easy as extracting a column from your DataFrame using df.colName. # # Updating a Spark DataFrame is somewhat different than working in pandas because the Spark DataFrame is immutable. This means that it can't be changed, and so columns can't be updated in place. # # Thus, all these methods return a new DataFrame. To overwrite the original DataFrame you must reassign the returned DataFrame using the method like so: # # df = df.withColumn("newCol", df.oldCol + 1) # The above code creates a DataFrame with the same columns as df plus a new column, newCol, where every entry is equal to the corresponding entry from oldCol, plus one. # # To overwrite an existing column, just pass the name of the column as the first argument! # # Remember, a SparkSession called spark is already in your workspace. # # INSTRUCTIONS # 70 XP # INSTRUCTIONS # 70 XP # Use the spark.table() method with the argument "flights" to create a DataFrame containing the values of the flights table in the .catalog. Save it as flights. # Print the output of flights.show(). The column air_time contains the duration of the flight in minutes. # Update flights to include a new column called duration_hrs, that contains the duration of each flight in hours. # Create the DataFrame flights flights = spark.table('flights') # Show the head print(flights.show()) # Add duration_hrs flights = flights.withColumn('duration_hrs', flights.air_time/60) # EXERCISE # Filtering Data # Now that you have a bit of SQL know-how under your belt, it's easier to talk about the analogous operations using Spark DataFrames. # # Let's take a look at the .filter() method. As you might suspect, this is the Spark counterpart of SQL's WHERE clause. The .filter() method takes either a Spark Column of boolean (True/False) values or the WHERE clause of a SQL expression as a string. # # For example, the following two expressions will produce the same output: # # flights.filter(flights.air_time > 120).show() # flights.filter("air_time > 120").show() # Remember, a SparkSession called spark is already in your workspace, along with the Spark DataFrame flights. # # INSTRUCTIONS # 100 XP # Use the .filter() method to find all the flights that flew over 1000 miles two ways: # First, pass a SQL string to .filter() that checks the distance is greater than 1000. Save this as long_flights1. # Then pass a boolean column to .filter() that checks the same thing. Save this as long_flights2. # Print the .show() of both DataFrames and make sure they're actually equal! # Filter flights with a SQL string long_flights1 = flights.filter('distance > 1000') # Filter flights with a boolean column long_flights2 = flights.filter(flights.distance > 1000) # Examine the data to check they're equal print(long_flights1.show()) print(long_flights2.show()) # EXERCISE # Selecting # The Spark variant of SQL's SELECT is the .select() method. This method takes multiple arguments - one for each column you want to select. These arguments can either be the column name as a string (one for each column) or a column object (using the df.colName syntax). When you pass a column object, you can perform operations like addition or subtraction on the column to change the data contained in it, much like inside .withColumn(). # # The difference between .select() and .withColumn() methods is that .select() returns only the columns you specify, while .withColumn() returns all the columns of the DataFrame in addition to the one you defined. It's often a good idea to drop columns you don't need at the beginning of an operation so that you're not dragging around extra data as you're wrangling. In this case, you would use .select() and not .withColumn(). # # Remember, a SparkSession called spark is already in your workspace, along with the Spark DataFrame flights. # # INSTRUCTIONS # 100 XP # Select the columns tailnum, origin, and dest from flights by passing the column names as strings. Save this as selected1. # Select the columns origin, dest, and carrier using the df.colName syntax and then filter the result using both of the filters already defined for you (filterA and filterB) to only keep flights from SEA to PDX. Save this as selected2. # Select the first set of columns selected1 = flights.select('tailnum', 'origin', 'dest') # Select the second set of columns temp = flights.select(flights.origin, flights.dest, flights.carrier) # Define first filter filterA = flights.origin == "SEA" # Define second filter filterB = flights.dest == "PDX" # Filter the data, first by filterA then by filterB selected2 = temp.filter(filterA).filter(filterB) # EXERCISE # Selecting II # Similar to SQL, you can also use the .select() method to perform column-wise operations. When you're selecting a column using the df.colName notation, you can perform any column operation and the .select() method will return the transformed column. For example, # # flights.select(flights.air_time/60) # returns a column of flight durations in hours instead of minutes. You can also use the .alias() method to rename a column you're selecting. So if you wanted to .select() the column duration_hrs (which isn't in your DataFrame) you could do # # flights.select((flights.air_time/60).alias("duration_hrs")) # The equivalent Spark DataFrame method .selectExpr() takes SQL expressions as a string: # # flights.selectExpr("air_time/60 as duration_hrs") # with the SQL as keyword being equivalent to the .alias() method. To select multiple columns, you can pass multiple strings. # # Remember, a SparkSession called spark is already in your workspace, along with the Spark DataFrame flights. # # INSTRUCTIONS # 100 XP # Create a table of the average speed of each flight both ways. # # Calculate average speed by dividing the distance by the air_time (converted to hours). Use the .alias() method name this column "avg_speed". Save the output as the variable avg_speed. # Select the columns "origin", "dest", "tailnum", and avg_speed (without quotes!). Save this as speed1. # Create the same table using .selectExpr() and a string containing a SQL expression. Save this as speed2. # Define avg_speed avg_speed = (flights.distance/(flights.air_time/60)).alias("avg_speed") # Select the correct columns speed1 = flights.select("origin", "dest", "tailnum", avg_speed) # Create the same table using a SQL expression speed2 = flights.selectExpr("origin", "dest", "tailnum", "distance/(air_time/60) as avg_speed") # EXERCISE # Aggregating # All of the common aggregation methods, like .min(), .max(), and .count() are GroupedData methods. These are created by calling the .groupBy() DataFrame method. You'll learn exactly what that means in a few exercises. For now, all you have to do to use these functions is call that method on your DataFrame. For example, to find the minimum value of a column, col, in a DataFrame, df, you could do # # df.groupBy().min("col").show() # This creates a GroupedData object (so you can use the .min() method), then finds the minimum value in col, and returns it as a DataFrame. # # Now you're ready to do some aggregating of your own! # # A SparkSession called spark is already in your workspace, along with the Spark DataFrame flights. # # INSTRUCTIONS # 100 XP # Find the length of the shortest (in terms of distance) flight that left PDX by first .filter()ing and using the .min() method. Perform the filtering by refrencing the column directly, not passing a SQL string. # Find the length of the longest (in terms of time) flight that left SEA by filter()ing and using the .max() method. Perform the filtering by refrencing the column directly, not passing a SQL string. # Find the shortest flight from PDX in terms of distance flights.filter(flights.origin == "PDX").groupBy().min("distance").show() # Find the longest flight from SEA in terms of duration flights.filter(flights.origin == 'SEA').groupBy().max("air_time").show() # EXERCISE # Aggregating II # To get you familiar with more of the built in aggregation methods, here's a few more exercises involving the flights table! # # Remember, a SparkSession called spark is already in your workspace, along with the Spark DataFrame flights. # # INSTRUCTIONS # 100 XP # Use the .avg() method to get the average air time of Delta Airlines flights (where the carrier column has the value "DL") that left SEA. Th place of departure is stored in the column origin. show() the result. # Use the .sum() method to get the total number of hours all planes in this dataset spent in the air by creating a column called duration_hrs from the column air_time. show() the result. # Average duration of Delta flights flights.filter(flights.carrier == 'DL').filter(flights.origin == 'SEA').groupBy().avg('air_time').show() # Total hours in the air flights.withColumn("duration_hrs", flights.air_time/60).groupBy().sum("duration_hrs").show() # EXERCISE # Grouping and Aggregating I # Part of what makes aggregating so powerful is the addition of groups. PySpark has a whole class devoted to grouped data frames: pyspark.sql.GroupedData, which you saw in the last two exercises. # # You've learned how to create a grouped DataFrame by calling the .groupBy() method on a DataFrame with no arguments. # # Now you'll see that when you pass the name of one or more columns in your DataFrame to the .groupBy() method, the aggregation methods behave like when you use a GROUP BY statement in a SQL query! # # Remember, a SparkSession called spark is already in your workspace, along with the Spark DataFrame flights. # # INSTRUCTIONS # 0 XP # Create a DataFrame called by_plane that is grouped by the column tailnum. # Use the .count() method with no arguments to count the number of flights each plane made. # Create a DataFrame called by_origin that is grouped by the column origin. # Find the .avg() of the air_time column to find average duration of flights from PDX and SEA. # Group by tailnum by_plane = flights.groupBy("tailnum") # Number of flights each plane made by_plane.count().show() # Group by origin by_origin = flights.groupBy("origin") # Average duration of flights from PDX and SEA by_origin.avg("air_time").show() # EXERCISE # Grouping and Aggregating II # In addition to the GroupedData methods you've already seen, there is also the .agg() method. This method lets you pass an aggregate column expression that uses any of the aggregate functions from the pyspark.sql.functions submodule. # # This submodule contains many useful functions for computing things like standard deviations. All the aggregation functions in this submodule take the name of a column in a GroupedData table. # # Remember, a SparkSession called spark is already in your workspace, along with the Spark DataFrame flights. The grouped DataFrames you created in the last exercise are also in your workspace. # # INSTRUCTIONS # 100 XP # Import the submodule pyspark.sql.functions as F. # Create a GroupedData table called by_month_dest that's grouped by both the month and dest columns. Refer to the two columns by passing both strings as separate arguments. # Use the .avg() method on the by_month_dest DataFrame to get the average dep_delay in each month for each destination. # Find the corresponding standard deviation of each average by using the .agg() method with the function F.stddev(). # Import pyspark.sql.functions as F import pyspark.sql.functions as F # Group by month and dest by_month_dest = flights.groupBy("month", "dest") # Average departure delay by month and destination by_month_dest.avg(dep_delay).show() # Standard deviation by_month_dest.agg(F.stddev("dep_delay")).show() # EXERCISE # Joining II # In PySpark, joins are performed using the DataFrame method .join(). This method takes three arguments. The first is the second DataFrame that you want to join with the first one. The second argument, on, is the name of the key column(s) as a string. The names of the key column(s) must be the same in each table. The third argument, how, specifies the kind of join to perform. In this course we'll always use the value how="leftouter". # # The flights dataset and a new dataset called airports are already in your workspace. # # INSTRUCTIONS # 100 XP # Examine the airports DataFrame by printing the .show(). Note which key column will let you join airports to the flights table. # Rename the faa column in airports to dest by re-assigning the result of airports.withColumnRenamed("faa", "dest") to airports. # Join the airports DataFrame to the flights DataFrame on the dest column by calling the .join() method on flights. Save the result as flights_with_airports. # The first argument should be the other DataFrame, airports. # The argument on should be the key column. # The argument how should be "leftouter". # Print the .show() of flights_with_airports. Note the new information that has been added. # Examine the data print(airports.show()) # Rename the faa column airports = airports.withColumnRenamed("faa", "dest") # Join the DataFrames flights_with_airports = flights.join(airports, on="dest", how="leftouter") # Examine the data again print(flights_with_airports.show()) # Machine Learning Pipelines # In the next two chapters you'll step through every stage of the machine learning pipeline, from data intake to model evaluation. Let's get to it! # # At the core of the pyspark.ml module are the Transformer and Estimator classes. Almost every other class in the module behaves similarly to these two basic classes. # # Transformer classes have a .transform() method that takes a DataFrame and returns a new DataFrame; usually the original one with a new column appended. For example, you might use the class Bucketizer to create discrete bins from a continuous feature or the class PCA to reduce the dimensionality of your dataset using principal component analysis. # # Estimator classes all implement a .fit() method. These methods also take a DataFrame, but instead of returning another DataFrame they return a model object. This can be something like a StringIndexerModel for including categorical data saved as strings in your models, or a RandomForestModel that uses the random forest algorithm for classification or regression. # EXERCISE # Join the DataFrames # In the next two chapters you'll be working to build a model that predicts whether or not a flight will be delayed based on the flights data we've been working with. This model will also include information about the plane that flew the route, so the first step is to join the two tables: flights and planes! # # INSTRUCTIONS # 100 XP # First, rename the year column of planes to plane_year to avoid duplicate column names. # Create a new DataFrame called model_data by joining the flights table with planes using the tailnum column as the key. # Rename year column planes = planes.withColumnRenamed("year", "plane_year") # Join the DataFrames model_data = flights.join(planes, on="tailnum", how="leftouter") # Data types # Good work! Before you get started modeling, it's important to know that Spark only handles numeric data. That means all of the columns in your DataFrame must be either integers or decimals (called 'doubles' in Spark). # # When we imported our data, we let Spark guess what kind of information each column held. Unfortunately, Spark doesn't always guess right and you can see that some of the columns in our DataFrame are strings containing numbers as opposed to actual numeric values. # # To remedy this, you can use the .cast() method in combination with the .withColumn() method. It's important to note that .cast() works on columns, while .withColumn() works on DataFrames. # # The only argument you need to pass to .cast() is the kind of value you want to create, in string form. For example, to create integers, you'll pass the argument "integer" and for decimal numbers you'll use "double". # # You can put this call to .cast() inside a call to .withColumn() to overwrite the already existing column, just like you did in the previous chapter! # EXERCISE # String to integer # Now you'll use the .cast() method you learned in the previous exercise to convert all the appropriate columns from your DataFrame model_data to integers! # # To convert the type of a column using the .cast() method, you can write code like this: # # dataframe = dataframe.withColumn("col", dataframe.col.cast("new_type") # INSTRUCTIONS # 100 XP # Use the method .withColumn() to .cast() the following columns to type "integer". Access the columns using the df.col notation. # model_data.arr_delay # model_data.air_time # model_data.month # model_data.plane_year # Cast the columns to integers model_data = model_data.withColumn("arr_delay", model_data.arr_delay.cast("integer")) model_data = model_data.withColumn("air_time", model_data.air_time.cast("integer")) model_data = model_data.withColumn("month", model_data.month.cast("integer")) model_data = model_data.withColumn("plane_year", model_data.plane_year.cast("integer")) # EXERCISE # Create a new column # In the last exercise, you converted the column plane_year to an integer. This column holds the year each plane was manufactured. However, your model will use the planes' age, which is slightly different from the year it was made! # # INSTRUCTIONS # 100 XP # Create the column plane_age using the .withColumn() method and subtracting the year of manufacture (column plane_year) from the year (column year) of the flight. # Create the column plane_age model_data = model_data.withColumn("plane_age", model_data.year - model_data.plane_year) # EXERCISE # Making a Boolean # Consider that you're modeling a yes or no question: is the flight late? However, your data contains the arrival delay in minutes for each flight. Thus, you'll need to create a boolean column which indicates whether the flight was late or not! # # INSTRUCTIONS # 100 XP # Use the .withColumn() method to create the column is_late. This column is equal to model_data.arr_delay > 0. # Convert this column to an integer column so that you can use it in your model and name it label (this is the default name for the response variable in Spark's machine learning routines). # Filter out missing values (this has been done for you). # Create is_late model_data = model_data.withColumn("is_late", model_data.arr_delay > 0) # Ceate another column:label and Convert to an integer model_data = model_data.withColumn("label", model_data.is_late.cast("integer")) # Remove missing values model_data = model_data.filter("arr_delay is not NULL and dep_delay is not NULL and air_time is not NULL and plane_year is not NULL") # Strings and factors # As you know, Spark requires numeric data for modeling. So far this hasn't been an issue; even boolean columns can easily be converted to integers without any trouble. But you'll also be using the airline and the plane's destination as features in your model. These are coded as strings and there isn't any obvious way to convert them to a numeric data type. # # Fortunately, PySpark has functions for handling this built into the pyspark.ml.features submodule. You can create what are called 'one-hot vectors' to represent the carrier and the destination of each flight. A one-hot vector is a way of representing a categorical feature where every observation has a vector in which all elements are zero except for at most one element, which has a value of one (1). # # Each element in the vector corresponds to a level of the feature, so it's possible to tell what the right level is by seeing which element of the vector is equal to one (1). # # The first step to encoding your categorical feature is to create a StringIndexer. Members of this class are Estimators that take a DataFrame with a column of strings and map each unique string to a number. Then, the Estimator returns a Transformer that takes a DataFrame, attaches the mapping to it as metadata, and returns a new DataFrame with a numeric column corresponding to the string column. # # The second step is to encode this numeric column as a one-hot vector using a OneHotEncoder. This works exactly the same way as the StringIndexer by creating an Estimator and then a Transformer. The end result is a column that encodes your categorical feature as a vector that's suitable for machine learning routines! # # This may seem complicated, but don't worry! All you have to remember is that you need to create a StringIndexer and a OneHotEncoder, and the Pipeline will take care of the rest. # EXERCISE # Carrier # In this exercise you'll create a StringIndexer and a OneHotEncoder to code the carrier column. To do this, you'll call the class constructors with the arguments inputCol and outputCol. # # The inputCol is the name of the column you want to index or encode, and the outputCol is the name of the new column that the Transformer should create. # # INSTRUCTIONS # 100 XP # Create a StringIndexer called carr_indexer by calling StringIndexer() with inputCol="carrier" and outputCol="carrier_index". # Create a OneHotEncoder called carr_encoder by calling OneHotEncoder() with inputCol="carrier_index" and outputCol="carrier_fact". # Create a StringIndexer carr_indexer = StringIndexer(inputCol="carrier", outputCol="carrier_index") # Create a OneHotEncoder carr_encoder = OneHotEncoder(inputCol="carrier_index", outputCol="carrier_fact") # EXERCISE # Destination # Now you'll encode the dest column just like you did in the previous exercise. # # INSTRUCTIONS # 100 XP # Create a StringIndexer called dest_indexer by calling StringIndexer() with inputCol="dest" and outputCol="dest_index". # Create a OneHotEncoder called dest_encoder by calling OneHotEncoder() with inputCol="dest_index" and outputCol="dest_fact". # Create a StringIndexer dest_indexer = StringIndexer(inputCol="dest", outputCol="dest_index") # Create a OneHotEncoder dest_encoder = OneHotEncoder(inputCol="dest_index", outputCol="dest_fact") # EXERCISE # Assemble a vector # Good work so far! # # The last step in the Pipeline is to combine all of the columns containing our features into a single column. This has to be done before modeling can take place because every Spark modeling routine expects the data to be in this form. You can do this by storing each of the values from a column as an entry in a vector. Then, from the model's point of view, every observation is a vector that contains all of the information about it and a label that tells the modeler what value that observation corresponds to. # # Because of this, the pyspark.ml.feature submodule contains a class called VectorAssembler. This Transformer takes all of the columns you specify and combines them into a new vector column. # # INSTRUCTIONS # 100 XP # INSTRUCTIONS # 100 XP # Create a VectorAssembler by calling VectorAssembler() with the inputCols names as a list and the outputCol name "features". # The list of columns should be ["month", "air_time", "carrier_fact", "dest_fact", "plane_age"] # Make a VectorAssembler vec_assembler = VectorAssembler(inputCols=["month", "air_time", "carrier_fact", "dest_fact", "plane_age"], outputCol="features") # EXERCISE # Create the pipeline # You're finally ready to create a Pipeline! # # Pipeline is a class in the pyspark.ml module that combines all the Estimators and Transformers that you've already created. This lets you reuse the same modeling process over and over again by wrapping it up in one simple object. Neat, right? # # INSTRUCTIONS # 100 XP # Import Pipeline from pyspark.ml. # Call the Pipeline() constructor with the keyword argument stages to create a Pipeline called flights_pipe. # stages should be a list holding all the stages you want your data to go through in the pipeline. Here this is just [dest_indexer, dest_encoder, carr_indexer, carr_encoder, vec_assembler] # Import Pipeline from pyspark.ml import Pipeline # Make the pipeline flights_pipe = Pipeline(stages=[dest_indexer, dest_encoder, carr_indexer, carr_encoder, vec_assembler]) # Test vs Train # After you've cleaned your data and gotten it ready for modeling, one of the most important steps is to split the data into a test set and a train set. After that, don't touch your test data until you think you have a good model! As you're building models and forming hypotheses, you can test them on your training data to get an idea of their performance. # # Once you've got your favorite model, you can see how well it predicts the new data in your test set. This never-before-seen data will give you a much more realistic idea of your model's performance in the real world when you're trying to predict or classify new data. # # In Spark it's important to make sure you split the data after all the transformations. This is because operations like StringIndexer don't always produce the same index even when given the same list of strings. # EXERCISE # Transform the data # Hooray, now you're finally ready to pass your data through the Pipeline you created! # # INSTRUCTIONS # 100 XP # Create the DataFrame piped_data by calling the Pipeline methods .fit() and .transform() in a chain. Both of these methods take model_data as their only argument. # Fit and transform the data piped_data = flights_pipe.fit(model_data).transform() # EXERCISE # Split the data # Now that you've done all your manipulations, the last step before modeling is to split the data! # # INSTRUCTIONS # 100 XP # Use the DataFrame method .randomSplit() to split model_data into two pieces, training with 60% of the data, and test with 40% of the data by passing the list [.6, .4] to the .randomSplit() method. # Split the data into training and test sets training, test = piped_data.randomSplit([.6, .4]) # What is logistic regression? # The model you'll be fitting in this chapter is called a logistic regression. This model is very similar to a linear regression, but instead of predicting a numeric variable, it predicts the probability (between 0 and 1) of an event. # # To use this as a classification algorithm, all you have to do is assign a cutoff point to these probabilities. If the predicted probability is above the cutoff point, you classify that observation as a 'yes' (in this case, the flight being late), if it's below, you classify it as a 'no'! # # You'll tune this model by testing different values for several hyperparameters. A hyperparameter is just a value in the model that's not estimated from the data, but rather is supplied by the user to maximize performance. For this course it's not necessary to understand the mathematics behind all of these values - what's important is that you'll try out a few different choices and pick the best one. # Import LogisticRegression from pyspark.ml.classification import LogisticRegression # Create a LogisticRegression Estimator lr = LogisticRegression() # Cross validation # In the next few exercises you'll be tuning your logistic regression model using a procedure called k-fold cross validation. This is a method of estimating the model's performance on unseen data (like your test DataFrame). # # It works by splitting the training data into a few different partitions. The exact number is up to you, but in this course you'll be using PySpark's default value of three. Once the data is split up, one of the partitions is set aside, and the model is fit to the others. Then the error is measured against the held out partition. This is repeated for each of the partitions, so that every block of data is held out and used as a test set exactly once. Then the error on each of the partitions is averaged. This is called the cross validation error of the model, and is a good estimate of the actual error on the held out data. # # You'll be using cross validation to choose the hyperparameters by creating a grid of the possible pairs of values for the two hyperparameters, elasticNetParam and regParam, and using the cross validation error to compare all the different models so you can choose the best one! # # What does cross validation allow you to estimate? # The model's error on held out data. # EXERCISE # Create the evaluator # The first thing you need when doing cross validation for model selection is a way to compare different models. Luckily, the pyspark.ml.evaluation submodule has classes for evaluating different kinds of models. Your model is a binary classification model, so you'll be using the BinaryClassificationEvaluator from the pyspark.ml.evaluation module. # # This evaluator calculates the area under the ROC. This is a metric that combines the two kinds of errors a binary classifier can make (false positives and false negatives) into a simple number. You'll learn more about this towards the end of the chapter! # # INSTRUCTIONS # 100 XP # Import the submodule pyspark.ml.evaluation as evals. # Create evaluator by calling evals.BinaryClassificationEvaluator() with the argument metricName="areaUnderROC". # Import the evaluation submodule import pyspark.ml.evaluation as evals # Create a BinaryClassificationEvaluator evaluator = evals.BinaryClassificationEvaluator(metricName="areaUnderROC") # EXERCISE # Make a grid # Next, you need to create a grid of values to search over when looking for the optimal hyperparameters. The submodule pyspark.ml.tuning includes a class called ParamGridBuilder that does just that (maybe you're starting to notice a pattern here; PySpark has a submodule for just about everything!). # # You'll need to use the .addGrid() and .build() methods to create a grid that you can use for cross validation. The .addGrid() method takes a model parameter (an attribute of the model Estimator, lr, that you created a few exercises ago) and a list of values that you want to try. The .build() method takes no arguments, it just returns the grid that you'll use later. # # INSTRUCTIONS # 100 XP # Import the submodule pyspark.ml.tuning under the alias tune. # Call the class constructor ParamGridBuilder() with no arguments. Save this as grid. # Call the .addGrid() method on grid with lr.regParam as the first argument and np.arange(0, .1, .01) as the second argument. This second call is a function from the numpy module (imported as np) that creates a list of numbers from 0 to .1, incrementing by .01. Overwrite grid with the result. # Update grid again by calling the .addGrid() method a second time create a grid for lr.elasticNetParam that includes only the values [0, 1]. # Call the .build() method on grid and overwrite it with the output. # Import the tuning submodule import pyspark.ml.tuning as tune # Create the parameter grid grid = tune.ParamGridBuilder() # Add the hyperparameter grid = grid.addGrid(lr.regParam, np.arange(0, .1, .01)) grid = grid.addGrid(lr.elasticNetParam, [0,1]) # Build the grid grid = grid.build() # EXERCISE # Make the validator # The submodule pyspark.ml.tuning also has a class called CrossValidator for performing cross validation. This Estimator takes the modeler you want to fit, the grid of hyperparameters you created, and the evaluator you want to use to compare your models. # # The submodule pyspark.ml.tune has already been imported as tune. You'll create the CrossValidator by passing it the logistic regression Estimator lr, the parameter grid, and the evaluator you created in the previous exercises. # # INSTRUCTIONS # 100 XP # Create a CrossValidator by calling tune.CrossValidator() with the arguments: # estimator=lr # estimatorParamMaps=grid # evaluator=evaluator # Name this object cv. # Create the CrossValidator cv = tune.CrossValidator(estimator=lr, estimatorParamMaps=grid, evaluator=evaluator ) # EXERCISE # Fit the model(s) # You're finally ready to fit the models and select the best one! # # Unfortunately, cross validation is a very computationally intensive procedure. Fitting all the models would take too long on DataCamp. # # To do this locally you would use the code # # # Fit cross validation models # models = cv.fit(training) # # # Extract the best model # best_lr = models.bestModel # Remember, the training data is called training and you're using lr to fit a logistic regression model. Cross validation selected the parameter values regParam=0 and elasticNetParam=0 as being the best. These are the default values, so you don't need to do anything else with lr before fitting the model. # # INSTRUCTIONS # 100 XP # Create best_lr by calling lr.fit() on the training data. # Print best_lr to verify that it's an object of the LogisticRegressionModel class. # Call lr.fit() best_lr = lr.fit(training) # Print best_lr print(best_lr) # Evaluating binary classifiers # For this course we'll be using a common metric for binary classification algorithms call the AUC, or area under the curve. In this case, the curve is the ROC, or receiver operating curve. The details of what these things actually measure isn't important for this course. All you need to know is that for our purposes, the closer the AUC is to one (1), the better the model is! # # If you've created a perfect binary classification model, what would the AUC be? # 1 # Evaluate the model Remember the test data that you set aside waaaaaay back in chapter 3? It's finally time to test your model on it! You can use the same evaluator you made to fit the model. INSTRUCTIONS 100 XP Use your model to generate predictions by applying best_lr.transform() to the test data. Save this as test_results. Call evaluator.evaluate() on test_results to compute the AUC. Print the output. # Use the model to predict the test set test_results = best_lr.transform(test) # Evaluate the predictions print(evaluator.evaluate(test_results)) # Conclusion # Congrats on making it to the end of the course! You went from knowing nothing about Spark to doing advanced machine learning. Cool huh? # # The next steps are learning how to create large scale Spark clusters and manage and submit jobs so that you can use models in the real world. # # And remember, Spark is still being actively developed, so there's new features coming all the time! # # Did you have a great time taking this course?
91be2e2437046bd4dba1aeec273c6ebabd7462f5
MamontRussel/2019_PPO_sociology
/Seminar_6_7.py
26,824
4.09375
4
''' Недели 5-7 Сoursera. Чтение файлов, множества, словари, обработка ошибок, дополнительные методы работы со строками. ''' ''' МЕТОДЫ РАБОТЫ СО СПИСКАМИ Списки в Python поддерживают множество методов для взаимодействия с ними. Стоит отметить, что эти методы изменяют исходный список. ''' test_list = list(range(10)) print(test_list) # Добавляет в список указанный элемент (в конец) test_list.append(11) print(test_list) # Сформируем другой список sublist = [12, 12] # И добавим его в существующий (в конец) test_list.extend(sublist) print(test_list) # Добавим в список строку "ABC" на позицию "1". Отличие от test_list[1] = 'ABC' в том, что сейчас элемент, # стоявший под индексом 1 не перезапишется, а все элементы сдвинутся вправо. test_list.insert(1, 'ABC') print(test_list) # Удалим из списка первое вхождение указанного элемента (по значению). test_list.remove('ABC') print(test_list) # Найдём позицию указанного элемента в списке. Если элемент встречается несколько раз, # то метод вернёт наименьшую позицию повторяющегося элемента. print(test_list.index(12)) # Метод возвращает количество указанных элементов в списке print(test_list.count(12)) # Метод возвращает элемент списка с указанным индексом и одновременно убирает его. popped_element = test_list.pop(5) print(popped_element) print(test_list) # Если индекс не указан - метод убирает последний элемент списка. popped_element = test_list.pop() print(popped_element) print(test_list) # Метод меняет порядок расположения элементов в списке на противоположный test_list.reverse() print(test_list) ''' УПРАЖНЕНИЯ 1. Напишите програму, которая считает количество строк с длиной 4 или больше и в которых первый и последний символы совпадают. Sample List : ['abca', 'xydz', 'aba', '12321', 'dd'] Ожидаемый результат : 2 2. Напишите код, который удаляет дубликаты из списка. 3. Напишите функцию, которая сравнивает два списка и возвращает True, если у них есть хотя бы один общий член. 4. Напишите программу, которая удаляет все четные числа из списка. 5. Напишите программу, которая в каждом подлисте находит максмум и суммирует их. ''' # 1 test_list = ['abca', 'xydz', 'aba', '12321', 'dd'] count = 0 for item in test_list: if (len(item) > 3) and (item[0] == item[-1]): count += 1 print(count) # 2 def common_data(list1, list2): common = False for x in list1: # итеририуемся по первому списку for y in list2: # итерируемся по второму списку if x == y: common = True return common print(common_data([1, 2, 3, 4, 5], [5, 6, 7, 8, 9])) print(common_data([1, 2, 3, 4, 5], [6, 7, 8, 9])) # 3 test_list = [2, 3, 6, 8, 19, 21, 22, 3, 3, 5, 20, 21] new_list = [] # создаем пустой списко for item in test_list: if item not in new_list: new_list.append(item) # если элемент еще не в списке, то добавляем его print(new_list) # 4 test_list = [2, 3, 6, 8, 19, 21, 22] new_list = [] for item in test_list: if item % 2 != 0: new_list.append(item) print(new_list) # 5 sum = 0 test_list = [[1,2,3], [4,5,6], [10,11,12], [7,8,9]] for list in test_list: # итерируемся по элементам большого списка max = 0 for element in list: # итерируемся по элементам каждого вложенного списка if element > max: max = element sum += max print(sum) ''' Отдельно следует рассказать про метод sort(). Метод производит сортировку списка. Задачи сортировки - очень распространены в программировании. В общем случае, они сводятся к выстроению элементов списка в заданном порядке. В Python есть встроенные методы для сортировки объектов для того, чтобы программист мог не усложнять себе задачу написанием алгоритма сортировки. Метод list.sort() - как раз, один из таких случаев. ''' test_list = [5, 8, 1, 4, 3, 7, 2] print(test_list) # Элементы списка расположены в хаотичном порядке test_list.sort() print(test_list) # Теперь элементы списка теперь расположены по возрастанию ''' Таким образом, метод list.sort() упорядочил элементы списка test_list Если нужно отсортировать элементы в обратном порядке, то можно использовать: ''' test_list.sort(reverse=True) # параметр reverse указывает на то, что нужно отсортировать список в обратном порядке print(test_list) ''' Следует обратить внимание, что метод list.sort() изменяет сам список, на котором его вызвали. Таким образом, при каждом вызове метода "sort()", наш список "test_list" изменяется. Это может быть удобно, если нам не нужно держать в памяти исходный список. Однако, в противном случае, или же - в случае неизменяемого типа данных (например, кортежа или строки) - этот метод не сработает. В таком случае, на помощь приходит встроенная в питон функция sorted() ''' print(sorted(test_list)) # Сам список при сортировке не изменяется ''' У функции sorted(), как и у метода list.sort() есть параметр key, с помощью которого можно указать функцию, которая будет применена к каждому элементу последовательности при сортировке. ''' test_string = 'A string With upper AND lower cases' print(sorted(test_string.split())) print(sorted(test_string.split(), key=str.upper)) ''' Имеем строку из слов, начинающихся с заглавных и строчных букв. test_strng.split() формирует список из элементов строки, разделённых пробелом. Далее, функция "sorted()" уже сортирует этот список, меняя регистр всех входящих в него элементов на верхний. ''' ''' ДОПОЛНИТЕЛЬНО Однако, в некоторых случаях, встроенных функций Python для сортировки недостаточно, и нужно реалиовать алгоритм самим. Поэтому, рассмотрим сортировку подсчётом (без использования sorted()) Например, это эффективнее в случаях, когда в списке много однотипных значений и нам нужно узнать, сколько раз встречается каждое ''' marks = [1, 2, 2, 5, 7, 4, 2, 10, 7, 10] # Создаём список, заполненный нулям длины, равной значению наибольшего элемента исходного списка + 1 # Потому что возможные значения от 0 до этого максимума (11 штук в данном случае). cntMarks = [0] * 11 for mark in marks: # проходим по каждому значению в исходном списке с оценками cntMarks[mark] += 1 # обновляем счетчик оценки в списке с нулями, если такой элемент встречается print(cntMarks) for nowMark in range(11): # выводим результаты подсчета print((str(nowMark) + ' ') * cntMarks[nowMark], end=' ') ''' МНОЖЕСТВА Еще одна важная структура данных в python - множества. Если вы знакомы с логикой или теорией множеств, то это собрания уникальных элементов. Главное отличие множеств - то, что элемент в них может встречаться только один раз (в отличие от списков и кортежей). Создаются фигурными скобками или функцией set(). Множества часто используются, когда нам нужен перечень уникальных элементов (например, чтобы проверить, если в данных ответ с определенным значением). Это экономит память хранения такого списка. Множества могут содержать объекты разных типов, но только неизменяемые (числа, строки). ''' set1 = {1, 2, 2, 3, 4, 4, 4, 5} print(set1) ''' Множества можно сравнивать между собой. К традиционным операциям добавляются дополнительные. ''' firstSet = {1, 2, 1, 3} secondSet = {3, 2, 1} print(firstSet == secondSet) # Все элементы совпадают print(firstSet != secondSet) # Есть различные элементы print(firstSet <= secondSet) # Все элементы А входят в B print(firstSet < secondSet) # Все элементы А входят в Б и есть различные элементы ''' Количество элементов можно так же узнать с помощью функции len() ''' len(set1) ''' Мы можем применять к множествам логические операции, чтобы смотреть имеют ли они общие или разные элементы. ''' firstSet = {1, 2, 1, 3, 5, 9} secondSet = {3, 2, 1, 4} print(firstSet) print(secondSet) print(firstSet | secondSet) # Объединение множеств print(firstSet & secondSet) # Пересечение множеств print(firstSet - secondSet) # Множество, элементы которого входят в A, но не входят в B print(firstSet ^ secondSet) # Элементы входят в A | B, но не входят в A & B ''' Давайте теперь напишем программу, которая удаляет дубликаты из списка. ''' test_list = [2, 3, 6, 8, 19, 21, 22, 3, 3, 5, 20, 21] new_list = list(set(test_list)) # cоздаем множество из списка - дубликаты удаляются, делаем из множества список print(new_list) ''' СЛОВАРИ Словарь - это такая структура данных, когда мы хотим хранить данные не по индексу, а чтобы какому-то ключю соответствовало какое-то значение (например, как в телефонной книге). Ключом (именем в телефонной книге) может быть любой неизменяемый объект(число, строка), а значением - любой (в т.ч. список, словарь, кортеж). Создать словарь можно с помощью фигурных скобок или функции dict(). Ниже обратите внимание на синтаксис. ''' phone_book = {'Tanya': '243-352', 'Oleg': ['242-212', '242-251']} print(phone_book) ''' Словарь - неупорядоченная структура. Мы не можем обратиться к объекту по индексу, но зато можем по ключу. ''' print(phone_book['Tanya']) ''' Чтобы узнать, какие ключи (keys) или значения (values) есть в словаре - можно воспользоваться соответствующими методами. ''' print(phone_book.keys()) print(phone_book.values()) print(phone_book.items()) # возвращает объект с ключами и значениями, по которому можно итерироваться ''' Мы можем вывести ключи и соответсвующие им значения с помощью цикла for ''' for key in phone_book.keys(): # выведем все ключи print(key, phone_book[key]) for key, value in phone_book.items(): # выведем все пары ключ-значение print(key, value) ''' Добавлять пары ключ значение в словарь очень просто: это делается по аналогии со списками. Удаление происходит с помощью функции del. Также можем проверить наличие ключа в словаре. ''' phone_book['Alex'] = '242-325' phone_book['Tanya'] = '25321-311' # перезаписываем значение print(phone_book) del phone_book['Oleg'] print(phone_book) print('Oleg' in phone_book.keys()) ''' Помните, мы сортировали список с оценками? Можем собрать два списка в словарь, где ключ - оценка, а значение - сколько раз она встречается в списке. ''' print(marks) print(cntMarks) marksDict = dict(zip(range(11), cntMarks)) # смотрит, что делает функция zip - она упаковывает два списка одинаковой длины попарно в кортежи # первый объект с первым и так далее. Функция dict() в свою очередь, может распаковать такую структуру # в словарь print(list(zip(range(11), cntMarks))) print(marksDict) ''' Напишите программу, которая объединяет значения из двух списков. Sample data: [{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}] Expected Output: Counter({'item1': 1150, 'item2': 300}) ''' sample_data = [{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}] new_dictionary = {} # создаем пустой словарь for dictionary in sample_data: # итерируемся по списку - заходим в каждый вложенный словарь if dictionary['item'] in new_dictionary.keys(): # проверяем, есть ли в нашем новом словаре такой ключ # если такой ключ там есть, то обновляем его значение new_dictionary[dictionary['item']] = new_dictionary[dictionary['item']] + dictionary['amount'] else: # если такого ключа нет - создаем его и присваиваем ему соответствующее значение new_dictionary[dictionary['item']] = dictionary['amount'] print(new_dictionary) ''' Вариант условия этой задачи для практики. У вас есть выгрузка оставшегося количества фруктов из базы данных магазинов. Каждый словарь в списке - магазин. Какие-то фрукты есть в разных магазинах, какие-то только в одном. Нужно сделать словарь, в котором ключами будут фрукты, а их количество - значениями. Если фрукт есть в наличии в нескольких магазинах - сложите эти значения. Ввод: [{'фрукт': 'банан', 'количество': 400}, {'фрукт': 'яблоко', 'количество': 300}, {'фрукт': 'банан', 'количество': 750}, {'фрукт' : 'груша', 'количество' : 20}, {'фрукт': 'яблоко', 'количество': 150}] Вывод: фрукты и их общее количество, список упорядочен по алфавиту. банан 1150 груша 20 яблоко 450 ''' ''' Словари очень удобно использовать для подсчета числа элементов. Давайте попробуем открыть файл и решить небольшую задачку. Мы открываем файл с помощью функции open(), которой передаем адрес файла, форму работы с файлом (только чтение r, запись w, запись и чтение r+) и кодировку (utf8 в нашем случае). Этот файл загружается в память. Затем мы можем загружать его по строкам. Обратите внимание, что файл нужно положить в папку вышего проекта, если вы не хотите прописывать к нему полный путь. ''' file = open('romeo.txt', 'r', encoding='utf8') # загружаем файл в память lines = file.readlines() # считываем строки из файла в память file.close() # мы уже сохранили информацию из файла, можем закрыть его for line in lines: print(line) ''' Давайте посчитаем, какие слова и как часто встрачаются в нашем файле. Создадим словарь, в котором ключом будет слово, а значением - количество раз, которое оно встречается. ''' words = dict() # создаем пустой словарь for line in lines: # итерируемся по строкам файла templst = list(map(lambda x: x.lower(), line.split())) # cохраняем все слова из строки в список в нижнем регистре print(templst) for word in templst: # итерируемся по списку, созданному на основе строки if word in words.keys(): # проверяем наличие ключа в словаре words[word] += 1 # если ключ в словаре - прибавляем 1 else: words[word] = 1 # если такого ключа нет - сохраняем ключ со значением один print(word, words[word]) print(words) print(words['pale']) ''' Теперь давайте найдем самое часто встречающееся слово. К сожалению словарь неупорядоченная структура данных и нам придется отсортировать его в ручную. Сделаем этот код функцией, потому что он нам пригодится в следующей задаче. ''' def dict_max_value(x): # будем считать, что по умолчанию максимульное значение равно одному, потому что в наших словарях # каждое слово встречается минимум 1 раз max_value = 1 # значение максимальное ключа мы пока не знаем, поэтому создаем пустую переменную max_key = None for key, value in x.items(): # итерируемся по парам ключ-значение if value > max_value: # проверяем, больше ли значение, чем максимум max_key = key # обновляем ключ, если да max_value = value # обновляем значение if max_value == 1: # если нет ни одного значения больше одного, давайте выведем эту информацию print('No max value, all 1') else: print('Max value is', max_value, 'for', max_key) dict_max_value(words) ''' ЗАДАЧА НА АВТОРА, КОТОРЫЙ ПИШЕТ БОЛЬШЕ ВСЕГО ПИСЕМ. Файл mbox.txt содержит метаданные почтового сервера. Мы знаем, что строка с адресом автора письма начинается с "From " (посмотрите в самом файле, какие там еще есть варианты). Мы хотим найти адреса всех авторов сообщений и найти того из них, кто пишет больше всех писем. ''' handle = open('mbox.txt', 'r', encoding='utf8') emails = {} for line in handle: if line.startswith('From '): # работаем только со строками, которые нас интересуют email = line.split()[1] # разбиваем строку и берем из нее email if email not in emails.keys(): # проверяем, есть ли уже такой адрес в нашем словаре emails[email] = 1 # если нет, то создаем такой ключ со значением 1 else: emails[email] += 1 # если да, то обновляем значение на 1 print(emails) handle.close() # закрываем файл, когда закончили работать с ним dict_max_value(emails) # воспользуемся нашей функцией, чтобы найти максимальное значение ''' ЗАДАЧА НА ПАРСИНГ ДАННЫХ В том же файле есть строка, которая обозначает, насколько спам фильтр уверен, что данное письмо не спам. Давайте найдем среднее значение X-DSPAM-Confidence для всей переписки. Нас интересуют только строки, начинающиеся с 'X-DSPAM-Confidence: ' (посмотрите в файле структуру метаданных хотя бы одного письма). ''' fhand = open('mbox.txt', 'r', encoding='utf8') count = 0 # создаем счетчик писем total = 0 # cоздаем переменную, в которой будем обновлять суммарное значение X-DSPAM-Confidence for line in fhand: if line.startswith('X-DSPAM-Confidence:'): # работаем только с интересующим нас строками print(line) x = line.find(':') # ищем местоположение символа, по которому будем срезать строку confidence = line[x+2:x+7] # ищем индексы, по которым будем доставать значение X-DSPAM-Confidence y = float(confidence) # переводим значение из строки в дробь print(y) count = count + 1 # обновляем count total = total + y # обновляем total average = total/count # находим среднее print('Average spam confidence: ', round(average, 2)) fhand.close() ''' МЕТОДЫ ДЛЯ РАБОТЫ СО СТРОКАМИ Словари очень часто используются для работы с текстом, поэтому давайте посмотрим, какие еще методы для строк есть в Python. ''' # isalpha - проверяет, что все символы строки являются буквами. print('Ask me a question!'.isalpha()) print('Ask'.isalpha()) # isdigit - проверяет, что все символы строки являются цифрами. print('13242'.isdigit()) # isalnum - проверяет, что все символы строки являются буквами или цифрами. print('Ask me a question!'.isalnum()) print('Ask232'.isalnum()) # islower - проверяет, что все символы строки являются маленькими (строчными) буквами. print('ssk me a question!'.islower()) # isupper - проверяет, что все символы строки являются большими (заглавными, прописными) буквами. print('ssk me a question!'.isupper()) # lstrip - обрезает все пробельные символы в начале строки. print(' ssk me a question! ') print(' ssk me a question! '.lstrip()) # rstrip - обрезает все пробельные символы в конце строки. print(' ssk me a question! '.rstrip()) # strip - обрезает все пробельные символы в начале и конце строки. print(' ssk me a question! '.strip())
7c2c2b3a2892a75a2d4640626e922e8b2aae8566
pakoy3k/MoreCodes-Python
/Basics9.py
339
3.6875
4
#Basics of Functions def function1(): print "Hello there!" def function2(num): print "That number is ", num def function3(): num_sum = 1 + 1 return num_sum def function4(firstName, lastName): fullName = firstName + " " + lastName; return fullName; function1(); function2(5); print function3(); print function4("More", "Codes");
e029d0a0956ad8294d039763f3b14e548494c702
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/topics/Collections/45/fifo.py
442
4.15625
4
from collections import deque def my_queue(n=5): return deque(maxlen=n) if __name__ == '__main__': mq = my_queue() for i in range(10): mq.append(i) print((i, list(mq))) """Queue size does not go beyond n int, this outputs: (0, [0]) (1, [0, 1]) (2, [0, 1, 2]) (3, [0, 1, 2, 3]) (4, [0, 1, 2, 3, 4]) (5, [1, 2, 3, 4, 5]) (6, [2, 3, 4, 5, 6]) (7, [3, 4, 5, 6, 7]) (8, [4, 5, 6, 7, 8]) (9, [5, 6, 7, 8, 9]) """
589e1196bcadd87bce66d0755e4694dd91651da3
TobiasYin/LeetCodeKotlin
/src/answer/leetcode/LeetCode1.py
410
3.53125
4
class Solution1: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ nums_set = set(nums) for i in nums_set: if target-i in nums_set: index_1=nums.index(i) nums[index_1]=None index_2=nums.index(target-i) return [index_1,index_2]
92243ca39cd61c370a56c294c065dc7cd79a964d
alightwing/advent-code-2019
/day_2.py
2,195
3.953125
4
# Advent of Code Day 2 solution - https://adventofcode.com/2019/day/2 # TEST DATA # raw_program = "1,0,0,0,99" # output 2,0,0,0,99 # raw_program = "2,3,0,3,99" # output 2,3,0,6,99 # raw_program = "2,4,4,5,99,0" # 2,4,4,5,99,9801 # raw_program = "1,1,1,4,99,5,6,0,99" # output 30,1,1,4,2,5,6,0,99 # ACTUAL DATA raw_program = "1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,2,19,6,23,2,13,23,27,1,9,27,31,2,31,9,35,1,6,35,39,2,10,39,43,1,5,43,47,1,5,47,51,2,51,6,55,2,10,55,59,1,59,9,63,2,13,63,67,1,10,67,71,1,71,5,75,1,75,6,79,1,10,79,83,1,5,83,87,1,5,87,91,2,91,6,95,2,6,95,99,2,10,99,103,1,103,5,107,1,2,107,111,1,6,111,0,99,2,14,0,0" input_program = [int(n) for n in raw_program.split(',')] # need to comment these lines out if testing input_program[1] = 12 input_program[2] = 2 # Part 1 def run_program(program): current_pos = 0 while True: # each operation is four parameters program_chunk = program[current_pos:current_pos+4] opcode = program_chunk[0] # opcode 99 is end of program if opcode == 99: break input_one = program[program_chunk[1]] input_two = program[program_chunk[2]] if opcode == 1: output = input_one + input_two elif opcode == 2: output = input_one * input_two else: raise AttributeError('unrecognised opcode: {}'.format(opcode)) program[program_chunk[3]] = output current_pos += 4 return program output_program = run_program(input_program.copy()) print(output_program[0]) # Part 2 def find_noun_verb(program_base): # have to check all combinations for noun in range(100): for verb in range(100): # make a copy for each program_iter = program_base.copy() program_iter[1] = noun program_iter[2] = verb program_iter = run_program(program_iter) if program_iter[0] == 19690720: print('Noun: ', noun) print('Verb: ', verb) print('Product: ', noun * 100 + verb) return find_noun_verb(input_program)
95188332c3276d0089f90f34121cd5280bab8892
kexinl/test_github
/test4.py
1,015
4.09375
4
from datetime import datetime def is_leap_year(year): is_leap = False if (year % 400 == 0) or ((year % 100 !=0) and (year % 400 == 0)): is_leap = True return is_leap def main(): input_date_str = input('请输入日期(yyyy/mm/dd/): ') input_date = datetime.strptime(input_date_str, '%Y/%m/%d') print(input_date) year = input_date.year month = input_date.month day = input_date.day month_day_dict = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} days = 0 days += day for i in range(1, month): days += month_day_dict[i] if is_leap_year(year) and month > 2: days += 1 print('这是第几{}天.'.format(days)) if __name__ == '__main__': main()
5dd29e321f43b2f9be08fabcd81a27a63d353cdc
laobadao/Deep-Learning
/homework/01_neural_network_deeplearning/week_2/part_1_1.py
3,207
4.96875
5
""" 吴恩达Coursera深度学习课程 DeepLearning.ai 编程作业(1-2) Part 1:Python Basics with Numpy (optional assignment) 1 - Building basic functions with numpy Numpy is the main package for scientific computing in Python. It is maintained by a large community (www.numpy.org). In this exercise you will learn several key numpy functions such as np.exp, np.log, and np.reshape. You will need to know how to use these functions for future assignments. 1.1 - sigmoid function, np.exp() Exercise: Build a function that returns the sigmoid of a real number x. Use math.exp(x) for the exponential function. Reminder: sigmoid(x)= 1/(1+e ^ -x) is sometimes also known as the logistic function. It is a non-linear function used not only in Machine Learning (Logistic Regression), but also in Deep Learning. To refer to a function belonging to a specific package you could call it using package_name.function(). Run the code below to see an example with math.exp(). """ # GRADED FUNCTION: basic_sigmoid import math def basic_sigmoid(x): """ Compute sigmoid of x. Arguments: x -- A scalar Return: s -- sigmoid(x) """ ### START CODE HERE ### (≈ 1 line of code) # math.exp(x) -> e ^ x ,e 的 x 次方 s = 1.0 / (1 + 1/ math.exp(x)) ### END CODE HERE ### return s # Actually, we rarely use the “math” library in deep learning # because the inputs of the functions are real numbers. # In deep learning we mostly use matrices and vectors. # This is why numpy is more useful. # 不常用 math 这个库,因为因为它的输入参数为实数,而实际上,在 deep learning 中,我们常用到的训练数据 # 都是 矩阵 或向量的形式,所以 numpy 这个库,非常的有用 import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function() def sigmoid1(x): """ Compute the sigmoid of x Arguments: x -- A scalar (标量) or numpy array of any size. Return: s -- sigmoid1(x) """ ### START CODE HERE ### (≈ 1 line of code) s = 1.0/(1+1/np.exp(x)) ### END CODE HERE ### return s # GRADED FUNCTION: sigmoid_derivative def sigmoid_derivative(x): """ Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x. You can store the output of the sigmoid function into variables and then use it to calculate the gradient. Arguments: x -- A scalar or numpy array Return: ds -- Your computed gradient. """ ### START CODE HERE ### (≈ 2 lines of code) s = 1.0 /(1 + 1/np.exp(x)) ds = s*(1-s) ### END CODE HERE ### return ds if __name__ == '__main__': print(basic_sigmoid(3)) ### One reason why we use "numpy" instead of "math" in Deep Learning ### x = [1, 2, 3] # you will see this give an error when you run it, because x is a vector. # basic_sigmoid(x) # TypeError: must be real number, not list print(sigmoid_derivative(0)) # 0.25 print(sigmoid_derivative(x)) # [ 0.19661193 0.10499359 0.04517666]
a109aabea2626c986f6d6ac3835c7cbfba826d34
anilachacko/python
/CO2/C002.py
157
3.859375
4
n=int(input("enter the limit")) a=0 b=1 print("fibonacci series") print(a) print(b) for i in range(1,n-1): c=a+b print(c) a=b b=c
d504f75cf01c29b1a096215477aae8f7d6f55ec9
kamojiro/atcoderall
/beginner/176/B2.py
44
3.671875
4
print("Yes" if int(input())%9==0 else "No")
92129c31f56378d915ac4d2f576d70cd8fe2bd8d
mwrouse/Python
/Chapter 10/challenge10_1.py
4,563
4.03125
4
""" Program......: challenge10_1.py Author.......: Michael Rouse Date.........: 3/5/14 Description..: Create your own version of the Mad Lib Program """ from tkinter import * class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): """ Initialize Frame. """ super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get story information and to display story. """ # create instruction label Label(self, text="Enter information for a new story").grid(row=0, column=0, columnspan=2, sticky=W) # create a label and text entry for the name of a person Label(self, text="Person: ").grid(row=1, column=0, sticky=W) self.person_ent = Entry(self) self.person_ent.grid(row=1, column=1, sticky=W) # create a label and text entry for a plural noun Label(self, text="Plural Noun:").grid(row=2, column=0, sticky=W) self.noun_ent = Entry(self) self.noun_ent.grid(row=2, column=1, sticky=W) # create a label and text entry for a verb Label(self, text="Verb:").grid(row=3, column=0, sticky=W) self.verb_ent = Entry(self) self.verb_ent.grid(row=3, column=1, sticky=W) # create a label for adjectives check buttons Label(self, text="Adjective(s):").grid(row=1, column=2, sticky=W) # create itchy check button self.is_itchy = BooleanVar() Checkbutton(self, text="itchy", variable=self.is_itchy).grid(row=1, column=3, sticky=W) # create joyous check button self.is_joyous = BooleanVar() Checkbutton(self, text="joyous", variable=self.is_joyous).grid(row=1, column=4, sticky=W) # create electric check button self.is_electric=BooleanVar() Checkbutton(self, text="electric", variable=self.is_electric).grid(row=1, column=5, sticky=W) # create a label for body parts radio buttons Label(self, text="Body Part:").grid(row=2, column=2, sticky=W) # create variable for single, body part self.body_part = StringVar() self.body_part.set(None) # create body part radio buttons body_parts = ["bellybutton", "big toe", "medulla oblongata"] column = 3 for part in body_parts: Radiobutton(self, text=part, variable=self.body_part, value=part ).grid(row=2, column=column, sticky=W) column += 1 # create a submit button Button(self, text="Click for story", command=self.tell_story ).grid(row=3, column=2, sticky=W) self.story_txt = Text(self, width=75, height=10, wrap=WORD) self.story_txt.grid(row=7, column=0, columnspan=6, pady=5) def tell_story(self): """ Fill text box with new story based on user input. """ # get values from the GUI person=self.person_ent.get() noun=self.noun_ent.get() verb=self.verb_ent.get() adjectives="" if self.is_itchy.get(): adjectives += "itchy, " if self.is_joyous.get(): adjectives += "joyous, " if self.is_electric.get(): adjectives += "electric, " body_part=self.body_part.get() # create the story story="The famous explorer " story += person story += " had nearly given up a life-long quest to find The Lost City of " story += noun.title() story += " when one day, the " story += noun story += " found " story += person + ". " story += "A strong, " story += adjectives story += "peculiar feeling overwhelmed the explorer. " story += "After all this time, the quest was finally over. A tear came to " story += person + "'s " story += body_part + ". " story += "And then, the " story += noun story += " promptly devoured " story += person + ". " story += "The moral of the story? Be careful what you " story += verb story += " for." # display the story self.story_txt.delete(0.0, END) self.story_txt.insert(0.0, story) # main root = Tk() root.title("Mad Lib") app=Application(root) root.mainloop()
0c47464c0b7e249f89c517ba2a03c16d25551ebd
nitsuga/mrplan
/src/mrplan_auctioneer/src/mrplan_auctioneer/item.py
1,073
4.03125
4
"""item.py This module defines the Item class used in MRPlan experiments. Eric Schneider <[email protected]> """ from enum import Enum class Material(Enum): """ Materials are composed to make up Items. At first, this class just identifies and distinguishes one material from another via an enumeration pattern. In future, this class may implement material properties as described in mrplan_msgs/msg/Item.msg """ GREY = 0 RED = 1 BLUE = 2 GREEN = 3 WHITE = 4 BLACK = 5 class Item(object): def __init__(self, _item_id='1', _materials=[0, 0, 0, 0, 0, 0], _site=''): # A unique identifier for this item. self.item_id = _item_id # The numbers of each type of material needed to construct # this Item. An index of this list represents a Material type # (an enumeration, above) with an integer values that represents # the number of units of that material required. self.materials = _materials self.site = _site self.completed = False self.awarded = False
4a1ea738d3d4eb866346b25aee832f31ae1540f6
porala/python
/practice/88.py
385
3.875
4
#Create a script that uses countries_by_area.txt file as data sourcea and prints out the top 5 most densely populated countries import pandas data = pandas.read_csv("countries_by_area.txt") data["density"] = data["population_2013"] / data["area_sqkm"] data = data.sort_values(by="density", ascending=False) for index, row in data[:5].iterrows(): print(row["country"])
62c5a065fedcfae0f79abff797ba06b21b46bd9c
cmirza/cs_work
/Unit_2/module_3.py
1,447
3.671875
4
def validBracketSequence(sequence): # define opening and closing chars open_char = ("(", "[", "{") close_char = (")", "]", "}") stack = [] # iterate over chars in sequence for char in sequence: if char in open_char: stack.append(char) elif char in close_char: pos = close_char.index(char) if len(stack) > 0 and open_char[pos] == stack[len(stack) - 1]: stack.pop() else: return False if len(stack) == 0: return True else: return False class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def queueOnStacks(requests): left = Stack() right = Stack() def insert(x): left.push(x) def remove(): # check if right stack is empty if len(right.items) == 0: while len(left.items) > 0: right.push(left.pop()) if len(right.items) == 0: return None # then return right stack item return right.pop() ans = [] for request in requests: req = request.split(" ") if req[0] == 'push': insert(int(req[1])) else: ans.append(remove()) return ans
b1efd564425abb04f08f754e34ec7bb01dcce28e
CptnSteve/prime_viz
/prime_viz.py
1,254
3.59375
4
import numpy as np import matplotlib.pyplot as plt def move_right(x,y): return x+1, y def move_left(x,y): return x-1, y def move_up(x,y): return x,y+1 def move_down(x,y): return x,y-1 def gen_points(end): from itertools import cycle moves = [move_right, move_down, move_left, move_up] _moves = cycle(moves) n = 1 pos = 0,0 times_to_move = 1 yield prime_check(n), pos[0], pos[1], n while True: for _ in range(2): move = next(_moves) for _ in range(times_to_move): if n >= end: return pos = move(*pos) n+=1 yield prime_check(n), pos[0], pos[1], n times_to_move+=1 def plotting(x, y): plt.scatter(x,y) plt.show() def prime_check(num): prime_status = 1 if (num==1): prime_status = 0 for i in range(2,num): if (num % i == 0): prime_status = 0 break return prime_status def main(): GRID_LEN = 150 grid_area = GRID_LEN * GRID_LEN x = [] y = [] for val in gen_points(grid_area): if val[0] == 1: x.append(val[1]) y.append(val[2]) if val[3] % 100 == 0: print("Eval: ", val[3], " out of ", grid_area) plotting(x,y) main()
074cf3c8a34d270d0e1c06462c2c637d54058e37
ianbooth12/python_crash_course
/chapter_2/2lesson.py
420
3.96875
4
inches_in_foot = 12_000_000 print(inches_in_foot) # Although Python removes underscores in print, makes more readable. x, y, z = 0, 0 ,0 print(x) # You can define multiple variables in one line of code with commas name1, name2, name3 = "mason", "jad", "kadin" print(name2) # Multiple variables can also be defined with different information BIRTHYEAR = 2001 # Constant variables can be indicated by typing in caps.
1c3fe91750ccb3f3873aba3d36fe7bcb302993ac
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4352/codes/1650_2450.py
127
4.03125
4
a = input("digite um nome:") b = input("digite outro nome:") if (a > b.upper()): print(b) print(a) else: print(a) print(b)
2e8181335d92a1f63aa6e07a865110d74d52a66d
LucasOJacintho/Curso_em_video_python
/Exercícios/ex84.py
913
3.734375
4
pessoas = [] dados = [] maior = menor = 0 while True: dados.append(str(input('Digite o nome: '))) dados.append((float(input('Digite o peso em kg: ')))) ##teste para definir qual é o peso maior e menor if len(pessoas) == 0: maior = menor = dados[1] else: if dados[1] > maior: maior = dados[1] if dados[1] < menor: menor = dados[1] pessoas.append(dados[:]) dados.clear() opcao = input('Quer continuar cadastrando? [S/N]: ') if opcao in 'Nn': break print('*' * 30) print(f'Foram cadastradas {len(pessoas)} pessoas na lista.') print(f'O maior peso da lista é {maior} kg que é o peso de ', end='') for i in pessoas: if i[1] == maior: print(f'[{i[0]}] ', end='') print(f'\nE o menor peso da lista é {menor} kg que é o peso de ', end='') for i in pessoas: if i[1] == menor: print(f'[{i[0]}] ', end='')
e148b845fbc45964a0d3de23b60f704e60386933
T-o-s-s-h-y/Learning
/Python/progate/python_study_2/page2/script.py
360
3.640625
4
# 変数fruitsに、複数の文字列を要素に持つリストを代入してください fruits = ['apple', 'banana', 'orange'] # インデックス番号が0の要素を出力してください print(fruits[0]) # インデックス番号が2の要素を文字列と連結して出力してください print("好きな果物は" + fruits[2] + "です")
257ef0e3cc3999e05789c38a8d071e839127fdd7
mattsuri/unit3
/quiz3.py
298
3.609375
4
#Matthew Suriawinata #3/5/18 #quiz3.py num = -15 while num < -8: print(num) num += 1 for i in range(50, 17, -4): print(i) total = 0 for i in range(-100, 1000, 2): total += i print(total) while True: text = input("Enter text: ") if "alpaca" in text: break
e095fcff239d4f6e7781b37f32fc0b828b6b0ed8
santhoshbabu4546/GUVI-9
/set7/prime1.py
197
3.875
4
import math a2=int(input()) x=0 if a2 == 2 and a2 == 3: print("yes") for i in range(2,int(math.sqrt(a2))+1): if a2%i==0: print("no") x=x+1 break if x==0: print("yes")
3437e33328dff4970cd7df338f4ff914ec55fb32
NidhoggZe/LeetCode
/py/1.两数之和2.py
486
3.59375
4
#用hashmap记录是否出现过(字典同时还能将索引存为值)O(n) class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ hashmap = {} for i in range(0, nums.__len__()): if target - nums[i] in hashmap: return [hashmap[target - nums[i]], i] else: hashmap[nums[i]] = i return None
8304a0454f11294a1e9a36f410c6806da5260cb8
chetanpv/python-snippets
/LevelTwo/square_odd_numbers.py
558
4.25
4
# Question: # Use a list comprehension to square each odd number in a list. The list is input by a sequence # of comma-separated numbers. # Suppose the following input is supplied to the program: # 1,2,3,4,5,6,7,8,9 # Then, the output should be: # 1,3,5,7,9 print "\nEnter sequence of numbers: " numbers = raw_input().split(",") output = [] for i in numbers: n = int(i) if n % 2 != 0: output.append(str(n*n)) print ",".join(output) output = [str(int(i)*int(i)) for i in numbers if int(i) % 2 != 0] print ",".join(output)
97aa9934fd753069b47ffa1518c5945a031dc0e0
WellingtonTorres/PythonExercicios
/ex009.py
182
3.859375
4
n = int(input('Digite um numero para ver sua tabuada: ')) i = 1 print('-' * 11) while i <= 10: r = n * i print('{} x {:2} = {:3}'.format(n, i, r)) i += 1 print('-' * 11)
8ffe034bda17bdde0d334ead9424d4e2589a8bb4
rkpatra201/python-practice
/python-basics/109_tuples.py
268
4
4
# tuples are same as list but are immutable item = (1, 1, "test", 3.2, {'a': 'b'}) print(item) print(type(item)) print(item[0]) print(item[2:]) print(len(item)) print(item.index(1)) print(item.count(1)) #item[2] = 20 #'tuple' object does not support item assignment
fd4e3cb4a2cd28da6ba2e5a1657df44ed81421a2
nickyfoto/lc
/python/tests/1345_jump_game_iv.py
10,674
3.5
4
# # @lc app=leetcode id=1345 lang=python3 # # [1345] Jump Game IV # # https://leetcode.com/problems/jump-game-iv/description/ # # algorithms # Hard (27.33%) # Likes: 37 # Dislikes: 1 # Total Accepted: 1.4K # Total Submissions: 5.1K # Testcase Example: '[100,-23,-23,404,100,23,23,23,3,404]' # # Given an array of integers arr, you are initially positioned at the first # index of the array. # # In one step you can jump from index i to index: # # # i + 1 where: i + 1 < arr.length. # i - 1 where: i - 1 >= 0. # j where: arr[i] == arr[j] and i != j. # # # Return the minimum number of steps to reach the last index of the array. # # Notice that you can not jump outside of the array at any time. # # # Example 1: # # # Input: arr = [100,-23,-23,404,100,23,23,23,3,404] # Output: 3 # Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that # index 9 is the last index of the array. # # # Example 2: # # # Input: arr = [7] # Output: 0 # Explanation: Start index is the last index. You don't need to jump. # # # Example 3: # # # Input: arr = [7,6,9,6,9,6,9,7] # Output: 1 # Explanation: You can jump directly from index 0 to index 7 which is last # index of the array. # # # Example 4: # # # Input: arr = [6,1,9] # Output: 2 # # # Example 5: # # # Input: arr = [11,22,7,7,7,7,7,7,7,22,13] # Output: 3 # # # # Constraints: # # # 1 <= arr.length <= 5 * 10^4 # -10^8 <= arr[i] <= 10^8 # # # @lc code=start from collections import defaultdict, deque from collections.abc import Mapping, Set from itertools import combinations class AtlasView(Mapping): __slots__ = ('_atlas',) def __getstate__(self): return {'_atlas': self._atlas} def __setstate__(self, state): self._atlas = state['_atlas'] def __init__(self, d): self._atlas = d def __len__(self): return len(self._atlas) def __iter__(self): return iter(self._atlas) def __getitem__(self, key): return self._atlas[key] def copy(self): return {n: self[n].copy() for n in self._atlas} def __str__(self): return str(self._atlas) # {nbr: self[nbr] for nbr in self}) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self._atlas) class AdjacencyView(AtlasView): __slots__ = () # Still uses AtlasView slots names _atlas def __getitem__(self, name): return AtlasView(self._atlas[name]) def copy(self): return {n: self[n].copy() for n in self._atlas} class NodeView(Mapping, Set): def __getstate__(self): return {'_nodes': self._nodes} def __setstate__(self, state): self._nodes = state['_nodes'] def __init__(self, graph): self._nodes = graph._node # Mapping methods def __len__(self): return len(self._nodes) def __iter__(self): return iter(self._nodes) def __getitem__(self, n): return self._nodes[n] # Set methods def __contains__(self, n): return n in self._nodes @classmethod def _from_iterable(cls, it): return set(it) # DataView method def __call__(self, data=False, default=None): if data is False: return self return NodeDataView(self._nodes, data, default) def data(self, data=True, default=None): if data is False: return self return NodeDataView(self._nodes, data, default) def __str__(self): return str(list(self)) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, tuple(self)) class Graph: node_dict_factory = dict node_attr_dict_factory = dict adjlist_outer_dict_factory = dict adjlist_inner_dict_factory = dict edge_attr_dict_factory = dict graph_attr_dict_factory = dict def __init__(self, incoming_graph_data=None, **attr): self.graph_attr_dict_factory = self.graph_attr_dict_factory self.node_dict_factory = self.node_dict_factory self.node_attr_dict_factory = self.node_attr_dict_factory self.adjlist_outer_dict_factory = self.adjlist_outer_dict_factory self.adjlist_inner_dict_factory = self.adjlist_inner_dict_factory self.edge_attr_dict_factory = self.edge_attr_dict_factory self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes self._node = self.node_dict_factory() # empty node attribute dict self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict # attempt to load graph with data if incoming_graph_data is not None: convert.to_networkx_graph(incoming_graph_data, create_using=self) # load graph attributes (must be after convert) self.graph.update(attr) def __iter__(self): return iter(self._node) @property def adj(self): return AdjacencyView(self._adj) def add_nodes_from(self, nodes_for_adding, **attr): for n in nodes_for_adding: # keep all this inside try/except because # CPython throws TypeError on n not in self._node, # while pre-2.7.5 ironpython throws on self._adj[n] try: if n not in self._node: self._adj[n] = self.adjlist_inner_dict_factory() attr_dict = self._node[n] = self.node_attr_dict_factory() attr_dict.update(attr) else: self._node[n].update(attr) except TypeError: nn, ndict = n if nn not in self._node: self._adj[nn] = self.adjlist_inner_dict_factory() newdict = attr.copy() newdict.update(ndict) attr_dict = self._node[nn] = self.node_attr_dict_factory() attr_dict.update(newdict) else: olddict = self._node[nn] olddict.update(attr) olddict.update(ndict) def add_edges_from(self, ebunch_to_add, **attr): for e in ebunch_to_add: ne = len(e) if ne == 3: u, v, dd = e elif ne == 2: u, v = e dd = {} # doesn't need edge_attr_dict_factory else: raise NetworkXError( "Edge tuple %s must be a 2-tuple or 3-tuple." % (e,)) if u not in self._node: self._adj[u] = self.adjlist_inner_dict_factory() self._node[u] = self.node_attr_dict_factory() if v not in self._node: self._adj[v] = self.adjlist_inner_dict_factory() self._node[v] = self.node_attr_dict_factory() datadict = self._adj[u].get(v, self.edge_attr_dict_factory()) datadict.update(attr) datadict.update(dd) self._adj[u][v] = datadict self._adj[v][u] = datadict @property def nodes(self): nodes = NodeView(self) self.__dict__['nodes'] = nodes return nodes def is_directed(self): """Returns True if graph is directed, False otherwise.""" return False def _bidirectional_pred_succ(G, source, target): # does BFS from both source and target and meets in the middle if target == source: return ({target: None}, {source: None}, source) # handle either directed or undirected if G.is_directed(): Gpred = G.pred Gsucc = G.succ else: Gpred = G.adj Gsucc = G.adj # predecesssor and successors in search pred = {source: None} succ = {target: None} # initialize fringes, start with forward forward_fringe = [source] reverse_fringe = [target] while forward_fringe and reverse_fringe: if len(forward_fringe) <= len(reverse_fringe): this_level = forward_fringe forward_fringe = [] for v in this_level: for w in Gsucc[v]: if w not in pred: forward_fringe.append(w) pred[w] = v if w in succ: # path found return pred, succ, w else: this_level = reverse_fringe reverse_fringe = [] for v in this_level: for w in Gpred[v]: if w not in succ: succ[w] = v reverse_fringe.append(w) if w in pred: # found path return pred, succ, w raise nx.NetworkXNoPath("No path between %s and %s." % (source, target)) def bidirectional_shortest_path(G, source, target): if source not in G or target not in G: msg = 'Either source {} or target {} is not in G' raise nx.NodeNotFound(msg.format(source, target)) # call helper to do the real work results = _bidirectional_pred_succ(G, source, target) pred, succ, w = results # build path from pred+w+succ path = [] # from source to w while w is not None: path.append(w) w = pred[w] path.reverse() # from w to target w = succ[path[-1]] while w is not None: path.append(w) w = succ[w] return path class Solution: # def minJumps(self, arr: List[int]) -> int: def minJumps(self, arr): d = defaultdict(list) [d[x].append(i) for i, x in enumerate(arr)] q = [(0,0)] num_met, pos_met = set(), set() while q: i, steps = q.pop(0) # state: position, step if i == len(arr) - 1: return steps num = arr[i] pos_met.add(i) # track explored positions print(d[num], (num not in num_met)) for p in [i - 1, i + 1] + d[num] * (num not in num_met): if p in pos_met or not 0 <= p < len(arr): continue q.append((p, steps + 1)) num_met.add(num) # track explored values def minJumps_tle(self, arr): d = defaultdict(list) for i, val in enumerate(arr): d[val].append(i) # print(d) n = len (arr) edges = [] for _, v in d.items(): edges += list(combinations(v, 2)) for i in range(1, n - 1): edges += [(i-1,i), (i,i+1)] # print(edges, n) # import networkx as nx # g = nx.Graph() g = Graph() g.add_nodes_from(range(n)) g.add_edges_from(edges) return len(bidirectional_shortest_path(g, 0, n - 1)) - 1 # @lc code=end
96b3f2f8175545ecf04a3dd05fd61d21a8a15f3b
NathanPaceydev/MadLibs-Oh-The-Places-You-Will-Go
/Rewrite_story_scrape.py
1,974
3.71875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #first time scraping program ## I wanted to do something static to start and just have fun with the outcome # import libraries import requests from bs4 import BeautifulSoup # In[2]: # scraping the staic website URL = "http://denuccio.net/ohplaces.html" page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") #print(page.text) # prints the text obj, ie the html code # In[3]: result = soup.find_all("p") StringDict = [] #print(result) for results in result: StringDict.append(str(results.get_text())) print("Oh the Places You Will Go\nDr.Suess") print(StringDict[1]) #iteratable container #job_elements = results.find_all("p") # In[4]: #User Input print("Enter a Body part") NounB = input() print("\nEnter a Verb") Verb1 = input() print("\nEnter a 2nd Verb") Verb2 = input() print("\nEnter Your Name") YourName = input() print("\nEnter a Place") place = input() print("Enter an Adjective") Adjective1 = input() print("Enter a number") num = input() stringPrint = "\n"+YourName+" Entered a noun: "+NounB+", a verb of: "+Verb1+" and "+Verb2+", in a location of "+ place print(stringPrint) # In[5]: stringT = (StringDict[1].strip()).split("***") string = stringT[0] #print(Noun) string = string.replace("brain",NounB) string = string.replace("foot",NounB) string = string.replace("the guy", YourName) string = string.replace("You", YourName) string = string.replace("town",place) string = string.replace("head straight",Verb1) string = string.replace("fliers",Verb2) string = string.replace("prowl",Verb2) string = string.replace("The Waiting Place",place) string = string.replace("Great",Adjective1) string = string.replace("Buxbaum",str(YourName[0]+"uxbaum")) string = string.replace("Bixby",str(YourName[0]+"ixby")) string = string.replace("Bray",str(YourName[0]+"ray")) string = string.replace("98",num) print("The New Updated Story Just for You:\n\n") print(string)
e0e5b303749671f617a28d8c84a3bacd00fb24f7
moguzozcan/HackerrankSolutions
/Python/scripts/while_loop.py
300
3.6875
4
c = 5 while c != 0: print(c) c -= 1 c = 5 while c: print(c) c -= 1 #Zen of Python explicit is better than implicit, use the first one #Infinite loops, if divisible by 7, exit the loop while True: response = input() if int(response) % 7 == 0: break
6bbc0fa9537921344976be8d802b5a21e4542f93
5l1v3r1/crypto_utils
/morse/main.py
714
3.6875
4
#!/usr/bin/python "Morse encoder/decoder with option of custom charset, CC-BY: hasherezade" import argparse from morse import * def main(): parser = argparse.ArgumentParser(description="Morse Encoder/Decoder") parser.add_argument('--charset', dest="charset", default='.- ', help="Charset in format: 'DitDashBreak', i.e '.- '") parser.add_argument('--decode', dest="decode", default=False, action='store_true', help="Decode or encode the given input?") args = parser.parse_args() m = Morse(args.charset) print "Enter a message:" raw = raw_input() if args.decode: print m.morse_dec(raw) else: print m.morse_enc(raw) if __name__ == "__main__": main()
bb5dd5eee44a3a59bd9371bf65bcfd293df34cec
avenet/hackerrank
/algorithms/implementation/repeated_string.py
268
3.59375
4
s = input().strip() n = int(input().strip()) a_count = s.count('a') whole_str_reps = n // len(s) partial_str_length = n % len(s) partial_str = s[:partial_str_length] partial_str_a_count = partial_str.count('a') print(a_count * whole_str_reps + partial_str_a_count)
a070a1d91a9d2cb4ddaf5fcae2c3ae6dd7251844
chauhanvishu/shiny-dollop
/ab/1.py
247
3.796875
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 12 23:52:15 2018 @author: aksha """ our_list = [] first_num = int(input('Enter first number: ')) second_num = int(input('Enter second number: ')) third_num = int(input('Enter third number: '))
a2978b664b22a741f9200cf18cbf12afa8167e7d
EricMoura/Aprendendo-Python
/Exercícios de Introdução/Ex030.py
152
4
4
num = int(input('Digite um número inteiro qualquer: ')) if num%2 == 0: print('Esse número é par') else: print('Esse número é ímpar')
3d9c924be611582a9b609dff66c250c143326f03
cdiebold/python-class
/longest_word.py
327
4.03125
4
def longest_word(sen): for ch in sen: if not char.isalnum(): sen = sen.replace(char, ' ') return max(sen.split(), key = len) if __name__ == "__main__": sen1 = "fun&!! time" sen2 = "I love dogs" res1 = longest_word(sen1) print(res1) res2 = longest_word(sen2) print(res2)
f4dd5068593579ae03d92f59e53fc6349086e556
choiseoungho/ssafy
/Day2/3장/ex2.py
728
3.578125
4
# 사용자가 시청한 작품의 리스트를 저장합니다. 수정하지 마세요. user_to_titles = { 1: [271, 318, 491], 2: [318, 19, 2980, 475], 3: [475], 4: [271, 318, 491, 2980, 19, 318, 475], 5: [882, 91, 2980, 557, 35], } def get_user_to_num_titles(user_to_titles): ''' 사용자가 시청한 작품의 수를 리턴합니다. >>> get_user_to_num_titles({1: [271, 318, 491]}) {1: 3} ''' user_to_num_titles = {} for user, titles in user_to_titles.items(): user_to_num_titles[user] = len(titles) return user_to_num_titles # 아래 주석을 해제하고 결과를 확인해보세요. print(get_user_to_num_titles(user_to_titles))
b5f1a6dbd33e6dc74106a9b38fee73f9c4058b5e
Prasanna0708/forloop-task
/while.py
119
4.3125
4
print("By using While Loop Printing values reverse from 10 to 1") x = 10 while(x>0): print(x) x = x-1
fdfaac9f6b17907935bdfd2f2d23652b9ea22f4c
A-Chornaya/Python-Programs
/Other tasks/dejkstra.py
3,492
3.75
4
# Algorithm Dejkstry # search for the shortest path from one knot of the graph to all others # Matrix as a list of lists from collections import deque def dejkstra(matrix, start): n = len(matrix) distance = [None] * n path = [0] * n distance[start] = 0 nonvisited = [start] visited = [] while nonvisited: current = min(nonvisited, key=lambda x: distance[x]) current_dist = distance[current] for i, weight in enumerate(matrix[current]): if i in visited: continue if weight: if distance[i] is None or distance[i] > weight + current_dist: distance[i] = weight + current_dist path[i] = current nonvisited.append(i) visited.append(current) nonvisited.remove(current) return distance, path def recreate_path(path_list, node): path = deque() current = node path.append(node) while path_list[current] != current: path.appendleft(path_list[current]) current = path_list[current] return list(path) Matrix = [ [0, 1, 3, 5, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 4, 2, 0, 0], [1, 0, 1, 3, 0] ] start = 0 dist, path = dejkstra(Matrix, start) print(dist, path) # [0, 1, 2, 4, 1] [0, 0, 4, 4, 0] node = 2 path_list = recreate_path(path, node) print(f'path from start={start} to node={node}: {path_list}') # path from start=0 to node=2: [0, 4, 2] print('') Matrix2 = [ [0, 7, 9, 0, 0, 14], [7, 0, 10, 15, 0, 0], [9, 10, 0, 11, 0, 2], [0, 15, 11, 0, 6, 0], [0, 0, 0, 6, 0, 9], [14, 0, 2, 0, 9, 0] ] start2 = 0 dist2, path2 = dejkstra(Matrix2, start) print(dist2, path2) # [0, 7, 9, 20, 20, 11] [0, 0, 0, 2, 5, 2] node2 = 4 path_list2 = recreate_path(path2, node2) print(f'path from start={start2} to node={node2}: {path_list2}') # path from start=0 to node=4: [0, 2, 5, 4] #################################################### # Matrix as a dict import operator def dejk(matrix, start): dist = dict.fromkeys(matrix.keys(), None) dist[start] = 0 nonvisited = dist.copy() path = dist.copy() path[start] = start visited = [] elements = len(matrix.keys()) while nonvisited: knot, weight = min(list(filter(lambda item: item[1] is not None, nonvisited.items())), key=operator.itemgetter(1)) for child in matrix[knot].keys(): if child not in nonvisited: continue if dist[child] is None or dist[child] > matrix[knot][child] + weight: dist[child] = matrix[knot][child] + weight path[child] = knot nonvisited[child] = dist[child] del nonvisited[knot] return dist, path G = { 'A': {'B': 5, 'D': 3, 'E': 12, 'F': 5}, 'B': {'A': 5, 'D': 1, 'G': 2}, 'C': {'G': 2, 'E': 1, 'F': 16}, 'D': {'B': 1, 'G': 1, 'E': 1, 'A': 3}, 'E': {'A': 12, 'D': 1, 'C': 1, 'F': 2}, 'F': {'A': 5, 'E': 2, 'C': 16}, 'G': {'B': 2, 'D': 1, 'C': 2}, } dist, path = dejk(G, 'B') print(dist) print(path) # {'A': 4, 'B': 0, 'C': 3, 'D': 1, 'E': 2, 'F': 4, 'G': 2} # {'A': 'D', 'B': 'B', 'C': 'E', 'D': 'B', 'E': 'D', 'F': 'E', 'G': 'B'}
6652cea1f27b477a57b8732b31db418c88ed5c67
thrama/coding-test
/python/gradingStudents.py
1,384
4.09375
4
import math import os import random import re import sys # # HackerLand University has the following grading policy: # - Every student receives a grades in the inclusive range from 0 to 100. # - Any grade less than 40 is a failing grade. # # Sam is a professor at the university and likes to round each student's grade # according to these rules: # - If the difference between the grade and the next multiple of 5 is less # than 3, round grade up to the next multiple of 5. # - If the value of grade is less than 38, no rounding occurs as the result # will still be a failing grade. # # For example, grade = 84 will be rounded to 85 but grade 29 will not be # rounded because the rounding would result in a number that is less than 40. # Given the initial value of grade for each of Sam's n students, write code # to automate the rounding process. # # Link: https://www.hackerrank.com/challenges/grading/problem # def gradingStudents(grades): r = [] for i in range(len(grades)): if grades[i] < 38: r.append(grades[i]) else: if grades[i] % 5 < 3: r.append(grades[i]) else: r.append(grades[i] + (5 - (grades[i] % 5))) return r if __name__ == '__main__': # simple test case grades = [ 73, 67, 38, 33 ] result = gradingStudents(grades) print(result)
17a2aa1badf14781162aa8c3bf172de640cbaea8
vimkaf/Learning-Python
/comment_break.py
205
3.796875
4
# This is a single line commment """ This is a multiline comment """ num = 15 for x in range(100): if x is num: print('x is the number') break else: print(x)
bd9572157e1c093764b8b1ebd0c0b9f0119fc871
Daria706/Lab
/Task 2.py
217
3.953125
4
a = float(input("Введите основание a")) h = float(input("Введите высоту h")) S = 0.5 * a * h if S%2 == 0: S=S/2 print("S=",S) else: print("Не могу делить на 2!")
afc23bc1cd715817243dde7acdf39c00570c6472
mepujan/IWAssignment_1_python
/data_types/data_type_21.py
353
4.375
4
# Write a Python program to get a list, sorted in increasing order by the last # element in each tuple from a given list of non-empty tuples. def last(n): return n[-1] def sort_list_last(tuples): return sorted(tuples, key=last) def main(): print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)])) if __name__ == '__main__': main()
cfd730b4343cc845beae838a576d06d08c83f6c9
RhysMurage/alx-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
418
4.375
4
#!/usr/bin/python3 """ Module that has the function print_square """ def print_square(size): """Prints a square using the character '#' Args: size (int): dimensions of the square """ if not isinstance(size, int): raise TypeError('size must be an integer') if size < 0: raise ValueError('size must be >= 0') h = 0 for h in range(0, size): print('#'*size)
e1ddc5442fae207bd82bece5723465c1d6257ced
ArpitSharma2800/Algorithms-and-Basic-Programmes
/Python/Algorithms/LeftSumArray.py
1,048
3.65625
4
# Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sum. def naive_method(arr): # slower method # O(n^2) n = len(arr) counter = 0 for x in range(n): # calculating sum of left and right part and comparing values if sum(arr[:x]) == sum(arr[x + 1:]): counter += 1 return counter def fast_method(arr): # faster method # O(n) left_sum_array = [] right_sum_array = [] temp_sum = 0 for x in arr: temp_sum += x left_sum_array.append(temp_sum) temp_sum = 0 for x in reversed(arr): temp_sum += x right_sum_array.append(temp_sum) counter = 0 # comparing left_sum_array and right_sum_array # incrementing counter whenever the values collide for x, y in zip(left_sum_array, right_sum_array): if x == y: counter += 1 return counter # Test Code arr = [2, 3, 4, 1, 5, 4] # Output : 1 # Subarrays are : {2, 3, 4} and {4, 5} print(fast_method(arr))
3c254824529fc639c8a3bd47fc9fe772329f9a5a
perext5528/Python_2019
/repl.it Example/3. If & Else/H. Queen move.py
186
3.75
4
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) dx = abs(x1 - x2) dy = abs(y1 - y2) if (x1==x2) or (y1==y2) or (dx == dy): print("YES") else: print("NO")
b57ecc5edda54252e5c44e2eda6dea963029124b
seanchen513/leetcode
/bits/0260_single_numer_iii.py
2,381
3.984375
4
""" 260. Single Number III Medium Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. Example: Input: [1,2,1,3,2,5] Output: [3,5] Note: The order of the result is not important. So in the above example, [5, 3] is also correct. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? """ from typing import List import collections ############################################################################### """ Solution: use dict to count numbers. O(n) time O(n) space """ class Solution: def singleNumber(self, nums: List[int]) -> List[int]: d = collections.Counter(nums) res = [] for x in d: if d[x] == 1: res.append(x) return res ############################################################################### """ Solution: use set. O(n) time O(n) space """ class Solution: def singleNumber(self, nums: List[int]) -> List[int]: s = set() for x in nums: if x in s: s.remove(x) else: s.add(x) return list(s) ############################################################################### """ Solution: use bits. O(n) time O(1) space """ import functools class Solution: def singleNumber(self, nums: List[int]) -> List[int]: # Find XOR of the two unique numbers. If we can find one of the two # unique numbers (say "a"), then the other one will be "a ^ mask". mask = 0 for x in nums: mask ^= x # mask = functools.reduce(operator.xor, nums) # Find rightmost 1-bit of xor. # ie, the rightmost bit where the two unique numbers differ diff = mask & -mask # Use "diff" to filter for the unique number that has a 1-bit in # the position of the 1-bit of diff. # This unique number will be "a". # The other unique number will be "a ^ xor". # All the other numbers either (1) have x & diff == 0, or # (2) have x & diff == 1, but get XOR'd into "a" twice, thus # cancelling itself out. a = 0 for x in nums: if x & diff: a ^= x return [a, a ^ mask]
135093a5d17b5e01e05b613e63ed425b17954229
rorochaudhary/sudoku
/sudoku_verifier.py
3,241
4.21875
4
# Name: Rohit Chaudhary # Course: CS 325 - Analysis of Algorithms # HW 8: Portfolio Project # Date: 12/7/20 # Description: For this project I chose to implement a 9x9 Sudoku solution verifier. The verifier takes as input a user-submitted solution.txt and determines whether solution.txt is a valid solution certifiate according to the rules of Sudoku. solution.py contains a 9x9 multi-dimensional array containing digit values 0-9 (where 0 denotes an empty position). def check_solution(certificate): """iterates over certificate and determines whether certificate is a valid solution according to Sudoku rules: each row, each column, and each non-overlapping 3x3 grid must contain values between 1 and 9. returns True if certificate is a valid solution or False otherwise""" # check for 9x9 size solution r = len(certificate) if r != 9: return False else: for i in range(r): if len(certificate[i]) != 9: return False # verify according to sudoku rules if check_rows(certificate) and check_columns(certificate) and check_subboxes(certificate): return True else: return False def check_rows(certificate): """intermediate function called by check_solution in order to determine whether each row of sudoku solution contains digits 1-9 exactly once""" r = len(certificate) for i in range(r): row = set(certificate[i]) if sum(row) != 45 or len(row) != 9: return False return True def check_columns(certificate): """intermediate function called by check_solution in order to determine whether each column of sudoku solution contains digits 1-9 exactly once""" r = len(certificate) # list of sets, each set is a column col_grid = [set() for x in range(r)] for i in range(r): for j in range(r): col_grid[j].add(certificate[i][j]) # verify columns for i in range(r): if sum(col_grid[i]) != 45 or len(col_grid[i]) != 9: return False return True def check_subboxes(certificate): """intermediate function called by check_solution in order to determine whether each 3x3 sub-box of the sudoku solution contains digits 1-9 exactly once""" r = len(certificate) boxes = [[set() for k in range(3)] for l in range(3)] # get the subboxes for i in range(r): for j in range(r): row = i // 3 col = j // 3 boxes[row][col].add(certificate[i][j]) # verify subboxes for i in range(3): for j in range(3): if sum(boxes[i][j]) != 45 or len(boxes[i][j]) != 9: return False return True # # code below grabs board in solution.txt and verifies the solution # if __name__ == "__main__": # with open('solution.txt', 'r') as f: # board = [] # for line in f.readlines(): # str_row = list(line) # row_len = len(str_row) # row = [] # for i in range(row_len): # if str_row[i].isdigit(): # row.append(int(str_row[i])) # board.append(row) # decision = check_solution(board) # print("decision:", decision)
ffda8b9cf42dfc4167698f5de1e4bc69c3db92fd
kariesta/Euler
/p30.py
577
3.859375
4
''' Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 14 + 64 + 34 + 44 8208 = 84 + 24 + 04 + 84 9474 = 94 + 44 + 74 + 44 As 1 = 14 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. ''' x = 0 for a in range(10): print(a, a*(9**5)) for a in range(33,999999): ars = str(a) s = sum([int(r)**5 for r in ars]) if s==a: x+=a print(a) print("rr ",x)