blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
16cf6f60ce743abd1698187a6c8107793a9e9049
HelloYeew/helloyeew-computer-programming-i
/6310545566_Phawit_ex6/ex6_files/try2.py
1,590
3.859375
4
import csv # open Cities.csv file with csv.DictReader and read its content into a list of dictionary, cities_data cities_data = [] with open('Cities.csv', 'r') as f: rows = csv.DictReader(f) for r in rows: cities_data.append(r) # open Countries.csv file with csv.DictReader and read its content into a list of dictionary, countries_data countries_data = [] with open('Countries.csv', 'r') as f: rows = csv.DictReader(f) for r in rows: countries_data.append(r) titanic_data = [] with open('Titanic.csv') as f: rows = csv.DictReader(f) for r in rows: titanic_data.append(r) def twin_list(titanic_data): """Returns a list of tuples of pairs of passengers who are likely to be twin children, i.e., same last name, same age, same place of embarkment, and age is under 18; each tuple has the following format: (person1's "last name" + "first name", person2's "last name" + "first name") """ twins = list() already_checked = list() for person in titanic_data: for person_2 in titanic_data: if person["age"] != "" and person_2["age"] != "": if person["first"] != person_2["first"] and person["last"] == person_2["last"] and float(person["age"]) < 18 and float(person_2["age"]) < 18 and person["age"] == person_2["age"] and person_2["first"] not in already_checked: twins.append((f"{person['last']} {person['first']}", f"{person_2['last']} {person_2['first']}")) already_checked.append(person["first"]) return twins print(twin_list(titanic_data))
cef5e148783afa94b122a1d583959097fee526af
HelloYeew/helloyeew-computer-programming-i
/Projects/task1/poly.py
3,857
3.59375
4
import numpy class Polynomial: def __init__(self, num_list): self.for_numpy = numpy.poly1d(num_list) self.num_list_original = num_list self.__num_list = num_list self.final_answer = "" self.other_object = ... def give_list(self): return self.__num_list def give_list_original(self): return self.num_list_original def add(self, object_for_add): self.other_object = object_for_add list_to_add = object_for_add.give_list() answer = self.__num_list i = len(self.__num_list)-1 j = len(list_to_add)-1 while i > 0: try: answer[i] = answer[i] + list_to_add[j] except: answer[i] = answer[i] + 0 i -= 1 j -= 1 answer = self.print_formula(answer) return answer def minus(self,object_for_minus): list_to_minus = object_for_minus.give_list() answer = self.__num_list i = len(self.__num_list) - 1 j = len(list_to_minus) - 1 while i > 0: try: answer[i] = answer[i] - list_to_minus[j] except: answer[i] = answer[i] - 0 i -= 1 j -= 1 answer = self.print_formula(answer) return answer def mul(self,object_for_mul): self.minus(self.other_object) list_mul1 = self.__num_list list_mul2 = object_for_mul.give_list() if len(list_mul2)>len(list_mul1): max_number = len(list_mul2) else: max_number = len(list_mul1) answer = [] for i in range((max_number*2)-1): answer.append(0) for i in range(len(list_mul1)): for j in range(len(list_mul2)): answer[i+j] += list_mul1[i]*list_mul2[j] print_answer = self.print_formula(answer) return print_answer def print_formula(self,list_print): print_formula = "" print_formula += str(list_print[0]) + f"(z**{len(list_print) - 1})" i = len(list_print) - 2 j = 1 while j < len(list_print): if i == 0: print_formula += " + " + str(list_print[j]) elif i == 1: print_formula += " + " + str(list_print[j]) + "(z)" else: print_formula += " + " + str(list_print[j]) + f"(z**{i})" j += 1 i -= 1 return print_formula def __add__(self, other): self.minus(other) return self.add(other) def __mul__(self, other): # self.minus(self.other_object) list_mul1 = self.__num_list list_mul2 = other.give_list() if len(list_mul2) > len(list_mul1): max_number = len(list_mul2) else: max_number = len(list_mul1) answer = [] for i in range((max_number * 2) - 1): answer.append(0) for i in range(len(list_mul1)): for j in range(len(list_mul2)): answer[i + j] += list_mul1[i] * list_mul2[j] print_answer = self.print_formula(answer) return print_answer def roots(self): answer = self.for_numpy.roots return answer def coefficients(self): answer = self.for_numpy.coefficients return answer def __call__(self, v): self.minus(self.other_object) answer = 0 for i in range(len(self.__num_list)): answer += self.__num_list[i]*v return answer def __str__(self): final_answer = self.print_formula(self.__num_list) return final_answer # use numpy from # - https://numpy.org/doc/stable/reference/generated/numpy.poly1d.html#numpy.poly1d # - https://numpy.org/doc/stable/reference/generated/numpy.roots.html?highlight=root
b0a74a6e2ce7d3392643479ebbd4280ec9ce554e
HelloYeew/helloyeew-computer-programming-i
/Fibonacci Loop.py
611
4.125
4
def fib(n): """This function prints a Fibonacci sequence up to the nth Fibonacci """ for loop in range(1,n+1): a = 1 b = 1 print(1,end=" ") if loop % 2 != 0: for i in range(loop // 2): print(a,end=" ") b = b + a print(b,end=" ") a = a + b print() else: for i in range((loop // 2) - 1): print(a,end=" ") b = b + a print(b,end=" ") a = a + b print(a,end=" ") print()
abc0cd5c971ca82768256b5ebd641c3ab9832c76
HelloYeew/helloyeew-computer-programming-i
/6310545566_Phawit_ex8/6310545566_Phawit_ex8/play_mastermind.py
395
3.59375
4
from mastermind import * new_game = MasterMindBoard() while True: print(new_game.show_number()) input_guess = input("What is your guess?: ") print('Your guess is', input_guess) if new_game.check_guess(input_guess) == False: print(new_game.display_clue()) print() else: print() print(new_game.done()) break # fix display_clue and test
3dd5303392fe607aa21e7cefce97426d59b90e49
HelloYeew/helloyeew-computer-programming-i
/OOP_Inclass/Inclass_Code.py
1,881
4.21875
4
class Point2D: """Point class represents and operate on x, y coordinate """ def __init__(self,x=0,y=0): self.x = x self.y = y def disance_from_origin(self): return (self.x*self.x + self.y*self.y)**0.5 def halfway(self, other): halfway_x = (other.x - self.x) / 2 halfway_y = (other.y - self.y) / 2 return Point2D(halfway_x,halfway_y) def __str__(self): return "[{0}, {1}]".format(self.x, self.y) # p = Point2D() # print("x coor of p is ", p.x) # print("y coor of p is ", p.y) # p.x = 3 # p.x = 4 # print("x coor of p is ", p.x) # print("y coor of p is ", p.y) # p = Point2D(10,20) # print("x coor of p is ", p.x) # print("y coor of p is ", p.y) p = Point2D(5, 12) print(p) q = Point2D(3, 4) print(q) distance_from_p_to_origin = p.disance_from_origin() p = Point2D() print(distance_from_p_to_origin) print() class Rectangle: """ Rectangle class represents a rectangle object with its size and location """ def __init__(self,point,width,height): self.corner = point self.width = width self.height = height def area(self): return self.width * self.height def grow(self, delta_width, delta_height): self.width += delta_width self.height += delta_height def move(self,dx,dy): self.corner.x += dx self.corner.y += dy def __str__(self): return "[{0}, {1}, {2}]".format(self.corner,self.width,self.height) box1 = Rectangle(5, 10, 5) print(box1) box2 = Rectangle(Point2D(20,30),100,200) print(box2) print("area of box1 is", box1.area()) print("area of box2 is", box2.area()) box1.grow(30,10) box1.move(2,3) print(box1, box1.area()) class Player: def __init__(self,name,num_wins,num_plays): self.name = name self.num_wins = num_wins self.num_plays = num_plays def
0e4fa88d43f58b9b26ebdaec0fb728e23271b2a4
HelloYeew/helloyeew-computer-programming-i
/try2.py
607
3.953125
4
def diamond(n): n = n + 1 loopup = 0 star = 0 while loopup < n: star += 1 print_star = "*" * (star * 2) front_back = " " * int(((n * 2) - len(print_star)) / 2) print(f" {front_back}{print_star}") loopup += 1 while loopup > 0: print_star = "*" * (star * 2) front_back = " " * int(((n * 2) - len(print_star)) / 2) print(f" {front_back}{print_star}") loopup -= 1 star -= 1 print("diamond(n) result:") # แก้วรรคข้าวหลัง print("") for i in range(0, 7): diamond(i) print("")
5c4e2bdb74dd1f8a9c5f82427acf1e7dc4b2c790
HelloYeew/helloyeew-computer-programming-i
/6310545566_Phawit_ex3/polygon_art.py
636
3.890625
4
import turtle import random turtle.speed(25) turtle.setheading(0) def polygon(x, y, size, n, clr): turtle.penup() turtle.color(clr) turtle.fillcolor(clr) turtle.goto(x, y) turtle.pendown() turtle.begin_fill() for i in range(n): turtle.forward(size) turtle.left(360 / n) turtle.end_fill() turtle.penup() for loop in range(30): point_x = random.randint(-325, 325) point_y = random.randint(-325, 325) shape_size = random.randint(30, 100) shape_side = random.randint(3, 8) color = "blue" polygon(point_x, point_y, shape_size, shape_side, color) turtle.done()
d101318dbf12545644a06c53067ca33e0f6ccaec
valevo/LexicalChoice
/compound_splitter.py
901
3.609375
4
#!/usr/bin/python import sys import fileinput import argparse def load_dict(file): splits = {} with open(file) as f: for line in f: es = line.decode('utf8').rstrip('\n').split(" ") w = es[0] indices = map(lambda i: i.split(','), es[1:]) splits[w] = [] for from_, to, fug in indices: s, e = int(from_), int(to) # Don't use single character splits - just add to prev split if e - s == 1: splits[w][-1][1] += 1 else: splits[w].append([s, e, fug]) return splits def split_word(w, splits): if w in splits: w_split = [] for from_, to, fug in splits[w]: wordpart = w[from_:to-len(fug)] wordpart = wordpart.lower() w_split.append(wordpart) return u" ".join(w_split) else: return w
bb7dc181239fe833015e83bf9061cc7e5045fbd9
JordanAceto/LED-chaser-game
/src/Timer.py
657
3.5625
4
import time class Timer(): def __init__(self, sample_period): ''' set up the initial sample period and last tick ''' self.sample_period = sample_period self.last_tick = time.time() def outatime(self): ''' return True if the timer has expired, else False ''' self.elapsed_time = time.time() - self.last_tick if (self.elapsed_time >= self.sample_period): self.last_tick = time.time() return True return False def speed_up(self): self.sample_period *= 0.75 def slow_down(self): self.sample_period *= 1.25
df24007be07bfa188fb0a80fa63ee538d5f8ada9
alphak007/Training
/toi2.py
607
3.671875
4
row1=list() row2=list() row3=list() row4=list() row5=list() row1.append(1) n=row1[0] n+=3 for i in range(n,n+2): row2.append(i) n=row2[-1]+3 for i in range(n,n+3): row3.append(i) n=row3[-1]+3 for i in range(n,n+4): row4.append(i) n=row4[-1]+3 for i in range(n,n+5): row5.append(i) print(row1) print(row2) print(row3) print(row4) print(row5) print("Row 1: ",row1[0]) print("Row 2: ",row2[0]+row2[1]) print("Row 3: ",row3[0]+row3[1]+row3[2]) print("Row 4: ",row4[0]+row4[1]+row4[2]+row4[3]) print("Row 5: ",row5[0]+row5[1]+row5[2]+row5[3]+row5[4])
390a1a743fd32d1c547513983bc3f23a9a3b3ef7
Rchana/python-projects
/patient-records.py
1,287
4.03125
4
class patientRecord: # values shared amoung all instances of the class patientCount = 0; # constructor called to initialize new instance def __init__(self, name, healthCardNumber, age, gender): self.name = name self.healthCardNumber = healthCardNumber self.age = age self.gender = gender patientRecord.patientCount += 1 # functions def displayPatientCount(self): print("The total number of patients is: ", patientRecord.patientCount) def displayPatient(self): print("") print("Name: ", self.name) print("Age: ", self.age) print("Gender:", self.gender) print("health card number: ", self.healthCardNumber) print("") # creating objects patient1 = patientRecord("Arrchana", 12345678, 19, "M") patient2 = patientRecord("Bhavya", 87654321, 19, "F") patient1.displayPatient() patient2.displayPatient() print("The total number of patients is: ", patientRecord.patientCount) # modifying attributes of objects patient2.age = 18 # special functions hasattr(patient1, "name") # returns true if name exists getattr(patient1, "name") # returns names setattr(patient1, "gender", "F") # sets gender to F # delattr(patient1, "healthCardNumber") # deletes healthCardNumber
cba7f3eb2893ddd773800b8bbd644b43766693aa
jolubanco/estudos-python-oo
/oo/teste.py
367
3.609375
4
def cria_conta(numero,titular,saldo,limite): conta = { 'numero' : numero, 'titular': titular, 'saldo' : saldo, 'limite' : limite } return conta def deposita(conta,valor): conta['saldo'] += valor def saca(conta,valor): conta['saldo'] -= valor def extrato(conta): print('O saldo é {}'.format(conta['saldo']))
175a34cd4447011b7090684bead66bcd63870851
fenrirs/LeetCode
/sum_root_to_leaf_numbers.py
1,326
3.96875
4
#https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/ '''Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / \ 2 3 The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Return the sum = 12 + 13 = 25.''' # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return an integer def traverse(self,root,depth): if not root.left and not root.right: self.res += int(''.join(self.str[:depth])) for nextNode in (root.left,root.right): if nextNode!=None: if depth>=len(self.str): self.str.append(str(nextNode.val)) else: self.str[depth] = str(nextNode.val) self.traverse(nextNode,depth+1) def sumNumbers(self, root): if not root: return 0 self.res = 0 self.str = [str(root.val)] self.traverse(root,1) return self.res
6c91df3269280f87f4e8b16d4f7b94aa2082ccb5
fenrirs/LeetCode
/implement_strstr.py
530
3.9375
4
#https://oj.leetcode.com/problems/implement-strstr/ '''Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.''' class Solution: # @param haystack, a string # @param needle, a string # @return a string or None def strStr(self, haystack, needle): lenH = len(haystack) lenN = len(needle) for i in range(lenH-lenN+1): if haystack[i:i+lenN]==needle: return haystack[i:] return None
60b6cd6a276a41378caa234e0767f7d79990ce2a
fenrirs/LeetCode
/valid_parentheses.py
701
3.9375
4
#https://oj.leetcode.com/problems/valid-parentheses/ '''Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.''' class Solution: # @return a boolean def isValid(self, s): cp={')':'(', '}':'{', ']':'['} list = [] for ch in s: if ch in ['(','{','[']: list.append(ch) else: if len(list)==0 or cp[ch]!=list[-1]: return False list.pop() if len(list)!=0: return False return True
bd28eab5afcae116f3039f52e602fb30764a355f
fenrirs/LeetCode
/copy_list_with_random_pointer.py
1,072
3.84375
4
#https://oj.leetcode.com/problems/copy-list-with-random-pointer/ '''A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list.''' # Definition for singly-linked list with a random pointer. # class RandomListNode: # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution: # @param head, a RandomListNode # @return a RandomListNode def copyRandomList(self, head): res = RandomListNode(0) pPreCopy = res pTemp = head dict = {} dict[None] = None #copy list while pTemp!=None: copy = RandomListNode(pTemp.label) pPreCopy.next = copy dict[pTemp] = copy pPreCopy = pPreCopy.next pTemp = pTemp.next #copy random pTemp = head while pTemp!=None: dict[pTemp].random = dict[pTemp.random] pTemp = pTemp.next return res.next
20ad12ab78c3aada7f7151970db06c3496a13f8f
fenrirs/LeetCode
/longest_common_prefix.py
607
3.6875
4
#https://oj.leetcode.com/problems/longest-common-prefix/ '''Write a function to find the longest common prefix string amongst an array of strings. ''' class Solution: # @return a string def longestCommonPrefix(self, strs): n = len(strs) if n==0: return '' minlen = min(len(strs[i]) for i in range(n)) if minlen==0: return '' for i in range(minlen): char = strs[0][i] for j in range(n): if strs[j][i]!=char: return strs[0][:i] if i>0 else '' return strs[0][:minlen]
e42428038d4bf4238d52bc3ddce1c4f3bfdf944f
AbhAgg/Python-Codes
/login_app.py
2,951
3.6875
4
import tkinter from tkinter import * import tkinter.messagebox from sys import exit import pymysql def Welcome_Screen(): if len (e1.get())==0 or len(e2.get()) == 0: Label(text='Both entries are necessary. ',justify="left",wraplength=100).grid(row=4,column=1) else: string="SELECT * from employee_details where name='"+e1.get()+"'and phone_number='"+e2.get()+"'" db = pymysql.connect("localhost","root","", database = "bank_database") cursor = db.cursor() cursor.execute(string) results = cursor.fetchall() db.commit() db.close() if results: for row in results: First_Name = row[0] Phone_Number = str(row[1]) top = Toplevel() top.title("Hello New Window") top.geometry("300x200") lbl = Label(top,text="Hello "+e1.get()+", Welcome to python") lbl.grid(row=0,column=0) answerLabel.configure(text="") else: answerLabel.configure(text="No entry found, Please register") def register_data(a,b,c): if len (a)==0 or len(b) == 0: Label(c,text='Both entries are necessary. ',justify="left",wraplength=100).grid(row=4,column=1) else: string="insert into employee_details values ('"+a+"','"+b+"') " db = pymysql.connect("localhost","root","", database = "bank_database") cursor = db.cursor() cursor.execute(string) db.commit() db.close() print("First Name: %s\nPhone Number: %s" % (a, b)) Label(c,text='Your Entry has been added',justify="left",wraplength=100).grid(row=4,column=1) def register(): top = Toplevel() top.title("Enter Details Window") top.geometry("300x200") lbl = Label(top,text="Please Enter your details.") lbl.grid(row=0,column=0) Label1=Label(top, text = 'Username',justify="left") Label1.grid(row=1,column=0) Label2=Label(top, text = 'Password',justify="left") Label2.grid(row=2,column=0) e3 = Entry(top) e4 = Entry(top) e3.grid(row=1, column=1) e4.grid(row=2, column=1) text1=e3.get() text2=e4.get() but1=Button(top,text="Register",command=lambda : register_data(e3.get(),e4.get(),top)) but1.grid(row=3,column=1) root = tkinter.Tk() root.title ("Hello World") root.geometry("300x200") Label1=Label(root, text = 'Username',justify="left") Label1.grid(row=0,column=1) Label2=Label(root, text = 'Password',justify="left") Label2.grid(row=1,column=1) e1 = Entry(root) e2 = Entry(root,text="") e1.grid(row=0, column=2) e2.grid(row=1, column=2) but1=Button(root,text="Register",command=register) but1.grid(row=3,column=1) but2=Button(root,text="Login", command=Welcome_Screen) but2.grid(row=3,column=2) answerLabel = Label(root) answerLabel.grid(row=4, column=1) root.mainloop()
ac0eac144872639a215ace3a2160a4ab29e05e7b
AbhAgg/Python-Codes
/thread_example4.py
889
3.6875
4
import _thread import threading import threaded import time class thread1: def __init__(self,a): for i in range (0,len(x)): threadLock.acquire() print(x[i]+"\n") threadLock.release() time.sleep(1) class thread2: def __init__(self,a): for i in range (0,len(y)): threadLock.acquire() print(y[i]+"\n") threadLock.release() time.sleep(1) try: x=list(input("Enter the First word: ")) y=list(input("Enter the Second word: ")) threadLock = threading.Lock() t1=threading.Thread(target=thread1, args=(x,)) t2=threading.Thread(target=thread2, args=(y,)) t1.start() t2.start() t1.join() t2.join() except: print("Unable to start thread.")
5aa0f3b7b8b8ff0d330e56ce461a0f0454ba1c47
vipul-royal/A7
/gcd.py
177
3.953125
4
t=0 gcd=0 a=int(input("Enter the value of a:")) b=int(input("Enter the value of b:")) x=a y=b while b!=0: t=b b=a%b a=t gcd=a print("The GCD of",x,"and",y,"is:",gcd)
bba1d2dd5f7133b487ab4d7c469e62c3f26ccbdd
franvergara66/Python_sockets
/python/1s.py
978
3.875
4
#+----------------------------------+ #| Server TCP/IP | #+----------------------------------+ import socket #Creo el objeto socket s = socket.socket() #Invoco al metodo bind, pasando como parametro una tupla con IP y puerto s.bind(("localhost", 9999)) #Invoco el metodo listen para escuchar conexiones con el numero maximo de conexiones como parametro s.listen(3) #El metodo accept bloquea la ejecucion a la espera de conexiones #accept devuelve un objeto socket y una tupla Ip y puerto sc, addr = s.accept() print "Recibo conexion de " + str(addr[0]) + ":" + str(addr[1]) addr_2= s.accept() while True: #invoco recv sobre el socket cliente, para recibir un maximo (segun parametro) de 1024 bytes recibido = sc.recv(1024) if recibido == "by": break print "Recibido:", recibido #Envio la respuesta al socket cliente sc.send(recibido) print "adios" #cierro sockets cliente y servidor sc.close() s.close()
6c43b0598523c3590ba54dfc962af52baa71074f
thevindur/Python-Basics
/w1790135 - ICT/Q1A.py
459
4.125
4
n1=int(input("Enter the first number: ")) n2=int(input("Enter the second number: ")) n3=int(input("Enter the third number: ")) #finding the square values s1=n1*n1 s2=n2*n2 s3=n3*n3 #finding the cube values c1=n1*n1*n1 c2=n2*n2*n2 c3=n3*n3*n3 #calculating the required spaces for the given example x=" "*5 x1=" "*4 y=" "*5 y1=" "*4 z=" "*3 print("\n") print("Number"+"\t"+"Square"+"\t"+"Cube") print(n1,x,s1,y,c1) print(n2,x,s2,y1,c2) print(n3,x1,s3,z,c3)
4fef20fe627a0889b68856fd64392612b0830776
rafaelferrero/aula25py
/ejercicios1/rafaelferrero_29087702/ejercicios.py
1,271
3.765625
4
# -*- coding: utf-8 -*- from funciones import * from decimal import * print(divide_enteros_y_al_cuadrado(42, 3) == 196) print(divide_enteros_y_al_cuadrado(42, 5.5) == 49) print(divide_enteros_y_al_cuadrado(42, 0.5) == 7056) print(convierte_a_decimal_y_multiplica('4.5', 2) == Decimal('9.0')) print(convierte_a_decimal_y_multiplica('0.1', 10) == Decimal('1.0')) print(convierte_a_decimal_y_multiplica('0.3', 10) == Decimal('3.0')) print(es_alphanumerico('4') == True) print(es_alphanumerico('m') == True) print(es_alphanumerico('') == False) print(tuplas(1, 2, 3) == (1, 2, 3)) print(tuplas(None, [], (1, 2, 3)) == (None, [], (1, 2, 3))) print(dicctionario('a', 1, 'b', 2) == {'a': 1, 'b': 2}) print(dicctionario((1,), [1], (1,2), [1,2]) == {(1,): [1], (1, 2): [1,2]}) print(conjunto(1.1, 1.2, 1.3, 1.3) == {1.1, 1.2, 1.3}) print(conjunto(None, True, True, True, False, False, None) == {None, True, False}) print(usar_if(3) == "menor a diez") print(usar_if(13) == "mayor a diez") print(usar_if(10) == "igual a diez") print(iterar([1, 2, 3, 4, 5, 6, 7, 8]) == [4, 16, 36, 64]) print(iterar((90, 80, 70, 60, 50)) == [8100, 6400, 4900, 3600, 2500]) print(iterar({23: 'a', 44: '44', 55: '8', 90: '', 21: ''}) == [8100, 1936]) print(iterar([21, 31, 45, 67, 81]) == [])
9370080bd1e7fe88b5cdd7e534f6d44cde1118b0
TecProg-20181/03--Mateusas3s
/hang.py
4,844
3.71875
4
import random import sys import string class Words: def __init__(self): self.wordlist_filename = "words.txt" def getWordlistFilename(self): return self.wordlist_filename def loadWords(self): """ Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") try: inFile = open(self.wordlist_filename, 'r') except FileNotFoundError: print("File", self.wordlist_filename, "not found!") sys.exit(0) line = inFile.readline() if not line: print("Words not found in file!") sys.exit(0) wordlist = line.split() print(" ", len(wordlist), "words loaded.") inFile.close() return wordlist class GuessWhat: def __init__(self): self.guessed = '' self.guesses = 8 def isWordGuessed(self, secretWord, lettersGuessed): secretLetters = [] for letter in secretWord: if letter in secretLetters: secretLetters.append(letter) if not(letter in lettersGuessed): return False return True def guessLetter(self, guessed, secretWord, lettersGuessed): for letter in secretWord: if letter in lettersGuessed: guessed += letter else: guessed += '_ ' return guessed def getGuesses(self): return self.guesses def putGuesses(self, guesses): self.guesses = guesses def getGuessedWord(self): return self.guessed def showGuesses(self, guesses): print('You have ', guesses, 'guesses left.') class Letter: def __init__(self): self.alfa = string.ascii_lowercase def getAlfa(self): return self.alfa def showAlfa(self, available): print('Available letters', available) def letterDif(self, alfa, secretWord): count_letter = 0 for letter in secretWord: if letter in alfa: count_letter = count_letter + 1 alfa = alfa.replace(letter, '') return count_letter def hangMain(): # Creating objects --------------------- words = Words() guess_what = GuessWhat() available_letter = Letter() secretWord = '' letters_dif = 27 alfa = available_letter.getAlfa() guesses = guess_what.getGuesses() wordlist = words.loadWords() # verificar se todas as palavras do arquivo tem a quantidade de # letra maior que o número de tentativas while letters_dif > guesses: secretWord = random.choice(wordlist).lower() letters_dif = available_letter.letterDif(alfa, secretWord) lettersGuessed = [] print('Welcome to the game, Hangam!') print('I am thinking of a word that is', len(secretWord), ' letters long.') print(letters_dif, "different letters in word!") print('-------------') while(not(guess_what.isWordGuessed(secretWord, lettersGuessed)) and guesses-1 > 0): guesses = guess_what.getGuesses() guess_what.showGuesses(guesses) alfa = available_letter.getAlfa() for letter in alfa: if letter in lettersGuessed: alfa = alfa.replace(letter, '') available_letter.showAlfa(alfa) letter = input('Please guess a letter: ') if letter in lettersGuessed: guessed = guess_what.guessLetter(guess_what.getGuessedWord(), secretWord, lettersGuessed) print('Oops! You have already guessed that letter: ', guessed) elif letter in secretWord: lettersGuessed.append(letter) guessed = guess_what.guessLetter(guess_what.getGuessedWord(), secretWord, lettersGuessed) print('Good Guess: ', guessed) elif letter not in string.ascii_lowercase: print("Please, enter only one lowercase letter") else: guess_what.putGuesses(guesses - 1) lettersGuessed.append(letter) guessed = guess_what.guessLetter(guess_what.getGuessedWord(), secretWord, lettersGuessed) print('Oops! That letter is not in my word: ', guessed) print('------------') else: if guess_what.isWordGuessed(secretWord, lettersGuessed): print('Congratulations, you won!') else: print('Sorry, you ran out of guesses. The word was ', secretWord, '.') hangMain()
8b1441d35c30aec092684983a016553284c6e926
Kaspazza/Python_recipes_application
/common.py
3,936
3.65625
4
import imports import algorithms import note # Read input from user def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch # choosing number of dish def choose_dish(final_dishes, all_dishes): dish_name = "niemamnie" while dish_name not in final_dishes: dish_number = input("Choose number of dish you want to see!\n") dish_name = all_dishes[int(dish_number)-1] return dish_name # creating list with established order def numeric_choose_dishes(dishes): all_dishes = [] for dish in dishes.keys(): all_dishes.append(dish) return all_dishes # choosing note adding def deciding_to_add_note(choosen_dish): decision = "0" while decision != "y" or decision != "n": decision = input("Do you want to add a note to your dish?(y/n)\n") if decision == "y": note_text = input("What you want to write in Your note?\n") note.add_note(choosen_dish, note_text) elif decision == "n": return else: print("\nYou can type only 'y' or 'n'\n") # show recipes for breakfast, dinner and supper def show_recipes(show_or_find, filename): if show_or_find == "find": final_dishes = search_type(filename) return final_dishes elif show_or_find == "show": print("\n*{0}*\n".format((filename.strip(".txt")).upper())) food_recipes = imports.import_recipes(filename) return food_recipes # choosing meal type def meal_type_decision(show_or_find): choose = "0" breakfast, supper, dinner = "breakfast.txt", "supper.txt", "dinner.txt" while choose != "b" or choose != "s" or choose != "d": choose = input("You want receipts for: breakfast, supper or dinner? (b,s,d)\n") if choose == "b": return show_recipes(show_or_find, breakfast) elif choose == "s": return show_recipes(show_or_find, supper) elif choose == "d": return show_recipes(show_or_find, dinner) else: print("\nsomething went wrong, be sure you typed 'b', 's' or 'd'\n") # getting dishes by choosen algorithm def search_type(file_type): choose = "0" dishes = imports.import_recipes(file_type) while choose != "1" or choose != "2": choose = input("Do You want to search for: \n 1.Receipts you can make with your ingredients \n 2.Receipts containing ingredient?(1 or 2)\n") if choose == "1": components = pick_components(choose) final_dishes = algorithms.get_dishes_by_all_components(components, dishes) break elif choose == "2": components = pick_components(choose) final_dishes = algorithms.get_dishes_by_one_component(components, dishes) break else: print("\nare you sure you picked 1 or 2? Try again!\n") return final_dishes # picking data for right algorithm def pick_components(type): ingredients_integer = True while ingredients_integer: try: number_of_ingredients = int(input("How many ingredients you want to use?\n")) ingredients_integer = False except ValueError: print("\nYou need to write a number!\n") if type == "1": components = {} for ingredients in range(int(number_of_ingredients)): ingredient = input("Pick ingredient\n") quantity = input("Pick quantity\n") components[ingredient] = quantity elif type == "2": components = [] for ingredients in range(int(number_of_ingredients)): ingredient = input("Pick ingredient\n") components.append(ingredient) return components
e7f43f7f4d079ea9fdb9ed6a5da83b2b1c63982f
dean2727/Namex
/namex.py
1,906
3.84375
4
''' Namex: a command line-based program that allows a user to rename all files in a directory. by Dean Orenstein, Edited 6/3/19, 11/12/19 ''' # Import libraries from os import * #~~~ Useful methods ~~~# # listdir(path): os, returns a list of the items in that directory # remove(path, dir_fd=None): os, delete the file path (not directory path) # rename(src, dst, src_dir_fd=None, dst_dir_fd=None): os, rename the file from src path to dst path # User inputs the directory path and common name for all files, name is assumed to be a regular expression # example of path: /Users/Deano/Documents/ENGR 216 path = '/' location, not_complete = input('Enter base location for path for target directory (e.g. Users): '), True while not_complete: if location.lower() == 'done': not_complete = False else: path += location + '/' location = input('Enter next location (type done to quit): ') # Each item is distinguished by a number following this name, e.g. name2, by default common_name = input('What would you like to name the items in this directory? ') # The files in the directory are targeted and manipulated items = listdir(path) # There are DS_store files (on mac) which must get removed from the list so numbering isnt screwed up items = [item for item in items] #if item.split('.')[1] != 'DS_Store'] num = 1 for item in items: # Extract name and extension (if there is one) l = item.split('.') if len(l) == 2: name, extension = l[0], l[1] rename(path+'/'+name+'.'+extension, path+'/'+common_name+str(num)+'.'+extension, src_dir_fd=None, dst_dir_fd=None) elif len(l) == 1: name = l[0] rename(path+'/'+name, path+'/'+common_name+str(num), src_dir_fd=None, dst_dir_fd=None) num += 1 # Console outputs a message saying that the task is complete print('Task complete! Check your finder application to see your new names :D')
44888c3249333f8888c6655a68e13515f72489ea
JasonMTarka/Password-Generator
/password_generator.py
3,324
4
4
from typing import Any from random import choice, shuffle class Password: """Set password generation parameters and generate passwords.""" _STR_OR_INT = str | int def __init__( self, lowercase: _STR_OR_INT = 1, uppercase: _STR_OR_INT = 1, nums: _STR_OR_INT = 1, syms: _STR_OR_INT = 0, min_nums: _STR_OR_INT = 2, min_syms: _STR_OR_INT = 2, pass_len: _STR_OR_INT = 8, value: str = "", ) -> None: """Set instance variables and generate a password.""" self.lowercase = int(lowercase) self.uppercase = int(uppercase) self.nums = int(nums) self.syms = int(syms) self.min_nums = int(min_nums) self.min_syms = int(min_syms) self.pass_len = int(pass_len) self.value = value if not self.value: self.generate() def __repr__(self) -> str: """Return string which can be used to instantiate this instance.""" return ( f"Password(" f"lowercase={self.lowercase}," f"uppercase={self.uppercase}," f"nums={self.nums}," f"syms={self.syms}," f"min_nums={self.min_nums}," f"min_syms={self.min_syms}," f"pass_len={self.pass_len}," f"value={self.value})" ) def __str__(self) -> str: """Return password value as a string.""" if self.value: return self.value else: return "Please select at least one character set." def __len__(self) -> int: """Return length of password.""" return self.pass_len def __getitem__(self, position: int) -> str | Any: """Allow iterating over password characters.""" return self.value[position] def __add__(self, other) -> str: """Allow adding to other Password objects, strings, or ints.""" try: return self.value + other.value except AttributeError: return self.value + str(other) def generate(self) -> None: """Generate a password from instance attributes.""" def _constructor() -> str: """Create empty password and append requested characters.""" temp_password = [] if self.nums: for i in range(0, self.min_nums): temp_password.append(choice(NUMS)) if self.syms: for i in range(0, self.min_syms): temp_password.append(choice(SYMBOLS)) shuffle(temp_password) while len(temp_password) > self.pass_len: temp_password.pop() while len(temp_password) < self.pass_len: temp_password.append(choice(source)) shuffle(temp_password) return "".join(temp_password) source = "" LOWERCASE = "abcdefghijklmnopqrstuvwxyz" UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" NUMS = "0123456789" SYMBOLS = "!@#$%^&*" if self.lowercase: source += LOWERCASE if self.uppercase: source += UPPERCASE if self.nums: source += NUMS if self.syms: source += SYMBOLS if source: self.value = _constructor()
2905e3872d902ee20de3c262833692dd3b966f75
vanj81/python
/Задача 3.py
306
3.578125
4
#coding: utf-8 age = int(input('Пожалуйста укажите ваш возраст: ')) if age >= 18: print('Доступ разрешен') access = True # доступ куда-либо else: print('Доступ запрещен') access = False # доступ куда-либо
fdd13bbcbacef17a715629a599e11ff0ffab0848
wasfever2012/huilvjs
/52weekv3.py
925
3.796875
4
# conding = utf-8 """ 作者:shao 功能:52周存钱计算 版本:V3.0 使用for循环 时间:2018-11-18 20:42:41 """ import math def main(): """ 主函数 :return: """ money_per_week = 10 # 每周存入金额 i = 1 # 周数记录 increase_money = 10 # 递增的存额 total_week = 52 # 总共时间(周数) saving = 0 # 账户累计 money_list = [] # 记录每周存款的列表 while i <= total_week: # 存钱操作 # saving += money_per_week money_list.append(money_per_week) saving = math.fsum(money_list) # 输出信息 print('第{}周,存入钱数为{},存款总额为{}'.format(i, money_per_week, saving)) # 更新下一周的存款信息 money_per_week += increase_money i += 1 if __name__ == '__main__': main()
bbacd3803582ed1b472670dde3e7df2245bd26dd
wasfever2012/huilvjs
/lecture02-3.py
861
4.09375
4
# coding = utf-8 """ 作者:shao 功能:分形树1-turtle使用 版本:v2.0-绘制渐大五角星 版本:v3.0-迭代函数 时间:2018年11月15日23:04:28 """ import turtle def draw_pentagram(size): """ 绘制一个五角星 :return: """ # 计数器 count = 1 while count <= 5: turtle.forward(size) turtle.right(144) count += 1 def diedai_pentagram(size): draw_pentagram(size) size += 50 if size <= 250: diedai_pentagram(size) def main(): """ 主函数 :return: """ # 抬起笔 turtle.penup() turtle.backward(200) turtle.pendown() # 设定笔的宽度 turtle.pensize(1.5) turtle.pencolor('yellow') size = 50 diedai_pentagram(size) turtle.exitonclick() if __name__ == '__main__': main()
11ff5eb9c3ba36b44135c2ea8ba781f6afa4e0a8
zh85hy/python-demo
/spider/spider.py
2,774
3.5
4
import re import ssl # from urllib import request import urllib.request as ur class Spider: # url = 'https://www.panda.tv/cate/kingglory' url = 'https://www.douyu.com/directory/game/wzry' # headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} headers = {'User-Agent': 'Mozilla/5.0'} root_pattern = '<p>([\w\W]*?)</p>' # \s\S or \w\W name_pattern = '<span class="dy-name ellipsis fl">([\w\W]*?)</span>' number_pattern = '<span class="dy-num fr" >([\s\S]*?)</span>' def __init__(self): pass def __fetch_content(self): # urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed ssl._create_default_https_context = ssl._create_unverified_context # urllib.error.HTTPError: HTTP Error 403: Forbidden req = ur.Request(Spider.url, headers=Spider.headers) # A string or An object # res = request.urlopen(Spider.url) res = ur.urlopen(req) # print(res) # htmls = str(res.read(), encoding='utf-8') # htmls = res.read() # bytes # A string htmls = res.read().decode('utf-8') # print(htmls) return htmls def __analyse_htmls(self, htmls): # A list root_htmls = re.findall(Spider.root_pattern, htmls) # print(root_htmls) htmls_return = [] for htmls in root_htmls: name_html = re.findall(Spider.name_pattern, htmls) number_html = re.findall(Spider.number_pattern, htmls) html = {'name': name_html, 'number': number_html} htmls_return.append(html) # print(htmls_return) return htmls_return def __refine(self, anchors): l = lambda anchor: { 'name': anchor['name'][0].strip(), 'number': anchor['number'][0].strip() } # anchors_refined = map(l, anchors) # print(anchors_refined) return map(l, anchors) def __sort_seed(self, anchor): r = re.findall('\d*', anchor['number']) number = float(r[0]) if '万' in anchor['number']: number *= 10000 return number def __sort(self, anchors): # Iterable return sorted(anchors, key=self.__sort_seed, reverse=True) def __show(self, anchors): for rank in range(0, len(anchors)): print('Rank ' + str(rank+1) + ': ' + anchors[rank]['name'] + ' ' + anchors[rank]['number']) def go(self): htmls = self.__fetch_content() anchors = self.__analyse_htmls(htmls) anchors_refined = self.__refine(anchors) anchors_sorted = self.__sort(anchors_refined) self.__show(anchors_sorted) spider = Spider() spider.go()
aecbec65c508470c367728791c3d0646d9a6426e
WitoldRadzik04/n-root-Calc
/sqrt.py
824
3.921875
4
num = int(input("Input num to be n rooted:\n")) n = int(input("Input n\n")) def sqrt(num): tnums = num a = 0 if(tnums>=1000000): a = 500 elif(tnums>=10000): a = 400 elif(tnums>=1000): a = 300 elif(tnums>=80): a = 200 else: a = 100 for i in range(a): tnums = (tnums + num/tnums)/2 #print(f"a: {a}") print(tnums) def nroot(num, n): tnum = num a = 1 if(num >= 1000000): a = 500 * (10*n) elif(num >=100000): a = 200 * (10*n) elif(num >= 10000): a = 150 * (10*n) elif(num >= 1000): a = 100 * (10*n) elif(num >= 500): a = 18 * (10*n) elif(num >= 100): a = 15 * (10*n) else: a = 100 for i in range (a): tnum = tnum - (tnum**n - num)/((n - 1) * (tnum**(n - 1))) #print(f"a: {a}") print(tnum) if(n == 2): sqrt(num) else: nroot(num, n)
abe9f3bdb1f8d872f1c96b705bb1e7e89d61e575
chaimleib/intervaltree
/test/intervals.py
3,929
3.515625
4
""" intervaltree: A mutable, self-balancing interval tree for Python 2 and 3. Queries may be by point, by range overlap, or by range envelopment. Test module: utilities to generate intervals Copyright 2013-2018 Chaim Leib Halbert Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import absolute_import from intervaltree import Interval from pprint import pprint from random import randint, choice from test.progress_bar import ProgressBar import os try: xrange except NameError: xrange = range try: unicode except NameError: unicode = str def make_iv(begin, end, label=False): if label: return Interval(begin, end, "[{0},{1})".format(begin, end)) else: return Interval(begin, end) def nogaps_rand(size=100, labels=False): """ Create a random list of Intervals with no gaps or overlaps between the intervals. :rtype: list of Intervals """ cur = -50 result = [] for i in xrange(size): length = randint(1, 10) result.append(make_iv(cur, cur + length, labels)) cur += length return result def gaps_rand(size=100, labels=False): """ Create a random list of intervals with random gaps, but no overlaps between the intervals. :rtype: list of Intervals """ cur = -50 result = [] for i in xrange(size): length = randint(1, 10) if choice([True, False]): cur += length length = randint(1, 10) result.append(make_iv(cur, cur + length, labels)) cur += length return result def overlaps_nogaps_rand(size=100, labels=False): l1 = nogaps_rand(size, labels) l2 = nogaps_rand(size, labels) result = set(l1) | set(l2) return list(result) def write_ivs_data(name, ivs, docstring='', imports=None): """ Write the provided ivs to test/name.py. :param name: file name, minus the extension :type name: str :param ivs: an iterable of Intervals :type ivs: collections.i :param docstring: a string to be inserted at the head of the file :param imports: executable code to be inserted before data=... """ def trepr(s): """ Like repr, but triple-quoted. NOT perfect! Taken from http://compgroups.net/comp.lang.python/re-triple-quoted-repr/1635367 """ text = '\n'.join([repr(line)[1:-1] for line in s.split('\n')]) squotes, dquotes = "'''", '"""' my_quotes, other_quotes = dquotes, squotes if my_quotes in text: if other_quotes in text: escaped_quotes = 3*('\\' + other_quotes[0]) text = text.replace(other_quotes, escaped_quotes) else: my_quotes = other_quotes return "%s%s%s" % (my_quotes, text, my_quotes) data = [tuple(iv) for iv in ivs] with open('test/data/{0}.py'.format(name), 'w') as f: if docstring: f.write(trepr(docstring)) f.write('\n') if isinstance(imports, (str, unicode)): f.write(imports) f.write('\n\n') elif isinstance(imports, (list, tuple, set)): for line in imports: f.write(line + '\n') f.write('\n') f.write('data = \\\n') pprint(data, f) if __name__ == '__main__': # ivs = gaps_rand() # write_ivs_data('ivs3', ivs, docstring=""" # Random integer ranges, with gaps. # """ # ) pprint(ivs)
a0519e36bce108138f822d346f8c9e267c9b2b11
gcpeixoto/FMECD
/_build/jupyter_execute/ipynb/06a-introducao-pandas.py
17,311
4.125
4
# Manipulação de dados com *pandas* ## Introdução *Pandas* é uma biblioteca para leitura, tratamento e manipulação de dados em *Python* que possui funções muito similares a softwares empregados em planilhamento, tais como _Microsoft Excel_, _LibreOffice Calc_ e _Apple Numbers_. Além de ser uma ferramenta de uso gratuito, ela possui inúmeras vantagens. Para saber mais sobre suas capacidades, veja [página oficial](https://pandas.pydata.org/about/index.html) da biblioteca. Nesta parte de nosso curso, aprenderemos duas novas estruturas de dados que *pandas* introduz: * *Series* e * *DataFrame*. Um *DataFrame* é uma estrutura de dados tabular com linhas e colunas rotuladas. | | Peso | Altura| Idade| Gênero | | :------------- |:-------------:| :-----:|:------:|:-----:| | Ana | 55 | 162 | 20 | `feminino` | | João | 80 | 178 | 19 | `masculino` | | Maria | 62 | 164 | 21 | `feminino` | | Pedro | 67 | 165 | 22 | `masculino`| | Túlio | 73 | 171 | 20 | `masculino` | As colunas do *DataFrame* são vetores unidimensionais do tipo *Series*, ao passo que as linhas são rotuladas por uma estrutura de dados especial chamada *index*. Os *index* no *Pandas* são listas personalizadas de rótulos que nos permitem realizar pesquisas rápidas e algumas operações importantes. Para utilizarmos estas estruturas de dados, importaremos as bibliotecas *numpy* utilizando o _placeholder_ usual *np* e *pandas* utilizando o _placeholder_ usual *pd*. import numpy as np import pandas as pd ## *Series* As *Series*: * são vetores, ou seja, são *arrays* unidimensionais; * possuem um *index* para cada entrada (e são muito eficientes para operar com base neles); * podem conter qualquer um dos tipos de dados (`int`, `str`, `float` etc.). ### Criando um objeto do tipo *Series* O método padrão é utilizar a função *Series* da biblioteca pandas: ```python serie_exemplo = pd.Series(dados_de_interesse, index=indice_de_interesse) ``` No exemplo acima, `dados_de_interesse` pode ser: * um dicionário (objeto do tipo `dict`); * uma lista (objeto do tipo `list`); * um objeto `array` do *numpy*; * um escalar, tal como o número inteiro 1. ### Criando *Series* a partir de dicionários dicionario_exemplo = {'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20} pd.Series(dicionario_exemplo) Note que o *index* foi obtido a partir das "chaves" dos dicionários. Assim, no caso do exemplo, o *index* foi dado por "Ana", "João", "Maria", "Pedro" e "Túlio". A ordem do *index* foi dada pela ordem de entrada no dicionário. Podemos fornecer um novo *index* ao dicionário já criado pd.Series(dicionario_exemplo, index=['Maria', 'Maria', 'ana', 'Paula', 'Túlio', 'Pedro']) Dados não encontrados são assinalados por um valor especial. O marcador padrão do *pandas* para dados faltantes é o `NaN` (*not a number*). ### Criando *Series* a partir de listas lista_exemplo = [1,2,3,4,5] pd.Series(lista_exemplo) Se os *index* não forem fornecidos, o *pandas* atribuirá automaticamente os valores `0, 1, ..., N-1`, onde `N` é o número de elementos da lista. ### Criando *Series* a partir de *arrays* do *numpy* array_exemplo = np.array([1,2,3,4,5]) pd.Series(array_exemplo) ### Fornecendo um *index* na criação da *Series* O total de elementos do *index* deve ser igual ao tamanho do *array*. Caso contrário, um erro será retornado. pd.Series(array_exemplo, index=['a','b','c','d','e','f']) pd.Series(array_exemplo, index=['a','b','c','d','e']) Além disso, não é necessário que que os elementos no *index* sejam únicos. pd.Series(array_exemplo, index=['a','a','b','b','c']) Um erro ocorrerá se uma operação que dependa da unicidade dos elementos no *index* for realizada, a exemplo do método `reindex`. series_exemplo = pd.Series(array_exemplo, index=['a','a','b','b','c']) series_exemplo.reindex(['b','a','c','d','e']) # 'a' e 'b' duplicados na origem ### Criando *Series* a partir de escalares pd.Series(1, index=['a', 'b', 'c', 'd']) Neste caso, um índice **deve** ser fornecido! ### *Series* comportam-se como *arrays* do *numpy* Uma *Series* do *pandas* comporta-se como um *array* unidimensional do *numpy*. Pode ser utilizada como argumento para a maioria das funções do *numpy*. A diferença é que o *index* aparece. Exemplo: series_exemplo = pd.Series(array_exemplo, index=['a','b','c','d','e']) series_exemplo[2] series_exemplo[:2] np.log(series_exemplo) Mais exemplos: serie_1 = pd.Series([1,2,3,4,5]) serie_2 = pd.Series([4,5,6,7,8]) serie_1 + serie_2 serie_1 * 2 - serie_2 * 3 Assim como *arrays* do *numpy*, as *Series* do *pandas* também possuem atributos *dtype* (data type). series_exemplo.dtype Se o interesse for utilizar os dados de uma *Series* do *pandas* como um *array* do *numpy*, basta utilizar o método `to_numpy` para convertê-la. series_exemplo.to_numpy() ### *Series* comportam-se como dicionários Podemos acessar os elementos de uma *Series* através das chaves fornecidas no *index*. series_exemplo series_exemplo['a'] Podemos adicionar novos elementos associados a chaves novas. series_exemplo['f'] = 6 series_exemplo 'f' in series_exemplo 'g' in series_exemplo Neste examplo, tentamos acessar uma chave inexistente. Logo, um erro ocorre. series_exemplo['g'] series_exemplo.get('g') Entretanto, podemos utilizar o método `get` para lidar com chaves que possivelmente inexistam e adicionar um `NaN` do *numpy* como valor alternativo se, de fato, não exista valor atribuído. series_exemplo.get('g',np.nan) ### O atributo `name` Uma *Series* do *pandas* possui um atributo opcional `name` que nos permite identificar o objeto. Ele é bastante útil em operações envolvendo *DataFrames*. serie_com_nome = pd.Series(dicionario_exemplo, name = "Idade") serie_com_nome ### A função `date_range` Em muitas situações, os índices podem ser organizados como datas. A função `data_range` cria índices a partir de datas. Alguns argumentos desta função são: - `start`: `str` contendo a data que serve como limite à esquerda das datas. Padrão: `None` - `end`: `str` contendo a data que serve como limite à direita das datas. Padrão: `None` - `freq`: frequência a ser considerada. Por exemplo, dias (`D`), horas (`H`), semanas (`W`), fins de meses (`M`), inícios de meses (`MS`), fins de anos (`Y`), inícios de anos (`YS`) etc. Pode-se também utilizar múltiplos (p.ex. `5H`, `2Y` etc.). Padrão: `None`. - `periods`: número de períodos a serem considerados (o período é determinado pelo argumento `freq`). Abaixo damos exemplos do uso de `date_range` com diferente formatos de data. pd.date_range(start='1/1/2020', freq='W', periods=10) pd.date_range(start='2010-01-01', freq='2Y', periods=10) pd.date_range('1/1/2020', freq='5H', periods=10) pd.date_range(start='2010-01-01', freq='3YS', periods=3) O exemplo a seguir cria duas *Series* com valores aleatórios associados a um interstício de 10 dias. indice_exemplo = pd.date_range('2020-01-01', periods=10, freq='D') serie_1 = pd.Series(np.random.randn(10),index=indice_exemplo) serie_2 = pd.Series(np.random.randn(10),index=indice_exemplo) ## *DataFrame* Como dissemos anterioremente, o *DataFrame* é a segunda estrutura basilar do *pandas*. Um *DataFrame*: - é uma tabela, ou seja, é bidimensional; - tem cada coluna formada como uma *Series* do *pandas*; - pode ter *Series* contendo tipos de dado diferentes. ### Criando um *DataFrame* O método padrão para criarmos um *DataFrame* é através de uma função com mesmo nome. ```python df_exemplo = pd.DataFrame(dados_de_interesse, index = indice_de_interesse, columns = colunas_de_interesse) ``` Ao criar um *DataFrame*, podemos informar - `index`: rótulos para as linhas (atributos *index* das *Series*). - `columns`: rótulos para as colunas (atributos *name* das *Series*). No _template_, `dados_de_interesse` pode ser * um dicionário de: * *arrays* unidimensionais do *numpy*; * listas; * dicionários; * *Series* do *pandas*. * um *array* bidimensional do *numpy*; * uma *Series* do *Pandas*; * outro *DataFrame*. ### Criando um *DataFrame* a partir de dicionários de *Series* Neste método de criação, as *Series* do dicionário não precisam possuir o mesmo número de elementos. O *index* do *DataFrame* será dado pela **união** dos *index* de todas as *Series* contidas no dicionário. Exemplo: serie_Idade = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22}, name="Idade") serie_Peso = pd.Series({'Ana':55, 'João': 80, 'Maria': 62, 'Pedro': 67, 'Túlio': 73}, name="Peso") serie_Altura = pd.Series({'Ana':162, 'João': 178, 'Maria': 162, 'Pedro': 165, 'Túlio': 171}, name="Altura") dicionario_series_exemplo = {'Idade': serie_Idade, 'Peso': serie_Peso, 'Altura': serie_Altura} df_dict_series = pd.DataFrame(dicionario_series_exemplo) df_dict_series Compare este resultado com a criação de uma planilha pelos métodos usuais. Veja que há muita flexibilidade para criarmos ou modificarmos uma tabela. Vejamos exemplos sobre como acessar intervalos de dados na tabela. pd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria']) pd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria'], columns=['Peso','Altura']) Neste exemplo, adicionamos a coluna `IMC`, ainda sem valores calculados. pd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria','Paula'], columns=['Peso','Altura','IMC']) df_exemplo_IMC = pd.DataFrame(dicionario_series_exemplo, columns=['Peso','Altura','IMC']) Agora, mostramos como os valores do IMC podem ser calculados diretamente por computação vetorizada sobre as *Series*. df_exemplo_IMC['IMC']=round(df_exemplo_IMC['Peso']/(df_exemplo_IMC['Altura']/100)**2,2) df_exemplo_IMC ### Criando um *DataFrame* a partir de dicionários de listas ou *arrays* do *numpy*: Neste método de criação, os *arrays* ou as listas **devem** possuir o mesmo comprimento. Se o *index* não for informado, o *index* será dado de forma similar ao do objeto tipo *Series*. Exemplo com dicionário de listas: dicionario_lista_exemplo = {'Idade': [20,19,21,22,20], 'Peso': [55,80,62,67,73], 'Altura': [162,178,162,165,171]} pd.DataFrame(dicionario_lista_exemplo) Mais exemplos: pd.DataFrame(dicionario_lista_exemplo, index=['Ana','João','Maria','Pedro','Túlio']) Exemplos com dicionário de *arrays* do *numpy*: dicionario_array_exemplo = {'Idade': np.array([20,19,21,22,20]), 'Peso': np.array([55,80,62,67,73]), 'Altura': np.array([162,178,162,165,171])} pd.DataFrame(dicionario_array_exemplo) Mais exemplos: pd.DataFrame(dicionario_array_exemplo, index=['Ana','João','Maria','Pedro','Túlio']) ### Criando um *DataFrame* a partir de uma *Series* do *pandas* Neste caso, o *DataFrame* terá o mesmo *index* que a *Series* do *pandas* e apenas uma coluna. series_exemplo = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20}) pd.DataFrame(series_exemplo) Caso a *Series* possua um atributo `name` especificado, este será o nome da coluna do *DataFrame*. series_exemplo_Idade = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20}, name="Idade") pd.DataFrame(series_exemplo_Idade) ### Criando um *DataFrame* a partir de lista de *Series* do *pandas* Neste caso, a entrada dos dados da lista no *DataFrame* será feita por linha. pd.DataFrame([serie_Peso, serie_Altura, serie_Idade]) Podemos corrigir a orientação usando o método `transpose`. pd.DataFrame([serie_Peso, serie_Altura, serie_Idade]).transpose() ### Criando um *DataFrame* a partir de arquivos Para criar um *DataFrame* a partir de um arquivo, precisamos de funções do tipo `pd.read_FORMATO`, onde `FORMATO` indica o formato a ser importado sob o pressuposto de que a biblioteca *pandas* foi devidamente importada com `pd`. Os formatos mais comuns são: * *csv* (comma-separated values), * *xls* ou *xlsx* (formatos do Microsoft Excel), * *hdf5* (comumente utilizado em *big data*), * *json* (comumente utilizado em páginas da internet). As funções para leitura correspondentes são: * `pd.read_csv`, * `pd.read_excel`, * `pd.read_hdf`, * `pd.read_json`, respectivamente. De todas elas, a função mais utilizada é `read_csv`. Ela possui vários argumentos. Vejamos os mais utilizados: * `file_path_or_buffer`: o endereço do arquivo a ser lido. Pode ser um endereço da internet. * `sep`: o separador entre as entradas de dados. O separador padrão é `,`. * `index_col`: a coluna que deve ser usada para formar o *index*. O padrão é `None`. Porém pode ser alterado para outro. Um separador comumente encontrado é o `\t` (TAB). * `names`: nomes das colunas a serem usadas. O padrão é `None`. * `header`: número da linha que servirá como nome para as colunas. O padrão é `infer` (ou seja, tenta deduzir automaticamente). Se os nomes das colunas forem passados através do `names`, então `header` será automaticamente considerado como `None`. **Exemplo:** considere o arquivo `data/exemplo_data.csv` contendo: ``` ,coluna_1,coluna_2 2020-01-01,-0.4160923582996922,1.8103644347460834 2020-01-02,-0.1379696602473578,2.5785204825192785 2020-01-03,0.5758273450544708,0.06086648807755068 2020-01-04,-0.017367186564883633,1.2995865328684455 2020-01-05,1.3842792448510655,-0.3817320973859929 2020-01-06,0.5497056238566345,-1.308789022968975 2020-01-07,-0.2822962331437976,-1.6889791765925102 2020-01-08,-0.9897300598660013,-0.028120707936426497 2020-01-09,0.27558240737928663,-0.1776585993494299 2020-01-10,0.6851316082235455,0.5025348904591399 ``` Para ler o arquivo acima basta fazer: df_exemplo_0 = pd.read_csv('data/exemplo_data.csv') df_exemplo_0 No exemplo anterior, as colunas receberam nomes corretamentes exceto pela primeira coluna que gostaríamos de considerar como *index*. Neste caso fazemos: df_exemplo = pd.read_csv('data/exemplo_data.csv', index_col=0) df_exemplo ### O método *head* do *DataFrame* O método `head`, sem argumento, permite que visualizemos as 5 primeiras linhas do *DataFrame*. df_exemplo.head() Se for passado um argumento com valor `n`, as `n` primeiras linhas são impressas. df_exemplo.head(2) df_exemplo.head(7) ### O método `tail` do *DataFrame* O método `tail`, sem argumento, retorna as últimas 5 linhas do *DataFrame*. df_exemplo.tail() Se for passado um argumento com valor `n`, as `n` últimas linhas são impressas. df_exemplo.tail(2) df_exemplo.tail(7) ### Atributos de *Series* e *DataFrames* Atributos comumente usados para *Series* e *DataFrames* são: * `shape`: fornece as dimensões do objeto em questão (*Series* ou *DataFrame*) em formato consistente com o atributo `shape` de um *array* do *numpy*. * `index`: fornece o índice do objeto. No caso do *DataFrame* são os rótulos das linhas. * `columns`: fornece as colunas (apenas disponível para *DataFrames*) Exemplo: df_exemplo.shape serie_1.shape df_exemplo.index serie_1.index df_exemplo.columns Se quisermos obter os dados contidos nos *index* ou nas *Series* podemos utilizar a propriedade `.array`. serie_1.index.array df_exemplo.columns.array Se o interesse for obter os dados como um `array` do *numpy*, devemos utilizar o método `.to_numpy()`. Exemplo: serie_1.index.to_numpy() df_exemplo.columns.to_numpy() O método `.to_numpy()` também está disponível em *DataFrames*: df_exemplo.to_numpy() A função do *numpy* `asarray()` é compatível com *index*, *columns* e *DataFrames* do *pandas*: np.asarray(df_exemplo.index) np.asarray(df_exemplo.columns) np.asarray(df_exemplo) ### Informações sobre as colunas de um *DataFrame* Para obtermos uma breve descrição sobre as colunas de um *DataFrame* utilizamos o método `info`. Exemplo: df_exemplo.info() ### Criando arquivos a partir de *DataFrames* Para criar arquivos a partir de *DataFrames*, basta utilizar os métodos do tipo `pd.to_FORMATO`, onde `FORMATO` indica o formato a ser exportado e supondo que a biblioteca *pandas* foi importada com `pd`. Com relação aos tipos de arquivo anteriores, os métodos para exportação correspondentes são: * `.to_csv` ('endereço_do_arquivo'), * `.to_excel` ('endereço_do_arquivo'), * `.to_hdf` ('endereço_do_arquivo'), * `.to_json`('endereço_do_arquivo'), onde `endereço_do_arquivo` é uma `str` que contém o endereço do arquivo a ser exportado. Exemplo: Para exportar para o arquivo `exemplo_novo.csv`, utilizaremos o método `.to_csv` ao *DataFrame* `df_exemplo`: df_exemplo.to_csv('data/exemplo_novo.csv') ### Exemplo COVID-19 PB Dados diários de COVID-19 do estado da Paraíba: *Fonte: https://superset.plataformatarget.com.br/superset/dashboard/microdados/* dados_covid_PB = pd.read_csv('https://superset.plataformatarget.com.br/superset/explore_json/?form_data=%7B%22slice_id%22%3A1550%7D&csv=true', sep=',', index_col=0) dados_covid_PB.info() dados_covid_PB.head() dados_covid_PB.tail() dados_covid_PB['estado'] = 'PB' dados_covid_PB.head() dados_covid_PB.to_csv('data/dadoscovidpb.csv')
6dc7111834363e610fde5cbb18a4d48156d7e2f1
gcpeixoto/FMECD
/_build/jupyter_execute/ipynb/06b-pandas-dataframe.py
24,063
4.09375
4
# Operações com *DataFrames* Como dissemos anterioremente, o *DataFrame* é a segunda estrutura basilar do *pandas*. Um *DataFrame*: - é uma tabela, ou seja, é bidimensional; - tem cada coluna formada como uma *Series* do *pandas*; - pode ter *Series* contendo tipos de dado diferentes. import numpy as np import pandas as pd ## Criação de um *DataFrame* O método padrão para criarmos um *DataFrame* é através de uma função com mesmo nome. ```python df_exemplo = pd.DataFrame(dados_de_interesse, index = indice_de_interesse, columns = colunas_de_interesse) ``` Ao criar um *DataFrame*, podemos informar - `index`: rótulos para as linhas (atributos *index* das *Series*). - `columns`: rótulos para as colunas (atributos *name* das *Series*). No _template_, `dados_de_interesse` pode ser * um dicionário de: * *arrays* unidimensionais do *numpy*; * listas; * dicionários; * *Series* do *pandas*. * um *array* bidimensional do *numpy*; * uma *Series* do *Pandas*; * outro *DataFrame*. ### *DataFrame* a partir de dicionários de *Series* Neste método de criação, as *Series* do dicionário não precisam possuir o mesmo número de elementos. O *index* do *DataFrame* será dado pela **união** dos *index* de todas as *Series* contidas no dicionário. Exemplo: serie_Idade = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22}, name="Idade") serie_Peso = pd.Series({'Ana':55, 'João': 80, 'Maria': 62, 'Pedro': 67, 'Túlio': 73}, name="Peso") serie_Altura = pd.Series({'Ana':162, 'João': 178, 'Maria': 162, 'Pedro': 165, 'Túlio': 171}, name="Altura") dicionario_series_exemplo = {'Idade': serie_Idade, 'Peso': serie_Peso, 'Altura': serie_Altura} df_dict_series = pd.DataFrame(dicionario_series_exemplo) df_dict_series Compare este resultado com a criação de uma planilha pelos métodos usuais. Veja que há muita flexibilidade para criarmos ou modificarmos uma tabela. Vejamos exemplos sobre como acessar intervalos de dados na tabela. pd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria']) pd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria'], columns=['Peso','Altura']) Neste exemplo, adicionamos a coluna `IMC`, ainda sem valores calculados. pd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria','Paula'], columns=['Peso','Altura','IMC']) df_exemplo_IMC = pd.DataFrame(dicionario_series_exemplo, columns=['Peso','Altura','IMC']) Agora, mostramos como os valores do IMC podem ser calculados diretamente por computação vetorizada sobre as *Series*. df_exemplo_IMC['IMC']=round(df_exemplo_IMC['Peso']/(df_exemplo_IMC['Altura']/100)**2,2) df_exemplo_IMC ### *DataFrame* a partir de dicionários de listas ou *arrays* do *numpy* Neste método de criação, os *arrays* ou as listas **devem** possuir o mesmo comprimento. Se o *index* não for informado, o *index* será dado de forma similar ao do objeto tipo *Series*. Exemplo com dicionário de listas: dicionario_lista_exemplo = {'Idade': [20,19,21,22,20], 'Peso': [55,80,62,67,73], 'Altura': [162,178,162,165,171]} pd.DataFrame(dicionario_lista_exemplo) Mais exemplos: pd.DataFrame(dicionario_lista_exemplo, index=['Ana','João','Maria','Pedro','Túlio']) Exemplos com dicionário de *arrays* do *numpy*: dicionario_array_exemplo = {'Idade': np.array([20,19,21,22,20]), 'Peso': np.array([55,80,62,67,73]), 'Altura': np.array([162,178,162,165,171])} pd.DataFrame(dicionario_array_exemplo) Mais exemplos: pd.DataFrame(dicionario_array_exemplo, index=['Ana','João','Maria','Pedro','Túlio']) ### *DataFrame* a partir de uma *Series* do *pandas* Neste caso, o *DataFrame* terá o mesmo *index* que a *Series* do *pandas* e apenas uma coluna. series_exemplo = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20}) pd.DataFrame(series_exemplo) Caso a *Series* possua um atributo `name` especificado, este será o nome da coluna do *DataFrame*. series_exemplo_Idade = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20}, name="Idade") pd.DataFrame(series_exemplo_Idade) ### *DataFrame* a partir de lista de *Series* do *pandas* Neste caso, a entrada dos dados da lista no *DataFrame* será feita por linha. pd.DataFrame([serie_Peso, serie_Altura, serie_Idade]) Podemos corrigir a orientação usando o método `transpose`. pd.DataFrame([serie_Peso, serie_Altura, serie_Idade]).transpose() ### *DataFrame* a partir de arquivos Para criar um *DataFrame* a partir de um arquivo, precisamos de funções do tipo `pd.read_FORMATO`, onde `FORMATO` indica o formato a ser importado sob o pressuposto de que a biblioteca *pandas* foi devidamente importada com `pd`. Os formatos mais comuns são: * *csv* (comma-separated values), * *xls* ou *xlsx* (formatos do Microsoft Excel), * *hdf5* (comumente utilizado em *big data*), * *json* (comumente utilizado em páginas da internet). As funções para leitura correspondentes são: * `pd.read_csv`, * `pd.read_excel`, * `pd.read_hdf`, * `pd.read_json`, respectivamente. De todas elas, a função mais utilizada é `read_csv`. Ela possui vários argumentos. Vejamos os mais utilizados: * `file_path_or_buffer`: o endereço do arquivo a ser lido. Pode ser um endereço da internet. * `sep`: o separador entre as entradas de dados. O separador padrão é `,`. * `index_col`: a coluna que deve ser usada para formar o *index*. O padrão é `None`. Porém pode ser alterado para outro. Um separador comumente encontrado é o `\t` (TAB). * `names`: nomes das colunas a serem usadas. O padrão é `None`. * `header`: número da linha que servirá como nome para as colunas. O padrão é `infer` (ou seja, tenta deduzir automaticamente). Se os nomes das colunas forem passados através do `names`, então `header` será automaticamente considerado como `None`. **Exemplo:** considere o arquivo `data/exemplo_data.csv` contendo: ``` ,coluna_1,coluna_2 2020-01-01,-0.4160923582996922,1.8103644347460834 2020-01-02,-0.1379696602473578,2.5785204825192785 2020-01-03,0.5758273450544708,0.06086648807755068 2020-01-04,-0.017367186564883633,1.2995865328684455 2020-01-05,1.3842792448510655,-0.3817320973859929 2020-01-06,0.5497056238566345,-1.308789022968975 2020-01-07,-0.2822962331437976,-1.6889791765925102 2020-01-08,-0.9897300598660013,-0.028120707936426497 2020-01-09,0.27558240737928663,-0.1776585993494299 2020-01-10,0.6851316082235455,0.5025348904591399 ``` Para ler o arquivo acima basta fazer: df_exemplo_0 = pd.read_csv('data/exemplo_data.csv') df_exemplo_0 No exemplo anterior, as colunas receberam nomes corretamentes exceto pela primeira coluna que gostaríamos de considerar como *index*. Neste caso fazemos: df_exemplo = pd.read_csv('data/exemplo_data.csv', index_col=0) df_exemplo #### O método *head* do *DataFrame* O método `head`, sem argumento, permite que visualizemos as 5 primeiras linhas do *DataFrame*. df_exemplo.head() Se for passado um argumento com valor `n`, as `n` primeiras linhas são impressas. df_exemplo.head(2) df_exemplo.head(7) #### O método `tail` do *DataFrame* O método `tail`, sem argumento, retorna as últimas 5 linhas do *DataFrame*. df_exemplo.tail() Se for passado um argumento com valor `n`, as `n` últimas linhas são impressas. df_exemplo.tail(2) df_exemplo.tail(7) ## Atributos de *Series* e *DataFrames* Atributos comumente usados para *Series* e *DataFrames* são: * `shape`: fornece as dimensões do objeto em questão (*Series* ou *DataFrame*) em formato consistente com o atributo `shape` de um *array* do *numpy*. * `index`: fornece o índice do objeto. No caso do *DataFrame* são os rótulos das linhas. * `columns`: fornece as colunas (apenas disponível para *DataFrames*) Exemplo: df_exemplo.shape serie_1 = pd.Series([1,2,3,4,5]) serie_1.shape df_exemplo.index serie_1.index df_exemplo.columns Se quisermos obter os dados contidos nos *index* ou nas *Series* podemos utilizar a propriedade `.array`. serie_1.index.array df_exemplo.columns.array Se o interesse for obter os dados como um `array` do *numpy*, devemos utilizar o método `.to_numpy()`. Exemplo: serie_1.index.to_numpy() df_exemplo.columns.to_numpy() O método `.to_numpy()` também está disponível em *DataFrames*: df_exemplo.to_numpy() A função do *numpy* `asarray()` é compatível com *index*, *columns* e *DataFrames* do *pandas*: np.asarray(df_exemplo.index) np.asarray(df_exemplo.columns) np.asarray(df_exemplo) ### Informações sobre as colunas de um *DataFrame* Para obtermos uma breve descrição sobre as colunas de um *DataFrame* utilizamos o método `info`. Exemplo: df_exemplo.info() ## Criando arquivos a partir de *DataFrames* Para criar arquivos a partir de *DataFrames*, basta utilizar os métodos do tipo `pd.to_FORMATO`, onde `FORMATO` indica o formato a ser exportado e supondo que a biblioteca *pandas* foi importada com `pd`. Com relação aos tipos de arquivo anteriores, os métodos para exportação correspondentes são: * `.to_csv` ('endereço_do_arquivo'), * `.to_excel` ('endereço_do_arquivo'), * `.to_hdf` ('endereço_do_arquivo'), * `.to_json`('endereço_do_arquivo'), onde `endereço_do_arquivo` é uma `str` que contém o endereço do arquivo a ser exportado. Exemplo: Para exportar para o arquivo `exemplo_novo.csv`, utilizaremos o método `.to_csv` ao *DataFrame* `df_exemplo`: df_exemplo.to_csv('data/exemplo_novo.csv') ### Exemplo COVID-19 PB Dados diários de COVID-19 do estado da Paraíba: *Fonte: https://superset.plataformatarget.com.br/superset/dashboard/microdados/* dados_covid_PB = pd.read_csv('https://superset.plataformatarget.com.br/superset/explore_json/?form_data=%7B%22slice_id%22%3A1550%7D&csv=true', sep=',', index_col=0) dados_covid_PB.info() dados_covid_PB.head() dados_covid_PB.tail() dados_covid_PB['estado'] = 'PB' dados_covid_PB.head() dados_covid_PB.to_csv('data/dadoscovidpb.csv') ### Índices dos valores máximos ou mínimos Os métodos `idxmin()` e `idxmax()` retornam o *index* cuja entrada fornece o valor mínimo ou máximo da *Series* ou *DataFrame*. Se houver múltiplas ocorrências de mínimos ou máximos, o método retorna a primeira ocorrência. Vamos recriar um *DataFrame* genérico. serie_Idade = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20}, name="Idade") serie_Peso = pd.Series({'Ana':55, 'João': 80, 'Maria': 62, 'Pedro': 67, 'Túlio': 73}, name="Peso") serie_Altura = pd.Series({'Ana':162, 'João': 178, 'Maria': 162, 'Pedro': 165, 'Túlio': 171}, name="Altura") dicionario_series_exemplo = {'Idade': serie_Idade, 'Peso': serie_Peso, 'Altura': serie_Altura} df_dict_series = pd.DataFrame(dicionario_series_exemplo) df_dict_series Assim, podemos localizar quem possui menores idade, peso e altura. df_dict_series.idxmin() De igual forma, localizamos quem possui maiores idade, peso e altura. df_dict_series.idxmax() **Exemplo:** Aplicaremos as funções `idxmin()` e `idxmax()` aos dados do arquivo `data/exemplo_data.csv` para localizar entradas de interesse. df_exemplo = pd.read_csv('data/exemplo_data.csv', index_col=0); df_exemplo df_exemplo = pd.DataFrame(df_exemplo, columns=['coluna_1','coluna_2','coluna_3']) Inserimos uma terceira coluna com dados fictícios. df_exemplo['coluna_3'] = pd.Series([1,2,3,4,5,6,7,8,np.nan,np.nan],index=df_exemplo.index) df_exemplo Os *index* correspondentes aos menores e maiores valores são datas, evidentemente. df_exemplo.idxmin() df_exemplo.idxmax() ### Reindexação de *DataFrames* No *pandas*, o método `reindex` * reordena o *DataFrame* de acordo com o conjunto de rótulos inserido como argumento; * insere valores faltantes caso um rótulo do novo *index* não tenha valor atribuído no conjunto de dados; * remove valores correspondentes a rótulos que não estão presentes no novo *index*. Exemplos: df_dict_series.reindex(index=['Victor', 'Túlio', 'Pedro', 'João'], columns=['Altura','Peso','IMC']) ## Remoção de linhas ou colunas de um *DataFrame* Para remover linhas ou colunas de um *DataFrame* do *pandas* podemos utilizar o método `drop`. O argumento `axis` identifica o eixo de remoção: `axis=0`, que é o padrão, indica a remoção de uma ou mais linhas; `axis=1` indica a remoção de uma ou mais colunas. Nos exemplos que segue, note que novos *DataFrames* são obtidos a partir de `df_dict_series` sem que este seja sobrescrito. df_dict_series.drop('Túlio') # axis=0 implícito df_dict_series.drop(['Ana','Maria'], axis=0) df_dict_series.drop(['Idade'], axis=1) ### Renomeando *index* e *columns* O método `rename` retorna uma cópia na qual o *index* (no caso de *Series* e *DataFrames*) e *columns* (no caso de *DataFrames*) foram renomeados. O método aceita como entrada um dicionário, uma *Series* do *pandas* ou uma função. Exemplo: serie_exemplo = pd.Series([1,2,3], index=['a','b','c']) serie_exemplo serie_exemplo.rename({'a':'abacaxi', 'b':'banana', 'c': 'cebola'}) Exemplo: df_dict_series df_dict_series.rename(index = {'Ana':'a', 'João':'j', 'Maria':'m', 'Pedro':'p','Túlio':'t'}, columns = {'Idade':'I', 'Peso':'P','Altura':'A'}) No próximo exemplo, usamos uma *Series* para renomear os rótulos. indice_novo = pd.Series({'Ana':'a', 'João':'j', 'Maria':'m', 'Pedro':'p','Túlio':'t'}) df_dict_series.rename(index = indice_novo) Neste exemplo, usamos a função `str.upper` (altera a `str` para "todas maiúsculas") para renomear colunas. df_dict_series.rename(columns=str.upper) ## Ordenação de *Series* e *DataFrames* É possível ordenar ambos pelos rótulos do *index* (para tanto é necessário que eles sejam ordenáveis) ou por valores nas colunas. O método `sort_index` ordena a *Series* ou o *DataFrame* pelo *index*. O método `sort_values` ordena a *Series* ou o *DataFrame* pelos valores (escolhendo uma ou mais colunas no caso de *DataFrames*). No caso do *DataFrame*, o argumento `by` é necessário para indicar qual(is) coluna(s) será(ão) utilizada(s) como base para a ordenação. Exemplos: serie_desordenada = pd.Series({'Maria': 21, 'Pedro': 22, 'Túlio': 20, 'João': 19, 'Ana':20}); serie_desordenada serie_desordenada.sort_index() # ordenação alfabética Mais exemplos: df_desordenado = df_dict_series.reindex(index=['Pedro','Maria','Ana','Túlio','João']) df_desordenado df_desordenado.sort_index() Mais exemplos: serie_desordenada.sort_values() df_desordenado.sort_values(by=['Altura']) # ordena por 'Altura' No caso de "empate", podemos utilizar outra coluna para desempatar. df_desordenado.sort_values(by=['Altura','Peso']) # usa a coluna 'Peso' para desempatar Os métodos `sort_index` e `sort_values` admitem o argumento opcional `ascending`, que permite inverter a ordenação caso tenha valor `False`. df_desordenado.sort_index(ascending=False) df_desordenado.sort_values(by=['Idade'], ascending=False) ## Comparação de *Series* e *DataFrames* *Series* e *DataFrames* possuem os seguintes métodos de comparação lógica: - `eq` (igual); - `ne` (diferente); - `lt` (menor do que); - `gt` (maior do que); - `le` (menor ou igual a); - `ge` (maior ou igual a) que permitem a utilização dos operadores binários `==`, `!=`, `<`, `>`, `<=` e `>=`, respectivamente. As comparações são realizadas em cada entrada da *Series* ou do *DataFrame*. **Observação**: Para que esses métodos sejam aplicados, todos os objetos presentes nas colunas do *DataFrame* devem ser de mesma natureza. Por exemplo, se um *DataFrame* possui algumas colunas numéricas e outras com *strings*, ao realizar uma comparação do tipo `> 1`, um erro ocorrerá, pois o *pandas* tentará comparar objetos do tipo `int` com objetos do tipo `str`, assim gerando uma incompatibilidade. Exemplos: serie_exemplo serie_exemplo == 2 De outra forma: serie_exemplo.eq(2) serie_exemplo > 1 Ou, na forma funcional: serie_exemplo.gt(1) df_exemplo > 1 **Importante:** Ao comparar *np.nan*, o resultado tipicamente é falso: np.nan == np.nan np.nan > np.nan np.nan >= np.nan Só é verdadeiro para indicar que é diferente: np.nan != np.nan Neste sentido, podemos ter tabelas iguais sem que a comparação usual funcione: # 'copy', como o nome sugere, gera uma cópia do DataFrame df_exemplo_2 = df_exemplo.copy() (df_exemplo == df_exemplo_2) O motivo de haver entradas como `False` ainda que `df_exemplo_2` seja uma cópia exata de `df_exemplo` é a presença do `np.nan`. Neste caso, devemos utilizar o método `equals` para realizar a comparação. df_exemplo.equals(df_exemplo_2) ## Os métodos `any`, `all` e a propriedade `empty` O método `any` é aplicado a entradas booleanas (verdadeiras ou falsas) e retorna *verdadeiro* se existir alguma entrada verdadeira, ou *falso*, se todas forem falsas. O método `all` é aplicado a entradas booleanas e retorna *verdadeiro* se todas as entradas forem verdadeiras, ou *falso*, se houver pelo menos uma entrada falsa. A propriedade `empty` retorna *verdadeiro* se a *Series* ou o *DataFrame* estiver vazio, ou *falso* caso contrário. Exemplos: serie_exemplo serie_exemplo_2 = serie_exemplo-2; serie_exemplo_2 (serie_exemplo_2 > 0).any() (serie_exemplo > 1).all() Este exemplo reproduz um valor `False` único. (df_exemplo == df_exemplo_2).all().all() serie_exemplo.empty Mais exemplos: (df_exemplo == df_exemplo_2).any() df_exemplo.empty df_vazio = pd.DataFrame() df_vazio.empty ## Seleção de colunas de um *DataFrame* Para selecionar colunas de um *DataFrame*, basta aplicar *colchetes* a uma lista contendo os nomes das colunas de interesse. No exemplo abaixo, temos um *DataFrame* contendo as colunas `'Idade'`, `'Peso'` e `'Altura'`. Selecionaremos `'Peso'` e `'Altura'`, apenas. df_dict_series[['Peso','Altura']] Se quisermos selecionar apenas uma coluna, não há necessidade de inserir uma lista. Basta utilizar o nome da coluna: df_dict_series['Peso'] Para remover colunas, podemos utilizar o método `drop`. df_dict_series.drop(['Peso','Altura'], axis=1) ### Criação de novas colunas a partir de colunas existentes Um método eficiente para criar novas colunas a partir de colunas já existentes é `eval`. Neste método, podemos utilizar como argumento uma *string* contendo uma expressão matemática envolvendo nomes de colunas do *DataFrame*. Como exemplo, vamos ver como calcular o IMC no *DataFrame* anterior: df_dict_series.eval('Peso/(Altura/100)**2') Se quisermos obter um *DataFrame* contendo o IMC como uma nova coluna, podemos utilizar o método `assign` (sem modificar o *DataFrame* original): df_dict_series.assign(IMC=round(df_dict_series.eval('Peso/(Altura/100)**2'),2)) df_dict_series # não modificado Se quisermos modificar o *DataFrame* para incluir a coluna IMC fazemos: df_dict_series['IMC']=round(df_dict_series.eval('Peso/(Altura/100)**2'),2) df_dict_series # modificado "in-place" ## Seleção de linhas de um *DataFrame* Podemos selecionar linhas de um *DataFrame* de diversas formas diferentes. Veremos agora algumas dessas formas. Diferentemente da forma de selecionar colunas, para selecionar diretamente linhas de um *DataFrame* devemos utilizar o método `loc` (fornecendo o *index*, isto é, o rótulo da linha) ou o `iloc` (fornecendo a posição da linha): Trabalharemos a seguir com um banco de dados atualizado sobre a COVID-19. Para tanto, importaremos o módulo `datetime` que nos auxiliará com datas. import datetime dados_covid_PB = pd.read_csv('https://superset.plataformatarget.com.br/superset/explore_json/?form_data=%7B%22slice_id%22%3A1550%7D&csv=true', sep=',', index_col=0) # busca o banco na data D-1, visto que a atualização # ocorre em D ontem = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d') dados_covid_PB.head(1) Podemos ver as informações de um único dia como argumento. Para tanto, excluímos a coluna `'Letalidade'` (valor não inteiro) e convertemos o restante para valores inteiros: dados_covid_PB.loc[ontem].drop('Letalidade').astype('int') Podemos selecionar um intervalo de datas como argumento (excluindo letalidade): dados_covid_PB.index = pd.to_datetime(dados_covid_PB.index) # Convertendo o index de string para data dados_covid_PB.loc[pd.date_range('2021-02-01',periods=5,freq="D")].drop('Letalidade',axis=1) #função pd.date_range é muito útil para criar índices a partir de datas. Podemos colocar uma lista como argumento: dados_covid_PB.loc[pd.to_datetime(['2021-01-01','2021-02-01'])] Vamos agora examinar os dados da posição 100 (novamente excluindo a coluna letalidade e convertendo para inteiro): dados_covid_PB.iloc[100].drop('Letalidade').astype('int') Podemos colocar um intervalo como argumento: dados_covid_PB.iloc[50:55].drop('Letalidade', axis=1).astype('int') ### Seleção de colunas com `loc` e `iloc` Podemos selecionar colunas utilizando os métodos `loc` e `iloc` utilizando um argumento adicional. dados_covid_PB.loc[:,['casosNovos','obitosNovos']] dados_covid_PB.iloc[:,4:6] # fatiamento na coluna ### Seleção de linhas e colunas específicas com `loc` e `iloc` Usando o mesmo princípio de *fatiamento* aplicado a *arrays* do numpy, podemos selecionar linhas e colunas em um intervalo específico de forma a obter uma subtabela. dados_covid_PB.iloc[95:100,4:6] Neste exemplo um pouco mais complexo, buscamos casos novos e óbitos novos em um período específico e ordenamos a tabela da data mais recente para a mais antiga. dados_covid_PB.loc[pd.date_range('2020-04-06','2020-04-10'),['casosNovos','obitosNovos']].sort_index(ascending=False) Suponha que o peso de Ana foi medido corretamente, mas registrado de maneira errônea no *DataFrame* `df_dict_series` como 55. df_dict_series Supondo que, na realidade, o valor é 65, alteramos a entrada específica com um simples `loc`. Em seguida, atualizamos a tabela. df_dict_series.loc['Ana','Peso'] = 65 df_dict_series = df_dict_series.assign(IMC=round(df_dict_series.eval('Peso/(Altura/100)**2'),2)) # O IMC mudou df_dict_series ### Seleção de linhas através de critérios lógicos ou funções Vamos selecionar quais os dias em que houve mais de 40 mortes registradas: dados_covid_PB.loc[dados_covid_PB['obitosNovos']>40] Selecionando os dias com mais de 25 óbitos e mais de 1500 casos novos: dados_covid_PB.loc[(dados_covid_PB.obitosNovos > 25) & (dados_covid_PB.casosNovos>1500)] **Obs**.: Note que podemos utilizar o nome da coluna como um atributo. Vamos inserir uma coluna sobrenome no `df_dict_series`: df_dict_series['Sobrenome'] = ['Silva', 'PraDo', 'Sales', 'MachadO', 'Coutinho'] df_dict_series Vamos encontrar as linhas cujo sobrenome termina em "do". Para tanto, note que a função abaixo retorna `True` se o final é "do" e `False` caso contrário. ```python def verifica_final_do(palavra): return palavra.lower()[-2:] == 'do' ``` **Obs**.: Note que convertemos tudo para minúsculo. Agora vamos utilizar essa função para alcançar nosso objetivo: # 'map' aplica a função lambda a cada elemento da *Series* df_dict_series['Sobrenome'].map(lambda palavra: palavra.lower()[-2:]=='do') # procurando no df inteiro df_dict_series.loc[df_dict_series['Sobrenome'].map(lambda palavra: palavra.lower()[-2:]=='do')] Vamos selecionar as linhas do mês 2 (fevereiro) usando `index.month`: dados_covid_PB.loc[dados_covid_PB.index.month==2].head() ### Seleção de linhas com o método *query* Similarmente ao método `eval`, ao utilizarmos `query`, podemos criar expressões lógicas a partir de nomes das colunas do *DataFrame*. Assim, podemos reescrever o código ```python dados_covid_PB.loc[(dados_covid_PB.obitosNovos>25) & (dados_covid_PB.casosNovos>1500)] ``` como dados_covid_PB.query('obitosNovos>25 and casosNovos>1500') # note que 'and' é usado em vez de '&'
765d8781c32f938bf3174f675c223fe72ee4d115
harimha/PycharmProjects
/Modules_usage/Syntax_built-in_usage.py
17,976
3.9375
4
""" This documents has been writing to show how to use python syntax and built-in module/function navigator # syn : ... : syntax # bi : ... : built_in function or module # method : ... # : comments / examples """ # syn : is """ id object가 같은지 비교 id(a) == id(b) 비교와 같음 """ a = [1,2,3] b = [1,2,3] a == b # True a is b # False print(id(a), id(b)) # id가 다름 b = a print(id(a), id(b)) # id 같음 a is b # bi : dir() """ return list of attributes and method which can be used """ dir(str) # bi : help() """ return documents about how to use """ help(str) help(str.lower) # 사용법, 도움말 확인 # bi : str() """ String Data """ dir(str) help(str) # str object indexing m = "Hello World" m[0] m[-1] m[:5] # method : str.lower() """ Return a copy of the string converted to lowercase """ m = "Hello World" m.lower() # method : str.upper() """ Retunr a copy of the string converted to uppercase """ m = "Hello World" m.upper() # method : str.count() """ 해당 character 개수 counting """ m = "Hello World" m.count("l") m.count("rld") # method : str.find() """ 해당 character start index 반환 """ m = "Hello World" m.find("World") m[m.find("World"):] m.find("Univers") # 없는 단어는 -1 반환 # method : str.replace() """ replace the character """ m = "Hello World" m.replace("World","Universe") # method : str.format() # syn : f"" """ string object formatting """ greeting = "Hello" name = "Michael" m = "{}, {}. Welcome!".format(greeting, name) m # 위와 같은 표현 m = f"{greeting}, {name.upper()}. Welcome!" m # ex) "My name is %s" %"하림" "My name is {}".format("하림") "{} x {} = {}".format(2,3,2*3) "{2} x {0} = {1}".format(3,2*3,2) # 순서 지정 가능 "{0:.4f}".format(0.12345) # 소수점 4째자리 까지 나타냄 # method : str.join() """ Concatenate any number of strings. """ help(str.join) course = ["History", "Math", "Physics"] course_str = ", ".join(course) course_str course_str = "-".join(course) course_str # method : str.split() """ Return a list of the words in the string, using sep as the delimiter string. """ help(str.split) course = ["History", "Math", "Physics"] course_str = "-".join(course) course_str.split("-") # bi : Dictionary(dict) """ Dictionary data 활용 """ dir(dict) help(dict) # method : dict.get() """ Return the value for key 잘못된 key가 들어오면 error가 아닌 지정한 값 반환 """ help(dict.get) student = {"name" : "john", "age" : 25, "courses" : ["Math","CompSci"]} student.get("age") student["Phone"] # 에러발생 print(student.get("Phone")) # None 반환 student.get("Phone", "Not found") # method : dict.get() """ update data """ help(dict.update) student = {"name" : "john", "age" : 25, "courses" : ["Math","CompSci"]} student.update({"name" : "Jane", "age" : 26, "Phone" : "555"}) student # syn : del """ delete key:value """ student = {"name" : "john", "age" : 25, "courses" : ["Math","CompSci"]} del student["age"] student # method : dict.pop() """ remove specified key and return the corresponding valu """ help(dict.pop) student = {"name" : "john", "age" : 25, "courses" : ["Math","CompSci"]} student.pop("age") student # bi : List dir(list) help(list) # Empty List empty_list = [] empty_list = list() # method : list.insert() """ Insert object before index extend와 구별 """ help(list.insert) courses = ["History", "Math", "Physics", "CompSci"] courses.insert(3,"Act") courses_2 = ["Art", "Education"] courses.insert(0,courses_2) courses # method : list.extend() """ Extend list by appending elements from the iterable. """ help(list.extend) courses = ["History", "Math", "Physics", "CompSci"] courses_2 = ["Art", "Education"] courses.extend(courses_2) courses # method : list.remove() """ Remove first occurrence of value. """ help(list.remove) courses = ["History", "Math", "Physics", "CompSci"] courses.remove('Math') courses # method : list.pop() """ Remove and return item at index (default last). """ help(list.pop) courses = ["History", "Math", "Physics", "CompSci"] courses.pop(1) # 1번째 데이터 삭제 # method : list.reverse() """ Reverse *IN PLACE* """ help(list.reverse) courses = ["History", "Math", "Physics", "CompSci"] courses.reverse() courses # method : list.sort() """ Stable sort *IN PLACE* default ascending order """ help(list.sort) nums = [1,5,2,4,3] nums.sort() nums nums.sort(reverse=True) nums # method : list.index() """ Return first index of value. """ help(list.index) courses = ["History", "Math", "Physics", "CompSci"] courses.index("Physics") # bi : Tuple dir(tuple) help(tuple) # Empty Tuple empty_tuple = () empty_tuple = tuple() # bi : Set dir(set) help(set) # Empty Set empty_set = set() # method : set.intersection() """ Return the intersection of two sets as a new set. """ help(set.intersection) cs_courses = {"History", "Math", "Physics", "CompSci"} art_courses = {"History", "Math", "Art", "Design"} cs_courses.intersection(art_courses) # method : set.difference() """ Return the difference of two or more sets as a new set. """ help(set.difference) cs_courses = {"History", "Math", "Physics", "CompSci"} art_courses = {"History", "Math", "Art", "Design"} cs_courses.difference(art_courses) # method : set.union() """ Return the union of sets as a new set. """ help(set.union) cs_courses = {"History", "Math", "Physics", "CompSci"} art_courses = {"History", "Math", "Art", "Design"} cs_courses.union(art_courses) # bi : sorted() """ sorting method """ help(sorted) nums = [5, 3, 1, 2, 6] sorted(nums) # bi : min() help(min) nums = [5, 3, 1, 2, 6] min(nums) # bi : max() help(max) nums = [5, 3, 1, 2, 6] max(nums) # bi : sum() help(sum) nums = [5, 3, 1, 2, 6] sum(nums) # syn : in """ 해당 data가 interable data에 있는지 확인 """ courses = ["History", "Math", "Physics", "CompSci"] "Math" in courses "math" in courses # 대소문자 구분 # syn : Arithmetic Operators # Floor Division 3 // 2 # Exponent 3 ** 2 # Modulus """ Return remainder """ 3 % 2 5 % 3 # bi : abs() """ convert the number to absolute value """ abs(-3) # bi : round() help(round) round(3.75) round(3.3) round(3.75, 1) # decimal digits round(43.75, -1) # syn : def """ define function 반복되는 코드는 함수로 만들어서 사용하면 나중에 수정할 때 편리 """ # set default parameter value def hello_func(greeting, name="You") : # name의 default 값 설정 return "{}, {}".format(greeting,name) print(hello_func("Hi")) print(hello_func("Hi", name = "Corey")) # positional arguments have to come before keyword arguments print(hello_func(name = "Corey", "Hi")) # error # syn : *args **kwargs """ Using this, when we don't know how many positional arguments and keword arguments are used args : positional argument, 함수 괄호안에 들어가는 일반적인 parameter list형으로 unpacking하여 넘겨주면 tuple형으로 return kwargs : keyword argument, 함수 괄호안에 keyword = value로 들어가는 parameter dictionary형으로 unpacking하여 넘겨준다. """ def student_info(*args, **kwargs): print(args) print(kwargs) student_info("Math", "Art", name="John", age=22) # packing courses = ["Math", "Art"] info = {"name":"John", "age":22} # unpacking """ use * or ** to unpacking """ student_info(courses,info) # not unpacking student_info(*courses,**info) # unpacking # syn : Module """ python module file is .py packing modules is Package """ # path which modules are imported from """ Modules can be imported when the module's path is included in the sys.path find the module in current dir and next sys.path's order """ import sys sys.path # Adding path """ 1. sys.path.add("C:/모듈위치") 2. add windows environment variable : 제어판 -> 시스템 및 보안 -> 시스템 -> 설정변경 -> 고급 -> 환경변수 -> 사용자변수 새로만들기 -> 변수명 = PYTHONPATH, 변수값 = "C:/모듈위치" """ # import module methods """ how to import module """ import pandas import pandas as pd from pandas import DataFrame from pandas import Series, DataFrame from pandas import Series as SR, DataFrame as DF from pandas import * # import all method # find module's location """ use __file__(Dunder file) to find module's location """ import random random random.__file__ import time time # built-in module time.__file__ # bi : enumerate() """ 열거하다 순서와 값을 각각 저장해서 enumerate object 생성 """ help(enumerate) courses = ["History", "Math", "Physics", "CompSci"] data = enumerate(courses, start=1) type(data) # enumerate 타입 for i, value in data : print(i, value) # syn : for """ loop code finite times """ # for문, if문 리스트 내포(List comprehension) """ [표현식 for 항목 in 반복가능객체 if 조건문 else 표현식] """ a = [1,2,3,4] result = [num * 3 for num in a] print(result) a = [1,2,3,4] result = [num * 3 for num in a if num % 2 == 0] print(result) """ 위와 같은 표현 a = [1,2,3,4] result = [] for num in a: result.append(num*3) """ # list comprehenstion muliti for loop result = [x*y for x in range(2,10) for y in range(1,10)] print(result) # syn : break """ break out loop """ nums = [1,2,3,4,5] for num in nums : if num == 3: print("Found!") break print(num) # syn : continue """ skip next iteration """ nums = [1,2,3,4,5] for num in nums : if num == 3: print("Found!") continue print(num) # syn : while """ 조건 만족할 때 까지 무한 루프 """ x = 0 while x < 5 : print(x) x += 1 x = 0 while x < 10 : if x == 5 : break print(x) x+=1 x = 0 while True : # 무한 루프 실행 if x == 5: break print(x) x+=1 # syn : Class """ create blueprint for reducing repetitive using of code """ # __init__ (initialize) """ define initialized attributes this will be executed when instance is initialized """ class BusinessCard() : def __init__(self, name, email, addr): self.name = name self.email = email self.addr = addr def print_info(self): print("------------------------") print("Name : ", self.name) print("Email : ", self.email) print("Address : ", self.addr) print("------------------------") member = BusinessCard("하림","cceedd", "전주시") member.print_info() # Class variable class Account : accountnum = 0 # Class variable def __init__(self, name): self.name = name # instance variable Account.accountnum += 1 def __del__(self): Account.accountnum -= 1 Account.accountnum Kim = Account("Kim") Lee = Account("Lee") # if the attribute not exist in instance's namespace, # find it in class's namespace Kim.__dict__ # instance's namespace Kim.accountnum Account.__dict__ # class's namespace Account.accountnum # Regular methods, Class methods, Static methods """ Regular methods are methods that automatically take 'the instance' as the first argument. Class methods are methods that automatically take 'the class' as the first argument. Static methods 'do not take' the instance or the class as the first argument. """ class Employee : num_of_emps = 0 raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.email = first + "." + last + "@email.com" self.pay = pay Employee.num_of_emps += 1 def fullname(self): # Regular method return "{} {}".format(self.first,self.last) def apply_raise(self): self.pay = int(self.pay*self.raise_amt) @classmethod # Regular method -> Class method def set_raise_amt(cls, amount): # cls : class cls.raise_amt = amount @classmethod def from_string(cls, emp_str): """ string data에서 parameter parsing후 class instance만들기 """ first, last, pay = emp_str.split("-") return cls(first, last, pay) @staticmethod # Regular method -> Static method def is_workday(day): if day.weekday() == 5 or day.weekday() == 6 : return False return True emp_1 = Employee("Corey", "Schafer", 50000) emp_2 = Employee("Test", "Employee", 60000) # class methods 활용 Employee.set_raise_amt(1.05) print(Employee.raise_amt, emp_1.raise_amt, emp_2.raise_amt) emp_str_1 = "John-Doe-70000" emp_str_2 = "Steve-Smith-30000" new_emp_1 = Employee.from_string(emp_str_1) new_emp_2 = Employee.from_string(emp_str_2) print(new_emp_1.fullname(),new_emp_2.fullname()) # static method 활용 """ if the method that we want to create don't need class or instance, we use static method """ import datetime my_date = datetime.date(2016, 7, 10) print(Employee.is_workday(my_date)) # class inheritance """ Creating sub class inherited from parent class makes easy to upgrade or to manage class """ class Employee : raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.email = first + "." + last + "@email.com" self.pay = pay def fullname(self): # Regular method return "{} {}".format(self.first,self.last) def apply_raise(self): self.pay = int(self.pay*self.raise_amt) # bi : super() """ sub class inherit the code from parent class """ class Developer(Employee): raise_amt = 1.10 # sub class variable def __init__(self, first, last, pay, prog_lang): super().__init__(first, last, pay) self.prog_lang = prog_lang dev_1 = Developer("Corey", "Schafer", 50000, "Python") dev_2 = Developer("Test", "Employee", 60000, "Java") help(Developer) # information of inheritance dev_1.pay dev_1.apply_raise() dev_1.pay dev_1.prog_lang # upgrade sub class class Manager(Employee): def __init__(self, first, last, pay, employees=None): super().__init__(first, last, pay) if employees is None: self.employees =[] else : self.employees = employees def add_emp(self, emp): if emp not in self.employees: self.employees.append(emp) def remove_emp(self, emp): if emp in self.employees: self.employees.remove(emp) def print_emps(self): for emp in self.employees: print("-->", emp.fullname()) help(Manager) mgr_1 = Manager("Sue", "Smith", 90000, [dev_1]) mgr_1.print_emps() mgr_1.add_emp(dev_2) mgr_1.print_emps() mgr_1.remove_emp(dev_2) mgr_1.print_emps() # bi : isinstance """ check whether the instance is come from the class """ isinstance(mgr_1, Manager) isinstance(mgr_1, Employee) # parent class isinstance(mgr_1, Developer) # bi : issubclass """ check whether the subclass is come from the class """ issubclass(Manager, Employee) issubclass(Developer, Employee) issubclass(Manager, Developer) # syn : Dunder """ Double underscore : __something__ someone call this Magic method Python Doc : https://docs.python.org/3/reference/datamodel.html#special-method-names """ class Employee : def __init__(self, first, last, pay): self.first = first self.last = last self.email = first + "." + last + "@email.com" self.pay = pay def fullname(self): # Regular method return "{} {}".format(self.first,self.last) # Dunder 예시 def __repr__(self): """ change to unambiguous representation of objects """ return "Employee('{}', '{}', {})".format(self.first, self.last, self.pay) def __str__(self): return '{} - {}'.format(self.fullname(), self.email) def __add__(self, other): return self.pay + other.pay emp_1 = Employee("Corey", "Schafer", 50000) emp_2 = Employee("Test", "Employee", 60000) emp_1 # __repr__ method 사용으로 바뀐 결과 repr(emp_1) emp_1.__repr__() # 위와 같음 str(emp_1) emp_1.__str__() # 위와 같음 1+2 int.__add__(1,2) # 위와 동일한 background에서 실행되는 코드 "a"+"b" str.__add__("a","b") # 위와 동일한 background에서 실행되는 코드 emp_1+emp_2 Employee.__add__(emp_1,emp_2) # syn : Property Decorators """ Getters : @property Setters : @property.setter Deleters : @property.deleter """ # 문제점 class Employee : def __init__(self, first, last): self.first = first self.last = last self.email = first + "." + last + "@email.com" def fullname(self): # Regular method return "{} {}".format(self.first,self.last) emp_1 = Employee("John", "Smith") emp_1.first = "James" print(emp_1.first) print(emp_1.email) # 초기 생성된 property가 변하지 않는 문제 print(emp_1.fullname()) # 해결 class Employee : def __init__(self, first, last): self.first = first self.last = last @property # Regular method -> property def email(self): return '{}.{}@email.com'.format(self.first, self.last) @property def fullname(self): # Regular method return "{} {}".format(self.first,self.last) @fullname.setter # property 변경 가능하도록 하기 위함 def fullname(self, name): first, last = name.split(" ") self.first = first self.last = last @fullname.deleter # property 삭제하기 위함 def fullname(self): self.first = None self.last = None emp_1 = Employee("John", "Smith") emp_1.first = "James" print(emp_1.first) print(emp_1.email) print(emp_1.fullname) # setter 활용 emp_1.fullname = "Harim Jeong" print(emp_1.first) print(emp_1.email) print(emp_1.fullname) # deleter 활용 del emp_1.fullname print(emp_1.first) print(emp_1.email) print(emp_1.fullname) #### PEP8 """ 일관된 코딩작성방법과 관련된 문서 https://b.luavis.kr/python/python-convention 한글버전 """ ## assert """ 코드를 점검하는데 사용된다. assert 조건문 만약 조건문이 True이면 아무런 행동을 하지 않고 False이면 assertion error를 발생시킨다. """ assert 1==1 assert 1==2
8caac84b2f1ec8350cb3117cf9c94143ed5fa023
harimha/PycharmProjects
/Modules_usage/데이터 시각화_활용.py
5,345
3.5625
4
""" Python 시각화 라이브러리 1. matplotlib 2. seaborn 3. plotnine 4. folium 5. plot.ly 6. pyecharts """ import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt # 1. matplotlib """ https://matplotlib.org/index.html """ print("Matplotlib version", matplotlib.__version__) # 버전확인 # plt.figure """ 그래프 그리기 전 도화지 """ plt.figure(figsize=(10,5)) # 그래프 그리기 전 도화지 fig = plt.figure() fig.suptitle('figure sample plots') # 제목 fig.set_size_inches(10,10) # 가로 10 iniches, 세로 10 inches # plt.rcParams """ Parameter """ plt.rcParams['figure.figsize'] = (10,5) # parameter로 지정해서 넘길 수 있음 # plt.subplots() """ (행,열,번호) 도화지 분할 개념 """ plt.subplot(2,2,1) plt.hist(pd.DataFrame(np.random.random(100))[0]) plt.subplot(2,2,4) plt.hist(pd.DataFrame(np.random.random(100))[0]) # Axes " plot이 그려지는 공간 " # Axis " plot의 축 " fig = plt.figure() fig, axes_list = plt.subplots(2, 2, figsize=(8,5)) # 각 객체를 변수로 담을 수 있음 # plotting axes_list[0][0].plot([1,2,3,4], 'ro-') axes_list[0][1].plot(np.random.randn(4, 10), np.random.randn(4,10), 'bo--') axes_list[1][0].plot(np.linspace(0.0, 5.0), np.cos(2 * np.pi * np.linspace(0.0, 5.0))) axes_list[1][1].plot([3,5], [3,5], 'bo:') axes_list[1][1].plot([3,7], [5,4], 'kx') plt.show() df = pd.DataFrame(np.random.randn(4,4)) df.plot(kind='barh') plt.style.use('ggplot') # ggplot style로 그리기 df.plot(kind='barh') plt.style.use('default') # 기본값으로 다시 전환 그리기 # 2. seaborn """ seaborn은 matplotlib을 기반으로 다양한 색 테마, 차트 기능을 추가한 라이브러리 matplotlib에 의존성을 가지고 있음 matplotlib에 없는 그래프(히트맵, 카운트플랏 등)을 가지고 있습니다 """ import seaborn as sns print("Seaborn version : ", sns.__version__) # 버전 확인 dir(sns) # 사용 가능한 메서드 sns.set(style="whitegrid") # 여러 미적인 parameter setting # sns.set_color_codes() current_palette = sns.color_palette() # 사용 가능한 컬러 팔레트 sns.palplot(current_palette) # 컬러 팔레트 시각화 # relational plot 관계형 분포도 그리기 tips = sns.load_dataset("tips") # 예시용 데이터 세트 sns.relplot(x="total_bill", y="tip", hue="smoker", style="smoker", data=tips) df = pd.DataFrame(dict(time=np.arange(500), value=np.random.randn(500).cumsum())) g = sns.relplot(x="time", y="value", kind="line", data=df) g.fig.autofmt_xdate() # cat plot sns.catplot(x="day", y="total_bill", hue="smoker", col="time", aspect=.6, kind="swarm", data=tips) titanic = sns.load_dataset("titanic") g = sns.catplot(x="fare", y="survived", row="class", kind="box", orient="h", height=1.5, aspect=4, data=titanic.query("fare > 0")) g.set(xscale="log"); # pairplot iris = sns.load_dataset("iris") sns.pairplot(iris) g = sns.PairGrid(iris) g.map_diag(sns.kdeplot) g.map_offdiag(sns.kdeplot, n_levels=6); # Heatmap flights = sns.load_dataset("flights") flights = flights.pivot("month", "year", "passengers") plt.figure(figsize=(10, 10)) ax = sns.heatmap(flights, annot=True, fmt="d") # 3. plotnine """ plotnine은 R의 ggplot2에 기반해 그래프를 그려주는 라이브러리입니다 """ # 4. folium """ folium은 지도 데이터(Open Street Map)에 leaflet.js를 이용해 위치정보를 시각화하는 라이브러리입니다 자바스크립트 기반이라 interactive하게 그래프를 그릴 수 있습니다 한국 GeoJSON 데이터는 southkorea-maps에서 확인할 수 있습니다 """ # pip install folium import folium print("folium version is", folium.__version__) m = folium.Map(location=[37.5502, 126.982], zoom_start=12) folium.Marker(location=[37.5502, 126.982], popup="Marker A", icon=folium.Icon(icon='cloud')).add_to(m) folium.Marker(location=[37.5411, 127.0107], popup="한남동", icon=folium.Icon(color='red')).add_to(m) m # 5. plot.ly """ plotly는 Interactive 그래프를 그려주는 라이브러리입니다 Scala, R, Python, Javascript, MATLAB 등에서 사용할 수 있습니다 시각화를 위해 D3.js를 사용하고 있습니다 사용해보면 사용이 쉽고, 세련된 느낌을 받습니다 Online과 offline이 따로 존재합니다(온라인시 api key 필요) plotly cloud라는 유료 모델도 있습니다 """ # pip install plotly import plotly print("plotly version :", plotly.__version__) plotly.offline.iplot({ "data": [{ "x": [1, 2, 3], "y": [4, 2, 5] }], "layout": { "title": "hello world" } }) import plotly.figure_factory as ff import plotly.plotly as py import plotly.graph_objs as go df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv") table = ff.create_table(df) plotly.offline.iplot(table, filename='jupyter-table1') # 6. pyecharts """ Baidu에서 데이터 시각화를 위해 만든 Echarts.js의 파이썬 버전입니다 정말 다양한 그래프들이 내장되어 있어 레포트를 작성할 때 좋습니다! 자바스크립트 기반이기 때문에 Interactive한 그래프를 그려줍니다 """ pip install pyecharts import pyecharts print("pyecharts version : ", pyecharts.__version__)
024442b68a04a0822ff02711b939005b071f6d1b
harimha/PycharmProjects
/Modules_usage/networkx_usage.py
7,233
3.640625
4
""" NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. navigator # Theme : ... # Package : ... # Module : ... # Class : ... # Method : ... # : comments / examples """ import matplotlib.pyplot as plt import networkx as nx help(nx) # Class : nx.Graph() """ Base class for undirected graphs. """ G = nx.Graph() # Class : nx.DiGraph() """ Base class for directed graphs. """ G = nx.DiGraph() # Class : nx.MultiGraph() """ """ G = nx.MultiGraph() # Class : nx.MultiDiGraph() """ """ G = nx.MultiDiGraph() # Method : nx.Graph.add_node() """ Add a single node `node_for_adding` and update node attributes """ G.add_node(1) G.add_node(2) G.add_node("A",role="trader") # Method : nx.Graph.add_nodes_from() G.add_nodes_from([(1,2),(3,4)]) B.add_nodes_from(["A","B","C","D","E"],bipartite=0) B.add_nodes_from([1,2,3,4], bipartite=1) # Method :nx.Graph.add_edge() G.add_edge(1,2) G.add_edge("A", "B", weight=6, relation="family") # Method : nx.Graph.add_edges_from() G.add_edges_from([(3,4),(5,6)]) # Method : nx.Graph.edges() G.edges() # list of all edges G.edges(data=True) # list of all edges with attributes G.edges(data="relation") # list of all edges with attribute "relation" # Method : nx.Graph.nodes() G.nodes() # list of all nodes G.nodes(data=True) # list of all nodes with attributes # Bipartite Graphs B=nx.Graph() B.add_nodes_from(["A","B","C","D","E"],bipartite=0) B.add_nodes_from([1,2,3,4], bipartite=1) B.add_edges_from([("A",1),("B",1),("C",1),("C",3),("D",2),("E",3)]) from networkx.algorithms import bipartite bipartite.is_bipartite(B) # check if B is bipartite B.add_edge("A","B") # break the rule bipartite.is_bipartite(B) B.remove_edge("A","B") # remove edge # check set of nodes is bipartite X = set([1,2,3,4]) bipartite.is_bipartite_node_set(B,X) X = set(["A","B","C","D","E"]) bipartite.is_bipartite_node_set(B,X) bipartite.sets(B) # Projected Graphs B = nx.Graph() B.add_edges_from([("A",1),("B",1),("C",1), ("D",1),("H",1),("B",2), ("C",2),("D",2),("E",2), ("G",2),("E",3),("F",3), ("H",3),("J",3),("E",4), ("I",4),("J",4)]) X = set(["A","B","C","D","E","F","G","H","I","J"]) P = bipartite.projected_graph(B,X) nx.draw(P) X = set([1,2,3,4]) P = bipartite.projected_graph(B,X) nx.draw(P, with_labels= 1) # Weighted Projected Graphs X = set([1,2,3,4]) P = bipartite.weighted_projected_graph(B,X) nx.draw(P, with_labels= 1) # generate network data import pandas as pd import numpy as np import random import statsmodels.api as sm n1 = [] n2 = [] outcome = [] for i in range(100) : (a, b) = np.random.choice([1, 2, 3, 4, 5, 6, 7], 2, replace=False) n1.append(a) n2.append(b) outcome.append(random.choice([-1,0,1])) net_df = pd.DataFrame({"n1":n1, "n2":n2, "outcome":outcome}) net_df.to_string("C:/Users/S/Desktop/edgelist.txt",index=False, header=False) net_df.to_csv("C:/Users/S/Desktop/edgelist.csv",index=False) help(net_df.to_string) # read Edgelist G4 = nx.read_edgelist('C:/Users/S/Desktop/edgelist.txt', data=[('outcome', int)]) G4.edges(data=True) chess = nx.read_edgelist('C:/Users/S/Desktop/edgelist.txt', data=[('outcome', int)], create_using=nx.MultiDiGraph()) chess.edges(data=True) G_df = pd.read_csv("C:/Users/S/Desktop/edgelist.csv", names=['n1', 'n2', 'outcome'], skiprows=1) G_df G5 = nx.from_pandas_edgelist(G_df, 'n1', 'n2', edge_attr='outcome') G5.edges(data=True) G5.degree() # return (node : number of edges(degree)) # edgelist to dataframe df = pd.DataFrame(G5.edges(data=True),columns=["white","black","outcome"]) df # 데이터 핸들링 스킬 df['outcome'] = df['outcome'].map(lambda x: x['outcome']) df won_as_white = df[df['outcome']==1].groupby('white').sum()["outcome"] won_as_black = -df[df['outcome']==-1].groupby('black').sum()["outcome"] win_count = won_as_white.add(won_as_black, fill_value=0) win_count.head() win_count.nlargest(5) # clustering coefficient G = nx.Graph() G.add_edges_from([("A","K"),("A","B"),("A","C"),("B","C"),("B","K"), ("C","E"),("C","F"),("D","E"),("E","F"),("E","H"), ("F","G"),("I","J")]) nx.clustering(G,"F") nx.clustering(G,"A") ################################################################################################################ # Method : print(nx.info(G)) # Method : nx.draw(G) G = nx.Graph() G.add_edges_from([(1,2),(2,3),(3,1)]) nx.draw(G) nx.write_edgelist(G,path="C:/Users/S/Desktop/edgelist.txt") G = nx.read_edgelist(path="C:/Users/S/Desktop/edgelist.txt", create_using=nx.Graph(), nodetype=int) nx.draw(G) G.nodes G.edges print(G.nodes) print(G.edges) nx.draw(G, with_labels=1) # label 표시 z = nx.complete_graph(10) # 모든 노드 연결됨 z.nodes() z.edges() z.order() z.size() nx.draw(z, with_labels=1) # label 표시 G = nx.gnp_random_graph(20,0.5) # 50% 확률로 randomly edges G.nodes() G.edges() G.order() G.size() nx.draw(G, with_labels=1) # label 표시 ## modellin road network of india import networkx as nx import matplotlib.pyplot as plt import random G = nx.Graph() # undirected graph # G = nx.DiGraph() # directed graph city_set = ["Delhi", "Bangalore", "Hyderabad", "Ahmedabad", "Chennai", "Kolkata", "Surat", "Pune", "Jaipur"] for each in city_set: G.add_node(each) nx.draw(G,with_labels=1) costs = [] values=100 while (values<=2000): costs.append(values) values+=100 print(costs) while(G.number_of_edges()<16): c1=random.choice(list(G.nodes)) c2=random.choice(list(G.nodes)) if c1!=c2 and G.has_edge(c1,c2) == 0 : w=random.choice(costs) G.add_edge(c1,c2,weight=w) print(nx.info(G)) G.edges(data=True) # change layout # pos = nx.spectral_layout(G) # pos = nx.spring_layout(G) pos = nx.circular_layout(G) nx.draw(G, with_labels=1,pos=pos) # draw edges labels nx.draw(G, with_labels=1,pos=pos) nx.draw_networkx_edge_labels(G,pos=pos) print(nx.is_connected(G)) # there exist path between every two pair of nodes for u in G.nodes(): for v in G.nodes(): print(u,v,nx.has_path(G,u,v)) nx.has_path() # shortest path """Returns the shortest weighted path from source to target in G. Uses Dijkstra's Method to compute the shortest weighted path between two nodes in a graph.""" u="Delhi" v="Kolkata" print(nx.dijkstra_path(G,u,v)) print(nx.dijkstra_path_length(G,u,v)) import matplotlib.pyplot as plt import networkx as nx G = nx.cycle_graph(24) pos = nx.spring_layout(G, iterations=200) nx.draw(G, pos, node_color=range(24), node_size=1000, cmap=plt.cm.Blues) plt.show() # Author: Aric Hagberg (hagberg@lanl.gov) import matplotlib.pyplot as plt import networkx as nx G = nx.house_graph() # explicitly set positions pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)} nx.draw_networkx_nodes(G, pos, node_size=2000, nodelist=[4]) nx.draw_networkx_nodes(G, pos, node_size=3000, nodelist=[0, 1, 2, 3], node_color='b') nx.draw_networkx_edges(G, pos, alpha=0.5, width=6) plt.axis('off') plt.show()
dc91208aabddc8e4a8e41ef4be9323b4c5ceae7d
box-of-voodoo/python_old
/tkinter_/mesbox.py
444
3.578125
4
from tkinter import * import tkinter.messagebox root=Tk() messagebox.showinfo('asdas','asdasdasdasdasd') answer = tkinter.messagebox.askquestion('question','XX?') print (answer) tkinter.messagebox.showwarning('x','X') tkinter.messagebox.showerror ('y','Y') ans=tkinter.messagebox.askokcancel('Y','Y') print(ans) answ=tkinter.messagebox.askyesno('G','g') print(answ) an=tkinter.messagebox.askretrycancel('g','H') print(an) root.mainloop()
43b077ab49a89e365f1af7fb4717303c7c94f9cc
box-of-voodoo/python_old
/logo/kvet.py
733
3.71875
4
from turtle import* Screen() t=Turtle() bgcolor('gray') x=0 t.up() t.bk(0) t.down() t.pen(speed=0,shown=False) t.color('red') colo=['red','orange','yellow'] col=['green','blue','cyan'] t.color('green') t.right(90) t.pen(pensize=5) t.fd(360) t.bk(360) t.pen(pensize=1) for i in range(60): x+=3 for z in range(3): t.color(col[z]) t.circle(x,60) t.up() t.circle(x,240) t.down() t.circle(x,60) t.right(120) t.right(60) t.right(30) for i in range(60): x-=3 for z in range(3): t.color(colo[z]) t.circle(x,60) t.up() t.circle(x,240) t.down() t.circle(x,60) t.right(120) t.right(60) t.st() t.right(240)
a3d7635634dd825bbe878c121ce0cd37f2f4c6c4
tirtow/swe-study
/test-2/python/unpacking.py
787
3.9375
4
# unpacking def f(x, y, z): return [x, y, z] # * - requires iterables t = (3, 4) f(2, *t) # [2, 3, 4] f(*t, 2) # [3, 4, 2] - can do unpacking before position # f(x=2, *t) # * has higher precedence than pass by name, gets multiple # values for x # ------------------------------------------------------------------------ # ** requires dict (or something like it) # keys must have same names as function parameters d = {"z": 4, "y": 3, "x": 2} f(**d) # [2, 3, 4] # f(x=2, **d) # gets conflicting values for x e = {"z": 4, "y": 3} f(2, **e) # because no x in dict, can consume first argument by position # f(**d, 2) # cannot unpack dictionary before position # f(**d, *t, y=2) # cannot unpack dictionary before iterable unpacking
415c453aefdbc94499dd3c6811886d7c6b48a6f1
Ushaakkam/python
/Input.py
190
3.953125
4
x=int(input("enter the value x value:")) y=int(input("enter the value y value:")) z=int(input("enter the value z value:")) print(max(x,y,z)) input("please press enter to exit")
604a599edc09ff277520aadd1bb79fb8157272ee
pallu182/practise_python
/fibonacci_sup.py
250
4.125
4
#!/usr/bin/python num = int(raw_input("Enter the number of fibonacci numbers to generate")) if num == 1: print 1 elif num == 2: print 1,"\n", 1 else: print 1 print 1 a = b = 1 for i in range(2,num): c = a + b a = b b = c print c
021a5f8669dc4f4c530e585af0b536260e1bc76e
DSoutter/PDA_Dynamic_and_Static_Testing
/part_2_code/tests/card_game_tests.py
754
3.765625
4
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.card1 = Card("Spades", 1) self.card2 = Card("Hearts", 2) self.cards_total = [self.card1, self.card2] def test_highest_card(self): self.assertEqual(True,CardGame.check_for_ace(self, self.card1)) def test_highest_card_False(self): self.assertEqual(False,CardGame.check_for_ace(self, self.card2)) def test_highest_card1(self): self.assertEqual(self.card2, CardGame.highest_card(self, self.card1, self.card2)) def test_cards_total(self): self.assertEqual("You have a total of 3", CardGame.cards_total(self, self.cards_total))
9893c2f8cc419202264698832fb95648a9b8ae41
wpzy/csdn
/del.py
218
3.625
4
#coding:utf-8 import sys import os import re for line in sys.stdin: if len(line)<=0: continue line=line.strip() line=line.decode('utf-8') tmp=line.strip().split(' ') if len(tmp)==2: print line.encode('utf-8')
ab264a97323768b302003da89876e6ba04dd2c29
enterstry/flow-python
/v2/functions.py
548
3.5
4
from typing import Callable def int_to_str(data: int, output: Callable[[str, str], None]): # hier muss nun eine Typenkonvertierung stattfinden, # da der Eingang vom Typ Integer und der Ausgang vom Typ String ist. print("int_to_str", type(data)) output('out', str(data)) def str_to_int(data: str, output: Callable[[str, int], None]): # hier muss nun eine Typenkonvertierung stattfinden, # da der Eingang vom Typ String und der Ausgang vom Typ Integer ist. print("str_to_int", type(data)) output('out', int(data))
ca5d8a47171f6b1fbc2d53f6648da8f0a6b9e900
km1414/Courses
/Computer-Science-50-Harward-University-edX/pset6/vigenere.py
1,324
4.28125
4
import sys import cs50 def main(): # checking whether number of arguments is correct if len(sys.argv) != 2: print("Wrong number of arguments!") exit(1) # extracts integer from input key = sys.argv[1] if not key.isalpha(): print("Wrong key!") exit(2) # text input from user text = cs50.get_string("plaintext: ") print("ciphertext: ", end = "") # cursor for key cursor = 0 # iterating over all characters in string for letter in text: # if character is alphabetical: if letter.isalpha(): # gets number for encryption from key number = ord(key[cursor % len(key)].upper()) - ord('A') cursor += 1 # if character is uppercase: if letter.isupper(): print(chr((ord(letter) - ord('A') + number) % 26 + ord('A')), end = "") # if character is lowercase: else: print(chr((ord(letter) - ord('a') + number) % 26 + ord('a')), end = "") # if character is non-alphabetical: else: print(letter, end = "") # new line print() # great success exit(0) # executes function if __name__ == "__main__": main()
f9a991a8108218ae3b746c1e29a044dcbe074761
sergchernata/FooBar
/03c.py
3,047
3.515625
4
from itertools import repeat, count, islice from collections import Counter from functools import reduce from math import sqrt, factorial import time def factors(n): step = 2 if n%2 else 1 return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(sqrt(n))+1, step) if n % i == 0))) def combinations(subset): subset.pop(0) count = 0 index = 1 for a in subset: for b in subset[index:]: if not a%b: count += 1 index += 1 return count def are_divisors(nums): nums = [n for n in nums] nums = nums[::-1] index = 1 for a in nums: for b in nums[index:]: if a%b: return False index += 1 return True # science, bitch! def yeah_science(v): return factorial(v) // (factorial(3) * factorial(v-3)) def answer(numbers): triples = 0 counts = Counter(numbers) numbers = numbers[::-1] # if we have only one unique number # or if all numbers are actual divisors already # then add their counts and use the formula if len(counts) == 1 or are_divisors(counts): v = sum(counts.values()) return yeah_science(v) for n in numbers: all_factors = factors(n) subset = [a for a in all_factors for _ in range(counts[a])] subset = sorted(subset, reverse = True) if len(subset) > 2: uniques = set(subset) v = len(subset) if v > 2 and (len(uniques) == 1 or are_divisors(uniques)): triples += yeah_science(v) counts[n] = 0 else: triples += combinations(subset) counts[n] -= 1 if counts[n] == 0: del counts[n] v = sum(counts.values()) if v > 2 and are_divisors(counts): return triples + yeah_science(v) numbers = [item for item in numbers if item != n] return triples #-*-*-*-*-*-*-*-*-*-*-*-*-# # benchmarking #-*-*-*-*-*-*-*-*-*-*-*-*-# num_list = [1,1,2,2,3,3,4,4,5,5,6,6] #num_list = list(range(1,9999)) # num_list = [] # for _ in range(1000): # num_list.append(1) # num_list.append(3) # num_list.append(7) start = time.time() print(answer(num_list)) end = time.time() print((end - start)) #-*-*-*-*-*-*-*-*-*-*-*-*-# # test cases #-*-*-*-*-*-*-*-*-*-*-*-*-# print(answer([1,1,1]) == 1) print(answer([1,1,1,1]) == 4) print(answer([1,2,3,4,5,6]) == 3) print(answer([1,2,3,4,5,6,6]) == 8) print(answer([1,2,3,4,5,6,12]) == 10) s = answer([1,1,1,1,1,1,1,3,3,7,7]) a = answer([1,1,1,1,1,1,1,3,3]) b = answer([1,1,1,1,1,1,1,7,7]) print(s, a, b, ' - ', s == a + b) s = answer([1,1,1,1,1,1,1,3,3,3,3,3,3,12,30,90]) a = answer([1,1,1,1,1,1,1,3,3,3,3,3,3,12]) b = answer([1,1,1,1,1,1,1,3,3,3,3,3,3,30,90]) print(s, a, b, ' - ', s == a + b) # the one i can't quite wrap my mind around # doesn't add up as it should s = answer([1,1,2,2,3,3,4,4,5,5,6,6]) a = answer([1,1,2,2,3,3,6,6]) b = answer([1,1,5,5]) c = answer([1,1,2,2,4,4]) d = answer([1,1,3,3]) e = answer([1,1,2,2]) print(s, a, b, c, d, e, ' - ', a + b + c + d + e) s = answer([1,2,3,4,5,6]) a = answer([1,2,3,6]) b = answer([1,2,4]) print(s, a, b, ' - ', s == a + b) s = answer([1,1,1,1,1,1,1,3,7]) a = answer([1,1,1,1,1,1,1,3]) b = answer([1,1,1,1,1,1,1,7]) print(s, a, b, ' - ', s == a + b)
2bbdcb5f16abe238e8dc279da2ff14e1e8b2e1bd
sheilapaiva/LabProg1
/Unidade5/Karel_o_Robo/Karel_o_Robo.py
581
3.71875
4
#coding: utf-8 #Aluna: Sheila Maria Mendes Paiva #Matrícula: 118210186 #Unidade: 5 Questão: Karel o Robô x, y = 0, 0 while True: coordenada = raw_input().split() direcao = coordenada[0] unidade_movimento = int(coordenada[1]) if unidade_movimento == 0: print "Fim de jogo" break else: if direcao == "E": x -= unidade_movimento elif direcao == "D": x += unidade_movimento elif direcao == "B": y -= unidade_movimento elif direcao == "C": y += unidade_movimento if abs(x) > 0 and abs(y) == abs(x) * 2: print "Parabéns, conquista do portal (%d, %d)" % (x, y) break
bbf7527869c124395fe806004332bf1a01f6f246
sheilapaiva/LabProg1
/Unidade8/conta_palavras/conta_palavras.py
422
3.921875
4
#coding: utf-8 #UFCG - Ciência da Computação #Programação I e laboratório de Programação I #Aluna: Sheila Maria Mendes Paiva #Unidade: 8 Questão: Conta Palavras def conta_palavras(k, palavras): lista_palavras = palavras.split(":") cont = 0 for i in range(len(lista_palavras)): if len(lista_palavras[i]) >= k: cont += 1 print lista_palavras return cont assert conta_palavras(5, "zero:um:dois:tres:quatro:cinco") == 2
38ce7c743cacbb6a8063c172e403a46ce0ee8b1b
sheilapaiva/LabProg1
/Unidade7/desloca_elemento/desloca_elemento.py
491
3.90625
4
#coding: utf-8 #UFCG - Ciência da Computação #Programação I e laboratório de Programação I #Aluna: Sheila Maria Mendes Paiva #Unidade: 7 Questão: Desloca Elemento def desloca(lista, origem, destino): deslocar = True elemento_origem = lista[origem] while deslocar == True: deslocar = False for i in range(len(lista) -1): if lista[i] == elemento_origem and lista[destino] != elemento_origem: lista[i], lista[i + 1] = lista[i + 1], lista[i] deslocar = True break return None
d8cf4ed0da53322286aebba455da13faca4499ce
sheilapaiva/LabProg1
/Unidade4/serie_impares_1/serie_impares_1.py
205
3.65625
4
# coding: utf-8 # Aluna: Sheila Maria Mendes Paiva # Matrícula: 118210186 # Unidade 4 Questão: Série (ímpares 1) for i in range(1,103,2): if (i % 3 == 0): print "*" elif (i % 5 == 0): print "*" else: print i
5885ab9f922b74f75ae0ef3af2f1f0d00d2cd087
sheilapaiva/LabProg1
/Unidade8/agenda_ordenada/agenda_ordenada.py
621
4.125
4
#coding: utf-8 #UFCG - Ciência da Computação #Programação I e laboratório de Programação I #Aluna: Sheila Maria Mendes Paiva #Unidade: 8 Questão: Agenda Ordenada def ordenar(lista): ta_ordenado = True while ta_ordenado == True: ta_ordenado = False for i in range(len(lista) -1): if lista[i] > lista[i + 1]: lista[i], lista[i + 1] = lista[i + 1], lista[i] ta_ordenado = True break return lista agenda = [] while True: nome = raw_input() if nome == "####": break agenda.append(nome) ordenar(agenda) for i in agenda: if i == nome: print "* %s" % nome else: print i print "----"
d633716cdf39bab10a5a25c46415856871747153
sheilapaiva/LabProg1
/Unidade4/grep/grep.py
373
3.796875
4
# coding: utf-8 # Aluna: Sheila Maria Mendes Paiva # Matrícula: 118210186 # Unidade 4 Questão: Grep palavra = raw_input() numero_frases = int(raw_input()) for i in range(numero_frases): frase = raw_input() lista_palavra_frase = frase.split(" ") for j in range(len(lista_palavra_frase)): palavra_frase = lista_palavra_frase[j] if palavra_frase.find(palavra) != -1: print frase
11c8853faad4f8916a73472af3844e081ad35703
sheilapaiva/LabProg1
/Unidade2/caixa_ceramica/caixa_ceramica.py
596
3.8125
4
#coding: utf-8 capacidade = float(raw_input("Capacidade de revestimento? ")) print "" print "== Dados do vão a revestir ==" comprimento = float(raw_input("Comprimento? ")) largura = float(raw_input("Largura? ")) altura = float(raw_input("Altura? ")) lateral1 = float(2 * (comprimento * altura)) lateral2 = float(2 * (largura * altura)) base = float(comprimento * largura) area_total = float(lateral1 + lateral2 + base) num_caixas = int(area_total / capacidade) print "" print "== Resultados ==" print "Área total a revestir: %.1f m2" % area_total print "Número de caixas: %d" % num_caixas
a6436b94643cbdb160fcd14bbb1bf871e5fb1f96
sheilapaiva/LabProg1
/Unidade9/soma_moldura_k/soma_moldura_k.py
440
3.921875
4
#coding: utf-8 #UFCG - Ciência da Computação #Programação I e laboratório de Programação I #Aluna: Sheila Maria Mendes Paiva #Unidade: 9 Questão: Soma Moldura k def soma_moldura(m, k): soma = 0 for i in range(k, len(m) - k): for j in range(k, len(m[i]) - k): if i == k: soma += m[i][j] elif i == len(m) - 1 - k: soma += m[i][j] elif j == k: soma += m[i][j] elif j == len(m) - 1 - k: soma += m[i][j] return soma
d9679db27c23d1056abbc94e653c19cc5179c0b6
sheilapaiva/LabProg1
/Unidade4/arvore_natal/arvore_natal.py
233
3.78125
4
#coding: utf-8 altura = int(raw_input()) numero_o = 1 numero_espacos = 0 for arvore in range(altura): print " " * (numero_espacos + (altura -1)) + numero_o * "o" numero_o +=2 numero_espacos -= 1 print (altura - 1) * " " + "o"
776d471213c0cb7b7c549d3e7312dfab6f1746cf
sheilapaiva/LabProg1
/Unidade6/caixa_alta/caixa_alta.py
487
3.890625
4
#coding: utf-8 #Aluna: Sheila Maria Mendes Paiva #Matrícula: 118210186 #Unidade: 6 Questão: Caixa Alta def caixa_alta(frase): frase_modificada = "" frase = " " + frase + " " for i in range(1,len(frase) - 1): if frase[i - 1] == " " and frase[i + 1] == " ": frase_modificada += frase[i].lower() elif frase[i - 1] == " " and frase[i + 1] != " ": frase_modificada += frase[i].upper() elif frase[i - 1] != " " or frase[i + 1] == " ": frase_modificada += frase[i] return frase_modificada
2862ae6390595dbd6265849c0f96341077afa02a
didi1215/leetcode
/leetcode/leetcode/editor/cn2/[剑指 Offer 59 - II]队列的最大值.py
1,605
3.84375
4
# 请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都 # 是O(1)。 # # 若队列为空,pop_front 和 max_value 需要返回 -1 # # 示例 1: # # 输入: # ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"] # [[],[1],[2],[],[],[]] # 输出: [null,null,null,2,1,2] # # # 示例 2: # # 输入: # ["MaxQueue","pop_front","max_value"] # [[],[],[]] # 输出: [null,-1,-1] # # # # # 限制: # # # 1 <= push_back,pop_front,max_value的总操作数 <= 10000 # 1 <= value <= 10^5 # # Related Topics 设计 队列 单调队列 # 👍 267 👎 0 # leetcode submit region begin(Prohibit modification and deletion) import queue class MaxQueue: def __init__(self): self.deque = queue.deque() self.queue = queue.Queue() def max_value(self) -> int: return self.deque[0] if self.deque else -1 def push_back(self, value: int) -> None: self.queue.put(value) while self.deque and self.deque[-1] < value: self.deque.pop() self.deque.append(value) def pop_front(self) -> int: if self.queue.empty(): return -1 val = self.queue.get() if val == self.deque[0]: self.deque.popleft() return val # Your MaxQueue object will be instantiated and called as such: # obj = MaxQueue() # param_1 = obj.max_value() # obj.push_back(value) # param_3 = obj.pop_front() # leetcode submit region end(Prohibit modification and deletion)
7a463545ad20fd7445dcc0846284a8679e749459
olgatarr/FaCLTarakanova
/hw3/hw3.py
349
3.734375
4
print('Введите три числа:') a = int(input('a = ')) b = int(input('b = ')) c = int(input('c = ')) if a*b == c: print(a, '*', b, ' = ', c) else: print(a, '*', b, ' != ', c) print(a, '*', b, ' = ', a*b, '\n') if a/b == c: print(a, '/', b, ' = ', c) else: print(a, '/', b, ' != ', c) print(a, '/', b, ' = ', a/b)
4b50d1346acd52620fff52b7af998043c69701a6
luispabreu/p3ws
/16_read_exn/code.py
594
3.765625
4
def f(x): if (x == 7): raise ValueError("f(7) is illegal") return (x+3)*2 def g(x,y): if (not isinstance(x,int)): raise TypeError("x must be an int in g(x,y)") return x + f(y) def h(x,y): try: return g(x,y-3) except ValueError as e: print(e) return 42 pass def main(): for (i,j) in [(1,2), ('hello', 4), (3,10), (4,3)]: try: print("i= " + str(i) + " j = " + str(j)) print(str(h(i,j))) except TypeError as e: print(e) pass pass pass
1f4b5b3a2db6bec3dcb91521b09c07fb8956ebb7
luispabreu/p3ws
/01_read_fcn/code.py
251
3.8125
4
def another_function(a): b = a a += 2 print('a is ' + str(a)) print('b is ' + str(b)) print('a + b is ' + str(a + b)) return b def main(): x = 5 y = another_function(x) print('y is ' + str(y)) return 0 main()
bf92dbc9c73edbc655c53b42c9e14ed9871f3f68
luispabreu/p3ws
/07_list_max/listmax.py
1,059
3.546875
4
def listMax(list): if list == None: return None if list == []: return None max = list[0] for i in list: if max < i: max = i pass pass return max def doTest(list): print('listMax(',end='') if list == None: print('None) is ',end='') pass else: n = len(list) print('[',end='') for i in range(0, n): print('{}'.format(list[i]),end='') if i < n - 1: print(', ',end='') pass pass print(']) is ',end='') pass max = listMax(list) if max == None: print('None') pass else: print('{}'.format(max)) pass pass def main(): list1 = [77, 33, 19, 99, 42, 6, 27, 4] list2 = [-3, -42, -99, -1000, -999, -88, -77] list3 = [425, 59, -3, 77, 0, 36] doTest(list1) doTest(list2) doTest(list3) doTest(None) doTest([]) return 0 if __name__ == '__main__': main() pass
50ec2658e785df4348467b8e5b48a352c4ce85c3
anlsh/cs4803
/vocal-mimicry/discriminators/identity_dtor.py
4,203
3.65625
4
""" Architecture ==================================================================== The basic idea of this discriminator is to, given two voice samples, determine whether they belong to the same person. I opted for a Siamese-network approach to the problem, as described in (1): which is a paper on exactly this topic. The architecture described in this paper uses a neural-network dimensionality reduction on both inputs before passing the reductions to some similarity function. After thinking about what makes a good dimensionality reduction for voices such that they can be compared, we came to the conclusion that it makes sense to use the style embeddings themselves as the dimensionality-reduced data The forward() function provides the probability that the two voices are the same. I support different ways to calculate this probability, being 1. Via norm of embedding difference 2. Via cosine similarity 3. Via learning the function via a (fully connected) neural network References ---------------------------------- (1) Speaker Verification Using CNNs https://arxiv.org/pdf/1803.05427.pdf """ from __future__ import division import torch from torch import nn import math from .common import fc_from_arch def get_identity_discriminator(style_size, identity_mode): """ Return a network which takes two voice samples and returns the probability that they are the same person See documentation of forward() below for information on input size """ return Identity_Discriminator( style_size, mode=identity_mode, ) class Identity_Discriminator(nn.Module): modes = ['norm', 'cos', 'nn'] def __init__( self, style_size, mode='norm', fc_hidden_arch=None, cossim_degree=None, ): """ :style_size: An integer, the size of the style embedding vector :distance_mode: One of 'norm', 'nn', 'cos' :fc_hidden_arch: The hidden layers to be used in the neural network if the difference function is to be learned. If distance_mode is not 'nn' and this parameter is not None, or if distance mode is 'nn' and this parameter is None, then a runtime error will be thrown """ super(Identity_Discriminator, self).__init__() self.style_size = style_size self.fc_hidden_arch = fc_hidden_arch self.cossim_degree = cossim_degree self.mode = mode if not (self.mode in self.modes): raise RuntimeError("Unrecognized mode: " + str(self.mode)) if (self.mode == 'nn') and (fc_hidden_arch is None): raise RuntimeError("In NeuralNet mode but no arch provided") elif (self.mode != 'nn') and (fc_hidden_arch is not None): raise RuntimeError("Not in NeuralNet mode but arch provided") if (self.mode == 'cos') and (cossim_degree is None): raise RuntimeError("In Cos-Sim mode but no exponent provided") elif (self.mode != 'cos') and (cossim_degree is not None): raise RuntimeError("Not in Cos-Sim mode but exponent provided") if self.mode != 'nn': self.network = None else: self.network = fc_from_arch(2 * style_size, 1, self.fc_hidden_arch) def forward(self, x, lengths): """ :x: should be a (N x 2 x S) tensor Returns a vector of shape (N,), with each entry being the probability that i1[n] and i2[n] were stylevectors for the same person """ assert(len(x.size()) == 3) assert(x.size(1) == 2) i1 = x[:, 0, :] i2 = x[:, 1, :] if self.mode == 'norm': return 1 - ( (2 / math.pi) * torch.atan(torch.norm(i1 - i2, p=2, dim=1))) elif self.mode == 'cos': return ((nn.functional.cosine_similarity(i1, i2, dim=1) + 1) / 2)**self.cossim_degree elif self.mode == 'nn': return torch.sigmoid( self.network.forward(torch.cat((i1, i2), dim=1))) if __name__ == "__main__": raise RuntimeError("Why in the world you running this as main?")
4e1d3a7bbecd6871b55f8cc775fb16be9305a6ce
markgalup/topcoder
/Solved/CardCount (SRM 161 Div. 2 250pts).py
712
3.5
4
class CardCount(object): def dealHands(self, numPlayers, deck): revdeck = list(deck) revdeck.reverse() hands = ["" for x in range(numPlayers)] while len(revdeck) >= numPlayers: for x in range(numPlayers): hands[x] += revdeck.pop() return hands print CardCount().dealHands(6, '012345012345012345') # R: ("000", "111", "222", "333", "444", "555") print CardCount().dealHands(4, '111122223333') # R: ("123", "123", "123", "123") print CardCount().dealHands(1, '012345012345012345') # R: ("012345012345012345") print CardCount().dealHands(6, '01234') # R: ("", "", "", "", "", "") print CardCount().dealHands(2, '') # R: ("", "")
b501db930953f14e140e86d73914ce30f1674de0
markgalup/topcoder
/Unsolved/SRM 649 Div. 2 250 pts.py
316
3.75
4
class DecipherabilityEasy(object): def check(self, s, t): #s += " " for x in range(len(s)): print s[:x] + s[x+1:] if s[:x] + s[x+1:] == t: return "Possible" return "Impossible" print DecipherabilityEasy().check("sunmke", "snuke" )
67a879e2bbe86872838034ddd0ff25f941115479
sathishkumar01/Python
/Pattern/number/5.Floyds Triangle.py
133
3.703125
4
n=int(input('Enter n:')) a=0 for i in range(1,n): for j in range(1,i): a=a+1 print(a,end=" ") print()
b77a792dd71b63c3a8e3f0fbb5bcdedf9851380f
sathishkumar01/Python
/Pattern/Alphabets/T.py
174
4
4
for i in range(5): for j in range(7): if ((j==3 ) or (i==0)): print("*",end="") else: print(end=" ") print()
92026682a04db9c3a0559d0e29f02d514193fc29
sathishkumar01/Python
/Pattern/Alphabets/S.py
277
3.9375
4
for i in range(10): for j in range(8): if ((j==0 ) and i>0 and i<3) or ((i==0 or i==3) and (j>0 and j<6)) or ((j==7) and i>3 and i<=5) or ((i==6) and j>0 and j<6): print("*",end="") else: print(end=" ") print()
e9015a5e5384f0c69030c92744d9ac8b911c7751
sathishkumar01/Python
/Pattern/Alphabets/G.py
303
3.921875
4
for i in range(5): for j in range(6): if ((j==0 ) and i!=0 and i!=4) or ((i==0 ) and j>0 and j<5) or ((i==4) and j>0 ) or ((j==5) and i>=2 and i<5) or ((j==4) and i==2)or ((j==3) and i==2) : print("*",end="") else: print(end=" ") print()
bb67b5a4f7a6878544f445bf871eeeafb6f32dcc
sathishkumar01/Python
/19.Fibonacci.py
131
3.859375
4
n=int(input("Enter Number:")) a=1 b=1 print(a) print(b) for x in range(0,n+1): c=a+b; a=b; b=c; print(c)
b5b4f440a749ee18200f2479df34699c6928e1bc
sathishkumar01/Python
/Pattern/Alphabets/W.py
384
3.546875
4
for i in range(5): for j in range(12): if ((j==0) and i==0) or ((j==1) and i==1) or ((j==2) and i==2) or ((j==3) and i==3) or ((j==4) and i==2) or ((j==5) and i==1) or ((j==6) and i==2) or ((j==7) and i==3) or ((j==8) and i==2) or ((j==9) and i==1) or ((j==10) and i==0): print("*",end="") else: print(end=" ") print()
b87e9b3fa5910c2f521321d84830411b624e0c39
SDSS-Computing-Studies/005a-tuples-vs-lists-AlexFoxall
/task2.py
569
4.15625
4
#!python3 """ Create a variable that contains an empy list. Ask a user to enter 5 words. Add the words into the list. Print the list inputs: string string string string string outputs: string example: Enter a word: apple Enter a word: worm Enter a word: dollar Enter a word: shingle Enter a word: virus ['apple', 'worm', 'dollar', 'shingle', 'virus'] """ t1 = input("Enter a word").strip() t2 = input("Enter a word").strip() t3 = input("Enter a word").strip() t4 = input("Enter a word").strip() t5 = input("Enter a word").strip() x = [t1, t2, t3, t4, t5] print(x)
d59fdd889061fdb58065c8d3d2aaf4509dbe76ca
ahmetcanbasaran/MU-CSE-Projects
/Extra/1.Intern(2017)_Middle_East_Technical_University_WINS_Lab/Works/OOP-Python/oop2.py
755
4
4
class Employee: raiseAmount = 1.04 numberOfEmployees = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.numberOfEmployees += 1 def fullName(self): return '{} {}'.format(self.first, self.last) def applyIncrease(self): self.pay = int(self.pay * 1.04) print(Employee.numberOfEmployees) emp_1 = Employee('Ahmet', 'Alaca' , 50000) print(emp_1.fullName()) print(Employee.numberOfEmployees) emp_2 = Employee('Mehmet', 'Karaca', 60000) print(emp_2.fullName()) print(Employee.numberOfEmployees) print(emp_1.fullName()) print('Before increasing: ' + str(emp_1.pay)) emp_1.applyIncrease() print('After increasing: ' + str(emp_1.pay))
f9ca15657c71d4d67c4e02f82cc972e254526c62
ahmetcanbasaran/MU-CSE-Projects
/7.Semester/CSE4088 - Inroduction to Machine Learning/Homeworks/2/main.py
12,379
3.8125
4
############################################# # # # CSE4088 - Intro. to Machine Learning # # Homework #2 # # Oguzhan BOLUKBAS - 150114022 # # # ############################################# ############################################# # # # Generalization Error # # # ############################################# import math # Question #2 e = 0.05 M = 10 print("\nQuestion #2 - For the case M = 10, the result is: ", math.ceil(-1 / (2 * e**2) * math.log(0.03 / (2 * M))), " and the least number of examples N is [c]1500") # Question #3 e = 0.05 M = 100 print("\nQuestion #3 - For the case M = 100, the result is: ", math.ceil(-1 / (2 * e**2) * math.log(0.03 / (2 * M))), " and the least number of examples N is [d]2000") ############################################# # # # The Perceptron Learning Algorithm # # # ############################################# import numpy as np import matplotlib.pyplot as plt # To generate uniformly points in X = [-1,1]x[-1,1] def random(n): return np.random.uniform(-1, 1, n) # Scalar multiplication vectors and to take sign of result def out_perceptron(X, weights): total = np.dot(X, weights) return np.sign(total) # To generate N datapoints and take transpose of the generated matrix def generate_datapoints(N): return (np.array([np.ones(N), random(N), random(N)])).T # Repeat the experiment for 1000 times ITERATION = 1000 """ def PLA(N, Question_10): iterations_total = 0 ratio_misclassification_total = 0 global iterations_avg global ratio_misclassification_avg for i in range(ITERATION): # To choose two random points (uniformly in X = [-1,1]x[-1,1]) A = np.random.uniform(-1, 1, 2) B = np.random.uniform(-1, 1, 2) # To find variables used in line formula: y = m*x + b m = (B[1] - A[1]) / (B[0] - A[0]) # Slope of the line b = A[1] - m * A[0] # Bias of the line # To generate a weight vector with -1 bias value weight_func = np.array([b, m, -1]) # To generate N data points X = generate_datapoints(N) # To calculate result of mult. of input and weight of nodes out_func = out_perceptron(X, weight_func) # It is added for Question 10 if (Question_10 == True): weight_pla = weight_lin_reg else: weight_pla = np.zeros(3) # To initialize weight vector as zeros counter = 0 # To count number of iterations in PLA while True: # To return output value of PLA's hypothesis out_pla = out_perceptron(X, weight_pla) # It compares classification with outputs of f and h and returns boolean equivalent = out_func != out_pla # Returns indices array where wrong classification by hypothesis h misclassification = np.where(equivalent)[0] if misclassification.size == 0: break # To pick a random misclassified point from "equivalent" indices array random_choice = np.random.choice(misclassification) # To update weight vector as real output calculated with f and X: weight_pla += out_func[random_choice] * X[random_choice].T counter += 1 iterations_total += counter # To generate data "outside" of training data to calculate error N_outside = 1000 # To generate new data array with size 1000x3 X = generate_datapoints(N_outside) # To calculate output of perceptron with new dataset X output_f = out_perceptron(X, weight_func) output_g = out_perceptron(X, weight_pla) # To calculate misclassification ratio ratio_misclassification = ((output_f != output_g).sum()) / N_outside ratio_misclassification_total += ratio_misclassification iterations_avg = iterations_total / ITERATION ratio_misclassification_avg = ratio_misclassification_total / ITERATION N = 10 PLA(N, False) print("\nQuestion #4 - It takes ", iterations_avg, " iterations for N = ", N, " and ", "the closest value for iterations taken on average is [b]15") print("\nQuestion #5 - P(f(x)!=h(x)) for N = ", N, " is ", "%.2f" % ratio_misclassification_avg, " and ", "the closest value for disagreement is [c]0.1") N = 100 PLA(N, False) print("\nQuestion #6 - It takes ", iterations_avg, " iterations for N = ", N, " and ", "the closest value for iterations taken on average is [b]100") print("\nQuestion #7 - P(f(x)!=h(x)) for N = ", N, " is ", "%.2f" % ratio_misclassification_avg, " and ", "the closest value for disagreement is [c]0.01") ############################################# # # # Linear Regression # # # ############################################# # NOTE: Same functions used above does not explained again # Question 8: N_sample = 100 E_in_total = 0 for linear_regression in range(ITERATION): A = random(2) B = random(2) m = (B[1] - A[1]) / (B[0] - A[0]) b = A[1] - m * A[0] weight_func = np.array([b, m, -1]) X = generate_datapoints(N_sample) output_func = out_perceptron(X, weight_func) # To take pseudo-inverse of X X_pseudo_inverse = np.dot(np.linalg.inv(np.dot(X.T, X)), X.T) # To calculate weight weight_lin_reg = np.dot(X_pseudo_inverse, output_func) # To calculate output of the perceptron output_lin_reg = out_perceptron(X, weight_lin_reg) # To calculate E_in E_in = sum(output_lin_reg != output_func) / N_sample E_in_total += E_in E_in_avg = E_in_total / ITERATION # Average of E_in over 1000 iterations print("\nQuestion #8 - Average of E_in over ", ITERATION, " iterations: ", "%.2f" % E_in_avg, " and the closest value to the average E_in is [c]0.01") # Question 9: N_fresh = 1000 E_out_total = 0 for i in range(ITERATION): # To generate fresh datapoints X_test = generate_datapoints(N_fresh) # To calculate output of the function output_func_test = out_perceptron(X_test, weight_func) # To calculate output of the hypothesis output_lin_reg_test = out_perceptron(X_test, weight_lin_reg) E_out = sum(output_lin_reg_test != output_func_test) / N_fresh E_out_total += E_out E_out_avg = E_out_total / ITERATION # Average of E_out over 1000 iterations print("\nQuestion #9 - Average of E_out over ", ITERATION, " iterations: ", "%.2f" % E_out_avg, "and the closest value to the average E_out is [c]0.01") # Question 10: N = 10 PLA(N, True) print("\nQuestion #10 - It takes ", iterations_avg, " iterations for N = ", N, " and ", "the closest value for iterations taken on average is [a]1") """ ############################################# # # # Nonlinear Transformation # # # ############################################# # Question 11: import matplotlib.pyplot as plt N = 1000 E_in_total = 0 for run in range(ITERATION): # To generate a dataset X = generate_datapoints(N) # NOTE: [:,1] returns second column of the matrix output_func = np.sign(X[:,1] * X[:,1] + X[:,2] * X[:,2] - 0.6) # To pick a subset (10% of N) subset = list(range(N)) # To list values drom 1 to N which is 1000 np.random.shuffle(subset) # To shuffle the subset random_subset = subset[:(N // 10)] # // used in order to get integer result # To flip sign of the output of the subset for i in random_subset: output_func[i] = output_func[i] * -1 # Calculation of linear regression pseudo_inverse_X = np.dot(np.linalg.inv(np.dot(X.T, X)), X.T) weight_lin_reg = np.dot(pseudo_inverse_X, output_func) # To calculate E_in output_lin_reg = out_perceptron(X, weight_lin_reg) E_in = sum((output_lin_reg != output_func)) / N E_in_total += E_in E_in_avg = E_in_total / ITERATION print("\nQuestion #11 - Average of E_in over ", ITERATION, " iterations: ", "%.2f" % E_in_avg, " and the closest value to the average E_in is [d]0.5") # Create a plot of the classified points plt.plot(X[:,1][output_func == 1], X[:,2][output_func == 1], 'ro') plt.plot(X[:,1][output_func == -1], X[:,2][output_func == -1], 'bo') plt.xlim(-1,1) plt.ylim(-1,1) plt.show() # Question #12: # To generate new nonlinear feature vector X_new = np.array([np.ones(N), X[:,1], X[:,2], X[:,1]*X[:,2], X[:,1]*X[:,1], X[:,2]*X[:,2]]).T # Calculation of linear regression on the new feature matrix pseudo_inverse_X = np.dot(np.linalg.inv(np.dot(X_new.T, X_new)), X_new.T) weight_lin_reg = np.dot(pseudo_inverse_X, output_func) print "\n\n\n", weight_lin_reg, "\n\n\n" print type(weight_lin_reg) # try the different hypotheses that are given weight_g1 = np.array([-1, -0.05, 0.08, 0.13, 1.5, 1.5]) weight_g2 = np.array([-1, -0.05, 0.08, 0.13, 1.5, 15]) weight_g3 = np.array([-1, -0.05, 0.08, 0.13, 15, 1.5]) weight_g4 = np.array([-1, -1.5, 0.08, 0.13, 0.05, 0.05]) weight_g5 = np.array([-1, -0.05, 0.08, 1.5, 0.15, 0.15]) # compute classifications made by each hypothesis output_lin_reg = out_perceptron(X_new, weight_lin_reg) output_g1 = out_perceptron(X_new, weight_g1) output_g2 = out_perceptron(X_new, weight_g2) output_g3 = out_perceptron(X_new, weight_g3) output_g4 = out_perceptron(X_new, weight_g4) output_g5 = out_perceptron(X_new, weight_g5) mismatch_1 = sum(output_g1 != output_lin_reg) / N mismatch_2 = sum(output_g2 != output_lin_reg) / N mismatch_3 = sum(output_g3 != output_lin_reg) / N mismatch_4 = sum(output_g4 != output_lin_reg) / N mismatch_5 = sum(output_g5 != output_lin_reg) / N print("\nQuestion #12 - The closest hypothesis to the my found is [a]") # To print only two digit after decimal for numpy arrays np.set_printoptions(precision = 2) print("My hypothesis is: ", weight_lin_reg) print("The closest hypothesis [a] is: [-1 -0.05 +0.08 +0.13 +1.5 +1.5]") # Create a plot of the classified points plt.plot(X_new[:,1][output_func == 1], X_new[:,2][output_func == 1], 'ro') plt.plot(X_new[:,1][output_func == -1], X_new[:,2][output_func == -1], 'bo') plt.xlim(-1,1) plt.ylim(-1,1) plt.show() # Question #13 N = 1000 E_out_total = 0 for run in range(ITERATION): # To generate a dataset X = generate_datapoints(N) # NOTE: [:,1] returns second column of the matrix output_func = np.sign(X[:,1] * X[:,1] + X[:,2] * X[:,2] - 0.6) # To pick a subset (10% of N) subset = list(range(N)) # To list values drom 1 to N which is 1000 np.random.shuffle(subset) # To shuffle the subset random_subset = subset[:(N // 10)] # // used in order to get integer result # To flip sign of the output of the subset for i in random_subset: output_func[i] = output_func[i] * -1 # To generate a new transformed feature matrix X_new = np.array([np.ones(N), X[:,1], X[:,2], X[:,1]*X[:,2], X[:,1]*X[:,1], X[:,2]*X[:,2]]).T # To compute classification made by my hypothesis from Problem 12 output_lin_reg = out_perceptron(X_new, weight_lin_reg) # Compute disagreement between hypothesis and target function E_out = sum(output_lin_reg != output_func) / N E_out_total += E_out E_out_avg = E_out_total / ITERATION # Create a plot of the classified points plt.plot(X[:,1][output_func == 1], X[:,2][output_func == 1], 'ro') plt.plot(X[:,1][output_func == -1], X[:,2][output_func == -1], 'bo') plt.xlim(-1,1) plt.ylim(-1,1) plt.show() print("\nQuestion #13 - Average of E_out over ", ITERATION, " iterations: ", "%.2f" % E_out_avg, " and the closest value to the average E_out is [b]0.1")
25e432397ff5acb6a55406866813d141dc3ba2c2
jyu001/New-Leetcode-Solution
/solved/248_strobogrammatic_number_III.py
1,518
4.15625
4
''' 248. Strobogrammatic Number III DescriptionHintsSubmissionsDiscussSolution A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high. Example: Input: low = "50", high = "100" Output: 3 Explanation: 69, 88, and 96 are three strobogrammatic numbers. Note: Because the range might be a large number, the low and high numbers are represented as string. ''' class Solution: def findallStro(self, n): if n==0: return [] if n==1: return ['1','0','8'] if n==2: return ['00',"11","69","88","96"] res = [] if n>2: listn = self.findallStro(n-2) for s in listn: res.extend(['1'+s+'1', '0'+s+'0', '6'+s+'9','9'+s+'6','8'+s+'8']) return res def strobogrammaticInRange(self, low, high): """ :type low: str :type high: str :rtype: int """ n = len(high) numl, numh = int(low), int(high) res = [] for i in range(n+1): res.extend(self.findallStro(i)) #newres = [] count = 0 for s in res: if len(s)!= 1 and s[0] == '0': continue num = int(s) #print(s, numl, numh) if num >= numl and num <= numh: #newres.append(s) count += 1 #print (count, newres) return count
8ca38071dc0271ec0c15a947543bfab9cb8afeba
jyu001/New-Leetcode-Solution
/solved/287_find_the_duplicate_number.py
1,016
3.984375
4
''' 287. Find the Duplicate Number DescriptionHintsSubmissionsDiscussSolution Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 Example 2: Input: [3,1,3,4,2] Output: 3 Note: You must not modify the array (assume the array is read only). You must use only constant, O(1) extra space. Your runtime complexity should be less than O(n2). There is only one duplicate number in the array, but it could be repeated more than once. ''' class Solution: def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ # sum(nums)-sum(set): (k-1)*n # sum(num[i]^2) - sum(set): (k-1)*n^2 n1 = sum(nums) - sum(list(set(nums))) nums2 = [i*i for i in nums] n2 = sum(nums2) - sum(list(set(nums2))) return n2//n1
038c31fd2ae5c53532f7eb1acdb46d8bf48a7991
jyu001/New-Leetcode-Solution
/solved/224_basic_calculator.py
2,232
3.90625
4
''' 224. Basic Calculator DescriptionHintsSubmissionsDiscussSolution Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . Example 1: Input: "1 + 1" Output: 2 Example 2: Input: " 2-1 + 2 " Output: 3 Example 3: Input: "(1+(4+5+2)-3)+(6+8)" Output: 23 Note: You may assume that the given expression is always valid. Do not use the eval built-in library function. ''' class Solution: def calculate(self, s): """ :type s: str :rtype: int """ brck = 0 brclist = [0] addminus = 1 addlist = [1] checknum = False currnum = 0 s = s + ' ' for c in s: if ord(c) > 47 and ord(c) < 58: currnum = currnum * 10 + int(c) checknum = True #print('1...','brck:', brck, 'c:',c, 'currnum:', currnum, 'addlist:',addlist, 'brclist[]:',brclist) else: if checknum: #print('2...','brck:', brck, 'c:',c, 'currnum:', currnum, 'addlist:',addlist, 'brclist[]:',brclist) brclist[brck] += currnum * addminus #print('2.5...','brck:', brck, 'c:',c, 'currnum:', currnum, 'addlist:',addlist, 'brclist[]:',brclist) if c == '(': brclist.append(0) brck += 1 addlist.append(addminus) addminus = 1 elif c == ')': a = brclist.pop(brck) b = addlist.pop(brck) brck -= 1 brclist[brck] += a * b #print('3...','brck:', brck, 'c:',c, 'currnum:', currnum, 'addlist:',addlist, 'brclist[]:',brclist) elif c == '+': addminus = 1 elif c == '-': addminus = -1 currnum = 0 checknum = False #print('4...','brck:', brck, 'c:',c, 'currnum:', currnum, 'addlist:',addlist, 'brclist[]:',brclist) return brclist[0]
496fad266efb7da5320b0c1694e88c0b59f43359
jyu001/New-Leetcode-Solution
/unsolved/unsolved_312_burst_balloons.py
3,333
3.859375
4
''' 312. Burst Balloons DescriptionHintsSubmissionsDiscussSolution Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent. Find the maximum coins you can collect by bursting the balloons wisely. Note: You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them. 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 Example: Input: [3,1,5,8] Output: 167 Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 ''' class Solution: def maxCoins(self, nums): """ :type nums: List[int] :rtype: int """ #from https://www.hrwhisper.me/leetcode-burst-balloons/ c = [1] + [i for i in nums if i > 0] + [1] n = len(c) dp = [[0] * n for _ in range(n)] for k in range(2, n): for left in range(0, n - k): right = left + k dp[left][right] = max(dp[left][i] + c[left] * c[i] * c[right] + dp[i][right] for i in range(left + 1, right)) return dp[0][n - 1] ''' class Solution: def maxCoins(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n == 0: return 0 elif n == 1: return nums[0] elif n == 2: if nums[0]>=nums[1]: return nums[0]*(nums[1] + 1) else: return nums[1]*(nums[0] + 1) for i in range(len(nums)): # remove '0's if nums[i] == 0: nums.pop(i) for i in range(1,len(nums)-1): # remove minimum values a, b, c = nums[i-1],nums[i],nums[i+1] if a>=b and b<=c : nums.pop(i) print('0',a*b*c,nums) return a*b*c + self.maxCoins(nums) # now there is no minimum value # find the maxm value, and there should be no more than one maxm nmax = 0 start = nums[0] for i in range(len(nums)): if nums[i]>=start: nmax, start = i, nums[i] res = 0 if nmax == 0: # no maximum, decreasing for i in range(len(nums)-2): res += nums[1]*nums[0]*nums[2] nums.pop(1) print('1', res, nums) return res + nums[0]*(nums[1] + 1) else: # one maximum if nmax > 1: for i in range(nmax-1): res += nums[nmax-i]*nums[nmax-i-1]*nums[nmax-i-2] nums.pop(nmax-1-i) n -= 1 if nmax < n-2: for i in range(n-2-nmax): res += nums[nmax]*nums[nmax+1]*nums[nmax+2] nums.pop(nmax+1) n -= 1 # now there should be exactly 3 numbers left print('2', res, nums) return res + nums[0]*nums[1]*nums[2] + self.maxCoins([nums[0]] + [nums[2]]) # in case 5, 1, 3, 8, 4, 2, 1, => 5, 8, 4, 2, 1 => 5, 8, 4, 2, 1 => 5, 4, 2, 1 '''
a28af6976e03d8fa8d8507b39755406c31f9cbfc
jyu001/New-Leetcode-Solution
/solved/234_palindrome_linked_list.py
1,728
3.890625
4
''' 234. Palindrome Linked List DescriptionHintsSubmissionsDiscussSolution Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true Follow up: Could you do it in O(n) time and O(1) space? ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if head == None: return True new = ListNode(0) new.next = head count = 0 while new.next: new.next = new.next.next count += 1 if count == 1: return True new.next = head for i in range(count//2): if i == count//2-1: new.next.next, new.next = None, new.next.next else: new.next= new.next.next if count%2: new.next =new.next.next # find the starting node of 2nd half def reverseList(hd): """ :type head: ListNode :rtype: ListNode """ if hd == None: return None new = ListNode(0) new.next = hd.next hd.next = None while new.next: hd, new.next.next = new.next.next, hd hd, new.next = new.next, hd new.next = hd return new.next new.next = reverseList(new.next) for i in range(count//2): if new.next.val - head.val: return False new.next, head = new.next.next, head.next return True
31e0e80766186110342b0c99930cdbaee68ae2a8
jyu001/New-Leetcode-Solution
/solved/95_unique_binary_search_tree_II.py
1,454
3.921875
4
''' 95. Unique Binary Search Trees II DescriptionHintsSubmissionsDiscussSolution Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. Example: Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n==0: return [] def check(i, j): if i > j: return [None] res = [] for k in range(i, j+1): left, right = check(i, k-1), check(k+1, j) for m in left: for n in right: root=TreeNode(k) root.left, root.right = m, n res.append(root) return res return check(1,n)
ac7b6e0c203555acec76e7380d4252c767881768
jyu001/New-Leetcode-Solution
/solved/772_basic_calculator_III.py
3,407
3.890625
4
''' 772. Basic Calculator III DescriptionHintsSubmissionsDiscussSolution Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . The expression string contains only non-negative integers, +, -, *, / operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647]. Some examples: "1 + 1" = 2 " 6-4 / 2 " = 4 "2*(5+5*2)/3+(6/2+8)" = 21 "(2+6* 3+5- (3*14/7+2)*5)+3"=-12 Note: Do not use the eval built-in library function. Your input "13/(1--1)" Your answer Line 24: ZeroDivisionError: integer division or modulo by zero Expected answer 6 ''' class Solution: def calculate_wn_parentheses(self, s): """ :type s: str :rtype: int """ res = 0 front = 0 simbol = 1 # + 1, - 2, * 3, / 4 checknum = False currnum = 0 s = s + '+0' for c in s: if ord(c) > 47 and ord(c) < 58: currnum = currnum * 10 + int(c) checknum = True #print('1...','brck:', brck, 'c:',c, 'currnum:', currnum, 'addlist:',addlist, 'brclist[]:',brclist) else: if checknum: #print('2...','brck:', brck, 'c:',c, 'currnum:', currnum, 'addlist:',addlist, 'brclist[]:',brclist) if simbol == 1: front += currnum elif simbol == 2: front -= currnum elif simbol == 3: front *= currnum elif front >= 0: front = front//currnum else: front = - (-front //currnum) #print('2.5...','brck:', brck, 'c:',c, 'currnum:', currnum, 'addlist:',addlist, 'brclist[]:',brclist) if c == '+': simbol = 1 elif c == '-': simbol = 2 elif c == '*': simbol = 3 elif c == '/': simbol = 4 if c == '+' or c == '-': res = res + front front = 0 currnum = 0 checknum = False #print('4...','brck:', brck, 'c:',c, 'currnum:', currnum, 'addlist:',addlist, 'brclist[]:',brclist) return res def calculate(self, s): """ :type s: str :rtype: int """ left, right = 0, 0 lists = [] count = 0 #print(s) for i in range(len(s)): c = s[i] if c == '(': count += 1 if count == 1: left = i if c == ")": count -= 1 if count == 0: right = i lists.append([left, right]) if lists == []: return self.calculate_wn_parentheses(s) for i in range(len(lists)): i = len(lists) - 1 - i left, right = lists[i][0], lists[i][1] s = s[:left] + str(self.calculate(s[left+1:right])) + s[right + 1:] #print (s) return self.calculate(s)
530f1fc8fb3d5693cf7ea5afe8d6a743f3bdf0ff
jyu001/New-Leetcode-Solution
/solved/44_wildcard_matching.py
5,691
3.9375
4
''' 44. Wildcard Matching DescriptionHintsSubmissionsDiscussSolution Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like ? or *. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "*" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = "cb" p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. Example 4: Input: s = "adceb" p = "*a*b" Output: true Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". Example 5: Input: s = "acdcb" p = "a*c?b" Output: false ''' ''' class Solution: def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ lst = [] indx, lens, cc, ques, star, count =0, 0, '', 0, 0, 0 for i in range(len(p)): if p[i]=='*' or p[i]=='?': if indx!=i: lst=[indx, lens, cc, ques, star] #indx, lens, cc, ques, star = i+1, 0, '', 0, 0 break # only scan the first substring, not the whole string if p[i]=='*': star+=1 else: ques, count = ques+1, count+1 indx = i+1 else: lens, cc, count = lens+1, cc+p[i], count+1 if i == len(p)-1: lst=[indx, lens, cc, ques, star] #print('lst:',lst) # first check if p == '': return False if s else True elif lst[1:4:2]==[0,0]: return True elif s == '': return False elif count > len(s): return False # check the first substrings s = s[ques:] if s[:lens] == cc: return self.isMatch(s[lens:], p[indx + lens:]) if star == 0: if s[:lens]==cc: return self.isMatch(s[lens:], p[indx+lens:]) else: n = s.find(cc) #print ('0', n, cc, s, p) while n>=0: #print ('1', n, s[n+lens:], p[indx+lens:]) if self.isMatch(s[n+lens:], p[indx+lens:]): return True s = s[n+1:] n = s.find(cc) return False import time start = time.time() s = "babbbbaabababaabbababaababaabbaabababbaaababbababaaaaaabbabaaaabababbabbababbbaaaababbbabbbbbbbbbbaabbb" p = "b**bb**a**bba*b**a*bbb**aba***babbb*aa****aabb*bbb***a" Solution().isMatch(s,p) end = time.time() print(int((end-start)*1000), 'ms') ''' ''' class Solution: def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ print(s,p) lst = p.split('*') for i in range(len(lst)): if lst[len(lst)-1-i]== '': lst.pop(len(lst)-1-i) lenlst = [len(c) for c in lst] #print (lst, '\n', lenlst) if p[0]!="*": if lst[0]!= '?' and s[:lenlst[0]] != lst[0]: return False else: return self.isMatch(s[lenlst[0]:], '*'+'*'.join(lst[1:])) elif p[-1]!='*': if lst[-1]!= '?' and s[-lenlst[-1]:] != lst[-1]: return False else: return self.isMatch(s[:-lenlst[-1]], "*.join(lst[:-1])+'*'") else: import time start = time.time() s = "babbbbaabababaabbababaababaabbaabababbaaababbababaaaaaabbabaaaabababbabbababbbaaaababbbabbbbbbbbbbaabbb" p = "b**bb**a**bba*b**a*bbb**aba***babbb*aa****aabb*bbb***a" Solution().isMatch(s,p) end = time.time() print(int((end-start)*1000), 'ms') ''' class Solution: def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ # remove common head and tail elements while p and s and p[0]==s[0]: p, s=p[1:], s[1:] while p and s and p[-1]==s[-1]: p, s=p[:-1], s[:-1] # deal with empty strings if s=='' and p=='': return True elif p=='': return False elif s=='': for c in p: if c!= '*': return False return True #check head and tail if p[0]!='*' and p[0]!='?' and p[0]!=s[0]: return False if p[-1]!='*' and p[-1]!='?' and p[-1]!=s[-1]: return False # in case there is only * and ? in p n, count = len(s), 0 for c in p: if c!="*": count += 1 if count > len(s): return False #print(s, p) # deal with the * and ? at the head, before any characters showing up i, star, question = 0, 0, 0 while p[i]=='*' or p[i]=='?' : if p[i] == '?': question += 1 if p[i] == '*': star += 1 i += 1 if i == len(p): if star!=0 or i==n: return True else: return False c = p[i] #print('c:',c, 'p:',p, 'i',i) for j in range(question, n): if star==0 and s[j] != c: return False elif star==0 and s[j]==c: return self.isMatch(s[j+1:], p[i+1:]) elif star>0: if s[j] != c: continue elif self.isMatch(s[j+1:], p[i+1:]): return True return False
367d6f206ce0300b7956b4babe6adcbdf8d5c473
jyu001/New-Leetcode-Solution
/solved/753_cracking_the_safe.py
2,373
3.65625
4
''' 753. Cracking the Safe DescriptionHintsSubmissionsDiscussSolution There is a box protected by a password. The password is n digits, where each letter can be one of the first k digits 0, 1, ..., k-1. You can keep inputting the password, the password will automatically be matched against the last n digits entered. For example, assuming the password is "345", I can open it when I type "012345", but I enter a total of 6 digits. Please return any string of minimum length that is guaranteed to open the box after the entire string is inputted. Example 1: Input: n = 1, k = 2 Output: "01" Note: "10" will be accepted too. Example 2: Input: n = 2, k = 2 Output: "00110" Note: "01100", "10011", "11001" will be accepted too. Note: n will be in the range [1, 4]. k will be in the range [1, 10]. k^n will be at most 4096. ''' class Solution: def crackSafe(self, n, k): """ :type n: int :type k: int :rtype: str """ res = '0'*n dct=set([res]) if k == 1: return res if n == 1: for i in range(1,k): res += str(i) return res lst = [k-1-i for i in range(k)] check = True while check: for i in range(k): new = res[-n+1:] + str(lst[i]) #print ('res:', res, 'new:', new, 'dct:', dct) if new not in dct: dct.add(new) res += str(lst[i]) break if i == k-1: check = False return res ''' # deep first search tree ***** lst = [] for i in range(k): lst.append(i) #print (lst) for i in range(1,n): l = [] for j in range(k): #res2 = str(j) res2 = str(j) for x in range(k): res2 += str(lst[(j+i+x)%k]) if j ==2: print('j:', j, res2) l.append(res2) print ('l', l) lst = l for i in range(k): res += lst[i] dup = [] for i in range(len(res)+1-n): s=res[i:i+n] if s not in dct: dct.add(s) else: dup += [i, s] print(dup) return res '''
68f9e4d6787862d6b741682e62adb1a175699620
jyu001/New-Leetcode-Solution
/solved/654_maximum_binary_tree.py
1,212
3.984375
4
''' 654. Maximum Binary Tree DescriptionHintsSubmissionsDiscussSolution Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number. Construct the maximum tree by the given array and output the root node of this tree. Example 1: Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: 6 / \ 3 5 \ / 2 0 \ 1 Note: The size of the given array will be in the range [1,1000]. ''' class Solution: def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ if not nums: return None n = max(nums) root = TreeNode(n) for i in range(len(nums)): if nums[i] == n: root.left = self.constructMaximumBinaryTree(nums[:i]) root.right = self.constructMaximumBinaryTree(nums[i+1:]) return root
0062d5c1383541388100388eac74846941dd2836
jyu001/New-Leetcode-Solution
/solved/77_combinations.py
844
3.640625
4
''' 77. Combinations DescriptionHintsSubmissionsDiscussSolution Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. Example: Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] ''' class Solution: def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ full = [i for i in range(1,n+1)] def check(k,lst): n = len(lst) if n==k: return [lst] if k>n or k==0: return [[]] res = [] #print('n,k', n, k) for i in range(n-k+1): l = lst[i+1:] for ll in check(k-1, l): res.append([lst[i]] + ll) return res return check(k,full)
eb30bd142d3a5add2fe99d5209cafd57e3cea02e
nikolakadic/kurs-uvod-u-programiranje
/predavanje-13/oo_nastavak/static_class_variables.py
383
3.671875
4
""" """ class Fruits: """ """ count = 0 # staticka atribut klase def __init__(self, name, count): self.name = name self.count = count Fruits.count += count apples = Fruits('apple', 10) pears = Fruits('pear', 20) print(getattr(apples,'count')) setattr(pears, 'count', 200) print(getattr(pears,'count')) print(hasattr(pears,'name'))
e0e676f4eda6005dfe5bb2348bd032adc800f46c
nikolakadic/kurs-uvod-u-programiranje
/predavanje-04/petlje.py
666
3.765625
4
a = 5 b = 0 # <, >, ==, !=, and, or, not while b < a: #print('Poceo sam da izvrsavam tijelo petlje') b = b + 1 #print('b je sada ', b) # 1 - inicijalna vrijednost brojaca - range[0] # provjera uslova < range [posljednji clan niza] # povecava brojac brojac = brojac + 1 # range(n) - ova ugradjena funkcija vraca [0, 1, 2, 3, 4, 5 ... n-1] # range(5) = ova funkcija vraca [0, 1, 2, 3, 4] for brojac in range(5): print(brojac) zid_crn = False zid_bijele_boje = True print(zid_bijele_boje) if zid_crn and 5 > 4: print('Zid je crn') else: print('Zid je bijele boje') #print('Ovo je nakon petlje')
1d3a7a293d517d8799bafa94b6bafaa414c401bd
nikolakadic/kurs-uvod-u-programiranje
/predavanje-08/tooo.py
1,252
3.75
4
""" Pocetak sudoku """ print("IGRATE IGRU SUDOKU") print("") gametable = [ [1, "", "","","","","","",8], ["", 2, "","","","","","",""], ["", "", 3,"","","","","",""], ["", "", "",4,"","","","",""], ["", "", "","",5,"","","",""], ["", "", "","","",6,"","",""], ["", "", "","","","",7,"",""], ["", "", "","","","","",8,""], [9, "", "","","","","","",1], ] def print_gametable(gametable): print(gametable[0]) print(gametable[1]) print(gametable[2]) print(gametable[3]) print(gametable[4]) print(gametable[5]) print(gametable[6]) print(gametable[7]) print(gametable[8]) print_gametable(gametable) limit = 10 game_end= False unos = 0 while not game_end and unos < limit: print("Igrate!") unos = int(input("Unesite broj od 1 do 9: ")) print("Unesite koordinate: ") x = int(input()) y = int(input()) if gametable[x][y] == "": gametable[x][y] = unos else: while gametable[x][y] != "": print("Polje je vec popunjeno, unesite druge koordinate") x = int(input()) y = int(input()) gametable[x][y] = unos print_gametable(gametable) else: print("Pogresan unos")
7a78fdfe0f82c13209b873926b537be693b2beb7
nikolakadic/kurs-uvod-u-programiranje
/predavanje-12/debugger_tutorial.py
165
3.59375
4
x = 5 print(x) y = 20 print(y) for i in range(200): x = 20 print(i) x = 3 print(x) x = x + 5 + 3 print(x) # REGISTRI, STEK, HIP # REGISTERS, STACK, HEAP
9768625c56b1cae32950f73499e9ea78ab59db6e
FractalBoy/advent-of-code-2020
/ship.py
2,735
3.5625
4
from math import atan, cos, degrees, radians, sin, sqrt class UnitVector: def __init__(self): self.origin = 0, 0 self.theta = 0 def rotate(self, angle): self.theta += angle self.theta %= 360 if self.theta > 180: self.theta -= 360 def translate(self, *args): if len(args) == 1: units = args[0] curr_x, curr_y = self.origin self.origin = ( curr_x + float(units) * cos(radians(self.theta)), curr_y + float(units) * sin(radians(self.theta)), ) elif len(args) == 2: [translate_x, translate_y] = args curr_x, curr_y = self.origin self.origin = (curr_x + translate_x, curr_y + translate_y) def __repr__(self): return f"Origin: {self.origin} Angle: {self.theta}" class Vector: def __init__(self): self.origin = 0, 0 self.waypoint = 10, 1 def translate(self, *args): if len(args) == 1: units = args[0] curr_x, curr_y = self.origin waypoint_x, waypoint_y = self.waypoint self.origin = (curr_x + units * waypoint_x, curr_y + units * waypoint_y) elif len(args) == 2: [translate_x, translate_y] = args waypoint_x, waypoint_y = self.waypoint self.waypoint = (waypoint_x + translate_x, waypoint_y + translate_y) def rotate(self, angle): angle = radians(angle) waypoint_x, waypoint_y = self.waypoint self.waypoint = ( waypoint_x * round(cos(angle)) - waypoint_y * round(sin(angle)), waypoint_x * round(sin(angle)) + waypoint_y * round(cos(angle)), ) def __repr__(self): return f"Origin: {self.origin} Waypoint: {self.waypoint}" class SimpleShip(UnitVector): def move(self, direction, units): dispatch_table = { "N": self.move_north, "E": self.move_east, "S": self.move_south, "W": self.move_west, "L": self.rotate_left, "R": self.rotate_right, "F": self.move_forward, } return dispatch_table[direction](units) def move_north(self, units): self.translate(0, units) def move_east(self, units): self.translate(units, 0) def move_south(self, units): self.translate(0, -units) def move_west(self, units): self.translate(-units, 0) def rotate_left(self, units): self.rotate(units) def rotate_right(self, units): self.rotate(-units) def move_forward(self, units): self.translate(units) class ComplexShip(Vector, SimpleShip): pass
bad0d581be04c1d145b6874a81272980339da3ce
jghee/Algorithm_Python
/coding/ch6/sort2.py
295
3.625
4
n = int(input()) info = [] for i in range(n): name, score = input().split() info.append((name, int(score))) def setting(data): return data[1] result = sorted(info, key=setting) # result = sorted(info, key=lambda student: studnet[1]) for i in result: print(i[0], end=' ')
8298ec6c8af26231d9561b22a215758912eb667a
clchiou/uva-problem-set
/leetcode/148-sort-list/148.py
5,815
4.125
4
#!/usr/bin/env python3 # # NOTE: You cannot use recursion because stack growth is not # constant space complexity. # class Solution: def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None if not head.next: return head length = 0 this = head while this: length += 1 this = this.next # # Bottom-up merge sort. # def merge(left, right, unit): assert left and right head = tail = None i = j = 0 while left and right and i < unit and j < unit: if left.val < right.val: node = left left = left.next i += 1 else: node = right right = right.next j += 1 if head: tail.next = node tail = tail.next else: head = tail = node if left and i < unit: assert not (right and j < unit) tail.next = left while left and i < unit: tail = left left = left.next i += 1 if right and j < unit: tail.next = right while right and j < unit: tail = right right = right.next j += 1 assert head return head, tail, left, right unit = 1 while unit < length: # Find multiple of unit close to half. prev = None this = head for _ in range(max(unit, length // unit // 2 * unit)): prev = this this = this.next left_tail = prev right_head = this # Break up left half and right half. left_tail.next = None tail = None left = head right = right_head while left or right: merged_head, merged_tail, next_left, next_right = \ merge(left, right, unit) if left is head: head = merged_head if tail: tail.next = merged_head tail = merged_tail left = next_left right = next_right # One half is empty; let's try to balance it. if not left and right: left = right for _ in range(unit - 1): right = right.next if right is None: break if right: this = right right = right.next this.next = None elif left and not right: right = left for _ in range(unit - 1): left = left.next if left is None: break if left: this = left left = left.next this.next = None # If there is really nothing left for merging. if not left: tail.next = right break if not right: tail.next = left break unit *= 2 return head if __name__ == '__main__': import random class ListNode: @classmethod def from_list(cls, list_): head = tail = None for val in list_: node = cls(val) if head: tail.next = node tail = tail.next else: head = tail = node return head def __init__(self, val): self.val = val self.next = None def __str__(self): return '<%d%s>' % (self.val, ', ...' if self.next else '') def to_list(self, bound=-1): list_ = [] node = self while node: list_.append(node.val) node = node.next if bound > 0 and len(list_) > bound: list_.append('...') break return list_ def assert_eq(expect, actual): if expect != actual: raise AssertionError('expect %r, not %r' % (expect, actual)) solution = Solution() assert_eq(None, solution.sortList(ListNode.from_list([]))) assert_eq([1], solution.sortList(ListNode.from_list([1])).to_list()) assert_eq([1, 2], solution.sortList(ListNode.from_list([1, 2])).to_list()) assert_eq([1, 2], solution.sortList(ListNode.from_list([2, 1])).to_list()) assert_eq( [1, 2, 3], solution.sortList(ListNode.from_list([2, 1, 3])).to_list(), ) assert_eq( [1, 2, 3, 4], solution.sortList(ListNode.from_list([2, 1, 4, 3])).to_list(), ) random.seed(7) num_repeat = 10 for n in range(4, 128): for _ in range(num_repeat): testdata = [random.randint(0, 1000) for _ in range(n)] expect = sorted(testdata) assert_eq( expect, solution.sortList(ListNode.from_list(testdata)).to_list(), ) with open('in') as testdata_file: expect = eval(testdata_file.read()) testdata = ListNode.from_list(expect) expect.sort() assert_eq(expect, solution.sortList(testdata).to_list())
dc70a991b6d8e3f39f25dd2b4aad14e965cb45ef
clchiou/uva-problem-set
/leetcode/419-battleships-in-a-board/419.py
705
3.734375
4
#!/usr/bin/env python3 class Solution: def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ num_ships = 0 for i in range(len(board)): for j in range(len(board[i])): if board[i][j] != 'X': pass elif i > 0 and board[i-1][j] == 'X': pass elif j > 0 and board[i][j-1] == 'X': pass else: num_ships += 1 return num_ships if __name__ == '__main__': import sys board = list(map(list, sys.stdin.readlines())) print(Solution().countBattleships(board))
25ebbda61eedaea5aa42cd6017c68dbaad2d9cc9
clchiou/uva-problem-set
/leetcode/513-find-bottom-left-tree-value/513.py
1,315
3.875
4
#!/usr/bin/env python3 class Solution: def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ leftmost = root.val queue = [root] while queue: leftmost = queue[0].val next_queue = [] for node in queue: if node.left: next_queue.append(node.left) if node.right: next_queue.append(node.right) queue = next_queue return leftmost class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): return '(%d %r %r)' % (self.val, self.left or (), self.right or ()) if __name__ == '__main__': solution = Solution() root = TreeNode(2, TreeNode(1), TreeNode(3)) print(root) print(solution.findBottomLeftValue(root)) root = TreeNode( 1, TreeNode( 2, TreeNode(4), None, ), TreeNode( 3, TreeNode( 5, TreeNode(7), None, ), TreeNode(6), ), ) print(root) print(solution.findBottomLeftValue(root))
b6d388ca18178eeac5a1e102c00163f10e9884a2
clchiou/uva-problem-set
/leetcode/215-kth-largest-element-in-an-array/215.py
1,188
3.5625
4
#!/usr/bin/env python3 class Solution: def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ import random def solve(nums, nth): if len(nums) == 1: return nums[0] pivot_i = random.randint(0, len(nums) - 1) pivot = nums[pivot_i] larger = [ x for i, x in enumerate(nums) if x > pivot and i != pivot_i ] if len(larger) >= nth: return solve(larger, nth) not_larger = [ x for i, x in enumerate(nums) if x <= pivot and i != pivot_i ] if len(larger) == nth - 1 and len(not_larger) == len(nums) - nth: return pivot return solve(not_larger, nth - len(larger) - 1) return solve(nums, k) if __name__ == '__main__': import sys solution = Solution() while True: line = sys.stdin.readline() if not line: break ints = list(map(int, line.split())) print(solution.findKthLargest(ints[:-1], ints[-1]))
3b02429c502bd626af33425069025aa8cadac2c9
clchiou/uva-problem-set
/solved/138/solve.py
294
3.625
4
#!/usr/bin/env python3 import math import sys def main(): count = 10 n = 2 while count > 0: k = math.sqrt((n * n + n) / 2) if math.trunc(k) == k: print('%10d%10d' % (k, n)) count -= 1 n += 1 if __name__ == '__main__': main()
0974f977ae53592c7068e046686a84073d227dea
clchiou/uva-problem-set
/leetcode/338-counting-bits/338.py
833
3.765625
4
#!/usr/bin/env python3 class Solution: def countBits(self, num): """ :type num: int :rtype: List[int] """ output = [0] num_ones = 0 binary = [0] * (32 + 1) # Assume num < 2^32. for _ in range(1, num + 1): # Add 1 to `binary`. for i in range(len(binary)): if binary[i] == 0: binary[i] = 1 num_ones += 1 break else: binary[i] = 0 num_ones -= 1 output.append(num_ones) return output if __name__ == '__main__': import sys solution = Solution() while True: line = sys.stdin.readline() if not line: break print(solution.countBits(int(line)))
eca8b4304251854b16c21e977a9f40a556a8211e
skylar02/HighSchoolCamp
/string_practice.py
2,700
4
4
""" title: string_practice author: Skylar date: 2019-06-11 13:45 """ import random #chara = input("Enter a character") #print("a" in chara or "b" in chara or "c" in chara or "d" in chara or "e" in chara or "f" in chara or "g" in chara or "h" in chara or "i" in chara or "j" in chara or "k" in chara or "l" in chara or "m" in chara or "n" in chara or "o" in chara or "p" in chara or "q" in chara or "r" in chara or "s" in chara or "t" in chara or "u" in chara or "v" in chara or "w" in chara or "x" in chara or "y" in chara or "z" in chara) #short = input("Enter a greeting here") #short_hand = short.replace("and", "&").replace("too", "2").replace("you", "U").replace("for", "4").replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") #print(short_hand) #fn = input("Enter your first name") #ln = input("Enter your last name") #cn = input("Enter birth city") #ug = input("Enter Alma Mater university") #rn = input("Enter a relative's name") #frn = input("Enter a friend's name") #print(fn[:4] + str(ln[-3:])) + cn[:3] + ug[-4:] + rn[str(random.randint(0,len(rn))):-1] + fn[0:str(random.randint(len(frn)))] #phrase = "Don't count your chickens before the hatch" #slogan = "For everything else, there's mastercard" #combined = f"{phrase}. {slogan}" #print(combined) #print(phrase[::2]) #print(phrase[17:25]) #print('m' in slogan) #print(combined.upper()) #print(''.join(combined)) #print(slogan[::-1]) def is_letter(chara): return chara.lower() in "qwertyuiopasdfghjklzxcvbnm" print(is_letter("qwertyuiop")) print(is_letter('0')) def short_hand(short): short = short.replace("and", "&").replace("too", "2").replace("you", "U").replace("for", "4") short = short.replace("a","").replace("e", "").replace("i", "").replace("o", "").replace("u", "") return short inp = input("Enter a phrase:") print(short_hand(inp)) def cred(fn, ln, cb, u, rn, fr): fn = fn[:3] ln = ln[-2:] cb = cb[:2] u = u[-3:] rn = rn[random.randint(0,len(rn)):] fr = fr[:random.randint(0,len(fr))] return fn+ln+cb+u+rn+fr f = input("Enter your first name") s = input("Enter your last name") t = input("Enter the city you were born in") fo = input("Enter the university you graduated from") fi = input("Enter the name of a relative") si = input("Enter the name of a friend") print(cred(f, s, t, fo, fi, si)) def removing(check): check = check.lower() check = check.replace(" ", "").replace(",", "").replace("'", "") return check er = input("Enter stuff") print(removing(er)) def palindrome(check): check = removing(check) return check in check[::-1] oyu = input("Enter more stuff") print(palindrome(oyu))
cc919777e9f8abc405b711e93b64184543882331
ctl106/AoC-solutions
/2020/03/solution2.py
1,074
3.53125
4
#!/usr/bin/env python3 import sys from functools import reduce KEY = {"end": "!", "tree": "#", "empty": "."} def read_input_file(): inname = sys.argv[1] inlst = [] infile = open(inname, "r") for line in infile: inlst.append(line.strip()) infile.close return inlst def contents(loc, mymap): output = None if loc[1] >= len(mymap): output = KEY["end"] else: output = mymap[loc[1]][loc[0]%len(mymap[0])] return output def traverse(loc, x, y, mymap): loc[0] += x loc[1] += y return contents(loc, mymap) def check_slope(inlst, x, y): total = 0 loc = [0, 0] content = contents(loc, inlst) while content != KEY["end"]: if content == KEY["tree"]: total += 1 content = traverse(loc, x, y, inlst) return total def solve(inlst): slopes = [ [1, 1], [3, 1], [5, 1], [7, 1], [1, 2], ] trees = [check_slope(inlst, slope[0], slope[1]) for slope in slopes] output = reduce((lambda x, y: x*y), trees) return output def main(): inlst = read_input_file() total = solve(inlst) print(total) if __name__ == "__main__": main()