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 |
|---|---|---|---|---|---|---|
49e055bca5c2583e22d6cf48a570c5c32a830c71 | aysin/Python-Projects | /repeat.py | 271 | 4 | 4 | #defines a 'repeat' function that takes 2 argument
def repeat(s, exclaim):
result = s * 3
if exclaim:
result += '!!!'
return result
def main():
print repeat ('Yay', False)
print repeat ('woo hoo', True)
print repeat('Yay', False)
print repeat('Woo Hoo', True)
|
d190cf17e29502fd451ff812f68414fef94eeec9 | aysin/Python-Projects | /ex32.py | 538 | 4.65625 | 5 | #creating list while doing loops
the_count = [1, 2, 3, 4, 5]
fruits = ['apple', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#this first kind of for loop goes through a list
for n in the_count:
print "This is count %d." % n
#same as above
for n in fruits:
print "A fruit type is: %s." % n
for n in change:
print "I got: %r." % n
#build an empty list
element = []
for n in range(0,6):
print "Adding %d to the list." % n
element.append(n)
for i in element:
print "elements was: %d" % i |
cd8dd7f643ff410882645f6492d301197eeee484 | nyLee-max/python_study | /chap03/chap03_01.py | 112 | 3.53125 | 4 | # 값 비교
print(10 == 100)
print(10 is 100)
print(10 != 100)
print(10 is not 100)
x = 25;
print(20 < x < 30) |
9514e7d97fcfa6bc45e153ac464989b4868ab991 | bmargerison/codewars | /Python/MakeUpperCase (8kyu).py | 189 | 3.96875 | 4 | """
Write a function which converts the input string to uppercase.
"""
# my solution
def make_upper_case(s):
return s.upper()
# best solution
def make_upper_case(s): return s.upper() |
5ee3bde1ea205254430a61648a14d1909d0956ae | ankimoha/BookStore | /frontend.py | 3,195 | 4.125 | 4 | """
This is an application that store all the information of a book in a bookstore
These are the things that a user can do in this application:
search a book
add a book
update an entry
delete
close
"""
from tkinter import *
import backend
def get_selected_record(event):
try:
global selected_tuple
index = list1.curselection()[0]
selected_tuple = list1.get(index)
e1.delete(0,END)
e1.insert(END,selected_tuple[1])
e2.delete(0,END)
e2.insert(END,selected_tuple[2])
e3.delete(0,END)
e3.insert(END,selected_tuple[3])
e4.delete(0,END)
e4.insert(END,selected_tuple[4])
except IndexError:
pass
def view_command():
list1.delete(0,END)
for row in backend.view():
list1.insert(END,row) #every row is inserted at the end of the listbox
def search_command():
list1.delete(0,END)
#the get method is used below because the title_text is in StringVar format, we need to convert that into string object
for row in backend.search(title_text.get(),author_text.get(),year_text.get(),isbn_text.get()):
list1.insert(END,row)
def add_command():
backend.insert(title_text.get(),author_text.get(),year_text.get(),isbn_text.get())
list1.delete(0,END)
list1.insert(END,(title_text.get(),author_text.get(),year_text.get(),isbn_text.get()))
def update_command():
backend.update(selected_tuple[0],title_text.get(),author_text.get(),year_text.get(),isbn_text.get())
def delete_command():
backend.delete(selected_tuple[0])
window = Tk()
window.wm_title("BookStrore")
l1 = Label(window,text = "Title")
l1.grid(row = 0,column = 0)
l2 = Label(window,text = "Author")
l2.grid(row = 0,column = 2)
l3 = Label(window,text = "Year")
l3.grid(row = 1,column = 0)
l4 = Label(window,text = "ISBN")
l4.grid(row = 1,column = 2)
title_text = StringVar()
e1 = Entry(window,textvariable = title_text)
e1.grid(row = 0,column = 1)
author_text = StringVar()
e2 = Entry(window,textvariable = author_text)
e2.grid(row = 0,column = 3)
year_text = StringVar()
e3 = Entry(window,textvariable = year_text)
e3.grid(row = 1,column = 1)
isbn_text = StringVar()
e4 = Entry(window,textvariable = isbn_text)
e4.grid(row = 1,column = 3)
list1 = Listbox(window,height = 6,width = 35)
list1.grid(row =2,column = 0,rowspan = 6,columnspan = 2)
sb1 = Scrollbar(window)
sb1.grid(row = 2, column = 2)
list1.configure(yscrollcommand = sb1.set)
sb1.configure(command=list1.yview)
list1.bind('<<ListboxSelect>>',get_selected_record)
b1 = Button(window,text = "View all", width = 12,command = view_command)
b1.grid(row = 2,column = 3)
b2 = Button(window,text = "Search", width = 12, command = search_command)
b2.grid(row = 3,column = 3)
b3 = Button(window,text = "Add Entry", width = 12, command = add_command)
b3.grid(row = 4,column = 3)
b4 = Button(window,text = "Update Selected", width = 12, command = update_command)
b4.grid(row = 5,column = 3)
b5 = Button(window,text = "Delete selected", width = 12, command = delete_command)
b5.grid(row = 6,column = 3)
b6 = Button(window,text = "Close", width = 12, command = window.destroy)
b6.grid(row = 7,column = 3)
window.mainloop()
|
ef43ec961cbe83db63f0d53f56796ecf2cc12b37 | AshTiwari/Python-Guide | /OOPS/OOPS_global_local_static_instance_variable.py | 559 | 3.65625 | 4 | #global, local, static, instance variable.
#global variable are defined at the op of program or defined using keyword:global
global global_var1 = 1
def local_variable:
#local variable are defined inside of a function or a class.
local_var1 = 2
class static_instance:
#local variable are defined inside of a function or a class.
local_var2 = 3
def __init__(self):
#all variables defined in the function of a class.
self.static_var1 = 4
def static(self):
self.static_var2 = 5
local_var3 = 6
|
0dd3b07d4250e643eab1ce11efbe11d05bfbf6cb | AshTiwari/Python-Guide | /staticmethod_Iheritance.py | 584 | 3.859375 | 4 | # static method in inheritance
class Parent:
class_var1 = 1
def __init__(self):
self.param1 = 10
self.param2 = Parent.staticmethod1()
self.param3 = self.staticmethod2()
@staticmethod
def staticmethod1():
return 20
@staticmethod
def staticmethod2():
return 30
class child(Parent):
@staticmethod
def staticmethod1():
return 200
@staticmethod
def staticmethod2():
return 300
if __name__ == "__main__":
object1 = child()
print(object1.param2)
print(object1.param3)
|
8d48eb05e3ba95ea9a2818f1b4ac5729c39aa3e8 | AshTiwari/Python-Guide | /Basic Python/user_defined_functions.py | 1,157 | 4.09375 | 4 | #User Defined Functions in python
# Functions
#Syntax
'''
def funct_name (parameters):
statements
return (expression)
x = funct_name(parameter_value)
#x takes the value returned by function.
#If the function dosen't return any value the x will take value 'None'.
'''
def increment(val):
val=val+1
print(val)
return val
x= increment(4)
print('The value returned by "increment function" is\n:')
print(x)
'''
Note:
1."def" stands for definition.
2.Parameters dosen't have types.
=> It has both advantage and disadvantage.
1. Coding becomes easy.
2. Debugging becomes difficult.
****************************************************** Excercise *******************************************************
1. >> def increment(val)
>> val=val+1
>> print(val)
>> x= increment(4)
>> print(x)
Predict O/P:
Ans:4
None
The function returns 'None'. So x takes 'None'.
Thus, not secifying types may give results which we didn't expect at begining.
'''
|
13a8aa65cf25ed0cf5b42a45f92c9fa5fc6b7e93 | AshTiwari/Python-Guide | /Regex/Regular_Expression.py | 4,578 | 3.9375 | 4 | # regular expression.
import re
message = ('Call at +91-9280690895 or +91-9920699095')
RegExpObj = re.compile(r'\+\d\d-\d\d\d\d\d\d\d\d\d\d') #raw string as an input argument.
#findall()
print('\n\nfindall()')
print('Prints all regular expression and its group.')
m_o = RegExpObj.findall(message) #makes 'm_o' a list,prints all the regexp found in message.
print('Printing the variable type returned and its value by findall() ')
print(type(m_o))
print(m_o)
#search()
print('\n\nsearch()')
m_o = RegExpObj.search(message) #match_object searches the expresion in the message
print('Printing results of searcch()')
print(m_o)
print(type(m_o))
#group() #next step of search()
print('\n\ngroup()')
m_o = RegExpObj.search(message)
if m_o ==None:
print('Phone Number not found.')
else:
print('Looking for a phone number in a message using group().')
print(m_o.group()) #mo.group() shows the first regExp found.
#We can break a reg-exp into multiple groups.
RegExpObj2 = re.compile(r'(\+\d\d)-(\d\d\d\d\d\d\d\d\d\d)') #Area code and phone no.
match_object2 = RegExpObj2.search(message)
if match_object2 ==None:
print('Phone Number not found.')
else:
print('Printing 1st group i.e area code.')
print(match_object2.group(1)) #prints the 1st group of exp found.
print('Printing 2nd group i.e. phone no.')
print(match_object2.group(2)) #prints the 2nd group of expression found.
#pipe character:'|' and curly braces: '{}'
print('\n\nPipe Charcter and {}')
print('Here, we can use "+" or "0" interchangebly because of pipe "|".')
RegExpObj3 = re.compile(r'((\+|0)\d{2})-(\d{10})') #| => or ;{n} => repeated n times.
message = ('Call me at +91-9999900000 or 022-2222200000')
m_o3 = RegExpObj3.search(message)
if m_o3 ==None:
print('Phone Number not found.')
else:
print('Printing all groups')
print(RegExpObj3.findall(message))
print('Printing each group')
print(m_o3.group(1))
print(m_o3.group(2))
print(m_o3.group(3))
#print(m_o3.group(4))
#print(m_o3.group(5)) # how to print next three group of second regex found.
#print(m_o3.group(6))
#Repetition of expressions.
print('Useful characters to check the repetition of expression.')
print('{n}: check if preceding string is repeated n times.')
print('?: check if preceding string is used 0 or 1 times.')
print('*: check if preceding string is used 0 or more time.')
print('+: check if preceding string is used 1 or more times.')
print('{n}: check if preceding string is used exactly n times.')
print('{x,y}: used more than x times and less than equal to y times.')
# ?
print('\n\n[?,*,+,{}] character')
msg1 = 'I am sorry'
msg2 = 'I am verysorry'
msg3 = 'I am veryveryverysorry.'
pattern1 = r'(very)?sorry'
pattern2 = r'(very)*sorry'
pattern3 = r'(very)+sorry'
pattern4 = r'(very){1,2}sorry'
print('\nWorking of ? character on 3 different messages.')
reo = re.compile(pattern1)
m_o = reo.search(msg1)
print(m_o.group())
m_o = reo.search(msg2)
print(m_o.group())
m_o = reo.search(msg3)
print(m_o.group()) # matches only the last 'very' and skips the first 2.
print('\nWorking of * character on 3 different messages.')
reo = re.compile(pattern2)
m_o = reo.search(msg1)
print(m_o.group())
m_o = reo.search(msg2)
print(m_o.group())
m_o = reo.search(msg3)
print(m_o.group())
print('\nWorking of + character on 3 different messages.')
reo = re.compile(pattern3)
m_o = reo.search(msg1)
if m_o==None:
print('No expression found in message one.')
m_o = reo.search(msg2)
print(m_o.group())
m_o = reo.search(msg3)
print(m_o.group())
print('\n{} already demonstrated with pipe character.')
print('\nWorking of {x,y} on 3 different messages.')
reo = re.compile(pattern4)
m_o = reo.search(msg1)
if m_o==None:
print('No expression found in message one.')
m_o = reo.search(msg2)
print(m_o.group())
m_o = reo.search(msg3)
print(m_o.group()) #matches only 2 of 'very'.
# greedy and non-greedy search
print('\n\n\nGreedy and non-greedy search.\n')
print('Python by defult uses greedy search method')
print('i.e it will find the longest possible search.')
reo = re.compile(r'(\d){3,5}')
mo = reo.search('1234567890')
print(mo.group())
print('To use non greedy search method use "?"')
print('i.e it will find the shortest possible search.')
reo = re.compile(r'(\d){3,5}?')
mo = reo.search('1234567890')
print(mo.group())
|
1689e0badd6bfc5c742c18bbce1df341cda6f723 | AshTiwari/Python-Guide | /OOPS/OOPS_Class_Composition_vs_Aggregation.py | 327 | 3.828125 | 4 | # difference between class composition and aggregation.
print('1.')
print('-In composition, if the object of second class deletes then')
print(' the object of first classs automatically deletes.')
print('-But, in aggregation both the objects are intanstiated seperately,')
print(' so they dont have an effect on each other.')
|
328e01359af583ee01b0d794f2cea72e30e382cd | AshTiwari/Python-Guide | /Files/file_os_delete_file.py | 1,029 | 3.953125 | 4 | #deleting files.
import os
os.path.isfile('D://f1.txt')
os.path.isdir('D://f1')
#for deleting files, access is denied.
#PermissionError: [WinError 5] Access is denied: 'C://Users//MSI//Desktop//folder'
#We can try to delete folder by changing user account control.
#Alternatively, we can check that the programming is running by typing command
#on python website.
#unlink() for txt files
open('D://text.txt','w')
print('File created.')
os.unlink('D://text.txt') #delete file
print('File deleted.')
try:
os.mkdir('D://folder')
except FileExistsError:
pass
try:
os.unlink('D://folder') #delete folder
except PermissionError:
print("Python dosen't have permission to delete the folderon this OS.")
#rmdir for directories.
#NOTE: Only deltes empty folder.
try:
os.mkdir('D://fold:er2')
except FileExistsError:
pass
try:
os.rmdir('D://folder2') #only deletes empty folder.
except PermissionError:
print("Python dosen't have permission to delete the folder on this OS.")
|
b8b2a1657751ce23a002789f4cc298aecaf43263 | AshTiwari/Python-Guide | /OOPS/OOPS_Operator_Overloading.py | 158 | 3.6875 | 4 | # operator overloading
print('Everything is object in python.')
print('- ' + str(type(2)))
print('- It is an object of class "int".')
# yet to complete.
|
210541b96402d575201e7bce74d539bd89e8aa97 | AshTiwari/Python-Guide | /Python Iter Tools/namedtuple_methods().py | 318 | 3.921875 | 4 | #named tuple functions.
from collections import namedtuple
student = namedtuple('student','name age')
print('Functions in namedtuple.')
print('\nPrint field of tuple.')
print(student._fields)
s1 = ('Ash',21)
s2 = ('Ashu',22)
print('\nPrinting tuple of namedtuple.')
t = (s1, s2)
print(t)
print(type(t[1]))
|
49210e9015050c7aefcbb429b1815f01e6e6a44e | AshTiwari/Python-Guide | /OOPS/OOPS_encapsulation.py | 1,474 | 3.890625 | 4 | #encapsulation.
class unencapsulated:
def __init__(self,rNo):
self.roll_no = rNo
class encapsulated:
def __init__(self,rNo):
self.__roll_no = rNo
def getRollNo(self) :
return self.__roll_no
def changeRollNo(self,no):
self.__roll_no = no
unsafe = unencapsulated(1)
#prints the roll_no and thus not private.
print('Printing a argument of an unencapsulated class.')
print(unsafe.roll_no)
#easily modify and hence no integrity.
unsafe.roll_no = 2
print('Modifying and printing an argument of an unencapsulated class.')
print(unsafe.roll_no)
print('\n\n\n')
safe = encapsulated(1) # creating object of the class.
#cannot print an argument that is private.
try:
print('Trying to print an argument of a encapsulated class.')
print(safe.roll_no) # cannot access it.
except AttributeError:
print('Fail:')
print("-'encapsulated' object has no attribute 'roll_no' ")
print('-i.e program cannot see if there is any argument named roll_no.')
print('-Thus keeping it safe.')
#neither can modify it.
safe.__roll_no = 2
print('\n')
print('Even if we try to modify the argument, we wont be able to do it.')
print(safe.getRollNo()) # prints the old value of roll_no not updated one.
print('\n')
safe.changeRollNo(3)
print('Succefully change the roll_no using changeRollNo function of the class.')
print(safe.getRollNo())
|
cde03d01900ffa7f01f5f80e4bfc869454ac8116 | AshTiwari/Python-Guide | /OOPS/OOPS_Abstract_Class_and_Method.py | 720 | 4.5625 | 5 | #abstract classes
# ABC- Abstract Base Class and abstractmethod
from abc import ABC, abstractmethod
print('abstract method is the method user must implement in the child class.')
print('abstract method cannot be instantiated outside child class.')
print('\n\n')
class parent(ABC):
def __init__(self):
pass
@abstractmethod #it is a decorator.
def square():
pass
class child(parent):
def __init__(self,num):
self.num = num
def square(self): # if not implemented here, it will give TypeError:
return self.num**2
Child =child(5)
print(Child.square())
try:
Parent =parent()
except TypeError:
print('Cant instantiate abstract class.')
|
eb9dee9b3ae053c0fb598791d6cd7f40e2171a87 | AshTiwari/Python-Guide | /Regex/Regular_Expression_search()andgroup().py | 701 | 3.84375 | 4 | #search(pattern) and group()
import re
message = ('Call at +91-9280690895 or +91-9920699095')
RegExpObj = re.compile(r'\+\d\d-\d\d\d\d\d\d\d\d\d\d') #raw string as an input argument.
#search()
m_o = RegExpObj.search(message) #match_object searches the expresion in the message
print('Printing results of searcch()')
print(m_o)
print(type(m_o))
#group() #next step of search()
print('\n\ngroup()')
m_o = RegExpObj.search(message)
if m_o ==None:
print('Phone Number not found.')
else:
print('Looking for a phone number in a message using group().')
print(m_o.group()) #mo.group() shows the first regExp found.
|
fb1a77d591507125bed703a7da342f8a20d1c21a | AshTiwari/Python-Guide | /Graphs/shortest_path_using_top_sort.py | 975 | 3.734375 | 4 | # shortest path on DAG
# handles negative edges.
from topological_sort import topologicalSort
def shortestPath(adjacent, edge_weight):
topological_sort = topologicalSort(adjacent)
start = topological_sort[0]
distance = [float("inf") for i in range(len(adjacent))]
distance[start] = 0
parent = {start:None}
for node in topological_sort:
for neighbour in adjacent[node]:
if distance[neighbour] > distance[node] + edge_weight[node][neighbour]:
parent[neighbour] = node
distance[neighbour] = distance[node] + edge_weight[node][neighbour]
return distance, parent
if __name__ == "__main__":
adjacent = {0:[1,2], 1:[2,3,4], 2:[3,6], 3:[4,5,6], 4:[7], 5:[7], 6:[7], 7:[]}
edge_weight = [[0,3,6,0,0,0,0],[0,0,4,4,11,0,0,0],[0,0,0,8,0,0,11,0],[0,0,0,0,-4,5,2,0],[0,0,0,0,0,0,0,9],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,2],[0,0,0,0,0,0,0,0]]
print(shortestPath(adjacent, edge_weight))
|
7e4ddd15e0f172c12d428ae551708b3c650abc08 | ColinFendrick/python-udemy | /python-1000/s5/mylistdelta.py | 154 | 3.625 | 4 | zlist = ["Fred", "Ralph", "Zelda", "Zoe"]
print(type(zlist))
for index in range(len(zlist)):
zlist[index] = "Guest " + zlist[index]
print(zlist)
|
11534692689f007ac35d5ceea6075fc24f86a318 | JeremyPaulPalmer/Python-Projects | /Hangman/bad_guess.py | 2,373 | 4 | 4 | import hangman
#Graphic representation of each stage of incorrect guesses. Final incorrect
#guess results in play defeat, hanged man, and prompt to show word and start
#new game
def bad_guess(x, word, letters):
if x == 6:
print(' _____')
print(' | |')
print(' O |')
print(' |')
print(' |')
print(' |')
print(' _____|\n')
print('You have', x, 'more incorrect guesses!\n')
elif x == 5:
print(' _____')
print(' | |')
print(' O |')
print(' | |')
print(' |')
print(' |')
print(' _____|\n')
print('You have', x, 'more incorrect guesses!\n')
elif x == 4:
print(' _____')
print(' | |')
print(' O |')
print(' \| |')
print(' |')
print(' |')
print(' _____|\n')
print('You have', x, 'more incorrect guesses!\n')
elif x == 3:
print(' _____')
print(' | |')
print(' O |')
print(' \|/ |')
print(' |')
print(' |')
print(' _____|\n')
print('You have', x, 'more incorrect guesses!\n')
elif x == 2:
print(' _____')
print(' | |')
print(' O |')
print(' \|/ |')
print(' | |')
print(' |')
print(' _____|\n')
print('You have', x, 'more incorrect guesses!\n')
elif x == 1:
print(' _____')
print(' | |')
print(' O |')
print(' \|/ |')
print(' | |')
print(' / |')
print(' _____|\n')
print('You have', x, 'more incorrect guesses!\n')
else:
print(' _____')
print(' | |')
print(' O |')
print(' | |')
print(' /|\ |')
print(' / \ |')
print(' _____|\n')
print('Oh no! The hangman has been hanged!!\n')
answer = input('Would you like to know the word? (y/n)')
if answer.lower().strip() == 'y':
print('\nYour word was: ', word.upper(),'\n')
answer = input('Would you like to try again? (y/n)')
if answer.lower().strip() == 'y':
hangman.play()
else:
print('\nThank you for playing! Swing you again soon! Muahaha!')
exit() |
16ce6311c48799bc0773f095191fe66c6541cf75 | JeremyPaulPalmer/Python-Projects | /Yahtzee/yahtzee.py | 2,524 | 3.6875 | 4 | import global_var
import dice_roll
import os
import sys
import view_dice
import upper_lower
import card
import choice
import time
print('Welcome to Yahtzee!')
card.card()
def play():
print('Roll', global_var.roll_counter + 1)
time.sleep(2)
full_upper = False
full_lower = False
#while upper and lower not full, keep going
while full_upper == False or full_lower == False:
#initial roll
if global_var.kept_dice_list == [] or global_var.kept_dice_list == 5:
dice_roll.roll(5)
global_var.roll_counter += 1
else:
dice_roll.roll(5 - len(global_var.kept_dice_list))
for i in global_var.kept_dice_list:
global_var.dice_list.append(i)
global_var.roll_counter += 1
global_var.kept_dice_list = []
#view dice
view_dice.view_dice()
#prompt user to choose between score, roll again or keep dice
if global_var.roll_counter < 3:
choice.choice()
else:
upper_lower.upper_lower()
#check to see if counters are 6 and 7 respectively in which case full equals True and the loop breaks.
if global_var.counter_upper == 6:
full_upper = True
if global_var.counter_lower == 7:
full_lower = True
#reinitialize lists
global_var.ones_list = []
global_var.twos_list = []
global_var.threes_list = []
global_var.fours_list = []
global_var.fives_list = []
global_var.sixes_list = []
global_var.dice_list = []
global_var.dice_hist = []
#check subtotal to see if the bonus is achieved
if full_upper:
if global_var.subtotal > 63:
global_var.upper_bonus = 35
global_var.total_upper = global_var.subtotal + global_var.upper_bonus
else:
global_var.upper_bonus = 0
global_var.total_upper = global_var.subtotal
if full_lower:
global_var.total_lower = sum(global_var.lower_sub_list)
if full_lower and full_upper:
global_var.grand_total = global_var.total_lower + global_var.total_upper
card.card()
answer = input('Great game! Would you like to play again? (y/n) ')
if answer == 'yes'.lower().strip() or answer == 'y'.lower().strip():
os.execv(__file__, sys.argv)
if __name__ == "__main__":
play() |
e43016c2f00cf2b4c02a1b79666c0b8e6596fa5c | JeremyPaulPalmer/Python-Projects | /Yahtzee/upper_score.py | 3,861 | 3.921875 | 4 | import global_var
import time
import card
def upper_score():
score = (input('Where would you like to score? (1-6) '))
while score != '1' and score != '2' and score != '3' and score != '4' and score != '5' and score != '6':
score = (input('Where would you like to score? (1-6) '))
if score == '0' or score >= '7':
score = ''
upper_score()
while score:
if score == 'ones'.lower().strip() or score == '1':
if global_var.ones == '__':
global_var.ones = sum(global_var.ones_list)
global_var.upper_sub_list.append(global_var.ones)
global_var.subtotal = sum(global_var.upper_sub_list)
global_var.counter_upper += 1
score = ''
else:
print('Already scored. Try again!')
score = input('\nWhere would you like to score?\n')
if score == 'twos'.lower().strip() or score == '2':
if global_var.twos == '__':
global_var.twos = sum(global_var.twos_list)
global_var.upper_sub_list.append(global_var.twos)
global_var.subtotal = sum(global_var.upper_sub_list)
global_var.counter_upper += 1
score = ''
else:
print('Already scored. Try again!')
score = input('\nWhere would you like to score?\n')
if score == 'threes'.lower().strip() or score == '3':
if global_var.threes == '__':
global_var.threes = sum(global_var.threes_list)
global_var.upper_sub_list.append(global_var.threes)
global_var.subtotal = sum(global_var.upper_sub_list)
global_var.counter_upper += 1
score = ''
else:
print('Already scored. Try again!')
score = input('\nWhere would you like to score?\n')
if score == 'fours'.lower().strip() or score == '4':
if global_var.fours == '__':
global_var.fours = sum(global_var.fours_list)
global_var.upper_sub_list.append(global_var.fours)
global_var.subtotal = sum(global_var.upper_sub_list)
global_var.counter_upper += 1
score = ''
else:
print('Already scored. Try again!')
score = input('\nWhere would you like to score?\n')
if score == 'fives'.lower().strip() or score == '5':
if global_var.fives == '__':
global_var.fives = sum(global_var.fives_list)
global_var.upper_sub_list.append(global_var.fives)
global_var.subtotal = sum(global_var.upper_sub_list)
global_var.counter_upper += 1
score = ''
else:
print('Already scored. Try again!')
score = input('\nWhere would you like to score?\n')
if score == 'sixes'.lower().strip() or score == '6':
if global_var.sixes == '__':
global_var.sixes = sum(global_var.sixes_list)
global_var.upper_sub_list.append(global_var.sixes)
global_var.subtotal = sum(global_var.upper_sub_list)
global_var.counter_upper += 1
score = ''
else:
print('Already scored. Try again!')
score = input('\nWhere would you like to score?\n')
card.card()
time.sleep(2)
global_var.roll_counter = 0
global_var.dice_list = []
global_var.dice_hist = [] |
8971130c5137892b0c1d8d4a522e99137320fe66 | JamesLuoau/reinforcement_learning | /model_based_keras.py | 5,914 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import gym
env = gym.make("CartPole-v0")
learning_rate = 1e-3 # Learning rate, applicable to both nn, policy and model
gamma = 0.99 # Discount factor for rewards
decay_rate = 0.99 # Decay factor for RMSProp leaky sum of grad**2
model_batch_size = 3 # Batch size used for training model nn
policy_batch_size = 3 # Batch size used for training policy nn
dimen = dimen = env.observation_space.shape[0] # Number of dimensions in the environment
def discount(r, gamma=0.99, standardize=False):
"""Takes 1d float array of rewards and computes discounted reward
e.g. f([1, 1, 1], 0.99) -> [1, 0.99, 0.9801]
"""
discounted = np.array([val * (gamma ** i) for i, val in enumerate(r)])
if standardize:
discounted -= np.mean(discounted)
discounted /= np.std(discounted)
return discounted
def step_model(sess, xs, action):
""" Uses our trained nn model to produce a new state given a previous state and action """
# Last state
x = xs[-1].reshape(1, -1)
# Append action
x = np.hstack([x, [[action]]])
# Predict output
output_y = sess.run(predicted_state_m, feed_dict={input_x_m: x})
# predicted_state_m == [state_0, state_1, state_2, state_3, reward, done]
output_next_state = output_y[:, :4]
output_reward = output_y[:, 4]
output_done = output_y[:, 5]
# First and third env outputs are limited to +/- 2.4 and +/- 0.4
output_next_state[:, 0] = np.clip(output_next_state[:, 0], -2.4, 2.4)
output_next_state[:, 2] = np.clip(output_next_state[:, 2], -0.4, 0.4)
# Threshold for being done is likliehood being > 0.1
output_done = True if output_done > 0.01 or len(xs) > 500 else False
return output_next_state, output_reward, output_done
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
num_hidden_m = 256
dimen_m = dimen + 1
model_m = Sequential()
model_m.add(Dense(num_hidden_m, input_dim=dimen_m, activation="relu"))
model_m.add(Dense(num_hidden_m, activation="relu"))
model_m.add(Dense(dimen + 1 + 1)) # output layer: next obs, reward, gameover
model_m.compile(optimizer=Adam(lr=learning_rate), loss="mse")
# Policy network
num_hidden_p = 256
dimen_p = dimen
model_p = Sequential()
model_p.add(Dense(num_hidden_p, input_dim=dimen_p, activation="relu"))
model_p.add(Dense(2)) # Two outputs, one for action 0, one for action 1
model_p.compile(optimizer=Adam(lr=learning_rate), loss="mse")
# Keep track our our rewards
reward_sum = 0
reward_total = []
# Tracks the score on the real (non-simulated) environment to determine when to stop
episode_count = 0
num_episodes = 5000
max_num_moves = 300
# Setup array to keep track of observations, rewards and actions
observations = np.empty(0).reshape(0, dimen)
rewards = np.empty(0).reshape(0, 1)
actions = np.empty(0).reshape(0, 1)
policies = np.empty(0).reshape(0, 2)
draw_from_model = False
train_the_model = True
train_the_policy = False
num_episode = 0
observation = env.reset()
while num_episode < num_episodes:
observation = observation.reshape(1, -1)
# Determine the policy
policy = model_p.predict(observation)
policies = np.vstack([policies, policy])
# Decide on an action based on the policy, allowing for some randomness
action = np.argmax(model_p.predict(observation)[0])
# Keep track of the observations and actions
observations = np.vstack([observations, observation])
actions = np.vstack([actions, action])
# Determine next observation either from model or real environment
if draw_from_model:
output = model_m.predict(np.hstack([observation, action]))
observation, reward, done = output[:4], output[4], output[5]
else:
observation, reward, done, _ = env.step(action)
# Keep track of rewards
reward_sum += reward
rewards = np.vstack([rewards, reward])
# If game is over or running long
if done or len(observations) > max_num_moves:
# Keep track of how many real scenarios to determine average score from real environment
episode_count += 1
# Keep track of rewards
reward_total.append(reward_sum)
# Discount rewards
disc_rewards = discount(rewards, standardize=True)
for idx, action, disc_reward in zip(range(len(actions)), actions, disc_rewards):
policies[idx, int(action[0])] = disc_reward
num_episode += 1
observation = env.reset()
if train_the_policy:
model_p.train_on_batch(observations, policies)
# Reset everything
observations = np.empty(0).reshape(0, dimen)
rewards = np.empty(0).reshape(0, 1)
actions = np.empty(0).reshape(0, 1)
policies = np.empty(0).reshape(0, 2)
# Print periodically
if (num_episode % (100 * policy_batch_size) == 0):
# prob_random -= 0.1
# prob_random = max(0.0, prob_random)
print("Episode {} rewards: {}".format(
num_episode, reward_sum / policy_batch_size))
# If we our real score is good enough, quit
if episode_count > 0:
if (reward_sum / episode_count >= 300):
print("Episode {} Training complete with total score of: {}".format(
num_episode, reward_sum / episode_count))
break
episode_count = 0
reward_sum = 0
reward_sum = 0
# See our trained bot in action
observation = env.reset()
observation
reward_sum = 0
num_move = 0
while True:
env.render()
x = np.reshape(observation, [1, dimen])
y = model_p.predict(x)
y = np.argmax(y[0])
observation, reward, done, _ = env.step(y)
reward_sum += reward
num_move += 1
if done or num_move > max_num_moves:
print("Total score: {}".format(reward_sum))
break |
e3e3d219ebe745654300590349f8ada101ff0181 | billtomking/Python_Practice | /井字棋/井字棋胜率估计(非随机).py | 12,185 | 3.640625 | 4 | #随机下子
import copy
import random
from time import time
from pprint import pprint
import csv
TheBoard = {'1':' ','2':' ','3':' ',
'4':' ','5':' ','6':' ',
'7':' ','8':' ','9':' '}
jie = ''
def printboard(board):
print('-' * 20)
print(j)
print(jie)
print(board['1'] + '|' + board['2'] + '|' + board['3'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-' * 20)
def Yan(board):
if board['1'] == board['2'] and board['2'] == board['3']:
if board['1'] != ' ':
return 1
else:
return
elif board['4'] == board['5'] and board['5'] == board['6']:
if board['4'] != ' ':
return 1
else:
return
elif board['7'] == board['8'] and board['8'] == board['9']:
if board['7'] != ' ':
return 1
else:
return
elif board['1'] == board['4'] and board['4'] == board['7']:
if board['1'] != ' ':
return 1
else:
return
elif board['3'] == board['6'] and board['6'] == board['9']:
if board['3'] != ' ':
return 1
else:
return
elif board['2'] == board['5'] and board['5'] == board['8']:
if board['2'] != ' ':
return 1
else:
return
elif board['1'] == board['5'] and board['5'] == board['9']:
if board['1'] != ' ':
return 1
else:
return
elif board['3'] == board['5'] and board['5'] == board['7']:
if board['3'] != ' ':
return 1
else:
return
else:
return
def You(board):
you = []
you1 = []
#必赢位置
if board['1'] == board['2'] and board['2'] == turn and board['3'] == ' ':
return 3
elif board['1'] == board['3'] and board['3'] == turn and board['2'] == ' ':
return 2
elif board['2'] == board['3'] and board['3'] == turn and board['1'] == ' ':
return 1
elif board['4'] == board['5'] and board['5'] == turn and board['6'] == ' ':
return 6
elif board['4'] == board['6'] and board['6'] == turn and board['5'] == ' ':
return 5
elif board['5'] == board['6'] and board['6'] == turn and board['4'] == ' ':
return 4
elif board['7'] == board['8'] and board['8'] == turn and board['9'] == ' ':
return 9
elif board['7'] == board['9'] and board['9'] == turn and board['8'] == ' ':
return 8
elif board['8'] == board['9'] and board['9'] == turn and board['7'] == ' ':
return 7
elif board['1'] == board['4'] and board['4'] == turn and board['7'] == ' ':
return 7
elif board['1'] == board['7'] and board['7'] == turn and board['4'] == ' ':
return 4
elif board['4'] == board['7'] and board['7'] == turn and board['1'] == ' ':
return 1
elif board['2'] == board['5'] and board['5'] == turn and board['8'] == ' ':
return 8
elif board['2'] == board['8'] and board['8'] == turn and board['5'] == ' ':
return 5
elif board['5'] == board['8'] and board['8'] == turn and board['2'] == ' ':
return 2
elif board['3'] == board['6'] and board['6'] == turn and board['9'] == ' ':
return 9
elif board['3'] == board['9'] and board['9'] == turn and board['6'] == ' ':
return 6
elif board['6'] == board['9'] and board['9'] == turn and board['3'] == ' ':
return 3
elif board['1'] == board['5'] and board['5'] == turn and board['9'] == ' ':
return 9
elif board['1'] == board['9'] and board['9'] == turn and board['5'] == ' ':
return 5
elif board['5'] == board['9'] and board['9'] == turn and board['1'] == ' ':
return 1
elif board['3'] == board['5'] and board['5'] == turn and board['7'] == ' ':
return 7
elif board['3'] == board['7'] and board['7'] == turn and board['5'] == ' ':
return 5
elif board['5'] == board['7'] and board['7'] == turn and board['3'] == ' ':
return 3
#必输位置
elif board['1'] == board['2'] and board['2'] != turn and board['2'] != ' ' and board['3'] == ' ':
return 3
elif board['1'] == board['3'] and board['3'] != turn and board['3'] != ' ' and board['2'] == ' ':
return 2
elif board['2'] == board['3'] and board['3'] != turn and board['3'] != ' ' and board['1'] == ' ':
return 1
elif board['4'] == board['5'] and board['5'] != turn and board['5'] != ' ' and board['6'] == ' ':
return 6
elif board['4'] == board['6'] and board['6'] != turn and board['6'] != ' ' and board['5'] == ' ':
return 5
elif board['5'] == board['6'] and board['6'] != turn and board['6'] != ' ' and board['4'] == ' ':
return 4
elif board['7'] == board['8'] and board['8'] != turn and board['8'] != ' ' and board['9'] == ' ':
return 9
elif board['7'] == board['9'] and board['9'] != turn and board['9'] != ' ' and board['8'] == ' ':
return 8
elif board['8'] == board['9'] and board['9'] != turn and board['9'] != ' ' and board['7'] == ' ':
return 7
elif board['1'] == board['4'] and board['4'] != turn and board['4'] != ' ' and board['7'] == ' ':
return 7
elif board['1'] == board['7'] and board['7'] != turn and board['7'] != ' ' and board['4'] == ' ':
return 4
elif board['4'] == board['7'] and board['7'] != turn and board['7'] != ' ' and board['1'] == ' ':
return 1
elif board['2'] == board['5'] and board['5'] != turn and board['5'] != ' ' and board['8'] == ' ':
return 8
elif board['2'] == board['8'] and board['8'] != turn and board['8'] != ' ' and board['5'] == ' ':
return 5
elif board['5'] == board['8'] and board['8'] != turn and board['8'] != ' ' and board['2'] == ' ':
return 2
elif board['3'] == board['6'] and board['6'] != turn and board['6'] != ' ' and board['9'] == ' ':
return 9
elif board['3'] == board['9'] and board['9'] != turn and board['9'] != ' ' and board['6'] == ' ':
return 6
elif board['6'] == board['9'] and board['9'] != turn and board['9'] != ' ' and board['3'] == ' ':
return 3
elif board['1'] == board['5'] and board['5'] != turn and board['5'] != ' ' and board['9'] == ' ':
return 9
elif board['1'] == board['9'] and board['9'] != turn and board['9'] != ' ' and board['5'] == ' ':
return 5
elif board['5'] == board['9'] and board['9'] != turn and board['9'] != ' ' and board['1'] == ' ':
return 1
elif board['3'] == board['5'] and board['5'] != turn and board['5'] != ' ' and board['7'] == ' ':
return 7
elif board['3'] == board['7'] and board['7'] != turn and board['7'] != ' ' and board['5'] == ' ':
return 5
elif board['5'] == board['7'] and board['7'] != turn and board['7'] != ' ' and board['3'] == ' ':
return 3
#需要加入不必要位置检测
else:#选出空位
for i in range(1,10):
if board[str(i)] == ' ':
you.append(str(i))
you1 = copy.copy(you)
if len({board['1'],board['2'],board['3']}) == 3:
if board['1'] == ' ':
you.remove('1')
elif board['2'] == ' ':
you.remove('2')
elif board['3'] == ' ':
you.remove('3')
if len({board['4'],board['5'],board['6']}) == 3:
if board['4'] == ' ':
you.remove('4')
elif board['5'] == ' ':
you.remove('5')
elif board['6'] == ' ':
you.remove('6')
if len({board['7'],board['8'],board['9']}) == 3:
if board['7'] == ' ':
you.remove('7')
elif board['8'] == ' ':
you.remove('8')
elif board['9'] == ' ':
you.remove('9')
if len({board['1'],board['4'],board['7']}) == 3:
if board['1'] == ' ':
try:
you.remove('1')
except:
pass
elif board['4'] == ' ':
try:
you.remove('4')
except:
pass
elif board['7'] == ' ':
try:
you.remove('7')
except:
pass
if len({board['2'],board['5'],board['8']}) == 3:
if board['2'] == ' ':
try:
you.remove('2')
except:
pass
elif board['5'] == ' ':
try:
you.remove('5')
except:
pass
elif board['8'] == ' ':
try:
you.remove('8')
except:
pass
if len({board['3'],board['6'],board['9']}) == 3:
if board['3'] == ' ':
try:
you.remove('3')
except:
pass
elif board['6'] == ' ':
try:
you.remove('6')
except:
pass
elif board['9'] == ' ':
try:
you.remove('9')
except:
pass
if len({board['1'],board['5'],board['9']}) == 3:
if board['1'] == ' ':
try:
you.remove('1')
except:
pass
elif board['5'] == ' ':
try:
you.remove('5')
except:
pass
elif board['9'] == ' ':
try:
you.remove('9')
except:
pass
if len({board['2'],board['5'],board['7']}) == 3:
if board['2'] == ' ':
try:
you.remove('2')
except:
pass
elif board['5'] == ' ':
try:
you.remove('5')
except:
pass
elif board['7'] == ' ':
try:
you.remove('7')
except:
pass
if you == []:
you = copy.copy(you1)
random.shuffle(you)
return you[0]
n=0
x=0
o=0
j=0
p=1
xWin=[]
oWin=[]
time1 = time()
ju = input('测试局数')
time1 = time()
board = TheBoard
while j < int(ju):
FangFa=[]
board = copy.copy(TheBoard)
turn = 'X'
n = 0
jie = ''
print(j)
while n < 9:
think = str(You(board))
if board[think] != ' ':
continue
FangFa.append(think)
board[think] = turn
if Yan(board) == 1:
j += 1
if turn == 'X':
x +=1
if FangFa not in xWin:
xWin.append(FangFa)
jie = '\'X\'赢了'
#printboard(board)
else :
o +=1
if FangFa not in oWin:
oWin.append(FangFa)
jie = '\'O\'赢了'
#printboard(board)
n = 9
elif n==8:#平局判定
j += 1
p +=1
n = 9
jie = '平局'
#printboard(board)
else:
if turn == 'X':
turn = 'O'
else:
turn = 'X'
n += 1
print('总数' + str(ju))
print('先手(X)胜数' + str(x))
print('后手(O)胜数' + str(o))
print('平局数' + str(p))
print('方法总数' + str(len(xWin)+len(oWin)))
with open('xW非随机('+ str(ju) +').csv','wt',newline='') as fout:
csvout = csv.writer(fout)
csvout.writerows(xWin)
with open('oW非随机('+ str(ju) +').csv','wt',newline='') as fout:
csvout = csv.writer(fout)
csvout.writerows(oWin)
print('运算用时' + str(time()-time1))
n = input()
|
f78e136d2c84ef95c26714d1f0bee1e901334128 | billtomking/Python_Practice | /文本加密解密/0.1/加密.py | 5,995 | 3.578125 | 4 | # 之后应该可以将字数转换部分集合到一个函数里
ming_wen = input('请输入明文(带空格)')
ming_wen = ming_wen.upper()
ming_wen = list(ming_wen.split())
mingl = len(ming_wen)
mi_wen = []
n = 0
def chuang_yao(n): # 用于产生随机密钥,之后可以考虑修改让用户自行输入
import random
if n=='':
n = mingl
i = 1
n = int(n)
mi_yao = []
while i <= n:
i += 1
a = random.randint(0, 35)
if a == 0:
b = '0'
elif a == 1:
b = '1'
elif a == 2:
b = '2'
elif a == 3:
b = '3'
elif a == 4:
b = '4'
elif a == 5:
b = '5'
elif a == 6:
b = '6'
elif a == 7:
b = '7'
elif a == 8:
b = '8'
elif a == 9:
b = '9'
elif a == 10:
b = 'A'
elif a == 11:
b = 'B'
elif a == 12:
b = 'C'
elif a == 13:
b = 'D'
elif a == 14:
b = 'E'
elif a == 15:
b = 'F'
elif a == 16:
b = 'G'
elif a == 17:
b = 'H'
elif a == 18:
b = 'I'
elif a == 19:
b = 'J'
elif a == 20:
b = 'K'
elif a == 21:
b = 'L'
elif a == 22:
b = 'M'
elif a == 23:
b = 'N'
elif a == 24:
b = 'O'
elif a == 25:
b = 'P'
elif a == 26:
b = 'Q'
elif a == 27:
b = 'R'
elif a == 28:
b = 'S'
elif a == 29:
b = 'T'
elif a == 30:
b = 'U'
elif a == 31:
b = 'V'
elif a == 32:
b = 'W'
elif a == 33:
b = 'X'
elif a == 34:
b = 'Y'
elif a == 35:
b = 'Z'
mi_yao.append(str(b))
return mi_yao
def zitoshu(yuan): # 用于将文字转换成数字,以便后续计算
yuan = str(yuan)
if yuan == '0':
return 0
elif yuan == '1':
return 1
elif yuan == '2':
return 2
elif yuan == '3':
return 3
elif yuan == '4':
return 4
elif yuan == '5':
return 5
elif yuan == '6':
return 6
elif yuan == '7':
return 7
elif yuan == '8':
return 8
elif yuan == '9':
return 9
elif yuan == 'A':
return 10
elif yuan == 'B':
return 11
elif yuan == 'C':
return 12
elif yuan == 'D':
return 13
elif yuan == 'E':
return 14
elif yuan == 'F':
return 15
elif yuan == 'G':
return 16
elif yuan == 'H':
return 17
elif yuan == 'I':
return 18
elif yuan == 'J':
return 19
elif yuan == 'K':
return 20
elif yuan == 'L':
return 21
elif yuan == 'M':
return 22
elif yuan == 'N':
return 23
elif yuan == 'O':
return 24
elif yuan == 'P':
return 25
elif yuan == 'Q':
return 26
elif yuan == 'R':
return 27
elif yuan == 'S':
return 28
elif yuan == 'T':
return 29
elif yuan == 'U':
return 30
elif yuan == 'V':
return 31
elif yuan == 'W':
return 32
elif yuan == 'X':
return 33
elif yuan == 'Y':
return 34
elif yuan == 'Z':
return 35
def shutozi(yuan): # 用于将计算结果转换成文字
yuan = str(yuan)
if yuan == '0':
return '0'
elif yuan == '1':
return '1'
elif yuan == '2':
return '2'
elif yuan == '3':
return '3'
elif yuan == '4':
return '4'
elif yuan == '5':
return '5'
elif yuan == '6':
return '6'
elif yuan == '7':
return '7'
elif yuan == '8':
return '8'
elif yuan == '9':
return '9'
elif yuan == '10':
return 'A'
elif yuan == '11':
return 'B'
elif yuan == '12':
return 'C'
elif yuan == '13':
return 'D'
elif yuan == '14':
return 'E'
elif yuan == '15':
return 'F'
elif yuan == '16':
return 'G'
elif yuan == '17':
return 'H'
elif yuan == '18':
return 'I'
elif yuan == '19':
return 'J'
elif yuan == '20':
return 'K'
elif yuan == '21':
return 'L'
elif yuan == '22':
return 'M'
elif yuan == '23':
return 'N'
elif yuan == '24':
return 'O'
elif yuan == '25':
return 'P'
elif yuan == '26':
return 'Q'
elif yuan == '27':
return 'R'
elif yuan == '28':
return 'S'
elif yuan == '29':
return 'T'
elif yuan == '30':
return 'U'
elif yuan == '31':
return 'V'
elif yuan == '32':
return 'W'
elif yuan == '33':
return 'X'
elif yuan == '34':
return 'Y'
elif yuan == '35':
return 'Z'
mi_yao = chuang_yao(input('密钥长度'))
while n < len(mi_yao): # 将密钥转换成数字
mi_yao[n] = zitoshu(mi_yao[n])
n += 1
n = 0
while n < len(ming_wen): # 将明文转换成数字
ming_wen[n] = zitoshu(ming_wen[n])
n += 1
i = 0
n = 0
for i in ming_wen: # 加密部分
if n >= len(mi_yao):
n = 0
k = mi_yao[n]
if n < len(mi_yao):
mi = (i - k)
if mi < 0:
mi += 36
mi_wen.append(mi)
n += 1
n = 0
while n < len(mi_wen): # 密文数字转文字
mi_wen[n] = shutozi(mi_wen[n])
n += 1
n = 0
while n < len(mi_yao): # 密钥数字转文字
mi_yao[n] = shutozi(mi_yao[n])
n += 1
mi_yao = ''.join(mi_yao)
mi_wen = ''.join(mi_wen)
print('密钥是' + '')
print(mi_yao) # 要找方法将列表转换成字符串
print('密文是:' + ' ')
print(mi_wen)
|
f7d8a882ffb990d069f1cb3e1119881752ea6beb | murphyptx/murphytools | /pdf_imageonly/pdfcheck.py | 884 | 3.65625 | 4 | import pdfplumber # the power tool to rip through and analyze the PDFs
import glob # filename pattern matching
import os # for interacting with the file system
import shutil # sile system operations; copying, etc.
pdf_source_path = ""
pdf_no_text_path = ""
pdf_text_path = ""
print('You are about to analyze PDFs for text content, under the following top level path:')
print(pdf_source_path)
print('\n')
print('PDF files containing text will be copied here:')
print(pdf_text_path)
print('\n')
print('PDF files without text will be copied here:')
print(pdf_no_text_path)
print('\n')
print('******* ATTENTION *******')
print('Check the above paths. \n If they are not correct, press '"Q"' \n If they are correct, press '"C"')
input('')
with pdfplumber.open("2021_bills_wrong_insurance.pdf") as pdf:
page = pdf.pages[0]
text = page.extract_text()
print(text)
|
47d9de81f2dca433304440c3eed83f236f1f78a0 | kirane61/letsUpgrade | /Projects/Milestone project/TicTacToe/game.py | 5,553 | 4.3125 | 4 | #Write a function that can print on a board
#set your board as a list
#Where each index 1-9 corresponds with a number on a number pad
#You get a 3 by 3 board representation
# from IPython.display import clear_output
def display_board(board):
# clear_output()
print('--------------------------')
print(' | | ')
print(' '+ board[6] +' | '+board[7]+' | '+board[8])
print(' | | ')
print('--------------------------')
print(' | | ')
print(' '+ board[3] +' | '+board[4]+' | '+board[5])
print(' | | ')
print('--------------------------')
print(' | | ')
print(' '+ board[0] +' | '+board[1]+' | '+board[2])
print(' | | ')
print('--------------------------')
test_board=[' ',' ',' ',' ',' ',' ',' ',' ',' ']
display_board(test_board)
# Write a function that can take in a player input and assign their marker as 'X' or 'O'
def player_input():
marker = ''
while not (marker == 'X' or marker == 'O'):
marker = input("Player1: Do you want to be X or O").upper()
if marker == 'X':
return ('X', 'O')
else:
return ('O', 'X')
# Write a function that takes in the board list object , a marker ('x' or'O),dESIRED NUMBER(1-9)
def place_maker(test_board, marker, position):
test_board[position - 1] = marker
# Write a function takes in a board and check to see if someone has wons?
def check_winner(board, mark):
return ((board[6] == mark and board[7] == mark and board[8] == mark) or # across top row
(board[3] == mark and board[4] == mark and board[5] == mark) or # across middle row
(board[0] == mark and board[1] == mark and board[2] == mark) or # across bottom row
(board[0] == mark and board[3] == mark and board[6] == mark) or # across left column
(board[1] == mark and board[4] == mark and board[7] == mark) or # across middle column
(board[2] == mark and board[5] == mark and board[8] == mark) or # across right coumn
(board[0] == mark and board[4] == mark and board[8] == mark) or # across left to right diagonal
(board[2] == mark and board[4] == mark and board[6]) == mark # across right to left diagonal
)
# Write a function that uses the random module to randomly decided which player goes first ?
# You may to lookup random randint() return a string at at which player went first?
import random
def choose_first():
if(random.randint(0,1)==0):
return 'player1'
else:
return 'player2'
#Write a functio that returns a boolean indicating whether a space on the board is freely available?
def space_check(board,position):
if board[position-1]==' ':
return True
else:
return False
#Write a function that check if the board is full and return a boolean value - True is full. Otherwise False
def full_board_check(board):
for i in range(9):
if(space_check(board, i)):
return False
return True
#Step 8:Write a function that asks for a players next position (as anumber 1-9)
# And then uses the function from step 6 to check if its a free position.
#If it is then return the position for later use
def player_choice(board):
position = 10
while position-1 not in [0, 1, 2, 3, 4, 5, 6, 7, 8] or not space_check(test_board, position - 1):
position = int(input("Choice your next position (1-9)"))
return position
#STEP 9:
# write a function that asks the player if they want to play again and return a boolean.
#If they want to play again and returns a boolean True if they do want to play
def check_for_replay():
user_input = input("Press Y to play again or N to stop it")
return user_input
#Step 10:
# Here use the while loop and the functions you have made to run the game
print("Welcome to Tic Tac Toe")
while True:
theBoard = [' '] * 10
player1_marker, player2_marker = player_input()
turn = choose_first()
print(turn + "will go first.")
if check_for_replay().lower()[0] == 'y':
game_on = True
else:
game_on = False
while game_on:
if turn == 'player1':
display_board(theBoard)
position = player_choice(theBoard)
place_maker(theBoard, player1_marker, position)
display_board(theBoard)
if check_winner(theBoard, player1_marker):
display_board(theBoard)
print("Congratulations! You have won the game !")
game_on = False
else:
if full_board_check(theBoard):
display_board(theBoard)
print("The game is draw !")
else:
turn = "player2"
else:
turn = 'player2'
display_board(theBoard)
position = player_choice(theBoard)
place_maker(theBoard, player2_marker, position)
display_board(theBoard)
if check_winner(theBoard, player2_marker):
display_board(theBoard)
print("Congratulations! "+player2_marker+" won the game!")
game_on = False
else:
if full_board_check(theBoard):
display_board(theBoard)
print("The game is draw!")
else:
turn = "player1"
if not check_for_replay():
break
|
54acadc2fb5af27b386dd4ead0cbfcdd62492a53 | kirane61/letsUpgrade | /Day3/ContactBook.py | 526 | 3.796875 | 4 |
#Contact Book
howManyContact = int(input("Enter the number of contacts you want to add: "))
contactDictionary = {}
for i in range(0,howManyContact):
name = input("Enter Name:")
number1 = input("Enter number1:")
number2 = input("Enter number2:")
imageurl = input("Enter imageUrl:")
email = input("Enter email:")
website = input("Enter website:")
contactDictionary[name]= {
"name":name,
"number1":number1,
"number2":number2,
"imageurl":imageurl,
"email": email,
"website": website
}
|
597e2b3918aa6a8bf0a63d2c6a8e88722c4d471f | hernaneche/gpiotest | /gpiotest.py | 556 | 3.78125 | 4 | #!/usr/bin/python
#coding: latin-1
import RPi.GPIO as GPIO
# Selecciona numeración de pines
# BCM es nro de gpio
# BOARD es nro de pin (indicado en placa)
pinNumber = 12
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pinNumber, GPIO.OUT) #configura como salida
#GPIO.output(pinNumber, False) #manejo individual
p = GPIO.PWM(pinNumber, 1) #configura pwm en pin, freq=1Hz
for i in range(0,100,5): # aumenta de a 5
p.start(i)
s = raw_input(str(i)+"% enter para continuar.")
print "fin"
s = raw_input("enter para salir")
GPIO.cleanup() |
4bc681eda2ae57a3d3b55dbba931d7130ecb6b67 | jklusnick/fashion_app | /create_person.py | 601 | 4.03125 | 4 | class Person:
"""GBiT student"""
def __init__(self, age, name, eye_color, fav_ice_cream):
self.age = age
self.name = name
self.eye_color = eye_color
self.fav_ice_cream = fav_ice_cream
def print_person(self):
print "This person's name is " + self.name + ", " + str(self.age) + " years old, has " + self.eye_color + " eye color, and " + self.fav_ice_cream + " is his favorite flavor of ice cream"
def change_name(self,new_name):
self.name = new_name
jake = Person(17, "Jake", "brown", "chocolate chip cookie dough")
jake.print_person()
jake.change_name("Jacob")
jake.print_person()
|
9a5abf54834ca5034906b847c71539513ee9fa28 | alastairparagas/functionalprogramming-workshop | /dataisimmutable.py | 788 | 3.921875 | 4 | # Bad Example
def mutatesParams(mutableObjectParam):
mutableObjectParam["newAddedProperty"] = "someValue"
return mutableObjectParam
someObject = {
"key": "value"
}
returnValue1 = mutatesParams(someObject)
print("newAddedProperty" in someObject.keys())
print("newAddedProperty" in someObject.keys())
print(someObject == returnValue1)
# Good Example
import copy
def doesNotMutateParams(mutableObjectParam):
returnedObject = copy.deepcopy(mutableObjectParam)
returnedObject["newAddedProperty"] = "someValue"
return returnedObject
someOtherObject = {
"key": "value"
}
returnValue2 = doesNotMutateParams(someOtherObject);
print("newAddedProperty" in someOtherObject.keys())
print("newAddedProperty" in returnValue2.keys())
print(someOtherObject == returnValue2)
|
e8187f4393ff43fc5d05a2a836249ecab831a4e3 | MariaKrepko/my_python | /my_max.py | 86 | 3.640625 | 4 | num1=input()
num2=input()
if num1 > num2:
print(num1)
else:
print(num2)
|
c6032cb68386c2ddc8018f357f98624a9440fcf8 | mhigu/AutonomousFlyingCar | /lessons/MovingInto3D/random_sampling.py | 2,910 | 3.90625 | 4 | import time
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from shapely.geometry import Polygon, Point
"""
In this notebook you'll work with the obstacle's polygon representation itself.
Your tasks will be:
Create polygons.
Sample random 3D points.
Remove points contained by an obstacle polygon.
Recall, a point (x,y,z)(x,y,z) collides with a polygon if the (x,y)(x,y) coordinates are
contained by the polygon and the zz coordinate (height) is less than the height of the polygon.
"""
def extract_polygons(data):
polygons = []
for i in range(data.shape[0]):
north, east, alt, d_north, d_east, d_alt = data[i, :]
# TODO: Extract the 4 corners of the obstacle
#
# NOTE: The order of the points matters since
# `shapely` draws the sequentially from point to point.
#
# If the area of the polygon is 0 you've likely got a weird
# order.
corners = [(north - d_north, east - d_east),
(north - d_north, east + d_east),
(north + d_north, east + d_east),
(north + d_north, east - d_east)]
# TODO: Compute the height of the polygon
height = alt + d_alt
# TODO: Once you've defined corners, define polygons
p = Polygon(corners)
polygons.append((p, height))
return polygons
def collides(polygons, point):
# TODO: Determine whether the point collides
# with any obstacles.
# return False
for polygon in polygons:
if polygon[1] > point[2] and polygon[0].contains(Point(*point[:2])):
return True
return False
if __name__ == "__main__":
# This is the same obstacle data from the previous lesson.
filename = 'data/colliders.csv'
data = np.loadtxt(filename, delimiter=',', dtype='Float64', skiprows=2)
print(data)
polygons = extract_polygons(data)
xmin = np.min(data[:, 0] - data[:, 3])
xmax = np.max(data[:, 0] + data[:, 3])
ymin = np.min(data[:, 1] - data[:, 4])
ymax = np.max(data[:, 1] + data[:, 4])
zmin = 0
# Limit the z axis for the visualization
zmax = 10
print("X")
print("min = {0}, max = {1}\n".format(xmin, xmax))
print("Y")
print("min = {0}, max = {1}\n".format(ymin, ymax))
print("Z")
print("min = {0}, max = {1}".format(zmin, zmax))
num_samples = 100
xvals = np.random.uniform(xmin, xmax, num_samples)
yvals = np.random.uniform(ymin, ymax, num_samples)
zvals = np.random.uniform(zmin, zmax, num_samples)
samples = list(zip(xvals, yvals, zvals))
print(samples[:10])
t0 = time.time()
to_keep = []
for point in samples:
if not collides(polygons, point):
to_keep.append(point)
time_taken = time.time() - t0
print("Time taken {0} seconds ...", time_taken)
print(len(to_keep))
|
b385be1d7263a98675cc78190b4ca1b74ae322a4 | bbiiggppiigg/basicml | /hw1/code/vector.py | 1,403 | 3.671875 | 4 | #!/usr/bin/python
class vector:
def __init__(self,n):
self.value = [0]*n
def set_value_by_vector(self,v):
if(v.length() != self.length() ):
print "Error"
return -1;
for i in range(v.length()):
self.value[i]=v.value[i]
#print (self.value,self.length);
def set_value_by_list(self,v):
if(len(v)!=self.length()):
return -1
for i in range(len(v)):
self.value[i] = v[i]
#print (self.value,self.length);
def output(self):
print (self.value)
def add(self,v):
if(v.length()!= self.length()):
return -1;
ret = vector(v.length())
for i in range(v.length()):
ret.value[i]= v.value[i] + self.value[i]
return ret
def inner_product(self,v):
if(self.length() != v.length()):
return -1;
ret =0 ;
for i in range(v.length()):
ret = ret + v.value[i]*self.value[i]
return ret
def length(self):
return len(self.value)
def extend_vector_by_constant(self,constant):
ret = vector(self.length()+1)
value_list = list()
value_list.append(constant)
ret.set_value_by_list(value_list+self.value)
return ret
def scale(self,scalar):
ret = vector(self.length())
for t in range(self.length()):
ret.value[t] = self.value[t]*scalar
return ret
def test():
v = vector(3)
v.set_value_by_list([1,2,3])
v2 = vector(3)
v2.set_value_by_vector(v)
v.output()
v2.output()
v3 = v.add(v2)
v3.output()
inp = v3.inner_product(v2)
print inp
#test() |
483e55d99cef39b301fd288a1574c6797841ee50 | jinliangXX/LeetCode | /27. Remove Element(移除元素)/solution.py | 828 | 3.59375 | 4 | from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
if not nums:
return 0
left, right = 0, len(nums) - 1
while left <= right:
if nums[left] == val:
is_true = False
while right > left:
if nums[right] != val:
nums[left], nums[right] = nums[right], nums[left]
right -= 1
left += 1
is_true = True
break
right -= 1
if not is_true:
return left
else:
left += 1
return left
if __name__ == '__main__':
so = Solution()
re = so.removeElement([1], 1)
print(re)
|
c01e19399cc294ef21fa48add227a9f976ae67ae | jinliangXX/LeetCode | /59. Spiral Matrix II(螺旋矩阵 II)/solution.py | 851 | 3.5625 | 4 | from typing import List
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
if n <= 0:
return list()
result = [[0 for _ in range(n)] for _ in range(n)]
i, j = 0, 0
turns = ((0, 1), (1, 0), (0, -1), (-1, 0))
turn = 0
for k in range(1, n ** 2 + 1):
result[i][j] = k
if n - 1 < i + turns[turn][0] or i + turns[turn][0] < 0 or j + turns[turn][
1] < 0 or j + turns[turn][1] > n - 1 or result[i + turns[turn][0]][
j + turns[turn][1]] != 0:
if turn == 3:
turn = 0
else:
turn += 1
i += turns[turn][0]
j += turns[turn][1]
return result
if __name__ == '__main__':
so = Solution()
print(so.generateMatrix(3))
|
63e8f13a4abdd89ce94e29b10ace4165d3ddd0ac | jinliangXX/LeetCode | /655. Print Binary Tree(输出二叉树)/solution.py | 837 | 3.828125 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def printTree(self, root: TreeNode) -> List[List[str]]:
def get_deep(node: TreeNode):
if not node:
return 0
return 1 + max(get_deep(node.left), get_deep(node.right))
deep = get_deep(root)
result = [['' for _ in range(2 ** deep - 1)] for _ in range(deep)]
def fill(node: TreeNode, i=0, l=0, r=2 ** deep - 1 - 1):
if not node:
return
j = (l + r) // 2
result[i][j] = str(node.val)
fill(node.left, i + 1, l, j - 1)
fill(node.right, i + 1, j + 1, r)
fill(root)
return result
|
94555b4909e244e1e8e9e23bb97ad48b81308118 | jinliangXX/LeetCode | /380. Insert Delete GetRandom O(1)/solution.py | 1,462 | 4.1875 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.result = list()
self.index = dict()
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.index:
return False
else:
self.result.append(val)
self.index[val] = len(self.result) - 1
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.index:
index = self.index[val]
last_val = self.result[len(self.result) - 1]
self.result[index] = last_val
self.index[last_val] = index
self.result.pop()
self.index.pop(val,0)
return True
else:
return False
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return self.result[random.randint(0, len(self.result) - 1)]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
|
af9bee822dff5d0926796378cf9915b611fd1aa6 | jinliangXX/LeetCode | /445. Add Two Numbers II/solution.py | 1,084 | 3.734375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
stack_l1 = list()
stack_l2 = list()
while l1 or l2:
if l1:
stack_l1.append(l1.val)
l1 = l1.next
if l2:
stack_l2.append(l2.val)
l2 = l2.next
num_next = 0
root_next = None
while len(stack_l1) > 0 or len(
stack_l2) > 0 or num_next != 0:
num_l1 = 0
num_l2 = 0
if len(stack_l1) > 0:
num_l1 = stack_l1.pop()
if len(stack_l2) > 0:
num_l2 = stack_l2.pop()
num = num_l1 + num_l2 + num_next
listnode = ListNode(num % 10)
listnode.next = root_next
root_next = listnode
num_next = int(num / 10)
return root_next
|
cb51a81e4c0632bb2b3a744a0d81dcdf22221aa1 | jinliangXX/LeetCode | /508. Most Frequent Subtree Sum(出现次数最多的子树元素和)/solution.py | 1,375 | 3.671875 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
if not root:
return list()
self.result = dict()
self.max_number = 0
def get_sum(node: TreeNode):
if not node:
return 0
left_sum = get_sum(node.left)
right_sum = get_sum(node.right)
if node.left:
self.result[left_sum] = self.result.get(left_sum, 0) + 1
self.max_number = max(self.max_number, self.result[left_sum])
if node.right:
self.result[right_sum] = self.result.get(right_sum, 0) + 1
self.max_number = max(self.max_number, self.result[right_sum])
return node.val + left_sum + right_sum
root_sum = get_sum(root)
self.result[root_sum] = self.result.get(root_sum, 0) + 1
self.max_number = max(self.max_number, self.result[root_sum])
return [index for index in self.result if self.result[index] == self.max_number]
if __name__ == '__main__':
so = Solution()
root = TreeNode(5)
root.left = TreeNode(2)
root.right = TreeNode(-3)
print(so.findFrequentTreeSum(root))
|
2ff1f2032f65bb0a23a44c71cce2ae6149237466 | jinliangXX/LeetCode | /654. Maximum Binary Tree(最大二叉树)/solution.py | 706 | 3.890625 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if not nums:
return None
max_num = max(nums)
max_index = nums.index(max_num)
node = TreeNode(max_num)
node.left = self.constructMaximumBinaryTree(nums[:max_index])
node.right = self.constructMaximumBinaryTree(nums[max_index + 1:])
return node
if __name__ == '__main__':
so = Solution()
input = [3, 2, 1, 6, 0, 5]
print(so.constructMaximumBinaryTree(input))
|
ead2a7fd5b119248dde16b690afaafab388ecb49 | jinliangXX/LeetCode | /166. Fraction to Recurring Decimal/solution.py | 1,222 | 3.6875 | 4 | class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
first = 1
if numerator < 0:
numerator = -numerator
first = -first
if denominator < 0:
denominator = -denominator
first = -first
result_one = int(numerator / denominator)
result_two = ''
num = numerator % denominator
if num == 0:
return str(first * result_one)
nums = list()
while num != 0:
nums.append(num)
num *= 10
now = int(num / denominator)
num = num % denominator
result_two += str(now)
if num in nums:
result_two = result_two[
:nums.index(num)] + '(' + str(
result_two[nums.index(num):]) + ')'
break
if first == -1:
result = '-' + str(
result_one) + '.' + result_two
else:
result = str(result_one) + '.' + result_two
return result
if __name__ == '__main__':
print(4 / 333)
|
4546f14c41c87e28bb3bf7e8a5ec3036b3460b09 | jinliangXX/LeetCode | /124. Binary Tree Maximum Path Sum(二叉树中的最大路径和)/solution.py | 1,169 | 3.8125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.result = int(-100)
def get_result(node: TreeNode) -> int:
if not node:
return int(-100)
left_sum = get_result(node.left)
right_sum = get_result(node.right)
node_result = max(node.val, left_sum + node.val, right_sum + node.val)
not_node_result = max(left_sum, right_sum, left_sum + node.val + right_sum)
if not_node_result >= node_result:
self.result = max(self.result, not_node_result)
return node_result
now = get_result(root)
self.result = max(self.result, now)
return self.result
if __name__ == '__main__':
so = Solution()
root = TreeNode(1)
root.left = TreeNode(-2)
root.right = TreeNode(-3)
root.right.left = TreeNode(-2)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.left.left.left = TreeNode(-1)
print(so.maxPathSum(root))
|
663fc3868cc9a9a56f07b979a55fabd72892f88c | jinliangXX/LeetCode | /5. Longest Palindromic Substring/solution.py | 607 | 3.5 | 4 | class Solution:
def longestPalindrome(self, s: str) -> str:
result = ''
method = [[0, 1], [1, 0], [1, 1]]
for i, char in enumerate(s):
for met in method:
left, right = i - met[0], i + met[1]
while left >= 0 and right < len(s) and s[
left] == s[right]:
left -= 1
right += 1
if right - left - 1 > len(result):
result = s[left + 1:right]
return result
if __name__ == '__main__':
so = Solution()
so.longestPalindrome('cbbd')
|
6745bddaba6f219dd408eaf1bde0b31bc1382fea | jinliangXX/LeetCode | /409. Longest Palindrome(最长回文串)/solution.py | 541 | 3.65625 | 4 | import collections
class Solution:
def longestPalindrome(self, s: str) -> int:
a_dict = collections.Counter(s)
result = 0
is_odd_number = False
for char in a_dict:
if a_dict[char] % 2 == 0:
result += a_dict[char]
else:
is_odd_number = True
result += a_dict[char] // 2 * 2
result += 1 if is_odd_number else 0
return result
if __name__ == '__main__':
so = Solution()
print(so.longestPalindrome("abccccdd"))
|
49f34fc8099a75e31180597c8af51e29a05fce81 | jinliangXX/LeetCode | /70. Climbing Stairs/solution.py | 576 | 3.796875 | 4 | class Solution:
def climbStairs(self, n: int) -> int:
last_two = 1
last_one = 2
if n < 3:
return n
for i in range(n + 1):
if i < 3:
continue
num = last_two + last_one
last_two = last_one
last_one = num
return num
def cal_num(self, n):
if n == 1 or n == 2 or n == 3:
return n
else:
return self.cal_num(n - 1) + self.cal_num(n - 2)
if __name__ == '__main__':
sol = Solution()
print(sol.climbStairs(44))
|
8ba913b7250f65e2e11701f7216ba7704d3ba513 | jinliangXX/LeetCode | /面试题 01.06. 字符串压缩/solution.py | 439 | 3.671875 | 4 | class Solution:
def compressString(self, S: str) -> str:
left, right = 0, 0
result = ''
while right < len(S):
while right < len(S) and S[right] == S[left]:
right += 1
result += S[left] + str(right - left)
left = right
return result if len(result) < len(S) else S
if __name__ == '__main__':
so = Solution()
print(so.compressString("abbccd"))
|
7f1deca0b2a2fdfb6126895717e120bdfbb33d91 | jinliangXX/LeetCode | /44. Wildcard Matching(通配符匹配)/solution.py | 777 | 3.578125 | 4 | class Solution:
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
result = [[False for _ in range(n + 1)] for _ in range(m + 1)]
result[0][0] = True
for i in range(1, n + 1):
if p[i-1] == '*':
result[0][i] = result[0][i - 1]
else:
result[0][i] = False
for i in range(1, m + 1):
for j in range(1, n + 1):
if s[i - 1] == p[j - 1] or p[j - 1] == '?':
result[i][j] = result[i - 1][j - 1]
if p[j - 1] == '*':
result[i][j] = result[i][j - 1] or result[i - 1][j]
return result[m][n]
if __name__ == '__main__':
so = Solution()
re = so.isMatch("aa", "*")
print(re)
|
6387bd99d374b9dd5e10b02777622f15c810b8f4 | jinliangXX/LeetCode | /103. Binary Tree Zigzag Level Order Traversal/solution.py | 935 | 3.65625 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[
List[int]]:
self.result = list()
result = self.get_cal(root, 0)
for i, list_now in enumerate(self.result):
if i % 2 == 1:
list_now = list_now[::-1]
return self.result
def get_cal(self, root, index):
if root is None:
return
if len(self.result) <= index:
new_list = list()
self.result.append(new_list)
self.result[index].append(root.val)
now = index + 1
self.get_cal(root.left, now)
self.get_cal(root.right, now)
if __name__ == '__main__':
a = [2, 3, 4, 5, 6, 7, 8, 9]
for now in a:
now = now + 1
print(a)
|
cc8fcc5f18b08502b4035a9ecc72711413c96614 | jinliangXX/LeetCode | /530. Minimum Absolute Difference in BST(二叉搜索树的最小绝对差)/solution.py | 874 | 3.671875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
self.result = None
self.last = None
if not root:
return self.result
def get_result(node: TreeNode):
if not node:
return
get_result(node.left)
if self.last is None:
self.last = node.val
else:
now = abs(self.last - node.val)
if self.result is None:
self.result = now
else:
self.result = min(now, self.result)
self.last = node.val
get_result(node.right)
get_result(root)
return self.result
|
42db1c7acd7d615fdd39d56ab45f5f05f7f1f3bb | jinliangXX/LeetCode | /814. Binary Tree Pruning(二叉树剪枝)/solution.py | 611 | 3.78125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
left_result = self.pruneTree(root.left)
right_result = self.pruneTree(root.right)
if not left_result:
root.left = None
if not right_result:
root.right = None
if not left_result and not right_result and root.val == 0:
return None
else:
return root
|
8bb1692cb6deaaea9046fe892f7014f7d48daf46 | jinliangXX/LeetCode | /872. Leaf-Similar Trees(叶子相似的树)/solution.py | 683 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
def get_result(node: TreeNode, result):
if not node:
return
if not node.left and not node.right:
result.append(node.val)
else:
get_result(node.left, result)
get_result(node.right, result)
result1, result2 = list(), list()
get_result(root1, result1)
get_result(root2, result2)
return result1 == result2
|
4ebb0881083611f711b8ac1fe710f47ae6a070cf | jinliangXX/LeetCode | /297. Serialize and Deserialize Binary Tree(二叉树的序列化与反序列化)/solution.py | 2,470 | 3.796875 | 4 | # Definition for a binary tree node.
import json
from queue import Queue
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
result = list()
if not root:
return str(result)
queue = Queue()
queue.put(root)
while not queue.empty():
lenght = queue.qsize()
is_null = False
for _ in range(lenght):
now = queue.get()
result.append(now.val) if now else result.append(now)
if now:
if now.left or now.right:
is_null = True
queue.put(now.left)
queue.put(now.right)
if not is_null:
break
return json.dumps(result)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
result = json.loads(data)
if not result:
return None
queue = Queue()
root = None
index = 0
while index < len(result):
if queue.empty():
root = TreeNode(result[index])
queue.put(root)
index += 1
continue
lenght = queue.qsize()
for _ in range(lenght):
node = queue.get()
if not node:
continue
if index + 1 >= len(result):
return root
node.left = TreeNode(result[index]) if result[index] is not None else None
node.right = TreeNode(result[index + 1]) if result[
index + 1] is not None else None
index += 2
queue.put(node.left)
queue.put(node.right)
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)
codec = Codec()
a = codec.deserialize(codec.serialize(root))
print(a)
|
55d1e60b44b18fdffc5ddce1516f5bf533be7e89 | smruti-10/zelthy | /assignment_3/wifi_networks.py | 482 | 3.6875 | 4 | class Wifi():
def __init__(self):
self.wifi_networks = [">[1] Wifi_network 1",">[2] Wifi_network 2",">[3] Wifi_network 3"]
print("> Your available wifi networks are:")
for i in self.wifi_networks:
print(i)
self.wifi_choice = input("Your choice?")
if self.wifi_choice:
self.passw = input("Password:")
if self.passw:
print("Connected!")
if __name__ == "__main__":
x = Wifi()
|
c33b8d86a0050189b9c31c284c75d1c4a08014e8 | codymlewis/perceptron | /Perceptron.py | 7,225 | 3.734375 | 4 | #!/usr/bin/env python3
import argparse
import numpy as np
import pandas as pd
'''
An implementation of a multi-layer perceptron.
Author: Cody Lewis
Date: 2019-09-21
'''
class Neuron:
'''A neuron of the perceptron'''
def __init__(self, input_layer=False):
self.activation_strength = 0
self.connections = []
self.is_input_layer = input_layer
def connect(self, other):
'''Connect a neuron to this'''
self.connections.append(Connection(self, other))
def input(self, value):
'''Input a value into this neuron'''
self.activation_strength = value
def output(self):
'''Recieve a final output from this neuron with softmax activation'''
val = np.exp(self.activation_strength)
self.activation_strength = 0
return val
def mutate(self, step_size):
'''Mutate the weights of the connections on this neuron'''
for connection in self.connections:
connection.mutate_weight(step_size)
def revert(self):
'''Reset the weights of the connections on this neuron'''
for connection in self.connections:
connection.revert_weight()
def activate(self):
'''Activate this neuron'''
for connection in self.connections:
if self.is_input_layer:
connection.activate(self.activation_strength)
else:
connection.activate(activate(self.activation_strength))
self.activation_strength = 0
def activated(self, value):
'''Get activated with the value'''
self.activation_strength += value
class Connection:
'''A connection between 2 neurons'''
def __init__(self, from_node, to_node):
self.from_node = from_node
self.to_node = to_node
self.weight = np.random.normal()
self.cached_weight = 0
def activate(self, value):
'''Activate the neuron that this connects to with the value'''
self.to_node.activated(value * self.weight)
def mutate_weight(self, step_size):
'''Mutate the weight of this'''
self.cached_weight = self.weight
self.weight += step_size * np.random.normal()
def revert_weight(self):
'''Reset the weight mutation'''
self.weight = self.cached_weight
class Perceptron:
'''A multi layer perceptron implementation'''
def __init__(self, structure):
self.layers = [
[Neuron(i == 0) for _ in range(layer_size)]
for i, layer_size in enumerate(structure)
]
for i in range(len(self.layers) - 1):
for neuron in self.layers[i]:
for next_neuron in self.layers[i + 1]:
neuron.connect(next_neuron)
def summary(self):
print(f"{'-' * 5} [Perceptron Summary] {'-' * 5}")
num_layers = len(self.layers)
for i, layer in enumerate(self.layers):
if i == 0:
layer_type = "Input Layer"
elif i == num_layers - 1:
layer_type = "Output Layer"
else:
layer_type = f"Hidden Layer {i}"
print(f"{layer_type}:\t{len(layer)}")
print("-" * 32)
def predict(self, inputs):
'''Predict a value given the inputs'''
for i, inp in enumerate(inputs):
self.layers[0][i + 1].input(inp)
# Set up bias
self.layers[0][0].input(1)
for layer in self.layers[:-1]:
for neuron in layer:
neuron.activate()
outputs = []
for neuron in self.layers[-1]:
outputs.append(neuron.output())
denominator = np.sum(outputs)
activations = []
for output in outputs:
activations.append(output / denominator)
return activations
def classify(self, inputs):
'''
Find the classification given a prediction for the prediction of the
inputs
'''
return np.argmax(self.predict(inputs))
def learn(self, error_goal, inputs, target_responses, verbose=False):
'''Learn the weights for the network using evolutionary hill descent'''
counter = 0
n_epochs = 10_000
error_champ = find_error(inputs, target_responses, self)
errors = [error_champ]
while(error_goal < error_champ) and (counter < n_epochs):
if verbose:
print(f"\rEpoch {counter + 1}, error: {error_champ}", end="")
step_size = 0.02 * np.random.normal()
for layer in self.layers[:-1]:
for neuron in layer:
neuron.mutate(step_size)
error_mutant = find_error(inputs, target_responses, self)
if error_mutant < error_champ:
error_champ = error_mutant
else:
for layer in self.layers[:-1]:
for neuron in layer:
neuron.revert()
counter += 1
errors.append(error_champ)
if verbose:
print()
return error_champ, errors
def activate(x_value, coefficient=1, constant=0):
'''
Perform the sigmoid function to determine whether a neuron is activated.
'''
return 1 / (1 + np.exp(-coefficient * x_value - constant))
def find_error(inputs, target_responses, perceptron):
'''
Find the error of the perceptron.
'''
error = 0
for i, target_response in zip(inputs, target_responses):
predictions = perceptron.predict(i)
error += log_loss(1, predictions[target_response])
return -error / len(inputs)
def log_loss(label, prediction, eps=1e-15):
'''Find the log loss'''
# clip performs a minmax
np.clip(prediction, eps, 1 - eps)
return label * np.log2(prediction)
def eval_predictions(model, data, labels):
'''Evaluate the accuracy of predictions on the data made by the model'''
print("Input data\tPrediction\tTrue Label")
accuracy = 0
for row, label in zip(data, labels):
prediction = model.classify(row)
print(f"{row}\t\t{prediction}\t\t{label}")
accuracy += prediction == label
print(f"Accuracy: {100 * accuracy / len(labels)}%")
print()
if __name__ == "__main__":
PARSER = argparse.ArgumentParser(description="A multi-layer perceptron")
PARSER.add_argument("-f", "--file", dest="file", type=str, action="store",
default="XOR2.csv",
help="csv file cotaining the training data and labels")
PARSER.add_argument("-l", "--layers", dest="layers", type=int,
action="store", default=[4], nargs="+",
help="Number of neurons in the hidden layers")
ARGS = PARSER.parse_args()
DF = pd.read_csv(ARGS.file, header=None)
DATA = DF[DF.columns[:-1]].to_numpy()
LABELS = DF[DF.columns[-1]].to_numpy()
MODEL = Perceptron(
[np.shape(DATA)[1] + 1] + ARGS.layers + [len(np.unique(LABELS))]
)
print(f"Constructed Perceptron:")
MODEL.summary()
print()
eval_predictions(MODEL, DATA, LABELS)
MODEL.learn(0.01, DATA, LABELS, True)
print()
eval_predictions(MODEL, DATA, LABELS)
|
fe09cf57664dc6a49600db1481f9fb0024d9d88b | z1908144712/leetcode | /48/main.py | 637 | 3.734375 | 4 | from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(0,n-1):
for j in range(i+1,n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
i, j = 0, n-1
while i < j:
for k in range(n):
matrix[k][i], matrix[k][j] = matrix[k][j], matrix[k][i]
i += 1
j -= 1
return
if __name__ == "__main__":
s = Solution()
matrix = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
s.rotate(matrix)
print(matrix) |
5ea0cc442e77167a80c56151628227d91d4b0889 | sathvik-85/Pong-game | /pong.py | 2,065 | 3.53125 | 4 | # Importing the library
import pygame,random, time
# Initializing Pygame
pygame.init()
#Window size
WIDTH,HEIGHT = 700,800
# Initializing surface
win = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Pong")
# Initialing RED
RED = (255,0,0)
BLUE_LIGHT = (52, 232, 235)
WHITE = (255,255,255)
run = True
x1=100
x2 = 700
y1 =350
y2 = 350
x3 =400
y3 = 400
player_score = 0
opponent_score = 0
clock = pygame.time.Clock()
player = pygame.Rect(50,250,10,100 )
opponent = pygame.Rect(650,250,10,100)
ball = pygame.Rect(290,310,20,20)
line = pygame.Rect(0,700,700,5)
myfont = pygame.font.SysFont('Times New Roman', 30)
ball_speed_x = 2 * random.choice((1,-1))
ball_speed_y = 2 * random.choice((1,-1))
def ball_restart():
time.sleep(1)
ball.center =(400,400)
ball_speed_x = random.choice((1,-1))
ball_speed_y = random.choice((1,-1))
while run:
key = pygame.key.get_pressed()
#spped of ball
ball.x += ball_speed_x
ball.y += ball_speed_y
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if key[pygame.K_DOWN] and player.y + 100< 680:
player.y += 8
if key[pygame.K_UP] and player.y >10:
player.y -= 8
if key[pygame.K_s] and opponent.y +100 < 680:
opponent.y += 8
if key[pygame.K_w] and opponent.y>10 :
opponent.y -= 8
if ball.top <=0 or ball.bottom >= 700:
ball_speed_y *= -1
if ball.left <=0 or ball.right >= 700:
if ball.left <=0:
opponent_score += 1
if ball.right>=700:
player_score += 1
ball_restart()
if ball.colliderect(player) or ball.colliderect(opponent):
ball_speed_x *= -1
if ball.left<= 0 or ball.right>= 800:
pygame.Rect(410,400,20,20)
win.fill(1)
pygame.draw.rect(win,RED,player)
pygame.draw.rect(win,RED,opponent)
pygame.draw.rect(win,BLUE_LIGHT,ball)
pygame.draw.rect(win,WHITE,line)
textsurface = myfont.render(f" Player_A: {player_score} Player_B: {opponent_score}" , False, (255, 255, 255))
win.blit(textsurface,(0,715))
pygame.display.flip()
clock.tick(60)
pygame.quit() |
3e53d2ad752183297b106c314c893fcf9078c65e | macord1/LazorProject | /Lazor.py | 25,648 | 3.546875 | 4 | from itertools import permutations
from itertools import combinations
import copy
import numpy as np
'''
SOFTWARE CARPENTRY LAZOR PROJECT
Molly Accord
Sreelakshmi Sunil
'''
'''
Computes solutions from bff file of lazor game.
Solutions are saves as a text file - solution.txt
Separate unit_tests.py file is used for performing tests.
'''
# Assuming the following numbers for positions of a block
# possible paths, block allowed - 0
# no block allowed - 1
# laser starting points - 10
# laser path - 11
# Points we need tha laser to intersect - 20
# Reflect block - 30
# Opaque block - 40
# Refract block - 50
# Fixed reflect block - 31
# Fixed opaque block - 41
# Fixed refract block - 51
class Block:
'''
Performs block operations such as reading bff files and saving the solution
'''
def __init__(self, File):
'''
Stores the name of bff file to file_name
***Parameters***
File: the passed bff files from the main loop
***Returns***
none
'''
self.file_name = File
def Read_file(self):
'''
Reads the bff file, converts the grid to a matrix and stores concerned values to variables
***Parameters***
File: the passed bff files from the main loop
***Returns***
grid_matrix : converted board to matrix
A (list): count of movable reflect blocks
B (list): count of movable opaque blocks
C (list): count of movable refract blocks
L (tupule): coordinates of laser starting points and vx,vy explaining direction of laser
P (tupule) : coordinates of points that laser must intersect
'''
GRID = []
A = 0
B = 0
C = 0
L = []
P = []
# openining the game bff file to read and store
bff = open(self.file_name, "r")
# reading all lines
lines = bff.readlines()
total_lines = len(lines)
# converting grid to a matrix
for i in range(total_lines):
separated = lines[i].strip('\n')
# starts at 'START' and ends at 'STOP'
if separated == "GRID START":
next_line = i + 1
selected = lines[next_line].strip('\n')
while selected != "GRID STOP":
row = selected.replace(" ", "")
GRID.append(row)
next_line = next_line + 1
selected = lines[next_line].strip('\n')
# storing values of A, B, C as lists
for i in range(next_line + 1, total_lines):
separated = lines[i].strip('\n')
try:
if separated[0] == "A":
A = int(separated[2])
elif separated[0] == "B":
B = int(separated[2])
elif separated[0] == "C":
C = int(separated[2])
elif separated[0] == "L":
if separated[6] == "-" and separated[9] == "-":
L_row = (int(separated[2]), int(separated[4]),
-1 * int(separated[7]), -1 * int(separated[10]))
elif separated[6] == "-" and separated[9] != "-":
L_row = (int(separated[2]), int(separated[4]),
-1 * int(separated[7]), int(separated[9]))
elif separated[6] != "-" and separated[8] == "-":
L_row = (int(separated[2]), int(separated[4]),
int(separated[6]), -1 * int(separated[9]))
else:
L_row = (int(separated[2]), int(separated[4]),
int(separated[6]), int(separated[8]))
L.append(L_row)
elif separated[0] == "P":
P_row = (int(separated[2]), int(separated[4]))
P.append(P_row)
except IndexError:
continue
width = 2 * len(GRID[0]) + 1
height = 2 * len(GRID) + 1
# intializing grid matrix as all zeros
grid_matrix = np.zeros((height, width), dtype=int)
for j in range(len(GRID)):
for i in range(len(GRID[0])):
if GRID[j][i] != "o":
value = GRID[j][i]
new_j = j * 2 + 1
new_i = i * 2 + 1
# Updating positions of centroids of fixed reflect, refract
# and opaque blocks as 31,51 and 41.
if value == "A":
grid_matrix[new_j][new_i] = 31 # 30 represents A block
elif value == "B":
grid_matrix[new_j][new_i] = 41 # 40 represents B block
elif value == "C":
grid_matrix[new_j][new_i] = 51 # 50 represents C block
elif value == "x":
grid_matrix[new_j][new_i] = 1 # 1 represents x block
else:
continue
return(grid_matrix, A, B, C, L, P)
class Laser:
'''
Stores grid_matrix and performs various laser functions
'''
def __init__(self, Matrix):
'''
Stores the name of bff file to file_name
***Parameters***
Matrix: the passed grid_matrix
***Returns***
none
'''
self.grid_matrix = Matrix
self.size1 = len(self.grid_matrix[0])
self.size2 = len(self.grid_matrix)
def valid_pos(self, x, y):
'''
Returns True if the coordinates specified (x and y) are within the matrix.
taken from maze generation hw for software carpentry
**Parameters**
x: *int*
An x coordinate to check if it resides within the matrix.
y: *int*
A y coordinate to check if it resides within the matrix.
size: *int*
length of the matrix (ie. len(matrix)).
**Returns**
possible_dir: *bool*
Whether the coordiantes are possible_dir (True) or not (False).
'''
return x >= 0 and x < self.size1 and y >= 0 and y < self.size2
def incident__side(self, y, x, val):
'''
Computes and returns the side of block where the laser hits
*** Parameters ***
y (int): y coordinate of current laser position
x (int): x coordinate of current laser position
val (int): assigned value for centroid according to the block
*** Returns ***
incident_side(string) : Right, Left , Up or Down
'''
if self.grid_matrix[y][x + 1] == val:
return 'left'
elif self.grid_matrix[y][x - 1] == val:
return 'right'
elif self.grid_matrix[y - 1][x] == val:
return 'down'
elif self.grid_matrix[y + 1][x] == val:
return 'up'
else:
pass
def reflect(self, side, vx, vy):
'''
Alters vx, vy from L for reflection
*** Parameters***
side(string) : side of block where the laser hits
vx (int) : direction x coordinate of laser
vy (int) : direction y coordinate of laser
*** Returns ***
vx (int) : updated direction x coordinate of laser
vy (int) : updated direction y coordinate of laser
'''
if side == 'left' or side == 'right':
# only vy inverts , vx remains same in (vy,vx)
vx = vx * -1
elif side == 'up' or side == 'down':
# only vy inverts , vx remains same in (vy,vx)
vy = vy * -1
else:
pass
return(vx, vy)
def intial_values(self, vx, vy, temp_x, temp_y):
'''
Calculates the next cell using vx,vy
*** Parameters ***
vx (int) : direction x coordinate of laser
vy (int) : direction y coordinate of laser
temp_y (int): y coordinate of current laser position
temp_x (int): x coordinate of current laser position
*** Returns ***
temp_y (int): updated y coordinate of (next) laser position
temp_x (int): updated x coordinate of (next) laser position
'''
# (vx,vy)
# (1, -1) - right up
# (1, 1) - right down
# (-1, 1) - left down
# (-1, -1) - left up
if (vx, vy) == (1, -1):
temp_x = temp_x + 1
temp_y = temp_y - 1
elif (vx, vy) == (1, 1):
temp_x = temp_x + 1
temp_y = temp_y + 1
elif (vx, vy) == (-1, 1):
temp_x = temp_x - 1
temp_y = temp_y + 1
elif (vx, vy) == (-1, -1):
temp_x = temp_x - 1
temp_y = temp_y - 1
else:
print("invalid vx vy")
return(temp_x, temp_y)
def check_allhit(self, P):
'''
Checks if all points that the laser must intersect are intersected
*** Parameters ***
P (tupule) : coordinates of points that laser must intersect
*** Returns ***
True : if all points that the laser must intersect are intersected
False : if all points that the laser must intersect are not intersected
'''
for i in range(0, len(P)):
temp_P = P[i]
xx = temp_P[0]
yy = temp_P[1]
if self.grid_matrix[yy][xx] != 11:
return False
else:
continue
return True
def block_change(matrix_copy, A, B, C):
'''
Computes all possible positions for movable blocks using
permutation and combination
*** Parameters ***
matrix_copy : grid_matrix intially read from the bff file
A (list): count of movable reflect blocks
B (list): count of movable opaque blocks
C (list): count of movable refract blocks
***Returns***
movBlocks_count (int) : total number of movable blocks
centroid_comb (list of lists) : all possible movBlocks_count centroid combinations
blocks_perm (list of lists) : all posible orders of movable blocks
'''
centroids_avail = []
# storing coordinates of all possible centroids
for i in range(1, len(matrix_copy) - 1, 2):
for j in range(1, len(matrix_copy[0]) - 1, 2):
# checks if any of the centroids are blocks
if matrix_copy[i][j] == 0:
centroids_avail.append([i, j])
else:
continue
# total no. of movable blocks
movBlocks_count = A + B + C
# possible combinations for available centroids
centroid_comb = combinations(centroids_avail, movBlocks_count)
blocks_list = []
i = 0
j = 0
k = 0
# inserting 30 as many times as A
for i in range(0, A):
blocks_list.append(30)
# inserting 40 as many times as B
for j in range(0, B):
blocks_list.append(40)
# inserting 50 as many times as C
for k in range(0, C):
blocks_list.append(50)
# all possible arragements for movable blocks
blocks_comb = permutations(blocks_list, movBlocks_count)
a = []
for i in list(blocks_comb):
a.append(i)
blocks_perm = []
# to avoid repeated tupules in permutations
for i in a:
if i not in blocks_perm:
blocks_perm.append(i)
return(centroid_comb, blocks_perm, movBlocks_count)
def make_cross(grid_matrix):
'''
To make a cross shape for the blocks
*** Parameters ***
grid_matrix : converted board to matrix
*** Returns ***
None
'''
# To make cross
for i in range(1, len(grid_matrix) - 1, 2):
for j in range(1, len(grid_matrix[0]) - 1, 2):
# checks if any of the centroids are blocks
if grid_matrix[i][j] in {30, 31, 40, 41, 50, 51}:
if grid_matrix[i][j - 1] in {0, 10, 20}:
grid_matrix[i][j - 1] = grid_matrix[i][j]
if grid_matrix[i][j + 1] in {0, 10, 20}:
grid_matrix[i][j + 1] = grid_matrix[i][j]
if grid_matrix[i - 1][j] in {0, 10, 20}:
grid_matrix[i - 1][j] = grid_matrix[i][j]
if grid_matrix[i + 1][j] in {0, 10, 20}:
grid_matrix[i + 1][j] = grid_matrix[i][j]
else:
continue
# To set common walls as refract
for i in range(1, len(grid_matrix) - 1, 2):
for j in range(1, len(grid_matrix[0]) - 1, 2):
# checks if any of the centroids are blocks
if grid_matrix[i][j] in {30, 31, 40, 41, 50, 51}:
if grid_matrix[i][j - 1] != grid_matrix[i][j] and grid_matrix[i][j - 1] not in {10, 20}:
grid_matrix[i][j - 1] = 50
if grid_matrix[i][j + 1] != grid_matrix[i][j] and grid_matrix[i][j + 1] not in {10, 20}:
grid_matrix[i][j + 1] = 50
if grid_matrix[i - 1][j] != grid_matrix[i][j] and grid_matrix[i - 1][j] not in {10, 20}:
grid_matrix[i - 1][j] = 50
if grid_matrix[i + 1][j] != grid_matrix[i][j] and grid_matrix[i + 1][j] not in {10, 20}:
grid_matrix[i + 1][j] = 50
else:
continue
def laser_path(temp_y, temp_x, vx, vy, grid_matrix):
'''
Determines the path of a laser
Depends on starting points of laser, reflective,
refractive and opaque blocks.
*** Parameters***
vx (int) : direction x coordinate of laser
vy (int) : direction y coordinate of laser
temp_y (int): y coordinate of current laser position
temp_x (int): x coordinate of current laser position
grid_matrix : converted board to matrix
*** Returns ***
None
'''
# vx1, vy1, temp_x1, temp_y1 used only in case of refract blocks
vx1 = 0
vy1 = 0
Lazor = Laser(grid_matrix)
while True:
temp_x, temp_y = Lazor.intial_values(vx, vy, temp_x, temp_y)
if Lazor.valid_pos(temp_x, temp_y):
# check only if the coordinates are possible
if grid_matrix[temp_y][temp_x] in {0, 1, 10, 20}:
# to set the lazer path until there is a block
grid_matrix[temp_y][temp_x] = 11
elif grid_matrix[temp_y][temp_x] == 30 or grid_matrix[temp_y][temp_x] == 31:
# when there is a reflect block
Lazor = Laser(grid_matrix)
try:
side = Lazor.incident__side(
temp_y, temp_x, grid_matrix[temp_y][temp_x])
vx, vy = Lazor.reflect(side, vx, vy)
except IndexError:
continue
grid_matrix[temp_y][temp_x] = 11
elif grid_matrix[temp_y][temp_x] == 50 or grid_matrix[temp_y][temp_x] == 51:
# when there is a refract block
Lazor = Laser(grid_matrix)
try:
side = Lazor.incident__side(
temp_y, temp_x, grid_matrix[temp_y][temp_x])
# code to refract laser
temp_y1 = temp_y
temp_x1 = temp_x
vx1 = vx
vy1 = vy
while True:
temp_x1, temp_y1 = Lazor.intial_values(
vx1, vy1, temp_x1, temp_y1)
if Lazor.valid_pos(temp_x1, temp_y1):
# checks only if the coordinates are possible
if grid_matrix[temp_y1][temp_x1] in {0, 1, 10, 20}:
# to set the lazer path until there is a block
grid_matrix[temp_y1][temp_x1] = 11
else:
continue
# breaks out of loop if temp_x1, temp_y1 is out of matrix size range
else:
break
# calling reflect function
vx, vy = Lazor.reflect(side, vx, vy)
except IndexError:
continue
grid_matrix[temp_y][temp_x] = 11
elif grid_matrix[temp_y][temp_x] == 40 or grid_matrix[temp_y][temp_x] == 41:
# when there is an opaque block
grid_matrix[temp_y][temp_x] = 11
break
else:
continue
# breaks out of loop if temp_x1, temp_y1 is out of matrix size range
else:
break
def save_solution(grid_matrix):
'''
Coverts and saves the obtained solution as a text file
*** Parameters ***
grid_matrix (matrix): final solved matrix
solution (txt file) : text file with the solution for the bff file
*** Returns ***
None
'''
# to save solution into a text file
text_file = open("solution.txt", "w")
# deleting any previous content in the file
text_file.truncate(0)
# STORING THE POSITIONS OF MOVABLE BLOCKS IN ORGINAL BOARD
opaque_blocks = []
reflect_blocks = []
refract_blocks = []
for i in range(1, len(grid_matrix) - 1, 2):
for j in range(1, len(grid_matrix[0]) - 1, 2):
# checks if any of the centroids are movable blocks
if grid_matrix[i][j] == 30:
reflect_blocks.append([i, j])
elif grid_matrix[i][j] == 40:
opaque_blocks.append([i, j])
elif grid_matrix[i][j] == 50:
refract_blocks.append([i, j])
else:
continue
text_file.write("THE POSITIONS OF MOVABLE BLOCKS IN ORGINAL BOARD \n\n")
if len(reflect_blocks) != 0:
text_file.write("\nPosition of Movable Reflect Blocks on board: \n")
for i in reflect_blocks:
# storing positions of blocks in actual board
row = i[0] // 2 + 1
col = i[1] // 2 + 1
text_file.write("Position %d from left in row %d \n" % (col, row))
if len(refract_blocks) != 0:
text_file.write("\nPosition of Movable Refract Blocks on board: \n")
for i in refract_blocks:
# storing positions of blocks in actual board
row = i[0] // 2 + 1
col = i[1] // 2 + 1
text_file.write("Position %d from left in row %d \n" % (col, row))
if len(opaque_blocks) != 0:
text_file.write("\nPosition of Movable Opaque Blocks on board: \n")
for i in opaque_blocks:
# storing positions of blocks in actual board
row = i[0] // 2 + 1
col = i[1] // 2 + 1
text_file.write("Position %d from left in row %d \n" % (col, row))
# create empty arrays for all info needed in text file
open_blocks = []
unfixed_A_blocks = []
unfixed_B_blocks = []
unfixed_C_blocks = []
fixed_A_blocks = []
fixed_B_blocks = []
fixed_C_blocks = []
Laser_start = []
Laser_reach = []
path = []
# store value types in their respective array
for i in range(0, len(grid_matrix)):
for j in range(0, len(grid_matrix[0])):
if (i % 2) != 0 and (j % 2) != 0 and grid_matrix[i][j] == 0:
open_blocks.append((j, i))
elif (i % 2) != 0 and (j % 2) != 0 and grid_matrix[i][j] == 30:
unfixed_A_blocks.append((j, i))
elif (i % 2) != 0 and (j % 2) != 0 and grid_matrix[i][j] == 40:
unfixed_B_blocks.append((j, i))
elif (i % 2) != 0 and (j % 2) != 0 and grid_matrix[i][j] == 50:
unfixed_C_blocks.append((j, i))
elif (i % 2) != 0 and (j % 2) != 0 and grid_matrix[i][j] == 31:
fixed_A_blocks.append((j, i))
elif (i % 2) != 0 and (j % 2) != 0 and grid_matrix[i][j] == 41:
fixed_B_blocks.append((j, i))
elif (i % 2) != 0 and (j % 2) != 0 and grid_matrix[i][j] == 51:
fixed_C_blocks.append((j, i))
elif grid_matrix[i][j] == 10:
Laser_start.append((j, i))
elif grid_matrix[i][j] == 11:
path.append((j, i))
for k in range(0, len(P)):
temp_P = P[k]
if i == temp_P[1] and j == temp_P[0]:
Laser_reach.append((j, i))
# write text file
text_file.write("\n\n\nOTHER MISCELLANEOUS INFORMATION \n\n")
text_file.write("Open blocks at x,y positions: ")
text_file.write(str(open_blocks))
text_file.write("\n")
text_file.write("\n")
text_file.write("unfixed A blocks, or reflect blocks at x,y positions: ")
text_file.write(str(unfixed_A_blocks))
text_file.write("\n")
text_file.write("\n")
text_file.write("unfixed B blocks, or opaque blocks at x,y positions: ")
text_file.write(str(unfixed_B_blocks))
text_file.write("\n")
text_file.write("\n")
text_file.write("unfixed C blocks, or refract blocks at x,y positions: ")
text_file.write(str(unfixed_C_blocks))
text_file.write("\n")
text_file.write("\n")
text_file.write("fixed A blocks at x,y positions: ")
text_file.write(str(fixed_A_blocks))
text_file.write("\n")
text_file.write("\n")
text_file.write("fixed B blocks at x,y positions: ")
text_file.write(str(fixed_B_blocks))
text_file.write("\n")
text_file.write("\n")
text_file.write("fixed C blocks at x,y positions: ")
text_file.write(str(fixed_C_blocks))
text_file.write("\n")
text_file.write("\n")
text_file.write("Laser(s) start at x,y positions: ")
text_file.write(str(Laser_start))
text_file.write("\n")
text_file.write("\n")
text_file.write("Laser(s) passes through x,y positions: ")
text_file.write(str(path))
text_file.write("\n")
text_file.write("\n")
text_file.write("Laser(s) pass through desired at x,y positions: ")
text_file.write(str(Laser_reach))
text_file.write("\n")
text_file.write("\n")
text_file.close()
if __name__ == "__main__":
'''
Main Function
Repeatedly checks if the game can be solved by inputing all
possible combinations of movable blocks
'''
# to read bff file
block = Block("mad_1.bff")
grid_matrix, A, B, C, L, P = block.Read_file()
# inserting 20 for the points that we need the laser to intersect
for i in range(0, len(P)):
temp_P = P[i]
xx = temp_P[0]
yy = temp_P[1]
grid_matrix[yy][xx] = 20
# Updating the positions of laser start and the points.
# inserting 10 to laser start points in the matrix grid
for i in range(0, len(L)):
temp_L = L[i]
L_x = temp_L[0]
L_y = temp_L[1]
vxx = temp_L[2]
vyy = temp_L[3]
grid_matrix[L_y][L_x] = 10
matrix_copy = copy.deepcopy(grid_matrix)
print("Please wait")
# stores all possible combinations of movable blocks
centroid_comb, blocks_perm, movBlocks_count = block_change(
matrix_copy, A, B, C)
# setting flag = 0 to check for solution
f = 0
# taking centroid combinations
for i in list(centroid_comb):
# taking block combinations
for j in range(0, len(blocks_perm)):
grid_matrix = copy.deepcopy(matrix_copy)
for k in range(0, movBlocks_count):
# seting different block positions
x_temp = i[k][0]
y_temp = i[k][1]
grid_matrix[x_temp][y_temp] = blocks_perm[j][k]
# out of k loop
# coverting centroids to cross for laser_path
make_cross(grid_matrix)
# updating laser positions
for m in range(0, len(L)):
temp_L = L[m]
L_x = temp_L[0]
L_y = temp_L[1]
vxx = temp_L[2]
vyy = temp_L[3]
# testing laser path for new combination of blocks
laser_path(L_y, L_x, vxx, vyy, grid_matrix)
# calling Laser class
Lazor = Laser(grid_matrix)
# checking if all points are hit by laser
if Lazor.check_allhit(P):
f = 1
break
else:
continue
# checking if the game is solved
if f == 1:
print("Solved")
print("Look for the 'solutions' text file")
break
else:
continue
if f == 0:
print("\nError : Not solved")
save_solution(grid_matrix)
|
f7039a59a2634d081b488230a2824f55058989ef | rafaelgmenezes/Mapping_kml | /kml_to_df.py | 2,745 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 28 16:49:08 2020
@author: Rafael G. de Menezes
Oceanographer, Msc. Marine Biotechnology
Clube do Cientista
Biosustente Estudos Ambientais ltda.
Developed with Python 3.7.6
README:
Python function to transform google earth .kml files list into a pandas DataFrame
Necessary function for the 'Mapping_kml' code (https://github.com/rafaelgmenezes/Mapping_kml)
.kml files location:
folder in current working directory
or files directly in current working directory
dataFrame ouput content:
Filename -> the .kml filename
Lon -> meridians coordinate
Lat -> parallels coordinate
output options:
fmt = 'df' -> a DataFrame object (default)
fmt = 'csv' -> save DataFrame in a .csv file
fmt = 'both' -> both outputs options above
"""
def kml_to_df (fmt = 'df'): # fmt = output format
fmt_options = ['df', 'csv', 'both']
if fmt not in fmt_options:
print ("'fmt' options:")
[print (f) for f in fmt_options]
print ("default = 'df'")
raise NameError("fmt argument is not set properly")
import os
from glob import glob
path = os.getcwd()
if len (glob('*.kml')) == 0:
try:
os.chdir('kmlfiles')
except:
try:
os.chdir('kmlbase')
except FileNotFoundError:
raise FileNotFoundError ('kml files were not found')
from bs4 import BeautifulSoup
import pandas as pd
kml_list = glob('*.kml')
df = pd.DataFrame(columns = ['Filename', 'Lon', 'Lat'])
remove_chars = ['[',']','<','>','\n','\t','coordinates', '/']
for file in kml_list:
with open(file, 'r') as f:
soup = BeautifulSoup(f, features = "html.parser")
node = soup.select('coordinates')
coords = str(node)
for char in remove_chars:
coords = coords.replace(char,'')
dfi = {'Lon': [], 'Lat': []}
for j in list(coords[:-1].split(' ')):
c = j.split(',')
dfi['Lon'].append(float(c[0]))
dfi['Lat'].append(float(c[1]))
f.close()
dfi = pd.DataFrame(dfi)
dfi['Filename'] = file.split('.')[0]
df = pd.concat([df,dfi], axis = 0, sort = False)
df = df.reset_index(drop = True)
print('\nkml files located at :\n', os.getcwd(), '\n were converted succesfully')
os.chdir(path)
if fmt == 'csv':
df.to_csv('kml_to_df_output.csv')
elif fmt == 'df':
return df
if fmt == 'both':
df.to_csv('kml_to_df_output.csv')
return df
|
4078939ebf8447a2f72f802a1479bf82126175f0 | ilyaperepelitsa/pydata | /databases.py | 793 | 3.734375 | 4 | import sqlite3
import pandas as pd
from pandas import DataFrame
query = """
CREATE TABLE test
(a VARCHAR(20), b VARCHAR(20),
c REAL, d INTEGER );"""
con = sqlite3.connect(":memory:")
con.execute(query)
con.commit()
data = [('Atlanta', 'Georgia', 1.25, 6),
('Tallahassee', 'Florida', 2.6, 3),
('Sacramento', 'California', 1.7, 5)]
stmt = "INSERT INTO test VALUES(?, ?, ?, ?)"
con.executemany(stmt, data)
con.commit()
cursor = con.execute("select * from test")
rows = cursor.fetchall()
rows
DataFrame(rows, columns = list(zip(*cursor.description))[0])
import pandas.io.sql as sql
# just a much easier way to read the same data into DataFrame
sql.read_sql('select * from test', con)
### MONGODB
import pymongo
con = pymongo.Connection("localhost", port = 27017)
|
8316850c2d6ae5b3ba5ec731786c2c727ae10fc8 | LiuMaoYang/SwordForOffer | /18/__init__.py | 1,283 | 3.796875 | 4 | # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def createTree(self):
global data
x = data[0]
del data[0]
if x == '#':
node = None
else:
node = TreeNode(x)
node.left = self.createTree()
node.right = self.createTree()
return node
def isSubTree(self, pRoot1, pRoot2):
if pRoot2 == None:
return True
if pRoot1 == None:
return False
if pRoot1.val == pRoot2.val:
return self.isSubTree(pRoot1.left, pRoot2.left) and self.isSubTree(pRoot1.right, pRoot2.right)
def HasSubtree(self, pRoot1, pRoot2):
if pRoot1 == None or pRoot2 == None:
return False
return self.isSubTree(pRoot1, pRoot2) or self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2)
data0 = raw_input().split('/ ')
data = data0[0].split(' ')
t1 = TreeNode(None)
tree1 = t1.createTree()
del data
data = data0[1].split(' ')
t2 = TreeNode(None)
tree2 = t2.createTree()
t = TreeNode(None)
if(t.HasSubtree(tree1, tree2)):
print "T2 is a subtree of T1"
else:
print "T2 is NOT a subtree of T1"
|
f26e4b7a391b46d38c6a5a84d73c8508dc34eb58 | LiuMaoYang/SwordForOffer | /12/main.py | 389 | 3.6875 | 4 | # -*- coding:utf-8 -*-
class Solution:
def __init__(self):
pass
def Power(self, base, exponent):
e=abs(exponent)
y=1.0
while(e>0):
y=y*base
e=e-1
if(exponent<0):
y=1/y
return y
so=Solution()
base=float(raw_input())
exp=int(raw_input())
print '{0}^{1}={2}'.format(base,exp,so.Power(base, exp)) |
5155a530d3d3dee39d7f94f0d1ad1901c1cefbfe | Verycoder/Verycoder.github.io | /mywork/python/reptile/regular.py | 560 | 3.609375 | 4 | '''
. : 匹配任意字符,换行符\n除外
* : 匹配前一个字符0次或无限次
? : 匹配前一个字符0次或1次
.*: 贪心算法
.*?: 非贪心算法
() : 括号内的数据作为返回结果
'''
import re
secret_code = 'hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse'
# . 的使用
#a = 'xz123'
#b = re.findall('x.', a)
#print(b)
# *的使用
#a = 'xyxy123'
#b = re.findall('x*', a)
#print(b)
# ?的使用
#a = 'xy123'
#b = re.findall('x?', a)
#print(b)
b = re.findall('xx.*xx', secret_code)
b = re.findall('xx.*?xx', secret_code)
b = re.findall('xx(.*?)xx', secret_code)
print(b) |
0d6618e8d328877e5d121958a59e5caf6334457d | Verycoder/Verycoder.github.io | /mywork/python/returnoffunc.py | 215 | 3.5625 | 4 | #encoding
'''
def test():
i = 7
return i
print(test())
'''
def test2(i, j):
'''this is a test function'''
result = i * j
return (i, j, result)
#print(test2(2, 5))
'''
a = test2(4, 6)
print(a[2])
'''
help(test2) |
d38a5e6361641c908495f91e3a0c8890959f9335 | Verycoder/Verycoder.github.io | /mywork/python/if.py | 99 | 4.03125 | 4 | a = 3
if (a == 8):
print("a = 8")
elif (a == 9):
print("a = 9")
else:
print("a != 8 && a != 9")
|
f3929bb9278ceb71bca85fa1aeb8f31e52d8337a | ayushi-rathod/creative-engine | /imageutil.py | 1,924 | 3.625 | 4 | from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
# author: Prateek Rokadiya
# Example usage
# img = resizeByWidth(img, w, p)
# where, w = wanted width, p = padding (decreases more width)
def resizeByWidth(img, toWidth, padding = 20):
new_width = toWidth - padding
new_height = new_width * img.size[1] // img.size[0] # Dimension w = img.size[0], h = img.size[1]
return img.resize((new_width, new_height), Image.ANTIALIAS)
# Example usage
# img = resizeByHeight(img, h, p)
# where, w = wanted height, p = padding (decreases more height)
def resizeByHeight(img, toHeight, padding = 20):
new_height = toHeight - padding
new_width = new_height * img.size[0] // img.size[1] # Dimension w = img.size[0], h = img.size[1]
return img.resize((new_width, new_height), Image.ANTIALIAS)
def pasteImage(baseImage, overlayImage, pasteAtXY_tuple):
# print("pasteAtXY_tuple")
baseImage.paste(overlayImage, pasteAtXY_tuple)
# return baseImage.copy()
def writeEmojis(baseImage, XY, text, fontPath, FONT_SIZE, FONT_COLOR=(0, 0, 0)):
draw = ImageDraw.Draw(baseImage)
font = ImageFont.truetype(fontPath, FONT_SIZE)
draw.text(XY, text,fill=FONT_COLOR, font=font)
del draw
def writeGreeting(baseImage, XY, T, fontPath, FONT_SIZE, FONT_COLOR=(0, 0, 0)):
def writeOnImage(baseImage, XY, text, fontPath, FONT_SIZE, FONT_COLOR=(0, 0, 0)):
draw = ImageDraw.Draw(baseImage)
font = ImageFont.truetype(fontPath, FONT_SIZE)
draw.text(XY, text,fill=FONT_COLOR, font=font)
del draw
to, txt, frm = T
# txt - break to a specific character length
blanks = ' '.join(['']*(65- 10 - len(frm)))
text = f'Dear {to},\n{txt}\n{blanks} -From {frm}.'
writeOnImage(baseImage, XY, text, fontPath, FONT_SIZE, FONT_COLOR)
def cropImageByHeight(baseImage, height):
return baseImage.crop((0, 0, baseImage.size[0], height)) |
0c127c312750a34e1161876e1f5cf3d9e1ba8b81 | Aarti5424/Week2Assignment | /main.py | 411 | 3.984375 | 4 | from math import pi
r = float(input ("Input the radius of the circle : "))
print ("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
fname = input("Input your First Name : ")
lname = input("Input your Last Name : ")
print ("Hello " + lname + " " + fname)
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
|
e8c4f5dcc44e10a19ab4699eec662ea89b841261 | boubli/Encrypt-messages | /__main__.py | 2,769 | 3.59375 | 4 | from tkinter import *
from tkinter import ttk
import sys, random
from tkinter import messagebox
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
myMessage = vv.get()
myKey = 'HWERTUYIOPQSDFGAJKLZXCVBNM'
myMode = v.get()
if myMode == 'mode22':
translated = encryptMessage(myKey, myMessage)
vvv.set(translated)
elif myMode == 'mode23':
translated = decryptMessage(myKey, myMessage)
vvv.set(translated)
else:
messagebox.showerror(title='Warning', message='Please select the encryption type')
checkValidKey(myKey)
def checkValidKey(key):
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
lettersList.sort()
if keyList != lettersList:
sys.exit('There is an error in the key or symbol set.')
def encryptMessage(key, message):
return translateMessage(key, message, 'encrypt')
def decryptMessage(key, message):
return translateMessage(key, message, 'decrypt')
def translateMessage(key, message, mode):
translated = ''
charsA = LETTERS
charsB = key
if mode == 'decrypt':
# For decrypting, we can use the same code as encrypting. We
# just need to swap where the key and LETTERS strings are used.
charsA, charsB = charsB, charsA
# loop through each symbol in the message
for symbol in message:
if symbol.upper() in charsA:
# encrypt/decrypt the symbol
symIndex = charsA.find(symbol.upper())
if symbol.isupper():
translated += charsB[symIndex].upper()
else:
translated += charsB[symIndex].lower()
else:
# symbol is not in LETTERS, just add it
translated += symbol
return translated
def getRandomKey():
key = list(LETTERS)
random.shuffle(key)
return ''.join(key)
def close():
exit()
window = Tk()
window.title("Encrypt Messages")
window.configure(background="#006266")
window.geometry("600x470+380+150")
style = ttk.Style()
style.theme_use('clam')
style.configure('TButton', background="#bdc3c7", foreground="#2c3e50", )
Label(window, text="Select encryption type", bg="#006266", fg="white", pady=12).pack()
v = StringVar()
mode = Entry(window, width=20, textvariable=v,).pack()
Label(window, text="Selet Your Message", bg="#006266", fg="white", pady=12).pack()
vv = StringVar()
messageBox = Entry(window, width=40, textvariable=vv).pack(ipady=30)
ttk.Button(window, text="Enceypet", command = main , ).pack(pady=12)
Label(window, text="This is Your Message", bg="#006266", fg="white", pady=12).pack()
vvv = StringVar()
outbput = Entry(window, width=40, textvariable=vvv).pack(ipady=30)
ttk.Button(window, text="Exit", command = close ).pack(pady=12)
window.mainloop() |
248b55c5db43544fc57eca7723e703f61f6a9285 | Khoa100/RegularCode | /Point.py | 752 | 3.53125 | 4 | class Point:
def __init__(self, row_init, col_init):
self.row = row_init
self.col = col_init
def mid_left(self):
return Point(self.row, self.col-1)
def mid_right(self):
return Point(self.row, self.col+1)
def vert_left(self, vert_dir):
return Point(self.row+vert_dir, self.col-1)
def vert_center(self, vert_dir):
return Point(self.row+vert_dir, self.col)
def vert_right(self, vert_dir):
return Point(self.row+vert_dir, self.col+1)
def __repr__(self):
return ''.join(["[", str(self.row), ",", str(self.col), "]"])
# equality checker
def __eq__(self, other):
return self.row == other.row and self.col == other.col
|
16971cbd6d666cd37b33803f08c0c4af22ac3730 | thatDaiwikKashyap/Face-Recognition-With_Pic | /facereco.py | 723 | 3.859375 | 4 | #import CV2 https://pypi.org/project/opencv-python/
import cv2
#Train the code
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Choose an image to detectfaces in
#img = cv2.imread('pic1.jpg')
img = cv2.imread('pic2.jpg')
# Must Convert to grey scale
grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect Face
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
# Draw rectangles
for (x,y,w,h) in face_coordinates:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0 , 255), 3)
#Name For The Python Shell
cv2 .imshow('Daiwik Face Detector' , img)
#Runs The Python Shell For some time until Enter Key Is pressed
cv2.waitKey()
print("Code Complete!")
|
076a40fc02b0791eedaae92747394f46170a9678 | prathyusak/pythonBasics | /errors.py | 2,720 | 4.21875 | 4 | #Syntax Errors and Exceptions
#while True print('Hello world') => syntax error
#ZeroDivisionError =>10 * (1/0)
#NameError => 4 + spam*3
#TypeError => '2' + 2
#################
# Handling Exceptions
import sys
def this_fails():
x = 1/0
while True:
try:
x = int(input("Please enter a number: "))
this_fails()
break
except ValueError:
print("Oops! That was no valid number. Try again...")
except (RuntimeError, TypeError, NameError): #except clause can have multiple exceptions
pass
except ZeroDivisionError as err:
print('Handling run-time error:', err)
break
except: #empty exception name serves as wildcard
print("Unexpected error:", sys.exc_info()[0])
raise #raising exceptions
################
#Exception chaining : when exception raised from except or finally block
# try:
# open('database.sqlite')
# except IOError as ioerr :
# raise RuntimeError from ioerr
# #To disable exception chaining
# try:
# open('database.sqlite')
# except IOError as ioerr :
# raise RuntimeError from None
################
#try except else finally
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else: #additional code in try block
print("result is", result)
finally: # executes at all times , cleanup acions
print("executing finally clause")
################
#User defined exceptions
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
#####################
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except B:
print("B")
# raise InputError('erro','mess')
except D: #an except clause listing a derived class is not compatible with a base class
print("D")
except C:
print("C")
|
894e6ecd16cceb83d90cf431d37f913c20fb3b11 | nikhilpradhan28/python_basic | /odd_even_list_for.py | 258 | 4.03125 | 4 | a=[]
n=int(input("Enter number of elements:"))
for i in range(1, n + 1):
b = int(input("Enter element:"))
a.append(b)
print(a)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print(even)
print(odd)
|
1017d52173ea39db94f0e419d4ba011357af3dc0 | nikhilpradhan28/python_basic | /Python_DataType/string_operations.py | 210 | 3.578125 | 4 | #print("Hello I am Nikhil")
#print('I am going to learn python')
#print("Hello I am Nikhil\t"+"I am going to learn python")
#print("Hello I am Nikhil\n"+"I am going to learn python")
print("7"+"7")
print("7"*7) |
e0023cf7a93de5270f164ed012d01ccd2b4e6ecc | annargrs/ldt | /ldt/helpers/formatting.py | 3,915 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""Text formatting functions
This section includes a few helper functions for formatting different
spelling variants.
"""
def remove_text_inside_brackets(text, brackets="()[]"):
'''
A helper function for :func:`get_relations`, code from `here
<https://stackoverflow.com/questions/14596884/remove-text-between-and-in-python>`_
Args:
text (str): the text to clean from brackets
brackets: the list of symbols counting as brackets
Returns:
(str): cleaned-up text
'''
count = [0] * (len(brackets) // 2) # count open/close brackets
saved_chars = []
for character in text:
for i, b in enumerate(brackets):
if character == b: # found bracket
kind, is_close = divmod(i, 2)
count[kind] += (-1) ** is_close # `+1`: open, `-1`: close
if count[kind] < 0: # unbalanced bracket
count[kind] = 0 # keep it
else: # found bracket to remove
break
else: # character is not a [balanced] bracket
if not any(count): # outside brackets
saved_chars.append(character)
return ''.join(saved_chars).strip()
def get_spacing_variants(word):
'''
A helper function for :func:`get_relations` that, given a
string spaced input, produces a list of different spelling versions of
this word (e.g. ["good night", "good-night", "good_night"])
Args:
word (str): input word
Returns:
(list): a list of variants: spaced, dashed and underscored
'''
res = []
res.append(word)
res.append(word.replace(" ", "_"))
res.append(word.replace(" ", "-"))
return res
def strip_non_alphabetical_characters(word, ignore=None):
"""Helper function for removing any non-alphabetical character with optional exclusion list.
Wiktionary etymologies are a mess to parse. This function attempts to extra clean-up cases like *(-ness* or *"king+*. Optionally, it will return only strings that are known determined to be words by :func:`noise.is_a_word`.
Args:
word (str): a potential word string to process
ignore (tuple): the characters to not strip (e.g. "-")
Returns:
str: cleaned up string (a potential word)
"""
if not word:
return None
if word.isalpha():
return word
else:
stripped = ""
for i in range(len(word)):
if i == 0 or i == len(word) - 1:
try:
if word[i].isalpha() or word[i] in ignore:
stripped += word[i]
except TypeError:
pass
else:
try:
if word:
if word[i] in ignore or word[i].isalpha():
stripped += word[i]
except TypeError:
pass
return "".join(stripped)
def dash_suffix(suffix):
"""A helper function for custom derivation dicts.
Some suffixes are mostly spelled with a dash (e.g. *tree-like*), and some
may be spelled with a dash for stylistic reasons (e.g. *work-able*).
This function ensures that both ways are tracked.
Args:
suffix (str): suffix to be dashed or not
Returns:
suffix (str): a dashed suffix
"""
if suffix.startswith("-"):
return suffix
else:
return "-" + suffix
def rreplace(word, old_suffix, new_suffix):
"""Helper for right-replacing suffixes"""
return new_suffix.join(word.rsplit(old_suffix, 1))
def _check_res(res):
"""Helper for avoiding empty dictionary as function argument in
morphological dictionaries"""
if not res:
res = {
"suffixes": [], "prefixes": [], "roots": [], "other": [],
"original_word": []
}
return res |
50c4c4c68abf3a777b4195e41b970174ae0173a2 | adonispujols/Adonis_ASC3 | /Bouncing_Ball_app/Bouncing_Ball_app.pyde | 980 | 4 | 4 | #Makes a ball bounce off the walls at set angles but starting from a random direction
from random import *
#Setting varaibles for easy customization
x_boundary = 400
y_boundary = 400
x_coordinate = 200
y_coordinate = 200
speed_x = randrange (1,5) #both changes in x and y are randomized to make ball move in random direction
speed_y = randrange (1,5)
def setup():
global x_coordinate
global y_coordinate
size(x_boundary,y_boundary)
def draw():
global x_coordinate
global y_coordinate
global speed_x
global speed_y
background(255)
noStroke()
fill(0)
ellipse(x_coordinate,y_coordinate,50,50)
## Checks if ball collided with a wall, then changes its speed appropriately
if 25>x_coordinate or x_coordinate>375:
speed_x = speed_x*-1
if 25>y_coordinate or y_coordinate>375:
speed_y = speed_y*-1
x_coordinate +=speed_x
y_coordinate +=speed_y
print(x_coordinate, y_coordinate,collision_state) |
72610155dc84c194919e0f4e4c8c68354f4d0e5c | ArshiaRa/Coffee-Machine | /Coffee Machine.py | 3,537 | 3.765625 | 4 | water = 400
milk = 540
beans = 120
cups = 9
money = 550
Ewater = 250
Ebeans = 16
Emilk = 0
Lwater = 350
Lbeans = 20
Lmilk = 75
Cwater = 200
Cbeans = 12
Cmilk = 100
def reduce(number,water11,beans11,milk11,money11,cups11):
global water
global beans
global milk
global money
global cups
if number == 1:
water = water - water11
milk = milk - milk11
beans -= beans11
money +=money11
cups-=cups11
def check(coffee,water2,beans2,milk2,money,cups):
global Emilk ,Ewater, Ebeans , Lwater , Lbeans , Lmilk,Cwater,Cbeans,Cmilk
if coffee == 1:
if water >=water2 and beans >= beans2:
print("I have enough resources, making you a coffee!")
reduce(1,Ewater,Ebeans,Emilk,4,1)
elif water < water2:
print("Sorry, not enough water!")
elif beans < beans2:
print("Sorry, not enough beans!")
elif coffee == 2:
if (water >=water2 and beans >= beans2 and milk >= milk2):
print("I have enough resources, making you a coffee!")
reduce(1,Lwater,Lbeans,Lmilk,7,1)
elif water < Lwater:
print("Sorry, not enough water!")
elif beans < Lbeans:
print("Sorry, not enough beans!")
elif milk < Lmilk:
print("Sorry, not enough milk!")
elif coffee == 3:
if (water >=water2 and beans >= beans2 and milk >= milk2):
print("I have enough resources, making you a coffee!")
reduce(1,Cwater,Cbeans,Cmilk,6,1)
elif water < Cwater:
print("Sorry, not enough water!")
elif beans < Cbeans:
print("Sorry, not enough beans!")
elif milk < Cmilk:
print("Sorry, not enough milk!")
def taking():
global money
print('I gave you',money)
money = 0
def filling():
global water
global beans
global milk
global cups
print("Write how many ml of water do you want to add:")
waterPlus = int(input())
water+=waterPlus
print("Write how many ml of milk do you want to add:")
milkPlus = int(input())
milk+=milkPlus
print("Write how many grams of coffee beans do you want to add:")
beansPlus=int(input())
beans+=beansPlus
print("Write how many disposable cups of coffee do you want to add:")
cupsPlus=int(input())
cups+=cupsPlus
def state():
print("The coffee machine has:")
print(int(water) , 'of water')
print(int(milk) , 'of milk')
print(int(beans) , 'of coffee beans')
print( int(cups),'of disposable cups')
print('$'+str(money) , 'of money')
def buying():
print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:")
choose = (input())
if choose =="back":
return
if int(choose) == 1:
return check(1,Ewater,Ebeans,Emilk,money,cups)
if int(choose) == 2:
return check(2,Lwater,Lbeans,Lmilk,money,cups)
if int(choose) == 3:
return check(3,Cwater,Cbeans,Cmilk,money,cups)
def action(string):
if string == 'remaining':
return state()
if string == 'buy':
return buying()
if string == 'fill':
return filling()
if string == 'exit':
exit(1)
if string == 'take':
return taking()
while True:
print("Write action (buy, fill, take , remaining, exit):")
string = input()
action(string)
|
9d80ad503bf762a8079389c4026f8ee5857d4f4e | LivNarc/exosphere | /user_generator.py | 452 | 3.640625 | 4 |
import csv
products ={}
user_file = raw_input('which file would you like to open:\n\t')
form = raw_input('which format would you like:n\t\'HTML'n\t\'Plain')
if form is 'HTML':
print 'HTML Report Here'
elif 'Plain' is:
print 'Plain Report Here'
else:
print 'invalid msg
with open(user_file,'rb') as csvfile:
report = csv.reader(csvfile, delimiter =';')
for row in report:
products[row[0]] = {'qty':row[3], 'revenue':row[2]}
print products
|
0bb7b65666ac17d8207a34eea9141ea700d5aa46 | N11K6/Digi_FX | /Distortion/Valve.py | 1,552 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This function applies distortion to a given audio signal by modelling the
effects from a vacuum tube. Input parameters are the signal vector x,
pre-gain G, "work point" Q, amount of distortion D, and pole positions r1
and r2 for the two filters used.
@author: nk
"""
import numpy as np
from scipy import signal
from scipy.io import wavfile
#%%
def Valve(x,G=1,Q=-0.05,D=400,r1=0.97,r2=0.8):
# Normalize input:
x = x / (np.max(np.abs(x)))
# Apply pre-gain:
x *= G
# Oversampling:
x_over = signal.resample(x, 8 * len(x))
if Q == 0:
y_over = x_over/(1-np.exp(-D * x_over)) - 1 / D
else:
# Apply Distortion:
PLUS = Q / (1-np.exp(D*Q))
EQUAL_QX = 1 / D + Q / (1 - np.exp(D * Q))
# Logical indexing:
logiQ = (x_over % Q != 0).astype(int)
x_Q = x_over - Q
y_0 = - (logiQ - 1) * EQUAL_QX
y_1 = (logiQ * x_Q) / (1 - np.exp(-D * (logiQ * x_over -Q)))+PLUS
y_over = y_0 + y_1
# Downsampling:
y = signal.decimate(y_over, 8)
# Filtering:
B = [1, -2, 1]
A = [1, -2*r1, r1**2]
y = signal.filtfilt(B, A, y)
b = 1-r2
a = [1, -r2]
y = signal.filtfilt(b, a, y)
# Normalization:
y /= np.max(np.abs(y))
return y
#%%
if __name__ == "__main__":
G=1
Q=-0.05
D=400
r1=0.97
r2=0.8
sr, data = wavfile.read("../TestGuitarPhraseMono.wav")
y = Valve(data,G,Q,D,r1,r2)
wavfile.write("example_Valve.wav", sr, y.astype(np.float32)) |
d93ea23a75b58330903c8d2e5cf8ebdfe587d1cf | matiasbouin/Facultad | /programacion 1/networking.py | 397 | 3.640625 | 4 | # NETWORKING
'''
URL and IMAGES from urllib
SOCKET PROGRAMMING from socket
SEND EMAILS from smtlib
'''
# Acces url and downloading html
import urllib.request
try:
url = urllib.request.urlopen('https://www.python.org/')
content = url.read()
url.close()
except urllib.error.HTTPError:
print("Page not found!")
exit()
f = open("python.html", 'wb')
f.write(content)
f.close()
|
d02b55e743382cd1bf8bc9381066afff35fe23c9 | caphael0925/CAPython | /src/MyAPPs/Get_primef.py | 1,132 | 3.578125 | 4 | '''
Created on 2012-12-7
@author: Caphael
'''
if __name__ == '__main__':
pass
import sys
inum=input('Please input a number:')
factor=0
factors=[]
primelist=[2]
i=1
prod=inum
def get_factor(prod):
global primlist
if prod in primelist:
return prod
for p in primelist:
if prod%p==0:
return p
while p<=prod:
if prod%p==0:
primelist.append(p)
return p
else:
p=p+1
return 0
while prod>1:
factor=get_factor(prod)
if factor==0 :
break
factors.append(factor)
prod=prod/factor
print list(set(factors))
#def get_next_factor(prod):
# if prod in prime:
# factor.append(prod)
# else:
# for i in prime:
# if prod%i==0:
# factor.append(i)
# prod=prod/i
# break
#
# while i<prod:
# i=i+1
# if prod%i==0:
# factor.append(i)
# prod=prod/i
# prime.append(i)
# get_next_factor()
|
061fb47ae51971c35c9155d67e75d00e7a261ce3 | lanbowcn/TFstudy | /TFAction/1-7-1.py | 927 | 3.53125 | 4 | import tensorflow as tf
import numpy as np
# 实现激励函数
sess = tf.Session()
# 显式调用内建激励函数
# 1.整流线性单元(Rectifier linear unit,ReLU)神经网络常用非线性函数
# 函数为max(0,x)连续但不平滑。
print(sess.run(tf.nn.relu([-3., 3., 10.])))
#2.为限制ReLU的线性增长部分,会在min()函数中嵌入max(0,x),其在tf中的实现成为ReLU6,表示
# min(max(0,x),6),这个是hard-sigmoid函数的变种,计算运行速度快,解决梯度消失(无线趋于0)
print(sess.run(tf.nn.relu6([-3., 3., 10.])))
# 3.sigmoid函数是最常用的连续、平滑的激励函数。
# 也被称作逻辑函数(logistic函数),表示为1/(1+exp(-x))。
# sigmoid函数用于在机器学习训练过程中反向传播项趋近于0,因此不怎么使用。
print(sess.run(tf.nn.sigmoid(-1., 0., 2)))#此处有错
# 自定义设计激励函数
|
426c6ee8f7b916d1a65112a928d60e93d6c9e347 | gersonpas/LoteriaCEF | /main.py | 1,622 | 3.515625 | 4 | from random import randint, sample
import time
print('\033[0;33m{:=^44}'.format('\033[0;33m LOTERIAS '))
print('''
[1] = QUINA
[2] = MEGA SENA
[3] = DUPLA SENA
[4] = LOTOFÁCIL
[5] = lOTOMANIA
[6] = DIA DE SORTE''')
loto = int(input('Escolha sua loteria: '))
while loto > 6 or loto < 1:
loto = int(input('\033[0;34mEntre com uma opção válida: '))
if loto == 1:
opção, init, fim, qdezInit, qdezFim = ' QUINA', 0, 80, 5, 15
elif loto == 2:
opção, init, fim, qdezInit, qdezFim = 'MEGA SENA', 1, 60, 6, 15
elif loto == 3:
opção, init, fim, qdezInit, qdezFim = 'DUPLA SENA', 1, 50, 6, 15
elif loto == 4:
opção, init, fim, qdezInit, qdezFim = 'LOTOFÁCIL', 1, 25, 15, 18
elif loto == 5:
opção, init, fim, qdezInit, qdezFim = 'lOTOMANIA', 0, 99, 50, 50
elif loto == 6:
opção, init, fim, qdezInit, qdezFim = 'DIA DE SORTE', 1, 30, 7, 15
Mes = sample(range(1, 12), 1)
print('Você escolheu {}, Ótima escolha!'.format(opção))
qdezenas = int(input('\033[0;33mEscolha um jogo entre {} e {} Dezenas\033[0;33m: '.format(qdezInit, qdezFim)))
while qdezenas < qdezInit or qdezenas > qdezFim:
qdezenas = int(input('Entre com uma opção valida: '))
print('-='*27)
print('Muito bem! Você escolheu a {} com {} Dezenas!'.format(opção, qdezenas))
print('-='*27)
print('\033[0;34m-='*50)
print('\033[0;33mSorteando os Números...')
time.sleep(2)
dezenas = sorted(sample(range(init, fim),qdezenas))
print('\033[0;34mAs {} Dezenas Sorteadas foram: {}'.format(qdezenas ,dezenas))
print('O Mês escolhido foi: {} '.format(Mes) if loto == 6 else '-='*50)
print('-='*50 if loto == 6 else '')
|
22bccb77b938e7e796a695a86638491a7fb70a03 | EdwardLijunyu/first-room | /数据结构/17二进制中1的个数.py | 1,134 | 3.59375 | 4 |
'''
输入一个整数,输出该数的二进制表示中的1的个数,其中负数用补码表示
请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,
把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
'''
class Solution:
def hammingWeight(self, n: int) -> int:
n = 0xFFFFFFFF & n # 将负数
print(bin(n)) #bin()是将数转化为二进制,负数转化为补码 int有32位 4个字节,一个字节8位
k = 0
for i in str(bin(n)):
if i == "1":
k += 1
return k
test=Solution()
print(test.hammingWeight(-6))
'''
反码的表示方法是:
正数的反码是其本身
负数的反码是在其原码的基础上, 符号位不变,其余各个位取反.
补码的表示方法是:
正数的补码就是其本身
负数的补码是在其原码的基础上, 符号位不变, 其余各位取反, 最后+1. (即在反码的基础上+1)
只有将负数转化为补码才能进行正确的加法运算1+(-1)=0
'''
|
34367a4657eed0a6868f596eebbd0899ba6ebbc3 | DevelopDevelopDevelop/Python-Practice | /deck_shuffler.py | 585 | 3.625 | 4 | # Build and shuffle a card deck
# My attempt to solve the problem of redundant cards
import random
# Assign list holders
card = []
suit = ["Clubs", "Spades", "Hearts", "Diamonds",]
royals = ["Jack", "Queen", "King", "Ace"]
deck = []
# Create list of numbered cards
for i in range(2,11):
card.append(str(i))
# Create list of royal cards and Aces
for j in range(4):
card.append(royals[j])
# Compile deck
for k in range(4):
for l in range(13):
cards = (card[l] + " of " + suit[k])
deck.append(cards)
# Shuffle deck
random.shuffle(deck)
for m in range(52):
print(deck[m])
|
6b7a130685cb240f3bda7a35efb4f31082d63f06 | cafesao/Programas_Python | /Adicionar_Valores.py | 808 | 3.984375 | 4 | #Variaveis
lista_valores = list()
cont_vezes = num_Cinco = int(0)
resposta = str()
#Adição de valores
while True:
numero_user = int(input('Digite um valor inteiro: '))
cont_vezes += 1
if numero_user not in lista_valores:
lista_valores.append(numero_user)
resposta = str(input('Deseja continuar? (Sim / Não): ')).split()[0].upper()
if resposta == 'N':
break
#Mostrar as listas
lista_valores.sort()
print(f'\nA lista de forma crescente: {lista_valores}')
lista_valores.sort(reverse=True)
print(f'A lista de forma decrescente: {lista_valores}')
print(f'\nVocê digitou {cont_vezes} vezes')
#Mostra se tem ou não o numero 5
if 5 in lista_valores:
print(f'\nNa lista tem o numero cinco')
else:
print('\nNão tem não tem o numero cinco') |
54ef9a990c29e514e8d23dee89d77162b6638c27 | cafesao/Programas_Python | /NotasV2.0.py | 2,869 | 3.5625 | 4 |
from tabulate import tabulate
alunos = []
dados = []
alunosc = []
alunost = media = 0
print('Bem-Vindo ao programa Media_Notas V2.0\n')
escola = str(input('Digite o nome da escola: ')).capitalize()
serie = str(input('Digite a serie: '))
while True:
a = str(input('\nDigite o nome do aluno: ')).capitalize()
dados.append(a)
for c in range (0,4):
n = float(input('Digite a nota do aluno: '))
dados.append(n)
alunos.append(dados[:])
dados.clear()
r = str(input('Deseja adicionar mais alunos? (Sim / Não): ')).split()[0].upper()
if r[0] == 'N':
break
for t in alunos:
alunost += 1
media = (t[1] + t[2] + t[3] + t[4]) / 4
print(f'O aluno {t[0]} tirou as seguintes notas: {t[1]} : {t[2]} : {t[3]} : {t[4]}')
print(f'A media foi: {media:.2f}')
print('')
while True:
r = str(input('Deseja emitir o boletim dos alunos? (Sim/Não): '))
if r[0] == 'N':
break
print('''
[1] Todos os alunos
[2] Aluno Específico''')
r = int(input('\nDeseja emitir o boletim de todos os alunos ou de algum especifico: '))
if r == 2:
print(f'No sistema tem {alunost} alunos')
print(f'Os alunos são: \n')
alunost = 0
for t in alunos:
print(f'{alunost} - {t[0]} ')
alunost += 1
r = int(input('\nQual aluno você deseja: '))
media = (alunos[r][1] + alunos[r][2] + alunos[r][3] + alunos[r][4]) / 4
if media >= 6:
aprov = 'Aprovado'
if media < 6:
aprov = 'Não Aprovado'
print(f'''
---------------------------------------------------------
Escola: {escola}
Serie: {serie}
Nome: {alunos[r][0]}
---------------------------------------------------------
1º Bi 2º Bi 3º Bi 4º Bi
Notas: {alunos[r][1]} {alunos[r][2]} {alunos[r][3]} {alunos[r][4]}
---------------------------------------------------------
Media: {media:.2f}
Aprovação: {aprov}
---------------------------------------------------------
''')
print()
break
if r == 1:
for b in alunos:
media = (b[1] + b[2] + b[3] + b[4]) / 4
if media >= 6:
aprov = 'Aprovado'
if media < 6:
aprov = 'Não Aprovado'
print(f'''
---------------------------------------------------------
Escola: {escola}
Serie: {serie}
Nome: {b[0]}
---------------------------------------------------------
1º Bi 2º Bi 3º Bi 4º Bi
Notas: {b[1]} {b[2]} {b[3]} {b[4]}
---------------------------------------------------------
Media: {media:.2f}
Aprovação: {aprov}
---------------------------------------------------------
''')
break |
7014dfce8be85d3e0d993081faa228fb5693d68a | cafesao/Programas_Python | /Alistamento.py | 834 | 4 | 4 | #Codigo
while True:
nome_user = str(input('Qual seu nome?: ')).split()[0].capitalize()
ano_nascimento = int(input('Qual o ano do seu nascimento?: '))
ano_nascimento = 2019 - ano_nascimento
if ano_nascimento < 18:
print(f'{nome_user}, você ainda não se alistou, faltam {18 - ano_nascimento} anos para vc se alistar. \n')
elif ano_nascimento == 18:
print(f'{nome_user}, você deve se alistar este ano, fique atento! \n')
else:
print(f'{nome_user}, passou o prazo de alistamento, verifique com a junta militar para regularizar sua situação. \n')
resposta = str(input('Deseja recomeçar? (Sim / Não): ')).split()[0].upper()
if resposta == 'N':
break
print('\nObrigado por utilizar o Alistamento.')
#Exemplo sem declarar ANTES nenhuma variavel |
f2f7e7c15682418d151df456a099d7fed777001d | cafesao/Programas_Python | /Contagem_Regressiva.py | 418 | 3.734375 | 4 | # Contagem regressiva para o estouro dos fogos!
import time
while True:
n1 = int(input('Digite um valor: '))
for c in range(n1,0,-1):
print(f'Vai estourar em: {c}')
time.sleep(1)
print('Os fogos estouraram!! \n')
r = str(input('Deseja recomeçar? (Sim / Não): ')).split()[0].upper()
if r[0] == 'N':
break
print('\nObrigado por utilizar Contagem Regressiva.')
|
bcbf7460cbac72daf800fa9cb4cb9944f2904270 | dmallows/Crayon | /plots/typesys.py | 13,462 | 3.625 | 4 | """Validating type system and simple types. It is worth noting that Type objects
only contain information for validation, and a default value. The decision to
use objects to represent types. Inspired by, though no patch on, Haskell's type
system.
Types are class objects, and are transformed using a (simple!) metaclass. When a
NameSpace is instanciated, Value objects are created for each field. These
(confusingly) can contain their own, settable default value, which overrides the
Type's if set. These values contain the current setting, and within a namespace
behave like actual instance objects rather seamlessly.
Children can inherit this behaviour, providing they call the init function.
"""
# Disclaimer: Abandon all hope, ye who enter here. There is probably far deeper
# magic than we will ever need... But this is the way the vision came. So, it
# stays for now!
# TODO: cleanup these exceptions - they're copy & pasted from the python docs!
import re # TODO: remove
from collections import OrderedDict
from crayon.color import Rgb
# =====================
# ===== ERRORS ========
# =====================
class Error(Exception):
"""Generic module Error class, as recommended by Python docs."""
def __str__(self):
return '%r: %s' % (self.expr, self.msg)
class ParseError(Error):
"""A string could not be parsed"""
def __init__(self, expr, msg):
self.expr = expr
self.msg = msg
class TestError(Error):
"""A test failed to pass"""
def __init__(self, expr, msg):
self.expr = expr
self.msg = msg
def __str__(self):
return '%s: %s' % (self.expr.__class__.__name__, self.msg)
class Type(object):
"""Base type class"""
# Counter for ordering (stolen from Django)
_counter = 0
def __init__(self, test = None, default = None):
self._counter = Type._counter
Type._counter += 1
self._test = test
self._default = default
@property
def default(self):
"""Read only default value for the type."""
return self._default
def from_py(self, v):
"""Convert from python representation and validate"""
return self.test(self._from_py(v))
def _from_py(self, v):
return v
def to_py(self, v):
"""Convert from internal representation to python representation"""
return self._to_py(v)
def _to_py(self, v):
return v
def from_string(self, v):
"""Convert from string and validate"""
return self.test(self._from_string(v))
def to_string(self, v):
"""Convert to string"""
return self._to_string(v)
def test(self, v):
"""Test the value against the registered tests."""
f = self._test
if f:
f(v)
return v
#================================
#========== TESTS ===============
#================================
# Lambdas have known problems when it comes to pickling. Classes are more solid.
# Here are some classes! The only requirement of tests is that they are
# callable. So a lambda or a (nested) function is **just** as legitimate.
class RangeTest(object):
"""Check a number is within defined range"""
def __init__(self, min_ = None, max_ = None):
self._r = min_, max_
def __call__(self, v):
if v is None:
return True
result = True
a, b = self._r
if a is not None:
if v < a:
raise TestError(self, '%s < %s' % (v,a))
if b is not None:
if v > b:
raise TestError(self, '%s > %s' % (v,b))
return v
class ElementTest(object):
"""Check that value is in a given set, naive way"""
def __init__(self, *ps):
self._ps = set(ps)
def __call__(self, v):
return (v in self._ps)
class ShallowElementTest(object):
"""Check that value is in a given set, using weak equality"""
def __init__(self, *ps):
self._ps = ps
def __call__(self, v):
for p in self._ps:
if p is v:
return True
return False
class DeepElementTest(object):
"""Check that value is in a given set in a referentially transparent way"""
def __init__(self, *ps):
self._ps = ps
def __call__(self, v):
for p in self._ps:
if p == v:
return True
return False
class InstanceTest(object):
"""Check that passed item is an instance of a given class"""
def __init__(self, cls):
self._cls = cls
def __call__(self, v):
return isinstance(v, self._cls)
# TODO: Combinations
#================================
#========== TYPES ===============
#================================
class Boolean(Type):
def __init__(self, default=False):
super(Boolean, self).__init__(test=ElementTest(True, False), default=default)
def to_string(self, v):
return repr(self.get())
def _from_string(self, v):
v = v.strip().lower()
if v in ('true','t','yes','y','1'):
return True
elif v in ('false','f','no','n','0'):
return False
else:
raise ParseError(v,"Couldn't parse")
class String(Type):
def __init__(self, default=None):
super(String, self).__init__(test=InstanceTest(basestring), default=default)
def _from_string(self, v):
return v
def to_string(self, v):
return v
class Enum(Type):
def __init__(self, vals, default = None):
vals = tuple(v.upper() for v in vals)
default = vals[0] if default is None else default.upper()
assert(default in vals)
super(Enum, self).__init__(test = ElementTest(*vals), default=default)
def _from_py(self, v):
return v.upper()
def _from_string(self, v):
return v.upper()
def _to_string(self, v):
return v.upper()
class Color(Type):
def _from_py(self, v):
try:
return v.rgb
except AttributeError, e:
raise ValueError(e)
def _to_py(self, v):
return v
def _to_string(self, v):
return 'rgb: %r' % v.color
def _from_string(self, v):
return ast.literal_eval(v)
# Numeric types
class Number(Type):
def __init__(self, min=None, max=None, default=0):
super(Number, self).__init__(test=RangeTest(min, max), default=default)
class Int(Number):
def _from_py(self, v):
try:
return int(v)
except ValueError:
raise
def _from_string(self, v):
try:
return int(v)
except ValueError as e:
raise ParseError(v, str(e))
def _to_string(self, v):
return '%d' % v
class Float(Number):
def _to_str(self, v):
return '%g' % v
def _from_str(self, v):
return float(v)
def _from_py(self, v):
return float(v)
# Polymorphic types (ah yes...)
# It is said that a lot of large scale projects end up re-implementing most
# features of Lisp. It seems that I am re-implementing much of the features of
# Haskell. Python actually makes this *easier* than Haskell (I have a
# disposition towards this kind of thing...).
class Tuple(Type):
"""Analogue of Python tuples"""
# TODO: remove regexp. (Serious bugs e.g. parsing strings). Use recursive
# descent parser instead.
_r = re.compile(r'\((.*)\)')
def __init__(self, *params):
default = tuple(i.default for i in params)
super(Tuple, self).__init__(default=default)
self._params = params
def _from_py(self, values):
return tuple(p.from_py(v) for p, v in zip(self._params, values))
def _to_py(self, values):
return tuple(p.to_py(v) for p, v in zip(self._params, values))
def _to_string(self, values):
return '(%s)' % ', '.join(
p.to_string(v) for p, v in zip(self._params, values))
def _from_string(self, values):
return ( p.from_string(v.strip()) for p, v in
zip(self._params,
self._r.match(values).group(1).split(',')) )
class Maybe(Type):
"""Type representing optional parameters"""
def __init__(self, proxy, default = None):
super(Maybe, self).__init__()
self._proxy = proxy
def _from_py(self, v):
# Maybe swallows the value if it's None
if v is None:
return
else:
return self._proxy.from_py(v)
def _to_py(self, v):
if v is None:
return None
else:
return self._proxy.to_py(v)
def _from_string(self, s):
if s is '':
return
else:
return self._proxy.from_string(s)
def _to_string(self, v):
if v is None:
return 'None'
else:
return self._proxy.to_string(v)
class Value(object):
def __init__(self, param, default=None):
self._param = param
self.default = param.default
self._value = None
def get(self):
value = self.default if self._value is None else self._value
return self._param.to_py(value)
def set(self, v):
self._value = self._param.from_py(v)
if hasattr(self, 'on_changed'):
self.on_changed()
@property
def changed(self):
return self._value is not None
def reset(self):
self._value = None
value = property(get, set, reset)
def show(self):
return self._param.to_string(self.value)
def read(self, v):
self.value = self._param.from_string(v)
if hasattr(self, on_changed):
self.on_changed()
def lookup_separated(self, keys):
if not keys:
return self
else:
raise RuntimeError('Value has no attributes')
string = property(show, read)
def set_default(self, default=None):
if hasattr(self, 'default'):
old_default = self._default
self._default = self._param.default if default is None else default
if self.changed and default != old_default and hasattr(
self, 'on_changed'):
self.on_changed()
else:
self._default = default
def get_default(self):
try:
return self._default()
except TypeError:
return self._default
def reset_default(self):
self._default = self._param.default
default = property(get_default, set_default, reset_default)
def property_helper(key):
def _getter(self):
return self._params[key].get()
def _setter(self, value):
return self._params[key].set(value)
def _deller(self):
return self._params[key].clear()
return _getter, _setter, _deller
class ModelMeta(type):
def __new__(cls, clsname, bases, attrs):
params = [(name, attrs.pop(name)) for name, obj in attrs.items() if
isinstance(obj, Type)]
params.sort(key=lambda x: x[1]._counter)
for base in reversed(bases):
if hasattr(base, '_params'):
params = base._params.items() + params
attrs['_params'] = params = OrderedDict(params)
properties = {}
for x, v in params.iteritems():
p = property(*property_helper(x))
attrs[x] = p
properties[x] = p
attrs['_properties'] = properties
new_class = super(ModelMeta, cls).__new__(cls, clsname, bases, attrs)
return new_class
class Proxy(object):
def __init__(self, param):
self._param = param
def __call__(self):
return self._param.get()
class NameSpace(object):
__metaclass__ = ModelMeta
def __new__(cls, *args, **kwargs):
params = cls._params.copy()
for key in params:
params[key] = Value(params[key])
self = super(NameSpace, cls).__new__(cls, *args, **kwargs)
self._params = params
return self
def __init__(self, *args, **kwargs):
return
def __getitem__(self, name):
try:
xs = name.split('.')
try:
x, = xs
try:
return self._params[x]
except:
return getattr(self, x)
except ValueError: # Couldn't unpack => multiple?
return self[xs]
except AttributeError: # Couldn't split => list
try:
return self[name[0]][name[1:]]
except TypeError:
return self[name[0]]
def namespaces(self):
names = OrderedDict()
for i in dir(self):
v = getattr(self, i)
if isinstance(v, NameSpace):
names[i] = v
return names
def params(self):
return self._params
def fmap(self, f):
"""Maps a function f(x) over each leaf of the structure"""
for i in self.namespaces().values():
i.fmap(f)
for p in self.params().values():
f(p)
def follow(self, f):
"""Recursively inherit defaults from given namespace"""
for k, v in f.params().iteritems():
try:
self._params[k].default = Proxy(v)
except KeyError:
pass
def iteritems(self):
return ((k, v.value) for k, v in self.params().iteritems())
|
9e4ba8e7e9a227ed061602d291bd1b5e7851f933 | zangell44/DS-Unit-3-Sprint-1-Software-Engineering | /acme.py | 2,589 | 3.953125 | 4 | #!/usr/bin/env python
"""
Classes representing products sold by Acme Corp
"""
import random
class Product:
"""
Generic class for items sold by Acme Corp
"""
def __init__(self, name, price=10, weight=20, flammability=0.5):
if not isinstance(name, str):
raise AttributeError("'name' of Product must be a string")
if not isinstance(price, int):
raise AttributeError("'price' of Product must be an int")
if not isinstance(weight, int):
raise AttributeError("'weight' of Product must be an int")
if not isinstance(flammability, float):
raise AttributeError("'flammability' of Product must be a float")
self.name = name
self.price = price
self.weight = weight
self.flammability = flammability
self.identifier = random.randint(1000000, 9999999)
def stealability(self):
""""
Returns a message indicating stealability of a Product
"""
stealability_score = float(self.price) / float(self.weight)
print (stealability_score)
if stealability_score < 0.5:
return 'Not so stealable...'
elif stealability_score >= 0.5 and stealability_score < 1.0:
return 'Kinda stealable.'
else:
return 'Very stealable!'
def explode(self):
"""
Returns a message indicating explosion potential of Product
"""
flammability_score = float(self.flammability) * float(self.weight)
if flammability_score < 10.0:
return '...fizzle.'
elif flammability_score >= 10.0 and flammability_score < 50.0:
return '...boom!'
else:
return '...BABOOM!!'
class BoxingGlove(Product):
"""
Boxing glove object sold by Acme corp
"""
def __init__(self, name, price=10, weight=10, flammability=0.5):
self.name = name
self.price = price
self.weight = weight
self.flammability = flammability
self.identifier = np.random.randint(1000000, 10000000)
def explode(self):
"""
Returns a message indicating non-explosive potential of boxing gloves
"""
return "...it's a glove."
def punch(self):
"""
Punches someone with boxing glove and returns their reaction based
on glove weight
"""
if self.weight < 5.0:
return 'That tickles.'
elif self.weight >= 5.0 and self.weight < 15.0:
return 'Hey that hurt!'
else:
return 'OUCH!'
|
57e443004e07c95bc99217d700e6b4f40f5c8a5f | yamaz420/PythonIntro-LOLcodeAndShit | /pythonLOL/vtp.py | 2,378 | 4.125 | 4 | from utils import Utils
class VocabularyTrainingProgram:
words = [
Word("hus", "house")
Word("bil", "car")
]
def show_menu(self):
choice = None
while choice !=5:
print(
'''
1. Add a new word
2. Shuffle the words in the list
3. Take the test
4. show all the words
5. Exit
'''
)
choice = Utils.get_int_input("Enter your menu choice: ")
if choice < 1 or choice > 5:
print("Error: not a valid menu choice")
elif choice != 5:
# print(self.menu_switcher(str(choice)))
# pass # invoke the corresponding method
self.menu_switcher(str(choice))()
else:
print("Closing the game...")
def menu_switcher(self, choice):
switch = {
"1": self.add_new_word,
"2": self.shuffle_words,
"3": self.take_the_test,
"4": self.show_all_words
}
return switch[choice]
def add_new_word(self):
swedish_word = Utils.get_string_input("Enter the swedish word: ")
english_word = Utils.get_string_input("Enter english word: ")
self.words.append(word(swedish_word, english_word))
print()
print("The new word has been added")
def show_all_words(self):
for word in self.words:
print(word.to_string())
def shuffle_words(self):
shuffle(self.words)
print("the words have been shuffeled")
def take_the_test(self):
points = 0
max_failures = 3
misses = 0
for word in self.words:
print()
answer = Utils.get_string_input(f"What is the translation for {word.get_english_word()}?")
if word.verify_answer(answer):
points += len(word.get_english_word())
print("CORRECT!")
else:
misses += 1
print(f"WronG! The Correct answer is {word.get_english_word()}.")
if misses = max_failures:
print()
print("GAME OVAH BIATCH, go practice nooooob")
print()
print(f"the test is ovah matey u focken focker fuuuuuuuuuuuuuuuuuuuck you got {points}")
|
4f55c17a043ee6a78b76220c8c25240a21b8195c | yamaz420/PythonIntro-LOLcodeAndShit | /pythonLOL/IfAndLoops.py | 1,881 | 4.15625 | 4 | #-----------!!!INDENTATION!!!-----------
# age = int(input("What is your age?"))
# if age >= 20:
# print("You are grown up, you can go to Systemet!")
# else:
# print("you are to young for systemet...")
# if age >= 20:
# if age >= 30:
# print("Allright, you can go to systemet for me, i hate showing ID")
# else:
# print("you can fo to systemet, just don't forget your ID...")
# else:
# print("you are too young for systemet")
### "or" = "||" "and" = "&&"
# if (day == "friday" or day == "Saturday") and age >= 18:
# print("is is a foot day to hit the club")
# elif day == "monday" or day == "tuseday":
# print("noooo, i hate these days")
# numbers = [1,2,3,45]
# if 45 in numbers:
# print("exists")
# else:
# print("no existo")
# truthy and falsy values also exist in python.
my_list = []
if my_list: # my_list.size() > 0 - in Java"
print(my_list)
else:
print("the list is empty")
i = 0 ## while-LOOP
while i < 10:
print (i, end = " ")
i += 1
# for-each-LOOP
names = ["hej", "niklas", "Erik"]
for name in names:
print(name, end = " ")
print(i, end = "\U0001F606") #Smiley ahahah #tackPelle
for i in range(10):
print(i, end = " ")
for i in range (1,20,2):
print (i, end= " ")
numbers = [1,24,12,52,26]
for i in range(len(numbers)):
print(numbers[i], end = " ")
persons = [ #list=arraylist of persons
{
"name": "Erik",
"age": 28
},
{
"name": "Martin",
"age": 34
},
{
"name": "Louise",
"age": 30
}
]
for person in persons:
print(person)
'''
multi-line-Commment
lalala
hahahahhahahahahahaHAH.
'''
just_names = [person["name"] for person in persons]
print(just_names)
over_30 = [person for person in persons if person["age"] >= 30] ##sortera persons-lista över 30
print(over_30)
|
f405ff7aa196a99aca98db4ad221cab524f36a28 | yamaz420/PythonIntro-LOLcodeAndShit | /pythonLOL/car.py | 836 | 3.703125 | 4 | from wheel import Wheel
import random
class Car:
nr_of_wheels = 4
def __init__(self, model, year):
self.model = model
self.year = year
self.wheels = []
self.install_wheels()
def install_wheels(self):
for i in range(self.nr_of_wheels):
condition = random.randint(40-100)
self.wheels.append(Wheel(condition)) #here we append an instande of the class wheel in every iteration
def to_string(self):
print(f"Car: {self.model} from the year {self.year}.")
def check_condition_of_wheels(self):
positions = ("From left", "From right", "rear left", "rear Right")
print("Condition of wheels: ")
for i in range(self.nr_of_wheels):
print(f"{positions[i]}: {self.wheels[i].condition}.)
|
e2847e6e40c6a7db988624957597c2f45108b4ba | EsslWeiss/Algs-and-DataStructures | /DataStructures/graph/bfs_graph_traverse.py | 773 | 3.875 | 4 | import ipdb
from collections import deque
# adj list matrix representation
GRAPH = {
0: {1, 2},
1: {0, 3, 4},
2: {0},
3: {1, 5},
4: {2, 3},
5: {10, 2, 6},
6: {10, 5, 7},
7: {0, 1, 3},
10: {0, 5, 6}
}
def bfs_traverse(graph, init_vertex):
ipdb.set_trace()
visited = [init_vertex]
queue = deque([init_vertex])
while queue:
curr_vertex = queue.popleft() # get vertex from left part
for neighbor_vertex in graph[curr_vertex]:
if neighbor_vertex not in visited:
visited.append(neighbor_vertex)
queue.append(neighbor_vertex)
return visited
if __name__ == "__main__":
visited_result = bfs_traverse(GRAPH, init_vertex=3)
print(visited_result)
|
9794994149b10a7f30ab5bc6b053d0479f1f2a2b | Baepeu/coding_training | /q14_01.py | 370 | 3.8125 | 4 | # 입력 : 구매금액, 주
# 출력 : 중간합계, 세금, 총 합계
amount = input("What is the order amount? ")
state = input("What is the state? ")
# 형변환
amount = float(amount)
tax = amount * 0.055
total = amount + tax
if state == 'WI':
print(f"The subtotal is ${amount:.2f}")
print(f"The tax is ${tax:.2f}")
print(f"The total is ${total:.2f}") |
3574b3fd265469ee1d9222831d97d839554bd1fa | Baepeu/coding_training | /q04_01.py | 319 | 4 | 4 | # 문자열 보간
# % 문법
# str.format() 메서드
# python 3.6 부터 등장한 f string
noun = input("Enter a noun: ")
verb = input("Enter a verb: ")
adjective = input("Enter an adjective: ")
adverb = input("Enter an adverb: ")
msg = f"Do you {verb} your {adjective} {noun} {adverb}? That's hilarious!"
print(msg) |
2dffe7f603412fad09fa52d71c9a9f533fe13e9f | Baepeu/coding_training | /q09_01.py | 453 | 3.5625 | 4 | from math import ceil
# round : 반올림, ceil : 올림, floor : 버림
# 입력 : 천장의 길이와 폭
# 출력 : 몇 리터가 필요한가?
# 입력
width = input("Width : ")
height = input("Height : ")
# 형변환
width = float(width)
height = float(height)
square_meters = width * height
# 올림
liters = ceil(square_meters / 9)
msg = f"You will need to purchase {liters} liters of paint to cover {square_meters} square meters"
print(msg) |
f6279772c0e492defaafef12e38a23afcc313661 | Baepeu/coding_training | /q08_01.py | 735 | 4.0625 | 4 | # 피자 파티
# 입력값 : 몇명, 몇판, 한판당 조각수
# 출력 : 한사람 당 몇조각씩 먹고 몇조각이 남느냐?
# 연산자 : //(몫), %(나머지)
# 데이터 입력
people = input("How many people? ")
pizzas = input("How many pizzas do you have? ")
print()
pieces = input("How many pieces are in a pizza? ")
# 형변환
people = int(people)
pizzas = int(pizzas)
pieces = int(pieces)
# 계산
total_pieces = pizzas * pieces
per_pieces = total_pieces // people
leftover = total_pieces % people
# 출력 구문 만들기
msg = f"{people} people with {pizzas} pizzas\n"
msg += f"Each person gets {per_pieces} pieces of pizza.\n"
msg += f"There are {leftover} leftover pieces."
# 최종 결과 출력
print(msg) |
c26b455b4b05b8be9d813d899dd9d461efba5af8 | Fingolfin123/ben_gislason_cse_exercise | /ben_gislason_cse_exercise/utilities/db_write.py | 1,076 | 3.515625 | 4 | import pandas as pd
import sqlite3
import os
from shutil import copyfile
from pathlib import Path
def dbWrite(dbPath, dbTable, df, optional_path):
'''
Writes dataframe to summary database file.
Parameters:
dbPath:
Path of summary database
this database is saved to local test directory
dbTable:
Name of resulting summary table
Returns:
df:
Dataframe representing selected table
'''
if not os.path.exists(optional_path):
os.mkdir(optional_path)
dbPath_out = optional_path + "/" + Path(dbPath).stem + "_summary.db"
#clean up old file if exists
if os.path.exists(dbPath_out):
print("summary file exists. removing and replacing")
os.remove(dbPath_out)
#Copies output file to desired path
copyfile(dbPath, dbPath_out)
try:
conn = sqlite3.connect(dbPath_out)
except Error as e:
print(e)
df.to_sql(dbTable, conn, if_exists='fail')
conn.close()
return dbPath_out
|
3c4ae6d7d146e231e636b75130ec3186bdece503 | nav272/100DaysofCode | /DAY3/pattern_16.py | 400 | 3.875 | 4 | print("------------Pattern 16---------")
txt = ""
i = 0
print(txt+"*")
txt = ""
j = 0
for i in range(3):
txt = txt+"*"
for k in range(i):
txt = txt+" "
txt = txt+"*"
print(txt)
j = 0
k = 0
txt = ""
for i in range(4):
txt = txt+"*"
for k in range(3-i):
txt = txt+" "
txt = txt+"*"
print(txt)
j = 0
k = 0
txt = ""
print(txt+"*")
|
a81662a267b8d8315298490f266244ce204957b5 | nav272/100DaysofCode | /DAY3/pattern_12.py | 375 | 3.90625 | 4 | print("------------Pattern 12---------")
txt = ""
i = 0
for j in range(5):
txt = txt+"*"
print(txt)
i = 0
for i in range(3):
j = 0
txt = ""
for l in range(i):
txt = txt+" "
txt = txt+"*"
for j in range(3-i):
txt = txt+" "
txt = txt+"*"
print(txt)
txt = ""
j = 0
txt = ""
for j in range(4):
txt = txt+" "
print(txt+"*")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.