blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
f136d041f32b05814a195e2b7d2e4924ee4cd1ff
dloeffen/datamining-practicals
/solutions/linear_models/code/utils.py
514
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 21 14:09:10 2020 @author: dirk """ import numpy as np def sum_squared_errors(y1, y2): # Implement sum of squared errors diff = y1 - y2 square = np.multiply(diff, diff) return np.sum(square) def mean_squared_error(y1, y2): # Implement mean squared error return sum_squared_errors(y1,y2)/len(y1) def root_mean_squared_error(y1, y2): # Implement root squared error return np.sqrt(mean_squared_error(y1,y2))
683354238d01811f3191a4ab9ee251c7c0131cf8
iamshubhamsalunkhe/Python
/funct_with_mult_argue/funct_with_mult_arguement.py
303
3.953125
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 14:48:40 2019 @author: Shubham """ #program to create a func with multiple arguement def newfunction(a,b,c,d): result = a*b-c+d print("The answer is ",result) newfunction(1,2,3,4) newfunction(a=1,b=2,c=3,d=5) newfunction(c=1,d,3,a=2,b=6)
acb5f38b59568f0e556fba6f043c24061a8099f8
YiDomiChen/leetcodesolution
/python/BFS/graph_valid_tree.py
1,056
3.75
4
from collections import deque class Solution(object): def validTree(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: bool """ if n == 0: return True if len(edges) != n - 1: return False graph = self.configAdjacency(n, edges) queue = deque([0]) nodes_set = set() while queue: node = queue.popleft() for neighbor in graph.get(node): if not neighbor in nodes_set: continue nodes_set.add(neighbor) queue.append(neighbor) return n == len(nodes_set) def configAdjacency(self, n, edges): graph = {} for i in range(n): graph[i] = set() for i in range(len(edges)): graph[edges[i][0]].add(edges[i][1]) graph[edges[i][1]].add(edges[i][0]) return graph def main(): if __name__=="__main__": main()
e4e980401e4628d11c76baf2eddfdcf0b0a0629a
prathamesh201999/python1
/Selection_sort.py
271
3.84375
4
def sort(list): for i in range(5): min = i for j in range(i,6): if list[j] < list[min]: min = j temp = list[i] list[i] = list[min] list[min] = temp list = [6,7,4,90,34,56] sort(list) print(list)
b23aeb9bf2fcee9be669403a3495ab14524fc704
danityang/PythonBase
/Tuple.py
1,279
3.578125
4
# coding=utf-8 # TODO Python元组 # 元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可 tup1 = ('Google', 'Runoob', 1997, 2000) tup2 = (1, 2, 3, 4, 5) tup3 = "a", "b", "c", "d" # 创建空元组 tup = () # 当元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用: tup4 = (50) print type(tup4) tup5 = (50,) print type(tup5) # TODO 访问元组 print tup1[0] print tup2[2] # TODO 修改元组 # 元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例: tup1 = (12, 34.56) tup2 = ('abc', 'xyz') tup3 = tup1 + tup2 print tup3 print # TODO 删除元组 # 元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例: tup = ('Google', 'Runoob', 1997, 2000) print (tup) del tup; print ("删除后的元组 tup : ") print tup # TODO 元组运算符 ''' len((1, 2, 3)) 3 计算元素个数 (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 连接 ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') 复制 3 in (1, 2, 3) True 元素是否存在 for x in (1, 2, 3): print x, 1 2 3 迭代 '''
03a45c53c2ed1f35e8a62623ac512e26c7dfe53b
matheuszei/Python_DesafiosCursoemvideo
/0082_desafio.py
667
3.890625
4
#Crie um programa que vai ler vários números e colocar em uma lista. #Depois disso, crie duas listas extras que vão conter apenas os valores pares e impares digitados. #Ao final, mostre o conteúdo das três listas geradas num = [] par = [] impar = [] while True: num.append(int(input('Digite um valor: '))) resp = input('Deseja continuar? [S/N] ').upper() if resp == 'N': break for i, v in enumerate(num): if v % 2 == 0: par.append(v) elif v % 2 == 1: impar.append(v) print('-=' * 30) print(f'A lista completa é {num}') print(f'A lista de pares é {par}') print(f'A lista de impares é {impar}')
665c843e5ea4b46187f73093633901757f731477
zgljl2012/web-search-engine-ui
/index.py
4,350
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ UI - a simple web search engine. The goal is to index an infinite list of URLs (web pages), and then be able to quickly search relevant URLs against a query. See https://github.com/AnthonySigogne/web-search-engine for more information. """ __author__ = "Anthony Sigogne" __copyright__ = "Copyright 2017, Byprog" __email__ = "[email protected]" __license__ = "MIT" __version__ = "1.0" import os import requests from urllib import parse from flask import Flask, request, jsonify, render_template # init flask app and env variables app = Flask(__name__) host = os.getenv("HOST") port = os.getenv("PORT") @app.route("/", methods=['GET']) def search(): """ URL : / Query engine to find a list of relevant URLs. Method : POST or GET (no query) Form data : - query : the search query - hits : the number of hits returned by query - start : the start of hits Return a template view with the list of relevant URLs. """ # GET data query = request.args.get("query", None) start = request.args.get("start", 0, type=int) hits = request.args.get("hits", 10, type=int) if start < 0 or hits < 0 : return "Error, start or hits cannot be negative numbers" if query : # query search engine try : host="127.0.0.1" port=8000 r = requests.post('http://%s:%s/search'%(host, port), data = { 'query':query, 'hits':hits, 'start':start }) except : return "Error, check your installation" # get data and compute range of results pages data = r.json() i = int(start/hits) maxi = 1+int(data["total"]/hits) range_pages = range(i-5,i+5 if i+5 < maxi else maxi) if i >= 6 else range(0,maxi if maxi < 10 else 10) # show the list of matching results return render_template('spatial/index.html', query=query, response_time=r.elapsed.total_seconds(), total=data["total"], hits=hits, start=start, range_pages=range_pages, results=data["results"], page=i, maxpage=maxi-1) # return homepage (no query) return render_template('spatial/index.html') @app.route("/reference", methods=['POST']) def reference(): """ URL : /reference Request the referencing of a website. Method : POST Form data : - url : url to website - email : contact email Return homepage. """ # POST data data = dict((key, request.form.get(key)) for key in request.form.keys()) if not data.get("url", False) or not data.get("email", False) : return "Vous n'avez pas renseigné l'URL ou votre email." # query search engine try : r = requests.post('http://%s:%s/reference'%(host, port), data = { 'url':data["url"], 'email':data["email"] }) except : return "Une erreur s'est produite, veuillez réessayer ultérieurement" return "Votre demande a bien été prise en compte et sera traitée dans les meilleurs délais." # -- JINJA CUSTOM FILTERS -- # @app.template_filter('truncate_title') def truncate_title(title): """ Truncate title to fit in result format. """ return title if len(title) <= 70 else title[:70]+"..." @app.template_filter('truncate_description') def truncate_description(description): """ Truncate description to fit in result format. """ if len(description) <= 160 : return description cut_desc = "" character_counter = 0 for i, letter in enumerate(description) : character_counter += 1 if character_counter > 160 : if letter == ' ' : return cut_desc+"..." else : return cut_desc.rsplit(' ',1)[0]+"..." cut_desc += description[i] return cut_desc @app.template_filter('truncate_url') def truncate_url(url): """ Truncate url to fit in result format. """ url = parse.unquote(url) if len(url) <= 60 : return url url = url[:-1] if url.endswith("/") else url url = url.split("//",1)[1].split("/") url = "%s/.../%s"%(url[0],url[-1]) return url[:60]+"..." if len(url) > 60 else url
dfcc2907faa42792a8b89ccd35598e42b3a3f8fd
Hermotimos/Learning
/lambda.py
2,189
4.75
5
"""" This file is for learning and exercise purposes. Topics: - simple lambda syntax - examples: map(), filter(), reduce() Sources: https://www.python.org/dev/peps/pep-0008/ https://dbader.org/blog/python-lambda-functions https://treyhunner.com/2018/09/stop-writing-lambda-expressions/ """ # SYNTAX: # lambda arguments: expression double = lambda x: x*2 square = lambda x: x**2 next_even = lambda x: x + 1 if x % 2 == 1 else x + 2 print(double(4)) print(square(4)) print(next_even(3)) print(next_even(6)) print() my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] example = lambda x: [e for e in x if e % 2 == 0] print(example(my_list)) print((lambda a, b: a + b)(111, 111)) print('##################################################') # as per PEP8 lambdas shouldn't be used in simple assignments as above # lambdas can be used inside other functions like below # filter() takes function and iterable as args # returns elements of list that pass the criteria of the function my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] filtered = list(filter(lambda x: (x % 2 == 0), my_list)) print(filtered) filtered = list(filter(lambda x: x % 2 == 0, my_list)) print(filtered) for num in filter(lambda x: x % 2 == 1, range(0, 10)): print(num, '', end='') print('\n##################################################') # map() takes function and iterable as args # returns all elements of iterable modified by the function my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] mapped = list(map(lambda x: x + 1, my_list)) print(mapped) mapped = list(map(lambda x: x + 1 if x % 2 == 0 else x, my_list)) print(mapped) print('\n##################################################') # reduce() takes function and iterable as args # performs rolling computation (function) on sequential pairs of elements from the iterable from functools import reduce summed = reduce(lambda a, b: a + b, [1, 2, 3, 4]) print(summed) my_tuple = (1, 2, 3, 4) summed = reduce(lambda a, b: a + b, my_tuple) print(summed) my_letters = ('a', 'b', 'c', 'c', 'c', 'c', 'd', 'a', 'g', 'b', 'b', 'b') concatenated = reduce(lambda a, b: a + b, my_letters) print(concatenated)
ffc304c25ab19b842027640e8bfbf3bad90ca907
Miguel-Tirado/Python
/python_work/Chapter_4/pizza.py
301
3.78125
4
pizzas = ['Hawaian','Perporni','Stuffed crust'] for pizza in pizzas: print(f"I love {pizza} pizza.") print(f"\nI love {pizzas[0]} for the pineapples.") print(f"I love {pizzas[1]} for the classic taste.") print(f"I love {pizzas[2]} for the chessy crust.") print("I just really like pizza, dont I.")
0209ef49786f6f802555933f3a13c6fb281149a8
aalhsn/python
/loops_task.py
977
3.890625
4
import time import datetime cashier_list = [] name ='' quantity = 0 price = 0.0 print(""" XYZ Point of Sales (POS) DATE | TIME {} by Abdullah Alhasan! """.format(datetime.datetime.now())) while True: name= input("Type Item's Name or 'done' If You Finished..>") if name == 'done': break price = input("Type in Item's Price..>") quantity = input("Type Quantity..>") cashier_list.append({'name': name, 'price': price, 'quantity': quantity}) print(""" ========================= ........RECEIPT.......... ========================= """) time.sleep(1) total = 0 for item in cashier_list: total_per_item = int(item['quantity']) * float(item['price']) print("{} (Price per item: {}) - Quantity: ({}) - Total: {}KWD".format(item['name'].upper(),item['price'],item['quantity'],round(total_per_item,3))) total += total_per_item print(""" ========================= GRAND TOTAL: {} KWD """.format(round(total,3)))
7c5abeb358b5790cff1bdfbf801c5093fa286443
SavinKumar/Python_lib
/Original files/Library.py
34,819
3.734375
4
from tkinter import * import sqlite3 import getpass from functools import partial from datetime import date conn = sqlite3.connect('orgdb.sqlite') cur = conn.cursor() def passw(): pa=getpass.getpass() passwo='seKde7sSG' print('Entered password is of ',len(pa),' characters, To continue press Enter otherwise Enter the passwords again') s=input() while s: print('Enter the correct password again: ') pa=getpass.getpass() print('Entered password is of ',len(pa),' characters, To continue press Enter otherwise Enter the passwords again') s=input() if pa==passwo: return 1; else: return 0; def p_exit(): exit() def p_add1(): add1=Tk() add1.title("Add records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) cur.execute('''INSERT OR IGNORE INTO Records('Roll_no') VALUES (?)''',(i,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = E_2.get()+" Added") L_.place(x=10,y=150) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number to add: ") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Add",command = p_ad) B_1.place(x=350,y=100) add1.mainloop() def p_addrng(): add1=Tk() add1.title("Add records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) j=int(E_3.get()) for k in range(i,j+1): cur.execute('''INSERT OR IGNORE INTO Records('Roll_no') VALUES (?)''',(k,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = str(j-i+1)+" Recods Added") L_.place(x=10,y=250) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Initial Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Final Roll number") L2.place(x=50,y=100) E_3 = Entry(add1,font=16,textvariable = c) E_3.place(x=410,y=100) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Add",command = p_ad) B_1.place(x=350,y=190) add1.mainloop() def p_del1(): add1=Tk() add1.title("Delete records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) cur.execute('''DELETE FROM Records where Roll_no = ?''',(i,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = E_2.get()+" Deleted") L_.place(x=10,y=150) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number to delete: ") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Delete",command = p_ad) B_1.place(x=350,y=100) add1.mainloop() def p_delrng(): add1=Tk() add1.title("Delete records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) j=int(E_3.get()) for k in range(i,j+1): cur.execute('''DELETE FROM Records where Roll_no = ?''',(k,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = str(j-i+1)+" Recods Deleted") L_.place(x=10,y=250) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Initial Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Final Roll number") L2.place(x=50,y=100) E_3 = Entry(add1,font=16,textvariable = c) E_3.place(x=410,y=100) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Delete",command = p_ad) B_1.place(x=350,y=190) add1.mainloop() def p_issue(): add1=Tk() add1.title("Issue Books") add1.geometry("900x900") def p_book(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] break mpty=0 if book1==0: mpty+=1 if book2==0: mpty+=1 if book3==0: mpty+=1 if book4==0: mpty+=1 if book5==0: mpty+=1 tt='You can issue '+str(mpty)+' number of books only as per the rule.' def p_lock(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] break b1=E_3.get() b2=E_4.get() b3=E_5.get() b4=E_6.get() b5=E_7.get() aaa=0 if b1=="": aaa+=1 if b2=="": aaa+=1 if b3=="": aaa+=1 if b4=="": aaa+=1 if b5=="": aaa+=1 L8 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Books for issue= "+str(5-aaa)) L8.place(x=50,y=510) aaa=5-aaa lst=[] if aaa==5: lst.append(b1) lst.append(b2) lst.append(b3) lst.append(b4) lst.append(b5) elif aaa==4: lst.append(b1) lst.append(b2) lst.append(b3) lst.append(b4) elif aaa==3: lst.append(b1) lst.append(b2) lst.append(b3) elif aaa==2: lst.append(b1) lst.append(b2) elif aaa==1: lst.append(b1) for j in range(len(lst)): aaa-=1 if book1==0: book1=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book1=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI1=? where Roll_no=?''',(di,i)) conn.commit() elif book2==0: book2=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book2=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI2=? where Roll_no=?''',(di,i)) conn.commit() elif book3==0: book3=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book3=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI3=? where Roll_no=?''',(di,i)) conn.commit() elif book4==0: book4=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book4=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI4=? where Roll_no=?''',(di,i)) conn.commit() elif book5==0: book5=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book5=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI5=? where Roll_no=?''',(di,i)) conn.commit() L9 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Books issued= "+str(len(lst))) L9.place(x=50,y=570) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = tt) L2.place(x=50,y=180) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book1") L3.place(x=50,y=260) E_3 = Entry(add1,font=16) E_3.place(x=410,y=260) L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book2") L4.place(x=50,y=310) E_4 = Entry(add1,font=16) E_4.place(x=410,y=310) L5 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book3") L5.place(x=50,y=360) E_5 = Entry(add1,font=16) E_5.place(x=410,y=360) L6 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book4") L6.place(x=50,y=410) E_6 = Entry(add1,font=16) E_6.place(x=410,y=410) L7 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book5") L7.place(x=50,y=460) E_7 = Entry(add1,font=16) E_7.place(x=410,y=460) B_2 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Book",command = p_lock) B_2.place(x=350,y=510) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=10,bd=5,bg='Yellow',font=16, text = "Continue",command = p_book) B_1.place(x=350,y=100) def p_delete(): add1=Tk() add1.title("Return book") add1.geometry("900x900") def p_del(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] break strr="" if book1!=0: strr=strr+str(book1)+',' if book2!=0: strr=strr+str(book2)+',' if book3!=0: strr=strr+str(book3)+',' if book4!=0: strr=strr+str(book4)+',' if book5!=0: strr=strr+str(book5) strr='You have these books issued '+strr def p_cal(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] d1=rec[6] d2=rec[7] d3=rec[8] d4=rec[9] d5=rec[10] break b1=E_3.get() b2=E_4.get() b3=E_5.get() b4=E_6.get() b5=E_7.get() aaa=0 if b1=="": aaa+=1 if b2=="": aaa+=1 if b3=="": aaa+=1 if b4=="": aaa+=1 if b5=="": aaa+=1 aaa=5-aaa lst=[] if aaa==5: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) lst.append(int(b5)) elif aaa==4: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) elif aaa==3: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) elif aaa==2: lst.append(int(b1)) lst.append(int(b2)) elif aaa==1: lst.append(int(b1)) dys_free=0 total=0 for j in range(len(lst)): if book1==lst[j]: r_dat=date.today() a=int(d1[6:]) b=int(d1[3:5]) c=int(d1[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book2==lst[j]: r_dat=date.today() a=int(d2[6:]) b=int(d2[3:5]) c=int(d2[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book3==lst[j]: r_dat=date.today() a=int(d3[6:]) b=int(d3[3:5]) c=int(d3[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book4==lst[j]: r_dat=date.today() a=int(d4[6:]) b=int(d4[3:5]) c=int(d4[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book5==lst[j]: r_dat=date.today() a=int(d5[6:]) b=int(d5[3:5]) c=int(d5[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys def p_conf(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] d1=rec[6] d2=rec[7] d3=rec[8] d4=rec[9] d5=rec[10] break b1=E_3.get() b2=E_4.get() b3=E_5.get() b4=E_6.get() b5=E_7.get() aaa=0 if b1=="": aaa+=1 if b2=="": aaa+=1 if b3=="": aaa+=1 if b4=="": aaa+=1 if b5=="": aaa+=1 aaa=5-aaa lst=[] if aaa==5: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) lst.append(int(b5)) elif aaa==4: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) elif aaa==3: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) elif aaa==2: lst.append(int(b1)) lst.append(int(b2)) elif aaa==1: lst.append(int(b1)) for j in range(len(lst)): if book1==lst[j]: conn.execute('''UPDATE Records set 'book1'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI1'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book2==lst[j]: conn.execute('''UPDATE Records set 'book2'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI2'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book3==lst[j]: conn.execute('''UPDATE Records set 'book3'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI3'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book4==lst[j]: conn.execute('''UPDATE Records set 'book4'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI4'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book5==lst[j]: conn.execute('''UPDATE Records set 'book5'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI5'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() L9 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "done") L9.place(x=350,y=720) L8 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Total fine: "+str(total)) L8.place(x=50,y=580) B_2 = Button(add1,activebackground='Green',activeforeground='Red',width=7,bd=5,bg='Yellow',font=16, text = "Confirm",command = p_conf) B_2.place(x=350,y=650) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = strr) L2.place(x=50,y=180) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book1") L3.place(x=50,y=260) E_3 = Entry(add1,font=16) E_3.place(x=410,y=260) L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book2") L4.place(x=50,y=310) E_4 = Entry(add1,font=16) E_4.place(x=410,y=310) L5 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book3") L5.place(x=50,y=360) E_5 = Entry(add1,font=16) E_5.place(x=410,y=360) L6 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book4") L6.place(x=50,y=410) E_6 = Entry(add1,font=16) E_6.place(x=410,y=410) L7 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book5") L7.place(x=50,y=460) E_7 = Entry(add1,font=16) E_7.place(x=410,y=460) B_2 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=7,bg='Yellow',font=16, text = "Return",command = p_cal) B_2.place(x=350,y=510) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=10,bd=5,bg='Yellow',font=16, text = "Continue",command = p_del) B_1.place(x=350,y=100) def p_mail(): add1=Tk() add1.title("Mail to students") add1.geometry("700x300") import smtplib row =conn.execute('''select * from Records''') lst1=[] for rec in row: mpty=0 book1=rec[1] d1=rec[6] book2=rec[2] d2=rec[7] book3=rec[3] d3=rec[8] book4=rec[4] d4=rec[9] book5=rec[5] d5=rec[10] if book1!=0: mpty+=1 if book2!=0: mpty+=1 if book3!=0: mpty+=1 if book4!=0: mpty+=1 if book5!=0: mpty+=1 total=0 free_days=0 for i in range(mpty): if book1 !=0: r_dat=date.today() a=int(d1[6:]) b=int(d1[3:5]) c=int(d1[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book2 !=0: r_dat=date.today() a=int(d2[6:]) b=int(d2[3:5]) c=int(d2[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book3 !=0: r_dat=date.today() a=int(d3[6:]) b=int(d3[3:5]) c=int(d3[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book4 !=0: r_dat=date.today() a=int(d4[6:]) b=int(d4[3:5]) c=int(d4[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book5 == lst1[i]: r_dat=date.today() a=int(d5[6:]) b=int(d5[3:5]) c=int(d5[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys if total!=0: lst1.append(rec[0]) lst2=[] for rrol in lst1: row =conn.execute('''select * from RecordsEmail where Roll_no=?''',(rrol,)) for rec in row: eme=rec[1] lst2.append(eme) lstt=lst2 L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text =str(len(lstt))+" are number of students whose fine started.") L1.place(x=10,y=10) sender = "[email protected]" recipient = lstt password = getpass.getpass() # Your SMTP password for Gmail subject = "UIET KUK LIBRARY" text = ''' Dear student, This is gentle remainder from uiet kuk library that we have started fine. This is automatic mailing so don't reply. This is only for uiet kuk student. If you are not student so please ignore it. ''' smtp_server = smtplib.SMTP_SSL("smtp.gmail.com", 465) smtp_server.login(sender, password) message = "Subject: {}\n\n{}".format(subject, text) if len(lstt)>0: smtp_server.sendmail(sender, recipient, message) smtp_server.close() L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text ="Done mailed.") L2.place(x=10,y=110) def p_details(): def p_show(): rol=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(rol,)) row1=conn.execute('''select * from RecordsEmail where Roll_no = ?''',(rol,)) for rec in row1: L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Email of student: "+rec[1]) L2.place(x=50,y=160) break lst1=[] total=0 mpty=0 for rec in row: book1=rec[1] d1=rec[6] book2=rec[2] d2=rec[7] book3=rec[3] d3=rec[8] book4=rec[4] d4=rec[9] book5=rec[5] d5=rec[10] break if book1!=0: mpty+=1 lst1.append(book1) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+str(book1)+" Issue Date: "+ d1) L3.place(x=50,y=220) if book2!=0: mpty+=1 lst1.append(book2) L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+ str(book2)+" Issue Date: "+ d2) L4.place(x=50,y=280) if book3!=0: mpty+=1 lst1.append(book3) L5 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+str(book3)+" Issue Date: "+ d3) L5.place(x=50,y=340) if book4!=0: mpty+=1 lst1.append(book4) L6 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+str(book4)+" Issue Date: "+ d4) L6.place(x=50,y=400) if book5!=0: mpty+=1 lst1.append(book5) L7 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text ="Book Number= "+ str(book5)+" Issue Date: "+ d5) L7.place(x=50,y=460) days_free=0 for i in range(len(lst1)): if book1 == lst1[i]: r_dat=date.today() a=int(d1[6:]) b=int(d1[3:5]) c=int(d1[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book2 == lst1[i]: r_dat=date.today() a=int(d2[6:]) b=int(d2[3:5]) c=int(d2[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book3 == lst1[i]: r_dat=date.today() a=int(d3[6:]) b=int(d3[3:5]) c=int(d3[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book4 == lst1[i]: r_dat=date.today() a=int(d4[6:]) b=int(d4[3:5]) c=int(d4[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book5 == lst1[i]: r_dat=date.today() a=int(d5[6:]) b=int(d5[3:5]) c=int(d5[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys L8 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Total fine= "+str(total)) L8.place(x=50,y=520) add1=Tk() add1.title("Show Details") add1.geometry("900x900") L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Show",command = p_show) B_1.place(x=350,y=100) add1.mainloop() def p_mail_change(): add1=Tk() add1.title("Edit Details") add1.geometry("900x900") def p_changeg(): i=int(E_2.get()) row1=conn.execute('''select * from RecordsEmail where Roll_no = ?''',(i,)) ssa='' for rec in row1: ssa='Email for rollno '+str(i)+' is '+rec[1] def p_change_conf(): rol=int(E_2.get()) newEmail=E_3.get() conn.execute('''UPDATE RecordsEmail set 'Email'=? where Roll_no=?''',(newEmail,rol,)) conn.commit() L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = 'Done') L4.place(x=150,y=360) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = ssa) L2.place(x=50,y=160) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = 'New Email: ') L3.place(x=50,y=220) E_3 = Entry(add1,font=16) E_3.place(x=410,y=220) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=8,bd=5,bg='Yellow',font=16, text = "Change",command = p_change_conf) B_1.place(x=350,y=300) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Edit",command = p_changeg) B_1.place(x=350,y=100) add1.mainloop() if not(passw()): exit() root = Tk() root.title("Library_Management") root.geometry("900x900") a='''UNIVERSITY INSTITUTE OF ENGINEERING AND TECHNOLOGY KURUKSHETRA UNIVERSITY KURUKSHETRA''' c= StringVar() b = StringVar() rol = StringVar() L = Label(root,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text =a) L.place(x=150,y=10) b1="Enroll 1 or more student(s) having different roll numbers" B_1 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b1,command = p_add1) B_1.place(x=150,y=100) b2="Enroll students in a range" B_2 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b2, command=p_addrng) B_2.place(x=150,y=160) b3 = "Delete 1 or more students(s) having different roll numbers" B_3 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b3,command = p_del1) B_3.place(x=150,y=220) b4="Delete students in a range" B_4 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b4, command=p_delrng) B_4.place(x=150,y=280) b5="Issue book(s) for a roll number" B_5 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b5, command=p_issue) B_5.place(x=150,y=340) b6="Return book(s) by any student using roll number" B_6 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b6, command=p_delete) B_6.place(x=150,y=400) b7="To get mail those students whose fine already started" B_7 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b7, command= p_mail) B_7.place(x=150,y=460) b8="To get all details related to any student" B_8 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b8,command= p_details) B_8.place(x=150,y=520) b9="Edit the details i.e. change Email of any student" B_9 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b9, command=p_mail_change) B_9.place(x=150,y=580) B_10 = Button(root,activebackground='Green',activeforeground='Red',width=10,bd=5,bg='Yellow',font=16, text ="Exit",command = p_exit) B_10.place(x=400,y=640) root.mainloop()
93857396636c163579b3e6834b6d3300b64b38db
NTHU-CS50-2020/week7
/leo/house/import.py
712
3.75
4
from sys import argv, exit from cs50 import SQL import csv import collections db = SQL("sqlite:///students.db") if (len(argv) != 2): exit("Usage: python import.py data.csv sequence.txt") with open(argv[1] , "r")as file: reader = csv.DictReader(file) for row in reader: name = row["name"].split() if(len(name) == 3): first = name[0] middle = name[1] last = name[2] elif(len(name) == 2): first = name[0] middle = None last = name[1] db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", first, middle, last, row["house"], row["birth"])
bc8db987a7cef010ba404cbe2088453d512881be
MRitter95/AFC-code
/Data_Analysis/Data_Processing/preAnalysis/resetDateModified.py
4,215
3.828125
4
import os import sys import time # We take advantage of the "Date modified" labels on our data files and folders # to organize things; specifically, we use them to sort the scope traces into # the appropriate folders. # Sometimes mistakes are made, and the dates modified change in such a way that # the folders are no longer correctly ordered by that label. This program adds # and removes a dummy file to each subfolder in such a way that they are once # again correctly ordered by their dates modified. # Here, I have taken advantage of prior knowledge that we took two data sets, # the first (second) in order of ascending (descending) frequency. In general, # the order may not be so obvious. If that's the case, the most recent (for # example) date modified of a file inside each folder could be used to # determine the correct order. loc= input('Which directory are you trying to reorder?') os.chdir(loc) order= input('Order files by ascending or descending frequency?(A/D)') if order!='A' and order!='D': print('Choose one of the two options. For other sorting orders, you\'ll have to modify the program.') sys.exit(0) allFolders= [] for root,dirs,files in os.walk(loc): # print(desiredOrder) for folder in dirs: allFolders.append(folder) print('as randomly found (probably alphabetically): ',allFolders) allFolders.sort(key=os.path.getmtime) originalOrder= allFolders.copy() print('sorted by date modified: ',originalOrder) if order=='A': allFolders.sort(key=int) else: allFolders.sort(reverse=True,key=int) desiredOrder= allFolders.copy() print('as desired: ',desiredOrder) if originalOrder==desiredOrder: print('Nothing to do here.') sys.exit(0) else: print('We\'ll have to reorder things.') for j in range(len(allFolders)): os.chdir(os.path.join(loc,allFolders[j])) print(os.getcwd()) f= open('dummy.txt','w') f.close() os.remove('dummy.txt') # note that this happens so fast that Windows Explorer apparently can't tell # that the folders are ordered at all: switching to ascending vs. descending # order of "date modified" has no effect, and it just orders the folders # numerically. This is why we do extra tests within this program to make sure # that Python can distinguish the dates modified (if it doesn't, the program # will say so at the end). If there are problems, include commented-out time # delay below, and be prepared to wait a while. time.sleep(0.1) # NOTE: there *were* problems. at the last step, the program finds the files # ordered correctly by date modified and claims success; but if the program # is run again, the the files are initially ordered wrong. adding the small # delay above fixed the problem. os.chdir(loc) allFolders.sort(key=os.path.getmtime) print('sorted by date modified: ',allFolders) if allFolders==desiredOrder: print('Success!') else: print('Reordering failed. Consider adding a time delay.') ############################################################################### # THE END #folders= filter(os.path.isdir,os.listdir(target)) #folders= [f for f in folders] ##folderList= [os.path.join(target,f) for f in folders] # #print("these are the folders",folders) # #n=0 #allDirs= [] #for f in folders: # os.chdir(os.path.join(target,f)) # subFolders= filter(os.path.isdir,os.listdir()) ## subFolders= [sf for sf in subFolders] ## print("these are the subfolders",subFolders) # # allDirs= allDirs+[os.path.join(os.getcwd(),sf) for sf in subFolders] # n+=1 # print(n) # #allDirs.sort(key=os.path.getmtime) # #print(len(allDirs),allDirs) #folders= os.listdir() #folders.sort(key=os.path.getmtime) #print(folders) #print(len(folders)) #print([x[0] for x in os.walk(target)]) #print(next(os.walk(target))[1][0]) # #print(next(os.walk(target))[1][1]) # #print(next(os.walk(target))[1][2]) # #os.chdir(os.path.join(target,next(os.walk(target))[1][0])) # #print(next(os.walk(os.getcwd()))[1]) # #os.chdir(os.path.join(target,next(os.walk(target))[1][1])) # #print(next(os.walk(os.getcwd()))[1]) # #os.chdir(os.path.join(target,next(os.walk(target))[1][2])) # #print(next(os.walk(os.getcwd()))[1])
5657210a4708bd372c858efba698a3bd82bdadb7
faizan1402/OPENCV
/blurimage.py
840
3.96875
4
# Bluring the imgage import cv2 import numpy as np img =cv2.imread("lena.png") cv2.imshow("Original Image",img) cv2.waitKey(0) #How to blur the imgblur # useing the Kernel function through img is blur Kernel matrix value is increase then img is more times #Syntax- #Kernel_dimension=np.ones((size of matrix to pass ),np.float 32)/size of matrix devide kernel_3x3 =np.ones((3,3),np.float32)/9 # We use the cv2.filter 2D to convolve the kernel with an image #filter function used the 2D # cv2.filter2D(img,deft,kernel function) blurred =cv2.filter2D(img,-1,kernel_3x3) #read the blurred img cv2.imshow('3x3 Kernel Blurring',blurred) cv2.waitKey(0) kernel_10x10 =np.ones((10,10),np.float32)/100 blurred =cv2.filter2D(img,-1,kernel_10x10) cv2.imshow("10x10 kernel Blurring",blurred) cv2.waitKey(0) cv2.destroyAllWindows()
840b4dddca04d25d204d8fd2bc469b5b5b148563
DrakeVorndran/Tweet-Generator
/Code/zoo.py
1,018
4.03125
4
from pprint import pprint def get_words(filename): """open the file and return a list of all words in it""" all_words_list = [] with open(filename) as file: for line in file: words_list = line.split() for word in words_list: all_words_list.append(word) return all_words_list def count_animals(animals_list): '''counts all of the occurences of unique words in a list and returns that data structure''' animal_counts = {} for animal_name in animals_list: if animal_name in animal_counts: animal_counts[animal_name] += 1 else: animal_counts[animal_name] = 1 return animal_counts def print_table(animal_counts): """Prints out a table of animals and their counts""" print("Ainmal | Count") print('----------------') for animal_name in animal_counts: count = str(animal_counts[animal_name]) print(animal_name + " | " + count) if __name__ == "__main__": words = get_words('animals.txt') counts = count_animals(words) print_table(counts)
1253b9d43e4b4249e502ac2dbc121e15119ec4bb
GregoryMNeal/Digital-Crafts-Class-Exercises
/Python/Function_Exercises/sin.py
298
3.5625
4
# Imports import math import matplotlib.pyplot as plot # Functions def f(x): s = math.sin(x) return s def plotit(): xs = list(range(-5, 6)) ys = [] for x in xs: ys.append(f(x)) plot.plot(xs, ys) plot.show() # Main if __name__ == "__main__": plotit()
36cfe108935709d137de45260e4eb980e6aa05b8
vishnu11121998/VISHNU-PRASATH
/july4/qu.py
1,020
4.09375
4
q = {"How many days do we have in a week?":["a.7","b.8","c.6","a"],"How many days are there in a year":["a.366","b.365","c.364","b"], "How many colors are there in a rainbow?":["a.9","b.7","c.6","b"], "Which animal is known as the ‘Ship of the Desert?":["a.camel","b.Thorny Devil","c.Chile","a"],"How many letters are there in the English alphabet?":["a.27","b.25","c.26","c"],"How many consonants are there in the English alphabet?":["a.21","b.22","c.23","a"]," How many sides are there in a triangle?":["a.4","b.5","c.3","c"],"In which direction does the sun rise?":["a.north","b.east","c.south","b"],"Which month of the year has the least number of days?":["a.february","b.march","c.june","a"],"We smell with our?":["a.nose","b.ear","c.eyes","a"] } q = list(q.items()) q = dict(q) count = 0 for i in q.keys(): print(i) for j in range(0,len(q[i])-1,1): print(q[i][j]) ans = input("ur choice is : ") if ans == q[i][len(q[i])-1]: count +=1 print("Total Score:",count)
643f96cd09a81880f20456183dab9ee032b1d2ac
kaliRegenold/advent2020
/2.py
1,318
3.796875
4
# Author: Kali Regenold def fun1(pass_list): valid_cnt = 0 for rule_pass in pass_list: # Separate the rule and password rule, password = rule_pass.split(':') # Count occurences of rule letter in password char_cnt = password.count(rule[-1]) # Increase valid count if number of rule letter occurences is within rule bounds valid_cnt += (char_cnt >= int(rule.split('-')[0]) and char_cnt <= int(rule.split('-')[1][0:-2])) print(valid_cnt) def fun2(pass_list): valid_cnt = 0 for rule_pass in pass_list: # Separate the rule and password rule, password = rule_pass.split(':') # Remove whitespace from password password = password.strip() # Extract valid rule letter positions from rule pos1 = int(rule.split('-')[0]) - 1 pos2 = int(rule.split('-')[1][0:-2]) - 1 # Increase valid count if rule letter in position 1 XOR rule letter in position 2 valid_cnt += ((password[pos1] == rule[-1]) ^ (password[pos2] == rule[-1])) print(valid_cnt) if __name__ == "__main__": # Read rule and password into a list separated by newline with open('2.in', 'r') as f: pass_list = f.readlines() pass_list = [x.strip() for x in pass_list] fun1(pass_list) fun2(pass_list)
14c35d7a8112d067bee8d8550211b1761b512301
adithya-r3/recycle-box
/init_db.py
328
3.53125
4
import sqlite3 connection = sqlite3.connect('database.db') with open('user.sql') as f: connection.executescript(f.read()) cur = connection.cursor() cur.execute("INSERT INTO user(name, email, username, password) VALUES (?, ?, ?, ?)", ('Keshav', '[email protected]', 'keshra12', 'krave')) connection.commit()
1634af2095da9383665dee7a2fa0000ff7c07285
madhur2k9/Expense-Manager
/Models/User.py
994
3.765625
4
class User: #Constructor for user class def __init__(self, id, email, password, name, date_created, last_login_date, current_balance): self._id = id self._email = email self._password = password self._name = name self._date_created = date_created self._last_login_date = last_login_date self._current_balance = current_balance # Setter methods def set_name(self, name): self._name = name def set_current_balance(self, balance): self._current_balance = balance def set_password(self, password): self._password = password def get_id(self): return self._id def get_email(self): return self._email def get_name(self): return self._name def get_date_created(self): return self._date_created def get_last_login_date(self): return self._last_login_date def get_current_balance(self): return self._current_balance
2bc5f4069a10f7591262503265bd96d27d432d40
flaviocardoso/uri204719
/feitos/menoreposicao.py
244
3.75
4
#!/usr/bin/python3 #menoreposicao.py 1180 N = int(input()) lista = list(map(int, input().split())) P, M = 0, lista[0] for i in range(1, N): if(lista[i] < M): P, M = i, lista[i] print("Menor valor: {0}\nPosicao: {1}".format(M, P))
5882e162efc5c3e0cbb704c61da496d8abe6eac4
jtlai0921/Python-
/ex07/test07_7.py
103
3.625
4
def F(a) : if (a < 0) : return 1 else : return F(a-2) + F(a-3) print(F(7))
ae4bc9f803e0842c860ccd684a9b2a19b08ad596
amoddhopavkar2/LeetCode-October-Challenge
/29_10.py
635
3.65625
4
# Maximize Distance to Closest Person class Solution: def maxDistToClosest(self, seats: List[int]) -> int: distances = [float("inf")] * len(seats) max_distance = 0 index = -1 for i in range(len(seats)): if seats[i] == 0: if index == -1: continue distances[i] = i - index else: index = i index = -1 for i in range(len(seats) - 1, -1, -1): if seats[i] == 0: if index == -1: continue distances[i] = min(distances[i], index - i) else: index = i for distance in distances: if distance != float("inf"): max_distance = max(max_distance, distance) return max_distance
7bff4cd8a3b1abdbf182637dcee2cb9ad597481c
soyun20/Python
/파일 라인수세기.py
84
3.5
4
a=open('hello.txt') count=0 for line in a: count+=1 print('Line Count: ',count)
5604b47bbee5724654a78c4c1f0c224f6b831c08
yosef8234/test
/sorting-algorithms/1-selection_sort.py
649
3.765625
4
# Best Case Time: O(n^2) # Worst Case Time: O(n^2) # Average Case Time: O(n^2) import numpy as np def argmin(array): # Get the index of the smallest # element in the array arg = 0 for i in range(1, len(array)): if array[i] < array[arg]: arg = i return arg def selection_sort(array): n = len(array) for i in range(n): j = argmin(array[i:n]) + i array[i], array[j] = array[j], array[i] return array # Input: selection_sort([]) == [] # Output: # True # Input: array = list(np.random.randint(100, size=120)) np.array_equal(selection_sort(array), np.sort(array)) # Output: # True
13f40b75f8f668d104280d38c612e2a08b272c09
LeHamzaSh/GettingInput
/app.py
172
3.78125
4
name = input('What is your name? ') print('Hi ' + name) color = input('What is your favourite color? ') print(color + ' is my favourite color too') print('Mosh likes blue')
378d91699890004b517cff05b4a4cef3b60aa4c3
jamesfneyer/Number-Guessing-Game
/GuesstheNumber.py
3,440
3.796875
4
import random def valid_four_choice(choice1, choice2, choice3, choice4, prompt): isValid = False while not isValid: replay = input(prompt) if replay.lower() == choice1 or replay.lower() == choice2 or replay.lower() == choice3 or replay.lower() == choice4: isValid = True if replay.lower() == choice1 or replay.lower() == choice2: return choice1 else: return choice3 else: print("Hey! That wasn't a valid input!") def get_continue(prompt): isValid = False while not isValid: replay = input(prompt) if replay.lower() == "y" or replay.lower() == "yes" or replay.lower() == "n" or replay.lower() == "no": isValid = True return replay.lower() == "y" or replay.lower() == "yes" else: print("Hey! That wasn't a valid input!") play_again = True who_guesses = input("Who is guessing the number? (computer/humanoid) ") if who_guesses.lower() == "humanoid" or who_guesses.lower() == "human": while play_again: turns = 10 correct_guess = False my_number = random.randint(1,100) # my_number = 50 while not correct_guess and turns > 0: print("Your turns left is "+str(turns)) your_guess = input("Enter your guess: ") try: your_number = int(your_guess) except ValueError: print("Error! Must be an integer.") else: if your_number == my_number: print("Dang, you got it! And with "+str(turns)+" left!") correct_guess = True else: if your_number > my_number: print("You guessed too high!") else: print("You guessed too low!") turns -= 1 if correct_guess: play_again = get_continue("Good job! Would you like to play again? ") else: play_again = get_continue("You lost! The number I was thinking of was "+str(my_number)+". Would you like to play again?") elif who_guesses.lower() == "computer": while play_again: turns = 0 difference = 50 guess = 50 correct_guess = False while not correct_guess: if turns == 0: print("Pick a number between 1 and 100!") is_correct = valid_four_choice("yes","y","no","n","Is the number you're thinking of "+str(guess)+"?") if is_correct.lower() == "yes": replay = input("All too easy. Only took me "+str(turns)+" turns. Play again? ") correct_guess = True play_again = get_continue("Would you like to play again? ") elif is_correct.lower() == "no": if difference != 1: difference //= 2 high_or_low = valid_four_choice("higher","high","lower","low","Dang! Was I too high or low? ") if high_or_low.lower() == "higher": guess -= difference correct_hl = True ++turns elif high_or_low.lower() == "lower": guess += difference correct_hl = True ++turns
db74ed686e5e972da905214a004fc84b7ae4138c
coolmich/py-leetcode
/solu/110|Balanced Binary Tree.py
598
3.875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def height(node): if not node: return 0 lh = height(node.left) if lh == -1: return -1 rh = height(node.right) if rh == -1 or abs(lh - rh) > 1: return -1 return max(lh, rh)+1 return height(root) != -1
d405b447b86c4de8467cb79175deca905e4ada83
fiso0/MxPython
/taobaoPriceBug/taobaoPriceBug.py
654
3.53125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # 本代码尝试使用BS4静态读取页面内容,但由于价格部分使用了动态显示,无法获取 from bs4 import BeautifulSoup import requests import urllib import os import sys import time def get_soup_of(url): """获取某个url的soup :param url: 待获取的网页地址 """ html = requests.get(url).text soup = BeautifulSoup(html, 'lxml') return (soup) if __name__ == '__main__': URL = input('商品网址:') # get current page soup = get_soup_of(URL) price = int(soup.select_one('.tm-price').text[1:-1]) # Find only the first tag that matches a selector(class="tm-price")
2435a99b2bfd535980da09b46dee4d39589cfe87
Thieberius/python
/objektorientiert/laufen.py
680
3.640625
4
class Jogger(list): """sportliche klasse für das verwalten von gelaufenen zeiten""" def __init__(self, altersklasse, zeit=[]): self.altersklasse = altersklasse self.gelaufene_zeiten = zeit def zeiterfassung(self, zeiten): self.gelaufene_zeiten += zeiten laufer_Hans = Jogger("M40") print(laufer_Hans.altersklasse) laufer_Hans.zeiterfassung(["2:30"]) print(laufer_Hans.gelaufene_zeiten) laufer_Hans.zeiterfassung(["2:40", "3:10"]) print(laufer_Hans.gelaufene_zeiten) print() print("vor POP:") print(laufer_Hans.gelaufene_zeiten) print("POP:") print(laufer_Hans.gelaufene_zeiten.pop()) print("nach POP:") print(laufer_Hans.gelaufene_zeiten)
e9bc3fc44ce652fe0d1ffb71635b4e6b08ef2d0f
gsaukov/python-machine
/core/days100/12.py
1,210
3.75
4
s = input('give me a string') l, d = 0,0 for c in s: if c.isalpha(): l=l+1 elif c.isdigit(): d=d+1 else: pass print('Letters', l) print('Digits', d) import re p = input('enter password: ') x = True while x: if(len(p) < 6 or len(p) > 16): break elif not re.search('[a-z]', p): break elif not re.search('[0-9]', p): break elif not re.search('[A-Z]', p): break elif not re.search('[$#@]', p): break elif re.search('\s', p): break else: print('password check is a green light') x = False break if x: print("that is a BS password - you are banned for life") even_digits = [] for i in range(100, 401): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0): even_digits.append(s) print(' $ '.join(even_digits)) letter_A = '' for row in range(0,7): for column in range (0,7): if(((column == 1 or column == 5) and row != 0) or ((row == 0 or row == 3) and (column > 1 and column < 5))): letter_A = letter_A + "*" else: letter_A = letter_A + ' ' letter_A = letter_A + '\n' print(letter_A)
fa8402577e91cc0061b5a47177bb7a8d19d0a601
d4rkr00t/leet-code
/python/leet/761-special-binary-string.py
836
3.609375
4
# Special Binary String # https://leetcode.com/problems/special-binary-string/ # hard # # The number of 0's is equal to the number of 1's. # Every prefix of the binary string has at least as many 1's as 0's. # Choose two consecutive, non-empty, special substrings of S, and swap them. # # Time: TBD # Space: TBD # # Solution: # TBD def makeLargestSpecial(S: str) -> str: count = i = 0 res = [] for j, v in enumerate(S): count = count + 1 if v=='1' else count - 1 if count == 0: res.append('1' + makeLargestSpecial(S[i + 1:j]) + '0') i = j + 1 return ''.join(sorted(res)[::-1]) print(makeLargestSpecial("11011000111000"), "11100100111000") # 14 # 11100100111000 # stack = [] # regions = [(8,13)] # start = 8 # end = 13 # # "1010110010" # "10" "10" # "1010" # ""
7ad92efd300cebb2edf4e83640fb9e1ce61b5797
k8thedinosaur/labs
/needswork_atm.py
3,320
4.3125
4
# # Lab: ATM Interface # # Save your solution in a directory in `practice/` named `atm-interface`. # # An account will be a class named `Account` in a module named `account`: it will have private attributes for the balance and interest rate. # Remember to underscore `_` prefix any private attributes. # A newly-instantiated account will have zero balance and an interest rate of 0.1%. # # Write class methods in the account class that: # # * `get_funds()` Return account balance # * `deposit(amount)` Deposit to the account # * `check_withdrawal(amount)` Return `True` if large enough balance for a withdrawal # * `withdraw(amount)` Withdraw an allowed amount; raise a `ValueError` if insufficent balance # * `calc_interest()` Calculate and return interest on the current account balance # # ## Advanced # # Write a program that functions as a simple ATM for two accounts: # # 1. Checking account # 1. Savings account # # Implement a user interface in a module `main` that lets a user pick each of those actions for a given account and updates the account. # After each action it will print the balance. # # ## Super Advanced # # Adds some advanced features to the account class. # # * Add a function called `get_standing()` have it return a bool with whether the account has less than $1000 in it. # # * Predatorily charge a transaction fee every time a withdrawal or deposit happens if the account is in bad standing. # # * Save the account balance to a file after each operation. # Read that balance on startup so the balance persists across program starts. # # * Add to each account class an account ID number. # # * Allow the user to open more than one account. # Let them perform all of the above operations by account number. # class BankAccount(BalanceRequestMixin): # def __init__(self, f_name, l_name, balance=0): # self.f_name = f_name # self.l_name = l_name # self.full_name = self.f_name + " " + self.l_name # self.balance = balance # self.setup() # # def deposit(self, amount): # self.balance += amount # print("You have deposited {}. Your new balance is {}.".format(amount, self.balance)) # # def withdraw(self, amount): # if self.balance - amount >= 0: # self.balance -= amount # print("You have withdrawn {}. Your new balance is {}.".format(amount, self.balance)) # else: # print("Insufficient funds.") # # def setup(self): # print("You have created an account for {}".format(self.full_name)) # # def __str__(self): # return "Account of {}.".format(self.full_name) # # def __repr__(self): # return self.__str__() # # class AltBankAccount(BankAccount, BalanceRequestMixin): # def withdraw(self, amount, cancel=False): # if cancel: # return super().withdraw(amount) # elif self.balance - amount - 200 >= 0: # self.balance -= amount # print("You have withdrawn {}. Your new balance is {}.".format(amount, self.balance)) # else: # print("Insufficient funds. >:[") # # # account1 = BankAccount("Kate", "Cat", 60) # account2 = AltBankAccount("Murray", "Cat", 5000) # # print(account1.balance) # print(account2.balance) # # # account2.withdraw(5000, True)
9d6c71959d37f8341d7ef29266ded6a186943f3f
JoshBatchelor777/Rock-Paper-Scissors_Game-Python2.7-
/rspPython_CodeBackup.py
2,140
4.125
4
### # Rock, Paper, Scissors! ### # Version: Python 2.7.13 # # Author: Josh Batchelor, 12/5/2017 # # Purpose: Make a simple RPS game. # import time import random import math moves = ['rock','paper','scissors'] cp = "Computer " pl = "Human " pPts = 0 cPts = 0 print("Rock, Paper Scissors game. You vs. {}".format(cp)) print("NOTE: Only enter rock, paper, or scissors as a move!") print("Best 2 out of 3 wins.") print("Round 1!") while True: if pPts == 3 or cPts == 3: break pm = raw_input("What's your move? ").lower() if pm == moves[0] or pm == moves[1] or pm == moves[2]: print("You chose " + pm + ".") if pm == "Harrison Fjord!".lower(): print("You shoot the Computer in a furious rage!" ) print("There are chunks of molten, burning metal and plastic everywhere") print("The computer has been defeated...") pPts = pPts + 999999 print(pl + "receives 999,999 for his victory!") cm = random.choice(moves) print(cp + " chose " + cm + ".") if cm == pm: print("It's a draw!") if cm == moves[0] and pm == moves[1]: pPts = pPts + 1 print(pl + "won. " + pl + "has " + str(pPts) + " points.") if cm == moves[0] and pm == moves[2]: cPts = cPts + 1 print(cp + "won. " + cp + "has " + str(cPts) + " points.") if cm == moves[1] and pm == moves[0]: cPts = cPts + 1 print(cp + "won. " + cp + "has " + str(cPts) + " points.") if cm == moves[1] and pm == moves[2]: pPts = pPts + 1 print(pl + "won. " + pl + "has " + str(pPts) + " points.") if cm == moves[2] and pm == moves[0]: pPts = pPts + 1 print(pl + "won. " + pl + "has " + str(pPts) + " points.") if cm == moves[2] and pm == moves[1]: cPts = cPts + 1 print(cp + "won. " + cp + "has " + str(cPts) + " points.") if pPts >= 3 or cPts >= 3: break print("*GAME HAS ENDED*") if pPts > cPts: print("You are the winner!") else: print(cp + "is the winner!") print("Goodbye")
f744677868fdcf0178c4676cfafd33ecdf83e89a
artbohr/codewars-algorithms-in-python
/7-kyu/father-and-son.py
610
3.890625
4
def sc(s): return ''.join([x for x in s if s.count(x.lower())>0 and s.count(x.upper())>0]) ''' #Task: Every uppercase letter is a Father, The corresponding lowercase letters is the Son. Given the string ```s```, If the father and son both exist, keep them. If it is a separate existence, delete them. Return the result. For example: ```sc("Aab")``` should return ```"Aa"``` ```sc("AabBc")``` should return ```"AabB"``` ```sc("AaaaAaab")``` should return ```"AaaaAaa"```(father can have a lot of childs) ```sc("aAAAaAAb")``` should return ```"aAAAaAA"```(childs can also have a lot of parents) '''
098f73aa57663128df4ddc7be94e5527ef3cc224
lilyfofa/python-exercises
/exercicio6.py
295
4.09375
4
import math n = int(input('Digite um número: ')) #print('O dobro do número {} é igual a {}. Seu triplo equivale a {}. Sua raiz quadrada vale {}.'.format(n,(n*2),(n*3),math.sqrt(n))) print(f'O dobro do número {n} é {n*2}, o triplo vale {n*3} e sua raiz quadrada equivale a {pow(n,1/2)}')
57507fada8e7f34764de2e85919b97c3baecd630
Jstanislaus/Matrices
/PythonApplication29/PythonApplication29.py
32,579
3.828125
4
import random from debugprint import Debug import time loop = True global dim3 def func1(): i = 0 array = [] attempt2 = 0 j = 0 attempt = 0 temp = 0 x0 = [] x1 =[] x2 = [] x3 = [] x4 = [] x5 = [] x6 = [] y1 = [] y2 = [] y3=[] dim3 = 0 drake = 0 topaz = 0 store1 = [] store2 = [] store3 = [] ez =0 store4 =[] store5 = [] store6 = [] store7 = [] store8 = [] holder = 0 dim = [] code1= True n =0 idk = 0 lol2 = 0 array3 =[] global y array2 = [] placeholder = 0 brrr= 0 loopy =True code = True k =0 x = str("arr") z = str("arr") print("\nThis is a matrix generator") menu = input("1. Choose matrices' dimensions \n2. Random dimensions\n3. Can you multiply these matrices?\n4. Multiplication with matrices practice\n5. Find the determinant of this random matrix\n6.Find the Inverse of a matrix\n\n") if menu.isdigit() and 1<= int(menu) <=7: menu = int(menu) else: print("\nError, Please enter a number from 1 to 6") time.sleep(1) func1() if menu == 1: dim = input("Please enter the dimensions you want for the matrix with a space between each character\n") dim = dim.split(" ") while True: if dim[0].isdigit() and dim[2].isdigit and dim[1]=="x": break else: print("Please enter a valid input such as 3 x 2 with a space between each character") for i in range (0,int(dim[0])): y = str(i) x += y x = [] for j in range (0,int(dim[2])): (x).append(random.randint(0,9)) if len(x) == int(dim[2]): print(x) elif menu == 2: while True: l = input("What do you want the max number of rows or columns to be? ") if l.isdigit(): l = int(l) break else: print("\nPlease enter a valid number") func1() dim1 = random.randint(2,l) dim2 = random.randint(2,l)# while True: maxsize = input("What do you want the maximum number of digits per number to be?(2 or 1)") if maxsize.isdigit() and 1 <= int(maxsize) <=2: maxsize = int(maxsize) break else: print("Please enter a valid number") if maxsize == 1: digit = 10 elif maxsize == 2: digit = 100 for i in range (0,int(dim1)): y = str(i) x += y x = [] for j in range (0,int(dim2)): (x).append(random.randint(0,digit)) if len(x) == int(dim2): print(x) elif menu == 3: que = input("Would you like to choose the dimensions?\n\n") if que == "Yes": while True: dim = input("Please enter the dimensions you want for the matrix with a space between each character\n") dim = dim.split(" ") if dim[0].isdigit() and dim[1]=="x"and dim[2].isdigit(): l = int(l) break else: print("\nPlease enter in the correct form such as 3 x 4 ") while True: maxsize = input("What do you want the maximum number of digits per number to be?(2 or 1)") if maxsize.isdigit() and 1 <= int(maxsize) <=2: maxsize = int(maxsize) break else: print("Please enter a valid number") if maxsize == 1: digit = 10 elif maxsize == 2: digit = 100 for i in range (0,int(dim[0])): y = str(i) x += y x = [] for j in range (0,int(dim[2])): (x).append(random.randint(0,digit)) if len(x) == int(dim[2]): array.append(x) while True: dim1 = input("Please enter the dimensions you want for the matrix with a space between each character\n") dim1 = dim1.split(" ") if dim[0].isdigit() and dim[1]=="x"and dim[2].isdigit(): l = int(l) break else: print("\nPlease enter in the correct form such as 3 x 4 ") for i in range (0,int(dim1[0])): y = str(i) x += y x = [] for j in range (0,int(dim1[2])): (x).append(random.randint(0,digit)) if len(x) == int(dim1[2]): store4.append(x) #dim[0] == dims #dim[2] == dim3 #dim1[0] == dim1 #dim1[2] == dim2 i=0 for i in range (0,len(array)): if len(array[i]) > int(dim[2]): array[i].pop() print(array[i]) i=0 print("\n\n") for i in range (0,len(store4)): if len(store4[i]) > int(dim1[2]): store4[i].pop() print(store4[i]) ques = input("Can these two arrays be multiplied?") if ques == "No": if int(dim1[0]) == int(dim[2]): if int(dim[0]) == int(dim1[2]): print("You are incorrect, they can be multiplied") else: print("You're correct, they cannot be multiplied") elif ques == "Yes": if int(dim1[0]) == int(dim[2]): if int(dim[0]) == int(dim1[2]): print("You are correct, they can be multiplied") else: print("You're incorrect, they cant be multiplied") time.sleep(1.5) code = False elif que == "No": w = 0 while code == True: while True: l = input("What do you want the max number of rows or columns to be? ") if l.isdigit(): l = int(l) break else: print("\nPlease enter a valid number") while True: maxsize = input("What do you want the maximum number of digits per number to be?(2 or 1)") if maxsize.isdigit() and 1 <= int(maxsize) <=2: maxsize = int(maxsize) break else: print("Please enter a valid number") if maxsize == 1: digit = 10 elif maxsize == 2: digit = 100 #makes num of rows for brrr in range (0,2): if brrr == 0: dims = random.randint(2,l) dim3 = random.randint(2,l) for i in range (0,int(dims)): #dim1 = num of rows #dim2 = size of row y = str(i) x += y x = [] for j in range (0,int(dim3)): #adds nums to arrays/ rows (x).append(random.randint(0,digit)) if len(x) == int(dim3): array.append(x) elif brrr == 1: dim1 = random.randint(2,l) dim2 = random.randint(2,l) for i in range (0,int(dim1)): #dim1 = num of rows #dim2 = size of row drake = int(y)+int(i) x += y x = [] for j in range (0,int(dim2)): #adds nums to arrays/ rows (x).append(random.randint(0,digit)) if len(x) == int(dim2): store4.append(x) for i in range (0,len(array)): if len(array[i]) > dim3: array[i].pop() print(array[i]) print("\n\n") for i in range (0,len(store4)): if len(store4[i]) > dim2: store4[i].pop() print(store4[i]) ques = input("Can these two arrays be multiplied?") if ques == "No": if dim1 == dim3: if dims == dim2: print("You are incorrect, they can be multiplied") else: print("You're correct, they cannot be multiplied") elif ques == "Yes": if dim1 == dim3: if dims == dim2: print("You are correct, they can be multiplied") else: print("You're incorrect, they cant be multiplied") time.sleep(1.5) code = False elif menu == 4: que = input("Would you like to choose the dimensions?\n\n") if que == "Yes": dim = input("Please enter the dimensions you want for the matrix with a space between each character\n") dim = dim.split(" ") while True: if dim[0].isdigit() and dim[2].isdigit and dim[1]=="x": break else: print("Please enter a valid input such as 3 x 2 with a space between each character") for i in range (0,int(dim[0])): y = str(i) x += y x = [] for j in range (0,int(dim[2])): (x).append(random.randint(0,9)) if len(x) == int(dim[2]): array.append(x) dim1 = input("Please enter the dimensions you want for the 2nd matrix with a space between each character\n") dim1 = dim1.split(" ") while True: if dim1[0].isdigit() and dim1[2].isdigit and dim1[1]=="x": break else: print("Please enter a valid input such as 3 x 2 with a space between each character") while True: maxsize = input("What do you want the maximum number of digits per number to be?(2 or 1)") if maxsize.isdigit() and 1 <= int(maxsize) <=2: maxsize = int(maxsize) break else: print("Please enter a valid number") if maxsize == 1: digit = 10 elif maxsize == 2: digit = 100 if dim1[0] == dim[2] and dim[0] == dim1[2] : for i in range (0,int(dim1[0])): y = str(i) x += y x = [] for j in range (0,int(dim1[2])): (x).append(random.randint(0,digit)) if len(x) == int(dim1[2]): store4.append(x) else: print("These arrays with these dimensions cannot be multiplied") #dim[0] == dims #dim[2] == dim3 #dim1[0] == dim1 #dim1[2] == dim2 i=0 for i in range (0,len(array)): if len(array[i]) > int(dim[2]): array[i].pop() print(array[i]) i=0 print("\n\n") for i in range (0,len(store4)): if len(store4[i]) > int(dim1[2]): store4[i].pop() print(store4[i]) #print(store1) #print(store2) i = 0 j=0 #print(str(dim1)) #print(str(dim2)) #print(str(dims)) #dim[0](num of rows)[2] (size of rows) is original matrix dim1 is 2nd matrix #dims(num of rows) and dim3(size of row) is original, dim1(num of rows) and 2(size of row) is 2nd matrix #print(dim[0]) # print(dim[2]) if dim1[0] < dim[0]: dim[0] = dim1[0] #print(str(dim3)) if dim1[2] < dim[2]: back = int(dim1[2]) #print(dim[0]) # print(dim[2]) dim2 = int(dim[0]) dim3 = int(dim[2]) x = x for k in range (0,back): #print("hi") for j in range(0,dim2): for i in range(0, dim3): add = array[j][i]*store4[i][k] #print(str(array[j][i])+" x "+str(store4[i][k])+ " = " +str(add)) holder += add store3.append(holder) holder = 0 #print(store3) # print(store3) for t in range(0,back): if t == 0: x0.append(store3[t]) elif t ==1: x1.append(store3[t]) elif t ==2: x2.append(store3[t]) elif t ==3: x3.append(store3[t]) elif t ==4: x4.append(store3[t]) elif t == 5: x5.append(store3[t]) elif t == 6: x6.append(store3[t]) store3.clear() code = False print("\n\n") if len(x0)>0: print(x0) if len(x1)>0: print(x1) if len(x2)>0: print(x2) if len(x3)>0: print(x3) if len(x4)>0: print(x4) if len(x5)>0: print(x5) if len(x6)>0: print(x6) elif que == "No": w = 0 while code == True: l = int(input("What do you want the max number of rows or columns to be? ")) while code1 == True: dims = random.randint(2,l) dim3 = random.randint(2,l) dim1 = random.randint(2,l) dim2 = random.randint(2,l) if dim3 <= dim2: if dim1 == dim3: if dim2 == dims: code1 = False while True: maxsize = input("What do you want the maximum number of digits per number to be?(2 or 1)") if maxsize.isdigit() and 1 <= int(maxsize) <=2: maxsize = int(maxsize) break else: print("Please enter a valid number") if maxsize == 1: digit = 10 elif maxsize == 2: digit = 100 #makes num of rows for brrr in range (0,2): if brrr == 0: for i in range (0,int(dims)): #dims = num of rows #dim3 = size of row y = str(i) x += y x = [] for j in range (0,int(dim3)): #adds nums to arrays/ rows (x).append(random.randint(0,digit)) if len(x) == int(dim3): array.append(x) elif brrr == 1: for i in range (0,int(dim1)): #dim1 = num of rows #dim2 = size of row drake = int(y)+int(i) x += y x = [] for j in range (0,int(dim2)): #adds nums to arrays/ rows (x).append(random.randint(0,digit)) if len(x) == int(dim2): store4.append(x) i=0 for i in range (0,len(array)): if len(array[i]) > dim3: array[i].pop() print(array[i]) i=0 print("\n\n") for i in range (0,len(store4)): if len(store4[i]) > dim2: store4[i].pop() print(store4[i]) #print(store1) #print(store2) i = 0 j=0 #print(str(dim1)) # print("hi") #print(str(dim3)) # print(str(dim2)) #print(str(dims)) if dim1 < dims: dims = dim1 if dim2 < dim3: dim3 = dim2 print(str(dim3)) print(str(dim2)) #dim2 is number of rows #dim3 is size of rows for k in range (0,dim3): for j in range(0,dim2): for i in range(0, dim3): add = array[j][i]*store4[i][k] print(str(array[j][i])+" x "+str(store4[i][k])+ " = " +str(add)) holder += add store3.append(holder) holder = 0 #print(store3) for t in range(0,dim3): if t == 0: x0.append(store3[t]) elif t ==1: x1.append(store3[t]) elif t ==2: x2.append(store3[t]) elif t ==3: x3.append(store3[t]) elif t ==4: x4.append(store3[t]) elif t == 5: x5.append(store3[t]) elif t == 6: x6.append(store3[t]) store3.clear() code = False print("\n\n") if len(x0)>0: print(x0) if len(x1)>0: print(x1) if len(x2)>0: print(x2) if len(x3)>0: print(x3) if len(x4)>0: print(x4) if len(x5)>0: print(x5) if len(x6)>0: print(x6) if menu == 5: dim = input("\nPlease enter the dimensions you want for the matrix with a space between each character (either 2 x 2 or 3 x 3)\n") dim = dim.split(" ") while True: if dim[0].isdigit() and dim[1]=="x"and dim[2].isdigit(): break else: print("\nPlease enter in the correct form such as 3 x 4 ") while True: maxsize = input("What do you want the maximum number of digits per number to be?(2 or 1)") if maxsize.isdigit() and 1 <= int(maxsize) <=2: maxsize = int(maxsize) break else: print("Please enter a valid number") if maxsize == 1: digit = 10 elif maxsize == 2: digit = 100 for i in range (0,int(dim[0])): y = str(i) x += y x = [] for j in range (0,int(dim[2])): (x).append(random.randint(0,digit)) if len(x) == int(dim[2]): print(x) store1.append(x) else: print("You can only find the determinant of a square matrix ") if int(dim[0]) ==2: multiplied = (store1[0][0]*store1[1][1])-(store1[0][1]*store1[1][0]) print(str(multiplied)) if int(dim[0]) == 3: for i in range(0,len(x)): # pack = [1,2] # pack2 = [0,1,2] # pack2.pop(int(i)) # n1 = pack2[0] # n2 = pack2[1] if i ==0: #print(str(store1[0][0]) + " * (" +str(store1[1][1])+ " * "+str(store1[2][2])+" -( "+str(store1[2][1])+" * "+str(store1[1][2])+ ")") sumdet = int(store1[0][0])*(((store1[1][1])*(store1[2][2]))-((store1[2][1])*(store1[1][2]))) #print(str(sumdet)) elif i ==1: # print(str(store1[0][i]) + " * (" +str(store1[1][int(n1)])+ " * "+str(store1[2][int(n2)])+" -( "+str(store1[2][int(n1)])+" * "+str(store1[1][int(n1)+2])+ ")") sumdet = int(store1[0][1])*((((store1[1][0])))*(store1[2][2])-((store1[2][0])*(store1[1][2]))) elif i == 2: #print(str(store1[0][i]) + " * (" +str(store1[1][int(n1)])+ " * "+str(store1[2][int(n2)])+" -( "+str(store1[2][int(n1)])+" * "+str(store1[1][int(n1)+1])+")") sumdet = int(store1[0][2])*((((store1[1][0])))*(store1[2][1])-((store1[2][0])*(store1[1][1]))) #print(" = "+str(sumdet)) x1.append(sumdet) determin = int(x1[0])-int(x1[1])+int(x1[2]) det = int(input("Find the determinant of this matrix")) if det == determin: print("You are right, the determinant is "+ str(determin)) else: print("You are incorrect, the determinant is "+ str(determin)) if menu == 6: dim = input("\nPlease enter the dimensions you want for the matrix with a space between each character (either 2 x 2 or 3 x 3)\n") dim = dim.split(" ") while True: if dim[0].isdigit() and dim[1]=="x"and dim[2].isdigit(): break else: print("\nPlease enter in the correct form such as 3 x 4 ") while True: maxsize = input("What do you want the maximum number of digits per number to be?(2 or 1)") if maxsize.isdigit() and 1 <= int(maxsize) <=2: maxsize = int(maxsize) break else: print("Please enter a valid number") if maxsize == 1: digit = 10 elif maxsize == 2: digit = 100 print("\n") Debug("Hello") if int(dim[0])>3 or int(dim[0])<2: print("Please enter either 2 x 2 or 3 x 3 in that form") func1() if int(dim[0]) == int(dim[2]): if isinstance(dim[0], int): print("Please enter in the form such as 3 x 3 ") for i in range (0,int(dim[0])): y = str(i) x += y x = [] for j in range (0,int(dim[2])): (x).append(random.randint(0,digit)) if len(x) == int(dim[2]): print(x) store1.append(x) else: print("You can only find the Inverse of a square matrix ") if int(dim[0]) ==2: determin = (store1[0][0]*store1[1][1])-(store1[0][1]*store1[1][0]) elif int(dim[0]) == 3: for i in range(0,len(x)): #pack = [1,2] #pack2 = [0,1,2] # pack2.pop(int(i)) #n1 = pack2[0] #n2 = pack2[1] if i ==0: print(str(store1[1][1])+ " * "+str(store1[2][2])+" -( "+str(store1[2][2])+" * "+str(store1[1][2])+ ")") sumdet = ((((store1[1][1])))*(store1[2][2])-((store1[2][1])*(store1[1][2]))) elif i ==1: print(str(store1[1][0])+ " * "+str(store1[2][2])+" -( "+str(store1[2][0])+" * "+str(store1[1][2])+ ")") sumdet = ((((store1[1][0])))*(store1[2][2])-((store1[2][0])*(store1[1][2]))) else: print(str(store1[1][0])+ " * "+str(store1[2][1])+" -( "+str(store1[2][0])+" * "+str(store1[1][1])+")") sumdet = ((((store1[1][0])))*(store1[2][1])-((store1[2][0])*(store1[1][1]))) print(" = "+str(sumdet)) x1.append(sumdet) for i in range(0,len(x)): # pack = [0,2] # pack2 = [0,1,2] # pack2.pop(int(i)) # n1 = pack2[0] # n2 = pack2[1] if i == 0: print(str(store1[0][1])+ " * "+str(store1[2][2])+" -( "+str(store1[0][2])+" * "+str(store1[2][1])+")") sumdet = ((((store1[0][1])))*(store1[2][2])-((store1[0][2])*(store1[2][1]))) elif i ==1: print(str(store1[0][0])+ " * "+str(store1[2][2])+" -( "+str(store1[2][0])+" * "+str(store1[0][2])+ ")") sumdet = ((((store1[0][0])))*(store1[2][2])-((store1[2][0])*(store1[0][2]))) else: print(str(store1[0][0])+ " * "+str(store1[2][1])+" -( "+str(store1[2][0])+" * "+str(store1[0][1])+")") sumdet = ((((store1[0][0])))*(store1[2][1])-((store1[2][0])*(store1[0][1]))) print(" = "+str(sumdet)) x2.append(sumdet) for i in range(0,len(x)): #pack = [0,1] # pack2 = [0,1,2] # pack2.pop(int(i)) # n1 = pack2[0] # n2 = pack2[1] if i ==0: print(str(store1[0][1])+ " * "+str(store1[1][2])+" -( "+str(store1[0][2])+" * "+str(store1[1][1])+")") sumdet = ((((store1[0][1])))*(store1[1][2])-((store1[0][2])*(store1[1][1]))) elif i ==1: print(str(store1[0][0])+ " * "+str(store1[1][2])+" -( "+str(store1[1][0])+" * "+str(store1[0][2])+ ")") sumdet = ((((store1[0][0])))*(store1[1][2])-((store1[1][0])*(store1[0][2]))) else: print(str(store1[0][0])+ " * "+str(store1[1][1])+" -( "+str(store1[0][1])+" * "+str(store1[1][0])+")") sumdet = (((store1[0][0])*(store1[1][1]))-((store1[0][1])*(store1[1][0]))) print(" = "+str(sumdet)) x3.append(sumdet) x1[1]=-1*x1[1] x2[0]=-1*x2[0] x2[2]=-1*x2[2] x3[1]=-1*x3[1] y1.append(x1[0]) y1.append(x2[0]) y1.append(x3[0]) y2.append(x1[1]) y2.append(x2[1]) y2.append(x3[1]) y3.append(x1[2]) y3.append(x2[2]) y3.append(x3[2]) # print("x3 is "+str(x3)) for i in range(0,len(x)): pack = [1,2] pack2 = [0,1,2] pack2.pop(int(i)) n1 = pack2[0] n2 = pack2[1] if i ==1: print(str(store1[0][i]) + " * (" +str(store1[1][int(n1)])+ " * "+str(store1[2][int(n2)])+" -( "+str(store1[2][int(n1)])+" * "+str(store1[1][int(n1)+2])+ ")") sumdet = int(store1[0][i])*((((store1[1][int(n1)])))*(store1[2][int(n2)])-((store1[2][int(n1)])*(store1[1][int(n1)+2]))) else: print(str(store1[0][i]) + " * (" +str(store1[1][int(n1)])+ " * "+str(store1[2][int(n2)])+" -( "+str(store1[2][int(n1)])+" * "+str(store1[1][int(n1)+1])+")") sumdet = int(store1[0][i])*((((store1[1][int(n1)])))*(store1[2][int(n2)])-((store1[2][int(n1)])*(store1[1][int(n1)+1]))) print(" = "+str(sumdet)) x4.append(sumdet) determin = int(x4[0])-int(x4[1])+int(x4[2]) det = int(input("\nWhat is the determinant for this matrix? ")) if det == determin: print("correct") else: print("incorrect, it is "+str(determin)) for i in range(0,len(y1)): attempt = int(input("\nWhat is the num "+str(i+1)+" element of the matrix? ")) if attempt == y1[i]: print("correct") else: print("Incorrect, it should be "+str(y2[i])) for i in range(0,len(y2)): attempt = int(input("\nWhat is the num "+str(i+1 + len(y1))+" element of the matrix? ")) if attempt == y2[i]: print("correct") else: print("Incorrect, it should be "+str(y2[i])) for i in range(0,len(y3)): attempt = int(input("\nWhat is the num "+str(i+1+len(y1)+len(y2))+" element of the matrix? ")) if attempt == y3[i]: print("correct") else: print("Incorrect, it should be "+str(y3[i])) print("\n\nThe inverse is ") if 100 >determin > 10: print("1 " + str(y1) + "\n---"+ " X "+ str(y2)+ "\n"+str(determin)+" "+str(y3)) elif determin > 100: print("1 " + str(y1) + "\n---"+ " X "+ str(y2)+ "\n"+str(determin)+" "+str(y3)) elif 0 <determin < 10: print("1 " + str(y1) + "\n---"+ " X "+ str(y2)+ "\n"+str(determin)+" "+str(y3)) elif determin == 0: print("There is no inverse") elif 0> determin >-10: print("1 " + str(y1) + "\n---"+ " X "+ str(y2)+ "\n"+str(determin)+" "+str(y3)) elif -10>determin>-100: print("1 " + str(y1) + "\n---"+ " X "+ str(y2)+ "\n"+str(determin)+" "+str(y3)) elif -100 > determin: print("1 " + str(y1) + "\n---"+ " X "+ str(y2)+ "\n"+str(determin)+" "+str(y3)) if int(dim[0]) == 2: temp = int(store1[0][0]) temp2 = -1*int(store1[0][1]) temp3 = -1*int(store1[1][0]) temp4 = int(store1[1][1]) store1.clear() store2.clear() store1.append(temp4) store1.append(temp2) store2.append(temp3) store2.append(temp) attempt2= int(input("What is the determinant?")) if attempt2 == determin: print("You are correct\n") else: print("Not quite right, the answer is:") print(str(determin)) for i in range(0,4): attempt = int(input("What is the num "+str(i+1)+" element of the matrix? ")) if i < 2: if attempt == store1[i]: print("correct") print("\n") time.sleep(1) else: print("Not quite right, it should be:") print(store1[i]) print("\n") time.sleep(1) elif i >= 2: i = i-2 if attempt == store2[i]: print("correct") print("\n") time.sleep(1) else: print("Not quite right, it should be:") print(store2[i]) print("\n") time.sleep(1) time.sleep(1.5) print("\n\nThe inverse is ") if 100 >determin > 10: print("1 " + str(store1) + "\n---"+ " X "+ str(store2)+ "\n"+str(determin)) elif determin > 100: print("1 " + str(store1) + "\n---"+ " X "+ str(store2)+ "\n"+str(determin)) elif determin < 10: print("1 " + str(store1) + "\n---"+ " X "+ str(store2)+ "\n"+str(determin)) while True: func1()
9bae794cfe8ef48a39300cfd2f51ea6d9deec401
PriyankaKhire/ProgrammingPracticePython
/Word Search Speed Coding.py
1,776
3.828125
4
#Word Search #https://leetcode.com/problems/word-search/ class Solution(object): def __init__(self): self.neighbors = [[-1, 0], [1, 0], [0, -1], [0, 1]] def isValid(self, row, col, board): if(row >= 0 and row < len(board)): if(col >= 0 and col < len(board[0])): return True return False def dfs(self, row, col, word, index, board, visited): if(index == len(word)): return True for neighbor in self.neighbors: new_row = row+neighbor[0] new_col = col+neighbor[1] if(self.isValid(new_row, new_col, board)): if(board[new_row][new_col] == word[index] and visited[new_row][new_col] == 0): visited[new_row][new_col] = 1 if(self.dfs(new_row, new_col, word, index+1, board, visited)): return True visited[new_row][new_col] = 0 def logic(self, board, word): for row in range(len(board)): for col in range(len(board[0])): if(board[row][col] == word[0]): visited = [[0 for c in range(len(board[0]))] for r in range(len(board))] visited[row][col] = 1 if(self.dfs(row, col, word, 1, board, visited)): return True return False def exist(self, board, word): print self.logic(board, word) """ :type board: List[List[str]] :type word: str :rtype: bool """ #Main board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] board = [["a","a"]] obj = Solution() obj.exist(board, "aaa")
5a3f4b296aa4be34844f480734d69a6aebdbac62
hevalenc/Curso_Udemy_Python
/classes3.py
1,021
4.46875
4
#aula sore Herança Simples - este arquivo está associado a aula_86 #a herança ocorre de cima para baixo, ou seja, a super classe (classe mão não herda funções de outras classes) e a #sub-classe (classe filha) herda funções da super classe class Pessoa: #esta classe é chamada de super classe def __init__(self, nome, idade): self.nome = nome self.idade = idade self.nomeclasse = self.__class__.__name__ #nomear as classes que estão usando esta função def falar(self): print(f'{self.nomeclasse} falando ...') class Cliente(Pessoa): #usará o mesmo método def __init__ da classe Pessoa, então instancia a classe origem entre () #em outra classe, isto é Herança, onde uma classe herda tudo de outra classe. Esta é uma sub-classe def comprar(self): print(f'{self.nomeclasse} comprando ...') class Aluno(Pessoa): #sub-classe pode ter métodos específicos def estudar(self): print(f'{self.nomeclasse} estudando ...')
52336ba193ad7d081e2292c1dfd5baef42766b6f
Vampirskiy/helloworld
/venv/Scripts/Урок1/in_type.py
138
3.609375
4
age=input('сколько вам лет?') period=20 age_period=int(age)+period print('через', period,'вам будет',age_period)
f38755586f5f15b1e59b52c3eaa381300d185dc3
ryoichi551124/PythonBasic
/q5.py
263
3.75
4
list1 = [10, 20, 30, 40, 10] list2 = [10, 20, 30, 40, 50] def check_list(list): if list[0] == list[-1]: flug = True else: flug = False print(f'Given list is {list}') print(f'result is {flug}') check_list(list1) check_list(list2)
f05859d048c6acadb3359e843fc37662bc01d58a
saedmansour/University-Code
/Artificial Intelligence/AI Multi Robot/Multi_robot/src/search/utils.py
4,413
3.5625
4
''' Provide some widely useful utilities. Safe for "from utils import *". ''' import operator, math, random, copy, sys, os.path, bisect, re import heapq # Inifinity should be a really large number... infinity = 1.0e400 ######################### ## Data Structures ## ######################### # Some implementations of data structures: # - Queue: The basic interface. # - LIFOQueue: A Stack. # - FIFOQueue: A standard queue. # - PriorityQueue: A queue with score to prioritize by. # - LimitedPriorityQueue: A queue that limits the amount of elements inserted # (used by BeamSearch for instance). class Queue: ''' Queue is an abstract class/interface. There are three types: Stack(): A Last In First Out Queue. FIFOQueue(): A First In First Out Queue. PriorityQueue(lt): Queue where items are sorted by lt, (default <). Each type supports the following methods and functions: q.append(item) -- add an item to the queue q.extend(items) -- equivalent to: for item in items: q.append(item) q.pop() -- return the top item from the queue len(q) -- number of items in q (also q.__len()) Note that isinstance(Stack(), Queue) is false, because we implement stacks as lists. If Python ever gets interfaces, Queue will be an interface. ''' def __init__(self): raise NotImplementedError() def append(self, item): ''' Appends the given item to the queue. ''' raise NotImplementedError() def pop(self): ''' Pops the next item in the order of the queue to pop. ''' raise NotImplementedError() def __len__(self): ''' Returns the number of items in the queue. ''' raise NotImplementedError() def extend(self, items): ''' Inserts a list of items into the queue at once. ''' for item in items: self.append(item) def LIFOQueue(): ''' Return an empty list, suitable as a Last-In-First-Out Queue. ''' return [] class FIFOQueue(Queue): ''' A First-In-First-Out Queue. ''' def __init__(self): self.q = [] self.start = 0 def append(self, item): self.q.append(item) def pop(self): e = self.q[self.start] self.start += 1 if self.start > 5 and self.start > len(self.q)/2: self.q = self.q[self.start:] self.start = 0 return e def __len__(self): return len(self.q) - self.start def extend(self, items): self.q.extend(items) class PriorityQueue(Queue): ''' A queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is min, the item with minimum f(x) is returned first; if order is max, then it is the item with maximum f(x). ''' def __init__(self, f=lambda x: x): self.q = [] self.f = f def append(self, item): heapq.heappush(self.q, (self.f(item), item)) def pop(self): return heapq.heappop(self.q)[1] def __len__(self): return len(self.q) class LimitedPriorityQueue(Queue): ''' A queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is min, the item with minimum f(x) is returned first; if order is max, then it is the item with maximum f(x). This variant limits the amount of elements that can be inserted. This may be used for example by a BeamSearch to only add to the queue a set number of states, and not all of them, to conserve memory. ''' def __init__(self, f=lambda x: x, element_limit=infinity): self.q = [] self.f = f self.limit = element_limit def append(self, item): ''' Appends the given item to the undelying priority queue. It makes sure to remove the worst element in the queue to stay within the element number limit if needed. ''' bisect.insort(self.q, (self.f(item), item)) if len(self) > self.limit: self.pop_back() def pop(self): return self.q.pop(0)[1] def pop_back(self): return self.q.pop()[1] def __len__(self): return len(self.q)
5c64e81a3c59c5c88f8f38b4a66ba2d98a2a40cd
Chandra-mouli-kante/Python-100-Days-Coding
/Sumof fibnocci.py
377
3.53125
4
''' fib series: 0 1 1 2 3 5 8 13 21 34 55 89 Ex: 30 21+8+1 Ex: 10 8+2 algo approach: Ex:30 21 30-21=9 8 9-8=1 1 ''' ''' def nearfib(n): #30,9 a,b=0,1 while n>=b: if n==b: return b a,b=b,a+b print(a) #21,8,1 return nearfib(n-a) #9,1 n=int(input()) #10 print(nearfib(n)) '''
ca7bda5a5111b574d86c5cefcd37c371a7d778ef
m-squared96/ODE-Solvers
/lv_exercise_8-2.py
1,494
3.78125
4
#!/usr/bin/python3 ''' This script is a solution to Exercise 8.2 of Newman and solves the Lotka-Volterra equations: dx/dt = (alpha)x - (beta)xy, dy/dt = (gamma)xy - (delta)y where x and y represent the populations of prey and predators in 1,000's respectively (so they're approximately continuous to three decimal places). Question asks for this system to be solved for the following parameters: 0 <= t <= 30 alpha = 1 beta = 0.5 gamma = 0.5 delta = 2 x(0) = y(0) = 2 ''' from numpy import arange,array import matplotlib.pyplot as plt def f(r,t): alpha = 1.0 beta = 0.5 gamma = 0.5 delta = 2.0 x = r[0] y = r[1] fx = alpha*x - beta*x*y fy = gamma*x*y - delta*y return array([fx,fy],float) t0 = 0.0 T = 30.0 N = 1000 h = (T - t0)/N tpoints = arange(t0,T,h) xpoints = [] ypoints = [] r = array([2.0,2.0],float) for t in tpoints: xpoints.append(r[0]) ypoints.append(r[1]) k1 = h*f(r,t) k2 = h*f(r + 0.5*k1,t + 0.5*h) k3 = h*f(r + 0.5*k2,t + 0.5*h) k4 = h*f(r + k3,t + h) r += (k1 + 2*k2 + 2*k3 + k4)/6 plt.figure() plt.plot(tpoints,xpoints,label="Prey") plt.plot(tpoints,ypoints,label="Predator") plt.title("Predator-Prey populations over time") plt.xlabel(r"$t$") plt.ylabel("Population (1,000's)") plt.legend() plt.figure() plt.plot(xpoints,ypoints) plt.title("Predator-Prey populations as a function of each other") plt.xlabel("Prey Population (1,000's)") plt.ylabel("Predator Population (1,000's)") plt.show()
82045f2b99f6d0317790a17ed2eca4c43f03fc38
Muktai-Suryawanshi/String-in-python
/LUR.py
140
3.546875
4
i = "SOFTWARE AND HARDWARE" print(i.lower()) print() j = "hello world" print(j.upper()) print() k = "Save,Trees" print(k.replace("v","r"))
8cb1c673931dc0a158c24f42bcce3ceead888324
craighawki/python_bootcamp
/averageheight.py
473
4.125
4
#!/usr/bin/env python # 🚨 Don't change the code below 👇 student_heights = input("Input a list of student heights ").split() for n in range(0, len(student_heights)): student_heights[n] = int(student_heights[n]) # 🚨 Don't change the code above 👆 #Write your code below this row 👇 tot = 0 count = 0 for num in student_heights: count += 1 tot += num print(tot) print(count) avg = int(tot / count) print(f"The average height is {avg} centimeters.")
ae3b3c9f1a62ad181c2b3cc7bfcbb4349ba680e3
Masetto97/Symbolic-Melody-Identification
/extra/utils/lang_utils.py
3,897
3.796875
4
#!/usr/bin/env python """ Common language-related functionality, typically involving introspection. """ from functools import wraps def enum(*sequential, **named): """ Return an enum with the specified names Parameters ---------- Returns ------- Example ------- >>> MyEnum = enum('one', 'two', 'three') >>> MyEnum.one 0 >>> MyEnum.two 1 >>> MyEnum.reverse_mapping[0] 'one' """ enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.iteritems()) enums['reverse_mapping'] = reverse return type('Enum', (), enums) def cached_property(func, name = None): """ cached_property(func, name=None) -> a descriptor This decorator implements an object's property which is computed the first time it is accessed, and which value is then stored in the object's __dict__ for later use. If the attribute is deleted, the value will be recomputed the next time it is accessed. Usage: >>> class X(object): >>> @cached_property >>> def foo(self): >>> return slow_computation() >>> x = X() >>> # first access of foo(slow): >>> x.foo >>> # subsequent access of foo (fast): >>> x.foo """ if name is None : name = func.__name__ @wraps(func) def _get (self ): try : return self.__dict__[name] except KeyError : self.__dict__[name] = func(self) return self.__dict__[name] @wraps(func) def _set (self,value): self.__dict__[name] = value @wraps(func) def _del (self ): self.__dict__.pop(name,None) return property(_get, _set, _del) def iter_subclasses(cls, _seen = None): """ iter_subclasses(cls) Generator over all subclasses of a given class, in depth first order. >>> list(iter_subclasses(int)) == [bool] True >>> class A(object): pass >>> class B(A): pass >>> class C(A): pass >>> class D(B,C): pass >>> class E(D): pass >>> >>> for cls in iter_subclasses(A): ... print(cls.__name__) B D E C >>> # get ALL (new-style) classes currently defined >>> [cls.__name__ for cls in iter_subclasses(object)] #doctest: +ELLIPSIS ['type', ...'tuple', ...] """ if not isinstance(cls, type): raise TypeError('iter_subclasses must be called with ' 'new-style classes, not %.100r' % cls) if _seen is None: _seen = set() try: subs = cls.__subclasses__() except TypeError: # fails only when cls is type subs = cls.__subclasses__(cls) for sub in subs: if sub not in _seen: _seen.add(sub) yield sub for sub in iter_subclasses(sub, _seen): yield sub class ComparableMixin(object): """source: http://regebro.wordpress.com/2010/12/13/python-implementing-rich-comparison-the-correct-way/ """ def _compare(self, other, method): try: return method(self._cmpkey(), other._cmpkey()) except (AttributeError, TypeError): # _cmpkey not implemented, or return different type, # so I can't compare with "other". return NotImplemented def __lt__(self, other): return self._compare(other, lambda s,o: s < o) def __le__(self, other): return self._compare(other, lambda s,o: s <= o) def __eq__(self, other): return self._compare(other, lambda s,o: s == o) def __ge__(self, other): return self._compare(other, lambda s,o: s >= o) def __gt__(self, other): return self._compare(other, lambda s,o: s > o) def __ne__(self, other): return self._compare(other, lambda s,o: s != o) if __name__ == '__main__': pass
efea7a0e91571502ae180e81f11f34687c803dd4
bobbygata/cti110
/M2HW1_Crawford.py
463
3.828125
4
# CTI-110 # M2HW1 - Distance Traveled # Robert Crawford # 9/6/2017 # speed, distanceAfter6, distanceAfter10, distanceAfter15 speed = 70 time = 6 time2 = 10 time3 = 15 distanceAfter6 = speed * time distanceAfter10 = speed * time2 distanceAfter15 = speed * time3 print ("The total miles at 6 hour is" , distanceAfter6) print ("The total miles at 10 hour is" , distanceAfter10) print ("The total miles at 15 hour is" , distanceAfter15)
9c817c94d0040b5e23223848d95b21f3f0b4ab63
qeedquan/challenges
/codeforces/1213A-chips-moving.py
1,734
4.15625
4
#!/usr/bin/env python """ You are given n chips on a number line. The i-th chip is placed at the integer coordinate xi. Some chips can have equal coordinates. You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: Move the chip i by 2 to the left or 2 to the right for free (i.e. replace the current coordinate xi with xi−2 or with xi+2); move the chip i by 1 to the left or 1 to the right and pay one coin for this move (i.e. replace the current coordinate xi with xi−1 or with xi+1). Note that it's allowed to move chips to any integer coordinate, including negative and zero. Your task is to find the minimum total number of coins required to move all n chips to the same coordinate (i.e. all xi should be equal after some sequence of moves). Input The first line of the input contains one integer n (1≤n≤100) — the number of chips. The second line of the input contains n integers x1,x2,…,xn (1≤xi≤10^9), where xi is the coordinate of the i-th chip. Output Print one integer — the minimum total number of coins required to move all n chips to the same coordinate. Examples input 3 1 2 3 output 1 input 5 2 2 2 3 3 output 2 Note In the first example you need to move the first chip by 2 to the right and the second chip by 1 to the right or move the third chip by 2 to the left and the second chip by 1 to the left so the answer is 1. In the second example you need to move two chips with coordinate 3 by 1 to the left so the answer is 2. """ def coins(a): c = 0 for v in a: if v%2 == 1: c += 1 return min(c, len(a)-c) def main(): assert(coins([1, 2, 3]) == 1) assert(coins([2, 2, 2, 3, 3]) == 2) main()
83d64ee15ae56ecbd6fe764ddd3c2dd651b22729
lsDantas/Hacker-s-Guide-to-Neural-Networks-in-Python
/backprop_practice.py
1,012
4.09375
4
import math # Multiply Gate x = a * b # and given gradient on x(dx), we saw that in backprop we would compute: da = b * dx db = a * dx # Add Gate x = a + b da = 1.0 * dx db = 1.0 * dx # Let's compute x = a + b + c in two steps: q = a + b # Gate 1 x = q + c # Gate 2 # Backward Pass: dc = 1.0 * dx # Backprop Gate 2 dq = 1.0 * dx da = 1.0 * dq # Backprop Gate 1 db = 1.0 * dq x = a + b + c da = 1.0 * dx db = 1.0 * dx dc = 1.0 * dx # Combining gates x = a * b + c # Given dx, backprop in-one-sweep would be => da = b * dx db = a * dx dc = 1.0 * dx def sig(x): return 1 / (1 + math.exp(-x)) # Let's do our neuron in two steps: q = a*x + b*y + c f = sig(q) # Sig is the sigmoid function # and now the backward pass, we are given df, and: df = 1 dq = (f * (1 - f)) * df # and now we chain it to the inputs da = x * dq dx = a * dq dy = b * dq db = y * dq dc = 1.0 * dq x = a*a + b*b + c*c da = 2 * a * dx db = 2 * b * dx dc = 2 * c * dx x = math.pow(((a * b + c) * d), 2) #pow(x,2) squares the input JS
d8d642d084f1fac10004c216fab9ad1b3599fcd6
rhiroyuki/46SimplePythonExercises
/exercise04.py
378
3.953125
4
""" Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise. """ def isVowel(character): return character in 'aeiou' def isVowel2(character): if character in 'aeiou': return True else: return False # tests if __name__ == "__main__": print(isVowel('a')) print(isVowel('b'))
f9caadf0ff0f2e1f1a8957b9337336a285cf5060
CodecoolWAW20171/web-askmate-project-sejsmogrzmoty
/ui.py
2,891
3.71875
4
# Note: no safeguard against wide columns - terminals wrap long lines. # If use suspect wide column be sure to stretch terminal beforehand or # run fullscreen def print_table(table, headers={}, head_form=['<'], cell_form=['<']): """ Prints table with data. Args: table (list): list of dictionaries to display headers (dict): dict or better OrderedDict containing keys to table dictionaries and corresponding table headers head_form (list): list with headers formatting for str.format funciton celll_form (list): list with column cells formatting for str.format funciton Returns: This function doesn't return anything it only prints to console. """ # formats sep_s = '|' mid_sep = ' '+sep_s+' ' left_sep = sep_s+' ' right_sep = ' '+sep_s seps = (left_sep, mid_sep, right_sep) # handle empty table if len(table) < 1: if headers: table = [{key: '' for key in headers}] else: return False headers = {key: (key if key not in headers else headers[key]) for key in table[0]} # fill with default values if empty n_cols = len(headers) n_rows = len(table) head_form = fill_empty(head_form, n_cols, head_form[0]) cell_form = fill_empty(cell_form, n_cols, cell_form[0]) # column widths coll_widths = [max(str_len(row[key]) for row in table) for key in headers] # final widths considering headers width widths = [max(str_len(header), coll_widths[c]) for c, header in enumerate(headers.values())] total_width = sum(widths) + len(left_sep) + len(mid_sep)*(n_cols-1) + len(right_sep) # formatting h_form = [head_form[w]+str(width) for w, width in enumerate(widths)] c_form = [cell_form[w]+str(width) for w, width in enumerate(widths)] # line separator line_seperator = ['-'*(w+2) for w in widths] line_seperator.insert(0, '') line_seperator.append('') line_seperator = sep_s.join(line_seperator) # actual printing print('/', '-'*(total_width-2), '\\', sep='') if any(headers.values()): print_row(headers, headers, n_cols, h_form, seps) print('\n'+line_seperator) for r, row in enumerate(table): print_row(row, headers, n_cols, c_form, seps) if r < n_rows-1: print() print() print('\\', '-'*(total_width-2), '/', sep='') def print_row(row, cols, n_cols, form, seps): print(seps[0], end='') for c, col in enumerate(cols): print("{:{}}".format(str(row[col]), form[c]), end='') if c < n_cols-1: print(seps[1], end='') else: print(seps[2], end='') def str_len(string_): return len(str(string_)) def fill_empty(list_, length, default): n = length - len(list_) for _ in range(n): list_.append(default) return list_
4b7c8b5939824bb66a5cf6e5704ac858e6158b35
123wtywty/ccc-2004-j
/2014/j2.py
209
3.765625
4
input() str1 = input() v_a = 0 v_b = 0 for i in str1: if i == 'A': v_a += 1 elif i == 'B': v_b += 1 if v_a > v_b: print('A') elif v_a < v_b: print('B') else: print('Tie')
e3a2a93ae901a793c00bfcb123388dfb011f910a
shen-huang/selfteaching-python-camp
/19100401/shense01/d3_exercise_calculator.py
677
4.125
4
def add(x,y): return x + y def subtract(x,y): return x - y def multiply(x,y): return x * y def divide(x,y): return x / y print("选择运算方式:") print("1、+") print("2、-") print("3、*") print("4、/") num1 = int(input("输入第一个数字:")) choice = input("输入运算器选择(1/2/3/4):") num2 = int(input("输入第二个数字:")) if choice == '1': print(num1,"+",num2,"=",add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=",subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=",multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=",divide(num1,num2)) else: print("非法输入")
851c0d5f833fbb9985c91e8dd24a528cafe9ee78
wk968/Tarot
/tarot.py
948
3.65625
4
import random import json class Card: def __init__(self,suit,val): self.suit = suit self.value = val def show(self): return ("{} of {}".format(self.value,self.suit)) class Deck: def __init__(self): self.cards = [] self.build() def build(self): for a in ["Cups","Pentacles","Swords","Wands","Major"]: if a=="Major": for b in range (0,22): self.cards.append(Card(a,b)) else: for b in range (1,15): self.cards.append(Card(a,b)) def show(self): for c in self.cards: c.show() def shuffle(self): for i in range(len(self.cards)-1, 0, -1): r = random.randint(0,i) self.cards[i], self.cards[r] = self.cards[r], self.cards[i] def draw(self): card = self.cards.pop() return card.show()
3fe9c22ab3812a9a350bca53cc59e793cf838919
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/hnkluk001/question1.py
691
4.09375
4
# Luke Henkeman # HNKLUK001 # Assignment 2, Question 1, CSC1015F # 7 March 2014 def leapyear(): input_year = eval(input("Enter a year:\n")) leap400int = input_year // 400 leap400nml = input_year / 400 leap4int = input_year // 4 leap4nml = input_year / 4 leap100int = input_year // 100 leap100nml = input_year / 100 if(leap400int == leap400nml): print(input_year,"is a leap year.") elif(leap4int == leap4nml): if(leap100int != leap100nml): print(input_year,"is a leap year.") else: print(input_year,"is not a leap year.") else: print(input_year,"is not a leap year.") leapyear()
835eef481c878855a0658c6f182866d945326cc5
cham0919/Algorithm-Python
/프로그래머스/탐욕법/큰_수_만들기.py
731
3.59375
4
"""https://programmers.co.kr/learn/courses/30/lessons/42883?language=python3""" numberList = [ "1924", "1231234", "4177252841", "1000" ] kList = [ 2, 3, 4, 1 ] returnList = [ "94", "3234", "775841", "100" ] def solution(number, k): answer = [] cnt = k for n in number: while len(answer) > 0 and answer[-1] < n and cnt > 0: cnt -= 1 answer.pop() answer.append(n) result = '' for i in range(len(number) - k): result += answer[i] return result for n, k, r in zip(numberList, kList ,returnList): result = solution(n, k) if result == r: print("성공") else: print("실패")
8fc056b5b10d5e0ff2e3506dfc61900c648b9e84
shae128/CodeLearning
/Python/PythonCertification/Exersices/PCA_5_5_10.py
347
3.9375
4
class ThisIsClass: def __init__(self, val): self.val = val ob1 = ThisIsClass(0) ob2 = ThisIsClass(2) ob3 = ob1 ob3.val += 1 print(ob1 is ob2) print(ob2 is ob3) print(ob3 is ob1) print(ob1.val, ob2.val, ob3.val) str1 = "Mary had a little " str2 = "Mary had a little lamb" str1 += "lamb" print(str1 == str2, str1 is str2)
0f54ad7dfac2458f054f6dad3673285acf634ae0
atulya-kairati/100_days_of_code
/day_63/sql_databases/flask_sql_alchemy_basics.py
2,119
3.5
4
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///new_book_database.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class Book(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(250), unique=True, nullable=False) author = db.Column(db.String(250), nullable=False) rating = db.Column(db.Float, nullable=False) def __repr__(self): return f'"<{self.id}> {self.title} - {self.author}"' def get_dict(self): return { "id": self.id, "title": self.title, "author": self.author, "rating": self.rating, } db.create_all() # creating new record db.session.add(Book(id=1, title="ABC", author="DEF", rating=5.96)) db.session.add(Book(title="OMG", author="DEF", rating=5.96)) # id will be autogenerated db.session.add(Book(title="OMG1", author="DEF", rating=7.96)) # id will be autogenerated db.session.add(Book(title="OMG2", author="DEF", rating=4.96)) # id will be autogenerated db.session.commit() # read all books = db.session.query(Book).all() print(books) # or books = Book.query.all() print(books) # read a particular record my_books = Book.query.filter_by(title='ABC').all() my_book = Book.query.filter_by(title='ABC').first() print(my_book) print(my_books) # updating my_book = Book.query.filter_by(title='ABC').first() my_book.title = 'ABC-2' db.session.commit() books = Book.query.all() print(books) # update a record by Primary key book_id = 2 my_book = Book.query.get(book_id) my_book.title = 'OMGLOLO' db.session.commit() books = Book.query.all() print(books) # deleting by id book_id = 1 my_book = Book.query.get(book_id) db.session.delete(my_book) db.session.commit() books = Book.query.all() print(books) # ordering books_ranking = Book.query.order_by(Book.rating.desc()) # books_ranking = Book.query.order_by(Book.rating.asc()) # for ascending c = db.session.query(Book).count() # count row for book in books_ranking: print(book.get_dict())
a69135fecce7531a572e9586bbb217c582ea16f0
Mekhdievm/homework
/1/ex4.py
397
3.515625
4
def ex4(width, length, height): if (width < 15) and (length < 15) and (height < 15): return "Коробка №1" elif length > 200: return "Упаковка для лыж" elif (width > 15 and width < 50) or (length > 15 and length < 50) or (height > 15 and height < 50) : return "Коробка №2" else: return "Стандартная коробка №3" print(ex4(10,205,5))
1e4ea92627ee155981eccd241e36b4585ab26610
anobhama/Intern-Pie-Infocomm-Pvt-Lmt
/Python Basics/q23_vowelConstanont.py
312
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 9 00:27:35 2020 @author: Anobhama """ #(Q23)WAP to input a character and check whether it is a vowel or consonant. ch=input("Enter a character : ") if ch in ['a','e','i','o','u','A','E','I','O','U']: print("It is a vowel") else: print("It is a consonant")
7aa11cf30f3a4bf5b75776c66d9025f5584e67e5
kmdubs/ProjEuler
/14.py
464
3.703125
4
def seq(num): count = 1 while num != 1: if num % 2 == 0: num = num/2 else: num = 3*num+1 count += 1 return count num = [] i = 0 while i < 1000000: num.append(i+1) i += 1 maxChain = 0 chainNum = 0 chain = 0 for x in num: if x % 1000 == 0: print x chain = seq(x) if chain > maxChain: maxChain = chain chainNum = x print "The longest chain has " + str(maxChain) + " number of chars." print "The starting number was: " + str(chainNum)
bd0526850e38ddd1df9d821abc6278a708797a10
centos-zhb/PythonPractice
/Python基本数据类型/Dictionary.py
1,031
3.8125
4
# -*- coding:utf-8 -*- ''' 字典(Dictionary)是python中的另一个非常有用的内置数据类型。 列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。 字典是一种映射类型,字典用"{ }"标识,它是一个无序的键(key) : 值(value)对集合。 键(key)必须使用不可变类型。 在同一个字典中,键(key)必须是唯一的。 1、字典是一种映射类型,它的元素是键值对。 2、字典的关键字必须为不可变类型,且不能重复。 3、创建空字典使用 { }。 ''' dict = {} dict['one'] = "1 - 菜鸟教程" dict[2] = "2 - 菜鸟工具" tinydict = {'name':'runoob','code':1,'site':'www.runoob.com'} print (dict['one']) # 输出键为 'one' 的值 print (dict[2]) # 输出键为 2 的值 print (tinydict) # 输出完整的字典 print (tinydict.keys()) # 输出所有键 print (tinydict.values()) # 输出所有值
8e1c545d1c5642e30571f4375369433df08bfc15
Hajer29/BikeShareData
/BikeShareData.py
6,554
3.96875
4
import time import pandas as pd import numpy as np CITY_DATA = { 'washington': 'washington.csv', 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv' } def get_filters(): print('Hello! Let\'s explore some US bikeshare data!') # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs while True : city = input('Would you like to see data for Chicago, New York, or Washington?').lower() if city not in ('chicago', 'new York','washington'): print ( ' Be sure you enter vaild city with Capitile letter' ) continue else: break # TO DO: get user input for month (all, january, february, ... , june) while True : month = input('Which month All - January, February, March, April, May, or June?').lower() if month in ('all', 'january', 'february', 'march', 'april', 'may', 'june' ): break else: print ( ' Be sure you enter vaild month with Capitile letter ' ) continue # TO DO: get user input for day of week (all, monday, tuesday, ... sunday) while True : day = input('Which day All - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday?').lower() if day not in ('all','monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'): print ( ' Be sure you enter vaild day with Capitile letter ' ) continue else: break print('-'*40) return city, month, day def load_data(city, month, day): # load data file into a dataframe df = pd.read_csv(CITY_DATA[city]) # convert the Start Time column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # extract month and day of week from Start Time to create new columns df['month'] = df['Start Time'].dt.month df['day'] = df['Start Time'].dt.weekday_name # filter by month if applicable if month != 'All': # use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 # filter by month to create the new dataframe df = df[df['month'] == month] # filter by day of week if applicable if day != 'All': # filter by day of week to create the new dataframe df = df[df['day'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # TO DO: display the most common month common_month= df['month'].mode()[0] print('Common Month:',common_month) # TO DO: display the most common day of week common_day= df['day'].mode()[0] print('Common Day:',common_day) # extract hour from the Start Time column to create an hour column df['hour'] = df['Start Time'].dt.hour # TO DO: display the most common start hour popular_hour = df['hour'].mode()[0] print('Popular Hour:',popular_hour) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # TO DO: display most commonly used start station popular_start_station=df["Start Station"].mode()[0] print (popular_start_station) # TO DO: display most commonly used end station popular_end_station=df["End Station"].mode()[0] print (popular_end_station) # TO DO: display most frequent combination of start station and end station trip frequent_combination= df.groupby(['Start Station','End Station']).count().idxmax().head(1) print('most frequent combination of start station and end station trip : \n',frequent_combination) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() print('start time',start_time) # TO DO: display total travel time total_travel_time = df['Trip Duration'].count() print('total travel time',total_travel_time) # TO DO: display mean travel time mean_travel_time = df['Trip Duration'].mean() print('mean travel time',mean_travel_time) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types user_types = df['User Type'].value_counts() print('user_types:', user_types) # TO DO: Display counts of gender try: Gender = df['Gender'].value_counts() print('Gender:\n',Gender) except KeyError : print ( 'Gender: \nsorry no Gender data for this city') # TO DO: Display earliest, most recent, and most common year of birth try: earliest = df['Birth Year'].max() m_recent = df['Birth Year'].min() common_year = df['Birth Year'].mode() print ('Earliest year of birth:',earliest,'\n most recent year of birth:',m_recent,'\n common year of birth:',common_year) except KeyError : print ( 'birth of yesr: \nsorry no data of birth of yesr for this city') print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) show_data = input('\nWould you like to see the raw data? Enter yes or no.\n') start = 0 end = 5 while show_data.lower() == 'yes': print(df.iloc[start:end]) show_data1 = input('\nWould you like to see the raw data again? Enter yes or no.\n') if show_data1.lower() == 'yes': start+= 5 end += 5 else: break restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
378ac430b3aee16d342f6409adcb12dc73780e2a
dhumindesai/Problem-Solving
/educative/modified_binary_search/search_range.py
1,339
3.59375
4
def search_range(nums, target): result = [-1, -1] left = 0 right = len(nums) - 1 mid = -1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: result = [mid, mid] break elif target > nums[mid]: left = mid + 1 else: right = mid - 1 left_start, left_end = 0, mid - 1 while left_start <= left_end: left_mid = (left_start + left_end) // 2 if nums[left_mid] == target and left_mid < result[0]: result[0] = left_mid left_end = left_mid - 1 continue elif target > nums[left_mid]: left_start = left_mid + 1 else: left_end = left_mid - 1 right_start, right_end = mid + 1, len(nums) - 1 while right_start <= right_end: right_mid = (right_start + right_end) // 2 if nums[right_mid] == target and right_mid > result[1]: result[1] = right_mid right_start = right_mid + 1 continue elif target > nums[right_mid]: right_start = right_mid + 1 else: right_end = right_mid - 1 return result # print(search_range([5,7,7,8,8,10], 8)) # print(search_range([1,2,2], 2)) print(search_range([1,1,1,1,1,1,2,3,4,4,5,5,5,6,7,8,8,8,8], 8))
4648c6272ba7630b4f8a02d493353cf47fd8806f
dong-pro/fullStackPython
/p1_basic/day01_07base/day02/03_while循环.py
1,434
3.578125
4
# 数数 1-100 # count = 1 # while count < 101: # print(count) # count = count + 1 # 让用户一直去输入内容, 并打印. 直到用户输入q的时候退出程序 # while True: # content = input('请输入一句话,(输入q退出程序):') # if content == 'q': # break # 打断. 终止当前本层循环 # print(content) # flag = True # while flag: # content = input('请输入一句话,(输入q退出程序):') # if content == 'q': # flag = False # 打断. 终止当前本层循环 # print(content) # else: # print('123') # while True: # content = input('请输入一句话,(输入q退出程序):') # if content == 'q': # continue # 停止当前本次循环. 继续执行下一次循环 # print(content) # break和continue的区别: break是彻底的停止掉当前层循环. continue停止当前本次循环,继续执行下一次循环 # count = 1 # while count <= 10: # if count == 4: # count = count + 1 # continue # 用来排除一些内容 # print(count) # count = count + 1 # 必须要写 # count = 1 # while count <= 20: # if count == 10: # break # 不会触发else的执行, while...else...是一个整体. break的时候彻底的停止这个整体 # print(count) # count = count + 1 # else: # 当上面的条件不成立的时候执行这个else中的代码 # print('数完了')
a8ad7437bc1bf66cbd87eb639142e9e1e713a88d
DennisSnijder/HU-PROG-1
/Lesson6/pe6_2.py
286
3.6875
4
list_of_strings: list = eval(input("Give in a list seperated by comma's : ")) if len(list_of_strings) < 10: print('The list should be at least 10 words long.') exit(1) newList: list = [] for i in list_of_strings: if len(i) == 4: newList.append(i) print(newList)
120b4f9e700ec23b47b655ef5689e5517f98e128
Nelsonkioko/password-locker
/credentials_test.py
1,068
3.859375
4
import unittest from credentials import Credential class TestCredentials(unittest.TestCase): """ Class to perform credentials test """ def setUp(self): """ This function will create a new instance of Password before each test """ self.new_password = Credential("twitter", "kioko", "Giz", "[email protected]", "0777770089") def test_new_password(self): """ Test whether a new password is instantiated correctly """ self.assertEqual(self.new_password.site, "twitter") self.assertEqual(self.new_password.username, "kioko") self.assertEqual(self.new_password.password, "Giz") self.assertEqual(self.new_password.email, "email") self.assertEqual(self.new_password.number, "number") def test_save_new_passssword(self): """ Check whether the new password is added to the passwords array """ self.new_password.create_password() self.assertEqual(len(Credential.passwords), 1) if __name__ == "__main__": unittest.main()
0344773c3c87fa316cf07630a6d997087917e332
bharatgupta99/beginner-python-projects
/99 beer bottles.py
616
3.703125
4
numbers = [x for x in range(99, -1, -1)] for i in numbers: if i == 1 : l1 = str(i) + ' bottle of beer on the wall, ' + str(i) + ' bottle of beer.' l2 = 'Take one down and pass it around, ' + 'no more' + ' bottles of beer on the wall.' elif i == 0: l1 = 'No more bottles of beer on the wall, no more bottles of beer.' l2 = 'Go to the store and buy some more, 99 bottles of beer on the wall.' else: l1 = str(i) + ' bottles of beer on the wall, ' + str(i) + ' bottles of beer.' l2 = 'Take one down and pass it around, ' + str(i-1) + ' bottles of beer on the wall.' print(l1 + '\n' + l2 + '\n')
99230579033b5fa134816e1303b342cd51d3fefc
parmarjitendra/Python
/package01/Practical28.py
150
4.1875
4
str1 = input("Enter any String : ") if ( str1[::-1] == str1 ) : print( str1 , " is a palindrome" ) else: print( str1 , " is not palindrome")
1f9ee06b5e532ef1eb4491d42ad5ce9a4d1b5973
Agata999/exercises
/zipping and enumerating lists.py
284
3.6875
4
projects = ['Brexit', 'Nord Stream', 'US Mexico Border'] leaders = ['Theresa May', 'Wladimir Putin', 'Donald Trump and Bill Clinton'] dates = ['2016-06-23', '2016-08-29', '1994-01-01'] for n, (p, d, l) in enumerate(zip(projects, dates, leaders)): print(f'{n+1}. The leader of {p} started {d} is {l}')
11ba83bdd3a15fe378b1f3fe88d3157431492af0
dashuai888/Python_Study
/Python_Study/dashuai/chapter02/1-AdvancedFeatures/demo3.py
1,945
4.25
4
#!/usr/bin/env python3 # --*-- coding: utf-8 --*-- """ 迭代 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)。 """ # list这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代: d = {'a': 1, 'b': 2, 'c': 3} for key in d: print(key) # a # c # b # 因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。 # 默认情况下,dict迭代的是key。如果要迭代value,可以用 for value in d.values(): print(value) # 如果要同时迭代key和value,可以用 for k, v in d.items(): print(k, v) # 由于字符串也是可迭代对象,因此,也可以作用于for循环: for ch in 'ABC': print(ch) # A # B # C # 所以,当使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。 # 那么,如何判断一个对象是可迭代对象呢? # 方法是通过 collections 模块的 Iterable 类型判断: from collections import Iterable isinstance('abc', Iterable) # str是否可迭代 # True isinstance([1, 2, 3], Iterable) # list是否可迭代 # True isinstance(123, Iterable) # 整数是否可迭代 # False # 最后一个小问题,如果要对list实现类似Java那样的下标循环怎么办? # Python 内置的 enumerate 函数可以把一个list变成索引 - 元素对,这样就可以在for循环中同时迭代索引和元素本身: for i, value in enumerate(['A', 'B', 'C']): print(i, value) # 0 A # 1 B # 2 C # 上面的for循环里,同时引用了两个变量,在Python里是很常见的,比如下面的代码: for x, y in [(1, 1), (2, 4), (3, 9)]: print(x, y) # 1 1 # 2 4 # 3 9
5298cd42f14ce4459272b7c3e0bdabddc8fb0339
AshurMotlagh/CECS-100
/Lab 21-2.py
327
4.0625
4
pi=3.14 def main(): rad=float(input("Enter the radius of the circle: ")) area=find_area(rad) print("Value of PI inside main is: ", pi) print("Area of the circle = ", area) print("Area of the circle upto 2 decimal points = ", format(area, '.2f')) def find_area(a): area=pi*(a**2) return area main()
0053d5b50d250f17e8b1aea7fd69aea71bf826e4
BJV-git/Data_structures_and_Algorithms
/Data_structures_and_Algorithms/arrays/set_matrix_zeroes.py
692
3.671875
4
# for constant space solution: do a dfs at every zero we encounter # logic is encode decode : nwo here we are encoding in terms pf its row and column to mark if thats z zero ro w or column def zeromatrix(matrix): row,col,first = len(matrix), len(matrix[0]), not all(matrix[0]) for i in range(1,row): for j in range(col): if matrix[i][j]==0: matrix[0][j]= matrix[i][0] = 0 for i in range(1,row): for j in range(col-1,-1,-1): # if there is first one zero, then entire row gets messed up as itis acting as ref if matrix[i][0] ==0 or matrix[0][j]==0: matrix[i][j]=0 if first: matrix[0] = [0]*col
947f8075cff6da338df8a679f891a3cefc1e3e52
LeRoiFou/mooc_sequences
/ex012_matrix.py
1,338
4.28125
4
""" Écrire une fonction print_mat(M) qui reçoit une matrice M en paramètre et affiche son contenu. Les éléments d’une même ligne de la matrice seront affichés sur une même ligne, et séparés par une espace, les éléments de la ligne suivante étant affichés sur une nouvelle ligne. Exemple L’appel suivant de la fonction : print_mat([[1, 2], [3, 4], [5, 6]]) doit afficher : 1 2 3 4 5 6 Consignes Important : Afin de permettre à UpyLaB de tester votre fonction, votre code contiendra également, après le code de la définition de la fonction print_mat, les instructions suivantes : ma_matrice = eval(input()) print_mat(ma_matrice) Si la matrice vide [] est passée en argument , la fonction affiche une ligne vide. Dans cet exercice, la présence d’espaces en fin de ligne ne sera pas sanctionnée. Par contre, veillez à ce qu’il n’y ait pas de ligne supplémentaire. Éditeur : Laurent REYNAUD Date : 10-08-2020 """ def print_mat(M): if not M: print("") else: for i in M: Stri = " ".join(str(_) for _ in i) print(Stri) print("Saisir : [[1, 2], [3, 4], [5, 6]]") print("Résultat attendu :") print("1 2") print("3 4") print("5 6") ma_matrice = eval(input()) print_mat(ma_matrice)
c35c3e74eade3ca2ae6ace20cbf32fdf6bdfec06
gabriellaec/desoft-analise-exercicios
/backup/user_230/ch35_2020_04_06_20_14_19_245411.py
153
3.90625
4
lista=[] while num!=0: num=int(input("Escolha um número:") lista.append(num) if num==0: soma=sum(lista) print (soma)
56bdc8240f83da6470785d5eb26537aea27c4214
comeeasy/study
/python/sw-academy-python2/list_tuple/prac17.py
317
3.765625
4
''' 두 개의 리스트 [1,3,6,78,35,55]와 [12,24,35,24,88,120,155]를 이용해 양쪽 리스트에 모두 있는 항목을 리스트로 반환하는 프로그램을 작성하십시오. ''' list1, list2 = [1,3,6,78,35,55], [12,24,35,24,88,120,155] print([num1 for num1 in list1 for num2 in list2 if num1 == num2])
7ce013fc79994d116d8e487fe2f0b7af7876bd68
Suwadith/Python-Tutorial
/Introduction-To-Python/37_files_and_directories.py
613
4.09375
4
from pathlib import Path path = Path("ecommerce") #if the Path is left empty Path(), it uses the current directory print(path.exists()) #Check if a folder exists #path.mkdir() - used for creating directories #path.rmdir() - used for deleting directories #path.glob('*.*') - returns all the files within the current directory #path.glob('*') - returns all the files within the current directory including all the directories #path.glob('*.py') - returns all the python files within the current directory for file in path.glob('*.py'): print(file) path = Path() for file in path.glob('*'): print(file)
9fe0321247d755958941a235e7e437c3700980ae
Feymus/AutoCaras
/Model/Sujeto.py
1,722
3.703125
4
''' Clase utiizada para representar cada sujeto junto a su lista de fotografias Created on Aug 16, 2017 @author: Michael Choque @author: Nelson Gomez @author: William Espinoza ''' class Sujeto(object): """ Clase Sujeto Esta clase es la representacion abstracta de un sujeto """ def __init__(self, nombre): ''' Constructor de la clase El constructor inicializa la lista de fotos de un sujeto y le asigna un nombre @param nombre Nombre de un sujeto ''' self.nombre = nombre self.lista_fotos = [] def agregar_foto(self, foto): ''' Metodo agregar_foto Metodo simple de agregar a la lista de fotos una foto @param foto matriz representando una imagen ''' self.lista_fotos.append(foto) def get_lista_fotos(self): ''' Metodo get_lista_fotos Metodo get para la lista de fotos de un sujeto @return una lista de matrices ''' return self.lista_fotos def get_nombre(self): ''' Metodo get_lista_fotos Metodo get para la lista de fotos un sujeto ''' return self.nombre def set_lista_fotos(self, plista_fotos): ''' Metodo set_lista_fotos Metodo set para la lista de fotos un sujeto ''' self.lista_fotos = plista_fotos def __eq__(self, otro): ''' Metodo __eq__ Overwrite del metodo __eq__ de python, para poder hacer comparaciones segun nombre ''' if otro is None: return False if not isinstance(otro, Sujeto): return False if not otro.nombre == self.nombre: return False return True
c891f6f37594b4a511c6744337956dea5478520e
daviddayan/david-dayan_EP2
/jogo da forca.py
8,587
3.625
4
# -*- coding: utf-8 -*- from random import choice import time f = open("entrada.txt", encoding="utf-8") linhas = f. readlines() n=[] for c in linhas: c2=c.strip() if c2!="": n.append(c2) #def desenha(tartaruga, n): # abre janela do turtle,desenha a forca while len(n)>0: chutes=0 acertos=0 erros=0 import turtle # Usa a biblioteca de turtle graphics window = turtle.Screen() # cria uma janela window.bgcolor("lightblue") window.title("JOGO DA FORCA") window.clear() tartaruga = turtle.Turtle() # Cria um objeto "desenhador" tartaruga.speed(5) # define a velocidade tartaruga.width("8") tartaruga.penup() # Remova e veja o que acontece tartaruga.setpos(-50,0) tartaruga.pendown() tartaruga.color("black") dist = 200 angulo = 90 for i in range(1): tartaruga.left(angulo) # Vira o angulo pedido tartaruga.forward(dist) # Avança a distancia pedida #import turtle # Usa a biblioteca de turtle graphics #window = turtle.Screen() # cria uma janela window.bgcolor("lightblue") window.title("Poligonos") #tartaruga = turtle.Turtle() # Cria um objeto "desenhador" tartaruga.right(90) tartaruga.speed(5) # define a velocidade tartaruga.penup() # Remova e veja o que acontece #tartaruga.setx() #tartaruga.sety() #tartaruga.setpos(-50,200) tartaruga.pendown() tartaruga.color("black") dist = 100 angulo = 0 for i in range(1): tartaruga.left(angulo) # Vira o angulo pedido tartaruga.forward(dist) # Avança a distancia pedida #import turtle # Usa a biblioteca de turtle graphics #window = turtle.Screen() # cria uma janela window.bgcolor("lightblue") window.title("Poligonos") #tartaruga = turtle.Turtle() # Cria um objeto "desenhador" tartaruga.right(0) tartaruga.speed(5) # define a velocidade tartaruga.penup() # Remova e veja o que acontece tartaruga.pendown() #tartaruga.color("red") dist = 60 angulo = 270 for i in range(1): tartaruga.left(angulo) # Vira o angulo pedido tartaruga.forward(dist) # Avança a distancia pedida escolha = choice(n) n.remove(escolha) tam=len(escolha) import turtle # Usa a biblioteca de turtle graphics #window = turtle.Screen() # cria uma janela window.bgcolor("lightblue") window.title("JOGO DA FORCA") tartaruga = turtle.Turtle() # Cria um objeto "desenhador" tartaruga.speed(5) # define a velocidade tartaruga.penup() # Remova e veja o que acontece tartaruga.setpos(0,-15) tartaruga.pendown() tartaruga.color("red") tartaruga.width("2") dist = 15 angulo = 0 for c in escolha: if c!= " ": tartaruga.left(angulo) # Vira o angulo pedido tartaruga.forward(dist) # Avança a distancia pedida else: tartaruga.penup() tartaruga.left(angulo) # Vira o angulo pedido tartaruga.forward(dist) # Avança a distancia pedida tartaruga.pendown() tartaruga.penup() tartaruga.forward(5) tartaruga.pendown() #p=escolha.index(letra) x=dist def boneco(): if erros==1: tartaruga.penup() tartaruga.setpos(50,95) tartaruga.pendown() tartaruga.color("red") dist = 1 angulo = 180-((150-2)*180)/150 for i in range(150): tartaruga.left(angulo) # Vira o angulo pedido tartaruga.forward(dist) # Avança a distancia pedida if erros==2: tartaruga.penup() tartaruga.setpos(50,95) tartaruga.pendown() tartaruga.setpos(50,30) if erros==3: tartaruga.penup() tartaruga.setpos(50,85) tartaruga.pendown() tartaruga.setpos(20,60) if erros==4: tartaruga.penup() tartaruga.setpos(50,85) tartaruga.pendown() tartaruga.setpos(80,60) if erros==5: tartaruga.penup() tartaruga.setpos(50,30) tartaruga.pendown() tartaruga.setpos(20,0) if erros==6: tartaruga.penup() tartaruga.setpos(50,30) tartaruga.pendown() tartaruga.setpos(80,0) def desenhar_letra(): n=0 for i in range(len(escolha)): if letra == escolha[i]: tartaruga.penup() tartaruga.setpos((0+(i*20)),-10) tartaruga.pendown() tartaruga.write(letra , font = ('Arial',14,'normal')) n+=1 if letra == "A" and escolha[i] == "Ã" or escolha[i]=="Â" : tartaruga.penup() tartaruga.setpos((0+(i*20)),-10) tartaruga.pendown() tartaruga.write(escolha[i] , font = ('Arial',14,'normal')) n+=1 if letra == "E" and escolha[i] == 'É' or escolha[i]=='Ê': tartaruga.penup() tartaruga.setpos((0+(i*20)),-10) tartaruga.pendown() tartaruga.write(escolha[i] , font = ('Arial',14,'normal')) n+=1 if letra == 'O' and escolha[i] == 'Ó' or escolha[i]=='Ô': tartaruga.penup() tartaruga.setpos((0+(i*20)),-10) tartaruga.pendown() tartaruga.write(escolha[i] , font = ('Arial',14,'normal')) n+=1 if letra == 'I' and escolha[i] == 'Í': tartaruga.penup() tartaruga.setpos((0+(i*20)),-10) tartaruga.pendown() tartaruga.write(escolha[i] , font = ('Arial',14,'normal')) n+=1 return n l=[] Q=("ABCDEFGHIJKLMNOPQRSTUVWXYZ") lista=list(Q) esp=escolha.count(" ") tentativas=0 escolha=escolha.upper() while erros < 6 and acertos < tam-esp: #if acertos < tam-esp: letra = window.textinput("letra", "escolha letra") letra=letra.upper() while letra in l: letra = window.textinput("letra", "escolha letra") letra=letra.upper() while letra not in lista: letra = window.textinput("letra", "escolha letra") letra=letra.upper() l.append(letra) tentativas+=1 #pos=escolha.index(letra) tartaruga.penup() tartaruga.setpos(90,210) tartaruga.color("black") tartaruga.write("chutes errados", font = ("Arial",20,"normal")) if letra not in escolha: chutes+=1 erros+=1 tartaruga.penup() tartaruga.setpos(95+15*chutes,195) tartaruga.color("green") tartaruga.write(letra,font=("Arial",14,"normal")) tartaruga.color("red") boneco() else: acertos+=desenhar_letra() t=[] t.append(tentativas) soma=0 for i in range(len(t)): soma+=t[i] if acertos==tam-esp: tartaruga.penup() tartaruga.color("black") tartaruga.setpos(85,120) tartaruga.write("PARABENS! VOCE ACERTOU A PALAVRA!") time.sleep(4) if erros==6: tartaruga.penup() tartaruga.color("black") tartaruga.setpos(85,120) tartaruga.write("VOCE ERROU A A PALAVRA E ESTA ENFORCADO!") time.sleep(4) window.clear() tartaruga.penup() tartaruga.setpos(-200,70) tartaruga.write("voce acertou:",font=("Arial",26,"normal")) tartaruga.penup() tartaruga.setpos(250,70) tartaruga.write(acertos,font=("Arial",26,"normal")) tartaruga.penup() tartaruga.setpos(-200,35) tartaruga.write("voce errou:",font=("Arial",26,"normal")) tartaruga.penup() tartaruga.setpos(250,35) tartaruga.write(erros,font=("Arial",26,"normal")) tartaruga.penup() tartaruga.setpos(-200,0) tartaruga.write("chutes por palavra certa:",font=("Arial",26,"normal")) tartaruga.penup() tartaruga.setpos(250,0) tartaruga.write(soma/acertos,font=("Arial",26,"normal")) window.exitonclick()
543d628bf554223ab1552a8bd1d9a674936102a8
mgunawan92/Team_Stats_Tool
/application.py
7,418
3.578125
4
# Import from constants.py the players' data to be used within your program. import constants from copy import deepcopy # deepcopy function obtained from https://stackoverflow.com/questions/14204326/how-to-copy-a-dictionary-of-lists # read the existing player data from the PLAYERS constants provided in constants.py # clean the player data without changing the original data # save it to a new collection player_collection = deepcopy(constants.PLAYERS) teams_collection = constants.TEAMS[:] # Create a clean_data function def clean_data(): for player in player_collection: # obtain height slice from each dictionary in list of PLAYERS height = (player["height"][0:2]) # convert height into int per requirements int_height = int(height) # insert converted integer height into each dictionary in player collection player["height"] = int_height # convert experience/inexperienced to bool values per requirements if player["experience"] == "YES": player["experience"] = True elif player["experience"] == "NO": player["experience"] = False # store guardians into guardian list # when cleaning the data, clean the guardian field as well before adding it into your newly created collection, split up the guardian string into a List player['guardians'] = player['guardians'].split(" and ") # Create a balance_teams function def balance_teams(): # create lists for all teams to store values panthers = [] bandits = [] warriors = [] # create lists for both experienced and inexperienced players to store values experienced_players = [] inexperienced_players = [] # sort by experienced/inexperienced and append to corresponding list for player in player_collection: if player["experience"] == True: experienced_players.append(player) elif player["experience"] == False: inexperienced_players.append(player) # append values from both experienced and inexperienced lists into team lists using pop() while experienced_players: panthers.append(experienced_players.pop()) bandits.append(experienced_players.pop()) warriors.append(experienced_players.pop()) while inexperienced_players: panthers.append(inexperienced_players.pop()) bandits.append(inexperienced_players.pop()) warriors.append(inexperienced_players.pop()) teams = [panthers, bandits, warriors] return teams if __name__ == "__main__": # clean data and balance teams (for both number of players and number of experienced/inexperienced players) clean_data() teams = balance_teams() #start while loop for repeated prompts while True: # function for displaying three teams when Option 1 in first prompt is selected def display_teams(): for index, team in enumerate(constants.TEAMS, start=1): print("{}) {}".format(index, team)) print() # function for creating list of experienced players based on selected team def experienced(teams): exp = [] for player in teams: if player["experience"] == True: exp.append(player) return exp # function for creating list of inexperienced players based on selected team def inexperienced(teams): inexp = [] for player in teams: if player["experience"] == False: inexp.append(player) return inexp # function for calculating average height based on selected team def average(teams): total_height = 0 for player in teams: total_height += player["height"] average_height = round(total_height/len(teams)) return average_height # function for displaying team stats within dunder main def display_team_info(team_selection): team_name = teams_collection[int(team_selection)-1] team_selection = teams[int(team_selection) - 1] experienced_players = experienced(team_selection) inexperienced_players = inexperienced(team_selection) average_height = average(team_selection) # creating list for players on team based on team selection names_of_players = [] for player in team_selection: names_of_players.append(player["name"]) players_list = ', '.join(names_of_players) # creating list for guardians corresponding to players on team based on team selection guardians = [] for player in team_selection: guardians += (player["guardians"]) guardian_list = ', '.join(guardians) # print stats print("\n\nTeam: {} Stats".format(team_name)) print("-" * 20) print("Total players: {}".format(len(team_selection))) print("Total experienced: {}".format(len(experienced_players))) print("Total inexperienced: {}".format(len(inexperienced_players))) print("Average height: {} inches".format(average_height)) print("\nPlayers on Team: {}".format(players_list)) print("\nGuardians: {}\n".format(guardian_list)) print("\nBASKETBALL TEAM STATS TOOL") print ("\n---- MENU----\n") print("Here are your choices: \n\n1) Display Team Stats. \n2) Quit") option = input("\nEnter an option > ") if option == "1": print("\n") display_teams() pass # break out of while loop if user decides to exit elif option == "2": print("\nGoodbye\n") break # notify user of invalid response, then repeat loop else: print("\nInvalid Option. Try again.\n") continue # start new while loop once user has selected option 1 while True: team_selection = input("Enter an option > ") if team_selection == "1" or team_selection == "2" or team_selection == "3": display_team_info(team_selection) break else: print("\nThat isn't a valid option, please enter an option corresponding to one of the listed teams.\n ") continue # start new while loop once user has selected finished viewing stats to see if they want to start again while True: continue_or_not = input("\nRestart Stats Tool? (Y/N)\n ") if continue_or_not == "Y" or continue_or_not == "y": exit = "No" break elif continue_or_not == "N" or continue_or_not == "n": exit = "Yes" break else: print("\nNot a valid response. Please try again\n") continue if exit == "Yes": print("\nGoodbye\n") break elif exit == "No": continue else: print("\nInvalid Option\n")
8a2142604cd0d0b71b09f367573f18772cb7b493
jose145/trabajo-05
/impresion 11.py
795
3.78125
4
#input cliente=input("Nombre y Apellidos:") nro_dni=int(input("Ingrese numero de DNI:")) nro_ruc=int(input("Ingese numero de ruc:")) nombre_libro1=input("Ingrese nombre del 1er libro:") nombre_libro2=input("Ingrese nombre del 2do libro:") precio_libro1=float(input("Ingrese Importe del 1ero libro:")) precio_libro2=float(input("Ingrese Importe del 2do libro:")) #procesing total_pagar=(precio_libro1+precio_libro2) #output print("#########################") print("# Libreria Bazar: El Diamante") print("Cliente:", cliente) print("Nro de DNI:", nro_dni) print("Nro de Ruc:",nro_ruc) print("Libro:", nombre_libro1 ," Precio:", precio_libro1) print("Libro:", nombre_libro2 ," Precio:", precio_libro2) print("Total a pagar:", total_pagar)
caa751b7b83175d619d1563abbe88d2fbe99c527
bhavnavarshney/Algorithms-and-Data-Structures
/Python/Binary-Insertion-Sort.py
228
4.25
4
print('****** Binary Insertion Sort **********') # Used to reduced the number of comparison in Insertion Sort O(log n) but shifting the elements after insertion takes O(n) # Complexity : O(nlogn)-> Comparisons and O(n*n) swaps
6a7cfe53fbfe1091f265bce6f3e02d197124f69d
KaloyankerR/Math-Concepts-For-Developers
/Final project/skip_list.py
3,266
3.671875
4
import random class Node(object): def __init__(self, key, level): self.key = key self.forward = [None]*(level+1) # list to hold references to node of different level class SkipList(object): def __init__(self, max_lvl, P): self.MAXLVL = max_lvl # Maximum level for this skip list self.P = P # P is the fraction of the nodes with level i references also having level i+1 references self.header = self.createNode(self.MAXLVL, -1) # create header node and initialize key to -1 self.level = 0 # current level of skip list def createNode(self, lvl, key): # creates a new node n = Node(key, lvl) return n def randomLevel(self): # creates random level for node lvl = 0 while random.random() < self.P and lvl < self.MAXLVL:lvl += 1 return lvl def insertElement(self, key): # inserts given key in the skip list update = [None]*(self.MAXLVL+1) # create update array and initialize it current = self.header for i in range(self.level, -1, -1): while current.forward[i] and \ current.forward[i].key < key: current = current.forward[i] update[i] = current current = current.forward[0] if current == None or current.key != key: # generates a random level for node rlevel = self.randomLevel() if rlevel > self.level: for i in range(self.level+1, rlevel+1): update[i] = self.header self.level = rlevel n = self.createNode(rlevel, key) # create new node with random level generated # inserts the node by rearranging references for i in range(rlevel+1): n.forward[i] = update[i].forward[i] update[i].forward[i] = n # print(f"Successfully inserted key {key}") def deleteElement(self, search_key): update = [None]*(self.MAXLVL+1) # creates an update array and initialize it current = self.header for i in range(self.level, -1, -1): while(current.forward[i] and \ current.forward[i].key < search_key): current = current.forward[i] update[i] = current current = current.forward[0] # If current node is target node if current != None and current.key == search_key: for i in range(self.level+1): if update[i].forward[i] != current: break update[i].forward[i] = current.forward[i] # Removes levels having no elements while(self.level>0 and\ self.header.forward[self.level] == None): self.level -= 1 print("Successfully deleted {}".format(search_key)) def searchElement(self, key): current = self.header for i in range(self.level, -1, -1): while(current.forward[i] and\ current.forward[i].key < key): current = current.forward[i] # reached level 0 and advance reference to # right, which is prssibly our desired node current = current.forward[0] # If current node have key equal to # search key, we have found our target node if current and current.key == key: print("Found key ", key) # Display skip list level wise def displayList(self): print("\n*****Skip List******") head = self.header for lvl in range(self.level+1): print("Level {}: ".format(lvl), end=" ") node = head.forward[lvl] while(node != None): print(node.key, end=" ") node = node.forward[lvl] print("")
cef361309ff4bd750efedf6bf3bfeedee13ad80f
Official21A/GitCommiter
/Tools/Directory.py
729
3.515625
4
# In this file we only have the methods for checking the existence of the directories. import os # This function corrects the path to documents def correct_path(): os.chdir("./Tools") # This functions resets the path from documents def reset_path(): current_pace = os.getcwd() path_dir = os.path.dirname(current_pace) os.chdir(path_dir) # This function checks if the directory that we work on is exist def dir_init(path="./Documents"): if not os.path.exists(path): os.mkdir(path) # This function checks the directory existence inside the documents def dir_search(path="Empty"): if path == "Empty": return False else: dir_init("./Documents/" + path) return True
e64d0bad1926b009686767e08f185969b0f7e190
lcantillo00/python-exercises
/12-ClasesObject/ex2.py
1,935
4.1875
4
class Point: def __init__(self, init_x, init_y): """ Create a new point at the given coordinates. """ self.x = init_x self.y = init_y def get_x(self): return self.x def get_y(self): return self.y def distance_from_origin(self): return ((self.x ** 2) + (self.y ** 2)) ** 0.5 def __repr__(self): return "x=" + str(self.x) + ", y=" + str(self.y) def reflect_x(self, newpoint): newx=newpoint.get_x() newy=-newpoint.get_y() return (newx,newy) p = Point(4, 3) q = Point(3, 5) print(p.reflect_x(q)) # /////////////////////////////////////////////////////////////////////////// class Point: def __init__(self, init_x, init_y): """ Create a new point at the given coordinates. """ self.x = init_x self.y = init_y def get_x(self): return self.x def get_y(self): return self.y def distance_from_origin(self): return ((self.x ** 2) + (self.y ** 2)) ** 0.5 def __repr__(self): return "x=" + str(self.x) + ", y=" + str(self.y) def reflex_x(self): newx=self.x newy=-self.y return (newx,newy) def main(): p=Point(3,5) r=p.reflex_x() print(r) if __name__ == "__main__": main() class Point: def __init__(self, init_x, init_y): """ Create a new point at the given coordinates. """ self.x = init_x self.y = init_y def get_x(self): return self.x def get_y(self): return self.y def distance_from_origin(self): return ((self.x ** 2) + (self.y ** 2)) ** 0.5 def __repr__(self): return "x=" + str(self.x) + ", y=" + str(self.y) def reflex_x(self): newx=self.x newy=-self.y return (newx,newy) def main(): p=Point(3,5) r=p.reflex_x() print(r) if __name__ == "__main__": main()
e54baf7fd3905cf6150bac4c5015a00ff3706a12
Harshada180201/21-DAYS-PROGRAMMING-CHALLENGE-ACES
/DAY_19/Bubble_Sort.py
615
4.3125
4
def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in correct position for j in range(0, n-i-1): # Swap if the element found is greater than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] arr = [64,23,56,21,10,15] print("Given Array is: ",arr) bubbleSort(arr) print ("Sorted array is:") for i in range(len(arr)): print (arr[i]) ''' OUTPUT : Given Array is: [64, 23, 56, 21, 10, 15] Sorted array is: 10 15 21 23 56 64 '''
9294f7cc4687f2184764f1d09d467f5f1eac0182
Dmurav/Data_structures
/linked_list.py
4,108
4.40625
4
class Node: #Класс "узел" со строковой репрезентацией значения def __init__(self, value=None, next=None): """Конструктор - инициализирует экзхемпляр класса""" self.value = value self.next = next def __str__(self): """Строковое представление экземпляра""" return str(self.value) #Метод распечатки связанного списка def print_list(self): """Метод применённый к первому в списке узлу распечатывает весь список пока есть ссылки""" node = self while node: print(node, end=' ') node = node.next #Метод узла для распечатки связанного списка в обратном порядке. def print_backward(self): """Метод начинает с хвоста и распечатывает список от хвоста к голове""" if self.next != None: tail = self.next tail.print_backward() print(self.value, end=' ') #Создаём несколько узлов node1 = Node(1) node2 = Node(2) node3 = Node(3) #Устанавливаем ссылки между узлами, создавая связанный список node1.next = node2 node2.next = node3 #Проверяем атрибуты и методы узла print("Значение узла node1 - " + str(node1.value)) print("Ссылка узла node1 - " + str(node1.next)) print("Строковое представление узла node1 - " + node1.__str__()) print("Связанный список распечатанный в обычном порядке ", end='') node1.print_list() print() print("Связанный список распечатанный в обратном порядке ", end='') node1.print_backward() class LinkedList: #Создаём класс "Связанный список с двумя методами def __init__(self): self.length = 0 self.head = None #Метод распечатки связанного списка def print_list(self): """Метод применённый к экземпляру класса распечатывает весь список пока есть ссылки""" node = self.head while node: print(node, end=' ') node = node.next #Метод обратной распечатки связанного списка def print_backward(self): """Метод начинает устанавливает конечный элемент в качестве головы списка и выполняет распечатку, эксплуатируя метод узла""" if self.head != None: self.head.print_backward() #Метод добавления узла в связанный список def add_first(self, value): """Метод позволяет создавать и добавлять в список узлы со значением. Добавляет узел на место головы""" node = Node(value) node.next = self.head self.head = node self.length += 1 #Создаём экземпляр связанного списка linkedlist = LinkedList() #Вызываем метод и добавляем в начало списка узлы linkedlist.add_first(1) linkedlist.add_first(2) linkedlist.add_first(3) #Вызываем методы класса над экземпляром связанного списка print("\n") print("Применяем метод распечатки листа", end=' ') linkedlist.print_list() print() print("Применяем метод распечатки листа в обратном порядке", end=' ') linkedlist.print_backward()
947b079e6283581c59452a1bb92fb7a95cb744ac
shreya12-hash/Speech-To-Text-and-Text-to-Speech-Conversion
/Speech To Text.py
609
3.828125
4
### An open source contribution by Shreya ### #import the module speech_recognition import speech_recognition as sr r = sr.Recognizer() sound_file = 'C:/Users/Biswas/Downloads/female.wav' file_audio = sr.AudioFile(sound_file) # Now we set the newly read audio file as the source to recognise as speech object with file_audio as source: audio_text = r.record(source) #Then save the recognised text in an object called 'text' for further processing text= r.recognize_google(audio_text) print(text) # Now create a text file for further processing f = open("extracted1.txt", "w") f.write(text) f.close()
a1f60fe5370d4fc133a5c8fbbdff608ba0a56a76
Darius-Brown/Python-Zed
/strings.py
373
3.6875
4
x = "There are %d types of people" % 10 binary = "binary" do_not = "don't" y = "thos who know %s, and those who %s" % (binary, do_not) print(x) print(y) print("I said: %r " % (x)) print(" I also said: '%s'" % (y)) hilarious = "true" joke_evaluation = "Isn't that joke funny? %r" print(joke_evaluation % hilarious) e = "left half" y = "right half" u = e + y print(u)
980069f37036377d6ed2529091e5a6503d83d6dd
ESteinman/rps_python
/rps.py
461
4.03125
4
import random moves = ['rock', 'paper', 'scissors'] player_wins = ['rockscissors', 'scissorspaper', 'paperrock'] player_move = input ("Please choose either rock/paper/scissor: ") computer_move = random.choice(moves) print ("Your move was: ", player_move) print ("Computer choosed", computer_move) if player_move == computer_move: print("It's a tie") elif player_move + computer_move in player_wins: print("You win!") else: print("You lose..."")
a61b5f4217a90df820cf44c5438d989466d49a69
Graziela-Silva/Jogos-Games
/Jogo de adivinhação - Guessing game.py
846
3.59375
4
#Jogo de adivinhação import random print('\033[33mTente adivinhar o número que estou pensando! \nDica: ele é inteiro e está entre 1 e 10') num = random.randint(1,10) cont = 0 op = 's' while op != 'n': n = int(input('\033[35mEm qual número eu pensei? ')) if n != num: cont +=1 print('\n\033[31mHá! você errou!') print('Você teve: {} tentativas \nNúmero pensado: {} \nNúmero escolhido: {}'.format(cont,num,n)) else: cont +=1 print('\n\033[32mParabéns! você acertou') print('Você teve: {} tentativas \nNúmero pensado: {} \nNúmero escolhido: {}'.format(cont,num,n)) print('\n\033[36mDeseja continuar?') op = str(input('[S] Sim: \n[N] Não: \nOpção escolhida: ')).lower() if op not in 'sn': print('\n\033[mOpção inválida, saindo...') op = 'n'
2b3b74f580a7eb6fcbe713a3d44567d9a58c0ed2
Ern-st/advent_of_code_2017
/2/check.py
472
3.546875
4
#!/usr/bin/env python from decimal import * f = open("input.txt") input = f.readlines() f.close() lines = [sorted([Decimal(s) for s in line.rstrip().split("\t")]) for line in input] checksum = 0 for numberSet in lines: for number in numberSet: for modulo in numberSet: if (number / modulo) % 1 == 0 and (number / modulo) != 1: print "{0} / {1} = {2}".format(number, modulo, number / modulo) checksum += (number / modulo) print "checksum: " + str(checksum)
6ac12a5e160a1451de4275d02dd2db075613c6e6
orenlivne/euler
/algorithms/mergesort.py
1,114
3.96875
4
''' ============================================================ Merge sort: O(n log n) time. ============================================================ ''' def mergesort(a): '''Sorts the array a in non-decreasing order.''' n = len(a) return a if n == 1 else list(merge(mergesort(a[:n / 2]), mergesort(a[n / 2:]))) # Note: the two sub-sorts can be performed in parallel! def merge(a, b): '''Merges two non-decreasing lists into one non-decreasing list.''' i, j, na, nb = 0, 0, len(a), len(b) while i < na and j < nb: min_a, min_b = a[i], b[j] if min_a < min_b: yield min_a i += 1 else: yield min_b j += 1 i, a = (j, b) if i == na else (i, a) for k in xrange(i, len(a)): yield a[k] if __name__ == "__main__": import timeit, numpy as np for n in 2 ** np.arange(20): print n, timeit.timeit(stmt='mergesort(a)', setup='import numpy as np; from __main__ import mergesort; \ a = np.random.randint(0, %d, %d)' % (n, n), number=1)
bf2565a88c7724cdeb93c4c65bd281e4670019bc
CityQueen/bbs1
/Abgaben - HBF IT 19A/20190910/Nicole.py
200
3.796875
4
var1= 5 var2= int (input("zahl eingeben")) var3= int(input("zahl eingeben")) var4= var1+var2*var3 print (var4) var5= 10 var6= 3 print (var5//var6) var7= "Fitness" print(a.find("F")) print(a.find("f"))
f37a5b301f8acb6ca1eac969a8701bdcb9ece2fe
santia-bot1/Luchopython
/palabra.py
1,003
4.28125
4
# Este programa pide a un usuario que escriba una palabra, la cual luego se mostrara en pantalla # tambien le pide la cantidad de veces que esta se va a repetir, luego que ingresa el valor numerico # deberia aparecer un lista con la palabra la cual se repite de forma vertical # el codigo esta dañado, en el momento no funciona, la idea es que lo arregle y anexo a esto le cree # un consecutivo numero para poder ver la cantidad de veces que se repitio sin necesidad de contarlas # en la pantalla # NOTA: no olvide que debe descargarlo a su local, hacer los cambios y luego volverlos a subir frase = input(Que palabras quieres mostrar en pantalla) # le pedimos al usaurio que nos indique las veces que quiere que las muestre num1 = int(input(Cuantas veces quieres imprimir tu palabra en pantalla)) # en el ciclo le indicamos que hagala repeticion desde 0 hasta el valoringresado anteriormente for x in range(0, num1): # asi sacamos la palabra que el usuario ingreso al inicio print(frase)
dbd232fee48eb275f97b99bba1a26af659de09e3
BrianQcq/LeetCode
/src/19_remove_nth_from_linked_list.py
364
3.5625
4
class Node(object): def __init__(self, val): self.val = val self.next = None class Solution(object): def remove(self, head, n): if not head: return None first = Node(0) first.next = head pos = cur = first for i in range(n): pos = pos.next while pos.next: cur = cur.next pos = pos.next cur.next = cur.next.next return first.next
e7f387e17055df16a96c4ab805edd580fad42a8a
margaretmutinda/functions
/assignment.py
1,066
4.21875
4
""" Given a list of dictionaries containing data such as productName, exclPrice passed to a function as a parameter, together with the Tax Rate. Calculate the inclPrice of each products. Then RETURN a list of dictionaries containing the product and their respective incl prices. e.g #input products = [ { "productName" : "Milk", "exclPrice": 50 }, { "productName" : "Bread", "exclPrice": 40 } ] #Output [ { "productName" : "Milk", "inclPrice": 50 }, { "productName" : "Bread", "inclPrice": 40 } ]""" def calculateInclusivePrice(products,rate): incl={} for product in products: VAT=product["exclusive_price"]*rate incl=product["exclusive_price"]+VAT print(product, " inclusive price: " + str(incl)+ " ") p=[{ "product_name":"milk", "exclusive_price":50 }, { "product_name":"bread", "exclusive_price":40 }, { "product_name":"sugar", "exclusive_price":130 } ] calculateInclusivePrice(p,0.16)
a946169dbb7eed9e3aed51b6a725a46e7523431f
J-Cheetham/MIT-OpenCourseware
/6.0002/PS1/ps1a.py
5,294
4.0625
4
########################### # 6.0002 Problem Set 1a: Space Cows # Name: # Collaborators: # Time: from ps1_partition import get_partitions import time #================================ # Part A: Transporting Space Cows #================================ # Problem 1 def load_cows(filename): """ Read the contents of the given file. Assumes the file contents contain data in the form of comma-separated cow name, weight pairs, and return a dictionary containing cow names as keys and corresponding weights as values. Parameters: filename - the name of the data file as a string Returns: a dictionary of cow name (string), weight (int) pairs """ with open(filename) as f: cow_dict = {} for line in f: """All but the last item in document has a new line marker that needs to be removed""" """Split cow and weight value and allocate to dictionary""" if "\n" in line: end_of_slice = len(line) - 1 slice_line = line[0:end_of_slice] split_line = slice_line.split(",") cow_dict[split_line[0]] = int(split_line[1]) #cow_dict[split_line[0]] = split_line[1] else: split_line = line.split(",") cow_dict[split_line[0]] = int(split_line[1]) return cow_dict # Problem 2 def greedy_cow_transport(cows,limit=10): """ Uses a greedy heuristic to determine an allocation of cows that attempts to minimize the number of spaceship trips needed to transport all the cows. The returned allocation of cows may or may not be optimal. The greedy heuristic should follow the following method: 1. As long as the current trip can fit another cow, add the largest cow that will fit to the trip 2. Once the trip is full, begin a new trip to transport the remaining cows Does not mutate the given dictionary of cows. Parameters: cows - a dictionary of name (string), weight (int) pairs limit - weight limit of the spaceship (an int) Returns: A list of lists, with each inner list containing the names of cows transported on a particular trip and the overall list containing all the trips """ all_trips = [] cows_list = [] for k, v in cows.items(): t = k, v cows_list.append(t) cows_list.sort(key=lambda x: x[1], reverse=True) while cows_list: remaining_limit = 10 trip = [] for i in cows_list: if i[1] < remaining_limit: trip.append(i[0]) remaining_limit -= i[1] #cannot remove cows from the cows_list in the for loop as the loop then skips the next cow #loop below removes cows that have been transported in the current trip from cows_list for i in trip: for c in cows_list: if i is c[0]: cows_list.remove(c) all_trips.append(trip) return all_trips # Problem 3 def brute_force_cow_transport(cows,limit=10): """ Finds the allocation of cows that minimizes the number of spaceship trips via brute force. The brute force algorithm should follow the following method: 1. Enumerate all possible ways that the cows can be divided into separate trips Use the given get_partitions function in ps1_partition.py to help you! 2. Select the allocation that minimizes the number of trips without making any trip that does not obey the weight limitation Does not mutate the given dictionary of cows. Parameters: cows - a dictionary of name (string), weight (int) pairs limit - weight limit of the spaceship (an int) Returns: A list of lists, with each inner list containing the names of cows transported on a particular trip and the overall list containing all the trips """ #TODO do this without a counter for partition in get_partitions(cows): counter = 0 for trip in partition: total_weight = 0 for i in trip: total_weight += cows.get(i) if total_weight <= limit: counter += 1 if counter is len(partition): return partition #cows = {'Jessie': 6, 'Maybel': 3, 'Callie': 2, 'Maggie': 5} # Problem 4 def compare_cow_transport_algorithms(): """ Using the data from ps1_cow_data.txt and the specified weight limit, run your greedy_cow_transport and brute_force_cow_transport functions here. Use the default weight limits of 10 for both greedy_cow_transport and brute_force_cow_transport. Print out the number of trips returned by each method, and how long each method takes to run in seconds. Returns: Does not return anything. """ cows = load_cows("ps1_cow_data.txt") start = time.time() greedy = greedy_cow_transport(cows) end = time.time() print('Greedy algorithm result', greedy, '\n Greedy took', (end - start), 'seconds to run.') start = time.time() brute = brute_force_cow_transport(cows) end = time.time() print('Brute force algorithm result', brute, '\n Brute force took', (end - start), 'seconds to run.') compare_cow_transport_algorithms()
d91b3c68a5f819694fefaee965ec7afa3575b267
madhuri-majety/IK
/Leetcode/multiply_strings.py
1,599
4.25
4
""" Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" Note: The length of both num1 and num2 is < 110. Both num1 and num2 contain only digits 0-9. Both num1 and num2 do not contain any leading zero, except the number 0 itself. You must not use any built-in BigInteger library or convert the inputs to integer directly. """ from operator import add class Multiply(object): def multiply_integers(self, s1, s2): if not int(s1) or not int(s2): print('0') len1 = len(s1) len2 = len(s2) result = [0]*(len1+len2) i_s1, i_s2 = 0, 0 for i in range(len1-1, -1, -1): n1 = int(s1[i]) carry = 0 i_s2 = 0 for j in range(len2-1, -1, -1): n2 = int(s2[j]) sum = (n1*n2) + result[i_s1 + i_s2] + carry carry = sum/10 result[i_s1 + i_s2] = sum % 10 i_s2 += 1 if carry > 0: result[i_s1 + i_s2] += carry i_s1 += 1 for num in range(len(result)-1, -1, -1): if result[num] == 0: result.pop(num) else: break prod = "".join([str(i) for i in result]) print(prod[::-1]) def main(): mul = Multiply() mul.multiply_integers('0', '0') if __name__ == '__main__': main()